content
stringlengths
23
1.05M
with My_Pack; with Suppack; with Ada.Text_IO; use Ada.Text_IO; procedure Test_Init is begin Put_Line (Integer'Image (My_Pack.Get)); My_Pack.Set (100); Put_Line (Integer'Image (My_Pack.Get)); Put_Line (Integer'Image (My_Pack.Get_Count)); Suppack.Print; Put_Line (Integer'Image (My_Pack.Get_Count)); end Test_Init;
package body Math_2D.Vectors is use type Types.Real_Type; function Magnitude (Vector : in Types.Vector_t) return Types.Real_Type'Base is begin return Types.Functions.Sqrt (Square_Magnitude (Vector)); end Magnitude; function Square_Magnitude (Vector : in Types.Vector_t) return Types.Real_Type'Base is begin return Inner_Product (Vector_A => Vector, Vector_B => Vector); end Square_Magnitude; function Normalize (Vector : in Types.Vector_t) return Types.Vector_t is Product : constant Types.Real_Type'Base := Inner_Product (Vector_A => Vector, Vector_B => Vector); Reciprocal : Types.Real_Type'Base; begin if Product /= 0.0 then Reciprocal := 1.0 / Types.Functions.Sqrt (Product); return Scale (Vector => Vector, Scalar => Reciprocal); else return Vector; end if; end Normalize; procedure Normalize (Vector : in out Types.Vector_t) is begin Vector := Normalize (Vector); end Normalize; end Math_2D.Vectors;
with Ada.Text_IO; use Ada.Text_IO; with Ada.Float_Text_IO; use Ada.Float_Text_IO; with Alea; -- Évaluer la qualité du générateur aléatoire dans plusieurs -- configurations. procedure Evaluer_Alea is Capacity : Constant Integer := 10000; Type T_List is array(1..Capacity) of Integer; Type T_Generator is record List : T_List; Length : Integer; -- { 10 <= Length <= Capacity } end record; function Init_Generator ( Length : In Integer) return T_Generator is package Mon_Alea is new Alea (1, Length); use Mon_Alea; Generator : T_Generator; begin Generator.Length := Length; for i in 1..Generator.Length loop Get_Random_Number (Generator.List(i)); end loop; return Generator; end Init_Generator; procedure Print_Generator( Generator : In T_Generator) is begin for i in 1 .. Generator.Length loop Put(Integer'Image(Generator.List(i))); end loop; end Print_Generator; function Occurrence ( Generator : In T_Generator; Item : In Integer) return Integer is Count : Integer; begin Count := 0; for i in 1..Generator.Length loop if Generator.List(i) = Item then Count := Count + 1; end if; end loop; return Count; end Occurrence; function Max_Frequency (Generator : In T_Generator) return Integer is Maxi_Frequency : Integer; begin Maxi_Frequency := Occurrence (Generator, Generator.List(1)); for i in 2..Generator.Length loop if Occurrence (Generator, Generator.List(i)) > Maxi_Frequency then Maxi_Frequency := Occurrence (Generator, Generator.List(i)); end if; end loop; return Maxi_Frequency; end Max_Frequency; function Min_Frequency (Generator : In T_Generator) return Integer is Mini_Frequency : Integer; begin Mini_Frequency := Occurrence (Generator, Generator.List(1)); for i in 2..Generator.Length loop if Occurrence (Generator, Generator.List(i)) < Mini_Frequency then Mini_Frequency := Occurrence (Generator, Generator.List(i)); end if; end loop; return Mini_Frequency; end Min_Frequency; -- Évaluer la qualité du générateur de nombre aléatoire Alea sur un -- intervalle donné en calculant les fréquences absolues minimales et -- maximales des entiers obtenus lors de plusieurs tirages aléatoire -- ainsi que la fréquence moyenne théorique. -- -- Paramètres : -- Borne: in Entier -- le nombre aléatoire est dans 1..Borne -- Taille: in Entier -- nombre de tirages à faire (taille de l'échantillon) -- Min, Max: out Entier -- fréquence minimale et maximale -- Moyenne: out Float -- fréquence moyenne théorique -- -- Nécessite : -- Borne > 1 -- Taille > 1 -- -- Assure : -- poscondition peu intéressante ! -- 0 <= Min Et Min <= Taille -- 0 <= Max Et Max <= Taille -- Min + Max <= Taille -- Moyenne = Réel(Taille) / Réel(Borne) -- Min <= Moyenne Et Moyenne <= Max -- -- Remarque : On ne peut ni formaliser les 'vraies' postconditions, -- ni écrire de programme de test car on ne maîtrise par le générateur -- aléatoire. Pour écrire un programme de test, on pourrait remplacer -- le générateur par un générateur qui fournit une séquence connue -- d'entiers et pour laquelle on pourrait déterminer les données -- statistiques demandées. -- Ici, pour tester on peut afficher les nombres aléatoires et refaire -- les calculs par ailleurs pour vérifier que le résultat produit est -- le bon. procedure Calculer_Statistiques ( Generator : In T_Generator; Borne : in Integer; -- Borne supérieur de l'intervalle de recherche Taille : in Integer; -- Taille de l'échantillon Min, Max : out Integer; -- min et max des fréquences de l'échantillon Moyenne : out Float -- moyenne des fréquences ) with Pre => Borne > 1 and Taille > 1, Post => 0 <= Min and Min <= Taille and 0 <= Max and Max <= Taille and Min + Max <= Taille and Moyenne = Float (Taille) / Float (Borne) and Float (Min) <= Moyenne and Moyenne <= Float (Max) is begin Moyenne := Float(Taille) / Float(Borne); Min := Min_Frequency (Generator); Max := Max_Frequency (Generator); end Calculer_Statistiques; -- Afficher les données statistiques -- Paramètres: -- Min, Max : in Entier -- le min et le max -- Moyenne : in Réel -- la moyenne procedure Afficher_Statistiques (Min, Max: Integer; Moyenne: in Float) is begin New_Line; Put_Line ("Min =" & Integer'Image (Min)); Put_Line ("Max =" & Integer'Image (Max)); Put ("Moyenne = "); Put (Moyenne, 1, 2, 0); -- Put d'un réel accepte trois paramètres supplémentaires -- le nombre de positions à utiliser avant le '.' (ici 1) -- le nombre de positions pour la partie décimale (ici 2) -- le nombre de positions pour l'exposant (ici 0) New_Line; end Afficher_Statistiques; Generator : T_Generator; Min, Max: Integer; -- fréquence minimale et maximale d'un échantillon Moyenne: Float; -- fréquences moyenne de l'échantillon begin -- Calculer les statistiques pour un dé à 6 faces et un petit échantillon Generator := Init_Generator (20); Print_Generator (Generator); Calculer_Statistiques (Generator, 6, 20, Min, Max, Moyenne); Afficher_Statistiques (Min, Max, Moyenne); New_Line; -- -- Calculer les statistiques pour un dé à 6 faces et un échantillon grand Generator := Init_Generator (10000); Calculer_Statistiques (Generator, 6, 10000, Min, Max, Moyenne); Afficher_Statistiques (Min, Max, Moyenne); New_Line; -- -- Calculer les statistiques pour un dé à 6 faces et un échantillon -- très grand Generator := Init_Generator (10e6); Calculer_Statistiques (Generator,6, 10e6, Min, Max, Moyenne); Afficher_Statistiques (Min, Max, Moyenne); New_Line; -- -- Calculer les statistiques pour un dé à 6 faces et un échantillon -- très, très grand Generator := Init_Generator (10e8); Calculer_Statistiques (Generator, 6, 10e8, Min, Max, Moyenne); Afficher_Statistiques (Min, Max, Moyenne); New_Line; end Evaluer_Alea;
--Just testing all the procedure pragmas I could think of. Procedure Pragmas is pragma List(Off); pragma Optimize(Off); Procedure TryInline is Foo : Integer := 0; begin null; end; pragma Inline(TryInline); begin null; end;
-- Tiny Text -- Copyright 2020 Jeremy Grosser -- See LICENSE for details with HAL.Bitmap; use HAL.Bitmap; with HAL; package Tiny_Text is Font_Width : constant := 3; Font_Height : constant := 6; subtype Font_Character is HAL.UInt18; type Font_Array is array (Character) of Font_Character; Font_Data : constant Font_Array := ( ' ' => 2#000_000_000_000_000_000#, '!' => 2#010_010_010_000_010_000#, '"' => 2#101_101_000_000_000_000#, '#' => 2#101_111_101_111_101_000#, '$' => 2#011_110_011_110_010_000#, '%' => 2#100_001_010_100_001_000#, '&' => 2#110_110_111_101_011_000#, ''' => 2#010_010_000_000_000_000#, '(' => 2#001_010_010_010_001_000#, ')' => 2#100_010_010_010_100_000#, '*' => 2#101_010_101_000_000_000#, '+' => 2#000_010_111_010_000_000#, ',' => 2#000_000_000_010_100_000#, '-' => 2#000_000_111_000_000_000#, '.' => 2#000_000_000_000_010_000#, '/' => 2#001_001_010_100_100_000#, '0' => 2#011_101_101_101_110_000#, '1' => 2#010_110_010_010_010_000#, '2' => 2#110_001_010_100_111_000#, '3' => 2#110_001_010_001_110_000#, '4' => 2#101_101_111_001_001_000#, '5' => 2#111_100_110_001_110_000#, '6' => 2#011_100_111_101_111_000#, '7' => 2#111_001_010_100_100_000#, '8' => 2#111_101_111_101_111_000#, '9' => 2#111_101_111_001_110_000#, ':' => 2#000_010_000_010_000_000#, ';' => 2#000_010_000_010_100_000#, '<' => 2#001_010_100_010_001_000#, '=' => 2#000_111_000_111_000_000#, '>' => 2#100_010_001_010_100_000#, '?' => 2#111_001_010_000_010_000#, '@' => 2#010_101_111_100_011_000#, 'A' => 2#010_101_111_101_101_000#, 'B' => 2#110_101_110_101_110_000#, 'C' => 2#011_100_100_100_011_000#, 'D' => 2#110_101_101_101_110_000#, 'E' => 2#111_100_111_100_111_000#, 'F' => 2#111_100_111_100_100_000#, 'G' => 2#011_100_111_101_011_000#, 'H' => 2#101_101_111_101_101_000#, 'I' => 2#111_010_010_010_111_000#, 'J' => 2#001_001_001_101_010_000#, 'K' => 2#101_101_110_101_101_000#, 'L' => 2#100_100_100_100_111_000#, 'M' => 2#101_111_111_101_101_000#, 'N' => 2#101_111_111_111_101_000#, 'O' => 2#010_101_101_101_010_000#, 'P' => 2#110_101_110_100_100_000#, 'Q' => 2#010_101_101_111_011_000#, 'R' => 2#110_101_111_110_101_000#, 'S' => 2#011_100_010_001_110_000#, 'T' => 2#111_010_010_010_010_000#, 'U' => 2#101_101_101_101_011_000#, 'V' => 2#101_101_101_010_010_000#, 'W' => 2#101_101_111_111_101_000#, 'X' => 2#101_101_010_101_101_000#, 'Y' => 2#101_101_010_010_010_000#, 'Z' => 2#111_001_010_100_111_000#, '[' => 2#111_100_100_100_111_000#, '\' => 2#000_100_010_001_000_000#, ']' => 2#111_001_001_001_111_000#, '^' => 2#010_101_000_000_000_000#, '_' => 2#000_000_000_000_111_000#, '`' => 2#100_010_000_000_000_000#, 'a' => 2#000_110_011_101_111_000#, 'b' => 2#100_110_101_101_110_000#, 'c' => 2#000_011_100_100_011_000#, 'd' => 2#001_011_101_101_011_000#, 'e' => 2#000_011_101_110_011_000#, 'f' => 2#001_010_111_010_010_000#, 'g' => 2#000_011_101_111_001_010#, 'h' => 2#100_110_101_101_101_000#, 'i' => 2#010_000_010_010_010_000#, 'j' => 2#001_000_001_001_101_010#, 'k' => 2#100_101_110_110_101_000#, 'l' => 2#110_010_010_010_111_000#, 'm' => 2#000_111_111_111_101_000#, 'n' => 2#000_110_101_101_101_000#, 'o' => 2#000_010_101_101_010_000#, 'p' => 2#000_110_101_101_110_100#, 'q' => 2#000_011_101_101_011_001#, 'r' => 2#000_011_100_100_100_000#, 's' => 2#000_011_110_011_110_000#, 't' => 2#010_111_010_010_011_000#, 'u' => 2#000_101_101_101_011_000#, 'v' => 2#000_101_101_111_010_000#, 'w' => 2#000_101_111_111_111_000#, 'x' => 2#000_101_010_010_101_000#, 'y' => 2#000_101_101_011_001_010#, 'z' => 2#000_111_011_110_111_000#, '{' => 2#011_010_100_010_011_000#, '|' => 2#010_010_000_010_010_000#, '}' => 2#110_010_001_010_110_000#, '~' => 2#011_110_000_000_000_000#, others => 2#111_101_101_101_111_000#); type Text_Buffer is tagged record Width, Height : Natural; Bitmap : Any_Bitmap_Buffer; Default_Cursor : Point; Cursor : Point; end record; procedure Initialize (This : in out Text_Buffer; Bitmap : Any_Bitmap_Buffer; Width : Natural; Height : Natural); procedure Clear (This : in out Text_Buffer); procedure Advance (This : in out Text_Buffer); procedure New_Line (This : in out Text_Buffer); procedure Put (This : in out Text_Buffer; Location : Point; Char : Character; Foreground : Bitmap_Color; Background : Bitmap_Color); procedure Put (This : in out Text_Buffer; Char : Character); procedure Put (This : in out Text_Buffer; Str : String); procedure Put_Line (This : in out Text_Buffer; Str : String); end Tiny_Text;
----------------------------------------------------------------------- -- mgrep-scanner -- Scan a directory and parse mail -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Mgrep.Matcher; private with Util.Strings.Vectors; private with Ada.Finalization; private with Ada.Exceptions; private with Util.Executors; private with Util.Concurrent.Counters; package Mgrep.Scanner is type Scanner_Type (Count : Positive; Rule : access Matcher.Mail_Rule) is tagged limited private; procedure Add_Directory (Scanner : in out Scanner_Type; Path : in String); procedure Add_File (Scanner : in out Scanner_Type; Path : in String); procedure Scan_File (Scanner : in out Scanner_Type; Path : in String); procedure Scan_Directory (Scanner : in out Scanner_Type; Path : in String); procedure Start (Scanner : in out Scanner_Type); procedure Stop (Scanner : in out Scanner_Type); procedure Process (Scanner : in out Scanner_Type; Done : out Boolean); function Get_File_Count (Scanner : in Scanner_Type) return Natural; function Get_Directory_Count (Scanner : in Scanner_Type) return Natural; private type Scanner_Access is access all Scanner_Type'Class; type Work_Kind is (SCAN_DIRECTORY, SCAN_MAIL); type Work_Type is record Kind : Work_Kind; Scanner : Scanner_Access; Path : Ada.Strings.Unbounded.Unbounded_String; end record; procedure Execute (Work : in out Work_Type); procedure Error (Work : in out Work_Type; Ex : in Ada.Exceptions.Exception_Occurrence); QUEUE_SIZE : constant := 100000; package Executors is new Util.Executors (Work_Type => Work_Type, Execute => Execute, Error => Error, Default_Queue_Size => QUEUE_SIZE); type Task_Manager (Count : Positive) is limited new Executors.Executor_Manager (Count) with null record; type Scanner_Type (Count : Positive; Rule : access Matcher.Mail_Rule) is limited new Ada.Finalization.Limited_Controlled with record Job_Count : Util.Concurrent.Counters.Counter; Scan_Dir_Count : Util.Concurrent.Counters.Counter; Scan_File_Count : Util.Concurrent.Counters.Counter; Dir_Count : Util.Concurrent.Counters.Counter; File_Count : Util.Concurrent.Counters.Counter; Self : Scanner_Access; Directories : Util.Strings.Vectors.Vector; Manager : Task_Manager (Count); end record; overriding procedure Initialize (Scanner : in out Scanner_Type); end Mgrep.Scanner;
----------------------------------------------------------------------- -- Secret -- Ada wrapper for Secret Service -- Copyright (C) 2017, 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 System; with Ada.Finalization; private with Interfaces.C.Strings; -- == Secret Service API == -- The Secret Service API is a service developped for the Gnome keyring and the KDE KWallet. -- It allows application to access and manage stored passwords and secrets in the two -- desktop environments. The libsecret is the C library that gives access to the secret -- service. The <tt>Secret</tt> package provides an Ada binding for this secret service API. -- -- @include secret-values.ads -- @include secret-attributes.ads -- @include secret-services.ads package Secret is type Object_Type is tagged private; -- Check if the value is empty. function Is_Null (Value : in Object_Type'Class) return Boolean; private use type System.Address; subtype Opaque_Type is System.Address; type Object_Type is new Ada.Finalization.Controlled with record Opaque : Opaque_Type := System.Null_Address; end record; -- Internal operation to set the libsecret internal pointer. procedure Set_Opaque (Into : in out Object_Type'Class; Data : in Opaque_Type); -- Internal operation to get the libsecret internal pointer. function Get_Opaque (From : in Object_Type'Class) return Opaque_Type; subtype Chars_Ptr is Interfaces.C.Strings.chars_ptr; procedure Free (P : in out Chars_Ptr) renames Interfaces.C.Strings.Free; function To_String (P : Chars_Ptr) return String renames Interfaces.C.Strings.Value; function New_String (V : in String) return Chars_Ptr renames Interfaces.C.Strings.New_String; type GError_Type is record Domain : Interfaces.Unsigned_32 := 0; Code : Interfaces.C.int := 0; Message : Chars_Ptr; end record with Convention => C; type GError is access all GError_Type with Convention => C; pragma Linker_Options ("-lsecret-1"); pragma Linker_Options ("-lglib-2.0"); pragma Linker_Options ("-lgio-2.0"); -- pragma Linker_Options ("-liconv"); end Secret;
package Opt12_Pkg is type Static_Integer_Subtype is range -32_000 .. 32_000; function Equal (L, R: Static_Integer_Subtype) return Boolean; type My_Fixed is delta 0.1 range -5.0 .. 5.0; Fix_Half : My_Fixed := 0.5; end Opt12_Pkg;
-- ________ ___ ______ ______ ___ -- /___ .. ._/ |.| |.___.\ /. __ .\ __|.| ____ -- / .. / |.| |.____/ |.|__|.| / .. ..| __\ .. \ -- _/ .. /___ |.| |.| === | .. __ .. ||. = .| | = .. | -- /_______/ |_| /__| /__| |_| \__\_| \__\_| -- Zip library -------------- -- Library for manipulating archive files in the Zip format -- -- Pure Ada 95 + code, 100% portable : OS - , CPU - and compiler - independent. -- -- Version / date / download info : see the version, reference, web strings -- defined at the end of the public part of this package. -- Legal licensing note: -- Copyright (c) 1999 .. 2012 Gautier de Montmollin -- 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. -- NB : this is the MIT License, as found 12 - Sep - 2007 on the site -- http://www.opensource.org/licenses/mit - license.php with Zip_Streams; with Ada.Calendar, Ada.Streams.Stream_IO, Ada.Text_IO, Ada.Strings.Unbounded; with Interfaces; package Zip is -------------- -- Zip_info -- -------------- -- Zip_info contains the Zip file name or input stream, -- and the archive's sorted directory type Zip_info is private; ----------------------------------------------------------------------- -- Load the whole .zip directory in archive (from) into a tree, for -- -- fast searching -- ----------------------------------------------------------------------- -- Load from a file procedure Load (info : out Zip_info; from : String; -- Zip file name case_sensitive : Boolean := False); -- Load from a stream procedure Load (info : out Zip_info; from : Zip_Streams.Zipstream_Class; case_sensitive : Boolean := False); Zip_file_Error, Zip_file_open_Error, Duplicate_name : exception; -- Parameter Form added to *_IO.[Open|Create] Form_For_IO_Open_N_Create : Ada.Strings.Unbounded.Unbounded_String := Ada.Strings.Unbounded.Null_Unbounded_String; -- See RM A.8.2 : File Management -- Example : "encoding=8bits" function Is_loaded (info : Zip_info) return Boolean; function Zip_name (info : Zip_info) return String; function Zip_comment (info : Zip_info) return String; function Zip_Stream (info : Zip_info) return Zip_Streams.Zipstream_Class; function Entries (info : Zip_info) return Natural; procedure Delete (info : in out Zip_info); Forgot_to_load_zip_info : exception; -- Data sizes in archive subtype File_size_type is Interfaces.Unsigned_32; --------- -- Compression methods or formats in the "official" PKWARE Zip format. -- Details in appnote.txt, part V.J -- C : supported for compressing -- D : supported for decompressing type PKZip_method is (store, -- C, D shrink, -- C, D reduce_1, -- C, D reduce_2, -- C, D reduce_3, -- C, D reduce_4, -- C, D implode, -- D tokenize, deflate, -- D deflate_e, -- D - Enhanced deflate bzip2, -- D lzma, ppmd, unknown ); -- Technical : translates the method code as set in zip archives function Method_from_code (x : Interfaces.Unsigned_16) return PKZip_method; function Method_from_code (x : Natural) return PKZip_method; -- Internal time definition subtype Time is Zip_Streams.Time; function Convert (date : Ada.Calendar.Time) return Time renames Zip_Streams.Calendar.Convert; function Convert (date : Time) return Ada.Calendar.Time renames Zip_Streams.Calendar.Convert; -- Traverse a whole Zip_info directory in sorted order, giving the -- name for each entry to an user - defined "Action" procedure. -- Concretely, you can process a whole Zip file that way, by extracting data -- with Extract, or open a reader stream with UnZip.Streams. -- See the Comp_Zip or Find_Zip tools as application examples. generic with procedure Action (name : String); -- 'name' is compressed entry's name procedure Traverse (z : Zip_info); -- Same as Traverse, but Action gives also technical informations about the -- compressed entry. generic with procedure Action ( name : String; -- 'name' is compressed entry's name file_index : Positive; comp_size : File_size_type; uncomp_size : File_size_type; crc_32 : Interfaces.Unsigned_32; date_time : Time; method : PKZip_method; unicode_file_name : Boolean ); procedure Traverse_verbose (z : Zip_info); -- Academic : see how well the name tree is balanced procedure Tree_stat (z : Zip_info; total : out Natural; max_depth : out Natural; avg_depth : out Float); -------------------------------------------------------------------------- -- Offsets - various procedures giving 1 - based indexes to local headers -- -------------------------------------------------------------------------- -- Find 1st offset in a Zip stream procedure Find_first_offset (file : Zip_Streams.Zipstream_Class; file_index : out Positive); -- Find offset of a certain compressed file -- in a Zip file (file opened and kept open) procedure Find_offset (file : Zip_Streams.Zipstream_Class; name : String; case_sensitive : Boolean; file_index : out Positive; comp_size : out File_size_type; uncomp_size : out File_size_type); -- Find offset of a certain compressed file in a Zip_info data procedure Find_offset (info : Zip_info; name : String; case_sensitive : Boolean; file_index : out Ada.Streams.Stream_IO.Positive_Count; comp_size : out File_size_type; uncomp_size : out File_size_type); File_name_not_found : exception; procedure Get_sizes (info : Zip_info; name : String; case_sensitive : Boolean; comp_size : out File_size_type; uncomp_size : out File_size_type); -- User - defined procedure for feedback occuring during -- compression or decompression (entry_skipped meaningful -- only for the latter) type Feedback_proc is access procedure (percents_done : Natural; -- %'s completed entry_skipped : Boolean; -- indicates one can show "skipped", no %'s user_abort : out Boolean); -- e.g. transmit a "click on Cancel" here ------------------------------------------------------------------------- -- Goodies - things used internally but that might be generally useful -- ------------------------------------------------------------------------- -- BlockRead : general - purpose procedure (nothing really specific to Zip / -- UnZip) : reads either the whole buffer from a file, or if the end of -- the file lays inbetween, a part of the buffer. -- -- The procedure's names and parameters match Borland Pascal / Delphi subtype Byte is Interfaces.Unsigned_8; type Byte_Buffer is array (Integer range <>) of aliased Byte; type p_Byte_Buffer is access Byte_Buffer; procedure BlockRead (file : Ada.Streams.Stream_IO.File_Type; buffer : out Byte_Buffer; actually_read : out Natural); -- = buffer'Length if no end of file before last buffer element -- Same for general streams -- procedure BlockRead (stream : Zip_Streams.Zipstream_Class; buffer : out Byte_Buffer; actually_read : out Natural); -- = buffer'Length if no end of stream before last buffer element -- Same, but instead of giving actually_read, raises End_Error if -- the buffer cannot be fully read. -- This mimics the 'Read stream attribute; can be a lot faster, depending -- on the compiler's run - time library. procedure BlockRead (stream : Zip_Streams.Zipstream_Class; buffer : out Byte_Buffer); -- This mimics the 'Write stream attribute; can be a lot faster, depending -- on the compiler's run - time library. -- NB : here we can use the root stream type : no question of size, index, .. . procedure BlockWrite (stream : in out Ada.Streams.Root_Stream_Type'Class; buffer : Byte_Buffer); -- This does the same as Ada 2005's Ada.Directories.Exists -- Just there as helper for Ada 95 only systems -- function Exists (name : String) return Boolean; -- Write a string containing line endings (possible from another system) -- into a text file, with the correct native line endings. -- Works for displaying/saving correctly -- CR&LF (DOS/Win), LF (UNIX), CR (Mac OS < 9) -- procedure Put_Multi_Line ( out_file : Ada.Text_IO.File_Type; text : String ); procedure Write_as_text ( out_file : Ada.Text_IO.File_Type; buffer : Byte_Buffer; last_char : in out Character -- track line - ending characters between writes ); -------------------------------------------------------------- -- Information about this package - e.g. for an "about" box -- -------------------------------------------------------------- version : constant String := "43 - pre"; reference : constant String := "14 - Jul - 2012"; web : constant String := "http://unzip - ada.sf.net/"; -- hopefully the latest version is at that URL .. . --- ^ ------------------- -- Private items -- ------------------- private -- Zip_info, 23.VI.1999. -- The PKZIP central directory is coded here as a binary tree -- to allow a fast retrieval of the searched offset in zip file. -- E.g. for a 1000 - file archive, the offset will be found in less -- than 11 moves : 2**10=1024 (balanced case), without any read -- in the archive. type Dir_node; type p_Dir_node is access Dir_node; type Dir_node (name_len : Natural) is record left, right : p_Dir_node; dico_name : String (1 .. name_len); -- UPPER if case - insensitive search file_name : String (1 .. name_len); file_index : Ada.Streams.Stream_IO.Positive_Count; comp_size : File_size_type; uncomp_size : File_size_type; crc_32 : Interfaces.Unsigned_32; date_time : Time; method : PKZip_method; unicode_file_name : Boolean; end record; type p_String is access String; type Zip_info is record loaded : Boolean := False; zip_file_name : p_String; -- a file name .. . zip_input_stream : Zip_Streams.Zipstream_Class; -- . .. or an input stream -- ^ when not null, we use this and not zip_file_name dir_binary_tree : p_Dir_node; total_entries : Natural; zip_file_comment : p_String; end record; end Zip;
------------------------------------------------------------------------------- -- This file is part of libsparkcrypto. -- -- Copyright (C) 2010, Alexander Senier -- Copyright (C) 2010, secunet Security Networks AG -- 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 nor the names of its contributors may be used -- to endorse or promote products derived from this software without -- specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS -- BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -- POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------- with LSC.Internal.Types; with LSC.Internal.SHA1; with LSC.Internal.SHA256; with LSC.Internal.SHA512; with LSC.Internal.RIPEMD160; with LSC.Internal.AES; with LSC.Internal.HMAC_SHA256; with LSC.Internal.HMAC_SHA384; with LSC.Internal.HMAC_SHA512; with LSC.Internal.Bignum; with Interfaces.C; with System; use type LSC.Internal.Types.Word32; use type LSC.Internal.Types.Word64; ------------------------------------------------------------------------------- -- ATTENTION: This is *NOT* a proper OpenSSL binding. It is very hacky and -- e.g. relies on facts like GNAT being used, that 'access all' is equivalent -- to a C pointer, and much more. It is bad style and only intended for -- benchmarking LSC - do not use it for anything but that. You've been warned! ------------------------------------------------------------------------------- package OpenSSL is type SHA1_Context_Type is private; type SHA256_Context_Type is private; type SHA384_Context_Type is private; type SHA512_Context_Type is private; type RIPEMD160_Context_Type is private; type AES_Enc_Context_Type is private; type AES_Dec_Context_Type is private; ---------------------------------------------------------------------------- -- AES function Create_AES128_Enc_Context (Key : LSC.Internal.AES.AES128_Key_Type) return AES_Enc_Context_Type; function Create_AES192_Enc_Context (Key : LSC.Internal.AES.AES192_Key_Type) return AES_Enc_Context_Type; function Create_AES256_Enc_Context (Key : LSC.Internal.AES.AES256_Key_Type) return AES_Enc_Context_Type; function Encrypt (Context : AES_Enc_Context_Type; Plaintext : LSC.Internal.AES.Block_Type) return LSC.Internal.AES.Block_Type; pragma Inline (Encrypt); procedure CBC_Encrypt (Plaintext : in LSC.Internal.AES.Message_Type; Ciphertext : out LSC.Internal.AES.Message_Type; Context : in AES_Enc_Context_Type; IV : in LSC.Internal.AES.Block_Type); pragma Inline (CBC_Encrypt); function Create_AES128_Dec_Context (Key : LSC.Internal.AES.AES128_Key_Type) return AES_Dec_Context_Type; function Create_AES192_Dec_Context (Key : LSC.Internal.AES.AES192_Key_Type) return AES_Dec_Context_Type; function Create_AES256_Dec_Context (Key : LSC.Internal.AES.AES256_Key_Type) return AES_Dec_Context_Type; function Decrypt (Context : AES_Dec_Context_Type; Ciphertext : LSC.Internal.AES.Block_Type) return LSC.Internal.AES.Block_Type; pragma Inline (Decrypt); procedure CBC_Decrypt (Ciphertext : in LSC.Internal.AES.Message_Type; Plaintext : out LSC.Internal.AES.Message_Type; Context : in AES_Dec_Context_Type; IV : in LSC.Internal.AES.Block_Type); pragma Inline (CBC_Decrypt); ---------------------------------------------------------------------------- -- SHA-1 procedure SHA1_Context_Init (Context : out SHA1_Context_Type); procedure SHA1_Context_Update (Context : in out SHA1_Context_Type; Block : in LSC.Internal.SHA1.Block_Type); procedure SHA1_Context_Finalize (Context : in out SHA1_Context_Type; Block : in LSC.Internal.SHA1.Block_Type; Length : in LSC.Internal.SHA1.Block_Length_Type); pragma Inline (SHA1_Context_Update, SHA1_Context_Finalize); function SHA1_Get_Hash (Context : in SHA1_Context_Type) return LSC.Internal.SHA1.Hash_Type; ---------------------------------------------------------------------------- -- SHA-256 procedure SHA256_Context_Init (Context : out SHA256_Context_Type); procedure SHA256_Context_Update (Context : in out SHA256_Context_Type; Block : in LSC.Internal.SHA256.Block_Type); procedure SHA256_Context_Finalize (Context : in out SHA256_Context_Type; Block : in LSC.Internal.SHA256.Block_Type; Length : in LSC.Internal.SHA256.Block_Length_Type); pragma Inline (SHA256_Context_Update, SHA256_Context_Finalize); function SHA256_Get_Hash (Context : in SHA256_Context_Type) return LSC.Internal.SHA256.SHA256_Hash_Type; ---------------------------------------------------------------------------- -- SHA-384 procedure SHA384_Context_Init (Context : out SHA384_Context_Type); procedure SHA384_Context_Update (Context : in out SHA384_Context_Type; Block : in LSC.Internal.SHA512.Block_Type); procedure SHA384_Context_Finalize (Context : in out SHA384_Context_Type; Block : in LSC.Internal.SHA512.Block_Type; Length : in LSC.Internal.SHA512.Block_Length_Type); pragma Inline (SHA384_Context_Update, SHA384_Context_Finalize); function SHA384_Get_Hash (Context : in SHA384_Context_Type) return LSC.Internal.SHA512.SHA384_Hash_Type; ---------------------------------------------------------------------------- -- SHA-512 procedure SHA512_Context_Init (Context : out SHA512_Context_Type); procedure SHA512_Context_Update (Context : in out SHA512_Context_Type; Block : in LSC.Internal.SHA512.Block_Type); procedure SHA512_Context_Finalize (Context : in out SHA512_Context_Type; Block : in LSC.Internal.SHA512.Block_Type; Length : in LSC.Internal.SHA512.Block_Length_Type); pragma Inline (SHA512_Context_Update, SHA512_Context_Finalize); function SHA512_Get_Hash (Context : in SHA512_Context_Type) return LSC.Internal.SHA512.SHA512_Hash_Type; ---------------------------------------------------------------------------- -- RIPEMD-160 procedure RIPEMD160_Context_Init (Context : out RIPEMD160_Context_Type); procedure RIPEMD160_Context_Update (Context : in out RIPEMD160_Context_Type; Block : in LSC.Internal.RIPEMD160.Block_Type); procedure RIPEMD160_Context_Finalize (Context : in out RIPEMD160_Context_Type; Block : in LSC.Internal.RIPEMD160.Block_Type; Length : in LSC.Internal.RIPEMD160.Block_Length_Type); pragma Inline (RIPEMD160_Context_Update, RIPEMD160_Context_Finalize); function RIPEMD160_Get_Hash (Context : in RIPEMD160_Context_Type) return LSC.Internal.RIPEMD160.Hash_Type; ---------------------------------------------------------------------------- -- HMAC_SHA1 subtype SHA1_Message_Index is LSC.Internal.Types.Word64 range 1 .. 100; subtype SHA1_Message_Type is LSC.Internal.SHA1.Message_Type (SHA1_Message_Index); function Authenticate_SHA1 (Key : LSC.Internal.SHA1.Block_Type; Message : SHA1_Message_Type; Length : LSC.Internal.Types.Word64) return LSC.Internal.SHA1.Hash_Type; pragma Inline (Authenticate_SHA1); ---------------------------------------------------------------------------- -- HMAC_SHA256 subtype SHA256_Message_Index is LSC.Internal.SHA256.Message_Index range 1 .. 100; subtype SHA256_Message_Type is LSC.Internal.SHA256.Message_Type (SHA256_Message_Index); function Authenticate_SHA256 (Key : LSC.Internal.SHA256.Block_Type; Message : SHA256_Message_Type; Length : LSC.Internal.Types.Word64) return LSC.Internal.HMAC_SHA256.Auth_Type; pragma Inline (Authenticate_SHA256); ---------------------------------------------------------------------------- subtype SHA512_Message_Index is LSC.Internal.SHA512.Message_Index range 1 .. 100; subtype SHA512_Message_Type is LSC.Internal.SHA512.Message_Type (SHA512_Message_Index); -- HMAC_SHA384 function Authenticate_SHA384 (Key : LSC.Internal.SHA512.Block_Type; Message : SHA512_Message_Type; Length : LSC.Internal.Types.Word64) return LSC.Internal.HMAC_SHA384.Auth_Type; pragma Inline (Authenticate_SHA384); ---------------------------------------------------------------------------- -- HMAC_SHA512 function Authenticate_SHA512 (Key : LSC.Internal.SHA512.Block_Type; Message : SHA512_Message_Type; Length : LSC.Internal.Types.Word64) return LSC.Internal.HMAC_SHA512.Auth_Type; pragma Inline (Authenticate_SHA512); ---------------------------------------------------------------------------- -- HMAC_RMD160 subtype RMD160_Message_Index is LSC.Internal.Types.Word64 range 1 .. 100; subtype RMD160_Message_Type is LSC.Internal.RIPEMD160.Message_Type (RMD160_Message_Index); function Authenticate_RMD160 (Key : LSC.Internal.RIPEMD160.Block_Type; Message : RMD160_Message_Type; Length : LSC.Internal.Types.Word64) return LSC.Internal.RIPEMD160.Hash_Type; pragma Inline (Authenticate_RMD160); ---------------------------------------------------------------------------- -- RSA procedure RSA_Public_Encrypt (M : in LSC.Internal.Bignum.Big_Int; E : in LSC.Internal.Bignum.Big_Int; P : in LSC.Internal.Bignum.Big_Int; C : out LSC.Internal.Bignum.Big_Int; Success : out Boolean); procedure RSA_Private_Decrypt (M : in LSC.Internal.Bignum.Big_Int; E : in LSC.Internal.Bignum.Big_Int; D : in LSC.Internal.Bignum.Big_Int; C : in LSC.Internal.Bignum.Big_Int; P : out LSC.Internal.Bignum.Big_Int; Success : out Boolean); private pragma Linker_Options ("-lcrypto"); type SHA512_Block_Type_Ptr is access all LSC.Internal.SHA512.Block_Type; pragma Convention (C, SHA512_Block_Type_Ptr); type SHA256_Block_Type_Ptr is access all LSC.Internal.SHA256.Block_Type; pragma Convention (C, SHA256_Block_Type_Ptr); type SHA1_Block_Type_Ptr is access all LSC.Internal.SHA1.Block_Type; pragma Convention (C, SHA1_Block_Type_Ptr); type SHA512_Hash_Type_Ptr is access all LSC.Internal.SHA512.SHA512_Hash_Type; pragma Convention (C, SHA512_Hash_Type_Ptr); type SHA256_Hash_Type_Ptr is access all LSC.Internal.SHA256.SHA256_Hash_Type; pragma Convention (C, SHA256_Hash_Type_Ptr); type SHA1_Hash_Type_Ptr is access all LSC.Internal.SHA1.Hash_Type; pragma Convention (C, SHA1_Hash_Type_Ptr); type C_Context_Type is array (1 .. 512) of Character; pragma Convention (C, C_Context_Type); type C_Context_Ptr is access all C_Context_Type; pragma Convention (C, C_Context_Ptr); ---------------------------------------------------------------------------- -- SHA-1 C binding procedure C_SHA1_Init (Context : C_Context_Ptr); pragma Import (C, C_SHA1_Init, "SHA1_Init"); procedure C_SHA1_Update (Context : C_Context_Ptr; Data : SHA1_Block_Type_Ptr; Length : Interfaces.C.size_t); pragma Import (C, C_SHA1_Update, "SHA1_Update"); procedure C_SHA1_Final (MD : SHA1_Hash_Type_Ptr; Context : C_Context_Ptr); pragma Import (C, C_SHA1_Final, "SHA1_Final"); ---------------------------------------------------------------------------- -- SHA-256 C binding procedure C_SHA256_Init (Context : C_Context_Ptr); pragma Import (C, C_SHA256_Init, "SHA256_Init"); procedure C_SHA256_Update (Context : C_Context_Ptr; Data : SHA256_Block_Type_Ptr; Length : Interfaces.C.size_t); pragma Import (C, C_SHA256_Update, "SHA256_Update"); procedure C_SHA256_Final (MD : SHA256_Hash_Type_Ptr; Context : C_Context_Ptr); pragma Import (C, C_SHA256_Final, "SHA256_Final"); ---------------------------------------------------------------------------- -- SHA-384 C binding procedure C_SHA384_Init (Context : C_Context_Ptr); pragma Import (C, C_SHA384_Init, "SHA384_Init"); procedure C_SHA384_Update (Context : C_Context_Ptr; Data : SHA512_Block_Type_Ptr; Length : Interfaces.C.size_t); pragma Import (C, C_SHA384_Update, "SHA384_Update"); procedure C_SHA384_Final (MD : SHA512_Hash_Type_Ptr; Context : C_Context_Ptr); pragma Import (C, C_SHA384_Final, "SHA384_Final"); ---------------------------------------------------------------------------- -- SHA-512 C binding procedure C_SHA512_Init (Context : C_Context_Ptr); pragma Import (C, C_SHA512_Init, "SHA512_Init"); procedure C_SHA512_Update (Context : C_Context_Ptr; Data : SHA512_Block_Type_Ptr; Length : Interfaces.C.size_t); pragma Import (C, C_SHA512_Update, "SHA512_Update"); procedure C_SHA512_Final (MD : SHA512_Hash_Type_Ptr; Context : C_Context_Ptr); pragma Import (C, C_SHA512_Final, "SHA512_Final"); ---------------------------------------------------------------------------- -- RIPEMD C binding type RIPEMD160_Block_Type_Ptr is access all LSC.Internal.RIPEMD160.Block_Type; pragma Convention (C, RIPEMD160_Block_Type_Ptr); type RIPEMD160_Hash_Type_Ptr is access all LSC.Internal.RIPEMD160.Hash_Type; pragma Convention (C, RIPEMD160_Hash_Type_Ptr); procedure C_RIPEMD160_Init (Context : C_Context_Ptr); pragma Import (C, C_RIPEMD160_Init, "RIPEMD160_Init"); procedure C_RIPEMD160_Update (Context : C_Context_Ptr; Data : RIPEMD160_Block_Type_Ptr; Length : Interfaces.C.size_t); pragma Import (C, C_RIPEMD160_Update, "RIPEMD160_Update"); procedure C_RIPEMD160_Final (MD : RIPEMD160_Hash_Type_Ptr; Context : C_Context_Ptr); pragma Import (C, C_RIPEMD160_Final, "RIPEMD160_Final"); ---------------------------------------------------------------------------- -- AES C binding type Key_Ptr is access all LSC.Internal.AES.AES256_Key_Type; pragma Convention (C, Key_Ptr); type Block_Ptr is access all LSC.Internal.AES.Block_Type; pragma Convention (C, Block_Ptr); procedure C_AES_set_encrypt_key (UserKey : Key_Ptr; Bits : Interfaces.C.int; AESKey : C_Context_Ptr); pragma Import (C, C_AES_set_encrypt_key, "AES_set_encrypt_key"); procedure C_AES_encrypt (In_Block : Block_Ptr; Out_Block : Block_Ptr; AESKey : C_Context_Ptr); pragma Import (C, C_AES_encrypt, "AES_encrypt"); procedure C_AES_CBC_Encrypt (Input : System.Address; Output : System.Address; Length : LSC.Internal.Types.Word32; AESKey : C_Context_Ptr; IV : Block_Ptr; Enc : Interfaces.Unsigned_16); pragma Import (C, C_AES_CBC_Encrypt, "AES_cbc_encrypt"); procedure C_AES_set_decrypt_key (UserKey : Key_Ptr; Bits : Interfaces.C.int; AESKey : C_Context_Ptr); pragma Import (C, C_AES_set_decrypt_key, "AES_set_decrypt_key"); procedure C_AES_decrypt (In_Block : Block_Ptr; Out_Block : Block_Ptr; AESKey : C_Context_Ptr); pragma Import (C, C_AES_decrypt, "AES_decrypt"); ---------------------------------------------------------------------------- -- libglue/HMAC_SHA1 C binding type HMAC_SHA1_Key_Ptr is access all LSC.Internal.SHA1.Block_Type; pragma Convention (C, HMAC_SHA1_Key_Ptr); type HMAC_SHA1_Msg_Ptr is access all SHA1_Message_Type; pragma Convention (C, HMAC_SHA1_Msg_Ptr); type HMAC_SHA1_Auth_Ptr is access all LSC.Internal.SHA1.Hash_Type; pragma Convention (C, HMAC_SHA1_Auth_Ptr); procedure C_Authenticate_SHA1 (Key : HMAC_SHA1_Key_Ptr; Message : HMAC_SHA1_Msg_Ptr; Length : LSC.Internal.Types.Word64; Digest : HMAC_SHA1_Auth_Ptr); pragma Import (C, C_Authenticate_SHA1, "Authenticate_SHA1"); ---------------------------------------------------------------------------- -- libglue/HMAC_SHA256 C binding type HMAC_SHA256_Key_Ptr is access all LSC.Internal.SHA256.Block_Type; pragma Convention (C, HMAC_SHA256_Key_Ptr); type HMAC_SHA256_Msg_Ptr is access all SHA256_Message_Type; pragma Convention (C, HMAC_SHA256_Msg_Ptr); type HMAC_SHA256_Auth_Ptr is access all LSC.Internal.HMAC_SHA256.Auth_Type; pragma Convention (C, HMAC_SHA256_Auth_Ptr); procedure C_Authenticate_SHA256 (Key : HMAC_SHA256_Key_Ptr; Message : HMAC_SHA256_Msg_Ptr; Length : LSC.Internal.Types.Word64; Digest : HMAC_SHA256_Auth_Ptr); pragma Import (C, C_Authenticate_SHA256, "Authenticate_SHA256"); ---------------------------------------------------------------------------- type HMAC_SHA512_Key_Ptr is access all LSC.Internal.SHA512.Block_Type; pragma Convention (C, HMAC_SHA512_Key_Ptr); type HMAC_SHA512_Msg_Ptr is access all SHA512_Message_Type; pragma Convention (C, HMAC_SHA512_Msg_Ptr); -- libglue/HMAC_SHA384 C binding type HMAC_SHA384_Auth_Ptr is access all LSC.Internal.HMAC_SHA384.Auth_Type; pragma Convention (C, HMAC_SHA384_Auth_Ptr); procedure C_Authenticate_SHA384 (Key : HMAC_SHA512_Key_Ptr; Message : HMAC_SHA512_Msg_Ptr; Length : LSC.Internal.Types.Word64; Digest : HMAC_SHA384_Auth_Ptr); pragma Import (C, C_Authenticate_SHA384, "Authenticate_SHA384"); ---------------------------------------------------------------------------- -- libglue/HMAC_SHA512 C binding type HMAC_SHA512_Auth_Ptr is access all LSC.Internal.HMAC_SHA512.Auth_Type; pragma Convention (C, HMAC_SHA512_Auth_Ptr); procedure C_Authenticate_SHA512 (Key : HMAC_SHA512_Key_Ptr; Message : HMAC_SHA512_Msg_Ptr; Length : LSC.Internal.Types.Word64; Digest : HMAC_SHA512_Auth_Ptr); pragma Import (C, C_Authenticate_SHA512, "Authenticate_SHA512"); ---------------------------------------------------------------------------- -- libglue/HMAC_RMD160 C binding type HMAC_RMD160_Key_Ptr is access all LSC.Internal.RIPEMD160.Block_Type; pragma Convention (C, HMAC_RMD160_Key_Ptr); type HMAC_RMD160_Msg_Ptr is access all RMD160_Message_Type; pragma Convention (C, HMAC_RMD160_Msg_Ptr); type HMAC_RMD160_Auth_Ptr is access all LSC.Internal.RIPEMD160.Hash_Type; pragma Convention (C, HMAC_RMD160_Auth_Ptr); procedure C_Authenticate_RMD160 (Key : HMAC_RMD160_Key_Ptr; Message : HMAC_RMD160_Msg_Ptr; Length : LSC.Internal.Types.Word64; Digest : HMAC_RMD160_Auth_Ptr); pragma Import (C, C_Authenticate_RMD160, "Authenticate_RMD160"); ---------------------------------------------------------------------------- type AES_Enc_Context_Type is record C_Context : C_Context_Type; end record; type AES_Dec_Context_Type is record C_Context : C_Context_Type; end record; type SHA1_Context_Type is record C_Context : C_Context_Type; Hash : LSC.Internal.SHA1.Hash_Type; end record; type SHA256_Context_Type is record C_Context : C_Context_Type; Hash : LSC.Internal.SHA256.SHA256_Hash_Type; end record; type SHA384_Context_Type is record C_Context : C_Context_Type; Hash : LSC.Internal.SHA512.SHA384_Hash_Type; end record; type SHA512_Context_Type is record C_Context : C_Context_Type; Hash : LSC.Internal.SHA512.SHA512_Hash_Type; end record; type RIPEMD160_Context_Type is record C_Context : C_Context_Type; Hash : LSC.Internal.RIPEMD160.Hash_Type; end record; ---------------------------------------------------------------------------- -- RSA procedure C_RSA_Public_Encrypt (M : in System.Address; M_Length : in LSC.Internal.Types.Word64; E : in System.Address; E_Length : in LSC.Internal.Types.Word64; P : in System.Address; C : in System.Address; Result : in System.Address); pragma Import (C, C_RSA_Public_Encrypt, "c_rsa_public_encrypt"); procedure C_RSA_Private_Decrypt (M : in System.Address; M_Length : in LSC.Internal.Types.Word64; E : in System.Address; E_Length : in LSC.Internal.Types.Word64; D : in System.Address; D_Length : in LSC.Internal.Types.Word64; C : in System.Address; P : in System.Address; Result : in System.Address); pragma Import (C, C_RSA_Private_Decrypt, "c_rsa_private_decrypt"); end OpenSSL;
pragma License (Unrestricted); with Ada.Directories; with Ada.Hierarchical_File_Names; package GNAT.Directory_Operations is subtype Dir_Name_Str is String; subtype Dir_Type is Ada.Directories.Search_Type; Directory_Error : exception; -- Basic Directory operations procedure Change_Dir (Dir_Name : Dir_Name_Str) renames Ada.Directories.Set_Directory; procedure Make_Dir (Dir_Name : Dir_Name_Str); procedure Remove_Dir ( Dir_Name : Dir_Name_Str; Recursive : Boolean := False); function Get_Current_Dir return Dir_Name_Str renames Ada.Directories.Current_Directory; -- Pathname Operations subtype Path_Name is String; function Dir_Name (Path : Path_Name) return Dir_Name_Str renames Ada.Hierarchical_File_Names.Containing_Directory; function Base_Name (Path : Path_Name; Suffix : String := "") return String; function File_Extension (Path : Path_Name) return String renames Ada.Hierarchical_File_Names.Extension; type Path_Style is (System_Default); function Format_Pathname ( Path : Path_Name; Style : Path_Style := System_Default) return Path_Name; -- Iterators procedure Open (Dir : in out Dir_Type; Dir_Name : Dir_Name_Str); procedure Close (Dir : in out Dir_Type) renames Ada.Directories.End_Search; procedure Read ( Dir : in out Dir_Type; Str : out String; Last : out Natural); end GNAT.Directory_Operations;
------------------------------------------------------------------------------ -- -- -- Hardware Abstraction Layer for STM32 Targets -- -- -- -- Copyright (C) 2014, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- This file provides Reset and Clock Control definitions for the STM32F4 -- (ARM Cortex M4F) microcontrollers from ST Microelectronics. pragma Restrictions (No_Elaboration_Code); with System; package STM32F4.RCC is type RCC_System_Clocks is record SYSCLK : Word; HCLK : Word; PCLK1 : Word; PCLK2 : Word; TIMCLK1 : Word; TIMCLK2 : Word; end record; function System_Clock_Frequencies return RCC_System_Clocks; procedure Set_PLLSAI_Factors (LCD : Bits_3; SAI1 : Bits_4; VCO : Bits_9; DivR : Bits_2); procedure Enable_PLLSAI; procedure GPIOA_Clock_Enable with Inline; procedure GPIOB_Clock_Enable with Inline; procedure GPIOC_Clock_Enable with Inline; procedure GPIOD_Clock_Enable with Inline; procedure GPIOE_Clock_Enable with Inline; procedure GPIOF_Clock_Enable with Inline; procedure GPIOG_Clock_Enable with Inline; procedure GPIOH_Clock_Enable with Inline; procedure GPIOI_Clock_Enable with Inline; procedure GPIOJ_Clock_Enable with Inline; procedure GPIOK_Clock_Enable with Inline; procedure CRC_Clock_Enable with Inline; procedure BKPSRAM_Clock_Enable with Inline; procedure CCMDATARAMEN_Clock_Enable with Inline; procedure DMA1_Clock_Enable with Inline; procedure DMA2_Clock_Enable with Inline; procedure GPIOA_Clock_Disable with Inline; procedure GPIOB_Clock_Disable with Inline; procedure GPIOC_Clock_Disable with Inline; procedure GPIOD_Clock_Disable with Inline; procedure GPIOE_Clock_Disable with Inline; procedure GPIOF_Clock_Disable with Inline; procedure GPIOG_Clock_Disable with Inline; procedure GPIOH_Clock_Disable with Inline; procedure GPIOI_Clock_Disable with Inline; procedure GPIOJ_Clock_Disable with Inline; procedure GPIOK_Clock_Disable with Inline; procedure CRC_Clock_Disable with Inline; procedure BKPSRAM_Clock_Disable with Inline; procedure CCMDATARAMEN_Clock_Disable with Inline; procedure DMA1_Clock_Disable with Inline; procedure DMA2_Clock_Disable with Inline; procedure RNG_Clock_Enable with Inline; procedure RNG_Clock_Disable with Inline; procedure TIM2_Clock_Enable with Inline; procedure TIM3_Clock_Enable with Inline; procedure TIM4_Clock_Enable with Inline; procedure TIM5_Clock_Enable with Inline; procedure TIM6_Clock_Enable with Inline; procedure TIM7_Clock_Enable with Inline; procedure TIM12_Clock_Enable with Inline; procedure TIM13_Clock_Enable with Inline; procedure TIM14_Clock_Enable with Inline; procedure WWDG_Clock_Enable with Inline; procedure SPI2_Clock_Enable with Inline; procedure SPI3_Clock_Enable with Inline; procedure USART2_Clock_Enable with Inline; procedure USART3_Clock_Enable with Inline; procedure UART4_Clock_Enable with Inline; procedure UART5_Clock_Enable with Inline; procedure UART7_Clock_Enable with Inline; procedure UART8_Clock_Enable with Inline; procedure I2C1_Clock_Enable with Inline; procedure I2C2_Clock_Enable with Inline; procedure I2C3_Clock_Enable with Inline; procedure PWR_Clock_Enable with Inline; procedure TIM2_Clock_Disable with Inline; procedure TIM3_Clock_Disable with Inline; procedure TIM4_Clock_Disable with Inline; procedure TIM5_Clock_Disable with Inline; procedure TIM6_Clock_Disable with Inline; procedure TIM7_Clock_Disable with Inline; procedure TIM12_Clock_Disable with Inline; procedure TIM13_Clock_Disable with Inline; procedure TIM14_Clock_Disable with Inline; procedure WWDG_Clock_Disable with Inline; procedure SPI2_Clock_Disable with Inline; procedure SPI3_Clock_Disable with Inline; procedure USART2_Clock_Disable with Inline; procedure USART3_Clock_Disable with Inline; procedure UART4_Clock_Disable with Inline; procedure UART5_Clock_Disable with Inline; procedure UART7_Clock_Disable with Inline; procedure UART8_Clock_Disable with Inline; procedure I2C1_Clock_Disable with Inline; procedure I2C2_Clock_Disable with Inline; procedure I2C3_Clock_Disable with Inline; procedure PWR_Clock_Disable with Inline; procedure TIM1_Clock_Enable with Inline; procedure TIM8_Clock_Enable with Inline; procedure USART1_Clock_Enable with Inline; procedure USART6_Clock_Enable with Inline; procedure ADC1_Clock_Enable with Inline; procedure SDIO_Clock_Enable with Inline; procedure SPI1_Clock_Enable with Inline; procedure SPI4_Clock_Enable with Inline; procedure SYSCFG_Clock_Enable with Inline; procedure TIM9_Clock_Enable with Inline; procedure TIM10_Clock_Enable with Inline; procedure TIM11_Clock_Enable with Inline; procedure SPI5_Clock_Enable with Inline; procedure SPI6_Clock_Enable with Inline; procedure LTDC_Clock_Enable with Inline; procedure TIM1_Clock_Disable with Inline; procedure TIM8_Clock_Disable with Inline; procedure USART1_Clock_Disable with Inline; procedure USART6_Clock_Disable with Inline; procedure ADC1_Clock_Disable with Inline; procedure SDIO_Clock_Disable with Inline; procedure SPI1_Clock_Disable with Inline; procedure SPI4_Clock_Disable with Inline; procedure SYSCFG_Clock_Disable with Inline; procedure TIM9_Clock_Disable with Inline; procedure TIM10_Clock_Disable with Inline; procedure TIM11_Clock_Disable with Inline; procedure SPI5_Clock_Disable with Inline; procedure SPI6_Clock_Disable with Inline; procedure LTDC_Clock_Disable with Inline; procedure AHB1_Force_Reset with Inline; procedure GPIOA_Force_Reset with Inline; procedure GPIOB_Force_Reset with Inline; procedure GPIOC_Force_Reset with Inline; procedure GPIOD_Force_Reset with Inline; procedure GPIOE_Force_Reset with Inline; procedure GPIOH_Force_Reset with Inline; procedure CRC_Force_Reset with Inline; procedure DMA1_Force_Reset with Inline; procedure DMA2_Force_Reset with Inline; procedure AHB1_Release_Reset with Inline; procedure GPIOA_Release_Reset with Inline; procedure GPIOB_Release_Reset with Inline; procedure GPIOC_Release_Reset with Inline; procedure GPIOD_Release_Reset with Inline; procedure GPIOE_Release_Reset with Inline; procedure GPIOF_Release_Reset with Inline; procedure GPIOG_Release_Reset with Inline; procedure GPIOH_Release_Reset with Inline; procedure GPIOI_Release_Reset with Inline; procedure CRC_Release_Reset with Inline; procedure DMA1_Release_Reset with Inline; procedure DMA2_Release_Reset with Inline; procedure AHB2_Force_Reset with Inline; procedure OTGFS_Force_Reset with Inline; procedure AHB2_Release_Reset with Inline; procedure OTGFS_Release_Reset with Inline; procedure RNG_Force_Reset with Inline; procedure RNG_Release_Reset with Inline; procedure APB1_Force_Reset with Inline; procedure TIM2_Force_Reset with Inline; procedure TIM3_Force_Reset with Inline; procedure TIM4_Force_Reset with Inline; procedure TIM5_Force_Reset with Inline; procedure TIM6_Force_Reset with Inline; procedure TIM7_Force_Reset with Inline; procedure TIM12_Force_Reset with Inline; procedure TIM13_Force_Reset with Inline; procedure TIM14_Force_Reset with Inline; procedure WWDG_Force_Reset with Inline; procedure SPI2_Force_Reset with Inline; procedure SPI3_Force_Reset with Inline; procedure USART2_Force_Reset with Inline; procedure I2C1_Force_Reset with Inline; procedure I2C2_Force_Reset with Inline; procedure I2C3_Force_Reset with Inline; procedure PWR_Force_Reset with Inline; procedure APB1_Release_Reset with Inline; procedure TIM2_Release_Reset with Inline; procedure TIM3_Release_Reset with Inline; procedure TIM4_Release_Reset with Inline; procedure TIM5_Release_Reset with Inline; procedure TIM6_Release_Reset with Inline; procedure TIM7_Release_Reset with Inline; procedure TIM12_Release_Reset with Inline; procedure TIM13_Release_Reset with Inline; procedure TIM14_Release_Reset with Inline; procedure WWDG_Release_Reset with Inline; procedure SPI2_Release_Reset with Inline; procedure SPI3_Release_Reset with Inline; procedure USART2_Release_Reset with Inline; procedure I2C1_Release_Reset with Inline; procedure I2C2_Release_Reset with Inline; procedure I2C3_Release_Reset with Inline; procedure PWR_Release_Reset with Inline; procedure APB2_Force_Reset with Inline; procedure TIM1_Force_Reset with Inline; procedure TIM8_Force_Reset with Inline; procedure USART1_Force_Reset with Inline; procedure USART6_Force_Reset with Inline; procedure ADC_Force_Reset with Inline; procedure SDIO_Force_Reset with Inline; procedure SPI1_Force_Reset with Inline; procedure SPI4_Force_Reset with Inline; procedure SYSCFG_Force_Reset with Inline; procedure TIM9_Force_Reset with Inline; procedure TIM10_Force_Reset with Inline; procedure TIM11_Force_Reset with Inline; procedure SPI5_Force_Reset with Inline; procedure SPI6_Force_Reset with Inline; procedure LTDC_Force_Reset with Inline; procedure APB2_Release_Reset with Inline; procedure TIM1_Release_Reset with Inline; procedure TIM8_Release_Reset with Inline; procedure USART1_Release_Reset with Inline; procedure USART6_Release_Reset with Inline; procedure ADC_Release_Reset with Inline; procedure SDIO_Release_Reset with Inline; procedure SPI1_Release_Reset with Inline; procedure SPI4_Release_Reset with Inline; procedure SYSCFG_Release_Reset with Inline; procedure TIM9_Release_Reset with Inline; procedure TIM10_Release_Reset with Inline; procedure TIM11_Release_Reset with Inline; procedure SPI5_Release_Reset with Inline; procedure SPI6_Release_Reset with Inline; procedure LTDC_Release_Reset with Inline; procedure FSMC_Clock_Enable with Inline; procedure FSMC_Clock_Disable with Inline; private type RCC_Registers is record CR : Word; -- clock control register at 16#00# PLLCFGR : Word; -- PLL configuration register at 16#04# CFGR : Word; -- clock configuration register at 16#08# CIR : Word; -- clock interrupt register at 16#0C# AHB1RSTR : Word; -- AHB1 peripheral reset register at 16#10# AHB2RSTR : Word; -- AHB2 peripheral reset register at 16#14# AHB3RSTR : Word; -- AHB3 peripheral reset register at 16#18# Reserved_0 : Word; -- Reserved at 16#1C# APB1RSTR : Word; -- APB1 peripheral reset register at 16#20# APB2RSTR : Word; -- APB2 peripheral reset register at 16#24# Reserved_1 : Word; -- Reserved at 16#28# Reserved_2 : Word; -- Reserved at 16#2c# AHB1ENR : Word; -- AHB1 peripheral clock register at 16#30# AHB2ENR : Word; -- AHB2 peripheral clock register at 16#34# AHB3ENR : Word; -- AHB3 peripheral clock register at 16#38# Reserved_3 : Word; -- Reserved at 16#0C# APB1ENR : Word; -- APB1 peripheral clock enable at 16#40# APB2ENR : Word; -- APB2 peripheral clock enable at 16#44# Reserved_4 : Word; -- Reserved at 16#48# Reserved_5 : Word; -- Reserved at 16#4c# AHB1LPENR : Word; -- AHB1 periph. low power clk en. at 16#50# AHB2LPENR : Word; -- AHB2 periph. low power clk en. at 16#54# AHB3LPENR : Word; -- AHB3 periph. low power clk en. at 16#58# Reserved_6 : Word; -- Reserved, 16#5C# APB1LPENR : Word; -- APB1 periph. low power clk en. at 16#60# APB2LPENR : Word; -- APB2 periph. low power clk en. at 16#64# Reserved_7 : Word; -- Reserved at 16#68# Reserved_8 : Word; -- Reserved at 16#6C# BDCR : Word; -- Backup domain control register at 16#70# CSR : Word; -- clock control/status register at 16#74# Reserved_9 : Word; -- Reserved at 16#78# Reserved_10 : Word; -- Reserved at 16#7C# SSCGR : Word; -- spread spectrum clk gen. reg. at 16#80# PLLI2SCFGR : Word; -- PLLI2S configuration register at 16#84# PLLSAICFGR : Word; -- PLLSAI configuration register at 16#88# DCKCFGR : Word; -- DCK configuration register at 16#8C# end record with Volatile; for RCC_Registers use record CR at 0 range 0 .. 31; PLLCFGR at 4 range 0 .. 31; CFGR at 8 range 0 .. 31; CIR at 12 range 0 .. 31; AHB1RSTR at 16 range 0 .. 31; AHB2RSTR at 20 range 0 .. 31; AHB3RSTR at 24 range 0 .. 31; Reserved_0 at 28 range 0 .. 31; APB1RSTR at 32 range 0 .. 31; APB2RSTR at 36 range 0 .. 31; Reserved_1 at 40 range 0 .. 31; Reserved_2 at 44 range 0 .. 31; AHB1ENR at 48 range 0 .. 31; AHB2ENR at 52 range 0 .. 31; AHB3ENR at 56 range 0 .. 31; Reserved_3 at 60 range 0 .. 31; APB1ENR at 64 range 0 .. 31; APB2ENR at 68 range 0 .. 31; Reserved_4 at 72 range 0 .. 31; Reserved_5 at 76 range 0 .. 31; AHB1LPENR at 80 range 0 .. 31; AHB2LPENR at 84 range 0 .. 31; AHB3LPENR at 88 range 0 .. 31; Reserved_6 at 92 range 0 .. 31; APB1LPENR at 96 range 0 .. 31; APB2LPENR at 100 range 0 .. 31; Reserved_7 at 104 range 0 .. 31; Reserved_8 at 108 range 0 .. 31; BDCR at 112 range 0 .. 31; CSR at 116 range 0 .. 31; Reserved_9 at 120 range 0 .. 31; Reserved_10 at 124 range 0 .. 31; SSCGR at 128 range 0 .. 31; PLLI2SCFGR at 132 range 0 .. 31; PLLSAICFGR at 136 range 0 .. 31; DCKCFGR at 140 range 0 .. 31; end record; Register : RCC_Registers with Volatile, Address => System'To_Address (RCC_Base); --------------------- Constants for RCC_CR register --------------------- HSION : constant := 16#00000001#; HSIRDY : constant := 16#00000002#; HSITRIM : constant := 16#000000F8#; HSITRIM_0 : constant := 16#00000008#; -- Bit 0 HSITRIM_1 : constant := 16#00000010#; -- Bit 1 HSITRIM_2 : constant := 16#00000020#; -- Bit 2 HSITRIM_3 : constant := 16#00000040#; -- Bit 3 HSITRIM_4 : constant := 16#00000080#; -- Bit 4 HSICAL : constant := 16#0000FF00#; HSICAL_0 : constant := 16#00000100#; -- Bit 0 HSICAL_1 : constant := 16#00000200#; -- Bit 1 HSICAL_2 : constant := 16#00000400#; -- Bit 2 HSICAL_3 : constant := 16#00000800#; -- Bit 3 HSICAL_4 : constant := 16#00001000#; -- Bit 4 HSICAL_5 : constant := 16#00002000#; -- Bit 5 HSICAL_6 : constant := 16#00004000#; -- Bit 6 HSICAL_7 : constant := 16#00008000#; -- Bit 7 HSEON : constant := 16#00010000#; HSERDY : constant := 16#00020000#; HSEBYP : constant := 16#00040000#; CSSON : constant := 16#00080000#; PLLON : constant := 16#01000000#; PLLRDY : constant := 16#02000000#; PLLI2SON : constant := 16#04000000#; PLLI2SRDY : constant := 16#08000000#; ------------------ Constants for RCC_PLLCFGR register -------------------- PLLM : constant := 16#0000003F#; PLLM_0 : constant := 16#00000001#; PLLM_1 : constant := 16#00000002#; PLLM_2 : constant := 16#00000004#; PLLM_3 : constant := 16#00000008#; PLLM_4 : constant := 16#00000010#; PLLM_5 : constant := 16#00000020#; PLLN : constant := 16#00007FC0#; PLLN_0 : constant := 16#00000040#; PLLN_1 : constant := 16#00000080#; PLLN_2 : constant := 16#00000100#; PLLN_3 : constant := 16#00000200#; PLLN_4 : constant := 16#00000400#; PLLN_5 : constant := 16#00000800#; PLLN_6 : constant := 16#00001000#; PLLN_7 : constant := 16#00002000#; PLLN_8 : constant := 16#00004000#; PLLP : constant := 16#00030000#; PLLP_0 : constant := 16#00010000#; PLLP_1 : constant := 16#00020000#; PLLSRC : constant := 16#00400000#; PLLSRC_HSE : constant := 16#00400000#; PLLSRC_HSI : constant := 16#00000000#; PLLQ : constant := 16#0F000000#; PLLQ_0 : constant := 16#01000000#; PLLQ_1 : constant := 16#02000000#; PLLQ_2 : constant := 16#04000000#; PLLQ_3 : constant := 16#08000000#; ------------------ Constants for RCC_CFGR register --------------------- -- SW configuration SW : constant := 16#00000003#; -- SW[1:0] bits (System clock Switch) SW_0 : constant := 16#00000001#; -- Bit 0 SW_1 : constant := 16#00000002#; -- Bit 1 SW_HSI : constant := 16#00000000#; -- HSI selected as system clock SW_HSE : constant := 16#00000001#; -- HSE selected as system clock SW_PLL : constant := 16#00000002#; -- PLL selected as system clock -- SWS configuration SWS : constant := 16#0000000C#; -- System Clock Switch Status bits SWS_0 : constant := 16#00000004#; -- Bit 0 SWS_1 : constant := 16#00000008#; -- Bit 1 SWS_HSI : constant := 16#00000000#; -- HSI used as system clock SWS_HSE : constant := 16#00000004#; -- HSE used as system clock SWS_PLL : constant := 16#00000008#; -- PLL used as system clock -- HPRE configuration HPRE : constant := 16#000000F0#; -- HPRE[3:0] bits (AHB prescaler) HPRE_0 : constant := 16#00000010#; -- Bit 0 HPRE_1 : constant := 16#00000020#; -- Bit 1 HPRE_2 : constant := 16#00000040#; -- Bit 2 HPRE_3 : constant := 16#00000080#; -- Bit 3 HPRE_DIV1 : constant := 16#00000000#; -- SYSCLK not divided HPRE_DIV2 : constant := 16#00000080#; -- SYSCLK divided by 2 HPRE_DIV4 : constant := 16#00000090#; -- SYSCLK divided by 4 HPRE_DIV8 : constant := 16#000000A0#; -- SYSCLK divided by 8 HPRE_DIV16 : constant := 16#000000B0#; -- SYSCLK divided by 16 HPRE_DIV64 : constant := 16#000000C0#; -- SYSCLK divided by 64 HPRE_DIV128 : constant := 16#000000D0#; -- SYSCLK divided by 128 HPRE_DIV256 : constant := 16#000000E0#; -- SYSCLK divided by 256 HPRE_DIV512 : constant := 16#000000F0#; -- SYSCLK divided by 512 -- PPRE1 configuration PPRE1 : constant := 16#00001C00#; -- APB1 prescaler bits PPRE1_0 : constant := 16#00000400#; -- Bit 0 PPRE1_1 : constant := 16#00000800#; -- Bit 1 PPRE1_2 : constant := 16#00001000#; -- Bit 2 PPRE1_DIV1 : constant := 16#00000000#; -- HCLK not divided PPRE1_DIV2 : constant := 16#00001000#; -- HCLK divided by 2 PPRE1_DIV4 : constant := 16#00001400#; -- HCLK divided by 4 PPRE1_DIV8 : constant := 16#00001800#; -- HCLK divided by 8 PPRE1_DIV16 : constant := 16#00001C00#; -- HCLK divided by 16 -- PPRE2 configuration PPRE2 : constant := 16#0000E000#; -- APB2 prescaler bits PPRE2_0 : constant := 16#00002000#; -- Bit 0 PPRE2_1 : constant := 16#00004000#; -- Bit 1 PPRE2_2 : constant := 16#00008000#; -- Bit 2 PPRE2_DIV1 : constant := 16#00000000#; -- HCLK not divided PPRE2_DIV2 : constant := 16#00008000#; -- HCLK divided by 2 PPRE2_DIV4 : constant := 16#0000A000#; -- HCLK divided by 4 PPRE2_DIV8 : constant := 16#0000C000#; -- HCLK divided by 8 PPRE2_DIV16 : constant := 16#0000E000#; -- HCLK divided by 16 -- RTCPRE configuration RTCPRE : constant := 16#001F0000#; RTCPRE_0 : constant := 16#00010000#; RTCPRE_1 : constant := 16#00020000#; RTCPRE_2 : constant := 16#00040000#; RTCPRE_3 : constant := 16#00080000#; RTCPRE_4 : constant := 16#00100000#; -- MCO1 configuration MCO1 : constant := 16#00600000#; MCO1_0 : constant := 16#00200000#; MCO1_1 : constant := 16#00400000#; I2SSRC : constant := 16#00800000#; MCO1PRE : constant := 16#07000000#; MCO1PRE_0 : constant := 16#01000000#; MCO1PRE_1 : constant := 16#02000000#; MCO1PRE_2 : constant := 16#04000000#; MCO2PRE : constant := 16#38000000#; MCO2PRE_0 : constant := 16#08000000#; MCO2PRE_1 : constant := 16#10000000#; MCO2PRE_2 : constant := 16#20000000#; MCO2 : constant := 16#C0000000#; MCO2_0 : constant := 16#40000000#; MCO2_1 : constant := 16#80000000#; ------------------ Constants for RCC_CIR register ------------------------ LSIRDYF : constant := 16#00000001#; LSERDYF : constant := 16#00000002#; HSIRDYF : constant := 16#00000004#; HSERDYF : constant := 16#00000008#; PLLRDYF : constant := 16#00000010#; PLLI2SRDYF : constant := 16#00000020#; CSSF : constant := 16#00000080#; LSIRDYIE : constant := 16#00000100#; LSERDYIE : constant := 16#00000200#; HSIRDYIE : constant := 16#00000400#; HSERDYIE : constant := 16#00000800#; PLLRDYIE : constant := 16#00001000#; PLLI2SRDYIE : constant := 16#00002000#; LSIRDYC : constant := 16#00010000#; LSERDYC : constant := 16#00020000#; HSIRDYC : constant := 16#00040000#; HSERDYC : constant := 16#00080000#; PLLRDYC : constant := 16#00100000#; PLLI2SRDYC : constant := 16#00200000#; CSSC : constant := 16#00800000#; ------------------ Constants for RCC_AHB1RSTR register ------------------- -- Note: we include the prefix for the sake of being able to check, when -- using the constants, that they are being assigned to the right bus. AHB1RSTR_GPIOARST : constant := 16#00000001#; AHB1RSTR_GPIOBRST : constant := 16#00000002#; AHB1RSTR_GPIOCRST : constant := 16#00000004#; AHB1RSTR_GPIODRST : constant := 16#00000008#; AHB1RSTR_GPIOERST : constant := 16#00000010#; AHB1RSTR_GPIOFRST : constant := 16#00000020#; AHB1RSTR_GPIOGRST : constant := 16#00000040#; AHB1RSTR_GPIOHRST : constant := 16#00000080#; AHB1RSTR_GPIOIRST : constant := 16#00000100#; AHB1RSTR_CRCRST : constant := 16#00001000#; AHB1RSTR_DMA1RST : constant := 16#00200000#; AHB1RSTR_DMA2RST : constant := 16#00400000#; AHB1RSTR_ETHMACRST : constant := 16#02000000#; AHB1RSTR_OTGHRST : constant := 16#10000000#; ------------------ Constants for RCC_AHB2RSTR register ------------------- AHB2RSTR_DCMIRST : constant := 16#00000001#; AHB2RSTR_RNGRST : constant := 16#00000040#; AHB2RSTR_OTGFSRST : constant := 16#00000080#; ------------------ Constants for RCC_AHB3RSTR register ------------------- AHB3RSTR_FSMCRST : constant := 16#00000001#; ------------------ Constants for RCC_APB1RSTR register ------------------- APB1RSTR_TIM2RST : constant := 16#00000001#; APB1RSTR_TIM3RST : constant := 16#00000002#; APB1RSTR_TIM4RST : constant := 16#00000004#; APB1RSTR_TIM5RST : constant := 16#00000008#; APB1RSTR_TIM6RST : constant := 16#00000010#; APB1RSTR_TIM7RST : constant := 16#00000020#; APB1RSTR_TIM12RST : constant := 16#00000040#; APB1RSTR_TIM13RST : constant := 16#00000080#; APB1RSTR_TIM14RST : constant := 16#00000100#; APB1RSTR_WWDGRST : constant := 16#00000800#; APB1RSTR_SPI2RST : constant := 16#00004000#; APB1RSTR_SPI3RST : constant := 16#00008000#; APB1RSTR_USART2RST : constant := 16#00020000#; APB1RSTR_USART3RST : constant := 16#00040000#; APB1RSTR_UART4RST : constant := 16#00080000#; APB1RSTR_UART5RST : constant := 16#00100000#; APB1RSTR_I2C1RST : constant := 16#00200000#; APB1RSTR_I2C2RST : constant := 16#00400000#; APB1RSTR_I2C3RST : constant := 16#00800000#; APB1RSTR_CAN1RST : constant := 16#02000000#; APB1RSTR_CAN2RST : constant := 16#04000000#; APB1RSTR_PWRRST : constant := 16#10000000#; APB1RSTR_DACRST : constant := 16#20000000#; ------------------ Constants for RCC_APB2RSTR register ------------------- APB2RSTR_TIM1RST : constant := 16#00000001#; APB2RSTR_TIM8RST : constant := 16#00000002#; APB2RSTR_USART1RST : constant := 16#00000010#; APB2RSTR_USART6RST : constant := 16#00000020#; APB2RSTR_ADCRST : constant := 16#00000100#; APB2RSTR_SDIORST : constant := 16#00000800#; APB2RSTR_SPI1RST : constant := 16#00001000#; APB2RSTR_SPI4RST : constant := 16#00002000#; APB2RSTR_SYSCFGRST : constant := 16#00004000#; APB2RSTR_TIM9RST : constant := 16#00010000#; APB2RSTR_TIM10RST : constant := 16#00020000#; APB2RSTR_TIM11RST : constant := 16#00040000#; APB2RSTR_SPI5RST : constant := 16#00100000#; APB2RSTR_SPI6RST : constant := 16#00200000#; APB2RSTR_LTDCRST : constant := 16#04000000#; ------------------ Constants for RCC_AHB1ENR register -------------------- AHB1ENR_GPIOAEN : constant := 16#00000001#; AHB1ENR_GPIOBEN : constant := 16#00000002#; AHB1ENR_GPIOCEN : constant := 16#00000004#; AHB1ENR_GPIODEN : constant := 16#00000008#; AHB1ENR_GPIOEEN : constant := 16#00000010#; AHB1ENR_GPIOFEN : constant := 16#00000020#; AHB1ENR_GPIOGEN : constant := 16#00000040#; AHB1ENR_GPIOHEN : constant := 16#00000080#; AHB1ENR_GPIOIEN : constant := 16#00000100#; AHB1ENR_GPIOJEN : constant := 16#00000200#; AHB1ENR_GPIOKEN : constant := 16#00000400#; AHB1ENR_CRCEN : constant := 16#00001000#; AHB1ENR_BKPSRAMEN : constant := 16#00040000#; AHB1ENR_CCMDATARAMEN : constant := 16#00100000#; AHB1ENR_DMA1EN : constant := 16#00200000#; AHB1ENR_DMA2EN : constant := 16#00400000#; AHB1ENR_ETHMACEN : constant := 16#02000000#; AHB1ENR_ETHMACTXEN : constant := 16#04000000#; AHB1ENR_ETHMACRXEN : constant := 16#08000000#; AHB1ENR_ETHMACPTPEN : constant := 16#10000000#; AHB1ENR_OTGHSEN : constant := 16#20000000#; AHB1ENR_OTGHSULPIEN : constant := 16#40000000#; ------------------ Constants for RCC_AHB2ENR register -------------------- AHB2ENR_DCMIEN : constant := 16#00000001#; AHB2ENR_RNGEN : constant := 16#00000040#; AHB2ENR_OTGFSEN : constant := 16#00000080#; ------------------ Constants for RCC_AHB3ENR register -------------------- AHB3ENR_FSMCEN : constant := 16#00000001#; ------------------ Constants for RCC_APB1ENR register -------------------- APB1ENR_TIM2EN : constant := 16#00000001#; APB1ENR_TIM3EN : constant := 16#00000002#; APB1ENR_TIM4EN : constant := 16#00000004#; APB1ENR_TIM5EN : constant := 16#00000008#; APB1ENR_TIM6EN : constant := 16#00000010#; APB1ENR_TIM7EN : constant := 16#00000020#; APB1ENR_TIM12EN : constant := 16#00000040#; APB1ENR_TIM13EN : constant := 16#00000080#; APB1ENR_TIM14EN : constant := 16#00000100#; APB1ENR_WWDGEN : constant := 16#00000800#; APB1ENR_SPI2EN : constant := 16#00004000#; APB1ENR_SPI3EN : constant := 16#00008000#; APB1ENR_USART2EN : constant := 16#00020000#; APB1ENR_USART3EN : constant := 16#00040000#; APB1ENR_UART4EN : constant := 16#00080000#; APB1ENR_UART5EN : constant := 16#00100000#; APB1ENR_I2C1EN : constant := 16#00200000#; APB1ENR_I2C2EN : constant := 16#00400000#; APB1ENR_I2C3EN : constant := 16#00800000#; APB1ENR_CAN1EN : constant := 16#02000000#; APB1ENR_CAN2EN : constant := 16#04000000#; APB1ENR_PWREN : constant := 16#10000000#; APB1ENR_DACEN : constant := 16#20000000#; APB1ENR_UART7EN : constant := 16#40000000#; APB1ENR_UART8EN : constant := 16#80000000#; ------------------ Constants for RCC_APB2ENR register -------------------- APB2ENR_TIM1EN : constant := 16#00000001#; APB2ENR_TIM8EN : constant := 16#00000002#; APB2ENR_USART1EN : constant := 16#00000010#; APB2ENR_USART6EN : constant := 16#00000020#; APB2ENR_ADC1EN : constant := 16#00000100#; APB2ENR_ADC2EN : constant := 16#00000200#; APB2ENR_ADC3EN : constant := 16#00000400#; APB2ENR_SDIOEN : constant := 16#00000800#; APB2ENR_SPI1EN : constant := 16#00001000#; APB2ENR_SPI4EN : constant := 16#00002000#; APB2ENR_SYSCFGEN : constant := 16#00004000#; APB2ENR_TIM9EN : constant := 16#00010000#; APB2ENR_TIM10EN : constant := 16#00020000#; APB2ENR_TIM11EN : constant := 16#00040000#; APB2ENR_SPI5EN : constant := 16#00100000#; APB2ENR_SPI6EN : constant := 16#00200000#; APB2ENR_LTDCEN : constant := 16#04000000#; ------------------ Constants for RCC_AHB1LPENR register ------------------ AHB1LPENR_GPIOALPEN : constant := 16#00000001#; AHB1LPENR_GPIOBLPEN : constant := 16#00000002#; AHB1LPENR_GPIOCLPEN : constant := 16#00000004#; AHB1LPENR_GPIODLPEN : constant := 16#00000008#; AHB1LPENR_GPIOELPEN : constant := 16#00000010#; AHB1LPENR_GPIOFLPEN : constant := 16#00000020#; AHB1LPENR_GPIOGLPEN : constant := 16#00000040#; AHB1LPENR_GPIOHLPEN : constant := 16#00000080#; AHB1LPENR_GPIOILPEN : constant := 16#00000100#; AHB1LPENR_CRCLPEN : constant := 16#00001000#; AHB1LPENR_FLITFLPEN : constant := 16#00008000#; AHB1LPENR_SRAM1LPEN : constant := 16#00010000#; AHB1LPENR_SRAM2LPEN : constant := 16#00020000#; AHB1LPENR_BKPSRAMLPEN : constant := 16#00040000#; AHB1LPENR_SRAM3LPEN : constant := 16#00080000#; AHB1LPENR_DMA1LPEN : constant := 16#00200000#; AHB1LPENR_DMA2LPEN : constant := 16#00400000#; AHB1LPENR_ETHMACLPEN : constant := 16#02000000#; AHB1LPENR_ETHMACTXLPEN : constant := 16#04000000#; AHB1LPENR_ETHMACRXLPEN : constant := 16#08000000#; AHB1LPENR_ETHMACPTPLPEN : constant := 16#10000000#; AHB1LPENR_OTGHSLPEN : constant := 16#20000000#; AHB1LPENR_OTGHSULPILPEN : constant := 16#40000000#; ------------------ Constants for RCC_AHB2LPENR register ------------------ AHB2LPENR_DCMILPEN : constant := 16#00000001#; AHB2LPENR_RNGLPEN : constant := 16#00000040#; AHB2LPENR_OTGFSLPEN : constant := 16#00000080#; ------------------ Constants for RCC_AHB3LPENR register ------------------ AHB3LPENR_FSMCLPEN : constant := 16#00000001#; ------------------ Constants for RCC_APB1LPENR register ------------------ APB1LPENR_TIM2LPEN : constant := 16#00000001#; APB1LPENR_TIM3LPEN : constant := 16#00000002#; APB1LPENR_TIM4LPEN : constant := 16#00000004#; APB1LPENR_TIM5LPEN : constant := 16#00000008#; APB1LPENR_TIM6LPEN : constant := 16#00000010#; APB1LPENR_TIM7LPEN : constant := 16#00000020#; APB1LPENR_TIM12LPEN : constant := 16#00000040#; APB1LPENR_TIM13LPEN : constant := 16#00000080#; APB1LPENR_TIM14LPEN : constant := 16#00000100#; APB1LPENR_WWDGLPEN : constant := 16#00000800#; APB1LPENR_SPI2LPEN : constant := 16#00004000#; APB1LPENR_SPI3LPEN : constant := 16#00008000#; APB1LPENR_USART2LPEN : constant := 16#00020000#; APB1LPENR_USART3LPEN : constant := 16#00040000#; APB1LPENR_UART4LPEN : constant := 16#00080000#; APB1LPENR_UART5LPEN : constant := 16#00100000#; APB1LPENR_I2C1LPEN : constant := 16#00200000#; APB1LPENR_I2C2LPEN : constant := 16#00400000#; APB1LPENR_I2C3LPEN : constant := 16#00800000#; APB1LPENR_CAN1LPEN : constant := 16#02000000#; APB1LPENR_CAN2LPEN : constant := 16#04000000#; APB1LPENR_PWRLPEN : constant := 16#10000000#; APB1LPENR_DACLPEN : constant := 16#20000000#; ------------------ Constants for RCC_APB2LPENR register ------------------ APB2LPENR_TIM1LPEN : constant := 16#00000001#; APB2LPENR_TIM8LPEN : constant := 16#00000002#; APB2LPENR_USART1LPEN : constant := 16#00000010#; APB2LPENR_USART6LPEN : constant := 16#00000020#; APB2LPENR_ADC1LPEN : constant := 16#00000100#; APB2LPENR_ADC2LPEN : constant := 16#00000200#; APB2LPENR_ADC3LPEN : constant := 16#00000400#; APB2LPENR_SDIOLPEN : constant := 16#00000800#; APB2LPENR_SPI1LPEN : constant := 16#00001000#; APB2LPENR_SPI4LPEN : constant := 16#00002000#; APB2LPENR_SYSCFGLPEN : constant := 16#00004000#; APB2LPENR_TIM9LPEN : constant := 16#00010000#; APB2LPENR_TIM10LPEN : constant := 16#00020000#; APB2LPENR_TIM11LPEN : constant := 16#00040000#; APB2LPENR_SPI5LPEN : constant := 16#00100000#; APB2LPENR_SPI6LPEN : constant := 16#00200000#; APB2LPENR_LTDCLPEN : constant := 16#04000000#; ------------------ Constants for RCC_BDCR register --------------------- LSEON : constant := 16#00000001#; LSERDY : constant := 16#00000002#; LSEBYP : constant := 16#00000004#; RTCSEL : constant := 16#00000300#; RTCSEL_0 : constant := 16#00000100#; RTCSEL_1 : constant := 16#00000200#; RTCEN : constant := 16#00008000#; BDRST : constant := 16#00010000#; ------------------ Constants for RCC_CSR register --------------------- LSION : constant := 16#00000001#; LSIRDY : constant := 16#00000002#; RMVF : constant := 16#01000000#; BORRSTF : constant := 16#02000000#; PADRSTF : constant := 16#04000000#; PORRSTF : constant := 16#08000000#; SFTRSTF : constant := 16#10000000#; WDGRSTF : constant := 16#20000000#; WWDGRSTF : constant := 16#40000000#; LPWRRSTF : constant := 16#80000000#; ------------------ Constants for RCC_SSCGR register --------------------- MODPER : constant := 16#00001FFF#; INCSTEP : constant := 16#0FFFE000#; SPREADSEL : constant := 16#40000000#; SSCGEN : constant := 16#80000000#; ------------------ Constants for RCC_PLLI2SCFGR register ----------------- PLLI2SN : constant := 16#00007FC0#; PLLI2SN_0 : constant := 16#00000040#; PLLI2SN_1 : constant := 16#00000080#; PLLI2SN_2 : constant := 16#00000100#; PLLI2SN_3 : constant := 16#00000200#; PLLI2SN_4 : constant := 16#00000400#; PLLI2SN_5 : constant := 16#00000800#; PLLI2SN_6 : constant := 16#00001000#; PLLI2SN_7 : constant := 16#00002000#; PLLI2SN_8 : constant := 16#00004000#; PLLI2SR : constant := 16#70000000#; PLLI2SR_0 : constant := 16#10000000#; PLLI2SR_1 : constant := 16#20000000#; PLLI2SR_2 : constant := 16#40000000#; end STM32F4.RCC;
-- { dg-do compile } -- { dg-options "-O2 -fdump-tree-optimized" } with Opt51_Pkg; use Opt51_Pkg; procedure Opt51 (E: Enum; F : out Float) is begin case (E) is when One => F := 1.0; when Two => F := 2.0; when Three => F := 3.0; when others => raise Program_Error; end case; end; -- { dg-final { scan-tree-dump-not "check_PE_Explicit_Raise" "optimized" } }
-------------------------------------------------------------------- --| Package : Stack_Package Version : 2.0 -------------------------------------------------------------------- --| Abstract : Specification of a classic stack. -------------------------------------------------------------------- --| File : Spec_Stack.ada --| Compiler/System : Alsys Ada - IBM AIX/370 --| Author : Dan Stubbs/Neil Webre Date : 2/27/92 --| References : Stubbs & Webre, Data Structures with Abstract --| Data Types and Ada, Brooks/Cole, 1993, Chapter 3. -------------------------------------------------------------------- generic type object_type is private; package stack_package is type stack (max_size : positive) is limited private; stack_empty : exception; stack_full : exception; procedure push (the_stack : in out stack; the_object : object_type); -- -- Results : Pushes the_object onto the_stack. -- -- Exceptions : stack_empty is raised if the stack contains -- max_size objects. -- procedure pop (the_stack : in out stack); -- -- Results : Returns, and removes from the_stack, the_object -- most recently pushed onto the_stack. -- -- Exceptions : stack_empty is raised if the_stack is empty. -- function top (the_stack : stack) return object_type; -- -- Results : Returns the object most recently pushed onto -- the_stack. -- -- Exceptions : stack_empty is raised if the_stack is empty. -- procedure clear (the_stack : in out stack); -- -- Results : Sets the number of objects in the_stack to zero. -- function number_of_objects (the_stack : stack) return natural; -- -- Results : Returns the number of objects in the_stack. -- generic with procedure process (the_object : object_type); procedure iterate (the_stack : stack); -- -- Results : Procedure process is applied to each object -- in the_stack. The order in which the objects are -- processed is NOT specified. -- procedure copy (the_stack : stack; the_copy : in out stack); -- -- Results : the_copy is a duplicate of the_stack. -- -- note : Consider using an instantiation of iterate to -- construct the copy. Can it be done? generic with function delete_this_object (the_object : object_type) return boolean; procedure prune_stack (the_stack : in out stack); -- -- Results : Delete from the_stack all objects for which -- delete_this_object is true. -- private type array_of_objects is array (positive range <>) of object_type; type stack (max_size : positive) is record latest : natural := 0; objects : array_of_objects (1 .. max_size); end record; end stack_package; package body stack_package is procedure push (the_stack : in out stack; the_object : object_type) is -- -- Length 4 Complexity 2 Performance O(1) -- begin the_stack.objects(the_stack.latest + 1) := the_object; the_stack.latest := the_stack.latest + 1; exception when constraint_error => raise stack_full; end push; procedure pop (the_stack : in out stack) is -- -- Length 2 Complexity 2 Performance O(1) -- begin the_stack.latest := the_stack.latest - 1; exception when constraint_error | numeric_error => raise stack_empty; end pop; function top (the_stack : stack) return object_type is -- -- Length 2 Complexity 2 Performance O(1) -- begin return the_stack.objects(the_stack.latest); exception when constraint_error => raise stack_empty; end top; procedure clear (the_stack : in out stack) is -- -- Length 1 Complexity 1 Performance O(1); -- begin the_stack.latest := 0; end Clear; function number_of_objects (the_stack : stack) return natural is -- -- Length 1 Complexity 1 Performance O(1) -- begin return the_stack.latest; end number_of_objects; procedure iterate (the_stack : stack) is -- -- Length 2 Complexity 2 Performance O(n) -- begin for index in 1 .. the_stack.latest loop process (the_stack.objects(index)); end loop; end iterate; procedure copy (the_stack : stack; the_copy : in out stack) is -- -- Length 5 Complexity 2 Performance O(n) -- begin if the_copy.max_size < the_stack.latest then raise stack_full; else the_copy.objects(1 .. the_stack.latest) := the_stack.objects(1 .. the_stack.latest); the_copy.latest := the_stack.latest; end if; end copy; procedure prune_stack (the_stack : in out stack) is -- -- Length 6 Complexity 3 Performance O(n) -- destination : natural := 0; begin for k in 1 .. the_stack.latest loop if not delete_this_object(the_stack.objects(k)) then destination := destination + 1; the_stack.objects(destination) := the_stack.objects(k); end if; end loop; the_stack.latest := destination; end prune_stack; end stack_package;
with P_StructuralTypes; use P_StructuralTypes; with Ada.Integer_Text_IO; with Ada.Sequential_IO; with Ada.Strings.Unbounded.Text_IO; with Ada.Text_IO; package body P_StepHandler.OutputHandler is ------------------------------------------------------------------------- ------------------------- CONSTRUCTOR ----------------------------------- ------------------------------------------------------------------------- function Make (Self : in out OutputHandler) return OutputHandler is begin Self.Ptr_BinaryContainer := null; Self.NextHandler := null; return Self; end; --------------------------------------------------------------- --- HANDLE PROCEDURE : OVERRIDEN FROM PARENT ABSTRACT CLASS --- --------------------------------------------------------------- overriding procedure Handle (Self : in out OutputHandler) is package Char_IO is new Ada.Sequential_IO (Character); use Char_IO; Output : File_Type; Byte : T_Byte; CharCode : Integer; begin ------------------------------------------------------------------------- -- This handler has two tasks : -- => Loop through the coded data in the binary container -- => Convert these blocks into character before inserting them into the -- output file ------------------------------------------------------------------------- Create (Output, Out_File, To_String(Self.Output_Name)); for i in Self.Ptr_BinaryContainer.all'Range loop for j in 1..8 loop Byte := Self.Ptr_BinaryContainer.all(i)(8*(j-1)+1..8*j); CharCode := Byte_To_CharacterCode(Byte); Write (Output,Character'Val(CharCode)); end loop; end loop; Close (Output); if Self.NextHandler /= null then Self.NextHandler.Handle; end if; end Handle; procedure Set_PaddingBitNumber (Self : in out OutputHandler ; Number : in Integer) is begin Self.PaddingBitNumber := Number; end; procedure Set_Output_Name (Self : in out OutputHandler; Name : Unbounded_String) is begin Self.Output_Name := Name; end; end P_StepHandler.OutputHandler;
with GMP; private with C.mpfr; package MPFR is pragma Preelaborate; pragma Linker_Options ("-lmpfr"); function Version return String; subtype Number_Base is GMP.Number_Base; type Precision is mod 2 ** GMP.Exponent'Size; type Rounding is ( To_Nearest_With_Ties_Away_From_Zero, To_Nearest, Towards_Zero, Towards_Plus_Infinity, Towards_Minus_Infinity, Away_From_Zero, Faithful); function Default_Precision return Precision; function Default_Rounding return Rounding; private pragma Compile_Time_Error ( Precision'Last /= Precision (C.mpfr.mpfr_uprec_t'Last), "please adjust Precision as mpfr_uprec_t"); for Rounding use ( To_Nearest_With_Ties_Away_From_Zero => C.mpfr.mpfr_rnd_t'Enum_Rep (C.mpfr.MPFR_RNDNA), To_Nearest => C.mpfr.mpfr_rnd_t'Enum_Rep (C.mpfr.MPFR_RNDN), Towards_Zero => C.mpfr.mpfr_rnd_t'Enum_Rep (C.mpfr.MPFR_RNDZ), Towards_Plus_Infinity => C.mpfr.mpfr_rnd_t'Enum_Rep (C.mpfr.MPFR_RNDU), Towards_Minus_Infinity => C.mpfr.mpfr_rnd_t'Enum_Rep (C.mpfr.MPFR_RNDD), Away_From_Zero => C.mpfr.mpfr_rnd_t'Enum_Rep (C.mpfr.MPFR_RNDA), Faithful => C.mpfr.mpfr_rnd_t'Enum_Rep (C.mpfr.MPFR_RNDF)); end MPFR;
-- SPDX-FileCopyrightText: 2019 Max Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT ------------------------------------------------------------- with Ada.Strings.Wide_Wide_Fixed; with Ada.Wide_Wide_Characters.Handling; package body Program.GNAT_Unit_Naming is -------------------- -- Body_Text_Name -- -------------------- function Body_Text_Name (Self : GNAT_Unit_Naming; Name : Program.Text) return Program.Text is Lower_Text : constant Text := Ada.Wide_Wide_Characters.Handling.To_Lower (Name); Base_Name : constant Text := Ada.Strings.Wide_Wide_Fixed.Translate (Lower_Text, Self.Map); begin return Base_Name & ".adb"; end Body_Text_Name; --------------------------- -- Declaration_Text_Name -- --------------------------- overriding function Declaration_Text_Name (Self : GNAT_Unit_Naming; Name : Program.Text) return Program.Text is Lower_Text : constant Text := Ada.Wide_Wide_Characters.Handling.To_Lower (Name); Base_Name : constant Text := Ada.Strings.Wide_Wide_Fixed.Translate (Lower_Text, Self.Map); begin return Base_Name & ".ads"; end Declaration_Text_Name; ------------------------ -- Standard_Text_Name -- ------------------------ overriding function Standard_Text_Name (Self : GNAT_Unit_Naming) return Text is pragma Unreferenced (Self); begin return "_standard_.ads"; end Standard_Text_Name; ----------------------- -- Subunit_Text_Name -- ----------------------- overriding function Subunit_Text_Name (Self : GNAT_Unit_Naming; Name : Program.Text) return Text renames Body_Text_Name; end Program.GNAT_Unit_Naming;
package body lace.Observer.deferred is package body Forge is function to_Observer (Name : in Event.observer_Name) return Item is begin return Self : constant Item := (Deferred.item with name => to_unbounded_String (Name)) do null; end return; end to_Observer; function new_Observer (Name : in Event.observer_Name) return View is Self : constant View := new Item' (to_Observer (Name)); begin return Self; end new_Observer; end Forge; overriding function Name (Self : in Item) return Event.observer_Name is begin return to_String (Self.Name); end Name; end lace.Observer.deferred;
----------------------------------------------------------------------- -- countries - A simple bean example -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Models.Selects; package body Countries is -- ------------------------------ -- Get a select item list which contains a list of countries. -- ------------------------------ function Create_Country_List return Util.Beans.Basic.Readonly_Bean_Access is use ASF.Models.Selects; Result : constant Select_Item_List_Access := new Select_Item_List; begin Result.Append (Label => "Andorra", Value => "AD"); Result.Append (Label => "Belgium", Value => "BE"); Result.Append (Label => "Canada", Value => "CA"); Result.Append (Label => "Denmark", Value => "DK"); Result.Append (Label => "Estonia", Value => "EE"); Result.Append (Label => "France", Value => "fr"); Result.Append (Label => "Germany", Value => "DE"); Result.Append (Label => "Hungary", Value => "HU"); Result.Append (Label => "Italy", Value => "IT"); Result.Append (Label => "Japan", Value => "JP"); Result.Append (Label => "Kosovo", Value => "XK"); Result.Append (Label => "Luxembourg", Value => "LT"); Result.Append (Label => "Martinique", Value => "MQ"); Result.Append (Label => "Netherlands", Value => "NL"); Result.Append (Label => "Oman", Value => "OM"); Result.Append (Label => "Portugal", Value => "PT"); Result.Append (Label => "Qatar", Value => "QA"); Result.Append (Label => "Russia", Value => "RU"); Result.Append (Label => "Spain", Value => "ES"); Result.Append (Label => "Taiwan", Value => "TW"); Result.Append (Label => "United States", Value => "US"); Result.Append (Label => "Vietnam", Value => "VN"); Result.Append (Label => "Western Sahara", Value => "EH"); Result.Append (Label => "Yemen", Value => "YE"); Result.Append (Label => "Zambia", Value => "ZM"); return Result.all'Access; end Create_Country_List; end Countries;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- E X P _ C H 6 -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2006, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, -- -- Boston, MA 02110-1301, USA. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Atree; use Atree; with Checks; use Checks; with Debug; use Debug; with Einfo; use Einfo; with Errout; use Errout; with Elists; use Elists; with Exp_Ch2; use Exp_Ch2; with Exp_Ch3; use Exp_Ch3; with Exp_Ch7; use Exp_Ch7; with Exp_Ch9; use Exp_Ch9; with Exp_Dbug; use Exp_Dbug; with Exp_Disp; use Exp_Disp; with Exp_Dist; use Exp_Dist; with Exp_Intr; use Exp_Intr; with Exp_Pakd; use Exp_Pakd; with Exp_Tss; use Exp_Tss; with Exp_Util; use Exp_Util; with Fname; use Fname; with Freeze; use Freeze; with Hostparm; use Hostparm; with Inline; use Inline; with Lib; use Lib; with Nlists; use Nlists; with Nmake; use Nmake; with Opt; use Opt; with Restrict; use Restrict; with Rident; use Rident; with Rtsfind; use Rtsfind; with Sem; use Sem; with Sem_Ch6; use Sem_Ch6; with Sem_Ch8; use Sem_Ch8; with Sem_Ch12; use Sem_Ch12; with Sem_Ch13; use Sem_Ch13; with Sem_Disp; use Sem_Disp; with Sem_Dist; use Sem_Dist; with Sem_Mech; use Sem_Mech; with Sem_Res; use Sem_Res; with Sem_Util; use Sem_Util; with Sinfo; use Sinfo; with Snames; use Snames; with Stand; use Stand; with Tbuild; use Tbuild; with Ttypes; use Ttypes; with Uintp; use Uintp; with Validsw; use Validsw; package body Exp_Ch6 is ----------------------- -- Local Subprograms -- ----------------------- procedure Check_Overriding_Operation (Subp : Entity_Id); -- Subp is a dispatching operation. Check whether it may override an -- inherited private operation, in which case its DT entry is that of -- the hidden operation, not the one it may have received earlier. -- This must be done before emitting the code to set the corresponding -- DT to the address of the subprogram. The actual placement of Subp in -- the proper place in the list of primitive operations is done in -- Declare_Inherited_Private_Subprograms, which also has to deal with -- implicit operations. This duplication is unavoidable for now??? procedure Detect_Infinite_Recursion (N : Node_Id; Spec : Entity_Id); -- This procedure is called only if the subprogram body N, whose spec -- has the given entity Spec, contains a parameterless recursive call. -- It attempts to generate runtime code to detect if this a case of -- infinite recursion. -- -- The body is scanned to determine dependencies. If the only external -- dependencies are on a small set of scalar variables, then the values -- of these variables are captured on entry to the subprogram, and if -- the values are not changed for the call, we know immediately that -- we have an infinite recursion. procedure Expand_Actuals (N : Node_Id; Subp : Entity_Id); -- For each actual of an in-out or out parameter which is a numeric -- (view) conversion of the form T (A), where A denotes a variable, -- we insert the declaration: -- -- Temp : T[ := T (A)]; -- -- prior to the call. Then we replace the actual with a reference to Temp, -- and append the assignment: -- -- A := TypeA (Temp); -- -- after the call. Here TypeA is the actual type of variable A. -- For out parameters, the initial declaration has no expression. -- If A is not an entity name, we generate instead: -- -- Var : TypeA renames A; -- Temp : T := Var; -- omitting expression for out parameter. -- ... -- Var := TypeA (Temp); -- -- For other in-out parameters, we emit the required constraint checks -- before and/or after the call. -- -- For all parameter modes, actuals that denote components and slices -- of packed arrays are expanded into suitable temporaries. -- -- For non-scalar objects that are possibly unaligned, add call by copy -- code (copy in for IN and IN OUT, copy out for OUT and IN OUT). procedure Expand_Inlined_Call (N : Node_Id; Subp : Entity_Id; Orig_Subp : Entity_Id); -- If called subprogram can be inlined by the front-end, retrieve the -- analyzed body, replace formals with actuals and expand call in place. -- Generate thunks for actuals that are expressions, and insert the -- corresponding constant declarations before the call. If the original -- call is to a derived operation, the return type is the one of the -- derived operation, but the body is that of the original, so return -- expressions in the body must be converted to the desired type (which -- is simply not noted in the tree without inline expansion). function Expand_Protected_Object_Reference (N : Node_Id; Scop : Entity_Id) return Node_Id; procedure Expand_Protected_Subprogram_Call (N : Node_Id; Subp : Entity_Id; Scop : Entity_Id); -- A call to a protected subprogram within the protected object may appear -- as a regular call. The list of actuals must be expanded to contain a -- reference to the object itself, and the call becomes a call to the -- corresponding protected subprogram. -------------------------------- -- Check_Overriding_Operation -- -------------------------------- procedure Check_Overriding_Operation (Subp : Entity_Id) is Typ : constant Entity_Id := Find_Dispatching_Type (Subp); Op_List : constant Elist_Id := Primitive_Operations (Typ); Op_Elmt : Elmt_Id; Prim_Op : Entity_Id; Par_Op : Entity_Id; begin if Is_Derived_Type (Typ) and then not Is_Private_Type (Typ) and then In_Open_Scopes (Scope (Etype (Typ))) and then Typ = Base_Type (Typ) then -- Subp overrides an inherited private operation if there is an -- inherited operation with a different name than Subp (see -- Derive_Subprogram) whose Alias is a hidden subprogram with the -- same name as Subp. Op_Elmt := First_Elmt (Op_List); while Present (Op_Elmt) loop Prim_Op := Node (Op_Elmt); Par_Op := Alias (Prim_Op); if Present (Par_Op) and then not Comes_From_Source (Prim_Op) and then Chars (Prim_Op) /= Chars (Par_Op) and then Chars (Par_Op) = Chars (Subp) and then Is_Hidden (Par_Op) and then Type_Conformant (Prim_Op, Subp) then Set_DT_Position (Subp, DT_Position (Prim_Op)); end if; Next_Elmt (Op_Elmt); end loop; end if; end Check_Overriding_Operation; ------------------------------- -- Detect_Infinite_Recursion -- ------------------------------- procedure Detect_Infinite_Recursion (N : Node_Id; Spec : Entity_Id) is Loc : constant Source_Ptr := Sloc (N); Var_List : constant Elist_Id := New_Elmt_List; -- List of globals referenced by body of procedure Call_List : constant Elist_Id := New_Elmt_List; -- List of recursive calls in body of procedure Shad_List : constant Elist_Id := New_Elmt_List; -- List of entity id's for entities created to capture the value of -- referenced globals on entry to the procedure. Scop : constant Uint := Scope_Depth (Spec); -- This is used to record the scope depth of the current procedure, so -- that we can identify global references. Max_Vars : constant := 4; -- Do not test more than four global variables Count_Vars : Natural := 0; -- Count variables found so far Var : Entity_Id; Elm : Elmt_Id; Ent : Entity_Id; Call : Elmt_Id; Decl : Node_Id; Test : Node_Id; Elm1 : Elmt_Id; Elm2 : Elmt_Id; Last : Node_Id; function Process (Nod : Node_Id) return Traverse_Result; -- Function to traverse the subprogram body (using Traverse_Func) ------------- -- Process -- ------------- function Process (Nod : Node_Id) return Traverse_Result is begin -- Procedure call if Nkind (Nod) = N_Procedure_Call_Statement then -- Case of one of the detected recursive calls if Is_Entity_Name (Name (Nod)) and then Has_Recursive_Call (Entity (Name (Nod))) and then Entity (Name (Nod)) = Spec then Append_Elmt (Nod, Call_List); return Skip; -- Any other procedure call may have side effects else return Abandon; end if; -- A call to a pure function can always be ignored elsif Nkind (Nod) = N_Function_Call and then Is_Entity_Name (Name (Nod)) and then Is_Pure (Entity (Name (Nod))) then return Skip; -- Case of an identifier reference elsif Nkind (Nod) = N_Identifier then Ent := Entity (Nod); -- If no entity, then ignore the reference -- Not clear why this can happen. To investigate, remove this -- test and look at the crash that occurs here in 3401-004 ??? if No (Ent) then return Skip; -- Ignore entities with no Scope, again not clear how this -- can happen, to investigate, look at 4108-008 ??? elsif No (Scope (Ent)) then return Skip; -- Ignore the reference if not to a more global object elsif Scope_Depth (Scope (Ent)) >= Scop then return Skip; -- References to types, exceptions and constants are always OK elsif Is_Type (Ent) or else Ekind (Ent) = E_Exception or else Ekind (Ent) = E_Constant then return Skip; -- If other than a non-volatile scalar variable, we have some -- kind of global reference (e.g. to a function) that we cannot -- deal with so we forget the attempt. elsif Ekind (Ent) /= E_Variable or else not Is_Scalar_Type (Etype (Ent)) or else Treat_As_Volatile (Ent) then return Abandon; -- Otherwise we have a reference to a global scalar else -- Loop through global entities already detected Elm := First_Elmt (Var_List); loop -- If not detected before, record this new global reference if No (Elm) then Count_Vars := Count_Vars + 1; if Count_Vars <= Max_Vars then Append_Elmt (Entity (Nod), Var_List); else return Abandon; end if; exit; -- If recorded before, ignore elsif Node (Elm) = Entity (Nod) then return Skip; -- Otherwise keep looking else Next_Elmt (Elm); end if; end loop; return Skip; end if; -- For all other node kinds, recursively visit syntactic children else return OK; end if; end Process; function Traverse_Body is new Traverse_Func; -- Start of processing for Detect_Infinite_Recursion begin -- Do not attempt detection in No_Implicit_Conditional mode, since we -- won't be able to generate the code to handle the recursion in any -- case. if Restriction_Active (No_Implicit_Conditionals) then return; end if; -- Otherwise do traversal and quit if we get abandon signal if Traverse_Body (N) = Abandon then return; -- We must have a call, since Has_Recursive_Call was set. If not just -- ignore (this is only an error check, so if we have a funny situation, -- due to bugs or errors, we do not want to bomb!) elsif Is_Empty_Elmt_List (Call_List) then return; end if; -- Here is the case where we detect recursion at compile time -- Push our current scope for analyzing the declarations and code that -- we will insert for the checking. New_Scope (Spec); -- This loop builds temporary variables for each of the referenced -- globals, so that at the end of the loop the list Shad_List contains -- these temporaries in one-to-one correspondence with the elements in -- Var_List. Last := Empty; Elm := First_Elmt (Var_List); while Present (Elm) loop Var := Node (Elm); Ent := Make_Defining_Identifier (Loc, Chars => New_Internal_Name ('S')); Append_Elmt (Ent, Shad_List); -- Insert a declaration for this temporary at the start of the -- declarations for the procedure. The temporaries are declared as -- constant objects initialized to the current values of the -- corresponding temporaries. Decl := Make_Object_Declaration (Loc, Defining_Identifier => Ent, Object_Definition => New_Occurrence_Of (Etype (Var), Loc), Constant_Present => True, Expression => New_Occurrence_Of (Var, Loc)); if No (Last) then Prepend (Decl, Declarations (N)); else Insert_After (Last, Decl); end if; Last := Decl; Analyze (Decl); Next_Elmt (Elm); end loop; -- Loop through calls Call := First_Elmt (Call_List); while Present (Call) loop -- Build a predicate expression of the form -- True -- and then global1 = temp1 -- and then global2 = temp2 -- ... -- This predicate determines if any of the global values -- referenced by the procedure have changed since the -- current call, if not an infinite recursion is assured. Test := New_Occurrence_Of (Standard_True, Loc); Elm1 := First_Elmt (Var_List); Elm2 := First_Elmt (Shad_List); while Present (Elm1) loop Test := Make_And_Then (Loc, Left_Opnd => Test, Right_Opnd => Make_Op_Eq (Loc, Left_Opnd => New_Occurrence_Of (Node (Elm1), Loc), Right_Opnd => New_Occurrence_Of (Node (Elm2), Loc))); Next_Elmt (Elm1); Next_Elmt (Elm2); end loop; -- Now we replace the call with the sequence -- if no-changes (see above) then -- raise Storage_Error; -- else -- original-call -- end if; Rewrite (Node (Call), Make_If_Statement (Loc, Condition => Test, Then_Statements => New_List ( Make_Raise_Storage_Error (Loc, Reason => SE_Infinite_Recursion)), Else_Statements => New_List ( Relocate_Node (Node (Call))))); Analyze (Node (Call)); Next_Elmt (Call); end loop; -- Remove temporary scope stack entry used for analysis Pop_Scope; end Detect_Infinite_Recursion; -------------------- -- Expand_Actuals -- -------------------- procedure Expand_Actuals (N : Node_Id; Subp : Entity_Id) is Loc : constant Source_Ptr := Sloc (N); Actual : Node_Id; Formal : Entity_Id; N_Node : Node_Id; Post_Call : List_Id; E_Formal : Entity_Id; procedure Add_Call_By_Copy_Code; -- For cases where the parameter must be passed by copy, this routine -- generates a temporary variable into which the actual is copied and -- then passes this as the parameter. For an OUT or IN OUT parameter, -- an assignment is also generated to copy the result back. The call -- also takes care of any constraint checks required for the type -- conversion case (on both the way in and the way out). procedure Add_Simple_Call_By_Copy_Code; -- This is similar to the above, but is used in cases where we know -- that all that is needed is to simply create a temporary and copy -- the value in and out of the temporary. procedure Check_Fortran_Logical; -- A value of type Logical that is passed through a formal parameter -- must be normalized because .TRUE. usually does not have the same -- representation as True. We assume that .FALSE. = False = 0. -- What about functions that return a logical type ??? function Is_Legal_Copy return Boolean; -- Check that an actual can be copied before generating the temporary -- to be used in the call. If the actual is of a by_reference type then -- the program is illegal (this can only happen in the presence of -- rep. clauses that force an incorrect alignment). If the formal is -- a by_reference parameter imposed by a DEC pragma, emit a warning to -- the effect that this might lead to unaligned arguments. function Make_Var (Actual : Node_Id) return Entity_Id; -- Returns an entity that refers to the given actual parameter, -- Actual (not including any type conversion). If Actual is an -- entity name, then this entity is returned unchanged, otherwise -- a renaming is created to provide an entity for the actual. procedure Reset_Packed_Prefix; -- The expansion of a packed array component reference is delayed in -- the context of a call. Now we need to complete the expansion, so we -- unmark the analyzed bits in all prefixes. --------------------------- -- Add_Call_By_Copy_Code -- --------------------------- procedure Add_Call_By_Copy_Code is Expr : Node_Id; Init : Node_Id; Temp : Entity_Id; Indic : Node_Id; Var : Entity_Id; F_Typ : constant Entity_Id := Etype (Formal); V_Typ : Entity_Id; Crep : Boolean; begin if not Is_Legal_Copy then return; end if; Temp := Make_Defining_Identifier (Loc, New_Internal_Name ('T')); -- Use formal type for temp, unless formal type is an unconstrained -- array, in which case we don't have to worry about bounds checks, -- and we use the actual type, since that has appropriate bounds. if Is_Array_Type (F_Typ) and then not Is_Constrained (F_Typ) then Indic := New_Occurrence_Of (Etype (Actual), Loc); else Indic := New_Occurrence_Of (Etype (Formal), Loc); end if; if Nkind (Actual) = N_Type_Conversion then V_Typ := Etype (Expression (Actual)); -- If the formal is an (in-)out parameter, capture the name -- of the variable in order to build the post-call assignment. Var := Make_Var (Expression (Actual)); Crep := not Same_Representation (F_Typ, Etype (Expression (Actual))); else V_Typ := Etype (Actual); Var := Make_Var (Actual); Crep := False; end if; -- Setup initialization for case of in out parameter, or an out -- parameter where the formal is an unconstrained array (in the -- latter case, we have to pass in an object with bounds). -- If this is an out parameter, the initial copy is wasteful, so as -- an optimization for the one-dimensional case we extract the -- bounds of the actual and build an uninitialized temporary of the -- right size. if Ekind (Formal) = E_In_Out_Parameter or else (Is_Array_Type (F_Typ) and then not Is_Constrained (F_Typ)) then if Nkind (Actual) = N_Type_Conversion then if Conversion_OK (Actual) then Init := OK_Convert_To (F_Typ, New_Occurrence_Of (Var, Loc)); else Init := Convert_To (F_Typ, New_Occurrence_Of (Var, Loc)); end if; elsif Ekind (Formal) = E_Out_Parameter and then Is_Array_Type (F_Typ) and then Number_Dimensions (F_Typ) = 1 and then not Has_Non_Null_Base_Init_Proc (F_Typ) then -- Actual is a one-dimensional array or slice, and the type -- requires no initialization. Create a temporary of the -- right size, but do not copy actual into it (optimization). Init := Empty; Indic := Make_Subtype_Indication (Loc, Subtype_Mark => New_Occurrence_Of (F_Typ, Loc), Constraint => Make_Index_Or_Discriminant_Constraint (Loc, Constraints => New_List ( Make_Range (Loc, Low_Bound => Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Var, Loc), -- LLVM local Attribute_Name => Name_First), High_Bound => Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Var, Loc), Attribute_Name => Name_Last))))); else Init := New_Occurrence_Of (Var, Loc); end if; -- An initialization is created for packed conversions as -- actuals for out parameters to enable Make_Object_Declaration -- to determine the proper subtype for N_Node. Note that this -- is wasteful because the extra copying on the call side is -- not required for such out parameters. ??? elsif Ekind (Formal) = E_Out_Parameter and then Nkind (Actual) = N_Type_Conversion and then (Is_Bit_Packed_Array (F_Typ) or else Is_Bit_Packed_Array (Etype (Expression (Actual)))) then if Conversion_OK (Actual) then Init := OK_Convert_To (F_Typ, New_Occurrence_Of (Var, Loc)); else Init := Convert_To (F_Typ, New_Occurrence_Of (Var, Loc)); end if; elsif Ekind (Formal) = E_In_Parameter then Init := New_Occurrence_Of (Var, Loc); else Init := Empty; end if; N_Node := Make_Object_Declaration (Loc, Defining_Identifier => Temp, Object_Definition => Indic, Expression => Init); Set_Assignment_OK (N_Node); Insert_Action (N, N_Node); -- Now, normally the deal here is that we use the defining -- identifier created by that object declaration. There is -- one exception to this. In the change of representation case -- the above declaration will end up looking like: -- temp : type := identifier; -- And in this case we might as well use the identifier directly -- and eliminate the temporary. Note that the analysis of the -- declaration was not a waste of time in that case, since it is -- what generated the necessary change of representation code. If -- the change of representation introduced additional code, as in -- a fixed-integer conversion, the expression is not an identifier -- and must be kept. if Crep and then Present (Expression (N_Node)) and then Is_Entity_Name (Expression (N_Node)) then Temp := Entity (Expression (N_Node)); Rewrite (N_Node, Make_Null_Statement (Loc)); end if; -- For IN parameter, all we do is to replace the actual if Ekind (Formal) = E_In_Parameter then Rewrite (Actual, New_Reference_To (Temp, Loc)); Analyze (Actual); -- Processing for OUT or IN OUT parameter else -- Kill current value indications for the temporary variable we -- created, since we just passed it as an OUT parameter. Kill_Current_Values (Temp); -- If type conversion, use reverse conversion on exit if Nkind (Actual) = N_Type_Conversion then if Conversion_OK (Actual) then Expr := OK_Convert_To (V_Typ, New_Occurrence_Of (Temp, Loc)); else Expr := Convert_To (V_Typ, New_Occurrence_Of (Temp, Loc)); end if; else Expr := New_Occurrence_Of (Temp, Loc); end if; Rewrite (Actual, New_Reference_To (Temp, Loc)); Analyze (Actual); Append_To (Post_Call, Make_Assignment_Statement (Loc, Name => New_Occurrence_Of (Var, Loc), Expression => Expr)); Set_Assignment_OK (Name (Last (Post_Call))); end if; end Add_Call_By_Copy_Code; ---------------------------------- -- Add_Simple_Call_By_Copy_Code -- ---------------------------------- procedure Add_Simple_Call_By_Copy_Code is Temp : Entity_Id; Decl : Node_Id; Incod : Node_Id; Outcod : Node_Id; Lhs : Node_Id; Rhs : Node_Id; Indic : Node_Id; F_Typ : constant Entity_Id := Etype (Formal); begin if not Is_Legal_Copy then return; end if; -- Use formal type for temp, unless formal type is an unconstrained -- array, in which case we don't have to worry about bounds checks, -- and we use the actual type, since that has appropriate bounds. if Is_Array_Type (F_Typ) and then not Is_Constrained (F_Typ) then Indic := New_Occurrence_Of (Etype (Actual), Loc); else Indic := New_Occurrence_Of (Etype (Formal), Loc); end if; -- Prepare to generate code Reset_Packed_Prefix; Temp := Make_Defining_Identifier (Loc, New_Internal_Name ('T')); Incod := Relocate_Node (Actual); Outcod := New_Copy_Tree (Incod); -- Generate declaration of temporary variable, initializing it -- with the input parameter unless we have an OUT formal or -- this is an initialization call. -- If the formal is an out parameter with discriminants, the -- discriminants must be captured even if the rest of the object -- is in principle uninitialized, because the discriminants may -- be read by the called subprogram. if Ekind (Formal) = E_Out_Parameter then Incod := Empty; if Has_Discriminants (Etype (Formal)) then Indic := New_Occurrence_Of (Etype (Actual), Loc); end if; elsif Inside_Init_Proc then -- Could use a comment here to match comment below ??? if Nkind (Actual) /= N_Selected_Component or else not Has_Discriminant_Dependent_Constraint (Entity (Selector_Name (Actual))) then Incod := Empty; -- Otherwise, keep the component in order to generate the proper -- actual subtype, that depends on enclosing discriminants. else null; end if; end if; Decl := Make_Object_Declaration (Loc, Defining_Identifier => Temp, Object_Definition => Indic, Expression => Incod); if Inside_Init_Proc and then No (Incod) then -- If the call is to initialize a component of a composite type, -- and the component does not depend on discriminants, use the -- actual type of the component. This is required in case the -- component is constrained, because in general the formal of the -- initialization procedure will be unconstrained. Note that if -- the component being initialized is constrained by an enclosing -- discriminant, the presence of the initialization in the -- declaration will generate an expression for the actual subtype. Set_No_Initialization (Decl); Set_Object_Definition (Decl, New_Occurrence_Of (Etype (Actual), Loc)); end if; Insert_Action (N, Decl); -- The actual is simply a reference to the temporary Rewrite (Actual, New_Occurrence_Of (Temp, Loc)); -- Generate copy out if OUT or IN OUT parameter if Ekind (Formal) /= E_In_Parameter then Lhs := Outcod; Rhs := New_Occurrence_Of (Temp, Loc); -- Deal with conversion if Nkind (Lhs) = N_Type_Conversion then Lhs := Expression (Lhs); Rhs := Convert_To (Etype (Actual), Rhs); end if; Append_To (Post_Call, Make_Assignment_Statement (Loc, Name => Lhs, Expression => Rhs)); Set_Assignment_OK (Name (Last (Post_Call))); end if; end Add_Simple_Call_By_Copy_Code; --------------------------- -- Check_Fortran_Logical -- --------------------------- procedure Check_Fortran_Logical is Logical : constant Entity_Id := Etype (Formal); Var : Entity_Id; -- Note: this is very incomplete, e.g. it does not handle arrays -- of logical values. This is really not the right approach at all???) begin if Convention (Subp) = Convention_Fortran and then Root_Type (Etype (Formal)) = Standard_Boolean and then Ekind (Formal) /= E_In_Parameter then Var := Make_Var (Actual); Append_To (Post_Call, Make_Assignment_Statement (Loc, Name => New_Occurrence_Of (Var, Loc), Expression => Unchecked_Convert_To ( Logical, Make_Op_Ne (Loc, Left_Opnd => New_Occurrence_Of (Var, Loc), Right_Opnd => Unchecked_Convert_To ( Logical, New_Occurrence_Of (Standard_False, Loc)))))); end if; end Check_Fortran_Logical; ------------------- -- Is_Legal_Copy -- ------------------- function Is_Legal_Copy return Boolean is begin -- An attempt to copy a value of such a type can only occur if -- representation clauses give the actual a misaligned address. if Is_By_Reference_Type (Etype (Formal)) then Error_Msg_N ("misaligned actual cannot be passed by reference", Actual); return False; -- For users of Starlet, we assume that the specification of by- -- reference mechanism is mandatory. This may lead to unligned -- objects but at least for DEC legacy code it is known to work. -- The warning will alert users of this code that a problem may -- be lurking. elsif Mechanism (Formal) = By_Reference and then Is_Valued_Procedure (Scope (Formal)) then Error_Msg_N ("by_reference actual may be misaligned?", Actual); return False; else return True; end if; end Is_Legal_Copy; -------------- -- Make_Var -- -------------- function Make_Var (Actual : Node_Id) return Entity_Id is Var : Entity_Id; begin if Is_Entity_Name (Actual) then return Entity (Actual); else Var := Make_Defining_Identifier (Loc, New_Internal_Name ('T')); N_Node := Make_Object_Renaming_Declaration (Loc, Defining_Identifier => Var, Subtype_Mark => New_Occurrence_Of (Etype (Actual), Loc), Name => Relocate_Node (Actual)); Insert_Action (N, N_Node); return Var; end if; end Make_Var; ------------------------- -- Reset_Packed_Prefix -- ------------------------- procedure Reset_Packed_Prefix is Pfx : Node_Id := Actual; begin loop Set_Analyzed (Pfx, False); exit when Nkind (Pfx) /= N_Selected_Component and then Nkind (Pfx) /= N_Indexed_Component; Pfx := Prefix (Pfx); end loop; end Reset_Packed_Prefix; -- Start of processing for Expand_Actuals begin Post_Call := New_List; Formal := First_Formal (Subp); Actual := First_Actual (N); while Present (Formal) loop E_Formal := Etype (Formal); if Is_Scalar_Type (E_Formal) or else Nkind (Actual) = N_Slice then Check_Fortran_Logical; -- RM 6.4.1 (11) elsif Ekind (Formal) /= E_Out_Parameter then -- The unusual case of the current instance of a protected type -- requires special handling. This can only occur in the context -- of a call within the body of a protected operation. if Is_Entity_Name (Actual) and then Ekind (Entity (Actual)) = E_Protected_Type and then In_Open_Scopes (Entity (Actual)) then if Scope (Subp) /= Entity (Actual) then Error_Msg_N ("operation outside protected type may not " & "call back its protected operations?", Actual); end if; Rewrite (Actual, Expand_Protected_Object_Reference (N, Entity (Actual))); end if; Apply_Constraint_Check (Actual, E_Formal); -- Out parameter case. No constraint checks on access type -- RM 6.4.1 (13) elsif Is_Access_Type (E_Formal) then null; -- RM 6.4.1 (14) elsif Has_Discriminants (Base_Type (E_Formal)) or else Has_Non_Null_Base_Init_Proc (E_Formal) then Apply_Constraint_Check (Actual, E_Formal); -- RM 6.4.1 (15) else Apply_Constraint_Check (Actual, Base_Type (E_Formal)); end if; -- Processing for IN-OUT and OUT parameters if Ekind (Formal) /= E_In_Parameter then -- For type conversions of arrays, apply length/range checks if Is_Array_Type (E_Formal) and then Nkind (Actual) = N_Type_Conversion then if Is_Constrained (E_Formal) then Apply_Length_Check (Expression (Actual), E_Formal); else Apply_Range_Check (Expression (Actual), E_Formal); end if; end if; -- If argument is a type conversion for a type that is passed -- by copy, then we must pass the parameter by copy. if Nkind (Actual) = N_Type_Conversion and then (Is_Numeric_Type (E_Formal) or else Is_Access_Type (E_Formal) or else Is_Enumeration_Type (E_Formal) or else Is_Bit_Packed_Array (Etype (Formal)) or else Is_Bit_Packed_Array (Etype (Expression (Actual))) -- Also pass by copy if change of representation or else not Same_Representation (Etype (Formal), Etype (Expression (Actual)))) then Add_Call_By_Copy_Code; -- References to components of bit packed arrays are expanded -- at this point, rather than at the point of analysis of the -- actuals, to handle the expansion of the assignment to -- [in] out parameters. elsif Is_Ref_To_Bit_Packed_Array (Actual) then Add_Simple_Call_By_Copy_Code; -- If a non-scalar actual is possibly unaligned, we need a copy elsif Is_Possibly_Unaligned_Object (Actual) and then not Represented_As_Scalar (Etype (Formal)) then Add_Simple_Call_By_Copy_Code; -- References to slices of bit packed arrays are expanded elsif Is_Ref_To_Bit_Packed_Slice (Actual) then Add_Call_By_Copy_Code; -- References to possibly unaligned slices of arrays are expanded elsif Is_Possibly_Unaligned_Slice (Actual) then Add_Call_By_Copy_Code; -- Deal with access types where the actual subtpe and the -- formal subtype are not the same, requiring a check. -- It is necessary to exclude tagged types because of "downward -- conversion" errors and a strange assertion error in namet -- from gnatf in bug 1215-001 ??? elsif Is_Access_Type (E_Formal) and then not Same_Type (E_Formal, Etype (Actual)) and then not Is_Tagged_Type (Designated_Type (E_Formal)) then Add_Call_By_Copy_Code; -- If the actual is not a scalar and is marked for volatile -- treatment, whereas the formal is not volatile, then pass -- by copy unless it is a by-reference type. elsif Is_Entity_Name (Actual) and then Treat_As_Volatile (Entity (Actual)) and then not Is_By_Reference_Type (Etype (Actual)) and then not Is_Scalar_Type (Etype (Entity (Actual))) and then not Treat_As_Volatile (E_Formal) then Add_Call_By_Copy_Code; elsif Nkind (Actual) = N_Indexed_Component and then Is_Entity_Name (Prefix (Actual)) and then Has_Volatile_Components (Entity (Prefix (Actual))) then Add_Call_By_Copy_Code; end if; -- Processing for IN parameters else -- For IN parameters is in the packed array case, we expand an -- indexed component (the circuit in Exp_Ch4 deliberately left -- indexed components appearing as actuals untouched, so that -- the special processing above for the OUT and IN OUT cases -- could be performed. We could make the test in Exp_Ch4 more -- complex and have it detect the parameter mode, but it is -- easier simply to handle all cases here.) if Nkind (Actual) = N_Indexed_Component and then Is_Packed (Etype (Prefix (Actual))) then Reset_Packed_Prefix; Expand_Packed_Element_Reference (Actual); -- If we have a reference to a bit packed array, we copy it, -- since the actual must be byte aligned. -- Is this really necessary in all cases??? elsif Is_Ref_To_Bit_Packed_Array (Actual) then Add_Simple_Call_By_Copy_Code; -- If a non-scalar actual is possibly unaligned, we need a copy elsif Is_Possibly_Unaligned_Object (Actual) and then not Represented_As_Scalar (Etype (Formal)) then Add_Simple_Call_By_Copy_Code; -- Similarly, we have to expand slices of packed arrays here -- because the result must be byte aligned. elsif Is_Ref_To_Bit_Packed_Slice (Actual) then Add_Call_By_Copy_Code; -- Only processing remaining is to pass by copy if this is a -- reference to a possibly unaligned slice, since the caller -- expects an appropriately aligned argument. elsif Is_Possibly_Unaligned_Slice (Actual) then Add_Call_By_Copy_Code; end if; end if; Next_Formal (Formal); Next_Actual (Actual); end loop; -- Find right place to put post call stuff if it is present if not Is_Empty_List (Post_Call) then -- If call is not a list member, it must be the triggering statement -- of a triggering alternative or an entry call alternative, and we -- can add the post call stuff to the corresponding statement list. if not Is_List_Member (N) then declare P : constant Node_Id := Parent (N); begin pragma Assert (Nkind (P) = N_Triggering_Alternative or else Nkind (P) = N_Entry_Call_Alternative); if Is_Non_Empty_List (Statements (P)) then Insert_List_Before_And_Analyze (First (Statements (P)), Post_Call); else Set_Statements (P, Post_Call); end if; end; -- Otherwise, normal case where N is in a statement sequence, -- just put the post-call stuff after the call statement. else Insert_Actions_After (N, Post_Call); end if; end if; -- The call node itself is re-analyzed in Expand_Call end Expand_Actuals; ----------------- -- Expand_Call -- ----------------- -- This procedure handles expansion of function calls and procedure call -- statements (i.e. it serves as the body for Expand_N_Function_Call and -- Expand_N_Procedure_Call_Statement. Processing for calls includes: -- Replace call to Raise_Exception by Raise_Exception always if possible -- Provide values of actuals for all formals in Extra_Formals list -- Replace "call" to enumeration literal function by literal itself -- Rewrite call to predefined operator as operator -- Replace actuals to in-out parameters that are numeric conversions, -- with explicit assignment to temporaries before and after the call. -- Remove optional actuals if First_Optional_Parameter specified. -- Note that the list of actuals has been filled with default expressions -- during semantic analysis of the call. Only the extra actuals required -- for the 'Constrained attribute and for accessibility checks are added -- at this point. procedure Expand_Call (N : Node_Id) is Loc : constant Source_Ptr := Sloc (N); Remote : constant Boolean := Is_Remote_Call (N); Subp : Entity_Id; Orig_Subp : Entity_Id := Empty; Parent_Subp : Entity_Id; Parent_Formal : Entity_Id; Actual : Node_Id; Formal : Entity_Id; Prev : Node_Id := Empty; Prev_Orig : Node_Id; -- Original node for an actual, which may have been rewritten. If the -- actual is a function call that has been transformed from a selected -- component, the original node is unanalyzed. Otherwise, it carries -- semantic information used to generate additional actuals. Scop : Entity_Id; Extra_Actuals : List_Id := No_List; CW_Interface_Formals_Present : Boolean := False; procedure Add_Actual_Parameter (Insert_Param : Node_Id); -- Adds one entry to the end of the actual parameter list. Used for -- default parameters and for extra actuals (for Extra_Formals). The -- argument is an N_Parameter_Association node. procedure Add_Extra_Actual (Expr : Node_Id; EF : Entity_Id); -- Adds an extra actual to the list of extra actuals. Expr is the -- expression for the value of the actual, EF is the entity for the -- extra formal. function Inherited_From_Formal (S : Entity_Id) return Entity_Id; -- Within an instance, a type derived from a non-tagged formal derived -- type inherits from the original parent, not from the actual. This is -- tested in 4723-003. The current derivation mechanism has the derived -- type inherit from the actual, which is only correct outside of the -- instance. If the subprogram is inherited, we test for this particular -- case through a convoluted tree traversal before setting the proper -- subprogram to be called. -------------------------- -- Add_Actual_Parameter -- -------------------------- procedure Add_Actual_Parameter (Insert_Param : Node_Id) is Actual_Expr : constant Node_Id := Explicit_Actual_Parameter (Insert_Param); begin -- Case of insertion is first named actual if No (Prev) or else Nkind (Parent (Prev)) /= N_Parameter_Association then Set_Next_Named_Actual (Insert_Param, First_Named_Actual (N)); Set_First_Named_Actual (N, Actual_Expr); if No (Prev) then if No (Parameter_Associations (N)) then Set_Parameter_Associations (N, New_List); Append (Insert_Param, Parameter_Associations (N)); end if; else Insert_After (Prev, Insert_Param); end if; -- Case of insertion is not first named actual else Set_Next_Named_Actual (Insert_Param, Next_Named_Actual (Parent (Prev))); Set_Next_Named_Actual (Parent (Prev), Actual_Expr); Append (Insert_Param, Parameter_Associations (N)); end if; Prev := Actual_Expr; end Add_Actual_Parameter; ---------------------- -- Add_Extra_Actual -- ---------------------- procedure Add_Extra_Actual (Expr : Node_Id; EF : Entity_Id) is Loc : constant Source_Ptr := Sloc (Expr); begin if Extra_Actuals = No_List then Extra_Actuals := New_List; Set_Parent (Extra_Actuals, N); end if; Append_To (Extra_Actuals, Make_Parameter_Association (Loc, Explicit_Actual_Parameter => Expr, Selector_Name => Make_Identifier (Loc, Chars (EF)))); Analyze_And_Resolve (Expr, Etype (EF)); end Add_Extra_Actual; --------------------------- -- Inherited_From_Formal -- --------------------------- function Inherited_From_Formal (S : Entity_Id) return Entity_Id is Par : Entity_Id; Gen_Par : Entity_Id; Gen_Prim : Elist_Id; Elmt : Elmt_Id; Indic : Node_Id; begin -- If the operation is inherited, it is attached to the corresponding -- type derivation. If the parent in the derivation is a generic -- actual, it is a subtype of the actual, and we have to recover the -- original derived type declaration to find the proper parent. if Nkind (Parent (S)) /= N_Full_Type_Declaration or else not Is_Derived_Type (Defining_Identifier (Parent (S))) or else Nkind (Type_Definition (Original_Node (Parent (S)))) /= N_Derived_Type_Definition or else not In_Instance then return Empty; else Indic := (Subtype_Indication (Type_Definition (Original_Node (Parent (S))))); if Nkind (Indic) = N_Subtype_Indication then Par := Entity (Subtype_Mark (Indic)); else Par := Entity (Indic); end if; end if; if not Is_Generic_Actual_Type (Par) or else Is_Tagged_Type (Par) or else Nkind (Parent (Par)) /= N_Subtype_Declaration or else not In_Open_Scopes (Scope (Par)) then return Empty; else Gen_Par := Generic_Parent_Type (Parent (Par)); end if; -- If the generic parent type is still the generic type, this is a -- private formal, not a derived formal, and there are no operations -- inherited from the formal. if Nkind (Parent (Gen_Par)) = N_Formal_Type_Declaration then return Empty; end if; Gen_Prim := Collect_Primitive_Operations (Gen_Par); Elmt := First_Elmt (Gen_Prim); while Present (Elmt) loop if Chars (Node (Elmt)) = Chars (S) then declare F1 : Entity_Id; F2 : Entity_Id; begin F1 := First_Formal (S); F2 := First_Formal (Node (Elmt)); while Present (F1) and then Present (F2) loop if Etype (F1) = Etype (F2) or else Etype (F2) = Gen_Par then Next_Formal (F1); Next_Formal (F2); else Next_Elmt (Elmt); exit; -- not the right subprogram end if; return Node (Elmt); end loop; end; else Next_Elmt (Elmt); end if; end loop; raise Program_Error; end Inherited_From_Formal; -- Start of processing for Expand_Call begin -- Ignore if previous error if Nkind (N) in N_Has_Etype and then Etype (N) = Any_Type then return; end if; -- Call using access to subprogram with explicit dereference if Nkind (Name (N)) = N_Explicit_Dereference then Subp := Etype (Name (N)); Parent_Subp := Empty; -- Case of call to simple entry, where the Name is a selected component -- whose prefix is the task, and whose selector name is the entry name elsif Nkind (Name (N)) = N_Selected_Component then Subp := Entity (Selector_Name (Name (N))); Parent_Subp := Empty; -- Case of call to member of entry family, where Name is an indexed -- component, with the prefix being a selected component giving the -- task and entry family name, and the index being the entry index. elsif Nkind (Name (N)) = N_Indexed_Component then Subp := Entity (Selector_Name (Prefix (Name (N)))); Parent_Subp := Empty; -- Normal case else Subp := Entity (Name (N)); Parent_Subp := Alias (Subp); -- Replace call to Raise_Exception by call to Raise_Exception_Always -- if we can tell that the first parameter cannot possibly be null. -- This helps optimization and also generation of warnings. if not Restriction_Active (No_Exception_Handlers) and then Is_RTE (Subp, RE_Raise_Exception) then declare FA : constant Node_Id := Original_Node (First_Actual (N)); begin -- The case we catch is where the first argument is obtained -- using the Identity attribute (which must always be -- non-null). if Nkind (FA) = N_Attribute_Reference and then Attribute_Name (FA) = Name_Identity then Subp := RTE (RE_Raise_Exception_Always); Set_Entity (Name (N), Subp); end if; end; end if; if Ekind (Subp) = E_Entry then Parent_Subp := Empty; end if; end if; -- Ada 2005 (AI-345): We have a procedure call as a triggering -- alternative in an asynchronous select or as an entry call in -- a conditional or timed select. Check whether the procedure call -- is a renaming of an entry and rewrite it as an entry call. if Ada_Version >= Ada_05 and then Nkind (N) = N_Procedure_Call_Statement and then ((Nkind (Parent (N)) = N_Triggering_Alternative and then Triggering_Statement (Parent (N)) = N) or else (Nkind (Parent (N)) = N_Entry_Call_Alternative and then Entry_Call_Statement (Parent (N)) = N)) then declare Ren_Decl : Node_Id; Ren_Root : Entity_Id := Subp; begin -- This may be a chain of renamings, find the root if Present (Alias (Ren_Root)) then Ren_Root := Alias (Ren_Root); end if; if Present (Original_Node (Parent (Parent (Ren_Root)))) then Ren_Decl := Original_Node (Parent (Parent (Ren_Root))); if Nkind (Ren_Decl) = N_Subprogram_Renaming_Declaration then Rewrite (N, Make_Entry_Call_Statement (Loc, Name => New_Copy_Tree (Name (Ren_Decl)), Parameter_Associations => New_Copy_List_Tree (Parameter_Associations (N)))); return; end if; end if; end; end if; -- First step, compute extra actuals, corresponding to any -- Extra_Formals present. Note that we do not access Extra_Formals -- directly, instead we simply note the presence of the extra -- formals as we process the regular formals and collect the -- corresponding actuals in Extra_Actuals. -- We also generate any required range checks for actuals as we go -- through the loop, since this is a convenient place to do this. Formal := First_Formal (Subp); Actual := First_Actual (N); while Present (Formal) loop -- Generate range check if required (not activated yet ???) -- if Do_Range_Check (Actual) then -- Set_Do_Range_Check (Actual, False); -- Generate_Range_Check -- (Actual, Etype (Formal), CE_Range_Check_Failed); -- end if; -- Prepare to examine current entry Prev := Actual; Prev_Orig := Original_Node (Prev); if not Analyzed (Prev_Orig) and then Nkind (Actual) = N_Function_Call then Prev_Orig := Prev; end if; -- Ada 2005 (AI-251): Check if any formal is a class-wide interface -- to expand it in a further round. CW_Interface_Formals_Present := CW_Interface_Formals_Present or else (Ekind (Etype (Formal)) = E_Class_Wide_Type and then Is_Interface (Etype (Etype (Formal)))) or else (Ekind (Etype (Formal)) = E_Anonymous_Access_Type and then Is_Interface (Directly_Designated_Type (Etype (Etype (Formal))))); -- Create possible extra actual for constrained case. Usually, the -- extra actual is of the form actual'constrained, but since this -- attribute is only available for unconstrained records, TRUE is -- expanded if the type of the formal happens to be constrained (for -- instance when this procedure is inherited from an unconstrained -- record to a constrained one) or if the actual has no discriminant -- (its type is constrained). An exception to this is the case of a -- private type without discriminants. In this case we pass FALSE -- because the object has underlying discriminants with defaults. if Present (Extra_Constrained (Formal)) then if Ekind (Etype (Prev)) in Private_Kind and then not Has_Discriminants (Base_Type (Etype (Prev))) then Add_Extra_Actual ( New_Occurrence_Of (Standard_False, Loc), Extra_Constrained (Formal)); elsif Is_Constrained (Etype (Formal)) or else not Has_Discriminants (Etype (Prev)) then Add_Extra_Actual ( New_Occurrence_Of (Standard_True, Loc), Extra_Constrained (Formal)); -- Do not produce extra actuals for Unchecked_Union parameters. -- Jump directly to the end of the loop. elsif Is_Unchecked_Union (Base_Type (Etype (Actual))) then goto Skip_Extra_Actual_Generation; else -- If the actual is a type conversion, then the constrained -- test applies to the actual, not the target type. declare Act_Prev : Node_Id; begin -- Test for unchecked conversions as well, which can occur -- as out parameter actuals on calls to stream procedures. Act_Prev := Prev; while Nkind (Act_Prev) = N_Type_Conversion or else Nkind (Act_Prev) = N_Unchecked_Type_Conversion loop Act_Prev := Expression (Act_Prev); end loop; -- If the expression is a conversion of a dereference, -- this is internally generated code that manipulates -- addresses, e.g. when building interface tables. No -- check should occur in this case, and the discriminated -- object is not directly a hand. if not Comes_From_Source (Actual) and then Nkind (Actual) = N_Unchecked_Type_Conversion and then Nkind (Act_Prev) = N_Explicit_Dereference then Add_Extra_Actual (New_Occurrence_Of (Standard_False, Loc), Extra_Constrained (Formal)); else Add_Extra_Actual (Make_Attribute_Reference (Sloc (Prev), Prefix => Duplicate_Subexpr_No_Checks (Act_Prev, Name_Req => True), Attribute_Name => Name_Constrained), Extra_Constrained (Formal)); end if; end; end if; end if; -- Create possible extra actual for accessibility level if Present (Extra_Accessibility (Formal)) then if Is_Entity_Name (Prev_Orig) then -- When passing an access parameter as the actual to another -- access parameter we need to pass along the actual's own -- associated access level parameter. This is done if we are -- in the scope of the formal access parameter (if this is an -- inlined body the extra formal is irrelevant). if Ekind (Entity (Prev_Orig)) in Formal_Kind and then Ekind (Etype (Prev_Orig)) = E_Anonymous_Access_Type and then In_Open_Scopes (Scope (Entity (Prev_Orig))) then declare Parm_Ent : constant Entity_Id := Param_Entity (Prev_Orig); begin pragma Assert (Present (Parm_Ent)); if Present (Extra_Accessibility (Parm_Ent)) then Add_Extra_Actual (New_Occurrence_Of (Extra_Accessibility (Parm_Ent), Loc), Extra_Accessibility (Formal)); -- If the actual access parameter does not have an -- associated extra formal providing its scope level, -- then treat the actual as having library-level -- accessibility. else Add_Extra_Actual (Make_Integer_Literal (Loc, Intval => Scope_Depth (Standard_Standard)), Extra_Accessibility (Formal)); end if; end; -- The actual is a normal access value, so just pass the -- level of the actual's access type. else Add_Extra_Actual (Make_Integer_Literal (Loc, Intval => Type_Access_Level (Etype (Prev_Orig))), Extra_Accessibility (Formal)); end if; else case Nkind (Prev_Orig) is when N_Attribute_Reference => case Get_Attribute_Id (Attribute_Name (Prev_Orig)) is -- For X'Access, pass on the level of the prefix X when Attribute_Access => Add_Extra_Actual ( Make_Integer_Literal (Loc, Intval => Object_Access_Level (Prefix (Prev_Orig))), Extra_Accessibility (Formal)); -- Treat the unchecked attributes as library-level when Attribute_Unchecked_Access | Attribute_Unrestricted_Access => Add_Extra_Actual ( Make_Integer_Literal (Loc, Intval => Scope_Depth (Standard_Standard)), Extra_Accessibility (Formal)); -- No other cases of attributes returning access -- values that can be passed to access parameters when others => raise Program_Error; end case; -- For allocators we pass the level of the execution of -- the called subprogram, which is one greater than the -- current scope level. when N_Allocator => Add_Extra_Actual ( Make_Integer_Literal (Loc, Scope_Depth (Current_Scope) + 1), Extra_Accessibility (Formal)); -- For other cases we simply pass the level of the -- actual's access type. when others => Add_Extra_Actual ( Make_Integer_Literal (Loc, Intval => Type_Access_Level (Etype (Prev_Orig))), Extra_Accessibility (Formal)); end case; end if; end if; -- Perform the check of 4.6(49) that prevents a null value from being -- passed as an actual to an access parameter. Note that the check is -- elided in the common cases of passing an access attribute or -- access parameter as an actual. Also, we currently don't enforce -- this check for expander-generated actuals and when -gnatdj is set. if Ada_Version >= Ada_05 then -- Ada 2005 (AI-231): Check null-excluding access types if Is_Access_Type (Etype (Formal)) and then Can_Never_Be_Null (Etype (Formal)) and then Nkind (Prev) /= N_Raise_Constraint_Error and then (Nkind (Prev) = N_Null or else not Can_Never_Be_Null (Etype (Prev))) then Install_Null_Excluding_Check (Prev); end if; -- Ada_Version < Ada_05 else if Ekind (Etype (Formal)) /= E_Anonymous_Access_Type or else Access_Checks_Suppressed (Subp) then null; elsif Debug_Flag_J then null; elsif not Comes_From_Source (Prev) then null; elsif Is_Entity_Name (Prev) and then Ekind (Etype (Prev)) = E_Anonymous_Access_Type then null; elsif Nkind (Prev) = N_Allocator or else Nkind (Prev) = N_Attribute_Reference then null; -- Suppress null checks when passing to access parameters of Java -- subprograms. (Should this be done for other foreign conventions -- as well ???) elsif Convention (Subp) = Convention_Java then null; else Install_Null_Excluding_Check (Prev); end if; end if; -- Perform appropriate validity checks on parameters that -- are entities. if Validity_Checks_On then if (Ekind (Formal) = E_In_Parameter and then Validity_Check_In_Params) or else (Ekind (Formal) = E_In_Out_Parameter and then Validity_Check_In_Out_Params) then -- If the actual is an indexed component of a packed -- type, it has not been expanded yet. It will be -- copied in the validity code that follows, and has -- to be expanded appropriately, so reanalyze it. if Nkind (Actual) = N_Indexed_Component then Set_Analyzed (Actual, False); end if; Ensure_Valid (Actual); end if; end if; -- For IN OUT and OUT parameters, ensure that subscripts are valid -- since this is a left side reference. We only do this for calls -- from the source program since we assume that compiler generated -- calls explicitly generate any required checks. We also need it -- only if we are doing standard validity checks, since clearly it -- is not needed if validity checks are off, and in subscript -- validity checking mode, all indexed components are checked with -- a call directly from Expand_N_Indexed_Component. if Comes_From_Source (N) and then Ekind (Formal) /= E_In_Parameter and then Validity_Checks_On and then Validity_Check_Default and then not Validity_Check_Subscripts then Check_Valid_Lvalue_Subscripts (Actual); end if; -- Mark any scalar OUT parameter that is a simple variable as no -- longer known to be valid (unless the type is always valid). This -- reflects the fact that if an OUT parameter is never set in a -- procedure, then it can become invalid on the procedure return. if Ekind (Formal) = E_Out_Parameter and then Is_Entity_Name (Actual) and then Ekind (Entity (Actual)) = E_Variable and then not Is_Known_Valid (Etype (Actual)) then Set_Is_Known_Valid (Entity (Actual), False); end if; -- For an OUT or IN OUT parameter, if the actual is an entity, then -- clear current values, since they can be clobbered. We are probably -- doing this in more places than we need to, but better safe than -- sorry when it comes to retaining bad current values! if Ekind (Formal) /= E_In_Parameter and then Is_Entity_Name (Actual) then Kill_Current_Values (Entity (Actual)); end if; -- If the formal is class wide and the actual is an aggregate, force -- evaluation so that the back end who does not know about class-wide -- type, does not generate a temporary of the wrong size. if not Is_Class_Wide_Type (Etype (Formal)) then null; elsif Nkind (Actual) = N_Aggregate or else (Nkind (Actual) = N_Qualified_Expression and then Nkind (Expression (Actual)) = N_Aggregate) then Force_Evaluation (Actual); end if; -- In a remote call, if the formal is of a class-wide type, check -- that the actual meets the requirements described in E.4(18). if Remote and then Is_Class_Wide_Type (Etype (Formal)) then Insert_Action (Actual, Make_Implicit_If_Statement (N, Condition => Make_Op_Not (Loc, Get_Remotely_Callable (Duplicate_Subexpr_Move_Checks (Actual))), Then_Statements => New_List ( Make_Raise_Program_Error (Loc, Reason => PE_Illegal_RACW_E_4_18)))); end if; -- This label is required when skipping extra actual generation for -- Unchecked_Union parameters. <<Skip_Extra_Actual_Generation>> Next_Actual (Actual); Next_Formal (Formal); end loop; -- If we are expanding a rhs of an assignment we need to check if tag -- propagation is needed. You might expect this processing to be in -- Analyze_Assignment but has to be done earlier (bottom-up) because the -- assignment might be transformed to a declaration for an unconstrained -- value if the expression is classwide. if Nkind (N) = N_Function_Call and then Is_Tag_Indeterminate (N) and then Is_Entity_Name (Name (N)) then declare Ass : Node_Id := Empty; begin if Nkind (Parent (N)) = N_Assignment_Statement then Ass := Parent (N); elsif Nkind (Parent (N)) = N_Qualified_Expression and then Nkind (Parent (Parent (N))) = N_Assignment_Statement then Ass := Parent (Parent (N)); end if; if Present (Ass) and then Is_Class_Wide_Type (Etype (Name (Ass))) then if Etype (N) /= Root_Type (Etype (Name (Ass))) then Error_Msg_NE ("tag-indeterminate expression must have type&" & "('R'M 5.2 (6))", N, Root_Type (Etype (Name (Ass)))); else Propagate_Tag (Name (Ass), N); end if; -- The call will be rewritten as a dispatching call, and -- expanded as such. return; end if; end; end if; -- Ada 2005 (AI-251): If some formal is a class-wide interface, expand -- it to point to the correct secondary virtual table if (Nkind (N) = N_Function_Call or else Nkind (N) = N_Procedure_Call_Statement) and then CW_Interface_Formals_Present then Expand_Interface_Actuals (N); end if; -- Deals with Dispatch_Call if we still have a call, before expanding -- extra actuals since this will be done on the re-analysis of the -- dispatching call. Note that we do not try to shorten the actual -- list for a dispatching call, it would not make sense to do so. -- Expansion of dispatching calls is suppressed when Java_VM, because -- the JVM back end directly handles the generation of dispatching -- calls and would have to undo any expansion to an indirect call. if (Nkind (N) = N_Function_Call or else Nkind (N) = N_Procedure_Call_Statement) and then Present (Controlling_Argument (N)) and then not Java_VM then Expand_Dispatching_Call (N); -- The following return is worrisome. Is it really OK to -- skip all remaining processing in this procedure ??? return; -- Similarly, expand calls to RCI subprograms on which pragma -- All_Calls_Remote applies. The rewriting will be reanalyzed -- later. Do this only when the call comes from source since we do -- not want such a rewritting to occur in expanded code. elsif Is_All_Remote_Call (N) then Expand_All_Calls_Remote_Subprogram_Call (N); -- Similarly, do not add extra actuals for an entry call whose entity -- is a protected procedure, or for an internal protected subprogram -- call, because it will be rewritten as a protected subprogram call -- and reanalyzed (see Expand_Protected_Subprogram_Call). elsif Is_Protected_Type (Scope (Subp)) and then (Ekind (Subp) = E_Procedure or else Ekind (Subp) = E_Function) then null; -- During that loop we gathered the extra actuals (the ones that -- correspond to Extra_Formals), so now they can be appended. else while Is_Non_Empty_List (Extra_Actuals) loop Add_Actual_Parameter (Remove_Head (Extra_Actuals)); end loop; end if; -- At this point we have all the actuals, so this is the point at -- which the various expansion activities for actuals is carried out. Expand_Actuals (N, Subp); -- If the subprogram is a renaming, or if it is inherited, replace it -- in the call with the name of the actual subprogram being called. -- If this is a dispatching call, the run-time decides what to call. -- The Alias attribute does not apply to entries. if Nkind (N) /= N_Entry_Call_Statement and then No (Controlling_Argument (N)) and then Present (Parent_Subp) then if Present (Inherited_From_Formal (Subp)) then Parent_Subp := Inherited_From_Formal (Subp); else while Present (Alias (Parent_Subp)) loop Parent_Subp := Alias (Parent_Subp); end loop; end if; -- The below setting of Entity is suspect, see F109-018 discussion??? Set_Entity (Name (N), Parent_Subp); if Is_Abstract (Parent_Subp) and then not In_Instance then Error_Msg_NE ("cannot call abstract subprogram &!", Name (N), Parent_Subp); end if; -- Add an explicit conversion for parameter of the derived type. -- This is only done for scalar and access in-parameters. Others -- have been expanded in expand_actuals. Formal := First_Formal (Subp); Parent_Formal := First_Formal (Parent_Subp); Actual := First_Actual (N); -- It is not clear that conversion is needed for intrinsic -- subprograms, but it certainly is for those that are user- -- defined, and that can be inherited on derivation, namely -- unchecked conversion and deallocation. -- General case needs study ??? if not Is_Intrinsic_Subprogram (Parent_Subp) or else Is_Generic_Instance (Parent_Subp) then while Present (Formal) loop if Etype (Formal) /= Etype (Parent_Formal) and then Is_Scalar_Type (Etype (Formal)) and then Ekind (Formal) = E_In_Parameter and then not Raises_Constraint_Error (Actual) then Rewrite (Actual, OK_Convert_To (Etype (Parent_Formal), Relocate_Node (Actual))); Analyze (Actual); Resolve (Actual, Etype (Parent_Formal)); Enable_Range_Check (Actual); elsif Is_Access_Type (Etype (Formal)) and then Base_Type (Etype (Parent_Formal)) /= Base_Type (Etype (Actual)) then if Ekind (Formal) /= E_In_Parameter then Rewrite (Actual, Convert_To (Etype (Parent_Formal), Relocate_Node (Actual))); Analyze (Actual); Resolve (Actual, Etype (Parent_Formal)); elsif Ekind (Etype (Parent_Formal)) = E_Anonymous_Access_Type and then Designated_Type (Etype (Parent_Formal)) /= Designated_Type (Etype (Actual)) and then not Is_Controlling_Formal (Formal) then -- This unchecked conversion is not necessary unless -- inlining is enabled, because in that case the type -- mismatch may become visible in the body about to be -- inlined. Rewrite (Actual, Unchecked_Convert_To (Etype (Parent_Formal), Relocate_Node (Actual))); Analyze (Actual); Resolve (Actual, Etype (Parent_Formal)); end if; end if; Next_Formal (Formal); Next_Formal (Parent_Formal); Next_Actual (Actual); end loop; end if; Orig_Subp := Subp; Subp := Parent_Subp; end if; -- Check for violation of No_Abort_Statements if Is_RTE (Subp, RE_Abort_Task) then Check_Restriction (No_Abort_Statements, N); -- Check for violation of No_Dynamic_Attachment elsif RTU_Loaded (Ada_Interrupts) and then (Is_RTE (Subp, RE_Is_Reserved) or else Is_RTE (Subp, RE_Is_Attached) or else Is_RTE (Subp, RE_Current_Handler) or else Is_RTE (Subp, RE_Attach_Handler) or else Is_RTE (Subp, RE_Exchange_Handler) or else Is_RTE (Subp, RE_Detach_Handler) or else Is_RTE (Subp, RE_Reference)) then Check_Restriction (No_Dynamic_Attachment, N); end if; -- Deal with case where call is an explicit dereference if Nkind (Name (N)) = N_Explicit_Dereference then -- Handle case of access to protected subprogram type if Ekind (Base_Type (Etype (Prefix (Name (N))))) = E_Access_Protected_Subprogram_Type then -- If this is a call through an access to protected operation, -- the prefix has the form (object'address, operation'access). -- Rewrite as a for other protected calls: the object is the -- first parameter of the list of actuals. declare Call : Node_Id; Parm : List_Id; Nam : Node_Id; Obj : Node_Id; Ptr : constant Node_Id := Prefix (Name (N)); T : constant Entity_Id := Equivalent_Type (Base_Type (Etype (Ptr))); D_T : constant Entity_Id := Designated_Type (Base_Type (Etype (Ptr))); begin Obj := Make_Selected_Component (Loc, Prefix => Unchecked_Convert_To (T, Ptr), Selector_Name => New_Occurrence_Of (First_Entity (T), Loc)); Nam := Make_Selected_Component (Loc, Prefix => Unchecked_Convert_To (T, Ptr), Selector_Name => New_Occurrence_Of (Next_Entity (First_Entity (T)), Loc)); Nam := Make_Explicit_Dereference (Loc, Nam); if Present (Parameter_Associations (N)) then Parm := Parameter_Associations (N); else Parm := New_List; end if; Prepend (Obj, Parm); if Etype (D_T) = Standard_Void_Type then Call := Make_Procedure_Call_Statement (Loc, Name => Nam, Parameter_Associations => Parm); else Call := Make_Function_Call (Loc, Name => Nam, Parameter_Associations => Parm); end if; Set_First_Named_Actual (Call, First_Named_Actual (N)); Set_Etype (Call, Etype (D_T)); -- We do not re-analyze the call to avoid infinite recursion. -- We analyze separately the prefix and the object, and set -- the checks on the prefix that would otherwise be emitted -- when resolving a call. Rewrite (N, Call); Analyze (Nam); Apply_Access_Check (Nam); Analyze (Obj); return; end; end if; end if; -- If this is a call to an intrinsic subprogram, then perform the -- appropriate expansion to the corresponding tree node and we -- are all done (since after that the call is gone!) -- In the case where the intrinsic is to be processed by the back end, -- the call to Expand_Intrinsic_Call will do nothing, which is fine, -- since the idea in this case is to pass the call unchanged. if Is_Intrinsic_Subprogram (Subp) then Expand_Intrinsic_Call (N, Subp); return; end if; if Ekind (Subp) = E_Function or else Ekind (Subp) = E_Procedure then if Is_Inlined (Subp) then Inlined_Subprogram : declare Bod : Node_Id; Must_Inline : Boolean := False; Spec : constant Node_Id := Unit_Declaration_Node (Subp); Scop : constant Entity_Id := Scope (Subp); function In_Unfrozen_Instance return Boolean; -- If the subprogram comes from an instance in the same -- unit, and the instance is not yet frozen, inlining might -- trigger order-of-elaboration problems in gigi. -------------------------- -- In_Unfrozen_Instance -- -------------------------- function In_Unfrozen_Instance return Boolean is S : Entity_Id; begin S := Scop; while Present (S) and then S /= Standard_Standard loop if Is_Generic_Instance (S) and then Present (Freeze_Node (S)) and then not Analyzed (Freeze_Node (S)) then return True; end if; S := Scope (S); end loop; return False; end In_Unfrozen_Instance; -- Start of processing for Inlined_Subprogram begin -- Verify that the body to inline has already been seen, and -- that if the body is in the current unit the inlining does -- not occur earlier. This avoids order-of-elaboration problems -- in the back end. -- This should be documented in sinfo/einfo ??? if No (Spec) or else Nkind (Spec) /= N_Subprogram_Declaration or else No (Body_To_Inline (Spec)) then Must_Inline := False; -- If this an inherited function that returns a private -- type, do not inline if the full view is an unconstrained -- array, because such calls cannot be inlined. elsif Present (Orig_Subp) and then Is_Array_Type (Etype (Orig_Subp)) and then not Is_Constrained (Etype (Orig_Subp)) then Must_Inline := False; elsif In_Unfrozen_Instance then Must_Inline := False; else Bod := Body_To_Inline (Spec); if (In_Extended_Main_Code_Unit (N) or else In_Extended_Main_Code_Unit (Parent (N)) or else Is_Always_Inlined (Subp)) and then (not In_Same_Extended_Unit (Sloc (Bod), Loc) or else Earlier_In_Extended_Unit (Sloc (Bod), Loc)) then Must_Inline := True; -- If we are compiling a package body that is not the main -- unit, it must be for inlining/instantiation purposes, -- in which case we inline the call to insure that the same -- temporaries are generated when compiling the body by -- itself. Otherwise link errors can occur. -- If the function being called is itself in the main unit, -- we cannot inline, because there is a risk of double -- elaboration and/or circularity: the inlining can make -- visible a private entity in the body of the main unit, -- that gigi will see before its sees its proper definition. elsif not (In_Extended_Main_Code_Unit (N)) and then In_Package_Body then Must_Inline := not In_Extended_Main_Source_Unit (Subp); end if; end if; if Must_Inline then Expand_Inlined_Call (N, Subp, Orig_Subp); else -- Let the back end handle it Add_Inlined_Body (Subp); if Front_End_Inlining and then Nkind (Spec) = N_Subprogram_Declaration and then (In_Extended_Main_Code_Unit (N)) and then No (Body_To_Inline (Spec)) and then not Has_Completion (Subp) and then In_Same_Extended_Unit (Sloc (Spec), Loc) then Cannot_Inline ("cannot inline& (body not seen yet)?", N, Subp); end if; end if; end Inlined_Subprogram; end if; end if; -- Check for a protected subprogram. This is either an intra-object -- call, or a protected function call. Protected procedure calls are -- rewritten as entry calls and handled accordingly. -- In Ada 2005, this may be an indirect call to an access parameter -- that is an access_to_subprogram. In that case the anonymous type -- has a scope that is a protected operation, but the call is a -- regular one. Scop := Scope (Subp); if Nkind (N) /= N_Entry_Call_Statement and then Is_Protected_Type (Scop) and then Ekind (Subp) /= E_Subprogram_Type then -- If the call is an internal one, it is rewritten as a call to -- to the corresponding unprotected subprogram. Expand_Protected_Subprogram_Call (N, Subp, Scop); end if; -- Functions returning controlled objects need special attention if Controlled_Type (Etype (Subp)) and then not Is_Return_By_Reference_Type (Etype (Subp)) then Expand_Ctrl_Function_Call (N); end if; -- Test for First_Optional_Parameter, and if so, truncate parameter -- list if there are optional parameters at the trailing end. -- Note we never delete procedures for call via a pointer. if (Ekind (Subp) = E_Procedure or else Ekind (Subp) = E_Function) and then Present (First_Optional_Parameter (Subp)) then declare Last_Keep_Arg : Node_Id; begin -- Last_Keep_Arg will hold the last actual that should be -- retained. If it remains empty at the end, it means that -- all parameters are optional. Last_Keep_Arg := Empty; -- Find first optional parameter, must be present since we -- checked the validity of the parameter before setting it. Formal := First_Formal (Subp); Actual := First_Actual (N); while Formal /= First_Optional_Parameter (Subp) loop Last_Keep_Arg := Actual; Next_Formal (Formal); Next_Actual (Actual); end loop; -- We have Formal and Actual pointing to the first potentially -- droppable argument. We can drop all the trailing arguments -- whose actual matches the default. Note that we know that all -- remaining formals have defaults, because we checked that this -- requirement was met before setting First_Optional_Parameter. -- We use Fully_Conformant_Expressions to check for identity -- between formals and actuals, which may miss some cases, but -- on the other hand, this is only an optimization (if we fail -- to truncate a parameter it does not affect functionality). -- So if the default is 3 and the actual is 1+2, we consider -- them unequal, which hardly seems worrisome. while Present (Formal) loop if not Fully_Conformant_Expressions (Actual, Default_Value (Formal)) then Last_Keep_Arg := Actual; end if; Next_Formal (Formal); Next_Actual (Actual); end loop; -- If no arguments, delete entire list, this is the easy case if No (Last_Keep_Arg) then while Is_Non_Empty_List (Parameter_Associations (N)) loop Delete_Tree (Remove_Head (Parameter_Associations (N))); end loop; Set_Parameter_Associations (N, No_List); Set_First_Named_Actual (N, Empty); -- Case where at the last retained argument is positional. This -- is also an easy case, since the retained arguments are already -- in the right form, and we don't need to worry about the order -- of arguments that get eliminated. elsif Is_List_Member (Last_Keep_Arg) then while Present (Next (Last_Keep_Arg)) loop Delete_Tree (Remove_Next (Last_Keep_Arg)); end loop; Set_First_Named_Actual (N, Empty); -- This is the annoying case where the last retained argument -- is a named parameter. Since the original arguments are not -- in declaration order, we may have to delete some fairly -- random collection of arguments. else declare Temp : Node_Id; Passoc : Node_Id; Discard : Node_Id; pragma Warnings (Off, Discard); begin -- First step, remove all the named parameters from the -- list (they are still chained using First_Named_Actual -- and Next_Named_Actual, so we have not lost them!) Temp := First (Parameter_Associations (N)); -- Case of all parameters named, remove them all if Nkind (Temp) = N_Parameter_Association then while Is_Non_Empty_List (Parameter_Associations (N)) loop Temp := Remove_Head (Parameter_Associations (N)); end loop; -- Case of mixed positional/named, remove named parameters else while Nkind (Next (Temp)) /= N_Parameter_Association loop Next (Temp); end loop; while Present (Next (Temp)) loop -- LLVM local Remove (Next (Temp)); end loop; end if; -- Now we loop through the named parameters, till we get -- to the last one to be retained, adding them to the list. -- Note that the Next_Named_Actual list does not need to be -- touched since we are only reordering them on the actual -- parameter association list. Passoc := Parent (First_Named_Actual (N)); loop Temp := Relocate_Node (Passoc); Append_To (Parameter_Associations (N), Temp); exit when Last_Keep_Arg = Explicit_Actual_Parameter (Passoc); Passoc := Parent (Next_Named_Actual (Passoc)); end loop; Set_Next_Named_Actual (Temp, Empty); loop Temp := Next_Named_Actual (Passoc); exit when No (Temp); Set_Next_Named_Actual (Passoc, Next_Named_Actual (Parent (Temp))); Delete_Tree (Temp); end loop; end; end if; end; end if; -- Special processing for Ada 2005 AI-329, which requires a call to -- Raise_Exception to raise Constraint_Error if the Exception_Id is -- null. Note that we never need to do this in GNAT mode, or if the -- parameter to Raise_Exception is a use of Identity, since in these -- cases we know that the parameter is never null. if Ada_Version >= Ada_05 and then not GNAT_Mode and then Is_RTE (Subp, RE_Raise_Exception) and then (Nkind (First_Actual (N)) /= N_Attribute_Reference or else Attribute_Name (First_Actual (N)) /= Name_Identity) then declare RCE : constant Node_Id := Make_Raise_Constraint_Error (Loc, Reason => CE_Null_Exception_Id); begin Insert_After (N, RCE); Analyze (RCE); end; end if; end Expand_Call; -------------------------- -- Expand_Inlined_Call -- -------------------------- procedure Expand_Inlined_Call (N : Node_Id; Subp : Entity_Id; Orig_Subp : Entity_Id) is Loc : constant Source_Ptr := Sloc (N); Is_Predef : constant Boolean := Is_Predefined_File_Name (Unit_File_Name (Get_Source_Unit (Subp))); Orig_Bod : constant Node_Id := Body_To_Inline (Unit_Declaration_Node (Subp)); Blk : Node_Id; Bod : Node_Id; Decl : Node_Id; Decls : constant List_Id := New_List; Exit_Lab : Entity_Id := Empty; F : Entity_Id; A : Node_Id; Lab_Decl : Node_Id; Lab_Id : Node_Id; New_A : Node_Id; Num_Ret : Int := 0; Ret_Type : Entity_Id; Targ : Node_Id; Targ1 : Node_Id; Temp : Entity_Id; Temp_Typ : Entity_Id; Is_Unc : constant Boolean := Is_Array_Type (Etype (Subp)) and then not Is_Constrained (Etype (Subp)); -- If the type returned by the function is unconstrained and the -- call can be inlined, special processing is required. procedure Find_Result; -- For a function that returns an unconstrained type, retrieve the -- name of the single variable that is the expression of a return -- statement in the body of the function. Build_Body_To_Inline has -- verified that this variable is unique, even in the presence of -- multiple return statements. procedure Make_Exit_Label; -- Build declaration for exit label to be used in Return statements function Process_Formals (N : Node_Id) return Traverse_Result; -- Replace occurrence of a formal with the corresponding actual, or -- the thunk generated for it. function Process_Sloc (Nod : Node_Id) return Traverse_Result; -- If the call being expanded is that of an internal subprogram, -- set the sloc of the generated block to that of the call itself, -- so that the expansion is skipped by the -next- command in gdb. -- Same processing for a subprogram in a predefined file, e.g. -- Ada.Tags. If Debug_Generated_Code is true, suppress this change -- to simplify our own development. procedure Rewrite_Function_Call (N : Node_Id; Blk : Node_Id); -- If the function body is a single expression, replace call with -- expression, else insert block appropriately. procedure Rewrite_Procedure_Call (N : Node_Id; Blk : Node_Id); -- If procedure body has no local variables, inline body without -- creating block, otherwise rewrite call with block. function Formal_Is_Used_Once (Formal : Entity_Id) return Boolean; -- Determine whether a formal parameter is used only once in Orig_Bod ----------------- -- Find_Result -- ----------------- procedure Find_Result is Decl : Node_Id; Id : Node_Id; function Get_Return (N : Node_Id) return Traverse_Result; -- Recursive function to locate return statements in body. function Get_Return (N : Node_Id) return Traverse_Result is begin if Nkind (N) = N_Return_Statement then Id := Expression (N); return Abandon; else return OK; end if; end Get_Return; procedure Find_It is new Traverse_Proc (Get_Return); -- Start of processing for Find_Result begin Find_It (Handled_Statement_Sequence (Orig_Bod)); -- At this point the body is unanalyzed. Traverse the list of -- declarations to locate the defining_identifier for it. Decl := First (Declarations (Blk)); while Present (Decl) loop if Chars (Defining_Identifier (Decl)) = Chars (Id) then Targ1 := Defining_Identifier (Decl); exit; else Next (Decl); end if; end loop; end Find_Result; --------------------- -- Make_Exit_Label -- --------------------- procedure Make_Exit_Label is begin -- Create exit label for subprogram if one does not exist yet if No (Exit_Lab) then Lab_Id := Make_Identifier (Loc, New_Internal_Name ('L')); Set_Entity (Lab_Id, Make_Defining_Identifier (Loc, Chars (Lab_Id))); Exit_Lab := Make_Label (Loc, Lab_Id); Lab_Decl := Make_Implicit_Label_Declaration (Loc, Defining_Identifier => Entity (Lab_Id), Label_Construct => Exit_Lab); end if; end Make_Exit_Label; --------------------- -- Process_Formals -- --------------------- function Process_Formals (N : Node_Id) return Traverse_Result is A : Entity_Id; E : Entity_Id; Ret : Node_Id; begin if Is_Entity_Name (N) and then Present (Entity (N)) then E := Entity (N); if Is_Formal (E) and then Scope (E) = Subp then A := Renamed_Object (E); if Is_Entity_Name (A) then Rewrite (N, New_Occurrence_Of (Entity (A), Loc)); elsif Nkind (A) = N_Defining_Identifier then Rewrite (N, New_Occurrence_Of (A, Loc)); else -- numeric literal Rewrite (N, New_Copy (A)); end if; end if; return Skip; elsif Nkind (N) = N_Return_Statement then if No (Expression (N)) then Make_Exit_Label; Rewrite (N, Make_Goto_Statement (Loc, Name => New_Copy (Lab_Id))); else if Nkind (Parent (N)) = N_Handled_Sequence_Of_Statements and then Nkind (Parent (Parent (N))) = N_Subprogram_Body then -- Function body is a single expression. No need for -- exit label. null; else Num_Ret := Num_Ret + 1; Make_Exit_Label; end if; -- Because of the presence of private types, the views of the -- expression and the context may be different, so place an -- unchecked conversion to the context type to avoid spurious -- errors, eg. when the expression is a numeric literal and -- the context is private. If the expression is an aggregate, -- use a qualified expression, because an aggregate is not a -- legal argument of a conversion. if Nkind (Expression (N)) = N_Aggregate or else Nkind (Expression (N)) = N_Null then Ret := Make_Qualified_Expression (Sloc (N), Subtype_Mark => New_Occurrence_Of (Ret_Type, Sloc (N)), Expression => Relocate_Node (Expression (N))); else Ret := Unchecked_Convert_To (Ret_Type, Relocate_Node (Expression (N))); end if; if Nkind (Targ) = N_Defining_Identifier then Rewrite (N, Make_Assignment_Statement (Loc, Name => New_Occurrence_Of (Targ, Loc), Expression => Ret)); else Rewrite (N, Make_Assignment_Statement (Loc, Name => New_Copy (Targ), Expression => Ret)); end if; Set_Assignment_OK (Name (N)); if Present (Exit_Lab) then Insert_After (N, Make_Goto_Statement (Loc, Name => New_Copy (Lab_Id))); end if; end if; return OK; -- Remove pragma Unreferenced since it may refer to formals that -- are not visible in the inlined body, and in any case we will -- not be posting warnings on the inlined body so it is unneeded. elsif Nkind (N) = N_Pragma and then Chars (N) = Name_Unreferenced then Rewrite (N, Make_Null_Statement (Sloc (N))); return OK; else return OK; end if; end Process_Formals; procedure Replace_Formals is new Traverse_Proc (Process_Formals); ------------------ -- Process_Sloc -- ------------------ function Process_Sloc (Nod : Node_Id) return Traverse_Result is begin if not Debug_Generated_Code then Set_Sloc (Nod, Sloc (N)); Set_Comes_From_Source (Nod, False); end if; return OK; end Process_Sloc; procedure Reset_Slocs is new Traverse_Proc (Process_Sloc); --------------------------- -- Rewrite_Function_Call -- --------------------------- procedure Rewrite_Function_Call (N : Node_Id; Blk : Node_Id) is HSS : constant Node_Id := Handled_Statement_Sequence (Blk); Fst : constant Node_Id := First (Statements (HSS)); begin -- Optimize simple case: function body is a single return statement, -- which has been expanded into an assignment. if Is_Empty_List (Declarations (Blk)) and then Nkind (Fst) = N_Assignment_Statement and then No (Next (Fst)) then -- The function call may have been rewritten as the temporary -- that holds the result of the call, in which case remove the -- now useless declaration. if Nkind (N) = N_Identifier and then Nkind (Parent (Entity (N))) = N_Object_Declaration then Rewrite (Parent (Entity (N)), Make_Null_Statement (Loc)); end if; Rewrite (N, Expression (Fst)); elsif Nkind (N) = N_Identifier and then Nkind (Parent (Entity (N))) = N_Object_Declaration then -- The block assigns the result of the call to the temporary Insert_After (Parent (Entity (N)), Blk); elsif Nkind (Parent (N)) = N_Assignment_Statement and then (Is_Entity_Name (Name (Parent (N))) or else (Nkind (Name (Parent (N))) = N_Explicit_Dereference and then Is_Entity_Name (Prefix (Name (Parent (N)))))) then -- Replace assignment with the block declare Original_Assignment : constant Node_Id := Parent (N); begin -- Preserve the original assignment node to keep the complete -- assignment subtree consistent enough for Analyze_Assignment -- to proceed (specifically, the original Lhs node must still -- have an assignment statement as its parent). -- We cannot rely on Original_Node to go back from the block -- node to the assignment node, because the assignment might -- already be a rewrite substitution. Discard_Node (Relocate_Node (Original_Assignment)); Rewrite (Original_Assignment, Blk); end; elsif Nkind (Parent (N)) = N_Object_Declaration then Set_Expression (Parent (N), Empty); Insert_After (Parent (N), Blk); elsif Is_Unc then Insert_Before (Parent (N), Blk); end if; end Rewrite_Function_Call; ---------------------------- -- Rewrite_Procedure_Call -- ---------------------------- procedure Rewrite_Procedure_Call (N : Node_Id; Blk : Node_Id) is HSS : constant Node_Id := Handled_Statement_Sequence (Blk); begin if Is_Empty_List (Declarations (Blk)) then Insert_List_After (N, Statements (HSS)); Rewrite (N, Make_Null_Statement (Loc)); else Rewrite (N, Blk); end if; end Rewrite_Procedure_Call; ------------------------- -- Formal_Is_Used_Once -- ------------------------ function Formal_Is_Used_Once (Formal : Entity_Id) return Boolean is Use_Counter : Int := 0; function Count_Uses (N : Node_Id) return Traverse_Result; -- Traverse the tree and count the uses of the formal parameter. -- In this case, for optimization purposes, we do not need to -- continue the traversal once more than one use is encountered. ---------------- -- Count_Uses -- ---------------- function Count_Uses (N : Node_Id) return Traverse_Result is begin -- The original node is an identifier if Nkind (N) = N_Identifier and then Present (Entity (N)) -- Original node's entity points to the one in the copied body and then Nkind (Entity (N)) = N_Identifier and then Present (Entity (Entity (N))) -- The entity of the copied node is the formal parameter and then Entity (Entity (N)) = Formal then Use_Counter := Use_Counter + 1; if Use_Counter > 1 then -- Denote more than one use and abandon the traversal Use_Counter := 2; return Abandon; end if; end if; return OK; end Count_Uses; procedure Count_Formal_Uses is new Traverse_Proc (Count_Uses); -- Start of processing for Formal_Is_Used_Once begin Count_Formal_Uses (Orig_Bod); return Use_Counter = 1; end Formal_Is_Used_Once; -- Start of processing for Expand_Inlined_Call begin -- Check for special case of To_Address call, and if so, just do an -- unchecked conversion instead of expanding the call. Not only is this -- more efficient, but it also avoids problem with order of elaboration -- when address clauses are inlined (address expression elaborated at -- wrong point). if Subp = RTE (RE_To_Address) then Rewrite (N, Unchecked_Convert_To (RTE (RE_Address), Relocate_Node (First_Actual (N)))); return; end if; -- Check for an illegal attempt to inline a recursive procedure. If the -- subprogram has parameters this is detected when trying to supply a -- binding for parameters that already have one. For parameterless -- subprograms this must be done explicitly. if In_Open_Scopes (Subp) then Error_Msg_N ("call to recursive subprogram cannot be inlined?", N); Set_Is_Inlined (Subp, False); return; end if; if Nkind (Orig_Bod) = N_Defining_Identifier or else Nkind (Orig_Bod) = N_Defining_Operator_Symbol then -- Subprogram is a renaming_as_body. Calls appearing after the -- renaming can be replaced with calls to the renamed entity -- directly, because the subprograms are subtype conformant. If -- the renamed subprogram is an inherited operation, we must redo -- the expansion because implicit conversions may be needed. Set_Name (N, New_Occurrence_Of (Orig_Bod, Loc)); if Present (Alias (Orig_Bod)) then Expand_Call (N); end if; return; end if; -- Use generic machinery to copy body of inlined subprogram, as if it -- were an instantiation, resetting source locations appropriately, so -- that nested inlined calls appear in the main unit. Save_Env (Subp, Empty); Set_Copied_Sloc_For_Inlined_Body (N, Defining_Entity (Orig_Bod)); Bod := Copy_Generic_Node (Orig_Bod, Empty, Instantiating => True); Blk := Make_Block_Statement (Loc, Declarations => Declarations (Bod), Handled_Statement_Sequence => Handled_Statement_Sequence (Bod)); if No (Declarations (Bod)) then Set_Declarations (Blk, New_List); end if; -- For the unconstrained case, capture the name of the local -- variable that holds the result. if Is_Unc then Find_Result; end if; -- If this is a derived function, establish the proper return type if Present (Orig_Subp) and then Orig_Subp /= Subp then Ret_Type := Etype (Orig_Subp); else Ret_Type := Etype (Subp); end if; -- Create temporaries for the actuals that are expressions, or that -- are scalars and require copying to preserve semantics. F := First_Formal (Subp); A := First_Actual (N); while Present (F) loop if Present (Renamed_Object (F)) then Error_Msg_N ("cannot inline call to recursive subprogram", N); return; end if; -- If the argument may be a controlling argument in a call within -- the inlined body, we must preserve its classwide nature to insure -- that dynamic dispatching take place subsequently. If the formal -- has a constraint it must be preserved to retain the semantics of -- the body. if Is_Class_Wide_Type (Etype (F)) or else (Is_Access_Type (Etype (F)) and then Is_Class_Wide_Type (Designated_Type (Etype (F)))) then Temp_Typ := Etype (F); elsif Base_Type (Etype (F)) = Base_Type (Etype (A)) and then Etype (F) /= Base_Type (Etype (F)) then Temp_Typ := Etype (F); else Temp_Typ := Etype (A); end if; -- If the actual is a simple name or a literal, no need to -- create a temporary, object can be used directly. if (Is_Entity_Name (A) and then (not Is_Scalar_Type (Etype (A)) or else Ekind (Entity (A)) = E_Enumeration_Literal)) -- When the actual is an identifier and the corresponding formal -- is used only once in the original body, the formal can be -- substituted directly with the actual parameter. or else (Nkind (A) = N_Identifier and then Formal_Is_Used_Once (F)) or else Nkind (A) = N_Real_Literal or else Nkind (A) = N_Integer_Literal or else Nkind (A) = N_Character_Literal then if Etype (F) /= Etype (A) then Set_Renamed_Object (F, Unchecked_Convert_To (Etype (F), Relocate_Node (A))); else Set_Renamed_Object (F, A); end if; else Temp := Make_Defining_Identifier (Loc, Chars => New_Internal_Name ('C')); -- If the actual for an in/in-out parameter is a view conversion, -- make it into an unchecked conversion, given that an untagged -- type conversion is not a proper object for a renaming. -- In-out conversions that involve real conversions have already -- been transformed in Expand_Actuals. if Nkind (A) = N_Type_Conversion and then Ekind (F) /= E_In_Parameter then New_A := Make_Unchecked_Type_Conversion (Loc, Subtype_Mark => New_Occurrence_Of (Etype (F), Loc), Expression => Relocate_Node (Expression (A))); elsif Etype (F) /= Etype (A) then New_A := Unchecked_Convert_To (Etype (F), Relocate_Node (A)); Temp_Typ := Etype (F); else New_A := Relocate_Node (A); end if; Set_Sloc (New_A, Sloc (N)); if Ekind (F) = E_In_Parameter and then not Is_Limited_Type (Etype (A)) then Decl := Make_Object_Declaration (Loc, Defining_Identifier => Temp, Constant_Present => True, Object_Definition => New_Occurrence_Of (Temp_Typ, Loc), Expression => New_A); else Decl := Make_Object_Renaming_Declaration (Loc, Defining_Identifier => Temp, Subtype_Mark => New_Occurrence_Of (Temp_Typ, Loc), Name => New_A); end if; Append (Decl, Decls); Set_Renamed_Object (F, Temp); end if; Next_Formal (F); Next_Actual (A); end loop; -- Establish target of function call. If context is not assignment or -- declaration, create a temporary as a target. The declaration for -- the temporary may be subsequently optimized away if the body is a -- single expression, or if the left-hand side of the assignment is -- simple enough, i.e. an entity or an explicit dereference of one. if Ekind (Subp) = E_Function then if Nkind (Parent (N)) = N_Assignment_Statement and then Is_Entity_Name (Name (Parent (N))) then Targ := Name (Parent (N)); elsif Nkind (Parent (N)) = N_Assignment_Statement and then Nkind (Name (Parent (N))) = N_Explicit_Dereference and then Is_Entity_Name (Prefix (Name (Parent (N)))) then Targ := Name (Parent (N)); else -- Replace call with temporary and create its declaration Temp := Make_Defining_Identifier (Loc, New_Internal_Name ('C')); Set_Is_Internal (Temp); -- For the unconstrained case. the generated temporary has the -- same constrained declaration as the result variable. -- It may eventually be possible to remove that temporary and -- use the result variable directly. if Is_Unc then Decl := Make_Object_Declaration (Loc, Defining_Identifier => Temp, Object_Definition => New_Copy_Tree (Object_Definition (Parent (Targ1)))); Replace_Formals (Decl); else Decl := Make_Object_Declaration (Loc, Defining_Identifier => Temp, Object_Definition => New_Occurrence_Of (Ret_Type, Loc)); Set_Etype (Temp, Ret_Type); end if; Set_No_Initialization (Decl); Append (Decl, Decls); Rewrite (N, New_Occurrence_Of (Temp, Loc)); Targ := Temp; end if; end if; Insert_Actions (N, Decls); -- Traverse the tree and replace formals with actuals or their thunks. -- Attach block to tree before analysis and rewriting. Replace_Formals (Blk); Set_Parent (Blk, N); if not Comes_From_Source (Subp) or else Is_Predef then Reset_Slocs (Blk); end if; if Present (Exit_Lab) then -- If the body was a single expression, the single return statement -- and the corresponding label are useless. if Num_Ret = 1 and then Nkind (Last (Statements (Handled_Statement_Sequence (Blk)))) = N_Goto_Statement then Remove (Last (Statements (Handled_Statement_Sequence (Blk)))); else Append (Lab_Decl, (Declarations (Blk))); Append (Exit_Lab, Statements (Handled_Statement_Sequence (Blk))); end if; end if; -- Analyze Blk with In_Inlined_Body set, to avoid spurious errors on -- conflicting private views that Gigi would ignore. If this is -- predefined unit, analyze with checks off, as is done in the non- -- inlined run-time units. declare I_Flag : constant Boolean := In_Inlined_Body; begin In_Inlined_Body := True; if Is_Predef then declare Style : constant Boolean := Style_Check; begin Style_Check := False; Analyze (Blk, Suppress => All_Checks); Style_Check := Style; end; else Analyze (Blk); end if; In_Inlined_Body := I_Flag; end; if Ekind (Subp) = E_Procedure then Rewrite_Procedure_Call (N, Blk); else Rewrite_Function_Call (N, Blk); -- For the unconstrained case, the replacement of the call has been -- made prior to the complete analysis of the generated declarations. -- Propagate the proper type now. if Is_Unc then if Nkind (N) = N_Identifier then Set_Etype (N, Etype (Entity (N))); else Set_Etype (N, Etype (Targ1)); end if; end if; end if; Restore_Env; -- Cleanup mapping between formals and actuals for other expansions F := First_Formal (Subp); while Present (F) loop Set_Renamed_Object (F, Empty); Next_Formal (F); end loop; end Expand_Inlined_Call; ---------------------------- -- Expand_N_Function_Call -- ---------------------------- procedure Expand_N_Function_Call (N : Node_Id) is Typ : constant Entity_Id := Etype (N); function Returned_By_Reference return Boolean; -- If the return type is returned through the secondary stack. that is -- by reference, we don't want to create a temp to force stack checking. -- Shouldn't this function be moved to exp_util??? function Rhs_Of_Assign_Or_Decl (N : Node_Id) return Boolean; -- If the call is the right side of an assignment or the expression in -- an object declaration, we don't need to create a temp as the left -- side will already trigger stack checking if necessary. -- -- If the call is a component in an extension aggregate, it will be -- expanded into assignments as well, so no temporary is needed. This -- also solves the problem of functions returning types with unknown -- discriminants, where it is not possible to declare an object of the -- type altogether. --------------------------- -- Returned_By_Reference -- --------------------------- function Returned_By_Reference return Boolean is S : Entity_Id; begin if Is_Return_By_Reference_Type (Typ) then return True; elsif Nkind (Parent (N)) /= N_Return_Statement then return False; elsif Requires_Transient_Scope (Typ) then -- Verify that the return type of the enclosing function has the -- same constrained status as that of the expression. S := Current_Scope; while Ekind (S) /= E_Function loop S := Scope (S); end loop; return Is_Constrained (Typ) = Is_Constrained (Etype (S)); else return False; end if; end Returned_By_Reference; --------------------------- -- Rhs_Of_Assign_Or_Decl -- --------------------------- function Rhs_Of_Assign_Or_Decl (N : Node_Id) return Boolean is begin if (Nkind (Parent (N)) = N_Assignment_Statement and then Expression (Parent (N)) = N) or else (Nkind (Parent (N)) = N_Qualified_Expression and then Nkind (Parent (Parent (N))) = N_Assignment_Statement and then Expression (Parent (Parent (N))) = Parent (N)) or else (Nkind (Parent (N)) = N_Object_Declaration and then Expression (Parent (N)) = N) or else (Nkind (Parent (N)) = N_Component_Association and then Expression (Parent (N)) = N and then Nkind (Parent (Parent (N))) = N_Aggregate and then Rhs_Of_Assign_Or_Decl (Parent (Parent (N)))) or else (Nkind (Parent (N)) = N_Extension_Aggregate and then Is_Private_Type (Etype (Typ))) then return True; else return False; end if; end Rhs_Of_Assign_Or_Decl; -- Start of processing for Expand_N_Function_Call begin -- A special check. If stack checking is enabled, and the return type -- might generate a large temporary, and the call is not the right side -- of an assignment, then generate an explicit temporary. We do this -- because otherwise gigi may generate a large temporary on the fly and -- this can cause trouble with stack checking. -- This is unecessary if the call is the expression in an object -- declaration, or if it appears outside of any library unit. This can -- only happen if it appears as an actual in a library-level instance, -- in which case a temporary will be generated for it once the instance -- itself is installed. if May_Generate_Large_Temp (Typ) and then not Rhs_Of_Assign_Or_Decl (N) and then not Returned_By_Reference and then Current_Scope /= Standard_Standard then if Stack_Checking_Enabled then -- Note: it might be thought that it would be OK to use a call to -- Force_Evaluation here, but that's not good enough, because -- that can results in a 'Reference construct that may still need -- a temporary. declare Loc : constant Source_Ptr := Sloc (N); Temp_Obj : constant Entity_Id := Make_Defining_Identifier (Loc, Chars => New_Internal_Name ('F')); Temp_Typ : Entity_Id := Typ; Decl : Node_Id; A : Node_Id; F : Entity_Id; Proc : Entity_Id; begin if Is_Tagged_Type (Typ) and then Present (Controlling_Argument (N)) then if Nkind (Parent (N)) /= N_Procedure_Call_Statement and then Nkind (Parent (N)) /= N_Function_Call then -- If this is a tag-indeterminate call, the object must -- be classwide. if Is_Tag_Indeterminate (N) then Temp_Typ := Class_Wide_Type (Typ); end if; else -- If this is a dispatching call that is itself the -- controlling argument of an enclosing call, the -- nominal subtype of the object that replaces it must -- be classwide, so that dispatching will take place -- properly. If it is not a controlling argument, the -- object is not classwide. Proc := Entity (Name (Parent (N))); F := First_Formal (Proc); A := First_Actual (Parent (N)); while A /= N loop Next_Formal (F); Next_Actual (A); end loop; if Is_Controlling_Formal (F) then Temp_Typ := Class_Wide_Type (Typ); end if; end if; end if; Decl := Make_Object_Declaration (Loc, Defining_Identifier => Temp_Obj, Object_Definition => New_Occurrence_Of (Temp_Typ, Loc), Constant_Present => True, Expression => Relocate_Node (N)); Set_Assignment_OK (Decl); Insert_Actions (N, New_List (Decl)); Rewrite (N, New_Occurrence_Of (Temp_Obj, Loc)); end; else -- If stack-checking is not enabled, increment serial number -- for internal names, so that subsequent symbols are consistent -- with and without stack-checking. Synchronize_Serial_Number; -- Now we can expand the call with consistent symbol names Expand_Call (N); end if; -- Normal case, expand the call else Expand_Call (N); end if; end Expand_N_Function_Call; --------------------------------------- -- Expand_N_Procedure_Call_Statement -- --------------------------------------- procedure Expand_N_Procedure_Call_Statement (N : Node_Id) is begin Expand_Call (N); end Expand_N_Procedure_Call_Statement; ------------------------------ -- Expand_N_Subprogram_Body -- ------------------------------ -- Add poll call if ATC polling is enabled, unless the body will be -- inlined by the back-end. -- Add return statement if last statement in body is not a return statement -- (this makes things easier on Gigi which does not want to have to handle -- a missing return). -- Add call to Activate_Tasks if body is a task activator -- Deal with possible detection of infinite recursion -- Eliminate body completely if convention stubbed -- Encode entity names within body, since we will not need to reference -- these entities any longer in the front end. -- Initialize scalar out parameters if Initialize/Normalize_Scalars -- Reset Pure indication if any parameter has root type System.Address -- Wrap thread body procedure Expand_N_Subprogram_Body (N : Node_Id) is Loc : constant Source_Ptr := Sloc (N); H : constant Node_Id := Handled_Statement_Sequence (N); Body_Id : Entity_Id; Spec_Id : Entity_Id; Except_H : Node_Id; Scop : Entity_Id; Dec : Node_Id; Next_Op : Node_Id; L : List_Id; procedure Add_Return (S : List_Id); -- Append a return statement to the statement sequence S if the last -- statement is not already a return or a goto statement. Note that -- the latter test is not critical, it does not matter if we add a -- few extra returns, since they get eliminated anyway later on. procedure Expand_Thread_Body; -- Perform required expansion of a thread body ---------------- -- Add_Return -- ---------------- procedure Add_Return (S : List_Id) is begin if not Is_Transfer (Last (S)) then -- The source location for the return is the end label -- of the procedure in all cases. This is a bit odd when -- there are exception handlers, but not much else we can do. Append_To (S, Make_Return_Statement (Sloc (End_Label (H)))); end if; end Add_Return; ------------------------ -- Expand_Thread_Body -- ------------------------ -- The required expansion of a thread body is as follows -- procedure <thread body procedure name> is -- _Secondary_Stack : aliased -- Storage_Elements.Storage_Array -- (1 .. Storage_Offset (Sec_Stack_Size)); -- for _Secondary_Stack'Alignment use Standard'Maximum_Alignment; -- _Process_ATSD : aliased System.Threads.ATSD; -- begin -- System.Threads.Thread_Body_Enter; -- (_Secondary_Stack'Address, -- _Secondary_Stack'Length, -- _Process_ATSD'Address); -- declare -- <user declarations> -- begin -- <user statements> -- <user exception handlers> -- end; -- System.Threads.Thread_Body_Leave; -- exception -- when E : others => -- System.Threads.Thread_Body_Exceptional_Exit (E); -- end; -- Note the exception handler is omitted if pragma Restriction -- No_Exception_Handlers is currently active. procedure Expand_Thread_Body is User_Decls : constant List_Id := Declarations (N); Sec_Stack_Len : Node_Id; TB_Pragma : constant Node_Id := Get_Rep_Pragma (Spec_Id, Name_Thread_Body); Ent_SS : Entity_Id; Ent_ATSD : Entity_Id; Ent_EO : Entity_Id; Decl_SS : Node_Id; Decl_ATSD : Node_Id; Excep_Handlers : List_Id; begin New_Scope (Spec_Id); -- Get proper setting for secondary stack size if List_Length (Pragma_Argument_Associations (TB_Pragma)) = 2 then Sec_Stack_Len := Expression (Last (Pragma_Argument_Associations (TB_Pragma))); else Sec_Stack_Len := New_Occurrence_Of (RTE (RE_Default_Secondary_Stack_Size), Loc); end if; Sec_Stack_Len := Convert_To (RTE (RE_Storage_Offset), Sec_Stack_Len); -- Build and set declarations for the wrapped thread body Ent_SS := Make_Defining_Identifier (Loc, Name_uSecondary_Stack); Ent_ATSD := Make_Defining_Identifier (Loc, Name_uProcess_ATSD); Decl_SS := Make_Object_Declaration (Loc, Defining_Identifier => Ent_SS, Aliased_Present => True, Object_Definition => Make_Subtype_Indication (Loc, Subtype_Mark => New_Occurrence_Of (RTE (RE_Storage_Array), Loc), Constraint => Make_Index_Or_Discriminant_Constraint (Loc, Constraints => New_List ( Make_Range (Loc, Low_Bound => Make_Integer_Literal (Loc, 1), High_Bound => Sec_Stack_Len))))); Decl_ATSD := Make_Object_Declaration (Loc, Defining_Identifier => Ent_ATSD, Aliased_Present => True, Object_Definition => New_Occurrence_Of (RTE (RE_ATSD), Loc)); Set_Declarations (N, New_List (Decl_SS, Decl_ATSD)); Analyze (Decl_SS); Analyze (Decl_ATSD); Set_Alignment (Ent_SS, UI_From_Int (Maximum_Alignment)); -- Create new exception handler if Restriction_Active (No_Exception_Handlers) then Excep_Handlers := No_List; else Check_Restriction (No_Exception_Handlers, N); Ent_EO := Make_Defining_Identifier (Loc, Name_uE); Excep_Handlers := New_List ( Make_Exception_Handler (Loc, Choice_Parameter => Ent_EO, Exception_Choices => New_List ( Make_Others_Choice (Loc)), Statements => New_List ( Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Thread_Body_Exceptional_Exit), Loc), Parameter_Associations => New_List ( New_Occurrence_Of (Ent_EO, Loc)))))); end if; -- Now build new handled statement sequence and analyze it Set_Handled_Statement_Sequence (N, Make_Handled_Sequence_Of_Statements (Loc, Statements => New_List ( Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Thread_Body_Enter), Loc), Parameter_Associations => New_List ( Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Ent_SS, Loc), Attribute_Name => Name_Address), Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Ent_SS, Loc), Attribute_Name => Name_Length), Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Ent_ATSD, Loc), Attribute_Name => Name_Address))), Make_Block_Statement (Loc, Declarations => User_Decls, Handled_Statement_Sequence => H), Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Thread_Body_Leave), Loc))), Exception_Handlers => Excep_Handlers)); Analyze (Handled_Statement_Sequence (N)); End_Scope; end Expand_Thread_Body; -- Start of processing for Expand_N_Subprogram_Body begin -- Set L to either the list of declarations if present, or -- to the list of statements if no declarations are present. -- This is used to insert new stuff at the start. if Is_Non_Empty_List (Declarations (N)) then L := Declarations (N); else L := Statements (Handled_Statement_Sequence (N)); end if; -- Find entity for subprogram Body_Id := Defining_Entity (N); if Present (Corresponding_Spec (N)) then Spec_Id := Corresponding_Spec (N); else Spec_Id := Body_Id; end if; -- Need poll on entry to subprogram if polling enabled. We only -- do this for non-empty subprograms, since it does not seem -- necessary to poll for a dummy null subprogram. Do not add polling -- point if calls to this subprogram will be inlined by the back-end, -- to avoid repeated polling points in nested inlinings. if Is_Non_Empty_List (L) then if Is_Inlined (Spec_Id) and then Front_End_Inlining and then Optimization_Level > 1 then null; else Generate_Poll_Call (First (L)); end if; end if; -- If this is a Pure function which has any parameters whose root -- type is System.Address, reset the Pure indication, since it will -- likely cause incorrect code to be generated as the parameter is -- probably a pointer, and the fact that the same pointer is passed -- does not mean that the same value is being referenced. -- Note that if the programmer gave an explicit Pure_Function pragma, -- then we believe the programmer, and leave the subprogram Pure. -- This code should probably be at the freeze point, so that it -- happens even on a -gnatc (or more importantly -gnatt) compile -- so that the semantic tree has Is_Pure set properly ??? if Is_Pure (Spec_Id) and then Is_Subprogram (Spec_Id) and then not Has_Pragma_Pure_Function (Spec_Id) then declare F : Entity_Id; begin F := First_Formal (Spec_Id); while Present (F) loop if Is_Descendent_Of_Address (Etype (F)) then Set_Is_Pure (Spec_Id, False); if Spec_Id /= Body_Id then Set_Is_Pure (Body_Id, False); end if; exit; end if; Next_Formal (F); end loop; end; end if; -- Initialize any scalar OUT args if Initialize/Normalize_Scalars if Init_Or_Norm_Scalars and then Is_Subprogram (Spec_Id) then declare F : Entity_Id; V : constant Boolean := Validity_Checks_On; begin -- We turn off validity checking, since we do not want any -- check on the initializing value itself (which we know -- may well be invalid!) Validity_Checks_On := False; -- Loop through formals F := First_Formal (Spec_Id); while Present (F) loop if Is_Scalar_Type (Etype (F)) and then Ekind (F) = E_Out_Parameter then Insert_Before_And_Analyze (First (L), Make_Assignment_Statement (Loc, Name => New_Occurrence_Of (F, Loc), Expression => Get_Simple_Init_Val (Etype (F), Loc))); end if; Next_Formal (F); end loop; Validity_Checks_On := V; end; end if; Scop := Scope (Spec_Id); -- Add discriminal renamings to protected subprograms. Install new -- discriminals for expansion of the next subprogram of this protected -- type, if any. if Is_List_Member (N) and then Present (Parent (List_Containing (N))) and then Nkind (Parent (List_Containing (N))) = N_Protected_Body then Add_Discriminal_Declarations (Declarations (N), Scop, Name_uObject, Loc); Add_Private_Declarations (Declarations (N), Scop, Name_uObject, Loc); -- Associate privals and discriminals with the next protected -- operation body to be expanded. These are used to expand references -- to private data objects and discriminants, respectively. Next_Op := Next_Protected_Operation (N); if Present (Next_Op) then Dec := Parent (Base_Type (Scop)); Set_Privals (Dec, Next_Op, Loc); Set_Discriminals (Dec); end if; end if; -- Clear out statement list for stubbed procedure if Present (Corresponding_Spec (N)) then Set_Elaboration_Flag (N, Spec_Id); if Convention (Spec_Id) = Convention_Stubbed or else Is_Eliminated (Spec_Id) then Set_Declarations (N, Empty_List); Set_Handled_Statement_Sequence (N, Make_Handled_Sequence_Of_Statements (Loc, Statements => New_List ( Make_Null_Statement (Loc)))); return; end if; end if; -- Returns_By_Ref flag is normally set when the subprogram is frozen -- but subprograms with no specs are not frozen. declare Typ : constant Entity_Id := Etype (Spec_Id); Utyp : constant Entity_Id := Underlying_Type (Typ); begin if not Acts_As_Spec (N) and then Nkind (Parent (Parent (Spec_Id))) /= N_Subprogram_Body_Stub then null; elsif Is_Return_By_Reference_Type (Typ) then Set_Returns_By_Ref (Spec_Id); elsif Present (Utyp) and then Controlled_Type (Utyp) then Set_Returns_By_Ref (Spec_Id); end if; end; -- For a procedure, we add a return for all possible syntactic ends -- of the subprogram. Note that reanalysis is not necessary in this -- case since it would require a lot of work and accomplish nothing. if Ekind (Spec_Id) = E_Procedure or else Ekind (Spec_Id) = E_Generic_Procedure then Add_Return (Statements (H)); if Present (Exception_Handlers (H)) then Except_H := First_Non_Pragma (Exception_Handlers (H)); while Present (Except_H) loop Add_Return (Statements (Except_H)); Next_Non_Pragma (Except_H); end loop; end if; -- For a function, we must deal with the case where there is at least -- one missing return. What we do is to wrap the entire body of the -- function in a block: -- begin -- ... -- end; -- becomes -- begin -- begin -- ... -- end; -- raise Program_Error; -- end; -- This approach is necessary because the raise must be signalled -- to the caller, not handled by any local handler (RM 6.4(11)). -- Note: we do not need to analyze the constructed sequence here, -- since it has no handler, and an attempt to analyze the handled -- statement sequence twice is risky in various ways (e.g. the -- issue of expanding cleanup actions twice). elsif Has_Missing_Return (Spec_Id) then declare Hloc : constant Source_Ptr := Sloc (H); Blok : constant Node_Id := Make_Block_Statement (Hloc, Handled_Statement_Sequence => H); Rais : constant Node_Id := Make_Raise_Program_Error (Hloc, Reason => PE_Missing_Return); begin Set_Handled_Statement_Sequence (N, Make_Handled_Sequence_Of_Statements (Hloc, Statements => New_List (Blok, Rais))); New_Scope (Spec_Id); Analyze (Blok); Analyze (Rais); Pop_Scope; end; end if; -- If subprogram contains a parameterless recursive call, then we may -- have an infinite recursion, so see if we can generate code to check -- for this possibility if storage checks are not suppressed. if Ekind (Spec_Id) = E_Procedure and then Has_Recursive_Call (Spec_Id) and then not Storage_Checks_Suppressed (Spec_Id) then Detect_Infinite_Recursion (N, Spec_Id); end if; -- Finally, if we are in Normalize_Scalars mode, then any scalar out -- parameters must be initialized to the appropriate default value. if Ekind (Spec_Id) = E_Procedure and then Normalize_Scalars then declare Floc : Source_Ptr; Formal : Entity_Id; Stm : Node_Id; begin Formal := First_Formal (Spec_Id); while Present (Formal) loop Floc := Sloc (Formal); if Ekind (Formal) = E_Out_Parameter and then Is_Scalar_Type (Etype (Formal)) then Stm := Make_Assignment_Statement (Floc, Name => New_Occurrence_Of (Formal, Floc), Expression => Get_Simple_Init_Val (Etype (Formal), Floc)); Prepend (Stm, Declarations (N)); Analyze (Stm); end if; Next_Formal (Formal); end loop; end; end if; -- Deal with thread body if Is_Thread_Body (Spec_Id) then Expand_Thread_Body; end if; -- Set to encode entity names in package body before gigi is called Qualify_Entity_Names (N); end Expand_N_Subprogram_Body; ----------------------------------- -- Expand_N_Subprogram_Body_Stub -- ----------------------------------- procedure Expand_N_Subprogram_Body_Stub (N : Node_Id) is begin if Present (Corresponding_Body (N)) then Expand_N_Subprogram_Body ( Unit_Declaration_Node (Corresponding_Body (N))); end if; end Expand_N_Subprogram_Body_Stub; ------------------------------------- -- Expand_N_Subprogram_Declaration -- ------------------------------------- -- If the declaration appears within a protected body, it is a private -- operation of the protected type. We must create the corresponding -- protected subprogram an associated formals. For a normal protected -- operation, this is done when expanding the protected type declaration. -- If the declaration is for a null procedure, emit null body procedure Expand_N_Subprogram_Declaration (N : Node_Id) is Loc : constant Source_Ptr := Sloc (N); Subp : constant Entity_Id := Defining_Entity (N); Scop : constant Entity_Id := Scope (Subp); Prot_Decl : Node_Id; Prot_Bod : Node_Id; Prot_Id : Entity_Id; begin -- Deal with case of protected subprogram. Do not generate protected -- operation if operation is flagged as eliminated. if Is_List_Member (N) and then Present (Parent (List_Containing (N))) and then Nkind (Parent (List_Containing (N))) = N_Protected_Body and then Is_Protected_Type (Scop) then if No (Protected_Body_Subprogram (Subp)) and then not Is_Eliminated (Subp) then Prot_Decl := Make_Subprogram_Declaration (Loc, Specification => Build_Protected_Sub_Specification (N, Scop, Unprotected_Mode)); -- The protected subprogram is declared outside of the protected -- body. Given that the body has frozen all entities so far, we -- analyze the subprogram and perform freezing actions explicitly. -- If the body is a subunit, the insertion point is before the -- stub in the parent. Prot_Bod := Parent (List_Containing (N)); if Nkind (Parent (Prot_Bod)) = N_Subunit then Prot_Bod := Corresponding_Stub (Parent (Prot_Bod)); end if; Insert_Before (Prot_Bod, Prot_Decl); Prot_Id := Defining_Unit_Name (Specification (Prot_Decl)); New_Scope (Scope (Scop)); Analyze (Prot_Decl); Create_Extra_Formals (Prot_Id); Set_Protected_Body_Subprogram (Subp, Prot_Id); Pop_Scope; end if; elsif Nkind (Specification (N)) = N_Procedure_Specification and then Null_Present (Specification (N)) then declare Bod : constant Node_Id := Make_Subprogram_Body (Loc, Specification => New_Copy_Tree (Specification (N)), Declarations => New_List, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => New_List (Make_Null_Statement (Loc)))); begin Set_Body_To_Inline (N, Bod); Insert_After (N, Bod); Analyze (Bod); -- Corresponding_Spec isn't being set by Analyze_Subprogram_Body, -- evidently because Set_Has_Completion is called earlier for null -- procedures in Analyze_Subprogram_Declaration, so we force its -- setting here. If the setting of Has_Completion is not set -- earlier, then it can result in missing body errors if other -- errors were already reported (since expansion is turned off). -- Should creation of the empty body be moved to the analyzer??? Set_Corresponding_Spec (Bod, Defining_Entity (Specification (N))); end; end if; end Expand_N_Subprogram_Declaration; --------------------------------------- -- Expand_Protected_Object_Reference -- --------------------------------------- function Expand_Protected_Object_Reference (N : Node_Id; Scop : Entity_Id) return Node_Id is Loc : constant Source_Ptr := Sloc (N); Corr : Entity_Id; Rec : Node_Id; Param : Entity_Id; Proc : Entity_Id; begin Rec := Make_Identifier (Loc, Name_uObject); Set_Etype (Rec, Corresponding_Record_Type (Scop)); -- Find enclosing protected operation, and retrieve its first parameter, -- which denotes the enclosing protected object. If the enclosing -- operation is an entry, we are immediately within the protected body, -- and we can retrieve the object from the service entries procedure. A -- barrier function has has the same signature as an entry. A barrier -- function is compiled within the protected object, but unlike -- protected operations its never needs locks, so that its protected -- body subprogram points to itself. Proc := Current_Scope; while Present (Proc) and then Scope (Proc) /= Scop loop Proc := Scope (Proc); end loop; Corr := Protected_Body_Subprogram (Proc); if No (Corr) then -- Previous error left expansion incomplete. -- Nothing to do on this call. return Empty; end if; Param := Defining_Identifier (First (Parameter_Specifications (Parent (Corr)))); if Is_Subprogram (Proc) and then Proc /= Corr then -- Protected function or procedure Set_Entity (Rec, Param); -- Rec is a reference to an entity which will not be in scope when -- the call is reanalyzed, and needs no further analysis. Set_Analyzed (Rec); else -- Entry or barrier function for entry body. The first parameter of -- the entry body procedure is pointer to the object. We create a -- local variable of the proper type, duplicating what is done to -- define _object later on. declare Decls : List_Id; Obj_Ptr : constant Entity_Id := Make_Defining_Identifier (Loc, Chars => New_Internal_Name ('T')); begin Decls := New_List ( Make_Full_Type_Declaration (Loc, Defining_Identifier => Obj_Ptr, Type_Definition => Make_Access_To_Object_Definition (Loc, Subtype_Indication => New_Reference_To (Corresponding_Record_Type (Scop), Loc)))); Insert_Actions (N, Decls); Insert_Actions (N, Freeze_Entity (Obj_Ptr, Sloc (N))); Rec := Make_Explicit_Dereference (Loc, Unchecked_Convert_To (Obj_Ptr, New_Occurrence_Of (Param, Loc))); -- Analyze new actual. Other actuals in calls are already analyzed -- and the list of actuals is not renalyzed after rewriting. Set_Parent (Rec, N); Analyze (Rec); end; end if; return Rec; end Expand_Protected_Object_Reference; -------------------------------------- -- Expand_Protected_Subprogram_Call -- -------------------------------------- procedure Expand_Protected_Subprogram_Call (N : Node_Id; Subp : Entity_Id; Scop : Entity_Id) is Rec : Node_Id; begin -- If the protected object is not an enclosing scope, this is -- an inter-object function call. Inter-object procedure -- calls are expanded by Exp_Ch9.Build_Simple_Entry_Call. -- The call is intra-object only if the subprogram being -- called is in the protected body being compiled, and if the -- protected object in the call is statically the enclosing type. -- The object may be an component of some other data structure, -- in which case this must be handled as an inter-object call. if not In_Open_Scopes (Scop) or else not Is_Entity_Name (Name (N)) then if Nkind (Name (N)) = N_Selected_Component then Rec := Prefix (Name (N)); else pragma Assert (Nkind (Name (N)) = N_Indexed_Component); Rec := Prefix (Prefix (Name (N))); end if; Build_Protected_Subprogram_Call (N, Name => New_Occurrence_Of (Subp, Sloc (N)), Rec => Convert_Concurrent (Rec, Etype (Rec)), External => True); else Rec := Expand_Protected_Object_Reference (N, Scop); if No (Rec) then return; end if; Build_Protected_Subprogram_Call (N, Name => Name (N), Rec => Rec, External => False); end if; Analyze (N); -- If it is a function call it can appear in elaboration code and -- the called entity must be frozen here. if Ekind (Subp) = E_Function then Freeze_Expression (Name (N)); end if; end Expand_Protected_Subprogram_Call; ----------------------- -- Freeze_Subprogram -- ----------------------- procedure Freeze_Subprogram (N : Node_Id) is Loc : constant Source_Ptr := Sloc (N); E : constant Entity_Id := Entity (N); procedure Check_Overriding_Inherited_Interfaces (E : Entity_Id); -- (Ada 2005): Check if the primitive E covers some interface already -- implemented by some ancestor of the tagged-type associated with E. procedure Register_Interface_DT_Entry (Prim : Entity_Id; Ancestor_Iface_Prim : Entity_Id := Empty); -- (Ada 2005): Register an interface primitive in a secondary dispatch -- table. If Prim overrides an ancestor primitive of its associated -- tagged-type then Ancestor_Iface_Prim indicates the entity of that -- immediate ancestor associated with the interface. procedure Register_Predefined_DT_Entry (Prim : Entity_Id); -- (Ada 2005): Register a predefined primitive in all the secondary -- dispatch tables of its primitive type. ------------------------------------------- -- Check_Overriding_Inherited_Interfaces -- ------------------------------------------- procedure Check_Overriding_Inherited_Interfaces (E : Entity_Id) is Typ : Entity_Id; Elmt : Elmt_Id; Prim_Op : Entity_Id; Overriden_Op : Entity_Id := Empty; begin if Ada_Version < Ada_05 or else not Is_Overriding_Operation (E) or else Is_Predefined_Dispatching_Operation (E) or else Present (Alias (E)) then return; end if; -- Get the entity associated with this primitive operation Typ := Scope (DTC_Entity (E)); loop exit when Etype (Typ) = Typ or else (Present (Full_View (Etype (Typ))) and then Full_View (Etype (Typ)) = Typ); -- Climb to the immediate ancestor handling private types if Present (Full_View (Etype (Typ))) then Typ := Full_View (Etype (Typ)); else Typ := Etype (Typ); end if; if Present (Abstract_Interfaces (Typ)) then -- Look for the overriden subprogram in the primary dispatch -- table of the ancestor. Overriden_Op := Empty; Elmt := First_Elmt (Primitive_Operations (Typ)); while Present (Elmt) loop Prim_Op := Node (Elmt); if Chars (Prim_Op) = Chars (E) and then Type_Conformant (New_Id => Prim_Op, Old_Id => E, Skip_Controlling_Formals => True) and then DT_Position (Prim_Op) = DT_Position (E) and then Etype (DTC_Entity (Prim_Op)) = RTE (RE_Tag) and then No (Abstract_Interface_Alias (Prim_Op)) then if Overriden_Op = Empty then Overriden_Op := Prim_Op; -- Additional check to ensure that if two candidates have -- been found then they refer to the same subprogram. else declare A1 : Entity_Id; A2 : Entity_Id; begin A1 := Overriden_Op; while Present (Alias (A1)) loop A1 := Alias (A1); end loop; A2 := Prim_Op; while Present (Alias (A2)) loop A2 := Alias (A2); end loop; if A1 /= A2 then raise Program_Error; end if; end; end if; end if; Next_Elmt (Elmt); end loop; -- If not found this is the first overriding of some abstract -- interface. if Overriden_Op /= Empty then -- Find the entries associated with interfaces that are -- alias of this primitive operation in the ancestor. Elmt := First_Elmt (Primitive_Operations (Typ)); while Present (Elmt) loop Prim_Op := Node (Elmt); if Present (Abstract_Interface_Alias (Prim_Op)) and then Alias (Prim_Op) = Overriden_Op then Register_Interface_DT_Entry (E, Prim_Op); end if; Next_Elmt (Elmt); end loop; end if; end if; end loop; end Check_Overriding_Inherited_Interfaces; --------------------------------- -- Register_Interface_DT_Entry -- --------------------------------- procedure Register_Interface_DT_Entry (Prim : Entity_Id; Ancestor_Iface_Prim : Entity_Id := Empty) is E : Entity_Id; Prim_Typ : Entity_Id; Prim_Op : Entity_Id; Iface_Typ : Entity_Id; Iface_DT_Ptr : Entity_Id; Iface_Tag : Entity_Id; New_Thunk : Node_Id; Thunk_Id : Entity_Id; begin -- Nothing to do if the run-time does not give support to abstract -- interfaces. if not (RTE_Available (RE_Interface_Tag)) then return; end if; if No (Ancestor_Iface_Prim) then Prim_Typ := Scope (DTC_Entity (Alias (Prim))); -- Look for the abstract interface subprogram E := Abstract_Interface_Alias (Prim); while Present (E) and then Is_Abstract (E) and then not Is_Interface (Scope (DTC_Entity (E))) loop E := Alias (E); end loop; Iface_Typ := Scope (DTC_Entity (E)); -- Generate the code of the thunk only when this primitive -- operation is associated with a secondary dispatch table. if Is_Interface (Iface_Typ) then Iface_Tag := Find_Interface_Tag (T => Prim_Typ, Iface => Iface_Typ); if Etype (Iface_Tag) = RTE (RE_Interface_Tag) then Thunk_Id := Make_Defining_Identifier (Loc, Chars => New_Internal_Name ('T')); New_Thunk := Expand_Interface_Thunk (N => Prim, Thunk_Alias => Alias (Prim), Thunk_Id => Thunk_Id); Insert_After (N, New_Thunk); Iface_DT_Ptr := Find_Interface_ADT (T => Prim_Typ, Iface => Iface_Typ); Insert_After (New_Thunk, Fill_Secondary_DT_Entry (Sloc (Prim), Prim => Prim, Iface_DT_Ptr => Iface_DT_Ptr, Thunk_Id => Thunk_Id)); end if; end if; else Iface_Typ := Scope (DTC_Entity (Abstract_Interface_Alias (Ancestor_Iface_Prim))); Iface_Tag := Find_Interface_Tag (T => Scope (DTC_Entity (Alias (Ancestor_Iface_Prim))), Iface => Iface_Typ); -- Generate the thunk only if the associated tag is an interface -- tag. The case in which the associated tag is the primary tag -- occurs when a tagged type is a direct derivation of an -- interface. For example: -- type I is interface; -- ... -- type T is new I with ... if Etype (Iface_Tag) = RTE (RE_Interface_Tag) then Thunk_Id := Make_Defining_Identifier (Loc, Chars => New_Internal_Name ('T')); if Present (Alias (Prim)) then Prim_Op := Alias (Prim); else Prim_Op := Prim; end if; New_Thunk := Expand_Interface_Thunk (N => Ancestor_Iface_Prim, Thunk_Alias => Prim_Op, Thunk_Id => Thunk_Id); Insert_After (N, New_Thunk); Iface_DT_Ptr := Find_Interface_ADT (T => Scope (DTC_Entity (Prim_Op)), Iface => Iface_Typ); Insert_After (New_Thunk, Fill_Secondary_DT_Entry (Sloc (Prim), Prim => Ancestor_Iface_Prim, Iface_DT_Ptr => Iface_DT_Ptr, Thunk_Id => Thunk_Id)); end if; end if; end Register_Interface_DT_Entry; ---------------------------------- -- Register_Predefined_DT_Entry -- ---------------------------------- procedure Register_Predefined_DT_Entry (Prim : Entity_Id) is Iface_DT_Ptr : Elmt_Id; Iface_Tag : Entity_Id; Iface_Typ : Elmt_Id; New_Thunk : Entity_Id; Prim_Typ : Entity_Id; Thunk_Id : Entity_Id; begin Prim_Typ := Scope (DTC_Entity (Prim)); if No (Access_Disp_Table (Prim_Typ)) or else No (Abstract_Interfaces (Prim_Typ)) or else not RTE_Available (RE_Interface_Tag) then return; end if; -- Skip the first acces-to-dispatch-table pointer since it leads -- to the primary dispatch table. We are only concerned with the -- secondary dispatch table pointers. Note that the access-to- -- dispatch-table pointer corresponds to the first implemented -- interface retrieved below. Iface_DT_Ptr := Next_Elmt (First_Elmt (Access_Disp_Table (Prim_Typ))); Iface_Typ := First_Elmt (Abstract_Interfaces (Prim_Typ)); while Present (Iface_DT_Ptr) and then Present (Iface_Typ) loop Iface_Tag := Find_Interface_Tag (Prim_Typ, Node (Iface_Typ)); pragma Assert (Present (Iface_Tag)); if Etype (Iface_Tag) = RTE (RE_Interface_Tag) then Thunk_Id := Make_Defining_Identifier (Loc, New_Internal_Name ('T')); New_Thunk := Expand_Interface_Thunk (N => Prim, Thunk_Alias => Prim, Thunk_Id => Thunk_Id); Insert_After (N, New_Thunk); Insert_After (New_Thunk, Make_DT_Access_Action (Node (Iface_Typ), Action => Set_Predefined_Prim_Op_Address, Args => New_List ( Unchecked_Convert_To (RTE (RE_Tag), New_Reference_To (Node (Iface_DT_Ptr), Loc)), Make_Integer_Literal (Loc, DT_Position (Prim)), Make_Attribute_Reference (Loc, Prefix => New_Reference_To (Thunk_Id, Loc), Attribute_Name => Name_Address)))); end if; Next_Elmt (Iface_DT_Ptr); Next_Elmt (Iface_Typ); end loop; end Register_Predefined_DT_Entry; -- Start of processing for Freeze_Subprogram begin -- When a primitive is frozen, enter its name in the corresponding -- dispatch table. If the DTC_Entity field is not set this is an -- overridden primitive that can be ignored. We suppress the -- initialization of the dispatch table entry when Java_VM because -- the dispatching mechanism is handled internally by the JVM. if Is_Dispatching_Operation (E) and then not Is_Abstract (E) and then Present (DTC_Entity (E)) and then not Java_VM and then not Is_CPP_Class (Scope (DTC_Entity (E))) then Check_Overriding_Operation (E); -- Ada 95 case: Register the subprogram in the primary dispatch table if Ada_Version < Ada_05 then -- Do not register the subprogram in the dispatch table if we -- are compiling with the No_Dispatching_Calls restriction. if not Restriction_Active (No_Dispatching_Calls) then Insert_After (N, Fill_DT_Entry (Sloc (N), Prim => E)); end if; -- Ada 2005 case: Register the subprogram in the secondary dispatch -- tables associated with abstract interfaces. else declare Typ : constant Entity_Id := Scope (DTC_Entity (E)); begin -- There is no dispatch table associated with abstract -- interface types. Each type implementing interfaces will -- fill the associated secondary DT entries. if not Is_Interface (Typ) or else Present (Alias (E)) then -- Ada 2005 (AI-251): Check if this entry corresponds with -- a subprogram that covers an abstract interface type. if Present (Abstract_Interface_Alias (E)) then Register_Interface_DT_Entry (E); -- Common case: Primitive subprogram else -- Generate thunks for all the predefined operations if not Restriction_Active (No_Dispatching_Calls) then if Is_Predefined_Dispatching_Operation (E) then Register_Predefined_DT_Entry (E); end if; Insert_After (N, Fill_DT_Entry (Sloc (N), Prim => E)); end if; Check_Overriding_Inherited_Interfaces (E); end if; end if; end; end if; end if; -- Mark functions that return by reference. Note that it cannot be -- part of the normal semantic analysis of the spec since the -- underlying returned type may not be known yet (for private types). declare Typ : constant Entity_Id := Etype (E); Utyp : constant Entity_Id := Underlying_Type (Typ); begin if Is_Return_By_Reference_Type (Typ) then Set_Returns_By_Ref (E); elsif Present (Utyp) and then Controlled_Type (Utyp) then Set_Returns_By_Ref (E); end if; end; end Freeze_Subprogram; end Exp_Ch6;
with Ada.Text_IO, POSIX.Process_Identification, POSIX.Unsafe_Process_Primitives; procedure Fork is use Ada.Text_IO, POSIX.Process_Identification, POSIX.Unsafe_Process_Primitives; begin if Fork = Null_Process_ID then Put_Line ("This is the new process."); else Put_Line ("This is the original process."); end if; exception when others => Put_Line ("Something went wrong."); end Fork;
-- Shoot'n'loot -- Copyright (c) 2020 Fabien Chouteau with Game_Assets.Misc_Objects; with GESTE.Maths_Types; use GESTE.Maths_Types; package body Projectile is Empty_Tile : constant GESTE_Config.Tile_Index := Game_Assets.Misc_Objects.Item.Empty_Tile.Tile_Id; procedure Move_Tile (This : in out Instance) with Inline; --------------- -- Move_Tile -- --------------- procedure Move_Tile (This : in out Instance) is begin This.Sprite.Move ((Integer (This.Obj.Position.X) - GESTE_Config.Tile_Size / 2, Integer (This.Obj.Position.Y) - GESTE_Config.Tile_Size / 2)); end Move_Tile; ---------- -- Init -- ---------- procedure Init (This : in out Instance) is begin This.Is_Alive := False; end Init; ----------- -- Alive -- ----------- function Alive (This : Instance) return Boolean is (This.Is_Alive); ----------- -- Spawn -- ----------- procedure Spawn (This : in out Instance; Pos : GESTE.Maths_Types.Point; Time_To_Live : GESTE.Maths_Types.Value; Priority : GESTE.Layer_Priority) is begin This.Obj.Set_Mass (1.0); This.Obj.Set_Position (Pos); Move_Tile (This); This.Time_To_Live := Time_To_Live; This.Is_Alive := True; This.Sprite.Set_Tile (This.Sprite.Init_Frame); GESTE.Add (This.Sprite'Unchecked_Access, Priority); end Spawn; ------------ -- Remove -- ------------ procedure Remove (This : in out Instance) is begin This.Sprite.Set_Tile (Empty_Tile); This.Time_To_Live := 0.1; end Remove; ---------------- -- Set_Sprite -- ---------------- procedure Set_Sprite (This : in out Instance; Id : GESTE_Config.Tile_Index) is begin This.Sprite.Set_Tile (Id); end Set_Sprite; --------------- -- Posistion -- --------------- function Position (This : Instance) return GESTE.Pix_Point is ((Integer (This.Obj.Position.X), Integer (This.Obj.Position.Y))); --------------- -- Set_Speed -- --------------- procedure Set_Speed (This : in out Instance; S : GESTE.Maths_Types.Vect) is begin This.Obj.Set_Speed (S); end Set_Speed; ------------ -- Update -- ------------ procedure Update (This : in out Instance; Elapsed : GESTE.Maths_Types.Value) is begin if This.Alive then if This.Time_To_Live < 0.0 then This.Is_Alive := False; GESTE.Remove (This.Sprite'Unchecked_Access); else This.Obj.Step (Elapsed); Move_Tile (This); This.Time_To_Live := This.Time_To_Live - Elapsed; end if; end if; end Update; end Projectile;
with Ada.Text_IO; use Ada.Text_IO; with Ada.Exceptions; use Ada.Exceptions; procedure Bad_Lunch is -- Enumeration type type Lunch_Spot_t is (WS, Nine, Home); type Day_t is (Sun, Mon, Tue, Wed, Thu, Fri, Sat); -- Subtype Weekday_t is a constrained Day_t subtype Weekday_t is Day_t range Mon .. Fri; -- Declaring a fixed-size array Where_To_Eat : array(Weekday_t) of Lunch_Spot_t; begin -- Array is the same size as number of Day_t values Where_To_Eat := (Nine, WS, Nine, WS, Nine); -- Can loop over a fixed-size array, or over a type/subtype itself for Day in Day_t loop case Where_To_Eat (Day) is when Home => Put_Line("Eating at home."); when Nine => Put_Line("Eating on 9."); when WS => Put_Line("Eating at Wise Sons"); -- case statement must include all cases end case; end loop; exception when Error : Constraint_Error => Put_Line("It's the weekend, no lunch at Square."); Put_Line(Exception_Information(Error)); end Bad_Lunch;
-- C94008C.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 SELECT WITH TERMINATE ALTERNATIVE WORKS CORRECTLY WITH -- NESTED TASKS. -- THIS TEST CONTAINS RACE CONDITIONS AND USES A GENERIC INSTANCE THAT -- CONTAINS TASKS. -- JEAN-PIERRE ROSEN 24 FEBRUARY 1984 -- JRK 4/7/86 -- JBG 8/29/86 ELIMINATED SHARED VARIABLES; ADDED GENERIC UNIT -- PWN 11/30/94 REMOVED PRAGMA PRIORITY INSTANCES FOR ADA 9X. with Impdef; WITH REPORT; USE REPORT; WITH SYSTEM; USE SYSTEM; PROCEDURE C94008C IS -- GENERIC UNIT FOR DOING UPDATES OF SHARED VARIABLES GENERIC TYPE HOLDER_TYPE IS PRIVATE; TYPE VALUE_TYPE IS PRIVATE; INITIAL_VALUE : HOLDER_TYPE; WITH PROCEDURE SET (HOLDER : OUT HOLDER_TYPE; VALUE : IN HOLDER_TYPE) IS <>; WITH PROCEDURE UPDATE (HOLDER : IN OUT HOLDER_TYPE; VALUE : IN VALUE_TYPE) IS <>; PACKAGE SHARED IS PROCEDURE SET (VALUE : IN HOLDER_TYPE); PROCEDURE UPDATE (VALUE : IN VALUE_TYPE); FUNCTION GET RETURN HOLDER_TYPE; END SHARED; PACKAGE BODY SHARED IS TASK SHARE IS ENTRY SET (VALUE : IN HOLDER_TYPE); ENTRY UPDATE (VALUE : IN VALUE_TYPE); ENTRY READ (VALUE : OUT HOLDER_TYPE); END SHARE; TASK BODY SHARE IS VARIABLE : HOLDER_TYPE; BEGIN LOOP SELECT ACCEPT SET (VALUE : IN HOLDER_TYPE) DO SHARED.SET (VARIABLE, VALUE); END SET; OR ACCEPT UPDATE (VALUE : IN VALUE_TYPE) DO SHARED.UPDATE (VARIABLE, VALUE); END UPDATE; OR ACCEPT READ (VALUE : OUT HOLDER_TYPE) DO VALUE := VARIABLE; END READ; OR TERMINATE; END SELECT; END LOOP; END SHARE; PROCEDURE SET (VALUE : IN HOLDER_TYPE) IS BEGIN SHARE.SET (VALUE); END SET; PROCEDURE UPDATE (VALUE : IN VALUE_TYPE) IS BEGIN SHARE.UPDATE (VALUE); END UPDATE; FUNCTION GET RETURN HOLDER_TYPE IS VALUE : HOLDER_TYPE; BEGIN SHARE.READ (VALUE); RETURN VALUE; END GET; BEGIN SHARE.SET (INITIAL_VALUE); -- SET INITIAL VALUE END SHARED; PACKAGE EVENTS IS TYPE EVENT_TYPE IS RECORD TRACE : STRING (1..4) := "...."; LENGTH : NATURAL := 0; END RECORD; PROCEDURE UPDATE (VAR : IN OUT EVENT_TYPE; VAL : CHARACTER); PROCEDURE SET (VAR : OUT EVENT_TYPE; VAL : EVENT_TYPE); END EVENTS; PACKAGE COUNTER IS PROCEDURE UPDATE (VAR : IN OUT INTEGER; VAL : INTEGER); PROCEDURE SET (VAR : OUT INTEGER; VAL : INTEGER); END COUNTER; PACKAGE BODY COUNTER IS PROCEDURE UPDATE (VAR : IN OUT INTEGER; VAL : INTEGER) IS BEGIN VAR := VAR + VAL; END UPDATE; PROCEDURE SET (VAR : OUT INTEGER; VAL : INTEGER) IS BEGIN VAR := VAL; END SET; END COUNTER; PACKAGE BODY EVENTS IS PROCEDURE UPDATE (VAR : IN OUT EVENT_TYPE; VAL : CHARACTER) IS BEGIN VAR.LENGTH := VAR.LENGTH + 1; VAR.TRACE(VAR.LENGTH) := VAL; END UPDATE; PROCEDURE SET (VAR : OUT EVENT_TYPE; VAL : EVENT_TYPE) IS BEGIN VAR := VAL; END SET; END EVENTS; USE EVENTS, COUNTER; PACKAGE TRACE IS NEW SHARED (EVENT_TYPE, CHARACTER, ("....", 0)); PACKAGE TERMINATE_COUNT IS NEW SHARED (INTEGER, INTEGER, 0); FUNCTION ENTER_TERMINATE RETURN BOOLEAN IS BEGIN TERMINATE_COUNT.UPDATE (1); RETURN TRUE; END ENTER_TERMINATE; BEGIN -- C94008C TEST ("C94008C", "CHECK CORRECT OPERATION OF SELECT WITH " & "TERMINATE ALTERNATIVE"); DECLARE PROCEDURE EVENT (VAR : CHARACTER) RENAMES TRACE.UPDATE; TASK T1 IS ENTRY E1; END T1; TASK BODY T1 IS TASK T2 IS ENTRY E2; END T2; TASK BODY T2 IS TASK T3 IS ENTRY E3; END T3; TASK BODY T3 IS BEGIN SELECT ACCEPT E3; OR WHEN ENTER_TERMINATE => TERMINATE; END SELECT; EVENT ('D'); END T3; BEGIN -- T2 SELECT ACCEPT E2; OR WHEN ENTER_TERMINATE => TERMINATE; END SELECT; DELAY 10.0 * Impdef.One_Second; IF TERMINATE_COUNT.GET /= 1 THEN DELAY 20.0 * Impdef.One_Long_Second; END IF; IF TERMINATE_COUNT.GET /= 1 THEN FAILED ("30 SECOND DELAY NOT ENOUGH - 1 "); END IF; EVENT ('C'); T1.E1; T3.E3; END T2; BEGIN -- T1; SELECT ACCEPT E1; OR WHEN ENTER_TERMINATE => TERMINATE; END SELECT; EVENT ('B'); TERMINATE_COUNT.SET (0); T2.E2; SELECT ACCEPT E1; OR WHEN ENTER_TERMINATE => TERMINATE; END SELECT; SELECT ACCEPT E1; OR TERMINATE; -- ONLY THIS ONE EVER CHOSEN. END SELECT; FAILED ("TERMINATE NOT SELECTED IN T1"); END T1; BEGIN DELAY 10.0 * Impdef.One_Second; -- WAIT FOR T1, T2, AND T3 TO GET TO SELECT STMTS. IF TERMINATE_COUNT.GET /= 3 THEN DELAY 20.0 * Impdef.One_Long_Second; END IF; IF TERMINATE_COUNT.GET /= 3 THEN FAILED ("30 SECOND DELAY NOT ENOUGH - 2"); END IF; EVENT ('A'); T1.E1; EXCEPTION WHEN OTHERS => FAILED ("EXCEPTION IN MAIN BLOCK"); END; IF TRACE.GET.TRACE /= "ABCD" THEN FAILED ("INCORRECT ORDER OF EVENTS: " & TRACE.GET.TRACE); END IF; RESULT; END C94008C;
-- C37009A.ADA -- Grant of Unlimited Rights -- -- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687, -- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained -- unlimited rights in the software and documentation contained herein. -- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making -- this public release, the Government intends to confer upon all -- recipients unlimited rights equal to those held by the Government. -- These rights include rights to use, duplicate, release or disclose the -- released technical data and computer software in whole or in part, in -- any manner and for any purpose whatsoever, and to have or permit others -- to do so. -- -- DISCLAIMER -- -- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR -- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED -- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE -- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE -- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A -- PARTICULAR PURPOSE OF SAID MATERIAL. --* -- OBJECTIVE: -- CHECK THAT AN UNCONSTRAINED RECORD TYPE CAN BE USED TO DECLARE A -- RECORD COMPONENT THAT CAN BE INITIALIZED WITH AN APPROPRIATE -- EXPLICIT OR DEFAULT VALUE. -- HISTORY: -- DHH 02/01/88 CREATED ORIGINAL TEST. WITH REPORT; USE REPORT; PROCEDURE C37009A IS TYPE FLOAT IS DIGITS 5; TYPE COLOR IS (RED, YELLOW, BLUE); TYPE COMPONENT IS RECORD I : INTEGER := 1; X : FLOAT := 3.5; BOL : BOOLEAN := FALSE; FIRST : COLOR := RED; END RECORD; TYPE COMP_DIS(A : INTEGER := 1) IS RECORD I : INTEGER := 1; X : FLOAT := 3.5; BOL : BOOLEAN := FALSE; FIRST : COLOR := RED; END RECORD; SUBTYPE SMAL_INTEGER IS INTEGER RANGE 1 .. 10; TYPE LIST IS ARRAY(INTEGER RANGE <>) OF FLOAT; TYPE DISCRIM(P : SMAL_INTEGER := 2) IS RECORD A : LIST(1 .. P) := (1 .. P => 1.25); END RECORD; TYPE REC_T IS -- EXPLICIT INIT. RECORD T : COMPONENT := (5, 6.0, TRUE, YELLOW); U : DISCRIM(3) := (3, (1 .. 3 => 2.25)); L : COMP_DIS(5) := (A => 5, I => 5, X => 6.0, BOL =>TRUE, FIRST => YELLOW); END RECORD; TYPE REC_DEF_T IS -- DEFAULT INIT. RECORD T : COMPONENT; U : DISCRIM; L : COMP_DIS; END RECORD; REC : REC_T; REC_DEF : REC_DEF_T; FUNCTION IDENT_FLT(X : FLOAT) RETURN FLOAT IS BEGIN IF EQUAL(3,3) THEN RETURN X; ELSE RETURN 0.0; END IF; END IDENT_FLT; FUNCTION IDENT_ENUM(X : COLOR) RETURN COLOR IS BEGIN IF EQUAL(3,3) THEN RETURN X; ELSE RETURN BLUE; END IF; END IDENT_ENUM; BEGIN TEST("C37009A", "CHECK THAT AN UNCONSTRAINED RECORD TYPE CAN " & "BE USED TO DECLARE A RECORD COMPONENT THAT " & "CAN BE INITIALIZED WITH AN APPROPRIATE " & "EXPLICIT OR DEFAULT VALUE"); IF REC_DEF.T.I /= IDENT_INT(1) THEN FAILED("INCORRECT DEFAULT INITIALIZATION OF INTEGER"); END IF; IF IDENT_BOOL(REC_DEF.T.BOL) THEN FAILED("INCORRECT DEFAULT INITIALIZATION OF BOOLEAN"); END IF; IF REC_DEF.T.X /= IDENT_FLT(3.5) THEN FAILED("INCORRECT DEFAULT INITIALIZATION OF REAL"); END IF; IF REC_DEF.T.FIRST /= IDENT_ENUM(RED) THEN FAILED("INCORRECT DEFAULT INITIALIZATION OF ENUMERATION"); END IF; FOR I IN 1 .. 2 LOOP IF REC_DEF.U.A(I) /= IDENT_FLT(1.25) THEN FAILED("INCORRECT DEFAULT INITIALIZATION OF ARRAY " & "POSITION " & INTEGER'IMAGE(I)); END IF; END LOOP; IF REC_DEF.L.A /= IDENT_INT(1) THEN FAILED("INCORRECT DEFAULT INITIALIZATION OF DISCRIMINANT " & "- L"); END IF; IF REC_DEF.L.I /= IDENT_INT(1) THEN FAILED("INCORRECT DEFAULT INITIALIZATION OF INTEGER - L"); END IF; IF IDENT_BOOL(REC_DEF.L.BOL) THEN FAILED("INCORRECT DEFAULT INITIALIZATION OF BOOLEAN - L"); END IF; IF REC_DEF.L.X /= IDENT_FLT(3.5) THEN FAILED("INCORRECT DEFAULT INITIALIZATION OF REAL - L"); END IF; IF REC_DEF.L.FIRST /= IDENT_ENUM(RED) THEN FAILED("INCORRECT DEFAULT INITIALIZATION OF ENUMERATION - L"); END IF; -------------------------------------------------------------------- IF REC.T.I /= IDENT_INT(5) THEN FAILED("INCORRECT EXPLICIT INITIALIZATION OF INTEGER"); END IF; IF NOT IDENT_BOOL(REC.T.BOL) THEN FAILED("INCORRECT EXPLICIT INITIALIZATION OF BOOLEAN"); END IF; IF REC.T.X /= IDENT_FLT(6.0) THEN FAILED("INCORRECT EXPLICIT INITIALIZATION OF REAL"); END IF; IF REC.T.FIRST /= YELLOW THEN FAILED("INCORRECT EXPLICIT INITIALIZATION OF ENUMERATION"); END IF; FOR I IN 1 .. 3 LOOP IF REC.U.A(I) /= IDENT_FLT(2.25) THEN FAILED("INCORRECT EXPLICIT INITIALIZATION OF ARRAY " & "POSITION " & INTEGER'IMAGE(I)); END IF; END LOOP; IF REC.L.A /= IDENT_INT(5) THEN FAILED("INCORRECT EXPLICIT INITIALIZATION OF DISCRIMINANT " & "- L"); END IF; IF REC.L.I /= IDENT_INT(5) THEN FAILED("INCORRECT EXPLICIT INITIALIZATION OF INTEGER - L"); END IF; IF NOT IDENT_BOOL(REC.L.BOL) THEN FAILED("INCORRECT EXPLICIT INITIALIZATION OF BOOLEAN - L"); END IF; IF REC.L.X /= IDENT_FLT(6.0) THEN FAILED("INCORRECT EXPLICIT INITIALIZATION OF REAL - L"); END IF; IF REC.L.FIRST /= IDENT_ENUM(YELLOW) THEN FAILED("INCORRECT EXPLICIT INITIALIZATION OF ENUMERATION " & "- L"); END IF; RESULT; END C37009A;
-- Copyright (c) 1990 Regents of the University of California. -- All rights reserved. -- -- This software was developed by John Self of the Arcadia project -- at the University of California, Irvine. -- -- Redistribution and use in source and binary forms are permitted -- provided that the above copyright notice and this paragraph are -- duplicated in all such forms and that any documentation, -- advertising materials, and other materials related to such -- distribution and use acknowledge that the software was developed -- by the University of California, Irvine. The name of the -- University may not be used to endorse or promote products derived -- from this software without specific prior written permission. -- THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR -- IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED -- WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. -- TITLE miscellaneous aflex routines -- AUTHOR: John Self (UCI) -- DESCRIPTION -- NOTES contains functions used in various places throughout aflex. -- $Header: /co/ua/self/arcadia/aflex/ada/src/RCS/miscS.a,v 1.9 90/01/12 15:20:19 self Exp Locker: self $ with Ada.Strings.Unbounded; with Ada.Strings.Wide_Wide_Unbounded; with Ada.Wide_Wide_Text_IO; with MISC_DEFS; with Unicode; package Misc is use Ada.Strings.Unbounded; use MISC_DEFS; procedure ACTION_OUT; procedure BUBBLE(V : in INT_PTR; N : in INTEGER); function CLOWER(C : in INTEGER) return INTEGER; procedure CSHELL (V : in out Unicode_Character_Array; N : Integer); -- cshell - shell sort a character array in increasing order -- -- description -- does a shell sort of the first n elements of array v. -- -- passed -- v - array to be sorted -- n - number of elements of v to be sorted procedure DATAEND; procedure DATAFLUSH (File : Ada.Wide_Wide_Text_IO.File_Type); procedure DATAFLUSH; function Aflex_Get_Time return Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; -- aflex_gettime - return current time procedure Aflex_Error (Msg : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); procedure Aflex_Error (Msg : Wide_Wide_String); -- aflexerror - report an error message and terminate -- overloaded function, one for vstring, one for string. -- function ALL_UPPER(STR : in VSTRING) return BOOLEAN; -- function ALL_LOWER(STR : in VSTRING) return BOOLEAN; procedure Aflex_Fatal (Msg : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); procedure Aflex_Fatal (Msg : Wide_Wide_String); -- aflexfatal - report a fatal error message and terminate -- overloaded function, one for vstring, one for string. procedure LINE_DIRECTIVE_OUT; procedure LINE_DIRECTIVE_OUT (OUTPUT_FILE_NAME : Ada.Wide_Wide_Text_IO.File_Type); procedure MK2DATA (File : Ada.Wide_Wide_Text_IO.File_Type; Value : Integer); procedure MKDATA(VALUE : in INTEGER); function MYCTOI (NUM_ARRAY : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) return INTEGER; function MYESC (ARR : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) return Unicode.Unicode_Character; -- myesc - return character corresponding to escape sequence function OTOI (STR : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) return Wide_Wide_Character; function Readable_Form (C : Wide_Wide_Character) return Unbounded_String; procedure SYNERR (STR : Wide_Wide_String); procedure TRANSITION_STRUCT_OUT(ELEMENT_V, ELEMENT_N : in INTEGER); function SET_YY_TRAILING_HEAD_MASK(SRC : in INTEGER) return INTEGER; function CHECK_YY_TRAILING_HEAD_MASK(SRC : in INTEGER) return INTEGER; function SET_YY_TRAILING_MASK(SRC : in INTEGER) return INTEGER; function CHECK_YY_TRAILING_MASK(SRC : in INTEGER) return INTEGER; function ISLOWER(C : in CHARACTER) return BOOLEAN; function ISUPPER(C : in CHARACTER) return BOOLEAN; function ISDIGIT(C : in CHARACTER) return BOOLEAN; function TOLOWER(C : in INTEGER) return INTEGER; function Basename return Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; -- Basename - find the basename of a file end Misc;
------------------------------------------------------------------------------ -- -- -- P G A D A . D A T A B A S E -- -- -- -- B o d y -- -- -- -- Copyright (c) Samuel Tardieu 2000 -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of Samuel Tardieu nor the names of its contributors -- -- may be used to endorse or promote products derived from this -- -- software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY SAMUEL TARDIEU AND CONTRIBUTORS ``AS -- -- IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -- -- FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SAMUEL -- -- TARDIEU OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -- -- INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -- -- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -- -- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -- -- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -- -- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -- -- OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, -- -- EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with Ada.Unchecked_Deallocation; with Interfaces.C.Strings; with Interfaces.C; package body PGAda.Database is package ICS renames Interfaces.C.Strings; package IC renames Interfaces.C; use type ICS.chars_ptr; use type IC.int; use type PGAda.Thin.PG_Conn_Access_t; use type PGAda.Thin.PG_Result_Access_t; Exec_Status_Match : constant array (Thin.Exec_Status_t) of Exec_Status_t := (PGAda.Thin.PGRES_EMPTY_QUERY => Empty_Query, PGAda.Thin.PGRES_COMMAND_OK => Command_OK, PGAda.Thin.PGRES_TUPLES_OK => Tuples_OK, PGAda.Thin.PGRES_COPY_OUT => Copy_Out, PGAda.Thin.PGRES_COPY_IN => Copy_In, PGAda.Thin.PGRES_BAD_RESPONSE => Bad_Response, PGAda.Thin.PGRES_NONFATAL_ERROR => Non_Fatal_Error, PGAda.Thin.PGRES_FATAL_ERROR => Fatal_Error); ----------------------- -- Local subprograms -- ----------------------- function C_String_Or_Null (S : String) return ICS.chars_ptr; procedure Free (S : in out ICS.chars_ptr); -- Create a C string or return Null_Ptr if the string is empty, and -- free it if needed. ------------ -- Adjust -- ------------ procedure Adjust (Result : in out Result_t) is begin Result.Ref_Count.all := Result.Ref_Count.all + 1; end Adjust; ---------------------- -- C_String_Or_Null -- ---------------------- function C_String_Or_Null (S : String) return ICS.chars_ptr is begin if S = "" then return ICS.Null_Ptr; else return ICS.New_String (S); end if; end C_String_Or_Null; ----------- -- Clear -- ----------- procedure Clear (Result : in out Result_t) is begin PGAda.Thin.PQ_Clear (Result.Actual); Result.Actual := null; end Clear; -------------------- -- Command_Status -- -------------------- function Command_Status (Result : Result_t) return String is begin return ICS.Value (PGAda.Thin.PQ_Cmd_Status (Result.Actual)); end Command_Status; -------------------- -- Command_Tuples -- -------------------- function Command_Tuples (Result : Result_t) return String is begin return ICS.Value (PGAda.Thin.PQ_Cmd_Tuples (Result.Actual)); end Command_Tuples; -------- -- DB -- -------- function DB (Connection : Connection_t) return String is begin return ICS.Value (PGAda.Thin.PQ_Db (Connection.Actual)); end DB; ------------------- -- Error_Message -- ------------------- function Error_Message (Connection : Connection_t) return String is begin return ICS.Value (PGAda.Thin.PQ_Error_Message (Connection.Actual)); end Error_Message; ------------------- -- Error_Message -- ------------------- function Error_Message (Result : Result_t) return String is begin return Result_Error_Field (Result => Result, Field => PGAda.Thin.PG_DIAG_MESSAGE_PRIMARY); end Error_Message; ---------- -- Exec -- ---------- procedure Exec (Connection : in Connection_t'Class; Query : in String; Result : out Result_t; Status : out Exec_Status_t) is C_Query : ICS.chars_ptr := ICS.New_String (Query); begin Result.Actual := PGAda.Thin.PQ_Exec (Connection.Actual, C_Query); ICS.Free (C_Query); Status := Result_Status (Result); end Exec; ---------- -- Exec -- ---------- procedure Exec (Connection : in Connection_t'Class; Query : in String; Result : out Result_t) is C_Query : ICS.chars_ptr := ICS.New_String (Query); begin Result.Actual := PGAda.Thin.PQ_Exec (Connection.Actual, C_Query); ICS.Free (C_Query); end Exec; ---------- -- Exec -- ---------- function Exec (Connection : Connection_t'Class; Query : String) return Result_t is Result : Result_t; begin Exec (Connection, Query, Result); return Result; end Exec; ---------- -- Exec -- ---------- procedure Exec (Connection : in Connection_t'Class; Query : in String) is Result : Result_t; begin -- Result value ignored by call pragma Warnings (off); Exec (Connection, Query, Result); pragma Warnings (on); end Exec; ---------------- -- Field_Name -- ---------------- function Field_Name (Result : Result_t; Field_Index : Positive) return String is begin return ICS.Value (PGAda.Thin.PQ_F_Name (Result.Actual, IC.int (Field_Index) - 1)); end Field_Name; -------------- -- Finalize -- -------------- procedure Finalize (Connection : in out Connection_t) is begin if Connection.Actual /= null then Finish (Connection); end if; end Finalize; -------------- -- Finalize -- -------------- procedure Finalize (Result : in out Result_t) is procedure Free is new Ada.Unchecked_Deallocation (Natural, Natural_Access_t); begin Result.Ref_Count.all := Result.Ref_Count.all - 1; if Result.Ref_Count.all = 0 and then Result.Actual /= null then Free (Result.Ref_Count); Clear (Result); end if; end Finalize; ------------ -- Finish -- ------------ procedure Finish (Connection : in out Connection_t) is begin PGAda.Thin.PQ_Finish (Connection.Actual); Connection.Actual := null; end Finish; ---------- -- Free -- ---------- procedure Free (S : in out ICS.chars_ptr) is begin if S /= ICS.Null_Ptr then ICS.Free (S); end if; end Free; ---------------- -- Get_Length -- ---------------- function Get_Length (Result : Result_t; Tuple_Index : Positive; Field_Index : Positive) return Natural is begin return Natural (PGAda.Thin.PQ_Get_Length (Result.Actual, IC.int (Tuple_Index) - 1, IC.int (Field_Index) - 1)); end Get_Length; --------------- -- Get_Value -- --------------- function Get_Value (Result : Result_t; Tuple_Index : Positive; Field_Index : Positive) return String is begin return ICS.Value (PGAda.Thin.PQ_Get_Value (Result.Actual, IC.int (Tuple_Index) - 1, IC.int (Field_Index) - 1)); end Get_Value; --------------- -- Get_Value -- --------------- function Get_Value (Result : Result_t; Tuple_Index : Positive; Field_Name : String) return String is C_Name : ICS.chars_ptr := ICS.New_String (Field_Name); Ret : constant String := Get_Value (Result, Tuple_Index, 1 + Natural (PGAda.Thin.PQ_F_Number (Result.Actual, C_Name))); begin Free (C_Name); return Ret; end Get_Value; --------------- -- Get_Value -- --------------- function Get_Value (Result : Result_t; Tuple_Index : Positive; Field_Index : Positive) return Integer is begin return Integer'Value (Get_Value (Result, Tuple_Index, Field_Index)); end Get_Value; --------------- -- Get_Value -- --------------- function Get_Value (Result : Result_t; Tuple_Index : Positive; Field_Name : String) return Integer is begin return Integer'Value (Get_Value (Result, Tuple_Index, Field_Name)); end Get_Value; --------------- -- Get_Value -- --------------- function Get_Value (Result : Result_t; Tuple_Index : Positive; Field_Index : Positive) return Long_Integer is begin return Long_Integer'Value (Get_Value (Result, Tuple_Index, Field_Index)); end Get_Value; --------------- -- Get_Value -- --------------- function Get_Value (Result : Result_t; Tuple_Index : Positive; Field_Name : String) return Long_Integer is begin return Long_Integer'Value (Get_Value (Result, Tuple_Index, Field_Name)); end Get_Value; --------------- -- Get_Value -- --------------- function Get_Value (Result : Result_t; Tuple_Index : Positive; Field_Index : Positive) return Long_Long_Integer is begin return Long_Long_Integer'Value (Get_Value (Result, Tuple_Index, Field_Index)); end Get_Value; --------------- -- Get_Value -- --------------- function Get_Value (Result : Result_t; Tuple_Index : Positive; Field_Name : String) return Long_Long_Integer is begin return Long_Long_Integer'Value (Get_Value (Result, Tuple_Index, Field_Name)); end Get_Value; ---------- -- Host -- ---------- function Host (Connection : Connection_t) return String is begin return ICS.Value (PGAda.Thin.PQ_Host (Connection.Actual)); end Host; ------------- -- Is_Null -- ------------- function Is_Null (Result : Result_t; Tuple_Index : Positive; Field_Index : Positive) return Boolean is begin return 1 = PGAda.Thin.PQ_Get_Is_Null (Result.Actual, IC.int (Tuple_Index) - 1, IC.int (Field_Index) - 1); end Is_Null; ---------------- -- Nbr_Fields -- ---------------- function Nbr_Fields (Result : Result_t) return Natural is begin return Natural (PGAda.Thin.PQ_N_Fields (Result.Actual)); end Nbr_Fields; ---------------- -- Nbr_Tuples -- ---------------- function Nbr_Tuples (Result : Result_t) return Natural is begin return Natural (PGAda.Thin.PQ_N_Tuples (Result.Actual)); end Nbr_Tuples; ---------------- -- OID_Status -- ---------------- function OID_Status (Result : Result_t) return String is begin return ICS.Value (PGAda.Thin.PQ_Oid_Status (Result.Actual)); end OID_Status; ------------- -- Options -- ------------- function Options (Connection : Connection_t) return String is begin return ICS.Value (PGAda.Thin.PQ_Options (Connection.Actual)); end Options; ---------- -- Port -- ---------- function Port (Connection : Connection_t) return Positive is begin return Positive'Value (ICS.Value (PGAda.Thin.PQ_Port (Connection.Actual))); end Port; ----------- -- Reset -- ----------- procedure Reset (Connection : in Connection_t) is begin PGAda.Thin.PQ_Reset (Connection.Actual); end Reset; ------------------- -- Result_Status -- ------------------- function Result_Status (Result : Result_t) return Exec_Status_t is begin return Exec_Status_Match (PGAda.Thin.PQ_Result_Status (Result.Actual)); end Result_Status; ------------------------ -- Result_Error_Field -- ------------------------ function Result_Error_Field (Result : Result_t; Field : Error_Field) return String is C_Res : constant ICS.chars_ptr := PGAda.Thin.PQ_Result_Error_Field (Result.Actual, Field); begin if C_Res = ICS.Null_Ptr then return ""; else return ICS.Value (C_Res); end if; end Result_Error_Field; ---------------- -- Error_Code -- ---------------- function Error_Code (Result : Result_t) return PGAda.Errors.Error_Value_t is begin return PGAda.Errors.Error_Value (Result_Error_Field (Result, PGAda.Thin.PG_DIAG_SQLSTATE)); end Error_Code; ------------------ -- Set_DB_Login -- ------------------ procedure Set_DB_Login (Connection : in out Connection_t; Host : in String := ""; Port : in Natural := 0; Options : in String := ""; TTY : in String := ""; DB_Name : in String := ""; Login : in String := ""; Password : in String := "") is C_Host : ICS.chars_ptr := C_String_Or_Null (Host); C_Port : ICS.chars_ptr; C_Options : ICS.chars_ptr := C_String_Or_Null (Options); C_TTY : ICS.chars_ptr := C_String_Or_Null (TTY); C_DB_Name : ICS.chars_ptr := C_String_Or_Null (DB_Name); C_Login : ICS.chars_ptr := C_String_Or_Null (Login); C_Password : ICS.chars_ptr := C_String_Or_Null (Password); begin if Port = 0 then C_Port := ICS.Null_Ptr; else C_Port := ICS.New_String (Positive'Image (Port)); end if; Connection.Actual := PGAda.Thin.PQ_Set_Db_Login (C_Host, C_Port, C_Options, C_TTY, C_DB_Name, C_Login, C_Password); Free (C_Host); Free (C_Port); Free (C_Options); Free (C_TTY); Free (C_DB_Name); Free (C_Login); Free (C_Password); if Connection.Actual = null then raise PG_Error; end if; end Set_DB_Login; ------------ -- Status -- ------------ function Status (Connection : Connection_t) return Connection_Status_t is begin case PGAda.Thin.PQ_Status (Connection.Actual) is when PGAda.Thin.CONNECTION_OK => return Connection_OK; when PGAda.Thin.CONNECTION_BAD => return Connection_Bad; end case; end Status; end PGAda.Database;
with Ahven, float_Math.Algebra.linear.d2; with Ada.Text_IO; use Ada.Text_IO; package body math_Tests.linear_Algebra_2d is use Ahven, float_Math; function almost_Equal (Left, Right : in Real) return Boolean is Tolerance : constant := 0.000_000_1; begin return abs (Left - Right) <= Tolerance; end almost_Equal; procedure translation_Matrix_Test is use float_Math, float_Math.Algebra.linear.d2; From : Vector_2 := (0.0, 0.0); To : Vector_2; begin To := From * to_translation_Transform ((1.0, 0.0)); assert (To (1) = 1.0, Image (To) & " translation () failed !"); assert (To (2) = 0.0, Image (To) & " translation () failed !"); To := From * to_translation_Transform ((0.0, 1.0)); assert (To (1) = 0.0, Image (To) & " translation () failed !"); assert (To (2) = 1.0, Image (To) & " translation () failed !"); To := From * to_translation_Transform ((-1.0, 0.0)); assert (To (1) = -1.0, Image (To) & " translation () failed !"); assert (To (2) = 0.0, Image (To) & " translation () failed !"); To := From * to_translation_Transform ((0.0, -1.0)); assert (To (1) = 0.0, Image (To) & " translation () failed !"); assert (To (2) = -1.0, Image (To) & " translation () failed !"); To := From * to_translation_Transform ((1.0, 1.0)); assert (To (1) = 1.0, Image (To) & " translation () failed !"); assert (To (2) = 1.0, Image (To) & " translation () failed !"); To := From * to_translation_Transform ((-1.0, -1.0)); assert (To (1) = -1.0, Image (To) & " translation () failed !"); assert (To (2) = -1.0, Image (To) & " translation () failed !"); end translation_Matrix_Test; procedure rotation_Matrix_Test is use float_Math, float_Math.Algebra.linear.d2; From : Vector_2 := (1.0, 0.0); To : Vector_2; begin To := From * to_rotation_Matrix (to_Radians (90.0)); assert (almost_Equal (To (1), 0.0), Image (To, 16) & " rotation (90a) failed !"); assert (almost_Equal (To (2), 1.0), Image (To, 16) & " rotation (90b) failed !"); To := From * to_rotation_Matrix (to_Radians (-90.0)); assert (almost_Equal (To (1), 0.0), Image (To, 16) & " rotation (-90a) failed !"); assert (almost_Equal (To (2), -1.0), Image (To, 16) & " rotation (-90b) failed !"); To := From * to_rotation_Matrix (to_Radians (180.0)); assert (almost_Equal (To (1), -1.0), Image (To, 16) & " rotation (180a) failed !"); assert (almost_Equal (To (2), 0.0), Image (To, 16) & " rotation (180b) failed !"); To := From * to_rotation_Matrix (to_Radians (-180.0)); assert (almost_Equal (To (1), -1.0), Image (To, 16) & " rotation (-180a) failed !"); assert (almost_Equal (To (2), 0.0), Image (To, 16) & " rotation (-180b) failed !"); To := From * to_rotation_Matrix (to_Radians (270.0)); assert (almost_Equal (To (1), 0.0), Image (To, 16) & " rotation (270a) failed !"); assert (almost_Equal (To (2), -1.0), Image (To, 16) & " rotation (270b) failed !"); To := From * to_rotation_Matrix (to_Radians (-270.0)); assert (almost_Equal (To (1), 0.0), Image (To, 16) & " rotation (-270) failed !"); assert (almost_Equal (To (2), 1.0), Image (To, 16) & " rotation (-270) failed !"); end rotation_Matrix_Test; procedure transform_Test is use float_Math, float_Math.Algebra.linear.d2; From : Vector_2 := (1.0, 0.0); To : Vector_2; Transform : Transform_2d := to_Transform_2d (rotation => to_Radians (90.0), translation => (0.0, 0.0)); begin To := From * Transform; assert (almost_Equal (To (1), 0.0), Image (To, 16) & " transform (a) failed !"); assert (almost_Equal (To (2), 1.0), Image (To, 16) & " transform (b) failed !"); Transform.Translation := (1.0, 0.0); To := From * Transform; assert (almost_Equal (To (1), 1.0), Image (To, 16) & " transform (c) failed !"); assert (almost_Equal (To (2), 1.0), Image (To, 16) & " transform (d) failed !"); end transform_Test; procedure Initialize (T : in out Test) is begin T.set_Name ("Linear Algebra (2D) Tests"); Framework.add_test_Routine (T, translation_Matrix_Test'Access, "translation_Matrix_Test"); Framework.add_test_Routine (T, rotation_Matrix_Test'Access, "rotation_Matrix_Test"); Framework.add_test_Routine (T, transform_Test'Access, "transform_Test"); end Initialize; end math_Tests.linear_Algebra_2d;
pragma License (Unrestricted); -- implementation unit required by compiler with System.Long_Long_Integer_Types; with System.Unsigned_Types; package System.Img_Uns is pragma Pure; -- required for Modular'Image by compiler (s-imguns.ads) procedure Image_Unsigned ( V : Unsigned_Types.Unsigned; S : in out String; P : out Natural); -- helper procedure Image ( V : Long_Long_Integer_Types.Word_Unsigned; S : in out String; P : out Natural); end System.Img_Uns;
----------------------------------------------------------------------- -- servlet-filters-cache_control -- HTTP response Cache-Control settings -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Servlet.Requests; with Servlet.Responses; with Servlet.Core; -- The <b>Servlet.Filters.Cache_Control</b> package implements a servlet filter to add -- cache control headers in a response. -- package Servlet.Filters.Cache_Control is -- Filter configuration parameter, when not empty, add a Vary header in the response. VARY_HEADER_PARAM : constant String := "header.vary"; -- Filter configuration parameter, defines the expiration date in seconds relative -- to the current date. When 0, disable browser caching. CACHE_CONTROL_PARAM : constant String := "header.cache-control"; type Cache_Control_Filter is new Servlet.Filters.Filter with record Vary : Ada.Strings.Unbounded.Unbounded_String; Cache_Control_Header : Ada.Strings.Unbounded.Unbounded_String; end record; -- The Do_Filter method of the Filter is called by the container each time -- a request/response pair is passed through the chain due to a client request -- for a resource at the end of the chain. The <b>Cache_Control</b> filter adds -- a <tt>Cache-Control</tt>, <tt>Expires</tt>, <tt>Pragma</tt> and optionally a -- <tt>Vary</tt> header in the HTTP response. overriding procedure Do_Filter (F : in Cache_Control_Filter; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class; Chain : in out Servlet.Core.Filter_Chain); -- Called by the servlet container to indicate to a filter that the filter -- instance is being placed into service. procedure Initialize (Server : in out Cache_Control_Filter; Config : in Servlet.Core.Filter_Config); end Servlet.Filters.Cache_Control;
with screen_io, maze; use screen_io , maze; with integer_text_io; use integer_text_io ; procedure hilbert is here: position ; this_way: direction := up; last_d: direction := up; order: integer ; procedure draw_line(l: integer) is c: character ; steps: integer := l ; begin if this_way = right or this_way = left then c := '_' ; steps := 2* l ; -- looks better this way. else c := '|' ; end if ; if steps = 0 then steps := 1 ; end if ; if this_way = down or last_d = down then for i in 1..steps loop here := next_pos(here, this_way) ; putc(c, here.row, here.col) ; end loop ; else for i in 1..steps loop putc(c, here.row, here.col) ; here := next_pos(here, this_way) ; end loop ; end if ; last_d := this_way ; end draw_line ; procedure turn(left_first: boolean) is begin if left_first then this_way := left_of(this_way) ; else this_way := right_of(this_way) ; end if ; end turn ; procedure draw_hilbert(size, level: integer; left_first: boolean) is begin if level = 0 then return ; else turn(left_first) ; draw_hilbert(size, level - 1, not left_first) ; draw_line(size) ; turn(not left_first) ; draw_hilbert(size, level - 1, left_first) ; draw_line(size) ; draw_hilbert(size, level - 1, left_first) ; turn(not left_first) ; draw_line(size) ; draw_hilbert(size, level - 1, not left_first) ; turn(left_first) ; end if ; end draw_hilbert ; begin loop clear ; for i in 1..4 loop here := (22, 60) ; clear ; puts("Hilbert's curve", 2, 62) ; --puts(" level "& integer'image(i), 3, 62) ; putsn(" level ", i, 3, 62) ; draw_hilbert(integer(24.0/(2**i+1)), i, true); end loop ; end loop ; end ;
with Gtk.Window; use Gtk.Window; with Gtk.Enums; with Gtk.Handlers; with Gtk.Main; with Gdk; with Gdk.Event; with Glib; use Glib; with Cairo; use Cairo; with Gdk.Cairo; pragma Elaborate_All (Gtk.Handlers); procedure Greyscale is Win : Gtk_Window; Width : constant := 640; Height : constant := 512; package Handlers is new Gtk.Handlers.Callback (Gtk_Window_Record); package Event_Cb is new Gtk.Handlers.Return_Callback ( Widget_Type => Gtk_Window_Record, Return_Type => Boolean); procedure Quit (Win : access Gtk_Window_Record'Class) is pragma Warnings (Off, Win); begin Gtk.Main.Main_Quit; end Quit; function Expose (Drawing : access Gtk_Window_Record'Class; Event : Gdk.Event.Gdk_Event) return Boolean is subtype Dub is Glib.Gdouble; Cr : Cairo_Context; Revert : Boolean; Grey : Dub; DH : constant Dub := Dub (Height) / 4.0; X, Y, DW : Dub; N : Natural; begin Cr := Gdk.Cairo.Create (Get_Window (Drawing)); for Row in 1 .. 4 loop N := 2 ** (Row + 2); Revert := (Row mod 2) = 0; DW := Dub (Width) / Dub (N); X := 0.0; Y := DH * Dub (Row - 1); for B in 0 .. (N - 1) loop Grey := Dub (B) / Dub (N - 1); if Revert then Grey := 1.0 - Grey; end if; Cairo.Set_Source_Rgb (Cr, Grey, Grey, Grey); Cairo.Rectangle (Cr, X, Y, DW, DH); Cairo.Fill (Cr); X := X + DW; end loop; end loop; Cairo.Destroy (Cr); return False; end Expose; begin Gtk.Main.Set_Locale; Gtk.Main.Init; Gtk_New (Win); Gtk.Window.Initialize (Win, Gtk.Enums.Window_Toplevel); Set_Title (Win, "Greyscale with GTKAda"); Set_Default_Size (Win, Width, Height); Set_App_Paintable (Win, True); -- Attach handlers Handlers.Connect (Win, "destroy", Handlers.To_Marshaller (Quit'Access)); Event_Cb.Connect (Win, "expose_event", Event_Cb.To_Marshaller (Expose'Access)); Show_All (Win); Gtk.Main.Main; end Greyscale;
-- { dg-do run } with Ada.Real_Time; procedure Test_Delay is begin delay until Ada.Real_Time.Clock; end Test_Delay;
procedure dynamic_array is type OpenArray is array (Natural range <>) of Integer; subtype ShortArray is OpenArray(1..4); type ItemArray is access ShortArray; Items : ItemArray := new ShortArray; begin Items.all := ShortArray'(others => 0); end dynamic_array;
------------------------------------------------------------ -- -- ADA REAL-TIME TIME-TRIGGERED SCHEDULING SUPPORT -- -- @file time_triggered_scheduling.adb -- -- @package Time_Triggered_Scheduling (BODY) -- -- @brief -- Ada Real-Time Time Triggered Scheduling support : Time Triggered Scheduling -- -- Ravenscar version -- ------------------------------------------------------------ with Ada.Task_Identification; use Ada.Task_Identification; with Ada.Synchronous_Task_Control; use Ada.Synchronous_Task_Control; package body Time_Triggered_Scheduling is -- Run time TT work info type Work_Control_Block is record Release_Point : Suspension_Object; Is_Running : Boolean := False; Work_Task_Id : Task_Id := Null_Task_Id; Last_Release : Time := Time_Last; end record; -- Array of Work_Control_Blocks WCB : array (Regular_Work_Id) of Work_Control_Block; -------------------------- -- Wait_For_Activation -- -------------------------- procedure Wait_For_Activation (Work_Id : Regular_Work_Id; When_Was_Released : out Time) is begin -- Register the Work_Id with the first task using it. -- Use of the Work_Id by another task breaks the model and causes PE if WCB (Work_Id).Work_Task_Id = Null_Task_Id then -- First time WFA called with this Work_Id -> Register caller WCB (Work_Id).Work_Task_Id := Current_Task; elsif WCB (Work_Id).Work_Task_Id /= Current_Task then -- Caller was not registered with this Work_Id raise Program_Error with ("Work_Id misuse"); end if; -- Caller is about to be suspended, hence not running WCB (Work_Id).Is_Running := False; Suspend_Until_True (WCB (Work_Id).Release_Point); -- Scheduler updated Last_Release when it released the worker task When_Was_Released := WCB (Work_Id).Last_Release; -- The worker is now released and starts running WCB (Work_Id).Is_Running := True; end Wait_For_Activation; ------------------------------ -- Time_Triggered_Scheduler -- ------------------------------ protected body Time_Triggered_Scheduler is -------------- -- Set_Plan -- -------------- procedure Set_Plan (TTP : in Time_Triggered_Plan_Access) is Now : constant Time := Clock; begin -- Take note of next plan to execute Next_Plan := TTP; -- Start new plan now if none is set. Otherwise, the scheduler will -- change to the Next_Plan at the end of the next mode change slot if Current_Plan = null then Change_Plan (Now); return; end if; -- Accept Set_Plan requests during a mode change slot (coming -- from ET tasks) and enforce the mode change at the end of it. -- Note that this point is reached only if there is currently -- a plan set, hence Current_Plan is not null if Current_Plan (Current_Slot_Index).Work_Id = Mode_Change_Slot then Change_Plan (Next_Slot_Release); end if; end Set_Plan; ----------------- -- Change_Plan -- ----------------- procedure Change_Plan (At_Time : Time) is begin Current_Plan := Next_Plan; Next_Plan := null; -- Setting both Current_ and Next_Slot_Index to 'First is consistent -- with the new slot TE handler for the first slot of a new plan. Current_Slot_Index := Current_Plan.all'First; Next_Slot_Index := Current_Plan.all'First; Next_Slot_Release := At_Time; NS_Event.Set_Handler (At_Time, NS_Handler_Access); end Change_Plan; ---------------- -- NS_Handler -- ---------------- procedure NS_Handler (Event : in out Timing_Event) is pragma Unreferenced (Event); Current_Work_Id : Any_Work_Id; Now : Time; begin Now := Next_Slot_Release; -- Check for overrun in the finishing slot. -- If this happens to be the first slot after a plan change, then -- an overrun from the last work of the old plan would have been -- detected at the start of the mode change slot. Current_Work_Id := Current_Plan (Current_Slot_Index).Work_Id; if Current_Work_Id in Regular_Work_Id and then WCB (Current_Work_Id).Is_Running then -- Overrun detected, raise PE raise Program_Error with ("Overrun detected in work " & Current_Work_Id'Image); end if; -- Update current slot index Current_Slot_Index := Next_Slot_Index; -- Compute next slot index if Next_Slot_Index < Current_Plan.all'Last then Next_Slot_Index := Next_Slot_Index + 1; else Next_Slot_Index := Current_Plan.all'First; end if; -- Compute next slot start time Next_Slot_Release := Next_Slot_Release + Current_Plan (Current_Slot_Index).Slot_Duration; -- Obtain current work id Current_Work_Id := Current_Plan (Current_Slot_Index).Work_Id; -- Process current slot actions -- Mode change slot case -- if Current_Work_Id = Mode_Change_Slot then if Next_Plan /= null then -- There's a pending plan change. It takes effect at the end of the MC slot Change_Plan (Next_Slot_Release); else -- Set the handler for the next scheduling point NS_Event.Set_Handler (Next_Slot_Release, NS_Handler_Access); end if; -- Empty slot case -- elsif Current_Work_Id = Empty_Slot then -- Set the handler for the next scheduling point NS_Event.Set_Handler (Next_Slot_Release, NS_Handler_Access); -- Regular slot case -- elsif Current_Work_Id in Regular_Work_Id'Range then -- Check whether the work's task has already registered. Raise PE otherwise if WCB (Current_Work_Id).Work_Task_Id = Null_Task_Id then raise Program_Error with ("Task not registered for Work_Id " & Current_Work_Id'Image); end if; -- Support for release time to measure release jitter of TT tasks WCB (Current_Work_Id).Last_Release := Now; -- Release task in charge of current work id Set_True (WCB (Current_Work_Id).Release_Point); -- Set the handler for the next scheduling point NS_Event.Set_Handler (Next_Slot_Release, NS_Handler_Access); else raise Program_Error with "Invalid Work Id"; end if; end NS_Handler; end Time_Triggered_Scheduler; ---------------- -- Set_Plan -- ---------------- procedure Set_Plan (TTP : in Time_Triggered_Plan_Access) is begin Time_Triggered_Scheduler.Set_Plan (TTP); end Set_Plan; end Time_Triggered_Scheduling;
-- part of ParserTools, (c) 2017 Felix Krause -- released under the terms of the MIT license, see the file "copying.txt" package body Text.Builder.Unicode is procedure Append (Object : in out Reference; Value : Strings_Edit.UTF8.Code_Point) is Buffer : String (1 .. 4); Position : Positive := 1; begin Strings_Edit.UTF8.Put (Buffer, Position, Value); Object.Append (Buffer (1 .. Position - 1)); --if Object.Next + 3 > -- maximum UTF-8 encoded character length is 4 -- System.Storage_Elements.Storage_Offset (Object.Buffer.all'Last) then -- Grow (Object, 4); --end if; --Strings_Edit.UTF8.Put (Object.Buffer.all, Positive (Object.Next), Value); end Append; end Text.Builder.Unicode;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2018 onox <denkpadje@gmail.com> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Unchecked_Deallocation; package body Orka.Smart_Pointers is procedure Free is new Ada.Unchecked_Deallocation (Data_Record, Data_Record_Access); function Is_Null (Object : Abstract_Pointer) return Boolean is (Object.Data = null); function References (Object : Abstract_Pointer) return Natural is (Object.Data.References.Count); procedure Set (Object : in out Abstract_Pointer; Value : not null Object_Access) is begin if Object.Data /= null then -- Decrement old reference count Finalize (Object); end if; Object.Data := new Data_Record'(Object => Value, References => <>); end Set; function Get (Object : Mutable_Pointer) return Reference is begin return Reference'(Value => Object.Data.Object, Hold => Object); end Get; function Get (Object : Pointer) return Constant_Reference is begin return Constant_Reference'(Value => Object.Data.Object, Hold => Object); end Get; overriding procedure Adjust (Object : in out Abstract_Pointer) is begin if Object.Data /= null then Object.Data.References.Increment; end if; end Adjust; overriding procedure Finalize (Object : in out Abstract_Pointer) is Zero : Boolean; begin if Object.Data /= null then Object.Data.References.Decrement (Zero); if Zero then Free_Object (Object.Data.Object); Free (Object.Data); end if; end if; -- Idempotence: next call to Finalize has no effect Object.Data := null; end Finalize; end Orka.Smart_Pointers;
with Ada.Exceptions; with Ada.Text_IO; use Ada.Text_IO; with CORBA.Impl; with CORBA.Object; with CORBA.ORB; with PortableServer.POA.Helper; with PortableServer.POAManager; with CorbaCBSG.CBSG.Impl; with PolyORB.CORBA_P.CORBALOC; -- Allow to specify how PolyORB should work with PolyORB.Setup.No_Tasking_Server; pragma Warnings (Off, PolyORB.Setup.No_Tasking_Server); procedure Server is begin declare -- Allow to get the parameters according to the CORBA Standard -- For example, InitialRef Argv : CORBA.ORB.Arg_List := CORBA.ORB.Command_Line_Arguments; begin -- Init of our bus named ORB CORBA.ORB.Init (CORBA.ORB.To_CORBA_String ("ORB"), Argv); declare -- The PortableObjectAdapter is the place we "store" our objects Root_POA : PortableServer.POA.Local_Ref; -- We declare a reference to our distributed object Ref : CORBA.Object.Ref; -- And its implementation Obj : constant CORBA.Impl.Object_Ptr := new CorbaCBSG.CBSG.Impl.Object; begin -- We get the root POA of our bus -- It's a CORBA interface, so note the use of CORBA String instead of Ada ones -- We then resolve it to an object reference Root_POA := PortableServer.POA.Helper.To_Local_Ref (CORBA.ORB.Resolve_Initial_References (CORBA.ORB.To_CORBA_String ("RootPOA"))); -- We start our POA (in fact, the top-level one) PortableServer.POAManager.Activate (PortableServer.POA.Get_The_POAManager (Root_POA)); -- We create a reference on our object (the servant) to expose it to the outside world Ref := PortableServer.POA.Servant_To_Reference (Root_POA, PortableServer.Servant (Obj)); -- And we display its address, the IOR. Put_Line ("'" & CORBA.To_Standard_String (CORBA.Object.Object_To_String (Ref)) & "'"); New_Line; -- And its shorter version, the corbaloc -- unfortunately, corbaloc is not supported by every ORB implementation Put_Line ("'" & CORBA.To_Standard_String (PolyORB.CORBA_P.CORBALOC.Object_To_Corbaloc (Ref)) & "'"); -- Launch the server. CORBA.ORB.Run is supposed to never return, -- print a message if it does. CORBA.ORB.Run; Put_Line ("ORB main loop terminated!"); end; end; exception -- Of course, we display a message in case of exception when E : others => Put_Line ("CBSG server raised " & Ada.Exceptions.Exception_Information (E)); raise; end Server;
-------------------------------------------------------------------------------- -- Copyright (c) 2013, Felix Krause <contact@flyx.org> -- -- Permission to use, copy, modify, and/or distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -------------------------------------------------------------------------------- with Ada.Containers.Indefinite_Vectors; with CL.Platforms; with System.Storage_Elements; with CL.Contexts; package CL.Programs is type Program is new Runtime_Object with null record; package SSE renames System.Storage_Elements; type Binary_List is array (Positive range <>) of access SSE.Storage_Array; package String_Vectors is new Ada.Containers.Indefinite_Vectors (Positive, String); subtype String_List is String_Vectors.Vector; type Bool_List is array (Positive range <>) of Boolean; type Build_Status is (In_Progress, Error, None, Success); type Build_Callback is access procedure (Subject : Program); package Constructors is function Create_From_Source (Context : Contexts.Context'Class; Source : String) return Program; -- Create a program from a list of OpenCL sources. function Create_From_Source (Context : Contexts.Context'Class; Sources : String_List) return Program; -- Create a program from a list of files containing OpenCL sources. -- The files can be provided as relative or absolute paths. function Create_From_Files (Context : Contexts.Context'Class; Sources : String_List) return Program; -- The result for each binary in Binaries will be stored in Success -- at the position of the binary's index in Binaries. Therefore, Success -- should have a range covering all indexes Binaries contains. -- If Success misses an index present in Binaries, Invalid_Arg_Size will -- be raised. -- Success.all(I) will be True iff Binaries(I) was loaded successfully. -- Iff Success is null, it will be ignored and instead an Invalid_Binary -- exception will be raised if any of the Binaries fails to build. function Create_From_Binary (Context : Contexts.Context'Class; Devices : Platforms.Device_List; Binaries : Binary_List; Success : access Bool_List) return Program; end Constructors; overriding procedure Adjust (Object : in out Program); overriding procedure Finalize (Object : in out Program); procedure Build (Source : Program; Devices : Platforms.Device_List; Options : String; Callback : Build_Callback); function Reference_Count (Source : Program) return UInt; function Context (Source : Program) return Contexts.Context; function Devices (Source : Program) return Platforms.Device_List; function Source (Source : Program) return String; function Binaries (Source : Program) return Binary_List; function Status (Source : Program; Device : Platforms.Device) return Build_Status; function Build_Options (Source : Program; Device : Platforms.Device) return String; function Build_Log (Source : Program; Device : Platforms.Device) return String; procedure Unload_Compiler; private for Build_Status use (Success => 0, None => -1, Error => -2, In_Progress => -3); for Build_Status'Size use Int'Size; pragma Convention (C, Build_Callback); end CL.Programs;
with Ada.Text_Io; package body Callbacks is procedure On_Change (Value : in Integer) is begin Ada.Text_Io.Put_Line("On_Change(" & Value'Image & ") called"); end; end Callbacks;
-- MIT License -- Copyright (c) 2021 Stephen Merrony -- 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.Strings.Unbounded; use Ada.Strings.Unbounded; with GNAT.Sockets; with DG_Types; use DG_Types; package AOSVS is type Args_Arr is array (0..31) of Unbounded_String; type PID_T is new Integer range 0 .. 255; PC_In_Pr : constant Natural := 8#0574#; Page8_Offset : constant Natural := 8192; WSFH_In_Pr : constant Natural := Page8_Offset + 12; WFP_In_Pr : constant Natural := Page8_Offset + 16; WSP_In_Pr : constant Natural := Page8_Offset + 18; WSL_In_Pr : constant Natural := Page8_Offset + 20; WSB_In_Pr : constant Natural := Page8_Offset + 22; type UST_T is record -- our representation of AOS/VS UST Ext_Var_Wd_Count : Word_T; Ext_Var_P0_Start : Word_T; Syms_Start : Dword_T; Syms_End : Dword_T; Debug_Addr : Phys_Addr_T; Revision : Dword_T; Task_Count : Word_T; Impure_Blocks : Word_T; Shared_Start_Block : Dword_T; -- this seems to be a page #, not a block # Int_Addr : Phys_Addr_T; Shared_Block_Count : Word_T; -- this seems to be a page count, not blocks PR_Type : Word_T; Shared_Start_Page_In_PR : Dword_T; end record; type PR_Addrs_T is record -- some key addresses from the PR file PR_Start, WFP, WSB, WSFH, WSL, WSP : Phys_Addr_T; end record; procedure Start (PR_Name : in String; Dir : in String; Segment : in Natural; Arg_Count : in Positive; Args : in Args_Arr; Console : in GNAT.Sockets.Stream_Access; Logging : in Boolean); function Encode_Global_Port (PID : in PID_T; Ring : in Natural; Local_Port : in Word_T) return Dword_T; procedure Decode_Global_Port (Global_Port : in Dword_T; PID : out PID_T; Ring : out Natural; Local_Port : out Word_T); function Colonify_Path (In_Str : in String) return String; function Slashify_Path (In_Str : in String) return String; Invalid_PR_File, Invalid_Directory, Not_Yet_Implemented : exception; end AOSVS;
pragma License (Unrestricted); -- runtime unit with System.Unwind.Representation; package System.Unwind.Handling is pragma Preelaborate; -- hook for entering an exception handler (a-exexpr-gcc.adb) procedure Begin_Handler ( Machine_Occurrence : Representation.Machine_Occurrence_Access) with Export, Convention => C, External_Name => "__gnat_begin_handler"; -- hook for leaving an exception handler (a-exexpr-gcc.adb) procedure End_Handler ( Machine_Occurrence : Representation.Machine_Occurrence_Access) with Export, Convention => C, External_Name => "__gnat_end_handler"; -- when E : others (a-exexpr-gcc.adb) procedure Set_Exception_Parameter ( X : not null Exception_Occurrence_Access; Machine_Occurrence : not null Representation.Machine_Occurrence_Access) with Export, Convention => C, External_Name => "__gnat_set_exception_parameter"; end System.Unwind.Handling;
with Ada.Text_Io, Ada.Integer_Text_Io; use Ada.Text_Io, Ada.Integer_Text_Io; with matrices,posicion_en_matriz; use matrices; procedure prueba_posicion_en_matriz is M1:Matriz_De_Enteros(1..4, 1..10); numero, posicion_fila, posicion_columna: Integer; begin -- Caso de prueba 1: M1 := ((1, 3, 5, 7, 9, 11, 13, 15, 17, 1), (3, 3, 5, 7, 9, 11, 13, 15, 17, 1), (5, 3, 5, 7, 9, 11, 13, 15, 17, 1), (7, 3, 5, 7, 9, 11, 13, 15, 17, 19)); -- lo mismo que hacer M1(1,1) := 1; ... M1(4, 10) := 19; Put_line("prueba 1: el numero al final de la matriz"); Put_line(" posicion_en_matriz((1, 3, 5, 7, 9, 11, 13, 15, 17, 1)"); Put_line(" (3, 3, 5, 7, 9, 11, 13, 15, 17, 1)"); Put_line(" (5, 3, 5, 7, 9, 11, 13, 15, 17, 1)"); Put_line(" (7, 3, 5, 7, 9, 11, 13, 15, 17, 19))"); put_line(" El resultado deberia de ser numero=19 fila=4 columna=10 "); numero:=19; posicion_en_matriz(M1, numero, posicion_fila, posicion_columna); Put(numero); Put(posicion_fila); Put(posicion_columna); New_Line(3); Put_Line("Pulsa Intro para continuar"); Skip_Line; New_Line(3); -- Caso de prueba 2: M1 := (( 1, 3, 5, 7, 9, 11, 13, 15, 17, 19), (21, 23, 25, 27, 29, 31, 33, 35, 37, 39), (41, 43, 45, 47, 49, 51, 53, 55, 57, 59), (61, 63, 65, 67, 69, 71, 73, 75, 77, 79)); -- lo mismo que hacer M1(1,1) := 1; ... M1(4, 10) := 19; Put_line("prueba 1: el numero al final de la matriz"); Put_line(" posicion_en_matriz(( 1, 3, 5, 7, 9, 11, 13, 15, 17, 19)"); Put_line(" (21, 23, 25, 27, 29, 31, 33, 35, 37, 39)"); Put_line(" (41, 43, 45, 47, 49, 51, 53, 55, 57, 59)"); Put_line(" (61, 63, 65, 67, 69, 71, 73, 75, 77, 79))"); put_line(" El resultado deberia de ser numero=55 fila=3 columna=8 "); numero:=55; posicion_en_matriz(M1, numero, posicion_fila, posicion_columna); Put(numero); Put(posicion_fila); Put(posicion_columna); New_Line(3); Put_Line("Pulsa Intro para continuar"); Skip_Line; New_Line(3); -- Caso de prueba 3: M1 := ((0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)); -- lo mismo que hacer M1(1,1) := 1; ... M1(4, 10) := 19; Put_line("prueba 1: el numero al final de la matriz"); Put_line(" posicion_en_matriz((0, 1, 2, 3, 4, 5, 6, 7, 8, 9)"); Put_line(" (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)"); Put_line(" (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)"); Put_line(" (0, 1, 2, 3, 4, 5, 6, 7, 8, 9))"); put_line(" El resultado deberia de ser numero=10 fila=-1 columna=-1 "); numero:=10; posicion_en_matriz(M1, numero, posicion_fila, posicion_columna); Put(numero); Put(posicion_fila); Put(posicion_columna); New_Line(3); Put_Line("Pulsa Intro para continuar"); Skip_Line; New_Line(3); end prueba_posicion_en_matriz;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- Copyright (C) 2016-2019, AdaCore -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Ada.Unchecked_Conversion; with Interfaces; use Interfaces; with Interfaces.ARM_V7AR; use Interfaces.ARM_V7AR; with System; use System; package body Board_Init is -- MPU table constants pragma Warnings (Off, "*is not referenced"); Size_32B : constant Unsigned_32 := 2#00100_0#; -- 0x04 << 1 Size_64B : constant Unsigned_32 := 2#00101_0#; -- 0x05 << 1 Size_126B : constant Unsigned_32 := 2#00110_0#; -- 0x06 << 1 Size_256B : constant Unsigned_32 := 2#00111_0#; -- 0x07 << 1 Size_512B : constant Unsigned_32 := 2#01000_0#; -- 0x08 << 1 Size_1kB : constant Unsigned_32 := 2#01001_0#; -- 0x09 << 1 Size_2kB : constant Unsigned_32 := 2#01010_0#; -- 0x0A << 1 Size_4kB : constant Unsigned_32 := 2#01011_0#; -- 0x0B << 1 Size_8kB : constant Unsigned_32 := 2#01100_0#; -- 0x0C << 1 Size_16kB : constant Unsigned_32 := 2#01101_0#; -- 0x0D << 1 Size_32kB : constant Unsigned_32 := 2#01110_0#; -- 0x0E << 1 Size_64kB : constant Unsigned_32 := 2#01111_0#; -- 0x0F << 1 Size_128kB : constant Unsigned_32 := 2#10000_0#; -- 0x10 << 1 Size_256kB : constant Unsigned_32 := 2#10001_0#; -- 0x11 << 1 Size_512kB : constant Unsigned_32 := 2#10010_0#; -- 0x12 << 1 Size_1MB : constant Unsigned_32 := 2#10011_0#; -- 0x13 << 1 Size_2MB : constant Unsigned_32 := 2#10100_0#; -- 0x14 << 1 Size_4MB : constant Unsigned_32 := 2#10101_0#; -- 0x15 << 1 Size_8MB : constant Unsigned_32 := 2#10110_0#; -- 0x16 << 1 Size_16MB : constant Unsigned_32 := 2#10111_0#; -- 0x17 << 1 Size_32MB : constant Unsigned_32 := 2#11000_0#; -- 0x18 << 1 Size_64MB : constant Unsigned_32 := 2#11001_0#; -- 0x19 << 1 Size_128MB : constant Unsigned_32 := 2#11010_0#; -- 0x1A << 1 Size_256MB : constant Unsigned_32 := 2#11011_0#; -- 0x1B << 1 Size_512MB : constant Unsigned_32 := 2#11100_0#; -- 0x1C << 1 Size_1GB : constant Unsigned_32 := 2#11101_0#; -- 0x1D << 1 Size_2GB : constant Unsigned_32 := 2#11110_0#; -- 0x1E << 1 Size_4GB : constant Unsigned_32 := 2#11111_0#; -- 0x1F << 1 XN : constant Unsigned_32 := 16#1000#; AP_NA_NA : constant Unsigned_32 := 16#000#; AP_RW_NA : constant Unsigned_32 := 16#100#; AP_RW_RO : constant Unsigned_32 := 16#200#; AP_RW_RW : constant Unsigned_32 := 16#300#; AP_RO_NA : constant Unsigned_32 := 16#500#; AP_RO_RO : constant Unsigned_32 := 16#600#; STRONGLY_ORDERED : constant Unsigned_32 := 16#00#; -- TEX: 0, C: 0, B: 0 SHAREABLE_DEVICE : constant Unsigned_32 := 16#01#; -- TEX: 0, C: 0, B: 1 WT_NO_WA : constant Unsigned_32 := 16#02#; -- TEX: 0, C: 1, B: 0 WB_NO_WA : constant Unsigned_32 := 16#03#; -- TEX: 0, C: 1, B: 1 NO_CACHE : constant Unsigned_32 := 16#08#; -- TEX: 1, C: 0, B: 0 WB_WA : constant Unsigned_32 := 16#0B#; -- TEX: 1, C: 1, B: 1 NON_SHAREABLE : constant Unsigned_32 := 16#10#; -- TEX: 2, C: 0, B: 0 SHARED : constant Unsigned_32 := 16#04#; pragma Warnings (On, "*is not referenced"); procedure System_Init; pragma Import (C, System_Init, "__gnat_system_init"); -- Initializes clocks and peripherals. This part is MCU specific. -- Code generated using HalCoGen.get procedure Enable_Event_Bus_Export; -- Allows the CPU to signal any single-bit or double-bit errors -- detected by its ECC logic for accesses to program flash or data -- RAM procedure Enable_ECC; -- Enables Checksum Checks on RAM and FLASH. procedure Setup_MPU; -- Setup the Memory Protection Unit regions and enables it procedure Enable_Cache; -- Enables instruction and data cache ----------------------------- -- Enable_Event_Bus_Export -- ----------------------------- procedure Enable_Event_Bus_Export is begin -- Set the X bit of the PMCR sys register CP15.Set_PMCR (CP15.Get_PMCR or 16#10#); end Enable_Event_Bus_Export; --------------- -- Setup_MPU -- --------------- procedure Setup_MPU is SRAM_Start : Character; pragma Import (Asm, SRAM_Start, "__gnat_ram_start"); SRAM_End : Character; pragma Import (Asm, SRAM_End, "__gnat_ram_end"); function As_Int is new Ada.Unchecked_Conversion (System.Address, Unsigned_32); SRAM_At_0 : constant Boolean := SRAM_Start'Address = System.Null_Address; SRAM_Size : constant Unsigned_32 := As_Int (SRAM_End'Address) - As_Int (SRAM_Start'Address); -- Cannot use System.Storage_Elements.Storage_Count here as -- System.Storage_Elements does not declare No_Elaboration_Code_All SCTLR : Unsigned_32; MPUIR : Unsigned_32; Num_Rgn : Unsigned_32; Policy : constant Unsigned_32 := NO_CACHE; begin -- First disable the MPU SCTLR := CP15.Get_SCTLR; if (SCTLR and 1) = 1 then SCTLR := SCTLR and 16#FFFF_FFFE#; -- Clear the MPU Enable bit Barriers.DSB; CP15.Set_SCTLR (SCTLR); Barriers.ISB; end if; -- Disable background region for MPU SCTLR := CP15.Get_SCTLR; SCTLR := SCTLR and (not (2 ** 17)); CP15.Set_SCTLR (SCTLR); -- Now will the MPU table MPUIR := CP15.Get_MPUIR; Num_Rgn := Shift_Right (MPUIR and 16#FF00#, 8); -- Region 1: background region CP15.Set_MPU_Region_Number (0); CP15.Set_MPU_Region_Base_Address (16#0000_0000#); CP15.Set_MPU_Region_Size_And_Enable (Shift_Left (16#FF#, 8) or Size_4GB or 1); CP15.Set_MPU_Region_Access_Control (XN or AP_NA_NA or Policy); -- Region 2: FLASH @ 0x0, or SRAM @ 0x0 if mem swapped CP15.Set_MPU_Region_Number (1); CP15.Set_MPU_Region_Base_Address (16#0000_0000#); if SRAM_At_0 then declare Sz : Unsigned_32; begin -- Supported configurations: 256kB SRAM, 512kB SRAM, or 16MB RAM -- at address 0x0. if SRAM_Size <= 256 * 1024 then Sz := Size_256kB; elsif SRAM_Size <= 512 * 1024 then Sz := Size_512kB; else Sz := Size_16MB; end if; CP15.Set_MPU_Region_Size_And_Enable (Sz or 1); end; CP15.Set_MPU_Region_Access_Control (AP_RW_RW or Policy); else CP15.Set_MPU_Region_Size_And_Enable (Size_4MB or 1); CP15.Set_MPU_Region_Access_Control (AP_RO_RO or Policy); end if; -- Region 3: SRAM @ 0x0800_0000 or FLASH is mem swapped CP15.Set_MPU_Region_Number (2); CP15.Set_MPU_Region_Base_Address (16#0800_0000#); if SRAM_At_0 then -- FLASH Region -- Only 512kB of FLASH is accessible in this case CP15.Set_MPU_Region_Size_And_Enable (Size_512kB or 1); CP15.Set_MPU_Region_Access_Control (AP_RO_RO or Policy); else declare Sz : Unsigned_32; begin -- Supported configurations: 256kB or 512kB SRAM. if SRAM_Size <= 256 * 1024 then Sz := Size_256kB; else Sz := Size_512kB; end if; CP15.Set_MPU_Region_Size_And_Enable (Sz or 1); end; CP15.Set_MPU_Region_Access_Control (AP_RW_RW or Policy); end if; -- Region 4: Async RAM CP15.Set_MPU_Region_Number (3); CP15.Set_MPU_Region_Base_Address (16#6000_0000#); CP15.Set_MPU_Region_Size_And_Enable (Size_64MB or 1); CP15.Set_MPU_Region_Access_Control (AP_RW_RW or STRONGLY_ORDERED); -- Region 5: SDRAM CP15.Set_MPU_Region_Number (4); CP15.Set_MPU_Region_Base_Address (16#8000_0000#); CP15.Set_MPU_Region_Size_And_Enable (Size_128MB or 1); CP15.Set_MPU_Region_Access_Control (AP_RW_RW or Policy or SHARED); -- Region 6: 6MB Flash OTP, ECC, EEPROM Bank CP15.Set_MPU_Region_Number (5); CP15.Set_MPU_Region_Base_Address (16#F000_0000#); -- Disable sub-regions 7 and 8 CP15.Set_MPU_Region_Size_And_Enable (16#C000# or Size_8MB or 1); CP15.Set_MPU_Region_Access_Control (XN or AP_RW_RW or NO_CACHE); -- Region 7: 16MB peripheral segment 2 CP15.Set_MPU_Region_Number (6); CP15.Set_MPU_Region_Base_Address (16#FC00_0000#); CP15.Set_MPU_Region_Size_And_Enable (Size_16MB or 1); CP15.Set_MPU_Region_Access_Control (XN or AP_RW_RW or NON_SHAREABLE); -- Region 8: 512B accessible CRC module CP15.Set_MPU_Region_Number (7); CP15.Set_MPU_Region_Base_Address (16#FE00_0000#); CP15.Set_MPU_Region_Size_And_Enable (Size_512B or 1); CP15.Set_MPU_Region_Access_Control (XN or AP_RW_RW or NON_SHAREABLE); -- Region 9: 16MB peripheral segment 3, including sys regs CP15.Set_MPU_Region_Number (8); CP15.Set_MPU_Region_Base_Address (16#FF00_0000#); CP15.Set_MPU_Region_Size_And_Enable (Size_16MB or 1); CP15.Set_MPU_Region_Access_Control (XN or AP_RW_RW or NON_SHAREABLE); -- Disable the unused regions for J in 9 .. Num_Rgn loop CP15.Set_MPU_Region_Number (J); CP15.Set_MPU_Region_Base_Address (16#0000_0000#); CP15.Set_MPU_Region_Size_And_Enable (Size_32B or 0); CP15.Set_MPU_Region_Access_Control (XN); end loop; -- Enable background region for MPU SCTLR := CP15.Get_SCTLR; SCTLR := SCTLR or (2 ** 17); CP15.Set_SCTLR (SCTLR); -- Enable the MPU SCTLR := CP15.Get_SCTLR; SCTLR := SCTLR or 1; CP15.Set_SCTLR (SCTLR); Barriers.ISB; end Setup_MPU; ---------------- -- Enable_ECC -- ---------------- procedure Enable_ECC is FEDACCTRL1 : Unsigned_32 with Volatile, Import, Address => System'To_Address (16#FFF8_7008#); MINITGCR : Unsigned_32 with Volatile, Import, Address => System'To_Address (16#FFFF_FF5C#); MSIENA : Unsigned_32 with Volatile, Import, Address => System'To_Address (16#FFFF_FF60#); MSTCGSTAT : Unsigned_32 with Volatile, Import, Address => System'To_Address (16#FFFF_FF68#); ACTLR : Unsigned_32; begin -- First enable response to ECC errors indicated by CPU for accesses to -- flash. -- FEDACCTRL1: -- EDACEN [0-3]: error detection and correction enabled -- EPEN [8]: error profiling is disabled -- EZFEN [9]: event on zeros fail enable -- EOFEN [10]: event on ones fail enable -- EDACMODE [16-19]: error correction mode selection as uncorrectable -- errors -- SUSP_IGNR [24]: cpu suspend signal blocks error bits setting and -- un-freezing FEDACCTRL1 := 16#000a_060A#; -- Initialize the CPU RAM ECC locations MINITGCR := 16#A#; -- enable global memroy hw initialization MSIENA := 16#1#; -- enable auto-hw init of SRAM loop -- check the MINIDONE bit exit when (MSTCGSTAT and 16#100#) /= 0; end loop; MINITGCR := 16#5#; -- remove the key from the hw initialization lock -- Enable CPU ECC checking for flash accesses ACTLR := CP15.Get_ACTLR; ACTLR := ACTLR or 16#C000000#; -- DICDI and DIB2DI bits Barriers.DMB; CP15.Set_ACTLR (ACTLR); Barriers.ISB; end Enable_ECC; ------------------ -- Enable_Cache -- ------------------ procedure Enable_Cache is ACTLR : Unsigned_32; SCTLR : Unsigned_32; begin ACTLR := CP15.Get_ACTLR; -- Clear bit 5 (enable ECC) ACTLR := ACTLR and not (2 ** 5); CP15.Set_ACTLR (ACTLR); SCTLR := CP15.Get_SCTLR; SCTLR := SCTLR or (2 ** 2) or (2 ** 12); -- resp D and I bits Barriers.DSB; Cache.Invalidate_DCache; Barriers.DSB; Cache.Invalidate_ICache; Barriers.DSB; CP15.Set_SCTLR (SCTLR); Barriers.ISB; end Enable_Cache; ---------------- -- Board_Init -- ---------------- procedure Board_Init is SYSESR : Unsigned_32 with Volatile, Import, Address => System'To_Address (16#FFFF_FFe4#); begin -- Check reset condition at startup if SYSESR = 0 then -- Reset condition is 0: the boot has already been taken care of, so -- let's just return. return; elsif (SYSESR and 16#8800#) /= 0 then -- Power-on reset or Debug reset: -- do a full system init first System_Init; Enable_Event_Bus_Export; Enable_ECC; -- Finally clear the reset flag SYSESR := 16#8800#; elsif (SYSESR and 16#20#) /= 0 then -- CPU reset: -- do a full system init first System_Init; Enable_Event_Bus_Export; -- Note: leave the ECC settings for RAM and FLASH as those have -- not changed after a CPU reset SYSESR := 16#20#; end if; Setup_MPU; Enable_Cache; end Board_Init; end Board_Init;
pragma License (Unrestricted); package Ada.Calendar.Arithmetic is -- Arithmetic on days: type Day_Count is range -366 * (1 + Year_Number'Last - Year_Number'First) .. +366 * (1 + Year_Number'Last - Year_Number'First); subtype Leap_Seconds_Count is Integer range -2047 .. 2047; procedure Difference ( Left, Right : Time; Days : out Day_Count; Seconds : out Duration; Leap_Seconds : out Leap_Seconds_Count); function "+" (Left : Time; Right : Day_Count) return Time; function "+" (Left : Day_Count; Right : Time) return Time; function "-" (Left : Time; Right : Day_Count) return Time; function "-" (Left, Right : Time) return Day_Count; pragma Inline ("+"); pragma Inline ("-"); end Ada.Calendar.Arithmetic;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- A D A . T E X T _ I O -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2016, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Ada.Streams; use Ada.Streams; with Interfaces.C_Streams; use Interfaces.C_Streams; with System.File_IO; with System.CRTL; with System.WCh_Cnv; use System.WCh_Cnv; with System.WCh_Con; use System.WCh_Con; with Ada.Unchecked_Conversion; with Ada.Unchecked_Deallocation; pragma Elaborate_All (System.File_IO); -- Needed because of calls to Chain_File in package body elaboration package body Ada.Text_IO is package FIO renames System.File_IO; subtype AP is FCB.AFCB_Ptr; function To_FCB is new Ada.Unchecked_Conversion (File_Mode, FCB.File_Mode); function To_TIO is new Ada.Unchecked_Conversion (FCB.File_Mode, File_Mode); use type FCB.File_Mode; use type System.CRTL.size_t; WC_Encoding : Character; pragma Import (C, WC_Encoding, "__gl_wc_encoding"); -- Default wide character encoding Err_Name : aliased String := "*stderr" & ASCII.NUL; In_Name : aliased String := "*stdin" & ASCII.NUL; Out_Name : aliased String := "*stdout" & ASCII.NUL; -- Names of standard files -- -- Use "preallocated" strings to avoid calling "new" during the elaboration -- of the run time. This is needed in the tasking case to avoid calling -- Task_Lock too early. A filename is expected to end with a null character -- in the runtime, here the null characters are added just to have a -- correct filename length. -- -- Note: the names for these files are bogus, and probably it would be -- better for these files to have no names, but the ACVC tests insist. -- We use names that are bound to fail in open etc. Null_Str : aliased constant String := ""; -- Used as form string for standard files ----------------------- -- Local Subprograms -- ----------------------- function Get_Upper_Half_Char (C : Character; File : File_Type) return Character; -- This function is shared by Get and Get_Immediate to extract an encoded -- upper half character value from the given File. The first byte has -- already been read and is passed in C. The character value is returned as -- the result, and the file pointer is bumped past the character. -- Constraint_Error is raised if the encoded value is outside the bounds of -- type Character. function Get_Upper_Half_Char_Immed (C : Character; File : File_Type) return Character; -- This routine is identical to Get_Upper_Half_Char, except that the reads -- are done in Get_Immediate mode (i.e. without waiting for a line return). function Getc (File : File_Type) return int; -- Gets next character from file, which has already been checked for being -- in read status, and returns the character read if no error occurs. The -- result is EOF if the end of file was read. function Getc_Immed (File : File_Type) return int; -- This routine is identical to Getc, except that the read is done in -- Get_Immediate mode (i.e. without waiting for a line return). function Has_Upper_Half_Character (Item : String) return Boolean; -- Returns True if any of the characters is in the range 16#80#-16#FF# function Nextc (File : File_Type) return int; -- Returns next character from file without skipping past it (i.e. it is a -- combination of Getc followed by an Ungetc). procedure Put_Encoded (File : File_Type; Char : Character); -- Called to output a character Char to the given File, when the encoding -- method for the file is other than brackets, and Char is upper half. procedure Putc (ch : int; File : File_Type); -- Outputs the given character to the file, which has already been checked -- for being in output status. Device_Error is raised if the character -- cannot be written. procedure Set_WCEM (File : in out File_Type); -- Called by Open and Create to set the wide character encoding method for -- the file, processing a WCEM form parameter if one is present. File is -- IN OUT because it may be closed in case of an error. procedure Terminate_Line (File : File_Type); -- If the file is in Write_File or Append_File mode, and the current line -- is not terminated, then a line terminator is written using New_Line. -- Note that there is no Terminate_Page routine, because the page mark at -- the end of the file is implied if necessary. procedure Ungetc (ch : int; File : File_Type); -- Pushes back character into stream, using ungetc. The caller has checked -- that the file is in read status. Device_Error is raised if the character -- cannot be pushed back. An attempt to push back and end of file character -- (EOF) is ignored. ------------------- -- AFCB_Allocate -- ------------------- function AFCB_Allocate (Control_Block : Text_AFCB) return FCB.AFCB_Ptr is pragma Unreferenced (Control_Block); begin return new Text_AFCB; end AFCB_Allocate; ---------------- -- AFCB_Close -- ---------------- procedure AFCB_Close (File : not null access Text_AFCB) is begin -- If the file being closed is one of the current files, then close -- the corresponding current file. It is not clear that this action -- is required (RM A.10.3(23)) but it seems reasonable, and besides -- ACVC test CE3208A expects this behavior. if File_Type (File) = Current_In then Current_In := null; elsif File_Type (File) = Current_Out then Current_Out := null; elsif File_Type (File) = Current_Err then Current_Err := null; end if; Terminate_Line (File_Type (File)); end AFCB_Close; --------------- -- AFCB_Free -- --------------- procedure AFCB_Free (File : not null access Text_AFCB) is type FCB_Ptr is access all Text_AFCB; FT : FCB_Ptr := FCB_Ptr (File); procedure Free is new Ada.Unchecked_Deallocation (Text_AFCB, FCB_Ptr); begin Free (FT); end AFCB_Free; ----------- -- Close -- ----------- procedure Close (File : in out File_Type) is begin FIO.Close (AP (File)'Unrestricted_Access); end Close; --------- -- Col -- --------- -- Note: we assume that it is impossible in practice for the column -- to exceed the value of Count'Last, i.e. no check is required for -- overflow raising layout error. function Col (File : File_Type) return Positive_Count is begin FIO.Check_File_Open (AP (File)); return File.Col; end Col; function Col return Positive_Count is begin return Col (Current_Out); end Col; ------------ -- Create -- ------------ procedure Create (File : in out File_Type; Mode : File_Mode := Out_File; Name : String := ""; Form : String := "") is Dummy_File_Control_Block : Text_AFCB; pragma Warnings (Off, Dummy_File_Control_Block); -- Yes, we know this is never assigned a value, only the tag -- is used for dispatching purposes, so that's expected. begin FIO.Open (File_Ptr => AP (File), Dummy_FCB => Dummy_File_Control_Block, Mode => To_FCB (Mode), Name => Name, Form => Form, Amethod => 'T', Creat => True, Text => True); File.Self := File; Set_WCEM (File); end Create; ------------------- -- Current_Error -- ------------------- function Current_Error return File_Type is begin return Current_Err; end Current_Error; function Current_Error return File_Access is begin return Current_Err.Self'Access; end Current_Error; ------------------- -- Current_Input -- ------------------- function Current_Input return File_Type is begin return Current_In; end Current_Input; function Current_Input return File_Access is begin return Current_In.Self'Access; end Current_Input; -------------------- -- Current_Output -- -------------------- function Current_Output return File_Type is begin return Current_Out; end Current_Output; function Current_Output return File_Access is begin return Current_Out.Self'Access; end Current_Output; ------------ -- Delete -- ------------ procedure Delete (File : in out File_Type) is begin FIO.Delete (AP (File)'Unrestricted_Access); end Delete; ----------------- -- End_Of_File -- ----------------- function End_Of_File (File : File_Type) return Boolean is ch : int; begin FIO.Check_Read_Status (AP (File)); if File.Before_Upper_Half_Character then return False; elsif File.Before_LM then if File.Before_LM_PM then return Nextc (File) = EOF; end if; else ch := Getc (File); if ch = EOF then return True; elsif ch /= LM then Ungetc (ch, File); return False; else -- ch = LM File.Before_LM := True; end if; end if; -- Here we are just past the line mark with Before_LM set so that we -- do not have to try to back up past the LM, thus avoiding the need -- to back up more than one character. ch := Getc (File); if ch = EOF then return True; elsif ch = PM and then File.Is_Regular_File then File.Before_LM_PM := True; return Nextc (File) = EOF; -- Here if neither EOF nor PM followed end of line else Ungetc (ch, File); return False; end if; end End_Of_File; function End_Of_File return Boolean is begin return End_Of_File (Current_In); end End_Of_File; ----------------- -- End_Of_Line -- ----------------- function End_Of_Line (File : File_Type) return Boolean is ch : int; begin FIO.Check_Read_Status (AP (File)); if File.Before_Upper_Half_Character then return False; elsif File.Before_LM then return True; else ch := Getc (File); if ch = EOF then return True; else Ungetc (ch, File); return (ch = LM); end if; end if; end End_Of_Line; function End_Of_Line return Boolean is begin return End_Of_Line (Current_In); end End_Of_Line; ----------------- -- End_Of_Page -- ----------------- function End_Of_Page (File : File_Type) return Boolean is ch : int; begin FIO.Check_Read_Status (AP (File)); if not File.Is_Regular_File then return False; elsif File.Before_Upper_Half_Character then return False; elsif File.Before_LM then if File.Before_LM_PM then return True; end if; else ch := Getc (File); if ch = EOF then return True; elsif ch /= LM then Ungetc (ch, File); return False; else -- ch = LM File.Before_LM := True; end if; end if; -- Here we are just past the line mark with Before_LM set so that we -- do not have to try to back up past the LM, thus avoiding the need -- to back up more than one character. ch := Nextc (File); return ch = PM or else ch = EOF; end End_Of_Page; function End_Of_Page return Boolean is begin return End_Of_Page (Current_In); end End_Of_Page; -------------- -- EOF_Char -- -------------- function EOF_Char return Integer is begin return EOF; end EOF_Char; ----------- -- Flush -- ----------- procedure Flush (File : File_Type) is begin FIO.Flush (AP (File)); end Flush; procedure Flush is begin Flush (Current_Out); end Flush; ---------- -- Form -- ---------- function Form (File : File_Type) return String is begin return FIO.Form (AP (File)); end Form; --------- -- Get -- --------- procedure Get (File : File_Type; Item : out Character) is ch : int; begin FIO.Check_Read_Status (AP (File)); if File.Before_Upper_Half_Character then File.Before_Upper_Half_Character := False; Item := File.Saved_Upper_Half_Character; elsif File.Before_LM then File.Before_LM := False; File.Col := 1; if File.Before_LM_PM then File.Line := 1; File.Page := File.Page + 1; File.Before_LM_PM := False; else File.Line := File.Line + 1; end if; end if; loop ch := Getc (File); if ch = EOF then raise End_Error; elsif ch = LM then File.Line := File.Line + 1; File.Col := 1; elsif ch = PM and then File.Is_Regular_File then File.Page := File.Page + 1; File.Line := 1; else Item := Character'Val (ch); File.Col := File.Col + 1; return; end if; end loop; end Get; procedure Get (Item : out Character) is begin Get (Current_In, Item); end Get; procedure Get (File : File_Type; Item : out String) is ch : int; J : Natural; begin FIO.Check_Read_Status (AP (File)); if File.Before_LM then File.Before_LM := False; File.Before_LM_PM := False; File.Col := 1; if File.Before_LM_PM then File.Line := 1; File.Page := File.Page + 1; File.Before_LM_PM := False; else File.Line := File.Line + 1; end if; end if; J := Item'First; while J <= Item'Last loop ch := Getc (File); if ch = EOF then raise End_Error; elsif ch = LM then File.Line := File.Line + 1; File.Col := 1; elsif ch = PM and then File.Is_Regular_File then File.Page := File.Page + 1; File.Line := 1; else Item (J) := Character'Val (ch); J := J + 1; File.Col := File.Col + 1; end if; end loop; end Get; procedure Get (Item : out String) is begin Get (Current_In, Item); end Get; ------------------- -- Get_Immediate -- ------------------- procedure Get_Immediate (File : File_Type; Item : out Character) is ch : int; begin FIO.Check_Read_Status (AP (File)); if File.Before_Upper_Half_Character then File.Before_Upper_Half_Character := False; Item := File.Saved_Upper_Half_Character; elsif File.Before_LM then File.Before_LM := False; File.Before_LM_PM := False; Item := Character'Val (LM); else ch := Getc_Immed (File); if ch = EOF then raise End_Error; else Item := (if not Is_Start_Of_Encoding (Character'Val (ch), File.WC_Method) then Character'Val (ch) else Get_Upper_Half_Char_Immed (Character'Val (ch), File)); end if; end if; end Get_Immediate; procedure Get_Immediate (Item : out Character) is begin Get_Immediate (Current_In, Item); end Get_Immediate; procedure Get_Immediate (File : File_Type; Item : out Character; Available : out Boolean) is ch : int; end_of_file : int; avail : int; procedure getc_immediate_nowait (stream : FILEs; ch : out int; end_of_file : out int; avail : out int); pragma Import (C, getc_immediate_nowait, "getc_immediate_nowait"); begin FIO.Check_Read_Status (AP (File)); Available := True; if File.Before_Upper_Half_Character then File.Before_Upper_Half_Character := False; Item := File.Saved_Upper_Half_Character; elsif File.Before_LM then File.Before_LM := False; File.Before_LM_PM := False; Item := Character'Val (LM); else getc_immediate_nowait (File.Stream, ch, end_of_file, avail); if ferror (File.Stream) /= 0 then raise Device_Error; elsif end_of_file /= 0 then raise End_Error; elsif avail = 0 then Available := False; Item := ASCII.NUL; else Available := True; Item := (if not Is_Start_Of_Encoding (Character'Val (ch), File.WC_Method) then Character'Val (ch) else Get_Upper_Half_Char_Immed (Character'Val (ch), File)); end if; end if; end Get_Immediate; procedure Get_Immediate (Item : out Character; Available : out Boolean) is begin Get_Immediate (Current_In, Item, Available); end Get_Immediate; -------------- -- Get_Line -- -------------- procedure Get_Line (File : File_Type; Item : out String; Last : out Natural) is separate; -- The implementation of Ada.Text_IO.Get_Line is split into a subunit so -- that different implementations can be used on different systems. procedure Get_Line (Item : out String; Last : out Natural) is begin Get_Line (Current_In, Item, Last); end Get_Line; function Get_Line (File : File_Type) return String is function Get_Rest (S : String) return String; -- This is a recursive function that reads the rest of the line and -- returns it. S is the part read so far. -------------- -- Get_Rest -- -------------- function Get_Rest (S : String) return String is -- The first time we allocate a buffer of size 500. Each following -- time we allocate a buffer the same size as what we have read so -- far. This limits us to a logarithmic number of calls to Get_Rest -- and also ensures only a linear use of stack space. Buffer : String (1 .. Integer'Max (500, S'Length)); Last : Natural; begin Get_Line (File, Buffer, Last); declare R : constant String := S & Buffer (1 .. Last); begin if Last < Buffer'Last then return R; else pragma Assert (Last = Buffer'Last); -- If the String has the same length as the buffer, and there -- is no end of line, check whether we are at the end of file, -- in which case we have the full String in the buffer. if End_Of_File (File) then return R; else return Get_Rest (R); end if; end if; end; end Get_Rest; -- Start of processing for Get_Line begin return Get_Rest (""); end Get_Line; function Get_Line return String is begin return Get_Line (Current_In); end Get_Line; ------------------------- -- Get_Upper_Half_Char -- ------------------------- function Get_Upper_Half_Char (C : Character; File : File_Type) return Character is Result : Wide_Character; function In_Char return Character; -- Function used to obtain additional characters it the wide character -- sequence is more than one character long. function WC_In is new Char_Sequence_To_Wide_Char (In_Char); ------------- -- In_Char -- ------------- function In_Char return Character is ch : constant Integer := Getc (File); begin if ch = EOF then raise End_Error; else return Character'Val (ch); end if; end In_Char; -- Start of processing for Get_Upper_Half_Char begin Result := WC_In (C, File.WC_Method); if Wide_Character'Pos (Result) > 16#FF# then raise Constraint_Error with "invalid wide character in Text_'I'O input"; else return Character'Val (Wide_Character'Pos (Result)); end if; end Get_Upper_Half_Char; ------------------------------- -- Get_Upper_Half_Char_Immed -- ------------------------------- function Get_Upper_Half_Char_Immed (C : Character; File : File_Type) return Character is Result : Wide_Character; function In_Char return Character; -- Function used to obtain additional characters it the wide character -- sequence is more than one character long. function WC_In is new Char_Sequence_To_Wide_Char (In_Char); ------------- -- In_Char -- ------------- function In_Char return Character is ch : constant Integer := Getc_Immed (File); begin if ch = EOF then raise End_Error; else return Character'Val (ch); end if; end In_Char; -- Start of processing for Get_Upper_Half_Char_Immed begin Result := WC_In (C, File.WC_Method); if Wide_Character'Pos (Result) > 16#FF# then raise Constraint_Error with "invalid wide character in Text_'I'O input"; else return Character'Val (Wide_Character'Pos (Result)); end if; end Get_Upper_Half_Char_Immed; ---------- -- Getc -- ---------- function Getc (File : File_Type) return int is ch : int; begin ch := fgetc (File.Stream); if ch = EOF and then ferror (File.Stream) /= 0 then raise Device_Error; else return ch; end if; end Getc; ---------------- -- Getc_Immed -- ---------------- function Getc_Immed (File : File_Type) return int is ch : int; end_of_file : int; procedure getc_immediate (stream : FILEs; ch : out int; end_of_file : out int); pragma Import (C, getc_immediate, "getc_immediate"); begin FIO.Check_Read_Status (AP (File)); if File.Before_LM then File.Before_LM := False; File.Before_LM_PM := False; ch := LM; else getc_immediate (File.Stream, ch, end_of_file); if ferror (File.Stream) /= 0 then raise Device_Error; elsif end_of_file /= 0 then return EOF; end if; end if; return ch; end Getc_Immed; ------------------------------ -- Has_Upper_Half_Character -- ------------------------------ function Has_Upper_Half_Character (Item : String) return Boolean is begin for J in Item'Range loop if Character'Pos (Item (J)) >= 16#80# then return True; end if; end loop; return False; end Has_Upper_Half_Character; ------------------------------- -- Initialize_Standard_Files -- ------------------------------- procedure Initialize_Standard_Files is begin Standard_Err.Stream := stderr; Standard_Err.Name := Err_Name'Access; Standard_Err.Form := Null_Str'Unrestricted_Access; Standard_Err.Mode := FCB.Out_File; Standard_Err.Is_Regular_File := is_regular_file (fileno (stderr)) /= 0; Standard_Err.Is_Temporary_File := False; Standard_Err.Is_System_File := True; Standard_Err.Text_Encoding := Default_Text; Standard_Err.Access_Method := 'T'; Standard_Err.Self := Standard_Err; Standard_Err.WC_Method := Default_WCEM; Standard_In.Stream := stdin; Standard_In.Name := In_Name'Access; Standard_In.Form := Null_Str'Unrestricted_Access; Standard_In.Mode := FCB.In_File; Standard_In.Is_Regular_File := is_regular_file (fileno (stdin)) /= 0; Standard_In.Is_Temporary_File := False; Standard_In.Is_System_File := True; Standard_In.Text_Encoding := Default_Text; Standard_In.Access_Method := 'T'; Standard_In.Self := Standard_In; Standard_In.WC_Method := Default_WCEM; Standard_Out.Stream := stdout; Standard_Out.Name := Out_Name'Access; Standard_Out.Form := Null_Str'Unrestricted_Access; Standard_Out.Mode := FCB.Out_File; Standard_Out.Is_Regular_File := is_regular_file (fileno (stdout)) /= 0; Standard_Out.Is_Temporary_File := False; Standard_Out.Is_System_File := True; Standard_Out.Text_Encoding := Default_Text; Standard_Out.Access_Method := 'T'; Standard_Out.Self := Standard_Out; Standard_Out.WC_Method := Default_WCEM; FIO.Make_Unbuffered (AP (Standard_Out)); FIO.Make_Unbuffered (AP (Standard_Err)); end Initialize_Standard_Files; ------------- -- Is_Open -- ------------- function Is_Open (File : File_Type) return Boolean is begin return FIO.Is_Open (AP (File)); end Is_Open; ---------- -- Line -- ---------- -- Note: we assume that it is impossible in practice for the line -- to exceed the value of Count'Last, i.e. no check is required for -- overflow raising layout error. function Line (File : File_Type) return Positive_Count is begin FIO.Check_File_Open (AP (File)); return File.Line; end Line; function Line return Positive_Count is begin return Line (Current_Out); end Line; ----------------- -- Line_Length -- ----------------- function Line_Length (File : File_Type) return Count is begin FIO.Check_Write_Status (AP (File)); return File.Line_Length; end Line_Length; function Line_Length return Count is begin return Line_Length (Current_Out); end Line_Length; ---------------- -- Look_Ahead -- ---------------- procedure Look_Ahead (File : File_Type; Item : out Character; End_Of_Line : out Boolean) is ch : int; begin FIO.Check_Read_Status (AP (File)); -- If we are logically before a line mark, we can return immediately if File.Before_LM then End_Of_Line := True; Item := ASCII.NUL; -- If we are before an upper half character just return it (this can -- happen if there are two calls to Look_Ahead in a row). elsif File.Before_Upper_Half_Character then End_Of_Line := False; Item := File.Saved_Upper_Half_Character; -- Otherwise we must read a character from the input stream else ch := Getc (File); if ch = LM or else ch = EOF or else (ch = PM and then File.Is_Regular_File) then End_Of_Line := True; Ungetc (ch, File); Item := ASCII.NUL; -- Case where character obtained does not represent the start of an -- encoded sequence so it stands for itself and we can unget it with -- no difficulty. elsif not Is_Start_Of_Encoding (Character'Val (ch), File.WC_Method) then End_Of_Line := False; Ungetc (ch, File); Item := Character'Val (ch); -- For the start of an encoding, we read the character using the -- Get_Upper_Half_Char routine. It will occupy more than one byte -- so we can't put it back with ungetc. Instead we save it in the -- control block, setting a flag that everyone interested in reading -- characters must test before reading the stream. else Item := Get_Upper_Half_Char (Character'Val (ch), File); End_Of_Line := False; File.Saved_Upper_Half_Character := Item; File.Before_Upper_Half_Character := True; end if; end if; end Look_Ahead; procedure Look_Ahead (Item : out Character; End_Of_Line : out Boolean) is begin Look_Ahead (Current_In, Item, End_Of_Line); end Look_Ahead; ---------- -- Mode -- ---------- function Mode (File : File_Type) return File_Mode is begin return To_TIO (FIO.Mode (AP (File))); end Mode; ---------- -- Name -- ---------- function Name (File : File_Type) return String is begin return FIO.Name (AP (File)); end Name; -------------- -- New_Line -- -------------- procedure New_Line (File : File_Type; Spacing : Positive_Count := 1) is begin -- Raise Constraint_Error if out of range value. The reason for this -- explicit test is that we don't want junk values around, even if -- checks are off in the caller. if not Spacing'Valid then raise Constraint_Error; end if; FIO.Check_Write_Status (AP (File)); for K in 1 .. Spacing loop Putc (LM, File); File.Line := File.Line + 1; if File.Page_Length /= 0 and then File.Line > File.Page_Length then Putc (PM, File); File.Line := 1; File.Page := File.Page + 1; end if; end loop; File.Col := 1; end New_Line; procedure New_Line (Spacing : Positive_Count := 1) is begin New_Line (Current_Out, Spacing); end New_Line; -------------- -- New_Page -- -------------- procedure New_Page (File : File_Type) is begin FIO.Check_Write_Status (AP (File)); if File.Col /= 1 or else File.Line = 1 then Putc (LM, File); end if; Putc (PM, File); File.Page := File.Page + 1; File.Line := 1; File.Col := 1; end New_Page; procedure New_Page is begin New_Page (Current_Out); end New_Page; ----------- -- Nextc -- ----------- function Nextc (File : File_Type) return int is ch : int; begin ch := fgetc (File.Stream); if ch = EOF then if ferror (File.Stream) /= 0 then raise Device_Error; end if; else if ungetc (ch, File.Stream) = EOF then raise Device_Error; end if; end if; return ch; end Nextc; ---------- -- Open -- ---------- procedure Open (File : in out File_Type; Mode : File_Mode; Name : String; Form : String := "") is Dummy_File_Control_Block : Text_AFCB; pragma Warnings (Off, Dummy_File_Control_Block); -- Yes, we know this is never assigned a value, only the tag -- is used for dispatching purposes, so that's expected. begin FIO.Open (File_Ptr => AP (File), Dummy_FCB => Dummy_File_Control_Block, Mode => To_FCB (Mode), Name => Name, Form => Form, Amethod => 'T', Creat => False, Text => True); File.Self := File; Set_WCEM (File); end Open; ---------- -- Page -- ---------- -- Note: we assume that it is impossible in practice for the page -- to exceed the value of Count'Last, i.e. no check is required for -- overflow raising layout error. function Page (File : File_Type) return Positive_Count is begin FIO.Check_File_Open (AP (File)); return File.Page; end Page; function Page return Positive_Count is begin return Page (Current_Out); end Page; ----------------- -- Page_Length -- ----------------- function Page_Length (File : File_Type) return Count is begin FIO.Check_Write_Status (AP (File)); return File.Page_Length; end Page_Length; function Page_Length return Count is begin return Page_Length (Current_Out); end Page_Length; --------- -- Put -- --------- procedure Put (File : File_Type; Item : Character) is begin FIO.Check_Write_Status (AP (File)); if File.Line_Length /= 0 and then File.Col > File.Line_Length then New_Line (File); end if; -- If lower half character, or brackets encoding, output directly if Character'Pos (Item) < 16#80# or else File.WC_Method = WCEM_Brackets then if fputc (Character'Pos (Item), File.Stream) = EOF then raise Device_Error; end if; -- Case of upper half character with non-brackets encoding else Put_Encoded (File, Item); end if; File.Col := File.Col + 1; end Put; procedure Put (Item : Character) is begin Put (Current_Out, Item); end Put; --------- -- Put -- --------- procedure Put (File : File_Type; Item : String) is begin FIO.Check_Write_Status (AP (File)); -- Only have something to do if string is non-null if Item'Length > 0 then -- If we have bounded lines, or if the file encoding is other than -- Brackets and the string has at least one upper half character, -- then output the string character by character. if File.Line_Length /= 0 or else (File.WC_Method /= WCEM_Brackets and then Has_Upper_Half_Character (Item)) then for J in Item'Range loop Put (File, Item (J)); end loop; -- Otherwise we can output the entire string at once. Note that if -- there are LF or FF characters in the string, we do not bother to -- count them as line or page terminators. else FIO.Write_Buf (AP (File), Item'Address, Item'Length); File.Col := File.Col + Item'Length; end if; end if; end Put; procedure Put (Item : String) is begin Put (Current_Out, Item); end Put; ----------------- -- Put_Encoded -- ----------------- procedure Put_Encoded (File : File_Type; Char : Character) is procedure Out_Char (C : Character); -- Procedure to output one character of an upper half encoded sequence procedure WC_Out is new Wide_Char_To_Char_Sequence (Out_Char); -------------- -- Out_Char -- -------------- procedure Out_Char (C : Character) is begin Putc (Character'Pos (C), File); end Out_Char; -- Start of processing for Put_Encoded begin WC_Out (Wide_Character'Val (Character'Pos (Char)), File.WC_Method); end Put_Encoded; -------------- -- Put_Line -- -------------- procedure Put_Line (File : File_Type; Item : String) is Ilen : Natural := Item'Length; Istart : Natural := Item'First; begin FIO.Check_Write_Status (AP (File)); -- If we have bounded lines, or if the file encoding is other than -- Brackets and the string has at least one upper half character, then -- output the string character by character. if File.Line_Length /= 0 or else (File.WC_Method /= WCEM_Brackets and then Has_Upper_Half_Character (Item)) then for J in Item'Range loop Put (File, Item (J)); end loop; New_Line (File); return; end if; -- Normal case where we do not need to output character by character -- We setup a single string that has the necessary terminators and -- then write it with a single call. The reason for doing this is -- that it gives better behavior for the use of Put_Line in multi- -- tasking programs, since often the OS will treat the entire put -- operation as an atomic operation. -- We only do this if the message is 512 characters or less in length, -- since otherwise Put_Line would use an unbounded amount of stack -- space and could cause undetected stack overflow. If we have a -- longer string, then output the first part separately to avoid this. if Ilen > 512 then FIO.Write_Buf (AP (File), Item'Address, size_t (Ilen - 512)); Istart := Istart + Ilen - 512; Ilen := 512; end if; -- Now prepare the string with its terminator declare Buffer : String (1 .. Ilen + 2); Plen : size_t; begin Buffer (1 .. Ilen) := Item (Istart .. Item'Last); Buffer (Ilen + 1) := Character'Val (LM); if File.Page_Length /= 0 and then File.Line > File.Page_Length then Buffer (Ilen + 2) := Character'Val (PM); Plen := size_t (Ilen) + 2; File.Line := 1; File.Page := File.Page + 1; else Plen := size_t (Ilen) + 1; File.Line := File.Line + 1; end if; FIO.Write_Buf (AP (File), Buffer'Address, Plen); File.Col := 1; end; end Put_Line; procedure Put_Line (Item : String) is begin Put_Line (Current_Out, Item); end Put_Line; ---------- -- Putc -- ---------- procedure Putc (ch : int; File : File_Type) is begin if fputc (ch, File.Stream) = EOF then raise Device_Error; end if; end Putc; ---------- -- Read -- ---------- -- This is the primitive Stream Read routine, used when a Text_IO file -- is treated directly as a stream using Text_IO.Streams.Stream. procedure Read (File : in out Text_AFCB; Item : out Stream_Element_Array; Last : out Stream_Element_Offset) is Discard_ch : int; pragma Warnings (Off, Discard_ch); begin -- Need to deal with Before_Upper_Half_Character ??? if File.Mode /= FCB.In_File then raise Mode_Error; end if; -- Deal with case where our logical and physical position do not match -- because of being after an LM or LM-PM sequence when in fact we are -- logically positioned before it. if File.Before_LM then -- If we are before a PM, then it is possible for a stream read -- to leave us after the LM and before the PM, which is a bit -- odd. The easiest way to deal with this is to unget the PM, -- so we are indeed positioned between the characters. This way -- further stream read operations will work correctly, and the -- effect on text processing is a little weird, but what can -- be expected if stream and text input are mixed this way? if File.Before_LM_PM then Discard_ch := ungetc (PM, File.Stream); File.Before_LM_PM := False; end if; File.Before_LM := False; Item (Item'First) := Stream_Element (Character'Pos (ASCII.LF)); if Item'Length = 1 then Last := Item'Last; else Last := Item'First + Stream_Element_Offset (fread (buffer => Item'Address, index => size_t (Item'First + 1), size => 1, count => Item'Length - 1, stream => File.Stream)); end if; return; end if; -- Now we do the read. Since this is a text file, it is normally in -- text mode, but stream data must be read in binary mode, so we -- temporarily set binary mode for the read, resetting it after. -- These calls have no effect in a system (like Unix) where there is -- no distinction between text and binary files. set_binary_mode (fileno (File.Stream)); Last := Item'First + Stream_Element_Offset (fread (Item'Address, 1, Item'Length, File.Stream)) - 1; if Last < Item'Last then if ferror (File.Stream) /= 0 then raise Device_Error; end if; end if; set_text_mode (fileno (File.Stream)); end Read; ----------- -- Reset -- ----------- procedure Reset (File : in out File_Type; Mode : File_Mode) is begin -- Don't allow change of mode for current file (RM A.10.2(5)) if (File = Current_In or else File = Current_Out or else File = Current_Error) and then To_FCB (Mode) /= File.Mode then raise Mode_Error; end if; Terminate_Line (File); FIO.Reset (AP (File)'Unrestricted_Access, To_FCB (Mode)); File.Page := 1; File.Line := 1; File.Col := 1; File.Line_Length := 0; File.Page_Length := 0; File.Before_LM := False; File.Before_LM_PM := False; end Reset; procedure Reset (File : in out File_Type) is begin Terminate_Line (File); FIO.Reset (AP (File)'Unrestricted_Access); File.Page := 1; File.Line := 1; File.Col := 1; File.Line_Length := 0; File.Page_Length := 0; File.Before_LM := False; File.Before_LM_PM := False; end Reset; ------------- -- Set_Col -- ------------- procedure Set_Col (File : File_Type; To : Positive_Count) is ch : int; begin -- Raise Constraint_Error if out of range value. The reason for this -- explicit test is that we don't want junk values around, even if -- checks are off in the caller. if not To'Valid then raise Constraint_Error; end if; FIO.Check_File_Open (AP (File)); -- Output case if Mode (File) >= Out_File then -- Error if we attempt to set Col to a value greater than the -- maximum permissible line length. if File.Line_Length /= 0 and then To > File.Line_Length then raise Layout_Error; end if; -- If we are behind current position, then go to start of new line if To < File.Col then New_Line (File); end if; -- Loop to output blanks till we are at the required column while File.Col < To loop Put (File, ' '); end loop; -- Input case else -- If we are logically before a LM, but physically after it, the -- file position still reflects the position before the LM, so eat -- it now and adjust the file position appropriately. if File.Before_LM then File.Before_LM := False; File.Before_LM_PM := False; File.Line := File.Line + 1; File.Col := 1; end if; -- Loop reading characters till we get one at the required Col value loop -- Read next character. The reason we have to read ahead is to -- skip formatting characters, the effect of Set_Col is to set -- us to a real character with the right Col value, and format -- characters don't count. ch := Getc (File); -- Error if we hit an end of file if ch = EOF then raise End_Error; -- If line mark, eat it and adjust file position elsif ch = LM then File.Line := File.Line + 1; File.Col := 1; -- If recognized page mark, eat it, and adjust file position elsif ch = PM and then File.Is_Regular_File then File.Page := File.Page + 1; File.Line := 1; File.Col := 1; -- Otherwise this is the character we are looking for, so put it -- back in the input stream (we have not adjusted the file -- position yet, so everything is set right after this ungetc). elsif To = File.Col then Ungetc (ch, File); return; -- Keep skipping characters if we are not there yet, updating the -- file position past the skipped character. else File.Col := File.Col + 1; end if; end loop; end if; end Set_Col; procedure Set_Col (To : Positive_Count) is begin Set_Col (Current_Out, To); end Set_Col; --------------- -- Set_Error -- --------------- procedure Set_Error (File : File_Type) is begin FIO.Check_Write_Status (AP (File)); Current_Err := File; end Set_Error; --------------- -- Set_Input -- --------------- procedure Set_Input (File : File_Type) is begin FIO.Check_Read_Status (AP (File)); Current_In := File; end Set_Input; -------------- -- Set_Line -- -------------- procedure Set_Line (File : File_Type; To : Positive_Count) is begin -- Raise Constraint_Error if out of range value. The reason for this -- explicit test is that we don't want junk values around, even if -- checks are off in the caller. if not To'Valid then raise Constraint_Error; end if; FIO.Check_File_Open (AP (File)); if To = File.Line then return; end if; if Mode (File) >= Out_File then if File.Page_Length /= 0 and then To > File.Page_Length then raise Layout_Error; end if; if To < File.Line then New_Page (File); end if; while File.Line < To loop New_Line (File); end loop; else while To /= File.Line loop Skip_Line (File); end loop; end if; end Set_Line; procedure Set_Line (To : Positive_Count) is begin Set_Line (Current_Out, To); end Set_Line; --------------------- -- Set_Line_Length -- --------------------- procedure Set_Line_Length (File : File_Type; To : Count) is begin -- Raise Constraint_Error if out of range value. The reason for this -- explicit test is that we don't want junk values around, even if -- checks are off in the caller. if not To'Valid then raise Constraint_Error; end if; FIO.Check_Write_Status (AP (File)); File.Line_Length := To; end Set_Line_Length; procedure Set_Line_Length (To : Count) is begin Set_Line_Length (Current_Out, To); end Set_Line_Length; ---------------- -- Set_Output -- ---------------- procedure Set_Output (File : File_Type) is begin FIO.Check_Write_Status (AP (File)); Current_Out := File; end Set_Output; --------------------- -- Set_Page_Length -- --------------------- procedure Set_Page_Length (File : File_Type; To : Count) is begin -- Raise Constraint_Error if out of range value. The reason for this -- explicit test is that we don't want junk values around, even if -- checks are off in the caller. if not To'Valid then raise Constraint_Error; end if; FIO.Check_Write_Status (AP (File)); File.Page_Length := To; end Set_Page_Length; procedure Set_Page_Length (To : Count) is begin Set_Page_Length (Current_Out, To); end Set_Page_Length; -------------- -- Set_WCEM -- -------------- procedure Set_WCEM (File : in out File_Type) is Start : Natural; Stop : Natural; begin File.WC_Method := WCEM_Brackets; FIO.Form_Parameter (File.Form.all, "wcem", Start, Stop); if Start = 0 then File.WC_Method := WCEM_Brackets; else if Stop = Start then for J in WC_Encoding_Letters'Range loop if File.Form (Start) = WC_Encoding_Letters (J) then File.WC_Method := J; return; end if; end loop; end if; Close (File); raise Use_Error with "invalid WCEM form parameter"; end if; end Set_WCEM; --------------- -- Skip_Line -- --------------- procedure Skip_Line (File : File_Type; Spacing : Positive_Count := 1) is ch : int; begin -- Raise Constraint_Error if out of range value. The reason for this -- explicit test is that we don't want junk values around, even if -- checks are off in the caller. if not Spacing'Valid then raise Constraint_Error; end if; FIO.Check_Read_Status (AP (File)); for L in 1 .. Spacing loop if File.Before_LM then File.Before_LM := False; -- Note that if File.Before_LM_PM is currently set, we also have -- to reset it (because it makes sense for Before_LM_PM to be set -- only when Before_LM is also set). This is done later on in this -- subprogram, as soon as Before_LM_PM has been taken into account -- for the purpose of page and line counts. else ch := Getc (File); -- If at end of file now, then immediately raise End_Error. Note -- that we can never be positioned between a line mark and a page -- mark, so if we are at the end of file, we cannot logically be -- before the implicit page mark that is at the end of the file. -- For the same reason, we do not need an explicit check for a -- page mark. If there is a FF in the middle of a line, the file -- is not in canonical format and we do not care about the page -- numbers for files other than ones in canonical format. if ch = EOF then raise End_Error; end if; -- If not at end of file, then loop till we get to an LM or EOF. -- The latter case happens only in non-canonical files where the -- last line is not terminated by LM, but we don't want to blow -- up for such files, so we assume an implicit LM in this case. loop exit when ch = LM or else ch = EOF; ch := Getc (File); end loop; end if; -- We have got past a line mark, now, for a regular file only, -- see if a page mark immediately follows this line mark and -- if so, skip past the page mark as well. We do not do this -- for non-regular files, since it would cause an undesirable -- wait for an additional character. File.Col := 1; File.Line := File.Line + 1; if File.Before_LM_PM then File.Page := File.Page + 1; File.Line := 1; File.Before_LM_PM := False; elsif File.Is_Regular_File then ch := Getc (File); -- Page mark can be explicit, or implied at the end of the file if (ch = PM or else ch = EOF) and then File.Is_Regular_File then File.Page := File.Page + 1; File.Line := 1; else Ungetc (ch, File); end if; end if; end loop; File.Before_Upper_Half_Character := False; end Skip_Line; procedure Skip_Line (Spacing : Positive_Count := 1) is begin Skip_Line (Current_In, Spacing); end Skip_Line; --------------- -- Skip_Page -- --------------- procedure Skip_Page (File : File_Type) is ch : int; begin FIO.Check_Read_Status (AP (File)); -- If at page mark already, just skip it if File.Before_LM_PM then File.Before_LM := False; File.Before_LM_PM := False; File.Page := File.Page + 1; File.Line := 1; File.Col := 1; return; end if; -- This is a bit tricky, if we are logically before an LM then -- it is not an error if we are at an end of file now, since we -- are not really at it. if File.Before_LM then File.Before_LM := False; File.Before_LM_PM := False; ch := Getc (File); -- Otherwise we do raise End_Error if we are at the end of file now else ch := Getc (File); if ch = EOF then raise End_Error; end if; end if; -- Now we can just rumble along to the next page mark, or to the -- end of file, if that comes first. The latter case happens when -- the page mark is implied at the end of file. loop exit when ch = EOF or else (ch = PM and then File.Is_Regular_File); ch := Getc (File); end loop; File.Page := File.Page + 1; File.Line := 1; File.Col := 1; File.Before_Upper_Half_Character := False; end Skip_Page; procedure Skip_Page is begin Skip_Page (Current_In); end Skip_Page; -------------------- -- Standard_Error -- -------------------- function Standard_Error return File_Type is begin return Standard_Err; end Standard_Error; function Standard_Error return File_Access is begin return Standard_Err'Access; end Standard_Error; -------------------- -- Standard_Input -- -------------------- function Standard_Input return File_Type is begin return Standard_In; end Standard_Input; function Standard_Input return File_Access is begin return Standard_In'Access; end Standard_Input; --------------------- -- Standard_Output -- --------------------- function Standard_Output return File_Type is begin return Standard_Out; end Standard_Output; function Standard_Output return File_Access is begin return Standard_Out'Access; end Standard_Output; -------------------- -- Terminate_Line -- -------------------- procedure Terminate_Line (File : File_Type) is begin FIO.Check_File_Open (AP (File)); -- For file other than In_File, test for needing to terminate last line if Mode (File) /= In_File then -- If not at start of line definition need new line if File.Col /= 1 then New_Line (File); -- For files other than standard error and standard output, we -- make sure that an empty file has a single line feed, so that -- it is properly formatted. We avoid this for the standard files -- because it is too much of a nuisance to have these odd line -- feeds when nothing has been written to the file. -- We also avoid this for files opened in append mode, in -- accordance with (RM A.8.2(10)) elsif (File /= Standard_Err and then File /= Standard_Out) and then (File.Line = 1 and then File.Page = 1) and then Mode (File) = Out_File then New_Line (File); end if; end if; end Terminate_Line; ------------ -- Ungetc -- ------------ procedure Ungetc (ch : int; File : File_Type) is begin if ch /= EOF then if ungetc (ch, File.Stream) = EOF then raise Device_Error; end if; end if; end Ungetc; ----------- -- Write -- ----------- -- This is the primitive Stream Write routine, used when a Text_IO file -- is treated directly as a stream using Text_IO.Streams.Stream. procedure Write (File : in out Text_AFCB; Item : Stream_Element_Array) is pragma Warnings (Off, File); -- Because in this implementation we don't need IN OUT, we only read function Has_Translated_Characters return Boolean; -- return True if Item array contains a character which will be -- translated under the text file mode. There is only one such -- character under DOS based systems which is character 10. text_translation_required : Boolean; for text_translation_required'Size use Character'Size; pragma Import (C, text_translation_required, "__gnat_text_translation_required"); Siz : constant size_t := Item'Length; ------------------------------- -- Has_Translated_Characters -- ------------------------------- function Has_Translated_Characters return Boolean is begin for K in Item'Range loop if Item (K) = 10 then return True; end if; end loop; return False; end Has_Translated_Characters; Needs_Binary_Write : constant Boolean := text_translation_required and then Has_Translated_Characters; -- Start of processing for Write begin if File.Mode = FCB.In_File then raise Mode_Error; end if; -- Now we do the write. Since this is a text file, it is normally in -- text mode, but stream data must be written in binary mode, so we -- temporarily set binary mode for the write, resetting it after. This -- is done only if needed (i.e. there is some characters in Item which -- needs to be written using the binary mode). -- These calls have no effect in a system (like Unix) where there is -- no distinction between text and binary files. -- Since the character translation is done at the time the buffer is -- written (this is true under Windows) we first flush current buffer -- with text mode if needed. if Needs_Binary_Write then if fflush (File.Stream) = -1 then raise Device_Error; end if; set_binary_mode (fileno (File.Stream)); end if; if fwrite (Item'Address, 1, Siz, File.Stream) /= Siz then raise Device_Error; end if; -- At this point we need to flush the buffer using the binary mode then -- we reset to text mode. if Needs_Binary_Write then if fflush (File.Stream) = -1 then raise Device_Error; end if; set_text_mode (fileno (File.Stream)); end if; end Write; begin -- Initialize Standard Files for J in WC_Encoding_Method loop if WC_Encoding = WC_Encoding_Letters (J) then Default_WCEM := J; end if; end loop; Initialize_Standard_Files; FIO.Chain_File (AP (Standard_In)); FIO.Chain_File (AP (Standard_Out)); FIO.Chain_File (AP (Standard_Err)); end Ada.Text_IO;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- P R E P C O M P -- -- -- -- B o d y -- -- -- -- Copyright (C) 2003-2020, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. 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 Errout; use Errout; with Lib.Writ; use Lib.Writ; with Opt; use Opt; with Osint; use Osint; with Prep; use Prep; with Scans; use Scans; with Scn; use Scn; with Sinput.L; use Sinput.L; with Stringt; use Stringt; with Table; package body Prepcomp is No_Preprocessing : Boolean := True; -- Set to False if there is at least one source that needs to be -- preprocessed. Source_Index_Of_Preproc_Data_File : Source_File_Index := No_Source_File; -- The following variable should be a constant, but this is not possible -- because its type GNAT.Dynamic_Tables.Instance has a component P of -- uninitialized private type GNAT.Dynamic_Tables.Table_Private and there -- are no exported values for this private type. Warnings are Off because -- it is never assigned a value. pragma Warnings (Off); No_Mapping : Prep.Symbol_Table.Instance; pragma Warnings (On); type Preproc_Data is record Mapping : Symbol_Table.Instance; File_Name : File_Name_Type := No_File; Deffile : String_Id := No_String; Undef_False : Boolean := False; Always_Blank : Boolean := False; Comments : Boolean := False; No_Deletion : Boolean := False; List_Symbols : Boolean := False; Processed : Boolean := False; end record; -- Structure to keep the preprocessing data for a file name or for the -- default (when Name_Id = No_Name). No_Preproc_Data : constant Preproc_Data := (Mapping => No_Mapping, File_Name => No_File, Deffile => No_String, Undef_False => False, Always_Blank => False, Comments => False, No_Deletion => False, List_Symbols => False, Processed => False); Default_Data : Preproc_Data := No_Preproc_Data; -- The preprocessing data to be used when no specific preprocessing data -- is specified for a source. Default_Data_Defined : Boolean := False; -- True if source for which no specific preprocessing is specified need to -- be preprocess with the Default_Data. Current_Data : Preproc_Data := No_Preproc_Data; package Preproc_Data_Table is new Table.Table (Table_Component_Type => Preproc_Data, Table_Index_Type => Int, Table_Low_Bound => 1, Table_Initial => 5, Table_Increment => 100, Table_Name => "Prepcomp.Preproc_Data_Table"); -- Table to store the specific preprocessing data Command_Line_Symbols : Symbol_Table.Instance; -- A table to store symbol definitions specified on the command line with -- -gnateD switches. package Dependencies is new Table.Table (Table_Component_Type => Source_File_Index, Table_Index_Type => Int, Table_Low_Bound => 1, Table_Initial => 10, Table_Increment => 100, Table_Name => "Prepcomp.Dependencies"); -- Table to store the dependencies on preprocessing files procedure Add_Command_Line_Symbols; -- Add the command line symbol definitions, if any, to Prep.Mapping table procedure Skip_To_End_Of_Line; -- Ignore errors and scan up to the next end of line or the end of file ------------------------------ -- Add_Command_Line_Symbols -- ------------------------------ procedure Add_Command_Line_Symbols is Symbol_Id : Prep.Symbol_Id; begin for J in 1 .. Symbol_Table.Last (Command_Line_Symbols) loop Symbol_Id := Prep.Index_Of (Command_Line_Symbols.Table (J).Symbol); if Symbol_Id = No_Symbol then Symbol_Table.Increment_Last (Prep.Mapping); Symbol_Id := Symbol_Table.Last (Prep.Mapping); end if; Prep.Mapping.Table (Symbol_Id) := Command_Line_Symbols.Table (J); end loop; end Add_Command_Line_Symbols; -------------------- -- Add_Dependency -- -------------------- procedure Add_Dependency (S : Source_File_Index) is begin Dependencies.Increment_Last; Dependencies.Table (Dependencies.Last) := S; end Add_Dependency; ---------------------- -- Add_Dependencies -- ---------------------- procedure Add_Dependencies is begin for Index in 1 .. Dependencies.Last loop Add_Preprocessing_Dependency (Dependencies.Table (Index)); end loop; end Add_Dependencies; ------------------- -- Check_Symbols -- ------------------- procedure Check_Symbols is begin -- If there is at least one switch -gnateD specified if Symbol_Table.Last (Command_Line_Symbols) >= 1 then Current_Data := No_Preproc_Data; No_Preprocessing := False; Current_Data.Processed := True; -- Start with an empty, initialized mapping table; use Prep.Mapping, -- because Prep.Index_Of uses Prep.Mapping. Prep.Mapping := No_Mapping; Symbol_Table.Init (Prep.Mapping); -- Add the command line symbols Add_Command_Line_Symbols; -- Put the resulting Prep.Mapping in Current_Data, and immediately -- set Prep.Mapping to nil. Current_Data.Mapping := Prep.Mapping; Prep.Mapping := No_Mapping; -- Set the default data Default_Data := Current_Data; Default_Data_Defined := True; end if; end Check_Symbols; ----------------------------------- -- Parse_Preprocessing_Data_File -- ----------------------------------- procedure Parse_Preprocessing_Data_File (N : File_Name_Type) is OK : Boolean := False; Dash_Location : Source_Ptr; Symbol_Data : Prep.Symbol_Data; Symbol_Id : Prep.Symbol_Id; T : constant Nat := Total_Errors_Detected; begin -- Load the preprocessing data file Source_Index_Of_Preproc_Data_File := Load_Preprocessing_Data_File (N); -- Fail if preprocessing data file cannot be found if Source_Index_Of_Preproc_Data_File = No_Source_File then Get_Name_String (N); Fail ("preprocessing data file """ & Name_Buffer (1 .. Name_Len) & """ not found"); end if; -- Initialize scanner and set its behavior for processing a data file Scn.Scanner.Initialize_Scanner (Source_Index_Of_Preproc_Data_File); Scn.Scanner.Set_End_Of_Line_As_Token (True); Scn.Scanner.Reset_Special_Characters; For_Each_Line : loop <<Scan_Line>> Scan; exit For_Each_Line when Token = Tok_EOF; if Token = Tok_End_Of_Line then goto Scan_Line; end if; -- Line is not empty OK := False; No_Preprocessing := False; Current_Data := No_Preproc_Data; case Token is when Tok_Asterisk => -- Default data if Default_Data_Defined then Error_Msg ("multiple default preprocessing data", Token_Ptr); else OK := True; Default_Data_Defined := True; end if; when Tok_String_Literal => -- Specific data String_To_Name_Buffer (String_Literal_Id); Canonical_Case_File_Name (Name_Buffer (1 .. Name_Len)); Current_Data.File_Name := Name_Find; OK := True; for Index in 1 .. Preproc_Data_Table.Last loop if Current_Data.File_Name = Preproc_Data_Table.Table (Index).File_Name then Error_Msg_File_1 := Current_Data.File_Name; Error_Msg ("multiple preprocessing data for{", Token_Ptr); OK := False; exit; end if; end loop; when others => Error_Msg ("`'*` or literal string expected", Token_Ptr); end case; -- If there is a problem, skip the line if not OK then Skip_To_End_Of_Line; goto Scan_Line; end if; -- Scan past the * or the literal string Scan; -- A literal string in second position is a definition file if Token = Tok_String_Literal then Current_Data.Deffile := String_Literal_Id; Current_Data.Processed := False; Scan; else -- If there is no definition file, set Processed to True now Current_Data.Processed := True; end if; -- Start with an empty, initialized mapping table; use Prep.Mapping, -- because Prep.Index_Of uses Prep.Mapping. Prep.Mapping := No_Mapping; Symbol_Table.Init (Prep.Mapping); -- Check the switches that may follow while Token /= Tok_End_Of_Line and then Token /= Tok_EOF loop if Token /= Tok_Minus then Error_Msg -- CODEFIX ("`'-` expected", Token_Ptr); Skip_To_End_Of_Line; goto Scan_Line; end if; -- Keep the location of the '-' for possible error reporting Dash_Location := Token_Ptr; -- Scan past the '-' Scan; OK := False; Change_Reserved_Keyword_To_Symbol; -- An identifier (or a reserved word converted to an -- identifier) is expected and there must be no blank space -- between the '-' and the identifier. if Token = Tok_Identifier and then Token_Ptr = Dash_Location + 1 then Get_Name_String (Token_Name); -- Check the character in the source, because the case is -- significant. case Sinput.Source (Token_Ptr) is when 'a' => -- All source text preserved (also implies -u) if Name_Len = 1 then Current_Data.No_Deletion := True; Current_Data.Undef_False := True; OK := True; end if; when 'u' => -- Undefined symbol are False if Name_Len = 1 then Current_Data.Undef_False := True; OK := True; end if; when 'b' => -- Blank lines if Name_Len = 1 then Current_Data.Always_Blank := True; OK := True; end if; when 'c' => -- Comment removed lines if Name_Len = 1 then Current_Data.Comments := True; OK := True; end if; when 's' => -- List symbols if Name_Len = 1 then Current_Data.List_Symbols := True; OK := True; end if; when 'D' => -- Symbol definition OK := Name_Len > 1; if OK then -- A symbol must be an Ada identifier; it cannot start -- with an underline or a digit. if Name_Buffer (2) = '_' or else Name_Buffer (2) in '0' .. '9' then Error_Msg ("symbol expected", Token_Ptr + 1); Skip_To_End_Of_Line; goto Scan_Line; end if; -- Get the name id of the symbol Symbol_Data.On_The_Command_Line := True; Name_Buffer (1 .. Name_Len - 1) := Name_Buffer (2 .. Name_Len); Name_Len := Name_Len - 1; Symbol_Data.Symbol := Name_Find; if Name_Buffer (1 .. Name_Len) = "if" or else Name_Buffer (1 .. Name_Len) = "else" or else Name_Buffer (1 .. Name_Len) = "elsif" or else Name_Buffer (1 .. Name_Len) = "end" or else Name_Buffer (1 .. Name_Len) = "not" or else Name_Buffer (1 .. Name_Len) = "and" or else Name_Buffer (1 .. Name_Len) = "then" then Error_Msg ("symbol expected", Token_Ptr + 1); Skip_To_End_Of_Line; goto Scan_Line; end if; -- Get the name id of the original symbol, with -- possibly capital letters. Name_Len := Integer (Scan_Ptr - Token_Ptr - 1); for J in 1 .. Name_Len loop Name_Buffer (J) := Sinput.Source (Token_Ptr + Text_Ptr (J)); end loop; Symbol_Data.Original := Name_Find; -- Scan past D<symbol> Scan; if Token /= Tok_Equal then Error_Msg -- CODEFIX ("`=` expected", Token_Ptr); Skip_To_End_Of_Line; goto Scan_Line; end if; -- Scan past '=' Scan; -- Here any reserved word is OK Change_Reserved_Keyword_To_Symbol (All_Keywords => True); -- Value can be an identifier (or a reserved word) -- or a literal string. case Token is when Tok_String_Literal => Symbol_Data.Is_A_String := True; Symbol_Data.Value := String_Literal_Id; when Tok_Identifier => Symbol_Data.Is_A_String := False; Start_String; for J in Token_Ptr .. Scan_Ptr - 1 loop Store_String_Char (Sinput.Source (J)); end loop; Symbol_Data.Value := End_String; when others => Error_Msg ("literal string or identifier expected", Token_Ptr); Skip_To_End_Of_Line; goto Scan_Line; end case; -- If symbol already exists, replace old definition -- by new one. Symbol_Id := Prep.Index_Of (Symbol_Data.Symbol); -- Otherwise, add a new entry in the table if Symbol_Id = No_Symbol then Symbol_Table.Increment_Last (Prep.Mapping); Symbol_Id := Symbol_Table.Last (Mapping); end if; Prep.Mapping.Table (Symbol_Id) := Symbol_Data; end if; when others => null; end case; Scan; end if; if not OK then Error_Msg ("invalid switch", Dash_Location); Skip_To_End_Of_Line; goto Scan_Line; end if; end loop; -- Add the command line symbols, if any, possibly replacing symbols -- just defined. Add_Command_Line_Symbols; -- Put the resulting Prep.Mapping in Current_Data, and immediately -- set Prep.Mapping to nil. Current_Data.Mapping := Prep.Mapping; Prep.Mapping := No_Mapping; -- Record Current_Data if Current_Data.File_Name = No_File then Default_Data := Current_Data; else Preproc_Data_Table.Increment_Last; Preproc_Data_Table.Table (Preproc_Data_Table.Last) := Current_Data; end if; Current_Data := No_Preproc_Data; end loop For_Each_Line; Scn.Scanner.Set_End_Of_Line_As_Token (False); -- Fail if there were errors in the preprocessing data file if Total_Errors_Detected > T then Errout.Finalize (Last_Call => True); Errout.Output_Messages; Fail ("errors found in preprocessing data file """ & Get_Name_String (N) & """"); end if; -- Record the dependency on the preprocessor data file Add_Dependency (Source_Index_Of_Preproc_Data_File); end Parse_Preprocessing_Data_File; --------------------------- -- Prepare_To_Preprocess -- --------------------------- procedure Prepare_To_Preprocess (Source : File_Name_Type; Preprocessing_Needed : out Boolean) is Default : Boolean := False; Index : Int := 0; begin -- By default, preprocessing is not needed Preprocessing_Needed := False; if No_Preprocessing then return; end if; -- First, look for preprocessing data specific to the current source for J in 1 .. Preproc_Data_Table.Last loop if Preproc_Data_Table.Table (J).File_Name = Source then Index := J; Current_Data := Preproc_Data_Table.Table (J); exit; end if; end loop; -- If no specific preprocessing data, then take the default if Index = 0 then if Default_Data_Defined then Current_Data := Default_Data; Default := True; else -- If no default, then nothing to do return; end if; end if; -- Set the preprocessing flags according to the preprocessing data if Current_Data.Comments and not Current_Data.Always_Blank then Comment_Deleted_Lines := True; Blank_Deleted_Lines := False; else Comment_Deleted_Lines := False; Blank_Deleted_Lines := True; end if; No_Deletion := Current_Data.No_Deletion; Undefined_Symbols_Are_False := Current_Data.Undef_False; List_Preprocessing_Symbols := Current_Data.List_Symbols; -- If not already done it, process the definition file if Current_Data.Processed then -- Set Prep.Mapping Prep.Mapping := Current_Data.Mapping; else -- First put the mapping in Prep.Mapping, because Prep.Parse_Def_File -- works on Prep.Mapping. Prep.Mapping := Current_Data.Mapping; String_To_Name_Buffer (Current_Data.Deffile); declare N : constant File_Name_Type := Name_Find; Deffile : constant Source_File_Index := Load_Definition_File (N); T : constant Nat := Total_Errors_Detected; Add_Deffile : Boolean := True; begin if Deffile <= No_Source_File then Fail ("definition file """ & Get_Name_String (N) & """ not found"); end if; -- Initialize the preprocessor and set the characteristics of the -- scanner for a definition file. Prep.Setup_Hooks (Error_Msg => Errout.Error_Msg'Access, Scan => Scn.Scanner.Scan'Access, Set_Ignore_Errors => Errout.Set_Ignore_Errors'Access, Put_Char => null, New_EOL => null); Scn.Scanner.Set_End_Of_Line_As_Token (True); Scn.Scanner.Reset_Special_Characters; -- Initialize the scanner and process the definition file Scn.Scanner.Initialize_Scanner (Deffile); Prep.Parse_Def_File; -- Reset the behavior of the scanner to the default Scn.Scanner.Set_End_Of_Line_As_Token (False); -- Fail if errors were found while processing the definition file if T /= Total_Errors_Detected then Errout.Finalize (Last_Call => True); Errout.Output_Messages; Fail ("errors found in definition file """ & Get_Name_String (N) & """"); end if; for Index in 1 .. Dependencies.Last loop if Dependencies.Table (Index) = Deffile then Add_Deffile := False; exit; end if; end loop; if Add_Deffile then Add_Dependency (Deffile); end if; end; -- Get back the mapping, indicate that the definition file is -- processed and store back the preprocessing data. Current_Data.Mapping := Prep.Mapping; Current_Data.Processed := True; if Default then Default_Data := Current_Data; else Preproc_Data_Table.Table (Index) := Current_Data; end if; end if; Preprocessing_Needed := True; end Prepare_To_Preprocess; --------------------------------------------- -- Process_Command_Line_Symbol_Definitions -- --------------------------------------------- procedure Process_Command_Line_Symbol_Definitions is Symbol_Data : Prep.Symbol_Data; Found : Boolean := False; begin Symbol_Table.Init (Command_Line_Symbols); -- The command line definitions have been stored temporarily in -- array Symbol_Definitions. for Index in 1 .. Preprocessing_Symbol_Last loop -- Check each symbol definition, fail immediately if syntax is not -- correct. Check_Command_Line_Symbol_Definition (Definition => Preprocessing_Symbol_Defs (Index).all, Data => Symbol_Data); Found := False; -- If there is already a definition for this symbol, replace the old -- definition by this one. for J in 1 .. Symbol_Table.Last (Command_Line_Symbols) loop if Command_Line_Symbols.Table (J).Symbol = Symbol_Data.Symbol then Command_Line_Symbols.Table (J) := Symbol_Data; Found := True; exit; end if; end loop; -- Otherwise, create a new entry in the table if not Found then Symbol_Table.Increment_Last (Command_Line_Symbols); Command_Line_Symbols.Table (Symbol_Table.Last (Command_Line_Symbols)) := Symbol_Data; end if; end loop; end Process_Command_Line_Symbol_Definitions; ------------------------- -- Skip_To_End_Of_Line -- ------------------------- procedure Skip_To_End_Of_Line is begin Set_Ignore_Errors (To => True); while Token /= Tok_End_Of_Line and then Token /= Tok_EOF loop Scan; end loop; Set_Ignore_Errors (To => False); end Skip_To_End_Of_Line; end Prepcomp;
----------------------------------------------------------------------- -- gprofiler-events - Profiler Events Description -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Glib; with Gtk.Handlers; with Gtk.Widget; with Util.Log.Loggers; package body MAT.Events.Gtkmat is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Events.Gtkmat"); package Event_Cb is new Gtk.Handlers.Return_Callback (Gtk.Drawing_Area.Gtk_Drawing_Area_Record, Boolean); Target : Event_Drawing_Type_Access; function Redraw (Area : access Gtk.Drawing_Area.Gtk_Drawing_Area_Record'Class; Cr : in Cairo.Cairo_Context) return Boolean is begin Draw (Target.all, Cr); return False; end Redraw; procedure Create (Drawing : in out Event_Drawing_Type) is begin Target := Drawing'Unrestricted_Access; Gtk.Drawing_Area.Gtk_New (Drawing.Drawing); -- Event_Cb.Connect (Drawing.Drawing, Gtk.Widget.Signal_Draw, -- Event_Cb.To_Marshaller (Redraw'Access)); -- , Drawing'Unrestricted_Access); end Create; procedure Draw (Onto : in Event_Drawing_Type; Cr : in Cairo.Cairo_Context) is use type Glib.Gdouble; use type MAT.Types.Target_Tick_Ref; use type MAT.Types.Target_Thread_Ref; type Thread_Ref_Array is array (1 .. 10) of MAT.Types.Target_Thread_Ref; Iter : MAT.Events.Tools.Target_Event_Cursor; Threads : Thread_Ref_Array := (others => 0); Start : MAT.Types.Target_Tick_Ref; Finish : MAT.Types.Target_Tick_Ref; Time_F : Glib.Gdouble; Thread_F : Glib.Gdouble; function Get_Thread_Index (Thread : in MAT.Types.Target_Thread_Ref) return Natural is begin for I in Thread_Ref_Array'Range loop if Threads (I) = Thread then return I; end if; if Threads (I) = 0 then Threads (I) := Thread; return I; end if; end loop; return Threads'Last; end Get_Thread_Index; function Get_Time_Pos (Time : in MAT.Types.Target_Tick_Ref) return Glib.Gdouble is Dt : constant MAT.Types.Target_Tick_Ref := Time - Start; begin return Time_F * Glib.Gdouble (Dt); end Get_Time_Pos; function Get_Thread_Pos (Thread : in MAT.Types.Target_Thread_Ref) return Glib.Gdouble is Pos : Natural := Get_Thread_Index (Thread); begin return Thread_F * Glib.Gdouble (Pos); end Get_Thread_Pos; Width : Glib.Gint; Height : Glib.Gint; begin Log.Info ("Redraw events window"); Cairo.Translate (Cr, 10.0, 10.0); -- Cairo.Scale (Cr, 10.0, 10.0); if Onto.List.Is_Empty then return; end if; Width := 1000; -- Onto.Drawing.Get_Allocated_Width; Height := 128; -- Onto.Drawing.Get_Allocated_Height; Start := Onto.List.First_Element.Time; Finish := Onto.List.Last_Element.Time; if Start = Finish then Time_F := 10.0; else Time_F := Glib.Gdouble (Width) / Glib.Gdouble (Finish - Start); end if; Thread_F := Glib.Gdouble (Height) / 10.0; Iter := Onto.List.First; while MAT.Events.Tools.Target_Event_Vectors.Has_Element (Iter) loop declare Event : MAT.Events.Target_Event_Type := MAT.Events.Tools.Target_Event_Vectors.Element (Iter); Y : Glib.Gdouble := Get_Thread_Pos (Event.Thread); X : Glib.Gdouble := Get_Time_Pos (Event.Time); begin if Event.Event = 4 then Cairo.Set_Source_Rgb (Cr, Red => 0.0, Green => 0.0, Blue => 1.0); else Cairo.Set_Source_Rgb (Cr, Red => 1.0, Green => 0.0, Blue => 0.0); end if; Cairo.Move_To (Cr, X, Y); Cairo.Line_To (Cr, X, Y + 10.0); Cairo.Stroke (Cr); end; MAT.Events.Tools.Target_Event_Vectors.Next (Iter); end loop; -- Cairo.Set_Source_Rgb (Cr, Red => 0.0, Green => 0.0, Blue => 0.0); -- for I in 1 .. 10 loop -- Cairo.Move_To (Cr, 10.0 * Glib.Gdouble (I), 0.0); -- Cairo.Line_To (Cr, 10.0 * Glib.Gdouble (I), 2.0); -- Cairo.Stroke (Cr); -- end loop; end Draw; end MAT.Events.Gtkmat;
------------------------------------------------------------------------------ -- -- -- GNU ADA RUN-TIME LIBRARY (GNARL) COMPONENTS -- -- -- -- S Y S T E M . O S _ I N T E R F A C E -- -- -- -- B o d y -- -- -- -- $Revision$ -- -- -- Copyright (C) 1991-2001 Florida State University -- -- -- -- GNARL is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNARL is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNARL; see file COPYING. If not, write -- -- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, -- -- MA 02111-1307, USA. -- -- -- -- As a special exception, if other files instantiate generics from this -- -- unit, or you link this unit with other files to produce an executable, -- -- this unit does not by itself cause the resulting executable to be -- -- covered by the GNU General Public License. This exception does not -- -- however invalidate any other reasons why the executable file might be -- -- covered by the GNU Public License. -- -- -- -- GNARL was developed by the GNARL team at Florida State University. It is -- -- now maintained by Ada Core Technologies Inc. in cooperation with Florida -- -- State University (http://www.gnat.com). -- -- -- ------------------------------------------------------------------------------ -- This is the OS/2 version of this package pragma Polling (Off); -- Turn off polling, we do not want ATC polling to take place during -- tasking operations. It causes infinite loops and other problems. with Interfaces.C.Strings; with Interfaces.OS2Lib.Errors; with Interfaces.OS2Lib.Synchronization; package body System.OS_Interface is use Interfaces; use Interfaces.OS2Lib; use Interfaces.OS2Lib.Synchronization; use Interfaces.OS2Lib.Errors; ------------------ -- Timer (spec) -- ------------------ -- Although the OS uses a 32-bit integer representing milliseconds -- as timer value that doesn't work for us since 32 bits are not -- enough for absolute timing. Also it is useful to use better -- intermediate precision when adding/subtracting timing intervals. -- So we use the standard Ada Duration type which is implemented using -- microseconds. -- Shouldn't the timer be moved to a separate package ??? type Timer is record Handle : aliased HTIMER := NULLHANDLE; Event : aliased HEV := NULLHANDLE; end record; procedure Initialize (T : out Timer); procedure Finalize (T : in out Timer); procedure Wait (T : in out Timer); procedure Reset (T : in out Timer); procedure Set_Timer_For (T : in out Timer; Period : in Duration); procedure Set_Timer_At (T : in out Timer; Time : in Duration); -- Add a hook to locate the Epoch, for use with Calendar???? ----------- -- Yield -- ----------- -- Give up the remainder of the time-slice and yield the processor -- to other threads of equal priority. Yield will return immediately -- without giving up the current time-slice when the only threads -- that are ready have a lower priority. -- ??? Just giving up the current time-slice seems not to be enough -- to get the thread to the end of the ready queue if OS/2 does use -- a queue at all. As a partial work-around, we give up two time-slices. -- This is the best we can do now, and at least is sufficient for passing -- the ACVC 2.0.1 Annex D tests. procedure Yield is begin Delay_For (0); Delay_For (0); end Yield; --------------- -- Delay_For -- --------------- procedure Delay_For (Period : in Duration_In_Millisec) is Result : APIRET; begin pragma Assert (Period >= 0, "GNULLI---Delay_For: negative argument"); -- ??? DosSleep is not the appropriate function for a delay in real -- time. It only gives up some number of scheduled time-slices. -- Use a timer instead or block for some semaphore with a time-out. Result := DosSleep (ULONG (Period)); if Result = ERROR_TS_WAKEUP then -- Do appropriate processing for interrupted sleep -- Can we raise an exception here? null; end if; pragma Assert (Result = NO_ERROR, "GNULLI---Error in Delay_For"); end Delay_For; ----------- -- Clock -- ----------- function Clock return Duration is -- Implement conversion from tick count to Duration -- using fixed point arithmetic. The frequency of -- the Intel 8254 timer chip is 18.2 * 2**16 Hz. Tick_Duration : constant := 1.0 / (18.2 * 2**16); Tick_Count : aliased QWORD; begin -- Read nr of clock ticks since boot time Must_Not_Fail (DosTmrQueryTime (Tick_Count'Access)); return Tick_Count * Tick_Duration; end Clock; ---------------------- -- Initialize Timer -- ---------------------- procedure Initialize (T : out Timer) is begin pragma Assert (T.Handle = NULLHANDLE, "GNULLI---Timer already initialized"); Must_Not_Fail (DosCreateEventSem (pszName => Interfaces.C.Strings.Null_Ptr, f_phev => T.Event'Unchecked_Access, flAttr => DC_SEM_SHARED, fState => False32)); end Initialize; ------------------- -- Set_Timer_For -- ------------------- procedure Set_Timer_For (T : in out Timer; Period : in Duration) is Rel_Time : Duration_In_Millisec := Duration_In_Millisec (Period * 1_000.0); begin pragma Assert (T.Event /= NULLHANDLE, "GNULLI---Timer not initialized"); pragma Assert (T.Handle = NULLHANDLE, "GNULLI---Timer already in use"); Must_Not_Fail (DosAsyncTimer (msec => ULONG (Rel_Time), F_hsem => HSEM (T.Event), F_phtimer => T.Handle'Unchecked_Access)); end Set_Timer_For; ------------------ -- Set_Timer_At -- ------------------ -- Note that the timer is started in a critical section to prevent the -- race condition when absolute time is converted to time relative to -- current time. T.Event will be posted when the Time has passed procedure Set_Timer_At (T : in out Timer; Time : in Duration) is Relative_Time : Duration; begin Must_Not_Fail (DosEnterCritSec); begin Relative_Time := Time - Clock; if Relative_Time > 0.0 then Set_Timer_For (T, Period => Time - Clock); else Sem_Must_Not_Fail (DosPostEventSem (T.Event)); end if; end; Must_Not_Fail (DosExitCritSec); end Set_Timer_At; ---------- -- Wait -- ---------- procedure Wait (T : in out Timer) is begin Sem_Must_Not_Fail (DosWaitEventSem (T.Event, SEM_INDEFINITE_WAIT)); T.Handle := NULLHANDLE; end Wait; ----------- -- Reset -- ----------- procedure Reset (T : in out Timer) is Dummy_Count : aliased ULONG; begin if T.Handle /= NULLHANDLE then Must_Not_Fail (DosStopTimer (T.Handle)); T.Handle := NULLHANDLE; end if; Sem_Must_Not_Fail (DosResetEventSem (T.Event, Dummy_Count'Unchecked_Access)); end Reset; -------------- -- Finalize -- -------------- procedure Finalize (T : in out Timer) is begin Reset (T); Must_Not_Fail (DosCloseEventSem (T.Event)); T.Event := NULLHANDLE; end Finalize; end System.OS_Interface;
-- Copyright (C) 2021 Steve Merrony -- 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 Gdk.Pixbuf; use Gdk.Pixbuf; with Glib; use Glib; package BDF_Font is Max_Chars : constant Positive := 128; BPP : constant Positive := 8; -- raw font dimensions Font_Width : constant Gint := 10; Font_Height : constant Gint := 12; type Zoom_T is (Large, Normal, Smaller, Tiny); type Matrix is array(0..Font_Width-1,0..Font_Height-1) of Boolean; type BDF_Char is record Loaded : Boolean; Pix_Buf, Dim_Pix_Buf, Reverse_Pix_Buf : Gdk_Pixbuf; Pixels : Matrix; end record; type Font_Array is array (0..Max_Chars-1) of BDF_Char; type Decoded_T is record Font : Font_Array; Char_Width, Char_Height : Gint; end record; protected Font is procedure Load_Font (File_Name : String; Zoom : Zoom_T); function Get_Char_Width return Gint; function Get_Char_Height return Gint; function Is_Loaded (Ix : in Natural) return Boolean; function Get_Dim_Pixbuf (Ix : in Natural) return Gdk_Pixbuf; function Get_Rev_Pixbuf (Ix : in Natural) return Gdk_Pixbuf; function Get_Pixbuf (Ix : in Natural) return Gdk_Pixbuf; private Decoded : Decoded_T; end Font; OPEN_FAILURE, BDF_DECODE : exception; end BDF_Font;
-- -- Copyright (C) 2022 Jeremy Grosser <jeremy@synack.me> -- -- SPDX-License-Identifier: BSD-3-Clause -- generic type Word is mod <>; type Word_Array is array (Natural range <>) of Word; package CRC with Preelaborate is Poly : Word; Sum : Word := 0; procedure Update (Data : Word); procedure Update (Data : Word_Array); function Calculate (Data : Word_Array; Initial : Word := 0) return Word; end CRC;
with Ada.Exception_Identification.From_Here; with Ada.Exceptions.Finally; with Ada.Unchecked_Deallocation; with System.Form_Parameters; with System.Native_IO.Names; with System.Standard_Allocators; with System.Storage_Elements; package body Ada.Streams.Naked_Stream_IO is use Exception_Identification.From_Here; use type IO_Modes.File_Mode; use type IO_Modes.File_Shared_Spec; use type Tags.Tag; -- use type System.Address; use type System.Native_IO.File_Mode; -- use type System.Native_IO.Handle_Type; use type System.Native_IO.Name_Pointer; use type System.Storage_Elements.Storage_Offset; procedure unreachable with Import, Convention => Intrinsic, External_Name => "__builtin_unreachable"; pragma No_Return (unreachable); function To_Pointer (Value : System.Address) return access Root_Stream_Type'Class with Import, Convention => Intrinsic; To_Native_Mode : constant array (IO_Modes.File_Mode) of System.Native_IO.File_Mode := ( IO_Modes.In_File => System.Native_IO.Read_Only_Mode, IO_Modes.Out_File => System.Native_IO.Write_Only_Mode, IO_Modes.Append_File => System.Native_IO.Write_Only_Mode or System.Native_IO.Append_Mode); Inout_To_Native_Mode : constant array (IO_Modes.Inout_File_Mode) of System.Native_IO.File_Mode := ( IO_Modes.In_File => System.Native_IO.Read_Only_Mode, IO_Modes.Inout_File => System.Native_IO.Read_Write_Mode, IO_Modes.Out_File => System.Native_IO.Write_Only_Mode); -- the parameter Form procedure Set ( Form : in out System.Native_IO.Packed_Form; Keyword : String; Item : String) is begin if Keyword = "shared" then if Item'Length > 0 and then ( Item (Item'First) = 'a' -- allow or else Item (Item'First) = 'n' -- no, compatibility or else Item (Item'First) = 'y') -- yes, compatibility then Form.Shared := IO_Modes.Allow; elsif Item'Length > 0 and then Item (Item'First) = 'r' then -- read Form.Shared := IO_Modes.Read_Only; elsif Item'Length > 0 and then Item (Item'First) = 'd' then -- deny Form.Shared := IO_Modes.Deny; end if; elsif Keyword = "wait" then if Item'Length > 0 and then Item (Item'First) = 'f' then -- false Form.Wait := False; elsif Item'Length > 0 and then Item (Item'First) = 't' then -- true Form.Wait := True; end if; elsif Keyword = "overwrite" then if Item'Length > 0 and then Item (Item'First) = 'f' then -- false Form.Overwrite := False; elsif Item'Length > 0 and then Item (Item'First) = 't' then -- true Form.Overwrite := True; end if; end if; end Set; function Pack (Form : String) return System.Native_IO.Packed_Form is Keyword_First : Positive; Keyword_Last : Natural; Item_First : Positive; Item_Last : Natural; Last : Natural; begin return Result : System.Native_IO.Packed_Form := Default_Form do Last := Form'First - 1; while Last < Form'Last loop System.Form_Parameters.Get ( Form (Last + 1 .. Form'Last), Keyword_First, Keyword_Last, Item_First, Item_Last, Last); Set ( Result, Form (Keyword_First .. Keyword_Last), Form (Item_First .. Item_Last)); end loop; end return; end Pack; procedure Unpack ( Form : System.Native_IO.Packed_Form; Result : out Form_String; Last : out Natural) is New_Last : Natural; begin Last := Form_String'First - 1; if Form.Shared /= IO_Modes.By_Mode then case IO_Modes.File_Shared (Form.Shared) is when IO_Modes.Allow => New_Last := Last + 10; Result (Last + 1 .. New_Last) := "shared=yes"; Last := New_Last; when IO_Modes.Read_Only => New_Last := Last + 11; Result (Last + 1 .. New_Last) := "shared=read"; Last := New_Last; when IO_Modes.Deny => New_Last := Last + 12; Result (Last + 1 .. New_Last) := "shared=write"; Last := New_Last; end case; end if; if Form.Wait then if Last /= Form_String'First - 1 then New_Last := Last + 1; Result (New_Last) := ','; Last := New_Last; end if; New_Last := Last + 9; Result (Last + 1 .. New_Last) := "wait=true"; Last := New_Last; end if; if Form.Overwrite then if Last /= Form_String'First - 1 then New_Last := Last + 1; Result (New_Last) := ','; Last := New_Last; end if; New_Last := Last + 14; Result (Last + 1 .. New_Last) := "overwrite=true"; Last := New_Last; end if; end Unpack; -- non-controlled function Allocate ( Handle : System.Native_IO.Handle_Type; Mode : System.Native_IO.File_Mode; Name : System.Native_IO.Name_Pointer; Form : System.Native_IO.Packed_Form; Kind : Stream_Kind; Has_Full_Name : Boolean; Closer : Close_Handler) return Non_Controlled_File_Type; function Allocate ( Handle : System.Native_IO.Handle_Type; Mode : System.Native_IO.File_Mode; Name : System.Native_IO.Name_Pointer; Form : System.Native_IO.Packed_Form; Kind : Stream_Kind; Has_Full_Name : Boolean; Closer : Close_Handler) return Non_Controlled_File_Type is begin return new Stream_Type'( Handle => Handle, Mode => Mode, Name => Name, Form => Form, Kind => Kind, Has_Full_Name => Has_Full_Name, Buffer_Inline => <>, Buffer => System.Null_Address, Buffer_Length => Uninitialized_Buffer, Buffer_Index => 0, Reading_Index => 0, Writing_Index => 0, Closer => Closer, Dispatcher => (Tag => Tags.No_Tag, File => null)); end Allocate; procedure Free (File : in out Non_Controlled_File_Type); procedure Free (File : in out Non_Controlled_File_Type) is use type System.Address; procedure Raw_Free is new Unchecked_Deallocation (Stream_Type, Non_Controlled_File_Type); begin if File.Buffer /= File.Buffer_Inline'Address then System.Standard_Allocators.Free (File.Buffer); end if; System.Native_IO.Free (File.Name); Raw_Free (File); end Free; type Scoped_Handle_And_File_And_Name is record -- to cleanup Handle : aliased System.Native_IO.Handle_Type; File : aliased Non_Controlled_File_Type; -- for Handle, and to cleanup when File = null Name : aliased System.Native_IO.Name_Pointer; -- for Handle Closer : Close_Handler; end record; pragma Suppress_Initialization (Scoped_Handle_And_File_And_Name); procedure Finally (X : in out Scoped_Handle_And_File_And_Name); procedure Finally (X : in out Scoped_Handle_And_File_And_Name) is use type System.Native_IO.Handle_Type; begin if X.Handle /= System.Native_IO.Invalid_Handle then -- External_No_Close is not set to Scoped_Handle_And_File_And_Name X.Closer (X.Handle, X.Name, Raise_On_Error => False); end if; if X.File /= null then Free (X.File); else System.Native_IO.Free (X.Name); end if; end Finally; procedure Set_Buffer_Index ( File : not null Non_Controlled_File_Type; Buffer_Index : Stream_Element_Offset); procedure Set_Buffer_Index ( File : not null Non_Controlled_File_Type; Buffer_Index : Stream_Element_Offset) is begin if File.Buffer_Length = Uninitialized_Buffer then File.Buffer_Index := Buffer_Index; elsif File.Buffer_Length = 0 then File.Buffer_Index := 0; else File.Buffer_Index := Buffer_Index rem Stream_Element_Positive_Count'(File.Buffer_Length); end if; File.Reading_Index := File.Buffer_Index; File.Writing_Index := File.Buffer_Index; end Set_Buffer_Index; procedure Set_Index_To_Append (File : not null Non_Controlled_File_Type); procedure Set_Index_To_Append (File : not null Non_Controlled_File_Type) is New_Index : Stream_Element_Offset; begin System.Native_IO.Set_Relative_Index ( File.Handle, 0, System.Native_IO.From_End, New_Index); Set_Buffer_Index (File, New_Index); end Set_Index_To_Append; procedure Allocate_And_Open ( Method : System.Native_IO.Open_Method; File : out Non_Controlled_File_Type; Mode : System.Native_IO.File_Mode; Name : String; Form : System.Native_IO.Packed_Form); procedure Allocate_And_Open ( Method : System.Native_IO.Open_Method; File : out Non_Controlled_File_Type; Mode : System.Native_IO.File_Mode; Name : String; Form : System.Native_IO.Packed_Form) is package Holder is new Exceptions.Finally.Scoped_Holder ( Scoped_Handle_And_File_And_Name, Finally); Scoped : aliased Scoped_Handle_And_File_And_Name := (System.Native_IO.Invalid_Handle, null, null, null); Kind : Stream_Kind; begin Holder.Assign (Scoped); if Name /= "" then Kind := Ordinary; else Kind := Temporary; end if; if Kind = Ordinary then Scoped.Closer := System.Native_IO.Close_Ordinary'Access; System.Native_IO.Names.Open_Ordinary ( Method => Method, Handle => Scoped.Handle, Mode => Mode, Name => Name, Out_Name => Scoped.Name, Form => Form); else Scoped.Closer := System.Native_IO.Close_Temporary'Access; System.Native_IO.Open_Temporary (Scoped.Handle, Scoped.Name); end if; Scoped.File := Allocate ( Handle => Scoped.Handle, Mode => Mode, Name => Scoped.Name, Form => Form, Kind => Kind, Has_Full_Name => Scoped.Name /= null, Closer => Scoped.Closer); if Kind = Ordinary and then (Mode and System.Native_IO.Append_Mode) /= 0 then Set_Index_To_Append (Scoped.File); -- sets index to the last end if; File := Scoped.File; -- complete Holder.Clear; end Allocate_And_Open; procedure Allocate_External ( File : out Non_Controlled_File_Type; Mode : System.Native_IO.File_Mode; Handle : System.Native_IO.Handle_Type; Name : String; Form : System.Native_IO.Packed_Form; To_Close : Boolean); procedure Allocate_External ( File : out Non_Controlled_File_Type; Mode : System.Native_IO.File_Mode; Handle : System.Native_IO.Handle_Type; Name : String; Form : System.Native_IO.Packed_Form; To_Close : Boolean) is package Name_Holder is new Exceptions.Finally.Scoped_Holder ( System.Native_IO.Name_Pointer, System.Native_IO.Free); Kind : Stream_Kind; Closer : Close_Handler; Full_Name : aliased System.Native_IO.Name_Pointer; begin if To_Close then Kind := External; Closer := System.Native_IO.Close_Ordinary'Access; else Kind := External_No_Close; Closer := null; end if; Name_Holder.Assign (Full_Name); System.Native_IO.New_External_Name (Name, Full_Name); -- '*' & Name & NUL File := Allocate ( Handle => Handle, Mode => Mode, Name => Full_Name, Form => Form, Kind => Kind, Has_Full_Name => False, Closer => Closer); -- complete Name_Holder.Clear; end Allocate_External; procedure Get_Full_Name (File : not null Non_Controlled_File_Type); procedure Get_Full_Name (File : not null Non_Controlled_File_Type) is begin if not File.Has_Full_Name then System.Native_IO.Names.Get_Full_Name ( File.Handle, File.Has_Full_Name, File.Name, Is_Standard => File.Kind = Standard_Handle, Raise_On_Error => File.Name = null); end if; end Get_Full_Name; procedure Reset ( File : aliased in out Non_Controlled_File_Type; Mode : System.Native_IO.File_Mode); procedure Reset ( File : aliased in out Non_Controlled_File_Type; Mode : System.Native_IO.File_Mode) is package Holder is new Exceptions.Finally.Scoped_Holder ( Scoped_Handle_And_File_And_Name, Finally); Scoped : aliased Scoped_Handle_And_File_And_Name := (System.Native_IO.Invalid_Handle, null, null, File.Closer); begin Holder.Assign (Scoped); case File.all.Kind is when Ordinary => Get_Full_Name (File); Scoped.Handle := File.Handle; Scoped.File := File; Scoped.Name := File.Name; File := null; Flush_Writing_Buffer (Scoped.File); -- close explicitly in below Scoped.Handle := System.Native_IO.Invalid_Handle; System.Native_IO.Close_Ordinary ( Scoped.File.Handle, Scoped.File.Name, Raise_On_Error => True); Scoped.File.Buffer_Index := 0; Scoped.File.Reading_Index := Scoped.File.Buffer_Index; Scoped.File.Writing_Index := Scoped.File.Buffer_Index; System.Native_IO.Open_Ordinary ( Method => System.Native_IO.Reset, Handle => Scoped.Handle, Mode => Mode, Name => Scoped.File.Name, Form => Scoped.File.Form); Scoped.File.Handle := Scoped.Handle; Scoped.File.Mode := Mode; if (Mode and System.Native_IO.Append_Mode) /= 0 then Set_Index_To_Append (Scoped.File); end if; when Temporary => Scoped.Handle := File.Handle; Scoped.File := File; Scoped.Name := File.Name; File := null; Scoped.File.Mode := Mode; if (Mode and System.Native_IO.Append_Mode) /= 0 then Flush_Writing_Buffer (Scoped.File); Set_Index_To_Append (Scoped.File); else Set_Index (Scoped.File, 1); end if; when External | External_No_Close | Standard_Handle => pragma Check (Pre, Boolean'(raise Status_Error)); unreachable; end case; File := Scoped.File; -- complete Holder.Clear; end Reset; procedure Get_Buffer (File : not null Non_Controlled_File_Type); procedure Get_Buffer (File : not null Non_Controlled_File_Type) is begin if File.Buffer_Length = Uninitialized_Buffer then File.Buffer_Length := System.Native_IO.Block_Size (File.Handle); if File.Buffer_Length = 0 then File.Buffer := File.Buffer_Inline'Address; File.Buffer_Index := 0; else File.Buffer := System.Standard_Allocators.Allocate ( System.Storage_Elements.Storage_Offset (File.Buffer_Length)); File.Buffer_Index := File.Buffer_Index rem Stream_Element_Positive_Count'(File.Buffer_Length); end if; File.Reading_Index := File.Buffer_Index; File.Writing_Index := File.Buffer_Index; end if; end Get_Buffer; procedure Ready_Reading_Buffer ( File : not null Non_Controlled_File_Type; Error : out Boolean); procedure Ready_Reading_Buffer ( File : not null Non_Controlled_File_Type; Error : out Boolean) is Buffer_Length : constant Stream_Element_Positive_Count := Stream_Element_Offset'Max (1, File.Buffer_Length); begin -- reading buffer is from File.Reading_Index until File.Buffer_Index File.Buffer_Index := File.Buffer_Index rem Buffer_Length; File.Reading_Index := File.Buffer_Index; declare Read_Length : Stream_Element_Offset; begin System.Native_IO.Read ( File.Handle, File.Buffer + System.Storage_Elements.Storage_Offset (File.Buffer_Index), Buffer_Length - File.Buffer_Index, Read_Length); Error := Read_Length < 0; if not Error then File.Buffer_Index := File.Buffer_Index + Read_Length; end if; end; File.Writing_Index := File.Buffer_Index; end Ready_Reading_Buffer; procedure Reset_Reading_Buffer (File : not null Non_Controlled_File_Type); procedure Reset_Reading_Buffer (File : not null Non_Controlled_File_Type) is Dummy_New_Index : Stream_Element_Offset; begin System.Native_IO.Set_Relative_Index ( File.Handle, File.Reading_Index - File.Buffer_Index, System.Native_IO.From_Current, Dummy_New_Index); File.Buffer_Index := File.Reading_Index; File.Writing_Index := File.Buffer_Index; end Reset_Reading_Buffer; procedure Ready_Writing_Buffer (File : not null Non_Controlled_File_Type); procedure Ready_Writing_Buffer (File : not null Non_Controlled_File_Type) is begin -- writing buffer is from File.Buffer_Index until File.Writing_Index File.Buffer_Index := File.Buffer_Index rem Stream_Element_Positive_Count'(File.Buffer_Length); File.Writing_Index := File.Buffer_Index; File.Reading_Index := File.Buffer_Index; end Ready_Writing_Buffer; function Offset_Of_Buffer (File : not null Non_Controlled_File_Type) return Stream_Element_Offset; function Offset_Of_Buffer (File : not null Non_Controlled_File_Type) return Stream_Element_Offset is begin return (File.Writing_Index - File.Buffer_Index) - (File.Buffer_Index - File.Reading_Index); end Offset_Of_Buffer; procedure Read_From_Buffer ( File : not null Non_Controlled_File_Type; Item : out Stream_Element_Array; Last : out Stream_Element_Offset); procedure Read_From_Buffer ( File : not null Non_Controlled_File_Type; Item : out Stream_Element_Array; Last : out Stream_Element_Offset) is Taking_Length : constant Stream_Element_Offset := Stream_Element_Offset'Min ( Item'Last - Item'First + 1, File.Buffer_Index - File.Reading_Index); Buffer : Stream_Element_Array ( 0 .. Stream_Element_Offset'Max (0, File.Buffer_Length - 1)); for Buffer'Address use File.Buffer; begin Last := Item'First + (Taking_Length - 1); Item (Item'First .. Last) := Buffer (File.Reading_Index .. File.Reading_Index + Taking_Length - 1); File.Reading_Index := File.Reading_Index + Taking_Length; end Read_From_Buffer; procedure Write_To_Buffer ( File : not null Non_Controlled_File_Type; Item : Stream_Element_Array; Last : out Stream_Element_Offset); procedure Write_To_Buffer ( File : not null Non_Controlled_File_Type; Item : Stream_Element_Array; Last : out Stream_Element_Offset) is Taking_Length : constant Stream_Element_Offset := Stream_Element_Offset'Min ( Item'Last - Item'First + 1, File.Buffer_Length - File.Writing_Index); Buffer : Stream_Element_Array ( 0 .. Stream_Element_Offset'Max (0, File.Buffer_Length - 1)); for Buffer'Address use File.Buffer; begin Last := Item'First + (Taking_Length - 1); Buffer (File.Writing_Index .. File.Writing_Index + Taking_Length - 1) := Item (Item'First .. Last); File.Writing_Index := File.Writing_Index + Taking_Length; end Write_To_Buffer; function End_Of_Ordinary_File (File : not null Non_Controlled_File_Type) return Boolean; function End_Of_Ordinary_File (File : not null Non_Controlled_File_Type) return Boolean is Size : constant Stream_Element_Count := System.Native_IO.Size (File.Handle); Index : constant Stream_Element_Offset := System.Native_IO.Index (File.Handle) + Offset_Of_Buffer (File); begin return Index > Size; -- The writing buffer can be expanded over the file size. end End_Of_Ordinary_File; procedure Close_And_Deallocate ( File : aliased in out Non_Controlled_File_Type; Raise_On_Error : Boolean); procedure Close_And_Deallocate ( File : aliased in out Non_Controlled_File_Type; Raise_On_Error : Boolean) is use type System.Native_IO.Handle_Type; package Holder is new Exceptions.Finally.Scoped_Holder ( Scoped_Handle_And_File_And_Name, Finally); Scoped : aliased Scoped_Handle_And_File_And_Name := (System.Native_IO.Invalid_Handle, null, null, File.Closer); Freeing_File : constant Non_Controlled_File_Type := File; begin Holder.Assign (Scoped); File := null; declare Kind : constant Stream_Kind := Freeing_File.Kind; begin if Kind /= Standard_Handle then if Kind /= External_No_Close then Scoped.Handle := Freeing_File.Handle; end if; Scoped.File := Freeing_File; Scoped.Name := Freeing_File.Name; else -- The standard files are statically allocated. if Freeing_File.Has_Full_Name then Scoped.Name := Freeing_File.Name; -- The standard files may be double-finalized -- from Ada.Streams.Stream_IO.Standard_Files and Ada.Text_IO. Freeing_File.Name := null; Freeing_File.Has_Full_Name := False; end if; end if; if Kind /= Temporary then Flush_Writing_Buffer ( Freeing_File, Raise_On_Error => Raise_On_Error); end if; end; if Scoped.Handle /= System.Native_IO.Invalid_Handle then -- close explicitly in below Scoped.Handle := System.Native_IO.Invalid_Handle; Freeing_File.Closer ( Freeing_File.Handle, Freeing_File.Name, Raise_On_Error => Raise_On_Error); end if; end Close_And_Deallocate; -- implementation of non-controlled procedure Create ( File : in out Non_Controlled_File_Type; Mode : IO_Modes.File_Mode := IO_Modes.Out_File; Name : String := ""; Form : System.Native_IO.Packed_Form := Default_Form) is pragma Check (Pre, Check => not Is_Open (File) or else raise Status_Error); begin Allocate_And_Open ( Method => System.Native_IO.Create, File => File, Mode => To_Native_Mode (Mode), Name => Name, Form => Form); end Create; procedure Create ( File : in out Non_Controlled_File_Type; Mode : IO_Modes.Inout_File_Mode := IO_Modes.Out_File; Name : String := ""; Form : System.Native_IO.Packed_Form := Default_Form) is pragma Check (Pre, Check => not Is_Open (File) or else raise Status_Error); begin Allocate_And_Open ( Method => System.Native_IO.Create, File => File, Mode => Inout_To_Native_Mode (Mode), Name => Name, Form => Form); end Create; procedure Open ( File : in out Non_Controlled_File_Type; Mode : IO_Modes.File_Mode; Name : String; Form : System.Native_IO.Packed_Form := Default_Form) is pragma Check (Pre, Check => not Is_Open (File) or else raise Status_Error); begin Allocate_And_Open ( Method => System.Native_IO.Open, File => File, Mode => To_Native_Mode (Mode), Name => Name, Form => Form); end Open; procedure Open ( File : in out Non_Controlled_File_Type; Mode : IO_Modes.Inout_File_Mode; Name : String; Form : System.Native_IO.Packed_Form := Default_Form) is pragma Check (Pre, Check => not Is_Open (File) or else raise Status_Error); begin Allocate_And_Open ( Method => System.Native_IO.Open, File => File, Mode => Inout_To_Native_Mode (Mode), Name => Name, Form => Form); end Open; procedure Close ( File : aliased in out Non_Controlled_File_Type; Raise_On_Error : Boolean := True) is pragma Check (Pre, Check => Is_Open (File) or else raise Status_Error); begin Close_And_Deallocate (File, Raise_On_Error => Raise_On_Error); end Close; procedure Delete (File : aliased in out Non_Controlled_File_Type) is pragma Check (Pre, Check => Is_Open (File) or else raise Status_Error); begin case File.Kind is when Ordinary => Get_Full_Name (File); File.Closer := System.Native_IO.Delete_Ordinary'Access; Close_And_Deallocate (File, Raise_On_Error => True); when Temporary => Close_And_Deallocate (File, Raise_On_Error => True); when External | External_No_Close | Standard_Handle => pragma Check (Pre, Boolean'(raise Status_Error)); unreachable; end case; end Delete; procedure Reset ( File : aliased in out Non_Controlled_File_Type; Mode : IO_Modes.File_Mode) is pragma Check (Pre, Check => Is_Open (File) or else raise Status_Error); begin Reset (File, To_Native_Mode (Mode)); end Reset; procedure Reset ( File : aliased in out Non_Controlled_File_Type; Mode : IO_Modes.Inout_File_Mode) is pragma Check (Pre, Check => Is_Open (File) or else raise Status_Error); begin Reset (File, Inout_To_Native_Mode (Mode)); end Reset; function Mode (File : not null Non_Controlled_File_Type) return IO_Modes.File_Mode is begin if File.Mode = System.Native_IO.Read_Only_Mode then return IO_Modes.In_File; elsif File.Mode = System.Native_IO.Write_Only_Mode then return IO_Modes.Out_File; else return IO_Modes.Append_File; -- implies Inout_File end if; end Mode; function Mode (File : not null Non_Controlled_File_Type) return IO_Modes.Inout_File_Mode is begin if File.Mode = System.Native_IO.Read_Only_Mode then return IO_Modes.In_File; elsif File.Mode /= System.Native_IO.Write_Only_Mode then return IO_Modes.Inout_File; -- implies Append_File else return IO_Modes.Out_File; end if; end Mode; function Mode (File : not null Non_Controlled_File_Type) return System.Native_IO.File_Mode is begin return File.Mode; end Mode; function Name (File : not null Non_Controlled_File_Type) return String is begin Get_Full_Name (File); return System.Native_IO.Value (File.Name); end Name; function Form (File : Non_Controlled_File_Type) return System.Native_IO.Packed_Form is begin return File.Form; end Form; function Is_Open (File : Non_Controlled_File_Type) return Boolean is begin return File /= null; end Is_Open; function End_Of_File (File : not null Non_Controlled_File_Type) return Boolean is begin Get_Buffer (File); if File.Buffer_Length = 0 then -- not ordinary file if File.Reading_Index = File.Buffer_Index then declare Error : Boolean; begin Ready_Reading_Buffer (File, Error); if Error then Raise_Exception (Device_Error'Identity); end if; end; end if; return File.Reading_Index = File.Buffer_Index; else return End_Of_Ordinary_File (File); end if; end End_Of_File; function Stream (File : not null Non_Controlled_File_Type) return not null access Root_Stream_Type'Class is begin if File.Dispatcher.Tag = Tags.No_Tag then if not System.Native_IO.Is_Seekable (File.Handle) then File.Dispatcher.Tag := Dispatchers.Root_Dispatcher'Tag; else File.Dispatcher.Tag := Dispatchers.Seekable_Dispatcher'Tag; end if; File.Dispatcher.File := File; end if; return To_Pointer (File.Dispatcher'Address); end Stream; procedure Read ( File : not null Non_Controlled_File_Type; Item : out Stream_Element_Array; Last : out Stream_Element_Offset) is Index : Stream_Element_Offset := Item'First; begin if File.Reading_Index < File.Buffer_Index then declare Temp_Last : Stream_Element_Offset; begin Read_From_Buffer (File, Item, Temp_Last); if Temp_Last = Item'Last then Last := Temp_Last; return; end if; Index := Temp_Last + 1; end; else if File.Writing_Index > File.Buffer_Index then Flush_Writing_Buffer (File); end if; if Index > Item'Last then Last := Index - 1; return; end if; end if; Get_Buffer (File); declare Error : Boolean := False; Buffer_Length : constant Stream_Element_Count := File.Buffer_Length; begin declare Taking_Length : Stream_Element_Count; begin Taking_Length := Item'Last - Index + 1; if Buffer_Length > 0 then declare Misaligned : constant Stream_Element_Count := (Buffer_Length - File.Buffer_Index) rem Buffer_Length; begin if Taking_Length < Misaligned then Taking_Length := 0; -- to use reading buffer else Taking_Length := Taking_Length - Misaligned; Taking_Length := Taking_Length - Taking_Length rem Buffer_Length; Taking_Length := Taking_Length + Misaligned; end if; end; end if; if Taking_Length > 0 then declare Read_Size : Stream_Element_Offset; begin System.Native_IO.Read ( File.Handle, Item (Index)'Address, Taking_Length, Read_Size); Error := Read_Size < 0; if not Error then Index := Index + Read_Size; -- update indexes if Buffer_Length > 0 then File.Buffer_Index := (File.Buffer_Index + Read_Size) rem Buffer_Length; else File.Buffer_Index := 0; end if; File.Reading_Index := File.Buffer_Index; File.Writing_Index := File.Buffer_Index; end if; end; end if; end; if not Error and then Index <= Item'Last and then File.Buffer_Length > 0 then Ready_Reading_Buffer (File, Error); -- reading buffer is empty if not Error and then File.Reading_Index < File.Buffer_Index then declare Temp_Last : Stream_Element_Offset; begin Read_From_Buffer ( File, Item (Index .. Item'Last), Temp_Last); Index := Temp_Last + 1; end; end if; end if; if Index <= Item'First then -- RM 13.13.1(8/2), Item'First - 1 is returned in Last for EOF. if Error then Raise_Exception (Device_Error'Identity); elsif Index = Stream_Element_Offset'First then raise Constraint_Error; -- AARM 13.13.1(11/2) end if; end if; end; Last := Index - 1; end Read; procedure Write ( File : not null Non_Controlled_File_Type; Item : Stream_Element_Array) is First : Stream_Element_Offset := Item'First; begin if File.Writing_Index > File.Buffer_Index then -- append to writing buffer declare Temp_Last : Stream_Element_Offset; begin Write_To_Buffer (File, Item, Temp_Last); if File.Writing_Index = File.Buffer_Length then Flush_Writing_Buffer (File); end if; if Temp_Last >= Item'Last then return; end if; First := Temp_Last + 1; end; else if File.Reading_Index < File.Buffer_Index then -- reset reading buffer Reset_Reading_Buffer (File); end if; if First > Item'Last then return; end if; end if; Get_Buffer (File); declare Buffer_Length : constant Stream_Element_Count := File.Buffer_Length; begin declare Taking_Length : Stream_Element_Count; begin Taking_Length := Item'Last - First + 1; if Buffer_Length > 0 then declare Misaligned : constant Stream_Element_Count := (Buffer_Length - File.Buffer_Index) rem Buffer_Length; begin if Taking_Length < Misaligned then Taking_Length := 0; -- to use writing buffer else Taking_Length := Taking_Length - Misaligned; Taking_Length := Taking_Length - Taking_Length rem Buffer_Length; Taking_Length := Taking_Length + Misaligned; end if; end; end if; if Taking_Length > 0 then declare Written_Length : Stream_Element_Offset; begin System.Native_IO.Write ( File.Handle, Item (First)'Address, Taking_Length, Written_Length); if Written_Length < 0 then Raise_Exception (Device_Error'Identity); end if; end; First := First + Taking_Length; -- update indexes if Buffer_Length > 0 then File.Buffer_Index := (File.Buffer_Index + Taking_Length) rem Buffer_Length; File.Reading_Index := File.Buffer_Index; File.Writing_Index := File.Buffer_Index; end if; end if; end; if First <= Item'Last and then Buffer_Length > 0 then Ready_Writing_Buffer (File); declare Temp_Last : Stream_Element_Offset; begin Write_To_Buffer (File, Item (First .. Item'Last), Temp_Last); end; end if; end; end Write; procedure Set_Index ( File : not null Non_Controlled_File_Type; To : Stream_Element_Positive_Count) is Dummy_New_Index : Stream_Element_Offset; Z_Index : constant Stream_Element_Offset := To - 1; -- zero based begin Flush_Writing_Buffer (File); if (File.Mode and System.Native_IO.Append_Mode) /= 0 then System.Native_IO.Unset ( File.Handle, Mask => not System.Native_IO.Append_Mode); end if; System.Native_IO.Set_Relative_Index ( File.Handle, Z_Index, System.Native_IO.From_Begin, Dummy_New_Index); Set_Buffer_Index (File, Z_Index); end Set_Index; function Index (File : not null Non_Controlled_File_Type) return Stream_Element_Positive_Count is begin return System.Native_IO.Index (File.Handle) + Offset_Of_Buffer (File); end Index; function Size (File : not null Non_Controlled_File_Type) return Stream_Element_Count is begin Flush_Writing_Buffer (File); return System.Native_IO.Size (File.Handle); end Size; procedure Set_Mode ( File : aliased in out Non_Controlled_File_Type; Mode : IO_Modes.File_Mode) is pragma Check (Pre, Check => Is_Open (File) or else raise Status_Error); package Holder is new Exceptions.Finally.Scoped_Holder ( Scoped_Handle_And_File_And_Name, Finally); Scoped : aliased Scoped_Handle_And_File_And_Name := (System.Native_IO.Invalid_Handle, null, null, File.Closer); Current : Stream_Element_Positive_Count; Native_Mode : System.Native_IO.File_Mode; begin Holder.Assign (Scoped); Native_Mode := To_Native_Mode (Mode); case File.all.Kind is when Ordinary => Get_Full_Name (File); Scoped.Handle := File.Handle; Scoped.File := File; Scoped.Name := File.Name; File := null; Current := Index (Scoped.File); Flush_Writing_Buffer (Scoped.File); -- close explicitly in below Scoped.Handle := System.Native_IO.Invalid_Handle; System.Native_IO.Close_Ordinary ( Scoped.File.Handle, Scoped.File.Name, Raise_On_Error => True); System.Native_IO.Open_Ordinary ( Method => System.Native_IO.Reset, Handle => Scoped.Handle, Mode => Native_Mode, Name => Scoped.File.Name, Form => Scoped.File.Form); Scoped.File.Handle := Scoped.Handle; Scoped.File.Mode := Native_Mode; when Temporary => Scoped.Handle := File.Handle; Scoped.File := File; Scoped.Name := File.Name; File := null; Current := Index (Scoped.File); Flush_Writing_Buffer (Scoped.File); Scoped.File.Mode := Native_Mode; when External | External_No_Close | Standard_Handle => pragma Check (Pre, Boolean'(raise Status_Error)); unreachable; end case; if (Native_Mode and System.Native_IO.Append_Mode) /= 0 then Set_Index_To_Append (Scoped.File); else Set_Index (Scoped.File, Current); end if; File := Scoped.File; -- complete Holder.Clear; end Set_Mode; procedure Flush (File : not null Non_Controlled_File_Type) is begin Flush_Writing_Buffer (File); System.Native_IO.Flush (File.Handle); end Flush; procedure Flush_Writing_Buffer ( File : not null Non_Controlled_File_Type; Raise_On_Error : Boolean := True) is begin if File.Writing_Index > File.Buffer_Index then declare Error : Boolean := False; Written_Length : Stream_Element_Offset; begin System.Native_IO.Write ( File.Handle, File.Buffer + System.Storage_Elements.Storage_Offset (File.Buffer_Index), File.Writing_Index - File.Buffer_Index, Written_Length); if Written_Length < 0 then if Raise_On_Error then Raise_Exception (Device_Error'Identity); end if; Error := True; end if; if not Error then File.Buffer_Index := File.Writing_Index rem Stream_Element_Positive_Count'(File.Buffer_Length); File.Writing_Index := File.Buffer_Index; File.Reading_Index := File.Buffer_Index; end if; end; end if; end Flush_Writing_Buffer; -- implementation of handle for non-controlled procedure Open ( File : in out Non_Controlled_File_Type; Mode : IO_Modes.File_Mode; Handle : System.Native_IO.Handle_Type; Name : String := ""; Form : System.Native_IO.Packed_Form := Default_Form; To_Close : Boolean := False) is pragma Check (Pre, Check => not Is_Open (File) or else raise Status_Error); begin Allocate_External ( File => File, Mode => To_Native_Mode (Mode), Handle => Handle, Name => Name, Form => Form, To_Close => To_Close); end Open; procedure Open ( File : in out Non_Controlled_File_Type; Mode : IO_Modes.Inout_File_Mode; Handle : System.Native_IO.Handle_Type; Name : String := ""; Form : System.Native_IO.Packed_Form := Default_Form; To_Close : Boolean := False) is pragma Check (Pre, Check => not Is_Open (File) or else raise Status_Error); begin Allocate_External ( File => File, Mode => Inout_To_Native_Mode (Mode), Handle => Handle, Name => Name, Form => Form, To_Close => To_Close); end Open; function Handle (File : not null Non_Controlled_File_Type) return System.Native_IO.Handle_Type is begin return File.Handle; end Handle; function Is_Standard (File : not null Non_Controlled_File_Type) return Boolean is begin return File.Kind = Standard_Handle; end Is_Standard; package body Dispatchers is overriding procedure Read ( Stream : in out Root_Dispatcher; Item : out Stream_Element_Array; Last : out Stream_Element_Offset) is pragma Check (Pre, Check => (Stream.File.Mode and System.Native_IO.Read_Write_Mask) /= System.Native_IO.Write_Only_Mode or else raise Mode_Error); begin Read (Stream.File, Item, Last); end Read; overriding procedure Write ( Stream : in out Root_Dispatcher; Item : Stream_Element_Array) is pragma Check (Pre, Check => (Stream.File.Mode and System.Native_IO.Read_Write_Mask) /= System.Native_IO.Read_Only_Mode or else raise Mode_Error); begin Write (Stream.File, Item); end Write; overriding procedure Read ( Stream : in out Seekable_Dispatcher; Item : out Stream_Element_Array; Last : out Stream_Element_Offset) is pragma Check (Pre, Check => (Stream.File.Mode and System.Native_IO.Read_Write_Mask) /= System.Native_IO.Write_Only_Mode or else raise Mode_Error); begin Read (Stream.File, Item, Last); end Read; overriding procedure Write ( Stream : in out Seekable_Dispatcher; Item : Stream_Element_Array) is pragma Check (Pre, Check => (Stream.File.Mode and System.Native_IO.Read_Write_Mask) /= System.Native_IO.Read_Only_Mode or else raise Mode_Error); begin Write (Stream.File, Item); end Write; overriding procedure Set_Index ( Stream : in out Seekable_Dispatcher; To : Stream_Element_Positive_Count) is begin Set_Index (Stream.File, To); end Set_Index; overriding function Index (Stream : Seekable_Dispatcher) return Stream_Element_Positive_Count is begin return Index (Stream.File); end Index; overriding function Size (Stream : Seekable_Dispatcher) return Stream_Element_Count is begin return Size (Stream.File); end Size; end Dispatchers; end Ada.Streams.Naked_Stream_IO;
----------------------------------------------------------------------- -- keystore-repository-data -- Data access and management for the keystore -- 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 Interfaces; with Util.Log.Loggers; with Keystore.Logs; with Keystore.Repository.Workers; -- === Data Block === -- -- Data block start is encrypted with wallet data key, data fragments are -- encrypted with their own key. Loading and saving data blocks occurs exclusively -- from the workers package. The data block can be stored in a separate file so that -- the wallet repository and its keys are separate from the data blocks. -- -- ``` -- +------------------+ -- | 03 03 | 2b -- | Encrypt size | 2b = DATA_ENTRY_SIZE * Nb data fragment -- | Wallet id | 4b -- | PAD 0 | 4b -- | PAD 0 | 4b -- +------------------+----- -- | Entry ID | 4b Encrypted with wallet id -- | Slot size | 2b -- | 0 0 | 2b -- | Data offset | 8b -- | Content HMAC-256 | 32b => 48b = DATA_ENTRY_SIZE -- +------------------+ -- | ... | -- +------------------+----- -- | ... | -- +------------------+ -- | Data content | Encrypted with data entry key -- +------------------+----- -- | Block HMAC-256 | 32b -- +------------------+ -- ``` -- package body Keystore.Repository.Data is use type Interfaces.Unsigned_64; use type Keystore.Repository.Workers.Data_Work_Access; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Keystore.Repository.Data"); -- ------------------------------ -- Find the data block to hold a new data entry that occupies the given space. -- The first data block that has enough space is used otherwise a new block -- is allocated and initialized. -- ------------------------------ procedure Allocate_Data_Block (Manager : in out Wallet_Repository; Space : in IO.Block_Index; Work : in Workers.Data_Work_Access) is pragma Unreferenced (Space); begin Manager.Stream.Allocate (IO.DATA_BLOCK, Work.Data_Block); Work.Data_Need_Setup := True; Logs.Debug (Log, "Allocated data block{0}", Work.Data_Block); end Allocate_Data_Block; -- ------------------------------ -- Write the data in one or several blocks. -- ------------------------------ procedure Add_Data (Manager : in out Wallet_Repository; Iterator : in out Keys.Data_Key_Iterator; Content : in Ada.Streams.Stream_Element_Array; Offset : in out Interfaces.Unsigned_64) is Size : IO.Buffer_Size; Input_Pos : Stream_Element_Offset := Content'First; Data_Offset : Stream_Element_Offset := Stream_Element_Offset (Offset); Work : Workers.Data_Work_Access; begin Workers.Initialize_Queue (Manager); while Input_Pos <= Content'Last loop -- Get a data work instance or flush pending works to make one available. Workers.Allocate_Work (Manager, Workers.DATA_ENCRYPT, null, Iterator, Work); Workers.Fill (Work.all, Content, Input_Pos, Size); if Size = 0 then Workers.Put_Work (Manager.Workers.all, Work); Work := null; exit; end if; Allocate_Data_Block (Manager, Size, Work); Keys.Allocate_Key_Slot (Manager, Iterator, Work.Data_Block, Size, Work.Key_Pos, Work.Key_Block.Buffer.Block); Work.Key_Block.Buffer := Iterator.Current.Buffer; Workers.Queue_Cipher_Work (Manager, Work); Work := null; -- Move on to what remains. Data_Offset := Data_Offset + Size; Input_Pos := Input_Pos + Size; end loop; Offset := Interfaces.Unsigned_64 (Data_Offset); Workers.Flush_Queue (Manager, null); exception when E : others => Log.Error ("Exception while encrypting data: ", E); if Work /= null then Workers.Put_Work (Manager.Workers.all, Work); end if; Workers.Flush_Queue (Manager, null); raise; end Add_Data; -- ------------------------------ -- Write the data in one or several blocks. -- ------------------------------ procedure Add_Data (Manager : in out Wallet_Repository; Iterator : in out Keys.Data_Key_Iterator; Content : in out Util.Streams.Input_Stream'Class; Offset : in out Interfaces.Unsigned_64) is Size : IO.Buffer_Size; Data_Offset : Stream_Element_Offset := Stream_Element_Offset (Offset); Work : Workers.Data_Work_Access; begin Workers.Initialize_Queue (Manager); loop -- Get a data work instance or flush pending works to make one available. Workers.Allocate_Work (Manager, Workers.DATA_ENCRYPT, null, Iterator, Work); -- Fill the work buffer by reading the stream. Workers.Fill (Work.all, Content, DATA_MAX_SIZE, Size); if Size = 0 then Workers.Put_Work (Manager.Workers.all, Work); exit; end if; Allocate_Data_Block (Manager, DATA_MAX_SIZE, Work); Keys.Allocate_Key_Slot (Manager, Iterator, Work.Data_Block, Size, Work.Key_Pos, Work.Key_Block.Buffer.Block); Work.Key_Block.Buffer := Iterator.Current.Buffer; Workers.Queue_Cipher_Work (Manager, Work); -- Move on to what remains. Data_Offset := Data_Offset + Size; end loop; Offset := Interfaces.Unsigned_64 (Data_Offset); Workers.Flush_Queue (Manager, null); exception when E : others => Log.Error ("Exception while encrypting data: ", E); Workers.Flush_Queue (Manager, null); raise; end Add_Data; procedure Update_Data (Manager : in out Wallet_Repository; Iterator : in out Keys.Data_Key_Iterator; Content : in Ada.Streams.Stream_Element_Array; Last_Pos : out Ada.Streams.Stream_Element_Offset; Offset : in out Interfaces.Unsigned_64) is Size : Stream_Element_Offset; Input_Pos : Stream_Element_Offset := Content'First; Work : Workers.Data_Work_Access; Data_Offset : Stream_Element_Offset := Stream_Element_Offset (Offset); begin Workers.Initialize_Queue (Manager); Keys.Next_Data_Key (Manager, Iterator); while Input_Pos <= Content'Last and Keys.Has_Data_Key (Iterator) loop Workers.Allocate_Work (Manager, Workers.DATA_ENCRYPT, null, Iterator, Work); Size := Content'Last - Input_Pos + 1; if Size > DATA_MAX_SIZE then Size := DATA_MAX_SIZE; end if; if Size > AES_Align (Iterator.Data_Size) then Size := AES_Align (Iterator.Data_Size); end if; Work.Buffer_Pos := 1; Work.Last_Pos := Size; Work.Data (1 .. Size) := Content (Input_Pos .. Input_Pos + Size - 1); Keys.Update_Key_Slot (Manager, Iterator, Size); Work.Key_Block.Buffer := Iterator.Current.Buffer; -- Run the encrypt data work either through work manager or through current task. Workers.Queue_Cipher_Work (Manager, Work); Input_Pos := Input_Pos + Size; Data_Offset := Data_Offset + Size; exit when Input_Pos > Content'Last; Keys.Next_Data_Key (Manager, Iterator); end loop; Workers.Flush_Queue (Manager, null); Offset := Interfaces.Unsigned_64 (Data_Offset); Last_Pos := Input_Pos; if Input_Pos <= Content'Last then Keys.Prepare_Append (Iterator); end if; exception when E : others => Log.Error ("Exception while encrypting data: ", E); Workers.Flush_Queue (Manager, null); raise; end Update_Data; procedure Update_Data (Manager : in out Wallet_Repository; Iterator : in out Keys.Data_Key_Iterator; Content : in out Util.Streams.Input_Stream'Class; End_Of_Stream : out Boolean; Offset : in out Interfaces.Unsigned_64) is Work : Workers.Data_Work_Access; Size : IO.Buffer_Size := 0; Data_Offset : Stream_Element_Offset := Stream_Element_Offset (Offset); Mark : Keys.Data_Key_Marker; begin Workers.Initialize_Queue (Manager); Keys.Mark_Data_Key (Iterator, Mark); Keys.Next_Data_Key (Manager, Iterator); while Keys.Has_Data_Key (Iterator) loop Workers.Allocate_Work (Manager, Workers.DATA_ENCRYPT, null, Iterator, Work); -- Fill the work buffer by reading the stream. Workers.Fill (Work.all, Content, AES_Align (Iterator.Data_Size), Size); if Size = 0 then Workers.Put_Work (Manager.Workers.all, Work); Delete_Data (Manager, Iterator, Mark); exit; end if; Keys.Update_Key_Slot (Manager, Iterator, Size); Work.Key_Block.Buffer := Iterator.Current.Buffer; -- Run the encrypt data work either through work manager or through current task. Workers.Queue_Cipher_Work (Manager, Work); Data_Offset := Data_Offset + Size; Keys.Mark_Data_Key (Iterator, Mark); Keys.Next_Data_Key (Manager, Iterator); end loop; Workers.Flush_Queue (Manager, null); Offset := Interfaces.Unsigned_64 (Data_Offset); End_Of_Stream := Size = 0; if not End_Of_Stream then Keys.Prepare_Append (Iterator); end if; exception when E : others => Log.Error ("Exception while encrypting data: ", E); Workers.Flush_Queue (Manager, null); raise; end Update_Data; -- ------------------------------ -- Erase the data fragments starting at the key iterator current position. -- ------------------------------ procedure Delete_Data (Manager : in out Wallet_Repository; Iterator : in out Keys.Data_Key_Iterator; Mark : in out Keys.Data_Key_Marker) is Work : Workers.Data_Work_Access; begin while Keys.Has_Data_Key (Iterator) loop Workers.Allocate_Work (Manager, Workers.DATA_RELEASE, null, Iterator, Work); -- Run the delete data work either through work manager or through current task. Workers.Queue_Delete_Work (Manager, Work); -- When the last data block was processed, erase the data key. if Keys.Is_Last_Key (Iterator) then Keys.Delete_Key (Manager, Iterator, Mark); end if; Keys.Next_Data_Key (Manager, Iterator); end loop; end Delete_Data; -- ------------------------------ -- Erase the data fragments starting at the key iterator current position. -- ------------------------------ procedure Delete_Data (Manager : in out Wallet_Repository; Iterator : in out Keys.Data_Key_Iterator) is Work : Workers.Data_Work_Access; Mark : Keys.Data_Key_Marker; begin Keys.Mark_Data_Key (Iterator, Mark); Workers.Initialize_Queue (Manager); loop Keys.Next_Data_Key (Manager, Iterator); exit when not Keys.Has_Data_Key (Iterator); Workers.Allocate_Work (Manager, Workers.DATA_RELEASE, null, Iterator, Work); -- Run the delete data work either through work manager or through current task. Workers.Queue_Delete_Work (Manager, Work); -- When the last data block was processed, erase the data key. if Keys.Is_Last_Key (Iterator) then Keys.Delete_Key (Manager, Iterator, Mark); end if; end loop; Workers.Flush_Queue (Manager, null); exception when E : others => Log.Error ("Exception while deleting data: ", E); Workers.Flush_Queue (Manager, null); raise; end Delete_Data; -- ------------------------------ -- Get the data associated with the named entry. -- ------------------------------ procedure Get_Data (Manager : in out Wallet_Repository; Iterator : in out Keys.Data_Key_Iterator; Output : out Ada.Streams.Stream_Element_Array) is procedure Process (Work : in Workers.Data_Work_Access); Data_Offset : Stream_Element_Offset := Output'First; procedure Process (Work : in Workers.Data_Work_Access) is Data_Size : constant Stream_Element_Offset := Work.End_Data - Work.Start_Data + 1; begin Output (Data_Offset .. Data_Offset + Data_Size - 1) := Work.Data (Work.Buffer_Pos .. Work.Buffer_Pos + Data_Size - 1); Data_Offset := Data_Offset + Data_Size; end Process; Work : Workers.Data_Work_Access; Enqueued : Boolean; begin Workers.Initialize_Queue (Manager); loop Keys.Next_Data_Key (Manager, Iterator); exit when not Keys.Has_Data_Key (Iterator); Workers.Allocate_Work (Manager, Workers.DATA_DECRYPT, Process'Access, Iterator, Work); -- Run the decipher work either through work manager or through current task. Workers.Queue_Decipher_Work (Manager, Work, Enqueued); if not Enqueued then Process (Work); end if; end loop; Workers.Flush_Queue (Manager, Process'Access); exception when E : others => Log.Error ("Exception while decrypting data: ", E); Workers.Flush_Queue (Manager, null); raise; end Get_Data; procedure Get_Data (Manager : in out Wallet_Repository; Iterator : in out Keys.Data_Key_Iterator; Output : in out Util.Streams.Output_Stream'Class) is procedure Process (Work : in Workers.Data_Work_Access); procedure Process (Work : in Workers.Data_Work_Access) is begin Output.Write (Work.Data (Work.Buffer_Pos .. Work.Last_Pos)); end Process; Work : Workers.Data_Work_Access; Enqueued : Boolean; begin Workers.Initialize_Queue (Manager); loop Keys.Next_Data_Key (Manager, Iterator); exit when not Keys.Has_Data_Key (Iterator); Workers.Allocate_Work (Manager, Workers.DATA_DECRYPT, Process'Access, Iterator, Work); -- Run the decipher work either through work manager or through current task. Workers.Queue_Decipher_Work (Manager, Work, Enqueued); if not Enqueued then Process (Work); end if; end loop; Workers.Flush_Queue (Manager, Process'Access); exception when E : others => Log.Error ("Exception while decrypting data: ", E); Workers.Flush_Queue (Manager, null); raise; end Get_Data; -- ------------------------------ -- Get the data associated with the named entry. -- ------------------------------ procedure Read (Manager : in out Wallet_Repository; Iterator : in out Keys.Data_Key_Iterator; Offset : in Ada.Streams.Stream_Element_Offset; Output : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is procedure Process (Work : in Workers.Data_Work_Access); Seek_Offset : Stream_Element_Offset := Offset; Data_Offset : Stream_Element_Offset := Output'First; procedure Process (Work : in Workers.Data_Work_Access) is Data_Size : Stream_Element_Offset := Work.End_Data - Work.Start_Data + 1 - Work.Seek_Offset; begin Work.Buffer_Pos := Work.Buffer_Pos + Work.Seek_Offset; if Data_Offset + Data_Size - 1 >= Output'Last then Data_Size := Output'Last - Data_Offset + 1; end if; Output (Data_Offset .. Data_Offset + Data_Size - 1) := Work.Data (Work.Buffer_Pos .. Work.Buffer_Pos + Data_Size - 1); Data_Offset := Data_Offset + Data_Size; end Process; Work : Workers.Data_Work_Access; Enqueued : Boolean; Length : Stream_Element_Offset := Output'Length; begin Workers.Initialize_Queue (Manager); Keys.Seek (Manager, Seek_Offset, Iterator); Length := Length + Seek_Offset; while Keys.Has_Data_Key (Iterator) and Length > 0 loop Workers.Allocate_Work (Manager, Workers.DATA_DECRYPT, Process'Access, Iterator, Work); Work.Seek_Offset := Seek_Offset; -- Run the decipher work either through work manager or through current task. Workers.Queue_Decipher_Work (Manager, Work, Enqueued); if not Enqueued then Process (Work); end if; exit when Length < Iterator.Data_Size; Length := Length - Iterator.Data_Size; Seek_Offset := 0; Keys.Next_Data_Key (Manager, Iterator); end loop; Workers.Flush_Queue (Manager, Process'Access); Last := Data_Offset - 1; exception when E : others => Log.Error ("Exception while decrypting data: ", E); Workers.Flush_Queue (Manager, null); raise; end Read; -- ------------------------------ -- Get the data associated with the named entry. -- ------------------------------ procedure Write (Manager : in out Wallet_Repository; Iterator : in out Keys.Data_Key_Iterator; Offset : in Ada.Streams.Stream_Element_Offset; Content : in Ada.Streams.Stream_Element_Array; Result : in out Interfaces.Unsigned_64) is use type Workers.Status_Type; Seek_Offset : Stream_Element_Offset := Offset; Input_Pos : Stream_Element_Offset := Content'First; Work : Workers.Data_Work_Access; Length : Stream_Element_Offset := Content'Length; Status : Workers.Status_Type; begin Workers.Initialize_Queue (Manager); Keys.Seek (Manager, Seek_Offset, Iterator); -- First part that overlaps an existing data block: -- read the current block, update the content. if Keys.Has_Data_Key (Iterator) and Length > 0 then Workers.Allocate_Work (Manager, Workers.DATA_DECRYPT, null, Iterator, Work); -- Run the decipher work ourselves. Work.Do_Decipher_Data; Status := Work.Status; if Status = Workers.SUCCESS then declare Data_Size : Stream_Element_Offset := Work.End_Data - Work.Start_Data + 1 - Seek_Offset; Pos : constant Stream_Element_Offset := Work.Buffer_Pos + Seek_Offset; begin if Input_Pos + Data_Size - 1 >= Content'Last then Data_Size := Content'Last - Input_Pos + 1; end if; Work.Data (Pos .. Pos + Data_Size - 1) := Content (Input_Pos .. Input_Pos + Data_Size - 1); Input_Pos := Input_Pos + Data_Size; Work.Kind := Workers.DATA_ENCRYPT; Work.Status := Workers.PENDING; Work.Entry_Id := Iterator.Entry_Id; Work.Key_Pos := Iterator.Key_Pos; Work.Key_Block.Buffer := Iterator.Current.Buffer; Work.Data_Block := Iterator.Data_Block; Work.Data_Need_Setup := False; Work.Data_Offset := Iterator.Current_Offset; Length := Length - Data_Size; Keys.Update_Key_Slot (Manager, Iterator, Work.End_Data - Work.Start_Data + 1); end; -- Run the encrypt data work either through work manager or through current task. Workers.Queue_Cipher_Work (Manager, Work); else Workers.Put_Work (Manager.Workers.all, Work); -- Check_Raise_Error (Status); end if; Keys.Next_Data_Key (Manager, Iterator); end if; while Keys.Has_Data_Key (Iterator) and Length >= DATA_MAX_SIZE loop Workers.Allocate_Work (Manager, Workers.DATA_ENCRYPT, null, Iterator, Work); Work.Buffer_Pos := 1; Work.Last_Pos := DATA_MAX_SIZE; Work.Data (1 .. DATA_MAX_SIZE) := Content (Input_Pos .. Input_Pos + DATA_MAX_SIZE - 1); Keys.Update_Key_Slot (Manager, Iterator, DATA_MAX_SIZE); Work.Key_Block.Buffer := Iterator.Current.Buffer; -- Run the encrypt data work either through work manager or through current task. Workers.Queue_Cipher_Work (Manager, Work); Input_Pos := Input_Pos + DATA_MAX_SIZE; -- Data_Offset := Data_Offset + DATA_MAX_SIZE; Length := Length - DATA_MAX_SIZE; exit when Input_Pos > Content'Last; Keys.Next_Data_Key (Manager, Iterator); end loop; -- Last part that overlaps an existing data block: -- read the current block, update the content. if Keys.Has_Data_Key (Iterator) and Length > 0 then Workers.Allocate_Work (Manager, Workers.DATA_DECRYPT, null, Iterator, Work); -- Run the decipher work ourselves. Work.Do_Decipher_Data; Status := Work.Status; if Status = Workers.SUCCESS then declare Last : constant Stream_Element_Offset := Content'Last - Input_Pos + 1; begin Work.Data (1 .. Last) := Content (Input_Pos .. Content'Last); Input_Pos := Content'Last + 1; if Last > Work.End_Data then Work.End_Data := Last; end if; Work.Kind := Workers.DATA_ENCRYPT; Work.Status := Workers.PENDING; Work.Entry_Id := Iterator.Entry_Id; Work.Key_Pos := Iterator.Key_Pos; Work.Key_Block.Buffer := Iterator.Current.Buffer; Work.Data_Block := Iterator.Data_Block; Work.Data_Need_Setup := False; Work.Data_Offset := Iterator.Current_Offset; Keys.Update_Key_Slot (Manager, Iterator, Work.End_Data - Work.Start_Data + 1); end; -- Run the encrypt data work either through work manager or through current task. Workers.Queue_Cipher_Work (Manager, Work); else Workers.Put_Work (Manager.Workers.all, Work); -- Check_Raise_Error (Status); end if; Keys.Next_Data_Key (Manager, Iterator); end if; Workers.Flush_Queue (Manager, null); Result := Iterator.Current_Offset; if Input_Pos <= Content'Last then Keys.Prepare_Append (Iterator); Add_Data (Manager, Iterator, Content (Input_Pos .. Content'Last), Result); end if; exception when E : others => Log.Error ("Exception while decrypting data: ", E); Workers.Flush_Queue (Manager, null); raise; end Write; end Keystore.Repository.Data;
with Ada.Text_IO; use Ada.Text_IO; procedure Test is begin Put('A'); New_Line; end;
with Ada.Text_IO; with Ada.Numerics.Generic_Elementary_Functions; with Thiele; procedure Main is package Math is new Ada.Numerics.Generic_Elementary_Functions (Long_Float); package Float_Thiele is new Thiele (Long_Float); use Float_Thiele; Row_Count : Natural := 32; X_Values : Real_Array (1 .. Row_Count); Sin_Values : Real_Array (1 .. Row_Count); Cos_Values : Real_Array (1 .. Row_Count); Tan_Values : Real_Array (1 .. Row_Count); begin -- build table for I in 1 .. Row_Count loop X_Values (I) := Long_Float (I) * 0.05 - 0.05; Sin_Values (I) := Math.Sin (X_Values (I)); Cos_Values (I) := Math.Cos (X_Values (I)); Tan_Values (I) := Math.Tan (X_Values (I)); end loop; declare Sin : Thiele_Interpolation := Create (Sin_Values, X_Values); Cos : Thiele_Interpolation := Create (Cos_Values, X_Values); Tan : Thiele_Interpolation := Create (Tan_Values, X_Values); begin Ada.Text_IO.Put_Line ("Internal Math.Pi: " & Long_Float'Image (Ada.Numerics.Pi)); Ada.Text_IO.Put_Line ("Thiele 6*InvSin(0.5):" & Long_Float'Image (6.0 * Inverse (Sin, 0.5))); Ada.Text_IO.Put_Line ("Thiele 3*InvCos(0.5):" & Long_Float'Image (3.0 * Inverse (Cos, 0.5))); Ada.Text_IO.Put_Line ("Thiele 4*InvTan(1): " & Long_Float'Image (4.0 * Inverse (Tan, 1.0))); end; end Main;
pragma License (Unrestricted); -- implementation unit package System.Form_Parameters is pragma Preelaborate; -- parsing form parameter -- the format is "keyword1=value1,keyword2=value2,..." procedure Get ( Form : String; Keyword_First : out Positive; Keyword_Last : out Natural; Item_First : out Positive; Item_Last : out Natural; Last : out Natural); end System.Form_Parameters;
----------------------------------------------------------------------- -- package body Crout_LU, LU decomposition, with equation solving -- 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 Runge_Coeffs_pd_5 -- -- Package contains coefficients for the Cash-Karp -- 5th order, 6 stage Runge Kutta method with error control. -- -- A test routine is provided to make make sure that they -- have not been corrupted. If the coefficients do not pass -- the tests, then they are given in redundant and alternate -- forms at the end of this package (commented out). -- -- NOTES ON THE ALGORITHM -- -- Given a differential equ. dY/dt = F(t,Y) and an initial condition -- Y(t), the Runge-Kutta formulas predict a new value of Y at -- Y(t + h) with the formula -- -- max -- Y(t + h) = Y(t) + SUM (K(j) * B(j)) -- j=1 -- -- where max = Stages'Last, (which equals 13 here, since this is a 13 -- stage Runge-Kutta formula) where the quantities K are calculated from -- -- K(1) = h * F(t, Y(t)) -- -- j-1 -- K(j) = h * F (t + C(j)*h, Y(t) + SUM (K(i)*A(j,i)) ) -- i=1 -- -- The Fehberg method, used here, provides two versions of the array -- B, so that Y(t + h) may be calculated to both 7th order and to -- 8th order using the same K(i)'s. This way, the local truncation -- error can be estimated without calculating the K(i)'s twice. -- -- If we apply this formula to a time-independent linear F, then we can -- derive a condition that can be used to test the correctness of the -- initialization values of the arrays A, B and C. To derive such a -- formula we use the fact that the RK prediction of Y(t + h) must equal -- the Taylor series prediction up to the required order. So, -- -- K(1) = h*F*Y (where F now is a matrix, and Y a vector) -- -- K(2) = h*F*(Y + K(1)*A21) -- -- K(3) = h*F*(Y + K(1)*A31 + K(2)*A32) -- -- K(4) = h*F*(Y + K(1)*A41 + K(2)*A42 + K(3)*A43) -- -- The linearity of F implies that F(a*Y + Z) = a*F*Y + F*Z so: -- -- K(1) = h*F*Y -- -- K(2) = h*F*Y + A21*h^2*F^2*Y -- -- K(3) = h*F*Y + (A31 + A32)*h^2*F^2*Y + A32*A21*h^3*F^3*Y -- -- K(4) = h*F*Y + (A41+A42+A43)*h^2*F^2*Y + (A42*A21+A43*A31)h^3*F^3*Y -- + A43*A32*A21*h^4F^4*Y -- -- Now we use the fact that we must have the RK prediction equal that -- of the Taylor's series up to a certain order: -- -- max -- SUM (K(j) * B(j)) = h*F*Y + ... + (1/n!)*h^n*F^n*Y + O(h^n+1) -- j=1 -- -- Here n=8 for the coefficients B = B8 given below. Its n=7 for B7. -- The above formula gives us a relation between 1/n! and B and A. -- This formula is used in the procedure TestRKPD given at the end -- of this package. We see immediately that we must have: -- -- max -- SUM (B(i)) = 1/1! -- i=1 -- -- max i-1 -- SUM (B(i) * SUM(Aij)) = 1/2! -- i=2 j=1 -- generic type Real is digits <>; package Runge_Coeffs_pd_5 is subtype RK_Range is Integer range 0..6; subtype Stages is RK_Range range 0..6; -- always 0 .. 6 type Coefficient is array(RK_Range) of Real; type Coefficient_Array is array(RK_Range) of Coefficient; procedure Test_Runge_Coeffs; A_rational : constant Coefficient_Array := ( (others => 0.0), (1.0/5.0, others => 0.0), (3.0/40.0, 9.0/40.0, others => 0.0), (44.0/45.0, -56.0/15.0, 32.0/9.0, others => 0.0), (19372.0/6561.0, -25360.0/2187.0, 64448.0/6561.0, -212.0/729.0, others => 0.0), (9017.0/3168.0, -355.0/33.0, 46732.0/5247.0, 49.0/176.0, -5103.0/18656.0, 0.0, 0.0), (35.0/384.0, 0.0, 500.0/1113.0, 125.0/192.0, -2187.0/6784.0, 11.0/84.0, 0.0) ); -- 4rth order: B4_rational : constant Coefficient := ( 5179.0/57600.0, 0.0, 7571.0/16695.0, 393.0/640.0, -92097.0/339200.0, 187.0/2100.0, 1.0/40.0 ); -- 5th order: B5_rational : constant Coefficient := ( 35.0/384.0, 0.0, 500.0/1113.0, 125.0/192.0, -2187.0/6784.0, 11.0/84.0, 0.0 ); -- coefficients C for getting Dt C_rational : constant Coefficient := ( 0.0, 1.0/5.0, 3.0/10.0, 4.0/5.0, 8.0/9.0, 1.0, 1.0 ); C : Coefficient renames C_rational; B4 : Coefficient renames B4_rational; B5 : Coefficient renames B5_rational; A : Coefficient_Array renames A_rational; end Runge_Coeffs_pd_5;
package Volatile12 is type Arr is array (Integer range <>) of Integer with Volatile; procedure Proc (A : Arr); end Volatile12;
pragma Ada_2012; package body String_Sets is ------------------- -- To_Set_String -- ------------------- function To_Set_String (X : String) return Set_String is Result : Set_String (X'Range); begin for K in X'Range loop Result (K) := To_Set (X (K)); end loop; return Result; end To_Set_String; ----------- -- Match -- ----------- function Match (X : String; Pattern : Set_String) return Boolean is begin if X'Length < Pattern'Length then return False; end if; for K in Pattern'Range loop if not Is_In (X (K - Pattern'First + X'First), Pattern (K)) then return False; end if; end loop; return True; end Match; end String_Sets;
-- -- Copyright (C) 2013 Reto Buerki <reet@codelabs.ch> -- Copyright (C) 2013 Adrian-Ken Rueegsegger <ken@codelabs.ch> -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions -- are met: -- 1. Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- 2. Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- 3. Neither the name of the University 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 REGENTS 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 REGENTS OR CONTRIBUTORS BE LIABLE -- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS -- OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -- LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -- OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -- SUCH DAMAGE. -- with Interfaces.C.Strings; with GNAT.OS_Lib; with Anet.Util; with Anet.Sockets.Unix; with Anet.Receivers.Stream; with Tkmrpc.Types; with Tkmrpc.Clients.Ike; with Tkmrpc.Dispatchers.Ike; with Tkmrpc.Mock; with Tkmrpc.Results; with Tkmrpc.Process_Stream; pragma Elaborate_All (Anet.Receivers.Stream); pragma Elaborate_All (Tkmrpc.Process_Stream); package body Tkmrpc_ORB_Tests is use Ahven; use Tkmrpc; package ICS renames Interfaces.C.Strings; package Unix_TCP_Receiver is new Anet.Receivers.Stream (Socket_Type => Anet.Sockets.Unix.TCP_Socket_Type, Address_Type => Anet.Sockets.Unix.Full_Path_Type, Accept_Connection => Anet.Sockets.Unix.Accept_Connection); procedure Dispatch is new Process_Stream (Address_Type => Anet.Sockets.Unix.Full_Path_Type, Dispatch => Tkmrpc.Dispatchers.Ike.Dispatch); Socket_Path : constant String := "/tmp/tkm.rpc-"; ------------------------------------------------------------------------- procedure C_Test_Client is use type Tkmrpc.Types.Nc_Id_Type; use type Tkmrpc.Types.Nonce_Length_Type; Sock : aliased Anet.Sockets.Unix.TCP_Socket_Type; Receiver : Unix_TCP_Receiver.Receiver_Type (S => Sock'Access); Args : GNAT.OS_Lib.Argument_List (1 .. 1); Success : Boolean := False; Path : constant String := Socket_Path & Anet.Util.Random_String (Len => 8); begin Sock.Init; Sock.Bind (Path => Anet.Sockets.Unix.Path_Type (Path)); Receiver.Listen (Callback => Dispatch'Access); Args (1) := new String'(Path); GNAT.OS_Lib.Spawn (Program_Name => "./client", Args => Args, Success => Success); GNAT.OS_Lib.Free (X => Args (1)); Assert (Condition => Success, Message => "Spawning client failed"); -- The C test client requests a nonce with id 1 and length 128. Assert (Condition => Mock.Last_Nonce_Id = 1, Message => "Last nonce id mismatch"); Assert (Condition => Mock.Last_Nonce_Length = 128, Message => "Last nonce length mismatch"); Receiver.Stop; Mock.Last_Nonce_Id := Types.Nc_Id_Type'Last; Mock.Last_Nonce_Length := 16; exception when others => Receiver.Stop; Mock.Last_Nonce_Id := Types.Nc_Id_Type'Last; Mock.Last_Nonce_Length := 16; raise; end C_Test_Client; ------------------------------------------------------------------------- procedure Client_Server_ORBs is use type Tkmrpc.Types.Nonce_Type; use type Tkmrpc.Types.Nonce_Length_Type; use type Tkmrpc.Types.Nc_Id_Type; use type Tkmrpc.Results.Result_Type; Sock : aliased Anet.Sockets.Unix.TCP_Socket_Type; Receiver : Unix_TCP_Receiver.Receiver_Type (S => Sock'Access); Nonce : Types.Nonce_Type; Result : Results.Result_Type; Path : constant String := Socket_Path & Anet.Util.Random_String (Len => 8); Address : ICS.chars_ptr := ICS.New_String (Str => Path); begin Sock.Init; Sock.Bind (Path => Anet.Sockets.Unix.Path_Type (Path)); Receiver.Listen (Callback => Dispatch'Access); Clients.Ike.Init (Result => Result, Address => Address); ICS.Free (Item => Address); Assert (Condition => Result = Results.Ok, Message => "IKE init failed"); Clients.Ike.Nc_Create (Nc_Id => 23, Nonce_Length => 243, Nonce => Nonce, Result => Result); Assert (Condition => Result = Results.Ok, Message => "Remote call failed"); Assert (Condition => Nonce = Mock.Ref_Nonce, Message => "Nonce incorrect"); Assert (Condition => Mock.Last_Nonce_Id = 23, Message => "Last nonce id mismatch"); Assert (Condition => Mock.Last_Nonce_Length = 243, Message => "Last nonce length mismatch"); Receiver.Stop; Mock.Last_Nonce_Id := Types.Nc_Id_Type'Last; Mock.Last_Nonce_Length := 16; exception when others => Receiver.Stop; Mock.Last_Nonce_Id := Types.Nc_Id_Type'Last; Mock.Last_Nonce_Length := 16; raise; end Client_Server_ORBs; ------------------------------------------------------------------------- procedure Initialize (T : in out Testcase) is begin T.Set_Name (Name => "ORB tests"); T.Add_Test_Routine (Routine => Client_Server_ORBs'Access, Name => "Client/server interaction"); T.Add_Test_Routine (Routine => C_Test_Client'Access, Name => "C test client"); end Initialize; end Tkmrpc_ORB_Tests;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- E X P _ F I X D -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2020, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING3. If not, go to -- -- http://www.gnu.org/licenses for a complete copy of the license. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Atree; use Atree; with Checks; use Checks; with Einfo; use Einfo; with Exp_Util; use Exp_Util; with Nlists; use Nlists; with Nmake; use Nmake; with Restrict; use Restrict; with Rident; use Rident; with Rtsfind; use Rtsfind; with Sem; use Sem; with Sem_Eval; use Sem_Eval; with Sem_Res; use Sem_Res; with Sem_Util; use Sem_Util; with Sinfo; use Sinfo; with Snames; use Snames; with Stand; use Stand; with Tbuild; use Tbuild; with Uintp; use Uintp; with Urealp; use Urealp; package body Exp_Fixd is ----------------------- -- Local Subprograms -- ----------------------- -- General note; in this unit, a number of routines are driven by the -- types (Etype) of their operands. Since we are dealing with unanalyzed -- expressions as they are constructed, the Etypes would not normally be -- set, but the construction routines that we use in this unit do in fact -- set the Etype values correctly. In addition, setting the Etype ensures -- that the analyzer does not try to redetermine the type when the node -- is analyzed (which would be wrong, since in the case where we set the -- Conversion_OK flag, it would think it was still dealing with a normal -- fixed-point operation and mess it up). function Build_Conversion (N : Node_Id; Typ : Entity_Id; Expr : Node_Id; Rchk : Boolean := False; Trunc : Boolean := False) return Node_Id; -- Build an expression that converts the expression Expr to type Typ, -- taking the source location from Sloc (N). If the conversions involve -- fixed-point types, then the Conversion_OK flag will be set so that the -- resulting conversions do not get re-expanded. On return the resulting -- node has its Etype set. If Rchk is set, then Do_Range_Check is set -- in the resulting conversion node. If Trunc is set, then the -- Float_Truncate flag is set on the conversion, which must be from -- a floating-point type to an integer type. function Build_Divide (N : Node_Id; L, R : Node_Id) return Node_Id; -- Builds an N_Op_Divide node from the given left and right operand -- expressions, using the source location from Sloc (N). The operands are -- either both Universal_Real, in which case Build_Divide differs from -- Make_Op_Divide only in that the Etype of the resulting node is set (to -- Universal_Real), or they can be integer or fixed-point types. In this -- case the types need not be the same, and Build_Divide chooses a type -- long enough to hold both operands (i.e. the size of the longer of the -- two operand types), and both operands are converted to this type. The -- Etype of the result is also set to this value. The Rounded_Result flag -- of the result in this case is set from the Rounded_Result flag of node -- N. On return, the resulting node is analyzed and has its Etype set. function Build_Double_Divide (N : Node_Id; X, Y, Z : Node_Id) return Node_Id; -- Returns a node corresponding to the value X/(Y*Z) using the source -- location from Sloc (N). The division is rounded if the Rounded_Result -- flag of N is set. The integer types of X, Y, Z may be different. On -- return the resulting node is analyzed, and has its Etype set. procedure Build_Double_Divide_Code (N : Node_Id; X, Y, Z : Node_Id; Qnn, Rnn : out Entity_Id; Code : out List_Id); -- Generates a sequence of code for determining the quotient and remainder -- of the division X/(Y*Z), using the source location from Sloc (N). -- Entities of appropriate types are allocated for the quotient and -- remainder and returned in Qnn and Rnn. The result is rounded if the -- Rounded_Result flag of N is set. The Etype fields of Qnn and Rnn are -- appropriately set on return. function Build_Multiply (N : Node_Id; L, R : Node_Id) return Node_Id; -- Builds an N_Op_Multiply node from the given left and right operand -- expressions, using the source location from Sloc (N). The operands are -- either both Universal_Real, in which case Build_Multiply differs from -- Make_Op_Multiply only in that the Etype of the resulting node is set (to -- Universal_Real), or they can be integer or fixed-point types. In this -- case the types need not be the same, and Build_Multiply chooses a type -- long enough to hold the product (i.e. twice the size of the longer of -- the two operand types), and both operands are converted to this type. -- The Etype of the result is also set to this value. However, the result -- can never overflow Integer_64, so this is the largest type that is ever -- generated. On return, the resulting node is analyzed and has Etype set. function Build_Rem (N : Node_Id; L, R : Node_Id) return Node_Id; -- Builds an N_Op_Rem node from the given left and right operand -- expressions, using the source location from Sloc (N). The operands are -- both integer types, which need not be the same. Build_Rem converts the -- operand with the smaller sized type to match the type of the other -- operand and sets this as the result type. The result is never rounded -- (rem operations cannot be rounded in any case). On return, the resulting -- node is analyzed and has its Etype set. function Build_Scaled_Divide (N : Node_Id; X, Y, Z : Node_Id) return Node_Id; -- Returns a node corresponding to the value X*Y/Z using the source -- location from Sloc (N). The division is rounded if the Rounded_Result -- flag of N is set. The integer types of X, Y, Z may be different. On -- return the resulting node is analyzed and has is Etype set. procedure Build_Scaled_Divide_Code (N : Node_Id; X, Y, Z : Node_Id; Qnn, Rnn : out Entity_Id; Code : out List_Id); -- Generates a sequence of code for determining the quotient and remainder -- of the division X*Y/Z, using the source location from Sloc (N). Entities -- of appropriate types are allocated for the quotient and remainder and -- returned in Qnn and Rrr. The integer types for X, Y, Z may be different. -- The division is rounded if the Rounded_Result flag of N is set. The -- Etype fields of Qnn and Rnn are appropriately set on return. procedure Do_Divide_Fixed_Fixed (N : Node_Id); -- Handles expansion of divide for case of two fixed-point operands -- (neither of them universal), with an integer or fixed-point result. -- N is the N_Op_Divide node to be expanded. procedure Do_Divide_Fixed_Universal (N : Node_Id); -- Handles expansion of divide for case of a fixed-point operand divided -- by a universal real operand, with an integer or fixed-point result. N -- is the N_Op_Divide node to be expanded. procedure Do_Divide_Universal_Fixed (N : Node_Id); -- Handles expansion of divide for case of a universal real operand -- divided by a fixed-point operand, with an integer or fixed-point -- result. N is the N_Op_Divide node to be expanded. procedure Do_Multiply_Fixed_Fixed (N : Node_Id); -- Handles expansion of multiply for case of two fixed-point operands -- (neither of them universal), with an integer or fixed-point result. -- N is the N_Op_Multiply node to be expanded. procedure Do_Multiply_Fixed_Universal (N : Node_Id; Left, Right : Node_Id); -- Handles expansion of multiply for case of a fixed-point operand -- multiplied by a universal real operand, with an integer or fixed- -- point result. N is the N_Op_Multiply node to be expanded, and -- Left, Right are the operands (which may have been switched). procedure Expand_Convert_Fixed_Static (N : Node_Id); -- This routine is called where the node N is a conversion of a literal -- or other static expression of a fixed-point type to some other type. -- In such cases, we simply rewrite the operand as a real literal and -- reanalyze. This avoids problems which would otherwise result from -- attempting to build and fold expressions involving constants. function Fpt_Value (N : Node_Id) return Node_Id; -- Given an operand of fixed-point operation, return an expression that -- represents the corresponding Universal_Real value. The expression -- can be of integer type, floating-point type, or fixed-point type. -- The expression returned is neither analyzed and resolved. The Etype -- of the result is properly set (to Universal_Real). function Integer_Literal (N : Node_Id; V : Uint; Negative : Boolean := False) return Node_Id; -- Given a non-negative universal integer value, build a typed integer -- literal node, using the smallest applicable standard integer type. If -- and only if Negative is true a negative literal is built. If V exceeds -- 2**63-1, the largest value allowed for perfect result set scaling -- factors (see RM G.2.3(22)), then Empty is returned. The node N provides -- the Sloc value for the constructed literal. The Etype of the resulting -- literal is correctly set, and it is marked as analyzed. function Real_Literal (N : Node_Id; V : Ureal) return Node_Id; -- Build a real literal node from the given value, the Etype of the -- returned node is set to Universal_Real, since all floating-point -- arithmetic operations that we construct use Universal_Real function Rounded_Result_Set (N : Node_Id) return Boolean; -- Returns True if N is a node that contains the Rounded_Result flag -- and if the flag is true or the target type is an integer type. procedure Set_Result (N : Node_Id; Expr : Node_Id; Rchk : Boolean := False; Trunc : Boolean := False); -- N is the node for the current conversion, division or multiplication -- operation, and Expr is an expression representing the result. Expr may -- be of floating-point or integer type. If the operation result is fixed- -- point, then the value of Expr is in units of small of the result type -- (i.e. small's have already been dealt with). The result of the call is -- to replace N by an appropriate conversion to the result type, dealing -- with rounding for the decimal types case. The node is then analyzed and -- resolved using the result type. If Rchk or Trunc are True, then -- respectively Do_Range_Check and Float_Truncate are set in the -- resulting conversion. ---------------------- -- Build_Conversion -- ---------------------- function Build_Conversion (N : Node_Id; Typ : Entity_Id; Expr : Node_Id; Rchk : Boolean := False; Trunc : Boolean := False) return Node_Id is Loc : constant Source_Ptr := Sloc (N); Result : Node_Id; Rcheck : Boolean := Rchk; begin -- A special case, if the expression is an integer literal and the -- target type is an integer type, then just retype the integer -- literal to the desired target type. Don't do this if we need -- a range check. if Nkind (Expr) = N_Integer_Literal and then Is_Integer_Type (Typ) and then not Rchk then Result := Expr; -- Cases where we end up with a conversion. Note that we do not use the -- Convert_To abstraction here, since we may be decorating the resulting -- conversion with Rounded_Result and/or Conversion_OK, so we want the -- conversion node present, even if it appears to be redundant. else -- Remove inner conversion if both inner and outer conversions are -- to integer types, since the inner one serves no purpose (except -- perhaps to set rounding, so we preserve the Rounded_Result flag) -- and also preserve the Conversion_OK and Do_Range_Check flags of -- the inner conversion. if Is_Integer_Type (Typ) and then Is_Integer_Type (Etype (Expr)) and then Nkind (Expr) = N_Type_Conversion then Result := Make_Type_Conversion (Loc, Subtype_Mark => New_Occurrence_Of (Typ, Loc), Expression => Expression (Expr)); Set_Rounded_Result (Result, Rounded_Result_Set (Expr)); Set_Conversion_OK (Result, Conversion_OK (Expr)); Rcheck := Rcheck or Do_Range_Check (Expr); -- For all other cases, a simple type conversion will work else Result := Make_Type_Conversion (Loc, Subtype_Mark => New_Occurrence_Of (Typ, Loc), Expression => Expr); Set_Float_Truncate (Result, Trunc); end if; -- Set Conversion_OK if either result or expression type is a -- fixed-point type, since from a semantic point of view, we are -- treating fixed-point values as integers at this stage. if Is_Fixed_Point_Type (Typ) or else Is_Fixed_Point_Type (Etype (Expression (Result))) then Set_Conversion_OK (Result); end if; -- Set Do_Range_Check if either it was requested by the caller, -- or if an eliminated inner conversion had a range check. if Rcheck then Enable_Range_Check (Result); else Set_Do_Range_Check (Result, False); end if; end if; Set_Etype (Result, Typ); return Result; end Build_Conversion; ------------------ -- Build_Divide -- ------------------ function Build_Divide (N : Node_Id; L, R : Node_Id) return Node_Id is Loc : constant Source_Ptr := Sloc (N); Left_Type : constant Entity_Id := Base_Type (Etype (L)); Right_Type : constant Entity_Id := Base_Type (Etype (R)); Left_Size : Int; Right_Size : Int; Rsize : Int; Result_Type : Entity_Id; Rnode : Node_Id; begin -- Deal with floating-point case first if Is_Floating_Point_Type (Left_Type) then pragma Assert (Left_Type = Universal_Real); pragma Assert (Right_Type = Universal_Real); Rnode := Make_Op_Divide (Loc, L, R); Result_Type := Universal_Real; -- Integer and fixed-point cases else -- An optimization. If the right operand is the literal 1, then we -- can just return the left hand operand. Putting the optimization -- here allows us to omit the check at the call site. if Nkind (R) = N_Integer_Literal and then Intval (R) = 1 then return L; end if; -- First figure out the effective sizes of the operands. Normally -- the effective size of an operand is the RM_Size of the operand. -- But a special case arises with operands whose size is known at -- compile time. In this case, we can use the actual value of the -- operand to get its size if it would fit signed in 8 or 16 bits. Left_Size := UI_To_Int (RM_Size (Left_Type)); if Compile_Time_Known_Value (L) then declare Val : constant Uint := Expr_Value (L); begin if Val < Int'(2 ** 7) then Left_Size := 8; elsif Val < Int'(2 ** 15) then Left_Size := 16; end if; end; end if; Right_Size := UI_To_Int (RM_Size (Right_Type)); if Compile_Time_Known_Value (R) then declare Val : constant Uint := Expr_Value (R); begin if Val <= Int'(2 ** 7) then Right_Size := 8; elsif Val <= Int'(2 ** 15) then Right_Size := 16; end if; end; end if; -- Do the operation using the longer of the two sizes Rsize := Int'Max (Left_Size, Right_Size); if Rsize <= 8 then Result_Type := Standard_Integer_8; elsif Rsize <= 16 then Result_Type := Standard_Integer_16; elsif Rsize <= 32 then Result_Type := Standard_Integer_32; else Result_Type := Standard_Integer_64; end if; Rnode := Make_Op_Divide (Loc, Left_Opnd => Build_Conversion (N, Result_Type, L), Right_Opnd => Build_Conversion (N, Result_Type, R)); end if; -- We now have a divide node built with Result_Type set. First -- set Etype of result, as required for all Build_xxx routines Set_Etype (Rnode, Base_Type (Result_Type)); -- The result is rounded if the target of the operation is decimal -- and Rounded_Result is set, or if the target of the operation -- is an integer type. if Is_Integer_Type (Etype (N)) or else Rounded_Result_Set (N) then Set_Rounded_Result (Rnode); end if; -- One more check. We did the divide operation using the longer of -- the two sizes, which is reasonable. However, in the case where the -- two types have unequal sizes, it is impossible for the result of -- a divide operation to be larger than the dividend, so we can put -- a conversion round the result to keep the evolving operation size -- as small as possible. if not Is_Floating_Point_Type (Left_Type) then Rnode := Build_Conversion (N, Left_Type, Rnode); end if; return Rnode; end Build_Divide; ------------------------- -- Build_Double_Divide -- ------------------------- function Build_Double_Divide (N : Node_Id; X, Y, Z : Node_Id) return Node_Id is Y_Size : constant Nat := UI_To_Int (Esize (Etype (Y))); Z_Size : constant Nat := UI_To_Int (Esize (Etype (Z))); Expr : Node_Id; begin -- If denominator fits in 64 bits, we can build the operations directly -- without causing any intermediate overflow, so that's what we do. if Nat'Max (Y_Size, Z_Size) <= 32 then return Build_Divide (N, X, Build_Multiply (N, Y, Z)); -- Otherwise we use the runtime routine -- [Qnn : Interfaces.Integer_64, -- Rnn : Interfaces.Integer_64; -- Double_Divide (X, Y, Z, Qnn, Rnn, Round); -- Qnn] else declare Loc : constant Source_Ptr := Sloc (N); Qnn : Entity_Id; Rnn : Entity_Id; Code : List_Id; pragma Warnings (Off, Rnn); begin Build_Double_Divide_Code (N, X, Y, Z, Qnn, Rnn, Code); Insert_Actions (N, Code); Expr := New_Occurrence_Of (Qnn, Loc); -- Set type of result in case used elsewhere (see note at start) Set_Etype (Expr, Etype (Qnn)); -- Set result as analyzed (see note at start on build routines) return Expr; end; end if; end Build_Double_Divide; ------------------------------ -- Build_Double_Divide_Code -- ------------------------------ -- If the denominator can be computed in 64-bits, we build -- [Nnn : constant typ := typ (X); -- Dnn : constant typ := typ (Y) * typ (Z) -- Qnn : constant typ := Nnn / Dnn; -- Rnn : constant typ := Nnn / Dnn; -- If the numerator cannot be computed in 64 bits, we build -- [Qnn : typ; -- Rnn : typ; -- Double_Divide (X, Y, Z, Qnn, Rnn, Round);] procedure Build_Double_Divide_Code (N : Node_Id; X, Y, Z : Node_Id; Qnn, Rnn : out Entity_Id; Code : out List_Id) is Loc : constant Source_Ptr := Sloc (N); X_Size : constant Nat := UI_To_Int (Esize (Etype (X))); Y_Size : constant Nat := UI_To_Int (Esize (Etype (Y))); Z_Size : constant Nat := UI_To_Int (Esize (Etype (Z))); QR_Siz : Nat; QR_Typ : Entity_Id; Nnn : Entity_Id; Dnn : Entity_Id; Quo : Node_Id; Rnd : Entity_Id; begin -- Find type that will allow computation of numerator QR_Siz := Nat'Max (X_Size, 2 * Nat'Max (Y_Size, Z_Size)); if QR_Siz <= 16 then QR_Typ := Standard_Integer_16; elsif QR_Siz <= 32 then QR_Typ := Standard_Integer_32; elsif QR_Siz <= 64 then QR_Typ := Standard_Integer_64; -- For more than 64, bits, we use the 64-bit integer defined in -- Interfaces, so that it can be handled by the runtime routine. else QR_Typ := RTE (RE_Integer_64); end if; -- Define quotient and remainder, and set their Etypes, so -- that they can be picked up by Build_xxx routines. Qnn := Make_Temporary (Loc, 'S'); Rnn := Make_Temporary (Loc, 'R'); Set_Etype (Qnn, QR_Typ); Set_Etype (Rnn, QR_Typ); -- Case that we can compute the denominator in 64 bits if QR_Siz <= 64 then -- Create temporaries for numerator and denominator and set Etypes, -- so that New_Occurrence_Of picks them up for Build_xxx calls. Nnn := Make_Temporary (Loc, 'N'); Dnn := Make_Temporary (Loc, 'D'); Set_Etype (Nnn, QR_Typ); Set_Etype (Dnn, QR_Typ); Code := New_List ( Make_Object_Declaration (Loc, Defining_Identifier => Nnn, Object_Definition => New_Occurrence_Of (QR_Typ, Loc), Constant_Present => True, Expression => Build_Conversion (N, QR_Typ, X)), Make_Object_Declaration (Loc, Defining_Identifier => Dnn, Object_Definition => New_Occurrence_Of (QR_Typ, Loc), Constant_Present => True, Expression => Build_Multiply (N, Build_Conversion (N, QR_Typ, Y), Build_Conversion (N, QR_Typ, Z)))); Quo := Build_Divide (N, New_Occurrence_Of (Nnn, Loc), New_Occurrence_Of (Dnn, Loc)); Set_Rounded_Result (Quo, Rounded_Result_Set (N)); Append_To (Code, Make_Object_Declaration (Loc, Defining_Identifier => Qnn, Object_Definition => New_Occurrence_Of (QR_Typ, Loc), Constant_Present => True, Expression => Quo)); Append_To (Code, Make_Object_Declaration (Loc, Defining_Identifier => Rnn, Object_Definition => New_Occurrence_Of (QR_Typ, Loc), Constant_Present => True, Expression => Build_Rem (N, New_Occurrence_Of (Nnn, Loc), New_Occurrence_Of (Dnn, Loc)))); -- Case where denominator does not fit in 64 bits, so we have to -- call the runtime routine to compute the quotient and remainder else Rnd := Boolean_Literals (Rounded_Result_Set (N)); Code := New_List ( Make_Object_Declaration (Loc, Defining_Identifier => Qnn, Object_Definition => New_Occurrence_Of (QR_Typ, Loc)), Make_Object_Declaration (Loc, Defining_Identifier => Rnn, Object_Definition => New_Occurrence_Of (QR_Typ, Loc)), Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Double_Divide), Loc), Parameter_Associations => New_List ( Build_Conversion (N, QR_Typ, X), Build_Conversion (N, QR_Typ, Y), Build_Conversion (N, QR_Typ, Z), New_Occurrence_Of (Qnn, Loc), New_Occurrence_Of (Rnn, Loc), New_Occurrence_Of (Rnd, Loc)))); end if; end Build_Double_Divide_Code; -------------------- -- Build_Multiply -- -------------------- function Build_Multiply (N : Node_Id; L, R : Node_Id) return Node_Id is Loc : constant Source_Ptr := Sloc (N); Left_Type : constant Entity_Id := Etype (L); Right_Type : constant Entity_Id := Etype (R); Left_Size : Int; Right_Size : Int; Rsize : Int; Result_Type : Entity_Id; Rnode : Node_Id; begin -- Deal with floating-point case first if Is_Floating_Point_Type (Left_Type) then pragma Assert (Left_Type = Universal_Real); pragma Assert (Right_Type = Universal_Real); Result_Type := Universal_Real; Rnode := Make_Op_Multiply (Loc, L, R); -- Integer and fixed-point cases else -- An optimization. If the right operand is the literal 1, then we -- can just return the left hand operand. Putting the optimization -- here allows us to omit the check at the call site. Similarly, if -- the left operand is the integer 1 we can return the right operand. if Nkind (R) = N_Integer_Literal and then Intval (R) = 1 then return L; elsif Nkind (L) = N_Integer_Literal and then Intval (L) = 1 then return R; end if; -- Otherwise we need to figure out the correct result type size -- First figure out the effective sizes of the operands. Normally -- the effective size of an operand is the RM_Size of the operand. -- But a special case arises with operands whose size is known at -- compile time. In this case, we can use the actual value of the -- operand to get its size if it would fit signed in 8 or 16 bits. Left_Size := UI_To_Int (RM_Size (Left_Type)); if Compile_Time_Known_Value (L) then declare Val : constant Uint := Expr_Value (L); begin if Val < Int'(2 ** 7) then Left_Size := 8; elsif Val < Int'(2 ** 15) then Left_Size := 16; end if; end; end if; Right_Size := UI_To_Int (RM_Size (Right_Type)); if Compile_Time_Known_Value (R) then declare Val : constant Uint := Expr_Value (R); begin if Val <= Int'(2 ** 7) then Right_Size := 8; elsif Val <= Int'(2 ** 15) then Right_Size := 16; end if; end; end if; -- Now the result size must be at least twice the longer of -- the two sizes, to accommodate all possible results. Rsize := 2 * Int'Max (Left_Size, Right_Size); if Rsize <= 8 then Result_Type := Standard_Integer_8; elsif Rsize <= 16 then Result_Type := Standard_Integer_16; elsif Rsize <= 32 then Result_Type := Standard_Integer_32; else Result_Type := Standard_Integer_64; end if; Rnode := Make_Op_Multiply (Loc, Left_Opnd => Build_Conversion (N, Result_Type, L), Right_Opnd => Build_Conversion (N, Result_Type, R)); end if; -- We now have a multiply node built with Result_Type set. First -- set Etype of result, as required for all Build_xxx routines Set_Etype (Rnode, Base_Type (Result_Type)); return Rnode; end Build_Multiply; --------------- -- Build_Rem -- --------------- function Build_Rem (N : Node_Id; L, R : Node_Id) return Node_Id is Loc : constant Source_Ptr := Sloc (N); Left_Type : constant Entity_Id := Etype (L); Right_Type : constant Entity_Id := Etype (R); Result_Type : Entity_Id; Rnode : Node_Id; begin if Left_Type = Right_Type then Result_Type := Left_Type; Rnode := Make_Op_Rem (Loc, Left_Opnd => L, Right_Opnd => R); -- If left size is larger, we do the remainder operation using the -- size of the left type (i.e. the larger of the two integer types). elsif Esize (Left_Type) >= Esize (Right_Type) then Result_Type := Left_Type; Rnode := Make_Op_Rem (Loc, Left_Opnd => L, Right_Opnd => Build_Conversion (N, Left_Type, R)); -- Similarly, if the right size is larger, we do the remainder -- operation using the right type. else Result_Type := Right_Type; Rnode := Make_Op_Rem (Loc, Left_Opnd => Build_Conversion (N, Right_Type, L), Right_Opnd => R); end if; -- We now have an N_Op_Rem node built with Result_Type set. First -- set Etype of result, as required for all Build_xxx routines Set_Etype (Rnode, Base_Type (Result_Type)); -- One more check. We did the rem operation using the larger of the -- two types, which is reasonable. However, in the case where the -- two types have unequal sizes, it is impossible for the result of -- a remainder operation to be larger than the smaller of the two -- types, so we can put a conversion round the result to keep the -- evolving operation size as small as possible. if Esize (Left_Type) >= Esize (Right_Type) then Rnode := Build_Conversion (N, Right_Type, Rnode); elsif Esize (Right_Type) >= Esize (Left_Type) then Rnode := Build_Conversion (N, Left_Type, Rnode); end if; return Rnode; end Build_Rem; ------------------------- -- Build_Scaled_Divide -- ------------------------- function Build_Scaled_Divide (N : Node_Id; X, Y, Z : Node_Id) return Node_Id is X_Size : constant Nat := UI_To_Int (Esize (Etype (X))); Y_Size : constant Nat := UI_To_Int (Esize (Etype (Y))); Expr : Node_Id; begin -- If numerator fits in 64 bits, we can build the operations directly -- without causing any intermediate overflow, so that's what we do. if Nat'Max (X_Size, Y_Size) <= 32 then return Build_Divide (N, Build_Multiply (N, X, Y), Z); -- Otherwise we use the runtime routine -- [Qnn : Integer_64, -- Rnn : Integer_64; -- Scaled_Divide (X, Y, Z, Qnn, Rnn, Round); -- Qnn] else declare Loc : constant Source_Ptr := Sloc (N); Qnn : Entity_Id; Rnn : Entity_Id; Code : List_Id; pragma Warnings (Off, Rnn); begin Build_Scaled_Divide_Code (N, X, Y, Z, Qnn, Rnn, Code); Insert_Actions (N, Code); Expr := New_Occurrence_Of (Qnn, Loc); -- Set type of result in case used elsewhere (see note at start) Set_Etype (Expr, Etype (Qnn)); return Expr; end; end if; end Build_Scaled_Divide; ------------------------------ -- Build_Scaled_Divide_Code -- ------------------------------ -- If the numerator can be computed in 64-bits, we build -- [Nnn : constant typ := typ (X) * typ (Y); -- Dnn : constant typ := typ (Z) -- Qnn : constant typ := Nnn / Dnn; -- Rnn : constant typ := Nnn / Dnn; -- If the numerator cannot be computed in 64 bits, we build -- [Qnn : Interfaces.Integer_64; -- Rnn : Interfaces.Integer_64; -- Scaled_Divide (X, Y, Z, Qnn, Rnn, Round);] procedure Build_Scaled_Divide_Code (N : Node_Id; X, Y, Z : Node_Id; Qnn, Rnn : out Entity_Id; Code : out List_Id) is Loc : constant Source_Ptr := Sloc (N); X_Size : constant Nat := UI_To_Int (Esize (Etype (X))); Y_Size : constant Nat := UI_To_Int (Esize (Etype (Y))); Z_Size : constant Nat := UI_To_Int (Esize (Etype (Z))); QR_Siz : Nat; QR_Typ : Entity_Id; Nnn : Entity_Id; Dnn : Entity_Id; Quo : Node_Id; Rnd : Entity_Id; begin -- Find type that will allow computation of numerator QR_Siz := Nat'Max (X_Size, 2 * Nat'Max (Y_Size, Z_Size)); if QR_Siz <= 16 then QR_Typ := Standard_Integer_16; elsif QR_Siz <= 32 then QR_Typ := Standard_Integer_32; elsif QR_Siz <= 64 then QR_Typ := Standard_Integer_64; -- For more than 64, bits, we use the 64-bit integer defined in -- Interfaces, so that it can be handled by the runtime routine. else QR_Typ := RTE (RE_Integer_64); end if; -- Define quotient and remainder, and set their Etypes, so -- that they can be picked up by Build_xxx routines. Qnn := Make_Temporary (Loc, 'S'); Rnn := Make_Temporary (Loc, 'R'); Set_Etype (Qnn, QR_Typ); Set_Etype (Rnn, QR_Typ); -- Case that we can compute the numerator in 64 bits if QR_Siz <= 64 then Nnn := Make_Temporary (Loc, 'N'); Dnn := Make_Temporary (Loc, 'D'); -- Set Etypes, so that they can be picked up by New_Occurrence_Of Set_Etype (Nnn, QR_Typ); Set_Etype (Dnn, QR_Typ); Code := New_List ( Make_Object_Declaration (Loc, Defining_Identifier => Nnn, Object_Definition => New_Occurrence_Of (QR_Typ, Loc), Constant_Present => True, Expression => Build_Multiply (N, Build_Conversion (N, QR_Typ, X), Build_Conversion (N, QR_Typ, Y))), Make_Object_Declaration (Loc, Defining_Identifier => Dnn, Object_Definition => New_Occurrence_Of (QR_Typ, Loc), Constant_Present => True, Expression => Build_Conversion (N, QR_Typ, Z))); Quo := Build_Divide (N, New_Occurrence_Of (Nnn, Loc), New_Occurrence_Of (Dnn, Loc)); Append_To (Code, Make_Object_Declaration (Loc, Defining_Identifier => Qnn, Object_Definition => New_Occurrence_Of (QR_Typ, Loc), Constant_Present => True, Expression => Quo)); Append_To (Code, Make_Object_Declaration (Loc, Defining_Identifier => Rnn, Object_Definition => New_Occurrence_Of (QR_Typ, Loc), Constant_Present => True, Expression => Build_Rem (N, New_Occurrence_Of (Nnn, Loc), New_Occurrence_Of (Dnn, Loc)))); -- Case where numerator does not fit in 64 bits, so we have to -- call the runtime routine to compute the quotient and remainder else Rnd := Boolean_Literals (Rounded_Result_Set (N)); Code := New_List ( Make_Object_Declaration (Loc, Defining_Identifier => Qnn, Object_Definition => New_Occurrence_Of (QR_Typ, Loc)), Make_Object_Declaration (Loc, Defining_Identifier => Rnn, Object_Definition => New_Occurrence_Of (QR_Typ, Loc)), Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Scaled_Divide), Loc), Parameter_Associations => New_List ( Build_Conversion (N, QR_Typ, X), Build_Conversion (N, QR_Typ, Y), Build_Conversion (N, QR_Typ, Z), New_Occurrence_Of (Qnn, Loc), New_Occurrence_Of (Rnn, Loc), New_Occurrence_Of (Rnd, Loc)))); end if; -- Set type of result, for use in caller Set_Etype (Qnn, QR_Typ); end Build_Scaled_Divide_Code; --------------------------- -- Do_Divide_Fixed_Fixed -- --------------------------- -- We have: -- (Result_Value * Result_Small) = -- (Left_Value * Left_Small) / (Right_Value * Right_Small) -- Result_Value = (Left_Value / Right_Value) * -- (Left_Small / (Right_Small * Result_Small)); -- we can do the operation in integer arithmetic if this fraction is an -- integer or the reciprocal of an integer, as detailed in (RM G.2.3(21)). -- Otherwise the result is in the close result set and our approach is to -- use floating-point to compute this close result. procedure Do_Divide_Fixed_Fixed (N : Node_Id) is Left : constant Node_Id := Left_Opnd (N); Right : constant Node_Id := Right_Opnd (N); Left_Type : constant Entity_Id := Etype (Left); Right_Type : constant Entity_Id := Etype (Right); Result_Type : constant Entity_Id := Etype (N); Right_Small : constant Ureal := Small_Value (Right_Type); Left_Small : constant Ureal := Small_Value (Left_Type); Result_Small : Ureal; Frac : Ureal; Frac_Num : Uint; Frac_Den : Uint; Lit_Int : Node_Id; begin -- Rounding is required if the result is integral if Is_Integer_Type (Result_Type) then Set_Rounded_Result (N); end if; -- Get result small. If the result is an integer, treat it as though -- it had a small of 1.0, all other processing is identical. if Is_Integer_Type (Result_Type) then Result_Small := Ureal_1; else Result_Small := Small_Value (Result_Type); end if; -- Get small ratio Frac := Left_Small / (Right_Small * Result_Small); Frac_Num := Norm_Num (Frac); Frac_Den := Norm_Den (Frac); -- If the fraction is an integer, then we get the result by multiplying -- the left operand by the integer, and then dividing by the right -- operand (the order is important, if we did the divide first, we -- would lose precision). if Frac_Den = 1 then Lit_Int := Integer_Literal (N, Frac_Num); -- always positive if Present (Lit_Int) then Set_Result (N, Build_Scaled_Divide (N, Left, Lit_Int, Right)); return; end if; -- If the fraction is the reciprocal of an integer, then we get the -- result by first multiplying the divisor by the integer, and then -- doing the division with the adjusted divisor. -- Note: this is much better than doing two divisions: multiplications -- are much faster than divisions (and certainly faster than rounded -- divisions), and we don't get inaccuracies from double rounding. elsif Frac_Num = 1 then Lit_Int := Integer_Literal (N, Frac_Den); -- always positive if Present (Lit_Int) then Set_Result (N, Build_Double_Divide (N, Left, Right, Lit_Int)); return; end if; end if; -- If we fall through, we use floating-point to compute the result Set_Result (N, Build_Multiply (N, Build_Divide (N, Fpt_Value (Left), Fpt_Value (Right)), Real_Literal (N, Frac))); end Do_Divide_Fixed_Fixed; ------------------------------- -- Do_Divide_Fixed_Universal -- ------------------------------- -- We have: -- (Result_Value * Result_Small) = (Left_Value * Left_Small) / Lit_Value; -- Result_Value = Left_Value * Left_Small /(Lit_Value * Result_Small); -- The result is required to be in the perfect result set if the literal -- can be factored so that the resulting small ratio is an integer or the -- reciprocal of an integer (RM G.2.3(21-22)). We now give a detailed -- analysis of these RM requirements: -- We must factor the literal, finding an integer K: -- Lit_Value = K * Right_Small -- Right_Small = Lit_Value / K -- such that the small ratio: -- Left_Small -- ------------------------------ -- (Lit_Value / K) * Result_Small -- Left_Small -- = ------------------------ * K -- Lit_Value * Result_Small -- is an integer or the reciprocal of an integer, and for -- implementation efficiency we need the smallest such K. -- First we reduce the left fraction to lowest terms -- If numerator = 1, then for K = 1, the small ratio is the reciprocal -- of an integer, and this is clearly the minimum K case, so set K = 1, -- Right_Small = Lit_Value. -- If numerator > 1, then set K to the denominator of the fraction so -- that the resulting small ratio is an integer (the numerator value). procedure Do_Divide_Fixed_Universal (N : Node_Id) is Left : constant Node_Id := Left_Opnd (N); Right : constant Node_Id := Right_Opnd (N); Left_Type : constant Entity_Id := Etype (Left); Result_Type : constant Entity_Id := Etype (N); Left_Small : constant Ureal := Small_Value (Left_Type); Lit_Value : constant Ureal := Realval (Right); Result_Small : Ureal; Frac : Ureal; Frac_Num : Uint; Frac_Den : Uint; Lit_K : Node_Id; Lit_Int : Node_Id; begin -- Get result small. If the result is an integer, treat it as though -- it had a small of 1.0, all other processing is identical. if Is_Integer_Type (Result_Type) then Result_Small := Ureal_1; else Result_Small := Small_Value (Result_Type); end if; -- Determine if literal can be rewritten successfully Frac := Left_Small / (Lit_Value * Result_Small); Frac_Num := Norm_Num (Frac); Frac_Den := Norm_Den (Frac); -- Case where fraction is the reciprocal of an integer (K = 1, integer -- = denominator). If this integer is not too large, this is the case -- where the result can be obtained by dividing by this integer value. if Frac_Num = 1 then Lit_Int := Integer_Literal (N, Frac_Den, UR_Is_Negative (Frac)); if Present (Lit_Int) then Set_Result (N, Build_Divide (N, Left, Lit_Int)); return; end if; -- Case where we choose K to make fraction an integer (K = denominator -- of fraction, integer = numerator of fraction). If both K and the -- numerator are small enough, this is the case where the result can -- be obtained by first multiplying by the integer value and then -- dividing by K (the order is important, if we divided first, we -- would lose precision). else Lit_Int := Integer_Literal (N, Frac_Num, UR_Is_Negative (Frac)); Lit_K := Integer_Literal (N, Frac_Den, False); if Present (Lit_Int) and then Present (Lit_K) then Set_Result (N, Build_Scaled_Divide (N, Left, Lit_Int, Lit_K)); return; end if; end if; -- Fall through if the literal cannot be successfully rewritten, or if -- the small ratio is out of range of integer arithmetic. In the former -- case it is fine to use floating-point to get the close result set, -- and in the latter case, it means that the result is zero or raises -- constraint error, and we can do that accurately in floating-point. -- If we end up using floating-point, then we take the right integer -- to be one, and its small to be the value of the original right real -- literal. That way, we need only one floating-point multiplication. Set_Result (N, Build_Multiply (N, Fpt_Value (Left), Real_Literal (N, Frac))); end Do_Divide_Fixed_Universal; ------------------------------- -- Do_Divide_Universal_Fixed -- ------------------------------- -- We have: -- (Result_Value * Result_Small) = -- Lit_Value / (Right_Value * Right_Small) -- Result_Value = -- (Lit_Value / (Right_Small * Result_Small)) / Right_Value -- The result is required to be in the perfect result set if the literal -- can be factored so that the resulting small ratio is an integer or the -- reciprocal of an integer (RM G.2.3(21-22)). We now give a detailed -- analysis of these RM requirements: -- We must factor the literal, finding an integer K: -- Lit_Value = K * Left_Small -- Left_Small = Lit_Value / K -- such that the small ratio: -- (Lit_Value / K) -- -------------------------- -- Right_Small * Result_Small -- Lit_Value 1 -- = -------------------------- * - -- Right_Small * Result_Small K -- is an integer or the reciprocal of an integer, and for -- implementation efficiency we need the smallest such K. -- First we reduce the left fraction to lowest terms -- If denominator = 1, then for K = 1, the small ratio is an integer -- (the numerator) and this is clearly the minimum K case, so set K = 1, -- and Left_Small = Lit_Value. -- If denominator > 1, then set K to the numerator of the fraction so -- that the resulting small ratio is the reciprocal of an integer (the -- numerator value). procedure Do_Divide_Universal_Fixed (N : Node_Id) is Left : constant Node_Id := Left_Opnd (N); Right : constant Node_Id := Right_Opnd (N); Right_Type : constant Entity_Id := Etype (Right); Result_Type : constant Entity_Id := Etype (N); Right_Small : constant Ureal := Small_Value (Right_Type); Lit_Value : constant Ureal := Realval (Left); Result_Small : Ureal; Frac : Ureal; Frac_Num : Uint; Frac_Den : Uint; Lit_K : Node_Id; Lit_Int : Node_Id; begin -- Get result small. If the result is an integer, treat it as though -- it had a small of 1.0, all other processing is identical. if Is_Integer_Type (Result_Type) then Result_Small := Ureal_1; else Result_Small := Small_Value (Result_Type); end if; -- Determine if literal can be rewritten successfully Frac := Lit_Value / (Right_Small * Result_Small); Frac_Num := Norm_Num (Frac); Frac_Den := Norm_Den (Frac); -- Case where fraction is an integer (K = 1, integer = numerator). If -- this integer is not too large, this is the case where the result -- can be obtained by dividing this integer by the right operand. if Frac_Den = 1 then Lit_Int := Integer_Literal (N, Frac_Num, UR_Is_Negative (Frac)); if Present (Lit_Int) then Set_Result (N, Build_Divide (N, Lit_Int, Right)); return; end if; -- Case where we choose K to make the fraction the reciprocal of an -- integer (K = numerator of fraction, integer = numerator of fraction). -- If both K and the integer are small enough, this is the case where -- the result can be obtained by multiplying the right operand by K -- and then dividing by the integer value. The order of the operations -- is important (if we divided first, we would lose precision). else Lit_Int := Integer_Literal (N, Frac_Den, UR_Is_Negative (Frac)); Lit_K := Integer_Literal (N, Frac_Num, False); if Present (Lit_Int) and then Present (Lit_K) then Set_Result (N, Build_Double_Divide (N, Lit_K, Right, Lit_Int)); return; end if; end if; -- Fall through if the literal cannot be successfully rewritten, or if -- the small ratio is out of range of integer arithmetic. In the former -- case it is fine to use floating-point to get the close result set, -- and in the latter case, it means that the result is zero or raises -- constraint error, and we can do that accurately in floating-point. -- If we end up using floating-point, then we take the right integer -- to be one, and its small to be the value of the original right real -- literal. That way, we need only one floating-point division. Set_Result (N, Build_Divide (N, Real_Literal (N, Frac), Fpt_Value (Right))); end Do_Divide_Universal_Fixed; ----------------------------- -- Do_Multiply_Fixed_Fixed -- ----------------------------- -- We have: -- (Result_Value * Result_Small) = -- (Left_Value * Left_Small) * (Right_Value * Right_Small) -- Result_Value = (Left_Value * Right_Value) * -- (Left_Small * Right_Small) / Result_Small; -- we can do the operation in integer arithmetic if this fraction is an -- integer or the reciprocal of an integer, as detailed in (RM G.2.3(21)). -- Otherwise the result is in the close result set and our approach is to -- use floating-point to compute this close result. procedure Do_Multiply_Fixed_Fixed (N : Node_Id) is Left : constant Node_Id := Left_Opnd (N); Right : constant Node_Id := Right_Opnd (N); Left_Type : constant Entity_Id := Etype (Left); Right_Type : constant Entity_Id := Etype (Right); Result_Type : constant Entity_Id := Etype (N); Right_Small : constant Ureal := Small_Value (Right_Type); Left_Small : constant Ureal := Small_Value (Left_Type); Result_Small : Ureal; Frac : Ureal; Frac_Num : Uint; Frac_Den : Uint; Lit_Int : Node_Id; begin -- Get result small. If the result is an integer, treat it as though -- it had a small of 1.0, all other processing is identical. if Is_Integer_Type (Result_Type) then Result_Small := Ureal_1; else Result_Small := Small_Value (Result_Type); end if; -- Get small ratio Frac := (Left_Small * Right_Small) / Result_Small; Frac_Num := Norm_Num (Frac); Frac_Den := Norm_Den (Frac); -- If the fraction is an integer, then we get the result by multiplying -- the operands, and then multiplying the result by the integer value. if Frac_Den = 1 then Lit_Int := Integer_Literal (N, Frac_Num); -- always positive if Present (Lit_Int) then Set_Result (N, Build_Multiply (N, Build_Multiply (N, Left, Right), Lit_Int)); return; end if; -- If the fraction is the reciprocal of an integer, then we get the -- result by multiplying the operands, and then dividing the result by -- the integer value. The order of the operations is important, if we -- divided first, we would lose precision. elsif Frac_Num = 1 then Lit_Int := Integer_Literal (N, Frac_Den); -- always positive if Present (Lit_Int) then Set_Result (N, Build_Scaled_Divide (N, Left, Right, Lit_Int)); return; end if; end if; -- If we fall through, we use floating-point to compute the result Set_Result (N, Build_Multiply (N, Build_Multiply (N, Fpt_Value (Left), Fpt_Value (Right)), Real_Literal (N, Frac))); end Do_Multiply_Fixed_Fixed; --------------------------------- -- Do_Multiply_Fixed_Universal -- --------------------------------- -- We have: -- (Result_Value * Result_Small) = (Left_Value * Left_Small) * Lit_Value; -- Result_Value = Left_Value * (Left_Small * Lit_Value) / Result_Small; -- The result is required to be in the perfect result set if the literal -- can be factored so that the resulting small ratio is an integer or the -- reciprocal of an integer (RM G.2.3(21-22)). We now give a detailed -- analysis of these RM requirements: -- We must factor the literal, finding an integer K: -- Lit_Value = K * Right_Small -- Right_Small = Lit_Value / K -- such that the small ratio: -- Left_Small * (Lit_Value / K) -- ---------------------------- -- Result_Small -- Left_Small * Lit_Value 1 -- = ---------------------- * - -- Result_Small K -- is an integer or the reciprocal of an integer, and for -- implementation efficiency we need the smallest such K. -- First we reduce the left fraction to lowest terms -- If denominator = 1, then for K = 1, the small ratio is an integer, and -- this is clearly the minimum K case, so set -- K = 1, Right_Small = Lit_Value -- If denominator > 1, then set K to the numerator of the fraction, so -- that the resulting small ratio is the reciprocal of the integer (the -- denominator value). procedure Do_Multiply_Fixed_Universal (N : Node_Id; Left, Right : Node_Id) is Left_Type : constant Entity_Id := Etype (Left); Result_Type : constant Entity_Id := Etype (N); Left_Small : constant Ureal := Small_Value (Left_Type); Lit_Value : constant Ureal := Realval (Right); Result_Small : Ureal; Frac : Ureal; Frac_Num : Uint; Frac_Den : Uint; Lit_K : Node_Id; Lit_Int : Node_Id; begin -- Get result small. If the result is an integer, treat it as though -- it had a small of 1.0, all other processing is identical. if Is_Integer_Type (Result_Type) then Result_Small := Ureal_1; else Result_Small := Small_Value (Result_Type); end if; -- Determine if literal can be rewritten successfully Frac := (Left_Small * Lit_Value) / Result_Small; Frac_Num := Norm_Num (Frac); Frac_Den := Norm_Den (Frac); -- Case where fraction is an integer (K = 1, integer = numerator). If -- this integer is not too large, this is the case where the result can -- be obtained by multiplying by this integer value. if Frac_Den = 1 then Lit_Int := Integer_Literal (N, Frac_Num, UR_Is_Negative (Frac)); if Present (Lit_Int) then Set_Result (N, Build_Multiply (N, Left, Lit_Int)); return; end if; -- Case where we choose K to make fraction the reciprocal of an integer -- (K = numerator of fraction, integer = denominator of fraction). If -- both K and the denominator are small enough, this is the case where -- the result can be obtained by first multiplying by K, and then -- dividing by the integer value. else Lit_Int := Integer_Literal (N, Frac_Den, UR_Is_Negative (Frac)); Lit_K := Integer_Literal (N, Frac_Num); if Present (Lit_Int) and then Present (Lit_K) then Set_Result (N, Build_Scaled_Divide (N, Left, Lit_K, Lit_Int)); return; end if; end if; -- Fall through if the literal cannot be successfully rewritten, or if -- the small ratio is out of range of integer arithmetic. In the former -- case it is fine to use floating-point to get the close result set, -- and in the latter case, it means that the result is zero or raises -- constraint error, and we can do that accurately in floating-point. -- If we end up using floating-point, then we take the right integer -- to be one, and its small to be the value of the original right real -- literal. That way, we need only one floating-point multiplication. Set_Result (N, Build_Multiply (N, Fpt_Value (Left), Real_Literal (N, Frac))); end Do_Multiply_Fixed_Universal; --------------------------------- -- Expand_Convert_Fixed_Static -- --------------------------------- procedure Expand_Convert_Fixed_Static (N : Node_Id) is begin Rewrite (N, Convert_To (Etype (N), Make_Real_Literal (Sloc (N), Expr_Value_R (Expression (N))))); Analyze_And_Resolve (N); end Expand_Convert_Fixed_Static; ----------------------------------- -- Expand_Convert_Fixed_To_Fixed -- ----------------------------------- -- We have: -- Result_Value * Result_Small = Source_Value * Source_Small -- Result_Value = Source_Value * (Source_Small / Result_Small) -- If the small ratio (Source_Small / Result_Small) is a sufficiently small -- integer, then the perfect result set is obtained by a single integer -- multiplication. -- If the small ratio is the reciprocal of a sufficiently small integer, -- then the perfect result set is obtained by a single integer division. -- In other cases, we obtain the close result set by calculating the -- result in floating-point. procedure Expand_Convert_Fixed_To_Fixed (N : Node_Id) is Rng_Check : constant Boolean := Do_Range_Check (N); Expr : constant Node_Id := Expression (N); Result_Type : constant Entity_Id := Etype (N); Source_Type : constant Entity_Id := Etype (Expr); Small_Ratio : Ureal; Ratio_Num : Uint; Ratio_Den : Uint; Lit : Node_Id; begin if Is_OK_Static_Expression (Expr) then Expand_Convert_Fixed_Static (N); return; end if; Small_Ratio := Small_Value (Source_Type) / Small_Value (Result_Type); Ratio_Num := Norm_Num (Small_Ratio); Ratio_Den := Norm_Den (Small_Ratio); if Ratio_Den = 1 then if Ratio_Num = 1 then Set_Result (N, Expr); return; else Lit := Integer_Literal (N, Ratio_Num); if Present (Lit) then Set_Result (N, Build_Multiply (N, Expr, Lit)); return; end if; end if; elsif Ratio_Num = 1 then Lit := Integer_Literal (N, Ratio_Den); if Present (Lit) then Set_Result (N, Build_Divide (N, Expr, Lit), Rng_Check); return; end if; end if; -- Fall through to use floating-point for the close result set case -- either as a result of the small ratio not being an integer or the -- reciprocal of an integer, or if the integer is out of range. Set_Result (N, Build_Multiply (N, Fpt_Value (Expr), Real_Literal (N, Small_Ratio)), Rng_Check); end Expand_Convert_Fixed_To_Fixed; ----------------------------------- -- Expand_Convert_Fixed_To_Float -- ----------------------------------- -- If the small of the fixed type is 1.0, then we simply convert the -- integer value directly to the target floating-point type, otherwise -- we first have to multiply by the small, in Universal_Real, and then -- convert the result to the target floating-point type. procedure Expand_Convert_Fixed_To_Float (N : Node_Id) is Rng_Check : constant Boolean := Do_Range_Check (N); Expr : constant Node_Id := Expression (N); Source_Type : constant Entity_Id := Etype (Expr); Small : constant Ureal := Small_Value (Source_Type); begin if Is_OK_Static_Expression (Expr) then Expand_Convert_Fixed_Static (N); return; end if; if Small = Ureal_1 then Set_Result (N, Expr); else Set_Result (N, Build_Multiply (N, Fpt_Value (Expr), Real_Literal (N, Small)), Rng_Check); end if; end Expand_Convert_Fixed_To_Float; ------------------------------------- -- Expand_Convert_Fixed_To_Integer -- ------------------------------------- -- We have: -- Result_Value = Source_Value * Source_Small -- If the small value is a sufficiently small integer, then the perfect -- result set is obtained by a single integer multiplication. -- If the small value is the reciprocal of a sufficiently small integer, -- then the perfect result set is obtained by a single integer division. -- In other cases, we obtain the close result set by calculating the -- result in floating-point. procedure Expand_Convert_Fixed_To_Integer (N : Node_Id) is Rng_Check : constant Boolean := Do_Range_Check (N); Expr : constant Node_Id := Expression (N); Source_Type : constant Entity_Id := Etype (Expr); Small : constant Ureal := Small_Value (Source_Type); Small_Num : constant Uint := Norm_Num (Small); Small_Den : constant Uint := Norm_Den (Small); Lit : Node_Id; begin if Is_OK_Static_Expression (Expr) then Expand_Convert_Fixed_Static (N); return; end if; if Small_Den = 1 then Lit := Integer_Literal (N, Small_Num); if Present (Lit) then Set_Result (N, Build_Multiply (N, Expr, Lit), Rng_Check); return; end if; elsif Small_Num = 1 then Lit := Integer_Literal (N, Small_Den); if Present (Lit) then Set_Result (N, Build_Divide (N, Expr, Lit), Rng_Check); return; end if; end if; -- Fall through to use floating-point for the close result set case -- either as a result of the small value not being an integer or the -- reciprocal of an integer, or if the integer is out of range. Set_Result (N, Build_Multiply (N, Fpt_Value (Expr), Real_Literal (N, Small)), Rng_Check); end Expand_Convert_Fixed_To_Integer; ----------------------------------- -- Expand_Convert_Float_To_Fixed -- ----------------------------------- -- We have -- Result_Value * Result_Small = Operand_Value -- so compute: -- Result_Value = Operand_Value * (1.0 / Result_Small) -- We do the small scaling in floating-point, and we do a multiplication -- rather than a division, since it is accurate enough for the perfect -- result cases, and faster. procedure Expand_Convert_Float_To_Fixed (N : Node_Id) is Expr : constant Node_Id := Expression (N); Orig_N : constant Node_Id := Original_Node (N); Result_Type : constant Entity_Id := Etype (N); Rng_Check : constant Boolean := Do_Range_Check (N); Small : constant Ureal := Small_Value (Result_Type); Truncate : Boolean; begin -- Optimize small = 1, where we can avoid the multiply completely if Small = Ureal_1 then Set_Result (N, Expr, Rng_Check, Trunc => True); -- Normal case where multiply is required. Rounding is truncating -- for decimal fixed point types only, see RM 4.6(29), except if the -- conversion comes from an attribute reference 'Round (RM 3.5.10 (14)): -- The attribute is implemented by means of a conversion that must -- round. else if Is_Decimal_Fixed_Point_Type (Result_Type) then Truncate := Nkind (Orig_N) /= N_Attribute_Reference or else Get_Attribute_Id (Attribute_Name (Orig_N)) /= Attribute_Round; else Truncate := False; end if; Set_Result (N => N, Expr => Build_Multiply (N => N, L => Fpt_Value (Expr), R => Real_Literal (N, Ureal_1 / Small)), Rchk => Rng_Check, Trunc => Truncate); end if; end Expand_Convert_Float_To_Fixed; ------------------------------------- -- Expand_Convert_Integer_To_Fixed -- ------------------------------------- -- We have -- Result_Value * Result_Small = Operand_Value -- Result_Value = Operand_Value / Result_Small -- If the small value is a sufficiently small integer, then the perfect -- result set is obtained by a single integer division. -- If the small value is the reciprocal of a sufficiently small integer, -- the perfect result set is obtained by a single integer multiplication. -- In other cases, we obtain the close result set by calculating the -- result in floating-point using a multiplication by the reciprocal -- of the Result_Small. procedure Expand_Convert_Integer_To_Fixed (N : Node_Id) is Rng_Check : constant Boolean := Do_Range_Check (N); Expr : constant Node_Id := Expression (N); Result_Type : constant Entity_Id := Etype (N); Small : constant Ureal := Small_Value (Result_Type); Small_Num : constant Uint := Norm_Num (Small); Small_Den : constant Uint := Norm_Den (Small); Lit : Node_Id; begin if Small_Den = 1 then Lit := Integer_Literal (N, Small_Num); if Present (Lit) then Set_Result (N, Build_Divide (N, Expr, Lit), Rng_Check); return; end if; elsif Small_Num = 1 then Lit := Integer_Literal (N, Small_Den); if Present (Lit) then Set_Result (N, Build_Multiply (N, Expr, Lit), Rng_Check); return; end if; end if; -- Fall through to use floating-point for the close result set case -- either as a result of the small value not being an integer or the -- reciprocal of an integer, or if the integer is out of range. Set_Result (N, Build_Multiply (N, Fpt_Value (Expr), Real_Literal (N, Ureal_1 / Small)), Rng_Check); end Expand_Convert_Integer_To_Fixed; -------------------------------- -- Expand_Decimal_Divide_Call -- -------------------------------- -- We have four operands -- Dividend -- Divisor -- Quotient -- Remainder -- All of which are decimal types, and which thus have associated -- decimal scales. -- Computing the quotient is a similar problem to that faced by the -- normal fixed-point division, except that it is simpler, because -- we always have compatible smalls. -- Quotient = (Dividend / Divisor) * 10**q -- where 10 ** q = Dividend'Small / (Divisor'Small * Quotient'Small) -- so q = Divisor'Scale + Quotient'Scale - Dividend'Scale -- For q >= 0, we compute -- Numerator := Dividend * 10 ** q -- Denominator := Divisor -- Quotient := Numerator / Denominator -- For q < 0, we compute -- Numerator := Dividend -- Denominator := Divisor * 10 ** q -- Quotient := Numerator / Denominator -- Both these divisions are done in truncated mode, and the remainder -- from these divisions is used to compute the result Remainder. This -- remainder has the effective scale of the numerator of the division, -- For q >= 0, the remainder scale is Dividend'Scale + q -- For q < 0, the remainder scale is Dividend'Scale -- The result Remainder is then computed by a normal truncating decimal -- conversion from this scale to the scale of the remainder, i.e. by a -- division or multiplication by the appropriate power of 10. procedure Expand_Decimal_Divide_Call (N : Node_Id) is Loc : constant Source_Ptr := Sloc (N); Dividend : Node_Id := First_Actual (N); Divisor : Node_Id := Next_Actual (Dividend); Quotient : Node_Id := Next_Actual (Divisor); Remainder : Node_Id := Next_Actual (Quotient); Dividend_Type : constant Entity_Id := Etype (Dividend); Divisor_Type : constant Entity_Id := Etype (Divisor); Quotient_Type : constant Entity_Id := Etype (Quotient); Remainder_Type : constant Entity_Id := Etype (Remainder); Dividend_Scale : constant Uint := Scale_Value (Dividend_Type); Divisor_Scale : constant Uint := Scale_Value (Divisor_Type); Quotient_Scale : constant Uint := Scale_Value (Quotient_Type); Remainder_Scale : constant Uint := Scale_Value (Remainder_Type); Q : Uint; Numerator_Scale : Uint; Stmts : List_Id; Qnn : Entity_Id; Rnn : Entity_Id; Computed_Remainder : Node_Id; Adjusted_Remainder : Node_Id; Scale_Adjust : Uint; begin -- Relocate the operands, since they are now list elements, and we -- need to reference them separately as operands in the expanded code. Dividend := Relocate_Node (Dividend); Divisor := Relocate_Node (Divisor); Quotient := Relocate_Node (Quotient); Remainder := Relocate_Node (Remainder); -- Now compute Q, the adjustment scale Q := Divisor_Scale + Quotient_Scale - Dividend_Scale; -- If Q is non-negative then we need a scaled divide if Q >= 0 then Build_Scaled_Divide_Code (N, Dividend, Integer_Literal (N, Uint_10 ** Q), Divisor, Qnn, Rnn, Stmts); Numerator_Scale := Dividend_Scale + Q; -- If Q is negative, then we need a double divide else Build_Double_Divide_Code (N, Dividend, Divisor, Integer_Literal (N, Uint_10 ** (-Q)), Qnn, Rnn, Stmts); Numerator_Scale := Dividend_Scale; end if; -- Add statement to set quotient value -- Quotient := quotient-type!(Qnn); Append_To (Stmts, Make_Assignment_Statement (Loc, Name => Quotient, Expression => Unchecked_Convert_To (Quotient_Type, Build_Conversion (N, Quotient_Type, New_Occurrence_Of (Qnn, Loc))))); -- Now we need to deal with computing and setting the remainder. The -- scale of the remainder is in Numerator_Scale, and the desired -- scale is the scale of the given Remainder argument. There are -- three cases: -- Numerator_Scale > Remainder_Scale -- in this case, there are extra digits in the computed remainder -- which must be eliminated by an extra division: -- computed-remainder := Numerator rem Denominator -- scale_adjust = Numerator_Scale - Remainder_Scale -- adjusted-remainder := computed-remainder / 10 ** scale_adjust -- Numerator_Scale = Remainder_Scale -- in this case, the we have the remainder we need -- computed-remainder := Numerator rem Denominator -- adjusted-remainder := computed-remainder -- Numerator_Scale < Remainder_Scale -- in this case, we have insufficient digits in the computed -- remainder, which must be eliminated by an extra multiply -- computed-remainder := Numerator rem Denominator -- scale_adjust = Remainder_Scale - Numerator_Scale -- adjusted-remainder := computed-remainder * 10 ** scale_adjust -- Finally we assign the adjusted-remainder to the result Remainder -- with conversions to get the proper fixed-point type representation. Computed_Remainder := New_Occurrence_Of (Rnn, Loc); if Numerator_Scale > Remainder_Scale then Scale_Adjust := Numerator_Scale - Remainder_Scale; Adjusted_Remainder := Build_Divide (N, Computed_Remainder, Integer_Literal (N, 10 ** Scale_Adjust)); elsif Numerator_Scale = Remainder_Scale then Adjusted_Remainder := Computed_Remainder; else -- Numerator_Scale < Remainder_Scale Scale_Adjust := Remainder_Scale - Numerator_Scale; Adjusted_Remainder := Build_Multiply (N, Computed_Remainder, Integer_Literal (N, 10 ** Scale_Adjust)); end if; -- Assignment of remainder result Append_To (Stmts, Make_Assignment_Statement (Loc, Name => Remainder, Expression => Unchecked_Convert_To (Remainder_Type, Adjusted_Remainder))); -- Final step is to rewrite the call with a block containing the -- above sequence of constructed statements for the divide operation. Rewrite (N, Make_Block_Statement (Loc, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => Stmts))); Analyze (N); end Expand_Decimal_Divide_Call; ----------------------------------------------- -- Expand_Divide_Fixed_By_Fixed_Giving_Fixed -- ----------------------------------------------- procedure Expand_Divide_Fixed_By_Fixed_Giving_Fixed (N : Node_Id) is Left : constant Node_Id := Left_Opnd (N); Right : constant Node_Id := Right_Opnd (N); begin -- Suppress expansion of a fixed-by-fixed division if the -- operation is supported directly by the target. if Target_Has_Fixed_Ops (Etype (Left), Etype (Right), Etype (N)) then return; end if; if Etype (Left) = Universal_Real then Do_Divide_Universal_Fixed (N); elsif Etype (Right) = Universal_Real then Do_Divide_Fixed_Universal (N); else Do_Divide_Fixed_Fixed (N); -- A focused optimization: if after constant folding the -- expression is of the form: T ((Exp * D) / D), where D is -- a static constant, return T (Exp). This form will show up -- when D is the denominator of the static expression for the -- 'small of fixed-point types involved. This transformation -- removes a division that may be expensive on some targets. if Nkind (N) = N_Type_Conversion and then Nkind (Expression (N)) = N_Op_Divide then declare Num : constant Node_Id := Left_Opnd (Expression (N)); Den : constant Node_Id := Right_Opnd (Expression (N)); begin if Nkind (Den) = N_Integer_Literal and then Nkind (Num) = N_Op_Multiply and then Nkind (Right_Opnd (Num)) = N_Integer_Literal and then Intval (Den) = Intval (Right_Opnd (Num)) then Rewrite (Expression (N), Left_Opnd (Num)); end if; end; end if; end if; end Expand_Divide_Fixed_By_Fixed_Giving_Fixed; ----------------------------------------------- -- Expand_Divide_Fixed_By_Fixed_Giving_Float -- ----------------------------------------------- -- The division is done in Universal_Real, and the result is multiplied -- by the small ratio, which is Small (Right) / Small (Left). Special -- treatment is required for universal operands, which represent their -- own value and do not require conversion. procedure Expand_Divide_Fixed_By_Fixed_Giving_Float (N : Node_Id) is Left : constant Node_Id := Left_Opnd (N); Right : constant Node_Id := Right_Opnd (N); Left_Type : constant Entity_Id := Etype (Left); Right_Type : constant Entity_Id := Etype (Right); begin -- Case of left operand is universal real, the result we want is: -- Left_Value / (Right_Value * Right_Small) -- so we compute this as: -- (Left_Value / Right_Small) / Right_Value if Left_Type = Universal_Real then Set_Result (N, Build_Divide (N, Real_Literal (N, Realval (Left) / Small_Value (Right_Type)), Fpt_Value (Right))); -- Case of right operand is universal real, the result we want is -- (Left_Value * Left_Small) / Right_Value -- so we compute this as: -- Left_Value * (Left_Small / Right_Value) -- Note we invert to a multiplication since usually floating-point -- multiplication is much faster than floating-point division. elsif Right_Type = Universal_Real then Set_Result (N, Build_Multiply (N, Fpt_Value (Left), Real_Literal (N, Small_Value (Left_Type) / Realval (Right)))); -- Both operands are fixed, so the value we want is -- (Left_Value * Left_Small) / (Right_Value * Right_Small) -- which we compute as: -- (Left_Value / Right_Value) * (Left_Small / Right_Small) else Set_Result (N, Build_Multiply (N, Build_Divide (N, Fpt_Value (Left), Fpt_Value (Right)), Real_Literal (N, Small_Value (Left_Type) / Small_Value (Right_Type)))); end if; end Expand_Divide_Fixed_By_Fixed_Giving_Float; ------------------------------------------------- -- Expand_Divide_Fixed_By_Fixed_Giving_Integer -- ------------------------------------------------- procedure Expand_Divide_Fixed_By_Fixed_Giving_Integer (N : Node_Id) is Left : constant Node_Id := Left_Opnd (N); Right : constant Node_Id := Right_Opnd (N); begin if Etype (Left) = Universal_Real then Do_Divide_Universal_Fixed (N); elsif Etype (Right) = Universal_Real then Do_Divide_Fixed_Universal (N); else Do_Divide_Fixed_Fixed (N); end if; end Expand_Divide_Fixed_By_Fixed_Giving_Integer; ------------------------------------------------- -- Expand_Divide_Fixed_By_Integer_Giving_Fixed -- ------------------------------------------------- -- Since the operand and result fixed-point type is the same, this is -- a straight divide by the right operand, the small can be ignored. procedure Expand_Divide_Fixed_By_Integer_Giving_Fixed (N : Node_Id) is Left : constant Node_Id := Left_Opnd (N); Right : constant Node_Id := Right_Opnd (N); begin Set_Result (N, Build_Divide (N, Left, Right)); end Expand_Divide_Fixed_By_Integer_Giving_Fixed; ------------------------------------------------- -- Expand_Multiply_Fixed_By_Fixed_Giving_Fixed -- ------------------------------------------------- procedure Expand_Multiply_Fixed_By_Fixed_Giving_Fixed (N : Node_Id) is Left : constant Node_Id := Left_Opnd (N); Right : constant Node_Id := Right_Opnd (N); procedure Rewrite_Non_Static_Universal (Opnd : Node_Id); -- The operand may be a non-static universal value, such an -- exponentiation with a non-static exponent. In that case, treat -- as a fixed * fixed multiplication, and convert the argument to -- the target fixed type. ---------------------------------- -- Rewrite_Non_Static_Universal -- ---------------------------------- procedure Rewrite_Non_Static_Universal (Opnd : Node_Id) is Loc : constant Source_Ptr := Sloc (N); begin Rewrite (Opnd, Make_Type_Conversion (Loc, Subtype_Mark => New_Occurrence_Of (Etype (N), Loc), Expression => Expression (Opnd))); Analyze_And_Resolve (Opnd, Etype (N)); end Rewrite_Non_Static_Universal; -- Start of processing for Expand_Multiply_Fixed_By_Fixed_Giving_Fixed begin -- Suppress expansion of a fixed-by-fixed multiplication if the -- operation is supported directly by the target. if Target_Has_Fixed_Ops (Etype (Left), Etype (Right), Etype (N)) then return; end if; if Etype (Left) = Universal_Real then if Nkind (Left) = N_Real_Literal then Do_Multiply_Fixed_Universal (N, Left => Right, Right => Left); elsif Nkind (Left) = N_Type_Conversion then Rewrite_Non_Static_Universal (Left); Do_Multiply_Fixed_Fixed (N); end if; elsif Etype (Right) = Universal_Real then if Nkind (Right) = N_Real_Literal then Do_Multiply_Fixed_Universal (N, Left, Right); elsif Nkind (Right) = N_Type_Conversion then Rewrite_Non_Static_Universal (Right); Do_Multiply_Fixed_Fixed (N); end if; else Do_Multiply_Fixed_Fixed (N); end if; end Expand_Multiply_Fixed_By_Fixed_Giving_Fixed; ------------------------------------------------- -- Expand_Multiply_Fixed_By_Fixed_Giving_Float -- ------------------------------------------------- -- The multiply is done in Universal_Real, and the result is multiplied -- by the adjustment for the smalls which is Small (Right) * Small (Left). -- Special treatment is required for universal operands. procedure Expand_Multiply_Fixed_By_Fixed_Giving_Float (N : Node_Id) is Left : constant Node_Id := Left_Opnd (N); Right : constant Node_Id := Right_Opnd (N); Left_Type : constant Entity_Id := Etype (Left); Right_Type : constant Entity_Id := Etype (Right); begin -- Case of left operand is universal real, the result we want is -- Left_Value * (Right_Value * Right_Small) -- so we compute this as: -- (Left_Value * Right_Small) * Right_Value; if Left_Type = Universal_Real then Set_Result (N, Build_Multiply (N, Real_Literal (N, Realval (Left) * Small_Value (Right_Type)), Fpt_Value (Right))); -- Case of right operand is universal real, the result we want is -- (Left_Value * Left_Small) * Right_Value -- so we compute this as: -- Left_Value * (Left_Small * Right_Value) elsif Right_Type = Universal_Real then Set_Result (N, Build_Multiply (N, Fpt_Value (Left), Real_Literal (N, Small_Value (Left_Type) * Realval (Right)))); -- Both operands are fixed, so the value we want is -- (Left_Value * Left_Small) * (Right_Value * Right_Small) -- which we compute as: -- (Left_Value * Right_Value) * (Right_Small * Left_Small) else Set_Result (N, Build_Multiply (N, Build_Multiply (N, Fpt_Value (Left), Fpt_Value (Right)), Real_Literal (N, Small_Value (Right_Type) * Small_Value (Left_Type)))); end if; end Expand_Multiply_Fixed_By_Fixed_Giving_Float; --------------------------------------------------- -- Expand_Multiply_Fixed_By_Fixed_Giving_Integer -- --------------------------------------------------- procedure Expand_Multiply_Fixed_By_Fixed_Giving_Integer (N : Node_Id) is Loc : constant Source_Ptr := Sloc (N); Left : constant Node_Id := Left_Opnd (N); Right : constant Node_Id := Right_Opnd (N); begin if Etype (Left) = Universal_Real then Do_Multiply_Fixed_Universal (N, Left => Right, Right => Left); elsif Etype (Right) = Universal_Real then Do_Multiply_Fixed_Universal (N, Left, Right); -- If both types are equal and we need to avoid floating point -- instructions, it's worth introducing a temporary with the -- common type, because it may be evaluated more simply without -- the need for run-time use of floating point. elsif Etype (Right) = Etype (Left) and then Restriction_Active (No_Floating_Point) then declare Temp : constant Entity_Id := Make_Temporary (Loc, 'F'); Mult : constant Node_Id := Make_Op_Multiply (Loc, Left, Right); Decl : constant Node_Id := Make_Object_Declaration (Loc, Defining_Identifier => Temp, Object_Definition => New_Occurrence_Of (Etype (Right), Loc), Expression => Mult); begin Insert_Action (N, Decl); Rewrite (N, OK_Convert_To (Etype (N), New_Occurrence_Of (Temp, Loc))); Analyze_And_Resolve (N, Standard_Integer); end; else Do_Multiply_Fixed_Fixed (N); end if; end Expand_Multiply_Fixed_By_Fixed_Giving_Integer; --------------------------------------------------- -- Expand_Multiply_Fixed_By_Integer_Giving_Fixed -- --------------------------------------------------- -- Since the operand and result fixed-point type is the same, this is -- a straight multiply by the right operand, the small can be ignored. procedure Expand_Multiply_Fixed_By_Integer_Giving_Fixed (N : Node_Id) is begin Set_Result (N, Build_Multiply (N, Left_Opnd (N), Right_Opnd (N))); end Expand_Multiply_Fixed_By_Integer_Giving_Fixed; --------------------------------------------------- -- Expand_Multiply_Integer_By_Fixed_Giving_Fixed -- --------------------------------------------------- -- Since the operand and result fixed-point type is the same, this is -- a straight multiply by the right operand, the small can be ignored. procedure Expand_Multiply_Integer_By_Fixed_Giving_Fixed (N : Node_Id) is begin Set_Result (N, Build_Multiply (N, Left_Opnd (N), Right_Opnd (N))); end Expand_Multiply_Integer_By_Fixed_Giving_Fixed; --------------- -- Fpt_Value -- --------------- function Fpt_Value (N : Node_Id) return Node_Id is Typ : constant Entity_Id := Etype (N); begin if Is_Integer_Type (Typ) or else Is_Floating_Point_Type (Typ) then return Build_Conversion (N, Universal_Real, N); -- Fixed-point case, must get integer value first else return Build_Conversion (N, Universal_Real, N); end if; end Fpt_Value; --------------------- -- Integer_Literal -- --------------------- function Integer_Literal (N : Node_Id; V : Uint; Negative : Boolean := False) return Node_Id is T : Entity_Id; L : Node_Id; begin if V < Uint_2 ** 7 then T := Standard_Integer_8; elsif V < Uint_2 ** 15 then T := Standard_Integer_16; elsif V < Uint_2 ** 31 then T := Standard_Integer_32; elsif V < Uint_2 ** 63 then T := Standard_Integer_64; else return Empty; end if; if Negative then L := Make_Integer_Literal (Sloc (N), UI_Negate (V)); else L := Make_Integer_Literal (Sloc (N), V); end if; -- Set type of result in case used elsewhere (see note at start) Set_Etype (L, T); Set_Is_Static_Expression (L); -- We really need to set Analyzed here because we may be creating a -- very strange beast, namely an integer literal typed as fixed-point -- and the analyzer won't like that. Set_Analyzed (L); return L; end Integer_Literal; ------------------ -- Real_Literal -- ------------------ function Real_Literal (N : Node_Id; V : Ureal) return Node_Id is L : Node_Id; begin L := Make_Real_Literal (Sloc (N), V); -- Set type of result in case used elsewhere (see note at start) Set_Etype (L, Universal_Real); return L; end Real_Literal; ------------------------ -- Rounded_Result_Set -- ------------------------ function Rounded_Result_Set (N : Node_Id) return Boolean is K : constant Node_Kind := Nkind (N); begin if (K = N_Type_Conversion or else K = N_Op_Divide or else K = N_Op_Multiply) and then (Rounded_Result (N) or else Is_Integer_Type (Etype (N))) then return True; else return False; end if; end Rounded_Result_Set; ---------------- -- Set_Result -- ---------------- procedure Set_Result (N : Node_Id; Expr : Node_Id; Rchk : Boolean := False; Trunc : Boolean := False) is Cnode : Node_Id; Expr_Type : constant Entity_Id := Etype (Expr); Result_Type : constant Entity_Id := Etype (N); begin -- No conversion required if types match and no range check or truncate if Result_Type = Expr_Type and then not (Rchk or Trunc) then Cnode := Expr; -- Else perform required conversion else Cnode := Build_Conversion (N, Result_Type, Expr, Rchk, Trunc); end if; Rewrite (N, Cnode); Analyze_And_Resolve (N, Result_Type); end Set_Result; end Exp_Fixd;
-- SPDX-FileCopyrightText: 2021 Max Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT ------------------------------------------------------------- with Interfaces; with Ada.Streams; generic with procedure Raw_Read (Address : Interfaces.Unsigned_8; Value : out Interfaces.Unsigned_8); with procedure Raw_Write (Address : Interfaces.Unsigned_8; Value : Interfaces.Unsigned_8); package Lora is pragma Pure; procedure Initialize (Frequency : Positive); procedure Sleep; procedure Idle; procedure Receive; procedure On_DIO_0_Raise (Data : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); end Lora;
-- -- Copyright 2022 (C) Nicolas Pinault (aka DrPi) -- -- SPDX-License-Identifier: BSD-3-Clause -- with Ada.Text_IO; use Ada.Text_IO; package body Errors is function Fail (Code : Exit_Status; Msg : String) return Exit_Status is begin Put_Line (Msg); return Code; end Fail; function Fail_Read_Error return Exit_Status is begin return Fail (READ_FAILED, "Failed to read input file."); end Fail_Read_Error; function Fail_Write_Error return Exit_Status is begin return Fail (WRITE_FAILED, "Failed to write output file."); end Fail_Write_Error; end Errors;
-- SPDX-FileCopyrightText: 2019 Max Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT ------------------------------------------------------------- package body Program.Nodes.Short_Circuit_Operations is function Create (Left : not null Program.Elements.Expressions.Expression_Access; And_Token : Program.Lexical_Elements.Lexical_Element_Access; Then_Token : Program.Lexical_Elements.Lexical_Element_Access; Or_Token : Program.Lexical_Elements.Lexical_Element_Access; Else_Token : Program.Lexical_Elements.Lexical_Element_Access; Right : not null Program.Elements.Expressions.Expression_Access) return Short_Circuit_Operation is begin return Result : Short_Circuit_Operation := (Left => Left, And_Token => And_Token, Then_Token => Then_Token, Or_Token => Or_Token, Else_Token => Else_Token, Right => Right, Enclosing_Element => null) do Initialize (Result); end return; end Create; function Create (Left : not null Program.Elements.Expressions .Expression_Access; Right : not null Program.Elements.Expressions .Expression_Access; Is_Part_Of_Implicit : Boolean := False; Is_Part_Of_Inherited : Boolean := False; Is_Part_Of_Instance : Boolean := False; Has_And_Then : Boolean := False; Has_Or_Else : Boolean := False) return Implicit_Short_Circuit_Operation is begin return Result : Implicit_Short_Circuit_Operation := (Left => Left, Right => Right, Is_Part_Of_Implicit => Is_Part_Of_Implicit, Is_Part_Of_Inherited => Is_Part_Of_Inherited, Is_Part_Of_Instance => Is_Part_Of_Instance, Has_And_Then => Has_And_Then, Has_Or_Else => Has_Or_Else, Enclosing_Element => null) do Initialize (Result); end return; end Create; overriding function Left (Self : Base_Short_Circuit_Operation) return not null Program.Elements.Expressions.Expression_Access is begin return Self.Left; end Left; overriding function Right (Self : Base_Short_Circuit_Operation) return not null Program.Elements.Expressions.Expression_Access is begin return Self.Right; end Right; overriding function And_Token (Self : Short_Circuit_Operation) return Program.Lexical_Elements.Lexical_Element_Access is begin return Self.And_Token; end And_Token; overriding function Then_Token (Self : Short_Circuit_Operation) return Program.Lexical_Elements.Lexical_Element_Access is begin return Self.Then_Token; end Then_Token; overriding function Or_Token (Self : Short_Circuit_Operation) return Program.Lexical_Elements.Lexical_Element_Access is begin return Self.Or_Token; end Or_Token; overriding function Else_Token (Self : Short_Circuit_Operation) return Program.Lexical_Elements.Lexical_Element_Access is begin return Self.Else_Token; end Else_Token; overriding function Has_And_Then (Self : Short_Circuit_Operation) return Boolean is begin return Self.And_Token.Assigned; end Has_And_Then; overriding function Has_Or_Else (Self : Short_Circuit_Operation) return Boolean is begin return Self.Or_Token.Assigned; end Has_Or_Else; overriding function Is_Part_Of_Implicit (Self : Implicit_Short_Circuit_Operation) return Boolean is begin return Self.Is_Part_Of_Implicit; end Is_Part_Of_Implicit; overriding function Is_Part_Of_Inherited (Self : Implicit_Short_Circuit_Operation) return Boolean is begin return Self.Is_Part_Of_Inherited; end Is_Part_Of_Inherited; overriding function Is_Part_Of_Instance (Self : Implicit_Short_Circuit_Operation) return Boolean is begin return Self.Is_Part_Of_Instance; end Is_Part_Of_Instance; overriding function Has_And_Then (Self : Implicit_Short_Circuit_Operation) return Boolean is begin return Self.Has_And_Then; end Has_And_Then; overriding function Has_Or_Else (Self : Implicit_Short_Circuit_Operation) return Boolean is begin return Self.Has_Or_Else; end Has_Or_Else; procedure Initialize (Self : in out Base_Short_Circuit_Operation'Class) is begin Set_Enclosing_Element (Self.Left, Self'Unchecked_Access); Set_Enclosing_Element (Self.Right, Self'Unchecked_Access); null; end Initialize; overriding function Is_Short_Circuit_Operation (Self : Base_Short_Circuit_Operation) return Boolean is pragma Unreferenced (Self); begin return True; end Is_Short_Circuit_Operation; overriding function Is_Expression (Self : Base_Short_Circuit_Operation) return Boolean is pragma Unreferenced (Self); begin return True; end Is_Expression; overriding procedure Visit (Self : not null access Base_Short_Circuit_Operation; Visitor : in out Program.Element_Visitors.Element_Visitor'Class) is begin Visitor.Short_Circuit_Operation (Self); end Visit; overriding function To_Short_Circuit_Operation_Text (Self : in out Short_Circuit_Operation) return Program.Elements.Short_Circuit_Operations .Short_Circuit_Operation_Text_Access is begin return Self'Unchecked_Access; end To_Short_Circuit_Operation_Text; overriding function To_Short_Circuit_Operation_Text (Self : in out Implicit_Short_Circuit_Operation) return Program.Elements.Short_Circuit_Operations .Short_Circuit_Operation_Text_Access is pragma Unreferenced (Self); begin return null; end To_Short_Circuit_Operation_Text; end Program.Nodes.Short_Circuit_Operations;
----------------------------------------------------------------------- -- awa-mail-components-factory -- Mail UI Component Factory -- Copyright (C) 2012, 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 ASF.Views.Nodes; with ASF.Components.Base; with AWA.Mail.Modules; with AWA.Mail.Components.Messages; with AWA.Mail.Components.Recipients; with AWA.Mail.Components.Attachments; package body AWA.Mail.Components.Factory is use ASF.Components.Base; use ASF.Views.Nodes; function Create_Bcc return UIComponent_Access; function Create_Body return UIComponent_Access; function Create_Cc return UIComponent_Access; function Create_From return UIComponent_Access; function Create_Message return UIComponent_Access; function Create_To return UIComponent_Access; function Create_Subject return UIComponent_Access; function Create_Attachment return UIComponent_Access; URI : aliased constant String := "http://code.google.com/p/ada-awa/mail"; BCC_TAG : aliased constant String := "bcc"; BODY_TAG : aliased constant String := "body"; CC_TAG : aliased constant String := "cc"; FROM_TAG : aliased constant String := "from"; MESSAGE_TAG : aliased constant String := "message"; SUBJECT_TAG : aliased constant String := "subject"; TO_TAG : aliased constant String := "to"; ATTACHMENT_TAG : aliased constant String := "attachment"; -- ------------------------------ -- Create an UIMailRecipient component -- ------------------------------ function Create_Bcc return UIComponent_Access is Result : constant Recipients.UIMailRecipient_Access := new Recipients.UIMailRecipient; begin Result.Set_Recipient (AWA.Mail.Clients.BCC); return Result.all'Access; end Create_Bcc; -- ------------------------------ -- Create an UIMailBody component -- ------------------------------ function Create_Body return UIComponent_Access is begin return new Messages.UIMailBody; end Create_Body; -- ------------------------------ -- Create an UIMailRecipient component -- ------------------------------ function Create_Cc return UIComponent_Access is Result : constant Recipients.UIMailRecipient_Access := new Recipients.UIMailRecipient; begin Result.Set_Recipient (AWA.Mail.Clients.CC); return Result.all'Access; end Create_Cc; -- ------------------------------ -- Create an UISender component -- ------------------------------ function Create_From return UIComponent_Access is begin return new Recipients.UISender; end Create_From; -- ------------------------------ -- Create an UIMailMessage component -- ------------------------------ function Create_Message return UIComponent_Access is use type AWA.Mail.Modules.Mail_Module_Access; Result : constant Messages.UIMailMessage_Access := new Messages.UIMailMessage; Module : constant AWA.Mail.Modules.Mail_Module_Access := AWA.Mail.Modules.Get_Mail_Module; begin if Module = null then return null; end if; Result.Set_Message (Module.Create_Message); return Result.all'Access; end Create_Message; -- ------------------------------ -- Create an UIMailSubject component -- ------------------------------ function Create_Subject return UIComponent_Access is begin return new Messages.UIMailSubject; end Create_Subject; -- ------------------------------ -- Create an UIMailRecipient component -- ------------------------------ function Create_To return UIComponent_Access is begin return new Recipients.UIMailRecipient; end Create_To; -- ------------------------------ -- Create an UIMailAttachment component -- ------------------------------ function Create_Attachment return UIComponent_Access is begin return new Attachments.UIMailAttachment; end Create_Attachment; Bindings : aliased constant ASF.Factory.Binding_Array := (1 => (Name => ATTACHMENT_TAG'Access, Component => Create_Attachment'Access, Tag => Create_Component_Node'Access), 2 => (Name => BCC_TAG'Access, Component => Create_Bcc'Access, Tag => Create_Component_Node'Access), 3 => (Name => BODY_TAG'Access, Component => Create_Body'Access, Tag => Create_Component_Node'Access), 4 => (Name => CC_TAG'Access, Component => Create_Cc'Access, Tag => Create_Component_Node'Access), 5 => (Name => FROM_TAG'Access, Component => Create_From'Access, Tag => Create_Component_Node'Access), 6 => (Name => MESSAGE_TAG'Access, Component => Create_Message'Access, Tag => Create_Component_Node'Access), 7 => (Name => SUBJECT_TAG'Access, Component => Create_Subject'Access, Tag => Create_Component_Node'Access), 8 => (Name => TO_TAG'Access, Component => Create_To'Access, Tag => Create_Component_Node'Access) ); Mail_Factory : aliased constant ASF.Factory.Factory_Bindings := (URI => URI'Access, Bindings => Bindings'Access); -- ------------------------------ -- Get the AWA Mail component factory. -- ------------------------------ function Definition return ASF.Factory.Factory_Bindings_Access is begin return Mail_Factory'Access; end Definition; end AWA.Mail.Components.Factory;
package body Benchmark.Hash is function Create_Hash return Benchmark_Pointer is begin return new Hash_Type; end Create_Hash; procedure Set_Argument(benchmark : in out Hash_Type; arg : in String) is value : constant String := Extract_Argument(arg); begin if Check_Argument(arg, "size") then benchmark.size := Positive'Value(value); elsif Check_Argument(arg, "iterations") then benchmark.iterations := Positive'Value(value); else Set_Argument(Benchmark_Type(benchmark), arg); end if; exception when others => raise Invalid_Argument; end Set_Argument; procedure Run(benchmark : in Hash_Type) is begin for i in 1 .. benchmark.iterations loop declare rand : constant Integer := Get_Random(benchmark); index : constant Natural := rand mod benchmark.size; begin if (Get_Random(benchmark) mod 2) = 0 then Read(benchmark, Address_Type(index) * 4, 4); else Write(benchmark, Address_Type(index) * 4, 4); end if; Idle(benchmark, benchmark.spacing); end; end loop; end Run; end Benchmark.Hash;
-- Copyright (c) 2020 Raspberry Pi (Trading) Ltd. -- -- SPDX-License-Identifier: BSD-3-Clause -- This spec has been automatically generated from rp2040.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with HAL; with System; package RP_SVD.ROSC is pragma Preelaborate; --------------- -- Registers -- --------------- -- Controls the number of delay stages in the ROSC ring\n LOW uses stages 0 -- to 7\n MEDIUM uses stages 0 to 5\n HIGH uses stages 0 to 3\n TOOHIGH -- uses stages 0 to 1 and should not be used because its frequency exceeds -- design specifications\n The clock output will not glitch when changing -- the range up one step at a time\n The clock output will glitch when -- changing the range down\n Note: the values here are gray coded which is -- why HIGH comes before TOOHIGH type CTRL_FREQ_RANGE_Field is (-- Reset value for the field Ctrl_Freq_Range_Field_Reset, Low, Medium, Toohigh, High) with Size => 12; for CTRL_FREQ_RANGE_Field use (Ctrl_Freq_Range_Field_Reset => 2720, Low => 4004, Medium => 4005, Toohigh => 4006, High => 4007); -- On power-up this field is initialised to ENABLE\n The system clock must -- be switched to another source before setting this field to DISABLE -- otherwise the chip will lock up\n The 12-bit code is intended to give -- some protection against accidental writes. An invalid setting will -- enable the oscillator. type CTRL_ENABLE_Field is (-- Reset value for the field Ctrl_Enable_Field_Reset, Disable, Enable) with Size => 12; for CTRL_ENABLE_Field use (Ctrl_Enable_Field_Reset => 0, Disable => 3358, Enable => 4011); -- Ring Oscillator control type CTRL_Register is record -- Controls the number of delay stages in the ROSC ring\n LOW uses -- stages 0 to 7\n MEDIUM uses stages 0 to 5\n HIGH uses stages 0 to 3\n -- TOOHIGH uses stages 0 to 1 and should not be used because its -- frequency exceeds design specifications\n The clock output will not -- glitch when changing the range up one step at a time\n The clock -- output will glitch when changing the range down\n Note: the values -- here are gray coded which is why HIGH comes before TOOHIGH FREQ_RANGE : CTRL_FREQ_RANGE_Field := Ctrl_Freq_Range_Field_Reset; -- On power-up this field is initialised to ENABLE\n The system clock -- must be switched to another source before setting this field to -- DISABLE otherwise the chip will lock up\n The 12-bit code is intended -- to give some protection against accidental writes. An invalid setting -- will enable the oscillator. ENABLE : CTRL_ENABLE_Field := Ctrl_Enable_Field_Reset; -- unspecified Reserved_24_31 : HAL.UInt8 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CTRL_Register use record FREQ_RANGE at 0 range 0 .. 11; ENABLE at 0 range 12 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; subtype FREQA_DS0_Field is HAL.UInt3; subtype FREQA_DS1_Field is HAL.UInt3; subtype FREQA_DS2_Field is HAL.UInt3; subtype FREQA_DS3_Field is HAL.UInt3; -- Set to 0x9696 to apply the settings\n Any other value in this field will -- set all drive strengths to 0 type FREQA_PASSWD_Field is (-- Reset value for the field Freqa_Passwd_Field_Reset, Pass) with Size => 16; for FREQA_PASSWD_Field use (Freqa_Passwd_Field_Reset => 0, Pass => 38550); -- The FREQA & FREQB registers control the frequency by controlling the -- drive strength of each stage\n The drive strength has 4 levels -- determined by the number of bits set\n Increasing the number of bits set -- increases the drive strength and increases the oscillation frequency\n 0 -- bits set is the default drive strength\n 1 bit set doubles the drive -- strength\n 2 bits set triples drive strength\n 3 bits set quadruples -- drive strength type FREQA_Register is record -- Stage 0 drive strength DS0 : FREQA_DS0_Field := 16#0#; -- unspecified Reserved_3_3 : HAL.Bit := 16#0#; -- Stage 1 drive strength DS1 : FREQA_DS1_Field := 16#0#; -- unspecified Reserved_7_7 : HAL.Bit := 16#0#; -- Stage 2 drive strength DS2 : FREQA_DS2_Field := 16#0#; -- unspecified Reserved_11_11 : HAL.Bit := 16#0#; -- Stage 3 drive strength DS3 : FREQA_DS3_Field := 16#0#; -- unspecified Reserved_15_15 : HAL.Bit := 16#0#; -- Set to 0x9696 to apply the settings\n Any other value in this field -- will set all drive strengths to 0 PASSWD : FREQA_PASSWD_Field := Freqa_Passwd_Field_Reset; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for FREQA_Register use record DS0 at 0 range 0 .. 2; Reserved_3_3 at 0 range 3 .. 3; DS1 at 0 range 4 .. 6; Reserved_7_7 at 0 range 7 .. 7; DS2 at 0 range 8 .. 10; Reserved_11_11 at 0 range 11 .. 11; DS3 at 0 range 12 .. 14; Reserved_15_15 at 0 range 15 .. 15; PASSWD at 0 range 16 .. 31; end record; subtype FREQB_DS4_Field is HAL.UInt3; subtype FREQB_DS5_Field is HAL.UInt3; subtype FREQB_DS6_Field is HAL.UInt3; subtype FREQB_DS7_Field is HAL.UInt3; -- Set to 0x9696 to apply the settings\n Any other value in this field will -- set all drive strengths to 0 type FREQB_PASSWD_Field is (-- Reset value for the field Freqb_Passwd_Field_Reset, Pass) with Size => 16; for FREQB_PASSWD_Field use (Freqb_Passwd_Field_Reset => 0, Pass => 38550); -- For a detailed description see freqa register type FREQB_Register is record -- Stage 4 drive strength DS4 : FREQB_DS4_Field := 16#0#; -- unspecified Reserved_3_3 : HAL.Bit := 16#0#; -- Stage 5 drive strength DS5 : FREQB_DS5_Field := 16#0#; -- unspecified Reserved_7_7 : HAL.Bit := 16#0#; -- Stage 6 drive strength DS6 : FREQB_DS6_Field := 16#0#; -- unspecified Reserved_11_11 : HAL.Bit := 16#0#; -- Stage 7 drive strength DS7 : FREQB_DS7_Field := 16#0#; -- unspecified Reserved_15_15 : HAL.Bit := 16#0#; -- Set to 0x9696 to apply the settings\n Any other value in this field -- will set all drive strengths to 0 PASSWD : FREQB_PASSWD_Field := Freqb_Passwd_Field_Reset; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for FREQB_Register use record DS4 at 0 range 0 .. 2; Reserved_3_3 at 0 range 3 .. 3; DS5 at 0 range 4 .. 6; Reserved_7_7 at 0 range 7 .. 7; DS6 at 0 range 8 .. 10; Reserved_11_11 at 0 range 11 .. 11; DS7 at 0 range 12 .. 14; Reserved_15_15 at 0 range 15 .. 15; PASSWD at 0 range 16 .. 31; end record; -- set to 0xaa0 + div where\n div = 0 divides by 32\n div = 1-31 divides by -- div\n any other value sets div=0 and therefore divides by 32\n this -- register resets to div=16 type DIV_DIV_Field is (-- Reset value for the field Div_Div_Field_Reset, Pass) with Size => 12; for DIV_DIV_Field use (Div_Div_Field_Reset => 0, Pass => 2720); -- Controls the output divider type DIV_Register is record -- set to 0xaa0 + div where\n div = 0 divides by 32\n div = 1-31 divides -- by div\n any other value sets div=0 and therefore divides by 32\n -- this register resets to div=16 DIV : DIV_DIV_Field := Div_Div_Field_Reset; -- unspecified Reserved_12_31 : HAL.UInt20 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for DIV_Register use record DIV at 0 range 0 .. 11; Reserved_12_31 at 0 range 12 .. 31; end record; subtype PHASE_SHIFT_Field is HAL.UInt2; subtype PHASE_PASSWD_Field is HAL.UInt8; -- Controls the phase shifted output type PHASE_Register is record -- phase shift the phase-shifted output by SHIFT input clocks\n this can -- be changed on-the-fly\n must be set to 0 before setting div=1 SHIFT : PHASE_SHIFT_Field := 16#0#; -- invert the phase-shifted output\n this is ignored when div=1 FLIP : Boolean := False; -- enable the phase-shifted output\n this can be changed on-the-fly ENABLE : Boolean := True; -- set to 0xaa0\n any other value enables the output with shift=0 PASSWD : PHASE_PASSWD_Field := 16#0#; -- unspecified Reserved_12_31 : HAL.UInt20 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for PHASE_Register use record SHIFT at 0 range 0 .. 1; FLIP at 0 range 2 .. 2; ENABLE at 0 range 3 .. 3; PASSWD at 0 range 4 .. 11; Reserved_12_31 at 0 range 12 .. 31; end record; -- Ring Oscillator Status type STATUS_Register is record -- unspecified Reserved_0_11 : HAL.UInt12 := 16#0#; -- Read-only. Oscillator is enabled but not necessarily running and -- stable\n this resets to 0 but transitions to 1 during chip startup ENABLED : Boolean := False; -- unspecified Reserved_13_15 : HAL.UInt3 := 16#0#; -- Read-only. post-divider is running\n this resets to 0 but transitions -- to 1 during chip startup DIV_RUNNING : Boolean := False; -- unspecified Reserved_17_23 : HAL.UInt7 := 16#0#; -- Write data bit of one shall clear (set to zero) the corresponding bit -- in the field. An invalid value has been written to CTRL_ENABLE or -- CTRL_FREQ_RANGE or FRFEQA or FREQB or DORMANT BADWRITE : Boolean := False; -- unspecified Reserved_25_30 : HAL.UInt6 := 16#0#; -- Read-only. Oscillator is running and stable STABLE : Boolean := False; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for STATUS_Register use record Reserved_0_11 at 0 range 0 .. 11; ENABLED at 0 range 12 .. 12; Reserved_13_15 at 0 range 13 .. 15; DIV_RUNNING at 0 range 16 .. 16; Reserved_17_23 at 0 range 17 .. 23; BADWRITE at 0 range 24 .. 24; Reserved_25_30 at 0 range 25 .. 30; STABLE at 0 range 31 .. 31; end record; -- This just reads the state of the oscillator output so randomness is -- compromised if the ring oscillator is stopped or run at a harmonic of -- the bus frequency type RANDOMBIT_Register is record -- Read-only. RANDOMBIT : Boolean; -- unspecified Reserved_1_31 : HAL.UInt31; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for RANDOMBIT_Register use record RANDOMBIT at 0 range 0 .. 0; Reserved_1_31 at 0 range 1 .. 31; end record; subtype COUNT_COUNT_Field is HAL.UInt8; -- A down counter running at the ROSC frequency which counts to zero and -- stops.\n To start the counter write a non-zero value.\n Can be used for -- short software pauses when setting up time sensitive hardware. type COUNT_Register is record COUNT : COUNT_COUNT_Field := 16#0#; -- unspecified Reserved_8_31 : HAL.UInt24 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for COUNT_Register use record COUNT at 0 range 0 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; ----------------- -- Peripherals -- ----------------- type ROSC_Peripheral is record -- Ring Oscillator control CTRL : aliased CTRL_Register; -- The FREQA & FREQB registers control the frequency by controlling the -- drive strength of each stage\n The drive strength has 4 levels -- determined by the number of bits set\n Increasing the number of bits -- set increases the drive strength and increases the oscillation -- frequency\n 0 bits set is the default drive strength\n 1 bit set -- doubles the drive strength\n 2 bits set triples drive strength\n 3 -- bits set quadruples drive strength FREQA : aliased FREQA_Register; -- For a detailed description see freqa register FREQB : aliased FREQB_Register; -- Ring Oscillator pause control\n This is used to save power by pausing -- the ROSC\n On power-up this field is initialised to WAKE\n An invalid -- write will also select WAKE\n Warning: setup the irq before selecting -- dormant mode DORMANT : aliased HAL.UInt32; -- Controls the output divider DIV : aliased DIV_Register; -- Controls the phase shifted output PHASE : aliased PHASE_Register; -- Ring Oscillator Status STATUS : aliased STATUS_Register; -- This just reads the state of the oscillator output so randomness is -- compromised if the ring oscillator is stopped or run at a harmonic of -- the bus frequency RANDOMBIT : aliased RANDOMBIT_Register; -- A down counter running at the ROSC frequency which counts to zero and -- stops.\n To start the counter write a non-zero value.\n Can be used -- for short software pauses when setting up time sensitive hardware. COUNT : aliased COUNT_Register; end record with Volatile; for ROSC_Peripheral use record CTRL at 16#0# range 0 .. 31; FREQA at 16#4# range 0 .. 31; FREQB at 16#8# range 0 .. 31; DORMANT at 16#C# range 0 .. 31; DIV at 16#10# range 0 .. 31; PHASE at 16#14# range 0 .. 31; STATUS at 16#18# range 0 .. 31; RANDOMBIT at 16#1C# range 0 .. 31; COUNT at 16#20# range 0 .. 31; end record; ROSC_Periph : aliased ROSC_Peripheral with Import, Address => ROSC_Base; end RP_SVD.ROSC;
with Ada.Strings.Unbounded; with Ada.Text_IO; package body kv.avm.Code_Buffers is function "+"(S : String) return String_Type renames Ada.Strings.Unbounded.To_Unbounded_String; function "+"(U : String_Type) return String renames Ada.Strings.Unbounded.To_String; procedure Put_Meta (Self : in out Buffer_Type; Data : in String) is begin Self.Count := Self.Count + 1; Self.Buffer(Self.Count) := +Data; end Put_Meta; procedure Put_Instruction (Self : in out Buffer_Type; Data : in String) is begin Self.Code := Self.Code + 1; Self.Count := Self.Count + 1; Self.Buffer(Self.Count) := +Data; end Put_Instruction; procedure Put_Comment (Self : in out Buffer_Type; Data : in String) is begin Self.Count := Self.Count + 1; Self.Buffer(Self.Count) := +Data; end Put_Comment; procedure Append (Self : in out Buffer_Type; Data : in Buffer_Type) is begin for I in 1 .. Data.Count loop Self.Count := Self.Count + 1; Self.Buffer(Self.Count) := Data.Buffer(I); end loop; Self.Code := Self.Code + Data.Code; end Append; function Code_Count(Self : Buffer_Type) return Natural is begin return Self.Code; end Code_Count; procedure Print (Self : in Buffer_Type) is begin for I in 1 .. Self.Count loop Ada.Text_IO.Put_Line(+Self.Buffer(I)); end loop; end Print; procedure Process_Lines (Self : in Buffer_Type; Processor : access procedure(Line : String)) is begin for I in 1 .. Self.Count loop Processor.all(+Self.Buffer(I)); end loop; end Process_Lines; end kv.avm.Code_Buffers;
-- ___ _ ___ _ _ -- -- / __| |/ (_) | | Common SKilL implementation -- -- \__ \ ' <| | | |__ stream manipulation package -- -- |___/_|\_\_|_|____| by: Timm Felden, Dennis Przytarski -- -- -- pragma Ada_2012; with Interfaces.C; with Interfaces.C.Pointers; with Skill.Types; limited with Skill.Streams.Reader; limited with Skill.Streams.Writer; with Interfaces.C_Streams; package Skill.Streams is type Unsigned_Char_Array is array (Interfaces.C.size_t range <>) of aliased Interfaces.C.unsigned_char; pragma Convention (C, Unsigned_Char_Array); for Unsigned_Char_Array'Component_Size use Interfaces.C.unsigned_char'Size; function Input (Path : Skill.Types.String_Access) return Skill.Streams.Reader.Input_Stream; function Write (Path : Skill.Types.String_Access) return Skill.Streams.Writer.Output_Stream; function Append (Path : Skill.Types.String_Access) return Skill.Streams.Writer.Output_Stream; private package C renames Interfaces.C; type Uchar_Array is array (C.size_t range <>) of aliased C.unsigned_char; package Uchar is new C.Pointers (Index => C.size_t, Element => C.unsigned_char, Element_Array => Uchar_Array, Default_Terminator => 0); subtype Map_Pointer is not null Uchar.Pointer; -- returns an invalid map pointer, that can be used in empty maps function Invalid_Pointer return Map_Pointer; pragma Inline (Invalid_Pointer); pragma Pure_Function (Invalid_Pointer); type Mmap is record File : Interfaces.C_Streams.FILEs; Length : Interfaces.C.size_t; Map : Uchar.Pointer; end record; end Skill.Streams;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2017, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with FE310.GPIO; use FE310.GPIO; with FE310.UART; use FE310.UART; with FE310_SVD; package FE310.Device is P00 : aliased GPIO_Point (Pin => 00); P01 : aliased GPIO_Point (Pin => 01); P02 : aliased GPIO_Point (Pin => 02); P03 : aliased GPIO_Point (Pin => 03); P04 : aliased GPIO_Point (Pin => 04); P05 : aliased GPIO_Point (Pin => 05); P06 : aliased GPIO_Point (Pin => 06); P07 : aliased GPIO_Point (Pin => 07); P08 : aliased GPIO_Point (Pin => 08); P09 : aliased GPIO_Point (Pin => 09); P10 : aliased GPIO_Point (Pin => 10); P11 : aliased GPIO_Point (Pin => 11); P12 : aliased GPIO_Point (Pin => 12); P13 : aliased GPIO_Point (Pin => 13); P14 : aliased GPIO_Point (Pin => 14); P15 : aliased GPIO_Point (Pin => 15); P16 : aliased GPIO_Point (Pin => 16); P17 : aliased GPIO_Point (Pin => 17); P18 : aliased GPIO_Point (Pin => 18); P19 : aliased GPIO_Point (Pin => 19); P20 : aliased GPIO_Point (Pin => 20); P21 : aliased GPIO_Point (Pin => 21); P22 : aliased GPIO_Point (Pin => 22); P23 : aliased GPIO_Point (Pin => 23); P24 : aliased GPIO_Point (Pin => 24); P25 : aliased GPIO_Point (Pin => 25); P26 : aliased GPIO_Point (Pin => 26); P27 : aliased GPIO_Point (Pin => 27); P28 : aliased GPIO_Point (Pin => 28); P29 : aliased GPIO_Point (Pin => 29); P30 : aliased GPIO_Point (Pin => 30); P31 : aliased GPIO_Point (Pin => 31); IOF_UART0 : constant IO_Function := IOF0; IOF_UART1 : constant IO_Function := IOF0; IOF_QSPI1 : constant IO_Function := IOF0; IOF_QSPI2 : constant IO_Function := IOF0; IOF_PWM0 : constant IO_Function := IOF1; IOF_PWM1 : constant IO_Function := IOF1; IOF_PWM2 : constant IO_Function := IOF1; Internal_UART0 : aliased Internal_UART with Import, Volatile, Address => FE310_SVD.UART0_Base; Internal_UART1 : aliased Internal_UART with Import, Volatile, Address => FE310_SVD.UART1_Base; UART0 : aliased UART_Port (Internal_UART0'Access); UART1 : aliased UART_Port (Internal_UART1'Access); end FE310.Device;
package body Self is function G (X : Integer) return Lim is begin return R : Lim := (Comp => X, others => <>); end G; procedure Change (X : in out Lim; Incr : Integer) is begin X.Comp := X.Comp + Incr; X.Self_Default.Comp := X.Comp + Incr; X.Self_Anon_Default.Comp := X.Comp + Incr; end Change; function Get (X : Lim) return Integer is begin return X.Comp; end; end Self;
----------------------------------------------------------------------- -- messages - A simple memory-based forum -- Copyright (C) 2012, 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.Calendar; with Util.Beans.Objects.Time; with ASF.Events.Faces.Actions; package body Messages is use Ada.Strings.Unbounded; Database : aliased Forum; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ function Get_Value (From : in Message_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "text" then return Util.Beans.Objects.To_Object (From.Text); elsif Name = "email" then return Util.Beans.Objects.To_Object (From.Email); elsif Name = "id" then return Util.Beans.Objects.To_Object (Integer (From.Id)); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ procedure Set_Value (From : in out Message_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "text" then From.Text := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "email" then From.Email := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "id" then From.Id := Message_Id (Util.Beans.Objects.To_Integer (Value)); end if; end Set_Value; -- ------------------------------ -- Post the message. -- ------------------------------ procedure Post (From : in out Message_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin if Length (From.Text) > 200 then Ada.Strings.Unbounded.Replace_Slice (From.Text, 200, Length (From.Text), "..."); end if; Database.Post (From); Outcome := To_Unbounded_String ("posted"); end Post; package Post_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Message_Bean, Method => Post, Name => "post"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (Post_Binding.Proxy'Unchecked_Access, Post_Binding.Proxy'Unchecked_Access); -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Message_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Binding_Array'Access; end Get_Method_Bindings; -- ------------------------------ -- Create a message bean instance. -- ------------------------------ function Create_Message_Bean return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Message_Bean_Access := new Message_Bean; begin return Result.all'Access; end Create_Message_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Forum_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "count" then return Util.Beans.Objects.To_Object (Integer (From.Get_Count)); elsif Name = "today" then return Util.Beans.Objects.Time.To_Object (Ada.Calendar.Clock); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Get the number of elements in the list. -- ------------------------------ overriding function Get_Count (From : in Forum_Bean) return Natural is pragma Unreferenced (From); begin return Database.Get_Message_Count; end Get_Count; -- ------------------------------ -- Set the current row index. Valid row indexes start at 1. -- ------------------------------ overriding procedure Set_Row_Index (From : in out Forum_Bean; Index : in Natural) is begin From.Pos := Message_Id (Index); From.Msg := Database.Get_Message (From.Pos); end Set_Row_Index; -- ------------------------------ -- Get the element at the current row index. -- ------------------------------ overriding function Get_Row (From : in Forum_Bean) return Util.Beans.Objects.Object is begin return From.Current; end Get_Row; -- ------------------------------ -- Create the list of messages. -- ------------------------------ function Create_Message_List return Util.Beans.Basic.Readonly_Bean_Access is F : constant Forum_Bean_Access := new Forum_Bean; begin F.Current := Util.Beans.Objects.To_Object (F.Msg'Access, Util.Beans.Objects.STATIC); return F.all'Access; end Create_Message_List; protected body Forum is -- ------------------------------ -- Post the message in the forum. -- ------------------------------ procedure Post (Message : in Message_Bean) is use type Ada.Containers.Count_Type; begin if Messages.Length > 100 then Messages.Delete (Message_Id'First); end if; Messages.Append (Message); end Post; -- ------------------------------ -- Delete the message identified by <b>Id</b>. -- ------------------------------ procedure Delete (Id : in Message_Id) is begin Messages.Delete (Id); end Delete; -- ------------------------------ -- Get the message identified by <b>Id</b>. -- ------------------------------ function Get_Message (Id : in Message_Id) return Message_Bean is begin return Messages.Element (Id); end Get_Message; -- ------------------------------ -- Get the number of messages in the forum. -- ------------------------------ function Get_Message_Count return Natural is begin return Natural (Messages.Length); end Get_Message_Count; end Forum; end Messages;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2017-2020, Fabien Chouteau -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with Ada.Text_IO; with System.Machine_Code; use System.Machine_Code; with AGATE.Arch.ArmvX_m; package body AGATE.SysCalls is SysCall_Handler_Table : array (Syscall_ID) of Syscall_Handler := (others => null); procedure SVCall_Handler; pragma Export (C, SVCall_Handler, "SVC_Handler"); -------------------- -- SVCall_Handler -- -------------------- procedure SVCall_Handler is type Stack_Array is array (1 .. 4) of Word with Pack, Size => 4 * 32; SP : System.Address; Ret : UInt64; Ret_Lo : Word; Ret_Hi : Word; ID : Syscall_ID; begin Check_All_Stack_Canaries; SP := System.Address (Arch.ArmvX_m.PSP); if SP mod Stack_Array'Alignment /= 0 then Ada.Text_IO.Put_Line ("Invalid SP address"); else declare Args : Stack_Array with Address => SP; begin if Args (1) in Syscall_ID'Pos (Syscall_ID'First) .. Syscall_ID'Pos (Syscall_ID'Last) then ID := Syscall_ID'Val (Args (1)); if SysCall_Handler_Table (ID) /= null then Ret := SysCall_Handler_Table (ID) (Args (2), Args (3), Args (4)); else raise Program_Error with "No handler for Syscall"; end if; else raise Program_Error with "Invalid syscall ID"; end if; end; end if; Ret_Lo := Word (Ret and 16#FFFF_FFFF#); Ret_Hi := Word (Shift_Right (Ret, 32) and 16#FFFF_FFFF#); Asm ("mrs r1, psp" & ASCII.LF & "str %0, [r1]" & ASCII.LF & "str %1, [r1, 4]", Inputs => (Word'Asm_Input ("r", Ret_Lo), Word'Asm_Input ("r", Ret_Hi)), Volatile => True, Clobber => "r1"); end SVCall_Handler; ---------- -- Call -- ---------- function Call (ID : Syscall_ID; Arg1, Arg2, Arg3 : Word := 0) return UInt64 is Ret_Lo, Ret_Hi : Word; begin Asm ("mov r0, %2" & ASCII.LF & "mov r1, %3" & ASCII.LF & "mov r2, %4" & ASCII.LF & "mov r3, %5" & ASCII.LF & "svc 1" & ASCII.LF & "mov %0, r0" & ASCII.LF & "mov %1, r1", Outputs => (Word'Asm_Output ("=r", Ret_Lo), Word'Asm_Output ("=r", Ret_Hi)), Inputs => (Syscall_ID'Asm_Input ("r", ID), Word'Asm_Input ("r", Arg1), Word'Asm_Input ("r", Arg2), Word'Asm_Input ("r", Arg3)), Clobber => "r0,r1,r2,r3", Volatile => True); return Shift_Left (UInt64 (Ret_Hi), 32) or UInt64 (Ret_Lo); end Call; ---------- -- Call -- ---------- procedure Call (ID : Syscall_ID; Arg1, Arg2, Arg3 : Word := 0) is Unref : UInt64 with Unreferenced; begin Unref := Call (ID, Arg1, Arg2, Arg3); end Call; --------------- -- Registred -- --------------- function Registred (ID : Syscall_ID) return Boolean is (SysCall_Handler_Table (ID) /= null); -------------- -- Register -- -------------- procedure Register (ID : Syscall_ID; Handler : not null Syscall_Handler) is begin if not Registred (ID) then SysCall_Handler_Table (ID) := Handler; end if; end Register; end AGATE.SysCalls;
with Ada.Numerics.Generic_Elementary_Functions; with Ada.Text_IO; use Ada.Text_IO; with GNATCOLL.GMP.Integers; with GNATCOLL.GMP.Lib; procedure Hamming is type Log_Type is new Long_Long_Float; package Funcs is new Ada.Numerics.Generic_Elementary_Functions (Log_Type); type Factors_Array is array (Positive range <>) of Positive; generic Factors : Factors_Array := (2, 3, 5); -- The factors for smooth numbers. Hamming numbers are 5-smooth. package Smooth_Numbers is type Number is private; function Compute (Nth : Positive) return Number; function Image (N : Number) return String; private type Exponent_Type is new Natural; type Exponents_Array is array (Factors'Range) of Exponent_Type; -- Numbers are stored as the exponents of the prime factors. type Number is record Exponents : Exponents_Array; Log : Log_Type; -- The log of the value, used to ease sorting. end record; function "=" (N1, N2 : Number) return Boolean is (for all F in Factors'Range => N1.Exponents (F) = N2.Exponents (F)); end Smooth_Numbers; package body Smooth_Numbers is One : constant Number := (Exponents => (others => 0), Log => 0.0); Factors_Log : array (Factors'Range) of Log_Type; function Image (N : Number) return String is use GNATCOLL.GMP.Integers, GNATCOLL.GMP.Lib; R, Tmp : Big_Integer; begin Set (R, "1"); for F in Factors'Range loop Set (Tmp, Factors (F)'Image); Raise_To_N (Tmp, GNATCOLL.GMP.Unsigned_Long (N.Exponents (F))); Multiply (R, Tmp); end loop; return Image (R); end Image; function Compute (Nth : Positive) return Number is Candidates : array (Factors'Range) of Number; Values : array (1 .. Nth) of Number; -- Will result in Storage_Error for very large values of Nth Indices : array (Factors'Range) of Natural := (others => Values'First); Current : Number; Tmp : Number; begin for F in Factors'Range loop Factors_Log (F) := Funcs.Log (Log_Type (Factors (F))); Candidates (F) := One; Candidates (F).Exponents (F) := 1; Candidates (F).Log := Factors_Log (F); end loop; Values (1) := One; for Count in 2 .. Nth loop -- Find next value (the lowest of the candidates) Current := Candidates (Factors'First); for F in Factors'First + 1 .. Factors'Last loop if Candidates (F).Log < Current.Log then Current := Candidates (F); end if; end loop; Values (Count) := Current; -- Update the candidates. There might be several candidates with -- the same value for F in Factors'Range loop if Candidates (F) = Current then Indices (F) := Indices (F) + 1; Tmp := Values (Indices (F)); Tmp.Exponents (F) := Tmp.Exponents (F) + 1; Tmp.Log := Tmp.Log + Factors_Log (F); Candidates (F) := Tmp; end if; end loop; end loop; return Values (Nth); end Compute; end Smooth_Numbers; package Hamming is new Smooth_Numbers ((2, 3, 5)); begin for N in 1 .. 20 loop Put (" " & Hamming.Image (Hamming.Compute (N))); end loop; New_Line; Put_Line (Hamming.Image (Hamming.Compute (1691))); Put_Line (Hamming.Image (Hamming.Compute (1_000_000))); end Hamming;
with ACO.Events; package body ACO.Protocols.Error_Control is overriding function Is_Valid (This : in out EC; Msg : in ACO.Messages.Message) return Boolean is pragma Unreferenced (This); use type ACO.Messages.Function_Code; begin return ACO.Messages.Func_Code (Msg) = EC_Id; end Is_Valid; procedure Message_Received (This : in out EC; Msg : in ACO.Messages.Message) is begin if EC_Commands.Is_Valid_Command (Msg, This.Id) then declare Hbt_State : constant EC_Commands.EC_State := EC_Commands.Get_EC_State (Msg); Id : constant ACO.Messages.Node_Nr := ACO.Messages.Node_Id (Msg); begin This.Od.Events.Node_Events.Put ((Event => ACO.Events.Heartbeat_Received, Received_Heartbeat => (Id => Id, State => EC_Commands.To_State (Hbt_State)))); This.On_Heartbeat (Id, Hbt_State); end; end if; end Message_Received; procedure EC_Log (This : in out EC; Level : in ACO.Log.Log_Level; Message : in String) is pragma Unreferenced (This); begin ACO.Log.Put_Line (Level, "(EC) " & Message); end EC_Log; end ACO.Protocols.Error_Control;
-- (C) Copyright 2000 by John Halleck, All rights reserved. -- Basic Routines of NSA's Secure Hash Algorithm. -- This is part of a project at http://www.cc.utah.edu/~nahaj/ package SHA.Process_Data is -- If you want to accumulate more than one hash at a time, then -- you'll need to specify a context for each accumulation. type Context is private; -- Current state of the operation. -- What we can put in a buffer. type Bit is mod 2 ** 1; type Byte is mod 2 ** 8; type Word is mod 2 ** 16; type Long is mod 2 ** 32; -- I know that this might not agree with the terminology of the -- underlying machine, but I had to call them something. Bytes_In_Block : constant := 64; -- Strictly speaking this is an internal number and I'd never make it -- visible... but the HMAC standard requires knowledge of it for each -- hash function, so I'm exporting it. type Bit_Index is new Natural range 0 .. Bits_In_Word; -- Exceptions we have: SHA_Not_Initialized : exception; -- Buffer given not initialized. SHA_Second_Initialize : exception; -- Second call to initialize. -- without intervening finalize. SHA_Overflow : exception; -- Not defined for more than 2**64 bits -- (So says the standard.) -- I realize that some folk want to just ignore this exception. While not -- strictly allowed by the standard, the standard doesn't give a way to -- get around the restriction. *** SO *** this exception is carefully -- NOT raised UNTIL the full processing of the input is done. So it is -- perfectly safe to catch and ignore this exception. ---------------------------------------------------------------------------- -- Most folk just want to Digest a string, so we will have this entry -- Point to keep it simple. function Digest_A_String (Given : String) return Digest; --------------------------------------------------------------------------- -- For those that want more control, we provide actual entry points. -- Start out the buffer. procedure Initialize; procedure Initialize (Given : in out Context); -- Procedures to add to the data being hashed. The standard really -- does define the hash in terms of bits. So, in opposition to -- common practice, I'm providing routines -- that can process -- Bytes or Non_Bytes. -- I let you freely intermix the sizes, even if it means partial -- word alignment in the actual buffer. procedure Add (Data : Bit); procedure Add (Data : Bit; Given : in out Context); procedure Add (Data : Byte); procedure Add (Data : Byte; Given : in out Context); procedure Add (Data : Word); procedure Add (Data : Word; Given : in out Context); procedure Add (Data : Long); procedure Add (Data : Long; Given : in out Context); -- Add arbitrary sized data. procedure Add (Data : Long; Size : Bit_Index); procedure Add (Data : Long; Size : Bit_Index; Given : in out Context); -- Get the final digest. function Finalize return Digest; procedure Finalize (Result : out Digest); procedure Finalize (Result : out Digest; Given : in out Context); ------------------------------------------------------------------------------ private -- I couldn't think of any advantage to letting people see the details of -- these structures. And some advantage to being able to change the count -- into an Unsigned_64 on machines that support it. Initial_Context : constant Digest := -- Directly from the standard. (16#67452301#, 16#EFCDAB89#, 16#98BADCFE#, 16#10325476#, 16#C3D2E1F0#); Words_In_Buffer : constant := 16; type Word_Range is new Natural range 0 .. Words_In_Buffer - 1; type Data_Buffer is array (Word_Range) of Unsigned_32; type Context is record Data : Data_Buffer := (others => 0); Count_High : Unsigned_32 := 0; Count_Low : Unsigned_32 := 0; Remaining_Bits : Bit_Index := 32; Next_Word : Word_Range := 0; Current : Digest := Initial_Context; Initialized : Boolean := False; end record; Initial_Value : constant Context := ((others => 0), 0, 0, 32, 0, Initial_Context, False); end SHA.Process_Data;
-- Copyright (C) 2019 Thierry Rascle <thierr26@free.fr> -- MIT license. Please refer to the LICENSE file. with Ada.Characters.Handling; use Ada.Characters.Handling; package Apsepp.Characters is subtype ISO_646_Upper_Letter is ISO_646 range 'A' .. 'Z'; end Apsepp.Characters;
with Ada.Strings.Hash; function Ada.Strings.Bounded.Hash (Key : Bounded.Bounded_String) return Containers.Hash_Type is begin return Strings.Hash (Key.Element (1 .. Key.Length)); end Ada.Strings.Bounded.Hash;
-- -- mykernel/ada/bootboot.ads -- -- Copyright (C) 2017 - 2021 bzt (bztsrc@gitlab) -- -- 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. -- -- This file is part of the BOOTBOOT Protocol package. -- @brief A sample BOOTBOOT compatible kernel -- -- with System; package bootboot is type UInt8 is mod (2 ** 8); type UInt16 is mod (2 ** 16); type UInt32 is mod (2 ** 32); type UInt64 is mod (2 ** 64); type magic_type is array(0 .. 3) of UInt8; type timezone_type is range -1440 .. +1440; type datetime_type is array(0 .. 7) of UInt8; type Screen is array(0 .. Integer'Last) of Uint32; BOOTBOOT_MMIO : constant := 16#ffffffff_f8000000#; -- memory mapped IO virtual address BOOTBOOT_FB : constant := 16#ffffffff_fc000000#; -- frame buffer virtual address BOOTBOOT_INFO : constant := 16#ffffffff_ffe00000#; -- bootboot struct virtual address BOOTBOOT_ENV : constant := 16#ffffffff_ffe01000#; -- environment string virtual address BOOTBOOT_CORE : constant := 16#ffffffff_ffe02000#; -- core loadable segment start -- minimum protocol level: -- hardcoded kernel name, static kernel memory addresses PROTOCOL_MINIMAL : constant := 0; -- static protocol level: -- kernel name parsed from environment, static kernel memory addresses PROTOCOL_STATIC : constant := 1; -- dynamic protocol level: -- kernel name parsed, kernel memory addresses from ELF or PE symbols PROTOCOL_DYNAMIC : constant := 2; -- big-endian flag PROTOCOL_BIGENDIAN : constant := 128; -- loader types, just informational LOADER_BIOS : constant := 0; LOADER_UEFI : constant := 2; LOADER_RPI : constant := 4; LOADER_COREBOOT : constant := 8; -- framebuffer pixel format, only 32 bits supported FB_ARGB : constant := 0; FB_RGBA : constant := 1; FB_ABGR : constant := 2; FB_BGRA : constant := 3; MMAP_USED : constant := 0; -- don't use. Reserved or unknown regions MMAP_FREE : constant := 1; -- usable memory MMAP_ACPI : constant := 2; -- acpi memory, volatile and non-volatile as well MMAP_MMIO : constant := 3; -- memory mapped IO region INITRD_MAXSIZE : constant := 16; -- Mb fb : Screen; for fb'Address use System'To_Address(BOOTBOOT_FB); pragma Volatile (fb); type bootboot_struct is record -- first 64 bytes is platform independent magic : magic_type; -- 'BOOT' magic size : UInt32; -- length of bootboot structure, minimum 128 protocol : UInt8; -- 1, static addresses, see PROTOCOL_* and LOADER_* above fb_type : UInt8; -- framebuffer type, see FB_* above numcores : UInt16; -- number of processor cores bspid : UInt16; -- Bootsrap processor ID (Local APIC Id on x86_64) timezone : timezone_type; -- in minutes -1440..1440 datetime : datetime_type; -- in BCD yyyymmddhhiiss UTC (independent to timezone) initrd_ptr : UInt64; -- ramdisk image position and size initrd_size : UInt64; fb_ptr : UInt64; -- framebuffer pointer and dimensions fb_size : UInt32; fb_width : UInt32; fb_height : UInt32; fb_scanline : UInt32; -- the rest (64 bytes) is platform specific x86_64_acpi_ptr : UInt64; x86_64_smbi_ptr : UInt64; x86_64_efi_ptr : UInt64; x86_64_mp_ptr : UInt64; x86_64_unused0 : UInt64; x86_64_unused1 : UInt64; x86_64_unused2 : UInt64; x86_64_unused3 : UInt64; end record; bootboot : bootboot_struct; for bootboot'Address use System'To_Address(BOOTBOOT_INFO); pragma Volatile (bootboot); -- mmap entry, type is stored in least significant tetrad (half byte) of size -- this means size described in 16 byte units (not a problem, most modern -- firmware report memory in pages, 4096 byte units anyway). type MMapEnt_type is record ptr : UInt64; size : UInt64; end record; MMap : MMapEnt_type; for MMap'Address use System'To_Address(BOOTBOOT_INFO + 128); pragma Volatile (MMap); end bootboot;
Чайковский Чайковский2
------------------------------------------------------------------------------- -- Copyright 2021, The Septum Developers (see AUTHORS file) -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- http://www.apache.org/licenses/LICENSE-2.0 -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ------------------------------------------------------------------------------- with Ada.Containers.Vectors; with Ada.Strings.Unbounded; with GNAT.Regpat; with SP.Contexts; with SP.Memory; with SP.Strings; package SP.Filters with Preelaborate is use SP.Strings; -- Filters need to do different things. Some filters match line contents, whereas others want to remove any match -- which has a match anywhere in the content. When a filter matches, some action with regards to the search should -- be done, whether to include or to exclude the match from the results. type Filter_Action is (Keep, Exclude); -- Search filters define which lines match and what to do about a match. type Filter (Action : Filter_Action) is abstract tagged null record; -- Describes the filter in an end-user type of way. TODO: This should be localized. function Image (F : Filter) return String is abstract; -- Determine if a filter matches a string. function Matches_Line (F : Filter; Str : String) return Boolean is abstract; type Filter_Access is access Filter'Class; package Pointers is new SP.Memory (T => Filter'Class, T_Access => Filter_Access); subtype Filter_Ptr is Pointers.Arc; -- Provides a means to store many types of filters in the same list. package Filter_List is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Filter_Ptr, "=" => Pointers."="); function Find_Text (Text : String) return Filter_Ptr; function Exclude_Text (Text : String) return Filter_Ptr; function Find_Like (Text : String) return Filter_Ptr; function Exclude_Like (Text : String) return Filter_Ptr; function Find_Regex (Text : String) return Filter_Ptr; function Exclude_Regex (Text : String) return Filter_Ptr; function Is_Valid_Regex (S : String) return Boolean; -- Looks for a match in any of the given lines. function Matches_File (F : Filter'Class; Lines : String_Vectors.Vector) return Boolean; function Matching_Lines (F : Filter'Class; Lines : String_Vectors.Vector) return SP.Contexts.Line_Matches.Set; private type Regex_Access is access GNAT.Regpat.Pattern_Matcher; package Rc_Regex is new SP.Memory (T => GNAT.Regpat.Pattern_Matcher, T_Access => Regex_Access); type Case_Sensitive_Match_Filter is new Filter with record Text : Ada.Strings.Unbounded.Unbounded_String; end record; type Case_Insensitive_Match_Filter is new Filter with record Text : Ada.Strings.Unbounded.Unbounded_String; end record; type Regex_Filter is new Filter with record Source : Ada.Strings.Unbounded.Unbounded_String; Regex : Rc_Regex.Arc; end record; overriding function Image (F : Case_Sensitive_Match_Filter) return String; overriding function Matches_Line (F : Case_Sensitive_Match_Filter; Str : String) return Boolean; overriding function Image (F : Case_Insensitive_Match_Filter) return String; overriding function Matches_Line (F : Case_Insensitive_Match_Filter; Str : String) return Boolean; overriding function Image (F : Regex_Filter) return String; overriding function Matches_Line (F : Regex_Filter; Str : String) return Boolean; end SP.Filters;
with Ada.Text_IO; with Ada.Strings.Fixed; with AWS.Config.Set; with AWS.Server; with HTTPd.Callbacks; procedure HTTPd.Main is Web_Server : AWS.Server.HTTP; Web_Config : AWS.Config.Object; begin -- Show header Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line(" HH HH TTTTTTT TTTTTTT PPPPPP dd "); Ada.Text_IO.Put_Line(" HH HH TTT TTT P PP dd "); Ada.Text_IO.Put_Line(" HHHHHHH TTT TTT PPPPPP dddddd "); Ada.Text_IO.Put_Line(" HH HH TTT TTT PP dd dd "); Ada.Text_IO.Put_Line(" HH HH TTT TTT PP dddddd "); Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line("Simple static Web Server made in Ada 2012"); Ada.Text_IO.Put_Line(">> v1.0 [25/April/2020]"); Ada.Text_IO.Put_Line(">> Made by: A.D. van der Heijde"); Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line("Stop server by pressing Q"); Ada.Text_IO.New_Line; -- Setup AWS.Config.Set.Server_Host (Web_Config, Host); AWS.Config.Set.Server_Port (Web_Config, Port); -- Start the server AWS.Server.Start (Web_Server, Callbacks.Default'Access, Web_Config); -- Connection to web server Ada.Text_IO.Put_Line("Connect to http://" & Host & ":" & Ada.Strings.Fixed.Trim(Port'Img, Ada.Strings.Left) & "/"); -- Wait for the Q key to exit AWS.Server.Wait (AWS.Server.Q_Key_Pressed); -- Stop the server AWS.Server.Shutdown (Web_Server); end HTTPd.Main;
with STM32_SVD; use STM32_SVD; with System; use System; package body STM32GD.GPIO.Port is function GPIO_Port_Representation (Port : STM32_SVD.GPIO.GPIO_Peripheral) return UInt4 is begin if Port'Address = GPIOA_Base then return 0; elsif Port'Address = GPIOB_Base then return 1; elsif Port'Address = GPIOC_Base then return 2; elsif Port'Address = GPIOD_Base then return 3; elsif Port'Address = GPIOE_Base then return 4; elsif Port'Address = GPIOH_Base then return 7; else raise Program_Error; end if; end GPIO_Port_Representation; end STM32GD.GPIO.Port;
----------------------------------------------------------------------- -- 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.IO_Exceptions; package body Util.Streams.Sockets is -- ----------------------- -- Initialize the socket stream. -- ----------------------- procedure Open (Stream : in out Socket_Stream; Socket : in GNAT.Sockets.Socket_Type) is use type GNAT.Sockets.Socket_Type; begin if Stream.Sock /= GNAT.Sockets.No_Socket then raise Ada.IO_Exceptions.Use_Error with "Socket stream is already opened"; end if; Stream.Sock := Socket; end Open; -- ----------------------- -- 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) is use type GNAT.Sockets.Socket_Type; begin if Stream.Sock /= GNAT.Sockets.No_Socket then raise Ada.IO_Exceptions.Use_Error with "Socket stream is already opened"; end if; GNAT.Sockets.Create_Socket (Socket => Stream.Sock, Family => Server.Family); GNAT.Sockets.Connect_Socket (Socket => Stream.Sock, Server => Server); end Connect; -- ----------------------- -- Close the socket stream. -- ----------------------- overriding procedure Close (Stream : in out Socket_Stream) is begin GNAT.Sockets.Close_Socket (Stream.Sock); Stream.Sock := GNAT.Sockets.No_Socket; end Close; -- ----------------------- -- Write the buffer array to the output stream. -- ----------------------- overriding procedure Write (Stream : in out Socket_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is Last : Ada.Streams.Stream_Element_Offset; pragma Unreferenced (Last); begin GNAT.Sockets.Send_Socket (Stream.Sock, Buffer, Last); end Write; -- ----------------------- -- 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) is begin GNAT.Sockets.Receive_Socket (Stream.Sock, Into, Last); end Read; -- ----------------------- -- Flush the stream and release the buffer. -- ----------------------- overriding procedure Finalize (Object : in out Socket_Stream) is use type GNAT.Sockets.Socket_Type; begin if Object.Sock /= GNAT.Sockets.No_Socket then Object.Close; end if; end Finalize; end Util.Streams.Sockets;
-- { dg-do compile } -- { dg-options "-O2" } with Text_IO; use Text_IO; with System.Storage_Elements; use System.Storage_Elements; with Warn12_Pkg; use Warn12_Pkg; procedure Warn12 (N : Natural) is Buffer_Size : constant Storage_Offset := Token_Groups'Size/System.Storage_Unit + 4096; Buffer : Storage_Array (1 .. Buffer_Size); for Buffer'Alignment use 8; Tg1 : Token_Groups; for Tg1'Address use Buffer'Address; Tg2 : Token_Groups; pragma Warnings (Off, Tg2); sid : Sid_And_Attributes; pragma Suppress (Index_Check, Sid_And_Attributes_Array); begin for I in 0 .. 7 loop sid := Tg1.Groups(I); -- { dg-bogus "out-of-bounds access" } Put_Line("Iteration"); end loop; for I in 0 .. N loop sid := Tg1.Groups(I); -- { dg-bogus "out-of-bounds access" } Put_Line("Iteration"); end loop; for I in 0 .. 7 loop sid := Tg2.Groups(I); -- { dg-warning "out-of-bounds access" } Put_Line("Iteration"); end loop; for I in 0 .. N loop sid := Tg2.Groups(I); -- { dg-warning "out-of-bounds access" } Put_Line("Iteration"); end loop; end;
package Inheritance is type Animal is tagged private; type Dog is new Animal with private; type Cat is new Animal with private; type Lab is new Dog with private; type Collie is new Dog with private; private type Animal is tagged null record; type Dog is new Animal with null record; type Cat is new Animal with null record; type Lab is new Dog with null record; type Collie is new Dog with null record; end Inheritance;
-- convert UCD/UnicodeData.txt (13, 14) -- bin/ucd_simplecasemapping $UCD/UnicodeData.txt > ../source/strings/a-uscama.ads with Ada.Command_Line; use Ada.Command_Line; with Ada.Containers.Ordered_Maps; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Ada.Text_IO; use Ada.Text_IO; procedure ucd_simplecasemapping is function Value (S : String) return Wide_Wide_Character is Img : constant String := "Hex_" & (1 .. 8 - S'Length => '0') & S; begin return Wide_Wide_Character'Value (Img); end Value; procedure Put_16 (Item : Integer) is S : String (1 .. 8); -- "16#XXXX#" begin Put (S, Item, Base => 16); S (1) := '1'; S (2) := '6'; S (3) := '#'; for I in reverse 4 .. 6 loop if S (I) = '#' then S (4 .. I) := (others => '0'); exit; end if; end loop; Put (S); end Put_16; package WWC_Maps is new Ada.Containers.Ordered_Maps ( Wide_Wide_Character, Wide_Wide_Character); use WWC_Maps; function Compressible (I : WWC_Maps.Cursor) return Boolean is begin return Wide_Wide_Character'Pos (Element (I)) - Wide_Wide_Character'Pos (Key (I)) in -128 .. 127; end Compressible; Upper_Table, Lower_Table, Shared_Table : WWC_Maps.Map; Upper_Num, Lower_Num : Natural; type Bit is (In_16, In_32); function Get_Bit (C : Wide_Wide_Character) return Bit is begin if C > Wide_Wide_Character'Val (16#FFFF#) then return In_32; else return In_16; end if; end Get_Bit; Shared_Num : array (Bit, Boolean) of Natural; begin declare File : Ada.Text_IO.File_Type; begin Open (File, In_File, Argument (1)); while not End_Of_File (File) loop declare Line : constant String := Get_Line (File); type Range_Type is record First : Positive; Last : Natural; end record; Fields : array (1 .. 14) of Range_Type; P : Positive := Line'First; N : Natural; Code : Wide_Wide_Character; begin for I in Fields'Range loop N := P; while N <= Line'Last and then Line (N) /= ';' loop N := N + 1; end loop; if (N <= Line'Last) /= (I < Field'Last) then raise Data_Error with Line & " -- A"; end if; Fields (I).First := P; Fields (I).Last := N - 1; P := N + 1; -- skip ';' end loop; Code := Value (Line (Fields (1).First .. Fields (1).Last)); if Fields (13).First <= Fields (13).Last then -- uppercase Insert ( Upper_Table, Code, Value (Line (Fields (13).First .. Fields (13).Last))); end if; if Fields (14).First <= Fields (14).Last then -- lowercase Insert ( Lower_Table, Code, Value (Line (Fields (14).First .. Fields (14).Last))); end if; -- note: last field (15) is titlecase. end; end loop; Close (File); end; Upper_Num := Natural (Length (Upper_Table)); Lower_Num := Natural (Length (Lower_Table)); declare I : WWC_Maps.Cursor := First (Lower_Table); begin while Has_Element (I) loop if Contains (Upper_Table, Element (I)) and then Element (Upper_Table, Element (I)) = Key (I) then Insert (Shared_Table, Key (I), Element (I)); end if; I := Next (I); end loop; end; for B in Bit loop for Compressed in Boolean loop Shared_Num (B, Compressed) := 0; end loop; end loop; declare I : WWC_Maps.Cursor := First (Shared_Table); begin while Has_Element (I) loop declare B : Bit := Get_Bit (Key (I)); begin if Compressible (I) then declare K : Wide_Wide_Character := Key (I); E : Wide_Wide_Character := Element (I); N : WWC_Maps.Cursor := Next (I); RLE : Positive := 1; Compressed : Boolean; begin while Has_Element (N) and then RLE < 255 and then Compressible (N) and then Key (N) = Wide_Wide_Character'Succ (K) and then Element (N) = Wide_Wide_Character'Succ (E) loop K := Key (N); E := Element (N); N := Next (N); RLE := RLE + 1; end loop; I := N; Compressed := RLE > 1; Shared_Num (B, Compressed) := Shared_Num (B, Compressed) + 1; end; else Shared_Num (B, False) := Shared_Num (B, False) + 1; I := Next (I); end if; end; end loop; end; Put_Line ("pragma License (Unrestricted);"); Put_Line ("-- implementation unit, translated from UnicodeData.txt (13, 14)"); Put_Line ("package Ada.UCD.Simple_Case_Mapping is"); Put_Line (" pragma Pure;"); New_Line; Put (" L_Total : constant := "); Put (Lower_Num, Width => 1); Put (";"); New_Line; Put (" U_Total : constant := "); Put (Upper_Num, Width => 1); Put (";"); New_Line; New_Line; Put_Line (" type Run_Length_8 is mod 2 ** 8;"); New_Line; Put_Line (" type Compressed_Item_Type is record"); Put_Line (" Start : UCS_2;"); Put_Line (" Length : Run_Length_8;"); Put_Line (" Diff : Difference_8;"); Put_Line (" end record;"); Put_Line (" pragma Suppress_Initialization (Compressed_Item_Type);"); Put_Line (" for Compressed_Item_Type'Size use 32; -- 16 + 8 + 8"); Put_Line (" for Compressed_Item_Type use record"); Put_Line (" Start at 0 range 0 .. 15;"); Put_Line (" Length at 0 range 16 .. 23;"); Put_Line (" Diff at 0 range 24 .. 31;"); Put_Line (" end record;"); New_Line; Put_Line (" type Compressed_Type is array (Positive range <>) of Compressed_Item_Type;"); Put_Line (" pragma Suppress_Initialization (Compressed_Type);"); Put_Line (" for Compressed_Type'Component_Size use 32;"); New_Line; Put (" subtype SL_Table_XXXX_Type is Map_16x1_Type (1 .. "); Put (Shared_Num (In_16, False), Width => 1); Put (");"); New_Line; Put (" subtype SL_Table_XXXX_Compressed_Type is Compressed_Type (1 .. "); Put (Shared_Num (In_16, True), Width => 1); Put (");"); New_Line; Put (" subtype SL_Table_1XXXX_Compressed_Type is Compressed_Type (1 .. "); Put (Shared_Num (In_32, True), Width => 1); Put (");"); New_Line; if Shared_Num (In_32, False) /= 0 then raise Data_Error with "num of shared"; end if; Put (" subtype DL_Table_XXXX_Type is Map_16x1_Type (1 .. "); Put (Lower_Num - Natural (Length (Shared_Table)), Width => 1); Put (");"); New_Line; Put (" subtype DU_Table_XXXX_Type is Map_16x1_Type (1 .. "); Put (Upper_Num - Natural (Length (Shared_Table)), Width => 1); Put (");"); New_Line; New_Line; for B in Bit loop for Compressed in Boolean loop if Shared_Num (B, Compressed) > 0 then Put (" SL_Table_"); if B = In_32 then Put ("1"); end if; Put ("XXXX"); if Compressed then Put ("_Compressed"); end if; Put (" : constant SL_Table_"); if B = In_32 then Put ("1"); end if; Put ("XXXX"); if Compressed then Put ("_Compressed"); end if; Put ("_Type := ("); New_Line; declare Offset : Integer := 0; I : WWC_Maps.Cursor := First (Shared_Table); Second : Boolean := False; begin if B = In_32 then Offset := 16#10000#; end if; while Has_Element (I) loop declare Item_B : Bit := Get_Bit (Key (I)); Item_RLE : Positive := 1; N : WWC_Maps.Cursor := Next (I); begin if Compressible (I) then declare K : Wide_Wide_Character := Key (I); E : Wide_Wide_Character := Element (I); begin while Has_Element (N) and then Item_RLE < 255 and then Compressible (N) and then Key (N) = Wide_Wide_Character'Succ (K) and then Element (N) = Wide_Wide_Character'Succ (E) loop K := Key (N); E := Element (N); N := Next (N); Item_RLE := Item_RLE + 1; end loop; end; end if; if Item_B = B and then (Item_RLE > 1) = Compressed then if Second then Put (","); New_Line; end if; Put (" "); if Shared_Num (B, Compressed) = 1 then Put ("1 => "); end if; Put ("("); Put_16 (Wide_Wide_Character'Pos (Key (I)) - Offset); Put (", "); if Compressed then Put (Item_RLE, Width => 1); Put (", "); Put ( Wide_Wide_Character'Pos (Element (I)) - Wide_Wide_Character'Pos (Key (I)), Width => 1); else Put_16 ( Wide_Wide_Character'Pos (Element (I)) - Offset); end if; Put (")"); Second := True; end if; I := N; end; end loop; Put (");"); New_Line; end; New_Line; end if; end loop; end loop; Put_Line (" DL_Table_XXXX : constant DL_Table_XXXX_Type := ("); declare I : WWC_Maps.Cursor := First (Lower_Table); Second : Boolean := False; begin while Has_Element (I) loop if not ( Contains (Shared_Table, Key (I)) and then Element (Shared_Table, Key (I)) = Element (I)) then if Second then Put (","); New_Line; end if; Put (" ("); Put_16 (Wide_Wide_Character'Pos (Key (I))); Put (", "); Put_16 (Wide_Wide_Character'Pos (Element (I))); Put (")"); Second := True; end if; I := Next (I); end loop; Put (");"); New_Line; end; New_Line; Put_Line (" DU_Table_XXXX : constant DU_Table_XXXX_Type := ("); declare I : WWC_Maps.Cursor := First (Upper_Table); Second : Boolean := False; begin while Has_Element (I) loop if not ( Contains (Shared_Table, Element (I)) and then Element (Shared_Table, Element (I)) = Key (I)) then if Second then Put (","); New_Line; end if; Put (" ("); Put_16 (Wide_Wide_Character'Pos (Key (I))); Put (", "); Put_16 (Wide_Wide_Character'Pos (Element (I))); Put (")"); Second := True; end if; I := Next (I); end loop; Put (");"); New_Line; end; New_Line; Put_Line ("end Ada.UCD.Simple_Case_Mapping;"); end ucd_simplecasemapping;
-- { dg-do compile } -- { dg-options "-gnat12 -gnato" } package Cond_Expr1 is function Tail (S : String) return String is (if S'Last <= S'First then "" else S (S'First + 1 .. S'Last)); end Cond_Expr1;
with AdaBase; with Connect; with CommonText; with Ada.Text_IO; with AdaBase.Results.Sets; procedure Bad_Select is package CON renames Connect; package TIO renames Ada.Text_IO; package ARS renames AdaBase.Results.Sets; package CT renames CommonText; row : ARS.Datarow; sql : String := "SELECT fruit, calories FROM froits " & "WHERE color = 'red'"; success : Boolean := True; begin -- PostgreSQL will abort a transaction even for a bad select -- so in this case, let's not start any transactions CON.DR.set_trait_autocommit (True); CON.connect_database; declare stmt : CON.Stmt_Type := CON.DR.query (sql); begin TIO.Put_Line ("Query successful: " & stmt.successful'Img); if not stmt.successful then TIO.Put_Line (" Driver message: " & stmt.last_driver_message); TIO.Put_Line (" Driver code: " & stmt.last_driver_code'Img); TIO.Put_Line (" SQL State: " & stmt.last_sql_state); success := False; end if; end; if not success then -- Fix SQL typo sql (31) := 'u'; TIO.Put_Line (""); TIO.Put_Line ("SQL now: " & sql); declare stmt : CON.Stmt_Type := CON.DR.query (sql); begin TIO.Put_Line ("Query successful: " & stmt.successful'Img); row := stmt.fetch_next; if not row.data_exhausted then TIO.Put_Line (" Number fields:" & row.count'Img); stmt.discard_rest; TIO.Put_Line (" Data discarded: " & stmt.data_discarded'Img); end if; end; end if; CON.DR.disconnect; end Bad_Select;
-- { dg-do compile } -- { dg-options "-O2 -gnatpn" } with Ada.Characters.Handling; use Ada.Characters.Handling; package body Opt20 is type Build_Mode_State is (None, Static, Dynamic, Relocatable); procedure Build_Library (For_Project : Integer) is Project_Name : constant String := Get_Name_String (For_Project); The_Build_Mode : Build_Mode_State := None; begin Fail (Project_Name); Write_Str (To_Lower (Build_Mode_State'Image (The_Build_Mode))); end; end Opt20;
with AWS.Client, AWS.Response, AWS.Resources, AWS.Messages; with Ada.Text_IO, Ada.Strings.Fixed; use Ada, AWS, AWS.Resources, AWS.Messages; procedure Get_UTC_Time is Page : Response.Data; File : Resources.File_Type; Buffer : String (1 .. 1024); Position, Last : Natural := 0; S : Messages.Status_Code; begin Page := Client.Get ("http://tycho.usno.navy.mil/cgi-bin/timer.pl"); S := Response.Status_Code (Page); if S not in Success then Text_IO.Put_Line ("Unable to retrieve data => Status Code :" & Image (S) & " Reason :" & Reason_Phrase (S)); return; end if; Response.Message_Body (Page, File); while not End_Of_File (File) loop Resources.Get_Line (File, Buffer, Last); Position := Strings.Fixed.Index (Source => Buffer (Buffer'First .. Last), Pattern => "UTC"); if Position > 0 then Text_IO.Put_Line (Buffer (5 .. Position + 2)); return; end if; end loop; end Get_UTC_Time;
with Ada.Text_IO; procedure Goodbye_World is begin Ada.Text_IO.Put("Goodbye, World!"); end Goodbye_World;
----------------------------------------------------------------------- -- druss-commands-get -- Raw JSON API Get command -- Copyright (C) 2017, 2018, 2019, 2021 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Strings.Unbounded; with Ada.Containers; with Bbox.API; with Druss.Gateways; package body Druss.Commands.Get is use type Ada.Containers.Count_Type; use Ada.Text_IO; use Ada.Strings.Unbounded; -- ------------------------------ -- Execute a GET operation on the Bbox API and return the raw JSON result. -- ------------------------------ overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Command, Name); procedure Execute_One (Gateway : in out Druss.Gateways.Gateway_Type); Need_Colon : Boolean := False; -- Execute the GET API operation and print the raw JSON result. procedure Execute_One (Gateway : in out Druss.Gateways.Gateway_Type) is Box : Bbox.API.Client_Type; begin Box.Set_Server (To_String (Gateway.Ip)); if Ada.Strings.Unbounded.Length (Gateway.Passwd) > 0 then Box.Login (To_String (Gateway.Passwd)); end if; for I in 1 .. Args.Get_Count loop declare Operation : constant String := Args.Get_Argument (I); Content : constant String := Box.Get (Operation); Last : Natural := Content'Last; begin if Need_Colon then Ada.Text_IO.Put (","); end if; while Last > Content'First and Content (Last) = ASCII.LF loop Last := Last - 1; end loop; -- We did a mistake when we designed the Bbox API and used '[' ... ']' arrays -- for most of the JSON result. Strip that unecessary array. if Content (Content'First) = '[' and Content (Last) = ']' then Ada.Text_IO.Put_Line (Content (Content'First + 1 .. Last - 1)); else Ada.Text_IO.Put_Line (Box.Get (Operation)); end if; Need_Colon := True; end; end loop; end Execute_One; begin if Args.Get_Count = 0 then Druss.Commands.Driver.Usage (Args, Context); else if Args.Get_Count > 1 or else Context.Gateways.Length > 1 then Ada.Text_IO.Put_Line ("["); end if; Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Execute_One'Access); if Args.Get_Count > 1 or else Context.Gateways.Length > 1 then Ada.Text_IO.Put_Line ("]"); end if; end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in out Command_Type; Name : in String; Context : in out Context_Type) is pragma Unreferenced (Command); Console : constant Druss.Commands.Consoles.Console_Access := Context.Console; begin Console.Notice (N_HELP, "get: Execute one or several GET operation on the Bbox API" & " and print the raw JSON result"); Console.Notice (N_HELP, "Usage: get <operation>..."); Console.Notice (N_HELP, ""); Console.Notice (N_HELP, " The Bbox API operation are called and the raw JSON result is printed."); Console.Notice (N_HELP, " When several operations are called, a JSON array is formed to insert"); Console.Notice (N_HELP, " their result in the final JSON content so that it is valid."); Console.Notice (N_HELP, " Examples:"); Console.Notice (N_HELP, " get device Get information about the Bbox"); Console.Notice (N_HELP, " get hosts Get the list of hosts detected by the Bbox"); Console.Notice (N_HELP, " get wan/ip Get information about the WAN connection"); Console.Notice (N_HELP, " get wan/ip wan/xdsl Get the WAN and xDSL line information"); end Help; end Druss.Commands.Get;
-- { dg-do compile } -- { dg-options "-O -gnatp" } with Loop_Optimization5_Pkg; use Loop_Optimization5_Pkg; procedure Loop_Optimization5 is Str : constant String := "12345678"; Cmd : constant String := Init; StartP : Positive := Cmd'First; StartS : Positive := Cmd'Last + 1; EndP : Natural := StartP - 1; Full_Cmd : String_Access; begin for J in StartP .. Cmd'Last - Str'Length + 1 loop if Cmd (J .. J + Str'Length - 1) = Str then EndP := J - 1; exit; end if; end loop; Full_Cmd := Locate (Cmd (StartP .. EndP)); end;
with Ada.Text_IO; with Generic_Shuffle; procedure Test_Shuffle is type Integer_Array is array (Positive range <>) of Integer; Integer_List : Integer_Array := (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18); procedure Integer_Shuffle is new Generic_Shuffle(Element_Type => Integer, Array_Type => Integer_Array); begin for I in Integer_List'Range loop Ada.Text_IO.Put(Integer'Image(Integer_List(I))); end loop; Integer_Shuffle(List => Integer_List); Ada.Text_IO.New_Line; for I in Integer_List'Range loop Ada.Text_IO.Put(Integer'Image(Integer_List(I))); end loop; end Test_Shuffle;
with Text_IO; use Text_IO; procedure hello_world is begin Put_Line("Hello World."); end hello_world;
package body ROSA.Tasks is procedure Create (Task_ID, Priority : in Unsigned_8; t : out Tasking) is begin t.Task_ID := Task_ID; t.Priority := Priority; t.State := Waiting; end Create; function Run (t : in Tasking) return Task_Status is begin if t.State /= Ready then return Not_Ready; end if; -- Fill this in later. return OK; end Run; function Suspend (t : in Tasking) return Task_Status is begin if t.State /= Running then return Not_Running; end if; -- Fill this in later. return OK; end Suspend; end ROSA.Tasks;
pragma Ada_2012; with Tokenize.Token_Vectors; with Ada.Strings.Fixed; package body EU_Projects.Efforts is ----------- -- Parse -- ----------- function Parse (Spec : String) return Effort_Maps.Map is use Tokenize; use Tokenize.Token_Vectors; use EU_Projects.Nodes.Partners; use Ada.Strings.Fixed; use Ada.Strings; Result : Effort_Maps.Map := Effort_Maps.Empty_Map; begin if Spec = "" then return Effort_Maps.Empty_Map; end if; for Partner_Spec of To_Vector (Split (Spec, ',', False)) loop declare use type Ada.Containers.Count_Type; Parts : constant Token_Vectors.Vector := Token_Vectors.To_Vector (Split (Partner_Spec, "=:", False)); Name : Partner_Label; begin if Parts.Length /= 2 then raise Bad_Effort_List with "Bad partner effort spec"; end if; Name := Partner_Label'(To_ID (Trim (Parts.First_Element, Both))); if Result.Contains (Name) then raise Bad_Effort_List with "Duplicated partner in effort list"; end if; Result.Include (Key => Name, New_Item => Person_Months (Natural'Value (Parts.Last_Element))); end; end loop; return Result; end Parse; end EU_Projects.Efforts;
with Ada.Unchecked_Conversion; with System.Address_To_Named_Access_Conversions; with System.Growth; with System.Standard_Allocators; with System.Storage_Elements; with System.System_Allocators.Allocated_Size; package body Ada.Strings.Generic_Unbounded is use type Streams.Stream_Element_Offset; use type System.Address; use type System.Storage_Elements.Storage_Offset; package FSA_Conv is new System.Address_To_Named_Access_Conversions ( Fixed_String, Fixed_String_Access); package DA_Conv is new System.Address_To_Named_Access_Conversions (Data, Data_Access); subtype Nonnull_Data_Access is not null Data_Access; function Upcast is new Unchecked_Conversion ( Nonnull_Data_Access, System.Reference_Counting.Container); function Downcast is new Unchecked_Conversion ( System.Reference_Counting.Container, Nonnull_Data_Access); type Data_Access_Access is access all Nonnull_Data_Access; type Container_Access is access all System.Reference_Counting.Container; function Upcast is new Unchecked_Conversion (Data_Access_Access, Container_Access); function Allocation_Size ( Capacity : System.Reference_Counting.Length_Type) return System.Storage_Elements.Storage_Count; function Allocation_Size ( Capacity : System.Reference_Counting.Length_Type) return System.Storage_Elements.Storage_Count is Header_Size : constant System.Storage_Elements.Storage_Count := Data'Size / Standard'Storage_Unit; Item_Size : System.Storage_Elements.Storage_Count; begin if String_Type'Component_Size rem Standard'Storage_Unit = 0 then -- optimized for packed Item_Size := Capacity * (String_Type'Component_Size / Standard'Storage_Unit); else -- unpacked Item_Size := (Capacity * String_Type'Component_Size + (Standard'Storage_Unit - 1)) / Standard'Storage_Unit; end if; return Header_Size + Item_Size; end Allocation_Size; procedure Adjust_Allocated (Data : not null Data_Access); procedure Adjust_Allocated (Data : not null Data_Access) is Header_Size : constant System.Storage_Elements.Storage_Count := Generic_Unbounded.Data'Size / Standard'Storage_Unit; M : constant System.Address := DA_Conv.To_Address (Data); Usable_Size : constant System.Storage_Elements.Storage_Count := System.System_Allocators.Allocated_Size (M) - Header_Size; begin if String_Type'Component_Size rem Standard'Storage_Unit = 0 then -- optimized for packed Data.Capacity := Integer ( Usable_Size / (String_Type'Component_Size / Standard'Storage_Unit)); else -- unpacked Data.Capacity := Integer ( Usable_Size * Standard'Storage_Unit / String_Type'Component_Size); end if; Data.Items := FSA_Conv.To_Pointer (M + Header_Size); end Adjust_Allocated; function Allocate_Data ( Max_Length : System.Reference_Counting.Length_Type; Capacity : System.Reference_Counting.Length_Type) return not null Data_Access; function Allocate_Data ( Max_Length : System.Reference_Counting.Length_Type; Capacity : System.Reference_Counting.Length_Type) return not null Data_Access is M : constant System.Address := System.Standard_Allocators.Allocate (Allocation_Size (Capacity)); Result : constant not null Data_Access := DA_Conv.To_Pointer (M); begin Result.Reference_Count := 1; Result.Max_Length := Max_Length; Adjust_Allocated (Result); return Result; end Allocate_Data; procedure Free_Data (Data : in out System.Reference_Counting.Data_Access); procedure Free_Data (Data : in out System.Reference_Counting.Data_Access) is begin System.Standard_Allocators.Free (DA_Conv.To_Address (Downcast (Data))); Data := null; end Free_Data; procedure Reallocate_Data ( Data : aliased in out not null System.Reference_Counting.Data_Access; Length : System.Reference_Counting.Length_Type; Max_Length : System.Reference_Counting.Length_Type; Capacity : System.Reference_Counting.Length_Type); procedure Reallocate_Data ( Data : aliased in out not null System.Reference_Counting.Data_Access; Length : System.Reference_Counting.Length_Type; Max_Length : System.Reference_Counting.Length_Type; Capacity : System.Reference_Counting.Length_Type) is pragma Unreferenced (Length); M : constant System.Address := System.Standard_Allocators.Reallocate ( DA_Conv.To_Address (Downcast (Data)), Allocation_Size (Capacity)); begin Data := Upcast (DA_Conv.To_Pointer (M)); Downcast (Data).Max_Length := Max_Length; Adjust_Allocated (Downcast (Data)); end Reallocate_Data; procedure Copy_Data ( Target : out not null System.Reference_Counting.Data_Access; Source : not null System.Reference_Counting.Data_Access; Length : System.Reference_Counting.Length_Type; Max_Length : System.Reference_Counting.Length_Type; Capacity : System.Reference_Counting.Length_Type); procedure Copy_Data ( Target : out not null System.Reference_Counting.Data_Access; Source : not null System.Reference_Counting.Data_Access; Length : System.Reference_Counting.Length_Type; Max_Length : System.Reference_Counting.Length_Type; Capacity : System.Reference_Counting.Length_Type) is Data : constant not null Data_Access := Allocate_Data (Max_Length, Capacity); subtype R is Integer range 1 .. Integer (Length); begin declare pragma Suppress (Access_Check); begin Data.Items (R) := Downcast (Source).Items (R); end; Target := Upcast (Data); end Copy_Data; procedure Reallocate ( Source : in out Unbounded_String; Length : Natural; Capacity : Natural); procedure Reallocate ( Source : in out Unbounded_String; Length : Natural; Capacity : Natural) is begin System.Reference_Counting.Unique ( Target => Upcast (Source.Data'Unchecked_Access), Target_Length => System.Reference_Counting.Length_Type (Source.Length), Target_Capacity => System.Reference_Counting.Length_Type ( Generic_Unbounded.Capacity (Source)), New_Length => System.Reference_Counting.Length_Type (Length), New_Capacity => System.Reference_Counting.Length_Type (Capacity), Sentinel => Upcast (Empty_Data'Unrestricted_Access), Reallocate => Reallocate_Data'Access, Copy => Copy_Data'Access, Free => Free_Data'Access); end Reallocate; function Create (Data : not null Data_Access; Length : Natural) return Unbounded_String; function Create (Data : not null Data_Access; Length : Natural) return Unbounded_String is begin return (Finalization.Controlled with Data => Data, Length => Length); end Create; -- implementation function Null_Unbounded_String return Unbounded_String is begin return Create (Data => Empty_Data'Unrestricted_Access, Length => 0); end Null_Unbounded_String; function Is_Null (Source : Unbounded_String) return Boolean is begin return Source.Length = 0; end Is_Null; function Length (Source : Unbounded_String) return Natural is begin return Source.Length; end Length; procedure Set_Length (Source : in out Unbounded_String; Length : Natural) is pragma Suppress (Access_Check); -- dereferencing Source.Data Old_Capacity : constant Natural := Capacity (Source); Failure : Boolean; begin System.Reference_Counting.In_Place_Set_Length ( Target_Data => Upcast (Source.Data), Target_Length => System.Reference_Counting.Length_Type (Source.Length), Target_Max_Length => Source.Data.Max_Length, Target_Capacity => System.Reference_Counting.Length_Type (Old_Capacity), New_Length => System.Reference_Counting.Length_Type (Length), Failure => Failure); if Failure then declare function Grow is new System.Growth.Good_Grow ( Natural, Component_Size => String_Type'Component_Size); New_Capacity : Natural; begin if Old_Capacity >= Length then -- Old_Capacity is possibly a large value by Generic_Constant New_Capacity := Length; -- shrinking else New_Capacity := Integer'Max (Grow (Old_Capacity), Length); end if; Reallocate (Source, Length, New_Capacity); end; end if; Source.Length := Length; end Set_Length; function Capacity (Source : Unbounded_String) return Natural is pragma Suppress (Access_Check); begin return Source.Data.Capacity; end Capacity; procedure Reserve_Capacity ( Source : in out Unbounded_String; Capacity : Natural) is New_Capacity : constant Natural := Integer'Max (Capacity, Source.Length); begin Reallocate (Source, Source.Length, New_Capacity); end Reserve_Capacity; function To_Unbounded_String (Source : String_Type) return Unbounded_String is Length : constant Natural := Source'Length; New_Data : constant not null Data_Access := Allocate_Data ( System.Reference_Counting.Length_Type (Length), System.Reference_Counting.Length_Type (Length)); begin declare pragma Suppress (Access_Check); begin New_Data.Items (1 .. Length) := Source; end; return Create (Data => New_Data, Length => Length); end To_Unbounded_String; function To_Unbounded_String (Length : Natural) return Unbounded_String is New_Data : constant not null Data_Access := Allocate_Data ( System.Reference_Counting.Length_Type (Length), System.Reference_Counting.Length_Type (Length)); begin return Create (Data => New_Data, Length => Length); end To_Unbounded_String; function To_String (Source : Unbounded_String) return String_Type is pragma Suppress (Access_Check); begin return Source.Data.Items (1 .. Source.Length); end To_String; procedure Set_Unbounded_String ( Target : out Unbounded_String; Source : String_Type) is pragma Suppress (Access_Check); Length : constant Natural := Source'Length; begin Target.Length := 0; Set_Length (Target, Length); Target.Data.Items (1 .. Length) := Source; end Set_Unbounded_String; procedure Append ( Source : in out Unbounded_String; New_Item : Unbounded_String) is pragma Suppress (Access_Check); New_Item_Length : constant Natural := New_Item.Length; Old_Length : constant Natural := Source.Length; begin if Old_Length = 0 and then Capacity (Source) < New_Item_Length then Assign (Source, New_Item); else declare Total_Length : constant Natural := Old_Length + New_Item_Length; begin Set_Length (Source, Total_Length); Source.Data.Items (Old_Length + 1 .. Total_Length) := New_Item.Data.Items (1 .. New_Item_Length); -- Do not use New_Item.Length in here for Append (X, X). end; end if; end Append; procedure Append ( Source : in out Unbounded_String; New_Item : String_Type) is pragma Suppress (Access_Check); Old_Length : constant Natural := Source.Length; Total_Length : constant Natural := Old_Length + New_Item'Length; begin Set_Length (Source, Total_Length); Source.Data.Items (Old_Length + 1 .. Total_Length) := New_Item; end Append; procedure Append_Element ( Source : in out Unbounded_String; New_Item : Character_Type) is pragma Suppress (Access_Check); Old_Length : constant Natural := Source.Length; Total_Length : constant Natural := Old_Length + 1; begin Set_Length (Source, Total_Length); Source.Data.Items (Total_Length) := New_Item; end Append_Element; function "&" (Left, Right : Unbounded_String) return Unbounded_String is begin return Result : Unbounded_String := Left do Append (Result, Right); end return; end "&"; function "&" (Left : Unbounded_String; Right : String_Type) return Unbounded_String is begin return Result : Unbounded_String := Left do Append (Result, Right); end return; end "&"; function "&" (Left : String_Type; Right : Unbounded_String) return Unbounded_String is begin return Result : Unbounded_String do if Left'Length > 0 then Reallocate (Result, 0, Left'Length + Right.Length); Append (Result, Left); end if; Append (Result, Right); end return; end "&"; function "&" (Left : Unbounded_String; Right : Character_Type) return Unbounded_String is begin return Result : Unbounded_String := Left do Append_Element (Result, Right); end return; end "&"; function "&" (Left : Character_Type; Right : Unbounded_String) return Unbounded_String is begin return Result : Unbounded_String do Reallocate (Result, 0, 1 + Right.Length); Append_Element (Result, Left); Append (Result, Right); end return; end "&"; function Element (Source : Unbounded_String; Index : Positive) return Character_Type is pragma Check (Pre, Index <= Source.Length or else raise Index_Error); pragma Suppress (Access_Check); begin return Source.Data.Items (Index); end Element; procedure Replace_Element ( Source : in out Unbounded_String; Index : Positive; By : Character_Type) is pragma Check (Pre, Index <= Source.Length or else raise Index_Error); pragma Suppress (Access_Check); begin Unique (Source); Source.Data.Items (Index) := By; end Replace_Element; function Slice ( Source : Unbounded_String; Low : Positive; High : Natural) return String_Type is pragma Check (Pre, Check => (Low <= Source.Length + 1 and then High <= Source.Length) or else raise Index_Error); pragma Suppress (Access_Check); begin return Source.Data.Items (Low .. High); end Slice; function Unbounded_Slice ( Source : Unbounded_String; Low : Positive; High : Natural) return Unbounded_String is begin return Result : Unbounded_String do Unbounded_Slice (Source, Result, Low, High); -- checking Index_Error end return; end Unbounded_Slice; procedure Unbounded_Slice ( Source : Unbounded_String; Target : out Unbounded_String; Low : Positive; High : Natural) is pragma Check (Pre, Check => (Low <= Source.Length + 1 and then High <= Source.Length) or else raise Index_Error); pragma Suppress (Access_Check); begin if Low = 1 then Assign (Target, Source); Set_Length (Target, High); else Set_Unbounded_String (Target, Source.Data.Items (Low .. High)); end if; end Unbounded_Slice; overriding function "=" (Left, Right : Unbounded_String) return Boolean is pragma Suppress (Access_Check); begin return Left.Data.Items (1 .. Left.Length) = Right.Data.Items (1 .. Right.Length); end "="; function "=" (Left : Unbounded_String; Right : String_Type) return Boolean is pragma Suppress (Access_Check); begin return Left.Data.Items (1 .. Left.Length) = Right; end "="; function "=" (Left : String_Type; Right : Unbounded_String) return Boolean is pragma Suppress (Access_Check); begin return Left = Right.Data.Items (1 .. Right.Length); end "="; function "<" (Left, Right : Unbounded_String) return Boolean is pragma Suppress (Access_Check); begin return Left.Data.Items (1 .. Left.Length) < Right.Data.Items (1 .. Right.Length); end "<"; function "<" (Left : Unbounded_String; Right : String_Type) return Boolean is pragma Suppress (Access_Check); begin return Left.Data.Items (1 .. Left.Length) < Right; end "<"; function "<" (Left : String_Type; Right : Unbounded_String) return Boolean is pragma Suppress (Access_Check); begin return Left < Right.Data.Items (1 .. Right.Length); end "<"; function "<=" (Left, Right : Unbounded_String) return Boolean is begin return not (Right < Left); end "<="; function "<=" (Left : Unbounded_String; Right : String_Type) return Boolean is begin return not (Right < Left); end "<="; function "<=" (Left : String_Type; Right : Unbounded_String) return Boolean is begin return not (Right < Left); end "<="; function ">" (Left, Right : Unbounded_String) return Boolean is begin return Right < Left; end ">"; function ">" (Left : Unbounded_String; Right : String_Type) return Boolean is begin return Right < Left; end ">"; function ">" (Left : String_Type; Right : Unbounded_String) return Boolean is begin return Right < Left; end ">"; function ">=" (Left, Right : Unbounded_String) return Boolean is begin return not (Left < Right); end ">="; function ">=" (Left : Unbounded_String; Right : String_Type) return Boolean is begin return not (Left < Right); end ">="; function ">=" (Left : String_Type; Right : Unbounded_String) return Boolean is begin return not (Left < Right); end ">="; procedure Assign ( Target : in out Unbounded_String; Source : Unbounded_String) is begin System.Reference_Counting.Assign ( Upcast (Target.Data'Unchecked_Access), Upcast (Source.Data'Unrestricted_Access), Free => Free_Data'Access); Target.Length := Source.Length; end Assign; procedure Move ( Target : in out Unbounded_String; Source : in out Unbounded_String) is begin System.Reference_Counting.Move ( Upcast (Target.Data'Unchecked_Access), Upcast (Source.Data'Unrestricted_Access), Sentinel => Upcast (Empty_Data'Unrestricted_Access), Free => Free_Data'Access); Target.Length := Source.Length; Source.Length := 0; end Move; function Constant_Reference ( Source : aliased Unbounded_String) return Slicing.Constant_Reference_Type is pragma Suppress (Access_Check); begin return Slicing.Constant_Slice ( String_Access'(Source.Data.Items.all'Unrestricted_Access).all, 1, Source.Length); end Constant_Reference; function Reference ( Source : aliased in out Unbounded_String) return Slicing.Reference_Type is pragma Suppress (Access_Check); begin Unique (Source); return Slicing.Slice ( String_Access'(Source.Data.Items.all'Unrestricted_Access).all, 1, Source.Length); end Reference; procedure Unique (Source : in out Unbounded_String'Class) is begin if System.Reference_Counting.Shared (Upcast (Source.Data)) then Reallocate ( Unbounded_String (Source), Source.Length, Source.Length); -- shrinking end if; end Unique; procedure Unique_And_Set_Length ( Source : in out Unbounded_String'Class; Length : Natural) is begin if System.Reference_Counting.Shared (Upcast (Source.Data)) then Reallocate (Unbounded_String (Source), Length, Length); -- shrinking else Set_Length (Unbounded_String (Source), Length); end if; end Unique_And_Set_Length; overriding procedure Adjust (Object : in out Unbounded_String) is begin System.Reference_Counting.Adjust (Upcast (Object.Data'Unchecked_Access)); end Adjust; overriding procedure Finalize (Object : in out Unbounded_String) is begin System.Reference_Counting.Clear ( Upcast (Object.Data'Unchecked_Access), Free => Free_Data'Access); Object.Data := Empty_Data'Unrestricted_Access; Object.Length := 0; end Finalize; package body Generic_Constant is S_Data : aliased constant Data := ( Reference_Count => System.Reference_Counting.Static, Capacity => Integer'Last, Max_Length => System.Reference_Counting.Length_Type (Integer'Last), Items => S.all'Unrestricted_Access); function Value return Unbounded_String is begin return Create ( Data => S_Data'Unrestricted_Access, Length => S'Length); end Value; end Generic_Constant; package body Streaming is procedure Read ( Stream : not null access Streams.Root_Stream_Type'Class; Item : out Unbounded_String) is pragma Suppress (Access_Check); First : Integer; Last : Integer; begin Integer'Read (Stream, First); Integer'Read (Stream, Last); declare Length : constant Integer := Last - First + 1; begin Item.Length := 0; Set_Length (Item, Length); Read (Stream, Item.Data.Items (1 .. Length)); end; end Read; procedure Write ( Stream : not null access Streams.Root_Stream_Type'Class; Item : Unbounded_String) is pragma Suppress (Access_Check); begin Integer'Write (Stream, 1); Integer'Write (Stream, Item.Length); Write (Stream, Item.Data.Items (1 .. Item.Length)); end Write; end Streaming; end Ada.Strings.Generic_Unbounded;
pragma License (Unrestricted); with Ada.Numerics.Generic_Elementary_Functions; package Ada.Numerics.Long_Elementary_Functions is new Generic_Elementary_Functions (Long_Float); pragma Pure (Ada.Numerics.Long_Elementary_Functions);