content
stringlengths 23
1.05M
|
|---|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Localization, Internationalization, Globalization for Ada --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2009-2014, Vadim Godunko <vgodunko@gmail.com> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
-- This package provides abstractions for strings (sequences of Unicode code
-- points), string's slices, and vectors of strings. Many operations in this
-- package and its children packages depends from the current or explicitly
-- specified locale.
--
-- Universal_String type provides unbounded strings of Unicode characters.
-- It utilizes implicit sharing technology (also known as copy-on-write), so
-- copy operations has constant execution time.
--
-- Universal_Slice is intended to be used primary when its period of life
-- is inside of period of life of referenced string. There are two important
-- advantages to use it: (1) slice data is not copied, (2) additional memory
-- is not allocated. Nethertheless, some operations on slices can be less
-- efficient, because data is not alligned properly as in string case.
--
-- Universal_String_Vector is unbounded form of vector of Universal_String.
--
-- Cursors child package and its children provides different kinds of
-- iterators - character, grapheme cluster, word, sentence, line breaks.
-- See these packages for detailed information.
------------------------------------------------------------------------------
pragma Ada_2012;
private with Ada.Finalization;
private with Ada.Streams;
with Ada.Strings.UTF_Encoding;
with League.Characters;
limited with League.String_Vectors;
private with Matreshka.Internals.Strings;
private with Matreshka.Internals.Utf16;
package League.Strings is
pragma Preelaborate;
pragma Remote_Types;
type Split_Behavior is (Keep_Empty, Skip_Empty);
type Universal_String is tagged private
with Iterator_Element => League.Characters.Universal_Character,
Constant_Indexing => Element;
-- Universal_String is a base type to represent information in textual form
-- as unbounded sequence of Unicode characters (Unicode code points).
type Universal_Slice is tagged private;
type Sort_Key is private;
pragma Preelaborable_Initialization (Sort_Key);
Empty_Universal_String : constant Universal_String;
----------------------
-- Universal_String --
----------------------
function To_Universal_String
(Item : Wide_Wide_String) return Universal_String;
function To_Wide_Wide_String
(Self : Universal_String'Class) return Wide_Wide_String;
function Hash (Self : Universal_String'Class) return League.Hash_Type;
function Length (Self : Universal_String'Class) return Natural;
function Is_Empty (Self : Universal_String'Class) return Boolean;
procedure Clear (Self : in out Universal_String'Class);
function Element
(Self : Universal_String'Class;
Index : Positive) return League.Characters.Universal_Character;
function Slice
(Self : Universal_String'Class;
Low : Positive;
High : Natural) return Universal_String;
-- procedure Slice
-- (Self : in out Universal_String'Class;
-- Low : Positive;
-- High : Natural);
-- Returns slice of the string. Raises Constraint_Error when given indices
-- specifies non-empty and out of bounds range.
procedure Slice
(Self : in out Universal_String'Class; Low : Positive; High : Natural);
function "&"
(Left : Universal_String'Class;
Right : Universal_String'Class) return Universal_String;
function "&"
(Left : Universal_String'Class;
Right : League.Characters.Universal_Character'Class)
return Universal_String;
function "&"
(Left : League.Characters.Universal_Character'Class;
Right : Universal_String'Class) return Universal_String;
function "&"
(Left : Universal_String'Class;
Right : Wide_Wide_Character) return Universal_String;
function "&"
(Left : Wide_Wide_Character;
Right : Universal_String'Class) return Universal_String;
function "&"
(Left : Universal_String'Class;
Right : Wide_Wide_String) return Universal_String;
function "&"
(Left : Wide_Wide_String;
Right : Universal_String'Class) return Universal_String;
procedure Append
(Self : in out Universal_String'Class;
Item : Universal_String'Class);
procedure Append
(Self : in out Universal_String'Class;
Item : League.Characters.Universal_Character'Class);
procedure Append
(Self : in out Universal_String'Class;
Item : Wide_Wide_String);
procedure Append
(Self : in out Universal_String'Class;
Item : Wide_Wide_Character);
-- Appends the character of the string onto the end of the string.
procedure Prepend
(Self : in out Universal_String'Class;
Item : Universal_String'Class);
procedure Prepend
(Self : in out Universal_String'Class;
Item : League.Characters.Universal_Character'Class);
procedure Prepend
(Self : in out Universal_String'Class;
Item : Wide_Wide_String);
procedure Prepend
(Self : in out Universal_String'Class;
Item : Wide_Wide_Character);
-- Prepends the character or the string to the beginning of the string.
-- procedure Replace
-- (Self : in out Universal_String'Class;
-- Index : Positive;
-- By : Universal_Character'Class);
--
-- procedure Replace
-- (Self : in out Universal_String'Class;
-- Index : Positive;
-- By : Wide_Wide_Characters);
procedure Replace
(Self : in out Universal_String'Class;
Low : Positive;
High : Natural;
By : Universal_String'Class);
procedure Replace
(Self : in out Universal_String'Class;
Low : Positive;
High : Natural;
By : Wide_Wide_String);
function Split
(Self : Universal_String'Class;
Separator : League.Characters.Universal_Character'Class;
Behavior : Split_Behavior := Keep_Empty)
return League.String_Vectors.Universal_String_Vector;
-- Splits the string into substrings wherever Separator occurs, and returns
-- the list of those strings. If Separator does not match anywhere in the
-- string, returns a single-element list containing this string.
function Split
(Self : Universal_String'Class;
Separator : Wide_Wide_Character;
Behavior : Split_Behavior := Keep_Empty)
return League.String_Vectors.Universal_String_Vector;
-- Splits the string into substrings wherever Separator occurs, and returns
-- the list of those strings. If Separator does not match anywhere in the
-- string, returns a single-element list containing this string.
function Head
(Self : Universal_String'Class;
Count : Natural) return Universal_String;
-- procedure Head
-- (Self : in out Universal_String'Class;
-- Count : Natural);
-- Returns specified number of starting characters of the string. Raises
-- Constraint_Error when length of the string is less then number of
-- requested characters.
function Tail
(Self : Universal_String'Class;
Count : Natural) return Universal_String;
-- procedure Tail
-- (Self : in out Universal_String'Class;
-- Count : Natural);
-- Returns specified number of ending characters of the string. Raises
-- Constraint_Error when length of the string is less then number of
-- requested characters.
function Head_To
(Self : Universal_String'Class;
To : Natural) return Universal_String renames Head;
-- procedure Head_To
-- (Self : in out Universal_String'Class;
-- To : Natural);
-- Returns leading characters up to and including specified position.
-- Raises Constraint_Error when length of the string is less than requested
-- position.
function Tail_From
(Self : Universal_String'Class;
From : Positive) return Universal_String;
-- procedure Tail_From
-- (Self : in out Universal_String'Class;
-- From : Positive);
-- Returns tailing characters starting from the given position.
function Index
(Self : Universal_String'Class;
Character : League.Characters.Universal_Character'Class) return Natural;
function Index
(Self : Universal_String'Class;
Character : Wide_Wide_Character) return Natural;
function Index
(Self : Universal_String'Class;
From : Positive;
Character : League.Characters.Universal_Character'Class) return Natural;
function Index
(Self : Universal_String'Class;
From : Positive;
Character : Wide_Wide_Character) return Natural;
function Index
(Self : Universal_String'Class;
From : Positive;
To : Natural;
Character : League.Characters.Universal_Character'Class) return Natural;
function Index
(Self : Universal_String'Class;
From : Positive;
To : Natural;
Character : Wide_Wide_Character) return Natural;
-- Returns index of the first occurrence of the specified character in the
-- string, or zero if there are no occurrences.
function Index
(Self : Universal_String'Class;
Pattern : Universal_String'Class) return Natural;
function Index
(Self : Universal_String'Class;
Pattern : Wide_Wide_String) return Natural;
function Index
(Self : Universal_String'Class;
From : Positive;
Pattern : Universal_String'Class) return Natural;
function Index
(Self : Universal_String'Class;
From : Positive;
Pattern : Wide_Wide_String) return Natural;
function Index
(Self : Universal_String'Class;
From : Positive;
To : Natural;
Pattern : Universal_String'Class) return Natural;
function Index
(Self : Universal_String'Class;
From : Positive;
To : Natural;
Pattern : Wide_Wide_String) return Natural;
-- Returns index of the first occurrence of the specified pattern in the
-- string, or zero if there are no occurrences.
function Last_Index
(Self : Universal_String'Class;
Character : League.Characters.Universal_Character'Class) return Natural;
function Last_Index
(Self : Universal_String'Class;
Character : Wide_Wide_Character) return Natural;
function Last_Index
(Self : Universal_String'Class;
To : Natural;
Character : League.Characters.Universal_Character'Class) return Natural;
function Last_Index
(Self : Universal_String'Class;
To : Natural;
Character : Wide_Wide_Character) return Natural;
function Last_Index
(Self : Universal_String'Class;
From : Positive;
To : Natural;
Character : League.Characters.Universal_Character'Class) return Natural;
function Last_Index
(Self : Universal_String'Class;
From : Positive;
To : Natural;
Character : Wide_Wide_Character) return Natural;
-- Returns the index position of the last occurrence of the character in
-- this string, searching backward, or zero if character is not found.
function Count
(Self : Universal_String'Class;
Character : League.Characters.Universal_Character'Class) return Natural;
function Count
(Self : Universal_String'Class;
Character : Wide_Wide_Character) return Natural;
-- Returns the number of occurrences of the Character in this string.
function Ends_With
(Self : Universal_String'Class;
Pattern : Universal_String'Class) return Boolean;
function Ends_With
(Self : Universal_String'Class;
Pattern : Wide_Wide_String) return Boolean;
-- Returns True if the string ends with Pattern; otherwise returns False.
function Starts_With
(Self : Universal_String'Class;
Pattern : Universal_String'Class) return Boolean;
function Starts_With
(Self : Universal_String'Class;
Pattern : Wide_Wide_String) return Boolean;
-- Returns True if the string starts with Pattern; otherwise returns False.
-----------------
-- Conversions --
-----------------
function To_Uppercase
(Self : Universal_String'Class) return Universal_String;
-- Converts each character in the specified string to uppercase form using
-- full case conversion (both context-dependent mappings and tailoring are
-- used). Returns result string.
function To_Lowercase
(Self : Universal_String'Class) return Universal_String;
-- Converts each character in the specified string to lowercase form using
-- full case conversion (both context-dependent mappings and tailoring are
-- used). Returns result string.
function To_Titlecase
(Self : Universal_String'Class) return Universal_String;
-- Converts each character in the specified string to titlecase form using
-- full case conversion (both context-dependent mappings and tailoring are
-- used). Returns result string.
function To_Casefold
(Self : Universal_String'Class) return Universal_String;
-- Converts each character in the specified string to case folding form
-- using full case conversion (only tailoring is used). Returns result
-- string.
function To_Simple_Uppercase
(Self : Universal_String'Class) return Universal_String;
-- Converts each character in the specified string to uppercase form using
-- simple case conversion (only tailoring is used). Returns result string.
function To_Simple_Lowercase
(Self : Universal_String'Class) return Universal_String;
-- Converts each character in the specified string to lowercase form using
-- simple case conversion (only tailoring is used). Returns result string.
function To_Simple_Titlecase
(Self : Universal_String'Class) return Universal_String;
-- Converts each character in the specified string to titlecase form using
-- simple case conversion (only tailoring is used). Returns result string.
function To_Simple_Casefold
(Self : Universal_String'Class) return Universal_String;
-- Converts each character in the specified string to case folding form
-- using simple case conversion (only tailoring is used). Returns result
-- string.
function To_NFC (Self : Universal_String'Class) return Universal_String;
-- Returns specified string converted into Normalization Form C (canonical
-- decomposition and cacnonical composition).
function To_NFD (Self : Universal_String'Class) return Universal_String;
-- Returns specified string converted into Normalization Form D (canonical
-- decomposition).
function To_NFKC (Self : Universal_String'Class) return Universal_String;
-- Returns specified string converted into Normalization Form KC
-- (compatibility decomposition and canonical composition).
function To_NFKD (Self : Universal_String'Class) return Universal_String;
-- Returns specified string converted into Normalization Form KD
-- (compatibility decomposition).
--------------------------------------
-- Equivalence tests and comparison --
--------------------------------------
overriding function "="
(Left : Universal_String; Right : Universal_String) return Boolean;
function "<"
(Left : Universal_String; Right : Universal_String) return Boolean;
function ">"
(Left : Universal_String; Right : Universal_String) return Boolean;
function "<="
(Left : Universal_String; Right : Universal_String) return Boolean;
function ">="
(Left : Universal_String; Right : Universal_String) return Boolean;
-- Compare two strings in binary order of Unicode Code Points.
function Collation (Self : Universal_String'Class) return Sort_Key;
-- Construct sort key for string comparison.
-------------------------------
-- UTF Encoding end Decoding --
-------------------------------
function From_UTF_8_String
(Item : Ada.Strings.UTF_Encoding.UTF_8_String) return Universal_String;
-- Converts standard String in UTF-8 encoding into string.
function To_UTF_8_String
(Self : Universal_String'Class)
return Ada.Strings.UTF_Encoding.UTF_8_String;
-- Converts string to UTF-8 encoded standard String.
function From_UTF_16_Wide_String
(Item : Ada.Strings.UTF_Encoding.UTF_16_Wide_String)
return Universal_String;
-- Converts standard String in UTF-16 host-endian encoding into string.
function To_UTF_16_Wide_String
(Self : Universal_String'Class)
return Ada.Strings.UTF_Encoding.UTF_16_Wide_String;
-- Converts string to UTF-16 encoded standard Wide_String using host-endian
-- variant.
---------------------------------------
-- Comparison operators for Sort_Key --
---------------------------------------
overriding function "=" (Left : Sort_Key; Right : Sort_Key) return Boolean;
function "<" (Left : Sort_Key; Right : Sort_Key) return Boolean;
function "<=" (Left : Sort_Key; Right : Sort_Key) return Boolean;
function ">" (Left : Sort_Key; Right : Sort_Key) return Boolean;
function ">=" (Left : Sort_Key; Right : Sort_Key) return Boolean;
private
type Abstract_Cursor is tagged;
type Cursor_Access is access all Abstract_Cursor'Class;
----------------------
-- Universal_String --
----------------------
procedure Read
(Stream : not null access Ada.Streams.Root_Stream_Type'Class;
Item : out Universal_String);
procedure Write
(Stream : not null access Ada.Streams.Root_Stream_Type'Class;
Item : Universal_String);
procedure Emit_Changed
(Self : Universal_String'Class;
Changed_First : Matreshka.Internals.Utf16.Utf16_String_Index;
Removed_Last : Matreshka.Internals.Utf16.Utf16_String_Index;
Inserted_Last : Matreshka.Internals.Utf16.Utf16_String_Index);
-- Must be called when internal string data is changed. It notify all
-- cursors about this change. All positions are in code units.
-- procedure Emit_Changed
-- (Self : not null String_Private_Data_Access;
-- Cursor : not null Modify_Cursor_Access;
-- Changed_First : Positive;
-- Removed_Last : Natural;
-- Inserted_Last : Natural);
-- Must be called when internal string data is changed. It notify all
-- iterators (except originator) about this change. All positions are in
-- code units.
type Cursor_List is record
Head : Cursor_Access := null;
end record;
type Universal_String is new Ada.Finalization.Controlled with record
Data : Matreshka.Internals.Strings.Shared_String_Access :=
Matreshka.Internals.Strings.Shared_Empty'Access;
-- Data component is non-null by convention. It is set to null only
-- during finalization to mark object as finalized.
List : aliased Cursor_List;
-- Storage for holder of the head of the list of cursors
Cursors : access Cursor_List;
-- List of cursors. This member is initialized to reference to List
-- member.
end record;
for Universal_String'Read use Read;
for Universal_String'Write use Write;
overriding procedure Initialize (Self : in out Universal_String);
overriding procedure Adjust (Self : in out Universal_String)
with Inline => True;
overriding procedure Finalize (Self : in out Universal_String);
Empty_String_Cursors : aliased Cursor_List := (Head => null);
Empty_Universal_String : constant Universal_String
:= (Ada.Finalization.Controlled with
Data => Matreshka.Internals.Strings.Shared_Empty'Access,
List => (Head => null),
Cursors => Empty_String_Cursors'Access);
-- To satisfy requerements of language to prevent modification of component
-- of constant the separate object is used to store list of associated
-- cursors.
---------------------
-- Universal_Slice --
---------------------
type Universal_Slice is new Ada.Finalization.Controlled with null record;
---------------------
-- Abstract_Cursor --
---------------------
type Universal_String_Access is access constant Universal_String'Class;
type Abstract_Cursor is abstract new Ada.Finalization.Controlled with record
Object : Universal_String_Access := null;
Next : Cursor_Access := null;
Previous : Cursor_Access := null;
end record;
not overriding procedure On_Changed
(Self : not null access Abstract_Cursor;
Changed_First : Positive;
Removed_Last : Natural;
Inserted_Last : Natural);
-- Called when internal string data is changed. All positions are in code
-- units. Default implementation invalidate iterator.
procedure Attach
(Self : in out Abstract_Cursor'Class;
Item : in out Universal_String'Class);
-- Attaches iterator to the specified string. Exclusive copy of the string
-- is created if needed.
overriding procedure Adjust (Self : in out Abstract_Cursor)
with Inline => True;
overriding procedure Finalize (Self : in out Abstract_Cursor);
--------------
-- Sort_Key --
--------------
procedure Read
(Stream : not null access Ada.Streams.Root_Stream_Type'Class;
Item : out Sort_Key);
procedure Write
(Stream : not null access Ada.Streams.Root_Stream_Type'Class;
Item : Sort_Key);
type Sort_Key is new Ada.Finalization.Controlled with record
Data : Matreshka.Internals.Strings.Shared_Sort_Key_Access
:= Matreshka.Internals.Strings.Shared_Empty_Key'Access;
end record;
for Sort_Key'Read use Read;
for Sort_Key'Write use Write;
overriding procedure Adjust (Self : in out Sort_Key)
with Inline => True;
overriding procedure Finalize (Self : in out Sort_Key);
pragma Inline ("=");
pragma Inline ("<");
pragma Inline (">");
pragma Inline ("<=");
pragma Inline (">=");
pragma Inline (Clear);
pragma Inline (Finalize);
pragma Inline (Is_Empty);
pragma Inline (Length);
end League.Strings;
|
-- { dg-do run }
-- { dg-options "-gnato -O" }
with Interfaces; use Interfaces;
procedure Opt26 is
procedure Shift_Left_Bool
(Bool : in Boolean;
U8 : out Interfaces.Unsigned_8)
is
begin
U8 := Shift_Left (Boolean'Pos (Bool), 6);
end Shift_Left_Bool;
procedure Shift_Left_Not_Bool
(Bool : in Boolean;
U8 : out Interfaces.Unsigned_8)
is
begin
U8 := Shift_Left (Boolean'Pos (not Bool), 6);
end Shift_Left_Not_Bool;
Bool : constant Boolean := True;
Byte1, Byte2 : Interfaces.Unsigned_8;
begin
Shift_Left_Bool (Bool, Byte1);
Shift_Left_Not_Bool (Bool, Byte2);
if Byte1 + Byte2 /= 64 then
raise Program_Error;
end if;
end;
|
with System;
package Last_Chance_Handler is
procedure Last_Chance_Handler (File : System.Address; Line : Integer);
pragma Export (C, Last_Chance_Handler, "__gnat_last_chance_handler");
pragma No_Return (Last_Chance_Handler);
end Last_Chance_Handler;
|
with Ada.Containers.Indefinite_Vectors;
with Imago.IL; with Imago.ILU;
use Imago.IL; use Imago.ILU;
use type Imago.IL.Bool;
use type Imago.IL.UInt;
with Ada.Text_IO;
use Ada.Text_IO;
with Ada.Integer_Text_IO;
use Ada.Integer_Text_IO;
with GNATCOLL.Strings;
use GNATCOLL.Strings;
with Ada.Strings.Maps;
with Ada.Strings.Fixed;
package body Util is
subtype IL_Image is IL.UInt;
type Im_Instance_Access is access Image_WFC.Instance;
type Ch_Instance_Access is access Character_WFC.Instance;
generic
with package The_WFC is new WFC(<>);
procedure Put_Instance_Info (Inst : in The_WFC.Instance);
procedure Put_Instance_Info (Inst : in The_WFC.Instance) is
begin
Put_Line(Standard_Error, "WFC Instance Info:");
Put_Line(Standard_Error, " Num_Tiles =>" & Inst.Num_Tiles'Image);
Put_Line(Standard_Error, " Instance_Bytes =>" & Integer'Image(Inst'Size / 8));
Put_Line(Standard_Error, " Adjacency_Bytes =>" & Integer'Image(Inst.Adjacencies'Size / 8));
Put_Line(Standard_Error, " Enabler_Bytes =>" & Integer'Image(Inst.Enablers'Size / 8));
New_Line(Standard_Error);
end;
procedure Put_Im_Instance_Info is
new Put_Instance_Info(Image_WFC);
procedure Put_Ch_Instance_Info is
new Put_Instance_Info(Character_WFC);
Input_Image, Output_Image : IL_Image;
Input_File : File_Type;
Output_File : File_Type;
Im_Instance : Im_Instance_Access;
Ch_Instance : Ch_Instance_Access;
type Input_Kind is (None, Pictoral, Textual);
-- The type of the last received input sample.
-- We want to be able to process both actual images
-- as well as simpler, textual files, for ease of use.
Last_Input_Kind : Input_Kind := None;
-- Remember whether we've had an input yet, and if so,
-- what type it was.
N, M : aliased Integer := 2;
-- The width and height of the tiles
-- to be used in the instantiation.
Rot, Ref : aliased Boolean := False;
-- Whether to include rotations, and reflections,
-- respectively, in the instantiation tileset.
Use_Stdout : aliased Boolean := False;
-- Whether to output text-only instance results
-- on stdout rather than using a separate file.
Output_Scale : aliased Integer := 1;
-- When in image mode, how much to scale up the output image.
Out_Name : XString;
-- The name of the file we will produce as output (sans extension, size info, id)
Out_Ct : Natural := 0;
-- How many outputs we've handled so far.
procedure Parse_Output_Command (Spec : String; W, H : out Natural) is
use Ada.Strings.Maps;
use Ada.Strings.Fixed;
Separator_Set : constant Character_Set := To_Set("xX,/:");
Separator_Ix : constant Natural := Index(Spec, Separator_Set);
Last : Natural;
begin
if Separator_Ix = 0 then
raise Argument_Error with "Cannot parse argument: (" & Spec & ")";
end if;
declare
Prefix : String renames Spec (Spec'First .. Separator_Ix - 1);
Suffix : String renames Spec (Separator_Ix + 1 .. Spec'Last);
begin
Get(Prefix, Item => W, Last => Last);
if Last /= Prefix'Last then
raise Argument_Error with "Cannot parse integer: (" & Prefix & ")";
end if;
Get(Suffix, Item => H, Last => Last);
if Last /= Suffix'Last then
raise Argument_Error with "Cannot parse integer: (" & Suffix & ")";
end if;
end;
exception
when Data_Error =>
raise Argument_Error with "Cannot parse argument: (" & Spec & ")";
end;
function Construct_Output_Filename (W, H : Natural) return String is
use Ada.Strings.Fixed;
use Ada.Strings;
W_Str : constant String := Trim(W'Image, Both);
H_Str : constant String := Trim(H'Image, Both);
Ct_Str : constant String := Trim(Out_Ct'Image, Both);
begin
Out_Ct := Out_Ct + 1;
return W_Str & "x" & H_Str & "_" & Ct_Str & "_" & To_String(Out_Name);
end;
function Initialize_Image_Instance return Im_Instance_Access is
Im_Width : constant UInt := UInt(IL.Get_Integer(IL_IMAGE_WIDTH));
Im_Height : constant UInt := UInt(IL.Get_Integer(IL_IMAGE_HEIGHT));
Im_Data : Image_Matrix (1 .. Natural(Im_Width), 1 .. Natural(Im_Height));
Im_Size : IL.UInt;
begin
IL.Bind_Image(Input_Image);
Im_Size :=
IL.Copy_Pixels(
XOff => 0, YOff => 0, ZOff => 0,
Width => Im_Width, Height => Im_Height, Depth => 1,
Format => IL_RGB,
Type_Of => IL_UNSIGNED_BYTE,
Data => Im_Data'Address
);
if Im_Size = 0 then
raise Execution_Error with "Failed to load image data.";
end if;
return new Image_WFC.Instance'(
Image_WFC.Initialize_From_Sample(
N => N, M => M,
Sample => Im_Data,
Include_Rotations => Rot,
Include_Reflections => Ref
)
);
end;
procedure Output_From_Image_Instance (W, H : Natural) is
pragma Assert (Im_Instance /= null);
Output_Filename : constant String := Construct_Output_Filename(W, H);
Im_Data : Image_Matrix (1 .. W, 1 .. H);
Num_Attempts : Natural := 0;
Success : IL.Bool;
begin
if Use_Stdout then
raise Argument_Error with "Cannot output image data to stdout.";
end if;
if Output_Scale < 1 then
raise Argument_Error with "Output scale cannot be less than 1.";
end if;
loop
exit when Image_WFC.Collapse_Within(Im_Instance.all, Im_Data);
Num_Attempts := Num_Attempts + 1;
if Num_Attempts >= 100 then
raise Execution_Error with "Failed to collapse within 100 (!) attempts.";
end if;
end loop;
IL.Bind_Image(Output_Image);
Success := IL.Tex_Image(
Width => UInt(W), Height => UInt(H), Depth => 1, Num_Channels => 3,
Format => IL_RGB,
Type_Of => IL_UNSIGNED_BYTE,
Data => Im_Data'Address
);
if Success /= IL_TRUE then
raise Execution_Error with "Failed to create output image texture.";
end if;
ILU.Image_Parameter(ILU_FILTER, ILU_NEAREST);
Success := ILU.Scale(
Width => UInt(Output_Scale * W),
Height => UInt(Output_Scale * H),
Depth => 1
);
if Success /= IL_True then
raise Execution_Error with "Failed to scale image texture.";
end if;
Success := IL.Save_Image(Output_Filename);
if Success /= IL_TRUE then
raise Execution_Error with "Failed to save output image file.";
end if;
end;
function Initialize_Character_Instance return Ch_Instance_Access is
package String_Vectors is new
Ada.Containers.Indefinite_Vectors(Positive, String);
Mat_Width : Natural := 0;
File_Lines : String_Vectors.Vector;
pragma Assert (Is_Open(Input_File));
begin
while not End_Of_File(Input_File) loop
File_Lines.Append(Get_Line(Input_File));
declare
Last_Line : String renames File_Lines.Last_Element;
begin
if Mat_Width = 0 then
Mat_Width := Last_Line'Length;
elsif Mat_Width /= Last_Line'Length then
raise Argument_Error with "Input file rows are not even.";
end if;
end;
end loop;
declare
Mat_Height : constant Natural := File_Lines.Last_Index;
Char_Input : Character_Matrix(1 .. Mat_Width, 1 .. Mat_Height);
begin
for Y in 1 .. Mat_Height loop
for X in 1 .. Mat_Width loop
Char_Input(X, Y) := File_Lines(Y)(X);
end loop;
end loop;
pragma Debug (Put_Line(Standard_Error, "Initialized Matrix from file (" & Name(Input_File) & ")"));
pragma Debug (Put_Line(Standard_Error, " Matrix_Width =>" & Mat_Width'Image));
pragma Debug (Put_Line(Standard_Error, " Matrix_Height =>" & Mat_Height'Image));
pragma Debug (New_Line(Standard_Error, 1));
Close(Input_File);
return new Character_WFC.Instance'(
Character_WFC.Initialize_From_Sample(
N => N, M => M,
Sample => Char_Input,
Include_Rotations => Rot,
Include_Reflections => Ref
)
);
end;
end;
procedure Output_From_Character_Instance (W, H : Natural) is
pragma Assert (Ch_Instance /= null);
Out_Filename : constant String := Construct_Output_Filename(W, H);
Char_Data : Character_Matrix (1 .. W, 1 .. H)
:= (others => (others => ' '));
procedure Put_To_File(F : File_Type) is
begin
for Y in 1..H loop
for X in 1..W loop
Put(F, Char_Data(X, Y));
end loop;
New_Line(F);
end loop;
end;
Num_Attempts : Natural := 0;
begin
loop
exit when Character_WFC.Collapse_Within(Ch_Instance.all, Char_Data);
Num_Attempts := Num_Attempts + 1;
if Num_Attempts >= 100 then
raise Execution_Error with "Failed to collapse within 100 (!) attempts.";
end if;
end loop;
if Use_Stdout then
Put_To_File(Standard_Output);
New_Line(Standard_Output);
else
Create(Output_File, Out_File, Out_Filename);
Put_To_File(Output_File);
Close(Output_File);
end if;
end;
procedure Set_Input_Source (Switch, Filename : String) is
pragma Unreferenced (Switch);
begin
if Last_Input_Kind /= None then
raise Argument_Error with "Multiple input sources specified.";
end if;
if Out_Name = Null_XString then
Out_Name.Set(Filename);
end if;
pragma Debug (Put_Line(Standard_Error, "Input source: (" & Filename & ")"));
IL.Bind_Image(Input_Image);
if IL.Load_Image(Filename) = IL_TRUE then
pragma Debug (Put_Line(Standard_Error, " Type => Pictoral"));
pragma Debug (New_Line(Standard_Error, 1));
Last_Input_Kind := Pictoral;
else
pragma Debug (Put_Line(Standard_Error, " Type => Textual (inferred)"));
pragma Debug (New_Line(Standard_Error, 1));
begin
Open(Input_File, In_File, Filename);
exception
when Name_Error | Status_Error =>
raise Argument_Error with "File cannot be opened: (" & Filename & ")";
end;
Last_Input_Kind := Textual;
end if;
end;
procedure Set_Output_Name (Switch, Name : String) is
pragma Unreferenced (Switch);
begin
pragma Debug (Put_Line(Standard_Error, "Output name set: (" & Name & ")"));
pragma Debug (New_Line(Standard_Error, 1));
Out_Name.Set(Name);
end;
procedure Define_CLI_Switches (Config : in out Command_Line_Configuration) is
begin
Define_Switch(Config, N'Access,
Switch => "-n:",
Initial => 2
);
Define_Switch(Config, M'Access,
Switch => "-m:",
Initial => 2
);
Define_Switch(Config, Rot'Access,
Switch => "-r", Long_Switch => "--rot"
);
Define_Switch(Config, Ref'Access,
Switch => "-f", Long_Switch => "--ref"
);
Define_Switch(Config, Use_Stdout'Access,
Switch => "-s", Long_Switch => "--stdout"
);
Define_Switch(Config, Output_Scale'Access,
Switch => "-x:", Long_Switch => "--scale=",
Initial => 1
);
Define_Switch(Config, Callback => Set_Input_Source'Access,
Switch => "-i:", Long_Switch => "--input="
);
Define_Switch(Config, Callback => Set_Output_Name'Access,
Switch => "-o:", Long_Switch => "--output="
);
end;
procedure Process_Command_Arguments is
type Output_Handler_Type is
access procedure (W, H : Natural);
function Handle_Arg (Handler : not null Output_Handler_Type) return Boolean is
Arg : constant String := Get_Argument;
Out_W, Out_H : Natural;
begin
if Arg = "" then
return False;
end if;
Parse_Output_Command(Arg, Out_W, Out_H);
Handler(Out_W, Out_H);
return True;
end;
Output_Handler : Output_Handler_Type;
begin
case Last_Input_Kind is
when None =>
return;
when Pictoral =>
Im_Instance := Initialize_Image_Instance;
Output_Handler := Output_From_Image_Instance'Access;
pragma Debug (Put_Im_Instance_Info(Im_Instance.all));
when Textual =>
Ch_Instance := Initialize_Character_Instance;
Output_Handler := Output_From_Character_Instance'Access;
pragma Debug (Put_Ch_Instance_Info(Ch_Instance.all));
end case;
loop
exit when not Handle_Arg(Output_Handler);
end loop;
end;
begin
IL.Init;
pragma Debug (Put_Line(Standard_Error, "Initialized libIL"));
pragma Debug (Put_Line(Standard_Error, " IL_Version =>" & IL.Get_Integer(IL.IL_VERSION_NUM)'Image));
pragma Debug (New_Line(Standard_Error, 1));
ILU.Init;
pragma Debug (Put_Line(Standard_Error, "Initialized libILU"));
pragma Debug (Put_Line(Standard_Error, " ILU_Version =>" & ILU_VERSION'Image));
pragma Debug (New_Line(Standard_Error, 1));
declare
Success : constant IL.Bool := IL.Enable(IL_FILE_OVERWRITE);
begin
if Success /= IL_TRUE then
Put_Line(Standard_Error, "Warning: failed to initialize libIL file overwrite mode.");
end if;
end;
Input_Image := IL.Gen_Image;
Output_Image := IL.Gen_Image;
end;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- G N A T . S O C K E T S . T H I N _ C O M M O N --
-- --
-- B o d y --
-- --
-- Copyright (C) 2008-2020, 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. --
-- --
------------------------------------------------------------------------------
package body GNAT.Sockets.Thin_Common is
-----------------
-- Set_Address --
-----------------
procedure Set_Address
(Sin : Sockaddr_Access;
Address : Sock_Addr_Type;
Length : out C.int)
is
use type C.char;
function Network_Port return C.unsigned_short is
(Short_To_Network (C.unsigned_short (Address.Port))) with Inline;
begin
Set_Family (Sin.Sin_Family, Address.Family);
Length := C.int (Lengths (Address.Family));
case Address.Family is
when Family_Inet =>
Sin.Sin_Port := Network_Port;
Sin.Sin_Addr := To_In_Addr (Address.Addr);
when Family_Inet6 =>
Sin.Sin6_Port := Network_Port;
Sin.Sin6_Addr := To_In6_Addr (Address.Addr);
Sin.Sin6_Scope_Id := 0;
when Family_Unix =>
declare
use type C.size_t;
Name_Len : constant C.size_t :=
C.size_t (ASU.Length (Address.Name));
begin
Length := Sockaddr_Length_And_Family'Size / System.Storage_Unit
+ C.int (Name_Len);
if Name_Len > Sin.Sun_Path'Length then
raise Constraint_Error with
"Too big address length for UNIX local communication";
end if;
if Name_Len = 0 then
Sin.Sun_Path (1) := C.nul;
else
Sin.Sun_Path (1 .. Name_Len) :=
C.To_C (ASU.To_String (Address.Name), Append_Nul => False);
if Sin.Sun_Path (1) /= C.nul
and then Name_Len < Sin.Sun_Path'Length
then
Sin.Sun_Path (Name_Len + 1) := C.nul;
Length := Length + 1;
end if;
end if;
end;
when Family_Unspec =>
null;
end case;
end Set_Address;
-----------------
-- Get_Address --
-----------------
function Get_Address
(Sin : Sockaddr; Length : C.int) return Sock_Addr_Type
is
use type C.unsigned_short, C.size_t, C.char, SOSC.OS_Type;
Family : constant C.unsigned_short :=
(if SOSC.Has_Sockaddr_Len = 0 then Sin.Sin_Family.Short_Family
else C.unsigned_short (Sin.Sin_Family.Char_Family));
Result : Sock_Addr_Type
(if SOSC.AF_INET6 > 0 and then SOSC.AF_INET6 = Family then Family_Inet6
elsif SOSC.AF_UNIX > 0 and then SOSC.AF_UNIX = Family then Family_Unix
elsif SOSC.AF_INET = Family then Family_Inet
else Family_Unspec);
begin
case Result.Family is
when Family_Inet =>
Result.Port := Port_Type (Network_To_Short (Sin.Sin_Port));
To_Inet_Addr (Sin.Sin_Addr, Result.Addr);
when Family_Inet6 =>
Result.Port := Port_Type (Network_To_Short (Sin.Sin6_Port));
To_Inet_Addr (Sin.Sin6_Addr, Result.Addr);
when Family_Unix =>
if Length > Sin.Sin_Family'Size / System.Storage_Unit then
Result.Name := ASU.To_Unbounded_String
(C.To_Ada
(Sin.Sun_Path
(1 .. C.size_t (Length)
- Sin.Sin_Family'Size / System.Storage_Unit),
Trim_Nul => Sin.Sun_Path (1) /= C.nul
or else SOSC.Target_OS = SOSC.Windows));
end if;
when Family_Unspec =>
null;
end case;
return Result;
end Get_Address;
----------------
-- Set_Family --
----------------
procedure Set_Family
(Length_And_Family : out Sockaddr_Length_And_Family;
Family : Family_Type)
is
C_Family : C.int renames Families (Family);
Has_Sockaddr_Len : constant Boolean := SOSC.Has_Sockaddr_Len /= 0;
begin
if Has_Sockaddr_Len then
Length_And_Family.Length := Lengths (Family);
Length_And_Family.Char_Family := C.unsigned_char (C_Family);
else
Length_And_Family.Short_Family := C.unsigned_short (C_Family);
end if;
end Set_Family;
----------------
-- To_In_Addr --
----------------
function To_In_Addr (Addr : Inet_Addr_Type) return In_Addr is
begin
if Addr.Family = Family_Inet then
return (S_B1 => C.unsigned_char (Addr.Sin_V4 (1)),
S_B2 => C.unsigned_char (Addr.Sin_V4 (2)),
S_B3 => C.unsigned_char (Addr.Sin_V4 (3)),
S_B4 => C.unsigned_char (Addr.Sin_V4 (4)));
end if;
raise Socket_Error with "IPv6 not supported";
end To_In_Addr;
------------------
-- To_Inet_Addr --
------------------
procedure To_Inet_Addr
(Addr : In_Addr;
Result : out Inet_Addr_Type) is
begin
Result.Sin_V4 (1) := Inet_Addr_Comp_Type (Addr.S_B1);
Result.Sin_V4 (2) := Inet_Addr_Comp_Type (Addr.S_B2);
Result.Sin_V4 (3) := Inet_Addr_Comp_Type (Addr.S_B3);
Result.Sin_V4 (4) := Inet_Addr_Comp_Type (Addr.S_B4);
end To_Inet_Addr;
------------------
-- To_Inet_Addr --
------------------
procedure To_Inet_Addr
(Addr : In6_Addr;
Result : out Inet_Addr_Type)
is
Sin_V6 : Inet_Addr_V6_Type;
begin
for J in Addr'Range loop
Sin_V6 (J) := Inet_Addr_Comp_Type (Addr (J));
end loop;
Result := (Family => Family_Inet6, Sin_V6 => Sin_V6);
end To_Inet_Addr;
----------------
-- To_In_Addr --
----------------
function To_In6_Addr (Addr : Inet_Addr_Type) return In6_Addr is
Result : In6_Addr;
begin
for J in Addr.Sin_V6'Range loop
Result (J) := C.unsigned_char (Addr.Sin_V6 (J));
end loop;
return Result;
end To_In6_Addr;
----------------------
-- Short_To_Network --
----------------------
function Short_To_Network (S : C.unsigned_short) return C.unsigned_short is
use Interfaces;
use System;
begin
-- Big-endian case. No conversion needed. On these platforms, htons()
-- defaults to a null procedure.
if Default_Bit_Order = High_Order_First then
return S;
-- Little-endian case. We must swap the high and low bytes of this
-- short to make the port number network compliant.
else
return C.unsigned_short (Rotate_Left (Unsigned_16 (S), 8));
end if;
end Short_To_Network;
end GNAT.Sockets.Thin_Common;
|
with Ada.Numerics.Big_Numbers.Big_Integers;
use Ada.Numerics.Big_Numbers.Big_Integers;
package body Fibonacci is
function Fib_Iter (N : Natural) return Big_Natural is
A : Big_Natural := To_Big_Integer (0);
B : Big_Natural := To_Big_Integer (1);
Tmp : Big_Natural := To_Big_Integer (0);
begin
for I in 0..N-1 loop
Tmp := A;
A := B;
B := Tmp + B;
end loop;
return A;
end Fib_Iter;
function Fib_Naive (N : Natural) return Natural is
begin
if N < 2 then return N;
else return Fib_Naive (N - 1) + Fib_Naive (N - 2);
end if;
end Fib_Naive;
function Fib_Recur (N : Natural) return Big_Natural is
function Fib_Aux (N : Natural; A : Big_Natural; B : Big_Natural)
return Big_Natural is
begin
if N > 0 then return Fib_Aux(N - 1, B, A + B);
else return A;
end if;
end Fib_Aux;
begin
return Fib_Aux (N, To_Big_Integer (0), To_Big_Integer (1));
end Fib_Recur;
function Big_Natural_Image (N : Big_Natural) return String is
begin
return To_String (N);
end Big_Natural_Image;
end Fibonacci;
|
-----------------------------------------------------------------------
-- wiki-render-wiki -- Wiki to Wiki renderer
-- Copyright (C) 2015, 2016, 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.Wide_Wide_Maps;
with Ada.Strings.Wide_Wide_Unbounded;
with Wiki.Documents;
with Wiki.Attributes;
with Wiki.Streams;
with Wiki.Strings;
-- === Wiki Renderer ===
-- The `Wiki_Renderer</tt> allows to render a wiki document into another wiki content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Wiki is
use Standard.Wiki.Attributes;
-- ------------------------------
-- Wiki to HTML writer
-- ------------------------------
type Wiki_Renderer is new Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Wiki_Renderer;
Stream : in Streams.Output_Stream_Access;
Format : in Wiki_Syntax);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Wiki_Renderer;
Doc : in Documents.Document;
Node : in Nodes.Node_Type);
-- Add a section header in the document.
procedure Render_Header (Engine : in out Wiki_Renderer;
Header : in Wide_Wide_String;
Level : in Positive);
-- Add a paragraph (<p>). Close the previous paragraph if any.
-- The paragraph must be closed at the next paragraph or next header.
procedure Add_Paragraph (Engine : in out Wiki_Renderer);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Engine : in out Wiki_Renderer;
Level : in Natural);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Add_List_Item (Engine : in out Wiki_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Render a link.
procedure Render_Link (Engine : in out Wiki_Renderer;
Name : in Strings.WString;
Attrs : in Attributes.Attribute_List);
-- Render an image.
procedure Render_Image (Engine : in out Wiki_Renderer;
Title : in Strings.WString;
Attrs : in Attributes.Attribute_List);
-- Render a quote.
procedure Render_Quote (Engine : in out Wiki_Renderer;
Title : in Strings.WString;
Attrs : in Attributes.Attribute_List);
-- Add a text block with the given format.
procedure Render_Text (Engine : in out Wiki_Renderer;
Text : in Wide_Wide_String;
Format : in Format_Map);
-- Render a text block that is pre-formatted.
procedure Render_Preformatted (Engine : in out Wiki_Renderer;
Text : in Strings.WString;
Format : in Strings.WString);
procedure Render_Tag (Engine : in out Wiki_Renderer;
Doc : in Documents.Document;
Node : in Nodes.Node_Type);
-- Finish the document after complete wiki text has been parsed.
procedure Finish (Engine : in out Wiki_Renderer;
Doc : in Documents.Document);
-- Set the text style format.
procedure Set_Format (Engine : in out Wiki_Renderer;
Format : in Format_Map);
private
use Ada.Strings.Wide_Wide_Unbounded;
type Wide_String_Access is access constant Wide_Wide_String;
type Wiki_Tag_Type is (Header_Start, Header_End,
Img_Start, Img_End,
Link_Start, Link_End, Link_Separator,
Quote_Start, Quote_End, Quote_Separator,
Preformat_Start, Preformat_End,
List_Start, List_Item, List_Ordered_Item,
Line_Break, Escape_Rule,
Horizontal_Rule,
Blockquote_Start, Blockquote_End);
type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access;
type Wiki_Format_Array is array (Format_Type) of Wide_String_Access;
procedure Write_Optional_Space (Engine : in out Wiki_Renderer);
-- Emit a new line.
procedure New_Line (Engine : in out Wiki_Renderer;
Optional : in Boolean := False);
procedure Need_Separator_Line (Engine : in out Wiki_Renderer);
procedure Close_Paragraph (Engine : in out Wiki_Renderer);
procedure Start_Keep_Content (Engine : in out Wiki_Renderer);
type List_Style_Array is array (1 .. 32) of Boolean;
EMPTY_TAG : aliased constant Wide_Wide_String := "";
type Wiki_Renderer is new Renderer with record
Output : Streams.Output_Stream_Access := null;
Syntax : Wiki_Syntax := SYNTAX_CREOLE;
Format : Format_Map := (others => False);
Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access);
Style_Start_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access);
Style_End_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access);
Escape_Set : Ada.Strings.Wide_Wide_Maps.Wide_Wide_Character_Set;
Has_Paragraph : Boolean := False;
Has_Item : Boolean := False;
Need_Paragraph : Boolean := False;
Need_Newline : Boolean := False;
Need_Space : Boolean := False;
Empty_Line : Boolean := True;
Empty_Previous_Line : Boolean := True;
Keep_Content : Natural := 0;
In_List : Boolean := False;
Invert_Header_Level : Boolean := False;
Allow_Link_Language : Boolean := False;
Link_First : Boolean := False;
Html_Blockquote : Boolean := False;
Line_Count : Natural := 0;
Current_Level : Natural := 0;
Quote_Level : Natural := 0;
UL_List_Level : Natural := 0;
OL_List_Level : Natural := 0;
Current_Style : Format_Map := (others => False);
Content : Unbounded_Wide_Wide_String;
Link_Href : Unbounded_Wide_Wide_String;
Link_Title : Unbounded_Wide_Wide_String;
Link_Lang : Unbounded_Wide_Wide_String;
end record;
end Wiki.Render.Wiki;
|
with Interfaces; use Interfaces;
with AVR;
with AVR.USART;
-- =============================================================================
-- Package AVR.IMAGE
--
-- String types and methods used by AVR.
-- =============================================================================
package IMAGE is
procedure U8_Img_Right (Data : Unsigned_8; Target : out AVR.USART.String_U8);
subtype String_3 is AVR.USART.String_U8 (1 .. 3);
subtype Digit is Character range '0' .. '9';
function Unsigned_8_To_String_Simon (Input : Interfaces.Unsigned_8) return String_3;
function Unsigned_8_To_String_Shark8 (Input : Interfaces.Unsigned_8) return String_3;
function String_To_Unsigned_8 (Input : AVR.USART.String_U8) return Unsigned_8;
function String_To_Unsigned_8_Shark8 (Input : String_3) return Unsigned_8;
function String_To_Unsigned_32 (Input : AVR.USART.String_U8) return Unsigned_32;
function Compare_String_U8 (Left, Right : in AVR.USART.String_U8) return Boolean;
end IMAGE;
|
-- { dg-do compile }
with Array18_Pkg; use Array18_Pkg;
procedure Array18 is
A : String (1 .. 1);
begin
A := F;
end;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Localization, Internationalization, Globalization for Ada --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2011-2018, Vadim Godunko <vgodunko@gmail.com> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with League.Characters.Latin;
package body League.IRIs is
use League.Characters.Latin;
use type League.Characters.Universal_Character;
package IRI_Parser is
procedure Parse_IRI_Reference
(Self : in out IRI'Class; Image : League.Strings.Universal_String);
-- Parses 'IRI-reference' production.
end IRI_Parser;
procedure Normalize_Path (Self : in out IRI'Class);
function Is_ALPHA
(C : League.Characters.Universal_Character) return Boolean;
-- Returns True when specified character is ALPHA.
function Is_DIGIT
(C : League.Characters.Universal_Character) return Boolean;
-- Returns True when specified character is DIGIT.
function Is_IUnreserved
(C : League.Characters.Universal_Character) return Boolean;
-- Returns True when specified character is iunreserved.
function Is_Sub_Delims
(C : League.Characters.Universal_Character) return Boolean;
-- Returns True when specified character is sub-delims.
---------
-- "=" --
---------
function "=" (Left : IRI; Right : IRI) return Boolean is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, """="" unimplemented");
raise Program_Error;
return "=" (Left, Right);
end "=";
--------------------
-- Append_Segment --
--------------------
procedure Append_Segment
(Self : in out IRI'Class;
Segment : League.Strings.Universal_String) is
begin
Self.Path.Append (Segment);
end Append_Segment;
---------------
-- Authority --
---------------
function Authority
(Self : IRI'Class) return League.Strings.Universal_String is
begin
return Result : League.Strings.Universal_String do
-- Append user info.
if not Self.User_Info.Is_Empty then
Result.Append (Self.User_Info);
Result.Append (Commercial_At);
end if;
-- Append host.
Result.Append (Self.Host);
-- Append port.
if Self.Port /= 0 then
declare
Image : constant Wide_Wide_String
:= Integer'Wide_Wide_Image (Self.Port);
begin
Result.Append (Colon);
Result.Append (Image (Image'First + 1 .. Image'Last));
end;
end if;
end return;
end Authority;
-----------
-- Clear --
-----------
procedure Clear (Self : in out IRI'Class) is
begin
Self.Scheme.Clear;
Self.Has_Authority := False;
Self.User_Info.Clear;
Self.Host.Clear;
Self.Port := 0;
Self.Path_Is_Absolute := True;
Self.Path.Clear;
Self.Query.Clear;
Self.Fragment.Clear;
end Clear;
-----------------------
-- Encoded_Authority --
-----------------------
function Encoded_Authority
(Self : IRI'Class)
return League.Stream_Element_Vectors.Stream_Element_Vector is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Encoded_Authority unimplemented");
raise Program_Error;
return Encoded_Authority (Self);
end Encoded_Authority;
----------------------
-- Encoded_Fragment --
----------------------
function Encoded_Fragment
(Self : IRI'Class)
return League.Stream_Element_Vectors.Stream_Element_Vector is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Encoded_Fragment unimplemented");
raise Program_Error;
return Encoded_Fragment (Self);
end Encoded_Fragment;
------------------
-- Encoded_Host --
------------------
function Encoded_Host
(Self : IRI'Class)
return League.Stream_Element_Vectors.Stream_Element_Vector is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Encoded_Host unimplemented");
raise Program_Error;
return Encoded_Host (Self);
end Encoded_Host;
------------------
-- Encoded_Path --
------------------
function Encoded_Path
(Self : IRI'Class)
return League.Stream_Element_Vectors.Stream_Element_Vector is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Encoded_Path unimplemented");
raise Program_Error;
return Encoded_Path (Self);
end Encoded_Path;
-------------------
-- Encoded_Query --
-------------------
function Encoded_Query
(Self : IRI'Class)
return League.Stream_Element_Vectors.Stream_Element_Vector is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Encoded_Query unimplemented");
raise Program_Error;
return Encoded_Query (Self);
end Encoded_Query;
--------------------
-- Encoded_Scheme --
--------------------
function Encoded_Scheme
(Self : IRI'Class)
return League.Stream_Element_Vectors.Stream_Element_Vector is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Encoded_Scheme unimplemented");
raise Program_Error;
return Encoded_Scheme (Self);
end Encoded_Scheme;
-----------------------
-- Encoded_User_Info --
-----------------------
function Encoded_User_Info
(Self : IRI'Class)
return League.Stream_Element_Vectors.Stream_Element_Vector
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Encoded_User_Info unimplemented");
raise Program_Error;
return Encoded_User_Info (Self);
end Encoded_User_Info;
--------------
-- Fragment --
--------------
function Fragment
(Self : IRI'Class) return League.Strings.Universal_String is
begin
return Self.Fragment;
end Fragment;
------------------
-- From_Encoded --
------------------
function From_Encoded
(Item : League.Stream_Element_Vectors.Stream_Element_Vector) return IRI is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "From_Encoded unimplemented");
raise Program_Error;
return From_Encoded (Item);
end From_Encoded;
---------------------------
-- From_Universal_String --
---------------------------
function From_Universal_String
(Item : League.Strings.Universal_String) return IRI is
begin
return Result : IRI do
Result.Set_IRI (Item);
end return;
end From_Universal_String;
----------------
-- IRI_Parser --
----------------
package body IRI_Parser is
-- All Parse_'production' subprograms has the same profile:
--
-- - Self: object where parsed data is stored;
--
-- - Image: textual representation of the IRI;
--
-- - First: index of the first character to be parsed by subprogram;
-- and index of the first character below successfully parsed
-- production. Parameter is unchanged on failure;
--
-- - Success: status of parsing.
procedure Parse_Scheme
(Self : in out IRI'Class;
Image : League.Strings.Universal_String;
First : in out Positive;
Success : out Boolean);
-- Parses 'scheme' production up to colon delimiter. First will point to
-- colon delimiter on success.
procedure Parse_IHier_Part
(Self : in out IRI'Class;
Image : League.Strings.Universal_String;
First : in out Positive;
Success : out Boolean);
-- Parses 'ihier-part' production up to first unexpected character.
-- First will point to that character.
procedure Parse_IAuthority
(Self : in out IRI'Class;
Image : League.Strings.Universal_String;
First : in out Positive;
Success : out Boolean);
-- Parses 'iauthority' production up to first unexpected character.
-- First will point to that character.
procedure Parse_IPath_Abempty
(Self : in out IRI'Class;
Image : League.Strings.Universal_String;
First : in out Positive;
Success : out Boolean);
-- Parses 'ipath-abempty' production up to first unexpected character.
-- First will point to that character.
procedure Parse_IPath_Absolute
(Self : in out IRI'Class;
Image : League.Strings.Universal_String;
First : in out Positive;
Success : out Boolean);
-- Parses 'ipath-absolute' production up to first unexpected character.
-- First will point to that character.
procedure Parse_ISegment
(Self : in out IRI'Class;
Image : League.Strings.Universal_String;
First : in out Positive;
Success : out Boolean);
-- Parses 'isegment' production up to first unexpected character. First
-- will point to that character.
procedure Parse_IUserInfo
(Self : in out IRI'Class;
Image : League.Strings.Universal_String;
First : in out Positive;
Success : out Boolean);
-- Parses 'iuserinfo' production up to commercial at delimiter. First
-- will point to that character.
procedure Parse_IHost
(Self : in out IRI'Class;
Image : League.Strings.Universal_String;
First : in out Positive;
Success : out Boolean);
-- Parses 'ihost' production up to first unexpected character. First
-- will point to that character.
procedure Parse_IReg_Name
(Self : in out IRI'Class;
Image : League.Strings.Universal_String;
First : in out Positive;
Success : out Boolean);
-- Parses 'ireg-name' production up to first unexpected character. First
-- will point to that character.
procedure Parse_Port
(Self : in out IRI'Class;
Image : League.Strings.Universal_String;
First : in out Positive;
Success : out Boolean);
-- Parses 'port' production up to first unexpected character. First
-- will point to that character.
procedure Parse_IQuery
(Self : in out IRI'Class;
Image : League.Strings.Universal_String;
First : in out Positive;
Success : out Boolean);
-- Parses 'iquery' production up to first unexpected character. First
-- will point to that character.
procedure Parse_IFragment
(Self : in out IRI'Class;
Image : League.Strings.Universal_String;
First : in out Positive;
Success : out Boolean);
-- Parses 'ifragment' production up to first unexpected character. First
-- will point to that character.
procedure Parse_IPath_Noscheme
(Self : in out IRI'Class;
Image : League.Strings.Universal_String;
First : in out Positive;
Success : out Boolean);
-- Parses 'ipath-noscheme' production up to first unexpected character.
-- First will point to that character.
procedure Parse_Pct_Encoded
(Self : in out IRI'Class;
Image : League.Strings.Universal_String;
First : in out Positive;
Success : out Boolean;
Result : in out League.Strings.Universal_String);
-- Parses 'pct-encoded' production. First will point to the character
-- after production. Parsed data is normalized (converted into upper
-- case) and appended to Result.
-- Character classification subprograms.
function Is_HEXDIG
(C : League.Characters.Universal_Character) return Boolean;
-- Returns True when specified character is HEXDIG.
function Is_IPrivate
(C : League.Characters.Universal_Character) return Boolean;
-- Returns True when specified character is iprivate.
---------------
-- Is_HEXDIG --
---------------
function Is_HEXDIG
(C : League.Characters.Universal_Character) return Boolean is
begin
return
(Digit_Zero <= C and C <= Digit_Nine)
or (Latin_Capital_Letter_A <= C and C <= Latin_Capital_Letter_F)
or (Latin_Small_Letter_A <= C and C <= Latin_Small_Letter_F);
end Is_HEXDIG;
-----------------
-- Is_IPrivate --
-----------------
function Is_IPrivate
(C : League.Characters.Universal_Character) return Boolean is
begin
-- [RFC 3987]
--
-- iprivate = %xE000-F8FF / %xF0000-FFFFD / %x100000-10FFFD
-- XXX Compatibility with Legacy IRI must be checked!
-- XXX Not implemented completely.
return Is_IUnreserved (C);
end Is_IPrivate;
----------------------
-- Parse_IAuthority --
----------------------
procedure Parse_IAuthority
(Self : in out IRI'Class;
Image : League.Strings.Universal_String;
First : in out Positive;
Success : out Boolean)
is
-- [RFC 3987]
--
-- iauthority = [ iuserinfo "@" ] ihost [ ":" port ]
Current : Positive := First;
begin
Self.Has_Authority := True;
-- Try to parse 'iuserinfo' production. By convention, it sets
-- Success to True when user info delimiter is not found.
Parse_IUserInfo (Self, Image, Current, Success);
if not Success then
return;
end if;
if Image.Element (Current) = Commercial_At then
Current := Current + 1;
end if;
-- Parse 'ihost' production.
Parse_IHost (Self, Image, Current, Success);
if not Success then
return;
end if;
-- Check port delimiter and parse 'port' production.
if Current <= Image.Length
and then Image.Element (Current) = Colon
then
Current := Current + 1;
-- Skip colon charater.
Parse_Port (Self, Image, Current, Success);
if not Success then
return;
end if;
end if;
First := Current;
Success := True;
end Parse_IAuthority;
---------------------
-- Parse_IFragment --
---------------------
procedure Parse_IFragment
(Self : in out IRI'Class;
Image : League.Strings.Universal_String;
First : in out Positive;
Success : out Boolean)
is
-- [RFC 3987]
--
-- ifragment = *( ipchar / "/" / "?" )
--
-- ipchar = iunreserved / pct-encoded / sub-delims / ":"
-- / "@"
Current : Positive := First;
C : League.Characters.Universal_Character;
begin
while Current <= Image.Length loop
C := Image.Element (Current);
if Is_IUnreserved (C)
or Is_Sub_Delims (C)
or C = Colon
or C = Commercial_At
or C = Solidus
or C = Question_Mark
then
Self.Fragment.Append (C);
Current := Current + 1;
elsif C = Percent_Sign then
Parse_Pct_Encoded
(Self, Image, Current, Success, Self.Fragment);
if not Success then
return;
end if;
else
exit;
end if;
end loop;
First := Current;
Success := True;
end Parse_IFragment;
----------------------
-- Parse_IHier_Part --
----------------------
procedure Parse_IHier_Part
(Self : in out IRI'Class;
Image : League.Strings.Universal_String;
First : in out Positive;
Success : out Boolean)
is
-- [RFC 3987]
--
-- ihier-part = "//" iauthority ipath-abempty
-- / ipath-absolute
-- / ipath-rootless
-- / ipath-empty
--
-- ipath-abempty = *( "/" isegment )
--
-- ipath-absolute = "/" [ isegment-nz *( "/" isegment ) ]
--
-- ipath-rootless = isegment-nz *( "/" isegment )
--
-- ipath-empty = 0<ipchar>
--
-- isegment = *ipchar
--
-- isegment-nz = 1*ipchar
Current : Positive := First;
begin
-- Check whether first two characters are '/' and at least one
-- additional character is present.
if Current + 2 <= Image.Length
and then Image.Element (Current) = Solidus
and then Image.Element (Current + 1) = Solidus
then
-- Parse 'iauthority' and 'ihier-part' productions.
Current := Current + 2;
Parse_IAuthority (Self, Image, Current, Success);
if not Success then
return;
end if;
Parse_IPath_Abempty (Self, Image, Current, Success);
if not Success then
return;
end if;
First := Current;
elsif Current < Image.Length
and then Image.Element (Current) = Solidus
then
-- Parse 'ipath-absolute' production.
Parse_IPath_Absolute (Self, Image, Current, Success);
if not Success then
return;
end if;
First := Current;
elsif Current <= Image.Length then
-- Try to parse 'ipath-rootless' production.
-- XXX Not implemented.
raise Program_Error;
else
-- 'ipath-empty' production.
Self.Path_Is_Absolute := True;
Success := True;
end if;
end Parse_IHier_Part;
-----------------
-- Parse_IHost --
-----------------
procedure Parse_IHost
(Self : in out IRI'Class;
Image : League.Strings.Universal_String;
First : in out Positive;
Success : out Boolean)
is
-- [RFC 3987]
--
-- ihost = IP-literal / IPv4address / ireg-name
--
-- IP-literal = "[" ( IPv6address / IPvFuture ) "]"
--
-- IPv4address = dec-octet "." dec-octet "." dec-octet "."
-- dec-octet
--
-- ireg-name = *( iunreserved / pct-encoded / sub-delims )
begin
if Image.Element (First) = Left_Square_Bracket then
-- XXX Not implemented.
raise Program_Error;
else
-- 'IPv4address' production is just a case of 'ireg-name'
-- production, it is not handled in some special way.
Parse_IReg_Name (Self, Image, First, Success);
end if;
end Parse_IHost;
-------------------------
-- Parse_IPath_Abempty --
-------------------------
procedure Parse_IPath_Abempty
(Self : in out IRI'Class;
Image : League.Strings.Universal_String;
First : in out Positive;
Success : out Boolean)
is
-- [RFC 3987]
--
-- ipath-abempty = *( "/" isegment )
Current : Positive := First;
begin
Self.Path_Is_Absolute := True;
while Current <= Image.Length loop
exit when Image.Element (Current) /= Solidus;
Current := Current + 1;
Parse_ISegment (Self, Image, Current, Success);
if not Success then
return;
end if;
end loop;
First := Current;
Success := True;
end Parse_IPath_Abempty;
--------------------------
-- Parse_IPath_Absolute --
--------------------------
procedure Parse_IPath_Absolute
(Self : in out IRI'Class;
Image : League.Strings.Universal_String;
First : in out Positive;
Success : out Boolean)
is
-- [RFC 3987]
--
-- ipath-absolute = "/" [ isegment-nz *( "/" isegment ) ]
--
-- isegment-nz = 1*ipchar
--
-- isegment = *ipchar
Current : Positive := First;
Old : Positive;
begin
-- Check whether first character is path separator.
if Image.Element (Current) /= Solidus then
Success := False;
return;
end if;
Current := Current + 1;
Self.Path_Is_Absolute := True;
-- Parse 'isegment-nz' production. Old is used to detect that parsed
-- segment has at least one character.
Old := Current;
Parse_ISegment (Self, Image, Current, Success);
if not Success then
return;
end if;
if Old = Current then
Success := False;
return;
end if;
-- Parse following segments.
while Current <= Image.Length loop
exit when Image.Element (Current) /= Solidus;
Current := Current + 1;
Parse_ISegment (Self, Image, Current, Success);
if not Success then
return;
end if;
end loop;
First := Current;
Success := True;
end Parse_IPath_Absolute;
--------------------------
-- Parse_IPath_Noscheme --
--------------------------
procedure Parse_IPath_Noscheme
(Self : in out IRI'Class;
Image : League.Strings.Universal_String;
First : in out Positive;
Success : out Boolean)
is
-- [RFC 3987]
--
-- ipath-noscheme = isegment-nz-nc *( "/" isegment )
--
-- isegment-nz-nc = 1*( iunreserved / pct-encoded / sub-delims
-- / "@" )
Segment : League.Strings.Universal_String;
Current : Positive := First;
C : League.Characters.Universal_Character;
begin
Self.Path_Is_Absolute := False;
while Current <= Image.Length loop
C := Image.Element (Current);
if Is_IUnreserved (C)
or Is_Sub_Delims (C)
or C = Commercial_At
then
Segment.Append (C);
Current := Current + 1;
elsif C = Percent_Sign then
Parse_Pct_Encoded (Self, Image, Current, Success, Segment);
if not Success then
return;
end if;
else
exit;
end if;
end loop;
if Segment.Is_Empty then
Success := False;
return;
end if;
Self.Path.Append (Segment);
while Current <= Image.Length loop
if Image.Element (Current) = Solidus then
Current := Current + 1;
Parse_ISegment (Self, Image, Current, Success);
if not Success then
return;
end if;
else
exit;
end if;
end loop;
First := Current;
Success := True;
end Parse_IPath_Noscheme;
------------------
-- Parse_IQuery --
------------------
procedure Parse_IQuery
(Self : in out IRI'Class;
Image : League.Strings.Universal_String;
First : in out Positive;
Success : out Boolean)
is
-- [RFC 3987]
--
-- iquery = *( ipchar / iprivate / "/" / "?" )
--
-- ipchar = iunreserved / pct-encoded / sub-delims / ":"
-- / "@"
Current : Positive := First;
C : League.Characters.Universal_Character;
begin
while Current <= Image.Length loop
C := Image.Element (Current);
if Is_IUnreserved (C)
or Is_Sub_Delims (C)
or C = Colon
or C = Commercial_At
or C = Solidus
or C = Question_Mark
or Is_IPrivate (C)
then
Self.Query.Append (C);
Current := Current + 1;
elsif C = Percent_Sign then
Parse_Pct_Encoded (Self, Image, Current, Success, Self.Query);
if not Success then
return;
end if;
else
exit;
end if;
end loop;
First := Current;
Success := True;
end Parse_IQuery;
---------------------
-- Parse_IReg_Name --
---------------------
procedure Parse_IReg_Name
(Self : in out IRI'Class;
Image : League.Strings.Universal_String;
First : in out Positive;
Success : out Boolean)
is
-- [RFC 3987]
--
-- ireg-name = *( iunreserved / pct-encoded / sub-delims )
C : League.Characters.Universal_Character;
Current : Positive := First;
begin
while Current <= Image.Length loop
C := Image.Element (Current);
if Is_IUnreserved (C)
or Is_Sub_Delims (C)
then
-- [RFC 3986]
--
-- "Although host is case-insensitive, producers and
-- normalizers should use lowercase for registered names and
-- hexadecimal addresses for the sake of uniformity, while only
-- using uppercase letters for percent-encodings."
--
-- [RFC 3987] 5.3.2.1. Case Normalization
--
-- "When an IRI uses components of the generic syntax, the
-- component syntax equivalence rules always apply; namely,
-- that the scheme and US-ASCII only host are case insensitive
-- and therefore should be normalized to lowercase.
if Is_ALPHA (C) then
Self.Host.Append (C.Simple_Lowercase_Mapping);
else
Self.Host.Append (C);
end if;
Current := Current + 1;
elsif C = Percent_Sign then
Parse_Pct_Encoded (Self, Image, Current, Success, Self.Host);
if not Success then
Self.Host.Clear;
return;
end if;
else
exit;
end if;
end loop;
First := Current;
Success := True;
end Parse_IReg_Name;
-------------------------
-- Parse_IRI_Reference --
-------------------------
procedure Parse_IRI_Reference
(Self : in out IRI'Class; Image : League.Strings.Universal_String)
is
-- [RFC 3987]
--
-- IRI-reference = IRI / irelative-ref
--
-- IRI = scheme ":" ihier-part [ "?" iquery ]
-- [ "#" ifragment ]
--
-- irelative-ref = irelative-part [ "?" iquery ] [ "#" ifragment ]
--
-- irelative-part = "//" iauthority ipath-abempty
-- / ipath-absolute
-- / ipath-noscheme
-- / ipath-empty
--
-- ipath-absolute = "/" [ isegment-nz *( "/" isegment ) ]
--
-- ipath-noscheme = isegment-nz-nc *( "/" isegment )
Success : Boolean;
Current : Positive := 1;
begin
Self.Clear;
-- Try to parse 'scheme' production.
Parse_Scheme (Self, Image, Current, Success);
if Success then
-- Skip colon delimiter.
Current := Current + 1;
Parse_IHier_Part (Self, Image, Current, Success);
if not Success then
raise Constraint_Error;
end if;
elsif Current + 2 <= Image.Length
and then Image.Element (Current) = Solidus
and then Image.Element (Current + 1) = Solidus
then
-- Parse 'iauthority' and 'ihier-part' productions.
Current := Current + 2;
Parse_IAuthority (Self, Image, Current, Success);
if not Success then
raise Constraint_Error;
end if;
Parse_IPath_Abempty (Self, Image, Current, Success);
if not Success then
raise Constraint_Error;
end if;
elsif Current < Image.Length
and then Image.Element (Current) = Solidus
then
-- Parse 'ipath-absolute' production.
Parse_IPath_Absolute (Self, Image, Current, Success);
if not Success then
raise Constraint_Error;
end if;
elsif Current <= Image.Length then
-- Parse 'ipath-noscheme' production.
Parse_IPath_Noscheme (Self, Image, Current, Success);
if not Success then
raise Constraint_Error;
end if;
end if;
-- Parse 'iquery' production if present.
if Current <= Image.Length
and then Image.Element (Current) = Question_Mark
then
-- Skip question mark delimiter.
Current := Current + 1;
Parse_IQuery (Self, Image, Current, Success);
if not Success then
raise Constraint_Error;
end if;
end if;
-- Parse 'fragment' production if present.
if Current <= Image.Length
and then Image.Element (Current) = Number_Sign
then
-- Skip number sign delimiter.
Current := Current + 1;
Parse_IFragment (Self, Image, Current, Success);
if not Success then
raise Constraint_Error;
end if;
end if;
if Current <= Image.Length then
raise Constraint_Error;
end if;
end Parse_IRI_Reference;
--------------------
-- Parse_ISegment --
--------------------
procedure Parse_ISegment
(Self : in out IRI'Class;
Image : League.Strings.Universal_String;
First : in out Positive;
Success : out Boolean)
is
-- [RFC 3987]
--
-- isegment = *ipchar
--
-- ipchar = iunreserved / pct-encoded / sub-delims / ":"
-- / "@"
Segment : League.Strings.Universal_String;
C : League.Characters.Universal_Character;
Current : Positive := First;
begin
while Current <= Image.Length loop
C := Image.Element (Current);
if Is_IUnreserved (C)
or Is_Sub_Delims (C)
or C = Colon
or C = Commercial_At
then
Segment.Append (C);
Current := Current + 1;
elsif C = Percent_Sign then
-- Percent encoded data.
Parse_Pct_Encoded (Self, Image, Current, Success, Segment);
if not Success then
return;
end if;
else
-- Unexpected character.
exit;
end if;
end loop;
-- Append parsed segment to the list of segments when it is not
-- empty.
if not Segment.Is_Empty then
Self.Path.Append (Segment);
end if;
First := Current;
Success := True;
end Parse_ISegment;
---------------------
-- Parse_IUserInfo --
---------------------
procedure Parse_IUserInfo
(Self : in out IRI'Class;
Image : League.Strings.Universal_String;
First : in out Positive;
Success : out Boolean)
is
-- [RFC 3987]
--
-- iuserinfo = *( iunreserved / pct-encoded / sub-delims / ":" )
Current : Positive := First;
C : League.Characters.Universal_Character;
begin
while Current <= Image.Length loop
C := Image.Element (Current);
if Is_IUnreserved (C)
or Is_Sub_Delims (C)
or C = Colon
then
Self.User_Info.Append (C);
Current := Current + 1;
elsif C = Percent_Sign then
Parse_Pct_Encoded
(Self, Image, Current, Success, Self.User_Info);
if not Success then
Self.User_Info.Clear;
return;
end if;
else
exit;
end if;
end loop;
Success := True;
if Current > Image.Length
or else Image.Element (Current) /= Commercial_At
then
-- By convention, character after 'iuserinfo' should be '@';
-- otherwise it is impossible to distinguish 'ihost' and
-- 'iuserinfo'. So, clear accumulated data to be able to try parse
-- 'ihost'.
Self.User_Info.Clear;
else
First := Current;
end if;
end Parse_IUserInfo;
-----------------------
-- Parse_Pct_Encoded --
-----------------------
procedure Parse_Pct_Encoded
(Self : in out IRI'Class;
Image : League.Strings.Universal_String;
First : in out Positive;
Success : out Boolean;
Result : in out League.Strings.Universal_String)
is
-- [RFC 3987]
--
-- pct-encoded = "%" HEXDIG HEXDIG
C1 : League.Characters.Universal_Character;
C2 : League.Characters.Universal_Character;
begin
if First + 2 <= Image.Length
and Image.Element (First) = Percent_Sign
then
C1 := Image.Element (First + 1);
C2 := Image.Element (First + 2);
if Is_HEXDIG (C1) and Is_HEXDIG (C2) then
-- Append to result parsed and normalized (converted to
-- uppercase) characters.
Result.Append (Percent_Sign);
Result.Append (C1.Simple_Uppercase_Mapping);
Result.Append (C2.Simple_Uppercase_Mapping);
First := First + 3;
Success := True;
else
Success := False;
end if;
else
Success := False;
end if;
end Parse_Pct_Encoded;
----------------
-- Parse_Port --
----------------
procedure Parse_Port
(Self : in out IRI'Class;
Image : League.Strings.Universal_String;
First : in out Positive;
Success : out Boolean)
is
-- [RFC 3987]
--
-- port = *DIGIT
C : League.Characters.Universal_Character;
Current : Positive := First;
begin
Self.Port := 0;
while Current <= Image.Length loop
C := Image.Element (Current);
exit when not IS_DIGIT (C);
Self.Port :=
Self.Port * 10
+ (Wide_Wide_Character'Pos (C.To_Wide_Wide_Character)
- Wide_Wide_Character'Pos('0'));
Current := Current + 1;
end loop;
Success := True;
First := Current;
end Parse_Port;
------------------
-- Parse_Scheme --
------------------
procedure Parse_Scheme
(Self : in out IRI'Class;
Image : League.Strings.Universal_String;
First : in out Positive;
Success : out Boolean)
is
-- [RFC 3987]
--
-- scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
C : League.Characters.Universal_Character;
Current : Positive := First;
begin
-- Check that at least two characters is available (one character of
-- the scheme and colon delimiter).
if Image.Length <= Current then
Success := False;
return;
end if;
-- Check first character of the scheme.
C := Image.Element (Current);
if not Is_ALPHA (C) then
Success := False;
return;
else
-- Convert to lowercase and append to result.
Self.Scheme.Append (C.Simple_Lowercase_Mapping);
Current := Current + 1;
end if;
while Current <= Image.Length loop
C := Image.Element (Current);
exit when
not Is_ALPHA (C)
and not IS_DIGIT (C)
and C /= Plus_Sign
and C /= Hyphen_Minus
and C /= Full_Stop;
-- Convert to lowercase and append to result.
Self.Scheme.Append (C.Simple_Lowercase_Mapping);
Current := Current + 1;
end loop;
-- Check that scheme is terminated by colon delimiter.
if C /= Colon then
Self.Scheme.Clear;
Success := False;
return;
end if;
Success := True;
First := Current;
end Parse_Scheme;
end IRI_Parser;
-----------------
-- Is_Absolute --
-----------------
function Is_Absolute (Self : IRI'Class) return Boolean is
begin
return not Self.Scheme.Is_Empty;
end Is_Absolute;
--------------
-- Is_ALPHA --
--------------
function Is_ALPHA
(C : League.Characters.Universal_Character) return Boolean is
begin
return
(Latin_Capital_Letter_A <= C and C <= Latin_Capital_Letter_Z)
or (Latin_Small_Letter_A <= C and C <= Latin_Small_Letter_Z);
end Is_ALPHA;
--------------
-- Is_DIGIT --
--------------
function Is_DIGIT
(C : League.Characters.Universal_Character) return Boolean is
begin
return Digit_Zero <= C and C <= Digit_Nine;
end Is_DIGIT;
--------------------
-- Is_IUnreserved --
--------------------
function Is_IUnreserved
(C : League.Characters.Universal_Character) return Boolean is
begin
-- [RFC 3987]
--
-- iunreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" / ucschar
--
-- ucschar = %xA0-D7FF / %xF900-FDCF / %xFDF0-FFEF
-- / %x10000-1FFFD / %x20000-2FFFD / %x30000-3FFFD
-- / %x40000-4FFFD / %x50000-5FFFD / %x60000-6FFFD
-- / %x70000-7FFFD / %x80000-8FFFD / %x90000-9FFFD
-- / %xA0000-AFFFD / %xB0000-BFFFD / %xC0000-CFFFD
-- / %xD0000-DFFFD / %xE1000-EFFFD
-- XXX Compatibility with Legacy IRI must be checked!
-- XXX Not implemented completely.
return
Is_ALPHA (C)
or (Digit_Zero <= C and C <= Digit_Nine)
or C = Hyphen_Minus
or C = Full_Stop
or C = Low_Line
or C = Tilde
or (C.Is_Valid and No_Break_Space <= C);
end Is_IUnreserved;
----------------------
-- Is_Path_Absolute --
----------------------
function Is_Path_Absolute (Self : IRI'Class) return Boolean is
begin
return Self.Path_Is_Absolute;
end Is_Path_Absolute;
-------------------
-- Is_Sub_Delims --
-------------------
function Is_Sub_Delims
(C : League.Characters.Universal_Character) return Boolean is
begin
-- sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
-- / "*" / "+" / "," / ";" / "="
return
C = Exclamation_Mark
or C = Dollar_Sign
or C = Ampersand
or C = Apostrophe
or C = Left_Parenthesis
or C = Right_Parenthesis
or C = Asterisk
or C = Plus_Sign
or C = Comma
or C = Semicolon
or C = Equals_Sign;
end Is_Sub_Delims;
--------------
-- Is_Valid --
--------------
function Is_Valid (Self : IRI'Class) return Boolean is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Is_Valid unimplemented");
raise Program_Error;
return Is_Valid (Self);
end Is_Valid;
--------------
-- Get_Host --
--------------
function Get_Host
(Self : IRI'Class) return League.Strings.Universal_String is
begin
return Self.Host;
end Get_Host;
--------------
-- Get_Path --
--------------
function Get_Path
(Self : IRI'Class) return League.String_Vectors.Universal_String_Vector is
begin
return Self.Path;
end Get_Path;
--------------
-- Get_Port --
--------------
function Get_Port
(Self : IRI'Class; Default : Natural := 0) return Natural is
begin
return Self.Port;
end Get_Port;
----------------
-- Get_Scheme --
----------------
function Get_Scheme
(Self : IRI'Class) return League.Strings.Universal_String is
begin
return Self.Scheme;
end Get_Scheme;
--------------------
-- Normalize_Path --
--------------------
procedure Normalize_Path (Self : in out IRI'Class) is
begin
-- XXX Not implemented.
null;
end Normalize_Path;
-----------
-- Query --
-----------
function Query (Self : IRI'Class) return League.Strings.Universal_String is
begin
return Self.Query;
end Query;
-------------
-- Resolve --
-------------
function Resolve (Self : IRI'Class; Relative : IRI'Class) return IRI is
begin
return Result : IRI := IRI (Relative) do
if Result.Scheme.Is_Empty then
Result.Scheme := Self.Scheme;
end if;
if not Result.Has_Authority then
Result.Has_Authority := Self.Has_Authority;
end if;
if Result.User_Info.Is_Empty then
Result.User_Info := Self.User_Info;
end if;
if Result.Host.Is_Empty then
Result.Host := Self.Host;
end if;
if Result.Port = 0 then
Result.Port := Self.Port;
end if;
if not Result.Path_Is_Absolute then
Result.Path.Prepend (Self.Path);
Result.Path_Is_Absolute := Self.Path_Is_Absolute;
end if;
Normalize_Path (Result);
end return;
end Resolve;
-----------------------
-- Set_Absolute_Path --
-----------------------
procedure Set_Absolute_Path
(Self : in out IRI'Class;
To : League.String_Vectors.Universal_String_Vector) is
begin
Self.Path := To;
Self.Path_Is_Absolute := True;
end Set_Absolute_Path;
-------------------
-- Set_Authority --
-------------------
procedure Set_Authority
(Self : in out IRI'Class; To : League.Strings.Universal_String) is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Set_Authority unimplemented");
raise Program_Error;
end Set_Authority;
-----------------
-- Set_Encoded --
-----------------
procedure Set_Encoded
(Self : in out IRI'Class;
To : League.Stream_Element_Vectors.Stream_Element_Vector)
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Set_Encoded unimplemented");
raise Program_Error;
end Set_Encoded;
---------------------------
-- Set_Encoded_Authority --
---------------------------
procedure Set_Encoded_Authority
(Self : in out IRI'Class;
To : League.Stream_Element_Vectors.Stream_Element_Vector) is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Set_Encoded_Authority unimplemented");
raise Program_Error;
end Set_Encoded_Authority;
--------------------------
-- Set_Encoded_Fragment --
--------------------------
procedure Set_Encoded_Fragment
(Self : in out IRI'Class;
To : League.Stream_Element_Vectors.Stream_Element_Vector) is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Set_Encoded_Fragment unimplemented");
raise Program_Error;
end Set_Encoded_Fragment;
----------------------
-- Set_Encoded_Host --
----------------------
procedure Set_Encoded_Host
(Self : in out IRI'Class;
To : League.Stream_Element_Vectors.Stream_Element_Vector) is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Set_Encoded_Host unimplemented");
raise Program_Error;
end Set_Encoded_Host;
----------------------
-- Set_Encoded_Path --
----------------------
procedure Set_Encoded_Path
(Self : in out IRI'Class;
To : League.Stream_Element_Vectors.Stream_Element_Vector) is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Set_Encoded_Path unimplemented");
raise Program_Error;
end Set_Encoded_Path;
-----------------------
-- Set_Encoded_Query --
-----------------------
procedure Set_Encoded_Query
(Self : in out IRI'Class;
To : League.Stream_Element_Vectors.Stream_Element_Vector) is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Set_Encoded_Query unimplemented");
raise Program_Error;
end Set_Encoded_Query;
------------------------
-- Set_Encoded_Scheme --
------------------------
procedure Set_Encoded_Scheme
(Self : in out IRI'Class;
To : League.Stream_Element_Vectors.Stream_Element_Vector) is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Set_Encoded_Scheme unimplemented");
raise Program_Error;
end Set_Encoded_Scheme;
---------------------------
-- Set_Encoded_User_Info --
---------------------------
procedure Set_Encoded_User_Info
(Self : in out IRI'Class;
To : League.Stream_Element_Vectors.Stream_Element_Vector) is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Set_Encoded_User_Info unimplemented");
raise Program_Error;
end Set_Encoded_User_Info;
------------------
-- Set_Fragment --
------------------
procedure Set_Fragment
(Self : in out IRI'Class; To : League.Strings.Universal_String) is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Set_Fragment unimplemented");
raise Program_Error;
end Set_Fragment;
--------------
-- Set_Host --
--------------
procedure Set_Host
(Self : in out IRI'Class; To : League.Strings.Universal_String) is
begin
-- [RFC 3987]
--
-- ihost = IP-literal / IPv4address / ireg-name
--
-- IP-literal = "[" ( IPv6address / IPvFuture ) "]"
--
-- IPv4address = dec-octet "." dec-octet "." dec-octet "."
-- dec-octet
--
-- ireg-name = *( iunreserved / pct-encoded / sub-delims )
-- XXX Check for valid 'ihost' production should be added.
Self.Has_Authority := True;
Self.Host := To;
end Set_Host;
-------------
-- Set_IRI --
-------------
procedure Set_IRI
(Self : in out IRI'Class; To : League.Strings.Universal_String) is
begin
IRI_Parser.Parse_IRI_Reference (Self, To);
end Set_IRI;
-----------------------
-- Set_Path_Absolute --
-----------------------
procedure Set_Path_Absolute (Self : in out IRI'Class; To : Boolean) is
begin
Self.Path_Is_Absolute := To;
end Set_Path_Absolute;
--------------
-- Set_Port --
--------------
procedure Set_Port (Self : in out IRI'Class; To : Natural) is
begin
Self.Port := To;
end Set_Port;
---------------
-- Set_Query --
---------------
procedure Set_Query
(Self : in out IRI'Class; To : League.Strings.Universal_String) is
begin
Self.Query := To;
end Set_Query;
-----------------------
-- Set_Relative_Path --
-----------------------
procedure Set_Relative_Path
(Self : in out IRI'Class;
To : League.String_Vectors.Universal_String_Vector) is
begin
Self.Path := To;
Self.Path_Is_Absolute := False;
end Set_Relative_Path;
----------------
-- Set_Scheme --
----------------
procedure Set_Scheme
(Self : in out IRI'Class; To : League.Strings.Universal_String)
is
C : League.Characters.Universal_Character;
begin
if not To.Is_Empty then
-- [RFC 3987]
--
-- scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
if not Is_ALPHA (To (1)) then
raise Constraint_Error with "Invalid scheme";
end if;
for J in 2 .. To.Length loop
C := To (J);
if not Is_ALPHA (C)
and then not Is_DIGIT (C)
and then C /= Plus_Sign
and then C /= Hyphen_Minus
and then C /= Full_Stop
then
raise Constraint_Error with "Invalid scheme";
end if;
end loop;
end if;
Self.Scheme := To;
end Set_Scheme;
-------------------
-- Set_User_Info --
-------------------
procedure Set_User_Info
(Self : in out IRI'Class; To : League.Strings.Universal_String) is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Set_User_Info unimplemented");
raise Program_Error;
end Set_User_Info;
----------------
-- To_Encoded --
----------------
function To_Encoded
(Self : IRI'Class)
return League.Stream_Element_Vectors.Stream_Element_Vector is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "To_Encoded unimplemented");
raise Program_Error;
return To_Encoded (Self);
end To_Encoded;
-------------------------
-- To_Universal_String --
-------------------------
function To_Universal_String
(Self : IRI'Class) return League.Strings.Universal_String
is
procedure Append_IPChar
(Result : in out League.Strings.Universal_String;
Character : League.Characters.Universal_Character);
-- Append character. All characters except ipchar are encoded.
procedure Append_ISegment
(Result : in out League.Strings.Universal_String;
Segment : League.Strings.Universal_String);
-- Append isegment. Encode all non ipchar characters.
-------------------
-- Append_IPChar --
-------------------
procedure Append_IPChar
(Result : in out League.Strings.Universal_String;
Character : League.Characters.Universal_Character)
is
To_HEX :
constant array (Natural range 0 .. 15)
of League.Characters.Universal_Character
:= (Digit_Zero,
Digit_One,
Digit_Two,
Digit_Three,
Digit_Four,
Digit_Five,
Digit_Six,
Digit_Seven,
Digit_Eight,
Digit_Nine,
Latin_Capital_Letter_A,
Latin_Capital_Letter_B,
Latin_Capital_Letter_C,
Latin_Capital_Letter_D,
Latin_Capital_Letter_E,
Latin_Capital_Letter_F);
begin
-- [RFC 3987]
--
-- ipchar = iunreserved / pct-encoded / sub-delims / ":"
-- / "@"
--
-- Note: isegment-nz-nc doesn't allow ":" character, because it
-- conflicts with scheme production.
if Is_IUnreserved (Character)
or else Is_Sub_Delims (Character)
or else Character = Colon
or else (not Self.Scheme.Is_Empty
and then Character = Commercial_At)
then
Result.Append (Character);
else
declare
Code : constant Natural
:= Wide_Wide_Character'Pos (Character.To_Wide_Wide_Character);
begin
if Code <= 16#7F# then
Result.Append (Percent_Sign);
Result.Append (To_Hex (Code / 16 mod 16));
Result.Append (To_Hex (Code mod 16));
else
raise Program_Error;
end if;
end;
end if;
end Append_IPChar;
---------------------
-- Append_ISegment --
---------------------
procedure Append_ISegment
(Result : in out League.Strings.Universal_String;
Segment : League.Strings.Universal_String) is
begin
for J in 1 .. Segment.Length loop
Append_IPChar (Result, Segment (J));
end loop;
end Append_ISegment;
begin
return Result : League.Strings.Universal_String do
-- Append scheme when defined.
if not Self.Scheme.Is_Empty then
Result.Append (Self.Scheme);
Result.Append (Colon);
end if;
-- Append two solidus and authority when present.
if Self.Has_Authority then
Result.Append (Solidus);
Result.Append (Solidus);
Result.Append (Self.Authority);
end if;
-- Append path.
for J in 1 .. Self.Path.Length loop
if J /= 1 or (J = 1 and Self.Path_Is_Absolute) then
Result.Append (Solidus);
end if;
Append_ISegment (Result, Self.Path.Element (J));
end loop;
-- Append query.
if not Self.Query.Is_Empty then
Result.Append (Question_Mark);
Result.Append (Self.Query);
end if;
-- Append fragment.
if not Self.Fragment.Is_Empty then
Result.Append (Number_Sign);
Result.Append (Self.Fragment);
end if;
end return;
end To_Universal_String;
---------------
-- User_Info --
---------------
function User_Info
(Self : IRI'Class) return League.Strings.Universal_String is
begin
return Self.User_Info;
end User_Info;
end League.IRIs;
|
-- { dg-do run }
with Init11; use Init11;
with Text_IO; use Text_IO;
with Dump;
procedure U11 is
Local_R1 : R1;
Local_R2 : R2;
C1 : My_Integer;
C2 : My_Integer;
begin
Local_R1 := (I => 1, A => (16#AB0012#, 16#CD0034#, 16#EF0056#));
Put ("Local_R1 :");
Dump (Local_R1'Address, R1'Max_Size_In_Storage_Elements);
New_Line;
-- { dg-output "Local_R1 : 01 00 00 00 12 00 ab 00 34 00 cd 00 56 00 ef 00.*\n" }
Local_R2 := (I => 1, A => (16#AB0012#, 16#CD0034#, 16#EF0056#));
Put ("Local_R2 :");
Dump (Local_R2'Address, R2'Max_Size_In_Storage_Elements);
New_Line;
-- { dg-output "Local_R2 : 00 00 00 01 00 ab 00 12 00 cd 00 34 00 ef 00 56.*\n" }
C1 := Local_R1.A (Integer(Local_R1.I));
Put_Line ("C1 :" & C1'Img);
-- { dg-output "C1 : 11206674.*\n" }
Local_R1.I := Local_R1.I + 1;
C1 := Local_R1.A (Integer(Local_R1.I));
Put_Line ("C1 :" & C1'Img);
-- { dg-output "C1 : 13434932.*\n" }
C2 := Local_R2.A (Integer(Local_R2.I));
Put_Line ("C2 :" & C2'Img);
-- { dg-output "C2 : 11206674.*\n" }
Local_R2.I := Local_R2.I + 1;
C2 := Local_R2.A (Integer(Local_R2.I));
Put_Line ("C2 :" & C2'Img);
-- { dg-output "C2 : 13434932.*\n" }
end;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- A D A . C A L E N D A R --
-- --
-- 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. --
-- --
------------------------------------------------------------------------------
with Ada.Unchecked_Conversion;
with Interfaces.C;
with System.OS_Primitives;
package body Ada.Calendar with
SPARK_Mode => Off
is
--------------------------
-- Implementation Notes --
--------------------------
-- In complex algorithms, some variables of type Ada.Calendar.Time carry
-- suffix _S or _N to denote units of seconds or nanoseconds.
--
-- Because time is measured in different units and from different origins
-- on various targets, a system independent model is incorporated into
-- Ada.Calendar. The idea behind the design is to encapsulate all target
-- dependent machinery in a single package, thus providing a uniform
-- interface to all existing and any potential children.
-- package Ada.Calendar
-- procedure Split (5 parameters) -------+
-- | Call from local routine
-- private |
-- package Formatting_Operations |
-- procedure Split (11 parameters) <--+
-- end Formatting_Operations |
-- end Ada.Calendar |
-- |
-- package Ada.Calendar.Formatting | Call from child routine
-- procedure Split (9 or 10 parameters) -+
-- end Ada.Calendar.Formatting
-- The behavior of the interfacing routines is controlled via various
-- flags. All new Ada 2005 types from children of Ada.Calendar are
-- emulated by a similar type. For instance, type Day_Number is replaced
-- by Integer in various routines. One ramification of this model is that
-- the caller site must perform validity checks on returned results.
-- The end result of this model is the lack of target specific files per
-- child of Ada.Calendar (e.g. a-calfor).
-----------------------
-- Local Subprograms --
-----------------------
procedure Check_Within_Time_Bounds (T : Time_Rep);
-- Ensure that a time representation value falls withing the bounds of Ada
-- time. Leap seconds support is taken into account.
procedure Cumulative_Leap_Seconds
(Start_Date : Time_Rep;
End_Date : Time_Rep;
Elapsed_Leaps : out Natural;
Next_Leap : out Time_Rep);
-- Elapsed_Leaps is the sum of the leap seconds that have occurred on or
-- after Start_Date and before (strictly before) End_Date. Next_Leap_Sec
-- represents the next leap second occurrence on or after End_Date. If
-- there are no leaps seconds after End_Date, End_Of_Time is returned.
-- End_Of_Time can be used as End_Date to count all the leap seconds that
-- have occurred on or after Start_Date.
--
-- Note: Any sub seconds of Start_Date and End_Date are discarded before
-- the calculations are done. For instance: if 113 seconds is a leap
-- second (it isn't) and 113.5 is input as an End_Date, the leap second
-- at 113 will not be counted in Leaps_Between, but it will be returned
-- as Next_Leap_Sec. Thus, if the caller wants to know if the End_Date is
-- a leap second, the comparison should be:
--
-- End_Date >= Next_Leap_Sec;
--
-- After_Last_Leap is designed so that this comparison works without
-- having to first check if Next_Leap_Sec is a valid leap second.
function Duration_To_Time_Rep is
new Ada.Unchecked_Conversion (Duration, Time_Rep);
-- Convert a duration value into a time representation value
function Time_Rep_To_Duration is
new Ada.Unchecked_Conversion (Time_Rep, Duration);
-- Convert a time representation value into a duration value
function UTC_Time_Offset
(Date : Time;
Is_Historic : Boolean) return Long_Integer;
-- This routine acts as an Ada wrapper around __gnat_localtime_tzoff which
-- in turn utilizes various OS-dependent mechanisms to calculate the time
-- zone offset of a date. Formal parameter Date represents an arbitrary
-- time stamp, either in the past, now, or in the future. If the flag
-- Is_Historic is set, this routine would try to calculate to the best of
-- the OS's abilities the time zone offset that was or will be in effect
-- on Date. If the flag is set to False, the routine returns the current
-- time zone with Date effectively set to Clock.
--
-- NOTE: Targets which support localtime_r will aways return a historic
-- time zone even if flag Is_Historic is set to False because this is how
-- localtime_r operates.
-----------------
-- Local Types --
-----------------
-- An integer time duration. The type is used whenever a positive elapsed
-- duration is needed, for instance when splitting a time value. Here is
-- how Time_Rep and Time_Dur are related:
-- 'First Ada_Low Ada_High 'Last
-- Time_Rep: +-------+------------------------+---------+
-- Time_Dur: +------------------------+---------+
-- 0 'Last
type Time_Dur is range 0 .. 2 ** 63 - 1;
--------------------------
-- Leap seconds control --
--------------------------
Flag : Integer;
pragma Import (C, Flag, "__gl_leap_seconds_support");
-- This imported value is used to determine whether the compilation had
-- binder flag "-y" present which enables leap seconds. A value of zero
-- signifies no leap seconds support while a value of one enables support.
Leap_Support : constant Boolean := (Flag = 1);
-- Flag to controls the usage of leap seconds in all Ada.Calendar routines
Leap_Seconds_Count : constant Natural := 27;
---------------------
-- Local Constants --
---------------------
Ada_Min_Year : constant Year_Number := Year_Number'First;
Secs_In_Four_Years : constant := (3 * 365 + 366) * Secs_In_Day;
Secs_In_Non_Leap_Year : constant := 365 * Secs_In_Day;
Nanos_In_Four_Years : constant := Secs_In_Four_Years * Nano;
-- Lower and upper bound of Ada time. Note that the lower and upper bound
-- account for the non-leap centennial years. See "Implementation of Time"
-- in the spec for what the zero value represents.
Ada_Low : constant Time_Rep := -(61 * 366 + 188 * 365) * Nanos_In_Day;
Ada_High : constant Time_Rep := (60 * 366 + 190 * 365) * Nanos_In_Day;
-- Even though the upper bound of time is 2399-12-31 23:59:59.999999999
-- UTC, it must be increased to include all leap seconds.
Ada_High_And_Leaps : constant Time_Rep :=
Ada_High + Time_Rep (Leap_Seconds_Count) * Nano;
-- Two constants used in the calculations of elapsed leap seconds.
-- End_Of_Time is later than Ada_High in time zone -28. Start_Of_Time
-- is earlier than Ada_Low in time zone +28.
End_Of_Time : constant Time_Rep :=
Ada_High + Time_Rep (3) * Nanos_In_Day;
Start_Of_Time : constant Time_Rep :=
Ada_Low - Time_Rep (3) * Nanos_In_Day;
-- The Unix lower time bound expressed as nanoseconds since the start of
-- Ada time in UTC.
Unix_Min : constant Time_Rep :=
Ada_Low + Time_Rep (17 * 366 + 52 * 365) * Nanos_In_Day;
-- The Unix upper time bound expressed as nanoseconds since the start of
-- Ada time in UTC.
Unix_Max : constant Time_Rep :=
Ada_Low + Time_Rep (34 * 366 + 102 * 365) * Nanos_In_Day +
Time_Rep (Leap_Seconds_Count) * Nano;
Cumulative_Days_Before_Month :
constant array (Month_Number) of Natural :=
(0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334);
-- The following table contains the hard time values of all existing leap
-- seconds. The values are produced by the utility program xleaps.adb. This
-- must be updated when additional leap second times are defined.
Leap_Second_Times : constant array (1 .. Leap_Seconds_Count) of Time_Rep :=
(-5601484800000000000,
-5585587199000000000,
-5554051198000000000,
-5522515197000000000,
-5490979196000000000,
-5459356795000000000,
-5427820794000000000,
-5396284793000000000,
-5364748792000000000,
-5317487991000000000,
-5285951990000000000,
-5254415989000000000,
-5191257588000000000,
-5112287987000000000,
-5049129586000000000,
-5017593585000000000,
-4970332784000000000,
-4938796783000000000,
-4907260782000000000,
-4859827181000000000,
-4812566380000000000,
-4765132779000000000,
-4544207978000000000,
-4449513577000000000,
-4339180776000000000,
-4244572775000000000,
-4197052774000000000);
---------
-- "+" --
---------
function "+" (Left : Time; Right : Duration) return Time is
pragma Unsuppress (Overflow_Check);
Left_N : constant Time_Rep := Time_Rep (Left);
begin
return Time (Left_N + Duration_To_Time_Rep (Right));
exception
when Constraint_Error =>
raise Time_Error;
end "+";
function "+" (Left : Duration; Right : Time) return Time is
begin
return Right + Left;
end "+";
---------
-- "-" --
---------
function "-" (Left : Time; Right : Duration) return Time is
pragma Unsuppress (Overflow_Check);
Left_N : constant Time_Rep := Time_Rep (Left);
begin
return Time (Left_N - Duration_To_Time_Rep (Right));
exception
when Constraint_Error =>
raise Time_Error;
end "-";
function "-" (Left : Time; Right : Time) return Duration is
pragma Unsuppress (Overflow_Check);
Dur_Low : constant Time_Rep := Duration_To_Time_Rep (Duration'First);
Dur_High : constant Time_Rep := Duration_To_Time_Rep (Duration'Last);
-- The bounds of type Duration expressed as time representations
Res_N : Time_Rep;
begin
Res_N := Time_Rep (Left) - Time_Rep (Right);
-- Due to the extended range of Ada time, "-" is capable of producing
-- results which may exceed the range of Duration. In order to prevent
-- the generation of bogus values by the Unchecked_Conversion, we apply
-- the following check.
if Res_N < Dur_Low or else Res_N > Dur_High then
raise Time_Error;
end if;
return Time_Rep_To_Duration (Res_N);
exception
when Constraint_Error =>
raise Time_Error;
end "-";
---------
-- "<" --
---------
function "<" (Left, Right : Time) return Boolean is
begin
return Time_Rep (Left) < Time_Rep (Right);
end "<";
----------
-- "<=" --
----------
function "<=" (Left, Right : Time) return Boolean is
begin
return Time_Rep (Left) <= Time_Rep (Right);
end "<=";
---------
-- ">" --
---------
function ">" (Left, Right : Time) return Boolean is
begin
return Time_Rep (Left) > Time_Rep (Right);
end ">";
----------
-- ">=" --
----------
function ">=" (Left, Right : Time) return Boolean is
begin
return Time_Rep (Left) >= Time_Rep (Right);
end ">=";
------------------------------
-- Check_Within_Time_Bounds --
------------------------------
procedure Check_Within_Time_Bounds (T : Time_Rep) is
begin
if Leap_Support then
if T < Ada_Low or else T > Ada_High_And_Leaps then
raise Time_Error;
end if;
else
if T < Ada_Low or else T > Ada_High then
raise Time_Error;
end if;
end if;
end Check_Within_Time_Bounds;
-----------
-- Clock --
-----------
function Clock return Time is
Elapsed_Leaps : Natural;
Next_Leap_N : Time_Rep;
-- The system clock returns the time in UTC since the Unix Epoch of
-- 1970-01-01 00:00:00.0. We perform an origin shift to the Ada Epoch
-- by adding the number of nanoseconds between the two origins.
Res_N : Time_Rep :=
Duration_To_Time_Rep (System.OS_Primitives.Clock) + Unix_Min;
begin
-- If the target supports leap seconds, determine the number of leap
-- seconds elapsed until this moment.
if Leap_Support then
Cumulative_Leap_Seconds
(Start_Of_Time, Res_N, Elapsed_Leaps, Next_Leap_N);
-- The system clock may fall exactly on a leap second
if Res_N >= Next_Leap_N then
Elapsed_Leaps := Elapsed_Leaps + 1;
end if;
-- The target does not support leap seconds
else
Elapsed_Leaps := 0;
end if;
Res_N := Res_N + Time_Rep (Elapsed_Leaps) * Nano;
return Time (Res_N);
end Clock;
-----------------------------
-- Cumulative_Leap_Seconds --
-----------------------------
procedure Cumulative_Leap_Seconds
(Start_Date : Time_Rep;
End_Date : Time_Rep;
Elapsed_Leaps : out Natural;
Next_Leap : out Time_Rep)
is
End_Index : Positive;
End_T : Time_Rep := End_Date;
Start_Index : Positive;
Start_T : Time_Rep := Start_Date;
begin
-- Both input dates must be normalized to UTC
pragma Assert (Leap_Support and then End_Date >= Start_Date);
Next_Leap := End_Of_Time;
-- Make sure that the end date does not exceed the upper bound
-- of Ada time.
if End_Date > Ada_High then
End_T := Ada_High;
end if;
-- Remove the sub seconds from both dates
Start_T := Start_T - (Start_T mod Nano);
End_T := End_T - (End_T mod Nano);
-- Some trivial cases:
-- Leap 1 . . . Leap N
-- ---+========+------+############+-------+========+-----
-- Start_T End_T Start_T End_T
if End_T < Leap_Second_Times (1) then
Elapsed_Leaps := 0;
Next_Leap := Leap_Second_Times (1);
elsif Start_T > Leap_Second_Times (Leap_Seconds_Count) then
Elapsed_Leaps := 0;
Next_Leap := End_Of_Time;
else
-- Perform the calculations only if the start date is within the leap
-- second occurrences table.
-- 1 2 N - 1 N
-- +----+----+-- . . . --+-------+---+
-- | T1 | T2 | | N - 1 | N |
-- +----+----+-- . . . --+-------+---+
-- ^ ^
-- | Start_Index | End_Index
-- +-------------------+
-- Leaps_Between
-- The idea behind the algorithm is to iterate and find two
-- closest dates which are after Start_T and End_T. Their
-- corresponding index difference denotes the number of leap
-- seconds elapsed.
Start_Index := 1;
loop
exit when Leap_Second_Times (Start_Index) >= Start_T;
Start_Index := Start_Index + 1;
end loop;
End_Index := Start_Index;
loop
exit when End_Index > Leap_Seconds_Count
or else Leap_Second_Times (End_Index) >= End_T;
End_Index := End_Index + 1;
end loop;
if End_Index <= Leap_Seconds_Count then
Next_Leap := Leap_Second_Times (End_Index);
end if;
Elapsed_Leaps := End_Index - Start_Index;
end if;
end Cumulative_Leap_Seconds;
---------
-- Day --
---------
function Day (Date : Time) return Day_Number is
D : Day_Number;
Y : Year_Number;
M : Month_Number;
S : Day_Duration;
pragma Unreferenced (Y, M, S);
begin
Split (Date, Y, M, D, S);
return D;
end Day;
------------------
-- Epoch_Offset --
------------------
function Epoch_Offset return Time_Rep is
begin
return (136 * 365 + 44 * 366) * Nanos_In_Day;
end Epoch_Offset;
-------------
-- Is_Leap --
-------------
function Is_Leap (Year : Year_Number) return Boolean is
begin
-- Leap centennial years
if Year mod 400 = 0 then
return True;
-- Non-leap centennial years
elsif Year mod 100 = 0 then
return False;
-- Regular years
else
return Year mod 4 = 0;
end if;
end Is_Leap;
-----------
-- Month --
-----------
function Month (Date : Time) return Month_Number is
Y : Year_Number;
M : Month_Number;
D : Day_Number;
S : Day_Duration;
pragma Unreferenced (Y, D, S);
begin
Split (Date, Y, M, D, S);
return M;
end Month;
-------------
-- Seconds --
-------------
function Seconds (Date : Time) return Day_Duration is
Y : Year_Number;
M : Month_Number;
D : Day_Number;
S : Day_Duration;
pragma Unreferenced (Y, M, D);
begin
Split (Date, Y, M, D, S);
return S;
end Seconds;
-----------
-- Split --
-----------
procedure Split
(Date : Time;
Year : out Year_Number;
Month : out Month_Number;
Day : out Day_Number;
Seconds : out Day_Duration)
is
H : Integer;
M : Integer;
Se : Integer;
Ss : Duration;
Le : Boolean;
pragma Unreferenced (H, M, Se, Ss, Le);
begin
-- Even though the input time zone is UTC (0), the flag Use_TZ will
-- ensure that Split picks up the local time zone.
Formatting_Operations.Split
(Date => Date,
Year => Year,
Month => Month,
Day => Day,
Day_Secs => Seconds,
Hour => H,
Minute => M,
Second => Se,
Sub_Sec => Ss,
Leap_Sec => Le,
Use_TZ => False,
Is_Historic => True,
Time_Zone => 0);
-- Validity checks
if not Year'Valid or else
not Month'Valid or else
not Day'Valid or else
not Seconds'Valid
then
raise Time_Error;
end if;
end Split;
-------------
-- Time_Of --
-------------
function Time_Of
(Year : Year_Number;
Month : Month_Number;
Day : Day_Number;
Seconds : Day_Duration := 0.0) return Time
is
-- The values in the following constants are irrelevant, they are just
-- placeholders; the choice of constructing a Day_Duration value is
-- controlled by the Use_Day_Secs flag.
H : constant Integer := 1;
M : constant Integer := 1;
Se : constant Integer := 1;
Ss : constant Duration := 0.1;
begin
-- Validity checks
if not Year'Valid or else
not Month'Valid or else
not Day'Valid or else
not Seconds'Valid
then
raise Time_Error;
end if;
-- Even though the input time zone is UTC (0), the flag Use_TZ will
-- ensure that Split picks up the local time zone.
return
Formatting_Operations.Time_Of
(Year => Year,
Month => Month,
Day => Day,
Day_Secs => Seconds,
Hour => H,
Minute => M,
Second => Se,
Sub_Sec => Ss,
Leap_Sec => False,
Use_Day_Secs => True,
Use_TZ => False,
Is_Historic => True,
Time_Zone => 0);
end Time_Of;
---------------------
-- UTC_Time_Offset --
---------------------
function UTC_Time_Offset
(Date : Time;
Is_Historic : Boolean) return Long_Integer
is
-- The following constants denote February 28 during non-leap centennial
-- years, the units are nanoseconds.
T_2100_2_28 : constant Time_Rep := Ada_Low +
(Time_Rep (49 * 366 + 150 * 365 + 59) * Secs_In_Day +
Time_Rep (Leap_Seconds_Count)) * Nano;
T_2200_2_28 : constant Time_Rep := Ada_Low +
(Time_Rep (73 * 366 + 226 * 365 + 59) * Secs_In_Day +
Time_Rep (Leap_Seconds_Count)) * Nano;
T_2300_2_28 : constant Time_Rep := Ada_Low +
(Time_Rep (97 * 366 + 302 * 365 + 59) * Secs_In_Day +
Time_Rep (Leap_Seconds_Count)) * Nano;
-- 56 years (14 leap years + 42 non-leap years) in nanoseconds:
Nanos_In_56_Years : constant := (14 * 366 + 42 * 365) * Nanos_In_Day;
type int_Pointer is access all Interfaces.C.int;
type long_Pointer is access all Interfaces.C.long;
type time_t is
range -(2 ** (Standard'Address_Size - Integer'(1))) ..
+(2 ** (Standard'Address_Size - Integer'(1)) - 1);
type time_t_Pointer is access all time_t;
procedure localtime_tzoff
(timer : time_t_Pointer;
is_historic : int_Pointer;
off : long_Pointer);
pragma Import (C, localtime_tzoff, "__gnat_localtime_tzoff");
-- This routine is a interfacing wrapper around the library function
-- __gnat_localtime_tzoff. Parameter 'timer' represents a Unix-based
-- time equivalent of the input date. If flag 'is_historic' is set, this
-- routine would try to calculate to the best of the OS's abilities the
-- time zone offset that was or will be in effect on 'timer'. If the
-- flag is set to False, the routine returns the current time zone
-- regardless of what 'timer' designates. Parameter 'off' captures the
-- UTC offset of 'timer'.
Adj_Cent : Integer;
Date_N : Time_Rep;
Flag : aliased Interfaces.C.int;
Offset : aliased Interfaces.C.long;
Secs_T : aliased time_t;
-- Start of processing for UTC_Time_Offset
begin
Date_N := Time_Rep (Date);
-- Dates which are 56 years apart fall on the same day, day light saving
-- and so on. Non-leap centennial years violate this rule by one day and
-- as a consequence, special adjustment is needed.
Adj_Cent :=
(if Date_N <= T_2100_2_28 then 0
elsif Date_N <= T_2200_2_28 then 1
elsif Date_N <= T_2300_2_28 then 2
else 3);
if Adj_Cent > 0 then
Date_N := Date_N - Time_Rep (Adj_Cent) * Nanos_In_Day;
end if;
-- Shift the date within bounds of Unix time
while Date_N < Unix_Min loop
Date_N := Date_N + Nanos_In_56_Years;
end loop;
while Date_N >= Unix_Max loop
Date_N := Date_N - Nanos_In_56_Years;
end loop;
-- Perform a shift in origins from Ada to Unix
Date_N := Date_N - Unix_Min;
-- Convert the date into seconds
Secs_T := time_t (Date_N / Nano);
-- Determine whether to treat the input date as historical or not. A
-- value of "0" signifies that the date is NOT historic.
Flag := (if Is_Historic then 1 else 0);
localtime_tzoff
(Secs_T'Unchecked_Access,
Flag'Unchecked_Access,
Offset'Unchecked_Access);
pragma Annotate (CodePeer, Modified, Offset);
return Long_Integer (Offset);
end UTC_Time_Offset;
----------
-- Year --
----------
function Year (Date : Time) return Year_Number is
Y : Year_Number;
M : Month_Number;
D : Day_Number;
S : Day_Duration;
pragma Unreferenced (M, D, S);
begin
Split (Date, Y, M, D, S);
return Y;
end Year;
-- The following packages assume that Time is a signed 64 bit integer
-- type, the units are nanoseconds and the origin is the start of Ada
-- time (1901-01-01 00:00:00.0 UTC).
---------------------------
-- Arithmetic_Operations --
---------------------------
package body Arithmetic_Operations is
---------
-- Add --
---------
function Add (Date : Time; Days : Long_Integer) return Time is
pragma Unsuppress (Overflow_Check);
Date_N : constant Time_Rep := Time_Rep (Date);
begin
return Time (Date_N + Time_Rep (Days) * Nanos_In_Day);
exception
when Constraint_Error =>
raise Time_Error;
end Add;
----------------
-- Difference --
----------------
procedure Difference
(Left : Time;
Right : Time;
Days : out Long_Integer;
Seconds : out Duration;
Leap_Seconds : out Integer)
is
Res_Dur : Time_Dur;
Earlier : Time_Rep;
Elapsed_Leaps : Natural;
Later : Time_Rep;
Negate : Boolean := False;
Next_Leap_N : Time_Rep;
Sub_Secs : Duration;
Sub_Secs_Diff : Time_Rep;
begin
-- Both input time values are assumed to be in UTC
if Left >= Right then
Later := Time_Rep (Left);
Earlier := Time_Rep (Right);
else
Later := Time_Rep (Right);
Earlier := Time_Rep (Left);
Negate := True;
end if;
-- If the target supports leap seconds, process them
if Leap_Support then
Cumulative_Leap_Seconds
(Earlier, Later, Elapsed_Leaps, Next_Leap_N);
if Later >= Next_Leap_N then
Elapsed_Leaps := Elapsed_Leaps + 1;
end if;
-- The target does not support leap seconds
else
Elapsed_Leaps := 0;
end if;
-- Sub seconds processing. We add the resulting difference to one
-- of the input dates in order to account for any potential rounding
-- of the difference in the next step.
Sub_Secs_Diff := Later mod Nano - Earlier mod Nano;
Earlier := Earlier + Sub_Secs_Diff;
Sub_Secs := Duration (Sub_Secs_Diff) / Nano_F;
-- Difference processing. This operation should be able to calculate
-- the difference between opposite values which are close to the end
-- and start of Ada time. To accommodate the large range, we convert
-- to seconds. This action may potentially round the two values and
-- either add or drop a second. We compensate for this issue in the
-- previous step.
Res_Dur :=
Time_Dur (Later / Nano - Earlier / Nano) - Time_Dur (Elapsed_Leaps);
Days := Long_Integer (Res_Dur / Secs_In_Day);
Seconds := Duration (Res_Dur mod Secs_In_Day) + Sub_Secs;
Leap_Seconds := Integer (Elapsed_Leaps);
if Negate then
Days := -Days;
Seconds := -Seconds;
if Leap_Seconds /= 0 then
Leap_Seconds := -Leap_Seconds;
end if;
end if;
end Difference;
--------------
-- Subtract --
--------------
function Subtract (Date : Time; Days : Long_Integer) return Time is
pragma Unsuppress (Overflow_Check);
Date_N : constant Time_Rep := Time_Rep (Date);
begin
return Time (Date_N - Time_Rep (Days) * Nanos_In_Day);
exception
when Constraint_Error =>
raise Time_Error;
end Subtract;
end Arithmetic_Operations;
---------------------------
-- Conversion_Operations --
---------------------------
package body Conversion_Operations is
-----------------
-- To_Ada_Time --
-----------------
function To_Ada_Time (Unix_Time : Long_Integer) return Time is
pragma Unsuppress (Overflow_Check);
Unix_Rep : constant Time_Rep := Time_Rep (Unix_Time) * Nano;
begin
return Time (Unix_Rep - Epoch_Offset);
exception
when Constraint_Error =>
raise Time_Error;
end To_Ada_Time;
-----------------
-- To_Ada_Time --
-----------------
function To_Ada_Time
(tm_year : Integer;
tm_mon : Integer;
tm_day : Integer;
tm_hour : Integer;
tm_min : Integer;
tm_sec : Integer;
tm_isdst : Integer) return Time
is
pragma Unsuppress (Overflow_Check);
Year : Year_Number;
Month : Month_Number;
Day : Day_Number;
Second : Integer;
Leap : Boolean;
Result : Time_Rep;
begin
-- Input processing
Year := Year_Number (1900 + tm_year);
Month := Month_Number (1 + tm_mon);
Day := Day_Number (tm_day);
-- Step 1: Validity checks of input values
if not Year'Valid or else not Month'Valid or else not Day'Valid
or else tm_hour not in 0 .. 24
or else tm_min not in 0 .. 59
or else tm_sec not in 0 .. 60
or else tm_isdst not in -1 .. 1
then
raise Time_Error;
end if;
-- Step 2: Potential leap second
if tm_sec = 60 then
Leap := True;
Second := 59;
else
Leap := False;
Second := tm_sec;
end if;
-- Step 3: Calculate the time value
Result :=
Time_Rep
(Formatting_Operations.Time_Of
(Year => Year,
Month => Month,
Day => Day,
Day_Secs => 0.0, -- Time is given in h:m:s
Hour => tm_hour,
Minute => tm_min,
Second => Second,
Sub_Sec => 0.0, -- No precise sub second given
Leap_Sec => Leap,
Use_Day_Secs => False, -- Time is given in h:m:s
Use_TZ => True, -- Force usage of explicit time zone
Is_Historic => True,
Time_Zone => 0)); -- Place the value in UTC
-- Step 4: Daylight Savings Time
if tm_isdst = 1 then
Result := Result + Time_Rep (3_600) * Nano;
end if;
return Time (Result);
exception
when Constraint_Error =>
raise Time_Error;
end To_Ada_Time;
-----------------
-- To_Duration --
-----------------
function To_Duration
(tv_sec : Long_Integer;
tv_nsec : Long_Integer) return Duration
is
pragma Unsuppress (Overflow_Check);
begin
return Duration (tv_sec) + Duration (tv_nsec) / Nano_F;
end To_Duration;
------------------------
-- To_Struct_Timespec --
------------------------
procedure To_Struct_Timespec
(D : Duration;
tv_sec : out Long_Integer;
tv_nsec : out Long_Integer)
is
pragma Unsuppress (Overflow_Check);
Secs : Duration;
Nano_Secs : Duration;
begin
-- Seconds extraction, avoid potential rounding errors
Secs := D - 0.5;
tv_sec := Long_Integer (Secs);
-- Nanoseconds extraction
Nano_Secs := D - Duration (tv_sec);
tv_nsec := Long_Integer (Nano_Secs * Nano);
end To_Struct_Timespec;
------------------
-- To_Struct_Tm --
------------------
procedure To_Struct_Tm
(T : Time;
tm_year : out Integer;
tm_mon : out Integer;
tm_day : out Integer;
tm_hour : out Integer;
tm_min : out Integer;
tm_sec : out Integer)
is
pragma Unsuppress (Overflow_Check);
Year : Year_Number;
Month : Month_Number;
Second : Integer;
Day_Secs : Day_Duration;
Sub_Sec : Duration;
Leap_Sec : Boolean;
begin
-- Step 1: Split the input time
Formatting_Operations.Split
(Date => T,
Year => Year,
Month => Month,
Day => tm_day,
Day_Secs => Day_Secs,
Hour => tm_hour,
Minute => tm_min,
Second => Second,
Sub_Sec => Sub_Sec,
Leap_Sec => Leap_Sec,
Use_TZ => True,
Is_Historic => False,
Time_Zone => 0);
-- Step 2: Correct the year and month
tm_year := Year - 1900;
tm_mon := Month - 1;
-- Step 3: Handle leap second occurrences
tm_sec := (if Leap_Sec then 60 else Second);
end To_Struct_Tm;
------------------
-- To_Unix_Time --
------------------
function To_Unix_Time (Ada_Time : Time) return Long_Integer is
pragma Unsuppress (Overflow_Check);
Ada_Rep : constant Time_Rep := Time_Rep (Ada_Time);
begin
return Long_Integer ((Ada_Rep + Epoch_Offset) / Nano);
exception
when Constraint_Error =>
raise Time_Error;
end To_Unix_Time;
end Conversion_Operations;
----------------------
-- Delay_Operations --
----------------------
package body Delay_Operations is
-----------------
-- To_Duration --
-----------------
function To_Duration (Date : Time) return Duration is
pragma Unsuppress (Overflow_Check);
Safe_Ada_High : constant Time_Rep := Ada_High - Epoch_Offset;
-- This value represents a "safe" end of time. In order to perform a
-- proper conversion to Unix duration, we will have to shift origins
-- at one point. For very distant dates, this means an overflow check
-- failure. To prevent this, the function returns the "safe" end of
-- time (roughly 2219) which is still distant enough.
Elapsed_Leaps : Natural;
Next_Leap_N : Time_Rep;
Res_N : Time_Rep;
begin
Res_N := Time_Rep (Date);
-- Step 1: If the target supports leap seconds, remove any leap
-- seconds elapsed up to the input date.
if Leap_Support then
Cumulative_Leap_Seconds
(Start_Of_Time, Res_N, Elapsed_Leaps, Next_Leap_N);
-- The input time value may fall on a leap second occurrence
if Res_N >= Next_Leap_N then
Elapsed_Leaps := Elapsed_Leaps + 1;
end if;
-- The target does not support leap seconds
else
Elapsed_Leaps := 0;
end if;
Res_N := Res_N - Time_Rep (Elapsed_Leaps) * Nano;
-- Step 2: Perform a shift in origins to obtain a Unix equivalent of
-- the input. Guard against very large delay values such as the end
-- of time since the computation will overflow.
Res_N := (if Res_N > Safe_Ada_High then Safe_Ada_High
else Res_N + Epoch_Offset);
return Time_Rep_To_Duration (Res_N);
end To_Duration;
end Delay_Operations;
---------------------------
-- Formatting_Operations --
---------------------------
package body Formatting_Operations is
-----------------
-- Day_Of_Week --
-----------------
function Day_Of_Week (Date : Time) return Integer is
Date_N : constant Time_Rep := Time_Rep (Date);
Time_Zone : constant Long_Integer := UTC_Time_Offset (Date, True);
Ada_Low_N : Time_Rep;
Day_Count : Long_Integer;
Day_Dur : Time_Dur;
High_N : Time_Rep;
Low_N : Time_Rep;
begin
-- As declared, the Ada Epoch is set in UTC. For this calculation to
-- work properly, both the Epoch and the input date must be in the
-- same time zone. The following places the Epoch in the input date's
-- time zone.
Ada_Low_N := Ada_Low - Time_Rep (Time_Zone) * Nano;
if Date_N > Ada_Low_N then
High_N := Date_N;
Low_N := Ada_Low_N;
else
High_N := Ada_Low_N;
Low_N := Date_N;
end if;
-- Determine the elapsed seconds since the start of Ada time
Day_Dur := Time_Dur (High_N / Nano - Low_N / Nano);
-- Count the number of days since the start of Ada time. 1901-01-01
-- GMT was a Tuesday.
Day_Count := Long_Integer (Day_Dur / Secs_In_Day) + 1;
return Integer (Day_Count mod 7);
end Day_Of_Week;
-----------
-- Split --
-----------
procedure Split
(Date : Time;
Year : out Year_Number;
Month : out Month_Number;
Day : out Day_Number;
Day_Secs : out Day_Duration;
Hour : out Integer;
Minute : out Integer;
Second : out Integer;
Sub_Sec : out Duration;
Leap_Sec : out Boolean;
Use_TZ : Boolean;
Is_Historic : Boolean;
Time_Zone : Long_Integer)
is
-- The following constants represent the number of nanoseconds
-- elapsed since the start of Ada time to and including the non
-- leap centennial years.
Year_2101 : constant Time_Rep := Ada_Low +
Time_Rep (49 * 366 + 151 * 365) * Nanos_In_Day;
Year_2201 : constant Time_Rep := Ada_Low +
Time_Rep (73 * 366 + 227 * 365) * Nanos_In_Day;
Year_2301 : constant Time_Rep := Ada_Low +
Time_Rep (97 * 366 + 303 * 365) * Nanos_In_Day;
Date_Dur : Time_Dur;
Date_N : Time_Rep;
Day_Seconds : Natural;
Elapsed_Leaps : Natural;
Four_Year_Segs : Natural;
Hour_Seconds : Natural;
Is_Leap_Year : Boolean;
Next_Leap_N : Time_Rep;
Rem_Years : Natural;
Sub_Sec_N : Time_Rep;
Year_Day : Natural;
begin
Date_N := Time_Rep (Date);
-- Step 1: Leap seconds processing in UTC
if Leap_Support then
Cumulative_Leap_Seconds
(Start_Of_Time, Date_N, Elapsed_Leaps, Next_Leap_N);
Leap_Sec := Date_N >= Next_Leap_N;
if Leap_Sec then
Elapsed_Leaps := Elapsed_Leaps + 1;
end if;
-- The target does not support leap seconds
else
Elapsed_Leaps := 0;
Leap_Sec := False;
end if;
Date_N := Date_N - Time_Rep (Elapsed_Leaps) * Nano;
-- Step 2: Time zone processing. This action converts the input date
-- from GMT to the requested time zone. Applies from Ada 2005 on.
if Use_TZ then
if Time_Zone /= 0 then
Date_N := Date_N + Time_Rep (Time_Zone) * 60 * Nano;
end if;
-- Ada 83 and 95
else
declare
Off : constant Long_Integer :=
UTC_Time_Offset (Time (Date_N), Is_Historic);
begin
Date_N := Date_N + Time_Rep (Off) * Nano;
end;
end if;
-- Step 3: Non-leap centennial year adjustment in local time zone
-- In order for all divisions to work properly and to avoid more
-- complicated arithmetic, we add fake February 29s to dates which
-- occur after a non-leap centennial year.
if Date_N >= Year_2301 then
Date_N := Date_N + Time_Rep (3) * Nanos_In_Day;
elsif Date_N >= Year_2201 then
Date_N := Date_N + Time_Rep (2) * Nanos_In_Day;
elsif Date_N >= Year_2101 then
Date_N := Date_N + Time_Rep (1) * Nanos_In_Day;
end if;
-- Step 4: Sub second processing in local time zone
Sub_Sec_N := Date_N mod Nano;
Sub_Sec := Duration (Sub_Sec_N) / Nano_F;
Date_N := Date_N - Sub_Sec_N;
-- Convert Date_N into a time duration value, changing the units
-- to seconds.
Date_Dur := Time_Dur (Date_N / Nano - Ada_Low / Nano);
-- Step 5: Year processing in local time zone. Determine the number
-- of four year segments since the start of Ada time and the input
-- date.
Four_Year_Segs := Natural (Date_Dur / Secs_In_Four_Years);
if Four_Year_Segs > 0 then
Date_Dur := Date_Dur - Time_Dur (Four_Year_Segs) *
Secs_In_Four_Years;
end if;
-- Calculate the remaining non-leap years
Rem_Years := Natural (Date_Dur / Secs_In_Non_Leap_Year);
if Rem_Years > 3 then
Rem_Years := 3;
end if;
Date_Dur := Date_Dur - Time_Dur (Rem_Years) * Secs_In_Non_Leap_Year;
Year := Ada_Min_Year + Natural (4 * Four_Year_Segs + Rem_Years);
Is_Leap_Year := Is_Leap (Year);
-- Step 6: Month and day processing in local time zone
Year_Day := Natural (Date_Dur / Secs_In_Day) + 1;
Month := 1;
-- Processing for months after January
if Year_Day > 31 then
Month := 2;
Year_Day := Year_Day - 31;
-- Processing for a new month or a leap February
if Year_Day > 28
and then (not Is_Leap_Year or else Year_Day > 29)
then
Month := 3;
Year_Day := Year_Day - 28;
if Is_Leap_Year then
Year_Day := Year_Day - 1;
end if;
-- Remaining months
while Year_Day > Days_In_Month (Month) loop
Year_Day := Year_Day - Days_In_Month (Month);
Month := Month + 1;
end loop;
end if;
end if;
-- Step 7: Hour, minute, second and sub second processing in local
-- time zone.
Day := Day_Number (Year_Day);
Day_Seconds := Integer (Date_Dur mod Secs_In_Day);
Day_Secs := Duration (Day_Seconds) + Sub_Sec;
Hour := Day_Seconds / 3_600;
Hour_Seconds := Day_Seconds mod 3_600;
Minute := Hour_Seconds / 60;
Second := Hour_Seconds mod 60;
exception
when Constraint_Error =>
raise Time_Error;
end Split;
-------------
-- Time_Of --
-------------
function Time_Of
(Year : Year_Number;
Month : Month_Number;
Day : Day_Number;
Day_Secs : Day_Duration;
Hour : Integer;
Minute : Integer;
Second : Integer;
Sub_Sec : Duration;
Leap_Sec : Boolean;
Use_Day_Secs : Boolean;
Use_TZ : Boolean;
Is_Historic : Boolean;
Time_Zone : Long_Integer) return Time
is
Count : Integer;
Elapsed_Leaps : Natural;
Next_Leap_N : Time_Rep;
Res_N : Time_Rep;
Rounded_Res_N : Time_Rep;
begin
-- Step 1: Check whether the day, month and year form a valid date
if Day > Days_In_Month (Month)
and then (Day /= 29 or else Month /= 2 or else not Is_Leap (Year))
then
raise Time_Error;
end if;
-- Start accumulating nanoseconds from the low bound of Ada time
Res_N := Ada_Low;
-- Step 2: Year processing and centennial year adjustment. Determine
-- the number of four year segments since the start of Ada time and
-- the input date.
Count := (Year - Year_Number'First) / 4;
for Four_Year_Segments in 1 .. Count loop
Res_N := Res_N + Nanos_In_Four_Years;
end loop;
-- Note that non-leap centennial years are automatically considered
-- leap in the operation above. An adjustment of several days is
-- required to compensate for this.
if Year > 2300 then
Res_N := Res_N - Time_Rep (3) * Nanos_In_Day;
elsif Year > 2200 then
Res_N := Res_N - Time_Rep (2) * Nanos_In_Day;
elsif Year > 2100 then
Res_N := Res_N - Time_Rep (1) * Nanos_In_Day;
end if;
-- Add the remaining non-leap years
Count := (Year - Year_Number'First) mod 4;
Res_N := Res_N + Time_Rep (Count) * Secs_In_Non_Leap_Year * Nano;
-- Step 3: Day of month processing. Determine the number of days
-- since the start of the current year. Do not add the current
-- day since it has not elapsed yet.
Count := Cumulative_Days_Before_Month (Month) + Day - 1;
-- The input year is leap and we have passed February
if Is_Leap (Year)
and then Month > 2
then
Count := Count + 1;
end if;
Res_N := Res_N + Time_Rep (Count) * Nanos_In_Day;
-- Step 4: Hour, minute, second and sub second processing
if Use_Day_Secs then
Res_N := Res_N + Duration_To_Time_Rep (Day_Secs);
else
Res_N :=
Res_N + Time_Rep (Hour * 3_600 + Minute * 60 + Second) * Nano;
if Sub_Sec = 1.0 then
Res_N := Res_N + Time_Rep (1) * Nano;
else
Res_N := Res_N + Duration_To_Time_Rep (Sub_Sec);
end if;
end if;
-- At this point, the generated time value should be withing the
-- bounds of Ada time.
Check_Within_Time_Bounds (Res_N);
-- Step 4: Time zone processing. At this point we have built an
-- arbitrary time value which is not related to any time zone.
-- For simplicity, the time value is normalized to GMT, producing
-- a uniform representation which can be treated by arithmetic
-- operations for instance without any additional corrections.
if Use_TZ then
if Time_Zone /= 0 then
Res_N := Res_N - Time_Rep (Time_Zone) * 60 * Nano;
end if;
-- Ada 83 and 95
else
declare
Cur_Off : constant Long_Integer :=
UTC_Time_Offset (Time (Res_N), Is_Historic);
Cur_Res_N : constant Time_Rep :=
Res_N - Time_Rep (Cur_Off) * Nano;
Off : constant Long_Integer :=
UTC_Time_Offset (Time (Cur_Res_N), Is_Historic);
begin
Res_N := Res_N - Time_Rep (Off) * Nano;
end;
end if;
-- Step 5: Leap seconds processing in GMT
if Leap_Support then
Cumulative_Leap_Seconds
(Start_Of_Time, Res_N, Elapsed_Leaps, Next_Leap_N);
Res_N := Res_N + Time_Rep (Elapsed_Leaps) * Nano;
-- An Ada 2005 caller requesting an explicit leap second or an
-- Ada 95 caller accounting for an invisible leap second.
if Leap_Sec or else Res_N >= Next_Leap_N then
Res_N := Res_N + Time_Rep (1) * Nano;
end if;
-- Leap second validity check
Rounded_Res_N := Res_N - (Res_N mod Nano);
if Use_TZ
and then Leap_Sec
and then Rounded_Res_N /= Next_Leap_N
then
raise Time_Error;
end if;
end if;
return Time (Res_N);
end Time_Of;
end Formatting_Operations;
---------------------------
-- Time_Zones_Operations --
---------------------------
package body Time_Zones_Operations is
---------------------
-- UTC_Time_Offset --
---------------------
function UTC_Time_Offset (Date : Time) return Long_Integer is
begin
return UTC_Time_Offset (Date, True);
end UTC_Time_Offset;
end Time_Zones_Operations;
-- Start of elaboration code for Ada.Calendar
begin
System.OS_Primitives.Initialize;
end Ada.Calendar;
|
-- AOC 2020, Day 8
with Ada.Text_IO; use Ada.Text_IO;
with Day; use Day;
procedure main is
acc : constant Integer := acc_before_repeat("input.txt");
h : constant Integer := acc_after_terminate("input.txt");
begin
put_line("Part 1: " & Integer'Image(acc));
put_line("Part 2: " & Integer'Image(h));
end main;
|
package body Controlled6_Pkg.Iterators is
function Find return Iterator_Type is
Iterator : Iterator_Type;
begin
return Iterator;
end Find;
function Current (Iterator : in Iterator_Type) return T is begin
return Iterator.Current.Item;
end Current;
procedure Find_Next (Iterator : in out Iterator_Type) is begin
Iterator.Current := null;
end Find_Next;
function Is_Null (Iterator : in Iterator_Type) return Boolean is begin
return Iterator.Current = null;
end Is_Null;
end Controlled6_Pkg.Iterators;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Ada Modeling Framework --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2011-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$
------------------------------------------------------------------------------
with AMF.Elements;
with AMF.Internals.Element_Collections;
with AMF.Internals.Helpers;
with AMF.Internals.Tables.UML_Attributes;
with AMF.Visitors.UML_Iterators;
with AMF.Visitors.UML_Visitors;
with League.Strings.Internals;
with Matreshka.Internals.Strings;
package body AMF.Internals.UML_Parameters is
-------------------
-- Enter_Element --
-------------------
overriding procedure Enter_Element
(Self : not null access constant UML_Parameter_Proxy;
Visitor : in out AMF.Visitors.Abstract_Visitor'Class;
Control : in out AMF.Visitors.Traverse_Control) is
begin
if Visitor in AMF.Visitors.UML_Visitors.UML_Visitor'Class then
AMF.Visitors.UML_Visitors.UML_Visitor'Class
(Visitor).Enter_Parameter
(AMF.UML.Parameters.UML_Parameter_Access (Self),
Control);
end if;
end Enter_Element;
-------------------
-- Leave_Element --
-------------------
overriding procedure Leave_Element
(Self : not null access constant UML_Parameter_Proxy;
Visitor : in out AMF.Visitors.Abstract_Visitor'Class;
Control : in out AMF.Visitors.Traverse_Control) is
begin
if Visitor in AMF.Visitors.UML_Visitors.UML_Visitor'Class then
AMF.Visitors.UML_Visitors.UML_Visitor'Class
(Visitor).Leave_Parameter
(AMF.UML.Parameters.UML_Parameter_Access (Self),
Control);
end if;
end Leave_Element;
-------------------
-- Visit_Element --
-------------------
overriding procedure Visit_Element
(Self : not null access constant UML_Parameter_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.UML_Iterators.UML_Iterator'Class then
AMF.Visitors.UML_Iterators.UML_Iterator'Class
(Iterator).Visit_Parameter
(Visitor,
AMF.UML.Parameters.UML_Parameter_Access (Self),
Control);
end if;
end Visit_Element;
-----------------
-- Get_Default --
-----------------
overriding function Get_Default
(Self : not null access constant UML_Parameter_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.UML_Attributes.Internal_Get_Default (Self.Element);
begin
if Aux = null then
return (Is_Empty => True);
else
return (False, League.Strings.Internals.Create (Aux));
end if;
end;
end Get_Default;
-----------------
-- Set_Default --
-----------------
overriding procedure Set_Default
(Self : not null access UML_Parameter_Proxy;
To : AMF.Optional_String) is
begin
if To.Is_Empty then
AMF.Internals.Tables.UML_Attributes.Internal_Set_Default
(Self.Element, null);
else
AMF.Internals.Tables.UML_Attributes.Internal_Set_Default
(Self.Element,
League.Strings.Internals.Internal (To.Value));
end if;
end Set_Default;
-----------------------
-- Get_Default_Value --
-----------------------
overriding function Get_Default_Value
(Self : not null access constant UML_Parameter_Proxy)
return AMF.UML.Value_Specifications.UML_Value_Specification_Access is
begin
return
AMF.UML.Value_Specifications.UML_Value_Specification_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.UML_Attributes.Internal_Get_Default_Value
(Self.Element)));
end Get_Default_Value;
-----------------------
-- Set_Default_Value --
-----------------------
overriding procedure Set_Default_Value
(Self : not null access UML_Parameter_Proxy;
To : AMF.UML.Value_Specifications.UML_Value_Specification_Access) is
begin
AMF.Internals.Tables.UML_Attributes.Internal_Set_Default_Value
(Self.Element,
AMF.Internals.Helpers.To_Element
(AMF.Elements.Element_Access (To)));
end Set_Default_Value;
-------------------
-- Get_Direction --
-------------------
overriding function Get_Direction
(Self : not null access constant UML_Parameter_Proxy)
return AMF.UML.UML_Parameter_Direction_Kind is
begin
return
AMF.Internals.Tables.UML_Attributes.Internal_Get_Direction
(Self.Element);
end Get_Direction;
-------------------
-- Set_Direction --
-------------------
overriding procedure Set_Direction
(Self : not null access UML_Parameter_Proxy;
To : AMF.UML.UML_Parameter_Direction_Kind) is
begin
AMF.Internals.Tables.UML_Attributes.Internal_Set_Direction
(Self.Element, To);
end Set_Direction;
----------------
-- Get_Effect --
----------------
overriding function Get_Effect
(Self : not null access constant UML_Parameter_Proxy)
return AMF.UML.Optional_UML_Parameter_Effect_Kind is
begin
return
AMF.Internals.Tables.UML_Attributes.Internal_Get_Effect
(Self.Element);
end Get_Effect;
----------------
-- Set_Effect --
----------------
overriding procedure Set_Effect
(Self : not null access UML_Parameter_Proxy;
To : AMF.UML.Optional_UML_Parameter_Effect_Kind) is
begin
AMF.Internals.Tables.UML_Attributes.Internal_Set_Effect
(Self.Element, To);
end Set_Effect;
----------------------
-- Get_Is_Exception --
----------------------
overriding function Get_Is_Exception
(Self : not null access constant UML_Parameter_Proxy)
return Boolean is
begin
return
AMF.Internals.Tables.UML_Attributes.Internal_Get_Is_Exception
(Self.Element);
end Get_Is_Exception;
----------------------
-- Set_Is_Exception --
----------------------
overriding procedure Set_Is_Exception
(Self : not null access UML_Parameter_Proxy;
To : Boolean) is
begin
AMF.Internals.Tables.UML_Attributes.Internal_Set_Is_Exception
(Self.Element, To);
end Set_Is_Exception;
-------------------
-- Get_Is_Stream --
-------------------
overriding function Get_Is_Stream
(Self : not null access constant UML_Parameter_Proxy)
return Boolean is
begin
return
AMF.Internals.Tables.UML_Attributes.Internal_Get_Is_Stream
(Self.Element);
end Get_Is_Stream;
-------------------
-- Set_Is_Stream --
-------------------
overriding procedure Set_Is_Stream
(Self : not null access UML_Parameter_Proxy;
To : Boolean) is
begin
AMF.Internals.Tables.UML_Attributes.Internal_Set_Is_Stream
(Self.Element, To);
end Set_Is_Stream;
-------------------
-- Get_Operation --
-------------------
overriding function Get_Operation
(Self : not null access constant UML_Parameter_Proxy)
return AMF.UML.Operations.UML_Operation_Access is
begin
return
AMF.UML.Operations.UML_Operation_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.UML_Attributes.Internal_Get_Operation
(Self.Element)));
end Get_Operation;
-------------------
-- Set_Operation --
-------------------
overriding procedure Set_Operation
(Self : not null access UML_Parameter_Proxy;
To : AMF.UML.Operations.UML_Operation_Access) is
begin
AMF.Internals.Tables.UML_Attributes.Internal_Set_Operation
(Self.Element,
AMF.Internals.Helpers.To_Element
(AMF.Elements.Element_Access (To)));
end Set_Operation;
-----------------------
-- Get_Parameter_Set --
-----------------------
overriding function Get_Parameter_Set
(Self : not null access constant UML_Parameter_Proxy)
return AMF.UML.Parameter_Sets.Collections.Set_Of_UML_Parameter_Set is
begin
return
AMF.UML.Parameter_Sets.Collections.Wrap
(AMF.Internals.Element_Collections.Wrap
(AMF.Internals.Tables.UML_Attributes.Internal_Get_Parameter_Set
(Self.Element)));
end Get_Parameter_Set;
-------------
-- Get_End --
-------------
overriding function Get_End
(Self : not null access constant UML_Parameter_Proxy)
return AMF.UML.Connector_Ends.Collections.Ordered_Set_Of_UML_Connector_End is
begin
return
AMF.UML.Connector_Ends.Collections.Wrap
(AMF.Internals.Element_Collections.Wrap
(AMF.Internals.Tables.UML_Attributes.Internal_Get_End
(Self.Element)));
end Get_End;
----------------------------
-- Get_Template_Parameter --
----------------------------
overriding function Get_Template_Parameter
(Self : not null access constant UML_Parameter_Proxy)
return AMF.UML.Connectable_Element_Template_Parameters.UML_Connectable_Element_Template_Parameter_Access is
begin
return
AMF.UML.Connectable_Element_Template_Parameters.UML_Connectable_Element_Template_Parameter_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.UML_Attributes.Internal_Get_Template_Parameter
(Self.Element)));
end Get_Template_Parameter;
----------------------------
-- Set_Template_Parameter --
----------------------------
overriding procedure Set_Template_Parameter
(Self : not null access UML_Parameter_Proxy;
To : AMF.UML.Connectable_Element_Template_Parameters.UML_Connectable_Element_Template_Parameter_Access) is
begin
AMF.Internals.Tables.UML_Attributes.Internal_Set_Template_Parameter
(Self.Element,
AMF.Internals.Helpers.To_Element
(AMF.Elements.Element_Access (To)));
end Set_Template_Parameter;
--------------
-- Get_Type --
--------------
overriding function Get_Type
(Self : not null access constant UML_Parameter_Proxy)
return AMF.UML.Types.UML_Type_Access is
begin
return
AMF.UML.Types.UML_Type_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.UML_Attributes.Internal_Get_Type
(Self.Element)));
end Get_Type;
--------------
-- Set_Type --
--------------
overriding procedure Set_Type
(Self : not null access UML_Parameter_Proxy;
To : AMF.UML.Types.UML_Type_Access) is
begin
AMF.Internals.Tables.UML_Attributes.Internal_Set_Type
(Self.Element,
AMF.Internals.Helpers.To_Element
(AMF.Elements.Element_Access (To)));
end Set_Type;
---------------------------
-- Get_Client_Dependency --
---------------------------
overriding function Get_Client_Dependency
(Self : not null access constant UML_Parameter_Proxy)
return AMF.UML.Dependencies.Collections.Set_Of_UML_Dependency is
begin
return
AMF.UML.Dependencies.Collections.Wrap
(AMF.Internals.Element_Collections.Wrap
(AMF.Internals.Tables.UML_Attributes.Internal_Get_Client_Dependency
(Self.Element)));
end Get_Client_Dependency;
-------------------------
-- Get_Name_Expression --
-------------------------
overriding function Get_Name_Expression
(Self : not null access constant UML_Parameter_Proxy)
return AMF.UML.String_Expressions.UML_String_Expression_Access is
begin
return
AMF.UML.String_Expressions.UML_String_Expression_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.UML_Attributes.Internal_Get_Name_Expression
(Self.Element)));
end Get_Name_Expression;
-------------------------
-- Set_Name_Expression --
-------------------------
overriding procedure Set_Name_Expression
(Self : not null access UML_Parameter_Proxy;
To : AMF.UML.String_Expressions.UML_String_Expression_Access) is
begin
AMF.Internals.Tables.UML_Attributes.Internal_Set_Name_Expression
(Self.Element,
AMF.Internals.Helpers.To_Element
(AMF.Elements.Element_Access (To)));
end Set_Name_Expression;
-------------------
-- Get_Namespace --
-------------------
overriding function Get_Namespace
(Self : not null access constant UML_Parameter_Proxy)
return AMF.UML.Namespaces.UML_Namespace_Access is
begin
return
AMF.UML.Namespaces.UML_Namespace_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.UML_Attributes.Internal_Get_Namespace
(Self.Element)));
end Get_Namespace;
------------------------
-- Get_Qualified_Name --
------------------------
overriding function Get_Qualified_Name
(Self : not null access constant UML_Parameter_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.UML_Attributes.Internal_Get_Qualified_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_Qualified_Name;
-----------------------------------
-- Get_Owning_Template_Parameter --
-----------------------------------
overriding function Get_Owning_Template_Parameter
(Self : not null access constant UML_Parameter_Proxy)
return AMF.UML.Template_Parameters.UML_Template_Parameter_Access is
begin
return
AMF.UML.Template_Parameters.UML_Template_Parameter_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.UML_Attributes.Internal_Get_Owning_Template_Parameter
(Self.Element)));
end Get_Owning_Template_Parameter;
-----------------------------------
-- Set_Owning_Template_Parameter --
-----------------------------------
overriding procedure Set_Owning_Template_Parameter
(Self : not null access UML_Parameter_Proxy;
To : AMF.UML.Template_Parameters.UML_Template_Parameter_Access) is
begin
AMF.Internals.Tables.UML_Attributes.Internal_Set_Owning_Template_Parameter
(Self.Element,
AMF.Internals.Helpers.To_Element
(AMF.Elements.Element_Access (To)));
end Set_Owning_Template_Parameter;
----------------------------
-- Get_Template_Parameter --
----------------------------
overriding function Get_Template_Parameter
(Self : not null access constant UML_Parameter_Proxy)
return AMF.UML.Template_Parameters.UML_Template_Parameter_Access is
begin
return
AMF.UML.Template_Parameters.UML_Template_Parameter_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.UML_Attributes.Internal_Get_Template_Parameter
(Self.Element)));
end Get_Template_Parameter;
----------------------------
-- Set_Template_Parameter --
----------------------------
overriding procedure Set_Template_Parameter
(Self : not null access UML_Parameter_Proxy;
To : AMF.UML.Template_Parameters.UML_Template_Parameter_Access) is
begin
AMF.Internals.Tables.UML_Attributes.Internal_Set_Template_Parameter
(Self.Element,
AMF.Internals.Helpers.To_Element
(AMF.Elements.Element_Access (To)));
end Set_Template_Parameter;
-------------
-- Default --
-------------
overriding function Default
(Self : not null access constant UML_Parameter_Proxy)
return AMF.Optional_String is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Default unimplemented");
raise Program_Error with "Unimplemented procedure UML_Parameter_Proxy.Default";
return Default (Self);
end Default;
---------------------
-- Compatible_With --
---------------------
overriding function Compatible_With
(Self : not null access constant UML_Parameter_Proxy;
Other : AMF.UML.Multiplicity_Elements.UML_Multiplicity_Element_Access)
return Boolean is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Compatible_With unimplemented");
raise Program_Error with "Unimplemented procedure UML_Parameter_Proxy.Compatible_With";
return Compatible_With (Self, Other);
end Compatible_With;
--------------------------
-- Includes_Cardinality --
--------------------------
overriding function Includes_Cardinality
(Self : not null access constant UML_Parameter_Proxy;
C : Integer)
return Boolean is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Includes_Cardinality unimplemented");
raise Program_Error with "Unimplemented procedure UML_Parameter_Proxy.Includes_Cardinality";
return Includes_Cardinality (Self, C);
end Includes_Cardinality;
---------------------------
-- Includes_Multiplicity --
---------------------------
overriding function Includes_Multiplicity
(Self : not null access constant UML_Parameter_Proxy;
M : AMF.UML.Multiplicity_Elements.UML_Multiplicity_Element_Access)
return Boolean is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Includes_Multiplicity unimplemented");
raise Program_Error with "Unimplemented procedure UML_Parameter_Proxy.Includes_Multiplicity";
return Includes_Multiplicity (Self, M);
end Includes_Multiplicity;
---------
-- Iss --
---------
overriding function Iss
(Self : not null access constant UML_Parameter_Proxy;
Lowerbound : Integer;
Upperbound : Integer)
return Boolean is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Iss unimplemented");
raise Program_Error with "Unimplemented procedure UML_Parameter_Proxy.Iss";
return Iss (Self, Lowerbound, Upperbound);
end Iss;
----------
-- Ends --
----------
overriding function Ends
(Self : not null access constant UML_Parameter_Proxy)
return AMF.UML.Connector_Ends.Collections.Set_Of_UML_Connector_End is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Ends unimplemented");
raise Program_Error with "Unimplemented procedure UML_Parameter_Proxy.Ends";
return Ends (Self);
end Ends;
-------------------------
-- All_Owning_Packages --
-------------------------
overriding function All_Owning_Packages
(Self : not null access constant UML_Parameter_Proxy)
return AMF.UML.Packages.Collections.Set_Of_UML_Package is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "All_Owning_Packages unimplemented");
raise Program_Error with "Unimplemented procedure UML_Parameter_Proxy.All_Owning_Packages";
return All_Owning_Packages (Self);
end All_Owning_Packages;
-----------------------------
-- Is_Distinguishable_From --
-----------------------------
overriding function Is_Distinguishable_From
(Self : not null access constant UML_Parameter_Proxy;
N : AMF.UML.Named_Elements.UML_Named_Element_Access;
Ns : AMF.UML.Namespaces.UML_Namespace_Access)
return Boolean is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Is_Distinguishable_From unimplemented");
raise Program_Error with "Unimplemented procedure UML_Parameter_Proxy.Is_Distinguishable_From";
return Is_Distinguishable_From (Self, N, Ns);
end Is_Distinguishable_From;
---------------
-- Namespace --
---------------
overriding function Namespace
(Self : not null access constant UML_Parameter_Proxy)
return AMF.UML.Namespaces.UML_Namespace_Access is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Namespace unimplemented");
raise Program_Error with "Unimplemented procedure UML_Parameter_Proxy.Namespace";
return Namespace (Self);
end Namespace;
------------------------
-- Is_Compatible_With --
------------------------
overriding function Is_Compatible_With
(Self : not null access constant UML_Parameter_Proxy;
P : AMF.UML.Parameterable_Elements.UML_Parameterable_Element_Access)
return Boolean is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Is_Compatible_With unimplemented");
raise Program_Error with "Unimplemented procedure UML_Parameter_Proxy.Is_Compatible_With";
return Is_Compatible_With (Self, P);
end Is_Compatible_With;
---------------------------
-- Is_Template_Parameter --
---------------------------
overriding function Is_Template_Parameter
(Self : not null access constant UML_Parameter_Proxy)
return Boolean is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Is_Template_Parameter unimplemented");
raise Program_Error with "Unimplemented procedure UML_Parameter_Proxy.Is_Template_Parameter";
return Is_Template_Parameter (Self);
end Is_Template_Parameter;
end AMF.Internals.UML_Parameters;
|
-- AoC 2020, Day 12
with Ada.Text_IO;
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;
package body Day is
package TIO renames Ada.Text_IO;
function char_to_action(c : in Character) return Action_Type is
begin
case c is
when 'N' => return north;
when 'S' => return south;
when 'E' => return east;
when 'W' => return west;
when 'L' => return left;
when 'R' => return right;
when 'F' => return forward;
when others => raise Instruction_Exception with "Unknown action: " & c;
end case;
end;
function parse_line(line : in String) return Instruction is
act : constant Action_Type := char_to_action(line(line'first));
val : constant Integer := Integer'Value(line(line'first+1..line'last));
begin
return Instruction'(action => act, value => val);
end parse_line;
function load_file(filename : in String) return Ferry is
file : TIO.File_Type;
vec : Instruction_Vectors.Vector := Empty_Vector;
begin
TIO.open(File => file, Mode => TIO.In_File, Name => filename);
while not TIO.end_of_file(file) loop
vec.append(parse_line(TIO.get_line(file)));
end loop;
TIO.close(file);
return Ferry'(instructions => vec, heading => east, x => 0, y => 0, way_x => -1, way_y => 10);
end load_file;
function action_to_heading(act : in Action_Type) return Heading_Type is
begin
case act is
when north => return north;
when south => return south;
when east => return east;
when west => return west;
when others => raise Instruction_Exception with "Cannot map action to heading: " & Action_Type'Image(act);
end case;
end action_to_heading;
procedure move(dir : in Heading_Type; dist : in Integer; f : in out Ferry) is
begin
case dir is
when north => f.x := f.x - dist;
when south => f.x := f.x + dist;
when east => f.y := f.y + dist;
when west => f.y := f.y - dist;
end case;
end move;
procedure turn(angle : in Integer; f : in out Ferry) is
curr_pos : constant Natural := Heading_Type'Pos(f.heading);
steps : constant Integer := angle / 90;
new_pos : constant Natural := (curr_pos + steps) mod 4;
new_heading : constant Heading_Type := Heading_Type'Val(new_pos);
begin
f.heading := new_heading;
end turn;
procedure simulate(f : in out Ferry) is
begin
for i of f.instructions loop
case i.action is
when north..west => move(action_to_heading(i.action), i.value, f);
when forward => move(f.heading, i.value, f);
when left => turn(-1 * i.value, f);
when right => turn(i.value, f);
end case;
end loop;
end simulate;
procedure move_waypoint(dir : in Heading_Type; dist : in Integer; f : in out Ferry) is
begin
case dir is
when north => f.way_x := f.way_x - dist;
when south => f.way_x := f.way_x + dist;
when east => f.way_y := f.way_y + dist;
when west => f.way_y := f.way_y - dist;
end case;
end move_waypoint;
procedure rotate_waypoint(angle : in Integer; f : in out Ferry) is
RadPerDegree : constant Float := Ada.Numerics.Pi / 180.0;
radians : constant Float := RadPerDegree * Float(angle);
x : constant Float := Float(f.way_x);
y : constant Float := Float(f.way_y);
new_x : constant Float := (x * cos(radians)) - (y * sin(radians));
new_y : constant Float := (x * sin(radians)) + (y * cos(radians));
begin
f.way_x := Integer(new_x);
f.way_y := Integer(new_y);
end rotate_waypoint;
procedure simulate_waypoint(f : in out Ferry) is
begin
for i of f.instructions loop
case i.action is
when north..west => move_waypoint(action_to_heading(i.action), i.value, f);
when forward =>
f.x := f.x + (i.value * f.way_x);
f.y := f.y + (i.value * f.way_y);
when left => rotate_waypoint(i.value, f);
when right => rotate_waypoint(-1 * i.value, f);
end case;
end loop;
end simulate_waypoint;
function distance(f : in Ferry) return Natural is
tmp : Ferry := f;
begin
simulate(tmp);
return abs(tmp.x) + abs(tmp.y);
end distance;
function waypoint_distance(f : in Ferry) return Natural is
tmp : Ferry := f;
begin
simulate_waypoint(tmp);
return abs(tmp.x) + abs(tmp.y);
end waypoint_distance;
end Day;
|
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Unchecked_Deallocation;
with Person_Handling; use Person_Handling;
package body Person_Sorted_List is
procedure Free is
new Ada.Unchecked_Deallocation(Post, List_Type);
function Empty(List: List_Type)
return Boolean is
begin
return List = null;
end Empty;
procedure Insert_First(List: in out List_Type; Data: in Person) is
Temp: List_Type;
begin
Temp := List;
List := new Post;
List.Data := Data;
List.Point := Temp;
end Insert_First;
procedure Insert(List: in out List_Type; Data: in Person) is
begin
if Empty(List) then
Insert_First(List, Data);
elsif Data < List.Data then
Insert_First(List, Data);
else
Insert(List.Point, Data);
end if;
end Insert;
procedure Put(List: List_Type) is
begin
if not Empty(List) then
Put(List.all.Data);
New_Line;
Put(List.all.Point);
end if;
end Put;
function Member(List: List_Type; Search: Person)
return Boolean is
begin
if Empty(List) then
return False;
end if;
if List.Data = Search then
return True;
else
return Member(List.all.Point, Search);
end if;
end Member;
procedure RemoveCurrent(List: in out List_Type) is
Temp: List_Type;
begin
Temp := List;
List := List.Point;
Free(Temp);
end RemoveCurrent;
procedure Remove(List: in out List_Type; Search: in Person) is
begin
if Empty(List) then
raise CANTFIND_ERROR;
end if;
if List.Data = Search then
RemoveCurrent(List);
else
if List.Point = null then
raise CANTFIND_ERROR;
end if;
Remove(List.Point, Search);
end if;
end Remove;
procedure Delete(List: in out List_Type) is
begin
if List.Point = null then
Free(List);
List := null;
else
RemoveCurrent(List);
Delete(List);
end if;
end Delete;
function Find(List: List_Type; Search: Person)
return Person is
begin
if Empty(List) then
raise CANTFIND_ERROR;
end if;
if List.Data = Search then
return List.Data;
end if;
if List.Point = null then
raise CANTFIND_ERROR;
end if;
return Find(List.Point, Search);
end Find;
procedure Find(List: in List_Type; Search: in Person; Data: out Person) is
begin
Data := Find(List, Search);
end Find;
function Length(List: List_Type)
return Integer is
begin
if List.Point /= null then
return 1 + Length(List.Point);
end if;
return 1;
end Length;
end Person_Sorted_List;
|
with GNAT.Regpat; use GNAT.Regpat;
with Rejuvenation.Finder; use Rejuvenation.Finder;
with Rejuvenation.Utils; use Rejuvenation.Utils;
package body Rejuvenation.Placeholders is
Placeholder_Matcher : constant GNAT.Regpat.Pattern_Matcher :=
Compile ("\$[SM]_[a-zA-Z0-9_]+");
function Is_Placeholder_Name (Name : String) return Boolean is
(GNAT.Regpat.Match (Placeholder_Matcher, Name));
Single_Placeholder_Matcher : constant GNAT.Regpat.Pattern_Matcher :=
Compile ("\$S_[a-zA-Z0-9_]+");
function Is_Single_Placeholder_Name (Name : String) return Boolean is
(GNAT.Regpat.Match (Single_Placeholder_Matcher, Name));
Multiple_Placeholder_Matcher : constant GNAT.Regpat.Pattern_Matcher :=
Compile ("\$M_[a-zA-Z0-9_]+");
function Is_Multiple_Placeholder_Name (Name : String) return Boolean is
(GNAT.Regpat.Match (Multiple_Placeholder_Matcher, Name));
function Get_Name_At_Placeholder_Location
(Node : Ada_Node'Class) return String;
-- return the string at the location of a placeholder name
-- in case of absence of placeholder location, the empty string is returned
--
-- Get_Name_At_Placeholder_Location
-- is introduced to localize the information
-- * what kind of nodes can be placeholders
-- * where is the placeholder name located for the different kinds
function Get_Name_At_Placeholder_Location
(Node : Ada_Node'Class) return String
is
begin
case Node.Kind is
when Ada_Identifier | Ada_Defining_Name | Ada_Enum_Literal_Decl =>
return Raw_Signature (Node);
when Ada_Call_Stmt =>
declare
Name : constant Libadalang.Analysis.Name :=
Node.As_Call_Stmt.F_Call;
begin
if Name.Kind = Ada_Identifier then
return Raw_Signature (Name);
end if;
end;
when Ada_Discriminant_Assoc =>
declare
D_A : constant Discriminant_Assoc := Node.As_Discriminant_Assoc;
Ids : constant Discriminant_Choice_List := D_A.F_Ids;
Discr_Expr : constant Expr := D_A.F_Discr_Expr;
begin
if Ids.Children_Count = 0
and then Discr_Expr.Kind = Ada_Identifier
then
return Raw_Signature (Discr_Expr);
end if;
end;
when Ada_Param_Assoc =>
declare
P_A : constant Param_Assoc := Node.As_Param_Assoc;
Designator : constant Ada_Node := P_A.F_Designator;
R_Expr : constant Expr := P_A.F_R_Expr;
begin
if Designator.Is_Null and then R_Expr.Kind = Ada_Identifier then
return Raw_Signature (R_Expr);
end if;
end;
when Ada_Aspect_Assoc =>
declare
A_A : constant Aspect_Assoc := Node.As_Aspect_Assoc;
N : constant Name := A_A.F_Id;
begin
if A_A.F_Expr.Is_Null and then N.Kind = Ada_Identifier then
return Raw_Signature (N);
end if;
end;
when Ada_Subtype_Indication =>
declare
SI : constant Subtype_Indication := Node.As_Subtype_Indication;
Name : constant Libadalang.Analysis.Name := SI.F_Name;
begin
if Name.Kind = Ada_Identifier and then SI.F_Constraint.Is_Null
then
return Raw_Signature (Name);
end if;
end;
when others =>
null;
end case;
return "";
end Get_Name_At_Placeholder_Location;
function Is_Placeholder (Node : Ada_Node'Class) return Boolean is
(Is_Placeholder_Name (Get_Name_At_Placeholder_Location (Node)));
function Is_Single_Placeholder (Node : Ada_Node'Class) return Boolean is
(Is_Single_Placeholder_Name (Get_Name_At_Placeholder_Location (Node)));
function Is_Multiple_Placeholder (Node : Ada_Node'Class) return Boolean is
(Is_Multiple_Placeholder_Name (Get_Name_At_Placeholder_Location (Node)));
function Get_Placeholder_Name (Node : Ada_Node'Class) return String is
(Get_Name_At_Placeholder_Location (Node));
function Get_Placeholders (Node : Ada_Node'Class) return Node_List.Vector is
(Find_Non_Contained (Node, Is_Placeholder'Access));
function Get_Placeholder_Names
(Node : Ada_Node'Class) return String_Sets.Set
is
Result : String_Sets.Set;
function Visit (Node : Ada_Node'Class) return Visit_Status;
function Visit (Node : Ada_Node'Class) return Visit_Status is
begin
if Is_Placeholder (Node) then
Result.Include (Get_Placeholder_Name (Node));
return Over;
else
return Into;
end if;
end Visit;
begin
Node.Traverse (Visit'Access);
return Result;
end Get_Placeholder_Names;
end Rejuvenation.Placeholders;
|
with Ada.Finalization;
with ACO.Messages;
with ACO.OD;
package ACO.Protocols is
type Protocol
(Od : not null access ACO.OD.Object_Dictionary'Class)
is abstract new Ada.Finalization.Limited_Controlled with private;
type Protocol_Access is access all Protocol'Class;
function Is_Valid
(This : in out Protocol;
Msg : in ACO.Messages.Message)
return Boolean is abstract;
private
type Protocol
(Od : not null access ACO.OD.Object_Dictionary'Class)
is abstract new Ada.Finalization.Limited_Controlled with null record;
end ACO.Protocols;
|
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.FMC is
pragma Preelaborate;
---------------
-- Registers --
---------------
subtype BCR_MTYP_Field is HAL.UInt2;
subtype BCR_MWID_Field is HAL.UInt2;
subtype BCR_CPSIZE_Field is HAL.UInt3;
subtype BCR_BMAP_Field is HAL.UInt2;
-- This register contains the control information of each memory bank, used
-- for SRAMs, PSRAM and NOR Flash memories.
type BCR_Register is record
-- Memory bank enable bit This bit enables the memory bank. After reset
-- Bank1 is enabled, all others are disabled. Accessing a disabled bank
-- causes an ERROR on AXI bus.
MBKEN : Boolean := True;
-- Address/data multiplexing enable bit When this bit is set, the
-- address and data values are multiplexed on the data bus, valid only
-- with NOR and PSRAM memories:
MUXEN : Boolean := True;
-- Memory type These bits define the type of external memory attached to
-- the corresponding memory bank:
MTYP : BCR_MTYP_Field := 16#2#;
-- Memory data bus width Defines the external memory device width, valid
-- for all type of memories.
MWID : BCR_MWID_Field := 16#1#;
-- Flash access enable This bit enables NOR Flash memory access
-- operations.
FACCEN : Boolean := True;
-- unspecified
Reserved_7_7 : HAL.Bit := 16#1#;
-- Burst enable bit This bit enables/disables synchronous accesses
-- during read operations. It is valid only for synchronous memories
-- operating in Burst mode:
BURSTEN : Boolean := False;
-- Wait signal polarity bit This bit defines the polarity of the wait
-- signal from memory used for either in synchronous or asynchronous
-- mode:
WAITPOL : Boolean := False;
-- unspecified
Reserved_10_10 : HAL.Bit := 16#0#;
-- Wait timing configuration The NWAIT signal indicates whether the data
-- from the memory are valid or if a wait state must be inserted when
-- accessing the memory in synchronous mode. This configuration bit
-- determines if NWAIT is asserted by the memory one clock cycle before
-- the wait state or during the wait state:
WAITCFG : Boolean := False;
-- Write enable bit This bit indicates whether write operations are
-- enabled/disabled in the bank by the FMC:
WREN : Boolean := True;
-- Wait enable bit This bit enables/disables wait-state insertion via
-- the NWAIT signal when accessing the memory in synchronous mode.
WAITEN : Boolean := True;
-- Extended mode enable. This bit enables the FMC to program the write
-- timings for asynchronous accesses inside the FMC_BWTR register, thus
-- resulting in different timings for read and write operations. Note:
-- When the extended mode is disabled, the FMC can operate in Mode1 or
-- Mode2 as follows: ** Mode 1 is the default mode when the SRAM/PSRAM
-- memory type is selected (MTYP =0x0 or 0x01) ** Mode 2 is the default
-- mode when the NOR memory type is selected (MTYP = 0x10).
EXTMOD : Boolean := False;
-- Wait signal during asynchronous transfers This bit enables/disables
-- the FMC to use the wait signal even during an asynchronous protocol.
ASYNCWAIT : Boolean := False;
-- CRAM Page Size These are used for Cellular RAM 1.5 which does not
-- allow burst access to cross the address boundaries between pages.
-- When these bits are configured, the FMC controller splits
-- automatically the burst access when the memory page size is reached
-- (refer to memory datasheet for page size). Other configuration:
-- reserved.
CPSIZE : BCR_CPSIZE_Field := 16#0#;
-- Write burst enable For PSRAM (CRAM) operating in Burst mode, the bit
-- enables synchronous accesses during write operations. The enable bit
-- for synchronous read accesses is the BURSTEN bit in the FMC_BCRx
-- register.
CBURSTRW : Boolean := False;
-- Continuous Clock Enable This bit enables the FMC_CLK clock output to
-- external memory devices. Note: The CCLKEN bit of the FMC_BCR2..4
-- registers is dont care. It is only enabled through the FMC_BCR1
-- register. Bank 1 must be configured in synchronous mode to generate
-- the FMC_CLK continuous clock. If CCLKEN bit is set, the FMC_CLK clock
-- ratio is specified by CLKDIV value in the FMC_BTR1 register. CLKDIV
-- in FMC_BWTR1 is dont care. If the synchronous mode is used and CCLKEN
-- bit is set, the synchronous memories connected to other banks than
-- Bank 1 are clocked by the same clock (the CLKDIV value in the
-- FMC_BTR2..4 and FMC_BWTR2..4 registers for other banks has no
-- effect.)
CCLKEN : Boolean := False;
-- Write FIFO Disable This bit disables the Write FIFO used by the FMC
-- controller. Note: The WFDIS bit of the FMC_BCR2..4 registers is dont
-- care. It is only enabled through the FMC_BCR1 register.
WFDIS : Boolean := False;
-- unspecified
Reserved_22_23 : HAL.UInt2 := 16#0#;
-- FMC bank mapping These bits allows different to remap SDRAM bank2 or
-- swap the FMC NOR/PSRAM and SDRAM banks.Refer to Table 10 for Note:
-- The BMAP bits of the FMC_BCR2..4 registers are dont care. It is only
-- enabled through the FMC_BCR1 register.
BMAP : BCR_BMAP_Field := 16#0#;
-- unspecified
Reserved_26_30 : HAL.UInt5 := 16#0#;
-- FMC controller Enable This bit enables/disables the FMC controller.
-- Note: The FMCEN bit of the FMC_BCR2..4 registers is dont care. It is
-- only enabled through the FMC_BCR1 register.
FMCEN : Boolean := False;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for BCR_Register use record
MBKEN at 0 range 0 .. 0;
MUXEN at 0 range 1 .. 1;
MTYP at 0 range 2 .. 3;
MWID at 0 range 4 .. 5;
FACCEN at 0 range 6 .. 6;
Reserved_7_7 at 0 range 7 .. 7;
BURSTEN at 0 range 8 .. 8;
WAITPOL at 0 range 9 .. 9;
Reserved_10_10 at 0 range 10 .. 10;
WAITCFG at 0 range 11 .. 11;
WREN at 0 range 12 .. 12;
WAITEN at 0 range 13 .. 13;
EXTMOD at 0 range 14 .. 14;
ASYNCWAIT at 0 range 15 .. 15;
CPSIZE at 0 range 16 .. 18;
CBURSTRW at 0 range 19 .. 19;
CCLKEN at 0 range 20 .. 20;
WFDIS at 0 range 21 .. 21;
Reserved_22_23 at 0 range 22 .. 23;
BMAP at 0 range 24 .. 25;
Reserved_26_30 at 0 range 26 .. 30;
FMCEN at 0 range 31 .. 31;
end record;
subtype BTR_ADDSET_Field is HAL.UInt4;
subtype BTR_ADDHLD_Field is HAL.UInt4;
subtype BTR_DATAST_Field is HAL.UInt8;
subtype BTR_BUSTURN_Field is HAL.UInt4;
subtype BTR_CLKDIV_Field is HAL.UInt4;
subtype BTR_DATLAT_Field is HAL.UInt4;
subtype BTR_ACCMOD_Field is HAL.UInt2;
-- This register contains the control information of each memory bank, used
-- for SRAMs, PSRAM and NOR Flash memories.If the EXTMOD bit is set in the
-- FMC_BCRx register, then this register is partitioned for write and read
-- access, that is, 2 registers are available: one to configure read
-- accesses (this register) and one to configure write accesses (FMC_BWTRx
-- registers).
type BTR_Register is record
-- Address setup phase duration These bits are written by software to
-- define the duration of the address setup phase (refer to Figure81 to
-- Figure93), used in SRAMs, ROMs and asynchronous NOR Flash: For each
-- access mode address setup phase duration, please refer to the
-- respective figure (refer to Figure81 to Figure93). Note: In
-- synchronous accesses, this value is dont care. In Muxed mode or Mode
-- D, the minimum value for ADDSET is 1.
ADDSET : BTR_ADDSET_Field := 16#F#;
-- Address-hold phase duration These bits are written by software to
-- define the duration of the address hold phase (refer to Figure81 to
-- Figure93), used in mode D or multiplexed accesses: For each access
-- mode address-hold phase duration, please refer to the respective
-- figure (Figure81 to Figure93). Note: In synchronous accesses, this
-- value is not used, the address hold phase is always 1 memory clock
-- period duration.
ADDHLD : BTR_ADDHLD_Field := 16#F#;
-- Data-phase duration These bits are written by software to define the
-- duration of the data phase (refer to Figure81 to Figure93), used in
-- asynchronous accesses: For each memory type and access mode
-- data-phase duration, please refer to the respective figure (Figure81
-- to Figure93). Example: Mode1, write access, DATAST=1: Data-phase
-- duration= DATAST+1 = 2 KCK_FMC clock cycles. Note: In synchronous
-- accesses, this value is dont care.
DATAST : BTR_DATAST_Field := 16#FF#;
-- Bus turnaround phase duration These bits are written by software to
-- add a delay at the end of a write-to-read or read-to write
-- transaction. The programmed bus turnaround delay is inserted between
-- an asynchronous read (in muxed or mode D) or write transaction and
-- any other asynchronous /synchronous read/write from/to a static bank.
-- If a read operation is performed, the bank can be the same or a
-- different one, whereas it must be different in case of write
-- operation to the bank, except in muxed mode or mode D. In some cases,
-- whatever the programmed BUSTRUN values, the bus turnaround delay is
-- fixed as follows: The bus turnaround delay is not inserted between
-- two consecutive asynchronous write transfers to the same static
-- memory bank except in muxed mode and mode D. There is a bus
-- turnaround delay of 1 FMC clock cycle between: Two consecutive
-- asynchronous read transfers to the same static memory bank except for
-- modes muxed and D. An asynchronous read to an asynchronous or
-- synchronous write to any static bank or dynamic bank except in modes
-- muxed and D mode. There is a bus turnaround delay of 2 FMC clock
-- cycle between: Two consecutive synchronous write operations (in Burst
-- or Single mode) to the same bank. A synchronous write (burst or
-- single) access and an asynchronous write or read transfer to or from
-- static memory bank (the bank can be the same or a different one in
-- case of a read operation. Two consecutive synchronous read operations
-- (in Burst or Single mode) followed by any synchronous/asynchronous
-- read or write from/to another static memory bank. There is a bus
-- turnaround delay of 3 FMC clock cycle between: Two consecutive
-- synchronous write operations (in Burst or Single mode) to different
-- static banks. A synchronous write access (in Burst or Single mode)
-- and a synchronous read from the same or a different bank. The bus
-- turnaround delay allows to match the minimum time between consecutive
-- transactions (tEHEL from NEx high to NEx low) and the maximum time
-- required by the memory to free the data bus after a read access
-- (tEHQZ): (BUSTRUN + 1) KCK_FMC period ≥ tEHELmin and (BUSTRUN +
-- 2)KCK_FMC period ≥ tEHQZmax if EXTMOD = 0 (BUSTRUN + 2)KCK_FMC
-- period ≥ max (tEHELmin, tEHQZmax) if EXTMOD = 126. ...
BUSTURN : BTR_BUSTURN_Field := 16#F#;
-- Clock divide ratio (for FMC_CLK signal) These bits define the period
-- of FMC_CLK clock output signal, expressed in number of KCK_FMC
-- cycles: In asynchronous NOR Flash, SRAM or PSRAM accesses, this value
-- is dont care. Note: Refer to Section20.6.5: Synchronous transactions
-- for FMC_CLK divider ratio formula)
CLKDIV : BTR_CLKDIV_Field := 16#F#;
-- Data latency for synchronous memory For synchronous access with read
-- write burst mode enabled these bits define the number of memory clock
-- cycles
DATLAT : BTR_DATLAT_Field := 16#F#;
-- Access mode These bits specify the asynchronous access modes as shown
-- in the timing diagrams. They are taken into account only when the
-- EXTMOD bit in the FMC_BCRx register is 1.
ACCMOD : BTR_ACCMOD_Field := 16#0#;
-- unspecified
Reserved_30_31 : HAL.UInt2 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for BTR_Register use record
ADDSET at 0 range 0 .. 3;
ADDHLD at 0 range 4 .. 7;
DATAST at 0 range 8 .. 15;
BUSTURN at 0 range 16 .. 19;
CLKDIV at 0 range 20 .. 23;
DATLAT at 0 range 24 .. 27;
ACCMOD at 0 range 28 .. 29;
Reserved_30_31 at 0 range 30 .. 31;
end record;
subtype PCR_PWID_Field is HAL.UInt2;
subtype PCR_TCLR_Field is HAL.UInt4;
subtype PCR_TAR_Field is HAL.UInt4;
subtype PCR_ECCPS_Field is HAL.UInt3;
-- NAND Flash control registers
type PCR_Register is record
-- unspecified
Reserved_0_0 : HAL.Bit := 16#0#;
-- Wait feature enable bit. This bit enables the Wait feature for the
-- NAND Flash memory bank:
PWAITEN : Boolean := False;
-- NAND Flash memory bank enable bit. This bit enables the memory bank.
-- Accessing a disabled memory bank causes an ERROR on AXI bus
PBKEN : Boolean := False;
-- unspecified
Reserved_3_3 : HAL.Bit := 16#1#;
-- Data bus width. These bits define the external memory device width.
PWID : PCR_PWID_Field := 16#1#;
-- ECC computation logic enable bit
ECCEN : Boolean := False;
-- unspecified
Reserved_7_8 : HAL.UInt2 := 16#0#;
-- CLE to RE delay. These bits set time from CLE low to RE low in number
-- of KCK_FMC clock cycles. The time is give by the following formula:
-- t_clr = (TCLR + SET + 2) TKCK_FMC where TKCK_FMC is the KCK_FMC clock
-- period Note: Set is MEMSET or ATTSET according to the addressed
-- space.
TCLR : PCR_TCLR_Field := 16#0#;
-- ALE to RE delay. These bits set time from ALE low to RE low in number
-- of KCK_FMC clock cycles. Time is: t_ar = (TAR + SET + 2) TKCK_FMC
-- where TKCK_FMC is the FMC clock period Note: Set is MEMSET or ATTSET
-- according to the addressed space.
TAR : PCR_TAR_Field := 16#0#;
-- ECC page size. These bits define the page size for the extended ECC:
ECCPS : PCR_ECCPS_Field := 16#0#;
-- unspecified
Reserved_20_31 : HAL.UInt12 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for PCR_Register use record
Reserved_0_0 at 0 range 0 .. 0;
PWAITEN at 0 range 1 .. 1;
PBKEN at 0 range 2 .. 2;
Reserved_3_3 at 0 range 3 .. 3;
PWID at 0 range 4 .. 5;
ECCEN at 0 range 6 .. 6;
Reserved_7_8 at 0 range 7 .. 8;
TCLR at 0 range 9 .. 12;
TAR at 0 range 13 .. 16;
ECCPS at 0 range 17 .. 19;
Reserved_20_31 at 0 range 20 .. 31;
end record;
-- This register contains information about the FIFO status and interrupt.
-- The FMC features a FIFO that is used when writing to memories to
-- transfer up to 16 words of data.This is used to quickly write to the
-- FIFO and free the AXI bus for transactions to peripherals other than the
-- FMC, while the FMC is draining its FIFO into the memory. One of these
-- register bits indicates the status of the FIFO, for ECC purposes.The ECC
-- is calculated while the data are written to the memory. To read the
-- correct ECC, the software must consequently wait until the FIFO is
-- empty.
type SR_Register is record
-- Interrupt rising edge status The flag is set by hardware and reset by
-- software. Note: If this bit is written by software to 1 it will be
-- set.
IRS : Boolean := False;
-- Interrupt high-level status The flag is set by hardware and reset by
-- software.
ILS : Boolean := False;
-- Interrupt falling edge status The flag is set by hardware and reset
-- by software. Note: If this bit is written by software to 1 it will be
-- set.
IFS : Boolean := False;
-- Interrupt rising edge detection enable bit
IREN : Boolean := False;
-- Interrupt high-level detection enable bit
ILEN : Boolean := False;
-- Interrupt falling edge detection enable bit
IFEN : Boolean := False;
-- Read-only. FIFO empty. Read-only bit that provides the status of the
-- FIFO
FEMPT : Boolean := True;
-- unspecified
Reserved_7_31 : HAL.UInt25 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for SR_Register use record
IRS at 0 range 0 .. 0;
ILS at 0 range 1 .. 1;
IFS at 0 range 2 .. 2;
IREN at 0 range 3 .. 3;
ILEN at 0 range 4 .. 4;
IFEN at 0 range 5 .. 5;
FEMPT at 0 range 6 .. 6;
Reserved_7_31 at 0 range 7 .. 31;
end record;
subtype PMEM_MEMSET_Field is HAL.UInt8;
subtype PMEM_MEMWAIT_Field is HAL.UInt8;
subtype PMEM_MEMHOLD_Field is HAL.UInt8;
subtype PMEM_MEMHIZ_Field is HAL.UInt8;
-- The FMC_PMEM read/write register contains the timing information for
-- NAND Flash memory bank. This information is used to access either the
-- common memory space of the NAND Flash for command, address write access
-- and data read/write access.
type PMEM_Register is record
-- Common memory x setup time These bits define the number of KCK_FMC
-- (+1) clock cycles to set up the address before the command assertion
-- (NWE, NOE), for NAND Flash read or write access to common memory
-- space:
MEMSET : PMEM_MEMSET_Field := 16#FC#;
-- Common memory wait time These bits define the minimum number of
-- KCK_FMC (+1) clock cycles to assert the command (NWE, NOE), for NAND
-- Flash read or write access to common memory space. The duration of
-- command assertion is extended if the wait signal (NWAIT) is active
-- (low) at the end of the programmed value of KCK_FMC:
MEMWAIT : PMEM_MEMWAIT_Field := 16#FC#;
-- Common memory hold time These bits define the number of KCK_FMC clock
-- cycles for write accesses and KCK_FMC+1 clock cycles for read
-- accesses during which the address is held (and data for write
-- accesses) after the command is de-asserted (NWE, NOE), for NAND Flash
-- read or write access to common memory space:
MEMHOLD : PMEM_MEMHOLD_Field := 16#FC#;
-- Common memory x data bus Hi-Z time These bits define the number of
-- KCK_FMC clock cycles during which the data bus is kept Hi-Z after the
-- start of a NAND Flash write access to common memory space. This is
-- only valid for write transactions:
MEMHIZ : PMEM_MEMHIZ_Field := 16#FC#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for PMEM_Register use record
MEMSET at 0 range 0 .. 7;
MEMWAIT at 0 range 8 .. 15;
MEMHOLD at 0 range 16 .. 23;
MEMHIZ at 0 range 24 .. 31;
end record;
subtype PATT_ATTSET_Field is HAL.UInt8;
subtype PATT_ATTWAIT_Field is HAL.UInt8;
subtype PATT_ATTHOLD_Field is HAL.UInt8;
subtype PATT_ATTHIZ_Field is HAL.UInt8;
-- The FMC_PATT read/write register contains the timing information for
-- NAND Flash memory bank. It is used for 8-bit accesses to the attribute
-- memory space of the NAND Flash for the last address write access if the
-- timing must differ from that of previous accesses (for Ready/Busy
-- management, refer to Section20.8.5: NAND Flash prewait feature).
type PATT_Register is record
-- Attribute memory setup time These bits define the number of KCK_FMC
-- (+1) clock cycles to set up address before the command assertion
-- (NWE, NOE), for NAND Flash read or write access to attribute memory
-- space:
ATTSET : PATT_ATTSET_Field := 16#FC#;
-- Attribute memory wait time These bits define the minimum number of x
-- KCK_FMC (+1) clock cycles to assert the command (NWE, NOE), for NAND
-- Flash read or write access to attribute memory space. The duration
-- for command assertion is extended if the wait signal (NWAIT) is
-- active (low) at the end of the programmed value of KCK_FMC:
ATTWAIT : PATT_ATTWAIT_Field := 16#FC#;
-- Attribute memory hold time These bits define the number of KCK_FMC
-- clock cycles during which the address is held (and data for write
-- access) after the command de-assertion (NWE, NOE), for NAND Flash
-- read or write access to attribute memory space:
ATTHOLD : PATT_ATTHOLD_Field := 16#FC#;
-- Attribute memory data bus Hi-Z time These bits define the number of
-- KCK_FMC clock cycles during which the data bus is kept in Hi-Z after
-- the start of a NAND Flash write access to attribute memory space on
-- socket. Only valid for writ transaction:
ATTHIZ : PATT_ATTHIZ_Field := 16#FC#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for PATT_Register use record
ATTSET at 0 range 0 .. 7;
ATTWAIT at 0 range 8 .. 15;
ATTHOLD at 0 range 16 .. 23;
ATTHIZ at 0 range 24 .. 31;
end record;
subtype BWTR_ADDSET_Field is HAL.UInt4;
subtype BWTR_ADDHLD_Field is HAL.UInt4;
subtype BWTR_DATAST_Field is HAL.UInt8;
subtype BWTR_BUSTURN_Field is HAL.UInt4;
subtype BWTR_ACCMOD_Field is HAL.UInt2;
-- This register contains the control information of each memory bank. It
-- is used for SRAMs, PSRAMs and NOR Flash memories. When the EXTMOD bit is
-- set in the FMC_BCRx register, then this register is active for write
-- access.
type BWTR_Register is record
-- Address setup phase duration. These bits are written by software to
-- define the duration of the address setup phase in KCK_FMC cycles
-- (refer to Figure81 to Figure93), used in asynchronous accesses: ...
-- Note: In synchronous accesses, this value is not used, the address
-- setup phase is always 1 Flash clock period duration. In muxed mode,
-- the minimum ADDSET value is 1.
ADDSET : BWTR_ADDSET_Field := 16#F#;
-- Address-hold phase duration. These bits are written by software to
-- define the duration of the address hold phase (refer to Figure81 to
-- Figure93), used in asynchronous multiplexed accesses: ... Note: In
-- synchronous NOR Flash accesses, this value is not used, the address
-- hold phase is always 1 Flash clock period duration.
ADDHLD : BWTR_ADDHLD_Field := 16#F#;
-- Data-phase duration. These bits are written by software to define the
-- duration of the data phase (refer to Figure81 to Figure93), used in
-- asynchronous SRAM, PSRAM and NOR Flash memory accesses:
DATAST : BWTR_DATAST_Field := 16#FF#;
-- Bus turnaround phase duration These bits are written by software to
-- add a delay at the end of a write transaction to match the minimum
-- time between consecutive transactions (tEHEL from ENx high to ENx
-- low): (BUSTRUN + 1) KCK_FMC period ≥ tEHELmin. The programmed
-- bus turnaround delay is inserted between a an asynchronous write
-- transfer and any other asynchronous /synchronous read or write
-- transfer to or from a static bank. If a read operation is performed,
-- the bank can be the same or a different one, whereas it must be
-- different in case of write operation to the bank, except in muxed
-- mode or mode D. In some cases, whatever the programmed BUSTRUN
-- values, the bus turnaround delay is fixed as follows: The bus
-- turnaround delay is not inserted between two consecutive asynchronous
-- write transfers to the same static memory bank except for muxed mode
-- and mode D. There is a bus turnaround delay of 2 FMC clock cycle
-- between: Two consecutive synchronous write operations (in Burst or
-- Single mode) to the same bank A synchronous write transfer ((in Burst
-- or Single mode) and an asynchronous write or read transfer to or from
-- static memory bank. There is a bus turnaround delay of 3 FMC clock
-- cycle between: Two consecutive synchronous write operations (in Burst
-- or Single mode) to different static banks. A synchronous write
-- transfer (in Burst or Single mode) and a synchronous read from the
-- same or a different bank. ...
BUSTURN : BWTR_BUSTURN_Field := 16#F#;
-- unspecified
Reserved_20_27 : HAL.UInt8 := 16#FF#;
-- Access mode. These bits specify the asynchronous access modes as
-- shown in the next timing diagrams.These bits are taken into account
-- only when the EXTMOD bit in the FMC_BCRx register is 1.
ACCMOD : BWTR_ACCMOD_Field := 16#0#;
-- unspecified
Reserved_30_31 : HAL.UInt2 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for BWTR_Register use record
ADDSET at 0 range 0 .. 3;
ADDHLD at 0 range 4 .. 7;
DATAST at 0 range 8 .. 15;
BUSTURN at 0 range 16 .. 19;
Reserved_20_27 at 0 range 20 .. 27;
ACCMOD at 0 range 28 .. 29;
Reserved_30_31 at 0 range 30 .. 31;
end record;
subtype SDCR_NC_Field is HAL.UInt2;
subtype SDCR_NR_Field is HAL.UInt2;
subtype SDCR_MWID_Field is HAL.UInt2;
subtype SDCR_CAS_Field is HAL.UInt2;
subtype SDCR_SDCLK_Field is HAL.UInt2;
subtype SDCR_RPIPE_Field is HAL.UInt2;
-- This register contains the control parameters for each SDRAM memory bank
type SDCR_Register is record
-- Number of column address bits These bits define the number of bits of
-- a column address.
NC : SDCR_NC_Field := 16#0#;
-- Number of row address bits These bits define the number of bits of a
-- row address.
NR : SDCR_NR_Field := 16#0#;
-- Memory data bus width. These bits define the memory device width.
MWID : SDCR_MWID_Field := 16#1#;
-- Number of internal banks This bit sets the number of internal banks.
NB : Boolean := True;
-- CAS Latency This bits sets the SDRAM CAS latency in number of memory
-- clock cycles
CAS : SDCR_CAS_Field := 16#1#;
-- Write protection This bit enables write mode access to the SDRAM
-- bank.
WP : Boolean := True;
-- SDRAM clock configuration These bits define the SDRAM clock period
-- for both SDRAM banks and allow disabling the clock before changing
-- the frequency. In this case the SDRAM must be re-initialized. Note:
-- The corresponding bits in the FMC_SDCR2 register is read only.
SDCLK : SDCR_SDCLK_Field := 16#0#;
-- Burst read This bit enables burst read mode. The SDRAM controller
-- anticipates the next read commands during the CAS latency and stores
-- data in the Read FIFO. Note: The corresponding bit in the FMC_SDCR2
-- register is read only.
RBURST : Boolean := False;
-- Read pipe These bits define the delay, in KCK_FMC clock cycles, for
-- reading data after CAS latency. Note: The corresponding bits in the
-- FMC_SDCR2 register is read only.
RPIPE : SDCR_RPIPE_Field := 16#0#;
-- unspecified
Reserved_15_31 : HAL.UInt17 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for SDCR_Register use record
NC at 0 range 0 .. 1;
NR at 0 range 2 .. 3;
MWID at 0 range 4 .. 5;
NB at 0 range 6 .. 6;
CAS at 0 range 7 .. 8;
WP at 0 range 9 .. 9;
SDCLK at 0 range 10 .. 11;
RBURST at 0 range 12 .. 12;
RPIPE at 0 range 13 .. 14;
Reserved_15_31 at 0 range 15 .. 31;
end record;
subtype SDTR_TMRD_Field is HAL.UInt4;
subtype SDTR_TXSR_Field is HAL.UInt4;
subtype SDTR_TRAS_Field is HAL.UInt4;
subtype SDTR_TRC_Field is HAL.UInt4;
subtype SDTR_TWR_Field is HAL.UInt4;
subtype SDTR_TRP_Field is HAL.UInt4;
subtype SDTR_TRCD_Field is HAL.UInt4;
-- This register contains the timing parameters of each SDRAM bank
type SDTR_Register is record
-- Load Mode Register to Active These bits define the delay between a
-- Load Mode Register command and an Active or Refresh command in number
-- of memory clock cycles. ....
TMRD : SDTR_TMRD_Field := 16#F#;
-- Exit Self-refresh delay These bits define the delay from releasing
-- the Self-refresh command to issuing the Activate command in number of
-- memory clock cycles. .... Note: If two SDRAM devices are used, the
-- FMC_SDTR1 and FMC_SDTR2 must be programmed with the same TXSR timing
-- corresponding to the slowest SDRAM device.
TXSR : SDTR_TXSR_Field := 16#F#;
-- Self refresh time These bits define the minimum Self-refresh period
-- in number of memory clock cycles. ....
TRAS : SDTR_TRAS_Field := 16#F#;
-- Row cycle delay These bits define the delay between the Refresh
-- command and the Activate command, as well as the delay between two
-- consecutive Refresh commands. It is expressed in number of memory
-- clock cycles. The TRC timing is only configured in the FMC_SDTR1
-- register. If two SDRAM devices are used, the TRC must be programmed
-- with the timings of the slowest device. .... Note: TRC must match the
-- TRC and TRFC (Auto Refresh period) timings defined in the SDRAM
-- device datasheet. Note: The corresponding bits in the FMC_SDTR2
-- register are dont care.
TRC : SDTR_TRC_Field := 16#F#;
-- Recovery delay These bits define the delay between a Write and a
-- Precharge command in number of memory clock cycles. .... Note: TWR
-- must be programmed to match the write recovery time (tWR) defined in
-- the SDRAM datasheet, and to guarantee that: TWR ≥ TRAS - TRCD
-- and TWR ≥TRC - TRCD - TRP Example: TRAS= 4 cycles, TRCD= 2
-- cycles. So, TWR >= 2 cycles. TWR must be programmed to 0x1. If two
-- SDRAM devices are used, the FMC_SDTR1 and FMC_SDTR2 must be
-- programmed with the same TWR timing corresponding to the slowest
-- SDRAM device.
TWR : SDTR_TWR_Field := 16#F#;
-- Row precharge delay These bits define the delay between a Precharge
-- command and another command in number of memory clock cycles. The TRP
-- timing is only configured in the FMC_SDTR1 register. If two SDRAM
-- devices are used, the TRP must be programmed with the timing of the
-- slowest device. .... Note: The corresponding bits in the FMC_SDTR2
-- register are dont care.
TRP : SDTR_TRP_Field := 16#F#;
-- Row to column delay These bits define the delay between the Activate
-- command and a Read/Write command in number of memory clock cycles.
-- ....
TRCD : SDTR_TRCD_Field := 16#F#;
-- unspecified
Reserved_28_31 : HAL.UInt4 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for SDTR_Register use record
TMRD at 0 range 0 .. 3;
TXSR at 0 range 4 .. 7;
TRAS at 0 range 8 .. 11;
TRC at 0 range 12 .. 15;
TWR at 0 range 16 .. 19;
TRP at 0 range 20 .. 23;
TRCD at 0 range 24 .. 27;
Reserved_28_31 at 0 range 28 .. 31;
end record;
subtype SDCMR_MODE_Field is HAL.UInt3;
subtype SDCMR_NRFS_Field is HAL.UInt4;
subtype SDCMR_MRD_Field is HAL.UInt14;
-- This register contains the command issued when the SDRAM device is
-- accessed. This register is used to initialize the SDRAM device, and to
-- activate the Self-refresh and the Power-down modes. As soon as the MODE
-- field is written, the command will be issued only to one or to both
-- SDRAM banks according to CTB1 and CTB2 command bits. This register is
-- the same for both SDRAM banks.
type SDCMR_Register is record
-- Command mode These bits define the command issued to the SDRAM
-- device. Note: When a command is issued, at least one Command Target
-- Bank bit ( CTB1 or CTB2) must be set otherwise the command will be
-- ignored. Note: If two SDRAM banks are used, the Auto-refresh and PALL
-- command must be issued simultaneously to the two devices with CTB1
-- and CTB2 bits set otherwise the command will be ignored. Note: If
-- only one SDRAM bank is used and a command is issued with its
-- associated CTB bit set, the other CTB bit of the unused bank must be
-- kept to 0.
MODE : SDCMR_MODE_Field := 16#0#;
-- Command Target Bank 2 This bit indicates whether the command will be
-- issued to SDRAM Bank 2 or not.
CTB2 : Boolean := False;
-- Command Target Bank 1 This bit indicates whether the command will be
-- issued to SDRAM Bank 1 or not.
CTB1 : Boolean := False;
-- Number of Auto-refresh These bits define the number of consecutive
-- Auto-refresh commands issued when MODE = 011. ....
NRFS : SDCMR_NRFS_Field := 16#0#;
-- Mode Register definition This 14-bit field defines the SDRAM Mode
-- Register content. The Mode Register is programmed using the Load Mode
-- Register command. The MRD[13:0] bits are also used to program the
-- extended mode register for mobile SDRAM.
MRD : SDCMR_MRD_Field := 16#0#;
-- unspecified
Reserved_23_31 : HAL.UInt9 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for SDCMR_Register use record
MODE at 0 range 0 .. 2;
CTB2 at 0 range 3 .. 3;
CTB1 at 0 range 4 .. 4;
NRFS at 0 range 5 .. 8;
MRD at 0 range 9 .. 22;
Reserved_23_31 at 0 range 23 .. 31;
end record;
subtype SDRTR_COUNT_Field is HAL.UInt13;
-- This register sets the refresh rate in number of SDCLK clock cycles
-- between the refresh cycles by configuring the Refresh Timer Count
-- value.Examplewhere 64 ms is the SDRAM refresh period.The refresh rate
-- must be increased by 20 SDRAM clock cycles (as in the above example) to
-- obtain a safe margin if an internal refresh request occurs when a read
-- request has been accepted. It corresponds to a COUNT value of
-- 0000111000000 (448). This 13-bit field is loaded into a timer which is
-- decremented using the SDRAM clock. This timer generates a refresh pulse
-- when zero is reached. The COUNT value must be set at least to 41 SDRAM
-- clock cycles.As soon as the FMC_SDRTR register is programmed, the timer
-- starts counting. If the value programmed in the register is 0, no
-- refresh is carried out. This register must not be reprogrammed after the
-- initialization procedure to avoid modifying the refresh rate.Each time a
-- refresh pulse is generated, this 13-bit COUNT field is reloaded into the
-- counter.If a memory access is in progress, the Auto-refresh request is
-- delayed. However, if the memory access and Auto-refresh requests are
-- generated simultaneously, the Auto-refresh takes precedence. If the
-- memory access occurs during a refresh operation, the request is buffered
-- to be processed when the refresh is complete.This register is common to
-- SDRAM bank 1 and bank 2.
type SDRTR_Register is record
-- Write-only. Clear Refresh error flag This bit is used to clear the
-- Refresh Error Flag (RE) in the Status Register.
CRE : Boolean := False;
-- Refresh Timer Count This 13-bit field defines the refresh rate of the
-- SDRAM device. It is expressed in number of memory clock cycles. It
-- must be set at least to 41 SDRAM clock cycles (0x29). Refresh rate =
-- (COUNT + 1) x SDRAM frequency clock COUNT = (SDRAM refresh period /
-- Number of rows) - 20
COUNT : SDRTR_COUNT_Field := 16#0#;
-- RES Interrupt Enable
REIE : Boolean := False;
-- unspecified
Reserved_15_31 : HAL.UInt17 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for SDRTR_Register use record
CRE at 0 range 0 .. 0;
COUNT at 0 range 1 .. 13;
REIE at 0 range 14 .. 14;
Reserved_15_31 at 0 range 15 .. 31;
end record;
-- SDSR_MODES array element
subtype SDSR_MODES_Element is HAL.UInt2;
-- SDSR_MODES array
type SDSR_MODES_Field_Array is array (1 .. 2) of SDSR_MODES_Element
with Component_Size => 2, Size => 4;
-- Type definition for SDSR_MODES
type SDSR_MODES_Field
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- MODES as a value
Val : HAL.UInt4;
when True =>
-- MODES as an array
Arr : SDSR_MODES_Field_Array;
end case;
end record
with Unchecked_Union, Size => 4;
for SDSR_MODES_Field use record
Val at 0 range 0 .. 3;
Arr at 0 range 0 .. 3;
end record;
-- SDRAM Status register
type SDSR_Register is record
-- Read-only. Refresh error flag An interrupt is generated if REIE = 1
-- and RE = 1
RE : Boolean;
-- Read-only. Status Mode for Bank 1 These bits define the Status Mode
-- of SDRAM Bank 1.
MODES : SDSR_MODES_Field;
-- unspecified
Reserved_5_31 : HAL.UInt27;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for SDSR_Register use record
RE at 0 range 0 .. 0;
MODES at 0 range 1 .. 4;
Reserved_5_31 at 0 range 5 .. 31;
end record;
-----------------
-- Peripherals --
-----------------
-- FMC
type FMC_Peripheral is record
-- This register contains the control information of each memory bank,
-- used for SRAMs, PSRAM and NOR Flash memories.
BCR1 : aliased BCR_Register;
-- This register contains the control information of each memory bank,
-- used for SRAMs, PSRAM and NOR Flash memories.If the EXTMOD bit is set
-- in the FMC_BCRx register, then this register is partitioned for write
-- and read access, that is, 2 registers are available: one to configure
-- read accesses (this register) and one to configure write accesses
-- (FMC_BWTRx registers).
BTR1 : aliased BTR_Register;
-- This register contains the control information of each memory bank,
-- used for SRAMs, PSRAM and NOR Flash memories.
BCR2 : aliased BCR_Register;
-- This register contains the control information of each memory bank,
-- used for SRAMs, PSRAM and NOR Flash memories.If the EXTMOD bit is set
-- in the FMC_BCRx register, then this register is partitioned for write
-- and read access, that is, 2 registers are available: one to configure
-- read accesses (this register) and one to configure write accesses
-- (FMC_BWTRx registers).
BTR2 : aliased BTR_Register;
-- This register contains the control information of each memory bank,
-- used for SRAMs, PSRAM and NOR Flash memories.
BCR3 : aliased BCR_Register;
-- This register contains the control information of each memory bank,
-- used for SRAMs, PSRAM and NOR Flash memories.If the EXTMOD bit is set
-- in the FMC_BCRx register, then this register is partitioned for write
-- and read access, that is, 2 registers are available: one to configure
-- read accesses (this register) and one to configure write accesses
-- (FMC_BWTRx registers).
BTR3 : aliased BTR_Register;
-- This register contains the control information of each memory bank,
-- used for SRAMs, PSRAM and NOR Flash memories.
BCR4 : aliased BCR_Register;
-- This register contains the control information of each memory bank,
-- used for SRAMs, PSRAM and NOR Flash memories.If the EXTMOD bit is set
-- in the FMC_BCRx register, then this register is partitioned for write
-- and read access, that is, 2 registers are available: one to configure
-- read accesses (this register) and one to configure write accesses
-- (FMC_BWTRx registers).
BTR4 : aliased BTR_Register;
-- NAND Flash control registers
PCR : aliased PCR_Register;
-- This register contains information about the FIFO status and
-- interrupt. The FMC features a FIFO that is used when writing to
-- memories to transfer up to 16 words of data.This is used to quickly
-- write to the FIFO and free the AXI bus for transactions to
-- peripherals other than the FMC, while the FMC is draining its FIFO
-- into the memory. One of these register bits indicates the status of
-- the FIFO, for ECC purposes.The ECC is calculated while the data are
-- written to the memory. To read the correct ECC, the software must
-- consequently wait until the FIFO is empty.
SR : aliased SR_Register;
-- The FMC_PMEM read/write register contains the timing information for
-- NAND Flash memory bank. This information is used to access either the
-- common memory space of the NAND Flash for command, address write
-- access and data read/write access.
PMEM : aliased PMEM_Register;
-- The FMC_PATT read/write register contains the timing information for
-- NAND Flash memory bank. It is used for 8-bit accesses to the
-- attribute memory space of the NAND Flash for the last address write
-- access if the timing must differ from that of previous accesses (for
-- Ready/Busy management, refer to Section20.8.5: NAND Flash prewait
-- feature).
PATT : aliased PATT_Register;
-- This register contain the current error correction code value
-- computed by the ECC computation modules of the FMC NAND controller.
-- When the CPU reads/writes the data from a NAND Flash memory page at
-- the correct address (refer to Section20.8.6: Computation of the error
-- correction code (ECC) in NAND Flash memory), the data read/written
-- from/to the NAND Flash memory are processed automatically by the ECC
-- computation module. When X bytes have been read (according to the
-- ECCPS field in the FMC_PCR registers), the CPU must read the computed
-- ECC value from the FMC_ECC registers. It then verifies if these
-- computed parity data are the same as the parity value recorded in the
-- spare area, to determine whether a page is valid, and, to correct it
-- otherwise. The FMC_ECCR register should be cleared after being read
-- by setting the ECCEN bit to 0. To compute a new data block, the ECCEN
-- bit must be set to 1.
ECCR : aliased HAL.UInt32;
-- This register contains the control information of each memory bank.
-- It is used for SRAMs, PSRAMs and NOR Flash memories. When the EXTMOD
-- bit is set in the FMC_BCRx register, then this register is active for
-- write access.
BWTR1 : aliased BWTR_Register;
-- This register contains the control information of each memory bank.
-- It is used for SRAMs, PSRAMs and NOR Flash memories. When the EXTMOD
-- bit is set in the FMC_BCRx register, then this register is active for
-- write access.
BWTR2 : aliased BWTR_Register;
-- This register contains the control information of each memory bank.
-- It is used for SRAMs, PSRAMs and NOR Flash memories. When the EXTMOD
-- bit is set in the FMC_BCRx register, then this register is active for
-- write access.
BWTR3 : aliased BWTR_Register;
-- This register contains the control information of each memory bank.
-- It is used for SRAMs, PSRAMs and NOR Flash memories. When the EXTMOD
-- bit is set in the FMC_BCRx register, then this register is active for
-- write access.
BWTR4 : aliased BWTR_Register;
-- This register contains the control parameters for each SDRAM memory
-- bank
SDCR1 : aliased SDCR_Register;
-- This register contains the control parameters for each SDRAM memory
-- bank
SDCR2 : aliased SDCR_Register;
-- This register contains the timing parameters of each SDRAM bank
SDTR1 : aliased SDTR_Register;
-- This register contains the timing parameters of each SDRAM bank
SDTR2 : aliased SDTR_Register;
-- This register contains the command issued when the SDRAM device is
-- accessed. This register is used to initialize the SDRAM device, and
-- to activate the Self-refresh and the Power-down modes. As soon as the
-- MODE field is written, the command will be issued only to one or to
-- both SDRAM banks according to CTB1 and CTB2 command bits. This
-- register is the same for both SDRAM banks.
SDCMR : aliased SDCMR_Register;
-- This register sets the refresh rate in number of SDCLK clock cycles
-- between the refresh cycles by configuring the Refresh Timer Count
-- value.Examplewhere 64 ms is the SDRAM refresh period.The refresh rate
-- must be increased by 20 SDRAM clock cycles (as in the above example)
-- to obtain a safe margin if an internal refresh request occurs when a
-- read request has been accepted. It corresponds to a COUNT value of
-- 0000111000000 (448). This 13-bit field is loaded into a timer which
-- is decremented using the SDRAM clock. This timer generates a refresh
-- pulse when zero is reached. The COUNT value must be set at least to
-- 41 SDRAM clock cycles.As soon as the FMC_SDRTR register is
-- programmed, the timer starts counting. If the value programmed in the
-- register is 0, no refresh is carried out. This register must not be
-- reprogrammed after the initialization procedure to avoid modifying
-- the refresh rate.Each time a refresh pulse is generated, this 13-bit
-- COUNT field is reloaded into the counter.If a memory access is in
-- progress, the Auto-refresh request is delayed. However, if the memory
-- access and Auto-refresh requests are generated simultaneously, the
-- Auto-refresh takes precedence. If the memory access occurs during a
-- refresh operation, the request is buffered to be processed when the
-- refresh is complete.This register is common to SDRAM bank 1 and bank
-- 2.
SDRTR : aliased SDRTR_Register;
-- SDRAM Status register
SDSR : aliased SDSR_Register;
end record
with Volatile;
for FMC_Peripheral use record
BCR1 at 16#0# range 0 .. 31;
BTR1 at 16#4# range 0 .. 31;
BCR2 at 16#8# range 0 .. 31;
BTR2 at 16#C# range 0 .. 31;
BCR3 at 16#10# range 0 .. 31;
BTR3 at 16#14# range 0 .. 31;
BCR4 at 16#18# range 0 .. 31;
BTR4 at 16#1C# range 0 .. 31;
PCR at 16#80# range 0 .. 31;
SR at 16#84# range 0 .. 31;
PMEM at 16#88# range 0 .. 31;
PATT at 16#8C# range 0 .. 31;
ECCR at 16#94# range 0 .. 31;
BWTR1 at 16#104# range 0 .. 31;
BWTR2 at 16#10C# range 0 .. 31;
BWTR3 at 16#114# range 0 .. 31;
BWTR4 at 16#11C# range 0 .. 31;
SDCR1 at 16#140# range 0 .. 31;
SDCR2 at 16#144# range 0 .. 31;
SDTR1 at 16#148# range 0 .. 31;
SDTR2 at 16#14C# range 0 .. 31;
SDCMR at 16#150# range 0 .. 31;
SDRTR at 16#154# range 0 .. 31;
SDSR at 16#158# range 0 .. 31;
end record;
-- FMC
FMC_Periph : aliased FMC_Peripheral
with Import, Address => FMC_Base;
end STM32_SVD.FMC;
|
with Ada.Text_IO, Ada.Containers.Indefinite_Vectors;
use Ada.Text_IO;
procedure Ordered_Words is
package Word_Vectors is new Ada.Containers.Indefinite_Vectors
(Index_Type => Positive, Element_Type => String);
use Word_Vectors;
File : File_Type;
Ordered_Words : Vector;
Max_Length : Positive := 1;
begin
Open (File, In_File, "unixdict.txt");
while not End_Of_File (File) loop
declare
Word : String := Get_Line (File);
begin
if (for all i in Word'First..Word'Last-1 => Word (i) <= Word(i+1)) then
if Word'Length > Max_Length then
Max_Length := Word'Length;
Ordered_Words.Clear;
Ordered_Words.Append (Word);
elsif Word'Length = Max_Length then
Ordered_Words.Append (Word);
end if;
end if;
end;
end loop;
for Word of Ordered_Words loop
Put_Line (Word);
end loop;
Close (File);
end Ordered_Words;
|
-----------------------------------------------------------------------
-- util-beans-objects-maps -- Object maps
-- Copyright (C) 2010, 2011, 2012, 2017, 2018 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.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with Util.Beans.Basic;
package Util.Beans.Objects.Maps is
package Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Object,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=");
subtype Cursor is Maps.Cursor;
subtype Map is Maps.Map;
-- Make all the Maps operations available (a kind of 'use Maps' for anybody).
function Length (Container : in Map) return Ada.Containers.Count_Type renames Maps.Length;
function Is_Empty (Container : in Map) return Boolean renames Maps.Is_Empty;
procedure Clear (Container : in out Map) renames Maps.Clear;
function Key (Position : Cursor) return String renames Maps.Key;
procedure Include (Container : in out Map;
Key : in String;
New_Item : in Object) renames Maps.Include;
procedure Query_Element (Position : in Cursor;
Process : not null access procedure (Key : String;
Element : Object))
renames Maps.Query_Element;
function Has_Element (Position : Cursor) return Boolean renames Maps.Has_Element;
function Element (Position : Cursor) return Object renames Maps.Element;
procedure Next (Position : in out Cursor) renames Maps.Next;
function Next (Position : Cursor) return Cursor renames Maps.Next;
function Equivalent_Keys (Left, Right : Cursor) return Boolean renames Maps.Equivalent_Keys;
function Equivalent_Keys (Left : Cursor; Right : String) return Boolean
renames Maps.Equivalent_Keys;
function Equivalent_Keys (Left : String; Right : Cursor) return Boolean
renames Maps.Equivalent_Keys;
function Copy (Source : Maps.Map; Capacity : in Ada.Containers.Count_Type) return Maps.Map
renames Maps.Copy;
-- ------------------------------
-- Map Bean
-- ------------------------------
-- The <b>Map_Bean</b> is a map of objects that also exposes the <b>Bean</b> interface.
-- This allows the map to be available and accessed from an Object instance.
type Map_Bean is new Maps.Map and Util.Beans.Basic.Bean with private;
type Map_Bean_Access is access all Map_Bean'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
function Get_Value (From : in Map_Bean;
Name : in String) return Object;
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
procedure Set_Value (From : in out Map_Bean;
Name : in String;
Value : in Object);
-- Create an object that contains a <tt>Map_Bean</tt> instance.
function Create return Object;
-- Iterate over the members of the map.
procedure Iterate (From : in Object;
Process : not null access procedure (Name : in String;
Item : in Object));
private
type Map_Bean is new Maps.Map and Util.Beans.Basic.Bean with null record;
end Util.Beans.Objects.Maps;
|
with Ada.Wide_Wide_Text_IO;
package body Output_Backend is
package IO renames Ada.Wide_Wide_Text_IO;
task body Output is
begin
accept Ready_Wait;
loop
select
accept Enter (Text : Wide_Wide_String; Continues_Word : Boolean) do
IO.Put (if Continues_Word then "" else " ");
IO.Put (Text);
end Enter;
or
accept Erase (Amount : Positive) do
for I in 1 .. Amount loop
IO.Put ("^H");
end loop;
end Erase;
or
accept Shut_Down;
exit;
end select;
end loop;
end Output;
end Output_Backend;
|
with Ada.Text_Io;
procedure CompileTimeCalculation is
Factorial : constant Integer := 10*9*8*7*6*5*4*3*2*1;
begin
Ada.Text_Io.Put(Integer'Image(Factorial));
end CompileTimeCalculation;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- G N A T . D I R E C T O R Y _ O P E R A T I O N S . I T E R A T I O N --
-- --
-- S p e c --
-- --
-- Copyright (C) 2001-2019, AdaCore --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- Iterators among files
package GNAT.Directory_Operations.Iteration is
generic
with procedure Action
(Item : String;
Index : Positive;
Quit : in out Boolean);
procedure Find
(Root_Directory : Dir_Name_Str;
File_Pattern : String);
-- Recursively searches the directory structure rooted at Root_Directory.
-- This provides functionality similar to the UNIX 'find' command.
-- Action will be called for every item matching the regular expression
-- File_Pattern (see GNAT.Regexp). Item is the full pathname to the file
-- starting with Root_Directory that has been matched. Index is set to one
-- for the first call and is incremented by one at each call. The iterator
-- will pass in the value False on each call to Action. The iterator will
-- terminate after passing the last matched path to Action or after
-- returning from a call to Action which sets Quit to True.
-- Raises GNAT.Regexp.Error_In_Regexp if File_Pattern is ill formed.
generic
with procedure Action
(Item : String;
Index : Positive;
Quit : in out Boolean);
procedure Wildcard_Iterator (Path : Path_Name);
-- Calls Action for each path matching Path. Path can include wildcards '*'
-- and '?' and [...]. The rules are:
--
-- * can be replaced by any sequence of characters
-- ? can be replaced by a single character
-- [a-z] match one character in the range 'a' through 'z'
-- [abc] match either character 'a', 'b' or 'c'
--
-- Item is the filename that has been matched. Index is set to one for the
-- first call and is incremented by one at each call. The iterator's
-- termination can be controlled by setting Quit to True. It is by default
-- set to False.
--
-- For example, if we have the following directory structure:
-- /boo/
-- foo.ads
-- /sed/
-- foo.ads
-- file/
-- foo.ads
-- /sid/
-- foo.ads
-- file/
-- foo.ads
-- /life/
--
-- A call with expression "/s*/file/*" will call Action for the following
-- items:
-- /sed/file/foo.ads
-- /sid/file/foo.ads
end GNAT.Directory_Operations.Iteration;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- S Y S T E M . P O O L _ S I Z E --
-- --
-- B o d y --
-- --
-- Copyright (C) 1992-2019, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with System.Soft_Links;
with Ada.Unchecked_Conversion;
package body System.Pool_Size is
package SSE renames System.Storage_Elements;
use type SSE.Storage_Offset;
-- Even though these storage pools are typically only used by a single
-- task, if multiple tasks are declared at the same or a more nested scope
-- as the storage pool, there still may be concurrent access. The current
-- implementation of Stack_Bounded_Pool always uses a global lock for
-- protecting access. This should eventually be replaced by an atomic
-- linked list implementation for efficiency reasons.
package SSL renames System.Soft_Links;
type Storage_Count_Access is access SSE.Storage_Count;
function To_Storage_Count_Access is
new Ada.Unchecked_Conversion (Address, Storage_Count_Access);
SC_Size : constant := SSE.Storage_Count'Object_Size / System.Storage_Unit;
package Variable_Size_Management is
-- Embedded pool that manages allocation of variable-size data
-- This pool is used as soon as the Elmt_Size of the pool object is 0
-- Allocation is done on the first chunk long enough for the request.
-- Deallocation just puts the freed chunk at the beginning of the list.
procedure Initialize (Pool : in out Stack_Bounded_Pool);
procedure Allocate
(Pool : in out Stack_Bounded_Pool;
Address : out System.Address;
Storage_Size : SSE.Storage_Count;
Alignment : SSE.Storage_Count);
procedure Deallocate
(Pool : in out Stack_Bounded_Pool;
Address : System.Address;
Storage_Size : SSE.Storage_Count;
Alignment : SSE.Storage_Count);
end Variable_Size_Management;
package Vsize renames Variable_Size_Management;
--------------
-- Allocate --
--------------
procedure Allocate
(Pool : in out Stack_Bounded_Pool;
Address : out System.Address;
Storage_Size : SSE.Storage_Count;
Alignment : SSE.Storage_Count)
is
begin
SSL.Lock_Task.all;
if Pool.Elmt_Size = 0 then
Vsize.Allocate (Pool, Address, Storage_Size, Alignment);
elsif Pool.First_Free /= 0 then
Address := Pool.The_Pool (Pool.First_Free)'Address;
Pool.First_Free := To_Storage_Count_Access (Address).all;
elsif
Pool.First_Empty <= (Pool.Pool_Size - Pool.Aligned_Elmt_Size + 1)
then
Address := Pool.The_Pool (Pool.First_Empty)'Address;
Pool.First_Empty := Pool.First_Empty + Pool.Aligned_Elmt_Size;
else
raise Storage_Error;
end if;
SSL.Unlock_Task.all;
exception
when others =>
SSL.Unlock_Task.all;
raise;
end Allocate;
----------------
-- Deallocate --
----------------
procedure Deallocate
(Pool : in out Stack_Bounded_Pool;
Address : System.Address;
Storage_Size : SSE.Storage_Count;
Alignment : SSE.Storage_Count)
is
begin
SSL.Lock_Task.all;
if Pool.Elmt_Size = 0 then
Vsize.Deallocate (Pool, Address, Storage_Size, Alignment);
else
To_Storage_Count_Access (Address).all := Pool.First_Free;
Pool.First_Free := Address - Pool.The_Pool'Address + 1;
end if;
SSL.Unlock_Task.all;
exception
when others =>
SSL.Unlock_Task.all;
raise;
end Deallocate;
----------------
-- Initialize --
----------------
procedure Initialize (Pool : in out Stack_Bounded_Pool) is
-- Define the appropriate alignment for allocations. This is the
-- maximum of the requested alignment, and the alignment required
-- for Storage_Count values. The latter test is to ensure that we
-- can properly reference the linked list pointers for free lists.
Align : constant SSE.Storage_Count :=
SSE.Storage_Count'Max
(SSE.Storage_Count'Alignment, Pool.Alignment);
begin
if Pool.Elmt_Size = 0 then
Vsize.Initialize (Pool);
else
Pool.First_Free := 0;
Pool.First_Empty := 1;
-- Compute the size to allocate given the size of the element and
-- the possible alignment requirement as defined above.
Pool.Aligned_Elmt_Size :=
SSE.Storage_Count'Max (SC_Size,
((Pool.Elmt_Size + Align - 1) / Align) * Align);
end if;
end Initialize;
------------------
-- Storage_Size --
------------------
function Storage_Size
(Pool : Stack_Bounded_Pool) return SSE.Storage_Count
is
begin
return Pool.Pool_Size;
end Storage_Size;
------------------------------
-- Variable_Size_Management --
------------------------------
package body Variable_Size_Management is
Minimum_Size : constant := 2 * SC_Size;
procedure Set_Size
(Pool : Stack_Bounded_Pool;
Chunk, Size : SSE.Storage_Count);
-- Update the field 'size' of a chunk of available storage
procedure Set_Next
(Pool : Stack_Bounded_Pool;
Chunk, Next : SSE.Storage_Count);
-- Update the field 'next' of a chunk of available storage
function Size
(Pool : Stack_Bounded_Pool;
Chunk : SSE.Storage_Count) return SSE.Storage_Count;
-- Fetch the field 'size' of a chunk of available storage
function Next
(Pool : Stack_Bounded_Pool;
Chunk : SSE.Storage_Count) return SSE.Storage_Count;
-- Fetch the field 'next' of a chunk of available storage
function Chunk_Of
(Pool : Stack_Bounded_Pool;
Addr : System.Address) return SSE.Storage_Count;
-- Give the chunk number in the pool from its Address
--------------
-- Allocate --
--------------
procedure Allocate
(Pool : in out Stack_Bounded_Pool;
Address : out System.Address;
Storage_Size : SSE.Storage_Count;
Alignment : SSE.Storage_Count)
is
Chunk : SSE.Storage_Count;
New_Chunk : SSE.Storage_Count;
Prev_Chunk : SSE.Storage_Count;
Our_Align : constant SSE.Storage_Count :=
SSE.Storage_Count'Max (SSE.Storage_Count'Alignment,
Alignment);
Align_Size : constant SSE.Storage_Count :=
SSE.Storage_Count'Max (
Minimum_Size,
((Storage_Size + Our_Align - 1) / Our_Align) *
Our_Align);
begin
-- Look for the first big enough chunk
Prev_Chunk := Pool.First_Free;
Chunk := Next (Pool, Prev_Chunk);
while Chunk /= 0 and then Size (Pool, Chunk) < Align_Size loop
Prev_Chunk := Chunk;
Chunk := Next (Pool, Chunk);
end loop;
-- Raise storage_error if no big enough chunk available
if Chunk = 0 then
raise Storage_Error;
end if;
-- When the chunk is bigger than what is needed, take appropriate
-- amount and build a new shrinked chunk with the remainder.
if Size (Pool, Chunk) - Align_Size > Minimum_Size then
New_Chunk := Chunk + Align_Size;
Set_Size (Pool, New_Chunk, Size (Pool, Chunk) - Align_Size);
Set_Next (Pool, New_Chunk, Next (Pool, Chunk));
Set_Next (Pool, Prev_Chunk, New_Chunk);
-- If the chunk is the right size, just delete it from the chain
else
Set_Next (Pool, Prev_Chunk, Next (Pool, Chunk));
end if;
Address := Pool.The_Pool (Chunk)'Address;
end Allocate;
--------------
-- Chunk_Of --
--------------
function Chunk_Of
(Pool : Stack_Bounded_Pool;
Addr : System.Address) return SSE.Storage_Count
is
begin
return 1 + abs (Addr - Pool.The_Pool (1)'Address);
end Chunk_Of;
----------------
-- Deallocate --
----------------
procedure Deallocate
(Pool : in out Stack_Bounded_Pool;
Address : System.Address;
Storage_Size : SSE.Storage_Count;
Alignment : SSE.Storage_Count)
is
pragma Warnings (Off, Pool);
Align_Size : constant SSE.Storage_Count :=
((Storage_Size + Alignment - 1) / Alignment) *
Alignment;
Chunk : constant SSE.Storage_Count := Chunk_Of (Pool, Address);
begin
-- Attach the freed chunk to the chain
Set_Size (Pool, Chunk,
SSE.Storage_Count'Max (Align_Size, Minimum_Size));
Set_Next (Pool, Chunk, Next (Pool, Pool.First_Free));
Set_Next (Pool, Pool.First_Free, Chunk);
end Deallocate;
----------------
-- Initialize --
----------------
procedure Initialize (Pool : in out Stack_Bounded_Pool) is
begin
Pool.First_Free := 1;
if Pool.Pool_Size > Minimum_Size then
Set_Next (Pool, Pool.First_Free, Pool.First_Free + Minimum_Size);
Set_Size (Pool, Pool.First_Free, 0);
Set_Size (Pool, Pool.First_Free + Minimum_Size,
Pool.Pool_Size - Minimum_Size);
Set_Next (Pool, Pool.First_Free + Minimum_Size, 0);
end if;
end Initialize;
----------
-- Next --
----------
function Next
(Pool : Stack_Bounded_Pool;
Chunk : SSE.Storage_Count) return SSE.Storage_Count
is
begin
pragma Warnings (Off);
-- Kill alignment warnings, we are careful to make sure
-- that the alignment is correct.
return To_Storage_Count_Access
(Pool.The_Pool (Chunk + SC_Size)'Address).all;
pragma Warnings (On);
end Next;
--------------
-- Set_Next --
--------------
procedure Set_Next
(Pool : Stack_Bounded_Pool;
Chunk, Next : SSE.Storage_Count)
is
begin
pragma Warnings (Off);
-- Kill alignment warnings, we are careful to make sure
-- that the alignment is correct.
To_Storage_Count_Access
(Pool.The_Pool (Chunk + SC_Size)'Address).all := Next;
pragma Warnings (On);
end Set_Next;
--------------
-- Set_Size --
--------------
procedure Set_Size
(Pool : Stack_Bounded_Pool;
Chunk, Size : SSE.Storage_Count)
is
begin
pragma Warnings (Off);
-- Kill alignment warnings, we are careful to make sure
-- that the alignment is correct.
To_Storage_Count_Access
(Pool.The_Pool (Chunk)'Address).all := Size;
pragma Warnings (On);
end Set_Size;
----------
-- Size --
----------
function Size
(Pool : Stack_Bounded_Pool;
Chunk : SSE.Storage_Count) return SSE.Storage_Count
is
begin
pragma Warnings (Off);
-- Kill alignment warnings, we are careful to make sure
-- that the alignment is correct.
return To_Storage_Count_Access (Pool.The_Pool (Chunk)'Address).all;
pragma Warnings (On);
end Size;
end Variable_Size_Management;
end System.Pool_Size;
|
pragma Warnings (Off);
pragma Style_Checks (Off);
-------------------------------------------------------------------------
-- GL.Geometry - GL geometry primitives
--
-- Copyright (c) Rod Kay 2007
-- AUSTRALIA
-- Permission granted to use this software, without any warranty,
-- for any purpose, provided this copyright note remains attached
-- and unmodified if sources are distributed further.
-------------------------------------------------------------------------
-- with Ada.Numerics.Generic_Elementary_functions;
-- with Ada.Text_IO; use Ada.Text_IO;
package body GL.Geometry.VBO is
use GL.Buffer;
function primitive_Id (Self : in vbo_Geometry) return GL.ObjectTypeEnm
is
begin
return self.primitive_Id;
end;
function vertex_Count (Self : in vbo_Geometry) return GL.geometry.vertex_Id
is
begin
return vertex_Id (self.vertex_Count);
end;
function indices_Count (Self : in vbo_Geometry) return GL.positive_uInt
is
begin
return GL.positive_uInt (self.indices_Count);
end;
function Bounds (Self : in vbo_Geometry) return GL.geometry.Bounds_record
is
begin
return self.Bounds;
end;
procedure draw (Self : in vbo_Geometry)
is
begin
self.Vertices.enable;
GL.vertexPointer (3, GL_DOUBLE, 0, null);
self.Indices.enable;
GL.Enable_Client_State (gl.VERTEX_ARRAY);
GL.drawElements (self.primitive_Id, self.indices_Count, GL.UNSIGNED_INT, null);
GL.Disable_Client_State (gl.VERTEX_ARRAY);
end;
-- Modified by zheng, 2011.1.20
function Vertices (Self : in vbo_Geometry) return GL.geometry.GL_Vertex_array
is
self_buf : aliased vbo_Geometry :=self;
begin
return self_buf.Vertices.get;
end;
-- Modified by zheng, 2011.1.20
function Indices (Self : in vbo_Geometry) return GL.geometry.vertex_Id_array
is
self_buf : aliased vbo_Geometry :=self;
gl_Indices : vertex_Id_array := self_buf.Indices.get;
begin
increment (gl_Indices);
return gl_Indices;
end;
procedure destroy (Self : in out vbo_Geometry)
is
begin
destroy (self.Vertices);
destroy (self.Indices);
end;
end GL.Geometry.VBO;
|
------------------------------------------------------------------------------
-- G N A T C O L L --
-- --
-- Copyright (C) 2009-2018, AdaCore --
-- --
-- This library is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 3, or (at your option) any later --
-- version. This library is distributed in the hope that it will be useful, --
-- but WITHOUT ANY WARRANTY; without even the implied warranty of --
-- 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/>. --
-- --
------------------------------------------------------------------------------
-- cspell:words symlink symlinks GNATCOLL Mmap Unref
with GNAT.Directory_Operations;
with GNAT.Strings; use GNAT.Strings;
with GNATCOLL.IO.Native;
with GNATCOLL.IO.Remote.Unix;
with GNATCOLL.IO.Remote.Windows;
with GNATCOLL.Mmap;
with GNATCOLL.Path; use GNATCOLL.Path;
with GNATCOLL.Remote; use GNATCOLL.Remote;
with GNATCOLL.Remote.Db; use GNATCOLL.Remote.Db;
package body GNATCOLL.IO.Remote is
procedure Internal_Initialize
(File : not null access Remote_File_Record'Class;
Host : String;
Path : FS_String);
-- Initialize internal fields according to the file's host
-------------------------
-- Internal_Initialize --
-------------------------
procedure Internal_Initialize
(File : not null access Remote_File_Record'Class;
Host : String;
Path : FS_String)
is
Server : constant Server_Access := Get_Server (Host);
Last : Natural := Path'Last;
begin
-- Regexps might return file strings with a trailing CR or LF. Let's
-- remove those before creating the File record.
while Path (Last) = ASCII.CR or Path (Last) = ASCII.LF loop
Last := Last - 1;
end loop;
File.Server := Server;
if File.Tmp_Norm then
File.Full := new FS_String'
(GNATCOLL.Path.Normalize
(Server.Shell_FS,
From_Unix (Server.Shell_FS, Path (Path'First .. Last))));
else
File.Full := new FS_String'
(From_Unix (Server.Shell_FS, Path (Path'First .. Last)));
end if;
File.Normalized_And_Resolved := null;
end Internal_Initialize;
------------------------
-- Ensure_Initialized --
------------------------
procedure Ensure_Initialized
(File : not null access Remote_File_Record'Class)
is
begin
if File.Server /= null then
return;
elsif not Is_Configured (File.Tmp_Host.all) then
raise Remote_Config_Error with
"File needs server " & File.Tmp_Host.all &
" which is not configured";
end if;
Internal_Initialize (File, File.Tmp_Host.all, File.Tmp_Path.all);
Free (File.Tmp_Host);
Free (File.Tmp_Path);
end Ensure_Initialized;
------------
-- Create --
------------
function Create
(Host : String;
Path : FS_String;
Normalize : Boolean) return File_Access
is
Ret : Remote_File_Access;
begin
Ret := new Remote_File_Record'
(Ref_Count => 1,
Tmp_Host => null,
Tmp_Path => null,
Tmp_Norm => Normalize,
Tmp_Name => (others => ' '),
Server => null,
Full => null,
Normalized => null,
Normalized_And_Resolved => null,
Kind => Unknown);
if not Is_Configured (Host) then
-- Delayed initialization
Ret.Tmp_Host := new String'(Host);
Ret.Tmp_Path := new FS_String'(Path);
else
Internal_Initialize (Ret, Host, Path);
end if;
return File_Access (Ret);
end Create;
-----------------
-- Current_Dir --
-----------------
function Current_Dir (Host : String) return File_Access is
Server : Server_Access;
begin
if not Is_Configured (Host) then
raise Remote_Config_Error with
"Invalid FS for host " & Host;
else
Server := Get_Server (Host);
end if;
case Server.Shell_FS is
when FS_Unix | FS_Unix_Case_Insensitive =>
return Create
(Host,
GNATCOLL.IO.Remote.Unix.Current_Dir (Server),
False);
when FS_Windows =>
return Create
(Host,
GNATCOLL.IO.Remote.Windows.Current_Dir (Server),
False);
when FS_Unknown =>
raise Remote_Config_Error with
"Invalid FS for host " & Host;
end case;
end Current_Dir;
--------------
-- Home_Dir --
--------------
function Home_Dir (Host : String) return File_Access is
Server : Server_Access;
begin
if not Is_Configured (Host) then
raise Remote_Config_Error with
"Invalid FS for host " & Host;
else
Server := Get_Server (Host);
end if;
case Server.Shell_FS is
when FS_Unix | FS_Unix_Case_Insensitive =>
return Create
(Host,
GNATCOLL.IO.Remote.Unix.Home_Dir (Server),
False);
when FS_Windows =>
return Create
(Host,
GNATCOLL.IO.Remote.Windows.Home_Dir (Server),
False);
when FS_Unknown =>
raise Remote_Config_Error with
"Invalid FS for host " & Host;
end case;
end Home_Dir;
-----------------------
-- Get_Tmp_Directory --
-----------------------
function Get_Tmp_Directory (Host : String) return File_Access is
Server : Server_Access;
begin
if not Is_Configured (Host) then
raise Remote_Config_Error with
"Invalid FS for host " & Host;
else
Server := Get_Server (Host);
end if;
case Server.Shell_FS is
when FS_Unix | FS_Unix_Case_Insensitive =>
return Create
(Host, GNATCOLL.IO.Remote.Unix.Tmp_Dir (Server), False);
when FS_Windows =>
return Create
(Host, GNATCOLL.IO.Remote.Windows.Tmp_Dir (Server), False);
when FS_Unknown =>
raise Remote_Config_Error with
"Invalid FS for host " & Host;
end case;
end Get_Tmp_Directory;
--------------------
-- Locate_On_Path --
--------------------
function Locate_On_Path (Host : String; Base : FS_String) return File_Access
is
Server : Server_Access;
begin
if not Is_Configured (Host) then
raise Remote_Config_Error with
"Invalid FS for host " & Host;
else
Server := Get_Server (Host);
end if;
if GNATCOLL.Path.Is_Absolute_Path (Server.Shell_FS, Base) then
return Create (Host, Base, False);
end if;
case Server.Shell_FS is
when FS_Unix | FS_Unix_Case_Insensitive =>
declare
Ret : constant FS_String :=
GNATCOLL.IO.Remote.Unix.Locate_On_Path (Server, Base);
begin
if Ret = "" then
return null;
else
return Create (Host, Ret, False);
end if;
end;
when FS_Windows =>
declare
Ret : constant FS_String :=
GNATCOLL.IO.Remote.Windows.Locate_On_Path
(Server, Base);
begin
if Ret = "" then
return null;
else
return Create (Host, Ret, False);
end if;
end;
when FS_Unknown =>
raise Remote_Config_Error with
"Invalid FS for host " & Host;
end case;
end Locate_On_Path;
------------------------
-- Get_Logical_Drives --
------------------------
function Get_Logical_Drives (Host : String) return File_Array is
Server : Server_Access;
List : GNAT.Strings.String_List_Access;
begin
if not Is_Configured (Host) then
raise Remote_Config_Error with
"Invalid FS for host " & Host;
else
Server := Get_Server (Host);
end if;
case Server.Shell_FS is
when FS_Unix | FS_Unix_Case_Insensitive =>
List := GNATCOLL.IO.Remote.Unix.Get_Logical_Drives (Server);
when FS_Windows =>
List := GNATCOLL.IO.Remote.Windows.Get_Logical_Drives (Server);
when FS_Unknown =>
raise Remote_Config_Error with
"Invalid FS for host " & Host;
end case;
if List = null then
return (1 .. 0 => <>);
end if;
declare
Ret : File_Array (1 .. List'Length);
begin
for J in Ret'Range loop
Ret (J) :=
Create (Host, FS_String (List (List'First + J - Ret'First).all),
False);
end loop;
GNAT.Strings.Free (List);
return Ret;
end;
end Get_Logical_Drives;
--------------
-- Get_Host --
--------------
function Get_Host
(File : not null access Remote_File_Record) return String
is
begin
if File.Server = null then
if not Is_Configured (File.Tmp_Host.all) then
return File.Tmp_Host.all;
else
Internal_Initialize (File, File.Tmp_Host.all, File.Tmp_Path.all);
Free (File.Tmp_Host);
Free (File.Tmp_Path);
return File.Server.Nickname;
end if;
else
return File.Server.Nickname;
end if;
end Get_Host;
------------------------
-- Dispatching_Create --
------------------------
overriding function Dispatching_Create
(Ref : not null access Remote_File_Record;
Full_Path : FS_String) return File_Access
is
begin
return Create (Ref.Get_Host, Full_Path, False);
end Dispatching_Create;
-------------
-- To_UTF8 --
-------------
overriding function To_UTF8
(Ref : not null access Remote_File_Record;
Path : FS_String) return String
is
pragma Unreferenced (Ref);
begin
return Codec.To_UTF8 (Path);
end To_UTF8;
---------------
-- From_UTF8 --
---------------
overriding function From_UTF8
(Ref : not null access Remote_File_Record;
Path : String) return FS_String
is
pragma Unreferenced (Ref);
begin
return Codec.From_UTF8 (Path);
end From_UTF8;
--------------
-- Is_Local --
--------------
overriding function Is_Local (File : Remote_File_Record) return Boolean is
pragma Unreferenced (File);
begin
return False;
end Is_Local;
------------
-- Get_FS --
------------
overriding function Get_FS
(File : not null access Remote_File_Record) return FS_Type
is
begin
Ensure_Initialized (File);
return File.Server.Shell_FS;
end Get_FS;
----------------------
-- Resolve_Symlinks --
----------------------
overriding procedure Resolve_Symlinks
(File : not null access Remote_File_Record)
is
begin
Ensure_Initialized (File);
-- ??? Should we do something more here (e.g. try to actually resolve ?)
if File.Normalized_And_Resolved = null then
if File.Normalized = null then
File.Normalized := new FS_String'
(GNATCOLL.Path.Normalize (Get_FS (File), File.Full.all));
end if;
File.Normalized_And_Resolved := File.Normalized;
end if;
end Resolve_Symlinks;
---------------------
-- Is_Regular_File --
---------------------
overriding function Is_Regular_File
(File : not null access Remote_File_Record) return Boolean
is
begin
Ensure_Initialized (File);
case File.Server.Shell_FS is
when FS_Unix | FS_Unix_Case_Insensitive =>
return GNATCOLL.IO.Remote.Unix.Is_Regular_File
(File.Server, File.Full.all);
when FS_Windows =>
return GNATCOLL.IO.Remote.Windows.Is_Regular_File
(File.Server, File.Full.all);
when FS_Unknown =>
raise Remote_Config_Error with
"Invalid FS for host " & File.Get_Host;
end case;
end Is_Regular_File;
----------
-- Size --
----------
overriding function Size
(File : not null access Remote_File_Record) return Long_Integer
is
begin
Ensure_Initialized (File);
case File.Server.Shell_FS is
when FS_Unix | FS_Unix_Case_Insensitive =>
return GNATCOLL.IO.Remote.Unix.Size
(File.Server, File.Full.all);
when FS_Windows =>
return GNATCOLL.IO.Remote.Windows.Size
(File.Server, File.Full.all);
when FS_Unknown =>
raise Remote_Config_Error with
"Invalid FS for host " & File.Get_Host;
end case;
end Size;
------------------
-- Is_Directory --
------------------
overriding function Is_Directory
(File : not null access Remote_File_Record) return Boolean
is
begin
Ensure_Initialized (File);
case File.Server.Shell_FS is
when FS_Unix | FS_Unix_Case_Insensitive =>
return GNATCOLL.IO.Remote.Unix.Is_Directory
(File.Server, File.Full.all);
when FS_Windows =>
return GNATCOLL.IO.Remote.Windows.Is_Directory
(File.Server, File.Full.all);
when FS_Unknown =>
raise Remote_Config_Error with
"Invalid FS for host " & File.Get_Host;
end case;
end Is_Directory;
----------------------
-- Is_Symbolic_Link --
----------------------
overriding function Is_Symbolic_Link
(File : not null access Remote_File_Record) return Boolean
is
begin
Ensure_Initialized (File);
case File.Server.Shell_FS is
when FS_Unix | FS_Unix_Case_Insensitive =>
return GNATCOLL.IO.Remote.Unix.Is_Symbolic_Link
(File.Server, File.Full.all);
when FS_Windows =>
return GNATCOLL.IO.Remote.Windows.Is_Symbolic_Link
(File.Server, File.Full.all);
when FS_Unknown =>
raise Remote_Config_Error with
"Invalid FS for host " & File.Get_Host;
end case;
end Is_Symbolic_Link;
---------------------
-- File_Time_Stamp --
---------------------
overriding function File_Time_Stamp
(File : not null access Remote_File_Record) return Ada.Calendar.Time
is
begin
Ensure_Initialized (File);
case File.Server.Shell_FS is
when FS_Unix | FS_Unix_Case_Insensitive =>
return GNATCOLL.IO.Remote.Unix.File_Time_Stamp
(File.Server, File.Full.all);
when FS_Windows =>
return GNATCOLL.IO.Remote.Windows.File_Time_Stamp
(File.Server, File.Full.all);
when FS_Unknown =>
raise Remote_Config_Error with
"Invalid FS for host " & File.Get_Host;
end case;
end File_Time_Stamp;
-----------------
-- Is_Readable --
-----------------
overriding function Is_Readable
(File : not null access Remote_File_Record) return Boolean is
begin
Ensure_Initialized (File);
case File.Server.Shell_FS is
when FS_Unix | FS_Unix_Case_Insensitive =>
return GNATCOLL.IO.Remote.Unix.Is_Readable
(File.Server, File.Full.all);
when FS_Windows =>
return GNATCOLL.IO.Remote.Windows.Is_Readable
(File.Server, File.Full.all);
when FS_Unknown =>
raise Remote_Config_Error with
"Invalid FS for host " & File.Get_Host;
end case;
end Is_Readable;
-----------------
-- Is_Writable --
-----------------
overriding function Is_Writable
(File : not null access Remote_File_Record) return Boolean is
begin
Ensure_Initialized (File);
case File.Server.Shell_FS is
when FS_Unix | FS_Unix_Case_Insensitive =>
return GNATCOLL.IO.Remote.Unix.Is_Writable
(File.Server, File.Full.all);
when FS_Windows =>
return GNATCOLL.IO.Remote.Windows.Is_Writable
(File.Server, File.Full.all);
when FS_Unknown =>
raise Remote_Config_Error with
"Invalid FS for host " & File.Get_Host;
end case;
end Is_Writable;
------------------
-- Set_Writable --
------------------
overriding procedure Set_Writable
(File : not null access Remote_File_Record;
State : Boolean)
is
begin
Ensure_Initialized (File);
case File.Server.Shell_FS is
when FS_Unix | FS_Unix_Case_Insensitive =>
GNATCOLL.IO.Remote.Unix.Set_Writable
(File.Server, File.Full.all,
State);
when FS_Windows =>
GNATCOLL.IO.Remote.Windows.Set_Writable
(File.Server, File.Full.all,
State);
when FS_Unknown =>
raise Remote_Config_Error with
"Invalid FS for host " & File.Get_Host;
end case;
end Set_Writable;
------------------
-- Set_Readable --
------------------
overriding procedure Set_Readable
(File : not null access Remote_File_Record;
State : Boolean)
is
begin
Ensure_Initialized (File);
case File.Server.Shell_FS is
when FS_Unix | FS_Unix_Case_Insensitive =>
GNATCOLL.IO.Remote.Unix.Set_Readable
(File.Server, File.Full.all,
State);
when FS_Windows =>
GNATCOLL.IO.Remote.Windows.Set_Readable
(File.Server, File.Full.all,
State);
when FS_Unknown =>
raise Remote_Config_Error with
"Invalid FS for host " & File.Get_Host;
end case;
end Set_Readable;
------------
-- Rename --
------------
overriding procedure Rename
(From : not null access Remote_File_Record;
Dest : not null access Remote_File_Record;
Success : out Boolean)
is
begin
Ensure_Initialized (From);
Ensure_Initialized (Dest);
if From.Get_Host /= Dest.Get_Host then
raise Remote_Config_Error with
"cannot rename a file to another host";
end if;
case From.Server.Shell_FS is
when FS_Unix | FS_Unix_Case_Insensitive =>
GNATCOLL.IO.Remote.Unix.Rename
(From.Server, From.Full.all, Dest.Full.all, Success);
when FS_Windows =>
GNATCOLL.IO.Remote.Windows.Rename
(From.Server, From.Full.all, Dest.Full.all, Success);
when FS_Unknown =>
raise Remote_Config_Error with
"Invalid FS for host " & From.Get_Host;
end case;
end Rename;
----------
-- Copy --
----------
overriding procedure Copy
(From : not null access Remote_File_Record;
Dest : FS_String;
Success : out Boolean)
is
begin
Ensure_Initialized (From);
case From.Server.Shell_FS is
when FS_Unix | FS_Unix_Case_Insensitive =>
GNATCOLL.IO.Remote.Unix.Copy
(From.Server, From.Full.all, Dest, Success);
when FS_Windows =>
GNATCOLL.IO.Remote.Windows.Copy
(From.Server, From.Full.all, Dest, Success);
when FS_Unknown =>
raise Remote_Config_Error with
"Invalid FS for host " & From.Get_Host;
end case;
end Copy;
------------
-- Delete --
------------
overriding procedure Delete
(File : not null access Remote_File_Record;
Success : out Boolean)
is
begin
Ensure_Initialized (File);
case File.Server.Shell_FS is
when FS_Unix | FS_Unix_Case_Insensitive =>
GNATCOLL.IO.Remote.Unix.Delete
(File.Server, File.Full.all,
Success);
when FS_Windows =>
GNATCOLL.IO.Remote.Windows.Delete
(File.Server, File.Full.all,
Success);
when FS_Unknown =>
raise Remote_Config_Error with
"Invalid FS for host " & File.Get_Host;
end case;
end Delete;
---------------------
-- Read_Whole_File --
---------------------
overriding function Read_Whole_File
(File : not null access Remote_File_Record)
return GNAT.Strings.String_Access
is
begin
Ensure_Initialized (File);
case File.Server.Shell_FS is
when FS_Unix | FS_Unix_Case_Insensitive =>
return GNATCOLL.IO.Remote.Unix.Read_Whole_File
(File.Server, File.Full.all);
when FS_Windows =>
return GNATCOLL.IO.Remote.Windows.Read_Whole_File
(File.Server, File.Full.all);
when FS_Unknown =>
raise Remote_Config_Error with
"Invalid FS for host " & File.Get_Host;
end case;
end Read_Whole_File;
---------------------
-- Read_Whole_File --
---------------------
overriding function Read_Whole_File
(File : not null access Remote_File_Record)
return GNATCOLL.Strings.XString
is
begin
Ensure_Initialized (File);
case File.Server.Shell_FS is
when FS_Unix | FS_Unix_Case_Insensitive =>
return GNATCOLL.IO.Remote.Unix.Read_Whole_File
(File.Server, File.Full.all);
when FS_Windows =>
return GNATCOLL.IO.Remote.Windows.Read_Whole_File
(File.Server, File.Full.all);
when FS_Unknown =>
raise Remote_Config_Error with
"Invalid FS for host " & File.Get_Host;
end case;
end Read_Whole_File;
----------------
-- Open_Write --
----------------
overriding procedure Open_Write
(File : not null access Remote_File_Record;
Append : Boolean := False;
FD : out GNAT.OS_Lib.File_Descriptor;
Error : out Ada.Strings.Unbounded.Unbounded_String)
is
pragma Unreferenced (Error);
-- Error diagnostics is not implemented for remote files.
Tmp_Dir : File_Access :=
GNATCOLL.IO.Native.Get_Tmp_Directory;
Cur_Dir : File_Access :=
GNATCOLL.IO.Native.Current_Dir;
Tmp : constant FS_String :=
GNATCOLL.Path.Ensure_Directory
(Tmp_Dir.Get_FS, Tmp_Dir.Full.all);
Cur : constant FS_String :=
GNATCOLL.Path.Ensure_Directory
(Cur_Dir.Get_FS, Cur_Dir.Full.all);
Content : GNAT.Strings.String_Access;
Written : Integer;
pragma Unreferenced (Written);
begin
Ensure_Initialized (File);
Unref (Tmp_Dir);
Unref (Cur_Dir);
GNAT.Directory_Operations.Change_Dir (String (Tmp));
GNAT.OS_Lib.Create_Temp_File (FD, File.Tmp_Name);
GNAT.Directory_Operations.Change_Dir (String (Cur));
if Append then
case File.Server.Shell_FS is
when FS_Unix | FS_Unix_Case_Insensitive =>
Content := GNATCOLL.IO.Remote.Unix.Read_Whole_File
(File.Server, File.Full.all);
when FS_Windows =>
Content := GNATCOLL.IO.Remote.Windows.Read_Whole_File
(File.Server, File.Full.all);
when FS_Unknown =>
raise Remote_Config_Error with
"Invalid FS for host " & File.Get_Host;
end case;
Written :=
GNAT.OS_Lib.Write (FD, Content.all'Address, Content'Length);
GNAT.Strings.Free (Content);
end if;
end Open_Write;
-----------
-- Close --
-----------
overriding procedure Close
(File : not null access Remote_File_Record;
FD : GNAT.OS_Lib.File_Descriptor;
Success : out Boolean)
is
Content : GNAT.Strings.String_Access;
Tmp_Dir : File_Access :=
GNATCOLL.IO.Native.Get_Tmp_Directory;
Tmp : constant FS_String :=
GNATCOLL.Path.Ensure_Directory
(Tmp_Dir.Get_FS, Tmp_Dir.Full.all);
Dead : Boolean;
pragma Unreferenced (Dead);
begin
Unref (Tmp_Dir);
Ensure_Initialized (File);
GNAT.OS_Lib.Close (FD);
Content := GNATCOLL.Mmap.Read_Whole_File
(String (Tmp) & File.Tmp_Name, Empty_If_Not_Found => True);
case File.Server.Shell_FS is
when FS_Unix | FS_Unix_Case_Insensitive =>
Success := GNATCOLL.IO.Remote.Unix.Write_File
(File.Server, File.Full.all, Content.all);
when FS_Windows =>
Success := GNATCOLL.IO.Remote.Windows.Write_File
(File.Server, File.Full.all, Content.all);
when FS_Unknown =>
raise Remote_Config_Error with
"Invalid FS for host " & File.Get_Host;
end case;
GNAT.OS_Lib.Delete_File (String (Tmp) & File.Tmp_Name, Dead);
end Close;
----------------
-- Change_Dir --
----------------
overriding function Change_Dir
(Dir : not null access Remote_File_Record) return Boolean
is
begin
Ensure_Initialized (Dir);
case Dir.Server.Shell_FS is
when FS_Unix | FS_Unix_Case_Insensitive =>
return GNATCOLL.IO.Remote.Unix.Change_Dir
(Dir.Server, Dir.Full.all);
when FS_Windows =>
return GNATCOLL.IO.Remote.Windows.Change_Dir
(Dir.Server, Dir.Full.all);
when FS_Unknown =>
raise Remote_Config_Error with
"Invalid FS for host " & Dir.Get_Host;
end case;
end Change_Dir;
--------------
-- Read_Dir --
--------------
overriding function Read_Dir
(Dir : not null access Remote_File_Record;
Dirs_Only : Boolean := False;
Files_Only : Boolean := False) return GNAT.Strings.String_List
is
begin
Ensure_Initialized (Dir);
case Dir.Server.Shell_FS is
when FS_Unix | FS_Unix_Case_Insensitive =>
return GNATCOLL.IO.Remote.Unix.Read_Dir
(Dir.Server, Dir.Full.all,
Dirs_Only, Files_Only);
when FS_Windows =>
return GNATCOLL.IO.Remote.Windows.Read_Dir
(Dir.Server, Dir.Full.all,
Dirs_Only, Files_Only);
when FS_Unknown =>
raise Remote_Config_Error with
"Invalid FS for host " & Dir.Get_Host;
end case;
end Read_Dir;
--------------
-- Make_Dir --
--------------
overriding function Make_Dir
(Dir : not null access Remote_File_Record;
Recursive : Boolean) return Boolean
is
begin
Ensure_Initialized (Dir);
case Dir.Server.Shell_FS is
when FS_Unix | FS_Unix_Case_Insensitive =>
return GNATCOLL.IO.Remote.Unix.Make_Dir
(Dir.Server, Dir.Full.all, Recursive);
when FS_Windows =>
return GNATCOLL.IO.Remote.Windows.Make_Dir
(Dir.Server, Dir.Full.all, Recursive);
when FS_Unknown =>
raise Remote_Config_Error with
"Invalid FS for host " & Dir.Get_Host;
end case;
end Make_Dir;
----------------
-- Remove_Dir --
----------------
overriding procedure Remove_Dir
(Dir : not null access Remote_File_Record;
Recursive : Boolean;
Success : out Boolean)
is
begin
Ensure_Initialized (Dir);
case Dir.Server.Shell_FS is
when FS_Unix | FS_Unix_Case_Insensitive =>
GNATCOLL.IO.Remote.Unix.Delete_Dir
(Dir.Server, Dir.Full.all, Recursive, Success);
when FS_Windows =>
GNATCOLL.IO.Remote.Windows.Delete_Dir
(Dir.Server, Dir.Full.all, Recursive, Success);
when FS_Unknown =>
raise Remote_Config_Error with
"Invalid FS for host " & Dir.Get_Host;
end case;
end Remove_Dir;
--------------
-- Copy_Dir --
--------------
overriding procedure Copy_Dir
(From : not null access Remote_File_Record;
Dest : FS_String;
Success : out Boolean)
is
begin
Ensure_Initialized (From);
case From.Server.Shell_FS is
when FS_Unix | FS_Unix_Case_Insensitive =>
GNATCOLL.IO.Remote.Unix.Copy_Dir
(From.Server, From.Full.all, Dest, Success);
when FS_Windows =>
GNATCOLL.IO.Remote.Windows.Copy_Dir
(From.Server, From.Full.all, Dest, Success);
when FS_Unknown =>
raise Remote_Config_Error with
"Invalid FS for host " & From.Get_Host;
end case;
end Copy_Dir;
---------------------------
-- Copy_File_Permissions --
---------------------------
overriding procedure Copy_File_Permissions
(From, To : not null access Remote_File_Record;
Success : out Boolean)
is
pragma Unreferenced (From, To);
begin
Success := False;
end Copy_File_Permissions;
-----------
-- Codec --
-----------
package body Codec is
-------------
-- To_UTF8 --
-------------
function To_UTF8 (Path : FS_String) return String is
begin
-- ??? What if the Transport uses a specific charset ?
return String (Path);
end To_UTF8;
---------------
-- From_UTF8 --
---------------
function From_UTF8 (Path : String) return FS_String is
begin
-- ??? What if the Transport uses a specific charset ?
return FS_String (Path);
end From_UTF8;
end Codec;
end GNATCOLL.IO.Remote;
|
------------------------------------------------------------------------------
-- Copyright (c) 2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Natools.Web.Error_Pages provides procedures to build error pages from --
-- site-wide templates, first trying "error-page-XXX" where XXX is the --
-- HTTP error code, then "error-page", then a hardcoded fallback. --
------------------------------------------------------------------------------
with Natools.S_Expressions;
with Natools.Web.Exchanges;
with Natools.Web.Sites;
private with Natools.S_Expressions.Atom_Refs;
package Natools.Web.Error_Pages is
procedure Method_Not_Allowed
(Exchange : in out Sites.Exchange;
Allow : in Exchanges.Method_Set);
procedure Not_Found (Exchange : in out Sites.Exchange);
procedure Permanent_Redirect
(Exchange : in out Sites.Exchange;
Location : in S_Expressions.Atom);
procedure See_Other
(Exchange : in out Sites.Exchange;
Location : in S_Expressions.Atom);
procedure Check_Method
(Exchange : in out Sites.Exchange;
Allowed_Set : in Exchanges.Method_Set;
Allowed : out Boolean);
procedure Check_Method
(Exchange : in out Sites.Exchange;
Allowed_Methods : in Exchanges.Method_Array;
Allowed : out Boolean);
procedure Check_Method
(Exchange : in out Sites.Exchange;
Allowed_Method : in Exchanges.Known_Method;
Allowed : out Boolean);
-- Check whether the method of Exchange is allowed, and if not
-- call Method_Not_Allowed.
private
type Error_Context is record
Location : S_Expressions.Atom_Refs.Immutable_Reference;
Code : S_Expressions.Atom (1 .. 3);
end record;
procedure Main_Render
(Exchange : in out Sites.Exchange;
Context : in Error_Context);
end Natools.Web.Error_Pages;
|
-- { dg-do compile }
-- { dg-options "-O3" }
procedure Opt45 is
type Index_T is mod 2 ** 32;
for Index_T'Size use 32;
for Index_T'Alignment use 1;
type Array_T is array (Index_T range <>) of Natural;
type Array_Ptr_T is access all Array_T;
My_Array_1 : aliased Array_T := (1, 2);
My_Array_2 : aliased Array_T := (3, 4);
Array_Ptr : Array_Ptr_T := null;
Index : Index_T := Index_T'First;
My_Value : Natural := Natural'First;
procedure Proc (Selection : Positive) is
begin
if Selection = 1 then
Array_Ptr := My_Array_1'Access;
Index := My_Array_1'First;
else
Array_Ptr := My_Array_2'Access;
Index := My_Array_2'First;
end if;
if My_Value = Natural'First then
My_Value := Array_Ptr.all (Index);
end if;
end;
begin
Proc (2);
end;
|
package body System.Native_Real_Time is
use type C.signed_int;
function Clock return Native_Time is
Result : aliased C.time.struct_timespec;
begin
if C.time.clock_gettime (C.time.CLOCK_MONOTONIC, Result'Access) < 0 then
raise Program_Error; -- ???
end if;
return Result;
end Clock;
procedure Simple_Delay_Until (T : Native_Time) is
Timeout_T : constant Duration := To_Duration (T);
Current_T : constant Duration := To_Duration (Clock);
D : Duration;
begin
if Timeout_T > Current_T then
D := Timeout_T - Current_T;
else
D := 0.0; -- always calling Delay_For for abort checking
end if;
System.Native_Time.Delay_For (D);
end Simple_Delay_Until;
procedure Delay_Until (T : Native_Time) is
begin
Delay_Until_Hook.all (T);
end Delay_Until;
end System.Native_Real_Time;
|
-----------------------------------------------------------------------
-- properties -- Generic name/value property management
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2014 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
with Ada.Text_IO;
with Util.Concurrent.Counters;
package Util.Properties is
NO_PROPERTY : exception;
use Ada.Strings.Unbounded;
subtype Value is Ada.Strings.Unbounded.Unbounded_String;
function "+" (S : String) return Value renames To_Unbounded_String;
function "-" (S : Value) return String renames To_String;
-- The manager holding the name/value pairs and providing the operations
-- to get and set the properties.
type Manager is new Ada.Finalization.Controlled with private;
type Manager_Access is access all Manager'Class;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in Value) return Boolean;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in String) return Boolean;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return Value;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Value) return Value;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Value) return String;
-- Returns the property value or Default if it does not exist.
function Get (Self : in Manager'Class;
Name : in String;
Default : in String) return String;
-- Insert the specified property in the list.
procedure Insert (Self : in out Manager'Class;
Name : in String;
Item : in String);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in String);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in Value);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in Unbounded_String;
Item : in Value);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in String);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in Value);
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager'Class;
Process : access procedure (Name, Item : Value));
type Name_Array is array (Natural range <>) of Value;
-- Return the name of the properties defined in the manager.
-- When a prefix is specified, only the properties starting with
-- the prefix are returned.
function Get_Names (Self : in Manager;
Prefix : in String := "") return Name_Array;
-- Load the properties from the file input stream. The file must follow
-- the definition of Java property files. When a prefix is specified, keep
-- only the properties that starts with the prefix. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
procedure Load_Properties (Self : in out Manager'Class;
File : in Ada.Text_IO.File_Type;
Prefix : in String := "";
Strip : in Boolean := False);
-- Load the properties from the file. The file must follow the
-- definition of Java property files. When a prefix is specified, keep
-- only the properties that starts with the prefix. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
-- Raises NAME_ERROR if the file does not exist.
procedure Load_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "";
Strip : in Boolean := False);
-- Copy the properties from FROM which start with a given prefix.
-- If the prefix is empty, all properties are copied. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
procedure Copy (Self : in out Manager'Class;
From : in Manager'Class;
Prefix : in String := "";
Strip : in Boolean := False);
private
-- Abstract interface for the implementation of Properties
-- (this allows to decouples the implementation from the API)
package Interface_P is
type Manager is abstract tagged limited record
Count : Util.Concurrent.Counters.Counter;
end record;
type Manager_Access is access all Manager'Class;
type Manager_Factory is access function return Manager_Access;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager; Name : in Value)
return Boolean is abstract;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager; Name : in Value)
return Value is abstract;
procedure Insert (Self : in out Manager; Name : in Value;
Item : in Value) is abstract;
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager; Name : in Value;
Item : in Value) is abstract;
-- Remove the property given its name.
procedure Remove (Self : in out Manager; Name : in Value) is abstract;
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager;
Process : access procedure (Name, Item : Value)) is abstract;
-- Deep copy of properties stored in 'From' to 'To'.
function Create_Copy (Self : in Manager)
return Manager_Access is abstract;
procedure Delete (Self : in Manager; Obj : in out Manager_Access)
is abstract;
function Get_Names (Self : in Manager;
Prefix : in String) return Name_Array is abstract;
end Interface_P;
procedure Set_Property_Implementation (Self : in out Manager;
Impl : in Interface_P.Manager_Access);
-- Create a property implementation if there is none yet.
procedure Check_And_Create_Impl (Self : in out Manager);
type Manager is new Ada.Finalization.Controlled with record
Impl : Interface_P.Manager_Access := null;
end record;
overriding
procedure Adjust (Object : in out Manager);
overriding
procedure Finalize (Object : in out Manager);
end Util.Properties;
|
-- { dg-do run }
with Ada.Text_IO, Ada.Tags;
procedure Test_Iface_Aggr is
package Pkg is
type Iface is interface;
function Constructor (S: Iface) return Iface'Class is abstract;
procedure Do_Test (It : Iface'class);
type Root is abstract tagged record
Comp_1 : Natural := 0;
end record;
type DT_1 is new Root and Iface with record
Comp_2, Comp_3 : Natural := 0;
end record;
function Constructor (S: DT_1) return Iface'Class;
type DT_2 is new DT_1 with null record; -- Test
function Constructor (S: DT_2) return Iface'Class;
end;
package body Pkg is
procedure Do_Test (It: in Iface'Class) is
Obj : Iface'Class := Constructor (It);
S : String := Ada.Tags.External_Tag (Obj'Tag);
begin
null;
end;
function Constructor (S: DT_1) return Iface'Class is
begin
return Iface'Class(DT_1'(others => <>));
end;
function Constructor (S: DT_2) return Iface'Class is
Result : DT_2;
begin
return Iface'Class(DT_2'(others => <>)); -- Test
end;
end;
use Pkg;
Obj: DT_2;
begin
Do_Test (Obj);
end;
|
--
-- The author disclaims copyright to this source code. In place of
-- a legal notice, here is a blessing:
--
-- May you do good and not evil.
-- May you find forgiveness for yourself and forgive others.
-- May you share freely, not taking more than you give.
--
with Ada.Strings.Unbounded;
with Types;
with Symbols;
with Errors;
with Rules;
with Rule_Lists;
package body Parser_FSM is
package Unbounded renames Ada.Strings.Unbounded;
subtype Ustring is Unbounded.Unbounded_String;
subtype Session_Type is Sessions.Session_Type;
subtype Scanner_Record is Parser_Data.Scanner_Record;
subtype Symbol_Record is Symbols.Symbol_Record;
subtype Rule_Symbol_Access is Rules.Rule_Symbol_Access;
subtype Dot_Type is Rules.Dot_Type;
subtype Index_Number is Rules.Index_Number;
Null_Ustring : constant Ustring :=
Unbounded.Null_Unbounded_String;
function To_String (Item : Ustring) return String
renames Unbounded.To_String;
function To_Ustring (Item : String) return Ustring
renames Unbounded.To_Unbounded_String;
function Length (Item : Ustring) return Natural
renames Unbounded.Length;
use Parser_Data;
procedure Do_State_Waiting_For_Decl_Or_Rule (Session : in out Session_Type;
Scanner : in out Scanner_Record;
Token : in String);
procedure Do_State_Precedence_Mark_1 (Scanner : in out Scanner_Record;
Token : in String);
procedure Do_State_Precedence_Mark_2 (Scanner : in out Scanner_Record;
Token : in String);
procedure Do_State_Waiting_For_Decl_Keyword (Session : in out Session_Type;
Scanner : in out Scanner_Record;
Token : in String);
procedure Do_State_Waiting_For_Destructor_Symbol (Session : in out Session_Type;
Scanner : in out Scanner_Record;
Token : in String);
procedure Do_State_Waiting_For_Decl_Arg (Session : in Session_Type;
Scanner : in out Scanner_Record;
Token : in String);
procedure Do_State_Waiting_For_Arrow (Scanner : in out Scanner_Record;
Token : in String);
procedure Do_State_LHS_Alias_1 (Scanner : in out Scanner_Record;
Token : in String);
procedure Do_State_LHS_Alias_2 (Scanner : in out Scanner_Record;
Token : in String);
procedure Do_State_LHS_Alias_3 (Scanner : in out Scanner_Record;
Token : in String);
procedure Do_State_RHS_Alias_1 (Scanner : in out Scanner_Record;
Token : in String);
procedure Do_State_RHS_Alias_2 (Scanner : in out Scanner_Record;
Token : in String);
procedure Do_State_In_RHS (Session : in out Session_Type;
Scanner : in out Scanner_Record;
Token : in String);
procedure Do_State_Waiting_For_Datatype_Symbol (Session : in out Session_Type;
Scanner : in out Scanner_Record;
Token : in String);
procedure Do_State_Waiting_For_Precedence_Symbol (Session : in out Session_Type;
Scanner : in out Scanner_Record;
Token : in String);
procedure Do_State_Waiting_For_Fallback_Id (Session : in out Session_Type;
Scanner : in out Scanner_Record;
Token : in String);
procedure Do_State_Waiting_For_Token_Name (Scanner : in out Scanner_Record;
Token : in String);
procedure Do_State_Waiting_For_Wildcard_Id (Session : in out Session_Type;
Scanner : in out Scanner_Record;
Token : in String);
procedure Do_State_Waiting_For_Class_Id (Scanner : in out Scanner_Record;
Token : in String);
procedure Do_State_Waiting_For_Class_Token (Scanner : in out Scanner_Record;
Token : in String);
--
--
--
use Errors;
procedure Do_State (Session : in out Session_Type;
Scanner : in out Scanner_Record;
Token : in String)
is
C : Character renames Token (Token'First);
begin
case Scanner.State is
when DUMMY =>
null;
when WAITING_FOR_DECL_OR_RULE =>
Do_State_Waiting_For_Decl_Or_Rule (Session, Scanner, Token);
when PRECEDENCE_MARK_1 =>
Do_State_Precedence_Mark_1 (Scanner, Token);
when PRECEDENCE_MARK_2 =>
Do_State_Precedence_Mark_2 (Scanner, Token);
when WAITING_FOR_ARROW =>
Do_State_Waiting_For_Arrow (Scanner, Token);
when LHS_ALIAS_1 =>
Do_State_LHS_Alias_1 (Scanner, Token);
when LHS_ALIAS_2 =>
Do_State_LHS_Alias_2 (Scanner, Token);
when LHS_ALIAS_3 =>
Do_State_LHS_Alias_3 (Scanner, Token);
when IN_RHS =>
Do_State_In_RHS (Session, Scanner, Token);
when RHS_ALIAS_1 =>
Do_State_RHS_Alias_1 (Scanner, Token);
when RHS_ALIAS_2 =>
Do_State_RHS_Alias_2 (Scanner, Token);
when WAITING_FOR_DECL_KEYWORD =>
Do_State_Waiting_For_Decl_Keyword (Session, Scanner, Token);
when WAITING_FOR_DESTRUCTOR_SYMBOL =>
Do_State_Waiting_For_Destructor_Symbol (Session, Scanner, Token);
when WAITING_FOR_DATATYPE_SYMBOL =>
Do_State_Waiting_For_Datatype_Symbol (Session, Scanner, Token);
when WAITING_FOR_PRECEDENCE_SYMBOL =>
Do_State_Waiting_For_Precedence_Symbol (Session, Scanner, Token);
when WAITING_FOR_DECL_ARG =>
Do_State_Waiting_For_Decl_Arg (Session, Scanner, Token);
when WAITING_FOR_FALLBACK_ID =>
Do_State_Waiting_For_Fallback_Id (Session, Scanner, Token);
when WAITING_FOR_TOKEN_NAME =>
Do_State_Waiting_For_Token_Name (Scanner, Token);
when WAITING_FOR_WILDCARD_ID =>
Do_State_Waiting_For_Wildcard_Id (Session, Scanner, Token);
when WAITING_FOR_CLASS_ID =>
Do_State_Waiting_For_Class_Id (Scanner, Token);
when WAITING_FOR_CLASS_TOKEN =>
Do_State_Waiting_For_Class_Token (Scanner, Token);
when RESYNC_AFTER_RULE_ERROR =>
-- // if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
-- // break;
null;
when RESYNC_AFTER_DECL_ERROR =>
case C is
when '.' =>
Scanner.State := WAITING_FOR_DECL_OR_RULE;
when '%' =>
Scanner.State := WAITING_FOR_DECL_KEYWORD;
when others =>
null;
end case;
end case;
end Do_State;
procedure Initialize_FSM (Session : in out Session_Type;
Scanner : in out Scanner_Record)
is
pragma Unreferenced (Session);
use Rule_Lists.Lists;
begin
Scanner.Previous_Rule := No_Element;
Scanner.Prec_Counter := 0;
Scanner.Rule := Empty_List;
Scanner.State := WAITING_FOR_DECL_OR_RULE;
end Initialize_FSM;
procedure Do_State_Waiting_For_Decl_Or_Rule (Session : in out Session_Type;
Scanner : in out Scanner_Record;
Token : in String)
is
pragma Unreferenced (Session);
use Rules;
use Rule_Lists.Lists;
Cur : Character renames Token (Token'First);
begin
if Cur = '%' then
Scanner.State := WAITING_FOR_DECL_KEYWORD;
elsif Cur in 'a' .. 'z' then
Scanner.LHS.Clear;
Scanner.LHS.Append (Symbols.Create (Token));
Scanner.RHS.Clear;
Scanner.LHS_Alias.Clear;
Scanner.State := WAITING_FOR_ARROW;
elsif Cur = '{' then
if Scanner.Previous_Rule = No_Element then
Parser_Error (E001, Scanner.Token_Lineno);
elsif Rules."/=" (Element (Scanner.Previous_Rule).Code, Null_Code) then
Parser_Error (E002, Scanner.Token_Lineno);
elsif Token = "{NEVER-REDUCE" then
Element (Scanner.Previous_Rule).Never_Reduce := True;
else
Element (Scanner.Previous_Rule).Line := Scanner.Token_Lineno;
Element (Scanner.Previous_Rule).Code :=
Ustring'(To_Ustring (Token (Token'First + 1 .. Token'Last)));
Element (Scanner.Previous_Rule).No_Code := False;
end if;
elsif Cur = '[' then
Scanner.State := PRECEDENCE_MARK_1;
else
Parser_Error (E003, Scanner.Token_Lineno, Token);
end if;
end Do_State_Waiting_For_Decl_Or_Rule;
procedure Do_State_Precedence_Mark_1 (Scanner : in out Scanner_Record;
Token : in String)
is
use Rules;
use Rule_Lists.Lists;
begin
if Token (Token'First) not in 'A' .. 'Z' then
Parser_Error (E004, Scanner.Token_Lineno);
elsif Scanner.Previous_Rule = No_Element then
Parser_Error (E005, Scanner.Token_Lineno, Token);
elsif Element (Scanner.Previous_Rule).Prec_Symbol /= null then
Parser_Error (E006, Scanner.Token_Lineno);
else
Element (Scanner.Previous_Rule).Prec_Symbol :=
Rule_Symbol_Access (Symbols.Create (Token));
end if;
Scanner.State := PRECEDENCE_MARK_2;
end Do_State_Precedence_Mark_1;
procedure Do_State_Precedence_Mark_2 (Scanner : in out Scanner_Record;
Token : in String)
is
begin
if Token (Token'First) /= ']' then
Parser_Error (E007, Scanner.Token_Lineno);
end if;
Scanner.State := WAITING_FOR_DECL_OR_RULE;
end Do_State_Precedence_Mark_2;
procedure Do_State_Waiting_For_Decl_Keyword (Session : in out Session_Type;
Scanner : in out Scanner_Record;
Token : in String)
is
Cur : Character renames Token (Token'First);
begin
if
Cur in 'a' .. 'z' or
Cur in 'A' .. 'Z'
then
Scanner.Decl_Keyword := To_Ustring (Token);
Scanner.Decl_Arg_Slot := null;
Scanner.Insert_Line_Macro := True;
Scanner.State := WAITING_FOR_DECL_ARG;
if Token = "name" then
Scanner.Decl_Arg_Slot := Session.Names.Name'Access;
Scanner.Insert_Line_Macro := False;
elsif Token = "include" then
Scanner.Decl_Arg_Slot := Session.Names.Include'Access;
elsif Token = "code" then
Scanner.Decl_Arg_Slot := Session.Names.Extra_Code'Access;
elsif Token = "token_destructor" then
Scanner.Decl_Arg_Slot := Session.Names.Token_Dest'Access;
elsif Token = "default_destructor" then
Scanner.Decl_Arg_Slot := Session.Names.Var_Dest'Access;
elsif Token = "token_prefix" then
Scanner.Decl_Arg_Slot := Session.Names.Token_Prefix'Access;
Scanner.Insert_Line_Macro := False;
elsif Token = "syntax_error" then
Scanner.Decl_Arg_Slot := Session.Names.Error'Access;
elsif Token = "parse_accept" then
Scanner.Decl_Arg_Slot := Session.Names.C_Accept'Access;
elsif Token = "parse_failure" then
Scanner.Decl_Arg_Slot := Session.Names.Failure'Access;
elsif Token = "stack_overflow" then
Scanner.Decl_Arg_Slot := Session.Names.Overflow'Access;
elsif Token = "extra_argument" then
Scanner.Decl_Arg_Slot := Session.Names.ARG2'Access;
Scanner.Insert_Line_Macro := False;
elsif Token = "extra_context" then
Scanner.Decl_Arg_Slot := Session.Names.CTX2'Access;
Scanner.Insert_Line_Macro := False;
elsif Token = "token_type" then
Scanner.Decl_Arg_Slot := Session.Names.Token_Type'Access;
Scanner.Insert_Line_Macro := False;
elsif Token = "default_type" then
Scanner.Decl_Arg_Slot := Session.Names.Var_Type'Access;
Scanner.Insert_Line_Macro := False;
elsif Token = "stack_size" then
Scanner.Decl_Arg_Slot := Session.Names.Stack_Size'Access;
Scanner.Insert_Line_Macro := False;
elsif Token = "start_symbol" then
Scanner.Decl_Arg_Slot := Session.Names.Start'Access;
Scanner.Insert_Line_Macro := False;
elsif Token = "left" then
Scanner.Prec_Counter := Scanner.Prec_Counter + 1;
Scanner.Decl_Association := Symbols.Left_Association;
Scanner.State := WAITING_FOR_PRECEDENCE_SYMBOL;
elsif Token = "right" then
Scanner.Prec_Counter := Scanner.Prec_Counter + 1;
Scanner.Decl_Association := Symbols.Right_Association;
Scanner.State := WAITING_FOR_PRECEDENCE_SYMBOL;
elsif Token = "nonassoc" then
Scanner.Prec_Counter := Scanner.Prec_Counter + 1;
Scanner.Decl_Association := Symbols.No_Association;
Scanner.State := WAITING_FOR_PRECEDENCE_SYMBOL;
elsif Token = "destructor" then
Scanner.State := WAITING_FOR_DESTRUCTOR_SYMBOL;
elsif Token = "type" then
Scanner.State := WAITING_FOR_DATATYPE_SYMBOL;
elsif Token = "fallback" then
Scanner.Fallback := null;
Scanner.State := WAITING_FOR_FALLBACK_ID;
elsif Token = "token" then
Scanner.State := WAITING_FOR_TOKEN_NAME;
elsif Token = "wildcard" then
Scanner.State := WAITING_FOR_WILDCARD_ID;
elsif Token = "token_class" then
Scanner.State := WAITING_FOR_CLASS_ID;
else
Parser_Error (E203, Scanner.Token_Lineno, Token);
Scanner.State := RESYNC_AFTER_DECL_ERROR;
end if;
else
Parser_Error (E204, Scanner.Token_Lineno, Token);
Scanner.State := RESYNC_AFTER_DECL_ERROR;
end if;
end Do_State_Waiting_For_Decl_Keyword;
procedure Do_State_Waiting_For_Destructor_Symbol (Session : in out Session_Type;
Scanner : in out Scanner_Record;
Token : in String)
is
pragma Unreferenced (Session);
begin
if
Token (Token'First) not in 'a' .. 'z' and
Token (Token'First) not in 'A' .. 'Z'
then
Parser_Error (E205, Scanner.Token_Lineno);
Scanner.State := RESYNC_AFTER_DECL_ERROR;
else
declare
use Symbols;
Symbol : Symbol_Access := Create (Token);
begin
Scanner.Decl_Arg_Slot := new Ustring'(Symbol.Destructor);
Scanner.Decl_Lineno_Slot := Symbol.Dest_Lineno'Access;
Scanner.Insert_Line_Macro := True;
end;
Scanner.State := WAITING_FOR_DECL_ARG;
end if;
end Do_State_Waiting_For_Destructor_Symbol;
procedure Do_State_Waiting_For_Arrow (Scanner : in out Scanner_Record;
Token : in String)
is
begin
if
Token'Length >= 3 and then
Token (Token'First .. Token'First + 2) = "::="
then
Scanner.State := IN_RHS;
elsif Token (Token'First) = '(' then
Scanner.State := LHS_ALIAS_1;
else
declare
use Symbols;
begin
Parser_Error (E008, Scanner.Token_Lineno,
Name_Of (Scanner.LHS.First_Element));
Scanner.State := RESYNC_AFTER_RULE_ERROR;
end;
end if;
end Do_State_Waiting_For_Arrow;
procedure Do_State_LHS_Alias_1 (Scanner : in out Scanner_Record;
Token : in String)
is
begin
if
Token (Token'First) in 'a' .. 'z' or
Token (Token'First) in 'A' .. 'Z'
then
Scanner.LHS_Alias.Clear;
Scanner.LHS_Alias.Append (To_Alias (Token));
Scanner.State := LHS_ALIAS_2;
else
Parser_Error
(E009, Scanner.Token_Lineno,
Argument_1 => Token,
Argument_2 => Symbols.Name_Of (Scanner.LHS.First_Element));
Scanner.State := RESYNC_AFTER_RULE_ERROR;
end if;
end Do_State_LHS_Alias_1;
procedure Do_State_LHS_Alias_2 (Scanner : in out Scanner_Record;
Token : in String)
is
begin
if Token (Token'First) = ')' then
Scanner.State := LHS_ALIAS_3;
else
Parser_Error (E010, Scanner.Token_Lineno,
To_String (Scanner.LHS_Alias.First_Element));
Scanner.State := RESYNC_AFTER_RULE_ERROR;
end if;
end Do_State_LHS_Alias_2;
procedure Do_State_LHS_Alias_3 (Scanner : in out Scanner_Record;
Token : in String)
is
begin
if Token (Token'First .. Token'First + 2) = "::=" then
Scanner.State := IN_RHS;
else
Parser_Error
(E011, Scanner.Token_Lineno,
Argument_1 => Symbols.Name_Of (Scanner.LHS.First_Element),
Argument_2 => To_String (Scanner.LHS_Alias.First_Element));
Scanner.State := RESYNC_AFTER_RULE_ERROR;
end if;
end Do_State_LHS_Alias_3;
procedure Do_State_RHS_Alias_1 (Scanner : in out Scanner_Record;
Token : in String)
is
begin
if
Token (Token'First) in 'a' .. 'z' or
Token (Token'First) in 'A' .. 'Z'
then
Scanner.Alias.Append (To_Alias (Token));
Scanner.State := RHS_ALIAS_2;
else
Parser_Error
(E012, Scanner.Token_Lineno,
Argument_1 => Token,
Argument_2 => Symbols.Name_Of (Scanner.RHS.Last_Element));
Scanner.State := RESYNC_AFTER_RULE_ERROR;
end if;
end Do_State_RHS_Alias_1;
procedure Do_State_RHS_Alias_2 (Scanner : in out Scanner_Record;
Token : in String)
is
begin
if Token (Token'First) = ')' then
Scanner.State := IN_RHS;
else
Parser_Error (E013, Scanner.Token_Lineno,
To_String (Scanner.LHS_Alias.First_Element));
Scanner.State := RESYNC_AFTER_RULE_ERROR;
end if;
end Do_State_RHS_Alias_2;
procedure Do_State_In_RHS (Session : in out Session_Type;
Scanner : in out Scanner_Record;
Token : in String)
is
pragma Unreferenced (Session);
Cur : Character renames Token (Token'First);
begin
if Cur = '.' then
declare
use Rule_Lists;
use Rules.Alias_Vectors;
Rule : Rule_Access;
begin
Rule := new Rules.Rule_Record;
Rule.Rule_Line := Scanner.Token_Lineno;
for I in Scanner.RHS.First_Index .. Scanner.RHS.Last_Index loop
Rule.RHS.Append
(New_Item => Rules.Rule_Symbol_Access (Scanner.RHS.Element (I)),
Count => 1);
if I in Scanner.Alias.First_Index .. Scanner.Alias.Last_Index then
Rule.RHS_Alias.Append (Scanner.Alias.Element (I));
else
Rule.RHS_Alias.Append (Null_Ustring);
end if;
if Length (Rule.RHS_Alias.Element (Dot_Type (I))) /= 0 then
declare
Symbol : constant Rule_Symbol_Access := Rule.RHS (Dot_Type (I));
begin
Symbol.Content := True;
end;
end if;
end loop;
Rule.LHS := Rule_Symbol_Access (Scanner.LHS.First_Element);
if Scanner.LHS_Alias.Is_Empty then
Rule.LHS_Alias := Null_Ustring;
else
Rule.LHS_Alias := Scanner.LHS_Alias.First_Element;
end if;
Rule.Code := Rules.Null_Code;
Rule.No_Code := True;
Rule.Prec_Symbol := null;
Rule.Index := Index_Number (Scanner.Rule.Length);
declare
use Symbols;
begin
Rule.Next_LHS := Rules.Rule_Access (Symbol_Access (Rule.LHS).Rule);
Symbol_Access (Rule.LHS).Rule := Rule;
end;
Scanner.Rule.Append (Rule);
Scanner.Previous_Rule := Scanner.Rule.Last;
end;
Scanner.State := WAITING_FOR_DECL_OR_RULE;
elsif
Cur in 'a' .. 'z' or
Cur in 'A' .. 'Z'
then
Scanner.RHS .Append (Symbols.Create (Token));
Scanner.Alias.Append (Null_Ustring);
elsif
(Cur = '|' or Cur = '/') and not
Scanner.RHS.Is_Empty
then
declare
use Symbols;
Symbol : Symbol_Access := Scanner.RHS.Last_Element;
begin
if Symbol.Kind /= Multi_Terminal then
declare
Orig_Symbol : constant Symbol_Access := Symbol;
begin
Symbol := new Symbol_Record;
Symbol.Kind := Multi_Terminal;
Symbol.Sub_Symbol.Append (Orig_Symbol);
Symbol.Name := Orig_Symbol.Name;
Scanner.RHS.Delete_Last;
Scanner.RHS.Append (Symbol);
end;
end if;
Symbol.Sub_Symbol.Append
(Symbols.Create (Token (Token'First + 1 .. Token'Last)));
if
Token (Token'First + 1) in 'a' .. 'z' or
To_String (Symbol.Sub_Symbol.First_Element.Name) (1) in 'a' .. 'z'
then
Parser_Error (E201, Scanner.Token_Lineno);
end if;
end;
elsif Cur = '(' and not Scanner.RHS.Is_Empty then
Scanner.State := RHS_ALIAS_1;
else
Parser_Error (E202, Scanner.Token_Lineno, Token);
Scanner.State := RESYNC_AFTER_RULE_ERROR;
end if;
end Do_State_In_RHS;
procedure Do_State_Waiting_For_Decl_Arg (Session : in Session_Type;
Scanner : in out Scanner_Record;
Token : in String)
is
Cur : Character renames Token (Token'First);
begin
if
Cur = '{' or
Cur = '"' or
Cur in 'a' .. 'z' or
Cur in 'A' .. 'Z' or
Cur in '0' .. '9'
then
declare
use Unbounded;
use type Types.Line_Number;
N : Integer;
Back : Integer;
New_String : constant String := Token;
Old_String : Ustring;
Buf_String : Ustring;
Z : Ustring;
New_First : Positive := New_String'First;
Old_Length : Natural;
Z_Pos : Natural;
Add_Line_Macro : Boolean;
Line : Ustring;
begin
if
New_String (New_First) = '"' or
New_String (New_First) = '{'
then
New_First := New_First + 1;
end if;
if Scanner.Decl_Arg_Slot = null then
Old_String := To_Ustring ("");
else
Old_String := Scanner.Decl_Arg_Slot.all;
end if;
Old_Length := Length (Old_String);
N := Old_Length + New_First + 20;
Add_Line_Macro :=
-- not Scanner.Gp.No_Linenos_Flag and
not Session.No_Linenos_Flag and
Scanner.Insert_Line_Macro and
(Scanner.Decl_Lineno_Slot = null or
Scanner.Decl_Lineno_Slot.all /= 0);
--
-- Add line macro
--
if Add_Line_Macro then
Z := Scanner.File_Name;
Z_Pos := 1;
Back := 0;
while Z_Pos <= Length (Z) loop
if Element (Z, Z_Pos) = '\' then
Back := Back + 1;
end if;
Z_Pos := Z_Pos + 1;
end loop;
Line := To_Unbounded_String ("#line ");
Append (Line, Types.Line_Number'Image (Scanner.Token_Lineno));
Append (Line, " ");
N := N + Length (Line) + Length (Scanner.File_Name) + Back;
end if;
-- Scanner.Decl_Arg_Slot = (char *) realloc(Scanner.Decl_Arg_Slot, n);
Buf_String := Scanner.Decl_Arg_Slot.all; -- + nOld;
if Add_Line_Macro then
-- if
-- Old_Length /= 0 and
-- Element (Buf_String, -1) /= ASCII.LF
-- then
-- -- *(zBuf++) := ASCII.NL;
-- Append (Buf_String, ASCII.LF);
-- end if;
-- Append line feed to Buf is missing at end
if
(Length (Old_String) /= 0 and Length (Buf_String) /= 0) and then
Element (Buf_String, Length (Buf_String)) /= ASCII.LF
then
Append (Buf_String, ASCII.LF);
end if;
Append (Buf_String, Line);
-- Put_Line ("## XX");
-- Put_Line (To_String (Buf_String));
-- Buf_String := Buf_String; -- + nLine;
-- *(zBuf++) = '"';
Append (Buf_String, '"');
Append (Z, Scanner.File_Name);
while Z_Pos <= Length (Z) loop
if Element (Z, Z_Pos) = '\' then
Append (Buf_String, '\');
end if;
-- *(zBuf++) = *z;
Append (Buf_String, Element (Z, Z_Pos));
Z_Pos := Z_Pos + 1;
end loop;
-- *(zBuf++) := '"';
-- *(zBuf++) := ASCII.NL;
Append (Buf_String, '"');
Append (Buf_String, ASCII.LF);
end if;
if
Scanner.Decl_Lineno_Slot /= null and
Scanner.Decl_Lineno_Slot.all = 0
then
Scanner.Decl_Lineno_Slot.all := Scanner.Token_Lineno;
end if;
Buf_String := To_Unbounded_String (New_String);
-- Buf_String := Buf_String; -- + nNew;
-- *zBuf := 0;
Scanner.State := WAITING_FOR_DECL_OR_RULE;
-- Scanner.Done := True;
end;
else
Parser_Error (E213, Scanner.Token_Lineno,
Argument_1 => To_String (Scanner.Decl_Keyword),
Argument_2 => Token);
Scanner.State := RESYNC_AFTER_DECL_ERROR;
end if;
end Do_State_Waiting_For_Decl_Arg;
procedure Do_State_Waiting_For_Datatype_Symbol (Session : in out Session_Type;
Scanner : in out Scanner_Record;
Token : in String)
is
pragma Unreferenced (Session);
use type Ustring;
begin
if
Token (Token'First) not in 'a' .. 'z' and
Token (Token'First) not in 'A' .. 'Z'
then
Parser_Error (E206, Scanner.Token_Lineno);
Scanner.State := RESYNC_AFTER_DECL_ERROR;
else
declare
use Symbols;
Symbol : Symbol_Access := Find (Token);
begin
if
Symbol /= null and then
Symbol.Data_Type /= Null_Ustring
then
Parser_Error (E207, Scanner.Line, Token);
Scanner.State := RESYNC_AFTER_DECL_ERROR;
else
if Symbol = null then
Symbol := Create (Token);
end if;
Scanner.Decl_Arg_Slot
:= Symbol.Data_Type'Access;
-- Scanner.Decl_Arg_Slot := new Unbounded_String'(Symbol.Data_Type);
-- new chars_ptr'(New_String (To_String (Symbol.Data_Type)));
Scanner.Insert_Line_Macro := False;
Scanner.State := WAITING_FOR_DECL_ARG;
end if;
end;
end if;
end Do_State_Waiting_For_Datatype_Symbol;
procedure Do_State_Waiting_For_Precedence_Symbol (Session : in out Session_Type;
Scanner : in out Scanner_Record;
Token : in String)
is
pragma Unreferenced (Session);
begin
if Token (Token'First) = '.' then
Scanner.State := WAITING_FOR_DECL_OR_RULE;
elsif Token (Token'First) in 'A' .. 'Z' then
declare
use Symbols;
Symbol : constant Symbol_Access := Create (Token);
begin
if Symbol.Precedence >= 0 then
Parser_Error (E217, Scanner.Token_Lineno, Token);
else
Symbol.Precedence := Scanner.Prec_Counter;
Symbol.Association := Scanner.Decl_Association;
end if;
end;
else
Parser_Error (E218, Scanner.Token_Lineno, Token);
end if;
end Do_State_Waiting_For_Precedence_Symbol;
procedure Do_State_Waiting_For_Fallback_Id (Session : in out Session_Type;
Scanner : in out Scanner_Record;
Token : in String)
is
begin
if Token (Token'First) = '.' then
Scanner.State := WAITING_FOR_DECL_OR_RULE;
elsif Token (Token'First) not in 'A' .. 'Z' then
Parser_Error (E215, Scanner.Token_Lineno, Token);
else
declare
use Symbols;
Symbol : constant Symbol_Access := Create (Token);
begin
if Scanner.Fallback = null then
Scanner.Fallback := Symbol;
elsif Symbol.Fallback /= null then
Parser_Error (E216, Scanner.Token_Lineno, Token);
else
Symbol.Fallback := Scanner.Fallback;
Session.Has_Fallback := True;
-- Scanner.Gp.Has_Fallback := True;
end if;
end;
end if;
end Do_State_Waiting_For_Fallback_Id;
procedure Do_State_Waiting_For_Token_Name (Scanner : in out Scanner_Record;
Token : in String)
is
begin
-- Tokens do not have to be declared before use. But they can be
-- in order to control their assigned integer number. The number for
-- each token is assigned when it is first seen. So by including
--
-- %token ONE TWO THREE
--
-- early in the grammar file, that assigns small consecutive values
-- to each of the tokens ONE TWO and THREE.
if Token (Token'First) = '.' then
Scanner.State := WAITING_FOR_DECL_OR_RULE;
elsif Token (Token'First) not in 'A' .. 'Z' then
Parser_Error (E214, Scanner.Token_Lineno, Token);
else
declare
use Symbols;
Dummy_Symbol : Symbol_Access;
begin
Dummy_Symbol := Create (Token);
end;
end if;
end Do_State_Waiting_For_Token_Name;
procedure Do_State_Waiting_For_Wildcard_Id (Session : in out Session_Type;
Scanner : in out Scanner_Record;
Token : in String)
is
C : Character renames Token (Token'First);
begin
if C = '.' then
Scanner.State := WAITING_FOR_DECL_OR_RULE;
elsif C not in 'A' .. 'Z' then
Parser_Error (E211, Scanner.Token_Lineno, Token);
else
declare
use Symbols;
Symbol : constant Symbol_Access := Create (Token);
begin
if Session.Wildcard = null then
Session.Wildcard := Symbol;
else
Parser_Error (E212, Scanner.Token_Lineno, Token);
end if;
end;
end if;
end Do_State_Waiting_For_Wildcard_Id;
procedure Do_State_Waiting_For_Class_Id (Scanner : in out Scanner_Record;
Token : in String)
is
use Symbols;
C : Character renames Token (Token'First);
begin
if C not in 'a' .. 'z' then
Parser_Error (E209, Scanner.Token_Lineno, Token);
Scanner.State := RESYNC_AFTER_DECL_ERROR;
elsif Find (Token) /= null then
Parser_Error (E210, Scanner.Token_Lineno, Token);
Scanner.State := RESYNC_AFTER_DECL_ERROR;
else
Scanner.Token_Class := Create (Token);
Scanner.Token_Class.Kind := Multi_Terminal;
Scanner.State := WAITING_FOR_CLASS_TOKEN;
end if;
end Do_State_Waiting_For_Class_Id;
procedure Do_State_Waiting_For_Class_Token (Scanner : in out Scanner_Record;
Token : in String)
is
C : Character renames Token (Token'First);
begin
if C = '.' then
Scanner.State := WAITING_FOR_DECL_OR_RULE;
elsif
C in 'A' .. 'Z' or
((C = '|' or C = '/') and
Token (Token'First + 1) in 'A' .. 'Z')
then
declare
use Symbols;
Symbol : constant Symbol_Access := Scanner.Token_Class;
First : Natural := Token'First;
begin
if C not in 'A' .. 'Z' then
First := Token'First + 1;
end if;
Symbol.Sub_Symbol.Append (Create (Token (First .. Token'Last)));
end;
else
Parser_Error (E208, Scanner.Token_Lineno, Token);
Scanner.State := RESYNC_AFTER_DECL_ERROR;
end if;
end Do_State_Waiting_For_Class_Token;
end Parser_FSM;
|
with Ada.Text_IO; use Ada.Text_IO;
package body Test_Assertions is
Max : constant := 50;
Separators : constant String (1 .. 60) := (others => '.');
-----------------
-- Assert_True --
-----------------
procedure Assert_True (Value : Boolean) is
begin
if not Value then
raise Test_Assertion_Error;
end if;
end Assert_True;
procedure Assert_True (Value : Boolean; Message : String) is
begin
Put (Message);
if Message'Length < Max then
Put (Separators (1 .. Max - Message'Length));
end if;
if Value then
Put_Line (" OK");
else
Put_Line (" FAILED (Assert_True)");
end if;
end Assert_True;
------------------
-- Assert_False --
------------------
procedure Assert_False (Value : Boolean) is
begin
if Value then
raise Test_Assertion_Error;
end if;
end Assert_False;
procedure Assert_False (Value : Boolean; Message : String) is
begin
Put (Message);
if Message'Length < Max then
Put (Separators (1 .. Max - Message'Length));
end if;
if not Value then
Put_Line (" OK");
else
Put_Line (" FAILED (Assert_False)");
end if;
end Assert_False;
end Test_Assertions;
|
-- Copyright 2016-2021 Bartek thindil Jasicki
--
-- This file is part of Steam Sky.
--
-- Steam Sky is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- Steam Sky is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with Steam Sky. If not, see <http://www.gnu.org/licenses/>.
with Ships; use Ships;
with Messages; use Messages;
with ShipModules; use ShipModules;
with Utils; use Utils;
with Ships.Cargo; use Ships.Cargo;
with Ships.Crew; use Ships.Crew;
with Ships.Movement; use Ships.Movement;
with Maps; use Maps;
with Crew.Inventory; use Crew.Inventory;
with Combat; use Combat;
with Factions; use Factions;
with Bases; use Bases;
with Careers; use Careers;
with Config; use Config;
package body Crew is
procedure GainExp(Amount: Natural; SkillNumber, CrewIndex: Positive) is
use Tiny_String;
SkillExp, AttributeExp, AttributeLevel, NewAmount: Natural := 0;
AttributeIndex: constant Skills_Container.Extended_Index :=
Natural
(SkillsData_Container.Element(Skills_List, SkillNumber).Attribute);
SkillIndex: Skills_Container.Extended_Index := 0;
SkillLevel: Skill_Range := 0;
procedure GainExpInAttribute(Attribute: Positive) is
Attribute_To_Check: Mob_Attribute_Record :=
Player_Ship.Crew(CrewIndex).Attributes(Attribute);
begin
if Attribute_To_Check.Level = 50 then
return;
end if;
AttributeExp := Attribute_To_Check.Experience + NewAmount;
AttributeLevel := Attribute_To_Check.Level;
if AttributeExp >= (AttributeLevel * 250) then
AttributeExp := AttributeExp - (AttributeLevel * 250);
AttributeLevel := AttributeLevel + 1;
end if;
Attribute_To_Check.Level := AttributeLevel;
Attribute_To_Check.Experience := AttributeExp;
Player_Ship.Crew(CrewIndex).Attributes(Attribute) :=
Attribute_To_Check;
end GainExpInAttribute;
begin
NewAmount :=
(if
Careers_List(Player_Career).Skills.Contains
(To_Unbounded_String
(To_String
(SkillsData_Container.Element(Skills_List, SkillNumber)
.Name)))
then Amount + (Amount / 2)
else Amount);
NewAmount :=
Natural(Float(NewAmount) * Float(New_Game_Settings.Experience_Bonus));
if NewAmount = 0 then
return;
end if;
-- Gain experience in condition assigned attribute
GainExpInAttribute(Positive(Condition_Index));
-- Gain experience in associated attribute
GainExpInAttribute(AttributeIndex);
-- Gain experience in skill
Experience_In_Skill_Loop :
for I in Player_Ship.Crew(CrewIndex).Skills.Iterate loop
if Player_Ship.Crew(CrewIndex).Skills(I).Index = SkillNumber then
SkillIndex := Skills_Container.To_Index(I);
exit Experience_In_Skill_Loop;
end if;
end loop Experience_In_Skill_Loop;
if SkillIndex > 0 then
if Player_Ship.Crew(CrewIndex).Skills(SkillIndex).Level =
Skill_Range'Last then
return;
end if;
SkillLevel := Player_Ship.Crew(CrewIndex).Skills(SkillIndex).Level;
SkillExp :=
Player_Ship.Crew(CrewIndex).Skills(SkillIndex).Experience +
NewAmount;
end if;
if SkillExp >= (SkillLevel * 25) then
SkillExp := SkillExp - (SkillLevel * 25);
SkillLevel := SkillLevel + 1;
end if;
if SkillIndex > 0 then
Player_Ship.Crew(CrewIndex).Skills(SkillIndex).Level := SkillLevel;
Player_Ship.Crew(CrewIndex).Skills(SkillIndex).Experience := SkillExp;
else
Player_Ship.Crew(CrewIndex).Skills.Append
(New_Item => (SkillNumber, SkillLevel, SkillExp));
end if;
end GainExp;
function GenerateMemberName
(Gender: Character; FactionIndex: Unbounded_String)
return Unbounded_String is
NewName: Unbounded_String := Null_Unbounded_String;
NameType: constant NamesTypes := Factions_List(FactionIndex).NamesType;
begin
if NameType = Factions.ROBOTIC then
return Generate_Robotic_Name;
end if;
if Gender = 'M' then
NewName :=
MaleSyllablesStart
(Get_Random
(MaleSyllablesStart.First_Index,
MaleSyllablesStart.Last_Index)) &
MaleVocals
(Get_Random(MaleVocals.First_Index, MaleVocals.Last_Index));
if Get_Random(1, 100) < 36 then
Append
(NewName,
MaleSyllablesMiddle
(Get_Random
(MaleSyllablesMiddle.First_Index,
MaleSyllablesMiddle.Last_Index)));
end if;
if Get_Random(1, 100) < 11 then
Append
(NewName,
MaleConsonants
(Get_Random
(MaleConsonants.First_Index, MaleConsonants.Last_Index)));
end if;
Append
(NewName,
MaleSyllablesEnd
(Get_Random
(MaleSyllablesEnd.First_Index, MaleSyllablesEnd.Last_Index)));
return NewName;
end if;
NewName :=
FemaleSyllablesStart
(Get_Random
(FemaleSyllablesStart.First_Index,
FemaleSyllablesStart.Last_Index)) &
FemaleVocals
(Get_Random(FemaleVocals.First_Index, FemaleVocals.Last_Index));
if Get_Random(1, 100) < 36 then
Append
(NewName,
FemaleSyllablesMiddle
(Get_Random
(FemaleSyllablesMiddle.First_Index,
FemaleSyllablesMiddle.Last_Index)));
end if;
if Get_Random(1, 100) < 11 then
Append
(NewName,
FemaleSyllablesMiddle
(Get_Random
(FemaleSyllablesMiddle.First_Index,
FemaleSyllablesMiddle.Last_Index)));
end if;
Append
(NewName,
FemaleSyllablesEnd
(Get_Random
(FemaleSyllablesEnd.First_Index,
FemaleSyllablesEnd.Last_Index)));
return NewName;
end GenerateMemberName;
function FindCabin(MemberIndex: Positive) return Natural is
begin
Find_Cabin_Loop :
for I in Player_Ship.Modules.Iterate loop
if Player_Ship.Modules(I).M_Type = CABIN then
Check_Owner_Loop :
for Owner of Player_Ship.Modules(I).Owner loop
if Owner = MemberIndex then
return Modules_Container.To_Index(I);
end if;
end loop Check_Owner_Loop;
end if;
end loop Find_Cabin_Loop;
return 0;
end FindCabin;
procedure UpdateCrew
(Minutes: Positive; TiredPoints: Natural; InCombat: Boolean := False) is
use Tiny_String;
TiredLevel, HungerLevel, ThirstLevel: Integer := 0;
HealthLevel: Integer := 100;
DeathReason: Unbounded_String;
ToolIndex: Inventory_Container.Extended_Index;
CabinIndex: Modules_Container.Extended_Index;
Times, RestAmount, I: Natural;
OrderTime, CurrentMinutes, HealAmount: Integer;
Damage: Damage_Factor := 0.0;
NeedCleaning, HaveMedicalRoom: Boolean := False;
SkillIndex: Skills_Container.Extended_Index;
function Consume(ItemType: Unbounded_String) return Natural is
ConsumeValue: Natural;
ItemIndex: Inventory_Container.Extended_Index :=
FindItem(Inventory => Player_Ship.Cargo, ItemType => ItemType);
begin
if ItemIndex > 0 then
ConsumeValue :=
Items_List(Player_Ship.Cargo(ItemIndex).ProtoIndex).Value(1);
if Items_List(Player_Ship.Cargo(ItemIndex).ProtoIndex).Value
.Length >
1
and then
Items_List(Player_Ship.Cargo(ItemIndex).ProtoIndex).Value(2) /=
0 then
UpdateMorale
(Player_Ship, I,
Items_List(Player_Ship.Cargo(ItemIndex).ProtoIndex).Value
(2));
end if;
UpdateCargo
(Player_Ship, Player_Ship.Cargo.Element(ItemIndex).ProtoIndex,
-1);
return ConsumeValue;
end if;
ItemIndex :=
FindItem
(Inventory => Player_Ship.Crew(I).Inventory,
ItemType => ItemType);
if ItemIndex > 0 then
ConsumeValue :=
Items_List(Player_Ship.Crew(I).Inventory(ItemIndex).ProtoIndex)
.Value
(1);
if Items_List(Player_Ship.Cargo(ItemIndex).ProtoIndex).Value(2) /=
0 then
UpdateMorale
(Player_Ship, I,
Items_List(Player_Ship.Cargo(ItemIndex).ProtoIndex).Value
(2));
end if;
UpdateInventory
(MemberIndex => I, Amount => -1, InventoryIndex => ItemIndex);
return ConsumeValue;
end if;
return 0;
end Consume;
procedure UpdateMember(Member: in out Member_Data) is
BackToWork: Boolean := True;
ConsumeResult: Natural := 0;
procedure NormalizeStat
(Stat: in out Integer; MaxValue: Positive := 100) is
begin
if Stat > MaxValue then
Stat := MaxValue;
elsif Stat < 0 then
Stat := 0;
end if;
end NormalizeStat;
begin
if Factions_List(Member.Faction).Flags.Contains
(To_Unbounded_String("nofatigue")) then
TiredLevel := 0;
end if;
if TiredLevel = 0 and Member.Order = Rest and
Member.PreviousOrder /= Rest then
if Member.PreviousOrder not in Repair | Clean
and then FindMember(Member.PreviousOrder) > 0 then
BackToWork := False;
end if;
if Member.PreviousOrder in Gunner | Craft then
Module_Loop :
for Module of Player_Ship.Modules loop
if (Member.PreviousOrder = Gunner and Module.M_Type = GUN)
and then (Module.Owner(1) in I | 0) then
BackToWork := True;
Module.Owner(1) := I;
exit Module_Loop;
elsif
(Member.PreviousOrder = Craft and Module.M_Type = WORKSHOP)
and then Module.Crafting_Index /=
Null_Unbounded_String then
Module_Is_Owner_Loop :
for Owner of Module.Owner loop
if Owner = I then
BackToWork := True;
Owner := I;
exit Module_Loop;
end if;
end loop Module_Is_Owner_Loop;
Module_Empty_Owner_Loop :
for Owner of Module.Owner loop
if Owner = 0 then
BackToWork := True;
Owner := I;
exit Module_Loop;
end if;
end loop Module_Empty_Owner_Loop;
end if;
end loop Module_Loop;
end if;
if BackToWork then
Member.Order := Member.PreviousOrder;
Member.OrderTime := 15;
AddMessage
(To_String(Member.Name) & " returns to work fully rested.",
OrderMessage, YELLOW);
UpdateMorale(Player_Ship, I, 1);
end if;
Member.PreviousOrder := Rest;
end if;
if TiredLevel >
(80 + Member.Attributes(Positive(Condition_Index)).Level) and
Member.Order /= Rest and not InCombat then
declare
CanRest: Boolean := True;
begin
if Member.Order = Boarding and HarpoonDuration = 0 and
Combat.Enemy.HarpoonDuration = 0 then
CanRest := False;
end if;
if CanRest then
Member.PreviousOrder := Member.Order;
Member.Order := Rest;
Member.OrderTime := 15;
if Member.Equipment(7) > 0 then
UpdateCargo
(Player_Ship,
Member.Inventory(Member.Equipment(7)).ProtoIndex, 1,
Member.Inventory(Member.Equipment(7)).Durability);
UpdateInventory
(MemberIndex => I, Amount => -1,
InventoryIndex => Member.Equipment(7));
Member.Equipment(7) := 0;
end if;
AddMessage
(To_String(Member.Name) &
" is too tired to work, they're going to rest.",
OrderMessage, YELLOW);
if FindCabin(I) = 0 then
Modules_Loop :
for Module of Player_Ship.Modules loop
if Module.M_Type = CABIN and Module.Durability > 0 then
Find_Cabin_Owner_Loop :
for Owner of Module.Owner loop
if Owner = 0 then
Owner := I;
AddMessage
(To_String(Member.Name) & " take " &
To_String(Module.Name) & " as own cabin.",
OtherMessage);
exit Modules_Loop;
end if;
end loop Find_Cabin_Owner_Loop;
end if;
end loop Modules_Loop;
end if;
else
AddMessage
(To_String(Member.Name) &
" is very tired but they can't go to rest.",
OrderMessage, RED);
UpdateMorale(Player_Ship, I, Get_Random(-5, -1));
end if;
end;
end if;
NormalizeStat(TiredLevel, 150);
Member.Tired := TiredLevel;
if HungerLevel > 80 then
Find_Food_Loop :
for FoodType of Factions_List(Member.Faction).FoodTypes loop
ConsumeResult := Consume(FoodType);
exit Find_Food_Loop when ConsumeResult > 0;
end loop Find_Food_Loop;
HungerLevel :=
(if HungerLevel - ConsumeResult < Skill_Range'First then
Skill_Range'First
else HungerLevel - ConsumeResult);
if ConsumeResult = 0 then
AddMessage
(To_String(Member.Name) &
" is hungry, but they can't find anything to eat.",
OtherMessage, RED);
UpdateMorale(Player_Ship, I, Get_Random(-10, -5));
end if;
end if;
NormalizeStat(HungerLevel);
Member.Hunger := HungerLevel;
if ThirstLevel > 40 then
Find_Drink_Loop :
for DrinksType of Factions_List(Member.Faction).DrinksTypes loop
ConsumeResult := Consume(DrinksType);
exit Find_Drink_Loop when ConsumeResult > 0;
end loop Find_Drink_Loop;
ThirstLevel :=
(if ThirstLevel - ConsumeResult < Skill_Range'First then
Skill_Range'First
else ThirstLevel - ConsumeResult);
if ConsumeResult = 0 then
AddMessage
(To_String(Member.Name) &
" is thirsty, but they can't find anything to drink.",
OtherMessage, RED);
UpdateMorale(Player_Ship, I, Get_Random(-20, -10));
end if;
end if;
NormalizeStat(ThirstLevel);
Member.Thirst := ThirstLevel;
NormalizeStat(HealthLevel);
Member.Health := HealthLevel;
if Member.Order not in Repair | Craft | Upgrading then
Member.OrderTime := OrderTime;
end if;
if Member.Skills.Length = 0 then
Member.ContractLength := Member.ContractLength - Minutes;
if Member.ContractLength < 0 then
Member.ContractLength := 0;
end if;
end if;
end UpdateMember;
begin
I := Player_Ship.Crew.First_Index;
Update_Crew_Loop :
while I <= Player_Ship.Crew.Last_Index loop
CurrentMinutes := Minutes;
OrderTime := Player_Ship.Crew(I).OrderTime;
Times := 0;
Update_Current_Minutes_Loop :
while CurrentMinutes > 0 loop
if CurrentMinutes >= OrderTime then
CurrentMinutes := CurrentMinutes - OrderTime;
Times := Times + 1;
OrderTime := 15;
else
OrderTime := OrderTime - CurrentMinutes;
CurrentMinutes := 0;
end if;
end loop Update_Current_Minutes_Loop;
HealthLevel := Player_Ship.Crew(I).Health;
HungerLevel := Player_Ship.Crew(I).Hunger;
ThirstLevel := Player_Ship.Crew(I).Thirst;
TiredLevel := Player_Ship.Crew(I).Tired;
if Times = 0 then
goto End_Of_Loop;
end if;
if Player_Ship.Crew(I).Order = Rest then
CabinIndex := FindCabin(I);
RestAmount := 0;
if Player_Ship.Crew(I).Tired > 0 then
if CabinIndex > 0 then
Damage :=
1.0 -
Damage_Factor
(Float(Player_Ship.Modules(CabinIndex).Durability) /
Float(Player_Ship.Modules(CabinIndex).Max_Durability));
RestAmount :=
Player_Ship.Modules(CabinIndex).Cleanliness -
Natural
(Float(Player_Ship.Modules(CabinIndex).Cleanliness) *
Float(Damage));
if RestAmount = 0 then
RestAmount := 1;
end if;
TiredLevel := TiredLevel - (Times * RestAmount);
else
TiredLevel := TiredLevel - Times;
end if;
if TiredLevel < 0 then
TiredLevel := 0;
end if;
end if;
if not Factions_List(Player_Ship.Crew(I).Faction).Flags.Contains
(To_Unbounded_String("nofatigue")) and
(HealthLevel in 1 .. 99) and CabinIndex > 0 then
HealthLevel := HealthLevel + Times;
if HealthLevel > 100 then
HealthLevel := 100;
end if;
end if;
if Player_Ship.Crew(I).Morale(1) < 50 then
UpdateMorale(Player_Ship, I, (Times + RestAmount));
if Player_Ship.Crew(I).Morale(1) > 50 then
Player_Ship.Crew(I).Morale := (50, 0);
end if;
end if;
else
if Player_Ship.Crew(I).Order /= Talk then
TiredLevel := TiredLevel + Times;
end if;
if TiredLevel >
(100 +
Player_Ship.Crew(I).Attributes(Positive(Condition_Index))
.Level) then
TiredLevel :=
(100 +
Player_Ship.Crew(I).Attributes(Positive(Condition_Index))
.Level);
end if;
if TiredLevel >=
(50 +
Player_Ship.Crew(I).Attributes(Positive(Condition_Index))
.Level) then
UpdateMorale(Player_Ship, I, ((Times / 5) * (-1)));
end if;
case Player_Ship.Crew(I).Order is
when Pilot =>
if Player_Ship.Speed /= DOCKED then
GainExp(Times, Piloting_Skill, I);
else
TiredLevel := Player_Ship.Crew(I).Tired;
end if;
when Engineer =>
if Player_Ship.Speed /= DOCKED then
GainExp(Times, Engineering_Skill, I);
else
TiredLevel := Player_Ship.Crew(I).Tired;
end if;
when Gunner =>
if Player_Ship.Speed = DOCKED then
TiredLevel := Player_Ship.Crew(I).Tired;
end if;
when Heal =>
HaveMedicalRoom := False;
Heal_Module_Loop :
for Module of Player_Ship.Modules loop
if Modules_List(Module.Proto_Index).MType =
MEDICAL_ROOM and
Module.Durability > 0 and Module.Owner.Contains(I) then
HaveMedicalRoom := True;
exit Heal_Module_Loop;
end if;
end loop Heal_Module_Loop;
Heal_Loop :
for Member of Player_Ship.Crew loop
if Member.Name /= Player_Ship.Crew(I).Name and
Member.Health < 100 then
HealAmount :=
Times *
(GetSkillLevel
(Player_Ship.Crew(I),
Factions_List(Member.Faction).HealingSkill) /
20);
if HealAmount < Times then
HealAmount := Times;
end if;
if not HaveMedicalRoom then
HealAmount := HealAmount / 2;
end if;
if HealAmount > 0 then
HealAmount := HealAmount * (-1);
ToolIndex :=
FindItem
(Inventory => Player_Ship.Cargo,
ItemType =>
Factions_List(Member.Faction).HealingTools);
if ToolIndex > 0 then
HealAmount :=
(if
Player_Ship.Cargo(ToolIndex).Amount <
abs (HealAmount)
then Player_Ship.Cargo(ToolIndex).Amount
else abs (HealAmount));
UpdateCargo
(Ship => Player_Ship, Amount => -(HealAmount),
CargoIndex => ToolIndex);
else
ToolIndex :=
FindItem
(Inventory => Player_Ship.Crew(I).Inventory,
ItemType =>
Factions_List(Member.Faction)
.HealingTools);
if ToolIndex > 0 then
HealAmount :=
(if
Player_Ship.Crew(I).Inventory(ToolIndex)
.Amount <
abs (HealAmount)
then
Player_Ship.Crew(I).Inventory(ToolIndex)
.Amount
else abs (HealAmount));
UpdateInventory
(MemberIndex => I, Amount => -(HealAmount),
InventoryIndex => ToolIndex);
end if;
end if;
end if;
if HealAmount > 0 then
Heal_Crew_Loop :
for J in Player_Ship.Crew.Iterate loop
if Player_Ship.Crew(J).Health < 100 and
Crew_Container.To_Index(J) /= I then
Player_Ship.Crew(J).Health :=
(if
Player_Ship.Crew(J).Health + HealAmount >
Skill_Range'Last
then Skill_Range'Last
else Player_Ship.Crew(J).Health +
HealAmount);
AddMessage
(To_String(Player_Ship.Crew(I).Name) &
" healed " &
To_String(Player_Ship.Crew(J).Name) &
" a bit.",
OrderMessage);
GainExp
(Times,
Factions_List(Member.Faction).HealingSkill,
I);
exit Heal_Crew_Loop;
end if;
end loop Heal_Crew_Loop;
else
if ToolIndex = 0 then
AddMessage
("You don't have any " &
To_String
(Factions_List(Member.Faction)
.HealingTools) &
" to continue healing the wounded " &
To_String(Member.Name) & ".",
OrderMessage, RED);
else
AddMessage
(To_String(Player_Ship.Crew(I).Name) &
" is not enough experienced to heal " &
To_String(Member.Name) &
" in that amount of time.",
OrderMessage, RED);
end if;
end if;
end if;
end loop Heal_Loop;
HealAmount := 1;
Update_Heal_Amount_Loop :
for J in Player_Ship.Crew.Iterate loop
if Player_Ship.Crew(J).Health < 100 and
Crew_Container.To_Index(J) /= I then
HealAmount := 0;
ToolIndex :=
FindItem
(Inventory => Player_Ship.Cargo,
ItemType =>
Factions_List(Player_Ship.Crew(J).Faction)
.HealingTools);
if ToolIndex = 0 then
ToolIndex :=
FindItem
(Inventory => Player_Ship.Crew(I).Inventory,
ItemType =>
Factions_List(Player_Ship.Crew(J).Faction)
.HealingTools);
if ToolIndex = 0 then
HealAmount := -1;
end if;
end if;
exit Update_Heal_Amount_Loop;
end if;
end loop Update_Heal_Amount_Loop;
if HealAmount > 0 then
AddMessage
(To_String(Player_Ship.Crew(I).Name) &
" finished healing the wounded.",
OrderMessage, GREEN);
end if;
if HealAmount /= 0 then
GiveOrders(Player_Ship, I, Rest);
end if;
when Clean =>
ToolIndex := FindTools(I, Cleaning_Tools, Clean);
NeedCleaning := False;
if ToolIndex > 0 then
Update_Clean_Tools_Loop :
for Module of Player_Ship.Modules loop
if Module.M_Type = CABIN
and then Module.Cleanliness < Module.Quality then
Module.Cleanliness :=
(if Module.Cleanliness + Times > Module.Quality
then Module.Quality
else Module.Cleanliness + Times);
DamageItem
(Inventory => Player_Ship.Crew(I).Inventory,
ItemIndex => ToolIndex, MemberIndex => I);
exit Update_Clean_Tools_Loop;
end if;
end loop Update_Clean_Tools_Loop;
Check_Dirty_Modules_Loop :
for Module of Player_Ship.Modules loop
if Module.M_Type = CABIN
and then Module.Cleanliness < Module.Quality then
NeedCleaning := True;
exit Check_Dirty_Modules_Loop;
end if;
end loop Check_Dirty_Modules_Loop;
end if;
if not NeedCleaning then
if ToolIndex = 0 then
AddMessage
("You can't continue cleaning the ship because you don't have any cleaning tools.",
OrderMessage, RED);
end if;
Remove_Clean_Order_Loop :
for J in Player_Ship.Crew.Iterate loop
if Player_Ship.Crew(J).Order = Clean then
GiveOrders
(Player_Ship, Crew_Container.To_Index(J), Rest);
end if;
end loop Remove_Clean_Order_Loop;
end if;
when Talk =>
if SkyMap(Player_Ship.Sky_X, Player_Ship.Sky_Y).BaseIndex =
0 then
GiveOrders(Player_Ship, I, Rest);
end if;
when Train =>
Modules_Loop :
for Module of Player_Ship.Modules loop
if Module.M_Type = TRAINING_ROOM then
for Owner of Module.Owner loop
if Owner = I then
SkillIndex := Module.Trained_Skill;
exit Modules_Loop;
end if;
end loop;
end if;
end loop Modules_Loop;
if SkillsData_Container.Element(Skills_List, SkillIndex)
.Tool /=
Null_Bounded_String then
ToolIndex :=
FindTools
(I,
To_Unbounded_String
(To_String
(SkillsData_Container.Element
(Skills_List, SkillIndex)
.Tool)),
Train, GetTrainingToolQuality(I, SkillIndex));
if ToolIndex > 0 then
Update_Train_Tool_Loop :
for J in 1 .. Times loop
GainExp(Get_Random(1, 5), SkillIndex, I);
DamageItem
(Inventory => Player_Ship.Crew(I).Inventory,
ItemIndex => ToolIndex, MemberIndex => I);
ToolIndex :=
FindTools
(I,
To_Unbounded_String
(To_String
(SkillsData_Container.Element
(Skills_List, SkillIndex)
.Tool)),
Train);
exit Update_Train_Tool_Loop when ToolIndex = 0;
end loop Update_Train_Tool_Loop;
AddMessage
(To_String(Player_Ship.Crew(I).Name) &
" trained a little " &
To_String
(SkillsData_Container.Element
(Skills_List, SkillIndex)
.Name) &
".",
OrderMessage);
end if;
if ToolIndex = 0 then
AddMessage
(To_String(Player_Ship.Crew(I).Name) &
" can't continue training because they don't have the proper tools.",
OrderMessage, RED);
GiveOrders(Player_Ship, I, Rest);
end if;
end if;
when others =>
null;
end case;
end if;
<<End_Of_Loop>>
if TiredPoints > 0 then
if Factions_List(Player_Ship.Crew(I).Faction).FoodTypes.Length >
0 then
HungerLevel :=
(if HungerLevel + TiredPoints > Skill_Range'Last then
Skill_Range'Last
else HungerLevel + TiredPoints);
if Player_Ship.Crew(I).Hunger = Skill_Range'Last then
HealthLevel := HealthLevel - TiredPoints;
UpdateMorale(Player_Ship, I, -(TiredPoints));
if HealthLevel < 1 then
HealthLevel := Skill_Range'First;
DeathReason := To_Unbounded_String("starvation");
end if;
end if;
end if;
if Factions_List(Player_Ship.Crew(I).Faction).DrinksTypes.Length >
0 then
ThirstLevel :=
(if ThirstLevel + TiredPoints > Skill_Range'Last then
Skill_Range'Last
else ThirstLevel + TiredPoints);
if Player_Ship.Crew(I).Thirst = Skill_Range'Last then
HealthLevel := HealthLevel - TiredPoints;
UpdateMorale(Player_Ship, I, -(TiredPoints));
if HealthLevel < 1 then
HealthLevel := Skill_Range'First;
DeathReason := To_Unbounded_String("dehydration");
end if;
end if;
end if;
if HealthLevel = Skill_Range'First then
if DeathReason = Null_Unbounded_String then
DeathReason := To_Unbounded_String("debugging");
end if;
Death(I, DeathReason, Player_Ship);
exit Update_Crew_Loop when I = 1;
end if;
end if;
if HealthLevel > Skill_Range'First then
Player_Ship.Crew.Update_Element
(Index => I, Process => UpdateMember'Access);
I := I + 1;
end if;
end loop Update_Crew_Loop;
end UpdateCrew;
procedure WaitForRest is
CabinIndex: Modules_Container.Extended_Index := 0;
TimeNeeded, TempTimeNeeded: Natural := 0;
Damage: Damage_Factor := 0.0;
CabinBonus: Natural;
begin
Wait_For_Rest_Loop :
for I in Player_Ship.Crew.Iterate loop
if Player_Ship.Crew(I).Tired > 0 and
Player_Ship.Crew(I).Order = Rest then
CabinIndex := 0;
TempTimeNeeded := 0;
CabinIndex := FindCabin(Crew_Container.To_Index(I));
if CabinIndex > 0 then
Damage :=
1.0 -
Damage_Factor
(Float(Player_Ship.Modules(CabinIndex).Durability) /
Float(Player_Ship.Modules(CabinIndex).Max_Durability));
CabinBonus :=
Player_Ship.Modules(CabinIndex).Cleanliness -
Natural
(Float(Player_Ship.Modules(CabinIndex).Cleanliness) *
Float(Damage));
if CabinBonus = 0 then
CabinBonus := 1;
end if;
TempTimeNeeded := (Player_Ship.Crew(I).Tired / CabinBonus) * 15;
if TempTimeNeeded = 0 then
TempTimeNeeded := 15;
end if;
else
TempTimeNeeded := Player_Ship.Crew(I).Tired * 15;
end if;
TempTimeNeeded := TempTimeNeeded + 15;
if TempTimeNeeded > TimeNeeded then
TimeNeeded := TempTimeNeeded;
end if;
end if;
end loop Wait_For_Rest_Loop;
if TimeNeeded > 0 then
Update_Game(TimeNeeded);
WaitInPlace(TimeNeeded);
end if;
end WaitForRest;
function GetSkillLevelName(SkillLevel: Skill_Range) return String is
begin
if Game_Settings.Show_Numbers then
return Positive'Image(SkillLevel);
end if;
case SkillLevel is
when 0 =>
return "Untrained";
when 1 .. 10 =>
return "Beginner";
when 11 .. 20 =>
return "Novice";
when 21 .. 30 =>
return "Apprentice";
when 31 .. 40 =>
return "Practitioner";
when 41 .. 50 =>
return "Competent";
when 51 .. 60 =>
return "Respected";
when 61 .. 70 =>
return "Renowned";
when 71 .. 80 =>
return "Master";
when 81 .. 90 =>
return "Grand-Master";
when 91 .. 99 =>
return "Legendary";
when others =>
return "Ultimate";
end case;
end GetSkillLevelName;
function GetAttributeLevelName(AttributeLevel: Positive) return String is
begin
if Game_Settings.Show_Numbers then
return Positive'Image(AttributeLevel);
end if;
case AttributeLevel is
when 1 .. 5 =>
return "Very low";
when 6 .. 10 =>
return "Low";
when 11 .. 15 =>
return "Below average";
when 16 .. 30 =>
return "Average";
when 31 .. 35 =>
return "Above average";
when 36 .. 40 =>
return "High";
when 41 .. 49 =>
return "Very high";
when others =>
return "Outstanding";
end case;
end GetAttributeLevelName;
procedure DailyPayment is
MoneyIndex2: constant Inventory_Container.Extended_Index :=
FindItem(Player_Ship.Cargo, Money_Index);
PayMessage: Unbounded_String;
MemberIndex: Crew_Container.Extended_Index;
HaveMoney: Boolean := True;
MoneyNeeded: Natural;
begin
MemberIndex := 1;
Daily_Payment_Loop :
for Member of Player_Ship.Crew loop
if Member.Payment(1) > 0 then
if MoneyIndex2 = 0 and HaveMoney then
AddMessage
("You don't have any " & To_String(Money_Name) &
" to pay your crew members.",
TradeMessage, RED);
HaveMoney := False;
end if;
if HaveMoney then
if Player_Ship.Cargo(MoneyIndex2).Amount <
Member.Payment(1) then
MoneyNeeded := Player_Ship.Cargo(MoneyIndex2).Amount;
UpdateCargo
(Ship => Player_Ship, ProtoIndex => Money_Index,
Amount => (0 - MoneyNeeded));
AddMessage
("You don't have enough " & To_String(Money_Name) &
" to pay your crew members.",
TradeMessage, RED);
HaveMoney := False;
end if;
if HaveMoney then
UpdateCargo
(Ship => Player_Ship, CargoIndex => MoneyIndex2,
Amount => (0 - Member.Payment(1)));
PayMessage := To_Unbounded_String("You pay ") & Member.Name;
if Member.Gender = 'M' then
Append(PayMessage, " his ");
else
Append(PayMessage, " her ");
end if;
Append(PayMessage, "daily payment.");
AddMessage(To_String(PayMessage), TradeMessage);
UpdateMorale(Player_Ship, MemberIndex, Get_Random(1, 5));
end if;
end if;
if not HaveMoney then
UpdateMorale(Player_Ship, MemberIndex, Get_Random(-50, -10));
end if;
end if;
MemberIndex := MemberIndex + 1;
end loop Daily_Payment_Loop;
MemberIndex := 1;
Update_Contracts_Loop :
while MemberIndex <= Player_Ship.Crew.Last_Index loop
if Player_Ship.Crew(MemberIndex).ContractLength > 0 then
Player_Ship.Crew(MemberIndex).ContractLength :=
Player_Ship.Crew(MemberIndex).ContractLength - 1;
if Player_Ship.Crew(MemberIndex).ContractLength = 0 then
AddMessage
("Your contract with " &
To_String(Player_Ship.Crew(MemberIndex).Name) &
" has ended.",
TradeMessage, RED);
if Player_Ship.Speed /= DOCKED then
Player_Ship.Crew(MemberIndex).Orders := (others => 0);
GiveOrders(Player_Ship, MemberIndex, Rest);
else
DeleteMember(MemberIndex, Player_Ship);
Sky_Bases
(SkyMap(Player_Ship.Sky_X, Player_Ship.Sky_Y).BaseIndex)
.Population :=
Sky_Bases
(SkyMap(Player_Ship.Sky_X, Player_Ship.Sky_Y).BaseIndex)
.Population +
1;
MemberIndex := MemberIndex - 1;
end if;
end if;
end if;
MemberIndex := MemberIndex + 1;
end loop Update_Contracts_Loop;
end DailyPayment;
function GetTrainingToolQuality
(MemberIndex, SkillIndex: Positive) return Positive is
ToolQuality: Positive := 100;
begin
Skill_Loop :
for Skill of Player_Ship.Crew(MemberIndex).Skills loop
if Skill.Index = SkillIndex then
Tool_Quality_Loop :
for Quality of SkillsData_Container.Element
(Skills_List, SkillIndex)
.Tools_Quality loop
if Skill.Level <= Quality.Level then
ToolQuality := Quality.Quality;
exit Skill_Loop;
end if;
end loop Tool_Quality_Loop;
end if;
end loop Skill_Loop;
return ToolQuality;
end GetTrainingToolQuality;
end Crew;
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A S I S . S T A T E M E N T S --
-- --
-- B o d y --
-- --
-- Copyright (C) 1995-2011, Free Software Foundation, Inc. --
-- --
-- ASIS-for-GNAT is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 2, or (at your option) any later --
-- version. ASIS-for-GNAT is distributed in the hope that it will be use- --
-- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- --
-- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General --
-- Public License for more details. You should have received a copy of the --
-- GNU General Public License distributed with ASIS-for-GNAT; see file --
-- COPYING. If not, write to the Free Software Foundation, 51 Franklin --
-- Street, Fifth Floor, Boston, MA 02110-1301, USA. --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the --
-- Software Engineering Laboratory of the Swiss Federal Institute of --
-- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the --
-- Scientific Research Computer Center of Moscow State University (SRCC --
-- MSU), Russia, with funding partially provided by grants from the Swiss --
-- National Science Foundation and the Swiss Academy of Engineering --
-- Sciences. ASIS-for-GNAT is now maintained by AdaCore --
-- (http://www.adacore.com). --
-- --
------------------------------------------------------------------------------
with Asis.Declarations; use Asis.Declarations;
with Asis.Elements; use Asis.Elements;
with Asis.Errors; use Asis.Errors;
with Asis.Exceptions; use Asis.Exceptions;
with Asis.Expressions; use Asis.Expressions;
with Asis.Extensions; use Asis.Extensions;
with Asis.Set_Get; use Asis.Set_Get;
with A4G.A_Sem; use A4G.A_Sem;
with A4G.A_Sinput; use A4G.A_Sinput;
with A4G.Contt.UT; use A4G.Contt.UT;
with A4G.Mapping; use A4G.Mapping;
with A4G.Norm; use A4G.Norm;
with A4G.Vcheck; use A4G.Vcheck;
with A4G.Span_End; use A4G.Span_End;
with Atree; use Atree;
with Nlists; use Nlists;
with Sinfo; use Sinfo;
with Sinput; use Sinput;
package body Asis.Statements is
Package_Name : constant String := "Asis.Statements.";
---------------------------
-- ASIS 2005 Draft stuff --
---------------------------
------------------------
-- Associated_Message --
------------------------
function Associated_Message
(Statement : Asis.Statement)
return Asis.Expression
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
begin
Check_Validity (Statement, Package_Name & "Associated_Message");
if not (Arg_Kind = A_Raise_Statement) then
Raise_ASIS_Inappropriate_Element
(Diagnosis => Package_Name & "Associated_Message",
Wrong_Kind => Arg_Kind);
end if;
return Node_To_Element_New
(Node => Sinfo.Expression (Node (Statement)),
Starting_Element => Statement);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Outer_Call => Package_Name & "Associated_Message");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Associated_Message",
Ex => Ex,
Arg_Element => Statement);
end Associated_Message;
----------------------------------------
-- Extended_Return_Exception_Handlers --
----------------------------------------
function Extended_Return_Exception_Handlers
(Statement : Asis.Statement;
Include_Pragmas : Boolean := False)
return Asis.Exception_Handler_List
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Resilt_List : List_Id := No_List;
begin
Check_Validity
(Statement, Package_Name & "Extended_Return_Exception_Handlers");
if not (Arg_Kind = An_Extended_Return_Statement) then
Raise_ASIS_Inappropriate_Element
(Diagnosis => Package_Name & "Extended_Return_Exception_Handlers",
Wrong_Kind => Arg_Kind);
end if;
if Present (Handled_Statement_Sequence (Node (Statement))) then
Resilt_List :=
Exception_Handlers (Handled_Statement_Sequence (Node (Statement)));
end if;
return N_To_E_List_New
(List => Resilt_List,
Include_Pragmas => Include_Pragmas,
Starting_Element => Statement);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Outer_Call => Package_Name &
"Extended_Return_Exception_Handlers");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Extended_Return_Exception_Handlers",
Ex => Ex,
Arg_Element => Statement);
end Extended_Return_Exception_Handlers;
--------------------------------
-- Extended_Return_Statements --
--------------------------------
function Extended_Return_Statements
(Statement : Asis.Statement;
Include_Pragmas : Boolean := False)
return Asis.Statement_List
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Result_List : List_Id := No_List;
begin
Check_Validity (Statement, Package_Name & "Extended_Return_Statements");
if not (Arg_Kind = An_Extended_Return_Statement) then
Raise_ASIS_Inappropriate_Element
(Diagnosis => Package_Name & "Extended_Return_Statements",
Wrong_Kind => Arg_Kind);
end if;
if Present (Handled_Statement_Sequence (Node (Statement))) then
Result_List :=
Sinfo.Statements (Handled_Statement_Sequence (Node (Statement)));
end if;
return N_To_E_List_New (List => Result_List,
Include_Pragmas => Include_Pragmas,
Starting_Element => Statement);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Outer_Call => Package_Name & "Extended_Return_Statements");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Extended_Return_Statements",
Ex => Ex,
Arg_Element => Statement);
end Extended_Return_Statements;
-------------------------------
-- Return_Object_Declaration --
-------------------------------
function Return_Object_Declaration
(Statement : Asis.Statement)
return Asis.Declaration
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Result_Node : Node_Id;
begin
Check_Validity (Statement, Package_Name & "Return_Object_Declaration");
if not (Arg_Kind = An_Extended_Return_Statement) then
Raise_ASIS_Inappropriate_Element
(Diagnosis => Package_Name & "Return_Object_Declaration",
Wrong_Kind => Arg_Kind);
end if;
Result_Node := First (Return_Object_Declarations (Node (Statement)));
while Nkind (Result_Node) /= N_Object_Declaration loop
-- It may be some internal subtypes here
Result_Node := Next (Result_Node);
end loop;
return Node_To_Element_New (Node => Result_Node,
Starting_Element => Statement);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Outer_Call => Package_Name & "Return_Object_Declaration");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Return_Object_Declaration",
Ex => Ex,
Arg_Element => Statement);
end Return_Object_Declaration;
------------------------------------------------------------------------------
-------------------
-- Aborted_Tasks --
-------------------
function Aborted_Tasks
(Statement : Asis.Statement)
return Asis.Expression_List
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Arg_Node : Node_Id;
begin
Check_Validity (Statement, Package_Name & "Aborted_Tasks");
if not (Arg_Kind = An_Abort_Statement) then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Aborted_Tasks",
Wrong_Kind => Arg_Kind);
end if;
Arg_Node := Node (Statement);
return N_To_E_List_New
(List => Names (Arg_Node),
Starting_Element => Statement);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Outer_Call => Package_Name & "Aborted_Tasks");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Aborted_Tasks",
Ex => Ex,
Arg_Element => Statement);
end Aborted_Tasks;
------------------------------------
-- Accept_Body_Exception_Handlers --
------------------------------------
function Accept_Body_Exception_Handlers
(Statement : Asis.Statement;
Include_Pragmas : Boolean := False)
return Asis.Exception_Handler_List
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Arg_Node : Node_Id;
Resilt_List : List_Id := No_List;
begin
Check_Validity (Statement,
Package_Name & "Accept_Body_Exception_Handlers");
if not (Arg_Kind = An_Accept_Statement) then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Accept_Body_Exception_Handlers",
Wrong_Kind => Arg_Kind);
end if;
Arg_Node := Node (Statement);
if Present (Handled_Statement_Sequence (Arg_Node)) then
Resilt_List :=
Exception_Handlers (Handled_Statement_Sequence (Arg_Node));
end if;
return N_To_E_List_New (List => Resilt_List,
Include_Pragmas => Include_Pragmas,
Starting_Element => Statement);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Bool_Par => Include_Pragmas,
Outer_Call => Package_Name & "Accept_Body_Exception_Handlers");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Accept_Body_Exception_Handlers",
Ex => Ex,
Arg_Element => Statement,
Bool_Par_ON => Include_Pragmas);
end Accept_Body_Exception_Handlers;
----------------------------
-- Accept_Body_Statements --
----------------------------
function Accept_Body_Statements
(Statement : Asis.Statement;
Include_Pragmas : Boolean := False)
return Asis.Statement_List
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Arg_Node : Node_Id;
Resilt_List : List_Id := No_List;
begin
Check_Validity (Statement, Package_Name & "Accept_Body_Statements");
if not (Arg_Kind = An_Accept_Statement) then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Accept_Body_Statements",
Wrong_Kind => Arg_Kind);
end if;
Arg_Node := Node (Statement);
if Present (Handled_Statement_Sequence (Arg_Node)) then
Resilt_List :=
Sinfo.Statements (Handled_Statement_Sequence (Arg_Node));
end if;
return N_To_E_List_New
(List => Resilt_List,
Include_Pragmas => Include_Pragmas,
Starting_Element => Statement);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Bool_Par => Include_Pragmas,
Outer_Call => Package_Name & "Accept_Body_Statements");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Accept_Body_Statements",
Ex => Ex,
Arg_Element => Statement,
Bool_Par_ON => Include_Pragmas);
end Accept_Body_Statements;
------------------------------
-- Accept_Entry_Direct_Name --
------------------------------
function Accept_Entry_Direct_Name
(Statement : Asis.Statement)
return Asis.Name
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Arg_Node : Node_Id;
begin
Check_Validity (Statement, Package_Name & "Accept_Entry_Direct_Name");
if not (Arg_Kind = An_Accept_Statement) then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Accept_Entry_Direct_Name",
Wrong_Kind => Arg_Kind);
end if;
Arg_Node := Node (Statement);
return Node_To_Element_New (
Node => Entry_Direct_Name (Arg_Node),
Internal_Kind => An_Identifier,
Starting_Element => Statement);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Outer_Call => Package_Name & "Accept_Entry_Direct_Name");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Accept_Entry_Direct_Name",
Ex => Ex,
Arg_Element => Statement);
end Accept_Entry_Direct_Name;
------------------------
-- Accept_Entry_Index --
------------------------
function Accept_Entry_Index
(Statement : Asis.Statement)
return Asis.Expression
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Arg_Node : Node_Id;
Result_Node : Node_Id;
begin
Check_Validity (Statement, Package_Name & "Accept_Entry_Index");
if not (Arg_Kind = An_Accept_Statement) then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Accept_Entry_Index",
Wrong_Kind => Arg_Kind);
end if;
Arg_Node := Node (Statement);
Result_Node := Entry_Index (Arg_Node);
if No (Result_Node) then
return Nil_Element;
else
return Node_To_Element_New (Node => Result_Node,
Starting_Element => Statement);
end if;
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Outer_Call => Package_Name & "Accept_Entry_Index");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Accept_Entry_Index",
Ex => Ex,
Arg_Element => Statement);
end Accept_Entry_Index;
-----------------------
-- Accept_Parameters --
-----------------------
function Accept_Parameters
(Statement : Asis.Statement)
return Asis.Parameter_Specification_List
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Arg_Node : Node_Id;
begin
Check_Validity (Statement, Package_Name & "Accept_Parameters");
if not (Arg_Kind = An_Accept_Statement) then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Accept_Parameters",
Wrong_Kind => Arg_Kind);
end if;
Arg_Node := Node (Statement);
return N_To_E_List_New
(List => Parameter_Specifications (Arg_Node),
Starting_Element => Statement,
Internal_Kind => A_Parameter_Specification);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Outer_Call => Package_Name & "Accept_Parameters");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Accept_Parameters",
Ex => Ex,
Arg_Element => Statement);
end Accept_Parameters;
---------------------------
-- Assignment_Expression --
---------------------------
function Assignment_Expression
(Statement : Asis.Statement)
return Asis.Expression
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Arg_Node : Node_Id;
begin
Check_Validity (Statement, Package_Name & "Assignment_Expression");
if not (Arg_Kind = An_Assignment_Statement) then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Assignment_Expression",
Wrong_Kind => Arg_Kind);
end if;
Arg_Node := Node (Statement);
return Node_To_Element_New (
Node => Sinfo.Expression (Arg_Node),
Starting_Element => Statement);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Outer_Call => Package_Name & "Assignment_Expression");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Assignment_Expression",
Ex => Ex,
Arg_Element => Statement);
end Assignment_Expression;
------------------------------
-- Assignment_Variable_Name --
------------------------------
function Assignment_Variable_Name
(Statement : Asis.Statement)
return Asis.Expression
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Arg_Node : Node_Id;
begin
Check_Validity (Statement, Package_Name & "Assignment_Variable_Name");
if not (Arg_Kind = An_Assignment_Statement) then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Assignment_Variable_Name",
Wrong_Kind => Arg_Kind);
end if;
Arg_Node := Node (Statement);
return Node_To_Element_New (
Node => Sinfo.Name (Arg_Node),
Starting_Element => Statement);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Outer_Call => Package_Name & "Assignment_Variable_Name");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Assignment_Variable_Name",
Ex => Ex,
Arg_Element => Statement);
end Assignment_Variable_Name;
-----------------------------
-- Block_Declarative_Items --
-----------------------------
function Block_Declarative_Items
(Statement : Asis.Statement;
Include_Pragmas : Boolean := False)
return Asis.Declarative_Item_List
is
Arg_El : Asis.Element;
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Arg_Node : Node_Id;
begin
Check_Validity (Statement, Package_Name & "Block_Declarative_Items");
if not (Arg_Kind = A_Block_Statement) then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Block_Declarative_Items",
Wrong_Kind => Arg_Kind);
end if;
Arg_Node := Node (Statement);
Arg_El := Statement;
if Special_Case (Arg_El) = A_Dummy_Block_Statement then
Set_Special_Case (Arg_El, Not_A_Special_Case);
end if;
return N_To_E_List_New
(List => Sinfo.Declarations (Arg_Node),
Include_Pragmas => Include_Pragmas,
Starting_Element => Arg_El);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Bool_Par => Include_Pragmas,
Outer_Call => Package_Name & "Block_Declarative_Items");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Block_Declarative_Items",
Ex => Ex,
Arg_Element => Statement,
Bool_Par_ON => Include_Pragmas);
end Block_Declarative_Items;
------------------------------
-- Block_Exception_Handlers --
------------------------------
function Block_Exception_Handlers
(Statement : Asis.Statement;
Include_Pragmas : Boolean := False)
return Asis.Exception_Handler_List
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Arg_Node : Node_Id;
Arg_El : Asis.Element;
begin
Check_Validity (Statement, Package_Name & "Block_Exception_Handlers");
if not (Arg_Kind = A_Block_Statement) then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Block_Exception_Handlers",
Wrong_Kind => Arg_Kind);
end if;
Arg_Node := Node (Statement);
if Special_Case (Statement) = A_Dummy_Block_Statement and then
No (Handled_Statement_Sequence (Arg_Node))
then
-- for the dummy block originated from the package_body_declaration
-- having no handled_sequence_of_statements on its own.
return Nil_Element_List;
end if;
Arg_El := Statement;
if Special_Case (Arg_El) = A_Dummy_Block_Statement then
Set_Special_Case (Arg_El, Not_A_Special_Case);
end if;
return N_To_E_List_New
(List =>
Exception_Handlers (Handled_Statement_Sequence (Arg_Node)),
Include_Pragmas => Include_Pragmas,
Starting_Element => Arg_El);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Bool_Par => Include_Pragmas,
Outer_Call => Package_Name & "Block_Exception_Handlers");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Block_Exception_Handlers",
Ex => Ex,
Arg_Element => Statement,
Bool_Par_ON => Include_Pragmas);
end Block_Exception_Handlers;
----------------------
-- Block_Statements --
----------------------
function Block_Statements
(Statement : Asis.Statement;
Include_Pragmas : Boolean := False)
return Asis.Statement_List
is
Arg_El : Asis.Element;
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Arg_Node : Node_Id;
begin
Check_Validity (Statement, Package_Name & "Block_Statements");
if not (Arg_Kind = A_Block_Statement) then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Block_Statements",
Wrong_Kind => Arg_Kind);
end if;
Arg_Node := Node (Statement);
Arg_El := Statement;
if Special_Case (Arg_El) = A_Dummy_Block_Statement then
Set_Special_Case (Arg_El, Not_A_Special_Case);
end if;
return N_To_E_List_New
(List =>
Sinfo.Statements (Handled_Statement_Sequence (Arg_Node)),
Include_Pragmas => Include_Pragmas,
Starting_Element => Arg_El);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Bool_Par => Include_Pragmas,
Outer_Call => Package_Name & "Block_Statements");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Block_Statements",
Ex => Ex,
Arg_Element => Statement,
Bool_Par_ON => Include_Pragmas);
end Block_Statements;
-------------------------------
-- Call_Statement_Parameters --
-------------------------------
function Call_Statement_Parameters
(Statement : Asis.Statement;
Normalized : Boolean := False)
return Asis.Association_List
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Arg_Node : Node_Id;
Res_Norm_Case : Normalization_Cases := Is_Not_Normalized;
Res_Node_List : List_Id;
begin
Check_Validity (Statement, Package_Name & "Call_Statement_Parameters");
Arg_Node := Node (Statement);
if (not (Arg_Kind = An_Entry_Call_Statement or else
Arg_Kind = A_Procedure_Call_Statement))
or else
(Normalized and then Nkind (Arg_Node) = N_Attribute_Reference)
then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Call_Statement_Parameters",
Wrong_Kind => Arg_Kind);
end if;
if Is_Prefix_Notation (Statement) then
Arg_Node := R_Node (Statement);
end if;
if Normalized then
Res_Norm_Case := Is_Normalized;
end if;
if Normalized and then
Nkind (Arg_Node) /= N_Attribute_Reference
then
if No (Parameter_Associations (Arg_Node))
or else
Is_Nil (Corresponding_Called_Entity (Statement))
then
return Nil_Element_List;
else
return Normalized_Param_Associations (Call_Elem => Statement);
end if;
else
if Nkind (Arg_Node) = N_Attribute_Reference then
-- call to 'Output, 'Read or 'Write
Res_Node_List := Sinfo.Expressions (Arg_Node);
else
Res_Node_List := Parameter_Associations (Arg_Node);
end if;
return N_To_E_List_New (List => Res_Node_List,
Internal_Kind => A_Parameter_Association,
Norm_Case => Res_Norm_Case,
Starting_Element => Statement);
end if;
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Bool_Par => Normalized,
Outer_Call => Package_Name & "Call_Statement_Parameters");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Call_Statement_Parameters",
Ex => Ex,
Arg_Element => Statement,
Bool_Par_ON => Normalized);
end Call_Statement_Parameters;
-----------------
-- Called_Name --
-----------------
function Called_Name
(Statement : Asis.Statement)
return Asis.Expression
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Arg_Node : Node_Id;
-- local variables needed for processing calls to 'Output, 'Read
-- and 'Write:
Result_Kind : Internal_Element_Kinds := Not_An_Element;
Result_Node : Node_Id;
begin
Check_Validity (Statement, Package_Name & "Called_Name");
if not (Arg_Kind = An_Entry_Call_Statement or else
Arg_Kind = A_Procedure_Call_Statement)
then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Called_Name",
Wrong_Kind => Arg_Kind);
end if;
if Is_Prefix_Notation (Statement) then
Arg_Node := R_Node (Statement);
else
Arg_Node := Node (Statement);
end if;
if Nkind (Arg_Node) = N_Attribute_Reference then
-- calls like T'Output (...); T'Read (...) and T'Write (...)
-- should be processed separately, and the result should
-- be built on the same node as argument
Result_Kind := Subprogram_Attribute_Kind (Arg_Node);
Result_Node := Arg_Node;
else
Result_Node := Sinfo.Name (Arg_Node);
end if;
if Is_Rewrite_Substitution (Result_Node)
and then
Nkind (Result_Node) = N_Explicit_Dereference
and then
Nkind (Prefix (Result_Node)) = N_Function_Call
then
-- Needed to process cases like F (1), where F - parameterless
-- function that returns access-to-subprogram result.
Result_Node := Prefix (Result_Node);
end if;
return Node_To_Element_New (
Starting_Element => Statement,
Node => Result_Node,
Internal_Kind => Result_Kind);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Outer_Call => Package_Name & "Called_Name");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Called_Name",
Ex => Ex,
Arg_Element => Statement);
end Called_Name;
---------------------
-- Case_Expression --
---------------------
function Case_Expression
(Statement : Asis.Statement)
return Asis.Expression
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Arg_Node : Node_Id;
begin
Check_Validity (Statement, Package_Name & "Case_Expression");
if not (Arg_Kind = A_Case_Statement or else
Arg_Kind = A_Case_Expression)
then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Case_Expression",
Wrong_Kind => Arg_Kind);
end if;
Arg_Node := Node (Statement);
return Node_To_Element_New
(Node => Sinfo.Expression (Arg_Node),
Starting_Element => Statement);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Outer_Call => Package_Name & "Case_Expression");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Case_Expression",
Ex => Ex,
Arg_Element => Statement);
end Case_Expression;
----------------------------------------
-- Case_Statement_Alternative_Choices --
----------------------------------------
function Case_Statement_Alternative_Choices
(Path : Asis.Path)
return Asis.Element_List
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Path);
Arg_Node : Node_Id;
begin
Check_Validity
(Path, Package_Name & "Case_Statement_Alternative_Choices");
if not (Arg_Kind = A_Case_Path) then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Case_Statement_Alternative_Choices",
Wrong_Kind => Arg_Kind);
end if;
Arg_Node := Node (Path);
return Discrete_Choice_Node_To_Element_List (
Choice_List => Discrete_Choices (Arg_Node),
Starting_Element => Path);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Path,
Outer_Call => Package_Name &
"Case_Statement_Alternative_Choices");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Case_Statement_Alternative_Choices",
Ex => Ex,
Arg_Element => Path);
end Case_Statement_Alternative_Choices;
-----------------------------------
-- Choice_Parameter_Specification --
-------------------------------------
function Choice_Parameter_Specification
(Handler : Asis.Exception_Handler)
return Asis.Declaration
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Handler);
Arg_Node : Node_Id;
Result_Node : Node_Id;
begin
Check_Validity
(Handler, Package_Name & "Choice_Parameter_Specification");
if not (Arg_Kind = An_Exception_Handler) then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Choice_Parameter_Specification",
Wrong_Kind => Arg_Kind);
end if;
Arg_Node := Node (Handler);
Result_Node := Choice_Parameter (Arg_Node);
if No (Result_Node) then
return Nil_Element;
else
return Node_To_Element_New (
Node => Result_Node,
Internal_Kind => A_Choice_Parameter_Specification,
Starting_Element => Handler);
end if;
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Handler,
Outer_Call => Package_Name & "Choice_Parameter_Specification");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Choice_Parameter_Specification",
Ex => Ex,
Arg_Element => Handler);
end Choice_Parameter_Specification;
--------------------------
-- Condition_Expression --
--------------------------
function Condition_Expression (Path : Asis.Path) return Asis.Expression is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Path);
Res_Node : Node_Id := Empty;
Arg_Node : Node_Id;
begin
Check_Validity (Path, Package_Name & "Condition_Expression");
if not (Arg_Kind = An_If_Path or else
Arg_Kind = An_Elsif_Path or else
Arg_Kind = An_If_Expression_Path or else
Arg_Kind = An_Elsif_Expression_Path)
then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Condition_Expression",
Wrong_Kind => Arg_Kind);
end if;
Arg_Node := R_Node (Path);
case Arg_Kind is
when An_If_Path |
An_Elsif_Path =>
Res_Node := Condition (Arg_Node);
when An_If_Expression_Path |
An_Elsif_Expression_Path =>
Res_Node := Prev (Arg_Node);
when others =>
null;
end case;
return Node_To_Element_New (Node => Res_Node,
Starting_Element => Path);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Path,
Outer_Call => Package_Name & "Condition_Expression");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Condition_Expression",
Ex => Ex,
Arg_Element => Path);
end Condition_Expression;
---------------------------------
-- Corresponding_Called_Entity --
---------------------------------
function Corresponding_Called_Entity
(Statement : Asis.Statement)
return Asis.Declaration
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
begin
Check_Validity (Statement, Package_Name & "Corresponding_Called_Entity");
if not (Arg_Kind = An_Entry_Call_Statement or else
Arg_Kind = A_Procedure_Call_Statement)
then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Corresponding_Called_Entity",
Wrong_Kind => Arg_Kind);
end if;
return Get_Corr_Called_Entity (Statement);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Outer_Call => Package_Name & "Corresponding_Called_Entity");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Corresponding_Called_Entity",
Ex => Ex,
Arg_Element => Statement);
end Corresponding_Called_Entity;
-----------------------------------------
-- Corresponding_Destination_Statement --
-----------------------------------------
function Corresponding_Destination_Statement
(Statement : Asis.Statement)
return Asis.Statement
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Arg_Node : Node_Id;
Res_Label : Node_Id;
Res_Stmt : Node_Id;
begin
Check_Validity
(Statement, Package_Name & "Corresponding_Destination_Statement");
if not (Arg_Kind = A_Goto_Statement) then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Corresponding_Destination_Statement",
Wrong_Kind => Arg_Kind);
end if;
Arg_Node := R_Node (Statement);
if Is_Rewrite_Substitution (Arg_Node)
and then
Nkind (Arg_Node) = N_Loop_Statement
and then
Nkind (Original_Node (Arg_Node)) = N_Goto_Statement
then
-- goto statement is rewritten into infinite loop
if not Is_Empty_List (Sinfo.Statements (Arg_Node)) then
Res_Stmt := First (Sinfo.Statements (Arg_Node));
else
-- Pathological case:
--
-- <<Junk>> goto Junk;
Res_Stmt := Arg_Node;
end if;
else
Arg_Node := Node (Statement);
Res_Label := Parent (Entity (Sinfo.Name (Arg_Node)));
-- this is N_Implicit_Label_Declaration node representing the
-- implicit declaration of the destination label
Res_Stmt := Label_Construct (Res_Label);
while not Is_Statement (Res_Stmt) loop
Res_Stmt := Next (Res_Stmt);
end loop;
-- if we are in the tree corresponding to a successful compiler
-- run, we shall for sure find a statement after any label!
end if;
return Node_To_Element_New (Node => Res_Stmt,
Starting_Element => Statement);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Outer_Call => Package_Name &
"Corresponding_Destination_Statement");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name &
"Corresponding_Destination_Statement",
Ex => Ex,
Arg_Element => Statement);
end Corresponding_Destination_Statement;
-------------------------
-- Corresponding_Entry --
-------------------------
function Corresponding_Entry
(Statement : Asis.Statement)
return Asis.Declaration
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Arg_Node : Node_Id;
Res_Entry_Dcl : Node_Id;
Result_Unit : Compilation_Unit;
begin
Check_Validity (Statement, Package_Name & "Corresponding_Entry");
if not (Arg_Kind = An_Accept_Statement) then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Corresponding_Entry",
Wrong_Kind => Arg_Kind);
end if;
Arg_Node := Node (Statement);
Res_Entry_Dcl := Parent (Entity (Entry_Direct_Name (Arg_Node)));
Result_Unit := Enclosing_Unit
(Encl_Cont_Id (Statement), Res_Entry_Dcl);
return Node_To_Element_New (Node => Res_Entry_Dcl,
In_Unit => Result_Unit);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Outer_Call => Package_Name & "Corresponding_Entry");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Corresponding_Entry",
Ex => Ex,
Arg_Element => Statement);
end Corresponding_Entry;
-------------------------------
-- Corresponding_Loop_Exited --
-------------------------------
function Corresponding_Loop_Exited
(Statement : Asis.Statement)
return Asis.Statement
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Arg_Node : Node_Id;
Res_Loop : Node_Id;
Loop_Name : Node_Id;
begin
Check_Validity (Statement, Package_Name & "Corresponding_Loop_Exited");
if not (Arg_Kind = An_Exit_Statement) then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Corresponding_Loop_Exited",
Wrong_Kind => Arg_Kind);
end if;
Arg_Node := Node (Statement);
Loop_Name := Sinfo.Name (Arg_Node);
if Present (Loop_Name) then
-- we simply jump to the result loop:
Loop_Name := Parent (Entity (Loop_Name));
-- here we are in the implicit declaration of the loop name
Res_Loop := Label_Construct (Loop_Name);
else
-- here we have to traverse the tree up to the first enclosing
-- loop statement
Res_Loop := Parent (Arg_Node);
while Nkind (Res_Loop) /= N_Loop_Statement loop
Res_Loop := Parent (Res_Loop);
end loop;
end if;
return Node_To_Element_New (Node => Res_Loop,
Starting_Element => Statement);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Outer_Call => Package_Name & "Corresponding_Loop_Exited");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Corresponding_Loop_Exited",
Ex => Ex,
Arg_Element => Statement);
end Corresponding_Loop_Exited;
----------------------
-- Delay_Expression --
----------------------
function Delay_Expression
(Statement : Asis.Statement)
return Asis.Expression
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Arg_Node : Node_Id;
begin
Check_Validity (Statement, Package_Name & "Delay_Expression");
if not (Arg_Kind = A_Delay_Until_Statement
or else
Arg_Kind = A_Delay_Relative_Statement)
then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Delay_Expression",
Wrong_Kind => Arg_Kind);
end if;
Arg_Node := Node (Statement);
return Node_To_Element_New
(Node => Sinfo.Expression (Arg_Node),
Starting_Element => Statement);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Outer_Call => Package_Name & "Delay_Expression");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Delay_Expression",
Ex => Ex,
Arg_Element => Statement);
end Delay_Expression;
-----------------------
-- Exception_Choices --
-----------------------
function Exception_Choices
(Handler : Asis.Exception_Handler)
return Asis.Element_List
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Handler);
Arg_Node : Node_Id;
begin
Check_Validity (Handler, Package_Name & "Exception_Choices");
if not (Arg_Kind = An_Exception_Handler) then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Exception_Choices",
Wrong_Kind => Arg_Kind);
end if;
Arg_Node := Node (Handler);
return N_To_E_List_New
(List => Exception_Choices (Arg_Node),
Starting_Element => Handler);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Handler,
Outer_Call => Package_Name & "Exception_Choices");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Exception_Choices",
Ex => Ex,
Arg_Element => Handler);
end Exception_Choices;
--------------------
-- Exit_Condition --
--------------------
function Exit_Condition
(Statement : Asis.Statement)
return Asis.Expression
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Arg_Node : Node_Id;
Result_Node : Node_Id;
begin
Check_Validity (Statement, Package_Name & "Exit_Condition");
if not (Arg_Kind = An_Exit_Statement) then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Exit_Loop_Name",
Wrong_Kind => Arg_Kind);
end if;
Arg_Node := Node (Statement);
Result_Node := Condition (Arg_Node);
if No (Result_Node) then
return Nil_Element;
else
return Node_To_Element_New (Node => Result_Node,
Starting_Element => Statement);
end if;
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Outer_Call => Package_Name & "Exit_Condition");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Exit_Condition",
Ex => Ex,
Arg_Element => Statement);
end Exit_Condition;
--------------------
-- Exit_Loop_Name --
--------------------
function Exit_Loop_Name
(Statement : Asis.Statement)
return Asis.Expression
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Arg_Node : Node_Id;
Result_Node : Node_Id;
begin
Check_Validity (Statement, Package_Name & "Exit_Loop_Name");
if not (Arg_Kind = An_Exit_Statement) then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Exit_Loop_Name",
Wrong_Kind => Arg_Kind);
end if;
Arg_Node := Node (Statement);
Result_Node := Sinfo.Name (Arg_Node);
if No (Result_Node) then
return Nil_Element;
else
return Node_To_Element_New (Node => Result_Node,
Starting_Element => Statement);
end if;
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Outer_Call => Package_Name & "Exit_Loop_Name");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Exit_Loop_Name",
Ex => Ex,
Arg_Element => Statement);
end Exit_Loop_Name;
--------------------------------------
-- For_Loop_Parameter_Specification --
--------------------------------------
function For_Loop_Parameter_Specification
(Statement : Asis.Statement)
return Asis.Declaration
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Res_Node : Node_Id;
Res_Kind : Internal_Element_Kinds := Not_An_Element;
begin
Check_Validity
(Statement, Package_Name & "For_Loop_Parameter_Specification");
if not (Arg_Kind = A_For_Loop_Statement) then
Raise_ASIS_Inappropriate_Element
(Package_Name & "For_Loop_Parameter_Specification",
Wrong_Kind => Arg_Kind);
end if;
Res_Node := Iteration_Scheme (Node (Statement));
if Present (Iterator_Specification (Res_Node)) then
Res_Node := Iterator_Specification (Res_Node);
if Of_Present (Res_Node) then
Res_Kind := An_Element_Iterator_Specification;
else
Res_Kind := A_Generalized_Iterator_Specification;
end if;
elsif Present (Loop_Parameter_Specification (Res_Node)) then
Res_Node := Loop_Parameter_Specification (Res_Node);
Res_Kind := A_Loop_Parameter_Specification;
else
null;
pragma Assert (False);
end if;
return Node_To_Element_New (
Node => Res_Node,
Internal_Kind => Res_Kind,
Starting_Element => Statement);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Outer_Call => Package_Name &
"For_Loop_Parameter_Specification");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "For_Loop_Parameter_Specification",
Ex => Ex,
Arg_Element => Statement);
end For_Loop_Parameter_Specification;
----------------
-- Goto_Label --
----------------
function Goto_Label
(Statement : Asis.Statement)
return Asis.Expression
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Arg_Node : Node_Id;
begin
Check_Validity (Statement, Package_Name & "Goto_Label");
if not (Arg_Kind = A_Goto_Statement) then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Goto_Label",
Wrong_Kind => Arg_Kind);
end if;
Arg_Node := Node (Statement);
return Node_To_Element_New (Node => Sinfo.Name (Arg_Node),
Starting_Element => Statement);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Outer_Call => Package_Name & "Goto_Label");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Goto_Label",
Ex => Ex,
Arg_Element => Statement);
end Goto_Label;
-----------
-- Guard --
-----------
function Guard (Path : Asis.Path) return Asis.Expression is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Path);
Arg_Node : Node_Id;
Result_Node : Node_Id;
begin
Check_Validity (Path, Package_Name & "Guard");
if not (Arg_Kind = A_Select_Path or else
Arg_Kind = An_Or_Path)
then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Guard",
Wrong_Kind => Arg_Kind);
end if;
if not (Nkind (Parent (R_Node (Path))) = N_Selective_Accept) then
return Nil_Element;
end if;
Arg_Node := Node (Path);
Result_Node := Condition (Arg_Node);
if No (Result_Node) then
return Nil_Element;
else
return Node_To_Element_New (Node => Result_Node,
Starting_Element => Path);
end if;
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Path,
Outer_Call => Package_Name & "Guard");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Guard",
Ex => Ex,
Arg_Element => Path);
end Guard;
------------------------
-- Handler_Statements --
------------------------
function Handler_Statements
(Handler : Asis.Exception_Handler;
Include_Pragmas : Boolean := False)
return Asis.Statement_List
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Handler);
Arg_Node : Node_Id;
begin
Check_Validity (Handler, Package_Name & "Handler_Statements");
if not (Arg_Kind = An_Exception_Handler) then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Handler_Statements",
Wrong_Kind => Arg_Kind);
end if;
Arg_Node := Node (Handler);
return N_To_E_List_New
(List => Sinfo.Statements (Arg_Node),
Include_Pragmas => Include_Pragmas,
Starting_Element => Handler);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Handler,
Bool_Par => Include_Pragmas,
Outer_Call => Package_Name & "Handler_Statements");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Handler_Statements",
Ex => Ex,
Arg_Element => Handler,
Bool_Par_ON => Include_Pragmas);
end Handler_Statements;
--------------------------------------
-- Is_Call_On_Dispatching_Operation --
--------------------------------------
function Is_Call_On_Dispatching_Operation
(Call : Asis.Element)
return Boolean
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Call);
Called_Entity : Asis.Element;
begin
-- Just the first version, should be tested more carefully!
-- Is currently implemented as a secondary query based on
-- some queries from Asis.Extensions.
-- ??? !!!
-- Still depends on partially implemented queries from
-- Asis.Extensions
Check_Validity (Call, Package_Name & "Is_Call_On_Dispatching_Operation");
if not (Arg_Kind = A_Function_Call or else
Arg_Kind = A_Procedure_Call_Statement)
then
return False;
end if;
if Arg_Kind = A_Function_Call then
Called_Entity := Corresponding_Called_Function (Call);
else
Called_Entity := Corresponding_Called_Entity (Call);
end if;
if Is_Nil (Called_Entity) or else
(not Is_Dispatching_Operation (Called_Entity))
then
return False;
else
return True;
end if;
-- Owning_Type := Primary_Owner (Called_Entity);
-- Owning_Type := Type_Declaration_View (Owning_Type);
-- Owning_Type_Kind := Int_Kind (Owning_Type);
-- return
-- (Owning_Type_Kind = A_Tagged_Private_Type_Definition or else
-- Owning_Type_Kind = A_Private_Extension_Definition or else
-- Owning_Type_Kind = A_Derived_Record_Extension_Definition or else
-- Owning_Type_Kind = A_Tagged_Record_Type_Definition);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Call,
Outer_Call => Package_Name &
"Is_Call_On_Dispatching_Operation");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Is_Call_On_Dispatching_Operation",
Ex => Ex,
Arg_Element => Call);
end Is_Call_On_Dispatching_Operation;
----------------------
-- Is_Declare_Block --
----------------------
function Is_Declare_Block
(Statement : Asis.Statement)
return Boolean
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Arg_Node : Node_Id;
First_Letter : Character;
-- the first character of the statement, should be either
-- B[egin] or D[eclare]
begin
-- If the argument represents the dummy block statement created by
-- the Asis_Declarations.Body_Block_Statement (obsolescent!)
-- function, the result will be True if and only if the
-- corresponding body has any declarative item on its own.
Check_Validity (Statement, Package_Name & "Is_Declare_Block");
if not (Arg_Kind = A_Block_Statement) then
return False;
end if;
Arg_Node := Node (Statement);
if Special_Case (Statement) = A_Dummy_Block_Statement then
if Present (Sinfo.Declarations (Arg_Node)) then
return True;
else
return False;
end if;
else
-- a "normal" block statement: here we should be more accurate, and
-- we cannot rely on "Present (Declarations (Arg_Node))" approach
-- because of the implicit label declarations
First_Letter := Source_Text (Get_Source_File_Index (
Sloc (Arg_Node))) -- the unit's text buffer
(Sloc (Arg_Node));
case First_Letter is
when 'b' | 'B' =>
return False;
when 'd' | 'D' =>
return True;
when others =>
-- Unexpected beginning of the block statement
raise Internal_Implementation_Error;
end case;
end if;
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Outer_Call => Package_Name & "Is_Declare_Block");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Is_Declare_Block",
Ex => Ex,
Arg_Element => Statement);
end Is_Declare_Block;
-------------------------
-- Is_Dispatching_Call --
-------------------------
function Is_Dispatching_Call (Call : Asis.Element) return Boolean is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Call);
Arg_Node : Node_Id := R_Node (Call);
begin
Check_Validity (Call, Package_Name & "Is_Dispatching_Call");
if not (Arg_Kind = A_Function_Call or else
Arg_Kind = A_Procedure_Call_Statement)
then
return False;
end if;
if Is_Prefix_Notation (Call)
and then
Nkind (Arg_Node) = N_Explicit_Dereference
and then
Is_Rewrite_Substitution (Arg_Node)
and then
Nkind (Original_Node (Arg_Node)) = N_Function_Call
then
Arg_Node := Prefix (Arg_Node);
end if;
if not (Nkind (Arg_Node) = N_Function_Call or else
Nkind (Arg_Node) = N_Procedure_Call_Statement)
then
-- this may be possible as a result of tree rewriting, but if we
-- have rewriting, we do not have a dispatching call, so:
return False;
else
return Present (Controlling_Argument (Arg_Node));
end if;
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Call,
Outer_Call => Package_Name & "Is_Dispatching_Call");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Is_Dispatching_Call",
Ex => Ex,
Arg_Element => Call);
end Is_Dispatching_Call;
----------------------
-- Is_Name_Repeated --
----------------------
function Is_Name_Repeated (Statement : Asis.Statement) return Boolean is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Last_Comp : Asis.Element;
S : Source_Ptr;
Result : Boolean;
begin
Check_Validity (Statement, Package_Name & "Is_Name_Repeated");
if not (Arg_Kind = A_Loop_Statement or else
Arg_Kind = A_While_Loop_Statement or else
Arg_Kind = A_For_Loop_Statement or else
Arg_Kind = A_Block_Statement or else
Arg_Kind = An_Accept_Statement)
then
Result := False;
end if;
if Arg_Kind = A_Loop_Statement or else
Arg_Kind = A_While_Loop_Statement or else
Arg_Kind = A_For_Loop_Statement or else
Arg_Kind = A_Block_Statement
then
Result := not Asis.Elements.Is_Nil (Statement_Identifier (Statement));
elsif Arg_Kind = An_Accept_Statement then
if Is_Nil (Accept_Body_Statements (Statement, True)) then
-- no statements - no "do .. end;" part - no "end"
-- to repeat the name after
Result := False;
else
Last_Comp := Get_Last_Component (Statement);
S := Set_Image_End (Last_Comp);
-- now S points to the last character (it for sure is ';')
-- of the last component (a statement, an exception
-- handler or pragma) in the accept statement.
-- First, we reset S to point onto the first character
-- after the final end of the accept statement:
-- the final "end" lexically is an identifier, so:
S := Next_Identifier (S);
S := S + 3;
-- the first character after "end"
S := Rightmost_Non_Blank (S);
-- and the final check - what follows the final "end"
if Get_Character (S) = ';' then
Result := False;
else
Result := True;
end if;
end if;
end if;
return Result;
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Outer_Call => Package_Name & "Is_Name_Repeated");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Is_Name_Repeated",
Ex => Ex,
Arg_Element => Statement);
end Is_Name_Repeated;
-----------------
-- Label_Names --
-----------------
function Label_Names
(Statement : Asis.Statement)
return Asis.Defining_Name_List
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Arg_Node : Node_Id;
Parent_Node : Node_Id;
Labels_Number : Nat := 0; -- how many labels the statement has
Label_Node : Node_Id;
begin
Check_Validity (Statement, Package_Name & "Label_Names");
if not (Arg_Kind in Internal_Statement_Kinds) then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Label_Names",
Wrong_Kind => Arg_Kind);
end if;
Arg_Node := Node (Statement);
-- First, process a special case when an infinite loop is programmed as
--
-- <<Target>> Stmt;
-- ...
-- goto Target;
--
-- If Stmt has exactly one label attached to it, the front-end rewrites
-- this construct as a subtree headed by N_Loop_Statement node
Parent_Node := Parent (R_Node (Statement));
if Nkind (Parent_Node) = N_Loop_Statement
and then
Is_Rewrite_Substitution (Parent_Node)
and then
Nkind (Original_Node (Parent_Node)) = N_Goto_Statement
and then
Arg_Node = First (Sinfo.Statements (Parent_Node))
then
return
(1 => Node_To_Element_New
(Node => Sinfo.Identifier (Parent_Node),
Internal_Kind => A_Defining_Identifier,
Starting_Element => Statement));
elsif Nkind (Arg_Node) = N_Goto_Statement
and then
Nkind (R_Node (Statement)) = N_Loop_Statement
and then
Is_Empty_List (Sinfo.Statements (R_Node (Statement)))
then
-- This is a pathological case of
--
-- <<Target>> goto Target;
return
(1 => Node_To_Element_New
(Node => Sinfo.Identifier (R_Node (Statement)),
Internal_Kind => A_Defining_Identifier,
Starting_Element => Statement));
end if;
if not Is_List_Member (Arg_Node) then
-- the accept statement in accept alternative, it cannot
-- have labels at all
return Nil_Element_List;
end if;
Label_Node := Prev (Arg_Node);
while Nkind (Label_Node) in N_Raise_xxx_Error loop
-- See B920-A06
Label_Node := Prev (Label_Node);
end loop;
while Nkind (Label_Node) = N_Label loop
Labels_Number := Labels_Number + 1;
Label_Node := Prev (Label_Node);
end loop;
-- Label_Node is not the Node of N_Label kind now
if Labels_Number = 0 then
return Nil_Element_List;
else
declare
Result_List : Asis.Element_List
(1 .. ASIS_Integer (Labels_Number));
begin
if Label_Node = Empty then
-- special case: the first statement in the statement
-- sequence is labeled
Label_Node := First (List_Containing (Arg_Node));
else
Label_Node := Next (Label_Node);
end if;
-- the first label attached to the statement and the number of
-- attached labels are obtained
for I in 1 .. ASIS_Integer (Labels_Number) loop
-- the order of labels is important !
Result_List (I) := Node_To_Element_New (
Node => Label_Node,
Internal_Kind => A_Defining_Identifier,
Starting_Element => Statement);
Label_Node := Next (Label_Node);
end loop;
return Result_List;
end;
end if;
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Outer_Call => Package_Name & "Label_Names");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Label_Names",
Ex => Ex,
Arg_Element => Statement);
end Label_Names;
---------------------
-- Loop_Statements --
---------------------
function Loop_Statements
(Statement : Asis.Statement;
Include_Pragmas : Boolean := False)
return Asis.Statement_List
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Arg_Node : Node_Id;
begin
Check_Validity (Statement, Package_Name & "Loop_Statements");
if not (Arg_Kind = A_Loop_Statement or else
Arg_Kind = A_While_Loop_Statement or else
Arg_Kind = A_For_Loop_Statement)
then
Raise_ASIS_Inappropriate_Element
("Asis_Statement.Loop_Statements",
Wrong_Kind => Arg_Kind);
end if;
Arg_Node := Node (Statement);
return N_To_E_List_New
(List => Sinfo.Statements (Arg_Node),
Include_Pragmas => Include_Pragmas,
Starting_Element => Statement);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Bool_Par => Include_Pragmas,
Outer_Call => Package_Name & "Loop_Statements");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Loop_Statements",
Ex => Ex,
Arg_Element => Statement,
Bool_Par_ON => Include_Pragmas);
end Loop_Statements;
--------------------------
-- Qualified_Expression --
--------------------------
function Qualified_Expression
(Statement : Asis.Statement)
return Asis.Expression
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Arg_Node : Node_Id;
begin
Check_Validity (Statement, Package_Name & "Qualified_Expression");
if not (Arg_Kind = A_Code_Statement) then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Qualified_Expression",
Wrong_Kind => Arg_Kind);
end if;
Arg_Node := Node (Statement);
return Node_To_Element_New (
Node => Sinfo.Expression (Arg_Node),
Internal_Kind => A_Qualified_Expression,
Starting_Element => Statement);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Outer_Call => Package_Name & "Qualified_Expression");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Qualified_Expression",
Ex => Ex,
Arg_Element => Statement);
end Qualified_Expression;
----------------------
-- Raised_Exception --
----------------------
function Raised_Exception
(Statement : Asis.Statement)
return Asis.Expression
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Arg_Node : Node_Id;
Result_Node : Node_Id;
begin
Check_Validity (Statement, Package_Name & "Raised_Exception");
if not (Arg_Kind = A_Raise_Statement) then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Raised_Exception",
Wrong_Kind => Arg_Kind);
end if;
Arg_Node := Node (Statement);
Result_Node := Sinfo.Name (Arg_Node);
if No (Result_Node) then
return Nil_Element;
else
return Node_To_Element_New (
Node => Result_Node,
Starting_Element => Statement);
end if;
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Outer_Call => Package_Name & "Raised_Exception");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Raised_Exception",
Ex => Ex,
Arg_Element => Statement);
end Raised_Exception;
------------------------
-- Requeue_Entry_Name --
------------------------
function Requeue_Entry_Name
(Statement : Asis.Statement)
return Asis.Name
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Arg_Node : Node_Id;
begin
Check_Validity (Statement, Package_Name & "Requeue_Entry_Name");
if not (Arg_Kind = A_Requeue_Statement
or else
Arg_Kind = A_Requeue_Statement_With_Abort)
then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Requeue_Entry_Name",
Wrong_Kind => Arg_Kind);
end if;
Arg_Node := Node (Statement);
return Node_To_Element_New (Node => Sinfo.Name (Arg_Node),
Starting_Element => Statement);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Outer_Call => Package_Name & "Requeue_Entry_Name");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Requeue_Entry_Name",
Ex => Ex,
Arg_Element => Statement);
end Requeue_Entry_Name;
-----------------------
-- Return_Expression --
-----------------------
function Return_Expression
(Statement : Asis.Statement)
return Asis.Expression
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Arg_Node : Node_Id;
Result_Node : Node_Id;
begin
Check_Validity (Statement, Package_Name & "Return_Expression");
if not (Arg_Kind = A_Return_Statement) then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Return_Expression",
Wrong_Kind => Arg_Kind);
end if;
Arg_Node := Node (Statement);
Result_Node := Sinfo.Expression (Arg_Node);
if No (Result_Node) then
return Nil_Element;
else
return Node_To_Element_New (Node => Result_Node,
Starting_Element => Statement);
end if;
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Outer_Call => Package_Name & "Return_Expression");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Return_Expression",
Ex => Ex,
Arg_Element => Statement);
end Return_Expression;
----------------------------
-- Sequence_Of_Statements --
----------------------------
function Sequence_Of_Statements
(Path : Asis.Path;
Include_Pragmas : Boolean := False)
return Asis.Statement_List
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Path);
Arg_Node : Node_Id;
Result_List : List_Id;
-- for processing An_If_Path, An_Elsif_Path, An_Else_Path, A_Case_Path
-- and A_Then_Abort_Path arguments; the node of such argument has
-- regular structure
-- local variables for processing A_Select_Path and An_Or_Path
-- arguments; the node of such arguments has irregular structure
Statement_List : List_Id;
First_Element : Asis.Element := Nil_Element;
Alternative_Node_Kind : Node_Kind;
begin
Check_Validity (Path, Package_Name & "Sequence_Of_Statements");
if not (Arg_Kind in Internal_Statement_Path_Kinds) then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Sequence_Of_Statements",
Wrong_Kind => Arg_Kind);
end if;
Arg_Node := Node (Path);
case Arg_Kind is
when An_If_Path | An_Elsif_Path =>
Result_List := Then_Statements (Arg_Node);
when An_Else_Path =>
Result_List := Else_Statements (Arg_Node);
when A_Case_Path =>
Result_List := Sinfo.Statements (Arg_Node);
when A_Then_Abort_Path =>
Result_List := Sinfo.Statements (Arg_Node);
when A_Select_Path | An_Or_Path =>
Alternative_Node_Kind := Nkind (Arg_Node);
if Alternative_Node_Kind = N_Terminate_Alternative then
-- special case: result list contains only one dummy terminate
-- statement; no tree traversing needed: the result is based
-- on the same node as the argument
return Asis.Statement_List'(
1 => Node_To_Element_New (
Node => Arg_Node,
Internal_Kind => A_Terminate_Alternative_Statement,
Starting_Element => Path));
else
-- this alternative corresponds to the situation of
-- N_Accept_Alternative, N_Delay_Alternative,
-- N_Entry_Call_Alternative or N_Triggering_Alternative
-- forming the first element of the element list to be
-- returned:
if Alternative_Node_Kind = N_Accept_Alternative then
First_Element :=
Node_To_Element_New (
Node => Accept_Statement (Arg_Node),
Internal_Kind => An_Accept_Statement,
Starting_Element => Path);
elsif Alternative_Node_Kind = N_Delay_Alternative then
First_Element :=
Node_To_Element_New (
Node => Delay_Statement (Arg_Node),
Starting_Element => Path);
elsif Alternative_Node_Kind = N_Entry_Call_Alternative then
First_Element :=
Node_To_Element_New (
Node => Entry_Call_Statement (Arg_Node),
Starting_Element => Path);
elsif Alternative_Node_Kind = N_Triggering_Alternative then
First_Element :=
Node_To_Element_New (
Node => Triggering_Statement (Arg_Node),
Starting_Element => Path);
end if;
-- the rest of the returned list:
Statement_List := Sinfo.Statements (Arg_Node);
return Asis.Statement_List'(1 => First_Element) &
N_To_E_List_New
(List => Statement_List,
Include_Pragmas => Include_Pragmas,
Starting_Element => Path);
end if;
when others =>
null;
end case;
return N_To_E_List_New (List => Result_List,
Include_Pragmas => Include_Pragmas,
Starting_Element => Path);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Path,
Bool_Par => Include_Pragmas,
Outer_Call => Package_Name & "Sequence_Of_Statements");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Sequence_Of_Statements",
Ex => Ex,
Arg_Element => Path,
Bool_Par_ON => Include_Pragmas);
end Sequence_Of_Statements;
--------------------------
-- Statement_Identifier --
--------------------------
function Statement_Identifier
(Statement : Asis.Statement)
return Asis.Defining_Name
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Arg_Node : Node_Id;
begin
Check_Validity (Statement, Package_Name & "Statement_Identifier");
if not (Arg_Kind = A_Loop_Statement or else
Arg_Kind = A_While_Loop_Statement or else
Arg_Kind = A_For_Loop_Statement or else
Arg_Kind = A_Block_Statement)
then
Raise_ASIS_Inappropriate_Element
("Asis_Statement.Statement_Identifier",
Wrong_Kind => Arg_Kind);
end if;
Arg_Node := Node (Statement);
if Special_Case (Statement) = A_Dummy_Block_Statement or else
Has_Created_Identifier (Arg_Node)
then
return Nil_Element;
else
return Node_To_Element_New (
Node => Sinfo.Identifier (Arg_Node),
Internal_Kind => A_Defining_Identifier,
Starting_Element => Statement);
end if;
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Outer_Call => Package_Name & "Statement_Identifier");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Statement_Identifier",
Ex => Ex,
Arg_Element => Statement);
end Statement_Identifier;
---------------------
-- Statement_Paths --
---------------------
function Statement_Paths
(Statement : Asis.Statement;
Include_Pragmas : Boolean := False)
return Asis.Path_List
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Arg_Node : Node_Id;
Path_List_Length : ASIS_Integer; -- Length of returned list
Elsif_Or_Length : ASIS_Integer; -- Number of Elsif or Or paths
Else_Present : Boolean;
begin
Check_Validity (Statement, Package_Name & "Statement_Paths");
if not (Arg_Kind = An_If_Statement or else
Arg_Kind = A_Case_Statement or else
Arg_Kind = A_Selective_Accept_Statement or else
Arg_Kind = A_Timed_Entry_Call_Statement or else
Arg_Kind = A_Conditional_Entry_Call_Statement or else
Arg_Kind = An_Asynchronous_Select_Statement)
then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Statement_Paths",
Wrong_Kind => Arg_Kind);
end if;
Arg_Node := Node (Statement);
case Arg_Kind is
when An_If_Statement =>
Path_List_Length := 1; -- An_If_Path
Else_Present := Present (Else_Statements (Arg_Node));
if Else_Present then
Path_List_Length := Path_List_Length + 1;
end if;
if Present (Elsif_Parts (Arg_Node)) then
Elsif_Or_Length := ASIS_Integer
(List_Length (Elsif_Parts (Arg_Node)));
else
Elsif_Or_Length := 0;
end if;
Path_List_Length := Path_List_Length + Elsif_Or_Length;
declare
Path_List : Asis.Element_List (1 .. Path_List_Length);
-- Element List to be returned by the function
begin
Path_List (1) := Node_To_Element_New
(Node => Arg_Node,
Internal_Kind => An_If_Path,
Starting_Element => Statement);
Path_List (2 .. Elsif_Or_Length + 1) :=
N_To_E_List_New
(List => Elsif_Parts (Arg_Node),
Internal_Kind => An_Elsif_Path,
Starting_Element => Statement);
if Else_Present then
Path_List (Path_List_Length) := Node_To_Element_New
(Node => Arg_Node,
Internal_Kind => An_Else_Path,
Starting_Element => Statement);
end if;
return Path_List;
end;
when A_Case_Statement =>
-- only here the value of Include_Pragmas is important
return N_To_E_List_New
(List => Alternatives (Arg_Node),
Include_Pragmas => Include_Pragmas,
Starting_Element => Statement);
when A_Selective_Accept_Statement =>
Elsif_Or_Length := ASIS_Integer
(List_Length (Select_Alternatives (Arg_Node)));
Path_List_Length := Elsif_Or_Length;
Else_Present := Present (Else_Statements (Arg_Node));
if Else_Present then
Path_List_Length := Path_List_Length + 1;
end if;
declare
Path_List : Asis.Element_List (1 .. Path_List_Length);
-- Element List to be returned by the function
begin
Path_List (1 .. Elsif_Or_Length) :=
N_To_E_List_New
(List => Select_Alternatives (Arg_Node),
Starting_Element => Statement);
if Else_Present then
Path_List (Path_List_Length) := Node_To_Element_New
(Node => Arg_Node,
Internal_Kind => An_Else_Path,
Starting_Element => Statement);
end if;
return Path_List;
end;
when A_Timed_Entry_Call_Statement =>
return Asis.Path_List'(
1 => Node_To_Element_New (
Node => Entry_Call_Alternative (Arg_Node),
Internal_Kind => A_Select_Path,
Starting_Element => Statement),
2 => Node_To_Element_New (
Node => Delay_Alternative (Arg_Node),
Internal_Kind => An_Or_Path,
Starting_Element => Statement));
when A_Conditional_Entry_Call_Statement =>
return Asis.Path_List'(
1 => Node_To_Element_New (
Node => Entry_Call_Alternative (Arg_Node),
Internal_Kind => A_Select_Path,
Starting_Element => Statement),
2 => Node_To_Element_New (
Node => Arg_Node,
Internal_Kind => An_Else_Path,
Starting_Element => Statement));
when An_Asynchronous_Select_Statement =>
return Asis.Path_List'(
1 => Node_To_Element_New (
Node => Triggering_Alternative (Arg_Node),
Internal_Kind => A_Select_Path,
Starting_Element => Statement),
2 => Node_To_Element_New (
Node => Abortable_Part (Arg_Node),
Internal_Kind => A_Then_Abort_Path,
Starting_Element => Statement));
when others =>
raise Internal_Implementation_Error;
-- this choice can never be reached, see the condition
-- for defining the appropriate element
end case;
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Bool_Par => Include_Pragmas,
Outer_Call => Package_Name & "Statement_Paths");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Statement_Paths",
Ex => Ex,
Arg_Element => Statement,
Bool_Par_ON => Include_Pragmas);
end Statement_Paths;
---------------------
-- While_Condition --
---------------------
function While_Condition
(Statement : Asis.Statement)
return Asis.Expression
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Statement);
Arg_Node : Node_Id;
begin
Check_Validity (Statement, Package_Name & "While_Condition");
if not (Arg_Kind = A_While_Loop_Statement) then
Raise_ASIS_Inappropriate_Element
(Package_Name & "While_Condition",
Wrong_Kind => Arg_Kind);
end if;
Arg_Node := Node (Statement);
return Node_To_Element_New (
Node => Condition (Iteration_Scheme (Arg_Node)),
Starting_Element => Statement);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Statement,
Outer_Call => Package_Name & "While_Condition");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "While_Condition",
Ex => Ex,
Arg_Element => Statement);
end While_Condition;
end Asis.Statements;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- Copyright (C) 2012-2020, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Ada.Unchecked_Conversion;
with System.BB.Board_Parameters;
with Interfaces; use Interfaces;
with Interfaces.STM32; use Interfaces.STM32;
with Interfaces.STM32.RCC; use Interfaces.STM32.RCC;
package body System.STM32 is
package Param renames System.BB.Board_Parameters;
HPRE_Presc_Table : constant array (AHB_Prescaler_Enum) of UInt32 :=
(2, 4, 8, 16, 64, 128, 256, 512);
PPRE_Presc_Table : constant array (APB_Prescaler_Enum) of UInt32 :=
(2, 4, 8, 16);
-------------------
-- System_Clocks --
-------------------
function System_Clocks return RCC_System_Clocks
is
Source : constant SYSCLK_Source :=
SYSCLK_Source'Val (RCC_Periph.CFGR.SWS);
Result : RCC_System_Clocks;
begin
case Source is
-- HSI as source
when SYSCLK_SRC_HSI =>
Result.SYSCLK := HSICLK;
-- HSE as source
when SYSCLK_SRC_HSE =>
Result.SYSCLK := Param.HSE_Clock_Frequency;
-- PLL as source
when SYSCLK_SRC_PLL =>
declare
PLLMUL : constant UInt32 :=
UInt32 (RCC_Periph.CFGR.PLLMUL) + 2;
PREDIV : constant UInt32 :=
UInt32 (RCC_Periph.CFGR2.PREDIV + 1);
PLLOUT : UInt32;
begin
case PLL_Source'Val (RCC_Periph.CFGR.PLLSRC) is
when PLL_SRC_HSI_2 =>
PLLOUT := (HSICLK / 2) * PLLMUL;
when PLL_SRC_HSI_PREDIV =>
PLLOUT := (HSICLK / PREDIV) * PLLMUL;
when PLL_SRC_HSE_PREDIV =>
PLLOUT := (Param.HSE_Clock_Frequency / PREDIV) * PLLMUL;
when PLL_SRC_HSI48_PREDIV =>
PLLOUT := (HSI48CLK / PREDIV) * PLLMUL;
end case;
Result.SYSCLK := PLLOUT;
end;
-- HSI48 as source
when SYSCLK_SRC_HSI48 =>
Result.SYSCLK := HSI48CLK;
end case;
declare
function To_AHBP is new Ada.Unchecked_Conversion
(CFGR_HPRE_Field, AHB_Prescaler);
function To_APBP is new Ada.Unchecked_Conversion
(CFGR_PPRE_Field, APB_Prescaler);
HPRE : constant AHB_Prescaler := To_AHBP (RCC_Periph.CFGR.HPRE);
HPRE_Div : constant UInt32 := (if HPRE.Enabled
then HPRE_Presc_Table (HPRE.Value)
else 1);
PPRE : constant APB_Prescaler := To_APBP (RCC_Periph.CFGR.PPRE);
PPRE_Div : constant UInt32 := (if PPRE.Enabled
then PPRE_Presc_Table (PPRE.Value)
else 1);
begin
Result.HCLK := Result.SYSCLK / HPRE_Div;
Result.PCLK := Result.HCLK / PPRE_Div;
if not PPRE.Enabled then
Result.TIMCLK := Result.PCLK;
else
Result.TIMCLK := Result.PCLK * 2;
end if;
end;
return Result;
end System_Clocks;
end System.STM32;
|
----------------------------------------------------------------
-- ZLib for Ada thick binding. --
-- --
-- Copyright (C) 2002-2003 Dmitriy Anisimkov --
-- --
-- Open source license information is in the zlib.ads file. --
----------------------------------------------------------------
-- $Id: zlib-streams.ads,v 1.2 2020/09/15 02:05:31 christos Exp $
package ZLib.Streams is
type Stream_Mode is (In_Stream, Out_Stream, Duplex);
type Stream_Access is access all Ada.Streams.Root_Stream_Type'Class;
type Stream_Type is
new Ada.Streams.Root_Stream_Type with private;
procedure Read
(Stream : in out Stream_Type;
Item : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
procedure Write
(Stream : in out Stream_Type;
Item : in Ada.Streams.Stream_Element_Array);
procedure Flush
(Stream : in out Stream_Type;
Mode : in Flush_Mode := Sync_Flush);
-- Flush the written data to the back stream,
-- all data placed to the compressor is flushing to the Back stream.
-- Should not be used until necessary, because it is decreasing
-- compression.
function Read_Total_In (Stream : in Stream_Type) return Count;
pragma Inline (Read_Total_In);
-- Return total number of bytes read from back stream so far.
function Read_Total_Out (Stream : in Stream_Type) return Count;
pragma Inline (Read_Total_Out);
-- Return total number of bytes read so far.
function Write_Total_In (Stream : in Stream_Type) return Count;
pragma Inline (Write_Total_In);
-- Return total number of bytes written so far.
function Write_Total_Out (Stream : in Stream_Type) return Count;
pragma Inline (Write_Total_Out);
-- Return total number of bytes written to the back stream.
procedure Create
(Stream : out Stream_Type;
Mode : in Stream_Mode;
Back : in Stream_Access;
Back_Compressed : in Boolean;
Level : in Compression_Level := Default_Compression;
Strategy : in Strategy_Type := Default_Strategy;
Header : in Header_Type := Default;
Read_Buffer_Size : in Ada.Streams.Stream_Element_Offset
:= Default_Buffer_Size;
Write_Buffer_Size : in Ada.Streams.Stream_Element_Offset
:= Default_Buffer_Size);
-- Create the Comression/Decompression stream.
-- If mode is In_Stream then Write operation is disabled.
-- If mode is Out_Stream then Read operation is disabled.
-- If Back_Compressed is true then
-- Data written to the Stream is compressing to the Back stream
-- and data read from the Stream is decompressed data from the Back stream.
-- If Back_Compressed is false then
-- Data written to the Stream is decompressing to the Back stream
-- and data read from the Stream is compressed data from the Back stream.
-- !!! When the Need_Header is False ZLib-Ada is using undocumented
-- ZLib 1.1.4 functionality to do not create/wait for ZLib headers.
function Is_Open (Stream : Stream_Type) return Boolean;
procedure Close (Stream : in out Stream_Type);
private
use Ada.Streams;
type Buffer_Access is access all Stream_Element_Array;
type Stream_Type
is new Root_Stream_Type with
record
Mode : Stream_Mode;
Buffer : Buffer_Access;
Rest_First : Stream_Element_Offset;
Rest_Last : Stream_Element_Offset;
-- Buffer for Read operation.
-- We need to have this buffer in the record
-- because not all read data from back stream
-- could be processed during the read operation.
Buffer_Size : Stream_Element_Offset;
-- Buffer size for write operation.
-- We do not need to have this buffer
-- in the record because all data could be
-- processed in the write operation.
Back : Stream_Access;
Reader : Filter_Type;
Writer : Filter_Type;
end record;
end ZLib.Streams;
|
--
-- Copyright 2018 The wookey project team <wookey@ssi.gouv.fr>
-- - Ryad Benadjila
-- - Arnauld Michelizza
-- - Mathieu Renard
-- - Philippe Thierry
-- - Philippe Trebuchet
--
-- 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 ewok.tasks_shared; use ewok.tasks_shared;
with ewok.exported.dma;
package ewok.sanitize
with spark_mode => on
is
function is_range_in_devices_slot
(ptr : system_address;
size : unsigned_32;
task_id : ewok.tasks_shared.t_task_id)
return boolean;
pragma warnings (off, "explicit membership test may be optimized");
function is_word_in_data_slot
(ptr : system_address;
task_id : ewok.tasks_shared.t_task_id;
mode : ewok.tasks_shared.t_task_mode) return boolean
with
global => null,
post => (if (ptr + 4 not in system_address'range) then is_word_in_data_slot'result = false);
function is_word_in_txt_slot
(ptr : system_address;
task_id : ewok.tasks_shared.t_task_id) return boolean
with
global => null,
-- there is now hypothesis on input values, yet we impose some
-- specific behavior for various overflows
post => (if (ptr + 4 not in system_address'range) then is_word_in_txt_slot'result = false);
function is_word_in_allocated_device
(ptr : system_address;
task_id : ewok.tasks_shared.t_task_id)
return boolean;
function is_word_in_any_slot
(ptr : system_address;
task_id : ewok.tasks_shared.t_task_id;
mode : ewok.tasks_shared.t_task_mode) return boolean
with
global => null,
-- there is now hypothesis on input values, yet we impose some
-- specific behavior for various overflows
post => (if (ptr + 4 not in system_address'range) then is_word_in_any_slot'result = false);
function is_range_in_data_slot
(ptr : system_address;
size : unsigned_32;
task_id : ewok.tasks_shared.t_task_id;
mode : ewok.tasks_shared.t_task_mode) return boolean
with
global => null,
-- there is now hypothesis on input values, yet we impose some
-- specific behavior for various overflows
post => (if (ptr + size not in system_address'range) then is_range_in_data_slot'result = false);
function is_range_in_txt_slot
(ptr : system_address;
size : unsigned_32;
task_id : ewok.tasks_shared.t_task_id) return boolean
with
global => null,
-- there is now hypothesis on input values, yet we impose some
-- specific behavior for various overflows
post => (if (ptr + size not in system_address'range) then is_range_in_txt_slot'result = false);
function is_range_in_any_slot
(ptr : system_address;
size : unsigned_32;
task_id : ewok.tasks_shared.t_task_id;
mode : ewok.tasks_shared.t_task_mode) return boolean
with
global => null,
-- there is now hypothesis on input values, yet we impose some
-- specific behavior for various overflows
post => (if (ptr + size not in system_address'range) then is_range_in_any_slot'result = false);
function is_range_in_dma_shm
(ptr : system_address;
size : unsigned_32;
dma_access : ewok.exported.dma.t_dma_shm_access;
task_id : ewok.tasks_shared.t_task_id) return boolean
with
spark_mode => off,
global => null,
-- there is now hypothesis on input values, yet we impose some
-- specific behavior for various overflows
post => (if (ptr + size not in system_address'range) then is_range_in_dma_shm'result = false);
pragma warnings (on);
end ewok.sanitize;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015-2020, 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 STMicroelectronics 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. --
-- --
-- --
-- This file is based on: --
-- --
-- @file stm32f4_discovery.h --
-- @author MCD Application Team --
-- @version V1.1.0 --
-- @date 19-June-2014 --
-- @brief This file contains definitions for STM32F4-Discovery Kit --
-- LEDs, push-buttons hardware resources. --
-- --
-- COPYRIGHT(c) 2014 STMicroelectronics --
------------------------------------------------------------------------------
-- This file provides declarations for devices on the STM32F4 Discovery kits
-- manufactured by ST Microelectronics.
with STM32.Device; use STM32.Device;
with STM32.GPIO; use STM32.GPIO;
with STM32.I2C; use STM32.I2C;
with STM32.SPI; use STM32.SPI;
with STM32.Timers; use STM32.Timers;
with STM32.USARTs; use STM32.USARTs;
with MPU9250; use MPU9250;
with AK8963; use AK8963;
with Ravenscar_Time;
package STM32.Board is
pragma Elaborate_Body;
subtype User_LED is GPIO_Point;
LED_Blue_L : User_LED renames PD2;
LED_Green_L : User_LED renames PC1;
LED_Green_R : User_LED renames PC2;
LED_Red_L : User_LED renames PC0;
LED_Red_R : User_LED renames PC3;
RG_LEDs : GPIO_Points :=
LED_Green_L & LED_Green_R & LED_Red_L & LED_Red_R;
All_LEDs : GPIO_Points :=
RG_LEDs & LED_Blue_L;
LCH_LED : GPIO_Point renames LED_Blue_L;
procedure Initialize_LEDs;
-- MUST be called prior to any use of the LEDs
procedure Turn_On (This : in out User_LED);
procedure Turn_Off (This : in out User_LED);
function Is_On (This : User_LED) return Boolean;
procedure All_LEDs_Off with Inline;
procedure All_LEDs_On with Inline;
procedure Toggle_LED (This : in out User_LED)
renames STM32.GPIO.Toggle;
procedure Toggle_LEDs (These : in out GPIO_Points)
renames STM32.GPIO.Toggle;
---------
-- PWM --
---------
MOTOR_123_Timer : Timer renames Timer_2;
MOTOR_4_Timer : Timer renames Timer_4;
MOTOR_1 : GPIO_Point renames PA1;
MOTOR_1_AF : GPIO_Alternate_Function renames GPIO_AF_TIM2_1;
MOTOR_1_Channel : Timer_Channel renames Channel_2;
MOTOR_2 : GPIO_Point renames PB11;
MOTOR_2_AF : GPIO_Alternate_Function renames GPIO_AF_TIM2_1;
MOTOR_2_Channel : Timer_Channel renames Channel_4;
MOTOR_3 : GPIO_Point renames PA15;
MOTOR_3_AF : GPIO_Alternate_Function renames GPIO_AF_TIM2_1;
MOTOR_3_Channel : Timer_Channel renames Channel_1;
MOTOR_4 : GPIO_Point renames PB9;
MOTOR_4_AF : GPIO_Alternate_Function renames GPIO_AF_TIM4_2;
MOTOR_4_Channel : Timer_Channel renames Channel_4;
---------
-- I2C --
---------
procedure Initialize_I2C_GPIO (Port : in out I2C_Port)
with
-- I2C_2 is not accessible on this board
Pre => As_Port_Id (Port) = I2C_Id_1
or else As_Port_Id (Port) = I2C_Id_3;
procedure Configure_I2C (Port : in out I2C_Port);
I2C_MPU_Port : I2C_Port renames I2C_3;
I2C_MPU_SCL : GPIO_Point renames PA8;
I2C_MPU_SDA : GPIO_Point renames PC9;
I2C_EXT_Port : I2C_Port renames I2C_1;
I2C_EXT_SCL : GPIO_Point renames PB6;
I2C_EXT_SDA : GPIO_Point renames PB7;
---------
-- SPI --
---------
procedure Initialize_EXT_SPI;
EXT_SPI : SPI_Port renames SPI_1;
EXT_SCK : GPIO_Point renames PA5;
EXT_MISO : GPIO_Point renames PA6;
EXT_MOSI : GPIO_Point renames PA7;
EXT_CS0 : GPIO_Point renames PC12;
EXT_CS1 : GPIO_Point renames PB4;
EXT_CS2 : GPIO_Point renames PB5;
EXT_CS3 : GPIO_Point renames PB8;
procedure Configure_EXT_CS (Pin : in out GPIO_Point)
with Pre =>
Pin = EXT_CS0 or Pin = EXT_CS1 or Pin = EXT_CS2 or Pin = EXT_CS3;
---------
-- USB --
---------
USB_ID : GPIO_Point renames PA10;
USB_DM : GPIO_Point renames PA11;
USB_DP : GPIO_Point renames PA12;
--------------------------
-- External connections --
--------------------------
EXT_USART1 : USART renames USART_3;
EXT_USART1_AF : GPIO_Alternate_Function renames GPIO_AF_USART3_7;
EXT_USART1_TX : GPIO_Point renames PC10;
EXT_USART1_RX : GPIO_Point renames PC11;
EXT_USART2 : USART renames USART_2;
EXT_USART2_AF : GPIO_Alternate_Function renames GPIO_AF_USART2_7;
EXT_USART2_TX : GPIO_Point renames PA2;
EXT_USART2_RX : GPIO_Point renames PA3;
-----------
-- Radio --
-----------
NRF_USART : USART renames USART_6;
NRF_USART_AF : GPIO_Alternate_Function renames GPIO_AF_USART6_8;
NRF_RX : GPIO_Point renames PC6;
NRF_TX : GPIO_Point renames PC7;
NRF_SWCLK : GPIO_Point renames PB13;
NRF_SWIO : GPIO_Point renames PB15;
NRF_FLOW_CTRL : GPIO_Point renames PA4;
---------
-- MPU --
---------
MPU_Device : MPU9250.MPU9250_Device (I2C_MPU_Port'Access,
High,
Ravenscar_Time.Delays);
MPU_INT : GPIO_Point renames PC13;
MPU_FSYNC : GPIO_Point renames PC14;
MAG_Device : AK8963_Device (I2C_MPU_Port'Access,
Add_00,
Ravenscar_Time.Delays);
end STM32.Board;
|
function Fib (X: in Integer) return Integer is
function Actual_Fib (N: in Integer) return Integer is
begin
if N < 2 then
return N;
else
return Actual_Fib (N-1) + Actual_Fib (N-2);
end if;
end Actual_Fib;
begin
if X < 0 then
raise Constraint_Error;
else
return Actual_Fib (X);
end if;
end Fib;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- D E B U G _ A --
-- --
-- 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 Sinfo; use Sinfo;
with Sinput; use Sinput;
with Output; use Output;
package body Debug_A is
Debug_A_Depth : Natural := 0;
-- Output for the debug A flag is preceded by a sequence of vertical bar
-- characters corresponding to the recursion depth of the actions being
-- recorded (analysis, expansion, resolution and evaluation of nodes)
-- This variable records the depth.
Max_Node_Ids : constant := 200;
-- Maximum number of Node_Id values that get stacked
Node_Ids : array (1 .. Max_Node_Ids) of Node_Id;
-- A stack used to keep track of Node_Id values for setting the value of
-- Current_Error_Node correctly. Note that if we have more than 200
-- recursion levels, we just don't reset the right value on exit, which
-- is not crucial, since this is only for debugging.
-----------------------
-- Local Subprograms --
-----------------------
procedure Debug_Output_Astring;
-- Outputs Debug_A_Depth number of vertical bars, used to preface messages
-------------------
-- Debug_A_Entry --
-------------------
procedure Debug_A_Entry (S : String; N : Node_Id) is
begin
-- Output debugging information if -gnatda flag set
if Debug_Flag_A then
Debug_Output_Astring;
Write_Str (S);
Write_Str ("Node_Id = ");
Write_Int (Int (N));
Write_Str (" ");
Write_Location (Sloc (N));
Write_Str (" ");
Write_Str (Node_Kind'Image (Nkind (N)));
Write_Eol;
end if;
-- Now push the new element
-- Why is this done unconditionally???
Debug_A_Depth := Debug_A_Depth + 1;
if Debug_A_Depth <= Max_Node_Ids then
Node_Ids (Debug_A_Depth) := N;
end if;
-- Set Current_Error_Node only if the new node has a decent Sloc
-- value, since it is for the Sloc value that we set this anyway.
-- If we don't have a decent Sloc value, we leave it unchanged.
if Sloc (N) > No_Location then
Current_Error_Node := N;
end if;
end Debug_A_Entry;
------------------
-- Debug_A_Exit --
------------------
procedure Debug_A_Exit (S : String; N : Node_Id; Comment : String) is
begin
Debug_A_Depth := Debug_A_Depth - 1;
-- We look down the stack to find something with a decent Sloc. (If
-- we find nothing, just leave it unchanged which is not so terrible)
-- This seems nasty overhead for the normal case ???
for J in reverse 1 .. Integer'Min (Max_Node_Ids, Debug_A_Depth) loop
if Sloc (Node_Ids (J)) > No_Location then
Current_Error_Node := Node_Ids (J);
exit;
end if;
end loop;
-- Output debugging information if -gnatda flag set
if Debug_Flag_A then
Debug_Output_Astring;
Write_Str (S);
Write_Str ("Node_Id = ");
Write_Int (Int (N));
Write_Str (Comment);
Write_Eol;
end if;
end Debug_A_Exit;
--------------------------
-- Debug_Output_Astring --
--------------------------
procedure Debug_Output_Astring is
Vbars : constant String := "|||||||||||||||||||||||||";
-- Should be constant, removed because of GNAT 1.78 bug ???
begin
if Debug_A_Depth > Vbars'Length then
for I in Vbars'Length .. Debug_A_Depth loop
Write_Char ('|');
end loop;
Write_Str (Vbars);
else
Write_Str (Vbars (1 .. Debug_A_Depth));
end if;
end Debug_Output_Astring;
end Debug_A;
|
generic
with procedure Process_Data(Item: Data);
with function Stop return Boolean;
with procedure Finish;
package Bin_Trees.Traverse is
task Inorder_Task is
entry Run(Tree: Tree_Type);
-- this will call each Item in Tree and, at the very end, it will call Finish
-- except when Stop becomes true; in this case, the task terminates
end Inorder_Task;
end Bin_Trees.Traverse;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- O S I N T - M --
-- --
-- B o d y --
-- --
-- Copyright (C) 2001-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 Osint;
pragma Elaborate_All (Osint);
-- This pragma is needed because of the call to Set_Program in the
-- elaboration of the package. We cannot rely on the static model
-- of elaboration since the compiler is routinely compiled with
-- checks off (-gnatp), and with older versions of the compiler
-- (up to and including most 5.04 wavefronts), -gnatp suppresses
-- the static elaboration check mechanisms. It could be removed
-- one day, but there really is no need to do so.
package body Osint.M is
-----------------------
-- More_Source_Files --
-----------------------
function More_Source_Files return Boolean renames More_Files;
----------------------
-- Next_Main_Source --
----------------------
function Next_Main_Source return File_Name_Type renames Next_Main_File;
----------------------
-- Object_File_Name --
----------------------
function Object_File_Name (N : File_Name_Type) return File_Name_Type
renames Osint.Object_File_Name;
begin
Set_Program (Make);
end Osint.M;
|
pragma Ada_2012;
with Ada.Strings.Fixed;
with Fakedsp.Data_Streams.Wave;
with Fakedsp.Data_Streams.Text;
with Utilities.Option_Lists;
use Ada;
use Utilities;
with Ada.Text_IO;
with Ada.Directories;
package body Fakedsp.Data_Streams.Files is
subtype Known_Types is
File_Type
range
File_Type'First .. File_Type'Pred (File_Type'Last);
subtype File_Extension is String (1 .. 3);
type Parsed_Filename (N : Positive) is
record
Name : String (1 .. N);
Typ : File_Type;
Options : Option_Lists.Option_List;
end record;
function Parse (Filename : String;
Format : File_Type) return Parsed_Filename
is
use Option_Lists;
Extension_To_Type : constant array (Known_Types) of File_Extension :=
(Wav_File => "wav",
Text_File => "txt");
------------------
-- Name_To_Type --
------------------
function Name_To_Type (Name : String;
Format : File_Type) return File_Type
is
begin
if Format /= Unknown then
return Format;
end if;
if Name = "-" then
if Format = Unknown or Format = Text_File then
return Text_File;
else
raise Text.Unimplemented_Format
with "Standard input only with text format";
end if;
end if;
declare
Ext : constant String := Ada.Directories.Extension (Name);
begin
Ada.Text_IO.Put_Line ("E=(" & Ext & ")(" & Name & ")" );
if Ext'Length /= File_Extension'Length then
return Unknown;
end if;
for T in File_Type loop
if Extension_To_Type (T) = Ext then
return T;
end if;
end loop;
end;
return Unknown;
end Name_To_Type;
Pos : constant Natural := Strings.Fixed.Index (Source => Filename,
Pattern => "::",
Going => Strings.Backward);
Optionless_Name : constant String := (if Pos = 0 then
Filename
else
Filename (Filename'First .. Pos - 1));
Options : constant Option_List := (if Pos = 0 then
Empty_List
else
Parse (Filename (Pos + 2 .. Filename'Last)));
begin
Ada.Text_IO.Put_Line ("F=(" & Optionless_Name & ")");
return Parsed_Filename'(N => Optionless_Name'Length,
Name => Optionless_Name,
Typ => Name_To_Type (Optionless_Name, Format),
Options => Options);
end Parse;
----------
-- Open --
----------
function Open (Filename : String;
Format : File_Type := Unknown)
return Data_Source_Access
is
Parsed : constant Parsed_Filename := Parse (Filename, Format);
begin
if Parsed.Name = "-" then
if Parsed.Typ = Unknown or Parsed.Typ = Text_File then
return Data_Source_Access (Text.Standard_Input (Parsed.Options));
else
raise Text.Unimplemented_Format
with "Standard input only with text format";
end if;
end if;
case Parsed.Typ is
when Wav_File =>
return Data_Source_Access (Wave.Open (Parsed.Name));
when Text_File =>
return Data_Source_Access (Text.Open_Source (Parsed.Name));
when Unknown =>
raise Constraint_Error with "Unknown file type for '" & Filename & "'";
end case;
end Open;
----------
-- Open --
----------
function Open (Filename : String;
Sampling : Frequency_Hz;
Format : File_Type := Unknown;
Last_Channel : Channel_Index := 1)
return Data_Destination_Access
is
Parsed : constant Parsed_Filename := Parse (Filename, Format);
begin
if Parsed.Name = "-" then
if Parsed.Typ = Unknown or Parsed.Typ = Text_File then
return Data_Destination_Access (Text.Standard_Output (Parsed.Options));
else
raise Text.Unimplemented_Format
with "Standard input only with text format";
end if;
end if;
case Parsed.Typ is
when Wav_File =>
return Data_Destination_Access (Wave.Open (Parsed.Name, Sampling, Last_Channel));
when Text_File =>
return Data_Destination_Access (Text.Open_Destination (Filename => Parsed.Name,
Options => Parsed.Options));
when Unknown =>
raise Constraint_Error with "Unknown file type for '" & Filename & "'";
end case;
end Open;
end Fakedsp.Data_Streams.Files;
|
-- { dg-do compile }
with Ada.Containers.Ordered_Maps;
with Ada.Tags.Generic_Dispatching_Constructor;
package body gen_disp is
use type Ada.Tags.Tag;
function "<" (L, R : in Ada.Tags.Tag) return Boolean is
begin
return Ada.Tags.External_Tag (L) < Ada.Tags.External_Tag (R);
end "<";
package Char_To_Tag_Map is new Ada.Containers.Ordered_Maps (
Key_Type => Character,
Element_Type => Ada.Tags.Tag,
"<" => "<",
"=" => Ada.Tags. "=");
package Tag_To_Char_Map is new Ada.Containers.Ordered_Maps (
Key_Type => Ada.Tags.Tag,
Element_Type => Character,
"<" => "<",
"=" => "=");
use type Char_To_Tag_Map.Cursor;
use type Tag_To_Char_Map.Cursor;
Char_To_Tag : Char_To_Tag_Map.Map;
Tag_To_Char : Tag_To_Char_Map.Map;
function Get_Object is new
Ada.Tags.Generic_Dispatching_Constructor
(Root_Type, Ada.Streams.Root_Stream_Type'Class, Root_Type'Input);
function Root_Type_Class_Input
(S : not null access Ada.Streams.Root_Stream_Type'Class)
return Root_Type'Class
is
External_Tag : constant Character := Character'Input (S);
C : constant Char_To_Tag_Map.Cursor := Char_To_Tag.Find (External_Tag);
begin
return Get_Object (Char_To_Tag_Map.Element (C), S);
end Root_Type_Class_Input;
end gen_disp;
|
-----------------------------------------------------------------------
-- components-utils-scripts -- Javascript queue
-- Copyright (C) 2011, 2012, 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.
-----------------------------------------------------------------------
package body ASF.Components.Utils.Scripts is
-- ------------------------------
-- Write the content that was collected by rendering the inner children.
-- Write the content in the Javascript queue.
-- ------------------------------
overriding
procedure Write_Content (UI : in UIScript;
Writer : in out Contexts.Writer.Response_Writer'Class;
Content : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
pragma Unreferenced (UI, Context);
begin
Writer.Queue_Script (Content);
end Write_Content;
-- ------------------------------
-- If the component provides a src attribute, render the <script src='xxx'></script>
-- tag with an optional async attribute.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIScript;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Src : constant String := UI.Get_Attribute (Context => Context, Name => "src");
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
begin
if Src'Length > 0 then
Writer.Queue_Include_Script (URL => Src,
Async => UI.Get_Attribute (Context => Context,
Name => "async"));
end if;
end;
end Encode_Begin;
end ASF.Components.Utils.Scripts;
|
pragma License (Unrestricted);
-- extended unit
private with System.Unbounded_Allocators;
package System.Storage_Pools.Subpools.Unbounded is
-- The subpools version of System.Storage_Pools.Unbounded.
pragma Preelaborate;
type Unbounded_Pool_With_Subpools is
limited new Root_Storage_Pool_With_Subpools with private;
-- Note: Default_Subpool_For_Pool is not supported.
private
type Unbounded_Subpool is limited new Root_Subpool with record
Allocator : Unbounded_Allocators.Unbounded_Allocator;
end record;
type Unbounded_Pool_With_Subpools is
limited new Root_Storage_Pool_With_Subpools with null record;
pragma Finalize_Storage_Only (Unbounded_Pool_With_Subpools);
overriding function Create_Subpool (
Pool : in out Unbounded_Pool_With_Subpools)
return not null Subpool_Handle;
overriding procedure Allocate_From_Subpool (
Pool : in out Unbounded_Pool_With_Subpools;
Storage_Address : out Address;
Size_In_Storage_Elements : Storage_Elements.Storage_Count;
Alignment : Storage_Elements.Storage_Count;
Subpool : not null Subpool_Handle);
overriding procedure Deallocate_Subpool (
Pool : in out Unbounded_Pool_With_Subpools;
Subpool : in out Subpool_Handle);
overriding procedure Deallocate (
Pool : in out Unbounded_Pool_With_Subpools;
Storage_Address : Address;
Size_In_Storage_Elements : Storage_Elements.Storage_Count;
Alignment : Storage_Elements.Storage_Count);
end System.Storage_Pools.Subpools.Unbounded;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015, 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 STMicroelectronics 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. --
-- --
-- --
-- This file is based on: --
-- --
-- @file stm32f4xx_hal_dac.h and stm32f4xx_hal_dac_ex.h --
-- @author MCD Application Team --
-- @version V1.3.1 --
-- @date 25-March-2015 --
-- @brief Header file of DAC HAL module. --
-- --
-- COPYRIGHT(c) 2014 STMicroelectronics --
------------------------------------------------------------------------------
-- This file provides interfaces for the digital-to-analog converters on the
-- STM32G4 (ARM Cortex M4F) microcontrollers from ST Microelectronics.
with System; use System;
private with STM32_SVD.DAC;
package STM32.DAC is
type Digital_To_Analog_Converter is limited private;
type DAC_Channel is (Channel_1, Channel_2);
-- Note that DAC_1 Channel 1 is tied to GPIO pin PA4 and DAC_1 Channel 2 to
-- PA5.
procedure Enable
(This : in out Digital_To_Analog_Converter;
Channel : DAC_Channel)
with
Inline,
Post => Enabled (This, Channel);
-- Powers up the channel. The channel is then enabled after a startup
-- time "Twakeup" specified in the datasheet.
--
-- NB: When no hardware trigger has been selected, the value in the
-- DAC_DHRx register is transfered automatically to the DAC_DORx register.
-- Therefore, in that case enabling the channel starts the output
-- conversion on that channel. See the RM0433 rev 7, section 26.4.5 "DAC
-- conversion" second and third paragraphs.
procedure Disable
(This : in out Digital_To_Analog_Converter;
Channel : DAC_Channel)
with
Inline,
Post => not Enabled (This, Channel);
-- When the software trigger has been selected, disabling the channel stops
-- the output conversion on that channel.
function Enabled
(This : Digital_To_Analog_Converter;
Channel : DAC_Channel)
return Boolean;
type DAC_Resolution is (DAC_Resolution_12_Bits, DAC_Resolution_8_Bits);
Max_12bit_Resolution : constant := 16#0FFF#;
Max_8bit_Resolution : constant := 16#00FF#;
type Data_Alignment is (Left_Aligned, Right_Aligned);
procedure Set_Output
(This : in out Digital_To_Analog_Converter;
Channel : DAC_Channel;
Value : UInt32;
Resolution : DAC_Resolution;
Alignment : Data_Alignment);
-- For the specified channel, writes the output Value to the data holding
-- register within This corresponding to the Resolution and Alignment.
--
-- The output voltage = ((Value / Max_nbit_Counts) * VRef+), where VRef+ is
-- the reference input voltage and the 'n' of Max_nbit_Counts is either 12
-- or 8.
procedure Trigger_Conversion_By_Software
(This : in out Digital_To_Analog_Converter;
Channel : DAC_Channel)
with
Pre => Trigger_Selection (This, Channel) = Software_Trigger and
Trigger_Enabled (This, Channel);
-- Cause the conversion to occur and the output to appear, per 26.4.7 "DAC
-- trigger selection" in the RM0433 rev 7. This routine is needed when the
-- Software Trigger has been selected and the trigger has been enabled,
-- otherwise no conversion occurs. If you don't enable the trigger any prior
-- selection has no effect, but note that when no *hardware* trigger is
-- selected the output happens automatically when the channel is enabled.
-- See the RM0440 section 26.4.5 "DAC conversion" second and third
-- paragraphs.
function Converted_Output_Value
(This : Digital_To_Analog_Converter;
Channel : DAC_Channel)
return UInt32;
-- Returns the latest output value for the specified channel.
procedure Set_Dual_Output_Voltages
(This : in out Digital_To_Analog_Converter;
Channel_1_Value : UInt32;
Channel_2_Value : UInt32;
Resolution : DAC_Resolution;
Alignment : Data_Alignment);
type Dual_Channel_Output is record
Channel_1_Data : UInt16;
Channel_2_Data : UInt16;
end record;
function Converted_Dual_Output_Value (This : Digital_To_Analog_Converter)
return Dual_Channel_Output;
-- Returns the combination of the latest output values for both channels.
type Channel_Mode is
(Normal_External_Pin_Buffer,
Normal_External_Pin_OnChip_Peripheral_Buffer,
Normal_External_Pin,
Normal_OnChip_Peripheral,
SampleHold_External_Pin_Buffer,
SampleHold_External_Pin_OnChip_Peripheral_Buffer,
SampleHold_External_Pin_OnChip_Peripheral,
SampleHold_OnChip_Peripheral);
procedure Configure_Channel_Mode
(This : in out Digital_To_Analog_Converter;
Channel : DAC_Channel;
Mode : Channel_Mode)
with
Pre => not Enabled (This, Channel) and
not Read_Calibration_Mode (This, Channel),
Post => Read_Channel_Mode (This, Channel) = Mode;
function Read_Channel_Mode
(This : Digital_To_Analog_Converter;
Channel : DAC_Channel)
return Channel_Mode;
procedure Configure_Sample_Hold_Time
(This : in out Digital_To_Analog_Converter;
Channel : DAC_Channel;
Sample : UInt10;
Hold : UInt10;
Refresh : UInt8);
-- Configure the sample, hold and refresh timing when in Sample & Hold mode
-- In this mode, the DAC core and all corresponding logic and registers are
-- driven by the LSI or LSE low-speed clock (dac_hold_ck) in addition to
-- the dac_hclk clock, so these timings are based on these clock sources.
-- See UM0433 rev 7 chapter 26.4.11 DAC channel modes pg. 1061 for
-- timing examples.
type External_Event_Trigger_Selection is
(Software_Trigger,
TIM1_TRGO,
TIM2_TRGO,
TIM4_TRGO,
TIM5_TRGO,
TIM6_TRGO,
TIM7_TRGO,
TIM8_TRGO,
TIM15_TRGO,
HRTIM_DAC_Trigger_1,
HRTIM_DAC_Trigger_2,
LPTIM1_OUT,
LPTIM2_OUT,
EXTI_Line_9_Trigger) -- any GPIO_x Pin_9
with Size => 4;
-- Refer to UM0433 rev 7 chapter 26.4.2 for DAC pins and internal signals.
procedure Select_Trigger
(This : in out Digital_To_Analog_Converter;
Channel : DAC_Channel;
Trigger : External_Event_Trigger_Selection)
with
Pre => not Trigger_Enabled (This, Channel), -- per note in RM, pg 435
Post => Trigger_Selection (This, Channel) = Trigger and
not Trigger_Enabled (This, Channel);
-- If the software trigger is selected, output conversion starts once the
-- channel is enabled.
function Trigger_Selection
(This : Digital_To_Analog_Converter;
Channel : DAC_Channel)
return External_Event_Trigger_Selection;
procedure Enable_Trigger
(This : in out Digital_To_Analog_Converter;
Channel : DAC_Channel)
with Post => Trigger_Enabled (This, Channel);
procedure Disable_Trigger
(This : in out Digital_To_Analog_Converter;
Channel : DAC_Channel)
with Post => not Trigger_Enabled (This, Channel);
function Trigger_Enabled
(This : Digital_To_Analog_Converter;
Channel : DAC_Channel)
return Boolean;
procedure Enable_DMA
(This : in out Digital_To_Analog_Converter;
Channel : DAC_Channel)
with Post => DMA_Enabled (This, Channel);
procedure Disable_DMA
(This : in out Digital_To_Analog_Converter;
Channel : DAC_Channel)
with Post => not DMA_Enabled (This, Channel);
function DMA_Enabled
(This : Digital_To_Analog_Converter;
Channel : DAC_Channel)
return Boolean;
type DAC_Status_Flag is
(DMA_Underrun_Channel_1,
DMA_Underrun_Channel_2,
Calibration_EQGT_Offset_Channel_1,
Calibration_EQGT_Offset_Channel_2,
Write_Operation_Busy_Channel_1,
Write_Operation_Busy_Channel_2);
function Status
(This : Digital_To_Analog_Converter;
Flag : DAC_Status_Flag)
return Boolean;
procedure Clear_Status
(This : in out Digital_To_Analog_Converter;
Flag : DAC_Status_Flag)
with
Inline,
Post => not Status (This, Flag);
type DAC_Interrupts is
(DMA_Underrun_Channel_1,
DMA_Underrun_Channel_2);
procedure Enable_Interrupts
(This : in out Digital_To_Analog_Converter;
Source : DAC_Interrupts)
with
Inline,
Post => Interrupt_Enabled (This, Source);
procedure Disable_Interrupts
(This : in out Digital_To_Analog_Converter;
Source : DAC_Interrupts)
with
Inline,
Post => not Interrupt_Enabled (This, Source);
function Interrupt_Enabled
(This : Digital_To_Analog_Converter;
Source : DAC_Interrupts)
return Boolean
with Inline;
procedure Clear_Interrupt_Pending
(This : in out Digital_To_Analog_Converter;
Channel : DAC_Channel)
with Inline;
type Wave_Generation_Selection is
(No_Wave_Generation,
Noise_Wave,
Triangle_Wave,
Sawtooth_Wave);
type Noise_Wave_Mask_Selection is
(LFSR_Unmask_Bit0,
LFSR_Unmask_Bits1_0,
LFSR_Unmask_Bits2_0,
LFSR_Unmask_Bits3_0,
LFSR_Unmask_Bits4_0,
LFSR_Unmask_Bits5_0,
LFSR_Unmask_Bits6_0,
LFSR_Unmask_Bits7_0,
LFSR_Unmask_Bits8_0,
LFSR_Unmask_Bits9_0,
LFSR_Unmask_Bits10_0,
LFSR_Unmask_Bits11_0);
-- Unmask LFSR bits for noise wave generation
type Triangle_Wave_Amplitude_Selection is
(Triangle_Amplitude_1, -- Select max triangle amplitude of 1
Triangle_Amplitude_3, -- Select max triangle amplitude of 3
Triangle_Amplitude_7, -- Select max triangle amplitude of 7
Triangle_Amplitude_15, -- Select max triangle amplitude of 15
Triangle_Amplitude_31, -- Select max triangle amplitude of 31
Triangle_Amplitude_63, -- Select max triangle amplitude of 63
Triangle_Amplitude_127, -- Select max triangle amplitude of 127
Triangle_Amplitude_255, -- Select max triangle amplitude of 255
Triangle_Amplitude_511, -- Select max triangle amplitude of 511
Triangle_Amplitude_1023, -- Select max triangle amplitude of 1023
Triangle_Amplitude_2047, -- Select max triangle amplitude of 2047
Triangle_Amplitude_4095); -- Select max triangle amplitude of 4095
type Wave_Generation (Kind : Wave_Generation_Selection) is record
case Kind is
when No_Wave_Generation =>
null;
when Noise_Wave =>
Mask : Noise_Wave_Mask_Selection;
when Triangle_Wave .. Sawtooth_Wave =>
Amplitude : Triangle_Wave_Amplitude_Selection;
end case;
end record;
Wave_Generation_Disabled : constant Wave_Generation :=
(Kind => No_Wave_Generation);
procedure Select_Wave_Generation
(This : in out Digital_To_Analog_Converter;
Channel : DAC_Channel;
Selection : Wave_Generation)
with Post => Selected_Wave_Generation (This, Channel) = Selection;
function Selected_Wave_Generation
(This : Digital_To_Analog_Converter;
Channel : DAC_Channel)
return Wave_Generation;
function Data_Address
(This : Digital_To_Analog_Converter;
Channel : DAC_Channel;
Resolution : DAC_Resolution;
Alignment : Data_Alignment)
return Address;
-- Returns the address of the Data Holding register within This, for the
-- specified Channel, at the specified Resolution and Alignment.
--
-- This function is stricly for use with DMA, all others use the API above.
procedure Set_Calibration_Mode
(This : in out Digital_To_Analog_Converter;
Channel : DAC_Channel;
Mode : Boolean)
with Post => Read_Calibration_Mode (This, Channel) = Mode;
function Read_Calibration_Mode
(This : Digital_To_Analog_Converter;
Channel : DAC_Channel)
return Boolean;
function Read_Calibration_Flag
(This : Digital_To_Analog_Converter;
Channel : DAC_Channel)
return Boolean;
procedure Set_Offset_Trimming
(This : in out Digital_To_Analog_Converter;
Channel : DAC_Channel;
Input : UInt5);
procedure Calibrate
(This : in out Digital_To_Analog_Converter;
Channel : DAC_Channel);
-- Calibrate the DAC channel. This routine is described in RM0433 rev 7
-- chapter 26.4.12 - DAC channel buffer calibration pg. 1064.
private
type Digital_To_Analog_Converter is new STM32_SVD.DAC.DAC_Peripheral;
end STM32.DAC;
|
-- This package has been generated automatically by GNATtest.
-- You are allowed to add your code to the bodies of test routines.
-- Such changes will be kept during further regeneration of this file.
-- All code placed outside of test routine bodies will be lost. The
-- code intended to set up and tear down the test environment should be
-- placed into Game.Test_Data.
with AUnit.Assertions; use AUnit.Assertions;
with System.Assertions;
-- begin read only
-- id:2.2/00/
--
-- This section can be used to add with clauses if necessary.
--
-- end read only
with Messages; use Messages;
with Config; use Config;
-- begin read only
-- end read only
package body Game.Test_Data.Tests is
-- begin read only
-- id:2.2/01/
--
-- This section can be used to add global variables and other elements.
--
-- end read only
-- begin read only
-- end read only
-- begin read only
procedure Wrap_Test_Update_Game_25a566_5306b6
(Minutes: Positive; In_Combat: Boolean := False) is
begin
GNATtest_Generated.GNATtest_Standard.Game.Update_Game
(Minutes, In_Combat);
end Wrap_Test_Update_Game_25a566_5306b6;
-- end read only
-- begin read only
procedure Test_Update_Game_test_updategame(Gnattest_T: in out Test);
procedure Test_Update_Game_25a566_5306b6(Gnattest_T: in out Test) renames
Test_Update_Game_test_updategame;
-- id:2.2/25a566d308fb13f6/Update_Game/1/0/test_updategame/
procedure Test_Update_Game_test_updategame(Gnattest_T: in out Test) is
procedure Update_Game
(Minutes: Positive; In_Combat: Boolean := False) renames
Wrap_Test_Update_Game_25a566_5306b6;
-- end read only
pragma Unreferenced(Gnattest_T);
Minutes: constant Natural := Game_Date.Minutes;
begin
Update_Game(1);
Assert(Minutes + 1 = Game_Date.Minutes, "Failed to update game time.");
-- begin read only
end Test_Update_Game_test_updategame;
-- end read only
-- begin read only
procedure Wrap_Test_End_Game_29871f_745ef4(Save: Boolean) is
begin
GNATtest_Generated.GNATtest_Standard.Game.End_Game(Save);
end Wrap_Test_End_Game_29871f_745ef4;
-- end read only
-- begin read only
procedure Test_End_Game_test_endgame(Gnattest_T: in out Test);
procedure Test_End_Game_29871f_745ef4(Gnattest_T: in out Test) renames
Test_End_Game_test_endgame;
-- id:2.2/29871f76a299de21/End_Game/1/0/test_endgame/
procedure Test_End_Game_test_endgame(Gnattest_T: in out Test) is
procedure End_Game(Save: Boolean) renames
Wrap_Test_End_Game_29871f_745ef4;
-- end read only
pragma Unreferenced(Gnattest_T);
begin
End_Game(False);
Assert(Messages_List.Length = 0, "Failed to clear old game data.");
New_Game_Settings.Player_Faction := To_Unbounded_String("POLEIS");
New_Game_Settings.Player_Career := To_Unbounded_String("general");
New_Game_Settings.Starting_Base := To_Unbounded_String("1");
New_Game;
-- begin read only
end Test_End_Game_test_endgame;
-- end read only
-- begin read only
function Wrap_Test_Find_Skill_Index_800ce5_5e7804
(Skill_Name: String) return Natural is
begin
begin
pragma Assert(Skill_Name'Length > 0);
null;
exception
when System.Assertions.Assert_Failure =>
AUnit.Assertions.Assert
(False,
"req_sloc(game.ads:0):Test_FindSkillIndex test requirement violated");
end;
declare
Test_Find_Skill_Index_800ce5_5e7804_Result: constant Natural :=
GNATtest_Generated.GNATtest_Standard.Game.Find_Skill_Index
(Skill_Name);
begin
begin
pragma Assert
(Test_Find_Skill_Index_800ce5_5e7804_Result <=
Natural(SkillsData_Container.Length(Container => Skills_List)));
null;
exception
when System.Assertions.Assert_Failure =>
AUnit.Assertions.Assert
(False,
"ens_sloc(game.ads:0:):Test_FindSkillIndex test commitment violated");
end;
return Test_Find_Skill_Index_800ce5_5e7804_Result;
end;
end Wrap_Test_Find_Skill_Index_800ce5_5e7804;
-- end read only
-- begin read only
procedure Test_Find_Skill_Index_test_findskillindex
(Gnattest_T: in out Test);
procedure Test_Find_Skill_Index_800ce5_5e7804
(Gnattest_T: in out Test) renames
Test_Find_Skill_Index_test_findskillindex;
-- id:2.2/800ce528dff2e51d/Find_Skill_Index/1/0/test_findskillindex/
procedure Test_Find_Skill_Index_test_findskillindex
(Gnattest_T: in out Test) is
function Find_Skill_Index(Skill_Name: String) return Natural renames
Wrap_Test_Find_Skill_Index_800ce5_5e7804;
-- end read only
pragma Unreferenced(Gnattest_T);
begin
Assert
(Find_Skill_Index("Piloting") = 1, "Failed to find existing skill.");
Assert
(Find_Skill_Index("sdljfskfhsf") = 0,
"Failed to not find non exisiting skill.");
-- begin read only
end Test_Find_Skill_Index_test_findskillindex;
-- end read only
-- begin read only
-- id:2.2/02/
--
-- This section can be used to add elaboration code for the global state.
--
begin
-- end read only
null;
-- begin read only
-- end read only
end Game.Test_Data.Tests;
|
-----------------------------------------------------------------------
-- html -- ASF HTML Components
-- Copyright (C) 2009, 2010, 2011, 2017, 2018 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 ASF.Components.Holders;
with ASF.Converters;
-- The <b>Text</b> package implements various components used to print text outputs.
--
-- See JSR 314 - JavaServer Faces Specification 4.1.10 UIOutput
--
-- The <b>UILabel</b> and <b>UIOutputFormat</b> components is ASF implementation of
-- the JavaServer Faces outputLabel and outputFormat components
-- (implemented with UIOutput in Java).
package ASF.Components.Html.Text is
-- ------------------------------
-- Output Component
-- ------------------------------
type UIOutput is new UIHtmlComponent and Holders.Value_Holder with private;
-- Get the local value of the component without evaluating
-- the associated Value_Expression.
overriding
function Get_Local_Value (UI : in UIOutput) return EL.Objects.Object;
-- Get the value of the component. If the component has a local
-- value which is not null, returns it. Otherwise, if we have a Value_Expression
-- evaluate and returns the value.
overriding
function Get_Value (UI : in UIOutput) return EL.Objects.Object;
-- Set the value to write on the output.
overriding
procedure Set_Value (UI : in out UIOutput;
Value : in EL.Objects.Object);
-- Get the converter that is registered on the component.
overriding
function Get_Converter (UI : in UIOutput)
return ASF.Converters.Converter_Access;
-- Set the converter to be used on the component.
overriding
procedure Set_Converter (UI : in out UIOutput;
Converter : in ASF.Converters.Converter_Access;
Release : in Boolean := False);
-- Get the converter associated with the component
function Get_Converter (UI : in UIOutput;
Context : in Faces_Context'Class)
return access ASF.Converters.Converter'Class;
overriding
procedure Finalize (UI : in out UIOutput);
-- Get the value of the component and apply the To_String converter on it if there is one.
function Get_Formatted_Value (UI : in UIOutput;
Context : in Contexts.Faces.Faces_Context'Class) return String;
-- Format the value by appling the To_String converter on it if there is one.
function Get_Formatted_Value (UI : in UIOutput;
Value : in Util.Beans.Objects.Object;
Context : in Contexts.Faces.Faces_Context'Class) return String;
procedure Write_Output (UI : in UIOutput;
Context : in out Contexts.Faces.Faces_Context'Class;
Value : in String);
procedure Encode_Begin (UI : in UIOutput;
Context : in out Contexts.Faces.Faces_Context'Class);
-- ------------------------------
-- Label Component
-- ------------------------------
type UIOutputLabel is new UIOutput with private;
procedure Encode_Begin (UI : in UIOutputLabel;
Context : in out Contexts.Faces.Faces_Context'Class);
procedure Encode_End (UI : in UIOutputLabel;
Context : in out Contexts.Faces.Faces_Context'Class);
-- ------------------------------
-- OutputFormat Component
-- ------------------------------
--
type UIOutputFormat is new UIOutput with private;
procedure Encode_Begin (UI : in UIOutputFormat;
Context : in out Contexts.Faces.Faces_Context'Class);
private
type UIOutput is new UIHtmlComponent and Holders.Value_Holder with record
Value : EL.Objects.Object;
Converter : ASF.Converters.Converter_Access := null;
Release_Converter : Boolean := False;
end record;
type UIOutputLabel is new UIOutput with null record;
type UIOutputFormat is new UIOutput with null record;
end ASF.Components.Html.Text;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- M A K E U T L --
-- --
-- B o d y --
-- --
-- Copyright (C) 2004-2005 Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
-- Boston, MA 02110-1301, USA. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Namet; use Namet;
with Osint; use Osint;
with Prj.Ext;
with Prj.Util;
with Snames; use Snames;
with Table;
with System.HTable;
package body Makeutl is
type Mark_Key is record
File : File_Name_Type;
Index : Int;
end record;
-- Identify either a mono-unit source (when Index = 0) or a specific unit
-- in a multi-unit source.
-- There follow many global undocumented declarations, comments needed ???
Max_Mask_Num : constant := 2048;
subtype Mark_Num is Union_Id range 0 .. Max_Mask_Num - 1;
function Hash (Key : Mark_Key) return Mark_Num;
package Marks is new System.HTable.Simple_HTable
(Header_Num => Mark_Num,
Element => Boolean,
No_Element => False,
Key => Mark_Key,
Hash => Hash,
Equal => "=");
-- A hash table to keep tracks of the marked units
type Linker_Options_Data is record
Project : Project_Id;
Options : String_List_Id;
end record;
Linker_Option_Initial_Count : constant := 20;
Linker_Options_Buffer : String_List_Access :=
new String_List (1 .. Linker_Option_Initial_Count);
Last_Linker_Option : Natural := 0;
package Linker_Opts is new Table.Table (
Table_Component_Type => Linker_Options_Data,
Table_Index_Type => Integer,
Table_Low_Bound => 1,
Table_Initial => 10,
Table_Increment => 100,
Table_Name => "Make.Linker_Opts");
procedure Add_Linker_Option (Option : String);
-----------------------
-- Add_Linker_Option --
-----------------------
procedure Add_Linker_Option (Option : String) is
begin
if Option'Length > 0 then
if Last_Linker_Option = Linker_Options_Buffer'Last then
declare
New_Buffer : constant String_List_Access :=
new String_List
(1 .. Linker_Options_Buffer'Last +
Linker_Option_Initial_Count);
begin
New_Buffer (Linker_Options_Buffer'Range) :=
Linker_Options_Buffer.all;
Linker_Options_Buffer.all := (others => null);
Free (Linker_Options_Buffer);
Linker_Options_Buffer := New_Buffer;
end;
end if;
Last_Linker_Option := Last_Linker_Option + 1;
Linker_Options_Buffer (Last_Linker_Option) := new String'(Option);
end if;
end Add_Linker_Option;
----------------------
-- Delete_All_Marks --
----------------------
procedure Delete_All_Marks is
begin
Marks.Reset;
end Delete_All_Marks;
----------
-- Hash --
----------
function Hash (Key : Mark_Key) return Mark_Num is
begin
return Union_Id (Key.File) mod Max_Mask_Num;
end Hash;
----------------------------
-- Is_External_Assignment --
----------------------------
function Is_External_Assignment (Argv : String) return Boolean is
Start : Positive := 3;
Finish : Natural := Argv'Last;
Equal_Pos : Natural;
begin
if Argv'Last < 5 then
return False;
elsif Argv (3) = '"' then
if Argv (Argv'Last) /= '"' or else Argv'Last < 7 then
return False;
else
Start := 4;
Finish := Argv'Last - 1;
end if;
end if;
Equal_Pos := Start;
while Equal_Pos <= Finish and then Argv (Equal_Pos) /= '=' loop
Equal_Pos := Equal_Pos + 1;
end loop;
if Equal_Pos = Start
or else Equal_Pos >= Finish
then
return False;
else
Prj.Ext.Add
(External_Name => Argv (Start .. Equal_Pos - 1),
Value => Argv (Equal_Pos + 1 .. Finish));
return True;
end if;
end Is_External_Assignment;
---------------
-- Is_Marked --
---------------
function Is_Marked
(Source_File : File_Name_Type;
Index : Int := 0) return Boolean
is
begin
return Marks.Get (K => (File => Source_File, Index => Index));
end Is_Marked;
-----------------------------
-- Linker_Options_Switches --
-----------------------------
function Linker_Options_Switches
(Project : Project_Id;
In_Tree : Project_Tree_Ref) return String_List
is
procedure Recursive_Add_Linker_Options (Proj : Project_Id);
-- The recursive routine used to add linker options
----------------------------------
-- Recursive_Add_Linker_Options --
----------------------------------
procedure Recursive_Add_Linker_Options (Proj : Project_Id) is
Data : Project_Data;
Linker_Package : Package_Id;
Options : Variable_Value;
Imported : Project_List;
begin
if Proj /= No_Project then
Data := In_Tree.Projects.Table (Proj);
if not Data.Seen then
In_Tree.Projects.Table (Proj).Seen := True;
Imported := Data.Imported_Projects;
while Imported /= Empty_Project_List loop
Recursive_Add_Linker_Options
(In_Tree.Project_Lists.Table
(Imported).Project);
Imported := In_Tree.Project_Lists.Table
(Imported).Next;
end loop;
if Proj /= Project then
Linker_Package :=
Prj.Util.Value_Of
(Name => Name_Linker,
In_Packages => Data.Decl.Packages,
In_Tree => In_Tree);
Options :=
Prj.Util.Value_Of
(Name => Name_Ada,
Index => 0,
Attribute_Or_Array_Name => Name_Linker_Options,
In_Package => Linker_Package,
In_Tree => In_Tree);
-- If attribute is present, add the project with
-- the attribute to table Linker_Opts.
if Options /= Nil_Variable_Value then
Linker_Opts.Increment_Last;
Linker_Opts.Table (Linker_Opts.Last) :=
(Project => Proj, Options => Options.Values);
end if;
end if;
end if;
end if;
end Recursive_Add_Linker_Options;
-- Start of processing for Linker_Options_Switches
begin
Linker_Opts.Init;
for Index in Project_Table.First ..
Project_Table.Last (In_Tree.Projects)
loop
In_Tree.Projects.Table (Index).Seen := False;
end loop;
Recursive_Add_Linker_Options (Project);
Last_Linker_Option := 0;
for Index in reverse 1 .. Linker_Opts.Last loop
declare
Options : String_List_Id := Linker_Opts.Table (Index).Options;
Proj : constant Project_Id :=
Linker_Opts.Table (Index).Project;
Option : Name_Id;
begin
-- If Dir_Path has not been computed for this project, do it now
if In_Tree.Projects.Table (Proj).Dir_Path = null then
In_Tree.Projects.Table (Proj).Dir_Path :=
new String'
(Get_Name_String
(In_Tree.Projects.Table
(Proj). Directory));
end if;
while Options /= Nil_String loop
Option :=
In_Tree.String_Elements.Table (Options).Value;
Get_Name_String (Option);
-- Do not consider empty linker options
if Name_Len /= 0 then
Add_Linker_Option (Name_Buffer (1 .. Name_Len));
-- Object files and -L switches specified with relative
-- paths must be converted to absolute paths.
Test_If_Relative_Path
(Switch =>
Linker_Options_Buffer (Last_Linker_Option),
Parent =>
In_Tree.Projects.Table (Proj).Dir_Path,
Including_L_Switch => True);
end if;
Options :=
In_Tree.String_Elements.Table (Options).Next;
end loop;
end;
end loop;
return Linker_Options_Buffer (1 .. Last_Linker_Option);
end Linker_Options_Switches;
-----------
-- Mains --
-----------
package body Mains is
package Names is new Table.Table
(Table_Component_Type => File_Name_Type,
Table_Index_Type => Integer,
Table_Low_Bound => 1,
Table_Initial => 10,
Table_Increment => 100,
Table_Name => "Makeutl.Mains.Names");
-- The table that stores the mains
Current : Natural := 0;
-- The index of the last main retrieved from the table
--------------
-- Add_Main --
--------------
procedure Add_Main (Name : String) is
begin
Name_Len := 0;
Add_Str_To_Name_Buffer (Name);
Names.Increment_Last;
Names.Table (Names.Last) := Name_Find;
end Add_Main;
------------
-- Delete --
------------
procedure Delete is
begin
Names.Set_Last (0);
Mains.Reset;
end Delete;
---------------
-- Next_Main --
---------------
function Next_Main return String is
begin
if Current >= Names.Last then
return "";
else
Current := Current + 1;
return Get_Name_String (Names.Table (Current));
end if;
end Next_Main;
---------------------
-- Number_Of_Mains --
---------------------
function Number_Of_Mains return Natural is
begin
return Names.Last;
end Number_Of_Mains;
-----------
-- Reset --
-----------
procedure Reset is
begin
Current := 0;
end Reset;
end Mains;
----------
-- Mark --
----------
procedure Mark (Source_File : File_Name_Type; Index : Int := 0) is
begin
Marks.Set (K => (File => Source_File, Index => Index), E => True);
end Mark;
---------------------------
-- Test_If_Relative_Path --
---------------------------
procedure Test_If_Relative_Path
(Switch : in out String_Access;
Parent : String_Access;
Including_L_Switch : Boolean := True)
is
begin
if Switch /= null then
declare
Sw : String (1 .. Switch'Length);
Start : Positive;
begin
Sw := Switch.all;
if Sw (1) = '-' then
if Sw'Length >= 3
and then (Sw (2) = 'A'
or else Sw (2) = 'I'
or else (Including_L_Switch and then Sw (2) = 'L'))
then
Start := 3;
if Sw = "-I-" then
return;
end if;
elsif Sw'Length >= 4
and then (Sw (2 .. 3) = "aL"
or else Sw (2 .. 3) = "aO"
or else Sw (2 .. 3) = "aI")
then
Start := 4;
else
return;
end if;
-- Because relative path arguments to --RTS= may be relative
-- to the search directory prefix, those relative path
-- arguments are not converted.
if not Is_Absolute_Path (Sw (Start .. Sw'Last)) then
if Parent = null or else Parent'Length = 0 then
Do_Fail
("relative search path switches (""",
Sw,
""") are not allowed");
else
Switch :=
new String'
(Sw (1 .. Start - 1) &
Parent.all &
Directory_Separator &
Sw (Start .. Sw'Last));
end if;
end if;
else
if not Is_Absolute_Path (Sw) then
if Parent = null or else Parent'Length = 0 then
Do_Fail
("relative paths (""", Sw, """) are not allowed");
else
Switch :=
new String'(Parent.all & Directory_Separator & Sw);
end if;
end if;
end if;
end;
end if;
end Test_If_Relative_Path;
-------------------
-- Unit_Index_Of --
-------------------
function Unit_Index_Of (ALI_File : File_Name_Type) return Int is
Start : Natural;
Finish : Natural;
Result : Int := 0;
begin
Get_Name_String (ALI_File);
-- First, find the last dot
Finish := Name_Len;
while Finish >= 1 and then Name_Buffer (Finish) /= '.' loop
Finish := Finish - 1;
end loop;
if Finish = 1 then
return 0;
end if;
-- Now check that the dot is preceded by digits
Start := Finish;
Finish := Finish - 1;
while Start >= 1 and then Name_Buffer (Start - 1) in '0' .. '9' loop
Start := Start - 1;
end loop;
-- If there is no difits, or if the digits are not preceded by
-- the character that precedes a unit index, this is not the ALI file
-- of a unit in a multi-unit source.
if Start > Finish
or else Start = 1
or else Name_Buffer (Start - 1) /= Multi_Unit_Index_Character
then
return 0;
end if;
-- Build the index from the digit(s)
while Start <= Finish loop
Result := Result * 10 +
Character'Pos (Name_Buffer (Start)) - Character'Pos ('0');
Start := Start + 1;
end loop;
return Result;
end Unit_Index_Of;
end Makeutl;
|
with System.Wid_Char;
package body System.Wid_WChar is
function Width_Wide_Character (Lo, Hi : Wide_Character) return Natural is
begin
if Lo > Hi then
return 0;
elsif Hi <= Wide_Character'Val (16#7f#) then
return Wid_Char.Width_Character (
Character'Val (Wide_Character'Pos (Lo)),
Character'Val (Wide_Character'Pos (Hi)));
else
return 8; -- "Hex_XXXX"
end if;
end Width_Wide_Character;
function Width_Wide_Wide_Character (Lo, Hi : Wide_Wide_Character)
return Natural is
begin
if Lo > Hi then
return 0;
elsif Hi <= Wide_Wide_Character'Val (16#7f#) then
return Wid_Char.Width_Character (
Character'Val (Wide_Wide_Character'Pos (Lo)),
Character'Val (Wide_Wide_Character'Pos (Hi)));
else
return 12; -- "Hex_XXXXXXXX"
end if;
end Width_Wide_Wide_Character;
end System.Wid_WChar;
|
with TEXT_IO;
package PREFACE is
procedure PUT(S: STRING);
procedure SET_COL(PC : TEXT_IO.POSITIVE_COUNT);
procedure PUT_LINE(S : STRING);
procedure NEW_LINE(SPACING : TEXT_IO.POSITIVE_COUNT := 1);
procedure PUT(N : INTEGER; WIDTH : TEXT_IO.FIELD := INTEGER'WIDTH);
end PREFACE;
|
-- part of OpenGLAda, (c) 2017 Felix Krause
-- released under the terms of the MIT license, see the file "COPYING"
with Glfw.Enums;
with Glfw.Display;
with Glfw.Events.Keys;
with Glfw.Events.Mouse;
with Glfw.Events.Joysticks;
with Interfaces.C.Strings;
with System;
private package Glfw.API is
type Raw_Video_Mode is array (1 .. 5) of aliased C.int;
pragma Convention (C, Raw_Video_Mode);
type Video_Mode_List is array (Positive range <>) of Raw_Video_Mode;
pragma Convention (C, Video_Mode_List);
type Window_Size_Callback is access procedure (Width, Height : C.int);
type Window_Close_Callback is access function return Bool;
type Window_Refresh_Callback is access procedure;
type Key_Callback is access procedure (Subject : Events.Keys.Key;
Action : Events.Button_State);
type Character_Callback is access procedure
(Unicode_Char : Events.Keys.Unicode_Character; Action : Events.Button_State);
type Button_Callback is access procedure (Subject : Events.Mouse.Button;
Action : Events.Button_State);
type Position_Callback is access procedure (X, Y : Events.Mouse.Coordinate);
type Wheel_Callback is access procedure (Pos : Events.Mouse.Wheel_Position);
pragma Convention (C, Window_Size_Callback);
pragma Convention (C, Window_Close_Callback);
pragma Convention (C, Window_Refresh_Callback);
pragma Convention (C, Key_Callback);
pragma Convention (C, Character_Callback);
pragma Convention (C, Button_Callback);
pragma Convention (C, Position_Callback);
pragma Convention (C, Wheel_Callback);
function Init return C.int;
pragma Import (Convention => C, Entity => Init,
External_Name => "glfwInit");
procedure Glfw_Terminate;
pragma Import (Convention => C, Entity => Glfw_Terminate,
External_Name => "glfwTerminate");
procedure Get_Version (Major, Minor, Revision : out C.int);
pragma Import (Convention => C, Entity => Get_Version,
External_Name => "glfwGetVersion");
function Open_Window (Width, Height, Red_Bits, Green_Bits, Blue_Bits,
Alpha_Bits, Depth_Bits, Stencil_Bits : C.int;
Mode : Display.Display_Mode) return Bool;
pragma Import (Convention => C, Entity => Open_Window,
External_Name => "glfwOpenWindow");
procedure Open_Window_Hint (Target : Glfw.Enums.Window_Hint; Info : C.int);
procedure Open_Window_Hint (Target : Glfw.Enums.Window_Hint; Info : Bool);
procedure Open_Window_Hint (Target : Glfw.Enums.Window_Hint;
Info : Display.OpenGL_Profile_Kind);
pragma Import (Convention => C, Entity => Open_Window_Hint,
External_Name => "glfwOpenWindowHint");
procedure Close_Window;
pragma Import (Convention => C, Entity => Close_Window,
External_Name => "glfwCloseWindow");
procedure Set_Window_Title (Title : C.Strings.chars_ptr);
pragma Import (Convention => C, Entity => Set_Window_Title,
External_Name => "glfwSetWindowTitle");
procedure Get_Window_Size (Width, Height : out C.int);
pragma Import (Convention => C, Entity => Get_Window_Size,
External_Name => "glfwGetWindowSize");
procedure Set_Window_Size (Width, Height : C.int);
pragma Import (Convention => C, Entity => Set_Window_Size,
External_Name => "glfwSetWindowSize");
procedure Set_Window_Pos (X, Y : C.int);
pragma Import (Convention => C, Entity => Set_Window_Pos,
External_Name => "glfwSetWindowPos");
procedure Iconify_Window;
pragma Import (Convention => C, Entity => Iconify_Window,
External_Name => "glfwIconifyWindow");
procedure Restore_Window;
pragma Import (Convention => C, Entity => Restore_Window,
External_Name => "glfwRestoreWindow");
procedure Swap_Buffers;
pragma Import (Convention => C, Entity => Swap_Buffers,
External_Name => "glfwSwapBuffers");
procedure Swap_Interval (Interval : C.int);
pragma Import (Convention => C, Entity => Swap_Interval,
External_Name => "glfwSwapInterval");
function Get_Window_Param (Param : Enums.Window_Info) return C.int;
function Get_Window_Param (Param : Enums.Window_Info) return Bool;
function Get_Window_Param (Param : Enums.Window_Info) return Display.OpenGL_Profile_Kind;
pragma Import (Convention => C, Entity => Get_Window_Param,
External_Name => "glfwGetWindowParam");
procedure Set_Window_Size_Callback (Cb : Window_Size_Callback);
pragma Import (Convention => C, Entity => Set_Window_Size_Callback,
External_Name => "glfwSetWindowSizeCallback");
procedure Set_Window_Close_Callback (Cb : Window_Close_Callback);
pragma Import (Convention => C, Entity => Set_Window_Close_Callback,
External_Name => "glfwSetWindowCloseCallback");
procedure Set_Window_Refresh_Callback (Cb : Window_Refresh_Callback);
pragma Import (Convention => C, Entity => Set_Window_Refresh_Callback,
External_Name => "glfwSetWindowCloseCallback");
function Get_Video_Modes (List : System.Address;
Max_Count : C.int) return C.int;
pragma Import (Convention => C, Entity => Get_Video_Modes,
External_Name => "glfwGetVideoModes");
procedure Get_Desktop_Mode (Mode : access C.int);
pragma Import (Convention => C, Entity => Get_Desktop_Mode,
External_Name => "glfwGetDesktopMode");
procedure Poll_Events;
pragma Import (Convention => C, Entity => Poll_Events,
External_Name => "glfwPollEvents");
procedure Wait_Events;
pragma Import (Convention => C, Entity => Wait_Events,
External_Name => "glfwWaitEvents");
function Get_Key (Key : Glfw.Events.Keys.Key) return Glfw.Events.Button_State;
pragma Import (Convention => C, Entity => Get_Key,
External_Name => "glfwGetKey");
function Get_Mouse_Button (Button : Glfw.Events.Mouse.Button)
return Glfw.Events.Button_State;
pragma Import (Convention => C, Entity => Get_Mouse_Button,
External_Name => "glfwGetMouseButton");
procedure Get_Mouse_Pos (XPos, YPos : out C.int);
pragma Import (Convention => C, Entity => Get_Mouse_Pos,
External_Name => "glfwGetMousePos");
procedure Set_Mouse_Pos (XPos, YPos : C.int);
pragma Import (Convention => C, Entity => Set_Mouse_Pos,
External_Name => "glfwSetMousePos");
function Get_Mouse_Wheel return Events.Mouse.Wheel_Position;
pragma Import (Convention => C, Entity => Get_Mouse_Wheel,
External_Name => "glfwGetMouseWheel");
procedure Set_Mouse_Wheel (Position : C.int);
pragma Import (Convention => C, Entity => Set_Mouse_Wheel,
External_Name => "glfwSetMouseWheel");
procedure Set_Key_Callback (CbFun : Key_Callback);
pragma Import (Convention => C, Entity => Set_Key_Callback,
External_Name => "glfwSetKeyCallback");
procedure Set_Char_Callback (CbFun : Character_Callback);
pragma Import (Convention => C, Entity => Set_Char_Callback,
External_Name => "glfwSetCharCallback");
procedure Set_Mouse_Button_Callback (CbFun : Button_Callback);
pragma Import (Convention => C, Entity => Set_Mouse_Button_Callback,
External_Name => "glfwSetMouseButtonCallback");
procedure Set_Mouse_Pos_Callback (CbFun : Position_Callback);
pragma Import (Convention => C, Entity => Set_Mouse_Pos_Callback,
External_Name => "glfwSetMousePosCallback");
procedure Set_Mouse_Wheel_Callback (CbFun : Wheel_Callback);
pragma Import (Convention => C, Entity => Set_Mouse_Wheel_Callback,
External_Name => "glfwSetMouseWheelCallback");
function Get_Joystick_Param (Joy : Enums.Joystick_ID;
Param : Enums.Joystick_Param)
return Interfaces.C.int;
pragma Import (Convention => C, Entity => Get_Joystick_Param,
External_Name => "glfwGetJoystickParam");
-- Pos will be modified on the C side. It should be declared
-- as 'in out' but Ada 2005 forbids that. Since is works fine this
-- way, we don't bother using C pointers instead that wouldn't
-- make the API any clearer.
function Get_Joystick_Pos (Joy : Enums.Joystick_ID;
Pos : Events.Joysticks.Axis_Positions;
Num_Axis : Interfaces.C.int)
return Interfaces.C.int;
pragma Import (Convention => C, Entity => Get_Joystick_Pos,
External_Name => "glfwGetJoystickPos");
-- See comment on Get_Joystick_Pos
function Get_Joystick_Buttons (Joy : Enums.Joystick_ID;
Pos : Events.Button_States;
Num_Buttons : Interfaces.C.int)
return Interfaces.C.int;
pragma Import (Convention => C, Entity => Get_Joystick_Buttons,
External_Name => "glfwGetJoystickButtons");
function Get_Time return C.double;
pragma Import (Convention => C, Entity => Get_Time,
External_Name => "glfwGetTime");
procedure Set_Time (Value : C.double);
pragma Import (Convention => C, Entity => Set_Time,
External_Name => "glfwSetTime");
procedure Sleep (Time : C.double);
pragma Import (Convention => C, Entity => Sleep,
External_Name => "glfwSleep");
function Extension_Supported (Name : C.Strings.chars_ptr) return Bool;
pragma Import (Convention => C, Entity => Extension_Supported,
External_Name => "glfwExtensionSupported");
procedure Get_GL_Version (Major, Minor, Rev : out C.int);
pragma Import (Convention => C, Entity => Get_GL_Version,
External_Name => "glfwGetGLVersion");
procedure Enable (Target : Enums.Feature);
pragma Import (Convention => C, Entity => Enable,
External_Name => "glfwEnable");
procedure Disable (Target : Enums.Feature);
pragma Import (Convention => C, Entity => Disable,
External_Name => "glfwDisable");
end Glfw.API;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2018 onox <denkpadje@gmail.com>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
package body Orka.Futures.Slots is
protected body Future_Object is
function Current_Status return Futures.Status is (Status);
procedure Set_Status (Value : Futures.Non_Failed_Status) is
begin
case Status is
when Waiting | Running =>
Status := Value;
when Failed | Done =>
raise Program_Error with "Future is already done or failed";
end case;
end Set_Status;
procedure Set_Failed (Reason : Ada.Exceptions.Exception_Occurrence) is
begin
Status := Failed;
Ada.Exceptions.Save_Occurrence (Occurrence, Reason);
end Set_Failed;
entry Wait_Until_Done (Value : out Futures.Status)
when Status in Done | Failed is
begin
Value := Status;
if Status = Failed then
Ada.Exceptions.Reraise_Occurrence (Occurrence);
end if;
end Wait_Until_Done;
function Handle_Location return Location_Index is (Location);
procedure Reset_And_Set_Location (Value : Location_Index) is
begin
Location := Value;
Status := Futures.Waiting;
end Reset_And_Set_Location;
procedure Set_Location (Value : Location_Index) is
begin
Location := Value;
end Set_Location;
end Future_Object;
overriding
procedure Release (Object : Future_Object; Slot : not null Future_Access) is
begin
Manager.Release (Slot);
end Release;
function Make_Handles return Handle_Array is
begin
return Result : Handle_Array do
for Index in Result'Range loop
Result (Index) := Index;
end loop;
end return;
end Make_Handles;
function Make_Futures return Future_Array is
begin
return Result : Future_Array do
for Index in Result'Range loop
Result (Index).Reset_And_Set_Location (Index);
end loop;
end return;
end Make_Futures;
Future_Slots : Future_Array := Make_Futures;
protected body Manager is
entry Acquire (Slot : out Future_Access) when Acquired < Handles'Length is
begin
Acquire_Or_Fail (Slot);
end Acquire;
procedure Acquire_Or_Fail (Slot : out Future_Access) is
pragma Assert (not Should_Stop);
begin
if Acquired >= Handles'Length then
raise Program_Error;
end if;
Acquired := Acquired + 1;
declare
New_Handle : constant Future_Handle := Handles (Acquired);
begin
Slot := Future_Slots (New_Handle)'Access;
end;
pragma Assert (Future_Object_Access (Slot).Handle_Location = Acquired);
end Acquire_Or_Fail;
procedure Release (Slot : not null Future_Access) is
pragma Assert (Should_Stop or else Slot.Current_Status in Done | Failed);
From : constant Location_Index := Future_Object_Access (Slot).Handle_Location;
To : constant Location_Index := Acquired;
pragma Assert (From <= To);
-- Only a slot that has been acquired can be released
From_Handle : constant Future_Handle := Handles (From);
To_Handle : constant Future_Handle := Handles (To);
begin
Handles (From) := To_Handle;
Handles (To) := From_Handle;
pragma Assert (Future_Slots (From_Handle)'Access = Slot);
-- After having moved the locations of the handles, we need to
-- update the slots so that they point to correct locations again
Future_Slots (From_Handle).Reset_And_Set_Location (To);
Future_Slots (To_Handle).Set_Location (From);
Acquired := Acquired - 1;
end Release;
procedure Shutdown is
begin
Should_Stop := True;
end Shutdown;
function Acquired_Slots return Natural is (Acquired);
function Stopping return Boolean is (Should_Stop);
end Manager;
end Orka.Futures.Slots;
|
-----------------------------------------------------------------------
-- awa-counters-beans -- Counter bean definition
-- Copyright (C) 2015, 2016, 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 ADO.Objects;
with ADO.Schemas;
with ADO.Queries;
with Util.Beans.Objects;
with Util.Beans.Basic;
with AWA.Counters.Modules;
with AWA.Counters.Models;
-- == Ada Bean ==
-- The `Counter_Bean` allows to represent a counter associated with some database
-- entity and allows its control by the `<awa:counter>` HTML component.
-- To use it, an instance of the `Counter_Bean` should be defined in a another
-- Ada bean declaration and configured. For example, it may be declared
-- as follows:
--
-- type Wiki_View_Bean is new AWA.Wikis.Models.Wiki_View_Info
-- with record
-- ...
-- Counter : aliased Counter_Bean
-- (Of_Type => ADO.Objects.KEY_INTEGER,
-- Of_Class => AWA.Wikis.Models.WIKI_PAGE_TABLE);
-- end record;
--
-- The counter value is held by the `Value` member of `Counter_Bean` and
-- it should be initialized programatically when the Ada bean instance
-- is loaded (for example through a `load` action).
-- The `Counter_Bean` needs to know the database entity to which it
-- is associated and its `Object` member must be initialized.
-- This is necessary for the `<awa:counter>` HTML component to increment
-- the associated counter when the page is displayed.
-- Below is an extract of such initialization:
--
-- procedure Load
-- (Bean : in out Wiki_View_Bean;
-- Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
-- begin
-- ...
-- Bean.Counter.Value := Bean.Get_Read_Count;
-- ADO.Objects.Set_Value (Bean.Counter.Object, Bean.Get_Id);
-- end Load;
--
--
-- The `Stat_List_Bean` allows to retrieve the list of counters per day for
-- a given database entity. It needs a special managed bean configuration
-- that describes the database entity type, the counter name and
-- SQL query name.
--
-- The example below from the [Wikis Module] declares the bean
-- `wikiPageStats`. The database entity is `awa_wiki_page` which is the
-- name of the database table that holds wiki page. The SQL query
-- to retrieve the result is `page-access-stats`.
--
-- <managed-bean>
-- <description>The counter statistics for a wiki page</description>
-- <managed-bean-name>wikiPageStats</managed-bean-name>
-- <managed-bean-class>AWA.Counters.Beans.Stat_List_Bean</managed-bean-class>
-- <managed-bean-scope>request</managed-bean-scope>
-- <managed-property>
-- <property-name>entity_type</property-name>
-- <property-class>String</property-class>
-- <value>awa_wiki_page</value>
-- </managed-property>
-- <managed-property>
-- <property-name>counter_name</property-name>
-- <property-class>String</property-class>
-- <value>read_count</value>
-- </managed-property>
-- <managed-property>
-- <property-name>query_name</property-name>
-- <property-class>String</property-class>
-- <value>page-access-stats</value>
-- </managed-property>
-- </managed-bean>
--
-- A typical XHTML view that wants to use such bean, should call the `load`
-- action at beginning to load the counter statistics by running the SQL
-- query.
--
-- <f:view contentType="application/json; charset=UTF-8"
-- xmlns:f="http://java.sun.com/jsf/core"
-- xmlns:h="http://java.sun.com/jsf/html">
-- <f:metadata>
-- <f:viewAction action='#{wikiPageStats.load}'/>
-- </f:metadata>
-- {"data":[<h:list value="#{wikiPageStats.stats}"
-- var="stat">["#{stat.date}", #{stat.count}],</h:list>[0,0]]}
-- </f:view>
--
package AWA.Counters.Beans is
type Counter_Bean (Of_Type : ADO.Objects.Object_Key_Type;
Of_Class : ADO.Schemas.Class_Mapping_Access) is
new Util.Beans.Basic.Readonly_Bean with record
Counter : Counter_Index_Type;
Value : Integer := -1;
Object : ADO.Objects.Object_Key (Of_Type, Of_Class);
end record;
type Counter_Bean_Access is access all Counter_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Counter_Bean;
Name : in String) return Util.Beans.Objects.Object;
type Counter_Stat_Bean is new AWA.Counters.Models.Stat_List_Bean with record
Module : AWA.Counters.Modules.Counter_Module_Access;
Stats : aliased AWA.Counters.Models.Stat_Info_List_Bean;
Stats_Bean : AWA.Counters.Models.Stat_Info_List_Bean_Access;
end record;
type Counter_Stat_Bean_Access is access all Counter_Stat_Bean'Class;
-- Get the query definition to collect the counter statistics.
function Get_Query (From : in Counter_Stat_Bean) return ADO.Queries.Query_Definition_Access;
overriding
function Get_Value (List : in Counter_Stat_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Counter_Stat_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the statistics information.
overriding
procedure Load (List : in out Counter_Stat_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Blog_Stat_Bean bean instance.
function Create_Counter_Stat_Bean (Module : in Modules.Counter_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end AWA.Counters.Beans;
|
-- part of AdaYaml, (c) 2017 Felix Krause
-- released under the terms of the MIT license, see the file "copying.txt"
package body Yaml.Events.Store is
function New_Store return Reference is
Ptr : constant not null Instance_Access := new Instance;
begin
return (Ada.Finalization.Controlled with Data => Ptr);
end New_Store;
function Value (Object : Reference) return Accessor is
((Data => Object.Data));
function Value (Object : Optional_Reference) return Accessor is
((Data => Object.Data));
function Optional (Object : Reference'Class) return Optional_Reference is
begin
Increase_Refcount (Object.Data);
return (Ada.Finalization.Controlled with Data => Object.Data);
end Optional;
function Required (Object : Optional_Reference'Class) return Reference is
begin
Increase_Refcount (Object.Data);
return (Ada.Finalization.Controlled with Data => Object.Data);
end Required;
procedure Memorize (Object : in out Instance; Item : Event; Force : Boolean)
is
use type Text.Reference;
begin
if Object.Stream_Count > 0 then
raise State_Error with
"cannot manipulate event queue while a Stream_Instance exists";
end if;
case Item.Kind is
when Annotation_Start =>
if Item.Annotation_Properties.Anchor /= Text.Empty then
Object.Anchor_Map.Include
(Item.Annotation_Properties.Anchor,
(Position => Object.Length + 1, Has_Been_Output => False));
elsif Object.Depth = 0 and not Force then
return;
end if;
if Object.Depth = After_Annotation_End then
Object.Depth := 1;
else
Object.Depth := Object.Depth + 1;
end if;
when Scalar =>
if Item.Scalar_Properties.Anchor /= Text.Empty then
Object.Anchor_Map.Include
(Item.Scalar_Properties.Anchor,
(Position => Object.Length + 1,
Has_Been_Output => False));
elsif Object.Depth = 0 and not Force then
return;
end if;
if Object.Depth = After_Annotation_End then
Object.Depth := 0;
end if;
when Mapping_Start =>
if Item.Collection_Properties.Anchor /= Text.Empty then
Object.Anchor_Map.Include
(Item.Collection_Properties.Anchor,
(Position => Object.Length + 1,
Has_Been_Output => False));
elsif Object.Depth = 0 and not Force then
return;
end if;
if Object.Depth = After_Annotation_End then
Object.Depth := 1;
else
Object.Depth := Object.Depth + 1;
end if;
when Sequence_Start =>
if Item.Collection_Properties.Anchor /= Text.Empty then
Object.Anchor_Map.Include
(Item.Collection_Properties.Anchor,
(Position => Object.Length + 1,
Has_Been_Output => False));
elsif Object.Depth = 0 and not Force then
return;
end if;
if Object.Depth = After_Annotation_End then
Object.Depth := 1;
else
Object.Depth := Object.Depth + 1;
end if;
when Mapping_End | Sequence_End =>
if Object.Depth = 0 and not Force then
return;
end if;
Object.Depth := Object.Depth - 1;
when Annotation_End =>
if Object.Depth = 0 and not Force then
return;
end if;
Object.Depth := Object.Depth - 1;
if Object.Depth = 0 then
Object.Depth := After_Annotation_End;
end if;
when others =>
if Object.Depth = 0 and not Force then
return;
elsif Object.Depth = After_Annotation_End then
Object.Depth := 0;
end if;
end case;
if Object.Length = Object.Data.all'Length then
Object.Grow;
end if;
Object.Length := Object.Length + 1;
Object.Data (Object.Length) := Item;
end Memorize;
procedure Memorize (Object : in out Instance; Item : Event) is
begin
Memorize (Object, Item, False);
end Memorize;
procedure Force_Memorize (Object : in out Instance; Item : Event;
Position : out Element_Cursor) is
begin
Memorize (Object, Item, True);
Position := Element_Cursor (Object.Length);
end Force_Memorize;
function Find (Object : Instance; Alias : Text.Reference)
return Anchor_Cursor is
(Anchor_Cursor (Object.Anchor_Map.Find (Alias)));
function Exists_In_Output (Position : Anchor_Cursor) return Boolean is
(Anchor_To_Index.Element
(Anchor_To_Index.Cursor (Position)).Has_Been_Output);
procedure Set_Exists_In_Output (Object : in out Instance;
Position : Anchor_Cursor) is
procedure Process (Key : Text.Reference;
Element : in out Anchor_Info) is
pragma Unreferenced (Key);
begin
Element.Has_Been_Output := True;
end Process;
begin
Anchor_To_Index.Update_Element (Object.Anchor_Map,
Anchor_To_Index.Cursor (Position),
Process'Access);
end Set_Exists_In_Output;
procedure Advance (Position : in out Element_Cursor) is
begin
Position := Element_Cursor'Succ (Position);
end Advance;
procedure Advance_At_Same_Level (Object : Instance;
Position : in out Element_Cursor) is
Depth : Natural := 0;
begin
loop
case Object.Data (Positive (Position)).Kind is
when Annotation_Start | Sequence_Start | Mapping_Start |
Document_Start =>
Depth := Depth + 1;
when Annotation_End =>
Depth := Depth - 1;
when Sequence_End | Mapping_End | Document_End =>
Depth := Depth - 1;
if Depth = 0 then
Position := Element_Cursor'Succ (Position);
return;
end if;
when Scalar | Alias =>
if Depth = 0 then
Position := Element_Cursor'Succ (Position);
return;
end if;
when Stream_Start | Stream_End =>
raise Stream_Error with "Unexpected event inside stream: " &
Object.Data (Positive (Position)).Kind'Img;
end case;
Position := Element_Cursor'Succ (Position);
end loop;
end Advance_At_Same_Level;
procedure Clear (Object : in out Instance) is
begin
if Object.Stream_Count > 0 then
raise State_Error with
"cannot manipulate event queue while a Stream_Instance exists";
end if;
Object.Anchor_Map.Clear;
Object.Depth := 0;
end Clear;
procedure Copy (Source : in Instance; Target : in out Instance) is
begin
if Target.Data.all'Length /= Source.Data.all'Length then
Target.Finalize;
Target.Data := new Event_Array (Source.Data.all'Range);
end if;
Target.Data.all := Source.Data.all;
Target.Length := Source.Length;
Target.Anchor_Map := Source.Anchor_Map;
Target.Depth := Source.Depth;
end Copy;
function Retrieve (Object : Reference'Class; Position : Anchor_Cursor)
return Stream_Reference is
Ptr : constant not null Stream_Instance_Access :=
new Stream_Instance'(Refcount_Base with Object => Reference (Object),
Depth => 0, Current => Anchor_To_Index.Element
(Anchor_To_Index.Cursor (Position)).Position);
begin
Object.Data.Stream_Count := Object.Data.Stream_Count + 1;
return Stream_Reference'(Ada.Finalization.Controlled with Data => Ptr);
end Retrieve;
function Retrieve (Object : Reference'Class; Position : Element_Cursor)
return Stream_Reference is
Ptr : constant not null Stream_Instance_Access :=
new Stream_Instance'(Refcount_Base with Object => Reference (Object),
Depth => 0, Current => Positive (Position));
begin
Object.Data.Stream_Count := Object.Data.Stream_Count + 1;
return Stream_Reference'(Ada.Finalization.Controlled with Data => Ptr);
end Retrieve;
function Value (Object : Stream_Reference) return Stream_Accessor is
((Data => Object.Data));
function Next (Object : in out Stream_Instance) return Event is
begin
if Object.Depth = 1 then
raise Constraint_Error with
"tried to query item after end of anchored node";
end if;
return Item : constant Event := Object.Object.Data.Data (Object.Current) do
case Item.Kind is
when Scalar => Object.Depth := Natural'Max (1, Object.Depth);
when Mapping_Start | Sequence_Start =>
Object.Depth := Natural'Max (2, Object.Depth + 1);
when others => null;
end case;
Object.Current := Object.Current + 1;
end return;
end Next;
function Exists (Object : Optional_Stream_Reference) return Boolean is
(Object.Data /= null);
function Value (Object : Optional_Stream_Reference) return Stream_Accessor is
((Data => Object.Data));
function Optional (Object : Stream_Reference'Class)
return Optional_Stream_Reference is
begin
Object.Data.Refcount := Object.Data.Refcount + 1;
return (Ada.Finalization.Controlled with Data => Object.Data);
end Optional;
procedure Clear (Object : in out Optional_Stream_Reference) is
begin
if Object.Data /= null then
Decrease_Refcount (Object.Data);
Object.Data := null;
end if;
end Clear;
function First (Object : Instance; Position : Anchor_Cursor) return Event is
(Object.Data (Anchor_To_Index.Element (Anchor_To_Index.Cursor
(Position)).Position));
function Element (Object : Instance; Position : Element_Cursor)
return Event is
(Object.Data (Positive (Position)));
procedure Adjust (Object : in out Reference) is
begin
Increase_Refcount (Object.Data);
end Adjust;
procedure Finalize (Object : in out Reference) is
begin
Decrease_Refcount (Object.Data);
end Finalize;
procedure Adjust (Object : in out Optional_Reference) is
begin
if Object.Data /= null then
Increase_Refcount (Object.Data);
end if;
end Adjust;
procedure Finalize (Object : in out Optional_Reference) is
begin
if Object.Data /= null then
Decrease_Refcount (Object.Data);
end if;
end Finalize;
procedure Finalize (Object : in out Stream_Instance) is
begin
Object.Object.Data.Stream_Count := Object.Object.Data.Stream_Count - 1;
end Finalize;
procedure Adjust (Object : in out Stream_Reference) is
begin
Increase_Refcount (Object.Data);
end Adjust;
procedure Finalize (Object : in out Stream_Reference) is
begin
Decrease_Refcount (Object.Data);
end Finalize;
procedure Adjust (Object : in out Optional_Stream_Reference) is
begin
if Object.Data /= null then
Increase_Refcount (Object.Data);
end if;
end Adjust;
procedure Finalize (Object : in out Optional_Stream_Reference) is
begin
if Object.Data /= null then
Decrease_Refcount (Object.Data);
end if;
end Finalize;
function To_Element_Cursor (Position : Anchor_Cursor) return Element_Cursor
is (if Position = No_Anchor then No_Element else
Element_Cursor (Anchor_To_Index.Element (Anchor_To_Index.Cursor
(Position)).Position));
end Yaml.Events.Store;
|
-- Copyright (c) 2016 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.Characters.Latin_1;
with Ada.IO_Exceptions;
with Ada.Unchecked_Conversion;
package body JSON.Streams is
use type AS.Stream_Element_Offset;
overriding
procedure Read_Character (Object : in out Stream_String; Item : out Character) is
begin
if Integer (Object.Index) not in Object.Text'Range then
raise Ada.IO_Exceptions.End_Error;
end if;
Item := Object.Text (Integer (Object.Index));
Object.Index := Object.Index + 1;
end Read_Character;
overriding
procedure Read_Character (Object : in out Stream_Bytes; Item : out Character) is
function Convert is new Ada.Unchecked_Conversion
(Source => AS.Stream_Element, Target => Character);
begin
if Object.Index not in Object.Bytes'Range then
raise Ada.IO_Exceptions.End_Error;
end if;
Item := Convert (Object.Bytes (Object.Index));
Object.Index := Object.Index + 1;
end Read_Character;
function Has_Buffered_Character (Object : Stream) return Boolean
is (Object.Next_Character /= Ada.Characters.Latin_1.NUL);
function Read_Character (Object : in out Stream) return Character is
Index : AS.Stream_Element_Offset;
begin
return Object.Read_Character (Index);
end Read_Character;
function Read_Character
(Object : in out Stream;
Index : out AS.Stream_Element_Offset) return Character
is
C : Character;
begin
Index := Object.Index;
if Object.Next_Character = Ada.Characters.Latin_1.NUL then
Stream'Class (Object).Read_Character (C);
else
C := Object.Next_Character;
Object.Next_Character := Ada.Characters.Latin_1.NUL;
end if;
return C;
end Read_Character;
procedure Write_Character (Object : in out Stream; Next : Character) is
begin
Object.Next_Character := Next;
end Write_Character;
overriding
function Get_String
(Object : Stream_String;
Offset, Length : AS.Stream_Element_Offset) return String is
begin
return Object.Text (Integer (Offset) .. Integer (Offset + Length - 1));
end Get_String;
overriding
function Get_String
(Object : Stream_Bytes;
Offset, Length : AS.Stream_Element_Offset) return String
is
subtype Constrained_String is String (1 .. Integer (Length));
function Convert is new Ada.Unchecked_Conversion
(Source => AS.Stream_Element_Array, Target => Constrained_String);
begin
return Convert (Object.Bytes (Offset .. Offset + Length - 1));
end Get_String;
function Create_Stream (Text : not null access String) return Stream'Class is
begin
return Stream_String'(Text => Text,
Next_Character => Ada.Characters.Latin_1.NUL,
Index => AS.Stream_Element_Offset (Text'First));
end Create_Stream;
function Create_Stream
(Bytes : not null access AS.Stream_Element_Array) return Stream'Class is
begin
return Stream_Bytes'(Bytes => Bytes,
Next_Character => Ada.Characters.Latin_1.NUL,
Index => Bytes'First);
end Create_Stream;
end JSON.Streams;
|
package Pack4 is
type Buffer is array (Natural range <>) of Boolean;
type Root (Size : Natural) is tagged record
Data : Buffer (1..Size);
end record;
pragma Pack (Root);
type Derived is new Root with null record;
end Pack4;
|
--------------------------------------------------------------------------------
-- MIT License
--
-- Copyright (c) 2020 Zane Myers
--
-- 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 Vulkan.Math.GenDMatrix;
with Vulkan.Math.Dvec2;
use Vulkan.Math.GenDMatrix;
use Vulkan.Math.Dvec2;
--------------------------------------------------------------------------------
--< @group Vulkan Math Basic Types
--------------------------------------------------------------------------------
--< @summary
--< This package provides a single precision floating point matrix with 3 rows
--< and 2 columns.
--------------------------------------------------------------------------------
package Vulkan.Math.Dmat3x2 is
pragma Preelaborate;
pragma Pure;
--< A 3x2 matrix of single-precision floating point numbers.
subtype Vkm_Dmat3x2 is Vkm_Dmat(
last_row_index => 2, last_column_index => 1);
----------------------------------------------------------------------------
--< @summary
--< Constructor for Vkm_Dmat3x2 type.
--<
--< @description
--< Construct a 3x2 matrix with each component set to 0.0
--<
--< @return
--< A 3x2 matrix.
----------------------------------------------------------------------------
function Make_Dmat3x2 return Vkm_Dmat3x2 is
(GDM.Make_GenMatrix(cN => 1, rN => 2)) with Inline;
----------------------------------------------------------------------------
--< @summary
--< Constructor for Vkm_Dmat3x2 type.
--<
--< @description
--< Construct a 3x2 matrix with each component set to a different value.
--<
--< | value1 value4 |
--< | value2 value5 |
--< | value3 value6 |
--<
--< @param value1
--< The first value to set for the matrix.
--<
--< @param value2
--< The second value to set for the matrix.
--<
--< @param value3
--< The third value to set for the matrix.
--<
--< @param value4
--< The fourth value to set for the matrix.
--<
--< @param value5
--< The fifth value to set for the matrix.
--<
--< @param value6
--< The sixth value to set for the matrix.
--<
--< @return
--< A 3x2 matrix.
----------------------------------------------------------------------------
function Make_Dmat3x2 (
value1, value2, value3,
value4, value5, value6 : in Vkm_Double) return Vkm_Dmat3x2 is
(GDM.Make_GenMatrix(
cN => 1, rN => 2,
c0r0_val => value1, c0r1_val => value3, c0r2_val => value5,
c1r0_val => value2, c1r1_val => value4, c1r2_val => value6)) with Inline;
----------------------------------------------------------------------------
--< @summary
--< Constructor for Vkm_Dmat3x2 type.
--<
--< @description
--< Construct a 3x2 matrix with each row set to the value of a 2 dimmensional
--< vector.
--<
--< @param value1
--< The first value to set for the matrix.
--<
--< @param value2
--< The second value to set for the matrix.
--<
--< @param value3
--< The third value to set for the matrix.
--<
--< @return
--< A 3x2 matrix.
----------------------------------------------------------------------------
function Make_Dmat3x2 (
value1, value2, value3 : in Vkm_Dvec2) return Vkm_Dmat3x2 is
(GDM.Make_GenMatrix(
cN => 1, rN => 2,
c0r0_val => value1.x, c0r1_val => value2.x, c0r2_val => value3.x,
c1r0_val => value1.y, c1r1_val => value2.y, c1r2_val => value3.y)) with Inline;
----------------------------------------------------------------------------
--< @summary
--< Constructor for Vkm_Dmat3x2 type.
--<
--< @description
--< Construct a 3x2 matrix using values from an existing matrix.
--<
--< If the provided matrix has dimmensions that are not the same as this
--< matrix, the corresponding element in the 4x4 identity matrix is used for
--< out of bounds accesses.
--<
--< @param value1
--< The submatrix to extract values from.
--<
--< @return
--< A 3x2 matrix.
----------------------------------------------------------------------------
function Make_Dmat3x2 (
value1 : in Vkm_Dmat) return Vkm_Dmat3x2 is
(GDM.Make_GenMatrix(
cN => 1, rN => 2,
c0r0_val => value1.c0r0, c0r1_val => value1.c0r1, c0r2_val => value1.c0r2,
c1r0_val => value1.c1r0, c1r1_val => value1.c1r1, c1r2_val => value1.c1r2)) with Inline;
end Vulkan.Math.Dmat3x2;
|
-- { dg-do compile }
with Interfaces.C; use Interfaces.C;
procedure Object_Overflow3 is
procedure Proc (x : Boolean) is begin null; end;
type Arr is array(0 .. ptrdiff_t'Last) of Boolean;
type Rec is record
A : Arr;
B : Arr;
end record;
Obj : Rec; -- { dg-warning "Storage_Error" }
begin
Obj.A(1) := True;
Proc (Obj.A(1));
end;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS --
-- --
-- SYSTEM.TASKING.PROTECTED_OBJECTS.SINGLE_ENTRY --
-- --
-- S p e c --
-- --
-- Copyright (C) 1992-2019, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNARL was developed by the GNARL team at Florida State University. --
-- Extensive contributions were provided by Ada Core Technologies, Inc. --
-- --
------------------------------------------------------------------------------
-- This package provides an optimized version of Protected_Objects.Operations
-- and Protected_Objects.Entries making the following assumptions:
-- PO have only one entry
-- There is only one caller at a time (No_Entry_Queue)
-- There is no dynamic priority support (No_Dynamic_Priorities)
-- No Abort Statements
-- (No_Abort_Statements, Max_Asynchronous_Select_Nesting => 0)
-- PO are at library level
-- None of the tasks will terminate (no need for finalization)
-- This interface is intended to be used in the Ravenscar profile, the
-- compiler is responsible for ensuring that the conditions mentioned above
-- are respected, except for the No_Entry_Queue restriction that is checked
-- dynamically in this package, since the check cannot be performed at compile
-- time, and is relatively cheap (see body).
-- This package is part of the high level tasking interface used by the
-- compiler to expand Ada 95 tasking constructs into simpler run time calls
-- (aka GNARLI, GNU Ada Run-time Library Interface)
-- Note: the compiler generates direct calls to this interface, via Rtsfind.
-- Any changes to this interface may require corresponding compiler changes
-- in exp_ch9.adb and possibly exp_ch7.adb
package System.Tasking.Protected_Objects.Single_Entry is
pragma Elaborate_Body;
---------------------------------
-- Compiler Interface (GNARLI) --
---------------------------------
-- The compiler will expand in the GNAT tree the following construct:
-- protected PO is
-- entry E;
-- procedure P;
-- private
-- Open : Boolean := False;
-- end PO;
-- protected body PO is
-- entry E when Open is
-- ...variable declarations...
-- begin
-- ...B...
-- end E;
-- procedure P is
-- ...variable declarations...
-- begin
-- ...C...
-- end P;
-- end PO;
-- as follows:
-- protected type poT is
-- entry e;
-- procedure p;
-- private
-- open : boolean := false;
-- end poT;
-- type poTV is limited record
-- open : boolean := false;
-- _object : aliased protection_entry;
-- end record;
-- procedure poPT__E1s (O : address; P : address; E :
-- protected_entry_index);
-- function poPT__B2s (O : address; E : protected_entry_index) return
-- boolean;
-- procedure poPT__pN (_object : in out poTV);
-- procedure poPT__pP (_object : in out poTV);
-- poTA : aliased entry_body := (
-- barrier => poPT__B2s'unrestricted_access,
-- action => poPT__E1s'unrestricted_access);
-- freeze poTV [
-- procedure poTVIP (_init : in out poTV) is
-- begin
-- _init.open := false;
-- object-init-proc (_init._object);
-- initialize_protection_entry (_init._object'unchecked_access,
-- unspecified_priority, _init'address, poTA'
-- unrestricted_access);
-- return;
-- end poTVIP;
-- ]
-- po : poT;
-- poTVIP (poTV!(po));
-- function poPT__B2s (O : address; E : protected_entry_index) return
-- boolean is
-- type poTVP is access poTV;
-- _object : poTVP := poTVP!(O);
-- poR : protection_entry renames _object._object;
-- openP : boolean renames _object.open;
-- begin
-- return open;
-- end poPT__B2s;
-- procedure poPT__E1s (O : address; P : address; E :
-- protected_entry_index) is
-- type poTVP is access poTV;
-- _object : poTVP := poTVP!(O);
-- begin
-- B1b : declare
-- poR : protection_entry renames _object._object;
-- openP : boolean renames _object.open;
-- ...variable declarations...
-- begin
-- ...B...
-- end B1b;
-- complete_single_entry_body (_object._object'unchecked_access);
-- return;
-- exception
-- when all others =>
-- exceptional_complete_single_entry_body (_object._object'
-- unchecked_access, get_gnat_exception);
-- return;
-- end poPT__E1s;
-- procedure poPT__pN (_object : in out poTV) is
-- poR : protection_entry renames _object._object;
-- openP : boolean renames _object.open;
-- ...variable declarations...
-- begin
-- ...C...
-- return;
-- end poPT__pN;
-- procedure poPT__pP (_object : in out poTV) is
-- procedure _clean is
-- begin
-- service_entry (_object._object'unchecked_access);
-- return;
-- end _clean;
-- begin
-- lock_entry (_object._object'unchecked_access);
-- B5b : begin
-- poPT__pN (_object);
-- at end
-- _clean;
-- end B5b;
-- return;
-- end poPT__pP;
type Protection_Entry is limited private;
-- This type contains the GNARL state of a protected object. The
-- application-defined portion of the state (i.e. private objects)
-- is maintained by the compiler-generated code.
type Protection_Entry_Access is access all Protection_Entry;
type Entry_Body_Access is access constant Entry_Body;
-- Access to barrier and action function of an entry
procedure Initialize_Protection_Entry
(Object : Protection_Entry_Access;
Ceiling_Priority : Integer;
Compiler_Info : System.Address;
Entry_Body : Entry_Body_Access);
-- Initialize the Object parameter so that it can be used by the run time
-- to keep track of the runtime state of a protected object.
procedure Lock_Entry (Object : Protection_Entry_Access);
-- Lock a protected object for write access. Upon return, the caller owns
-- the lock to this object, and no other call to Lock or Lock_Read_Only
-- with the same argument will return until the corresponding call to
-- Unlock has been made by the caller.
procedure Lock_Read_Only_Entry
(Object : Protection_Entry_Access);
-- Lock a protected object for read access. Upon return, the caller owns
-- the lock for read access, and no other calls to Lock with the same
-- argument will return until the corresponding call to Unlock has been
-- made by the caller. Other calls to Lock_Read_Only may (but need not)
-- return before the call to Unlock, and the corresponding callers will
-- also own the lock for read access.
procedure Unlock_Entry (Object : Protection_Entry_Access);
-- Relinquish ownership of the lock for the object represented by the
-- Object parameter. If this ownership was for write access, or if it was
-- for read access where there are no other read access locks outstanding,
-- one (or more, in the case of Lock_Read_Only) of the tasks waiting on
-- this lock (if any) will be given the lock and allowed to return from
-- the Lock or Lock_Read_Only call.
procedure Service_Entry (Object : Protection_Entry_Access);
-- Service the entry queue of the specified object, executing the
-- corresponding body of any queued entry call that is waiting on True
-- barrier. This is used when the state of a protected object may have
-- changed, in particular after the execution of the statement sequence
-- of a protected procedure.
--
-- This must be called with abort deferred and with the corresponding
-- object locked. Object is unlocked on return.
procedure Protected_Single_Entry_Call
(Object : Protection_Entry_Access;
Uninterpreted_Data : System.Address);
-- Make a protected entry call to the specified object
--
-- Pends a protected entry call on the protected object represented by
-- Object. A pended call is not queued; it may be executed immediately
-- or queued, depending on the state of the entry barrier.
--
-- Uninterpreted_Data
-- This will be returned by Next_Entry_Call when this call is serviced.
-- It can be used by the compiler to pass information between the
-- caller and the server, in particular entry parameters.
procedure Exceptional_Complete_Single_Entry_Body
(Object : Protection_Entry_Access;
Ex : Ada.Exceptions.Exception_Id);
-- Perform all of the functions of Complete_Entry_Body. In addition, report
-- in Ex the exception whose propagation terminated the entry body to the
-- runtime system.
function Protected_Count_Entry (Object : Protection_Entry) return Natural;
-- Return the number of entry calls on Object (0 or 1)
function Protected_Single_Entry_Caller
(Object : Protection_Entry) return Task_Id;
-- Return value of E'Caller, where E is the protected entry currently being
-- handled. This will only work if called from within an entry body, as
-- required by the LRM (C.7.1(14)).
private
type Protection_Entry is record
Common : aliased Protection;
-- State of the protected object. This part is common to any protected
-- object, including those without entries.
Compiler_Info : System.Address;
-- Pointer to compiler-generated record representing protected object
Call_In_Progress : Entry_Call_Link;
-- Pointer to the entry call being executed (if any)
Entry_Body : Entry_Body_Access;
-- Pointer to executable code for the entry body of the protected type
Entry_Queue : Entry_Call_Link;
-- Place to store the waiting entry call (if any)
end record;
end System.Tasking.Protected_Objects.Single_Entry;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- G N A T . S O C K E T S . T H I N --
-- --
-- B o d y --
-- --
-- $Revision$
-- --
-- Copyright (C) 2001 Ada Core Technologies, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, --
-- MA 02111-1307, USA. --
-- --
-- As a special exception, if other files instantiate generics from this --
-- unit, or you link this unit with other files to produce an executable, --
-- this unit does not by itself cause the resulting executable to be --
-- covered by the GNU General Public License. This exception does not --
-- however invalidate any other reasons why the executable file might be --
-- covered by the GNU Public License. --
-- --
-- GNAT is maintained by Ada Core Technologies Inc (http://www.gnat.com). --
-- --
------------------------------------------------------------------------------
with GNAT.OS_Lib; use GNAT.OS_Lib;
with Interfaces.C; use Interfaces.C;
package body GNAT.Sockets.Thin is
-- When this package is initialized with Process_Blocking_IO set
-- to True, sockets are set in non-blocking mode to avoid blocking
-- the whole process when a thread wants to perform a blocking IO
-- operation. But the user can set a socket in non-blocking mode
-- by purpose. We track the socket in such a mode by redefining
-- C_Ioctl. In blocking IO operations, we exit normally when the
-- non-blocking flag is set by user, we poll and try later when
-- this flag is set automatically by this package.
type Socket_Info is record
Non_Blocking : Boolean := False;
end record;
Table : array (C.int range 0 .. 31) of Socket_Info;
-- Get info on blocking flag. This array is limited to 32 sockets
-- because the select operation allows socket set of less then 32
-- sockets.
Quantum : constant Duration := 0.2;
-- comment needed ???
Thread_Blocking_IO : Boolean := True;
function Syscall_Accept
(S : C.int;
Addr : System.Address;
Addrlen : access C.int)
return C.int;
pragma Import (C, Syscall_Accept, "accept");
function Syscall_Connect
(S : C.int;
Name : System.Address;
Namelen : C.int)
return C.int;
pragma Import (C, Syscall_Connect, "connect");
function Syscall_Ioctl
(S : C.int;
Req : C.int;
Arg : Int_Access)
return C.int;
pragma Import (C, Syscall_Ioctl, "ioctl");
function Syscall_Recv
(S : C.int;
Msg : System.Address;
Len : C.int;
Flags : C.int)
return C.int;
pragma Import (C, Syscall_Recv, "recv");
function Syscall_Recvfrom
(S : C.int;
Msg : System.Address;
Len : C.int;
Flags : C.int;
From : Sockaddr_In_Access;
Fromlen : access C.int)
return C.int;
pragma Import (C, Syscall_Recvfrom, "recvfrom");
function Syscall_Send
(S : C.int;
Msg : System.Address;
Len : C.int;
Flags : C.int)
return C.int;
pragma Import (C, Syscall_Send, "send");
function Syscall_Sendto
(S : C.int;
Msg : System.Address;
Len : C.int;
Flags : C.int;
To : Sockaddr_In_Access;
Tolen : C.int)
return C.int;
pragma Import (C, Syscall_Sendto, "sendto");
function Syscall_Socket
(Domain, Typ, Protocol : C.int)
return C.int;
pragma Import (C, Syscall_Socket, "socket");
procedure Set_Non_Blocking (S : C.int);
--------------
-- C_Accept --
--------------
function C_Accept
(S : C.int;
Addr : System.Address;
Addrlen : access C.int)
return C.int
is
Res : C.int;
begin
loop
Res := Syscall_Accept (S, Addr, Addrlen);
exit when Thread_Blocking_IO
or else Res /= Failure
or else Table (S).Non_Blocking
or else Errno /= Constants.EWOULDBLOCK;
delay Quantum;
end loop;
if not Thread_Blocking_IO
and then Res /= Failure
then
-- A socket inherits the properties ot its server especially
-- the FNDELAY flag.
Table (Res).Non_Blocking := Table (S).Non_Blocking;
Set_Non_Blocking (Res);
end if;
return Res;
end C_Accept;
---------------
-- C_Connect --
---------------
function C_Connect
(S : C.int;
Name : System.Address;
Namelen : C.int)
return C.int
is
Res : C.int;
begin
Res := Syscall_Connect (S, Name, Namelen);
if Thread_Blocking_IO
or else Res /= Failure
or else Table (S).Non_Blocking
or else Errno /= Constants.EINPROGRESS
then
return Res;
end if;
declare
Set : aliased Fd_Set;
Now : aliased Timeval;
begin
loop
Set := 2 ** Natural (S);
Now := Immediat;
Res := C_Select
(S + 1,
null, Set'Unchecked_Access,
null, Now'Unchecked_Access);
exit when Res > 0;
if Res = Failure then
return Res;
end if;
delay Quantum;
end loop;
end;
Res := Syscall_Connect (S, Name, Namelen);
if Res = Failure
and then Errno = Constants.EISCONN
then
return Thin.Success;
else
return Res;
end if;
end C_Connect;
-------------
-- C_Ioctl --
-------------
function C_Ioctl
(S : C.int;
Req : C.int;
Arg : Int_Access)
return C.int
is
begin
if not Thread_Blocking_IO
and then Req = Constants.FIONBIO
then
Table (S).Non_Blocking := (Arg.all /= 0);
end if;
return Syscall_Ioctl (S, Req, Arg);
end C_Ioctl;
------------
-- C_Recv --
------------
function C_Recv
(S : C.int;
Msg : System.Address;
Len : C.int;
Flags : C.int)
return C.int
is
Res : C.int;
begin
loop
Res := Syscall_Recv (S, Msg, Len, Flags);
exit when Thread_Blocking_IO
or else Res /= Failure
or else Table (S).Non_Blocking
or else Errno /= Constants.EWOULDBLOCK;
delay Quantum;
end loop;
return Res;
end C_Recv;
----------------
-- C_Recvfrom --
----------------
function C_Recvfrom
(S : C.int;
Msg : System.Address;
Len : C.int;
Flags : C.int;
From : Sockaddr_In_Access;
Fromlen : access C.int)
return C.int
is
Res : C.int;
begin
loop
Res := Syscall_Recvfrom (S, Msg, Len, Flags, From, Fromlen);
exit when Thread_Blocking_IO
or else Res /= Failure
or else Table (S).Non_Blocking
or else Errno /= Constants.EWOULDBLOCK;
delay Quantum;
end loop;
return Res;
end C_Recvfrom;
------------
-- C_Send --
------------
function C_Send
(S : C.int;
Msg : System.Address;
Len : C.int;
Flags : C.int)
return C.int
is
Res : C.int;
begin
loop
Res := Syscall_Send (S, Msg, Len, Flags);
exit when Thread_Blocking_IO
or else Res /= Failure
or else Table (S).Non_Blocking
or else Errno /= Constants.EWOULDBLOCK;
delay Quantum;
end loop;
return Res;
end C_Send;
--------------
-- C_Sendto --
--------------
function C_Sendto
(S : C.int;
Msg : System.Address;
Len : C.int;
Flags : C.int;
To : Sockaddr_In_Access;
Tolen : C.int)
return C.int
is
Res : C.int;
begin
loop
Res := Syscall_Sendto (S, Msg, Len, Flags, To, Tolen);
exit when Thread_Blocking_IO
or else Res /= Failure
or else Table (S).Non_Blocking
or else Errno /= Constants.EWOULDBLOCK;
delay Quantum;
end loop;
return Res;
end C_Sendto;
--------------
-- C_Socket --
--------------
function C_Socket
(Domain : C.int;
Typ : C.int;
Protocol : C.int)
return C.int
is
Res : C.int;
begin
Res := Syscall_Socket (Domain, Typ, Protocol);
if not Thread_Blocking_IO
and then Res /= Failure
then
Set_Non_Blocking (Res);
end if;
return Res;
end C_Socket;
-----------
-- Clear --
-----------
procedure Clear
(Item : in out Fd_Set;
Socket : in C.int)
is
Mask : constant Fd_Set := 2 ** Natural (Socket);
begin
if (Item and Mask) /= 0 then
Item := Item xor Mask;
end if;
end Clear;
-----------
-- Empty --
-----------
procedure Empty (Item : in out Fd_Set) is
begin
Item := 0;
end Empty;
--------------
-- Finalize --
--------------
procedure Finalize is
begin
null;
end Finalize;
----------------
-- Initialize --
----------------
procedure Initialize (Process_Blocking_IO : Boolean) is
begin
Thread_Blocking_IO := not Process_Blocking_IO;
end Initialize;
--------------
-- Is_Empty --
--------------
function Is_Empty (Item : Fd_Set) return Boolean is
begin
return Item = 0;
end Is_Empty;
------------
-- Is_Set --
------------
function Is_Set (Item : Fd_Set; Socket : C.int) return Boolean is
begin
return (Item and 2 ** Natural (Socket)) /= 0;
end Is_Set;
---------
-- Max --
---------
function Max (Item : Fd_Set) return C.int
is
L : C.int := -1;
C : Fd_Set := Item;
begin
while C /= 0 loop
L := L + 1;
C := C / 2;
end loop;
return L;
end Max;
---------
-- Set --
---------
procedure Set (Item : in out Fd_Set; Socket : in C.int) is
begin
Item := Item or 2 ** Natural (Socket);
end Set;
----------------------
-- Set_Non_Blocking --
----------------------
procedure Set_Non_Blocking (S : C.int) is
Res : C.int;
Val : aliased C.int := 1;
begin
-- Do not use C_Fcntl because this subprogram tracks the
-- sockets set by user in non-blocking mode.
Res := Syscall_Ioctl (S, Constants.FIONBIO, Val'Unchecked_Access);
end Set_Non_Blocking;
--------------------------
-- Socket_Error_Message --
--------------------------
function Socket_Error_Message (Errno : Integer) return String is
use type Interfaces.C.Strings.chars_ptr;
C_Msg : C.Strings.chars_ptr;
begin
C_Msg := C_Strerror (C.int (Errno));
if C_Msg = C.Strings.Null_Ptr then
return "Unknown system error";
else
return C.Strings.Value (C_Msg);
end if;
end Socket_Error_Message;
end GNAT.Sockets.Thin;
|
-------------------------------------------------------------------------------
-- Copyright (c) 2020 Daniel King
--
-- 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.
-------------------------------------------------------------------------------
package body Generic_COBS
with Pure, SPARK_Mode => On
is
------------
-- Decode --
------------
procedure Decode (Input : Byte_Array;
Output : out Byte_Array;
Length : out Byte_Count) is
B : Byte;
Code : Byte := Byte'Last;
Run_Length : Byte_Count := 0;
begin
Length := 0;
for I in 0 .. Index'Base (Input'Length - 1) loop
pragma Loop_Invariant (Length <= Byte_Count (I));
pragma Loop_Invariant
(for all J in 0 .. Length - 1 =>
Output (Output'First + Index'Base (J))'Initialized);
B := Input (Input'First + I);
exit when B = Frame_Delimiter;
if Run_Length > 0 then
Output (Output'First + Index'Base (Length)) := B;
Length := Length + 1;
else
if Code /= Byte'Last then
Output (Output'First + Index'Base (Length)) := Frame_Delimiter;
Length := Length + 1;
end if;
Code := B;
Run_Length := Byte_Count (Byte'Pos (B));
end if;
Run_Length := Run_Length - 1;
end loop;
end Decode;
------------
-- Encode --
------------
procedure Encode (Input : Byte_Array;
Output : out Byte_Array;
Length : out Byte_Count) is
Block_Length : Positive_Byte_Count;
Offset : Byte_Count;
Remaining : Byte_Count;
Nb_Overhead_Bytes : Positive_Byte_Count with Ghost;
begin
-- Encode first block
Encode_Block (Input, Output, Length);
Offset := Length - 1;
Remaining := Input'Length - (Length - 1);
Nb_Overhead_Bytes := 1;
while Remaining > 0 loop
pragma Loop_Variant (Decreases => Remaining,
Increases => Offset,
Increases => Length,
Increases => Nb_Overhead_Bytes);
pragma Loop_Invariant (Offset + Remaining = Input'Length);
pragma Loop_Invariant (Length = Offset + Nb_Overhead_Bytes);
pragma Loop_Invariant
(Nb_Overhead_Bytes < Max_Overhead_Bytes (Offset));
pragma Loop_Invariant
(for all I in Output'First ..
Output'First + Index'Base (Length - 1) =>
Output (I)'Initialized);
pragma Loop_Invariant
(for all I in Output'First ..
Output'First + Index'Base (Length - 1) =>
Output (I) /= Frame_Delimiter);
Encode_Block
(Input (Input'First + Index'Base (Offset) .. Input'Last),
Output (Output'First + Index'Base (Length) .. Output'Last),
Block_Length);
Nb_Overhead_Bytes := Nb_Overhead_Bytes + 1;
Length := Length + Block_Length;
Offset := Offset + (Block_Length - 1);
Remaining := Remaining - (Block_Length - 1);
end loop;
pragma Assert
(for all I in Output'First ..
Output'First + Index'Base (Length - 1) =>
Output (I) /= Frame_Delimiter);
Output (Output'First + Index'Base (Length)) := Frame_Delimiter;
Length := Length + 1;
end Encode;
--------------------
-- Encode_Block --
--------------------
procedure Encode_Block (Input : Byte_Array;
Output : out Byte_Array;
Length : out Byte_Count) is
B : Byte;
Code : Positive_Byte_Count := 1;
-- Keeps track of the length of the current run of non-zero octets.
-- Note that this can be 1 more than Max_Run_Size since this is
-- 1 more than the current run length (it includes the overhead octet
-- in its count).
Code_Pos : Index := Output'First;
-- The position in 'Output' of the previous overhead/zero octet.
-- When a run of up to 254 non-zero octets is completed (and thus the
-- length of the run is now known), then the byte at this position in
-- 'Output' is updated with the run length.
begin
Length := 1; -- Initial overhead octet is appended.
if Input'Length > 0 then
for I in Byte_Count range 0 .. Input'Length - 1 loop
pragma Warnings
(Off, """Output"" may be referenced before it has a value",
Reason => "Initialization of Output is guaranteed via proof");
pragma Loop_Invariant (Code in 1 .. Maximum_Run_Length + 1);
pragma Loop_Invariant
(Code = Length - Byte_Count (Code_Pos - Output'First));
pragma Loop_Invariant
(Code_Pos in Output'First ..
Output'First + Index'Base (Length) - 1);
pragma Loop_Invariant (Length = Byte_Count (I + 1));
-- All bytes written so far are initialized, except the
-- one at Code_Pos which is written later.
pragma Loop_Invariant
(for all I in Output'First ..
Output'First + Index'Base (Length) - 1 =>
(if I /= Code_Pos then Output (I)'Initialized));
-- The frame delimiter is never written to the output.
pragma Loop_Invariant
(for all I in Output'First ..
Output'First + Index'Base (Length) - 1 =>
(if I /= Code_Pos then Output (I) /= Frame_Delimiter));
pragma Warnings (On);
-- Stop when a complete block is reached.
exit when Code = Maximum_Run_Length + 1;
B := Input (Input'First + Index'Base (I));
if B /= Frame_Delimiter then
-- Copy non-zero byte
Output (Output'First + Index'Base (Length)) := B;
Code := Code + 1;
Length := Length + 1;
else
-- Replace zero byte
Output (Code_Pos) := Byte'Val (Code);
Code_Pos := Output'First + Index'Base (Length);
Length := Length + 1;
Code := 1;
end if;
end loop;
end if;
Output (Code_Pos) := Byte'Val (Code);
end Encode_Block;
end Generic_COBS;
|
with Ada.Text_IO; use Ada.Text_IO;
package body Inline11_Pkg is
function My_Img (I : Integer) return String is
begin
return I'Img;
end;
procedure Trace (I : Integer) is
begin
Put_Line (My_Img (I));
end;
end Inline11_Pkg;
|
pragma License (Unrestricted);
package Interfaces.COBOL is
pragma Preelaborate;
-- Types and operations for internal data representations
type Floating is new Float; -- implementation-defined
type Long_Floating is new Long_Float; -- implementation-defined
type Binary is new Integer; -- implementation-defined
type Long_Binary is new Long_Long_Integer; -- implementation-defined
Max_Digits_Binary : constant := 9; -- implementation-defined
Max_Digits_Long_Binary : constant := 18; -- implementation-defined
type Decimal_Element is mod 2 ** 4; -- implementation-defined
type Packed_Decimal is array (Positive range <>) of Decimal_Element;
pragma Pack (Packed_Decimal);
type COBOL_Character is
new Character; -- implementation-defined character type
-- modified
-- Ada_To_COBOL : array (Character) of COBOL_Character :=
-- implementation-defined;
function Ada_To_COBOL (
Item : Character;
Substitute : COBOL_Character := '?')
return COBOL_Character;
-- modified
-- COBOL_To_Ada : array (COBOL_Character) of Character :=
-- implementation-defined;
function COBOL_To_Ada (
Item : COBOL_Character;
Substitute : Character := '?')
return Character;
type Alphanumeric is array (Positive range <>) of COBOL_Character;
pragma Pack (Alphanumeric);
-- modified
function To_COBOL (
Item : String;
Substitute : Alphanumeric := "?") -- additional
return Alphanumeric;
-- modified
function To_Ada (
Item : Alphanumeric;
Substitute : String := "?") -- additional
return String;
-- modified
procedure To_COBOL (
Item : String;
Target : out Alphanumeric;
Last : out Natural;
Substitute : Alphanumeric := "?"); -- additional
-- modified
procedure To_Ada (
Item : Alphanumeric;
Target : out String;
Last : out Natural;
Substitute : String := "?"); -- additional
type Numeric is array (Positive range <>) of COBOL_Character;
pragma Pack (Numeric);
-- Formats for COBOL data representations
type Display_Format is private;
Unsigned : constant Display_Format;
Leading_Separate : constant Display_Format;
Trailing_Separate : constant Display_Format;
Leading_Nonseparate : constant Display_Format;
Trailing_Nonseparate : constant Display_Format;
type Binary_Format is private;
High_Order_First : constant Binary_Format;
Low_Order_First : constant Binary_Format;
Native_Binary : constant Binary_Format;
type Packed_Format is private;
Packed_Unsigned : constant Packed_Format;
Packed_Signed : constant Packed_Format;
-- Types for external representation of COBOL binary data
type Byte is mod 2 ** COBOL_Character'Size;
type Byte_Array is array (Positive range <>) of Byte;
pragma Pack (Byte_Array);
Conversion_Error : exception;
generic
type Num is delta <> digits <>;
package Decimal_Conversions is
-- Display Formats: data values are represented as Numeric
function Valid (Item : Numeric; Format : Display_Format)
return Boolean;
function Length (Format : Display_Format) return Natural;
function To_Decimal (Item : Numeric; Format : Display_Format)
return Num;
function To_Display (Item : Num; Format : Display_Format)
return Numeric;
-- Packed Formats: data values are represented as Packed_Decimal
function Valid (Item : Packed_Decimal; Format : Packed_Format)
return Boolean;
function Length (Format : Packed_Format) return Natural;
function To_Decimal (Item : Packed_Decimal; Format : Packed_Format)
return Num;
function To_Packed (Item : Num; Format : Packed_Format)
return Packed_Decimal;
-- Binary Formats: external data values are represented as Byte_Array
function Valid (Item : Byte_Array; Format : Binary_Format)
return Boolean;
function Length (Format : Binary_Format) return Natural;
function To_Decimal (Item : Byte_Array; Format : Binary_Format)
return Num;
function To_Binary (Item : Num; Format : Binary_Format)
return Byte_Array;
-- Internal Binary formats:
-- data values are of type Binary or Long_Binary
function To_Decimal (Item : Binary) return Num;
function To_Decimal (Item : Long_Binary) return Num;
function To_Binary (Item : Num) return Binary;
function To_Long_Binary (Item : Num) return Long_Binary;
end Decimal_Conversions;
-- Note: This implementation assumes to interface with OpenCOBOL.
-- Nonseparated negative '0' .. '9' are encoded as 'p' .. 'y' in
-- the display formats Leading_Nonseparate and Trailing_Nonseparate.
-- 'C', 'A', 'E', and 'F' are positive, 'B' and 'D' are negative in
-- the packed format Packed_Signed.
private
type Display_Format is (U, LS, TS, LN, TN);
pragma Discard_Names (Display_Format);
Unsigned : constant Display_Format := U;
Leading_Separate : constant Display_Format := LS;
Trailing_Separate : constant Display_Format := TS;
Leading_Nonseparate : constant Display_Format := LN;
Trailing_Nonseparate : constant Display_Format := TN;
type Binary_Format is (H, L, N);
pragma Discard_Names (Binary_Format);
High_Order_First : constant Binary_Format := H;
Low_Order_First : constant Binary_Format := L;
Native_Binary : constant Binary_Format := N;
type Packed_Format is (U, S);
pragma Discard_Names (Packed_Format);
Packed_Unsigned : constant Packed_Format := U;
Packed_Signed : constant Packed_Format := S;
end Interfaces.COBOL;
|
With Ada.Text_IO; Use Ada.Text_IO;
Procedure MultiplicaMatriz is
type Integer_Matrix is array (Integer range <>, Integer range <>) of Integer'Base;
matriz1 : Integer_Matrix(1..3, 1..2);
matriz2 : Integer_Matrix(1..2, 1..3);
resultado: Integer_Matrix(1..3, 1..3);
-- Leitura String
function Get_String return String is
Line : String (1 .. 1_000);
Last : Natural;
begin
Get_Line (Line, Last);
return Line (1 .. Last);
end Get_String;
-- Leitura Integer
function Get_Integer return Integer is
S : constant String := Get_String;
begin
return Integer'Value (S);
end Get_Integer;
-- Lê 15 elementos do array
procedure Faz_Leitura is
begin
for L in Integer range 1 .. 3 loop
for C in Integer range 1 .. 2 loop
matriz1(L, C) := Get_Integer;
end loop;
end loop;
for L in Integer range 1 .. 2 loop
for C in Integer range 1 .. 3 loop
matriz2(L, C) := Get_Integer;
end loop;
end loop;
end Faz_Leitura;
procedure Print_Resultado is
begin
for L in Integer range 1 .. 3 loop
for C in Integer range 1 .. 3 loop
Put(Integer'Image(resultado(L, C)));
Put(" ");
end loop;
Put_Line("");
end loop;
end Print_Resultado;
procedure Inicializa is
begin
for I in Integer range 1 .. 3 loop
for J in Integer range 1 .. 3 loop
resultado(I, J) := 0;
end loop;
end loop;
end Inicializa;
procedure Multiplica is
begin
for I in Integer range 1 .. 3 loop
for J in Integer range 1 .. 3 loop
for K in Integer range 1 .. 2 loop
resultado(I, J) := resultado(I, J) + matriz1(I, K) * matriz2(K, J);
end loop;
end loop;
end loop;
end Multiplica;
begin
Faz_Leitura;
Inicializa;
Multiplica;
Print_Resultado;
end MultiplicaMatriz;
|
with Ada.Text_IO;
with BigInteger; use BigInteger;
package body Problem_13 is
package IO renames Ada.Text_IO;
procedure Solve is
type Problem_13_Array is Array (1 .. 100) of BigInt;
nums : Problem_13_Array;
sum : BigInt := BigInteger.Create(0);
begin
nums( 1) := BigInteger.Create("37107287533902102798797998220837590246510135740250");
nums( 2) := BigInteger.Create("46376937677490009712648124896970078050417018260538");
nums( 3) := BigInteger.Create("74324986199524741059474233309513058123726617309629");
nums( 4) := BigInteger.Create("91942213363574161572522430563301811072406154908250");
nums( 5) := BigInteger.Create("23067588207539346171171980310421047513778063246676");
nums( 6) := BigInteger.Create("89261670696623633820136378418383684178734361726757");
nums( 7) := BigInteger.Create("28112879812849979408065481931592621691275889832738");
nums( 8) := BigInteger.Create("44274228917432520321923589422876796487670272189318");
nums( 9) := BigInteger.Create("47451445736001306439091167216856844588711603153276");
nums( 10) := BigInteger.Create("70386486105843025439939619828917593665686757934951");
nums( 11) := BigInteger.Create("62176457141856560629502157223196586755079324193331");
nums( 12) := BigInteger.Create("64906352462741904929101432445813822663347944758178");
nums( 13) := BigInteger.Create("92575867718337217661963751590579239728245598838407");
nums( 14) := BigInteger.Create("58203565325359399008402633568948830189458628227828");
nums( 15) := BigInteger.Create("80181199384826282014278194139940567587151170094390");
nums( 16) := BigInteger.Create("35398664372827112653829987240784473053190104293586");
nums( 17) := BigInteger.Create("86515506006295864861532075273371959191420517255829");
nums( 18) := BigInteger.Create("71693888707715466499115593487603532921714970056938");
nums( 19) := BigInteger.Create("54370070576826684624621495650076471787294438377604");
nums( 20) := BigInteger.Create("53282654108756828443191190634694037855217779295145");
nums( 21) := BigInteger.Create("36123272525000296071075082563815656710885258350721");
nums( 22) := BigInteger.Create("45876576172410976447339110607218265236877223636045");
nums( 23) := BigInteger.Create("17423706905851860660448207621209813287860733969412");
nums( 24) := BigInteger.Create("81142660418086830619328460811191061556940512689692");
nums( 25) := BigInteger.Create("51934325451728388641918047049293215058642563049483");
nums( 26) := BigInteger.Create("62467221648435076201727918039944693004732956340691");
nums( 27) := BigInteger.Create("15732444386908125794514089057706229429197107928209");
nums( 28) := BigInteger.Create("55037687525678773091862540744969844508330393682126");
nums( 29) := BigInteger.Create("18336384825330154686196124348767681297534375946515");
nums( 30) := BigInteger.Create("80386287592878490201521685554828717201219257766954");
nums( 31) := BigInteger.Create("78182833757993103614740356856449095527097864797581");
nums( 32) := BigInteger.Create("16726320100436897842553539920931837441497806860984");
nums( 33) := BigInteger.Create("48403098129077791799088218795327364475675590848030");
nums( 34) := BigInteger.Create("87086987551392711854517078544161852424320693150332");
nums( 35) := BigInteger.Create("59959406895756536782107074926966537676326235447210");
nums( 36) := BigInteger.Create("69793950679652694742597709739166693763042633987085");
nums( 37) := BigInteger.Create("41052684708299085211399427365734116182760315001271");
nums( 38) := BigInteger.Create("65378607361501080857009149939512557028198746004375");
nums( 39) := BigInteger.Create("35829035317434717326932123578154982629742552737307");
nums( 40) := BigInteger.Create("94953759765105305946966067683156574377167401875275");
nums( 41) := BigInteger.Create("88902802571733229619176668713819931811048770190271");
nums( 42) := BigInteger.Create("25267680276078003013678680992525463401061632866526");
nums( 43) := BigInteger.Create("36270218540497705585629946580636237993140746255962");
nums( 44) := BigInteger.Create("24074486908231174977792365466257246923322810917141");
nums( 45) := BigInteger.Create("91430288197103288597806669760892938638285025333403");
nums( 46) := BigInteger.Create("34413065578016127815921815005561868836468420090470");
nums( 47) := BigInteger.Create("23053081172816430487623791969842487255036638784583");
nums( 48) := BigInteger.Create("11487696932154902810424020138335124462181441773470");
nums( 49) := BigInteger.Create("63783299490636259666498587618221225225512486764533");
nums( 50) := BigInteger.Create("67720186971698544312419572409913959008952310058822");
nums( 51) := BigInteger.Create("95548255300263520781532296796249481641953868218774");
nums( 52) := BigInteger.Create("76085327132285723110424803456124867697064507995236");
nums( 53) := BigInteger.Create("37774242535411291684276865538926205024910326572967");
nums( 54) := BigInteger.Create("23701913275725675285653248258265463092207058596522");
nums( 55) := BigInteger.Create("29798860272258331913126375147341994889534765745501");
nums( 56) := BigInteger.Create("18495701454879288984856827726077713721403798879715");
nums( 57) := BigInteger.Create("38298203783031473527721580348144513491373226651381");
nums( 58) := BigInteger.Create("34829543829199918180278916522431027392251122869539");
nums( 59) := BigInteger.Create("40957953066405232632538044100059654939159879593635");
nums( 60) := BigInteger.Create("29746152185502371307642255121183693803580388584903");
nums( 61) := BigInteger.Create("41698116222072977186158236678424689157993532961922");
nums( 62) := BigInteger.Create("62467957194401269043877107275048102390895523597457");
nums( 63) := BigInteger.Create("23189706772547915061505504953922979530901129967519");
nums( 64) := BigInteger.Create("86188088225875314529584099251203829009407770775672");
nums( 65) := BigInteger.Create("11306739708304724483816533873502340845647058077308");
nums( 66) := BigInteger.Create("82959174767140363198008187129011875491310547126581");
nums( 67) := BigInteger.Create("97623331044818386269515456334926366572897563400500");
nums( 68) := BigInteger.Create("42846280183517070527831839425882145521227251250327");
nums( 69) := BigInteger.Create("55121603546981200581762165212827652751691296897789");
nums( 70) := BigInteger.Create("32238195734329339946437501907836945765883352399886");
nums( 71) := BigInteger.Create("75506164965184775180738168837861091527357929701337");
nums( 72) := BigInteger.Create("62177842752192623401942399639168044983993173312731");
nums( 73) := BigInteger.Create("32924185707147349566916674687634660915035914677504");
nums( 74) := BigInteger.Create("99518671430235219628894890102423325116913619626622");
nums( 75) := BigInteger.Create("73267460800591547471830798392868535206946944540724");
nums( 76) := BigInteger.Create("76841822524674417161514036427982273348055556214818");
nums( 77) := BigInteger.Create("97142617910342598647204516893989422179826088076852");
nums( 78) := BigInteger.Create("87783646182799346313767754307809363333018982642090");
nums( 79) := BigInteger.Create("10848802521674670883215120185883543223812876952786");
nums( 80) := BigInteger.Create("71329612474782464538636993009049310363619763878039");
nums( 81) := BigInteger.Create("62184073572399794223406235393808339651327408011116");
nums( 82) := BigInteger.Create("66627891981488087797941876876144230030984490851411");
nums( 83) := BigInteger.Create("60661826293682836764744779239180335110989069790714");
nums( 84) := BigInteger.Create("85786944089552990653640447425576083659976645795096");
nums( 85) := BigInteger.Create("66024396409905389607120198219976047599490197230297");
nums( 86) := BigInteger.Create("64913982680032973156037120041377903785566085089252");
nums( 87) := BigInteger.Create("16730939319872750275468906903707539413042652315011");
nums( 88) := BigInteger.Create("94809377245048795150954100921645863754710598436791");
nums( 89) := BigInteger.Create("78639167021187492431995700641917969777599028300699");
nums( 90) := BigInteger.Create("15368713711936614952811305876380278410754449733078");
nums( 91) := BigInteger.Create("40789923115535562561142322423255033685442488917353");
nums( 92) := BigInteger.Create("44889911501440648020369068063960672322193204149535");
nums( 93) := BigInteger.Create("41503128880339536053299340368006977710650566631954");
nums( 94) := BigInteger.Create("81234880673210146739058568557934581403627822703280");
nums( 95) := BigInteger.Create("82616570773948327592232845941706525094512325230608");
nums( 96) := BigInteger.Create("22918802058777319719839450180888072429661980811197");
nums( 97) := BigInteger.Create("77158542502016545090413245809786882778948721859617");
nums( 98) := BigInteger.Create("72107838435069186155435662884062257473692284509516");
nums( 99) := BigInteger.Create("20849603980134001723930671666823555245252804609722");
nums(100) := BigInteger.Create("53503534226472524250874054075591789781264330331690");
for index in nums'Range loop
sum := sum + nums(index);
end loop;
declare
total : constant String := BigInteger.ToString(sum);
start : String (1 .. 10);
begin
for index in start'Range loop
start(index) := total(index);
end loop;
IO.Put_Line(start);
end;
end Solve;
end Problem_13;
|
-- This spec has been automatically generated from STM32F303xE.svd
-- Definition of the device's interrupts
package STM32_SVD.Interrupts is
----------------
-- Interrupts --
----------------
-- Window Watchdog interrupt
WWDG : constant := 0;
-- PVD through EXTI line detection interrupt
PVD : constant := 1;
-- Tamper and TimeStamp interrupts
TAMP_STAMP : constant := 2;
-- RTC Wakeup interrupt through the EXTI line
RTC_WKUP : constant := 3;
-- Flash global interrupt
FLASH : constant := 4;
-- RCC global interrupt
RCC : constant := 5;
-- EXTI Line0 interrupt
EXTI0 : constant := 6;
-- EXTI Line3 interrupt
EXTI1 : constant := 7;
-- EXTI Line2 and Touch sensing interrupts
EXTI2_TSC : constant := 8;
-- EXTI Line3 interrupt
EXTI3 : constant := 9;
-- EXTI Line4 interrupt
EXTI4 : constant := 10;
-- DMA1 channel 1 interrupt
DMA1_CH1 : constant := 11;
-- DMA1 channel 2 interrupt
DMA1_CH2 : constant := 12;
-- DMA1 channel 3 interrupt
DMA1_CH3 : constant := 13;
-- DMA1 channel 4 interrupt
DMA1_CH4 : constant := 14;
-- DMA1 channel 5 interrupt
DMA1_CH5 : constant := 15;
-- DMA1 channel 6 interrupt
DMA1_CH6 : constant := 16;
-- DMA1 channel 7interrupt
DMA1_CH7 : constant := 17;
-- ADC1 and ADC2 global interrupt
ADC1_2 : constant := 18;
-- USB High Priority/CAN_TX interrupts
USB_HP_CAN_TX : constant := 19;
-- USB Low Priority/CAN_RX0 interrupts
USB_LP_CAN_RX0 : constant := 20;
-- CAN_RX1 interrupt
CAN_RX1 : constant := 21;
-- CAN_SCE interrupt
CAN_SCE : constant := 22;
-- EXTI Line5 to Line9 interrupts
EXTI9_5 : constant := 23;
-- TIM1 Break/TIM15 global interruts
TIM1_BRK_TIM15 : constant := 24;
-- TIM1 Update/TIM16 global interrupts
TIM1_UP_TIM16 : constant := 25;
-- TIM1 trigger and commutation/TIM17 interrupts
TIM1_TRG_COM_TIM17 : constant := 26;
-- TIM1 capture compare interrupt
TIM1_CC : constant := 27;
-- TIM2 global interrupt
TIM2 : constant := 28;
-- TIM3 global interrupt
TIM3 : constant := 29;
-- TIM4 global interrupt
TIM4 : constant := 30;
-- I2C1 event interrupt and EXTI Line23 interrupt
I2C1_EV_EXTI23 : constant := 31;
-- I2C1 error interrupt
I2C1_ER : constant := 32;
-- I2C2 event interrupt & EXTI Line24 interrupt
I2C2_EV_EXTI24 : constant := 33;
-- I2C2 error interrupt
I2C2_ER : constant := 34;
-- SPI1 global interrupt
SPI1 : constant := 35;
-- SPI2 global interrupt
SPI2 : constant := 36;
-- USART1 global interrupt and EXTI Line 25 interrupt
USART1_EXTI25 : constant := 37;
-- USART2 global interrupt and EXTI Line 26 interrupt
USART2_EXTI26 : constant := 38;
-- USART3 global interrupt and EXTI Line 28 interrupt
USART3_EXTI28 : constant := 39;
-- EXTI Line15 to Line10 interrupts
EXTI15_10 : constant := 40;
-- RTC alarm interrupt
RTCAlarm : constant := 41;
-- USB wakeup from Suspend
USB_WKUP : constant := 42;
-- TIM8 break interrupt
TIM8_BRK : constant := 43;
-- TIM8 update interrupt
TIM8_UP : constant := 44;
-- TIM8 Trigger and commutation interrupts
TIM8_TRG_COM : constant := 45;
-- TIM8 capture compare interrupt
TIM8_CC : constant := 46;
-- ADC3 global interrupt
ADC3 : constant := 47;
-- SPI3 global interrupt
SPI3 : constant := 51;
-- UART4 global and EXTI Line 34 interrupts
UART4_EXTI34 : constant := 52;
-- UART5 global and EXTI Line 35 interrupts
UART5_EXTI35 : constant := 53;
-- TIM6 global and DAC12 underrun interrupts
TIM6_DACUNDER : constant := 54;
-- TIM7 global interrupt
TIM7 : constant := 55;
-- DMA2 channel1 global interrupt
DMA2_CH1 : constant := 56;
-- DMA2 channel2 global interrupt
DMA2_CH2 : constant := 57;
-- DMA2 channel3 global interrupt
DMA2_CH3 : constant := 58;
-- DMA2 channel4 global interrupt
DMA2_CH4 : constant := 59;
-- DMA2 channel5 global interrupt
DMA2_CH5 : constant := 60;
-- ADC4 global interrupt
ADC4 : constant := 61;
-- COMP1 & COMP2 & COMP3 interrupts combined with EXTI Lines 21, 22 and 29
-- interrupts
COMP123 : constant := 64;
-- COMP4 & COMP5 & COMP6 interrupts combined with EXTI Lines 30, 31 and 32
-- interrupts
COMP456 : constant := 65;
-- COMP7 interrupt combined with EXTI Line 33 interrupt
COMP7 : constant := 66;
-- USB High priority interrupt
USB_HP : constant := 74;
-- USB Low priority interrupt
USB_LP : constant := 75;
-- USB wakeup from Suspend and EXTI Line 18
USB_WKUP_EXTI : constant := 76;
-- Floating point interrupt
FPU : constant := 81;
end STM32_SVD.Interrupts;
|
package zlib.Strings is
pragma Preelaborate;
procedure Deflate (
Stream : in out zlib.Stream;
In_Item : in String;
In_Last : out Natural;
Out_Item : out Ada.Streams.Stream_Element_Array;
Out_Last : out Ada.Streams.Stream_Element_Offset;
Finish : in Boolean;
Finished : out Boolean);
procedure Deflate (
Stream : in out zlib.Stream;
In_Item : in String;
In_Last : out Natural;
Out_Item : out Ada.Streams.Stream_Element_Array;
Out_Last : out Ada.Streams.Stream_Element_Offset);
procedure Deflate (
Stream : in out zlib.Stream;
Out_Item : out Ada.Streams.Stream_Element_Array;
Out_Last : out Ada.Streams.Stream_Element_Offset;
Finish : in Boolean;
Finished : out Boolean)
renames zlib.Deflate;
procedure Inflate (
Stream : in out zlib.Stream;
In_Item : in Ada.Streams.Stream_Element_Array;
In_Last : out Ada.Streams.Stream_Element_Offset;
Out_Item : out String;
Out_Last : out Natural;
Finish : in Boolean;
Finished : out Boolean);
procedure Inflate (
Stream : in out zlib.Stream;
In_Item : in Ada.Streams.Stream_Element_Array;
In_Last : out Ada.Streams.Stream_Element_Offset;
Out_Item : out String;
Out_Last : out Natural);
procedure Inflate (
Stream : in out zlib.Stream;
Out_Item : out String;
Out_Last : out Natural;
Finish : in Boolean;
Finished : out Boolean);
end zlib.Strings;
|
-- Abstract :
--
-- Subprograms common to more than one parser, higher-level than in wisitoken.ads
--
-- Copyright (C) 2018 - 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;
with WisiToken.Lexer;
with WisiToken.Syntax_Trees;
package WisiToken.Parse is
type Base_Parser is abstract new Ada.Finalization.Limited_Controlled with record
Trace : access WisiToken.Trace'Class;
Lexer : WisiToken.Lexer.Handle;
User_Data : WisiToken.Syntax_Trees.User_Data_Access;
Terminals : aliased WisiToken.Base_Token_Arrays.Vector;
Line_Begin_Token : aliased WisiToken.Line_Begin_Token_Vectors.Vector;
-- Line_Begin_Token (I) is the index into Terminals of the first
-- grammar token on line I. Line_Begin_Token.First_Index is the first
-- line containing a grammar token (after leading comments). However,
-- if the only token on line I is a non_grammar token (ie a comment,
-- or a newline for a blank line), Line_Begin_Token (I) is the last
-- grammar token on the previous non-blank line. If Line (I) is a
-- non-first line in a multi-line token, Line_Begin_Token (I) is
-- Invalid_Token_Index.
end record;
-- Common to all parsers. Finalize should free any allocated objects.
function Next_Grammar_Token (Parser : in out Base_Parser) return Token_ID;
-- Get next token from Lexer, call User_Data.Lexer_To_Augmented. If
-- it is a grammar token, store in Terminals and return its id.
-- Otherwise, repeat.
--
-- Propagates Fatal_Error from Lexer.
procedure Lex_All (Parser : in out Base_Parser);
-- Clear Terminals, Line_Begin_Token; reset User_Data. Then call
-- Next_Grammar_Token repeatedly until EOF_ID is returned.
--
-- The user must first call Lexer.Reset_* to set the input text.
procedure Parse (Parser : aliased in out Base_Parser) is abstract;
-- Call Lex_All, then execute parse algorithm to parse the tokens,
-- storing the result in Parser for Execute_Actions.
--
-- If a parse error is encountered, raises Syntax_Error.
-- Parser.Lexer_Errors and Parser contain information about the
-- errors.
--
-- For other errors, raises Parse_Error with an appropriate error
-- message.
function Tree (Parser : in Base_Parser) return Syntax_Trees.Tree is abstract;
-- Return the syntax tree resulting from the parse.
function Any_Errors (Parser : in Base_Parser) return Boolean is abstract;
procedure Put_Errors (Parser : in Base_Parser) is abstract;
-- Output error messages to Ada.Text_IO.Current_Error.
procedure Execute_Actions (Parser : in out Base_Parser) is abstract;
-- Execute all actions in Parser.Tree.
end WisiToken.Parse;
|
pragma License (Unrestricted);
-- Ada 2012
with Ada.Characters.Handling;
private with Ada.UCD;
package Ada.Wide_Wide_Characters.Handling is
-- pragma Pure;
pragma Preelaborate;
-- function Character_Set_Version return String;
Character_Set_Version : constant String;
function Is_Control (Item : Wide_Wide_Character) return Boolean
renames Characters.Handling.Overloaded_Is_Control;
function Is_Letter (Item : Wide_Wide_Character) return Boolean
renames Characters.Handling.Overloaded_Is_Letter;
function Is_Lower (Item : Wide_Wide_Character) return Boolean
renames Characters.Handling.Overloaded_Is_Lower;
function Is_Upper (Item : Wide_Wide_Character) return Boolean
renames Characters.Handling.Overloaded_Is_Upper;
function Is_Basic (Item : Wide_Wide_Character) return Boolean
renames Characters.Handling.Overloaded_Is_Basic;
-- Note: Wide_Wide_Characters.Handling.Is_Basic is incompatible with
-- Characters.Handling.Is_Basic. See AI12-0260-1.
function Is_Digit (Item : Wide_Wide_Character) return Boolean
renames Characters.Handling.Overloaded_Is_Digit;
function Is_Decimal_Digit (Item : Wide_Wide_Character) return Boolean
renames Is_Digit;
function Is_Hexadecimal_Digit (Item : Wide_Wide_Character) return Boolean
renames Characters.Handling.Overloaded_Is_Hexadecimal_Digit;
function Is_Alphanumeric (Item : Wide_Wide_Character) return Boolean
renames Characters.Handling.Overloaded_Is_Alphanumeric;
function Is_Special (Item : Wide_Wide_Character) return Boolean
renames Characters.Handling.Overloaded_Is_Special;
-- function Is_Line_Terminator (Item : Wide_Wide_Character) return Boolean;
-- function Is_Mark (Item : Wide_Wide_Character) return Boolean;
-- function Is_Other_Format (Item : Wide_Wide_Character) return Boolean;
-- function Is_Punctuation_Connector (Item : Wide_Wide_Character)
-- return Boolean;
-- function Is_Space (Item : Wide_Wide_Character) return Boolean;
function Is_Graphic (Item : Wide_Wide_Character) return Boolean
renames Characters.Handling.Overloaded_Is_Graphic;
function To_Basic (Item : Wide_Wide_Character) return Wide_Wide_Character
renames Characters.Handling.Overloaded_To_Basic;
function To_Lower (Item : Wide_Wide_Character) return Wide_Wide_Character
renames Characters.Handling.Overloaded_To_Lower;
function To_Upper (Item : Wide_Wide_Character) return Wide_Wide_Character
renames Characters.Handling.Overloaded_To_Upper;
function To_Lower (Item : Wide_Wide_String) return Wide_Wide_String
renames Characters.Handling.Overloaded_To_Lower;
function To_Upper (Item : Wide_Wide_String) return Wide_Wide_String
renames Characters.Handling.Overloaded_To_Upper;
function To_Basic (Item : Wide_Wide_String) return Wide_Wide_String
renames Characters.Handling.Overloaded_To_Basic;
private
Character_Set_Version : constant String := UCD.Version;
end Ada.Wide_Wide_Characters.Handling;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- S Y S T E M . M M A P --
-- --
-- B o d y --
-- --
-- Copyright (C) 2007-2020, AdaCore --
-- --
-- This library is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 3, or (at your option) any later --
-- version. This library is distributed in the hope that it will be useful, --
-- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN- --
-- TABILITY or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Ada.IO_Exceptions;
with Ada.Unchecked_Conversion;
with Ada.Unchecked_Deallocation;
with System.Strings; use System.Strings;
with System.Mmap.OS_Interface; use System.Mmap.OS_Interface;
package body System.Mmap is
type Mapped_File_Record is record
Current_Region : Mapped_Region;
-- The legacy API enables only one region to be mapped, directly
-- associated with the mapped file. This references this region.
File : System_File;
-- Underlying OS-level file
end record;
type Mapped_Region_Record is record
File : Mapped_File;
-- The file this region comes from. Be careful: for reading file, it is
-- valid to have it closed before one of its regions is free'd.
Write : Boolean;
-- Whether the file this region comes from is open for writing.
Data : Str_Access;
-- Unbounded access to the mapped content.
System_Offset : File_Size;
-- Position in the file of the first byte actually mapped in memory
User_Offset : File_Size;
-- Position in the file of the first byte requested by the user
System_Size : File_Size;
-- Size of the region actually mapped in memory
User_Size : File_Size;
-- Size of the region requested by the user
Mapped : Boolean;
-- Whether this region is actually memory mapped
Mutable : Boolean;
-- If the file is opened for reading, wheter this region is writable
Buffer : System.Strings.String_Access;
-- When this region is not actually memory mapped, contains the
-- requested bytes.
Mapping : System_Mapping;
-- Underlying OS-level data for the mapping, if any
end record;
Invalid_Mapped_Region_Record : constant Mapped_Region_Record :=
(null, False, null, 0, 0, 0, 0, False, False, null,
Invalid_System_Mapping);
Invalid_Mapped_File_Record : constant Mapped_File_Record :=
(Invalid_Mapped_Region, Invalid_System_File);
Empty_String : constant String := "";
-- Used to provide a valid empty Data for empty files, for instanc.
procedure Dispose is new Ada.Unchecked_Deallocation
(Mapped_File_Record, Mapped_File);
procedure Dispose is new Ada.Unchecked_Deallocation
(Mapped_Region_Record, Mapped_Region);
function Convert is new Ada.Unchecked_Conversion
(Standard.System.Address, Str_Access);
procedure Compute_Data (Region : Mapped_Region);
-- Fill the Data field according to system and user offsets. The region
-- must actually be mapped or bufferized.
procedure From_Disk (Region : Mapped_Region);
-- Read a region of some file from the disk
procedure To_Disk (Region : Mapped_Region);
-- Write the region of the file back to disk if necessary, and free memory
----------------------------
-- Open_Read_No_Exception --
----------------------------
function Open_Read_No_Exception
(Filename : String;
Use_Mmap_If_Available : Boolean := True) return Mapped_File
is
File : constant System_File :=
Open_Read (Filename, Use_Mmap_If_Available);
begin
if File = Invalid_System_File then
return Invalid_Mapped_File;
end if;
return new Mapped_File_Record'
(Current_Region => Invalid_Mapped_Region,
File => File);
end Open_Read_No_Exception;
---------------
-- Open_Read --
---------------
function Open_Read
(Filename : String;
Use_Mmap_If_Available : Boolean := True) return Mapped_File
is
Res : constant Mapped_File :=
Open_Read_No_Exception (Filename, Use_Mmap_If_Available);
begin
if Res = Invalid_Mapped_File then
raise Ada.IO_Exceptions.Name_Error
with "Cannot open " & Filename;
else
return Res;
end if;
end Open_Read;
----------------
-- Open_Write --
----------------
function Open_Write
(Filename : String;
Use_Mmap_If_Available : Boolean := True) return Mapped_File
is
File : constant System_File :=
Open_Write (Filename, Use_Mmap_If_Available);
begin
if File = Invalid_System_File then
raise Ada.IO_Exceptions.Name_Error
with "Cannot open " & Filename;
else
return new Mapped_File_Record'
(Current_Region => Invalid_Mapped_Region,
File => File);
end if;
end Open_Write;
-----------
-- Close --
-----------
procedure Close (File : in out Mapped_File) is
begin
-- Closing a closed file is allowed and should do nothing
if File = Invalid_Mapped_File then
return;
end if;
if File.Current_Region /= null then
Free (File.Current_Region);
end if;
if File.File /= Invalid_System_File then
Close (File.File);
end if;
Dispose (File);
end Close;
----------
-- Free --
----------
procedure Free (Region : in out Mapped_Region) is
Ignored : Integer;
pragma Unreferenced (Ignored);
begin
-- Freeing an already free'd file is allowed and should do nothing
if Region = Invalid_Mapped_Region then
return;
end if;
if Region.Mapping /= Invalid_System_Mapping then
Dispose_Mapping (Region.Mapping);
end if;
To_Disk (Region);
Dispose (Region);
end Free;
----------
-- Read --
----------
procedure Read
(File : Mapped_File;
Region : in out Mapped_Region;
Offset : File_Size := 0;
Length : File_Size := 0;
Mutable : Boolean := False)
is
File_Length : constant File_Size := Mmap.Length (File);
Req_Offset : constant File_Size := Offset;
Req_Length : File_Size := Length;
-- Offset and Length of the region to map, used to adjust mapping
-- bounds, reflecting what the user will see.
Region_Allocated : Boolean := False;
begin
-- If this region comes from another file, or simply if the file is
-- writeable, we cannot re-use this mapping: free it first.
if Region /= Invalid_Mapped_Region
and then
(Region.File /= File or else File.File.Write)
then
Free (Region);
end if;
if Region = Invalid_Mapped_Region then
Region := new Mapped_Region_Record'(Invalid_Mapped_Region_Record);
Region_Allocated := True;
end if;
Region.File := File;
if Req_Offset >= File_Length then
-- If the requested offset goes beyond file size, map nothing
Req_Length := 0;
elsif Length = 0
or else
Length > File_Length - Req_Offset
then
-- If Length is 0 or goes beyond file size, map till end of file
Req_Length := File_Length - Req_Offset;
else
Req_Length := Length;
end if;
-- Past this point, the offset/length the user will see is fixed. On the
-- other hand, the system offset/length is either already defined, from
-- a previous mapping, or it is set to 0. In the latter case, the next
-- step will set them according to the mapping.
Region.User_Offset := Req_Offset;
Region.User_Size := Req_Length;
-- If the requested region is inside an already mapped region, adjust
-- user-requested data and do nothing else.
if (File.File.Write or else Region.Mutable = Mutable)
and then
Req_Offset >= Region.System_Offset
and then
(Req_Offset + Req_Length
<= Region.System_Offset + Region.System_Size)
then
Region.User_Offset := Req_Offset;
Compute_Data (Region);
return;
elsif Region.Buffer /= null then
-- Otherwise, as we are not going to re-use the buffer, free it
System.Strings.Free (Region.Buffer);
Region.Buffer := null;
elsif Region.Mapping /= Invalid_System_Mapping then
-- Otherwise, there is a memory mapping that we need to unmap.
Dispose_Mapping (Region.Mapping);
end if;
-- mmap() will sometimes return NULL when the file exists but is empty,
-- which is not what we want, so in the case of a zero length file we
-- fall back to read(2)/write(2)-based mode.
if File_Length > 0 and then File.File.Mapped then
Region.System_Offset := Req_Offset;
Region.System_Size := Req_Length;
Create_Mapping
(File.File,
Region.System_Offset, Region.System_Size,
Mutable,
Region.Mapping);
Region.Mapped := True;
Region.Mutable := Mutable;
else
-- There is no alignment requirement when manually reading the file.
Region.System_Offset := Req_Offset;
Region.System_Size := Req_Length;
Region.Mapped := False;
Region.Mutable := True;
From_Disk (Region);
end if;
Region.Write := File.File.Write;
Compute_Data (Region);
exception
when others =>
-- Before propagating any exception, free any region we allocated
-- here.
if Region_Allocated then
Dispose (Region);
end if;
raise;
end Read;
----------
-- Read --
----------
procedure Read
(File : Mapped_File;
Offset : File_Size := 0;
Length : File_Size := 0;
Mutable : Boolean := False)
is
begin
Read (File, File.Current_Region, Offset, Length, Mutable);
end Read;
----------
-- Read --
----------
function Read
(File : Mapped_File;
Offset : File_Size := 0;
Length : File_Size := 0;
Mutable : Boolean := False) return Mapped_Region
is
Region : Mapped_Region := Invalid_Mapped_Region;
begin
Read (File, Region, Offset, Length, Mutable);
return Region;
end Read;
------------
-- Length --
------------
function Length (File : Mapped_File) return File_Size is
begin
return File.File.Length;
end Length;
------------
-- Offset --
------------
function Offset (Region : Mapped_Region) return File_Size is
begin
return Region.User_Offset;
end Offset;
------------
-- Offset --
------------
function Offset (File : Mapped_File) return File_Size is
begin
return Offset (File.Current_Region);
end Offset;
----------
-- Last --
----------
function Last (Region : Mapped_Region) return Integer is
begin
return Integer (Region.User_Size);
end Last;
----------
-- Last --
----------
function Last (File : Mapped_File) return Integer is
begin
return Last (File.Current_Region);
end Last;
-------------------
-- To_Str_Access --
-------------------
function To_Str_Access
(Str : System.Strings.String_Access) return Str_Access is
begin
if Str = null then
return null;
else
return Convert (Str.all'Address);
end if;
end To_Str_Access;
----------
-- Data --
----------
function Data (Region : Mapped_Region) return Str_Access is
begin
return Region.Data;
end Data;
----------
-- Data --
----------
function Data (File : Mapped_File) return Str_Access is
begin
return Data (File.Current_Region);
end Data;
----------------
-- Is_Mutable --
----------------
function Is_Mutable (Region : Mapped_Region) return Boolean is
begin
return Region.Mutable or Region.Write;
end Is_Mutable;
----------------
-- Is_Mmapped --
----------------
function Is_Mmapped (File : Mapped_File) return Boolean is
begin
return File.File.Mapped;
end Is_Mmapped;
-------------------
-- Get_Page_Size --
-------------------
function Get_Page_Size return Integer is
Result : constant File_Size := Get_Page_Size;
begin
return Integer (Result);
end Get_Page_Size;
---------------------
-- Read_Whole_File --
---------------------
function Read_Whole_File
(Filename : String;
Empty_If_Not_Found : Boolean := False)
return System.Strings.String_Access
is
File : Mapped_File := Open_Read (Filename);
Region : Mapped_Region renames File.Current_Region;
Result : String_Access;
begin
Read (File);
if Region.Data /= null then
Result := new String'(String
(Region.Data (1 .. Last (Region))));
elsif Region.Buffer /= null then
Result := Region.Buffer;
Region.Buffer := null; -- So that it is not deallocated
end if;
Close (File);
return Result;
exception
when Ada.IO_Exceptions.Name_Error =>
if Empty_If_Not_Found then
return new String'("");
else
return null;
end if;
when others =>
Close (File);
return null;
end Read_Whole_File;
---------------
-- From_Disk --
---------------
procedure From_Disk (Region : Mapped_Region) is
begin
pragma Assert (Region.File.all /= Invalid_Mapped_File_Record);
pragma Assert (Region.Buffer = null);
Region.Buffer := Read_From_Disk
(Region.File.File, Region.User_Offset, Region.User_Size);
Region.Mapped := False;
end From_Disk;
-------------
-- To_Disk --
-------------
procedure To_Disk (Region : Mapped_Region) is
begin
if Region.Write and then Region.Buffer /= null then
pragma Assert (Region.File.all /= Invalid_Mapped_File_Record);
Write_To_Disk
(Region.File.File,
Region.User_Offset, Region.User_Size,
Region.Buffer);
end if;
System.Strings.Free (Region.Buffer);
Region.Buffer := null;
end To_Disk;
------------------
-- Compute_Data --
------------------
procedure Compute_Data (Region : Mapped_Region) is
Base_Data : Str_Access;
-- Address of the first byte actually mapped in memory
Data_Shift : constant Integer :=
Integer (Region.User_Offset - Region.System_Offset);
begin
if Region.User_Size = 0 then
Region.Data := Convert (Empty_String'Address);
return;
elsif Region.Mapped then
Base_Data := Convert (Region.Mapping.Address);
else
Base_Data := Convert (Region.Buffer.all'Address);
end if;
Region.Data := Convert (Base_Data (Data_Shift + 1)'Address);
end Compute_Data;
end System.Mmap;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- Copyright (C) 2012-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. --
-- --
------------------------------------------------------------------------------
-- This file is based on the startup code from the following file in Nordic's
-- nRF5 SDK (version 15.1.0): modules/nrfx/mdk/system_nrf52.c for errata
-- workarounds and configuration of the SWD pins and reset pin.
--
-- This Errata_X functions detect if certain errata are applicable for the
-- MCU. If they are applicable, then a workaround is applied for the errata.
-- Some of these errata workarounds rely on reading and/or writing registers
-- that are not documented in the datasheet. As mentioned above, these
-- register addresses and values are copied from Nordic's nRF5 SDK.
pragma Ada_2012; -- To work around pre-commit check?
pragma Suppress (All_Checks);
with System;
with System.Machine_Code; use System.Machine_Code;
with Interfaces; use Interfaces;
with Interfaces.NRF52; use Interfaces.NRF52;
with Interfaces.NRF52.CLOCK; use Interfaces.NRF52.CLOCK;
with Interfaces.NRF52.FICR; use Interfaces.NRF52.FICR;
with Interfaces.NRF52.GPIO; use Interfaces.NRF52.GPIO;
with Interfaces.NRF52.NVMC; use Interfaces.NRF52.NVMC;
with Interfaces.NRF52.UICR; use Interfaces.NRF52.UICR;
with Interfaces.NRF52.TEMP; use Interfaces.NRF52.TEMP;
procedure Setup_Board is
---------------------------
-- Board Configuration --
---------------------------
Use_HFXO : constant Boolean := False;
-- Set to True to use the high-frequency external oscillator (HFXO).
-- When False, the on-chip oscillator is used.
-- The HFXO can also be turned on and off later by the main program.
LFCLK_Source : constant LFCLKSRC_SRC_Field := Xtal;
-- Selects the source for the LFCLK.
-- Xtal selects the external 32.768 kHz crystal (LFXO).
-- Rc selects the internal 32.768 kHz RC oscillator.
-- Synth selects the LFCLK synthesized from the 16 MHz HFCLK.
Use_SWO_Trace : constant Boolean := True;
-- Set to True to enable the SWO trace pins.
Use_Reset_Pin : constant Boolean := True;
-- When True, P0.18 will be configured as the reset pin.
--------------------------
-- Errata Workarounds --
--------------------------
-- Some of these registers are not documented in the Objective Product Spec
-- but they are used in the nRF5 SDK startup code to detect when
-- certain errata are applicable.
Undocumented_Reg_1 : UInt32
with Address => System'To_Address (16#F000_0FE0#);
Undocumented_Reg_2 : UInt32
with Address => System'To_Address (16#F000_0FE4#);
Undocumented_Reg_3 : UInt32
with Address => System'To_Address (16#F000_0FE8#);
Undocumented_Reg_4 : UInt32
with Address => System'To_Address (16#1000_0130#);
Undocumented_Reg_5 : UInt32
with Address => System'To_Address (16#1000_0134#);
-- Undocumented registers used for the workaround of erratas 12, 16
Errata_12_Reg_1 : UInt32
with Volatile, Address => System'To_Address (16#4001_3540#);
Errata_12_Reg_2 : UInt32
with Volatile, Address => System'To_Address (16#1000_0324#);
Errata_16_Reg : UInt32
with Volatile, Address => System'To_Address (16#4007_C074#);
Errata_31_Reg_1 : UInt32
with Volatile, Address => System'To_Address (16#4000_053C#);
Errata_31_Reg_2 : UInt32
with Volatile, Address => System'To_Address (16#1000_0244#);
Errata_37_Reg : UInt32
with Volatile, Address => System'To_Address (16#4000_05A0#);
Errata_57_Reg_1 : UInt32
with Volatile, Address => System'To_Address (16#4000_5610#);
Errata_57_Reg_2 : UInt32
with Volatile, Address => System'To_Address (16#4000_5688#);
Errata_57_Reg_3 : UInt32
with Volatile, Address => System'To_Address (16#4000_5618#);
Errata_57_Reg_4 : UInt32
with Volatile, Address => System'To_Address (16#4000_5614#);
Errata_108_Reg_1 : UInt32
with Volatile, Address => System'To_Address (16#4000_0EE4#);
Errata_108_Reg_2 : UInt32
with Volatile, Address => System'To_Address (16#1000_0258#);
Errata_182_Reg : UInt32
with Volatile, Address => System'To_Address (16#4000_173C#);
CoreDebug_DEMCR : UInt32
with Volatile, Address => System'To_Address (16#E000_EDFC#);
DEMCR_TRCENA_Mask : constant UInt32 := 16#0100_0000#;
-- The POWER.RESETREAS register.
-- We define this here instead of including Interfaces.POWER as a
-- workaround for a warning about unused bits in the definition
-- of RAM_Cluster in the auto-generated code.
POWER_RESETREAS : UInt32
with Volatile, Address => System'To_Address (16#4000_0400#);
-- The following functions detect if different errata are applicable on
-- the specific MCU revision. For example, Errata_12 checks if a errata #12
-- is applicable ("COMP: Reference ladder not correctly calibrated").
function Errata_12 return Boolean is
(((Undocumented_Reg_1 and 16#FF#) = 6)
and ((Undocumented_Reg_2 and 16#F#) = 0)
and ((Undocumented_Reg_3 and 16#F0#) in 16#30# | 16#40# | 16#50#))
with Inline_Always;
function Errata_16 return Boolean is
(((Undocumented_Reg_1 and 16#FF#) = 6)
and ((Undocumented_Reg_2 and 16#F#) = 0)
and ((Undocumented_Reg_3 and 16#F0#) = 16#30#))
with Inline_Always;
function Errata_31 return Boolean is
(((Undocumented_Reg_1 and 16#FF#) = 6)
and ((Undocumented_Reg_2 and 16#F#) = 0)
and ((Undocumented_Reg_3 and 16#F0#) in 16#30# | 16#40# | 16#50#))
with Inline_Always;
function Errata_32 return Boolean is
(((Undocumented_Reg_1 and 16#FF#) = 6)
and ((Undocumented_Reg_2 and 16#F#) = 0)
and ((Undocumented_Reg_3 and 16#F0#) = 16#30#))
with Inline_Always;
function Errata_36 return Boolean is
(((Undocumented_Reg_1 and 16#FF#) = 6)
and ((Undocumented_Reg_2 and 16#F#) = 0)
and ((Undocumented_Reg_3 and 16#F0#) in 16#30# | 16#40# | 16#50#))
with Inline_Always;
function Errata_37 return Boolean is
(((Undocumented_Reg_1 and 16#FF#) = 6)
and ((Undocumented_Reg_2 and 16#F#) = 0)
and ((Undocumented_Reg_3 and 16#F0#) = 16#30#))
with Inline_Always;
function Errata_57 return Boolean is
(((Undocumented_Reg_1 and 16#FF#) = 6)
and ((Undocumented_Reg_2 and 16#F#) = 0)
and ((Undocumented_Reg_3 and 16#F0#) = 16#30#))
with Inline_Always;
function Errata_66 return Boolean is
(((Undocumented_Reg_1 and 16#FF#) = 6)
and ((Undocumented_Reg_2 and 16#F#) = 0)
and ((Undocumented_Reg_3 and 16#F0#) = 16#50#))
with Inline_Always;
function Errata_108 return Boolean is
(((Undocumented_Reg_1 and 16#FF#) = 6)
and ((Undocumented_Reg_2 and 16#F#) = 0)
and ((Undocumented_Reg_3 and 16#F0#) in 16#30# | 16#40# | 16#50#))
with Inline_Always;
function Errata_136 return Boolean is
(((Undocumented_Reg_1 and 16#FF#) = 6)
and ((Undocumented_Reg_2 and 16#F#) = 0)
and ((Undocumented_Reg_3 and 16#F0#) in 16#30# | 16#40# | 16#50#))
with Inline_Always;
function Errata_182 return Boolean is
(Undocumented_Reg_4 = 6 and Undocumented_Reg_5 = 6)
with Inline_Always;
procedure NVIC_SystemReset;
procedure NVIC_SystemReset is
SCB_AIRCR : UInt32
with Volatile, Address => System'To_Address (16#E000_ED0C#);
VECTKEY : constant UInt32 := 16#05FA_0000#;
PRIGROUP_Mask : constant UInt32 := 16#0000_0700#;
SYSRESETREQ : constant UInt32 := 16#0000_0004#;
begin
-- Ensure all outstanding memory accesses including buffered write
-- are completed before reset
Asm ("dsb", Volatile => True);
SCB_AIRCR := VECTKEY or (SCB_AIRCR and PRIGROUP_Mask) or SYSRESETREQ;
Asm ("dsb", Volatile => True);
loop
null;
end loop;
end NVIC_SystemReset;
begin
-- Enable SWO trace pins
if Use_SWO_Trace then
CoreDebug_DEMCR := CoreDebug_DEMCR or DEMCR_TRCENA_Mask;
CLOCK_Periph.TRACECONFIG.TRACEMUX := Serial;
P0_Periph.PIN_CNF (18) := PIN_CNF_Register'
(DIR => Output,
INPUT => Connect,
PULL => Disabled,
Reserved_4_7 => 0,
DRIVE => H0H1,
Reserved_11_15 => 0,
SENSE => Disabled,
Reserved_18_31 => 0);
end if;
-- Workaround for Errata 12 "COMP: Reference ladder not correctly
-- calibrated"
if Errata_12 then
Errata_12_Reg_1 := Shift_Right (Errata_12_Reg_2 and 16#1F00#, 8);
end if;
-- Workaround for Errata 16 "System: RAM may be corrupt on wakeup from
-- CPU IDLE"
if Errata_16 then
Errata_16_Reg := 3131961357;
end if;
-- Workaround for Errata 31 "CLOCK: Calibration values are not correctly
-- loaded from FICR at reset"
if Errata_31 then
Errata_31_Reg_1 := Shift_Right (Errata_31_Reg_2 and 16#E000#, 13);
end if;
-- Workaround for Errata 32 "DIF: Debug session automatically enables
-- TracePort pins"
if Errata_32 then
CoreDebug_DEMCR := CoreDebug_DEMCR and (not DEMCR_TRCENA_Mask);
end if;
-- Workaround for Errata 36 "CLOCK: Some registers are not reset when
-- expected"
if Errata_36 then
CLOCK_Periph.EVENTS_DONE := (EVENTS_DONE => 0, others => <>);
CLOCK_Periph.EVENTS_CTTO := (EVENTS_CTTO => 0, others => <>);
CLOCK_Periph.CTIV := (CTIV => 0, Reserved_7_31 => 0);
end if;
-- Workaround for Errata 37 "RADIO: Encryption engine is slow by default"
if Errata_37 then
Errata_37_Reg := 3;
end if;
-- Workaround for Errata 57 "NFCT: NFC Modulation amplitude"
if Errata_57 then
Errata_57_Reg_1 := 16#0000_0005#;
Errata_57_Reg_2 := 16#0000_0001#;
Errata_57_Reg_3 := 16#0000_0000#;
Errata_57_Reg_4 := 16#0000_003F#;
end if;
-- Workaround for Errata 66 "TEMP: Linearity specification not met with
-- default settings"
if Errata_66 then
TEMP_Periph.A0.A0 := FICR_Periph.TEMP.A0.A;
TEMP_Periph.A1.A1 := FICR_Periph.TEMP.A1.A;
TEMP_Periph.A2.A2 := FICR_Periph.TEMP.A2.A;
TEMP_Periph.A3.A3 := FICR_Periph.TEMP.A3.A;
TEMP_Periph.A4.A4 := FICR_Periph.TEMP.A4.A;
TEMP_Periph.A5.A5 := FICR_Periph.TEMP.A5.A;
TEMP_Periph.B0.B0 := FICR_Periph.TEMP.B0.B;
TEMP_Periph.B1.B1 := FICR_Periph.TEMP.B1.B;
TEMP_Periph.B2.B2 := FICR_Periph.TEMP.B2.B;
TEMP_Periph.B3.B3 := FICR_Periph.TEMP.B3.B;
TEMP_Periph.B4.B4 := FICR_Periph.TEMP.B4.B;
TEMP_Periph.B5.B5 := FICR_Periph.TEMP.B5.B;
TEMP_Periph.T0.T0 := FICR_Periph.TEMP.T0.T;
TEMP_Periph.T1.T1 := FICR_Periph.TEMP.T1.T;
TEMP_Periph.T2.T2 := FICR_Periph.TEMP.T2.T;
TEMP_Periph.T3.T3 := FICR_Periph.TEMP.T3.T;
TEMP_Periph.T4.T4 := FICR_Periph.TEMP.T4.T;
end if;
-- Workaround for Errata 108 "RAM: RAM content cannot be trusted upon
-- waking up from System ON Idle or System OFF mode"
if Errata_108 then
Errata_108_Reg_1 := Errata_108_Reg_2 and 16#0000_004F#;
end if;
-- Workaround for Errata 136 "System: Bits in RESETREAS are set when they
-- should not be"
if Errata_136 then
-- Clear all flags except RESETPIN if RESETPIN is the reset reason
if (POWER_RESETREAS and 16#0000_0001#) /= 0 then
POWER_RESETREAS := 16#FFFF_FFFE#;
end if;
end if;
-- Workaround for Errata 182 "RADIO: Fixes for anomalies #102, #106, and
-- #107 do not take effect"
if Errata_182 then
Errata_182_Reg := Errata_182_Reg or 16#200#;
end if;
if Use_Reset_Pin then
-- Enable nRESET pin on P0.18
if UICR_Periph.PSELRESET (0).CONNECT = Disconnected or
UICR_Periph.PSELRESET (1).CONNECT = Disconnected
then
NVMC_Periph.CONFIG := CONFIG_Register'
(WEN => Wen,
Reserved_2_31 => 0);
loop
exit when NVMC_Periph.READY.READY = Ready;
end loop;
UICR_Periph.PSELRESET (0) := PSELRESET_Register'
(PIN => 21,
Reserved_6_30 => 0,
CONNECT => Connected);
loop
exit when NVMC_Periph.READY.READY = Ready;
end loop;
UICR_Periph.PSELRESET (1) := PSELRESET_Register'
(PIN => 21,
Reserved_6_30 => 0,
CONNECT => Connected);
loop
exit when NVMC_Periph.READY.READY = Ready;
end loop;
NVMC_Periph.CONFIG := CONFIG_Register'
(WEN => Ren,
Reserved_2_31 => 0);
loop
exit when NVMC_Periph.READY.READY = Ready;
end loop;
NVIC_SystemReset;
end if;
end if;
-- Configure the 32.768 kHz external crystal.
-- The LFCLK will be started later, if required by the runtime.
--
-- The Ravenscar runtime uses LFCLK as its timing source for task delays,
-- so LFCLK will be started by System.BB.Board_Support.Initialize_Board.
--
-- The ZFP runtime does not use LFCLK, so it is not started in ZFP.
CLOCK_Periph.LFCLKSRC := LFCLKSRC_Register'
(SRC => LFCLK_Source,
Reserved_2_15 => 0,
BYPASS => Disabled,
EXTERNAL => Disabled,
Reserved_18_31 => 0);
-- Optionally enable the external HFXO.
-- If HFXO is disabled, then the HFCLK will use the internal HF oscillator
if Use_HFXO then
CLOCK_Periph.TASKS_HFCLKSTART := (TASKS_HFCLKSTART => 1, others => <>);
end if;
end Setup_Board;
|
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Float_Random; use Ada.Numerics.Float_Random;
procedure Test_Monte_Carlo is
Dice : Generator;
function Pi (Throws : Positive) return Float is
Inside : Natural := 0;
begin
for Throw in 1..Throws loop
if Random (Dice) ** 2 + Random (Dice) ** 2 <= 1.0 then
Inside := Inside + 1;
end if;
end loop;
return 4.0 * Float (Inside) / Float (Throws);
end Pi;
begin
Put_Line (" 10_000:" & Float'Image (Pi ( 10_000)));
Put_Line (" 100_000:" & Float'Image (Pi ( 100_000)));
Put_Line (" 1_000_000:" & Float'Image (Pi ( 1_000_000)));
Put_Line (" 10_000_000:" & Float'Image (Pi ( 10_000_000)));
Put_Line ("100_000_000:" & Float'Image (Pi (100_000_000)));
end Test_Monte_Carlo;
|
------------------------------------------------------------------------------
-- --
-- tiled-code-gen --
-- --
-- Copyright (C) 2018 Fabien Chouteau --
-- --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with Interfaces;
package TCG.Palette is
subtype Component is Interfaces.Unsigned_8;
type ARGB_Color is record
A, R, G, B : Component;
end record;
type Color_Id is new Natural;
type Output_Color_Format is (ARGB, RGB565, RGB565_Swap, RGB555, RGB888);
function Add_Color (C : ARGB_Color) return Color_Id;
function Convert (Id : Color_Id) return ARGB_Color;
function In_Palette (C : ARGB_Color) return Boolean;
-- Return True is the given color is already definied in the palette
function Transparent_Defined return Boolean;
-- Return True is the the transparent collor is alreadty defined
function Transparent return Color_Id
with Pre => Transparent_Defined;
-- Return the color defined as transparent
function Transparent return ARGB_Color
with Pre => Transparent_Defined;
-- Return the color defined as transparent
procedure Set_Transparent (C : ARGB_Color)
with Pre => (not Transparent_Defined or else Transparent = C)
and then not In_Palette (C),
Post => Transparent_Defined and then Transparent = C;
-- Set the color that will be treated as transparent.
function Number_Of_Colors return Natural;
function First_Id return Color_Id;
-- Return the first valid Color_Id
function Last_Id return Color_Id;
-- Return the last valid Color_Id
function Image (Id : Color_Id) return String;
-- Return a string representing a color id (not the color itself)
function Image (C : ARGB_Color;
Format : Output_Color_Format)
return String;
-- Return a string representing the color using the given format
function Format_Supported (Fmt : String) return Boolean;
-- Return True if the Fmt string represent a supported color format
function Supported_Formats return String;
-- Return a String that contains the names of all supported color formats
function Convert (Fmt : String) return Output_Color_Format
with Pre => Format_Supported (Fmt);
-- Return the Output_Color_Format designated by the Fmt string
function To_ARGB (Str : String) return ARGB_Color
with Pre => Str'Length = 6;
-- Convert and 6 hexadecimal characters string to ARGB_Color
procedure Put;
private
function Image (C : ARGB_Color) return String;
function To_RGB565 (C : ARGB_Color) return Interfaces.Unsigned_16;
function To_RGB565_Swap (C : ARGB_Color) return Interfaces.Unsigned_16;
function To_RGB555 (C : ARGB_Color) return Interfaces.Unsigned_16;
function To_RGB888 (C : ARGB_Color) return Interfaces.Unsigned_32;
end TCG.Palette;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- SQL Database Access --
-- --
-- Examples Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2011-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$
------------------------------------------------------------------------------
with Ada.Wide_Wide_Text_IO;
with League.Strings;
with League.Holders.Floats;
with League.Holders.Integers;
--with Matreshka.Internals.SQL_Drivers.Firebird.Factory;
--with Matreshka.Internals.SQL_Drivers.MySQL.Factory;
--with Matreshka.Internals.SQL_Drivers.Oracle.Factory;
--with Matreshka.Internals.SQL_Drivers.PostgreSQL.Factory;
with Matreshka.Internals.SQL_Drivers.SQLite3.Factory;
with SQL.Databases;
with SQL.Options;
with SQL.Queries;
procedure Simple_SQL is
function "+"
(Item : Wide_Wide_String) return League.Strings.Universal_String
renames League.Strings.To_Universal_String;
-- DB_Driver : constant League.Strings.Universal_String := +"MYSQL";
-- MySQL
-- DB_Type : constant League.Strings.Universal_String := +"ORACLE";
-- Oracle
-- DB_Driver : constant League.Strings.Universal_String := +"POSTGRESQL";
-- PostgreSQL
DB_Driver : constant League.Strings.Universal_String := +"SQLITE3";
-- SQLite3
-- DB_Driver : constant League.Strings.Universal_String := +"FIREBIRD";
-- DB_Options : constant League.Strings.Universal_String :=
-- +"SYSDBA/masterkey@localhost:/tmp/aaa";
-- Firebird
DB_Options : SQL.Options.SQL_Options;
begin
-- MySQL
-- DB_Options.Set (+"database", +"test");
-- Oracle
-- DB_Options.Set
-- (Matreshka.Internals.SQL_Drivers.Oracle.User_Option, +"scott");
-- DB_Options.Set
-- (Matreshka.Internals.SQL_Drivers.Oracle.Password_Option, +"tiger");
-- DB_Options.Set
-- (Matreshka.Internals.SQL_Drivers.Oracle.Database_Option, +"db");
-- PostgreSQL
-- SQLite3
DB_Options.Set (+"filename", +"test.db");
declare
D : aliased SQL.Databases.SQL_Database
:= SQL.Databases.Create (DB_Driver, DB_Options);
begin
D.Open;
declare
Q : SQL.Queries.SQL_Query := D.Query;
begin
Q.Prepare
(+"CREATE TABLE point (x INTEGER, y CHARACTER VARYING (6), z FLOAT)");
Q.Execute;
end;
declare
Q : SQL.Queries.SQL_Query := D.Query;
begin
Q.Prepare (+"INSERT INTO point (x, y, z) VALUES (:x, :y, :z)");
Q.Bind_Value (+":z", League.Holders.Floats.To_Holder (4.5));
Q.Bind_Value (+":y", League.Holders.To_Holder (+"xyz"));
Q.Bind_Value (+":x", League.Holders.Integers.To_Holder (5));
Q.Execute;
end;
declare
Q : aliased SQL.Queries.SQL_Query := D.Query;
begin
Q.Prepare (+"SELECT x, y, z FROM point");
Q.Execute;
while Q.Next loop
Ada.Wide_Wide_Text_IO.Put_Line
(Integer'Wide_Wide_Image
(League.Holders.Integers.Element (Q.Value (1)))
& ":"
& League.Holders.Element (Q.Value (2)).To_Wide_Wide_String
& ":"
& Float'Wide_Wide_Image
(League.Holders.Floats.Element (Q.Value (3))));
end loop;
end;
D.Close;
end;
end Simple_SQL;
|
--
-- Copyright (C) 2018, AdaCore
--
-- Copyright (c) 2013, 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:
--
-- * 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 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.
--
-- 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.
--
-- This spec has been automatically generated from nrf51.svd
pragma Ada_2012;
pragma Style_Checks (Off);
with System;
package Interfaces.NRF51.UART is
pragma Preelaborate;
pragma No_Elaboration_Code_All;
---------------
-- Registers --
---------------
-- Shortcut between CTS event and STARTRX task.
type SHORTS_CTS_STARTRX_Field is
(
-- Shortcut disabled.
Disabled,
-- Shortcut enabled.
Enabled)
with Size => 1;
for SHORTS_CTS_STARTRX_Field use
(Disabled => 0,
Enabled => 1);
-- Shortcut between NCTS event and STOPRX task.
type SHORTS_NCTS_STOPRX_Field is
(
-- Shortcut disabled.
Disabled,
-- Shortcut enabled.
Enabled)
with Size => 1;
for SHORTS_NCTS_STOPRX_Field use
(Disabled => 0,
Enabled => 1);
-- Shortcuts for UART.
type SHORTS_Register is record
-- unspecified
Reserved_0_2 : Interfaces.NRF51.UInt3 := 16#0#;
-- Shortcut between CTS event and STARTRX task.
CTS_STARTRX : SHORTS_CTS_STARTRX_Field :=
Interfaces.NRF51.UART.Disabled;
-- Shortcut between NCTS event and STOPRX task.
NCTS_STOPRX : SHORTS_NCTS_STOPRX_Field :=
Interfaces.NRF51.UART.Disabled;
-- unspecified
Reserved_5_31 : Interfaces.NRF51.UInt27 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for SHORTS_Register use record
Reserved_0_2 at 0 range 0 .. 2;
CTS_STARTRX at 0 range 3 .. 3;
NCTS_STOPRX at 0 range 4 .. 4;
Reserved_5_31 at 0 range 5 .. 31;
end record;
-- Enable interrupt on CTS event.
type INTENSET_CTS_Field is
(
-- Interrupt disabled.
Disabled,
-- Interrupt enabled.
Enabled)
with Size => 1;
for INTENSET_CTS_Field use
(Disabled => 0,
Enabled => 1);
-- Enable interrupt on CTS event.
type INTENSET_CTS_Field_1 is
(
-- Reset value for the field
Intenset_Cts_Field_Reset,
-- Enable interrupt on write.
Set)
with Size => 1;
for INTENSET_CTS_Field_1 use
(Intenset_Cts_Field_Reset => 0,
Set => 1);
-- Enable interrupt on NCTS event.
type INTENSET_NCTS_Field is
(
-- Interrupt disabled.
Disabled,
-- Interrupt enabled.
Enabled)
with Size => 1;
for INTENSET_NCTS_Field use
(Disabled => 0,
Enabled => 1);
-- Enable interrupt on NCTS event.
type INTENSET_NCTS_Field_1 is
(
-- Reset value for the field
Intenset_Ncts_Field_Reset,
-- Enable interrupt on write.
Set)
with Size => 1;
for INTENSET_NCTS_Field_1 use
(Intenset_Ncts_Field_Reset => 0,
Set => 1);
-- Enable interrupt on RXRDY event.
type INTENSET_RXDRDY_Field is
(
-- Interrupt disabled.
Disabled,
-- Interrupt enabled.
Enabled)
with Size => 1;
for INTENSET_RXDRDY_Field use
(Disabled => 0,
Enabled => 1);
-- Enable interrupt on RXRDY event.
type INTENSET_RXDRDY_Field_1 is
(
-- Reset value for the field
Intenset_Rxdrdy_Field_Reset,
-- Enable interrupt on write.
Set)
with Size => 1;
for INTENSET_RXDRDY_Field_1 use
(Intenset_Rxdrdy_Field_Reset => 0,
Set => 1);
-- Enable interrupt on TXRDY event.
type INTENSET_TXDRDY_Field is
(
-- Interrupt disabled.
Disabled,
-- Interrupt enabled.
Enabled)
with Size => 1;
for INTENSET_TXDRDY_Field use
(Disabled => 0,
Enabled => 1);
-- Enable interrupt on TXRDY event.
type INTENSET_TXDRDY_Field_1 is
(
-- Reset value for the field
Intenset_Txdrdy_Field_Reset,
-- Enable interrupt on write.
Set)
with Size => 1;
for INTENSET_TXDRDY_Field_1 use
(Intenset_Txdrdy_Field_Reset => 0,
Set => 1);
-- Enable interrupt on ERROR event.
type INTENSET_ERROR_Field is
(
-- Interrupt disabled.
Disabled,
-- Interrupt enabled.
Enabled)
with Size => 1;
for INTENSET_ERROR_Field use
(Disabled => 0,
Enabled => 1);
-- Enable interrupt on ERROR event.
type INTENSET_ERROR_Field_1 is
(
-- Reset value for the field
Intenset_Error_Field_Reset,
-- Enable interrupt on write.
Set)
with Size => 1;
for INTENSET_ERROR_Field_1 use
(Intenset_Error_Field_Reset => 0,
Set => 1);
-- Enable interrupt on RXTO event.
type INTENSET_RXTO_Field is
(
-- Interrupt disabled.
Disabled,
-- Interrupt enabled.
Enabled)
with Size => 1;
for INTENSET_RXTO_Field use
(Disabled => 0,
Enabled => 1);
-- Enable interrupt on RXTO event.
type INTENSET_RXTO_Field_1 is
(
-- Reset value for the field
Intenset_Rxto_Field_Reset,
-- Enable interrupt on write.
Set)
with Size => 1;
for INTENSET_RXTO_Field_1 use
(Intenset_Rxto_Field_Reset => 0,
Set => 1);
-- Interrupt enable set register.
type INTENSET_Register is record
-- Enable interrupt on CTS event.
CTS : INTENSET_CTS_Field_1 := Intenset_Cts_Field_Reset;
-- Enable interrupt on NCTS event.
NCTS : INTENSET_NCTS_Field_1 := Intenset_Ncts_Field_Reset;
-- Enable interrupt on RXRDY event.
RXDRDY : INTENSET_RXDRDY_Field_1 := Intenset_Rxdrdy_Field_Reset;
-- unspecified
Reserved_3_6 : Interfaces.NRF51.UInt4 := 16#0#;
-- Enable interrupt on TXRDY event.
TXDRDY : INTENSET_TXDRDY_Field_1 := Intenset_Txdrdy_Field_Reset;
-- unspecified
Reserved_8_8 : Interfaces.NRF51.Bit := 16#0#;
-- Enable interrupt on ERROR event.
ERROR : INTENSET_ERROR_Field_1 := Intenset_Error_Field_Reset;
-- unspecified
Reserved_10_16 : Interfaces.NRF51.UInt7 := 16#0#;
-- Enable interrupt on RXTO event.
RXTO : INTENSET_RXTO_Field_1 := Intenset_Rxto_Field_Reset;
-- unspecified
Reserved_18_31 : Interfaces.NRF51.UInt14 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for INTENSET_Register use record
CTS at 0 range 0 .. 0;
NCTS at 0 range 1 .. 1;
RXDRDY at 0 range 2 .. 2;
Reserved_3_6 at 0 range 3 .. 6;
TXDRDY at 0 range 7 .. 7;
Reserved_8_8 at 0 range 8 .. 8;
ERROR at 0 range 9 .. 9;
Reserved_10_16 at 0 range 10 .. 16;
RXTO at 0 range 17 .. 17;
Reserved_18_31 at 0 range 18 .. 31;
end record;
-- Disable interrupt on CTS event.
type INTENCLR_CTS_Field is
(
-- Interrupt disabled.
Disabled,
-- Interrupt enabled.
Enabled)
with Size => 1;
for INTENCLR_CTS_Field use
(Disabled => 0,
Enabled => 1);
-- Disable interrupt on CTS event.
type INTENCLR_CTS_Field_1 is
(
-- Reset value for the field
Intenclr_Cts_Field_Reset,
-- Disable interrupt on write.
Clear)
with Size => 1;
for INTENCLR_CTS_Field_1 use
(Intenclr_Cts_Field_Reset => 0,
Clear => 1);
-- Disable interrupt on NCTS event.
type INTENCLR_NCTS_Field is
(
-- Interrupt disabled.
Disabled,
-- Interrupt enabled.
Enabled)
with Size => 1;
for INTENCLR_NCTS_Field use
(Disabled => 0,
Enabled => 1);
-- Disable interrupt on NCTS event.
type INTENCLR_NCTS_Field_1 is
(
-- Reset value for the field
Intenclr_Ncts_Field_Reset,
-- Disable interrupt on write.
Clear)
with Size => 1;
for INTENCLR_NCTS_Field_1 use
(Intenclr_Ncts_Field_Reset => 0,
Clear => 1);
-- Disable interrupt on RXRDY event.
type INTENCLR_RXDRDY_Field is
(
-- Interrupt disabled.
Disabled,
-- Interrupt enabled.
Enabled)
with Size => 1;
for INTENCLR_RXDRDY_Field use
(Disabled => 0,
Enabled => 1);
-- Disable interrupt on RXRDY event.
type INTENCLR_RXDRDY_Field_1 is
(
-- Reset value for the field
Intenclr_Rxdrdy_Field_Reset,
-- Disable interrupt on write.
Clear)
with Size => 1;
for INTENCLR_RXDRDY_Field_1 use
(Intenclr_Rxdrdy_Field_Reset => 0,
Clear => 1);
-- Disable interrupt on TXRDY event.
type INTENCLR_TXDRDY_Field is
(
-- Interrupt disabled.
Disabled,
-- Interrupt enabled.
Enabled)
with Size => 1;
for INTENCLR_TXDRDY_Field use
(Disabled => 0,
Enabled => 1);
-- Disable interrupt on TXRDY event.
type INTENCLR_TXDRDY_Field_1 is
(
-- Reset value for the field
Intenclr_Txdrdy_Field_Reset,
-- Disable interrupt on write.
Clear)
with Size => 1;
for INTENCLR_TXDRDY_Field_1 use
(Intenclr_Txdrdy_Field_Reset => 0,
Clear => 1);
-- Disable interrupt on ERROR event.
type INTENCLR_ERROR_Field is
(
-- Interrupt disabled.
Disabled,
-- Interrupt enabled.
Enabled)
with Size => 1;
for INTENCLR_ERROR_Field use
(Disabled => 0,
Enabled => 1);
-- Disable interrupt on ERROR event.
type INTENCLR_ERROR_Field_1 is
(
-- Reset value for the field
Intenclr_Error_Field_Reset,
-- Disable interrupt on write.
Clear)
with Size => 1;
for INTENCLR_ERROR_Field_1 use
(Intenclr_Error_Field_Reset => 0,
Clear => 1);
-- Disable interrupt on RXTO event.
type INTENCLR_RXTO_Field is
(
-- Interrupt disabled.
Disabled,
-- Interrupt enabled.
Enabled)
with Size => 1;
for INTENCLR_RXTO_Field use
(Disabled => 0,
Enabled => 1);
-- Disable interrupt on RXTO event.
type INTENCLR_RXTO_Field_1 is
(
-- Reset value for the field
Intenclr_Rxto_Field_Reset,
-- Disable interrupt on write.
Clear)
with Size => 1;
for INTENCLR_RXTO_Field_1 use
(Intenclr_Rxto_Field_Reset => 0,
Clear => 1);
-- Interrupt enable clear register.
type INTENCLR_Register is record
-- Disable interrupt on CTS event.
CTS : INTENCLR_CTS_Field_1 := Intenclr_Cts_Field_Reset;
-- Disable interrupt on NCTS event.
NCTS : INTENCLR_NCTS_Field_1 := Intenclr_Ncts_Field_Reset;
-- Disable interrupt on RXRDY event.
RXDRDY : INTENCLR_RXDRDY_Field_1 := Intenclr_Rxdrdy_Field_Reset;
-- unspecified
Reserved_3_6 : Interfaces.NRF51.UInt4 := 16#0#;
-- Disable interrupt on TXRDY event.
TXDRDY : INTENCLR_TXDRDY_Field_1 := Intenclr_Txdrdy_Field_Reset;
-- unspecified
Reserved_8_8 : Interfaces.NRF51.Bit := 16#0#;
-- Disable interrupt on ERROR event.
ERROR : INTENCLR_ERROR_Field_1 := Intenclr_Error_Field_Reset;
-- unspecified
Reserved_10_16 : Interfaces.NRF51.UInt7 := 16#0#;
-- Disable interrupt on RXTO event.
RXTO : INTENCLR_RXTO_Field_1 := Intenclr_Rxto_Field_Reset;
-- unspecified
Reserved_18_31 : Interfaces.NRF51.UInt14 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for INTENCLR_Register use record
CTS at 0 range 0 .. 0;
NCTS at 0 range 1 .. 1;
RXDRDY at 0 range 2 .. 2;
Reserved_3_6 at 0 range 3 .. 6;
TXDRDY at 0 range 7 .. 7;
Reserved_8_8 at 0 range 8 .. 8;
ERROR at 0 range 9 .. 9;
Reserved_10_16 at 0 range 10 .. 16;
RXTO at 0 range 17 .. 17;
Reserved_18_31 at 0 range 18 .. 31;
end record;
-- A start bit is received while the previous data still lies in RXD. (Data
-- loss).
type ERRORSRC_OVERRUN_Field is
(
-- Error not present.
Notpresent,
-- Error present.
Present)
with Size => 1;
for ERRORSRC_OVERRUN_Field use
(Notpresent => 0,
Present => 1);
-- A start bit is received while the previous data still lies in RXD. (Data
-- loss).
type ERRORSRC_OVERRUN_Field_1 is
(
-- Reset value for the field
Errorsrc_Overrun_Field_Reset,
-- Clear error on write.
Clear)
with Size => 1;
for ERRORSRC_OVERRUN_Field_1 use
(Errorsrc_Overrun_Field_Reset => 0,
Clear => 1);
-- A character with bad parity is received. Only checked if HW parity
-- control is enabled.
type ERRORSRC_PARITY_Field is
(
-- Error not present.
Notpresent,
-- Error present.
Present)
with Size => 1;
for ERRORSRC_PARITY_Field use
(Notpresent => 0,
Present => 1);
-- A character with bad parity is received. Only checked if HW parity
-- control is enabled.
type ERRORSRC_PARITY_Field_1 is
(
-- Reset value for the field
Errorsrc_Parity_Field_Reset,
-- Clear error on write.
Clear)
with Size => 1;
for ERRORSRC_PARITY_Field_1 use
(Errorsrc_Parity_Field_Reset => 0,
Clear => 1);
-- A valid stop bit is not detected on the serial data input after all bits
-- in a character have been received.
type ERRORSRC_FRAMING_Field is
(
-- Error not present.
Notpresent,
-- Error present.
Present)
with Size => 1;
for ERRORSRC_FRAMING_Field use
(Notpresent => 0,
Present => 1);
-- A valid stop bit is not detected on the serial data input after all bits
-- in a character have been received.
type ERRORSRC_FRAMING_Field_1 is
(
-- Reset value for the field
Errorsrc_Framing_Field_Reset,
-- Clear error on write.
Clear)
with Size => 1;
for ERRORSRC_FRAMING_Field_1 use
(Errorsrc_Framing_Field_Reset => 0,
Clear => 1);
-- The serial data input is '0' for longer than the length of a data frame.
type ERRORSRC_BREAK_Field is
(
-- Error not present.
Notpresent,
-- Error present.
Present)
with Size => 1;
for ERRORSRC_BREAK_Field use
(Notpresent => 0,
Present => 1);
-- The serial data input is '0' for longer than the length of a data frame.
type ERRORSRC_BREAK_Field_1 is
(
-- Reset value for the field
Errorsrc_Break_Field_Reset,
-- Clear error on write.
Clear)
with Size => 1;
for ERRORSRC_BREAK_Field_1 use
(Errorsrc_Break_Field_Reset => 0,
Clear => 1);
-- Error source. Write error field to 1 to clear error.
type ERRORSRC_Register is record
-- A start bit is received while the previous data still lies in RXD.
-- (Data loss).
OVERRUN : ERRORSRC_OVERRUN_Field_1 :=
Errorsrc_Overrun_Field_Reset;
-- A character with bad parity is received. Only checked if HW parity
-- control is enabled.
PARITY : ERRORSRC_PARITY_Field_1 := Errorsrc_Parity_Field_Reset;
-- A valid stop bit is not detected on the serial data input after all
-- bits in a character have been received.
FRAMING : ERRORSRC_FRAMING_Field_1 :=
Errorsrc_Framing_Field_Reset;
-- The serial data input is '0' for longer than the length of a data
-- frame.
BREAK : ERRORSRC_BREAK_Field_1 := Errorsrc_Break_Field_Reset;
-- unspecified
Reserved_4_31 : Interfaces.NRF51.UInt28 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for ERRORSRC_Register use record
OVERRUN at 0 range 0 .. 0;
PARITY at 0 range 1 .. 1;
FRAMING at 0 range 2 .. 2;
BREAK at 0 range 3 .. 3;
Reserved_4_31 at 0 range 4 .. 31;
end record;
-- Enable or disable UART and acquire IOs.
type ENABLE_ENABLE_Field is
(
-- UART disabled.
Disabled,
-- UART enabled.
Enabled)
with Size => 3;
for ENABLE_ENABLE_Field use
(Disabled => 0,
Enabled => 4);
-- Enable UART and acquire IOs.
type ENABLE_Register is record
-- Enable or disable UART and acquire IOs.
ENABLE : ENABLE_ENABLE_Field := Interfaces.NRF51.UART.Disabled;
-- unspecified
Reserved_3_31 : Interfaces.NRF51.UInt29 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for ENABLE_Register use record
ENABLE at 0 range 0 .. 2;
Reserved_3_31 at 0 range 3 .. 31;
end record;
subtype RXD_RXD_Field is Interfaces.NRF51.Byte;
-- RXD register. On read action the buffer pointer is displaced. Once read
-- the character is consumed. If read when no character available, the UART
-- will stop working.
type RXD_Register is record
-- Read-only. *** Reading this field has side effects on other resources
-- ***. RX data from previous transfer. Double buffered.
RXD : RXD_RXD_Field;
-- unspecified
Reserved_8_31 : Interfaces.NRF51.UInt24;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for RXD_Register use record
RXD at 0 range 0 .. 7;
Reserved_8_31 at 0 range 8 .. 31;
end record;
subtype TXD_TXD_Field is Interfaces.NRF51.Byte;
-- TXD register.
type TXD_Register is record
-- Write-only. TX data for transfer.
TXD : TXD_TXD_Field := 16#0#;
-- unspecified
Reserved_8_31 : Interfaces.NRF51.UInt24 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for TXD_Register use record
TXD at 0 range 0 .. 7;
Reserved_8_31 at 0 range 8 .. 31;
end record;
-- Hardware flow control.
type CONFIG_HWFC_Field is
(
-- Hardware flow control disabled.
Disabled,
-- Hardware flow control enabled.
Enabled)
with Size => 1;
for CONFIG_HWFC_Field use
(Disabled => 0,
Enabled => 1);
-- Include parity bit.
type CONFIG_PARITY_Field is
(
-- Parity bit excluded.
Excluded,
-- Parity bit included.
Included)
with Size => 3;
for CONFIG_PARITY_Field use
(Excluded => 0,
Included => 7);
-- Configuration of parity and hardware flow control register.
type CONFIG_Register is record
-- Hardware flow control.
HWFC : CONFIG_HWFC_Field := Interfaces.NRF51.UART.Disabled;
-- Include parity bit.
PARITY : CONFIG_PARITY_Field := Interfaces.NRF51.UART.Excluded;
-- unspecified
Reserved_4_31 : Interfaces.NRF51.UInt28 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for CONFIG_Register use record
HWFC at 0 range 0 .. 0;
PARITY at 0 range 1 .. 3;
Reserved_4_31 at 0 range 4 .. 31;
end record;
-- Peripheral power control.
type POWER_POWER_Field is
(
-- Module power disabled.
Disabled,
-- Module power enabled.
Enabled)
with Size => 1;
for POWER_POWER_Field use
(Disabled => 0,
Enabled => 1);
-- Peripheral power control.
type POWER_Register is record
-- Peripheral power control.
POWER : POWER_POWER_Field := Interfaces.NRF51.UART.Disabled;
-- unspecified
Reserved_1_31 : Interfaces.NRF51.UInt31 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for POWER_Register use record
POWER at 0 range 0 .. 0;
Reserved_1_31 at 0 range 1 .. 31;
end record;
-----------------
-- Peripherals --
-----------------
-- Universal Asynchronous Receiver/Transmitter.
type UART_Peripheral is record
-- Start UART receiver.
TASKS_STARTRX : aliased Interfaces.NRF51.UInt32;
-- Stop UART receiver.
TASKS_STOPRX : aliased Interfaces.NRF51.UInt32;
-- Start UART transmitter.
TASKS_STARTTX : aliased Interfaces.NRF51.UInt32;
-- Stop UART transmitter.
TASKS_STOPTX : aliased Interfaces.NRF51.UInt32;
-- Suspend UART.
TASKS_SUSPEND : aliased Interfaces.NRF51.UInt32;
-- CTS activated.
EVENTS_CTS : aliased Interfaces.NRF51.UInt32;
-- CTS deactivated.
EVENTS_NCTS : aliased Interfaces.NRF51.UInt32;
-- Data received in RXD.
EVENTS_RXDRDY : aliased Interfaces.NRF51.UInt32;
-- Data sent from TXD.
EVENTS_TXDRDY : aliased Interfaces.NRF51.UInt32;
-- Error detected.
EVENTS_ERROR : aliased Interfaces.NRF51.UInt32;
-- Receiver timeout.
EVENTS_RXTO : aliased Interfaces.NRF51.UInt32;
-- Shortcuts for UART.
SHORTS : aliased SHORTS_Register;
-- Interrupt enable set register.
INTENSET : aliased INTENSET_Register;
-- Interrupt enable clear register.
INTENCLR : aliased INTENCLR_Register;
-- Error source. Write error field to 1 to clear error.
ERRORSRC : aliased ERRORSRC_Register;
-- Enable UART and acquire IOs.
ENABLE : aliased ENABLE_Register;
-- Pin select for RTS.
PSELRTS : aliased Interfaces.NRF51.UInt32;
-- Pin select for TXD.
PSELTXD : aliased Interfaces.NRF51.UInt32;
-- Pin select for CTS.
PSELCTS : aliased Interfaces.NRF51.UInt32;
-- Pin select for RXD.
PSELRXD : aliased Interfaces.NRF51.UInt32;
-- RXD register. On read action the buffer pointer is displaced. Once
-- read the character is consumed. If read when no character available,
-- the UART will stop working.
RXD : aliased RXD_Register;
-- TXD register.
TXD : aliased TXD_Register;
-- UART Baudrate.
BAUDRATE : aliased Interfaces.NRF51.UInt32;
-- Configuration of parity and hardware flow control register.
CONFIG : aliased CONFIG_Register;
-- Peripheral power control.
POWER : aliased POWER_Register;
end record
with Volatile;
for UART_Peripheral use record
TASKS_STARTRX at 16#0# range 0 .. 31;
TASKS_STOPRX at 16#4# range 0 .. 31;
TASKS_STARTTX at 16#8# range 0 .. 31;
TASKS_STOPTX at 16#C# range 0 .. 31;
TASKS_SUSPEND at 16#1C# range 0 .. 31;
EVENTS_CTS at 16#100# range 0 .. 31;
EVENTS_NCTS at 16#104# range 0 .. 31;
EVENTS_RXDRDY at 16#108# range 0 .. 31;
EVENTS_TXDRDY at 16#11C# range 0 .. 31;
EVENTS_ERROR at 16#124# range 0 .. 31;
EVENTS_RXTO at 16#144# range 0 .. 31;
SHORTS at 16#200# range 0 .. 31;
INTENSET at 16#304# range 0 .. 31;
INTENCLR at 16#308# range 0 .. 31;
ERRORSRC at 16#480# range 0 .. 31;
ENABLE at 16#500# range 0 .. 31;
PSELRTS at 16#508# range 0 .. 31;
PSELTXD at 16#50C# range 0 .. 31;
PSELCTS at 16#510# range 0 .. 31;
PSELRXD at 16#514# range 0 .. 31;
RXD at 16#518# range 0 .. 31;
TXD at 16#51C# range 0 .. 31;
BAUDRATE at 16#524# range 0 .. 31;
CONFIG at 16#56C# range 0 .. 31;
POWER at 16#FFC# range 0 .. 31;
end record;
-- Universal Asynchronous Receiver/Transmitter.
UART0_Periph : aliased UART_Peripheral
with Import, Address => System'To_Address (16#40002000#);
end Interfaces.NRF51.UART;
|
type Restricted is range 1..10;
My_Var : Restricted;
if My_Var = 5 then
-- do something
elsif My_Var > 5 then
-- do something
else
-- do something
end if;
|
-- WORDS, a Latin dictionary, by Colonel William Whitaker (USAF, Retired)
--
-- Copyright William A. Whitaker (1936–2010)
--
-- This is a free program, which means it is proper to copy it and pass
-- it on to your friends. Consider it a developmental item for which
-- there is no charge. However, just for form, it is Copyrighted
-- (c). Permission is hereby freely given for any and all use of program
-- and data. You can sell it as your own, but at least tell me.
--
-- This version is distributed without obligation, but the developer
-- would appreciate comments and suggestions.
--
-- All parts of the WORDS system, source code and data files, are made freely
-- available to anyone who wishes to use them, for whatever purpose.
with Ada.Integer_Text_IO;
separate (Latin_Utils.Inflections_Package)
package body Decn_Record_IO is
---------------------------------------------------------------------------
procedure Get (File : in File_Type; Item : out Decn_Record)
is
Spacer : Character := ' ';
pragma Unreferenced (Spacer);
begin
Ada.Integer_Text_IO.Get (File, Item.Which);
Get (File, Spacer);
Ada.Integer_Text_IO.Get (File, Item.Var);
end Get;
---------------------------------------------------------------------------
procedure Get (Item : out Decn_Record)
is
Spacer : Character := ' ';
pragma Unreferenced (Spacer);
begin
Ada.Integer_Text_IO.Get (Item.Which);
Get (Spacer);
Ada.Integer_Text_IO.Get (Item.Var);
end Get;
---------------------------------------------------------------------------
procedure Put (File : in File_Type; Item : in Decn_Record) is
begin
Ada.Integer_Text_IO.Put (File, Item.Which, 1);
Put (File, ' ');
Ada.Integer_Text_IO.Put (File, Item.Var, 1);
end Put;
---------------------------------------------------------------------------
procedure Put (Item : in Decn_Record) is
begin
Ada.Integer_Text_IO.Put (Item.Which, 1);
Put (' ');
Ada.Integer_Text_IO.Put (Item.Var, 1);
end Put;
---------------------------------------------------------------------------
procedure Get
(Source : in String;
Target : out Decn_Record;
Last : out Integer
)
is
-- This variable are used for computing lower bound of substrings
Low : Integer := Source'First - 1;
begin
Ada.Integer_Text_IO.Get
(Source (Low + 1 .. Source'Last), Target.Which, Low);
Low := Low + 1;
Ada.Integer_Text_IO.Get
(Source (Low + 1 .. Source'Last), Target.Var, Last);
end Get;
---------------------------------------------------------------------------
procedure Put (Target : out String; Item : in Decn_Record)
is
-- These variables are used for computing bounds of substrings
Low : Integer := Target'First - 1;
High : Integer := 0;
begin
-- Put Which_Type
High := Low + 1;
Ada.Integer_Text_IO.Put (Target (Low + 1 .. High), Item.Which);
Low := High + 1;
-- Put Variant_Type
Target (Low) := ' ';
High := Low + 1;
Ada.Integer_Text_IO.Put (Target (Low + 1 .. High), Item.Var);
-- Fill remainder of String
Target (High + 1 .. Target'Last) := (others => ' ');
end Put;
---------------------------------------------------------------------------
end Decn_Record_IO;
|
with Ada.Strings.Bounded;
package Trie is
package BoundedString is new Ada.Strings.Bounded.Generic_Bounded_Length(Max => 16);
type Trie is private;
type Fragment_Endpoints is record
first, last : Positive;
end record;
type Fragment_Endpoint_Array is Array(Positive range <>) of Fragment_Endpoints;
function Make_Trie(filename : String) return Trie;
procedure Find_Words(words : Trie; fragments: String; endpoints: Fragment_Endpoint_Array);
private
type Trie_Node;
type Trie_Node_Access is access Trie_Node;
type Trie_Descendant is Array (Character range 'a' .. 'z') of Trie_Node_Access;
type Trie_Node is record
is_terminal : Boolean;
word : BoundedString.Bounded_String;
children : Trie_Descendant;
end record;
type Trie is record
root : Trie_Node_Access;
node_count : Natural;
end record;
end Trie;
|
----------------------------------------------------------------------------
-- Symbolic Expressions (symexpr)
--
-- Copyright (C) 2012, Riccardo Bernardini
--
-- This file is part of symexpr.
--
-- symexpr is free software: you can redistribute it and/or modify
-- it under the terms of the Lesser GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- symexpr is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the Lesser GNU General Public License
-- along with gclp. If not, see <http://www.gnu.org/licenses/>.
----------------------------------------------------------------------------
--
-- <summary>
-- I wrote the first version of this package a day when I wanted to allow
-- the user of a program to specify values in a symbolic form like
-- "max(intro.end, bluesheet.end)" After writing the code that handled this
-- type of expression, I noticed that the code was general enough and with
-- minimal effort I converted it to a generic package that I succesively
-- improved.
--
-- This package allows you to handle expression in "symbolic" form inside
-- your program. Expressions operate on "scalars" whose type parametrizes
-- this package (so you can have expressions of floats, integers or...
-- dates [my case]).
--
-- You can
--
-- (A) Construct symbolic expression
-- => by parsing strings with Parse, e.g.,
--
-- X := parse("2*3 - max(y, abs(u))")
--
-- => by constructing them using the provided constructors and
-- operators. For example,
--
-- X := Variable("x");
-- Poly := to_expr(12)*X*X - to_expr(4)*x + to_expr(1);
-- Top := Function_Call("max", Function_Call("abs", x), Poly);
--
-- in this case Top is an expression that represents the function
--
-- max(abs(x), 12*x*x - 4*x + 1)
--
-- (B) Replace variables in expression with scalars or other
-- expressions (function Replace)
--
-- (C) Evaluate an expression. For example, to plot a graph of Top(X)
-- you can use
--
-- for I in 1..10 loop
-- Plot(I, Eval(Replace(Top, "x", I)));
-- end loop;
--
-- As said above, this package is parameterized by the type of the scalar.
-- It requires that the usual operators (+, -, *, ...) are defined.
-- </summary>
-- with Ada.Strings.Unbounded;
with Ada.Finalization;
with Ada.Containers.Indefinite_Ordered_Maps;
with Ada.Containers.Indefinite_Ordered_Sets;
-- with Symbolic_Identifiers;
--
--
--
generic
type Scalar_Type is private;
-- The type representing the scalars
type Scalar_Array is array (Positive range <>) of Scalar_Type;
type Identifier is private;
with function "<" (L, R : Identifier) return Boolean is <>;
with function "+" (X : Scalar_Type) return Scalar_Type is <>;
with function "-" (X : Scalar_Type) return Scalar_Type is <>;
with function "+" (L, R : Scalar_Type) return Scalar_Type is <>;
with function "-" (L, R : Scalar_Type) return Scalar_Type is <>;
with function "*" (L, R : Scalar_Type) return Scalar_Type is <>;
with function "/" (L, R : Scalar_Type) return Scalar_Type is <>;
with function Call (Name : Identifier; Param : Scalar_Array)
return Scalar_Type is <>;
-- Callback used to evaluate the functions in a Symoblic_Expression
-- Name is the name of the function, while Param will store the
-- parameters given to the function
with function Image (Item : Scalar_Type) return String;
-- Return a text representation of a scalar
with function ID_Image (Item : Identifier) return String;
-- Return a text representation of a scalar
package Symbolic_Expressions is
-- use type Symbolic_Identifiers.Identifier;
subtype Variable_Name is Identifier;
subtype Function_Name is Identifier;
type Symbolic_Expression is new
Ada.Finalization.Controlled
with
private;
type Expression_Array is array (Positive range <>) of Symbolic_Expression;
function Is_Constant (X : Symbolic_Expression) return Boolean;
-- Return true if X has no free variables
Not_A_Scalar : exception;
function Eval (X : Symbolic_Expression) return Scalar_Type;
-- Evaluate expression X and return the corresponding scalar value.
-- Raise Not_A_Scalar is Is_Constant(X) is false
function To_Expr (X : Scalar_Type) return Symbolic_Expression;
-- Return an expression representing the value of X
function Variable (Name : Variable_Name) return Symbolic_Expression;
-- Return an expression representing the given variable
function Function_Call (Name : Function_Name;
Parameters : Expression_Array)
return Symbolic_Expression;
-- Return an expression representing a function call
function "+" (L : Symbolic_Expression) return Symbolic_Expression;
function "-" (L : Symbolic_Expression) return Symbolic_Expression;
function "+" (L, R : Symbolic_Expression) return Symbolic_Expression;
function "-" (L, R : Symbolic_Expression) return Symbolic_Expression;
function "*" (L, R : Symbolic_Expression) return Symbolic_Expression;
function "/" (L, R : Symbolic_Expression) return Symbolic_Expression;
function "+" (L : Symbolic_Expression; R : Scalar_Type) return Symbolic_Expression;
function "-" (L : Symbolic_Expression; R : Scalar_Type) return Symbolic_Expression;
function "*" (L : Symbolic_Expression; R : Scalar_Type) return Symbolic_Expression;
function "/" (L : Symbolic_Expression; R : Scalar_Type) return Symbolic_Expression;
function "+" (L : Scalar_Type; R : Symbolic_Expression) return Symbolic_Expression;
function "-" (L : Scalar_Type; R : Symbolic_Expression) return Symbolic_Expression;
function "*" (L : Scalar_Type; R : Symbolic_Expression) return Symbolic_Expression;
function "/" (L : Scalar_Type; R : Symbolic_Expression) return Symbolic_Expression;
package Variable_Sets is
new Ada.Containers.Indefinite_Ordered_Sets (Variable_Name);
function Free_Variables (Item : Symbolic_Expression)
return Variable_Sets.Set;
-- Return the name of the variables used in Item
procedure Iterate_On_Vars (Item : Symbolic_Expression;
Process : access procedure (Var_Name : Variable_Name));
-- Call Process for every variable in Item
function Replace (Item : Symbolic_Expression;
Var_Name : Variable_Name;
Value : Scalar_Type)
return Symbolic_Expression;
-- Replace every occurence of Var_Name in Item with the given scalar value
package Variable_Tables is
new Ada.Containers.Indefinite_Ordered_Maps
(Key_Type => Variable_Name,
Element_Type => Scalar_Type);
-- Maps Variable_Tables.Maps are used to associate values to
-- variable names
function Replace (Item : Symbolic_Expression;
Table : Variable_Tables.Map)
return Symbolic_Expression;
-- For every variable in Item, check if the variable name is a key
-- of Table and, if found, replace every occurence of the variable
-- with the corresponding value stored in Table.
function Replace (Item : Symbolic_Expression;
Var_Name : Variable_Name;
Value : Symbolic_Expression)
return Symbolic_Expression;
-- Replace every instance of variable Var_Name with the expression
-- Value
-- ============= --
-- == PARSING == --
-- ============= --
-- =========== --
-- == DEBUG == --
-- =========== --
function Dump (Item : Symbolic_Expression) return String;
-- Return a textual representation of Item. Useful for debugging.
-- Currently it returns a tree-like string similar to
--
-- *
-- Const 4
-- -
-- +
-- Const 5
-- Const 1
-- Call max
-- Var pluto.end
-- Var pippo.end
--
-- The tree above is relative to the expression
--
-- 4 * (5 + 1 - max (pluto.end, pippo.end))
--
-- Why does not it return a "human" string like the latter one? Because
-- Dump is for debugging, so it is more useful to be able to see the
-- internal structure of Item.
private
-- -- use Ada.Strings.Unbounded;
-- package Bounded_IDs is
-- new Ada.Strings.Bounded.Generic_Bounded_Length (Symbolic_Identifiers.Max_ID_Length);
-- subtype Bounded_ID is Bounded_IDs.Bounded_String
-- with Dynamic_Predicate => Symbolic_Identifiers.Is_Valid_ID (Bounded_IDs.To_String (Bounded_ID));
-- function To_Bounded_ID (X : Symbolic_Identifiers.Variable_Name) return Bounded_ID
-- is (Bounded_IDs.To_Bounded_String (String (X)));
--
-- function To_String (X : Bounded_ID) return String
-- is (Bounded_IDs.To_String (X));
use Ada.Finalization;
-- A symbolic expression is stored as a tree, where each node has a
-- "class" representing the operation associated with the node.
type Node_Class is (Unary_Plus, Unary_Minus,
Sum, Sub, Mult, Div,
Fun_Call, Var, Const);
type Node_Type (Class : Node_Class);
type Node_Access is access Node_Type;
type Parameter_Array is array (1..128) of Node_Access;
type Node_Type (Class : Node_Class) is
record
case Class is
when Unary_Plus | Unary_Minus =>
Term : Node_Access;
when Sum | Sub | Mult | Div =>
Left, Right : Node_Access;
when Fun_Call =>
Fun_Name : Function_Name;
Parameters : Parameter_Array;
N_Params : Natural;
when Var =>
Var_Name : Variable_Name;
when Const =>
Value : Scalar_Type;
end case;
end record;
function Duplicate (Item : Node_Access) return Node_Access;
pragma Precondition (Item /= null);
-- Create a duplicate of the tree rooted in Item
procedure Free (Item : in out Node_Access);
-- Release the memory associated with the tree in Item
--
-- Symbolic_Expression is just a thin "shell" around Node_Access.
-- This makes recursive procedures a bit simpler and allows us
-- to hide all the house-keeping from the user.
--
type Symbolic_Expression is new
Ada.Finalization.Controlled
with
record
Expr : Node_Access;
end record;
overriding procedure Initialize (Item : in out Symbolic_Expression);
overriding procedure Finalize (Item : in out Symbolic_Expression);
overriding procedure Adjust (Item : in out Symbolic_Expression);
end Symbolic_Expressions;
|
-- hello_world.adb
with Ada.Text_IO; use Ada.Text_IO;
procedure hello_world is
begin
Put_Line("Hello world!");
Put("It's a wonderful day!");
New_Line;
end hello_world;
|
with Interfaces.C; use Interfaces.C;
with common_data_h; use common_data_h;
with speed_data_h; use speed_data_h;
with types;
package converters with SPARK_Mode is
use Types;
function double_to_speed (d : double) return Types.speed with
Pre => d > Double(-80.0) and d < Double(80.0),
Post => double_to_speed'Result = Types.Speed(d);
function point_to_cart_x (p : point_3d) return Types.Cartesian_Coordinate with
pre => p.x < 180.0 and -180.0 < p.x ;
function point_to_cart_y (p : point_3d) return Types.Cartesian_Coordinate with
pre => p.y < 180.0 and -180.0 < p.y ;
function point_to_cart_z (p : point_3d) return Types.Cartesian_Coordinate with
pre => p.z < 180.0 and -180.0 < p.z ;
function speed_ada_to_speed (s : speed_ada) return Types.Speed with
pre => s.speed > Double(-80.0) and s.speed < Double(80.0),
Post => Types.Speed(s.speed) = speed_ada_to_speed'Result;
end converters;
|
with stm32.gpio;
with Bit_Types; use Bit_Types;
package HAL.GPIO
with SPARK_Mode
is
pragma Preelaborate;
type GPIO_Port_Type is (A, B, C, D, E, F);
subtype GPIO_Pin_Type is Integer range 1 .. 16;
type GPIO_Point_Type is record
Port : GPIO_Port_Type;
Pin : GPIO_Pin_Type;
end record;
type GPIO_Signal_Type is (LOW, HIGH);
-- precondition: only write if direction is output (ghost code)
procedure write (Point : GPIO_Point_Type; Signal : GPIO_Signal_Type);
-- with pre => stm32.gpio.GPIOA_Periph.MODER.Arr(Point.Pin) = stm32.gpio.Mode_OUT;
function read (Point : GPIO_Point_Type) return GPIO_Signal_Type;
-- function map(Point : GPIO_Point_Type) return stm32.gpio.GPIO_Peripheral
-- is ( case Point.Port is
-- when A => stm32.gpio.GPIOA_Periph,
-- when B => stm32.gpio.GPIOB_Periph,
-- when C => stm32.gpio.GPIOC_Periph,
-- when D => stm32.gpio.GPIOD_Periph,
-- when E => stm32.gpio.GPIOE_Periph,
-- when F => stm32.gpio.GPIOF_Periph );
end HAL.GPIO;
|
procedure Operator is
Result : Integer;
begin
Result := "+" (Left => 1, Right => 1);
Result := 1 + 1;
end Operator;
|
-- { dg-do run }
-- Verify that an array of non-aliased zero-sized element is zero-sized
procedure Array10 is
type Rec is null record;
type Arr1 is array (1..8) of Rec;
type Arr2 is array (Long_Integer) of Rec;
R : Rec;
A1 : Arr1;
A2 : Arr2;
begin
if Rec'Size /= 0 then
raise Program_Error;
end if;
if Arr1'Size /= 0 then
raise Program_Error;
end if;
if Arr2'Size /= 0 then
raise Program_Error;
end if;
end;
|
-- { dg-do compile }
-- { dg-options "-gnatwa" }
package Rep_Clause1 is
generic
type Custom_T is private;
package Handler is
type Storage_T is record
A : Boolean;
B : Boolean;
C : Custom_T;
end record;
for Storage_T use record
A at 0 range 0..0;
B at 1 range 0..0;
end record;
end Handler;
end Rep_Clause1;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- T R E E P R --
-- --
-- S p e c --
-- --
-- $Revision$
-- --
-- Copyright (C) 1992,1993,1994,1995 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 Types; use Types;
package Treepr is
-- This package provides printing routines for the abstract syntax tree
-- These routines are intended only for debugging use.
procedure Tree_Dump;
-- This routine is called from the GNAT main program to dump trees as
-- requested by debug options (including tree of Standard if requested).
procedure Print_Tree_Node (N : Node_Id; Label : String := "");
-- Prints a single tree node, without printing descendants. The Label
-- string is used to preface each line of the printed output.
procedure Print_Tree_List (L : List_Id);
-- Prints a single node list, without printing the descendants of any
-- of the nodes in the list
procedure Print_Tree_Elist (E : Elist_Id);
-- Prints a single node list, without printing the descendants of any
-- of the nodes in the list
procedure Print_Node_Subtree (N : Node_Id);
-- Prints the subtree routed at a specified tree node, including all
-- referenced descendants.
procedure Print_List_Subtree (L : List_Id);
-- Prints the subtree consisting of the given node list and all its
-- referenced descendants.
procedure Print_Elist_Subtree (E : Elist_Id);
-- Prints the subtree consisting of the given element list and all its
-- referenced descendants.
procedure PE (E : Elist_Id);
-- Debugging procedure (to be called within gdb)
-- same as Print_Tree_Elist
procedure PL (L : List_Id);
-- Debugging procedure (to be called within gdb)
-- same as Print_Tree_List
procedure PN (N : Node_Id);
-- Debugging procedure (to be called within gdb)
-- same as Print_Tree_Node with Label = ""
procedure PT (N : Node_Id);
-- Debugging procedure (to be called within gdb)
-- same as Print_Node_Subtree
end Treepr;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- G N A T . M E M O R Y _ D U M P --
-- --
-- S p e c --
-- --
-- Copyright (C) 2003-2005, 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 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
-- Boston, MA 02110-1301, USA. --
-- --
--
--
--
--
--
--
--
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- A routine for dumping memory to either standard output or standard error.
-- Uses GNAT.IO for actual output (use the controls in GNAT.IO to specify
-- the destination of the output, which by default is Standard_Output).
with System;
package GNAT.Memory_Dump is
pragma Preelaborate;
procedure Dump (Addr : System.Address; Count : Natural);
-- Dumps indicated number (Count) of bytes, starting at the address given
-- by Addr. The coding of this routine in its current form assumes the
-- case of a byte addressable machine (and is therefore inapplicable to
-- machines like the AAMP, where the storage unit is not 8 bits). The
-- output is one or more lines in the following format, which is for the
-- case of 32-bit addresses (64-bit addressea are handled appropriately):
--
-- 0234_3368: 66 67 68 . . . 73 74 75 "fghijklmnopqstuv"
--
-- All but the last line have 16 bytes. A question mark is used in the
-- string data to indicate a non-printable character.
end GNAT.Memory_Dump;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Web Framework --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2014-2018, Vadim Godunko <vgodunko@gmail.com> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with Ada.Synchronous_Task_Control;
with GNAT.Ctrl_C;
with AWS.Config.Set;
with AWS.Default;
with AWS.Net.WebSocket.Registry.Control;
with AWS.Response;
with AWS.Server.Log;
with AWS.Status;
with League.Holders;
with League.Settings;
with League.Strings;
with Matreshka.Servlet_AWS_Requests;
with Matreshka.Servlet_AWS_Responses;
with Matreshka.Servlet_Containers;
with Servlet.HTTP_Responses;
with Servlet.HTTP_Upgrade_Handlers;
with Web_Socket.Handlers.AWS_Handlers;
package body Matreshka.Servlet_Servers.AWS_Servers is
Config : AWS.Config.Object := AWS.Config.Get_Current;
-- Initialize config from .ini file
Server : AWS.Server.HTTP;
Shutdown_Request : Ada.Synchronous_Task_Control.Suspension_Object;
Container : Matreshka.Servlet_Containers.Servlet_Container_Access;
procedure Shutdown_Request_Handler;
-- Interrupt handler to process shutdown request from the operating system.
task Shutdown_Controller is
entry Start;
end Shutdown_Controller;
function Request_Callback
(Request : AWS.Status.Data) return AWS.Response.Data;
-- Handles request.
function WebSocket_Callback
(Socket : AWS.Net.Socket_Access;
Request : AWS.Status.Data) return AWS.Net.WebSocket.Object'Class;
-- Handles request of WebSocket connection.
procedure Read_Setting
(Config : in out AWS.Config.Object;
Settings : League.Settings.Settings;
Name : Wide_Wide_String;
Default : String);
-- Read setting with given Name or set Default if no such setting.
--------------
-- Finalize --
--------------
procedure Finalize (Self : not null access AWS_Server'Class) is
begin
Shutdown_Request_Handler;
end Finalize;
----------------
-- Initialize --
----------------
procedure Initialize (Self : not null access AWS_Server'Class) is
function "+"
(Text : Wide_Wide_String) return League.Strings.Universal_String
renames League.Strings.To_Universal_String;
Settings : League.Settings.Settings;
Holder : League.Holders.Holder;
begin
AWS.Config.Set.Reuse_Address (Config, True);
Read_Setting (Config, Settings, "max_post_parameters", "1_000_000");
-- Default number of POST parameters limited to 100, too small.
Read_Setting (Config, Settings, "upload_size_limit", "1_000_000_000");
Read_Setting (Config, Settings, "server_port", "8080");
Read_Setting (Config, Settings, "upload_directory", ".");
-- Upload_Directory is required to process files in POST parameters.
Read_Setting (Config, Settings, "log_file_directory", ".");
AWS.Server.Start (Server, Request_Callback'Access, Config);
AWS.Server.Log.Start (Server);
AWS.Server.Log.Start_Error (Server);
AWS.Net.WebSocket.Registry.Register_Pattern
("/.*", WebSocket_Callback'Access);
AWS.Net.WebSocket.Registry.Control.Start;
Shutdown_Controller.Start;
end Initialize;
------------------
-- Read_Setting --
------------------
procedure Read_Setting
(Config : in out AWS.Config.Object;
Settings : League.Settings.Settings;
Name : Wide_Wide_String;
Default : String)
is
use type League.Strings.Universal_String;
Holder : League.Holders.Holder;
Setting : constant League.Strings.Universal_String :=
League.Strings.To_Universal_String (Name);
Key : constant League.Strings.Universal_String := "/aws/" & Setting;
begin
if Settings.Contains (Key) then
Holder := Settings.Value (Key);
if League.Holders.Has_Tag
(Holder, League.Holders.Universal_Integer_Tag)
then
AWS.Config.Set.Parameter
(Config,
Setting.To_UTF_8_String,
League.Holders.Universal_Integer'Image
(League.Holders.Element (Holder)));
else
AWS.Config.Set.Parameter
(Config,
Setting.To_UTF_8_String,
League.Holders.Element (Holder).To_UTF_8_String);
end if;
else
AWS.Config.Set.Parameter (Config, Setting.To_UTF_8_String, Default);
end if;
end Read_Setting;
----------------------
-- Request_Callback --
----------------------
function Request_Callback
(Request : AWS.Status.Data) return AWS.Response.Data
is
Servlet_Request :
aliased Matreshka.Servlet_AWS_Requests.AWS_Servlet_Request;
Servlet_Response :
aliased Matreshka.Servlet_AWS_Responses.AWS_Servlet_Response;
begin
Matreshka.Servlet_AWS_Requests.Initialize (Servlet_Request, Request);
Matreshka.Servlet_AWS_Responses.Initialize
(Servlet_Response, Servlet_Request'Unchecked_Access);
Container.Dispatch
(Servlet_Request'Unchecked_Access, Servlet_Response'Unchecked_Access);
return Result : constant AWS.Response.Data := Servlet_Response.Build do
Servlet_Request.Finalize;
end return;
end Request_Callback;
-------------------
-- Set_Container --
-------------------
overriding procedure Set_Container
(Self : not null access AWS_Server;
Container : Matreshka.Servlet_Containers.Servlet_Container_Access) is
begin
AWS_Servers.Container := Container;
end Set_Container;
-------------------------
-- Shutdown_Controller --
-------------------------
task body Shutdown_Controller is
begin
select
accept Start;
Ada.Synchronous_Task_Control.Set_False (Shutdown_Request);
GNAT.Ctrl_C.Install_Handler (Shutdown_Request_Handler'Access);
or
terminate;
end select;
-- Wait till shutdown request was received.
Ada.Synchronous_Task_Control.Suspend_Until_True (Shutdown_Request);
-- Shutdown AWS server.
AWS.Server.Shutdown (Server);
end Shutdown_Controller;
------------------------------
-- Shutdown_Request_Handler --
------------------------------
procedure Shutdown_Request_Handler is
begin
Ada.Synchronous_Task_Control.Set_True (Shutdown_Request);
end Shutdown_Request_Handler;
------------------------
-- WebSocket_Callback --
------------------------
function WebSocket_Callback
(Socket : AWS.Net.Socket_Access;
Request : AWS.Status.Data) return AWS.Net.WebSocket.Object'Class
is
use type Servlet.HTTP_Responses.Status_Code;
use type Servlet.HTTP_Upgrade_Handlers.HTTP_Upgrade_Handler_Access;
Servlet_Request :
aliased Matreshka.Servlet_AWS_Requests.AWS_Servlet_Request;
Servlet_Response :
aliased Matreshka.Servlet_AWS_Responses.AWS_Servlet_Response;
begin
Matreshka.Servlet_AWS_Requests.Initialize (Servlet_Request, Request);
Matreshka.Servlet_AWS_Responses.Initialize
(Servlet_Response, Servlet_Request'Unchecked_Access);
Container.Dispatch
(Servlet_Request'Unchecked_Access, Servlet_Response'Unchecked_Access);
if Servlet_Response.Get_Status
= Servlet.HTTP_Responses.Switching_Protocols
and then Servlet_Request.Get_Upgrade_Handler /= null
then
Servlet_Request.Finalize;
return
Web_Socket.Handlers.AWS_Handlers.Create
(Socket,
Request,
Web_Socket.Handlers.AWS_Handlers.AWS_Web_Socket_Handler_Access
(Servlet_Request.Get_Upgrade_Handler));
else
Servlet_Request.Finalize;
raise Program_Error;
end if;
end WebSocket_Callback;
end Matreshka.Servlet_Servers.AWS_Servers;
|
with Ada.Text_IO; use Ada.Text_IO;
with GL.Objects.Shaders;
with Program_Loader;
package body Shader_Manager is
Black : constant GL.Types.Singles.Vector4 := (0.0, 0.0, 0.0, 0.0);
Render_Uniforms : Shader_Uniforms;
procedure Init (Render_Program : in out GL.Objects.Programs.Program) is
use GL.Objects.Programs;
use GL.Objects.Shaders;
use GL.Types.Singles;
use Program_Loader;
Light : constant Singles.Vector3 := (0.0, 4.0, 1.0);
Direction : constant Singles.Vector3 := (0.0, 0.0, 1.0);
begin
Render_Program := Program_From
((Src ("src/shaders/vertex_shader_1_1.glsl", Vertex_Shader),
Src ("src/shaders/fragment_shader_1_1.glsl", Fragment_Shader)));
Render_Uniforms.View_Matrix_ID :=
Uniform_Location (Render_Program, "view_matrix");
Render_Uniforms.Model_Matrix_ID :=
Uniform_Location (Render_Program, "model_matrix");
Render_Uniforms.Projection_Matrix_ID :=
Uniform_Location (Render_Program, "projection_matrix");
Render_Uniforms.Rotation_Matrix_ID :=
Uniform_Location (Render_Program, "rotation_matrix");
Render_Uniforms.Translation_Matrix_ID :=
Uniform_Location (Render_Program, "translation_matrix");
Render_Uniforms.Light_Direction_ID :=
Uniform_Location (Render_Program, "light_direction");
Render_Uniforms.Light_Position_ID :=
Uniform_Location (Render_Program, "light_position");
Render_Uniforms.Line_Width_ID :=
Uniform_Location (Render_Program, "line_width");
Render_Uniforms.Ambient_Colour_ID :=
Uniform_Location (Render_Program, "Ambient_Colour");
Render_Uniforms.Diffuse_Colour_ID :=
Uniform_Location (Render_Program, "Diffuse_Colour");
Render_Uniforms.Drawing_Colour_ID :=
Uniform_Location (Render_Program, "Drawing_Colour");
Use_Program (Render_Program);
GL.Uniforms.Set_Single (Render_Uniforms.Light_Direction_ID, Direction);
GL.Uniforms.Set_Single (Render_Uniforms.Light_Position_ID, Light);
GL.Uniforms.Set_Single (Render_Uniforms.Line_Width_ID, 1.0);
GL.Uniforms.Set_Single (Render_Uniforms.Model_Matrix_ID, Identity4);
GL.Uniforms.Set_Single (Render_Uniforms.View_Matrix_ID, Identity4);
GL.Uniforms.Set_Single (Render_Uniforms.Projection_Matrix_ID, Identity4);
GL.Uniforms.Set_Single (Render_Uniforms.Rotation_Matrix_ID, Identity4);
GL.Uniforms.Set_Single (Render_Uniforms.Translation_Matrix_ID, Identity4);
GL.Uniforms.Set_Single (Render_Uniforms.Ambient_Colour_ID, Black);
GL.Uniforms.Set_Single (Render_Uniforms.Diffuse_Colour_ID, Black);
GL.Uniforms.Set_Single (Render_Uniforms.Drawing_Colour_ID, Black);
exception
when others =>
Put_Line ("An exception occurred in Shader_Manager.Init.");
raise;
end Init;
-- -------------------------------------------------------------------------
procedure Set_Ambient_Colour (Ambient_Colour : Singles.Vector4) is
begin
GL.Uniforms.Set_Single (Render_Uniforms.Ambient_Colour_ID, Ambient_Colour);
end Set_Ambient_Colour;
-- -------------------------------------------------------------------------
procedure Set_Diffuse_Colour (Diffuse_Colour : Singles.Vector4) is
begin
GL.Uniforms.Set_Single
(Render_Uniforms.Diffuse_Colour_ID, Diffuse_Colour);
end Set_Diffuse_Colour;
-- -------------------------------------------------------------------------
procedure Set_Drawing_Colour (Drawing_Colour : Singles.Vector4) is
begin
GL.Uniforms.Set_Single
(Render_Uniforms.Drawing_Colour_ID, Drawing_Colour);
end Set_Drawing_Colour;
-- -------------------------------------------------------------------------
procedure Set_Light_Direction_Vector (Light_Direction : Singles.Vector3) is
begin
GL.Uniforms.Set_Single
(Render_Uniforms.Light_Direction_ID, Light_Direction);
end Set_Light_Direction_Vector;
-- -------------------------------------------------------------------------
procedure Set_Light_Position_Vector (Light_Position : Singles.Vector3) is
begin
GL.Uniforms.Set_Single
(Render_Uniforms.Light_Position_ID, Light_Position);
end Set_Light_Position_Vector;
-- -------------------------------------------------------------------------
procedure Set_Line_Width (Width : Single) is
begin
GL.Uniforms.Set_Single
(Render_Uniforms.Line_Width_ID, Width);
end Set_Line_Width;
-- -------------------------------------------------------------------------
procedure Set_Model_Matrix (Model_Matrix : Singles.Matrix4) is
begin
GL.Uniforms.Set_Single (Render_Uniforms.Model_Matrix_ID, Model_Matrix);
end Set_Model_Matrix;
-- -------------------------------------------------------------------------
procedure Set_View_Matrix (View_Matrix : Singles.Matrix4) is
begin
GL.Uniforms.Set_Single (Render_Uniforms.View_Matrix_ID, View_Matrix);
end Set_View_Matrix;
-- -------------------------------------------------------------------------
procedure Set_Projection_Matrix (Projection_Matrix : Singles.Matrix4) is
begin
GL.Uniforms.Set_Single
(Render_Uniforms.Projection_Matrix_ID, Projection_Matrix);
end Set_Projection_Matrix;
-- -------------------------------------------------------------------------
procedure Set_Rotation_Matrix (Rotation_Matrix : Singles.Matrix4) is
begin
GL.Uniforms.Set_Single
(Render_Uniforms.Rotation_Matrix_ID, Rotation_Matrix);
end Set_Rotation_Matrix;
-- -------------------------------------------------------------------------
procedure Set_Translation_Matrix (Translation_Matrix : Singles.Matrix4) is
begin
GL.Uniforms.Set_Single
(Render_Uniforms.Translation_Matrix_ID, Translation_Matrix);
end Set_Translation_Matrix;
-- -------------------------------------------------------------------------
end Shader_Manager;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015, 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 STMicroelectronics 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. --
-- --
-- --
-- This file is based on: --
-- --
-- @file ili9341.c --
-- @author MCD Application Team --
-- @version V1.0.2 --
-- @date 02-December-2014 --
-- @brief This file provides a set of functions needed to manage the --
-- L3GD20, ST MEMS motion sensor, 3-axis digital output --
-- gyroscope. --
-- --
-- COPYRIGHT(c) 2014 STMicroelectronics --
------------------------------------------------------------------------------
with Ada.Unchecked_Conversion;
with ILI9341_Regs; use ILI9341_Regs;
package body ILI9341 is
function As_UInt16 is new Ada.Unchecked_Conversion
(Source => Colors, Target => UInt16);
-------------------
-- Current_Width --
-------------------
function Current_Width (This : ILI9341_Device) return Natural is
(This.Selected_Width);
--------------------
-- Current_Height --
--------------------
function Current_Height (This : ILI9341_Device) return Natural is
(This.Selected_Height);
-------------------------
-- Current_Orientation --
-------------------------
function Current_Orientation (This : ILI9341_Device) return Orientations is
(This.Selected_Orientation);
----------------
-- Initialize --
----------------
procedure Initialize
(This : in out ILI9341_Device;
Mode : ILI9341_Mode)
is
begin
if This.Initialized then
return;
end if;
This.Chip_Select_High;
This.Init_LCD (Mode);
This.Selected_Width := Device_Width;
This.Selected_Height := Device_Height;
This.Selected_Orientation := Portrait_2;
This.Initialized := True;
end Initialize;
---------------
-- Set_Pixel --
---------------
procedure Set_Pixel
(This : in out ILI9341_Device;
X : Width;
Y : Height;
Color : Colors)
is
Color_High_UInt8 : constant UInt8 :=
UInt8 (Shift_Right (As_UInt16 (Color), 8));
Color_Low_UInt8 : constant UInt8 :=
UInt8 (As_UInt16 (Color) and 16#FF#);
begin
This.Set_Cursor_Position (X, Y, X, Y);
This.Send_Command (ILI9341_GRAM);
This.Send_Data (Color_High_UInt8);
This.Send_Data (Color_Low_UInt8);
end Set_Pixel;
----------
-- Fill --
----------
procedure Fill (This : in out ILI9341_Device; Color : Colors) is
Color_High_UInt8 : constant UInt8 :=
UInt8 (Shift_Right (As_UInt16 (Color), 8));
Color_Low_UInt8 : constant UInt8 :=
UInt8 (As_UInt16 (Color) and 16#FF#);
begin
This.Set_Cursor_Position (X1 => 0,
Y1 => 0,
X2 => This.Selected_Width - 1,
Y2 => This.Selected_Height - 1);
This.Send_Command (ILI9341_GRAM);
for N in 1 .. (Device_Width * Device_Height) loop
This.Send_Data (Color_High_UInt8);
This.Send_Data (Color_Low_UInt8);
end loop;
end Fill;
---------------------
-- Set_Orientation --
---------------------
procedure Set_Orientation (This : in out ILI9341_Device;
To : Orientations)
is
begin
This.Send_Command (ILI9341_MAC);
case To is
when Portrait_1 => This.Send_Data (16#58#);
when Portrait_2 => This.Send_Data (16#88#);
when Landscape_1 => This.Send_Data (16#28#);
when Landscape_2 => This.Send_Data (16#E8#);
end case;
case To is
when Portrait_1 | Portrait_2 =>
This.Selected_Width := Device_Width;
This.Selected_Height := Device_Height;
when Landscape_1 | Landscape_2 =>
This.Selected_Width := Device_Height;
This.Selected_Height := Device_Width;
end case;
This.Selected_Orientation := To;
end Set_Orientation;
--------------------
-- Enable_Display --
--------------------
procedure Enable_Display (This : in out ILI9341_Device) is
begin
This.Send_Command (ILI9341_DISPLAY_ON);
end Enable_Display;
---------------------
-- Disable_Display --
---------------------
procedure Disable_Display (This : in out ILI9341_Device) is
begin
This.Send_Command (ILI9341_DISPLAY_OFF);
end Disable_Display;
-------------------------
-- Set_Cursor_Position --
-------------------------
procedure Set_Cursor_Position
(This : in out ILI9341_Device;
X1 : Width;
Y1 : Height;
X2 : Width;
Y2 : Height)
is
X1_High : constant UInt8 := UInt8 (Shift_Right (UInt16 (X1), 8));
X1_Low : constant UInt8 := UInt8 (UInt16 (X1) and 16#FF#);
X2_High : constant UInt8 := UInt8 (Shift_Right (UInt16 (X2), 8));
X2_Low : constant UInt8 := UInt8 (UInt16 (X2) and 16#FF#);
Y1_High : constant UInt8 := UInt8 (Shift_Right (UInt16 (Y1), 8));
Y1_Low : constant UInt8 := UInt8 (UInt16 (Y1) and 16#FF#);
Y2_High : constant UInt8 := UInt8 (Shift_Right (UInt16 (Y2), 8));
Y2_Low : constant UInt8 := UInt8 (UInt16 (Y2) and 16#FF#);
begin
This.Send_Command (ILI9341_COLUMN_ADDR);
This.Send_Data (X1_High);
This.Send_Data (X1_Low);
This.Send_Data (X2_High);
This.Send_Data (X2_Low);
This.Send_Command (ILI9341_PAGE_ADDR);
This.Send_Data (Y1_High);
This.Send_Data (Y1_Low);
This.Send_Data (Y2_High);
This.Send_Data (Y2_Low);
end Set_Cursor_Position;
----------------------
-- Chip_Select_High --
----------------------
procedure Chip_Select_High (This : in out ILI9341_Device) is
begin
This.Chip_Select.Set;
end Chip_Select_High;
---------------------
-- Chip_Select_Low --
---------------------
procedure Chip_Select_Low (This : in out ILI9341_Device) is
begin
This.Chip_Select.Clear;
end Chip_Select_Low;
---------------
-- Send_Data --
---------------
procedure Send_Data (This : in out ILI9341_Device; Data : UInt8) is
Status : SPI_Status;
begin
This.WRX.Set;
This.Chip_Select_Low;
This.Port.Transmit (SPI_Data_8b'(1 => Data), Status);
if Status /= Ok then
raise Program_Error;
end if;
This.Chip_Select_High;
end Send_Data;
------------------
-- Send_Command --
------------------
procedure Send_Command (This : in out ILI9341_Device; Cmd : UInt8) is
Status : SPI_Status;
begin
This.WRX.Clear;
This.Chip_Select_Low;
This.Port.Transmit (SPI_Data_8b'(1 => Cmd), Status);
if Status /= Ok then
raise Program_Error;
end if;
This.Chip_Select_High;
end Send_Command;
--------------
-- Init_LCD --
--------------
procedure Init_LCD (This : in out ILI9341_Device;
Mode : ILI9341_Mode) is
begin
This.Reset.Set;
This.Send_Command (ILI9341_RESET);
This.Time.Delay_Milliseconds (5);
This.Send_Command (ILI9341_POWERA);
This.Send_Data (16#39#);
This.Send_Data (16#2C#);
This.Send_Data (16#00#);
This.Send_Data (16#34#);
This.Send_Data (16#02#);
This.Send_Command (ILI9341_POWERB);
This.Send_Data (16#00#);
This.Send_Data (16#C1#);
This.Send_Data (16#30#);
This.Send_Command (ILI9341_DTCA);
This.Send_Data (16#85#);
This.Send_Data (16#00#);
This.Send_Data (16#78#);
This.Send_Command (ILI9341_DTCB);
This.Send_Data (16#00#);
This.Send_Data (16#00#);
This.Send_Command (ILI9341_POWER_SEQ);
This.Send_Data (16#64#);
This.Send_Data (16#03#);
This.Send_Data (16#12#);
This.Send_Data (16#81#);
This.Send_Command (ILI9341_PRC);
This.Send_Data (16#20#);
This.Send_Command (ILI9341_POWER1);
This.Send_Data (16#23#);
This.Send_Command (ILI9341_POWER2);
This.Send_Data (16#10#);
This.Send_Command (ILI9341_VCOM1);
This.Send_Data (16#3E#);
This.Send_Data (16#28#);
This.Send_Command (ILI9341_VCOM2);
This.Send_Data (16#86#);
This.Send_Command (ILI9341_MAC);
This.Send_Data (16#C8#);
This.Send_Command (ILI9341_FRC);
This.Send_Data (16#00#);
This.Send_Data (16#18#);
case Mode is
when RGB_Mode =>
This.Send_Command (ILI9341_RGB_INTERFACE);
This.Send_Data (16#C2#);
This.Send_Command (ILI9341_INTERFACE);
This.Send_Data (16#01#);
This.Send_Data (16#00#);
This.Send_Data (16#06#);
This.Send_Command (ILI9341_DFC);
This.Send_Data (16#0A#);
This.Send_Data (16#A7#);
This.Send_Data (16#27#);
This.Send_Data (16#04#);
when SPI_Mode =>
This.Send_Command (ILI9341_PIXEL_FORMAT);
This.Send_Data (16#55#);
This.Send_Command (ILI9341_DFC);
This.Send_Data (16#08#);
This.Send_Data (16#82#);
This.Send_Data (16#27#);
end case;
This.Send_Command (ILI9341_3GAMMA_EN);
This.Send_Data (16#00#);
This.Send_Command (ILI9341_COLUMN_ADDR);
This.Send_Data (16#00#);
This.Send_Data (16#00#);
This.Send_Data (16#00#);
This.Send_Data (16#EF#);
This.Send_Command (ILI9341_PAGE_ADDR);
This.Send_Data (16#00#);
This.Send_Data (16#00#);
This.Send_Data (16#01#);
This.Send_Data (16#3F#);
This.Send_Command (ILI9341_GAMMA);
This.Send_Data (16#01#);
This.Send_Command (ILI9341_PGAMMA);
This.Send_Data (16#0F#);
This.Send_Data (16#31#);
This.Send_Data (16#2B#);
This.Send_Data (16#0C#);
This.Send_Data (16#0E#);
This.Send_Data (16#08#);
This.Send_Data (16#4E#);
This.Send_Data (16#F1#);
This.Send_Data (16#37#);
This.Send_Data (16#07#);
This.Send_Data (16#10#);
This.Send_Data (16#03#);
This.Send_Data (16#0E#);
This.Send_Data (16#09#);
This.Send_Data (16#00#);
This.Send_Command (ILI9341_NGAMMA);
This.Send_Data (16#00#);
This.Send_Data (16#0E#);
This.Send_Data (16#14#);
This.Send_Data (16#03#);
This.Send_Data (16#11#);
This.Send_Data (16#07#);
This.Send_Data (16#31#);
This.Send_Data (16#C1#);
This.Send_Data (16#48#);
This.Send_Data (16#08#);
This.Send_Data (16#0F#);
This.Send_Data (16#0C#);
This.Send_Data (16#31#);
This.Send_Data (16#36#);
This.Send_Data (16#0F#);
This.Send_Command (ILI9341_SLEEP_OUT);
case Mode is
when RGB_Mode =>
This.Time.Delay_Milliseconds (150);
when SPI_Mode =>
This.Time.Delay_Milliseconds (20);
end case;
-- document ILI9341_DS_V1.02, section 11.2, pg 205 says we need
-- either 120ms or 5ms, depending on the mode, but seems incorrect.
This.Send_Command (ILI9341_DISPLAY_ON);
This.Send_Command (ILI9341_GRAM);
end Init_LCD;
end ILI9341;
|
-- This demonstration illustrates the use of PWM to control the brightness of
-- an LED. The effect is to make the LED increase and decrease in brightness,
-- iteratively, for as long as the application runs. In effect the LED light
-- waxes and wanes. See http://visualgdb.com/tutorials/arm/stm32/fpu/ for the
-- inspiration.
--
-- The demo uses an abstract data type PWM_Modulator to control the power to
-- the LED via pulse-width-modulation. A timer is still used underneath, but
-- the details are hidden. For direct use of the timer see the other demo.
--
pragma Restrictions (No_Task_Hierarchy);
with STM32.Device; use STM32.Device;
with STM32.Timers; use STM32.Timers;
with STM32.PWM; use STM32.PWM;
with STM_Board; use STM_Board;
with Last_Chance_Handler; pragma Unreferenced (Last_Chance_Handler);
-- The "last chance handler" is the user-defined routine that is called when
-- an exception is propagated. We need it in the executable, therefore it
-- must be somewhere in the closure of the context clauses.
procedure Test_LED_PWM is
-- The LD2 green led at GPIO PA5 is the TIM2_CH1 timer output when
-- programmed as AF1 alternate function.
Selected_Timer : Timer renames Timer_2;
Timer_AF : constant STM32.GPIO_Alternate_Function := GPIO_AF_TIM2_1;
Output_Channel : constant Timer_Channel := Channel_1;
Requested_Frequency : constant Hertz := 25_000;
Power_Control : PWM_Modulator;
function Sine (Input : Long_Float) return Long_Float;
-- We use the sine function to drive the power applied to the LED, thereby
-- making the LED increase and decrease in brightness. We attach the timer
-- to the LED and then control how much power is supplied by changing the
-- value of the timer's output compare register. The sine function drives
-- that value, thus the waxing/waning effect.
function Sine (Input : Long_Float) return Long_Float is
Pi : constant Long_Float := 3.14159_26535_89793_23846;
X : constant Long_Float := Long_Float'Remainder (Input, Pi * 2.0);
B : constant Long_Float := 4.0 / Pi;
C : constant Long_Float := (-4.0) / (Pi * Pi);
Y : constant Long_Float := B * X + C * X * abs (X);
P : constant Long_Float := 0.225;
begin
return P * (Y * abs (Y) - Y) + Y;
end Sine;
begin
Configure_PWM_Timer (Selected_Timer'Access, Requested_Frequency);
Power_Control.Attach_PWM_Channel
(Selected_Timer'Access,
Output_Channel,
Green_LED,
Timer_AF);
Power_Control.Enable_Output;
declare
Arg : Long_Float := 0.0;
Value : Percentage;
Increment : constant Long_Float := 0.00003;
-- The Increment value controls the rate at which the brightness
-- increases and decreases. The value is more or less arbitrary, but
-- note that the effect of compiler optimization is observable.
begin
loop
Value := Percentage (50.0 * (1.0 + Sine (Arg)));
Power_Control.Set_Duty_Cycle (Value);
Arg := Arg + Increment;
end loop;
end;
end Test_LED_PWM;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- E X P _ P A K D --
-- --
-- B o d y --
-- --
-- Copyright (C) 1992-2016, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING3. If not, go to --
-- http://www.gnu.org/licenses for a complete copy of the license. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Atree; use Atree;
with Checks; use Checks;
with Einfo; use Einfo;
with Errout; use Errout;
with Exp_Dbug; use Exp_Dbug;
with Exp_Util; use Exp_Util;
with Layout; use Layout;
with Lib.Xref; use Lib.Xref;
with Namet; use Namet;
with Nlists; use Nlists;
with Nmake; use Nmake;
with Opt; use Opt;
with Sem; use Sem;
with Sem_Aux; use Sem_Aux;
with Sem_Ch3; use Sem_Ch3;
with Sem_Ch8; use Sem_Ch8;
with Sem_Ch13; use Sem_Ch13;
with Sem_Eval; use Sem_Eval;
with Sem_Res; use Sem_Res;
with Sem_Util; use Sem_Util;
with Sinfo; use Sinfo;
with Snames; use Snames;
with Stand; use Stand;
with Targparm; use Targparm;
with Tbuild; use Tbuild;
with Ttypes; use Ttypes;
with Uintp; use Uintp;
package body Exp_Pakd is
---------------------------
-- Endian Considerations --
---------------------------
-- As described in the specification, bit numbering in a packed array
-- is consistent with bit numbering in a record representation clause,
-- and hence dependent on the endianness of the machine:
-- For little-endian machines, element zero is at the right hand end
-- (low order end) of a bit field.
-- For big-endian machines, element zero is at the left hand end
-- (high order end) of a bit field.
-- The shifts that are used to right justify a field therefore differ in
-- the two cases. For the little-endian case, we can simply use the bit
-- number (i.e. the element number * element size) as the count for a right
-- shift. For the big-endian case, we have to subtract the shift count from
-- an appropriate constant to use in the right shift. We use rotates
-- instead of shifts (which is necessary in the store case to preserve
-- other fields), and we expect that the backend will be able to change the
-- right rotate into a left rotate, avoiding the subtract, if the machine
-- architecture provides such an instruction.
-----------------------
-- Local Subprograms --
-----------------------
procedure Compute_Linear_Subscript
(Atyp : Entity_Id;
N : Node_Id;
Subscr : out Node_Id);
-- Given a constrained array type Atyp, and an indexed component node N
-- referencing an array object of this type, build an expression of type
-- Standard.Integer representing the zero-based linear subscript value.
-- This expression includes any required range checks.
function Compute_Number_Components
(N : Node_Id;
Typ : Entity_Id) return Node_Id;
-- Build an expression that multiplies the length of the dimensions of the
-- array, used to control array equality checks.
procedure Convert_To_PAT_Type (Aexp : Node_Id);
-- Given an expression of a packed array type, builds a corresponding
-- expression whose type is the implementation type used to represent
-- the packed array. Aexp is analyzed and resolved on entry and on exit.
procedure Get_Base_And_Bit_Offset
(N : Node_Id;
Base : out Node_Id;
Offset : out Node_Id);
-- Given a node N for a name which involves a packed array reference,
-- return the base object of the reference and build an expression of
-- type Standard.Integer representing the zero-based offset in bits
-- from Base'Address to the first bit of the reference.
function Known_Aligned_Enough (Obj : Node_Id; Csiz : Nat) return Boolean;
-- There are two versions of the Set routines, the ones used when the
-- object is known to be sufficiently well aligned given the number of
-- bits, and the ones used when the object is not known to be aligned.
-- This routine is used to determine which set to use. Obj is a reference
-- to the object, and Csiz is the component size of the packed array.
-- True is returned if the alignment of object is known to be sufficient,
-- defined as 1 for odd bit sizes, 4 for bit sizes divisible by 4, and
-- 2 otherwise.
function Make_Shift_Left (N : Node_Id; S : Node_Id) return Node_Id;
-- Build a left shift node, checking for the case of a shift count of zero
function Make_Shift_Right (N : Node_Id; S : Node_Id) return Node_Id;
-- Build a right shift node, checking for the case of a shift count of zero
function RJ_Unchecked_Convert_To
(Typ : Entity_Id;
Expr : Node_Id) return Node_Id;
-- The packed array code does unchecked conversions which in some cases
-- may involve non-discrete types with differing sizes. The semantics of
-- such conversions is potentially endianness dependent, and the effect
-- we want here for such a conversion is to do the conversion in size as
-- though numeric items are involved, and we extend or truncate on the
-- left side. This happens naturally in the little-endian case, but in
-- the big endian case we can get left justification, when what we want
-- is right justification. This routine does the unchecked conversion in
-- a stepwise manner to ensure that it gives the expected result. Hence
-- the name (RJ = Right justified). The parameters Typ and Expr are as
-- for the case of a normal Unchecked_Convert_To call.
procedure Setup_Enumeration_Packed_Array_Reference (N : Node_Id);
-- This routine is called in the Get and Set case for arrays that are
-- packed but not bit-packed, meaning that they have at least one
-- subscript that is of an enumeration type with a non-standard
-- representation. This routine modifies the given node to properly
-- reference the corresponding packed array type.
procedure Setup_Inline_Packed_Array_Reference
(N : Node_Id;
Atyp : Entity_Id;
Obj : in out Node_Id;
Cmask : out Uint;
Shift : out Node_Id);
-- This procedure performs common processing on the N_Indexed_Component
-- parameter given as N, whose prefix is a reference to a packed array.
-- This is used for the get and set when the component size is 1, 2, 4,
-- or for other component sizes when the packed array type is a modular
-- type (i.e. the cases that are handled with inline code).
--
-- On entry:
--
-- N is the N_Indexed_Component node for the packed array reference
--
-- Atyp is the constrained array type (the actual subtype has been
-- computed if necessary to obtain the constraints, but this is still
-- the original array type, not the Packed_Array_Impl_Type value).
--
-- Obj is the object which is to be indexed. It is always of type Atyp.
--
-- On return:
--
-- Obj is the object containing the desired bit field. It is of type
-- Unsigned, Long_Unsigned, or Long_Long_Unsigned, and is either the
-- entire value, for the small static case, or the proper selected byte
-- from the array in the large or dynamic case. This node is analyzed
-- and resolved on return.
--
-- Shift is a node representing the shift count to be used in the
-- rotate right instruction that positions the field for access.
-- This node is analyzed and resolved on return.
--
-- Cmask is a mask corresponding to the width of the component field.
-- Its value is 2 ** Csize - 1 (e.g. 2#1111# for component size of 4).
--
-- Note: in some cases the call to this routine may generate actions
-- (for handling multi-use references and the generation of the packed
-- array type on the fly). Such actions are inserted into the tree
-- directly using Insert_Action.
function Revert_Storage_Order (N : Node_Id) return Node_Id;
-- Perform appropriate justification and byte ordering adjustments for N,
-- an element of a packed array type, when both the component type and
-- the enclosing packed array type have reverse scalar storage order.
-- On little-endian targets, the value is left justified before byte
-- swapping. The Etype of the returned expression is an integer type of
-- an appropriate power-of-2 size.
--------------------------
-- Revert_Storage_Order --
--------------------------
function Revert_Storage_Order (N : Node_Id) return Node_Id is
Loc : constant Source_Ptr := Sloc (N);
T : constant Entity_Id := Etype (N);
T_Size : constant Uint := RM_Size (T);
Swap_RE : RE_Id;
Swap_F : Entity_Id;
Swap_T : Entity_Id;
-- Swapping function
Arg : Node_Id;
Adjusted : Node_Id;
Shift : Uint;
begin
if T_Size <= 8 then
-- Array component size is less than a byte: no swapping needed
Swap_F := Empty;
Swap_T := RTE (RE_Unsigned_8);
else
-- Select byte swapping function depending on array component size
if T_Size <= 16 then
Swap_RE := RE_Bswap_16;
elsif T_Size <= 32 then
Swap_RE := RE_Bswap_32;
else pragma Assert (T_Size <= 64);
Swap_RE := RE_Bswap_64;
end if;
Swap_F := RTE (Swap_RE);
Swap_T := Etype (Swap_F);
end if;
Shift := Esize (Swap_T) - T_Size;
Arg := RJ_Unchecked_Convert_To (Swap_T, N);
if not Bytes_Big_Endian and then Shift > Uint_0 then
Arg :=
Make_Op_Shift_Left (Loc,
Left_Opnd => Arg,
Right_Opnd => Make_Integer_Literal (Loc, Shift));
end if;
if Present (Swap_F) then
Adjusted :=
Make_Function_Call (Loc,
Name => New_Occurrence_Of (Swap_F, Loc),
Parameter_Associations => New_List (Arg));
else
Adjusted := Arg;
end if;
Set_Etype (Adjusted, Swap_T);
return Adjusted;
end Revert_Storage_Order;
------------------------------
-- Compute_Linear_Subscript --
------------------------------
procedure Compute_Linear_Subscript
(Atyp : Entity_Id;
N : Node_Id;
Subscr : out Node_Id)
is
Loc : constant Source_Ptr := Sloc (N);
Oldsub : Node_Id;
Newsub : Node_Id;
Indx : Node_Id;
Styp : Entity_Id;
begin
Subscr := Empty;
-- Loop through dimensions
Indx := First_Index (Atyp);
Oldsub := First (Expressions (N));
while Present (Indx) loop
Styp := Etype (Indx);
Newsub := Relocate_Node (Oldsub);
-- Get expression for the subscript value. First, if Do_Range_Check
-- is set on a subscript, then we must do a range check against the
-- original bounds (not the bounds of the packed array type). We do
-- this by introducing a subtype conversion.
if Do_Range_Check (Newsub)
and then Etype (Newsub) /= Styp
then
Newsub := Convert_To (Styp, Newsub);
end if;
-- Now evolve the expression for the subscript. First convert
-- the subscript to be zero based and of an integer type.
-- Case of integer type, where we just subtract to get lower bound
if Is_Integer_Type (Styp) then
-- If length of integer type is smaller than standard integer,
-- then we convert to integer first, then do the subtract
-- Integer (subscript) - Integer (Styp'First)
if Esize (Styp) < Esize (Standard_Integer) then
Newsub :=
Make_Op_Subtract (Loc,
Left_Opnd => Convert_To (Standard_Integer, Newsub),
Right_Opnd =>
Convert_To (Standard_Integer,
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Styp, Loc),
Attribute_Name => Name_First)));
-- For larger integer types, subtract first, then convert to
-- integer, this deals with strange long long integer bounds.
-- Integer (subscript - Styp'First)
else
Newsub :=
Convert_To (Standard_Integer,
Make_Op_Subtract (Loc,
Left_Opnd => Newsub,
Right_Opnd =>
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Styp, Loc),
Attribute_Name => Name_First)));
end if;
-- For the enumeration case, we have to use 'Pos to get the value
-- to work with before subtracting the lower bound.
-- Integer (Styp'Pos (subscr)) - Integer (Styp'Pos (Styp'First));
-- This is not quite right for bizarre cases where the size of the
-- enumeration type is > Integer'Size bits due to rep clause ???
else
pragma Assert (Is_Enumeration_Type (Styp));
Newsub :=
Make_Op_Subtract (Loc,
Left_Opnd => Convert_To (Standard_Integer,
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Styp, Loc),
Attribute_Name => Name_Pos,
Expressions => New_List (Newsub))),
Right_Opnd =>
Convert_To (Standard_Integer,
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Styp, Loc),
Attribute_Name => Name_Pos,
Expressions => New_List (
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Styp, Loc),
Attribute_Name => Name_First)))));
end if;
Set_Paren_Count (Newsub, 1);
-- For the first subscript, we just copy that subscript value
if No (Subscr) then
Subscr := Newsub;
-- Otherwise, we must multiply what we already have by the current
-- stride and then add in the new value to the evolving subscript.
else
Subscr :=
Make_Op_Add (Loc,
Left_Opnd =>
Make_Op_Multiply (Loc,
Left_Opnd => Subscr,
Right_Opnd =>
Make_Attribute_Reference (Loc,
Attribute_Name => Name_Range_Length,
Prefix => New_Occurrence_Of (Styp, Loc))),
Right_Opnd => Newsub);
end if;
-- Move to next subscript
Next_Index (Indx);
Next (Oldsub);
end loop;
end Compute_Linear_Subscript;
-------------------------------
-- Compute_Number_Components --
-------------------------------
function Compute_Number_Components
(N : Node_Id;
Typ : Entity_Id) return Node_Id
is
Loc : constant Source_Ptr := Sloc (N);
Len_Expr : Node_Id;
begin
Len_Expr :=
Make_Attribute_Reference (Loc,
Attribute_Name => Name_Length,
Prefix => New_Occurrence_Of (Typ, Loc),
Expressions => New_List (Make_Integer_Literal (Loc, 1)));
for J in 2 .. Number_Dimensions (Typ) loop
Len_Expr :=
Make_Op_Multiply (Loc,
Left_Opnd => Len_Expr,
Right_Opnd =>
Make_Attribute_Reference (Loc,
Attribute_Name => Name_Length,
Prefix => New_Occurrence_Of (Typ, Loc),
Expressions => New_List (Make_Integer_Literal (Loc, J))));
end loop;
return Len_Expr;
end Compute_Number_Components;
-------------------------
-- Convert_To_PAT_Type --
-------------------------
-- The PAT is always obtained from the actual subtype
procedure Convert_To_PAT_Type (Aexp : Node_Id) is
Act_ST : Entity_Id;
begin
Convert_To_Actual_Subtype (Aexp);
Act_ST := Underlying_Type (Etype (Aexp));
Create_Packed_Array_Impl_Type (Act_ST);
-- Just replace the etype with the packed array type. This works because
-- the expression will not be further analyzed, and Gigi considers the
-- two types equivalent in any case.
-- This is not strictly the case ??? If the reference is an actual in
-- call, the expansion of the prefix is delayed, and must be reanalyzed,
-- see Reset_Packed_Prefix. On the other hand, if the prefix is a simple
-- array reference, reanalysis can produce spurious type errors when the
-- PAT type is replaced again with the original type of the array. Same
-- for the case of a dereference. Ditto for function calls: expansion
-- may introduce additional actuals which will trigger errors if call is
-- reanalyzed. The following is correct and minimal, but the handling of
-- more complex packed expressions in actuals is confused. Probably the
-- problem only remains for actuals in calls.
Set_Etype (Aexp, Packed_Array_Impl_Type (Act_ST));
if Is_Entity_Name (Aexp)
or else
(Nkind (Aexp) = N_Indexed_Component
and then Is_Entity_Name (Prefix (Aexp)))
or else Nkind_In (Aexp, N_Explicit_Dereference, N_Function_Call)
then
Set_Analyzed (Aexp);
end if;
end Convert_To_PAT_Type;
-----------------------------------
-- Create_Packed_Array_Impl_Type --
-----------------------------------
procedure Create_Packed_Array_Impl_Type (Typ : Entity_Id) is
Loc : constant Source_Ptr := Sloc (Typ);
Ctyp : constant Entity_Id := Component_Type (Typ);
Csize : constant Uint := Component_Size (Typ);
Ancest : Entity_Id;
PB_Type : Entity_Id;
PASize : Uint;
Decl : Node_Id;
PAT : Entity_Id;
Len_Expr : Node_Id;
Len_Bits : Uint;
Bits_U1 : Node_Id;
PAT_High : Node_Id;
Btyp : Entity_Id;
Lit : Node_Id;
procedure Install_PAT;
-- This procedure is called with Decl set to the declaration for the
-- packed array type. It creates the type and installs it as required.
procedure Set_PB_Type;
-- Sets PB_Type to Packed_Bytes{1,2,4} as required by the alignment
-- requirements (see documentation in the spec of this package).
-----------------
-- Install_PAT --
-----------------
procedure Install_PAT is
Pushed_Scope : Boolean := False;
begin
-- We do not want to put the declaration we have created in the tree
-- since it is often hard, and sometimes impossible to find a proper
-- place for it (the impossible case arises for a packed array type
-- with bounds depending on the discriminant, a declaration cannot
-- be put inside the record, and the reference to the discriminant
-- cannot be outside the record).
-- The solution is to analyze the declaration while temporarily
-- attached to the tree at an appropriate point, and then we install
-- the resulting type as an Itype in the packed array type field of
-- the original type, so that no explicit declaration is required.
-- Note: the packed type is created in the scope of its parent type.
-- There are at least some cases where the current scope is deeper,
-- and so when this is the case, we temporarily reset the scope
-- for the definition. This is clearly safe, since the first use
-- of the packed array type will be the implicit reference from
-- the corresponding unpacked type when it is elaborated.
if Is_Itype (Typ) then
Set_Parent (Decl, Associated_Node_For_Itype (Typ));
else
Set_Parent (Decl, Declaration_Node (Typ));
end if;
if Scope (Typ) /= Current_Scope then
Push_Scope (Scope (Typ));
Pushed_Scope := True;
end if;
Set_Is_Itype (PAT, True);
Set_Is_Packed_Array_Impl_Type (PAT, True);
Set_Packed_Array_Impl_Type (Typ, PAT);
Analyze (Decl, Suppress => All_Checks);
if Pushed_Scope then
Pop_Scope;
end if;
-- Set Esize and RM_Size to the actual size of the packed object
-- Do not reset RM_Size if already set, as happens in the case of
-- a modular type.
if Unknown_Esize (PAT) then
Set_Esize (PAT, PASize);
end if;
if Unknown_RM_Size (PAT) then
Set_RM_Size (PAT, PASize);
end if;
Adjust_Esize_Alignment (PAT);
-- Set remaining fields of packed array type
Init_Alignment (PAT);
Set_Parent (PAT, Empty);
Set_Associated_Node_For_Itype (PAT, Typ);
Set_Original_Array_Type (PAT, Typ);
-- Propagate representation aspects
Set_Is_Atomic (PAT, Is_Atomic (Typ));
Set_Is_Independent (PAT, Is_Independent (Typ));
Set_Is_Volatile (PAT, Is_Volatile (Typ));
Set_Is_Volatile_Full_Access (PAT, Is_Volatile_Full_Access (Typ));
Set_Treat_As_Volatile (PAT, Treat_As_Volatile (Typ));
-- For a non-bit-packed array, propagate reverse storage order
-- flag from original base type to packed array base type.
if not Is_Bit_Packed_Array (Typ) then
Set_Reverse_Storage_Order
(Etype (PAT), Reverse_Storage_Order (Base_Type (Typ)));
end if;
-- We definitely do not want to delay freezing for packed array
-- types. This is of particular importance for the itypes that are
-- generated for record components depending on discriminants where
-- there is no place to put the freeze node.
Set_Has_Delayed_Freeze (PAT, False);
Set_Has_Delayed_Freeze (Etype (PAT), False);
-- If we did allocate a freeze node, then clear out the reference
-- since it is obsolete (should we delete the freeze node???)
Set_Freeze_Node (PAT, Empty);
Set_Freeze_Node (Etype (PAT), Empty);
end Install_PAT;
-----------------
-- Set_PB_Type --
-----------------
procedure Set_PB_Type is
begin
-- If the user has specified an explicit alignment for the
-- type or component, take it into account.
if Csize <= 2 or else Csize = 4 or else Csize mod 2 /= 0
or else Alignment (Typ) = 1
or else Component_Alignment (Typ) = Calign_Storage_Unit
then
PB_Type := RTE (RE_Packed_Bytes1);
elsif Csize mod 4 /= 0
or else Alignment (Typ) = 2
then
PB_Type := RTE (RE_Packed_Bytes2);
else
PB_Type := RTE (RE_Packed_Bytes4);
end if;
end Set_PB_Type;
-- Start of processing for Create_Packed_Array_Impl_Type
begin
-- If we already have a packed array type, nothing to do
if Present (Packed_Array_Impl_Type (Typ)) then
return;
end if;
-- If our immediate ancestor subtype is constrained, and it already
-- has a packed array type, then just share the same type, since the
-- bounds must be the same. If the ancestor is not an array type but
-- a private type, as can happen with multiple instantiations, create
-- a new packed type, to avoid privacy issues.
if Ekind (Typ) = E_Array_Subtype then
Ancest := Ancestor_Subtype (Typ);
if Present (Ancest)
and then Is_Array_Type (Ancest)
and then Is_Constrained (Ancest)
and then Present (Packed_Array_Impl_Type (Ancest))
then
Set_Packed_Array_Impl_Type (Typ, Packed_Array_Impl_Type (Ancest));
return;
end if;
end if;
-- We preset the result type size from the size of the original array
-- type, since this size clearly belongs to the packed array type. The
-- size of the conceptual unpacked type is always set to unknown.
PASize := RM_Size (Typ);
-- Case of an array where at least one index is of an enumeration
-- type with a non-standard representation, but the component size
-- is not appropriate for bit packing. This is the case where we
-- have Is_Packed set (we would never be in this unit otherwise),
-- but Is_Bit_Packed_Array is false.
-- Note that if the component size is appropriate for bit packing,
-- then the circuit for the computation of the subscript properly
-- deals with the non-standard enumeration type case by taking the
-- Pos anyway.
if not Is_Bit_Packed_Array (Typ) then
-- Here we build a declaration:
-- type tttP is array (index1, index2, ...) of component_type
-- where index1, index2, are the index types. These are the same
-- as the index types of the original array, except for the non-
-- standard representation enumeration type case, where we have
-- two subcases.
-- For the unconstrained array case, we use
-- Natural range <>
-- For the constrained case, we use
-- Natural range Enum_Type'Pos (Enum_Type'First) ..
-- Enum_Type'Pos (Enum_Type'Last);
-- Note that tttP is created even if no index subtype is a non
-- standard enumeration, because we still need to remove padding
-- normally inserted for component alignment.
PAT :=
Make_Defining_Identifier (Loc,
Chars => New_External_Name (Chars (Typ), 'P'));
declare
Indexes : constant List_Id := New_List;
Indx : Node_Id;
Indx_Typ : Entity_Id;
Enum_Case : Boolean;
Typedef : Node_Id;
begin
Indx := First_Index (Typ);
while Present (Indx) loop
Indx_Typ := Etype (Indx);
Enum_Case := Is_Enumeration_Type (Indx_Typ)
and then Has_Non_Standard_Rep (Indx_Typ);
-- Unconstrained case
if not Is_Constrained (Typ) then
if Enum_Case then
Indx_Typ := Standard_Natural;
end if;
Append_To (Indexes, New_Occurrence_Of (Indx_Typ, Loc));
-- Constrained case
else
if not Enum_Case then
Append_To (Indexes, New_Occurrence_Of (Indx_Typ, Loc));
else
Append_To (Indexes,
Make_Subtype_Indication (Loc,
Subtype_Mark =>
New_Occurrence_Of (Standard_Natural, Loc),
Constraint =>
Make_Range_Constraint (Loc,
Range_Expression =>
Make_Range (Loc,
Low_Bound =>
Make_Attribute_Reference (Loc,
Prefix =>
New_Occurrence_Of (Indx_Typ, Loc),
Attribute_Name => Name_Pos,
Expressions => New_List (
Make_Attribute_Reference (Loc,
Prefix =>
New_Occurrence_Of (Indx_Typ, Loc),
Attribute_Name => Name_First))),
High_Bound =>
Make_Attribute_Reference (Loc,
Prefix =>
New_Occurrence_Of (Indx_Typ, Loc),
Attribute_Name => Name_Pos,
Expressions => New_List (
Make_Attribute_Reference (Loc,
Prefix =>
New_Occurrence_Of (Indx_Typ, Loc),
Attribute_Name => Name_Last)))))));
end if;
end if;
Next_Index (Indx);
end loop;
if not Is_Constrained (Typ) then
Typedef :=
Make_Unconstrained_Array_Definition (Loc,
Subtype_Marks => Indexes,
Component_Definition =>
Make_Component_Definition (Loc,
Aliased_Present => False,
Subtype_Indication =>
New_Occurrence_Of (Ctyp, Loc)));
else
Typedef :=
Make_Constrained_Array_Definition (Loc,
Discrete_Subtype_Definitions => Indexes,
Component_Definition =>
Make_Component_Definition (Loc,
Aliased_Present => False,
Subtype_Indication =>
New_Occurrence_Of (Ctyp, Loc)));
end if;
Decl :=
Make_Full_Type_Declaration (Loc,
Defining_Identifier => PAT,
Type_Definition => Typedef);
end;
Install_PAT;
return;
-- Case of bit-packing required for unconstrained array. We create
-- a subtype that is equivalent to use Packed_Bytes{1,2,4} as needed.
elsif not Is_Constrained (Typ) then
-- When generating standard DWARF (i.e when GNAT_Encodings is
-- DWARF_GNAT_Encodings_Minimal), the ___XP suffix will be stripped
-- by the back-end but generate it anyway to ease compiler debugging.
-- This will help to distinguish implementation types from original
-- packed arrays.
PAT :=
Make_Defining_Identifier (Loc,
Chars => Make_Packed_Array_Impl_Type_Name (Typ, Csize));
Set_PB_Type;
Decl :=
Make_Subtype_Declaration (Loc,
Defining_Identifier => PAT,
Subtype_Indication => New_Occurrence_Of (PB_Type, Loc));
Install_PAT;
return;
-- Remaining code is for the case of bit-packing for constrained array
-- The name of the packed array subtype is
-- ttt___XPsss
-- where sss is the component size in bits and ttt is the name of
-- the parent packed type.
else
PAT :=
Make_Defining_Identifier (Loc,
Chars => Make_Packed_Array_Impl_Type_Name (Typ, Csize));
-- Build an expression for the length of the array in bits.
-- This is the product of the length of each of the dimensions
Len_Expr := Compute_Number_Components (Typ, Typ);
-- Temporarily attach the length expression to the tree and analyze
-- and resolve it, so that we can test its value. We assume that the
-- total length fits in type Integer. This expression may involve
-- discriminants, so we treat it as a default/per-object expression.
Set_Parent (Len_Expr, Typ);
Preanalyze_Spec_Expression (Len_Expr, Standard_Long_Long_Integer);
-- Use a modular type if possible. We can do this if we have
-- static bounds, and the length is small enough, and the length
-- is not zero. We exclude the zero length case because the size
-- of things is always at least one, and the zero length object
-- would have an anomalous size.
if Compile_Time_Known_Value (Len_Expr) then
Len_Bits := Expr_Value (Len_Expr) * Csize;
-- Check for size known to be too large
if Len_Bits >
Uint_2 ** (Standard_Integer_Size - 1) * System_Storage_Unit
then
if System_Storage_Unit = 8 then
Error_Msg_N
("packed array size cannot exceed " &
"Integer''Last bytes", Typ);
else
Error_Msg_N
("packed array size cannot exceed " &
"Integer''Last storage units", Typ);
end if;
-- Reset length to arbitrary not too high value to continue
Len_Expr := Make_Integer_Literal (Loc, 65535);
Analyze_And_Resolve (Len_Expr, Standard_Long_Long_Integer);
end if;
-- We normally consider small enough to mean no larger than the
-- value of System_Max_Binary_Modulus_Power, checking that in the
-- case of values longer than word size, we have long shifts.
if Len_Bits > 0
and then
(Len_Bits <= System_Word_Size
or else (Len_Bits <= System_Max_Binary_Modulus_Power
and then Support_Long_Shifts_On_Target))
then
-- We can use the modular type, it has the form:
-- subtype tttPn is btyp
-- range 0 .. 2 ** ((Typ'Length (1)
-- * ... * Typ'Length (n)) * Csize) - 1;
-- The bounds are statically known, and btyp is one of the
-- unsigned types, depending on the length.
if Len_Bits <= Standard_Short_Short_Integer_Size then
Btyp := RTE (RE_Short_Short_Unsigned);
elsif Len_Bits <= Standard_Short_Integer_Size then
Btyp := RTE (RE_Short_Unsigned);
elsif Len_Bits <= Standard_Integer_Size then
Btyp := RTE (RE_Unsigned);
elsif Len_Bits <= Standard_Long_Integer_Size then
Btyp := RTE (RE_Long_Unsigned);
else
Btyp := RTE (RE_Long_Long_Unsigned);
end if;
Lit := Make_Integer_Literal (Loc, 2 ** Len_Bits - 1);
Set_Print_In_Hex (Lit);
Decl :=
Make_Subtype_Declaration (Loc,
Defining_Identifier => PAT,
Subtype_Indication =>
Make_Subtype_Indication (Loc,
Subtype_Mark => New_Occurrence_Of (Btyp, Loc),
Constraint =>
Make_Range_Constraint (Loc,
Range_Expression =>
Make_Range (Loc,
Low_Bound =>
Make_Integer_Literal (Loc, 0),
High_Bound => Lit))));
if PASize = Uint_0 then
PASize := Len_Bits;
end if;
Install_PAT;
-- Propagate a given alignment to the modular type. This can
-- cause it to be under-aligned, but that's OK.
if Present (Alignment_Clause (Typ)) then
Set_Alignment (PAT, Alignment (Typ));
end if;
return;
end if;
end if;
-- Could not use a modular type, for all other cases, we build
-- a packed array subtype:
-- subtype tttPn is
-- System.Packed_Bytes{1,2,4} (0 .. (Bits + 7) / 8 - 1);
-- Bits is the length of the array in bits
Set_PB_Type;
Bits_U1 :=
Make_Op_Add (Loc,
Left_Opnd =>
Make_Op_Multiply (Loc,
Left_Opnd =>
Make_Integer_Literal (Loc, Csize),
Right_Opnd => Len_Expr),
Right_Opnd =>
Make_Integer_Literal (Loc, 7));
Set_Paren_Count (Bits_U1, 1);
PAT_High :=
Make_Op_Subtract (Loc,
Left_Opnd =>
Make_Op_Divide (Loc,
Left_Opnd => Bits_U1,
Right_Opnd => Make_Integer_Literal (Loc, 8)),
Right_Opnd => Make_Integer_Literal (Loc, 1));
Decl :=
Make_Subtype_Declaration (Loc,
Defining_Identifier => PAT,
Subtype_Indication =>
Make_Subtype_Indication (Loc,
Subtype_Mark => New_Occurrence_Of (PB_Type, Loc),
Constraint =>
Make_Index_Or_Discriminant_Constraint (Loc,
Constraints => New_List (
Make_Range (Loc,
Low_Bound =>
Make_Integer_Literal (Loc, 0),
High_Bound =>
Convert_To (Standard_Integer, PAT_High))))));
Install_PAT;
-- Currently the code in this unit requires that packed arrays
-- represented by non-modular arrays of bytes be on a byte
-- boundary for bit sizes handled by System.Pack_nn units.
-- That's because these units assume the array being accessed
-- starts on a byte boundary.
if Get_Id (UI_To_Int (Csize)) /= RE_Null then
Set_Must_Be_On_Byte_Boundary (Typ);
end if;
end if;
end Create_Packed_Array_Impl_Type;
-----------------------------------
-- Expand_Bit_Packed_Element_Set --
-----------------------------------
procedure Expand_Bit_Packed_Element_Set (N : Node_Id) is
Loc : constant Source_Ptr := Sloc (N);
Lhs : constant Node_Id := Name (N);
Ass_OK : constant Boolean := Assignment_OK (Lhs);
-- Used to preserve assignment OK status when assignment is rewritten
Rhs : Node_Id := Expression (N);
-- Initially Rhs is the right hand side value, it will be replaced
-- later by an appropriate unchecked conversion for the assignment.
Obj : Node_Id;
Atyp : Entity_Id;
PAT : Entity_Id;
Ctyp : Entity_Id;
Csiz : Int;
Cmask : Uint;
Shift : Node_Id;
-- The expression for the shift value that is required
Shift_Used : Boolean := False;
-- Set True if Shift has been used in the generated code at least once,
-- so that it must be duplicated if used again.
New_Lhs : Node_Id;
New_Rhs : Node_Id;
Rhs_Val_Known : Boolean;
Rhs_Val : Uint;
-- If the value of the right hand side as an integer constant is
-- known at compile time, Rhs_Val_Known is set True, and Rhs_Val
-- contains the value. Otherwise Rhs_Val_Known is set False, and
-- the Rhs_Val is undefined.
function Get_Shift return Node_Id;
-- Function used to get the value of Shift, making sure that it
-- gets duplicated if the function is called more than once.
---------------
-- Get_Shift --
---------------
function Get_Shift return Node_Id is
begin
-- If we used the shift value already, then duplicate it. We
-- set a temporary parent in case actions have to be inserted.
if Shift_Used then
Set_Parent (Shift, N);
return Duplicate_Subexpr_No_Checks (Shift);
-- If first time, use Shift unchanged, and set flag for first use
else
Shift_Used := True;
return Shift;
end if;
end Get_Shift;
-- Start of processing for Expand_Bit_Packed_Element_Set
begin
pragma Assert (Is_Bit_Packed_Array (Etype (Prefix (Lhs))));
Obj := Relocate_Node (Prefix (Lhs));
Convert_To_Actual_Subtype (Obj);
Atyp := Etype (Obj);
PAT := Packed_Array_Impl_Type (Atyp);
Ctyp := Component_Type (Atyp);
Csiz := UI_To_Int (Component_Size (Atyp));
-- We remove side effects, in case the rhs modifies the lhs, because we
-- are about to transform the rhs into an expression that first READS
-- the lhs, so we can do the necessary shifting and masking. Example:
-- "X(2) := F(...);" where F modifies X(3). Otherwise, the side effect
-- will be lost.
Remove_Side_Effects (Rhs);
-- We convert the right hand side to the proper subtype to ensure
-- that an appropriate range check is made (since the normal range
-- check from assignment will be lost in the transformations). This
-- conversion is analyzed immediately so that subsequent processing
-- can work with an analyzed Rhs (and e.g. look at its Etype)
-- If the right-hand side is a string literal, create a temporary for
-- it, constant-folding is not ready to wrap the bit representation
-- of a string literal.
if Nkind (Rhs) = N_String_Literal then
declare
Decl : Node_Id;
begin
Decl :=
Make_Object_Declaration (Loc,
Defining_Identifier => Make_Temporary (Loc, 'T', Rhs),
Object_Definition => New_Occurrence_Of (Ctyp, Loc),
Expression => New_Copy_Tree (Rhs));
Insert_Actions (N, New_List (Decl));
Rhs := New_Occurrence_Of (Defining_Identifier (Decl), Loc);
end;
end if;
Rhs := Convert_To (Ctyp, Rhs);
Set_Parent (Rhs, N);
-- If we are building the initialization procedure for a packed array,
-- and Initialize_Scalars is enabled, each component assignment is an
-- out-of-range value by design. Compile this value without checks,
-- because a call to the array init_proc must not raise an exception.
-- Condition is not consistent with description above, Within_Init_Proc
-- is True also when we are building the IP for a record or protected
-- type that has a packed array component???
if Within_Init_Proc
and then Initialize_Scalars
then
Analyze_And_Resolve (Rhs, Ctyp, Suppress => All_Checks);
else
Analyze_And_Resolve (Rhs, Ctyp);
end if;
-- Case of component size 1,2,4 or any component size for the modular
-- case. These are the cases for which we can inline the code.
if Csiz = 1 or else Csiz = 2 or else Csiz = 4
or else (Present (PAT) and then Is_Modular_Integer_Type (PAT))
then
Setup_Inline_Packed_Array_Reference (Lhs, Atyp, Obj, Cmask, Shift);
-- The statement to be generated is:
-- Obj := atyp!((Obj and Mask1) or (shift_left (rhs, Shift)))
-- or in the case of a freestanding Reverse_Storage_Order object,
-- Obj := Swap (atyp!((Swap (Obj) and Mask1)
-- or (shift_left (rhs, Shift))))
-- where Mask1 is obtained by shifting Cmask left Shift bits
-- and then complementing the result.
-- the "and Mask1" is omitted if rhs is constant and all 1 bits
-- the "or ..." is omitted if rhs is constant and all 0 bits
-- rhs is converted to the appropriate type
-- The result is converted back to the array type, since
-- otherwise we lose knowledge of the packed nature.
-- Determine if right side is all 0 bits or all 1 bits
if Compile_Time_Known_Value (Rhs) then
Rhs_Val := Expr_Rep_Value (Rhs);
Rhs_Val_Known := True;
-- The following test catches the case of an unchecked conversion of
-- an integer literal. This results from optimizing aggregates of
-- packed types.
elsif Nkind (Rhs) = N_Unchecked_Type_Conversion
and then Compile_Time_Known_Value (Expression (Rhs))
then
Rhs_Val := Expr_Rep_Value (Expression (Rhs));
Rhs_Val_Known := True;
else
Rhs_Val := No_Uint;
Rhs_Val_Known := False;
end if;
-- Some special checks for the case where the right hand value is
-- known at compile time. Basically we have to take care of the
-- implicit conversion to the subtype of the component object.
if Rhs_Val_Known then
-- If we have a biased component type then we must manually do the
-- biasing, since we are taking responsibility in this case for
-- constructing the exact bit pattern to be used.
if Has_Biased_Representation (Ctyp) then
Rhs_Val := Rhs_Val - Expr_Rep_Value (Type_Low_Bound (Ctyp));
end if;
-- For a negative value, we manually convert the two's complement
-- value to a corresponding unsigned value, so that the proper
-- field width is maintained. If we did not do this, we would
-- get too many leading sign bits later on.
if Rhs_Val < 0 then
Rhs_Val := 2 ** UI_From_Int (Csiz) + Rhs_Val;
end if;
end if;
-- Now create copies removing side effects. Note that in some complex
-- cases, this may cause the fact that we have already set a packed
-- array type on Obj to get lost. So we save the type of Obj, and
-- make sure it is reset properly.
New_Lhs := Duplicate_Subexpr (Obj, Name_Req => True);
New_Rhs := Duplicate_Subexpr_No_Checks (Obj);
-- First we deal with the "and"
if not Rhs_Val_Known or else Rhs_Val /= Cmask then
declare
Mask1 : Node_Id;
Lit : Node_Id;
begin
if Compile_Time_Known_Value (Shift) then
Mask1 :=
Make_Integer_Literal (Loc,
Modulus (Etype (Obj)) - 1 -
(Cmask * (2 ** Expr_Value (Get_Shift))));
Set_Print_In_Hex (Mask1);
else
Lit := Make_Integer_Literal (Loc, Cmask);
Set_Print_In_Hex (Lit);
Mask1 :=
Make_Op_Not (Loc,
Right_Opnd => Make_Shift_Left (Lit, Get_Shift));
end if;
New_Rhs :=
Make_Op_And (Loc,
Left_Opnd => New_Rhs,
Right_Opnd => Mask1);
end;
end if;
-- Then deal with the "or"
if not Rhs_Val_Known or else Rhs_Val /= 0 then
declare
Or_Rhs : Node_Id;
procedure Fixup_Rhs;
-- Adjust Rhs by bias if biased representation for components
-- or remove extraneous high order sign bits if signed.
procedure Fixup_Rhs is
Etyp : constant Entity_Id := Etype (Rhs);
begin
-- For biased case, do the required biasing by simply
-- converting to the biased subtype (the conversion
-- will generate the required bias).
if Has_Biased_Representation (Ctyp) then
Rhs := Convert_To (Ctyp, Rhs);
-- For a signed integer type that is not biased, generate
-- a conversion to unsigned to strip high order sign bits.
elsif Is_Signed_Integer_Type (Ctyp) then
Rhs := Unchecked_Convert_To (RTE (Bits_Id (Csiz)), Rhs);
end if;
-- Set Etype, since it can be referenced before the node is
-- completely analyzed.
Set_Etype (Rhs, Etyp);
-- We now need to do an unchecked conversion of the
-- result to the target type, but it is important that
-- this conversion be a right justified conversion and
-- not a left justified conversion.
Rhs := RJ_Unchecked_Convert_To (Etype (Obj), Rhs);
end Fixup_Rhs;
begin
if Rhs_Val_Known
and then Compile_Time_Known_Value (Get_Shift)
then
Or_Rhs :=
Make_Integer_Literal (Loc,
Rhs_Val * (2 ** Expr_Value (Get_Shift)));
Set_Print_In_Hex (Or_Rhs);
else
-- We have to convert the right hand side to Etype (Obj).
-- A special case arises if what we have now is a Val
-- attribute reference whose expression type is Etype (Obj).
-- This happens for assignments of fields from the same
-- array. In this case we get the required right hand side
-- by simply removing the inner attribute reference.
if Nkind (Rhs) = N_Attribute_Reference
and then Attribute_Name (Rhs) = Name_Val
and then Etype (First (Expressions (Rhs))) = Etype (Obj)
then
Rhs := Relocate_Node (First (Expressions (Rhs)));
Fixup_Rhs;
-- If the value of the right hand side is a known integer
-- value, then just replace it by an untyped constant,
-- which will be properly retyped when we analyze and
-- resolve the expression.
elsif Rhs_Val_Known then
-- Note that Rhs_Val has already been normalized to
-- be an unsigned value with the proper number of bits.
Rhs := Make_Integer_Literal (Loc, Rhs_Val);
-- Otherwise we need an unchecked conversion
else
Fixup_Rhs;
end if;
Or_Rhs := Make_Shift_Left (Rhs, Get_Shift);
end if;
if Nkind (New_Rhs) = N_Op_And then
Set_Paren_Count (New_Rhs, 1);
Set_Etype (New_Rhs, Etype (Left_Opnd (New_Rhs)));
end if;
New_Rhs :=
Make_Op_Or (Loc,
Left_Opnd => New_Rhs,
Right_Opnd => Or_Rhs);
end;
end if;
-- Now do the rewrite
Rewrite (N,
Make_Assignment_Statement (Loc,
Name => New_Lhs,
Expression =>
Unchecked_Convert_To (Etype (New_Lhs), New_Rhs)));
Set_Assignment_OK (Name (N), Ass_OK);
-- All other component sizes for non-modular case
else
-- We generate
-- Set_nn (Arr'address, Subscr, Bits_nn!(Rhs))
-- where Subscr is the computed linear subscript
declare
Bits_nn : constant Entity_Id := RTE (Bits_Id (Csiz));
Set_nn : Entity_Id;
Subscr : Node_Id;
Atyp : Entity_Id;
Rev_SSO : Node_Id;
begin
if No (Bits_nn) then
-- Error, most likely High_Integrity_Mode restriction
return;
end if;
-- Acquire proper Set entity. We use the aligned or unaligned
-- case as appropriate.
if Known_Aligned_Enough (Obj, Csiz) then
Set_nn := RTE (Set_Id (Csiz));
else
Set_nn := RTE (SetU_Id (Csiz));
end if;
-- Now generate the set reference
Obj := Relocate_Node (Prefix (Lhs));
Convert_To_Actual_Subtype (Obj);
Atyp := Etype (Obj);
Compute_Linear_Subscript (Atyp, Lhs, Subscr);
-- Set indication of whether the packed array has reverse SSO
Rev_SSO :=
New_Occurrence_Of
(Boolean_Literals (Reverse_Storage_Order (Atyp)), Loc);
-- Below we must make the assumption that Obj is
-- at least byte aligned, since otherwise its address
-- cannot be taken. The assumption holds since the
-- only arrays that can be misaligned are small packed
-- arrays which are implemented as a modular type, and
-- that is not the case here.
Rewrite (N,
Make_Procedure_Call_Statement (Loc,
Name => New_Occurrence_Of (Set_nn, Loc),
Parameter_Associations => New_List (
Make_Attribute_Reference (Loc,
Prefix => Obj,
Attribute_Name => Name_Address),
Subscr,
Unchecked_Convert_To (Bits_nn, Convert_To (Ctyp, Rhs)),
Rev_SSO)));
end;
end if;
Analyze (N, Suppress => All_Checks);
end Expand_Bit_Packed_Element_Set;
-------------------------------------
-- Expand_Packed_Address_Reference --
-------------------------------------
procedure Expand_Packed_Address_Reference (N : Node_Id) is
Loc : constant Source_Ptr := Sloc (N);
Base : Node_Id;
Offset : Node_Id;
begin
-- We build an expression that has the form
-- outer_object'Address
-- + (linear-subscript * component_size for each array reference
-- + field'Bit_Position for each record field
-- + ...
-- + ...) / Storage_Unit;
Get_Base_And_Bit_Offset (Prefix (N), Base, Offset);
Rewrite (N,
Unchecked_Convert_To (RTE (RE_Address),
Make_Op_Add (Loc,
Left_Opnd =>
Unchecked_Convert_To (RTE (RE_Integer_Address),
Make_Attribute_Reference (Loc,
Prefix => Base,
Attribute_Name => Name_Address)),
Right_Opnd =>
Unchecked_Convert_To (RTE (RE_Integer_Address),
Make_Op_Divide (Loc,
Left_Opnd => Offset,
Right_Opnd =>
Make_Integer_Literal (Loc, System_Storage_Unit))))));
Analyze_And_Resolve (N, RTE (RE_Address));
end Expand_Packed_Address_Reference;
---------------------------------
-- Expand_Packed_Bit_Reference --
---------------------------------
procedure Expand_Packed_Bit_Reference (N : Node_Id) is
Loc : constant Source_Ptr := Sloc (N);
Base : Node_Id;
Offset : Node_Id;
begin
-- We build an expression that has the form
-- (linear-subscript * component_size for each array reference
-- + field'Bit_Position for each record field
-- + ...
-- + ...) mod Storage_Unit;
Get_Base_And_Bit_Offset (Prefix (N), Base, Offset);
Rewrite (N,
Unchecked_Convert_To (Universal_Integer,
Make_Op_Mod (Loc,
Left_Opnd => Offset,
Right_Opnd => Make_Integer_Literal (Loc, System_Storage_Unit))));
Analyze_And_Resolve (N, Universal_Integer);
end Expand_Packed_Bit_Reference;
------------------------------------
-- Expand_Packed_Boolean_Operator --
------------------------------------
-- This routine expands "a op b" for the packed cases
procedure Expand_Packed_Boolean_Operator (N : Node_Id) is
Loc : constant Source_Ptr := Sloc (N);
Typ : constant Entity_Id := Etype (N);
L : constant Node_Id := Relocate_Node (Left_Opnd (N));
R : constant Node_Id := Relocate_Node (Right_Opnd (N));
Ltyp : Entity_Id;
Rtyp : Entity_Id;
PAT : Entity_Id;
begin
Convert_To_Actual_Subtype (L);
Convert_To_Actual_Subtype (R);
Ensure_Defined (Etype (L), N);
Ensure_Defined (Etype (R), N);
Apply_Length_Check (R, Etype (L));
Ltyp := Etype (L);
Rtyp := Etype (R);
-- Deal with silly case of XOR where the subcomponent has a range
-- True .. True where an exception must be raised.
if Nkind (N) = N_Op_Xor then
Silly_Boolean_Array_Xor_Test (N, Rtyp);
end if;
-- Now that that silliness is taken care of, get packed array type
Convert_To_PAT_Type (L);
Convert_To_PAT_Type (R);
PAT := Etype (L);
-- For the modular case, we expand a op b into
-- rtyp!(pat!(a) op pat!(b))
-- where rtyp is the Etype of the left operand. Note that we do not
-- convert to the base type, since this would be unconstrained, and
-- hence not have a corresponding packed array type set.
-- Note that both operands must be modular for this code to be used
if Is_Modular_Integer_Type (PAT)
and then
Is_Modular_Integer_Type (Etype (R))
then
declare
P : Node_Id;
begin
if Nkind (N) = N_Op_And then
P := Make_Op_And (Loc, L, R);
elsif Nkind (N) = N_Op_Or then
P := Make_Op_Or (Loc, L, R);
else -- Nkind (N) = N_Op_Xor
P := Make_Op_Xor (Loc, L, R);
end if;
Rewrite (N, Unchecked_Convert_To (Ltyp, P));
end;
-- For the array case, we insert the actions
-- Result : Ltype;
-- System.Bit_Ops.Bit_And/Or/Xor
-- (Left'Address,
-- Ltype'Length * Ltype'Component_Size;
-- Right'Address,
-- Rtype'Length * Rtype'Component_Size
-- Result'Address);
-- where Left and Right are the Packed_Bytes{1,2,4} operands and
-- the second argument and fourth arguments are the lengths of the
-- operands in bits. Then we replace the expression by a reference
-- to Result.
-- Note that if we are mixing a modular and array operand, everything
-- works fine, since we ensure that the modular representation has the
-- same physical layout as the array representation (that's what the
-- left justified modular stuff in the big-endian case is about).
else
declare
Result_Ent : constant Entity_Id := Make_Temporary (Loc, 'T');
E_Id : RE_Id;
begin
if Nkind (N) = N_Op_And then
E_Id := RE_Bit_And;
elsif Nkind (N) = N_Op_Or then
E_Id := RE_Bit_Or;
else -- Nkind (N) = N_Op_Xor
E_Id := RE_Bit_Xor;
end if;
Insert_Actions (N, New_List (
Make_Object_Declaration (Loc,
Defining_Identifier => Result_Ent,
Object_Definition => New_Occurrence_Of (Ltyp, Loc)),
Make_Procedure_Call_Statement (Loc,
Name => New_Occurrence_Of (RTE (E_Id), Loc),
Parameter_Associations => New_List (
Make_Byte_Aligned_Attribute_Reference (Loc,
Prefix => L,
Attribute_Name => Name_Address),
Make_Op_Multiply (Loc,
Left_Opnd =>
Make_Attribute_Reference (Loc,
Prefix =>
New_Occurrence_Of
(Etype (First_Index (Ltyp)), Loc),
Attribute_Name => Name_Range_Length),
Right_Opnd =>
Make_Integer_Literal (Loc, Component_Size (Ltyp))),
Make_Byte_Aligned_Attribute_Reference (Loc,
Prefix => R,
Attribute_Name => Name_Address),
Make_Op_Multiply (Loc,
Left_Opnd =>
Make_Attribute_Reference (Loc,
Prefix =>
New_Occurrence_Of
(Etype (First_Index (Rtyp)), Loc),
Attribute_Name => Name_Range_Length),
Right_Opnd =>
Make_Integer_Literal (Loc, Component_Size (Rtyp))),
Make_Byte_Aligned_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Result_Ent, Loc),
Attribute_Name => Name_Address)))));
Rewrite (N,
New_Occurrence_Of (Result_Ent, Loc));
end;
end if;
Analyze_And_Resolve (N, Typ, Suppress => All_Checks);
end Expand_Packed_Boolean_Operator;
-------------------------------------
-- Expand_Packed_Element_Reference --
-------------------------------------
procedure Expand_Packed_Element_Reference (N : Node_Id) is
Loc : constant Source_Ptr := Sloc (N);
Obj : Node_Id;
Atyp : Entity_Id;
PAT : Entity_Id;
Ctyp : Entity_Id;
Csiz : Int;
Shift : Node_Id;
Cmask : Uint;
Lit : Node_Id;
Arg : Node_Id;
begin
-- If the node is an actual in a call, the prefix has not been fully
-- expanded, to account for the additional expansion for in-out actuals
-- (see expand_actuals for details). If the prefix itself is a packed
-- reference as well, we have to recurse to complete the transformation
-- of the prefix.
if Nkind (Prefix (N)) = N_Indexed_Component
and then not Analyzed (Prefix (N))
and then Is_Bit_Packed_Array (Etype (Prefix (Prefix (N))))
then
Expand_Packed_Element_Reference (Prefix (N));
end if;
-- The prefix may be rewritten below as a conversion. If it is a source
-- entity generate reference to it now, to prevent spurious warnings
-- about unused entities.
if Is_Entity_Name (Prefix (N))
and then Comes_From_Source (Prefix (N))
then
Generate_Reference (Entity (Prefix (N)), Prefix (N), 'r');
end if;
-- If not bit packed, we have the enumeration case, which is easily
-- dealt with (just adjust the subscripts of the indexed component)
-- Note: this leaves the result as an indexed component, which is
-- still a variable, so can be used in the assignment case, as is
-- required in the enumeration case.
if not Is_Bit_Packed_Array (Etype (Prefix (N))) then
Setup_Enumeration_Packed_Array_Reference (N);
return;
end if;
-- Remaining processing is for the bit-packed case
Obj := Relocate_Node (Prefix (N));
Convert_To_Actual_Subtype (Obj);
Atyp := Etype (Obj);
PAT := Packed_Array_Impl_Type (Atyp);
Ctyp := Component_Type (Atyp);
Csiz := UI_To_Int (Component_Size (Atyp));
-- Case of component size 1,2,4 or any component size for the modular
-- case. These are the cases for which we can inline the code.
if Csiz = 1 or else Csiz = 2 or else Csiz = 4
or else (Present (PAT) and then Is_Modular_Integer_Type (PAT))
then
Setup_Inline_Packed_Array_Reference (N, Atyp, Obj, Cmask, Shift);
Lit := Make_Integer_Literal (Loc, Cmask);
Set_Print_In_Hex (Lit);
-- We generate a shift right to position the field, followed by a
-- masking operation to extract the bit field, and we finally do an
-- unchecked conversion to convert the result to the required target.
-- Note that the unchecked conversion automatically deals with the
-- bias if we are dealing with a biased representation. What will
-- happen is that we temporarily generate the biased representation,
-- but almost immediately that will be converted to the original
-- unbiased component type, and the bias will disappear.
Arg :=
Make_Op_And (Loc,
Left_Opnd => Make_Shift_Right (Obj, Shift),
Right_Opnd => Lit);
Set_Etype (Arg, Ctyp);
-- Component extraction is performed on a native endianness scalar
-- value: if Atyp has reverse storage order, then it has been byte
-- swapped, and if the component being extracted is itself of a
-- composite type with reverse storage order, then we need to swap
-- it back to its expected endianness after extraction.
if Reverse_Storage_Order (Atyp)
and then (Is_Record_Type (Ctyp) or else Is_Array_Type (Ctyp))
and then Reverse_Storage_Order (Ctyp)
then
Arg := Revert_Storage_Order (Arg);
end if;
-- We needed to analyze this before we do the unchecked convert
-- below, but we need it temporarily attached to the tree for
-- this analysis (hence the temporary Set_Parent call).
Set_Parent (Arg, Parent (N));
Analyze_And_Resolve (Arg);
Rewrite (N, RJ_Unchecked_Convert_To (Ctyp, Arg));
-- All other component sizes for non-modular case
else
-- We generate
-- Component_Type!(Get_nn (Arr'address, Subscr))
-- where Subscr is the computed linear subscript
declare
Get_nn : Entity_Id;
Subscr : Node_Id;
Rev_SSO : constant Node_Id :=
New_Occurrence_Of
(Boolean_Literals (Reverse_Storage_Order (Atyp)), Loc);
begin
-- Acquire proper Get entity. We use the aligned or unaligned
-- case as appropriate.
if Known_Aligned_Enough (Obj, Csiz) then
Get_nn := RTE (Get_Id (Csiz));
else
Get_nn := RTE (GetU_Id (Csiz));
end if;
-- Now generate the get reference
Compute_Linear_Subscript (Atyp, N, Subscr);
-- Below we make the assumption that Obj is at least byte
-- aligned, since otherwise its address cannot be taken.
-- The assumption holds since the only arrays that can be
-- misaligned are small packed arrays which are implemented
-- as a modular type, and that is not the case here.
Rewrite (N,
Unchecked_Convert_To (Ctyp,
Make_Function_Call (Loc,
Name => New_Occurrence_Of (Get_nn, Loc),
Parameter_Associations => New_List (
Make_Attribute_Reference (Loc,
Prefix => Obj,
Attribute_Name => Name_Address),
Subscr,
Rev_SSO))));
end;
end if;
Analyze_And_Resolve (N, Ctyp, Suppress => All_Checks);
end Expand_Packed_Element_Reference;
----------------------
-- Expand_Packed_Eq --
----------------------
-- Handles expansion of "=" on packed array types
procedure Expand_Packed_Eq (N : Node_Id) is
Loc : constant Source_Ptr := Sloc (N);
L : constant Node_Id := Relocate_Node (Left_Opnd (N));
R : constant Node_Id := Relocate_Node (Right_Opnd (N));
LLexpr : Node_Id;
RLexpr : Node_Id;
Ltyp : Entity_Id;
Rtyp : Entity_Id;
PAT : Entity_Id;
begin
Convert_To_Actual_Subtype (L);
Convert_To_Actual_Subtype (R);
Ltyp := Underlying_Type (Etype (L));
Rtyp := Underlying_Type (Etype (R));
Convert_To_PAT_Type (L);
Convert_To_PAT_Type (R);
PAT := Etype (L);
LLexpr :=
Make_Op_Multiply (Loc,
Left_Opnd => Compute_Number_Components (N, Ltyp),
Right_Opnd => Make_Integer_Literal (Loc, Component_Size (Ltyp)));
RLexpr :=
Make_Op_Multiply (Loc,
Left_Opnd => Compute_Number_Components (N, Rtyp),
Right_Opnd => Make_Integer_Literal (Loc, Component_Size (Rtyp)));
-- For the modular case, we transform the comparison to:
-- Ltyp'Length = Rtyp'Length and then PAT!(L) = PAT!(R)
-- where PAT is the packed array type. This works fine, since in the
-- modular case we guarantee that the unused bits are always zeroes.
-- We do have to compare the lengths because we could be comparing
-- two different subtypes of the same base type.
if Is_Modular_Integer_Type (PAT) then
Rewrite (N,
Make_And_Then (Loc,
Left_Opnd =>
Make_Op_Eq (Loc,
Left_Opnd => LLexpr,
Right_Opnd => RLexpr),
Right_Opnd =>
Make_Op_Eq (Loc,
Left_Opnd => L,
Right_Opnd => R)));
-- For the non-modular case, we call a runtime routine
-- System.Bit_Ops.Bit_Eq
-- (L'Address, L_Length, R'Address, R_Length)
-- where PAT is the packed array type, and the lengths are the lengths
-- in bits of the original packed arrays. This routine takes care of
-- not comparing the unused bits in the last byte.
else
Rewrite (N,
Make_Function_Call (Loc,
Name => New_Occurrence_Of (RTE (RE_Bit_Eq), Loc),
Parameter_Associations => New_List (
Make_Byte_Aligned_Attribute_Reference (Loc,
Prefix => L,
Attribute_Name => Name_Address),
LLexpr,
Make_Byte_Aligned_Attribute_Reference (Loc,
Prefix => R,
Attribute_Name => Name_Address),
RLexpr)));
end if;
Analyze_And_Resolve (N, Standard_Boolean, Suppress => All_Checks);
end Expand_Packed_Eq;
-----------------------
-- Expand_Packed_Not --
-----------------------
-- Handles expansion of "not" on packed array types
procedure Expand_Packed_Not (N : Node_Id) is
Loc : constant Source_Ptr := Sloc (N);
Typ : constant Entity_Id := Etype (N);
Opnd : constant Node_Id := Relocate_Node (Right_Opnd (N));
Rtyp : Entity_Id;
PAT : Entity_Id;
Lit : Node_Id;
begin
Convert_To_Actual_Subtype (Opnd);
Rtyp := Etype (Opnd);
-- Deal with silly False..False and True..True subtype case
Silly_Boolean_Array_Not_Test (N, Rtyp);
-- Now that the silliness is taken care of, get packed array type
Convert_To_PAT_Type (Opnd);
PAT := Etype (Opnd);
-- For the case where the packed array type is a modular type, "not A"
-- expands simply into:
-- Rtyp!(PAT!(A) xor Mask)
-- where PAT is the packed array type, Mask is a mask of all 1 bits of
-- length equal to the size of this packed type, and Rtyp is the actual
-- actual subtype of the operand.
Lit := Make_Integer_Literal (Loc, 2 ** RM_Size (PAT) - 1);
Set_Print_In_Hex (Lit);
if not Is_Array_Type (PAT) then
Rewrite (N,
Unchecked_Convert_To (Rtyp,
Make_Op_Xor (Loc,
Left_Opnd => Opnd,
Right_Opnd => Lit)));
-- For the array case, we insert the actions
-- Result : Typ;
-- System.Bit_Ops.Bit_Not
-- (Opnd'Address,
-- Typ'Length * Typ'Component_Size,
-- Result'Address);
-- where Opnd is the Packed_Bytes{1,2,4} operand and the second argument
-- is the length of the operand in bits. We then replace the expression
-- with a reference to Result.
else
declare
Result_Ent : constant Entity_Id := Make_Temporary (Loc, 'T');
begin
Insert_Actions (N, New_List (
Make_Object_Declaration (Loc,
Defining_Identifier => Result_Ent,
Object_Definition => New_Occurrence_Of (Rtyp, Loc)),
Make_Procedure_Call_Statement (Loc,
Name => New_Occurrence_Of (RTE (RE_Bit_Not), Loc),
Parameter_Associations => New_List (
Make_Byte_Aligned_Attribute_Reference (Loc,
Prefix => Opnd,
Attribute_Name => Name_Address),
Make_Op_Multiply (Loc,
Left_Opnd =>
Make_Attribute_Reference (Loc,
Prefix =>
New_Occurrence_Of
(Etype (First_Index (Rtyp)), Loc),
Attribute_Name => Name_Range_Length),
Right_Opnd =>
Make_Integer_Literal (Loc, Component_Size (Rtyp))),
Make_Byte_Aligned_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Result_Ent, Loc),
Attribute_Name => Name_Address)))));
Rewrite (N, New_Occurrence_Of (Result_Ent, Loc));
end;
end if;
Analyze_And_Resolve (N, Typ, Suppress => All_Checks);
end Expand_Packed_Not;
-----------------------------
-- Get_Base_And_Bit_Offset --
-----------------------------
procedure Get_Base_And_Bit_Offset
(N : Node_Id;
Base : out Node_Id;
Offset : out Node_Id)
is
Loc : Source_Ptr;
Term : Node_Id;
Atyp : Entity_Id;
Subscr : Node_Id;
begin
Base := N;
Offset := Empty;
-- We build up an expression serially that has the form
-- linear-subscript * component_size for each array reference
-- + field'Bit_Position for each record field
-- + ...
loop
Loc := Sloc (Base);
if Nkind (Base) = N_Indexed_Component then
Convert_To_Actual_Subtype (Prefix (Base));
Atyp := Etype (Prefix (Base));
Compute_Linear_Subscript (Atyp, Base, Subscr);
Term :=
Make_Op_Multiply (Loc,
Left_Opnd => Subscr,
Right_Opnd =>
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Atyp, Loc),
Attribute_Name => Name_Component_Size));
elsif Nkind (Base) = N_Selected_Component then
Term :=
Make_Attribute_Reference (Loc,
Prefix => Selector_Name (Base),
Attribute_Name => Name_Bit_Position);
else
return;
end if;
if No (Offset) then
Offset := Term;
else
Offset :=
Make_Op_Add (Loc,
Left_Opnd => Offset,
Right_Opnd => Term);
end if;
Base := Prefix (Base);
end loop;
end Get_Base_And_Bit_Offset;
-------------------------------------
-- Involves_Packed_Array_Reference --
-------------------------------------
function Involves_Packed_Array_Reference (N : Node_Id) return Boolean is
begin
if Nkind (N) = N_Indexed_Component
and then Is_Bit_Packed_Array (Etype (Prefix (N)))
then
return True;
elsif Nkind (N) = N_Selected_Component then
return Involves_Packed_Array_Reference (Prefix (N));
else
return False;
end if;
end Involves_Packed_Array_Reference;
--------------------------
-- Known_Aligned_Enough --
--------------------------
function Known_Aligned_Enough (Obj : Node_Id; Csiz : Nat) return Boolean is
Typ : constant Entity_Id := Etype (Obj);
function In_Partially_Packed_Record (Comp : Entity_Id) return Boolean;
-- If the component is in a record that contains previous packed
-- components, consider it unaligned because the back-end might
-- choose to pack the rest of the record. Lead to less efficient code,
-- but safer vis-a-vis of back-end choices.
--------------------------------
-- In_Partially_Packed_Record --
--------------------------------
function In_Partially_Packed_Record (Comp : Entity_Id) return Boolean is
Rec_Type : constant Entity_Id := Scope (Comp);
Prev_Comp : Entity_Id;
begin
Prev_Comp := First_Entity (Rec_Type);
while Present (Prev_Comp) loop
if Is_Packed (Etype (Prev_Comp)) then
return True;
elsif Prev_Comp = Comp then
return False;
end if;
Next_Entity (Prev_Comp);
end loop;
return False;
end In_Partially_Packed_Record;
-- Start of processing for Known_Aligned_Enough
begin
-- Odd bit sizes don't need alignment anyway
if Csiz mod 2 = 1 then
return True;
-- If we have a specified alignment, see if it is sufficient, if not
-- then we can't possibly be aligned enough in any case.
elsif Known_Alignment (Etype (Obj)) then
-- Alignment required is 4 if size is a multiple of 4, and
-- 2 otherwise (e.g. 12 bits requires 4, 10 bits requires 2)
if Alignment (Etype (Obj)) < 4 - (Csiz mod 4) then
return False;
end if;
end if;
-- OK, alignment should be sufficient, if object is aligned
-- If object is strictly aligned, then it is definitely aligned
if Strict_Alignment (Typ) then
return True;
-- Case of subscripted array reference
elsif Nkind (Obj) = N_Indexed_Component then
-- If we have a pointer to an array, then this is definitely
-- aligned, because pointers always point to aligned versions.
if Is_Access_Type (Etype (Prefix (Obj))) then
return True;
-- Otherwise, go look at the prefix
else
return Known_Aligned_Enough (Prefix (Obj), Csiz);
end if;
-- Case of record field
elsif Nkind (Obj) = N_Selected_Component then
-- What is significant here is whether the record type is packed
if Is_Record_Type (Etype (Prefix (Obj)))
and then Is_Packed (Etype (Prefix (Obj)))
then
return False;
-- Or the component has a component clause which might cause
-- the component to become unaligned (we can't tell if the
-- backend is doing alignment computations).
elsif Present (Component_Clause (Entity (Selector_Name (Obj)))) then
return False;
elsif In_Partially_Packed_Record (Entity (Selector_Name (Obj))) then
return False;
-- In all other cases, go look at prefix
else
return Known_Aligned_Enough (Prefix (Obj), Csiz);
end if;
elsif Nkind (Obj) = N_Type_Conversion then
return Known_Aligned_Enough (Expression (Obj), Csiz);
-- For a formal parameter, it is safer to assume that it is not
-- aligned, because the formal may be unconstrained while the actual
-- is constrained. In this situation, a small constrained packed
-- array, represented in modular form, may be unaligned.
elsif Is_Entity_Name (Obj) then
return not Is_Formal (Entity (Obj));
else
-- If none of the above, must be aligned
return True;
end if;
end Known_Aligned_Enough;
---------------------
-- Make_Shift_Left --
---------------------
function Make_Shift_Left (N : Node_Id; S : Node_Id) return Node_Id is
Nod : Node_Id;
begin
if Compile_Time_Known_Value (S) and then Expr_Value (S) = 0 then
return N;
else
Nod :=
Make_Op_Shift_Left (Sloc (N),
Left_Opnd => N,
Right_Opnd => S);
Set_Shift_Count_OK (Nod, True);
return Nod;
end if;
end Make_Shift_Left;
----------------------
-- Make_Shift_Right --
----------------------
function Make_Shift_Right (N : Node_Id; S : Node_Id) return Node_Id is
Nod : Node_Id;
begin
if Compile_Time_Known_Value (S) and then Expr_Value (S) = 0 then
return N;
else
Nod :=
Make_Op_Shift_Right (Sloc (N),
Left_Opnd => N,
Right_Opnd => S);
Set_Shift_Count_OK (Nod, True);
return Nod;
end if;
end Make_Shift_Right;
-----------------------------
-- RJ_Unchecked_Convert_To --
-----------------------------
function RJ_Unchecked_Convert_To
(Typ : Entity_Id;
Expr : Node_Id) return Node_Id
is
Source_Typ : constant Entity_Id := Etype (Expr);
Target_Typ : constant Entity_Id := Typ;
Src : Node_Id := Expr;
Source_Siz : Nat;
Target_Siz : Nat;
begin
Source_Siz := UI_To_Int (RM_Size (Source_Typ));
Target_Siz := UI_To_Int (RM_Size (Target_Typ));
-- For a little-endian target type stored byte-swapped on a
-- big-endian machine, do not mask to Target_Siz bits.
if Bytes_Big_Endian
and then (Is_Record_Type (Target_Typ)
or else
Is_Array_Type (Target_Typ))
and then Reverse_Storage_Order (Target_Typ)
then
Source_Siz := Target_Siz;
end if;
-- First step, if the source type is not a discrete type, then we first
-- convert to a modular type of the source length, since otherwise, on
-- a big-endian machine, we get left-justification. We do it for little-
-- endian machines as well, because there might be junk bits that are
-- not cleared if the type is not numeric. This can be done only if the
-- source siz is different from 0 (i.e. known), otherwise we must trust
-- the type declarations (case of non-discrete components).
if Source_Siz /= 0
and then Source_Siz /= Target_Siz
and then not Is_Discrete_Type (Source_Typ)
then
Src := Unchecked_Convert_To (RTE (Bits_Id (Source_Siz)), Src);
end if;
-- In the big endian case, if the lengths of the two types differ, then
-- we must worry about possible left justification in the conversion,
-- and avoiding that is what this is all about.
if Bytes_Big_Endian and then Source_Siz /= Target_Siz then
-- Next step. If the target is not a discrete type, then we first
-- convert to a modular type of the target length, since otherwise,
-- on a big-endian machine, we get left-justification.
if not Is_Discrete_Type (Target_Typ) then
Src := Unchecked_Convert_To (RTE (Bits_Id (Target_Siz)), Src);
end if;
end if;
-- And now we can do the final conversion to the target type
return Unchecked_Convert_To (Target_Typ, Src);
end RJ_Unchecked_Convert_To;
----------------------------------------------
-- Setup_Enumeration_Packed_Array_Reference --
----------------------------------------------
-- All we have to do here is to find the subscripts that correspond to the
-- index positions that have non-standard enumeration types and insert a
-- Pos attribute to get the proper subscript value.
-- Finally the prefix must be uncheck-converted to the corresponding packed
-- array type.
-- Note that the component type is unchanged, so we do not need to fiddle
-- with the types (Gigi always automatically takes the packed array type if
-- it is set, as it will be in this case).
procedure Setup_Enumeration_Packed_Array_Reference (N : Node_Id) is
Pfx : constant Node_Id := Prefix (N);
Typ : constant Entity_Id := Etype (N);
Exprs : constant List_Id := Expressions (N);
Expr : Node_Id;
begin
-- If the array is unconstrained, then we replace the array reference
-- with its actual subtype. This actual subtype will have a packed array
-- type with appropriate bounds.
if not Is_Constrained (Packed_Array_Impl_Type (Etype (Pfx))) then
Convert_To_Actual_Subtype (Pfx);
end if;
Expr := First (Exprs);
while Present (Expr) loop
declare
Loc : constant Source_Ptr := Sloc (Expr);
Expr_Typ : constant Entity_Id := Etype (Expr);
begin
if Is_Enumeration_Type (Expr_Typ)
and then Has_Non_Standard_Rep (Expr_Typ)
then
Rewrite (Expr,
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Expr_Typ, Loc),
Attribute_Name => Name_Pos,
Expressions => New_List (Relocate_Node (Expr))));
Analyze_And_Resolve (Expr, Standard_Natural);
end if;
end;
Next (Expr);
end loop;
Rewrite (N,
Make_Indexed_Component (Sloc (N),
Prefix =>
Unchecked_Convert_To (Packed_Array_Impl_Type (Etype (Pfx)), Pfx),
Expressions => Exprs));
Analyze_And_Resolve (N, Typ);
end Setup_Enumeration_Packed_Array_Reference;
-----------------------------------------
-- Setup_Inline_Packed_Array_Reference --
-----------------------------------------
procedure Setup_Inline_Packed_Array_Reference
(N : Node_Id;
Atyp : Entity_Id;
Obj : in out Node_Id;
Cmask : out Uint;
Shift : out Node_Id)
is
Loc : constant Source_Ptr := Sloc (N);
PAT : Entity_Id;
Otyp : Entity_Id;
Csiz : Uint;
Osiz : Uint;
begin
Csiz := Component_Size (Atyp);
Convert_To_PAT_Type (Obj);
PAT := Etype (Obj);
Cmask := 2 ** Csiz - 1;
if Is_Array_Type (PAT) then
Otyp := Component_Type (PAT);
Osiz := Component_Size (PAT);
else
Otyp := PAT;
-- In the case where the PAT is a modular type, we want the actual
-- size in bits of the modular value we use. This is neither the
-- Object_Size nor the Value_Size, either of which may have been
-- reset to strange values, but rather the minimum size. Note that
-- since this is a modular type with full range, the issue of
-- biased representation does not arise.
Osiz := UI_From_Int (Minimum_Size (Otyp));
end if;
Compute_Linear_Subscript (Atyp, N, Shift);
-- If the component size is not 1, then the subscript must be multiplied
-- by the component size to get the shift count.
if Csiz /= 1 then
Shift :=
Make_Op_Multiply (Loc,
Left_Opnd => Make_Integer_Literal (Loc, Csiz),
Right_Opnd => Shift);
end if;
-- If we have the array case, then this shift count must be broken down
-- into a byte subscript, and a shift within the byte.
if Is_Array_Type (PAT) then
declare
New_Shift : Node_Id;
begin
-- We must analyze shift, since we will duplicate it
Set_Parent (Shift, N);
Analyze_And_Resolve
(Shift, Standard_Integer, Suppress => All_Checks);
-- The shift count within the word is
-- shift mod Osiz
New_Shift :=
Make_Op_Mod (Loc,
Left_Opnd => Duplicate_Subexpr (Shift),
Right_Opnd => Make_Integer_Literal (Loc, Osiz));
-- The subscript to be used on the PAT array is
-- shift / Osiz
Obj :=
Make_Indexed_Component (Loc,
Prefix => Obj,
Expressions => New_List (
Make_Op_Divide (Loc,
Left_Opnd => Duplicate_Subexpr (Shift),
Right_Opnd => Make_Integer_Literal (Loc, Osiz))));
Shift := New_Shift;
end;
-- For the modular integer case, the object to be manipulated is the
-- entire array, so Obj is unchanged. Note that we will reset its type
-- to PAT before returning to the caller.
else
null;
end if;
-- The one remaining step is to modify the shift count for the
-- big-endian case. Consider the following example in a byte:
-- xxxxxxxx bits of byte
-- vvvvvvvv bits of value
-- 33221100 little-endian numbering
-- 00112233 big-endian numbering
-- Here we have the case of 2-bit fields
-- For the little-endian case, we already have the proper shift count
-- set, e.g. for element 2, the shift count is 2*2 = 4.
-- For the big endian case, we have to adjust the shift count, computing
-- it as (N - F) - Shift, where N is the number of bits in an element of
-- the array used to implement the packed array, F is the number of bits
-- in a source array element, and Shift is the count so far computed.
-- We also have to adjust if the storage order is reversed
if Bytes_Big_Endian xor Reverse_Storage_Order (Base_Type (Atyp)) then
Shift :=
Make_Op_Subtract (Loc,
Left_Opnd => Make_Integer_Literal (Loc, Osiz - Csiz),
Right_Opnd => Shift);
end if;
Set_Parent (Shift, N);
Set_Parent (Obj, N);
Analyze_And_Resolve (Obj, Otyp, Suppress => All_Checks);
Analyze_And_Resolve (Shift, Standard_Integer, Suppress => All_Checks);
-- Make sure final type of object is the appropriate packed type
Set_Etype (Obj, Otyp);
end Setup_Inline_Packed_Array_Reference;
end Exp_Pakd;
|
package Aliasing2 is
type Arr is Array (1..4) of Integer;
type Ptr is access all Integer;
A : Arr;
function F (P : Ptr) return Integer;
end Aliasing2;
|
-- Copyright 2016,2017 Steven Stewart-Gallus
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-- implied. See the License for the specific language governing
-- permissions and limitations under the License.
with Linted.Queue;
with Linted.Last_Chance;
package body Linted.Tests is
Len : constant := 20;
type Ix is mod Len + 2 with Default_Value => 0;
type Int is mod Len + 1 with Default_Value => 0;
function Is_Valid (X : Int) return Boolean is (True);
package My_Queue is new Queue (Int, Ix, Is_Valid);
package Second_Queue is new Queue (Int, Ix, Is_Valid);
task type Queuer;
task type Dequeuer;
Queuers : array (1 .. 4) of Queuer;
Dequeuers : array (1 .. 4) of Dequeuer;
task body Queuer is
begin
for II in 1 .. 20 loop
Second_Queue.Enqueue (20);
end loop;
end Queuer;
task body Dequeuer is
Val : Int;
begin
for II in 1 .. 20 loop
Second_Queue.Dequeue (Val);
pragma Assert (Val = 20);
end loop;
end Dequeuer;
procedure Run is
begin
for II in 1 .. Int (Len) loop
My_Queue.Enqueue (II);
end loop;
for II in 1 .. Int (Len) loop
declare
Current : Int;
begin
My_Queue.Dequeue (Current);
if Current /= II then
raise Program_Error with Int'Image (Current) & " /= " & Int'Image (II);
end if;
end;
end loop;
end Run;
end Linted.Tests;
|
with
gel.World,
gel.Camera,
gel.Window;
package gel.Applet.gui_world
--
-- Provides a gel applet configured with a single window and a single GUI world.
--
is
type Item is new gel.Applet.item with private;
type View is access all Item'Class;
package Forge
is
function new_Applet (Name : in String;
use_Window : in gel.Window.view;
space_Kind : in physics.space_Kind) return gel.Applet.gui_world.view;
end Forge;
procedure free (Self : in out View);
gui_world_Id : constant world_Id := 1;
gui_camera_Id : constant camera_Id := 1;
function gui_World (Self : in Item) return gel.World .view;
function gui_Camera (Self : in Item) return gel.Camera.view;
private
type Item is new gel.Applet.item with
record
null;
end record;
end gel.Applet.gui_world;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.