content
stringlengths
23
1.05M
-- This spec has been automatically generated from FE310.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with HAL; with System; package FE310_SVD.PRIC is pragma Preelaborate; --------------- -- Registers -- --------------- subtype HFROSCCFG_DIV_Field is HAL.UInt6; subtype HFROSCCFG_TRIM_Field is HAL.UInt5; -- HF Ring Oscillator Configuration Register. type HFROSCCFG_Register is record DIV : HFROSCCFG_DIV_Field := 16#0#; -- unspecified Reserved_6_15 : HAL.UInt10 := 16#0#; TRIM : HFROSCCFG_TRIM_Field := 16#0#; -- unspecified Reserved_21_29 : HAL.UInt9 := 16#0#; ENABLE : Boolean := False; READY : Boolean := False; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for HFROSCCFG_Register use record DIV at 0 range 0 .. 5; Reserved_6_15 at 0 range 6 .. 15; TRIM at 0 range 16 .. 20; Reserved_21_29 at 0 range 21 .. 29; ENABLE at 0 range 30 .. 30; READY at 0 range 31 .. 31; end record; -- HF Crystal Oscillator Configuration Register. type HFXOSCCFG_Register is record -- unspecified Reserved_0_29 : HAL.UInt30 := 16#0#; ENABLE : Boolean := False; READY : Boolean := False; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for HFXOSCCFG_Register use record Reserved_0_29 at 0 range 0 .. 29; ENABLE at 0 range 30 .. 30; READY at 0 range 31 .. 31; end record; subtype PLLCFG_R_Field is HAL.UInt3; subtype PLLCFG_F_Field is HAL.UInt6; subtype PLLCFG_Q_Field is HAL.UInt2; type PLLCFG_SEL_Field is ( -- The HFROSCCLK directly drives HFCLK. Internal, -- Drive the final HFCLK with PLL output, bypassed or otherwise. Pll) with Size => 1; for PLLCFG_SEL_Field use (Internal => 0, Pll => 1); type PLLCFG_REFSEL_Field is ( -- Internal Oscillator. Internal, -- Crystal OScillator. Crystal) with Size => 1; for PLLCFG_REFSEL_Field use (Internal => 0, Crystal => 1); -- PLL Configuration Register. type PLLCFG_Register is record R : PLLCFG_R_Field := 16#0#; -- unspecified Reserved_3_3 : HAL.Bit := 16#0#; F : PLLCFG_F_Field := 16#0#; Q : PLLCFG_Q_Field := 16#0#; -- unspecified Reserved_12_15 : HAL.UInt4 := 16#0#; SEL : PLLCFG_SEL_Field := FE310_SVD.PRIC.Internal; REFSEL : PLLCFG_REFSEL_Field := FE310_SVD.PRIC.Internal; BYPASS : Boolean := False; -- unspecified Reserved_19_30 : HAL.UInt12 := 16#0#; LOCK : Boolean := False; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for PLLCFG_Register use record R at 0 range 0 .. 2; Reserved_3_3 at 0 range 3 .. 3; F at 0 range 4 .. 9; Q at 0 range 10 .. 11; Reserved_12_15 at 0 range 12 .. 15; SEL at 0 range 16 .. 16; REFSEL at 0 range 17 .. 17; BYPASS at 0 range 18 .. 18; Reserved_19_30 at 0 range 19 .. 30; LOCK at 0 range 31 .. 31; end record; subtype PLLOUTDIV_DIV_Field is HAL.UInt6; -- PLL Output Divider Register. type PLLOUTDIV_Register is record DIV : PLLOUTDIV_DIV_Field := 16#0#; -- unspecified Reserved_6_7 : HAL.UInt2 := 16#0#; DIV_BY_1 : Boolean := False; -- unspecified Reserved_9_31 : HAL.UInt23 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for PLLOUTDIV_Register use record DIV at 0 range 0 .. 5; Reserved_6_7 at 0 range 6 .. 7; DIV_BY_1 at 0 range 8 .. 8; Reserved_9_31 at 0 range 9 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- Power, Reset, Clock, Interrupt. type PRIC_Peripheral is record -- HF Ring Oscillator Configuration Register. HFROSCCFG : aliased HFROSCCFG_Register; -- HF Crystal Oscillator Configuration Register. HFXOSCCFG : aliased HFXOSCCFG_Register; -- PLL Configuration Register. PLLCFG : aliased PLLCFG_Register; -- PLL Output Divider Register. PLLOUTDIV : aliased PLLOUTDIV_Register; end record with Volatile; for PRIC_Peripheral use record HFROSCCFG at 16#0# range 0 .. 31; HFXOSCCFG at 16#4# range 0 .. 31; PLLCFG at 16#8# range 0 .. 31; PLLOUTDIV at 16#C# range 0 .. 31; end record; -- Power, Reset, Clock, Interrupt. PRIC_Periph : aliased PRIC_Peripheral with Import, Address => System'To_Address (16#10008000#); end FE310_SVD.PRIC;
$NetBSD: patch-src__editor_src_src__editor__buffer.adb,v 1.2 2014/04/30 16:32:20 marino Exp $ Disambiguation required to compile with FSF GNAT 4.9.0 --- src_editor/src/src_editor_buffer.adb.orig 2012-09-28 15:42:43.000000000 +0000 +++ src_editor/src/src_editor_buffer.adb @@ -5820,7 +5820,7 @@ package body Src_Editor_Buffer is while Result and then not Ends_Line (Iter) - and then Is_Space (Get_Char (Iter)) + and then Glib.Unicode.Is_Space (Gtk.Text_Iter.Get_Char (Iter)) loop Forward_Char (Iter, Result); Offset := Offset + 1;
-- { dg-do run } -- { dg-options "-O2" } with Enum1_Pkg; use Enum1_Pkg; procedure Enum1 is function Cond return Boolean is begin return My_N = Two or My_N = Three; end; begin if Cond then raise Constraint_Error; end if; end;
WITH Ada.Text_Io; USE Ada.Text_Io; procedure Ver_Substring_aa is -- salida: 11 booleanos(SE) -- post: corresponden a cada uno de los casos de pruebas dise�ados. -- pre: { True } function Substring_aa( S : String) return Boolean is -- EJERCICIO 3- ESPECIFICA E IMPLEMENTA recursivamente el subprograma -- Substring_aa que decide si el string S contiene el substring 'aa'. BEGIN -- Completar if S'Size < 16 then return False; end if; if S(S'First .. S'First + 1) = "aa" then return True; end if; return Substring_aa(S(S'First + 1 .. S'Last)); end Substring_aa; -- post: { True <=> Substring(S) } begin Put_Line("-------------------------------------"); Put("La palabra vacia no contiene el string 'aa': "); Put(Boolean'Image(Substring_aa(""))); New_Line; New_Line; New_Line; Put_Line("-------------------------------------"); Put_Line("Palabras de 1 caracter"); Put("-- La palabra de 1 caracter 'a' no contiene el substring 'aa': "); Put(Boolean'Image(Substring_aa("a"))); New_Line; Put("-- La palabra de 1 caracter 'b' no contiene el substring 'aa': "); Put(Boolean'Image(Substring_aa("b"))); New_Line; New_Line; New_Line; Put_Line("-------------------------------------"); Put_Line("Palabras de varios caracteres"); Put("-- 'aaaa' contiene el substring 'aa': "); Put(Boolean'Image(Substring_aa("aaaa"))); New_Line; Put("-- 'bbbb' no contiene el substring 'aa': "); Put(Boolean'Image(Substring_aa("bbbb"))); New_Line; Put("-- 'abab' no contiene el substring 'aa': "); Put(Boolean'Image(Substring_aa("abab"))); New_Line; Put("-- 'baba' no contiene el substring 'aa': "); Put(Boolean'Image(Substring_aa("baba"))); New_Line; Put("-- 'abba' no contiene el substring 'aa': "); Put(Boolean'Image(Substring_aa("abba"))); New_Line; Put("-- 'aabb' contiene el substring 'aa': "); Put(Boolean'Image(Substring_aa("aabb"))); New_Line; Put("-- 'baab' contiene el substring 'aa': "); Put(Boolean'Image(Substring_aa("baab"))); New_Line; Put("-- 'bbaa' contiene el substring 'aa': "); Put(Boolean'Image(Substring_aa("bbaa"))); New_Line; Put_Line("-------------------------------------"); end Ver_Substring_aa;
function Lnko ( A, B : Positive ) return Positive is X: Positive := A; Y: Natural := B; Tmp: Natural; begin while Y /= 0 loop Tmp := X mod Y; X := Y; Y := Tmp; end loop; return X; end Lnko;
----------------------------------------------------------------------- -- keystore-passwords-tests -- Tests for Keystore.Passwords -- Copyright (C) 2019 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Ada.Streams.Stream_IO; with Util.Test_Caller; with Util.Encoders.SHA256; with Util.Encoders.HMAC.SHA256; with Keystore.Tests; with Keystore.Passwords.Keys; with Keystore.Passwords.Files; package body Keystore.Passwords.Tests is use type Ada.Streams.Stream_Element_Array; package Caller is new Util.Test_Caller (Test, "AKT.Passwords"); function Hash (Provider : in Keys.Key_Provider_Access) return Util.Encoders.SHA256.Hash_Array; procedure Free is new Ada.Unchecked_Deallocation (Object => Keys.Key_Provider'Class, Name => Keys.Key_Provider_Access); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Keystore.Passwords.Files", Test_File_Password'Access); end Add_Tests; function Hash (Provider : in Keys.Key_Provider_Access) return Util.Encoders.SHA256.Hash_Array is Context : Util.Encoders.HMAC.SHA256.Context; Key : Secret_Key (Length => 32); IV : Secret_Key (Length => 16); Sign : Secret_Key (Length => 32); Result : Util.Encoders.SHA256.Hash_Array; begin Provider.Get_Keys (Key, IV, Sign); Util.Encoders.HMAC.SHA256.Set_Key (Context, Key); Util.Encoders.HMAC.SHA256.Update (Context, IV); Util.Encoders.HMAC.SHA256.Update (Context, Sign); Util.Encoders.HMAC.SHA256.Finish (Context, Result); return Result; end Hash; -- ------------------------------ -- Test the using the Passwords.Files -- ------------------------------ procedure Test_File_Password (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/pass/key1.bin"); Provider1 : Keys.Key_Provider_Access; Provider2 : Keys.Key_Provider_Access; Hash1 : Util.Encoders.SHA256.Hash_Array; Hash2 : Util.Encoders.SHA256.Hash_Array; File : Ada.Streams.Stream_IO.File_Type; begin Provider1 := Files.Generate (Path); Provider2 := Files.Create (Path); Hash1 := Hash (Provider1); Hash2 := Hash (Provider2); T.Assert (Hash1 = Hash2, "Generate and Create are inconsistent"); Free (Provider1); Provider1 := Files.Generate (Path); Hash1 := Hash (Provider1); T.Assert (Hash1 /= Hash2, "Generate and Create are inconsistent"); Free (Provider1); Free (Provider2); Ada.Streams.Stream_IO.Create (File, Ada.Streams.Stream_IO.Out_File, Path); Ada.Streams.Stream_IO.Close (File); begin Provider2 := Files.Create (Path); T.Fail ("No exception raised for an empty file"); exception when Bad_Password => null; end; Ada.Streams.Stream_IO.Create (File, Ada.Streams.Stream_IO.Out_File, Path); for I in 1 .. 200 loop Ada.Streams.Stream_IO.Write (File, Hash1); end loop; Ada.Streams.Stream_IO.Close (File); begin Provider2 := Files.Create (Path); T.Fail ("No exception raised for a big file"); exception when Bad_Password => null; end; if not Keystore.Tests.Is_Windows then begin Provider2 := Files.Create ("Makefile.conf"); T.Fail ("No exception raised for a file stored in an unprotected dir"); exception when Bad_Password => null; end; end if; end Test_File_Password; end Keystore.Passwords.Tests;
------------------------------------------------------------------------------ -- File : Float_portable_binary_transfer.ads -- Description : Split & merge floating - point numbers into integers to -- facilitate a portable transfer, including Input - Output -- Date / Version : 2 - Sep - 2006; 28 - Aug - 2006; 27 - Aug - 2006 -- Author : G. de Montmollin - public domain code ------------------------------------------------------------------------------ generic type Num is digits <>; type Mantissa_type is range <>; type Exponent_type is range <>; -- If one is not sure that 'Machine_Mantissa and 'Machine_Radis -- will be the same on the machine performing Split than on the -- machine performing Merge, it is better to impose the mantissa scaling imposed_mantissa : Boolean; -- choice imposed_scaling : Num; -- factor from fraction to mantissa value package Float_portable_binary_transfer is procedure Split (f : in Num; m : out Mantissa_type; e : out Exponent_type); procedure Merge (m : in Mantissa_type; e : in Exponent_type; f : out Num); -- Split / Merge in two parts (e.g. for transporting a Long_Float -- when the compiler has only up to 32 - bit integers. For splitting, -- the scaling factor is applied once for m1, then a second time for m2. procedure Split (f : in Num; m1, m2 : out Mantissa_type; e : out Exponent_type); procedure Merge (m1, m2 : in Mantissa_type; e : in Exponent_type; f : out Num); end Float_portable_binary_transfer;
with Interfaces; use Interfaces; with Bitmap_Graphics; use Bitmap_Graphics; package body Bitmap_Buffer is -- Set the color for the whole buffer. procedure Set(Buf: Buffer_Ref; Clr: Color) is Val: Unsigned_8; begin case Clr is when White => Val := 255; when Black => Val := 0; end case; for I in 1 .. Buf.Data'Last loop Buf.Data(I) := Val; end loop; end Set; -- Set the color for one point in the graphics buffer. procedure Set (Buf: Buffer_Ref; -- The graphic buffer P : Point; -- Point to draw Clr: Color) -- Color for point P is Index : Natural; -- Index of the byte in buffer Old_Val, New_Val : Unsigned_8; -- Old and new value for this byte begin if P.X <= Width and P.Y <= Height then Index := P.X + (P.Y / 8) * Width; Old_Val := Buf.Data(Index); case Clr is when White => New_Val := Old_Val or Shift_Left(1, P.Y mod 8); when Black => New_Val := Old_Val or Shift_Left(0, P.Y mod 8); end case; Buf.Data(Index) := New_Val; end if; end Set; function Pt(P: Point; X,Y:Integer) return Point is begin return (P.X + X, P.Y + Y); end Pt; function Pt(X,Y:Natural) return Point is begin return (X, Y); end Pt; -- Draw a point with size "Size" at poiny X,Y. procedure Dot(Buf:Buffer_Ref; P:Point; Size:Positive:=1; Clr:Color:=White) is begin for Dx in -(Size-1) .. (Size-1) loop for Dy in -(Size-1) .. (Size-1) loop Set(Buf, Pt(P, Dx, Dy), Clr); end loop; end loop; end Dot; procedure Swap(X: in out Natural; Y: in out Natural) is Tmp : Natural; begin Tmp := X; X := Y; Y := Tmp; end Swap; procedure Line (Buf:Buffer_Ref; P,Q: Point; Size:Positive:=1; Clr:Color:=White) is X, Y: Natural; Dx, Dy : Integer; Step_X, Step_Y: Integer; Esp : Integer; begin if P.X <= Width and P.Y <= Height and Q.X <= Width and Q.Y <= Height then if P.X < Q.X then Dx := Q.X - P.X; Step_X := 1; else Dx := P.X - Q.X; Step_X := -1; end if; if P.Y < Q.Y then Dy := P.Y - Q.Y; -- ! Dy needs to be negative Step_Y := 1; else Dy := Q.Y - P.Y; Step_Y := -1; end if; X := P.X; Y := P.Y; Esp := Dx + Dy; -- int32_t dy =(int32_t)Yend -(int32_t)Ystart <= 0 ? Yend - Ystart : Ystart - Yend; loop Dot(Buf, Pt(X, Y), Size, Clr); if 2 * Esp >= dy then exit when X = Q.X; Esp := Esp + dy; X := X + Step_X; end if; if 2 * Esp <= dx then exit when Y = Q.Y; Esp := Esp + dx; Y := Y + Step_Y; end if; end loop; end if; end Line; procedure Rectangle (Buf:Buffer_Ref; P,Q: Point; Size:Positive:=1; Clr:Color:=White) is begin Line(Buf, P, Pt(Q.X, P.Y), Size, Clr); Line(Buf, P, Pt(P.X, Q.Y), Size, Clr); Line(Buf, Q, Pt(Q.X, P.Y), Size, Clr); Line(Buf, Q, Pt(P.X, Q.Y), Size, Clr); end Rectangle; procedure Fill_Rectangle (Buf:Buffer_Ref; P,Q: Point; Clr:Color:=White) is Y_A, Y_B: Natural; begin if P.Y < Q.Y then Y_A := P.Y; Y_B := Q.Y; else Y_A := Q.Y; Y_B := P.Y; end if; for Y in Y_A .. Y_B loop Line(Buf, Pt(P.X, Y), Pt(Q.X, Y), 1, Clr); end loop; end Fill_Rectangle; procedure Circle (Buf:Buffer_Ref; P: Point; R: Natural; Size: Positive:=1; Clr: Color:=White) is X, Y: Integer; Esp : Integer; begin X := 0; Y := R; Esp := 3 - (R * 2); while X <= Y loop Dot(Buf, Pt(P.X + X, P.Y + Y), Size, Clr); --1 Dot(Buf, Pt(P.X - X, P.Y + Y), Size, Clr); --2 Dot(Buf, Pt(P.X - Y, P.Y + X), Size, Clr); --3 Dot(Buf, Pt(P.X - Y, P.Y - X), Size, Clr); --4 Dot(Buf, Pt(P.X - X, P.Y - Y), Size, Clr); --5 Dot(Buf, Pt(P.X + X, P.Y - Y), Size, Clr); --6 Dot(Buf, Pt(P.X + Y, P.Y - X), Size, Clr); --7 Dot(Buf, Pt(P.X + Y, P.Y + X), Size, Clr); --0 if Esp < 0 then Esp := Esp + (4 * X + 6); else Esp := Esp + (10 + 4 * (X - Y)); Y := Y - 1; end if; X := X + 1; end loop; end Circle; procedure Fill_Circle (Buf:Buffer_Ref; P: Point; R: Natural; Clr: Color:=White) is X,Y: Integer; Esp : Integer; begin X := 0; Y := R; Esp := 3 - (R * 2); while X <= Y loop for Count_Y in X .. (Y-1) loop null; Dot(Buf, Pt(P.X + X, P.Y + Count_Y), 1, Clr); --1 Dot(Buf, Pt(P.X - X, P.Y + Count_Y), 1, Clr); --2 Dot(Buf, Pt(P.X - Count_Y, P.Y + X), 1, Clr); --3 Dot(Buf, Pt(P.X - Count_Y, P.Y - X), 1, Clr); --4 Dot(Buf, Pt(P.X - X, P.Y - Count_Y), 1, Clr); --5 Dot(Buf, Pt(P.X + X, P.Y - Count_Y), 1, Clr); --6 Dot(Buf, Pt(P.X + Count_Y, P.Y - X), 1, Clr); --7 Dot(Buf, Pt(P.X + Count_Y, P.Y + X), 1, Clr); end loop; if Esp < 0 then Esp := Esp+ ( 4 * X + 6); else Esp := Esp + (10 + 4 *(X - Y )); Y := Y - 1; end if; X := X+1; end loop; end Fill_Circle; procedure Draw_Char (Buf : Buffer_Ref; X, Y : Natural; Ch : Character; Font_Ref : Font_Access; Fgnd, Bgnd : Color) is Value : Unsigned_8; Size, Offset : Natural; Mask : constant Unsigned_8 := 16#80#; Masked_Value: Unsigned_8; begin if Font_Ref.Width mod 8 = 0 then Size := Font_Ref.Height * (Font_Ref.Width / 8); else Size := Font_Ref.Height * (Font_Ref.Width / 8 + 1); end if; Offset := (Character'Pos(Ch) - Character'Pos(' ')) * size; Value := Font_Ref.Data(Offset); for Page in 0 .. (Font_Ref.Height-1) loop Column_Loop: for Column in 0 .. (Font_Ref.Width-1) loop Masked_Value := Value and (Shift_Right(Mask, Column mod 8)) ; if Bgnd = Black then if Masked_Value /= 0 then Set(Buf, Pt(X + Column, Y + Page), Fgnd); end if; else if Masked_Value /= 0 then Set(Buf, Pt(X + Column, Y + Page), Fgnd); else Set(Buf, Pt(X + Column, Y + Page), Bgnd); end if; end if; if Column mod 8 = 7 then Offset := Offset + 1; Value := Font_Ref.Data(Offset); end if; end loop Column_Loop; if Font_Ref.Width mod 8 /= 0 then Offset := Offset + 1; Value := Font_Ref.Data(Offset); end if; end loop; end Draw_Char; procedure Put (Buf : Buffer_Ref; P : Point; Ch : Character; Size: Positive; Fgnd: Color:= White; Bgnd: Color:= Black) is F : Font_Access; begin F := Bitmap_Graphics.Get_Font(Size); Draw_Char(Buf, P.X, P.Y, Ch, F, Fgnd, Bgnd); end Put; procedure Draw_Str (Buf : Buffer_Ref; P : Point; Str : String; Font_Ref: Font_Access; Fgnd : Color:= White; Bgnd : Color:= Black) is X : Natural := P.X; -- Current x position Y : Natural := P.Y; -- Current y position begin for I in 1 .. Str'Last loop -- if the X direction is filled, then continue at next line if (X + Font_Ref.Width) > Width then X := P.X; Y := Y + Font_Ref.Height; end if; -- If the Y direction is full, reposition to P if (Y + Font_Ref.Height) > Height then X := P.X; Y := P.Y; end if; Draw_Char(Buf, X, Y, Str(I), Font_Ref, Fgnd, Bgnd); X := X + Font_Ref.Width; end loop; end Draw_Str; -- Draw a string into the graphics buffer. procedure Put (Buf : Buffer_Ref; P : Point; Str : String; Size: Positive; Fgnd: Color:= White; Bgnd: Color:= Black) is F : Font_Access; begin F := Get_Font(Size); Draw_Str(Buf, P, Str, F, Fgnd, Bgnd); end Put; procedure Draw_Num (Buf : Buffer_Ref; X, Y : Natural; Num : Natural; Font_Ref : Font_Access; Fgnd, Bgnd : Color) is Str : String(1..128); Pos : Positive := 1; Rev_Str : String(1..128); Rev_Pos : Positive := 1; Number : Integer := Num; begin -- Converts a number to a string while Number > 0 loop Rev_Str(Rev_Pos) := Character'Val(Number mod 10 + Character'Pos('0')); Rev_Pos := Rev_Pos + 1; Number := Number / 10; end loop; -- The string is inverted while Rev_Pos > 1 loop Str(Pos) := Rev_Str(Rev_Pos-1); Pos := Pos + 1; Rev_Pos := Rev_Pos -1; end loop; Draw_Str(Buf, Pt(X, Y), Str(1.. (Pos-1)), Font_Ref, Fgnd, Bgnd); end Draw_Num; -- Draw a number into the graphics buffer. procedure Put (Buf : Buffer_Ref; P : Point; Num : Natural; Size: Positive; Fgnd: Color:= White; Bgnd: Color:= Black) is F : Font_Access; begin F := Get_Font(Size); Draw_Num(Buf, P.X, P.Y, Num, F, Fgnd, Bgnd); end Put; procedure Bitmap (Buf : Buffer_Ref; P : Point; Bytes : Byte_Array_Access; Siz : Size) is Byte_Width : Natural := (Siz.Width + 7)/8; Byte : Unsigned_8; Mask : Unsigned_8; Masked_Value : Unsigned_8; begin for J in 0 .. (Siz.Height-1) loop for I in 0 .. (Siz.Width-1) loop Byte := Bytes(J * Byte_Width + I / 8); Mask := Shift_Right(128, I mod 8); Masked_Value := Byte and Mask; if Masked_Value /= 0 then Dot(Buf, Pt(P.X + I, P.Y + J)); end if; end loop; end loop; end Bitmap; procedure Bitmap (Buf : Buffer_Ref; P : Point; Icon : Bitmap_Icon) is Width : Natural; Height : Natural; Data : Byte_Array_Access; begin Get_Icon(Icon, Width, Height, Data); Bitmap(Buf, P, Data, (Width, Height)); end; end Bitmap_Buffer;
-- Copyright (c) 2021 Devin Hill -- zlib License -- see LICENSE for details. package body GBA.Numerics.Vectors is function Pointwise (V, W : Vec) return Vec is begin return ( 0 => Operator (V (0), W (0)) , 1 => Operator (V (1), W (1)) ); end; function Scalar (V : Vec; E : Element) return Vec is begin return ( 0 => Operator (V (0), E) , 1 => Operator (V (1), E) ); end; function EMul (X, Y : Element) return Element is ( X * Y ) with Inline_Always; function EDiv (X, Y : Element) return Element is ( X / Y ) with Inline_Always; function VAdd is new Pointwise ("+"); function VSub is new Pointwise ("-"); function VMul is new Pointwise (EMul); function VDiv is new Pointwise (EDiv); function VAdd is new Scalar ("+"); function VSub is new Scalar ("-"); function VMul is new Scalar (EMul); function VDiv is new Scalar (EDiv); function "+" (V, W : Vec) return Vec renames VAdd; function "-" (V, W : Vec) return Vec renames VSub; function "*" (V, W : Vec) return Vec renames VMul; function "/" (V, W : Vec) return Vec renames VDiv; function "+" (V : Vec; E : Element) return Vec renames VAdd; function "-" (V : Vec; E : Element) return Vec renames VSub; function "*" (V : Vec; E : Element) return Vec renames VMul; function "/" (V : Vec; E : Element) return Vec renames VDiv; function Dot (V, W : Vec) return Element is begin return Vec'(V * W)'Reduce ("+", 0.0); end; end GBA.Numerics.Vectors;
with Ada.Text_IO; procedure Integers_In_English is type Spellable is range -999_999_999_999_999_999..999_999_999_999_999_999; function Spell (N : Spellable) return String is function Twenty (N : Spellable) return String is begin case N mod 20 is when 0 => return "zero"; when 1 => return "one"; when 2 => return "two"; when 3 => return "three"; when 4 => return "four"; when 5 => return "five"; when 6 => return "six"; when 7 => return "seven"; when 8 => return "eight"; when 9 => return "nine"; when 10 => return "ten"; when 11 => return "eleven"; when 12 => return "twelve"; when 13 => return "thirteen"; when 14 => return "fourteen"; when 15 => return "fifteen"; when 16 => return "sixteen"; when 17 => return "seventeen"; when 18 => return "eighteen"; when others => return "nineteen"; end case; end Twenty; function Decade (N : Spellable) return String is begin case N mod 10 is when 2 => return "twenty"; when 3 => return "thirty"; when 4 => return "forty"; when 5 => return "fifty"; when 6 => return "sixty"; when 7 => return "seventy"; when 8 => return "eighty"; when others => return "ninety"; end case; end Decade; function Hundred (N : Spellable) return String is begin if N < 20 then return Twenty (N); elsif 0 = N mod 10 then return Decade (N / 10 mod 10); else return Decade (N / 10) & '-' & Twenty (N mod 10); end if; end Hundred; function Thousand (N : Spellable) return String is begin if N < 100 then return Hundred (N); elsif 0 = N mod 100 then return Twenty (N / 100) & " hundred"; else return Twenty (N / 100) & " hundred and " & Hundred (N mod 100); end if; end Thousand; function Triplet ( N : Spellable; Order : Spellable; Name : String; Rest : not null access function (N : Spellable) return String ) return String is High : Spellable := N / Order; Low : Spellable := N mod Order; begin if High = 0 then return Rest (Low); elsif Low = 0 then return Thousand (High) & ' ' & Name; else return Thousand (High) & ' ' & Name & ", " & Rest (Low); end if; end Triplet; function Million (N : Spellable) return String is begin return Triplet (N, 10**3, "thousand", Thousand'Access); end Million; function Milliard (N : Spellable) return String is begin return Triplet (N, 10**6, "million", Million'Access); end Milliard; function Billion (N : Spellable) return String is begin return Triplet (N, 10**9, "milliard", Milliard'Access); end Billion; function Billiard (N : Spellable) return String is begin return Triplet (N, 10**12, "billion", Billion'Access); end Billiard; begin if N < 0 then return "negative " & Spell(-N); else return Triplet (N, 10**15, "billiard", Billiard'Access); end if; end Spell; procedure Spell_And_Print(N: Spellable) is Number: constant String := Spellable'Image(N); Spaces: constant String(1 .. 20) := (others => ' '); -- 20 * ' ' begin Ada.Text_IO.Put_Line(Spaces(Spaces'First .. Spaces'Last-Number'Length) & Number & ' ' & Spell(N)); end Spell_And_Print; Samples: constant array (Natural range <>) of Spellable := (99, 300, 310, 1_501, 12_609, 512_609, 43_112_609, 77_000_112_609, 2_000_000_000_100, 999_999_999_999_999_999, 0, -99, -1501, -77_000_112_609, -123_456_789_987_654_321); begin for I in Samples'Range loop Spell_And_Print(Samples(I)); end loop; end Integers_In_English;
pragma Style_Checks (Off); -- This spec has been automatically generated from STM32H743x.svd pragma Restrictions (No_Elaboration_Code); with HAL; with System; package STM32_SVD.GPIO is pragma Preelaborate; --------------- -- Registers -- --------------- -- MODER_MODE array element subtype MODER_MODE_Element is HAL.UInt2; -- MODER_MODE array type MODER_MODE_Field_Array is array (0 .. 15) of MODER_MODE_Element with Component_Size => 2, Size => 32; -- GPIO port mode register type MODER_Register (As_Array : Boolean := False) is record case As_Array is when False => -- MODE as a value Val : HAL.UInt32; when True => -- MODE as an array Arr : MODER_MODE_Field_Array; end case; end record with Unchecked_Union, Size => 32, Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for MODER_Register use record Val at 0 range 0 .. 31; Arr at 0 range 0 .. 31; end record; -- OTYPER_OT array type OTYPER_OT_Field_Array is array (0 .. 15) of Boolean with Component_Size => 1, Size => 16; -- Type definition for OTYPER_OT type OTYPER_OT_Field (As_Array : Boolean := False) is record case As_Array is when False => -- OT as a value Val : HAL.UInt16; when True => -- OT as an array Arr : OTYPER_OT_Field_Array; end case; end record with Unchecked_Union, Size => 16; for OTYPER_OT_Field use record Val at 0 range 0 .. 15; Arr at 0 range 0 .. 15; end record; -- GPIO port output type register type OTYPER_Register is record -- Port x configuration bits (y = 0..15) These bits are written by -- software to configure the I/O output type. OT : OTYPER_OT_Field := (As_Array => False, Val => 16#0#); -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for OTYPER_Register use record OT at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; -- OSPEEDR_OSPEED array element subtype OSPEEDR_OSPEED_Element is HAL.UInt2; -- OSPEEDR_OSPEED array type OSPEEDR_OSPEED_Field_Array is array (0 .. 15) of OSPEEDR_OSPEED_Element with Component_Size => 2, Size => 32; -- GPIO port output speed register type OSPEEDR_Register (As_Array : Boolean := False) is record case As_Array is when False => -- OSPEED as a value Val : HAL.UInt32; when True => -- OSPEED as an array Arr : OSPEEDR_OSPEED_Field_Array; end case; end record with Unchecked_Union, Size => 32, Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for OSPEEDR_Register use record Val at 0 range 0 .. 31; Arr at 0 range 0 .. 31; end record; -- PUPDR_PUPD array element subtype PUPDR_PUPD_Element is HAL.UInt2; -- PUPDR_PUPD array type PUPDR_PUPD_Field_Array is array (0 .. 15) of PUPDR_PUPD_Element with Component_Size => 2, Size => 32; -- GPIO port pull-up/pull-down register type PUPDR_Register (As_Array : Boolean := False) is record case As_Array is when False => -- PUPD as a value Val : HAL.UInt32; when True => -- PUPD as an array Arr : PUPDR_PUPD_Field_Array; end case; end record with Unchecked_Union, Size => 32, Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for PUPDR_Register use record Val at 0 range 0 .. 31; Arr at 0 range 0 .. 31; end record; -- IDR array type IDR_Field_Array is array (0 .. 15) of Boolean with Component_Size => 1, Size => 16; -- Type definition for IDR type IDR_Field (As_Array : Boolean := False) is record case As_Array is when False => -- IDR as a value Val : HAL.UInt16; when True => -- IDR as an array Arr : IDR_Field_Array; end case; end record with Unchecked_Union, Size => 16; for IDR_Field use record Val at 0 range 0 .. 15; Arr at 0 range 0 .. 15; end record; -- GPIO port input data register type IDR_Register is record -- Read-only. Port input data bit (y = 0..15) These bits are read-only. -- They contain the input value of the corresponding I/O port. IDR : IDR_Field; -- unspecified Reserved_16_31 : HAL.UInt16; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for IDR_Register use record IDR at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; -- ODR array type ODR_Field_Array is array (0 .. 15) of Boolean with Component_Size => 1, Size => 16; -- Type definition for ODR type ODR_Field (As_Array : Boolean := False) is record case As_Array is when False => -- ODR as a value Val : HAL.UInt16; when True => -- ODR as an array Arr : ODR_Field_Array; end case; end record with Unchecked_Union, Size => 16; for ODR_Field use record Val at 0 range 0 .. 15; Arr at 0 range 0 .. 15; end record; -- GPIO port output data register type ODR_Register is record -- Port output data bit These bits can be read and written by software. -- Note: For atomic bit set/reset, the OD bits can be individually set -- and/or reset by writing to the GPIOx_BSRR or GPIOx_BRR registers (x = -- A..F). ODR : ODR_Field := (As_Array => False, Val => 16#0#); -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for ODR_Register use record ODR at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; -- BSRR_BS array type BSRR_BS_Field_Array is array (0 .. 15) of Boolean with Component_Size => 1, Size => 16; -- Type definition for BSRR_BS type BSRR_BS_Field (As_Array : Boolean := False) is record case As_Array is when False => -- BS as a value Val : HAL.UInt16; when True => -- BS as an array Arr : BSRR_BS_Field_Array; end case; end record with Unchecked_Union, Size => 16; for BSRR_BS_Field use record Val at 0 range 0 .. 15; Arr at 0 range 0 .. 15; end record; -- BSRR_BR array type BSRR_BR_Field_Array is array (0 .. 15) of Boolean with Component_Size => 1, Size => 16; -- Type definition for BSRR_BR type BSRR_BR_Field (As_Array : Boolean := False) is record case As_Array is when False => -- BR as a value Val : HAL.UInt16; when True => -- BR as an array Arr : BSRR_BR_Field_Array; end case; end record with Unchecked_Union, Size => 16; for BSRR_BR_Field use record Val at 0 range 0 .. 15; Arr at 0 range 0 .. 15; end record; -- GPIO port bit set/reset register type BSRR_Register is record -- Write-only. Port x set bit y (y= 0..15) These bits are write-only. A -- read to these bits returns the value 0x0000. BS : BSRR_BS_Field := (As_Array => False, Val => 16#0#); -- Write-only. Port x reset bit y (y = 0..15) These bits are write-only. -- A read to these bits returns the value 0x0000. Note: If both BSx and -- BRx are set, BSx has priority. BR : BSRR_BR_Field := (As_Array => False, Val => 16#0#); end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for BSRR_Register use record BS at 0 range 0 .. 15; BR at 0 range 16 .. 31; end record; -- LCKR_LCK array type LCKR_LCK_Field_Array is array (0 .. 15) of Boolean with Component_Size => 1, Size => 16; -- Type definition for LCKR_LCK type LCKR_LCK_Field (As_Array : Boolean := False) is record case As_Array is when False => -- LCK as a value Val : HAL.UInt16; when True => -- LCK as an array Arr : LCKR_LCK_Field_Array; end case; end record with Unchecked_Union, Size => 16; for LCKR_LCK_Field use record Val at 0 range 0 .. 15; Arr at 0 range 0 .. 15; end record; -- This register is used to lock the configuration of the port bits when a -- correct write sequence is applied to bit 16 (LCKK). The value of bits -- [15:0] is used to lock the configuration of the GPIO. During the write -- sequence, the value of LCKR[15:0] must not change. When the LOCK -- sequence has been applied on a port bit, the value of this port bit can -- no longer be modified until the next MCU reset or peripheral reset.A -- specific write sequence is used to write to the GPIOx_LCKR register. -- Only word access (32-bit long) is allowed during this locking -- sequence.Each lock bit freezes a specific configuration register -- (control and alternate function registers). type LCKR_Register is record -- Port x lock bit y (y= 0..15) These bits are read/write but can only -- be written when the LCKK bit is 0. LCK : LCKR_LCK_Field := (As_Array => False, Val => 16#0#); -- Lock key This bit can be read any time. It can only be modified using -- the lock key write sequence. LOCK key write sequence: WR LCKR[16] = 1 -- + LCKR[15:0] WR LCKR[16] = 0 + LCKR[15:0] WR LCKR[16] = 1 + -- LCKR[15:0] RD LCKR RD LCKR[16] = 1 (this read operation is optional -- but it confirms that the lock is active) Note: During the LOCK key -- write sequence, the value of LCK[15:0] must not change. Any error in -- the lock sequence aborts the lock. After the first lock sequence on -- any bit of the port, any read access on the LCKK bit will return 1 -- until the next MCU reset or peripheral reset. LCKK : Boolean := False; -- unspecified Reserved_17_31 : HAL.UInt15 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for LCKR_Register use record LCK at 0 range 0 .. 15; LCKK at 0 range 16 .. 16; Reserved_17_31 at 0 range 17 .. 31; end record; -- AFRL_AFSEL array element subtype AFRL_AFSEL_Element is HAL.UInt4; -- AFRL_AFSEL array type AFRL_AFSEL_Field_Array is array (0 .. 7) of AFRL_AFSEL_Element with Component_Size => 4, Size => 32; -- GPIO alternate function low register type AFRL_Register (As_Array : Boolean := False) is record case As_Array is when False => -- AFSEL as a value Val : HAL.UInt32; when True => -- AFSEL as an array Arr : AFRL_AFSEL_Field_Array; end case; end record with Unchecked_Union, Size => 32, Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AFRL_Register use record Val at 0 range 0 .. 31; Arr at 0 range 0 .. 31; end record; -- AFRH_AFSEL array element subtype AFRH_AFSEL_Element is HAL.UInt4; -- AFRH_AFSEL array type AFRH_AFSEL_Field_Array is array (8 .. 15) of AFRH_AFSEL_Element with Component_Size => 4, Size => 32; -- GPIO alternate function high register type AFRH_Register (As_Array : Boolean := False) is record case As_Array is when False => -- AFSEL as a value Val : HAL.UInt32; when True => -- AFSEL as an array Arr : AFRH_AFSEL_Field_Array; end case; end record with Unchecked_Union, Size => 32, Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AFRH_Register use record Val at 0 range 0 .. 31; Arr at 0 range 0 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- GPIO type GPIO_Peripheral is record -- GPIO port mode register MODER : aliased MODER_Register; -- GPIO port output type register OTYPER : aliased OTYPER_Register; -- GPIO port output speed register OSPEEDR : aliased OSPEEDR_Register; -- GPIO port pull-up/pull-down register PUPDR : aliased PUPDR_Register; -- GPIO port input data register IDR : aliased IDR_Register; -- GPIO port output data register ODR : aliased ODR_Register; -- GPIO port bit set/reset register BSRR : aliased BSRR_Register; -- This register is used to lock the configuration of the port bits when -- a correct write sequence is applied to bit 16 (LCKK). The value of -- bits [15:0] is used to lock the configuration of the GPIO. During the -- write sequence, the value of LCKR[15:0] must not change. When the -- LOCK sequence has been applied on a port bit, the value of this port -- bit can no longer be modified until the next MCU reset or peripheral -- reset.A specific write sequence is used to write to the GPIOx_LCKR -- register. Only word access (32-bit long) is allowed during this -- locking sequence.Each lock bit freezes a specific configuration -- register (control and alternate function registers). LCKR : aliased LCKR_Register; -- GPIO alternate function low register AFRL : aliased AFRL_Register; -- GPIO alternate function high register AFRH : aliased AFRH_Register; end record with Volatile; for GPIO_Peripheral use record MODER at 16#0# range 0 .. 31; OTYPER at 16#4# range 0 .. 31; OSPEEDR at 16#8# range 0 .. 31; PUPDR at 16#C# range 0 .. 31; IDR at 16#10# range 0 .. 31; ODR at 16#14# range 0 .. 31; BSRR at 16#18# range 0 .. 31; LCKR at 16#1C# range 0 .. 31; AFRL at 16#20# range 0 .. 31; AFRH at 16#24# range 0 .. 31; end record; -- GPIO GPIOA_Periph : aliased GPIO_Peripheral with Import, Address => GPIOA_Base; -- GPIO GPIOB_Periph : aliased GPIO_Peripheral with Import, Address => GPIOB_Base; -- GPIO GPIOC_Periph : aliased GPIO_Peripheral with Import, Address => GPIOC_Base; -- GPIO GPIOD_Periph : aliased GPIO_Peripheral with Import, Address => GPIOD_Base; -- GPIO GPIOE_Periph : aliased GPIO_Peripheral with Import, Address => GPIOE_Base; -- GPIO GPIOF_Periph : aliased GPIO_Peripheral with Import, Address => GPIOF_Base; -- GPIO GPIOG_Periph : aliased GPIO_Peripheral with Import, Address => GPIOG_Base; -- GPIO GPIOH_Periph : aliased GPIO_Peripheral with Import, Address => GPIOH_Base; -- GPIO GPIOI_Periph : aliased GPIO_Peripheral with Import, Address => GPIOI_Base; -- GPIO GPIOJ_Periph : aliased GPIO_Peripheral with Import, Address => GPIOJ_Base; -- GPIO GPIOK_Periph : aliased GPIO_Peripheral with Import, Address => GPIOK_Base; end STM32_SVD.GPIO;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2021, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with Ada.Unchecked_Conversion; with Interfaces; package body LPS25H.SPI is use HAL; -- SPI direction and multiplicity masks: 'or' these into the -- register to control the characteristics of the required -- transfer with the LPS25H. Read_Request : constant := 2#1000_0000#; Transfer_Multiples : constant := 2#0100_0000#; -- Utility specs -- generic Register : HAL.UInt8; type Register_Type is private; procedure Write_Register (This : LPS25H_Barometric_Sensor_SPI; Value : Register_Type; Status : out Boolean); procedure Write (This : LPS25H_Barometric_Sensor_SPI; Index : HAL.UInt8; Data : HAL.UInt8; Status : out Boolean); procedure Read (This : LPS25H_Barometric_Sensor_SPI; Index : HAL.UInt8; Data : out HAL.UInt8_Array; Status : out Boolean); procedure Read (This : LPS25H_Barometric_Sensor_SPI; Index : HAL.UInt8; Data : out HAL.UInt8; Status : out Boolean); -------------- -- Get_Data -- -------------- overriding procedure Get_Data (This : in out LPS25H_Barometric_Sensor_SPI; Press : out Pressure; Temp : out Temperature; Asl : out Altitude; Status : out Boolean) is Buf : HAL.UInt8_Array (0 .. 2) := (others => 0); begin -- Pressure declare type Integer_24 is range -(2 ** 23) .. 2 ** 23 - 1 with Size => 24; subtype Buffer_3 is HAL.UInt8_Array (Buf'Range); function Convert is new Ada.Unchecked_Conversion (Buffer_3, Integer_24); begin -- bit 6 => read multiple bytes This.Read (PRESS_OUT_XL or Transfer_Multiples, Buf, Status); if not Status then return; end if; Press := Float (Convert (Buf)) / 4096.0; end; -- Temperature declare subtype Buffer_2 is HAL.UInt8_Array (0 .. 1); function Convert is new Ada.Unchecked_Conversion (Buffer_2, Interfaces.Integer_16); begin -- bit 6 => read multiple bytes This.Read (TEMP_OUT_L or Transfer_Multiples, Buf (0 .. 1), Status); if not Status then return; end if; Temp := 42.5 + Float (Convert (Buf (0 .. 1))) / 480.0; end; -- See Wikipedia, "Barometric formula": The pressure drops -- approximately by 11.3 pascals per meter in first 1000 meters -- above sea level. -- See Wikipedia, "Atmospheric pressure": the standard atmosphere is -- 1013.25 mbar. -- 1 Pascal = 0.01 mbar Asl := (1013.25 - Press) * (100.0 / 11.3); end Get_Data; ---------------- -- Initialize -- ---------------- overriding procedure Initialize (This : in out LPS25H_Barometric_Sensor_SPI) is Data : UInt8; Status : Boolean; begin This.Timing.Delay_Milliseconds (5); -- ? This.Read (WHO_AM_I, Data, Status); if not Status then return; end if; if Data /= WAI_ID then return; end if; declare procedure Write_Ctrl_Reg1 is new Write_Register (CTRL_REG1, Ctrl_Reg1_Register); begin Write_Ctrl_Reg1 (This, (PD => 1, ODR => Hz_25, BDU => 1, others => <>), Status); if not Status then return; end if; end; This.Initialized := True; end Initialize; -- Utilities -- -------------------- -- Write_Register -- -------------------- procedure Write_Register (This : LPS25H_Barometric_Sensor_SPI; Value : Register_Type; Status : out Boolean) is pragma Assert (Register_Type'Size = 8); function Convert is new Ada.Unchecked_Conversion (Register_Type, HAL.UInt8); begin Write (This, Index => Register, Data => Convert (Value), Status => Status); end Write_Register; ----------- -- Write -- ----------- procedure Write (This : LPS25H_Barometric_Sensor_SPI; Index : HAL.UInt8; Data : HAL.UInt8; Status : out Boolean) is Outcome : HAL.SPI.SPI_Status; use all type HAL.SPI.SPI_Status; Buf : constant HAL.SPI.SPI_Data_8b := (Index, Data); begin This.CS.Clear; This.Port.Transmit (Data => Buf, Status => Outcome); Status := Outcome = Ok; This.CS.Set; end Write; ---------- -- Read -- ---------- procedure Read (This : LPS25H_Barometric_Sensor_SPI; Index : HAL.UInt8; Data : out HAL.UInt8_Array; Status : out Boolean) is Outcome : HAL.SPI.SPI_Status; Buf : HAL.SPI.SPI_Data_8b (Data'Range); use all type HAL.SPI.SPI_Status; begin This.CS.Clear; -- bit 7 => read This.Port.Transmit (Data => HAL.SPI.SPI_Data_8b'((1 => Index or Read_Request)), Status => Outcome); Status := Outcome = Ok; if Status then This.Port.Receive (Data => Buf, Status => Outcome); Status := Outcome = Ok; if Status then for J in Buf'Range loop Data (J) := Buf (J); end loop; end if; end if; This.CS.Set; end Read; ---------- -- Read -- ---------- procedure Read (This : LPS25H_Barometric_Sensor_SPI; Index : HAL.UInt8; Data : out HAL.UInt8; Status : out Boolean) is Buf : UInt8_Array (1 .. 1); begin This.Read (Index => Index, Data => Buf, Status => Status); if Status then Data := Buf (1); end if; end Read; end LPS25H.SPI;
with Ada.Text_IO; procedure Hello is begin Ada.Text_IO.Put_Line("Hello, world!"); end Hello;
-- -- Copyright (C) 2015-2016 secunet Security Networks AG -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- package HW.GFX.DP_Defs is type Aux_Message_Command is mod 2 ** 4; type Aux_Message_Address is mod 2 ** 20; subtype Aux_Payload_Length is Natural range 0 .. 16; subtype Aux_Payload_Index is Natural range 0 .. Aux_Payload_Length'Last - 1; subtype Aux_Payload is Buffer (Aux_Payload_Index); subtype Aux_Request_Length is Natural range 3 .. 20; subtype Aux_Request_Index is Natural range 0 .. Aux_Request_Length'Last - 1; subtype Aux_Request is Buffer (Aux_Request_Index); subtype Aux_Response_Length is Natural range 1 .. 17; subtype Aux_Response_Index is Natural range 0 .. Aux_Response_Length'Last - 1; subtype Aux_Response is Buffer (Aux_Response_Index); end HW.GFX.DP_Defs;
with Runge_8th; with Text_IO; use Text_IO; with Sinu; with Ada.Numerics.Generic_Elementary_Functions; procedure runge_8th_order_demo_1 is type Real is digits 15; package Sinusoid is new Sinu (Real); use Sinusoid; package Sin_Integrate is new Runge_8th (Real, Dyn_Index, Dynamical_Variable, F, "*", "+", "-", Norm); use Sin_Integrate; package math is new Ada.Numerics.Generic_Elementary_Functions(Real); use math; package rio is new Float_IO(Real); use rio; package iio is new Integer_IO(Step_Integer); use iio; Initial_Condition : Dynamical_Variable; Previous_Y, Final_Y : Dynamical_Variable; Previous_t, Final_t : Real; Final_Time : Real; Starting_Time : Real; Delta_t : Real; Steps : Step_Integer; begin new_line; put ("Test integrates an equation whose solution is Sin(t)."); new_line; put ("The equation is (d/dt)**2 (Y) = -Y. (Y = Sin(t) has a period of 2*Pi.)"); new_line(2); put ("Enter number of time steps (try 1024): "); get (Steps); new_line; put ("Every time the integration advances this number of steps, ERROR is printed."); new_line; -- choose initial conditions Initial_Condition(0) := 0.0; Initial_Condition(1) := 1.0; Starting_Time := 0.0; Final_Time := 64.0; Previous_Y := Initial_Condition; Previous_t := Starting_Time; Delta_t := Final_Time - Starting_Time; for i in 1..28 loop Final_t := Previous_t + Delta_t; Integrate (Final_State => Final_Y, -- the result (output). Final_Time => Final_t, -- integrate out to here (input). Initial_State => Previous_Y, -- input an initial condition (input). Initial_Time => Previous_t, -- start integrating here (input). No_Of_Steps => Steps); -- if no err control, use this no_of_steps Previous_Y := Final_Y; Previous_t := Final_t; -- Start over. --put ("Final value of numerically integrated sin: "); --put (Final_Y(0), Aft => 7); new_line; put ("Time = t ="); put (Final_t, Aft => 7); put (", Error = Sin(t)-Y = "); put (Sin (Final_t) - Final_Y(0), Aft => 7); end loop; new_line(2); put ("Total elapsed time is:"); put (Final_t / (2.0*3.14159265), Aft => 7); put (" in units of 2 pi."); end;
-- { dg-do compile } package body Iface2 is procedure change (This, That : Prot.Any_Future) is begin null; end; end Iface2;
----------------------------------------------------------------------- -- servlet-rest-tests - Unit tests for Servlet.Rest and Servlet.Core.Rest -- Copyright (C) 2016, 2017, 2020 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Log; with Util.Test_Caller; with Util.Measures; with EL.Contexts.Default; with Security.Permissions; with Servlet.Requests.Mockup; with Servlet.Responses.Mockup; with Servlet.Core.Rest; with Servlet.Rest.Definition; with Servlet.Rest.Operation; package body Servlet.Rest.Tests is package Caller is new Util.Test_Caller (Test, "Rest"); procedure Benchmark (Ctx : in Servlet.Core.Servlet_Registry; Title : in String; Method : in String; URI : in String); package Test_Permission is new Security.Permissions.Definition ("test-permission"); package API_Simple_Get is new Servlet.Rest.Operation (Handler => Simple_Get'Access, URI => "/simple/:id"); package API_Simple_List is new Servlet.Rest.Operation (Handler => Simple_Get'Access, URI => "/simple"); package API_Simple_Post is new Servlet.Rest.Operation (Handler => Simple_Post'Access, URI => "/simple", Method => Servlet.Rest.POST); package API_Simple_Delete is new Servlet.Rest.Operation (Handler => Simple_Delete'Access, URI => "/simple/:id", Method => Servlet.Rest.DELETE); package API_Simple_Put is new Servlet.Rest.Operation (Handler => Simple_Put'Access, URI => "/simple/:id", Method => Servlet.Rest.PUT); package API_Simple_Head is new Servlet.Rest.Operation (Handler => Simple_Head'Access, URI => "/simple/:id", Method => Servlet.Rest.HEAD); package API_Simple_Options is new Servlet.Rest.Operation (Handler => Simple_Options'Access, URI => "/simple/:id", Method => Servlet.Rest.OPTIONS); package API_Simple_Patch is new Servlet.Rest.Operation (Handler => Simple_Patch'Access, URI => "/simple/:id", Method => Servlet.Rest.PATCH); package Test_API_Definition is new Servlet.Rest.Definition (Object_Type => Test_API, URI => "/test"); package API_Create is new Test_API_Definition.Definition (Handler => Create'Access, Method => Servlet.Rest.POST, Pattern => "", Permission => Test_Permission.Permission) with Unreferenced; package API_Update is new Test_API_Definition.Definition (Handler => Update'Access, Method => Servlet.Rest.PUT, Pattern => ":id", Permission => 0) with Unreferenced; package API_Delete is new Test_API_Definition.Definition (Handler => Delete'Access, Method => Servlet.Rest.DELETE, Pattern => ":id", Permission => 0) with Unreferenced; package API_List is new Test_API_Definition.Definition (Handler => List'Access, Method => Servlet.Rest.GET, Pattern => "", Permission => 0) with Unreferenced; package API_Get is new Test_API_Definition.Definition (Handler => List'Access, Method => Servlet.Rest.GET, Pattern => ":id", Permission => 0) with Unreferenced; package API_Head is new Test_API_Definition.Definition (Handler => Head'Access, Method => Servlet.Rest.HEAD, Pattern => ":id", Permission => 0) with Unreferenced; package API_Options is new Test_API_Definition.Definition (Handler => Options'Access, Method => Servlet.Rest.OPTIONS, Pattern => ":id", Permission => 0) with Unreferenced; package API_Patch is new Test_API_Definition.Definition (Handler => Patch'Access, Method => Servlet.Rest.PATCH, Pattern => ":id", Permission => 0) with Unreferenced; procedure Simple_Get (Req : in out Servlet.Rest.Request'Class; Reply : in out Servlet.Rest.Response'Class; Stream : in out Servlet.Rest.Output_Stream'Class) is Data : Test_API; begin List (Data, Req, Reply, Stream); end Simple_Get; procedure Simple_Put (Req : in out Servlet.Rest.Request'Class; Reply : in out Servlet.Rest.Response'Class; Stream : in out Servlet.Rest.Output_Stream'Class) is Data : Test_API; begin Update (Data, Req, Reply, Stream); end Simple_Put; procedure Simple_Post (Req : in out Servlet.Rest.Request'Class; Reply : in out Servlet.Rest.Response'Class; Stream : in out Servlet.Rest.Output_Stream'Class) is Data : Test_API; begin Create (Data, Req, Reply, Stream); end Simple_Post; procedure Simple_Delete (Req : in out Servlet.Rest.Request'Class; Reply : in out Servlet.Rest.Response'Class; Stream : in out Servlet.Rest.Output_Stream'Class) is Data : Test_API; begin Delete (Data, Req, Reply, Stream); end Simple_Delete; procedure Simple_Head (Req : in out Servlet.Rest.Request'Class; Reply : in out Servlet.Rest.Response'Class; Stream : in out Servlet.Rest.Output_Stream'Class) is Data : Test_API; begin Head (Data, Req, Reply, Stream); end Simple_Head; procedure Simple_Options (Req : in out Servlet.Rest.Request'Class; Reply : in out Servlet.Rest.Response'Class; Stream : in out Servlet.Rest.Output_Stream'Class) is Data : Test_API; begin Options (Data, Req, Reply, Stream); end Simple_Options; procedure Simple_Patch (Req : in out Servlet.Rest.Request'Class; Reply : in out Servlet.Rest.Response'Class; Stream : in out Servlet.Rest.Output_Stream'Class) is Data : Test_API; begin Patch (Data, Req, Reply, Stream); end Simple_Patch; procedure Create (Data : in out Test_API; Req : in out Servlet.Rest.Request'Class; Reply : in out Servlet.Rest.Response'Class; Stream : in out Servlet.Rest.Output_Stream'Class) is pragma Unreferenced (Data, Req, Stream); begin Reply.Set_Status (Servlet.Responses.SC_CREATED); -- Servlet.Rest.Created (Reply, "23"); Reply.Set_Header (Name => "Location", Value => "/test/23"); end Create; procedure Update (Data : in out Test_API; Req : in out Servlet.Rest.Request'Class; Reply : in out Servlet.Rest.Response'Class; Stream : in out Servlet.Rest.Output_Stream'Class) is pragma Unreferenced (Data, Stream); Id : constant String := Req.Get_Path_Parameter (1); begin if Id'Length > 0 then Reply.Set_Status (Servlet.Responses.SC_OK); else Reply.Set_Status (Servlet.Responses.SC_NOT_FOUND); end if; end Update; procedure Delete (Data : in out Test_API; Req : in out Servlet.Rest.Request'Class; Reply : in out Servlet.Rest.Response'Class; Stream : in out Servlet.Rest.Output_Stream'Class) is pragma Unreferenced (Data, Req, Stream); begin Reply.Set_Status (Servlet.Responses.SC_NO_CONTENT); end Delete; procedure Head (Data : in out Test_API; Req : in out Servlet.Rest.Request'Class; Reply : in out Servlet.Rest.Response'Class; Stream : in out Servlet.Rest.Output_Stream'Class) is pragma Unreferenced (Data, Req, Stream); begin Reply.Set_Status (Servlet.Responses.SC_GONE); end Head; procedure Patch (Data : in out Test_API; Req : in out Servlet.Rest.Request'Class; Reply : in out Servlet.Rest.Response'Class; Stream : in out Servlet.Rest.Output_Stream'Class) is pragma Unreferenced (Data, Req, Stream); begin Reply.Set_Status (Servlet.Responses.SC_ACCEPTED); end Patch; procedure List (Data : in out Test_API; Req : in out Servlet.Rest.Request'Class; Reply : in out Servlet.Rest.Response'Class; Stream : in out Servlet.Rest.Output_Stream'Class) is pragma Unreferenced (Data); begin if Req.Get_Path_Parameter_Count = 0 then Stream.Start_Document; Stream.Start_Array ("list"); for I in 1 .. 10 loop Stream.Start_Entity ("item"); Stream.Write_Attribute ("id", I); Stream.Write_Attribute ("name", "Item " & Natural'Image (I)); Stream.End_Entity ("item"); end loop; Stream.End_Array ("list"); Stream.End_Document; else declare Id : constant String := Req.Get_Path_Parameter (1); begin if Id = "100" then Reply.Set_Status (Servlet.Responses.SC_NOT_FOUND); elsif Id /= "44" then Reply.Set_Status (Servlet.Responses.SC_GONE); end if; end; end if; end List; procedure Options (Data : in out Test_API; Req : in out Servlet.Rest.Request'Class; Reply : in out Servlet.Rest.Response'Class; Stream : in out Servlet.Rest.Output_Stream'Class) is pragma Unreferenced (Data, Req, Stream); begin Reply.Set_Status (Servlet.Responses.SC_OK); Reply.Set_Header (Name => "Allow", Value => "OPTIONS, GET, POST, PUT, DELETE, PATCH"); end Options; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Servlet.Rest.POST API operation", Test_Create'Access); Caller.Add_Test (Suite, "Test Servlet.Rest.GET API operation", Test_Get'Access); Caller.Add_Test (Suite, "Test Servlet.Rest.PUT API operation", Test_Update'Access); Caller.Add_Test (Suite, "Test Servlet.Rest.DELETE API operation", Test_Delete'Access); Caller.Add_Test (Suite, "Test Servlet.Rest.HEAD API operation", Test_Head'Access); Caller.Add_Test (Suite, "Test Servlet.Rest.TRACE API operation", Test_Invalid'Access); Caller.Add_Test (Suite, "Test Servlet.Rest.OPTIONS API operation", Test_Options'Access); Caller.Add_Test (Suite, "Test Servlet.Rest.PATCH API operation", Test_Patch'Access); end Add_Tests; procedure Benchmark (Ctx : in Servlet.Core.Servlet_Registry; Title : in String; Method : in String; URI : in String) is T : Util.Measures.Stamp; begin for I in 1 .. 1000 loop declare Request : Servlet.Requests.Mockup.Request; Reply : Servlet.Responses.Mockup.Response; Dispatcher : constant Servlet.Core.Request_Dispatcher := Ctx.Get_Request_Dispatcher (Path => URI); begin Request.Set_Method (Method); Request.Set_Request_URI (URI); Servlet.Core.Forward (Dispatcher, Request, Reply); end; end loop; Util.Measures.Report (T, Title, 1000); end Benchmark; procedure Test_Operation (T : in out Test; Method : in String; URI : in String; Status : in Natural) is use Servlet.Core; use Util.Tests; Ctx : Servlet_Registry; S1 : aliased Servlet.Core.Rest.Rest_Servlet; EL_Ctx : EL.Contexts.Default.Default_Context; Request : Servlet.Requests.Mockup.Request; Reply : Servlet.Responses.Mockup.Response; begin Ctx.Add_Servlet ("API", S1'Unchecked_Access); Ctx.Add_Mapping (Name => "API", Pattern => "/simple/*"); Ctx.Start; Ctx.Dump_Routes (Util.Log.INFO_LEVEL); Servlet.Rest.Register (Ctx, API_Simple_Get.Definition); Servlet.Rest.Register (Ctx, API_Simple_List.Definition); Servlet.Rest.Register (Ctx, API_Simple_Post.Definition); Servlet.Rest.Register (Ctx, API_Simple_Put.Definition); Servlet.Rest.Register (Ctx, API_Simple_Delete.Definition); Servlet.Rest.Register (Ctx, API_Simple_Head.Definition); Servlet.Rest.Register (Ctx, API_Simple_Options.Definition); Servlet.Rest.Register (Ctx, API_Simple_Patch.Definition); Ctx.Dump_Routes (Util.Log.INFO_LEVEL); Test_API_Definition.Register (Registry => Ctx, Name => "API", ELContext => EL_Ctx); Request.Set_Method (Method); declare Dispatcher : constant Request_Dispatcher := Ctx.Get_Request_Dispatcher (Path => URI); Result : Ada.Strings.Unbounded.Unbounded_String; begin Request.Set_Request_URI (URI); Forward (Dispatcher, Request, Reply); -- Check the response after the API method execution. Reply.Read_Content (Result); Assert_Equals (T, Status, Reply.Get_Status, "Invalid status for " & Method & ":" & URI); end; Benchmark (Ctx, Method & " " & URI, Method, URI); end Test_Operation; -- ------------------------------ -- Test REST POST create operation -- ------------------------------ procedure Test_Create (T : in out Test) is begin Test_Operation (T, "POST", "/test", Servlet.Responses.SC_CREATED); Test_Operation (T, "POST", "/simple", Servlet.Responses.SC_CREATED); end Test_Create; -- ------------------------------ -- Test REST PUT update operation -- ------------------------------ procedure Test_Update (T : in out Test) is begin Test_Operation (T, "PUT", "/test/44", Servlet.Responses.SC_OK); Test_Operation (T, "PUT", "/simple/44", Servlet.Responses.SC_OK); end Test_Update; -- ------------------------------ -- Test REST GET operation -- ------------------------------ procedure Test_Get (T : in out Test) is begin Test_Operation (T, "GET", "/test", Servlet.Responses.SC_OK); Test_Operation (T, "GET", "/test/44", Servlet.Responses.SC_OK); Test_Operation (T, "GET", "/test/100", Servlet.Responses.SC_NOT_FOUND); Test_Operation (T, "GET", "/simple", Servlet.Responses.SC_OK); Test_Operation (T, "GET", "/simple/44", Servlet.Responses.SC_OK); Test_Operation (T, "GET", "/simple/100", Servlet.Responses.SC_NOT_FOUND); end Test_Get; -- ------------------------------ -- Test REST DELETE delete operation -- ------------------------------ procedure Test_Delete (T : in out Test) is begin Test_Operation (T, "DELETE", "/test/44", Servlet.Responses.SC_NO_CONTENT); Test_Operation (T, "DELETE", "/simple/44", Servlet.Responses.SC_NO_CONTENT); end Test_Delete; -- ------------------------------ -- Test REST HEAD operation -- ------------------------------ procedure Test_Head (T : in out Test) is begin Test_Operation (T, "HEAD", "/test/44", Servlet.Responses.SC_GONE); Test_Operation (T, "HEAD", "/simple/44", Servlet.Responses.SC_GONE); end Test_Head; -- ------------------------------ -- Test REST OPTIONS operation -- ------------------------------ procedure Test_Options (T : in out Test) is begin Test_Operation (T, "OPTIONS", "/test/44", Servlet.Responses.SC_OK); Test_Operation (T, "OPTIONS", "/simple/44", Servlet.Responses.SC_OK); end Test_Options; -- ------------------------------ -- Test REST PATCH operation -- ------------------------------ procedure Test_Patch (T : in out Test) is begin Test_Operation (T, "PATCH", "/test/44", Servlet.Responses.SC_ACCEPTED); Test_Operation (T, "PATCH", "/simple/44", Servlet.Responses.SC_ACCEPTED); end Test_Patch; -- ------------------------------ -- Test REST operation on invalid operation. -- ------------------------------ procedure Test_Invalid (T : in out Test) is begin Test_Operation (T, "TRACE", "/test/44", Servlet.Responses.SC_NOT_FOUND); Test_Operation (T, "TRACE", "/simple/44", Servlet.Responses.SC_NOT_FOUND); end Test_Invalid; end Servlet.Rest.Tests;
with SDL_Display; package body Render is Width : constant := 320; Height : constant := 240; package Display is new SDL_Display (Width => Width, Height => Height, Pixel_Scale => 4, Buffer_Size => 320 * 240); Screen_Pt : GESTE.Pix_Point := (0, 0); ----------------- -- Push_Pixels -- ----------------- procedure Push_Pixels (Buffer : GESTE.Output_Buffer) renames Display.Push_Pixels; ---------------------- -- Set_Drawing_Area -- ---------------------- procedure Set_Drawing_Area (Area : GESTE.Pix_Rect) renames Display.Set_Drawing_Area; ----------------------- -- Set_Screen_Offset -- ----------------------- procedure Set_Screen_Offset (Pt : GESTE.Pix_Point) is begin Display.Set_Screen_Offset (Pt); Screen_Pt := Pt; end Set_Screen_Offset; ---------------- -- Render_All -- ---------------- procedure Render_All (Background : GESTE_Config.Output_Color) is begin GESTE.Render_All ((Screen_Pt, (Screen_Pt.X + Width - 1, Screen_Pt.Y + Height - 1)), Background, Display.Buffer, Display.Push_Pixels'Access, Display.Set_Drawing_Area'Access); end Render_All; ------------------ -- Render_Dirty -- ------------------ procedure Render_Dirty (Background : GESTE_Config.Output_Color) is begin GESTE.Render_Dirty ((Screen_Pt, (Screen_Pt.X + Width - 1, Screen_Pt.Y + Height - 1)), Background, Display.Buffer, Display.Push_Pixels'Access, Display.Set_Drawing_Area'Access); end Render_Dirty; --------------- -- Dark_Cyan -- --------------- function Dark_Cyan return GESTE_Config.Output_Color is (Display.To_SDL_Color (176, 226, 255)); ----------- -- Black -- ----------- function Black return GESTE_Config.Output_Color is (Display.To_SDL_Color (0, 0, 0)); end Render;
-- This spec has been automatically generated from STM32L4x6.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with HAL; with System; package STM32_SVD.LCD is pragma Preelaborate; --------------- -- Registers -- --------------- subtype CR_DUTY_Field is HAL.UInt3; subtype CR_BIAS_Field is HAL.UInt2; -- control register type CR_Register is record -- LCD controller enable LCDEN : Boolean := False; -- Voltage source selection VSEL : Boolean := False; -- Duty selection DUTY : CR_DUTY_Field := 16#0#; -- Bias selector BIAS : CR_BIAS_Field := 16#0#; -- Mux segment enable MUX_SEG : Boolean := False; -- Voltage output buffer enable BUFEN : Boolean := False; -- unspecified Reserved_9_31 : HAL.UInt23 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CR_Register use record LCDEN at 0 range 0 .. 0; VSEL at 0 range 1 .. 1; DUTY at 0 range 2 .. 4; BIAS at 0 range 5 .. 6; MUX_SEG at 0 range 7 .. 7; BUFEN at 0 range 8 .. 8; Reserved_9_31 at 0 range 9 .. 31; end record; subtype FCR_PON_Field is HAL.UInt3; subtype FCR_DEAD_Field is HAL.UInt3; subtype FCR_CC_Field is HAL.UInt3; subtype FCR_BLINKF_Field is HAL.UInt3; subtype FCR_BLINK_Field is HAL.UInt2; subtype FCR_DIV_Field is HAL.UInt4; subtype FCR_PS_Field is HAL.UInt4; -- frame control register type FCR_Register is record -- High drive enable HD : Boolean := False; -- Start of frame interrupt enable SOFIE : Boolean := False; -- unspecified Reserved_2_2 : HAL.Bit := 16#0#; -- Update display done interrupt enable UDDIE : Boolean := False; -- Pulse ON duration PON : FCR_PON_Field := 16#0#; -- Dead time duration DEAD : FCR_DEAD_Field := 16#0#; -- Contrast control CC : FCR_CC_Field := 16#0#; -- Blink frequency selection BLINKF : FCR_BLINKF_Field := 16#0#; -- Blink mode selection BLINK : FCR_BLINK_Field := 16#0#; -- DIV clock divider DIV : FCR_DIV_Field := 16#0#; -- PS 16-bit prescaler PS : FCR_PS_Field := 16#0#; -- unspecified Reserved_26_31 : HAL.UInt6 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for FCR_Register use record HD at 0 range 0 .. 0; SOFIE at 0 range 1 .. 1; Reserved_2_2 at 0 range 2 .. 2; UDDIE at 0 range 3 .. 3; PON at 0 range 4 .. 6; DEAD at 0 range 7 .. 9; CC at 0 range 10 .. 12; BLINKF at 0 range 13 .. 15; BLINK at 0 range 16 .. 17; DIV at 0 range 18 .. 21; PS at 0 range 22 .. 25; Reserved_26_31 at 0 range 26 .. 31; end record; -- status register type SR_Register is record -- Read-only. ENS ENS : Boolean := False; -- Read-only. Start of frame flag SOF : Boolean := False; -- Write-only. Update display request UDR : Boolean := False; -- Read-only. Update Display Done UDD : Boolean := False; -- Read-only. Ready flag RDY : Boolean := False; -- Read-only. LCD Frame Control Register Synchronization flag FCRSF : Boolean := True; -- unspecified Reserved_6_31 : HAL.UInt26 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for SR_Register use record ENS at 0 range 0 .. 0; SOF at 0 range 1 .. 1; UDR at 0 range 2 .. 2; UDD at 0 range 3 .. 3; RDY at 0 range 4 .. 4; FCRSF at 0 range 5 .. 5; Reserved_6_31 at 0 range 6 .. 31; end record; -- clear register type CLR_Register is record -- unspecified Reserved_0_0 : HAL.Bit := 16#0#; -- Write-only. Start of frame flag clear SOFC : Boolean := False; -- unspecified Reserved_2_2 : HAL.Bit := 16#0#; -- Write-only. Update display done clear UDDC : Boolean := False; -- unspecified Reserved_4_31 : HAL.UInt28 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CLR_Register use record Reserved_0_0 at 0 range 0 .. 0; SOFC at 0 range 1 .. 1; Reserved_2_2 at 0 range 2 .. 2; UDDC at 0 range 3 .. 3; Reserved_4_31 at 0 range 4 .. 31; end record; -- RAM_COM0_S array type RAM_COM0_S_Field_Array is array (0 .. 30) of Boolean with Component_Size => 1, Size => 31; -- Type definition for RAM_COM0_S type RAM_COM0_S_Field (As_Array : Boolean := False) is record case As_Array is when False => -- S as a value Val : HAL.UInt31; when True => -- S as an array Arr : RAM_COM0_S_Field_Array; end case; end record with Unchecked_Union, Size => 31; for RAM_COM0_S_Field use record Val at 0 range 0 .. 30; Arr at 0 range 0 .. 30; end record; -- display memory type RAM_COM0_Register is record -- S00 S : RAM_COM0_S_Field := (As_Array => False, Val => 16#0#); -- unspecified Reserved_31_31 : HAL.Bit := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for RAM_COM0_Register use record S at 0 range 0 .. 30; Reserved_31_31 at 0 range 31 .. 31; end record; -- RAM_COM_S array type RAM_COM_S_Field_Array is array (0 .. 31) of Boolean with Component_Size => 1, Size => 32; -- display memory type RAM_COM_Register (As_Array : Boolean := False) is record case As_Array is when False => -- S as a value Val : HAL.UInt32; when True => -- S as an array Arr : RAM_COM_S_Field_Array; end case; end record with Unchecked_Union, Size => 32, Volatile_Full_Access, Bit_Order => System.Low_Order_First; for RAM_COM_Register use record Val at 0 range 0 .. 31; Arr at 0 range 0 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- Liquid crystal display controller type LCD_Peripheral is record -- control register CR : aliased CR_Register; -- frame control register FCR : aliased FCR_Register; -- status register SR : aliased SR_Register; -- clear register CLR : aliased CLR_Register; -- display memory RAM_COM0 : aliased RAM_COM0_Register; -- display memory RAM_COM1 : aliased RAM_COM_Register; -- display memory RAM_COM2 : aliased RAM_COM_Register; -- display memory RAM_COM3 : aliased RAM_COM_Register; -- display memory RAM_COM4 : aliased RAM_COM_Register; -- display memory RAM_COM5 : aliased RAM_COM_Register; -- display memory RAM_COM6 : aliased RAM_COM_Register; -- display memory RAM_COM7 : aliased RAM_COM_Register; end record with Volatile; for LCD_Peripheral use record CR at 16#0# range 0 .. 31; FCR at 16#4# range 0 .. 31; SR at 16#8# range 0 .. 31; CLR at 16#C# range 0 .. 31; RAM_COM0 at 16#14# range 0 .. 31; RAM_COM1 at 16#1C# range 0 .. 31; RAM_COM2 at 16#24# range 0 .. 31; RAM_COM3 at 16#2C# range 0 .. 31; RAM_COM4 at 16#34# range 0 .. 31; RAM_COM5 at 16#3C# range 0 .. 31; RAM_COM6 at 16#44# range 0 .. 31; RAM_COM7 at 16#4C# range 0 .. 31; end record; -- Liquid crystal display controller LCD_Periph : aliased LCD_Peripheral with Import, Address => System'To_Address (16#40002400#); end STM32_SVD.LCD;
with Memory.RAM; use Memory.RAM; package body Test.RAM is procedure Run_Tests is mem : RAM_Pointer := Create_RAM(latency => 100, burst => 1, word_size => 4, word_count => 8); other : Memory_Pointer := null; begin Check(Get_Time(mem.all) = 0); Check(Get_Writes(mem.all) = 0); Check(Get_Cost(mem.all) = 0); Read(mem.all, 0, 4); Check(Get_Time(mem.all) = 100); Check(Get_Writes(mem.all) = 0); Read(mem.all, 2, 4); Check(Get_Time(mem.all) = 201); Check(Get_Writes(mem.all) = 0); Read(mem.all, 2, 2); Check(Get_Time(mem.all) = 301); Check(Get_Writes(mem.all) = 0); Read(mem.all, 2, 3); Check(Get_Time(mem.all) = 402); Check(Get_Writes(mem.all) = 0); Write(mem.all, 1, 8); Check(Get_Time(mem.all) = 504); Check(Get_Writes(mem.all) = 1); Reset(mem.all, 0); Check(Get_Time(mem.all) = 0); Check(To_String(mem.all) = "(ram (latency 100)(burst 1)(word_size 4)(word_count 8))"); other := Clone(mem.all); Check(To_String(other.all) = To_String(mem.all)); Destroy(Memory_Pointer(mem)); Destroy(Memory_Pointer(other)); end Run_Tests; end Test.RAM;
with CSS.Core.Sheets; package CSS.Parser.Parser is Error_Count : Natural := 0; function Parse (Content : in String; Document : in CSS.Core.Sheets.CSSStylesheet_Access) return Integer; -- Set or clear the parser debug flag. -- procedure Set_Debug (Flag : in Boolean); end CSS.Parser.Parser;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- A U N I T . T E S T _ C A S E S -- -- -- -- S p e c -- -- -- -- -- -- Copyright (C) 2000-2011, AdaCore -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- -- -- -- -- -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT is maintained by AdaCore (http://www.adacore.com) -- -- -- ------------------------------------------------------------------------------ with Ada_Containers; use Ada_Containers; with Ada_Containers.AUnit_Lists; with AUnit.Options; with AUnit.Simple_Test_Cases; with AUnit.Test_Results; use AUnit.Test_Results; -- Test case: a collection of test routines package AUnit.Test_Cases is type Test_Case is abstract new AUnit.Simple_Test_Cases.Test_Case with private; type Test_Case_Access is access all Test_Case'Class; type Test_Routine is access procedure (Test : in out Test_Case'Class); type Routine_Spec is record Routine : Test_Routine; Routine_Name : Message_String; end record; procedure Add_Routine (T : in out Test_Case'Class; Val : Routine_Spec); procedure Register_Tests (Test : in out Test_Case) is abstract; -- Register test methods with test suite procedure Set_Up_Case (Test : in out Test_Case); -- Set up performed before each test case (set of test routines) procedure Tear_Down_Case (Test : in out Test_Case); -- Tear down performed after each test case package Registration is procedure Register_Routine (Test : in out Test_Case'Class; Routine : Test_Routine; Name : String); -- Add test routine to test case function Routine_Count (Test : Test_Case'Class) return Count_Type; -- Count of registered routines in test case end Registration; generic type Specific_Test_Case is abstract new Test_Case with private; package Specific_Test_Case_Registration is -- Specific Test Case registration type Specific_Test_Routine is access procedure (Test : in out Specific_Test_Case'Class); procedure Register_Wrapper (Test : in out Specific_Test_Case'Class; Routine : Specific_Test_Routine; Name : String); -- Add test routine for a specific test case end Specific_Test_Case_Registration; procedure Run (Test : access Test_Case; Options : AUnit.Options.AUnit_Options; R : in out Result'Class; Outcome : out Status); -- Run test case. Do not override. procedure Run_Test (Test : in out Test_Case); -- Perform the current test procedure. Do not override. function Routine_Name (Test : Test_Case) return Message_String; -- Routine name. Returns the routine under test. Do not override. private type Routine_Access is access all Routine_Spec; -- Test routine description package Routine_Lists is new Ada_Containers.AUnit_Lists (Routine_Spec); -- Container for test routines package Failure_Lists is new Ada_Containers.AUnit_Lists (Message_String); -- Container for failed assertion messages per routine type Test_Case is abstract new AUnit.Simple_Test_Cases.Test_Case with record Routines : aliased Routine_Lists.List; Routine : Routine_Spec; end record; end AUnit.Test_Cases;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Ada.Text_IO.Text_Streams; package body File_Operations.Heap is package TIO renames Ada.Text_IO; package STR renames Ada.Text_IO.Text_Streams; procedure slurp_file (dossier : String) is begin file_contents := new HM_File_String; if File_Size = 0 then return; end if; declare handle : TIO.File_Type; attempts : Natural := 0; begin -- The introduction of variants causes a buildsheet to be scanned once per variant. -- It's possible (even common) for simultaneous requests to scan the same buildsheet to -- occur. Thus, if the file is already open, wait and try again (up to 5 times) loop begin TIO.Open (handle, TIO.In_File, dossier); exit; exception when TIO.Use_Error | TIO.Status_Error => if attempts = 5 then raise file_handling with "slurp_file: failed open: " & dossier; end if; attempts := attempts + 1; delay 0.1; end; end loop; for arrow in file_contents'Range loop file_contents (arrow) := Character'Input (STR.Stream (handle)); end loop; TIO.Close (handle); exception when others => if TIO.Is_Open (handle) then TIO.Close (handle); end if; raise file_handling with "slurp_file(" & dossier & ") failed"; end; exception when Storage_Error => raise file_handling with "slurp_file: failed to allocate memory on heap"; end slurp_file; end File_Operations.Heap;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- S E M -- -- -- -- 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 Debug; use Debug; with Debug_A; use Debug_A; with Elists; use Elists; with Exp_SPARK; use Exp_SPARK; with Expander; use Expander; with Ghost; use Ghost; with Lib; use Lib; with Lib.Load; use Lib.Load; with Nlists; use Nlists; with Output; use Output; with Restrict; use Restrict; with Sem_Attr; use Sem_Attr; with Sem_Ch2; use Sem_Ch2; with Sem_Ch3; use Sem_Ch3; with Sem_Ch4; use Sem_Ch4; with Sem_Ch5; use Sem_Ch5; with Sem_Ch6; use Sem_Ch6; with Sem_Ch7; use Sem_Ch7; with Sem_Ch8; use Sem_Ch8; with Sem_Ch9; use Sem_Ch9; with Sem_Ch10; use Sem_Ch10; with Sem_Ch11; use Sem_Ch11; with Sem_Ch12; use Sem_Ch12; with Sem_Ch13; use Sem_Ch13; with Sem_Prag; use Sem_Prag; with Sem_Util; use Sem_Util; with Sinfo; use Sinfo; with Stand; use Stand; with Stylesw; use Stylesw; with Uintp; use Uintp; with Uname; use Uname; with Unchecked_Deallocation; pragma Warnings (Off, Sem_Util); -- Suppress warnings of unused with for Sem_Util (used only in asserts) package body Sem is Debug_Unit_Walk : Boolean renames Debug_Flag_Dot_WW; -- Controls debugging printouts for Walk_Library_Items Outer_Generic_Scope : Entity_Id := Empty; -- Global reference to the outer scope that is generic. In a non-generic -- context, it is empty. At the moment, it is only used for avoiding -- freezing of external references in generics. Comp_Unit_List : Elist_Id := No_Elist; -- Used by Walk_Library_Items. This is a list of N_Compilation_Unit nodes -- processed by Semantics, in an appropriate order. Initialized to -- No_Elist, because it's too early to call New_Elmt_List; we will set it -- to New_Elmt_List on first use. generic with procedure Action (Withed_Unit : Node_Id); procedure Walk_Withs_Immediate (CU : Node_Id; Include_Limited : Boolean); -- Walk all the with clauses of CU, and call Action for the with'ed unit. -- Ignore limited withs, unless Include_Limited is True. CU must be an -- N_Compilation_Unit. generic with procedure Action (Withed_Unit : Node_Id); procedure Walk_Withs (CU : Node_Id; Include_Limited : Boolean); -- Same as Walk_Withs_Immediate, but also include with clauses on subunits -- of this unit, since they count as dependences on their parent library -- item. CU must be an N_Compilation_Unit whose Unit is not an N_Subunit. ------------- -- Analyze -- ------------- -- WARNING: This routine manages Ghost regions. Return statements must be -- replaced by gotos which jump to the end of the routine and restore the -- Ghost mode. procedure Analyze (N : Node_Id) is Saved_GM : constant Ghost_Mode_Type := Ghost_Mode; Saved_IGR : constant Node_Id := Ignored_Ghost_Region; -- Save the Ghost-related attributes to restore on exit begin Debug_A_Entry ("analyzing ", N); -- Immediate return if already analyzed if Analyzed (N) then Debug_A_Exit ("analyzing ", N, " (done, analyzed already)"); return; end if; -- A declaration may be subject to pragma Ghost. Set the mode now to -- ensure that any nodes generated during analysis and expansion are -- marked as Ghost. if Is_Declaration (N) then Mark_And_Set_Ghost_Declaration (N); end if; -- Otherwise processing depends on the node kind case Nkind (N) is when N_Abort_Statement => Analyze_Abort_Statement (N); when N_Abstract_Subprogram_Declaration => Analyze_Abstract_Subprogram_Declaration (N); when N_Accept_Alternative => Analyze_Accept_Alternative (N); when N_Accept_Statement => Analyze_Accept_Statement (N); when N_Aggregate => Analyze_Aggregate (N); when N_Allocator => Analyze_Allocator (N); when N_And_Then => Analyze_Short_Circuit (N); when N_Assignment_Statement => Analyze_Assignment (N); when N_Asynchronous_Select => Analyze_Asynchronous_Select (N); when N_At_Clause => Analyze_At_Clause (N); when N_Attribute_Reference => Analyze_Attribute (N); when N_Attribute_Definition_Clause => Analyze_Attribute_Definition_Clause (N); when N_Block_Statement => Analyze_Block_Statement (N); when N_Case_Expression => Analyze_Case_Expression (N); when N_Case_Statement => Analyze_Case_Statement (N); when N_Character_Literal => Analyze_Character_Literal (N); when N_Code_Statement => Analyze_Code_Statement (N); when N_Compilation_Unit => Analyze_Compilation_Unit (N); when N_Component_Declaration => Analyze_Component_Declaration (N); when N_Compound_Statement => Analyze_Compound_Statement (N); when N_Conditional_Entry_Call => Analyze_Conditional_Entry_Call (N); when N_Delay_Alternative => Analyze_Delay_Alternative (N); when N_Delay_Relative_Statement => Analyze_Delay_Relative (N); when N_Delay_Until_Statement => Analyze_Delay_Until (N); when N_Delta_Aggregate => Analyze_Aggregate (N); when N_Entry_Body => Analyze_Entry_Body (N); when N_Entry_Body_Formal_Part => Analyze_Entry_Body_Formal_Part (N); when N_Entry_Call_Alternative => Analyze_Entry_Call_Alternative (N); when N_Entry_Declaration => Analyze_Entry_Declaration (N); when N_Entry_Index_Specification => Analyze_Entry_Index_Specification (N); when N_Enumeration_Representation_Clause => Analyze_Enumeration_Representation_Clause (N); when N_Exception_Declaration => Analyze_Exception_Declaration (N); when N_Exception_Renaming_Declaration => Analyze_Exception_Renaming (N); when N_Exit_Statement => Analyze_Exit_Statement (N); when N_Expanded_Name => Analyze_Expanded_Name (N); when N_Explicit_Dereference => Analyze_Explicit_Dereference (N); when N_Expression_Function => Analyze_Expression_Function (N); when N_Expression_With_Actions => Analyze_Expression_With_Actions (N); when N_Extended_Return_Statement => Analyze_Extended_Return_Statement (N); when N_Extension_Aggregate => Analyze_Aggregate (N); when N_Formal_Object_Declaration => Analyze_Formal_Object_Declaration (N); when N_Formal_Package_Declaration => Analyze_Formal_Package_Declaration (N); when N_Formal_Subprogram_Declaration => Analyze_Formal_Subprogram_Declaration (N); when N_Formal_Type_Declaration => Analyze_Formal_Type_Declaration (N); when N_Free_Statement => Analyze_Free_Statement (N); when N_Freeze_Entity => Analyze_Freeze_Entity (N); when N_Freeze_Generic_Entity => Analyze_Freeze_Generic_Entity (N); when N_Full_Type_Declaration => Analyze_Full_Type_Declaration (N); when N_Function_Call => Analyze_Function_Call (N); when N_Function_Instantiation => Analyze_Function_Instantiation (N); when N_Generic_Function_Renaming_Declaration => Analyze_Generic_Function_Renaming (N); when N_Generic_Package_Declaration => Analyze_Generic_Package_Declaration (N); when N_Generic_Package_Renaming_Declaration => Analyze_Generic_Package_Renaming (N); when N_Generic_Procedure_Renaming_Declaration => Analyze_Generic_Procedure_Renaming (N); when N_Generic_Subprogram_Declaration => Analyze_Generic_Subprogram_Declaration (N); when N_Goto_Statement => Analyze_Goto_Statement (N); when N_Handled_Sequence_Of_Statements => Analyze_Handled_Statements (N); when N_Identifier => Analyze_Identifier (N); when N_If_Expression => Analyze_If_Expression (N); when N_If_Statement => Analyze_If_Statement (N); when N_Implicit_Label_Declaration => Analyze_Implicit_Label_Declaration (N); when N_In => Analyze_Membership_Op (N); when N_Incomplete_Type_Declaration => Analyze_Incomplete_Type_Decl (N); when N_Indexed_Component => Analyze_Indexed_Component_Form (N); when N_Integer_Literal => Analyze_Integer_Literal (N); when N_Iterator_Specification => Analyze_Iterator_Specification (N); when N_Itype_Reference => Analyze_Itype_Reference (N); when N_Label => Analyze_Label (N); when N_Loop_Parameter_Specification => Analyze_Loop_Parameter_Specification (N); when N_Loop_Statement => Analyze_Loop_Statement (N); when N_Not_In => Analyze_Membership_Op (N); when N_Null => Analyze_Null (N); when N_Null_Statement => Analyze_Null_Statement (N); when N_Number_Declaration => Analyze_Number_Declaration (N); when N_Object_Declaration => Analyze_Object_Declaration (N); when N_Object_Renaming_Declaration => Analyze_Object_Renaming (N); when N_Operator_Symbol => Analyze_Operator_Symbol (N); when N_Op_Abs => Analyze_Unary_Op (N); when N_Op_Add => Analyze_Arithmetic_Op (N); when N_Op_And => Analyze_Logical_Op (N); when N_Op_Concat => Analyze_Concatenation (N); when N_Op_Divide => Analyze_Arithmetic_Op (N); when N_Op_Eq => Analyze_Equality_Op (N); when N_Op_Expon => Analyze_Arithmetic_Op (N); when N_Op_Ge => Analyze_Comparison_Op (N); when N_Op_Gt => Analyze_Comparison_Op (N); when N_Op_Le => Analyze_Comparison_Op (N); when N_Op_Lt => Analyze_Comparison_Op (N); when N_Op_Minus => Analyze_Unary_Op (N); when N_Op_Mod => Analyze_Mod (N); when N_Op_Multiply => Analyze_Arithmetic_Op (N); when N_Op_Ne => Analyze_Equality_Op (N); when N_Op_Not => Analyze_Negation (N); when N_Op_Or => Analyze_Logical_Op (N); when N_Op_Plus => Analyze_Unary_Op (N); when N_Op_Rem => Analyze_Arithmetic_Op (N); when N_Op_Rotate_Left => Analyze_Arithmetic_Op (N); when N_Op_Rotate_Right => Analyze_Arithmetic_Op (N); when N_Op_Shift_Left => Analyze_Arithmetic_Op (N); when N_Op_Shift_Right => Analyze_Arithmetic_Op (N); when N_Op_Shift_Right_Arithmetic => Analyze_Arithmetic_Op (N); when N_Op_Subtract => Analyze_Arithmetic_Op (N); when N_Op_Xor => Analyze_Logical_Op (N); when N_Or_Else => Analyze_Short_Circuit (N); when N_Others_Choice => Analyze_Others_Choice (N); when N_Package_Body => Analyze_Package_Body (N); when N_Package_Body_Stub => Analyze_Package_Body_Stub (N); when N_Package_Declaration => Analyze_Package_Declaration (N); when N_Package_Instantiation => Analyze_Package_Instantiation (N); when N_Package_Renaming_Declaration => Analyze_Package_Renaming (N); when N_Package_Specification => Analyze_Package_Specification (N); when N_Parameter_Association => Analyze_Parameter_Association (N); when N_Pragma => Analyze_Pragma (N); when N_Private_Extension_Declaration => Analyze_Private_Extension_Declaration (N); when N_Private_Type_Declaration => Analyze_Private_Type_Declaration (N); when N_Procedure_Call_Statement => Analyze_Procedure_Call (N); when N_Procedure_Instantiation => Analyze_Procedure_Instantiation (N); when N_Protected_Body => Analyze_Protected_Body (N); when N_Protected_Body_Stub => Analyze_Protected_Body_Stub (N); when N_Protected_Definition => Analyze_Protected_Definition (N); when N_Protected_Type_Declaration => Analyze_Protected_Type_Declaration (N); when N_Qualified_Expression => Analyze_Qualified_Expression (N); when N_Quantified_Expression => Analyze_Quantified_Expression (N); when N_Raise_Expression => Analyze_Raise_Expression (N); when N_Raise_Statement => Analyze_Raise_Statement (N); when N_Raise_xxx_Error => Analyze_Raise_xxx_Error (N); when N_Range => Analyze_Range (N); when N_Range_Constraint => Analyze_Range (Range_Expression (N)); when N_Real_Literal => Analyze_Real_Literal (N); when N_Record_Representation_Clause => Analyze_Record_Representation_Clause (N); when N_Reference => Analyze_Reference (N); when N_Requeue_Statement => Analyze_Requeue (N); when N_Simple_Return_Statement => Analyze_Simple_Return_Statement (N); when N_Selected_Component => Find_Selected_Component (N); -- ??? why not Analyze_Selected_Component, needs comments when N_Selective_Accept => Analyze_Selective_Accept (N); when N_Single_Protected_Declaration => Analyze_Single_Protected_Declaration (N); when N_Single_Task_Declaration => Analyze_Single_Task_Declaration (N); when N_Slice => Analyze_Slice (N); when N_String_Literal => Analyze_String_Literal (N); when N_Subprogram_Body => Analyze_Subprogram_Body (N); when N_Subprogram_Body_Stub => Analyze_Subprogram_Body_Stub (N); when N_Subprogram_Declaration => Analyze_Subprogram_Declaration (N); when N_Subprogram_Renaming_Declaration => Analyze_Subprogram_Renaming (N); when N_Subtype_Declaration => Analyze_Subtype_Declaration (N); when N_Subtype_Indication => Analyze_Subtype_Indication (N); when N_Subunit => Analyze_Subunit (N); when N_Target_Name => Analyze_Target_Name (N); when N_Task_Body => Analyze_Task_Body (N); when N_Task_Body_Stub => Analyze_Task_Body_Stub (N); when N_Task_Definition => Analyze_Task_Definition (N); when N_Task_Type_Declaration => Analyze_Task_Type_Declaration (N); when N_Terminate_Alternative => Analyze_Terminate_Alternative (N); when N_Timed_Entry_Call => Analyze_Timed_Entry_Call (N); when N_Triggering_Alternative => Analyze_Triggering_Alternative (N); when N_Type_Conversion => Analyze_Type_Conversion (N); when N_Unchecked_Expression => Analyze_Unchecked_Expression (N); when N_Unchecked_Type_Conversion => Analyze_Unchecked_Type_Conversion (N); when N_Use_Package_Clause => Analyze_Use_Package (N); when N_Use_Type_Clause => Analyze_Use_Type (N); when N_Validate_Unchecked_Conversion => null; when N_Variant_Part => Analyze_Variant_Part (N); when N_With_Clause => Analyze_With_Clause (N); -- A call to analyze a marker is ignored because the node does not -- have any static and run-time semantics. when N_Call_Marker | N_Variable_Reference_Marker => null; -- A call to analyze the Empty node is an error, but most likely it -- is an error caused by an attempt to analyze a malformed piece of -- tree caused by some other error, so if there have been any other -- errors, we just ignore it, otherwise it is a real internal error -- which we complain about. -- We must also consider the case of call to a runtime function that -- is not available in the configurable runtime. when N_Empty => pragma Assert (Serious_Errors_Detected /= 0 or else Configurable_Run_Time_Violations /= 0); null; -- A call to analyze the error node is simply ignored, to avoid -- causing cascaded errors (happens of course only in error cases) -- Disable expansion in case it is still enabled, to prevent other -- subsequent compiler glitches. when N_Error => Expander_Mode_Save_And_Set (False); null; -- Push/Pop nodes normally don't come through an analyze call. An -- exception is the dummy ones bracketing a subprogram body. In any -- case there is nothing to be done to analyze such nodes. when N_Push_Pop_xxx_Label => null; -- SCIL nodes don't need analysis because they are decorated when -- they are built. They are added to the tree by Insert_Actions and -- the call to analyze them is generated when the full list is -- analyzed. when N_SCIL_Dispatch_Table_Tag_Init | N_SCIL_Dispatching_Call | N_SCIL_Membership_Test => null; -- A quantified expression with a missing "all" or "some" qualifier -- looks identical to an iterated component association. By language -- definition, the latter must be present within array aggregates. If -- this is not the case, then the iterated component association is -- really an illegal quantified expression. Diagnose this scenario. when N_Iterated_Component_Association => Diagnose_Iterated_Component_Association (N); when N_Iterated_Element_Association => null; -- May require a more precise error if misplaced. -- For the remaining node types, we generate compiler abort, because -- these nodes are always analyzed within the Sem_Chn routines and -- there should never be a case of making a call to the main Analyze -- routine for these node kinds. For example, an N_Access_Definition -- node appears only in the context of a type declaration, and is -- processed by the analyze routine for type declarations. when N_Abortable_Part | N_Access_Definition | N_Access_Function_Definition | N_Access_Procedure_Definition | N_Access_To_Object_Definition | N_Aspect_Specification | N_Case_Expression_Alternative | N_Case_Statement_Alternative | N_Compilation_Unit_Aux | N_Component_Association | N_Component_Clause | N_Component_Definition | N_Component_List | N_Constrained_Array_Definition | N_Contract | N_Decimal_Fixed_Point_Definition | N_Defining_Character_Literal | N_Defining_Identifier | N_Defining_Operator_Symbol | N_Defining_Program_Unit_Name | N_Delta_Constraint | N_Derived_Type_Definition | N_Designator | N_Digits_Constraint | N_Discriminant_Association | N_Discriminant_Specification | N_Elsif_Part | N_Entry_Call_Statement | N_Enumeration_Type_Definition | N_Exception_Handler | N_Floating_Point_Definition | N_Formal_Decimal_Fixed_Point_Definition | N_Formal_Derived_Type_Definition | N_Formal_Discrete_Type_Definition | N_Formal_Floating_Point_Definition | N_Formal_Modular_Type_Definition | N_Formal_Ordinary_Fixed_Point_Definition | N_Formal_Private_Type_Definition | N_Formal_Incomplete_Type_Definition | N_Formal_Signed_Integer_Type_Definition | N_Function_Specification | N_Generic_Association | N_Index_Or_Discriminant_Constraint | N_Iteration_Scheme | N_Mod_Clause | N_Modular_Type_Definition | N_Ordinary_Fixed_Point_Definition | N_Parameter_Specification | N_Pragma_Argument_Association | N_Procedure_Specification | N_Real_Range_Specification | N_Record_Definition | N_Signed_Integer_Type_Definition | N_Unconstrained_Array_Definition | N_Unused_At_End | N_Unused_At_Start | N_Variant => raise Program_Error; end case; Debug_A_Exit ("analyzing ", N, " (done)"); -- Mark relevant use-type and use-package clauses as effective -- preferring the original node over the analyzed one in the case that -- constant folding has occurred and removed references that need to be -- examined. Also, if the node in question is overloaded then this is -- deferred until resolution. declare Operat : Node_Id := Empty; begin -- Attempt to obtain a checkable operator node if Nkind (Original_Node (N)) in N_Op then Operat := Original_Node (N); elsif Nkind (N) in N_Op then Operat := N; end if; -- Mark the operator if Present (Operat) and then Present (Entity (Operat)) and then not Is_Overloaded (Operat) then Mark_Use_Clauses (Operat); end if; end; -- Now that we have analyzed the node, we call the expander to perform -- possible expansion. We skip this for subexpressions, because we don't -- have the type yet, and the expander will need to know the type before -- it can do its job. For subexpression nodes, the call to the expander -- happens in Sem_Res.Resolve. A special exception is Raise_xxx_Error, -- which can appear in a statement context, and needs expanding now in -- the case (distinguished by Etype, as documented in Sinfo). -- The Analyzed flag is also set at this point for non-subexpression -- nodes (in the case of subexpression nodes, we can't set the flag yet, -- since resolution and expansion have not yet been completed). Note -- that for N_Raise_xxx_Error we have to distinguish the expression -- case from the statement case. if Nkind (N) not in N_Subexpr or else (Nkind (N) in N_Raise_xxx_Error and then Etype (N) = Standard_Void_Type) then Expand (N); -- Replace a reference to a renaming with the renamed object for SPARK. -- In general this modification is performed by Expand_SPARK, however -- certain constructs may not reach the resolution or expansion phase -- and thus remain unchanged. The replacement is not performed when the -- construct is overloaded as resolution must first take place. This is -- also not done when analyzing a generic to preserve the original tree -- and because the reference may become overloaded in the instance. elsif GNATprove_Mode and then Nkind (N) in N_Expanded_Name | N_Identifier and then not Is_Overloaded (N) and then not Inside_A_Generic then Expand_SPARK_Potential_Renaming (N); end if; Restore_Ghost_Region (Saved_GM, Saved_IGR); end Analyze; -- Version with check(s) suppressed procedure Analyze (N : Node_Id; Suppress : Check_Id) is begin if Suppress = All_Checks then declare Svs : constant Suppress_Array := Scope_Suppress.Suppress; begin Scope_Suppress.Suppress := (others => True); Analyze (N); Scope_Suppress.Suppress := Svs; end; else declare Svg : constant Boolean := Scope_Suppress.Suppress (Suppress); begin Scope_Suppress.Suppress (Suppress) := True; Analyze (N); Scope_Suppress.Suppress (Suppress) := Svg; end; end if; end Analyze; ------------------ -- Analyze_List -- ------------------ procedure Analyze_List (L : List_Id) is Node : Node_Id; begin Node := First (L); while Present (Node) loop Analyze (Node); Next (Node); end loop; end Analyze_List; -- Version with check(s) suppressed procedure Analyze_List (L : List_Id; Suppress : Check_Id) is begin if Suppress = All_Checks then declare Svs : constant Suppress_Array := Scope_Suppress.Suppress; begin Scope_Suppress.Suppress := (others => True); Analyze_List (L); Scope_Suppress.Suppress := Svs; end; else declare Svg : constant Boolean := Scope_Suppress.Suppress (Suppress); begin Scope_Suppress.Suppress (Suppress) := True; Analyze_List (L); Scope_Suppress.Suppress (Suppress) := Svg; end; end if; end Analyze_List; -------------------------- -- Copy_Suppress_Status -- -------------------------- procedure Copy_Suppress_Status (C : Check_Id; From : Entity_Id; To : Entity_Id) is Found : Boolean; pragma Warnings (Off, Found); procedure Search_Stack (Top : Suppress_Stack_Entry_Ptr; Found : out Boolean); -- Search given suppress stack for matching entry for entity. If found -- then set Checks_May_Be_Suppressed on To, and push an appropriate -- entry for To onto the local suppress stack. ------------------ -- Search_Stack -- ------------------ procedure Search_Stack (Top : Suppress_Stack_Entry_Ptr; Found : out Boolean) is Ptr : Suppress_Stack_Entry_Ptr; begin Ptr := Top; while Ptr /= null loop if Ptr.Entity = From and then (Ptr.Check = All_Checks or else Ptr.Check = C) then if Ptr.Suppress then Set_Checks_May_Be_Suppressed (To, True); Push_Local_Suppress_Stack_Entry (Entity => To, Check => C, Suppress => True); Found := True; return; end if; end if; Ptr := Ptr.Prev; end loop; Found := False; return; end Search_Stack; -- Start of processing for Copy_Suppress_Status begin if not Checks_May_Be_Suppressed (From) then return; end if; -- First search the global entity suppress table for a matching entry. -- We also search this in reverse order so that if there are multiple -- pragmas for the same entity, the last one applies. Search_Stack (Global_Suppress_Stack_Top, Found); if Found then return; end if; -- Now search the local entity suppress stack, we search this in -- reverse order so that we get the innermost entry that applies to -- this case if there are nested entries. Note that for the purpose -- of this procedure we are ONLY looking for entries corresponding -- to a two-argument Suppress, where the second argument matches From. Search_Stack (Local_Suppress_Stack_Top, Found); end Copy_Suppress_Status; ------------------------- -- Enter_Generic_Scope -- ------------------------- procedure Enter_Generic_Scope (S : Entity_Id) is begin if No (Outer_Generic_Scope) then Outer_Generic_Scope := S; end if; end Enter_Generic_Scope; ------------------------ -- Exit_Generic_Scope -- ------------------------ procedure Exit_Generic_Scope (S : Entity_Id) is begin if S = Outer_Generic_Scope then Outer_Generic_Scope := Empty; end if; end Exit_Generic_Scope; ----------------------- -- Explicit_Suppress -- ----------------------- function Explicit_Suppress (E : Entity_Id; C : Check_Id) return Boolean is Ptr : Suppress_Stack_Entry_Ptr; begin if not Checks_May_Be_Suppressed (E) then return False; else Ptr := Global_Suppress_Stack_Top; while Ptr /= null loop if Ptr.Entity = E and then (Ptr.Check = All_Checks or else Ptr.Check = C) then return Ptr.Suppress; end if; Ptr := Ptr.Prev; end loop; end if; return False; end Explicit_Suppress; ----------------------------- -- External_Ref_In_Generic -- ----------------------------- function External_Ref_In_Generic (E : Entity_Id) return Boolean is Scop : Entity_Id; begin -- Entity is global if defined outside of current outer_generic_scope: -- Either the entity has a smaller depth that the outer generic, or it -- is in a different compilation unit, or it is defined within a unit -- in the same compilation, that is not within the outer_generic. if No (Outer_Generic_Scope) then return False; elsif Scope_Depth (Scope (E)) < Scope_Depth (Outer_Generic_Scope) or else not In_Same_Source_Unit (E, Outer_Generic_Scope) then return True; else Scop := Scope (E); while Present (Scop) loop if Scop = Outer_Generic_Scope then return False; elsif Scope_Depth (Scop) < Scope_Depth (Outer_Generic_Scope) then return True; else Scop := Scope (Scop); end if; end loop; return True; end if; end External_Ref_In_Generic; ---------------- -- Initialize -- ---------------- procedure Initialize is Next : Suppress_Stack_Entry_Ptr; procedure Free is new Unchecked_Deallocation (Suppress_Stack_Entry, Suppress_Stack_Entry_Ptr); begin -- Free any global suppress stack entries from a previous invocation -- of the compiler (in the normal case this loop does nothing). while Suppress_Stack_Entries /= null loop Next := Suppress_Stack_Entries.Next; Free (Suppress_Stack_Entries); Suppress_Stack_Entries := Next; end loop; Local_Suppress_Stack_Top := null; Global_Suppress_Stack_Top := null; -- Clear scope stack, and reset global variables Scope_Stack.Init; Unloaded_Subunits := False; end Initialize; ------------------------------ -- Insert_After_And_Analyze -- ------------------------------ procedure Insert_After_And_Analyze (N : Node_Id; M : Node_Id) is Node : Node_Id; begin if Present (M) then -- If we are not at the end of the list, then the easiest -- coding is simply to insert before our successor. if Present (Next (N)) then Insert_Before_And_Analyze (Next (N), M); -- Case of inserting at the end of the list else -- Capture the Node_Id of the node to be inserted. This Node_Id -- will still be the same after the insert operation. Node := M; Insert_After (N, M); -- Now just analyze from the inserted node to the end of -- the new list (note that this properly handles the case -- where any of the analyze calls result in the insertion of -- nodes after the analyzed node, expecting analysis). while Present (Node) loop Analyze (Node); Mark_Rewrite_Insertion (Node); Next (Node); end loop; end if; end if; end Insert_After_And_Analyze; -- Version with check(s) suppressed procedure Insert_After_And_Analyze (N : Node_Id; M : Node_Id; Suppress : Check_Id) is begin if Suppress = All_Checks then declare Svs : constant Suppress_Array := Scope_Suppress.Suppress; begin Scope_Suppress.Suppress := (others => True); Insert_After_And_Analyze (N, M); Scope_Suppress.Suppress := Svs; end; else declare Svg : constant Boolean := Scope_Suppress.Suppress (Suppress); begin Scope_Suppress.Suppress (Suppress) := True; Insert_After_And_Analyze (N, M); Scope_Suppress.Suppress (Suppress) := Svg; end; end if; end Insert_After_And_Analyze; ------------------------------- -- Insert_Before_And_Analyze -- ------------------------------- procedure Insert_Before_And_Analyze (N : Node_Id; M : Node_Id) is Node : Node_Id; begin if Present (M) then -- Capture the Node_Id of the first list node to be inserted. -- This will still be the first node after the insert operation, -- since Insert_List_After does not modify the Node_Id values. Node := M; Insert_Before (N, M); -- The insertion does not change the Id's of any of the nodes in -- the list, and they are still linked, so we can simply loop from -- the original first node until we meet the node before which the -- insertion is occurring. Note that this properly handles the case -- where any of the analyzed nodes insert nodes after themselves, -- expecting them to get analyzed. while Node /= N loop Analyze (Node); Mark_Rewrite_Insertion (Node); Next (Node); end loop; end if; end Insert_Before_And_Analyze; -- Version with check(s) suppressed procedure Insert_Before_And_Analyze (N : Node_Id; M : Node_Id; Suppress : Check_Id) is begin if Suppress = All_Checks then declare Svs : constant Suppress_Array := Scope_Suppress.Suppress; begin Scope_Suppress.Suppress := (others => True); Insert_Before_And_Analyze (N, M); Scope_Suppress.Suppress := Svs; end; else declare Svg : constant Boolean := Scope_Suppress.Suppress (Suppress); begin Scope_Suppress.Suppress (Suppress) := True; Insert_Before_And_Analyze (N, M); Scope_Suppress.Suppress (Suppress) := Svg; end; end if; end Insert_Before_And_Analyze; -------------------------------------------- -- Insert_Before_First_Source_Declaration -- -------------------------------------------- procedure Insert_Before_First_Source_Declaration (Stmt : Node_Id; Decls : List_Id) is Decl : Node_Id; begin -- Inspect the declarations of the related subprogram body looking for -- the first source declaration. pragma Assert (Present (Decls)); Decl := First (Decls); while Present (Decl) loop if Comes_From_Source (Decl) then Insert_Before (Decl, Stmt); return; end if; Next (Decl); end loop; -- If we get there, then the subprogram body lacks any source -- declarations. The body of _Postconditions now acts as the -- last declaration. Append (Stmt, Decls); end Insert_Before_First_Source_Declaration; ----------------------------------- -- Insert_List_After_And_Analyze -- ----------------------------------- procedure Insert_List_After_And_Analyze (N : Node_Id; L : List_Id) is After : constant Node_Id := Next (N); Node : Node_Id; begin if Is_Non_Empty_List (L) then -- Capture the Node_Id of the first list node to be inserted. -- This will still be the first node after the insert operation, -- since Insert_List_After does not modify the Node_Id values. Node := First (L); Insert_List_After (N, L); -- Now just analyze from the original first node until we get to the -- successor of the original insertion point (which may be Empty if -- the insertion point was at the end of the list). Note that this -- properly handles the case where any of the analyze calls result in -- the insertion of nodes after the analyzed node (possibly calling -- this routine recursively). while Node /= After loop Analyze (Node); Mark_Rewrite_Insertion (Node); Next (Node); end loop; end if; end Insert_List_After_And_Analyze; ------------------------------------ -- Insert_List_Before_And_Analyze -- ------------------------------------ procedure Insert_List_Before_And_Analyze (N : Node_Id; L : List_Id) is Node : Node_Id; begin if Is_Non_Empty_List (L) then -- Capture the Node_Id of the first list node to be inserted. This -- will still be the first node after the insert operation, since -- Insert_List_After does not modify the Node_Id values. Node := First (L); Insert_List_Before (N, L); -- The insertion does not change the Id's of any of the nodes in -- the list, and they are still linked, so we can simply loop from -- the original first node until we meet the node before which the -- insertion is occurring. Note that this properly handles the case -- where any of the analyzed nodes insert nodes after themselves, -- expecting them to get analyzed. while Node /= N loop Analyze (Node); Mark_Rewrite_Insertion (Node); Next (Node); end loop; end if; end Insert_List_Before_And_Analyze; ---------- -- Lock -- ---------- procedure Lock is begin Scope_Stack.Release; Scope_Stack.Locked := True; end Lock; ------------------------ -- Preanalysis_Active -- ------------------------ function Preanalysis_Active return Boolean is begin return not Full_Analysis and not Expander_Active; end Preanalysis_Active; ---------------- -- Preanalyze -- ---------------- procedure Preanalyze (N : Node_Id) is Save_Full_Analysis : constant Boolean := Full_Analysis; begin Full_Analysis := False; Expander_Mode_Save_And_Set (False); Analyze (N); Expander_Mode_Restore; Full_Analysis := Save_Full_Analysis; end Preanalyze; -------------------------------------- -- Push_Global_Suppress_Stack_Entry -- -------------------------------------- procedure Push_Global_Suppress_Stack_Entry (Entity : Entity_Id; Check : Check_Id; Suppress : Boolean) is begin Global_Suppress_Stack_Top := new Suppress_Stack_Entry' (Entity => Entity, Check => Check, Suppress => Suppress, Prev => Global_Suppress_Stack_Top, Next => Suppress_Stack_Entries); Suppress_Stack_Entries := Global_Suppress_Stack_Top; return; end Push_Global_Suppress_Stack_Entry; ------------------------------------- -- Push_Local_Suppress_Stack_Entry -- ------------------------------------- procedure Push_Local_Suppress_Stack_Entry (Entity : Entity_Id; Check : Check_Id; Suppress : Boolean) is begin Local_Suppress_Stack_Top := new Suppress_Stack_Entry' (Entity => Entity, Check => Check, Suppress => Suppress, Prev => Local_Suppress_Stack_Top, Next => Suppress_Stack_Entries); Suppress_Stack_Entries := Local_Suppress_Stack_Top; return; end Push_Local_Suppress_Stack_Entry; --------------- -- Semantics -- --------------- procedure Semantics (Comp_Unit : Node_Id) is procedure Do_Analyze; -- Perform the analysis of the compilation unit ---------------- -- Do_Analyze -- ---------------- -- WARNING: This routine manages Ghost regions. Return statements must -- be replaced by gotos which jump to the end of the routine and restore -- the Ghost mode. procedure Do_Analyze is Saved_GM : constant Ghost_Mode_Type := Ghost_Mode; Saved_IGR : constant Node_Id := Ignored_Ghost_Region; -- Save the Ghost-related attributes to restore on exit -- Generally style checks are preserved across compilations, with -- one exception: s-oscons.ads, which allows arbitrary long lines -- unconditionally, and has no restore mechanism, because it is -- intended as a lowest-level Pure package. Saved_ML : constant Int := Style_Max_Line_Length; Saved_CML : constant Boolean := Style_Check_Max_Line_Length; List : Elist_Id; begin List := Save_Scope_Stack; Push_Scope (Standard_Standard); -- Set up a clean environment before analyzing Install_Ghost_Region (None, Empty); Outer_Generic_Scope := Empty; Scope_Suppress := Suppress_Options; Scope_Stack.Table (Scope_Stack.Last).Component_Alignment_Default := Configuration_Component_Alignment; Scope_Stack.Table (Scope_Stack.Last).Is_Active_Stack_Base := True; -- Now analyze the top level compilation unit node Analyze (Comp_Unit); -- Check for scope mismatch on exit from compilation pragma Assert (Current_Scope = Standard_Standard or else Comp_Unit = Cunit (Main_Unit)); -- Then pop entry for Standard, and pop implicit types Pop_Scope; Restore_Scope_Stack (List); Restore_Ghost_Region (Saved_GM, Saved_IGR); Style_Max_Line_Length := Saved_ML; Style_Check_Max_Line_Length := Saved_CML; end Do_Analyze; -- Local variables -- The following locations save the corresponding global flags and -- variables so that they can be restored on completion. This is needed -- so that calls to Rtsfind start with the proper default values for -- these variables, and also that such calls do not disturb the settings -- for units being analyzed at a higher level. S_Current_Sem_Unit : constant Unit_Number_Type := Current_Sem_Unit; S_Full_Analysis : constant Boolean := Full_Analysis; S_GNAT_Mode : constant Boolean := GNAT_Mode; S_Global_Dis_Names : constant Boolean := Global_Discard_Names; S_In_Assertion_Expr : constant Nat := In_Assertion_Expr; S_In_Declare_Expr : constant Nat := In_Declare_Expr; S_In_Default_Expr : constant Boolean := In_Default_Expr; S_In_Spec_Expr : constant Boolean := In_Spec_Expression; S_Inside_A_Generic : constant Boolean := Inside_A_Generic; S_Outer_Gen_Scope : constant Entity_Id := Outer_Generic_Scope; S_Style_Check : constant Boolean := Style_Check; Already_Analyzed : constant Boolean := Analyzed (Comp_Unit); Curunit : constant Unit_Number_Type := Get_Cunit_Unit_Number (Comp_Unit); -- New value of Current_Sem_Unit Generic_Main : constant Boolean := Nkind (Unit (Cunit (Main_Unit))) in N_Generic_Declaration; -- If the main unit is generic, every compiled unit, including its -- context, is compiled with expansion disabled. Is_Main_Unit_Or_Main_Unit_Spec : constant Boolean := Curunit = Main_Unit or else (Nkind (Unit (Cunit (Main_Unit))) = N_Package_Body and then Library_Unit (Cunit (Main_Unit)) = Cunit (Curunit)); -- Configuration flags have special settings when compiling a predefined -- file as a main unit. This applies to its spec as well. Ext_Main_Source_Unit : constant Boolean := In_Extended_Main_Source_Unit (Comp_Unit); -- Determine if unit is in extended main source unit Save_Config_Attrs : Config_Switches_Type; -- Variable used to save values of config switches while we analyze the -- new unit, to be restored on exit for proper recursive behavior. Save_Cunit_Restrictions : Save_Cunit_Boolean_Restrictions; -- Used to save non-partition wide restrictions before processing new -- unit. All with'ed units are analyzed with config restrictions reset -- and we need to restore these saved values at the end. Save_Preanalysis_Counter : constant Nat := Inside_Preanalysis_Without_Freezing; -- Saves the preanalysis nesting-level counter; required since we may -- need to analyze a unit as a consequence of the preanalysis of an -- expression without freezing (and the loaded unit must be fully -- analyzed). -- Start of processing for Semantics begin Inside_Preanalysis_Without_Freezing := 0; if Debug_Unit_Walk then if Already_Analyzed then Write_Str ("(done)"); end if; Write_Unit_Info (Get_Cunit_Unit_Number (Comp_Unit), Unit (Comp_Unit), Prefix => "--> "); Indent; end if; Compiler_State := Analyzing; Current_Sem_Unit := Curunit; -- Compile predefined units with GNAT_Mode set to True, to properly -- process the categorization stuff. However, do not set GNAT_Mode -- to True for the renamings units (Text_IO, IO_Exceptions, Direct_IO, -- Sequential_IO) as this would prevent pragma Extend_System from being -- taken into account, for example when Text_IO is renaming DEC.Text_IO. if Is_Predefined_Unit (Current_Sem_Unit) and then not Is_Predefined_Renaming (Current_Sem_Unit) then GNAT_Mode := True; end if; -- For generic main, never do expansion if Generic_Main then Expander_Mode_Save_And_Set (False); -- Non generic case else Expander_Mode_Save_And_Set -- Turn on expansion if generating code (Operating_Mode = Generate_Code -- Or if special debug flag -gnatdx is set or else Debug_Flag_X -- Or if in configuration run-time mode. We do this so we get -- error messages about missing entities in the run-time even -- if we are compiling in -gnatc (no code generation) mode. -- Similar processing applies to No_Run_Time_Mode. However, -- don't do this if debug flag -gnatd.Z is set or when we are -- compiling a separate unit (this is to handle a situation -- where this new processing causes trouble). or else ((Configurable_Run_Time_Mode or No_Run_Time_Mode) and then not Debug_Flag_Dot_ZZ and then Nkind (Unit (Cunit (Main_Unit))) /= N_Subunit)); end if; Full_Analysis := True; Inside_A_Generic := False; In_Assertion_Expr := 0; In_Declare_Expr := 0; In_Default_Expr := False; In_Spec_Expression := False; Set_Comes_From_Source_Default (False); -- Save current config switches and reset then appropriately Save_Config_Attrs := Save_Config_Switches; Set_Config_Switches (Is_Internal_Unit (Current_Sem_Unit), Is_Main_Unit_Or_Main_Unit_Spec); -- Save current non-partition-wide restrictions Save_Cunit_Restrictions := Cunit_Boolean_Restrictions_Save; -- For unit in main extended unit, we reset the configuration values -- for the non-partition-wide restrictions. For other units reset them. if Ext_Main_Source_Unit then Restore_Config_Cunit_Boolean_Restrictions; else Reset_Cunit_Boolean_Restrictions; end if; -- Turn off style checks for unit that is not in the extended main -- source unit. This improves processing efficiency for such units -- (for which we don't want style checks anyway, and where they will -- get suppressed), and is definitely needed to stop some style checks -- from invading the run-time units (e.g. overriding checks). if not Ext_Main_Source_Unit then Style_Check := False; -- If this is part of the extended main source unit, set style check -- mode to match the style check mode of the main source unit itself. else Style_Check := Style_Check_Main; end if; -- Only do analysis of unit that has not already been analyzed if not Analyzed (Comp_Unit) then Initialize_Version (Current_Sem_Unit); -- Do analysis, and then append the compilation unit onto the -- Comp_Unit_List, if appropriate. This is done after analysis, -- so if this unit depends on some others, they have already been -- appended. We ignore bodies, except for the main unit itself, and -- for subprogram bodies that act as specs. We have also to guard -- against ill-formed subunits that have an improper context. Do_Analyze; if Present (Comp_Unit) and then Nkind (Unit (Comp_Unit)) in N_Proper_Body and then (Nkind (Unit (Comp_Unit)) /= N_Subprogram_Body or else not Acts_As_Spec (Comp_Unit)) and then not Ext_Main_Source_Unit then null; else Append_New_Elmt (Comp_Unit, To => Comp_Unit_List); if Debug_Unit_Walk then Write_Str ("Appending "); Write_Unit_Info (Get_Cunit_Unit_Number (Comp_Unit), Unit (Comp_Unit)); end if; end if; end if; -- Save indication of dynamic elaboration checks for ALI file Set_Dynamic_Elab (Current_Sem_Unit, Dynamic_Elaboration_Checks); -- Restore settings of saved switches to entry values Current_Sem_Unit := S_Current_Sem_Unit; Full_Analysis := S_Full_Analysis; Global_Discard_Names := S_Global_Dis_Names; GNAT_Mode := S_GNAT_Mode; In_Assertion_Expr := S_In_Assertion_Expr; In_Declare_Expr := S_In_Declare_Expr; In_Default_Expr := S_In_Default_Expr; In_Spec_Expression := S_In_Spec_Expr; Inside_A_Generic := S_Inside_A_Generic; Outer_Generic_Scope := S_Outer_Gen_Scope; Style_Check := S_Style_Check; Restore_Config_Switches (Save_Config_Attrs); -- Deal with restore of restrictions Cunit_Boolean_Restrictions_Restore (Save_Cunit_Restrictions); Expander_Mode_Restore; if Debug_Unit_Walk then Outdent; if Already_Analyzed then Write_Str ("(done)"); end if; Write_Unit_Info (Get_Cunit_Unit_Number (Comp_Unit), Unit (Comp_Unit), Prefix => "<-- "); end if; Inside_Preanalysis_Without_Freezing := Save_Preanalysis_Counter; end Semantics; -------- -- ss -- -------- function ss (Index : Int) return Scope_Stack_Entry is begin return Scope_Stack.Table (Index); end ss; --------- -- sst -- --------- function sst return Scope_Stack_Entry is begin return ss (Scope_Stack.Last); end sst; ------------ -- Unlock -- ------------ procedure Unlock is begin Scope_Stack.Locked := False; end Unlock; ------------------------ -- Walk_Library_Items -- ------------------------ procedure Walk_Library_Items is type Unit_Number_Set is array (Main_Unit .. Last_Unit) of Boolean; pragma Pack (Unit_Number_Set); Main_CU : constant Node_Id := Cunit (Main_Unit); Spec_CU : Node_Id := Empty; Seen, Done : Unit_Number_Set := (others => False); -- Seen (X) is True after we have seen unit X in the walk. This is used -- to prevent processing the same unit more than once. Done (X) is True -- after we have fully processed X, and is used only for debugging -- printouts and assertions. Do_Main : Boolean := False; -- Flag to delay processing the main body until after all other units. -- This is needed because the spec of the main unit may appear in the -- context of some other unit. We do not want this to force processing -- of the main body before all other units have been processed. -- -- Another circularity pattern occurs when the main unit is a child unit -- and the body of an ancestor has a with-clause of the main unit or on -- one of its children. In both cases the body in question has a with- -- clause on the main unit, and must be excluded from the traversal. In -- some convoluted cases this may lead to a CodePeer error because the -- spec of a subprogram declared in an instance within the parent will -- not be seen in the main unit. function Depends_On_Main (CU : Node_Id) return Boolean; -- The body of a unit that is withed by the spec of the main unit may in -- turn have a with_clause on that spec. In that case do not traverse -- the body, to prevent loops. It can also happen that the main body has -- a with_clause on a child, which of course has an implicit with on its -- parent. It's OK to traverse the child body if the main spec has been -- processed, otherwise we also have a circularity to avoid. procedure Do_Action (CU : Node_Id; Item : Node_Id); -- Calls Action, with some validity checks procedure Do_Unit_And_Dependents (CU : Node_Id; Item : Node_Id); -- Calls Do_Action, first on the units with'ed by this one, then on -- this unit. If it's an instance body, do the spec first. If it is -- an instance spec, do the body last. procedure Do_Withed_Unit (Withed_Unit : Node_Id); -- Apply Do_Unit_And_Dependents to a unit in a context clause procedure Process_Bodies_In_Context (Comp : Node_Id); -- The main unit and its spec may depend on bodies that contain generics -- that are instantiated in them. Iterate through the corresponding -- contexts before processing main (spec/body) itself, to process bodies -- that may be present, together with their context. The spec of main -- is processed wherever it appears in the list of units, while the body -- is processed as the last unit in the list. --------------------- -- Depends_On_Main -- --------------------- function Depends_On_Main (CU : Node_Id) return Boolean is CL : Node_Id; MCU : constant Node_Id := Unit (Main_CU); begin -- Problem does not arise with main subprograms if Nkind (MCU) not in N_Package_Body | N_Package_Declaration then return False; end if; CL := First (Context_Items (CU)); while Present (CL) loop if Nkind (CL) = N_With_Clause and then Library_Unit (CL) = Main_CU and then not Done (Get_Cunit_Unit_Number (Library_Unit (CL))) then return True; end if; Next (CL); end loop; return False; end Depends_On_Main; --------------- -- Do_Action -- --------------- procedure Do_Action (CU : Node_Id; Item : Node_Id) is begin -- This calls Action at the end. All the preceding code is just -- assertions and debugging output. pragma Assert (No (CU) or else Nkind (CU) = N_Compilation_Unit); case Nkind (Item) is when N_Generic_Function_Renaming_Declaration | N_Generic_Package_Declaration | N_Generic_Package_Renaming_Declaration | N_Generic_Procedure_Renaming_Declaration | N_Generic_Subprogram_Declaration | N_Package_Declaration | N_Package_Renaming_Declaration | N_Subprogram_Declaration | N_Subprogram_Renaming_Declaration => -- Specs are OK null; when N_Package_Body => -- Package bodies are processed separately if the main unit -- depends on them. null; when N_Subprogram_Body => -- A subprogram body must be the main unit pragma Assert (Acts_As_Spec (CU) or else CU = Main_CU); null; when N_Function_Instantiation | N_Package_Instantiation | N_Procedure_Instantiation => -- Can only happen if some generic body (needed for gnat2scil -- traversal, but not by GNAT) is not available, ignore. null; -- All other cases cannot happen when N_Subunit => pragma Assert (False, "subunit"); null; when N_Null_Statement => -- Do not call Action for an ignored ghost unit pragma Assert (Is_Ignored_Ghost_Node (Original_Node (Item))); return; when others => pragma Assert (False); null; end case; if Present (CU) then pragma Assert (Item /= Stand.Standard_Package_Node); pragma Assert (Item = Unit (CU)); declare Unit_Num : constant Unit_Number_Type := Get_Cunit_Unit_Number (CU); procedure Assert_Done (Withed_Unit : Node_Id); -- Assert Withed_Unit is already Done, unless it's a body. It -- might seem strange for a with_clause to refer to a body, but -- this happens in the case of a generic instantiation, which -- gets transformed into the instance body (and the instance -- spec is also created). With clauses pointing to the -- instantiation end up pointing to the instance body. ----------------- -- Assert_Done -- ----------------- procedure Assert_Done (Withed_Unit : Node_Id) is begin if Withed_Unit /= Main_CU and then not Done (Get_Cunit_Unit_Number (Withed_Unit)) then -- N_Null_Statement will happen in case of a ghost unit -- which gets rewritten. if Nkind (Unit (Withed_Unit)) not in N_Generic_Package_Declaration | N_Package_Body | N_Package_Renaming_Declaration | N_Subprogram_Body | N_Null_Statement then Write_Unit_Name (Unit_Name (Get_Cunit_Unit_Number (Withed_Unit))); Write_Str (" not yet walked!"); if Get_Cunit_Unit_Number (Withed_Unit) = Unit_Num then Write_Str (" (self-ref)"); end if; Write_Eol; pragma Assert (False); end if; end if; end Assert_Done; procedure Assert_Withed_Units_Done is new Walk_Withs (Assert_Done); begin if Debug_Unit_Walk then Write_Unit_Info (Unit_Num, Item, Withs => True); end if; -- Main unit should come last, except in the case where we -- skipped System_Aux_Id, in which case we missed the things it -- depends on, and in the case of parent bodies if present. pragma Assert (not Done (Main_Unit) or else Present (System_Aux_Id) or else Nkind (Item) = N_Package_Body); -- We shouldn't do the same thing twice pragma Assert (not Done (Unit_Num)); -- Everything we depend upon should already be done pragma Debug (Assert_Withed_Units_Done (CU, Include_Limited => False)); end; else -- Must be Standard, which has no entry in the units table pragma Assert (Item = Stand.Standard_Package_Node); if Debug_Unit_Walk then Write_Line ("Standard"); end if; end if; Action (Item); end Do_Action; -------------------- -- Do_Withed_Unit -- -------------------- procedure Do_Withed_Unit (Withed_Unit : Node_Id) is begin Do_Unit_And_Dependents (Withed_Unit, Unit (Withed_Unit)); -- If the unit in the with_clause is a generic instance, the clause -- now denotes the instance body. Traverse the corresponding spec -- because there may be no other dependence that will force the -- traversal of its own context. if Nkind (Unit (Withed_Unit)) = N_Package_Body and then Is_Generic_Instance (Defining_Entity (Unit (Library_Unit (Withed_Unit)))) then Do_Withed_Unit (Library_Unit (Withed_Unit)); end if; end Do_Withed_Unit; ---------------------------- -- Do_Unit_And_Dependents -- ---------------------------- procedure Do_Unit_And_Dependents (CU : Node_Id; Item : Node_Id) is Unit_Num : constant Unit_Number_Type := Get_Cunit_Unit_Number (CU); Child : Node_Id; Body_U : Unit_Number_Type; Parent_CU : Node_Id; procedure Do_Withed_Units is new Walk_Withs (Do_Withed_Unit); begin if not Seen (Unit_Num) then -- Process the with clauses Do_Withed_Units (CU, Include_Limited => False); -- Process the unit if it is a spec or the main unit, if it -- has no previous spec or we have done all other units. if Nkind (Item) not in N_Package_Body | N_Subprogram_Body or else Acts_As_Spec (CU) then if CU = Main_CU and then not Do_Main then Seen (Unit_Num) := False; else Seen (Unit_Num) := True; if CU = Library_Unit (Main_CU) then Process_Bodies_In_Context (CU); -- If main is a child unit, examine parent unit contexts -- to see if they include instantiated units. Also, if -- the parent itself is an instance, process its body -- because it may contain subprograms that are called -- in the main unit. if Is_Child_Unit (Cunit_Entity (Main_Unit)) then Child := Cunit_Entity (Main_Unit); while Is_Child_Unit (Child) loop Parent_CU := Cunit (Get_Cunit_Entity_Unit_Number (Scope (Child))); Process_Bodies_In_Context (Parent_CU); if Nkind (Unit (Parent_CU)) = N_Package_Body and then Nkind (Original_Node (Unit (Parent_CU))) = N_Package_Instantiation and then not Seen (Get_Cunit_Unit_Number (Parent_CU)) then Body_U := Get_Cunit_Unit_Number (Parent_CU); Seen (Body_U) := True; Do_Action (Parent_CU, Unit (Parent_CU)); Done (Body_U) := True; end if; Child := Scope (Child); end loop; end if; end if; Do_Action (CU, Item); Done (Unit_Num) := True; end if; end if; end if; end Do_Unit_And_Dependents; ------------------------------- -- Process_Bodies_In_Context -- ------------------------------- procedure Process_Bodies_In_Context (Comp : Node_Id) is Body_CU : Node_Id; Body_U : Unit_Number_Type; Clause : Node_Id; Spec : Node_Id; procedure Do_Withed_Units is new Walk_Withs (Do_Withed_Unit); -- Start of processing for Process_Bodies_In_Context begin Clause := First (Context_Items (Comp)); while Present (Clause) loop if Nkind (Clause) = N_With_Clause then Spec := Library_Unit (Clause); Body_CU := Library_Unit (Spec); -- If we are processing the spec of the main unit, load bodies -- only if the with_clause indicates that it forced the loading -- of the body for a generic instantiation. Note that bodies of -- parents that are instances have been loaded already. if Present (Body_CU) and then Body_CU /= Main_CU and then Nkind (Unit (Body_CU)) /= N_Subprogram_Body and then Nkind (Unit (Comp)) /= N_Package_Declaration then Body_U := Get_Cunit_Unit_Number (Body_CU); if not Seen (Body_U) and then not Depends_On_Main (Body_CU) then Seen (Body_U) := True; Do_Withed_Units (Body_CU, Include_Limited => False); Do_Action (Body_CU, Unit (Body_CU)); Done (Body_U) := True; end if; end if; end if; Next (Clause); end loop; end Process_Bodies_In_Context; -- Local Declarations Cur : Elmt_Id; -- Start of processing for Walk_Library_Items begin if Debug_Unit_Walk then Write_Line ("Walk_Library_Items:"); Indent; end if; -- Do Standard first, then walk the Comp_Unit_List Do_Action (Empty, Standard_Package_Node); -- First place the context of all instance bodies on the corresponding -- spec, because it may be needed to analyze the code at the place of -- the instantiation. Cur := First_Elmt (Comp_Unit_List); while Present (Cur) loop declare CU : constant Node_Id := Node (Cur); N : constant Node_Id := Unit (CU); begin if Nkind (N) = N_Package_Body and then Is_Generic_Instance (Defining_Entity (N)) then Append_List (Context_Items (CU), Context_Items (Library_Unit (CU))); end if; Next_Elmt (Cur); end; end loop; -- Now traverse compilation units (specs) in order Cur := First_Elmt (Comp_Unit_List); while Present (Cur) loop declare CU : constant Node_Id := Node (Cur); N : constant Node_Id := Unit (CU); Par : Entity_Id; begin pragma Assert (Nkind (CU) = N_Compilation_Unit); case Nkind (N) is -- If it is a subprogram body, process it if it has no -- separate spec. -- If it's a package body, ignore it, unless it is a body -- created for an instance that is the main unit. In the case -- of subprograms, the body is the wrapper package. In case of -- a package, the original file carries the body, and the spec -- appears as a later entry in the units list. -- Otherwise bodies appear in the list only because of inlining -- or instantiations, and they are processed only if relevant. -- The flag Withed_Body on a context clause indicates that a -- unit contains an instantiation that may be needed later, -- and therefore the body that contains the generic body (and -- its context) must be traversed immediately after the -- corresponding spec (see Do_Unit_And_Dependents). -- The main unit itself is processed separately after all other -- specs, and relevant bodies are examined in Process_Main. when N_Subprogram_Body => if Acts_As_Spec (N) then Do_Unit_And_Dependents (CU, N); end if; when N_Package_Body => if CU = Main_CU and then Nkind (Original_Node (Unit (Main_CU))) in N_Generic_Instantiation and then Present (Library_Unit (Main_CU)) then Do_Unit_And_Dependents (Library_Unit (Main_CU), Unit (Library_Unit (Main_CU))); end if; -- It is a spec, process it, and the units it depends on, -- unless it is a descendant of the main unit. This can happen -- when the body of a parent depends on some other descendant. when N_Null_Statement => -- Ignore an ignored ghost unit pragma Assert (Is_Ignored_Ghost_Node (Original_Node (N))); null; when others => -- Skip spec of main unit for now, we want to process it -- after all other specs. if Nkind (Unit (CU)) = N_Package_Declaration and then Library_Unit (CU) = Main_CU and then CU /= Main_CU then Spec_CU := CU; else Par := Scope (Defining_Entity (Unit (CU))); if Is_Child_Unit (Defining_Entity (Unit (CU))) then while Present (Par) and then Par /= Standard_Standard and then Par /= Cunit_Entity (Main_Unit) loop Par := Scope (Par); end loop; end if; if Par /= Cunit_Entity (Main_Unit) then Do_Unit_And_Dependents (CU, N); end if; end if; end case; end; Next_Elmt (Cur); end loop; -- Now process main package spec if skipped if Present (Spec_CU) then Do_Unit_And_Dependents (Spec_CU, Unit (Spec_CU)); end if; -- Now process package bodies on which main depends, followed by bodies -- of parents, if present, and finally main itself. if not Done (Main_Unit) then Do_Main := True; Process_Main : declare Parent_CU : Node_Id; Body_CU : Node_Id; Body_U : Unit_Number_Type; Child : Entity_Id; function Is_Subunit_Of_Main (U : Node_Id) return Boolean; -- If the main unit has subunits, their context may include -- bodies that are needed in the body of main. We must examine -- the context of the subunits, which are otherwise not made -- explicit in the main unit. ------------------------ -- Is_Subunit_Of_Main -- ------------------------ function Is_Subunit_Of_Main (U : Node_Id) return Boolean is Lib : Node_Id; begin if Present (U) and then Nkind (Unit (U)) = N_Subunit then Lib := Library_Unit (U); return Lib = Main_CU or else Is_Subunit_Of_Main (Lib); else return False; end if; end Is_Subunit_Of_Main; -- Start of processing for Process_Main begin Process_Bodies_In_Context (Main_CU); for Unit_Num in Done'Range loop if Is_Subunit_Of_Main (Cunit (Unit_Num)) then Process_Bodies_In_Context (Cunit (Unit_Num)); end if; end loop; -- If the main unit is a child unit, parent bodies may be present -- because they export instances or inlined subprograms. Check for -- presence of these, which are not present in context clauses. -- Note that if the parents are instances, their bodies have been -- processed before the main spec, because they may be needed -- therein, so the following loop only affects non-instances. if Is_Child_Unit (Cunit_Entity (Main_Unit)) then Child := Cunit_Entity (Main_Unit); while Is_Child_Unit (Child) loop Parent_CU := Cunit (Get_Cunit_Entity_Unit_Number (Scope (Child))); Body_CU := Library_Unit (Parent_CU); if Present (Body_CU) and then not Seen (Get_Cunit_Unit_Number (Body_CU)) and then not Depends_On_Main (Body_CU) then Body_U := Get_Cunit_Unit_Number (Body_CU); Seen (Body_U) := True; Do_Action (Body_CU, Unit (Body_CU)); Done (Body_U) := True; end if; Child := Scope (Child); end loop; end if; Do_Action (Main_CU, Unit (Main_CU)); Done (Main_Unit) := True; end Process_Main; end if; if Debug_Unit_Walk then if Done /= (Done'Range => True) then Write_Eol; Write_Line ("Ignored units:"); Indent; for Unit_Num in Done'Range loop if not Done (Unit_Num) then -- Units with configuration pragmas (.ads files) have empty -- compilation-unit nodes; skip printing info about them. if Present (Cunit (Unit_Num)) then Write_Unit_Info (Unit_Num, Unit (Cunit (Unit_Num)), Withs => True); end if; end if; end loop; Outdent; end if; end if; pragma Assert (Done (Main_Unit)); if Debug_Unit_Walk then Outdent; Write_Line ("end Walk_Library_Items."); end if; end Walk_Library_Items; ---------------- -- Walk_Withs -- ---------------- procedure Walk_Withs (CU : Node_Id; Include_Limited : Boolean) is pragma Assert (Nkind (CU) = N_Compilation_Unit); pragma Assert (Nkind (Unit (CU)) /= N_Subunit); procedure Walk_Immediate is new Walk_Withs_Immediate (Action); begin -- First walk the withs immediately on the library item Walk_Immediate (CU, Include_Limited); -- For a body, we must also check for any subunits which belong to it -- and which have context clauses of their own, since these with'ed -- units are part of its own dependencies. if Nkind (Unit (CU)) in N_Unit_Body then for S in Main_Unit .. Last_Unit loop -- We are only interested in subunits. For preproc. data and def. -- files, Cunit is Empty, so we need to test that first. if Cunit (S) /= Empty and then Nkind (Unit (Cunit (S))) = N_Subunit then declare Pnode : Node_Id; begin Pnode := Library_Unit (Cunit (S)); -- In -gnatc mode, the errors in the subunits will not have -- been recorded, but the analysis of the subunit may have -- failed, so just quit. if No (Pnode) then exit; end if; -- Find ultimate parent of the subunit while Nkind (Unit (Pnode)) = N_Subunit loop Pnode := Library_Unit (Pnode); end loop; -- See if it belongs to current unit, and if so, include its -- with_clauses. Do not process main unit prematurely. if Pnode = CU and then CU /= Cunit (Main_Unit) then Walk_Immediate (Cunit (S), Include_Limited); end if; end; end if; end loop; end if; end Walk_Withs; -------------------------- -- Walk_Withs_Immediate -- -------------------------- procedure Walk_Withs_Immediate (CU : Node_Id; Include_Limited : Boolean) is pragma Assert (Nkind (CU) = N_Compilation_Unit); Context_Item : Node_Id; Lib_Unit : Node_Id; begin Context_Item := First (Context_Items (CU)); while Present (Context_Item) loop if Nkind (Context_Item) = N_With_Clause and then (Include_Limited or else not Limited_Present (Context_Item)) then Lib_Unit := Library_Unit (Context_Item); Action (Lib_Unit); end if; Next (Context_Item); end loop; end Walk_Withs_Immediate; end Sem;
with Ada.Interrupts.Names; with SAM.Device; with SAM.GPIO; package Screen_Isr is Interrupt_Line : SAM.GPIO.GPIO_Point renames SAM.Device.PC9; protected ISR_Body is procedure Handler;-- with -- Attach_Handler => Ada.Interrupts.Names.PIOC; end ISR_Body; end Screen_Isr;
with OpenGL.Error; package body OpenGL.Check is procedure State_OK (Message : in String := "") is use type Error.Error_t; Error_Value : constant Error.Error_t := Error.Get_Error; begin if Error_Value /= Error.No_Error then if Message'Length /= 0 then Raise_Exception (Message & ": " & Error.Error_t'Image (Error_Value)); else Raise_Exception (Error.Error_t'Image (Error_Value)); end if; end if; end State_OK; procedure Raise_Exception (Message : in String) is begin raise GL_Error with Message; end Raise_Exception; end OpenGL.Check;
-- 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.Exceptions; with Ada.Real_Time; with Ada.Text_IO; with Orka.Futures; with Orka.Jobs; with Package_9_Jobs; procedure Orka_9_Jobs is Job_0 : constant Orka.Jobs.Job_Ptr := new Package_9_Jobs.Test_Sequential_Job' (Orka.Jobs.Abstract_Job with ID => 0); Job_1 : constant Orka.Jobs.Job_Ptr := new Package_9_Jobs.Test_Sequential_Job' (Orka.Jobs.Abstract_Job with ID => 1); Job_2 : constant Orka.Jobs.Job_Ptr := new Package_9_Jobs.Test_Sequential_Job' (Orka.Jobs.Abstract_Job with ID => 2); Job_3 : constant Orka.Jobs.Parallel_Job_Ptr := new Package_9_Jobs.Test_Parallel_Job; Job_4 : constant Orka.Jobs.Job_Ptr := Orka.Jobs.Parallelize (Job_3, Package_9_Jobs.Clone_Job'Access, 24, 6); Handle : Orka.Futures.Pointers.Mutable_Pointer; Status : Orka.Futures.Status; use Ada.Exceptions; use Ada.Real_Time; use Ada.Text_IO; T1, T2 : Time; package Job_System renames Package_9_Jobs.Job_System; begin -- Graph: Job_0 --> Job_1 --> Job_4 (4 slices) --> Job_2 Orka.Jobs.Chain ((Job_0, Job_1, Job_4, Job_2)); Job_System.Queue.Enqueue (Job_0, Handle); Put_Line ("References (2): " & Handle.References'Image); T1 := Clock; declare Reference : constant Orka.Futures.Pointers.Reference := Handle.Get; Future : constant Orka.Futures.Future_Access := Reference.Value; begin select Future.Wait_Until_Done (Status); T2 := Clock; Put_Line (" Status: " & Status'Image); Put_Line (" Time: " & Duration'Image (1e3 * To_Duration (T2 - T1)) & " ms"); or delay until T1 + Milliseconds (10); Put_Line (" Time out: " & Reference.Current_Status'Image); end select; exception when Error : others => Put_Line ("Error: " & Exception_Information (Error)); end; Put_Line ("References (1): " & Handle.References'Image); Job_System.Shutdown; Put_Line ("CPU Queue: " & Job_System.Queue.Length (Job_System.Queues.CPU)'Image); Put_Line ("GPU Queue: " & Job_System.Queue.Length (Job_System.Queues.GPU)'Image); end Orka_9_Jobs;
-- Abstract: -- -- An unbounded minimum Fibonacci heap of definite non-limited elements. -- -- References: -- -- [1] Introduction to Algorithms, Third Edition. Thomas H. Cormen, -- Charles E. Leiserson, Ronald L. Rivest, Clifford Stein. Chapter 19. -- -- Copyright (C) 2017 - 2019 Free Software Foundation, Inc. -- -- This library is free software; you can redistribute it and/or modify it -- under terms of the GNU General Public License as published by the Free -- Software Foundation; either version 3, or (at your option) any later -- version. This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN- -- TABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- As a special exception under Section 7 of GPL version 3, you are granted -- additional permissions described in the GCC Runtime Library Exception, -- version 3.1, as published by the Free Software Foundation. pragma License (Modified_GPL); with Ada.Finalization; generic type Element_Type is private; type Key_Type is private; with function Key (Item : in Element_Type) return Key_Type; with procedure Set_Key (Item : in out Element_Type; Key : in Key_Type); pragma Unreferenced (Set_Key); -- needed for Decrease_Key with function "<" (Left, Right : in Key_Type) return Boolean is <>; package SAL.Gen_Unbounded_Definite_Min_Heaps_Fibonacci is type Heap_Type is new Ada.Finalization.Controlled with private; Empty_Heap : constant Heap_Type; overriding procedure Initialize (Object : in out Heap_Type); overriding procedure Finalize (Object : in out Heap_Type); overriding procedure Adjust (Object : in out Heap_Type); procedure Clear (Heap : in out Heap_Type); -- Empty Heap. function Count (Heap : in Heap_Type) return Base_Peek_Type; -- Return count of elements in Heap. function Remove (Heap : in out Heap_Type) return Element_Type; -- Remove minimum element in Heap, return it. function Min_Key (Heap : in out Heap_Type) return Key_Type; -- Return a copy of the minimum key value. function Get (Heap : in out Heap_Type) return Element_Type renames Remove; procedure Drop (Heap : in out Heap_Type); -- Remove minimum element in Heap, discard it. procedure Add (Heap : in out Heap_Type; Item : in Element_Type); -- Add Item to Heap. procedure Insert (Heap : in out Heap_Type; Item : in Element_Type) renames Add; type Constant_Reference_Type (Element : not null access constant Element_Type) is private with Implicit_Dereference => Element; function Peek (Heap : in Heap_Type) return Constant_Reference_Type; -- Return a constant reference to the min element. pragma Inline (Peek); -- We don't provide a Cursor/Iterator interface; to complex to -- implement. So far, we only need a read-only forward iterator, -- which Process provides. procedure Process (Heap : in Heap_Type; Process_Element : access procedure (Element : in Element_Type)); -- Call Process_Element with each Element in Heap. Min is first; rest are in -- arbitrary order. private type Node; type Node_Access is access Node; type Node is record Element : aliased Element_Type; Parent : Node_Access; Child : Node_Access; Left : Node_Access; Right : Node_Access; Degree : Natural; Mark : Boolean; end record; type Heap_Type is new Ada.Finalization.Controlled with record Min : Node_Access; Count : Base_Peek_Type; end record; type Constant_Reference_Type (Element : not null access constant Element_Type) is record Dummy : Integer := raise Program_Error with "uninitialized reference"; end record; Empty_Heap : constant Heap_Type := (Ada.Finalization.Controlled with Min => null, Count => 0); end SAL.Gen_Unbounded_Definite_Min_Heaps_Fibonacci;
----------------------------------------------------------------------- -- Generic Quicksort procedure ----------------------------------------------------------------------- generic type Element_Type is private; type Index_Type is (<>); type Element_Array is array(Index_Type range <>) of Element_Type; with function "<" (Left, Right : Element_Type) return Boolean is <>; with function ">" (Left, Right : Element_Type) return Boolean is <>; procedure Sort(Item : in out Element_Array);
with AOC.AOC_2019.Day01; with AOC.AOC_2019.Day02; with AOC.AOC_2019.Day03; with AOC.AOC_2019.Day05; with AOC.AOC_2019.Day06; with AOC.AOC_2019.Day07; with AOC.AOC_2019.Day08; package body AOC.AOC_2019 is function Get_Day (R : Runner_2019; Day_Number : Natural) return Day.Access_Day is begin return (case Day_Number is when 1 => new Day01.Day_01, when 2 => new Day02.Day_02, when 3 => new Day03.Day_03, when 5 => new Day05.Day_05, when 6 => new Day06.Day_06, when 7 => new Day07.Day_07, when 8 => new Day08.Day_08, when others => null); end Get_Day; end AOC.AOC_2019;
with Leds; use Leds; with Morse; use Morse; with Ada.Real_Time; use Ada.Real_time; package body Tasking is procedure Last_Chance_Handler (Msg : System.Address; Line : Integer) is begin Led_Set(LED0, Red); Led_Set(LED1, Red); end Last_Chance_Handler; procedure Wait_Forever is begin loop delay until Clock + Seconds (3600); end loop; end Wait_Forever; task body Init is begin Led_Init; Wait_Forever; end Init; task body Task_1 is Wait_Restart : constant Time_Span := Seconds(1); Morse_String : constant String := "Hello World"; Timeout : Time := Clock; begin Timeout := Timeout + Wait_restart; delay until Timeout; loop Morse_Display (Morse_String); Timeout := Timeout + Wait_restart; delay until Timeout; end loop; exception when others => Led_Set(LED0, Red); end Task_1; task body Task_2 is begin loop Blink(LED1, Magenta, Seconds(1)); end loop; exception when others => Led_Set(LED1, Red); end Task_2; end Tasking;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS -- -- -- -- S Y S T E M . B B . B O A R D _ P A R A M E T E R S -- -- -- -- S p e c -- -- -- -- Copyright (C) 2016-2021, 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. -- -- -- -- The port of GNARL to bare board targets was initially developed by the -- -- Real-Time Systems Group at the Technical University of Madrid. -- -- -- ------------------------------------------------------------------------------ -- This package defines board parameters for the STM32L562 boards package System.BB.Board_Parameters is pragma No_Elaboration_Code_All; pragma Pure; Main_Clock_Frequency : constant := 110_000_000; -- Maximum frequency of the system clock, per RM0438 section 9.3.3, when -- the PLL is used. HSE_Clock_Frequency : constant := 8_000_000; -- The high speed external oscillator is optional and not mounted by -- default on the STM32L562QE Discovery Board, per UM2617 Rev 4, section -- 6.5.2, page 22/61 (User Manual for STM32L562QE MCU). Also, 8MHz is -- typical but not necessarily the value configured if the HSE is actualy -- present. MSI_Clock_Frequency : constant := 48_000_000; -- The Multispeed Internal clock, a configurable oscialltor used in our -- config to drive the PLL. NB: requires setting bits in RCC_CR.MSIRANGE -- field! Otherwise is 4MHz on powerup. FLASH_Latency : constant := 5; -- After reset, the CPU clock frequency is 4 MHz and 0 wait state (WS) is -- configured in the FLASH_ACR register. We will run at 110MHz so we use -- 5 wait states, per RM0438 Rev 6 pg 179/2194, section 6.3.3 Read access -- latency, table 31 "Number of wait states according to CPU clock (HCLK) -- frequency" end System.BB.Board_Parameters;
----------------------------------------------------------------------- -- Util.Serialize.Mappers.Record_Mapper -- Mapper for record types -- Copyright (C) 2010, 2011, 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 Util.Beans.Objects; with Util.Serialize.IO; generic type Element_Type (<>) is limited private; type Element_Type_Access is access all Element_Type; type Fields is (<>); -- The <b>Set_Member</b> procedure will be called by the mapper when a mapping associated -- with <b>Field</b> is recognized. The <b>Value</b> holds the value that was extracted -- according to the mapping. The <b>Set_Member</b> procedure should save in the target -- object <b>Into</b> the value. If an error is detected, the procedure can raise the -- <b>Util.Serialize.Mappers.Field_Error</b> exception. The exception message will be -- reported by the IO reader as an error. with procedure Set_Member (Into : in out Element_Type; Field : in Fields; Value : in Util.Beans.Objects.Object); -- Adding a second function/procedure as generic parameter makes the -- Vector_Mapper generic package fail to instantiate a valid package. -- The failure occurs in Vector_Mapper in the 'with package Element_Mapper' instantiation. -- -- with function Get_Member (From : in Element_Type; -- Field : in Fields) return Util.Beans.Objects.Object; package Util.Serialize.Mappers.Record_Mapper is type Get_Member_Access is access function (From : in Element_Type; Field : in Fields) return Util.Beans.Objects.Object; -- Procedure to give access to the <b>Element_Type</b> object from the context. type Process_Object is not null access procedure (Ctx : in out Util.Serialize.Contexts.Context'Class; Attr : in Mapping'Class; Value : in Util.Beans.Objects.Object; Process : not null access procedure (Attr : in Mapping'Class; Item : in out Element_Type; Value : in Util.Beans.Objects.Object)); type Proxy_Object is not null access procedure (Attr : in Mapping'Class; Element : in out Element_Type; Value : in Util.Beans.Objects.Object); -- Set the attribute member described by the <b>Attr</b> mapping -- into the value passed in <b>Element</b>. This operation will call -- the package parameter function of the same name. procedure Set_Member (Attr : in Mapping'Class; Element : in out Element_Type; Value : in Util.Beans.Objects.Object); -- ----------------------- -- Data context -- ----------------------- -- Data context to get access to the target element. type Element_Data is new Util.Serialize.Contexts.Data with private; type Element_Data_Access is access all Element_Data'Class; -- Get the element object. function Get_Element (Data : in Element_Data) return Element_Type_Access; -- Set the element object. When <b>Release</b> is set, the element <b>Element</b> -- will be freed when the reader context is deleted (by <b>Finalize</b>). procedure Set_Element (Data : in out Element_Data; Element : in Element_Type_Access; Release : in Boolean := False); -- Finalize the object when it is removed from the reader context. -- If the <b>Release</b> parameter was set, the target element will be freed. overriding procedure Finalize (Data : in out Element_Data); -- ----------------------- -- Record mapper -- ----------------------- type Mapper is new Util.Serialize.Mappers.Mapper with private; type Mapper_Access is access all Mapper'Class; -- Execute the mapping operation on the object associated with the current context. -- The object is extracted from the context and the <b>Execute</b> operation is called. procedure Execute (Handler : in Mapper; Map : in Mapping'Class; Ctx : in out Util.Serialize.Contexts.Context'Class; Value : in Util.Beans.Objects.Object); -- Add a mapping for setting a member. When the attribute rule defined by <b>Path</b> -- is matched, the <b>Set_Member</b> procedure will be called with the value and the -- <b>Field</b> identification. procedure Add_Mapping (Into : in out Mapper; Path : in String; Field : in Fields); -- Add a mapping associated with the path and described by a mapper object. -- The <b>Proxy</b> procedure is in charge of giving access to the target -- object used by the <b>Map</b> mapper. procedure Add_Mapping (Into : in out Mapper; Path : in String; Map : in Util.Serialize.Mappers.Mapper_Access; Proxy : in Proxy_Object); -- Clone the <b>Handler</b> instance and get a copy of that single object. overriding function Clone (Handler : in Mapper) return Util.Serialize.Mappers.Mapper_Access; -- procedure Bind (Into : in out Mapper; Getter : in Get_Member_Access); procedure Bind (Into : in out Mapper; From : in Mapper_Access); function Get_Getter (From : in Mapper) return Get_Member_Access; -- Set the element in the context. When <b>Release</b> is set, the element <b>Element</b> -- will be freed when the reader context is deleted (by <b>Finalize</b>). procedure Set_Context (Ctx : in out Util.Serialize.Contexts.Context'Class; Element : in Element_Type_Access; Release : in Boolean := False); -- Build a default mapping based on the <b>Fields</b> enumeration. -- The enumeration name is used for the mapping name with the optional <b>FIELD_</b> -- prefix stripped. procedure Add_Default_Mapping (Into : in out Mapper); -- Write the element on the stream using the mapper description. procedure Write (Handler : in Mapper; Stream : in out Util.Serialize.IO.Output_Stream'Class; Element : in Element_Type); -- Write the element on the stream using the mapper description. procedure Write (Handler : in Util.Serialize.Mappers.Mapper'Class; Getter : in Get_Member_Access; Stream : in out Util.Serialize.IO.Output_Stream'Class; Element : in Element_Type); private type Element_Data is new Util.Serialize.Contexts.Data with record Element : Element_Type_Access; Release : Boolean; end record; type Mapper is new Util.Serialize.Mappers.Mapper with record Execute : Proxy_Object := Set_Member'Access; Get_Member : Get_Member_Access; end record; type Attribute_Mapping is new Mapping with record Index : Fields; end record; type Attribute_Mapping_Access is access all Attribute_Mapping'Class; procedure Set_Member (Attr : in Attribute_Mapping; Element : in out Element_Type; Value : in Util.Beans.Objects.Object); type Proxy_Mapper is new Mapper with null record; type Proxy_Mapper_Access is access all Proxy_Mapper'Class; -- Find the mapper associated with the given name. -- Returns null if there is no mapper. overriding function Find_Mapper (Controller : in Proxy_Mapper; Name : in String; Attribute : in Boolean := False) return Util.Serialize.Mappers.Mapper_Access; end Util.Serialize.Mappers.Record_Mapper;
Pragma Ada_2012; Pragma Assertion_Policy( Check ); Package EVIL.Util with Pure, SPARK_Mode => On is End EVIL.Util;
with Ada.Calendar; with Ada.Containers.Indefinite_Ordered_Maps; with Ada.Streams; private with Ada.Calendar.Formatting; private with Ada.Characters.Latin_1; package Web is use type Ada.Streams.Stream_Element_Offset; -- string map package String_Maps is new Ada.Containers.Indefinite_Ordered_Maps (String, String); function Element ( Map : String_Maps.Map; Key : String; Default : String := "") return String; function Element ( Map : String_Maps.Map; Key : String; Default : Ada.Streams.Stream_Element_Array := (-1 .. 0 => <>)) return Ada.Streams.Stream_Element_Array; procedure Include ( Map : in out String_Maps.Map; Key : in String; Item : in String) renames String_Maps.Include; procedure Include ( Map : in out String_Maps.Map; Key : in String; Item : in Ada.Streams.Stream_Element_Array); -- time subtype Time_Name is String (1 .. 29); -- "WWW, DD-MMM-YYYY HH:MM:SS GMT" function Image (Time : Ada.Calendar.Time) return Time_Name; function Value (Image : String) return Ada.Calendar.Time; -- protocol type Protocol is new String; HTTP : constant Protocol := "http://"; -- mime-type type Mime_Type is new String; Content_Multipart_Form_Data : constant Mime_Type := "multipart/form-data"; Content_URL_Encoded : constant Mime_Type := "application/x-www-form-urlencoded"; Text_Plain : constant Mime_Type := "text/plain"; Text_HTML : constant Mime_Type := "text/html"; Text_XML : constant Mime_Type := "text/xml"; Application_RSS_XML : constant Mime_Type := "application/rss+xml"; -- server function Host return String; function Compose (Protocol : Web.Protocol; Host, Path : String) return String; -- robots type Robots_Options is record No_Index : Boolean := False; No_Follow : Boolean := False; No_Archive : Boolean := False; No_Snippet : Boolean := False; No_Translate : Boolean := False; No_Image_Index : Boolean := False; end record; pragma Pack (Robots_Options); -- input function Request_URI return String; -- including query function Request_Path return String; -- excluding query function Remote_Addr return String; function Remote_Host return String; function User_Agent return String; function Post return Boolean; type Post_Encoded_Kind is (Miscellany, URL_Encoded, Multipart_Form_Data); function Get_Post_Length return Natural; function Get_Post_Encoded_Kind return Post_Encoded_Kind; function Encode_URI (S : String) return String; function Decode_URI (S : String) return String; subtype Query_Strings is String_Maps.Map; function Decode_Query_String (S : String) return Query_Strings; function Get_Query_Strings return Query_Strings; function Decode_Multipart_Form_Data (S : String) return Query_Strings; function Get (Stream : not null access Ada.Streams.Root_Stream_Type'Class) return Query_Strings; subtype Cookie is String_Maps.Map; function Get_Cookie return Cookie; -- output procedure Header_303 ( Stream : not null access Ada.Streams.Root_Stream_Type'Class; Location : in String); procedure Header_See_Other ( Stream : not null access Ada.Streams.Root_Stream_Type'Class; Location : in String) renames Header_303; procedure Header_503 ( Stream : not null access Ada.Streams.Root_Stream_Type'Class); procedure Header_Service_Unavailable ( Stream : not null access Ada.Streams.Root_Stream_Type'Class) renames Header_503; procedure Header_Content_Type ( Stream : not null access Ada.Streams.Root_Stream_Type'Class; Content : in Mime_Type); procedure Header_Cookie ( Stream : not null access Ada.Streams.Root_Stream_Type'Class; Cookie : in Web.Cookie; Expires : in Ada.Calendar.Time); procedure Header_Cookie ( Stream : not null access Ada.Streams.Root_Stream_Type'Class; Cookie : in Web.Cookie); procedure Header_X_Robots_Tag ( Stream : not null access Ada.Streams.Root_Stream_Type'Class; Options : in Robots_Options); procedure Header_Break ( Stream : not null access Ada.Streams.Root_Stream_Type'Class); generic Stream : not null access Ada.Streams.Root_Stream_Type'Class; procedure Generic_Write (Item : in String); private -- time subtype Year_Name is String (1 .. 4); function Year_Image (Year : Natural) return Year_Name; subtype Month_Name is String (1 .. 3); function Month_Image (Month : Ada.Calendar.Month_Number) return Month_Name; function Month_Value (S : String) return Ada.Calendar.Month_Number; subtype Day_Name is String (1 .. 3); function Day_Image (Day : Ada.Calendar.Formatting.Day_Name) return Day_Name; function Day_Value (S : String) return Ada.Calendar.Formatting.Day_Name; subtype String_2 is String (1 .. 2); function Z2_Image (Value : Natural) return String_2; -- input Content_Length_Variable : constant String := "CONTENT_LENGTH"; Content_Type_Variable : constant String := "CONTENT_TYPE"; HTTP_Cookie_Variable : constant String := "HTTP_COOKIE"; HTTP_Host_Variable : constant String := "HTTP_HOST"; HTTP_User_Agent_Variable : constant String := "HTTP_USER_AGENT"; Remote_Addr_Variable : constant String := "REMOTE_ADDR"; Remote_Host_Variable : constant String := "REMOTE_HOST"; Request_Method_Variable : constant String := "REQUEST_METHOD"; Request_URI_Variable : constant String := "REQUEST_URI"; Server_Name_Variable : constant String := "SERVER_NAME"; Query_String_Variable : constant String := "QUERY_STRING"; function Equal_Case_Insensitive (S, L : String) return Boolean; function Prefixed_Case_Insensitive (S, L_Prefix : String) return Boolean; -- output Line_Break : aliased constant String := (1 => Ada.Characters.Latin_1.LF); end Web;
with AdaBase.Results.Sets; with Connect; with CommonText; with Ada.Text_IO; procedure Iterate is package CON renames Connect; package TIO renames Ada.Text_IO; package AR renames AdaBase.Results; package CT renames CommonText; fruit : aliased AR.Textual; color : aliased AR.Textual; calories : aliased AR.NByte2; dashes : String (1 .. 50) := (others => '='); procedure list_fruit; procedure list_hockey_teams (row : AR.Sets.Datarow); procedure list_fruit is pair : String := CT.USS (fruit) & " (" & CT.USS (color) & ")"; plen : Natural := pair'Length; zone : String (1 .. 20) := (others => ' '); begin zone (1 .. plen) := pair; TIO.Put_Line (zone & " contains" & calories'Img & " calories"); end list_fruit; procedure list_hockey_teams (row : AR.Sets.Datarow) is begin TIO.Put_Line (row.column ("city").as_string & " " & row.column ("mascot").as_string & " (" & row.column ("abbreviation").as_string & ")"); end list_hockey_teams; begin CON.connect_database; declare stmt : CON.Stmt_Type := CON.DR.query_select (tables => "fruits", columns => "fruit, calories, color", conditions => "calories >= 50", order => "calories"); begin stmt.bind ("fruit", fruit'Unchecked_Access); stmt.bind ("calories", calories'Unchecked_Access); stmt.bind ("color", color'Unchecked_Access); TIO.Put_Line ("Demonstrate STMT.iterate (query + bound variables)"); TIO.Put_Line (dashes); TIO.Put_Line ("List of fruit the contain at least 50 calories"); TIO.Put_Line (dashes); stmt.iterate (process => list_fruit'Access); end; declare stmt : CON.Stmt_Type := CON.DR.prepare_select (tables => "nhl_teams", columns => "*", conditions => "city LIKE :pattern", order => "city"); begin TIO.Put_Line (""); TIO.Put_Line ("Demonstrate STMT.iterate (prepare + data access)"); TIO.Put_Line (dashes); TIO.Put_Line ("List of NHL teams in locations starting with 'C'"); TIO.Put_Line (dashes); stmt.assign ("pattern", "C%"); if stmt.execute then stmt.iterate (process => list_hockey_teams'Access); end if; end; CON.DR.disconnect; end Iterate;
private with GStreamer.GST_Low_Level.Gstreamer_0_10_Gst_Rtsp_Gstrtspurl_H; with Glib; with System; with Ada.Finalization; with GNAT.Sockets; package GStreamer.Rtsp.url is DEFAULT_PORT : constant := 554; type GstRTSPUrl (<>)is tagged private; function Get_Type return GLIB.GType; function Parse (Urlstr : String) return GstRTSPUrl; function Get_Request_Uri (Arg1 : GstRTSPUrl) return String; function Decode_Path_Components (Url : GstRTSPUrl) return System.Address; procedure Set_Port (Url : GstRTSPUrl; Port : GNAT.Sockets.Port_Type); function Get_Port (Url : GstRTSPUrl) return GNAT.Sockets.Port_Type; private type GstRTSPUrl is new Ada.Finalization.Controlled with record Data : aliased GStreamer.GST_Low_Level.Gstreamer_0_10_Gst_Rtsp_Gstrtspurl_H.GstRTSPUrl; end record; end GStreamer.Rtsp.url;
with GLOBE_3D; package Sierpinski is type Cubic_Face_count is new Integer range 1 .. 6; type Cubic_Face_texture is array (Cubic_Face_count) of GLOBE_3D.Image_id; procedure Create_Cube ( object : in out GLOBE_3D.p_Object_3D; scale : GLOBE_3D.Real; centre : GLOBE_3D.Point_3D; texture : Cubic_Face_texture; tiled : Boolean; fractal_level : Natural ); end Sierpinski;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS -- -- -- -- S Y S T E M . T A S K I N G . D E B U G -- -- -- -- B o d y -- -- -- -- Copyright (C) 1997-2005 Free Software Foundation, Inc. -- -- -- -- GNARL is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNARL is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNARL; see file COPYING. If not, write -- -- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, -- -- Boston, MA 02110-1301, USA. -- -- -- -- 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. -- -- Extensive contributions were provided by Ada Core Technologies, Inc. -- -- -- ------------------------------------------------------------------------------ -- This package encapsulates all direct interfaces to task debugging services -- that are needed by gdb with gnat mode. -- Note : This file *must* be compiled with debugging information -- Do not add any dependency to GNARL packages since this package is used -- in both normal and restricted (ravenscar) environments. with System.CRTL; with System.Task_Primitives.Operations; with Unchecked_Conversion; package body System.Tasking.Debug is package STPO renames System.Task_Primitives.Operations; function To_Integer is new Unchecked_Conversion (Task_Id, System.Address); type Trace_Flag_Set is array (Character) of Boolean; Trace_On : Trace_Flag_Set := ('A' .. 'Z' => False, others => True); ----------------------- -- Local Subprograms -- ----------------------- procedure Write (Fd : Integer; S : String; Count : Integer); procedure Put (S : String); -- Display S on standard output. procedure Put_Line (S : String := ""); -- Display S on standard output with an additional line terminator. -------------------- -- Get_User_State -- -------------------- function Get_User_State return Long_Integer is begin return STPO.Self.User_State; end Get_User_State; ---------------- -- List_Tasks -- ---------------- procedure List_Tasks is C : Task_Id; begin C := All_Tasks_List; while C /= null loop Print_Task_Info (C); C := C.Common.All_Tasks_Link; end loop; end List_Tasks; ------------------------ -- Print_Current_Task -- ------------------------ procedure Print_Current_Task is begin Print_Task_Info (STPO.Self); end Print_Current_Task; --------------------- -- Print_Task_Info -- --------------------- procedure Print_Task_Info (T : Task_Id) is Entry_Call : Entry_Call_Link; Parent : Task_Id; begin if T = null then Put_Line ("null task"); return; end if; Put (T.Common.Task_Image (1 .. T.Common.Task_Image_Len) & ": " & Task_States'Image (T.Common.State)); Parent := T.Common.Parent; if Parent = null then Put (", parent: <none>"); else Put (", parent: " & Parent.Common.Task_Image (1 .. Parent.Common.Task_Image_Len)); end if; Put (", prio:" & T.Common.Current_Priority'Img); if not T.Callable then Put (", not callable"); end if; if T.Aborting then Put (", aborting"); end if; if T.Deferral_Level /= 0 then Put (", abort deferred"); end if; if T.Common.Call /= null then Entry_Call := T.Common.Call; Put (", serving:"); while Entry_Call /= null loop Put (To_Integer (Entry_Call.Self)'Img); Entry_Call := Entry_Call.Acceptor_Prev_Call; end loop; end if; if T.Open_Accepts /= null then Put (", accepting:"); for J in T.Open_Accepts'Range loop Put (T.Open_Accepts (J).S'Img); end loop; if T.Terminate_Alternative then Put (" or terminate"); end if; end if; if T.User_State /= 0 then Put (", state:" & T.User_State'Img); end if; Put_Line; end Print_Task_Info; --------- -- Put -- --------- procedure Put (S : String) is begin Write (2, S, S'Length); end Put; -------------- -- Put_Line -- -------------- procedure Put_Line (S : String := "") is begin Write (2, S & ASCII.LF, S'Length + 1); end Put_Line; ---------------------- -- Resume_All_Tasks -- ---------------------- procedure Resume_All_Tasks (Thread_Self : OS_Interface.Thread_Id) is C : Task_Id; Dummy : Boolean; pragma Unreferenced (Dummy); begin STPO.Lock_RTS; C := All_Tasks_List; while C /= null loop Dummy := STPO.Resume_Task (C, Thread_Self); C := C.Common.All_Tasks_Link; end loop; STPO.Unlock_RTS; end Resume_All_Tasks; --------------- -- Set_Trace -- --------------- procedure Set_Trace (Flag : Character; Value : Boolean := True) is begin Trace_On (Flag) := Value; end Set_Trace; -------------------- -- Set_User_State -- -------------------- procedure Set_User_State (Value : Long_Integer) is begin STPO.Self.User_State := Value; end Set_User_State; ----------------------- -- Suspend_All_Tasks -- ----------------------- procedure Suspend_All_Tasks (Thread_Self : OS_Interface.Thread_Id) is C : Task_Id; Dummy : Boolean; pragma Unreferenced (Dummy); begin STPO.Lock_RTS; C := All_Tasks_List; while C /= null loop Dummy := STPO.Suspend_Task (C, Thread_Self); C := C.Common.All_Tasks_Link; end loop; STPO.Unlock_RTS; end Suspend_All_Tasks; ------------------------ -- Task_Creation_Hook -- ------------------------ procedure Task_Creation_Hook (Thread : OS_Interface.Thread_Id) is pragma Inspection_Point (Thread); -- gdb needs to access the thread parameter in order to implement -- the multitask mode under VxWorks. begin null; end Task_Creation_Hook; --------------------------- -- Task_Termination_Hook -- --------------------------- procedure Task_Termination_Hook is begin null; end Task_Termination_Hook; ----------- -- Trace -- ----------- procedure Trace (Self_Id : Task_Id; Msg : String; Flag : Character; Other_Id : Task_Id := null) is begin if Trace_On (Flag) then Put (To_Integer (Self_Id)'Img & ':' & Flag & ':' & Self_Id.Common.Task_Image (1 .. Self_Id.Common.Task_Image_Len) & ':'); if Other_Id /= null then Put (To_Integer (Other_Id)'Img & ':'); end if; Put_Line (Msg); end if; end Trace; ----------- -- Write -- ----------- procedure Write (Fd : Integer; S : String; Count : Integer) is Discard : Integer; pragma Unreferenced (Discard); begin Discard := System.CRTL.write (Fd, S (S'First)'Address, Count); -- Is it really right to ignore write errors here ??? end Write; end System.Tasking.Debug;
with physics.Shape, physics.Model, lace.Any; package physics.Object -- -- Provide an interface for physics objects. -- is use Math; type Item is limited interface and lace.Any.limited_item; type View is access all Item'Class; type Views is array (Positive range <>) of View; ---------- --- Forge -- procedure define (Self : access Item; Shape : in physics.Shape.view; Mass : in Real; Friction : in Real; Restitution : in Real; at_Site : in Vector_3) is abstract; procedure destruct (Self : in out Item) is abstract; procedure free (Self : in out View); --------------- --- Attributes -- procedure user_Data_is (Self : in out Item; Now : access lace.Any.limited_item'Class) is abstract; function user_Data (Self : in Item) return access lace.Any.limited_item'Class is abstract; function Mass (Self : in Item) return Real is abstract; function Model (Self : in Item) return physics.Model.view is abstract; procedure Model_is (Self : in out Item; Now : in physics.Model.view) is abstract; function Shape (Self : in Item) return physics.Shape.view is abstract; function Scale (Self : in Item) return Vector_3 is abstract; procedure Scale_is (Self : in out Item; Now : in Vector_3) is abstract; --- Dynamics -- protected type safe_Dynamics is procedure set (To : in Matrix_4x4); function get return Matrix_4x4; procedure set_Spin (To : in Matrix_3x3); function get_Spin return Matrix_3x3; procedure set_Site (To : in Vector_3); function get_Site return Vector_3; private Dynamics : Matrix_4x4 := Identity_4x4; end safe_Dynamics; procedure update_Dynamics (Self : in out Item) is abstract; function get_Dynamics (Self : in Item) return Matrix_4x4 is abstract; procedure activate (Self : in out Item; force_Activation : in Boolean := False) is abstract; function Site (Self : in Item) return Vector_3 is abstract; procedure Site_is (Self : in out Item; Now : in Vector_3) is abstract; function Spin (Self : in Item) return Matrix_3x3 is abstract; procedure Spin_is (Self : in out Item; Now : in Matrix_3x3) is abstract; function xy_Spin (Self : in Item) return Radians is abstract; procedure xy_Spin_is (Self : in out Item; Now : in Radians) is abstract; function Transform (Self : in Item) return Matrix_4x4 is abstract; procedure Transform_is (Self : in out Item; Now : in Matrix_4x4) is abstract; function Speed (Self : in Item) return Vector_3 is abstract; procedure Speed_is (Self : in out Item; Now : in Vector_3) is abstract; function Gyre (Self : in Item) return Vector_3 is abstract; procedure Gyre_is (Self : in out Item; Now : in Vector_3) is abstract; function is_Active (Self : in Item) return Boolean is abstract; procedure Friction_is (Self : in out Item; Now : in Real) is abstract; procedure Restitution_is (Self : in out Item; Now : in Real) is abstract; --------------- --- Operations -- --- Forces -- procedure apply_Torque (Self : in out Item; Torque : in Vector_3) is abstract; procedure apply_Torque_impulse (Self : in out Item; Torque : in Vector_3) is abstract; procedure apply_Force (Self : in out Item; Force : in Vector_3) is abstract; end physics.Object;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- S Y S T E M . F I N A L I Z A T I O N _ M A S T E R S -- -- -- -- B o d y -- -- -- -- Copyright (C) 2015-2019, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Ada.Exceptions; use Ada.Exceptions; with System.Address_Image; with System.HTable; use System.HTable; with System.IO; use System.IO; with System.Soft_Links; use System.Soft_Links; with System.Storage_Elements; use System.Storage_Elements; package body System.Finalization_Masters is -- Finalize_Address hash table types. In general, masters are homogeneous -- collections of controlled objects. Rare cases such as allocations on a -- subpool require heterogeneous masters. The following table provides a -- relation between object address and its Finalize_Address routine. type Header_Num is range 0 .. 127; function Hash (Key : System.Address) return Header_Num; -- Address --> Finalize_Address_Ptr package Finalize_Address_Table is new Simple_HTable (Header_Num => Header_Num, Element => Finalize_Address_Ptr, No_Element => null, Key => System.Address, Hash => Hash, Equal => "="); --------------------------- -- Add_Offset_To_Address -- --------------------------- function Add_Offset_To_Address (Addr : System.Address; Offset : System.Storage_Elements.Storage_Offset) return System.Address is begin return System.Storage_Elements."+" (Addr, Offset); end Add_Offset_To_Address; ------------ -- Attach -- ------------ procedure Attach (N : not null FM_Node_Ptr; L : not null FM_Node_Ptr) is begin Lock_Task.all; Attach_Unprotected (N, L); Unlock_Task.all; -- Note: No need to unlock in case of an exception because the above -- code can never raise one. end Attach; ------------------------ -- Attach_Unprotected -- ------------------------ procedure Attach_Unprotected (N : not null FM_Node_Ptr; L : not null FM_Node_Ptr) is begin L.Next.Prev := N; N.Next := L.Next; L.Next := N; N.Prev := L; end Attach_Unprotected; --------------- -- Base_Pool -- --------------- function Base_Pool (Master : Finalization_Master) return Any_Storage_Pool_Ptr is begin return Master.Base_Pool; end Base_Pool; ----------------------------------------- -- Delete_Finalize_Address_Unprotected -- ----------------------------------------- procedure Delete_Finalize_Address_Unprotected (Obj : System.Address) is begin Finalize_Address_Table.Remove (Obj); end Delete_Finalize_Address_Unprotected; ------------ -- Detach -- ------------ procedure Detach (N : not null FM_Node_Ptr) is begin Lock_Task.all; Detach_Unprotected (N); Unlock_Task.all; -- Note: No need to unlock in case of an exception because the above -- code can never raise one. end Detach; ------------------------ -- Detach_Unprotected -- ------------------------ procedure Detach_Unprotected (N : not null FM_Node_Ptr) is begin if N.Prev /= null and then N.Next /= null then N.Prev.Next := N.Next; N.Next.Prev := N.Prev; N.Prev := null; N.Next := null; end if; end Detach_Unprotected; -------------- -- Finalize -- -------------- overriding procedure Finalize (Master : in out Finalization_Master) is Cleanup : Finalize_Address_Ptr; Curr_Ptr : FM_Node_Ptr; Ex_Occur : Exception_Occurrence; Obj_Addr : Address; Raised : Boolean := False; function Is_Empty_List (L : not null FM_Node_Ptr) return Boolean; -- Determine whether a list contains only one element, the dummy head ------------------- -- Is_Empty_List -- ------------------- function Is_Empty_List (L : not null FM_Node_Ptr) return Boolean is begin return L.Next = L and then L.Prev = L; end Is_Empty_List; -- Start of processing for Finalize begin Lock_Task.all; -- Synchronization: -- Read - allocation, finalization -- Write - finalization if Master.Finalization_Started then Unlock_Task.all; -- Double finalization may occur during the handling of stand alone -- libraries or the finalization of a pool with subpools. Due to the -- potential aliasing of masters in these two cases, do not process -- the same master twice. return; end if; -- Lock the master to prevent any allocations while the objects are -- being finalized. The master remains locked because either the master -- is explicitly deallocated or the associated access type is about to -- go out of scope. -- Synchronization: -- Read - allocation, finalization -- Write - finalization Master.Finalization_Started := True; while not Is_Empty_List (Master.Objects'Unchecked_Access) loop Curr_Ptr := Master.Objects.Next; -- Synchronization: -- Write - allocation, deallocation, finalization Detach_Unprotected (Curr_Ptr); -- Skip the list header in order to offer proper object layout for -- finalization. Obj_Addr := Curr_Ptr.all'Address + Header_Size; -- Retrieve TSS primitive Finalize_Address depending on the master's -- mode of operation. -- Synchronization: -- Read - allocation, finalization -- Write - outside if Master.Is_Homogeneous then -- Synchronization: -- Read - finalization -- Write - allocation, outside Cleanup := Master.Finalize_Address; else -- Synchronization: -- Read - finalization -- Write - allocation, deallocation Cleanup := Finalize_Address_Unprotected (Obj_Addr); end if; begin Cleanup (Obj_Addr); exception when Fin_Occur : others => if not Raised then Raised := True; Save_Occurrence (Ex_Occur, Fin_Occur); end if; end; -- When the master is a heterogeneous collection, destroy the object -- - Finalize_Address pair since it is no longer needed. -- Synchronization: -- Read - finalization -- Write - outside if not Master.Is_Homogeneous then -- Synchronization: -- Read - finalization -- Write - allocation, deallocation, finalization Delete_Finalize_Address_Unprotected (Obj_Addr); end if; end loop; Unlock_Task.all; -- If the finalization of a particular object failed or Finalize_Address -- was not set, reraise the exception now. if Raised then Reraise_Occurrence (Ex_Occur); end if; end Finalize; ---------------------- -- Finalize_Address -- ---------------------- function Finalize_Address (Master : Finalization_Master) return Finalize_Address_Ptr is begin return Master.Finalize_Address; end Finalize_Address; ---------------------------------- -- Finalize_Address_Unprotected -- ---------------------------------- function Finalize_Address_Unprotected (Obj : System.Address) return Finalize_Address_Ptr is begin return Finalize_Address_Table.Get (Obj); end Finalize_Address_Unprotected; -------------------------- -- Finalization_Started -- -------------------------- function Finalization_Started (Master : Finalization_Master) return Boolean is begin return Master.Finalization_Started; end Finalization_Started; ---------- -- Hash -- ---------- function Hash (Key : System.Address) return Header_Num is begin return Header_Num (To_Integer (Key) mod Integer_Address (Header_Num'Range_Length)); end Hash; ----------------- -- Header_Size -- ----------------- function Header_Size return System.Storage_Elements.Storage_Count is begin return FM_Node'Size / Storage_Unit; end Header_Size; ---------------- -- Initialize -- ---------------- overriding procedure Initialize (Master : in out Finalization_Master) is begin -- The dummy head must point to itself in both directions Master.Objects.Next := Master.Objects'Unchecked_Access; Master.Objects.Prev := Master.Objects'Unchecked_Access; end Initialize; -------------------- -- Is_Homogeneous -- -------------------- function Is_Homogeneous (Master : Finalization_Master) return Boolean is begin return Master.Is_Homogeneous; end Is_Homogeneous; ------------- -- Objects -- ------------- function Objects (Master : Finalization_Master) return FM_Node_Ptr is begin return Master.Objects'Unrestricted_Access; end Objects; ------------------ -- Print_Master -- ------------------ procedure Print_Master (Master : Finalization_Master) is Head : constant FM_Node_Ptr := Master.Objects'Unrestricted_Access; Head_Seen : Boolean := False; N_Ptr : FM_Node_Ptr; begin -- Output the basic contents of a master -- Master : 0x123456789 -- Is_Hmgen : TURE <or> FALSE -- Base_Pool: null <or> 0x123456789 -- Fin_Addr : null <or> 0x123456789 -- Fin_Start: TRUE <or> FALSE Put ("Master : "); Put_Line (Address_Image (Master'Address)); Put ("Is_Hmgen : "); Put_Line (Master.Is_Homogeneous'Img); Put ("Base_Pool: "); if Master.Base_Pool = null then Put_Line ("null"); else Put_Line (Address_Image (Master.Base_Pool'Address)); end if; Put ("Fin_Addr : "); if Master.Finalize_Address = null then Put_Line ("null"); else Put_Line (Address_Image (Master.Finalize_Address'Address)); end if; Put ("Fin_Start: "); Put_Line (Master.Finalization_Started'Img); -- Output all chained elements. The format is the following: -- ^ <or> ? <or> null -- |Header: 0x123456789 (dummy head) -- | Prev: 0x123456789 -- | Next: 0x123456789 -- V -- ^ - the current element points back to the correct element -- ? - the current element points back to an erroneous element -- n - the current element points back to null -- Header - the address of the list header -- Prev - the address of the list header which the current element -- points back to -- Next - the address of the list header which the current element -- points to -- (dummy head) - present if dummy head N_Ptr := Head; while N_Ptr /= null loop -- Should never be null Put_Line ("V"); -- We see the head initially; we want to exit when we see the head a -- second time. if N_Ptr = Head then exit when Head_Seen; Head_Seen := True; end if; -- The current element is null. This should never happen since the -- list is circular. if N_Ptr.Prev = null then Put_Line ("null (ERROR)"); -- The current element points back to the correct element elsif N_Ptr.Prev.Next = N_Ptr then Put_Line ("^"); -- The current element points to an erroneous element else Put_Line ("? (ERROR)"); end if; -- Output the header and fields Put ("|Header: "); Put (Address_Image (N_Ptr.all'Address)); -- Detect the dummy head if N_Ptr = Head then Put_Line (" (dummy head)"); else Put_Line (""); end if; Put ("| Prev: "); if N_Ptr.Prev = null then Put_Line ("null"); else Put_Line (Address_Image (N_Ptr.Prev.all'Address)); end if; Put ("| Next: "); if N_Ptr.Next = null then Put_Line ("null"); else Put_Line (Address_Image (N_Ptr.Next.all'Address)); end if; N_Ptr := N_Ptr.Next; end loop; end Print_Master; ------------------- -- Set_Base_Pool -- ------------------- procedure Set_Base_Pool (Master : in out Finalization_Master; Pool_Ptr : Any_Storage_Pool_Ptr) is begin Master.Base_Pool := Pool_Ptr; end Set_Base_Pool; -------------------------- -- Set_Finalize_Address -- -------------------------- procedure Set_Finalize_Address (Master : in out Finalization_Master; Fin_Addr_Ptr : Finalize_Address_Ptr) is begin -- Synchronization: -- Read - finalization -- Write - allocation, outside Lock_Task.all; Set_Finalize_Address_Unprotected (Master, Fin_Addr_Ptr); Unlock_Task.all; end Set_Finalize_Address; -------------------------------------- -- Set_Finalize_Address_Unprotected -- -------------------------------------- procedure Set_Finalize_Address_Unprotected (Master : in out Finalization_Master; Fin_Addr_Ptr : Finalize_Address_Ptr) is begin if Master.Finalize_Address = null then Master.Finalize_Address := Fin_Addr_Ptr; end if; end Set_Finalize_Address_Unprotected; ---------------------------------------------------- -- Set_Heterogeneous_Finalize_Address_Unprotected -- ---------------------------------------------------- procedure Set_Heterogeneous_Finalize_Address_Unprotected (Obj : System.Address; Fin_Addr_Ptr : Finalize_Address_Ptr) is begin Finalize_Address_Table.Set (Obj, Fin_Addr_Ptr); end Set_Heterogeneous_Finalize_Address_Unprotected; -------------------------- -- Set_Is_Heterogeneous -- -------------------------- procedure Set_Is_Heterogeneous (Master : in out Finalization_Master) is begin -- Synchronization: -- Read - finalization -- Write - outside Lock_Task.all; Master.Is_Homogeneous := False; Unlock_Task.all; end Set_Is_Heterogeneous; end System.Finalization_Masters;
----------------------------------------------------------------------- -- csstools -- CSS Tools Command -- Copyright (C) 2017, 2018, 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 GNAT.Command_Line; use GNAT.Command_Line; with GNAT.Traceback.Symbolic; with Ada.Containers; with Ada.Strings.Unbounded; with Ada.Text_IO; with Ada.Command_Line; with Ada.Directories; with Ada.Exceptions; with Util.Log.Loggers; with Util.Files; with Util.Commands; with CSS.Parser.Lexer_dfa; with CSS.Analysis.Parser.Lexer_dfa; with CSS.Core; with CSS.Tools.Messages; with CSS.Printer.Text_IO; with CSS.Analysis.Parser; with CSS.Analysis.Rules.Main; with CSS.Tools.Configs; with CSS.Commands; procedure CssTools is use Ada.Strings.Unbounded; use Ada.Containers; use Ada.Directories; use Ada.Command_Line; procedure Print_Message (Severity : in CSS.Tools.Messages.Severity_Type; Loc : in CSS.Core.Location; Message : in String); procedure Set_Config_Directory (Path : in String; Silent : in Boolean := False); Debug : Boolean := False; Verbose : Boolean := False; Quiet : Boolean := False; Status : Exit_Status := Success; Output_Path : Unbounded_String; Report_Path : Unbounded_String; Config_Dir : Unbounded_String; Output : CSS.Printer.Text_IO.File_Type; Report : CSS.Printer.Text_IO.File_Type; Context : CSS.Commands.Context_Type; First : Natural := 0; Console : aliased CSS.Commands.Text_Consoles.Console_Type; All_Args : Util.Commands.Default_Argument_List (0); -- ------------------------------ -- Verify and set the configuration path -- ------------------------------ procedure Set_Config_Directory (Path : in String; Silent : in Boolean := False) is Log_Path : constant String := Ada.Directories.Compose (Path, "csstools.properties"); begin -- Ignore if the config directory was already set. if Length (Config_Dir) > 0 then return; end if; -- Check that we can read some configuration file. if not Ada.Directories.Exists (Log_Path) then if not Silent then Ada.Text_IO.Put_Line ("Invalid config directory: " & Path); Status := Failure; end if; return; end if; -- Configure the logs Util.Log.Loggers.Initialize (Log_Path); Config_Dir := To_Unbounded_String (Path); end Set_Config_Directory; procedure Print_Message (Severity : in CSS.Tools.Messages.Severity_Type; Loc : in CSS.Core.Location; Message : in String) is use CSS.Tools.Messages; begin Ada.Text_IO.Put (CSS.Core.To_String (Loc)); Ada.Text_IO.Put (":"); if Severity = MSG_ERROR then Ada.Text_IO.Put ("error: "); elsif Severity = MSG_WARNING then Ada.Text_IO.Put ("warning: "); else Ada.Text_IO.Put ("info: "); end if; Ada.Text_IO.Put_Line (Message); end Print_Message; Config_Path : Ada.Strings.Unbounded.Unbounded_String; begin CSS.Commands.Initialize (Context); Context.Console := Console'Unchecked_Access; Initialize_Option_Scan (Stop_At_First_Non_Switch => True, Section_Delimiters => "targs"); Output.Compress := True; Report.Compress := False; Report.Indent_Level := 4; Report.Full_Semi := True; -- Parse the command line begin loop case Getopt ("* v p d q r: R: c: o: ") is when ASCII.NUL => exit; when 'c' => Set_Config_Directory (Parameter); when 'R' => Config_Path := To_Unbounded_String (Parameter); when 'r' => Report_Path := To_Unbounded_String (Parameter); when 'o' => Output_Path := To_Unbounded_String (Parameter); when 'd' => Debug := True; when 'p' => Output.Indent_Level := 4; Output.Full_Semi := True; Output.Compress := False; when 'v' => Verbose := True; when 'q' => Quiet := True; when '*' => exit; when others => null; end case; First := First + 1; end loop; exception when others => CSS.Commands.Driver.Usage (All_Args, Context); Ada.Command_Line.Set_Exit_Status (2); return; end; if Length (Config_Dir) = 0 then declare Name : constant String := Ada.Command_Line.Command_Name; Path : constant String := Ada.Directories.Containing_Directory (Name); Dir : constant String := Ada.Directories.Containing_Directory (Path); begin Set_Config_Directory (Compose (Dir, "config"), True); Set_Config_Directory (Util.Files.Compose (Dir, "share/csstools"), True); Set_Config_Directory (CSS.Tools.Configs.CONFIG_DIR, True); end; end if; if Length (Config_Path) > 0 then CSS.Analysis.Parser.Load (To_String (Config_Path), CSS.Analysis.Rules.Main.Rule_Repository); end if; if Length (Config_Dir) > 0 then CSS.Analysis.Parser.Load_All (To_String (Config_Dir) & "/rules", CSS.Analysis.Rules.Main.Rule_Repository); end if; CSS.Parser.Lexer_dfa.aflex_debug := Debug; CSS.Analysis.Parser.Lexer_dfa.aflex_debug := Debug; if Length (Output_Path) > 0 then Ada.Text_IO.Create (Output.File, Ada.Text_IO.Out_File, To_String (Output_Path)); end if; if Length (Report_Path) > 0 then Ada.Text_IO.Create (Report.File, Ada.Text_IO.Out_File, To_String (Report_Path)); end if; if Verbose then CSS.Analysis.Rules.Print (Report, CSS.Analysis.Rules.Main.Rule_Repository.all); end if; if First >= Ada.Command_Line.Argument_Count then Ada.Text_IO.Put_Line ("Missing command name to execute."); CSS.Commands.Driver.Usage (All_Args, Context); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); return; end if; declare Cmd_Name : constant String := Full_Switch; Args : Util.Commands.Default_Argument_List (First + 1); begin CSS.Commands.Driver.Execute (Cmd_Name, Args, Context); end; if Context.Err_Handler.Get_Error_Count > 0 then Status := Failure; end if; Context.Err_Handler.Iterate (Print_Message'Access); -- loop -- declare -- Path : constant String := Get_Argument; -- begin -- exit when Path'Length = 0; -- Doc.Set_Href (Path); -- CSS.Parser.Load (Path, Doc'Unchecked_Access, Err_Handler'Unchecked_Access); -- if Analyze_Flag then -- CSS.Analysis.Duplicates.Analyze (Doc.Rules, Err_Handler, Dup_Rules); -- CSS.Analysis.Rules.Main.Analyze (Doc, Err_Handler); -- end if; -- Err_Handler.Iterate (Print_Message'Access); -- if Length (Output_Path) > 0 then -- Output.Print (Doc); -- end if; -- if Err_Handler.Get_Error_Count > 0 then -- Status := Failure; -- end if; -- if Analyze_Flag then -- CSS.Analysis.Classes.Analyze (Doc, Class_Map, Err_Handler); -- end if; -- end; -- end loop; -- if Length (Report_Path) > 0 then -- CSS.Reports.Docs.Print (Report, Class_Map); -- end if; -- if not Quiet then -- if Verbose then -- Ada.Text_IO.Put_Line ("Comments: "); -- Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (CSS.Parser.Lexer.Current_Comment)); -- end if; -- Ada.Text_IO.Put_Line ("Errors : " & Natural'Image (Context.Err_Handler.Get_Error_Count)); -- Ada.Text_IO.Put_Line ("Warnings : " & Natural'Image (Context.Err_Handler.Get_Warning_Count)); -- Ada.Text_IO.Put_Line ("CSS rules : " & Count_Type'Image (Context.Doc.Rules.Length)); -- Ada.Text_IO.Put_Line ("CSS values : " & Natural'Image (Context.Doc.Values.Length)); -- Ada.Text_IO.Put_Line ("CSS classes : " & Count_Type'Image (Context.Class_Map.Length)); -- Ada.Text_IO.Put_Line ("Duplicate rules : " & Count_Type'Image (Context.Dup_Rules.Length)); -- end if; Ada.Command_Line.Set_Exit_Status (Status); exception when E : Invalid_Switch => Ada.Text_IO.Put_Line ("Invalid option: " & Ada.Exceptions.Exception_Message (E)); CSS.Commands.Driver.Usage (All_Args, Context); Ada.Command_Line.Set_Exit_Status (2); when E : others => Context.Err_Handler.Iterate (Print_Message'Access); Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Message (E)); Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E)); Ada.Command_Line.Set_Exit_Status (1); end CssTools;
-- Copyright (c) 2010 - 2018, Nordic Semiconductor ASA -- -- 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, except as embedded into a Nordic -- Semiconductor ASA integrated circuit in a product or a software update for -- such product, 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 Nordic Semiconductor ASA nor the names of its -- contributors may be used to endorse or promote products derived from this -- software without specific prior written permission. -- -- 4. This software, with or without modification, must only be used with a -- Nordic Semiconductor ASA integrated circuit. -- -- 5. Any software provided in binary form under this license must not be reverse -- engineered, decompiled, modified and/or disassembled. -- -- THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS -- OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES -- OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE -- DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE -- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE -- GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -- LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT -- OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- This spec has been automatically generated from nrf52.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with HAL; with System; package NRF_SVD.QDEC is pragma Preelaborate; --------------- -- Registers -- --------------- -- Shortcut between REPORTRDY event and READCLRACC task type SHORTS_REPORTRDY_READCLRACC_Field is (-- Disable shortcut Disabled, -- Enable shortcut Enabled) with Size => 1; for SHORTS_REPORTRDY_READCLRACC_Field use (Disabled => 0, Enabled => 1); -- Shortcut between SAMPLERDY event and STOP task type SHORTS_SAMPLERDY_STOP_Field is (-- Disable shortcut Disabled, -- Enable shortcut Enabled) with Size => 1; for SHORTS_SAMPLERDY_STOP_Field use (Disabled => 0, Enabled => 1); -- Shortcut between REPORTRDY event and RDCLRACC task type SHORTS_REPORTRDY_RDCLRACC_Field is (-- Disable shortcut Disabled, -- Enable shortcut Enabled) with Size => 1; for SHORTS_REPORTRDY_RDCLRACC_Field use (Disabled => 0, Enabled => 1); -- Shortcut between REPORTRDY event and STOP task type SHORTS_REPORTRDY_STOP_Field is (-- Disable shortcut Disabled, -- Enable shortcut Enabled) with Size => 1; for SHORTS_REPORTRDY_STOP_Field use (Disabled => 0, Enabled => 1); -- Shortcut between DBLRDY event and RDCLRDBL task type SHORTS_DBLRDY_RDCLRDBL_Field is (-- Disable shortcut Disabled, -- Enable shortcut Enabled) with Size => 1; for SHORTS_DBLRDY_RDCLRDBL_Field use (Disabled => 0, Enabled => 1); -- Shortcut between DBLRDY event and STOP task type SHORTS_DBLRDY_STOP_Field is (-- Disable shortcut Disabled, -- Enable shortcut Enabled) with Size => 1; for SHORTS_DBLRDY_STOP_Field use (Disabled => 0, Enabled => 1); -- Shortcut between SAMPLERDY event and READCLRACC task type SHORTS_SAMPLERDY_READCLRACC_Field is (-- Disable shortcut Disabled, -- Enable shortcut Enabled) with Size => 1; for SHORTS_SAMPLERDY_READCLRACC_Field use (Disabled => 0, Enabled => 1); -- Shortcut register type SHORTS_Register is record -- Shortcut between REPORTRDY event and READCLRACC task REPORTRDY_READCLRACC : SHORTS_REPORTRDY_READCLRACC_Field := NRF_SVD.QDEC.Disabled; -- Shortcut between SAMPLERDY event and STOP task SAMPLERDY_STOP : SHORTS_SAMPLERDY_STOP_Field := NRF_SVD.QDEC.Disabled; -- Shortcut between REPORTRDY event and RDCLRACC task REPORTRDY_RDCLRACC : SHORTS_REPORTRDY_RDCLRACC_Field := NRF_SVD.QDEC.Disabled; -- Shortcut between REPORTRDY event and STOP task REPORTRDY_STOP : SHORTS_REPORTRDY_STOP_Field := NRF_SVD.QDEC.Disabled; -- Shortcut between DBLRDY event and RDCLRDBL task DBLRDY_RDCLRDBL : SHORTS_DBLRDY_RDCLRDBL_Field := NRF_SVD.QDEC.Disabled; -- Shortcut between DBLRDY event and STOP task DBLRDY_STOP : SHORTS_DBLRDY_STOP_Field := NRF_SVD.QDEC.Disabled; -- Shortcut between SAMPLERDY event and READCLRACC task SAMPLERDY_READCLRACC : SHORTS_SAMPLERDY_READCLRACC_Field := NRF_SVD.QDEC.Disabled; -- unspecified Reserved_7_31 : HAL.UInt25 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for SHORTS_Register use record REPORTRDY_READCLRACC at 0 range 0 .. 0; SAMPLERDY_STOP at 0 range 1 .. 1; REPORTRDY_RDCLRACC at 0 range 2 .. 2; REPORTRDY_STOP at 0 range 3 .. 3; DBLRDY_RDCLRDBL at 0 range 4 .. 4; DBLRDY_STOP at 0 range 5 .. 5; SAMPLERDY_READCLRACC at 0 range 6 .. 6; Reserved_7_31 at 0 range 7 .. 31; end record; -- Write '1' to Enable interrupt for SAMPLERDY event type INTENSET_SAMPLERDY_Field is (-- Read: Disabled Disabled, -- Read: Enabled Enabled) with Size => 1; for INTENSET_SAMPLERDY_Field use (Disabled => 0, Enabled => 1); -- Write '1' to Enable interrupt for SAMPLERDY event type INTENSET_SAMPLERDY_Field_1 is (-- Reset value for the field Intenset_Samplerdy_Field_Reset, -- Enable Set) with Size => 1; for INTENSET_SAMPLERDY_Field_1 use (Intenset_Samplerdy_Field_Reset => 0, Set => 1); -- Write '1' to Enable interrupt for REPORTRDY event type INTENSET_REPORTRDY_Field is (-- Read: Disabled Disabled, -- Read: Enabled Enabled) with Size => 1; for INTENSET_REPORTRDY_Field use (Disabled => 0, Enabled => 1); -- Write '1' to Enable interrupt for REPORTRDY event type INTENSET_REPORTRDY_Field_1 is (-- Reset value for the field Intenset_Reportrdy_Field_Reset, -- Enable Set) with Size => 1; for INTENSET_REPORTRDY_Field_1 use (Intenset_Reportrdy_Field_Reset => 0, Set => 1); -- Write '1' to Enable interrupt for ACCOF event type INTENSET_ACCOF_Field is (-- Read: Disabled Disabled, -- Read: Enabled Enabled) with Size => 1; for INTENSET_ACCOF_Field use (Disabled => 0, Enabled => 1); -- Write '1' to Enable interrupt for ACCOF event type INTENSET_ACCOF_Field_1 is (-- Reset value for the field Intenset_Accof_Field_Reset, -- Enable Set) with Size => 1; for INTENSET_ACCOF_Field_1 use (Intenset_Accof_Field_Reset => 0, Set => 1); -- Write '1' to Enable interrupt for DBLRDY event type INTENSET_DBLRDY_Field is (-- Read: Disabled Disabled, -- Read: Enabled Enabled) with Size => 1; for INTENSET_DBLRDY_Field use (Disabled => 0, Enabled => 1); -- Write '1' to Enable interrupt for DBLRDY event type INTENSET_DBLRDY_Field_1 is (-- Reset value for the field Intenset_Dblrdy_Field_Reset, -- Enable Set) with Size => 1; for INTENSET_DBLRDY_Field_1 use (Intenset_Dblrdy_Field_Reset => 0, Set => 1); -- Write '1' to Enable interrupt for STOPPED event type INTENSET_STOPPED_Field is (-- Read: Disabled Disabled, -- Read: Enabled Enabled) with Size => 1; for INTENSET_STOPPED_Field use (Disabled => 0, Enabled => 1); -- Write '1' to Enable interrupt for STOPPED event type INTENSET_STOPPED_Field_1 is (-- Reset value for the field Intenset_Stopped_Field_Reset, -- Enable Set) with Size => 1; for INTENSET_STOPPED_Field_1 use (Intenset_Stopped_Field_Reset => 0, Set => 1); -- Enable interrupt type INTENSET_Register is record -- Write '1' to Enable interrupt for SAMPLERDY event SAMPLERDY : INTENSET_SAMPLERDY_Field_1 := Intenset_Samplerdy_Field_Reset; -- Write '1' to Enable interrupt for REPORTRDY event REPORTRDY : INTENSET_REPORTRDY_Field_1 := Intenset_Reportrdy_Field_Reset; -- Write '1' to Enable interrupt for ACCOF event ACCOF : INTENSET_ACCOF_Field_1 := Intenset_Accof_Field_Reset; -- Write '1' to Enable interrupt for DBLRDY event DBLRDY : INTENSET_DBLRDY_Field_1 := Intenset_Dblrdy_Field_Reset; -- Write '1' to Enable interrupt for STOPPED event STOPPED : INTENSET_STOPPED_Field_1 := Intenset_Stopped_Field_Reset; -- unspecified Reserved_5_31 : HAL.UInt27 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for INTENSET_Register use record SAMPLERDY at 0 range 0 .. 0; REPORTRDY at 0 range 1 .. 1; ACCOF at 0 range 2 .. 2; DBLRDY at 0 range 3 .. 3; STOPPED at 0 range 4 .. 4; Reserved_5_31 at 0 range 5 .. 31; end record; -- Write '1' to Disable interrupt for SAMPLERDY event type INTENCLR_SAMPLERDY_Field is (-- Read: Disabled Disabled, -- Read: Enabled Enabled) with Size => 1; for INTENCLR_SAMPLERDY_Field use (Disabled => 0, Enabled => 1); -- Write '1' to Disable interrupt for SAMPLERDY event type INTENCLR_SAMPLERDY_Field_1 is (-- Reset value for the field Intenclr_Samplerdy_Field_Reset, -- Disable Clear) with Size => 1; for INTENCLR_SAMPLERDY_Field_1 use (Intenclr_Samplerdy_Field_Reset => 0, Clear => 1); -- Write '1' to Disable interrupt for REPORTRDY event type INTENCLR_REPORTRDY_Field is (-- Read: Disabled Disabled, -- Read: Enabled Enabled) with Size => 1; for INTENCLR_REPORTRDY_Field use (Disabled => 0, Enabled => 1); -- Write '1' to Disable interrupt for REPORTRDY event type INTENCLR_REPORTRDY_Field_1 is (-- Reset value for the field Intenclr_Reportrdy_Field_Reset, -- Disable Clear) with Size => 1; for INTENCLR_REPORTRDY_Field_1 use (Intenclr_Reportrdy_Field_Reset => 0, Clear => 1); -- Write '1' to Disable interrupt for ACCOF event type INTENCLR_ACCOF_Field is (-- Read: Disabled Disabled, -- Read: Enabled Enabled) with Size => 1; for INTENCLR_ACCOF_Field use (Disabled => 0, Enabled => 1); -- Write '1' to Disable interrupt for ACCOF event type INTENCLR_ACCOF_Field_1 is (-- Reset value for the field Intenclr_Accof_Field_Reset, -- Disable Clear) with Size => 1; for INTENCLR_ACCOF_Field_1 use (Intenclr_Accof_Field_Reset => 0, Clear => 1); -- Write '1' to Disable interrupt for DBLRDY event type INTENCLR_DBLRDY_Field is (-- Read: Disabled Disabled, -- Read: Enabled Enabled) with Size => 1; for INTENCLR_DBLRDY_Field use (Disabled => 0, Enabled => 1); -- Write '1' to Disable interrupt for DBLRDY event type INTENCLR_DBLRDY_Field_1 is (-- Reset value for the field Intenclr_Dblrdy_Field_Reset, -- Disable Clear) with Size => 1; for INTENCLR_DBLRDY_Field_1 use (Intenclr_Dblrdy_Field_Reset => 0, Clear => 1); -- Write '1' to Disable interrupt for STOPPED event type INTENCLR_STOPPED_Field is (-- Read: Disabled Disabled, -- Read: Enabled Enabled) with Size => 1; for INTENCLR_STOPPED_Field use (Disabled => 0, Enabled => 1); -- Write '1' to Disable interrupt for STOPPED event type INTENCLR_STOPPED_Field_1 is (-- Reset value for the field Intenclr_Stopped_Field_Reset, -- Disable Clear) with Size => 1; for INTENCLR_STOPPED_Field_1 use (Intenclr_Stopped_Field_Reset => 0, Clear => 1); -- Disable interrupt type INTENCLR_Register is record -- Write '1' to Disable interrupt for SAMPLERDY event SAMPLERDY : INTENCLR_SAMPLERDY_Field_1 := Intenclr_Samplerdy_Field_Reset; -- Write '1' to Disable interrupt for REPORTRDY event REPORTRDY : INTENCLR_REPORTRDY_Field_1 := Intenclr_Reportrdy_Field_Reset; -- Write '1' to Disable interrupt for ACCOF event ACCOF : INTENCLR_ACCOF_Field_1 := Intenclr_Accof_Field_Reset; -- Write '1' to Disable interrupt for DBLRDY event DBLRDY : INTENCLR_DBLRDY_Field_1 := Intenclr_Dblrdy_Field_Reset; -- Write '1' to Disable interrupt for STOPPED event STOPPED : INTENCLR_STOPPED_Field_1 := Intenclr_Stopped_Field_Reset; -- unspecified Reserved_5_31 : HAL.UInt27 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for INTENCLR_Register use record SAMPLERDY at 0 range 0 .. 0; REPORTRDY at 0 range 1 .. 1; ACCOF at 0 range 2 .. 2; DBLRDY at 0 range 3 .. 3; STOPPED at 0 range 4 .. 4; Reserved_5_31 at 0 range 5 .. 31; end record; -- Enable or disable the quadrature decoder type ENABLE_ENABLE_Field is (-- Disable Disabled, -- Enable Enabled) with Size => 1; for ENABLE_ENABLE_Field use (Disabled => 0, Enabled => 1); -- Enable the quadrature decoder type ENABLE_Register is record -- Enable or disable the quadrature decoder ENABLE : ENABLE_ENABLE_Field := NRF_SVD.QDEC.Disabled; -- unspecified Reserved_1_31 : HAL.UInt31 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for ENABLE_Register use record ENABLE at 0 range 0 .. 0; Reserved_1_31 at 0 range 1 .. 31; end record; -- LED output pin polarity type LEDPOL_LEDPOL_Field is (-- Led active on output pin low Activelow, -- Led active on output pin high Activehigh) with Size => 1; for LEDPOL_LEDPOL_Field use (Activelow => 0, Activehigh => 1); -- LED output pin polarity type LEDPOL_Register is record -- LED output pin polarity LEDPOL : LEDPOL_LEDPOL_Field := NRF_SVD.QDEC.Activelow; -- unspecified Reserved_1_31 : HAL.UInt31 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for LEDPOL_Register use record LEDPOL at 0 range 0 .. 0; Reserved_1_31 at 0 range 1 .. 31; end record; -- Sample period. The SAMPLE register will be updated for every new sample type SAMPLEPER_SAMPLEPER_Field is (-- 128 us Val_128US, -- 256 us Val_256US, -- 512 us Val_512US, -- 1024 us Val_1024US, -- 2048 us Val_2048US, -- 4096 us Val_4096US, -- 8192 us Val_8192US, -- 16384 us Val_16384US, -- 32768 us Val_32MS, -- 65536 us Val_65MS, -- 131072 us Val_131MS) with Size => 4; for SAMPLEPER_SAMPLEPER_Field use (Val_128US => 0, Val_256US => 1, Val_512US => 2, Val_1024US => 3, Val_2048US => 4, Val_4096US => 5, Val_8192US => 6, Val_16384US => 7, Val_32MS => 8, Val_65MS => 9, Val_131MS => 10); -- Sample period type SAMPLEPER_Register is record -- Sample period. The SAMPLE register will be updated for every new -- sample SAMPLEPER : SAMPLEPER_SAMPLEPER_Field := NRF_SVD.QDEC.Val_128US; -- unspecified Reserved_4_31 : HAL.UInt28 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for SAMPLEPER_Register use record SAMPLEPER at 0 range 0 .. 3; Reserved_4_31 at 0 range 4 .. 31; end record; -- Specifies the number of samples to be accumulated in the ACC register -- before the REPORTRDY and DBLRDY events can be generated type REPORTPER_REPORTPER_Field is (-- 10 samples / report Val_10Smpl, -- 40 samples / report Val_40Smpl, -- 80 samples / report Val_80Smpl, -- 120 samples / report Val_120Smpl, -- 160 samples / report Val_160Smpl, -- 200 samples / report Val_200Smpl, -- 240 samples / report Val_240Smpl, -- 280 samples / report Val_280Smpl, -- 1 sample / report Val_1Smpl) with Size => 4; for REPORTPER_REPORTPER_Field use (Val_10Smpl => 0, Val_40Smpl => 1, Val_80Smpl => 2, Val_120Smpl => 3, Val_160Smpl => 4, Val_200Smpl => 5, Val_240Smpl => 6, Val_280Smpl => 7, Val_1Smpl => 8); -- Number of samples to be taken before REPORTRDY and DBLRDY events can be -- generated type REPORTPER_Register is record -- Specifies the number of samples to be accumulated in the ACC register -- before the REPORTRDY and DBLRDY events can be generated REPORTPER : REPORTPER_REPORTPER_Field := NRF_SVD.QDEC.Val_10Smpl; -- unspecified Reserved_4_31 : HAL.UInt28 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for REPORTPER_Register use record REPORTPER at 0 range 0 .. 3; Reserved_4_31 at 0 range 4 .. 31; end record; ------------------------------ -- PSEL cluster's Registers -- ------------------------------ subtype LED_PSEL_PIN_Field is HAL.UInt5; -- Connection type LED_CONNECT_Field is (-- Connect Connected, -- Disconnect Disconnected) with Size => 1; for LED_CONNECT_Field use (Connected => 0, Disconnected => 1); -- Pin select for LED signal type LED_PSEL_Register is record -- Pin number PIN : LED_PSEL_PIN_Field := 16#1F#; -- unspecified Reserved_5_30 : HAL.UInt26 := 16#3FFFFFF#; -- Connection CONNECT : LED_CONNECT_Field := NRF_SVD.QDEC.Disconnected; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for LED_PSEL_Register use record PIN at 0 range 0 .. 4; Reserved_5_30 at 0 range 5 .. 30; CONNECT at 0 range 31 .. 31; end record; subtype A_PSEL_PIN_Field is HAL.UInt5; -- Connection type A_CONNECT_Field is (-- Connect Connected, -- Disconnect Disconnected) with Size => 1; for A_CONNECT_Field use (Connected => 0, Disconnected => 1); -- Pin select for A signal type A_PSEL_Register is record -- Pin number PIN : A_PSEL_PIN_Field := 16#1F#; -- unspecified Reserved_5_30 : HAL.UInt26 := 16#3FFFFFF#; -- Connection CONNECT : A_CONNECT_Field := NRF_SVD.QDEC.Disconnected; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for A_PSEL_Register use record PIN at 0 range 0 .. 4; Reserved_5_30 at 0 range 5 .. 30; CONNECT at 0 range 31 .. 31; end record; subtype B_PSEL_PIN_Field is HAL.UInt5; -- Connection type B_CONNECT_Field is (-- Connect Connected, -- Disconnect Disconnected) with Size => 1; for B_CONNECT_Field use (Connected => 0, Disconnected => 1); -- Pin select for B signal type B_PSEL_Register is record -- Pin number PIN : B_PSEL_PIN_Field := 16#1F#; -- unspecified Reserved_5_30 : HAL.UInt26 := 16#3FFFFFF#; -- Connection CONNECT : B_CONNECT_Field := NRF_SVD.QDEC.Disconnected; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for B_PSEL_Register use record PIN at 0 range 0 .. 4; Reserved_5_30 at 0 range 5 .. 30; CONNECT at 0 range 31 .. 31; end record; -- Unspecified type PSEL_Cluster is record -- Pin select for LED signal LED : aliased LED_PSEL_Register; -- Pin select for A signal A : aliased A_PSEL_Register; -- Pin select for B signal B : aliased B_PSEL_Register; end record with Size => 96; for PSEL_Cluster use record LED at 16#0# range 0 .. 31; A at 16#4# range 0 .. 31; B at 16#8# range 0 .. 31; end record; -- Enable input debounce filters type DBFEN_DBFEN_Field is (-- Debounce input filters disabled Disabled, -- Debounce input filters enabled Enabled) with Size => 1; for DBFEN_DBFEN_Field use (Disabled => 0, Enabled => 1); -- Enable input debounce filters type DBFEN_Register is record -- Enable input debounce filters DBFEN : DBFEN_DBFEN_Field := NRF_SVD.QDEC.Disabled; -- unspecified Reserved_1_31 : HAL.UInt31 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for DBFEN_Register use record DBFEN at 0 range 0 .. 0; Reserved_1_31 at 0 range 1 .. 31; end record; subtype LEDPRE_LEDPRE_Field is HAL.UInt9; -- Time period the LED is switched ON prior to sampling type LEDPRE_Register is record -- Period in us the LED is switched on prior to sampling LEDPRE : LEDPRE_LEDPRE_Field := 16#10#; -- unspecified Reserved_9_31 : HAL.UInt23 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for LEDPRE_Register use record LEDPRE at 0 range 0 .. 8; Reserved_9_31 at 0 range 9 .. 31; end record; subtype ACCDBL_ACCDBL_Field is HAL.UInt4; -- Register accumulating the number of detected double transitions type ACCDBL_Register is record -- Read-only. Register accumulating the number of detected double or -- illegal transitions. ( SAMPLE = 2 ). ACCDBL : ACCDBL_ACCDBL_Field; -- unspecified Reserved_4_31 : HAL.UInt28; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for ACCDBL_Register use record ACCDBL at 0 range 0 .. 3; Reserved_4_31 at 0 range 4 .. 31; end record; subtype ACCDBLREAD_ACCDBLREAD_Field is HAL.UInt4; -- Snapshot of the ACCDBL, updated by the READCLRACC or RDCLRDBL task type ACCDBLREAD_Register is record -- Read-only. Snapshot of the ACCDBL register. This field is updated -- when the READCLRACC or RDCLRDBL task is triggered. ACCDBLREAD : ACCDBLREAD_ACCDBLREAD_Field; -- unspecified Reserved_4_31 : HAL.UInt28; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for ACCDBLREAD_Register use record ACCDBLREAD at 0 range 0 .. 3; Reserved_4_31 at 0 range 4 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- Quadrature Decoder type QDEC_Peripheral is record -- Task starting the quadrature decoder TASKS_START : aliased HAL.UInt32; -- Task stopping the quadrature decoder TASKS_STOP : aliased HAL.UInt32; -- Read and clear ACC and ACCDBL TASKS_READCLRACC : aliased HAL.UInt32; -- Read and clear ACC TASKS_RDCLRACC : aliased HAL.UInt32; -- Read and clear ACCDBL TASKS_RDCLRDBL : aliased HAL.UInt32; -- Event being generated for every new sample value written to the -- SAMPLE register EVENTS_SAMPLERDY : aliased HAL.UInt32; -- Non-null report ready EVENTS_REPORTRDY : aliased HAL.UInt32; -- ACC or ACCDBL register overflow EVENTS_ACCOF : aliased HAL.UInt32; -- Double displacement(s) detected EVENTS_DBLRDY : aliased HAL.UInt32; -- QDEC has been stopped EVENTS_STOPPED : aliased HAL.UInt32; -- Shortcut register SHORTS : aliased SHORTS_Register; -- Enable interrupt INTENSET : aliased INTENSET_Register; -- Disable interrupt INTENCLR : aliased INTENCLR_Register; -- Enable the quadrature decoder ENABLE : aliased ENABLE_Register; -- LED output pin polarity LEDPOL : aliased LEDPOL_Register; -- Sample period SAMPLEPER : aliased SAMPLEPER_Register; -- Motion sample value SAMPLE : aliased HAL.UInt32; -- Number of samples to be taken before REPORTRDY and DBLRDY events can -- be generated REPORTPER : aliased REPORTPER_Register; -- Register accumulating the valid transitions ACC : aliased HAL.UInt32; -- Snapshot of the ACC register, updated by the READCLRACC or RDCLRACC -- task ACCREAD : aliased HAL.UInt32; -- Unspecified PSEL : aliased PSEL_Cluster; -- Enable input debounce filters DBFEN : aliased DBFEN_Register; -- Time period the LED is switched ON prior to sampling LEDPRE : aliased LEDPRE_Register; -- Register accumulating the number of detected double transitions ACCDBL : aliased ACCDBL_Register; -- Snapshot of the ACCDBL, updated by the READCLRACC or RDCLRDBL task ACCDBLREAD : aliased ACCDBLREAD_Register; end record with Volatile; for QDEC_Peripheral use record TASKS_START at 16#0# range 0 .. 31; TASKS_STOP at 16#4# range 0 .. 31; TASKS_READCLRACC at 16#8# range 0 .. 31; TASKS_RDCLRACC at 16#C# range 0 .. 31; TASKS_RDCLRDBL at 16#10# range 0 .. 31; EVENTS_SAMPLERDY at 16#100# range 0 .. 31; EVENTS_REPORTRDY at 16#104# range 0 .. 31; EVENTS_ACCOF at 16#108# range 0 .. 31; EVENTS_DBLRDY at 16#10C# range 0 .. 31; EVENTS_STOPPED at 16#110# range 0 .. 31; SHORTS at 16#200# range 0 .. 31; INTENSET at 16#304# range 0 .. 31; INTENCLR at 16#308# range 0 .. 31; ENABLE at 16#500# range 0 .. 31; LEDPOL at 16#504# range 0 .. 31; SAMPLEPER at 16#508# range 0 .. 31; SAMPLE at 16#50C# range 0 .. 31; REPORTPER at 16#510# range 0 .. 31; ACC at 16#514# range 0 .. 31; ACCREAD at 16#518# range 0 .. 31; PSEL at 16#51C# range 0 .. 95; DBFEN at 16#528# range 0 .. 31; LEDPRE at 16#540# range 0 .. 31; ACCDBL at 16#544# range 0 .. 31; ACCDBLREAD at 16#548# range 0 .. 31; end record; -- Quadrature Decoder QDEC_Periph : aliased QDEC_Peripheral with Import, Address => QDEC_Base; end NRF_SVD.QDEC;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- E X P _ D B U G -- -- -- -- B o d y -- -- -- -- Copyright (C) 1996-2020, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING3. If not, go to -- -- http://www.gnu.org/licenses for a complete copy of the license. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Alloc; with Atree; use Atree; with Debug; use Debug; with Einfo; use Einfo; with Exp_Util; use Exp_Util; with Nlists; use Nlists; with Nmake; use Nmake; with Opt; use Opt; with Output; use Output; with Sem_Aux; use Sem_Aux; with Sem_Eval; use Sem_Eval; with Sem_Util; use Sem_Util; with Sinfo; use Sinfo; with Stand; use Stand; with Stringt; use Stringt; with Table; with Tbuild; use Tbuild; with Urealp; use Urealp; package body Exp_Dbug is -- The following table is used to queue up the entities passed as -- arguments to Qualify_Entity_Names for later processing when -- Qualify_All_Entity_Names is called. package Name_Qualify_Units is new Table.Table ( Table_Component_Type => Node_Id, Table_Index_Type => Nat, Table_Low_Bound => 1, Table_Initial => Alloc.Name_Qualify_Units_Initial, Table_Increment => Alloc.Name_Qualify_Units_Increment, Table_Name => "Name_Qualify_Units"); -------------------------------- -- Use of Qualification Flags -- -------------------------------- -- There are two flags used to keep track of qualification of entities -- Has_Fully_Qualified_Name -- Has_Qualified_Name -- The difference between these is as follows. Has_Qualified_Name is -- set to indicate that the name has been qualified as required by the -- spec of this package. As described there, this may involve the full -- qualification for the name, but for some entities, notably procedure -- local variables, this full qualification is not required. -- The flag Has_Fully_Qualified_Name is set if indeed the name has been -- fully qualified in the Ada sense. If Has_Fully_Qualified_Name is set, -- then Has_Qualified_Name is also set, but the other way round is not -- the case. -- Consider the following example: -- with ... -- procedure X is -- B : Ddd.Ttt; -- procedure Y is .. -- Here B is a procedure local variable, so it does not need fully -- qualification. The flag Has_Qualified_Name will be set on the -- first attempt to qualify B, to indicate that the job is done -- and need not be redone. -- But Y is qualified as x__y, since procedures are always fully -- qualified, so the first time that an attempt is made to qualify -- the name y, it will be replaced by x__y, and both flags are set. -- Why the two flags? Well there are cases where we derive type names -- from object names. As noted in the spec, type names are always -- fully qualified. Suppose for example that the backend has to build -- a padded type for variable B. then it will construct the PAD name -- from B, but it requires full qualification, so the fully qualified -- type name will be x__b___PAD. The two flags allow the circuit for -- building this name to realize efficiently that b needs further -- qualification. -------------------- -- Homonym_Suffix -- -------------------- -- The string defined here (and its associated length) is used to gather -- the homonym string that will be appended to Name_Buffer when the name -- is complete. Strip_Suffixes appends to this string as does -- Append_Homonym_Number, and Output_Homonym_Numbers_Suffix appends the -- string to the end of Name_Buffer. Homonym_Numbers : String (1 .. 256); Homonym_Len : Natural := 0; ---------------------- -- Local Procedures -- ---------------------- procedure Add_Uint_To_Buffer (U : Uint); -- Add image of universal integer to Name_Buffer, updating Name_Len procedure Add_Real_To_Buffer (U : Ureal); -- Add nnn_ddd to Name_Buffer, where nnn and ddd are integer values of -- the normalized numerator and denominator of the given real value. procedure Append_Homonym_Number (E : Entity_Id); -- If the entity E has homonyms in the same scope, then make an entry -- in the Homonym_Numbers array, bumping Homonym_Count accordingly. function Bounds_Match_Size (E : Entity_Id) return Boolean; -- Determine whether the bounds of E match the size of the type. This is -- used to determine whether encoding is required for a discrete type. function Is_Handled_Scale_Factor (U : Ureal) return Boolean; -- The argument U is the Small_Value of a fixed-point type. This function -- determines whether the back-end can handle this scale factor. When it -- cannot, we have to output a GNAT encoding for the corresponding type. procedure Output_Homonym_Numbers_Suffix; -- If homonym numbers are stored, then output them into Name_Buffer procedure Prepend_String_To_Buffer (S : String); -- Prepend given string to the contents of the string buffer, updating -- the value in Name_Len (i.e. string is added at start of buffer). procedure Prepend_Uint_To_Buffer (U : Uint); -- Prepend image of universal integer to Name_Buffer, updating Name_Len procedure Qualify_Entity_Name (Ent : Entity_Id); -- If not already done, replaces the Chars field of the given entity -- with the appropriate fully qualified name. procedure Reset_Buffers; -- Reset the contents of Name_Buffer and Homonym_Numbers by setting their -- respective lengths to zero. procedure Strip_Suffixes (BNPE_Suffix_Found : in out Boolean); -- Given an qualified entity name in Name_Buffer, remove any plain X or -- X{nb} qualification suffix. The contents of Name_Buffer is not changed -- but Name_Len may be adjusted on return to remove the suffix. If a -- BNPE suffix is found and stripped, then BNPE_Suffix_Found is set to -- True. If no suffix is found, then BNPE_Suffix_Found is not modified. -- This routine also searches for a homonym suffix, and if one is found -- it is also stripped, and the entries are added to the global homonym -- list (Homonym_Numbers) so that they can later be put back. ------------------------ -- Add_Real_To_Buffer -- ------------------------ procedure Add_Real_To_Buffer (U : Ureal) is begin Add_Uint_To_Buffer (Norm_Num (U)); Add_Str_To_Name_Buffer ("_"); Add_Uint_To_Buffer (Norm_Den (U)); end Add_Real_To_Buffer; ------------------------ -- Add_Uint_To_Buffer -- ------------------------ procedure Add_Uint_To_Buffer (U : Uint) is begin if U < 0 then Add_Uint_To_Buffer (-U); Add_Char_To_Name_Buffer ('m'); else UI_Image (U, Decimal); Add_Str_To_Name_Buffer (UI_Image_Buffer (1 .. UI_Image_Length)); end if; end Add_Uint_To_Buffer; --------------------------- -- Append_Homonym_Number -- --------------------------- procedure Append_Homonym_Number (E : Entity_Id) is procedure Add_Nat_To_H (Nr : Nat); -- Little procedure to append Nr to Homonym_Numbers ------------------ -- Add_Nat_To_H -- ------------------ procedure Add_Nat_To_H (Nr : Nat) is begin if Nr >= 10 then Add_Nat_To_H (Nr / 10); end if; Homonym_Len := Homonym_Len + 1; Homonym_Numbers (Homonym_Len) := Character'Val (Nr mod 10 + Character'Pos ('0')); end Add_Nat_To_H; -- Start of processing for Append_Homonym_Number begin if Has_Homonym (E) then if Homonym_Len > 0 then Homonym_Len := Homonym_Len + 1; Homonym_Numbers (Homonym_Len) := '_'; end if; Add_Nat_To_H (Homonym_Number (E)); end if; end Append_Homonym_Number; ----------------------- -- Bounds_Match_Size -- ----------------------- function Bounds_Match_Size (E : Entity_Id) return Boolean is Siz : Uint; begin if not Is_OK_Static_Subtype (E) then return False; elsif Is_Integer_Type (E) and then Subtypes_Statically_Match (E, Base_Type (E)) then return True; -- Here we check if the static bounds match the natural size, which is -- the size passed through with the debugging information. This is the -- Esize rounded up to 8, 16, 32 or 64 as appropriate. else declare Umark : constant Uintp.Save_Mark := Uintp.Mark; Result : Boolean; begin if Esize (E) <= 8 then Siz := Uint_8; elsif Esize (E) <= 16 then Siz := Uint_16; elsif Esize (E) <= 32 then Siz := Uint_32; else Siz := Uint_64; end if; if Is_Modular_Integer_Type (E) or else Is_Enumeration_Type (E) then Result := Expr_Rep_Value (Type_Low_Bound (E)) = 0 and then 2 ** Siz - Expr_Rep_Value (Type_High_Bound (E)) = 1; else Result := Expr_Rep_Value (Type_Low_Bound (E)) + 2 ** (Siz - 1) = 0 and then 2 ** (Siz - 1) - Expr_Rep_Value (Type_High_Bound (E)) = 1; end if; Release (Umark); return Result; end; end if; end Bounds_Match_Size; -------------------------------- -- Debug_Renaming_Declaration -- -------------------------------- function Debug_Renaming_Declaration (N : Node_Id) return Node_Id is Loc : constant Source_Ptr := Sloc (N); Ent : constant Node_Id := Defining_Entity (N); Nam : constant Node_Id := Name (N); Ren : Node_Id; Typ : Entity_Id; Obj : Entity_Id; Res : Node_Id; Enable : Boolean := Nkind (N) = N_Package_Renaming_Declaration; -- By default, we do not generate an encoding for renaming. This is -- however done (in which case this is set to True) in a few cases: -- - when a package is renamed, -- - when the renaming involves a packed array, -- - when the renaming involves a packed record. Last_Is_Indexed_Comp : Boolean := False; -- Whether the last subscript value was an indexed component access (XS) procedure Enable_If_Packed_Array (N : Node_Id); -- Enable encoding generation if N is a packed array function Output_Subscript (N : Node_Id; S : String) return Boolean; -- Outputs a single subscript value as ?nnn (subscript is compile time -- known value with value nnn) or as ?e (subscript is local constant -- with name e), where S supplies the proper string to use for ?. -- Returns False if the subscript is not of an appropriate type to -- output in one of these two forms. The result is prepended to the -- name stored in Name_Buffer. function Scope_Contains (Sc : Node_Id; Ent : Entity_Id) return Boolean; -- Return whether Ent belong to the Sc scope ---------------------------- -- Enable_If_Packed_Array -- ---------------------------- procedure Enable_If_Packed_Array (N : Node_Id) is T : constant Entity_Id := Underlying_Type (Etype (N)); begin Enable := Enable or else (Ekind (T) in Array_Kind and then Present (Packed_Array_Impl_Type (T))); end Enable_If_Packed_Array; ---------------------- -- Output_Subscript -- ---------------------- function Output_Subscript (N : Node_Id; S : String) return Boolean is begin if Compile_Time_Known_Value (N) then Prepend_Uint_To_Buffer (Expr_Value (N)); elsif Nkind (N) = N_Identifier and then Scope_Contains (Scope (Entity (N)), Ent) and then (Ekind (Entity (N)) = E_Constant or else Ekind (Entity (N)) = E_In_Parameter) then Prepend_String_To_Buffer (Get_Name_String (Chars (Entity (N)))); else return False; end if; Prepend_String_To_Buffer (S); return True; end Output_Subscript; -------------------- -- Scope_Contains -- -------------------- function Scope_Contains (Sc : Node_Id; Ent : Entity_Id) return Boolean is Cur : Node_Id := Scope (Ent); begin while Present (Cur) loop if Cur = Sc then return True; end if; Cur := Scope (Cur); end loop; return False; end Scope_Contains; -- Start of processing for Debug_Renaming_Declaration begin if not Comes_From_Source (N) and then not Needs_Debug_Info (Ent) then return Empty; end if; -- Get renamed entity and compute suffix Name_Len := 0; Ren := Nam; loop -- The expression that designates the renamed object is sometimes -- expanded into bit-wise operations. We want to work instead on -- array/record components accesses, so try to analyze the unexpanded -- forms. Ren := Original_Node (Ren); case Nkind (Ren) is when N_Expanded_Name | N_Identifier => if not Present (Renamed_Object (Entity (Ren))) then exit; end if; -- This is a renaming of a renaming: traverse until the final -- renaming to see if anything is packed along the way. Ren := Renamed_Object (Entity (Ren)); when N_Selected_Component => declare Sel_Id : constant Entity_Id := Entity (Selector_Name (Ren)); First_Bit : Uint; begin -- If the renaming involves a call to a primitive function, -- we are out of the scope of renaming encodings. We will -- very likely create a variable to hold the renamed value -- anyway, so the renaming entity will be available in -- debuggers. exit when Ekind (Sel_Id) not in E_Component | E_Discriminant; First_Bit := Normalized_First_Bit (Sel_Id); Enable := Enable or else Is_Packed (Underlying_Type (Etype (Prefix (Ren)))) or else (First_Bit /= No_Uint and then First_Bit /= Uint_0); end; Prepend_String_To_Buffer (Get_Name_String (Chars (Selector_Name (Ren)))); Prepend_String_To_Buffer ("XR"); Ren := Prefix (Ren); Last_Is_Indexed_Comp := False; when N_Indexed_Component => declare X : Node_Id; begin Enable_If_Packed_Array (Prefix (Ren)); X := Last (Expressions (Ren)); while Present (X) loop if not Output_Subscript (X, "XS") then Set_Materialize_Entity (Ent); return Empty; end if; Prev (X); Last_Is_Indexed_Comp := True; end loop; end; Ren := Prefix (Ren); when N_Slice => -- Assuming X is an array: -- X (Y1 .. Y2) (Y3) -- is equivalent to: -- X (Y3) -- GDB cannot handle packed array slices, so avoid describing -- the slice if we can avoid it. if not Last_Is_Indexed_Comp then Enable_If_Packed_Array (Prefix (Ren)); Typ := Etype (First_Index (Etype (Ren))); if not Output_Subscript (Type_High_Bound (Typ), "XS") then Set_Materialize_Entity (Ent); return Empty; end if; if not Output_Subscript (Type_Low_Bound (Typ), "XL") then Set_Materialize_Entity (Ent); return Empty; end if; Last_Is_Indexed_Comp := False; end if; Ren := Prefix (Ren); when N_Explicit_Dereference => Prepend_String_To_Buffer ("XA"); Ren := Prefix (Ren); Last_Is_Indexed_Comp := False; -- For now, anything else simply results in no translation when others => Set_Materialize_Entity (Ent); return Empty; end case; end loop; -- If we found no reason here to emit an encoding, stop now if not Enable then Set_Materialize_Entity (Ent); return Empty; end if; Prepend_String_To_Buffer ("___XE"); -- Include the designation of the form of renaming case Nkind (N) is when N_Object_Renaming_Declaration => Prepend_String_To_Buffer ("___XR"); when N_Exception_Renaming_Declaration => Prepend_String_To_Buffer ("___XRE"); when N_Package_Renaming_Declaration => Prepend_String_To_Buffer ("___XRP"); when others => return Empty; end case; -- Add the name of the renaming entity to the front Prepend_String_To_Buffer (Get_Name_String (Chars (Ent))); -- If it is a child unit create a fully qualified name, to disambiguate -- multiple child units with the same name and different parents. if Nkind (N) = N_Package_Renaming_Declaration and then Is_Child_Unit (Ent) then Prepend_String_To_Buffer ("__"); Prepend_String_To_Buffer (Get_Name_String (Chars (Scope (Ent)))); end if; -- Create the special object whose name is the debug encoding for the -- renaming declaration. -- For now, the object name contains the suffix encoding for the renamed -- object, but not the name of the leading entity. The object is linked -- the renamed entity using the Debug_Renaming_Link field. Then the -- Qualify_Entity_Name procedure uses this link to create the proper -- fully qualified name. -- The reason we do things this way is that we really need to copy the -- qualification of the renamed entity, and it is really much easier to -- do this after the renamed entity has itself been fully qualified. Obj := Make_Defining_Identifier (Loc, Chars => Name_Enter); Res := Make_Object_Declaration (Loc, Defining_Identifier => Obj, Object_Definition => New_Occurrence_Of (Standard_Debug_Renaming_Type, Loc)); Set_Debug_Renaming_Link (Obj, Entity (Ren)); Set_Debug_Info_Needed (Obj); -- The renamed entity may be a temporary, e.g. the result of an -- implicit dereference in an iterator. Indicate that the temporary -- itself requires debug information. If the renamed entity comes -- from source this is a no-op. Set_Debug_Info_Needed (Entity (Ren)); -- Mark the object as internal so that it won't be initialized when -- pragma Initialize_Scalars or Normalize_Scalars is in use. Set_Is_Internal (Obj); return Res; -- If we get an exception, just figure it is a case that we cannot -- successfully handle using our current approach, since this is -- only for debugging, no need to take the compilation with us. exception when others => return Make_Null_Statement (Loc); end Debug_Renaming_Declaration; ----------------------------- -- Is_Handled_Scale_Factor -- ----------------------------- function Is_Handled_Scale_Factor (U : Ureal) return Boolean is begin -- Keep in sync with gigi (see E_*_Fixed_Point_Type handling in -- decl.c:gnat_to_gnu_entity). if UI_Eq (Numerator (U), Uint_1) then if Rbase (U) = 2 or else Rbase (U) = 10 then return True; end if; end if; return (UI_Is_In_Int_Range (Norm_Num (U)) and then UI_Is_In_Int_Range (Norm_Den (U))); end Is_Handled_Scale_Factor; ---------------------- -- Get_Encoded_Name -- ---------------------- -- Note: see spec for details on encodings procedure Get_Encoded_Name (E : Entity_Id) is Has_Suffix : Boolean; begin -- If not generating code, there is no need to create encoded names, and -- problems when the back-end is called to annotate types without full -- code generation. See comments in Get_External_Name for additional -- details. -- However we do create encoded names if the back end is active, even -- if Operating_Mode got reset. Otherwise any serious error reported -- by the backend calling Error_Msg changes the Compilation_Mode to -- Check_Semantics, which disables the functionality of this routine, -- causing the generation of spurious additional errors. -- Couldn't we just test Original_Operating_Mode here? ??? if Operating_Mode /= Generate_Code and then not Generating_Code then return; end if; Get_Name_String (Chars (E)); -- Nothing to do if we do not have a type if not Is_Type (E) -- Or if this is an enumeration base type or else (Is_Enumeration_Type (E) and then Is_Base_Type (E)) -- Or if this is a dummy type for a renaming or else (Name_Len >= 3 and then Name_Buffer (Name_Len - 2 .. Name_Len) = "_XR") or else (Name_Len >= 4 and then (Name_Buffer (Name_Len - 3 .. Name_Len) = "_XRE" or else Name_Buffer (Name_Len - 3 .. Name_Len) = "_XRP")) -- For all these cases, just return the name unchanged then Name_Buffer (Name_Len + 1) := ASCII.NUL; return; end if; Has_Suffix := True; -- Fixed-point case: generate GNAT encodings when asked to or when we -- know the back-end will not be able to handle the scale factor. if Is_Fixed_Point_Type (E) and then (GNAT_Encodings /= DWARF_GNAT_Encodings_Minimal or else not Is_Handled_Scale_Factor (Small_Value (E))) then Get_External_Name (E, True, "XF_"); Add_Real_To_Buffer (Delta_Value (E)); if Small_Value (E) /= Delta_Value (E) then Add_Str_To_Name_Buffer ("_"); Add_Real_To_Buffer (Small_Value (E)); end if; -- Discrete case where bounds do not match size. Not necessary if we can -- emit standard DWARF. elsif GNAT_Encodings /= DWARF_GNAT_Encodings_Minimal and then Is_Discrete_Type (E) and then not Bounds_Match_Size (E) then declare Lo : constant Node_Id := Type_Low_Bound (E); Hi : constant Node_Id := Type_High_Bound (E); Lo_Con : constant Boolean := Compile_Time_Known_Value (Lo); Hi_Con : constant Boolean := Compile_Time_Known_Value (Hi); Lo_Discr : constant Boolean := Nkind (Lo) = N_Identifier and then Ekind (Entity (Lo)) = E_Discriminant; Hi_Discr : constant Boolean := Nkind (Hi) = N_Identifier and then Ekind (Entity (Hi)) = E_Discriminant; Lo_Encode : constant Boolean := Lo_Con or Lo_Discr; Hi_Encode : constant Boolean := Hi_Con or Hi_Discr; Biased : constant Boolean := Has_Biased_Representation (E); begin if Biased then Get_External_Name (E, True, "XB"); else Get_External_Name (E, True, "XD"); end if; if Lo_Encode or Hi_Encode then if Biased then Add_Str_To_Name_Buffer ("_"); else if Lo_Encode then if Hi_Encode then Add_Str_To_Name_Buffer ("LU_"); else Add_Str_To_Name_Buffer ("L_"); end if; else Add_Str_To_Name_Buffer ("U_"); end if; end if; if Lo_Con then Add_Uint_To_Buffer (Expr_Rep_Value (Lo)); elsif Lo_Discr then Get_Name_String_And_Append (Chars (Entity (Lo))); end if; if Lo_Encode and Hi_Encode then Add_Str_To_Name_Buffer ("__"); end if; if Hi_Con then Add_Uint_To_Buffer (Expr_Rep_Value (Hi)); elsif Hi_Discr then Get_Name_String_And_Append (Chars (Entity (Hi))); end if; end if; end; -- For all other cases, the encoded name is the normal type name else Has_Suffix := False; Get_External_Name (E); end if; if Debug_Flag_B and then Has_Suffix then Write_Str ("**** type "); Write_Name (Chars (E)); Write_Str (" is encoded as "); Write_Str (Name_Buffer (1 .. Name_Len)); Write_Eol; end if; Name_Buffer (Name_Len + 1) := ASCII.NUL; end Get_Encoded_Name; ----------------------- -- Get_External_Name -- ----------------------- procedure Get_External_Name (Entity : Entity_Id; Has_Suffix : Boolean := False; Suffix : String := "") is procedure Get_Qualified_Name_And_Append (Entity : Entity_Id); -- Appends fully qualified name of given entity to Name_Buffer ----------------------------------- -- Get_Qualified_Name_And_Append -- ----------------------------------- procedure Get_Qualified_Name_And_Append (Entity : Entity_Id) is begin -- If the entity is a compilation unit, its scope is Standard, -- there is no outer scope, and the no further qualification -- is required. -- If the front end has already computed a fully qualified name, -- then it is also the case that no further qualification is -- required. if Present (Scope (Scope (Entity))) and then not Has_Fully_Qualified_Name (Entity) then Get_Qualified_Name_And_Append (Scope (Entity)); Add_Str_To_Name_Buffer ("__"); Get_Name_String_And_Append (Chars (Entity)); Append_Homonym_Number (Entity); else Get_Name_String_And_Append (Chars (Entity)); end if; end Get_Qualified_Name_And_Append; -- Local variables E : Entity_Id := Entity; -- Start of processing for Get_External_Name begin -- If we are not in code generation mode, this procedure may still be -- called from Back_End (more specifically - from gigi for doing type -- representation annotation or some representation-specific checks). -- But in this mode there is no need to mess with external names. -- Furthermore, the call causes difficulties in this case because the -- string representing the homonym number is not correctly reset as a -- part of the call to Output_Homonym_Numbers_Suffix (which is not -- called in gigi). if Operating_Mode /= Generate_Code then return; end if; Reset_Buffers; -- If this is a child unit, we want the child if Nkind (E) = N_Defining_Program_Unit_Name then E := Defining_Identifier (Entity); end if; -- Case of interface name being used if Ekind (E) in E_Constant | E_Exception | E_Function | E_Procedure | E_Variable and then Present (Interface_Name (E)) and then No (Address_Clause (E)) and then not Has_Suffix then Append (Global_Name_Buffer, Strval (Interface_Name (E))); -- All other cases besides the interface name case else -- If this is a library level subprogram (i.e. a subprogram that is a -- compilation unit other than a subunit), then we prepend _ada_ to -- ensure distinctions required as described in the spec. -- Check explicitly for child units, because those are not flagged -- as Compilation_Units by lib. Should they be ??? if Is_Subprogram (E) and then (Is_Compilation_Unit (E) or Is_Child_Unit (E)) and then not Has_Suffix then Add_Str_To_Name_Buffer ("_ada_"); end if; -- If the entity is a subprogram instance that is not a compilation -- unit, generate the name of the original Ada entity, which is the -- one gdb needs. if Is_Generic_Instance (E) and then Is_Subprogram (E) and then not Is_Compilation_Unit (Scope (E)) and then Ekind (Scope (E)) in E_Package | E_Package_Body and then Present (Related_Instance (Scope (E))) then E := Related_Instance (Scope (E)); end if; Get_Qualified_Name_And_Append (E); end if; if Has_Suffix then Add_Str_To_Name_Buffer ("___"); Add_Str_To_Name_Buffer (Suffix); end if; -- Add a special prefix to distinguish Ghost entities. In Ignored Ghost -- mode, these entities should not leak in the "living" space and they -- should be removed by the compiler in a post-processing pass. Thus, -- the prefix allows anyone to check that the final executable indeed -- does not contain such entities, in such a case. Do not insert this -- prefix for compilation units, whose name is used as a basis for the -- name of the generated elaboration procedure and (when appropriate) -- the executable produced. Only insert this prefix once, for Ghost -- entities declared inside other Ghost entities. Three leading -- underscores are used so that "___ghost_" is a unique substring of -- names produced for Ghost entities, while "__ghost_" can appear in -- names of entities inside a child/local package called "Ghost". -- The compiler-generated finalizer for an enabled Ghost unit is treated -- specially, as its name must be known to the binder, which has no -- knowledge of Ghost status. In that case, the finalizer is not marked -- as Ghost so that no prefix is added. Note that the special ___ghost_ -- prefix is retained when the Ghost unit is ignored, which still allows -- inspecting the final executable for the presence of an ignored Ghost -- finalizer procedure. if Is_Ghost_Entity (E) and then not Is_Compilation_Unit (E) and then (Name_Len < 9 or else Name_Buffer (1 .. 9) /= "___ghost_") then Insert_Str_In_Name_Buffer ("___ghost_", 1); end if; Name_Buffer (Name_Len + 1) := ASCII.NUL; end Get_External_Name; -------------------------- -- Get_Variant_Encoding -- -------------------------- procedure Get_Variant_Encoding (V : Node_Id) is Choice : Node_Id; procedure Choice_Val (Typ : Character; Choice : Node_Id); -- Output encoded value for a single choice value. Typ is the key -- character ('S', 'F', or 'T') that precedes the choice value. ---------------- -- Choice_Val -- ---------------- procedure Choice_Val (Typ : Character; Choice : Node_Id) is begin if Nkind (Choice) = N_Integer_Literal then Add_Char_To_Name_Buffer (Typ); Add_Uint_To_Buffer (Intval (Choice)); -- Character literal with no entity present (this is the case -- Standard.Character or Standard.Wide_Character as root type) elsif Nkind (Choice) = N_Character_Literal and then No (Entity (Choice)) then Add_Char_To_Name_Buffer (Typ); Add_Uint_To_Buffer (Char_Literal_Value (Choice)); else declare Ent : constant Entity_Id := Entity (Choice); begin if Ekind (Ent) = E_Enumeration_Literal then Add_Char_To_Name_Buffer (Typ); Add_Uint_To_Buffer (Enumeration_Rep (Ent)); else pragma Assert (Ekind (Ent) = E_Constant); Choice_Val (Typ, Constant_Value (Ent)); end if; end; end if; end Choice_Val; -- Start of processing for Get_Variant_Encoding begin Name_Len := 0; Choice := First (Discrete_Choices (V)); while Present (Choice) loop if Nkind (Choice) = N_Others_Choice then Add_Char_To_Name_Buffer ('O'); elsif Nkind (Choice) = N_Range then Choice_Val ('R', Low_Bound (Choice)); Choice_Val ('T', High_Bound (Choice)); elsif Is_Entity_Name (Choice) and then Is_Type (Entity (Choice)) then Choice_Val ('R', Type_Low_Bound (Entity (Choice))); Choice_Val ('T', Type_High_Bound (Entity (Choice))); elsif Nkind (Choice) = N_Subtype_Indication then declare Rang : constant Node_Id := Range_Expression (Constraint (Choice)); begin Choice_Val ('R', Low_Bound (Rang)); Choice_Val ('T', High_Bound (Rang)); end; else Choice_Val ('S', Choice); end if; Next (Choice); end loop; Name_Buffer (Name_Len + 1) := ASCII.NUL; if Debug_Flag_B then declare VP : constant Node_Id := Parent (V); -- Variant_Part CL : constant Node_Id := Parent (VP); -- Component_List RD : constant Node_Id := Parent (CL); -- Record_Definition FT : constant Node_Id := Parent (RD); -- Full_Type_Declaration begin Write_Str ("**** variant for type "); Write_Name (Chars (Defining_Identifier (FT))); Write_Str (" is encoded as "); Write_Str (Name_Buffer (1 .. Name_Len)); Write_Eol; end; end if; end Get_Variant_Encoding; ----------------------------------------- -- Build_Subprogram_Instance_Renamings -- ----------------------------------------- procedure Build_Subprogram_Instance_Renamings (N : Node_Id; Wrapper : Entity_Id) is Loc : Source_Ptr; Decl : Node_Id; E : Entity_Id; begin E := First_Entity (Wrapper); while Present (E) loop if Nkind (Parent (E)) = N_Object_Declaration and then Is_Elementary_Type (Etype (E)) then Loc := Sloc (Expression (Parent (E))); Decl := Make_Object_Renaming_Declaration (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Chars (E)), Subtype_Mark => New_Occurrence_Of (Etype (E), Loc), Name => New_Occurrence_Of (E, Loc)); Append (Decl, Declarations (N)); Set_Debug_Info_Needed (Defining_Identifier (Decl)); end if; Next_Entity (E); end loop; end Build_Subprogram_Instance_Renamings; ------------------------------------ -- Get_Secondary_DT_External_Name -- ------------------------------------ procedure Get_Secondary_DT_External_Name (Typ : Entity_Id; Ancestor_Typ : Entity_Id; Suffix_Index : Int) is begin Get_External_Name (Typ); if Ancestor_Typ /= Typ then declare Len : constant Natural := Name_Len; Save_Str : constant String (1 .. Name_Len) := Name_Buffer (1 .. Name_Len); begin Get_External_Name (Ancestor_Typ); -- Append the extended name of the ancestor to the -- extended name of Typ Name_Buffer (Len + 2 .. Len + Name_Len + 1) := Name_Buffer (1 .. Name_Len); Name_Buffer (1 .. Len) := Save_Str; Name_Buffer (Len + 1) := '_'; Name_Len := Len + Name_Len + 1; end; end if; Add_Nat_To_Name_Buffer (Suffix_Index); end Get_Secondary_DT_External_Name; --------------------------------- -- Make_Packed_Array_Impl_Type_Name -- --------------------------------- function Make_Packed_Array_Impl_Type_Name (Typ : Entity_Id; Csize : Uint) return Name_Id is begin Get_Name_String (Chars (Typ)); Add_Str_To_Name_Buffer ("___XP"); Add_Uint_To_Buffer (Csize); return Name_Find; end Make_Packed_Array_Impl_Type_Name; ----------------------------------- -- Output_Homonym_Numbers_Suffix -- ----------------------------------- procedure Output_Homonym_Numbers_Suffix is J : Natural; begin if Homonym_Len > 0 then -- Check for all 1's, in which case we do not output J := 1; loop exit when Homonym_Numbers (J) /= '1'; -- If we reached end of string we do not output if J = Homonym_Len then Homonym_Len := 0; return; end if; exit when Homonym_Numbers (J + 1) /= '_'; J := J + 2; end loop; -- If we exit the loop then suffix must be output Add_Str_To_Name_Buffer ("__"); Add_Str_To_Name_Buffer (Homonym_Numbers (1 .. Homonym_Len)); Homonym_Len := 0; end if; end Output_Homonym_Numbers_Suffix; ------------------------------ -- Prepend_String_To_Buffer -- ------------------------------ procedure Prepend_String_To_Buffer (S : String) is N : constant Integer := S'Length; begin Name_Buffer (1 + N .. Name_Len + N) := Name_Buffer (1 .. Name_Len); Name_Buffer (1 .. N) := S; Name_Len := Name_Len + N; end Prepend_String_To_Buffer; ---------------------------- -- Prepend_Uint_To_Buffer -- ---------------------------- procedure Prepend_Uint_To_Buffer (U : Uint) is begin if U < 0 then Prepend_String_To_Buffer ("m"); Prepend_Uint_To_Buffer (-U); else UI_Image (U, Decimal); Prepend_String_To_Buffer (UI_Image_Buffer (1 .. UI_Image_Length)); end if; end Prepend_Uint_To_Buffer; ------------------------------ -- Qualify_All_Entity_Names -- ------------------------------ procedure Qualify_All_Entity_Names is E : Entity_Id; Ent : Entity_Id; Nod : Node_Id; begin for J in Name_Qualify_Units.First .. Name_Qualify_Units.Last loop Nod := Name_Qualify_Units.Table (J); -- When a scoping construct is ignored Ghost, it is rewritten as -- a null statement. Skip such constructs as they no longer carry -- names. if Nkind (Nod) = N_Null_Statement then goto Continue; end if; E := Defining_Entity (Nod); Reset_Buffers; Qualify_Entity_Name (E); -- Normally entities in the qualification list are scopes, but in the -- case of a library-level package renaming there is an associated -- variable that encodes the debugger name and that variable is -- entered in the list since it occurs in the Aux_Decls list of the -- compilation and doesn't have a normal scope. if Ekind (E) /= E_Variable then Ent := First_Entity (E); while Present (Ent) loop Reset_Buffers; Qualify_Entity_Name (Ent); Next_Entity (Ent); -- There are odd cases where Last_Entity (E) = E. This happens -- in the case of renaming of packages. This test avoids -- getting stuck in such cases. exit when Ent = E; end loop; end if; <<Continue>> null; end loop; end Qualify_All_Entity_Names; ------------------------- -- Qualify_Entity_Name -- ------------------------- procedure Qualify_Entity_Name (Ent : Entity_Id) is Full_Qualify_Name : String (1 .. Name_Buffer'Length); Full_Qualify_Len : Natural := 0; -- Used to accumulate fully qualified name of subprogram procedure Fully_Qualify_Name (E : Entity_Id); -- Used to qualify a subprogram or type name, where full -- qualification up to Standard is always used. Name is set -- in Full_Qualify_Name with the length in Full_Qualify_Len. -- Note that this routine does not prepend the _ada_ string -- required for library subprograms (this is done in the back end). function Is_BNPE (S : Entity_Id) return Boolean; -- Determines if S is a BNPE, i.e. Body-Nested Package Entity, which -- is defined to be a package which is immediately nested within a -- package body. function Qualify_Needed (S : Entity_Id) return Boolean; -- Given a scope, determines if the scope is to be included in the -- fully qualified name, True if so, False if not. Blocks and loops -- are excluded from a qualified name. procedure Set_BNPE_Suffix (E : Entity_Id); -- Recursive routine to append the BNPE qualification suffix. Works -- from right to left with E being the current entity in the list. -- The result does NOT have the trailing n's and trailing b stripped. -- The caller must do this required stripping. procedure Set_Entity_Name (E : Entity_Id); -- Internal recursive routine that does most of the work. This routine -- leaves the result sitting in Name_Buffer and Name_Len. BNPE_Suffix_Needed : Boolean := False; -- Set true if a body-nested package entity suffix is required Save_Chars : constant Name_Id := Chars (Ent); -- Save original name ------------------------ -- Fully_Qualify_Name -- ------------------------ procedure Fully_Qualify_Name (E : Entity_Id) is Discard : Boolean := False; begin -- Ignore empty entry (can happen in error cases) if No (E) then return; -- If this we are qualifying entities local to a generic instance, -- use the name of the original instantiation, not that of the -- anonymous subprogram in the wrapper package, so that gdb doesn't -- have to know about these. elsif Is_Generic_Instance (E) and then Is_Subprogram (E) and then not Comes_From_Source (E) and then not Is_Compilation_Unit (Scope (E)) then Fully_Qualify_Name (Related_Instance (Scope (E))); return; end if; -- If we reached fully qualified name, then just copy it if Has_Fully_Qualified_Name (E) then Get_Name_String (Chars (E)); Strip_Suffixes (Discard); Full_Qualify_Name (1 .. Name_Len) := Name_Buffer (1 .. Name_Len); Full_Qualify_Len := Name_Len; Set_Has_Fully_Qualified_Name (Ent); -- Case of non-fully qualified name else if Scope (E) = Standard_Standard then Set_Has_Fully_Qualified_Name (Ent); else Fully_Qualify_Name (Scope (E)); Full_Qualify_Name (Full_Qualify_Len + 1) := '_'; Full_Qualify_Name (Full_Qualify_Len + 2) := '_'; Full_Qualify_Len := Full_Qualify_Len + 2; end if; if Has_Qualified_Name (E) then Get_Unqualified_Name_String (Chars (E)); else Get_Name_String (Chars (E)); end if; -- Here we do one step of the qualification Full_Qualify_Name (Full_Qualify_Len + 1 .. Full_Qualify_Len + Name_Len) := Name_Buffer (1 .. Name_Len); Full_Qualify_Len := Full_Qualify_Len + Name_Len; Append_Homonym_Number (E); end if; if Is_BNPE (E) then BNPE_Suffix_Needed := True; end if; end Fully_Qualify_Name; ------------- -- Is_BNPE -- ------------- function Is_BNPE (S : Entity_Id) return Boolean is begin return Ekind (S) = E_Package and then Is_Package_Body_Entity (S); end Is_BNPE; -------------------- -- Qualify_Needed -- -------------------- function Qualify_Needed (S : Entity_Id) return Boolean is begin -- If we got all the way to Standard, then we have certainly -- fully qualified the name, so set the flag appropriately, -- and then return False, since we are most certainly done. if S = Standard_Standard then Set_Has_Fully_Qualified_Name (Ent, True); return False; -- Otherwise figure out if further qualification is required else return Is_Subprogram (Ent) or else Ekind (Ent) = E_Subprogram_Body or else (Ekind (S) /= E_Block and then Ekind (S) /= E_Loop and then not Is_Dynamic_Scope (S)); end if; end Qualify_Needed; --------------------- -- Set_BNPE_Suffix -- --------------------- procedure Set_BNPE_Suffix (E : Entity_Id) is S : constant Entity_Id := Scope (E); begin if Qualify_Needed (S) then Set_BNPE_Suffix (S); if Is_BNPE (E) then Add_Char_To_Name_Buffer ('b'); else Add_Char_To_Name_Buffer ('n'); end if; else Add_Char_To_Name_Buffer ('X'); end if; end Set_BNPE_Suffix; --------------------- -- Set_Entity_Name -- --------------------- procedure Set_Entity_Name (E : Entity_Id) is S : constant Entity_Id := Scope (E); begin -- If we reach an already qualified name, just take the encoding -- except that we strip the package body suffixes, since these -- will be separately put on later. if Has_Qualified_Name (E) then Get_Name_String_And_Append (Chars (E)); Strip_Suffixes (BNPE_Suffix_Needed); -- If the top level name we are adding is itself fully -- qualified, then that means that the name that we are -- preparing for the Fully_Qualify_Name call will also -- generate a fully qualified name. if Has_Fully_Qualified_Name (E) then Set_Has_Fully_Qualified_Name (Ent); end if; -- Case where upper level name is not encoded yet else -- Recurse if further qualification required if Qualify_Needed (S) then Set_Entity_Name (S); Add_Str_To_Name_Buffer ("__"); end if; -- Otherwise get name and note if it is a BNPE Get_Name_String_And_Append (Chars (E)); if Is_BNPE (E) then BNPE_Suffix_Needed := True; end if; Append_Homonym_Number (E); end if; end Set_Entity_Name; -- Start of processing for Qualify_Entity_Name begin if Has_Qualified_Name (Ent) then return; -- If the entity is a variable encoding the debug name for an object -- renaming, then the qualified name of the entity associated with the -- renamed object can now be incorporated in the debug name. elsif Ekind (Ent) = E_Variable and then Present (Debug_Renaming_Link (Ent)) then Name_Len := 0; Qualify_Entity_Name (Debug_Renaming_Link (Ent)); Get_Name_String (Chars (Ent)); -- Retrieve the now-qualified name of the renamed entity and insert -- it in the middle of the name, just preceding the suffix encoding -- describing the renamed object. declare Renamed_Id : constant String := Get_Name_String (Chars (Debug_Renaming_Link (Ent))); Insert_Len : constant Integer := Renamed_Id'Length + 1; Index : Natural := Name_Len - 3; begin -- Loop backwards through the name to find the start of the "___" -- sequence associated with the suffix. while Index >= Name_Buffer'First and then (Name_Buffer (Index + 1) /= '_' or else Name_Buffer (Index + 2) /= '_' or else Name_Buffer (Index + 3) /= '_') loop Index := Index - 1; end loop; pragma Assert (Name_Buffer (Index + 1 .. Index + 3) = "___"); -- Insert an underscore separator and the entity name just in -- front of the suffix. Name_Buffer (Index + 1 + Insert_Len .. Name_Len + Insert_Len) := Name_Buffer (Index + 1 .. Name_Len); Name_Buffer (Index + 1) := '_'; Name_Buffer (Index + 2 .. Index + Insert_Len) := Renamed_Id; Name_Len := Name_Len + Insert_Len; end; -- Reset the name of the variable to the new name that includes the -- name of the renamed entity. Set_Chars (Ent, Name_Enter); -- If the entity needs qualification by its scope then develop it -- here, add the variable's name, and again reset the entity name. if Qualify_Needed (Scope (Ent)) then Name_Len := 0; Set_Entity_Name (Scope (Ent)); Add_Str_To_Name_Buffer ("__"); Get_Name_String_And_Append (Chars (Ent)); Set_Chars (Ent, Name_Enter); end if; Set_Has_Qualified_Name (Ent); return; elsif Is_Subprogram (Ent) or else Ekind (Ent) = E_Subprogram_Body or else Is_Type (Ent) or else Ekind (Ent) = E_Exception then Fully_Qualify_Name (Ent); Name_Len := Full_Qualify_Len; Name_Buffer (1 .. Name_Len) := Full_Qualify_Name (1 .. Name_Len); -- Qualification needed for enumeration literals when generating C code -- (to simplify their management in the backend). elsif Modify_Tree_For_C and then Ekind (Ent) = E_Enumeration_Literal and then Scope (Ultimate_Alias (Ent)) /= Standard_Standard then Fully_Qualify_Name (Ent); Name_Len := Full_Qualify_Len; Name_Buffer (1 .. Name_Len) := Full_Qualify_Name (1 .. Name_Len); elsif Qualify_Needed (Scope (Ent)) then Name_Len := 0; Set_Entity_Name (Ent); else Set_Has_Qualified_Name (Ent); -- If a variable is hidden by a subsequent loop variable, qualify -- the name of that loop variable to prevent visibility issues when -- translating to C. Note that gdb probably never handled properly -- this accidental hiding, given that loops are not scopes at -- runtime. We also qualify a name if it hides an outer homonym, -- and both are declared in blocks. if Modify_Tree_For_C and then Ekind (Ent) = E_Variable then if Present (Hiding_Loop_Variable (Ent)) then declare Var : constant Entity_Id := Hiding_Loop_Variable (Ent); begin Set_Entity_Name (Var); Add_Str_To_Name_Buffer ("L"); Set_Chars (Var, Name_Enter); end; elsif Present (Homonym (Ent)) and then Ekind (Scope (Ent)) = E_Block and then Ekind (Scope (Homonym (Ent))) = E_Block then Set_Entity_Name (Ent); Add_Str_To_Name_Buffer ("B"); Set_Chars (Ent, Name_Enter); end if; end if; return; end if; -- Fall through with a fully qualified name in Name_Buffer/Name_Len Output_Homonym_Numbers_Suffix; -- Add body-nested package suffix if required if BNPE_Suffix_Needed and then Ekind (Ent) /= E_Enumeration_Literal then Set_BNPE_Suffix (Ent); -- Strip trailing n's and last trailing b as required. note that -- we know there is at least one b, or no suffix would be generated. while Name_Buffer (Name_Len) = 'n' loop Name_Len := Name_Len - 1; end loop; Name_Len := Name_Len - 1; end if; Set_Chars (Ent, Name_Enter); Set_Has_Qualified_Name (Ent); if Debug_Flag_BB then Write_Str ("*** "); Write_Name (Save_Chars); Write_Str (" qualified as "); Write_Name (Chars (Ent)); Write_Eol; end if; end Qualify_Entity_Name; -------------------------- -- Qualify_Entity_Names -- -------------------------- procedure Qualify_Entity_Names (N : Node_Id) is begin Name_Qualify_Units.Append (N); end Qualify_Entity_Names; ------------------- -- Reset_Buffers -- ------------------- procedure Reset_Buffers is begin Name_Len := 0; Homonym_Len := 0; end Reset_Buffers; -------------------- -- Strip_Suffixes -- -------------------- procedure Strip_Suffixes (BNPE_Suffix_Found : in out Boolean) is SL : Natural; pragma Warnings (Off, BNPE_Suffix_Found); -- Since this procedure only ever sets the flag begin -- Search for and strip BNPE suffix for J in reverse 2 .. Name_Len loop if Name_Buffer (J) = 'X' then Name_Len := J - 1; BNPE_Suffix_Found := True; exit; end if; exit when Name_Buffer (J) /= 'b' and then Name_Buffer (J) /= 'n'; end loop; -- Search for and strip homonym numbers suffix for J in reverse 2 .. Name_Len - 2 loop if Name_Buffer (J) = '_' and then Name_Buffer (J + 1) = '_' then if Name_Buffer (J + 2) in '0' .. '9' then if Homonym_Len > 0 then Homonym_Len := Homonym_Len + 1; Homonym_Numbers (Homonym_Len) := '-'; end if; SL := Name_Len - (J + 1); Homonym_Numbers (Homonym_Len + 1 .. Homonym_Len + SL) := Name_Buffer (J + 2 .. Name_Len); Name_Len := J - 1; Homonym_Len := Homonym_Len + SL; end if; exit; end if; end loop; end Strip_Suffixes; end Exp_Dbug;
-- { dg-do compile } -- { dg-options "-gnatws" } with System; use System; procedure Trampoline1 is A : Integer; function F (I : Integer) return Integer is begin return A + I; end F; CA : System.Address := F'Code_Address; begin if CA = System.Null_Address then raise Program_Error; end if; end; -- { dg-final { scan-assembler-not "GNU-stack.*x" } }
procedure main is aft : integer := 1; s, str : string(1..3); begin s := "abc"; str((aft)..3) := s(1..3); end;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- E X P _ C H 8 -- -- -- -- B o d y -- -- -- -- $Revision$ -- -- -- Copyright (C) 1992-2001 Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, -- -- MA 02111-1307, USA. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Atree; use Atree; with Einfo; use Einfo; with Exp_Dbug; use Exp_Dbug; with Exp_Util; use Exp_Util; with Nlists; use Nlists; with Sem; use Sem; with Sem_Ch8; use Sem_Ch8; with Sinfo; use Sinfo; with Stand; use Stand; package body Exp_Ch8 is --------------------------------------------- -- Expand_N_Exception_Renaming_Declaration -- --------------------------------------------- procedure Expand_N_Exception_Renaming_Declaration (N : Node_Id) is Decl : constant Node_Id := Debug_Renaming_Declaration (N); begin if Present (Decl) then Insert_Action (N, Decl); end if; end Expand_N_Exception_Renaming_Declaration; ------------------------------------------ -- Expand_N_Object_Renaming_Declaration -- ------------------------------------------ -- Most object renaming cases can be done by just capturing the address -- of the renamed object. The cases in which this is not true are when -- this address is not computable, since it involves extraction of a -- packed array element, or of a record component to which a component -- clause applies (that can specify an arbitrary bit boundary), or where -- the enclosing record itself has a non-standard representation. -- In these two cases, we pre-evaluate the renaming expression, by -- extracting and freezing the values of any subscripts, and then we -- set the flag Is_Renaming_Of_Object which means that any reference -- to the object will be handled by macro substitution in the front -- end, and the back end will know to ignore the renaming declaration. -- An additional odd case that requires processing by expansion is -- the renaming of a discriminant of a mutable record type. The object -- is a constant because it renames something that cannot be assigned to, -- but in fact the underlying value can change and must be reevaluated -- at each reference. Gigi does have a notion of a "constant view" of -- an object, and therefore the front-end must perform the expansion. -- For simplicity, and to bypass some obscure code-generation problem, -- we use macro substitution for all renamed discriminants, whether the -- enclosing type is constrained or not. -- The other special processing required is for the case of renaming -- of an object of a class wide type, where it is necessary to build -- the appropriate subtype for the renamed object. -- More comments needed for this para ??? procedure Expand_N_Object_Renaming_Declaration (N : Node_Id) is Nam : Node_Id := Name (N); T : Entity_Id; Decl : Node_Id; procedure Evaluate_Name (Fname : Node_Id); -- A recursive procedure used to freeze a name in the sense described -- above, i.e. any variable references or function calls are removed. -- Of course the outer level variable reference must not be removed. -- For example in A(J,F(K)), A is left as is, but J and F(K) are -- evaluated and removed. function Evaluation_Required (Nam : Node_Id) return Boolean; -- Determines whether it is necessary to do static name evaluation -- for renaming of Nam. It is considered necessary if evaluating the -- name involves indexing a packed array, or extracting a component -- of a record to which a component clause applies. Note that we are -- only interested in these operations if they occur as part of the -- name itself, subscripts are just values that are computed as part -- of the evaluation, so their form is unimportant. ------------------- -- Evaluate_Name -- ------------------- procedure Evaluate_Name (Fname : Node_Id) is K : constant Node_Kind := Nkind (Fname); E : Node_Id; begin -- For an explicit dereference, we simply force the evaluation -- of the name expression. The dereference provides a value that -- is the address for the renamed object, and it is precisely -- this value that we want to preserve. if K = N_Explicit_Dereference then Force_Evaluation (Prefix (Fname)); -- For a selected component, we simply evaluate the prefix elsif K = N_Selected_Component then Evaluate_Name (Prefix (Fname)); -- For an indexed component, or an attribute reference, we evaluate -- the prefix, which is itself a name, recursively, and then force -- the evaluation of all the subscripts (or attribute expressions). elsif K = N_Indexed_Component or else K = N_Attribute_Reference then Evaluate_Name (Prefix (Fname)); E := First (Expressions (Fname)); while Present (E) loop Force_Evaluation (E); if Original_Node (E) /= E then Set_Do_Range_Check (E, Do_Range_Check (Original_Node (E))); end if; Next (E); end loop; -- For a slice, we evaluate the prefix, as for the indexed component -- case and then, if there is a range present, either directly or -- as the constraint of a discrete subtype indication, we evaluate -- the two bounds of this range. elsif K = N_Slice then Evaluate_Name (Prefix (Fname)); declare DR : constant Node_Id := Discrete_Range (Fname); Constr : Node_Id; Rexpr : Node_Id; begin if Nkind (DR) = N_Range then Force_Evaluation (Low_Bound (DR)); Force_Evaluation (High_Bound (DR)); elsif Nkind (DR) = N_Subtype_Indication then Constr := Constraint (DR); if Nkind (Constr) = N_Range_Constraint then Rexpr := Range_Expression (Constr); Force_Evaluation (Low_Bound (Rexpr)); Force_Evaluation (High_Bound (Rexpr)); end if; end if; end; -- For a type conversion, the expression of the conversion must be -- the name of an object, and we simply need to evaluate this name. elsif K = N_Type_Conversion then Evaluate_Name (Expression (Fname)); -- For a function call, we evaluate the call. elsif K = N_Function_Call then Force_Evaluation (Fname); -- The remaining cases are direct name, operator symbol and -- character literal. In all these cases, we do nothing, since -- we want to reevaluate each time the renamed object is used. else return; end if; end Evaluate_Name; ------------------------- -- Evaluation_Required -- ------------------------- function Evaluation_Required (Nam : Node_Id) return Boolean is begin if Nkind (Nam) = N_Indexed_Component or else Nkind (Nam) = N_Slice then if Is_Packed (Etype (Prefix (Nam))) then return True; else return Evaluation_Required (Prefix (Nam)); end if; elsif Nkind (Nam) = N_Selected_Component then declare Rec_Type : Entity_Id := Etype (Prefix (Nam)); begin if Present (Component_Clause (Entity (Selector_Name (Nam)))) or else Has_Non_Standard_Rep (Rec_Type) then return True; elsif Ekind (Entity (Selector_Name (Nam))) = E_Discriminant and then Is_Record_Type (Rec_Type) and then not Is_Concurrent_Record_Type (Rec_Type) then return True; else return Evaluation_Required (Prefix (Nam)); end if; end; else return False; end if; end Evaluation_Required; -- Start of processing for Expand_N_Object_Renaming_Declaration begin -- Perform name evaluation if required if Evaluation_Required (Nam) then Evaluate_Name (Nam); Set_Is_Renaming_Of_Object (Defining_Identifier (N)); end if; -- Deal with construction of subtype in class-wide case T := Etype (Defining_Identifier (N)); if Is_Class_Wide_Type (T) then Expand_Subtype_From_Expr (N, T, Subtype_Mark (N), Name (N)); Find_Type (Subtype_Mark (N)); Set_Etype (Defining_Identifier (N), Entity (Subtype_Mark (N))); end if; -- Create renaming entry for debug information Decl := Debug_Renaming_Declaration (N); if Present (Decl) then Insert_Action (N, Decl); end if; end Expand_N_Object_Renaming_Declaration; ------------------------------------------- -- Expand_N_Package_Renaming_Declaration -- ------------------------------------------- procedure Expand_N_Package_Renaming_Declaration (N : Node_Id) is Decl : constant Node_Id := Debug_Renaming_Declaration (N); begin if Present (Decl) then -- If we are in a compilation unit, then this is an outer -- level declaration, and must have a scope of Standard if Nkind (Parent (N)) = N_Compilation_Unit then declare Aux : constant Node_Id := Aux_Decls_Node (Parent (N)); begin New_Scope (Standard_Standard); if No (Actions (Aux)) then Set_Actions (Aux, New_List (Decl)); else Append (Decl, Actions (Aux)); end if; Analyze (Decl); Pop_Scope; end; -- Otherwise, just insert after the package declaration else Insert_Action (N, Decl); end if; end if; end Expand_N_Package_Renaming_Declaration; end Exp_Ch8;
----------------------------------------------------------------------- -- keystore-tools -- Tools for the keystore -- Copyright (C) 2019 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams.Stream_IO; with Util.Log.Loggers; with Util.Streams.Files; package body Keystore.Tools is use type Ada.Directories.File_Kind; subtype File_Kind is Ada.Directories.File_Kind; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Keystore.Tools"); -- ------------------------------ -- Store the file in the keystore and use the prefix followed by the file basename -- for the name to identify the stored the content. -- ------------------------------ procedure Store (Wallet : in out Keystore.Wallet'Class; Path : in String; Prefix : in String) is Name : constant String := Prefix & Ada.Directories.Simple_Name (Path); File : Util.Streams.Files.File_Stream; begin Log.Info ("Store file {0} as {1}", Path, Name); File.Open (Mode => Ada.Streams.Stream_IO.In_File, Name => Path); Wallet.Set (Name => Name, Kind => Keystore.T_FILE, Input => File); end Store; -- ------------------------------ -- Scan the directory for files matching the pattern and store them in the -- keystore when the filter predicate accepts them. -- ------------------------------ procedure Store (Wallet : in out Keystore.Wallet'Class; Path : in String; Prefix : in String; Pattern : in String; Filter : not null access function (Ent : in Directory_Entry_Type) return Boolean) is Search_Filter : constant Ada.Directories.Filter_Type := (Ada.Directories.Ordinary_File => True, Ada.Directories.Directory => True, Ada.Directories.Special_File => False); Search : Ada.Directories.Search_Type; Ent : Directory_Entry_Type; begin Log.Info ("Scan directory {0}", Path); Ada.Directories.Start_Search (Search, Directory => Path, Pattern => Pattern, Filter => Search_Filter); while Ada.Directories.More_Entries (Search) loop Ada.Directories.Get_Next_Entry (Search, Ent); declare Name : constant String := Ada.Directories.Simple_Name (Ent); Kind : constant File_Kind := Ada.Directories.Kind (Ent); Fpath : constant String := Ada.Directories.Full_Name (Ent); begin if Kind /= Ada.Directories.Directory then if Filter (Ent) then Store (Wallet, Fpath, Prefix); end if; elsif Name /= "." and then Name /= ".." then if Filter (Ent) then Store (Wallet, Fpath, Prefix & Name & '/', Pattern, Filter); end if; end if; end; end loop; end Store; end Keystore.Tools;
-- This spec has been automatically generated from STM32F103.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with HAL; with System; package STM32_SVD.WWDG is pragma Preelaborate; --------------- -- Registers -- --------------- subtype CR_T_Field is HAL.UInt7; -- Control register (WWDG_CR) type CR_Register is record -- 7-bit counter (MSB to LSB) T : CR_T_Field := 16#7F#; -- Activation bit WDGA : Boolean := False; -- unspecified Reserved_8_31 : HAL.UInt24 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CR_Register use record T at 0 range 0 .. 6; WDGA at 0 range 7 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; subtype CFR_W_Field is HAL.UInt7; subtype CFR_WDGTB_Field is HAL.UInt2; -- Configuration register (WWDG_CFR) type CFR_Register is record -- 7-bit window value W : CFR_W_Field := 16#7F#; -- Timer Base WDGTB : CFR_WDGTB_Field := 16#0#; -- Early Wakeup Interrupt EWI : Boolean := False; -- unspecified Reserved_10_31 : HAL.UInt22 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CFR_Register use record W at 0 range 0 .. 6; WDGTB at 0 range 7 .. 8; EWI at 0 range 9 .. 9; Reserved_10_31 at 0 range 10 .. 31; end record; -- Status register (WWDG_SR) type SR_Register is record -- Early Wakeup Interrupt EWI : Boolean := False; -- unspecified Reserved_1_31 : HAL.UInt31 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for SR_Register use record EWI at 0 range 0 .. 0; Reserved_1_31 at 0 range 1 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- Window watchdog type WWDG_Peripheral is record -- Control register (WWDG_CR) CR : aliased CR_Register; -- Configuration register (WWDG_CFR) CFR : aliased CFR_Register; -- Status register (WWDG_SR) SR : aliased SR_Register; end record with Volatile; for WWDG_Peripheral use record CR at 16#0# range 0 .. 31; CFR at 16#4# range 0 .. 31; SR at 16#8# range 0 .. 31; end record; -- Window watchdog WWDG_Periph : aliased WWDG_Peripheral with Import, Address => System'To_Address (16#40002C00#); end STM32_SVD.WWDG;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- L I B . X R E F -- -- -- -- B o d y -- -- -- -- $Revision$ -- -- -- Copyright (C) 1998-2001, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, -- -- MA 02111-1307, USA. -- -- -- -- 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 Csets; use Csets; with Debug; use Debug; with Lib.Util; use Lib.Util; with Namet; use Namet; with Opt; use Opt; with Sinfo; use Sinfo; with Sinput; use Sinput; with Table; use Table; with Widechar; use Widechar; with GNAT.Heap_Sort_A; package body Lib.Xref is ------------------ -- Declarations -- ------------------ -- The Xref table is used to record references. The Loc field is set -- to No_Location for a definition entry. subtype Xref_Entry_Number is Int; type Xref_Entry is record Ent : Entity_Id; -- Entity referenced (E parameter to Generate_Reference) Def : Source_Ptr; -- Original source location for entity being referenced. Note that -- these values are used only during the output process, they are -- not set when the entries are originally built. This is because -- private entities can be swapped when the initial call is made. Loc : Source_Ptr; -- Location of reference (Original_Location (Sloc field of N parameter -- to Generate_Reference). Set to No_Location for the case of a -- defining occurrence. Typ : Character; -- Reference type (Typ param to Generate_Reference) Eun : Unit_Number_Type; -- Unit number corresponding to Ent Lun : Unit_Number_Type; -- Unit number corresponding to Loc. Value is undefined and not -- referenced if Loc is set to No_Location. end record; package Xrefs is new Table.Table ( Table_Component_Type => Xref_Entry, Table_Index_Type => Int, Table_Low_Bound => 1, Table_Initial => Alloc.Xrefs_Initial, Table_Increment => Alloc.Xrefs_Increment, Table_Name => "Xrefs"); ------------------------- -- Generate_Definition -- ------------------------- procedure Generate_Definition (E : Entity_Id) is Loc : Source_Ptr; Indx : Nat; begin pragma Assert (Nkind (E) in N_Entity); -- Note that we do not test Xref_Entity_Letters here. It is too -- early to do so, since we are often called before the entity -- is fully constructed, so that the Ekind is still E_Void. if Opt.Xref_Active -- Definition must come from source and then Comes_From_Source (E) -- And must have a reasonable source location that is not -- within an instance (all entities in instances are ignored) and then Sloc (E) > No_Location and then Instantiation_Location (Sloc (E)) = No_Location -- And must be a non-internal name from the main source unit and then In_Extended_Main_Source_Unit (E) and then not Is_Internal_Name (Chars (E)) then Xrefs.Increment_Last; Indx := Xrefs.Last; Loc := Original_Location (Sloc (E)); Xrefs.Table (Indx).Ent := E; Xrefs.Table (Indx).Loc := No_Location; Xrefs.Table (Indx).Eun := Get_Source_Unit (Loc); Xrefs.Table (Indx).Lun := No_Unit; end if; end Generate_Definition; --------------------------------- -- Generate_Operator_Reference -- --------------------------------- procedure Generate_Operator_Reference (N : Node_Id) is begin if not In_Extended_Main_Source_Unit (N) then return; end if; -- If the operator is not a Standard operator, then we generate -- a real reference to the user defined operator. if Sloc (Entity (N)) /= Standard_Location then Generate_Reference (Entity (N), N); -- A reference to an implicit inequality operator is a also a -- reference to the user-defined equality. if Nkind (N) = N_Op_Ne and then not Comes_From_Source (Entity (N)) and then Present (Corresponding_Equality (Entity (N))) then Generate_Reference (Corresponding_Equality (Entity (N)), N); end if; -- For the case of Standard operators, we mark the result type -- as referenced. This ensures that in the case where we are -- using a derived operator, we mark an entity of the unit that -- implicitly defines this operator as used. Otherwise we may -- think that no entity of the unit is used. The actual entity -- marked as referenced is the first subtype, which is the user -- defined entity that is relevant. else if Nkind (N) = N_Op_Eq or else Nkind (N) = N_Op_Ne or else Nkind (N) = N_Op_Le or else Nkind (N) = N_Op_Lt or else Nkind (N) = N_Op_Ge or else Nkind (N) = N_Op_Gt then Set_Referenced (First_Subtype (Etype (Right_Opnd (N)))); else Set_Referenced (First_Subtype (Etype (N))); end if; end if; end Generate_Operator_Reference; ------------------------ -- Generate_Reference -- ------------------------ procedure Generate_Reference (E : Entity_Id; N : Node_Id; Typ : Character := 'r'; Set_Ref : Boolean := True; Force : Boolean := False) is Indx : Nat; Nod : Node_Id; Ref : Source_Ptr; Def : Source_Ptr; Ent : Entity_Id; begin pragma Assert (Nkind (E) in N_Entity); -- Never collect references if not in main source unit. However, -- we omit this test if Typ is 'e', since these entries are -- really structural, and it is useful to have them in units -- that reference packages as well as units that define packages. if not In_Extended_Main_Source_Unit (N) and then Typ /= 'e' then return; end if; -- Unless the reference is forced, we ignore references where -- the reference itself does not come from Source. if not Force and then not Comes_From_Source (N) then return; end if; -- Deal with setting entity as referenced, unless suppressed. -- Note that we still do Set_Referenced on entities that do not -- come from source. This situation arises when we have a source -- reference to a derived operation, where the derived operation -- itself does not come from source, but we still want to mark it -- as referenced, since we really are referencing an entity in the -- corresponding package (this avoids incorrect complaints that the -- package contains no referenced entities). if Set_Ref then Set_Referenced (E); -- If this is a subprogram instance, mark as well the internal -- subprogram in the wrapper package, which may be a visible -- compilation unit. if Is_Overloadable (E) and then Is_Generic_Instance (E) and then Present (Alias (E)) then Set_Referenced (Alias (E)); end if; end if; -- Generate reference if all conditions are met: if -- Cross referencing must be active Opt.Xref_Active -- The entity must be one for which we collect references and then Xref_Entity_Letters (Ekind (E)) /= ' ' -- Both Sloc values must be set to something sensible and then Sloc (E) > No_Location and then Sloc (N) > No_Location -- We ignore references from within an instance and then Instantiation_Location (Sloc (N)) = No_Location -- Ignore dummy references and then Typ /= ' ' then if Nkind (N) = N_Identifier or else Nkind (N) = N_Defining_Identifier or else Nkind (N) in N_Op or else Nkind (N) = N_Defining_Operator_Symbol or else (Nkind (N) = N_Character_Literal and then Sloc (Entity (N)) /= Standard_Location) or else Nkind (N) = N_Defining_Character_Literal then Nod := N; elsif Nkind (N) = N_Expanded_Name or else Nkind (N) = N_Selected_Component then Nod := Selector_Name (N); else return; end if; -- Normal case of source entity comes from source if Comes_From_Source (E) then Ent := E; -- Entity does not come from source, but is a derived subprogram -- and the derived subprogram comes from source, in which case -- the reference is to this parent subprogram. elsif Is_Overloadable (E) and then Present (Alias (E)) and then Comes_From_Source (Alias (E)) then Ent := Alias (E); -- Ignore reference to any other source that is not from source else return; end if; -- Record reference to entity Ref := Original_Location (Sloc (Nod)); Def := Original_Location (Sloc (Ent)); Xrefs.Increment_Last; Indx := Xrefs.Last; Xrefs.Table (Indx).Loc := Ref; Xrefs.Table (Indx).Typ := Typ; Xrefs.Table (Indx).Eun := Get_Source_Unit (Def); Xrefs.Table (Indx).Lun := Get_Source_Unit (Ref); Xrefs.Table (Indx).Ent := Ent; end if; end Generate_Reference; ----------------------- -- Output_References -- ----------------------- procedure Output_References is Nrefs : constant Nat := Xrefs.Last; Rnums : array (0 .. Nrefs) of Nat; -- This array contains numbers of references in the Xrefs table. This -- list is sorted in output order. The extra 0'th entry is convenient -- for the call to sort. When we sort the table, we move these entries -- around, but we do not move the original table entries. function Lt (Op1, Op2 : Natural) return Boolean; -- Comparison function for Sort call procedure Move (From : Natural; To : Natural); -- Move procedure for Sort call function Lt (Op1, Op2 : Natural) return Boolean is T1 : Xref_Entry renames Xrefs.Table (Rnums (Nat (Op1))); T2 : Xref_Entry renames Xrefs.Table (Rnums (Nat (Op2))); begin -- First test. If entity is in different unit, sort by unit if T1.Eun /= T2.Eun then return Dependency_Num (T1.Eun) < Dependency_Num (T2.Eun); -- Second test, within same unit, sort by entity Sloc elsif T1.Def /= T2.Def then return T1.Def < T2.Def; -- Third test, sort definitions ahead of references elsif T1.Loc = No_Location then return True; elsif T2.Loc = No_Location then return False; -- Fourth test, for same entity, sort by reference location unit elsif T1.Lun /= T2.Lun then return Dependency_Num (T1.Lun) < Dependency_Num (T2.Lun); -- Fifth test order of location within referencing unit elsif T1.Loc /= T2.Loc then return T1.Loc < T2.Loc; -- Finally, for two locations at the same address, we prefer -- the one that does NOT have the type 'r' so that a modification -- or extension takes preference, when there are more than one -- reference at the same location. else return T2.Typ = 'r'; end if; end Lt; procedure Move (From : Natural; To : Natural) is begin Rnums (Nat (To)) := Rnums (Nat (From)); end Move; -- Start of processing for Output_References begin if not Opt.Xref_Active then return; end if; -- Capture the definition Sloc values. We delay doing this till now, -- since at the time the reference or definition is made, private -- types may be swapped, and the Sloc value may be incorrect. We -- also set up the pointer vector for the sort. for J in 1 .. Nrefs loop Rnums (J) := J; Xrefs.Table (J).Def := Original_Location (Sloc (Xrefs.Table (J).Ent)); end loop; -- Sort the references GNAT.Heap_Sort_A.Sort (Integer (Nrefs), Move'Unrestricted_Access, Lt'Unrestricted_Access); -- Now output the references Output_Refs : declare Curxu : Unit_Number_Type; -- Current xref unit Curru : Unit_Number_Type; -- Current reference unit for one entity Cursrc : Source_Buffer_Ptr; -- Current xref unit source text Curent : Entity_Id; -- Current entity Curnam : String (1 .. Name_Buffer'Length); Curlen : Natural; -- Simple name and length of current entity Curdef : Source_Ptr; -- Original source location for current entity Crloc : Source_Ptr; -- Current reference location Ctyp : Character; -- Entity type character Tref : Entity_Id; -- Type reference Rref : Node_Id; -- Renaming reference Trunit : Unit_Number_Type; -- Unit number for type reference function Name_Change (X : Entity_Id) return Boolean; -- Determines if entity X has a different simple name from Curent ----------------- -- Name_Change -- ----------------- function Name_Change (X : Entity_Id) return Boolean is begin Get_Unqualified_Name_String (Chars (X)); if Name_Len /= Curlen then return True; else return Name_Buffer (1 .. Curlen) /= Curnam (1 .. Curlen); end if; end Name_Change; -- Start of processing for Output_Refs begin Curxu := No_Unit; Curent := Empty; Curdef := No_Location; Curru := No_Unit; Crloc := No_Location; for Refno in 1 .. Nrefs loop Output_One_Ref : declare XE : Xref_Entry renames Xrefs.Table (Rnums (Refno)); -- The current entry to be accessed P : Source_Ptr; -- Used to index into source buffer to get entity name P2 : Source_Ptr; WC : Char_Code; Err : Boolean; Ent : Entity_Id; Sav : Entity_Id; Left : Character; Right : Character; -- Used for {} or <> for type reference procedure Output_Instantiation_Refs (Loc : Source_Ptr); -- Recursive procedure to output instantiation references for -- the given source ptr in [file|line[...]] form. No output -- if the given location is not a generic template reference. ------------------------------- -- Output_Instantiation_Refs -- ------------------------------- procedure Output_Instantiation_Refs (Loc : Source_Ptr) is Iloc : constant Source_Ptr := Instantiation_Location (Loc); Lun : Unit_Number_Type; begin -- Nothing to do if this is not an instantiation if Iloc = No_Location then return; end if; -- For now, nothing to do unless special debug flag set if not Debug_Flag_MM then return; end if; -- Output instantiation reference Write_Info_Char ('['); Lun := Get_Source_Unit (Iloc); if Lun /= Curru then Curru := XE.Lun; Write_Info_Nat (Dependency_Num (Curru)); Write_Info_Char ('|'); end if; Write_Info_Nat (Int (Get_Logical_Line_Number (Iloc))); -- Recursive call to get nested instantiations Output_Instantiation_Refs (Iloc); -- Output final ] after call to get proper nesting Write_Info_Char (']'); return; end Output_Instantiation_Refs; -- Start of processing for Output_One_Ref begin Ent := XE.Ent; Ctyp := Xref_Entity_Letters (Ekind (Ent)); -- Skip reference if it is the only reference to an entity, -- and it is an end-line reference, and the entity is not in -- the current extended source. This prevents junk entries -- consisting only of packages with end lines, where no -- entity from the package is actually referenced. if XE.Typ = 'e' and then Ent /= Curent and then (Refno = Nrefs or else Ent /= Xrefs.Table (Rnums (Refno + 1)).Ent) and then not In_Extended_Main_Source_Unit (Ent) then goto Continue; end if; -- For private type, get full view type if Ctyp = '+' and then Present (Full_View (XE.Ent)) then Ent := Underlying_Type (Ent); if Present (Ent) then Ctyp := Xref_Entity_Letters (Ekind (Ent)); end if; end if; -- Special exception for Boolean if Ctyp = 'E' and then Is_Boolean_Type (Ent) then Ctyp := 'B'; end if; -- For variable reference, get corresponding type if Ctyp = '*' then Ent := Etype (XE.Ent); Ctyp := Fold_Lower (Xref_Entity_Letters (Ekind (Ent))); -- If variable is private type, get full view type if Ctyp = '+' and then Present (Full_View (Etype (XE.Ent))) then Ent := Underlying_Type (Etype (XE.Ent)); if Present (Ent) then Ctyp := Xref_Entity_Letters (Ekind (Ent)); end if; end if; -- Special handling for access parameter if Ekind (Etype (XE.Ent)) = E_Anonymous_Access_Type and then Is_Formal (XE.Ent) then Ctyp := 'p'; -- Special handling for Boolean elsif Ctyp = 'e' and then Is_Boolean_Type (Ent) then Ctyp := 'b'; end if; end if; -- Only output reference if interesting type of entity, -- and suppress self references. Also suppress definitions -- of body formals (we only treat these as references, and -- the references were separately recorded). if Ctyp /= ' ' and then XE.Loc /= XE.Def and then (not Is_Formal (XE.Ent) or else No (Spec_Entity (XE.Ent))) then -- Start new Xref section if new xref unit if XE.Eun /= Curxu then if Write_Info_Col > 1 then Write_Info_EOL; end if; Curxu := XE.Eun; Cursrc := Source_Text (Source_Index (Curxu)); Write_Info_Initiate ('X'); Write_Info_Char (' '); Write_Info_Nat (Dependency_Num (XE.Eun)); Write_Info_Char (' '); Write_Info_Name (Reference_Name (Source_Index (XE.Eun))); end if; -- Start new Entity line if new entity. Note that we -- consider two entities the same if they have the same -- name and source location. This causes entities in -- instantiations to be treated as though they referred -- to the template. if No (Curent) or else (XE.Ent /= Curent and then (Name_Change (XE.Ent) or else XE.Def /= Curdef)) then Curent := XE.Ent; Curdef := XE.Def; Get_Unqualified_Name_String (Chars (XE.Ent)); Curlen := Name_Len; Curnam (1 .. Curlen) := Name_Buffer (1 .. Curlen); if Write_Info_Col > 1 then Write_Info_EOL; end if; -- Write column number information Write_Info_Nat (Int (Get_Logical_Line_Number (XE.Def))); Write_Info_Char (Ctyp); Write_Info_Nat (Int (Get_Column_Number (XE.Def))); -- Write level information if Is_Public (Curent) and then not Is_Hidden (Curent) then Write_Info_Char ('*'); else Write_Info_Char (' '); end if; -- Output entity name. We use the occurrence from the -- actual source program at the definition point P := Original_Location (Sloc (XE.Ent)); -- Entity is character literal if Cursrc (P) = ''' then Write_Info_Char (Cursrc (P)); Write_Info_Char (Cursrc (P + 1)); Write_Info_Char (Cursrc (P + 2)); -- Entity is operator symbol elsif Cursrc (P) = '"' or else Cursrc (P) = '%' then Write_Info_Char (Cursrc (P)); P2 := P; loop P2 := P2 + 1; Write_Info_Char (Cursrc (P2)); exit when Cursrc (P2) = Cursrc (P); end loop; -- Entity is identifier else loop if Is_Start_Of_Wide_Char (Cursrc, P) then Scan_Wide (Cursrc, P, WC, Err); elsif not Identifier_Char (Cursrc (P)) then exit; else P := P + 1; end if; end loop; for J in Original_Location (Sloc (XE.Ent)) .. P - 1 loop Write_Info_Char (Cursrc (J)); end loop; end if; -- See if we have a renaming reference if Is_Object (XE.Ent) and then Present (Renamed_Object (XE.Ent)) then Rref := Renamed_Object (XE.Ent); elsif Is_Overloadable (XE.Ent) and then Nkind (Parent (Declaration_Node (XE.Ent))) = N_Subprogram_Renaming_Declaration then Rref := Name (Parent (Declaration_Node (XE.Ent))); elsif Ekind (XE.Ent) = E_Package and then Nkind (Declaration_Node (XE.Ent)) = N_Package_Renaming_Declaration then Rref := Name (Declaration_Node (XE.Ent)); else Rref := Empty; end if; if Present (Rref) then if Nkind (Rref) = N_Expanded_Name then Rref := Selector_Name (Rref); end if; if Nkind (Rref) /= N_Identifier then Rref := Empty; end if; end if; -- Write out renaming reference if we have one if Debug_Flag_MM and then Present (Rref) then Write_Info_Char ('='); Write_Info_Nat (Int (Get_Logical_Line_Number (Sloc (Rref)))); Write_Info_Char (':'); Write_Info_Nat (Int (Get_Column_Number (Sloc (Rref)))); end if; -- See if we have a type reference Tref := XE.Ent; Left := '{'; Right := '}'; loop Sav := Tref; -- Processing for types if Is_Type (Tref) then -- Case of base type if Base_Type (Tref) = Tref then -- If derived, then get first subtype if Tref /= Etype (Tref) then Tref := First_Subtype (Etype (Tref)); -- Set brackets for derived type, but don't -- override pointer case since the fact that -- something is a pointer is more important if Left /= '(' then Left := '<'; Right := '>'; end if; -- If non-derived ptr, get designated type elsif Is_Access_Type (Tref) then Tref := Designated_Type (Tref); Left := '('; Right := ')'; -- For other non-derived base types, nothing else exit; end if; -- For a subtype, go to ancestor subtype else Tref := Ancestor_Subtype (Tref); -- If no ancestor subtype, go to base type if No (Tref) then Tref := Base_Type (Sav); end if; end if; -- For objects, functions, enum literals, -- just get type from Etype field. elsif Is_Object (Tref) or else Ekind (Tref) = E_Enumeration_Literal or else Ekind (Tref) = E_Function or else Ekind (Tref) = E_Operator then Tref := Etype (Tref); -- For anything else, exit else exit; end if; -- Exit if no type reference, or we are stuck in -- some loop trying to find the type reference. exit when No (Tref) or else Tref = Sav; -- Here we have a type reference to output -- Case of standard entity, output name if Sloc (Tref) = Standard_Location then -- For now, output only if special -gnatdM flag set exit when not Debug_Flag_MM; Write_Info_Char (Left); Write_Info_Name (Chars (Tref)); Write_Info_Char (Right); exit; -- Case of source entity, output location elsif Comes_From_Source (Tref) then -- For now, output only derived type entries -- unless we have special debug flag -gnatdM exit when not (Debug_Flag_MM or else Left = '<'); -- Do not output type reference if referenced -- entity is not in the main unit and is itself -- not referenced, since otherwise the reference -- will dangle. exit when not Referenced (Tref) and then not In_Extended_Main_Source_Unit (Tref); -- Output the reference Write_Info_Char (Left); Trunit := Get_Source_Unit (Sloc (Tref)); if Trunit /= Curxu then Write_Info_Nat (Dependency_Num (Trunit)); Write_Info_Char ('|'); end if; Write_Info_Nat (Int (Get_Logical_Line_Number (Sloc (Tref)))); Write_Info_Char (Xref_Entity_Letters (Ekind (Tref))); Write_Info_Nat (Int (Get_Column_Number (Sloc (Tref)))); Write_Info_Char (Right); exit; -- If non-standard, non-source entity, keep looking else null; end if; end loop; -- End of processing for entity output Curru := Curxu; Crloc := No_Location; end if; -- Output the reference if XE.Loc /= No_Location and then XE.Loc /= Crloc then Crloc := XE.Loc; -- Start continuation if line full, else blank if Write_Info_Col > 72 then Write_Info_EOL; Write_Info_Initiate ('.'); end if; Write_Info_Char (' '); -- Output file number if changed if XE.Lun /= Curru then Curru := XE.Lun; Write_Info_Nat (Dependency_Num (Curru)); Write_Info_Char ('|'); end if; Write_Info_Nat (Int (Get_Logical_Line_Number (XE.Loc))); Write_Info_Char (XE.Typ); Write_Info_Nat (Int (Get_Column_Number (XE.Loc))); Output_Instantiation_Refs (Sloc (XE.Ent)); end if; end if; end Output_One_Ref; <<Continue>> null; end loop; Write_Info_EOL; end Output_Refs; end Output_References; end Lib.Xref;
-- Project: StratoX -- System: Stratosphere Balloon Flight Controller -- Author: Martin Becker (becker@rcs.ei.tum.de) -- based on AdaCore's Ada_Driver_Library -- XXX! Nothing here is thread-safe! -- @summary Directory (end directory entries) handling for FAT FS package FAT_Filesystem.Directories with SPARK_Mode => Off is type Directory_Handle is private; -- used to read directories function Open_Root_Directory (FS : FAT_Filesystem_Access; Dir : out Directory_Handle) return Status_Code; type Directory_Entry is private; -- used to represent one item in directory function Open (E : Directory_Entry; Dir : out Directory_Handle) return Status_Code with Pre => Is_Subdirectory (E); -- get handle of given item. Handle can be used with Read(). function Make_Directory (Parent : in out Directory_Handle; newname : String; D_Entry : out Directory_Entry) return Status_Code with Pre => newname'Length < 12; -- create a new directory within the given one -- we only allow short names for now. -- if directory already exists, returns its entry. procedure Close (Dir : in out Directory_Handle); function Read (Dir : in out Directory_Handle; DEntry : out Directory_Entry; Deleted : Boolean := False) return Status_Code; -- @summary get the next entry in the given directory -- after calling this, Dir.Dir_Current are invalid iff return /= OK. -- However, the Dir_Begin and Dir_End components are always valid. -- if Deleted is true, then deleted entries are also returned and -- marked with FS=null function Get_Name (E : Directory_Entry) return String; function Is_Read_Only (E : Directory_Entry) return Boolean; function Is_Hidden (E : Directory_Entry) return Boolean; function Is_System_File (E : Directory_Entry) return Boolean; function Is_Subdirectory (E : Directory_Entry) return Boolean; function Is_Archive (E : Directory_Entry) return Boolean; private pragma SPARK_Mode (Off); type FAT_Directory_Entry_Attribute is record Read_Only : Boolean; Hidden : Boolean; System_File : Boolean; Volume_Label : Boolean; Subdirectory : Boolean; Archive : Boolean; end record with Size => 8, Pack; type FAT_Directory_Entry is record Filename : String (1 .. 8); Extension : String (1 .. 3); Attributes : FAT_Directory_Entry_Attribute; Reserved : String (1 .. 8); Cluster_H : Unsigned_16; Time : Unsigned_16; Date : Unsigned_16; Cluster_L : Unsigned_16; Size : Unsigned_32; -- TODO: what is this? end record with Size => 32 * 8; -- 32 Byte per entry for FAT_Directory_Entry use record Filename at 16#00# range 0 .. 63; Extension at 16#08# range 0 .. 23; Attributes at 16#0B# range 0 .. 7; Reserved at 16#0C# range 0 .. 63; Cluster_H at 16#14# range 0 .. 15; Time at 16#16# range 0 .. 15; Date at 16#18# range 0 .. 15; Cluster_L at 16#1A# range 0 .. 15; Size at 16#1C# range 0 .. 31; end record; ENTRY_SIZE : constant := 32; VFAT_Directory_Entry_Attribute : constant FAT_Directory_Entry_Attribute := (Subdirectory => False, Archive => False, others => True); -- Attrite value 16#F0# defined at offset 16#0B# and identifying a VFAT -- entry rather than a regular directory entry type VFAT_Sequence_Number is mod 2 ** 5 with Size => 5; type VFAT_Sequence is record Sequence : VFAT_Sequence_Number; Stop_Bit : Boolean; end record with Size => 8, Pack; type VFAT_Directory_Entry is record VFAT_Attr : VFAT_Sequence; Name_1 : Wide_String (1 .. 5); Attribute : FAT_Directory_Entry_Attribute; E_Type : Unsigned_8; Checksum : Unsigned_8; Name_2 : Wide_String (1 .. 6); Cluster : Unsigned_16; Name_3 : Wide_String (1 .. 2); end record with Pack, Size => 32 * 8; -- type File_Object_Structure is record -- FS : FAT_Filesystem_Access; -- Flags : Unsigned_8; -- Err : Unsigned_8; -- File_Ptr : Unsigned_32 := 0; -- File_Size : Unsigned_32; -- Start_Cluster : Unsigned_32; -- Current_Cluster : Unsigned_32; -- end record; -- FIXME: encapsulate this, and provide function "move_forward" or something. type Directory_Handle_Pointer is record Index : Unsigned_16; Cluster : Unsigned_32; Block : Unsigned_32; end record; procedure Invalidate_Handle_Pointer (h : in out Directory_Handle_Pointer); function Valid_Handle_Pointer (h : Directory_Handle_Pointer) return Boolean; type Directory_Handle is record FS : FAT_Filesystem_Access; Dir_Begin : Directory_Handle_Pointer; -- points to the first entry of the directory Dir_Current : Directory_Handle_Pointer; -- points to the current, valid entry Dir_End : Directory_Handle_Pointer; -- points past the last valid entry end record; -- used to read directories type Directory_Entry is record FS : FAT_Filesystem_Access; Name : String (1 .. 128); Name_First : Natural := 129; -- where the string starts within 'Name' Name_Last : Natural := 0; -- where the string ends within 'Name' CRC : Unsigned_8 := 0; Attributes : FAT_Directory_Entry_Attribute; Start_Cluster : Unsigned_32; -- the address of the data/contents of the entry Size : Unsigned_32; Entry_Address : FAT_Address; -- the address of the entry itself -- FIXME: add time stamps, attributes, etc. end record; -- each item in a directory is described by this in high-level view procedure Rewind (Dir : in out Directory_Handle); function Get_Entry_Or_Deleted (Parent : in out Directory_Handle; E_Name : String; Ent : out Directory_Entry; Deleted : out Boolean) return Boolean; -- search for entry with the given name. -- if Deleted is true, then the 'Ent' points -- to an empty directory entry that can be -- re-used. If Deleted is false, then an entry -- with the given name was actually found function Is_Deleted (F_Entry : FAT_Directory_Entry) return Boolean; function Get_Entry (Parent : in out Directory_Handle; E_Name : String; Ent : out Directory_Entry) return Boolean; -- search for entry with the given name. procedure Goto_Last_Entry (Parent : in out Directory_Handle); -- proceed to last entry in given directory function Allocate_Entry (Parent : in out Directory_Handle; New_Name : String; Ent_Addr : out FAT_Address) return Status_Code; -- find a location for a new entry within Parent_Ent -- and make sure that the directory stays terminated procedure Set_Name (newname : String; D : in out Directory_Entry) with Pre => newname'Length > 0; procedure Set_Name (newname : String; E : in out FAT_Directory_Entry) with Pre => newname'Length > 0; function Directory_To_FAT_Entry (D_Entry : in Directory_Entry; F_Entry : out FAT_Directory_Entry) return Status_Code; function FAT_To_Directory_Entry (FS : FAT_Filesystem_Access; F_Entry : in FAT_Directory_Entry; D_Entry : in out Directory_Entry; Last_Seq : in out VFAT_Sequence_Number) return Status_Code; -- @summary decypher the raw entry (file/dir name, etc) and write -- to record. -- @return OK when decipher is complete, otherwise needs to be -- called again with the next entry (VFAT entries have -- multiple parts) function Is_Read_Only (E : Directory_Entry) return Boolean is (E.Attributes.Read_Only); function Is_Hidden (E : Directory_Entry) return Boolean is (E.Attributes.Hidden); function Is_System_File (E : Directory_Entry) return Boolean is (E.Attributes.System_File); function Is_Subdirectory (E : Directory_Entry) return Boolean is (E.Attributes.Subdirectory); function Is_Archive (E : Directory_Entry) return Boolean is (E.Attributes.Archive); end FAT_Filesystem.Directories;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- G N A T V S N -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2020, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ package body Gnatvsn is ---------------------- -- Copyright_Holder -- ---------------------- function Copyright_Holder return String is begin return "Free Software Foundation, Inc."; end Copyright_Holder; ------------------------ -- Gnat_Free_Software -- ------------------------ function Gnat_Free_Software return String is begin return "This is free software; see the source for copying conditions." & ASCII.LF & "There is NO warranty; not even for MERCHANTABILITY or FITNESS" & " FOR A PARTICULAR PURPOSE."; end Gnat_Free_Software; type char_array is array (Natural range <>) of aliased Character; Version_String : char_array (0 .. Ver_Len_Max - 1); -- Import the C string defined in the (language-independent) source file -- version.c using the zero-based convention of the C language. -- The size is not the real one, which does not matter since we will -- check for the nul character in Gnat_Version_String. pragma Import (C, Version_String, "version_string"); ------------------------- -- Gnat_Version_String -- ------------------------- function Gnat_Version_String return String is S : String (1 .. Ver_Len_Max); Pos : Natural := 0; begin loop exit when Version_String (Pos) = ASCII.NUL; S (Pos + 1) := Version_String (Pos); Pos := Pos + 1; exit when Pos = Ver_Len_Max; end loop; return S (1 .. Pos); end Gnat_Version_String; end Gnatvsn;
with agar.core.types; with agar.core.tail_queue; with agar.gui.widget.label; package agar.gui.widget.fixed_plotter is use type c.unsigned; type item_t is limited private; type item_access_t is access all item_t; pragma convention (c, item_access_t); type plotter_t; type plotter_access_t is access all plotter_t; pragma convention (c, plotter_access_t); package item_tail_queue is new agar.core.tail_queue (entry_type => item_access_t); subtype value_t is agar.core.types.uint16_t; type name_t is array (1 .. agar.gui.widget.label.max) of aliased c.char; pragma convention (c, name_t); type type_t is (PLOTTER_POINTS, PLOTTER_LINES); for type_t use (PLOTTER_POINTS => 0, PLOTTER_LINES => 1); for type_t'size use c.unsigned'size; pragma convention (c, type_t); type flags_t is new c.unsigned; PLOTTER_SCROLL : constant flags_t := 16#01#; PLOTTER_XAXIS : constant flags_t := 16#02#; PLOTTER_HFILL : constant flags_t := 16#04#; PLOTTER_VFILL : constant flags_t := 16#08#; PLOTTER_EXPAND : constant flags_t := PLOTTER_HFILL or PLOTTER_VFILL; type plotter_priv_t is limited private; type plotter_t is record widget : aliased widget_t; plotter_type : type_t; privdata : plotter_priv_t; end record; pragma convention (c, plotter_t); -- API function allocate (parent : widget_access_t; plot_type : type_t; flags : flags_t) return plotter_access_t; pragma import (c, allocate, "AG_FixedPlotterNew"); function curve (plotter : plotter_access_t; name : string; r : agar.core.types.uint8_t; g : agar.core.types.uint8_t; b : agar.core.types.uint8_t; limit : agar.core.types.uint32_t) return item_access_t; pragma inline (curve); procedure datum (plotter : plotter_access_t; value : value_t); pragma import (c, datum, "AG_FixedPlotterDatum"); function widget (plotter : plotter_access_t) return widget_access_t; pragma inline (widget); private type plotter_priv_t is record flags : flags_t; y_range : value_t; x_offset : value_t; y_origin : c.int; items : item_tail_queue.head_t; end record; pragma convention (c, plotter_priv_t); type item_t is record name : name_t; color : agar.core.types.uint32_t; values : access value_t; nvalues : agar.core.types.uint32_t; maxvalues : agar.core.types.uint32_t; limit : agar.core.types.uint32_t; fpl : plotter_access_t; items : item_tail_queue.entry_t; end record; pragma convention (c, item_t); end agar.gui.widget.fixed_plotter;
with AVR.MCU; -- ============================================================================= -- Package body AVR.TIMERS.CLOCK -- ============================================================================= package body AVR.TIMERS.CLOCK is procedure Initialize (Timer : TIMERS.Timer_Type) is use type TIMERS.Timer_Type; begin if Timer = TIMERS.TIMER4 then --+-------------------------------------------------------------------- --| Timer/Counter 1 Control Register A: --| TCCR1A = COM1A1|COM1A0|COM1B1|COM1B0|COM1C1|COM1C0|WGM11|WGM10 --| --| Normal operation (WGM=0|0|0|0), normal port operation: --| TCCR1A = 0|0|0|0|0|0|0|0 --+-------------------------------------------------------------------- --Reg_Timer1.TCCRA := 0; -- That is already 0 --+-------------------------------------------------------------------- --| Timer/Counter 1 Control Register B: --| TCCR1B = ICNC1|ICES1|--|WGM13|WGM12|CS12|CS11|CS10 --| --| ICNC1 = Input Capture Noise Canceller : not used (=0) --| ICES1 = Input Capture Edge Select : negative edge (=0) --| Normal operation (WGM=0|0|0|0) --| CS12:0 : Clock Select = No prescalling : 0|0|1 --| TCCR1B = 0|0|0|0|0|0|0|1 --+-------------------------------------------------------------------- Reg_Timer4.TCCRB.CS (0) := True; -- Initialize Counter Reg_Timer4.TCNT := (others => 0); -- Enable overflow interrupt Reg_Timer4_TIMSK.TOIE := True; -- Enable the overflow flag Reg_Timer4_TIFR.TOV := True; end if; end Initialize; procedure Schedule_Update_Clock is begin -- Priv_Clock_Cycles here is actually 16#FFFF# cycles, due to the -- interrupt overflow call. So when reading the clock, this value shall be -- multiplied by 16#FFFF# to give the right number of cycles passed. Priv_Clock_Cycles := Priv_Clock_Cycles + 1; end Schedule_Update_Clock; function Get_Current_Time_In_Nanoseconds return Unsigned_64 is begin -- The multiplication by 16#FFFF# is because the overflow interrupt is -- called when the timer counts from 0 to 16#FFFF#, so it passes all these -- cycles before called. return (Priv_Clock_Cycles * 1_000_000_000 / AVR.MCU.F_CPU) * 16#FFFF#; exception when others => return 0; end Get_Current_Time_In_Nanoseconds; function Get_Current_Time_In_Seconds return Unsigned_64 is begin return Get_Current_Time_In_Nanoseconds / 1_000_000_000; exception when others => return 0; end Get_Current_Time_In_Seconds; function Get_Current_Time return Time_Type is Curr_Time : Time_Type; Curr_Seconds : constant Unsigned_64 := Get_Current_Time_In_Seconds; begin Curr_Time.HH := Time_Hour_Type (Curr_Seconds / Unsigned_64 (3600)); Curr_Time.MM := Time_Minute_Type ((Curr_Seconds - Unsigned_64 (Curr_Time.HH * 3600)) / Unsigned_64 (60)); Curr_Time.SS := Time_Second_Type ((Curr_Seconds - Unsigned_64 (Curr_Time.HH * 3600) - Unsigned_64 (Curr_Time.MM * 60)) / Unsigned_64 (60)); return Curr_Time; exception when others => return (HH => 0, MM => 0, SS => 0); end Get_Current_Time; end AVR.TIMERS.CLOCK;
with Interfaces.C.Strings, System; use type Interfaces.C.int, Interfaces.C.Strings.chars_ptr, System.Address; package body FLTK.Event is procedure fl_event_add_handler (F : in System.Address); pragma Import (C, fl_event_add_handler, "fl_event_add_handler"); pragma Inline (fl_event_add_handler); procedure fl_event_set_event_dispatch (F : in System.Address); pragma Import (C, fl_event_set_event_dispatch, "fl_event_set_event_dispatch"); pragma Inline (fl_event_set_event_dispatch); -- actually handle_ but can't have an underscore on the end of an identifier function fl_event_handle (E : in Interfaces.C.int; W : in System.Address) return Interfaces.C.int; pragma Import (C, fl_event_handle, "fl_event_handle"); pragma Inline (fl_event_handle); function fl_event_get_grab return System.Address; pragma Import (C, fl_event_get_grab, "fl_event_get_grab"); pragma Inline (fl_event_get_grab); procedure fl_event_set_grab (T : in System.Address); pragma Import (C, fl_event_set_grab, "fl_event_set_grab"); pragma Inline (fl_event_set_grab); function fl_event_get_pushed return System.Address; pragma Import (C, fl_event_get_pushed, "fl_event_get_pushed"); pragma Inline (fl_event_get_pushed); procedure fl_event_set_pushed (T : in System.Address); pragma Import (C, fl_event_set_pushed, "fl_event_set_pushed"); pragma Inline (fl_event_set_pushed); function fl_event_get_belowmouse return System.Address; pragma Import (C, fl_event_get_belowmouse, "fl_event_get_belowmouse"); pragma Inline (fl_event_get_belowmouse); procedure fl_event_set_belowmouse (T : in System.Address); pragma Import (C, fl_event_set_belowmouse, "fl_event_set_belowmouse"); pragma Inline (fl_event_set_belowmouse); function fl_event_get_focus return System.Address; pragma Import (C, fl_event_get_focus, "fl_event_get_focus"); pragma Inline (fl_event_get_focus); procedure fl_event_set_focus (To : in System.Address); pragma Import (C, fl_event_set_focus, "fl_event_set_focus"); pragma Inline (fl_event_set_focus); function fl_event_compose (D : out Interfaces.C.int) return Interfaces.C.int; pragma Import (C, fl_event_compose, "fl_event_compose"); pragma Inline (fl_event_compose); procedure fl_event_compose_reset; pragma Import (C, fl_event_compose_reset, "fl_event_compose_reset"); pragma Inline (fl_event_compose_reset); function fl_event_text return Interfaces.C.Strings.chars_ptr; pragma Import (C, fl_event_text, "fl_event_text"); pragma Inline (fl_event_text); function fl_event_length return Interfaces.C.int; pragma Import (C, fl_event_length, "fl_event_length"); pragma Inline (fl_event_length); function fl_event_get return Interfaces.C.int; pragma Import (C, fl_event_get, "fl_event_get"); pragma Inline (fl_event_get); function fl_event_state return Interfaces.C.unsigned_long; pragma Import (C, fl_event_state, "fl_event_state"); pragma Inline (fl_event_state); function fl_event_check_state (S : in Interfaces.C.unsigned_long) return Interfaces.C.int; pragma Import (C, fl_event_check_state, "fl_event_check_state"); pragma Inline (fl_event_check_state); function fl_event_x return Interfaces.C.int; pragma Import (C, fl_event_x, "fl_event_x"); pragma Inline (fl_event_x); function fl_event_x_root return Interfaces.C.int; pragma Import (C, fl_event_x_root, "fl_event_x_root"); pragma Inline (fl_event_x_root); function fl_event_y return Interfaces.C.int; pragma Import (C, fl_event_y, "fl_event_y"); pragma Inline (fl_event_y); function fl_event_y_root return Interfaces.C.int; pragma Import (C, fl_event_y_root, "fl_event_y_root"); pragma Inline (fl_event_y_root); function fl_event_dx return Interfaces.C.int; pragma Import (C, fl_event_dx, "fl_event_dx"); pragma Inline (fl_event_dx); function fl_event_dy return Interfaces.C.int; pragma Import (C, fl_event_dy, "fl_event_dy"); pragma Inline (fl_event_dy); procedure fl_event_get_mouse (X, Y : out Interfaces.C.int); pragma Import (C, fl_event_get_mouse, "fl_event_get_mouse"); pragma Inline (fl_event_get_mouse); function fl_event_is_click return Interfaces.C.int; pragma Import (C, fl_event_is_click, "fl_event_is_click"); pragma Inline (fl_event_is_click); function fl_event_is_clicks return Interfaces.C.int; pragma Import (C, fl_event_is_clicks, "fl_event_is_clicks"); pragma Inline (fl_event_is_clicks); procedure fl_event_set_clicks (C : in Interfaces.C.int); pragma Import (C, fl_event_set_clicks, "fl_event_set_clicks"); pragma Inline (fl_event_set_clicks); function fl_event_button return Interfaces.C.int; pragma Import (C, fl_event_button, "fl_event_button"); pragma Inline (fl_event_button); function fl_event_button1 return Interfaces.C.int; pragma Import (C, fl_event_button1, "fl_event_button1"); pragma Inline (fl_event_button1); function fl_event_button2 return Interfaces.C.int; pragma Import (C, fl_event_button2, "fl_event_button2"); pragma Inline (fl_event_button2); function fl_event_button3 return Interfaces.C.int; pragma Import (C, fl_event_button3, "fl_event_button3"); pragma Inline (fl_event_button3); function fl_event_inside (X, Y, W, H : in Interfaces.C.int) return Interfaces.C.int; pragma Import (C, fl_event_inside, "fl_event_inside"); pragma Inline (fl_event_inside); function fl_event_key return Interfaces.C.unsigned_long; pragma Import (C, fl_event_key, "fl_event_key"); pragma Inline (fl_event_key); function fl_event_original_key return Interfaces.C.unsigned_long; pragma Import (C, fl_event_original_key, "fl_event_original_key"); pragma Inline (fl_event_original_key); function fl_event_key_during (K : in Interfaces.C.unsigned_long) return Interfaces.C.int; pragma Import (C, fl_event_key_during, "fl_event_key_during"); pragma Inline (fl_event_key_during); function fl_event_get_key (K : in Interfaces.C.unsigned_long) return Interfaces.C.int; pragma Import (C, fl_event_get_key, "fl_event_get_key"); pragma Inline (fl_event_get_key); function fl_event_ctrl return Interfaces.C.int; pragma Import (C, fl_event_ctrl, "fl_event_ctrl"); pragma Inline (fl_event_ctrl); function fl_event_alt return Interfaces.C.int; pragma Import (C, fl_event_alt, "fl_event_alt"); pragma Inline (fl_event_alt); function fl_event_command return Interfaces.C.int; pragma Import (C, fl_event_command, "fl_event_command"); pragma Inline (fl_event_command); function fl_event_shift return Interfaces.C.int; pragma Import (C, fl_event_shift, "fl_event_shift"); pragma Inline (fl_event_shift); function Event_Handler_Hook (Num : in Interfaces.C.int) return Interfaces.C.int is Ret_Val : Event_Outcome; begin for Func of reverse Handlers loop Ret_Val := Func (Event_Kind'Val (Num)); if Ret_Val /= Not_Handled then return Event_Outcome'Pos (Ret_Val); end if; end loop; return Event_Outcome'Pos (Not_Handled); end Event_Handler_Hook; -- function Dispatch_Hook -- (Num : in Interfaces.C.int; -- Ptr : in System.Address) -- return Interfaces.C.int -- is -- Ret_Val : Event_Outcome; -- Actual_Window : access FLTK.Widgets.Groups.Windows.Window'Class; -- begin -- if Ptr /= System.Null_Address then -- Actual_Window := Window_Convert.To_Pointer (fl_widget_get_user_data (Ptr)); -- end if; -- if Current_Dispatch = null then -- Ret_Val := Default_Dispatch (Event_Kind'Val (Num), Actual_Window); -- else -- Ret_Val := Current_Dispatch (Event_Kind'Val (Num), Actual_Window); -- end if; -- return Event_Outcome'Pos (Ret_Val); -- end Dispatch_Hook; procedure Add_Handler (Func : in Event_Handler) is begin Handlers.Append (Func); end Add_Handler; procedure Remove_Handler (Func : in Event_Handler) is begin for I in reverse Handlers.First_Index .. Handlers.Last_Index loop if Handlers (I) = Func then Handlers.Delete (I); return; end if; end loop; end Remove_Handler; -- function Get_Dispatch -- return Event_Dispatch is -- begin -- if Current_Dispatch = null then -- return Default_Dispatch'Access; -- else -- return Current_Dispatch; -- end if; -- end Get_Dispatch; -- procedure Set_Dispatch -- (Func : in Event_Dispatch) is -- begin -- Current_Dispatch := Func; -- end Set_Dispatch; -- function Default_Dispatch -- (Event : in Event_Kind; -- Win : access FLTK.Widgets.Groups.Windows.Window'Class) -- return Event_Outcome is -- begin -- if Win = null then -- return Event_Outcome'Val (fl_event_handle -- (Event_Kind'Pos (Event), System.Null_Address)); -- else -- return Event_Outcome'Val (fl_event_handle -- (Event_Kind'Pos (Event), -- Wrapper (Win.all).Void_Ptr)); -- end if; -- end Default_Dispatch; function Get_Grab return access FLTK.Widgets.Groups.Windows.Window'Class is begin return Window_Convert.To_Pointer (fl_widget_get_user_data (fl_event_get_grab)); end Get_Grab; procedure Set_Grab (To : in FLTK.Widgets.Groups.Windows.Window'Class) is begin fl_event_set_grab (Wrapper (To).Void_Ptr); end Set_Grab; procedure Release_Grab is begin fl_event_set_grab (System.Null_Address); end Release_Grab; function Get_Pushed return access FLTK.Widgets.Widget'Class is begin return Widget_Convert.To_Pointer (fl_widget_get_user_data (fl_event_get_pushed)); end Get_Pushed; procedure Set_Pushed (To : in FLTK.Widgets.Widget'Class) is begin fl_event_set_pushed (Wrapper (To).Void_Ptr); end Set_Pushed; function Get_Below_Mouse return access FLTK.Widgets.Widget'Class is begin return Widget_Convert.To_Pointer (fl_widget_get_user_data (fl_event_get_belowmouse)); end Get_Below_Mouse; procedure Set_Below_Mouse (To : in FLTK.Widgets.Widget'Class) is begin fl_event_set_belowmouse (Wrapper (To).Void_Ptr); end Set_Below_Mouse; function Get_Focus return access FLTK.Widgets.Widget'Class is begin return Widget_Convert.To_Pointer (fl_widget_get_user_data (fl_event_get_focus)); end Get_Focus; procedure Set_Focus (To : in FLTK.Widgets.Widget'Class) is begin fl_event_set_focus (Wrapper (To).Void_Ptr); end Set_Focus; function Compose (Del : out Natural) return Boolean is begin return fl_event_compose (Interfaces.C.int (Del)) /= 0; end Compose; procedure Compose_Reset is begin fl_event_compose_reset; end Compose_Reset; function Text return String is Str : Interfaces.C.Strings.chars_ptr := fl_event_text; begin if Str = Interfaces.C.Strings.Null_Ptr then return ""; else return Interfaces.C.Strings.Value (Str, Interfaces.C.size_t (fl_event_length)); end if; end Text; function Text_Length return Natural is begin return Natural (fl_event_length); end Text_Length; function Last return Event_Kind is begin return Event_Kind'Val (fl_event_get); end Last; function Last_Modifier return Modifier is begin return To_Ada (fl_event_state); end Last_Modifier; function Last_Modifier (Had : in Modifier) return Boolean is begin return fl_event_check_state (To_C (Had)) /= 0; end Last_Modifier; function Mouse_X return Integer is begin return Integer (fl_event_x); end Mouse_X; function Mouse_X_Root return Integer is begin return Integer (fl_event_x_root); end Mouse_X_Root; function Mouse_Y return Integer is begin return Integer (fl_event_y); end Mouse_Y; function Mouse_Y_Root return Integer is begin return Integer (fl_event_y_root); end Mouse_Y_Root; function Mouse_DX return Integer is begin return Integer (fl_event_dx); end Mouse_DX; function Mouse_DY return Integer is begin return Integer (fl_event_dy); end Mouse_DY; procedure Get_Mouse (X, Y : out Integer) is begin fl_event_get_mouse (Interfaces.C.int (X), Interfaces.C.int (Y)); end Get_Mouse; function Is_Click return Boolean is begin return fl_event_is_click /= 0; end Is_Click; function Is_Multi_Click return Boolean is begin return fl_event_is_clicks /= 0; end Is_Multi_Click; procedure Set_Clicks (To : in Natural) is begin fl_event_set_clicks (Interfaces.C.int (To)); end Set_Clicks; function Last_Button return Mouse_Button is begin return Mouse_Button'Val (fl_event_button); end Last_Button; function Mouse_Left return Boolean is begin return fl_event_button1 /= 0; end Mouse_Left; function Mouse_Middle return Boolean is begin return fl_event_button2 /= 0; end Mouse_Middle; function Mouse_Right return Boolean is begin return fl_event_button3 /= 0; end Mouse_Right; function Is_Inside (X, Y, W, H : in Integer) return Boolean is begin return fl_event_inside (Interfaces.C.int (X), Interfaces.C.int (Y), Interfaces.C.int (W), Interfaces.C.int (H)) /= 0; end Is_Inside; function Last_Key return Keypress is begin return To_Ada (fl_event_key); end Last_Key; function Original_Last_Key return Keypress is begin return To_Ada (fl_event_original_key); end Original_Last_Key; function Pressed_During (Key : in Keypress) return Boolean is begin return fl_event_key_during (To_C (Key)) /= 0; end Pressed_During; function Key_Now (Key : in Keypress) return Boolean is begin return fl_event_get_key (To_C (Key)) /= 0; end Key_Now; function Key_Ctrl return Boolean is begin return fl_event_ctrl /= 0; end Key_Ctrl; function Key_Alt return Boolean is begin return fl_event_alt /= 0; end Key_Alt; function Key_Command return Boolean is begin return fl_event_command /= 0; end Key_Command; function Key_Shift return Boolean is begin return fl_event_shift /= 0; end Key_Shift; begin fl_event_add_handler (Event_Handler_Hook'Address); -- fl_event_set_event_dispatch (Dispatch_Hook'Address); end FLTK.Event;
-- ___ _ ___ _ _ -- -- / __| |/ (_) | | Common SKilL implementation -- -- \__ \ ' <| | | |__ skills vector container implementation -- -- |___/_|\_\_|_|____| by: Dennis Przytarski, Timm Felden -- -- -- pragma Ada_2012; with Ada.Finalization; with Ada.Unchecked_Conversion; with Skill.Types; with Skill.Containers.Vectors; -- arrays used by skill; those are basically ada vectors with template aware boxing generic type T is private; package Skill.Containers.Arrays is pragma Warnings(Off); use Skill.Types; function Cast is new Ada.Unchecked_Conversion (Box, T); function Cast is new Ada.Unchecked_Conversion (T, Box); package Vec is new Skill.Containers.Vectors (Natural, T); type Array_T is new Boxed_Array_T with record This : Vec.Vector; end record; type Ref is access Array_T; type Iterator_T is new Array_Iterator_T with record This : Vec.Vector; Cursor : Natural; end record; function Has_Next (This : access Iterator_T) return Boolean is (This.This.Check_Index (This.Cursor)); function Next (This : access Iterator_T) return Skill.Types.Box; procedure Free (This : access Array_T); procedure Free (This : access Iterator_T); procedure Append (This : access Array_T; V : Box); procedure Add (This : access Array_T; V : Box); function Get (This : access Array_T; I : Natural) return Box is (Cast (This.This.Element (I))); -- append all elements of that to this procedure Append_All(This : access Array_T; That : Ref); -- prepend all elements of that to this procedure Prepend_All(This : access Array_T; That : Ref); procedure Update (This : access Array_T; I : Natural; V : Box); procedure Ensure_Size (This : access Array_T; I : Natural); function Length (This : access Array_T) return Natural is (Vec.Length (This.This)); overriding function Iterator (This : access Array_T) return Array_Iterator is (new Iterator_T'(This => This.This, Cursor => 0)); -- create a new container function Make return Ref; -- turn a box into a container of right type function Unboxed is new Ada.Unchecked_Conversion (Box, Ref); end Skill.Containers.Arrays;
-- -- Copyright (C) 2015-2016 secunet Security Networks AG -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- package HW.Time with Abstract_State => (State with External => Async_Writers) is type T is private; function Now return T with Volatile_Function, Global => (Input => State); function US_From_Now (US : Natural) return T with Volatile_Function, Global => (Input => State); function MS_From_Now (MS : Natural) return T with Volatile_Function, Global => (Input => State); function Now_US return Int64 with Volatile_Function, Global => (Input => State); ---------------------------------------------------------------------------- pragma Warnings (GNATprove, Off, "subprogram ""*Delay*"" has no effect", Reason => "No effect on dataflow but time always passes."); -- Delay execution until Deadline has been reached. procedure Delay_Until (Deadline : T) with Global => (Input => State); procedure U_Delay (US : Natural) with Global => (Input => State); procedure M_Delay (MS : Natural) with Global => (Input => State); pragma Warnings (GNATprove, On, "subprogram ""*Delay*"" has no effect"); ---------------------------------------------------------------------------- function Timed_Out (Deadline : T) return Boolean with Volatile_Function, Global => (Input => State); private type T is new Word64; end HW.Time; -- vim: set ts=8 sts=3 sw=3 et:
with Ada.Text_IO; use Ada.Text_IO; with Libadalang.Analysis; use Libadalang.Analysis; with Libadalang.Common; use Libadalang.Common; with Rejuvenation; use Rejuvenation; with Rejuvenation.Match_Patterns; use Rejuvenation.Match_Patterns; with Rejuvenation.Simple_Factory; use Rejuvenation.Simple_Factory; with Rejuvenation.Utils; use Rejuvenation.Utils; package body Examples.Match_Patterns is -- Without placeholders -------- procedure Demo_Without_Placeholders_Success; procedure Demo_Without_Placeholders_Failure; -- With single placeholders -------- procedure Demo_With_Single_Placeholders_Success_Single_Occurrence; procedure Demo_With_Single_Placeholders_Success_Consistent_Occurrences; procedure Demo_With_Single_Placeholders_Failure_Inconsistent_Occurrences; procedure Demo_With_Single_Placeholders_Success_Consistent_Complex_Occurrences; -- With multiple placeholders -------- procedure Demo_With_Multiple_Placeholders_Success_Single_Occurrence; procedure Demo_With_Multiple_Placeholders_Success_Consistent_Occurrences; procedure Demo_With_Multiple_Placeholders_Failure_Inconsistent_Occurrences; -- With single and multiple placeholders -------- procedure Demo_With_Single_And_Multiple_Placeholders_Success; procedure Demo_With_Single_And_Multiple_Placeholders_Failure; procedure Demo is begin Put_Line ("=== Examples of Match_Pattern ======="); New_Line; Put_Line ("--- Examples without placeholders (success) -------"); New_Line; Demo_Without_Placeholders_Success; New_Line; Put_Line ("--- Examples without placeholders (failure) -------"); New_Line; Demo_Without_Placeholders_Failure; New_Line; Put_Line ("--- Examples with single placeholders " & "(success: single occurence) -------"); New_Line; Demo_With_Single_Placeholders_Success_Single_Occurrence; New_Line; Put_Line ("--- Examples with single placeholders " & "(success: consistent occurences) -------"); New_Line; Demo_With_Single_Placeholders_Success_Consistent_Occurrences; New_Line; Put_Line ("--- Examples with single placeholders " & "(failure: inconsistent occurences) -------"); New_Line; Demo_With_Single_Placeholders_Failure_Inconsistent_Occurrences; New_Line; Put_Line ("--- Examples with single placeholders " & "(success: consistent complex occurences) -------"); New_Line; Demo_With_Single_Placeholders_Success_Consistent_Complex_Occurrences; New_Line; Put_Line ("--- Examples with multiple placeholders " & "(success: single occurence) -------"); New_Line; Demo_With_Multiple_Placeholders_Success_Single_Occurrence; New_Line; Put_Line ("--- Examples with multiple placeholders " & "(success: consistent occurences) -------"); New_Line; Demo_With_Multiple_Placeholders_Success_Consistent_Occurrences; New_Line; Put_Line ("--- Examples with multiple placeholders " & "(failure: inconsistent occurences) -------"); New_Line; Demo_With_Multiple_Placeholders_Failure_Inconsistent_Occurrences; New_Line; Put_Line ("--- Examples with single and multiple placeholders " & "(success) -------"); New_Line; Demo_With_Single_And_Multiple_Placeholders_Success; New_Line; Put_Line ("--- Examples with single and multiple placeholders " & "(failure) -------"); New_Line; Demo_With_Single_And_Multiple_Placeholders_Failure; New_Line; end Demo; -- Without placeholders -------- procedure Demo_Without_Placeholders_Success is MP : Match_Pattern; Result : Boolean; begin Result := MP.Match_Full (Pattern => Analyze_Fragment ("x := 42;", Stmt_Rule).Root, Instance => Analyze_Fragment ("x := 42;", Stmt_Rule).Root); Put_Line (Result'Image); end Demo_Without_Placeholders_Success; procedure Demo_Without_Placeholders_Failure is MP : Match_Pattern; Result : Boolean; begin Rejuvenation.Match_Patterns.DIAGNOSE := True; -- To get diagnosis information Result := MP.Match_Full (Pattern => Analyze_Fragment ("x := 21;", Stmt_Rule).Root, Instance => Analyze_Fragment ("x := 42;", Stmt_Rule).Root); Rejuvenation.Match_Patterns.DIAGNOSE := False; Put_Line (Result'Image); end Demo_Without_Placeholders_Failure; -- With single placeholders -------- procedure Demo_With_Single_Placeholders_Success_Single_Occurrence is -- To be able to access placeholder nodes, do not inline Unit. Unit : constant Analysis_Unit := Analyze_Fragment ("x := 42;", Stmt_Rule); MP : Match_Pattern; Result : Boolean; begin Result := MP.Match_Full (Pattern => Analyze_Fragment ("x := $S_value;", Stmt_Rule).Root, Instance => Unit.Root); Put_Line (Result'Image & " " & MP.Has_Single ("$S_value")'Image & " " & MP.Get_Single_As_Node ("$S_value").Image & " " & MP.Get_Single_As_Raw_Signature ("$S_value")); end Demo_With_Single_Placeholders_Success_Single_Occurrence; procedure Demo_With_Single_Placeholders_Success_Consistent_Occurrences is -- To be able to access placeholder nodes, do not inline Unit. Unit : constant Analysis_Unit := Analyze_Fragment ("x := 42 + 42;", Stmt_Rule); MP : Match_Pattern; Result : Boolean; begin Result := MP.Match_Full (Pattern => Analyze_Fragment ("x := $S_value + $S_value;", Stmt_Rule).Root, Instance => Unit.Root); Put_Line (Result'Image & " " & MP.Has_Single ("$S_value")'Image & " " & MP.Get_Single_As_Node ("$S_value").Image & " " & MP.Get_Single_As_Raw_Signature ("$S_value")); end Demo_With_Single_Placeholders_Success_Consistent_Occurrences; procedure Demo_With_Single_Placeholders_Failure_Inconsistent_Occurrences is -- To be able to access placeholder nodes, do not inline Unit. Unit : constant Analysis_Unit := Analyze_Fragment ("x := 42 + 21;", Stmt_Rule); MP : Match_Pattern; Result : Boolean; begin Rejuvenation.Match_Patterns.DIAGNOSE := True; -- To get diagnosis information Result := MP.Match_Full (Pattern => Analyze_Fragment ("x := $S_value + $S_value;", Stmt_Rule).Root, Instance => Unit.Root); Rejuvenation.Match_Patterns.DIAGNOSE := False; Put_Line (Result'Image & " " & MP.Has_Single ("$S_value")'Image); end Demo_With_Single_Placeholders_Failure_Inconsistent_Occurrences; procedure Demo_With_Single_Placeholders_Success_Consistent_Complex_Occurrences is -- To be able to access placeholder nodes, do not inline Unit. Unit : constant Analysis_Unit := Analyze_Fragment ("x := (f(a)+12) + (f(a)+12);", Stmt_Rule); MP : Match_Pattern; Result : Boolean; begin Result := MP.Match_Full (Pattern => Analyze_Fragment ("x := $S_value + $S_value;", Stmt_Rule).Root, Instance => Unit.Root); Put_Line (Result'Image & " " & MP.Has_Single ("$S_value")'Image & " " & MP.Get_Single_As_Node ("$S_value").Image & " " & MP.Get_Single_As_Raw_Signature ("$S_value")); end Demo_With_Single_Placeholders_Success_Consistent_Complex_Occurrences; -- With multiple placeholders -------- procedure Demo_With_Multiple_Placeholders_Success_Single_Occurrence is -- To be able to access placeholder nodes, do not inline Unit. Unit : constant Analysis_Unit := Analyze_Fragment ("x := 42;", Stmt_Rule); MP : Match_Pattern; Result : Boolean; begin Result := MP.Match_Full (Pattern => Analyze_Fragment ("x := $M_value;", Stmt_Rule).Root, Instance => Unit.Root); Put_Line (Result'Image & " " & MP.Has_Multiple ("$M_value")'Image & " " & MP.Get_Multiple_As_Nodes ("$M_value").Length'Image & " " & MP.Get_Multiple_As_Nodes ("$M_value") (1).Image); end Demo_With_Multiple_Placeholders_Success_Single_Occurrence; procedure Demo_With_Multiple_Placeholders_Success_Consistent_Occurrences is -- To be able to access placeholder nodes, do not inline Unit. Unit : constant Analysis_Unit := Analyze_Fragment ("x := 42 + 42;", Stmt_Rule); MP : Match_Pattern; Result : Boolean; begin Result := MP.Match_Full (Pattern => Analyze_Fragment ("x := $M_value + $M_value;", Stmt_Rule).Root, Instance => Unit.Root); Put_Line (Result'Image & " " & MP.Has_Multiple ("$M_value")'Image & " " & MP.Get_Multiple_As_Nodes ("$M_value").Length'Image & " " & MP.Get_Multiple_As_Nodes ("$M_value") (1).Image); end Demo_With_Multiple_Placeholders_Success_Consistent_Occurrences; procedure Demo_With_Multiple_Placeholders_Failure_Inconsistent_Occurrences is -- To be able to access placeholder nodes, do not inline Unit. Unit : constant Analysis_Unit := Analyze_Fragment ("x := 42 + 21;", Stmt_Rule); MP : Match_Pattern; Result : Boolean; begin Rejuvenation.Match_Patterns.DIAGNOSE := True; -- To get diagnosis information Result := MP.Match_Full (Pattern => Analyze_Fragment ("x := $M_value + $M_value;", Stmt_Rule).Root, Instance => Unit.Root); Rejuvenation.Match_Patterns.DIAGNOSE := False; Put_Line (Result'Image & " " & MP.Has_Multiple ("$M_value")'Image); end Demo_With_Multiple_Placeholders_Failure_Inconsistent_Occurrences; -- With single and multiple placeholders -------- procedure Demo_With_Single_And_Multiple_Placeholders_Success is -- To be able to access placeholder nodes, do not inline Unit. Unit : constant Analysis_Unit := Analyze_Fragment ("x := 42; x := 21; y := 22; x := 42;", Stmts_Rule); MP : Match_Pattern; Result : Boolean; begin Result := MP.Match_Full (Pattern => Analyze_Fragment ("x := $S_value; $M_stats; x := $S_value;", Stmts_Rule) .Root, Instance => Unit.Root); Put_Line (Result'Image & " " & MP.Has_Single ("$S_value")'Image & " " & MP.Get_Single_As_Node ("$S_value").Image & " " & MP.Get_Single_As_Raw_Signature ("$S_value") & " " & MP.Has_Multiple ("$M_stats")'Image & " " & MP.Get_Multiple_As_Nodes ("$M_stats").Length'Image & " " & MP.Get_Multiple_As_Nodes ("$M_stats") (1).Image & " " & Rejuvenation.Utils.Raw_Signature (MP.Get_Multiple_As_Nodes ("$M_stats") (1)) & " " & MP.Get_Multiple_As_Nodes ("$M_stats") (2).Image & " " & Rejuvenation.Utils.Raw_Signature (MP.Get_Multiple_As_Nodes ("$M_stats") (2))); end Demo_With_Single_And_Multiple_Placeholders_Success; procedure Demo_With_Single_And_Multiple_Placeholders_Failure is -- To be able to access placeholder nodes, do not inline Unit. Unit : constant Analysis_Unit := Analyze_Fragment ("x := 42; y := 21; y := 21; x := 43;", Stmts_Rule); MP : Match_Pattern; Result : Boolean; begin Rejuvenation.Match_Patterns.DIAGNOSE := True; -- To get diagnosis information Result := MP.Match_Full (Pattern => Analyze_Fragment ("x := $S_value; $M_stats; x := $S_value;", Stmts_Rule) .Root, Instance => Unit.Root); Rejuvenation.Match_Patterns.DIAGNOSE := False; Put_Line (Result'Image & " " & MP.Has_Single ("$S_value")'Image & " " & MP.Has_Multiple ("$M_stats")'Image); end Demo_With_Single_And_Multiple_Placeholders_Failure; end Examples.Match_Patterns;
package Constant2_Pkg2 is function F1 return Boolean; function F2 return Boolean; end Constant2_Pkg2;
----------------------------------------------------------------------- -- awa-services -- Services -- Copyright (C) 2011, 2012, 2013, 2014, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Attributes; with Security.Contexts; package body AWA.Services.Contexts is use type ADO.Sessions.Connection_Status; use type AWA.Users.Principals.Principal_Access; package Task_Context is new Ada.Task_Attributes (Service_Context_Access, null); -- ------------------------------ -- Get the application associated with the current service operation. -- ------------------------------ function Get_Application (Ctx : in Service_Context) return AWA.Applications.Application_Access is begin return Ctx.Application; end Get_Application; -- ------------------------------ -- Get the current database connection for reading. -- ------------------------------ function Get_Session (Ctx : in Service_Context_Access) return ADO.Sessions.Session is begin -- If a master database session was created, use it. if Ctx.Master.Get_Status = ADO.Sessions.OPEN then return ADO.Sessions.Session (Ctx.Master); elsif Ctx.Slave.Get_Status /= ADO.Sessions.OPEN then Ctx.Slave := Ctx.Application.Get_Session; end if; return Ctx.Slave; end Get_Session; -- ------------------------------ -- Get the current database connection for reading and writing. -- ------------------------------ function Get_Master_Session (Ctx : in Service_Context_Access) return ADO.Sessions.Master_Session is begin if Ctx.Master.Get_Status /= ADO.Sessions.OPEN then Ctx.Master := Ctx.Application.Get_Master_Session; end if; return Ctx.Master; end Get_Master_Session; -- ------------------------------ -- Get the current user invoking the service operation. -- Returns a null user if there is none. -- ------------------------------ function Get_User (Ctx : in Service_Context) return AWA.Users.Models.User_Ref is begin if Ctx.Principal = null then return AWA.Users.Models.Null_User; else return Ctx.Principal.Get_User; end if; end Get_User; -- ------------------------------ -- Get the current user identifier invoking the service operation. -- Returns NO_IDENTIFIER if there is none. -- ------------------------------ function Get_User_Identifier (Ctx : in Service_Context) return ADO.Identifier is begin if Ctx.Principal = null then return ADO.NO_IDENTIFIER; else return Ctx.Principal.Get_User_Identifier; end if; end Get_User_Identifier; -- ------------------------------ -- Get the current user session from the user invoking the service operation. -- Returns a null session if there is none. -- ------------------------------ function Get_User_Session (Ctx : in Service_Context) return AWA.Users.Models.Session_Ref is begin if Ctx.Principal = null then return AWA.Users.Models.Null_Session; else return Ctx.Principal.Get_Session; end if; end Get_User_Session; -- ------------------------------ -- Starts a transaction. -- ------------------------------ procedure Start (Ctx : in out Service_Context) is begin if Ctx.Transaction = 0 and then not Ctx.Active_Transaction then Ctx.Master.Begin_Transaction; Ctx.Active_Transaction := True; end if; Ctx.Transaction := Ctx.Transaction + 1; end Start; -- ------------------------------ -- Commits the current transaction. The database transaction is really committed by the -- last <b>Commit</b> called. -- ------------------------------ procedure Commit (Ctx : in out Service_Context) is begin Ctx.Transaction := Ctx.Transaction - 1; if Ctx.Transaction = 0 and then Ctx.Active_Transaction then Ctx.Master.Commit; Ctx.Active_Transaction := False; end if; end Commit; -- ------------------------------ -- Rollback the current transaction. The database transaction is rollback at the first -- call to <b>Rollback</b>. -- ------------------------------ procedure Rollback (Ctx : in out Service_Context) is begin null; end Rollback; -- ------------------------------ -- Get the attribute registered under the given name in the HTTP session. -- ------------------------------ function Get_Session_Attribute (Ctx : in Service_Context; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (Ctx, Name); begin return Util.Beans.Objects.Null_Object; end Get_Session_Attribute; -- ------------------------------ -- Set the attribute registered under the given name in the HTTP session. -- ------------------------------ procedure Set_Session_Attribute (Ctx : in out Service_Context; Name : in String; Value : in Util.Beans.Objects.Object) is begin null; end Set_Session_Attribute; -- ------------------------------ -- Set the current application and user context. -- ------------------------------ procedure Set_Context (Ctx : in out Service_Context; Application : in AWA.Applications.Application_Access; Principal : in AWA.Users.Principals.Principal_Access) is begin Ctx.Application := Application; Ctx.Principal := Principal; end Set_Context; -- ------------------------------ -- Initializes the service context. -- ------------------------------ overriding procedure Initialize (Ctx : in out Service_Context) is use type AWA.Applications.Application_Access; begin Ctx.Previous := Task_Context.Value; Task_Context.Set_Value (Ctx'Unchecked_Access); if Ctx.Previous /= null and then Ctx.Application = null then Ctx.Application := Ctx.Previous.Application; end if; end Initialize; -- ------------------------------ -- Finalize the service context, rollback non-committed transaction, releases any object. -- ------------------------------ overriding procedure Finalize (Ctx : in out Service_Context) is begin -- When the service context is released, we must not have any active transaction. -- This means we are leaving the service in an abnormal way such as when an -- exception is raised. If this is the case, rollback the transaction. if Ctx.Active_Transaction then Ctx.Master.Rollback; end if; Task_Context.Set_Value (Ctx.Previous); end Finalize; -- ------------------------------ -- Get the current service context. -- Returns null if the current thread is not associated with any service context. -- ------------------------------ function Current return Service_Context_Access is begin return Task_Context.Value; end Current; -- ------------------------------ -- Run the process procedure on behalf of the specific user and session. -- This operation changes temporarily the identity of the current user principal and -- executes the <tt>Process</tt> procedure. -- ------------------------------ procedure Run_As (User : in AWA.Users.Models.User_Ref; Session : in AWA.Users.Models.Session_Ref) is Ctx : Service_Context; Sec : Security.Contexts.Security_Context; Principal : aliased AWA.Users.Principals.Principal := AWA.Users.Principals.Create (User, Session); begin Ctx.Principal := Principal'Unchecked_Access; Sec.Set_Context (Ctx.Application.Get_Security_Manager, Principal'Unchecked_Access); Process; end Run_As; end AWA.Services.Contexts;
--------------------------------------------------------------------------- -- package Hypot -- Copyright (C) 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 Hypot provides routines for calculating -- -- Hypot = Sqrt (Max**2 + Min**2) -- Min_Arg_Over_Hypot = Min / Sqrt (Max**2 + Min**2) -- Max_Arg_Over_Hypot_Minus_1 = Max / Sqrt (Max**2 + Min**2) - One -- -- The idea, mostly for fun, was to improve numerical accuracy on -- Intel SSE hardware. The routines are slightly more accurate than -- the simplest methods, and quite a bit slower. -- Typically, they add an additional 1 or 2 calls to "/". generic type Real is digits <>; package Hypot is -- If Abs b > Abs a then -- -- Max = Abs b, Min = Abs a -- -- Hypot = Sqrt (Max**2 + Min**2) -- Min_Arg_Over_Hypot = Min / Sqrt (Max**2 + Min**2) -- Max_Arg_Over_Hypot_Minus_1 = Max / Sqrt (Max**2 + Min**2) - One procedure Get_Hypotenuse (a, b : in Real; Hypot : out Real; Min_Arg_Over_Hypot : out Real; Max_Arg_Over_Hypot_Minus_1 : out Real); function Hypotenuse (a, b : in Real) return Real; end Hypot;
pragma Ada_2012; with Ada.Streams; use Ada.Streams; with Interfaces; use Interfaces; with AUnit.Assertions; use AUnit.Assertions; with AUnit.Test_Caller; with Endianness; use Endianness; package body Tests is package Caller is new AUnit.Test_Caller (Fixture); Test_Suite : aliased AUnit.Test_Suites.Test_Suite; function Suite return AUnit.Test_Suites.Access_Test_Suite is Name : constant String := "[endianness] "; begin Test_Suite.Add_Test (Caller.Create (Name & "Swap_Endian()", Swap_Endian_Test'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Native_To_Big_Endian() and Big_Endian_To_Native()", Native_To_Big_Endian_And_Back_Test'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Native_To_Little_Endian() and Little_Endian_To_Native()", Native_To_Little_Endian_And_Back_Test'Access)); return Test_Suite'Access; end Suite; procedure Swap_Endian_Test (Object : in out Fixture) is begin declare function Swap is new Swap_Endian (Integer); begin Assert (Swap (42) = 704_643_072, "Integer swap"); Assert (Swap (Swap (42)) = 42, "Integer swap reflexive"); end; declare function Swap is new Swap_Endian (Integer_8); begin Assert (Swap (Integer_8 (10)) = 10, "Integer_8 swap"); end; declare function Swap is new Swap_Endian (Unsigned_16); begin Assert (Swap (Unsigned_16 (10)) = 2_560, "Unsigned_16 swap"); end; declare function Swap is new Swap_Endian (Long_Long_Integer); begin Assert (Swap (Long_Long_Integer (10)) = 720_575_940_379_279_360, "Long_Long_Integer swap"); end; declare function Swap is new Swap_Endian (Unsigned_64); begin Assert (Swap (Unsigned_64 (10)) = 720_575_940_379_279_360, "Unsigned_64 swap"); end; end Swap_Endian_Test; procedure Native_To_Big_Endian_And_Back_Test (Object : in out Fixture) is begin declare function To is new Native_To_Big_Endian (Integer); function From is new Big_Endian_To_Native (Integer); X : constant Integer := 12_345; A : constant Stream_Element_Array (0 .. 3) := To (X); begin Assert (From (A) = X, "Integer"); end; declare function To is new Native_To_Big_Endian (Unsigned_16); function From is new Big_Endian_To_Native (Unsigned_16); X : constant Unsigned_16 := 12_345; A : constant Stream_Element_Array (0 .. 1) := To (X); begin Assert (From (A) = X, "Unsigned_16"); end; declare function To is new Native_To_Big_Endian (Integer_8); function From is new Big_Endian_To_Native (Integer_8); X : constant Integer_8 := 123; A : constant Stream_Element_Array (0 .. 0) := To (X); begin Assert (From (A) = X, "Integer_8"); end; declare function To is new Native_To_Big_Endian (Long_Long_Integer); function From is new Big_Endian_To_Native (Long_Long_Integer); X : constant Long_Long_Integer := 1_234_567_890; A : constant Stream_Element_Array (0 .. 7) := To (X); begin Assert (From (A) = X, "Long_Long_Integer"); end; end Native_To_Big_Endian_And_Back_Test; procedure Native_To_Little_Endian_And_Back_Test (Object : in out Fixture) is begin declare function To is new Native_To_Little_Endian (Integer); function From is new Little_Endian_To_Native (Integer); X : constant Integer := 12_345; A : constant Stream_Element_Array (0 .. 3) := To (X); begin Assert (From (A) = X, "Integer"); end; declare function To is new Native_To_Little_Endian (Unsigned_16); function From is new Little_Endian_To_Native (Unsigned_16); X : constant Unsigned_16 := 12_345; A : constant Stream_Element_Array (0 .. 1) := To (X); begin Assert (From (A) = X, "Unsigned_16"); end; declare function To is new Native_To_Little_Endian (Integer_8); function From is new Little_Endian_To_Native (Integer_8); X : constant Integer_8 := 123; A : constant Stream_Element_Array (0 .. 0) := To (X); begin Assert (From (A) = X, "Integer_8"); end; declare function To is new Native_To_Little_Endian (Long_Long_Integer); function From is new Little_Endian_To_Native (Long_Long_Integer); X : constant Long_Long_Integer := 1_234_567_890; A : constant Stream_Element_Array (0 .. 7) := To (X); begin Assert (From (A) = X, "Long_Long_Integer"); end; end Native_To_Little_Endian_And_Back_Test; end Tests;
-- Used for all testcases for SQLite driver with AdaBase.Driver.Base.SQLite; with AdaBase.Statement.Base.SQLite; package Connect is -- All specific drivers renamed to "Database_Driver" subtype Database_Driver is AdaBase.Driver.Base.SQLite.SQLite_Driver; subtype Stmt_Type is AdaBase.Statement.Base.SQLite.SQLite_statement; subtype Stmt_Type_access is AdaBase.Statement.Base.SQLite.SQLite_statement_access; DR : Database_Driver; procedure connect_database; end Connect;
-- Copyright (c) 1990 Regents of the University of California. -- All rights reserved. -- -- The primary authors of ayacc were David Taback and Deepak Tolani. -- Enhancements were made by Ronald J. Schmalz. -- -- Send requests for ayacc information to ayacc-info@ics.uci.edu -- Send bug reports for ayacc to ayacc-bugs@ics.uci.edu -- -- 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. -- Module : lr0_machine.ada -- Component of : ayacc -- Version : 1.2 -- Date : 11/21/86 12:30:58 -- SCCS File : disk21~/rschm/hasee/sccs/ayacc/sccs/sxlr0_machine.ada -- $Header: /dc/uc/self/tmp/gnat_ayacc_new/lr0bad/RCS/lr0_machine.ads,v 1.1 1995/02/16 17:28:09 self Exp self $ -- $Log: lr0_machine.ads,v $ -- Revision 0.1 86/04/01 15:06:19 ada -- This version fixes some minor bugs with empty grammars -- and $$ expansion. It also uses vads5.1b enhancements -- such as pragma inline. -- -- -- Revision 0.0 86/02/19 18:37:14 ada -- -- These files comprise the initial version of Ayacc -- designed and implemented by David Taback and Deepak Tolani. -- Ayacc has been compiled and tested under the Verdix Ada compiler -- version 4.06 on a vax 11/750 running Unix 4.2BSD. -- with Rule_Table, Symbol_Table, Set_Pack; use Rule_Table, Symbol_Table; package LR0_Machine is type Parse_State is range -1..5_000; Null_Parse_State : constant Parse_State := -1; type Item is record Rule_ID : Rule; Dot_Position : Natural; end record; type Transition is record Symbol : Grammar_Symbol; State_ID : Parse_State; end record; function "<" (Item_1, Item_2 : Item) return Boolean; function "<" (Trans_1, Trans_2 : Transition) return Boolean; package Parse_State_Set_Pack is new Set_Pack(Parse_State, "<"); package Item_Set_Pack is new Set_Pack(Item, "<"); package Transition_Set_Pack is new Set_Pack(Transition, "<"); package Grammar_Symbol_Set_Pack is new Set_Pack(Grammar_Symbol, "<"); subtype Parse_State_Set is Parse_State_Set_Pack.Set; subtype Item_Set is Item_Set_Pack.Set; subtype Transition_Set is Transition_Set_Pack.Set; subtype Grammar_Symbol_Set is Grammar_Symbol_Set_Pack.Set; subtype Parse_State_Iterator is Parse_State_Set_Pack.Set_Iterator; subtype Item_Iterator is Item_Set_Pack.Set_Iterator; subtype Transition_Iterator is Transition_Set_Pack.Set_Iterator; subtype Grammar_Symbol_Iterator is Grammar_Symbol_Set_Pack.Set_Iterator; procedure LR0_Initialize; -- must be called first. function First_Parse_State return Parse_State; function Last_Parse_State return Parse_State; function Get_Goto (State_ID : Parse_State; Sym : Grammar_Symbol) return Parse_State; -- Returns the predecessor states of STATE_ID and the item I. -- Must be called with PRED_SET empty! procedure Get_Pred_Set (State_ID : in Parse_State; I : in Item; Pred_Set : in out Parse_State_Set); type Transition_Type is (Terminals, Nonterminals, Grammar_Symbols); procedure Get_Transitions (State_ID : in Parse_State; Kind : in Transition_Type; Set_1 : in out Transition_Set); procedure Get_Transition_Symbols (State_ID : in Parse_State; Kind : in Transition_Type; Set_1 : in out Grammar_Symbol_Set); procedure Get_Kernel (State_ID : in Parse_State; Set_1 : in out Item_Set); procedure Closure (Set_1 : in out Item_Set); -- -- The following routines allow the user to iterate over the -- items in the kernel of a particular state. -- type Kernel_Iterator is limited private; procedure Initialize (Iterator : in out Kernel_Iterator; State_ID : in Parse_State); function More(Iterator : Kernel_Iterator) return Boolean; procedure Next(Iterator : in out Kernel_Iterator; I : out Item); -- -- The following routines allow the user to iterate over the -- nonterminal transitions of a particular state -- type Nt_Transition_Iterator is limited private; procedure Initialize (Iterator : in out Nt_Transition_Iterator; State_ID : in Parse_State); function More (Iterator : Nt_Transition_Iterator) return Boolean; procedure Next (Iterator : in out Nt_Transition_Iterator; Trans : out Transition); -- The following routines allow iteration over the Terminal transitions -- of a particular state. type T_Transition_Iterator is limited private; -- For Terminals procedure Initialize (Iterator : in out T_Transition_Iterator; State_ID : in Parse_State); function More (Iterator : T_Transition_Iterator) return Boolean; procedure Next (Iterator : in out T_Transition_Iterator; Trans : out Transition); To_Many_States : exception; No_More_Iterations : exception; State_Out_of_Bounds : exception; --RJS pragma inline(more); --DEC Ada Bug: , next); private type Item_Array_Index is range 0..5_000; -- An arbitrarily big number ----- type Item_Array; type Item_Array is array (Item_Array_Index range <>) of Item; type Item_Array_Pointer is access Item_Array; type Kernel_Iterator is record Kernel : Item_Array_Pointer; Curser : Item_Array_Index; end record; ----- type Transition_Array; -- The type declarations for storing the nonterminal transitions of -- the DFA in the states. type Transition_Array is array(Integer range <>) of Transition; type Transition_Array_Pointer is access Transition_Array; type Nt_Transition_Iterator is record Nonterm_Trans : Transition_Array_Pointer; Curser : Integer; -- Use a derived type instead ??? end record; type T_Transition_Iterator is record Term_Trans : Transition_Array_Pointer; Curser : Integer; end record; end LR0_Machine;
with Ada.Text_IO; use Ada.Text_IO; procedure String_Concatenation is S : String := "Hello"; begin Put_Line (S); declare S1 : String := S & " literal"; begin Put_Line (S1); end; end String_Concatenation;
with AdaM.Environment; procedure AdaM.parse (File : in String; Into : in out AdaM.Environment.item);
with Basic_Subprogram_Calls.Child; with Other_Basic_Subprogram_Calls; with Subprogram_Unit; with Subprogram_Unit_2; package body Basic_Subprogram_Calls is function F7 return Integer; function F8 return Integer is begin return 42; end F8; function F9 return Integer; function F9 return Integer is begin return 42; end F9; function F12 return Integer is separate; procedure P4 is separate; function F13(I : Integer) return Integer renames F2; function F14 return Integer renames F12; procedure P5(I : Integer := F14) renames P3; procedure P6 renames P4; procedure Test is I : Integer := F10; begin I := F1; I := F2(42); I := F3; I := F3(42); I := F4; I := F5(42); I := F6; I := F6(42); I := F7; I := F8; I := F9; declare J : Integer; begin J := F1; end; Label: declare J : Integer; begin J := F2(F12); end Label; P1; P2(42); P3; P3(F11); P4; end Test; function F1 return Integer is begin return 42; end F1; function F2(I : Integer) return Integer is begin return I; end F2; function F3(I : Integer := 42) return Integer is begin return I; end F3; function F7 return Integer is begin return 42; end F7; procedure P1 is begin null; end P1; procedure P2(I : Integer) is begin null; end P2; procedure P3(I : Integer := F1) is J : Integer; begin J := F13(I); J := F14; P5; P5(J); P6; J := Nested.Nested_F1; Nested.Nested_P1; declare use Nested; begin J := Nested.Nested_F1; Nested.Nested_P1; end; P7; P8; J := Child.Child_F1; Child.Child_P1; J := Other_Basic_Subprogram_Calls.Other_F1; Other_Basic_Subprogram_Calls.Other_P1; declare use Child; use Other_Basic_Subprogram_Calls; begin J := Child_F1; Child_P1; J := Other_F1; Other_P1; end; end P3; package body Nested is function Nested_F1 return Integer is begin return 42; end Nested_F1; procedure Nested_P1 is I : Integer := 42; S : String := I'Image; F : access function return Integer := Other_Basic_Subprogram_Calls.Other_F1'Access; P : access procedure := Other_Basic_Subprogram_Calls.Other_P1'Access; begin P := Nested_P1'Access; P := Nested_P1'Access; P := P1'Access; P := P7'Access; F := F1'Access; F := F4'Access; F := F14'Access; F := F12'Access; end Nested_P1; end Nested; package Nested_Renamed renames Nested; procedure P8 is null; function F_Overload(I: Integer) return Integer is begin return I; end F_Overload; function F_Overload(B: Boolean) return Integer is begin return 42; end F_Overload; function F_Overload(I: Integer) return Boolean is begin return True; end F_Overload; procedure P_Overload(I : Integer) is begin null; end P_Overload; procedure P_Overload(B : in out Boolean) is I : Integer; begin B := F_Overload(42); I := F_Overload(B); I := F_Overload(I); P_Overload(B); P_Overload(I); Nested_Renamed.Nested_P1; I := Nested_Renamed.Nested_F1; end P_Overload; procedure Test3 is A : array (1 .. 5) of Integer; type PAT is array (Integer range <>) of access procedure; function F1 return access PAT is begin return new PAT(1 .. 5); end F1; function F2(I : Integer) return access PAT is begin return new PAT(1 .. I); end F2; begin A(3) := 42; F1(2) := Other_Basic_Subprogram_Calls.Other_P1'Access; F2(42)(2) := Other_Basic_Subprogram_Calls.Other_P1'Access; F2(42)(2) := F1(3); A(2) := A(3); end Test3; function F_Internal return Integer is separate; procedure Test4 is Exception_Declaration_Name : exception; begin Statement_Identifier_Name: begin Test3; exception when Choice_Parameter_Specification_Name: Exception_Declaration_Name => raise; end Statement_Identifier_Name; <<Label_Statement_Identifier_Name>> Test3; end Test4; X : aliased Integer := F9; Y : array (1 .. 5) of access Integer; procedure AnonSubp(F : access function(X, Y: Integer) return Integer) is null; function AnonReturn return access Integer is begin return X'Access; end AnonReturn; begin Subprogram_Unit; Subprogram_Unit_2; end Basic_Subprogram_Calls;
--------------------------------------------------------------------------------- -- Copyright 2004-2005 © Luke A. Guest -- -- This code is to be used for tutorial purposes only. -- You may not redistribute this code in any form without my express permission. --------------------------------------------------------------------------------- with Vector3; with Plane; with Line_Segment; use type Vector3.Object; package Geometrical_Methods is function CollisionDetected(P : in Plane.Object; V : in Vector3.Object) return Boolean; function CollisionDetected(P : in Plane.Object; L : in Line_Segment.Object) return Boolean; function ClosestPoint(V : in Vector3.Object; P : in Plane.Object) return Vector3.Object; end Geometrical_Methods;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- T R E E P R S -- -- -- -- S p e c -- -- -- -- Generated by xtreeprs revision 1.1 using -- -- sinfo.ads revision 1.6 -- -- treeprs.adt revision 1.1 -- -- -- -- Copyright (C) 1992-1997 Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, -- -- MA 02111-1307, USA. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- This package contains the declaration of the string used by the Tree_Print -- package. It must be updated whenever the arrangements of the field names -- in package Sinfo is changed. The utility program XTREEPRS is used to -- do this update correctly using the template treeprs.adt as input. with Sinfo; use Sinfo; package Treeprs is -------------------------------- -- String Data for Node Print -- -------------------------------- -- String data for print out. The Pchars array is a long string with the -- the entry for each node type consisting of a single blank, followed by -- a series of entries, one for each Op or Flag field used for the node. -- Each entry has a single character which identifies the field, followed -- by the synonym name. The starting location for a given node type is -- found from the corresponding entry in the Pchars_Pos_Array. -- The following characters identify the field. These are characters -- which could never occur in a field name, so they also mark the -- end of the previous name. subtype Fchar is Character range '#' .. '9'; F_Field1 : constant Fchar := '#'; -- Character'Val (16#23#) F_Field2 : constant Fchar := '$'; -- Character'Val (16#24#) F_Field3 : constant Fchar := '%'; -- Character'Val (16#25#) F_Field4 : constant Fchar := '&'; -- Character'Val (16#26#) F_Field5 : constant Fchar := '''; -- Character'Val (16#27#) F_Flag1 : constant Fchar := '('; -- Character'Val (16#28#) F_Flag2 : constant Fchar := ')'; -- Character'Val (16#29#) F_Flag3 : constant Fchar := '*'; -- Character'Val (16#2A#) F_Flag4 : constant Fchar := '+'; -- Character'Val (16#2B#) F_Flag5 : constant Fchar := ','; -- Character'Val (16#2C#) F_Flag6 : constant Fchar := '-'; -- Character'Val (16#2D#) F_Flag7 : constant Fchar := '.'; -- Character'Val (16#2E#) F_Flag8 : constant Fchar := '/'; -- Character'Val (16#2F#) F_Flag9 : constant Fchar := '0'; -- Character'Val (16#30#) F_Flag10 : constant Fchar := '1'; -- Character'Val (16#31#) F_Flag11 : constant Fchar := '2'; -- Character'Val (16#32#) F_Flag12 : constant Fchar := '3'; -- Character'Val (16#33#) F_Flag13 : constant Fchar := '4'; -- Character'Val (16#34#) F_Flag14 : constant Fchar := '5'; -- Character'Val (16#35#) F_Flag15 : constant Fchar := '6'; -- Character'Val (16#36#) F_Flag16 : constant Fchar := '7'; -- Character'Val (16#37#) F_Flag17 : constant Fchar := '8'; -- Character'Val (16#38#) F_Flag18 : constant Fchar := '9'; -- Character'Val (16#39#) -- Note this table does not include entity field and flags whose access -- functions are in Einfo (these are handled by the Print_Entity_Info -- procedure in Treepr, which uses the routines in Einfo to get the -- proper symbolic information). In addition, the following fields are -- handled by Treepr, and do not appear in the Pchars array: -- Analyzed -- Cannot_Be_Constant -- Chars -- Comes_From_Source -- Error_Posted -- Etype -- Is_Controlling_Actual -- Is_Overloaded -- Is_Static_Expression -- Left_Opnd -- Must_Check_Expr -- Must_Not_Freeze -- No_Overflow_Expr -- Paren_Count -- Raises_Constraint_Error -- Right_Opnd Pchars : constant String := -- Unused_At_Start "" & -- At_Clause "#Identifier%Expression" & -- Component_Clause "#Component_Name$Position%First_Bit&Last_Bit" & -- Enumeration_Representation_Clause "#Identifier%Array_Aggregate&Next_Rep_Item" & -- Mod_Clause "%Expression&Pragmas_Before" & -- Record_Representation_Clause "#Identifier$Mod_Clause%Component_Clauses&Next_Rep_Item" & -- Attribute_Definition_Clause "$Name%Expression&Next_Rep_Item+From_At_Mod" & -- Empty "" & -- Pragma "$Pragma_Argument_Associations%Debug_Statement&Next_Rep_Item" & -- Pragma_Argument_Association "%Expression" & -- Error "" & -- Defining_Character_Literal "$Next_Entity%Scope" & -- Defining_Identifier "$Next_Entity%Scope" & -- Defining_Operator_Symbol "$Next_Entity%Scope" & -- Expanded_Name "%Prefix$Selector_Name&Entity&Associated_Node4Redundant_Use2Has_Privat" & "e_View" & -- Identifier "&Entity&Associated_Node$Original_Discriminant4Redundant_Use2Has_Priva" & "te_View" & -- Operator_Symbol "%Strval&Entity&Associated_Node2Has_Private_View" & -- Character_Literal "$Char_Literal_Value&Entity&Associated_Node2Has_Private_View" & -- Op_Add "" & -- Op_Concat "4Is_Component_Left_Opnd5Is_Component_Right_Opnd" & -- Op_Divide "5Treat_Fixed_As_Integer4Do_Division_Check9Rounded_Result" & -- Op_Expon "4Is_Power_Of_2_For_Shift" & -- Op_Mod "5Treat_Fixed_As_Integer4Do_Division_Check" & -- Op_Multiply "5Treat_Fixed_As_Integer9Rounded_Result" & -- Op_Rem "5Treat_Fixed_As_Integer4Do_Division_Check" & -- Op_Subtract "" & -- Op_And "+Do_Length_Check" & -- Op_Eq "" & -- Op_Ge "" & -- Op_Gt "" & -- Op_Le "" & -- Op_Lt "" & -- Op_Ne "" & -- Op_Or "+Do_Length_Check" & -- Op_Xor "+Do_Length_Check" & -- Op_Rotate_Left "+Shift_Count_OK" & -- Op_Rotate_Right "+Shift_Count_OK" & -- Op_Shift_Left "+Shift_Count_OK" & -- Op_Shift_Right "+Shift_Count_OK" & -- Op_Shift_Right_Arithmetic "+Shift_Count_OK" & -- Op_Abs "" & -- Op_Minus "" & -- Op_Not "" & -- Op_Plus "" & -- Attribute_Reference "%Prefix$Attribute_Name#Expressions&Entity&Associated_Node2Do_Access_C" & "heck8Do_Overflow_Check4Redundant_Use+OK_For_Stream" & -- And_Then "#Actions" & -- Conditional_Expression "#Expressions$Then_Actions%Else_Actions" & -- Explicit_Dereference "%Prefix2Do_Access_Check" & -- Function_Call "$Name%Parameter_Associations&First_Named_Actual#Controlling_Argument4" & "Do_Tag_Check8Parameter_List_Truncated9ABE_Is_Certain" & -- In "" & -- Indexed_Component "%Prefix#Expressions2Do_Access_Check" & -- Integer_Literal "%Intval4Print_In_Hex" & -- Not_In "" & -- Null "" & -- Or_Else "#Actions" & -- Procedure_Call_Statement "$Name%Parameter_Associations&First_Named_Actual#Controlling_Argument4" & "Do_Tag_Check8Parameter_List_Truncated9ABE_Is_Certain" & -- Qualified_Expression "&Subtype_Mark%Expression" & -- Raise_Constraint_Error "#Condition" & -- Raise_Program_Error "#Condition" & -- Raise_Storage_Error "#Condition" & -- Aggregate "#Expressions$Component_Associations8Null_Record_Present%Aggregate_Bou" & "nds&Associated_Node+Static_Processing_OK9Compile_Time_Known_Aggreg" & "ate2Expansion_Delayed" & -- Allocator "%Expression#Storage_Pool&Procedure_To_Call4No_Initialization8Do_Stora" & "ge_Check" & -- Extension_Aggregate "%Ancestor_Part&Associated_Node#Expressions$Component_Associations8Nul" & "l_Record_Present2Expansion_Delayed" & -- Range "#Low_Bound$High_Bound2Includes_Infinities" & -- Real_Literal "%Realval&Corresponding_Integer_Value2Is_Machine_Number" & -- Reference "%Prefix" & -- Selected_Component "%Prefix$Selector_Name&Associated_Node2Do_Access_Check4Do_Discriminant" & "_Check" & -- Slice "%Prefix&Discrete_Range2Do_Access_Check" & -- String_Literal "%Strval2Has_Wide_Character" & -- Subprogram_Info "#Identifier" & -- Type_Conversion "&Subtype_Mark%Expression8Do_Overflow_Check4Do_Tag_Check+Do_Length_Che" & "ck2Float_Truncate9Rounded_Result5Conversion_OK" & -- Unchecked_Expression "%Expression" & -- Unchecked_Type_Conversion "&Subtype_Mark%Expression2Kill_Range_Check" & -- Subtype_Indication "&Subtype_Mark%Constraint/Must_Not_Freeze" & -- Component_Declaration "#Defining_Identifier+Aliased_Present'Subtype_Indication%Expression,Mo" & "re_Ids-Prev_Ids" & -- Entry_Declaration "#Defining_Identifier&Discrete_Subtype_Definition%Parameter_Specificat" & "ions" & -- Formal_Object_Declaration "#Defining_Identifier6In_Present8Out_Present&Subtype_Mark%Expression,M" & "ore_Ids-Prev_Ids" & -- Formal_Type_Declaration "#Defining_Identifier%Formal_Type_Definition&Discriminant_Specificatio" & "ns4Unknown_Discriminants_Present" & -- Full_Type_Declaration "#Defining_Identifier&Discriminant_Specifications%Type_Definition2Disc" & "r_Check_Funcs_Built" & -- Incomplete_Type_Declaration "#Defining_Identifier&Discriminant_Specifications4Unknown_Discriminant" & "s_Present" & -- Loop_Parameter_Specification "#Defining_Identifier6Reverse_Present&Discrete_Subtype_Definition" & -- Object_Declaration "#Defining_Identifier+Aliased_Present8Constant_Present&Object_Definiti" & "on%Expression$Handler_List_Entry'Corresponding_Generic_Association" & ",More_Ids-Prev_Ids4No_Initialization6Assignment_OK2Exception_Junk5" & "Delay_Finalize_Attach7Is_Subprogram_Descriptor" & -- Protected_Type_Declaration "#Defining_Identifier&Discriminant_Specifications%Protected_Definition" & "'Corresponding_Body" & -- Private_Extension_Declaration "#Defining_Identifier&Discriminant_Specifications4Unknown_Discriminant" & "s_Present+Abstract_Present'Subtype_Indication" & -- Private_Type_Declaration "#Defining_Identifier&Discriminant_Specifications4Unknown_Discriminant" & "s_Present+Abstract_Present6Tagged_Present8Limited_Present" & -- Subtype_Declaration "#Defining_Identifier'Subtype_Indication&Generic_Parent_Type2Exception" & "_Junk" & -- Function_Specification "#Defining_Unit_Name$Elaboration_Boolean%Parameter_Specifications&Subt" & "ype_Mark'Generic_Parent" & -- Procedure_Specification "#Defining_Unit_Name$Elaboration_Boolean%Parameter_Specifications'Gene" & "ric_Parent" & -- Entry_Index_Specification "#Defining_Identifier&Discrete_Subtype_Definition" & -- Freeze_Entity "&Entity$Access_Types_To_Process%TSS_Elist#Actions'First_Subtype_Link" & -- Access_Function_Definition "6Protected_Present%Parameter_Specifications&Subtype_Mark" & -- Access_Procedure_Definition "6Protected_Present%Parameter_Specifications" & -- Task_Type_Declaration "#Defining_Identifier$Task_Body_Procedure&Discriminant_Specifications%" & "Task_Definition'Corresponding_Body" & -- Package_Body_Stub "#Defining_Identifier&Library_Unit'Corresponding_Body" & -- Protected_Body_Stub "#Defining_Identifier&Library_Unit'Corresponding_Body" & -- Subprogram_Body_Stub "#Specification&Library_Unit'Corresponding_Body" & -- Task_Body_Stub "#Defining_Identifier&Library_Unit'Corresponding_Body" & -- Function_Instantiation "#Defining_Unit_Name$Name%Generic_Associations&Parent_Spec'Instance_Sp" & "ec9ABE_Is_Certain" & -- Package_Instantiation "#Defining_Unit_Name$Name%Generic_Associations&Parent_Spec'Instance_Sp" & "ec9ABE_Is_Certain" & -- Procedure_Instantiation "#Defining_Unit_Name$Name&Parent_Spec%Generic_Associations'Instance_Sp" & "ec9ABE_Is_Certain" & -- Package_Body "#Defining_Unit_Name$Declarations&Handled_Statement_Sequence'Correspon" & "ding_Spec4Was_Originally_Stub" & -- Subprogram_Body "#Specification$Declarations&Handled_Statement_Sequence%Activation_Cha" & "in_Entity'Corresponding_Spec+Acts_As_Spec6Bad_Is_Detected8Do_Stora" & "ge_Check-Has_Priority_Pragma.Is_Protected_Subprogram_Body,Is_Task_" & "Master4Was_Originally_Stub" & -- Protected_Body "#Defining_Identifier$Declarations&End_Label'Corresponding_Spec4Was_Or" & "iginally_Stub" & -- Task_Body "#Defining_Identifier$Declarations&Handled_Statement_Sequence,Is_Task_" & "Master%Activation_Chain_Entity'Corresponding_Spec4Was_Originally_S" & "tub" & -- Implicit_Label_Declaration "#Defining_Identifier$Label_Construct" & -- Package_Declaration "#Specification'Corresponding_Body&Parent_Spec%Activation_Chain_Entity" & -- Single_Task_Declaration "#Defining_Identifier%Task_Definition" & -- Subprogram_Declaration "#Specification%Body_To_Inline'Corresponding_Body&Parent_Spec" & -- Use_Package_Clause "$Names%Next_Use_Clause&Hidden_By_Use_Clause" & -- Generic_Package_Declaration "#Specification'Corresponding_Body$Generic_Formal_Declarations&Parent_" & "Spec%Activation_Chain_Entity" & -- Generic_Subprogram_Declaration "#Specification'Corresponding_Body$Generic_Formal_Declarations&Parent_" & "Spec" & -- Constrained_Array_Definition "$Discrete_Subtype_Definitions+Aliased_Present'Subtype_Indication" & -- Unconstrained_Array_Definition "$Subtype_Marks+Aliased_Present'Subtype_Indication" & -- Exception_Renaming_Declaration "#Defining_Identifier$Name" & -- Object_Renaming_Declaration "#Defining_Identifier&Subtype_Mark$Name'Corresponding_Generic_Associat" & "ion" & -- Package_Renaming_Declaration "#Defining_Unit_Name$Name&Parent_Spec" & -- Subprogram_Renaming_Declaration "#Specification$Name&Parent_Spec'Corresponding_Spec" & -- Generic_Function_Renaming_Declaration "#Defining_Unit_Name$Name&Parent_Spec" & -- Generic_Package_Renaming_Declaration "#Defining_Unit_Name$Name&Parent_Spec" & -- Generic_Procedure_Renaming_Declaration "#Defining_Unit_Name$Name&Parent_Spec" & -- Abort_Statement "$Names" & -- Accept_Statement "#Entry_Direct_Name'Entry_Index%Parameter_Specifications&Handled_State" & "ment_Sequence$Declarations" & -- Assignment_Statement "$Name%Expression4Do_Tag_Check+Do_Length_Check,Forwards_OK-Backwards_O" & "K.No_Ctrl_Actions" & -- Asynchronous_Select "#Triggering_Alternative$Abortable_Part" & -- Block_Statement "#Identifier$Declarations&Handled_Statement_Sequence,Is_Task_Master%Ac" & "tivation_Chain_Entity6Has_Created_Identifier-Is_Task_Allocation_Bl" & "ock.Is_Asynchronous_Call_Block" & -- Case_Statement "%Expression&Alternatives'End_Span" & -- Code_Statement "%Expression" & -- Conditional_Entry_Call "#Entry_Call_Alternative&Else_Statements" & -- Delay_Relative_Statement "%Expression" & -- Delay_Until_Statement "%Expression" & -- Entry_Call_Statement "$Name%Parameter_Associations&First_Named_Actual" & -- Free_Statement "%Expression#Storage_Pool&Procedure_To_Call" & -- Goto_Statement "$Name2Exception_Junk" & -- Loop_Statement "#Identifier$Iteration_Scheme%Statements&End_Label6Has_Created_Identif" & "ier" & -- Null_Statement "" & -- Raise_Statement "$Name" & -- Requeue_Statement "$Name6Abort_Present" & -- Return_Statement "%Expression#Storage_Pool&Procedure_To_Call4Do_Tag_Check$Return_Type,B" & "y_Ref" & -- Selective_Accept "#Select_Alternatives&Else_Statements" & -- Timed_Entry_Call "#Entry_Call_Alternative&Delay_Alternative" & -- Exit_Statement "$Name#Condition" & -- If_Statement "#Condition$Then_Statements%Elsif_Parts&Else_Statements'End_Span" & -- Accept_Alternative "$Accept_Statement#Condition%Statements&Pragmas_Before'Accept_Handler_" & "Records" & -- Delay_Alternative "$Delay_Statement#Condition%Statements&Pragmas_Before" & -- Elsif_Part "#Condition$Then_Statements%Condition_Actions" & -- Entry_Body_Formal_Part "&Entry_Index_Specification%Parameter_Specifications#Condition" & -- Iteration_Scheme "#Condition%Condition_Actions&Loop_Parameter_Specification" & -- Terminate_Alternative "#Condition&Pragmas_Before'Pragmas_After" & -- Abortable_Part "%Statements" & -- Abstract_Subprogram_Declaration "#Specification" & -- Access_Definition "&Subtype_Mark" & -- Access_To_Object_Definition "6All_Present'Subtype_Indication8Constant_Present" & -- Case_Statement_Alternative "&Discrete_Choices%Statements" & -- Compilation_Unit "&Library_Unit#Context_Items6Private_Present$Unit'Aux_Decls_Node8Has_N" & "o_Elaboration_Code4Body_Required+Acts_As_Spec%First_Inlined_Subpro" & "gram" & -- Compilation_Unit_Aux "$Declarations#Actions'Pragmas_After" & -- Component_Association "#Choices$Loop_Actions%Expression" & -- Component_List "%Component_Items&Variant_Part4Null_Present" & -- Derived_Type_Definition "+Abstract_Present'Subtype_Indication%Record_Extension_Part" & -- Decimal_Fixed_Point_Definition "%Delta_Expression$Digits_Expression&Real_Range_Specification" & -- Defining_Program_Unit_Name "$Name#Defining_Identifier" & -- Delta_Constraint "%Delta_Expression&Range_Constraint" & -- Designator "$Name#Identifier" & -- Digits_Constraint "$Digits_Expression&Range_Constraint" & -- Discriminant_Association "#Selector_Names%Expression" & -- Discriminant_Specification "#Defining_Identifier'Discriminant_Type%Expression,More_Ids-Prev_Ids" & -- Enumeration_Type_Definition "#Literals" & -- Entry_Body "#Defining_Identifier'Entry_Body_Formal_Part$Declarations&Handled_Stat" & "ement_Sequence%Activation_Chain_Entity" & -- Entry_Call_Alternative "#Entry_Call_Statement%Statements&Pragmas_Before" & -- Exception_Declaration "#Defining_Identifier%Expression,More_Ids-Prev_Ids" & -- Exception_Handler "$Choice_Parameter&Exception_Choices%Statements,Zero_Cost_Handling" & -- Floating_Point_Definition "$Digits_Expression&Real_Range_Specification" & -- Formal_Decimal_Fixed_Point_Definition "" & -- Formal_Derived_Type_Definition "&Subtype_Mark6Private_Present+Abstract_Present" & -- Formal_Discrete_Type_Definition "" & -- Formal_Floating_Point_Definition "" & -- Formal_Modular_Type_Definition "" & -- Formal_Ordinary_Fixed_Point_Definition "" & -- Formal_Package_Declaration "#Defining_Identifier$Name%Generic_Associations6Box_Present'Instance_S" & "pec9ABE_Is_Certain" & -- Formal_Private_Type_Definition "+Abstract_Present6Tagged_Present8Limited_Present" & -- Formal_Signed_Integer_Type_Definition "" & -- Formal_Subprogram_Declaration "#Specification$Default_Name6Box_Present" & -- Generic_Association "$Selector_Name#Explicit_Generic_Actual_Parameter" & -- Handled_Sequence_Of_Statements "%Statements&End_Label'Exception_Handlers#At_End_Proc$First_Real_State" & "ment,Zero_Cost_Handling" & -- Index_Or_Discriminant_Constraint "#Constraints" & -- Itype_Reference "#Itype" & -- Label "#Identifier2Exception_Junk" & -- Modular_Type_Definition "%Expression" & -- Number_Declaration "#Defining_Identifier%Expression,More_Ids-Prev_Ids" & -- Ordinary_Fixed_Point_Definition "%Delta_Expression&Real_Range_Specification" & -- Others_Choice "#Others_Discrete_Choices2All_Others" & -- Package_Specification "#Defining_Unit_Name$Visible_Declarations%Private_Declarations&End_Lab" & "el'Generic_Parent" & -- Parameter_Association "$Selector_Name%Explicit_Actual_Parameter&Next_Named_Actual" & -- Parameter_Specification "#Defining_Identifier6In_Present8Out_Present$Parameter_Type%Expression" & "4Do_Accessibility_Check,More_Ids-Prev_Ids'Default_Expression" & -- Protected_Definition "$Visible_Declarations%Private_Declarations&End_Label-Has_Priority_Pra" & "gma" & -- Range_Constraint "&Range_Expression" & -- Real_Range_Specification "#Low_Bound$High_Bound" & -- Record_Definition "&End_Label+Abstract_Present6Tagged_Present8Limited_Present#Component_" & "List4Null_Present" & -- Signed_Integer_Type_Definition "#Low_Bound$High_Bound" & -- Single_Protected_Declaration "#Defining_Identifier%Protected_Definition" & -- Subunit "$Name#Proper_Body%Corresponding_Stub" & -- Task_Definition "$Visible_Declarations%Private_Declarations&End_Label-Has_Priority_Pra" & "gma,Has_Storage_Size_Pragma.Has_Task_Info_Pragma/Has_Task_Name_Pra" & "gma" & -- Triggering_Alternative "#Triggering_Statement%Statements&Pragmas_Before" & -- Use_Type_Clause "$Subtype_Marks%Next_Use_Clause&Hidden_By_Use_Clause" & -- Validate_Unchecked_Conversion "#Source_Type$Target_Type" & -- Variant "&Discrete_Choices#Component_List$Enclosing_Variant%Present_Expr'Dchec" & "k_Function" & -- Variant_Part "$Name#Variants" & -- With_Clause "$Name&Library_Unit'Corresponding_Spec,First_Name-Last_Name4Context_In" & "stalled+Elaborate_Present6Elaborate_All_Present8Implicit_With.Unre" & "ferenced_In_Spec/No_Entities_Ref_In_Spec" & -- With_Type_Clause "$Name6Tagged_Present" & -- Unused_At_End ""; type Pchar_Pos_Array is array (Node_Kind) of Positive; Pchar_Pos : constant Pchar_Pos_Array := Pchar_Pos_Array'( N_Unused_At_Start => 1, N_At_Clause => 1, N_Component_Clause => 23, N_Enumeration_Representation_Clause => 66, N_Mod_Clause => 107, N_Record_Representation_Clause => 133, N_Attribute_Definition_Clause => 187, N_Empty => 229, N_Pragma => 229, N_Pragma_Argument_Association => 288, N_Error => 299, N_Defining_Character_Literal => 299, N_Defining_Identifier => 317, N_Defining_Operator_Symbol => 335, N_Expanded_Name => 353, N_Identifier => 428, N_Operator_Symbol => 504, N_Character_Literal => 551, N_Op_Add => 610, N_Op_Concat => 610, N_Op_Divide => 657, N_Op_Expon => 713, N_Op_Mod => 737, N_Op_Multiply => 778, N_Op_Rem => 816, N_Op_Subtract => 857, N_Op_And => 857, N_Op_Eq => 873, N_Op_Ge => 873, N_Op_Gt => 873, N_Op_Le => 873, N_Op_Lt => 873, N_Op_Ne => 873, N_Op_Or => 873, N_Op_Xor => 889, N_Op_Rotate_Left => 905, N_Op_Rotate_Right => 920, N_Op_Shift_Left => 935, N_Op_Shift_Right => 950, N_Op_Shift_Right_Arithmetic => 965, N_Op_Abs => 980, N_Op_Minus => 980, N_Op_Not => 980, N_Op_Plus => 980, N_Attribute_Reference => 980, N_And_Then => 1099, N_Conditional_Expression => 1107, N_Explicit_Dereference => 1145, N_Function_Call => 1168, N_In => 1289, N_Indexed_Component => 1289, N_Integer_Literal => 1324, N_Not_In => 1344, N_Null => 1344, N_Or_Else => 1344, N_Procedure_Call_Statement => 1352, N_Qualified_Expression => 1473, N_Raise_Constraint_Error => 1497, N_Raise_Program_Error => 1507, N_Raise_Storage_Error => 1517, N_Aggregate => 1527, N_Allocator => 1683, N_Extension_Aggregate => 1760, N_Range => 1863, N_Real_Literal => 1904, N_Reference => 1958, N_Selected_Component => 1965, N_Slice => 2040, N_String_Literal => 2078, N_Subprogram_Info => 2104, N_Type_Conversion => 2115, N_Unchecked_Expression => 2230, N_Unchecked_Type_Conversion => 2241, N_Subtype_Indication => 2282, N_Component_Declaration => 2322, N_Entry_Declaration => 2406, N_Formal_Object_Declaration => 2479, N_Formal_Type_Declaration => 2564, N_Full_Type_Declaration => 2665, N_Incomplete_Type_Declaration => 2753, N_Loop_Parameter_Specification => 2831, N_Object_Declaration => 2895, N_Protected_Type_Declaration => 3142, N_Private_Extension_Declaration => 3230, N_Private_Type_Declaration => 3344, N_Subtype_Declaration => 3470, N_Function_Specification => 3544, N_Procedure_Specification => 3636, N_Entry_Index_Specification => 3715, N_Freeze_Entity => 3763, N_Access_Function_Definition => 3831, N_Access_Procedure_Definition => 3887, N_Task_Type_Declaration => 3930, N_Package_Body_Stub => 4033, N_Protected_Body_Stub => 4085, N_Subprogram_Body_Stub => 4137, N_Task_Body_Stub => 4183, N_Function_Instantiation => 4235, N_Package_Instantiation => 4321, N_Procedure_Instantiation => 4407, N_Package_Body => 4493, N_Subprogram_Body => 4591, N_Protected_Body => 4818, N_Task_Body => 4900, N_Implicit_Label_Declaration => 5038, N_Package_Declaration => 5074, N_Single_Task_Declaration => 5143, N_Subprogram_Declaration => 5179, N_Use_Package_Clause => 5239, N_Generic_Package_Declaration => 5282, N_Generic_Subprogram_Declaration => 5379, N_Constrained_Array_Definition => 5452, N_Unconstrained_Array_Definition => 5516, N_Exception_Renaming_Declaration => 5565, N_Object_Renaming_Declaration => 5590, N_Package_Renaming_Declaration => 5662, N_Subprogram_Renaming_Declaration => 5698, N_Generic_Function_Renaming_Declaration => 5748, N_Generic_Package_Renaming_Declaration => 5784, N_Generic_Procedure_Renaming_Declaration => 5820, N_Abort_Statement => 5856, N_Accept_Statement => 5862, N_Assignment_Statement => 5957, N_Asynchronous_Select => 6043, N_Block_Statement => 6081, N_Case_Statement => 6246, N_Code_Statement => 6279, N_Conditional_Entry_Call => 6290, N_Delay_Relative_Statement => 6329, N_Delay_Until_Statement => 6340, N_Entry_Call_Statement => 6351, N_Free_Statement => 6398, N_Goto_Statement => 6440, N_Loop_Statement => 6460, N_Null_Statement => 6532, N_Raise_Statement => 6532, N_Requeue_Statement => 6537, N_Return_Statement => 6556, N_Selective_Accept => 6630, N_Timed_Entry_Call => 6666, N_Exit_Statement => 6707, N_If_Statement => 6722, N_Accept_Alternative => 6785, N_Delay_Alternative => 6861, N_Elsif_Part => 6913, N_Entry_Body_Formal_Part => 6957, N_Iteration_Scheme => 7018, N_Terminate_Alternative => 7075, N_Abortable_Part => 7114, N_Abstract_Subprogram_Declaration => 7125, N_Access_Definition => 7139, N_Access_To_Object_Definition => 7152, N_Case_Statement_Alternative => 7200, N_Compilation_Unit => 7228, N_Compilation_Unit_Aux => 7367, N_Component_Association => 7402, N_Component_List => 7434, N_Derived_Type_Definition => 7476, N_Decimal_Fixed_Point_Definition => 7534, N_Defining_Program_Unit_Name => 7594, N_Delta_Constraint => 7619, N_Designator => 7653, N_Digits_Constraint => 7669, N_Discriminant_Association => 7704, N_Discriminant_Specification => 7730, N_Enumeration_Type_Definition => 7797, N_Entry_Body => 7806, N_Entry_Call_Alternative => 7913, N_Exception_Declaration => 7960, N_Exception_Handler => 8009, N_Floating_Point_Definition => 8074, N_Formal_Decimal_Fixed_Point_Definition => 8117, N_Formal_Derived_Type_Definition => 8117, N_Formal_Discrete_Type_Definition => 8163, N_Formal_Floating_Point_Definition => 8163, N_Formal_Modular_Type_Definition => 8163, N_Formal_Ordinary_Fixed_Point_Definition => 8163, N_Formal_Package_Declaration => 8163, N_Formal_Private_Type_Definition => 8250, N_Formal_Signed_Integer_Type_Definition => 8298, N_Formal_Subprogram_Declaration => 8298, N_Generic_Association => 8337, N_Handled_Sequence_Of_Statements => 8385, N_Index_Or_Discriminant_Constraint => 8477, N_Itype_Reference => 8489, N_Label => 8495, N_Modular_Type_Definition => 8521, N_Number_Declaration => 8532, N_Ordinary_Fixed_Point_Definition => 8581, N_Others_Choice => 8623, N_Package_Specification => 8658, N_Parameter_Association => 8744, N_Parameter_Specification => 8802, N_Protected_Definition => 8931, N_Range_Constraint => 9003, N_Real_Range_Specification => 9020, N_Record_Definition => 9041, N_Signed_Integer_Type_Definition => 9127, N_Single_Protected_Declaration => 9148, N_Subunit => 9189, N_Task_Definition => 9225, N_Triggering_Alternative => 9363, N_Use_Type_Clause => 9410, N_Validate_Unchecked_Conversion => 9461, N_Variant => 9485, N_Variant_Part => 9564, N_With_Clause => 9578, N_With_Type_Clause => 9753, N_Unused_At_End => 9773); end Treeprs;
with Ada.Text_IO; procedure Move_To_Front is subtype Lower_Case is Character range 'a' .. 'z'; subtype Index is Integer range 0 .. 25; type Table is array (Index) of Lower_Case; Alphabet: constant Table := "abcdefghijklmnopqrstuvwxyz"; type Number_String is array(Positive range <>) of Natural; function Encode(S: String) return Number_String is Key: Table := Alphabet; function Encode(S: String; Tab: in out Table) return Number_String is procedure Look_Up(A: in out Table; Ch: Lower_Case; Pos: out Index) is begin for I in A'Range loop if A(I) = Ch then Pos := I; A := A(Pos) & A(A'First .. Pos-1) & A(Pos+1 .. A'Last); return; end if; end loop; raise Program_Error with "unknown character"; end Look_Up; Empty: Number_String(1 .. 0); Result: Natural; begin if S'Length = 0 then return Empty; else Look_Up(Tab, S(S'First), Result); return Result & Encode(S(S'First+1 .. S'Last), Tab); end if; end Encode; begin return Encode(S, Key); end Encode; function Decode(N: Number_String) return String is Key: Table := Alphabet; function Decode(N: Number_String; Tab: in out Table) return String is procedure Look_Up(A: in out Table; Pos: Index; Ch: out Lower_Case) is begin Ch := A(Pos); A := A(Pos) & A(A'First .. Pos-1) & A(Pos+1 .. A'Last); end Look_Up; Result: String(N'Range); begin for I in N'Range loop Look_Up(Tab, N(I), Result(I)); end loop; return Result; end Decode; begin return Decode(N, Key); end Decode; procedure Encode_Write_Check(S: String) is N: Number_String := Encode(S); T: String := Decode(N); Check: String := (if S=T then "Correct!" else "*WRONG*!"); begin Ada.Text_IO.Put("'" & S & "' encodes to"); for Num of N loop Ada.Text_IO.Put(Integer'Image(Num)); end loop; Ada.Text_IO.Put_Line(". This decodes to '" & T & "'. " & Check); end Encode_Write_Check; begin Encode_Write_Check("broood"); Encode_Write_Check("bananaaa"); Encode_Write_Check("hiphophiphop"); end Move_To_Front;
pragma Style_Checks (Off); -- This spec has been automatically generated from ATSAMD51G19A.svd pragma Restrictions (No_Elaboration_Code); with HAL; with System; package SAM_SVD.NVMCTRL is pragma Preelaborate; --------------- -- Registers -- --------------- -- Write Mode type CTRLA_WMODESelect is (-- Manual Write MAN, -- Automatic Double Word Write ADW, -- Automatic Quad Word AQW, -- Automatic Page Write AP) with Size => 2; for CTRLA_WMODESelect use (MAN => 0, ADW => 1, AQW => 2, AP => 3); -- Power Reduction Mode during Sleep type CTRLA_PRMSelect is (-- NVM block enters low-power mode when entering standby mode. NVM block -- enters low-power mode when SPRM command is issued. NVM block exits -- low-power mode upon first access. SEMIAUTO, -- NVM block enters low-power mode when entering standby mode. NVM block -- enters low-power mode when SPRM command is issued. NVM block exits -- low-power mode when system is not in standby mode. FULLAUTO, -- NVM block does not enter low-power mode when entering standby mode. NVM -- block enters low-power mode when SPRM command is issued. NVM block exits -- low-power mode upon first access. MANUAL) with Size => 2; for CTRLA_PRMSelect use (SEMIAUTO => 0, FULLAUTO => 1, MANUAL => 3); subtype NVMCTRL_CTRLA_RWS_Field is HAL.UInt4; -- NVMCTRL_CTRLA_AHBNS array type NVMCTRL_CTRLA_AHBNS_Field_Array is array (0 .. 1) of Boolean with Component_Size => 1, Size => 2; -- Type definition for NVMCTRL_CTRLA_AHBNS type NVMCTRL_CTRLA_AHBNS_Field (As_Array : Boolean := False) is record case As_Array is when False => -- AHBNS as a value Val : HAL.UInt2; when True => -- AHBNS as an array Arr : NVMCTRL_CTRLA_AHBNS_Field_Array; end case; end record with Unchecked_Union, Size => 2; for NVMCTRL_CTRLA_AHBNS_Field use record Val at 0 range 0 .. 1; Arr at 0 range 0 .. 1; end record; -- NVMCTRL_CTRLA_CACHEDIS array type NVMCTRL_CTRLA_CACHEDIS_Field_Array is array (0 .. 1) of Boolean with Component_Size => 1, Size => 2; -- Type definition for NVMCTRL_CTRLA_CACHEDIS type NVMCTRL_CTRLA_CACHEDIS_Field (As_Array : Boolean := False) is record case As_Array is when False => -- CACHEDIS as a value Val : HAL.UInt2; when True => -- CACHEDIS as an array Arr : NVMCTRL_CTRLA_CACHEDIS_Field_Array; end case; end record with Unchecked_Union, Size => 2; for NVMCTRL_CTRLA_CACHEDIS_Field use record Val at 0 range 0 .. 1; Arr at 0 range 0 .. 1; end record; -- Control A type NVMCTRL_CTRLA_Register is record -- unspecified Reserved_0_1 : HAL.UInt2 := 16#0#; -- Auto Wait State Enable AUTOWS : Boolean := True; -- Suspend Enable SUSPEN : Boolean := False; -- Write Mode WMODE : CTRLA_WMODESelect := SAM_SVD.NVMCTRL.MAN; -- Power Reduction Mode during Sleep PRM : CTRLA_PRMSelect := SAM_SVD.NVMCTRL.SEMIAUTO; -- NVM Read Wait States RWS : NVMCTRL_CTRLA_RWS_Field := 16#0#; -- Force AHB0 access to NONSEQ, burst transfers are continuously -- rearbitrated AHBNS : NVMCTRL_CTRLA_AHBNS_Field := (As_Array => False, Val => 16#0#); -- AHB0 Cache Disable CACHEDIS : NVMCTRL_CTRLA_CACHEDIS_Field := (As_Array => False, Val => 16#0#); end record with Volatile_Full_Access, Object_Size => 16, Bit_Order => System.Low_Order_First; for NVMCTRL_CTRLA_Register use record Reserved_0_1 at 0 range 0 .. 1; AUTOWS at 0 range 2 .. 2; SUSPEN at 0 range 3 .. 3; WMODE at 0 range 4 .. 5; PRM at 0 range 6 .. 7; RWS at 0 range 8 .. 11; AHBNS at 0 range 12 .. 13; CACHEDIS at 0 range 14 .. 15; end record; -- Command type CTRLB_CMDSelect is (-- Erase Page - Only supported in the USER and AUX pages. EP, -- Erase Block - Erases the block addressed by the ADDR register, not -- supported in the user page EB, -- Write Page - Writes the contents of the page buffer to the page addressed -- by the ADDR register, not supported in the user page WP, -- Write Quad Word - Writes a 128-bit word at the location addressed by the -- ADDR register. WQW, -- Software Reset - Power-Cycle the NVM memory and replay the device automatic -- calibration procedure and resets the module configuration registers SWRST, -- Lock Region - Locks the region containing the address location in the ADDR -- register. LR, -- Unlock Region - Unlocks the region containing the address location in the -- ADDR register. UR, -- Sets the power reduction mode. SPRM, -- Clears the power reduction mode. CPRM, -- Page Buffer Clear - Clears the page buffer. PBC, -- Set Security Bit SSB, -- Bank swap and system reset, if SMEE is used also reallocate SMEE data into -- the opposite BANK BKSWRST, -- Chip Erase Lock - DSU.CE command is not available CELCK, -- Chip Erase Unlock - DSU.CE command is available CEULCK, -- Sets STATUS.BPDIS, Boot loader protection is discarded until CBPDIS is -- issued or next start-up sequence SBPDIS, -- Clears STATUS.BPDIS, Boot loader protection is not discarded CBPDIS, -- Activate SmartEEPROM Sector 0, deactivate Sector 1 ASEES0, -- Activate SmartEEPROM Sector 1, deactivate Sector 0 ASEES1, -- Starts SmartEEPROM sector reallocation algorithm SEERALOC, -- Flush SMEE data when in buffered mode SEEFLUSH, -- Lock access to SmartEEPROM data from any mean LSEE, -- Unlock access to SmartEEPROM data USEE, -- Lock access to the SmartEEPROM Register Address Space (above 64KB) LSEER, -- Unlock access to the SmartEEPROM Register Address Space (above 64KB) USEER) with Size => 7; for CTRLB_CMDSelect use (EP => 0, EB => 1, WP => 3, WQW => 4, SWRST => 16, LR => 17, UR => 18, SPRM => 19, CPRM => 20, PBC => 21, SSB => 22, BKSWRST => 23, CELCK => 24, CEULCK => 25, SBPDIS => 26, CBPDIS => 27, ASEES0 => 48, ASEES1 => 49, SEERALOC => 50, SEEFLUSH => 51, LSEE => 52, USEE => 53, LSEER => 54, USEER => 55); -- Command Execution type CTRLB_CMDEXSelect is (-- Reset value for the field CTRLB_CMDEXSelect_Reset, -- Execution Key KEY) with Size => 8; for CTRLB_CMDEXSelect use (CTRLB_CMDEXSelect_Reset => 0, KEY => 165); -- Control B type NVMCTRL_CTRLB_Register is record -- Write-only. Command CMD : CTRLB_CMDSelect := SAM_SVD.NVMCTRL.EP; -- unspecified Reserved_7_7 : HAL.Bit := 16#0#; -- Write-only. Command Execution CMDEX : CTRLB_CMDEXSelect := CTRLB_CMDEXSelect_Reset; end record with Volatile_Full_Access, Object_Size => 16, Bit_Order => System.Low_Order_First; for NVMCTRL_CTRLB_Register use record CMD at 0 range 0 .. 6; Reserved_7_7 at 0 range 7 .. 7; CMDEX at 0 range 8 .. 15; end record; subtype NVMCTRL_PARAM_NVMP_Field is HAL.UInt16; -- Page Size type PARAM_PSZSelect is (-- 8 bytes Val_8, -- 16 bytes Val_16, -- 32 bytes Val_32, -- 64 bytes Val_64, -- 128 bytes Val_128, -- 256 bytes Val_256, -- 512 bytes Val_512, -- 1024 bytes Val_1024) with Size => 3; for PARAM_PSZSelect use (Val_8 => 0, Val_16 => 1, Val_32 => 2, Val_64 => 3, Val_128 => 4, Val_256 => 5, Val_512 => 6, Val_1024 => 7); -- SmartEEPROM Supported type PARAM_SEESelect is (-- 0 bytes Val_0, -- 16384 bytes Val_1, -- 32768 bytes Val_2, -- 49152 bytes Val_3, -- 65536 bytes Val_4, -- 81920 bytes Val_5, -- 98304 bytes Val_6, -- 114688 bytes Val_7, -- 131072 bytes Val_8, -- 147456 bytes Val_9, -- 163840 bytes A) with Size => 1; for PARAM_SEESelect use (Val_0 => 0, Val_1 => 1, Val_2 => 2, Val_3 => 3, Val_4 => 4, Val_5 => 5, Val_6 => 6, Val_7 => 7, Val_8 => 8, Val_9 => 9, A => 10); -- NVM Parameter type NVMCTRL_PARAM_Register is record -- Read-only. NVM Pages NVMP : NVMCTRL_PARAM_NVMP_Field; -- Read-only. Page Size PSZ : PARAM_PSZSelect; -- unspecified Reserved_19_30 : HAL.UInt12; -- Read-only. SmartEEPROM Supported SEE : PARAM_SEESelect; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for NVMCTRL_PARAM_Register use record NVMP at 0 range 0 .. 15; PSZ at 0 range 16 .. 18; Reserved_19_30 at 0 range 19 .. 30; SEE at 0 range 31 .. 31; end record; -- Interrupt Enable Clear type NVMCTRL_INTENCLR_Register is record -- Command Done Interrupt Clear DONE : Boolean := False; -- Address Error ADDRE : Boolean := False; -- Programming Error Interrupt Clear PROGE : Boolean := False; -- Lock Error Interrupt Clear LOCKE : Boolean := False; -- ECC Single Error Interrupt Clear ECCSE : Boolean := False; -- ECC Dual Error Interrupt Clear ECCDE : Boolean := False; -- NVM Error Interrupt Clear NVME : Boolean := False; -- Suspended Write Or Erase Interrupt Clear SUSP : Boolean := False; -- Active SEES Full Interrupt Clear SEESFULL : Boolean := False; -- Active SEES Overflow Interrupt Clear SEESOVF : Boolean := False; -- SEE Write Completed Interrupt Clear SEEWRC : Boolean := False; -- unspecified Reserved_11_15 : HAL.UInt5 := 16#0#; end record with Volatile_Full_Access, Object_Size => 16, Bit_Order => System.Low_Order_First; for NVMCTRL_INTENCLR_Register use record DONE at 0 range 0 .. 0; ADDRE at 0 range 1 .. 1; PROGE at 0 range 2 .. 2; LOCKE at 0 range 3 .. 3; ECCSE at 0 range 4 .. 4; ECCDE at 0 range 5 .. 5; NVME at 0 range 6 .. 6; SUSP at 0 range 7 .. 7; SEESFULL at 0 range 8 .. 8; SEESOVF at 0 range 9 .. 9; SEEWRC at 0 range 10 .. 10; Reserved_11_15 at 0 range 11 .. 15; end record; -- Interrupt Enable Set type NVMCTRL_INTENSET_Register is record -- Command Done Interrupt Enable DONE : Boolean := False; -- Address Error Interrupt Enable ADDRE : Boolean := False; -- Programming Error Interrupt Enable PROGE : Boolean := False; -- Lock Error Interrupt Enable LOCKE : Boolean := False; -- ECC Single Error Interrupt Enable ECCSE : Boolean := False; -- ECC Dual Error Interrupt Enable ECCDE : Boolean := False; -- NVM Error Interrupt Enable NVME : Boolean := False; -- Suspended Write Or Erase Interrupt Enable SUSP : Boolean := False; -- Active SEES Full Interrupt Enable SEESFULL : Boolean := False; -- Active SEES Overflow Interrupt Enable SEESOVF : Boolean := False; -- SEE Write Completed Interrupt Enable SEEWRC : Boolean := False; -- unspecified Reserved_11_15 : HAL.UInt5 := 16#0#; end record with Volatile_Full_Access, Object_Size => 16, Bit_Order => System.Low_Order_First; for NVMCTRL_INTENSET_Register use record DONE at 0 range 0 .. 0; ADDRE at 0 range 1 .. 1; PROGE at 0 range 2 .. 2; LOCKE at 0 range 3 .. 3; ECCSE at 0 range 4 .. 4; ECCDE at 0 range 5 .. 5; NVME at 0 range 6 .. 6; SUSP at 0 range 7 .. 7; SEESFULL at 0 range 8 .. 8; SEESOVF at 0 range 9 .. 9; SEEWRC at 0 range 10 .. 10; Reserved_11_15 at 0 range 11 .. 15; end record; -- Interrupt Flag Status and Clear type NVMCTRL_INTFLAG_Register is record -- Command Done DONE : Boolean := False; -- Address Error ADDRE : Boolean := False; -- Programming Error PROGE : Boolean := False; -- Lock Error LOCKE : Boolean := False; -- ECC Single Error ECCSE : Boolean := False; -- ECC Dual Error ECCDE : Boolean := False; -- NVM Error NVME : Boolean := False; -- Suspended Write Or Erase Operation SUSP : Boolean := False; -- Active SEES Full SEESFULL : Boolean := False; -- Active SEES Overflow SEESOVF : Boolean := False; -- SEE Write Completed SEEWRC : Boolean := False; -- unspecified Reserved_11_15 : HAL.UInt5 := 16#0#; end record with Volatile_Full_Access, Object_Size => 16, Bit_Order => System.Low_Order_First; for NVMCTRL_INTFLAG_Register use record DONE at 0 range 0 .. 0; ADDRE at 0 range 1 .. 1; PROGE at 0 range 2 .. 2; LOCKE at 0 range 3 .. 3; ECCSE at 0 range 4 .. 4; ECCDE at 0 range 5 .. 5; NVME at 0 range 6 .. 6; SUSP at 0 range 7 .. 7; SEESFULL at 0 range 8 .. 8; SEESOVF at 0 range 9 .. 9; SEEWRC at 0 range 10 .. 10; Reserved_11_15 at 0 range 11 .. 15; end record; -- Boot Loader Protection Size type STATUS_BOOTPROTSelect is (-- 120 kbytes Val_120, -- 112 kbytes Val_112, -- 104 kbytes Val_104, -- 96 kbytes Val_96, -- 88 kbytes Val_88, -- 80 kbytes Val_80, -- 72 kbytes Val_72, -- 64 kbytes Val_64, -- 56 kbytes Val_56, -- 48 kbytes Val_48, -- 40 kbytes Val_40, -- 32 kbytes Val_32, -- 24 kbytes Val_24, -- 16 kbytes Val_16, -- 8 kbytes Val_8, -- 0 kbytes Val_0) with Size => 4; for STATUS_BOOTPROTSelect use (Val_120 => 0, Val_112 => 1, Val_104 => 2, Val_96 => 3, Val_88 => 4, Val_80 => 5, Val_72 => 6, Val_64 => 7, Val_56 => 8, Val_48 => 9, Val_40 => 10, Val_32 => 11, Val_24 => 12, Val_16 => 13, Val_8 => 14, Val_0 => 15); -- Status type NVMCTRL_STATUS_Register is record -- Read-only. Ready to accept a command READY : Boolean; -- Read-only. Power Reduction Mode PRM : Boolean; -- Read-only. NVM Page Buffer Active Loading LOAD : Boolean; -- Read-only. NVM Write Or Erase Operation Is Suspended SUSP : Boolean; -- Read-only. BANKA First AFIRST : Boolean; -- Read-only. Boot Loader Protection Disable BPDIS : Boolean; -- unspecified Reserved_6_7 : HAL.UInt2; -- Read-only. Boot Loader Protection Size BOOTPROT : STATUS_BOOTPROTSelect; -- unspecified Reserved_12_15 : HAL.UInt4; end record with Volatile_Full_Access, Object_Size => 16, Bit_Order => System.Low_Order_First; for NVMCTRL_STATUS_Register use record READY at 0 range 0 .. 0; PRM at 0 range 1 .. 1; LOAD at 0 range 2 .. 2; SUSP at 0 range 3 .. 3; AFIRST at 0 range 4 .. 4; BPDIS at 0 range 5 .. 5; Reserved_6_7 at 0 range 6 .. 7; BOOTPROT at 0 range 8 .. 11; Reserved_12_15 at 0 range 12 .. 15; end record; subtype NVMCTRL_ADDR_ADDR_Field is HAL.UInt24; -- Address type NVMCTRL_ADDR_Register is record -- NVM Address ADDR : NVMCTRL_ADDR_ADDR_Field := 16#0#; -- unspecified Reserved_24_31 : HAL.UInt8 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for NVMCTRL_ADDR_Register use record ADDR at 0 range 0 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; -- Page Buffer Load Data x -- Page Buffer Load Data x type NVMCTRL_PBLDATA_Registers is array (0 .. 1) of HAL.UInt32; subtype NVMCTRL_ECCERR_ADDR_Field is HAL.UInt24; -- Low Double-Word Error Type type ECCERR_TYPELSelect is (-- No Error Detected Since Last Read None, -- At Least One Single Error Detected Since last Read Single, -- At Least One Dual Error Detected Since Last Read Dual) with Size => 2; for ECCERR_TYPELSelect use (None => 0, Single => 1, Dual => 2); -- High Double-Word Error Type type ECCERR_TYPEHSelect is (-- No Error Detected Since Last Read None, -- At Least One Single Error Detected Since last Read Single, -- At Least One Dual Error Detected Since Last Read Dual) with Size => 2; for ECCERR_TYPEHSelect use (None => 0, Single => 1, Dual => 2); -- ECC Error Status Register type NVMCTRL_ECCERR_Register is record -- Read-only. Error Address ADDR : NVMCTRL_ECCERR_ADDR_Field; -- unspecified Reserved_24_27 : HAL.UInt4; -- Read-only. Low Double-Word Error Type TYPEL : ECCERR_TYPELSelect; -- Read-only. High Double-Word Error Type TYPEH : ECCERR_TYPEHSelect; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for NVMCTRL_ECCERR_Register use record ADDR at 0 range 0 .. 23; Reserved_24_27 at 0 range 24 .. 27; TYPEL at 0 range 28 .. 29; TYPEH at 0 range 30 .. 31; end record; -- Debug Control type NVMCTRL_DBGCTRL_Register is record -- Debugger ECC Read Disable ECCDIS : Boolean := False; -- Debugger ECC Error Tracking Mode ECCELOG : Boolean := False; -- unspecified Reserved_2_7 : HAL.UInt6 := 16#0#; end record with Volatile_Full_Access, Object_Size => 8, Bit_Order => System.Low_Order_First; for NVMCTRL_DBGCTRL_Register use record ECCDIS at 0 range 0 .. 0; ECCELOG at 0 range 1 .. 1; Reserved_2_7 at 0 range 2 .. 7; end record; -- Write Mode type SEECFG_WMODESelect is (-- A NVM write command is issued after each write in the pagebuffer UNBUFFERED, -- A NVM write command is issued when a write to a new page is requested BUFFERED) with Size => 1; for SEECFG_WMODESelect use (UNBUFFERED => 0, BUFFERED => 1); -- SmartEEPROM Configuration Register type NVMCTRL_SEECFG_Register is record -- Write Mode WMODE : SEECFG_WMODESelect := SAM_SVD.NVMCTRL.UNBUFFERED; -- Automatic Page Reallocation Disable APRDIS : Boolean := False; -- unspecified Reserved_2_7 : HAL.UInt6 := 16#0#; end record with Volatile_Full_Access, Object_Size => 8, Bit_Order => System.Low_Order_First; for NVMCTRL_SEECFG_Register use record WMODE at 0 range 0 .. 0; APRDIS at 0 range 1 .. 1; Reserved_2_7 at 0 range 2 .. 7; end record; subtype NVMCTRL_SEESTAT_SBLK_Field is HAL.UInt4; subtype NVMCTRL_SEESTAT_PSZ_Field is HAL.UInt3; -- SmartEEPROM Status Register type NVMCTRL_SEESTAT_Register is record -- Read-only. Active SmartEEPROM Sector ASEES : Boolean; -- Read-only. Page Buffer Loaded LOAD : Boolean; -- Read-only. Busy BUSY : Boolean; -- Read-only. SmartEEPROM Write Access Is Locked LOCK : Boolean; -- Read-only. SmartEEPROM Write Access To Register Address Space Is -- Locked RLOCK : Boolean; -- unspecified Reserved_5_7 : HAL.UInt3; -- Read-only. Blocks Number In a Sector SBLK : NVMCTRL_SEESTAT_SBLK_Field; -- unspecified Reserved_12_15 : HAL.UInt4; -- Read-only. SmartEEPROM Page Size PSZ : NVMCTRL_SEESTAT_PSZ_Field; -- unspecified Reserved_19_31 : HAL.UInt13; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for NVMCTRL_SEESTAT_Register use record ASEES at 0 range 0 .. 0; LOAD at 0 range 1 .. 1; BUSY at 0 range 2 .. 2; LOCK at 0 range 3 .. 3; RLOCK at 0 range 4 .. 4; Reserved_5_7 at 0 range 5 .. 7; SBLK at 0 range 8 .. 11; Reserved_12_15 at 0 range 12 .. 15; PSZ at 0 range 16 .. 18; Reserved_19_31 at 0 range 19 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- Non-Volatile Memory Controller type NVMCTRL_Peripheral is record -- Control A CTRLA : aliased NVMCTRL_CTRLA_Register; -- Control B CTRLB : aliased NVMCTRL_CTRLB_Register; -- NVM Parameter PARAM : aliased NVMCTRL_PARAM_Register; -- Interrupt Enable Clear INTENCLR : aliased NVMCTRL_INTENCLR_Register; -- Interrupt Enable Set INTENSET : aliased NVMCTRL_INTENSET_Register; -- Interrupt Flag Status and Clear INTFLAG : aliased NVMCTRL_INTFLAG_Register; -- Status STATUS : aliased NVMCTRL_STATUS_Register; -- Address ADDR : aliased NVMCTRL_ADDR_Register; -- Lock Section RUNLOCK : aliased HAL.UInt32; -- Page Buffer Load Data x PBLDATA : aliased NVMCTRL_PBLDATA_Registers; -- ECC Error Status Register ECCERR : aliased NVMCTRL_ECCERR_Register; -- Debug Control DBGCTRL : aliased NVMCTRL_DBGCTRL_Register; -- SmartEEPROM Configuration Register SEECFG : aliased NVMCTRL_SEECFG_Register; -- SmartEEPROM Status Register SEESTAT : aliased NVMCTRL_SEESTAT_Register; end record with Volatile; for NVMCTRL_Peripheral use record CTRLA at 16#0# range 0 .. 15; CTRLB at 16#4# range 0 .. 15; PARAM at 16#8# range 0 .. 31; INTENCLR at 16#C# range 0 .. 15; INTENSET at 16#E# range 0 .. 15; INTFLAG at 16#10# range 0 .. 15; STATUS at 16#12# range 0 .. 15; ADDR at 16#14# range 0 .. 31; RUNLOCK at 16#18# range 0 .. 31; PBLDATA at 16#1C# range 0 .. 63; ECCERR at 16#24# range 0 .. 31; DBGCTRL at 16#28# range 0 .. 7; SEECFG at 16#2A# range 0 .. 7; SEESTAT at 16#2C# range 0 .. 31; end record; -- Non-Volatile Memory Controller NVMCTRL_Periph : aliased NVMCTRL_Peripheral with Import, Address => NVMCTRL_Base; end SAM_SVD.NVMCTRL;
------------------------------------------------------------------------------ -- -- -- GNU ADA RUN-TIME LIBRARY (GNARL) COMPONENTS -- -- -- -- S Y S T E M . T A S K _ P R I M I T I V E S . G E N _ T C B I N F -- -- -- -- B o d y -- -- -- -- $Revision$ -- -- -- Copyright (C) 1999-2000 Free Software Fundation -- -- -- -- 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. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- This is an SGI Irix version of this package -- This procedure creates the file "a-tcbinf.c" -- "A-tcbinf.c" is subsequently compiled and made part of the RTL -- to be referenced by the SGI Workshop debugger. The main procedure: -- "Gen_Tcbinf" imports this child procedure and runs as part of the -- RTL build process. Because of the complex process used to build -- the GNAT RTL for all the different systems and the frequent changes -- made to the internal data structures, its impractical to create -- "a-tcbinf.c" using a standalone process. with System.Tasking; with Ada.Text_IO; with Unchecked_Conversion; procedure System.Task_Primitives.Gen_Tcbinf is use System.Tasking; subtype Version_String is String (1 .. 4); Version : constant Version_String := "3.11"; function To_Integer is new Unchecked_Conversion (Version_String, Integer); type Dummy_TCB_Ptr is access Ada_Task_Control_Block (Entry_Num => 0); Dummy_TCB : constant Dummy_TCB_Ptr := new Ada_Task_Control_Block (0); C_File : Ada.Text_IO.File_Type; procedure Pl (S : String); procedure Nl (C : Ada.Text_IO.Positive_Count := 1); function State_Name (S : Task_States) return String; procedure Pl (S : String) is begin Ada.Text_IO.Put_Line (C_File, S); end Pl; procedure Nl (C : Ada.Text_IO.Positive_Count := 1) is begin Ada.Text_IO.New_Line (C_File, C); end Nl; function State_Name (S : Task_States) return String is begin case S is when Unactivated => return "Unactivated"; when Runnable => return "Runnable"; when Terminated => return "Terminated"; when Activator_Sleep => return "Child Activation Wait"; when Acceptor_Sleep => return "Accept/Select Wait"; when Entry_Caller_Sleep => return "Waiting on Entry Call"; when Async_Select_Sleep => return "Async_Select Wait"; when Delay_Sleep => return "Delay Sleep"; when Master_Completion_Sleep => return "Child Termination Wait"; when Master_Phase_2_Sleep => return "Wait Child in Term Alt"; when Interrupt_Server_Idle_Sleep => return "Int Server Idle Sleep"; when Interrupt_Server_Blocked_Interrupt_Sleep => return "Int Server Blk Int Sleep"; when Timer_Server_Sleep => return "Timer Server Sleep"; when AST_Server_Sleep => return "AST Server Sleep"; when Asynchronous_Hold => return "Asynchronous Hold"; when Interrupt_Server_Blocked_On_Event_Flag => return "Int Server Blk Evt Flag"; end case; end State_Name; All_Tasks_Link_Offset : constant Integer := Dummy_TCB.Common'Position + Dummy_TCB.Common.All_Tasks_Link'Position; Entry_Count_Offset : constant Integer := Dummy_TCB.Entry_Num'Position; Entry_Point_Offset : constant Integer := Dummy_TCB.Common'Position + Dummy_TCB.Common.Task_Entry_Point'Position; Parent_Offset : constant Integer := Dummy_TCB.Common'Position + Dummy_TCB.Common.Parent'Position; Base_Priority_Offset : constant Integer := Dummy_TCB.Common'Position + Dummy_TCB.Common.Base_Priority'Position; Current_Priority_Offset : constant Integer := Dummy_TCB.Common'Position + Dummy_TCB.Common.Current_Priority'Position; Stack_Size_Offset : constant Integer := Dummy_TCB.Common'Position + Dummy_TCB.Common.Compiler_Data.Pri_Stack_Info.Size'Position; State_Offset : constant Integer := Dummy_TCB.Common'Position + Dummy_TCB.Common.State'Position; Task_Image_Offset : constant Integer := Dummy_TCB.Common'Position + Dummy_TCB.Common.Task_Image'Position; Thread_Offset : constant Integer := Dummy_TCB.Common'Position + Dummy_TCB.Common.LL'Position + Dummy_TCB.Common.LL.Thread'Position; begin Ada.Text_IO.Create (C_File, Ada.Text_IO.Out_File, "a-tcbinf.c"); Pl (""); Pl ("#include <sys/types.h>"); Pl (""); Pl ("#define TCB_INFO_VERSION 2"); Pl ("#define TCB_LIBRARY_VERSION " & Integer'Image (To_Integer (Version))); Pl (""); Pl ("typedef struct {"); Pl (""); Pl (" __uint32_t info_version;"); Pl (" __uint32_t library_version;"); Pl (""); Pl (" __uint32_t All_Tasks_Link_Offset;"); Pl (" __uint32_t Entry_Count_Offset;"); Pl (" __uint32_t Entry_Point_Offset;"); Pl (" __uint32_t Parent_Offset;"); Pl (" __uint32_t Base_Priority_Offset;"); Pl (" __uint32_t Current_Priority_Offset;"); Pl (" __uint32_t Stack_Size_Offset;"); Pl (" __uint32_t State_Offset;"); Pl (" __uint32_t Task_Image_Offset;"); Pl (" __uint32_t Thread_Offset;"); Pl (""); Pl (" char **state_names;"); Pl (" __uint32_t state_names_max;"); Pl (""); Pl ("} task_control_block_info_t;"); Pl (""); Pl ("static char *accepting_state_names = NULL;"); Pl (""); Pl ("static char *task_state_names[] = {"); for State in Task_States loop Pl (" """ & State_Name (State) & ""","); end loop; Pl (" """"};"); Pl (""); Pl (""); Pl ("task_control_block_info_t __task_control_block_info = {"); Pl (""); Pl (" TCB_INFO_VERSION,"); Pl (" TCB_LIBRARY_VERSION,"); Pl (""); Pl (" " & All_Tasks_Link_Offset'Img & ","); Pl (" " & Entry_Count_Offset'Img & ","); Pl (" " & Entry_Point_Offset'Img & ","); Pl (" " & Parent_Offset'Img & ","); Pl (" " & Base_Priority_Offset'Img & ","); Pl (" " & Current_Priority_Offset'Img & ","); Pl (" " & Stack_Size_Offset'Img & ","); Pl (" " & State_Offset'Img & ","); Pl (" " & Task_Image_Offset'Img & ","); Pl (" " & Thread_Offset'Img & ","); Pl (""); Pl (" task_state_names,"); Pl (" sizeof (task_state_names),"); Pl (""); Pl (""); Pl ("};"); Ada.Text_IO.Close (C_File); end System.Task_Primitives.Gen_Tcbinf;
with Ada.Text_IO; use Ada.Text_IO; package User is procedure Hello_Part1 is begin Put_Line ("Hello from part1"); end Hello_Part1; end User;
----------------------------------------------------------------------- -- ado-sequences-tests -- Test sequences factories -- Copyright (C) 2011, 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 Util.Test_Caller; with ADO.Drivers; with ADO.Sessions; with ADO.SQL; with Regtests.Simple.Model; with ADO.Sequences.Hilo; with ADO.Sessions.Factory; package body ADO.Sequences.Tests is use Util.Tests; type Test_Impl is new ADO.Objects.Object_Record (Key_Type => ADO.Objects.KEY_INTEGER, Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE'Access) with record Version : Integer; Value : ADO.Identifier; Name : Ada.Strings.Unbounded.Unbounded_String; Select_Name : Ada.Strings.Unbounded.Unbounded_String; end record; overriding procedure Destroy (Object : access Test_Impl); overriding procedure Find (Object : in out Test_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); overriding procedure Load (Object : in out Test_Impl; Session : in out ADO.Sessions.Session'Class); overriding procedure Save (Object : in out Test_Impl; Session : in out ADO.Sessions.Master_Session'Class); overriding procedure Delete (Object : in out Test_Impl; Session : in out ADO.Sessions.Master_Session'Class); overriding procedure Create (Object : in out Test_Impl; Session : in out ADO.Sessions.Master_Session'Class); package Caller is new Util.Test_Caller (Test, "ADO.Sequences"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Sequences.Create", Test_Create_Factory'Access); end Add_Tests; -- Test creation of the sequence factory. -- This test revealed a memory leak if we failed to create a database connection. procedure Test_Create_Factory (T : in out Test) is Seq_Factory : ADO.Sequences.Factory; Obj : Test_Impl; Factory : aliased ADO.Sessions.Factory.Session_Factory; begin Seq_Factory.Set_Default_Generator (ADO.Sequences.Hilo.Create_HiLo_Generator'Access, Factory'Unchecked_Access); begin Seq_Factory.Allocate (Obj); T.Assert (False, "No exception raised."); exception when ADO.Drivers.Connection_Error => null; -- Good! An exception is expected because the session factory is empty. end; end Test_Create_Factory; overriding procedure Destroy (Object : access Test_Impl) is begin null; end Destroy; overriding procedure Find (Object : in out Test_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is pragma Unreferenced (Object, Session, Query); begin Found := False; end Find; overriding procedure Load (Object : in out Test_Impl; Session : in out ADO.Sessions.Session'Class) is begin null; end Load; overriding procedure Save (Object : in out Test_Impl; Session : in out ADO.Sessions.Master_Session'Class) is begin null; end Save; overriding procedure Delete (Object : in out Test_Impl; Session : in out ADO.Sessions.Master_Session'Class) is begin null; end Delete; overriding procedure Create (Object : in out Test_Impl; Session : in out ADO.Sessions.Master_Session'Class) is begin null; end Create; end ADO.Sequences.Tests;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Common; use Common; with LMCP_Messages; use LMCP_Messages; private with UxAS.Comms.LMCP_Object_Message_Sender_Pipes; -- Package only concerned with message passing. It defines its own state, -- named Mailbox here, which is not mixed with the state of the service. package Assignment_Tree_Branch_Bound_Communication with SPARK_Mode is type Assignment_Tree_Branch_Bound_Mailbox is limited private; procedure Initialize (This : out Assignment_Tree_Branch_Bound_Mailbox; Source_Group : String; Unique_Id : Int64; Entity_Id : UInt32; Service_Id : UInt32); procedure sendBroadcastMessage (This : in out Assignment_Tree_Branch_Bound_Mailbox; Msg : Message_Root'Class); procedure sendErrorMessage (This : in out Assignment_Tree_Branch_Bound_Mailbox; Error_String : Unbounded_String); private pragma SPARK_Mode (Off); use Ada.Strings.Unbounded; use UxAS.Comms.LMCP_Object_Message_Sender_Pipes; type Assignment_Tree_Branch_Bound_Mailbox is tagged limited record Message_Sender_Pipe : LMCP_Object_Message_Sender_Pipe; Source_Group : Unbounded_String; Unique_Entity_Send_Message_Id : Int64; end record; end Assignment_Tree_Branch_Bound_Communication;
package Irc is pragma Pure (Irc); Version : constant String := "0.1.0"; end Irc;
-- SPDX-FileCopyrightText: 2021 Max Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT ------------------------------------------------------------- with League.String_Vectors; with WebIDL.Parsers; with WebIDL.Scanners; with WebIDL.String_Sources; with WebIDL.Token_Handlers; with WebIDL.Tokens; package WebIDL.Lexers is pragma Preelaborate; type Lexer is limited new WebIDL.Parsers.Abstract_Lexer with private; procedure Initialize (Self : in out Lexer'Class; Text : League.String_Vectors.Universal_String_Vector); private type Lexer is limited new WebIDL.Parsers.Abstract_Lexer with record Vector : League.String_Vectors.Universal_String_Vector; Source : aliased WebIDL.String_Sources.String_Source; Scanner : aliased WebIDL.Scanners.Scanner; Handler : aliased WebIDL.Token_Handlers.Handler; end record; overriding procedure Next_Token (Self : in out Lexer; Value : out WebIDL.Tokens.Token); end WebIDL.Lexers;
with Types; use Types; package Commands is type Drive_Special is (Straight, CW, CCW); -- Command Constructors function Construct_Date_Time (D : Day; H : Hour; M : Minute) return Comm_Rec; function Construct_Drive_Special (Special : Drive_Special; V : Velocity) return Comm_Rec; end Commands;
-- Abstract : -- -- See spec. -- -- Copyright (C) 2018 - 2020 Free Software Foundation, Inc. -- -- This library is free software; you can redistribute it and/or modify it -- under terms of the GNU General Public License as published by the Free -- Software Foundation; either version 3, or (at your option) any later -- version. This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN- -- TABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- As a special exception under Section 7 of GPL version 3, you are granted -- additional permissions described in the GCC Runtime Library Exception, -- version 3.1, as published by the Free Software Foundation. pragma License (Modified_GPL); with Ada.Directories; with Ada.Real_Time; with Ada.Strings.Fixed; with Ada.Text_IO; package body WisiToken.Generate is function Error_Message (File_Name : in String; File_Line : in Line_Number_Type; Message : in String) return String is use Ada.Directories; use Ada.Strings.Fixed; use Ada.Strings; begin return Simple_Name (File_Name) & ":" & Trim (Line_Number_Type'Image (File_Line), Left) & ":0: " & Message; end Error_Message; procedure Put_Error (Message : in String) is begin Error := True; Ada.Text_IO.Put_Line (Ada.Text_IO.Standard_Error, Message); end Put_Error; procedure Check_Consistent (Grammar : in WisiToken.Productions.Prod_Arrays.Vector; Descriptor : in WisiToken.Descriptor; Source_File_Name : in String) is begin if Descriptor.Accept_ID /= Descriptor.First_Nonterminal then Put_Error (Error_Message (Source_File_Name, Line_Number_Type'First, "Descriptor.Accept_ID /= Descriptor.First_Nonterminal")); end if; if Grammar.First_Index /= Descriptor.First_Nonterminal then Put_Error (Error_Message (Source_File_Name, Line_Number_Type'First, "Grammar.First_Index /= Descriptor.First_Nonterminal")); end if; if Grammar.Last_Index /= Descriptor.Last_Nonterminal then Put_Error (Error_Message (Source_File_Name, Line_Number_Type'First, "Grammar.Last_Index /= Descriptor.Last_Nonterminal")); end if; for Nonterm in Descriptor.First_Nonterminal .. Descriptor.Last_Nonterminal loop if Grammar (Nonterm).LHS /= Nonterm then Put_Error (Error_Message (Source_File_Name, Line_Number_Type'First, "Grammar (" & Image (Nonterm, Descriptor) & ").LHS = " & Image (Grammar (Nonterm).LHS, Descriptor) & " /= " & Image (Nonterm, Descriptor))); end if; end loop; end Check_Consistent; function Check_Unused_Tokens (Descriptor : in WisiToken.Descriptor; Grammar : in WisiToken.Productions.Prod_Arrays.Vector) return Boolean is subtype Terminals is Token_ID range Descriptor.First_Terminal .. Descriptor.Last_Terminal; subtype Nonterminals is Token_ID range Descriptor.First_Nonterminal .. Descriptor.Last_Nonterminal; Used_Tokens : Token_ID_Set := (Descriptor.First_Terminal .. Descriptor.Last_Nonterminal => False); Changed : Boolean := False; Abort_Generate : Boolean := False; Unused_Tokens : Boolean := False; begin Used_Tokens (Descriptor.Accept_ID) := True; -- First mark all nonterminals that occur in used nonterminals as -- used. loop for Prod of Grammar loop if Used_Tokens (Prod.LHS) then for RHS of Prod.RHSs loop for J of RHS.Tokens loop if J in Nonterminals then Changed := Changed or else not Used_Tokens (J); Used_Tokens (J) := True; end if; end loop; end loop; end if; end loop; exit when not Changed; Changed := False; end loop; -- Now mark terminals used in used nonterminals for Prod of Grammar loop if Used_Tokens (Prod.LHS) then for RHS of Prod.RHSs loop for J of RHS.Tokens loop if not (J in Used_Tokens'Range) then WisiToken.Generate.Put_Error ("non-grammar token " & Image (J, Descriptor) & " used in grammar"); -- This causes lots of problems with token_id not in terminal or -- nonterminal range, so abort early. Abort_Generate := True; end if; if J in Terminals then Used_Tokens (J) := True; end if; end loop; end loop; end if; end loop; for I in Used_Tokens'Range loop if not Used_Tokens (I) then if not Unused_Tokens then WisiToken.Generate.Put_Error ("Unused tokens:"); Unused_Tokens := True; end if; WisiToken.Generate.Put_Error (Image (I, Descriptor)); end if; end loop; if Abort_Generate then raise Grammar_Error; end if; return Unused_Tokens; end Check_Unused_Tokens; function Nullable (Grammar : in WisiToken.Productions.Prod_Arrays.Vector) return Token_Array_Production_ID is use all type Ada.Containers.Count_Type; subtype Nonterminal is Token_ID range Grammar.First_Index .. Grammar.Last_Index; Result : Token_Array_Production_ID := (Nonterminal => Invalid_Production_ID); Changed : Boolean := True; begin loop exit when not Changed; Changed := False; for Prod of Grammar loop if Result (Prod.LHS) = Invalid_Production_ID then for RHS_Index in Prod.RHSs.First_Index .. Prod.RHSs.Last_Index loop declare RHS : WisiToken.Productions.Right_Hand_Side renames Prod.RHSs (RHS_Index); begin if RHS.Tokens.Length = 0 or else (RHS.Tokens (1) in Nonterminal and then Result (RHS.Tokens (1)) /= Invalid_Production_ID) then Result (Prod.LHS) := (Prod.LHS, RHS_Index); Changed := True; end if; end; end loop; end if; end loop; end loop; return Result; end Nullable; function Has_Empty_Production (Nullable : in Token_Array_Production_ID) return Token_ID_Set is begin return Result : Token_ID_Set := (Nullable'First .. Nullable'Last => False) do for I in Result'Range loop Result (I) := Nullable (I) /= Invalid_Production_ID; end loop; end return; end Has_Empty_Production; function Has_Empty_Production (Grammar : in WisiToken.Productions.Prod_Arrays.Vector) return Token_ID_Set is use all type Ada.Containers.Count_Type; subtype Nonterminal is Token_ID range Grammar.First_Index .. Grammar.Last_Index; Result : Token_ID_Set := (Nonterminal => False); Changed : Boolean := True; begin loop exit when not Changed; Changed := False; for Prod of Grammar loop for RHS of Prod.RHSs loop if (RHS.Tokens.Length = 0 or else (RHS.Tokens (1) in Nonterminal and then Result (RHS.Tokens (1)))) and not Result (Prod.LHS) then Result (Prod.LHS) := True; Changed := True; end if; end loop; end loop; end loop; return Result; end Has_Empty_Production; function First (Grammar : in WisiToken.Productions.Prod_Arrays.Vector; Has_Empty_Production : in Token_ID_Set; First_Terminal : in Token_ID; Non_Terminal : in Token_ID) return Token_ID_Set is Search_Tokens : Token_ID_Set := (Grammar.First_Index .. Grammar.Last_Index => False); begin Search_Tokens (Non_Terminal) := True; return Derivations : Token_ID_Set := (First_Terminal .. Grammar.Last_Index => False) do while Any (Search_Tokens) loop declare Added_Tokens : Token_ID_Set := (First_Terminal .. Grammar.Last_Index => False); Added_Nonterms : Token_ID_Set := (Grammar.First_Index .. Grammar.Last_Index => False); begin for Prod of Grammar loop if Search_Tokens (Prod.LHS) then for RHS of Prod.RHSs loop for Derived_Token of RHS.Tokens loop if not Derivations (Derived_Token) then Added_Tokens (Derived_Token) := True; if Derived_Token in Added_Nonterms'Range then Added_Nonterms (Derived_Token) := True; end if; end if; if Derived_Token in Has_Empty_Production'Range and then Has_Empty_Production (Derived_Token) then null; else exit; end if; end loop; end loop; end if; end loop; Derivations := Derivations or Added_Tokens; Search_Tokens := Added_Nonterms; end; end loop; end return; end First; function First (Grammar : in WisiToken.Productions.Prod_Arrays.Vector; Has_Empty_Production : in Token_ID_Set; First_Terminal : in Token_ID) return Token_Array_Token_Set is Matrix : Token_Array_Token_Set := (Grammar.First_Index .. Grammar.Last_Index => (First_Terminal .. Grammar.Last_Index => False)); procedure Set_Slice (Matrix : in out Token_Array_Token_Set; I : Token_ID; Value : in Token_ID_Set) is begin for J in Matrix'Range (2) loop Matrix (I, J) := Value (J); end loop; end Set_Slice; begin for NT_Index in Matrix'Range loop Set_Slice (Matrix, NT_Index, First (Grammar, Has_Empty_Production, First_Terminal, NT_Index)); end loop; return Matrix; end First; function To_Terminal_Sequence_Array (First : in Token_Array_Token_Set; Descriptor : in WisiToken.Descriptor) return Token_Sequence_Arrays.Vector is subtype Terminal is Token_ID range Descriptor.First_Terminal .. Descriptor.Last_Terminal; begin return Result : Token_Sequence_Arrays.Vector do Result.Set_First_Last (First'First (1), First'Last (1)); for I in First'Range (1) loop declare Row : Token_ID_Arrays.Vector renames Result (I); begin for J in First'Range (2) loop if First (I, J) and then J in Terminal then Row.Append (J); end if; end loop; end; end loop; end return; end To_Terminal_Sequence_Array; function Follow (Grammar : in WisiToken.Productions.Prod_Arrays.Vector; Descriptor : in WisiToken.Descriptor; First : in Token_Array_Token_Set; Has_Empty_Production : in Token_ID_Set) return Token_Array_Token_Set is subtype Terminal is Token_ID range Descriptor.First_Terminal .. Descriptor.Last_Terminal; subtype Nonterminal is Token_ID range Descriptor.First_Nonterminal .. Descriptor.Last_Nonterminal; Prev_Result : Token_Array_Token_Set := (Nonterminal => (Terminal => False)); Result : Token_Array_Token_Set := (Nonterminal => (Terminal => False)); ID : Token_ID; begin -- [dragon] pgp 189: -- -- Rule 1 Follow (S, EOF) = True; EOF is explicit in the -- start symbol production, so this is covered by Rule 2. -- -- Rule 2: If A => alpha B Beta, add First (Beta) to Follow (B) -- -- Rule 3; if A => alpha B, or A -> alpha B Beta and Beta -- can be null, add Follow (A) to Follow (B) -- -- We don't assume any order in the productions list, so we -- have to keep applying rule 3 until nothing changes. for B in Nonterminal loop for Prod of Grammar loop for A of Prod.RHSs loop for I in A.Tokens.First_Index .. A.Tokens.Last_Index loop if A.Tokens (I) = B then if I < A.Tokens.Last_Index then -- Rule 1 ID := A.Tokens (1 + I); if ID in Terminal then Result (B, ID) := True; else Or_Slice (Result, B, Slice (First, ID)); end if; end if; end if; end loop; end loop; end loop; end loop; Prev_Result := Result; loop for B in Nonterminal loop for Prod of Grammar loop for A of Prod.RHSs loop for I in A.Tokens.First_Index .. A.Tokens.Last_Index loop if A.Tokens (I) = B then if I = A.Tokens.Last_Index or else (A.Tokens (1 + I) in Nonterminal and then Has_Empty_Production (A.Tokens (1 + I))) then -- rule 3 Or_Slice (Result, B, Slice (Result, Prod.LHS)); end if; end if; end loop; end loop; end loop; end loop; exit when Prev_Result = Result; Prev_Result := Result; end loop; return Result; end Follow; function To_Graph (Grammar : in WisiToken.Productions.Prod_Arrays.Vector) return Grammar_Graphs.Graph is subtype Nonterminals is Token_ID range Grammar.First_Index .. Grammar.Last_Index; Graph : Grammar_Graphs.Graph; J : Integer := 1; begin if Trace_Generate_Minimal_Complete > Outline then Ada.Text_IO.Put_Line ("grammar graph:"); end if; for LHS in Grammar.First_Index .. Grammar.Last_Index loop declare Prod : WisiToken.Productions.Instance renames Grammar (LHS); begin for RHS in Prod.RHSs.First_Index .. Prod.RHSs.Last_Index loop declare Tokens : Token_ID_Arrays.Vector renames Prod.RHSs (RHS).Tokens; begin for I in Tokens.First_Index .. Tokens.Last_Index loop if Tokens (I) in Nonterminals then if Trace_Generate_Minimal_Complete > Detail then Ada.Text_IO.Put_Line ("(" & Trimmed_Image (LHS) & ", " & Trimmed_Image (Tokens (I)) & "," & J'Image & ")"); J := J + 1; end if; Graph.Add_Edge (LHS, Tokens (I), (RHS, I)); end if; end loop; end; end loop; end; end loop; if Trace_Generate_Minimal_Complete > Outline then Ada.Text_IO.Put_Line ("..." & Graph.Count_Nodes'Image & " nodes" & Graph.Count_Edges'Image & " edges."); end if; return Graph; end To_Graph; function Recursion (LHS : in Token_ID; Token_Index : in Positive; Tokens : in Token_ID_Arrays.Vector) return Recursion_Class is begin return (if Token_Index = Tokens.First_Index then (if LHS = Tokens (Tokens.First_Index) then Direct_Left else Other_Left) elsif Token_Index = Tokens.Last_Index then (if LHS = Tokens (Tokens.Last_Index) then Direct_Right else Other_Right) else Other); end Recursion; procedure Set_Grammar_Recursions (Recursions : in WisiToken.Generate.Recursions; Grammar : in out WisiToken.Productions.Prod_Arrays.Vector) is begin for LHS of Grammar loop for RHS of LHS.RHSs loop RHS.Recursion.Set_First_Last (RHS.Tokens.First_Index, RHS.Tokens.Last_Index); end loop; end loop; for Path of Recursions.Recursions loop declare use WisiToken.Productions; Previous_Item_LHS : Token_ID := (if Recursions.Full then Path (Path'Last).Vertex else Token_ID'Last); begin for Item of Path loop for Edge of Item.Edges loop declare LHS : constant Token_ID := (if Recursions.Full then Previous_Item_LHS else Item.Vertex); RHS : Right_Hand_Side renames Grammar (LHS).RHSs (Edge.Data.RHS); begin RHS.Recursion (Edge.Data.Token_Index) := Recursion (LHS => LHS, Token_Index => Edge.Data.Token_Index, Tokens => RHS.Tokens); end; end loop; Previous_Item_LHS := Item.Vertex; end loop; end; end loop; end Set_Grammar_Recursions; function Compute_Full_Recursion (Grammar : in out WisiToken.Productions.Prod_Arrays.Vector; Descriptor : in WisiToken.Descriptor) return Recursions is Time_Start : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; Graph : constant Grammar_Graphs.Graph := To_Graph (Grammar); begin return Result : Recursions := (Full => True, Recursions => Graph.Find_Cycles) do Grammar_Graphs.Sort_Paths.Sort (Result.Recursions); Set_Grammar_Recursions (Result, Grammar); if Trace_Time then declare use Ada.Real_Time; Time_End : constant Time := Clock; begin Ada.Text_IO.Put_Line (Ada.Text_IO.Standard_Error, "compute partial recursion time:" & Duration'Image (To_Duration (Time_End - Time_Start))); end; end if; if Trace_Generate_Minimal_Complete > Extra then Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line ("Productions:"); WisiToken.Productions.Put (Grammar, Descriptor); Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line ("full recursions:"); for I in Result.Recursions.First_Index .. Result.Recursions.Last_Index loop Ada.Text_IO.Put_Line (Trimmed_Image (I) & " => " & Grammar_Graphs.Image (Result.Recursions (I))); end loop; end if; end return; end Compute_Full_Recursion; function Compute_Partial_Recursion (Grammar : in out WisiToken.Productions.Prod_Arrays.Vector; Descriptor : in WisiToken.Descriptor) return Recursions is use Grammar_Graphs; Time_Start : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; Graph : constant Grammar_Graphs.Graph := To_Graph (Grammar); Components : constant Component_Lists.List := Strongly_Connected_Components (To_Adjancency (Graph), Non_Trivial_Only => True); Loops : constant Vertex_Lists.List := Graph.Loops; begin return Result : Recursions do Result.Full := False; for Comp of Components loop declare Path : Recursion_Cycle (1 .. Integer (Comp.Length)); Last : Integer := Path'First - 1; begin for V of Comp loop Last := Last + 1; Path (Last) := (V, Graph.Edges (V)); end loop; Result.Recursions.Append (Path); end; end loop; declare Path : Recursion_Cycle (1 .. Integer (Loops.Length)); Last : Integer := Path'First - 1; begin for V of Loops loop Last := Last + 1; Path (Last) := (V, Graph.Edges (V)); end loop; Result.Recursions.Append (Path); end; Set_Grammar_Recursions (Result, Grammar); if Trace_Time then declare use Ada.Real_Time; Time_End : constant Time := Clock; begin Ada.Text_IO.Put_Line (Ada.Text_IO.Standard_Error, "compute full recursion time:" & Duration'Image (To_Duration (Time_End - Time_Start))); end; end if; if Trace_Generate_Minimal_Complete > Extra then Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line ("Productions:"); WisiToken.Productions.Put (Grammar, Descriptor); Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line ("partial recursions:"); for I in Result.Recursions.First_Index .. Result.Recursions.Last_Index loop Ada.Text_IO.Put_Line (Trimmed_Image (I) & " => " & Grammar_Graphs.Image (Result.Recursions (I))); end loop; end if; end return; end Compute_Partial_Recursion; ---------- -- Indented text output procedure Indent_Line (Text : in String) is use Ada.Text_IO; begin Set_Col (Indent); Put_Line (Text); Line_Count := Line_Count + 1; end Indent_Line; procedure Indent_Start (Text : in String) is use Ada.Text_IO; begin Set_Col (Indent); Put (Text); end Indent_Start; procedure Indent_Wrap (Text : in String) is use all type Ada.Text_IO.Count; use Ada.Strings; use Ada.Strings.Fixed; I : Natural; First : Integer := Text'First; begin if Text'Length + Indent <= Max_Line_Length then Indent_Line (Text); else loop I := Text'Last; loop I := Index (Text (First .. Text'Last), " ", From => I, Going => Backward); exit when I - First + Integer (Indent) <= Max_Line_Length; I := I - 1; end loop; Indent_Line (Trim (Text (First .. I - 1), Right)); First := I + 1; exit when Text'Last - First + Integer (Indent) <= Max_Line_Length; end loop; Indent_Line (Text (First .. Text'Last)); end if; end Indent_Wrap; procedure Indent_Wrap_Comment (Text : in String; Comment_Syntax : in String) is use all type Ada.Text_IO.Count; use Ada.Strings; use Ada.Strings.Fixed; Prefix : constant String := Comment_Syntax & " "; I : Natural; First : Integer := Text'First; begin if Text'Length + Indent <= Max_Line_Length - 4 then Indent_Line (Prefix & Text); else loop I := Text'Last; loop I := Index (Text (First .. Text'Last), " ", From => I, Going => Backward); exit when I - First + Integer (Indent) <= Max_Line_Length - 4; I := I - 1; end loop; Indent_Line (Prefix & Text (First .. I - 1)); First := I + 1; exit when Text'Last - First + Integer (Indent) <= Max_Line_Length - 4; end loop; Indent_Line (Prefix & Text (First .. Text'Last)); end if; end Indent_Wrap_Comment; end WisiToken.Generate;
with Ada.Containers.Vectors; generic type Element_Type is private; type Element_Array is array (Positive range <>) of Element_Type; package Readable_Sequences.Generic_Sequences is type Sequence is tagged private; Empty_Sequence : constant Sequence; type Cursor is private; Beginning : constant Cursor; function Create (Init : Element_Array) return Sequence; function Create (End_Of_Sequence_Marker : Element_Type) return Sequence; function Create (Init : Element_Array; End_Of_Sequence_Marker : Element_Type) return Sequence; function Has_End_Of_Sequence_Marker (Item : Sequence) return Boolean; function Dump (Seq : Sequence; From : Cursor := Beginning) return Element_Array; procedure Clear (Seq : in out Sequence) with Post => Seq.Length = 0 and not Seq.Saved_Position and Seq.Current_Position = Beginning; function Index (Seq : Sequence) return Positive; procedure Append (Seq : in out Sequence; Elements : Element_Array) with Post => Seq.Length = Seq.Length'Old + Elements'Length; procedure Append (To : in out Sequence; What : Element_Type) with Post => To.Length = To.Length'Old + 1; procedure Append (To : in out Sequence; What : Sequence) with Post => To.Length = To.Length'Old + What.Length; procedure Rewind (Seq : in out Sequence; To : Cursor := Beginning); function Length (Seq : Sequence) return Natural; function Remaining (Seq : Sequence) return Natural with Post => Remaining'Result <= Seq.Length; -- Return the number of elements that still need to be read from -- Seq. This includes also the current element function Current_Position (Seq : Sequence) return Cursor; procedure Set_Position (Seq : in out Sequence; Pos : Cursor); function Saved_Position (Seq : Sequence)return Boolean; procedure Save_Position (Seq : in out Sequence) with Pre => not Seq.Saved_Position, Post => Seq.Saved_Position; procedure Restore_Position (Seq : in out Sequence) with Pre => Seq.Saved_Position, Post => not Seq.Saved_Position; procedure Clear_Position (Seq : in out Sequence) with Pre => Seq.Saved_Position, Post => not Seq.Saved_Position; function End_Of_Sequence (Seq : Sequence) return Boolean is (Seq.Remaining = 0); function Read (Seq : Sequence; Ahead : Natural := 0) return Element_Type with Pre => Seq.Has_End_Of_Sequence_Marker or Seq.Remaining > Ahead; function Next (Seq : in out Sequence) return Element_Type; procedure Next (Seq : in out Sequence; Step : Positive := 1) with Post => Seq.Remaining = Integer'Max (Seq.Remaining'Old - Step, 0); procedure Back (Seq : in out Sequence; Step : Positive := 1) with Post => Seq.Remaining = Integer'Min (Seq.Remaining'Old + Step, Seq.Length); procedure Process (Seq : Sequence; Callback : access procedure (Item : Element_Type)); Beyond_End : exception; private type Cursor is range 1 .. Integer'Last; Beginning : constant Cursor := Cursor'First; package Element_Vectors is new Ada.Containers.Vectors (Index_Type => Cursor, Element_Type => Element_Type); type Sequence is tagged record Vector : Element_Vectors.Vector := Element_Vectors.Empty_Vector; Position : Cursor := Beginning; Old_Position : Cursor; Position_Saved : Boolean := False; Has_End_Marker : Boolean := False; End_Marker : Element_Type; end record; function Saved_Position (Seq : Sequence)return Boolean is (Seq.Position_Saved); function Current_Position (Seq : Sequence) return Cursor is (Seq.Position); function Length (Seq : Sequence) return Natural is (Natural (Seq.Vector.Length)); function Remaining (Seq : Sequence) return Natural is (Integer (Seq.Vector.Last_Index) - Integer (Seq.Position) + 1); function Read (Seq : Sequence; Ahead : Natural := 0) return Element_Type is (if Seq.Remaining > Ahead then Seq.Vector (Cursor (Integer (Seq.Position) + Ahead)) elsif Seq.Has_End_Marker then Seq.End_Marker else raise Beyond_End); function Has_End_Of_Sequence_Marker (Item : Sequence) return Boolean is (Item.Has_End_Marker); Empty_Sequence : constant Sequence := Sequence'(Vector => Element_Vectors.Empty_Vector, Position => Cursor'First, Old_Position => <>, Position_Saved => False, Has_End_Marker => False, End_Marker => <>); function Index (Seq : Sequence) return Positive is (Positive (Seq.Position)); end Readable_Sequences.Generic_Sequences;
pragma License (Unrestricted); -- Ada 2012 package Ada.Locales is pragma Preelaborate; pragma Remote_Types; -- extended from here -- These are language code defined by ISO 639-1/2. -- Ada RM requires alpha-3 in spite of that -- almost all the operating systems use alpha-2. type ISO_639_Alpha_2 is new String (1 .. 2); -- with Dynamic_Predicate => -- [gcc-4.8] rejects -- (for all E of ISO_639_Alpha_2 => E in 'a' .. 'z'); type ISO_639_Alpha_3 is new String (1 .. 3); -- with Dynamic_Predicate => -- [gcc-4.8] rejects -- (for all E of ISO_639_Alpha_3 => E in 'a' .. 'z'); ISO_639_Alpha_2_Unknown : constant ISO_639_Alpha_2 := "un"; -- ??? ISO_639_Alpha_3_Unknown : constant ISO_639_Alpha_3 := "und"; function To_Alpha_2 (Item : ISO_639_Alpha_3) return ISO_639_Alpha_2; function To_Alpha_3 (Item : ISO_639_Alpha_2) return ISO_639_Alpha_3; function Language return ISO_639_Alpha_2; function Language return ISO_639_Alpha_3; -- Language_Code pragma Inline (Language); -- renamed -- extended from here -- These are country code defined by ISO 3166-1. type ISO_3166_1_Alpha_2 is new String (1 .. 2); -- with Dynamic_Predicate => -- [gcc-4.8] rejects -- (for all E of ISO_3166_1_Alpha_2 => E in 'A' .. 'Z'); ISO_3166_1_Alpha_2_Unknown : constant ISO_3166_1_Alpha_2 := "ZZ"; function Country return ISO_3166_1_Alpha_2; -- Country_Code pragma Inline (Country); -- renamed -- modified -- type Language_Code is new String (1 .. 3) -- with Dynamic_Predicate => -- (for all E of Language_Code => E in 'a' .. 'z'); -- AI12-0037-1 subtype Language_Code is ISO_639_Alpha_3; -- modified -- type Country_Code is new String (1 .. 2) -- with Dynamic_Predicate => -- (for all E of Country_Code => E in 'A' .. 'Z'); -- AI12-0037-1 subtype Country_Code is ISO_3166_1_Alpha_2; -- Language_Unknown : constant Language_Code := "und"; Language_Unknown : Language_Code renames ISO_639_Alpha_3_Unknown; -- Country_Unknown : constant Country_Code := "ZZ"; Country_Unknown : Country_Code renames ISO_3166_1_Alpha_2_Unknown; -- function Language return Language_Code; -- function Country return Country_Code; end Ada.Locales;
-- part of OpenGLAda, (c) 2017 Felix Krause -- released under the terms of the MIT license, see the file "COPYING" with GL.Pixels; with GL.Low_Level.Enums; package GL.Objects.Renderbuffers is pragma Preelaborate; type Renderbuffer_Target (<>) is tagged limited private; procedure Allocate (Object : Renderbuffer_Target; Format : Pixels.Internal_Format; Width, Height : Size; Samples : Size := 0); function Width (Object : Renderbuffer_Target) return Size; function Height (Object : Renderbuffer_Target) return Size; function Internal_Format (Object : Renderbuffer_Target) return Pixels.Internal_Format; function Red_Size (Object : Renderbuffer_Target) return Size; function Green_Size (Object : Renderbuffer_Target) return Size; function Blue_Size (Object : Renderbuffer_Target) return Size; function Alpha_Size (Object : Renderbuffer_Target) return Size; function Depth_Size (Object : Renderbuffer_Target) return Size; function Stencil_Size (Object : Renderbuffer_Target) return Size; function Raw_Kind (Object : Renderbuffer_Target) return Low_Level.Enums.Renderbuffer_Kind; Active_Renderbuffer : constant Renderbuffer_Target; type Renderbuffer is new GL_Object with private; procedure Bind (Target : Renderbuffer_Target; Object : Renderbuffer'Class); function Current (Target : Renderbuffer_Target) return Renderbuffer'Class; No_Renderbuffer : constant Renderbuffer; private type Renderbuffer is new GL_Object with null record; overriding procedure Internal_Create_Id (Object : Renderbuffer; Id : out UInt); overriding procedure Internal_Release_Id (Object : Renderbuffer; Id : UInt); type Renderbuffer_Target (Kind : Low_Level.Enums.Renderbuffer_Kind) is tagged limited null record; Active_Renderbuffer : constant Renderbuffer_Target := Renderbuffer_Target'(Kind => Low_Level.Enums.Renderbuffer); No_Renderbuffer : constant Renderbuffer := Renderbuffer'(Ada.Finalization.Controlled with Reference => Reference_To_Null_Object'Access); end GL.Objects.Renderbuffers;
package body Task_With_Body is task body The_Task_Type is begin null; end The_Task_Type; end Task_With_Body;
with Ada.Text_IO; use Ada.Text_IO; procedure Loop_Continue is begin for I in 1..10 loop Put (Integer'Image(I)); if I = 5 or I = 10 then New_Line; goto Continue; end if; Put (","); <<Continue>> --Ada 2012 no longer requires a statement after the label end loop; end Loop_Continue;
-- see http://gcc.gnu.org/onlinedocs/gcc/AVR-Built_002din-Functions.html with Interfaces; package System.GCC_Builtins is pragma Pure; subtype U8 is Interfaces.Unsigned_8; subtype I8 is Interfaces.Integer_8; subtype U16 is Interfaces.Unsigned_16; subtype I16 is Interfaces.Integer_16; subtype U32 is Interfaces.Unsigned_32; subtype U64 is Interfaces.Unsigned_64; procedure nop; procedure sei; procedure cli; procedure sleep; procedure wdr; function swap (B : U8) return U8; function fmul (Left, Right : U8) return U16; function fmuls (Left, Right : I8) return I16; function fmulsu (Left : I8; Right : U8) return I16; procedure delay_cycles (Ticks : U32); function map8 (map : U32; val : U8) return U8; function map16 (map : U64; val : U16) return U16; private pragma Inline_Always (nop); pragma Inline_Always (sei); pragma Inline_Always (cli); pragma Inline_Always (sleep); pragma Inline_Always (wdr); pragma Inline_Always (swap); pragma Import (Intrinsic, nop, "__builtin_avr_nop"); pragma Import (Intrinsic, sei, "__builtin_avr_sei"); pragma Import (Intrinsic, cli, "__builtin_avr_cli"); pragma Import (Intrinsic, sleep, "__builtin_avr_sleep"); pragma Import (Intrinsic, wdr, "__builtin_avr_wdr"); pragma Import (Intrinsic, swap, "__builtin_avr_swap"); pragma Import (Intrinsic, fmul, "__builtin_avr_fmul"); pragma Import (Intrinsic, fmuls, "__builtin_avr_fmuls"); pragma Import (Intrinsic, fmulsu, "__builtin_avr_fmulsu"); pragma Import (Intrinsic, delay_cycles, "__builtin_avr_delay_cycles"); pragma Import (Intrinsic, map8, "__builtin_avr_map8"); pragma Import (Intrinsic, map16, "__builtin_avr_map16"); end System.GCC_Builtins;
with Interfaces; with Ada.Numerics.Float_Random; use Interfaces; generic type T is private; with function "+" (L, R : T) return T is <>; with function "-" (L, R : T) return T is <>; with function "*" (L, R : T) return T is <>; with function "/" (L, R : T) return T is <>; with function ">" (L, R : T) return Boolean is <>; with function "<" (L, R : T) return Boolean is <>; with function ">=" (L, R : T) return Boolean is <>; with function "<=" (L, R : T) return Boolean is <>; --with function ":="(E2 : float) return T is <>; --with procedure assign(E1 : T; E2 : flost) is <>; package Generic_Vector_Math is function min(a, b : T) return T; function max(a, b : T) return T; function min(a, b, c : T) return T; function max(a, b, c : T) return T; function sqr(x : T) return T; type vector2 is record x, y : T; end record; type vector3 is record x, y, z : T; end record; type vector4 is record x, y, z, w : T; end record; function "+"(a, b : vector4) return vector4; function "+"(a, b : vector3) return vector3; function "*"(a, b : vector3) return vector3; function "-"(a, b : vector3) return vector3; function "*"(a : vector3; k: T) return vector3; function "*"(k: T; a : vector3) return vector3; function dot(a, b : vector3) return T; function cross(a, b : vector3) return vector3; function min(a, b : vector3) return vector3; function max(a, b : vector3) return vector3; function clamp(x : vector3; a,b : T) return vector3; function clamp(x,a,b : vector3) return vector3; function clamp(x,a,b : T) return T; type Matrix4 is array (0..3, 0..3) of T; function "*"(v : vector3; m : Matrix4) return vector3; function "*"(v : vector4; m : Matrix4) return vector4; function "*"(m : Matrix4; v : vector3) return vector3; function "*"(m : Matrix4; v : vector4) return vector4; function "*"(m1 : Matrix4; m2 : Matrix4) return Matrix4; function GetRow(m : Matrix4; i : integer) return vector4; function GetCol(m : Matrix4; i : integer) return vector4; procedure SetRow(m : in out Matrix4; i : in integer; v : in vector4); procedure SetCol(m : in out Matrix4; i : in integer; v : in vector4); pragma Inline ("+"); pragma Inline ("*"); pragma Inline ("-"); pragma Inline (dot); pragma Inline (min); pragma Inline (max); pragma Inline (sqr); pragma Inline (clamp); end Generic_Vector_Math;
-- Copyright (c) 2021 Devin Hill -- zlib License -- see LICENSE for details. with System.Parameters; with System.Storage_Elements; with System.Allocation.Arenas; package System.Secondary_Stack is package SP renames System.Parameters; package SSE renames System.Storage_Elements; package SAA renames System.Allocation.Arenas; -- This package provides the interface GNAT requires -- to allocate items on the secondary stack. GNAT will allocate -- the stack for us, but we re-use the local arena allocator -- interface which other memory pools use. subtype SS_Stack is SAA.Local_Arena; type SS_Stack_Ptr is access all SS_Stack; procedure SS_Allocate (Addr : out System.Address; Storage_Size : SSE.Storage_Count) with Inline; -- Allocate enough space for a Storage_Size bytes object with Maximum -- alignment. The address of the allocated space is returned in Addr. subtype Mark_Id is SAA.Marker; -- Type used to mark the stack for mark/release processing. function SS_Mark return SAA.Marker with Inline; -- Return the Mark corresponding to the current state of the stack procedure SS_Release (M : SAA.Marker) with Inline; -- Restore the state of the stack corresponding to the mark M function Get_Sec_Stack return SS_Stack_Ptr with Pure_Function, Inline; -- Get the pointer to the secondary stack data. -- Even though we know where it is statically, for some reason -- GNAT requires us to define this function by name. private -- GNATbind will allocate an array of SS_Stack for us. -- Here, we export the values which it writes to so we can access -- the stacks at runtime to initialize them. We can see how to do -- so based on the generated b__<program>.adb files. Binder_Sec_Stacks_Count : Natural with Export, External_Name => "__gnat_binder_ss_count"; -- The number of default sized secondary stacks allocated by the binder. Default_Secondary_Stack_Size : SP.Size_Type with Export, External_Name => "__gnat_default_ss_size"; -- The size of the secondary stack (used for the discriminant) Default_Sized_SS_Pool : System.Address with Export, External_Name => "__gnat_default_ss_pool"; -- The address of the array of stacks which GNAT generates. -- If secondary stacks are used at all, it will properly -- initialize this variable and everything will work out. SS_Pool : Integer; -- Empirically GNAT requires this variable for some reason. -- It must be present or else it won't allow secondary stack use. end System.Secondary_Stack;
-- Copyright (C)2021,2022 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 Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with GNAT.Sockets; use GNAT.Sockets; package Telnet is Cmd_SE : constant Character := Character'Val(240); Cmd_NOP : constant Character := Character'Val(241); Cmd_DM : constant Character := Character'Val(242); Cmd_BRK : constant Character := Character'Val(243); Cmd_IP : constant Character := Character'Val(244); Cmd_AO : constant Character := Character'Val(245); Cmd_AYT : constant Character := Character'Val(246); Cmd_EC : constant Character := Character'Val(247); Cmd_EL : constant Character := Character'Val(248); Cmd_GA : constant Character := Character'Val(249); Cmd_SB : constant Character := Character'Val(250); Cmd_WILL : constant Character := Character'Val(251); Cmd_WONT : constant Character := Character'Val(252); Cmd_DO : constant Character := Character'Val(253); Cmd_DONT : constant Character := Character'Val(254); Cmd_IAC : constant Character := Character'Val(255); type Message is new String; type Session_T is tagged record Conn : GNAT.Sockets.Socket_Type; Host_Str : Unbounded_String; -- The host as specified by our user Port_Num : Integer; -- The port as specified by our user end record; type Session_Acc_T is access all Session_T; function New_Connection (Host_Str : in String; Port_Num : in Integer) return Session_Acc_T; -- Attempt to initiate a new TCPIP/Telnet connection to the specified Host and Port. -- Data from the remote host will be directed to the supplied Terminal. -- To send data, call the Send procedure procedure Send (Sess : in Session_Acc_T; Str : in String); procedure Close_Connection (Sess : in out Session_T); task type Receiver is entry Start (Sess : in Session_Acc_T); end Receiver; type Receiver_Acc is access Receiver; Receiver_Task : Receiver_Acc; task type Keyboard_Sender is entry Start (S : in Session_Acc_T); entry Accept_Data (Str : in String); entry Stop; end Keyboard_Sender; type Sender_Acc is access Keyboard_Sender; Keyboard_Sender_Task : Sender_Acc; Disconnected : exception; end Telnet;
-- Copyright (c) 2019 Maxim Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- with Program.Compilation_Unit_Vectors; with Program.Contexts; with Program.Source_Buffers; with Program.Symbols; with Program.Visibility; private with Ada.Containers.Hashed_Maps; private with Ada.Containers.Vectors; private with Program.Compilation_Units; private with Program.Compilations; private with Program.Symbols.Tables; package Program.Plain_Contexts is pragma Preelaborate; type Context is limited new Program.Contexts.Context with private; procedure Initialize (Self : in out Context'Class); procedure Find_Or_Create_Symbol (Self : in out Context'Class; Buffer : not null Program.Source_Buffers.Source_Buffer_Access; Span : Program.Source_Buffers.Span; Result : out Program.Symbols.Symbol); function Find (Self : Context'Class; Value : Program.Text) return Program.Symbols.Symbol; procedure Parse_File (Self : aliased in out Context'Class; Text_Name : Text; Env : aliased in out Program.Visibility.Context); overriding function Library_Unit_Declarations (Self : Context) return Program.Compilation_Unit_Vectors.Compilation_Unit_Vector_Access; overriding function Compilation_Unit_Bodies (Self : Context) return Program.Compilation_Unit_Vectors.Compilation_Unit_Vector_Access; private type Symbol_List_Index is range 0 .. Integer'Last; function Hash (Value : Symbol_List_Index) return Ada.Containers.Hash_Type is (Ada.Containers.Hash_Type'Mod (Value)); type Symbol_List_Item is record Prefix : Symbol_List_Index; Symbol : Program.Symbols.Symbol; end record; function Hash (Value : Symbol_List_Item) return Ada.Containers.Hash_Type; package Symbol_List_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Symbol_List_Item, Element_Type => Symbol_List_Index, Hash => Hash, Equivalent_Keys => "="); package Unit_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Symbol_List_Index, Element_Type => Program.Compilation_Units.Compilation_Unit_Access, Hash => Hash, Equivalent_Keys => "=", "=" => Program.Compilation_Units."="); package Unit_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Program.Compilation_Units.Compilation_Unit_Access, "=" => Program.Compilation_Units."="); type Unit_Vector (Context : access Program.Plain_Contexts.Context) is limited new Program.Compilation_Unit_Vectors.Compilation_Unit_Vector with record Map : Unit_Maps.Map; List : Unit_Vectors.Vector; end record; overriding function Get_Length (Self : Unit_Vector) return Positive; overriding function Element (Self : Unit_Vector; Index : Positive) return not null Program.Compilation_Units.Compilation_Unit_Access; overriding function Find_Unit (Self : Unit_Vector; Name : Text) return Program.Compilation_Units.Compilation_Unit_Access; package Compilation_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Program.Compilations.Compilation_Access, "=" => Program.Compilations."="); type Context is limited new Program.Contexts.Context with record Symbols : Program.Symbols.Tables.Symbol_Table; Symbol_Lists : Symbol_List_Maps.Map; Declarations : aliased Unit_Vector (Context'Unchecked_Access); Bodies : aliased Unit_Vector (Context'Unchecked_Access); Compilations : Compilation_Vectors.Vector; end record; end Program.Plain_Contexts;
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Ada Modeling Framework -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2012, Vadim Godunko <vgodunko@gmail.com> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ -- This file is generated, don't edit it. ------------------------------------------------------------------------------ with AMF.DC; with AMF.DG.Fills; with AMF.Elements; with AMF.Internals.Helpers; with AMF.Internals.Tables.DD_Attributes; with AMF.Real_Collections; with AMF.Visitors.DG_Iterators; with AMF.Visitors.DG_Visitors; with League.Strings.Internals; with Matreshka.Internals.Strings; package body AMF.Internals.DG_Styles is -------------- -- Get_Fill -- -------------- overriding function Get_Fill (Self : not null access constant DG_Style_Proxy) return AMF.DG.Fills.DG_Fill_Access is begin return AMF.DG.Fills.DG_Fill_Access (AMF.Internals.Helpers.To_Element (AMF.Internals.Tables.DD_Attributes.Internal_Get_Fill (Self.Element))); end Get_Fill; -------------- -- Set_Fill -- -------------- overriding procedure Set_Fill (Self : not null access DG_Style_Proxy; To : AMF.DG.Fills.DG_Fill_Access) is begin AMF.Internals.Tables.DD_Attributes.Internal_Set_Fill (Self.Element, AMF.Internals.Helpers.To_Element (AMF.Elements.Element_Access (To))); end Set_Fill; -------------------- -- Get_Fill_Color -- -------------------- overriding function Get_Fill_Color (Self : not null access constant DG_Style_Proxy) return AMF.DC.Optional_DC_Color is begin return AMF.Internals.Tables.DD_Attributes.Internal_Get_Fill_Color (Self.Element); end Get_Fill_Color; -------------------- -- Set_Fill_Color -- -------------------- overriding procedure Set_Fill_Color (Self : not null access DG_Style_Proxy; To : AMF.DC.Optional_DC_Color) is begin AMF.Internals.Tables.DD_Attributes.Internal_Set_Fill_Color (Self.Element, To); end Set_Fill_Color; ---------------------- -- Get_Fill_Opacity -- ---------------------- overriding function Get_Fill_Opacity (Self : not null access constant DG_Style_Proxy) return AMF.Optional_Real is begin return AMF.Internals.Tables.DD_Attributes.Internal_Get_Fill_Opacity (Self.Element); end Get_Fill_Opacity; ---------------------- -- Set_Fill_Opacity -- ---------------------- overriding procedure Set_Fill_Opacity (Self : not null access DG_Style_Proxy; To : AMF.Optional_Real) is begin AMF.Internals.Tables.DD_Attributes.Internal_Set_Fill_Opacity (Self.Element, To); end Set_Fill_Opacity; ---------------------- -- Get_Stroke_Width -- ---------------------- overriding function Get_Stroke_Width (Self : not null access constant DG_Style_Proxy) return AMF.Optional_Real is begin return AMF.Internals.Tables.DD_Attributes.Internal_Get_Stroke_Width (Self.Element); end Get_Stroke_Width; ---------------------- -- Set_Stroke_Width -- ---------------------- overriding procedure Set_Stroke_Width (Self : not null access DG_Style_Proxy; To : AMF.Optional_Real) is begin AMF.Internals.Tables.DD_Attributes.Internal_Set_Stroke_Width (Self.Element, To); end Set_Stroke_Width; ------------------------ -- Get_Stroke_Opacity -- ------------------------ overriding function Get_Stroke_Opacity (Self : not null access constant DG_Style_Proxy) return AMF.Optional_Real is begin return AMF.Internals.Tables.DD_Attributes.Internal_Get_Stroke_Opacity (Self.Element); end Get_Stroke_Opacity; ------------------------ -- Set_Stroke_Opacity -- ------------------------ overriding procedure Set_Stroke_Opacity (Self : not null access DG_Style_Proxy; To : AMF.Optional_Real) is begin AMF.Internals.Tables.DD_Attributes.Internal_Set_Stroke_Opacity (Self.Element, To); end Set_Stroke_Opacity; ---------------------- -- Get_Stroke_Color -- ---------------------- overriding function Get_Stroke_Color (Self : not null access constant DG_Style_Proxy) return AMF.DC.Optional_DC_Color is begin return AMF.Internals.Tables.DD_Attributes.Internal_Get_Stroke_Color (Self.Element); end Get_Stroke_Color; ---------------------- -- Set_Stroke_Color -- ---------------------- overriding procedure Set_Stroke_Color (Self : not null access DG_Style_Proxy; To : AMF.DC.Optional_DC_Color) is begin AMF.Internals.Tables.DD_Attributes.Internal_Set_Stroke_Color (Self.Element, To); end Set_Stroke_Color; ---------------------------- -- Get_Stroke_Dash_Length -- ---------------------------- overriding function Get_Stroke_Dash_Length (Self : not null access constant DG_Style_Proxy) return AMF.Real_Collections.Sequence_Of_Real is begin return AMF.Internals.Tables.DD_Attributes.Internal_Get_Stroke_Dash_Length (Self.Element); end Get_Stroke_Dash_Length; ------------------- -- Get_Font_Size -- ------------------- overriding function Get_Font_Size (Self : not null access constant DG_Style_Proxy) return AMF.Optional_Real is begin return AMF.Internals.Tables.DD_Attributes.Internal_Get_Font_Size (Self.Element); end Get_Font_Size; ------------------- -- Set_Font_Size -- ------------------- overriding procedure Set_Font_Size (Self : not null access DG_Style_Proxy; To : AMF.Optional_Real) is begin AMF.Internals.Tables.DD_Attributes.Internal_Set_Font_Size (Self.Element, To); end Set_Font_Size; ------------------- -- Get_Font_Name -- ------------------- overriding function Get_Font_Name (Self : not null access constant DG_Style_Proxy) return AMF.Optional_String is begin declare use type Matreshka.Internals.Strings.Shared_String_Access; Aux : constant Matreshka.Internals.Strings.Shared_String_Access := AMF.Internals.Tables.DD_Attributes.Internal_Get_Font_Name (Self.Element); begin if Aux = null then return (Is_Empty => True); else return (False, League.Strings.Internals.Create (Aux)); end if; end; end Get_Font_Name; ------------------- -- Set_Font_Name -- ------------------- overriding procedure Set_Font_Name (Self : not null access DG_Style_Proxy; To : AMF.Optional_String) is begin if To.Is_Empty then AMF.Internals.Tables.DD_Attributes.Internal_Set_Font_Name (Self.Element, null); else AMF.Internals.Tables.DD_Attributes.Internal_Set_Font_Name (Self.Element, League.Strings.Internals.Internal (To.Value)); end if; end Set_Font_Name; -------------------- -- Get_Font_Color -- -------------------- overriding function Get_Font_Color (Self : not null access constant DG_Style_Proxy) return AMF.DC.Optional_DC_Color is begin return AMF.Internals.Tables.DD_Attributes.Internal_Get_Font_Color (Self.Element); end Get_Font_Color; -------------------- -- Set_Font_Color -- -------------------- overriding procedure Set_Font_Color (Self : not null access DG_Style_Proxy; To : AMF.DC.Optional_DC_Color) is begin AMF.Internals.Tables.DD_Attributes.Internal_Set_Font_Color (Self.Element, To); end Set_Font_Color; --------------------- -- Get_Font_Italic -- --------------------- overriding function Get_Font_Italic (Self : not null access constant DG_Style_Proxy) return AMF.Optional_Boolean is begin return AMF.Internals.Tables.DD_Attributes.Internal_Get_Font_Italic (Self.Element); end Get_Font_Italic; --------------------- -- Set_Font_Italic -- --------------------- overriding procedure Set_Font_Italic (Self : not null access DG_Style_Proxy; To : AMF.Optional_Boolean) is begin AMF.Internals.Tables.DD_Attributes.Internal_Set_Font_Italic (Self.Element, To); end Set_Font_Italic; ------------------- -- Get_Font_Bold -- ------------------- overriding function Get_Font_Bold (Self : not null access constant DG_Style_Proxy) return AMF.Optional_Boolean is begin return AMF.Internals.Tables.DD_Attributes.Internal_Get_Font_Bold (Self.Element); end Get_Font_Bold; ------------------- -- Set_Font_Bold -- ------------------- overriding procedure Set_Font_Bold (Self : not null access DG_Style_Proxy; To : AMF.Optional_Boolean) is begin AMF.Internals.Tables.DD_Attributes.Internal_Set_Font_Bold (Self.Element, To); end Set_Font_Bold; ------------------------ -- Get_Font_Underline -- ------------------------ overriding function Get_Font_Underline (Self : not null access constant DG_Style_Proxy) return AMF.Optional_Boolean is begin return AMF.Internals.Tables.DD_Attributes.Internal_Get_Font_Underline (Self.Element); end Get_Font_Underline; ------------------------ -- Set_Font_Underline -- ------------------------ overriding procedure Set_Font_Underline (Self : not null access DG_Style_Proxy; To : AMF.Optional_Boolean) is begin AMF.Internals.Tables.DD_Attributes.Internal_Set_Font_Underline (Self.Element, To); end Set_Font_Underline; ----------------------------- -- Get_Font_Strike_Through -- ----------------------------- overriding function Get_Font_Strike_Through (Self : not null access constant DG_Style_Proxy) return AMF.Optional_Boolean is begin return AMF.Internals.Tables.DD_Attributes.Internal_Get_Font_Strike_Through (Self.Element); end Get_Font_Strike_Through; ----------------------------- -- Set_Font_Strike_Through -- ----------------------------- overriding procedure Set_Font_Strike_Through (Self : not null access DG_Style_Proxy; To : AMF.Optional_Boolean) is begin AMF.Internals.Tables.DD_Attributes.Internal_Set_Font_Strike_Through (Self.Element, To); end Set_Font_Strike_Through; ------------------- -- Enter_Element -- ------------------- overriding procedure Enter_Element (Self : not null access constant DG_Style_Proxy; Visitor : in out AMF.Visitors.Abstract_Visitor'Class; Control : in out AMF.Visitors.Traverse_Control) is begin if Visitor in AMF.Visitors.DG_Visitors.DG_Visitor'Class then AMF.Visitors.DG_Visitors.DG_Visitor'Class (Visitor).Enter_Style (AMF.DG.Styles.DG_Style_Access (Self), Control); end if; end Enter_Element; ------------------- -- Leave_Element -- ------------------- overriding procedure Leave_Element (Self : not null access constant DG_Style_Proxy; Visitor : in out AMF.Visitors.Abstract_Visitor'Class; Control : in out AMF.Visitors.Traverse_Control) is begin if Visitor in AMF.Visitors.DG_Visitors.DG_Visitor'Class then AMF.Visitors.DG_Visitors.DG_Visitor'Class (Visitor).Leave_Style (AMF.DG.Styles.DG_Style_Access (Self), Control); end if; end Leave_Element; ------------------- -- Visit_Element -- ------------------- overriding procedure Visit_Element (Self : not null access constant DG_Style_Proxy; Iterator : in out AMF.Visitors.Abstract_Iterator'Class; Visitor : in out AMF.Visitors.Abstract_Visitor'Class; Control : in out AMF.Visitors.Traverse_Control) is begin if Iterator in AMF.Visitors.DG_Iterators.DG_Iterator'Class then AMF.Visitors.DG_Iterators.DG_Iterator'Class (Iterator).Visit_Style (Visitor, AMF.DG.Styles.DG_Style_Access (Self), Control); end if; end Visit_Element; end AMF.Internals.DG_Styles;
with Ada.Strings; use Ada.Strings; with Ada.Strings.Fixed; use Ada.Strings.Fixed; with Ada.Text_IO; use Ada.Text_IO; with Libadalang.Analysis; use Libadalang.Analysis; with Libadalang.Common; use Libadalang.Common; with Rejuvenation.Finder; with Rejuvenation.Utils; package body Generator.Match_Pattern_Specific is use Rejuvenation.Node_List; function Equivalent_Key (Left, Right : String) return Boolean is begin return Left = Right; end Equivalent_Key; function Equivalent_Value (Left, Right : List_String.Vector) return Boolean is use List_String; begin return Left = Right; end Equivalent_Value; Type_Decls : constant Rejuvenation.Node_List.Vector := Rejuvenation.Finder.Find (Unit_LAL_Ads.Root, Ada_Type_Decl); Subp_Decls : constant Rejuvenation.Node_List.Vector := Rejuvenation.Finder.Find (Unit_LAL_Ads.Root, Ada_Subp_Spec); Type_Decls2 : constant Rejuvenation.Node_List.Vector := Rejuvenation.Finder.Find (Unit_LALCO_Ads.Root, Ada_Type_Decl); Kinds : List_String.Vector; Type_To_Direct_Children, Type_To_All_Fields : Mapping_Single_Map.Map; procedure Append (Map : in out Mapping_Single_Map.Map; Key : String; Value : String) is begin if not Map.Contains (Key) then declare List : List_String.Vector; begin Map.Include (Key, List); end; end if; declare List : List_String.Vector := Map.Element (Key); UValue : constant Unbounded_String := To_Unbounded_String (Value); begin if not List.Contains (UValue) then List.Append (UValue); Map.Include (Key, List); end if; end; end Append; procedure Process_Node_Kinds is begin for Type_Decl of Type_Decls2 loop declare Name : constant Libadalang.Analysis.Name := Type_Decl.As_Type_Decl.F_Name.F_Name; Str_Name : constant String := Rejuvenation.Utils.Raw_Signature (Name); Def : constant Type_Def := Type_Decl.As_Type_Decl.F_Type_Def; begin if Str_Name = "Ada_Node_Kind_Type" then for E of Def.As_Enum_Type_Def.F_Enum_Literals loop Kinds.Append (To_Unbounded_String (Rejuvenation.Utils.Raw_Signature (E))); end loop; end if; end; end loop; end Process_Node_Kinds; procedure Process_Type_Decl is begin for Type_Decl of Type_Decls loop declare Name : constant Libadalang.Analysis.Name := Type_Decl.As_Type_Decl.F_Name.F_Name; Str_Name : constant String := Rejuvenation.Utils.Raw_Signature (Name); TypeDef : constant Type_Def := Type_Decl.As_Type_Decl.F_Type_Def; begin if TypeDef.Kind = Ada_Derived_Type_Def then if not TypeDef.As_Derived_Type_Def.F_Record_Extension.Is_Null then declare Sub_Type : constant Subtype_Indication := TypeDef.As_Derived_Type_Def.F_Subtype_Indication; Sub_Type_Name : constant Libadalang.Analysis.Name := Sub_Type.F_Name; Str_Sub_Type_Name : constant String := Rejuvenation.Utils.Raw_Signature (Sub_Type_Name); begin -- Put_Line(Str_Name & " -> " & Str_Sub_Type_Name); Append (Type_To_Direct_Children, Str_Sub_Type_Name, Str_Name); end; end if; end if; end; end loop; end Process_Type_Decl; procedure Process_Subp is procedure Add_Recursive (Name : String; Type_Name : String); procedure Add_Recursive (Name : String; Type_Name : String) is begin if Type_To_Direct_Children.Contains (Type_Name) then for N of Type_To_Direct_Children (Type_Name) loop -- Put_Line(" -> " & To_String(N)); Append (Type_To_All_Fields, To_String (N), Name); Add_Recursive (Name, To_String (N)); end loop; end if; end Add_Recursive; begin for Subp_Decl of Subp_Decls loop declare Subp_Name : constant Defining_Name := Subp_Decl.As_Subp_Spec.F_Subp_Name; Name : constant String := Rejuvenation.Utils.Raw_Signature (Subp_Name); begin if Index (Name, "F_") = 1 then declare First_Param : constant Param_Spec := Subp_Decl.As_Subp_Spec.F_Subp_Params .F_Params.Child (1).As_Param_Spec; First_Param_Type : constant Subtype_Indication := First_Param.F_Type_Expr.As_Subtype_Indication; First_Param_Type_Name : constant Libadalang.Analysis.Name := First_Param_Type.F_Name.As_Attribute_Ref.F_Prefix; Str_First_Param_Type_Name : constant String := Rejuvenation.Utils.Raw_Signature (First_Param_Type_Name); begin -- Put_Line(Name & " / " & Str_First_Param_Type_Name); Append (Type_To_All_Fields, Str_First_Param_Type_Name, Name); Add_Recursive (Name, Str_First_Param_Type_Name); end; end if; end; end loop; end Process_Subp; procedure Generate_Match_Specific is begin for E in Type_To_All_Fields.Iterate loop if Kinds.Contains (To_Unbounded_String ("Ada_" & Mapping_Single_Map.Key (E))) then Put_Line ("elsif Pattern.Kind = Ada_" & Mapping_Single_Map.Key (E) & " then"); Put_Line (" declare"); Put_Line (" Pattern2 : constant " & Mapping_Single_Map.Key (E) & " := Pattern.As_" & Mapping_Single_Map.Key (E) & ";"); Put_Line (" Instance2 : constant " & Mapping_Single_Map.Key (E) & " := Instance.As_" & Mapping_Single_Map.Key (E) & ";"); Put_Line (" begin"); for N of Mapping_Single_Map.Element (E) loop declare Prefix : Unbounded_String; Postfix : Unbounded_String; begin if N = Mapping_Single_Map.Element (E).First_Element then Prefix := To_Unbounded_String (" return "); else Prefix := To_Unbounded_String (" "); end if; if N = Mapping_Single_Map.Element (E).Last_Element then Postfix := To_Unbounded_String (";"); else Postfix := To_Unbounded_String (" and then"); end if; Put_Line (To_String (Prefix) & "MP.Match (Pattern2." & To_String (N) & ", Instance2." & To_String (N) & ")" & To_String (Postfix)); end; end loop; Put_Line (" end;"); end if; end loop; end Generate_Match_Specific; procedure Main is begin Process_Node_Kinds; Process_Type_Decl; Process_Subp; Generate_Match_Specific; end Main; end Generator.Match_Pattern_Specific;
----------------------------------------------------------------------- -- gen-commands-distrib -- Distrib command for dynamo -- Copyright (C) 2012, 2013, 2014, 2017, 2018, 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 Ada.Text_IO; with GNAT.Regpat; with Util.Strings; package body Gen.Commands.Distrib is use Ada.Strings.Unbounded; procedure Increment_Build (Generator : in out Gen.Generator.Handler); procedure Increment_Build (Generator : in out Gen.Generator.Handler) is Pattern : constant GNAT.Regpat.Pattern_Matcher := GNAT.Regpat.Compile (".*([0-9]+).*"); Matches : GNAT.Regpat.Match_Array (0 .. 1); Build : constant String := Generator.Get_Project_Property ("build", "1"); Number : Natural := 0; Result : Unbounded_String; begin if GNAT.Regpat.Match (Pattern, Build) then GNAT.Regpat.Match (Pattern, Build, Matches); Number := Natural'Value (Build (Matches (1).First .. Matches (1).Last)); Number := Number + 1; if Matches (1).First > Build'First then Append (Result, Build (Build'First .. Matches (1).First - 1)); end if; Append (Result, Util.Strings.Image (Number)); if Matches (1).Last < Build'Last then Append (Result, Build (Matches (1).Last + 1 .. Build'Last)); end if; Generator.Set_Project_Property ("build", To_String (Result)); end if; Generator.Save_Project; end Increment_Build; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Cmd : in out Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Name); begin if Args.Get_Count = 0 or Args.Get_Count > 2 then Generator.Error ("Missing target directory"); return; end if; Generator.Read_Project ("dynamo.xml", True); Increment_Build (Generator); -- Setup the target directory where the distribution is created. Generator.Set_Result_Directory (Args.Get_Argument (1)); -- Read the package description. if Args.Get_Count = 2 then Gen.Generator.Read_Package (Generator, Args.Get_Argument (2)); else Gen.Generator.Read_Package (Generator, "package.xml"); end if; -- Run the generation. Gen.Generator.Prepare (Generator); Gen.Generator.Generate_All (Generator); Gen.Generator.Finish (Generator); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Cmd : in out Command; Name : in String; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Name, Generator); use Ada.Text_IO; begin Put_Line ("dist: Build the distribution files to prepare the server installation"); Put_Line ("Usage: dist target-dir [package.xml]"); New_Line; Put_Line (" The dist command reads the XML package description to build the" & " distribution tree."); Put_Line (" This command is intended to be used after the project is built. It prepares"); Put_Line (" the files for their installation on the target server in a " & "production environment."); Put_Line (" The package.xml describes what files are necessary on the server."); Put_Line (" It allows to make transformations such as compressing Javascript, CSS and " & "images"); end Help; end Gen.Commands.Distrib;
------------------------------------------------------------------------------ -- -- -- GNAT RUNTIME COMPONENTS -- -- -- -- S Y S T E M . S T R E A M _ A T T R I B U T E S -- -- -- -- S p e c -- -- -- -- $Revision$ -- -- -- Copyright (C) 1992-2000 Free Software Foundation, Inc. -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, -- -- MA 02111-1307, USA. -- -- -- -- As a special exception, if other files instantiate generics from this -- -- unit, or you link this unit with other files to produce an executable, -- -- this unit does not by itself cause the resulting executable to be -- -- covered by the GNU General Public License. This exception does not -- -- however invalidate any other reasons why the executable file might be -- -- covered by the GNU Public License. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- This package contains the implementations of the stream attributes for -- elementary types. These are the subprograms that are directly accessed -- by occurrences of the stream attributes where the type is elementary. -- We only provide the subprograms for the standard base types. For user -- defined types, the subprogram for the corresponding root type is called -- with an appropriate conversion. with System; with System.Unsigned_Types; with Ada.Streams; package System.Stream_Attributes is pragma Preelaborate (Stream_Attributes); pragma Suppress (Accessibility_Check, Stream_Attributes); -- No need to check accessibility on arguments of subprograms package UST renames System.Unsigned_Types; subtype RST is Ada.Streams.Root_Stream_Type'Class; -- Enumeration types are usually transferred using the routine for the -- corresponding integer. The exception is that special routines are -- provided for Boolean and the character types, in case the protocol -- in use provides specially for these types. -- Access types use either a thin pointer (single address) or fat pointer -- (double address) form. The following types are used to hold access -- values using unchecked conversions. type Thin_Pointer is record P1 : System.Address; end record; type Fat_Pointer is record P1 : System.Address; P2 : System.Address; end record; ------------------------------------ -- Treatment of enumeration types -- ------------------------------------ -- In this interface, there are no specific routines for general input -- or output of enumeration types. Generally, enumeration types whose -- representation is unsigned (no negative representation values) are -- treated as unsigned integers, and enumeration types that do have -- negative representation values are treated as signed integers. -- An exception is that there are specialized routines for Boolean, -- Character, and Wide_Character types, but these specialized routines -- are used only if the type in question has a standard representation. -- For the case of a non-standard representation (one where the size of -- the first subtype is specified, or where an enumeration representation -- clause is given, these three types are treated like any other cases -- of enumeration types, as described above. -- for --------------------- -- Input Functions -- --------------------- -- Functions for S'Input attribute. These functions are also used for -- S'Read, with the obvious transformation, since the input operation -- is the same for all elementary types (no bounds or discriminants -- are involved). function I_AD (Stream : access RST) return Fat_Pointer; function I_AS (Stream : access RST) return Thin_Pointer; function I_B (Stream : access RST) return Boolean; function I_C (Stream : access RST) return Character; function I_F (Stream : access RST) return Float; function I_I (Stream : access RST) return Integer; function I_LF (Stream : access RST) return Long_Float; function I_LI (Stream : access RST) return Long_Integer; function I_LLF (Stream : access RST) return Long_Long_Float; function I_LLI (Stream : access RST) return Long_Long_Integer; function I_LLU (Stream : access RST) return UST.Long_Long_Unsigned; function I_LU (Stream : access RST) return UST.Long_Unsigned; function I_SF (Stream : access RST) return Short_Float; function I_SI (Stream : access RST) return Short_Integer; function I_SSI (Stream : access RST) return Short_Short_Integer; function I_SSU (Stream : access RST) return UST.Short_Short_Unsigned; function I_SU (Stream : access RST) return UST.Short_Unsigned; function I_U (Stream : access RST) return UST.Unsigned; function I_WC (Stream : access RST) return Wide_Character; ----------------------- -- Output Procedures -- ----------------------- -- Procedures for S'Write attribute. These procedures are also used -- for 'Output, since for elementary types there is no difference -- between 'Write and 'Output because there are no discriminants -- or bounds to be written. procedure W_AD (Stream : access RST; Item : in Fat_Pointer); procedure W_AS (Stream : access RST; Item : in Thin_Pointer); procedure W_B (Stream : access RST; Item : in Boolean); procedure W_C (Stream : access RST; Item : in Character); procedure W_F (Stream : access RST; Item : in Float); procedure W_I (Stream : access RST; Item : in Integer); procedure W_LF (Stream : access RST; Item : in Long_Float); procedure W_LI (Stream : access RST; Item : in Long_Integer); procedure W_LLF (Stream : access RST; Item : in Long_Long_Float); procedure W_LLI (Stream : access RST; Item : in Long_Long_Integer); procedure W_LLU (Stream : access RST; Item : in UST.Long_Long_Unsigned); procedure W_LU (Stream : access RST; Item : in UST.Long_Unsigned); procedure W_SF (Stream : access RST; Item : in Short_Float); procedure W_SI (Stream : access RST; Item : in Short_Integer); procedure W_SSI (Stream : access RST; Item : in Short_Short_Integer); procedure W_SSU (Stream : access RST; Item : in UST.Short_Short_Unsigned); procedure W_SU (Stream : access RST; Item : in UST.Short_Unsigned); procedure W_U (Stream : access RST; Item : in UST.Unsigned); procedure W_WC (Stream : access RST; Item : in Wide_Character); private pragma Inline (I_AD); pragma Inline (I_AS); pragma Inline (I_B); pragma Inline (I_C); pragma Inline (I_F); pragma Inline (I_I); pragma Inline (I_LF); pragma Inline (I_LI); pragma Inline (I_LLF); pragma Inline (I_LLI); pragma Inline (I_LLU); pragma Inline (I_LU); pragma Inline (I_SF); pragma Inline (I_SI); pragma Inline (I_SSI); pragma Inline (I_SSU); pragma Inline (I_SU); pragma Inline (I_U); pragma Inline (I_WC); pragma Inline (W_AD); pragma Inline (W_AS); pragma Inline (W_B); pragma Inline (W_C); pragma Inline (W_F); pragma Inline (W_I); pragma Inline (W_LF); pragma Inline (W_LI); pragma Inline (W_LLF); pragma Inline (W_LLI); pragma Inline (W_LLU); pragma Inline (W_LU); pragma Inline (W_SF); pragma Inline (W_SI); pragma Inline (W_SSI); pragma Inline (W_SSU); pragma Inline (W_SU); pragma Inline (W_U); pragma Inline (W_WC); end System.Stream_Attributes;
with Glib; use Glib; with Gtk.Adjustment; use Gtk.Adjustment; with Gtk.Button; use Gtk.Button; with Gtk.Combo_Box; use Gtk.Combo_Box; with Gtk.Combo_Box_Text; use Gtk.Combo_Box_Text; with Gtk.Label; use Gtk.Label; with Gtk.Main; use Gtk.Main; with Gtk.Scale; use Gtk.Scale; with Gtk.Spin_Button; use Gtk.Spin_Button; with Gtk.Table; use Gtk.Table; with Gtk.Window; use Gtk.Window; with PortAudioAda; use PortAudioAda; with GA_Sine_Callbacks; use GA_Sine_Callbacks; with GA_Sine_Globals; use GA_Sine_Globals; with GA_Sine_Package; use GA_Sine_Package; procedure GA_Sine is window : Gtk_Window; table : Gtk.Table.Gtk_Table; label : Gtk.Label.Gtk_Label; spin : Gtk.Spin_Button.Gtk_Spin_Button; button : Gtk.Button.Gtk_Button; adjust : Gtk.Adjustment.Gtk_Adjustment; scale : Gtk.Scale.Gtk_Hscale; combo : Gtk.Combo_Box_Text.Gtk_Combo_Box_Text; err : PA_Error; begin err := PA_Initialize; if err /= paNoError then raise PortAudio_Exception with PA_Get_Error_Text (err); end if; Init; Gtk_New (window); Set_Title (window, "PortAudio Test: Sine"); Set_Size_Request (window, -1, -1); Return_Handlers.Connect (window, "delete_event", Return_Handlers.To_Marshaller (Delete_Event'Access)); Handlers.Connect (window, "destroy", Handlers.To_Marshaller (Destroy'Access)); ----------------------------------------------------------------------------- Gtk_New (table, 4, 3, True); Set_Row_Spacings (table, 4); Set_Col_Spacings (table, 10); -- Labels Gtk_New (label, "Frames per buffer"); Attach (table, label, 0, 1, 0, 1); Gtk_New (label, "Sample rate"); Attach (table, label, 0, 1, 1, 2); Gtk_New (label, "Amplitude"); Attach (table, label, 0, 1, 2, 3); Gtk_New (label, "Frequency"); Attach (table, label, 0, 1, 3, 4); -- Controls Gtk_New (spin, 0.0, 1024.0, 16.0); Attach (table, spin, 1, 2, 0, 1); Set_Alignment (spin, 1.0); Set_Value (spin, Gdouble (Frames_Per_Buffer)); SpinHand.Connect (spin, "value_changed", SpinHand.To_Marshaller (Frames_Per_Buffer_Callback'Access)); options (EO_frames_Per_Buffer).optionWidget := spin; options (EO_frames_Per_Buffer).optionUse := OU_Before; Gtk_New (combo); Attach (table, combo, 1, 2, 1, 2); for i in sample_Rates'Range loop Append_Text (combo, sample_Rates (i).txtRate); end loop; Set_Active (combo, 8); CombHand.Connect (combo, "changed", CombHand.To_Marshaller (Sample_Rate_Callback'Access)); options (EO_Sample_Rate).optionWidget := combo; options (EO_Sample_Rate).optionUse := OU_Before; Gtk_New (adjust, 0.0, 0.0, 1.0, 0.01, 0.1); Gtk_New_Hscale (scale, adjust); Attach (table, scale, 1, 2, 2, 3); Set_Digits (scale, 2); Set_Value (scale, Gdouble (gUserData.amplitude)); ScaleHand.Connect (scale, "value_changed", ScaleHand.To_Marshaller (Amplitude_Callback'Access)); options (EO_Amplitude).optionWidget := spin; options (EO_Amplitude).optionUse := OU_Before; Gtk_New (adjust, 0.0, 16.351598, 8372.018085, 0.01, 10.0); Gtk_New_Hscale (scale, adjust); Set_Digits (scale, 2); Attach (table, scale, 1, 2, 3, 4); Set_Value (scale, Gdouble (gUserData.frequency)); ScaleHand.Connect (scale, "value_changed", ScaleHand.To_Marshaller (Frequency_Callback'Access)); options (EO_Frequency).optionWidget := spin; options (EO_Frequency).optionUse := OU_Before; -- Buttons Gtk_New (button, "Start"); Attach (table, button, 2, 3, 0, 1); Handlers.Connect (button, "clicked", Handlers.To_Marshaller (Start_Callback'Access)); Gtk_New (button, "Stop"); Attach (table, button, 2, 3, 1, 2); Handlers.Connect (button, "clicked", Handlers.To_Marshaller (Stop_Callback'Access)); Gtk_New (button, "Quit"); Attach (table, button, 2, 3, 3, 4); Handlers.Connect (button, "clicked", Handlers.To_Marshaller (Destroy'Access)); ----------------------------------------------------------------------------- Add (window, table); Show_All (window); Main; err := PA_Terminate; if err /= paNoError then raise PortAudio_Exception with PA_Get_Error_Text (err); end if; end GA_Sine;
with openGL.Program.lit.textured_skinned; package openGL.Geometry.lit_textured_skinned -- -- Supports per-vertex site, texture, lighting and skinning. -- is type Item is new openGL.Geometry.item with private; function new_Geometry return access Geometry.lit_textured_skinned.item'Class; procedure define_Program; ---------- -- Vertex -- type Vertex is record Site : Vector_3; Normal : Vector_3; Coords : Coordinate_2D; Shine : Real; bone_Ids : Vector_4; bone_Weights : Vector_4; end record; pragma Convention (C, Vertex); type Vertex_array is array (long_Index_t range <>) of aliased Vertex; -------------- -- Attributes -- procedure Vertices_are (Self : in out Item; Now : in Vertex_array); overriding procedure Indices_are (Self : in out Item; Now : in Indices; for_Facia : in Positive); function Program return openGL.Program.lit.textured_skinned.view; private type Item is new Geometry.item with null record; overriding procedure enable_Texture (Self : in Item); end openGL.Geometry.lit_textured_skinned;
with Measure_Units; use Measure_Units; with Ada.Text_IO; use Ada.Text_IO; procedure Aviotest0 is Avg_Speed : Kn := 350.0; Travel_Time : Duration := 2.0 * 3600.0; -- two hours CR : Climb_Rate := 1500.0; Climb_Time : Duration := 60.0 * 20; -- 2 minutes Alt0 : Ft := 50_000.0; -- from here Alt1 : Ft := 20_000.0; -- to here Sink_Time : Duration := 60.0 * 10; -- in 10 minutes begin Put_Line ("avg speed (kt): " & Avg_Speed); Put_Line ("avg speed (m/s): " & To_Mps (Avg_Speed)); Put_Line ("flight duration (s): " & Duration'Image (Travel_Time)); Put_Line ("distance (NM): " & (Avg_Speed * Travel_Time)); Put_Line ("distance (m): " & To_Meters (Avg_Speed * Travel_Time)); Put_Line ("climb rate (ft/min): " & CR); Put_Line ("alt (ft) after " & Duration'Image (Climb_Time) & " s: " & (CR * Climb_Time)); Put_Line ("change alt rate (ft/m): " & ((Alt1 - Alt0) / Sink_Time)); end Aviotest0;
-- SPDX-License-Identifier: MIT -- -- Copyright (c) 2016 - 2018 Gautier de Montmollin (maintainer of the Ada version) -- SWITZERLAND -- -- 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. -- There are three LZ77 encoders at choice here: -- -- 1/ LZ77_using_LZHuf, based on LZHuf -- -- 2/ LZ77_using_IZ, based on Info-Zip's Zip's deflate.c which is -- actually the LZ77 part of Zip's compression. -- -- 3/ LZ77_using_BT4, based on LZMA SDK's BT4 algorithm. -- -- Variant 1/, LZ77_using_LZHuf, is working since 2009. Two problems: it is slow -- and not well adapted to the Deflate format (mediocre compression). -- -- Variant 2/, LZ77_using_IZ, is much faster, and better suited for Deflate. -- It has been added on 05-Mar-2016. -- The code is tailored and optimized for a single set of -- the String_buffer_size, Look_Ahead, Threshold LZ77 parameters - those for Deflate. -- -- Variant 3/, LZ77_using_BT4, was added on 06-Sep-2016. -- The seems to be the best match finder for LZMA on data of the >= 1 MB scale. -- To do: -- -- 2/ -- - LZ77 / IZ: similar to the test with TOO_FAR, try to cluster distances around -- values needing less extra bits (may not work at all...) -- - LZ77 / IZ: tune TOO_FAR (max: 32767), see http://optipng.sf.net/pngtech/too_far.html -- "TOO_FAR in zlib Is Not Too Far" for discussion with System; package body DCF.Lz77 is -- System.Word_Size: 13.3(8): A word is the largest amount of storage -- that can be conveniently and efficiently manipulated by the hardware, -- given the implementation's run-time model Min_Bits_32 : constant := Integer'Max (32, System.Word_Size); Min_Bits_16 : constant := Integer'Max (16, System.Word_Size); -- We define an Integer type which is at least 32 bits, but n bits -- on a native n (> 32) bits architecture (no performance hit on 64+ -- bits architectures) -- Integer_M16 not needed: Integer already guarantees 16 bits type Integer_M32 is range -2**(Min_Bits_32 - 1) .. 2**(Min_Bits_32 - 1) - 1; subtype Natural_M32 is Integer_M32 range 0 .. Integer_M32'Last; type Unsigned_M16 is mod 2**Min_Bits_16; type Unsigned_M32 is mod 2**Min_Bits_32; procedure Encode is -------------------------- -- Info-Zip algorithm -- -------------------------- -- LZ77_using_IZ: based on deflate.c by Jean-Loup Gailly. -- Core description of the algorithm: -- -- The most straightforward technique turns out to be the fastest for -- most input files: try all possible matches and select the longest. -- The key feature of this algorithm is that insertions into the string -- dictionary are very simple and thus fast, and deletions are avoided -- completely. Insertions are performed at each input character, whereas -- string matches are performed only when the previous match ends. So it -- is preferable to spend more time in matches to allow very fast string -- insertions and avoid deletions. The matching algorithm for small -- strings is inspired from that of Rabin & Karp [1]. A brute force approach -- is used to find longer strings when a small match has been found. -- -- The idea of lazy evaluation of matches is due to Jan-Mark Wams. -- -- [1] A description of the Rabin and Karp algorithm is given in the book -- "Algorithms" by R. Sedgewick, Addison-Wesley, p252. -- -- About hashing: chapter 6.4 of The Art of Computer Programming, Volume 3, D.E. Knuth -- Rabin and Karp algorithm: http://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm -- Compression level: 0: store, 1: best speed, 9: best compression, 10: variant of level 9 -- Ada code: only levels 4 to 10 are supported. procedure Lz77_Using_Iz (Level : Natural) is Hash_Bits : constant := 15; -- 13..15 Hash_Size : constant := 2**Hash_Bits; Hash_Mask : constant := Hash_Size - 1; Wsize : constant Integer_M32 := Integer_M32 (String_Buffer_Size); Wmask : constant Unsigned_M16 := Unsigned_M16 (Wsize - 1); -- HASH_SIZE and WSIZE must be powers of two Nil : constant := 0; -- Tail of hash chains Too_Far : constant := 4096; -- Matches of length 3 are discarded if their distance exceeds TOO_FAR -- subtype Ulg is Unsigned_M32; subtype Unsigned is Unsigned_M16; subtype Ush is Unsigned_M16; -- subtype long is Integer_M32; -- subtype int is Integer; subtype Pos is Unsigned_M32; -- must be at least 32 bits -- subtype IPos is unsigned; -- A Pos is an index in the character window. IPos is used only for parameter passing. Window : array (0 .. 2 * Wsize - 1) of Byte; -- Sliding window. Input bytes are read into the second half of the window, -- and move to the first half later to keep a dictionary of at least WSIZE -- bytes. With this organization, matches are limited to a distance of -- WSIZE-MAX_MATCH bytes, but this ensures that IO is always -- performed with a length multiple of the block size. Prev : array (0 .. Unsigned (Wsize - 1)) of Pos; -- Link to older string with same hash index. -- This link is maintained only for the last 32K strings. -- An index in this array is thus a window index modulo 32K. Head : array (0 .. Unsigned (Hash_Size - 1)) of Pos; -- Heads of the hash chains or NIL. Window_Size : Ulg; -- window size, 2*WSIZE except for MMAP or BIG_MEM, where it is the -- input file length plus MIN_LOOKAHEAD. Sliding : Boolean; -- Set to False when the input file is already in memory [was: int] Ins_H : Unsigned; -- hash index of string to be inserted Min_Match : constant Integer_M32 := Integer_M32 (Threshold) + 1; -- Deflate: 3 Max_Match : constant Integer_M32 := Integer_M32 (Look_Ahead); -- Deflate: 258 -- Minimum amount of lookahead, except at the end of the input file. Min_Lookahead : constant Integer_M32 := Max_Match + Min_Match + 1; -- Deflate: 262 -- This LZ77 compression doesn't use the full possible distance range: 32507..32768 unused! Max_Dist : constant Integer_M32 := Wsize - Min_Lookahead; -- Deflate: 32506 H_Shift : constant Integer := Integer ((Hash_Bits + Min_Match - 1) / Min_Match); -- Number of bits by which ins_h and del_h must be shifted at each -- input step. It must be such that after MIN_MATCH steps, the oldest -- byte no longer takes part in the hash key, that is: -- H_SHIFT * MIN_MATCH >= HASH_BITS Prev_Length : Natural_M32; -- [was: unsigned] -- Length of the best match at previous step. Matches not greater than this -- are discarded. This is used in the lazy match evaluation. Strstart : Natural_M32; -- start of string to insert [was: unsigned] Match_Start : Natural_M32; -- start of matching string [was: unsigned] Eofile : Boolean; -- flag set at end of input file [was: int] Lookahead : Natural_M32; -- number of valid bytes ahead in window [was: unsigned] Max_Chain_Length : Unsigned; -- To speed up deflation, hash chains are never searched beyond this length. -- A higher limit improves compression ratio but degrades the speed. Max_Lazy_Match : Natural_M32; -- [was: unsigned] -- Attempt to find a better match only when the current match is strictly -- smaller than this value. This mechanism is used only for compression -- levels >= 4. Good_Match : Natural_M32; -- [was: unsigned] -- Use a faster search when the previous match is longer than this Nice_Match : Integer_M32; -- Stop searching when current match exceeds this -- Values for max_lazy_match, good_match, nice_match and max_chain_length, -- depending on the desired pack level (0..9). The values given below have -- been tuned to exclude worst case performance for pathological files. -- Better values may be found for specific files. type Config is record Good_Length : Natural_M32; -- reduce lazy search above this match length [was: ush] Max_Lazy : Natural_M32; -- do not perform lazy search above this match length Nice_Length : Integer_M32; -- quit search above this match length Max_Chain : Ush; end record; Configuration_Table : constant array (0 .. 10) of Config := ( -- good lazy nice chain (0, 0, 0, 0), -- 0: store only (4, 4, 8, 4), -- 1: maximum speed, no lazy matches (4, 5, 16, 8), (4, 6, 32, 32), (4, 4, 16, 16), -- 4: lazy matches (8, 16, 32, 32), (8, 16, 128, 128), (8, 32, 128, 256), (32, 128, 258, 1024), (32, 258, 258, 4096), -- 9: maximum compression (34, 258, 258, 4096)); -- "secret" variant of level 9 -- Update a hash value with the given input byte -- IN assertion: all calls to to UPDATE_HASH are made with consecutive -- input characters, so that a running hash key can be computed from the -- previous key instead of complete recalculation each time. procedure Update_Hash (H : in out Unsigned; C : Byte) is pragma Inline (Update_Hash); begin H := (Unsigned (Shift_Left (Unsigned_32 (H), H_Shift)) xor Unsigned (C)) and Hash_Mask; end Update_Hash; -- Insert string starting at s in the dictionary and set match_head to the previous head -- of the hash chain (the most recent string with same hash key). Return -- the previous length of the hash chain. -- IN assertion: all calls to to INSERT_STRING are made with consecutive -- input characters and the first MIN_MATCH bytes of s are valid -- (except for the last MIN_MATCH-1 bytes of the input file). procedure Insert_String (S : Integer_M32; Match_Head : out Natural_M32) is pragma Inline (Insert_String); begin Update_Hash (Ins_H, Window (S + Min_Match - 1)); Match_Head := Natural_M32 (Head (Ins_H)); Prev (Unsigned (S) and Wmask) := Pos (Match_Head); Head (Ins_H) := Pos (S); end Insert_String; procedure Read_Buf (From : Integer_M32; Amount : Unsigned; Actual : out Integer_M32) is Need : Unsigned := Amount; begin -- put_line("Read buffer: from:" & from'img & "; amount:" & amount'img); Actual := 0; while Need > 0 and then More_Bytes loop Window (From + Actual) := Read_Byte; Actual := Actual + 1; Need := Need - 1; end loop; -- put_line("Read buffer: actual:" & actual'img); end Read_Buf; -- Fill the window when the lookahead becomes insufficient. -- Updates strstart and lookahead, and sets eofile if end of input file. -- -- IN assertion: lookahead < MIN_LOOKAHEAD && strstart + lookahead > 0 -- OUT assertions: strstart <= window_size-MIN_LOOKAHEAD -- At least one byte has been read, or eofile is set; file reads are -- performed for at least two bytes (required for the translate_eol option). procedure Fill_Window is More : Unsigned; M : Pos; N : Natural_M32; begin loop More := Unsigned (Window_Size - Ulg (Lookahead) - Ulg (Strstart)); if False then -- C: "if (more == (unsigned)EOF) {" ?... GdM: seems a 16-bit code for EOF -- Very unlikely, but possible on 16 bit machine if strstart == 0 -- and lookahead == 1 (input done one byte at time) More := More - 1; elsif Strstart >= Wsize + Max_Dist and then Sliding then -- By the IN assertion, the window is not empty so we can't confuse -- more == 0 with more == 64K on a 16 bit machine. Window (0 .. Wsize - 1) := Window (Wsize .. 2 * Wsize - 1); -- GdM: in rare cases (e.g. level 9 on test file "enwik8"), match_start happens -- to be < WSIZE. We do as in the original 16-bit C code: mod 2**16, such that the -- index is the window's range. -- This assumes WSIZE = 2**15, which is checked at startup of LZ77_using_IZ. -- Very likely, match_start is garbage anyway - see http://sf.net/p/infozip/bugs/49/ Match_Start := Natural_M32 (Unsigned_16 (Match_Start) - Unsigned_16 (Wsize mod (2**16))); Strstart := Strstart - Wsize; -- we now have strstart >= MAX_DIST: for Nn in 0 .. Unsigned'(Hash_Size - 1) loop M := Head (Nn); if M >= Pos (Wsize) then Head (Nn) := M - Pos (Wsize); else Head (Nn) := Nil; end if; end loop; -- for Nn in 0 .. Unsigned (Wsize - 1) loop M := Prev (Nn); if M >= Pos (Wsize) then Prev (Nn) := M - Pos (Wsize); else Prev (Nn) := Nil; end if; -- If n is not on any hash chain, prev[n] is garbage but its value will never be used. end loop; More := More + Unsigned (Wsize); end if; exit when Eofile; -- If there was no sliding: -- strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && -- more == window_size - lookahead - strstart -- => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) -- => more >= window_size - 2*WSIZE + 2 -- In the MMAP or BIG_MEM case (not yet supported in gzip), -- window_size == input_size + MIN_LOOKAHEAD && -- strstart + lookahead <= input_size => more >= MIN_LOOKAHEAD. -- Otherwise, window_size == 2*WSIZE so more >= 2. -- If there was sliding, more >= WSIZE. So in all cases, more >= 2. -- -- Assert(more >= 2, "more < 2"); -- Read_Buf (Strstart + Lookahead, More, N); if N = 0 then Eofile := True; else Lookahead := Lookahead + N; end if; exit when Lookahead >= Min_Lookahead or Eofile; end loop; -- put_line("Fill done - eofile = " & eofile'img); end Fill_Window; -- Initialize the "longest match" routines for a new file -- -- IN assertion: window_size is > 0 if the input file is already read or -- mapped in the window array, 0 otherwise. In the first case, -- window_size is sufficient to contain the whole input file plus -- MIN_LOOKAHEAD bytes (to avoid referencing memory beyond the end -- of window when looking for matches towards the end). procedure Lm_Init (Pack_Level : Natural) is begin -- Do not slide the window if the whole input is already in -- memory (window_size > 0) Sliding := False; if Window_Size = 0 then Sliding := True; Window_Size := 2 * Ulg (Wsize); end if; -- Initialize the hash table. -- prev will be initialized on the fly. Head := (others => Nil); -- Set the default configuration parameters: Max_Lazy_Match := Configuration_Table (Pack_Level).Max_Lazy; Good_Match := Configuration_Table (Pack_Level).Good_Length; Nice_Match := Configuration_Table (Pack_Level).Nice_Length; Max_Chain_Length := Configuration_Table (Pack_Level).Max_Chain; -- Info-Zip comment: ??? reduce max_chain_length for binary files Strstart := 0; Read_Buf (0, Unsigned (Wsize), Lookahead); if Lookahead = 0 then Eofile := True; return; end if; Eofile := False; -- Make sure that we always have enough lookahead. This is important -- if input comes from a device such as a tty. if Lookahead < Min_Lookahead then Fill_Window; end if; Ins_H := 0; for J in 0 .. Natural_M32 (Min_Match) - 2 loop Update_Hash (Ins_H, Window (J)); end loop; -- If lookahead < MIN_MATCH, ins_h is garbage, but this is -- not important since only literal bytes will be emitted. end Lm_Init; -- Set match_start to the longest match starting at the given string and -- return its length. Matches shorter or equal to prev_length are discarded, -- in which case the result is equal to prev_length and match_start is -- garbage. -- IN assertions: current_match is the head of the hash chain for the current -- string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 procedure Longest_Match (Current_Match : in out Integer_M32; Longest : out Integer_M32) is Chain_Length : Unsigned := Max_Chain_Length; -- max hash chain length Scan : Integer_M32 := Strstart; -- current string Match : Integer_M32; -- matched string Len : Integer_M32; -- length of current match Best_Len : Integer_M32 := Prev_Length; -- best match length so far Limit : Natural_M32; -- [was: IPos] Strend : constant Integer_M32 := Strstart + Max_Match; Scan_End : Integer_M32 := Scan + Best_Len; begin -- Stop when current_match becomes <= limit. To simplify the code, -- we prevent matches with the string of window index 0. if Strstart > Max_Dist then Limit := Strstart - Max_Dist; else Limit := Nil; end if; -- Do not waste too much time if we already have a good match: if Prev_Length >= Good_Match then Chain_Length := Chain_Length / 4; end if; -- Assert(strstart <= window_size-MIN_LOOKAHEAD, "insufficient lookahead"); loop -- Assert(current_match < strstart, "no future"); Match := Current_Match; -- Skip to next match if the match length cannot increase -- or if the match length is less than 2: -- -- NB: this is the Not-UNALIGNED_OK variant in the C code. -- Translation of the UNALIGNED_OK variant is left as an exercise ;-). -- (!! worth a try: GNAT optimizes window(match..match+1[3]) to 16[32] bit) -- if Window (Match + Best_Len) /= Window (Scan_End) or else Window (Match + Best_Len - 1) /= Window (Scan_End - 1) or else Window (Match) /= Window (Scan) or else Window (Match + 1) /= Window (Scan + 1) then Match := Match + 1; -- C: continue else -- The check at best_len - 1 can be removed because it will be made -- again later. (This heuristic is not always a win.) -- -- It is not necessary to compare window(scan + 2) and -- window(match + 2) since they are always equal when -- the other bytes match, given that the hash keys are -- equal and that HASH_BITS >= 8 Scan := Scan + 2; Match := Match + 2; -- C: The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. -- It is easy to get rid of this optimization if necessary -- Ada: see the "else" part below if Max_Match = 258 then -- We check for insufficient lookahead only every 8th comparison; -- the 256th check will be made at strstart + 258 loop Scan := Scan + 1; Match := Match + 1; exit when Window (Scan) /= Window (Match); Scan := Scan + 1; Match := Match + 1; exit when Window (Scan) /= Window (Match); Scan := Scan + 1; Match := Match + 1; exit when Window (Scan) /= Window (Match); Scan := Scan + 1; Match := Match + 1; exit when Window (Scan) /= Window (Match); Scan := Scan + 1; Match := Match + 1; exit when Window (Scan) /= Window (Match); Scan := Scan + 1; Match := Match + 1; exit when Window (Scan) /= Window (Match); Scan := Scan + 1; Match := Match + 1; exit when Window (Scan) /= Window (Match); Scan := Scan + 1; Match := Match + 1; exit when Window (Scan) /= Window (Match) or else Scan >= Strend; end loop; else -- We check for insufficient lookahead after every comparison loop Scan := Scan + 1; Match := Match + 1; exit when Window (Scan) /= Window (Match) or else Scan >= Strend; end loop; end if; -- Assert(scan <= window+(unsigned)(window_size-1), "wild scan"); Len := Max_Match - (Strend - Scan); Scan := Strend - Max_Match; if Len > Best_Len then Match_Start := Current_Match; Best_Len := Len; exit when Len >= Nice_Match; Scan_End := Scan + Best_Len; end if; end if; Current_Match := Integer_M32 (Prev (Unsigned (Current_Match) and Wmask)); exit when Current_Match <= Limit; Chain_Length := Chain_Length - 1; exit when Chain_Length = 0; end loop; Longest := Best_Len; end Longest_Match; procedure Lz77_Part_Of_Iz_Deflate is Hash_Head : Natural_M32 := Nil; -- head of hash chain Prev_Match : Natural_M32; -- previous match [was: IPos] Match_Available : Boolean := False; -- set if previous match exists Match_Length : Natural_M32 := Min_Match - 1; -- length of best match Max_Insert : Natural_M32; begin Match_Start := 0; -- NB: no initialization in deflate.c -- NB: level <= 3 would call deflate_fast; -- -- Process the input block while Lookahead /= 0 loop -- Insert the string window(strstart .. strstart + 2) in the -- dictionary, and set hash_head to the head of the hash chain: if Lookahead >= Min_Match then Insert_String (Strstart, Hash_Head); end if; -- Find the longest match, discarding those <= prev_length Prev_Length := Match_Length; Prev_Match := Match_Start; Match_Length := Min_Match - 1; if Hash_Head /= Nil and then Prev_Length < Max_Lazy_Match and then Strstart - Hash_Head <= Max_Dist then -- To simplify the code, we prevent matches with the string -- of window index 0 (in particular we have to avoid a match -- of the string with itself at the start of the input file). -- -- Do not look for matches beyond the end of the input. -- This is necessary to make deflate deterministic. if Nice_Match > Lookahead then Nice_Match := Lookahead; end if; Longest_Match (Hash_Head, Match_Length); -- Longest_Match sets match_start if Match_Length > Lookahead then Match_Length := Lookahead; end if; -- Ignore a length 3 match if it is too distant: if Match_Length = Min_Match and then Strstart - Match_Start > Too_Far then -- If prev_match is also MIN_MATCH, match_start is garbage -- but we will ignore the current match anyway Match_Length := Min_Match - 1; end if; end if; -- If there was a match at the previous step and the current -- match is not better, output the previous match: if Prev_Length >= Min_Match and then Match_Length <= Prev_Length then Max_Insert := Strstart + Lookahead - Min_Match; -- C: in DEBUG mode: check_match(strstart-1, prev_match, prev_length); -- ------------------------------------ -- Output a Distance-Length code -- ------------------------------------ Write_Dl_Code (Positive (Strstart - 1 - Prev_Match), Positive (Prev_Length)); -- Insert in hash table all strings up to the end of the match. -- strstart-1 and strstart are already inserted Lookahead := Lookahead - (Prev_Length - 1); Prev_Length := Prev_Length - 2; loop Strstart := Strstart + 1; if Strstart <= Max_Insert then Insert_String (Strstart, Hash_Head); -- strstart never exceeds WSIZE - MAX_MATCH, so there -- are always MIN_MATCH bytes ahead end if; Prev_Length := Prev_Length - 1; exit when Prev_Length = 0; end loop; Strstart := Strstart + 1; Match_Available := False; Match_Length := Min_Match - 1; elsif Match_Available then -- If there was no match at the previous position, output a -- single literal. If there was a match but the current match -- is longer, truncate the previous match to a single literal ------------------------ -- Output a literal -- ------------------------ Write_Literal (Window (Strstart - 1)); Strstart := Strstart + 1; Lookahead := Lookahead - 1; else -- There is no previous match to compare with, wait -- for the next step to decide Match_Available := True; Strstart := Strstart + 1; Lookahead := Lookahead - 1; end if; -- Assert(strstart <= isize && lookahead <= isize, "a bit too far"); -- -- Make sure that we always have enough lookahead, except -- at the end of the input file. We need MAX_MATCH bytes -- for the next match, plus MIN_MATCH bytes to insert the -- string following the next match. if Lookahead < Min_Lookahead then Fill_Window; end if; end loop; ----------------------------------- -- Output last literal, if any -- ----------------------------------- if Match_Available then Write_Literal (Window (Strstart - 1)); end if; end Lz77_Part_Of_Iz_Deflate; Code_Too_Clever : exception; begin if Look_Ahead /= 258 or String_Buffer_Size /= 2**15 or Threshold /= 2 then raise Code_Too_Clever; -- was optimized for these parameters end if; Window_Size := 0; Lm_Init (Level); Lz77_Part_Of_Iz_Deflate; end Lz77_Using_Iz; begin Lz77_Using_Iz (4 + Method_Type'Pos (Method) - Method_Type'Pos (Iz_4)); end Encode; end DCF.Lz77;
-- 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: /dc/uc/self/arcadia/aflex/ada/src/RCS/miscB.a,v 1.22 1991/07/01 21:30:37 self Exp self $ with Ada.Calendar; with Ada.Characters.Conversions; with Ada.Directories; with Ada.Integer_Wide_Wide_Text_IO; with Ada.Strings.Wide_Wide_Unbounded.Wide_Wide_Text_IO; with MISC, Main_Body; use MISC; package body MISC is use Ada.Characters.Conversions; use Ada.Integer_Wide_Wide_Text_IO; use Ada.Strings.Wide_Wide_Unbounded; use Ada.Strings.Wide_Wide_Unbounded.Wide_Wide_Text_IO; use Ada.Wide_Wide_Text_IO; use Unicode; function "+" (Item : String) return Unbounded_String renames To_Unbounded_String; function "+" (Item : Unbounded_String) return String renames To_String; function "+" (Item : Wide_Wide_String) return Unbounded_Wide_Wide_String renames To_Unbounded_Wide_Wide_String; -- action_out - write the actions from the temporary file to lex.yy.c procedure Action_OUT is Buf : Unbounded_Wide_Wide_String; begin while not End_Of_File (Temp_Action_File) loop GET_LINE (Temp_Action_File, Buf); if Length (BUF) >= 2 and then Slice (Buf, 1, 2) = "%%" then exit; else PUT_LINE(BUF); end if; end loop; end ACTION_OUT; -- bubble - bubble sort an integer array in increasing order -- -- description -- sorts the first n elements of array v and replaces them in -- increasing order. -- -- passed -- v - the array to be sorted -- n - the number of elements of 'v' to be sorted procedure BUBBLE(V : in INT_PTR; N : in INTEGER) is K : INTEGER; begin for I in reverse 2 .. N loop for J in 1 .. I - 1 loop if (V(J) > V(J + 1)) then -- compare K := V(J); -- exchange V(J) := V(J + 1); V(J + 1) := K; end if; end loop; end loop; end BUBBLE; -- clower - replace upper-case letter to lower-case function CLOWER(C : in INTEGER) return INTEGER is begin if (ISUPPER(CHARACTER'VAL(C))) then return TOLOWER(C); else return C; end if; end CLOWER; ------------ -- CSHELL -- ------------ procedure CSHELL (V : in out Unicode_Character_Array; N : Integer) is GAP, J, JG : INTEGER; K : Unicode_Character; LOWER_BOUND : constant INTEGER := V'FIRST; begin GAP := N / 2; while GAP > 0 loop for I in GAP .. N - 1 loop J := I - GAP; while (J >= 0) loop JG := J + GAP; if (V(J + LOWER_BOUND) <= V(JG + LOWER_BOUND)) then exit; end if; K := V (J + LOWER_BOUND); V(J + LOWER_BOUND) := V(JG + LOWER_BOUND); V(JG + LOWER_BOUND) := K; J := J - GAP; end loop; end loop; GAP := GAP/2; end loop; end CSHELL; -- dataend - finish up a block of data declarations procedure DATAEND is begin if (DATAPOS > 0) then DATAFLUSH; -- add terminator for initialization Put_Line (" );"); New_Line; DATALINE := 0; end if; end DATAEND; --------------- -- DATAFLUSH -- --------------- -- dataflush - flush generated data statements procedure DATAFLUSH (File : Ada.Wide_Wide_Text_IO.File_Type) is begin New_Line (File); DATALINE := DATALINE + 1; if DATALINE >= NUMDATALINES then -- put out a blank line so that the table is grouped into -- large blocks that enable the user to find elements easily New_Line (File); DATALINE := 0; end if; -- reset the number of characters written on the current line DATAPOS := 0; end DATAFLUSH; --------------- -- DATAFLUSH -- --------------- procedure DATAFLUSH is begin DATAFLUSH (CURRENT_OUTPUT); end DATAFLUSH; -------------------- -- Aflex_Get_Time -- -------------------- function Aflex_Get_Time return Unbounded_Wide_Wide_String is use Ada.Calendar; Seconds_Per_Hour : constant Day_Duration := 3600.0; Current_Time : Time; Current_Year : Year_Number; Current_Month : Month_Number; Current_Day : Day_Number; Current_Seconds : Day_Duration; Month_String : Unbounded_Wide_Wide_String; Hour_String : Unbounded_Wide_Wide_String; Minute_String : Unbounded_Wide_Wide_String; Second_String : Unbounded_Wide_Wide_String; Hour : Integer; Minute : Integer; Second : Integer; begin Current_Time := Clock; Split (Current_Time, Current_Year, Current_Month, Current_Day, Current_Seconds); case Current_Month is when 1 => Month_String := +"Jan"; when 2 => Month_String := +"Feb"; when 3 => Month_String := +"Mar"; when 4 => Month_String := +"Apr"; when 5 => Month_String := +"May"; when 6 => Month_String := +"Jun"; when 7 => Month_String := +"Jul"; when 8 => Month_String := +"Aug"; when 9 => Month_String := +"Sep"; when 10 => Month_String := +"Oct"; when 11 => Month_String := +"Nov"; when 12 => Month_String := +"Dec"; end case; Hour := Integer (Current_Seconds) / Integer (Seconds_Per_Hour); Minute := Integer ((Current_Seconds - (Hour * Seconds_Per_Hour)) / 60); Second := Integer (Current_Seconds - Hour * Seconds_Per_Hour - Minute * 60.0); if Hour >= 10 then Hour_String := +Integer'Wide_Wide_Image (Hour) (2 .. 3); else Hour_String := +"0" & Integer'Wide_Wide_Image (Hour) (2); end if; if Minute >= 10 then Minute_String := +Integer'Wide_Wide_Image (Minute) (2 .. 3); else Minute_String := +"0" & Integer'Wide_Wide_Image (Minute) (2); end if; if Second >= 10 then Second_String := +Integer'Wide_Wide_Image (Second) (2 .. 3); else Second_String := +"0" & Integer'Wide_Wide_Image (Second) (2); end if; return Month_String & Integer'Wide_Wide_Image (Current_Day) & Hour_String & ":" & Minute_String & ":" & Second_String & Integer'Wide_Wide_Image (Current_Year); end Aflex_Get_Time; ----------------- -- Aflex_Error -- ----------------- procedure Aflex_Error (Msg : Unbounded_Wide_Wide_String) is begin Put (Standard_Error, "aflex: " & Msg); New_Line (Standard_Error); Main_Body.Aflex_End (1); end Aflex_Error; ----------------- -- Aflex_Error -- ----------------- procedure Aflex_Error (Msg : Wide_Wide_String) is begin Put (Standard_Error, "aflex: " & Msg); New_Line (Standard_Error); Main_Body.Aflex_End (1); end Aflex_Error; ----------------- -- Aflex_Fatal -- ----------------- procedure Aflex_Fatal (Msg : Wide_Wide_String) is begin Put (Standard_Error, "aflex: fatal internal error " & Msg); New_Line (Standard_Error); Main_Body.Aflex_End (1); end Aflex_Fatal; ----------------- -- Aflex_Fatal -- ----------------- procedure Aflex_Fatal (Msg : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is begin Put (Standard_Error, "aflex: fatal internal error " & Msg); New_Line (Standard_Error); Main_Body.Aflex_End (1); end Aflex_Fatal; -------------- -- Basename -- -------------- function Basename return Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String is begin if Length (In_File_Name) = 0 then -- if reading standard input give everything this name return +"aflex_yy"; end if; return +To_Wide_Wide_String (Ada.Directories.Base_Name (+In_File_Name)); end Basename; ------------------------ -- LINE_DIRECTIVE_OUT -- ------------------------ -- line_directive_out - spit out a "# line" statement procedure LINE_DIRECTIVE_OUT (OUTPUT_FILE_NAME : Ada.Wide_Wide_Text_IO.File_Type) is begin if GEN_LINE_DIRS then Put (OUTPUT_FILE_NAME, "--# line "); Put (OUTPUT_FILE_NAME, LINENUM, 1); Put (OUTPUT_FILE_NAME, " """); Put (OUTPUT_FILE_NAME, To_Wide_Wide_String (To_String (In_File_Name))); Put_Line (OUTPUT_FILE_NAME, """"); end if; end LINE_DIRECTIVE_OUT; ------------------------ -- LINE_DIRECTIVE_OUT -- ------------------------ procedure LINE_DIRECTIVE_OUT is begin if (GEN_LINE_DIRS) then PUT("--# line "); PUT(LINENUM, 1); PUT(" """); PUT(To_Wide_Wide_String (To_String (In_File_Name))); PUT_LINE(""""); end if; end LINE_DIRECTIVE_OUT; -- all_upper - returns true if a string is all upper-case -- function ALL_UPPER(STR : in VSTRING) return BOOLEAN is -- begin -- for I in 1 .. LEN(STR) loop -- if (not ((CHAR(STR, I) >= 'A') and (CHAR(STR, I) <= 'Z'))) then -- return FALSE; -- end if; -- end loop; -- return TRUE; -- end ALL_UPPER; -- all_lower - returns true if a string is all lower-case -- function ALL_LOWER(STR : in VSTRING) return BOOLEAN is -- begin -- for I in 1 .. LEN(STR) loop -- if (not ((CHAR(STR, I) >= 'a') and (CHAR(STR, I) <= 'z'))) then -- return FALSE; -- end if; -- end loop; -- return TRUE; -- end ALL_LOWER; ------------- -- MK2DATA -- ------------- -- mk2data - generate a data statement for a two-dimensional array -- -- generates a data statement initializing the current 2-D array to "value" procedure MK2DATA (File : Ada.Wide_Wide_Text_IO.File_Type; Value : Integer) is begin if DATAPOS >= NUMDATAITEMS then PUT (FILE, ','); DATAFLUSH (FILE); end if; if DATAPOS = 0 then -- indent PUT (FILE, " "); else PUT (FILE, ','); end if; DATAPOS := DATAPOS + 1; PUT (FILE, VALUE, 5); end MK2DATA; -- -- generates a data statement initializing the current array element to -- "value" procedure MKDATA(VALUE : in INTEGER) is begin if (DATAPOS >= NUMDATAITEMS) then PUT(','); DATAFLUSH; end if; if (DATAPOS = 0) then -- indent PUT(" "); else PUT(','); end if; DATAPOS := DATAPOS + 1; PUT(VALUE, 5); end MKDATA; ------------ -- MYCTOI -- ------------ -- myctoi - return the integer represented by a string of digits function MYCTOI (NUM_ARRAY : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) return INTEGER is TOTAL : INTEGER := 0; CNT : INTEGER := 1; begin while CNT <= Length (NUM_ARRAY) loop TOTAL := TOTAL*10; TOTAL := TOTAL + Wide_Wide_Character'Pos (Element (NUM_ARRAY, CNT)) - CHARACTER'POS('0'); CNT := CNT + 1; end loop; return TOTAL; end MYCTOI; ----------- -- MYESC -- ----------- function MYESC (ARR : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) return Unicode.Unicode_Character is begin case Element (ARR, 2) is when 'a' => return Unicode.BEL; when 'b' => return Unicode.BS; when 'f' => return Unicode.FF; when 'n' => return Unicode.LF; when 'r' => return Unicode.CR; when 't' => return Unicode.HT; when 'v' => return Unicode.VT; when 'u' => -- \u<Unicode> declare Esc_Char : constant Unicode_Character := Unicode_Character'Val (Integer'Wide_Wide_Value ("16#" & Slice (Arr, 3, Length (Arr)) & "#")); begin if (ESC_CHAR = Unicode.NUL) then MISC.SYNERR("escape sequence for null not allowed"); return Unicode.SOH; end if; return ESC_CHAR; end; when '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' => -- \<octal> declare ESC_CHAR : Wide_Wide_Character; begin ESC_CHAR := OTOI (Unbounded_Slice (ARR, 2, Length (ARR))); if (ESC_CHAR = NUL) then MISC.SYNERR("escape sequence for null not allowed"); return Unicode.SOH; end if; return ESC_CHAR; end; when others => return Element (ARR, 2); end case; end MYESC; ---------- -- OTOI -- ---------- -- otoi - convert an octal digit string to an integer value function OTOI (STR : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) return Wide_Wide_Character is TOTAL : INTEGER := 0; CNT : INTEGER := 1; begin while CNT <= Length (STR) loop TOTAL := TOTAL*8; TOTAL := TOTAL + Wide_Wide_Character'Pos (Element (STR, CNT)) - CHARACTER'POS('0'); CNT := CNT + 1; end loop; return Wide_Wide_Character'Val (TOTAL); end OTOI; ------------------- -- Readable_Form -- ------------------- -- readable_form - return the the human-readable form of a character -- -- The returned string is in static storage. function Readable_Form (C : Wide_Wide_Character) return Unbounded_String is To_Hex_Digit : constant String := "0123456789ABCDEF"; Code : constant Integer := Wide_Wide_Character'Pos (C); begin if Code <= 16#FFFF# then case C is when LF => -- Newline return +"\n"; when HT => -- Horizontal Tab return +"\t"; when FF => -- Form Feed return +"\f"; when CR => -- Carriage Return return +"\r"; when BS => -- Backspace return +"\b"; when ' ' => -- Space return +"' '"; when Wide_Wide_Character'Val (33) .. Wide_Wide_Character'Val (127) => return +String' (1 .. 1 => Character'Val (Wide_Wide_Character'Pos (C))); when others => declare Image : String (1 .. 6) := "\uXXXX"; begin Image (3) := To_Hex_Digit ((Code / 2 ** 12) mod 16 + 1); Image (4) := To_Hex_Digit ((Code / 2 ** 8) mod 16 + 1); Image (5) := To_Hex_Digit ((Code / 2 ** 4) mod 16 + 1); Image (6) := To_Hex_Digit (Code mod 16 + 1); return +Image; end; end case; else declare Image : String (1 .. 8) := "\uXXXXXX"; begin Image (3) := To_Hex_Digit (Code / 2 ** 20 + 1); Image (4) := To_Hex_Digit ((Code / 2 ** 16) mod 2 ** 4 + 1); Image (5) := To_Hex_Digit ((Code / 2 ** 12) mod 2 ** 4 + 1); Image (6) := To_Hex_Digit ((Code / 2 ** 8) mod 2 ** 4 + 1); Image (7) := To_Hex_Digit ((Code / 2 ** 4) mod 2 ** 4 + 1); Image (8) := To_Hex_Digit (Code mod 2 ** 4 + 1); return +Image; end; end if; end Readable_Form; -- transition_struct_out - output a yy_trans_info structure -- -- outputs the yy_trans_info structure with the two elements, element_v and -- element_n. Formats the output with spaces and carriage returns. procedure TRANSITION_STRUCT_OUT(ELEMENT_V, ELEMENT_N : in INTEGER) is begin PUT(ELEMENT_V, 7); PUT(", "); PUT(ELEMENT_N, 5); PUT(","); DATAPOS := DATAPOS + TRANS_STRUCT_PRINT_LENGTH; if (DATAPOS >= 75) then NEW_LINE; DATALINE := DATALINE + 1; if DATALINE mod 10 = 0 then NEW_LINE; end if; DATAPOS := 0; end if; end TRANSITION_STRUCT_OUT; function SET_YY_TRAILING_HEAD_MASK(SRC : in INTEGER) return INTEGER is begin if (CHECK_YY_TRAILING_HEAD_MASK(SRC) = 0) then return SRC + YY_TRAILING_HEAD_MASK; else return SRC; end if; end SET_YY_TRAILING_HEAD_MASK; function CHECK_YY_TRAILING_HEAD_MASK(SRC : in INTEGER) return INTEGER is begin if (SRC >= YY_TRAILING_HEAD_MASK) then return YY_TRAILING_HEAD_MASK; else return 0; end if; end CHECK_YY_TRAILING_HEAD_MASK; function SET_YY_TRAILING_MASK(SRC : in INTEGER) return INTEGER is begin if (CHECK_YY_TRAILING_MASK(SRC) = 0) then return SRC + YY_TRAILING_MASK; else return SRC; end if; end SET_YY_TRAILING_MASK; function CHECK_YY_TRAILING_MASK(SRC : in INTEGER) return INTEGER is begin -- this test is whether both bits are on, or whether onlyy TRAIL_MASK is set if ((SRC >= YY_TRAILING_HEAD_MASK + YY_TRAILING_MASK) or (( CHECK_YY_TRAILING_HEAD_MASK(SRC) = 0) and (SRC >= YY_TRAILING_MASK))) then return YY_TRAILING_MASK; else return 0; end if; end CHECK_YY_TRAILING_MASK; function ISLOWER(C : in CHARACTER) return BOOLEAN is begin return (C in 'a' .. 'z'); end ISLOWER; function ISUPPER(C : in CHARACTER) return BOOLEAN is begin return (C in 'A' .. 'Z'); end ISUPPER; function ISDIGIT(C : in CHARACTER) return BOOLEAN is begin return (C in '0' .. '9'); end ISDIGIT; function TOLOWER(C : in INTEGER) return INTEGER is begin return C - CHARACTER'POS('A') + CHARACTER'POS('a'); end TOLOWER; procedure SYNERR (STR : in Wide_Wide_String) is begin SYNTAXERROR := TRUE; PUT (STANDARD_ERROR, "Syntax error at line "); PUT (STANDARD_ERROR, LINENUM); PUT (STANDARD_ERROR, STR); NEW_LINE (STANDARD_ERROR); end SYNERR; end MISC;
----------------------------------------------------------------------- -- mat-targets-probes - Definition and Analysis of process start events -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Bfd; with ELF; with MAT.Formats; with MAT.Readers.Marshaller; package body MAT.Targets.Probes is M_PID : constant MAT.Events.Internal_Reference := 1; M_EXE : constant MAT.Events.Internal_Reference := 2; M_HEAP_START : constant MAT.Events.Internal_Reference := 3; M_HEAP_END : constant MAT.Events.Internal_Reference := 4; M_END : constant MAT.Events.Internal_Reference := 5; M_LIBNAME : constant MAT.Events.Internal_Reference := 6; M_LADDR : constant MAT.Events.Internal_Reference := 7; M_COUNT : constant MAT.Events.Internal_Reference := 8; M_TYPE : constant MAT.Events.Internal_Reference := 9; M_VADDR : constant MAT.Events.Internal_Reference := 10; M_SIZE : constant MAT.Events.Internal_Reference := 11; M_FLAGS : constant MAT.Events.Internal_Reference := 12; PID_NAME : aliased constant String := "pid"; EXE_NAME : aliased constant String := "exe"; HP_START_NAME : aliased constant String := "hp_start"; HP_END_NAME : aliased constant String := "hp_end"; END_NAME : aliased constant String := "end"; LIBNAME_NAME : aliased constant String := "libname"; LADDR_NAME : aliased constant String := "laddr"; COUNT_NAME : aliased constant String := "count"; TYPE_NAME : aliased constant String := "type"; VADDR_NAME : aliased constant String := "vaddr"; SIZE_NAME : aliased constant String := "size"; FLAGS_NAME : aliased constant String := "flags"; Process_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => PID_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_PID), 2 => (Name => EXE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_EXE), 3 => (Name => HP_START_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_HEAP_START), 4 => (Name => HP_END_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_HEAP_END), 5 => (Name => END_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_END)); Library_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => LIBNAME_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_LIBNAME), 2 => (Name => LADDR_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_LADDR), 3 => (Name => COUNT_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_COUNT), 4 => (Name => TYPE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_TYPE), 5 => (Name => VADDR_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_VADDR), 6 => (Name => SIZE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_SIZE), 7 => (Name => FLAGS_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_FLAGS)); -- ------------------------------ -- Create a new process after the begin event is received from the event stream. -- ------------------------------ procedure Create_Process (Probe : in Process_Probe_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String) is begin Probe.Target.Create_Process (Pid => Pid, Path => Path, Process => Probe.Target.Current); Probe.Target.Process.Events := Probe.Events; Probe.Target.Process.Frames := Probe.Frames; MAT.Memory.Targets.Initialize (Memory => Probe.Target.Process.Memory, Manager => Probe.Manager.all); end Create_Process; procedure Probe_Begin (Probe : in Process_Probe_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message; Event : in out MAT.Events.Target_Event_Type) is use type MAT.Types.Target_Addr; use type MAT.Events.Attribute_Type; Pid : MAT.Types.Target_Process_Ref := 0; Path : Ada.Strings.Unbounded.Unbounded_String; Heap : MAT.Memory.Region_Info; begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_PID => Pid := MAT.Readers.Marshaller.Get_Target_Process_Ref (Msg, Def.Kind); when M_EXE => Path := MAT.Readers.Marshaller.Get_String (Msg); when M_HEAP_START => Heap.Start_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when M_HEAP_END => Heap.End_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; Heap.Size := Heap.End_Addr - Heap.Start_Addr; Heap.Path := Ada.Strings.Unbounded.To_Unbounded_String ("[heap]"); Event.Addr := Heap.Start_Addr; Event.Size := Heap.Size; Probe.Create_Process (Pid, Path); Probe.Manager.Read_Message (Msg); Probe.Manager.Read_Event_Definitions (Msg); Probe.Target.Process.Memory.Add_Region (Heap); Probe.Target.Process.Endian := MAT.Readers.Get_Endian (Msg); if Probe.Manager.Get_Address_Size = MAT.Events.T_UINT32 then MAT.Formats.Set_Address_Size (8); else MAT.Formats.Set_Address_Size (16); end if; end Probe_Begin; -- ------------------------------ -- Extract the information from the 'library' event. -- ------------------------------ procedure Probe_Library (Probe : in Process_Probe_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message; Event : in out MAT.Events.Target_Event_Type) is use type MAT.Types.Target_Addr; Count : MAT.Types.Target_Size := 0; Path : Ada.Strings.Unbounded.Unbounded_String; Addr : MAT.Types.Target_Addr; Pos : Natural := Defs'Last + 1; Offset : MAT.Types.Target_Addr; begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_COUNT => Count := MAT.Readers.Marshaller.Get_Target_Size (Msg, Def.Kind); Pos := I + 1; exit; when M_LIBNAME => Path := MAT.Readers.Marshaller.Get_String (Msg); when M_LADDR => Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; Event.Addr := Addr; Event.Size := 0; for Region in 1 .. Count loop declare Region : MAT.Memory.Region_Info; Kind : ELF.Elf32_Word := 0; begin for I in Pos .. Defs'Last loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_SIZE => Region.Size := MAT.Readers.Marshaller.Get_Target_Size (Msg, Def.Kind); when M_VADDR => Region.Start_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when M_TYPE => Kind := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when M_FLAGS => Region.Flags := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; if Kind = ELF.PT_LOAD then Region.Start_Addr := Addr + Region.Start_Addr; Region.End_Addr := Region.Start_Addr + Region.Size; if Ada.Strings.Unbounded.Length (Path) = 0 then Region.Path := Probe.Target.Process.Path; Offset := 0; else Region.Path := Path; Offset := Region.Start_Addr; end if; Event.Size := Event.Size + Region.Size; Probe.Target.Process.Memory.Add_Region (Region); -- When auto-symbol loading is enabled, load the symbols associated with the -- shared libraries used by the program. if Probe.Target.Options.Load_Symbols then begin Probe.Target.Process.Symbols.Value.Load_Symbols (Region, Offset); exception when Bfd.OPEN_ERROR => Probe.Target.Console.Error ("Cannot open symbol library file '" & Ada.Strings.Unbounded.To_String (Region.Path) & "'"); end; end if; end if; end; end loop; end Probe_Library; overriding procedure Extract (Probe : in Process_Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out MAT.Events.Target_Event_Type) is use type MAT.Events.Probe_Index_Type; begin if Event.Index = MAT.Events.MSG_BEGIN then Probe.Probe_Begin (Params.all, Msg, Event); elsif Event.Index = MAT.Events.MSG_LIBRARY then Probe.Probe_Library (Params.all, Msg, Event); end if; end Extract; procedure Execute (Probe : in Process_Probe_Type; Event : in out MAT.Events.Target_Event_Type) is begin null; end Execute; -- ------------------------------ -- Register the reader to extract and analyze process events. -- ------------------------------ procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class; Probe : in Process_Probe_Type_Access) is begin Probe.Manager := Into'Unchecked_Access; Into.Register_Probe (Probe.all'Access, "begin", MAT.Events.MSG_BEGIN, Process_Attributes'Access); Into.Register_Probe (Probe.all'Access, "end", MAT.Events.MSG_END, Process_Attributes'Access); Into.Register_Probe (Probe.all'Access, "shlib", MAT.Events.MSG_LIBRARY, Library_Attributes'Access); end Register; -- ------------------------------ -- Initialize the target object to prepare for reading process events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class) is Process_Probe : constant Process_Probe_Type_Access := new Process_Probe_Type; begin Process_Probe.Target := Target'Unrestricted_Access; Process_Probe.Events := Manager.Get_Target_Events; Process_Probe.Frames := Manager.Get_Target_Frames; Register (Manager, Process_Probe); end Initialize; end MAT.Targets.Probes;
-- { dg-do compile } -- { dg-options "-O -fdump-tree-optimized" } package body Loop_Optimization21 is function Min (X : in Item_Vector) return Item is Tmp_Min : Item; begin Tmp_Min := X (X'First); for I in X'First + 1 .. X'Last loop if X (I) <= Tmp_Min then Tmp_Min := X (I); end if; end loop; return Tmp_Min; end Min; end Loop_Optimization21; -- { dg-final { scan-tree-dump-times "Index_Check" 1 "optimized" } }