content stringlengths 23 1.05M |
|---|
------------------------------------------------------------------------------
-- Copyright (c) 2017-2019, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Natools.Web.ACL.Sx_Backends provides an extremely simple ACL backend --
-- based on a S-expression file. --
------------------------------------------------------------------------------
private with Natools.Constant_Indefinite_Ordered_Maps;
private with Natools.References;
private with Natools.Storage_Pools;
package Natools.Web.ACL.Sx_Backends is
type Backend is new ACL.Backend with private;
overriding procedure Authenticate
(Self : in Backend;
Exchange : in out Exchanges.Exchange);
function Create
(Arguments : in out S_Expressions.Lockable.Descriptor'Class)
return ACL.Backend'Class;
type Hash_Function is access function
(Message : in S_Expressions.Atom)
return S_Expressions.Atom;
procedure Register
(Id : in Character;
Fn : in Hash_Function);
private
subtype Hash_Id is Character;
package Token_Maps is new Constant_Indefinite_Ordered_Maps
(S_Expressions.Atom, Containers.Identity,
S_Expressions.Less_Than, Containers."=");
type Hashed_Token_Array is array (Hash_Id range <>)
of Token_Maps.Constant_Map;
package Hashed_Token_Array_Refs is new References
(Hashed_Token_Array,
Storage_Pools.Access_In_Default_Pool'Storage_Pool,
Storage_Pools.Access_In_Default_Pool'Storage_Pool);
type Backend is new ACL.Backend with record
Map : Token_Maps.Constant_Map;
Hashed : Hashed_Token_Array_Refs.Immutable_Reference;
end record;
type Hash_Function_Array is array (Hash_Id range <>) of Hash_Function;
package Hash_Function_Array_Refs is new References
(Hash_Function_Array,
Storage_Pools.Access_In_Default_Pool'Storage_Pool,
Storage_Pools.Access_In_Default_Pool'Storage_Pool);
Hash_Function_DB : Hash_Function_Array_Refs.Reference;
end Natools.Web.ACL.Sx_Backends;
|
-- Score PIXAL le 07/10/2020 à 14:33 : 100%
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
procedure Robot_Type_1 is
-- Direction
type T_Direction is (NORD, EST, SUD, OUEST);
-- Robot type 1
type T_Robot_1 is record
Absc: Integer; -- Abscisse du robot
Ord: Integer; -- Ordonnée du robot
Orientation: T_Direction; -- Orientation du robot
end record;
-- Environnement:
MAX_X: constant Integer := 10;
MAX_Y: constant Integer := 10;
type T_Environnement is array (-MAX_X..MAX_X, -MAX_Y..MAX_Y) of Boolean;
--| Le programme principal |------------------------------------------------
R1: T_Robot_1; -- Robot 1
R2: T_Robot_1; -- Robot 2
E1: T_Environnement; -- L'Environnement
begin
-- Initialisation de R1 pour que son abscisse soit 4, son ordonnée 2 et sa direction ouest
R1 := (Absc => 4, Ord => 2, Orientation => OUEST);
-- Initialisation de R2 avec R1
R2 := R1;
-- Modification de l'abscisse de R1 pour qu'elle devienne 3
R1.Absc := 3;
-- Afficher l'abscisse de R1. La valeur affichée sera 3
Put ("Abscisse de R1 : ");
Put (R1.Absc, 1);
New_Line;
-- Afficher l'abscisse de R2. La valeur affichée sera 4
Put ("Abscisse de R2 : ");
Put (R2.Absc, 1);
New_Line;
-- Modifier l'environnement pour que la case de coordonnées (4,2) soit libre.
E1(4, 2) := True;
-- Afficher "OK" si le robot R1 est sur une case libre, "ERREUR" sinon
if E1(R1.Absc, R1.Ord) then
Put_Line ("OK");
else
Put_Line ("ERREUR");
end if;
--! Résponses aux questions:
-- 1: T_Direction est Enum (NORD, EST, SUD, OUEST)
-- T_Robot_1 est Enregistrement: X is Integer, Y is Integer, Direction is T_Direction.
--
-- 2: T_Environnement est Matrice (minX..maxX, minY..maxY) de type Boolean
--
-- 3: Obtenir son abscisse: x := robot.X
-- robot.Direction := NORD
-- environnement(robot.x, robot.y) (retourne un boolean)
--
-- 4: Les sous-programmes à ajouter: Tourner_Droite, Avancer.
end Robot_Type_1;
|
with Interfaces;
with Ada.Streams.Stream_IO;
with Ada.Unchecked_Deallocation;
use Interfaces;
use Ada.Streams.Stream_IO;
package Bitmap is
type PixelData is array (Integer range <>) of Unsigned_32;
type PixelDataRef is access PixelData;
procedure delete is new Ada.Unchecked_Deallocation(Object => PixelData, Name => PixelDataRef);
type Image is record
width : Integer;
height : Integer;
data : PixelDataRef;
end record;
procedure Init(im : out Image; w : Integer; h : Integer);
procedure Delete(im : in out Image);
procedure LoadBMP(im : in out Image; a_fileName : String);
procedure SaveBMP(im : Image; a_fileName : String);
private
subtype WORD is Unsigned_16;
subtype DWORD is Unsigned_32;
type Pixel is record
r,g,b : Unsigned_8;
end record;
type BITBAPFILEHEADER is record
bfType : WORD;
bfSize : DWORD;
bfReserved1 : WORD;
bfReserved2 : WORD;
bfOffBits : DWORD;
end record;
type BITMAPINFOHEADER is record
biSize : DWORD;
biWidth : DWORD;
biHeight : DWORD;
biPlanes : WORD;
biBitCount : WORD;
biCompression : DWORD;
biSizeImage : DWORD;
biXPelsPerMeter : DWORD;
biYPelsPerMeter : DWORD;
biClrUsed : DWORD;
biClrImportant : DWORD;
end record;
end Bitmap;
|
-- AoC 2020, Day 15
with Ada.Text_IO;
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Containers; use Ada.Containers;
package body Day is
package TIO renames Ada.Text_IO;
function natural_hash(n : in Natural) return Hash_Type is
begin
return Hash_Type(n);
end natural_hash;
package Natural_Hashed_Maps is new Ada.Containers.Indefinite_Hashed_Maps
(Key_Type => Natural,
Element_Type => Natural,
Hash => Natural_Hash,
Equivalent_Keys => "=");
use Natural_Hashed_Maps;
last_age : Natural_Hashed_Maps.Map := Empty_Map;
previous_age : Natural_Hashed_Maps.Map := Empty_Map;
function sequence(s : in Input_Array; step : in Natural) return Natural is
index : Natural := 1;
last : Natural;
prev : Natural;
diff : Natural;
begin
clear(last_age);
clear(previous_age);
for e of s loop
last_age.insert(e, index);
last := e;
index := index + 1;
end loop;
loop
if not previous_age.contains(last) then
diff := 0;
else
prev := previous_age(last);
last := last_age(last);
diff := last - prev;
end if;
if last_age.contains(diff) then
previous_age.include(diff, last_age(diff));
end if;
last_age.include(diff, index);
last := diff;
if index = step then
return last;
end if;
if index mod 100_000 = 0 then
TIO.put_line(Natural'Image(index));
end if;
index := index + 1;
end loop;
end sequence;
end Day;
|
-- part of AdaYaml, (c) 2017 Felix Krause
-- released under the terms of the MIT license, see the file "copying.txt"
with Ada.Finalization;
with Text;
with Lexer;
package Yaml is
-- occurs when the lexical analysis of a YAML character streams discovers
-- ill-formed input.
Lexer_Error : exception renames Lexer.Lexer_Error;
-- occurs when the syntactic analysis of a YAML token stream discovers an
-- ill-formed input.
Parser_Error : exception;
-- occurs when a DOM cannot be composed from a given event stream.
Composer_Error : exception;
-- occurs when an ill-formed event stream is tried to be presented.
Presenter_Error : exception;
-- occurs when data cannot be written to a destination.
Destination_Error : exception;
-- occurs when an event stream contains an invalid sequence of events.
Stream_Error : exception;
-- occurs when annotation processing encounters an invalid usage of an
-- annotation.
Annotation_Error : exception;
-- the version of the library. major and minor version correspond to the
-- YAML version, the patch version is local to this implementation.
function Version_Major return Natural with Inline;
function Version_Minor return Natural with Inline;
function Version_Patch return Natural with Inline;
-- all positions in a mark start at 1
subtype Mark_Position is Positive;
-- a position in the input stream.
type Mark is record
Index, Line, Column : Mark_Position;
end record;
type Event_Kind is (Stream_Start, Stream_End, Document_Start, Document_End,
Alias, Scalar, Sequence_Start, Sequence_End,
Mapping_Start, Mapping_End, Annotation_Start,
Annotation_End);
type Collection_Style_Type is (Any, Block, Flow) with
Convention => C;
type Scalar_Style_Type is
(Any, Plain, Single_Quoted, Double_Quoted, Literal, Folded) with
Convention => C;
subtype Flow_Scalar_Style_Type is Scalar_Style_Type range Literal .. Folded;
type Properties is record
Anchor, Tag : Text.Reference;
end record;
function Default_Properties return Properties;
function Is_Empty (Props : Properties) return Boolean with Inline;
type Event (Kind : Event_Kind := Stream_End) is record
-- Start_Position is first character, End_Position is after last
-- character. this is necessary for zero-length events.
Start_Position, End_Position : Mark;
case Kind is
when Document_Start =>
Version : Text.Reference;
Implicit_Start : Boolean := True;
when Document_End =>
Implicit_End : Boolean;
when Mapping_Start | Sequence_Start =>
Collection_Style : Collection_Style_Type := Any;
Collection_Properties : Properties;
when Annotation_Start =>
Annotation_Properties : Properties;
Namespace : Text.Reference;
Name : Text.Reference;
when Scalar =>
Scalar_Properties : Properties;
Content : Text.Reference;
Scalar_Style : Scalar_Style_Type := Any;
when Alias =>
Target : Text.Reference;
when Mapping_End | Sequence_End | Annotation_End | Stream_Start |
Stream_End => null;
end case;
end record;
function To_String (E : Event) return String;
Standard_Annotation_Namespace : constant Text.Reference;
-- base type for refcounted types (mainly event streams). all streams and
-- some other objects can be used with reference-counting smart pointers, so
-- this base type implements the reference counting. note that this type
-- does not have any stream semantic; that is to be implemented by child
-- types by providing a Stream_Concept instance (if they are streams).
--
-- beware that this type is only the vessel for the reference count and does
-- not do any reference counting itself; the reference-counting management
-- functions must be called from a smart pointer type. An object of a child
-- type can be used on the stack, in which case the reference count is not
-- used and instead the object just goes out of scope.
type Refcount_Base is abstract limited new
Ada.Finalization.Limited_Controlled with private;
-- increases reference count. only call this explicitly when implementing
-- a reference-counting smart pointer.
procedure Increase_Refcount (Object : not null access Refcount_Base'Class);
-- decreases reference count. only call this explicitly when implementing a
-- reference-counting smart pointer. this procedure will free the object
-- when the reference count hits zero, rendering the provided pointer
-- useless and dangerous to use afterwards!
procedure Decrease_Refcount (Object : not null access Refcount_Base'Class);
private
Standard_Annotation_Namespace_Holder : constant Text.Constant_Instance :=
Text.Hold ("@@");
Standard_Annotation_Namespace : constant Text.Reference := Text.Held
(Standard_Annotation_Namespace_Holder);
type Refcount_Base is abstract limited new
Ada.Finalization.Limited_Controlled with record
Refcount : Natural := 1;
end record;
end Yaml;
|
-----------------------------------------------------------------------
-- asf.servlets.files -- Static file servlet
-- Copyright (C) 2010, 2011, 2013 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Files;
with Util.Strings;
with Util.Streams;
with Util.Streams.Files;
with Ada.Streams;
with Ada.Streams.Stream_IO;
with Ada.Directories;
with ASF.Streams;
with ASF.Applications;
package body ASF.Servlets.Files is
use Ada.Streams;
use Ada.Streams.Stream_IO;
use Ada.Directories;
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
procedure Initialize (Server : in out File_Servlet;
Context : in Servlet_Registry'Class) is
Dir : constant String := Context.Get_Init_Parameter (ASF.Applications.VIEW_DIR);
Def_Type : constant String := Context.Get_Init_Parameter ("content-type.default");
begin
Server.Dir := new String '(Dir);
Server.Default_Content_Type := new String '(Def_Type);
end Initialize;
-- ------------------------------
-- Returns the time the Request object was last modified, in milliseconds since
-- midnight January 1, 1970 GMT. If the time is unknown, this method returns
-- a negative number (the default).
--
-- Servlets that support HTTP GET requests and can quickly determine their
-- last modification time should override this method. This makes browser and
-- proxy caches work more effectively, reducing the load on server and network
-- resources.
-- ------------------------------
function Get_Last_Modified (Server : in File_Servlet;
Request : in Requests.Request'Class)
return Ada.Calendar.Time is
pragma Unreferenced (Server, Request);
begin
return Ada.Calendar.Clock;
end Get_Last_Modified;
-- ------------------------------
-- Set the content type associated with the given file
-- ------------------------------
procedure Set_Content_Type (Server : in File_Servlet;
Path : in String;
Response : in out Responses.Response'Class) is
Pos : constant Natural := Util.Strings.Rindex (Path, '.');
begin
if Pos = 0 then
Response.Set_Content_Type (Server.Default_Content_Type.all);
return;
end if;
if Path (Pos .. Path'Last) = ".css" then
Response.Set_Content_Type ("text/css");
return;
end if;
if Path (Pos .. Path'Last) = ".js" then
Response.Set_Content_Type ("text/javascript");
return;
end if;
if Path (Pos .. Path'Last) = ".html" then
Response.Set_Content_Type ("text/html");
return;
end if;
if Path (Pos .. Path'Last) = ".txt" then
Response.Set_Content_Type ("text/plain");
return;
end if;
if Path (Pos .. Path'Last) = ".png" then
Response.Set_Content_Type ("image/png");
return;
end if;
if Path (Pos .. Path'Last) = ".jpg" then
Response.Set_Content_Type ("image/jpg");
return;
end if;
end Set_Content_Type;
-- ------------------------------
-- Called by the server (via the service method) to allow a servlet to handle
-- a GET request.
--
-- Overriding this method to support a GET request also automatically supports
-- an HTTP HEAD request. A HEAD request is a GET request that returns no body
-- in the response, only the request header fields.
--
-- When overriding this method, read the request data, write the response headers,
-- get the response's writer or output stream object, and finally, write the
-- response data. It's best to include content type and encoding.
-- When using a PrintWriter object to return the response, set the content type
-- before accessing the PrintWriter object.
--
-- The servlet container must write the headers before committing the response,
-- because in HTTP the headers must be sent before the response body.
--
-- Where possible, set the Content-Length header (with the
-- Response.Set_Content_Length method), to allow the servlet container
-- to use a persistent connection to return its response to the client,
-- improving performance. The content length is automatically set if the entire
-- response fits inside the response buffer.
--
-- When using HTTP 1.1 chunked encoding (which means that the response has a
-- Transfer-Encoding header), do not set the Content-Length header.
--
-- The GET method should be safe, that is, without any side effects for which
-- users are held responsible. For example, most form queries have no side effects.
-- If a client request is intended to change stored data, the request should use
-- some other HTTP method.
--
-- The GET method should also be idempotent, meaning that it can be safely repeated.
-- Sometimes making a method safe also makes it idempotent. For example, repeating
-- queries is both safe and idempotent, but buying a product online or modifying
-- data is neither safe nor idempotent.
--
-- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request"
-- ------------------------------
procedure Do_Get (Server : in File_Servlet;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
use Util.Files;
URI : constant String := Request.Get_Path_Info;
Path : constant String := Find_File_Path (Name => URI, Paths => Server.Dir.all);
begin
if not Ada.Directories.Exists (Path)
or else Ada.Directories.Kind (Path) /= Ada.Directories.Ordinary_File then
Response.Send_Error (Responses.SC_NOT_FOUND);
return;
end if;
File_Servlet'Class (Server).Set_Content_Type (Path, Response);
declare
Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream;
Input : Util.Streams.Files.File_Stream;
begin
Input.Open (Name => Path, Mode => In_File);
Util.Streams.Copy (From => Input, Into => Output);
end;
end Do_Get;
end ASF.Servlets.Files;
|
package PW is
task type Semaphore is
entry Initialize(N : in Natural);
entry Wait;
entry Signal;
entry Try(Success : out Boolean);
end Semaphore;
type SemaphoreAccess is access Semaphore;
task PlaceSemaphore is
entry Wait;
entry Signal;
end PlaceSemaphore;
task PrinterSemaphore is
entry Wait;
entry Signal;
end PrinterSemaphore;
type Car is
record
Number : Integer;
ToDistributor : Integer;
InDistributor : Integer;
GoToExit : Boolean;
end record;
task type CarAction is
entry Construct(Cr : Car);
end CarAction;
type CarActionAccess is access CarAction;
function CarConstructor(Number : Integer; ca : CarActionAccess) return Car;
type Distributor is tagged
record
S : SemaphoreAccess;
end record;
procedure Initialize(D : in out Distributor);
type DistributorCollectionArray is array(1..3) of Distributor;
type DistributorCollection is tagged
record
DC : DistributorCollectionArray;
end record;
procedure Initialize(DC : in out DistributorCollection);
function FindEmptyDistributor(DC : in DistributorCollection) return Integer;
type QueueArray is array(1..3) of Car;
type EntryQueue is
record
Queue : QueueArray;
FirstIndex, LastIndex : Integer := 0;
end record;
procedure Put(q : in out EntryQueue; c : in Car);
procedure Pop(q : in out EntryQueue; c : out Car);
procedure GetFirst(q : in out EntryQueue; c : out Car);
function Size(q : EntryQueue) return Integer;
task SpawnCar;
task Data is
entry SendDC(DC : in DistributorCollection);
entry GetDC(DC : out DistributorCollection);
entry SendQueue(Q : in EntryQueue);
entry GetQueue(Q : out EntryQueue);
end Data;
end PW;
|
package body String_Int is
Zero_Pos: constant Natural := Digit'Pos(Digit'First);
procedure Add(A, B: in Digit; Sum: out Digit; Carry: in out Digit) is
S: Natural := Digit'Pos(A) + Digit'Pos(B) + Digit'Pos(Carry);
begin
S := S - 3 * Zero_Pos;
Sum := Digit'Val((S mod 10) + Zero_Pos);
Carry := Digit'Val(S / 10 + Zero_Pos);
end Add;
function "+"(A, B: Number) return Number is
Result: Number(1 .. 1 + Index'Max(A'Length, B'Length));
Carry: Digit := '0';
AI: Integer := A'Last;
BI: Integer := B'Last;
begin
for Dst in reverse Result'Range loop
Add(
A => (if AI < A'First then '0' else A(AI)),
B => (if BI < B'First then '0' else B(BI)),
Sum => Result(Dst),
Carry => Carry);
AI := Integer'Pred(AI);
BI := Integer'Pred(BI);
end loop;
for I in Result'Range loop
if Result(I) /= '0' then
return Result(I .. Result'Last);
end if;
end loop;
return Result;
end "+";
function From_String(S: String) return Number is
Result: Number(S'Range);
begin
for I in S'Range loop Result(I) := Digit(S(I)); end loop;
return Result;
end From_String;
function To_String(N: Number) return String is
Result: String(N'Range);
begin
for I in N'Range loop Result(I) := Character(N(I)); end loop;
return Result;
end To_String;
end String_Int;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- A D A . W I D E _ T E X T _ I O . E D I T I N G --
-- --
-- S p e c --
-- --
-- Copyright (C) 1992-2009, 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. --
-- --
------------------------------------------------------------------------------
package Ada.Wide_Text_IO.Editing is
type Picture is private;
function Valid
(Pic_String : String;
Blank_When_Zero : Boolean := False) return Boolean;
function To_Picture
(Pic_String : String;
Blank_When_Zero : Boolean := False) return Picture;
function Pic_String (Pic : Picture) return String;
function Blank_When_Zero (Pic : Picture) return Boolean;
Max_Picture_Length : constant := 64;
Picture_Error : exception;
Default_Currency : constant Wide_String := "$";
Default_Fill : constant Wide_Character := ' ';
Default_Separator : constant Wide_Character := ',';
Default_Radix_Mark : constant Wide_Character := '.';
generic
type Num is delta <> digits <>;
Default_Currency : Wide_String :=
Wide_Text_IO.Editing.Default_Currency;
Default_Fill : Wide_Character :=
Wide_Text_IO.Editing.Default_Fill;
Default_Separator : Wide_Character :=
Wide_Text_IO.Editing.Default_Separator;
Default_Radix_Mark : Wide_Character :=
Wide_Text_IO.Editing.Default_Radix_Mark;
package Decimal_Output is
function Length
(Pic : Picture;
Currency : Wide_String := Default_Currency) return Natural;
function Valid
(Item : Num;
Pic : Picture;
Currency : Wide_String := Default_Currency) return Boolean;
function Image
(Item : Num;
Pic : Picture;
Currency : Wide_String := Default_Currency;
Fill : Wide_Character := Default_Fill;
Separator : Wide_Character := Default_Separator;
Radix_Mark : Wide_Character := Default_Radix_Mark) return Wide_String;
procedure Put
(File : File_Type;
Item : Num;
Pic : Picture;
Currency : Wide_String := Default_Currency;
Fill : Wide_Character := Default_Fill;
Separator : Wide_Character := Default_Separator;
Radix_Mark : Wide_Character := Default_Radix_Mark);
procedure Put
(Item : Num;
Pic : Picture;
Currency : Wide_String := Default_Currency;
Fill : Wide_Character := Default_Fill;
Separator : Wide_Character := Default_Separator;
Radix_Mark : Wide_Character := Default_Radix_Mark);
procedure Put
(To : out Wide_String;
Item : Num;
Pic : Picture;
Currency : Wide_String := Default_Currency;
Fill : Wide_Character := Default_Fill;
Separator : Wide_Character := Default_Separator;
Radix_Mark : Wide_Character := Default_Radix_Mark);
end Decimal_Output;
private
MAX_PICSIZE : constant := 50;
MAX_MONEYSIZE : constant := 10;
Invalid_Position : constant := -1;
subtype Pic_Index is Natural range 0 .. MAX_PICSIZE;
type Picture_Record (Length : Pic_Index := 0) is record
Expanded : String (1 .. Length);
end record;
type Format_Record is record
Picture : Picture_Record;
-- Read only
Blank_When_Zero : Boolean;
-- Read/write
Original_BWZ : Boolean;
-- The following components get written
Star_Fill : Boolean := False;
Radix_Position : Integer := Invalid_Position;
Sign_Position,
Second_Sign : Integer := Invalid_Position;
Start_Float,
End_Float : Integer := Invalid_Position;
Start_Currency,
End_Currency : Integer := Invalid_Position;
Max_Leading_Digits : Integer := 0;
Max_Trailing_Digits : Integer := 0;
Max_Currency_Digits : Integer := 0;
Floater : Wide_Character := '!';
-- Initialized to illegal value
end record;
type Picture is record
Contents : Format_Record;
end record;
type Number_Attributes is record
Negative : Boolean := False;
Has_Fraction : Boolean := False;
Start_Of_Int,
End_Of_Int,
Start_Of_Fraction,
End_Of_Fraction : Integer := Invalid_Position; -- invalid value
end record;
function Parse_Number_String (Str : String) return Number_Attributes;
-- Assumed format is 'IMAGE or Fixed_IO.Put format (depends on no
-- trailing blanks...)
procedure Precalculate (Pic : in out Format_Record);
-- Precalculates fields from the user supplied data
function Format_Number
(Pic : Format_Record;
Number : String;
Currency_Symbol : Wide_String;
Fill_Character : Wide_Character;
Separator_Character : Wide_Character;
Radix_Point : Wide_Character) return Wide_String;
-- Formats number according to Pic
function Expand (Picture : String) return String;
end Ada.Wide_Text_IO.Editing;
|
with interfaces.c.strings;
package agar.gui.unit is
package cs renames interfaces.c.strings;
type unit_t is record
key : cs.chars_ptr;
abbr : cs.chars_ptr;
name : cs.chars_ptr;
divider : c.double;
func : access function (x : c.double; y : c.int) return c.double;
end record;
type unit_access_t is access all unit_t;
type unit_const_access_t is access constant unit_t;
pragma convention (c, unit_t);
pragma convention (c, unit_access_t);
pragma convention (c, unit_const_access_t);
function find (key : string) return unit_const_access_t;
pragma inline (find);
function best
(unit_group : unit_const_access_t;
n : long_float) return unit_const_access_t;
pragma inline (best);
-- missing: AG_UnitFormat - docs/header type mismatch
function abbreviation (unit : unit_const_access_t) return cs.chars_ptr;
pragma import (c, abbreviation, "agar_unitabbr");
function abbreviation (unit : unit_const_access_t) return string;
pragma inline (abbreviation);
function unit_to_base
(n : long_float;
unit_group : unit_const_access_t) return long_float;
pragma inline (unit_to_base);
function base_to_unit
(n : long_float;
unit_group : unit_const_access_t) return long_float;
pragma inline (base_to_unit);
function unit_to_unit
(n : long_float;
unit_from : unit_const_access_t;
unit_to : unit_const_access_t) return long_float;
pragma inline (unit_to_unit);
end agar.gui.unit;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- S T R I N G T --
-- --
-- B o d y --
-- --
-- Copyright (C) 1992-2009, 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 Alloc;
with Namet; use Namet;
with Output; use Output;
with Table;
package body Stringt is
-- The following table stores the sequence of character codes for the
-- stored string constants. The entries are referenced from the
-- separate Strings table.
package String_Chars is new Table.Table (
Table_Component_Type => Char_Code,
Table_Index_Type => Int,
Table_Low_Bound => 0,
Table_Initial => Alloc.String_Chars_Initial,
Table_Increment => Alloc.String_Chars_Increment,
Table_Name => "String_Chars");
-- The String_Id values reference entries in the Strings table, which
-- contains String_Entry records that record the length of each stored
-- string and its starting location in the String_Chars table.
type String_Entry is record
String_Index : Int;
Length : Nat;
end record;
package Strings is new Table.Table (
Table_Component_Type => String_Entry,
Table_Index_Type => String_Id'Base,
Table_Low_Bound => First_String_Id,
Table_Initial => Alloc.Strings_Initial,
Table_Increment => Alloc.Strings_Increment,
Table_Name => "Strings");
-- Note: it is possible that two entries in the Strings table can share
-- string data in the String_Chars table, and in particular this happens
-- when Start_String is called with a parameter that is the last string
-- currently allocated in the table.
-------------------------------
-- Add_String_To_Name_Buffer --
-------------------------------
procedure Add_String_To_Name_Buffer (S : String_Id) is
Len : constant Natural := Natural (String_Length (S));
begin
for J in 1 .. Len loop
Name_Buffer (Name_Len + J) :=
Get_Character (Get_String_Char (S, Int (J)));
end loop;
Name_Len := Name_Len + Len;
end Add_String_To_Name_Buffer;
----------------
-- End_String --
----------------
function End_String return String_Id is
begin
return Strings.Last;
end End_String;
---------------------
-- Get_String_Char --
---------------------
function Get_String_Char (Id : String_Id; Index : Int) return Char_Code is
begin
pragma Assert (Id in First_String_Id .. Strings.Last
and then Index in 1 .. Strings.Table (Id).Length);
return String_Chars.Table (Strings.Table (Id).String_Index + Index - 1);
end Get_String_Char;
----------------
-- Initialize --
----------------
procedure Initialize is
begin
String_Chars.Init;
Strings.Init;
end Initialize;
----------
-- Lock --
----------
procedure Lock is
begin
String_Chars.Locked := True;
Strings.Locked := True;
String_Chars.Release;
Strings.Release;
end Lock;
------------------
-- Start_String --
------------------
-- Version to start completely new string
procedure Start_String is
begin
Strings.Append ((String_Index => String_Chars.Last + 1, Length => 0));
end Start_String;
-- Version to start from initially stored string
procedure Start_String (S : String_Id) is
begin
Strings.Increment_Last;
-- Case of initial string value is at the end of the string characters
-- table, so it does not need copying, instead it can be shared.
if Strings.Table (S).String_Index + Strings.Table (S).Length =
String_Chars.Last + 1
then
Strings.Table (Strings.Last).String_Index :=
Strings.Table (S).String_Index;
-- Case of initial string value must be copied to new string
else
Strings.Table (Strings.Last).String_Index :=
String_Chars.Last + 1;
for J in 1 .. Strings.Table (S).Length loop
String_Chars.Append
(String_Chars.Table (Strings.Table (S).String_Index + (J - 1)));
end loop;
end if;
-- In either case the result string length is copied from the argument
Strings.Table (Strings.Last).Length := Strings.Table (S).Length;
end Start_String;
-----------------------
-- Store_String_Char --
-----------------------
procedure Store_String_Char (C : Char_Code) is
begin
String_Chars.Append (C);
Strings.Table (Strings.Last).Length :=
Strings.Table (Strings.Last).Length + 1;
end Store_String_Char;
procedure Store_String_Char (C : Character) is
begin
Store_String_Char (Get_Char_Code (C));
end Store_String_Char;
------------------------
-- Store_String_Chars --
------------------------
procedure Store_String_Chars (S : String) is
begin
for J in S'First .. S'Last loop
Store_String_Char (Get_Char_Code (S (J)));
end loop;
end Store_String_Chars;
procedure Store_String_Chars (S : String_Id) is
-- We are essentially doing this:
-- for J in 1 .. String_Length (S) loop
-- Store_String_Char (Get_String_Char (S, J));
-- end loop;
-- but when the string is long it's more efficient to grow the
-- String_Chars table all at once.
S_First : constant Int := Strings.Table (S).String_Index;
S_Len : constant Int := String_Length (S);
Old_Last : constant Int := String_Chars.Last;
New_Last : constant Int := Old_Last + S_Len;
begin
String_Chars.Set_Last (New_Last);
String_Chars.Table (Old_Last + 1 .. New_Last) :=
String_Chars.Table (S_First .. S_First + S_Len - 1);
Strings.Table (Strings.Last).Length :=
Strings.Table (Strings.Last).Length + S_Len;
end Store_String_Chars;
----------------------
-- Store_String_Int --
----------------------
procedure Store_String_Int (N : Int) is
begin
if N < 0 then
Store_String_Char ('-');
Store_String_Int (-N);
else
if N > 9 then
Store_String_Int (N / 10);
end if;
Store_String_Char (Character'Val (Character'Pos ('0') + N mod 10));
end if;
end Store_String_Int;
--------------------------
-- String_Chars_Address --
--------------------------
function String_Chars_Address return System.Address is
begin
return String_Chars.Table (0)'Address;
end String_Chars_Address;
------------------
-- String_Equal --
------------------
function String_Equal (L, R : String_Id) return Boolean is
Len : constant Nat := Strings.Table (L).Length;
begin
if Len /= Strings.Table (R).Length then
return False;
else
for J in 1 .. Len loop
if Get_String_Char (L, J) /= Get_String_Char (R, J) then
return False;
end if;
end loop;
return True;
end if;
end String_Equal;
-----------------------------
-- String_From_Name_Buffer --
-----------------------------
function String_From_Name_Buffer return String_Id is
begin
Start_String;
for J in 1 .. Name_Len loop
Store_String_Char (Get_Char_Code (Name_Buffer (J)));
end loop;
return End_String;
end String_From_Name_Buffer;
-------------------
-- String_Length --
-------------------
function String_Length (Id : String_Id) return Nat is
begin
return Strings.Table (Id).Length;
end String_Length;
---------------------------
-- String_To_Name_Buffer --
---------------------------
procedure String_To_Name_Buffer (S : String_Id) is
begin
Name_Len := Natural (String_Length (S));
for J in 1 .. Name_Len loop
Name_Buffer (J) :=
Get_Character (Get_String_Char (S, Int (J)));
end loop;
end String_To_Name_Buffer;
---------------------
-- Strings_Address --
---------------------
function Strings_Address return System.Address is
begin
return Strings.Table (First_String_Id)'Address;
end Strings_Address;
---------------
-- Tree_Read --
---------------
procedure Tree_Read is
begin
String_Chars.Tree_Read;
Strings.Tree_Read;
end Tree_Read;
----------------
-- Tree_Write --
----------------
procedure Tree_Write is
begin
String_Chars.Tree_Write;
Strings.Tree_Write;
end Tree_Write;
------------
-- Unlock --
------------
procedure Unlock is
begin
String_Chars.Locked := False;
Strings.Locked := False;
end Unlock;
-------------------------
-- Unstore_String_Char --
-------------------------
procedure Unstore_String_Char is
begin
String_Chars.Decrement_Last;
Strings.Table (Strings.Last).Length :=
Strings.Table (Strings.Last).Length - 1;
end Unstore_String_Char;
---------------------
-- Write_Char_Code --
---------------------
procedure Write_Char_Code (Code : Char_Code) is
procedure Write_Hex_Byte (J : Char_Code);
-- Write single hex byte (value in range 0 .. 255) as two digits
--------------------
-- Write_Hex_Byte --
--------------------
procedure Write_Hex_Byte (J : Char_Code) is
Hexd : constant array (Char_Code range 0 .. 15) of Character :=
"0123456789abcdef";
begin
Write_Char (Hexd (J / 16));
Write_Char (Hexd (J mod 16));
end Write_Hex_Byte;
-- Start of processing for Write_Char_Code
begin
if Code in 16#20# .. 16#7E# then
Write_Char (Character'Val (Code));
else
Write_Char ('[');
Write_Char ('"');
if Code > 16#FF_FFFF# then
Write_Hex_Byte (Code / 2 ** 24);
end if;
if Code > 16#FFFF# then
Write_Hex_Byte ((Code / 2 ** 16) mod 256);
end if;
if Code > 16#FF# then
Write_Hex_Byte ((Code / 256) mod 256);
end if;
Write_Hex_Byte (Code mod 256);
Write_Char ('"');
Write_Char (']');
end if;
end Write_Char_Code;
------------------------------
-- Write_String_Table_Entry --
------------------------------
procedure Write_String_Table_Entry (Id : String_Id) is
C : Char_Code;
begin
if Id = No_String then
Write_Str ("no string");
else
Write_Char ('"');
for J in 1 .. String_Length (Id) loop
C := Get_String_Char (Id, J);
if C = Character'Pos ('"') then
Write_Str ("""""");
else
Write_Char_Code (C);
end if;
-- If string is very long, quit
if J >= 1000 then -- arbitrary limit
Write_Str ("""...etc (length = ");
Write_Int (String_Length (Id));
Write_Str (")");
return;
end if;
end loop;
Write_Char ('"');
end if;
end Write_String_Table_Entry;
end Stringt;
|
separate (SPARKNaCl)
procedure Sanitize_Boolean (R : out Boolean) is
begin
R := False; -- Boolean'Pos (0)
-- It seems an inspection point is not possible on R here, since
-- it is passed by copy in a register
-- pragma Inspection_Point (R); -- See RM H3.2 (9)
-- Add target-dependent code here to
-- 1. flush and invalidate data cache,
-- 2. wait until writes have committed (e.g. a memory-fence instruction)
-- 3. whatever else is required.
end Sanitize_Boolean;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2018 onox <denkpadje@gmail.com>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
package body Orka.Containers.Bounded_Vectors is
function Length (Container : Vector) return Length_Type is
(Container.Length);
function Is_Empty (Container : Vector) return Boolean is
(Length (Container) = 0);
function Is_Full (Container : Vector) return Boolean is
(Length (Container) = Container.Capacity);
procedure Append (Container : in out Vector; Elements : Vector) is
Start_Index : constant Index_Type := Container.Length + Index_Type'First;
Stop_Index : constant Index_Type'Base := Start_Index + Elements.Length - 1;
procedure Copy_Elements (Elements : Element_Array) is
begin
Container.Elements (Start_Index .. Stop_Index) := Elements;
end Copy_Elements;
begin
Elements.Query (Copy_Elements'Access);
Container.Length := Container.Length + Elements.Length;
end Append;
procedure Append (Container : in out Vector; Element : Element_Type) is
Index : constant Index_Type := Container.Length + Index_Type'First;
begin
Container.Length := Container.Length + 1;
Container.Elements (Index) := Element;
end Append;
procedure Remove_Last (Container : in out Vector; Element : out Element_Type) is
Index : constant Index_Type := Container.Length + Index_Type'First - 1;
begin
Element := Container.Elements (Index);
Container.Elements (Index .. Index) := (others => <>);
Container.Length := Container.Length - 1;
end Remove_Last;
procedure Clear (Container : in out Vector) is
begin
Container.Elements := (others => <>);
Container.Length := 0;
end Clear;
procedure Query
(Container : Vector;
Process : not null access procedure (Elements : Element_Array))
is
Last_Index : constant Index_Type'Base := Container.Length + Index_Type'First - 1;
begin
Process (Container.Elements (Index_Type'First .. Last_Index));
end Query;
procedure Update
(Container : in out Vector;
Index : Index_Type;
Process : not null access procedure (Element : in out Element_Type)) is
begin
Process (Container.Elements (Index));
end Update;
function Element (Container : Vector; Index : Index_Type) return Element_Type is
(Container.Elements (Index));
function Element (Container : aliased Vector; Position : Cursor) return Element_Type is
begin
if Position = No_Element then
raise Constraint_Error;
elsif Position.Object.all /= Container then
raise Program_Error;
else
return Element (Container, Position.Index);
end if;
end Element;
function Constant_Reference
(Container : aliased Vector;
Index : Index_Type) return Constant_Reference_Type is
begin
return Constant_Reference_Type'(Value => Container.Elements (Index)'Access);
end Constant_Reference;
function Constant_Reference
(Container : aliased Vector;
Position : Cursor) return Constant_Reference_Type is
begin
if Position = No_Element then
raise Constraint_Error;
elsif Position.Object.all /= Container then
raise Program_Error;
else
return Constant_Reference (Container, Position.Index);
end if;
end Constant_Reference;
function Reference
(Container : aliased in out Vector;
Index : Index_Type) return Reference_Type is
begin
return Reference_Type'(Value => Container.Elements (Index)'Access);
end Reference;
function Reference
(Container : aliased in out Vector;
Position : Cursor) return Reference_Type is
begin
if Position = No_Element then
raise Constraint_Error;
elsif Position.Object.all /= Container then
raise Program_Error;
else
return Reference (Container, Position.Index);
end if;
end Reference;
function Iterate (Container : Vector)
return Vector_Iterator_Interfaces.Reversible_Iterator'Class is
begin
return Iterator'(Container => Container'Unchecked_Access);
end Iterate;
overriding function First (Object : Iterator) return Cursor is
begin
if Object.Container.all.Is_Empty then
return No_Element;
else
return Cursor'(Object => Object.Container, Index => Index_Type'First);
end if;
end First;
overriding function Last (Object : Iterator) return Cursor is
begin
if Object.Container.all.Is_Empty then
return No_Element;
else
return Cursor'(Object => Object.Container,
Index => Object.Container.all.Length);
end if;
end Last;
overriding function Next
(Object : Iterator;
Position : Cursor) return Cursor is
begin
if Position = No_Element then
raise Constraint_Error;
elsif Position.Index = Position.Object.Length + Index_Type'First - 1 then
return No_Element;
else
return Cursor'(Position.Object, Position.Index + 1);
end if;
end Next;
overriding function Previous
(Object : Iterator;
Position : Cursor) return Cursor is
begin
if Position = No_Element then
raise Constraint_Error;
elsif Position.Index = Index_Type'First then
return No_Element;
else
return Cursor'(Position.Object, Position.Index - 1);
end if;
end Previous;
end Orka.Containers.Bounded_Vectors;
|
package Trains with
SPARK_Mode
is
-- the railroad is composed of a set of one-way tracks, where each track
-- joins two locations. A track has a length that is a multiple of an
-- elementary distance.
Num_Locations : constant := 39;
type Location is new Positive range 1 .. Num_Locations;
type Track is record
From : Location;
To : Location;
Length : Positive;
end record;
Num_Tracks : constant := 51;
type Track_Opt_Id is new Natural range 0 .. Num_Tracks;
subtype Track_Id is Track_Opt_Id range 1 .. Num_Tracks;
No_Track_Id : constant Track_Opt_Id := 0;
-- example railroad going around between locations 1 to 5, with additional
-- tracks from 1 to 3, 2 to 5 and 3 to 5.
Tracks : array (Track_Id) of Track := (others => (1, 1, 1));
-- the map of previous tracks records for each location the tracks that
-- precede it. This information should be consistent with the one in
-- Tracks.
Max_Num_Previous_Tracks : constant := 3;
type Prev_Id is range 1 .. Max_Num_Previous_Tracks;
type Track_Ids is array (Prev_Id) of Track_Opt_Id;
Previous_Tracks : array (Location) of Track_Ids := (others => (0, 0, 0));
-- the railroad should respect the property that no track precedes itself
function No_Track_Precedes_Itself return Boolean is
(for all Track in Track_Id =>
(for all Id in Prev_Id =>
Previous_Tracks (Tracks (Track).From) (Id) /= Track));
-- a train is identified by its unique identifier. The position of each
-- train is given by the starting track it's in (Track_Begin) and the
-- position in this track (Pos_Begin), with the ending track it's in
-- (Track_End) which can be the same as the starting track. A train
-- can never be on three tracks.
Max_Num_Trains : constant := 20;
type Train_Id is new Positive range 1 .. Max_Num_Trains;
type Train_Position is record
Track_Begin : Track_Id;
Pos_Begin : Natural;
Track_End : Track_Id;
end record;
Cur_Num_Trains : Train_Id := Train_Id'First;
Trains : array (Train_Id) of Train_Position;
function Entering_A_Track (Position : Train_Position) return Boolean is
(Position.Track_Begin /= Position.Track_End and then
(for some Id in Prev_Id =>
Position.Track_End = Previous_Tracks (Tracks (Position.Track_Begin).From) (Id)));
function Inside_A_Track (Position : Train_Position) return Boolean is
(Position.Track_Begin = Position.Track_End);
-- it should always hold that there is at most one train in every track
-- segment
function One_Train_At_Most_Per_Track return Boolean is
(for all Train in Train_Id range 1 .. Cur_Num_Trains =>
(for all Other_Train in Train_Id range 1 .. Cur_Num_Trains =>
(if Other_Train /= Train then
Trains (Train).Track_Begin /= Trains (Other_Train).Track_Begin and then
Trains (Train).Track_Begin /= Trains (Other_Train).Track_End and then
Trains (Train).Track_End /= Trains (Other_Train).Track_Begin and then
Trains (Train).Track_End /= Trains (Other_Train).Track_End)));
-- at each instant, the behavior of the train depends on the value of the
-- signal on the track it's in and on the track ahead
type Signal is (Green, Orange, Red);
Track_Signals : array (Track_Id) of Signal;
-- the signal should be Red on every track on which there is a train, and
-- Orange on every previous track, unless already Red on that track.
function Occupied_Tracks_On_Red return Boolean is
(for all Train in Train_Id range 1 .. Cur_Num_Trains =>
Track_Signals (Trains (Train).Track_Begin) = Red and then
Track_Signals (Trains (Train).Track_End) = Red);
-- Return the Id'th track that precedes the ending track of the train
function Get_Previous_Track
(Position : Train_Position;
Id : Prev_Id) return Track_Opt_Id
is
(Previous_Tracks (Tracks (Position.Track_End).From) (Id));
-- Return the Id'th track that precedes the starting track of the train,
-- provided it is different from the ending track of the train
function Get_Other_Previous_Track
(Position : Train_Position;
Id : Prev_Id) return Track_Opt_Id
is
(if Previous_Tracks (Tracks (Position.Track_Begin).From) (Id) =
Position.Track_End
then
No_Track_Id
else
Previous_Tracks (Tracks (Position.Track_Begin).From) (Id));
function Is_Previous_Track
(Position : Train_Position;
Track : Track_Id) return Boolean
is
(for some Id in Prev_Id =>
Track = Get_Previous_Track (Position, Id)
or else
Track = Get_Other_Previous_Track (Position, Id));
function Previous_Tracks_On_Orange_Or_Red return Boolean is
(for all Train in Train_Id range 1 .. Cur_Num_Trains =>
(for all Id in Prev_Id =>
(if Get_Previous_Track (Trains (Train), Id) /= No_Track_Id then
Track_Signals (Get_Previous_Track (Trains (Train), Id)) in
Orange | Red)
and then
(if Get_Other_Previous_Track (Trains (Train), Id) /= No_Track_Id then
Track_Signals (Get_Other_Previous_Track (Trains (Train), Id)) in
Orange | Red)));
function Safe_Signaling return Boolean is
(Occupied_Tracks_On_Red and then
Previous_Tracks_On_Orange_Or_Red);
-- valid movements of trains can be of 3 kinds:
-- . moving inside one or two tracks
-- . entering a new track
-- . leaving a track
-- The following functions correspond each to one of these kinds of
-- movements. Function Valid_Move returns whether a movement is among
-- these 3 kinds.
function Moving_Inside_Current_Tracks
(Cur_Position : Train_Position;
New_Position : Train_Position) return Boolean
is
(Cur_Position.Track_Begin = New_Position.Track_Begin and then
Cur_Position.Track_End = New_Position.Track_End);
function Moving_To_A_New_Track
(Cur_Position : Train_Position;
New_Position : Train_Position) return Boolean
is
(Inside_A_Track (Cur_Position) and then
Entering_A_Track (New_Position) and then
Cur_Position.Track_Begin = New_Position.Track_End);
function Moving_Away_From_Current_Track
(Cur_Position : Train_Position;
New_Position : Train_Position) return Boolean
is
(Entering_A_Track (Cur_Position) and then
Inside_A_Track (New_Position) and then
Cur_Position.Track_Begin = New_Position.Track_End);
function Valid_Move
(Cur_Position : Train_Position;
New_Position : Train_Position) return Boolean
is
-- either the train keeps moving in the current tracks
(Moving_Inside_Current_Tracks (Cur_Position, New_Position)
or else
-- or the train was inside a track and enters a new track
Moving_To_A_New_Track (Cur_Position, New_Position)
or else
-- or the train was entering a track and leaves the previous one
Moving_Away_From_Current_Track (Cur_Position, New_Position));
-- moving the train ahead along a valid movement can result in:
-- . Full_Speed: the movement was performed, the position of the train
-- (Trains) and the signals (Track_Signals) have been
-- updated, and the train can continue full speed.
-- . Slow_Down: Same as Full_Speed, but the train is entering an Orange
-- track and should slow down.
-- . Keep_Going: Same as Full_Speed, but the train should keep its
-- current speed.
-- . Stop: No movement performed, the train should stop here,
-- prior to entering a Red track.
type Move_Result is (Full_Speed, Slow_Down, Keep_Going, Stop);
procedure Move
(Train : Train_Id;
New_Position : Train_Position;
Result : out Move_Result)
with
Global => (Input => Cur_Num_Trains,
In_Out => (Trains, Track_Signals)),
Pre => Train in 1 .. Cur_Num_Trains and then
Valid_Move (Trains (Train), New_Position) and then
One_Train_At_Most_Per_Track and then
Safe_Signaling,
Post => One_Train_At_Most_Per_Track and then
Safe_Signaling;
end Trains;
|
-- CC1010B.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 THE NAMES IN A GENERIC PACKAGE BODY ARE STATICALLY
-- IDENTIFIED (I.E., BOUND) AT THE POINT WHERE THE GENERIC BODY
-- TEXTUALLY OCCURS, AND ARE NOT DYNAMICALLY BOUND AT THE POINT
-- OF INSTANTIATION.
-- ASL 8/13/81
WITH REPORT;
PROCEDURE CC1010B IS
USE REPORT;
FREE : CONSTANT INTEGER := 5;
BEGIN
TEST("CC1010B","PROPER VISIBILITY OF FREE IDENTIFIERS IN " &
"GENERIC PACKAGE DECLARATIONS, BODIES AND INSTANTIATIONS");
DECLARE
GENERIC
GFP : INTEGER := FREE;
PACKAGE P IS
SPECITEM : CONSTANT INTEGER := FREE;
END P;
FREE : CONSTANT INTEGER := 6;
PACKAGE BODY P IS
BODYITEM : INTEGER := FREE;
BEGIN
IF GFP /= 5 OR SPECITEM /= 5 OR BODYITEM /= 6 THEN
FAILED ("BINDINGS INCORRECT");
END IF;
END P;
BEGIN
DECLARE
FREE : CONSTANT INTEGER := 7;
PACKAGE INST IS NEW P;
BEGIN
NULL;
END;
END;
RESULT;
END CC1010B;
|
-- part of OpenGLAda, (c) 2017 Felix Krause
-- released under the terms of the MIT license, see the file "COPYING"
with GL.Blending;
with GL.Buffers;
with GL.Types.Colors;
with GL.Fixed.Matrix;
with GL.Immediate;
with GL.Toggles;
with Glfw.Windows.Context;
with Glfw.Input.Mouse;
with Glfw.Input.Keys;
with Glfw.Monitors;
procedure Glfw_Test.Mouse is
Base_Title : constant String
:= "Click and drag rectangles. Hold mods for coloring. ";
type Test_Window is new Glfw.Windows.Window with record
Start_X, Start_Y : GL.Types.Double;
Color : GL.Types.Colors.Color;
Redraw : Boolean := False;
end record;
overriding
procedure Init (Object : not null access Test_Window;
Width, Height : Glfw.Size;
Title : String;
Monitor : Glfw.Monitors.Monitor := Glfw.Monitors.No_Monitor;
Share : access Glfw.Windows.Window'Class := null);
overriding
procedure Mouse_Position_Changed (Object : not null access Test_Window;
X, Y : Glfw.Input.Mouse.Coordinate);
overriding
procedure Mouse_Button_Changed (Object : not null access Test_Window;
Button : Glfw.Input.Mouse.Button;
State : Glfw.Input.Button_State;
Mods : Glfw.Input.Keys.Modifiers);
procedure Init (Object : not null access Test_Window;
Width, Height : Glfw.Size;
Title : String;
Monitor : Glfw.Monitors.Monitor := Glfw.Monitors.No_Monitor;
Share : access Glfw.Windows.Window'Class := null) is
Upcast : constant Glfw.Windows.Window_Reference
:= Glfw.Windows.Window (Object.all)'Access;
begin
Upcast.Init (Width, Height, Title, Monitor, Share);
Object.Enable_Callback (Glfw.Windows.Callbacks.Mouse_Position);
Object.Enable_Callback (Glfw.Windows.Callbacks.Mouse_Button);
end Init;
procedure Mouse_Position_Changed (Object : not null access Test_Window;
X, Y : Glfw.Input.Mouse.Coordinate) is
use GL.Types.Doubles;
use type Glfw.Input.Button_State;
begin
Object.Set_Title (Base_Title & "(" & X'Img & ", " & Y'Img & ")");
if not Object.Redraw and then
Object.Mouse_Button_State (0) = Glfw.Input.Pressed then
GL.Immediate.Set_Color (Object.Color);
GL.Toggles.Enable (GL.Toggles.Blend);
GL.Blending.Set_Blend_Func
(GL.Blending.Src_Alpha, GL.Blending.One_Minus_Src_Alpha);
declare
Token : GL.Immediate.Input_Token
:= GL.Immediate.Start (GL.Types.Quads);
begin
Token.Add_Vertex (Vector2'(Object.Start_X, Object.Start_Y));
Token.Add_Vertex (Vector2'(Object.Start_X, GL.Types.Double (Y)));
Token.Add_Vertex (Vector2'(GL.Types.Double (X), GL.Types.Double (Y)));
Token.Add_Vertex (Vector2'(GL.Types.Double (X), Object.Start_Y));
end;
Object.Redraw := True;
end if;
end Mouse_Position_Changed;
procedure Mouse_Button_Changed (Object : not null access Test_Window;
Button : Glfw.Input.Mouse.Button;
State : Glfw.Input.Button_State;
Mods : Glfw.Input.Keys.Modifiers) is
use GL.Types.Colors;
use type Glfw.Input.Mouse.Button;
use type Glfw.Input.Button_State;
Colored : Boolean := False;
X, Y : Glfw.Input.Mouse.Coordinate;
begin
if Button /= 0 or else State /= Glfw.Input.Pressed then
return;
end if;
if Mods.Shift then
Object.Color (R) := 1.0;
Colored := True;
else
Object.Color (R) := 0.0;
end if;
if Mods.Control then
Object.Color (G) := 1.0;
Colored := True;
else
Object.Color (G) := 0.0;
end if;
if Mods.Alt then
Object.Color (B) := 1.0;
Colored := True;
else
Object.Color (B) := 0.0;
end if;
if Mods.Super then
Object.Color (A) := 0.5;
else
Object.Color (A) := 1.0;
end if;
if not Colored then
Object.Color := (0.1, 0.1, 0.1, Object.Color (A));
end if;
Object.Get_Cursor_Pos (X, Y);
Object.Start_X := GL.Types.Double (X);
Object.Start_Y := GL.Types.Double (Y);
end Mouse_Button_Changed;
My_Window : aliased Test_Window;
use GL.Fixed.Matrix;
use GL.Buffers;
use type GL.Types.Double;
begin
Glfw.Init;
Enable_Print_Errors;
My_Window'Access.Init (800, 600, Base_Title);
Glfw.Windows.Context.Make_Current (My_Window'Access);
Projection.Load_Identity;
Projection.Apply_Orthogonal (0.0, 800.0, 600.0, 0.0, -1.0, 1.0);
while not My_Window'Access.Should_Close loop
Clear (Buffer_Bits'(others => True));
while not My_Window.Redraw and not My_Window'Access.Should_Close loop
Glfw.Input.Wait_For_Events;
end loop;
GL.Flush;
My_Window.Redraw := False;
Glfw.Windows.Context.Swap_Buffers (My_Window'Access);
end loop;
Glfw.Shutdown;
end Glfw_Test.Mouse;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Localization, Internationalization, Globalization for Ada --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2010-2013, Vadim Godunko <vgodunko@gmail.com> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
-- This package provides several constants for x86 and x86_64 platform.
------------------------------------------------------------------------------
with Interfaces;
with Matreshka.Internals.Utf16;
with Matreshka.SIMD.Intel;
private package Matreshka.Internals.Strings.Constants is
pragma Preelaborate;
use type Interfaces.Integer_16;
Terminator_Mask_32 : constant
array (Matreshka.Internals.Utf16.Utf16_String_Index range 0 .. 1)
of Interfaces.Unsigned_32
:= (0 => 16#0000_0000#,
1 => 16#0000_FFFF#);
-- This mask is used to set unused components of the element to zero on
-- 32-bits platforms.
Terminator_Mask_64 : constant
array (Matreshka.Internals.Utf16.Utf16_String_Index range 0 .. 3)
of Interfaces.Unsigned_64
:= (0 => 16#0000_0000_0000_0000#,
1 => 16#0000_0000_0000_FFFF#,
2 => 16#0000_0000_FFFF_FFFF#,
3 => 16#0000_FFFF_FFFF_FFFF#);
-- This mask is used to set unused components of the element to zero on
-- 64-bits platforms.
Terminator_Mask_x86_64 : constant
array (Matreshka.Internals.Utf16.Utf16_String_Index range 0 .. 7)
of Matreshka.SIMD.Intel.v8hi
:= (0 => ( others => 0),
1 => (1 => -1, others => 0),
2 => (1 .. 2 => -1, others => 0),
3 => (1 .. 3 => -1, others => 0),
4 => (1 .. 4 => -1, others => 0),
5 => (1 .. 5 => -1, others => 0),
6 => (1 .. 6 => -1, others => 0),
7 => (1 .. 7 => -1, others => 0));
-- This mask is used to set unused components of the element to zero on
-- x86_64 platforms.
Terminator_Mask_AVX : constant
array (Matreshka.Internals.Utf16.Utf16_String_Index range 0 .. 15)
of Matreshka.SIMD.Intel.v16hi
:= (0 => ( others => 0),
1 => (1 => -1, others => 0),
2 => (1 .. 2 => -1, others => 0),
3 => (1 .. 3 => -1, others => 0),
4 => (1 .. 4 => -1, others => 0),
5 => (1 .. 5 => -1, others => 0),
6 => (1 .. 6 => -1, others => 0),
7 => (1 .. 7 => -1, others => 0),
8 => (1 .. 8 => -1, others => 0),
9 => (1 .. 9 => -1, others => 0),
10 => (1 .. 10 => -1, others => 0),
11 => (1 .. 11 => -1, others => 0),
12 => (1 .. 12 => -1, others => 0),
13 => (1 .. 13 => -1, others => 0),
14 => (1 .. 14 => -1, others => 0),
15 => (1 .. 15 => -1, others => 0));
-- This mask is used to set unused components of the element to zero on
-- platforms where AVX instruction set is supported.
Surrogate_Kind_Mask_x86_64 : constant Matreshka.SIMD.Intel.v8hi
:= (others => -1_024); -- FC00
Masked_High_Surrogate_x86_64 : constant Matreshka.SIMD.Intel.v8hi
:= (others => -10_240); -- D800
Masked_Low_Surrogate_x86_64 : constant Matreshka.SIMD.Intel.v8hi
:= (others => -9_216); -- DC00
-- Mask and constants to detect surrogate characters in vector. To detect
-- surrogate mask should be applied to vector and result should be compared
-- with corresponding constant to detect high or low surrogates in vector.
Surrogate_Kind_Mask_AVX : constant Matreshka.SIMD.Intel.v16hi
:= (others => -1_024); -- FC00
Masked_High_Surrogate_AVX : constant Matreshka.SIMD.Intel.v16hi
:= (others => -10_240); -- D800
Masked_Low_Surrogate_AVX : constant Matreshka.SIMD.Intel.v16hi
:= (others => -9_216); -- DC00
-- Mask and constants to detect surrogate characters in vector. To detect
-- surrogate mask should be applied to vector and result should be compared
-- with corresponding constant to detect high or low surrogates in vector.
end Matreshka.Internals.Strings.Constants;
|
------------------------------------------------------------------------------
-- --
-- GNU ADA RUNTIME LIBRARY (GNARL) COMPONENTS --
-- --
-- I N T E R F A C E S . C . P O S I X _ R T E --
-- --
-- S p e c --
-- --
-- $Revision: 2 $ --
-- --
-- Copyright (c) 1991,1992,1993,1994, FSU, All Rights Reserved --
-- --
-- GNARL is free software; you can redistribute it and/or modify it under --
-- terms of the GNU Library General Public License as published by the --
-- Free Software Foundation; either version 2, or (at your option) any --
-- later version. GNARL is distributed in the hope that it will be use- --
-- ful, but but WITHOUT ANY WARRANTY; without even the implied warranty of --
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Gen- --
-- eral Library Public License for more details. You should have received --
-- a copy of the GNU Library General Public License along with GNARL; see --
-- file COPYING.LIB. If not, write to the Free Software Foundation, 675 --
-- Mass Ave, Cambridge, MA 02139, USA. --
-- --
------------------------------------------------------------------------------
-- This package interfaces with the POSIX real-time extensions. It may
-- also implement some of them using UNIX operations. It is not a complete
-- interface, it only includes what is needed to implement the Ada runtime.
with System;
-- temporarily, should really only be for 1 ???
with Interfaces.C.POSIX_Error; use Interfaces.C.POSIX_Error;
-- Used for, Return_Code
with Interfaces.C.System_Constants;
use Interfaces.C;
-- Used for, various constants
package Interfaces.C.POSIX_RTE is
pragma Elaborate_Body (Interfaces.C.POSIX_RTE);
Alignment : constant := Natural'Min (1, 8);
NSIG : constant := System_Constants.NSIG;
-- Maximum number of signal entries
type Signal is new int;
type Signal_Set is private;
procedure sigaddset
(set : access Signal_Set;
sig : in Signal;
Result : out POSIX_Error.Return_Code);
procedure sigdelset
(set : access Signal_Set;
sig : in Signal;
Result : out POSIX_Error.Return_Code);
procedure sigfillset
(set : access Signal_Set;
Result : out POSIX_Error.Return_Code);
procedure sigemptyset
(set : access Signal_Set;
Result : out POSIX_Error.Return_Code);
function sigismember
(set : access Signal_Set;
sig : Signal)
return Return_Code;
pragma Import (C, sigismember, "sigismember");
type sigval is record
u0 : int;
end record;
-- This is not used at the moment, need to update to reflect
-- any changes in the Pthreads signal.h in the future
type struct_siginfo is record
si_signo : Signal;
si_code : int;
si_value : sigval;
end record;
type siginfo_ptr is access struct_siginfo;
type sigset_t_ptr is access Signal_Set;
SIG_ERR : constant := System_Constants.SIG_ERR;
SIG_DFL : constant := System_Constants.SIG_DFL;
SIG_IGN : constant := System_Constants.SIG_IGN;
-- constants for sa_handler
type struct_sigaction is record
sa_handler : System.Address;
-- address of signal handler
sa_mask : aliased Signal_Set;
-- Additional signals to be blocked during
-- execution of signal-catching function
sa_flags : int;
-- Special flags to affect behavior of signal
end record;
type sigaction_ptr is access struct_sigaction;
-- Signal catching function (signal handler) has the following profile :
-- procedure Signal_Handler
-- (signo : Signal;
-- info : siginfo_ptr;
-- context : sigcontext_ptr);
SA_NOCLDSTOP : constant := System_Constants.SA_NOCLDSTOP;
-- Don't send a SIGCHLD on child stop
SA_SIGINFO : constant := System_Constants.SA_SIGINFO;
-- sa_flags flags for struct_sigaction
SIG_BLOCK : constant := System_Constants.SIG_BLOCK;
SIG_UNBLOCK : constant := System_Constants.SIG_UNBLOCK;
SIG_SETMASK : constant := System_Constants.SIG_SETMASK;
-- sigprocmask flags (how)
type jmp_buf is array
(1 .. System_Constants.jmp_buf_size) of unsigned;
for jmp_buf'Alignment use Alignment;
type sigjmp_buf is array
(1 .. System_Constants.sigjmp_buf_size) of unsigned;
for sigjmp_buf'Alignment use Alignment;
type jmp_buf_ptr is access jmp_buf;
type sigjmp_buf_ptr is access sigjmp_buf;
-- Environment for long jumps
procedure sigaction
(sig : Signal;
act : access struct_sigaction;
oact : access struct_sigaction;
Result : out Return_Code);
pragma Inline (sigaction);
-- install new sigaction structure and obtain old one
procedure sigaction
(sig : Signal;
oact : access struct_sigaction;
Result : out Return_Code);
pragma Inline (sigaction);
-- Same thing as above, but without the act parameter. By passing null
-- pointer we can find out the action associated with it.
-- WE WANT TO MAKE THIS VERSION TO INCLUDE THE PREVIOUS sigaction.
-- TO BE FIXED LATER ???
procedure sigprocmask
(how : int;
set : access Signal_Set;
oset : access Signal_Set;
Result : out Return_Code);
pragma Inline (sigprocmask);
-- Install new signal mask and obtain old one
procedure sigsuspend
(mask : access Signal_Set;
Result : out Return_Code);
pragma Inline (sigsuspend);
-- Suspend waiting for signals in mask and resume after
-- executing handler or take default action
procedure sigpending
(set : access Signal_Set;
Result : out Return_Code);
pragma Inline (sigpending);
-- get pending signals on thread and process
procedure longjmp (env : jmp_buf; val : int);
pragma Inline (longjmp);
-- execute a jump across procedures according to setjmp
procedure siglongjmp (env : sigjmp_buf; val : int);
pragma Inline (siglongjmp);
-- execute a jump across procedures according to sigsetjmp
procedure setjmp (env : jmp_buf; Result : out Return_Code);
pragma Inline (setjmp);
-- set up a jump across procedures and return here with longjmp
procedure sigsetjmp
(env : sigjmp_buf;
savemask : int;
Result : out Return_Code);
pragma Inline (sigsetjmp);
-- Set up a jump across procedures and return here with siglongjmp
SIGKILL : constant Signal := System_Constants.SIGKILL;
SIGSTOP : constant Signal := System_Constants.SIGSTOP;
-- Signals which cannot be masked
-- Some synchronous signals (cannot be used for interrupt entries)
SIGALRM : constant Signal := System_Constants.SIGALRM;
SIGILL : constant Signal := System_Constants.SIGILL;
SIGFPE : constant Signal := System_Constants.SIGFPE;
SIGSEGV : constant Signal := System_Constants.SIGSEGV;
SIGABRT : constant Signal := System_Constants.SIGABRT;
-- Signals which can be used for Interrupt Entries.
SIGHUP : constant Signal := System_Constants.SIGHUP;
SIGINT : constant Signal := System_Constants.SIGINT;
SIGQUIT : constant Signal := System_Constants.SIGQUIT;
SIGPIPE : constant Signal := System_Constants.SIGPIPE;
SIGTERM : constant Signal := System_Constants.SIGTERM;
SIGUSR1 : constant Signal := System_Constants.SIGUSR1;
SIGUSR2 : constant Signal := System_Constants.SIGUSR2;
SIGCHLD : constant Signal := System_Constants.SIGCHLD;
SIGCONT : constant Signal := System_Constants.SIGCONT;
SIGTSTP : constant Signal := System_Constants.SIGTSTP;
SIGTTIN : constant Signal := System_Constants.SIGTTIN;
SIGTTOU : constant Signal := System_Constants.SIGTTOU;
-- OS specific signals
type Signal_Array is array (positive range <>) of Signal;
OS_Specific_Sync_Signals :
Signal_Array (System_Constants.OS_Specific_Sync_Sigs'Range);
OS_Specific_Async_Signals :
Signal_Array (System_Constants.OS_Specific_Async_Sigs'Range);
private
type Signal_Set is array
(1 .. System_Constants.sigset_t_size) of unsigned;
for Signal_Set'Alignment use Alignment;
end Interfaces.C.POSIX_RTE;
|
with Ada.Text_Io;
with Ada.Float_Text_Io;
with Ada.Integer_Text_Io;
procedure Two_Dimensional_Arrays is
type Matrix_Type is array(Positive range <>, Positive range <>) of Float;
Dim_1 : Positive;
Dim_2 : Positive;
begin
Ada.Integer_Text_Io.Get(Item => Dim_1);
Ada.Integer_Text_Io.Get(Item => Dim_2);
-- Create an inner block with the correctly sized array
declare
Matrix : Matrix_Type(1..Dim_1, 1..Dim_2);
begin
Matrix(1, Dim_2) := 3.14159;
Ada.Float_Text_Io.Put(Item => Matrix(1, Dim_2), Fore => 1, Aft => 5, Exp => 0);
Ada.Text_Io.New_Line;
end;
-- The variable Matrix is popped off the stack automatically
end Two_Dimensional_Arrays;
|
-----------------------------------------------------------------------
-- util-streams-sockets -- Socket streams
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with GNAT.Sockets;
-- The <b>Util.Streams.Sockets</b> package defines a socket stream.
package Util.Streams.Sockets is
-- -----------------------
-- Socket stream
-- -----------------------
-- The <b>Socket_Stream</b> is an output/input stream that reads or writes
-- to or from a socket.
type Socket_Stream is limited new Output_Stream and Input_Stream with private;
-- Initialize the socket stream.
procedure Open (Stream : in out Socket_Stream;
Socket : in GNAT.Sockets.Socket_Type);
-- Initialize the socket stream by opening a connection to the server defined in <b>Server</b>.
procedure Connect (Stream : in out Socket_Stream;
Server : in GNAT.Sockets.Sock_Addr_Type);
-- Close the socket stream.
overriding
procedure Close (Stream : in out Socket_Stream);
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Socket_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
overriding
procedure Read (Stream : in out Socket_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
private
use Ada.Streams;
type Socket_Stream is new Ada.Finalization.Limited_Controlled
and Output_Stream and Input_Stream with record
Sock : GNAT.Sockets.Socket_Type := GNAT.Sockets.No_Socket;
end record;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out Socket_Stream);
end Util.Streams.Sockets;
|
-- Copyright (c) 2021 Devin Hill
-- zlib License -- see LICENSE for details.
with System;
use type System.Address;
package body GBA.Display.Tiles is
function Tile_Block_Address (Ix : Tile_Block_Index) return Address is
begin
return Video_RAM_Address'First + (Address (Ix) * 16#4000#);
end;
function Screen_Block_Address (Ix : Screen_Block_Index) return Address is
begin
return Video_RAM_Address'First + (Address (Ix) * 16#800#);
end;
end GBA.Display.Tiles; |
-- { dg-do run }
-- { dg-options "-O2 -gnatn" }
with Opt38_Pkg; use Opt38_Pkg;
procedure Opt38 is
begin
Test (-1);
end;
|
-- RUN: %llvmgcc -c %s
procedure Placeholder is
subtype Bounded is Integer range 1 .. 5;
type Vector is array (Bounded range <>) of Integer;
type Interval (Length : Bounded := 1) is record
Points : Vector (1 .. Length);
end record;
An_Interval : Interval := (Length => 1, Points => (1 => 1));
generic The_Interval : Interval; package R is end;
package body R is end;
package S is new R (An_Interval);
begin null; end;
|
-- Simple test of "*", "/", "+", and "-" using random arguments.
-- Doesn't test endpoints very well.
with Extended_Real;
with Extended_Real.e_Rand;
with Extended_Real.IO;
with Text_IO; use Text_IO;
procedure e_real_io_tst_2 is
type Real is digits 15;
package ext is new Extended_Real (Real);
use ext;
package eio is new ext.IO;
use eio;
package rnd is new ext.e_Rand;
use rnd;
package rio is new Text_IO.Float_IO(Real);
use rio;
package iio is new Text_IO.Integer_IO(e_Integer);
use iio;
X, Z1 : e_Real;
Last : Integer;
Max_Error, Err : e_Real;
Exp_First, Exp_Last : e_Integer;
type Integer32 is range -2**31+1..2**31-1;
Mult_Limit : constant Integer32 := 8_000_000; -- usually > N * 10^6
-- Number of iterations of multiplication div test. The +/- tests
-- are 8 times this numbers.
Some_Seed : constant Integer := 7251738;
-- Start at different rand stream.
--------------------
-- Get_Random_Exp --
--------------------
-- Make Random e_Integer in range Exp_First..Exp_Last
--
function Random_Exp
(Exp_First : in e_Integer;
Exp_Last : in e_Integer)
return e_Integer
is
Exp : e_Integer;
X : Real;
begin
-- returns random Real in range [0, 1):
--X := Real (rnd.Next_Random_Int mod 2**12) * 2.0**(-12);
-- returns random Real in range (0, 1]:
X := Real (1 + rnd.Next_Random_Int mod 2**24) * 2.0**(-24);
Exp := Exp_First + e_Integer (X * (Real (Exp_Last) - Real (Exp_First)));
return Exp;
end;
-------------
-- Get_999 --
-------------
-- Make an e_real full of digits that have the max value that any
-- any digit can have.
--
function Get_999 return e_Real is
Max_Digit : constant e_Digit := Make_e_Digit (e_Real_Machine_Radix-1.0);
Next_Digit : e_Digit;
Delta_Exp : e_Integer;
Result : e_Real; -- Init to 0 important
begin
for I in 0 .. e_Real_Machine_Mantissa-1 loop
Delta_Exp := -I - 1;
Next_Digit := Scaling (Max_Digit, Delta_Exp);
Result := Next_Digit + Result;
end loop;
return Result;
end;
----------------------------------
-- Print_Extended_Real_Settings --
----------------------------------
procedure Print_Extended_Real_Settings
is
Bits_In_Radix : constant := Desired_No_Of_Bits_In_Radix;
begin
new_line(1);
put (" Desired_Decimal_Digit_Precision =");
put (Integer'Image(Desired_Decimal_Digit_Precision));
new_line(1);
new_line(1);
put ("Number of decimal digits of precision requested: ");
put (Integer'Image(Desired_Decimal_Digit_Precision));
new_line(1);
put ("Number of digits in use (including 2 guard digits): ");
put (e_Integer'Image(e_Real_Machine_Mantissa));
new_line(1);
put ("These digits are not decimal; they have Radix: 2**(");
put (e_Integer'Image(Bits_In_Radix)); put(")");
new_line(1);
put ("In other words, each of these digits is in range: 0 .. 2**(");
put (e_Integer'Image(Bits_In_Radix)); put(")"); put (" - 1.");
new_line(1);
put ("Number of decimal digits per actual digit is approx: 9");
new_line(2);
put("Guard digits (digits of extra precision) are appended to the end of");
new_line(1);
put("each number. There are always 2 guard digits. This adds up to 18");
new_line(1);
put("decimal digits of extra precision. The arithmetic operators, (""*"",");
new_line(1);
put("""/"", ""+"" etc) usually produce results that are correct to all");
new_line(1);
put("digits except the final (guard) digit.");
new_line(2);
put("If a number is correct to all digits except the final (guard) digit,");
new_line(1);
put("expect errors of the order:");
new_line(2);
put(e_Real_Image (e_Real_Model_Epsilon / (One+One)**Bits_In_Radix, aft => 10));
new_line(2);
put("If you lose 2 digits of accuracy (i.e. both guard digits) instead");
new_line(1);
put("of 1 (as in the above case) then you lose another 9 decimal digits");
new_line(1);
put("of accuracy. In this case expect errors of the order:");
new_line(2);
put(e_Real_Image (e_Real_Model_Epsilon, aft => 10));
new_line(2);
put("The above number, by the way, is e_Real_Model_Epsilon.");
new_line(3);
end Print_Extended_Real_Settings;
begin
rnd.Reset (Some_Seed);
Print_Extended_Real_Settings;
put ("The test translates binary to text, then back to binary, and prints");
new_line(1);
put ("the difference: prints X - e_Real_Val (e_Real_Image (X)) over randomly");
new_line(1);
put ("generated X's. 8_000_000 X's are used, and the max error is printed.");
new_line(1);
put ("The testing goes on for as many hours as you let it:");
new_line(2);
for repetitions in 1 .. 1_000_000 loop
Exp_First := e_Real_Machine_Emin+1; -- cause X has exp of -1 intitially.
Exp_Last := e_Real_Machine_Emax-1;
-- The random num we make by scaling with Exp in [Exp_First, Exp_Last]
-- The function Random returns a rand in the range [0.0 .. 1.0).
-- The smallest exp of Random is Max_Available_Digits - 1.
Max_Error := Zero;
for I in Integer32 range 1 .. Mult_Limit loop
X := Random * Get_999;
X := Scaling (X, Random_Exp (Exp_First, Exp_Last));
e_Real_Val (e_Real_Image (X), Z1, Last);
Err := (Z1/X - One);
if Err > Max_Error then
Max_Error := Err;
end if;
end loop;
new_line;
put ("Max Error =");
put (e_Real_Image (Max_Error));
end loop;
end;
|
package body physics.Motor is
procedure dummy is begin null; end;
-- bool Motor::internal_dependsOnSolid(Solid* s)
-- {
-- return false;
-- }
--
-- bool Motor::internal_dependsOnJoint(Joint* j)
-- {
-- return false;
-- }
--
end physics.Motor;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2022 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 body Xoshiro128 with SPARK_Mode => On is
-- This is an Ada port of https://prng.di.unimi.it/xoshiro128plusplus.c.
--
-- https://arxiv.org/abs/1805.01407
-- doi:10.1145/3460772
-- https://arxiv.org/abs/1910.06437
--
-- David Blackman and Sebastiano Vigna.
-- Scrambled linear pseudorandom number generators. ACM Trans. Math. Softw., 47:1−32, 2021.
--
-- The text below is from xoshiro128plusplus.c:
--
-- /* Written in 2019 by David Blackman and Sebastiano Vigna (vigna@acm.org)
--
-- To the extent possible under law, the author has dedicated all copyright
-- and related and neighboring rights to this software to the public domain
-- worldwide. This software is distributed without any warranty.
--
-- See <http://creativecommons.org/publicdomain/zero/1.0/>. */
--
-- /* This is xoshiro128++ 1.0, one of our 32-bit all-purpose, rock-solid
-- generators. It has excellent speed, a state size (128 bits) that is
-- large enough for mild parallelism, and it passes all tests we are aware
-- of.
--
-- For generating just single-precision (i.e., 32-bit) floating-point
-- numbers, xoshiro128+ is even faster.
--
-- The state must be seeded so that it is not everywhere zero. */
function Rotate_Left (X : Unsigned_32; K : Integer) return Unsigned_32 is
((X * 2**K) or (X / 2**(Unsigned_32'Size - K)));
procedure Next (S : in out Generator; Value : out Unsigned_32) is
-- xoshiro128++ (xoshiro128+ is just S (0) + S (3))
Result : constant Unsigned_32 := Rotate_Left (S (0) + S (3), 7) + S (0);
T : constant Unsigned_32 := S (1) * 2**9;
begin
S (2) := S (2) xor S (0);
S (3) := S (3) xor S (1);
S (1) := S (1) xor S (2);
S (0) := S (0) xor S (3);
S (2) := S (2) xor T;
S (3) := Rotate_Left (S (3), 11);
Value := Result;
end Next;
function To_Float (Value : Unsigned_32) return Unit_Interval is
(Float (Value / 2**8) * 2.0**(-24));
-- 8 and 24 for 32-bit, 11 and 53 for 64-bit
procedure Reset (S : out Generator; Seed : Unsigned_64) is
Value : constant Unsigned_32 := Unsigned_32 (Seed mod Unsigned_32'Modulus);
begin
for I in S'Range loop
S (I) := Rotate_Left (Value, I + 1);
end loop;
end Reset;
end Xoshiro128;
|
with Ada.Exception_Identification.From_Here;
with System.Address_To_Constant_Access_Conversions;
with System.Address_To_Named_Access_Conversions;
with System.Storage_Elements;
with System.Zero_Terminated_Strings;
with C.stdint;
package body System.Native_Environment_Encoding is
use Ada.Exception_Identification.From_Here;
use type Ada.Streams.Stream_Element_Offset;
use type Storage_Elements.Storage_Offset;
use type C.icucore.UChar_const_ptr;
use type C.icucore.UConverter_ptr;
pragma Compile_Time_Error (
Standard'Storage_Unit /= Ada.Streams.Stream_Element_Array'Component_Size,
"Address operations is not equivalent to Stream_Element operations");
package char_const_ptr_Conv is
new Address_To_Constant_Access_Conversions (C.char, C.char_const_ptr);
package char_ptr_Conv is
new Address_To_Named_Access_Conversions (C.char, C.char_ptr);
package UChar_const_ptr_Conv is
new Address_To_Constant_Access_Conversions (
C.icucore.UChar,
C.icucore.UChar_const_ptr);
package UChar_ptr_Conv is
new Address_To_Named_Access_Conversions (
C.icucore.UChar,
C.icucore.UChar_ptr);
procedure Adjust_Buffer (
Buffer : in out Buffer_Type;
First : in out C.icucore.UChar_const_ptr;
Limit : in out C.icucore.UChar_ptr);
procedure Adjust_Buffer (
Buffer : in out Buffer_Type;
First : in out C.icucore.UChar_const_ptr;
Limit : in out C.icucore.UChar_ptr) is
begin
if UChar_const_ptr_Conv.To_Address (First) >=
Buffer'Address + Storage_Elements.Storage_Offset'(Half_Buffer_Length)
then
-- shift
declare
First_Index : constant Storage_Elements.Storage_Offset :=
UChar_const_ptr_Conv.To_Address (First) - Buffer'Address;
Limit_Index : constant Storage_Elements.Storage_Offset :=
UChar_ptr_Conv.To_Address (Limit) - Buffer'Address;
Length : constant Storage_Elements.Storage_Offset :=
Limit_Index - First_Index;
Buffer_Storage : Storage_Elements.Storage_Array (
0 ..
Buffer_Type'Size / Standard'Storage_Unit - 1);
for Buffer_Storage'Address use Buffer'Address;
begin
Buffer_Storage (0 .. Length - 1) :=
Buffer_Storage (First_Index .. Limit_Index - 1);
First := UChar_const_ptr_Conv.To_Pointer (Buffer'Address);
Limit := UChar_ptr_Conv.To_Pointer (Buffer'Address + Length);
end;
end if;
end Adjust_Buffer;
procedure Default_Substitute (
uconv : C.icucore.UConverter_ptr;
Item : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
procedure Default_Substitute (
uconv : C.icucore.UConverter_ptr;
Item : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset)
is
len : aliased C.stdint.int8_t := Item'Length;
Error : aliased C.icucore.UErrorCode :=
C.icucore.unicode.utypes.U_ZERO_ERROR;
pragma Suppress (Validity_Check, Error);
begin
C.icucore.unicode.ucnv.ucnv_getSubstChars (
uconv,
char_ptr_Conv.To_Pointer (Item'Address),
len'Access,
Error'Access);
case Error is
when C.icucore.unicode.utypes.U_INDEX_OUTOFBOUNDS_ERROR =>
raise Constraint_Error;
when others =>
null;
end case;
Last := Item'First + Ada.Streams.Stream_Element_Offset (len) - 1;
end Default_Substitute;
-- implementation
function Get_Image (Encoding : Encoding_Id) return String is
begin
return Zero_Terminated_Strings.Value (Encoding);
end Get_Image;
function Get_Default_Substitute (Encoding : Encoding_Id)
return Ada.Streams.Stream_Element_Array
is
Result : Ada.Streams.Stream_Element_Array (
0 .. -- from 0 for a result value
Max_Substitute_Length - 1);
Last : Ada.Streams.Stream_Element_Offset;
uconv : C.icucore.UConverter_ptr;
Error : aliased C.icucore.UErrorCode :=
C.icucore.unicode.utypes.U_ZERO_ERROR;
begin
uconv := C.icucore.unicode.ucnv.ucnv_open (Encoding, Error'Access);
if uconv = null then
Raise_Exception (Name_Error'Identity);
end if;
Default_Substitute (uconv, Result, Last);
C.icucore.unicode.ucnv.ucnv_close (uconv);
return Result (Result'First .. Last);
end Get_Default_Substitute;
function Get_Min_Size_In_Stream_Elements (Encoding : Encoding_Id)
return Ada.Streams.Stream_Element_Offset
is
Result : Ada.Streams.Stream_Element_Offset;
uconv : C.icucore.UConverter_ptr;
Error : aliased C.icucore.UErrorCode :=
C.icucore.unicode.utypes.U_ZERO_ERROR;
begin
uconv := C.icucore.unicode.ucnv.ucnv_open (Encoding, Error'Access);
if uconv = null then
Raise_Exception (Name_Error'Identity);
end if;
Result := Ada.Streams.Stream_Element_Offset (
C.icucore.unicode.ucnv.ucnv_getMinCharSize (uconv));
C.icucore.unicode.ucnv.ucnv_close (uconv);
return Result;
end Get_Min_Size_In_Stream_Elements;
function Get_Current_Encoding return Encoding_Id is
begin
return UTF_8_Name (0)'Access;
end Get_Current_Encoding;
procedure Open (Object : in out Converter; From, To : Encoding_Id) is
From_uconv : C.icucore.UConverter_ptr;
To_uconv : C.icucore.UConverter_ptr;
Error : aliased C.icucore.UErrorCode :=
C.icucore.unicode.utypes.U_ZERO_ERROR;
pragma Suppress (Validity_Check, Error);
begin
From_uconv := C.icucore.unicode.ucnv.ucnv_open (From, Error'Access);
if From_uconv = null then
Raise_Exception (Name_Error'Identity);
end if;
To_uconv := C.icucore.unicode.ucnv.ucnv_open (To, Error'Access);
if To_uconv = null then
C.icucore.unicode.ucnv.ucnv_close (From_uconv);
Raise_Exception (Name_Error'Identity);
end if;
C.icucore.unicode.ucnv.ucnv_setFromUCallBack (
To_uconv,
C.icucore.unicode.ucnv_err.UCNV_FROM_U_CALLBACK_STOP'Access,
C.void_const_ptr (Null_Address),
null,
null,
Error'Access);
case Error is
when C.icucore.unicode.utypes.U_ZERO_ERROR =>
null;
when others =>
C.icucore.unicode.ucnv.ucnv_close (To_uconv);
C.icucore.unicode.ucnv.ucnv_close (From_uconv);
Raise_Exception (Use_Error'Identity);
end case;
-- about "From"
Object.From_uconv := From_uconv;
-- intermediate
Object.Buffer_First :=
UChar_const_ptr_Conv.To_Pointer (Object.Buffer'Address);
Object.Buffer_Limit := UChar_ptr_Conv.To_Pointer (Object.Buffer'Address);
-- about "To"
Object.To_uconv := To_uconv;
Default_Substitute (
To_uconv,
Object.Substitute,
Object.Substitute_Length);
end Open;
procedure Close (Object : in out Converter) is
begin
C.icucore.unicode.ucnv.ucnv_close (Object.From_uconv);
C.icucore.unicode.ucnv.ucnv_close (Object.To_uconv);
end Close;
function Is_Open (Object : Converter) return Boolean is
begin
return Object.From_uconv /= null;
end Is_Open;
function Min_Size_In_From_Stream_Elements_No_Check (Object : Converter)
return Ada.Streams.Stream_Element_Offset is
begin
return Ada.Streams.Stream_Element_Offset (
C.icucore.unicode.ucnv.ucnv_getMinCharSize (Object.From_uconv));
end Min_Size_In_From_Stream_Elements_No_Check;
function Substitute_No_Check (Object : Converter)
return Ada.Streams.Stream_Element_Array is
begin
return Object.Substitute (1 .. Object.Substitute_Length);
end Substitute_No_Check;
procedure Set_Substitute_No_Check (
Object : in out Converter;
Substitute : Ada.Streams.Stream_Element_Array) is
begin
if Substitute'Length > Object.Substitute'Length then
raise Constraint_Error;
end if;
Object.Substitute_Length := Substitute'Length;
Object.Substitute (1 .. Object.Substitute_Length) := Substitute;
end Set_Substitute_No_Check;
procedure Convert_No_Check (
Object : Converter;
Item : Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Out_Item : out Ada.Streams.Stream_Element_Array;
Out_Last : out Ada.Streams.Stream_Element_Offset;
Finish : Boolean;
Status : out Subsequence_Status_Type)
is
Mutable_Object : Converter
renames Object'Unrestricted_Access.all;
Unfilled_Buffer_Limit : constant C.icucore.UChar_const_ptr :=
UChar_const_ptr_Conv.To_Pointer (
Object.Buffer'Address
+ Storage_Elements.Storage_Offset'(Buffer_Type'Length));
Pointer : aliased C.char_const_ptr :=
char_const_ptr_Conv.To_Pointer (Item'Address);
Limit : constant C.char_const_ptr :=
char_const_ptr_Conv.To_Pointer (
Item'Address + Storage_Elements.Storage_Offset'(Item'Length));
Out_Pointer : aliased C.char_ptr :=
char_ptr_Conv.To_Pointer (Out_Item'Address);
Out_Limit : constant C.char_ptr :=
char_ptr_Conv.To_Pointer (
Out_Item'Address
+ Storage_Elements.Storage_Offset'(Out_Item'Length));
Finish_2nd : Boolean;
Error : aliased C.icucore.UErrorCode;
pragma Suppress (Validity_Check, Error);
begin
Adjust_Buffer (
Mutable_Object.Buffer,
Mutable_Object.Buffer_First,
Mutable_Object.Buffer_Limit);
Status := Success;
Error := C.icucore.unicode.utypes.U_ZERO_ERROR;
C.icucore.unicode.ucnv.ucnv_toUnicode (
Object.From_uconv,
Mutable_Object.Buffer_Limit'Access,
Unfilled_Buffer_Limit,
Pointer'Access,
Limit,
null,
Boolean'Pos (Finish),
Error'Access);
case Error is
when C.icucore.unicode.utypes.U_ZERO_ERROR =>
null;
when C.icucore.unicode.utypes.U_TRUNCATED_CHAR_FOUND =>
Status := Truncated;
when C.icucore.unicode.utypes.U_ILLEGAL_CHAR_FOUND =>
Status := Illegal_Sequence;
when C.icucore.unicode.utypes.U_BUFFER_OVERFLOW_ERROR =>
null; -- not finished
when others =>
Raise_Exception (Use_Error'Identity);
end case;
Last := Item'First
+ Ada.Streams.Stream_Element_Offset (
Storage_Elements.Storage_Offset'(
char_const_ptr_Conv.To_Address (Pointer) - Item'Address)
- 1);
Finish_2nd := Finish and then Last = Item'Last;
Error := C.icucore.unicode.utypes.U_ZERO_ERROR;
C.icucore.unicode.ucnv.ucnv_fromUnicode (
Object.To_uconv,
Out_Pointer'Access,
Out_Limit,
Mutable_Object.Buffer_First'Access,
Object.Buffer_Limit,
null,
Boolean'Pos (Finish_2nd),
Error'Access);
case Error is
when C.icucore.unicode.utypes.U_ZERO_ERROR =>
if Finish_2nd and then Status = Success then
Status := Finished;
end if;
when C.icucore.unicode.utypes.U_INVALID_CHAR_FOUND =>
if Status = Success then
Status := Illegal_Sequence;
end if;
when C.icucore.unicode.utypes.U_BUFFER_OVERFLOW_ERROR =>
if Status = Success then
Status := Overflow;
end if;
when others => -- unknown
Raise_Exception (Use_Error'Identity);
end case;
Out_Last := Out_Item'First
+ Ada.Streams.Stream_Element_Offset (
Storage_Elements.Storage_Offset'(
char_ptr_Conv.To_Address (Out_Pointer) - Out_Item'Address)
- 1);
end Convert_No_Check;
procedure Convert_No_Check (
Object : Converter;
Item : Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Out_Item : out Ada.Streams.Stream_Element_Array;
Out_Last : out Ada.Streams.Stream_Element_Offset;
Status : out Continuing_Status_Type)
is
Subsequence_Status : Subsequence_Status_Type;
begin
Convert_No_Check (
Object,
Item,
Last,
Out_Item,
Out_Last,
False,
Subsequence_Status);
pragma Assert (
Subsequence_Status in
Subsequence_Status_Type (Continuing_Status_Type'First) ..
Subsequence_Status_Type (Continuing_Status_Type'Last));
Status := Continuing_Status_Type (Subsequence_Status);
end Convert_No_Check;
procedure Convert_No_Check (
Object : Converter;
Out_Item : out Ada.Streams.Stream_Element_Array;
Out_Last : out Ada.Streams.Stream_Element_Offset;
Finish : True_Only;
Status : out Finishing_Status_Type)
is
pragma Unreferenced (Finish);
Mutable_Object : Converter
renames Object'Unrestricted_Access.all;
Out_Pointer : aliased C.char_ptr :=
char_ptr_Conv.To_Pointer (Out_Item'Address);
Out_Limit : constant C.char_ptr :=
char_ptr_Conv.To_Pointer (
Out_Item'Address
+ Storage_Elements.Storage_Offset'(Out_Item'Length));
Error : aliased C.icucore.UErrorCode :=
C.icucore.unicode.utypes.U_ZERO_ERROR;
pragma Suppress (Validity_Check, Error);
begin
C.icucore.unicode.ucnv.ucnv_fromUnicode (
Object.To_uconv,
Out_Pointer'Access,
Out_Limit,
Mutable_Object.Buffer_First'Access,
Object.Buffer_Limit,
null,
1, -- flush
Error'Access);
case Error is
when C.icucore.unicode.utypes.U_ZERO_ERROR =>
Status := Finished;
when C.icucore.unicode.utypes.U_BUFFER_OVERFLOW_ERROR =>
Status := Overflow;
when others => -- unknown
Raise_Exception (Use_Error'Identity);
end case;
Out_Last := Out_Item'First
+ Ada.Streams.Stream_Element_Offset (
Storage_Elements.Storage_Offset'(
char_ptr_Conv.To_Address (Out_Pointer) - Out_Item'Address)
- 1);
end Convert_No_Check;
procedure Convert_No_Check (
Object : Converter;
Item : Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Out_Item : out Ada.Streams.Stream_Element_Array;
Out_Last : out Ada.Streams.Stream_Element_Offset;
Finish : True_Only;
Status : out Substituting_Status_Type)
is
Index : Ada.Streams.Stream_Element_Offset := Item'First;
Out_Index : Ada.Streams.Stream_Element_Offset := Out_Item'First;
begin
loop
declare
Subsequence_Status : Subsequence_Status_Type;
begin
Convert_No_Check (
Object,
Item (Index .. Item'Last),
Last,
Out_Item (Out_Index .. Out_Item'Last),
Out_Last,
Finish => Finish,
Status => Subsequence_Status);
pragma Assert (
Subsequence_Status in
Subsequence_Status_Type (Status_Type'First) ..
Subsequence_Status_Type (Status_Type'Last));
case Status_Type (Subsequence_Status) is
when Finished =>
Status := Finished;
return;
when Success =>
Status := Success;
return;
when Overflow =>
Status := Overflow;
return; -- error
when Illegal_Sequence =>
declare
Is_Overflow : Boolean;
begin
Put_Substitute (
Object,
Out_Item (Out_Last + 1 .. Out_Item'Last),
Out_Last,
Is_Overflow);
if Is_Overflow then
Status := Overflow;
return; -- wait a next try
end if;
end;
declare
New_Last : Ada.Streams.Stream_Element_Offset :=
Last
+ Min_Size_In_From_Stream_Elements_No_Check (Object);
begin
if New_Last > Item'Last
or else New_Last < Last -- overflow
then
New_Last := Item'Last;
end if;
Last := New_Last;
end;
Index := Last + 1;
Out_Index := Out_Last + 1;
end case;
end;
end loop;
end Convert_No_Check;
procedure Put_Substitute (
Object : Converter;
Out_Item : out Ada.Streams.Stream_Element_Array;
Out_Last : out Ada.Streams.Stream_Element_Offset;
Is_Overflow : out Boolean) is
begin
Is_Overflow := Out_Item'Length < Object.Substitute_Length;
if Is_Overflow then
Out_Last := Out_Item'First - 1;
else
Out_Last := Out_Item'First + (Object.Substitute_Length - 1);
Out_Item (Out_Item'First .. Out_Last) :=
Object.Substitute (1 .. Object.Substitute_Length);
end if;
end Put_Substitute;
end System.Native_Environment_Encoding;
|
-- Copyright 2017-2021 Bartek thindil Jasicki
--
-- This file is part of Steam Sky.
--
-- Steam Sky is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- Steam Sky is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with Steam Sky. If not, see <http://www.gnu.org/licenses/>.
with Ada.Characters.Handling; use Ada.Characters.Handling;
with DOM.Core; use DOM.Core;
with DOM.Core.Documents;
with DOM.Core.Nodes; use DOM.Core.Nodes;
with DOM.Core.Elements; use DOM.Core.Elements;
with Items; use Items;
with Log; use Log;
with Utils; use Utils;
package body Mobs is
procedure LoadMobs(Reader: Tree_Reader) is
MobsData: Document;
NodesList, ChildNodes: Node_List;
TempRecord: ProtoMobRecord
(Amount_Of_Attributes => Attributes_Amount,
Amount_Of_Skills => Skills_Amount);
TempSkills: Skills_Container.Vector;
TempInventory: MobInventory_Container.Vector;
TempPriorities: constant Natural_Array(1 .. 12) := (others => 0);
TempEquipment: constant Equipment_Array := (others => 0);
OrdersNames: constant array(1 .. 11) of Unbounded_String :=
(To_Unbounded_String("Piloting"), To_Unbounded_String("Engineering"),
To_Unbounded_String("Operating guns"),
To_Unbounded_String("Repair ship"),
To_Unbounded_String("Manufacturing"),
To_Unbounded_String("Upgrading ship"),
To_Unbounded_String("Talking in bases"),
To_Unbounded_String("Healing wounded"),
To_Unbounded_String("Cleaning ship"),
To_Unbounded_String("Defend ship"),
To_Unbounded_String("Board enemy ship"));
EquipmentNames: constant array(1 .. 7) of Unbounded_String :=
(To_Unbounded_String("Weapon"), To_Unbounded_String("Shield"),
To_Unbounded_String("Head"), To_Unbounded_String("Torso"),
To_Unbounded_String("Arms"), To_Unbounded_String("Legs"),
To_Unbounded_String("Tool"));
Action, SubAction: Data_Action;
MobNode, ChildNode: Node;
ChildIndex: Natural;
DeleteIndex: Positive;
MobIndex, ItemIndex: Unbounded_String;
begin
MobsData := Get_Tree(Reader);
NodesList :=
DOM.Core.Documents.Get_Elements_By_Tag_Name(MobsData, "mobile");
Load_Mobs_Loop :
for I in 0 .. Length(NodesList) - 1 loop
TempRecord :=
(Amount_Of_Attributes => Attributes_Amount,
Amount_Of_Skills => Skills_Amount, Skills => TempSkills,
Attributes => (others => <>), Order => Rest,
Priorities => TempPriorities, Inventory => TempInventory,
Equipment => TempEquipment);
MobNode := Item(NodesList, I);
MobIndex := To_Unbounded_String(Get_Attribute(MobNode, "index"));
Action :=
(if Get_Attribute(MobNode, "action")'Length > 0 then
Data_Action'Value(Get_Attribute(MobNode, "action"))
else ADD);
if Action in UPDATE | REMOVE then
if not ProtoMobs_Container.Contains(ProtoMobs_List, MobIndex) then
raise Data_Loading_Error
with "Can't " & To_Lower(Data_Action'Image(Action)) &
" mob '" & To_String(MobIndex) &
"', there is no mob with that index.";
end if;
elsif ProtoMobs_Container.Contains(ProtoMobs_List, MobIndex) then
raise Data_Loading_Error
with "Can't add mob '" & To_String(MobIndex) &
"', there is already a mob with that index.";
end if;
if Action /= REMOVE then
if Action = UPDATE then
TempRecord := ProtoMobs_List(MobIndex);
end if;
ChildNodes :=
DOM.Core.Elements.Get_Elements_By_Tag_Name(MobNode, "skill");
Load_Skills_Loop :
for J in 0 .. Length(ChildNodes) - 1 loop
ChildNode := Item(ChildNodes, J);
ChildIndex :=
Find_Skill_Index(Get_Attribute(ChildNode, "name"));
if Get_Attribute(ChildNode, "name") = "WeaponSkill" then
ChildIndex :=
Natural(SkillsData_Container.Length(Skills_List)) + 1;
end if;
if ChildIndex = 0 then
raise Data_Loading_Error
with "Can't " & To_Lower(Data_Action'Image(Action)) &
" mob '" & To_String(MobIndex) &
"', there no skill named '" &
Get_Attribute(ChildNode, "name") & "'.";
end if;
SubAction :=
(if Get_Attribute(ChildNode, "action")'Length > 0 then
Data_Action'Value(Get_Attribute(ChildNode, "action"))
else ADD);
case SubAction is
when ADD =>
if Get_Attribute(ChildNode, "level")'Length /= 0 then
TempRecord.Skills.Append
(New_Item =>
(ChildIndex,
Integer'Value(Get_Attribute(ChildNode, "level")),
0));
else
if Integer'Value
(Get_Attribute(ChildNode, "minlevel")) >
Integer'Value
(Get_Attribute(ChildNode, "maxlevel")) then
raise Data_Loading_Error
with "Can't " &
To_Lower(Data_Action'Image(Action)) & " mob '" &
To_String(MobIndex) &
" invalid range for skill '" &
Get_Attribute(ChildNode, "name") & "'";
end if;
TempRecord.Skills.Append
(New_Item =>
(ChildIndex,
Integer'Value
(Get_Attribute(ChildNode, "minlevel")),
Integer'Value
(Get_Attribute(ChildNode, "maxlevel"))));
end if;
when UPDATE =>
for Skill of TempRecord.Skills loop
if Skill.Index = ChildIndex then
if Get_Attribute(ChildNode, "level")'Length /=
0 then
Skill :=
(ChildIndex,
Integer'Value
(Get_Attribute(ChildNode, "level")),
0);
else
if Integer'Value
(Get_Attribute(ChildNode, "minlevel")) >
Integer'Value
(Get_Attribute(ChildNode, "maxlevel")) then
raise Data_Loading_Error
with "Can't " &
To_Lower(Data_Action'Image(Action)) &
" mob '" & To_String(MobIndex) &
" invalid range for skill '" &
Get_Attribute(ChildNode, "name") & "'";
end if;
Skill :=
(ChildIndex,
Integer'Value
(Get_Attribute(ChildNode, "minlevel")),
Integer'Value
(Get_Attribute(ChildNode, "maxlevel")));
end if;
exit;
end if;
end loop;
when REMOVE =>
Remove_Skill_Loop :
for K in TempRecord.Skills.Iterate loop
if TempRecord.Skills(K).Index = ChildIndex then
DeleteIndex := Skills_Container.To_Index(K);
exit Remove_Skill_Loop;
end if;
end loop Remove_Skill_Loop;
TempRecord.Skills.Delete(Index => DeleteIndex);
end case;
end loop Load_Skills_Loop;
ChildNodes :=
DOM.Core.Elements.Get_Elements_By_Tag_Name(MobNode, "attribute");
if Length(ChildNodes) > 0 and Action = UPDATE then
TempRecord.Attributes := (others => <>);
end if;
Load_Attributes_Loop :
for J in 0 .. Length(ChildNodes) - 1 loop
ChildNode := Item(ChildNodes, J);
if Get_Attribute(ChildNode, "level") /= "" then
TempRecord.Attributes(J + 1) :=
(Integer'Value(Get_Attribute(ChildNode, "level")), 0);
else
if Integer'Value(Get_Attribute(ChildNode, "minlevel")) >
Integer'Value(Get_Attribute(ChildNode, "maxlevel")) then
raise Data_Loading_Error
with "Can't " & To_Lower(Data_Action'Image(Action)) &
" mob '" & To_String(MobIndex) &
" invalid range for attribute.";
end if;
TempRecord.Attributes(J + 1) :=
(Integer'Value(Get_Attribute(ChildNode, "minlevel")),
Integer'Value(Get_Attribute(ChildNode, "maxlevel")));
end if;
exit Load_Attributes_Loop when J + 1 =
Positive
(AttributesData_Container.Length
(Container => Attributes_List));
end loop Load_Attributes_Loop;
ChildNodes :=
DOM.Core.Elements.Get_Elements_By_Tag_Name(MobNode, "priority");
Load_Orders_Loop :
for J in 0 .. Length(ChildNodes) - 1 loop
ChildNode := Item(ChildNodes, J);
Set_Priorities_Loop :
for K in OrdersNames'Range loop
if OrdersNames(K) =
To_Unbounded_String(Get_Attribute(ChildNode, "name")) then
TempRecord.Priorities(K) :=
(if Get_Attribute(ChildNode, "value") = "Normal" then 1
else 2);
exit Set_Priorities_Loop;
end if;
end loop Set_Priorities_Loop;
end loop Load_Orders_Loop;
if Get_Attribute(MobNode, "order")'Length > 0 then
TempRecord.Order :=
Crew_Orders'Value(Get_Attribute(MobNode, "order"));
end if;
ChildNodes :=
DOM.Core.Elements.Get_Elements_By_Tag_Name(MobNode, "item");
Load_Items_Loop :
for J in 0 .. Length(ChildNodes) - 1 loop
ChildNode := Item(ChildNodes, J);
ItemIndex :=
To_Unbounded_String(Get_Attribute(ChildNode, "index"));
if not Objects_Container.Contains(Items_List, ItemIndex) then
raise Data_Loading_Error
with "Can't " & To_Lower(Data_Action'Image(Action)) &
" mob '" & To_String(MobIndex) &
"', there is no item with index '" &
Get_Attribute(ChildNode, "index") & "'.";
end if;
SubAction :=
(if Get_Attribute(ChildNode, "action")'Length > 0 then
Data_Action'Value(Get_Attribute(ChildNode, "action"))
else ADD);
case SubAction is
when ADD =>
if Get_Attribute(ChildNode, "amount")'Length /= 0 then
TempRecord.Inventory.Append
(New_Item =>
(ItemIndex,
Integer'Value
(Get_Attribute(ChildNode, "amount")),
0));
else
if Integer'Value
(Get_Attribute(ChildNode, "minamount")) >
Integer'Value
(Get_Attribute(ChildNode, "maxamount")) then
raise Data_Loading_Error
with "Can't " &
To_Lower(Data_Action'Image(Action)) & " mob '" &
To_String(MobIndex) &
" invalid range for amount of '" &
Get_Attribute(ChildNode, "index") & "'.";
end if;
TempRecord.Inventory.Append
(New_Item =>
(ItemIndex,
Integer'Value
(Get_Attribute(ChildNode, "minamount")),
Integer'Value
(Get_Attribute(ChildNode, "maxamount"))));
end if;
when UPDATE =>
Update_Items_Loop :
for Item of TempRecord.Inventory loop
if Item.ProtoIndex = ItemIndex then
if Get_Attribute(ChildNode, "amount")'Length /=
0 then
Item :=
(ItemIndex,
Integer'Value
(Get_Attribute(ChildNode, "amount")),
0);
else
if Integer'Value
(Get_Attribute(ChildNode, "minamount")) >
Integer'Value
(Get_Attribute(ChildNode, "maxamount")) then
raise Data_Loading_Error
with "Can't " &
To_Lower(Data_Action'Image(Action)) &
" mob '" & To_String(MobIndex) &
" invalid range for amount of '" &
Get_Attribute(ChildNode, "index") & "'.";
end if;
Item :=
(ItemIndex,
Integer'Value
(Get_Attribute(ChildNode, "minamount")),
Integer'Value
(Get_Attribute(ChildNode, "maxamount")));
end if;
exit Update_Items_Loop;
end if;
end loop Update_Items_Loop;
when REMOVE =>
declare
DeleteIndex: Natural := 0;
begin
Remove_Items_Loop :
for K in
TempRecord.Inventory.First_Index ..
TempRecord.Inventory.Last_Index loop
if TempRecord.Inventory(K).ProtoIndex =
ItemIndex then
DeleteIndex := K;
exit Remove_Items_Loop;
end if;
end loop Remove_Items_Loop;
if DeleteIndex > 0 then
TempRecord.Inventory.Delete(DeleteIndex);
end if;
end;
end case;
end loop Load_Items_Loop;
ChildNodes :=
DOM.Core.Elements.Get_Elements_By_Tag_Name(MobNode, "equipment");
Equipment_Loop :
for J in 0 .. Length(ChildNodes) - 1 loop
ChildNode := Item(ChildNodes, J);
Update_Equipment_Loop :
for K in EquipmentNames'Range loop
if EquipmentNames(K) =
To_Unbounded_String(Get_Attribute(ChildNode, "slot")) then
TempRecord.Equipment(K) :=
Positive'Value(Get_Attribute(ChildNode, "index"));
exit Update_Equipment_Loop;
end if;
end loop Update_Equipment_Loop;
end loop Equipment_Loop;
if Action /= UPDATE then
ProtoMobs_Container.Include
(ProtoMobs_List, MobIndex, TempRecord);
Log_Message("Mob added: " & To_String(MobIndex), EVERYTHING);
else
ProtoMobs_List(MobIndex) := TempRecord;
Log_Message("Mob updated: " & To_String(MobIndex), EVERYTHING);
end if;
else
ProtoMobs_Container.Exclude(ProtoMobs_List, MobIndex);
Log_Message("Mob removed: " & To_String(MobIndex), EVERYTHING);
end if;
end loop Load_Mobs_Loop;
end LoadMobs;
function GenerateMob
(MobIndex, FactionIndex: Unbounded_String) return Member_Data is
Mob: Member_Data
(Amount_Of_Attributes => Attributes_Amount,
Amount_Of_Skills => Skills_Amount);
ProtoMob: constant ProtoMobRecord := ProtoMobs_List(MobIndex);
Amount: Natural;
HighestSkillLevel, WeaponSkillLevel: Skill_Range := 1;
SkillIndex: Skills_Container.Extended_Index;
begin
Mob.Faction :=
(if Get_Random(1, 100) < 99 then FactionIndex else GetRandomFaction);
Mob.Gender := 'M';
if not Factions_List(Mob.Faction).Flags.Contains
(To_Unbounded_String("nogender"))
and then Get_Random(1, 100) > 50 then
Mob.Gender := 'F';
end if;
Mob.Name := GenerateMemberName(Mob.Gender, Mob.Faction);
Skills_Loop :
for Skill of ProtoMob.Skills loop
SkillIndex :=
(if Skill.Index = Skills_Amount + 1 then
Factions_List(Mob.Faction).WeaponSkill
else Skill.Index);
if Skill.Experience = 0 then
Mob.Skills.Append(New_Item => (SkillIndex, Skill.Level, 0));
else
Mob.Skills.Append
(New_Item =>
(SkillIndex, Get_Random(Skill.Level, Skill.Experience), 0));
end if;
if SkillIndex = Factions_List(Mob.Faction).WeaponSkill then
WeaponSkillLevel := Mob.Skills(Mob.Skills.Last_Index).Level;
end if;
if Mob.Skills(Mob.Skills.Last_Index).Level > HighestSkillLevel then
HighestSkillLevel := Mob.Skills(Mob.Skills.Last_Index).Level;
end if;
end loop Skills_Loop;
Attributes_Loop :
for Attribute in ProtoMob.Attributes'Range loop
if ProtoMob.Attributes(Attribute).Experience = 0 then
Mob.Attributes(Attribute) := ProtoMob.Attributes(Attribute);
else
Mob.Attributes(Attribute) :=
(Get_Random
(ProtoMob.Attributes(Attribute).Level,
ProtoMob.Attributes(Attribute).Experience),
0);
end if;
end loop Attributes_Loop;
Inventory_Loop :
for I in ProtoMob.Inventory.Iterate loop
Amount :=
(if ProtoMob.Inventory(I).MaxAmount > 0 then
Get_Random
(ProtoMob.Inventory(I).MinAmount,
ProtoMob.Inventory(I).MaxAmount)
else ProtoMob.Inventory(I).MinAmount);
Mob.Inventory.Append
(New_Item =>
(ProtoIndex => ProtoMob.Inventory(I).ProtoIndex,
Amount => Amount, Name => Null_Unbounded_String,
Durability => 100, Price => 0));
end loop Inventory_Loop;
Mob.Equipment := ProtoMob.Equipment;
declare
ItemsList: UnboundedString_Container.Vector;
ItemIndex: Unbounded_String;
begin
Equipment_Loop :
for I in 1 .. 6 loop
ItemsList :=
(case I is when 1 => Weapons_List, when 2 => Shields_List,
when 3 => HeadArmors_List, when 4 => ChestArmors_List,
when 5 => ArmsArmors_List, when 6 => LegsArmors_List);
if Mob.Equipment(I) = 0 then
ItemIndex := Null_Unbounded_String;
if Get_Random(1, 100) < 95 then
ItemIndex :=
GetRandomItem
(ItemsList, I, HighestSkillLevel, WeaponSkillLevel,
Mob.Faction);
end if;
if ItemIndex /= Null_Unbounded_String then
Mob.Inventory.Append
(New_Item =>
(ProtoIndex => ItemIndex, Amount => 1,
Name => Null_Unbounded_String, Durability => 100,
Price => 0));
Mob.Equipment(I) := Mob.Inventory.Last_Index;
end if;
end if;
end loop Equipment_Loop;
end;
Mob.Orders := ProtoMob.Priorities;
Mob.Order := ProtoMob.Order;
Mob.OrderTime := 15;
Mob.PreviousOrder := Rest;
Mob.Health := 100;
Mob.Tired := 0;
Mob.Hunger := 0;
Mob.Thirst := 0;
Mob.Payment := (20, 0);
Mob.ContractLength := -1;
Mob.Morale := (50, 0);
Mob.Loyalty := 100;
Mob.HomeBase := 1;
return Mob;
end GenerateMob;
function GetRandomItem
(ItemsIndexes: UnboundedString_Container.Vector;
EquipIndex, HighestLevel, WeaponSkillLevel: Positive;
FactionIndex: Unbounded_String) return Unbounded_String is
ItemIndex, MaxIndex: Positive;
NewIndexes: UnboundedString_Container.Vector;
Added: Boolean;
begin
if EquipIndex > 1 then
Equipment_Item_Loop :
for I in ItemsIndexes.First_Index .. ItemsIndexes.Last_Index loop
Added := False;
Add_Equipment_Item_Loop :
for J in NewIndexes.First_Index .. NewIndexes.Last_Index loop
if Items_List(ItemsIndexes(I)).Price <
Items_List(NewIndexes(J)).Price then
NewIndexes.Insert(J, ItemsIndexes(I));
Added := True;
exit Add_Equipment_Item_Loop;
end if;
end loop Add_Equipment_Item_Loop;
if not Added then
NewIndexes.Append(ItemsIndexes(I));
end if;
end loop Equipment_Item_Loop;
MaxIndex :=
Positive
((Float(NewIndexes.Last_Index) * (Float(HighestLevel) / 100.0)) +
1.0);
if MaxIndex > NewIndexes.Last_Index then
MaxIndex := NewIndexes.Last_Index;
end if;
ItemIndex := Get_Random(NewIndexes.First_Index, MaxIndex);
else
Proto_Items_Loop :
for I in ItemsIndexes.First_Index .. ItemsIndexes.Last_Index loop
Added := False;
Add_Proto_Item_Loop :
for J in NewIndexes.First_Index .. NewIndexes.Last_Index loop
if Items_List(ItemsIndexes(I)).Price <
Items_List(NewIndexes(J)).Price and
Items_List(ItemsIndexes(I)).Value(3) =
Factions_List(FactionIndex).WeaponSkill then
NewIndexes.Insert(J, ItemsIndexes(I));
Added := True;
exit Add_Proto_Item_Loop;
end if;
end loop Add_Proto_Item_Loop;
if not Added and
Items_List(ItemsIndexes(I)).Value(3) =
Factions_List(FactionIndex).WeaponSkill then
NewIndexes.Append(ItemsIndexes(I));
end if;
end loop Proto_Items_Loop;
if NewIndexes.Length = 0 then
return Null_Unbounded_String;
end if;
MaxIndex :=
Positive
((Float(NewIndexes.Last_Index) *
(Float(WeaponSkillLevel) / 100.0)) +
1.0);
if MaxIndex > NewIndexes.Last_Index then
MaxIndex := NewIndexes.Last_Index;
end if;
Get_Weapon_Loop :
loop
ItemIndex := Get_Random(NewIndexes.First_Index, MaxIndex);
exit Get_Weapon_Loop when Items_List(NewIndexes(ItemIndex)).Value
(3) =
Factions_List(FactionIndex).WeaponSkill;
end loop Get_Weapon_Loop;
end if;
Get_Item_Index_Loop :
for Index of ItemsIndexes loop
if Index = NewIndexes(ItemIndex) then
return Index;
end if;
end loop Get_Item_Index_Loop;
return Null_Unbounded_String;
end GetRandomItem;
end Mobs;
|
with AUnit;
with AUnit.Test_Cases;
with ZMQ.Contexts;
with ZMQ.Sockets;
package ZMQ.Tests.Testcases.Test_Pubsub is
type Test_Case;
type Test_Case is new AUnit.Test_Cases.Test_Case with record
Ctx : ZMQ.Contexts.Context;
Pub : ZMQ.Sockets.Socket;
Sub : ZMQ.Sockets.Socket;
end record;
procedure Register_Tests (T : in out Test_Case);
-- Register routines to be run
function Name (T : Test_Case)
return AUnit.Message_String;
-- Returns name identifying the test case
end ZMQ.Tests.TestCases.Test_Pubsub;
|
-- Abstract :
--
-- See spec.
--
-- Copyright (C) 2017, 2019 Free Software Foundation, Inc.
--
-- This library is free software; you can redistribute it and/or modify it
-- under terms of the GNU General Public License as published by the Free
-- Software Foundation; either version 3, or (at your option) any later
-- version. This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN-
-- TABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-- As a special exception under Section 7 of GPL version 3, you are granted
-- additional permissions described in the GCC Runtime Library Exception,
-- version 3.1, as published by the Free Software Foundation.
pragma License (Modified_GPL);
with Ada.Calendar.Formatting;
with Ada.Strings.Fixed;
package body WisiToken.Text_IO_Trace is
function Insert_Prefix_At_Newlines (Trace : in Text_IO_Trace.Trace; Item : in String) return String
is
use Ada.Strings.Fixed;
use Ada.Strings.Unbounded;
Result : Unbounded_String;
First : Integer := Item'First;
Last : Integer;
begin
loop
Last := Index (Pattern => "" & ASCII.LF, Source => Item (First .. Item'Last));
exit when Last = 0;
Result := Result & Item (First .. Last) & Trace.Prefix;
First := Last + 1;
end loop;
Result := Result & Item (First .. Item'Last);
return -Result;
end Insert_Prefix_At_Newlines;
----------
-- Public subprograms, declaration order
overriding
procedure Set_Prefix (Trace : in out Text_IO_Trace.Trace; Prefix : in String)
is begin
Trace.Prefix := +Prefix;
end Set_Prefix;
overriding
procedure Put (Trace : in out Text_IO_Trace.Trace; Item : in String; Prefix : in Boolean := True)
is
use Ada.Text_IO;
begin
if Trace.File /= null and then Is_Open (Trace.File.all) then
Ada.Text_IO.Put (Trace.File.all, (if Prefix then -Trace.Prefix else "") & Item);
else
Ada.Text_IO.Put ((if Prefix then -Trace.Prefix else "") & Item);
end if;
end Put;
overriding
procedure Put_Line (Trace : in out Text_IO_Trace.Trace; Item : in String)
is
use Ada.Strings.Fixed;
use Ada.Text_IO;
Temp : constant String :=
(if 0 /= Index (Item, "" & ASCII.LF)
then Insert_Prefix_At_Newlines (Trace, Item)
else Item);
begin
if Trace.File /= null and then Is_Open (Trace.File.all) then
Ada.Text_IO.Put_Line (Trace.File.all, -Trace.Prefix & Temp);
Ada.Text_IO.Flush (Trace.File.all);
else
Ada.Text_IO.Put_Line (-Trace.Prefix & Temp);
Ada.Text_IO.Flush;
end if;
end Put_Line;
overriding
procedure New_Line (Trace : in out Text_IO_Trace.Trace)
is
use Ada.Text_IO;
begin
if Trace.File /= null and then Is_Open (Trace.File.all) then
Ada.Text_IO.New_Line (Trace.File.all);
else
Ada.Text_IO.New_Line;
end if;
end New_Line;
overriding
procedure Put_Clock (Trace : in out Text_IO_Trace.Trace; Label : in String)
is begin
Trace.Put_Line
(Ada.Calendar.Formatting.Image
(Ada.Calendar.Clock, Include_Time_Fraction => True) & " " & Label);
end Put_Clock;
procedure Set_File (Trace : in out Text_IO_Trace.Trace; File : in Ada.Text_IO.File_Access)
is begin
Trace.File := File;
end Set_File;
procedure Clear_File (Trace : in out Text_IO_Trace.Trace)
is begin
Trace.File := null;
end Clear_File;
end WisiToken.Text_IO_Trace;
|
-----------------------------------------------------------------------
-- keystore-ios -- IO low level operation for the keystore
-- Copyright (C) 2019 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Encoders.SHA256;
with Util.Encoders.HMAC.SHA256;
with Keystore.Logs;
-- Generic Block header
-- +------------------+
-- | Block type | 2b
-- | Encrypt 1 size | 2b
-- | Wallet id | 4b
-- | PAD 0 | 4b
-- | PAD 0 | 4b
-- +------------------+
-- | ...AES-CTR... | B
-- +------------------+
-- | Block HMAC-256 | 32b
-- +------------------+
--
-- Free block
-- +------------------+
-- | 00 00 00 00 | 4b
-- | 00 00 00 00 | 4b
-- | Next free block | 4b
-- | PAD 0 | 4b
-- +------------------+
-- | Free block ID | 4b
-- +------------------+
-- | ... |
-- +------------------+
-- | PAD 0 |
-- +------------------+
-- | PAD 0 | 32b
-- +------------------+
--
package body Keystore.IO is
use Interfaces;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Keystore.IO");
procedure Put_Encrypt_Size (Into : in out Block_Type;
Value : in Block_Index);
function Get_Decrypt_Size (From : in IO_Block_Type) return Interfaces.Unsigned_16;
procedure Put_Encrypt_Size (Into : in out Block_Type;
Value : in Block_Index) is
V : constant Interfaces.Unsigned_16 := Interfaces.Unsigned_16 (Value);
begin
Into (BT_HEADER_START + 2) := Stream_Element (Shift_Right (V, 8));
Into (BT_HEADER_START + 3) := Stream_Element (V and 16#0ff#);
end Put_Encrypt_Size;
function Get_Decrypt_Size (From : in IO_Block_Type) return Interfaces.Unsigned_16 is
begin
return Shift_Left (Unsigned_16 (From (BT_HEADER_START + 2)), 8) or
Unsigned_16 (From (BT_HEADER_START + 3));
end Get_Decrypt_Size;
-- ------------------------------
-- Read the block from the wallet IO stream and decrypt the block content using
-- the decipher object. The decrypted content is stored in the marshaller which
-- is ready to read the start of the block header.
-- ------------------------------
procedure Read (Stream : in out Wallet_Stream'Class;
Decipher : in out Util.Encoders.AES.Decoder;
Sign : in Secret_Key;
Decrypt_Size : out Block_Index;
Into : in out Buffers.Storage_Buffer) is
procedure Read (Data : in IO_Block_Type);
procedure Read (Data : in IO_Block_Type) is
Last : Stream_Element_Offset;
Encoded : Stream_Element_Offset;
Hash : Util.Encoders.SHA256.Hash_Array;
Last_Pos : Stream_Element_Offset;
Context : Util.Encoders.HMAC.SHA256.Context;
Size : Interfaces.Unsigned_16;
Buf : constant Buffers.Buffer_Accessor := Into.Data.Value;
begin
Size := Get_Decrypt_Size (Data);
-- Check that the decrypt size looks correct.
if Size = 0 or else Size > Data'Length or else (Size mod 16) /= 0 then
Keystore.Logs.Warn (Log, "Bloc{0} has invalid size", Into.Block);
raise Invalid_Block;
end if;
Decrypt_Size := Block_Index (Size);
Last_Pos := BT_DATA_START + Stream_Element_Offset (Decrypt_Size) - 1;
Buf.Data (Buf.Data'First .. BT_DATA_START - 1)
:= Data (Data'First .. BT_DATA_START - 1);
if Log.Get_Level >= Util.Log.INFO_LEVEL then
Log.Info ("Read block{0} decrypt {1} .. {2}",
Buffers.To_String (Into.Block),
Stream_Element_Offset'Image (BT_DATA_START),
Stream_Element_Offset'Image (Last_Pos));
end if;
-- Decrypt the Size bytes
Decipher.Transform (Data => Data (BT_DATA_START .. Last_Pos),
Into => Buf.Data (BT_DATA_START .. Last_Pos),
Last => Last,
Encoded => Encoded);
Decipher.Finish (Into => Buf.Data (Last + 1 .. Last_Pos),
Last => Last);
if Encoded - 1 /= Last_Pos or Last /= Last_Pos then
Keystore.Logs.Warn (Log, "Bloc{0} decryption failed", Into.Block);
raise Invalid_Block;
end if;
if Last_Pos < Buf.Data'Last then
Buf.Data (Last_Pos + 1 .. Buf.Data'Last) := Data (Last_Pos + 1 .. Buf.Data'Last);
end if;
Keystore.Logs.Debug (Log, "Dump block{0} before AES decrypt", Into.Block);
Keystore.Logs.Dump (Log, Data (BT_DATA_START .. BT_DATA_START + 95));
-- Keystore.Logs.Debug (Log, "...", 1);
Keystore.Logs.Dump (Log, Data (Buf.Data'Last - 100 .. Buf.Data'Last));
Keystore.Logs.Debug (Log, "Dump block{0} after AES decrypt", Into.Block);
Keystore.Logs.Dump (Log, Buf.Data (BT_DATA_START .. BT_DATA_START + 95));
-- Keystore.Logs.Debug (Log, "...", 1);
Keystore.Logs.Dump (Log, Buf.Data (Buf.Data'Last - 100 .. Buf.Data'Last));
-- Make HMAC-SHA256 signature of the block excluding the block hash mac.
Util.Encoders.HMAC.SHA256.Set_Key (Context, Sign);
Util.Encoders.HMAC.SHA256.Update (Context, Buf.Data);
Util.Encoders.HMAC.SHA256.Finish (Context, Hash);
-- Check that the block hash mac matches our hash.
if Hash /= Data (BT_HMAC_HEADER_POS .. Data'Last) then
Keystore.Logs.Warn (Log, "Block{0} HMAC-256 is invalid", Into.Block);
raise Invalid_Signature;
end if;
end Read;
begin
Stream.Read (Into.Block, Read'Access);
end Read;
-- ------------------------------
-- Write the block in the wallet IO stream. Encrypt the block data using the
-- cipher object. Sign the header and encrypted data using HMAC-256 and the
-- given signature.
-- ------------------------------
procedure Write (Stream : in out Wallet_Stream'Class;
Encrypt_Size : in Block_Index := BT_DATA_LENGTH;
Cipher : in out Util.Encoders.AES.Encoder;
Sign : in Secret_Key;
From : in out Buffers.Storage_Buffer) is
procedure Write (Data : out IO_Block_Type);
procedure Write (Data : out IO_Block_Type) is
Last : Stream_Element_Offset;
Encoded : Stream_Element_Offset;
Last_Pos : constant Stream_Element_Offset := BT_DATA_START + Encrypt_Size - 1;
Buf : constant Buffers.Buffer_Accessor := From.Data.Value;
begin
if Log.Get_Level >= Util.Log.INFO_LEVEL then
Log.Info ("Write block{0} encrypt {1} .. {2}",
Buffers.To_String (From.Block),
Stream_Element_Offset'Image (BT_DATA_START),
Stream_Element_Offset'Image (Last_Pos));
end if;
Put_Encrypt_Size (Buf.Data, Encrypt_Size);
Data (BT_HEADER_START .. BT_DATA_START - 1)
:= Buf.Data (BT_HEADER_START .. BT_DATA_START - 1);
Cipher.Transform (Data => Buf.Data (BT_DATA_START .. Last_Pos),
Into => Data (BT_DATA_START .. Last_Pos),
Last => Last,
Encoded => Encoded);
Log.Info ("Last={0} Encoded={0}",
Stream_Element_Offset'Image (Last),
Stream_Element_Offset'Image (Encoded));
if Last_Pos < Buf.Data'Last then
Data (Last_Pos + 1 .. Buf.Data'Last) := Buf.Data (Last_Pos + 1 .. Buf.Data'Last);
end if;
Keystore.Logs.Debug (Log, "Dump data block{0} before AES and write", From.Block);
Keystore.Logs.Dump (Log, Buf.Data (BT_DATA_START .. BT_DATA_START + 95));
-- Keystore.Logs.Debug (Log, "...", 1);
Keystore.Logs.Dump (Log, Buf.Data (Buf.Data'Last - 100 .. Buf.Data'Last));
Keystore.Logs.Debug (Log, "Dump data block{0} after AES and write", From.Block);
Keystore.Logs.Dump (Log, Data (BT_DATA_START .. BT_DATA_START + 95));
-- Keystore.Logs.Debug (Log, "...", 1);
Keystore.Logs.Dump (Log, Data (Buf.Data'Last - 100 .. Buf.Data'Last));
-- Make HMAC-SHA256 signature of the block excluding the block hash mac.
Util.Encoders.HMAC.SHA256.Sign (Key => Sign,
Data => Buf.Data,
Result => Data (BT_HMAC_HEADER_POS .. Data'Last));
end Write;
begin
Stream.Write (From.Block, Write'Access);
end Write;
end Keystore.IO;
|
with Memory.Trace;
separate (Parser)
procedure Parse_Trace(parser : in out Parser_Type;
result : out Memory_Pointer) is
mem : Memory_Pointer := null;
begin
if Get_Type(parser) = Open then
Parse_Memory(parser, mem);
end if;
result := Memory_Pointer(Trace.Create_Trace(mem));
end Parse_Trace;
|
package Access_To_Object is
type Access_Type_1 is access Integer;
type Access_Type_2 is access all Integer;
type Access_Type_3 is access constant Integer;
end Access_To_Object;
|
with Ada.Containers.Indefinite_Vectors;
private with Ada.Containers.Indefinite_Hashed_Maps;
generic
type Source_Type (<>) is private;
type Item_Type (<>) is private;
with function Hash(Item: Item_Type) return Ada.Containers.Hash_Type is <>;
package Generic_Inverted_Index is
type Storage_Type is tagged private;
package Source_Vecs is new Ada.Containers.Indefinite_Vectors
(Index_Type => Positive,
Element_Type => Source_Type);
procedure Store(Storage: in out Storage_Type;
Source: Source_Type;
Item: Item_Type);
-- stores Source in a table, indexed by Item
-- if there is already an Item/Source entry, the Table isn_t changed
function Find(Storage: Storage_Type; Item: Item_Type)
return Source_Vecs.Vector;
-- Generates a vector of all Sources for the given Item
function "and"(Left, Right: Source_Vecs.Vector) return Source_Vecs.Vector;
-- returns a vector of all sources, which are both in Left and in Right
function "or"(Left, Right: Source_Vecs.Vector) return Source_Vecs.Vector;
-- returns a vector of all sources, which are in Left, Right, or both
function Empty(Vec: Source_Vecs.Vector) return Boolean;
-- returns true if Vec is empty
function First_Source(The_Sources: Source_Vecs.Vector) return Source_Type;
-- returns the first enty in The_Sources; pre: The_Sourses is not empty
procedure Delete_First_Source(The_Sources: in out Source_Vecs.Vector;
Count: Ada.Containers.Count_Type := 1);
-- Removes the first Count entries; pre: The_Sourses has that many entries
type Process_Source is not null access procedure (Source: Source_Type);
generic
with procedure Do_Something(Source: Source_Type);
procedure Iterate(The_Sources: Source_Vecs.Vector);
-- calls Do_Something(Source) for all sources in The_Sources;
private
function Same_Vector(U,V: Source_Vecs.Vector) return Boolean;
package Maps is new Ada.Containers.Indefinite_Hashed_Maps
-- for each item (=key) we store a vector with sources
(Key_Type => Item_Type,
Element_Type => Source_Vecs.Vector,
Hash => Hash,
Equivalent_Keys => "=",
"=" => Same_Vector);
type Storage_Type is new Maps.Map with null record;
end Generic_Inverted_Index;
|
-- Copyright (c) 2019 Maxim Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-- License-Filename: LICENSE
-------------------------------------------------------------
with League.Text_Codecs;
with Slim.Message_Visiters;
package body Slim.Messages.META is
----------
-- Read --
----------
overriding function Read
(Data : not null access League.Stream_Element_Vectors
.Stream_Element_Vector) return META_Message
is
Value : constant Ada.Streams.Stream_Element_Array :=
Data.To_Stream_Element_Array;
Last : Ada.Streams.Stream_Element_Offset := 0;
begin
for J in reverse Value'Range loop
if Value (J) not in 0 then
Last := J;
exit;
end if;
end loop;
return Result : META_Message do
Result.Value := League.Text_Codecs.Codec_For_Application_Locale.Decode
(Value (Value'First .. Last));
end return;
end Read;
-----------
-- Value --
-----------
not overriding function Value (Self : META_Message)
return League.Strings.Universal_String is
begin
return Self.Value;
end Value;
-----------
-- Visit --
-----------
overriding procedure Visit
(Self : not null access META_Message;
Visiter : in out Slim.Message_Visiters.Visiter'Class) is
begin
Visiter.META (Self);
end Visit;
-----------
-- Write --
-----------
overriding procedure Write
(Self : META_Message;
Tag : out Message_Tag;
Data : out League.Stream_Element_Vectors.Stream_Element_Vector) is
begin
Tag := "META";
Data := League.Text_Codecs.Codec_For_Application_Locale.Encode
(Self.Value);
end Write;
end Slim.Messages.META;
|
with STM32GD.Systick; use STM32GD.Systick;
with STM32GD.Vectors;
with STM32_SVD; use STM32_SVD;
package body Monotonic_Counter is
procedure SysTick_Handler;
pragma Machine_Attribute (SysTick_Handler, "naked");
Vectors: STM32GD.Vectors.IRQ_Vectors := (
SysTick_Handler => Monotonic_Counter.SysTick_Handler'Address,
others => STM32GD.Vectors.Default_Handler'Address
) with Export;
pragma Linker_Section (Vectors, ".vectors");
procedure SysTick_Handler is
begin
Counter := Counter + 1;
if Counter = 0 then
Overflow := True;
end if;
end SysTick_Handler;
procedure Reset is
begin
Counter := 0;
Overflow := False;
Systick_Periph.RVR := (
RELOAD => 8_000_000 / 8_000);
Systick_Periph.CSR := (
ENABLE => 1,
TICKINT => 1,
CLKSOURCE => 1,
COUNTFLAG => 0,
Reserved_3_15 => 0,
Reserved_17_31 => 0);
end Reset;
end Monotonic_Counter;
|
-- Based on libgasandbox.draw.h and draw.cpp
with Ada.Text_IO; use Ada.Text_IO;
with GL;
with GL.Attributes;
with GL.Objects.Buffers;
with GL.Objects.Vertex_Arrays;
with GL.Rasterization;
with GL.Types; use GL.Types;
with Utilities;
with Maths;
with GA_Utilities;
with Palet;
with Shader_Manager;
package body Plane is
type Surface_Type is (Back_Surface, Front_Surface);
-- ------------------------------------------------------------------------
procedure Add_To_Array (theArray : in out Singles.Vector3_Array;
Current_Index : Int;
Addition : Singles.Vector3_Array) is
begin
for index in Int range 1 .. 6 loop
theArray (Current_Index + index) := Addition (index);
end loop;
end Add_To_Array;
-- ------------------------------------------------------------------------
function Build_Quad_Vertices (Bottom_Left : Singles.Vector3;
Step_Size : Single)
return Singles.Vector3_Array is
X : constant Single := Bottom_Left (GL.X);
Y : constant Single := Bottom_Left (GL.Y);
Z : constant Single := Bottom_Left (GL.Z);
Quad_Vertices : constant Singles.Vector3_Array (1 .. 6) :=
(Bottom_Left,
(X, Y + Step_Size, Z),
(X + Step_Size, Y + Step_Size, Z),
(Bottom_Left),
(X + Step_Size, Y, Z),
(X + Step_Size, Y + Step_Size, Z));
begin
return Quad_Vertices;
end Build_Quad_Vertices;
-- ------------------------------------------------------------------------
procedure Display_Plane
(Vertex_Buffer, Normals_Buffer : GL.Objects.Buffers.Buffer;
Num_Vertices : Int) is
begin
GL.Attributes.Enable_Vertex_Attrib_Array (0);
GL.Objects.Buffers.Array_Buffer.Bind (Vertex_Buffer);
GL.Attributes.Set_Vertex_Attrib_Pointer (0, 3, Single_Type, False, 0, 0);
GL.Attributes.Enable_Vertex_Attrib_Array (1);
GL.Objects.Buffers.Array_Buffer.Bind (Normals_Buffer);
GL.Attributes.Set_Vertex_Attrib_Pointer (1, 3, Single_Type, False, 0, 0);
GL.Objects.Vertex_Arrays.Draw_Arrays (Mode => Triangle_Strip,
First => 0,
Count => Num_Vertices);
GL.Attributes.Disable_Vertex_Attrib_Array (0);
GL.Attributes.Disable_Vertex_Attrib_Array (1);
exception
when others =>
Put_Line ("An exception occurred in Plane.Display_Plane.");
raise;
end Display_Plane;
-- ------------------------------------------------------------------------
procedure Draw_Plane (Render_Program : GL.Objects.Programs.Program;
Point,
X_Dir, Y_Dir, Normal : C3GA.Vector_E3;
Weight : Float := 1.0) is
-- Attitude: Normal is perpendicular to plane of Ortho_1 and Ortho_2.
use GL.Objects.Buffers;
use Palet;
use Singles;
Vertex_Array : GL.Objects.Vertex_Arrays.Vertex_Array_Object;
Vertex_Buffer : GL.Objects.Buffers.Buffer;
Normals_Buffer : GL.Objects.Buffers.Buffer;
Model_Matrix : Matrix4 := Identity4;
Plane_Size : constant Single := Single (Palet.Get_Plane_Size); -- 6.0
Scale_Magnitude : constant Single := Single (Weight);
Step_Size : constant Single := 0.1;
Scaled_Step_Size : constant Single := Step_Size * Plane_Size;
Num_Vertices : constant Int :=
Int (2.0 * Plane_Size / Step_Size);
Scale_Matrix : constant Matrix4 := Maths.Scaling_Matrix
((Scale_Magnitude, Scale_Magnitude, Scale_Magnitude));
V_Index : Int := 0;
Vertices : Vector3_Array (1 .. Num_Vertices) :=
(others => (others => 0.0));
Normals : Vector3_Array (1 .. Num_Vertices) :=
(others => (others => 0.0));
X : Single;
Y : Single;
YY_Dir : Vector3;
QY : Vector3;
Quad_Vertices : Singles.Vector3_Array (1 .. 6);
Quad_Normals : Singles.Vector3_Array (1 .. 6);
begin
Vertex_Array.Initialize_Id;
Vertex_Array.Bind;
GL.Objects.Programs.Use_Program (Render_Program);
if Palet.Get_Draw_Mode.Magnitude then
Model_Matrix := Scale_Matrix * Model_Matrix;
end if;
Shader_Manager.Set_Model_Matrix (Model_Matrix);
GA_Utilities.Print_E3_Vector ("Plane.Draw_Plane Point", Point);
GA_Utilities.Print_E3_Vector ("Plane.Draw_Plane X_Dir", X_Dir);
GA_Utilities.Print_E3_Vector ("Plane.Draw_Plane Y_Dir", Y_Dir);
-- draw both front and back side individually
for Surface in Surface_Type'Range loop
if Wireframe or (Surface = Back_Surface and Palet.Orientation) then
GL.Rasterization.Set_Polygon_Mode (GL.Rasterization.Line);
else
GL.Rasterization.Set_Polygon_Mode (GL.Rasterization.Fill);
end if;
Y := -Plane_Size;
while Y < Plane_Size - Scaled_Step_Size loop
V_Index := 0;
YY_Dir := Y * Y_Dir;
X := -Plane_Size;
-- for each Y value draw a triangle strip (rectangle) of
-- "length" 2 Plane_Size and "height" YY_Dir
-- The "length" in Scaled_Step_Size ^ 2 quad increments
-- with each quad drawn as 2 triangles
-- X_Dir and Y_Dir are orthogonal
while X < Plane_Size - Scaled_Step_Size loop
if Surface = Front_Surface then
QY := YY_Dir;
else
QY := Scaled_Step_Size * YY_Dir;
end if;
Quad_Vertices := Build_Quad_Vertices
((Point - X * X_Dir + QY), Scaled_Step_Size);
Add_To_Array (Vertices, V_Index, Quad_Vertices);
if Palet.Get_Draw_Mode.Magnitude then
Quad_Normals := Build_Quad_Vertices
(Point + X * Normal + YY_Dir, Scaled_Step_Size);
Add_To_Array (Normals, V_Index, Quad_Normals);
end if;
X := X + Scaled_Step_Size;
V_Index := V_Index + 6;
end loop;
if Surface = Back_Surface then
for n in Int range 1 .. Num_Vertices loop
Normals (n) := -Normals (n);
end loop;
end if;
Vertex_Buffer.Initialize_Id;
Array_Buffer.Bind (Vertex_Buffer);
Utilities.Load_Vertex_Buffer (Array_Buffer, Vertices, Static_Draw);
-- if Palet.Get_Draw_Mode.Magnitude then -- draw normals
-- -- ??? GL.Rasterization.Set_Polygon_Mode (GL.Rasterization.Fill);
Normals_Buffer.Initialize_Id;
Array_Buffer.Bind (Normals_Buffer);
Utilities.Load_Vertex_Buffer (Array_Buffer, Normals,
Static_Draw);
-- end if;
Display_Plane (Vertex_Buffer, Normals_Buffer, Num_Vertices);
Y := Y + Scaled_Step_Size;
end loop;
end loop;
exception
when others =>
Put_Line ("An exception occurred in Plane.Draw_Plane.");
raise;
end Draw_Plane;
-- ------------------------------------------------------------------------
end Plane;
|
with Gtk.Button; use Gtk.Button;
with Gtk.Main;
package body button_click is
procedure button_clicked (Self : access Gtk_Button_Record'Class) is
begin
Gtk.Main.Main_Quit;
end button_clicked;
end button_click;
|
with Ada.Text_IO;
use Ada.Text_IO;
with Interfaces;
package Memory is
type Address is range 0 .. 2 ** 63 - 1;
type Value is new Interfaces.Integer_64;
type Block is array(Address range <>) of Value;
function Read_Comma_Separated(
From: File_Type := Standard_Input) return Block;
end Memory;
|
-- C43212A.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 CONSTRAINT_ERROR IS RAISED IF ALL SUBAGGREGATES FOR A
-- PARTICULAR DIMENSION DO NOT HAVE THE SAME BOUNDS.
-- EG 02/06/1984
-- JBG 3/30/84
-- JRK 4/18/86 CORRECTED ERROR TO ALLOW CONSTRAINT_ERROR TO BE
-- RAISED EARLIER.
-- EDS 7/15/98 AVOID OPTIMIZATION.
WITH REPORT;
PROCEDURE C43212A IS
USE REPORT;
BEGIN
TEST ("C43212A", "CHECK THAT CONSTRAINT_ERROR IS RAISED IF ALL " &
"SUBAGGREGATES FOR A PARTICULAR DIMENSION DO " &
"NOT HAVE THE SAME BOUNDS");
DECLARE
TYPE CHOICE_INDEX IS (H, I);
TYPE CHOICE_CNTR IS ARRAY(CHOICE_INDEX) OF INTEGER;
CNTR : CHOICE_CNTR := (CHOICE_INDEX => 0);
FUNCTION CALC (A : CHOICE_INDEX; B : INTEGER)
RETURN INTEGER IS
BEGIN
CNTR(A) := CNTR(A) + 1;
RETURN IDENT_INT(B);
END CALC;
BEGIN
CASE_1 : DECLARE
TYPE T IS ARRAY(INTEGER RANGE <>, INTEGER RANGE <>)
OF INTEGER;
A1 : T(1 .. 3, 2 .. 5) := (OTHERS => (OTHERS => 0));
BEGIN
CNTR := (CHOICE_INDEX => 0);
A1 := (1 => (CALC(H,2) .. CALC(I,5) => -4),
2 => (CALC(H,3) .. CALC(I,6) => -5),
3 => (CALC(H,2) .. CALC(I,5) => -3));
FAILED ("CASE 1 : CONSTRAINT_ERROR NOT RAISED" &
INTEGER'IMAGE(A1(1,5)) );
EXCEPTION
WHEN CONSTRAINT_ERROR =>
IF CNTR(H) < 2 AND CNTR(I) < 2 THEN
FAILED ("CASE 1 : BOUNDS OF SUBAGGREGATES " &
"NOT DETERMINED INDEPENDENTLY");
END IF;
WHEN OTHERS =>
FAILED ("CASE 1 : WRONG EXCEPTION RAISED");
END CASE_1;
CASE_1A : DECLARE
TYPE T IS ARRAY(INTEGER RANGE <>, INTEGER RANGE <>)
OF INTEGER;
A1 : T(1 .. 3, 2 .. 3) := (1 .. 3 => (2 .. 3 => 1));
BEGIN
IF (1 .. 2 => (IDENT_INT(3) .. IDENT_INT(4) => 0),
3 => (1, 2)) = A1 THEN
BEGIN
COMMENT(" IF SHOULD GENERATE CONSTRAINT_ERROR " &
INTEGER'IMAGE(A1(1,2)) );
EXCEPTION
WHEN OTHERS =>
FAILED ("CASE 1A : CONSTRAINT_ERROR NOT RAISED");
END;
END IF;
FAILED ("CASE 1A : CONSTRAINT_ERROR NOT RAISED");
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ("CASE 1A : WRONG EXCEPTION RAISED");
END CASE_1A;
CASE_2 : DECLARE
TYPE T IS ARRAY(INTEGER RANGE <>, INTEGER RANGE <>)
OF INTEGER;
A2 : T(1 .. 3, IDENT_INT(4) .. 2);
BEGIN
CNTR := (CHOICE_INDEX => 0);
A2 := (1 => (CALC(H,5) .. CALC(I,3) => -4),
3 => (CALC(H,4) .. CALC(I,2) => -5),
2 => (CALC(H,4) .. CALC(I,2) => -3));
FAILED ("CASE 2 : CONSTRAINT_ERROR NOT RAISED " &
INTEGER'IMAGE(IDENT_INT(A2'FIRST(1))));
EXCEPTION
WHEN CONSTRAINT_ERROR =>
IF CNTR(H) < 2 AND CNTR(I) < 2 THEN
FAILED ("CASE 2 : BOUNDS OF SUBAGGREGATES " &
"NOT DETERMINED INDEPENDENTLY");
END IF;
WHEN OTHERS =>
FAILED ("CASE 2 : WRONG EXCEPTION RAISED");
END CASE_2;
END;
RESULT;
END C43212A;
|
package body Kafka.Config is
Error_Buffer_Size : constant size_t := 512;
RD_Kafka_Conf_OK : constant Integer := 0;
procedure Set(Config : Config_Type;
Name : String;
Value : String) is
C_Name : chars_ptr := New_String(Name);
C_Value : chars_ptr := New_String(Value);
C_Err : chars_ptr := Alloc(Error_Buffer_Size);
Result : Integer;
begin
Result := rd_kafka_conf_set(Config, C_Name, C_Value, C_Err, Error_Buffer_Size);
if Result /= RD_Kafka_Conf_OK then
declare
Error : String := Interfaces.C.Strings.Value(C_Err);
begin
Free(C_Name);
Free(C_Value);
Free(C_Err);
raise Kafka_Error with Error;
end;
end if;
Free(C_Name);
Free(C_Value);
Free(C_Err);
end Set;
end Kafka.Config;
|
-- Abstract :
--
-- Type and operations for graphs.
--
-- References:
--
-- [1] Introduction to Algorithms, Thomas H. Cormen, Charles E.
-- Leiserson, Ronald L. Rivest, Clifford Stein.
--
-- [2] "An Efficient Search Algorithm to Find the Elementary Circuits
-- of a Graph", James C. Tiernan, Communications of the ACM Volume 13
-- Number 12 December 1970.
-- https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.516.9454&rep=rep1&type=pdf
--
-- [3] "Finding all the Elementary Circuits of a Directed Graph",
-- Donald B. Johnson, SIAM J. Comput. Vol 4, No. 1, March 1975.
-- https://epubs.siam.org/doi/abs/10.1137/0204007
--
-- [4] "Depth-First Search and Linear Graph Algorithms", Robert
-- Tarjan, SIAM J. Comput. Vol. 1, No 2, June 1972.
-- https://epubs.siam.org/doi/abs/10.1137/0201010
--
-- Copyright (C) 2017, 2019, 2020 Free Software Foundation All Rights Reserved.
--
-- This library is free software; you can redistribute it and/or modify it
-- under terms of the GNU General Public License as published by the Free
-- Software Foundation; either version 3, or (at your option) any later
-- version. This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN-
-- TABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-- As a special exception under Section 7 of GPL version 3, you are granted
-- additional permissions described in the GCC Runtime Library Exception,
-- version 3.1, as published by the Free Software Foundation.
pragma License (Modified_GPL);
with Ada.Containers.Doubly_Linked_Lists;
with Ada.Containers.Indefinite_Vectors;
with SAL.Ada_Containers.Gen_Doubly_Linked_Lists_Image;
with SAL.Gen_Trimmed_Image;
with SAL.Gen_Unbounded_Definite_Vectors;
generic
type Edge_Data is private;
Default_Edge_Data : in Edge_Data;
type Vertex_Index is range <>;
Invalid_Vertex : in Vertex_Index'Base;
type Path_Index is range <>;
with function Edge_Image (Item : in Edge_Data) return String;
package SAL.Gen_Graphs is
type Graph is tagged private;
procedure Add_Edge
(Graph : in out Gen_Graphs.Graph;
Vertex_A : in Vertex_Index;
Vertex_B : in Vertex_Index;
Data : in Edge_Data);
-- Adds a directed edge from Vertex_A to Vertex_B.
function Count_Nodes (Graph : in Gen_Graphs.Graph) return Ada.Containers.Count_Type;
function Count_Edges (Graph : in Gen_Graphs.Graph) return Ada.Containers.Count_Type;
function Multigraph (Graph : in Gen_Graphs.Graph) return Boolean;
-- If more than one edge is added between two vertices, the graph is
-- a multigraph. The edges are given separate identifiers internally.
Multigraph_Error : exception;
type Base_Edge_ID is range 0 .. Integer'Last;
subtype Edge_ID is Base_Edge_ID range 1 .. Base_Edge_ID'Last;
Invalid_Edge_ID : constant Base_Edge_ID := 0;
-- Edge ids are unique graph-wide, assigned by Add_Edge.
type Edge_Item is record
ID : Base_Edge_ID := Invalid_Edge_ID;
Data : Edge_Data := Default_Edge_Data;
end record;
function Image (Item : in Edge_Item) return String
is (Edge_Image (Item.Data));
package Edge_Lists is new Ada.Containers.Doubly_Linked_Lists (Edge_Item);
function "+" (Right : in Edge_Item) return Edge_Lists.List;
function Edges (Graph : in Gen_Graphs.Graph; Vertex : in Vertex_Index) return Edge_Lists.List;
-- All edges from Vertex, as set by Add_Edge.
function Image is new SAL.Ada_Containers.Gen_Doubly_Linked_Lists_Image
(Element_Type => Edge_Item,
Lists => Edge_Lists,
Element_Image => Image);
type Path_Item is record
Vertex : Vertex_Index'Base := Invalid_Vertex;
Edges : Edge_Lists.List;
-- Edges describe the edges leading from the previous vertex
-- in the path to Vertex. If this is the first vertex in an open
-- path, Edges is empty. If it is the first vertex in a
-- cycle, the edge are from the last vertex in the cycle.
end record;
type Path is array (Positive range <>) of Path_Item;
function Image (Item : in Path) return String;
-- For trace, debugging.
package Path_Arrays is new Ada.Containers.Indefinite_Vectors (Path_Index, Path);
function "<" (Left, Right : in Path) return Boolean;
package Sort_Paths is new Path_Arrays.Generic_Sorting;
function Find_Paths
(Graph : in out Gen_Graphs.Graph;
From : in Vertex_Index;
To : in Edge_Data)
return Path_Arrays.Vector;
-- Return all non-cyclic paths starting at From that lead to a To
-- edge, using algorithm [1]. First entry in each item in result is
-- From, with first edge. Last entry in result contains edge data for
-- To.
--
-- Raises Multigraph_Error if Graph is a multigraph.
function Find_Cycles_Tiernan (Graph : in Gen_Graphs.Graph) return Path_Arrays.Vector;
-- Return all cyclic paths in Graph, using algorithm [2] extended for
-- multigraphs.
--
-- Time complexity is exponential in the number of nodes. Used in
-- unit tests for Find_Cycles, since [2] is easier to
-- implement.
function Find_Cycles (Graph : in Gen_Graphs.Graph) return Path_Arrays.Vector;
-- Return all cyclic paths in Graph, using algorithm [3] extended for
-- multigraphs.
--
-- Time complexity is linear in the number of nodes and edges.
package Vertex_Lists is new Ada.Containers.Doubly_Linked_Lists (Vertex_Index);
function Trimmed_Image is new SAL.Gen_Trimmed_Image (Vertex_Index);
function Image is new SAL.Ada_Containers.Gen_Doubly_Linked_Lists_Image
(Vertex_Index, "=", Vertex_Lists, Trimmed_Image);
function Loops (Graph : in Gen_Graphs.Graph) return Vertex_Lists.List;
-- List of vertices that have an edge to themselves.
package Adjacency_Structures is new SAL.Gen_Unbounded_Definite_Vectors
(Vertex_Index, Vertex_Lists.List, Vertex_Lists.Empty_List);
-- Graphs with no Edge_ID or Edge_Data; useful as intermediate results.
function To_Adjancency (Graph : in Gen_Graphs.Graph) return Adjacency_Structures.Vector;
package Component_Lists is new Ada.Containers.Doubly_Linked_Lists (Vertex_Lists.List, Vertex_Lists."=");
function Strongly_Connected_Components
(Graph : in Adjacency_Structures.Vector;
Non_Trivial_Only : in Boolean := False)
return Component_Lists.List;
-- Find strongly connected components of Graph, using algorithm in [4].
-- If Non_Trivial_Only, don't include single-vertex components.
Trace : Integer := 0;
-- Some bodies output debug info to Text_IO.Current_Output for
-- non-zero values of Trace.
private
type Edge_Node is record
-- Edge is from vertex contaning this Node to Vertex_B
ID : Edge_ID;
Vertex_B : Vertex_Index;
Multigraph : Boolean; -- Same Vertex_B as another edge in same vertex.
Data : Edge_Data;
end record;
package Edge_Node_Lists is new Ada.Containers.Doubly_Linked_Lists (Edge_Node);
package Vertex_Arrays is new SAL.Gen_Unbounded_Definite_Vectors
(Vertex_Index, Edge_Node_Lists.List, Edge_Node_Lists.Empty_List);
type Graph is tagged record
Last_Edge_ID : Base_Edge_ID := Invalid_Edge_ID;
Multigraph : Boolean := False;
Vertices : Vertex_Arrays.Vector;
end record;
end SAL.Gen_Graphs;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- E X P _ A T A G --
-- --
-- S p e c --
-- --
-- Copyright (C) 2006-2020, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING3. If not, go to --
-- http://www.gnu.org/licenses for a complete copy of the license. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Atree; use Atree;
with Einfo; use Einfo;
with Elists; use Elists;
with Exp_Disp; use Exp_Disp;
with Namet; use Namet;
with Nlists; use Nlists;
with Nmake; use Nmake;
with Opt; use Opt;
with Rtsfind; use Rtsfind;
with Sinfo; use Sinfo;
with Sem_Aux; use Sem_Aux;
with Sem_Disp; use Sem_Disp;
with Sem_Util; use Sem_Util;
with Stand; use Stand;
with Snames; use Snames;
with Tbuild; use Tbuild;
package body Exp_Atag is
-----------------------
-- Local Subprograms --
-----------------------
function Build_DT
(Loc : Source_Ptr;
Tag_Node : Node_Id) return Node_Id;
-- Build code that displaces the Tag to reference the base of the wrapper
-- record
--
-- Generates:
-- To_Dispatch_Table_Ptr
-- (To_Address (Tag_Node) - Tag_Node.Prims_Ptr'Position);
function Build_Range (Loc : Source_Ptr; Lo, Hi : Nat) return Node_Id;
-- Build an N_Range node for [Lo; Hi] with Standard.Natural type
function Build_TSD
(Loc : Source_Ptr;
Tag_Node_Addr : Node_Id) return Node_Id;
-- Build code that retrieves the address of the record containing the Type
-- Specific Data generated by GNAT.
--
-- Generate: To_Type_Specific_Data_Ptr
-- (To_Addr_Ptr (Tag_Node_Addr - Typeinfo_Offset).all);
function Build_Val (Loc : Source_Ptr; V : Uint) return Node_Id;
-- Build an N_Integer_Literal node for V with Standard.Natural type
------------------------------------------------
-- Build_Common_Dispatching_Select_Statements --
------------------------------------------------
procedure Build_Common_Dispatching_Select_Statements
(Typ : Entity_Id;
Stmts : List_Id)
is
Loc : constant Source_Ptr := Sloc (Typ);
Tag_Node : Node_Id;
begin
-- Generate:
-- C := get_prim_op_kind (tag! (<type>VP), S);
-- where C is the out parameter capturing the call kind and S is the
-- dispatch table slot number.
if Tagged_Type_Expansion then
Tag_Node :=
Unchecked_Convert_To (RTE (RE_Tag),
New_Occurrence_Of
(Node (First_Elmt (Access_Disp_Table (Typ))), Loc));
else
Tag_Node :=
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Typ, Loc),
Attribute_Name => Name_Tag);
end if;
Append_To (Stmts,
Make_Assignment_Statement (Loc,
Name => Make_Identifier (Loc, Name_uC),
Expression =>
Make_Function_Call (Loc,
Name =>
New_Occurrence_Of (RTE (RE_Get_Prim_Op_Kind), Loc),
Parameter_Associations => New_List (
Tag_Node,
Make_Identifier (Loc, Name_uS)))));
-- Generate:
-- if C = POK_Procedure
-- or else C = POK_Protected_Procedure
-- or else C = POK_Task_Procedure;
-- then
-- F := True;
-- return;
-- where F is the out parameter capturing the status of a potential
-- entry call.
Append_To (Stmts,
Make_If_Statement (Loc,
Condition =>
Make_Or_Else (Loc,
Left_Opnd =>
Make_Op_Eq (Loc,
Left_Opnd => Make_Identifier (Loc, Name_uC),
Right_Opnd =>
New_Occurrence_Of (RTE (RE_POK_Procedure), Loc)),
Right_Opnd =>
Make_Or_Else (Loc,
Left_Opnd =>
Make_Op_Eq (Loc,
Left_Opnd => Make_Identifier (Loc, Name_uC),
Right_Opnd =>
New_Occurrence_Of
(RTE (RE_POK_Protected_Procedure), Loc)),
Right_Opnd =>
Make_Op_Eq (Loc,
Left_Opnd => Make_Identifier (Loc, Name_uC),
Right_Opnd =>
New_Occurrence_Of
(RTE (RE_POK_Task_Procedure), Loc)))),
Then_Statements =>
New_List (
Make_Assignment_Statement (Loc,
Name => Make_Identifier (Loc, Name_uF),
Expression => New_Occurrence_Of (Standard_True, Loc)),
Make_Simple_Return_Statement (Loc))));
end Build_Common_Dispatching_Select_Statements;
--------------
-- Build_DT --
--------------
function Build_DT
(Loc : Source_Ptr;
Tag_Node : Node_Id) return Node_Id
is
begin
return
Make_Function_Call (Loc,
Name => New_Occurrence_Of (RTE (RE_DT), Loc),
Parameter_Associations => New_List (
Unchecked_Convert_To (RTE (RE_Tag), Tag_Node)));
end Build_DT;
----------------------------
-- Build_Get_Access_Level --
----------------------------
function Build_Get_Access_Level
(Loc : Source_Ptr;
Tag_Node : Node_Id) return Node_Id
is
begin
return
Make_Selected_Component (Loc,
Prefix =>
Make_Explicit_Dereference (Loc,
Build_TSD (Loc,
Unchecked_Convert_To (RTE (RE_Address), Tag_Node))),
Selector_Name =>
New_Occurrence_Of
(RTE_Record_Component (RE_Access_Level), Loc));
end Build_Get_Access_Level;
-------------------------
-- Build_Get_Alignment --
-------------------------
function Build_Get_Alignment
(Loc : Source_Ptr;
Tag_Node : Node_Id) return Node_Id
is
begin
return
Make_Selected_Component (Loc,
Prefix =>
Make_Explicit_Dereference (Loc,
Build_TSD (Loc,
Unchecked_Convert_To (RTE (RE_Address), Tag_Node))),
Selector_Name =>
New_Occurrence_Of (RTE_Record_Component (RE_Alignment), Loc));
end Build_Get_Alignment;
------------------------------------------
-- Build_Get_Predefined_Prim_Op_Address --
------------------------------------------
procedure Build_Get_Predefined_Prim_Op_Address
(Loc : Source_Ptr;
Position : Uint;
Tag_Node : in out Node_Id;
New_Node : out Node_Id)
is
Ctrl_Tag : Node_Id;
begin
Ctrl_Tag := Unchecked_Convert_To (RTE (RE_Address), Tag_Node);
-- Unchecked_Convert_To relocates the controlling tag node and therefore
-- we must update it.
Tag_Node := Expression (Ctrl_Tag);
-- Build code that retrieves the address of the dispatch table
-- containing the predefined Ada primitives:
--
-- Generate:
-- To_Predef_Prims_Table_Ptr
-- (To_Addr_Ptr (To_Address (Tag) - Predef_Prims_Offset).all);
New_Node :=
Make_Indexed_Component (Loc,
Prefix =>
Unchecked_Convert_To (RTE (RE_Predef_Prims_Table_Ptr),
Make_Explicit_Dereference (Loc,
Unchecked_Convert_To (RTE (RE_Addr_Ptr),
Make_Function_Call (Loc,
Name =>
Make_Expanded_Name (Loc,
Chars => Name_Op_Subtract,
Prefix =>
New_Occurrence_Of
(RTU_Entity (System_Storage_Elements), Loc),
Selector_Name =>
Make_Identifier (Loc, Name_Op_Subtract)),
Parameter_Associations => New_List (
Ctrl_Tag,
New_Occurrence_Of
(RTE (RE_DT_Predef_Prims_Offset), Loc)))))),
Expressions =>
New_List (Build_Val (Loc, Position)));
end Build_Get_Predefined_Prim_Op_Address;
-----------------------------
-- Build_Inherit_CPP_Prims --
-----------------------------
function Build_Inherit_CPP_Prims (Typ : Entity_Id) return List_Id is
Loc : constant Source_Ptr := Sloc (Typ);
CPP_Nb_Prims : constant Nat := CPP_Num_Prims (Typ);
CPP_Table : array (1 .. CPP_Nb_Prims) of Boolean := (others => False);
CPP_Typ : constant Entity_Id := Enclosing_CPP_Parent (Typ);
Result : constant List_Id := New_List;
Parent_Typ : constant Entity_Id := Etype (Typ);
E : Entity_Id;
Elmt : Elmt_Id;
Parent_Tag : Entity_Id;
Prim : Entity_Id;
Prim_Pos : Nat;
Typ_Tag : Entity_Id;
begin
pragma Assert (not Is_CPP_Class (Typ));
-- No code needed if this type has no primitives inherited from C++
if CPP_Nb_Prims = 0 then
return Result;
end if;
-- Stage 1: Inherit and override C++ slots of the primary dispatch table
-- Generate:
-- Typ'Tag (Prim_Pos) := Prim'Unrestricted_Access;
Parent_Tag := Node (First_Elmt (Access_Disp_Table (Parent_Typ)));
Typ_Tag := Node (First_Elmt (Access_Disp_Table (Typ)));
Elmt := First_Elmt (Primitive_Operations (Typ));
while Present (Elmt) loop
Prim := Node (Elmt);
E := Ultimate_Alias (Prim);
Prim_Pos := UI_To_Int (DT_Position (E));
-- Skip predefined, abstract, and eliminated primitives. Skip also
-- primitives not located in the C++ part of the dispatch table.
if not Is_Predefined_Dispatching_Operation (Prim)
and then not Is_Predefined_Dispatching_Operation (E)
and then not Present (Interface_Alias (Prim))
and then not Is_Abstract_Subprogram (E)
and then not Is_Eliminated (E)
and then Prim_Pos <= CPP_Nb_Prims
and then Find_Dispatching_Type (E) = Typ
then
-- Remember that this slot is used
pragma Assert (CPP_Table (Prim_Pos) = False);
CPP_Table (Prim_Pos) := True;
Append_To (Result,
Make_Assignment_Statement (Loc,
Name =>
Make_Indexed_Component (Loc,
Prefix =>
Make_Explicit_Dereference (Loc,
Unchecked_Convert_To
(Node (Last_Elmt (Access_Disp_Table (Typ))),
New_Occurrence_Of (Typ_Tag, Loc))),
Expressions =>
New_List (Build_Val (Loc, UI_From_Int (Prim_Pos)))),
Expression =>
Unchecked_Convert_To (RTE (RE_Prim_Ptr),
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (E, Loc),
Attribute_Name => Name_Unrestricted_Access))));
end if;
Next_Elmt (Elmt);
end loop;
-- If all primitives have been overridden then there is no need to copy
-- from Typ's parent its dispatch table. Otherwise, if some primitive is
-- inherited from the parent we copy only the C++ part of the dispatch
-- table from the parent before the assignments that initialize the
-- overridden primitives.
-- Generate:
-- type CPP_TypG is array (1 .. CPP_Nb_Prims) ofd Prim_Ptr;
-- type CPP_TypH is access CPP_TypG;
-- CPP_TypG!(Typ_Tag).all := CPP_TypG!(Parent_Tag).all;
-- Note: There is no need to duplicate the declarations of CPP_TypG and
-- CPP_TypH because, for expansion of dispatching calls, these
-- entities are stored in the last elements of Access_Disp_Table.
for J in CPP_Table'Range loop
if not CPP_Table (J) then
Prepend_To (Result,
Make_Assignment_Statement (Loc,
Name =>
Make_Explicit_Dereference (Loc,
Unchecked_Convert_To
(Node (Last_Elmt (Access_Disp_Table (CPP_Typ))),
New_Occurrence_Of (Typ_Tag, Loc))),
Expression =>
Make_Explicit_Dereference (Loc,
Unchecked_Convert_To
(Node (Last_Elmt (Access_Disp_Table (CPP_Typ))),
New_Occurrence_Of (Parent_Tag, Loc)))));
exit;
end if;
end loop;
-- Stage 2: Inherit and override C++ slots of secondary dispatch tables
declare
Iface : Entity_Id;
Iface_Nb_Prims : Nat;
Parent_Ifaces_List : Elist_Id;
Parent_Ifaces_Comp_List : Elist_Id;
Parent_Ifaces_Tag_List : Elist_Id;
Parent_Iface_Tag_Elmt : Elmt_Id;
Typ_Ifaces_List : Elist_Id;
Typ_Ifaces_Comp_List : Elist_Id;
Typ_Ifaces_Tag_List : Elist_Id;
Typ_Iface_Tag_Elmt : Elmt_Id;
begin
Collect_Interfaces_Info
(T => Parent_Typ,
Ifaces_List => Parent_Ifaces_List,
Components_List => Parent_Ifaces_Comp_List,
Tags_List => Parent_Ifaces_Tag_List);
Collect_Interfaces_Info
(T => Typ,
Ifaces_List => Typ_Ifaces_List,
Components_List => Typ_Ifaces_Comp_List,
Tags_List => Typ_Ifaces_Tag_List);
Parent_Iface_Tag_Elmt := First_Elmt (Parent_Ifaces_Tag_List);
Typ_Iface_Tag_Elmt := First_Elmt (Typ_Ifaces_Tag_List);
while Present (Parent_Iface_Tag_Elmt) loop
Parent_Tag := Node (Parent_Iface_Tag_Elmt);
Typ_Tag := Node (Typ_Iface_Tag_Elmt);
pragma Assert
(Related_Type (Parent_Tag) = Related_Type (Typ_Tag));
Iface := Related_Type (Parent_Tag);
Iface_Nb_Prims :=
UI_To_Int (DT_Entry_Count (First_Tag_Component (Iface)));
if Iface_Nb_Prims > 0 then
-- Update slots of overridden primitives
declare
Last_Nod : constant Node_Id := Last (Result);
Nb_Prims : constant Nat := UI_To_Int
(DT_Entry_Count
(First_Tag_Component (Iface)));
Elmt : Elmt_Id;
Prim : Entity_Id;
E : Entity_Id;
Prim_Pos : Nat;
Prims_Table : array (1 .. Nb_Prims) of Boolean;
begin
Prims_Table := (others => False);
Elmt := First_Elmt (Primitive_Operations (Typ));
while Present (Elmt) loop
Prim := Node (Elmt);
E := Ultimate_Alias (Prim);
if not Is_Predefined_Dispatching_Operation (Prim)
and then Present (Interface_Alias (Prim))
and then Find_Dispatching_Type (Interface_Alias (Prim))
= Iface
and then not Is_Abstract_Subprogram (E)
and then not Is_Eliminated (E)
and then Find_Dispatching_Type (E) = Typ
then
Prim_Pos := UI_To_Int (DT_Position (Prim));
-- Remember that this slot is already initialized
pragma Assert (Prims_Table (Prim_Pos) = False);
Prims_Table (Prim_Pos) := True;
Append_To (Result,
Make_Assignment_Statement (Loc,
Name =>
Make_Indexed_Component (Loc,
Prefix =>
Make_Explicit_Dereference (Loc,
Unchecked_Convert_To
(Node
(Last_Elmt
(Access_Disp_Table (Iface))),
New_Occurrence_Of (Typ_Tag, Loc))),
Expressions =>
New_List
(Build_Val (Loc, UI_From_Int (Prim_Pos)))),
Expression =>
Unchecked_Convert_To (RTE (RE_Prim_Ptr),
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (E, Loc),
Attribute_Name =>
Name_Unrestricted_Access))));
end if;
Next_Elmt (Elmt);
end loop;
-- Check if all primitives from the parent have been
-- overridden (to avoid copying the whole secondary
-- table from the parent).
-- IfaceG!(Typ_Sec_Tag).all := IfaceG!(Parent_Sec_Tag).all;
for J in Prims_Table'Range loop
if not Prims_Table (J) then
Insert_After (Last_Nod,
Make_Assignment_Statement (Loc,
Name =>
Make_Explicit_Dereference (Loc,
Unchecked_Convert_To
(Node (Last_Elmt (Access_Disp_Table (Iface))),
New_Occurrence_Of (Typ_Tag, Loc))),
Expression =>
Make_Explicit_Dereference (Loc,
Unchecked_Convert_To
(Node (Last_Elmt (Access_Disp_Table (Iface))),
New_Occurrence_Of (Parent_Tag, Loc)))));
exit;
end if;
end loop;
end;
end if;
Next_Elmt (Typ_Iface_Tag_Elmt);
Next_Elmt (Parent_Iface_Tag_Elmt);
end loop;
end;
return Result;
end Build_Inherit_CPP_Prims;
-------------------------
-- Build_Inherit_Prims --
-------------------------
function Build_Inherit_Prims
(Loc : Source_Ptr;
Typ : Entity_Id;
Old_Tag_Node : Node_Id;
New_Tag_Node : Node_Id;
Num_Prims : Nat) return Node_Id
is
begin
if RTE_Available (RE_DT) then
return
Make_Assignment_Statement (Loc,
Name =>
Make_Slice (Loc,
Prefix =>
Make_Selected_Component (Loc,
Prefix =>
Make_Explicit_Dereference (Loc,
Build_DT (Loc, New_Tag_Node)),
Selector_Name =>
New_Occurrence_Of
(RTE_Record_Component (RE_Prims_Ptr), Loc)),
Discrete_Range =>
Build_Range (Loc, 1, Num_Prims)),
Expression =>
Make_Slice (Loc,
Prefix =>
Make_Selected_Component (Loc,
Prefix =>
Make_Explicit_Dereference (Loc,
Build_DT (Loc, Old_Tag_Node)),
Selector_Name =>
New_Occurrence_Of
(RTE_Record_Component (RE_Prims_Ptr), Loc)),
Discrete_Range =>
Build_Range (Loc, 1, Num_Prims)));
else
return
Make_Assignment_Statement (Loc,
Name =>
Make_Slice (Loc,
Prefix =>
Unchecked_Convert_To
(Node (Last_Elmt (Access_Disp_Table (Typ))),
New_Tag_Node),
Discrete_Range =>
Build_Range (Loc, 1, Num_Prims)),
Expression =>
Make_Slice (Loc,
Prefix =>
Unchecked_Convert_To
(Node (Last_Elmt (Access_Disp_Table (Typ))),
Old_Tag_Node),
Discrete_Range =>
Build_Range (Loc, 1, Num_Prims)));
end if;
end Build_Inherit_Prims;
-------------------------------
-- Build_Get_Prim_Op_Address --
-------------------------------
procedure Build_Get_Prim_Op_Address
(Loc : Source_Ptr;
Typ : Entity_Id;
Position : Uint;
Tag_Node : in out Node_Id;
New_Node : out Node_Id)
is
New_Prefix : Node_Id;
begin
pragma Assert
(Position <= DT_Entry_Count (First_Tag_Component (Typ)));
-- At the end of the Access_Disp_Table list we have the type
-- declaration required to convert the tag into a pointer to
-- the prims_ptr table (see Freeze_Record_Type).
New_Prefix :=
Unchecked_Convert_To
(Node (Last_Elmt (Access_Disp_Table (Typ))), Tag_Node);
-- Unchecked_Convert_To relocates the controlling tag node and therefore
-- we must update it.
Tag_Node := Expression (New_Prefix);
New_Node :=
Make_Indexed_Component (Loc,
Prefix => New_Prefix,
Expressions => New_List (Build_Val (Loc, Position)));
end Build_Get_Prim_Op_Address;
-----------------------------
-- Build_Get_Transportable --
-----------------------------
function Build_Get_Transportable
(Loc : Source_Ptr;
Tag_Node : Node_Id) return Node_Id
is
begin
return
Make_Selected_Component (Loc,
Prefix =>
Make_Explicit_Dereference (Loc,
Build_TSD (Loc,
Unchecked_Convert_To (RTE (RE_Address), Tag_Node))),
Selector_Name =>
New_Occurrence_Of
(RTE_Record_Component (RE_Transportable), Loc));
end Build_Get_Transportable;
------------------------------------
-- Build_Inherit_Predefined_Prims --
------------------------------------
function Build_Inherit_Predefined_Prims
(Loc : Source_Ptr;
Old_Tag_Node : Node_Id;
New_Tag_Node : Node_Id;
Num_Predef_Prims : Nat) return Node_Id
is
begin
return
Make_Assignment_Statement (Loc,
Name =>
Make_Slice (Loc,
Prefix =>
Make_Explicit_Dereference (Loc,
Unchecked_Convert_To (RTE (RE_Predef_Prims_Table_Ptr),
Make_Explicit_Dereference (Loc,
Unchecked_Convert_To (RTE (RE_Addr_Ptr),
New_Tag_Node)))),
Discrete_Range =>
Build_Range (Loc, 1, Num_Predef_Prims)),
Expression =>
Make_Slice (Loc,
Prefix =>
Make_Explicit_Dereference (Loc,
Unchecked_Convert_To (RTE (RE_Predef_Prims_Table_Ptr),
Make_Explicit_Dereference (Loc,
Unchecked_Convert_To (RTE (RE_Addr_Ptr),
Old_Tag_Node)))),
Discrete_Range =>
Build_Range (Loc, 1, Num_Predef_Prims)));
end Build_Inherit_Predefined_Prims;
-------------------------
-- Build_Offset_To_Top --
-------------------------
function Build_Offset_To_Top
(Loc : Source_Ptr;
This_Node : Node_Id) return Node_Id
is
Tag_Node : Node_Id;
begin
Tag_Node :=
Make_Explicit_Dereference (Loc,
Unchecked_Convert_To (RTE (RE_Tag_Ptr), This_Node));
return
Make_Explicit_Dereference (Loc,
Unchecked_Convert_To (RTE (RE_Offset_To_Top_Ptr),
Make_Function_Call (Loc,
Name =>
Make_Expanded_Name (Loc,
Chars => Name_Op_Subtract,
Prefix =>
New_Occurrence_Of
(RTU_Entity (System_Storage_Elements), Loc),
Selector_Name => Make_Identifier (Loc, Name_Op_Subtract)),
Parameter_Associations => New_List (
Unchecked_Convert_To (RTE (RE_Address), Tag_Node),
New_Occurrence_Of
(RTE (RE_DT_Offset_To_Top_Offset), Loc)))));
end Build_Offset_To_Top;
-----------------
-- Build_Range --
-----------------
function Build_Range (Loc : Source_Ptr; Lo, Hi : Nat) return Node_Id is
Result : Node_Id;
begin
Result :=
Make_Range (Loc,
Low_Bound => Build_Val (Loc, UI_From_Int (Lo)),
High_Bound => Build_Val (Loc, UI_From_Int (Hi)));
Set_Etype (Result, Standard_Natural);
Set_Analyzed (Result);
return Result;
end Build_Range;
------------------------------------------
-- Build_Set_Predefined_Prim_Op_Address --
------------------------------------------
function Build_Set_Predefined_Prim_Op_Address
(Loc : Source_Ptr;
Tag_Node : Node_Id;
Position : Uint;
Address_Node : Node_Id) return Node_Id
is
begin
return
Make_Assignment_Statement (Loc,
Name =>
Make_Indexed_Component (Loc,
Prefix =>
Unchecked_Convert_To (RTE (RE_Predef_Prims_Table_Ptr),
Make_Explicit_Dereference (Loc,
Unchecked_Convert_To (RTE (RE_Addr_Ptr), Tag_Node))),
Expressions =>
New_List (Build_Val (Loc, Position))),
Expression => Address_Node);
end Build_Set_Predefined_Prim_Op_Address;
-------------------------------
-- Build_Set_Prim_Op_Address --
-------------------------------
function Build_Set_Prim_Op_Address
(Loc : Source_Ptr;
Typ : Entity_Id;
Tag_Node : Node_Id;
Position : Uint;
Address_Node : Node_Id) return Node_Id
is
Ctrl_Tag : Node_Id := Tag_Node;
New_Node : Node_Id;
begin
Build_Get_Prim_Op_Address (Loc, Typ, Position, Ctrl_Tag, New_Node);
return
Make_Assignment_Statement (Loc,
Name => New_Node,
Expression => Address_Node);
end Build_Set_Prim_Op_Address;
-----------------------------
-- Build_Set_Size_Function --
-----------------------------
function Build_Set_Size_Function
(Loc : Source_Ptr;
Tag_Node : Node_Id;
Size_Func : Entity_Id) return Node_Id is
begin
pragma Assert (Chars (Size_Func) = Name_uSize
and then RTE_Record_Component_Available (RE_Size_Func));
return
Make_Assignment_Statement (Loc,
Name =>
Make_Selected_Component (Loc,
Prefix =>
Make_Explicit_Dereference (Loc,
Build_TSD (Loc,
Unchecked_Convert_To (RTE (RE_Address), Tag_Node))),
Selector_Name =>
New_Occurrence_Of
(RTE_Record_Component (RE_Size_Func), Loc)),
Expression =>
Unchecked_Convert_To (RTE (RE_Size_Ptr),
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Size_Func, Loc),
Attribute_Name => Name_Unrestricted_Access)));
end Build_Set_Size_Function;
------------------------------------
-- Build_Set_Static_Offset_To_Top --
------------------------------------
function Build_Set_Static_Offset_To_Top
(Loc : Source_Ptr;
Iface_Tag : Node_Id;
Offset_Value : Node_Id) return Node_Id is
begin
return
Make_Assignment_Statement (Loc,
Make_Explicit_Dereference (Loc,
Unchecked_Convert_To (RTE (RE_Offset_To_Top_Ptr),
Make_Function_Call (Loc,
Name =>
Make_Expanded_Name (Loc,
Chars => Name_Op_Subtract,
Prefix =>
New_Occurrence_Of
(RTU_Entity (System_Storage_Elements), Loc),
Selector_Name => Make_Identifier (Loc, Name_Op_Subtract)),
Parameter_Associations => New_List (
Unchecked_Convert_To (RTE (RE_Address), Iface_Tag),
New_Occurrence_Of
(RTE (RE_DT_Offset_To_Top_Offset), Loc))))),
Offset_Value);
end Build_Set_Static_Offset_To_Top;
---------------
-- Build_TSD --
---------------
function Build_TSD
(Loc : Source_Ptr;
Tag_Node_Addr : Node_Id) return Node_Id is
begin
return
Unchecked_Convert_To (RTE (RE_Type_Specific_Data_Ptr),
Make_Explicit_Dereference (Loc,
Prefix => Unchecked_Convert_To (RTE (RE_Addr_Ptr),
Make_Function_Call (Loc,
Name =>
Make_Expanded_Name (Loc,
Chars => Name_Op_Subtract,
Prefix =>
New_Occurrence_Of
(RTU_Entity (System_Storage_Elements), Loc),
Selector_Name => Make_Identifier (Loc, Name_Op_Subtract)),
Parameter_Associations => New_List (
Tag_Node_Addr,
New_Occurrence_Of
(RTE (RE_DT_Typeinfo_Ptr_Size), Loc))))));
end Build_TSD;
---------------
-- Build_Val --
---------------
function Build_Val (Loc : Source_Ptr; V : Uint) return Node_Id is
Result : Node_Id;
begin
Result := Make_Integer_Literal (Loc, V);
Set_Etype (Result, Standard_Natural);
Set_Is_Static_Expression (Result);
Set_Analyzed (Result);
return Result;
end Build_Val;
end Exp_Atag;
|
-- Copyright (c) 2019 Maxim Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-- License-Filename: LICENSE
-------------------------------------------------------------
with Ada.Containers.Hashed_Maps;
with League.Strings;
package Slim.Fonts is
type Font is limited private;
type Font_Access is access constant Font;
procedure Read
(Self : in out Font;
Name : League.Strings.Universal_String);
type Bounding_Box is record
Left, Right : Integer;
Top, Bottom : Integer;
end record;
function Size
(Self : Font;
Text : League.Strings.Universal_String) return Bounding_Box;
-- Return bounding box for given text, as if it's printed with zero offsets
generic
type Coordinate is range <>;
with procedure Draw_Pixel (X, Y : Coordinate);
procedure Draw_Text
(Self : Font;
Text : League.Strings.Universal_String;
Offset_X : Coordinate;
Offset_Y : Coordinate);
private
type Bit_Count is range 0 .. 64;
type Bit_Matrix is array (Bit_Count range <>, Bit_Count range <>) of Boolean
with Pack;
type Glyph_Bitmap (Width, Height : Bit_Count) is record
Offset_X : Bit_Count'Base;
Offset_Y : Bit_Count'Base;
Dev_Width : Bit_Count; -- Device Width of a glyph
V : Bit_Matrix (1 .. Height, 1 .. Width);
end record;
type Glyph_Bitmap_Access is access all Glyph_Bitmap;
function Hash
(Value : Wide_Wide_Character) return Ada.Containers.Hash_Type;
package Glyph_Bitmap_Maps is new Ada.Containers.Hashed_Maps
(Key_Type => Wide_Wide_Character,
Element_Type => Glyph_Bitmap_Access,
Hash => Hash,
Equivalent_Keys => "=",
"=" => "=");
type Font is record
Encoding : League.Strings.Universal_String;
Map : Glyph_Bitmap_Maps.Map;
end record;
end Slim.Fonts;
|
-- Copyright © by Jeff Foley 2017-2022. All rights reserved.
-- Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
-- SPDX-License-Identifier: Apache-2.0
name = "TeamCymru"
type = "misc"
function asn(ctx, addr, asn)
if (addr == "") then return end
local result = origin(ctx, addr)
if (result == nil or result.asn == 0) then return end
result['netblocks'] = result.prefix
local desc = get_desc(ctx, result.asn)
if (desc == "") then return end
result['desc'] = desc
new_asn(ctx, result)
end
function origin(ctx, addr)
local name = ""
local arpa = ".origin.asn.cymru.com"
if is_ipv4(addr) then
name = reverse_ipv4(addr)
else
name = ipv6_nibble(addr)
arpa = ".origin6.asn.cymru.com"
end
if (name == "") then return nil end
local resp, err = resolve(ctx, name .. arpa, "TXT", false)
if ((err ~= nil and err ~= "") or #resp == 0) then return nil end
local fields = split(resp[1].rrdata, "|")
return {
['addr']=addr,
['asn']=tonumber(trim_space(fields[1])),
['prefix']=trim_space(fields[2]),
['registry']=trim_space(fields[4]),
['cc']=trim_space(fields[3]),
}
end
function get_desc(ctx, asn)
local name = "AS" .. tostring(asn) .. ".asn.cymru.com"
local resp, err = resolve(ctx, name, "TXT", false)
if ((err ~= nil and err ~= "") or #resp == 0) then return "" end
local fields = split(resp[1].rrdata, "|")
if (#fields < 5) then return "" end
return trim_space(fields[5])
end
function split(str, delim)
local result = {}
local pattern = "[^%" .. delim .. "]+"
local matches = find(str, pattern)
if (matches == nil or #matches == 0) then return result end
for _, match in pairs(matches) do
table.insert(result, match)
end
return result
end
function trim_space(s)
return s:match( "^%s*(.-)%s*$" )
end
function is_ipv4(addr)
local octets = { addr:match("^(%d+)%.(%d+)%.(%d+)%.(%d+)$") }
if (#octets == 4) then
for _, v in pairs(octets) do
if tonumber(v) > 255 then return false end
end
return true
end
return false
end
function reverse_ipv4(addr)
local octets = { addr:match("^(%d+)%.(%d+)%.(%d+)%.(%d+)$") }
local ip = ""
for i, o in pairs(octets) do
local n = o
if (i ~= 1) then n = n .. "." end
ip = n .. ip
end
return ip
end
function ipv6_nibble(addr)
local ip = expand_ipv6(addr)
if (ip == "") then return ip end
local parts = split(ip, ":")
-- padding
local mask = "0000"
for i, part in ipairs(parts) do
parts[i] = mask:sub(1, #mask - #part) .. part
end
-- 32 parts from 8
local temp = {}
for i, hdt in ipairs(parts) do
for part in hdt:gmatch("%x") do
temp[#temp+1] = part
end
end
parts = temp
local reverse = {}
for i = #parts, 1, -1 do
table.insert(reverse, parts[i])
end
return table.concat(reverse, ".")
end
function expand_ipv6(addr)
-- preserve ::
addr = string.gsub(addr, "::", ":z:")
-- get a table of each hexadectet
local hexadectets = {}
for hdt in string.gmatch(addr, "[%.z%x]+") do
hexadectets[#hexadectets+1] = hdt
end
-- deal with :: and check for invalid address
local z_done = false
for index, value in ipairs(hexadectets) do
if value == "z" and z_done then
-- can't have more than one ::
return ""
elseif value == "z" and not z_done then
z_done = true
hexadectets[index] = "0"
local bound = 8 - #hexadectets
for i = 1, bound, 1 do
table.insert(hexadectets, index+i, "0")
end
elseif tonumber(value, 16) > 65535 then
-- more than FFFF!
return ""
end
end
-- make sure we have exactly 8 hexadectets
if (#hexadectets > 8) then return "" end
while (#hexadectets < 8) do
hexadectets[#hexadectets+1] = "0"
end
return (table.concat(hexadectets, ":"))
end
|
with
openGL.Visual;
package openGL.Terrain
--
-- Provides a constructor for heightmap terrain.
--
is
function new_Terrain (heights_File : in asset_Name;
texture_File : in asset_Name := null_Asset;
Scale : in math.Vector_3 := (1.0, 1.0, 1.0)) return Visual.Grid;
end openGL.Terrain;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Ada Modeling Framework --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2012, Vadim Godunko <vgodunko@gmail.com> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
-- This file is generated, don't edit it.
------------------------------------------------------------------------------
package AMF.Internals.Tables.CMOF_Metamodel.Objects is
procedure Initialize;
private
procedure Initialize_1 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_2 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_3 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_4 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_5 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_6 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_7 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_8 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_9 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_10 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_11 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_12 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_13 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_14 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_15 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_16 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_17 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_18 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_19 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_20 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_21 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_22 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_23 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_24 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_25 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_26 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_27 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_28 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_29 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_30 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_31 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_32 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_33 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_34 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_35 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_36 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_37 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_38 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_39 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_40 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_41 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_42 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_43 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_44 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_45 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_46 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_47 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_48 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_49 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_50 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_51 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_52 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_53 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_54 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_55 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_56 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_57 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_58 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_59 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_60 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_61 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_62 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_63 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_64 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_65 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_66 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_67 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_68 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_69 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_70 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_71 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_72 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_73 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_74 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_75 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_76 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_77 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_78 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_79 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_80 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_81 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_82 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_83 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_84 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_85 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_86 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_87 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_88 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_89 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_90 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_91 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_92 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_93 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_94 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_95 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_96 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_97 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_98 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_99 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_100 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_101 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_102 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_103 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_104 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_105 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_106 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_107 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_108 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_109 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_110 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_111 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_112 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_113 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_114 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_115 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_116 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_117 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_118 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_119 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_120 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_121 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_122 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_123 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_124 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_125 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_126 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_127 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_128 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_129 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_130 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_131 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_132 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_133 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_134 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_135 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_136 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_137 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_138 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_139 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_140 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_141 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_142 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_143 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_144 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_145 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_146 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_147 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_148 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_149 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_150 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_151 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_152 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_153 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_154 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_155 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_156 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_157 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_158 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_159 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_160 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_161 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_162 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_163 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_164 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_165 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_166 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_167 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_168 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_169 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_170 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_171 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_172 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_173 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_174 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_175 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_176 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_177 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_178 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_179 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_180 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_181 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_182 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_183 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_184 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_185 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_186 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_187 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_188 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_189 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_190 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_191 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_192 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_193 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_194 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_195 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_196 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_197 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_198 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_199 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_200 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_201 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_202 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_203 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_204 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_205 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_206 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_207 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_208 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_209 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_210 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_211 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_212 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_213 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_214 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_215 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_216 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_217 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_218 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_219 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_220 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_221 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_222 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_223 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_224 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_225 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_226 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_227 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_228 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_229 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_230 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_231 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_232 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_233 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_234 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_235 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_236 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_237 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_238 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_239 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_240 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_241 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_242 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_243 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_244 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_245 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_246 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_247 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_248 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_249 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_250 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_251 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_252 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_253 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_254 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_255 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_256 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_257 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_258 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_259 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_260 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_261 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_262 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_263 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_264 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_265 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_266 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_267 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_268 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_269 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_270 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_271 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_272 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_273 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_274 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_275 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_276 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_277 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_278 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_279 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_280 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_281 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_282 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_283 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_284 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_285 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_286 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_287 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_288 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_289 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_290 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_291 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_292 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_293 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_294 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_295 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_296 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_297 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_298 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_299 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_300 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_301 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_302 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_303 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_304 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_305 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_306 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_307 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_308 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_309 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_310 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_311 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_312 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_313 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_314 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_315 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_316 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_317 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_318 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_319 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_320 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_321 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_322 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_323 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_324 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_325 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_326 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_327 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_328 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_329 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_330 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_331 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_332 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_333 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_334 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_335 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_336 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_337 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_338 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_339 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_340 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_341 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_342 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_343 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_344 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_345 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_346 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_347 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_348 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_349 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_350 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_351 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_352 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_353 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_354 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_355 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_356 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_357 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_358 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_359 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_360 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_361 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_362 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_363 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_364 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_365 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_366 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_367 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_368 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_369 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_370 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_371 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_372 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_373 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_374 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_375 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_376 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_377 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_378 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_379 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_380 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_381 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_382 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_383 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_384 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_385 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_386 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_387 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_388 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_389 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_390 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_391 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_392 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_393 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_394 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_395 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_396 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_397 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_398 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_399 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_400 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_401 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_402 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_403 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_404 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_405 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_406 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_407 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_408 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_409 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_410 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_411 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_412 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_413 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_414 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_415 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_416 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_417 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_418 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_419 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_420 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_421 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_422 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_423 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_424 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_425 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_426 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_427 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_428 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_429 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_430 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_431 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_432 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_433 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_434 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_435 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_436 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_437 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_438 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_439 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_440 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_441 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_442 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_443 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_444 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_445 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_446 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_447 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_448 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_449 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_450 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_451 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_452 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_453 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_454 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_455 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_456 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_457 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_458 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_459 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_460 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_461 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_462 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_463 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_464 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_465 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_466 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_467 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_468 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_469 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_470 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_471 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_472 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_473 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_474 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_475 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_476 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_477 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_478 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_479 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_480 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_481 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_482 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_483 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_484 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_485 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_486 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_487 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_488 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_489 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_490 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_491 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_492 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_493 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_494 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_495 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_496 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_497 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_498 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_499 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_500 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_501 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_502 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_503 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_504 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_505 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_506 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_507 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_508 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_509 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_510 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_511 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_512 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_513 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_514 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_515 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_516 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_517 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_518 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_519 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_520 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_521 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_522 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_523 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_524 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_525 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_526 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_527 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_528 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_529 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_530 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_531 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_532 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_533 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_534 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_535 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_536 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_537 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_538 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_539 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_540 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_541 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_542 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_543 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_544 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_545 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_546 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_547 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_548 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_549 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_550 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_551 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_552 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_553 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_554 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_555 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_556 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_557 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_558 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_559 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_560 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_561 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_562 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_563 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_564 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_565 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_566 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_567 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_568 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_569 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_570 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_571 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_572 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_573 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_574 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_575 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_576 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_577 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_578 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_579 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_580 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_581 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_582 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_583 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_584 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_585 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_586 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_587 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_588 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_589 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_590 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_591 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_592 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_593 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_594 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_595 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_596 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_597 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_598 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_599 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_600 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_601 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_602 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_603 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_604 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_605 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_606 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_607 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_608 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_609 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_610 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_611 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_612 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_613 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_614 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_615 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_616 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_617 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_618 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_619 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_620 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_621 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_622 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_623 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_624 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_625 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_626 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_627 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_628 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_629 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_630 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_631 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_632 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_633 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_634 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_635 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_636 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_637 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_638 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_639 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_640 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_641 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_642 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_643 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_644 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_645 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_646 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_647 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_648 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_649 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_650 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_651 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_652 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_653 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_654 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_655 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_656 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_657 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_658 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_659 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_660 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_661 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_662 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_663 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_664 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_665 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_666 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_667 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_668 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_669 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_670 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_671 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_672 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_673 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_674 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_675 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_676 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_677 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_678 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_679 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_680 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_681 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_682 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_683 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_684 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_685 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_686 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_687 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_688 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_689 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_690 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_691 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_692 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_693 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_694 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_695 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_696 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_697 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_698 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_699 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_700 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_701 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_702 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_703 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_704 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_705 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_706 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_707 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_708 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_709 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_710 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_711 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_712 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_713 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_714 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_715 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_716 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_717 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_718 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_719 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_720 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_721 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_722 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_723 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_724 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_725 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_726 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_727 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_728 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_729 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_730 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_731 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_732 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_733 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_734 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_735 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_736 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_737 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_738 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_739 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_740 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_741 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_742 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_743 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_744 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_745 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_746 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_747 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_748 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_749 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_750 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_751 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_752 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_753 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_754 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_755 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_756 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_757 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_758 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_759 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_760 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_761 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_762 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_763 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_764 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_765 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_766 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_767 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_768 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_769 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_770 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_771 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_772 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_773 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_774 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_775 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_776 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_777 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_778 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_779 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_780 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_781 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_782 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_783 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_784 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_785 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_786 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_787 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_788 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_789 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_790 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_791 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_792 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_793 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_794 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_795 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_796 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_797 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_798 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_799 (Extent : AMF.Internals.AMF_Extent);
procedure Initialize_800 (Extent : AMF.Internals.AMF_Extent);
end AMF.Internals.Tables.CMOF_Metamodel.Objects;
|
with Ada.Command_Line;
with Ada.Text_IO;
with SDL;
with SDL.Events.Events;
with SDL.Events.Keyboards;
with SDL.Log;
with SDL.TTFs.Makers;
with SDL.Video.Palettes;
with SDL.Video.Surfaces;
with SDL.Video.Windows.Makers;
procedure TTF is
W : SDL.Video.Windows.Window;
Window_Surface : SDL.Video.Surfaces.Surface;
-- Renderer : SDL.Video.Renderers.Renderer;
Font : SDL.TTFs.Fonts;
Text_Surface : SDL.Video.Surfaces.Surface;
-- Text_Texture : SDL.Video.Textures.Texture;
begin
if Ada.Command_Line.Argument_Count = 0 then
Ada.Text_IO.Put_Line ("Error! Enter TTF font path on command line.");
else
SDL.Log.Set (Category => SDL.Log.Application, Priority => SDL.Log.Debug);
if SDL.Initialise (Flags => SDL.Enable_Screen) = True and then SDL.TTFs.Initialise = True then
SDL.Video.Windows.Makers.Create (Win => W,
Title => "TTF (Esc to exit)",
Position => SDL.Natural_Coordinates'(X => 100, Y => 100),
Size => SDL.Positive_Sizes'(800, 640),
Flags => SDL.Video.Windows.Resizable);
-- SDL.Video.Renderers.Makers.Create (Renderer, W);
Window_Surface := W.Get_Surface;
-- SDL.TTFs.Makers.Create (Font, "/home/laguest/.fonts/Belga.ttf", 24);
SDL.TTFs.Makers.Create (Font, Ada.Command_Line.Argument (1), 36);
Text_Surface := Font.Render_Solid (Text => "Hello from SDLAda",
Colour => SDL.Video.Palettes.Colour'(Red => 0,
Green => 200,
Blue => 200,
Alpha => 255));
-- Text_Surface.Set_Blend_Mode (SDL.Video.None);
-- Text_Surface := Font.Render_Shaded (Text => "Hello from SDLAda",
-- Colour => SDL.Video.Palettes.Colour'(Red => 255,
-- Green => 255,
-- Blue => 255,
-- Alpha => 255),
-- Background_Colour => SDL.Video.Palettes.Colour'(Red => 0,
-- Green => 20,
-- Blue => 250,
-- Alpha => 255));
-- Text_Surface := Font.Render_Blended (Text => "Hello from SDLAda",
-- Colour => SDL.Video.Palettes.Colour'(Red => 50, others => 255));
-- SDL.Video.Textures.Makers.Create (Text_Texture, Renderer, Text_Surface);
Window_Surface.Blit (Source => Text_Surface);
W.Update_Surface;
-- Main loop.
declare
Event : SDL.Events.Events.Events;
Finished : Boolean := False;
use type SDL.Events.Keyboards.Key_Codes;
begin
-- W.Update_Surface; -- Shows the above two calls.
loop
while SDL.Events.Events.Poll (Event) loop
case Event.Common.Event_Type is
when SDL.Events.Quit =>
Finished := True;
when SDL.Events.Keyboards.Key_Down =>
if Event.Keyboard.Key_Sym.Key_Code = SDL.Events.Keyboards.Code_Escape then
Finished := True;
end if;
when others =>
null;
end case;
end loop;
-- Renderer.Clear;
-- Renderer.Copy (Text_Texture);
-- Renderer.Present;
exit when Finished;
end loop;
end;
SDL.Log.Put_Debug ("");
-- Window_Surface.Finalize;
W.Finalize;
SDL.TTFs.Finalise;
SDL.Finalise;
else
Ada.Text_IO.Put_Line ("Error! could not initialise SDL or SDL.TTF!");
end if;
end if;
end TTF;
|
with System;
with Utils; use Utils;
package body Drivers.RFM69 is
package IRQHandler is new HAL.Pin_IRQ (Pin => IRQ);
F_Osc : constant Unsigned_32 := 32_000_000;
type Unsigned_2 is mod 2 ** 2;
type Unsigned_3 is mod 2 ** 3;
type Unsigned_5 is mod 2 ** 5;
type Unsigned_7 is mod 2 ** 7;
type Register_Type is (
FIFO,
OPMODE,
DATAMODUL,
BITRATEMSB,
BITRATELSB,
FDEVMSB,
FDEVLSB,
FRFMSB,
FRFMID,
FRFLSB,
OSC1,
AFCCTRL,
LOWBAT,
LISTEN1,
LISTEN2,
LISTEN3,
VERSION,
PALEVEL,
PARAMP,
OCP,
AGCREF,
AGCTHRESH1,
AGCTHRESH2,
AGCTHRESH3,
LNA,
RXBW,
AFCBW,
OOKPEAK,
OOKAVG,
OOKFIX,
AFCFEI,
AFCMSB,
AFCLSB,
FEIMSB,
FEILSB,
RSSICONFIG,
RSSIVALUE,
DIOMAPPING1,
DIOMAPPING2,
IRQFLAGS1,
IRQFLAGS2,
RSSITHRESH,
RXTIMEOUT1,
RXTIMEOUT2,
PREAMBLEMSB,
PREAMBLELSB,
SYNCCONFIG,
SYNCVALUE1,
SYNCVALUE2,
SYNCVALUE3,
SYNCVALUE4,
SYNCVALUE5,
SYNCVALUE6,
SYNCVALUE7,
SYNCVALUE8,
PACKETCONFIG1,
PAYLOADLENGTH,
NODEADRS,
BROADCASTADRS,
AUTOMODES,
FIFOTHRESH,
PACKETCONFIG2,
AESKEY1,
AESKEY2,
AESKEY3,
AESKEY4,
AESKEY5,
AESKEY6,
AESKEY7,
AESKEY8,
AESKEY9,
AESKEY10,
AESKEY11,
AESKEY12,
AESKEY13,
AESKEY14,
AESKEY15,
AESKEY16,
TEMP1,
TEMP2);
for Register_Type use (
FIFO => 16#00#,
OPMODE => 16#01#,
DATAMODUL => 16#02#,
BITRATEMSB => 16#03#,
BITRATELSB => 16#04#,
FDEVMSB => 16#05#,
FDEVLSB => 16#06#,
FRFMSB => 16#07#,
FRFMID => 16#08#,
FRFLSB => 16#09#,
OSC1 => 16#0A#,
AFCCTRL => 16#0B#,
LOWBAT => 16#0C#,
LISTEN1 => 16#0D#,
LISTEN2 => 16#0E#,
LISTEN3 => 16#0F#,
VERSION => 16#10#,
PALEVEL => 16#11#,
PARAMP => 16#12#,
OCP => 16#13#,
AGCREF => 16#14#,
AGCTHRESH1 => 16#15#,
AGCTHRESH2 => 16#16#,
AGCTHRESH3 => 16#17#,
LNA => 16#18#,
RXBW => 16#19#,
AFCBW => 16#1A#,
OOKPEAK => 16#1B#,
OOKAVG => 16#1C#,
OOKFIX => 16#1D#,
AFCFEI => 16#1E#,
AFCMSB => 16#1F#,
AFCLSB => 16#20#,
FEIMSB => 16#21#,
FEILSB => 16#22#,
RSSICONFIG => 16#23#,
RSSIVALUE => 16#24#,
DIOMAPPING1 => 16#25#,
DIOMAPPING2 => 16#26#,
IRQFLAGS1 => 16#27#,
IRQFLAGS2 => 16#28#,
RSSITHRESH => 16#29#,
RXTIMEOUT1 => 16#2A#,
RXTIMEOUT2 => 16#2B#,
PREAMBLEMSB => 16#2C#,
PREAMBLELSB => 16#2D#,
SYNCCONFIG => 16#2E#,
SYNCVALUE1 => 16#2F#,
SYNCVALUE2 => 16#30#,
SYNCVALUE3 => 16#31#,
SYNCVALUE4 => 16#32#,
SYNCVALUE5 => 16#33#,
SYNCVALUE6 => 16#34#,
SYNCVALUE7 => 16#35#,
SYNCVALUE8 => 16#36#,
PACKETCONFIG1 => 16#37#,
PAYLOADLENGTH => 16#38#,
NODEADRS => 16#39#,
BROADCASTADRS => 16#3A#,
AUTOMODES => 16#3B#,
FIFOTHRESH => 16#3C#,
PACKETCONFIG2 => 16#3D#,
AESKEY1 => 16#3E#,
AESKEY2 => 16#3F#,
AESKEY3 => 16#40#,
AESKEY4 => 16#41#,
AESKEY5 => 16#42#,
AESKEY6 => 16#43#,
AESKEY7 => 16#44#,
AESKEY8 => 16#45#,
AESKEY9 => 16#46#,
AESKEY10 => 16#47#,
AESKEY11 => 16#48#,
AESKEY12 => 16#49#,
AESKEY13 => 16#4A#,
AESKEY14 => 16#4B#,
AESKEY15 => 16#4C#,
AESKEY16 => 16#4D#,
TEMP1 => 16#4E#,
TEMP2 => 16#4F#);
type OPMODE_Mode_Type is (SLEEP, STDBY, FS, TX, RX)
with Size => 3;
for OPMODE_Mode_Type use (
SLEEP => 2#000#,
STDBY => 2#001#,
FS => 2#010#,
TX => 2#011#,
RX => 2#100#);
type Command_Type is (R_REGISTER, W_REGISTER);
for Command_Type use (
R_REGISTER => 2#0000_0000#,
W_REGISTER => 2#1000_0000#);
type OPMODE_Register_Type (As_Value : Boolean := False) is
record
case As_Value is
when True =>
Val : Unsigned_8;
when False =>
Sequencer_Off : Boolean;
Listen_On : Boolean;
Listen_Abort : Boolean;
Mode : OPMODE_Mode_Type;
end case;
end record
with Unchecked_Union, Size => 8, Bit_Order => System.Low_Order_First;
for OPMODE_Register_Type use
record
Val at 0 range 0 .. 7;
Sequencer_Off at 0 range 7 .. 7;
Listen_On at 0 range 6 .. 6;
Listen_Abort at 0 range 5 .. 5;
Mode at 0 range 2 .. 4;
end record;
subtype DIO_Mapping_Type is Unsigned_2;
type DIOMAPPING1_Register_Type (As_Value : Boolean := False) is
record
case As_Value is
when True =>
Val : Unsigned_8;
when False =>
DIO0_Mapping : DIO_Mapping_Type;
DIO1_Mapping : DIO_Mapping_Type;
DIO2_Mapping : DIO_Mapping_Type;
DIO3_Mapping : DIO_Mapping_Type;
end case;
end record
with Unchecked_Union, Size => 8, Bit_Order => System.Low_Order_First;
for DIOMAPPING1_Register_Type use
record
DIO0_Mapping at 0 range 6 .. 7;
DIO1_Mapping at 0 range 4 .. 5;
DIO2_Mapping at 0 range 2 .. 3;
DIO3_Mapping at 0 range 0 .. 1;
end record;
type IRQFLAGS1_Register_Type (As_Value : Boolean := False) is
record
case As_Value is
when True =>
Val : Unsigned_8;
when False =>
Mode_Ready : Boolean;
Rx_Ready : Boolean;
Tx_Ready : Boolean;
PLL_Lock : Boolean;
RSSI : Boolean;
Timeout : Boolean;
Auto_Mode : Boolean;
Sync_Address_Match : Boolean;
end case;
end record
with Unchecked_Union, Size => 8, Bit_Order => System.Low_Order_First;
for IRQFLAGS1_Register_Type use
record
Mode_Ready at 0 range 7 .. 7;
Rx_Ready at 0 range 6 .. 6;
Tx_Ready at 0 range 5 .. 5;
PLL_Lock at 0 range 4 .. 4;
RSSI at 0 range 3 .. 3;
Timeout at 0 range 2 .. 2;
Auto_Mode at 0 range 1 .. 1;
Sync_Address_Match at 0 range 0 .. 0;
end record;
type IRQFLAGS2_Register_Type (As_Value : Boolean := False) is
record
case As_Value is
when True =>
Val : Unsigned_8;
when False =>
FIFO_Full : Boolean;
FIFO_Not_Emtpy : Boolean;
FIFO_Level : Boolean;
FIFO_Overrun : Boolean;
Packet_Sent : Boolean;
Payload_Ready : Boolean;
CRC_Ok : Boolean;
end case;
end record
with Unchecked_Union, Size => 8, Bit_Order => System.Low_Order_First;
for IRQFLAGS2_Register_Type use
record
FIFO_Full at 0 range 7 .. 7;
FIFO_Not_Emtpy at 0 range 6 .. 6;
FIFO_Level at 0 range 5 .. 5;
FIFO_Overrun at 0 range 4 .. 4;
Packet_Sent at 0 range 3 .. 3;
Payload_Ready at 0 range 2 .. 2;
CRC_Ok at 0 range 1 .. 1;
end record;
type SYNCCONFIG_FIFO_Fill_Condition_Type is (Sync_Address, Always)
with Size => 1;
for SYNCCONFIG_FIFO_Fill_Condition_Type use
(Sync_Address => 2#0#, Always => 2#1#);
type SYNCCONFIG_Register_Type (As_Value : Boolean := False) is
record
case As_Value is
when True =>
Val : Unsigned_8;
when False =>
Sync_On : Boolean;
FIFO_Fill_Condition : SYNCCONFIG_FIFO_Fill_Condition_Type;
Sync_Size : Unsigned_3;
Sync_Tol : Unsigned_3;
end case;
end record
with Unchecked_Union, Size => 8, Bit_Order => System.Low_Order_First;
for SYNCCONFIG_Register_Type use
record
Sync_On at 0 range 7 .. 7;
FIFO_Fill_Condition at 0 range 6 .. 6;
Sync_Size at 0 range 3 .. 5;
Sync_Tol at 0 range 0 .. 2;
end record;
type DATAMODUL_Data_Mode_Type is (Packet_Mode, Continuous_Synchronizer,
Continuous_No_Synchronizer)
with Size => 2;
for DATAMODUL_Data_Mode_Type use (
Packet_Mode => 2#00#,
Continuous_Synchronizer => 2#10#,
Continuous_No_Synchronizer => 2#11#);
type DATAMODUL_Modulation_Type is (FSK, OOK)
with Size => 2;
for DATAMODUL_Modulation_Type use (
FSK => 2#00#,
OOK => 2#01#);
type DATAMODUL_Modulation_Shaping is (No_Shaping, Shaping_1, Shaping_2,
Shaping_3);
for DATAMODUL_Modulation_Shaping use (
No_Shaping => 0,
Shaping_1 => 1,
Shaping_2 => 2,
Shaping_3 => 3);
type DATAMODUL_Register_Type (As_Value : Boolean := False) is
record
case As_Value is
when True =>
Val : Unsigned_8;
when False =>
Data_Mode : DATAMODUL_Data_Mode_Type;
Modulation_Type : DATAMODUL_Modulation_Type;
Modulation_Shaping : DATAMODUL_Modulation_Shaping;
end case;
end record
with Unchecked_Union, Size => 8, Bit_Order => System.Low_Order_First;
for DATAMODUL_Register_Type use
record
Data_Mode at 0 range 5 .. 6;
Modulation_Type at 0 range 3 .. 4;
Modulation_Shaping at 0 range 0 .. 2;
end record;
type FIFOTHRESH_Start_Condition_Type is (FIFO_Level, FIFO_Not_Empty);
for FIFOTHRESH_Start_Condition_Type use (
FIFO_Level => 2#0#,
FIFO_Not_Empty => 2#1#);
type FIFOTHRESH_Register_Type (As_Value : Boolean := False) is
record
case As_Value is
when True =>
Val : Unsigned_8;
when False =>
Start_Condition : FIFOTHRESH_Start_Condition_Type;
FIFO_Threshold : Unsigned_7;
end case;
end record
with Unchecked_Union, Size => 8, Bit_Order => System.Low_Order_First;
for FIFOTHRESH_Register_Type use
record
Start_Condition at 0 range 7 .. 7;
FIFO_Threshold at 0 range 0 .. 6;
end record;
type RXBW_Register_Type (As_Value : Boolean := False) is
record
case As_Value is
when True =>
Val : Unsigned_8;
when False =>
DCC_Freq : Unsigned_3;
RX_BW_Mant : Unsigned_2;
RX_BW_Exp : Unsigned_3;
end case;
end record
with Unchecked_Union, Size => 8, Bit_Order => System.Low_Order_First;
for RXBW_Register_Type use
record
DCC_Freq at 0 range 5 .. 7;
RX_BW_Mant at 0 range 3 .. 4;
RX_BW_Exp at 0 range 0 .. 2;
end record;
type PALEVEL_Register_Type (As_Value : Boolean := False) is
record
case As_Value is
when True =>
Val : Unsigned_8;
when False =>
PA0_On : Boolean;
PA1_On : Boolean;
PA2_On : Boolean;
Output_Power : Unsigned_5;
end case;
end record
with Unchecked_Union, Size => 8, Bit_Order => System.Low_Order_First;
for PALEVEL_Register_Type use
record
PA0_On at 0 range 7 .. 7;
PA1_On at 0 range 6 .. 6;
PA2_On at 0 range 5 .. 5;
Output_Power at 0 range 0 .. 4;
end record;
type AFCBW_Register_Type (As_Value : Boolean := False) is
record
case As_Value is
when True =>
Val : Unsigned_8;
when False =>
DCC_Freq_AFC : Unsigned_3;
RX_BW_Mant_AFC : Unsigned_2;
RX_BW_Exp_AFC : Unsigned_3;
end case;
end record
with Unchecked_Union, Size => 8, Bit_Order => System.Low_Order_First;
for AFCBW_Register_Type use
record
DCC_Freq_AFC at 0 range 5 .. 7;
RX_BW_Mant_AFC at 0 range 3 .. 4;
RX_BW_Exp_AFC at 0 range 0 .. 2;
end record;
type PACKETCONFIG1_Packet_Format_Type is (Fixed_Length, Variable_Length)
with Size => 1;
for PACKETCONFIG1_Packet_Format_Type use (
Fixed_Length => 2#0#,
Variable_Length => 2#1#);
type PACKETCONFIG1_DC_Free_Type is (None, Manchester, Whitening)
with Size => 2;
for PACKETCONFIG1_DC_Free_Type use (
None => 2#00#,
Manchester => 2#01#,
Whitening => 2#10#);
type PACKETCONFIG1_Address_Filtering_Type is (None, Node_Address,
Node_or_Broadcast_Address)
with Size => 2;
for PACKETCONFIG1_Address_Filtering_Type use (
None => 2#00#,
Node_Address => 2#01#,
Node_or_Broadcast_Address => 2#10#);
type PACKETCONFIG1_Register_Type (As_Value : Boolean := False) is
record
case As_Value is
when True =>
Val : Unsigned_8;
when False =>
Packet_Format : PACKETCONFIG1_Packet_Format_Type;
DC_Free : PACKETCONFIG1_DC_Free_Type;
CRC_On : Boolean;
CRC_Auto_Clear_Off : Boolean;
Address_Filtering : PACKETCONFIG1_Address_Filtering_Type;
end case;
end record
with Unchecked_Union, Size => 8, Bit_Order => System.Low_Order_First;
for PACKETCONFIG1_Register_Type use
record
Packet_Format at 0 range 7 .. 7;
DC_Free at 0 range 5 .. 6;
CRC_On at 0 range 4 .. 4;
CRC_Auto_Clear_Off at 0 range 3 .. 3;
Address_Filtering at 0 range 1 .. 2;
end record;
OPMODE_Init : constant OPMODE_Register_Type := (
Mode => STDBY,
others => False);
SYNCCONFIG_Init : constant SYNCCONFIG_Register_Type := (
As_Value => False,
Sync_On => True,
FIFO_Fill_Condition => Sync_Address,
Sync_Size => 3,
Sync_Tol => 0);
PACKETCONFIG1_Init : constant PACKETCONFIG1_Register_Type := (
As_Value => False,
Packet_Format => Variable_Length,
DC_Free => None,
CRC_On => True,
CRC_Auto_Clear_Off => False,
Address_Filtering => None);
DATAMODUL_Init : constant DATAMODUL_Register_Type := (
As_Value => False,
Data_Mode => Packet_Mode,
Modulation_Type => FSK,
Modulation_Shaping => No_Shaping);
RXBW_Init : constant RXBW_Register_Type := (
As_Value => False,
DCC_Freq => 2,
RX_BW_Mant => 0,
RX_BW_Exp => 2);
AFCBW_Init : constant AFCBW_Register_Type := (
As_Value => False,
DCC_Freq_AFC => 2,
RX_BW_Mant_AFC => 0,
RX_BW_Exp_AFC => 2);
RSSITHRESH_Init : constant Unsigned_8 := 100 * 2;
SYNCVALUE1_Init : constant Unsigned_8 := 16#F0#;
SYNCVALUE2_Init : constant Unsigned_8 := 16#12#;
SYNCVALUE3_Init : constant Unsigned_8 := 16#78#;
PREAMBLELSB_Init : constant Unsigned_8 := 6;
FDEVMSB_Init : constant Unsigned_8 := 195;
FDEVLSB_Init : constant Unsigned_8 := 5;
procedure Write_Register (Register : Register_Type; Value : Unsigned_8);
procedure Read_Register (Register : Register_Type; Value : out Unsigned_8);
function Read_Register (Register : Register_Type) return Unsigned_8;
procedure Set_Mode (Mode : OPMODE_Mode_Type);
procedure Write_Register (Register : Register_Type; Value : Unsigned_8) is
begin
Chip_Select.Clear;
SPI.Send (Register'Enum_Rep + W_REGISTER'Enum_Rep);
SPI.Send (Value);
Chip_Select.Set;
end Write_Register;
procedure Read_Register (Register : Register_Type; Value : out Unsigned_8) is
begin
Chip_Select.Clear;
SPI.Send (Register'Enum_Rep + R_REGISTER'Enum_Rep);
SPI.Receive (Value);
Chip_Select.Set;
end Read_Register;
function Read_Register (Register : Register_Type) return Unsigned_8 is
Value : Unsigned_8;
begin
Chip_Select.Clear;
SPI.Send (Register'Enum_Rep + R_REGISTER'Enum_Rep);
SPI.Receive (Value);
Chip_Select.Set;
return Value;
end Read_Register;
procedure Read_Registers (Registers : out Raw_Register_Array) is
begin
for R in Register_Type loop
Read_Register(R, Registers (R'Enum_Rep));
end loop;
end Read_Registers;
procedure Print_Registers is
begin
Put_Line (
"Version: " & To_Hex_String (Read_Register (VERSION)) &
" OpMode: " & To_Hex_String (Read_Register (OPMODE)) &
" IrqFlags: " & To_Hex_String (Read_Register (IRQFLAGS1)) & " " &
To_Hex_String (Read_Register (IRQFLAGS2)) &
" PacketConfig: " & To_Hex_String (Read_Register (PACKETCONFIG1)) &
" " & To_Hex_String (Read_Register (PACKETCONFIG2)) &
" PayloadLength: " & To_Hex_String (Read_Register (PAYLOADLENGTH)));
Put_Line (
"FifoThresh: " & To_Hex_String (Read_Register (FIFOTHRESH)) &
" RSSIConfig: " & To_Hex_String (Read_Register (RSSICONFIG)) &
" RSSIValue: " & To_Hex_String (Read_Register (RSSIVALUE)) &
" SyncConfig: " & To_Hex_String (Read_Register (SYNCCONFIG)) &
" DataModul: " & To_Hex_String (Read_Register (DATAMODUL)) &
" PaLevel: " & To_Hex_String (Read_Register (PALEVEL)) &
" Frequency: " & To_Hex_String (Read_Register (FRFMSB)) &
To_Hex_String (Read_Register (FRFMID)) &
To_Hex_String (Read_Register (FRFLSB)) &
" Bitrate: " & To_Hex_String (Read_Register (BITRATEMSB)) & " " &
To_Hex_String (Read_Register (BITRATELSB))
);
end Print_Registers;
procedure Init is
FIFOTHRESH_Init : constant FIFOTHRESH_Register_Type := (
As_Value => False,
Start_Condition => FIFO_Not_Empty,
FIFO_Threshold => Unsigned_7 (Packet_Size / 2));
begin
Write_Register (OPMODE, OPMODE_Init.Val);
Write_Register (FIFOTHRESH, FIFOTHRESH_Init.Val);
Write_Register (PACKETCONFIG1, PACKETCONFIG1_Init.Val);
Write_Register (RSSITHRESH, RSSITHRESH_Init);
Write_Register (SYNCCONFIG, SYNCCONFIG_Init.Val);
Write_Register (SYNCVALUE1, SYNCVALUE1_Init);
Write_Register (SYNCVALUE2, SYNCVALUE2_Init);
Write_Register (SYNCVALUE3, SYNCVALUE3_Init);
Write_Register (PREAMBLELSB, PREAMBLELSB_Init);
Write_Register (DATAMODUL, DATAMODUL_Init.Val);
Write_Register (FDEVMSB, FDEVMSB_Init);
Write_Register (FDEVLSB, FDEVLSB_Init);
Write_Register (RXBW, RXBW_Init.Val);
Write_Register (AFCBW, AFCBW_Init.Val);
Set_Frequency (Frequency);
IRQHandler.Configure_Trigger (Falling => True);
end Init;
procedure Set_Sync_Word (Sync_Word : Sync_Word_Type) is
begin
null;
end Set_Sync_Word;
procedure Set_Frequency (Frequency : Unsigned_32) is
F : Unsigned_32;
begin
F := (Frequency / 1_000_000) * (2 ** 19) / (F_Osc / 1_000_000);
Chip_Select.Clear;
SPI.Send (FRFMSB'Enum_Rep + W_REGISTER'Enum_Rep);
SPI.Send (Unsigned_8 ((F / (2 ** 16)) mod 2 ** 8));
SPI.Send (Unsigned_8 ((F / (2 ** 8)) mod 2 ** 8));
SPI.Send (Unsigned_8 (F mod 2 ** 8));
Chip_Select.Set;
end Set_Frequency;
procedure Set_Bitrate (Bitrate : Unsigned_32) is
B : Unsigned_32;
begin
B := F_Osc / Bitrate;
Chip_Select.Clear;
SPI.Send (BITRATEMSB'Enum_Rep + W_REGISTER'Enum_Rep);
SPI.Send (Unsigned_8 ((B / (2 ** 8)) mod 2 ** 8));
SPI.Send (Unsigned_8 (B mod 2 ** 8));
Chip_Select.Set;
end Set_Bitrate;
procedure Set_Broadcast_Address (Address : Address_Type) is
begin
null;
end Set_Broadcast_Address;
procedure Set_RX_Address (Address : Address_Type) is
begin
null;
end Set_RX_Address;
procedure Set_TX_Address (Address : Address_Type) is
begin
null;
end Set_TX_Address;
procedure Set_Mode (Mode : OPMODE_Mode_Type) is
M : OPMODE_Register_Type;
F : IRQFLAGS1_Register_Type;
R : Unsigned_8;
begin
Read_Register (OPMODE, R);
M.Val := R;
M.Mode := Mode;
Write_Register (OPMODE, M.Val);
loop
Read_Register (IRQFLAGS1, R);
F.Val := R;
exit when F.Mode_Ready;
end loop;
end Set_Mode;
procedure Set_Output_Power (Power : Output_Power_Type) is
P : PALEVEL_Register_Type;
R : Unsigned_8;
begin
Read_Register (PALEVEL, R);
P.Val := R;
P.Output_Power := Unsigned_5 (Power + 18);
Write_Register (PALEVEL, P.Val);
end Set_Output_Power;
procedure TX_Mode is
begin
Set_Mode (TX);
end TX_Mode;
procedure RX_Mode is
begin
Set_Mode (RX);
Write_Register (IRQFLAGS1, 2#0000_1001#);
end RX_Mode;
procedure TX (Packet: Packet_Type) is
begin
TX (Packet, Packet'Length);
end TX;
procedure TX (Packet: Packet_Type; Length: Unsigned_8) is
Wait : Unsigned_32;
begin
Set_Mode (TX);
Chip_Select.Clear;
SPI.Send (FIFO'Enum_Rep + W_REGISTER'Enum_Rep);
SPI.Send (Length);
for I in 0 .. Length - 1 loop
SPI.Send (Packet (I + Packet'First));
end loop;
Chip_Select.Set;
Wait := 100000;
while not TX_Complete and Wait > 0 loop
Wait := Wait - 1;
end loop;
Set_Mode (STDBY);
end TX;
function TX_Complete return Boolean is
Flags : IRQFLAGS2_Register_Type;
F : Unsigned_8;
begin
Read_Register (IRQFLAGS2, F);
Flags.Val := F;
return Flags.Packet_Sent;
end TX_Complete;
function RX_Available_Reg return Boolean is
Flags : IRQFLAGS2_Register_Type;
F : Unsigned_8;
begin
Read_Register (IRQFLAGS2, F);
Flags.Val := F;
return Flags.Payload_Ready;
end RX_Available_Reg;
function RX_Available return Boolean is
begin
return IRQ.Is_Set;
end RX_Available;
function Wait_For_RX return Boolean is
begin
loop
exit when RX_Available;
end loop;
return True;
end Wait_For_RX;
procedure RX (Packet : out Packet_Type; Length : out Unsigned_8) is
L : Unsigned_8;
begin
Chip_Select.Clear;
SPI.Send (FIFO'Enum_Rep + R_REGISTER'Enum_Rep);
SPI.Receive (L);
for I in 0 .. L - 1 loop
exit when I = Packet'Length;
SPI.Receive (Packet (I + Packet'First));
end loop;
Chip_Select.Set;
Length := L;
end RX;
procedure Power_Down is
begin
Set_Mode (SLEEP);
end Power_Down;
procedure Cancel is
begin
IRQHandler.Cancel_Wait;
end Cancel;
end Drivers.RFM69;
|
-- { dg-do compile }
-- { dg-options "-gnatws" }
package body Slice8_Pkg3 is
Current : Str.Lines (Str.Line_Count);
Last : Natural := 0;
function Get return Str.Paragraph is
Result : constant Str.Paragraph := (Size => Last,
Data => Current (1..Last));
begin
Last := 0;
return Result;
end Get;
end Slice8_Pkg3;
|
with Real_Type; use Real_Type;
package body Vectors_Conversions is
------------------
-- To_Vector_3D --
------------------
function To_Vector_3D (V : Vector_3D_LF) return Vector_3D is
(x => Real (V (x)),
y => Real (V (y)),
z => Real (V (z)));
---------------------
-- To_Vector_3D_LF --
---------------------
function To_Vector_3D_LF (V : Vector_3D) return Vector_3D_LF is
(x => Long_Float (V (x)),
y => Long_Float (V (y)),
z => Long_Float (V (z)));
------------------
-- To_Vector_2D --
------------------
function To_Vector_2D (V : Vector_2D_I) return Vector_2D is
(x => Real (V (x)),
y => Real (V (y)));
------------------
-- To_Vector_2D --
------------------
function To_Vector_2D (V : Vector_2D_N) return Vector_2D is
(x => Real (V (x)),
y => Real (V (y)));
------------------
-- To_Vector_2D --
------------------
function To_Vector_2D (V : Vector_2D_P) return Vector_2D is
(x => Real (V (x)),
y => Real (V (y)));
end Vectors_Conversions;
|
-- Copyright (c) 2019-2020 Maxim Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-- License-Filename: LICENSE
-------------------------------------------------------------
with Ada.Unchecked_Conversion;
with Interfaces;
with System;
with Torrent.Trackers;
package Torrent.UDP_Tracker_Protocol is
type Connect_Request is record
Protocol_Id : Interfaces.Unsigned_64 := 16#417_27_10_1980#;
Action : Interfaces.Unsigned_32;
Transaction_Id : Interfaces.Unsigned_32;
end record;
for Connect_Request'Bit_Order use System.High_Order_First;
for Connect_Request'Scalar_Storage_Order use System.High_Order_First;
for Connect_Request use record
Protocol_Id at 0 range 0 .. 63;
Action at 8 range 0 .. 31;
Transaction_Id at 12 range 0 .. 31;
end record;
subtype Raw_Connect_Request is Ada.Streams.Stream_Element_Array
(1 .. Connect_Request'Max_Size_In_Storage_Elements);
function Cast is new Ada.Unchecked_Conversion
(Connect_Request, Raw_Connect_Request);
type Connect_Response is record
Action : Interfaces.Unsigned_32;
Transaction_Id : Interfaces.Unsigned_32;
Connection_Id : Interfaces.Unsigned_64;
end record;
for Connect_Response'Bit_Order use System.High_Order_First;
for Connect_Response'Scalar_Storage_Order use System.High_Order_First;
for Connect_Response use record
Action at 0 range 0 .. 31;
Transaction_Id at 4 range 0 .. 31;
Connection_Id at 8 range 0 .. 63;
end record;
function Cast is new Ada.Unchecked_Conversion
(Raw_Connect_Request, Connect_Response);
subtype IPV4_Address is Ada.Streams.Stream_Element_Array (1 .. 4);
pragma Warnings (Off, "scalar storage order specified for");
type Announce_Request is record
Connection_Id : Interfaces.Unsigned_64;
Action : Interfaces.Unsigned_32;
Transaction_Id : Interfaces.Unsigned_32;
Info_Hash : SHA1;
Peer_Id : SHA1;
Downloaded : Interfaces.Unsigned_64;
Left : Interfaces.Unsigned_64;
Uploaded : Interfaces.Unsigned_64;
Event : Interfaces.Unsigned_32;
IP_Address : IPV4_Address := (others => 0);
Key : Interfaces.Unsigned_32;
Num_Want : Interfaces.Unsigned_32 := Interfaces.Unsigned_32'Last;
Port : Interfaces.Unsigned_16;
end record;
for Announce_Request'Bit_Order use System.High_Order_First;
for Announce_Request'Scalar_Storage_Order use System.High_Order_First;
for Announce_Request use record
Connection_Id at 0 range 0 .. 63;
Action at 8 range 0 .. 31;
Transaction_Id at 12 range 0 .. 31;
Info_Hash at 16 range 0 .. 159;
Peer_Id at 36 range 0 .. 159;
Downloaded at 56 range 0 .. 63;
Left at 64 range 0 .. 63;
Uploaded at 72 range 0 .. 63;
Event at 80 range 0 .. 31;
IP_Address at 84 range 0 .. 31;
Key at 88 range 0 .. 31;
Num_Want at 92 range 0 .. 31;
Port at 96 range 0 .. 15;
end record;
subtype Raw_Announce_Request is Ada.Streams.Stream_Element_Array
(1 .. 98); -- Announce_Request'Max_Size_In_Storage_Elements
function Cast is new Ada.Unchecked_Conversion
(Announce_Request, Raw_Announce_Request);
Cast_Event : constant array (Torrent.Trackers.Announcement_Kind) of
Interfaces.Unsigned_32 :=
(Torrent.Trackers.Started => 2,
Torrent.Trackers.Completed => 1,
Torrent.Trackers.Stopped => 3,
Torrent.Trackers.Regular => 0);
type Announce_Response is record
Action : Interfaces.Unsigned_32;
Transaction_Id : Interfaces.Unsigned_32;
Interval : Interfaces.Unsigned_32;
Leechers : Interfaces.Unsigned_32;
Seeders : Interfaces.Unsigned_32;
end record;
for Announce_Response'Bit_Order use System.High_Order_First;
for Announce_Response'Scalar_Storage_Order use System.High_Order_First;
for Announce_Response use record
Action at 0 range 0 .. 31;
Transaction_Id at 4 range 0 .. 31;
Interval at 8 range 0 .. 31;
Leechers at 12 range 0 .. 31;
Seeders at 16 range 0 .. 31;
end record;
subtype Raw_Announce_Response is Ada.Streams.Stream_Element_Array
(1 .. Announce_Response'Max_Size_In_Storage_Elements);
function Cast is new Ada.Unchecked_Conversion
(Raw_Announce_Response, Announce_Response);
type Peer_Address is record
IP_Address : IPV4_Address;
Port : Interfaces.Unsigned_16;
end record;
for Peer_Address'Bit_Order use System.High_Order_First;
for Peer_Address'Scalar_Storage_Order use System.High_Order_First;
for Peer_Address use record
IP_Address at 0 range 0 .. 31;
Port at 4 range 0 .. 15;
end record;
subtype Raw_Peer_Address is Ada.Streams.Stream_Element_Array
(1 .. Peer_Address'Max_Size_In_Storage_Elements);
function Cast is new Ada.Unchecked_Conversion
(Raw_Peer_Address, Peer_Address);
end Torrent.UDP_Tracker_Protocol;
|
with Primes.PrimeNumberRequest_DataReader;
with Primes.PrimeNumberReply_DataWriter;
with DDS.Request_Reply.Replier.Typed_Replier_Generic;
package Primes.PrimeNumberReplier is new DDS.Request_Reply.Replier.Typed_Replier_Generic
(Request_DataReader => Primes.PrimeNumberRequest_DataReader,
Reply_DataWriter => Primes.PrimeNumberReply_DataWriter);
|
-- PACKAGE Cholesky_LU
--
-- Cholesky's algorithm for LU decomposition of Real positive-definite
-- square matrices. Positive definite matrices are a special class of
-- symmetric, non-singular matrices for which no pivioting is required
-- in LU decomposition. LU_decompose factors the matrix A into A = L*U,
-- where U = transpose(L). LU_Decompose writes over A with L and U.
-- U is upper triangular, and is placed in the upper triangular part of A.
--
-- The procedure does not test the matrix for positive definiteness.
-- (A good way to test for positive definiteness is to run LU_decompose
-- on it to see if Constraint_Error is raised.) All positive definite
-- matrices are symmetric and their central diagonals have no zero
-- valued elements or negative valued elements.
--
-- A square (N X N) matrix with elements of generic type Real
-- is input as "A" and returned in LU form. A must be symmetric. This
-- isn't tested. Instead only the lower triangle of A is read. It
-- is assumed that the upper triangle of A is the transpose of the lower.
--
-- The LU form of A can be used to solve simultaneous linear
-- equations of the form A*X = B. The column vector B is input
-- into procedure Solve, and the solution is returned as X.
--
generic
type Real is digits <>;
type Index is range <>;
-- Defines the maximum size that the matrix can be.
-- The maximum matrix will be (N X N) where
-- N = Index'Last - Index'First + 1. This is the storage
-- set aside for the matrix, but the user may use the routines
-- below on matrices of any size up to and including (N X N).
type Matrix is array(Index, Index) of Real;
-- Row major form is appropriate for Matrix * Col_Vector_Vector
-- operations, which dominate the algorithm in procedure Solve.
package Cholesky_LU is
type Row_Vector is array(Index) of Real;
subtype Col_Vector is Row_Vector;
procedure LU_Decompose
(A : in out Matrix; -- A is over-written with LU.
Diag_Inverse : out Col_Vector;
Final_Index : in Index := Index'Last;
Starting_Index : in Index := Index'First);
-- Destroys A and writes over it with the LU decomposition of A.
-- Only operates in range Starting_Index .. Final_Index.
-- A must be symmetric (not checked).
-- Constraint_Error is raised if A is not positive definite.
-- Constraint_Error is raised if evidence of singularity is detected.
-- In both cases this evidence may be due to numerical error.
procedure Solve
(X : out Col_Vector;
B : in Col_Vector;
A_LU : in Matrix;
Diag_Inverse : in Col_Vector;
Final_Index : in Index := Index'Last;
Starting_Index : in Index := Index'First);
-- Solves for X in the equation A*X = b. You enter the LU
-- decomposition of A, not A itself. A_Lu and Diag_Inverse are
-- the objects returned by LU_decompose.
function Product
(A : in Matrix;
X : in Col_Vector;
Final_Index : in Index := Index'Last;
Starting_Index : in Index := Index'First)
return Col_Vector;
-- Matrix vector multiplication.
function "-"(A, B : in Col_Vector) return Col_Vector;
private
Zero : constant Real := (+0.0);
One : constant Real := (+1.0);
Two : constant Real := (+2.0);
Min_Allowed_Real : constant Real := Two ** (Real'Machine_Emin + 4);
-- Must be positive. If pivots are found to be smaller than this, then
-- it is taken as evidence that the matrix is not postive definite,
-- and Constraint_Error is raised.
end Cholesky_LU;
|
with Ada.Integer_Text_IO;
with Ada.Text_IO;
package body Problem_19 is
package IO renames Ada.Text_IO;
package I_IO renames Ada.Integer_Text_IO;
procedure Solve is
type Day_Of_Week is mod 7;
type Year is new Positive range 1900 .. 2010;
current_day : Day_Of_Week := 1;
count : Natural := 0;
type Month_Count_Array is Array (1 .. 12) of Day_Of_Week;
Normal_Days_In_Month : aliased constant Month_Count_Array := (3, 0, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3);
Leap_Days_In_Month : aliased constant Month_Count_Array := (3, 1, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3);
Current_Days_In_Month : access constant Month_Count_Array;
procedure New_Year(current_year : in Year) is
begin
if (current_year mod 4 = 0 and current_year mod 100 /= 0) or (current_year mod 400 = 0) then
Current_Days_In_Month := Leap_Days_In_Month'Access;
else
Current_Days_In_Month := Normal_Days_In_Month'Access;
end if;
end;
begin
for current_year in year'Range loop
New_Year(current_year);
for month in 1 .. 12 loop
if current_day = 0 and current_year /= 1900 then
count := count + 1;
end if;
current_day := current_day + Current_Days_In_Month(month);
end loop;
end loop;
I_IO.Put(count);
IO.New_Line;
end Solve;
end Problem_19;
|
-----------------------------------------------------------------------
-- servlet-routes-tests - Unit tests for Servlet.Routes
-- Copyright (C) 2015, 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.Strings.Unbounded;
with Util.Tests;
with Util.Beans.Objects;
with Servlet.Tests;
package Servlet.Routes.Tests is
-- A test bean to verify the path parameter injection.
type Test_Bean is new Util.Beans.Basic.Bean with record
Id : Ada.Strings.Unbounded.Unbounded_String;
Name : Ada.Strings.Unbounded.Unbounded_String;
end record;
type Test_Bean_Access is access all Test_Bean;
overriding
function Get_Value (Bean : in Test_Bean;
Name : in String) return Util.Beans.Objects.Object;
overriding
procedure Set_Value (Bean : in out Test_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
MAX_TEST_ROUTES : constant Positive := 100;
type Test_Route_Type is new Route_Type with record
Index : Natural := 0;
end record;
type Test_Route_Type_Access is access Test_Route_Type;
type Test_Route_Array is array (1 .. MAX_TEST_ROUTES) of Route_Type_Ref;
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Servlet.Tests.EL_Test with record
Routes : Test_Route_Array;
Bean : Test_Bean_Access;
end record;
-- Setup the test instance.
overriding
procedure Set_Up (T : in out Test);
-- Verify that the path matches the given route.
procedure Verify_Route (T : in out Test;
Router : in out Router_Type;
Path : in String;
Index : in Positive;
Bean : in out Test_Bean'Class);
-- Add the route associted with the path pattern.
procedure Add_Route (T : in out Test;
Router : in out Router_Type;
Path : in String;
Index : in Positive;
Bean : in out Test_Bean'Class);
-- Test the Add_Route with "/".
procedure Test_Add_Route_With_Root_Path (T : in out Test);
-- Test the Add_Route with simple fixed path components.
-- Example: /list/index.html
procedure Test_Add_Route_With_Path (T : in out Test);
-- Test the Add_Route with extension mapping.
-- Example: /list/*.html
procedure Test_Add_Route_With_Ext (T : in out Test);
-- Test the Add_Route with fixed path components and path parameters.
-- Example: /users/:id/view.html
procedure Test_Add_Route_With_Param (T : in out Test);
-- Test the Add_Route with fixed path components and path parameters (Alternate syntax).
-- Example: /users/{id}/view.html
procedure Test_Add_Route_With_Param_Alt (T : in out Test);
-- Test the Add_Route with fixed path components and EL path injection.
-- Example: /users/#{user.id}/view.html
procedure Test_Add_Route_With_EL (T : in out Test);
-- Test the Iterate over several paths.
procedure Test_Iterate (T : in out Test);
end Servlet.Routes.Tests;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Localization, Internationalization, Globalization for Ada --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2013-2014, Vadim Godunko <vgodunko@gmail.com> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with League.JSON.Documents.Internals;
with League.JSON.Values.Internals;
with Matreshka.JSON_Documents;
package body League.JSON.Arrays is
package Array_Iterable_Holder_Cursors is
type Cursor is new League.Holders.Iterable_Holder_Cursors.Cursor
with record
Data : JSON_Array;
Index : Natural := 0;
end record;
overriding function Next (Self : in out Cursor) return Boolean;
overriding function Element (Self : Cursor) return League.Holders.Holder;
end Array_Iterable_Holder_Cursors;
package body Array_Iterable_Holder_Cursors is
-------------
-- Element --
-------------
overriding function Element
(Self : Cursor) return League.Holders.Holder is
begin
return League.JSON.Values.To_Holder
(Self.Data.Element (Self.Index));
end Element;
----------
-- Next --
----------
overriding function Next (Self : in out Cursor) return Boolean is
begin
Self.Index := Self.Index + 1;
-- There is no corresponding value for 'null' JSON value, so stop
-- iteration if we found a such value.
return Self.Index <= Self.Data.Length
and then Self.Data.Element (Self.Index).Kind not in
League.JSON.Values.Null_Value;
end Next;
end Array_Iterable_Holder_Cursors;
------------
-- Adjust --
------------
overriding procedure Adjust (Self : in out JSON_Array) is
begin
Matreshka.JSON_Types.Reference (Self.Data);
end Adjust;
------------
-- Append --
------------
procedure Append
(Self : in out JSON_Array'Class; Value : League.JSON.Values.JSON_Value)
is
Aux : constant Matreshka.JSON_Types.Shared_JSON_Value_Access
:= League.JSON.Values.Internals.Internal (Value);
begin
Matreshka.JSON_Types.Mutate (Self.Data);
Matreshka.JSON_Types.Reference (Aux);
Self.Data.Values.Append (Aux);
end Append;
------------
-- Delete --
------------
procedure Delete (Self : in out JSON_Array'Class; Index : Positive) is
Aux : Matreshka.JSON_Types.Shared_JSON_Value_Access;
begin
if Index
in Self.Data.Values.First_Index .. Self.Data.Values.Last_Index
then
Matreshka.JSON_Types.Mutate (Self.Data);
Aux := Self.Data.Values.Element (Index);
Self.Data.Values.Delete (Index);
Matreshka.JSON_Types.Dereference (Aux);
end if;
end Delete;
------------------
-- Delete_First --
------------------
procedure Delete_First (Self : in out JSON_Array'Class) is
Aux : Matreshka.JSON_Types.Shared_JSON_Value_Access;
begin
if not Self.Data.Values.Is_Empty then
Matreshka.JSON_Types.Mutate (Self.Data);
Aux := Self.Data.Values.First_Element;
Self.Data.Values.Delete_First;
Matreshka.JSON_Types.Dereference (Aux);
end if;
end Delete_First;
-----------------
-- Delete_Last --
-----------------
procedure Delete_Last (Self : in out JSON_Array'Class) is
Aux : Matreshka.JSON_Types.Shared_JSON_Value_Access;
begin
if not Self.Data.Values.Is_Empty then
Matreshka.JSON_Types.Mutate (Self.Data);
Aux := Self.Data.Values.Last_Element;
Self.Data.Values.Delete_Last;
Matreshka.JSON_Types.Dereference (Aux);
end if;
end Delete_Last;
-------------
-- Element --
-------------
function Element
(Self : JSON_Array'Class;
Index : Positive) return League.JSON.Values.JSON_Value is
begin
if Index
in Self.Data.Values.First_Index .. Self.Data.Values.Last_Index
then
return
League.JSON.Values.Internals.Create
(Self.Data.Values.Element (Index));
else
return League.JSON.Values.Empty_JSON_Value;
end if;
end Element;
--------------
-- Finalize --
--------------
overriding procedure Finalize (Self : in out JSON_Array) is
use type Matreshka.JSON_Types.Shared_JSON_Array_Access;
begin
if Self.Data /= null then
Matreshka.JSON_Types.Dereference (Self.Data);
end if;
end Finalize;
-----------
-- First --
-----------
function First
(Self : aliased JSON_Array)
return League.Holders.Iterable_Holder_Cursors.Cursor'Class is
begin
return Array_Iterable_Holder_Cursors.Cursor'(Self, 0);
end First;
-------------------
-- First_Element --
-------------------
function First_Element
(Self : JSON_Array'Class) return League.JSON.Values.JSON_Value is
begin
if not Self.Data.Values.Is_Empty then
return
League.JSON.Values.Internals.Create
(Self.Data.Values.First_Element);
else
return League.JSON.Values.Empty_JSON_Value;
end if;
end First_Element;
------------
-- Insert --
------------
procedure Insert
(Self : in out JSON_Array'Class;
Index : Positive;
Value : League.JSON.Values.JSON_Value)
is
Aux : constant Matreshka.JSON_Types.Shared_JSON_Value_Access
:= League.JSON.Values.Internals.Internal (Value);
begin
if Index
in Self.Data.Values.First_Index .. Self.Data.Values.Last_Index
then
Matreshka.JSON_Types.Mutate (Self.Data);
Matreshka.JSON_Types.Reference (Aux);
Self.Data.Values.Insert (Index, Aux);
end if;
end Insert;
--------------
-- Is_Empty --
--------------
function Is_Empty (Self : JSON_Array'Class) return Boolean is
begin
return Self.Data.Values.Is_Empty;
end Is_Empty;
------------------
-- Last_Element --
------------------
function Last_Element
(Self : JSON_Array'Class) return League.JSON.Values.JSON_Value is
begin
if not Self.Data.Values.Is_Empty then
return
League.JSON.Values.Internals.Create (Self.Data.Values.Last_Element);
else
return League.JSON.Values.Empty_JSON_Value;
end if;
end Last_Element;
------------
-- Length --
------------
function Length (Self : JSON_Array'Class) return Natural is
begin
return Natural (Self.Data.Values.Length);
end Length;
-------------
-- Prepend --
-------------
procedure Prepend
(Self : in out JSON_Array'Class; Value : League.JSON.Values.JSON_Value)
is
Aux : constant Matreshka.JSON_Types.Shared_JSON_Value_Access
:= League.JSON.Values.Internals.Internal (Value);
begin
Matreshka.JSON_Types.Mutate (Self.Data);
Matreshka.JSON_Types.Reference (Aux);
Self.Data.Values.Prepend (Aux);
end Prepend;
-------------
-- Replace --
-------------
procedure Replace
(Self : in out JSON_Array'Class;
Index : Positive;
Value : League.JSON.Values.JSON_Value)
is
New_Value : constant Matreshka.JSON_Types.Shared_JSON_Value_Access
:= League.JSON.Values.Internals.Internal (Value);
Old_Value : Matreshka.JSON_Types.Shared_JSON_Value_Access;
begin
if Index
in Self.Data.Values.First_Index .. Self.Data.Values.Last_Index
then
Matreshka.JSON_Types.Mutate (Self.Data);
Matreshka.JSON_Types.Reference (New_Value);
Old_Value := Self.Data.Values.Element (Index);
Self.Data.Values.Replace_Element (Index, New_Value);
Matreshka.JSON_Types.Dereference (Old_Value);
end if;
end Replace;
----------
-- Take --
----------
function Take
(Self : in out JSON_Array'Class;
Index : Positive) return League.JSON.Values.JSON_Value
is
Old_Value : Matreshka.JSON_Types.Shared_JSON_Value_Access;
begin
if Index
in Self.Data.Values.First_Index .. Self.Data.Values.Last_Index
then
Matreshka.JSON_Types.Mutate (Self.Data);
Old_Value := Self.Data.Values.Element (Index);
Self.Data.Values.Delete (Index);
return League.JSON.Values.Internals.Wrap (Old_Value);
else
return League.JSON.Values.Empty_JSON_Value;
end if;
end Take;
----------------------
-- To_JSON_Document --
----------------------
function To_JSON_Document
(Self : JSON_Array'Class) return League.JSON.Documents.JSON_Document is
begin
Matreshka.JSON_Types.Reference (Self.Data);
return
League.JSON.Documents.Internals.Wrap
(new Matreshka.JSON_Documents.Shared_JSON_Document'
(Counter => <>,
Array_Value => Self.Data,
Object_Value => null));
end To_JSON_Document;
-------------------
-- To_JSON_Value --
-------------------
function To_JSON_Value
(Self : JSON_Array'Class) return League.JSON.Values.JSON_Value is
begin
Matreshka.JSON_Types.Reference (Self.Data);
return
League.JSON.Values.Internals.Wrap
(new Matreshka.JSON_Types.Shared_JSON_Value'
(Counter => <>,
Value =>
(Kind => Matreshka.JSON_Types.Array_Value,
Array_Value => Self.Data)));
end To_JSON_Value;
end League.JSON.Arrays;
|
with Ada.Numerics.Generic_Real_Arrays;
generic
type Real is digits <>;
package Thiele is
package Real_Arrays is new Ada.Numerics.Generic_Real_Arrays (Real);
subtype Real_Array is Real_Arrays.Real_Vector;
type Thiele_Interpolation (Length : Natural) is private;
function Create (X, Y : Real_Array) return Thiele_Interpolation;
function Inverse (T : Thiele_Interpolation; X : Real) return Real;
private
type Thiele_Interpolation (Length : Natural) is record
X, Y, RhoX : Real_Array (1 .. Length);
end record;
end Thiele;
|
-- part of OpenGLAda, (c) 2017 Felix Krause
-- released under the terms of the MIT license, see the file "COPYING"
private with Ada.Containers.Hashed_Maps;
private with Ada.Finalization;
with FT.Faces;
with GL.Objects.Textures;
private with GL.Objects.Vertex_Arrays;
private with GL.Objects.Buffers;
private with GL.Objects.Programs;
with GL.Types.Colors;
private with GL.Uniforms;
package GL.Text is
Rendering_Error : exception;
-- This type holds a reference to the compiled shader program used to render
-- text as bitmaps. It needs to be created once and can be shared amongst
-- all renderers. The shader program can only be initialized once the target
-- OpenGL context has been created.
--
-- Since this type only holds references to OpenGL objects, it has reference
-- semantics when copying; the references are automatically
-- reference-counted.
type Shader_Program_Reference is private;
-- A renderer instance needs to be created for each font family, size and
-- variant you want to render. A renderer renders text to a monochrome
-- texture which can then be used als alpha-channel to render the text with
-- arbitrary color / texture to the screen.
type Renderer_Reference is tagged private;
subtype UTF_8_String is String;
type Pixel_Difference is new Interfaces.C.int;
subtype Pixel_Size is Pixel_Difference range 0 .. Pixel_Difference'Last;
-- Compiles the necessary shaders and links them into a program. OpenGL
-- context must be initialized before creating the program!
procedure Create (Object : in out Shader_Program_Reference);
-- Returns True iff Create has been called successfully on the given
-- object.
function Created (Object : Shader_Program_Reference) return Boolean;
-- Creates a renderer that renders the font face given by Face.
procedure Create (Object : in out Renderer_Reference;
Program : Shader_Program_Reference;
Face : FT.Faces.Face_Reference);
-- Creates a renderer that renders the font face at Face_Index in the
-- font file specified by Font_Path with the pixel size given by Size.
procedure Create (Object : in out Renderer_Reference;
Program : Shader_Program_Reference;
Font_Path : String;
Face_Index : FT.Faces.Face_Index_Type;
Size : Pixel_Size);
-- Returns True iff Create has been called successfully on the given
-- object.
function Created (Object : Renderer_Reference) return Boolean;
procedure Calculate_Dimensions (Object : Renderer_Reference;
Content : UTF_8_String;
Width : out Pixel_Size;
Y_Min : out Pixel_Difference;
Y_Max : out Pixel_Size);
function To_Texture (Object : Renderer_Reference; Content : UTF_8_String;
Text_Color : GL.Types.Colors.Color)
return GL.Objects.Textures.Texture;
function To_Texture (Object : Renderer_Reference; Content : UTF_8_String;
Width, Y_Min, Y_Max : Pixel_Difference;
Text_Color : GL.Types.Colors.Color)
return GL.Objects.Textures.Texture;
private
type Shader_Program_Reference is record
Id : GL.Objects.Programs.Program;
Info_Id, Texture_Id, Color_Id, Transform_Id : GL.Uniforms.Uniform;
Square_Array : GL.Objects.Vertex_Arrays.Vertex_Array_Object;
Square_Buffer : GL.Objects.Buffers.Buffer;
end record;
type Loaded_Character is record
Width, Y_Min, Y_Max, Advance, Left : Pixel_Difference;
Image : GL.Objects.Textures.Texture;
end record;
function Hash (Value : FT.ULong) return Ada.Containers.Hash_Type;
package Loaded_Characters is new Ada.Containers.Hashed_Maps
(FT.ULong, Loaded_Character, Hash, Interfaces.C."=");
type Renderer_Data is record
Face : FT.Faces.Face_Reference;
Refcount : Natural := 1;
Characters : Loaded_Characters.Map;
Program : Shader_Program_Reference;
end record;
type Pointer is access Renderer_Data;
type Renderer_Reference is new Ada.Finalization.Controlled with record
Data : Pointer;
end record;
overriding procedure Adjust (Object : in out Renderer_Reference);
overriding procedure Finalize (Object : in out Renderer_Reference);
end GL.Text;
|
-- This spec has been automatically generated from STM32F103.svd
pragma Restrictions (No_Elaboration_Code);
pragma Ada_2012;
pragma Style_Checks (Off);
with HAL;
with System;
package STM32_SVD.BKP is
pragma Preelaborate;
---------------
-- Registers --
---------------
subtype DR1_D1_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR1_Register is record
-- Backup data
D1 : DR1_D1_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR1_Register use record
D1 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR2_D2_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR2_Register is record
-- Backup data
D2 : DR2_D2_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR2_Register use record
D2 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR3_D3_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR3_Register is record
-- Backup data
D3 : DR3_D3_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR3_Register use record
D3 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR4_D4_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR4_Register is record
-- Backup data
D4 : DR4_D4_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR4_Register use record
D4 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR5_D5_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR5_Register is record
-- Backup data
D5 : DR5_D5_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR5_Register use record
D5 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR6_D6_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR6_Register is record
-- Backup data
D6 : DR6_D6_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR6_Register use record
D6 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR7_D7_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR7_Register is record
-- Backup data
D7 : DR7_D7_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR7_Register use record
D7 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR8_D8_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR8_Register is record
-- Backup data
D8 : DR8_D8_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR8_Register use record
D8 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR9_D9_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR9_Register is record
-- Backup data
D9 : DR9_D9_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR9_Register use record
D9 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR10_D10_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR10_Register is record
-- Backup data
D10 : DR10_D10_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR10_Register use record
D10 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype RTCCR_CAL_Field is HAL.UInt7;
-- RTC clock calibration register (BKP_RTCCR)
type RTCCR_Register is record
-- Calibration value
CAL : RTCCR_CAL_Field := 16#0#;
-- Calibration Clock Output
CCO : Boolean := False;
-- Alarm or second output enable
ASOE : Boolean := False;
-- Alarm or second output selection
ASOS : Boolean := False;
-- unspecified
Reserved_10_31 : HAL.UInt22 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for RTCCR_Register use record
CAL at 0 range 0 .. 6;
CCO at 0 range 7 .. 7;
ASOE at 0 range 8 .. 8;
ASOS at 0 range 9 .. 9;
Reserved_10_31 at 0 range 10 .. 31;
end record;
-- Backup control register (BKP_CR)
type CR_Register is record
-- Tamper pin enable
TPE : Boolean := False;
-- Tamper pin active level
TPAL : Boolean := False;
-- unspecified
Reserved_2_31 : HAL.UInt30 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for CR_Register use record
TPE at 0 range 0 .. 0;
TPAL at 0 range 1 .. 1;
Reserved_2_31 at 0 range 2 .. 31;
end record;
-- BKP_CSR control/status register (BKP_CSR)
type CSR_Register is record
-- Write-only. Clear Tamper event
CTE : Boolean := False;
-- Write-only. Clear Tamper Interrupt
CTI : Boolean := False;
-- Tamper Pin interrupt enable
TPIE : Boolean := False;
-- unspecified
Reserved_3_7 : HAL.UInt5 := 16#0#;
-- Read-only. Tamper Event Flag
TEF : Boolean := False;
-- Read-only. Tamper Interrupt Flag
TIF : Boolean := False;
-- unspecified
Reserved_10_31 : HAL.UInt22 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for CSR_Register use record
CTE at 0 range 0 .. 0;
CTI at 0 range 1 .. 1;
TPIE at 0 range 2 .. 2;
Reserved_3_7 at 0 range 3 .. 7;
TEF at 0 range 8 .. 8;
TIF at 0 range 9 .. 9;
Reserved_10_31 at 0 range 10 .. 31;
end record;
subtype DR11_DR11_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR11_Register is record
-- Backup data
DR11 : DR11_DR11_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR11_Register use record
DR11 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR12_DR12_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR12_Register is record
-- Backup data
DR12 : DR12_DR12_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR12_Register use record
DR12 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR13_DR13_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR13_Register is record
-- Backup data
DR13 : DR13_DR13_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR13_Register use record
DR13 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR14_D14_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR14_Register is record
-- Backup data
D14 : DR14_D14_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR14_Register use record
D14 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR15_D15_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR15_Register is record
-- Backup data
D15 : DR15_D15_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR15_Register use record
D15 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR16_D16_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR16_Register is record
-- Backup data
D16 : DR16_D16_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR16_Register use record
D16 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR17_D17_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR17_Register is record
-- Backup data
D17 : DR17_D17_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR17_Register use record
D17 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR18_D18_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR18_Register is record
-- Backup data
D18 : DR18_D18_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR18_Register use record
D18 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR19_D19_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR19_Register is record
-- Backup data
D19 : DR19_D19_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR19_Register use record
D19 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR20_D20_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR20_Register is record
-- Backup data
D20 : DR20_D20_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR20_Register use record
D20 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR21_D21_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR21_Register is record
-- Backup data
D21 : DR21_D21_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR21_Register use record
D21 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR22_D22_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR22_Register is record
-- Backup data
D22 : DR22_D22_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR22_Register use record
D22 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR23_D23_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR23_Register is record
-- Backup data
D23 : DR23_D23_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR23_Register use record
D23 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR24_D24_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR24_Register is record
-- Backup data
D24 : DR24_D24_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR24_Register use record
D24 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR25_D25_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR25_Register is record
-- Backup data
D25 : DR25_D25_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR25_Register use record
D25 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR26_D26_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR26_Register is record
-- Backup data
D26 : DR26_D26_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR26_Register use record
D26 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR27_D27_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR27_Register is record
-- Backup data
D27 : DR27_D27_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR27_Register use record
D27 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR28_D28_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR28_Register is record
-- Backup data
D28 : DR28_D28_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR28_Register use record
D28 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR29_D29_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR29_Register is record
-- Backup data
D29 : DR29_D29_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR29_Register use record
D29 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR30_D30_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR30_Register is record
-- Backup data
D30 : DR30_D30_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR30_Register use record
D30 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR31_D31_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR31_Register is record
-- Backup data
D31 : DR31_D31_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR31_Register use record
D31 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR32_D32_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR32_Register is record
-- Backup data
D32 : DR32_D32_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR32_Register use record
D32 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR33_D33_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR33_Register is record
-- Backup data
D33 : DR33_D33_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR33_Register use record
D33 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR34_D34_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR34_Register is record
-- Backup data
D34 : DR34_D34_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR34_Register use record
D34 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR35_D35_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR35_Register is record
-- Backup data
D35 : DR35_D35_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR35_Register use record
D35 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR36_D36_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR36_Register is record
-- Backup data
D36 : DR36_D36_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR36_Register use record
D36 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR37_D37_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR37_Register is record
-- Backup data
D37 : DR37_D37_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR37_Register use record
D37 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR38_D38_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR38_Register is record
-- Backup data
D38 : DR38_D38_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR38_Register use record
D38 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR39_D39_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR39_Register is record
-- Backup data
D39 : DR39_D39_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR39_Register use record
D39 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR40_D40_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR40_Register is record
-- Backup data
D40 : DR40_D40_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR40_Register use record
D40 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR41_D41_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR41_Register is record
-- Backup data
D41 : DR41_D41_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR41_Register use record
D41 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype DR42_D42_Field is HAL.UInt16;
-- Backup data register (BKP_DR)
type DR42_Register is record
-- Backup data
D42 : DR42_D42_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DR42_Register use record
D42 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
-----------------
-- Peripherals --
-----------------
-- Backup registers
type BKP_Peripheral is record
-- Backup data register (BKP_DR)
DR1 : aliased DR1_Register;
-- Backup data register (BKP_DR)
DR2 : aliased DR2_Register;
-- Backup data register (BKP_DR)
DR3 : aliased DR3_Register;
-- Backup data register (BKP_DR)
DR4 : aliased DR4_Register;
-- Backup data register (BKP_DR)
DR5 : aliased DR5_Register;
-- Backup data register (BKP_DR)
DR6 : aliased DR6_Register;
-- Backup data register (BKP_DR)
DR7 : aliased DR7_Register;
-- Backup data register (BKP_DR)
DR8 : aliased DR8_Register;
-- Backup data register (BKP_DR)
DR9 : aliased DR9_Register;
-- Backup data register (BKP_DR)
DR10 : aliased DR10_Register;
-- RTC clock calibration register (BKP_RTCCR)
RTCCR : aliased RTCCR_Register;
-- Backup control register (BKP_CR)
CR : aliased CR_Register;
-- BKP_CSR control/status register (BKP_CSR)
CSR : aliased CSR_Register;
-- Backup data register (BKP_DR)
DR11 : aliased DR11_Register;
-- Backup data register (BKP_DR)
DR12 : aliased DR12_Register;
-- Backup data register (BKP_DR)
DR13 : aliased DR13_Register;
-- Backup data register (BKP_DR)
DR14 : aliased DR14_Register;
-- Backup data register (BKP_DR)
DR15 : aliased DR15_Register;
-- Backup data register (BKP_DR)
DR16 : aliased DR16_Register;
-- Backup data register (BKP_DR)
DR17 : aliased DR17_Register;
-- Backup data register (BKP_DR)
DR18 : aliased DR18_Register;
-- Backup data register (BKP_DR)
DR19 : aliased DR19_Register;
-- Backup data register (BKP_DR)
DR20 : aliased DR20_Register;
-- Backup data register (BKP_DR)
DR21 : aliased DR21_Register;
-- Backup data register (BKP_DR)
DR22 : aliased DR22_Register;
-- Backup data register (BKP_DR)
DR23 : aliased DR23_Register;
-- Backup data register (BKP_DR)
DR24 : aliased DR24_Register;
-- Backup data register (BKP_DR)
DR25 : aliased DR25_Register;
-- Backup data register (BKP_DR)
DR26 : aliased DR26_Register;
-- Backup data register (BKP_DR)
DR27 : aliased DR27_Register;
-- Backup data register (BKP_DR)
DR28 : aliased DR28_Register;
-- Backup data register (BKP_DR)
DR29 : aliased DR29_Register;
-- Backup data register (BKP_DR)
DR30 : aliased DR30_Register;
-- Backup data register (BKP_DR)
DR31 : aliased DR31_Register;
-- Backup data register (BKP_DR)
DR32 : aliased DR32_Register;
-- Backup data register (BKP_DR)
DR33 : aliased DR33_Register;
-- Backup data register (BKP_DR)
DR34 : aliased DR34_Register;
-- Backup data register (BKP_DR)
DR35 : aliased DR35_Register;
-- Backup data register (BKP_DR)
DR36 : aliased DR36_Register;
-- Backup data register (BKP_DR)
DR37 : aliased DR37_Register;
-- Backup data register (BKP_DR)
DR38 : aliased DR38_Register;
-- Backup data register (BKP_DR)
DR39 : aliased DR39_Register;
-- Backup data register (BKP_DR)
DR40 : aliased DR40_Register;
-- Backup data register (BKP_DR)
DR41 : aliased DR41_Register;
-- Backup data register (BKP_DR)
DR42 : aliased DR42_Register;
end record
with Volatile;
for BKP_Peripheral use record
DR1 at 16#0# range 0 .. 31;
DR2 at 16#4# range 0 .. 31;
DR3 at 16#8# range 0 .. 31;
DR4 at 16#C# range 0 .. 31;
DR5 at 16#10# range 0 .. 31;
DR6 at 16#14# range 0 .. 31;
DR7 at 16#18# range 0 .. 31;
DR8 at 16#1C# range 0 .. 31;
DR9 at 16#20# range 0 .. 31;
DR10 at 16#24# range 0 .. 31;
RTCCR at 16#28# range 0 .. 31;
CR at 16#2C# range 0 .. 31;
CSR at 16#30# range 0 .. 31;
DR11 at 16#3C# range 0 .. 31;
DR12 at 16#40# range 0 .. 31;
DR13 at 16#44# range 0 .. 31;
DR14 at 16#48# range 0 .. 31;
DR15 at 16#4C# range 0 .. 31;
DR16 at 16#50# range 0 .. 31;
DR17 at 16#54# range 0 .. 31;
DR18 at 16#58# range 0 .. 31;
DR19 at 16#5C# range 0 .. 31;
DR20 at 16#60# range 0 .. 31;
DR21 at 16#64# range 0 .. 31;
DR22 at 16#68# range 0 .. 31;
DR23 at 16#6C# range 0 .. 31;
DR24 at 16#70# range 0 .. 31;
DR25 at 16#74# range 0 .. 31;
DR26 at 16#78# range 0 .. 31;
DR27 at 16#7C# range 0 .. 31;
DR28 at 16#80# range 0 .. 31;
DR29 at 16#84# range 0 .. 31;
DR30 at 16#88# range 0 .. 31;
DR31 at 16#8C# range 0 .. 31;
DR32 at 16#90# range 0 .. 31;
DR33 at 16#94# range 0 .. 31;
DR34 at 16#98# range 0 .. 31;
DR35 at 16#9C# range 0 .. 31;
DR36 at 16#A0# range 0 .. 31;
DR37 at 16#A4# range 0 .. 31;
DR38 at 16#A8# range 0 .. 31;
DR39 at 16#AC# range 0 .. 31;
DR40 at 16#B0# range 0 .. 31;
DR41 at 16#B4# range 0 .. 31;
DR42 at 16#B8# range 0 .. 31;
end record;
-- Backup registers
BKP_Periph : aliased BKP_Peripheral
with Import, Address => System'To_Address (16#40006C00#);
end STM32_SVD.BKP;
|
--
-- Copyright (c) 2007-2009 Tero Koskinen <tero.koskinen@iki.fi>
--
-- Permission to use, copy, modify, and distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
--
with Ada.Unchecked_Deallocation;
package body Ahven.Results is
use Ahven.Results.Result_List;
use Ahven.Results.Result_Info_List;
-- Bunch of setters and getters.
-- The implementation is straightforward.
procedure Set_Test_Name (Info : in out Result_Info;
Name : Bounded_String) is
begin
Info.Test_Name := Name;
end Set_Test_Name;
procedure Set_Routine_Name (Info : in out Result_Info;
Name : Bounded_String) is
begin
Info.Routine_Name := Name;
end Set_Routine_Name;
procedure Set_Message (Info : in out Result_Info;
Message : Bounded_String) is
begin
Info.Message := Message;
end Set_Message;
procedure Set_Test_Name (Info : in out Result_Info; Name : String) is
begin
Set_Test_Name (Info, To_Bounded_String (Name));
end Set_Test_Name;
procedure Set_Routine_Name (Info : in out Result_Info; Name : String) is
begin
Set_Routine_Name (Info, To_Bounded_String (Name));
end Set_Routine_Name;
procedure Set_Message (Info : in out Result_Info; Message : String) is
begin
Set_Message (Info, To_Bounded_String (Message));
end Set_Message;
procedure Set_Long_Message (Info : in out Result_Info;
Message : Bounded_String) is
begin
Set_Long_Message (Info, To_String (Message));
end Set_Long_Message;
procedure Set_Long_Message
(Info : in out Result_Info;
Message : Long_AStrings.Bounded_String) is
begin
Info.Long_Message := Message;
end Set_Long_Message;
procedure Set_Long_Message (Info : in out Result_Info; Message : String) is
begin
Set_Long_Message (Info, Long_AStrings.To_Bounded_String (Message));
end Set_Long_Message;
procedure Set_Execution_Time (Info : in out Result_Info;
Elapsed_Time : Duration) is
begin
Info.Execution_Time := Elapsed_Time;
end Set_Execution_Time;
procedure Set_Output_File (Info : in out Result_Info;
Filename : Bounded_String) is
begin
Info.Output_File := Filename;
end Set_Output_File;
procedure Set_Output_File (Info : in out Result_Info;
Filename : String) is
begin
Set_Output_File (Info, To_Bounded_String (Filename));
end Set_Output_File;
function Get_Test_Name (Info : Result_Info) return String is
begin
return To_String (Info.Test_Name);
end Get_Test_Name;
function Get_Routine_Name (Info : Result_Info) return String is
begin
return To_String (Info.Routine_Name);
end Get_Routine_Name;
function Get_Message (Info : Result_Info) return String is
begin
return To_String (Info.Message);
end Get_Message;
function Get_Long_Message (Info : Result_Info) return String is
begin
return Long_AStrings.To_String (Info.Long_Message);
end Get_Long_Message;
function Get_Execution_Time (Info : Result_Info) return Duration is
begin
return Info.Execution_Time;
end Get_Execution_Time;
function Get_Output_File (Info : Result_Info) return Bounded_String is
begin
return Info.Output_File;
end Get_Output_File;
procedure Add_Child (Collection : in out Result_Collection;
Child : Result_Collection_Access) is
begin
Append (Collection.Children, (Ptr => Child));
end Add_Child;
procedure Add_Error (Collection : in out Result_Collection;
Info : Result_Info) is
begin
Append (Collection.Errors, Info);
end Add_Error;
procedure Add_Skipped (Collection : in out Result_Collection;
Info : Result_Info) is
begin
Append (Collection.Skips, Info);
end Add_Skipped;
procedure Add_Failure (Collection : in out Result_Collection;
Info : Result_Info) is
begin
Append (Collection.Failures, Info);
end Add_Failure;
procedure Add_Pass (Collection : in out Result_Collection;
Info : Result_Info) is
begin
Append (Collection.Passes, Info);
end Add_Pass;
-- When Result_Collection is released, it recursively releases
-- its all children.
procedure Release (Collection : in out Result_Collection) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Result_Collection,
Name => Result_Collection_Access);
Position : Result_List.Cursor := First (Collection.Children);
Ptr : Result_Collection_Access := null;
begin
loop
exit when not Is_Valid (Position);
Ptr := Data (Position).Ptr;
Release (Ptr.all);
Free (Ptr);
Position := Next (Position);
end loop;
Clear (Collection.Children);
-- No need to call Free for these three since
-- they are stored as plain objects instead of pointers.
Clear (Collection.Errors);
Clear (Collection.Failures);
Clear (Collection.Passes);
end Release;
procedure Set_Name (Collection : in out Result_Collection;
Name : Bounded_String) is
begin
Collection.Test_Name := Name;
end Set_Name;
procedure Set_Parent (Collection : in out Result_Collection;
Parent : Result_Collection_Access) is
begin
Collection.Parent := Parent;
end Set_Parent;
function Test_Count (Collection : Result_Collection) return Natural is
Count : Natural := Result_Info_List.Length (Collection.Errors) +
Result_Info_List.Length (Collection.Failures) +
Result_Info_List.Length (Collection.Skips) +
Result_Info_List.Length (Collection.Passes);
Position : Result_List.Cursor := First (Collection.Children);
begin
loop
exit when not Is_Valid (Position);
Count := Count + Test_Count (Data (Position).Ptr.all);
Position := Next (Position);
end loop;
return Count;
end Test_Count;
function Direct_Test_Count (Collection : Result_Collection)
return Natural
is
begin
return Length (Collection.Errors) +
Length (Collection.Failures) +
Length (Collection.Passes);
end Direct_Test_Count;
function Pass_Count (Collection : Result_Collection) return Natural is
Count : Natural := Length (Collection.Passes);
Position : Result_List.Cursor := First (Collection.Children);
begin
loop
exit when not Is_Valid (Position);
Count := Count + Pass_Count (Data (Position).Ptr.all);
Position := Next (Position);
end loop;
return Count;
end Pass_Count;
function Error_Count (Collection : Result_Collection) return Natural is
Count : Natural := Length (Collection.Errors);
Position : Result_List.Cursor := First (Collection.Children);
begin
loop
exit when not Is_Valid (Position);
Count := Count + Error_Count (Data (Position).Ptr.all);
Position := Next (Position);
end loop;
return Count;
end Error_Count;
function Failure_Count (Collection : Result_Collection) return Natural is
Count : Natural := Length (Collection.Failures);
Position : Result_List.Cursor := First (Collection.Children);
begin
loop
exit when not Is_Valid (Position);
Count := Count + Failure_Count (Data (Position).Ptr.all);
Position := Next (Position);
end loop;
return Count;
end Failure_Count;
function Skipped_Count (Collection : Result_Collection) return Natural is
Count : Natural := Length (Collection.Skips);
Position : Result_List.Cursor := First (Collection.Children);
begin
loop
exit when not Is_Valid (Position);
Count := Count + Skipped_Count (Data (Position).Ptr.all);
Position := Next (Position);
end loop;
return Count;
end Skipped_Count;
function Get_Test_Name (Collection : Result_Collection)
return Bounded_String is
begin
return Collection.Test_Name;
end Get_Test_Name;
function Get_Parent (Collection : Result_Collection)
return Result_Collection_Access is
begin
return Collection.Parent;
end Get_Parent;
function Get_Execution_Time (Collection : Result_Collection)
return Duration
is
Position : Result_Info_List.Cursor;
Total_Time : Duration := 0.0;
Child_Position : Result_List.Cursor;
begin
Position := First (Collection.Passes);
Pass_Loop :
loop
exit Pass_Loop when not Is_Valid (Position);
Total_Time := Total_Time + Get_Execution_Time (Data (Position));
Position := Next (Position);
end loop Pass_Loop;
Position := First (Collection.Failures);
Failure_Loop :
loop
exit Failure_Loop when not Is_Valid (Position);
Total_Time := Total_Time + Get_Execution_Time (Data (Position));
Position := Next (Position);
end loop Failure_Loop;
Position := First (Collection.Errors);
Error_Loop :
loop
exit Error_Loop when not Is_Valid (Position);
Total_Time := Total_Time + Get_Execution_Time (Data (Position));
Position := Next (Position);
end loop Error_Loop;
Child_Loop :
loop
exit Child_Loop when not Result_List.Is_Valid (Child_Position);
Total_Time := Total_Time +
Get_Execution_Time
(Result_List.Data (Child_Position).Ptr.all);
Child_Position := Result_List.Next (Child_Position);
end loop Child_Loop;
return Total_Time;
end Get_Execution_Time;
function First_Pass (Collection : Result_Collection)
return Result_Info_Cursor is
begin
return First (Collection.Passes);
end First_Pass;
function First_Failure (Collection : Result_Collection)
return Result_Info_Cursor is
begin
return First (Collection.Failures);
end First_Failure;
function First_Skipped (Collection : Result_Collection)
return Result_Info_Cursor is
begin
return First (Collection.Skips);
end First_Skipped;
function First_Error (Collection : Result_Collection)
return Result_Info_Cursor is
begin
return First (Collection.Errors);
end First_Error;
function Next (Position : Result_Info_Cursor) return Result_Info_Cursor is
begin
return Result_Info_Cursor
(Result_Info_List.Next (Result_Info_List.Cursor (Position)));
end Next;
function Data (Position : Result_Info_Cursor) return Result_Info is
begin
return Result_Info_List.Data (Result_Info_List.Cursor (Position));
end Data;
function Is_Valid (Position : Result_Info_Cursor) return Boolean is
begin
return Result_Info_List.Is_Valid (Result_Info_List.Cursor (Position));
end Is_Valid;
function First_Child (Collection : in Result_Collection)
return Result_Collection_Cursor is
begin
return First (Collection.Children);
end First_Child;
function Next (Position : Result_Collection_Cursor)
return Result_Collection_Cursor is
begin
return Result_Collection_Cursor
(Result_List.Next (Result_List.Cursor (Position)));
end Next;
function Is_Valid (Position : Result_Collection_Cursor) return Boolean is
begin
return Result_List.Is_Valid (Result_List.Cursor (Position));
end Is_Valid;
function Data (Position : Result_Collection_Cursor)
return Result_Collection_Access is
begin
return Result_List.Data (Result_List.Cursor (Position)).Ptr;
end Data;
function Child_Depth (Collection : Result_Collection) return Natural
is
function Child_Depth_Impl (Coll : Result_Collection;
Level : Natural) return Natural;
function Child_Depth_Impl (Coll : Result_Collection;
Level : Natural)
return Natural
is
Max : Natural := 0;
Current : Natural := 0;
Position : Result_List.Cursor := Result_List.First (Coll.Children);
begin
loop
exit when not Is_Valid (Position);
Current := Child_Depth_Impl (Data (Position).Ptr.all, Level + 1);
if Max < Current then
Max := Current;
end if;
Position := Result_List.Next (Position);
end loop;
return Level + Max;
end Child_Depth_Impl;
begin
return Child_Depth_Impl (Collection, 0);
end Child_Depth;
end Ahven.Results;
|
with Ada.Containers.Vectors; use Ada.Containers;
package Digraphs is
type Node_Idx_With_Null is new Natural;
subtype Node_Index is Node_Idx_With_Null range 1 .. Node_Idx_With_Null'Last;
-- a Node_Index is a number from 1, 2, 3, ... and the representative of a node
type Graph_Type is tagged private;
-- make sure Node is in Graph (possibly without connections)
procedure Add_Node
(Graph: in out Graph_Type'Class; Node: Node_Index);
-- insert an edge From->To into Graph; do nothing if already there
procedure Add_Connection
(Graph: in out Graph_Type'Class; From, To: Node_Index);
-- get the largest Node_Index used in any Add_Node or Add_Connection op.
-- iterate over all nodes of Graph: "for I in 1 .. Graph.Node_Count loop ..."
function Node_Count(Graph: Graph_Type) return Node_Idx_With_Null;
-- remove an edge From->To from Fraph; do nothing if not there
-- Graph.Node_Count is not changed
procedure Del_Connection
(Graph: in out Graph_Type'Class; From, To: Node_Index);
-- check if an edge From->to exists in Graph
function Connected
(Graph: Graph_Type; From, To: Node_Index) return Boolean;
-- data structure to store a list of nodes
package Node_Vec is new Vectors(Positive, Node_Index);
-- get a list of all nodes From->Somewhere in Graph
function All_Connections
(Graph: Graph_Type; From: Node_Index) return Node_Vec.Vector;
Graph_Is_Cyclic: exception;
-- a depth-first search to find a topological sorting of the nodes
-- raises Graph_Is_Cyclic if no topological sorting is possible
function Top_Sort
(Graph: Graph_Type) return Node_Vec.Vector;
private
package Conn_Vec is new Vectors(Node_Index, Node_Vec.Vector, Node_Vec."=");
type Graph_Type is new Conn_Vec.Vector with null record;
end Digraphs;
|
-- SPDX-FileCopyrightText: 2020 Max Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
----------------------------------------------------------------
with Ada.Tags;
with League.Strings;
with Markdown.Blocks;
limited with Markdown.Visitors;
package Markdown.ATX_Headings is
type ATX_Heading is new Markdown.Blocks.Block with private;
overriding function Create
(Line : not null access Markdown.Blocks.Text_Line) return ATX_Heading;
overriding procedure Visit
(Self : in out ATX_Heading;
Visitor : in out Markdown.Visitors.Visitor'Class);
procedure Filter
(Line : Markdown.Blocks.Text_Line;
Tag : in out Ada.Tags.Tag;
CIP : out Can_Interrupt_Paragraph);
subtype Heading_Level is Positive range 1 .. 6;
function Title (Self : ATX_Heading'Class)
return League.Strings.Universal_String;
function Level (Self : ATX_Heading'Class) return Heading_Level;
private
type ATX_Heading is new Markdown.Blocks.Block with record
Title : League.Strings.Universal_String;
Level : Heading_Level := 1;
end record;
end Markdown.ATX_Headings;
|
-- This file provides interfaces for the operational amplifiers on the
-- STM32G4 (ARM Cortex M4F) microcontrollers from ST Microelectronics.
private with STM32_SVD.OPAMP;
package STM32.OPAMP is
type Operational_Amplifier is limited private;
procedure Enable (This : in out Operational_Amplifier)
with Post => Enabled (This);
procedure Disable (This : in out Operational_Amplifier)
with Post => not Enabled (This);
function Enabled (This : Operational_Amplifier) return Boolean;
type NI_Input_Mode is (Normal_Mode, Calibration_Mode);
procedure Set_NI_Input_Mode
(This : in out Operational_Amplifier;
Input : NI_Input_Mode)
with Post => Get_NI_Input_Mode (This) = Input;
-- Select a calibration reference voltage on non-inverting input and
-- disables external connections.
function Get_NI_Input_Mode
(This : Operational_Amplifier) return NI_Input_Mode;
-- Return the source connected to the non-inverting input of the
-- operational amplifier.
type NI_Input_Port is (GPIO, Option_2)
with Size => 2;
-- These bits allows to select the source connected to the non-inverting
-- input of the operational amplifier. The first 3 options are common, the
-- last option change for each OPAMP:
-- Option OPAMP1 OPAMP2
-- 2 DAC1_OUT DAC2_OUT
procedure Set_NI_Input_Port
(This : in out Operational_Amplifier;
Input : NI_Input_Port)
with Post => Get_NI_Input_Port (This) = Input;
-- Select the source connected to the non-inverting input of the
-- operational amplifier.
function Get_NI_Input_Port
(This : Operational_Amplifier) return NI_Input_Port;
-- Return the source connected to the non-inverting input of the
-- operational amplifier.
type I_Input_Port is
(INM0,
INM1,
Feedback_Resistor_PGA_Mode,
Follower_Mode);
procedure Set_I_Input_Port
(This : in out Operational_Amplifier;
Input : I_Input_Port)
with Post => Get_I_Input_Port (This) = Input;
-- Select the source connected to the inverting input of the
-- operational amplifier.
function Get_I_Input_Port
(This : Operational_Amplifier) return I_Input_Port;
-- Return the source connected to the inverting input of the
-- operational amplifier.
type PGA_Mode_Gain is
(NI_Gain_2,
NI_Gain_4,
NI_Gain_8,
NI_Gain_16,
NI_Gain_2_Filtering_INM0,
NI_Gain_4_Filtering_INM0,
NI_Gain_8_Filtering_INM0,
NI_Gain_16_Filtering_INM0,
I_Gain_1_NI_Gain_2_INM0,
I_Gain_3_NI_Gain_4_INM0,
I_Gain_7_NI_Gain_8_INM0,
I_Gain_15_NI_Gain_16_INM0,
I_Gain_1_NI_Gain_2_INM0_INM1,
I_Gain_3_NI_Gain_4_INM0_INM1,
I_Gain_7_NI_Gain_8_INM0_INM1,
I_Gain_15_NI_Gain_16_INM0_INM1)
with Size => 4;
-- Gain in PGA mode.
procedure Set_PGA_Mode_Gain
(This : in out Operational_Amplifier;
Input : PGA_Mode_Gain)
with Post => Get_PGA_Mode_Gain (This) = Input;
-- Select the gain in PGA mode.
function Get_PGA_Mode_Gain
(This : Operational_Amplifier) return PGA_Mode_Gain;
-- Return the gain in PGA mode.
type Speed_Mode is (Normal_Mode, HighSpeed_Mode);
procedure Set_Speed_Mode
(This : in out Operational_Amplifier;
Input : Speed_Mode)
with Pre => not Enabled (This),
Post => Get_Speed_Mode (This) = Input;
-- OPAMP in normal or high-speed mode.
function Get_Speed_Mode
(This : Operational_Amplifier) return Speed_Mode;
-- Return the OPAMP speed mode.
type Init_Parameters is record
Input_Minus : I_Input_Port;
Input_Plus : NI_Input_Port;
PGA_Mode : PGA_Mode_Gain;
Power_Mode : Speed_Mode;
end record;
procedure Configure_Opamp
(This : in out Operational_Amplifier;
Param : Init_Parameters);
procedure Set_User_Trimming
(This : in out Operational_Amplifier;
Enabled : Boolean)
with Post => Get_User_Trimming (This) = Enabled;
-- Allows to switch from ‘factory’ AOP offset trimmed values to ‘user’ AOP
-- offset trimmed values.
function Get_User_Trimming
(This : Operational_Amplifier) return Boolean;
-- Return the state of user trimming.
type Differential_Pair is (NMOS, PMOS);
procedure Set_Offset_Trimming
(This : in out Operational_Amplifier;
Pair : Differential_Pair;
Input : UInt5)
with Post => Get_Offset_Trimming (This, Pair) = Input;
-- Select the offset trimming value for NMOS or PMOS.
function Get_Offset_Trimming
(This : Operational_Amplifier;
Pair : Differential_Pair) return UInt5;
-- Return the offset trimming value for NMOS or PMOS.
procedure Set_Calibration_Mode
(This : in out Operational_Amplifier;
Enabled : Boolean)
with Post => Get_Calibration_Mode (This) = Enabled;
-- Select the calibration mode connecting VM and VP to the OPAMP
-- internal reference voltage.
function Get_Calibration_Mode
(This : Operational_Amplifier) return Boolean;
-- Return the calibration mode.
type Calibration_Value is
(VREFOPAMP_Is_3_3_VDDA, -- 3.3%
VREFOPAMP_Is_10_VDDA, -- 10%
VREFOPAMP_Is_50_VDDA, -- 50%
VREFOPAMP_Is_90_VDDA -- 90%
);
-- Offset calibration bus to generate the internal reference voltage.
procedure Set_Calibration_Value
(This : in out Operational_Amplifier;
Input : Calibration_Value)
with Post => Get_Calibration_Value (This) = Input;
-- Select the offset calibration bus used to generate the internal
-- reference voltage when CALON = 1 or FORCE_VP = 1.
function Get_Calibration_Value
(This : Operational_Amplifier) return Calibration_Value;
-- Return the offset calibration bus voltage.
procedure Calibrate (This : in out Operational_Amplifier);
-- Calibrate the NMOS and PMOS differential pair. This routine
-- is described in the RM0440 rev 6 pg. 797. The offset trim time,
-- during calibration, must respect the minimum time needed
-- between two steps to have 1 mV accuracy.
-- This routine must be executed first with normal speed mode, then with
-- high-speed mode, if used.
type Internal_Output is
(Is_Output,
Is_Not_Output);
type Output_Status_Flag is
(NI_Lesser_Then_I,
NI_Greater_Then_I);
function Get_Output_Status_Flag
(This : Operational_Amplifier) return Output_Status_Flag;
-- Return the output status flag when the OPAMP is used as comparator
-- during calibration.
private
-- representation for the whole Operationa Amplifier type -----------------
type Operational_Amplifier is limited record
CSR : STM32_SVD.OPAMP.OPAMP1_CSR_Register;
OTR : STM32_SVD.OPAMP.OPAMP1_OTR_Register;
HSOTR : STM32_SVD.OPAMP.OPAMP1_HSOTR_Register;
end record with Volatile, Size => 3 * 32;
for Operational_Amplifier use record
CSR at 16#00# range 0 .. 31;
OTR at 16#04# range 0 .. 31;
HSOTR at 16#08# range 0 .. 31;
end record;
end STM32.OPAMP;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- B I N D O --
-- --
-- B o d y --
-- --
-- Copyright (C) 2019-2020, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING3. If not, go to --
-- http://www.gnu.org/licenses for a complete copy of the license. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Binde;
with Opt; use Opt;
with Bindo.Elaborators;
use Bindo.Elaborators;
package body Bindo is
---------------------------------
-- Elaboration-order mechanism --
---------------------------------
-- The elaboration-order (EO) mechanism implemented in this unit and its
-- children has the following objectives:
--
-- * Find an ordering of all library items (historically referred to as
-- "units") in the bind which require elaboration, taking into account:
--
-- - The dependencies between units expressed in the form of with
-- clauses.
--
-- - Pragmas Elaborate, Elaborate_All, Elaborate_Body, Preelaborable,
-- and Pure.
--
-- - The flow of execution at elaboration time.
--
-- - Additional dependencies between units supplied to the binder by
-- means of a forced-elaboration-order file.
--
-- The high-level idea empoyed by the EO mechanism is to construct two
-- graphs and use the information they represent to find an ordering of
-- all units.
--
-- The invocation graph represents the flow of execution at elaboration
-- time.
--
-- The library graph captures the dependencies between units expressed
-- by with clause and elaboration-related pragmas. The library graph is
-- further augmented with additional information from the invocation
-- graph by exploring the execution paths from a unit with elaboration
-- code to other external units.
--
-- The strongly connected components of the library graph are computed.
--
-- The order is obtained using a topological sort-like algorithm which
-- traverses the library graph and its strongly connected components in
-- an attempt to order available units while enabling other units to be
-- ordered.
--
-- * Diagnose elaboration circularities between units
--
-- An elaboration circularity arises when either
--
-- - At least one unit cannot be ordered, or
--
-- - All units can be ordered, but an edge with an Elaborate_All
-- pragma links two vertices within the same component of the
-- library graph.
--
-- The library graph is traversed to discover, collect, and sort all
-- cycles that hinder the elaboration order.
--
-- The most important cycle is diagnosed by describing its effects on
-- the elaboration order and listing all units comprising the circuit.
-- Various suggestions on how to break the cycle are offered.
-----------------
-- Terminology --
-----------------
-- * Component - A strongly connected component of a graph.
--
-- * Elaborable component - A component that is not waiting on other
-- components to be elaborated.
--
-- * Elaborable vertex - A vertex that is not waiting on strong and weak
-- predecessors, and whose component is elaborable.
--
-- * Elaboration circularity - A cycle involving units from the bind.
--
-- * Elaboration root - A special invocation construct which denotes the
-- elaboration procedure of a unit.
--
-- * Invocation - The act of activating a task, calling a subprogram, or
-- instantiating a generic.
--
-- * Invocation construct - An entry declaration, [single] protected type,
-- subprogram declaration, subprogram instantiation, or a [single] task
-- type declared in the visible, private, or body declarations of some
-- unit. The construct is encoded in the ALI file of the related unit.
--
-- * Invocation graph - A directed graph which models the flow of execution
-- at elaboration time.
--
-- - Vertices - Invocation constructs plus extra information. Certain
-- vertices act as elaboration roots.
--
-- - Edges - Invocation relations plus extra information.
--
-- * Invocation relation - A flow link between two invocation constructs.
-- This link is encoded in the ALI file of unit that houses the invoker.
--
-- * Invocation signature - A set of attributes that uniquely identify an
-- invocation construct within the namespace of all ALI files.
--
-- * Invoker - The source construct of an invocation relation (the caller,
-- instantiator, or task activator).
--
-- * Library graph - A directed graph which captures with clause and pragma
-- dependencies between units.
--
-- - Vertices - Units plus extra information.
--
-- - Edges - With clause, pragma, and additional dependencies between
-- units.
--
-- * Pending predecessor - A vertex that must be elaborated before another
-- vertex can be elaborated.
--
-- * Strong edge - A non-invocation library graph edge. Strong edges
-- represent the language-defined relations between units.
--
-- * Strong predecessor - A library graph vertex reachable via a strong
-- edge.
--
-- * Target - The destination construct of an invocation relation (the
-- generic, subprogram, or task type).
--
-- * Weak edge - An invocation library graph edge. Weak edges represent
-- the speculative flow of execution at elaboration time, which may or
-- may not take place.
--
-- * Weak predecessor - A library graph vertex reachable via a weak edge.
--
-- * Weakly elaborable vertex - A vertex that is waiting solely on weak
-- predecessors to be elaborated, and whose component is elaborable.
------------------
-- Architecture --
------------------
-- Find_Elaboration_Order
-- |
-- +--> Collect_Elaborable_Units
-- +--> Write_ALI_Tables
-- +--> Elaborate_Units
-- |
-- +------ | -------------- Construction phase ------------------------+
-- | | |
-- | +--> Build_Library_Graph |
-- | +--> Validate_Library_Graph |
-- | +--> Write_Library_Graph |
-- | | |
-- | +--> Build_Invocation_Graph |
-- | +--> Validate_Invocation_Graph |
-- | +--> Write_Invocation_Graph |
-- | | |
-- +------ | ----------------------------------------------------------+
-- |
-- +------ | -------------- Augmentation phase ------------------------+
-- | | |
-- | +--> Augment_Library_Graph |
-- | | |
-- +------ | ----------------------------------------------------------+
-- |
-- +------ | -------------- Ordering phase ----------------------------+
-- | | |
-- | +--> Find_Components |
-- | | |
-- | +--> Elaborate_Library_Graph |
-- | +--> Validate_Elaboration_Order |
-- | +--> Write_Elaboration_Order |
-- | | |
-- | +--> Write_Unit_Closure |
-- | | |
-- +------ | ----------------------------------------------------------+
-- |
-- +------ | -------------- Diagnostics phase -------------------------+
-- | | |
-- | +--> Find_Cycles |
-- | +--> Validate_Cycles |
-- | +--> Write_Cycles |
-- | | |
-- | +--> Diagnose_Cycle / Diagnose_All_Cycles |
-- | |
-- +-------------------------------------------------------------------+
------------------------
-- Construction phase --
------------------------
-- The Construction phase has the following objectives:
--
-- * Build the library graph by inspecting the ALI file of each unit that
-- requires elaboration.
--
-- * Validate the consistency of the library graph, only when switch -d_V
-- is in effect.
--
-- * Write the contents of the invocation graph in human-readable form to
-- standard output when switch -d_L is in effect.
--
-- * Build the invocation graph by inspecting invocation constructs and
-- relations in the ALI file of each unit that requires elaboration.
--
-- * Validate the consistency of the invocation graph, only when switch
-- -d_V is in effect.
--
-- * Write the contents of the invocation graph in human-readable form to
-- standard output when switch -d_I is in effect.
------------------------
-- Augmentation phase --
------------------------
-- The Augmentation phase has the following objectives:
--
-- * Discover transitions of the elaboration flow from a unit with an
-- elaboration root to other units. Augment the library graph with
-- extra edges for each such transition.
--------------------
-- Ordering phase --
--------------------
-- The Ordering phase has the following objectives:
--
-- * Discover all components of the library graph by treating specs and
-- bodies as single vertices.
--
-- * Try to order as many vertices of the library graph as possible by
-- performing a topological sort based on the pending predecessors of
-- vertices across all components and within a single component.
--
-- * Validate the consistency of the order, only when switch -d_V is in
-- effect.
--
-- * Write the contents of the order in human-readable form to standard
-- output when switch -d_O is in effect.
--
-- * Write the sources of the order closure when switch -R is in effect.
-----------------------
-- Diagnostics phase --
-----------------------
-- The Diagnostics phase has the following objectives:
--
-- * Discover, save, and sort all cycles in the library graph. The cycles
-- are sorted based on the following heuristics:
--
-- - A cycle with higher precedence is preferred.
--
-- - A cycle with fewer invocation edges is preferred.
--
-- - A cycle with a shorter length is preferred.
--
-- * Validate the consistency of cycles, only when switch -d_V is in
-- effect.
--
-- * Write the contents of all cycles in human-readable form to standard
-- output when switch -d_O is in effect.
--
-- * Diagnose the most important cycle, or all cycles when switch -d_C is
-- in effect. The diagnostic consists of:
--
-- - The reason for the existence of the cycle, along with the unit
-- whose elaboration cannot be guaranteed.
--
-- - A detailed traceback of the cycle, showcasing the transition
-- between units, along with any other elaboration-order-related
-- information.
--
-- - A set of suggestions on how to break the cycle considering the
-- the edges comprising the circuit, the elaboration model used to
-- compile the units, the availability of invocation information,
-- and the state of various relevant switches.
--------------
-- Switches --
--------------
-- -d_a Ignore the effects of pragma Elaborate_All
--
-- GNATbind creates a regular with edge instead of an Elaborate_All
-- edge in the library graph, thus eliminating the effects of the
-- pragma.
--
-- -d_b Ignore the effects of pragma Elaborate_Body
--
-- GNATbind treats a spec and body pair as decoupled.
--
-- -d_e Ignore the effects of pragma Elaborate
--
-- GNATbind creates a regular with edge instead of an Elaborate edge
-- in the library graph, thus eliminating the effects of the pragma.
-- In addition, GNATbind does not create an edge to the body of the
-- pragma argument.
--
-- -d_t Output cycle-detection trace information
--
-- GNATbind outputs trace information on cycle-detection activities
-- to standard output.
--
-- -d_A Output ALI invocation tables
--
-- GNATbind outputs the contents of ALI table Invocation_Constructs
-- and Invocation_Edges in textual format to standard output.
--
-- -d_C Diagnose all cycles
--
-- GNATbind outputs diagnostics for all unique cycles in the bind,
-- rather than just the most important one.
--
-- -d_I Output invocation graph
--
-- GNATbind outputs the invocation graph in text format to standard
-- output.
--
-- -d_L Output library graph
--
-- GNATbind outputs the library graph in textual format to standard
-- output.
--
-- -d_P Output cycle paths
--
-- GNATbind outputs the cycle paths in text format to standard output
--
-- -d_S Output elaboration-order status information
--
-- GNATbind outputs trace information concerning the status of its
-- various phases to standard output.
--
-- -d_T Output elaboration-order trace information
--
-- GNATbind outputs trace information on elaboration-order detection
-- activities to standard output.
--
-- -d_V Validate bindo cycles, graphs, and order
--
-- GNATbind validates the invocation graph, library graph along with
-- its cycles, and elaboration order by detecting inconsistencies and
-- producing error reports.
--
-- -e Output complete list of elaboration-order dependencies
--
-- GNATbind outputs the dependencies between units to standard
-- output.
--
-- -f Force elaboration order from given file
--
-- GNATbind applies an additional set of edges to the library graph.
-- The edges are read from a file specified by the argument of the
-- flag.
--
-- -H Legacy elaboration-order model enabled
--
-- GNATbind uses the library-graph and heuristics-based elaboration-
-- order model.
--
-- -l Output chosen elaboration order
--
-- GNATbind outputs the elaboration order in text format to standard
-- output.
--
-- -p Pessimistic (worst-case) elaboration order
--
-- This switch is not used in Bindo and its children.
----------------------------------------
-- Debugging elaboration-order issues --
----------------------------------------
-- Prior to debugging elaboration-order-related issues, enable all relevant
-- debug flags to collect as much information as possible. Depending on the
-- number of files in the bind, Bindo may emit anywhere between several MBs
-- to several hundred MBs of data to standard output. The switches are:
--
-- -d_A -d_C -d_I -d_L -d_P -d_t -d_T -d_V
--
-- Bindo offers several debugging routines that can be invoked from gdb.
-- Those are defined in the body of Bindo.Writers, in sections denoted by
-- header Debug. For quick reference, the routines are:
--
-- palgc -- print all library-graph cycles
-- pau -- print all units
-- pc -- print component
-- pige -- print invocation-graph edge
-- pigv -- print invocation-graph vertex
-- plgc -- print library-graph cycle
-- plge -- print library-graph edge
-- plgv -- print library-graph vertex
-- pu -- print units
--
-- * Apparent infinite loop
--
-- The elaboration order mechanism appears to be stuck in an infinite
-- loop. Use switch -d_S to output the status of each elaboration phase.
--
-- * Invalid elaboration order
--
-- The elaboration order is invalid when:
--
-- - A unit that requires elaboration is missing from the order
-- - A unit that does not require elaboration is present in the order
--
-- Examine the output of the elaboration algorithm available via switch
-- -d_T to determine how the related units were included in or excluded
-- from the order. Determine whether the library graph contains all the
-- relevant edges for those units.
--
-- Units and routines of interest:
-- Bindo.Elaborators
-- Elaborate_Library_Graph
-- Elaborate_Units
--
-- * Invalid invocation graph
--
-- The invocation graph is invalid when:
--
-- - An edge lacks an attribute
-- - A vertex lacks an attribute
--
-- Find the malformed edge or vertex and determine which attribute is
-- missing. Examine the contents of the invocation-related ALI tables
-- available via switch -d_A. If the invocation construct or relation
-- is missing, verify the ALI file. If the ALI lacks all the relevant
-- information, then Sem_Elab most likely failed to discover a valid
-- elaboration path.
--
-- Units and routines of interest:
-- Bindo.Builders
-- Bindo.Graphs
-- Add_Edge
-- Add_Vertex
-- Build_Invocation_Graph
--
-- * Invalid library graph
--
-- The library graph is invalid when:
--
-- - An edge lacks an attribute
-- - A vertex lacks an attribute
--
-- Find the malformed edge or vertex and determine which attribute is
-- missing.
--
-- Units and routines of interest:
-- Bindo.Builders
-- Bindo.Graphs
-- Add_Edge
-- Add_Vertex
-- Build_Library_Graph
--
-- * Invalid library-graph cycle
--
-- A library-graph cycle is invalid when:
--
-- - It lacks enough edges to form a circuit
-- - At least one edge in the circuit is repeated
--
-- Find the malformed cycle and determine which attribute is missing.
--
-- Units and routines of interest:
-- Bindo.Graphs
-- Find_Cycles
----------------------------
-- Find_Elaboration_Order --
----------------------------
procedure Find_Elaboration_Order
(Order : out Unit_Id_Table;
Main_Lib_File : File_Name_Type)
is
begin
-- Use the library graph and heuristic-based elaboration order when
-- switch -H (legacy elaboration-order mode enabled).
if Legacy_Elaboration_Order then
Binde.Find_Elab_Order (Order, Main_Lib_File);
-- Otherwise use the invocation and library-graph-based elaboration
-- order.
else
Invocation_And_Library_Graph_Elaborators.Elaborate_Units
(Order => Order,
Main_Lib_File => Main_Lib_File);
end if;
end Find_Elaboration_Order;
end Bindo;
|
with Ada.Assertions;
use Ada.Assertions;
package body Encodings.Line_Endings.Generic_Strip_CR is
procedure Convert(
This: in out Coder;
Source: in String_Type;
Source_Last: out Natural;
Target: out String_Type;
Target_Last: out Natural
) is
C: Character_Type;
begin
Source_Last := Source'First - 1;
Target_Last := Target'First - 1;
while Source_Last < Source'Last loop
C := Source(Source_Last + 1);
if This.Have_CR and C /= Line_Feed then -- emit CR not the part of CRLF sequence
if Target_Last < Target'Last then
Target_Last := Target_Last + 1;
Target(Target_Last) := Carriage_Return;
else
return;
end if;
This.Have_CR := False;
end if;
if C = Carriage_Return then
Assert(This.Have_CR = False, "Have should be cleared before or if condition shoudn't be true");
This.Have_CR := True;
else
This.Have_CR := False;
if Target_Last < Target'Last then
Target_Last := Target_Last + 1;
Target(Target_Last) := C;
else
return;
end if;
end if;
Source_Last := Source_Last + 1;
end loop;
end Convert;
end Encodings.Line_Endings.Generic_Strip_CR;
|
--
-- Copyright (C) 2021 Jeremy Grosser <jeremy@synack.me>
--
-- SPDX-License-Identifier: BSD-3-Clause
--
package body ST7789 is
procedure Write
(This : in out ST7789_Screen;
Reg : Register)
is
use HAL.SPI;
Status : SPI_Status;
begin
This.CS.Clear;
This.DC.Clear;
This.Port.Transmit (SPI_Data_8b'(1 => Register'Enum_Rep (Reg)), Status);
if Status /= Ok then
raise Program_Error;
end if;
This.CS.Set;
end Write;
procedure Write
(This : in out ST7789_Screen;
Reg : Register;
Data : HAL.UInt8)
is
begin
Write (This, Reg, HAL.UInt8_Array'(1 => Data));
end Write;
procedure Write
(This : in out ST7789_Screen;
Reg : Register;
Data : HAL.UInt8_Array)
is
use HAL.SPI;
Status : SPI_Status;
begin
This.CS.Clear;
This.DC.Clear;
This.Port.Transmit (SPI_Data_8b'(1 => Register'Enum_Rep (Reg)), Status);
if Status /= Ok then
raise Program_Error;
end if;
This.DC.Set;
This.Port.Transmit (SPI_Data_8b (Data), Status);
if Status /= Ok then
raise Program_Error;
end if;
This.CS.Set;
end Write;
procedure Initialize
(This : in out ST7789_Screen)
is
use HAL.GPIO;
subtype U8 is HAL.UInt8_Array;
begin
if This.RST /= null then
This.RST.Clear;
end if;
This.CS.Clear;
This.Time.Delay_Milliseconds (50);
if This.RST /= null then
This.RST.Set;
end if;
This.CS.Set;
This.Time.Delay_Milliseconds (50);
Write (This, SWRESET);
This.Time.Delay_Milliseconds (150);
Write (This, MADCTL, 16#04#);
Write (This, TEON, 16#00#);
Write (This, FRMCTR2, U8'(16#0C#, 16#0C#, 16#00#, 16#33#, 16#33#));
Write (This, COLMOD, 16#55#); -- 16bpp RGB565 see datasheet 8.8.42
Write (This, GAMSET, 16#04#);
Write (This, GCTRL, 16#14#);
Write (This, VCOMS, 16#25#);
Write (This, LCMCTRL, 16#2C#);
Write (This, VDVVRHEN, 16#01#);
Write (This, VRHS, 16#12#);
Write (This, VDVS, 16#20#);
Write (This, PWRCTRL1, U8'(16#A4#, 16#A1#));
Write (This, FRCTRL2, 16#15#); -- 50 Hz, column inversion
Write (This, GMCTRP1, U8'(16#D0#, 16#04#, 16#0D#, 16#11#, 16#13#, 16#2B#, 16#3F#,
16#54#, 16#4C#, 16#18#, 16#0D#, 16#0B#, 16#1F#, 16#23#));
Write (This, GMCTRN1, U8'(16#D0#, 16#04#, 16#0C#, 16#11#, 16#13#, 16#2C#, 16#3F#,
16#44#, 16#51#, 16#2F#, 16#1F#, 16#1F#, 16#20#, 16#23#));
Write (This, INVON);
Write (This, SLPOUT);
Write (This, DISPON);
This.Time.Delay_Milliseconds (100);
Write (This, CASET, U8'(16#00#, 16#00#, 16#00#, 16#EF#));
Write (This, RASET, U8'(16#00#, 16#00#, 16#00#, 16#EF#));
Write (This, RAMWR);
end Initialize;
procedure Write
(This : in out ST7789_Screen;
Data : Pixels)
is
use HAL.SPI;
D : SPI_Data_16b (1 .. Data'Length)
with Import, Address => Data'Address;
Status : SPI_Status;
begin
This.CS.Clear;
This.DC.Set;
This.Port.Transmit (D, Status, Timeout => 0);
This.CS.Set;
end Write;
end ST7789;
|
-- Widget for creating bar codes with Gnoga
--
-- Copyright (C) 2018 by PragmAda Software Engineering
--
-- Released under the terms of the 3-Clause BSD License. See https://opensource.org/licenses/BSD-3-Clause
with Bar_Codes;
with Gnoga.Gui.Base;
private with Gnoga.Gui.Element.Canvas;
package Gnoga_Bar_Codes is
type Bar_Code is new Bar_Codes.Bar_Code with private;
procedure Create (Code : in out Bar_Code;
Parent : in out Gnoga.Gui.Base.Base_Type'Class;
Width : in Integer;
Height : in Integer;
ID : in String := "");
-- Creates a Bar_Code at the currunt position in Parent Width pixels wide and Height high
-- Width should be a least 2 * Bar_Codes.Fitting (the longest text you'll display).Width
procedure Generate (Code : in out Bar_Code; Kind : In Bar_Codes.Kind_Of_Code; Text : in String);
-- Generates a bar code of Bar_Codes.Kind Kind representing Text in the (already created) Bar_Code Code
-- Text should not contain any non-ASCII characters
-- If 2 * Bar_Codes.Fitting (Text).Width > the Width used to create Code, Text will be truncated to fit
private -- Gnoga_Bar_Codes
type Bar_Code is new Bar_Codes.Bar_Code with record
Canvas : Gnoga.Gui.Element.Canvas.Canvas_Access;
Box : Bar_Codes.Module_Box;
Kind : Bar_Codes.Kind_Of_Code;
end record;
overriding procedure Filled_Rectangle (Code : in Bar_Code; Shape : in Bar_Codes.Module_Box);
end Gnoga_Bar_Codes;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- B A C K _ E N D --
-- --
-- S p e c --
-- --
-- Copyright (C) 1992-2015, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING3. If not, go to --
-- http://www.gnu.org/licenses for a complete copy of the license. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- Call the back end with all the information needed
-- Note: there are multiple bodies/variants of this package, so do not
-- modify this spec without coordination.
package Back_End is
type Back_End_Mode_Type is (
Generate_Object,
-- Full back end operation with object file generation
Declarations_Only,
-- Partial back end operation with no object file generation. In this
-- mode the only useful action performed by gigi is to process all
-- declarations issuing any error messages (in particular those to
-- do with rep clauses), and to back annotate representation info.
Skip);
-- Back end call is skipped (syntax only, or errors found)
pragma Convention (C, Back_End_Mode_Type);
for Back_End_Mode_Type use (0, 1, 2);
procedure Call_Back_End (Mode : Back_End_Mode_Type);
-- Call back end, i.e. make call to driver traversing the tree and
-- outputting code. This call is made with all tables locked. The back
-- end is responsible for unlocking any tables it may need to change,
-- and locking them again before returning.
procedure Scan_Compiler_Arguments;
-- Acquires command-line parameters passed to the compiler and processes
-- them. Calls Scan_Front_End_Switches for any front-end switches found.
--
-- The processing of arguments is private to the back end, since the way
-- of acquiring the arguments as well as the set of allowable back end
-- switches is different depending on the particular back end being used.
--
-- Any processed switches that influence the result of a compilation must
-- be added to the Compilation_Arguments table.
--
-- This routine is expected to set the following to True if necessary (the
-- default for all of these in Opt is False).
--
-- Opt.Disable_FE_Inline
-- Opt.Disable_FE_Inline_Always
-- Opt.Suppress_Control_Float_Optimizations
-- Opt.Generate_SCO
-- Opt.Generate_SCO_Instance_Table
-- Opt.Stack_Checking_Enabled
-- Opt.No_Stdinc
-- Opt.No_Stdlib
procedure Gen_Or_Update_Object_File;
-- Is used to generate the object file (if generated directly by gnat1), or
-- update it if it has already been generated by the call to Call_Back_End,
-- so that its timestamp is updated by the call.
--
-- This is a no-op with the gcc back-end (the object file is generated by
-- the assembler afterwards), but is needed for back-ends that directly
-- generate the final object file so that the object file's timestamp is
-- correct when compared with the corresponding ali file by gnatmake.
end Back_End;
|
with HAL.UART;
with FE310.UART;
with FE310.Device;
package body IO is
type BToCT is array (Byte range 0 .. 15) of Character;
BToC : constant BToCT :=
('0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F');
---------
-- Put --
---------
procedure Put (C : Character) is
B : HAL.UART.UART_Data_8b (0 .. 0);
S : HAL.UART.UART_Status;
begin
B (0) := Character'Pos (C);
FE310.UART.Transmit (FE310.Device.UART0, B, S);
pragma Unreferenced (S);
end Put;
--------------
-- New_Line --
--------------
procedure New_Line (Spacing : Positive := 1) is
begin
for J in 1 .. Spacing loop
Put (ASCII.CR);
Put (ASCII.LF);
end loop;
end New_Line;
---------
-- Put --
---------
procedure Put (X : Integer) is
Int : Integer;
S : String (1 .. Integer'Width);
First : Natural := S'Last + 1;
Val : Integer;
begin
-- Work on negative values to avoid overflows
Int := (if X < 0 then X else -X);
loop
-- Cf RM 4.5.5 Multiplying Operators. The rem operator will return
-- negative values for negative values of Int.
Val := Int rem 10;
Int := (Int - Val) / 10;
First := First - 1;
S (First) := Character'Val (Character'Pos ('0') - Val);
exit when Int = 0;
end loop;
if X < 0 then
First := First - 1;
S (First) := '-';
end if;
Put (S (First .. S'Last));
end Put;
procedure Put (X : UInt64)
is
Int : UInt64 := X;
S : String (1 .. UInt64'Width) := (others => ' ');
First : Natural := S'Last + 1;
Val : UInt64;
begin
loop
Val := Int rem 10;
Int := (Int - Val) / 10;
First := First - 1;
S (First) := Character'Val (Character'Pos ('0') + Val);
exit when Int = 0;
end loop;
-- Fixed width output
Put (S);
end Put;
---------
-- Put --
---------
procedure Put (S : String) is
begin
for J in S'Range loop
Put (S (J));
end loop;
end Put;
--------------
-- Put_Line --
--------------
procedure Put_Line (S : String) is
begin
Put (S);
New_Line;
end Put_Line;
procedure Put_Line (S : String; X : Unsigned_64)
is
begin
Put (S);
Put (UInt64 (X));
New_Line;
end Put_Line;
procedure Put (B : in Byte)
is
begin
Put ("16#");
Put (BToC (B / 16));
Put (BToC (B mod 16));
Put ("# ");
end Put;
procedure Put (S : in String; D : in Byte_Seq)
is
begin
Put_Line (S);
for I in D'Range loop
Put (D (I));
if I mod 8 = 7 then
New_Line;
end if;
end loop;
New_Line;
end Put;
end IO;
|
with Ada.Exceptions.Finally;
with Ada.Unchecked_Conversion;
with Ada.Unchecked_Deallocation;
with Ada.Unchecked_Reallocation;
with System.Growth;
package body Ada.Environment_Encoding.Generic_Strings is
pragma Check_Policy (Validate => Ignore);
use type Streams.Stream_Element_Offset;
pragma Compile_Time_Error (
String_Type'Component_Size /= Character_Type'Size,
"String_Type is not packed");
pragma Compile_Time_Error (
Character_Type'Size rem Streams.Stream_Element'Size /= 0,
"String_Type could not be treated as Stream_Element_Array");
function Current_Id return Encoding_Id;
function Current_Id return Encoding_Id is
begin
if Character_Type'Size = 8 then
return UTF_8;
elsif Character_Type'Size = 16 then
return UTF_16;
elsif Character_Type'Size = 32 then
return UTF_32;
else
raise Program_Error; -- bad instance
end if;
end Current_Id;
type String_Type_Access is access String_Type;
procedure Free is
new Unchecked_Deallocation (
String_Type,
String_Type_Access);
procedure Reallocate is
new Unchecked_Reallocation (
Positive,
Character_Type,
String_Type,
String_Type_Access);
type Stream_Element_Array_Access is access Streams.Stream_Element_Array;
procedure Free is
new Unchecked_Deallocation (
Streams.Stream_Element_Array,
Stream_Element_Array_Access);
procedure Reallocate is
new Unchecked_Reallocation (
Streams.Stream_Element_Offset,
Streams.Stream_Element,
Streams.Stream_Element_Array,
Stream_Element_Array_Access);
Minimal_Size : constant := 8;
-- implementation of decoder
function From (Id : Encoding_Id) return Decoder is
-- [gcc-7] strange error if extended return is placed outside of
-- the package Controlled, and Disable_Controlled => True
type T1 is access function (From, To : Encoding_Id) return Converter;
type T2 is access function (From, To : Encoding_Id) return Decoder;
function Cast is new Unchecked_Conversion (T1, T2);
begin
return Cast (Controlled.Open'Access) (From => Id, To => Current_Id);
end From;
procedure Decode (
Object : Decoder;
Item : Streams.Stream_Element_Array;
Last : out Streams.Stream_Element_Offset;
Out_Item : out String_Type;
Out_Last : out Natural;
Finish : Boolean;
Status : out Subsequence_Status_Type)
is
CS_In_SE : constant Streams.Stream_Element_Count :=
Character_Type'Size / Streams.Stream_Element'Size;
Out_Item_As_SEA :
Streams.Stream_Element_Array (1 .. Out_Item'Length * CS_In_SE);
for Out_Item_As_SEA'Address use Out_Item'Address;
Out_Item_SEA_Last : Streams.Stream_Element_Offset;
begin
Convert (
Object,
Item,
Last,
Out_Item_As_SEA,
Out_Item_SEA_Last,
Finish,
Status);
pragma Check (Validate, Out_Item_SEA_Last rem CS_In_SE = 0);
Out_Last := Out_Item'First + Integer (Out_Item_SEA_Last / CS_In_SE - 1);
end Decode;
procedure Decode (
Object : Decoder;
Item : Streams.Stream_Element_Array;
Last : out Streams.Stream_Element_Offset;
Out_Item : out String_Type;
Out_Last : out Natural;
Status : out Continuing_Status_Type)
is
CS_In_SE : constant Streams.Stream_Element_Count :=
Character_Type'Size / Streams.Stream_Element'Size;
Out_Item_As_SEA :
Streams.Stream_Element_Array (1 .. Out_Item'Length * CS_In_SE);
for Out_Item_As_SEA'Address use Out_Item'Address;
Out_Item_SEA_Last : Streams.Stream_Element_Offset;
begin
Convert (Object, Item, Last, Out_Item_As_SEA, Out_Item_SEA_Last, Status);
pragma Check (Validate, Out_Item_SEA_Last rem CS_In_SE = 0);
Out_Last := Out_Item'First + Integer (Out_Item_SEA_Last / CS_In_SE - 1);
end Decode;
procedure Decode (
Object : Decoder;
Out_Item : out String_Type;
Out_Last : out Natural;
Finish : True_Only;
Status : out Finishing_Status_Type)
is
CS_In_SE : constant Streams.Stream_Element_Count :=
Character_Type'Size / Streams.Stream_Element'Size;
Out_Item_As_SEA :
Streams.Stream_Element_Array (1 .. Out_Item'Length * CS_In_SE);
for Out_Item_As_SEA'Address use Out_Item'Address;
Out_Item_SEA_Last : Streams.Stream_Element_Offset;
begin
Convert (Object, Out_Item_As_SEA, Out_Item_SEA_Last, Finish, Status);
pragma Check (Validate, Out_Item_SEA_Last rem CS_In_SE = 0);
Out_Last := Out_Item'First + Integer (Out_Item_SEA_Last / CS_In_SE - 1);
end Decode;
procedure Decode (
Object : Decoder;
Item : Streams.Stream_Element_Array;
Last : out Streams.Stream_Element_Offset;
Out_Item : out String_Type;
Out_Last : out Natural;
Finish : True_Only;
Status : out Status_Type)
is
CS_In_SE : constant Streams.Stream_Element_Count :=
Character_Type'Size / Streams.Stream_Element'Size;
Out_Item_As_SEA :
Streams.Stream_Element_Array (1 .. Out_Item'Length * CS_In_SE);
for Out_Item_As_SEA'Address use Out_Item'Address;
Out_Item_SEA_Last : Streams.Stream_Element_Offset;
begin
Convert (
Object,
Item,
Last,
Out_Item_As_SEA,
Out_Item_SEA_Last,
Finish,
Status);
pragma Check (Validate, Out_Item_SEA_Last rem CS_In_SE = 0);
Out_Last := Out_Item'First + Integer (Out_Item_SEA_Last / CS_In_SE - 1);
end Decode;
procedure Decode (
Object : Decoder;
Item : Streams.Stream_Element_Array;
Last : out Streams.Stream_Element_Offset;
Out_Item : out String_Type;
Out_Last : out Natural;
Finish : True_Only;
Status : out Substituting_Status_Type)
is
CS_In_SE : constant Streams.Stream_Element_Count :=
Character_Type'Size / Streams.Stream_Element'Size;
Out_Item_As_SEA :
Streams.Stream_Element_Array (1 .. Out_Item'Length * CS_In_SE);
for Out_Item_As_SEA'Address use Out_Item'Address;
Out_Item_SEA_Last : Streams.Stream_Element_Offset;
begin
Convert (
Object,
Item,
Last,
Out_Item_As_SEA,
Out_Item_SEA_Last,
Finish,
Status);
pragma Check (Validate, Out_Item_SEA_Last rem CS_In_SE = 0);
Out_Last := Out_Item'First + Integer (Out_Item_SEA_Last / CS_In_SE - 1);
end Decode;
function Decode (
Object : Decoder;
Item : Streams.Stream_Element_Array)
return String_Type
is
package Holder is
new Exceptions.Finally.Scoped_Holder (String_Type_Access, Free);
CS_In_SE : constant Streams.Stream_Element_Count :=
Character_Type'Size / Streams.Stream_Element'Size;
MS_In_SE : constant Streams.Stream_Element_Positive_Count :=
Min_Size_In_From_Stream_Elements (Object);
I : Streams.Stream_Element_Offset := Item'First;
Out_Item : aliased String_Type_Access;
Out_Last : Natural;
begin
Holder.Assign (Out_Item);
Out_Item := new String_Type (
1 ..
Natural (
Streams.Stream_Element_Count'Max (
2 * ((Item'Length + MS_In_SE - 1) / MS_In_SE),
Minimal_Size / CS_In_SE)));
Out_Last := 0;
loop
declare
Last : Streams.Stream_Element_Offset;
Status : Substituting_Status_Type;
begin
Decode (
Object,
Item (I .. Item'Last),
Last,
Out_Item.all (Out_Last + 1 .. Out_Item'Last),
Out_Last,
Finish => True,
Status => Status);
case Status is
when Finished =>
exit;
when Success =>
null;
when Overflow =>
declare
function Grow is new System.Growth.Fast_Grow (Natural);
begin
Reallocate (Out_Item, 1, Grow (Out_Item'Last));
end;
end case;
I := Last + 1;
end;
end loop;
return Out_Item (Out_Item'First .. Out_Last);
end Decode;
-- implementation of encoder
function To (Id : Encoding_Id) return Encoder is
-- [gcc-7] strange error if extended return is placed outside of
-- the package Controlled, and Disable_Controlled => True
type T1 is access function (From, To : Encoding_Id) return Converter;
type T2 is access function (From, To : Encoding_Id) return Encoder;
function Cast is new Unchecked_Conversion (T1, T2);
begin
return Cast (Controlled.Open'Access) (From => Current_Id, To => Id);
end To;
procedure Encode (
Object : Encoder;
Item : String_Type;
Last : out Natural;
Out_Item : out Streams.Stream_Element_Array;
Out_Last : out Streams.Stream_Element_Offset;
Finish : Boolean;
Status : out Subsequence_Status_Type)
is
CS_In_SE : constant Streams.Stream_Element_Count :=
Character_Type'Size / Streams.Stream_Element'Size;
Item_As_SEA : Streams.Stream_Element_Array (1 .. Item'Length * CS_In_SE);
for Item_As_SEA'Address use Item'Address;
Item_SEA_Last : Streams.Stream_Element_Offset;
begin
Convert (
Object,
Item_As_SEA,
Item_SEA_Last,
Out_Item,
Out_Last,
Finish,
Status);
pragma Check (Validate, Item_SEA_Last rem CS_In_SE = 0);
Last := Item'First + Integer (Item_SEA_Last / CS_In_SE - 1);
end Encode;
procedure Encode (
Object : Encoder;
Item : String_Type;
Last : out Natural;
Out_Item : out Streams.Stream_Element_Array;
Out_Last : out Streams.Stream_Element_Offset;
Status : out Continuing_Status_Type)
is
CS_In_SE : constant Streams.Stream_Element_Count :=
Character_Type'Size / Streams.Stream_Element'Size;
Item_As_SEA : Streams.Stream_Element_Array (1 .. Item'Length * CS_In_SE);
for Item_As_SEA'Address use Item'Address;
Item_SEA_Last : Streams.Stream_Element_Offset;
begin
Convert (Object, Item_As_SEA, Item_SEA_Last, Out_Item, Out_Last, Status);
pragma Check (Validate, Item_SEA_Last rem CS_In_SE = 0);
Last := Item'First + Integer (Item_SEA_Last / CS_In_SE - 1);
end Encode;
procedure Encode (
Object : Encoder;
Item : String_Type;
Last : out Natural;
Out_Item : out Streams.Stream_Element_Array;
Out_Last : out Streams.Stream_Element_Offset;
Finish : True_Only;
Status : out Status_Type)
is
CS_In_SE : constant Streams.Stream_Element_Count :=
Character_Type'Size / Streams.Stream_Element'Size;
Item_As_SEA : Streams.Stream_Element_Array (1 .. Item'Length * CS_In_SE);
for Item_As_SEA'Address use Item'Address;
Item_SEA_Last : Streams.Stream_Element_Offset;
begin
Convert (
Object,
Item_As_SEA,
Item_SEA_Last,
Out_Item,
Out_Last,
Finish,
Status);
pragma Check (Validate, Item_SEA_Last rem CS_In_SE = 0);
Last := Item'First + Integer (Item_SEA_Last / CS_In_SE - 1);
end Encode;
procedure Encode (
Object : Encoder;
Item : String_Type;
Last : out Natural;
Out_Item : out Streams.Stream_Element_Array;
Out_Last : out Streams.Stream_Element_Offset;
Finish : True_Only;
Status : out Substituting_Status_Type)
is
CS_In_SE : constant Streams.Stream_Element_Count :=
Character_Type'Size / Streams.Stream_Element'Size;
Item_As_SEA : Streams.Stream_Element_Array (1 .. Item'Length * CS_In_SE);
for Item_As_SEA'Address use Item'Address;
Item_SEA_Last : Streams.Stream_Element_Offset;
begin
Convert (
Object,
Item_As_SEA,
Item_SEA_Last,
Out_Item,
Out_Last,
Finish,
Status);
pragma Check (Validate, Item_SEA_Last rem CS_In_SE = 0);
Last := Item'First + Integer (Item_SEA_Last / CS_In_SE - 1);
end Encode;
function Encode (
Object : Encoder;
Item : String_Type)
return Streams.Stream_Element_Array
is
package Holder is
new Exceptions.Finally.Scoped_Holder (
Stream_Element_Array_Access,
Free);
CS_In_SE : constant Streams.Stream_Element_Count :=
Character_Type'Size / Streams.Stream_Element'Size;
I : Positive := Item'First;
Out_Item : aliased Stream_Element_Array_Access;
Out_Last : Streams.Stream_Element_Offset;
begin
Holder.Assign (Out_Item);
Out_Item := new Streams.Stream_Element_Array (
0 ..
Streams.Stream_Element_Offset'Max (
2 * Item'Length * CS_In_SE,
Minimal_Size)
- 1);
Out_Last := -1;
loop
declare
Last : Natural;
Status : Substituting_Status_Type;
begin
Encode (
Object,
Item (I .. Item'Last),
Last,
Out_Item.all (Out_Last + 1 .. Out_Item'Last),
Out_Last,
Finish => True,
Status => Status);
case Status is
when Finished =>
exit;
when Success =>
null;
when Overflow =>
declare
function Grow is
new System.Growth.Fast_Grow (
Streams.Stream_Element_Count);
begin
Reallocate (Out_Item, 1, Grow (Out_Item'Last));
end;
end case;
I := Last + 1;
end;
end loop;
return Out_Item (Out_Item'First .. Out_Last);
end Encode;
end Ada.Environment_Encoding.Generic_Strings;
|
with Ada.Integer_Text_IO;
with Ada.Text_IO;
package body Problem_24 is
package IO renames Ada.Text_IO;
package I_IO renames Ada.Integer_Text_IO;
procedure Solve is
subtype digit is Natural range 0 .. 9;
chosen : Array (digit) of Boolean;
unchosen : digit := 9;
remaining : Natural := 1_000_000;
function Factorial(n : in Natural) return Natural is
result : Natural := 1;
begin
for num in 2 .. n loop
result := result * num;
end loop;
return result;
end Factorial;
begin
for index in chosen'Range loop
chosen(index) := False;
end loop;
while remaining > 0 and unchosen > 0 loop
declare
subPermutations : constant Natural := factorial(unchosen);
choice : digit := remaining / subPermutations;
begin
remaining := remaining mod subPermutations;
for index in chosen'Range loop
if not chosen(index) then
if choice = 0 then
chosen(index) := True;
I_IO.Put(index, 1);
unchosen := unchosen - 1;
exit;
end if;
choice := choice - 1;
end if;
end loop;
end;
end loop;
for index in chosen'Range loop
exit when unchosen = 0;
if not chosen(index) then
I_IO.Put(index, 1);
unchosen := unchosen - 1;
end if;
end loop;
IO.New_Line;
end Solve;
end Problem_24;
|
with LSC.Internal.Bignum;
private package LSC.Internal.Bignum.Print
with SPARK_Mode => Off
is
pragma Pure;
procedure Print_Big_Int
(Item : LSC.Internal.Bignum.Big_Int;
Columns : Natural);
end LSC.Internal.Bignum.Print;
|
with Node_List_Parsers;
with Line_Arrays;
procedure Prova_Parser is
type Class is (Wp, Tsk, Deliv);
package My_Parser is new Node_List_Parsers (Class);
use My_Parser;
Eol : constant Character := Character'Val (10);
X : constant String := "" & Eol
& "" & Eol
& "" & Eol
& " [ Wp ]" & Eol
& "name : zorro" & Eol
& "label : pluto " & Eol
& "Viva la pappa col pomodoro" & Eol
& "" & Eol
& "" & Eol
& "[task]" & Eol
& "begin:12" & Eol;
Names : My_Parser.Name_Maps.Map;
begin
Names.Insert (Key => +"task",
New_Item => Tsk);
declare
Result : constant Node_List := Parse (Line_Arrays.Split (X), Names);
begin
Dump (Result);
end;
end Prova_Parser;
|
-- { dg-do compile }
with System;
procedure Volatile_Aggregate is
function GetArrayUpperBound return Integer is
begin
return 2;
end GetArrayUpperBound;
some_value : Integer := GetArrayUpperBound;
type Gp_Element_Type is record
Element : Integer;
end record;
type some_type is array (1 .. some_value) of Gp_Element_Type;
type Aligned_Some_Type is record
Value : aliased some_type;
end record;
for Aligned_Some_Type'Alignment use 8;
an_aligned_type : aligned_Some_Type;
my_address : system.address;
pragma Volatile (an_aligned_type);
begin
my_address := an_aligned_type.value(1)'address;
end;
|
-- Motherlode
-- Copyright (c) 2020 Fabien Chouteau
with HAL; use HAL;
with PyGamer; use PyGamer;
with PyGamer.Time;
with PyGamer.Controls;
with PyGamer.Screen;
with Parameters;
with Render;
with World;
with Player;
with Sound;
package body Cargo_Menu is
use type World.Valuable_Cell;
Selected : World.Valuable_Cell := World.Valuable_Cell'First;
-----------------
-- Draw_Screen --
-----------------
procedure Draw_Screen (FB : in out HAL.UInt16_Array) is
Cargo_X_Offset : constant Natural := 0;
Cargo_Y_Offest : Natural := 0;
W_Column : constant Natural := Screen.Width - 1;
V_Column : constant Natural := W_Column - 8 * 8;
Q_Column : constant Natural := V_Column - 7 * 8;
begin
FB := (others => 0);
Render.Draw_String_Left (FB, "Qty",
X => Q_Column,
Y => Cargo_Y_Offest + 4);
Render.Draw_String_Left (FB, "Value",
X => V_Column,
Y => Cargo_Y_Offest + 4);
Render.Draw_String_Left (FB, "Weight",
X => W_Column,
Y => Cargo_Y_Offest + 4);
Cargo_Y_Offest := Cargo_Y_Offest + 20;
for Kind in World.Valuable_Cell loop
declare
Qty : constant Natural := Player.Quantity (Kind);
Value : constant Natural := Qty * Parameters.Value (Kind);
Weight : constant Natural := Qty * Parameters.Weight (Kind);
begin
Render.Draw_Cell (FB, Cargo_X_Offset, Cargo_Y_Offest, Kind);
Render.Draw_String_Left (FB => FB,
Str => Integer'Image (Qty),
X => Q_Column,
Y => Cargo_Y_Offest + 4);
Render.Draw_String_Left (FB => FB,
Str => Integer'Image (Value),
X => V_Column,
Y => Cargo_Y_Offest + 4);
Render.Draw_String_Left (FB => FB,
Str => Integer'Image (Weight),
X => W_Column,
Y => Cargo_Y_Offest + 4);
end;
if Selected = Kind then
Render.Draw_H_Line (FB,
Cargo_X_Offset, Cargo_Y_Offest,
Len => Screen.Width - Cargo_X_Offset - 1,
Color => UInt16'Last);
Render.Draw_H_Line (FB,
Cargo_X_Offset, Cargo_Y_Offest + World.Cell_Size,
Len => Screen.Width - Cargo_X_Offset - 1,
Color => UInt16'Last);
end if;
Cargo_Y_Offest := Cargo_Y_Offest + 20;
end loop;
Render.Draw_String (FB => FB,
Str => "Press A to drop",
X => 0,
Y => Cargo_Y_Offest + 4);
Render.Draw_String (FB => FB,
Str => "Press Select to exit",
X => 0,
Y => Cargo_Y_Offest + 4 + 16);
end Draw_Screen;
---------
-- Run --
---------
procedure Run is
Period : constant Time.Time_Ms := Parameters.Frame_Period;
Next_Release : Time.Time_Ms;
begin
Next_Release := Time.Clock;
loop
Controls.Scan;
if Controls.Falling (Controls.Sel) then
return;
end if;
if Controls.Falling (Controls.A) then
Player.Drop (Selected);
end if;
if Controls.Falling (Controls.Down) then
if Selected = World.Valuable_Cell'Last then
Selected := World.Valuable_Cell'First;
else
Selected := World.Valuable_Cell'Succ (Selected);
end if;
elsif Controls.Falling (Controls.Up) then
if Selected = World.Valuable_Cell'First then
Selected := World.Valuable_Cell'Last;
else
Selected := World.Valuable_Cell'Pred (Selected);
end if;
end if;
if Render.Flip then
Render.Refresh_Screen (Render.FB1'Access);
Draw_Screen (Render.FB2);
else
Render.Refresh_Screen (Render.FB2'Access);
Draw_Screen (Render.FB1);
end if;
Render.Flip := not Render.Flip;
Sound.Tick;
Time.Delay_Until (Next_Release);
Next_Release := Next_Release + Period;
end loop;
end Run;
end Cargo_Menu;
|
with Numerics, Numerics.Sparse_Matrices, Chebyshev, Ada.Text_IO;
use Numerics, Numerics.Sparse_Matrices, Chebyshev, Ada.Text_IO;
generic
K : in Nat;
N_Constraints : in Pos := 0;
package Dense_AD.Integrator is
N : constant Nat := (Num - N_Constraints) / 2;
type Dense_Or_Sparse is (Dense, Sparse);
type Create_Or_Append is (Create, Append, Neither);
type Variable is record
T : Real := 0.0;
X : Vector := (others => 0.0);
end record;
type Control_Type is record
Dto : Real := 1.0;
Dt : Real := 1.0;
Dtn : Real := 1.0;
Tol : Real := 1.0e-10;
Err : Real := 1.0;
Started : Boolean := False;
Max_Dt : Real := 1.0;
end record;
type Array_Of_Vectors is array (1 .. Num) of Real_Vector (1 .. K);
function New_Control_Type (Dt : in Real := 1.0;
Tol : in Real := 1.0e-10;
Started : in Boolean := False) return Control_Type;
function Chebyshev_Transform (Y : in Real_Vector) return Array_Of_Vectors
with Pre => Y'First = 1 and Y'Length = Num * K;
function Interpolate (A : in Array_Of_Vectors;
T : in Real;
L : in Real;
R : in Real) return Vector;
procedure Update (Var : in out Variable;
Y : in Real_Vector;
Dt : in Real)
with Pre => Y'First = 1 and Y'Length = Num * K;
function Update (Lagrangian : not null access
function (T : real; X : Vector) return AD_Type;
Var : in Variable;
Control : in out Control_Type;
Density : in Dense_Or_Sparse) return Real_Vector;
function Update (Lagrangian : not null access
function (T : real; X : Vector) return AD_Type;
Var : in Variable;
Control : in out Control_Type) return Real_Vector;
procedure Print_Lagrangian (File : in File_Type;
Var : in Variable;
Lagrangian : not null access
function (T : real; X : Vector) return AD_Type;
Fore : in Field := 3;
Aft : in Field := 5;
Exp : in Field := 3);
procedure Print_Lagrangian (Var : in Variable;
Lagrangian : not null access
function (T : real; X : Vector) return AD_Type;
Fore : in Field := 3;
Aft : in Field := 5;
Exp : in Field := 3);
procedure Print_XYZ (File : in out File_Type;
Var : in Variable);
procedure Print_XYZ (File : in out File_Type;
Var : in Variable;
Name : in String;
Mode : in Create_Or_Append := Neither);
procedure Print_CSV (File : in out File_Type;
Var : in Variable;
Name : in String;
Lagrangian : not null access
function (T : real; X : Vector) return AD_Type;
Mode : in Create_Or_Append := Neither);
function Hamiltonian (T : in Real;
X : in Vector;
Lagrangian : not null access
function (T : real; X : Vector) return AD_Type)
return Real;
function Split (Y : in Real_Vector) return Array_Of_Vectors
with Pre => Y'First = 1 and Y'Length = Num * K;
Grid : constant Real_Vector := Chebyshev_Gauss_Lobatto (K, 0.0, 1.0);
NK : constant Nat := Num * K;
private
Collocation_Density : Dense_Or_Sparse := Sparse;
procedure Iterate (Lagrangian : not null access
function (T : real; X : Vector) return AD_Type;
Y : in out Real_Vector;
Var : in Variable;
Control : in out Control_Type);
procedure Colloc (Lagrangian : not null access
function (T : real; X : Vector) return AD_Type;
Q : in out Real_Vector;
Var : in Variable;
Control : in out Control_Type);
procedure Collocation (Lagrangian : not null access
function (T : real; X : Vector) return AD_Type;
Q : in out Real_Vector;
Var : in Variable;
Control : in out Control_Type);
procedure FJ (Lagrangian : not null access
function (T : real; X : Vector) return AD_Type;
Var : in Variable;
Control : in Control_Type;
Q : in Real_Vector;
F : out Real_Vector;
J : out Real_Matrix);
procedure Sp_Collocation (Lagrangian : not null access
function (T : real; X : Vector) return AD_Type;
Q : in out Real_Vector;
Var : in Variable;
Control : in out Control_Type);
procedure Sp_FJ (Lagrangian : not null access
function (T : real; X : Vector) return AD_Type;
Var : in Variable;
Control : in Control_Type;
Q : in Real_Vector;
F : out Sparse_Vector;
J : out Sparse_Matrix);
type Array_Of_Sparse_Matrix is array (1 .. 4) of Sparse_Matrix;
function Setup return Array_Of_Sparse_Matrix;
Der : constant Real_Matrix := Derivative_Matrix (K, 0.0, 1.0);
EyeN : constant Sparse_Matrix := Eye (N);
EyeK : constant Sparse_Matrix := Eye (K);
Eye2N : constant Sparse_Matrix := Eye (2 * N);
EyeNc : constant Sparse_Matrix := Eye (N_Constraints);
D : constant Sparse_Matrix := Sparse (Der);
ZeroN : constant Sparse_Matrix := Zero (N);
ZeroNc : constant Sparse_Matrix := Zero (N_Constraints);
Zero2N : constant Sparse_Matrix := Zero (2 * N);
Sp : constant Array_Of_Sparse_Matrix := Setup;
Mat_A : constant Real_Matrix := Dense (Sp (1));
Mat_B : constant Real_Matrix := Dense (Sp (2));
Mat_C : constant Real_Matrix := Dense (Sp (3));
Mat_D : constant Real_Matrix := Dense (Sp (4));
end Dense_AD.Integrator;
|
with Ada.Text_IO, Matrix_Scalar;
procedure Scalar_Ops is
subtype T is Integer range 1 .. 3;
package M is new Matrix_Scalar(T, T, Integer);
-- the functions to solve the task
function "+" is new M.Func("+");
function "-" is new M.Func("-");
function "*" is new M.Func("*");
function "/" is new M.Func("/");
function "**" is new M.Func("**");
function "mod" is new M.Func("mod");
-- for output purposes, we need a Matrix->String conversion
function Image is new M.Image(Integer'Image);
A: M.Matrix := ((1,2,3),(4,5,6),(7,8,9)); -- something to begin with
begin
Ada.Text_IO.Put_Line(" Initial M=" & Image(A));
Ada.Text_IO.Put_Line(" M+2=" & Image(A+2));
Ada.Text_IO.Put_Line(" M-2=" & Image(A-2));
Ada.Text_IO.Put_Line(" M*2=" & Image(A*2));
Ada.Text_IO.Put_Line(" M/2=" & Image(A/2));
Ada.Text_IO.Put_Line(" square(M)=" & Image(A ** 2));
Ada.Text_IO.Put_Line(" M mod 2=" & Image(A mod 2));
Ada.Text_IO.Put_Line("(M*2) mod 3=" & Image((A*2) mod 3));
end Scalar_Ops;
|
with Interfaces.C.Strings;
package body Edit_Line is
package C renames Interfaces.C;
use type C.Strings.chars_ptr;
function Read_Line (Prompt : in String) return String is
function Read_Line (Prompt : in C.Strings.chars_ptr) return C.Strings.chars_ptr with
Import => True,
Convention => C,
External_Name => "readline";
C_Prompt : C.Strings.chars_ptr := C.Strings.New_String (Prompt);
C_Result : C.Strings.chars_ptr := Read_Line (C_Prompt);
begin
C.Strings.Free (C_Prompt);
if C_Result /= C.Strings.Null_Ptr then
return S : String := C.Strings.Value (C_Result) do
C.Strings.Free (C_Result);
end return;
end if;
return "";
end Read_Line;
procedure Add_History (Input : in String) is
procedure Add_History (Input : in C.Strings.chars_ptr) with
Import => True,
Convention => C,
External_Name => "add_history";
C_Input : C.Strings.chars_ptr := C.Strings.New_String (Input);
begin
Add_History (C_Input);
C.Strings.Free (C_Input);
end Add_History;
end Edit_Line;
|
with Ada.Finalization;
with System;
package body Ada.Exceptions.Finally is
pragma Suppress (All_Checks);
use type System.Address;
type Finalizer is limited new Finalization.Limited_Controlled with record
Params : System.Address;
Handler : not null access procedure (Params : System.Address);
end record;
pragma Discard_Names (Finalizer);
overriding procedure Finalize (Object : in out Finalizer);
overriding procedure Finalize (Object : in out Finalizer) is
begin
if Object.Params /= System.Null_Address then
Object.Handler (Object.Params);
end if;
end Finalize;
-- implementation
package body Scoped_Holder is
procedure Finally (Params : System.Address);
procedure Finally (Params : System.Address) is
function To_Pointer (Value : System.Address) return access Parameters
with Import, Convention => Intrinsic;
begin
Handler (To_Pointer (Params).all);
end Finally;
Object : Finalizer :=
(Finalization.Limited_Controlled
with Params => System.Null_Address, Handler => Finally'Access);
pragma Unreferenced (Object);
procedure Assign (Params : aliased in out Parameters) is
begin
Object.Params := Params'Address;
end Assign;
procedure Clear is
begin
Object.Params := System.Null_Address;
end Clear;
end Scoped_Holder;
procedure Try_Finally (
Params : aliased in out Parameters;
Process : not null access procedure (Params : in out Parameters);
Handler : not null access procedure (Params : in out Parameters))
is
procedure Finally (Params : System.Address);
procedure Finally (Params : System.Address) is
function To_Pointer (Value : System.Address) return access Parameters
with Import, Convention => Intrinsic;
begin
Handler (To_Pointer (Params).all);
end Finally;
Object : Finalizer :=
(Finalization.Limited_Controlled
with
Params => Params'Address,
Handler => Finally'Unrestricted_Access);
pragma Unreferenced (Object);
begin
Process.all (Params);
end Try_Finally;
procedure Try_When_All (
Params : aliased in out Parameters;
Process : not null access procedure (Params : in out Parameters);
Handler : not null access procedure (Params : in out Parameters))
is
procedure Finally (Params : System.Address);
procedure Finally (Params : System.Address) is
function To_Pointer (Value : System.Address) return access Parameters
with Import, Convention => Intrinsic;
begin
Handler (To_Pointer (Params).all);
end Finally;
Object : Finalizer :=
(Finalization.Limited_Controlled
with
Params => Params'Address,
Handler => Finally'Unrestricted_Access);
pragma Unreferenced (Object);
begin
Process.all (Params);
Object.Params := System.Null_Address;
end Try_When_All;
end Ada.Exceptions.Finally;
|
--
-- 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;
package Backend is
type Context_Type is
record
File_Template : Ada.Text_IO.File_Type;
end record;
Context : Context_Type;
end Backend;
|
with OpenAL.ALC_Thin;
with OpenAL.Types;
package body OpenAL.Context.Error is
function Get_Error (Device : in Device_t) return Error_t is
begin
return Map_Constant_To_Error (ALC_Thin.Get_Error (Device.Device_Data));
end Get_Error;
function Map_Constant_To_Error (Error : in Types.Enumeration_t) return Error_t is
Value : Error_t;
begin
case Error is
when ALC_Thin.ALC_NO_ERROR => Value := No_Error;
when ALC_Thin.ALC_INVALID_DEVICE => Value := Invalid_Device;
when ALC_Thin.ALC_INVALID_CONTEXT => Value := Invalid_Context;
when ALC_Thin.ALC_INVALID_ENUM => Value := Invalid_Enumeration;
when ALC_Thin.ALC_INVALID_VALUE => Value := Invalid_Value;
when ALC_Thin.ALC_OUT_OF_MEMORY => Value := Out_Of_Memory;
when others => Value := Unknown_Error;
end case;
return Value;
end Map_Constant_To_Error;
end OpenAL.Context.Error;
|
-- Lumen.Joystick -- Support (Linux) joysticks under Lumen
--
-- Chip Richards, NiEstu, Phoenix AZ, Summer 2010
-- This code is covered by the ISC License:
--
-- Copyright © 2010, NiEstu
--
-- Permission to use, copy, modify, and/or distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- The software is provided "as is" and the author disclaims all warranties
-- with regard to this software including all implied warranties of
-- merchantability and fitness. In no event shall the author be liable for any
-- special, direct, indirect, or consequential damages or any damages
-- whatsoever resulting from loss of use, data or profits, whether in an
-- action of contract, negligence or other tortious action, arising out of or
-- in connection with the use or performance of this software.
-- Environment
with Ada.Finalization;
with Lumen.Internal;
with Lumen.Window;
package Lumen.Joystick is
---------------------------------------------------------------------------
-- Exceptions defined by this package
Open_Failed : exception; -- cannot open given joystick device, or cannot fetch its info
-- The default joystick device pathname
Default_Pathname : String := "/dev/input/js0";
---------------------------------------------------------------------------
-- Joystick event
type Joystick_Event_Type is (Joystick_Axis_Change, Joystick_Button_Press, Joystick_Button_Release);
type Joystick_Event_Data (Which : Joystick_Event_Type := Joystick_Axis_Change) is record
Number : Positive; -- which axis or button
case Which is
when Joystick_Axis_Change =>
Axis_Value : Integer;
when Joystick_Button_Press | Joystick_Button_Release =>
null;
end case;
end record;
---------------------------------------------------------------------------
-- Our joystick handle, used to refer to joysticks within the library and app
type Stick_Info_Pointer is private;
type Handle is new Ada.Finalization.Limited_Controlled with record
Info : Stick_Info_Pointer;
end record;
procedure Finalize (Stick : in out Handle);
---------------------------------------------------------------------------
-- Open a joystick device
procedure Open (Stick : in out Handle;
Path : in String := Default_Pathname);
-- Close a joystick device
procedure Close (Stick : in out Handle);
-- Various joystick information functions
function Name (Stick : in Handle) return String; -- joystick's name
function Axes (Stick : in Handle) return Natural; -- number of axes
function Buttons (Stick : in Handle) return Natural; -- number of buttons
-- Returns the number of events that are waiting in the joystick's event
-- queue. Useful to avoid blocking while waiting for the next event to
-- show up.
function Pending (Stick : in Handle) return Natural;
-- Read a joystick event
function Next_Event (Stick : in Handle) return Joystick_Event_Data;
---------------------------------------------------------------------------
private
type Stick_Info;
type Stick_Info_Pointer is access Stick_Info;
end Lumen.Joystick;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- T Y P E S --
-- --
-- S p e c --
-- --
-- Copyright (C) 1992-2015, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This package contains host independent type definitions which are used
-- in more than one unit in the compiler. They are gathered here for easy
-- reference, although in some cases the full description is found in the
-- relevant module which implements the definition. The main reason that they
-- are not in their "natural" specs is that this would cause a lot of inter-
-- spec dependencies, and in particular some awkward circular dependencies
-- would have to be dealt with.
-- WARNING: There is a C version of this package. Any changes to this source
-- file must be properly reflected in the C header file types.h declarations.
-- Note: the declarations in this package reflect an expectation that the host
-- machine has an efficient integer base type with a range at least 32 bits
-- 2s-complement. If there are any machines for which this is not a correct
-- assumption, a significant number of changes will be required.
with System;
with Unchecked_Conversion;
with Unchecked_Deallocation;
package Types is
pragma Preelaborate;
-------------------------------
-- General Use Integer Types --
-------------------------------
type Int is range -2 ** 31 .. +2 ** 31 - 1;
-- Signed 32-bit integer
subtype Nat is Int range 0 .. Int'Last;
-- Non-negative Int values
subtype Pos is Int range 1 .. Int'Last;
-- Positive Int values
type Word is mod 2 ** 32;
-- Unsigned 32-bit integer
type Short is range -32768 .. +32767;
for Short'Size use 16;
-- 16-bit signed integer
type Byte is mod 2 ** 8;
for Byte'Size use 8;
-- 8-bit unsigned integer
type size_t is mod 2 ** Standard'Address_Size;
-- Memory size value, for use in calls to C routines
--------------------------------------
-- 8-Bit Character and String Types --
--------------------------------------
-- We use Standard.Character and Standard.String freely, since we are
-- compiling ourselves, and we properly implement the required 8-bit
-- character code as required in Ada 95. This section defines a few
-- general use constants and subtypes.
EOF : constant Character := ASCII.SUB;
-- The character SUB (16#1A#) is used in DOS and other systems derived
-- from DOS (XP, NT etc) to signal the end of a text file. Internally
-- all source files are ended by an EOF character, even on Unix systems.
-- An EOF character acts as the end of file only as the last character
-- of a source buffer, in any other position, it is treated as a blank
-- if it appears between tokens, and as an illegal character otherwise.
-- This makes life easier dealing with files that originated from DOS,
-- including concatenated files with interspersed EOF characters.
subtype Graphic_Character is Character range ' ' .. '~';
-- Graphic characters, as defined in ARM
subtype Line_Terminator is Character range ASCII.LF .. ASCII.CR;
-- Line terminator characters (LF, VT, FF, CR). For further details, see
-- the extensive discussion of line termination in the Sinput spec.
subtype Upper_Half_Character is
Character range Character'Val (16#80#) .. Character'Val (16#FF#);
-- 8-bit Characters with the upper bit set
type Character_Ptr is access all Character;
type String_Ptr is access all String;
-- Standard character and string pointers
procedure Free is new Unchecked_Deallocation (String, String_Ptr);
-- Procedure for freeing dynamically allocated String values
subtype Big_String is String (Positive);
type Big_String_Ptr is access all Big_String;
-- Virtual type for handling imported big strings. Note that we should
-- never have any allocators for this type, but we don't give a storage
-- size of zero, since there are legitimate deallocations going on.
function To_Big_String_Ptr is
new Unchecked_Conversion (System.Address, Big_String_Ptr);
-- Used to obtain Big_String_Ptr values from external addresses
subtype Word_Hex_String is String (1 .. 8);
-- Type used to represent Word value as 8 hex digits, with lower case
-- letters for the alphabetic cases.
function Get_Hex_String (W : Word) return Word_Hex_String;
-- Convert word value to 8-character hex string
-----------------------------------------
-- Types Used for Text Buffer Handling --
-----------------------------------------
-- We can not use type String for text buffers, since we must use the
-- standard 32-bit integer as an index value, since we count on all index
-- values being the same size.
type Text_Ptr is new Int;
-- Type used for subscripts in text buffer
type Text_Buffer is array (Text_Ptr range <>) of Character;
-- Text buffer used to hold source file or library information file
type Text_Buffer_Ptr is access all Text_Buffer;
-- Text buffers for input files are allocated dynamically and this type
-- is used to reference these text buffers.
procedure Free is new Unchecked_Deallocation (Text_Buffer, Text_Buffer_Ptr);
-- Procedure for freeing dynamically allocated text buffers
------------------------------------------
-- Types Used for Source Input Handling --
------------------------------------------
type Logical_Line_Number is range 0 .. Int'Last;
for Logical_Line_Number'Size use 32;
-- Line number type, used for storing logical line numbers (i.e. line
-- numbers that include effects of any Source_Reference pragmas in the
-- source file). The value zero indicates a line containing a source
-- reference pragma.
No_Line_Number : constant Logical_Line_Number := 0;
-- Special value used to indicate no line number
type Physical_Line_Number is range 1 .. Int'Last;
for Physical_Line_Number'Size use 32;
-- Line number type, used for storing physical line numbers (i.e. line
-- numbers in the physical file being compiled, unaffected by the presence
-- of source reference pragmas).
type Column_Number is range 0 .. 32767;
for Column_Number'Size use 16;
-- Column number (assume that 2**15 - 1 is large enough). The range for
-- this type is used to compute Hostparm.Max_Line_Length. See also the
-- processing for -gnatyM in Stylesw).
No_Column_Number : constant Column_Number := 0;
-- Special value used to indicate no column number
Source_Align : constant := 2 ** 12;
-- Alignment requirement for source buffers (by keeping source buffers
-- aligned, we can optimize the implementation of Get_Source_File_Index.
-- See this routine in Sinput for details.
subtype Source_Buffer is Text_Buffer;
-- Type used to store text of a source file. The buffer for the main
-- source (the source specified on the command line) has a lower bound
-- starting at zero. Subsequent subsidiary sources have lower bounds
-- which are one greater than the previous upper bound, rounded up to
-- a multiple of Source_Align.
subtype Big_Source_Buffer is Text_Buffer (0 .. Text_Ptr'Last);
-- This is a virtual type used as the designated type of the access type
-- Source_Buffer_Ptr, see Osint.Read_Source_File for details.
type Source_Buffer_Ptr is access all Big_Source_Buffer;
-- Pointer to source buffer. We use virtual origin addressing for source
-- buffers, with thin pointers. The pointer points to a virtual instance
-- of type Big_Source_Buffer, where the actual type is in fact of type
-- Source_Buffer. The address is adjusted so that the virtual origin
-- addressing works correctly. See Osint.Read_Source_Buffer for further
-- details. Again, as for Big_String_Ptr, we should never allocate using
-- this type, but we don't give a storage size clause of zero, since we
-- may end up doing deallocations of instances allocated manually.
subtype Source_Ptr is Text_Ptr;
-- Type used to represent a source location, which is a subscript of a
-- character in the source buffer. As noted above, different source buffers
-- have different ranges, so it is possible to tell from a Source_Ptr value
-- which source it refers to. Note that negative numbers are allowed to
-- accommodate the following special values.
No_Location : constant Source_Ptr := -1;
-- Value used to indicate no source position set in a node. A test for a
-- Source_Ptr value being > No_Location is the approved way to test for a
-- standard value that does not include No_Location or any of the following
-- special definitions. One important use of No_Location is to label
-- generated nodes that we don't want the debugger to see in normal mode
-- (very often we conditionalize so that we set No_Location in normal mode
-- and the corresponding source line in -gnatD mode).
Standard_Location : constant Source_Ptr := -2;
-- Used for all nodes in the representation of package Standard other than
-- nodes representing the contents of Standard.ASCII. Note that testing for
-- a value being <= Standard_Location tests for both Standard_Location and
-- for Standard_ASCII_Location.
Standard_ASCII_Location : constant Source_Ptr := -3;
-- Used for all nodes in the presentation of package Standard.ASCII
System_Location : constant Source_Ptr := -4;
-- Used to identify locations of pragmas scanned by Targparm, where we know
-- the location is in System, but we don't know exactly what line.
First_Source_Ptr : constant Source_Ptr := 0;
-- Starting source pointer index value for first source program
-------------------------------------
-- Range Definitions for Tree Data --
-------------------------------------
-- The tree has fields that can hold any of the following types:
-- Pointers to other tree nodes (type Node_Id)
-- List pointers (type List_Id)
-- Element list pointers (type Elist_Id)
-- Names (type Name_Id)
-- Strings (type String_Id)
-- Universal integers (type Uint)
-- Universal reals (type Ureal)
-- In most contexts, the strongly typed interface determines which of these
-- types is present. However, there are some situations (involving untyped
-- traversals of the tree), where it is convenient to be easily able to
-- distinguish these values. The underlying representation in all cases is
-- an integer type Union_Id, and we ensure that the range of the various
-- possible values for each of the above types is disjoint so that this
-- distinction is possible.
-- Note: it is also helpful for debugging purposes to make these ranges
-- distinct. If a bug leads to misidentification of a value, then it will
-- typically result in an out of range value and a Constraint_Error.
type Union_Id is new Int;
-- The type in the tree for a union of possible ID values
List_Low_Bound : constant := -100_000_000;
-- The List_Id values are subscripts into an array of list headers which
-- has List_Low_Bound as its lower bound. This value is chosen so that all
-- List_Id values are negative, and the value zero is in the range of both
-- List_Id and Node_Id values (see further description below).
List_High_Bound : constant := 0;
-- Maximum List_Id subscript value. This allows up to 100 million list Id
-- values, which is in practice infinite, and there is no need to check the
-- range. The range overlaps the node range by one element (with value
-- zero), which is used both for the Empty node, and for indicating no
-- list. The fact that the same value is used is convenient because it
-- means that the default value of Empty applies to both nodes and lists,
-- and also is more efficient to test for.
Node_Low_Bound : constant := 0;
-- The tree Id values start at zero, because we use zero for Empty (to
-- allow a zero test for Empty). Actual tree node subscripts start at 0
-- since Empty is a legitimate node value.
Node_High_Bound : constant := 099_999_999;
-- Maximum number of nodes that can be allocated is 100 million, which
-- is in practice infinite, and there is no need to check the range.
Elist_Low_Bound : constant := 100_000_000;
-- The Elist_Id values are subscripts into an array of elist headers which
-- has Elist_Low_Bound as its lower bound.
Elist_High_Bound : constant := 199_999_999;
-- Maximum Elist_Id subscript value. This allows up to 100 million Elists,
-- which is in practice infinite and there is no need to check the range.
Elmt_Low_Bound : constant := 200_000_000;
-- Low bound of element Id values. The use of these values is internal to
-- the Elists package, but the definition of the range is included here
-- since it must be disjoint from other Id values. The Elmt_Id values are
-- subscripts into an array of list elements which has this as lower bound.
Elmt_High_Bound : constant := 299_999_999;
-- Upper bound of Elmt_Id values. This allows up to 100 million element
-- list members, which is in practice infinite (no range check needed).
Names_Low_Bound : constant := 300_000_000;
-- Low bound for name Id values
Names_High_Bound : constant := 399_999_999;
-- Maximum number of names that can be allocated is 100 million, which is
-- in practice infinite and there is no need to check the range.
Strings_Low_Bound : constant := 400_000_000;
-- Low bound for string Id values
Strings_High_Bound : constant := 499_999_999;
-- Maximum number of strings that can be allocated is 100 million, which
-- is in practice infinite and there is no need to check the range.
Ureal_Low_Bound : constant := 500_000_000;
-- Low bound for Ureal values
Ureal_High_Bound : constant := 599_999_999;
-- Maximum number of Ureal values stored is 100_000_000 which is in
-- practice infinite so that no check is required.
Uint_Low_Bound : constant := 600_000_000;
-- Low bound for Uint values
Uint_Table_Start : constant := 2_000_000_000;
-- Location where table entries for universal integers start (see
-- Uintp spec for details of the representation of Uint values).
Uint_High_Bound : constant := 2_099_999_999;
-- The range of Uint values is very large, since a substantial part
-- of this range is used to store direct values, see Uintp for details.
-- The following subtype definitions are used to provide convenient names
-- for membership tests on Int values to see what data type range they
-- lie in. Such tests appear only in the lowest level packages.
subtype List_Range is Union_Id
range List_Low_Bound .. List_High_Bound;
subtype Node_Range is Union_Id
range Node_Low_Bound .. Node_High_Bound;
subtype Elist_Range is Union_Id
range Elist_Low_Bound .. Elist_High_Bound;
subtype Elmt_Range is Union_Id
range Elmt_Low_Bound .. Elmt_High_Bound;
subtype Names_Range is Union_Id
range Names_Low_Bound .. Names_High_Bound;
subtype Strings_Range is Union_Id
range Strings_Low_Bound .. Strings_High_Bound;
subtype Uint_Range is Union_Id
range Uint_Low_Bound .. Uint_High_Bound;
subtype Ureal_Range is Union_Id
range Ureal_Low_Bound .. Ureal_High_Bound;
-----------------------------
-- Types for Atree Package --
-----------------------------
-- Node_Id values are used to identify nodes in the tree. They are
-- subscripts into the Nodes table declared in package Atree. Note that
-- the special values Empty and Error are subscripts into this table.
-- See package Atree for further details.
type Node_Id is range Node_Low_Bound .. Node_High_Bound;
-- Type used to identify nodes in the tree
subtype Entity_Id is Node_Id;
-- A synonym for node types, used in the Einfo package to refer to nodes
-- that are entities (i.e. nodes with an Nkind of N_Defining_xxx). All such
-- nodes are extended nodes and these are the only extended nodes, so that
-- in practice entity and extended nodes are synonymous.
subtype Node_Or_Entity_Id is Node_Id;
-- A synonym for node types, used in cases where a given value may be used
-- to represent either a node or an entity. We like to minimize such uses
-- for obvious reasons of logical type consistency, but where such uses
-- occur, they should be documented by use of this type.
Empty : constant Node_Id := Node_Low_Bound;
-- Used to indicate null node. A node is actually allocated with this
-- Id value, so that Nkind (Empty) = N_Empty. Note that Node_Low_Bound
-- is zero, so Empty = No_List = zero.
Empty_List_Or_Node : constant := 0;
-- This constant is used in situations (e.g. initializing empty fields)
-- where the value set will be used to represent either an empty node or
-- a non-existent list, depending on the context.
Error : constant Node_Id := Node_Low_Bound + 1;
-- Used to indicate an error in the source program. A node is actually
-- allocated with this Id value, so that Nkind (Error) = N_Error.
Empty_Or_Error : constant Node_Id := Error;
-- Since Empty and Error are the first two Node_Id values, the test for
-- N <= Empty_Or_Error tests to see if N is Empty or Error. This definition
-- provides convenient self-documentation for such tests.
First_Node_Id : constant Node_Id := Node_Low_Bound;
-- Subscript of first allocated node. Note that Empty and Error are both
-- allocated nodes, whose Nkind fields can be accessed without error.
------------------------------
-- Types for Nlists Package --
------------------------------
-- List_Id values are used to identify node lists stored in the tree, so
-- that each node can be on at most one such list (see package Nlists for
-- further details). Note that the special value Error_List is a subscript
-- in this table, but the value No_List is *not* a valid subscript, and any
-- attempt to apply list operations to No_List will cause a (detected)
-- error.
type List_Id is range List_Low_Bound .. List_High_Bound;
-- Type used to identify a node list
No_List : constant List_Id := List_High_Bound;
-- Used to indicate absence of a list. Note that the value is zero, which
-- is the same as Empty, which is helpful in initializing nodes where a
-- value of zero can represent either an empty node or an empty list.
Error_List : constant List_Id := List_Low_Bound;
-- Used to indicate that there was an error in the source program in a
-- context which would normally require a list. This node appears to be
-- an empty list to the list operations (a null list is actually allocated
-- which has this Id value).
First_List_Id : constant List_Id := Error_List;
-- Subscript of first allocated list header
------------------------------
-- Types for Elists Package --
------------------------------
-- Element list Id values are used to identify element lists stored outside
-- of the tree, allowing nodes to be members of more than one such list
-- (see package Elists for further details).
type Elist_Id is range Elist_Low_Bound .. Elist_High_Bound;
-- Type used to identify an element list (Elist header table subscript)
No_Elist : constant Elist_Id := Elist_Low_Bound;
-- Used to indicate absence of an element list. Note that this is not an
-- actual Elist header, so element list operations on this value are not
-- valid.
First_Elist_Id : constant Elist_Id := No_Elist + 1;
-- Subscript of first allocated Elist header
-- Element Id values are used to identify individual elements of an element
-- list (see package Elists for further details).
type Elmt_Id is range Elmt_Low_Bound .. Elmt_High_Bound;
-- Type used to identify an element list
No_Elmt : constant Elmt_Id := Elmt_Low_Bound;
-- Used to represent empty element
First_Elmt_Id : constant Elmt_Id := No_Elmt + 1;
-- Subscript of first allocated Elmt table entry
-------------------------------
-- Types for Stringt Package --
-------------------------------
-- String_Id values are used to identify entries in the strings table. They
-- are subscripts into the Strings table defined in package Stringt.
-- Note that with only a few exceptions, which are clearly documented, the
-- type String_Id should be regarded as a private type. In particular it is
-- never appropriate to perform arithmetic operations using this type.
-- Doesn't this also apply to all other *_Id types???
type String_Id is range Strings_Low_Bound .. Strings_High_Bound;
-- Type used to identify entries in the strings table
No_String : constant String_Id := Strings_Low_Bound;
-- Used to indicate missing string Id. Note that the value zero is used
-- to indicate a missing data value for all the Int types in this section.
First_String_Id : constant String_Id := No_String + 1;
-- First subscript allocated in string table
-------------------------
-- Character Code Type --
-------------------------
-- The type Char is used for character data internally in the compiler, but
-- character codes in the source are represented by the Char_Code type.
-- Each character literal in the source is interpreted as being one of the
-- 16#7FFF_FFFF# possible Wide_Wide_Character codes, and a unique Integer
-- value is assigned, corresponding to the UTF-32 value, which also
-- corresponds to the Pos value in the Wide_Wide_Character type, and also
-- corresponds to the Pos value in the Wide_Character and Character types
-- for values that are in appropriate range. String literals are similarly
-- interpreted as a sequence of such codes.
type Char_Code_Base is mod 2 ** 32;
for Char_Code_Base'Size use 32;
subtype Char_Code is Char_Code_Base range 0 .. 16#7FFF_FFFF#;
for Char_Code'Value_Size use 32;
for Char_Code'Object_Size use 32;
function Get_Char_Code (C : Character) return Char_Code;
pragma Inline (Get_Char_Code);
-- Function to obtain internal character code from source character. For
-- the moment, the internal character code is simply the Pos value of the
-- input source character, but we provide this interface for possible
-- later support of alternative character sets.
function In_Character_Range (C : Char_Code) return Boolean;
pragma Inline (In_Character_Range);
-- Determines if the given character code is in range of type Character,
-- and if so, returns True. If not, returns False.
function In_Wide_Character_Range (C : Char_Code) return Boolean;
pragma Inline (In_Wide_Character_Range);
-- Determines if the given character code is in range of the type
-- Wide_Character, and if so, returns True. If not, returns False.
function Get_Character (C : Char_Code) return Character;
pragma Inline (Get_Character);
-- For a character C that is in Character range (see above function), this
-- function returns the corresponding Character value. It is an error to
-- call Get_Character if C is not in Character range.
function Get_Wide_Character (C : Char_Code) return Wide_Character;
-- For a character C that is in Wide_Character range (see above function),
-- this function returns the corresponding Wide_Character value. It is an
-- error to call Get_Wide_Character if C is not in Wide_Character range.
---------------------------------------
-- Types used for Library Management --
---------------------------------------
type Unit_Number_Type is new Int;
-- Unit number. The main source is unit 0, and subsidiary sources have
-- non-zero numbers starting with 1. Unit numbers are used to index the
-- Units table in package Lib.
Main_Unit : constant Unit_Number_Type := 0;
-- Unit number value for main unit
No_Unit : constant Unit_Number_Type := -1;
-- Special value used to signal no unit
type Source_File_Index is new Int range -1 .. Int'Last;
-- Type used to index the source file table (see package Sinput)
Internal_Source_File : constant Source_File_Index :=
Source_File_Index'First;
-- Value used to indicate the buffer for the source-code-like strings
-- internally created withing the compiler (see package Sinput)
No_Source_File : constant Source_File_Index := 0;
-- Value used to indicate no source file present
-----------------------------------
-- Representation of Time Stamps --
-----------------------------------
-- All compiled units are marked with a time stamp which is derived from
-- the source file (we assume that the host system has the concept of a
-- file time stamp which is modified when a file is modified). These
-- time stamps are used to ensure consistency of the set of units that
-- constitutes a library. Time stamps are 14-character strings with
-- with the following format:
-- YYYYMMDDHHMMSS
-- YYYY year
-- MM month (2 digits 01-12)
-- DD day (2 digits 01-31)
-- HH hour (2 digits 00-23)
-- MM minutes (2 digits 00-59)
-- SS seconds (2 digits 00-59)
-- In the case of Unix systems (and other systems which keep the time in
-- GMT), the time stamp is the GMT time of the file, not the local time.
-- This solves problems in using libraries across networks with clients
-- spread across multiple time-zones.
Time_Stamp_Length : constant := 14;
-- Length of time stamp value
subtype Time_Stamp_Index is Natural range 1 .. Time_Stamp_Length;
type Time_Stamp_Type is new String (Time_Stamp_Index);
-- Type used to represent time stamp
Empty_Time_Stamp : constant Time_Stamp_Type := (others => ' ');
-- Value representing an empty or missing time stamp. Looks less than any
-- real time stamp if two time stamps are compared. Note that although this
-- is not private, clients should not rely on the exact way in which this
-- string is represented, and instead should use the subprograms below.
Dummy_Time_Stamp : constant Time_Stamp_Type := (others => '0');
-- This is used for dummy time stamp values used in the D lines for
-- non-existent files, and is intended to be an impossible value.
function "=" (Left, Right : Time_Stamp_Type) return Boolean;
function "<=" (Left, Right : Time_Stamp_Type) return Boolean;
function ">=" (Left, Right : Time_Stamp_Type) return Boolean;
function "<" (Left, Right : Time_Stamp_Type) return Boolean;
function ">" (Left, Right : Time_Stamp_Type) return Boolean;
-- Comparison functions on time stamps. Note that two time stamps are
-- defined as being equal if they have the same day/month/year and the
-- hour/minutes/seconds values are within 2 seconds of one another. This
-- deals with rounding effects in library file time stamps caused by
-- copying operations during installation. We have particularly noticed
-- that WinNT seems susceptible to such changes.
--
-- Note : the Empty_Time_Stamp value looks equal to itself, and less than
-- any non-empty time stamp value.
procedure Split_Time_Stamp
(TS : Time_Stamp_Type;
Year : out Nat;
Month : out Nat;
Day : out Nat;
Hour : out Nat;
Minutes : out Nat;
Seconds : out Nat);
-- Given a time stamp, decompose it into its components
procedure Make_Time_Stamp
(Year : Nat;
Month : Nat;
Day : Nat;
Hour : Nat;
Minutes : Nat;
Seconds : Nat;
TS : out Time_Stamp_Type);
-- Given the components of a time stamp, initialize the value
-------------------------------------
-- Types used for Check Management --
-------------------------------------
type Check_Id is new Nat;
-- Type used to represent a check id
No_Check_Id : constant := 0;
-- Check_Id value used to indicate no check
Access_Check : constant := 1;
Accessibility_Check : constant := 2;
Alignment_Check : constant := 3;
Allocation_Check : constant := 4;
Atomic_Synchronization : constant := 5;
Discriminant_Check : constant := 6;
Division_Check : constant := 7;
Duplicated_Tag_Check : constant := 8;
Elaboration_Check : constant := 9;
Index_Check : constant := 10;
Length_Check : constant := 11;
Overflow_Check : constant := 12;
Predicate_Check : constant := 13;
Range_Check : constant := 14;
Storage_Check : constant := 15;
Tag_Check : constant := 16;
Validity_Check : constant := 17;
-- Values used to represent individual predefined checks (including the
-- setting of Atomic_Synchronization, which is implemented internally using
-- a "check" whose name is Atomic_Synchronization).
All_Checks : constant := 18;
-- Value used to represent All_Checks value
subtype Predefined_Check_Id is Check_Id range 1 .. All_Checks;
-- Subtype for predefined checks, including All_Checks
-- The following array contains an entry for each recognized check name
-- for pragma Suppress. It is used to represent current settings of scope
-- based suppress actions from pragma Suppress or command line settings.
-- Note: when Suppress_Array (All_Checks) is True, then generally all other
-- specific check entries are set True, except for the Elaboration_Check
-- entry which is set only if an explicit Suppress for this check is given.
-- The reason for this non-uniformity is that we do not want All_Checks to
-- suppress elaboration checking when using the static elaboration model.
-- We recognize only an explicit suppress of Elaboration_Check as a signal
-- that the static elaboration checking should skip a compile time check.
type Suppress_Array is array (Predefined_Check_Id) of Boolean;
pragma Pack (Suppress_Array);
-- To add a new check type to GNAT, the following steps are required:
-- 1. Add an entry to Snames spec for the new name
-- 2. Add an entry to the definition of Check_Id above
-- 3. Add a new function to Checks to handle the new check test
-- 4. Add a new Do_xxx_Check flag to Sinfo (if required)
-- 5. Add appropriate checks for the new test
-- The following provides precise details on the mode used to generate
-- code for intermediate operations in expressions for signed integer
-- arithmetic (and how to generate overflow checks if enabled). Note
-- that this only affects handling of intermediate results. The final
-- result must always fit within the target range, and if overflow
-- checking is enabled, the check on the final result is against this
-- target range.
type Overflow_Mode_Type is (
Not_Set,
-- Dummy value used during initialization process to show that the
-- corresponding value has not yet been initialized.
Strict,
-- Operations are done in the base type of the subexpression. If
-- overflow checks are enabled, then the check is against the range
-- of this base type.
Minimized,
-- Where appropriate, intermediate arithmetic operations are performed
-- with an extended range, using Long_Long_Integer if necessary. If
-- overflow checking is enabled, then the check is against the range
-- of Long_Long_Integer.
Eliminated);
-- In this mode arbitrary precision arithmetic is used as needed to
-- ensure that it is impossible for intermediate arithmetic to cause an
-- overflow. In this mode, intermediate expressions are not affected by
-- the overflow checking mode, since overflows are eliminated.
subtype Minimized_Or_Eliminated is
Overflow_Mode_Type range Minimized .. Eliminated;
-- Define subtype so that clients don't need to know ordering. Note that
-- Overflow_Mode_Type is not marked as an ordered enumeration type.
-- The following structure captures the state of check suppression or
-- activation at a particular point in the program execution.
type Suppress_Record is record
Suppress : Suppress_Array;
-- Indicates suppression status of each possible check
Overflow_Mode_General : Overflow_Mode_Type;
-- This field indicates the mode for handling code generation and
-- overflow checking (if enabled) for intermediate expression values.
-- This applies to general expressions outside assertions.
Overflow_Mode_Assertions : Overflow_Mode_Type;
-- This field indicates the mode for handling code generation and
-- overflow checking (if enabled) for intermediate expression values.
-- This applies to any expression occuring inside assertions.
end record;
-----------------------------------
-- Global Exception Declarations --
-----------------------------------
-- This section contains declarations of exceptions that are used
-- throughout the compiler or in other GNAT tools.
Unrecoverable_Error : exception;
-- This exception is raised to immediately terminate the compilation of the
-- current source program. Used in situations where things are bad enough
-- that it doesn't seem worth continuing (e.g. max errors reached, or a
-- required file is not found). Also raised when the compiler finds itself
-- in trouble after an error (see Comperr).
Terminate_Program : exception;
-- This exception is raised to immediately terminate the tool being
-- executed. Each tool where this exception may be raised must have a
-- single exception handler that contains only a null statement and that is
-- the last statement of the program. If needed, procedure Set_Exit_Status
-- is called with the appropriate exit status before raising
-- Terminate_Program.
---------------------------------
-- Parameter Mechanism Control --
---------------------------------
-- Function and parameter entities have a field that records the passing
-- mechanism. See specification of Sem_Mech for full details. The following
-- subtype is used to represent values of this type:
subtype Mechanism_Type is Int range -2 .. Int'Last;
-- Type used to represent a mechanism value. This is a subtype rather than
-- a type to avoid some annoying processing problems with certain routines
-- in Einfo (processing them to create the corresponding C). The values in
-- the range -2 .. 0 are used to represent mechanism types declared as
-- named constants in the spec of Sem_Mech. Positive values are used for
-- the case of a pragma C_Pass_By_Copy that sets a threshold value for the
-- mechanism to be used. For example if pragma C_Pass_By_Copy (32) is given
-- then Default_C_Record_Mechanism is set to 32, and the meaning is to use
-- By_Reference if the size is greater than 32, and By_Copy otherwise.
------------------------------
-- Run-Time Exception Codes --
------------------------------
-- When the code generator generates a run-time exception, it provides a
-- reason code which is one of the following. This reason code is used to
-- select the appropriate run-time routine to be called, determining both
-- the exception to be raised, and the message text to be added.
-- The prefix CE/PE/SE indicates the exception to be raised
-- CE = Constraint_Error
-- PE = Program_Error
-- SE = Storage_Error
-- The remaining part of the name indicates the message text to be added,
-- where all letters are lower case, and underscores are converted to
-- spaces (for example CE_Invalid_Data adds the text "invalid data").
-- To add a new code, you need to do the following:
-- 1. Assign a new number to the reason. Do not renumber existing codes,
-- since this causes compatibility/bootstrap issues, and problems in
-- the CIL/JVM backends. So always add the new code at the end of the
-- list.
-- 2. Update the contents of the array Kind
-- 3. Modify the corresponding definitions in types.h, including the
-- definition of last_reason_code.
-- 4. Add the name of the routines in exp_ch11.Get_RT_Exception_Name
-- 5. Add a new routine in Ada.Exceptions with the appropriate call and
-- static string constant. Note that there is more than one version
-- of a-except.adb which must be modified.
-- Note on ordering of references. For the tables in Ada.Exceptions units,
-- usually the ordering does not matter, and we use the same ordering as
-- is used here (note the requirement in the ordering here that CE/PE/SE
-- codes be kept together, so the subtype declarations work OK). However,
-- there is an important exception, which is in a-except-2005.adb, where
-- ordering of the Rcheck routines must correspond to the ordering of the
-- Rmsg_xx messages. This is required by the .NET scripts.
type RT_Exception_Code is
(CE_Access_Check_Failed, -- 00
CE_Access_Parameter_Is_Null, -- 01
CE_Discriminant_Check_Failed, -- 02
CE_Divide_By_Zero, -- 03
CE_Explicit_Raise, -- 04
CE_Index_Check_Failed, -- 05
CE_Invalid_Data, -- 06
CE_Length_Check_Failed, -- 07
CE_Null_Exception_Id, -- 08
CE_Null_Not_Allowed, -- 09
CE_Overflow_Check_Failed, -- 10
CE_Partition_Check_Failed, -- 11
CE_Range_Check_Failed, -- 12
CE_Tag_Check_Failed, -- 13
PE_Access_Before_Elaboration, -- 14
PE_Accessibility_Check_Failed, -- 15
PE_Address_Of_Intrinsic, -- 16
PE_Aliased_Parameters, -- 17
PE_All_Guards_Closed, -- 18
PE_Bad_Predicated_Generic_Type, -- 19
PE_Current_Task_In_Entry_Body, -- 20
PE_Duplicated_Entry_Address, -- 21
PE_Explicit_Raise, -- 22
PE_Finalize_Raised_Exception, -- 23
PE_Implicit_Return, -- 24
PE_Misaligned_Address_Value, -- 25
PE_Missing_Return, -- 26
PE_Overlaid_Controlled_Object, -- 27
PE_Potentially_Blocking_Operation, -- 28
PE_Stubbed_Subprogram_Called, -- 29
PE_Unchecked_Union_Restriction, -- 30
PE_Non_Transportable_Actual, -- 31
SE_Empty_Storage_Pool, -- 32
SE_Explicit_Raise, -- 33
SE_Infinite_Recursion, -- 34
SE_Object_Too_Large, -- 35
PE_Stream_Operation_Not_Allowed); -- 36
Last_Reason_Code : constant := 36;
-- Last reason code
type Reason_Kind is (CE_Reason, PE_Reason, SE_Reason);
-- Categorization of reason codes by exception raised
Rkind : array (RT_Exception_Code range <>) of Reason_Kind :=
(CE_Access_Check_Failed => CE_Reason,
CE_Access_Parameter_Is_Null => CE_Reason,
CE_Discriminant_Check_Failed => CE_Reason,
CE_Divide_By_Zero => CE_Reason,
CE_Explicit_Raise => CE_Reason,
CE_Index_Check_Failed => CE_Reason,
CE_Invalid_Data => CE_Reason,
CE_Length_Check_Failed => CE_Reason,
CE_Null_Exception_Id => CE_Reason,
CE_Null_Not_Allowed => CE_Reason,
CE_Overflow_Check_Failed => CE_Reason,
CE_Partition_Check_Failed => CE_Reason,
CE_Range_Check_Failed => CE_Reason,
CE_Tag_Check_Failed => CE_Reason,
PE_Access_Before_Elaboration => PE_Reason,
PE_Accessibility_Check_Failed => PE_Reason,
PE_Address_Of_Intrinsic => PE_Reason,
PE_Aliased_Parameters => PE_Reason,
PE_All_Guards_Closed => PE_Reason,
PE_Bad_Predicated_Generic_Type => PE_Reason,
PE_Current_Task_In_Entry_Body => PE_Reason,
PE_Duplicated_Entry_Address => PE_Reason,
PE_Explicit_Raise => PE_Reason,
PE_Finalize_Raised_Exception => PE_Reason,
PE_Implicit_Return => PE_Reason,
PE_Misaligned_Address_Value => PE_Reason,
PE_Missing_Return => PE_Reason,
PE_Overlaid_Controlled_Object => PE_Reason,
PE_Potentially_Blocking_Operation => PE_Reason,
PE_Stubbed_Subprogram_Called => PE_Reason,
PE_Unchecked_Union_Restriction => PE_Reason,
PE_Non_Transportable_Actual => PE_Reason,
PE_Stream_Operation_Not_Allowed => PE_Reason,
SE_Empty_Storage_Pool => SE_Reason,
SE_Explicit_Raise => SE_Reason,
SE_Infinite_Recursion => SE_Reason,
SE_Object_Too_Large => SE_Reason);
end Types;
|
-- Copyright 2018-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.Characters.Handling; use Ada.Characters.Handling;
with DOM.Core; use DOM.Core;
with DOM.Core.Documents;
with DOM.Core.Nodes; use DOM.Core.Nodes;
with DOM.Core.Elements; use DOM.Core.Elements;
with Log; use Log;
with Factions; use Factions;
package body Careers is
procedure Load_Careers(Reader: Tree_Reader) is
Temp_Record: Career_Record;
Nodes_List, Child_Nodes: Node_List;
Careers_Data: Document;
Skill_Name, Career_Index: Unbounded_String;
Tmp_Skills: UnboundedString_Container.Vector;
Delete_Index: Positive;
Career_Node: Node;
Action, Skill_Action: Data_Action;
begin
Careers_Data := Get_Tree(Read => Reader);
Nodes_List :=
DOM.Core.Documents.Get_Elements_By_Tag_Name
(Doc => Careers_Data, Tag_Name => "career");
Load_Careers_Loop :
for I in 0 .. Length(List => Nodes_List) - 1 loop
Temp_Record := (Name => Null_Unbounded_String, Skills => Tmp_Skills);
Career_Node := Item(List => Nodes_List, Index => I);
Career_Index :=
To_Unbounded_String
(Source => Get_Attribute(Elem => Career_Node, Name => "index"));
Action :=
(if Get_Attribute(Elem => Career_Node, Name => "action")'Length > 0
then
Data_Action'Value
(Get_Attribute(Elem => Career_Node, Name => "action"))
else ADD);
if Action in UPDATE | REMOVE then
if not Careers_Container.Contains
(Container => Careers_List, Key => Career_Index) then
raise Data_Loading_Error
with "Can't " & To_Lower(Item => Data_Action'Image(Action)) &
" career '" & To_String(Source => Career_Index) &
"', there is no career with that index.";
end if;
elsif Careers_Container.Contains
(Container => Careers_List, Key => Career_Index) then
raise Data_Loading_Error
with "Can't add career '" & To_String(Source => Career_Index) &
"', there is already a career with that index.";
end if;
if Action /= REMOVE then
if Action = UPDATE then
Temp_Record := Careers_List(Career_Index);
end if;
if Get_Attribute(Elem => Career_Node, Name => "name") /= "" then
Temp_Record.Name :=
To_Unbounded_String
(Source =>
Get_Attribute(Elem => Career_Node, Name => "name"));
end if;
Child_Nodes :=
DOM.Core.Elements.Get_Elements_By_Tag_Name
(Elem => Career_Node, Name => "skill");
Read_Skills_Loop :
for J in 0 .. Length(List => Child_Nodes) - 1 loop
Skill_Name :=
To_Unbounded_String
(Source =>
Get_Attribute
(Elem => Item(List => Child_Nodes, Index => J),
Name => "name"));
Skill_Action :=
(if Get_Attribute(Item(Child_Nodes, J), "action")'Length > 0
then
Data_Action'Value
(Get_Attribute(Item(Child_Nodes, J), "action"))
else ADD);
if Find_Skill_Index(To_String(Skill_Name)) = 0 then
raise Data_Loading_Error
with "Can't " & To_Lower(Data_Action'Image(Action)) &
"career '" & To_String(Career_Index) & "', skill '" &
To_String(Skill_Name) & "' not exists";
end if;
if Skill_Action /= REMOVE then
Temp_Record.Skills.Append(New_Item => Skill_Name);
else
Delete_Index := Temp_Record.Skills.First_Index;
Remove_Skills_Loop :
while Delete_Index <= Temp_Record.Skills.Last_Index loop
if Temp_Record.Skills(Delete_Index) = Skill_Name then
Temp_Record.Skills.Delete(Index => Delete_Index);
exit Remove_Skills_Loop;
end if;
Delete_Index := Delete_Index + 1;
end loop Remove_Skills_Loop;
end if;
end loop Read_Skills_Loop;
if Action /= UPDATE then
Careers_Container.Include
(Careers_List, Career_Index, Temp_Record);
Log_Message
("Career added: " & To_String(Temp_Record.Name), EVERYTHING);
else
Careers_List(Career_Index) := Temp_Record;
Log_Message
("Career updated: " & To_String(Temp_Record.Name),
EVERYTHING);
end if;
else
Careers_Container.Exclude(Careers_List, Career_Index);
Remove_Careers_Loop :
for Faction of Factions_List loop
Factions.Careers_Container.Exclude
(Faction.Careers, Career_Index);
end loop Remove_Careers_Loop;
Log_Message
("Career removed: " & To_String(Career_Index), EVERYTHING);
end if;
end loop Load_Careers_Loop;
end Load_Careers;
end Careers;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS --
-- --
-- S Y S T E M . B B . P A R A M E T E R S --
-- --
-- S p e c --
-- --
-- Copyright (C) 1999-2002 Universidad Politecnica de Madrid --
-- Copyright (C) 2003-2005 The European Space Agency --
-- Copyright (C) 2003-2016, AdaCore --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- --
-- --
-- --
-- --
-- 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. --
-- --
-- The port of GNARL to bare board targets was initially developed by the --
-- Real-Time Systems Group at the Technical University of Madrid. --
-- --
------------------------------------------------------------------------------
-- This package defines basic parameters used by the low level tasking system
-- This is the STM32F40x (ARMv7) version of this package
pragma Restrictions (No_Elaboration_Code);
with Interfaces.STM32.RCC;
with System.STM32;
with System.BB.Board_Parameters;
with System.BB.MCU_Parameters;
package System.BB.Parameters
with SPARK_Mode => On is
pragma Preelaborate (System.BB.Parameters);
Clock_Frequency : constant := Board_Parameters.Clock_Frequency;
pragma Assert (Clock_Frequency in System.STM32.SYSCLK_Range);
Ticks_Per_Second : constant := Clock_Frequency;
-- Set the requested SYSCLK frequency. Setup_Pll will try to set configure
-- PLL to match this value when possible or reset the board.
----------------
-- Prescalers --
----------------
AHB_PRE : constant System.STM32.AHB_Prescaler := System.STM32.AHBPRE_DIV1;
APB1_PRE : constant System.STM32.APB_Prescaler :=
(Enabled => True, Value => System.STM32.DIV4);
APB2_PRE : constant System.STM32.APB_Prescaler :=
(Enabled => True, Value => System.STM32.DIV2);
--------------------
-- External Clock --
--------------------
-- The external clock can be specific for each board. We provide here
-- a value for the most common STM32 boards.
-- Change the value based on the external clock used on your specific
-- hardware.
HSE_Clock : constant := Board_Parameters.HSE_Clock_Frequency;
HSI_Clock : constant := 16_000_000;
Has_FPU : constant Boolean := True;
-- Set to true if core has a FPU
----------------
-- Interrupts --
----------------
-- These definitions are in this package in order to isolate target
-- dependencies.
Number_Of_Interrupt_ID : constant := MCU_Parameters.Number_Of_Interrupts;
-- Number of interrupts (for both the interrupt controller and the
-- Sys_Tick_Trap). This static constant is used to declare a type, and
-- the handler table.
Trap_Vectors : constant := 17;
-- While on this target there is little difference between interrupts
-- and traps, we consider the following traps:
--
-- Name Nr
--
-- Reset_Vector 1
-- NMI_Vector 2
-- Hard_Fault_Vector 3
-- Mem_Manage_Vector 4
-- Bus_Fault_Vector 5
-- Usage_Fault_Vector 6
-- SVC_Vector 11
-- Debug_Mon_Vector 12
-- Pend_SV_Vector 14
-- Sys_Tick_Vector 15
-- Interrupt_Request_Vector 16
--
-- These trap vectors correspond to different low-level trap handlers in
-- the run time. Note that as all interrupt requests (IRQs) will use the
-- same interrupt wrapper, there is no benefit to consider using separate
-- vectors for each.
Context_Buffer_Capacity : constant := 10;
-- The context buffer contains registers r4 .. r11 and the SP_process
-- (PSP). The size is rounded up to an even number for alignment
------------
-- Stacks --
------------
Interrupt_Stack_Size : constant := 2 * 1024;
-- Size of each of the interrupt stacks in bytes. While there nominally is
-- an interrupt stack per interrupt priority, the entire space is used as a
-- single stack.
Interrupt_Sec_Stack_Size : constant := 128;
-- Size of the secondary stack for interrupt handlers
----------
-- CPUS --
----------
Max_Number_Of_CPUs : constant := 1;
-- Maximum number of CPUs
Multiprocessor : constant Boolean := Max_Number_Of_CPUs /= 1;
-- Are we on a multiprocessor board?
end System.BB.Parameters;
|
---------------------------------------------------------------------------------
-- package body Banded_LU, LU decomposition, equation solving for banded matrices
-- Copyright (C) 1995-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.
---------------------------------------------------------------------------------
with Text_IO;
package body Banded_LU is
-------------
-- Product --
-------------
-- Matrix Vector multiplication
function Product
(A : in Banded_Matrix;
X : in Column;
Final_Index : in Index := Index'Last;
Starting_Index : in Index := Index'First)
return Column
is
Result : Column := (others => Zero);
Sum : Real;
Col_First, Col_Last : Integer;
begin
for Row in Starting_Index .. Final_Index loop
Sum := Zero;
Col_First := Integer'Max (Row - No_Of_Off_Diagonals, Starting_Index);
Col_Last := Integer'Min (Row + No_Of_Off_Diagonals, Final_Index);
for Col in Col_First .. Col_Last loop
Sum := Sum + A (Row)(Col - Row) * X (Col);
end loop;
Result(Row) := Sum;
end loop;
return Result;
end Product;
---------------------
-- Refine_Solution --
---------------------
-- if No_Of_Iterations=0 then usual solution is returned.
-- if No_Of_Iterations=1 then solution is refined iteratively once.
--
-- Not necessarily much use if error is due to ill-conditioning of Matrix A.
--
-- Iterative refinement of the solution returned by LU_decompose() and
-- Solve(). Uses the Newton-like iteration for the solution of A*X = b,
--
-- X_{k+1} = X_k + A_Inverse_Approximate * (b - A*X_k).
--
-- Here A_Inverse_Approximate (we will call it V below) represents the
-- solution returned by LU_decompose() followed by Solve().
--
-- if y = exact error in 1st iteration: y = X_inf - X_1, then y is the
-- exact solution of A*y = d_1 where d_1 = b - A*X_1.
-- Let V denote approximate inverse of A. Iterate for y using
--
-- Delta_Y_{k+1} == Y_{k+1} - Y_k = V*(d_1 - A*Y_k).
--
-- Remember Y = exact error in 1st iteration = SUM (Delta_Y_k's).
-- Here's the actual method:
--
-- Let d_1 = b - A*X_1 (the standard Residual: 1st estimate of error in A*X = b)
-- Delta_Y_1 = V*d_1
-- Let d_2 = d_1 - A*Delta_Y_1
-- Delta_Y_2 = V*(d_1 - A*Delta_Y_1) = V*d_2
-- Let d_3 = d_2 - A*Delta_Y_2
-- Delta_Y_3 = V*(d_1 - A*Delta_Y_1 - A*Delta_Y_2) = V*d_3
--
-- so: d_k = d_{k-1} - A*Delta_Y_{k-1}; Delta_Y_k = V*d_k
--
-- Sum the Delta_Y_k's to get the correction to X_1: Y = SUM (Delta_Y_k's).
--
procedure Refine_Solution
(X : out Column;
B : in Column;
A_LU : in Banded_Matrix;
Diag_Inverse : in Column;
A : in Banded_Matrix;
No_Of_Iterations : in Natural := 1;
Final_Index : in Index := Index'Last;
Starting_Index : in Index := Index'First)
is
Delta_Y, X_1, A_Y : Column := (others => 0.0);
D_k : Column := (others => 0.0);
Y_f : Column := (others => 0.0);
begin
-- Get X_1 as defined above.
Solve (X_1, B, A_LU, Diag_Inverse, Final_Index, Starting_Index);
if No_Of_Iterations > 0 then
A_Y := Product(A, X_1, Final_Index, Starting_Index);
-- D_1:
for I in Starting_Index .. Final_Index loop
D_k(I) := B(I) - A_Y(I);
end loop;
Solve (Delta_Y, D_k, A_LU, Diag_Inverse, Final_Index, Starting_Index);
-- Y_f is Sum of all the iterated Delta_Y's. Initialize it:
Y_f := Delta_Y;
for Iteration in 1..No_Of_Iterations-1 loop
-- get d_k = d_k - A*Delta_Y_k
A_Y := Product (A, Delta_Y, Final_Index, Starting_Index);
for I in Starting_Index .. Final_Index loop
D_k(I) := D_k(I) - A_Y(I);
end loop;
-- get Delta_Y = V*D_k:
Solve (Delta_Y, D_k, A_LU, Diag_Inverse, Final_Index, Starting_Index);
-- Accumulate Y_f: the full correction to X_1:
for I in Starting_Index .. Final_Index loop
Y_f(I) := Y_f(I) + Delta_Y(I);
end loop;
end loop;
end if;
for I in Starting_Index..Final_Index loop
X(I) := Y_f(I) + X_1(I);
end loop;
end Refine_Solution;
----------------
-- Matrix_Val --
----------------
-- Translates (Row, Col) to (I, Diagonal_id) using
-- the formula I = Row, and Diagonal_id = Col - Row.
--
-- Banded Matrices are by definition 0 everywhere except on the
-- diagonal bands. So 0 is returned if (Row, Col) is not in the
-- banded region.
function Matrix_Val
(A : Banded_Matrix;
Row : Index;
Col : Index)
return Real
is
Diag_ID : constant Integer := (Col - Row);
Result : Real;
begin
if Abs Diag_ID > No_Of_Off_Diagonals then
Result := 0.0;
else
Result := A(Row)(Diag_ID);
end if;
return Result;
end;
------------------
-- LU_Decompose --
------------------
-- Translates from (Row, Col) indices to (I, Diagonal)
-- with the formula I = Row, and Diagonal = Col - Row.
procedure LU_Decompose
(A : in out Banded_Matrix;
Diag_Inverse : out Column;
Final_Index : in Index := Index'Last;
Starting_Index : in Index := Index'First)
is
Stage : Index;
Sum : Real;
Col_First, Row_Last : Integer;
Min_Allowed_Pivot_Ratio, Min_Allowed_Pivot_Val : Real;
Reciprocal_Pivot_Val, Pivot_Val, Abs_Pivot_Val : Real;
Max_Pivot_Val : Real := Min_Allowed_Real;
Min_Pivot_Ratio : constant Real := 2.0**(-Real'Machine_Mantissa) * 1.0E-3;
begin
Diag_Inverse := (Others => 0.0);
if Final_Index - Starting_Index + 1 < No_Of_Off_Diagonals + 1 then
text_io.put ("Matrix Size must be >= No_Of_Off_Diagonals+1.");
raise Constraint_Error;
end if;
Min_Allowed_Pivot_Ratio := Min_Pivot_Ratio;
-- Step 0. 1 X 1 matrices: They can't exist because of above.
-- Step 1. The outer loop.
-- At each stage we calculate row "stage" of the Upper matrix U
-- and Column "Stage" of the Lower matrix L.
-- The matrix A is overwritten with these, because the elements
-- of A in those places are never needed in future stages.
-- However, the elements of L ARE needed in those places,
-- so to get those elements we will be accessing A (which stores them).
for Stage in Starting_Index..Final_Index-1 loop
Row_Last := Integer'Min (Stage + No_Of_Off_Diagonals, Final_Index);
if Stage > Starting_Index then
for J in Stage .. Row_Last loop
Sum := 0.0;
--for K in Starting_Index .. Stage-1 loop
-- --Sum := Sum + L(J)(K)*U(K)(Stage);
-- Sum := Sum + A(J)(K)*A(K)(Stage);
--end loop;
Col_First := Integer'Max (J - No_Of_Off_Diagonals, Starting_Index);
for K in Col_First..Stage-1 loop
Sum := Sum + A(J)(K-J)*A(K)(Stage-K);
end loop;
--L(J)(Stage) := L(J)(Stage) - Sum;
--L(J)(Stage-J) := L(J)(Stage-J) - Sum;
A(J)(Stage-J) := A(J)(Stage-J) - Sum;
end loop;
end if;
-- Step 2: Get row "stage" of U and
-- column "stage" of L. Notice these formulas update
-- only (Stage+1..Last) elements of the respective row
-- and column, and depend on only (1..Stage) elements
-- of U and L, which were calculated previously, and stored in A.
Pivot_Val := A(Stage)(0);
Abs_Pivot_Val := Abs (Pivot_Val);
if Abs_Pivot_Val > Max_Pivot_Val then
Max_Pivot_Val := Abs_Pivot_Val;
end if;
Min_Allowed_Pivot_Val := Max_Pivot_Val*Min_Allowed_Pivot_Ratio + Min_Allowed_Real;
if (Abs_Pivot_Val < Min_Allowed_Pivot_Val) then
Min_Allowed_Pivot_Val := Real'Copy_Sign (Min_Allowed_Pivot_Val, Pivot_Val);
Reciprocal_Pivot_Val := 1.0 / Min_Allowed_Pivot_Val;
else
Reciprocal_Pivot_Val := 1.0 / Pivot_Val;
end if;
if (Abs_Pivot_Val < Min_Allowed_Real) then
Reciprocal_Pivot_Val := 0.0;
end if;
Diag_Inverse(Stage) := Reciprocal_Pivot_Val;
for J in Stage+1..Row_Last loop
Sum := 0.0;
if Stage > Starting_Index then
--for K in Starting_Index .. Stage-1 loop
-- --Sum := Sum + L(Stage)(K)*U(K)(J);
-- Sum := Sum + A(Stage)(K)*A(K)(J);
--end loop;
Col_First := Integer'Max (Starting_Index, J - No_Of_Off_Diagonals);
for K in Col_First..Stage-1 loop
Sum := Sum + A(Stage)(K-Stage) * A(K)(J-K);
end loop;
end if;
--U(Stage)(J) := (A(Stage)(J) - Sum) * Scale_Factor;
A(Stage)(J-Stage) := (A(Stage)(J-Stage) - Sum) * Reciprocal_Pivot_Val;
end loop;
end loop;
-- Step 3: Get final row and column.
Stage := Final_Index;
Sum := 0.0;
--for K in Starting_Index .. Stage-1 loop
-- --Sum := Sum + L(Stage)(K)*U(K)(Stage);
-- Sum := Sum + A(Stage)(K)*A(K)(Stage);
--end loop;
Col_First := Integer'Max(Starting_Index, Integer(Stage)-No_Of_Off_Diagonals);
for K in Col_First..Stage-1 loop
Sum := Sum + A(Stage)(K-Stage)*A(K)(Stage-K);
end loop;
A(Stage)(0) := A(Stage)(0) - Sum;
Pivot_Val := A(Stage)(0);
Abs_Pivot_Val := Abs (Pivot_Val);
if Abs_Pivot_Val > Max_Pivot_Val then
Max_Pivot_Val := Abs_Pivot_Val;
end if;
Min_Allowed_Pivot_Val := Max_Pivot_Val*Min_Allowed_Pivot_Ratio + Min_Allowed_Real;
if Abs_Pivot_Val < Min_Allowed_Pivot_Val then
Min_Allowed_Pivot_Val := Real'Copy_Sign (Min_Allowed_Pivot_Val, Pivot_Val);
Reciprocal_Pivot_Val := 1.0 / Min_Allowed_Pivot_Val;
else
Reciprocal_Pivot_Val := 1.0 / Pivot_Val;
end if;
if Abs_Pivot_Val < Min_Allowed_Real then
Reciprocal_Pivot_Val := 0.0;
end if;
Diag_Inverse(Stage) := Reciprocal_Pivot_Val;
end LU_Decompose;
-----------
-- Solve --
-----------
procedure Solve
(X : out Column;
B : in Column;
A_LU : in Banded_Matrix;
Diag_Inverse : in Column;
Final_Index : in Index := Index'Last;
Starting_Index : in Index := Index'First)
is
Z : Column;
ID_of_1st_non_0 : Index := Starting_Index;
Sum : Real;
Col_First : Index;
Col_Last : Index;
begin
for Row in Index loop
X(Row) := 0.0;
end loop;
-- An optimization to make matrix inversion efficient.
-- in Banded_Matrix inversion, the input vector B is
-- is a unit vector: it is all zeros except for a 1.0. Need to
-- to find 1st non-zero element of B:
for I in Starting_Index..Final_Index loop
if Abs (B(I)) > 0.0 then
ID_of_1st_non_0 := I;
exit;
end if;
end loop;
-- In solving for Z in the equation L Z = B, the Z's will
-- all be zero up to the 1st non-zero element of B.
if ID_of_1st_non_0 > Index'First then
for I in Starting_Index..ID_of_1st_non_0-1 loop
Z(I) := 0.0;
end loop;
end if;
-- The matrix equation is in the form L * U * X = B.
-- First assume U * X is Z, and
-- solve for Z in the equation L Z = B.
Z(ID_of_1st_non_0) := B(ID_of_1st_non_0) * Diag_Inverse(ID_of_1st_non_0);
if ID_of_1st_non_0 < Final_Index then
for Row in ID_of_1st_non_0+1..Final_Index loop
Sum := 0.0;
Col_First := Integer'Max (Starting_Index, Row - No_Of_Off_Diagonals);
for Col in Col_First .. Row-1 loop
Sum := Sum + A_LU(Row)(Col-Row) * Z(Col);
end loop;
Z(Row) := (B(Row) - Sum) * Diag_Inverse(Row);
end loop;
end if;
-- Solve for X in the equation U X = Z.
X(Final_Index) := Z(Final_Index);
if Final_Index > Starting_Index then
for Row in reverse Starting_Index..Final_Index-1 loop
Sum := 0.0;
Col_Last := Integer'Min (Final_Index, Row + No_Of_Off_Diagonals);
for Col in Row+1 .. Col_Last loop
Sum := Sum + A_LU(Row)(Col-Row) * X(Col);
end loop;
X(Row) := (Z(Row) - Sum);
end loop;
end if;
end Solve;
end Banded_LU;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
with Ada.Streams;
package Zstandard.Functions.Streaming_Decompression is
package STR renames Ada.Streams;
Output_container_size : constant Thin.IC.size_t := Thin.ZSTD_DStreamOutSize;
subtype Output_Data_Container is
STR.Stream_Element_Array (1 .. STR.Stream_Element_Offset (Output_container_size));
type Decompressor is tagged private;
-- This is the initialization procedure.
-- The input stream and output buffer capacity are externally provided
procedure Initialize
(mechanism : out Decompressor;
input_stream : not null access STR.Root_Stream_Type'Class);
-- Decompress data as each input chunk is received
-- if "complete" then the decompression is complete (don't call procedure any more)
-- The "last_element" is the end of the container range (e.g. 1 .. last_element)
procedure Decompress_Data
(mechanism : Decompressor;
complete : out Boolean;
output_data : out Output_Data_Container;
last_element : out Natural);
streaming_decompression_initialization : exception;
streaming_decompression_error : exception;
private
Recommended_Chunk_Size : constant Thin.IC.size_t := Thin.ZSTD_DStreamInSize;
type Decompressor is tagged
record
source_stream : access STR.Root_Stream_Type'Class;
zstd_stream : Thin.ZSTD_DStream_ptr := Thin.Null_DStream_pointer;
end record;
function convert_to_stream_array
(char_data : Thin.IC.char_array;
number_characters : Thin.IC.size_t) return STR.Stream_Element_Array;
function convert_to_char_array
(stream_data : STR.Stream_Element_Array;
output_array_size : Thin.IC.size_t) return Thin.IC.char_array;
end Zstandard.Functions.Streaming_Decompression;
|
-- ___ _ ___ _ _ --
-- / __| |/ (_) | | Common SKilL implementation --
-- \__ \ ' <| | | |__ file partitioning info --
-- |___/_|\_\_|_|____| by: Timm Felden --
-- --
pragma Ada_2012;
with Ada.Containers.Vectors;
with Skill.Types;
with Skill.Containers.Vectors;
-- documentation can be found in java common
package Skill.Internal.Parts is
type Block is record
BPO : Skill.Types.Skill_ID_T;
Static_Count : Skill.Types.Skill_ID_T;
Dynamic_Count : Skill.Types.Skill_ID_T;
end record;
package Blocks_P is new Skill.Containers.Vectors (Natural, Block);
subtype Blocks is Blocks_P.Vector;
type Chunk_T is abstract tagged record
First : Skill.Types.v64;
Last : Skill.Types.v64;
Count : Skill.Types.Skill_ID_T;
end record;
type Chunk is access Chunk_T'Class;
procedure Free (This : access Chunk_T) is abstract;
type Simple_Chunk is new Chunk_T with record
BPO : Skill.Types.Skill_ID_T;
end record;
type Simple_Chunk_X is not null access all Simple_Chunk;
function To_Simple (This : access Chunk_T'Class) return Simple_Chunk_X;
type Bulk_Chunk is new Chunk_T with record
-- The Number of Blocks, Starting From The First That Have To Be Updated
Block_Count : Natural;
end record;
type Bulk_Chunk_X is not null access all Bulk_Chunk;
function To_Bulk (This : access Chunk_T'Class) return Bulk_Chunk_X;
package Chunks is new Ada.Containers.Vectors (Natural, Chunk);
procedure Free (This : access Simple_Chunk);
procedure Free (This : access Bulk_Chunk);
end Skill.Internal.Parts;
|
with Ada.Float_Text_IO;
with Ada.Text_IO;
with Angle; use Angle;
with Ada.Real_Time; use Ada.Real_Time;
with Task_Scheduling; use Task_Scheduling;
with Setup; use Setup;
with Shared_Data;
with Meassure_Velocity;
with Meassure_Acceleration;
with Acceptance_Test_Lib; use Acceptance_Test_Lib;
with Exception_Declarations; use Exception_Declarations;
with Type_Lib; use Type_Lib;
with PID_Functionality; use PID_Functionality;
package Task_Implementations is
task Gyroscope_Reader with Priority => 20;
task Accelerometer_Reader with Priority => 19;
task Cascade_Controller with Priority => 18;
task Actuator_Writer with Priority => 17;
private
-- Protected types to store and retrive shared data
Accelerometer_SR : Shared_Data.Sensor_Reading;
Gyroscope_SR : Shared_Data.Sensor_Reading;
Motor_AW : Shared_Data.Actuator_Write;
Recoveryblock_Count_Limit : Constant Integer := 4;
end Task_Implementations;
|
-- Copyright (c) 2017 Maxim Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-- License-Filename: LICENSE
-------------------------------------------------------------
package body Ada_Pretty.Expressions is
--------------
-- Document --
--------------
overriding function Document
(Self : Apply;
Printer : not null access League.Pretty_Printers.Printer'Class;
Pad : Natural)
return League.Pretty_Printers.Document
is
-- Format this as
-- Prefix
-- (Arguments)
pragma Unreferenced (Pad);
Prefix : League.Pretty_Printers.Document :=
Self.Prefix.Document (Printer, 0);
Result : League.Pretty_Printers.Document := Printer.New_Document;
begin
Result.New_Line;
Result.Put ("(");
Result.Append (Self.Arguments.Document (Printer, 0).Nest (1));
Result.Put (")");
Result.Nest (2);
Prefix.Append (Result);
Prefix.Group;
return Prefix;
end Document;
--------------
-- Document --
--------------
overriding function Document
(Self : Qualified;
Printer : not null access League.Pretty_Printers.Printer'Class;
Pad : Natural)
return League.Pretty_Printers.Document
is
-- Format this as Prefix'(Arguments) or
-- Prefix'
-- (Arguments)
pragma Unreferenced (Pad);
Prefix : League.Pretty_Printers.Document :=
Self.Prefix.Document (Printer, 0);
Result : League.Pretty_Printers.Document := Printer.New_Document;
begin
Result.New_Line (Gap => "");
Result.Put ("(");
Result.Append (Self.Argument.Document (Printer, 0).Nest (1));
Result.Put (")");
Result.Nest (2);
Prefix.Put ("'");
Prefix.Append (Result);
Prefix.Group;
return Prefix;
end Document;
--------------
-- Document --
--------------
overriding function Document
(Self : Component_Association;
Printer : not null access League.Pretty_Printers.Printer'Class;
Pad : Natural)
return League.Pretty_Printers.Document
is
Result : League.Pretty_Printers.Document := Printer.New_Document;
begin
if Self.Choices /= null then
Result.Append (Self.Choices.Document (Printer, Pad));
Result.Put (" =>");
Result.New_Line;
Result.Append (Self.Value.Document (Printer, Pad));
Result.Nest (2);
Result.Group;
else
Result.Append (Self.Value.Document (Printer, Pad));
end if;
return Result;
end Document;
--------------
-- Document --
--------------
overriding function Document
(Self : If_Expression;
Printer : not null access League.Pretty_Printers.Printer'Class;
Pad : Natural)
return League.Pretty_Printers.Document
is
Result : League.Pretty_Printers.Document := Printer.New_Document;
Then_Part : League.Pretty_Printers.Document := Printer.New_Document;
begin
Result.Put ("if ");
Result.Append (Self.Condition.Document (Printer, Pad));
Then_Part.New_Line;
Then_Part.Put ("then ");
Then_Part.Append (Self.Then_Path.Document (Printer, Pad));
Then_Part.Nest (2);
Result.Append (Then_Part);
if Self.Elsif_List /= null then
declare
Elsif_Part : League.Pretty_Printers.Document :=
Printer.New_Document;
begin
Elsif_Part.Append (Self.Elsif_List.Document (Printer, Pad));
Elsif_Part.Nest (2);
Result.New_Line;
Result.Append (Elsif_Part);
end;
end if;
if Self.Else_Path /= null then
declare
Else_Part : League.Pretty_Printers.Document :=
Printer.New_Document;
begin
Else_Part.Put ("else ");
Else_Part.Append (Self.Else_Path.Document (Printer, Pad));
Else_Part.Nest (2);
Result.New_Line;
Result.Append (Else_Part);
end;
end if;
return Result;
end Document;
--------------
-- Document --
--------------
overriding function Document
(Self : Infix;
Printer : not null access League.Pretty_Printers.Printer'Class;
Pad : Natural)
return League.Pretty_Printers.Document
is
Result : League.Pretty_Printers.Document := Printer.New_Document;
begin
Result.New_Line;
Result.Put (Self.Operator);
Result.Put (" ");
Result.Append (Self.Left.Document (Printer, Pad));
Result.Nest (2);
Result.Group;
return Result;
end Document;
--------------
-- Document --
--------------
overriding function Document
(Self : Integer_Literal;
Printer : not null access League.Pretty_Printers.Printer'Class;
Pad : Natural)
return League.Pretty_Printers.Document
is
pragma Unreferenced (Pad);
Image : constant Wide_Wide_String :=
Natural'Wide_Wide_Image (Self.Value);
begin
return Printer.New_Document.Put (Image (2 .. Image'Last));
end Document;
--------------
-- Document --
--------------
overriding function Document
(Self : Name;
Printer : not null access League.Pretty_Printers.Printer'Class;
Pad : Natural) return League.Pretty_Printers.Document
is
Result : League.Pretty_Printers.Document := Printer.New_Document;
Padding : constant Wide_Wide_String
(Self.Name.Length + 1 .. Pad) := (others => ' ');
begin
Result.Put (Self.Name);
if Padding'Length > 0 then
Result.Put (Padding);
end if;
return Result;
end Document;
--------------
-- Document --
--------------
overriding function Document
(Self : Parentheses;
Printer : not null access League.Pretty_Printers.Printer'Class;
Pad : Natural)
return League.Pretty_Printers.Document
is
pragma Unreferenced (Pad);
Result : League.Pretty_Printers.Document := Printer.New_Document;
Child : constant League.Pretty_Printers.Document :=
Self.Child.Document (Printer, 0);
begin
Result.Put ("(");
Result.Append (Child.Nest (1));
Result.Put (")");
return Result;
end Document;
--------------
-- Document --
--------------
overriding function Document
(Self : Selected_Name;
Printer : not null access League.Pretty_Printers.Printer'Class;
Pad : Natural)
return League.Pretty_Printers.Document
is
pragma Unreferenced (Pad);
-- Format this as
-- Prefix
-- .Selector
Result : League.Pretty_Printers.Document := Printer.New_Document;
Prefix : League.Pretty_Printers.Document :=
Self.Prefix.Document (Printer, 0);
Selector : constant League.Pretty_Printers.Document :=
Self.Selector.Document (Printer, 0);
begin
Result.New_Line (Gap => "");
Result.Put (".");
Result.Append (Selector);
Result.Nest (2);
Result.Group;
Prefix.Append (Result);
return Prefix;
end Document;
--------------
-- Document --
--------------
overriding function Document
(Self : String;
Printer : not null access League.Pretty_Printers.Printer'Class;
Pad : Natural)
return League.Pretty_Printers.Document
is
pragma Unreferenced (Pad);
Result : League.Pretty_Printers.Document := Printer.New_Document;
begin
Result.Put ("""");
Result.Put (Self.Text);
Result.Put ("""");
return Result;
end Document;
----------
-- Join --
----------
overriding function Join
(Self : Component_Association;
List : Node_Access_Array;
Pad : Natural;
Printer : not null access League.Pretty_Printers.Printer'Class)
return League.Pretty_Printers.Document
is
Result : League.Pretty_Printers.Document := Printer.New_Document;
begin
Result.Append (Self.Document (Printer, Pad));
for J in List'Range loop
declare
Next : League.Pretty_Printers.Document := Printer.New_Document;
begin
Next.Put (",");
Next.New_Line;
Next.Append (List (J).Document (Printer, Pad));
Next.Group;
Result.Append (Next);
end;
end loop;
return Result;
end Join;
overriding function Max_Pad (Self : Argument_Association) return Natural is
begin
if Self.Choices = null then
return 0;
else
return Self.Choices.Max_Pad;
end if;
end Max_Pad;
---------------
-- New_Apply --
---------------
function New_Apply
(Prefix : not null Node_Access;
Arguments : not null Node_Access) return Node'Class is
begin
return Apply'(Prefix, Arguments);
end New_Apply;
------------------------------
-- New_Argument_Association --
------------------------------
function New_Argument_Association
(Choice : Node_Access;
Value : not null Node_Access) return Node'Class is
begin
return Argument_Association'(Choice, Value);
end New_Argument_Association;
-------------------------------
-- New_Component_Association --
-------------------------------
function New_Component_Association
(Choices : Node_Access;
Value : not null Node_Access) return Node'Class is
begin
return Component_Association'(Choices, Value);
end New_Component_Association;
------------
-- New_If --
------------
function New_If
(Condition : not null Node_Access;
Then_Path : not null Node_Access;
Elsif_List : Node_Access;
Else_Path : Node_Access) return Node'Class is
begin
return If_Expression'(Condition, Then_Path, Elsif_List, Else_Path);
end New_If;
---------------
-- New_Infix --
---------------
function New_Infix
(Operator : League.Strings.Universal_String;
Left : not null Node_Access)
return Node'Class is
begin
return Infix'(Operator, Left);
end New_Infix;
-----------------
-- New_Literal --
-----------------
function New_Literal
(Value : Natural; Base : Positive) return Node'Class is
begin
return Integer_Literal'(Value, Base);
end New_Literal;
--------------
-- New_Name --
--------------
function New_Name (Name : League.Strings.Universal_String)
return Node'Class is
begin
return Expressions.Name'(Name => Name);
end New_Name;
---------------------
-- New_Parentheses --
---------------------
function New_Parentheses
(Child : not null Node_Access) return Node'Class is
begin
return Expressions.Parentheses'(Child => Child);
end New_Parentheses;
-------------------
-- New_Qualified --
-------------------
function New_Qualified
(Prefix : not null Node_Access;
Argument : not null Node_Access) return Node'Class is
begin
return Expressions.Qualified'(Prefix, Argument);
end New_Qualified;
-----------------------
-- New_Selected_Name --
-----------------------
function New_Selected_Name
(Prefix : not null Node_Access;
Selector : not null Node_Access) return Node'Class is
begin
return Selected_Name'(Prefix, Selector);
end New_Selected_Name;
----------------
-- New_String --
----------------
function New_String (Text : League.Strings.Universal_String)
return Node'Class is
begin
return String'(Text => Text);
end New_String;
end Ada_Pretty.Expressions;
|
-- Copyright 2019 Michael Casadevall <michael@casadevall.pro>
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to
-- deal in the Software without restriction, including without limitation the
-- rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
-- sell copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
-- THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-- DEALINGS IN THE SOFTWARE.
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Unchecked_Deallocation;
with Ada.Calendar; use Ada.Calendar;
with Ada.Calendar.Formatting; use Ada.Calendar.Formatting;
package body DNSCatcher.Utils.Logger is
procedure Free_Logger_Msg_Ptr is new Ada.Unchecked_Deallocation
(Object => Logger_Message_Packet, Name => Logger_Message_Packet_Ptr);
function Format_Log_Level
(Use_Color : Boolean;
Log_Level : Log_Levels)
return Unbounded_String
is
Color_Prefix : Unbounded_String;
Log_Level_Str : Unbounded_String;
Now : constant Time := Clock;
begin
-- Add ANSI color codes if we're using color on Linux
if Use_Color
then
case Log_Level is
when EMERGERENCY =>
Color_Prefix := To_Unbounded_String (ANSI_Light_Red);
when ALERT =>
Color_Prefix := To_Unbounded_String (ANSI_Light_Red);
when CRITICAL =>
Color_Prefix := To_Unbounded_String (ANSI_Light_Red);
when ERROR =>
Color_Prefix := To_Unbounded_String (ANSI_Red);
when WARNING =>
Color_Prefix := To_Unbounded_String (ANSI_Light_Yellow);
when NOTICE =>
Color_Prefix := To_Unbounded_String (ANSI_Yellow);
when INFO =>
Color_Prefix := To_Unbounded_String (ANSI_Green);
when DEBUG =>
Color_Prefix := To_Unbounded_String (ANSI_Light_Blue);
end case;
Log_Level_Str :=
Color_Prefix & To_Unbounded_String (Log_Level'Image) & ANSI_Reset;
else
Log_Level_Str := To_Unbounded_String (Log_Level'Image);
end if;
return To_Unbounded_String
(Image (Date => Now) & " [" & To_String (Log_Level_Str) & "]");
end Format_Log_Level;
function Create_String_From_Components
(Components : Component_Vector.Vector)
return Unbounded_String
is
Components_String : Unbounded_String;
procedure Component_To_String (c : Component_Vector.Cursor) is
Scratch_String : Unbounded_String;
begin
Scratch_String := Components (c);
Components_String := Components_String & "[" & Scratch_String & "]";
end Component_To_String;
begin
-- If there's no component, just leave it blank
if Components.Length = 0
then
return To_Unbounded_String ("");
end if;
Components.Iterate (Component_To_String'Access);
return Components_String;
end Create_String_From_Components;
protected body Logger_Queue_Type is
-- Handles queue of packets for the logger thread
entry Add_Packet (Queue : Logger_Message_Packet_Ptr) when True is
begin
Queued_Packets.Append (Queue);
end Add_Packet;
entry Get (Queue : out Logger_Message_Packet_Ptr)
when Queued_Packets.Length > 0 is
begin
Queue := Queued_Packets.First_Element;
Queued_Packets.Delete_First;
end Get;
entry Count (Count : out Integer) when True is
begin
Count := Integer (Queued_Packets.Length);
end Count;
entry Empty when True is
begin
declare
procedure Dump_Vector_Data
(c : Logger_Message_Packet_Vector.Cursor)
is
begin
Free_Logger_Msg_Ptr (Queued_Packets (c));
end Dump_Vector_Data;
begin
Queued_Packets.Iterate (Dump_Vector_Data'access);
end;
end Empty;
end Logger_Queue_Type;
protected body Logger_Message_Packet is
entry Push_Component (Component : String) when True is
begin
Current_Component.Append (To_Unbounded_String (Component));
end Push_Component;
entry Pop_Component when True is
begin
Current_Component.Delete_Last;
end Pop_Component;
entry Log_Message
(Level : Log_Levels;
Msg : String) when True is
Msg_Record : Log_Message_Record;
begin
Msg_Record.Log_Level := Level;
Msg_Record.Component := Current_Component.Copy;
Msg_Record.Message := To_Unbounded_String (Msg);
Logged_Msgs.Append (Msg_Record);
end Log_Message;
entry Get (Msg : out Log_Message_Record) when Logged_Msgs.Length > 0 is
begin
Msg := Logged_Msgs.First_Element;
Logged_Msgs.Delete_First;
end Get;
entry Get_All_And_Empty (Queue : out Log_Message_Vector.Vector) when True
is
begin
Queue := Logged_Msgs.Copy;
Logged_Msgs.Clear;
end Get_All_And_Empty;
entry Count (Count : out Integer) when True is
begin
Count := Integer (Logged_Msgs.Length);
end Count;
entry Empty when True is
begin
Logged_Msgs.Clear;
end Empty;
end Logger_Message_Packet;
task body Logger is
-- Running task for the logger processing the global message queue
Logger_Cfg : Logger_Configuration;
Keep_Running : Boolean := False;
Current_Queue : Logger_Message_Packet_Ptr;
Msg_Packets : Log_Message_Vector.Vector;
Msg_String : Unbounded_String;
Queues_To_Process : Integer;
procedure Process_Queue is
procedure Print_Messages (c : Log_Message_Vector.Cursor) is
Current_Msg : constant Log_Message_Record :=
Log_Message_Vector.Element (c);
begin
-- This is so ugly :(
if Log_Levels'Enum_Rep (Logger_Cfg.Log_Level) >=
Log_Levels'Enum_Rep (Current_Msg.Log_Level)
then
Msg_String :=
Format_Log_Level
(Logger_Cfg.Use_Color, Current_Msg.Log_Level);
Msg_String :=
Msg_String &
Create_String_From_Components (Current_Msg.Component);
Msg_String := Msg_String & " " & Current_Msg.Message;
Put_Line (To_String (Msg_String));
end if;
end Print_Messages;
begin
Logger_Queue.Count (Queues_To_Process);
while Queues_To_Process > 0
loop
Logger_Queue.Get (Current_Queue);
-- Get a local copy and then empty it; we don't care past that
-- point
if Current_Queue /= null
then
Current_Queue.Get_All_And_Empty (Msg_Packets);
Msg_Packets.Iterate (Print_Messages'Access);
Free_Logger_Msg_Ptr (Current_Queue);
end if;
Logger_Queue.Count (Queues_To_Process);
end loop;
exception
-- Not sure if there's a better way to do this, but avoids a race
-- condition
when Constraint_Error =>
begin
null;
end;
end Process_Queue;
begin
-- Set some sane defaults for Logger config if not initialized
Logger_Cfg.Log_Level := NOTICE;
Logger_Cfg.Use_Color := False;
loop
-- Processing loop
while Keep_Running
loop
select
accept Start do
null;
end Start;
or
accept Stop do
-- Flush the pending queue
Keep_Running := False;
Process_Queue;
end Stop;
else
Process_Queue;
delay 0.1;
end select;
end loop;
-- Idling loop ready for shutdown
while Keep_Running = False
loop
select
accept Initialize (Cfg : Logger_Configuration) do
Logger_Cfg := Cfg;
end Initialize;
or
accept Start do
Keep_Running := True;
end Start;
or
accept Stop do
null;
end Stop;
or
terminate;
end select;
end loop;
end loop;
end Logger;
end DNSCatcher.Utils.Logger;
|
-----------------------------------------------------------------------
-- awa-blogs-beans -- Beans for blog module
-- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with ADO;
with AWA.Blogs.Modules;
with AWA.Blogs.Models;
with AWA.Tags.Beans;
-- == Blog Beans ==
-- Several bean types are provided to represent and manage the blogs and their posts.
-- The blog module registers the bean constructors when it is initialized.
-- To use them, one must declare a bean definition in the application XML configuration.
package AWA.Blogs.Beans is
-- Attributes exposed by <b>Post_Bean</b>
BLOG_ID_ATTR : constant String := "blogId";
POST_ID_ATTR : constant String := "id";
POST_UID_ATTR : constant String := "uid";
POST_TITLE_ATTR : constant String := "title";
POST_TEXT_ATTR : constant String := "text";
POST_URI_ATTR : constant String := "uri";
POST_STATUS_ATTR : constant String := "status";
POST_USERNAME_ATTR : constant String := "username";
POST_TAG_ATTR : constant String := "tags";
POST_ALLOW_COMMENTS_ATTR : constant String := "allow_comments";
-- ------------------------------
-- Blog Bean
-- ------------------------------
-- The <b>Blog_Bean</b> holds the information about the current blog.
-- It allows to create the blog as well as update its primary title.
type Blog_Bean is new AWA.Blogs.Models.Blog_Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
end record;
type Blog_Bean_Access is access all Blog_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Blog_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Blog_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create a new blog.
overriding
procedure Create (Bean : in out Blog_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Blog_Bean bean instance.
function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Post Bean
-- ------------------------------
-- The <b>Post_Bean</b> is used to create or update a post associated with a blog.
type Post_Bean is new AWA.Blogs.Models.Post_Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
Blog_Id : ADO.Identifier;
-- List of tags associated with the post.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Post_Bean_Access is access all Post_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Post_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Post_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the post.
procedure Load_Post (Post : in out Post_Bean;
Id : in ADO.Identifier);
-- Create or save the post.
overriding
procedure Save (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete a post.
overriding
procedure Delete (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the post.
overriding
procedure Load (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Post_Bean bean instance.
function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Post List Bean
-- ------------------------------
-- The <b>Post_List_Bean</b> gives a list of visible posts to be displayed to users.
-- The list can be filtered by a given tag. The list pagination is supported.
type Post_List_Bean is new AWA.Blogs.Models.Post_List_Bean with record
Posts : aliased AWA.Blogs.Models.Post_Info_List_Bean;
Service : Modules.Blog_Module_Access := null;
Tags : AWA.Tags.Beans.Entity_Tag_Map;
Posts_Bean : AWA.Blogs.Models.Post_Info_List_Bean_Access;
end record;
type Post_List_Bean_Access is access all Post_List_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Post_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Post_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
overriding
procedure Load (From : in out Post_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the list of posts. If a tag was set, filter the list of posts with the tag.
procedure Load_List (Into : in out Post_List_Bean);
-- Create the Post_List_Bean bean instance.
function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Get a select item list which contains a list of post status.
function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Init_Flag is (INIT_BLOG_LIST, INIT_POST_LIST, INIT_COMMENT_LIST);
type Init_Map is array (Init_Flag) of Boolean;
-- ------------------------------
-- Admin List Bean
-- ------------------------------
-- The <b>Blog_Admin_Bean</b> is used for the administration of a blog. It gives the
-- list of posts that are created, published or not.
type Blog_Admin_Bean is new Util.Beans.Basic.Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
-- The blog identifier.
Blog_Id : ADO.Identifier := ADO.NO_IDENTIFIER;
-- List of blogs.
Blog_List : aliased AWA.Blogs.Models.Blog_Info_List_Bean;
Blog_List_Bean : AWA.Blogs.Models.Blog_Info_List_Bean_Access;
-- List of posts.
Post_List : aliased AWA.Blogs.Models.Admin_Post_Info_List_Bean;
Post_List_Bean : AWA.Blogs.Models.Admin_Post_Info_List_Bean_Access;
-- List of comments.
Comment_List : aliased AWA.Blogs.Models.Comment_Info_List_Bean;
Comment_List_Bean : AWA.Blogs.Models.Comment_Info_List_Bean_Access;
-- Initialization flags.
Init_Flags : aliased Init_Map := (others => False);
Flags : access Init_Map;
end record;
type Blog_Admin_Bean_Access is access all Blog_Admin_Bean;
-- Get the blog identifier.
function Get_Blog_Id (List : in Blog_Admin_Bean) return ADO.Identifier;
-- Load the posts associated with the current blog.
procedure Load_Posts (List : in Blog_Admin_Bean);
-- Load the comments associated with the current blog.
procedure Load_Comments (List : in Blog_Admin_Bean);
overriding
function Get_Value (List : in Blog_Admin_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Blog_Admin_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the list of blogs.
procedure Load_Blogs (List : in Blog_Admin_Bean);
-- Create the Blog_Admin_Bean bean instance.
function Create_Blog_Admin_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end AWA.Blogs.Beans;
|
-- Generated by Snowball 2.2.0 - https://snowballstem.org/
package body Stemmer.Norwegian is
pragma Style_Checks ("-mr");
pragma Warnings (Off, "*variable*is never read and never assigned*");
pragma Warnings (Off, "*mode could be*instead of*");
pragma Warnings (Off, "*formal parameter.*is not modified*");
pragma Warnings (Off, "*this line is too long*");
pragma Warnings (Off, "*is not referenced*");
procedure R_Other_suffix (Z : in out Context_Type; Result : out Boolean);
procedure R_Consonant_pair (Z : in out Context_Type; Result : out Boolean);
procedure R_Main_suffix (Z : in out Context_Type; Result : out Boolean);
procedure R_Mark_regions (Z : in out Context_Type; Result : out Boolean);
G_V : constant Grouping_Array (0 .. 151) := (
True, False, False, False, True, False, False, False,
True, False, False, False, False, False, True, False,
False, False, False, False, True, False, False, False,
True, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, True, True, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, True
);
G_S_ending : constant Grouping_Array (0 .. 31) := (
True, True, True, False, True, True, True, False,
True, False, True, True, True, True, True, False,
True, False, True, False, True, False, False, True,
True, False, False, False, False, False, False, False
);
Among_String : constant String := "a" & "e" & "ede" & "ande" & "ende"
& "ane" & "ene" & "hetene" & "erte" & "en" & "heten" & "ar" & "er" & "heter"
& "s" & "as" & "es" & "edes" & "endes" & "enes" & "hetenes" & "ens" & "hetens"
& "ers" & "ets" & "et" & "het" & "ert" & "ast" & "dt" & "vt" & "leg" & "eleg"
& "ig" & "eig" & "lig" & "elig" & "els" & "lov" & "elov" & "slov" & "hetslov";
A_0 : constant Among_Array_Type (0 .. 28) := (
(1, 1, -1, 1, 0),
(2, 2, -1, 1, 0),
(3, 5, 1, 1, 0),
(6, 9, 1, 1, 0),
(10, 13, 1, 1, 0),
(14, 16, 1, 1, 0),
(17, 19, 1, 1, 0),
(20, 25, 6, 1, 0),
(26, 29, 1, 3, 0),
(30, 31, -1, 1, 0),
(32, 36, 9, 1, 0),
(37, 38, -1, 1, 0),
(39, 40, -1, 1, 0),
(41, 45, 12, 1, 0),
(46, 46, -1, 2, 0),
(47, 48, 14, 1, 0),
(49, 50, 14, 1, 0),
(51, 54, 16, 1, 0),
(55, 59, 16, 1, 0),
(60, 63, 16, 1, 0),
(64, 70, 19, 1, 0),
(71, 73, 14, 1, 0),
(74, 79, 21, 1, 0),
(80, 82, 14, 1, 0),
(83, 85, 14, 1, 0),
(86, 87, -1, 1, 0),
(88, 90, 25, 1, 0),
(91, 93, -1, 3, 0),
(94, 96, -1, 1, 0));
A_1 : constant Among_Array_Type (0 .. 1) := (
(97, 98, -1, -1, 0),
(99, 100, -1, -1, 0));
A_2 : constant Among_Array_Type (0 .. 10) := (
(101, 103, -1, 1, 0),
(104, 107, 0, 1, 0),
(108, 109, -1, 1, 0),
(110, 112, 2, 1, 0),
(113, 115, 2, 1, 0),
(116, 119, 4, 1, 0),
(120, 122, -1, 1, 0),
(123, 125, -1, 1, 0),
(126, 129, 7, 1, 0),
(130, 133, 7, 1, 0),
(134, 140, 9, 1, 0));
procedure R_Mark_regions (Z : in out Context_Type; Result : out Boolean) is
C : Result_Index;
A : Integer;
v_1 : Char_Index;
begin
-- (, line 26
Z.I_P1 := Z.L;
-- test, line 30
v_1 := Z.C;
-- (, line 30
C := Skip_Utf8 (Z, 3); -- hop, line 30
if C < 0 then
Result := False;
return;
end if;
Z.C := C;
-- setmark x, line 30
Z.I_X := Z.C;
Z.C := v_1;
-- goto, line 31
Out_Grouping (Z, G_V, 97, 248, True, C); if C < 0 then
Result := False;
return;
end if;
-- gopast, line 31
-- non v, line 31
In_Grouping (Z, G_V, 97, 248, True, C);
if C < 0 then
Result := False;
return;
end if;
Z.C := Z.C + C;
-- setmark p1, line 31
Z.I_P1 := Z.C;
-- try, line 32
-- (, line 32
if not (Z.I_P1 < Z.I_X) then
goto lab2;
end if;
Z.I_P1 := Z.I_X;
<<lab2>>
Result := True;
end R_Mark_regions;
procedure R_Main_suffix (Z : in out Context_Type; Result : out Boolean) is
C : Result_Index;
A : Integer;
v_2 : Integer;
v_3 : Char_Index;
begin
-- (, line 37
if Z.C < Z.I_P1 then
Result := False;
return;
end if;
v_2 := Z.Lb; Z.Lb := Z.I_P1;
-- (, line 38
Z.Ket := Z.C; -- [, line 38
-- substring, line 38
if Z.C <= Z.Lb or else Check_Among (Z, Z.C - 1, 3, 16#1c4022#) then
Z.Lb := v_2;
Result := False;
return;
-- substring, line 38
end if;
Find_Among_Backward (Z, A_0, Among_String, null, A);
if A = 0 then
Z.Lb := v_2;
Result := False;
return;
end if;
Z.Bra := Z.C; -- ], line 38
Z.Lb := v_2;
-- among, line 39
case A is
when 1 =>
-- (, line 44
-- delete, line 44
Slice_Del (Z);
when 2 =>
-- (, line 46
-- or, line 46
v_3 := Z.L - Z.C;
In_Grouping_Backward (Z, G_S_ending, 98, 122, False, C);
if C /= 0 then
goto lab1;
end if;
goto lab0;
<<lab1>>
Z.C := Z.L - v_3;
-- (, line 46
-- literal, line 46
C := Eq_S_Backward (Z, "k");
if C = 0 then
Result := False;
return;
end if;
Z.C := Z.C - C;
Out_Grouping_Backward (Z, G_V, 97, 248, False, C);
if C /= 0 then
Result := False;
return;
end if;
<<lab0>>
-- delete, line 46
Slice_Del (Z);
when 3 =>
-- (, line 48
-- <-, line 48
Slice_From (Z, "er");
when others =>
null;
end case;
Result := True;
end R_Main_suffix;
procedure R_Consonant_pair (Z : in out Context_Type; Result : out Boolean) is
C : Result_Index;
A : Integer;
v_1 : Char_Index;
v_3 : Integer;
begin
-- (, line 52
-- test, line 53
v_1 := Z.L - Z.C;
-- (, line 53
if Z.C < Z.I_P1 then
Result := False;
return;
end if;
v_3 := Z.Lb; Z.Lb := Z.I_P1;
-- (, line 54
Z.Ket := Z.C; -- [, line 54
-- substring, line 54
if Z.C - 1 <= Z.Lb or else Character'Pos (Z.P (Z.C)) /= 116 then
Z.Lb := v_3;
Result := False;
return;
-- substring, line 54
end if;
Find_Among_Backward (Z, A_1, Among_String, null, A);
if A = 0 then
Z.Lb := v_3;
Result := False;
return;
end if;
Z.Bra := Z.C; -- ], line 54
Z.Lb := v_3;
Z.C := Z.L - v_1;
-- next, line 59
C := Skip_Utf8_Backward (Z);
if C < 0 then
Result := False;
return;
end if;
Z.C := C;
Z.Bra := Z.C; -- ], line 59
-- delete, line 59
Slice_Del (Z);
Result := True;
end R_Consonant_pair;
procedure R_Other_suffix (Z : in out Context_Type; Result : out Boolean) is
C : Result_Index;
A : Integer;
v_2 : Integer;
begin
-- (, line 62
if Z.C < Z.I_P1 then
Result := False;
return;
end if;
v_2 := Z.Lb; Z.Lb := Z.I_P1;
-- (, line 63
Z.Ket := Z.C; -- [, line 63
-- substring, line 63
if Z.C - 1 <= Z.Lb or else Check_Among (Z, Z.C - 1, 3, 16#480080#) then
Z.Lb := v_2;
Result := False;
return;
-- substring, line 63
end if;
Find_Among_Backward (Z, A_2, Among_String, null, A);
if A = 0 then
Z.Lb := v_2;
Result := False;
return;
end if;
Z.Bra := Z.C; -- ], line 63
Z.Lb := v_2;
-- (, line 67
-- delete, line 67
Slice_Del (Z);
Result := True;
end R_Other_suffix;
procedure Stem (Z : in out Context_Type; Result : out Boolean) is
C : Result_Index;
A : Integer;
v_1 : Char_Index;
v_2 : Char_Index;
v_3 : Char_Index;
v_4 : Char_Index;
begin
-- (, line 72
-- do, line 74
v_1 := Z.C;
-- call mark_regions, line 74
R_Mark_regions (Z, Result);
Z.C := v_1;
Z.Lb := Z.C; Z.C := Z.L; -- backwards, line 75
-- (, line 75
-- do, line 76
v_2 := Z.L - Z.C;
-- call main_suffix, line 76
R_Main_suffix (Z, Result);
Z.C := Z.L - v_2;
-- do, line 77
v_3 := Z.L - Z.C;
-- call consonant_pair, line 77
R_Consonant_pair (Z, Result);
Z.C := Z.L - v_3;
-- do, line 78
v_4 := Z.L - Z.C;
-- call other_suffix, line 78
R_Other_suffix (Z, Result);
Z.C := Z.L - v_4;
Z.C := Z.Lb;
Result := True;
end Stem;
end Stemmer.Norwegian;
|
-- ADATU401.ADA Ver. 4.01 2001-SEP-10 Copyright 1988-2001 John J. Herro
--
-- SOFTWARE INNOVATIONS TECHNOLOGY www.adatutor.com
-- 1083 MANDARIN DR NE
-- PALM BAY FL 32905-4706 john@adatutor.com
--
-- (321) 951-0233
--
--
-- This code is written in Ada 83 and will compile on Ada 83 and Ada 95
-- compilers.
--
-- Before compiling this file, you must compile ONE of the following:
--
-- ADA95.ADA Recommended when using any Ada 95 compiler.
-- JANUS16.PKG Recommended when using a PC with 16-bit Janus/Ada.
-- JANUS32.PKG Recommended when using a PC with 32-bit Janus/Ada.
-- OPEN.ADA Recommended when using a PC with an Open Ada compiler.
-- UNIX.ADA Recommended for UNIX based systems, if you can also
-- compile ONECHAR.C or ALTCHAR.C with a C compiler and
-- link with Ada.
-- VAX.ADA Recommended when using VAX Ada.
-- VANILLA.ADA "Plain vanilla" version for all other systems. Should work
-- with ANY standard Ada 83 or Ada 95 compiler. On some
-- systems, VANILLA.ADA may require you to strike Enter
-- after each response.
--
-- See the PRINTME.TXT file for more information on installing AdaTutor on
-- other computers.
--
--
-- NOTE: If you compile this file (ADATU401.ADA) for a PC, the PC will have to
-- run ANSI.SYS (which comes with DOS and Windows) for AdaTutor to run
-- correctly. The file ADATUTOR.EXE, supplied with this program, runs on a PC
-- and does NOT require ANSI.SYS. It was produced by compiling PCSOURCE.ADA
-- rather than ADATU401.ADA.
--
-- Introduction:
--
-- AdaTutor provides interactive instruction in the Ada programming language,
-- allowing you to learn at your own pace. Under DOS (or in a DOS partition
-- under any version of Windows), access to an Ada compiler is helpful, but not
-- required. You can exit this program at any time by striking X, and later
-- resume the session exactly where you left off. If you have a color screen,
-- you can set the foreground, background, and border colors at any time by
-- typing S.
--
-- AdaTutor presents a screenful of information at a time. Screens are read
-- in 64-byte blocks from the random access file ADATUTOR.DAT, using Direct_IO.
-- For most screens, AdaTutor waits for you to strike one character to
-- determine which screen to show next. Screens are numbered starting with
-- 101; each screen has a three-digit number. Screens 101 through 108 have
-- special uses, as follows:
--
-- 101 - This screen is presented when you complete the Ada course. It
-- contains a congratulatory message. After this screen is shown,
-- control returns directly to the operating system; the program doesn't
-- wait for you to strike a character.
-- 102 - This screen is presented when you exit AdaTutor before completing the
-- course. After this screen is shown, control returns directly to the
-- operating system; the program doesn't wait for you to strike a
-- character.
-- 103 - This screen is shown whenever you strike X. It displays the number of
-- the last screen shown and the approximate percentage through the
-- course. It then asks if you want to exit the program. If you strike
-- Y, screen 102 is shown and control returns to the operating system.
-- If you type N, screen 108 is shown to provide a menu of further
-- choices. From screen 103, you can also strike M to see the main menu
-- (screen 106).
-- 104 - This is the opening screen. It asks if you've used AdaTutor before.
-- If you strike N, a welcome screen is presented and the course begins.
-- If you strike Y, screen 107 is shown.
-- 105 - This screen allows you to type the number of the next screen you want
-- to see. For this screen, instead of striking one character, you type
-- a three-digit number and presses Enter. Any number from 104 through
-- the largest screen number is accepted.
-- 106 - This screen contains the main menu of topics covered in AdaTutor.
-- When you select a main topic, an appropriate sub-menu is shown.
-- 107 - This screen is shown when you say that you've used AdaTutor before.
-- It says "Welcome back!" and provides a menu that lets you resume where
-- you left off, go back to the last question or Outside Assignment, go
-- to the main menu (screen 106), or go to any specified screen number
-- (via screen 105).
-- 108 - This screen is shown when you answer N to screen 103. It provides a
-- menu similar to screen 107, except that the first choice takes you
-- back to the screen shown before you saw 103. For example, if you
-- strike X while viewing screen 300, you'll see screen 103. If you then
-- answer N, you'll see screen 108. From 108 the first menu selection
-- takes you back to 300.
--
-- Format of the Data File:
--
-- ADATUTOR.DAT is a random access file of 64-byte blocks. The format of this
-- file changed considerably starting with version 2.00 of AdaTutor. It's now
-- much more compact, and, although it's still a data file, it now contains
-- only the 95 printable ASCII characters.
--
-- The first block of ADATUTOR.DAT is referred to as block 1, and the first 35
-- blocks together are called the index. Bytes 2 through 4 of block 1 contain,
-- in ASCII, the number of the welcome screen that's shown when you say that
-- you haven't used AdaTutor before. Bytes 6 through 8 of block 1 contain the
-- number of the highest screen in the course. (Bytes 1 and 5 of block 1
-- contain spaces.)
--
-- Bytes 9 of block 1 through the end of block 35 contain four bytes of
-- information for each of the possible screens 101 through 658. For example,
-- information for screen 101 is stored in bytes 9 through 12 of block 1, the
-- next four bytes are for screen 102, etc. For screens that don't exist, all
-- four bytes contain spaces.
--
-- The first of the four bytes is A if the corresponding screen introduces an
-- Outside Assignment, Q if the screen asks a question, or a space otherwise.
-- The next two bytes give the number of the block where data for the screen
-- begins, in base 95! A space represents 0, ! represents 1, " represents 2,
-- # represents 3, $ represents 4, etc., through all the printable characters
-- of the ASCII set. A tilde (~) represents 94.
--
-- The last of the four bytes gives the position, 1 through 64, within the
-- block where the data for this screen starts. Again, ! represents 1,
-- " represents 2, # represents 3, etc.
--
-- Data for the screens are stored starting in position 1 of block 36. In the
-- screen data, the following characters have special meaning:
--
-- ` displays the number of spaces indicated by the next character (# = 3,
-- $ = 4, etc.)
-- ~ toggles reverse video.
-- ^ toggles high intensity.
-- { causes CR-LF.
-- } moves cursor to row 24, column 1, for a prompt.
--
-- These characters have special meaning in screen 103 only:
--
-- # shows approximate percentage through the course.
-- $ shows the number of the screen seen before 103.
--
-- Immediately after }, b represents "Please type a space to go on, or B to go
-- back." and q represents "Please type a space to go on, or B to go back to
-- the question."
--
--
-- The data for each screen are followed by the "control information" for that
-- screen, in square brackets. The control information is a list of characters
-- that you might strike after seeing this screen. Each character is followed
-- by the three-digit number of the next screen to be shown when that character
-- is struck. For example, Y107N122 is the control information for screen 104.
-- This means that if you strike Y, screen 107 will be shown next, and if you
-- strikes N, screen 122 will be shown. Striking any other character will
-- simply cause a beep (except that X can always be typed to exit the program,
-- S can always be typed to set colors, and CR will be ignored). If the
-- control information is simply #, you are prompted to type the next screen
-- number. This feature is used in screen 105.
--
-- A "screen number" of 098 following a character means "go back to the last
-- Outside Assignment," and 099 means "go back to the last question." These
-- special numbers are used in screens 107 and 108. Number 100 means "go back
-- to the previous screen seen."
--
-- AdaTutor opens the Data File in In_File mode for read-only access.
--
--
--
-- Format of the User File:
--
-- The User File USERDATA.TXT is a text file containing four lines: the number
-- of the last screen seen the last time you ran AdaTutor, a number
-- representing the foreground color, a number representing the background
-- color, and a number representing the border color. The numbers 0 through 7
-- represent black, red, green, yellow, blue, magenta, cyan, and white, in that
-- order. Note that not all color PCs have a separate border color.
--
with Custom_IO, Direct_IO, Text_IO; use Custom_IO;
procedure AdaTutor is
subtype Block_Subtype is String(1 .. 64);
package Random_IO is new Direct_IO(Block_Subtype); use Random_IO;
Ix_Size : constant := 35; -- Number of blocks in the index.
Data_File : File_Type; -- The file from which screens are read.
User_File : Text_IO.File_Type; -- Holds last screen seen, and colors.
Block : Block_Subtype; -- Buffer for random-access I/O.
Vpos : Integer; -- Number of the current block.
Hpos : Integer; -- Current position within current block.
SN, Old_SN : Integer := 104; -- Screen num. and previous screen num.
Quitting_SN : Integer := 104; -- Screen number where you left off.
Highest_SN : Integer; -- Highest screen number in the course.
Welcome_SN : Integer; -- Number of the screen shown to new users.
Indx : String(1 .. 64*Ix_Size); -- Index from the Data File.
Files_OK : Boolean := False; -- True when files open successfully.
High_Int : Boolean := False; -- True when displaying high intensity.
Rev_Vid : Boolean := False; -- True when displaying reverse video.
Ctrl_C : constant Character := Character'Val(3); -- Control C.
Beep : constant Character := Character'Val(7); -- Bell.
LF : constant Character := Character'Val(10); -- Line Feed.
CR : constant Character := Character'Val(13); -- Carr. Return.
User_File_Name : constant String := "USERDATA.TXT"; -- Name of User File.
Legal_Note : constant String := " Copyright 1988-2001 John J. Herro ";
-- Legal_Note isn't used by the program, but it causes most
-- compilers to place this string in the executable file.
procedure Open_Data_File is separate;
procedure Open_User_File is separate;
procedure Show_Current_Screen is separate;
procedure Get_Next_Screen_Number is separate;
procedure Update_User_File is separate;
begin
Open_Data_File;
Open_User_File;
if Files_OK then
Set_Border_Color(To => Border_Color); -- Set default colors.
Put(Normal_Colors);
while SN > 0 loop -- "Screen number" of 0 means end the program.
Put(Clear_Scrn); -- Clear the screen.
Show_Current_Screen;
Get_Next_Screen_Number;
end loop;
Close(Data_File);
Update_User_File;
end if;
end AdaTutor;
separate (AdaTutor)
procedure Open_Data_File is
Data_File_Name : constant String := "ADATUTOR.DAT";
begin
Open(Data_File, Mode => In_File, Name => Data_File_Name);
for I in 1 .. Ix_Size loop -- Read index from start of Data File.
Read(Data_File, Item => Block, From => Count(I));
Indx(64*I - 63 .. 64*I) := Block;
end loop;
Welcome_SN := Integer'Value(Indx(2 .. 4));
Highest_SN := Integer'Value(Indx(6 .. 8));
Files_OK := True;
exception
when Name_Error =>
Put("I'm sorry. The file " & Data_File_Name);
Put_Line(" seems to be missing.");
when others =>
Put("I'm sorry. The file " & Data_File_Name);
Put_Line(" seems to have the wrong form.");
end Open_Data_File;
separate (AdaTutor)
procedure Open_User_File is
Input : String(1 .. 6);
Len : Integer;
begin
Text_IO.Open(User_File, Mode => Text_IO.In_File, Name => User_File_Name);
Text_IO.Get_Line(User_File, Input, Len);
Quitting_SN := Integer'Value(Input(1 .. Len));
Old_SN := Quitting_SN;
Text_IO.Get_Line(User_File, Input, Len);
Foregrnd_Color := Color'Val(Integer'Value(Input(1 .. Len)));
Fore_Color_Digit := Input(2);
Normal_Colors(6) := Fore_Color_Digit;
Text_IO.Get_Line(User_File, Input, Len);
Backgrnd_Color := Color'Val(Integer'Value(Input(1 .. Len)));
Back_Color_Digit := Input(2);
Normal_Colors(9) := Back_Color_Digit;
Text_IO.Get_Line(User_File, Input, Len);
Border_Color := Color'Val(Integer'Value(Input(1 .. Len)));
Text_IO.Close(User_File);
exception
when Text_IO.Name_Error =>
Put("I'm sorry. The file " & User_File_Name);
Put_Line(" seems to be missing.");
Files_OK := False;
when others =>
Put("I'm sorry. The file " & User_File_Name);
Put_Line(" seems to have the wrong form.");
Files_OK := False;
end Open_User_File;
separate (AdaTutor)
procedure Show_Current_Screen is
Half_Diff : Integer := (Highest_SN - Welcome_SN) / 2;
Percent : Integer := (50 * (Old_SN - Welcome_SN)) / Half_Diff;
-- Percentage of the course completed. Using 50 and
-- Half_Diff guarantees that the numerator < 2 ** 15.
Expanding : Boolean := False; -- True when expanding multiple spaces.
Literal : Boolean := False; -- True to display next character as is.
Prompting : Boolean := False; -- True for first character in a prompt.
Space : constant String(1 .. 80) := (others => ' ');
procedure Process_Char is separate;
begin
Vpos := 95*(Character'Pos(Indx(SN*4 - 394)) - 32) + -- Point to start
Character'Pos(Indx(SN*4 - 393)) - 32; -- of current
Hpos := Character'Pos(Indx(SN*4 - 392)) - 32; -- screen.
Read(Data_File, Item => Block, From => Count(Vpos));
if Percent < 0 then -- Make sure Percent is reasonable.
Percent := 0;
elsif Percent > 99 then
Percent := 99;
end if;
while Block(Hpos) /= '[' or Expanding or Literal loop -- [ starts ctrl info.
if Expanding then
if Block(Hpos) = '!' then
Literal := True;
else
Put(Space(1 .. Character'Pos(Block(Hpos)) - 32));
end if;
Expanding := False;
elsif Literal then
Put(Block(Hpos));
Literal := False;
elsif Prompting then
case Block(Hpos) is
when 'b' => Put("Please type a space to go on, or B to go back.");
when 'q' => Put("Please type a space to go on, or B to go back ");
Put("to the question.");
when others => Process_Char;
end case;
Prompting := False;
else
Process_Char;
end if;
Hpos := Hpos + 1;
if Hpos > Block'Length then
Vpos := Vpos + 1;
Hpos := 1;
Read(Data_file, Item => Block, From => Count(Vpos));
end if;
end loop;
end Show_Current_Screen;
separate (AdaTutor.Show_Current_Screen)
procedure Process_Char is
begin
case Block(Hpos) is
when '{' => New_Line; -- { = CR-LF.
when '`' => Expanding := True; -- ` = several spaces.
when '^' => High_Int := not High_Int; -- ^ = toggle bright.
if High_Int then
Put(Esc & "[1m");
else
Put(Normal_Colors);
end if;
when '}' => Put(Esc & "[24;1H(Screen"); -- } = go to line 24.
Put(Integer'Image(SN) & ") "); -- and show SN.
Prompting := True;
when '~' => Rev_Vid := not Rev_Vid; -- ~ = toggle rev. vid.
if Rev_Vid then
Put(Esc & "[7m");
else
Put(Normal_Colors);
end if;
when '$' => if SN = 103 then -- $ = screen #.
Put(Integer'Image(Old_SN));
else
Put('$');
end if;
when '#' => if SN = 103 then -- # = % completed.
Put(Integer'Image(Percent));
else
Put('#');
end if;
when others => Put(Block(Hpos));
end case;
end Process_Char;
separate (AdaTutor)
procedure Get_Next_Screen_Number is
Ctrl_Info : Block_Subtype; -- Control info. for the current screen.
Place : Integer := 1; -- Current position within Ctrl_Info.
Input : String(1 .. 4); -- Screen number that you type.
Len : Integer; -- Length of typed response.
Valid : Boolean; -- True when typed response is valid.
procedure Set_Colors is separate;
procedure Input_One_Keystroke is separate;
begin
while Block(Hpos) /= ']' loop -- Read control information from Data File.
Hpos := Hpos + 1;
if Hpos > Block'Length then
Vpos := Vpos + 1;
Hpos := 1;
Read(Data_File, Item => Block, From => Count(Vpos));
end if;
Ctrl_Info(Place) := Block(Hpos);
Place := Place + 1;
end loop;
if SN = 103 then -- Screen 103 means you typed X to exit.
Quitting_SN := Old_SN;
elsif SN >= Welcome_SN then -- Save SN so you can return to it.
Old_SN := SN;
end if;
if SN < 103 then -- Set SN to # of the next screen.
SN := 0; -- Set signal to end the program after screens 101 and 102.
elsif Ctrl_Info(1) = '#' then -- You type the next screen number.
Valid := False;
while not Valid loop -- Keep trying until response is valid.
Put("# "); -- Prompt for screen number.
Input := " "; Get_Line(Input, Len); -- Input screen number.
if Input(1) = 'x' or Input(1) = 'X' or Input(1) = Ctrl_C then
SN := 103; -- Show screen 103 if you type X.
Valid := True; -- X is a valid response.
elsif Input(1) = 's' or Input(1) = 'S' then
Set_Colors; -- Set colors if you type S.
Valid := True; -- S is a valid response.
else
begin -- Convert ASCII input to
SN := Integer'Value(Input); -- integer. If in range,
Valid := SN in 104 .. Highest_SN; -- set Valid to True. If
exception -- it can't be converted
when others => null; -- (e.g., illegal char.),
end; -- or it's out of range,
end if; -- leave Valid = False so
if not Valid and Len > 0 then -- you can try again.
Put_Line("Incorrect number. Please try again.");
end if;
end loop;
else
Input_One_Keystroke;
end if;
end Get_Next_Screen_Number;
separate (AdaTutor.Get_Next_Screen_Number)
procedure Set_Colors is
Bright : constant String := Esc & "[1m"; -- Causes high intensity.
Keystroke : Character := 'f'; -- Single character that you type.
Space : constant String(1 .. 23) := (others => ' ');
begin
while Keystroke = 'f' or Keystroke = 'b' or Keystroke = 'r' or
Keystroke = 'F' or Keystroke = 'B' or Keystroke = 'R' or
Keystroke = CR or Keystroke = LF loop
Put(Clear_Scrn); -- Clear the screen.
New_Line;
Put(Space & "The " & Bright & "foreground" & Normal_Colors);
Put_Line(" color is now " & Color'Image(Foregrnd_Color) & '.');
Put(Space & "The " & Bright & "background" & Normal_Colors);
Put_Line(" color is now " & Color'Image(Backgrnd_Color) & '.');
Put(Space & "The " & Bright & " border " & Normal_Colors);
Put_Line(" color is now " & Color'Image(Border_Color) & '.');
New_Line;
Put_Line(Space & " Note: Some color PCs don't have");
Put_Line(Space & " separate border colors.");
New_Line;
Put_Line(Space & " Strike:");
Put_Line(Space & "F to change the foreground color,");
Put_Line(Space & "B to change the background color,");
Put_Line(Space & "R to change the border color.");
New_Line;
Put_Line(Space & "Strike the space bar to continue.");
Get(Keystroke); -- Get one character from keyboard.
if Keystroke = 'f' or Keystroke = 'F' then
Foregrnd_Color := Color'Val((Color'Pos(Foregrnd_Color) + 1) mod 8);
if Foregrnd_Color = Backgrnd_Color then
Foregrnd_Color := Color'Val((Color'Pos(Foregrnd_Color) + 1) mod 8);
end if;
elsif Keystroke = 'b' or Keystroke = 'B' then
Backgrnd_Color := Color'Val((Color'Pos(Backgrnd_Color) + 1) mod 8);
if Foregrnd_Color = Backgrnd_Color then
Backgrnd_Color := Color'Val((Color'Pos(Backgrnd_Color) + 1) mod 8);
end if;
elsif Keystroke = 'r' or Keystroke = 'R' then
Border_Color := Color'Val((Color'Pos(Border_Color) + 1) mod 8);
end if;
Fore_Color_Digit := Character'Val(48 + Color'Pos(Foregrnd_Color));
Back_Color_Digit := Character'Val(48 + Color'Pos(Backgrnd_Color));
Normal_Colors(6) := Fore_Color_Digit;
Normal_Colors(9) := Back_Color_Digit;
Put(Normal_Colors);
Set_Border_Color(To => Border_Color);
end loop;
end Set_Colors;
separate (AdaTutor.Get_Next_Screen_Number)
procedure Input_One_Keystroke is
Keystroke : Character; -- Single character that you type.
Valid : Boolean := False; -- True when typed response is valid.
Search : Character; -- 'A' = last Outside Assignment; 'Q' = last Ques.
begin
Put(" >"); -- Prompt for one character.
while not Valid loop -- Keep trying until response is valid.
Get(Keystroke); -- Get one character from keyboard.
if Keystroke in 'a' .. 'z' then -- Force upper case to simplify.
Keystroke := Character'Val(Character'Pos(Keystroke) - 32);
end if;
if Keystroke = 'X' or Keystroke = Ctrl_C then
SN := 103; -- Show screen 103 if you type X.
Valid := True; -- X is a valid response.
elsif Keystroke = 'S' then
Set_Colors; -- Set colors if you type S.
Valid := True; -- S is a valid response.
end if;
Place := 1; -- Search list of valid characters for this screen.
Valid := Valid; -- This statement works around a minor bug in
-- ver. 1.0 of the Meridian IFORM optimizer.
while not Valid and Ctrl_Info(Place) /= ']' loop -- ] ends the list.
if Keystroke = Ctrl_Info(Place) then
-- Typed char. found in list; get screen # from control info.
SN := Integer'Value(Ctrl_Info(Place + 1 .. Place + 3));
Valid := True; -- Characters in the list are all valid responses.
end if;
Place := Place + 4; -- A 3-digit number follows each char. in list.
end loop;
if not Valid and Keystroke /= CR and Keystroke /= LF then
Put(Beep); -- Beep if response is not valid,
end if; -- but ignore CRs and LFs quietly.
end loop;
if SN = 98 then -- Go back to last Outside Assignment.
Search := 'A';
elsif SN = 99 then -- Go back to last question.
Search := 'Q';
elsif SN = 100 then -- Go back to the last screen seen.
SN := Quitting_SN;
end if;
if SN = 98 or SN = 99 then
SN := Old_SN;
while SN > Welcome_SN and Indx(SN*4 - 395) /= Search loop
SN := SN - 1;
end loop;
end if;
end Input_One_Keystroke;
separate (AdaTutor)
procedure Update_User_File is
begin
Text_IO.Create(User_File, Mode => Text_IO.Out_File, Name => User_File_Name);
Text_IO.Put_Line(User_File, Integer'Image(Quitting_SN));
Text_IO.Put_Line(User_File, Integer'Image(Color'Pos(Foregrnd_Color)));
Text_IO.Put_Line(User_File, Integer'Image(Color'Pos(Backgrnd_Color)));
Text_IO.Put_Line(User_File, Integer'Image(Color'Pos(Border_Color)));
Text_IO.Close(User_File);
end Update_User_File;
|
-----------------------------------------------------------------------
-- package body Extended_Real.Elementary_Functions, extended precision functions
-- 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 body Extended_Real.Elementary_Functions is
Max_Available_Bits : constant e_Integer
:= Desired_No_Of_Bits_in_Radix * e_Real_Machine_Mantissa;
-- This equals: Bits_per_Mantissa = Bits_per_Digit * No_of_Digits_per_Mantissa
-- (e_Real_Machine_Mantissa = Mantissa'Length = No_of_Digits_per_Mantissa).
-- The following are frequently used global constants:
Radix : constant Real := e_Real_Machine_Radix;
Half_Digit : constant E_Digit := Make_E_Digit (0.5);
Two_Digit : constant E_Digit := Make_E_Digit (2.0);
Three_Digit : constant E_Digit := Make_E_Digit (3.0);
Four_Digit : constant E_Digit := Make_E_Digit (4.0);
Nine_Digit : constant E_Digit := Make_E_Digit (9.0);
Twelve_Digit : constant E_Digit := Make_E_Digit (12.0);
--One : constant e_Real := +1.0; -- in Extended_Real spec
--Zero : constant e_Real := +0.0;
Two : constant e_Real := +2.0;
Three : constant e_Real := +3.0;
Half : constant e_Real := +0.5;
Three_Quarters : constant e_Real := +(0.75);
Less_Than_Half_Pi : constant e_Real := +(3.14159265 / 2.0);
-- Global memory for important constants. They're initialized
-- on the first call to the functions that return them, and
-- there after are simply returned from memory:
-- Pi, Sqrt_2, etc
type Pi_mem is record
Val : e_Real; -- automatically initialized to Zero.
Initialized : Boolean := False;
end record;
Pi_Memory : Pi_Mem;
type Inverse_Pi_mem is record
Val : e_Real; -- automatically initialized to Zero.
Initialized : Boolean := False;
end record;
Inverse_Pi_Memory : Inverse_Pi_Mem;
type Quarter_Pi_mem is record
Val : e_Real; -- automatically initialized to Zero.
Initialized : Boolean := False;
end record;
Quarter_Pi_Memory : Quarter_Pi_Mem;
type Inverse_Sqrt_2_mem is record
Val : e_Real;
Initialized : Boolean := False;
end record;
Inverse_Sqrt_2_memory : Inverse_Sqrt_2_mem;
type Half_Inverse_Log_2_mem is record
Val : e_Real;
Initialized : Boolean := False;
end record;
Half_Inverse_Log_2_memory : Half_Inverse_Log_2_mem;
type Log_2_mem is record
Val : e_Real;
Initialized : Boolean := False;
end record;
Log_2_memory : Log_2_mem;
------------
-- Arcsin --
------------
-- The result of the Arcsin function is in the quadrant containing
-- the point (1.0, x), where x is the value of the parameter X. This
-- quadrant is I or IV; thus, the range of the Arcsin function is
-- approximately -Pi/2.0 to Pi/2.0 (-Cycle/4.0 to Cycle/4.0, if the
-- parameter Cycle is specified).
-- Argument_Error is raised by Arcsin when the absolute
-- value of the parameter X exceeds one.
--
-- Uses Newton's method: Y_k+1 = Y_k + (A - Sin(Y_k)) / Cos(Y_k)
-- to get Arcsin(A).
-- Requires call to Arcsin (Real) and assumes that this call gets
-- the first two radix digits correct: 48 bits usually. (It almost
-- always gets 53 bits correct.)
--
-- Arcsin(x) = x + x^3/6 + 3*x^5/40 ...
-- (so Arctan(x) = x if x < e_Real_Model_Epsilon)
function Arcsin (X : e_Real)
return e_Real
is
Y_0 : e_Real;
X_Abs : e_Real := Abs (X);
No_Correct_Bits : E_Integer;
Sign_Is_Negative : Boolean := False;
Scaling_Performed : Boolean := False;
begin
if Are_Equal (X_Abs, Positive_Infinity) then
raise E_Argument_Error;
end if;
if One < X_Abs then
raise E_Argument_Error;
end if;
if X_Abs < e_Real_Model_Epsilon then
return X; -- series solution: arcsin = x + x^3/6 + ...
end if;
Sign_Is_Negative := False;
if X < Zero then
Sign_Is_Negative := True;
end if;
if Are_Equal (X_Abs, One) then
Y_0 := Two_Digit * e_Quarter_Pi;
if Sign_Is_Negative then Y_0 := -Y_0; end if;
return Y_0;
end if;
-- STEP 2. We may have to scale the argument if it's near 1. Newton_Raphson
-- doesn't do well there. So we use identity:
--
-- arcsin(x) - arcsin(y) = arcsin(x*Sqrt(1-y*y) - y*Sqrt(1-x*x)),
--
-- so setting y = 1 (get the arccos(x) = Pi/2 - Arcsin(x)):
--
-- arcsin(x) = -arcsin(Sqrt(1-x*x)) + Pi/2.
--
-- Well, we can't use Sqrt(1-x*x) because there's too much error near
-- X = small. We can use Sqrt(1-X) * Sqrt(1+X) but don't want the 2 sqrts.
-- So! we want Arcsin (Sqrt(1-X) * Sqrt(1+X)) = Y, or
-- Sin(Y) = 2 * Sqrt((1-X)/2) * Sqrt((1+X)/2). Then Sin(Y) = 2*Sin(Z)Cos(Z)
-- where Z = Arcsin(Sqrt((1-X)/2)). So, Y = Arcsin (Sin(Z + Z)) = 2*Z.
-- The final answer is Arcsin(X) = Pi/2 - 2*Arcsin(Sqrt((1-X)/2)).
--
-- IMPORTANT: We can't scale if X_Abs <= 0.5 because we use this
-- routine with an argument of 0.5 to calculate Pi, and scaling
-- requires a knowledge of Pi.
Scaling_Performed := False;
if Three_Quarters < X_Abs then
X_Abs := Sqrt (Half - Half_Digit * X_Abs);
Scaling_Performed := True;
end if;
-- Need starting value for Newton's iteration of Arcsin (X_scaled).
-- Assume positive arg to improve likelihood that
-- external Arcsin fctn. does what we want.
Y_0 := Make_Extended (Arcsin (Make_Real (X_Abs)));
No_Correct_Bits := Real'Machine_Mantissa - 2;
loop
--Y_0 := Y_0 + (X_Abs - Sin(Y_0)) / Cos(Y_0);
Y_0 := Y_0 + Divide ((X_Abs - Sin(Y_0)) , Cos(Y_0));
-- Cos is never near 0.
No_Correct_Bits := No_Correct_Bits * 2;
exit when No_Correct_Bits >= Max_Available_Bits;
end loop;
if Scaling_Performed then
Y_0 := Two_Digit * (e_Quarter_Pi - Y_0);
end if;
if Sign_Is_Negative then
Y_0 := -Y_0;
end if;
return Y_0;
end Arcsin;
------------
-- Arccos --
------------
-- The result of the Arccos function is in the quadrant containing
-- the point (x, 1.0), where x is the value of the parameter X. This
-- quadrant is I or II; thus, the Arccos function ranges from 0.0 to
-- approximately Pi (Cycle/2.0, if the parameter Cycle is
-- specified).
--
-- Argument_Error is raised by Arccos when the absolute
-- value of the parameter X exceeds one.
--
-- In all cases use Arccos(X) = Pi/2 - Arcsin(X).
-- When Abs(X) < 0.5 we use Pi/2 - Arcsin(X). When
-- Abs(X) > 0.5 it's better to use the following formula for Arcsin:
-- Arcsin(X) = Pi/2 - 2*Arcsin(Sqrt((1-|X|)/2)). (X > 0.0)
-- Arcsin(X) = -Pi/2 + 2*Arcsin(Sqrt((1-|X|)/2)). (X < 0.0)
--
function Arccos (X : e_Real)
return e_Real
is
Result : e_Real;
X_Abs : constant e_Real := Abs (X);
begin
if X_Abs > One then
raise Constraint_Error;
end if;
if Are_Equal (X, Zero) then
return Two_Digit * e_Quarter_Pi;
end if;
if Are_Equal (X, One) then
return Zero;
end if;
if Are_Equal (X, -One) then
return e_Pi;
end if;
if Are_Equal (X, Positive_Infinity) then
raise E_Argument_Error;
end if;
if Are_Equal (X, Negative_Infinity) then
raise E_Argument_Error;
end if;
if X > Half then
Result := Two_Digit * Arcsin (Sqrt (Half - Half_Digit*X_Abs));
elsif X < -Half then
Result := Four_Digit*
(e_Quarter_Pi - Half_Digit*Arcsin (Sqrt (Half - Half_Digit*X_Abs)));
else
Result := (e_Quarter_Pi - Arcsin(X)) + e_Quarter_Pi;
end if;
-- e_Quarter_Pi is stored with more correct binary digits than
-- E_Half_Pi because it's slightly less than 1.0.
return Result;
end Arccos;
------------
-- Arctan --
------------
-- Newton's method avoids divisions:
--
-- Result := Result + Cos(Result) * (Cos(Result) * Arg - Sin(Result))
--
-- Arctan(x) = Pi/2 - Arctan(1/x)
-- Arctan(x) = -Pi/2 + Arctan(1/x) (x<0)
--
-- Arctan(x) = x - x^3/3 + x^5/5 - x^7/7 ...
-- (so Arctan(x) = x if x < e_Real_Model_Epsilon)
--
-- Arctan (X) = Arcsin(X / Sqrt(1 + X**2)).
--
-- Not really Ada95-ish for Arctan.
--
function Arctan
(X : e_Real)
return e_Real
is
Y_0, Arg, Cos_Y_0, Sin_Y_0 : e_Real;
X_Abs : constant e_Real := Abs (X);
X_real : Real;
Sign_Is_Negative : Boolean := False;
Argument_Reduced : Boolean := False;
No_Correct_Bits : E_Integer;
begin
if X_Abs < e_Real_Model_Epsilon then
return X; -- series solution: arctan = x - x^3/3 + ...
end if;
Sign_Is_Negative := False;
if X < Zero then
Sign_Is_Negative := True;
end if;
-- returns Pi/2 at +/- inf. (Note Reciprocal returns 1/inf as Zero.)
-- inf is regarded as large finite number. Raising exceptions
-- in these cases may also be good idea. Which is right?
if Are_Equal (X_Abs, Positive_Infinity) then
Y_0 := Two_Digit * e_Quarter_Pi;
if Sign_Is_Negative then Y_0 := -Y_0; end if;
return Y_0;
end if;
-- function Make_Real underflows to 0.0 as desired for small X_Abs.
if X_abs < Two then
Argument_Reduced := False;
Arg := X_abs;
else
-- use: Arctan(x) = Pi/2 - Arctan(1/x)
Argument_Reduced := True;
Arg := Reciprocal (X_abs);
end if;
X_real := Make_Real (Arg);
Y_0 := Make_Extended (Arctan (X_real));
No_Correct_Bits := Real'Machine_Mantissa - 2;
loop
Sin_Y_0 := Sin (Y_0);
Cos_Y_0 := Cos (Y_0); -- bst accuracy.
--Cos_Y_0 := Sqrt (One - Sin_Y_0*Sin_Y_0); -- fstr, not too bad accuracy-wise.
Y_0 := Y_0 + (Arg*Cos_Y_0 - Sin_Y_0) * Cos_Y_0;
No_Correct_Bits := No_Correct_Bits * 2;
exit when No_Correct_Bits >= Max_Available_Bits;
end loop;
if Argument_Reduced then
Y_0 := Two_Digit * (e_Quarter_Pi - Half_Digit*Y_0);
end if;
-- Lose a whole guard digit of precision when we double e_Quarter_Pi.
-- (It becomes slightly > 1, pushes a digit off the end of the mantissa.)
-- So do the subtraction 1st.
if Sign_Is_Negative then
Y_0 := -Y_0;
end if;
return Y_0;
end Arctan;
---------
-- Log --
---------
-- Uses Newton's method: Y_k+1 = Y_k + (A - Exp(Y_k)) / Exp(Y_k)
-- to get Log(A) = Natural Log, the inverse of Exp.
-- Requires call to Log (Real) and assumes that this call gets
-- the first two radix digits correct: 48 bits usually. (It almost
-- always gets 53 bits correct.) Argument reduction due to Brent:
-- 1st step is to get a rough approximate value of Log(X), called
-- Log_X_approx. Then get Y = Log(X/exp(Log_X_approx)).
-- The final answer is Log(X) = Y + Log_X_approx. (Disabled at present.)
-- This gets Y very near 0, which greatly speeds up subsequent
-- calls to Exp in the Newton iteration above. Actually,
-- the scaling business is commented out below. If you uncomment it,
-- the routine runs 60% faster, in some tests, but is less accurate.
-- We'll err on the side of accuracy and use an unscaled X. But
-- if you use extended floating point with 2 guard digits, it would
-- be sensible to use the scaled X, because the loss in accuracy is
-- negligable compared to the extra precision of another guard digit.
-- Test for X = One: must return Zero.
--
-- The exception Constraint_Error is raised, signaling a pole of the
-- mathematical function (analogous to dividing by zero), in the following
-- cases, provided that Float_Type'Machine_Overflows is True:
-- by the Log, Cot, and Coth functions, when the value of the
-- parameter X is zero;
function Log (X : e_Real)
return e_Real
is
Result, X_scaled, Y_0 : e_Real;
X_Exp : E_Integer;
No_Correct_Bits : E_Integer;
Log_X_approx_real : Real;
begin
if X < Zero then
raise E_Argument_Error;
end if;
if Are_Equal (X, Zero) then
raise Constraint_Error;
end if;
if Are_Equal (X, Positive_Infinity) then
raise E_Argument_Error;
end if;
if Are_Equal (X, Negative_Infinity) then
raise E_Argument_Error;
end if;
if Are_Equal (X, One) then
return Zero;
end if;
-- STEP 1. First argument reduction step. Get Log_X_approx_real using
-- a call to log(real). If X=0 or inf, then X_scaled=0..get exception.
X_Exp := Exponent (X);
X_scaled := Fraction (X); -- not zero or infinity.
Log_X_approx_real := Log (Make_Real(X_scaled)) + Log (Radix) * Real (X_Exp);
X_scaled := X;
-- Log_X_approx := Make_Extended (Log_X_approx_real);
-- X_scaled := X / Exp (Log_X_approx);
-- The above Scaling is the fastest, since then Exp does no scaling.
-- It is clearly less accurate, tho' tolerably so, especially if you
-- use two guard digits instead of 1. We use the unscaled X here,
-- because it (for example) returns a value of Log(2.0)
-- with an error that is about 50 times smaller than the above.
-- STEP 2. Need starting value for Newton's iteration of Log (X_scaled).
--Y_0 := Make_Extended (Log (Make_Real (X_scaled))); -- slightly > Zero
Y_0 := Make_Extended (Log_X_approx_real);
-- STEP 3. Start the iteration. Calculate the number of iterations
-- required as follows. num correct digits doubles each iteration.
-- 1st iteration gives 4 digits, etc. Each step set desired precision
-- to one digit more than that we expect from the Iteration.
No_Correct_Bits := Real'Machine_Mantissa - 2;
loop
Y_0 := Y_0 + (X_scaled * Exp(-Y_0) - One);
No_Correct_Bits := No_Correct_Bits * 2;
exit when No_Correct_Bits >= Max_Available_Bits;
end loop;
--Result := Y_0 + Log_X_approx; -- for use with scaled version (Step 2)
Result := Y_0;
return Result;
end Log;
--------------------------
-- Log (arbitrary base) --
--------------------------
-- The exception E_Argument_Error is raised, signaling a parameter
-- value outside the domain of the corresponding mathematical function,
-- in the following cases:
-- by the Log function with specified base, when the value of the
-- parameter Base is zero, one, or negative;
--
-- The exception Constraint_Error is raised, signaling a pole of the
-- mathematical function (analogous to dividing by zero), in the following
-- cases, provided that Float_Type'Machine_Overflows is True:
-- by the Log, Cot, and Coth functions, when the value of the
-- parameter X is zero.
--
-- Struggling to remember: Z = Log(X, Base) implies X = Base**Z
-- or X = Exp (Log(Base)*Z) which implies Log(X) = Log(Base) * Z, so
-- Log(X, Base) = Z = Log(X) / Log(Base).
--
function Log (X : e_Real; Base : e_Real) return e_Real is
Result : e_Real;
begin
if Are_Equal (Base,Zero) then
raise E_Argument_Error;
end if;
if Base < Zero then
raise E_Argument_Error;
end if;
if Are_Equal (Base,One) then
raise E_Argument_Error;
end if;
if Are_Equal (Base,Two) then
Result := Two_Digit * (Log(X) * e_Half_Inverse_Log_2);
-- Divide by e_log_2. Multiply by 0.5/Log(2) not 1/log(2), because
-- 0.5/Log(2) is slightly less than 1, hence contains more correct
-- digits. (And multiplication is preferred for efficiency.)
else
Result := Log(X) / Log(Base);
end if;
return Result;
end Log;
----------
-- "**' --
----------
-- Say X**N = Exp (Log (X) * N).
--
-- Exponentiation by a zero exponent yields the value one.
-- Exponentiation by a unit exponent yields the value of the left
-- operand. Exponentiation of the value one yields the value one.
-- Exponentiation of the value zero yields the value zero.
-- The results of the Sqrt and Arccosh functions and that of the
-- exponentiation operator are nonnegative.
--
-- Argument_Error is raised by "**" operator, when the value of the left
-- operand is negative or when both operands have the value zero;
--
function "**" (Left : e_Real; Right : e_Real) return e_Real is
Result : e_Real;
begin
-- Errors:
if Left < Zero then
raise E_Argument_Error;
end if;
if Are_Equal (Left, Zero) and then Are_Equal (Right, Zero) then
raise E_Argument_Error;
end if;
-- Special Cases. We now know that they aren't both Zero:
if Are_Equal (Right, Zero) then -- Left is not Zero
return One;
end if;
if Are_Equal (Left, Zero) then -- Right is not Zero
return Zero;
end if;
if Are_Equal (Right, One) then
return Left;
end if;
if Are_Equal (Left, One) then -- Still OK if Right = Zero
return One;
end if;
-- Should we optimize for integer N?
Result := Exp (Log (Left) * Right);
return Result;
end "**";
---------
-- Exp --
---------
-- Sum Taylor series for Exp(X).
-- Actually, we sum series for Exp(X) - 1 - X, because scaling makes
-- X small, and Exp(X) - 1 - X has more correct digits for small X.
-- [get max arg size and test for it.]
--
function Exp
(X : e_Real)
return e_Real
is
Order : Real := 0.0;
Delta_Exponent : E_Integer := 0;
Next_Term, Sum : e_Real;
X_Scaled_2, X_scaled_1 : e_Real;
Total_Digits_To_Use : E_Integer;
N : Integer;
N_e_Real : e_Real;
J : constant Integer := 11;
Scale_Factor_2 : constant Integer := 2**J;
-- Must be power of 2 for function call to Make_E_Digit.
-- The optimal value increases with desired precision. But higher
-- order terms in the series are cheap, so it's not *too* important.
Inverse_Two_To_The_J : constant E_Digit
:= Make_E_Digit (1.0 / Real (Scale_Factor_2));
We_Flipped_The_Sign_Of_X_scaled : Boolean := False;
First_Stage_Scaling_Performed : Boolean := False;
Second_Stage_Scaling_Performed : Boolean := False;
begin
if Are_Equal (X, Zero) then
return One;
end if;
if Are_Equal (X, Positive_Infinity) then
raise E_Argument_Error;
end if;
if Are_Equal (X, Negative_Infinity) then
raise E_Argument_Error;
end if;
-- STEP 1. Reduce argument in 2 stages: 1st Remainder(X, Log(2)),
-- then divide by 2**J.
-- So X_Scaled = Remainder (X, Log_2), or approximately:
-- X_Scaled = X - Unbiased_Rounding (X / Log(2)) * Log(2) = X - N * Log(2)
-- Then Exp(X) = Exp(X_Scaled) * Exp(N*Log(2)) = Exp(X_Scaled) * 2**N.
--
-- Second stage of argument reduction: divide X_Scaled by 2**J:
-- Exp(X) = Exp(X_Scaled/2**J)**2**J * 2**N.
--
-- E_log_2 is calculated by recursively calling this routine, but
-- with an argument very near 0.0, so First stage scaling is not
-- performed. (It also calls with arg of approx. log(2) = 0.69, so
-- must not allow 1st stage scaling for args that small.)
N := 0;
X_Scaled_1 := X;
First_Stage_Scaling_Performed := False;
if Three_Quarters < Abs (X) then
N_e_Real := Unbiased_Rounding (Two_Digit * (X_Scaled_1 * E_Half_Inverse_Log_2));
X_Scaled_1 := Remainder (X_Scaled_1, E_Log_2);
-- Use X_Scaled_1 := X_Scaled_1 - N_e_Real * E_Log_2; ?
-- Not much faster. Somewhat less accurate. Seems OK for small args.
if Make_Extended (Real (Integer'Last)) < Abs (N_e_Real) then
raise E_Argument_Error with "Argument too large in Exp.";
end if;
N := Integer (Make_Real (N_e_Real));
First_Stage_Scaling_Performed := True;
end if;
-- STEP 1b. We want to get Exp() slightly less than one, to maximize
-- the precision of the calculation. So make sure arg is negative.
We_Flipped_The_Sign_Of_X_scaled := False;
if not (X_scaled_1 < Zero) then
We_Flipped_The_Sign_Of_X_scaled := True;
X_scaled_1 := -X_scaled_1;
end if;
-- STEP 2. 2nd stage of argument reduction. Divide X_scaled by 2**J.
-- Don't scale if arg is already small to avoid complications due
-- to underflow of arg to zero. Arg may already be 0. It's OK.
if Exponent (X_Scaled_1) >= -2 then -- it'll do, Zero OK here
X_Scaled_2 := Inverse_Two_To_The_J * X_Scaled_1;
Second_Stage_Scaling_Performed := True;
else
X_scaled_2 := X_scaled_1;
Second_Stage_Scaling_Performed := False;
end if;
-- STEP 3. Start the sum. Calculate Exp(X_Scaled) - (1 + X_Scaled),
-- because for small X_Scaled, this contains more correct digits than Exp.
-- Start summing the series at order 2 instead of order 0.
-- We have verified above that X_scaled /= Zero.
Order := 2.0;
Next_Term := Half_Digit * X_Scaled_2 * X_Scaled_2;
Sum := Next_Term;
loop
Order := Order + 1.0;
if Order = Radix then
raise E_Argument_Error with "Too many terms needed in Exp taylor sum.";
end if;
-- Use relative Exponents of Sum and Next_Term to check convergence
-- of the sum. Exponent doesn't work for args of 0, so check.
-- Abs (Next_Term) <= Abs (Sum), so we need only check Next_Term.
if Are_Equal (Next_Term, Zero) then exit; end if;
Delta_Exponent := Exponent (Sum) - Exponent (Next_Term);
Total_Digits_To_Use := e_Real_Machine_Mantissa - Delta_Exponent + 1;
exit when Total_Digits_To_Use <= 0;
Next_Term := (X_Scaled_2 * Next_Term) / Make_E_Digit (Order);
Sum := Sum + Next_Term;
-- Sum can overflow to infinity? Not with our scaled arguments.
end loop;
-- STEP 4. Undo effect of 2nd stage of argument scaling. Recall we
-- divided the arg by 2**J, and found Exp(X_Scaled/2**J). Now to get
-- Exp(X_Scaled), must take Exp(X_Scaled/2**J)**2**J, which means
-- repeated squaring of Exp(X_Scaled/2**J) (J times). It's more complicated
-- than that because we calculated G(X) = Exp(X) - 1 - X (since G contains
-- more correct digits than Exp, expecially for small X.) So we
-- use G(2X) = Exp(2X) - 1 - 2X = (G + (1 + X))*(G + (1 + X)) - 1 - 2X
-- = G*G + 2*G*(1+X) + X*X
-- G(2X) = (G(X)+X)**2 + 2G(X).
-- G(4X) = (G(2X)+2X)**2 + 2G(2X).
-- Repeat J times to unscale G. The following also returns X_scaled*2**J.
if Second_Stage_Scaling_Performed then
for I in 1..J loop
Sum := (Sum + X_scaled_2)**2 + Two_Digit * Sum;
X_Scaled_2 := Two_Digit * X_Scaled_2;
end loop;
end if;
-- DO the following whether or not Second_Stage or First_Stage
-- scaling was performed (because the series sum neglected the
-- the 1 and the X. If there were no extra guard digit for
-- subtraction ((X_scaled_1 + Sum) is negative) then it would be best
-- to use (0.5 + (Sum + Xscaled)) + 0.5. Following is OK though to
-- get a number slightly less than one with full precision.
-- Recover Exp = G(X) + 1 + X = Sum + 1 + X = (Sum + X_scaled) + 1:
Sum := (Sum + X_scaled_1) + One;
-- Second stage unscaling. We now have Y = Exp(-|X_scaled_1|), which is
-- slightly less than 1.0. Keep
-- in Y < 1.0 form as we unscale: might preserve more precision that
-- way, cause we lose much precision if invert a number that's slightly
-- less than one.
if First_Stage_Scaling_Performed then
if We_Flipped_The_Sign_Of_X_scaled then
Sum := Sum * Two**(-N);
else
Sum := Sum * Two**(N);
end if;
end if;
if We_Flipped_The_Sign_Of_X_scaled then
Sum := Reciprocal (Sum);
-- X_scaled was positive. We flipped its sign so must invert the result.
end if;
return Sum;
end Exp;
---------------------------
-- Sin (arbitrary cycle) --
---------------------------
-- The exception E_Argument_Error is raised, signaling a parameter
-- value outside the domain of the corresponding mathematical function,
-- in the following cases:
-- by any forward or inverse trigonometric function with specified
-- cycle, when the value of the parameter Cycle is zero or negative;
-- The results of the Sin, Cos, Tan, and Cot functions with
-- specified cycle are exact when the mathematical result is zero;
-- those of the first two are also exact when the mathematical
-- result is +/-1.0.
function Sin
(X : e_Real;
Cycle : e_Real)
return e_Real
is
Fraction_Of_Cycle, Result : e_Real;
begin
-- The input parameter X is units of Cycle. For example X = Cycle
-- is same as X = 2Pi, so could call Sin (2 * Pi * X / Cycle), but we
-- want to apply the remainder function here to directly meet certain
-- requirements on returning exact results.
-- Recall: Remainder = X - Round (X/Cycle) * Cycle = X - N * Cycle
-- which is in the range -Cycle/2 .. Cycle/2. The formula will be
--
-- Sin (X, Cycle) = Sin (2 * Pi * X / Cycle)
-- = Sin (2 * Pi * (X - N * Cycle) / Cycle)
-- = Sin (2 * Pi * Remainder(X,Cycle) / Cycle)
if Are_Equal (Cycle, Zero) then
raise E_Argument_Error;
end if;
if Cycle < Zero then
raise E_Argument_Error;
end if;
Fraction_Of_Cycle := Remainder (X, Cycle) / Cycle;
if Are_Equal (Fraction_Of_Cycle, Zero) then
return Zero;
end if;
if Are_Equal (Abs (Fraction_Of_Cycle), Half) then
return Zero;
end if;
if Are_Equal (Fraction_Of_Cycle, Make_Extended(0.25)) then
return One;
end if;
if Are_Equal (Fraction_Of_Cycle, Make_Extended(-0.25)) then
return -One;
end if;
Result := Sin (Make_E_Digit(8.0) * (e_Quarter_Pi * Fraction_Of_Cycle));
-- Pi/4 is used instead of Pi/2, because it contains more correct
-- binary digits.
return Result;
end Sin;
---------
-- Sin --
---------
-- Sum Taylor series for Sin (X).
--
-- Max argument is at present set by requirement:
-- Exponent(X) < Present_Precision-1
function Sin
(X : e_Real)
return e_Real
is
Half_Sqrt_Of_Radix : constant Real := 2.0**(Desired_No_Of_Bits_in_Radix/2-1);
Order : Real := 0.0;
Delta_Exponent : E_Integer := 0;
Next_Term, Sum : e_Real;
X_Scaled_1, X_Scaled_2, X_Scaled_2_Squared : e_Real;
Total_Digits_To_Use : E_Integer;
N_e_Real, Half_N : e_Real;
J : constant Integer := 8;
Three_To_The_J : constant E_Digit := Make_E_Digit (3.0**J);
Factorial_Part : E_Digit;
Sign_Of_Term_Is_Pos : Boolean := True;
Arg_Is_Negative : Boolean := False;
N_Is_Odd : Boolean := False;
First_Stage_Scaling_Performed : Boolean := False;
Second_Stage_Scaling_Performed : Boolean := False;
begin
if Are_Equal (X, Zero) then
return Zero;
end if;
if Are_Equal (X, Positive_Infinity) then
raise E_Argument_Error;
end if;
if Are_Equal (X, Negative_Infinity) then
raise E_Argument_Error;
end if;
Arg_Is_Negative := False;
if X < Zero then
Arg_Is_Negative := True;
end if;
if Exponent(X) >= e_Real_Machine_Mantissa-1 then
raise E_Argument_Error;
end if;
-- Can't figure out N below. N_e_Real has to be
-- integer valued: 0, 1, ... 2**(Radix*e_Real_Machine_Mantissa) - 1
-- This determines Max allowed Argument.
-- If Exponent(N_e_Real) is too large, then can't tell if N is even or odd.
-- STEP 1. First argument reduction: Get modulo Pi by Remainder(X, Pi).
-- Get X in range -Pi/2..Pi/2.
-- X_scaled_1 := X - N_e_Real * e_Pi;
if Less_Than_Half_Pi < Abs(X) then
X_scaled_1 := Remainder (Abs(X), e_Pi);
N_e_Real := Unbiased_Rounding ((Abs(X)-X_scaled_1) * e_Inverse_Pi);
First_Stage_Scaling_Performed := True;
else
X_Scaled_1 := Abs(X);
N_e_Real := Zero;
First_Stage_Scaling_Performed := False;
end if;
-- Need to know if N is even or odd. N is Positive.
-- If Exponent(N_e_Real) is too large, then we can't tell if N is even or
-- odd. So raise Arg error. This determines Max Arg.
N_Is_Odd := False;
if not Are_Equal (N_e_Real, Zero) then
Half_N := Half_Digit * N_e_Real;
if Truncation (Half_N) < Half_N then
N_Is_Odd := True;
end if;
end if;
-- STEP 2. Second stage of argument reduction. Divide by 3**5 = 243
-- to get Arg less than about 0.01?. Call this 3**J in what follows.
-- Later we recursively use J repetitions of the formula
-- Sin(3*Theta) = Sin(Theta)*(3 - 4*Sin(Theta)**2), to get Sin(Theta*3**J)
-- Cos(3*Theta) = -Cos(Theta)*(3 - 4*Cos(Theta)**2), to get Cos(Theta*3**J)
-- to get Sin (Original_Arg).
--
-- MUST avoid underflow to Zero in this step. So only if X_Scaled is big.
-- Actually, X_scaled = 0 may pass through, but it's OK to start out 0.
if Exponent (X_Scaled_1) >= -2 then -- it'll do
X_Scaled_2 := X_scaled_1 / Three_To_The_J;
Second_Stage_Scaling_Performed := True;
else
X_Scaled_2 := X_scaled_1;
Second_Stage_Scaling_Performed := False;
end if;
-- STEP 3. Start the sum. Terms are labeled Order = 1, 2, 3
-- but the series is X - X**3/3! + X**5/5! + ...+- X**(2*Order-1)/(2*Order-1)!.
-- Summed G(X) = Sin(X) - X, which contains more correct digits at
-- the end. We need these extra digits when we unscale the result.
X_Scaled_2_Squared := X_scaled_2 * X_Scaled_2;
Order := 2.0;
Sign_Of_Term_Is_Pos := False;
Next_Term := X_Scaled_2 * X_Scaled_2_Squared / Make_E_Digit (6.0);
Sum := -Next_Term;
-- Above we make the 1st term in G, and begin the sum.
loop
Sign_Of_Term_Is_Pos := not Sign_Of_Term_Is_Pos;
Order := Order + 1.0;
-- Can't make Factorial part if, roughly, 2*Order-1.0 > Radix-1,
-- Because max argument of Make_E_Digit is Radix-1.
if Order >= Radix / 2.0 then
raise E_Argument_Error with "Too many terms needed in Exp taylor sum.";
end if;
-- Use relative Eponents of Sum and Next_Term to check convergence
-- of the sum. Exponent doesn't work for args of 0, so check.
-- Abs (Next_Term) <= Abs (Sum), so we need only check Next_Term.
if Are_Equal (Next_Term, Zero) then exit; end if;
Delta_Exponent := Exponent (Sum) - Exponent (Next_Term);
Total_Digits_To_Use := e_Real_Machine_Mantissa - Delta_Exponent + 1;
exit when Total_Digits_To_Use <= 0;
if Order < Half_Sqrt_Of_Radix then
Factorial_Part := Make_E_Digit ((2.0*Order-1.0)*(2.0*Order-2.0));
Next_Term := (X_Scaled_2_Squared * Next_Term) / Factorial_Part;
else
Factorial_Part := Make_E_Digit ((2.0*Order-1.0));
Next_Term := (X_Scaled_2_Squared * Next_Term) / Factorial_Part;
Factorial_Part := Make_E_Digit ((2.0*Order-2.0));
Next_Term := Next_Term / Factorial_Part;
end if;
if Sign_Of_Term_Is_Pos then
Sum := Sum + Next_Term;
else
Sum := Sum - Next_Term;
end if;
end loop;
-- STEP 4. Scale the result iteratively. Recall we divided the arg by 3**J,
-- so we recursively use J repetitions of the formula
-- Sin(3*X) = Sin(X)*(3 - 4*Sin(X)**2), to get Sin(X*3**J).
-- Actually, we summed G(X) = Sin(X) - X. So the formula for G(X) is
-- G(3X) = S(3X) - 3X = S(X)*(3 - 4S(X)**2) - 3X,
-- = (G+X)*(3 - 4(G+X)**2) - 3X,
-- = 3G - 4(G+X)**3, (Cancel out the 3X),
-- G(3X) = 3G(X) - 4(G(X)+X)**3.
-- G(9X) = 3G(3X) - 4(G(3X)+3X)**3, etc.
-- Still requires only 2 (full) mults per loop, just like the original formula.
-- Notice below that we output X_scaled * 3**J, which is required next step.
if Second_Stage_Scaling_Performed then
for I in 1..J loop
Sum := Three_Digit * Sum - Four_Digit * (Sum + X_scaled_2)**3;
X_scaled_2 := Three_Digit * X_scaled_2;
end loop;
end if;
-- STEP 5. We have Sin(X - N * Pi). Want Sin(X). If N is odd, then
-- flip sign of Sum. Next, flip sign again if the
-- original argument is neg: Arg_Is_Negative = True.
-- Remember, we summed for Sum = G = Sin - X, whether or not scaling
-- was performed. (X is called X_scaled, no matter what.)
-- So we recover Sin = G + X
Sum := Sum + X_scaled_1;
if First_Stage_Scaling_Performed then
if N_Is_Odd then
Sum := -Sum;
end if;
end if;
if Arg_Is_Negative then
Sum := -Sum;
end if;
return Sum;
end Sin;
---------------------------
-- Cos (arbitrary cycle) --
---------------------------
-- The exception E_Argument_Error is raised, signaling a parameter
-- value outside the domain of the corresponding mathematical function,
-- in the following cases:
-- by any forward or inverse trigonometric function with specified
-- cycle, when the value of the parameter Cycle is zero or negative;
-- The results of the Sin, Cos, Tan, and Cot functions with
-- specified cycle are exact when the mathematical result is zero;
-- those of the first two are also exact when the mathematical
-- result is +/-1.0.
--
function Cos (X : e_Real; Cycle : e_Real) return e_Real is
Fraction_Of_Cycle, Result : e_Real;
begin
-- The input parameter X is units of Cycle. For example X = Cycle
-- is same as X = 2Pi, so could use Cos (2 * Pi * X / Cycle), but we
-- want to apply the remainder function here to directly meet certain
-- requirements on returning exact results.
-- Recall: Remainder = X - Round (X/Cycle) * Cycle = X - N * Cycle
-- which is in the range -Cycle/2 .. Cycle/2. The formula will be
--
-- Cos (X, Cycle) = Cos (2 * Pi * X / Cycle)
-- = Cos (2 * Pi * (X - N * Cycle) / Cycle)
-- = Cos (2 * Pi * Remainder(X,Cycle) / Cycle)
if Are_Equal (Cycle, Zero) then
raise E_Argument_Error;
end if;
if Cycle < Zero then
raise E_Argument_Error;
end if;
-- Now get twice the fraction of the cycle, and handle special cases:
Fraction_Of_Cycle := Remainder (X, Cycle) / Cycle;
if Are_Equal (Fraction_Of_Cycle, Zero) then
return One;
end if;
if Are_Equal (Abs (Fraction_Of_Cycle), Half) then
return -One;
end if;
if Are_Equal (Abs (Fraction_Of_Cycle), Make_Extended(0.25)) then
return Zero;
end if;
Result := Cos (Make_E_Digit(8.0) * (e_Quarter_Pi * Fraction_Of_Cycle));
-- Use Pi/4 becase it contains more correct binary digits than Pi.
return Result;
end Cos;
---------
-- Cos --
---------
-- Sum Taylor series for Cos (X). Actually sum series for G = Cos(X) - 1.
-- Reason is, G contains more correct digits than Cos, which is
-- required when we undo effects of argument reduction.
-- Max argument is at present
-- set by requirement: Exponent(X) < Present_Precision-1
--
function Cos
(X : e_Real)
return e_Real
is
Half_Sqrt_Of_Radix : constant Real := 2.0**(Desired_No_Of_Bits_in_Radix/2-1);
Order : Real := 0.0;
Delta_Exponent : E_Integer := 0;
Next_Term, Sum, Sum_2, Sum_3 : e_Real;
X_Scaled_1, X_Scaled_Squared : e_Real;
Total_Digits_To_Use : E_Integer;
N_e_Real, Half_N : e_Real;
J : constant Integer := 8;
Three_To_The_J : constant E_Digit := Make_E_Digit (3.0**J);
Factorial_Part : E_Digit;
Sign_Of_Term_Is_Pos : Boolean := True;
N_Is_Odd : Boolean := False;
First_Stage_Scaling_Performed : Boolean := False;
Second_Stage_Scaling_Performed : Boolean := False;
begin
if Are_Equal (X, Zero) then
return One;
end if;
if Are_Equal (X, Positive_Infinity) then
raise E_Argument_Error;
end if;
if Are_Equal (X, Negative_Infinity) then
raise E_Argument_Error;
end if;
if Exponent(X) >= e_Real_Machine_Mantissa-1 then
raise E_Argument_Error;
end if;
-- Can't figure out N below. N_e_Real has to be
-- integer valued: 0, 1, ... 2**(Radix*e_Real_Machine_Mantissa) - 1
-- This determines Max allowed Argument.
-- STEP 1. First stage argument reduction.
-- Take X modulo Pi by Remainder(X, Pi). Get X in range -Pi/2..Pi/2.
-- X_scaled_1 := X - N_e_Real * e_Pi;
if Less_Than_Half_Pi < Abs(X) then
X_scaled_1 := Remainder (Abs(X), e_Pi);
N_e_Real := Unbiased_Rounding ((Abs(X)-X_scaled_1) * e_Inverse_Pi);
First_Stage_Scaling_Performed := True;
else
X_Scaled_1 := Abs(X);
N_e_Real := Zero;
First_Stage_Scaling_Performed := False;
end if;
-- Need to know if N is even or odd. N is Positive.
N_Is_Odd := False;
if not Are_Equal (N_e_Real, Zero) then
Half_N := Half_Digit * N_e_Real;
if Truncation (Half_N) < Half_N then
N_Is_Odd := True;
end if;
end if;
-- STEP 1b. If X_Scaled is nearing Pi/2 then it's too big for Taylor's.
-- Must call Sin (Pi/2 - X_Scaled). IMPORTANT: only do this for
-- X_scaled > Pi/6, because Arcsin(X => 0.5) = Pi/6 is used to calculate
-- Pi, and would get infinite recursive calls when Arcsin calls Cos
-- which calls Sin, while Sin and Cos call e_Quarter_Pi, which
-- calls Arcsin. e_Quarter_Pi is used instead of the less accurate Pi/2.
if One < X_Scaled_1 then
Sum := Sin ((e_Quarter_Pi - X_Scaled_1) + e_Quarter_Pi);
if N_Is_Odd then
Sum := -Sum;
end if;
return Sum;
end if;
-- STEP 2. Second stage of argument reduction. Divide by 3**8 = 81*81
-- to get argument less than about .02. Call this 3**J in what follows.
-- Later we recursively use J repetitions of the formula
-- Sin(3*Theta) = Sin(Theta)*(3 - 4*Sin(Theta)**2), to get Sin(Theta*3**J)
-- Cos(3*Theta) = -Cos(Theta)*(3 - 4*Cos(Theta)**2), to get Cos(Theta*3**J).
--
-- It's OK if X_scaled is 0 at this point, but not if the following
-- forces it to underflow to 0. Therefore only scale large args:
if Exponent (X_Scaled_1) >= -2 then -- it'll do
X_Scaled_1 := X_scaled_1 / Three_To_The_J;
Second_Stage_Scaling_Performed := True;
else
Second_Stage_Scaling_Performed := False;
end if;
-- STEP 3. Start the sum. Terms are labeled Order = 0, 1, 2, 3
-- but the series is 1 - X**2/2! + X**4/4! + ...+- X**(2*Order)/(2*Order)!.
-- Below we actually calculate Cos(X) - 1.
-- Start summing the series at order 1 instead of order 0.
Order := 1.0;
X_Scaled_Squared := X_scaled_1 * X_Scaled_1;
Next_Term := Half_Digit * X_Scaled_Squared;
Sum := -Next_Term;
Sign_Of_Term_Is_Pos := False;
loop
Sign_Of_Term_Is_Pos := not Sign_Of_Term_Is_Pos;
Order := Order + 1.0;
-- Can't make Factorial part if, roughly, 2*Order > Radix-1.
if Order >= (Radix-1.0) / 2.0 then
raise E_Argument_Error with "Too many terms needed in Exp taylor sum.";
end if;
-- Use relative Eponents of Sum and Next_Term to check convergence
-- of the sum. Exponent doesn't work for args of 0, so check.
-- Abs (Next_Term) <= Abs (Sum), so we need only check Next_Term.
-- If Next_Term is 0, we are finished anyway.
if Are_Equal (Next_Term, Zero) then exit; end if;
Delta_Exponent := Exponent (Sum) - Exponent (Next_Term);
Total_Digits_To_Use := e_Real_Machine_Mantissa - Delta_Exponent + 1;
exit when Total_Digits_To_Use <= 0;
if Order < Half_Sqrt_Of_Radix then
Factorial_Part := Make_E_Digit ((2.0*Order)*(2.0*Order-1.0));
Next_Term := (X_Scaled_Squared * Next_Term) / Factorial_Part;
else -- Do it the slow way. (Should rarely happen.)
Factorial_Part := Make_E_Digit (2.0*Order);
Next_Term := (X_Scaled_Squared * Next_Term) / Factorial_Part;
Factorial_Part := Make_E_Digit (2.0*Order-1.0);
Next_Term := Next_Term / Factorial_Part;
end if;
if Sign_Of_Term_Is_Pos then
Sum := Sum + Next_Term;
else
Sum := Sum - Next_Term;
end if;
end loop;
-- STEP 4. Scale the result iteratively. Recall we got Cos(Arg/3**J). Now
-- we want Cos(Arg). So we use J repetitions of the formula
-- Cos(3*Theta) = -Cos(Theta)*(3 - 4*Cos(Theta)**2), to get Cos(Theta*3**J).
-- Recall we summed for Cos(X) - 1, because we retain more correct digits
-- this way for small X. (The 1 would have shifted correct digits off the
-- array.) So we actually have is Sum = G(X) = Cos(X) - 1. So the formula
-- for Cos(3X) is (1+G)*(4(G+1)**2 - 3) = (1+G)*(1 + 8G + 4G**2). Then
-- G(3X) = Cos(3X) - 1 = 9G + 12G*2 + 4G**3. Next, unscale G:
if Second_Stage_Scaling_Performed then
for I in 1..J loop
--Sum := Sum * (Four_Digit * Sum * Sum - Three);
Sum_2 := Sum*Sum;
Sum_3 := Sum*Sum_2;
Sum := Nine_Digit * Sum + Twelve_Digit * Sum_2 + Four_Digit * Sum_3;
end loop;
end if;
-- STEP 5. We have Cos(X - N * Pi). Want Cos(X). If N is odd, then
-- flip sign of Sum. First remember we summed for G = Cos - 1, whether or
-- not scaling was performed. Must recover Cos next:
Sum := Sum + One; -- Get Cos(X) = G(X) + 1 = Sum + 1.
if First_Stage_Scaling_Performed then
if N_Is_Odd then
Sum := -Sum;
end if;
end if;
return Sum;
end Cos;
-------------------------
-- Reciprocal_Nth_Root --
-------------------------
-- Uses Newton's method to get A**(-1/N):
-- Y_k+1 = Y_k + (1 - A * Y_k**N) * Y_k / N.
-- Requires call to log(A) and assumes that this call gets
-- the first two radix digits correct: 48 bits usually. (It almost
-- always gets more correct.)
-- REMEMBER, this calculates to the max possible precision;
-- Does not reflect dynamic precision floating point.
-- N must be less than Radix - 1, which is usually 2**24 - 1.
function Reciprocal_Nth_Root
(X : e_Real;
N : Positive)
return e_Real is
Exponent_Of_X, Scaled_Exp_Of_X, Exp_Mod_N : E_Integer;
Result, X_Fraction, Scaled_X_Fraction, Y_0 : e_Real;
Shift_Sign, Ratio : Real := 0.0;
Log_Of_Scaled_X_Fraction, Real_X_Fraction : Real := 0.0;
No_Correct_Bits : E_Integer;
E_Digit_N, Inverse_E_Digit_N : E_Digit; -- already initialized
Optimization_Is_Possible : Boolean := False;
begin
if Are_Equal (X, Zero) then
raise E_Argument_Error;
end if;
if Are_Equal (X, Positive_Infinity) then
raise E_Argument_Error;
end if;
if Are_Equal (X, Negative_Infinity) then
raise E_Argument_Error;
end if;
if Real(N) > (Radix-1.0) then
raise E_Argument_Error;
end if;
-- STEP 0b. An optimization. If N is a power of two, we can speed
-- up the calculation by multiplying by 1/N rather than dividing by
-- N in the newton iteration.
Optimization_Is_Possible := False;
for I in 0..Desired_No_Of_Bits_In_Radix-2 loop
if 2**I = N then
Optimization_Is_Possible := True;
end if;
end loop;
if Optimization_Is_Possible then
Inverse_E_Digit_N := Make_E_Digit (1.0 / Real(N));
else
E_Digit_N := Make_E_Digit (Real(N));
end if;
-- STEP 1. Argument reduction. Break X into Fraction and Exponent.
-- Choose to decrement Abs(Exponent) by (Exponent MOD N),
-- and multiply fraction by Radix ** (Exponent MOD N).
-- The reason is of course, we want to divide decremented Exponent by N,
-- so we want Scaled_Exp_Of_X to be an integral multiple of -N.
Exponent_Of_X := Exponent (X); -- What if X is 0, inf, etc???
X_Fraction := Fraction (X);
Exp_Mod_N := Abs (Exponent_Of_X) MOD E_Integer(N); -- N never < 1.
-- Make sure that Scaled_Exp_Of_X is in range of e_Real, and also
-- make sure that it is scaled to an integral multiple of N.
if Exponent_Of_X < 0 then
Scaled_Exp_Of_X := Exponent_Of_X + Exp_Mod_N;
Shift_Sign := +1.0;
else
Scaled_Exp_Of_X := Exponent_Of_X - Exp_Mod_N;
Shift_Sign := -1.0;
end if;
-- Scale the fraction to compensate for the above shift in the Exponent:
if Exponent_Of_X < 0 then
Scaled_X_Fraction := Scaling (X_Fraction, - Exp_Mod_N);
else
Scaled_X_Fraction := Scaling (X_Fraction, + Exp_Mod_N);
end if;
-- STEP 2. Get starting value for Newton's iteration.
-- Want Real number estimate of Scaled_X_Fraction**(-1/N).
-- Get the first 2 radix digits correct (48 bits usually), and call it Y_0.
-- Must worry about exponents too large for type Real in the value
-- Scaled_X_Fraction prior to the **(-1/N) operation, so we do it indirectly.
-- Arg ** (-1/N): use exp (log (Arg**(-1/N))) = exp ( (-1/N)*log (Arg) ).
-- Need estimate: [ X_Fraction * Radix**(-Shift_Sign * Exp_Mod_N) ]**(-1/N).
-- First want natural Log(X_Fraction * Radix**(-Shift_Sign * Exp_Mod_N))
-- which equals Log(X_Fraction) - Shift_Sign * Log(Radix) * Exp_Mod_N.
-- Next divide this quantity by -N, and take exp():
-- Exp (-Log (X_Fraction) / N + Shift_Sign * Log(Radix) * Exp_Mod_N / N).
-- This is the estimate we want, and because Exp_Mod_N / N is always
-- < 1.0, the arguments should be well within range of Log and Exp,
-- because Exp (Shift_Sign * Log(Radix) * Exp_Mod_N / N) is less than Radix.
Real_X_Fraction := Make_Real (X_Fraction);
Ratio := Real (Exp_Mod_N) / Real(N);
Log_Of_Scaled_X_Fraction
:= -Log (Real_X_Fraction) / Real(N) + Shift_Sign * Ratio * Log (Radix);
Y_0 := Make_Extended (Exp (Log_Of_Scaled_X_Fraction));
-- Starting val in Newton's iteration.
-- STEP 3. Start the iteration. Calculate the number of iterations
-- required as follows. num correct digits doubles each iteration.
-- 1st iteration gives 4 digits, etc. Each step set desired precision
-- to one digit more than that we expect from the Iteration.
--
-- It is important to remember that e_Real_Machine_Mantissa includes
-- the 1 or 2 guard digits. The last of these may have a lot of error in
-- the end, the first of these may have some error. That's why they're
-- there. Also remember that when Set_No_Of_Digits_To_Use is
-- called, the precision it sets includes the 2 guard digits, both
-- of which may be wrong, so we add 2 to the setting below, just
-- in case.
No_Correct_Bits := Real'Machine_Mantissa - 2;
loop
if Optimization_Is_Possible then -- multiply by inverse of N:
Y_0 := Y_0 + Inverse_E_Digit_N * ((One - Scaled_X_Fraction * Y_0**N) * Y_0);
else -- divide by N:
Y_0 := Y_0 + (One - Scaled_X_Fraction * Y_0**N) * Y_0 / E_Digit_N;
end if;
No_Correct_Bits := No_Correct_Bits * 2;
exit when No_Correct_Bits > Max_Available_Bits;
end loop;
Result := Scaling (Y_0, (-Scaled_Exp_Of_X) / E_Integer (N));
-- Product of Y_0 = Scaled_X_Fraction**(-1/N) with
-- Radix**(-Scaled_Exponent(X) / N) equals X**(-1/N).
return Result;
end Reciprocal_Nth_Root;
------------
-- Divide --
------------
-- Uses Newton's method: Y_k+1 = Y_k + (1 - A*Y_k) * Y_k to get Z / A.
-- Requires call to 1 / Make_Real(A).
function Divide (Z, X : e_Real)
return e_Real
is
Exponent_Of_X : E_Integer;
Result, X_Fraction, Y_0 : e_Real;
No_Correct_Bits : E_Integer;
begin
if Are_Equal (X, Zero) then
raise E_Argument_Error;
end if;
if Are_Equal (X, Positive_Infinity) then -- like underflow
return Zero;
end if;
if Are_Equal (X, Negative_Infinity) then -- like underflow
return Zero;
end if;
-- Argument reduction. Break X into Fraction and Exponent.
-- Iterate to get inverse of fraction. Negate to get inverse of Exp.
Exponent_Of_X := Exponent (X);
X_Fraction := Fraction (X);
-- Get the first 2 radix digits correct (48 bits usually). Remember that the
-- Newton's iteration here produces 1/(X_Fraction). The result will be
-- the product of the newton's iteration and Radix to the power Exp_Scale_Val.
Y_0 := Make_Extended (1.0 / Make_Real (X_Fraction));
-- Starting val in Newton's iteration.
No_Correct_Bits := Real'Machine_Mantissa - 2;
-- Iterate:
loop
--Y_0:= Y_0 *(Two_Digit + (-X_Fraction) * Y_0); -- faster, much less accurate
Mult (Y_0, (Two - X_Fraction * Y_0)); -- faster, much less accurate
No_Correct_Bits := No_Correct_Bits * 2;
exit when No_Correct_Bits >= Max_Available_Bits / 2 + 1;
-- final correction is outside the loop.
end loop;
Result := Z * Y_0; -- Z / X
Result := Result + (Z - X_Fraction * Result) * Y_0; --bst so far
-- Y_0 := Y_0 + (One - X_Fraction * Y_0) * Y_0;
-- The iteration for Y_0 is the final step for 1/X. Multiplied by Z to get Result.
Result := Scaling (Result, -Exponent_Of_X);
-- Product of 1/Fraction(X) with Radix**(-Exponent(X)) equals 1/X.
return Result;
end Divide;
----------------
-- Reciprocal --
----------------
-- Uses Newton's method: Y_k+1 = Y_k + (1 - A*Y_k) * Y_k to get 1 / A.
function Reciprocal (X : e_Real)
return e_Real
is
Exponent_Of_X : E_Integer;
Result, X_Fraction, Y_0 : e_Real;
No_Correct_Bits : E_Integer;
begin
if Are_Equal (X, Zero) then
raise E_Argument_Error;
end if;
if Are_Equal (X, Positive_Infinity) then -- like underflow
return Zero;
end if;
if Are_Equal (X, Negative_Infinity) then -- like underflow
return Zero;
end if;
-- Argument reduction. Break X into Fraction and Exponent.
-- Iterate to get inverse of fraction. Negate to get inverse of Exp.
Exponent_Of_X := Exponent (X);
X_Fraction := Fraction (X);
-- Newton's iteration here produces 1/(X_Fraction). Final result will be
-- the product of the newton's iteration and Radix to the power Exp_Scale_Val.
Y_0 := Make_Extended (1.0 / Make_Real (X_Fraction));
-- Starting val in Newton's iteration.
No_Correct_Bits := Real'Machine_Mantissa - 2;
-- Iterate:
loop
--Y_0:= Y_0 *(Two_Digit + (-X_Fraction) * Y_0); -- faster, much less accurate
Mult (Y_0, (Two - X_Fraction * Y_0)); -- faster, much less accurate
No_Correct_Bits := No_Correct_Bits * 2;
exit when No_Correct_Bits > Max_Available_Bits / 2 + 1;
-- final correction is below.
end loop;
Y_0 := Y_0 + (One - X_Fraction * Y_0) * Y_0; -- accurate final step.
Result := Scaling (Y_0, -Exponent_Of_X);
-- Product of 1/Fraction(X) with Radix**(-Exponent(X)) equals 1/X.
return Result;
end Reciprocal;
---------------------
-- Reciprocal_Sqrt --
---------------------
-- Uses Newton's method: Y_k+1 = Y_k + (1 - A*Y_k**2) * Y_k / 2
-- to get 1 / sqrt(A). Multiply by A to get desired result; then refine.
function Reciprocal_Sqrt (X : e_Real)
return e_Real
is
Result : e_Real;
X_scaled, Y_0 : e_Real;
Exp_Scale_Val : E_Integer;
No_Correct_Bits : E_Integer;
begin
if X < Zero then
raise E_Argument_Error;
end if;
if Are_Equal (X, Positive_Infinity) then
raise E_Argument_Error;
end if;
if Are_Equal (X, Negative_Infinity) then
raise E_Argument_Error;
end if;
if Are_Equal (X, Zero) then
raise E_Argument_Error;
end if;
-- Break X into Fraction and Exponent. If Exponent is
-- odd then add or subtract 1. (Increase X if X < 1, decrease otherwise.)
-- Only important thing is scale X
-- down to somewhere near 1, and to scale X by an even power of Radix.
-- We break X up because the Newton's method works better on X_scaled than
-- than on X in general. Also we use Sqrt(Make_Real(X_scaled)) to start
-- things off for Newton's method, so we want X_scaled in range of Sqrt(Real).
Exp_Scale_Val := Exponent (X); -- what if X is 0, inf, etc..???
-- Exp is odd. Make it even, but keep things in range of e_Real:
if Abs (Exp_Scale_Val) mod 2 /= 0 then
if Exp_Scale_Val < 0 then
Exp_Scale_Val := Exp_Scale_Val + 1;
else
Exp_Scale_Val := Exp_Scale_Val - 1;
end if;
end if;
X_scaled := Scaling (X, -Exp_Scale_Val);
-- Take Sqrt by dividing the even Exp_Scale_Val by 2, and by taking
-- the SQRT of X_scaled. Start the iteration off with a call to SQRT
-- in the standard library for type Real.
Exp_Scale_Val := Exp_Scale_Val / 2;
Y_0 := Make_Extended (Sqrt (1.0 / Make_Real (X_scaled)));
-- Starting val in Newton's iteration.
No_Correct_Bits := Real'Machine_Mantissa - 2;
loop
--Y_0:= Y_0 + Half_Digit * ((One - X_scaled * (Y_0 * Y_0)) * Y_0);
--Y_0:= Y_0*(Half_Digit * (Three - X_scaled * (Y_0 * Y_0))); --inaccurate
Mult (Y_0, Half_Digit * (Three - X_scaled * (Y_0 * Y_0)));
No_Correct_Bits := No_Correct_Bits * 2;
exit when No_Correct_Bits > Max_Available_Bits / 2 + 1;
-- final correction is below.
end loop;
-- both work:
--Y_0 := Y_0 + Half_Digit * ((One - X_scaled * (Y_0 * Y_0)) * Y_0);
Y_0 := Y_0 - Half_Digit * (X_scaled * (Y_0 * Y_0) - One) * Y_0;
Result := Scaling (Y_0, -Exp_Scale_Val);
return Result;
end Reciprocal_Sqrt;
----------
-- Sqrt --
----------
-- Uses Newton's method: Y_k+1 = Y_k + (1 - A*Y_k**2) * Y_k / 2
-- to get 1 / sqrt(A). Multiply by A to get desired result; then refine.
-- Requires call to Sqrt(Real) and assumes that this call gets
-- the first radix digit correct. (It almost
-- always gets 53 bits correct.)
function Sqrt (X : e_Real)
return e_Real
is
Result, X_scaled, Y_0 : e_Real;
Exp_Scale_Val : E_Integer;
No_Correct_Bits : E_Integer;
begin
if X < Zero then
raise E_Argument_Error;
end if;
if Are_Equal (X, Positive_Infinity) then
raise E_Argument_Error;
end if;
if Are_Equal (X, Negative_Infinity) then
raise E_Argument_Error;
end if;
if Are_Equal (X, Zero) then
return Zero;
end if;
--if Are_Equal (X, One) then -- Ada9X.
--return One;
--end if;
-- Break X into Fraction and Exponent. If Exponent is
-- odd then add or subtract 1. (Increase X if X < 1, decrease otherwise.)
-- Only important thing is scale X
-- down to somewhere near 1, and to scale X by an even power of Radix.
-- We break X up because the Newton's method works better on X_scaled than
-- than on X in general. Also we use Sqrt(Make_Real(X_scaled)) to start
-- things off for Newton's method, so we want X_scaled in range of Sqrt(Real).
Exp_Scale_Val := Exponent (X); -- what if X is 0, inf, etc..???
-- This Exp is powers of Radix = 2**30 or 2**29.
-- Exp is odd. Make it even, but keep things in range of e_Real:
if Abs (Exp_Scale_Val) mod 2 /= 0 then
if Exp_Scale_Val < 0 then
Exp_Scale_Val := Exp_Scale_Val + 1;
else
Exp_Scale_Val := Exp_Scale_Val - 1;
end if;
end if;
X_scaled := Scaling (X, -Exp_Scale_Val);
Exp_Scale_Val := Exp_Scale_Val / 2;
Y_0 := Make_Extended (Sqrt (1.0 / Make_Real (X_scaled)));
-- Starting val in Newton's iteration.
No_Correct_Bits := Real'Machine_Mantissa - 2;
loop
--Y_0:= Y_0 + Half_Digit * ((One - X_scaled * Y_0 * Y_0) * Y_0);
--Y_0:= Y_0*(Half_Digit * (Three - X_scaled * Y_0 * Y_0)); --inaccurate
Mult (Y_0, Half_Digit * (Three - X_scaled * Y_0 * Y_0));
No_Correct_Bits := No_Correct_Bits * 2;
exit when No_Correct_Bits > Max_Available_Bits / 2 + 1;
-- Have the final correction outside the loop.
end loop;
Result := Y_0 * X_scaled; -- now it's SQRT(X_scaled); Y_0 = 1/SQRT(X_scaled)
Result := Result + Half_Digit * (X_scaled - Result*Result) * Y_0; --important
Result := Scaling (Result, Exp_Scale_Val); -- equals SQRT(X).
return Result;
end Sqrt;
-------------
-- Make_Pi --
-------------
-- This is an important independent test of Arcsin (hence Sin and Arcos).
-- Once we verify that Arcsin (hence Sin) is correct, can test other
-- arguments with (eg) Sin (A + B) = etc.
-- Has much greater error than 4*Arcsin(1/Sqrt(2)).
-- Need Pi to full precision for the trigonometic functions.
-- Here is the Salamin-Brent algorithm.
-- A_0 = 1.0, B_0 = 1.0/Sqrt(2.0), and D_0 = Sqrt(2.0) - 0.5.
--
-- A_k = (A_{k-1} + B_{k-1}) / 2
-- B_k = Sqrt (A_{k-1} * B_{k-1})
-- D_k = D_{k-1} - 2**k * (A_k - B_k)**2
--
-- Then P_k = (A_k + B_k)**2 / D_k converges quadratically to
-- Pi. All steps must be done at full precision.
--
-- function Make_Pi return e_Real is
-- A_0, B_0, D_0 : e_Real;
-- A_1, B_1, D_1 : e_Real;
-- C, Result : e_Real;
-- Two_To_The_k : E_Digit;
-- Two_To_The_20 : constant E_Digit := Make_E_Digit (2.0**20);
-- We_Are_Finished : Boolean := False;
-- No_Of_Correct_Digits : E_Integer;
-- Old_Precision : constant E_Integer := Present_Precision;
-- begin
--
-- A_0 := One;
-- B_0 := E_Inverse_Sqrt_2;
-- D_0 := Two * E_Inverse_Sqrt_2 - Half;
-- -- this give Pi_0 = 3.1877, or error of about 1.47 %. This is smaller
-- -- 1 part in 64, so 6 bits correct. There follows (k=1) 12, (k=2) 24.
-- -- So requires two more iterations to get one digit, 3 to get 2
-- -- digits. Seems to work better than this estimate.
--
-- No_Of_Correct_Digits := 1;
--
-- -- The following loop should get us up to half a million digits. In
-- -- the unlikely case you need more, then another loop follows.
-- -- k in 1..7 gives you 33 Radix 2**24 digits.
--
-- for k in 1..20 loop
--
-- Two_To_The_k := Make_E_Digit (2.0**k);
--
-- A_1 := Half_Digit * (A_0 + B_0);
-- B_1 := Sqrt (A_0 * B_0);
-- C := (A_1 - B_1);
-- D_1 := D_0 - Two_To_The_k * (C * C);
--
-- if k >= 3 then
-- -- We did 3rd iteration to get 2 correct digits.
-- -- No_Correct.. was initialized to 1.
-- No_Of_Correct_Digits := No_Of_Correct_Digits * 2;
-- end if;
-- -- Should be OK overflow-wise here. Range of E_Integer is 4 times
-- -- the limit set by Max_Available_Precision.
--
-- if No_Of_Correct_Digits > e_Real_Machine_Mantissa then
-- We_Are_Finished := True;
-- exit;
-- end if;
--
-- A_0 := A_1; B_0 := B_1; D_0 := D_1;
--
--
-- end loop;
--
-- -- We want to optimize the calculation of D_1 above by multiplying
-- -- by an E_Digit on the left (Two_To_The_k) instead of an e_Real.
-- -- Stop doing this at Two_To_The_k = 2**20 to stay in range of E_Digit.
-- -- Below we finish up if necessary by multiplying twice..still much
-- -- more efficient than e_Real*e_Real.
--
-- if not We_Are_Finished then -- keep trying
-- for k in 21..40 loop
--
-- Two_To_The_k := Make_E_Digit (2.0**(k-20));
--
-- A_1 := Half_Digit * (A_0 + B_0);
-- B_1 := Sqrt (A_0 * B_0);
-- C := (A_1 - B_1);
-- D_1 := D_0 - Two_To_The_k * (Two_To_The_20 * (C * C));
--
-- No_Of_Correct_Digits := No_Of_Correct_Digits * 2;
-- exit when No_Of_Correct_Digits > e_Real_Machine_Mantissa;
--
-- A_0 := A_1; B_0 := B_1; D_0 := D_1;
--
-- end loop;
-- end if;
--
-- C := (A_1 + B_1);
-- Result := C * C / D_1;
--
-- Set_No_Of_Digits_To_Use (Old_Precision); -- Restore precision.
--
-- return Result;
--
-- end Make_Pi;
----------------
-- Make_Log_2 --
----------------
-- Important independent test of Log(X). Verify that Log(X) is correct
-- at X = 2, and use (eg) Log(XY) = Log(X) + Log(Y) to test other vals.
-- This is for testing other routines: Has greater error than Log(X).
-- Log_2, hopefully, for testing purposes.
-- A_0 = 1.0, B_0 = Two**(2-M);
--
-- A_k = (A_{k-1} + B_{k-1}) / 2
-- B_k = Sqrt (A_{k-1} * B_{k-1})
--
-- Then Log(2) = Pi / (2 * B_k * m) ???
--
-- Here M = N/2+1 where N = 29*e_Real_Machine_Mantissa = number of bits desired.
--
-- function Make_Log_2 return e_Real is
-- A_0, B_0 : e_Real;
-- A_1, B_1 : e_Real;
-- Result : e_Real;
-- We_Are_Finished : Boolean := False;
-- No_Of_Correct_Digits : E_Integer;
-- N : Integer := 24 * Integer(e_Real_Machine_Mantissa); -- Upper estimate.
-- M : Integer := N/2 + 24; -- Need only N/2 + 1
-- begin
--
-- A_0 := One;
-- B_0 := Two**(2-M); -- clean this up with the scaling ftcn.
--
-- No_Of_Correct_Digits := 1;
--
-- -- The following loop should get us up to half a million digits. In
-- -- the unlikely case you need more, then another loop follows.
--
-- for k in 1..16 loop -- I suspect far fewer than 20 iterations required.
--
-- A_1 := Half_Digit * (A_0 + B_0);
-- B_1 := Sqrt (A_0 * B_0);
--
-- A_0 := A_1; B_0 := B_1;
--
-- end loop;
--
-- Result := Half_Digit * e_Pi / (B_1 * Make_Extended(Real(M)));
--
-- Set_No_Of_Digits_To_Use (Old_Precision); -- Restore precision.
--
-- return Result;
--
-- end Make_Log_2;
----------
-- e_Pi --
----------
-- Returns Pi to Max Available Precision. Use Arcsin, cause it has
-- much lower error than Make_Pi.
-- Used for scaling trig functions, etc.
function e_Pi return e_Real is
begin
if not Pi_memory.Initialized then
--Pi_memory.Val := Make_Pi;
Pi_memory.Val := Four_Digit * e_Quarter_Pi;
-- Only works because arg is so small no scaling by E_pi is done.
Pi_memory.Initialized := True;
end if;
return Pi_memory.Val;
end e_Pi;
------------------
-- e_Inverse_Pi --
------------------
-- Returns Pi to Max Available Precision. Use Arcsin, cause it has
-- lower error than Make_Pi.
-- Used for scaling trig functions, etc.
function e_Inverse_Pi return e_Real is
begin
if not Inverse_Pi_memory.Initialized then
Inverse_Pi_memory.Val := (+0.25) / e_Quarter_Pi;
Inverse_Pi_memory.Initialized := True;
end if;
return Inverse_Pi_memory.Val;
end e_Inverse_Pi;
------------------
-- e_Quarter_Pi --
------------------
-- Returns Pi/4 to Max Available Precision.
-- Used for scaling trig functions, etc.
function e_Quarter_Pi return e_Real is
begin
if not Quarter_Pi_memory.Initialized then
Quarter_Pi_memory.Val := (+1.5) * Arcsin (Half);
Quarter_Pi_memory.Initialized := True;
end if;
return Quarter_Pi_memory.Val;
end e_Quarter_Pi;
----------------------
-- e_Inverse_Sqrt_2 --
----------------------
-- Returns 1/Sqrt(2.0) to Max Available Precision.
-- Used for making Pi.
function e_Inverse_Sqrt_2 return e_Real is
begin
if not Inverse_Sqrt_2_memory.Initialized then
Inverse_Sqrt_2_memory.Val := Reciprocal_Nth_Root (Two, 2);
Inverse_Sqrt_2_memory.Initialized := True;
end if;
return Inverse_Sqrt_2_memory.Val;
end e_Inverse_Sqrt_2;
--------------------------
-- e_Half_Inverse_Log_2 --
--------------------------
-- Returns Exp(1.0) to Max Available Precision.
-- Used for scaling arguments of Exp.
function e_Half_Inverse_Log_2 return e_Real is
begin
if not Half_Inverse_Log_2_memory.Initialized then
Half_Inverse_Log_2_memory.Val := Half / E_Log_2;
Half_Inverse_Log_2_memory.Initialized := True;
end if;
return Half_Inverse_Log_2_memory.Val;
end e_Half_Inverse_Log_2;
--------------
-- e_Log_2 --
--------------
-- Returns Log(2.0) to Max Available Precision.
-- Used for scaling Exp(X).
function e_Log_2 return e_Real is
begin
if not Log_2_memory.Initialized then
Log_2_memory.Val := Log (Two);
Log_2_memory.Initialized := True;
end if;
return Log_2_memory.Val;
end e_Log_2;
end Extended_Real.Elementary_Functions;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- G N A T X R E F --
-- --
-- B o d y --
-- --
-- $Revision$
-- --
-- Copyright (C) 1998-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. --
-- --
------------------------------------------------------------------------------
with Xr_Tabls;
with Xref_Lib; use Xref_Lib;
with Ada.Text_IO;
with Ada.Strings.Fixed;
with GNAT.Command_Line;
with Gnatvsn;
with Osint;
procedure Gnatxref is
Search_Unused : Boolean := False;
Local_Symbols : Boolean := True;
Prj_File : File_Name_String;
Prj_File_Length : Natural := 0;
Usage_Error : exception;
Full_Path_Name : Boolean := False;
Vi_Mode : Boolean := False;
Read_Only : Boolean := False;
Have_File : Boolean := False;
Der_Info : Boolean := False;
procedure Parse_Cmd_Line;
-- Parse every switch on the command line
procedure Write_Usage;
-- Print a small help page for program usage
--------------------
-- Parse_Cmd_Line --
--------------------
procedure Parse_Cmd_Line is
begin
loop
case GNAT.Command_Line.Getopt ("a aI: aO: d f g h I: p: u v") is
when ASCII.NUL =>
exit;
when 'a' =>
if GNAT.Command_Line.Full_Switch = "a" then
Read_Only := True;
elsif GNAT.Command_Line.Full_Switch = "aI" then
Osint.Add_Src_Search_Dir (GNAT.Command_Line.Parameter);
else
Osint.Add_Lib_Search_Dir (GNAT.Command_Line.Parameter);
end if;
when 'd' =>
Der_Info := True;
when 'f' =>
Full_Path_Name := True;
when 'g' =>
Local_Symbols := False;
when 'h' =>
Write_Usage;
when 'I' =>
Osint.Add_Src_Search_Dir (GNAT.Command_Line.Parameter);
Osint.Add_Lib_Search_Dir (GNAT.Command_Line.Parameter);
when 'p' =>
declare
S : constant String := GNAT.Command_Line.Parameter;
begin
Prj_File_Length := S'Length;
Prj_File (1 .. Prj_File_Length) := S;
end;
when 'u' =>
Search_Unused := True;
Vi_Mode := False;
when 'v' =>
Vi_Mode := True;
Search_Unused := False;
when others =>
Write_Usage;
end case;
end loop;
-- Get the other arguments
loop
declare
S : constant String := GNAT.Command_Line.Get_Argument;
begin
exit when S'Length = 0;
if Ada.Strings.Fixed.Index (S, ":") /= 0 then
Ada.Text_IO.Put_Line
("Only file names are allowed on the command line");
Write_Usage;
end if;
Add_File (S);
Have_File := True;
end;
end loop;
exception
when GNAT.Command_Line.Invalid_Switch =>
Ada.Text_IO.Put_Line ("Invalid switch : "
& GNAT.Command_Line.Full_Switch);
Write_Usage;
when GNAT.Command_Line.Invalid_Parameter =>
Ada.Text_IO.Put_Line ("Parameter missing for : "
& GNAT.Command_Line.Parameter);
Write_Usage;
end Parse_Cmd_Line;
-----------------
-- Write_Usage --
-----------------
procedure Write_Usage is
use Ada.Text_IO;
begin
Put_Line ("GNATXREF " & Gnatvsn.Gnat_Version_String
& " Copyright 1998-2001, Ada Core Technologies Inc.");
Put_Line ("Usage: gnatxref [switches] file1 file2 ...");
New_Line;
Put_Line (" file ... list of source files to xref, " &
"including with'ed units");
New_Line;
Put_Line ("gnatxref switches:");
Put_Line (" -a Consider all files, even when the ali file is"
& " readonly");
Put_Line (" -aIdir Specify source files search path");
Put_Line (" -aOdir Specify library/object files search path");
Put_Line (" -d Output derived type information");
Put_Line (" -f Output full path name");
Put_Line (" -g Output information only for global symbols");
Put_Line (" -Idir Like -aIdir -aOdir");
Put_Line (" -p file Use file as the default project file");
Put_Line (" -u List unused entities");
Put_Line (" -v Print a 'tags' file for vi");
New_Line;
raise Usage_Error;
end Write_Usage;
begin
Parse_Cmd_Line;
if not Have_File then
Write_Usage;
end if;
Xr_Tabls.Set_Default_Match (True);
-- Find the project file
if Prj_File_Length = 0 then
Xr_Tabls.Create_Project_File
(Default_Project_File (Osint.To_Host_Dir_Spec (".", False).all));
else
Xr_Tabls.Create_Project_File (Prj_File (1 .. Prj_File_Length));
end if;
-- Fill up the table
Search_Xref (Local_Symbols, Read_Only, Der_Info);
if Search_Unused then
Print_Unused (Full_Path_Name);
elsif Vi_Mode then
Print_Vi (Full_Path_Name);
else
Print_Xref (Full_Path_Name);
end if;
exception
when Usage_Error =>
null;
end Gnatxref;
|
-----------------------------------------------------------------------
-- akt-callbacks -- Callbacks for Ada Keystore GTK application
-- Copyright (C) 2019, 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 Gtk.Main;
with Gtk.Widget;
with Gtk.GEntry;
with Gtk.File_Filter;
with Gtk.File_Chooser;
with Gtk.File_Chooser_Dialog;
with Gtk.Spin_Button;
with Gtk.Window;
with Util.Log.Loggers;
with Keystore;
package body AKT.Callbacks is
use type Gtk.Spin_Button.Gtk_Spin_Button;
use type Gtk.GEntry.Gtk_Entry;
use type Gtk.Widget.Gtk_Widget;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AKT.Callbacks");
App : AKT.Windows.Application_Access;
function Get_Widget (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class;
Name : in String) return Gtk.Widget.Gtk_Widget is
(Gtk.Widget.Gtk_Widget (Object.Get_Object (Name)));
function Get_Entry (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class;
Name : in String) return Gtk.GEntry.Gtk_Entry is
(Gtk.GEntry.Gtk_Entry (Object.Get_Object (Name)));
function Get_Spin_Button (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class;
Name : in String) return Gtk.Spin_Button.Gtk_Spin_Button is
(Gtk.Spin_Button.Gtk_Spin_Button (Object.Get_Object (Name)));
-- ------------------------------
-- Initialize and register the callbacks.
-- ------------------------------
procedure Initialize (Application : in AKT.Windows.Application_Access;
Builder : in Gtkada.Builder.Gtkada_Builder) is
begin
App := Application;
-- AKT.Callbacks.Application := Application;
Builder.Register_Handler (Handler_Name => "menu-quit",
Handler => AKT.Callbacks.On_Menu_Quit'Access);
-- Open file from menu and dialog.
Builder.Register_Handler (Handler_Name => "menu-open",
Handler => AKT.Callbacks.On_Menu_Open'Access);
Builder.Register_Handler (Handler_Name => "open-file",
Handler => AKT.Callbacks.On_Open_File'Access);
Builder.Register_Handler (Handler_Name => "cancel-open-file",
Handler => AKT.Callbacks.On_Cancel_Open_File'Access);
-- Create file from menu and dialog.
Builder.Register_Handler (Handler_Name => "menu-new",
Handler => AKT.Callbacks.On_Menu_New'Access);
Builder.Register_Handler (Handler_Name => "create-file",
Handler => AKT.Callbacks.On_Create_File'Access);
Builder.Register_Handler (Handler_Name => "cancel-create-file",
Handler => AKT.Callbacks.On_Cancel_Create_File'Access);
Builder.Register_Handler (Handler_Name => "window-close",
Handler => AKT.Callbacks.On_Close_Window'Access);
Builder.Register_Handler (Handler_Name => "about",
Handler => AKT.Callbacks.On_Menu_About'Access);
Builder.Register_Handler (Handler_Name => "close-about",
Handler => AKT.Callbacks.On_Close_About'Access);
Builder.Register_Handler (Handler_Name => "close-password",
Handler => AKT.Callbacks.On_Close_Password'Access);
Builder.Register_Handler (Handler_Name => "tool-edit",
Handler => AKT.Callbacks.On_Tool_Edit'Access);
Builder.Register_Handler (Handler_Name => "tool-lock",
Handler => AKT.Callbacks.On_Tool_Lock'Access);
Builder.Register_Handler (Handler_Name => "tool-unlock",
Handler => AKT.Callbacks.On_Tool_Unlock'Access);
Builder.Register_Handler (Handler_Name => "tool-save",
Handler => AKT.Callbacks.On_Tool_Save'Access);
Builder.Register_Handler (Handler_Name => "tool-add",
Handler => AKT.Callbacks.On_Tool_Add'Access);
Builder.Register_Handler (Handler_Name => "dialog-password-ok",
Handler => AKT.Callbacks.On_Dialog_Password_Ok'Access);
end Initialize;
-- ------------------------------
-- Callback executed when the "quit" action is executed from the menu.
-- ------------------------------
procedure On_Menu_Quit (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is
pragma Unreferenced (Object);
begin
Gtk.Main.Main_Quit;
end On_Menu_Quit;
-- ------------------------------
-- Callback executed when the "about" action is executed from the menu.
-- ------------------------------
procedure On_Menu_About (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is
About : constant Gtk.Widget.Gtk_Widget := Get_Widget (Object, "about");
begin
About.Show;
end On_Menu_About;
-- ------------------------------
-- Callback executed when the "menu-new" action is executed from the file menu.
-- ------------------------------
procedure On_Menu_New (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is
Chooser : constant Gtk.Widget.Gtk_Widget := Get_Widget (Object, "create_file_chooser");
Filter : Gtk.File_Filter.Gtk_File_Filter;
File_Chooser : Gtk.File_Chooser.Gtk_File_Chooser;
begin
if Chooser /= null then
File_Chooser := Gtk.File_Chooser_Dialog."+"
(Gtk.File_Chooser_Dialog.Gtk_File_Chooser_Dialog (Chooser));
Gtk.File_Filter.Gtk_New (Filter);
Gtk.File_Filter.Add_Pattern (Filter, "*.akt");
Gtk.File_Filter.Set_Name (Filter, "Keystore Files");
Gtk.File_Chooser.Add_Filter (File_Chooser, Filter);
Gtk.File_Filter.Gtk_New (Filter);
Gtk.File_Filter.Add_Pattern (Filter, "*");
Gtk.File_Filter.Set_Name (Filter, "All Files");
Gtk.File_Chooser.Add_Filter (File_Chooser, Filter);
end if;
Chooser.Show;
end On_Menu_New;
-- ------------------------------
-- Callback executed when the "menu-open" action is executed from the file menu.
-- ------------------------------
procedure On_Menu_Open (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is
Chooser : constant Gtk.Widget.Gtk_Widget := Get_Widget (Object, "open_file_chooser");
Filter : Gtk.File_Filter.Gtk_File_Filter;
File_Chooser : Gtk.File_Chooser.Gtk_File_Chooser;
begin
if Chooser /= null then
File_Chooser := Gtk.File_Chooser_Dialog."+"
(Gtk.File_Chooser_Dialog.Gtk_File_Chooser_Dialog (Chooser));
Gtk.File_Filter.Gtk_New (Filter);
Gtk.File_Filter.Add_Pattern (Filter, "*.akt");
Gtk.File_Filter.Set_Name (Filter, "Keystore Files");
Gtk.File_Chooser.Add_Filter (File_Chooser, Filter);
Gtk.File_Filter.Gtk_New (Filter);
Gtk.File_Filter.Add_Pattern (Filter, "*");
Gtk.File_Filter.Set_Name (Filter, "All Files");
Gtk.File_Chooser.Add_Filter (File_Chooser, Filter);
end if;
Chooser.Show;
end On_Menu_Open;
-- ------------------------------
-- Callback executed when the "tool-add" action is executed from the toolbar.
-- ------------------------------
procedure On_Tool_Add (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is
pragma Unreferenced (Object);
begin
App.Save_Current;
App.Refresh_Toolbar;
end On_Tool_Add;
-- ------------------------------
-- Callback executed when the "tool-save" action is executed from the toolbar.
-- ------------------------------
procedure On_Tool_Save (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is
pragma Unreferenced (Object);
begin
App.Save_Current;
App.Refresh_Toolbar;
end On_Tool_Save;
-- ------------------------------
-- Callback executed when the "tool-edit" action is executed from the toolbar.
-- ------------------------------
procedure On_Tool_Edit (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is
pragma Unreferenced (Object);
begin
App.Edit_Current;
App.Refresh_Toolbar;
end On_Tool_Edit;
-- ------------------------------
-- Callback executed when the "tool-lock" action is executed from the toolbar.
-- ------------------------------
procedure On_Tool_Lock (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is
pragma Unreferenced (Object);
begin
if not App.Is_Locked then
App.Lock;
end if;
end On_Tool_Lock;
-- ------------------------------
-- Callback executed when the "tool-unlock" action is executed from the toolbar.
-- ------------------------------
procedure On_Tool_Unlock (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is
Password_Dialog : constant Gtk.Widget.Gtk_Widget := Get_Widget (Object, "password_dialog");
Widget : constant Gtk.Widget.Gtk_Widget := Get_Widget (Object, "main");
begin
if App.Is_Locked and then Password_Dialog /= null then
Gtk.Window.Set_Transient_For (Gtk.Window.Gtk_Window (Password_Dialog),
Gtk.Window.Gtk_Window (Widget));
Password_Dialog.Show;
end if;
end On_Tool_Unlock;
-- ------------------------------
-- Callback executed when the "open-file" action is executed from the open_file dialog.
-- ------------------------------
procedure On_Open_File (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is
Chooser : constant Gtk.Widget.Gtk_Widget := Get_Widget (Object, "open_file_chooser");
Password : constant Gtk.GEntry.Gtk_Entry := Get_Entry (Object, "open_file_password");
Filename : constant Gtk.GEntry.Gtk_Entry := Get_Entry (Object, "open_file_name");
File_Chooser : Gtk.File_Chooser.Gtk_File_Chooser;
begin
if Chooser /= null and Password /= null and Filename /= null then
if Gtk.GEntry.Get_Text (Password) = "" then
App.Message ("Password is empty");
else
Chooser.Hide;
File_Chooser := Gtk.File_Chooser_Dialog."+"
(Gtk.File_Chooser_Dialog.Gtk_File_Chooser_Dialog (Chooser));
Log.Info ("Selected file {0}", Gtk.File_Chooser.Get_Filename (File_Chooser));
App.Open_File (Path => Gtk.File_Chooser.Get_Filename (File_Chooser),
Password => Keystore.Create (Gtk.GEntry.Get_Text (Password)));
end if;
end if;
end On_Open_File;
-- ------------------------------
-- Callback executed when the "cancel-open-file" action is executed from the open_file dialog.
-- ------------------------------
procedure On_Cancel_Open_File (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is
Chooser : constant Gtk.Widget.Gtk_Widget := Get_Widget (Object, "open_file_chooser");
begin
Chooser.Hide;
end On_Cancel_Open_File;
-- ------------------------------
-- Callback executed when the "create-file" action is executed from the open_file dialog.
-- ------------------------------
procedure On_Create_File (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is
Chooser : constant Gtk.Widget.Gtk_Widget := Get_Widget (Object, "create_file_chooser");
Password : constant Gtk.GEntry.Gtk_Entry := Get_Entry (Object, "create_file_password");
Filename : constant Gtk.GEntry.Gtk_Entry := Get_Entry (Object, "create_file_name");
Count : constant Gtk.Spin_Button.Gtk_Spin_Button
:= Get_Spin_Button (Object, "split_data_count");
File_Chooser : Gtk.File_Chooser.Gtk_File_Chooser;
begin
if Chooser /= null and Password /= null then
if Gtk.GEntry.Get_Text (Password) = "" then
App.Message ("Password is empty");
else
Chooser.Hide;
File_Chooser := Gtk.File_Chooser_Dialog."+"
(Gtk.File_Chooser_Dialog.Gtk_File_Chooser_Dialog (Chooser));
Log.Info ("Selected file {0}", Gtk.File_Chooser.Get_Filename (File_Chooser));
App.Create_File (Path => Gtk.GEntry.Get_Text (Filename),
Storage_Count => Natural (Count.Get_Value_As_Int),
Password => Keystore.Create (Gtk.GEntry.Get_Text (Password)));
end if;
end if;
end On_Create_File;
-- ------------------------------
-- Callback executed when the "cancel-create-file" action is executed
-- from the open_file dialog.
-- ------------------------------
procedure On_Cancel_Create_File (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is
Chooser : constant Gtk.Widget.Gtk_Widget := Get_Widget (Object, "create_file_chooser");
begin
Chooser.Hide;
end On_Cancel_Create_File;
-- ------------------------------
-- Callback executed when the "delete-event" action is executed from the main window.
-- ------------------------------
function On_Close_Window (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class)
return Boolean is
pragma Unreferenced (Object);
begin
Gtk.Main.Main_Quit;
return True;
end On_Close_Window;
-- ------------------------------
-- Callback executed when the "close-about" action is executed from the about box.
-- ------------------------------
procedure On_Close_About (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is
About : constant Gtk.Widget.Gtk_Widget := Get_Widget (Object, "about");
begin
About.Hide;
end On_Close_About;
-- ------------------------------
-- Callback executed when the "close-password" action is executed from the password dialog.
-- ------------------------------
procedure On_Close_Password (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is
Password_Dialog : constant Gtk.Widget.Gtk_Widget := Get_Widget (Object, "password_dialog");
begin
if Password_Dialog /= null then
Password_Dialog.Hide;
end if;
end On_Close_Password;
-- ------------------------------
-- Callback executed when the "dialog-password-ok" action is executed from the password dialog.
-- ------------------------------
procedure On_Dialog_Password_Ok (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is
Password_Dialog : constant Gtk.Widget.Gtk_Widget := Get_Widget (Object, "password_dialog");
Password : constant Gtk.GEntry.Gtk_Entry := Get_Entry (Object, "password");
begin
if Password_Dialog /= null and Password /= null then
if Gtk.GEntry.Get_Text (Password) = "" then
App.Message ("Password is empty");
else
Password_Dialog.Hide;
App.Unlock (Password => Keystore.Create (Gtk.GEntry.Get_Text (Password)));
end if;
end if;
end On_Dialog_Password_Ok;
end AKT.Callbacks;
|
package Square_Root with SPARK_Mode is
function Sqrt (X : Float; Tolerance : Float) return Float
with
SPARK_Mode,
Pre => X >= 0.0 and X <= 1.8E19 and
Tolerance > Float'Model_Epsilon and Tolerance <= 1.0,
Post => abs (X - Sqrt'Result ** 2) <= X * Tolerance;
end Square_Root;
|
with Atomic.Critical_Section; use Atomic.Critical_Section;
with System;
package body Atomic.Unsigned
with SPARK_Mode => Off
is
----------
-- Load --
----------
function Load
(This : aliased Instance;
Order : Mem_Order := Seq_Cst)
return T
is
Vola : T with Volatile, Address => This'Address;
State : Interrupt_State;
Result : T;
begin
Critical_Section.Enter (State);
Result := Vola;
Critical_Section.Leave (State);
return Result;
end Load;
-----------
-- Store --
-----------
procedure Store
(This : aliased in out Instance;
Val : T;
Order : Mem_Order := Seq_Cst)
is
Vola : T with Volatile, Address => This'Address;
State : Interrupt_State;
begin
Critical_Section.Enter (State);
Vola := Val;
Critical_Section.Leave (State);
end Store;
---------
-- Add --
---------
procedure Add (This : aliased in out Instance;
Val : T;
Order : Mem_Order := Seq_Cst)
is
Vola : T with Volatile, Address => This'Address;
State : Interrupt_State;
begin
Critical_Section.Enter (State);
Vola := Vola + Val;
Critical_Section.Leave (State);
end Add;
---------
-- Sub --
---------
procedure Sub (This : aliased in out Instance;
Val : T;
Order : Mem_Order := Seq_Cst)
is
Vola : T with Volatile, Address => This'Address;
State : Interrupt_State;
begin
Critical_Section.Enter (State);
Vola := Vola - Val;
Critical_Section.Leave (State);
end Sub;
------------
-- Op_And --
------------
procedure Op_And (This : aliased in out Instance;
Val : T;
Order : Mem_Order := Seq_Cst)
is
Vola : T with Volatile, Address => This'Address;
State : Interrupt_State;
begin
Critical_Section.Enter (State);
Vola := Vola and Val;
Critical_Section.Leave (State);
end Op_And;
------------
-- Op_XOR --
------------
procedure Op_XOR (This : aliased in out Instance;
Val : T;
Order : Mem_Order := Seq_Cst)
is
Vola : T with Volatile, Address => This'Address;
State : Interrupt_State;
begin
Critical_Section.Enter (State);
Vola := Vola xor Val;
Critical_Section.Leave (State);
end Op_XOR;
-----------
-- Op_OR --
-----------
procedure Op_OR (This : aliased in out Instance;
Val : T;
Order : Mem_Order := Seq_Cst)
is
Vola : T with Volatile, Address => This'Address;
State : Interrupt_State;
begin
Critical_Section.Enter (State);
Vola := Vola or Val;
Critical_Section.Leave (State);
end Op_OR;
----------
-- NAND --
----------
procedure NAND (This : aliased in out Instance;
Val : T;
Order : Mem_Order := Seq_Cst)
is
Vola : T with Volatile, Address => This'Address;
State : Interrupt_State;
begin
Critical_Section.Enter (State);
Vola := not (Vola and Val);
Critical_Section.Leave (State);
end NAND;
-- SPARK compatible --
--------------
-- Exchange --
--------------
procedure Exchange (This : aliased in out Instance;
Val : T;
Old : out T;
Order : Mem_Order := Seq_Cst)
is
Vola : T with Volatile, Address => This'Address;
State : Interrupt_State;
begin
Critical_Section.Enter (State);
Old := Vola;
Vola := Val;
Critical_Section.Leave (State);
end Exchange;
----------------------
-- Compare_Exchange --
----------------------
procedure Compare_Exchange (This : aliased in out Instance;
Expected : T;
Desired : T;
Weak : Boolean;
Success : out Boolean;
Success_Order : Mem_Order := Seq_Cst;
Failure_Order : Mem_Order := Seq_Cst)
is
Vola : T with Volatile, Address => This'Address;
State : Interrupt_State;
begin
Critical_Section.Enter (State);
if Vola = Expected then
Vola := Desired;
Success := True;
else
Success := False;
end if;
Critical_Section.Leave (State);
end Compare_Exchange;
---------------
-- Add_Fetch --
---------------
procedure Add_Fetch (This : aliased in out Instance;
Val : T;
Result : out T;
Order : Mem_Order := Seq_Cst)
is
Vola : T with Volatile, Address => This'Address;
State : Interrupt_State;
begin
Critical_Section.Enter (State);
Result := Vola + Val;
Vola := Result;
Critical_Section.Leave (State);
end Add_Fetch;
---------------
-- Sub_Fetch --
---------------
procedure Sub_Fetch (This : aliased in out Instance;
Val : T;
Result : out T;
Order : Mem_Order := Seq_Cst)
is
Vola : T with Volatile, Address => This'Address;
State : Interrupt_State;
begin
Critical_Section.Enter (State);
Result := Vola - Val;
Vola := Result;
Critical_Section.Leave (State);
end Sub_Fetch;
---------------
-- And_Fetch --
---------------
procedure And_Fetch (This : aliased in out Instance;
Val : T;
Result : out T;
Order : Mem_Order := Seq_Cst)
is
Vola : T with Volatile, Address => This'Address;
State : Interrupt_State;
begin
Critical_Section.Enter (State);
Result := Vola and Val;
Vola := Result;
Critical_Section.Leave (State);
end And_Fetch;
---------------
-- XOR_Fetch --
---------------
procedure XOR_Fetch (This : aliased in out Instance;
Val : T;
Result : out T;
Order : Mem_Order := Seq_Cst)
is
Vola : T with Volatile, Address => This'Address;
State : Interrupt_State;
begin
Critical_Section.Enter (State);
Result := Vola xor Val;
Vola := Result;
Critical_Section.Leave (State);
end XOR_Fetch;
--------------
-- OR_Fetch --
--------------
procedure OR_Fetch (This : aliased in out Instance;
Val : T;
Result : out T;
Order : Mem_Order := Seq_Cst)
is
Vola : T with Volatile, Address => This'Address;
State : Interrupt_State;
begin
Critical_Section.Enter (State);
Result := Vola or Val;
Vola := Result;
Critical_Section.Leave (State);
end OR_Fetch;
----------------
-- NAND_Fetch --
----------------
procedure NAND_Fetch (This : aliased in out Instance;
Val : T;
Result : out T;
Order : Mem_Order := Seq_Cst)
is
Vola : T with Volatile, Address => This'Address;
State : Interrupt_State;
begin
Critical_Section.Enter (State);
Result := not (Vola and Val);
Vola := Result;
Critical_Section.Leave (State);
end NAND_Fetch;
---------------
-- Fetch_Add --
---------------
procedure Fetch_Add (This : aliased in out Instance;
Val : T;
Result : out T;
Order : Mem_Order := Seq_Cst)
is
Vola : T with Volatile, Address => This'Address;
State : Interrupt_State;
begin
Critical_Section.Enter (State);
Result := Vola;
Vola := Vola + Val;
Critical_Section.Leave (State);
end Fetch_Add;
---------------
-- Fetch_Sub --
---------------
procedure Fetch_Sub (This : aliased in out Instance;
Val : T;
Result : out T;
Order : Mem_Order := Seq_Cst)
is
Vola : T with Volatile, Address => This'Address;
State : Interrupt_State;
begin
Critical_Section.Enter (State);
Result := Vola;
Vola := Vola - Val;
Critical_Section.Leave (State);
end Fetch_Sub;
---------------
-- Fetch_And --
---------------
procedure Fetch_And (This : aliased in out Instance;
Val : T;
Result : out T;
Order : Mem_Order := Seq_Cst)
is
Vola : T with Volatile, Address => This'Address;
State : Interrupt_State;
begin
Critical_Section.Enter (State);
Result := Vola;
Vola := Vola and Val;
Critical_Section.Leave (State);
end Fetch_And;
---------------
-- Fetch_XOR --
---------------
procedure Fetch_XOR (This : aliased in out Instance;
Val : T;
Result : out T;
Order : Mem_Order := Seq_Cst)
is
Vola : T with Volatile, Address => This'Address;
State : Interrupt_State;
begin
Critical_Section.Enter (State);
Result := Vola;
Vola := Vola xor Val;
Critical_Section.Leave (State);
end Fetch_XOR;
--------------
-- Fetch_OR --
--------------
procedure Fetch_OR (This : aliased in out Instance;
Val : T;
Result : out T;
Order : Mem_Order := Seq_Cst)
is
Vola : T with Volatile, Address => This'Address;
State : Interrupt_State;
begin
Critical_Section.Enter (State);
Result := Vola;
Vola := Vola or Val;
Critical_Section.Leave (State);
end Fetch_OR;
----------------
-- Fetch_NAND --
----------------
procedure Fetch_NAND (This : aliased in out Instance;
Val : T;
Result : out T;
Order : Mem_Order := Seq_Cst)
is
Vola : T with Volatile, Address => This'Address;
State : Interrupt_State;
begin
Critical_Section.Enter (State);
Result := Vola;
Vola := not (Vola and Val);
Critical_Section.Leave (State);
end Fetch_NAND;
-- NOT SPARK Compatible --
--------------
-- Exchange --
--------------
function Exchange
(This : aliased in out Instance;
Val : T;
Order : Mem_Order := Seq_Cst)
return T
is
Result : T;
begin
Exchange (This, Val, Result, Order);
return Result;
end Exchange;
----------------------
-- Compare_Exchange --
----------------------
function Compare_Exchange
(This : aliased in out Instance;
Expected : T;
Desired : T;
Weak : Boolean;
Success_Order : Mem_Order := Seq_Cst;
Failure_Order : Mem_Order := Seq_Cst)
return Boolean
is
Result : Boolean;
begin
Compare_Exchange (This, Expected, Desired, Weak, Result, Success_Order,
Failure_Order);
return Result;
end Compare_Exchange;
---------------
-- Add_Fetch --
---------------
function Add_Fetch
(This : aliased in out Instance; Val : T; Order : Mem_Order := Seq_Cst)
return T
is
Result : T;
begin
Add_Fetch (This, Val, Result, Order);
return Result;
end Add_Fetch;
---------------
-- Sub_Fetch --
---------------
function Sub_Fetch
(This : aliased in out Instance; Val : T; Order : Mem_Order := Seq_Cst)
return T
is
Result : T;
begin
Sub_Fetch (This, Val, Result, Order);
return Result;
end Sub_Fetch;
---------------
-- And_Fetch --
---------------
function And_Fetch
(This : aliased in out Instance; Val : T; Order : Mem_Order := Seq_Cst)
return T
is
Result : T;
begin
And_Fetch (This, Val, Result, Order);
return Result;
end And_Fetch;
---------------
-- XOR_Fetch --
---------------
function XOR_Fetch
(This : aliased in out Instance; Val : T; Order : Mem_Order := Seq_Cst)
return T
is
Result : T;
begin
XOR_Fetch (This, Val, Result, Order);
return Result;
end XOR_Fetch;
--------------
-- OR_Fetch --
--------------
function OR_Fetch
(This : aliased in out Instance; Val : T; Order : Mem_Order := Seq_Cst)
return T
is
Result : T;
begin
OR_Fetch (This, Val, Result, Order);
return Result;
end OR_Fetch;
----------------
-- NAND_Fetch --
----------------
function NAND_Fetch
(This : aliased in out Instance; Val : T; Order : Mem_Order := Seq_Cst)
return T
is
Result : T;
begin
NAND_Fetch (This, Val, Result, Order);
return Result;
end NAND_Fetch;
---------------
-- Fetch_Add --
---------------
function Fetch_Add
(This : aliased in out Instance; Val : T; Order : Mem_Order := Seq_Cst)
return T
is
Result : T;
begin
Fetch_Add (This, Val, Result, Order);
return Result;
end Fetch_Add;
---------------
-- Fetch_Sub --
---------------
function Fetch_Sub
(This : aliased in out Instance; Val : T; Order : Mem_Order := Seq_Cst)
return T
is
Result : T;
begin
Fetch_Sub (This, Val, Result, Order);
return Result;
end Fetch_Sub;
---------------
-- Fetch_And --
---------------
function Fetch_And
(This : aliased in out Instance; Val : T; Order : Mem_Order := Seq_Cst)
return T
is
Result : T;
begin
Fetch_And (This, Val, Result, Order);
return Result;
end Fetch_And;
---------------
-- Fetch_XOR --
---------------
function Fetch_XOR
(This : aliased in out Instance; Val : T; Order : Mem_Order := Seq_Cst)
return T
is
Result : T;
begin
Fetch_XOR (This, Val, Result, Order);
return Result;
end Fetch_XOR;
--------------
-- Fetch_OR --
--------------
function Fetch_OR
(This : aliased in out Instance; Val : T; Order : Mem_Order := Seq_Cst)
return T
is
Result : T;
begin
Fetch_OR (This, Val, Result, Order);
return Result;
end Fetch_OR;
----------------
-- Fetch_NAND --
----------------
function Fetch_NAND
(This : aliased in out Instance; Val : T; Order : Mem_Order := Seq_Cst)
return T
is
Result : T;
begin
Fetch_NAND (This, Val, Result, Order);
return Result;
end Fetch_NAND;
end Atomic.Unsigned;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.