content stringlengths 23 1.05M |
|---|
with Ada.Text_IO; use Ada.Text_IO;
with Test_Solution; use Test_Solution;
with Ada.Containers.Vectors;
with Ada.Strings.Unbounded;
with Problem_1;
with Problem_2;
with Problem_3;
with Problem_4;
with Problem_5;
with Problem_6;
with Problem_7;
with Problem_8;
with Problem_9;
with Problem_10;
with Problem_11;
with Problem_12;
with Problem_13;
with Problem_14;
with Problem_15;
with Problem_16;
with Problem_17;
with Problem_18;
with Problem_19;
with Problem_20;
with Problem_21;
procedure main is
use Ada.Strings.Unbounded;
package Suite is new Ada.Containers.Vectors( Index_Type => Natural,
Element_Type => Solution_Case);
Test_Suite : Suite.Vector;
Count : Integer := 1;
Failed : Integer := 0;
begin
Test_Suite.Append(Problem_1.Get_Solutions);
Test_Suite.Append(Problem_2.Get_Solutions);
Test_Suite.Append(Problem_3.Get_Solutions);
Test_Suite.Append(Problem_4.Get_Solutions);
Test_Suite.Append(Problem_5.Get_Solutions);
Test_Suite.Append(Problem_6.Get_Solutions);
Test_Suite.Append(Problem_7.Get_Solutions);
Test_Suite.Append(Problem_8.Get_Solutions);
Test_Suite.Append(Problem_9.Get_Solutions);
Test_Suite.Append(Problem_10.Get_Solutions);
Test_Suite.Append(Problem_11.Get_Solutions);
Test_Suite.Append(Problem_12.Get_Solutions);
Test_Suite.Append(Problem_13.Get_Solutions);
Test_Suite.Append(Problem_14.Get_Solutions);
Test_Suite.Append(Problem_15.Get_Solutions);
Test_Suite.Append(Problem_16.Get_Solutions);
Test_Suite.Append(Problem_17.Get_Solutions);
Test_Suite.Append(Problem_18.Get_Solutions);
Test_Suite.Append(Problem_19.Get_Solutions);
Test_Suite.Append(Problem_20.Get_Solutions);
Test_Suite.Append(Problem_21.Get_Solutions);
for C of Test_Suite loop
Put_Line("Running test case: " & To_String(C.Name) );
Count := 1;
for T of C.Tests loop
Put("Running Test" & Integer'Image(Count) & " :");
declare
begin
T.all;
Put(" Passed");
exception
when Assertion_Error =>
Failed := Failed + 1;
Put(" Failed");
end;
New_Line;
Count := Count + 1;
end loop;
end loop;
New_Line;
Put_Line("Failed" & Integer'Image(Failed) & " Tests");
end main;
|
--
-- 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.
--
-----------------------------------------------------------------------------
-- Principal data structures for the LEMON parser generator.
-- Cherrylime
-- Lime body
-- Ada Lemon binding
--
with Ada.Strings.Unbounded;
with Ada.Containers.Vectors;
limited with Symbols;
with Rule_Lists;
with Report_Parsers;
with States;
with Types;
with Action_Tables;
package Sessions is
subtype UString is Ada.Strings.Unbounded.Unbounded_String;
subtype Symbol_Record is Symbols.Symbol_Record;
subtype Symbol_Index is Types.Symbol_Index;
subtype Action_Value is Action_Tables.Action_Value;
subtype Offset_Type is Types.Offset_Type;
Null_UString : UString
renames Ada.Strings.Unbounded.Null_Unbounded_String;
-- Symbols (terminals and nonterminals) of the grammar are stored
-- in the following:
-- Name of the symbol
-- Index number for this symbol
-- Symbols are all either TERMINALS or NTs
-- Linked list of rules of this (if an NT)
-- fallback token in case this token doesn't parse
-- Precedence if defined (-1 otherwise)
-- Associativity if precedence is defined
-- First-set for all rules of this symbol
-- True if NT and can generate an empty string
-- Number of times used
-- Code which executes whenever this symbol is
-- popped from the stack during error processing
-- Line number for start of destructor. Set to
-- -1 for duplicate destructors.
-- The data type of information held by this
-- object. Only used if type==NONTERMINAL
-- The data type number. In the parser, the value
-- stack is a union. The .yy%d element of this
-- union is the correct data type for this object
-- True if this symbol ever carries content - if
-- it is ever more than just syntax
-- The state vector for the entire parser generator is recorded as
-- follows. (LEMON uses no global variables and makes little use of
-- static variables. Fields in the following structure can be thought
-- of as begin global variables in the program.)
type Parser_Names_Record is
record
Name : aliased UString := Null_UString;
-- Name of the generated parser
ARG2 : aliased UString := Null_UString;
-- Declaration of the 3th argument to parser
CTX2 : aliased UString := Null_UString;
-- Declaration of 2nd argument to constructor
Token_Type : aliased UString := Null_UString;
-- Type of terminal symbols in the parser stack
Var_Type : aliased UString := Null_UString;
-- The default type of non-terminal symbols
Start : aliased UString := Null_UString;
-- Name of the start symbol for the grammar
Stack_Size : aliased UString := Null_UString;
-- Size of the parser stack
Include : aliased UString := Null_UString;
-- Code to put at the start of the C file
Error : aliased UString := Null_UString;
-- Code to execute when an error is seen
Overflow : aliased UString := Null_UString;
-- Code to execute on a stack overflow
Failure : aliased UString := Null_UString;
-- Code to execute on parser failure
C_Accept : aliased UString := Null_UString;
-- Code to execute when the parser excepts
Extra_Code : aliased UString := Null_UString;
-- Code appended to the generated file
Token_Dest : aliased UString := Null_UString;
-- Code to execute to destroy token data
Var_Dest : aliased UString := Null_UString;
-- Code for the default non-terminal destructor
Token_Prefix : aliased UString := Null_UString;
-- A prefix added to token names in the .h file
end record;
Parser_Names : aliased Parser_Names_Record :=
(others => Null_UString);
subtype State_Index is Types.Symbol_Index;
package State_Vectors is
new Ada.Containers.Vectors (Index_Type => State_Index,
Element_Type => States.State_Access,
"=" => States."=");
type Session_Type is
record
Sorted : State_Vectors.Vector;
-- Table of states sorted by state number
Rule : Rule_Lists.Lists.List;
-- List of all rules
Start_Rule : Rule_Lists.Lists.Cursor;
-- First rule
-- Number of states in Sorted
Num_X_State : State_Index;
-- nstate with tail degenerate states removed
Num_Rule_With_Action : Integer;
-- Number of rules with actions
Num_Symbol : Symbol_Index;
-- Number of terminal and nonterminal symbols
Num_Terminal : Symbol_Index;
-- Number of terminal symbols
Min_Shift_Reduce : Action_Value;
-- Minimum shift-reduce action value
Err_Action : Action_Value;
-- Error action value
Acc_Action : Action_Value;
-- Accept action value
No_Action : Action_Value;
-- No-op action value
Min_Reduce : Action_Value;
-- Minimum reduce action
Max_Action : Action_Value;
-- Maximum action value of any kind
Symbols2 : Integer;
-- XXX delme -- Sorted array of pointers to symbols
Error_Cnt : Integer;
-- Number of errors
Error_Symbol : access Symbol_Record;
-- The error symbol
Wildcard : access Symbol_Record;
-- Token that matches anything
Names : access Parser_Names_Record;
File_Name : UString;
-- Name of the input file
Out_Name : UString;
-- Name of the current output file
-- Token_Prefix : aliased chars_ptr;
-- A prefix added to token names in the .h file
Num_Conflict : Integer;
-- Number of parsing conflicts
Num_Action_Tab : Integer;
-- Number of entries in the yy_action[] table
Num_Lookahead_Tab : Integer;
-- Number of entries in yy_lookahead[]
Table_Size : Integer;
-- Total table size of all tables in bytes
Basis_Flag : Boolean;
-- Print only basis configurations
Has_Fallback : Boolean;
-- True if any %fallback is seen in the grammar
No_Linenos_Flag : Boolean;
-- True if #line statements should not be printed
Argv0 : UString;
-- Name of the program
Parser : Report_Parsers.Context_Access;
end record;
function Clean_Session return Session_Type;
No_Offset : aliased constant Offset_Type := Offset_Type'First;
procedure Create_Sorted_States (Session : in out Session_Type);
--
end Sessions;
|
-- Copyright 2020 Free Software Foundation, Inc.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
package Pck is
type Rec_Type (C : Character := 'd') is record
case C is
when Character'First => X_First : Integer;
when Character'Val (127) => X_127 : Integer;
when Character'Val (128) => X_128 : Integer;
when Character'Last => X_Last : Integer;
when others => null;
end case;
end record;
type Second_Type (I : Integer) is record
One: Integer;
case I is
when -5 .. 5 =>
X : Integer;
when others =>
Y : Integer;
end case;
end record;
type Nested_And_Variable (One, Two: Integer) is record
Str : String (1 .. One);
case One is
when 0 =>
null;
when others =>
OneValue : Integer;
Str2 : String (1 .. Two);
case Two is
when 0 =>
null;
when others =>
TwoValue : Integer;
end case;
end case;
end record;
end Pck;
|
-- Abstract :
--
-- Output Ada code implementing the grammar defined by input
-- parameters, and a parser for that grammar. The grammar parser
-- actions must be Ada.
--
-- Copyright (C) 2017 - 2020 Free Software Foundation, Inc.
--
-- The WisiToken package 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.
pragma License (Modified_GPL);
with Ada.Strings.Fixed;
with Ada.Text_IO; use Ada.Text_IO;
with GNAT.Regexp;
with WisiToken.BNF.Generate_Packrat;
with WisiToken.BNF.Generate_Utils;
with WisiToken.BNF.Output_Ada_Common; use WisiToken.BNF.Output_Ada_Common;
with WisiToken.Generate.Packrat;
with WisiToken_Grammar_Runtime;
procedure WisiToken.BNF.Output_Ada
(Input_Data : in WisiToken_Grammar_Runtime.User_Data_Type;
Output_File_Name_Root : in String;
Generate_Data : aliased in WisiToken.BNF.Generate_Utils.Generate_Data;
Packrat_Data : in WisiToken.Generate.Packrat.Data;
Tuple : in Generate_Tuple;
Test_Main : in Boolean;
Multiple_Tuples : in Boolean)
is
Common_Data : Output_Ada_Common.Common_Data := WisiToken.BNF.Output_Ada_Common.Initialize
(Input_Data, Tuple, Output_File_Name_Root, Check_Interface => False);
Gen_Alg_Name : constant String :=
(if Test_Main or Multiple_Tuples
then "_" & Generate_Algorithm_Image (Common_Data.Generate_Algorithm).all
else "");
function Symbol_Regexp (Item : in String) return String
is begin
-- Return a regular expression string that matches Item as a symbol;
-- it must be preceded and followed by non-symbol characters.
--
-- GNAT.Regexp does not have a char for 'end of string', so we hope
-- that doesn't occur. Sigh.
return ".*[ (\.]" & Item & "[ );\.,].*";
end Symbol_Regexp;
procedure Create_Ada_Actions_Body
(Action_Names : not null access WisiToken.Names_Array_Array;
Check_Names : not null access WisiToken.Names_Array_Array;
Label_Count : in Ada.Containers.Count_Type;
Package_Name : in String)
is
use all type Ada.Containers.Count_Type;
use GNAT.Regexp;
use Generate_Utils;
use WisiToken.Generate;
File_Name : constant String := Output_File_Name_Root & "_actions.adb";
User_Data_Regexp : constant Regexp := Compile (Symbol_Regexp ("User_Data"), Case_Sensitive => False);
Tree_Regexp : constant Regexp := Compile (Symbol_Regexp ("Tree"), Case_Sensitive => False);
Nonterm_Regexp : constant Regexp := Compile (Symbol_Regexp ("Nonterm"), Case_Sensitive => False);
Tokens_Regexp : constant Regexp := Compile (Symbol_Regexp ("Tokens"), Case_Sensitive => False);
Body_File : File_Type;
begin
Create (Body_File, Out_File, File_Name);
Set_Output (Body_File);
Indent := 1;
Put_File_Header (Ada_Comment, Use_Tuple => True, Tuple => Tuple);
Put_Raw_Code (Ada_Comment, Input_Data.Raw_Code (Copyright_License));
Put_Raw_Code (Ada_Comment, Input_Data.Raw_Code (Actions_Body_Context));
New_Line;
if Label_Count > 0 then
Put_Line ("with SAL;");
end if;
Put_Line ("package body " & Package_Name & " is");
Indent := Indent + 3;
New_Line;
if Input_Data.Check_Count > 0 then
Indent_Line ("use WisiToken.Semantic_Checks;");
New_Line;
end if;
Put_Raw_Code (Ada_Comment, Input_Data.Raw_Code (Actions_Body_Pre));
-- generate Action and Check subprograms.
for Rule of Input_Data.Tokens.Rules loop
-- No need for a Token_Cursor here, since we only need the
-- nonterminals.
declare
use Ada.Strings.Unbounded;
LHS_ID : constant WisiToken.Token_ID := Find_Token_ID (Generate_Data, -Rule.Left_Hand_Side);
RHS_Index : Integer := 0;
function Is_Elisp (Action : in Unbounded_String) return Boolean
is begin
return Length (Action) >= 6 and then
(Slice (Action, 1, 6) = "(progn" or
Slice (Action, 1, 5) = "wisi-");
end Is_Elisp;
procedure Put_Labels (RHS : in RHS_Type; Line : in String)
is
Output : array (Rule.Labels.First_Index .. Rule.Labels.Last_Index) of Boolean := (others => False);
procedure Update_Output (Label : in String)
is begin
for I in Rule.Labels.First_Index .. Rule.Labels.Last_Index loop
if Label = Rule.Labels (I) then
Output (I) := True;
end if;
end loop;
end Update_Output;
begin
for I in RHS.Tokens.First_Index .. RHS.Tokens.Last_Index loop
if Length (RHS.Tokens (I).Label) > 0 then
declare
Label : constant String := -RHS.Tokens (I).Label;
begin
if Match (Line, Compile (Symbol_Regexp (Label), Case_Sensitive => False)) then
Indent_Line
(Label & " : constant SAL.Peek_Type :=" & SAL.Peek_Type'Image (I) & ";");
Update_Output (Label);
end if;
end;
end if;
end loop;
for I in Rule.Labels.First_Index .. Rule.Labels.Last_Index loop
if not Output (I) and
Match (Line, Compile (Symbol_Regexp (-Rule.Labels (I)), Case_Sensitive => False))
then
Indent_Line (-Rule.Labels (I) & " : constant SAL.Base_Peek_Type := SAL.Base_Peek_Type'First;");
end if;
end loop;
end Put_Labels;
begin
for RHS of Rule.Right_Hand_Sides loop
if Length (RHS.Action) > 0 and then not Is_Elisp (RHS.Action) then
declare
Line : constant String := -RHS.Action;
-- Actually multiple lines; we assume the formatting is adequate.
Name : constant String := Action_Names (LHS_ID)(RHS_Index).all;
Unref_User_Data : Boolean := True;
Unref_Tree : Boolean := True;
Unref_Nonterm : Boolean := True;
Unref_Tokens : Boolean := True;
Need_Comma : Boolean := False;
procedure Check_Unref (Line : in String)
is begin
if Match (Line, User_Data_Regexp) then
Unref_User_Data := False;
end if;
if Match (Line, Tree_Regexp) then
Unref_Tree := False;
end if;
if Match (Line, Nonterm_Regexp) then
Unref_Nonterm := False;
end if;
if Match (Line, Tokens_Regexp) then
Unref_Tokens := False;
end if;
end Check_Unref;
begin
Check_Unref (Line);
Indent_Line ("procedure " & Name);
Indent_Line (" (User_Data : in out WisiToken.Syntax_Trees.User_Data_Type'Class;");
Indent_Line (" Tree : in out WisiToken.Syntax_Trees.Tree;");
Indent_Line (" Nonterm : in WisiToken.Valid_Node_Index;");
Indent_Line (" Tokens : in WisiToken.Valid_Node_Index_Array)");
Indent_Line ("is");
Indent := Indent + 3;
if Unref_User_Data or Unref_Tree or Unref_Nonterm or Unref_Tokens then
Indent_Start ("pragma Unreferenced (");
if Unref_User_Data then
Put ("User_Data");
Need_Comma := True;
end if;
if Unref_Tree then
Put ((if Need_Comma then ", " else "") & "Tree");
Need_Comma := True;
end if;
if Unref_Nonterm then
Put ((if Need_Comma then ", " else "") & "Nonterm");
Need_Comma := True;
end if;
if Unref_Tokens then
Put ((if Need_Comma then ", " else "") & "Tokens");
Need_Comma := True;
end if;
Put_Line (");");
end if;
Put_Labels (RHS, Line);
Indent := Indent - 3;
Indent_Line ("begin");
Indent := Indent + 3;
Indent_Line (Line);
Indent := Indent - 3;
Indent_Line ("end " & Name & ";");
New_Line;
end;
end if;
if Length (RHS.Check) > 0 and then not Is_Elisp (RHS.Check) then
declare
use Ada.Strings.Fixed;
Line : constant String := -RHS.Check;
Name : constant String := Check_Names (LHS_ID)(RHS_Index).all;
Unref_Lexer : constant Boolean := 0 = Index (Line, "Lexer");
Unref_Nonterm : constant Boolean := 0 = Index (Line, "Nonterm");
Unref_Tokens : constant Boolean := 0 = Index (Line, "Tokens");
Unref_Recover : constant Boolean := 0 = Index (Line, "Recover_Active");
Need_Comma : Boolean := False;
begin
Indent_Line ("function " & Name);
Indent_Line (" (Lexer : access constant WisiToken.Lexer.Instance'Class;");
Indent_Line (" Nonterm : in out WisiToken.Recover_Token;");
Indent_Line (" Tokens : in WisiToken.Recover_Token_Array;");
Indent_Line (" Recover_Active : in Boolean)");
Indent_Line (" return WisiToken.Semantic_Checks.Check_Status");
Indent_Line ("is");
Indent := Indent + 3;
if Unref_Lexer or Unref_Nonterm or Unref_Tokens or Unref_Recover then
Indent_Start ("pragma Unreferenced (");
if Unref_Lexer then
Put ("Lexer");
Need_Comma := True;
end if;
if Unref_Nonterm then
Put ((if Need_Comma then ", " else "") & "Nonterm");
Need_Comma := True;
end if;
if Unref_Tokens then
Put ((if Need_Comma then ", " else "") & "Tokens");
Need_Comma := True;
end if;
if Unref_Recover then
Put ((if Need_Comma then ", " else "") & "Recover_Active");
Need_Comma := True;
end if;
Put_Line (");");
end if;
Put_Labels (RHS, Line);
Indent := Indent - 3;
Indent_Line ("begin");
Indent := Indent + 3;
Indent_Line (Line);
Indent := Indent - 3;
Indent_Line ("end " & Name & ";");
New_Line;
end;
end if;
RHS_Index := RHS_Index + 1;
end loop;
end;
end loop;
Put_Raw_Code (Ada_Comment, Input_Data.Raw_Code (Actions_Body_Post));
Put_Line ("end " & Package_Name & ";");
Close (Body_File);
Set_Output (Standard_Output);
end Create_Ada_Actions_Body;
procedure Create_Ada_Main_Body
(Actions_Package_Name : in String;
Main_Package_Name : in String)
is
use WisiToken.Generate;
File_Name : constant String := To_Lower (Main_Package_Name) & ".adb";
re2c_Package_Name : constant String := -Common_Data.Lower_File_Name_Root & "_re2c_c";
Body_File : File_Type;
begin
Create (Body_File, Out_File, File_Name);
Set_Output (Body_File);
Indent := 1;
Put_File_Header (Ada_Comment, Use_Tuple => True, Tuple => Tuple);
Put_Raw_Code (Ada_Comment, Input_Data.Raw_Code (Copyright_License));
New_Line;
if (case Common_Data.Generate_Algorithm is
when LR_Generate_Algorithm => Input_Data.Action_Count > 0 or Input_Data.Check_Count > 0,
when Packrat_Generate_Algorithm | External => Input_Data.Action_Count > 0)
then
Put_Line ("with " & Actions_Package_Name & "; use " & Actions_Package_Name & ";");
end if;
case Common_Data.Lexer is
when None | Elisp_Lexer =>
null;
when re2c_Lexer =>
Put_Line ("with WisiToken.Lexer.re2c;");
Put_Line ("with " & re2c_Package_Name & ";");
end case;
case Common_Data.Generate_Algorithm is
when LR_Generate_Algorithm =>
null;
when Packrat_Gen =>
Put_Line ("with WisiToken.Parse.Packrat.Generated;");
when Packrat_Proc =>
Put_Line ("with WisiToken.Parse.Packrat.Procedural;");
Put_Line ("with WisiToken.Productions;");
when External =>
null;
end case;
Put_Line ("package body " & Main_Package_Name & " is");
Indent := Indent + 3;
New_Line;
case Common_Data.Lexer is
when None | Elisp_Lexer =>
null;
when re2c_Lexer =>
Indent_Line ("package Lexer is new WisiToken.Lexer.re2c");
Indent_Line (" (" & re2c_Package_Name & ".New_Lexer,");
Indent_Line (" " & re2c_Package_Name & ".Free_Lexer,");
Indent_Line (" " & re2c_Package_Name & ".Reset_Lexer,");
Indent_Line (" " & re2c_Package_Name & ".Next_Token);");
New_Line;
end case;
case Common_Data.Generate_Algorithm is
when LR_Generate_Algorithm =>
LR_Create_Create_Parser (Input_Data, Common_Data, Generate_Data);
when Packrat_Gen =>
WisiToken.BNF.Generate_Packrat (Packrat_Data, Generate_Data);
Packrat_Create_Create_Parser (Common_Data, Generate_Data, Packrat_Data);
when Packrat_Proc =>
Packrat_Create_Create_Parser (Common_Data, Generate_Data, Packrat_Data);
when External =>
External_Create_Create_Grammar (Generate_Data);
end case;
Put_Line ("end " & Main_Package_Name & ";");
Close (Body_File);
Set_Output (Standard_Output);
end Create_Ada_Main_Body;
procedure Create_Ada_Test_Main
(Actions_Package_Name : in String;
Main_Package_Name : in String)
is
use WisiToken.Generate;
Generic_Package_Name : constant String :=
(case Common_Data.Generate_Algorithm is
when LR_Generate_Algorithm =>
(if Input_Data.Language_Params.Error_Recover then
(if Common_Data.Text_Rep
then "Gen_LR_Text_Rep_Parser_Run"
else "Gen_LR_Parser_Run")
else
(if Common_Data.Text_Rep
then "Gen_LR_Text_Rep_Parser_No_Recover_Run"
else "Gen_LR_Parser_No_Recover_Run")),
when Packrat_Generate_Algorithm => "Gen_Packrat_Parser_Run",
when External => raise SAL.Programmer_Error);
Unit_Name : constant String := File_Name_To_Ada (Output_File_Name_Root) &
"_" & Generate_Algorithm'Image (Common_Data.Generate_Algorithm) & "_Run";
Default_Language_Runtime_Package : constant String := "WisiToken.Parse.LR.McKenzie_Recover." & File_Name_To_Ada
(Output_File_Name_Root);
File_Name : constant String := To_Lower (Unit_Name) & ".ads";
File : File_Type;
begin
Create (File, Out_File, File_Name);
Set_Output (File);
Indent := 1;
Put_File_Header (Ada_Comment, Use_Tuple => True, Tuple => Tuple);
-- no Copyright_License; just a test file
New_Line;
Put_Line ("with " & Generic_Package_Name & ";");
Put_Line ("with " & Actions_Package_Name & ";");
Put_Line ("with " & Main_Package_Name & ";");
if Input_Data.Language_Params.Error_Recover and
Input_Data.Language_Params.Use_Language_Runtime
then
declare
Pkg : constant String :=
(if -Input_Data.Language_Params.Language_Runtime_Name = ""
then Default_Language_Runtime_Package
else -Input_Data.Language_Params.Language_Runtime_Name);
begin
-- For language-specific names in actions, checks.
Put_Line ("with " & Pkg & ";");
Put_Line ("use " & Pkg & ";");
end;
end if;
Put_Line ("procedure " & Unit_Name & " is new " & Generic_Package_Name);
Put_Line (" (" & Actions_Package_Name & ".Descriptor,");
if Common_Data.Text_Rep then
Put_Line (" """ & Output_File_Name_Root & "_" &
To_Lower (Generate_Algorithm_Image (Tuple.Gen_Alg).all) &
"_parse_table.txt"",");
end if;
if Input_Data.Language_Params.Error_Recover then
if Input_Data.Language_Params.Use_Language_Runtime then
Put_Line ("Fixes'Access, Matching_Begin_Tokens'Access, String_ID_Set'Access,");
else
Put_Line ("null, null, null,");
end if;
end if;
Put_Line (Main_Package_Name & ".Create_Parser);");
Close (File);
Set_Output (Standard_Output);
end Create_Ada_Test_Main;
begin
case Common_Data.Lexer is
when None | re2c_Lexer =>
null;
when Elisp_Lexer =>
raise User_Error with WisiToken.Generate.Error_Message
(Input_Data.Grammar_Lexer.File_Name, 1, "Ada output language does not support " & Lexer_Image
(Common_Data.Lexer).all & " lexer");
end case;
case Tuple.Interface_Kind is
when None =>
null;
when Module | Process =>
raise User_Error with WisiToken.Generate.Error_Message
(Input_Data.Grammar_Lexer.File_Name, 1, "Ada output language does not support setting Interface");
end case;
declare
Main_Package_Name : constant String := File_Name_To_Ada (Output_File_Name_Root & Gen_Alg_Name) & "_Main";
Actions_Package_Name : constant String := File_Name_To_Ada (Output_File_Name_Root) & "_Actions";
begin
if Input_Data.Action_Count > 0 or Input_Data.Check_Count > 0 then
-- Some WisiToken tests have no actions or checks.
Create_Ada_Actions_Body
(Generate_Data.Action_Names, Generate_Data.Check_Names, Input_Data.Label_Count, Actions_Package_Name);
end if;
Create_Ada_Actions_Spec
(Output_File_Name_Root & "_actions.ads", Actions_Package_Name, Input_Data, Common_Data, Generate_Data);
if Tuple.Gen_Alg = External then
Create_External_Main_Spec (Main_Package_Name, Tuple, Input_Data);
Create_Ada_Main_Body (Actions_Package_Name, Main_Package_Name);
else
Create_Ada_Main_Body (Actions_Package_Name, Main_Package_Name);
Create_Ada_Main_Spec (To_Lower (Main_Package_Name) & ".ads", Main_Package_Name, Input_Data, Common_Data);
if Test_Main then
Create_Ada_Test_Main (Actions_Package_Name, Main_Package_Name);
end if;
end if;
end;
exception
when others =>
Set_Output (Standard_Output);
raise;
end WisiToken.BNF.Output_Ada;
|
pragma profile(Ravenscar);
pragma Partition_Elaboration_Policy (Sequential);
package account with SPARK_Mode
is
Num_Accounts : Natural := 0;
task type Account_Management is
end Account_Management;
-- tasks at package level
t1 : Account_Management;
t2 : Account_Management;
end Account;
|
-- This package has been generated automatically by GNATtest.
-- Do not edit any part of it, see GNATtest documentation for more details.
-- begin read only
with Gnattest_Generated;
package Crew.Inventory.Test_Data.Tests is
type Test is new GNATtest_Generated.GNATtest_Standard.Crew.Inventory
.Test_Data
.Test with
null record;
procedure Test_UpdateInventory_5fa756_83591c(Gnattest_T: in out Test);
-- crew-inventory.ads:41:4:UpdateInventory:Test_UpdateInventory
procedure Test_FreeInventory_df8fe5_1b9261(Gnattest_T: in out Test);
-- crew-inventory.ads:62:4:FreeInventory:Test_FreeInventory
procedure Test_TakeOffItem_a8b09e_af73e9(Gnattest_T: in out Test);
-- crew-inventory.ads:76:4:TakeOffItem:Test_TakeOffItem
procedure Test_ItemIsUsed_9a8ce5_329a6e(Gnattest_T: in out Test);
-- crew-inventory.ads:90:4:ItemIsUsed:Test_ItemIsUsed
procedure Test_FindTools_9ef8ba_dbafa3(Gnattest_T: in out Test);
-- crew-inventory.ads:110:4:FindTools:Test_FindTools
end Crew.Inventory.Test_Data.Tests;
-- end read only
|
With
System.Address_Image,
Ada.Strings.Fixed,
Ada.Strings.Unbounded;
Separate(Risi_Script.Types.Implementation)
Package Body Image_Operations is
-------------------------
-- UTILITY FUNCTIONS --
-------------------------
Function Trim( S : String ) return String is
Use Ada.Strings.Fixed, Ada.Strings;
begin
Return Trim(Side => Left, Source => S);
end Trim;
Function Trim( S : String ) return Ada.Strings.Unbounded.Unbounded_String is
Use Ada.Strings.Unbounded;
begin
Return To_Unbounded_String( Trim(S) );
end Trim;
----------------------------
-- IMAGE IMPLEMENTATIONS --
----------------------------
Function Static_Dispatch_Image( Elem : Representation ) return String is
(case Get_Enumeration(Elem) is
when RT_Integer => Image(Elem.Integer_Value),
when RT_Array => Image(Elem.Array_Value),
when RT_Hash => Image(Elem.Hash_Value),
when RT_String => Image(Elem.String_Value),
when RT_Real => Image(Elem.Real_Value),
when RT_Pointer => Image(Elem.Pointer_Value),
when RT_Reference => Image_Operations.Image(Elem.Reference_Value),
when RT_Fixed => Image(Elem.Fixed_Value),
when RT_Boolean => Image(Elem.Boolean_value),
when RT_Func => Image(Elem.Func_Value)
);
Function Image(Item : Integer_Type) return String is
( Trim( Integer_Type'Image(Item) ) );
Function Image(Item : Array_Type) return String is
Use Ada.Strings.Unbounded, List;
Working : Unbounded_String;
begin
for E in Item.Iterate loop
declare
Key : constant Natural := To_Index( E );
Last : constant Boolean := Key = Item.Last_Index;
Elem : Representation renames Element(E);
Item : constant string := Static_Dispatch_Image( Elem );
begin
Append(
Source => Working,
New_Item => Item & (if not Last then ", " else "")
);
end;
end loop;
return To_String( Working );
end Image;
Function Image(Item : Hash_Type) return String is
Use Ada.Strings.Unbounded, Hash;
Working : Unbounded_String;
begin
for E in Item.Iterate loop
declare
Key : constant String := '"' & Hash.Key( E ) & '"';
Last : constant Boolean := E = Item.Last;
Elem : Representation renames Element(E);
Item : constant string :=
(case Get_Enumeration(Elem) is
when RT_Integer => Image(Elem.Integer_Value),
when RT_Array => Image(Elem.Array_Value),
when RT_Hash => Image(Elem.Hash_Value),
when RT_String => Image(Elem.String_Value),
when RT_Real => Image(Elem.Real_Value),
when RT_Pointer => Image(Elem.Pointer_Value),
when RT_Reference => Image_Operations.Image(Elem.Reference_Value),
when RT_Fixed => Image(Elem.Fixed_Value),
when RT_Boolean => Image(Elem.Boolean_value),
when RT_Func => Image(Elem.Func_Value)
);
begin
Append(
Source => Working,
New_Item => Key & " => " &
Item & (if not Last then ", " else "")
);
end;
end loop;
return To_String( Working );
end Image;
Function Image(Item : String_Type) return String
renames Ada.Strings.Unbounded.To_String;
Function Image(Item : Real_Type) return String is
( Trim( Real_Type'Image(Item) ) );
Function Image(Item : Pointer_Type) return String is
( System.Address_Image( System.Address(Item) ) );
Function Image(Item : Fixed_Type) return String is
( Trim( Fixed_Type'Image(Item) ) );
Function Image(Item : Boolean_Type) return String is
( Boolean_Type'Image(Item) );
Function Image(Item : Func_Type) return String is ("");
Function Image(Item : Reference_Type ) return String is
(case Get_Enumeration(Item) is
when RT_Integer => Image( Item.Integer_Value ),
when RT_Array => Image( Item.Array_Value ),
when RT_Hash => Image( Item.Hash_Value ),
when RT_String => Image( Item.String_Value ),
when RT_Real => Image( Item.Real_Value ),
when RT_Pointer => Image( Item.Pointer_Value ),
when RT_Reference => Types.Implementation.Image( Item.Reference_Value ),
when RT_Fixed => Image( Item.Fixed_Value ),
when RT_Boolean => Image( Item.Boolean_Value ),
when RT_Func => Image( Item.Func_Value )
);
End Image_Operations;
|
-- { dg-do compile }
with gen_interface_p;
package gen_interface is
type T is interface;
procedure P (Thing: T) is abstract;
package NG is new gen_interface_p (T, P);
end;
|
pragma License (Unrestricted);
-- extended unit
with Ada.IO_Exceptions;
with Ada.Streams;
private with Ada.Finalization;
private with System.Native_Environment_Encoding;
package Ada.Environment_Encoding is
-- Platform-depended text encoding.
pragma Preelaborate;
-- encoding identifier
type Encoding_Id is private;
function Image (Encoding : Encoding_Id) return String;
pragma Inline (Image); -- renamed
function Default_Substitute (Encoding : Encoding_Id)
return Streams.Stream_Element_Array;
pragma Inline (Default_Substitute); -- renamed
function Min_Size_In_Stream_Elements (Encoding : Encoding_Id)
return Streams.Stream_Element_Offset;
pragma Inline (Min_Size_In_Stream_Elements); -- renamed
UTF_8 : constant Encoding_Id;
UTF_16 : constant Encoding_Id;
UTF_32 : constant Encoding_Id;
function Current_Encoding return Encoding_Id;
pragma Inline (Current_Encoding); -- renamed
-- subsidiary types to converter
type Subsequence_Status_Type is (
Finished,
Success,
Overflow, -- the output buffer is not large enough
Illegal_Sequence, -- a input character could not be mapped to the output
Truncated); -- the input buffer is broken off at a multi-byte character
type Continuing_Status_Type is
new Subsequence_Status_Type range
Success ..
Subsequence_Status_Type'Last;
type Finishing_Status_Type is
new Subsequence_Status_Type range
Finished ..
Overflow;
type Status_Type is
new Subsequence_Status_Type range
Finished ..
Illegal_Sequence;
type Substituting_Status_Type is
new Status_Type range
Finished ..
Overflow;
subtype True_Only is Boolean range True .. True;
-- converter
type Converter is limited private;
-- subtype Open_Converter is Converter
-- with
-- Dynamic_Predicate => Is_Open (Converter),
-- Predicate_Failure => raise Status_Error;
function Is_Open (Object : Converter) return Boolean;
pragma Inline (Is_Open);
function Min_Size_In_From_Stream_Elements (
Object : Converter) -- Open_Converter
return Streams.Stream_Element_Offset;
pragma Inline (Min_Size_In_From_Stream_Elements);
function Substitute (
Object : Converter) -- Open_Converter
return Streams.Stream_Element_Array;
pragma Inline (Substitute);
procedure Set_Substitute (
Object : in out Converter; -- Open_Converter
Substitute : Streams.Stream_Element_Array);
-- convert subsequence
procedure Convert (
Object : Converter; -- Open_Converter
Item : Streams.Stream_Element_Array;
Last : out Streams.Stream_Element_Offset;
Out_Item : out Streams.Stream_Element_Array;
Out_Last : out Streams.Stream_Element_Offset;
Finish : Boolean;
Status : out Subsequence_Status_Type);
procedure Convert (
Object : Converter; -- Open_Converter
Item : Streams.Stream_Element_Array;
Last : out Streams.Stream_Element_Offset;
Out_Item : out Streams.Stream_Element_Array;
Out_Last : out Streams.Stream_Element_Offset;
Status : out Continuing_Status_Type);
procedure Convert (
Object : Converter; -- Open_Converter
Out_Item : out Streams.Stream_Element_Array;
Out_Last : out Streams.Stream_Element_Offset;
Finish : True_Only;
Status : out Finishing_Status_Type);
-- convert all character sequence
procedure Convert (
Object : Converter; -- Open_Converter
Item : Streams.Stream_Element_Array;
Last : out Streams.Stream_Element_Offset;
Out_Item : out Streams.Stream_Element_Array;
Out_Last : out Streams.Stream_Element_Offset;
Finish : True_Only;
Status : out Status_Type);
-- convert all character sequence with substitute
procedure Convert (
Object : Converter; -- Open_Converter
Item : Streams.Stream_Element_Array;
Last : out Streams.Stream_Element_Offset;
Out_Item : out Streams.Stream_Element_Array;
Out_Last : out Streams.Stream_Element_Offset;
Finish : True_Only;
Status : out Substituting_Status_Type);
-- exceptions
Status_Error : exception
renames IO_Exceptions.Status_Error;
Name_Error : exception
renames IO_Exceptions.Name_Error;
Use_Error : exception
renames IO_Exceptions.Use_Error;
private
-- max length of one multi-byte character
Max_Substitute_Length : constant :=
System.Native_Environment_Encoding.Max_Substitute_Length;
-- encoding identifier
type Encoding_Id is new System.Native_Environment_Encoding.Encoding_Id;
function Image (Encoding : Encoding_Id) return String
renames Get_Image;
function Default_Substitute (Encoding : Encoding_Id)
return Streams.Stream_Element_Array
renames Get_Default_Substitute;
function Min_Size_In_Stream_Elements (Encoding : Encoding_Id)
return Streams.Stream_Element_Offset
renames Get_Min_Size_In_Stream_Elements;
UTF_8 : constant Encoding_Id :=
Encoding_Id (System.Native_Environment_Encoding.UTF_8);
UTF_16 : constant Encoding_Id :=
Encoding_Id (System.Native_Environment_Encoding.UTF_16);
UTF_32 : constant Encoding_Id :=
Encoding_Id (System.Native_Environment_Encoding.UTF_32);
function Current_Encoding return Encoding_Id
renames Get_Current_Encoding;
-- converter
package Controlled is
type Converter is limited private;
function Reference (Object : Environment_Encoding.Converter)
return not null access System.Native_Environment_Encoding.Converter;
function Open (From, To : Encoding_Id)
return Environment_Encoding.Converter;
-- [gcc-7] strange error if this function is placed outside of
-- the package Controlled, and Disable_Controlled => True
private
type Converter is limited new Finalization.Limited_Controlled with record
Data : aliased System.Native_Environment_Encoding.Converter :=
(others => <>);
end record
with
Disable_Controlled =>
System.Native_Environment_Encoding.Disable_Controlled;
overriding procedure Finalize (Object : in out Converter);
end Controlled;
type Converter is new Controlled.Converter;
end Ada.Environment_Encoding;
|
with Ada.Unchecked_Deallocation;
package body BT is
procedure Free is new Ada.Unchecked_Deallocation (Trit_Array, Trit_Access);
-- Conversions
-- String to BT
function To_Balanced_Ternary (Str: String) return Balanced_Ternary is
J : Positive := 1;
Tmp : Trit_Access;
begin
Tmp := new Trit_Array (1..Str'Last);
for I in reverse Str'Range loop
case Str(I) is
when '+' => Tmp (J) := 1;
when '-' => Tmp (J) := -1;
when '0' => Tmp (J) := 0;
when others => raise Constraint_Error;
end case;
J := J + 1;
end loop;
return (Ada.Finalization.Controlled with Ref => Tmp);
end To_Balanced_Ternary;
-- Integer to BT
function To_Balanced_Ternary (Num: Integer) return Balanced_Ternary is
K : Integer := 0;
D : Integer;
Value : Integer := Num;
Tmp : Trit_Array(1..19); -- 19 trits is enough to contain
-- a 32 bits signed integer
begin
loop
D := (Value mod 3**(K+1))/3**K;
if D = 2 then D := -1; end if;
Value := Value - D*3**K;
K := K + 1;
Tmp(K) := Trit(D);
exit when Value = 0;
end loop;
return (Ada.Finalization.Controlled
with Ref => new Trit_Array'(Tmp(1..K)));
end To_Balanced_Ternary;
-- BT to Integer --
-- If the BT number is too large Ada will raise CONSTRAINT ERROR
function To_Integer (Num : Balanced_Ternary) return Integer is
Value : Integer := 0;
Pos : Integer := 1;
begin
for I in Num.Ref.all'Range loop
Value := Value + Integer(Num.Ref(I)) * Pos;
Pos := Pos * 3;
end loop;
return Value;
end To_Integer;
-- BT to String --
function To_String (Num : Balanced_Ternary) return String is
I : constant Integer := Num.Ref.all'Last;
Result : String (1..I);
begin
for J in Result'Range loop
case Num.Ref(I-J+1) is
when 0 => Result(J) := '0';
when -1 => Result(J) := '-';
when 1 => Result(J) := '+';
end case;
end loop;
return Result;
end To_String;
-- unary minus --
function "-" (Left : in Balanced_Ternary)
return Balanced_Ternary is
Result : constant Balanced_Ternary := Left;
begin
for I in Result.Ref.all'Range loop
Result.Ref(I) := - Result.Ref(I);
end loop;
return Result;
end "-";
-- addition --
Carry : Trit;
function Add (Left, Right : in Trit)
return Trit is
begin
if Left /= Right then
Carry := 0;
return Left + Right;
else
Carry := Left;
return -Right;
end if;
end Add;
pragma Inline (Add);
function "+" (Left, Right : in Trit_Array)
return Balanced_Ternary is
Max_Size : constant Integer :=
Integer'Max(Left'Last, Right'Last);
Tmp_Left, Tmp_Right : Trit_Array(1..Max_Size) := (others => 0);
Result : Trit_Array(1..Max_Size+1) := (others => 0);
begin
Tmp_Left (1..Left'Last) := Left;
Tmp_Right(1..Right'Last) := Right;
for I in Tmp_Left'Range loop
Result(I) := Add (Result(I), Tmp_Left(I));
Result(I+1) := Carry;
Result(I) := Add(Result(I), Tmp_Right(I));
Result(I+1) := Add(Result(I+1), Carry);
end loop;
-- remove trailing zeros
for I in reverse Result'Range loop
if Result(I) /= 0 then
return (Ada.Finalization.Controlled
with Ref => new Trit_Array'(Result(1..I)));
end if;
end loop;
return (Ada.Finalization.Controlled
with Ref => new Trit_Array'(1 => 0));
end "+";
function "+" (Left, Right : in Balanced_Ternary)
return Balanced_Ternary is
begin
return Left.Ref.all + Right.Ref.all;
end "+";
-- Subtraction
function "-" (Left, Right : in Balanced_Ternary)
return Balanced_Ternary is
begin
return Left + (-Right);
end "-";
-- multiplication
function "*" (Left, Right : in Balanced_Ternary)
return Balanced_Ternary is
A, B : Trit_Access;
Result : Balanced_Ternary;
begin
if Left.Ref.all'Length > Right.Ref.all'Length then
A := Right.Ref; B := Left.Ref;
else
B := Right.Ref; A := Left.Ref;
end if;
for I in A.all'Range loop
if A(I) /= 0 then
declare
Tmp_Result : Trit_Array (1..I+B.all'Length-1) := (others => 0);
begin
for J in B.all'Range loop
Tmp_Result(I+J-1) := B(J) * A(I);
end loop;
Result := Result.Ref.all + Tmp_Result;
end;
end if;
end loop;
return Result;
end "*";
procedure Adjust (Object : in out Balanced_Ternary) is
begin
Object.Ref := new Trit_Array'(Object.Ref.all);
end Adjust;
procedure Finalize (Object : in out Balanced_Ternary) is
begin
Free (Object.Ref);
end Finalize;
procedure Initialize (Object : in out Balanced_Ternary) is
begin
Object.Ref := new Trit_Array'(1 => 0);
end Initialize;
end BT;
|
-- Ada regular expression library
-- (c) Kristian Klomsten Skordal 2020-2021 <kristian.skordal@wafflemail.net>
-- Report bugs and issues on <https://github.com/skordal/ada-regex>
separate (Regex.Regular_Expressions) procedure Compile (Output : in out Regular_Expression) is
Start_State : constant State_Machine_State_Access := Create_State (Firstpos (Output.Syntax_Tree));
Unmarked_State : State_Machine_State_Access := null;
begin
Output.State_Machine_States.Append (Start_State);
Output.Start_State := Start_State;
Calculate_Followpos (Output.Syntax_Tree);
loop
Unmarked_State := null;
Find_Unmarked_State_Loop : for State of Output.State_Machine_States loop
if State.Marked = False then
Unmarked_State := State;
exit Find_Unmarked_State_Loop;
end if;
end loop Find_Unmarked_State_Loop;
exit when Unmarked_State = null;
-- Mark state:
Unmarked_State.Marked := True;
declare
package Input_Symbol_Sets is new Utilities.Sorted_Sets (Element_Type => Input_Symbol_Access,
"<" => Compare_Input_Symbols, "=" => Input_Symbol_Equals);
use Input_Symbol_Sets;
Input_Symbols : Sorted_Set := Empty_Set;
begin
-- Find all input symbols for this state and determine if it is an accepting state:
for Syntax_Node of Unmarked_State.Syntax_Tree_Nodes loop
if Syntax_Node.Node_Type = Single_Character then
Input_Symbols.Add (new Input_Symbol'(Symbol_Type => Single_Character, Char => Syntax_Node.Char));
elsif Syntax_Node.Node_Type = Any_Character then
Input_Symbols.Add (new Input_Symbol'(Symbol_Type => Any_Character));
elsif Syntax_Node.Node_Type = Acceptance then
Unmarked_State.Accepting := True;
Unmarked_State.Acceptance_Id := Syntax_Node.Acceptance_Id;
end if;
end loop;
-- Create transitions for each input symbol:
for Symbol of Input_Symbols loop
declare
use type Syntax_Tree_Node_Sets.Sorted_Set;
Target_State_Set : Syntax_Tree_Node_Sets.Sorted_Set := Syntax_Tree_Node_Sets.Empty_Set;
Target_State : State_Machine_State_Access := null;
begin
for Syntax_Node of Unmarked_State.Syntax_Tree_Nodes loop
if Symbol.Symbol_Type = Single_Character then
if Syntax_Node.Node_Type = Single_Character and then Syntax_Node.Char = Symbol.Char then
Target_State_Set.Add (Syntax_Node.Followpos);
end if;
elsif Symbol.Symbol_Type = Any_Character then
if Syntax_Node.Node_Type = Any_Character then
Target_State_Set.Add (Syntax_Node.Followpos);
end if;
end if;
end loop;
-- Find or create the target node:
Find_Target_State_Loop : for State of Output.State_Machine_States loop
if State.Syntax_Tree_Nodes = Target_State_Set then
Target_State := State;
exit Find_Target_State_Loop;
end if;
end loop Find_Target_State_Loop;
if Target_State = null then
Target_State := Create_State (Target_State_Set);
Output.State_Machine_States.Append (Target_State);
end if;
Unmarked_State.Transitions.Append (Create_Transition_On_Symbol (Clone (Symbol), Target_State));
end;
end loop;
end;
end loop;
end Compile;
|
-- using glibc provided by Linux From Scratch
private package iconv.Inside is
pragma Preelaborate;
function Version return String;
procedure Iterate (Process : not null access procedure (Name : in String));
end iconv.Inside;
|
-- Copyright (c) 2019 Maxim Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-- License-Filename: LICENSE
-------------------------------------------------------------
with Ada.Containers.Ordered_Sets;
with Ada.Containers.Vectors;
package body Coroutines.Timeouts is
type Timeout_Manager;
type Timeout_Manager_Access is access all Timeout_Manager'Class;
type Timeout_Event is new Event_Object with record
Time : Ada.Calendar.Time;
Context : Coroutines.Context;
Manager : Timeout_Manager_Access;
Ready : Boolean := False;
end record;
overriding procedure Activate (Self : in out Timeout_Event);
overriding function Ready (Self : Timeout_Event) return Boolean;
overriding procedure Deactivate (Self : in out Timeout_Event);
type Timeout_Event_Access is access all Timeout_Event;
use type Ada.Calendar.Time;
function Equal (Left, Right : Timeout_Event_Access) return Boolean is
(Left.Context = Right.Context and then Left.Time = Right.Time);
function Less (Left, Right : Timeout_Event_Access) return Boolean;
package Event_Sets is new Ada.Containers.Ordered_Sets
(Element_Type => Timeout_Event_Access,
"<" => Less,
"=" => Equal);
package Event_Vectors is new Ada.Containers.Vectors
(Index_Type => Positive,
Element_Type => Timeout_Event_Access);
type Timeout_Manager is new Coroutine_Manager with record
Active : Event_Sets.Set;
Unused : Event_Vectors.Vector;
Down : Coroutine_Manager_Access;
end record;
overriding procedure Get_Always_Ready_Event
(Self : in out Timeout_Manager;
Result : out Event_Id);
overriding procedure New_Round
(Self : in out Timeout_Manager;
Queue : in out Context_Vectors.Vector;
Timeout : Duration);
Manager : aliased Timeout_Manager;
--------------
-- Activate --
--------------
overriding procedure Activate (Self : in out Timeout_Event) is
begin
if not Self.Manager.Active.Contains (Self'Unchecked_Access) then
Self.Manager.Active.Insert (Self'Unchecked_Access);
end if;
end Activate;
----------------
-- Deactivate --
----------------
overriding procedure Deactivate (Self : in out Timeout_Event) is
begin
if Self.Manager.Active.Contains (Self'Unchecked_Access) then
Self.Manager.Active.Delete (Self'Unchecked_Access);
end if;
Self.Manager.Unused.Append (Self'Unchecked_Access);
end Deactivate;
----------------------------
-- Get_Always_Ready_Event --
----------------------------
procedure Get_Always_Ready_Event
(Self : in out Timeout_Manager;
Result : out Event_Id)
is
pragma Unreferenced (Self);
begin
Result := Timeout (0.0);
end Get_Always_Ready_Event;
----------------
-- Initialize --
----------------
procedure Initialize is
begin
Manager.Down := Coroutines.Manager;
Coroutines.Manager := Manager'Access;
end Initialize;
----------
-- Less --
----------
function Less (Left, Right : Timeout_Event_Access) return Boolean is
function Less_Context return Boolean;
------------------
-- Less_Context --
------------------
function Less_Context return Boolean is
use type System.Storage_Elements.Integer_Address;
L : constant System.Storage_Elements.Integer_Address :=
System.Storage_Elements.To_Integer (System.Address (Left.Context));
R : constant System.Storage_Elements.Integer_Address :=
System.Storage_Elements.To_Integer (System.Address (Right.Context));
begin
return L < R;
end Less_Context;
begin
return Left.Time < Right.Time
or else (Left.Time = Right.Time and then Less_Context);
end Less;
---------------
-- New_Round --
---------------
procedure New_Round
(Self : in out Timeout_Manager;
Queue : in out Context_Vectors.Vector;
Timeout : Duration)
is
Limit : Duration := Timeout;
First : Timeout_Event_Access;
Now : Ada.Calendar.Time;
begin
if not Self.Active.Is_Empty then
Now := Ada.Calendar.Clock;
while not Self.Active.Is_Empty loop
First := Self.Active.First_Element;
if First.Time <= Now then
Queue.Append (First.Context);
Self.Active.Delete_First;
Limit := 0.0;
else
Limit := Duration'Min (Timeout, First.Time - Now);
exit;
end if;
end loop;
end if;
if Self.Down /= null then
Self.Down.New_Round (Queue, Timeout => Limit);
elsif Queue.Is_Empty then
delay Limit;
end if;
end New_Round;
-----------
-- Ready --
-----------
overriding function Ready (Self : Timeout_Event) return Boolean is
begin
return Self.Ready;
end Ready;
-------------
-- Timeout --
-------------
function Timeout (Value : Duration) return Event_Id is
-- use type Ada.Calendar.Time;
begin
return Timeout (Ada.Calendar.Clock + Value);
end Timeout;
-------------
-- Timeout --
-------------
function Timeout (Value : Ada.Calendar.Time) return Event_Id is
Result : Timeout_Event_Access;
begin
if Manager.Unused.Is_Empty then
Result := new Timeout_Event;
else
Result := Manager.Unused.Last_Element;
Manager.Unused.Delete_Last;
end if;
Result.all := (Event_Object with
Time => Value,
Context => Current_Context,
Manager => Manager'Access,
Ready => False);
return Event_Id (Result);
end Timeout;
end Coroutines.Timeouts;
|
with Ada.Text_IO, Ada.Command_Line;
use Ada.Text_IO, Ada.Command_Line;
procedure powerset is
procedure print_subset (set : natural) is
-- each i'th binary digit of "set" indicates if the i'th integer belongs to "set" or not.
k : natural := set;
first : boolean := true;
begin
Put ("{");
for i in 1..Argument_Count loop
if k mod 2 = 1 then
if first then
first := false;
else
Put (",");
end if;
Put (Argument (i));
end if;
k := k / 2; -- we go to the next bit of "set"
end loop;
Put_Line("}");
end print_subset;
begin
for i in 0..2**Argument_Count-1 loop
print_subset (i);
end loop;
end powerset;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2022 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 STSW-IMG009, issue 3.5.1/UM2150 Rev 4.
-- --
-- COPYRIGHT(c) 2021 STMicroelectronics --
------------------------------------------------------------------------------
with HAL.I2C;
with HAL.Time;
package VL53L1X is
VL53L1X_Error : exception;
type VL53L1X_Ranging_Sensor
(Port : not null HAL.I2C.Any_I2C_Port;
Timing : not null HAL.Time.Any_Delays) is limited private;
function Is_Booted (This : VL53L1X_Ranging_Sensor) return Boolean;
type Boot_Status is (Ok, I2C_Error, I2C_Timeout, I2C_Busy);
procedure Boot_Device
(This : in out VL53L1X_Ranging_Sensor;
Loop_Interval_Ms : Positive := 10;
Status : out Boot_Status)
with
Pre => not Is_Booted (This),
Post => Is_Booted (This) = (Status = Ok);
procedure Set_Device_Address
(This : in out VL53L1X_Ranging_Sensor;
Addr : HAL.I2C.I2C_Address)
with
Pre => Is_Booted (This);
function Sensor_Initialized (This : VL53L1X_Ranging_Sensor) return Boolean;
procedure Sensor_Init
(This : in out VL53L1X_Ranging_Sensor)
with
Pre => Is_Booted (This),
Post => Sensor_Initialized (This);
type Distance_Mode is (Short, Long);
function Get_Distance_Mode
(This : in out VL53L1X_Ranging_Sensor) return Distance_Mode
with Pre => Sensor_Initialized (This);
procedure Set_Distance_Mode
(This : in out VL53L1X_Ranging_Sensor;
Mode : Distance_Mode := Long)
with Pre => Sensor_Initialized (This);
-- The defaulted mode is what the device initializes to.
subtype Milliseconds is Natural;
subtype Measurement_Budget is Milliseconds
with Predicate => Measurement_Budget in 15 | 20 | 33 | 50 | 100 | 200 | 500;
function Get_Inter_Measurement_Time
(This : in out VL53L1X_Ranging_Sensor) return Milliseconds
with Pre => Sensor_Initialized (This);
function Get_Measurement_Budget
(This : in out VL53L1X_Ranging_Sensor) return Measurement_Budget
with Pre => Sensor_Initialized (This);
procedure Set_Inter_Measurement_Time
(This : in out VL53L1X_Ranging_Sensor;
Interval : Milliseconds)
with Pre =>
Sensor_Initialized (This) and not Ranging_Started (This);
procedure Set_Measurement_Budget
(This : in out VL53L1X_Ranging_Sensor;
Budget : Measurement_Budget := 100)
with Pre =>
Sensor_Initialized (This) and not Ranging_Started (This);
function Ranging_Started (This : VL53L1X_Ranging_Sensor) return Boolean;
procedure Start_Ranging
(This : in out VL53L1X_Ranging_Sensor)
with
Pre => Sensor_Initialized (This),
Post => Ranging_Started (This);
procedure Wait_For_Measurement
(This : in out VL53L1X_Ranging_Sensor;
Loop_Interval_Ms : Positive := 10)
with
Pre => Ranging_Started (This);
function Is_Measurement_Ready
(This : in out VL53L1X_Ranging_Sensor) return Boolean
with
Pre => Ranging_Started (This);
type Ranging_Status is
(Ok, Sigma_Failure, Signal_Failure, Out_Of_Bounds, Wraparound);
-- Sigma_Failure: the repeatability or standard deviation of the
-- measurement is bad due to a decreasing signal-to-noise
-- ratio. Increasing the timing budget can improve the standard
-- deviation and avoid this problem.
--
-- Signal_Failure: the return signal is too weak to return a good
-- answer. The reason may be that the target is too far, or the
-- target is not reflective enough, or the target is too
-- small. Increasing the timing buget might help, but there may
-- simply be no target available.
--
-- Out_Of_Bounds: the sensor is ranging in a “non-appropriated”
-- zone and the measured result may be inconsistent. This status
-- is considered as a warning but, in general, it happens when a
-- target is at the maximum distance possible from the sensor,
-- i.e. around 5 m. However, this is only for very bright targets.
--
-- Wraparound: may occur when the target is very reflective and
-- the distance to the target is longer than the physical limited
-- distance measurable by the sensor. Such distances include
-- approximately 5 m when the senor is in Long distance mode and
-- approximately 1.3 m when the sensor is in Short distance
-- mode. Example: a traffic sign located at 6 m can be seen by the
-- sensor and returns a range of 1 m. This is due to “radar
-- aliasing”: if only an approximate distance is required, we may
-- add 6 m to the distance returned. However, that is a very
-- approximate estimation.
subtype Millimetres is Natural;
type Measurement (Status : Ranging_Status := Ok) is record
case Status is
when Ok => Distance : Millimetres;
when others => null;
end case;
end record;
function Get_Measurement
(This : in out VL53L1X_Ranging_Sensor) return Measurement
with
Pre => Ranging_Started (This);
procedure Clear_Interrupt
(This : in out VL53L1X_Ranging_Sensor)
with
Pre => Ranging_Started (This);
procedure Stop_Ranging
(This : in out VL53L1X_Ranging_Sensor)
with
Pre => Sensor_Initialized (This),
Post => not Ranging_Started (This);
private
type Sensor_State is (Unbooted, Booted, Initialized, Ranging);
type VL53L1X_Ranging_Sensor (Port : not null HAL.I2C.Any_I2C_Port;
Timing : not null HAL.Time.Any_Delays)
is limited record
State : Sensor_State := Unbooted;
-- Default address: can be changed by software
I2C_Address : HAL.I2C.I2C_Address := 16#52#;
end record;
function Is_Booted (This : VL53L1X_Ranging_Sensor) return Boolean
is (This.State >= Booted);
function Sensor_Initialized (This : VL53L1X_Ranging_Sensor) return Boolean
is (This.State >= Initialized);
function Ranging_Started (This : VL53L1X_Ranging_Sensor) return Boolean
is (This.State = Ranging);
end VL53L1X;
|
------------------------------------------------------------------------------
-- --
-- GNAT LIBRARY COMPONENTS --
-- --
-- G N A T . M O S T _ R E C E N T _ E X C E P T I O N --
-- --
-- S p e c --
-- --
-- Copyright (C) 2000-2021, AdaCore --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- --
-- --
-- --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This package provides routines for accessing the most recently raised
-- exception. This may be useful for certain logging activities. It may
-- also be useful for mimicking implementation dependent capabilities in
-- Ada 83 compilers, but see also GNAT.Current_Exceptions for this usage.
with Ada.Exceptions;
package GNAT.Most_Recent_Exception is
-----------------
-- Subprograms --
-----------------
function Occurrence
return Ada.Exceptions.Exception_Occurrence;
-- Returns the Exception_Occurrence for the most recently raised exception
-- in the current task. If no exception has been raised in the current task
-- prior to the call, returns Null_Occurrence.
function Occurrence_Access
return Ada.Exceptions.Exception_Occurrence_Access;
-- Similar to the above, but returns an access to the occurrence value.
-- This value is in a task specific location, and may be validly accessed
-- as long as no further exception is raised in the calling task.
-- Note: unlike the routines in GNAT.Current_Exception, these functions
-- access the most recently raised exception, regardless of where they
-- are called. Consider the following example:
-- exception
-- when Constraint_Error =>
-- begin
-- ...
-- exception
-- when Tasking_Error => ...
-- end;
--
-- -- Assuming a Tasking_Error was raised in the inner block,
-- -- a call to GNAT.Most_Recent_Exception.Occurrence will
-- -- return information about this Tasking_Error exception,
-- -- not about the Constraint_Error exception being handled
-- -- by the current handler code.
end GNAT.Most_Recent_Exception;
|
--******************************************************************************
--
-- package CALENDAR
--
--******************************************************************************
package CALENDAR is
type TIME is private;
subtype YEAR_NUMBER is INTEGER range 1901 .. 2099;
subtype MONTH_NUMBER is INTEGER range 1 .. 12;
subtype DAY_NUMBER is INTEGER range 1 .. 31;
subtype DAY_DURATION is DURATION range 0.0 .. 86_400.0;
function CLOCK return TIME;
function YEAR (DATE : TIME) return YEAR_NUMBER;
function MONTH (DATE : TIME) return MONTH_NUMBER;
function DAY (DATE : TIME) return DAY_NUMBER;
function SECONDS(DATE : TIME) return DAY_DURATION;
procedure SPLIT (DATE : in TIME;
YEAR : out YEAR_NUMBER;
MONTH : out MONTH_NUMBER;
DAY : out DAY_NUMBER;
SECONDS : out DAY_DURATION);
function TIME_OF(YEAR : YEAR_NUMBER;
MONTH : MONTH_NUMBER;
DAY : DAY_NUMBER;
SECONDS : DAY_DURATION := 0.0) return TIME;
function "+" (LEFT : TIME;
RIGHT : DURATION) return TIME;
function "+" (LEFT : DURATION;
RIGHT : TIME) return TIME;
function "-" (LEFT : TIME;
RIGHT : DURATION) return TIME;
function "-" (LEFT : TIME;
RIGHT : TIME) return DURATION;
function "<" (LEFT, RIGHT : TIME) return BOOLEAN;
function "<=" (LEFT, RIGHT : TIME) return BOOLEAN;
function ">" (LEFT, RIGHT : TIME) return BOOLEAN;
function ">=" (LEFT, RIGHT : TIME) return BOOLEAN;
TIME_ERROR : exception;
-- can be raised by TIME_OF, "+", AND "-"
private
-- implementation-dependent
type TIME is new integer;
end CALENDAR;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS --
-- --
-- I N T E R F A C E S . L E O N 3 . T I M E R S --
-- --
-- S p e c --
-- --
-- Copyright (C) 1999-2002 Universidad Politecnica de Madrid --
-- Copyright (C) 2003-2006 The European Space Agency --
-- Copyright (C) 2003-2017, AdaCore --
-- --
-- GNARL is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNARL is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- 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. --
-- --
-- The port of GNARL to bare board targets was initially developed by the --
-- Real-Time Systems Group at the Technical University of Madrid. --
-- --
------------------------------------------------------------------------------
pragma Restrictions (No_Elaboration_Code);
with System.BB.Board_Support;
with System.BB.Board_Parameters;
package Interfaces.Leon3.Timers is
pragma Preelaborate;
-- Pragma Suppress_Initialization (register_type) must be used in order
-- to keep eficiency. Otherwise, initialization procedures are always
-- generated for objects of packed boolean array types and of record types
-- that have components of these types.
----------------------------
-- Local type definitions --
----------------------------
type Scaler_10 is mod 2 ** 10;
for Scaler_10'Size use 10;
-- 10-bit scaler
---------------------
-- Timer Registers --
---------------------
Timer_Base : constant := System.BB.Board_Parameters.Timer_Base;
subtype Timer_Register is System.BB.Board_Support.Time.Timer_Interval;
pragma Suppress_Initialization (Timer_Register);
type Timer_Control_Register is record
Enable : Boolean;
-- 1 : enable counting
-- 0 : hold scaler (and counter) w
Reload_Counter : Boolean;
-- 1 : reload counter at zero and restart
-- 0 : stop counter at zero w
Load_Counter : Boolean;
-- 1 : load counter with preset value and start if enabled
-- 0 : no function w
Interrupt_Enable : Boolean;
-- 1 : timer underflow signals interrupt
-- 0 : interrupts disabled
Interrupt_Pending : Boolean;
-- 0 : interrupt not pending
-- 1 : interrupt pending, remains 1 until writing 0 to this bit
Chain : Boolean;
-- 0 : timer functions independently
-- 1 : decrementing timer N begins when timer (N - 1) underflows
Debug_Halt : Boolean;
-- State of timer when DF = 0, read only
-- 0 : active
-- 1 : frozen
Reserved : Reserved_25;
end record;
for Timer_Control_Register use record
Reserved at 0 range Bit31 .. Bit07;
Debug_Halt at 0 range Bit06 .. Bit06;
Chain at 0 range Bit05 .. Bit05;
Interrupt_Pending at 0 range Bit04 .. Bit04;
Interrupt_Enable at 0 range Bit03 .. Bit03;
Load_Counter at 0 range Bit02 .. Bit02; -- Load_Timer (LD) in AUM
Reload_Counter at 0 range Bit01 .. Bit01; -- Restart (RS) in AUM
Enable at 0 range Bit00 .. Bit00;
end record;
for Timer_Control_Register'Size use 32;
pragma Suppress_Initialization (Timer_Control_Register);
pragma Volatile_Full_Access (Timer_Control_Register);
-------------
-- Timer 1 --
-------------
Timer_1_Counter : Timer_Register;
Timer_1_Reload : Timer_Register;
Timer_1_Control : Timer_Control_Register;
for Timer_1_Counter'Address use System'To_Address (Timer_Base + 16#10#);
for Timer_1_Reload'Address use System'To_Address (Timer_Base + 16#14#);
for Timer_1_Control'Address use System'To_Address (Timer_Base + 16#18#);
-------------
-- Timer 2 --
-------------
Timer_2_Counter : Timer_Register;
Timer_2_Reload : Timer_Register;
Timer_2_Control : Timer_Control_Register;
for Timer_2_Counter'Address use System'To_Address (Timer_Base + 16#20#);
for Timer_2_Reload'Address use System'To_Address (Timer_Base + 16#24#);
for Timer_2_Control'Address use System'To_Address (Timer_Base + 16#28#);
-------------
-- Timer 3 --
-------------
Timer_3_Counter : Timer_Register;
Timer_3_Reload : Timer_Register;
Timer_3_Control : Timer_Control_Register;
for Timer_3_Counter'Address use System'To_Address (Timer_Base + 16#30#);
for Timer_3_Reload'Address use System'To_Address (Timer_Base + 16#34#);
for Timer_3_Control'Address use System'To_Address (Timer_Base + 16#38#);
-------------
-- Timer 4 --
-------------
Timer_4_Counter : Timer_Register;
Timer_4_Reload : Timer_Register;
Timer_4_Control : Timer_Control_Register;
for Timer_4_Counter'Address use System'To_Address (Timer_Base + 16#40#);
for Timer_4_Reload'Address use System'To_Address (Timer_Base + 16#44#);
for Timer_4_Control'Address use System'To_Address (Timer_Base + 16#48#);
--------------
-- Watchdog --
--------------
-- Watchdog_Register_Address is not available.
-- On LEON3, Timer_4 also drives the WDOGN watchdog signal
Watchdog_Register : Timer_Register renames Timer_4_Counter;
---------------
-- Prescaler --
---------------
type Prescaler_Register is record
Value : Scaler_10;
Reserved : Reserved_22;
end record;
for Prescaler_Register use record
Reserved at 0 range Bit31 .. Bit10;
Value at 0 range Bit09 .. Bit00;
end record;
for Prescaler_Register'Size use 32;
pragma Suppress_Initialization (Prescaler_Register);
pragma Volatile_Full_Access (Prescaler_Register);
Prescaler_Counter : Prescaler_Register;
for Prescaler_Counter'Address use System'To_Address (Timer_Base + 16#00#);
Prescaler_Reload : Prescaler_Register;
for Prescaler_Reload'Address use System'To_Address (Timer_Base + 16#04#);
end Interfaces.Leon3.Timers;
|
------------------------------------------------------------------------------
-- --
-- Ada User Repository Annex (AURA) --
-- ANNEXI-STRAYLINE Reference Implementation --
-- --
-- Command Line Interface --
-- --
-- ------------------------------------------------------------------------ --
-- --
-- Copyright (C) 2020-2021, ANNEXI-STRAYLINE Trans-Human Ltd. --
-- All rights reserved. --
-- --
-- Original Contributors: --
-- * Richard Wai (ANNEXI-STRAYLINE) --
-- --
-- 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 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 --
-- OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- This package is driven by the aura cli main program (aura.adb) specifically,
-- and is designed to be executed sequentially, in an apprpriate order
-- (determined by the main program). As such, it maintains a state via the
-- public "Command" object (below), as well as an internal Parameters object
-- (of type Parameters_Set)
with Build;
with Registrar.Library_Units;
package Scheduling is
Process_Failed: exception;
-- Raised during "normal", but ugly failures that are reported via work
-- reports, or involve explicit checks.
--
-- Generally speaking, if this exception occurs, it is not safe to save the
-- Registry or Configuration.
Build_Failed: exception;
-- Raised specifically when any unit fails to compile, bind, or link. Unlike
-- Process_Failed, this error implies that the Registry and Configuration
-- can (and should) be safely saved so that subsequent invokcations do not
-- need to recompile everything.
----------------
-- Parameters --
----------------
type Selected_Command is
(Build_Command,
Checkout_Command,
Clean_Command,
Compile_Command,
Help_Command,
Library_Command,
Run_Command,
Systemize_Command);
Command: Selected_Command := Checkout_Command;
-- Set by Initialize_Parameters;
procedure Initialize_Parameters;
-- Loads the previous set of parameters (if any), and then applies and
-- validates the parameters passed in.
--
-- Additionally checks the correctness of the specified
-- options/configuration for relevent commands.
--
-- If the parameters are not valid, a message explaining why is output,
-- and Process_Failed is raised, otherwise Command is set to the selected
-- command
--
-- Initialize_Parameters sets a variety of global variables in the
-- Scheduling and UI_Primitives packages, and must be invoked before
-- executing any other subprograms in this package
---------------
-- Processes --
---------------
procedure Clean;
-- Removes all state from the project.
-- 1. Removes the .aura subdirectory, containing all saved state (config and
-- last-run
-- 2. Removes the aura-build subdirectory
procedure Enter_Root;
-- Enters all units in the root directory
procedure Initialize_Repositories;
procedure Add_Explicit_Checkouts;
-- Enters "Requested" subsystems into the Registrar if they are not already
-- registered
--
-- This should be called after Enter_Root to ensure that root subsystems are
-- not checked-out by this process.
--
-- If there are no explicit checkouts to add, no action is taken.
procedure Checkout_Cycle;
-- Goes through successful cycles of Checkout -> Hash -> Configure -> Cache
-- until no Subsystems are in a state of "Requested".
--
-- If three cycles pass where the number of requested subsystems does not
-- change, a list of all requested subsystems is output and Process_Failed
-- is raised.
--
-- After a successful Checkout_Cycle process (all Requested subsystems
-- aquired and configured), the Root Configuration is processed (if any) and
-- then all Configuration Manifests are excluded from the Registrar.
procedure Consolidate_Dependencies;
-- Consolidates and builds all dependency maps
procedure Check_Completion;
-- Check for any subsystems that are Unavailable (checkout failed for
-- "common" reasons), and report diagnostic information to the user
-- before aborting.
--
-- If all Subsystems are Available, Check for any units with a state of
-- Requested (there should be none), and report any found to the user before
-- aborting
--
-- If -v is not given as a parameter, specific dependency relationships are
-- not output, and a simiplified description of incomplete or unavailable
-- subsystems is output.
--
-- If there are checkout failures and Verbose will be False,
-- Consolidate_Dependencies does not need to be invoked first, otherwise
-- it must be invoked first.
procedure Hash_Registry;
-- Hash all units in the registry, including compilation products
procedure Compile;
-- Executes:
-- 1. Build.Compute_Recomplations
-- 2. Build.Compilation.Compile
--
-- If Quiet is True, compiler output is not copied to the output
procedure Bind;
-- Creates a binder file, waits for the registration, and then executes a
-- compilation run to compile the binder unit
procedure Expand_Dependencies;
-- If a main unit is specified, all dependencies are added to the link set,
-- otherwise the link-set already contains all units. This must be invoked
-- before Scan_Linker_Options or Link_Or_Archive
procedure Scan_Linker_Options;
-- Invokes and tracks the Scan_Linker_Options phase when linking an image
-- or library
procedure Link_Or_Archive with
Pre => Command in Build_Command | Run_Command | Library_Command;
-- Depending on the command (build/run/library), and the output image name
-- (for library command only), either links an executable, a dynamic library,
-- or creates a regular object archive (".a" extension)
procedure Execute_Image;
-- Executes the compiled and linked image, passing no parameters, but
-- preserving the environment values.
--
-- On systems (such as Unix) that support replacing the image of the running
-- process, Execute_Image will not return. However, on systems that only
-- support explict process creation (such as Windows), a new process is
-- created, and Execute_Image returns normally.
procedure Save_Registry;
-- Saves Last_Run
procedure Save_Config;
-- Saves the build configuration (parameters)
end Scheduling;
|
pragma License (Unrestricted);
-- implementation unit
package System.Once is
pragma Preelaborate;
type Flag is mod 2 ** 8; -- it should be initialized to zero
for Flag'Size use 8;
pragma Atomic (Flag);
procedure Initialize (
Flag : not null access Once.Flag;
Process : not null access procedure);
end System.Once;
|
PROCEDURE Defining_Character_literal IS
BEGIN
DECLARE
TYPE E2 IS ('1');
BEGIN
NULL;
END;
END Defining_Character_literal;
|
with Ada.Real_Time;
procedure Delay_Until is
use Ada.Real_Time;
Start_Time : Time := Clock;
Period : constant Time_Span := Milliseconds(5000);
Poll_Time : Time;
begin
Poll_Time := Start_Time;
delay until Poll_Time;
end Delay_Until;
|
with Ada.Text_IO; use Ada.Text_IO;
package body NewLineExamples is
function Text_New_Lines (Text : String) return String
is
begin
return Text & ASCII.CR & ASCII.LF & ASCII.CR & ASCII.LF;
end Text_New_Lines;
function Twice_Text_New_Line (Text : String) return String
is
begin
return Text & ASCII.CR & ASCII.LF & Text & ASCII.CR & ASCII.LF;
end Twice_Text_New_Line;
Nl : constant String := (1 => ASCII.CR, 2 => ASCII.LF);
function Text_Duplicate (Text : String) return String
is
begin
return Text & Nl & Text & Nl;
end Text_Duplicate;
function Text_Dupl (Text : String) return String
is
begin
declare
EndOfLine : constant String := ASCII.CR & ASCII.LF;
begin
return Text & EndOfLine & Text & EndOfLine;
end;
end Text_Dupl;
function Text_Twice (Text : String) return String
is
CrLf : constant String := ASCII.CR & ASCII.LF;
begin
return Text & CrLf & Text & CrLf;
end Text_Twice;
function Text_Thrice (Text : String) return String
is
NewLine : constant String := (ASCII.CR & ASCII.LF);
begin
return Text & NewLine & Text & NewLine & Text & NewLine;
end Text_Thrice;
function Twice_Text (Text : String) return String
is
New_Line : constant String := "" & ASCII.CR & ASCII.LF;
begin
return New_Line & Text & New_Line & Text;
end Twice_Text;
end NewLineExamples;
|
-- Copyright 2016-2019 NXP
-- All rights reserved.SPDX-License-Identifier: BSD-3-Clause
-- This spec has been automatically generated from LPC55S6x.svd
pragma Restrictions (No_Elaboration_Code);
pragma Ada_2012;
pragma Style_Checks (Off);
with HAL;
with System;
package NXP_SVD.USBHSD is
pragma Preelaborate;
---------------
-- Registers --
---------------
subtype DEVCMDSTAT_DEV_ADDR_Field is HAL.UInt7;
subtype DEVCMDSTAT_Speed_Field is HAL.UInt2;
subtype DEVCMDSTAT_PHY_TEST_MODE_Field is HAL.UInt3;
-- USB Device Command/Status register
type DEVCMDSTAT_Register is record
-- USB device address.
DEV_ADDR : DEVCMDSTAT_DEV_ADDR_Field := 16#0#;
-- USB device enable.
DEV_EN : Boolean := False;
-- SETUP token received.
SETUP : Boolean := False;
-- Forces the NEEDCLK output to always be on:.
FORCE_NEEDCLK : Boolean := False;
-- unspecified
Reserved_10_10 : HAL.Bit := 16#0#;
-- LPM Supported:.
LPM_SUP : Boolean := True;
-- Interrupt on NAK for interrupt and bulk OUT EP:.
INTONNAK_AO : Boolean := False;
-- Interrupt on NAK for interrupt and bulk IN EP:.
INTONNAK_AI : Boolean := False;
-- Interrupt on NAK for control OUT EP:.
INTONNAK_CO : Boolean := False;
-- Interrupt on NAK for control IN EP:.
INTONNAK_CI : Boolean := False;
-- Device status - connect.
DCON : Boolean := False;
-- Device status - suspend.
DSUS : Boolean := False;
-- unspecified
Reserved_18_18 : HAL.Bit := 16#0#;
-- Device status - LPM Suspend.
LPM_SUS : Boolean := False;
-- Read-only. LPM Remote Wake-up Enabled by USB host.
LPM_REWP : Boolean := False;
-- unspecified
Reserved_21_21 : HAL.Bit := 16#0#;
-- Read-only. This field indicates the speed at which the device
-- operates: 00b: reserved 01b: full-speed 10b: high-speed 11b:
-- super-speed (reserved for future use).
Speed : DEVCMDSTAT_Speed_Field := 16#0#;
-- Device status - connect change.
DCON_C : Boolean := False;
-- Device status - suspend change.
DSUS_C : Boolean := False;
-- Device status - reset change.
DRES_C : Boolean := False;
-- unspecified
Reserved_27_27 : HAL.Bit := 16#0#;
-- Read-only. This bit indicates if VBUS is detected or not.
VBUS_DEBOUNCED : Boolean := False;
-- This field is written by firmware to put the PHY into a test mode as
-- defined by the USB2.0 specification
PHY_TEST_MODE : DEVCMDSTAT_PHY_TEST_MODE_Field := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DEVCMDSTAT_Register use record
DEV_ADDR at 0 range 0 .. 6;
DEV_EN at 0 range 7 .. 7;
SETUP at 0 range 8 .. 8;
FORCE_NEEDCLK at 0 range 9 .. 9;
Reserved_10_10 at 0 range 10 .. 10;
LPM_SUP at 0 range 11 .. 11;
INTONNAK_AO at 0 range 12 .. 12;
INTONNAK_AI at 0 range 13 .. 13;
INTONNAK_CO at 0 range 14 .. 14;
INTONNAK_CI at 0 range 15 .. 15;
DCON at 0 range 16 .. 16;
DSUS at 0 range 17 .. 17;
Reserved_18_18 at 0 range 18 .. 18;
LPM_SUS at 0 range 19 .. 19;
LPM_REWP at 0 range 20 .. 20;
Reserved_21_21 at 0 range 21 .. 21;
Speed at 0 range 22 .. 23;
DCON_C at 0 range 24 .. 24;
DSUS_C at 0 range 25 .. 25;
DRES_C at 0 range 26 .. 26;
Reserved_27_27 at 0 range 27 .. 27;
VBUS_DEBOUNCED at 0 range 28 .. 28;
PHY_TEST_MODE at 0 range 29 .. 31;
end record;
subtype INFO_FRAME_NR_Field is HAL.UInt11;
subtype INFO_ERR_CODE_Field is HAL.UInt4;
subtype INFO_MINREV_Field is HAL.UInt8;
subtype INFO_MAJREV_Field is HAL.UInt8;
-- USB Info register
type INFO_Register is record
-- Read-only. Frame number.
FRAME_NR : INFO_FRAME_NR_Field;
-- Read-only. The error code which last occurred:.
ERR_CODE : INFO_ERR_CODE_Field;
-- unspecified
Reserved_15_15 : HAL.Bit;
-- Read-only. Minor revision.
MINREV : INFO_MINREV_Field;
-- Read-only. Major revision.
MAJREV : INFO_MAJREV_Field;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for INFO_Register use record
FRAME_NR at 0 range 0 .. 10;
ERR_CODE at 0 range 11 .. 14;
Reserved_15_15 at 0 range 15 .. 15;
MINREV at 0 range 16 .. 23;
MAJREV at 0 range 24 .. 31;
end record;
subtype EPLISTSTART_EP_LIST_PRG_Field is HAL.UInt12;
subtype EPLISTSTART_EP_LIST_FIXED_Field is HAL.UInt12;
-- USB EP Command/Status List start address
type EPLISTSTART_Register is record
-- unspecified
Reserved_0_7 : HAL.UInt8 := 16#0#;
-- Programmable portion of the USB EP Command/Status List address.
EP_LIST_PRG : EPLISTSTART_EP_LIST_PRG_Field := 16#0#;
-- Read-only. Fixed portion of USB EP Command/Status List address.
EP_LIST_FIXED : EPLISTSTART_EP_LIST_FIXED_Field := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for EPLISTSTART_Register use record
Reserved_0_7 at 0 range 0 .. 7;
EP_LIST_PRG at 0 range 8 .. 19;
EP_LIST_FIXED at 0 range 20 .. 31;
end record;
subtype LPM_HIRD_HW_Field is HAL.UInt4;
subtype LPM_HIRD_SW_Field is HAL.UInt4;
-- USB Link Power Management register
type LPM_Register is record
-- Read-only. Host Initiated Resume Duration - HW.
HIRD_HW : LPM_HIRD_HW_Field := 16#0#;
-- Host Initiated Resume Duration - SW.
HIRD_SW : LPM_HIRD_SW_Field := 16#0#;
-- As long as this bit is set to one and LPM supported bit is set to
-- one, HW will return a NYET handshake on every LPM token it receives.
DATA_PENDING : Boolean := False;
-- unspecified
Reserved_9_31 : HAL.UInt23 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for LPM_Register use record
HIRD_HW at 0 range 0 .. 3;
HIRD_SW at 0 range 4 .. 7;
DATA_PENDING at 0 range 8 .. 8;
Reserved_9_31 at 0 range 9 .. 31;
end record;
subtype EPSKIP_SKIP_Field is HAL.UInt12;
-- USB Endpoint skip
type EPSKIP_Register is record
-- Endpoint skip: Writing 1 to one of these bits, will indicate to HW
-- that it must deactivate the buffer assigned to this endpoint and
-- return control back to software.
SKIP : EPSKIP_SKIP_Field := 16#0#;
-- unspecified
Reserved_12_31 : HAL.UInt20 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for EPSKIP_Register use record
SKIP at 0 range 0 .. 11;
Reserved_12_31 at 0 range 12 .. 31;
end record;
subtype EPINUSE_BUF_Field is HAL.UInt10;
-- USB Endpoint Buffer in use
type EPINUSE_Register is record
-- unspecified
Reserved_0_1 : HAL.UInt2 := 16#0#;
-- Buffer in use: This register has one bit per physical endpoint.
BUF : EPINUSE_BUF_Field := 16#0#;
-- unspecified
Reserved_12_31 : HAL.UInt20 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for EPINUSE_Register use record
Reserved_0_1 at 0 range 0 .. 1;
BUF at 0 range 2 .. 11;
Reserved_12_31 at 0 range 12 .. 31;
end record;
subtype EPBUFCFG_BUF_SB_Field is HAL.UInt10;
-- USB Endpoint Buffer Configuration register
type EPBUFCFG_Register is record
-- unspecified
Reserved_0_1 : HAL.UInt2 := 16#0#;
-- Buffer usage: This register has one bit per physical endpoint.
BUF_SB : EPBUFCFG_BUF_SB_Field := 16#0#;
-- unspecified
Reserved_12_31 : HAL.UInt20 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for EPBUFCFG_Register use record
Reserved_0_1 at 0 range 0 .. 1;
BUF_SB at 0 range 2 .. 11;
Reserved_12_31 at 0 range 12 .. 31;
end record;
-- USB interrupt status register
type INTSTAT_Register is record
-- Interrupt status register bit for the Control EP0 OUT direction.
EP0OUT : Boolean := False;
-- Interrupt status register bit for the Control EP0 IN direction.
EP0IN : Boolean := False;
-- Interrupt status register bit for the EP1 OUT direction.
EP1OUT : Boolean := False;
-- Interrupt status register bit for the EP1 IN direction.
EP1IN : Boolean := False;
-- Interrupt status register bit for the EP2 OUT direction.
EP2OUT : Boolean := False;
-- Interrupt status register bit for the EP2 IN direction.
EP2IN : Boolean := False;
-- Interrupt status register bit for the EP3 OUT direction.
EP3OUT : Boolean := False;
-- Interrupt status register bit for the EP3 IN direction.
EP3IN : Boolean := False;
-- Interrupt status register bit for the EP4 OUT direction.
EP4OUT : Boolean := False;
-- Interrupt status register bit for the EP4 IN direction.
EP4IN : Boolean := False;
-- Interrupt status register bit for the EP5 OUT direction.
EP5OUT : Boolean := False;
-- Interrupt status register bit for the EP5 IN direction.
EP5IN : Boolean := False;
-- unspecified
Reserved_12_29 : HAL.UInt18 := 16#0#;
-- Frame interrupt.
FRAME_INT : Boolean := False;
-- Device status interrupt.
DEV_INT : Boolean := False;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for INTSTAT_Register use record
EP0OUT at 0 range 0 .. 0;
EP0IN at 0 range 1 .. 1;
EP1OUT at 0 range 2 .. 2;
EP1IN at 0 range 3 .. 3;
EP2OUT at 0 range 4 .. 4;
EP2IN at 0 range 5 .. 5;
EP3OUT at 0 range 6 .. 6;
EP3IN at 0 range 7 .. 7;
EP4OUT at 0 range 8 .. 8;
EP4IN at 0 range 9 .. 9;
EP5OUT at 0 range 10 .. 10;
EP5IN at 0 range 11 .. 11;
Reserved_12_29 at 0 range 12 .. 29;
FRAME_INT at 0 range 30 .. 30;
DEV_INT at 0 range 31 .. 31;
end record;
subtype INTEN_EP_INT_EN_Field is HAL.UInt12;
-- USB interrupt enable register
type INTEN_Register is record
-- If this bit is set and the corresponding USB interrupt status bit is
-- set, a HW interrupt is generated on the interrupt line.
EP_INT_EN : INTEN_EP_INT_EN_Field := 16#0#;
-- unspecified
Reserved_12_29 : HAL.UInt18 := 16#0#;
-- If this bit is set and the corresponding USB interrupt status bit is
-- set, a HW interrupt is generated on the interrupt line.
FRAME_INT_EN : Boolean := False;
-- If this bit is set and the corresponding USB interrupt status bit is
-- set, a HW interrupt is generated on the interrupt line.
DEV_INT_EN : Boolean := False;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for INTEN_Register use record
EP_INT_EN at 0 range 0 .. 11;
Reserved_12_29 at 0 range 12 .. 29;
FRAME_INT_EN at 0 range 30 .. 30;
DEV_INT_EN at 0 range 31 .. 31;
end record;
subtype INTSETSTAT_EP_SET_INT_Field is HAL.UInt12;
-- USB set interrupt status register
type INTSETSTAT_Register is record
-- If software writes a one to one of these bits, the corresponding USB
-- interrupt status bit is set.
EP_SET_INT : INTSETSTAT_EP_SET_INT_Field := 16#0#;
-- unspecified
Reserved_12_29 : HAL.UInt18 := 16#0#;
-- If software writes a one to one of these bits, the corresponding USB
-- interrupt status bit is set.
FRAME_SET_INT : Boolean := False;
-- If software writes a one to one of these bits, the corresponding USB
-- interrupt status bit is set.
DEV_SET_INT : Boolean := False;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for INTSETSTAT_Register use record
EP_SET_INT at 0 range 0 .. 11;
Reserved_12_29 at 0 range 12 .. 29;
FRAME_SET_INT at 0 range 30 .. 30;
DEV_SET_INT at 0 range 31 .. 31;
end record;
subtype EPTOGGLE_TOGGLE_Field is HAL.UInt30;
-- USB Endpoint toggle register
type EPTOGGLE_Register is record
-- Read-only. Endpoint data toggle: This field indicates the current
-- value of the data toggle for the corresponding endpoint.
TOGGLE : EPTOGGLE_TOGGLE_Field;
-- unspecified
Reserved_30_31 : HAL.UInt2;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for EPTOGGLE_Register use record
TOGGLE at 0 range 0 .. 29;
Reserved_30_31 at 0 range 30 .. 31;
end record;
-----------------
-- Peripherals --
-----------------
-- USB1 High-speed Device Controller
type USBHSD_Peripheral is record
-- USB Device Command/Status register
DEVCMDSTAT : aliased DEVCMDSTAT_Register;
-- USB Info register
INFO : aliased INFO_Register;
-- USB EP Command/Status List start address
EPLISTSTART : aliased EPLISTSTART_Register;
-- USB Data buffer start address
DATABUFSTART : aliased HAL.UInt32;
-- USB Link Power Management register
LPM : aliased LPM_Register;
-- USB Endpoint skip
EPSKIP : aliased EPSKIP_Register;
-- USB Endpoint Buffer in use
EPINUSE : aliased EPINUSE_Register;
-- USB Endpoint Buffer Configuration register
EPBUFCFG : aliased EPBUFCFG_Register;
-- USB interrupt status register
INTSTAT : aliased INTSTAT_Register;
-- USB interrupt enable register
INTEN : aliased INTEN_Register;
-- USB set interrupt status register
INTSETSTAT : aliased INTSETSTAT_Register;
-- USB Endpoint toggle register
EPTOGGLE : aliased EPTOGGLE_Register;
end record
with Volatile;
for USBHSD_Peripheral use record
DEVCMDSTAT at 16#0# range 0 .. 31;
INFO at 16#4# range 0 .. 31;
EPLISTSTART at 16#8# range 0 .. 31;
DATABUFSTART at 16#C# range 0 .. 31;
LPM at 16#10# range 0 .. 31;
EPSKIP at 16#14# range 0 .. 31;
EPINUSE at 16#18# range 0 .. 31;
EPBUFCFG at 16#1C# range 0 .. 31;
INTSTAT at 16#20# range 0 .. 31;
INTEN at 16#24# range 0 .. 31;
INTSETSTAT at 16#28# range 0 .. 31;
EPTOGGLE at 16#34# range 0 .. 31;
end record;
-- USB1 High-speed Device Controller
USBHSD_Periph : aliased USBHSD_Peripheral
with Import, Address => System'To_Address (16#40094000#);
end NXP_SVD.USBHSD;
|
-- C46042A.ADA
-- Grant of Unlimited Rights
--
-- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687,
-- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained
-- unlimited rights in the software and documentation contained herein.
-- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making
-- this public release, the Government intends to confer upon all
-- recipients unlimited rights equal to those held by the Government.
-- These rights include rights to use, duplicate, release or disclose the
-- released technical data and computer software in whole or in part, in
-- any manner and for any purpose whatsoever, and to have or permit others
-- to do so.
--
-- DISCLAIMER
--
-- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR
-- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED
-- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE
-- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE
-- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A
-- PARTICULAR PURPOSE OF SAID MATERIAL.
--*
-- CHECK ARRAY CONVERSIONS WHEN THE TARGET TYPE IS A CONSTRAINED
-- ARRAY TYPE AND THE OPERAND TYPE HAS BOUNDS THAT DO NOT BELONG TO
-- THE BASE TYPE OF THE TARGET TYPE'S INDEX SUBTYPE.
-- R.WILLIAMS 9/8/86
WITH REPORT; USE REPORT;
PROCEDURE C46042A IS
TYPE INT IS RANGE -100 .. 100;
TYPE NEWINTEGER IS NEW INTEGER;
TYPE DAY IS (SUN, MON, TUE, WED, THU, FRI, SAT);
TYPE NDAY1 IS NEW DAY RANGE MON .. FRI;
TYPE NDAY2 IS NEW DAY RANGE MON .. FRI;
TYPE NNDAY1 IS NEW NDAY1;
FUNCTION IDENT (X : INT) RETURN INT IS
BEGIN
RETURN INT'VAL (IDENT_INT (INT'POS (X)));
END IDENT;
FUNCTION IDENT (X : NEWINTEGER) RETURN NEWINTEGER IS
BEGIN
RETURN NEWINTEGER'VAL (IDENT_INT (NEWINTEGER'POS (X)));
END IDENT;
FUNCTION IDENT (X : NDAY1) RETURN NDAY1 IS
BEGIN
RETURN NDAY1'VAL (IDENT_INT (NDAY1'POS (X)));
END IDENT;
FUNCTION IDENT (X : NDAY2) RETURN NDAY2 IS
BEGIN
RETURN NDAY2'VAL (IDENT_INT (NDAY2'POS (X)));
END IDENT;
FUNCTION IDENT (X : NNDAY1) RETURN NNDAY1 IS
BEGIN
RETURN NNDAY1'VAL (IDENT_INT (NNDAY1'POS (X)));
END IDENT;
BEGIN
TEST ( "C46042A", "CHECK ARRAY CONVERSIONS WHEN THE TARGET " &
"TYPE IS A CONSTRAINED ARRAY TYPE AND THE " &
"OPERAND TYPE HAS BOUNDS THAT DO NOT " &
"BELONG TO THE BASE TYPE OF THE TARGET " &
"TYPE'S INDEX SUBTYPE" );
DECLARE
TYPE UNARR1 IS ARRAY (INTEGER RANGE <>) OF INTEGER;
SUBTYPE CONARR1 IS UNARR1 (IDENT_INT (1) .. IDENT_INT (10));
TYPE UNARR2 IS ARRAY (INTEGER RANGE <>, NDAY1 RANGE <>)
OF INTEGER;
SUBTYPE CONARR2 IS UNARR2 (IDENT_INT (1) .. IDENT_INT (10),
IDENT (MON) .. IDENT (TUE));
TYPE ARR1 IS ARRAY (INT RANGE <>) OF INTEGER;
A1 : ARR1 (IDENT (11) .. IDENT (20)) :=
(IDENT (11) .. IDENT (20) => 0);
TYPE ARR2 IS ARRAY (INT RANGE <>, NDAY2 RANGE <>)
OF INTEGER;
A2 : ARR2 (IDENT (11) .. IDENT (20),
IDENT (WED) .. IDENT (THU)) :=
(IDENT (11) .. IDENT (20) =>
(IDENT (WED) .. IDENT (THU) => 0));
TYPE ARR3 IS ARRAY (NEWINTEGER RANGE <>, NNDAY1 RANGE <>)
OF INTEGER;
A3 : ARR3 (IDENT (11) .. IDENT (20),
IDENT (WED) .. IDENT (THU)) :=
(IDENT (11) .. IDENT (20) =>
(IDENT (WED) .. IDENT (THU) => 0));
PROCEDURE CHECK (A : UNARR1) IS
BEGIN
IF A'FIRST /= 1 OR A'LAST /= 10 THEN
FAILED ( "INCORRECT CONVERSION OF UNARR1 (A1)" );
END IF;
END CHECK;
PROCEDURE CHECK (A : UNARR2; STR : STRING) IS
BEGIN
IF A'FIRST (1) /= 1 OR A'LAST /= 10 OR
A'FIRST (2) /= MON OR A'LAST (2) /= TUE THEN
FAILED ( "INCORRECT CONVERSION OF UNARR2 (A" &
STR & ")" );
END IF;
END CHECK;
BEGIN
BEGIN
CHECK (CONARR1 (A1));
EXCEPTION
WHEN OTHERS =>
FAILED ( "EXCEPTION RAISED BY 'CONARR1 (A1)'" );
END;
BEGIN
CHECK (CONARR2 (A2), "2");
EXCEPTION
WHEN OTHERS =>
FAILED ( "EXCEPTION RAISED BY 'CONARR2 (A2)'" );
END;
BEGIN
CHECK (CONARR2 (A3), "3");
EXCEPTION
WHEN OTHERS =>
FAILED ( "EXCEPTION RAISED BY 'CONARR2 (A3)'" );
END;
END;
RESULT;
END C46042A;
|
with Ada.Text_IO;
with Ada.Calendar;
with Interfaces; use Interfaces;
with Formatted_Output; use Formatted_Output;
with Formatted_Output_Integer; use Formatted_Output_Integer;
with Formatted_Output_Long_Integer; use Formatted_Output_Long_Integer;
with Formatted_Output_Long_Long_Integer; use Formatted_Output_Long_Long_Integer;
with Formatted_Output_Float; use Formatted_Output_Float;
with Formatted_Output_Long_Float; use Formatted_Output_Long_Float;
with Formatted_Output_Long_Long_Float; use Formatted_Output_Long_Long_Float;
with Formatted_Output.Decimal_Output;
with Formatted_Output.Modular_Output;
with Formatted_Output_Short_Integer; use Formatted_Output_Short_Integer;
with Formatted_Output_Short_Short_Integer; use Formatted_Output_Short_Short_Integer;
with Formatted_Output.Enumeration_Output;
with Formatted_Output.Time_Output; use Formatted_Output.Time_Output;
with L10n; use L10n;
procedure Formatted_Output_Demo is
procedure Show_Integer_Ranges;
procedure Show_Float_Ranges;
-------------------------
-- Show_Integer_Ranges --
-------------------------
procedure Show_Integer_Ranges is
begin
Put_Line
(+"Short_Short_Integer type range:\n\t%+_30d .. %-+_30d"
& Short_Short_Integer'First & Short_Short_Integer'Last);
Put_Line
(+"Short_Integer type range:\n\t%+_30d .. %-+_30d"
& Short_Integer'First & Short_Integer'Last);
Put_Line
(+"Integer type range:\n\t%+_30d .. %-+_30d"
& Integer'First & Integer'Last);
Put_Line
(+"Long_Integer type range:\n\t%+_30d .. %-+_30d"
& Long_Integer'First & Long_Integer'Last);
Put_Line
(+"Long_Long_Integer type range:\n\t%+_30d .. %-+_30d"
& Long_Long_Integer'First & Long_Long_Integer'Last);
Put_Line
(+"Natural type range:\n\t%+_30d .. %-+_30d"
& Natural'First & Natural'Last);
Put_Line
(+"Positive type range:\n\t%+_30d .. %-+_30d"
& Positive'First & Positive'Last);
end Show_Integer_Ranges;
-----------------------
-- Show_Float_Ranges --
-----------------------
procedure Show_Float_Ranges is
begin
Put_Line
(+"Float type range:\n\t%+_35.20e .. %-+_35.20e"
& Float'First & Float'Last);
Put_Line
(+"Long_Float type range:\n\t%+_35.20e .. %-+_35.20e"
& Long_Float'First & Long_Float'Last);
Put_Line
(+"Long_Long_Float type range:\n\t%+_35.20e .. %-+_35.20e"
& Long_Long_Float'First & Long_Long_Float'Last);
end Show_Float_Ranges;
package Unsigned_Output is
new Formatted_Output.Modular_Output (Interfaces.Unsigned_64);
use Unsigned_Output;
type Money is delta 0.01 digits 18;
package Money_Output is new Formatted_Output.Decimal_Output (Money);
use Money_Output;
package Character_Output is
new Formatted_Output.Enumeration_Output (Character);
use Character_Output;
Str : String := "Hello, world!";
T : Ada.Calendar.Time := Ada.Calendar.Clock;
begin
Set_Locale;
Formatted_Output.Put_Line (+"String = %s" & Str);
Formatted_Output.Put_Line (+"Char = %c" & Str (Str'First));
Ada.Text_IO.New_Line;
Show_Integer_Ranges;
Ada.Text_IO.New_Line;
Show_Float_Ranges;
Ada.Text_IO.New_Line;
Formatted_Output.Put_Line
(+"Unsigned_64 type range:\n\t%_35d .. %-_35d"
& Unsigned_64'First & Unsigned_64'Last);
Ada.Text_IO.New_Line;
Formatted_Output.Put_Line
(+"Money type range (%s):\n\t%+_35e .. %-+_35e"
& "type Money is delta 0.01 digits 18"
& Money'First & Money'Last);
Ada.Text_IO.New_Line;
Formatted_Output.Put_Line
(+"Current Time (Locale: %s) = %s"
& Get_Locale & Format_Time ("'%c'", T));
Set_Locale (Locale => "POSIX");
Formatted_Output.Put_Line
(+"Current Time (Locale: %s) = %s"
& Get_Locale & Format_Time ("'%c'", T));
Set_Locale (Locale => "uk_UA.UTF-8");
Formatted_Output.Put_Line
(+"Current Time (Locale: %s) = %s"
& Get_Locale & Format_Time ("'%c'", T));
end Formatted_Output_Demo;
|
pragma Ada_2012;
package body Pcap is
---------------
-- Lookupdev --
---------------
function Lookupdev (D : String) return String is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Lookupdev unimplemented");
return raise Program_Error with "Unimplemented function Lookupdev";
end Lookupdev;
---------------
-- Lookupnet --
---------------
procedure Lookupnet
(Net : String;
Addr : out Ipv4Addr;
Mask : out Ipv4Mask)
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Lookupnet unimplemented");
raise Program_Error with "Unimplemented procedure Lookupnet";
end Lookupnet;
------------
-- Create --
------------
function Create (Source : String := "any") return Pcap_T is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Create unimplemented");
return raise Program_Error with "Unimplemented function Create";
end Create;
-----------------
-- Set_Snaplen --
-----------------
procedure Set_Snaplen (Self : Pcap_T; Snaplen : Natural) is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Set_Snaplen unimplemented");
raise Program_Error with "Unimplemented procedure Set_Snaplen";
end Set_Snaplen;
-----------------
-- Set_Promisc --
-----------------
procedure Set_Promisc (Self : Pcap_T; Promisc : Boolean) is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Set_Promisc unimplemented");
raise Program_Error with "Unimplemented procedure Set_Promisc";
end Set_Promisc;
-------------------
-- Can_Set_Rfmon --
-------------------
function Can_Set_Rfmon (Self : Pcap_T) return Boolean is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Can_Set_Rfmon unimplemented");
return raise Program_Error with "Unimplemented function Can_Set_Rfmon";
end Can_Set_Rfmon;
---------------
-- Set_Rfmon --
---------------
procedure Set_Rfmon (Self : Pcap_T; Promisc : Boolean) is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Set_Rfmon unimplemented");
raise Program_Error with "Unimplemented procedure Set_Rfmon";
end Set_Rfmon;
-----------------
-- Set_Timeout --
-----------------
procedure Set_Timeout (Self : Pcap_T; TimeOut : Duration) is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Set_Timeout unimplemented");
raise Program_Error with "Unimplemented procedure Set_Timeout";
end Set_Timeout;
---------------------
-- Set_Tstamp_Type --
---------------------
procedure Set_Tstamp_Type (Self : Pcap_T; Arg2 : Tstamp_Type := HOST) is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Set_Tstamp_Type unimplemented");
raise Program_Error with "Unimplemented procedure Set_Tstamp_Type";
end Set_Tstamp_Type;
------------------------
-- Set_Immediate_Mode --
------------------------
procedure Set_Immediate_Mode
(Self : Pcap_T;
Immediate_Mode : Boolean := True)
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Set_Immediate_Mode unimplemented");
raise Program_Error with "Unimplemented procedure Set_Immediate_Mode";
end Set_Immediate_Mode;
---------------------
-- Set_Buffer_Size --
---------------------
procedure Set_Buffer_Size (Self : Pcap_T; Buffer_Size : Natural) is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Set_Buffer_Size unimplemented");
raise Program_Error with "Unimplemented procedure Set_Buffer_Size";
end Set_Buffer_Size;
--------------------------
-- Set_Tstamp_Precision --
--------------------------
procedure Set_Tstamp_Precision
(Self : Pcap_T;
Precision : Tstamp_Precision_Type := MICRO)
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Set_Tstamp_Precision unimplemented");
raise Program_Error with "Unimplemented procedure Set_Tstamp_Precision";
end Set_Tstamp_Precision;
--------------------------
-- Get_Tstamp_Precision --
--------------------------
function Get_Tstamp_Precision
(Arg1 : Pcap_T)
return Tstamp_Precision_Type
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Get_Tstamp_Precision unimplemented");
return raise Program_Error with "Unimplemented function Get_Tstamp_Precision";
end Get_Tstamp_Precision;
--------------
-- Activate --
--------------
function Activate (Arg1 : access Pcap_T) return Integer is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Activate unimplemented");
return raise Program_Error with "Unimplemented function Activate";
end Activate;
-----------------------
-- List_Tstamp_Types --
-----------------------
function List_Tstamp_Types (Self : Pcap_T) return Tstamp_Types is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "List_Tstamp_Types unimplemented");
return raise Program_Error with "Unimplemented function List_Tstamp_Types";
end List_Tstamp_Types;
end Pcap;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS --
-- --
-- S Y S T E M . O S _ P R I M I T I V E S --
-- --
-- B o d y --
-- --
-- Copyright (C) 1998-2020, Free Software Foundation, Inc. --
-- --
-- GNARL is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 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 version is for VxWorks targets
with System.OS_Interface;
-- Since the thread library is part of the VxWorks kernel, using OS_Interface
-- is not a problem here, as long as we only use System.OS_Interface as a
-- set of C imported routines: using Ada routines from this package would
-- create a dependency on libgnarl in libgnat, which is not desirable.
with System.OS_Constants;
with Interfaces.C;
package body System.OS_Primitives is
use System.OS_Interface;
use type Interfaces.C.int;
package OSC renames System.OS_Constants;
------------------------
-- Internal functions --
------------------------
function To_Clock_Ticks (D : Duration) return int;
-- Convert a duration value (in seconds) into clock ticks.
-- Note that this routine is duplicated from System.OS_Interface since
-- as explained above, we do not want to depend on libgnarl
function To_Clock_Ticks (D : Duration) return int is
Ticks : Long_Long_Integer;
Rate_Duration : Duration;
Ticks_Duration : Duration;
begin
if D < 0.0 then
return -1;
end if;
-- Ensure that the duration can be converted to ticks
-- at the current clock tick rate without overflowing.
Rate_Duration := Duration (sysClkRateGet);
if D > (Duration'Last / Rate_Duration) then
Ticks := Long_Long_Integer (int'Last);
else
Ticks_Duration := D * Rate_Duration;
Ticks := Long_Long_Integer (Ticks_Duration);
if Ticks_Duration > Duration (Ticks) then
Ticks := Ticks + 1;
end if;
if Ticks > Long_Long_Integer (int'Last) then
Ticks := Long_Long_Integer (int'Last);
end if;
end if;
return int (Ticks);
end To_Clock_Ticks;
-----------
-- Clock --
-----------
function Clock return Duration is
TS : aliased timespec;
Result : int;
begin
Result := clock_gettime (OSC.CLOCK_RT_Ada, TS'Unchecked_Access);
pragma Assert (Result = 0);
return Duration (TS.ts_sec) + Duration (TS.ts_nsec) / 10#1#E9;
end Clock;
-----------------
-- Timed_Delay --
-----------------
procedure Timed_Delay
(Time : Duration;
Mode : Integer)
is
Rel_Time : Duration;
Abs_Time : Duration;
Base_Time : constant Duration := Clock;
Check_Time : Duration := Base_Time;
Ticks : int;
Result : int;
pragma Unreferenced (Result);
begin
if Mode = Relative then
Rel_Time := Time;
Abs_Time := Time + Check_Time;
else
Rel_Time := Time - Check_Time;
Abs_Time := Time;
end if;
if Rel_Time > 0.0 then
loop
Ticks := To_Clock_Ticks (Rel_Time);
if Mode = Relative and then Ticks < int'Last then
-- The first tick will delay anytime between 0 and
-- 1 / sysClkRateGet seconds, so we need to add one to
-- be on the safe side.
Ticks := Ticks + 1;
end if;
Result := taskDelay (Ticks);
Check_Time := Clock;
exit when Abs_Time <= Check_Time or else Check_Time < Base_Time;
Rel_Time := Abs_Time - Check_Time;
end loop;
end if;
end Timed_Delay;
----------------
-- Initialize --
----------------
procedure Initialize is
begin
null;
end Initialize;
end System.OS_Primitives;
|
package Aggr15 is
type T is tagged record
I : Integer;
end record;
type DATA_T is record
D : T;
end record;
type ALL_DATA_T is array (1..2, 1..2) of DATA_T;
function ALL_CREATE return ALL_DATA_T;
end Aggr15;
|
-- C57003A.ADA
-- Grant of Unlimited Rights
--
-- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687,
-- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained
-- unlimited rights in the software and documentation contained herein.
-- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making
-- this public release, the Government intends to confer upon all
-- recipients unlimited rights equal to those held by the Government.
-- These rights include rights to use, duplicate, release or disclose the
-- released technical data and computer software in whole or in part, in
-- any manner and for any purpose whatsoever, and to have or permit others
-- to do so.
--
-- DISCLAIMER
--
-- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR
-- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED
-- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE
-- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE
-- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A
-- PARTICULAR PURPOSE OF SAID MATERIAL.
--*
-- CHECK THAT THE EXIT STATEMENT IS EVALUATED EACH TIME THROUGH A LOOP,
-- AND THAT IT IS EVALUATED CORRECTLY WHETHER POSITIONED AT THE
-- BEGINNING, MIDDLE, OR END OF THE LOOP.
-- EACH TEST IS A LOOP ON J WHERE THE EXIT CONDITIONS ARE TO EVALUATE
-- TO 'FALSE' A CERTAIN NUMBER OF TIMES UNTIL, AT THE APPROPRIATE
-- TIME, ONE OF THEM EVALUATES TO 'TRUE' AND CAUSES THE LOOP TO BE
-- EXITED.
--
--
-- THE TEST IS PERFORMED 30 TIMES FOR EACH OF THE FIRST TWO
-- DATA TYPES CONSIDERED ('INTEGER', USER-DEFINED ENUMERATION)
-- AND 26 TIMES FOR 'CHARACTER' (THUS 86 TIMES ALTOGETHER).
--
--
-- EACH DATA TYPE HAS ITS OWN SEPARATE SECTION OF CODE. ALL SECTIONS
-- FOLLOW THE SAME TESTING ALGORITHM (MUTATIS MUTANDIS). THE CALCU-
-- LATIONS WHICH KEEP TRACK OF THE FLOW OF CONTROL ARE ALL DONE IN
-- INTEGER ARITHMETIC. THERE ARE THREE DATA TYPES, THUS THREE
-- SECTIONS.
--
--
-- FOR EACH DATA TYPE, THE 30 TESTS ARE DIVIDED INTO 3 "SEGMENTS"
--
-- << NOTE: THE NUMBER OF SEGMENTS IS WRITTEN " 3 " ,
-- THE NUMBER OF SECTIONS IS WRITTEN "THREE" >>
--
-- (OF 10 TESTS EACH, EXCEPT 10,10,6 FOR 'CHARACTER'), NUMBERED
-- 0 , 1 , 2 AND CORRESPONDING TO THE 3 SIGNIFICANTLY DIFFERENT
-- POSITIONS OF AN EXIT STATEMENT WITH RESPECT TO THE LOOP IT IS IN
-- ( "AT THE VERY TOP" , "AT THE VERY BOTTOM" , "ANYWHERE IN BETWEEN"
-- ). AT THE BEGINNING OF EACH TEST, THE VARIABLE WHICH_SEGMENT
-- IS UPDATED TO CONTAIN THE NEW VALUE OF THIS IDENTIFYING NUMBER
-- (FOR THE TEST ABOUT TO BEGIN):
--
-- EXIT AT THE TOP ........ WHICH_SEGMENT = 0
-- EXIT FROM THE MIDDLE ........ WHICH_SEGMENT = 1
-- EXIT AT THE BOTTOM ........ WHICH_SEGMENT = 2 .
--
--
-- WITHIN EACH SECTION, THE TESTS ARE NUMBERED FROM 1 TO 30
-- (26 FOR 'CHARACTER'). THIS NUMBER IS STORED IN THE INTEGER
-- VARIABLE INT_I (EQUAL TO THE CURRENT VALUE OF THE OUTER-LOOP
-- INDEX WHEN THAT INDEX IS OF INTEGER TYPE), WHOSE APPROPRIATE VALUE
-- FOR EACH TEST IS SET AT THE BEGINNING OF THE TEST.
--
--
-- AS PART OF THE EVALUATION PROCESS, THE PROGRAM COMPUTES FOR EACH
-- TEST (I.E. FOR EACH VALUE OF I , OR OF INT_I ) THE APPROPRIATE
-- NUMBER OF INNER-LOOP ITERATIONS REQUIRED BEFORE EXIT; THIS IS
-- THE EXPECTED VALUE OF J (EXPRESSED AS AN INTEGER IN THE RANGE
-- 1..10 ) AND STORES IT IN EXPECTED_J . FOR EACH OF THE THREE
-- SECTIONS, THE TIME SEQUENCE OF THESE 30 VALUES IS
--
-- 1 2 3 4 5 6 7 8 9 10 << SEGMENT 1 >>
-- 6 6 7 7 8 8 9 9 10 10 << SEGMENT 2 >>
-- 7 8 8 8 9 9 9 10 10 10 << SEGMENT 3 >>
--
-- (EACH SECTION GETS ALL 3 ROWS, NOT ONE ROW PER SECTION;
-- FOR 'CHARACTER', WHERE ONLY 26 VALUES ARE REQUIRED, THE LAST 4
-- VALUES ARE OMITTED). THIS NUMBER IS COMPARED WITH THE ACTUAL
-- VALUE OF J (ACTUAL NUMBER OF INNER-LOOP ITERATIONS BEFORE THE
-- EXECUTION OF THE EXIT STATEMENT) AS SAVED JUST BEFORE THE EXIT
-- FROM THE LOOP (AGAIN IN THE FORM OF AN INTEGER IN THE RANGE
-- 1..30 , IRRESPECTIVE OF THE DATA TYPE BEING TESTED), I F
-- SUCH SAVED VALUE IS AVAILABLE.
--
--
-- THE ACTUAL VALUE OF INNER-LOOP ITERATIONS (AS SAVED IMMEDIATELY
-- BEFORE THE EXIT, AS OPPOSED TO A VALUE LEFT OVER FROM SOME
-- PREVIOUS ITERATION) IS AVAILABLE ONLY IF WHICH_SEGMENT /= 0 ,
-- AND IS THEN STORED IN SAVE_J .
--
--
-- FOR THE CASE WHICH_SEGMENT = 0 , THE ITERATIONS ARE COUNTED IN
-- THE VARIABLE COUNT , WHOSE VALUE AT THE COMPLETION OF THE
-- I-TH TEST ( I IN 1..10 ) MUST BE EQUAL TO EXPECTED_J - 1 ,
-- AND THUS TO I - 1 (METHODOLOGICALLY AS WELL AS COMPUTATIONALLY
-- THIS IS NO DIFFERENT FROM USING THE MOST RECENT VALUE OF SAVE_J
-- WHEN A CURRENT ONE CANNOT BE OBTAINED). AFTER BEING INCREMENTED
-- BY 1 , COUNT IS CHECKED AGAINST EXPECTED_J .
--
--
-- THIS CONCLUDES THE DESCRIPTION OF THE CASE WHICH_SEGMENT = 0 ,
-- AND THUS OF THE ALGORITHM. THE ONLY REASON FOR SPLITTING THE
-- CASE WHICH_SEGMENT /= 0 INTO TWO IS THE DESIRE TO PROVIDE FOR
-- DISTINCT MESSAGES.
-- RM 04/23/81
-- SPS 3/7/83
WITH REPORT;
PROCEDURE C57003A IS
USE REPORT ;
BEGIN
TEST( "C57003A" , "TEST THAT THE EXIT STATEMENT IS EVALUATED" &
" EACH TIME THROUGH THE LOOP" );
DECLARE
WHICH_SEGMENT : INTEGER RANGE 0..2 ; -- BOUNDS ARE TIGHT
SAVE_J : INTEGER RANGE 1..10 ;
EXPECTED_J : INTEGER RANGE 1..10 ;
COUNT : INTEGER RANGE 0..100 := 0 ;
INT_I : INTEGER RANGE 1..30 ;
TYPE ENUM IS ( CHANGE_THE_ORIGIN_FROM_0_TO_1 ,
A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 ,
A11, A12, A13, A14, A15, A16, A17, A18, A19, A20 ,
A21, A22, A23, A24, A25, A26, A27, A28, A29, A30 );
BEGIN
--------------------------------------------------------------
----------------------- INTEGER ----------------------------
FOR I IN INTEGER RANGE 1..30 LOOP
WHICH_SEGMENT := ( I - 1 ) / 10 ;
EXPECTED_J := ( I + WHICH_SEGMENT ) /
( WHICH_SEGMENT + 1 ) ;
COUNT := 0 ;
FOR J IN INTEGER RANGE 1..10 LOOP
-- J NOT SAVED HERE (SO THAT 'EXIT' BE FIRST STMT)
EXIT WHEN WHICH_SEGMENT = 0 AND
1*J >= I ;--COUNT+:=1 ON NXT LINE INSTEAD
COUNT := COUNT + 1 ;
NULL ;
NULL ;
NULL ;
SAVE_J := J ;
EXIT WHEN WHICH_SEGMENT = 1 AND
2*J >= I ;
NULL ;
NULL ;
NULL ;
SAVE_J := J ;
EXIT WHEN WHICH_SEGMENT = 2 AND
3*J >= I ;
END LOOP;
COUNT := COUNT + 1 ; -- SEE HEADER
CASE WHICH_SEGMENT IS
WHEN 0 =>
IF COUNT /= EXPECTED_J THEN
FAILED( "WRONG COUNT; INT, EXIT AT TOP" );
END IF;
WHEN 1 => -- WOULD WORK ALSO FOR 0
IF SAVE_J /= EXPECTED_J THEN
FAILED( "WRONG COUNT; I,EXIT AT MIDDLE" );
END IF;
WHEN 2 =>
IF SAVE_J /= EXPECTED_J THEN
FAILED( "WRONG COUNT; I,EXIT AT BOTTOM" );
END IF;
END CASE;
END LOOP;
--------------------------------------------------------------
---------------------- CHARACTER ---------------------------
FOR I IN CHARACTER RANGE 'A'..'Z' LOOP
INT_I := CHARACTER'POS(I) - CHARACTER'POS('A') + 1;
WHICH_SEGMENT := ( INT_I - 1 ) / 10 ;
EXPECTED_J := ( INT_I + WHICH_SEGMENT ) /
( WHICH_SEGMENT + 1 ) ;
COUNT := 0 ;
FOR J IN CHARACTER RANGE 'A'..'J' LOOP
-- J NOT SAVED HERE (SO THAT 'EXIT' BE FIRST STMT)
EXIT WHEN WHICH_SEGMENT = 0 AND
J >= I ; -- COUNT+:=1 ON NXT LINE INSTEAD
COUNT := COUNT + 1 ;
NULL ;
NULL ;
NULL ;
SAVE_J := CHARACTER'POS(J) - CHARACTER'POS('A') + 1;
EXIT WHEN WHICH_SEGMENT = 1 AND
2 * SAVE_J >= INT_I ;
NULL ;
NULL ;
NULL ;
EXIT WHEN WHICH_SEGMENT = 2 AND
3 * SAVE_J >= INT_I ;
END LOOP;
COUNT := COUNT + 1 ;
CASE WHICH_SEGMENT IS
WHEN 0 =>
IF COUNT /= EXPECTED_J THEN
FAILED( "WRONG COUNT;CHAR, EXIT AT TOP" );
END IF;
WHEN 1 => -- WOULD WORK ALSO FOR 0
IF SAVE_J /= EXPECTED_J THEN
FAILED( "WRONG COUNT; C,EXIT AT MIDDLE" );
END IF;
WHEN 2 =>
IF SAVE_J /= EXPECTED_J THEN
FAILED( "WRONG COUNT; C,EXIT AT BOTTOM" );
END IF;
END CASE;
END LOOP;
--------------------------------------------------------------
--------------------- ENUMERATION --------------------------
FOR I IN ENUM RANGE A1..A30 LOOP
INT_I := ENUM'POS(I) ;
WHICH_SEGMENT := ( INT_I - 1 ) / 10 ;
EXPECTED_J := ( INT_I + WHICH_SEGMENT ) /
( WHICH_SEGMENT + 1 ) ;
COUNT := 0 ;
FOR J IN ENUM RANGE A1..A10 LOOP
-- J NOT SAVED HERE (SO THAT 'EXIT' BE FIRST STMT)
EXIT WHEN WHICH_SEGMENT = 0 AND
J >= I ; -- COUNT+:=1 ON NXT LINE INSTEAD
COUNT := COUNT + 1 ;
NULL ;
NULL ;
NULL ;
SAVE_J := ENUM'POS(J) ;
EXIT WHEN WHICH_SEGMENT = 1 AND
2 * SAVE_J >= INT_I ;
NULL ;
NULL ;
NULL ;
EXIT WHEN WHICH_SEGMENT = 2 AND
3 * SAVE_J >= INT_I ;
END LOOP;
COUNT := COUNT + 1 ;
CASE WHICH_SEGMENT IS
WHEN 0 =>
IF COUNT /= EXPECTED_J THEN
FAILED( "WRONG COUNT;ENUM, EXIT AT TOP" );
END IF;
WHEN 1 => -- WOULD WORK ALSO FOR 0
IF SAVE_J /= EXPECTED_J THEN
FAILED( "WRONG COUNT; E,EXIT AT MIDDLE" );
END IF;
WHEN 2 =>
IF SAVE_J /= EXPECTED_J THEN
FAILED( "WRONG COUNT; E,EXIT AT BOTTOM" );
END IF;
END CASE;
END LOOP;
--------------------------------------------------------------
END ;
RESULT ;
END C57003A ;
|
package OpenGL.State is
type Capability_t is
(Alpha_Test,
Auto_Normal,
Blend,
Color_Array,
Color_Logic_Op,
Color_Material,
Color_Sum,
Color_Table,
Convolution_1D,
Convolution_2D,
Cull_Face,
Depth_Test,
Dither,
Edge_Flag_Array,
Fog,
Fog_Coord_Array,
Histogram,
Index_Array,
Index_Logic_Op,
Lighting,
Line_Smooth,
Line_Stipple,
Map1_Color_4,
Map1_Index,
Map1_Normal,
Map1_Texture_Coord_1,
Map1_Texture_Coord_2,
Map1_Texture_Coord_3,
Map1_Texture_Coord_4,
Map2_Color_4,
Map2_Index,
Map2_Normal,
Map2_Texture_Coord_1,
Map2_Texture_Coord_2,
Map2_Texture_Coord_3,
Map2_Texture_Coord_4,
Map2_Vertex_3,
Map2_Vertex_4,
Minmax,
Multisample,
Normal_Array,
Normalize,
Point_Smooth,
Point_Sprite,
Polygon_Smooth,
Polygon_Offset_Fill,
Polygon_Offset_Line,
Polygon_Offset_Point,
Polygon_Stipple,
Post_Color_Matrix_Color_Table,
Post_Convolution_Color_Table,
Rescale_Normal,
Sample_Alpha_To_Coverage,
Sample_Alpha_To_One,
Sample_Coverage,
Scissor_Test,
Secondary_Color_Array,
Separable_2D,
Stencil_Test,
Texture_1D,
Texture_2D,
Texture_3D,
Texture_Coord_Array,
Texture_Cube_Map,
Texture_Gen_Q,
Texture_Gen_R,
Texture_Gen_S,
Texture_Gen_T,
Texture_Rectangle_ARB,
Vertex_Array,
Vertex_Program_Point_Size,
Vertex_Program_Two_Side);
-- proc_map : glEnable
procedure Enable (Capability : in Capability_t);
pragma Inline (Enable);
-- proc_map : glDisable
procedure Disable (Capability : in Capability_t);
pragma Inline (Disable);
-- proc_map : glIsEnabled
function Is_Enabled (Capability : in Capability_t) return Boolean;
pragma Inline (Is_Enabled);
--
-- Client state.
--
type Client_Capability_t is
(Color_Array,
Edge_Flag_Array,
Fog_Coord_Array,
Index_Array,
Normal_Array,
Secondary_Color_Array,
Texture_Coord_Array,
Vertex_Array);
-- proc_map : glEnableClientState
procedure Enable_Client_State (Capability : in Client_Capability_t);
pragma Inline (Enable_Client_State);
-- proc_map : glDisableClientState
procedure Disable_Client_State (Capability : in Client_Capability_t);
pragma Inline (Disable_Client_State);
end OpenGL.State;
|
pragma License (Unrestricted);
-- implementation unit
package System.Formatting.Literals.Float is
pragma Pure;
-- parsing Ada-form literals of real types
procedure Get_Literal (
Item : String;
Last : out Natural;
Result : out Long_Long_Float;
Error : out Boolean);
end System.Formatting.Literals.Float;
|
with Ada.Text_IO; use Ada.Text_IO;
procedure Day20 is
type Position is record
X : Integer;
Y : Integer;
end record;
function Next_Pos (Pos : Position; Dir : Character) return Position is
begin
case Dir is
when 'N' => return (Pos.X, Pos.Y + 1);
when 'S' => return (Pos.X, Pos.Y - 1);
when 'W' => return (Pos.X - 1, Pos.Y);
when 'E' => return (Pos.X + 1, Pos.Y);
when others =>
raise Constraint_Error with "Invalid direction: " & Dir;
end case;
end Next_Pos;
Grid : array
(Integer range -1000 .. 1000, Integer range -1000 .. 1000) of Natural :=
(0 => (0 => 0,
others => Natural'Last),
others => (others => Natural'Last));
Global_Pos : Position := (0, 0);
procedure Parse (Regex : String; Old_Pos : Position) is
Pos : Position := Old_Pos;
I, J, K : Positive := Regex'First;
Depth : Natural := 0;
begin
while I <= Regex'Last loop
exit when Regex (I) = '(';
declare
New_Pos : constant Position := Next_Pos (Pos, Regex (I));
New_Value : constant Natural := Grid (New_Pos.X, New_Pos.Y);
Old_Value : constant Natural := Grid (Pos.X, Pos.Y);
begin
Pos := New_Pos;
Grid (Pos.X, Pos.Y) := Natural'Min (New_Value, Old_Value + 1);
end;
I := I + 1;
end loop;
Global_Pos := Pos;
if I > Regex'Last then
return;
end if;
J := I + 1;
Depth := 1; -- only reachable if Regex (I) = '('
loop
if Regex (J) = '(' then
Depth := Depth + 1;
elsif Regex (J) = ')' then
Depth := Depth - 1;
end if;
exit when Depth = 0;
J := J + 1;
end loop;
K := I;
loop
declare
Sub_Regex : constant String := Regex (K + 1 .. J - 1);
begin
Depth := 0;
K := Sub_Regex'First;
while K <= Sub_Regex'Last loop
if Sub_Regex (K) = '(' then
Depth := Depth + 1;
elsif Sub_Regex (K) = ')' then
Depth := Depth - 1;
end if;
exit when Depth = 0 and Sub_Regex (K) = '|';
K := K + 1;
end loop;
Parse (Sub_Regex (Sub_Regex'First .. K - 1), Pos);
exit when K > Sub_Regex'Last;
end;
end loop;
if J < Regex'Last then
Parse (Regex (J + 1 .. Regex'Last), Global_Pos);
end if;
end Parse;
File : File_Type;
begin
Open (File, In_File, "input.txt");
declare
Input : constant String := Get_Line (File);
begin
Parse (Input (Input'First + 1 .. Input'Last - 1), (0, 0));
end;
Close (File);
declare
Room_Count : Natural := 0;
Max_Doors : Natural := 0;
begin
for X in Grid'Range (1) loop
for Y in Grid'Range (2) loop
if Grid (X, Y) < Natural'Last then
Max_Doors := Natural'Max (Max_Doors, Grid (X, Y));
if Grid (X, Y) >= 1000 then
Room_Count := Room_Count + 1;
end if;
end if;
end loop;
end loop;
Put_Line ("Part 1 =" & Natural'Image (Max_Doors));
Put_Line ("Part 2 =" & Natural'Image (Room_Count));
end;
end Day20;
|
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Exceptions;
with Ada.Text_IO; use Ada.Text_IO;
with TOML; use TOML;
with TOML.File_IO;
package body Offmt_Lib.Storage is
From_TOML_Error : exception;
function To_TOML (List : Trace_Element_Lists.List) return TOML_Value;
function To_TOML (Elt : Trace_Element) return TOML_Value;
function To_TOML (T : Trace) return TOML_Value;
function From_TOML (Val : TOML_Value) return Trace_Map;
function From_TOML (Val : TOML_Value) return Trace_Element;
function From_TOML (Val : TOML_Value) return Trace;
function From_TOML (Val : TOML_Value) return Trace_Element_Lists.List;
-------------
-- To_TOML --
-------------
function To_TOML (Elt : Trace_Element) return TOML_Value is
begin
case Elt.Kind is
when Plain_String =>
return Create_String (Elt.Str);
when Format_String =>
declare
Table : constant TOML_Value := Create_Table;
begin
Table.Set ("kind", Create_String (Elt.Fmt.Kind'Img));
Table.Set ("type", Create_String (Elt.Fmt.Typ'Img));
Table.Set ("expr", Create_String (Elt.Fmt.Expression));
return Table;
end;
end case;
end To_TOML;
-------------
-- To_TOML --
-------------
function To_TOML (List : Trace_Element_Lists.List) return TOML_Value is
Arr : constant TOML_Value := Create_Array;
begin
for Elt of List loop
Arr.Append (To_TOML (Elt));
end loop;
return Arr;
end To_TOML;
-------------
-- To_TOML --
-------------
function To_TOML (T : Trace) return TOML_Value is
Table : constant TOML_Value := Create_Table;
begin
Table.Set ("original", Create_String (T.Original));
Table.Set ("format_list", To_TOML (T.List));
return Table;
end To_TOML;
-----------
-- Store --
-----------
function Store (Map : Trace_Map; Filename : String) return Store_Result is
Table : constant TOML_Value := Create_Table;
File_Out : File_Type;
begin
Ada.Text_IO.Create (File_Out, Out_File, Filename);
if not Is_Open (File_Out) then
return (Success => False,
Msg => To_Unbounded_String ("Cannot open '" &
Filename & "' for output"));
end if;
for T of Map loop
Table.Set (T.Id'Img, To_TOML (T));
end loop;
TOML.File_IO.Dump_To_File (Table, File_Out);
Ada.Text_IO.Close (File_Out);
return (Success => True);
end Store;
---------------
-- From_TOML --
---------------
function From_TOML (Val : TOML_Value) return Trace_Element is
begin
if Val.Kind = TOML_String then
return (Kind => Plain_String, Str => Val.As_Unbounded_String);
elsif Val.Kind = TOML_Table then
declare
Fmt : Format;
begin
Fmt.Kind := Format_Kind'Value (Val.Get ("kind").As_String);
Fmt.Typ := Format_Type'Value (Val.Get ("type").As_String);
Fmt.Expression := Val.Get ("expr").As_Unbounded_String;
return (Kind => Format_String, Fmt => Fmt);
end;
else
raise From_TOML_Error
with "Invalid TOML_Kind for Trace_Element: " & Val.Kind'Img;
end if;
end From_TOML;
---------------
-- From_TOML --
---------------
function From_TOML (Val : TOML_Value) return Trace_Element_Lists.List is
Result : Trace_Element_Lists.List;
begin
if Val.Kind /= TOML_Array then
raise From_TOML_Error with
"Invalid TOML_Kind for Trace_Element_List: " & Val.Kind'Img;
else
for Index in 1 .. Val.Length loop
Result.Append (From_TOML (Val.Item (Index)));
end loop;
end if;
return Result;
end From_TOML;
---------------
-- From_TOML --
---------------
function From_TOML (Val : TOML_Value) return Trace is
Result : Trace;
begin
if Val.Kind /= TOML_Table then
raise From_TOML_Error with
"Invalid TOML_Kind for Trace: " & Val.Kind'Img;
else
Result.Original := Val.Get ("original").As_Unbounded_String;
Result.List := From_TOML (Val.Get ("format_list"));
end if;
return Result;
end From_TOML;
---------------
-- From_TOML --
---------------
function From_TOML (Val : TOML_Value) return Trace_Map is
Result : Trace_Map;
begin
if Val.Kind /= TOML_Table then
raise From_TOML_Error with
"Invalid TOML_Kind for Trace_Map: " & Val.Kind'Img;
else
for Elt of Val.Iterate_On_Table loop
declare
Id : constant Trace_ID := Trace_ID'Value (To_String (Elt.Key));
T : Trace := From_TOML (Elt.Value);
begin
T.Id := Id;
Result.Include (Id, T);
end;
end loop;
end if;
return Result;
end From_TOML;
----------
-- Load --
----------
function Load (Filename : String) return Load_Result is
TOML_Result : constant TOML.Read_Result :=
TOML.File_IO.Load_File (Filename);
begin
if TOML_Result.Success then
declare
Map : constant Trace_Map := From_TOML (TOML_Result.Value);
begin
return (Success => True, Map => Map);
exception
when E : From_TOML_Error =>
return (Success => False,
Msg => To_Unbounded_String
(Ada.Exceptions.Exception_Message (E)));
end;
else
return (Success => False, Msg => TOML_Result.Message);
end if;
end Load;
end Offmt_Lib.Storage;
|
-----------------------------------------------------------------------
-- sqlbench-simple -- Simple SQL benchmark
-- Copyright (C) 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.Strings.Unbounded;
with ADO.Statements;
with Util.Files;
package body Sqlbench.Simple is
use Ada.Strings.Unbounded;
generic
LIMIT : Positive;
procedure Select_Table_N (Context : in out Context_Type);
procedure Select_Table_N (Context : in out Context_Type) is
DB : constant ADO.Sessions.Master_Session := Context.Get_Session;
Count : Natural;
Stmt : ADO.Statements.Query_Statement
:= DB.Create_Statement ("SELECT * FROM test_simple LIMIT " & Positive'Image (LIMIT));
begin
for I in 1 .. Context.Repeat loop
Stmt.Execute;
Count := 0;
while Stmt.Has_Elements loop
Count := Count + 1;
Stmt.Next;
end loop;
if Count /= LIMIT then
raise Benchmark_Error with "Invalid result count:" & Natural'Image (Count);
end if;
end loop;
end Select_Table_N;
procedure Do_Static (Context : in out Context_Type);
procedure Select_Static (Context : in out Context_Type);
procedure Connect_Select_Static (Context : in out Context_Type);
procedure Drop_Create (Context : in out Context_Type);
procedure Insert (Context : in out Context_Type);
procedure Select_Table_1 is new Select_Table_N (1);
procedure Select_Table_10 is new Select_Table_N (10);
procedure Select_Table_100 is new Select_Table_N (100);
procedure Select_Table_500 is new Select_Table_N (500);
procedure Select_Table_1000 is new Select_Table_N (1000);
Create_SQL : Ada.Strings.Unbounded.Unbounded_String;
procedure Register (Tests : in out Context_Type) is
Driver : constant String := Tests.Get_Driver_Name;
begin
if Driver /= "sqlite" and Driver /= "postgresql" then
Tests.Register (Do_Static'Access, "DO 1");
end if;
Tests.Register (Select_Static'Access, "SELECT 1");
Tests.Register (Connect_Select_Static'Access, "CONNECT; SELECT 1; CLOSE");
Tests.Register (Drop_Create'Access, "DROP table; CREATE table", 1);
Tests.Register (Insert'Access, "INSERT INTO table", 10);
Tests.Register (Select_Table_1'Access, "SELECT * FROM table LIMIT 1");
Tests.Register (Select_Table_10'Access, "SELECT * FROM table LIMIT 10");
Tests.Register (Select_Table_100'Access, "SELECT * FROM table LIMIT 100");
Tests.Register (Select_Table_500'Access, "SELECT * FROM table LIMIT 500");
Tests.Register (Select_Table_1000'Access, "SELECT * FROM table LIMIT 1000");
Util.Files.Read_File (Tests.Get_Config_Path ("create-table.sql"), Create_SQL);
end Register;
procedure Do_Static (Context : in out Context_Type) is
Stmt : ADO.Statements.Query_Statement := Context.Session.Create_Statement ("DO 1");
begin
for I in 1 .. Context.Repeat loop
Stmt.Execute;
end loop;
end Do_Static;
procedure Select_Static (Context : in out Context_Type) is
Stmt : ADO.Statements.Query_Statement := Context.Session.Create_Statement ("SELECT 1");
begin
for I in 1 .. Context.Repeat loop
Stmt.Execute;
end loop;
end Select_Static;
procedure Connect_Select_Static (Context : in out Context_Type) is
begin
for I in 1 .. Context.Repeat loop
declare
DB : constant ADO.Sessions.Session := Context.Factory.Get_Session;
Stmt : ADO.Statements.Query_Statement := DB.Create_Statement ("SELECT 1");
begin
Stmt.Execute;
end;
end loop;
end Connect_Select_Static;
procedure Drop_Create (Context : in out Context_Type) is
Drop_Stmt : ADO.Statements.Query_Statement
:= Context.Session.Create_Statement ("DROP TABLE test_simple");
Create_Stmt : ADO.Statements.Query_Statement
:= Context.Session.Create_Statement (To_String (Create_SQL));
begin
for I in 1 .. Context.Repeat loop
begin
Drop_Stmt.Execute;
Context.Session.Commit;
exception
when ADO.Statements.SQL_Error =>
Context.Session.Rollback;
end;
Context.Session.Begin_Transaction;
Create_Stmt.Execute;
Context.Session.Commit;
Context.Session.Begin_Transaction;
end loop;
end Drop_Create;
procedure Insert (Context : in out Context_Type) is
Stmt : ADO.Statements.Query_Statement
:= Context.Session.Create_Statement ("INSERT INTO test_simple (value) VALUES (1)");
begin
for I in 1 .. Context.Repeat loop
Stmt.Execute;
end loop;
Context.Session.Commit;
end Insert;
end Sqlbench.Simple;
|
pragma Ada_2005;
pragma Style_Checks (Off);
pragma Warnings (Off);
with Interfaces.C; use Interfaces.C;
with glib;
with glib.Values;
with System;
with System;
package GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstatomicqueue_h is
-- GStreamer
-- * Copyright (C) 2009-2010 Edward Hervey <bilboed@bilboed.com>
-- * (C) 2011 Wim Taymans <wim.taymans@gmail.com>
-- *
-- * gstatomicqueue.h:
-- *
-- * This library is free software; you can redistribute it and/or
-- * modify it under the terms of the GNU Library General Public
-- * License as published by the Free Software Foundation; either
-- * version 2 of the License, 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. See the GNU
-- * Library General Public License for more details.
-- *
-- * You should have received a copy of the GNU Library General Public
-- * License along with this library; if not, write to the
-- * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-- * Boston, MA 02111-1307, USA.
--
--*
-- * GstAtomicQueue:
-- *
-- * Opaque atomic data queue.
-- *
-- * Use the acessor functions to get the stored values.
-- *
-- * Since: 0.10.33
--
-- skipped empty struct u_GstAtomicQueue
-- skipped empty struct GstAtomicQueue
function gst_atomic_queue_new (initial_size : GLIB.guint) return System.Address; -- gst/gstatomicqueue.h:42
pragma Import (C, gst_atomic_queue_new, "gst_atomic_queue_new");
procedure gst_atomic_queue_ref (queue : System.Address); -- gst/gstatomicqueue.h:44
pragma Import (C, gst_atomic_queue_ref, "gst_atomic_queue_ref");
procedure gst_atomic_queue_unref (queue : System.Address); -- gst/gstatomicqueue.h:45
pragma Import (C, gst_atomic_queue_unref, "gst_atomic_queue_unref");
procedure gst_atomic_queue_push (queue : System.Address; data : System.Address); -- gst/gstatomicqueue.h:47
pragma Import (C, gst_atomic_queue_push, "gst_atomic_queue_push");
function gst_atomic_queue_pop (queue : System.Address) return System.Address; -- gst/gstatomicqueue.h:48
pragma Import (C, gst_atomic_queue_pop, "gst_atomic_queue_pop");
function gst_atomic_queue_peek (queue : System.Address) return System.Address; -- gst/gstatomicqueue.h:49
pragma Import (C, gst_atomic_queue_peek, "gst_atomic_queue_peek");
function gst_atomic_queue_length (queue : System.Address) return GLIB.guint; -- gst/gstatomicqueue.h:51
pragma Import (C, gst_atomic_queue_length, "gst_atomic_queue_length");
end GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstatomicqueue_h;
|
package body scanner.DFA is
function YYText return Wide_Wide_String is
Aux : constant Wide_Wide_String (1 .. YY_CP - YY_BP)
:= Wide_Wide_String (YY_Ch_Buf.Data (YY_BP .. YY_CP - 1));
begin
return Aux;
end YYText;
-- returns the length of the matched text
function YYLength return Integer is
begin
return YY_CP - YY_BP;
end YYLength;
-- done after the current pattern has been matched and before the
-- corresponding action - sets up yytext
procedure YY_DO_BEFORE_ACTION is
begin
YYText_Ptr := YY_BP;
YY_C_Buf_P := YY_CP;
end YY_DO_BEFORE_ACTION;
function Previous
(Data : CH_Buf_Type; Index : Integer) return Wide_Wide_Character
is
Aux : constant Integer := Index - 1;
begin
return Data.Data (Aux);
end Previous;
procedure Next
(Data : CH_Buf_Type;
Index : in out Integer;
Code : out Wide_Wide_Character) is
begin
Code := Data.Data (Index);
Index := Index + 1;
end Next;
end scanner.DFA;
|
-----------------------------------------------------------------------
-- gen-model-tables -- Database table model representation
-- Copyright (C) 2009 - 2021 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Ada.Strings.Unbounded.Hash;
with Gen.Model.List;
with Gen.Model.Packages;
with Gen.Model.Mappings;
with Gen.Model.Operations;
package Gen.Model.Tables is
type Table_Definition is tagged;
type Table_Definition_Access is access all Table_Definition'Class;
-- ------------------------------
-- Column Definition
-- ------------------------------
type Column_Definition is new Definition with record
Number : Natural := 0;
Table : Table_Definition_Access;
Bean : UBO.Object;
-- The column type name.
Type_Name : UString;
-- The SQL type associated with the column.
Sql_Type : UString;
-- The SQL name associated with the column.
Sql_Name : UString;
-- The SQL length for strings.
Sql_Length : Positive := 255;
-- Whether the column must not be null in the database
Not_Null : Boolean := False;
-- Whether the column must be unique
Unique : Boolean := False;
-- True if this column is the optimistic locking version column.
Is_Version : Boolean := False;
-- True if this column is the primary key column.
Is_Key : Boolean := False;
-- True if the column can be read by the application.
Is_Readable : Boolean := True;
-- True if the column is included in the insert statement
Is_Inserted : Boolean := True;
-- True if the column is included in the update statement
Is_Updated : Boolean := True;
-- True if the column is auditable (generate code to track changes).
Is_Auditable : Boolean := False;
-- True if the Ada mapping must use the foreign key type.
Use_Foreign_Key_Type : Boolean := False;
-- The class generator to use for this column.
Generator : UBO.Object;
-- The type mapping of the column.
Type_Mapping : Gen.Model.Mappings.Mapping_Definition_Access;
end record;
type Column_Definition_Access is access all Column_Definition'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : Column_Definition;
Name : String) return UBO.Object;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Column_Definition);
-- Validate the definition by checking and reporting problems to the logger interface.
overriding
procedure Validate (Def : in out Column_Definition;
Log : in out Util.Log.Logging'Class);
-- Returns true if the column type is a basic type.
function Is_Basic_Type (From : Column_Definition) return Boolean;
-- Returns true if the column is using a variable length (ex: a string).
function Is_Variable_Length (From : Column_Definition) return Boolean;
-- Returns the column type.
function Get_Type (From : Column_Definition) return String;
-- Set the column type.
procedure Set_Type (Into : in out Column_Definition;
Name : in String);
-- Set the SQL length of the column.
procedure Set_Sql_Length (Into : in out Column_Definition;
Value : in String;
Log : in out Util.Log.Logging'Class);
-- Returns the column type mapping.
function Get_Type_Mapping (From : in Column_Definition)
return Gen.Model.Mappings.Mapping_Definition_Access;
package Column_List is new Gen.Model.List (T => Column_Definition,
T_Access => Column_Definition_Access);
-- ------------------------------
-- Association Definition
-- ------------------------------
type Association_Definition is new Column_Definition with private;
type Association_Definition_Access is access all Association_Definition'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : Association_Definition;
Name : String) return UBO.Object;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Association_Definition);
package Operation_List is
new Gen.Model.List (T => Gen.Model.Operations.Operation_Definition,
T_Access => Gen.Model.Operations.Operation_Definition_Access);
package Table_Vectors is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Table_Definition_Access);
-- ------------------------------
-- Table Definition
-- ------------------------------
type Table_Definition is new Mappings.Mapping_Definition with record
Members : aliased Column_List.List_Definition;
Members_Bean : UBO.Object;
Auditables : aliased Column_List.List_Definition;
Auditables_Bean : UBO.Object;
Operations : aliased Operation_List.List_Definition;
Operations_Bean : UBO.Object;
Parent : Table_Definition_Access;
Parent_Name : UString;
Package_Def : Gen.Model.Packages.Package_Definition_Access;
Type_Name : UString;
Pkg_Name : UString;
Table_Name : UString;
Version_Column : Column_Definition_Access;
Id_Column : Column_Definition_Access;
-- The number of <<PK>> columns found.
Key_Count : Natural := 0;
Has_Associations : Boolean := False;
-- The list of tables that this table depends on.
Dependencies : Table_Vectors.Vector;
-- Controls whether the <tt>Vector</tt> type and the <tt>List</tt> procedure must
-- be generated.
Has_List : Boolean := True;
-- Mark flag used by the dependency calculation.
Has_Mark : Boolean := False;
-- Whether the bean type is a limited type or not.
Is_Limited : Boolean := False;
-- Whether the serialization operation have to be generated.
Is_Serializable : Boolean := False;
-- Whether the table contains auditable fields.
Is_Auditable : Boolean := False;
end record;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : Table_Definition;
Name : String) return UBO.Object;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Table_Definition);
-- Validate the definition by checking and reporting problems to the logger interface.
overriding
procedure Validate (Def : in out Table_Definition;
Log : in out Util.Log.Logging'Class);
-- Initialize the table definition instance.
overriding
procedure Initialize (O : in out Table_Definition);
-- Collect the dependencies to other tables.
procedure Collect_Dependencies (O : in out Table_Definition);
type Dependency_Type is (NONE, FORWARD, BACKWARD); -- CIRCULAR is not yet managed.
-- Get the dependency between the two tables.
-- Returns NONE if both table don't depend on each other.
-- Returns FORWARD if the <tt>Left</tt> table depends on <tt>Right</tt>.
-- Returns BACKWARD if the <tt>Right</tt> table depends on <tt>Left</tt>.
function Depends_On (Left, Right : in Table_Definition_Access) return Dependency_Type;
-- Create a table with the given name.
function Create_Table (Name : in UString) return Table_Definition_Access;
-- Create a table column with the given name and add it to the table.
procedure Add_Column (Table : in out Table_Definition;
Name : in UString;
Column : out Column_Definition_Access);
-- Create a table association with the given name and add it to the table.
procedure Add_Association (Table : in out Table_Definition;
Name : in UString;
Assoc : out Association_Definition_Access);
-- Create an operation with the given name and add it to the table.
procedure Add_Operation (Table : in out Table_Definition;
Name : in UString;
Operation : out Model.Operations.Operation_Definition_Access);
-- Set the table name and determines the package name.
procedure Set_Table_Name (Table : in out Table_Definition;
Name : in String);
package Table_Map is
new Ada.Containers.Hashed_Maps (Key_Type => UString,
Element_Type => Table_Definition_Access,
Hash => Ada.Strings.Unbounded.Hash,
Equivalent_Keys => "=");
subtype Table_Cursor is Table_Map.Cursor;
-- Returns true if the table cursor contains a valid table
function Has_Element (Position : Table_Cursor) return Boolean
renames Table_Map.Has_Element;
-- Returns the table definition.
function Element (Position : Table_Cursor) return Table_Definition_Access
renames Table_Map.Element;
-- Move the iterator to the next table definition.
procedure Next (Position : in out Table_Cursor)
renames Table_Map.Next;
package Table_List is new Gen.Model.List (T => Definition,
T_Access => Definition_Access);
private
type Association_Definition is new Column_Definition with null record;
end Gen.Model.Tables;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- 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 Orka.Transforms.SIMD_Vectors;
generic
with package Vector_Transforms is new Orka.Transforms.SIMD_Vectors (<>);
type Matrix_Type is array (Index_Homogeneous) of Vector_Transforms.Vector_Type;
with function Multiply_Matrices (Left, Right : Matrix_Type) return Matrix_Type;
with function Multiply_Vector
(Left : Matrix_Type;
Right : Vector_Transforms.Vector_Type) return Vector_Transforms.Vector_Type;
with function Transpose_Matrix (Matrix : Matrix_Type) return Matrix_Type;
package Orka.Transforms.SIMD_Matrices is
pragma Pure;
package Vectors renames Vector_Transforms;
function "-" (Elements : Vectors.Point) return Vectors.Point renames Vectors."-";
subtype Element_Type is Vectors.Element_Type;
subtype Vector_Type is Vectors.Vector_Type;
subtype Matrix4 is Matrix_Type;
subtype Vector4 is Vector_Type;
Identity_Matrix : constant Matrix_Type :=
((1.0, 0.0, 0.0, 0.0),
(0.0, 1.0, 0.0, 0.0),
(0.0, 0.0, 1.0, 0.0),
(0.0, 0.0, 0.0, 1.0));
function Zero_Point return Vectors.Point is (Vectors.Zero_Point);
-- Return a zero vector that indicates a point. The fourth (W) component
-- is 1.
function Diagonal (Elements : Vector_Type) return Matrix_Type;
-- Return a matrix with the main diagonal equal to the given
-- vector and zeros in all other elements
function Main_Diagonal (Matrix : Matrix_Type) return Vector_Type;
-- Return a vector with the elements of the main diagonal
function Trace (Matrix : Matrix_Type) return Element_Type;
-- Return the trace of the (square) matrix
--
-- The trace is a linear mapping:
--
-- tr(A + B) = tr(A) + tr(B)
-- tr(c * A) = c * tr(A) where c is a scalar (tr(A*B) /= tr(A) * tr(B))
--
-- And invariant under cyclic permutation:
--
-- tr(A * B * C) = tr(C * A * B)
-- Linear transform: a transform in which vector addition and scalar
-- multiplication is preserved.
-- Affine transform: a transform that includes a linear transform and
-- a translation. Parallelism of lines remain unchanged, but lengths
-- and angles may not. A concatenation of affine transforms is affine.
--
-- Orthogonal matrix: the inverse of the matrix is equal to the transpose.
-- A concatenation of orthogonal matrices is orthogonal.
function T (Offset : Vector_Type) return Matrix_Type;
function T (Offset : Vectors.Point) return Matrix_Type;
-- Translate points by the given amount
--
-- Matrix is affine.
--
-- The inverse T^-1 (t) = T (-t).
function Rx (Angle : Element_Type) return Matrix_Type;
-- Rotate around the x-axis by the given amount in radians
--
-- Matrix is orthogonal and affine.
--
-- The inverse Rx^-1 (o) = Rx (-o) = (Rx (o))^T.
function Ry (Angle : Element_Type) return Matrix_Type;
-- Rotate around the y-axis by the given amount in radians
--
-- Matrix is orthogonal and affine.
--
-- The inverse Ry^-1 (o) = Ry (-o) = (Ry (o))^T.
function Rz (Angle : Element_Type) return Matrix_Type;
-- Rotate around the z-axis by the given amount in radians
--
-- Matrix is orthogonal and affine.
--
-- The inverse Rz^-1 (o) = Rz (-o) = (Rz (o))^T.
function R (Axis : Vector_Type; Angle : Element_Type) return Matrix_Type;
-- Rotate around the given axis by the given amount in radians
--
-- Matrix is orthogonal and affine.
--
-- The inverse is R^-1 (a, o) = R (a, -o) = (R (a, o))^T.
function R (Quaternion : Vector_Type) return Matrix_Type;
-- Converts a quaternion to a rotation matrix
--
-- Note: the quaternion must be a unit quaternion (normalized).
function S (Factors : Vector_Type) return Matrix_Type;
-- Scale points by the given amount in the x-, y-, and z-axis
--
-- If all axes are scaled by the same amount, then the matrix is
-- affine.
--
-- The inverse is S^-1 (s) = S (1/s_x, 1/s_y, 1/s_z).
function "*" (Left, Right : Matrix_Type) return Matrix_Type renames Multiply_Matrices;
function "*"
(Left : Matrix_Type;
Right : Vector_Type) return Vector_Type renames Multiply_Vector;
function "*" (Left : Vector_Type; Right : Matrix_Type) return Vector_Type;
-- Return sum of inner products
function "+" (Offset : Vector_Type; Matrix : Matrix_Type) return Matrix_Type is
(T (Offset) * Matrix);
-- Add a translation transformation to the matrix
function "*" (Factor : Element_Type; Matrix : Matrix_Type) return Matrix_Type is
(S ((Factor, Factor, Factor, 1.0)) * Matrix);
-- Add a scale transformation to the matrix
function Transpose (Matrix : Matrix_Type) return Matrix_Type renames Transpose_Matrix;
-- Return the transpose of the matrix
function Outer (Left, Right : Vector_Type) return Matrix_Type;
function R
(Axis : Vector_Type;
Angle : Element_Type;
Point : Vectors.Point) return Matrix_Type
is (T (Point) * R (Axis, Angle) * T (-Point));
-- Return a rotation matrix with the center of rotation at the given point
function R
(Quaternion : Vector_Type;
Point : Vectors.Point) return Matrix_Type
is (T (Point) * R (Quaternion) * T (-Point));
-- Return rotation matrix using a quaternion with the center of rotation at the given point
--
-- The quaternion must be a unit quaternion (normalized).
function Rx (Angle : Element_Type; Point : Vectors.Point) return Matrix_Type is
(T (Point) * Rx (Angle) * T (-Point));
-- Add a rotation transformation around the X axis with the center
-- of rotation at the given point to the matrix
function Ry (Angle : Element_Type; Point : Vectors.Point) return Matrix_Type is
(T (Point) * Ry (Angle) * T (-Point));
-- Add a rotation transformation around the Y axis with the center
-- of rotation at the given point to the matrix
function Rz (Angle : Element_Type; Point : Vectors.Point) return Matrix_Type is
(T (Point) * Rz (Angle) * T (-Point));
-- Add a rotation transformation around the Z axis with the center
-- of rotation at the given point to the matrix
----------------------------------------------------------------------------
use type Element_Type;
function FOV (Width, Distance : Element_Type) return Element_Type;
-- Return an appropriate field of view in radians for a given screen
-- width and view distance in physical units (mm/inches)
--
-- For example, for a 35 mm frame (which is 36 mm wide) and a
-- 50 mm standard lens, the function gives ~ 39 degrees.
function Finite_Perspective (FOV, Aspect, Z_Near, Z_Far : Element_Type) return Matrix_Type
with Pre => FOV > 0.0 and Aspect > 0.0 and Z_Near > 0.0 and Z_Far > Z_Near;
-- Return a matrix providing perspective projection with a depth
-- range of [0, 1]
--
-- The vertical field of view must be in radians.
function Infinite_Perspective (FOV, Aspect, Z_Near : Element_Type) return Matrix_Type
with Pre => FOV > 0.0 and Aspect > 0.0 and Z_Near > 0.0;
-- Return a matrix providing perspective projection with Z_far to
-- infinite and a depth range of [0, 1]
--
-- The vertical field of view must be in radians.
function Infinite_Perspective_Reversed_Z
(FOV, Aspect, Z_Near : Element_Type) return Matrix_Type
with Pre => FOV > 0.0 and Aspect > 0.0 and Z_Near > 0.0;
-- Return a matrix providing perspective projection with Z_far to
-- infinite and a depth range of [1, 0]
--
-- The vertical field of view must be in radians.
function Orthographic (X_Mag, Y_Mag, Z_Near, Z_Far : Element_Type) return Matrix_Type
with Pre => Z_Near >= 0.0 and Z_Far >= 0.0;
-- Return a matrix providing orthographic projection with a depth
-- range of [0, 1]
end Orka.Transforms.SIMD_Matrices;
|
-- Taken from #2943 submitted by @koenmeersman
with Ada.Text_IO;
separate (Buffer);
package body Test is
procedure Inner is separate;
begin
null;
end Test;
|
------------------------------------------------------------------------------
-- G E L A A S I S --
-- ASIS implementation for Gela project, a portable Ada compiler --
-- http://gela.ada-ru.org --
-- - - - - - - - - - - - - - - - --
-- Read copyright and license at the end of this file --
------------------------------------------------------------------------------
-- $Revision: 209 $ $Date: 2013-11-30 21:03:24 +0200 (Сб., 30 нояб. 2013) $:
with XASIS.Utils;
with XASIS.Types;
with Asis.Gela.Classes;
with Asis.Declarations;
with Asis.Gela.Lists;
with Asis.Gela.Elements;
with Asis.Gela.Elements.Decl;
with Asis.Gela.Elements.Expr;
with Asis.Gela.Element_Utils;
with Asis.Gela.Elements.Def_Names;
with Asis.Gela.Elements.Defs.Types;
package body Asis.Gela.Implicit is
package S renames Standard;
procedure Process_Standard (Unit : Asis.Compilation_Unit);
procedure Find_Declaration
(Unit : in Asis.Compilation_Unit;
Result : out Asis.Declaration;
Name : in Program_Text);
procedure Init_Implicit
(Element : in out Elements.Base_Element_Node'Class;
Parent : in Asis.Element);
function Is_Root (Decl : Asis.Declaration) return S.Boolean;
procedure Make_Operation
(Point : in out Visibility.Point;
Decl : Asis.Declaration;
Name : Wide_String;
Args : Positive := 2;
Result : Asis.Declaration := Asis.Nil_Element;
Right : Asis.Declaration := Asis.Nil_Element;
Left : Asis.Declaration := Asis.Nil_Element;
Dispatch : Boolean := False);
function Need_Logical (Tipe, Was : Classes.Type_Info) return S.Boolean;
function Need_Ordering (Tipe, Was : Classes.Type_Info) return S.Boolean;
procedure Hide_Implementation_Defined
(Decl : in Asis.Declaration);
procedure Hide_Implementation_Defined
(Unit : in Asis.Compilation_Unit;
Name : in Program_Text);
procedure Make_Operations
(Tipe : in Classes.Type_Info;
Decl : in Asis.Declaration;
Point : in out Visibility.Point;
Was : in Classes.Type_Info);
The_System_Address : Asis.Declaration;
The_System_Bit_Order : Asis.Declaration;
The_Task_Id : Asis.Declaration;
The_Exception_Id : Asis.Declaration;
The_Exception_Occurrence : Asis.Declaration;
The_Root_Storage_Pool : Asis.Declaration;
The_Tag : Asis.Declaration;
The_Root_Stream_Type : Asis.Declaration;
The_Universal_Integer : Asis.Declaration;
The_Universal_Real : Asis.Declaration;
The_Universal_Fixed : Asis.Declaration;
The_Universal_Access : Asis.Declaration;
The_Root_Integer : Asis.Declaration;
The_Root_Real : Asis.Declaration;
The_String : Asis.Declaration;
The_Wide_String : Asis.Declaration;
The_Wide_Wide_String : Asis.Declaration;
The_Float : Asis.Declaration;
The_Boolean : Asis.Declaration;
The_Duration : Asis.Declaration;
The_Integer : Asis.Declaration;
The_Natural : Asis.Declaration;
The_Wide_Character : Asis.Declaration;
The_Wide_Wide_Character : Asis.Declaration;
The_Character : Asis.Declaration;
----------------------
-- Create_Root_Type --
----------------------
procedure Create_Root_Type
(Unit : in Asis.Compilation_Unit;
Kind : in Root_Type_Kinds;
Result : out Asis.Declaration;
Before : in Program_Text)
is
use Asis.Gela.Elements.Decl;
use Asis.Gela.Elements.Defs.Types;
The_Unit : constant Asis.Declaration :=
Unit_Declaration (Unit.all);
Root_Definition : constant Root_Type_Ptr := new Root_Type_Node;
Root_Declaration : constant Ordinary_Type_Declaration_Ptr :=
new Ordinary_Type_Declaration_Node;
begin
Result := Element (Root_Declaration);
Init_Implicit (Root_Declaration.all, The_Unit);
Set_Type_Declaration_View (Root_Declaration.all,
Element (Root_Definition));
Set_Declaration_Origin (Root_Declaration.all,
An_Implicit_Predefined_Declaration);
Init_Implicit (Root_Definition.all, Result);
Set_Root_Type_Kind (Root_Definition.all, Kind);
Element_Utils.Add_To_Visible (The_Unit, Result, Before);
end Create_Root_Type;
----------------------
-- Find_Declaration --
----------------------
procedure Find_Declaration
(Unit : in Asis.Compilation_Unit;
Result : out Asis.Declaration;
Name : in Program_Text)
is
use Asis.Declarations;
The_Unit : constant Asis.Declaration := Unit_Declaration (Unit.all);
Items : constant Asis.Declarative_Item_List :=
Visible_Part_Declarative_Items (The_Unit);
begin
for I in Items'Range loop
if Element_Kind (Items (I).all) = A_Declaration
and then XASIS.Utils.Has_Defining_Name (Items (I), Name)
then
Result := Items (I);
return;
end if;
end loop;
end Find_Declaration;
------------------
-- Hide_Element --
------------------
procedure Hide_Element (Item : Asis.Expression) is
use Asis.Gela.Elements;
begin
if Assigned (Item) then
Set_Is_Part_Of_Implicit (Base_Element_Node (Item.all), True);
end if;
end Hide_Element;
---------------------------------
-- Hide_Implementation_Defined --
---------------------------------
procedure Hide_Implementation_Defined (Decl : Asis.Declaration) is
Exp : Asis.Expression;
Def : Asis.Definition;
begin
case Declaration_Kind (Decl.all) is
when An_Ordinary_Type_Declaration
| A_Subtype_Declaration=>
Def := Type_Declaration_View (Decl.all);
case Definition_Kind (Def.all) is
when A_Subtype_Indication =>
Def := Subtype_Constraint (Def.all);
Hide_Element (Lower_Bound (Def.all));
Hide_Element (Upper_Bound (Def.all));
when A_Type_Definition =>
case Type_Definition_Kind (Def.all) is
when An_Enumeration_Type_Definition =>
declare
List : constant Asis.Declaration_List :=
Enumeration_Literal_Declarations (Def.all);
begin
for J in List'Range loop
Hide_Element (List (J));
end loop;
end;
when A_Signed_Integer_Type_Definition =>
Def := Integer_Constraint (Def.all);
Exp := Lower_Bound (Def.all);
if Expression_Kind (Exp.all) /= An_Integer_Literal then
Hide_Element (Exp);
end if;
Exp := Upper_Bound (Def.all);
if Expression_Kind (Exp.all) /= An_Integer_Literal then
Hide_Element (Exp);
end if;
when A_Modular_Type_Definition =>
Hide_Element (Mod_Static_Expression (Def.all));
when A_Floating_Point_Definition =>
Hide_Element (Digits_Expression (Def.all));
Def := Real_Range_Constraint (Def.all);
if Assigned (Def) then
Hide_Element (Lower_Bound (Def.all));
Hide_Element (Upper_Bound (Def.all));
end if;
when An_Ordinary_Fixed_Point_Definition =>
Hide_Element (Delta_Expression (Def.all));
Def := Real_Range_Constraint (Def.all);
if Assigned (Def) then
Hide_Element (Lower_Bound (Def.all));
Hide_Element (Upper_Bound (Def.all));
end if;
when A_Decimal_Fixed_Point_Definition =>
Hide_Element (Digits_Expression (Def.all));
Hide_Element (Delta_Expression (Def.all));
Def := Real_Range_Constraint (Def.all);
if Assigned (Def) then
Hide_Element (Lower_Bound (Def.all));
Hide_Element (Upper_Bound (Def.all));
end if;
when others =>
raise Internal_Error;
end case;
when others =>
raise Internal_Error;
end case;
when A_Constant_Declaration
| An_Integer_Number_Declaration
| A_Real_Number_Declaration =>
Hide_Element (Initialization_Expression (Decl.all));
when others =>
raise Internal_Error;
end case;
end Hide_Implementation_Defined;
---------------------------------
-- Hide_Implementation_Defined --
---------------------------------
procedure Hide_Implementation_Defined
(Unit : in Asis.Compilation_Unit;
Name : in Program_Text)
is
Decl : Asis.Declaration;
begin
Find_Declaration (Unit, Decl, Name);
Hide_Implementation_Defined (Decl);
end Hide_Implementation_Defined;
-------------
-- Is_Root --
-------------
function Is_Root (Decl : Asis.Declaration) return S.Boolean is
Def : constant Asis.Definition := Type_Declaration_View (Decl.all);
begin
return Type_Definition_Kind (Def.all) = Asis.A_Root_Type_Definition;
end Is_Root;
-----------------------------
-- Make_Not_Equal_Operator --
-----------------------------
procedure Make_Not_Equal_Operator
(Equal : Asis.Declaration;
Point : in out Visibility.Point)
is
use Asis.Gela.Classes;
use Asis.Declarations;
Dispatch : Boolean := False;
Left_Info : Type_Info;
Right_Info : Type_Info;
List : constant Asis.Parameter_Specification_List :=
Parameter_Profile (Equal);
begin
Left_Info := Type_Of_Declaration (List (1), Equal);
if List'Length = 2 then
Right_Info := Type_Of_Declaration (List (2), Equal);
else
Right_Info := Left_Info;
end if;
if Declaration_Kind (Equal.all)
in A_Procedure_Declaration .. A_Function_Declaration
then
Dispatch := Is_Dispatching_Operation (Equal.all);
end if;
Make_Operation
(Point => Point,
Decl => Equal,
Name => """/=""",
Result => The_Boolean,
Right => Get_Declaration (Right_Info),
Left => Get_Declaration (Left_Info),
Dispatch => Dispatch);
end Make_Not_Equal_Operator;
--------------------
-- Make_Operation --
--------------------
procedure Make_Operation
(Point : in out Visibility.Point;
Decl : Asis.Declaration;
Name : Wide_String;
Args : Positive := 2;
Result : Asis.Declaration := Asis.Nil_Element;
Right : Asis.Declaration := Asis.Nil_Element;
Left : Asis.Declaration := Asis.Nil_Element;
Dispatch : Boolean := False)
is
use Asis.Gela.Lists;
use XASIS.Utils;
use Asis.Gela.Elements;
use Asis.Gela.Element_Utils;
use Asis.Gela.Elements.Decl;
use Asis.Gela.Elements.Defs;
use Asis.Gela.Elements.Expr;
use Asis.Gela.Elements.Def_Names;
D_Name : constant Asis.Element_List := Names (Decl.all);
Img : constant Asis.Program_Text := Declaration_Direct_Name (Decl);
Def : Asis.Element;
Func : constant Function_Declaration_Ptr :=
new Function_Declaration_Node;
Ident : Identifier_Ptr;
Mark : Subtype_Indication_Ptr;
Param : Parameter_Specification_Ptr;
P_Name : Defining_Identifier_Ptr;
F_Name : constant Defining_Operator_Symbol_Ptr :=
new Defining_Operator_Symbol_Node;
Items : Primary_Defining_Name_Lists.List :=
new Primary_Defining_Name_Lists.List_Node;
Params : constant Primary_Parameter_Lists.List :=
new Primary_Parameter_Lists.List_Node;
Overriden : Boolean;
Decl_Is_Type : Boolean := True;
begin
case Declaration_Kind (Decl.all) is
when An_Ordinary_Type_Declaration
| A_Task_Type_Declaration
| A_Protected_Type_Declaration
| A_Private_Type_Declaration
| A_Private_Extension_Declaration
| A_Subtype_Declaration
| A_Formal_Type_Declaration =>
Def := Type_Declaration_View (Decl.all);
Decl_Is_Type := True;
Set_Corresponding_Type (Func.all, Def);
when A_Function_Declaration =>
Decl_Is_Type := False;
Set_Corresponding_Equality_Operator (Func.all, Decl);
Set_Corresponding_Equality_Operator
(Function_Declaration_Node (Decl.all), Asis.Element (Func));
when A_Function_Renaming_Declaration =>
Set_Corresponding_Equality_Operator (Func.all, Decl);
Set_Corresponding_Equality_Operator
(Function_Renaming_Declaration_Node (Decl.all),
Asis.Element (Func));
Decl_Is_Type := False;
when A_Formal_Function_Declaration =>
Decl_Is_Type := False;
when others =>
raise Internal_Error;
end case;
Init_Implicit (Func.all, Decl);
Set_Declaration_Origin (Func.all, An_Implicit_Predefined_Declaration);
Init_Implicit (F_Name.all, Asis.Element (Func));
Set_Defining_Name_Image (F_Name.all, Name);
Elements.Def_Names.Set_Operator_Kind (F_Name.all,
Operator_Kind (Name, Args = 2));
Primary_Defining_Name_Lists.Add (Items.all, Asis.Element (F_Name));
Set_Names (Func.all, Asis.Element (Items));
for I in 1 .. Args loop
Param := new Parameter_Specification_Node;
Init_Implicit (Param.all, Asis.Element (Func));
Set_Trait_Kind (Param.all, An_Ordinary_Trait);
Set_Declaration_Origin (Param.all,
An_Implicit_Predefined_Declaration);
P_Name := new Defining_Identifier_Node;
Init_Implicit (P_Name.all, Asis.Element (Param));
if I = Args then
Set_Defining_Name_Image (P_Name.all, "Right");
else
Set_Defining_Name_Image (P_Name.all, "Left");
end if;
Items := new Primary_Defining_Name_Lists.List_Node;
Primary_Defining_Name_Lists.Add (Items.all, Asis.Element (P_Name));
Set_Names (Param.all, Asis.Element (Items));
Set_Mode_Kind (Param.all, A_Default_In_Mode);
Mark := new Subtype_Indication_Node;
Init_Implicit (Mark.all, Asis.Element (Param));
Ident := new Identifier_Node;
Init_Implicit (Ident.all, Asis.Element (Mark));
if I = Args and then Assigned (Right) then
declare
Right_Img : constant Asis.Program_Text :=
Declaration_Direct_Name (Right);
R_Name : constant Asis.Element_List := Names (Right.all);
begin
Set_Name_Image (Ident.all, Right_Img);
if R_Name'Length > 0 then
Add_Defining_Name (Asis.Element (Ident), R_Name (1));
end if;
Set_Name_Declaration (Asis.Element (Ident), Right);
end;
elsif I /= Args and then Assigned (Left) then
declare
Left_Img : constant Asis.Program_Text :=
Declaration_Direct_Name (Left);
L_Name : constant Asis.Element_List := Names (Left.all);
begin
Set_Name_Image (Ident.all, Left_Img);
if L_Name'Length > 0 then
Add_Defining_Name (Asis.Element (Ident), L_Name (1));
end if;
Set_Name_Declaration (Asis.Element (Ident), Left);
end;
else
Set_Name_Image (Ident.all, Img);
if D_Name'Length > 0 then
Add_Defining_Name (Asis.Element (Ident), D_Name (1));
end if;
Set_Name_Declaration (Asis.Element (Ident), Decl);
end if;
Set_Subtype_Mark (Mark.all, Asis.Element (Ident));
Set_Object_Declaration_Subtype (Param.all, Asis.Element (Mark));
Primary_Parameter_Lists.Add (Params.all, Asis.Element (Param));
end loop;
Set_Parameter_Profile (Func.all, Asis.Element (Params));
Set_Is_Dispatching_Operation (Func.all, Dispatch);
Mark := new Subtype_Indication_Node;
Init_Implicit (Mark.all, Asis.Element (Func));
Ident := new Identifier_Node;
Init_Implicit (Ident.all, Asis.Element (Mark));
if not Assigned (Result) then
Set_Name_Image (Ident.all, Img);
if D_Name'Length > 0 then
Add_Defining_Name (Asis.Element (Ident), D_Name (1));
end if;
Set_Name_Declaration (Asis.Element (Ident), Decl);
else
declare
Result_Img : constant Asis.Program_Text :=
Declaration_Direct_Name (Result);
R_Name : constant Asis.Element_List := Names (Result.all);
begin
Set_Name_Image (Ident.all, Result_Img);
if R_Name'Length > 0 then
Add_Defining_Name (Asis.Element (Ident), R_Name (1));
end if;
Set_Name_Declaration (Asis.Element (Ident), Result);
end;
end if;
Set_Subtype_Mark (Mark.all, Asis.Element (Ident));
Set_Result_Subtype (Func.all, Asis.Element (Mark));
Visibility.New_Implicit_Declaration
(Asis.Element (Func), Point, Decl, Overriden);
if not Overriden and then Decl_Is_Type then
Element_Utils.Add_Type_Operator (Def, Asis.Element (Func));
end if;
end Make_Operation;
---------------------
-- Make_Operations --
---------------------
procedure Make_Operations
(Decl : in Asis.Declaration;
Point : in out Visibility.Point)
is
Tipe : constant Classes.Type_Info :=
Classes.Type_From_Declaration (Decl, Decl);
begin
Make_Operations (Tipe, Decl, Point, Classes.Not_A_Type);
end Make_Operations;
---------------------
-- Make_Operations --
---------------------
procedure Make_Operations
(Tipe : in Classes.Type_Info;
Was : in Classes.Type_Info;
Point : in out Visibility.Point)
is
Decl : Asis.Declaration := Classes.Get_Declaration (Tipe);
begin
Make_Operations (Tipe, Decl, Point, Was);
end Make_Operations;
---------------------
-- Make_Operations --
---------------------
procedure Make_Operations
(Tipe : in Classes.Type_Info;
Decl : in Asis.Declaration;
Point : in out Visibility.Point;
Was : in Classes.Type_Info)
is
use Asis.Gela.Classes;
Comp : Asis.Declaration;
begin
if Is_Universal (Tipe) then
if Is_Fixed_Point (Tipe) then
Make_Operation (Point, Decl, """*""");
Make_Operation (Point, Decl, """/""");
elsif Is_Access (Tipe) then
Make_Operation (Point, Decl, """=""", Result => The_Boolean);
Make_Operation (Point, Decl, """/=""", Result => The_Boolean);
end if;
return;
end if;
if Need_Logical (Tipe, Was) then
Make_Operation (Point, Decl, """and""");
Make_Operation (Point, Decl, """or""");
Make_Operation (Point, Decl, """xor""");
Make_Operation (Point, Decl, """not""", 1);
end if;
if not Is_Limited (Tipe) and Is_Limited (Was) then
Make_Operation (Point, Decl, """=""", Result => The_Boolean,
Dispatch => Is_Tagged (Tipe));
Make_Operation (Point, Decl, """/=""", Result => The_Boolean,
Dispatch => Is_Tagged (Tipe));
end if;
if Need_Ordering (Tipe, Was) then
Make_Operation (Point, Decl, """<""", Result => The_Boolean);
Make_Operation (Point, Decl, """<=""", Result => The_Boolean);
Make_Operation (Point, Decl, """>""", Result => The_Boolean);
Make_Operation (Point, Decl, """>=""", Result => The_Boolean);
end if;
if Is_Numeric (Tipe) and not Is_Numeric (Was) then
Make_Operation (Point, Decl, """+""");
Make_Operation (Point, Decl, """-""");
Make_Operation (Point, Decl, """+""", 1);
Make_Operation (Point, Decl, """-""", 1);
Make_Operation (Point, Decl, """abs""", 1);
end if;
if Is_Array (Tipe, 1) then
Comp := Get_Declaration (Get_Array_Element_Type (Tipe));
if not Is_Limited (Tipe) and Is_Limited (Was) then
Make_Operation (Point, Decl, """&""");
Make_Operation (Point, Decl, """&""", Right => Comp);
Make_Operation (Point, Decl, """&""", Left => Comp);
Make_Operation (Point, Decl, """&""", Right => Comp, Left => Comp);
end if;
end if;
if Is_Integer (Tipe) and not Is_Integer (Was) then
Make_Operation (Point, Decl, """*""");
Make_Operation (Point, Decl, """/""");
Make_Operation (Point, Decl, """mod""");
Make_Operation (Point, Decl, """rem""");
Make_Operation (Point, Decl, """**""", Right => The_Natural);
elsif Is_Float_Point (Tipe) and not Is_Float_Point (Was) then
Make_Operation (Point, Decl, """*""");
Make_Operation (Point, Decl, """/""");
Make_Operation (Point, Decl, """**""", Right => The_Integer);
if Is_Root (Decl) then
Make_Operation (Point, Decl, """*""", Right => The_Root_Integer);
Make_Operation (Point, Decl, """*""", Left => The_Root_Integer);
Make_Operation (Point, Decl, """/""", Right => The_Root_Integer);
end if;
elsif Is_Fixed_Point (Tipe) and not Is_Fixed_Point (Was) then
Make_Operation (Point, Decl, """*""", Right => The_Integer);
Make_Operation (Point, Decl, """*""", Left => The_Integer);
Make_Operation (Point, Decl, """/""", Right => The_Integer);
end if;
end Make_Operations;
------------------
-- Need_Logical --
------------------
function Need_Logical (Tipe, Was : Classes.Type_Info) return S.Boolean is
use Asis.Gela.Classes;
begin
if Is_Boolean (Tipe) and not Is_Boolean (Was) then
return True;
elsif Is_Modular_Integer (Tipe) and not Is_Modular_Integer (Was) then
return True;
elsif Is_Boolean_Array (Tipe) and not Is_Boolean_Array (Was) then
return True;
end if;
return False;
end Need_Logical;
-------------------
-- Need_Ordering --
-------------------
function Need_Ordering (Tipe, Was : Classes.Type_Info) return S.Boolean is
use Asis.Gela.Classes;
begin
if Is_Scalar (Tipe) and not Is_Scalar (Was) then
return True;
elsif Is_Discrete_Array (Tipe) and not Is_Discrete_Array (Was) then
return True;
end if;
return False;
end Need_Ordering;
-------------------
-- Init_Implicit --
-------------------
procedure Init_Implicit
(Element : in out Elements.Base_Element_Node'Class;
Parent : in Asis.Element)
is
use Asis.Gela.Elements;
The_Unit : constant Asis.Compilation_Unit :=
Enclosing_Compilation_Unit (Parent.all);
begin
Set_Enclosing_Element (Element, Parent);
Set_Is_Part_Of_Implicit (Element, True);
Set_Start_Position (Element, (1, 1));
Set_End_Position (Element, (0, 0));
Set_Enclosing_Compilation_Unit (Element, The_Unit);
end Init_Implicit;
----------------------
-- Process_Standard --
----------------------
procedure Process_Standard (Unit : Asis.Compilation_Unit) is
begin
Find_Declaration (Unit, The_String, "String");
Find_Declaration (Unit, The_Wide_String, "Wide_String");
Find_Declaration (Unit, The_Wide_Wide_String, "Wide_Wide_String");
Find_Declaration (Unit, The_Boolean, "Boolean");
Find_Declaration (Unit, The_Integer, "Integer");
Find_Declaration (Unit, The_Natural, "Natural");
Find_Declaration (Unit, The_Duration, "Duration");
Find_Declaration (Unit, The_Float, "Float");
Find_Declaration (Unit, The_Character, "Character");
Find_Declaration (Unit, The_Wide_Character, "Wide_Character");
Find_Declaration (Unit, The_Wide_Wide_Character, "Wide_Wide_Character");
Create_Root_Type (Unit, A_Universal_Integer_Definition,
The_Universal_Integer, "Integer");
Create_Root_Type (Unit, A_Root_Integer_Definition,
The_Root_Integer, "Integer");
Create_Root_Type (Unit, A_Universal_Real_Definition,
The_Universal_Real, "Float");
Create_Root_Type (Unit, A_Universal_Fixed_Definition,
The_Universal_Fixed, "Float");
Create_Root_Type (Unit, A_Root_Real_Definition,
The_Root_Real, "Float");
Create_Root_Type (Unit, A_Universal_Access_Definition,
The_Universal_Access, "Character");
Hide_Implementation_Defined (The_Character);
Hide_Implementation_Defined (The_Wide_Character);
Hide_Implementation_Defined (The_Wide_Wide_Character);
Hide_Implementation_Defined (The_Integer);
Hide_Implementation_Defined (The_Float);
Hide_Implementation_Defined (The_Duration);
XASIS.Types.Initialize
(Universal_Integer => The_Universal_Integer,
Universal_Real => The_Universal_Real,
Universal_Fixed => The_Universal_Fixed,
Universal_Access => The_Universal_Access,
Root_Integer => The_Root_Integer,
Root_Real => The_Root_Real,
String => The_String,
Wide_String => The_Wide_String,
Wide_Wide_String => The_Wide_Wide_String,
Float => The_Float,
Boolean => The_Boolean,
Duration => The_Duration,
Integer => The_Integer,
Natural => The_Natural,
Wide_Wide_Character => The_Wide_Wide_Character,
Wide_Character => The_Wide_Character,
Character => The_Character);
end Process_Standard;
------------------
-- Process_Unit --
------------------
procedure Process_Unit (Unit : Asis.Compilation_Unit) is
use XASIS.Utils;
Name : constant Wide_String := Unit_Full_Name (Unit.all);
begin
if Are_Equal_Identifiers (Name, "Standard") then
Process_Standard (Unit);
elsif Are_Equal_Identifiers (Name, "System") then
Find_Declaration (Unit, The_System_Address, "Address");
Find_Declaration (Unit, The_System_Bit_Order, "Bit_Order");
XASIS.Types.Initialize
(System_Address => The_System_Address,
System_Bit_Order => The_System_Bit_Order);
Hide_Implementation_Defined (Unit, "System_Name");
Hide_Implementation_Defined (Unit, "Min_Int");
Hide_Implementation_Defined (Unit, "Max_Int");
Hide_Implementation_Defined (Unit, "Max_Binary_Modulus");
Hide_Implementation_Defined (Unit, "Max_Nonbinary_Modulus");
Hide_Implementation_Defined (Unit, "Max_Base_Digits");
Hide_Implementation_Defined (Unit, "Max_Digits");
Hide_Implementation_Defined (Unit, "Max_Mantissa");
Hide_Implementation_Defined (Unit, "Fine_Delta");
Hide_Implementation_Defined (Unit, "Tick");
Hide_Implementation_Defined (Unit, "Storage_Unit");
Hide_Implementation_Defined (Unit, "Word_Size");
Hide_Implementation_Defined (Unit, "Memory_Size");
Hide_Implementation_Defined (Unit, "Default_Bit_Order");
Hide_Implementation_Defined (Unit, "Any_Priority");
Hide_Implementation_Defined (Unit, "Priority");
elsif Are_Equal_Identifiers (Name, "System.Storage_Pools") then
Find_Declaration (Unit, The_Root_Storage_Pool, "Root_Storage_Pool");
XASIS.Types.Initialize
(Root_Storage_Pool => The_Root_Storage_Pool);
elsif Are_Equal_Identifiers (Name, "System.RPC") then
Hide_Implementation_Defined (Unit, "Partition_Id");
elsif Are_Equal_Identifiers (Name, "System.Storage_Elements") then
Hide_Implementation_Defined (Unit, "Storage_Offset");
Hide_Implementation_Defined (Unit, "Storage_Element");
Hide_Implementation_Defined (Unit, "Integer_Address");
elsif Are_Equal_Identifiers (Name, "Interfaces.C") then
Hide_Implementation_Defined (Unit, "CHAR_BIT");
Hide_Implementation_Defined (Unit, "SCHAR_MIN");
Hide_Implementation_Defined (Unit, "SCHAR_MAX");
Hide_Implementation_Defined (Unit, "UCHAR_MAX");
Hide_Implementation_Defined (Unit, "int");
Hide_Implementation_Defined (Unit, "short");
Hide_Implementation_Defined (Unit, "long");
Hide_Implementation_Defined (Unit, "unsigned");
Hide_Implementation_Defined (Unit, "unsigned_short");
Hide_Implementation_Defined (Unit, "unsigned_long");
Hide_Implementation_Defined (Unit, "ptrdiff_t");
Hide_Implementation_Defined (Unit, "size_t");
Hide_Implementation_Defined (Unit, "C_float");
Hide_Implementation_Defined (Unit, "double");
Hide_Implementation_Defined (Unit, "long_double");
Hide_Implementation_Defined (Unit, "char");
Hide_Implementation_Defined (Unit, "nul");
Hide_Implementation_Defined (Unit, "wchar_t");
Hide_Implementation_Defined (Unit, "wide_nul");
Hide_Implementation_Defined (Unit, "char16_t");
Hide_Implementation_Defined (Unit, "char16_nul");
Hide_Implementation_Defined (Unit, "char32_t");
Hide_Implementation_Defined (Unit, "char32_nul");
elsif Are_Equal_Identifiers (Name, "Ada.Command_Line") then
Hide_Implementation_Defined (Unit, "Exit_Status");
elsif Are_Equal_Identifiers (Name, "Ada.Containers") then
Hide_Implementation_Defined (Unit, "Hash_Type");
Hide_Implementation_Defined (Unit, "Count_Type");
elsif Are_Equal_Identifiers (Name, "Ada.Decimal") then
Hide_Implementation_Defined (Unit, "Max_Scale");
Hide_Implementation_Defined (Unit, "Min_Scale");
Hide_Implementation_Defined (Unit, "Max_Decimal_Digits");
elsif Are_Equal_Identifiers (Name, "Ada.Direct_IO")
or else Are_Equal_Identifiers (Name, "Ada.Streams.Stream_IO")
then
Hide_Implementation_Defined (Unit, "Count");
elsif Are_Equal_Identifiers (Name, "Ada.Directories") then
Hide_Implementation_Defined (Unit, "File_Size");
elsif Are_Equal_Identifiers (Name, "Ada.Dispatching.Round_Robin") then
Hide_Implementation_Defined (Unit, "Default_Quantum");
elsif Are_Equal_Identifiers (Name, "Ada.Execution_Time") then
-- TODO: Make it A_Real_Number_Declaration
Hide_Implementation_Defined (Unit, "CPU_Time_Unit");
elsif Are_Equal_Identifiers (Name, "Ada.Execution_Time.Timers") then
Hide_Implementation_Defined (Unit, "Min_Handler_Ceiling");
elsif Are_Equal_Identifiers (Name, "Ada.Execution_Time.Group_Budgets")
then
Hide_Implementation_Defined (Unit, "Min_Handler_Ceiling");
elsif Are_Equal_Identifiers (Name, "Ada.Interrupts") then
Hide_Implementation_Defined (Unit, "Interrupt_ID");
elsif Are_Equal_Identifiers (Name, "Ada.Real_Time") then
-- TODO: Make it A_Real_Number_Declaration
Hide_Implementation_Defined (Unit, "Time_Unit");
Hide_Implementation_Defined (Unit, "Seconds_Count");
elsif Are_Equal_Identifiers (Name, "Ada.Text_IO")
or else Are_Equal_Identifiers (Name, "Ada.Wide_Text_IO")
or else Are_Equal_Identifiers (Name, "Ada.Wide_Wide_Text_IO")
then
Hide_Implementation_Defined (Unit, "Count");
Hide_Implementation_Defined (Unit, "Field");
elsif Are_Equal_Identifiers (Name, "Ada.Numerics.Discrete_Random")
or else Are_Equal_Identifiers (Name, "Ada.Numerics.Float_Random")
then
Hide_Implementation_Defined (Unit, "Max_Image_Width");
elsif Are_Equal_Identifiers (Name, "Ada.Storage_IO") then
Hide_Implementation_Defined (Unit, "Buffer_Size");
elsif Are_Equal_Identifiers (Name, "Ada.Streams") then
Hide_Implementation_Defined (Unit, "Stream_Element");
Hide_Implementation_Defined (Unit, "Stream_Element_Offset");
Find_Declaration (Unit, The_Root_Stream_Type, "Root_Stream_Type");
XASIS.Types.Initialize_Root_Stream (The_Root_Stream_Type);
elsif Are_Equal_Identifiers (Name, "Ada.Exceptions") then
Find_Declaration (Unit, The_Exception_Id, "Exception_Id");
Find_Declaration
(Unit, The_Exception_Occurrence, "Exception_Occurrence");
XASIS.Types.Initialize_Exception
(The_Exception_Id, The_Exception_Occurrence);
elsif Are_Equal_Identifiers (Name, "Ada.Task_Identification") then
Find_Declaration (Unit, The_Task_Id, "Task_Id");
XASIS.Types.Initialize_Task_Id (The_Task_Id);
elsif Are_Equal_Identifiers (Name, "Ada.Tags") then
Find_Declaration (Unit, The_Tag, "Tag");
XASIS.Types.Initialize_Tag (The_Tag);
end if;
end Process_Unit;
end Asis.Gela.Implicit;
------------------------------------------------------------------------------
-- Copyright (c) 2006-2013, Maxim Reznik
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice,
-- this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
-- * Neither the name of the Maxim Reznik, IE nor the names of its
-- contributors may be used to endorse or promote products derived from
-- this software without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
-- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-- POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
|
-----------------------------------------------------------------------
-- wiki-filters -- Wiki filters
-- 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.Finalization;
with Wiki.Attributes;
with Wiki.Documents;
with Wiki.Nodes;
with Wiki.Strings;
-- == Filters ==
-- The `Wiki.Filters` package provides a simple filter framework that allows to plug
-- specific filters when a wiki document is parsed and processed. The `Filter_Type`
-- implements the operations that the `Wiki.Parsers` will use to populate the document.
-- A filter can do some operations while calls are made so that it can:
--
-- * Get the text content and filter it by looking at forbidden words in some dictionary,
-- * Ignore some formatting construct (for example to forbid the use of links),
-- * Verify and do some corrections on HTML content embedded in wiki text,
-- * Expand some plugins, specific links to complex content.
--
-- To implement a new filter, the `Filter_Type` type must be used as a base type
-- and some of the operations have to be overriden. The default `Filter_Type` operations
-- just propagate the call to the attached wiki document instance (ie, a kind of pass
-- through filter).
--
-- @include wiki-filters-toc.ads
-- @include wiki-filters-html.ads
-- @include wiki-filters-collectors.ads
-- @include wiki-filters-autolink.ads
-- @include wiki-filters-variables.ads
package Wiki.Filters is
pragma Preelaborate;
-- ------------------------------
-- Filter type
-- ------------------------------
type Filter_Type is limited new Ada.Finalization.Limited_Controlled with private;
type Filter_Type_Access is access all Filter_Type'Class;
-- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document.
procedure Add_Node (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Kind : in Wiki.Nodes.Simple_Node_Kind);
-- Add a text content with the given format to the document.
procedure Add_Text (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map);
-- Add a section header with the given level in the document.
procedure Add_Header (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Natural);
-- Push a HTML node with the given tag to the document.
procedure Push_Node (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Pop a HTML node with the given tag.
procedure Pop_Node (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
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 (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Level : in Positive;
Ordered : in Boolean);
-- Add a link.
procedure Add_Link (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add an image.
procedure Add_Image (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add a quote.
procedure Add_Quote (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString);
-- Add a new row to the current table.
procedure Add_Row (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document);
-- Add a column to the current table row. The column is configured with the
-- given attributes. The column content is provided through calls to Append.
procedure Add_Column (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Finish the creation of the table.
procedure Finish_Table (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document);
-- Finish the document after complete wiki text has been parsed.
procedure Finish (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document);
type Filter_Chain is new Filter_Type with private;
-- Add the filter at beginning of the filter chain.
procedure Add_Filter (Chain : in out Filter_Chain;
Filter : in Filter_Type_Access);
-- Internal operation to copy the filter chain.
procedure Set_Chain (Chain : in out Filter_Chain;
From : in Filter_Chain'Class);
private
type Filter_Type is limited new Ada.Finalization.Limited_Controlled with record
Next : Filter_Type_Access;
end record;
type Filter_Chain is new Filter_Type with null record;
end Wiki.Filters;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- A 4 G . D D A _ A U X --
-- --
-- S p e c --
-- --
-- $Revision: 14154 $
-- --
-- Copyright (C) 1999-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. --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- It is now maintained by Ada Core Technologies Inc (http://www.gnat.com). --
-- --
------------------------------------------------------------------------------
-- This package contains auxiliary routines used to support the data
-- decomposition annex. At the level of this package, types and components
-- are represented by their normal Entity_Id values. The corresponding
-- entities have the necessary representation information stored in them.
-- DDA_Aux acts as an interface between the main ASIS routines and all
-- representation issues.
with Asis.Data_Decomposition;
with Repinfo; use Repinfo;
with Types; use Types;
with Uintp; use Uintp;
package A4G.DDA_Aux is
--------------------------------
-- Portable_Data Declarations --
--------------------------------
-- Asis.Data_Decomposition.Portable_Value;
-- Portable values are simply bytes, i.e. defined as mod 256. This is
-- fine for all the byte addressable architectures that GNAT runs on
-- now, and we will worry later about exotic cases (which may well
-- never arise).
-- Portable_Positive is Asis.Data_Decomposition.Portable_Positive;
-- This is simply a synonym for Asis.ASIS_Positive
-- Asis.Data_Decomposition.Portable_Data;
-- This is array (Portable_Positive range <>) of Portable_Data. Thus
-- it is simply an array of bytes. The representation of data in this
-- format is as follows:
--
-- For non-scalar values, the data value is stored at the start of
-- the value, occupying as many bits as needed. If there are padding
-- bits (on the right), they are stored as zero bits when a value is
-- retrieved, and ignored when a value is stored.
--
-- For scalar values, the data value is of length 1, 2, 4, or 8 bytes
-- in proper little-endian or big-endian format with sign or zero
-- bits filling the unused high order bits. For enumeration values,
-- this is the Enum_Rep value, i.e. the actual stored value, not the
-- Pos value. For biased types, the value is unsigned and biased.
---------------------------------
-- Basic Interface Definiitons --
---------------------------------
Variable_Rep_Info : exception;
-- This exception is raised if an attempt is made to access representation
-- information that depends on the value of a variable other than a
-- discriminant for the current record. For example, if the length of
-- a component of subtype String (1 .. N) is requested, and N is not a
-- discriminant or a static constant.
Invalid_Data : exception;
-- Exception raised if an invalid data value is detected. There is no
-- systematic checking for invalid values, but there are some situations
-- in which bad values are detected, and this exception is raised.
No_Component : exception;
-- Exception raised if a request is made to access a component in a
-- variant part of a record when the component does not exist for the
-- particular set of discriminant values present. Also raised if a
-- request is made to access an out of bounds subscript value for an
-- array element.
Null_Discrims : Repinfo.Discrim_List (1 .. 0) := (others => Uint_0);
-- Used as default if no discriminants given
----------------------
-- Utility Routines --
----------------------
function Build_Discrim_List
(Rec : Entity_Id;
Data : Asis.Data_Decomposition.Portable_Data)
return Repinfo.Discrim_List;
-- Given a record entity, and a value of this record type, builds a
-- list of discriminants from the given value and returns it. The
-- portable data value must include at least all the discriminants
-- if the type is for a discriminated record. If Rec is other than
-- a discriminated record type, then Data is ignored and Null_Discrims
-- is returned.
function Eval_Scalar_Node
(N : Node_Id;
Discs : Repinfo.Discrim_List := Null_Discrims)
return Uint;
-- This function is used to get the value of a node representing a value
-- of a scalar type. Evaluation is possible for static expressions and
-- for discriminant values (in the latter case, Discs must be provided
-- and must contain the appropriate list of discriminants). Note that
-- in the case of enumeration values, the result is the Pos value, not
-- the Enum_Rep value for the given enumeration literal.
--
-- Raises Variable_Rep_Info is raised if the expression is other than
-- a discriminant or a static expression, or if it is a discriminant
-- and no discriminant list is provided.
--
-- Note that this functionality is related to that provided by
-- Sem_Eval.Expr_Value, but this unit is not available in ASIS.
function Linear_Index
(Typ : Entity_Id;
Subs : Asis.Data_Decomposition.Dimension_Indexes;
Discs : Repinfo.Discrim_List := Null_Discrims)
return Asis.ASIS_Natural;
-- Given Typ, the entity for a definite array type or subtype, and Subs,
-- a list of 1's origin subscripts (that is, as usual Dimension_Indexes
-- has subscripts that are 1's origin with respect to the declared lower
-- bound), this routine computes the corresponding zero-origin linear
-- index from the start of the array data. The case of Fortran convention
-- (with row major order) is properly handled.
--
-- Raises No_Component if any of the subscripts is out of range (i.e.
-- exceeds the length of the corresponding subscript position).
function UI_From_Aint (A : Asis.ASIS_Integer) return Uint;
-- Converts ASIS_Integer value to Uint
function UI_Is_In_Aint_Range (U : Uint) return Boolean;
-- Determine if a universal integer value U is in range of ASIS_Integer.
-- Returns True iff in range (meaning that UI_To_Aint can be safely used).
function UI_To_Aint (U : Uint) return Asis.ASIS_Integer;
-- Converts Uint value to ASIS_Integer, the result must be in range
-- of ASIS_Integer, or otherwise the exception Invalid_Data is raised.
--------------------------------
-- Universal Integer Encoding --
--------------------------------
-- These routines deal with decoding and encoding scalar values from
-- Uint to portable data format.
function Encode_Scalar_Value
(Typ : Entity_Id;
Val : Uint)
return Asis.Data_Decomposition.Portable_Data;
-- Given Typ, the entity for a scalar type or subtype, this function
-- constructs a portable data valuethat represents a value of this
-- type given by Val. The value of the Uint may not exceed the largest
-- scalar value supported by the implementation. The result will be 1,
-- 2, 4 or 8 bytes long depending on the value of the input, positioned
-- to be intepreted as an integer, and sign or zero extended as needed.
-- For enumeration types, the value is the Enum_Rep value, not the Pos
-- value. For biased types, the bias is NOT present in the Uint value
-- (part of the job of Encode_Scalar_Value is to introduce the bias).
--
-- Raises Invalid_Data if value is out of range of the base type of Typ
function Encode_Scalar_Value
(Typ : Entity_Id;
Val : Asis.ASIS_Integer)
return Asis.Data_Decomposition.Portable_Data;
-- Similar to above function except input is ASIS_Integer instead of Uint
function Decode_Scalar_Value
(Typ : Entity_Id;
Data : Asis.Data_Decomposition.Portable_Data)
return Uint;
-- Given Typ, the entity for a scalar type or subtype, this function
-- takes the portable data value Data, that represents a value of
-- this type, and returns the equivalent Uint value. For enumeration
-- types the value is the Enum_Rep value, not the Pos value. For biased
-- types, the result is unbiased (part of the job of Decode_Scalar_Value
-- is to remove the bias).
--------------------------------
-- Record Discriminant Access --
--------------------------------
function Extract_Discriminant
(Data : Asis.Data_Decomposition.Portable_Data;
Disc : Entity_Id)
return Uint;
-- This function can be used to extract a discriminant value from a
-- record. Data is the portable data value representing the record
-- value, and Disc is the E_Discriminant entity for the discriminant.
function Set_Discriminant
(Data : Asis.Data_Decomposition.Portable_Data;
Disc : Entity_Id;
Val : Uint)
return Asis.Data_Decomposition.Portable_Data;
-- Given Data, a portable data value representing the prefix of a record
-- value which may already have some other discriminant values set, this
-- function creates a new Portable_Data value, increased in length
-- if necessary, in which the discriminant represented by E_Discriminant
-- entity Disc is set to the given value.
--
-- Raises Invalid_Data if the value does not fit in the field
procedure Set_Discriminant
(Data : in out Asis.Data_Decomposition.Portable_Data;
Disc : Entity_Id;
Val : Uint);
-- Similar to the function above, except that the modification is done
-- in place on the given portable data value. In this case, the Data
-- value must be long enough to contain the given discriminant field.
function Set_Discriminant
(Data : Asis.Data_Decomposition.Portable_Data;
Disc : Entity_Id;
Val : Asis.ASIS_Integer)
return Asis.Data_Decomposition.Portable_Data;
-- Similar to function above, but takes argument in ASIS_Integer form
procedure Set_Discriminant
(Data : in out Asis.Data_Decomposition.Portable_Data;
Disc : Entity_Id;
Val : Asis.ASIS_Integer);
-- Similar to function above, but takes argument in ASIS_Integer form
-----------------------------
-- Record Component Access --
-----------------------------
function Component_Present
(Comp : Entity_Id;
Discs : Repinfo.Discrim_List)
return Boolean;
-- Determines if the given component is present or not. For the case
-- where the component is part of a variant of a discriminated record,
-- Discs must contain the full list of discriminants for the record,
-- and the result is True or False depending on whether the variant
-- containing the field is present or not for the given discriminant
-- values. If the component is not part of a variant, including the
-- case where the record is non-discriminated, then Discs is ignored
-- and the result is always True.
function Extract_Record_Component
(Data : Asis.Data_Decomposition.Portable_Data;
Comp : Entity_Id;
Discs : Repinfo.Discrim_List := Null_Discrims)
return Asis.Data_Decomposition.Portable_Data;
-- Given Data, a portable data value representing a record value, this
-- routine extracts the component value corresponding to E_Component
-- entity Comp, and returns a new portable data value corresponding to
-- this component. The Discs parameter supplies the discriminants and
-- must be present in the discriminated record case if the component
-- may depend on discriminants. For scalar types, the result value
-- is 1,2,4, or 8 bytes, properly positioned to be interpreted as an
-- integer, and sign/zero extended as required. For all other types,
-- the value is extended if necessary to be an integral number of
-- bytes by adding zero bits.
--
-- Raises No_Component if an attempt is made to set a component in a
-- non-existent variant.
--
-- Raises No_Component if the specified component is part of a variant
-- that does not exist for the given discriminant values
--
-- Raises Variable_Rep_Info if the size or position of the component
-- depends on a variable other than a discriminant
function Set_Record_Component
(Data : Asis.Data_Decomposition.Portable_Data;
Comp : Entity_Id;
Val : Asis.Data_Decomposition.Portable_Data;
Discs : Repinfo.Discrim_List := Null_Discrims)
return Asis.Data_Decomposition.Portable_Data;
-- Given Data, a portable data value that represents a record value,
-- or a prefix of such a record, sets the component represented by the
-- E_Component entity Comp is set to the value represented by the portable
-- data value Val, and the result is returned as a portable data value,
-- extended in length if necessary to accomodate the newly added entry.
-- The Discs parameter supplies the discriminants and must be present
-- in the discriminated record case if the component may depend on
-- the values of discriminants.
--
-- Raises No_Component if an attempt is made to set a component in a
-- non-existent variant.
--
-- Raises No_Component if the specified component is part of a variant
-- that does not exist for the given discriminant values
--
-- Raises Variable_Rep_Info if the size or position of the component
-- depends on a variable other than a discriminant
--
-- Raises Invalid_Data if the data value is too large to fit.
procedure Set_Record_Component
(Data : in out Asis.Data_Decomposition.Portable_Data;
Comp : Entity_Id;
Val : Asis.Data_Decomposition.Portable_Data;
Discs : Repinfo.Discrim_List := Null_Discrims);
-- Same as the above, but operates in place on the given data value,
-- which must in this case be long enough to contain the component.
----------------------------
-- Array Component Access --
----------------------------
function Extract_Array_Component
(Typ : Entity_Id;
Data : Asis.Data_Decomposition.Portable_Data;
Subs : Asis.Data_Decomposition.Dimension_Indexes;
Discs : Repinfo.Discrim_List := Null_Discrims)
return Asis.Data_Decomposition.Portable_Data;
-- Given Typ, the entity for an array type, and Data, a portable data
-- value representing a value of this array type, this function extracts
-- the array element corresponding to the given list of subscript values.
-- The parameter Discs must be given if any of the bounds of the array
-- may depend on discriminant values, and supplies the corresponding
-- discriminants. For scalar component types, the value is 1,2,4, or 8,
-- properly positioned to be interpreted as an integer, and sign/zero
-- extended as required. For all other types, the value is extended if
-- necessary to be an integral number of bytes by adding zero bits.
--
-- Raises No_Component if any of the subscripts is out of bounds
-- (that is, exceeds the length of the corresponding index).
--
-- Raises Variable_Rep_Info if length of any index depends on a
-- variable other than a discriminant.
--
function Set_Array_Component
(Typ : Entity_Id;
Data : Asis.Data_Decomposition.Portable_Data;
Subs : Asis.Data_Decomposition.Dimension_Indexes;
Val : Asis.Data_Decomposition.Portable_Data;
Discs : Repinfo.Discrim_List := Null_Discrims)
return Asis.Data_Decomposition.Portable_Data;
-- Given a portable data value representing either a value of the array
-- type Typ, or a prefix of such a value, sets the element referenced by
-- the given subscript values in Subs, to the given value Val. The
-- parameter Discs must be given if any of the bounds of the array
-- may depend on discriminant values, and supplies the corresponding
-- discriminants. The returned result is the original portable data
-- value, extended if necessary to include the new element, with the
-- new element value in place.
--
-- Raises No_Component if any of the subscripts is out of bounds
-- (that is, exceeds the length of the corresponding index).
--
-- Raises Variable_Rep_Info if length of any index depends on a
-- variable other than a discriminant.
--
-- Raises Invalid_Data if the data value is too large to fit.
procedure Set_Array_Component
(Typ : Entity_Id;
Data : in out Asis.Data_Decomposition.Portable_Data;
Subs : Asis.Data_Decomposition.Dimension_Indexes;
Val : Asis.Data_Decomposition.Portable_Data;
Discs : Repinfo.Discrim_List := Null_Discrims);
-- Same as above, but operates in place on the given stream. The stream
-- must be long enough to contain the given element in this case.
-------------------------------
-- Representation Parameters --
-------------------------------
-- These routines give direct access to the values of the
-- representation fields stored in the tree, including the
-- proper interpretation of variable values that depend on
-- the values of discriminants.
function Get_Esize
(Comp : Entity_Id;
Discs : Repinfo.Discrim_List := Null_Discrims)
return Uint;
-- Obtains the size (actually the object size, Esize) of any subtype
-- or record component or discriminant. The function can be used for
-- components of discriminanted or non-discriminated records. In the
-- case of components of a discriminated record where the value depends
-- on discriminants, Discs provides the necessary discriminant values.
-- In all other cases, Discs is ignored and can be defaulted.
--
-- Raises Variable_Rep_Info if the size depends on a variable other
-- than a discriminant.
--
-- Raises No_Component if the component is in a variant that does not
-- exist for the given set of discriminant values.
function Get_Component_Bit_Offset
(Comp : Entity_Id;
Discs : Repinfo.Discrim_List := Null_Discrims)
return Uint;
-- Obtains the component first bit value for the specified component or
-- discriminant. This function can be used for discriminanted or non-
-- discriminanted records. In the case of components of a discriminated
-- record where the value depends on discriminants, Discs provides the
-- necessary discriminant values. Otherwise (and in particular in the case
-- of discriminants themselves), Discs is ignored and can be defaulted.
--
-- Raises Variable_Rep_Info if the size depends on a variable other
-- than a discriminant.
--
-- Raises No_Component if the component is in a variant that does not
-- exist for the given set of discriminant values.
function Get_Component_Size
(Typ : Entity_Id)
return Uint;
-- Given an array type or subtype, returns the component size value
function Get_Length
(Typ : Entity_Id;
Sub : Asis.ASIS_Positive;
Discs : Repinfo.Discrim_List := Null_Discrims)
return Asis.ASIS_Natural;
-- Given Typ, the entity for a definite array type or subtype, returns
-- the Length of the subscript designated by Sub (1 = first subscript
-- as in Length attribute). If the bounds of the array may depend on
-- discriminants, then Discs contains the list of discriminant values
-- (e.g. if we have an array field A.B, then the discriminants of A
-- may be needed).
--
-- Raises Variable_Rep_Info if the size depends on a variable other
-- than a discriminant.
-------------------------------
-- Computation of Attributes --
-------------------------------
-- The DDA_Aux package simply provides access to the representation
-- information stored in the tree, as described in Einfo, as refined
-- by the description in Repinfo with regard to the case where some
-- of the values depend on discriminants.
-- The ASIS spec requires that ASIS be able to compute the values of
-- the attributes Position, First_Bit, and Last_Bit.
-- This is done as follows. First compute the Size (with Get_Esize)
-- and the Component_Bit_Offset (with Get_Component_Bit_Offset). In the
-- case of a nested reference, e.g.
-- A.B.C
-- You need to extract the value A.B, and then ask for the
-- size of its component C, and also the component first bit
-- value of this component C.
-- This value gets added to the Component_Bit_Offset value for
-- the B field in A.
-- For arrays, the equivalent of Component_Bit_Offset is computed simply
-- as the zero origin linearized subscript multiplied by the value of
-- Component_Size for the array. As another example, consider:
-- A.B(15)
-- In this case you get the component first bit of the field B in A,
-- using the discriminants of A if there are any. Then you get the
-- component first bit of the 15th element of B, using the discriminants
-- of A (since the bounds of B may depend on them). You then add these
-- two component first bit values.
-- Once you have the aggregated value of the first bit offset (i.e. the
-- sum of the Component_Bit_Offset values and corresponding array offsets
-- for all levels of the access), then the formula is simply:
-- X'Position = First_Bit_Offset / Storage_Unit_Size
-- X'First = First_Bit_Offset mod Storage_Unit_Size
-- X'Last = X'First + component_size - 1
end A4G.DDA_Aux;
|
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
procedure Range_Extraction is
type Sequence is array (Positive range <>) of Integer;
function Image (S : Sequence) return String is
Result : Unbounded_String;
From : Integer;
procedure Flush (To : Integer) is
begin
if Length (Result) > 0 then
Append (Result, ',');
end if;
Append (Result, Trim (Integer'Image (From), Ada.Strings.Left));
if From < To then
if From+1 = To then
Append (Result, ',');
else
Append (Result, '-');
end if;
Append (Result, Trim (Integer'Image (To), Ada.Strings.Left));
end if;
end Flush;
begin
if S'Length > 0 then
From := S (S'First);
for I in S'First + 1..S'Last loop
if S (I - 1) + 1 /= S (I) then
Flush (S (I - 1));
From := S (I);
end if;
end loop;
Flush (S (S'Last));
end if;
return To_String (Result);
end Image;
begin
Put_Line
( Image
( ( 0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39
) ) );
end Range_Extraction;
|
procedure My_Package is
generic
type Unsigned_Type is range <>;
package Generic_Integer_Images is
function Digit_To_Character (X : Unsigned_Type) return Character;
end Generic_Integer_Images;
package body Generic_Integer_Images is
function Digit_To_Character (X : Unsigned_Type) return Character is
(Character'Val (0));
end Generic_Integer_Images;
type Signed_Address is range
-2**(Standard'Address_Size - 1) .. 2**(Standard'Address_Size - 1) - 1;
begin
null;
end My_Package;
|
package UxAS.Comms.Transport.Receiver is
type Transport_Receiver_Base is abstract new Transport_Base with private;
type Transport_Receiver_Base_Ref is access all Transport_Receiver_Base;
type Any_Transport_Receiver_Base is access Transport_Receiver_Base'Class;
Any_Address_Accepted : constant String := "";
-- no filtering applied
-- bool
-- addSubscriptionAddress(const std::string& address);
procedure Add_Subscription_Address
(This : in out Transport_Receiver_Base;
Address : String;
Result : out Boolean);
-- bool
-- removeSubscriptionAddress(const std::string& address);
procedure Remove_Subscription_Address
(This : in out Transport_Receiver_Base;
Address : String;
Result : out Boolean);
-- bool
-- removeAllSubscriptionAddresses();
procedure Remove_All_Subscription_Addresses
(This : in out Transport_Receiver_Base;
Result : out Boolean);
-- bool
-- addSubscriptionAddressToSocket(const std::string& address) override;
procedure Add_Subscription_Address_To_Socket
(This : in out Transport_Receiver_Base;
Address : String;
Result : out Boolean)
is abstract;
-- bool
-- removeSubscriptionAddressFromSocket(const std::string& address) override;
procedure Remove_Subscription_Address_From_Socket
(This : in out Transport_Receiver_Base;
Address : String;
Result : out Boolean)
is abstract;
private
type Transport_Receiver_Base is abstract new Transport_Base with record
-- std::unordered_set<std::string> m_subscriptionAddresses;
Subscriptions : Subscription_Address_Set;
end record;
end UxAS.Comms.Transport.Receiver;
|
-- Institution: Technische Universität München
-- Department: Realtime Computer Systems (RCS)
-- Project: StratoX
-- Module: Software Configuration
--
-- Authors: Emanuel Regnath (emanuel.regnath@tum.de)
--
-- Description:
-- Configuration of the Software, adjust these parameters to your needs
package Config is
MAIN_TICK_RATE_MS : constant := 10; -- Tickrate in Milliseconds
end Config;
|
--------------------------------------------------------------------------------
-- Copyright (c) 2013, Felix Krause <contact@flyx.org>
--
-- Permission to use, copy, modify, and/or distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
--------------------------------------------------------------------------------
with CL.Platforms;
with CL.Contexts;
with CL.Memory;
with CL.Memory.Images;
with CL.Memory.Buffers;
with CL_Test.Helpers;
with Ada.Text_IO;
with Ada.Strings.Fixed;
procedure CL_Test.Memory is
package ATI renames Ada.Text_IO;
Pfs : constant CL.Platforms.Platform_List := CL.Platforms.List;
pragma Assert (Pfs'Length > 0);
Pf : constant CL.Platforms.Platform := Pfs (1);
Dvs : constant CL.Platforms.Device_List := Pf.Devices(CL.Platforms.Device_Kind_All);
pragma Assert (Dvs'Length > 0);
Context : constant CL.Contexts.Context
:= CL.Contexts.Constructors.Create_For_Devices (Pf, Dvs,
CL_Test.Helpers.Callback'Access);
use type CL.Size;
use type CL.Memory.Images.Image_Format;
use type CL.Memory.Access_Kind;
use type CL.Contexts.Context;
begin
for Index in CL.Memory.Access_Kind loop
ATI.Put_Line ("Context Refcount:" & Context.Reference_Count'Img);
ATI.New_Line;
ATI.Put_Line ("Testing Buffer");
declare
Buffer : constant CL.Memory.Buffers.Buffer
:= CL.Memory.Buffers.Constructors.Create (Context, Index, 1024);
begin
ATI.Put_Line ("Created Buffer.");
ATI.Put_Line ("Context Refcount:" & Context.Reference_Count'Img);
pragma Assert (Buffer.Mode = Index);
pragma Assert (Buffer.Size = 1024);
ATI.Put_Line ("Map count:" & Buffer.Map_Count'Img);
pragma Assert (Buffer.Context = Context);
ATI.Put_Line ("Test completed.");
ATI.Put_Line (Ada.Strings.Fixed."*" (80, '-'));
end;
ATI.Put_Line ("Context Refcount:" & Context.Reference_Count'Img);
ATI.Put_Line ("Testing Image2D");
-- test 2D image
declare
-- decide for an image format to use
Format_List : constant CL.Memory.Images.Image_Format_List
:= CL.Memory.Images.Supported_Image_Formats (Context, Index,
CL.Memory.Images.T_Image2D);
pragma Assert (Format_List'Length > 0);
Image : constant CL.Memory.Images.Image2D
:= CL.Memory.Images.Constructors.Create_Image2D
(Context, Index, Format_List (1), 1024, 512, 0);
begin
ATI.Put_Line ("Created Image.");
ATI.Put_Line ("Context Refcount:" & Context.Reference_Count'Img);
ATI.Put_Line ("Size:" & Image.Size'Img);
pragma Assert (Image.Mode = Index);
pragma Assert (Image.Context = Context);
pragma Assert (Image.Format = Format_List (1));
pragma Assert (Image.Width = 1024);
pragma Assert (Image.Height = 512);
ATI.Put_Line ("Element size:" & Image.Element_Size'Img);
ATI.Put_Line ("Row pitch:" & Image.Row_Pitch'Img);
ATI.Put_Line ("Test completed.");
ATI.Put_Line (Ada.Strings.Fixed."*" (80, '-'));
end;
end loop;
end CL_Test.Memory;
|
--------------------------------------------------------------------------------
-- MIT License
--
-- Copyright (c) 2021 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.Dmat2x2.Test;
with Vulkan.Math.Dmat2x3.Test;
with Vulkan.Math.Dmat2x4.Test;
with Vulkan.Math.Dmat3x2.Test;
with Vulkan.Math.Dmat3x3.Test;
with Vulkan.Math.Dmat3x4.Test;
with Vulkan.Math.Dmat4x2.Test;
with Vulkan.Math.Dmat4x3.Test;
with Vulkan.Math.Dmat4x4.Test;
use Vulkan.Math.Dmat2x2.Test;
use Vulkan.Math.Dmat2x3.Test;
use Vulkan.Math.Dmat2x4.Test;
use Vulkan.Math.Dmat3x2.Test;
use Vulkan.Math.Dmat3x3.Test;
use Vulkan.Math.Dmat3x4.Test;
use Vulkan.Math.Dmat4x2.Test;
use Vulkan.Math.Dmat4x3.Test;
use Vulkan.Math.Dmat4x4.Test;
package body Vulkan.Math.Test_Dmat is
-- Test Harness for double precision floating point matrices.
procedure Test_Dmat is
begin
Test_Dmat2x2;
Test_Dmat2x3;
Test_Dmat2x4;
Test_Dmat3x2;
Test_Dmat3x3;
Test_Dmat3x4;
Test_Dmat4x2;
Test_Dmat4x3;
Test_Dmat4x4;
end Test_Dmat;
end Vulkan.Math.Test_Dmat;
|
-- 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.Command_Line;
with Ada.Text_IO; use Ada.Text_IO;
with Latin_Utils.Strings_Package; use Latin_Utils.Strings_Package;
use Latin_Utils;
with Latin_Utils.Config; use Latin_Utils.Config;
with Support_Utils.Word_Parameters; use Support_Utils.Word_Parameters;
with Words_Engine.Word_Package; use Words_Engine.Word_Package;
with Words_Engine.Initialization;
with Process_Input;
procedure Words_Main (Configuration : Configuration_Type) is
Input_Line : String (1 .. 250) := (others => ' ');
Arguments_Start : Integer := 1;
begin
-- The language shift in arguments must take place here
-- since later parsing of line ignores non-letter Characters
-- configuration := developer_version;
-- The main mode of usage for WORDS is a simple call, followed by
-- screen interaction.
if Ada.Command_Line.Argument_Count = 0 then -- Simple WORDS
Method := Interactive; -- Interactive
Suppress_Preface := False;
Set_Output (Ada.Text_IO.Standard_Output);
Words_Engine.Initialization.Initialize_Engine;
Process_Input (Configuration);
--But there are other, command line options.
--WORDS may be called with Arguments on the same line,
--in a number of different modes.
--
else
Suppress_Preface := True;
Words_Engine.Initialization.Initialize_Engine;
--Single parameter, either a simple Latin word or an Input file.
--WORDS amo
--WORDS infile
if Ada.Command_Line.Argument_Count = 1 then -- InPut 1 word in-line
One_Argument :
declare
Input_Name : constant String :=
Trim (Ada.Command_Line.Argument (1));
begin
-- Try file name, not raises NAME_ERROR
Open (Input, In_File, Input_Name);
Method := Command_Line_Files;
Set_Input (Input);
Set_Output (Ada.Text_IO.Standard_Output);
-- No additional Arguments, so just go to PARSE now
Process_Input (Configuration);
exception -- Triggers on INPUT
when Name_Error => -- Raised NAME_ERROR therefore
Method := Command_Line_Input; -- Found word in command line
end One_Argument;
--With two Arguments the options are: Inputfile and Outputfile,
--two Latin words, or a language shift to English (Latin being
--the startup default)
--and an English word (with no part of speech).
--WORDS infile outfile
--WORDS amo amas
--WORDS ^e love
elsif Ada.Command_Line.Argument_Count = 2 then -- INPUT and OUTPUT files
Two_Arguments : -- or multiwords in-line
declare
Input_Name : constant String :=
Trim (Ada.Command_Line.Argument (1));
Output_Name : constant String :=
Trim (Ada.Command_Line.Argument (2));
begin
if Input_Name (1) = Change_Language_Character then
if Input_Name'Length > 1 then
Change_Language (Input_Name (2));
Arguments_Start := 2;
Method := Command_Line_Input; -- Parse the one word
end if;
else
Open (Input, In_File, Input_Name);
Create (Output, Out_File, Output_Name);
Method := Command_Line_Files;
Set_Input (Input);
Set_Output (Output);
Suppress_Preface := True;
Output_Screen_Size := Integer'Last;
-- No additional Arguments, so just go to PARSE now
Process_Input (Configuration);
Set_Input (Ada.Text_IO.Standard_Input); -- Clean up
Set_Output (Ada.Text_IO.Standard_Output);
Close (Output);
end if;
exception -- Triggers on either INPUT or OUTPUT !!!
when Name_Error =>
Method := Command_Line_Input; -- Found words in command line
end Two_Arguments;
--With three Arguments there could be three Latin words
-- or a language shift
--and and English word and part of speech.
--WORDS amo amas amat
--WORDS ^e love v
elsif Ada.Command_Line.Argument_Count = 3 then
-- INPUT and OUTPUT files or multiwords in-line
Three_Arguments :
declare
Arg1 : constant String := Trim (Ada.Command_Line.Argument (1));
-- we probably don't need to define these for their side-effects
-- arg2 : constant String := Trim (Ada.Command_Line.Argument (2));
-- arg3 : constant String := Trim (Ada.Command_Line.Argument (3));
begin
if Arg1 (1) = Change_Language_Character then
if Arg1'Length > 1 then
Change_Language (Arg1 (2));
Arguments_Start := 2;
Method := Command_Line_Input; -- Parse the one word
end if;
else
Method := Command_Line_Input;
end if;
end Three_Arguments;
--More than three Arguments must all be Latin words.
--WORDS amo amas amat amamus amatis amant
else -- More than three Arguments
Method := Command_Line_Input;
end if;
if Method = Command_Line_Input then -- Process words in command line
More_Arguments :
begin
Suppress_Preface := True;
-- Assemble Input words
for I in Arguments_Start .. Ada.Command_Line.Argument_Count loop
Input_Line := Head (
Trim (Input_Line) & " " & Ada.Command_Line.Argument (I), 250);
end loop;
--Ada.TEXT_IO.PUT_LINE ("To PARSE >" & TRIM (INPUT_LINE));
Process_Input (Configuration, Trim (Input_Line));
end More_Arguments;
end if;
end if;
end Words_Main;
|
with AVR.MCU;
package body Hardware.DriveTrain is
procedure Init is
begin
MCU.DDRB_Bits (Pin_Right) := DD_Output;
MCU.DDRB_Bits (Pin_Left) := DD_Output;
PWM.Connect (Pin_Right, Motor_Right);
PWM.Connect (Pin_Left, Motor_Left);
PWM.Set (Motor_Right, Rotate_Stop);
PWM.Set (Motor_Left, Rotate_Stop);
end Init;
procedure Forward is
begin
PWM.Set (Motor_Right, Rotate_Backward);
PWM.Set (Motor_Left, Rotate_Forward);
end Forward;
procedure Backward is
begin
PWM.Set (Motor_Left, Rotate_Backward);
PWM.Set (Motor_Right, Rotate_Forward);
end Backward;
procedure Rotate_Left is
begin
PWM.Set (Motor_Left, Rotate_Backward);
PWM.Set (Motor_Right, Rotate_Backward);
end Rotate_Left;
procedure Rotate_Right is
begin
PWM.Set (Motor_Left, Rotate_Forward);
PWM.Set (Motor_Right, Rotate_Forward);
end Rotate_Right;
procedure Stop is
begin
PWM.Set (Motor_Left, Rotate_Stop);
PWM.Set (Motor_Right, Rotate_Stop);
end Stop;
end Hardware.DriveTrain;
|
with Sodium.Functions; use Sodium.Functions;
with Ada.Text_IO; use Ada.Text_IO;
procedure Demo_Ada
is
message : constant String := "JRM wrote this note.";
message2 : constant String := "1972 Miami Dolphins";
cipherlen : constant Positive := Cipher_Length (message);
cipher2len : constant Positive := Cipher_Length (message2);
begin
if not initialize_sodium_library then
Put_Line ("Initialization failed");
return;
end if;
declare
alice_public_key : Public_Box_Key;
alice_secret_key : Secret_Box_Key;
bob_public_key : Public_Box_Key;
bob_secret_key : Secret_Box_Key;
shared_key : Box_Shared_Key;
new_nonce : Box_Nonce := Random_Nonce;
cipher_text : Encrypted_Data (1 .. cipherlen);
cipher2_text : Encrypted_Data (1 .. cipher2len);
clear_text : String (1 .. message'Length);
clear_text2 : String (1 .. message2'Length);
new_box_seed : Sign_Key_Seed := Random_Box_Key_seed;
begin
Generate_Box_Keys (alice_public_key, alice_secret_key);
Generate_Box_Keys (bob_public_key, bob_secret_key, new_box_seed);
Put_Line ("Alice Public Key: " & As_Hexidecimal (alice_public_key));
Put_Line ("Alice Secret Key: " & As_Hexidecimal (alice_secret_key));
Put_Line ("Bob Public Key: " & As_Hexidecimal (bob_public_key));
Put_Line ("Bob Secret Key: " & As_Hexidecimal (bob_secret_key));
cipher_text := Encrypt_Message (plain_text_message => message,
recipient_public_key => bob_public_key,
sender_secret_key => alice_secret_key,
unique_nonce => new_nonce);
Put_Line ("CipherText (Alice): " & As_Hexidecimal (cipher_text));
clear_text := Decrypt_Message (ciphertext => cipher_text,
sender_public_key => alice_public_key,
recipient_secret_key => bob_secret_key,
unique_nonce => new_nonce);
Put_Line ("Back again: " & clear_text);
shared_key := Generate_Shared_Key (recipient_public_key => alice_public_key,
sender_secret_key => bob_secret_key);
Put_Line ("");
Put_Line ("Shared Key (Bob): " & As_Hexidecimal (shared_key));
new_nonce := Random_Nonce;
cipher2_text := Encrypt_Message (plain_text_message => message2,
shared_key => shared_key,
unique_nonce => new_nonce);
Put_Line ("CipherText2 (Bob): " & As_Hexidecimal (cipher2_text));
clear_text2 := Decrypt_Message (ciphertext => cipher2_text,
shared_key => shared_key,
unique_nonce => new_nonce);
Put_Line ("Back again: " & clear_text2);
end;
end Demo_Ada;
|
pragma Extend_System (Aux_DEC);
with System; use System;
package Valued_Proc_Pkg is
procedure GETMSG (STATUS : out UNSIGNED_LONGWORD;
MSGLEN : out UNSIGNED_WORD);
pragma Interface (EXTERNAL, GETMSG);
pragma IMPORT_VALUED_PROCEDURE (GETMSG, "SYS$GETMSG",
(UNSIGNED_LONGWORD, UNSIGNED_WORD),
(VALUE, REFERENCE));
end Valued_Proc_Pkg;
|
-- SPDX-FileCopyrightText: 2010-2021 Max Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-------------------------------------------------------------
with WebIDL.Abstract_Sources;
with League.Strings;
with WebIDL.Scanner_Handlers;
with WebIDL.Tokens;
with WebIDL.Scanner_Types; use WebIDL.Scanner_Types;
package WebIDL.Scanners is
pragma Preelaborate;
subtype Token is WebIDL.Tokens.Token;
type Scanner is tagged limited private;
procedure Set_Source
(Self : in out Scanner'Class;
Source : not null WebIDL.Abstract_Sources.Source_Access);
procedure Set_Handler
(Self : in out Scanner'Class;
Handler : not null WebIDL.Scanner_Handlers.Handler_Access);
subtype Start_Condition is State;
procedure Set_Start_Condition
(Self : in out Scanner'Class; Condition : Start_Condition);
function Get_Start_Condition
(Self : Scanner'Class) return Start_Condition;
procedure Get_Token (Self : access Scanner'Class; Result : out Token);
function Get_Text
(Self : Scanner'Class) return League.Strings.Universal_String;
function Get_Token_Length (Self : Scanner'Class) return Positive;
function Get_Token_Position (Self : Scanner'Class) return Positive;
private
Buffer_Half_Size : constant := 2048;
subtype Buffer_Index is Positive range 1 .. 2 * Buffer_Half_Size;
type Character_Class_Array is array (Buffer_Index) of Character_Class;
Error_Character : constant Character_Class := 0;
Error_State : constant State := State'Last;
type Buffer_Half is (Low, High);
type Buffer_Offset is array (Buffer_Half) of Natural;
type Scanner is tagged limited record
Handler : WebIDL.Scanner_Handlers.Handler_Access;
Source : WebIDL.Abstract_Sources.Source_Access;
Start : State := INITIAL;
Next : Buffer_Index := 1;
From : Buffer_Index := 1;
To : Natural := 0;
Rule : Scanner_Types.Rule_Index;
Offset : Buffer_Offset := (0, 0);
Buffer : Wide_Wide_String (Buffer_Index) :=
(1 => Wide_Wide_Character'Val (WebIDL.Abstract_Sources.End_Of_Buffer),
others => <>);
Classes : Character_Class_Array := (1 => Error_Character, others => <>);
end record;
procedure Read_Buffer (Self : in out Scanner'Class);
end WebIDL.Scanners;
|
--
-- Copyright (C) 2015-2017 secunet Security Networks AG
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
with HW.GFX.GMA.Config;
with HW.GFX.GMA.Panel;
with HW.GFX.GMA.Connectors.DDI;
with HW.Debug;
with GNAT.Source_Info;
package body HW.GFX.GMA.Connectors is
procedure Post_Reset_Off
is
begin
DDI.Post_Reset_Off;
end Post_Reset_Off;
procedure Initialize
is
begin
DDI.Initialize;
end Initialize;
procedure Pre_On
(Pipe : in Pipe_Index;
Port_Cfg : in Port_Config;
PLL_Hint : in Word32;
Success : out Boolean)
is
begin
pragma Debug (Debug.Put_Line (GNAT.Source_Info.Enclosing_Entity));
if Port_Cfg.Port in Digital_Port then
DDI.Pre_On (Port_Cfg, PLL_Hint, Success);
else
Success := False; -- Should not happen
end if;
end Pre_On;
procedure Post_On
(Pipe : in Pipe_Index;
Port_Cfg : in Port_Config;
PLL_Hint : in Word32;
Success : out Boolean)
is
begin
pragma Debug (Debug.Put_Line (GNAT.Source_Info.Enclosing_Entity));
if Port_Cfg.Port in Digital_Port then
DDI.Post_On (Port_Cfg);
if Port_Cfg.Port = DIGI_A then
Panel.Backlight_On;
end if;
Success := True;
else
Success := False; -- Should not happen
end if;
end Post_On;
----------------------------------------------------------------------------
procedure Pre_Off (Port_Cfg : Port_Config)
is
begin
pragma Debug (Debug.Put_Line (GNAT.Source_Info.Enclosing_Entity));
if Port_Cfg.Port = DIGI_A then
Panel.Backlight_Off;
Panel.Off;
end if;
end Pre_Off;
procedure Post_Off (Port_Cfg : Port_Config)
is
begin
pragma Debug (Debug.Put_Line (GNAT.Source_Info.Enclosing_Entity));
if Port_Cfg.Port in Digital_Port then
DDI.Off (Port_Cfg.Port);
end if;
end Post_Off;
----------------------------------------------------------------------------
procedure Pre_All_Off
is
begin
Panel.Backlight_Off;
Panel.Off;
end Pre_All_Off;
procedure Post_All_Off
is
begin
for Port in Digital_Port range DIGI_A .. Config.Last_Digital_Port loop
DDI.Off (Port);
end loop;
end Post_All_Off;
end HW.GFX.GMA.Connectors;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- S E M _ M E C H --
-- --
-- B o d y --
-- --
-- $Revision$
-- --
-- Copyright (C) 1996-2001 Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, --
-- MA 02111-1307, USA. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Atree; use Atree;
with Einfo; use Einfo;
with Errout; use Errout;
with Targparm; use Targparm;
with Nlists; use Nlists;
with Sem; use Sem;
with Sem_Util; use Sem_Util;
with Sinfo; use Sinfo;
with Snames; use Snames;
with Stand; use Stand;
package body Sem_Mech is
-------------------------
-- Set_Mechanism_Value --
-------------------------
procedure Set_Mechanism_Value (Ent : Entity_Id; Mech_Name : Node_Id) is
Class : Node_Id;
Param : Node_Id;
procedure Bad_Class;
-- Signal bad descriptor class name
procedure Bad_Mechanism;
-- Signal bad mechanism name
procedure Bad_Class is
begin
Error_Msg_N ("unrecognized descriptor class name", Class);
end Bad_Class;
procedure Bad_Mechanism is
begin
Error_Msg_N ("unrecognized mechanism name", Mech_Name);
end Bad_Mechanism;
-- Start of processing for Set_Mechanism_Value
begin
if Mechanism (Ent) /= Default_Mechanism then
Error_Msg_NE
("mechanism for & has already been set", Mech_Name, Ent);
end if;
-- MECHANISM_NAME ::= value | reference | descriptor
if Nkind (Mech_Name) = N_Identifier then
if Chars (Mech_Name) = Name_Value then
Set_Mechanism_With_Checks (Ent, By_Copy, Mech_Name);
return;
elsif Chars (Mech_Name) = Name_Reference then
Set_Mechanism_With_Checks (Ent, By_Reference, Mech_Name);
return;
elsif Chars (Mech_Name) = Name_Descriptor then
Check_VMS (Mech_Name);
Set_Mechanism_With_Checks (Ent, By_Descriptor, Mech_Name);
return;
elsif Chars (Mech_Name) = Name_Copy then
Error_Msg_N
("bad mechanism name, Value assumed", Mech_Name);
Set_Mechanism (Ent, By_Copy);
else
Bad_Mechanism;
return;
end if;
-- MECHANISM_NAME ::= descriptor (CLASS_NAME)
-- CLASS_NAME ::= ubs | ubsb | uba | s | sb | a | nca
-- Note: this form is parsed as an indexed component
elsif Nkind (Mech_Name) = N_Indexed_Component then
Class := First (Expressions (Mech_Name));
if Nkind (Prefix (Mech_Name)) /= N_Identifier
or else Chars (Prefix (Mech_Name)) /= Name_Descriptor
or else Present (Next (Class))
then
Bad_Mechanism;
return;
end if;
-- MECHANISM_NAME ::= descriptor (Class => CLASS_NAME)
-- CLASS_NAME ::= ubs | ubsb | uba | s | sb | a | nca
-- Note: this form is parsed as a function call
elsif Nkind (Mech_Name) = N_Function_Call then
Param := First (Parameter_Associations (Mech_Name));
if Nkind (Name (Mech_Name)) /= N_Identifier
or else Chars (Name (Mech_Name)) /= Name_Descriptor
or else Present (Next (Param))
or else No (Selector_Name (Param))
or else Chars (Selector_Name (Param)) /= Name_Class
then
Bad_Mechanism;
return;
else
Class := Explicit_Actual_Parameter (Param);
end if;
else
Bad_Mechanism;
return;
end if;
-- Fall through here with Class set to descriptor class name
Check_VMS (Mech_Name);
if Nkind (Class) /= N_Identifier then
Bad_Class;
return;
elsif Chars (Class) = Name_UBS then
Set_Mechanism_With_Checks (Ent, By_Descriptor_UBS, Mech_Name);
elsif Chars (Class) = Name_UBSB then
Set_Mechanism_With_Checks (Ent, By_Descriptor_UBSB, Mech_Name);
elsif Chars (Class) = Name_UBA then
Set_Mechanism_With_Checks (Ent, By_Descriptor_UBA, Mech_Name);
elsif Chars (Class) = Name_S then
Set_Mechanism_With_Checks (Ent, By_Descriptor_S, Mech_Name);
elsif Chars (Class) = Name_SB then
Set_Mechanism_With_Checks (Ent, By_Descriptor_SB, Mech_Name);
elsif Chars (Class) = Name_A then
Set_Mechanism_With_Checks (Ent, By_Descriptor_A, Mech_Name);
elsif Chars (Class) = Name_NCA then
Set_Mechanism_With_Checks (Ent, By_Descriptor_NCA, Mech_Name);
else
Bad_Class;
return;
end if;
end Set_Mechanism_Value;
-------------------------------
-- Set_Mechanism_With_Checks --
-------------------------------
procedure Set_Mechanism_With_Checks
(Ent : Entity_Id;
Mech : Mechanism_Type;
Enod : Node_Id)
is
begin
-- Right now we only do some checks for functions returning arguments
-- by desctiptor. Probably mode checks need to be added here ???
if Mech in Descriptor_Codes and then not Is_Formal (Ent) then
if Is_Record_Type (Etype (Ent)) then
Error_Msg_N ("?records cannot be returned by Descriptor", Enod);
return;
end if;
end if;
-- If we fall through, all checks have passed
Set_Mechanism (Ent, Mech);
end Set_Mechanism_With_Checks;
--------------------
-- Set_Mechanisms --
--------------------
procedure Set_Mechanisms (E : Entity_Id) is
Formal : Entity_Id;
Typ : Entity_Id;
begin
-- Skip this processing if inside a generic template. Not only is
-- it uneccessary (since neither extra formals nor mechanisms are
-- relevant for the template itself), but at least at the moment,
-- procedures get frozen early inside a template so attempting to
-- look at the formal types does not work too well if they are
-- private types that have not been frozen yet.
if Inside_A_Generic then
return;
end if;
-- Loop through formals
Formal := First_Formal (E);
while Present (Formal) loop
if Mechanism (Formal) = Default_Mechanism then
Typ := Underlying_Type (Etype (Formal));
-- If there is no underlying type, then skip this processing and
-- leave the convention set to Default_Mechanism. It seems odd
-- that there should ever be such cases but there are (see
-- comments for filed regression tests 1418-001 and 1912-009) ???
if No (Typ) then
goto Skip_Formal;
end if;
case Convention (E) is
---------
-- Ada --
---------
-- Note: all RM defined conventions are treated the same
-- from the point of view of parameter passing mechanims
when Convention_Ada |
Convention_Intrinsic |
Convention_Entry |
Convention_Protected |
Convention_Stubbed =>
-- By reference types are passed by reference (RM 6.2(4))
if Is_By_Reference_Type (Typ) then
Set_Mechanism (Formal, By_Reference);
-- By copy types are passed by copy (RM 6.2(3))
elsif Is_By_Copy_Type (Typ) then
Set_Mechanism (Formal, By_Copy);
-- All other types we leave the Default_Mechanism set, so
-- that the backend can choose the appropriate method.
else
null;
end if;
-------
-- C --
-------
-- Note: Assembler, C++, Java, Stdcall also use C conventions
when Convention_Assembler |
Convention_C |
Convention_CPP |
Convention_Java |
Convention_Stdcall =>
-- The following values are passed by copy
-- IN Scalar parameters (RM B.3(66))
-- IN parameters of access types (RM B.3(67))
-- Access parameters (RM B.3(68))
-- Access to subprogram types (RM B.3(71))
-- Note: in the case of access parameters, it is the
-- pointer that is passed by value. In GNAT access
-- parameters are treated as IN parameters of an
-- anonymous access type, so this falls out free.
-- The bottom line is that all IN elementary types
-- are passed by copy in GNAT.
if Is_Elementary_Type (Typ) then
if Ekind (Formal) = E_In_Parameter then
Set_Mechanism (Formal, By_Copy);
-- OUT and IN OUT parameters of elementary types are
-- passed by reference (RM B.3(68)). Note that we are
-- not following the advice to pass the address of a
-- copy to preserve by copy semantics.
else
Set_Mechanism (Formal, By_Reference);
end if;
-- Records are normally passed by reference (RM B.3(69)).
-- However, this can be overridden by the use of the
-- C_Pass_By_Copy pragma or C_Pass_By_Copy convention.
elsif Is_Record_Type (Typ) then
-- If the record is not convention C, then we always
-- pass by reference, C_Pass_By_Copy does not apply.
if Convention (Typ) /= Convention_C then
Set_Mechanism (Formal, By_Reference);
-- If convention C_Pass_By_Copy was specified for
-- the record type, then we pass by copy.
elsif C_Pass_By_Copy (Typ) then
Set_Mechanism (Formal, By_Copy);
-- Otherwise, for a C convention record, we set the
-- convention in accordance with a possible use of
-- the C_Pass_By_Copy pragma. Note that the value of
-- Default_C_Record_Mechanism in the absence of such
-- a pragma is By_Reference.
else
Set_Mechanism (Formal, Default_C_Record_Mechanism);
end if;
-- Array types are passed by reference (B.3 (71))
elsif Is_Array_Type (Typ) then
Set_Mechanism (Formal, By_Reference);
-- For all other types, use Default_Mechanism mechanism
else
null;
end if;
-----------
-- COBOL --
-----------
when Convention_COBOL =>
-- Access parameters (which in GNAT look like IN parameters
-- of an access type) are passed by copy (RM B.4(96)) as
-- are all other IN parameters of scalar type (RM B.4(97)).
-- For now we pass these parameters by reference as well.
-- The RM specifies the intent BY_CONTENT, but gigi does
-- not currently transform By_Copy properly. If we pass by
-- reference, it will be imperative to introduce copies ???
if Is_Elementary_Type (Typ)
and then Ekind (Formal) = E_In_Parameter
then
Set_Mechanism (Formal, By_Reference);
-- All other parameters (i.e. all non-scalar types, and
-- all OUT or IN OUT parameters) are passed by reference.
-- Note that at the moment we are not bothering to make
-- copies of scalar types as recommended in the RM.
else
Set_Mechanism (Formal, By_Reference);
end if;
-------------
-- Fortran --
-------------
when Convention_Fortran =>
-- In OpenVMS, pass a character of array of character
-- value using Descriptor(S). Should this also test
-- Debug_Flag_M ???
if OpenVMS_On_Target
and then (Root_Type (Typ) = Standard_Character
or else
(Is_Array_Type (Typ)
and then
Root_Type (Component_Type (Typ)) =
Standard_Character))
then
Set_Mechanism (Formal, By_Descriptor_S);
-- Access types are passed by default (presumably this
-- will mean they are passed by copy)
elsif Is_Access_Type (Typ) then
null;
-- For now, we pass all other parameters by reference.
-- It is not clear that this is right in the long run,
-- but it seems to correspond to what gnu f77 wants.
else
Set_Mechanism (Formal, By_Reference);
end if;
end case;
end if;
<<Skip_Formal>> -- remove this when problem above is fixed ???
Next_Formal (Formal);
end loop;
-- Now deal with return type, we always leave the default mechanism
-- set except for the case of returning a By_Reference type for an
-- Ada convention, where we force return by reference
if Ekind (E) = E_Function
and then Mechanism (E) = Default_Mechanism
and then not Has_Foreign_Convention (E)
and then Is_By_Reference_Type (Etype (E))
then
Set_Mechanism (E, By_Reference);
end if;
end Set_Mechanisms;
end Sem_Mech;
|
------------------------------------------------------------------------------
-- Copyright (c) 2011, 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.Getopt_Long is a native Ada implementation of getopt_long() --
-- processor for command line arguments. --
-- --
-- This package is generic, and its only formal parameter is a descrete --
-- type supposed to cover all command-line options. --
-- --
-- Configuration objects hold the list of recognized options and parameters --
-- about how to process them. Options can have a single-character short --
-- name or a multiple-character long name. Moreover, there is no limit to --
-- the number of flag names referring to the same Option_Id value. --
-- --
-- Once the Configuration object has been filled with flags recognized --
-- by the client, the actual command-line arguments can be processed, --
-- using the handler callbacks from a Handlers.Callback'Class object. --
-- --
-- Callback subprograms for normal operation are Option, for command-line --
-- flags identified by their Option_Id, and Argument, for top-level command --
-- line arguments. There are also callbacks for error conditions (missing --
-- or unexpected argument, unknown option), whose implementation in --
-- Handlers.Callback are simply to raise Option_Error with an appropriate --
-- message. --
------------------------------------------------------------------------------
with Ada.Command_Line;
private with Ada.Containers.Indefinite_Ordered_Maps;
generic
type Option_Id is (<>);
package Natools.Getopt_Long is
pragma Preelaborate (Getopt_Long);
Null_Long_Name : constant String := "";
Null_Short_Name : constant Character := Character'Val (0);
------------------------------------------
-- Holder for both short and long names --
------------------------------------------
type Name_Style is (Long, Short);
type Any_Name (Style : Name_Style; Size : Positive) is record
case Style is
when Short =>
Short : Character;
when Long =>
Long : String (1 .. Size);
end case;
end record;
function To_Name (Long_Name : String) return Any_Name;
function To_Name (Short_Name : Character) return Any_Name;
function Image (Name : Any_Name) return String;
------------------------
-- Callback interface --
------------------------
Option_Error : exception;
package Handlers is
type Callback is abstract tagged null record;
procedure Option
(Handler : in out Callback;
Id : Option_Id;
Argument : String)
is abstract;
-- Callback for successfully-parsed options.
procedure Argument
(Handler : in out Callback;
Argument : String)
is abstract;
-- Callback for non-flag arguments.
procedure Missing_Argument
(Handler : in out Callback;
Id : Option_Id;
Name : Any_Name);
-- Raise Option_Error (default error handler).
procedure Unexpected_Argument
(Handler : in out Callback;
Id : Option_Id;
Name : Any_Name;
Argument : String);
-- Raise Option_Error (default error handler).
procedure Unknown_Option
(Handler : in out Callback;
Name : Any_Name);
-- Raise Option_Error (default error handler).
end Handlers;
----------------------------
-- Configuration database --
----------------------------
type Argument_Requirement is
(No_Argument, Required_Argument, Optional_Argument);
type Configuration is tagged private;
-- Simple parameters --
function Posixly_Correct (Config : Configuration) return Boolean;
procedure Posixly_Correct
(Config : in out Configuration;
To : Boolean := True);
function Long_Only (Config : Configuration) return Boolean;
procedure Use_Long_Only
(Config : in out Configuration;
Value : Boolean := True);
-- Option list management --
procedure Add_Option
(Config : in out Configuration;
Long_Name : String;
Short_Name : Character;
Has_Arg : Argument_Requirement;
Id : Option_Id);
-- Add an option with both a short and a long name to the database.
procedure Add_Option
(Config : in out Configuration;
Long_Name : String;
Has_Arg : Argument_Requirement;
Id : Option_Id);
-- Add an option with only a long name to the database.
procedure Add_Option
(Config : in out Configuration;
Short_Name : Character;
Has_Arg : Argument_Requirement;
Id : Option_Id);
-- Add an option with only a short name to the database.
procedure Del_Option
(Config : in out Configuration;
Id : Option_Id);
-- Remove from the database an option identified by its id.
procedure Del_Option
(Config : in out Configuration;
Long_Name : String);
-- Remove from the database an option identified by its long name.
procedure Del_Option
(Config : in out Configuration;
Short_Name : Character);
-- Remove from the database an option identified by its short name.
-- Formatting subprograms --
function Format_Long_Names
(Config : Configuration;
Id : Option_Id;
Separator : String := ", ";
Name_Prefix : String := "--")
return String;
-- Return a human-readable list of long names for the given option.
function Format_Names
(Config : Configuration;
Id : Option_Id;
Separator : String := ", ";
Long_Name_Prefix : String := "--";
Short_Name_Prefix : String := "-";
Short_First : Boolean := True)
return String;
-- Return a human-readable list of all names for the given option.
function Format_Short_Names
(Config : Configuration;
Id : Option_Id;
Separator : String := ", ";
Name_Prefix : String := "-")
return String;
-- Return a human-readable list of short names for the given option.
function Get_Long_Name
(Config : Configuration;
Id : Option_Id;
Index : Positive := 1)
return String;
-- Return the "Index"th long name for the given option id.
-- Raise Constraint_Error when Index is not
-- in range 1 .. Get_Long_Name_Count (Config, Id)
function Get_Long_Name_Count
(Config : Configuration;
Id : Option_Id)
return Natural;
-- Return the number of long names for the given option id.
function Get_Short_Name_Count
(Config : Configuration;
Id : Option_Id)
return Natural;
-- Return the number of short names for the given option id.
function Get_Short_Names
(Config : Configuration;
Id : Option_Id)
return String;
-- Return a string containing the characters for short names for
-- the given option id.
procedure Iterate
(Config : Configuration;
Process : not null access procedure (Id : Option_Id;
Long_Name : String;
Short_Name : Character;
Has_Arg : Argument_Requirement));
-- Iterate over all options, starting with options having a short name,
-- followed by options having only a long name, sorted respectively by
-- short and long name.
-- Process is called for each option; for options lacking a long name,
-- Long_Name is "", and for options lacking a short name, Short_Name
-- is Character'Val (0).
--------------------------------------
-- Command line argument processing --
--------------------------------------
procedure Process
(Config : Configuration;
Handler : in out Handlers.Callback'Class;
Argument_Count : not null access function return Natural
:= Ada.Command_Line.Argument_Count'Access;
Argument : not null access function (Number : Positive) return String
:= Ada.Command_Line.Argument'Access);
-- Process system command line argument list, using the provided option
-- definitions and handler callbacks.
private
type Option (Long_Name_Length : Natural) is record
Id : Option_Id;
Has_Arg : Argument_Requirement;
Long_Name : String (1 .. Long_Name_Length);
Short_Name : Character;
end record;
package Long_Option_Maps is
new Ada.Containers.Indefinite_Ordered_Maps (String, Option);
package Short_Option_Maps is
new Ada.Containers.Indefinite_Ordered_Maps (Character, Option);
type Configuration is tagged record
By_Long_Name : Long_Option_Maps.Map;
By_Short_Name : Short_Option_Maps.Map;
Posixly_Correct : Boolean := True;
Long_Only : Boolean := False;
end record;
end Natools.Getopt_Long;
|
------------------------------------------------------------------------------
-- --
-- GNAT EXAMPLE --
-- --
-- Copyright (C) 2013-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. --
-- --
------------------------------------------------------------------------------
pragma Restrictions (No_Elaboration_Code);
-- This subprogram is called before elaboration
pragma Warnings (Off);
with System.SAM4S; use System.SAM4S;
pragma Warnings (On);
with Interfaces.SAM; use Interfaces.SAM;
with Interfaces.SAM.EFC; use Interfaces.SAM.EFC;
with Interfaces.SAM.PMC; use Interfaces.SAM.PMC;
with Interfaces.SAM.SYSC; use Interfaces.SAM.SYSC;
procedure Setup_Pll is
CKGR_MOR : CKGR_MOR_Register;
begin
-- Main crystal is 12 Mhz and PLLA is set to x10. So main clock is 120 Mhz.
-- 5 wait states for the flash
EFC0_Periph.FMR.FWS := 5;
-- 28.2.13 Programming Sequence
-- 1. Enabling the Main Oscillator:
-- The main oscillator is enabled by setting the MOSCXTEN field in
-- the Main Oscillator Register (CKGR_MOR). The user can define a
-- start-up time. This can be achieved by writing a value in the
-- MOSCXTST field in CKGR_MOR. Once this register has been
-- correctly configured, the user must wait for MOSCXTS field in
-- the PMC_SR register to be set. This can be done either by
-- polling the status register, or by waiting the interrupt line
-- to be raised if the associated inter- rupt to MOSCXTS has been
-- enabled in the PMC_IER register.
CKGR_MOR := PMC_Periph.CKGR_MOR;
-- The Key field needs to be set to 0x37 to enable write to the
-- CKGR_MOR register
CKGR_MOR.KEY := Passwd;
CKGR_MOR.MOSCXTEN := True;
CKGR_MOR.MOSCXTST := 62;
PMC_Periph.CKGR_MOR := CKGR_MOR;
-- Wait until the xtal stabilize
while not PMC_Periph.PMC_SR.MOSCXTS loop
null;
end loop;
-- Select the xtal (must already be true, but doesn't harm)
CKGR_MOR := PMC_Periph.CKGR_MOR;
-- The Key field needs to be set to 0x37 to enable write to the
-- CKGR_MOR register
CKGR_MOR.KEY := Passwd;
CKGR_MOR.MOSCSEL := True;
PMC_Periph.CKGR_MOR := CKGR_MOR;
-- 2. Checking the Main Oscillator Frequency (Optional):
-- In some situations the user may need an accurate measure of the
-- main clock frequency. This measure can be accomplished via the
-- Main Clock Frequency Register (CKGR_MCFR). Once the MAINFRDY
-- field is set in CKGR_MCFR, the user may read the MAINF field in
-- CKGR_MCFR by performing another CKGR_MCFR read access. This
-- provides the number of main clock cycles within sixteen slow
-- clock cycles.
null;
-- 3. Setting PLL and Divider:
-- All parameters needed to configure PLLA and the divider are
-- located in CKGR_PLLAxR.
-- The DIV field is used to control the divider itself. It must be
-- set to 1 when PLL is used. By default, DIV parameter is set to
-- 0 which means that the divider is turned off.
-- The MUL field is the PLL multiplier factor. This parameter can
-- be programmed between 0 and 80. If MUL is set to 0, PLL will be
-- turned off, otherwise the PLL output frequency is PLL input
-- frequency multiplied by (MUL + 1).
-- The PLLCOUNT field specifies the number of slow clock cycles
-- before the LOCK bit is set in PMC_SR, after CKGR_PLLA(B)R has
-- been written.
-- First disable: MULA set to 0, DIVA set to 0
PMC_Periph.CKGR_PLLAR :=
(ONE => True,
MULA => 0,
DIVA => 0,
others => <>);
PMC_Periph.CKGR_PLLAR :=
(ONE => True,
DIVA => 1,
MULA => 10 - 1,
others => <>);
-- Once the CKGR_PLL register has been written, the user must wait
-- for the LOCK bit to be set in the PMC_SR. This can be done
-- either by polling the status register or by waiting the
-- interrupt line to be raised if the associated interrupt to LOCK
-- has been enabled in PMC_IER. All parameters in CKGR_PLLA(B)R
-- can be programmed in a single write operation. If at some stage
-- one of the following parameters, MUL or DIV is modified, the
-- LOCK bit will go low to indicate that PLL is not ready
-- yet. When PLL is locked, LOCK will be set again. The user is
-- constrained to wait for LOCK bit to be set before using the PLL
-- output clock.
while not PMC_Periph.PMC_SR.LOCKA loop
null;
end loop;
-- 4. Selection of Master Clock and Processor Clock
-- The Master Clock and the Processor Clock are configurable via
-- the Master Clock Register (PMC_MCKR).
-- The CSS field is used to select the Master Clock divider
-- source. By default, the selected clock source is main clock.
-- The PRES field is used to control the Master Clock
-- prescaler. The user can choose between different values (1, 2,
-- 3, 4, 8, 16, 32, 64). Master Clock output is prescaler input
-- divided by PRES parameter. By default, PRES parameter is set to
-- 1 which means that master clock is equal to main clock.
-- Once PMC_MCKR has been written, the user must wait for the
-- MCKRDY bit to be set in PMC_SR. This can be done either by
-- polling the status register or by waiting for the interrupt
-- line to be raised if the associated interrupt to MCKRDY has
-- been enabled in the PMC_IER register.
-- The PMC_MCKR must not be programmed in a single write
-- operation. The preferred programming sequence for PMC_MCKR is
-- as follows:
-- * If a new value for CSS field corresponds to PLL Clock,
-- * Program the PRES field in PMC_MCKR.
-- * Wait for the MCKRDY bit to be set in PMC_SR.
-- * Program the CSS field in PMC_MCKR.
-- * Wait for the MCKRDY bit to be set in PMC_SR.
-- * If a new value for CSS field corresponds to Main Clock
-- or Slow Clock,
-- * Program the CSS field in PMC_MCKR.
-- * Wait for the MCKRDY bit to be set in the PMC_SR.
-- * Program the PRES field in PMC_MCKR.
-- * Wait for the MCKRDY bit to be set in PMC_SR.
PMC_Periph.PMC_MCKR.PRES := Clk_1;
while not PMC_Periph.PMC_SR.MCKRDY loop
null;
end loop;
PMC_Periph.PMC_MCKR.CSS := Plla_Clk;
while not PMC_Periph.PMC_SR.MCKRDY loop
null;
end loop;
-- If at some stage one of the following parameters, CSS or PRES
-- is modified, the MCKRDY bit will go low to indicate that the
-- Master Clock and the Processor Clock are not ready yet. The
-- user must wait for MCKRDY bit to be set again before using the
-- Master and Processor Clocks.
-- Note: IF PLLx clock was selected as the Master Clock and the
-- user decides to modify it by writing in CKGR_PLLR, the MCKRDY
-- flag will go low while PLL is unlocked. Once PLL is locked
-- again, LOCK goes high and MCKRDY is set.
-- While PLL is unlocked, the Master Clock selection is
-- automatically changed to Slow Clock. For further information,
-- see Section 28.2.14.2 "Clock Switching Waveforms" on page 467.
-- Code Example:
-- write_register(PMC_MCKR,0x00000001)
-- wait (MCKRDY=1)
-- write_register(PMC_MCKR,0x00000011)
-- wait (MCKRDY=1)
-- The Master Clock is main clock divided by 2.
-- The Processor Clock is the Master Clock.
-- 5. Selection of Programmable Clocks
-- Programmable clocks are controlled via registers, PMC_SCER,
-- PMC_SCDR and PMC_SCSR.
-- Programmable clocks can be enabled and/or disabled via PMC_SCER
-- and PMC_SCDR. 3 Programmable clocks can be enabled or
-- disabled. The PMC_SCSR provides a clear indication as to which
-- Programmable clock is enabled. By default all Programmable
-- clocks are disabled.
-- Programmable Clock Registers (PMC_PCKx) are used to configure
-- Programmable clocks.
-- The CSS field is used to select the Programmable clock divider
-- source. Four clock options are available: main clock, slow
-- clock, PLLACK, PLLBCK. By default, the clock source selected is
-- slow clock.
-- The PRES field is used to control the Programmable clock
-- prescaler. It is possible to choose between different values
-- (1, 2, 4, 8, 16, 32, 64). Programmable clock output is
-- prescaler input divided by PRES parameter. By default, the PRES
-- parameter is set to 0 which means that master clock is equal to
-- slow clock.
-- Once PMC_PCKx has been programmed, The corresponding
-- Programmable clock must be enabled and the user is constrained
-- to wait for the PCKRDYx bit to be set in PMC_SR. This can be
-- done either by polling the status register or by waiting the
-- interrupt line to be raised, if the associated interrupt to
-- PCKRDYx has been enabled in the PMC_IER register. All parameters in
-- PMC_PCKx can be programmed in a single write operation.
-- If the CSS and PRES parameters are to be modified, the
-- corresponding Programmable clock must be disabled first. The
-- parameters can then be modified. Once this has been done, the
-- user must re-enable the Programmable clock and wait for the
-- PCKRDYx bit to be set.
null;
-- 6. Enabling Peripheral Clocks
-- Once all of the previous steps have been completed, the
-- peripheral clocks can be enabled and/or disabled via registers
-- PMC_PCER0, PMC_PCER, PMC_PCDR0 and PMC_PCDR.
null;
-- Disable watchdog. The register can be written once, so this file has
-- to be modified to enable watchdog.
WDT_Periph.MR.WDDIS := True;
end Setup_Pll;
|
with Ada.Text_IO; use Ada.Text_IO;
with YAML;
use type YAML.Error_Kind;
procedure Parser is
function LStrip (S : String) return String;
function Image (M : YAML.Mark_Type) return String;
procedure Process (P : in out YAML.Parser_Type);
procedure Put (N : YAML.Node_Ref; Indent : Natural);
function LStrip (S : String) return String is
begin
return (if S (S'First) = ' '
then S (S'First + 1 .. S'Last)
else S);
end LStrip;
function Image (M : YAML.Mark_Type) return String is
begin
return LStrip (Natural'Image (M.Line))
& ':' & LStrip (Natural'Image (M.Column));
end Image;
procedure Process (P : in out YAML.Parser_Type) is
D : YAML.Document_Type;
E : YAML.Error_Type;
begin
P.Load (E, D);
if E.Kind /= YAML.No_Error then
Put_Line (YAML.Image (E));
else
Put (D.Root_Node, 0);
end if;
P.Discard_Input;
New_Line;
end Process;
procedure Put (N : YAML.Node_Ref; Indent : Natural) is
Prefix : constant String := (1 .. Indent => ' ');
begin
Put (Prefix
& '[' & Image (N.Start_Mark) & '-' & Image (N.End_Mark) & "]");
case YAML.Kind (N) is
when YAML.No_Node =>
Put_Line (" <null>");
when YAML.Scalar_Node =>
Put_Line (' ' & String (N.Value));
when YAML.Sequence_Node =>
for I in 1 .. N.Length loop
New_Line;
Put_Line (Prefix & "- ");
Put (N.Item (I), Indent + 2);
end loop;
when YAML.Mapping_Node =>
New_Line;
Put_Line (Prefix & "Pairs:");
for I in 1 .. N.Length loop
declare
Pair : constant YAML.Node_Pair := N.Item (I);
begin
Put (Prefix & "Key:");
Put (Pair.Key, Indent + 2);
Put (Prefix & "Value:");
Put (Pair.Value, Indent + 2);
end;
end loop;
end case;
end Put;
P : YAML.Parser_Type;
begin
P.Set_Input_String ("1", YAML.UTF8_Encoding);
Process (P);
P.Set_Input_String ("[1, 2, 3, a, null]", YAML.UTF8_Encoding);
Process (P);
P.Set_Input_String ("foo: 1", YAML.UTF8_Encoding);
Process (P);
P.Set_Input_File ("parser-valid.yaml", YAML.UTF8_Encoding);
Process (P);
P.Set_Input_File ("parser-scanner-error-0.yaml", YAML.UTF8_Encoding);
Process (P);
P.Set_Input_File ("parser-scanner-error-1.yaml", YAML.UTF8_Encoding);
Process (P);
P.Set_Input_File ("parser-parser-error-0.yaml", YAML.UTF8_Encoding);
Process (P);
P.Set_Input_File ("parser-parser-error-1.yaml", YAML.UTF8_Encoding);
Process (P);
end Parser;
|
generic
type Elem is private;
package generic_package_declaration is
procedure Exchange(U, V : in out Elem);
end generic_package_declaration;
|
generic
type T is (<>);
with function MAX_ADD(X : T; I : INTEGER) return T;
package Discr16_G is
LO : T := T'val(T'pos(T'first));
HI : T := T'val(T'pos(MAX_ADD(LO, 15)));
type A2 is array(T range <>) of T;
type R2(D : T) is
record
C : A2(LO..D);
end record;
end;
|
------------------------------------------------------------------------------
-- --
-- J E W L --
-- --
-- Body of the top-level package providing I/O and Windows facilities --
-- for beginners. --
-- --
-- Copyright (C) John English 2000. Contact address: je@brighton.ac.uk --
-- This software is released under the terms of the GNU General Public --
-- License and is intended primarily for educational use. Please contact --
-- the author to report bugs, suggestions and modifications. --
-- --
------------------------------------------------------------------------------
-- $Id: jewl.adb 1.7 2007/01/08 17:00:00 JE Exp $
------------------------------------------------------------------------------
--
-- $Log: jewl.adb $
-- Revision 1.7 2007/01/08 17:00:00 JE
-- * Fixed linker options in JEWL.Win32_Interface to accommodate changes to GNAT
-- GPL 2006 compiler (thanks to John McCormick for this)
-- * Added delay in message loop to avoid the appearance of hogging 100% of CPU
-- time
--
-- Revision 1.6 2001/11/02 16:00:00 JE
-- * Fixed canvas bug when saving an empty canvas
-- * Restore with no prior save now acts as erase
-- * Removed redundant variable declaration in Image function
--
-- Revision 1.5 2001/08/22 15:00:00 JE
-- * Minor bugfix to Get_Text for combo boxes
-- * Minor changes to documentation (including new example involving dialogs)
--
-- Revision 1.4 2001/01/25 09:00:00 je
-- Changes visible to the user:
--
-- * Added support for drawing bitmaps on canvases (Draw_Image operations
-- and new type Image_Type)
-- * Added Play_Sound
-- * Added several new operations on all windows: Get_Origin, Get_Width,
-- Get_Height, Set_Origin, Set_Size and Focus
-- * Added several functions giving screen and window dimensions: Screen_Width,
-- Screen_Height, Frame_Width, Frame_Height, Dialog_Width, Dialog_Height and
-- Menu_Height
-- * Canvases can now handle keyboard events: new constructor and Key_Code added
-- * Added procedure Play_Sound
-- * Operations "+" and "-" added for Point_Type
-- * Pens can now be zero pixels wide
-- * The absolute origin of a frame can now have be specified when the frame
-- is created
-- * Added new File_Dialog operations Add_Filter and Set_Directory
-- * Added Get_Line renames to JEWL.IO for compatibility with Ada.Text_IO
-- * Added all the Get(File,Item) operations mentioned in documentation but
-- unaccountably missing :-(
-- * Documentation updated to reflect the above changes
-- * HTML versions of public package specifications added with links from
-- main documentation pages
--
-- Other internal changes:
--
-- * Canvas fonts, pens etc. now use JEWL.Reference_Counted_Type rather than
-- reinventing this particular wheel, as do images
-- * Various minor code formatting changes: some code reordered for clarity,
-- some comments added or amended,
-- * Changes introduced in 1.2 to support GNAT 3.10 have been reversed, since
-- GNAT 3.10 still couldn't compile this code correctly... ;-(
--
-- Outstanding issues:
--
-- * Optimisation breaks the code (workaround: don't optimise)
--
-- Revision 1.3 2000/07/07 12:00:00 je
-- * JEWL.Simple_Windows added; JEWL.IO modified to use JEWL.Simple_Windows.
-- * JEWL.IO bug fix: Put_Line to file wrote newline to standard output
-- instead of to the file (thanks to Jeff Carter for pointing this out).
-- * Panels fixed so that mouse clicks are passed on correctly to subwindows.
-- * Memos fixed so that tabs are handled properly.
-- * Password feature added to editboxes.
-- * Minor typos fixed in comments within the package sources.
-- * Documentation corrected and updated following comments from Moti Ben-Ari
-- and Don Overheu.
--
-- Revision 1.2 2000/04/18 20:00:00 je
-- * Minor code changes to enable compilation by GNAT 3.10
-- * Minor documentation errors corrected
-- * Some redundant "with" clauses removed
--
-- Revision 1.1 2000/04/18 20:00:00 je
-- Initial revision
--
-- Revision 1.1 2000/04/09 21:00:00 je
-- Initial revision
--
------------------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;
package body JEWL is
----------------------------------------------------------------------------
--
-- O P E R A T I O N S O N S U P P O R T T Y P E S
--
----------------------------------------------------------------------------
--
-- Light: generate a lightened version of a given colour by increasing the
-- intensity of each hue by 50%.
--
function Light (Colour : Colour_Type) return Colour_Type is
begin
return (Red => (Colour.Red+Colour_Range'Last+1)/2,
Green => (Colour.Green+Colour_Range'Last+1)/2,
Blue => (Colour.Blue+Colour_Range'Last+1)/2);
end Light;
----------------------------------------------------------------------------
--
-- Dark: generate a darkened version of a given colour by decreasing the
-- intensity of each hue by 50%.
--
function Dark (Colour : Colour_Type) return Colour_Type is
begin
return (Red => Colour.Red/2,
Green => Colour.Green/2,
Blue => Colour.Blue/2);
end Dark;
----------------------------------------------------------------------------
--
-- Font: create a Font_Type structure which has the length of the font
-- name as a discriminant.
--
function Font (Name : String;
Size : Positive;
Bold : Boolean := False;
Italic : Boolean := False) return Font_Type is
F : Font_Type(Name'Length);
begin
F.Name := Name;
F.Size := Size;
F.Bold := Bold;
F.Italic := Italic;
return F;
end Font;
----------------------------------------------------------------------------
--
-- Name: get the name of a font's typeface.
--
function Name (Font : Font_Type) return String is
begin
return Font.Name;
end Name;
----------------------------------------------------------------------------
--
-- Size: get the size of a font in points.
--
function Size (Font : Font_Type) return Natural is
begin
return Font.Size;
end Size;
----------------------------------------------------------------------------
--
-- Bold: True is the specified font is bold.
--
function Bold (Font : Font_Type) return Boolean is
begin
return Font.Bold;
end Bold;
----------------------------------------------------------------------------
--
-- Italic: True is the specified font is italic.
--
function Italic (Font : Font_Type) return Boolean is
begin
return Font.Italic;
end Italic;
----------------------------------------------------------------------------
--
-- Endpoint: calculate the endpoint of a line drawn from a specified origin
-- for a given length at a given angle.
--
function Endpoint (From : Point_Type;
Length : Positive;
Angle : Angle_Type) return Point_Type is
begin
return (From.X + Integer(Float(Length)*Sin(Float(Angle),360.0)),
From.Y - Integer(Float(Length)*Cos(Float(Angle),360.0)));
end Endpoint;
----------------------------------------------------------------------------
--
-- Inside: test if Point is inside the rectangle defined by From and To,
-- bearing in mind that any two opposite corners can be given
-- (not necessarily top left and bottom right).
--
function Inside (Point : Point_Type;
From : Point_Type;
To : Point_Type) return Boolean is
begin
return Point.X >= Integer'Min(From.X,To.X) and
Point.X <= Integer'Max(From.X,To.X) and
Point.Y >= Integer'Min(From.Y,To.Y) and
Point.Y <= Integer'Max(From.Y,To.Y);
end Inside;
----------------------------------------------------------------------------
--
-- "+": add two points (P1.X + P2.X, P1.Y + P2.Y).
--
function "+" (P1, P2 : Point_Type) return Point_Type is
begin
return (X => P1.X+P2.X, Y => P1.Y+P2.Y);
end "+";
----------------------------------------------------------------------------
--
-- "-": subtract two points (P1.X - P2.X, P1.Y - P2.Y).
--
function "-" (P1, P2 : Point_Type) return Point_Type is
begin
return (X => P1.X-P2.X, Y => P1.Y-P2.Y);
end "-";
----------------------------------------------------------------------------
--
-- I N T E R N A L O P E R A T I O N S
--
----------------------------------------------------------------------------
--
-- Free: deallocate a reference-counted object.
--
procedure Free is new Ada.Unchecked_Deallocation
(Reference_Counted_Type'Class,
Reference_Counted_Ptr);
----------------------------------------------------------------------------
--
-- Cleanup: the finalisation primitive for reference-counted types.
-- Override this for derived types to do something useful.
--
procedure Cleanup (Object : in out Reference_Counted_Type) is
begin
null;
end Cleanup;
----------------------------------------------------------------------------
--
-- Finalize: decrement the reference count when an object containing
-- a pointer to a reference-counted object is destroyed.
-- When the reference count reaches zero, finalise the
-- reference-counted object and free its memory.
--
procedure Finalize (Object : in out Controlled_Type) is
begin
if Object.Pointer /= null then
if Object.Pointer.Count > 0 then
Object.Pointer.Count := Object.Pointer.Count - 1;
if Object.Pointer.Count = 0 then
Cleanup (Object.Pointer.all);
Free (Object.Pointer);
end if;
end if;
end if;
end Finalize;
----------------------------------------------------------------------------
-- Adjust: bump the reference count when copying an object containing a
-- pointer to a reference-counted object. Do nothing if the
-- pointer is null.
--
procedure Adjust (Object : in out Controlled_Type) is
begin
if Object.Pointer /= null then
Object.Pointer.Count := Object.Pointer.Count + 1;
end if;
end Adjust;
end JEWL;
|
with
GL,
GL.Binding,
openGL.Tasks,
interfaces.C;
package body openGL.Renderer
is
use GL,
interfaces.C;
procedure Background_is (Self : in out Item; Now : in openGL.Color;
Opacity : in Opaqueness := 1.0)
is
begin
Self.Background.Primary := +Now;
Self.Background.Alpha := to_color_Value (Primary (Opacity));
end Background_is;
procedure Background_is (Self : in out Item; Now : in openGL.lucid_Color)
is
begin
Self.Background := +Now;
end Background_is;
procedure clear_Frame (Self : in Item)
is
use GL.Binding;
check_is_OK : constant Boolean := openGL.Tasks.Check with Unreferenced;
begin
glClearColor (GLfloat (to_Primary (Self.Background.Primary.Red)),
GLfloat (to_Primary (Self.Background.Primary.Green)),
GLfloat (to_Primary (Self.Background.Primary.Blue)),
GLfloat (to_Primary (Self.Background.Alpha)));
glClear ( GL_COLOR_BUFFER_BIT
or GL_DEPTH_BUFFER_BIT);
glCullFace (GL_BACK);
glEnable (GL_CULL_FACE);
end clear_Frame;
end openGL.Renderer;
|
package body kv.avm.Methods is
----------------------------------------------------------------------------
function New_Method(Name : String; Code : kv.avm.Instructions.Code_Access) return Method_Access is
Method : Method_Access;
begin
Method := new Method_Type;
Method.Initialize(Name, Code);
return Method;
end New_Method;
----------------------------------------------------------------------------
procedure Initialize
(Self : in out Method_Type;
Name : in String;
Code : in kv.avm.Instructions.Code_Access) is
begin
Self.Name := new String'(Name);
Self.Code := Code;
end Initialize;
----------------------------------------------------------------------------
procedure Add_Predicate
(Self : in out Method_Type;
Predicate : in kv.avm.References.Offset_Type) is
begin
Self.Predicate := Predicate;
Self.Gated := True;
end Add_Predicate;
----------------------------------------------------------------------------
function Has_Predicate(Self : Method_Type) return Boolean is
begin
return Self.Gated;
end Has_Predicate;
----------------------------------------------------------------------------
function Get_Predicate(Self : Method_Type) return kv.avm.References.Offset_Type is
begin
return Self.Predicate;
end Get_Predicate;
----------------------------------------------------------------------------
function Get_Predicate(Self : Method_Type) return kv.avm.References.Reference_Type is
begin
return (Memory => kv.avm.References.Attribute, Index => Self.Predicate);
end Get_Predicate;
----------------------------------------------------------------------------
function Get_Name(Self : Method_Type) return String is
begin
return Self.Name.all;
end Get_Name;
----------------------------------------------------------------------------
function Get_Code(Self : Method_Type) return kv.avm.Instructions.Code_Access is
begin
return Self.Code;
end Get_Code;
end kv.avm.Methods;
|
with Ada.Text_IO; use Ada.Text_IO;
package body Route_Aggregator with SPARK_Mode is
pragma Unevaluated_Use_Of_Old (Allow);
pragma Assertion_Policy (Ignore);
-- Lemmas used to factor out reasonning about the redefined model of
-- Int64_Formal_Set_Maps
-------------------
-- Model_Include --
-------------------
procedure Model_Include
(M1, M2 : Int64_Formal_Set_Maps.Formal_Model.M.Map;
N1, N2 : Int_Set_Maps_M.Map)
-- Lemma: Inclusion of old models implies inclusion of redefined models
with Ghost,
Global => null,
Pre => Same_Mappings (M1, N1) and Same_Mappings (M2, N2) and M1 <= M2,
Post => N1 <= N2;
procedure Model_Include
(M1, M2 : Int64_Formal_Set_Maps.Formal_Model.M.Map;
N1, N2 : Int_Set_Maps_M.Map)
is
begin
null;
end Model_Include;
-----------------------------
-- Lift_From_Keys_To_Model --
-----------------------------
procedure Lift_From_Keys_To_Model (PendingRoute : Int64_Formal_Set_Map)
-- Lemma: Lift quantification done on Keys of the pending route map to its
-- model.
with Ghost,
Global => null,
Post =>
(for all Key of Model (PendingRoute) =>
(Find (Keys (PendingRoute), Key) > 0
and then Int_Set_Maps_K.Get (Keys (PendingRoute), Find (Keys (PendingRoute), Key)) =
Key));
procedure Lift_From_Keys_To_Model (PendingRoute : Int64_Formal_Set_Map)
is
begin
null;
end Lift_From_Keys_To_Model;
-- Subprograms wraping insertion and deletion in m_pendingRoute. They
-- restate part of the postcondition of the callee, but also reestablish
-- the predicate of Route_Aggregator_State and compute the effect of the
-- modification on Plan_To_Route.
-----------------------
-- Local subprograms --
-----------------------
procedure Check_All_Route_Plans_PendingAutoReq
(Mailbox : in out Route_Aggregator_Mailbox;
State : in out Route_Aggregator_State)
with
-- General invariants
Pre => All_Plans_Registered (State.m_routePlanResponses, State.m_routePlans)
and Only_Pending_Plans (State.m_routePlanResponses, State.m_routePlans)
and Valid_Plan_Responses (State.m_pendingRoute, State.m_pendingAutoReq, State.m_routePlanResponses)
and (for all K in 1 .. Length (State.m_pendingRoute) =>
Is_Pending (Model (State.m_pendingRoute), Model (State.m_routePlanResponses), Int_Set_Maps_K.Get (Keys (State.m_pendingRoute), K)))
-- History invariants
and Valid_Events (State.m_routeRequestId)
and No_RouteRequest_Lost (State.m_pendingRoute)
and No_PlanResponse_Lost (State.m_pendingRoute, State.m_routePlanResponses)
and All_Pending_Plans_Sent (State.m_pendingRoute, State.m_routePlanResponses),
-- General invariants
Post => All_Plans_Registered (State.m_routePlanResponses, State.m_routePlans)
and Only_Pending_Plans (State.m_routePlanResponses, State.m_routePlans)
and Valid_Plan_Responses (State.m_pendingRoute, State.m_pendingAutoReq, State.m_routePlanResponses)
and No_Finished_Request (State.m_pendingRoute, State.m_pendingAutoReq, State.m_routePlanResponses)
-- History invariants
and History'Old <= History
and Valid_Events (State.m_routeRequestId)
and No_RouteRequest_Lost (State.m_pendingRoute)
and No_PlanResponse_Lost (State.m_pendingRoute, State.m_routePlanResponses)
and All_Pending_Plans_Sent (State.m_pendingRoute, State.m_routePlanResponses);
procedure Check_All_Route_Plans_PendingRoute
(Mailbox : in out Route_Aggregator_Mailbox;
State : in out Route_Aggregator_State)
with
-- General invariants
Pre => All_Plans_Registered (State.m_routePlanResponses, State.m_routePlans)
and Only_Pending_Plans (State.m_routePlanResponses, State.m_routePlans)
and Valid_Plan_Responses (State.m_pendingRoute, State.m_pendingAutoReq, State.m_routePlanResponses)
-- History invariants
and Valid_Events (State.m_routeRequestId)
and No_RouteRequest_Lost (State.m_pendingRoute)
and No_PlanResponse_Lost (State.m_pendingRoute, State.m_routePlanResponses)
and All_Pending_Plans_Sent (State.m_pendingRoute, State.m_routePlanResponses),
-- General invariants
Post => All_Plans_Registered (State.m_routePlanResponses, State.m_routePlans)
and Only_Pending_Plans (State.m_routePlanResponses, State.m_routePlans)
and Valid_Plan_Responses (State.m_pendingRoute, State.m_pendingAutoReq, State.m_routePlanResponses)
and (for all K in 1 .. Length (State.m_pendingRoute) =>
Is_Pending (Model (State.m_pendingRoute), Model (State.m_routePlanResponses), Int_Set_Maps_K.Get (Keys (State.m_pendingRoute), K)))
-- History invariants
and History'Old <= History
and Valid_Events (State.m_routeRequestId)
and No_RouteRequest_Lost (State.m_pendingRoute)
and No_PlanResponse_Lost (State.m_pendingRoute, State.m_routePlanResponses)
and All_Pending_Plans_Sent (State.m_pendingRoute, State.m_routePlanResponses);
procedure Delete_PendingRequest
(m_pendingRequest : in out Int64_Formal_Set_Map;
otherPending : Int64_Formal_Set_Map;
m_routeRequestId : Int64;
Position : in out Int64_Formal_Set_Maps.Cursor)
with
Pre => Has_Element (m_pendingRequest, Position)
and All_Pending_Requests_Seen (Model (m_pendingRequest), m_routeRequestId)
and No_Overlaps (Model (m_pendingRequest))
and No_Overlaps (Model (m_pendingRequest), Model (otherPending)),
Post =>
-- Predicate of State
All_Pending_Requests_Seen (Model (m_pendingRequest), m_routeRequestId)
and No_Overlaps (Model (m_pendingRequest))
and No_Overlaps (Model (m_pendingRequest), Model (otherPending))
-- Postcondition copied from Int64_Formal_Set_Maps.Delete
and Length (m_pendingRequest) = Length (m_pendingRequest)'Old - 1
and not Int_Set_Maps_M.Has_Key (Model (m_pendingRequest), Key (m_pendingRequest, Position)'Old)
and not Int_Set_Maps_P.Has_Key (Positions (m_pendingRequest), Position'Old)
and Model (m_pendingRequest) <= Model (m_pendingRequest)'Old
and Int_Set_Maps_M.Keys_Included_Except
(Model (m_pendingRequest)'Old,
Model (m_pendingRequest),
Key (m_pendingRequest, Position)'Old)
and Int_Set_Maps_K.Range_Equal
(Left => Keys (m_pendingRequest)'Old,
Right => Keys (m_pendingRequest),
Fst => 1,
Lst => Int_Set_Maps_P.Get (Positions (m_pendingRequest)'Old, Position'Old) - 1)
and Int_Set_Maps_K.Range_Shifted
(Left => Keys (m_pendingRequest),
Right => Keys (m_pendingRequest)'Old,
Fst => Int_Set_Maps_P.Get (Positions (m_pendingRequest)'Old, Position'Old),
Lst => Length (m_pendingRequest),
Offset => 1)
and P_Positions_Shifted
(Positions (m_pendingRequest),
Positions (m_pendingRequest)'Old,
Cut => Int_Set_Maps_P.Get (Positions (m_pendingRequest)'Old, Position'Old))
-- Effect on Plan_To_Route
and Plan_To_Route (m_pendingRequest) <= Plan_To_Route (m_pendingRequest)'Old
and (for all I of Plan_To_Route (m_pendingRequest)'Old =>
Has_Key (Plan_To_Route (m_pendingRequest), I)
or else Get (Plan_To_Route (m_pendingRequest)'Old, I) = Key (m_pendingRequest, Position)'Old);
procedure Insert_PendingRequest
(m_pendingRequest : in out Int64_Formal_Set_Map;
otherPending : Int64_Formal_Set_Map;
m_routeRequestId : Int64;
RequestID : Int64;
PlanRequests : Int64_Formal_Set)
with Pre => not Int_Set_Maps_M.Has_Key (Model (m_pendingRequest), RequestID)
and Length (m_pendingRequest) < m_pendingRequest.Capacity
and
All_Pending_Requests_Seen (Model (m_pendingRequest), m_routeRequestId)
and
No_Overlaps (Model (m_pendingRequest))
and
No_Overlaps (Model (m_pendingRequest), Model (otherPending))
and
(for all Id of PlanRequests => Id <= m_routeRequestId)
and
(for all R_Id of Model (m_pendingRequest) =>
(for all E of Int_Set_Maps_M.Get (Model (m_pendingRequest), R_Id) => not Contains (PlanRequests, E)))
and
(for all R_Id of Model (otherPending) =>
(for all E of Int_Set_Maps_M.Get (Model (otherPending), R_Id) => not Contains (PlanRequests, E))),
Post =>
-- Predicate of State
All_Pending_Requests_Seen (Model (m_pendingRequest), m_routeRequestId)
and No_Overlaps (Model (m_pendingRequest))
and No_Overlaps (Model (m_pendingRequest), Model (otherPending))
-- Part of the postcondition copied from Int64_Formal_Set_Maps.Insert
and Model (m_pendingRequest)'Old <= Model (m_pendingRequest)
and Contains (Model (m_pendingRequest), RequestID)
and (for all E of Int_Set_Maps_M.Get (Model (m_pendingRequest), RequestID) =>
Contains (PlanRequests, E))
and (for all E of PlanRequests => Contains (Int_Set_Maps_M.Get (Model (m_pendingRequest), RequestID), E))
and (for all K of Model (m_pendingRequest) =>
Int_Set_Maps_M.Has_Key (Model (m_pendingRequest)'Old, K)
or K = RequestID)
-- Effect on Plan_To_Route
and Plan_To_Route (m_pendingRequest)'Old <= Plan_To_Route (m_pendingRequest)
and (for all I of PlanRequests =>
Has_Key (Plan_To_Route (m_pendingRequest), I)
and then Get (Plan_To_Route (m_pendingRequest), I) = RequestID)
and (for all I of Plan_To_Route (m_pendingRequest) =>
Contains (PlanRequests, I) or Has_Key (Plan_To_Route (m_pendingRequest)'Old, I));
---------------------------
-- Build_Matrix_Requests --
---------------------------
procedure Build_Matrix_Requests
(Mailbox : in out Route_Aggregator_Mailbox;
Data : Route_Aggregator_Configuration_Data;
State : in out Route_Aggregator_State;
ReqId : Int64)
with
SPARK_Mode => Off
is
sendAirPlanRequest : RPReq_Seq;
sendGroundPlanRequest : RPReq_Seq;
Empty_Formal_Set : Int64_Formal_Set;
begin
Insert (State.m_pendingAutoReq, ReqId, Empty_Formal_Set);
if Length (Element (State.m_uniqueAutomationRequests, ReqId).EntityList) = 0 then
declare
AReq : UniqueAutomationRequest :=
Element (State.m_uniqueAutomationRequests, ReqId);
begin
AReq.EntityList := Data.m_entityStates;
Replace (State.m_uniqueAutomationRequests, ReqId, AReq);
end;
end if;
declare
AReq : constant UniqueAutomationRequest :=
Element (State.m_uniqueAutomationRequests, ReqId);
begin
For_Each_Vehicle : for VehicleId of AReq.EntityList loop
Make_Request : declare
StartHeading_Deg : Real32 := 0.0;
StartLocation : Location3D;
FoundPlanningState : Boolean := False;
Vehicle : EntityState;
begin
for PlanningState of AReq.PlanningStates loop
if PlanningState.EntityID = VehicleId then
StartLocation := PlanningState.PlanningPosition;
StartHeading_Deg := PlanningState.PlanningHeading;
FoundPlanningState := True;
exit;
end if;
end loop;
if FoundPlanningState
or else (for some EntityId of Data.m_entityStates =>
(EntityId = VehicleId))
then
Build_Eligible_Task_Options : declare
TaskOptionList : TaskOption_Seq;
Found_Elig : Boolean := False;
PlanRequest : RoutePlanRequest;
Set : Int64_Formal_Set := Element (State.m_pendingAutoReq, ReqId);
begin
for TaskId of AReq.TaskList loop
if Contains (State.m_taskOptions, TaskId) then
for Option of Element (State.m_taskOptions, TaskId).Options loop
Found_Elig := False;
for V of Option.EligibleEntities loop
if V = VehicleId then
Found_Elig := True;
exit;
end if;
end loop;
if Length (Option.EligibleEntities) = 0
or else Found_Elig
then
TaskOptionList := Add (TaskOptionList, Option);
end if;
end loop;
end if;
end loop;
PlanRequest.AssociatedTaskID := 0;
PlanRequest.IsCostOnlyRequest := False;
PlanRequest.OperatingRegion := AReq.OperatingRegion;
PlanRequest.VehicleID := VehicleId;
State.m_routeRequestId := State.m_routeRequestId + 1;
PlanRequest.RequestID := State.m_routeRequestId;
Insert (Set, State.m_routeRequestId);
Replace (State.m_pendingAutoReq,
ReqId,
Set);
if not FoundPlanningState then
Vehicle := ES_Maps.Get (Data.m_entityStatesInfo, VehicleId);
StartLocation := Vehicle.Location;
StartHeading_Deg := Vehicle.Heading;
end if;
for Option of TaskOptionList loop
declare
TOP : constant TaskOptionPair :=
(VehicleId, 0, 0, Option.TaskID, Option.OptionID);
R : RouteConstraints;
begin
Insert (State.m_routeTaskPairing, State.m_routeId + 1, TOP);
R.StartLocation := StartLocation;
R.StartHeading := StartHeading_Deg;
R.EndLocation := Option.StartLocation;
R.EndHeading := Option.StartHeading;
R.RouteID := State.m_routeId + 1;
PlanRequest.RouteRequests :=
Add (PlanRequest.RouteRequests, R);
State.m_routeId := State.m_routeId + 1;
end;
end loop;
for T1 in TaskOptionList loop
for T2 in TaskOptionList loop
if T1 /= T2 then
declare
O1 : constant TaskOption :=
Get (TaskOptionList, T1);
O2 : constant TaskOption :=
Get (TaskOptionList, T2);
TOP : constant TaskOptionPair :=
(VehicleId,
O1.TaskID,
O1.OptionID,
O2.TaskID,
O2.OptionID);
R : RouteConstraints;
begin
Insert (State.m_routeTaskPairing, State.m_routeId + 1, TOP);
R.StartLocation := O1.EndLocation;
R.StartHeading := O1.EndHeading;
R.EndLocation := O2.StartLocation;
R.EndHeading := O2.StartHeading;
R.RouteID := State.m_routeId + 1;
PlanRequest.RouteRequests :=
Add (PlanRequest.RouteRequests, R);
State.m_routeId := State.m_routeId + 1;
end;
end if;
end loop;
end loop;
if Contains (Data.m_groundVehicles, VehicleId) then
sendGroundPlanRequest :=
Add (sendGroundPlanRequest, PlanRequest);
else
sendAirPlanRequest :=
Add (sendAirPlanRequest, PlanRequest);
end if;
end Build_Eligible_Task_Options;
end if;
end Make_Request;
end loop For_Each_Vehicle;
for RPReq of sendAirPlanRequest loop
sendLimitedCastMessage (Mailbox,
AircraftPathPlanner,
RPReq);
end loop;
for RPReq of sendGroundPlanRequest loop
if Data.m_fastPlan then
Euclidean_Plan (Data,
State.m_routePlanResponses,
State.m_routePlans,
RPReq);
else
sendLimitedCastMessage (Mailbox,
GroundPathPlanner,
RPReq);
end if;
end loop;
if Data.m_fastPlan then
Check_All_Route_Plans (Mailbox, State);
end if;
end;
end Build_Matrix_Requests;
---------------------------
-- Check_All_Route_Plans --
---------------------------
procedure Check_All_Route_Plans
(Mailbox : in out Route_Aggregator_Mailbox;
State : in out Route_Aggregator_State)
is
begin
Check_All_Route_Plans_PendingRoute (Mailbox, State);
Check_All_Route_Plans_PendingAutoReq (Mailbox, State);
end Check_All_Route_Plans;
------------------------------------------
-- Check_All_Route_Plans_PendingAutoReq --
------------------------------------------
procedure Check_All_Route_Plans_PendingAutoReq
(Mailbox : in out Route_Aggregator_Mailbox;
State : in out Route_Aggregator_State)
is
i : Int64_Formal_Set_Maps.Cursor := First (State.m_pendingAutoReq);
D : Count_Type := 0 with Ghost;
-- Number of removed elements
begin
-- Check pending automation requests
while Has_Element (State.m_pendingAutoReq, i) loop
pragma Loop_Invariant (Has_Element (State.m_pendingAutoReq, i));
pragma Loop_Invariant
(D = Length (State.m_pendingAutoReq)'Loop_Entry - Length (State.m_pendingAutoReq));
pragma Loop_Invariant
(Model (State.m_pendingAutoReq) <= Int_Set_Maps_M.Map'(Model (State.m_pendingAutoReq))'Loop_Entry);
pragma Loop_Invariant
(for all K in 1 .. Int_Set_Maps_P.Get (Positions (State.m_pendingAutoReq), i) - 1 =>
(for some L in 1 .. Int_Set_Maps_P.Get (Positions (State.m_pendingAutoReq), i) - 1 + D =>
Int_Set_Maps_K.Get (Keys (State.m_pendingAutoReq), K) = Int_Set_Maps_K.Get (Keys (State.m_pendingAutoReq)'Loop_Entry, L)));
pragma Loop_Invariant
(for all K in 1 .. Int_Set_Maps_P.Get (Positions (State.m_pendingAutoReq), i) - 1 =>
Is_Pending (Model (State.m_pendingAutoReq), Model (State.m_routePlanResponses), Int_Set_Maps_K.Get (Keys (State.m_pendingAutoReq), K)));
pragma Loop_Invariant
(for all K in Int_Set_Maps_P.Get (Positions (State.m_pendingAutoReq), i) .. Length (State.m_pendingAutoReq) =>
Int_Set_Maps_K.Get (Keys (State.m_pendingAutoReq), K) = Int_Set_Maps_K.Get (Keys (State.m_pendingAutoReq)'Loop_Entry, K + D));
-- General invariants
pragma Loop_Invariant
(All_Plans_Registered (State.m_routePlanResponses, State.m_routePlans));
pragma Loop_Invariant
(Only_Pending_Plans (State.m_routePlanResponses, State.m_routePlans));
pragma Loop_Invariant
(Valid_Plan_Responses (State.m_pendingRoute, State.m_pendingAutoReq, State.m_routePlanResponses));
pragma Loop_Invariant
(for all K in 1 .. Length (State.m_pendingRoute) =>
Is_Pending (Model (State.m_pendingRoute), Model (State.m_routePlanResponses), Int_Set_Maps_K.Get (Keys (State.m_pendingRoute), K)));
-- History invariants
pragma Loop_Invariant (History'Loop_Entry <= History);
pragma Loop_Invariant (Valid_Events (State.m_routeRequestId));
pragma Loop_Invariant (No_RouteRequest_Lost (State.m_pendingRoute));
pragma Loop_Invariant (No_PlanResponse_Lost (State.m_pendingRoute, State.m_routePlanResponses));
pragma Loop_Invariant (All_Pending_Plans_Sent (State.m_pendingRoute, State.m_routePlanResponses));
declare
isFulfilled : constant Boolean :=
(for all J of Element (State.m_pendingAutoReq, i) =>
Contains (State.m_routePlanResponses, J));
begin
if isFulfilled then
SendMatrix (Mailbox,
State.m_uniqueAutomationRequests,
State.m_pendingRoute,
State.m_pendingAutoReq,
State.m_routePlans,
State.m_routeTaskPairing,
State.m_routePlanResponses,
State.m_taskOptions,
Key (State.m_pendingAutoReq, i));
declare
Dummy : Int64_Formal_Set_Maps.Cursor := i;
UAR_Key : constant Int64 := Key (State.m_pendingAutoReq, i);
Pos : constant Count_Type := Int_Set_Maps_P.Get (Positions (State.m_pendingAutoReq), i) with Ghost;
begin
Next (State.m_pendingAutoReq, i);
Delete_PendingRequest (State.m_pendingAutoReq, State.m_pendingRoute, State.m_routeRequestId, Dummy);
Delete (State.m_uniqueAutomationRequests, UAR_Key);
D := D + 1;
pragma Assert
(for all K in 1 .. Pos - 1 =>
Is_Pending (Model (State.m_pendingAutoReq), Model (State.m_routePlanResponses), Int_Set_Maps_K.Get (Keys (State.m_pendingAutoReq), K)));
end;
else
Next (State.m_pendingAutoReq, i);
end if;
end;
end loop;
-- Restablish No_Finished_Request
pragma Assert
(for all K in 1 .. Length (State.m_pendingRoute) =>
Is_Pending (Model (State.m_pendingRoute), Model (State.m_routePlanResponses), Int_Set_Maps_K.Get (Keys (State.m_pendingRoute), K)));
Lift_From_Keys_To_Model (State.m_pendingRoute);
pragma Assert
(for all K in 1 .. Length (State.m_pendingAutoReq) =>
Is_Pending (Model (State.m_pendingAutoReq), Model (State.m_routePlanResponses), Int_Set_Maps_K.Get (Keys (State.m_pendingAutoReq), K)));
Lift_From_Keys_To_Model (State.m_pendingAutoReq);
end Check_All_Route_Plans_PendingAutoReq;
----------------------------------------
-- Check_All_Route_Plans_PendingRoute --
----------------------------------------
procedure Check_All_Route_Plans_PendingRoute
(Mailbox : in out Route_Aggregator_Mailbox;
State : in out Route_Aggregator_State)
is
i : Int64_Formal_Set_Maps.Cursor := First (State.m_pendingRoute);
D : Count_Type := 0 with Ghost;
-- Number of removed elements
begin
-- check pending route requests
while Has_Element (State.m_pendingRoute, i) loop
pragma Loop_Invariant (Has_Element (State.m_pendingRoute, i));
pragma Loop_Invariant
(D = Length (State.m_pendingRoute)'Loop_Entry - Length (State.m_pendingRoute));
pragma Loop_Invariant
(Model (State.m_pendingRoute) <= Int_Set_Maps_M.Map'(Model (State.m_pendingRoute))'Loop_Entry);
pragma Loop_Invariant
(for all K in 1 .. Int_Set_Maps_P.Get (Positions (State.m_pendingRoute), i) - 1 =>
(for some L in 1 .. Int_Set_Maps_P.Get (Positions (State.m_pendingRoute), i) - 1 + D =>
Int_Set_Maps_K.Get (Keys (State.m_pendingRoute), K) = Int_Set_Maps_K.Get (Keys (State.m_pendingRoute)'Loop_Entry, L)));
pragma Loop_Invariant
(for all K in 1 .. Int_Set_Maps_P.Get (Positions (State.m_pendingRoute), i) - 1 =>
Is_Pending (Model (State.m_pendingRoute), Model (State.m_routePlanResponses), Int_Set_Maps_K.Get (Keys (State.m_pendingRoute), K)));
pragma Loop_Invariant
(for all K in Int_Set_Maps_P.Get (Positions (State.m_pendingRoute), i) .. Length (State.m_pendingRoute) =>
Int_Set_Maps_K.Get (Keys (State.m_pendingRoute), K) = Int_Set_Maps_K.Get (Keys (State.m_pendingRoute)'Loop_Entry, K + D));
-- General invariants
pragma Loop_Invariant
(All_Plans_Registered (State.m_routePlanResponses, State.m_routePlans));
pragma Loop_Invariant
(Only_Pending_Plans (State.m_routePlanResponses, State.m_routePlans));
pragma Loop_Invariant
(Valid_Plan_Responses (State.m_pendingRoute, State.m_pendingAutoReq, State.m_routePlanResponses));
-- History invariants
pragma Loop_Invariant (History'Loop_Entry <= History);
pragma Loop_Invariant (Valid_Events (State.m_routeRequestId));
pragma Loop_Invariant (No_RouteRequest_Lost (State.m_pendingRoute));
pragma Loop_Invariant (No_PlanResponse_Lost (State.m_pendingRoute, State.m_routePlanResponses));
pragma Loop_Invariant (All_Pending_Plans_Sent (State.m_pendingRoute, State.m_routePlanResponses));
declare
isFulfilled : constant Boolean :=
(for all J of Element (State.m_pendingRoute, i) =>
Contains (State.m_routePlanResponses, J));
begin
if isFulfilled then
SendRouteResponse (Mailbox, State.m_pendingRoute, State.m_pendingAutoReq, State.m_routePlanResponses, State.m_routePlans, Key (State.m_pendingRoute, i));
declare
Dummy : Int64_Formal_Set_Maps.Cursor := i;
Pos : constant Count_Type := Int_Set_Maps_P.Get (Positions (State.m_pendingRoute), i) with Ghost;
begin
Next (State.m_pendingRoute, i);
Delete_PendingRequest (State.m_pendingRoute, State.m_pendingAutoReq, State.m_routeRequestId, Dummy);
D := D + 1;
pragma Assert
(for all K in 1 .. Pos - 1 =>
Is_Pending (Model (State.m_pendingRoute), Model (State.m_routePlanResponses), Int_Set_Maps_K.Get (Keys (State.m_pendingRoute), K)));
end;
pragma Assert (All_Pending_Plans_Sent (State.m_pendingRoute, State.m_routePlanResponses));
else
Next (State.m_pendingRoute, i);
end if;
end;
end loop;
pragma Assert
(for all K in 1 .. Length (State.m_pendingRoute) =>
Is_Pending (Model (State.m_pendingRoute), Model (State.m_routePlanResponses), Int_Set_Maps_K.Get (Keys (State.m_pendingRoute), K)));
end Check_All_Route_Plans_PendingRoute;
-------------------------------------
-- Check_All_Task_Options_Received --
-------------------------------------
procedure Check_All_Task_Options_Received
(Mailbox : in out Route_Aggregator_Mailbox;
Data : Route_Aggregator_Configuration_Data;
State : in out Route_Aggregator_State)
with
SPARK_Mode => Off
is
C : UAR_Maps.Cursor :=
First (State.m_uniqueAutomationRequests);
begin
while Has_Element (State.m_uniqueAutomationRequests, C) loop
declare
Areq : constant UniqueAutomationRequest :=
Element (State.m_uniqueAutomationRequests, C);
AllReceived : constant Boolean :=
(for all TaskId of Areq.TaskList =>
Contains (State.m_taskOptions, TaskId));
begin
if AllReceived then
Build_Matrix_Requests
(Mailbox,
Data,
State,
Key (State.m_uniqueAutomationRequests, C));
end if;
end;
Next (State.m_uniqueAutomationRequests, C);
end loop;
end Check_All_Task_Options_Received;
---------------------------
-- Delete_PendingRequest --
---------------------------
procedure Delete_PendingRequest
(m_pendingRequest : in out Int64_Formal_Set_Map;
otherPending : Int64_Formal_Set_Map;
m_routeRequestId : Int64;
Position : in out Int64_Formal_Set_Maps.Cursor)
is
pragma Unreferenced (otherPending, m_routeRequestId);
Old_pendingRoute_M : constant Int64_Formal_Set_Maps.Formal_Model.M.Map :=
Int64_Formal_Set_Maps.Formal_Model.Model (m_pendingRequest) with Ghost;
Old_pendingRoute : constant Int_Set_Maps_M.Map := Model (m_pendingRequest) with Ghost;
begin
Delete (m_pendingRequest, Position);
-- Establish the effect on the redefined Model of maps of formal sets
Model_Include
(Int64_Formal_Set_Maps.Formal_Model.Model (m_pendingRequest), Old_pendingRoute_M,
Model (m_pendingRequest), Old_pendingRoute);
end Delete_PendingRequest;
--------------------
-- Euclidean_Plan --
--------------------
procedure Euclidean_Plan
(Data : Route_Aggregator_Configuration_Data;
routePlanResponses : in out Int64_RouteResponse_Map;
routePlans : in out Int64_IdPlanPair_Map;
Request : RoutePlanRequest)
is
pragma Unreferenced (Data, routePlans, routePlanResponses, Request);
-- -- UxAS::common::utilities::CUnitConversions flatEarth;
-- FlatEarth : Conversions.Unit_Converter;
-- -- int64_t regionId = request->getOperatingRegion();
-- RegionId : Int64 := Request.OperatingRegion;
-- -- int64_t vehicleId = request->getVehicleID();
-- VehicleId : Int64 := Request.VehicleID;
-- -- int64_t taskId = request->getAssociatedTaskID();
-- TaskId : Int64 := Request.AssociatedTaskID;
-- -- double speed = 1.0; // default if no speed available
-- Speed : Real64 := 1.0;
begin
raise Program_Error with "Euclidean_Plan is unimplemented";
-- if (m_entityConfigurations.find(vehicleId) != m_entityConfigurations.end())
-- {
-- double speed = m_entityConfigurations[vehicleId]->getNominalSpeed();
-- if (speed < 1e-2)
-- {
-- speed = 1.0; // default to 1 if too small for division
-- }
-- }
-- auto response = std::shared_ptr<UxAS::messages::route::RoutePlanResponse>(new UxAS::messages::route::RoutePlanResponse);
-- response->setAssociatedTaskID(taskId);
-- response->setOperatingRegion(regionId);
-- response->setVehicleID(vehicleId);
-- response->setResponseID(request->getRequestID());
--
-- for (size_t k = 0; k < request->getRouteRequests().size(); k++)
-- {
-- UxAS::messages::route::RouteConstraints* routeRequest = request->getRouteRequests().at(k);
-- int64_t routeId = routeRequest->getRouteID();
-- VisiLibity::Point startPt, endPt;
-- double north, east;
--
-- UxAS::messages::route::RoutePlan* plan = new UxAS::messages::route::RoutePlan;
-- plan->setRouteID(routeId);
--
-- flatEarth.ConvertLatLong_degToNorthEast_m(routeRequest->getStartLocation()->getLatitude(), routeRequest->getStartLocation()->getLongitude(), north, east);
-- startPt.set_x(east);
-- startPt.set_y(north);
--
-- flatEarth.ConvertLatLong_degToNorthEast_m(routeRequest->getEndLocation()->getLatitude(), routeRequest->getEndLocation()->getLongitude(), north, east);
-- endPt.set_x(east);
-- endPt.set_y(north);
--
-- double linedist = VisiLibity::distance(startPt, endPt);
-- plan->setRouteCost(linedist / speed * 1000); // milliseconds to arrive
-- m_routePlans[routeId] = std::make_pair(request->getRequestID(), std::shared_ptr<UxAS::messages::route::RoutePlan>(plan));
-- }
-- m_routePlanResponses[response->getResponseID()] = response;
end Euclidean_Plan;
--------------------------------
-- Handle_Route_Plan_Response --
--------------------------------
procedure Handle_Route_Plan_Response
(Mailbox : in out Route_Aggregator_Mailbox;
State : in out Route_Aggregator_State;
Response : RoutePlanResponse)
is
begin
pragma Assume (Length (History) < Count_Type'Last, "We still have room for a new event in History");
History := Add (History, (Kind => Receive_PlanResponse, Id => Response.ResponseID));
pragma Assert (No_RouteRequest_Lost (State.m_pendingRoute));
pragma Assume (Length (State.m_routePlanResponses) < State.m_routePlanResponses.Capacity, "We have some room for a new plan response");
Insert (State.m_routePlanResponses, Response.ResponseID, Response);
pragma Assert (Valid_Plan_Responses (State.m_pendingRoute, State.m_pendingAutoReq, State.m_routePlanResponses));
pragma Assert
(Only_Pending_Plans (State.m_routePlanResponses, State.m_routePlans));
for p in 1 .. Last (Response.RouteResponses) loop
-- All plans are registered up to p
pragma Loop_Invariant
(for all RP of Model (State.m_routePlanResponses) =>
(if RP /= Response.ResponseID then
(for all Pl of Element (State.m_routePlanResponses, RP).RouteResponses =>
Contains (State.m_routePlans, Pl.RouteID)
and then Element (State.m_routePlans, Pl.RouteID).Id = RP)));
pragma Loop_Invariant
(for all K in 1 .. p - 1 =>
Contains (State.m_routePlans, Get (Response.RouteResponses, K).RouteID)
and then Element (State.m_routePlans, Get (Response.RouteResponses, K).RouteID).Id = Response.ResponseID);
pragma Loop_Invariant
(for all K in p .. Last (Response.RouteResponses) =>
not Contains (State.m_routePlans, Get (Response.RouteResponses, K).RouteID));
-- Invariants
pragma Loop_Invariant
(Only_Pending_Plans (State.m_routePlanResponses, State.m_routePlans));
pragma Assume (Length (State.m_routePlans) < State.m_routePlans.Capacity, "We have enough room for all route plans");
declare
ID : constant Int64 := Get (Response.RouteResponses, p).RouteID;
Plan : constant RoutePlan := Get (Response.RouteResponses, p);
begin
Insert (State.m_routePlans, ID,
IdPlanPair'(Id => Response.ResponseID,
Plan => Plan,
Cost => Get (Response.RouteResponses, p).RouteCost));
end;
pragma Assert (Contains (Element (State.m_routePlanResponses, Response.ResponseID).RouteResponses, Get (Response.RouteResponses, p).RouteID));
end loop;
pragma Assert (No_RouteRequest_Lost (State.m_pendingRoute));
pragma Assert (for all Pl of Element (State.m_routePlanResponses, Response.ResponseID).RouteResponses =>
Contains (State.m_routePlans, Pl.RouteID)
and then Element (State.m_routePlans, Pl.RouteID).Id = Response.ResponseID);
pragma Assert (for all RP of Model (State.m_routePlanResponses) =>
(for all Pl of Element (State.m_routePlanResponses, RP).RouteResponses =>
Contains (State.m_routePlans, Pl.RouteID)
and then Element (State.m_routePlans, Pl.RouteID).Id = RP));
Check_All_Route_Plans (Mailbox, State);
end Handle_Route_Plan_Response;
--------------------------
-- Handle_Route_Request --
--------------------------
procedure Handle_Route_Request
(Data : Route_Aggregator_Configuration_Data;
Mailbox : in out Route_Aggregator_Mailbox;
State : in out Route_Aggregator_State;
Request : RouteRequest)
is
use all type History_Type;
Vehicle_Ids : Int64_Seq := Request.VehicleID;
PlanRequests : Int64_Formal_Set;
begin
pragma Assert (No_PlanResponse_Lost (State.m_pendingRoute, State.m_routePlanResponses));
pragma Assume (Length (History) < Count_Type'Last, "We still have room for a new event in History");
History := Add (History, (Kind => Receive_RouteRequest, Id => Request.RequestID));
pragma Assert
(for all Pos in Event_Sequences.First .. Last (History) - 1 =>
(if Get (History, Pos).Kind = Receive_PlanResponse
and Has_Key (Plan_To_Route (State.m_pendingRoute), Get (History, Pos).Id)
then Contains (State.m_routePlanResponses, Get (History, Pos).Id)));
pragma Assert (No_PlanResponse_Lost (State.m_pendingRoute, State.m_routePlanResponses));
---------------------------------------------------------------------------------------------------------------
-- this doesn't match the C++ exactly, because it doesn't put the new vehicle
-- ids into the message parameter (which is "by reference" via pointer in C++)
-- but that seems to be OK because only EuclidianPlan would use it, apparently
if Length (Vehicle_Ids) = 0 then
Vehicle_Ids := Data.m_entityStates;
end if;
---------------------------------------------------------------------------------------------------------------
-- We only have route plan responses with Ids smaller than State.m_routeRequestId
pragma Assert
(for all K of Model (State.m_routePlanResponses) =>
K <= State.m_routeRequestId);
pragma Assert
(for all E of History =>
(if E.Kind = Receive_PlanResponse then
E.Id <= State.m_routeRequestId));
for K in 1 .. Last (Vehicle_Ids) loop
-- We are only adding to planrequests new request ids
pragma Loop_Invariant
(State.m_routeRequestId'Loop_Entry <= State.m_routeRequestId);
pragma Loop_Invariant
(for all Id of Model (PlanRequests) => Id > State.m_routeRequestId'Loop_Entry
and Id <= State.m_routeRequestId);
pragma Loop_Invariant
(for all Id of Model (State.m_pendingRoute) =>
(for all K of Int_Set_Maps_M.Get (Model (State.m_pendingRoute), Id) =>
K <= State.m_routeRequestId'Loop_Entry));
pragma Loop_Invariant (Length (PlanRequests) <= Count_Type (K - 1));
-- If fast planning is used, we may already have some responses for the
-- new plan requests.
pragma Loop_Invariant
(for all K of Model (State.m_routePlanResponses) =>
Contains (Model (State.m_routePlanResponses)'Loop_Entry, K)
or else (Data.m_fastPlan and then Contains (PlanRequests, K)));
-- General Invariants
pragma Loop_Invariant
(All_Plans_Registered (State.m_routePlanResponses, State.m_routePlans));
pragma Loop_Invariant
(Only_Pending_Plans (State.m_routePlanResponses, State.m_routePlans));
pragma Loop_Invariant
(No_Finished_Request (State.m_pendingRoute, State.m_pendingAutoReq, State.m_routePlanResponses));
-- Update of the history, it may contain new plan requests
pragma Loop_Invariant (History'Loop_Entry <= History);
pragma Loop_Invariant
(for all I in 1 .. Last (History) =>
(if I > Last (History)'Loop_Entry then
Get (History, I).Kind = Send_PlanRequest));
-- History Invariants
pragma Loop_Invariant (Valid_Events (State.m_routeRequestId));
pragma Loop_Invariant
(No_PlanResponse_Lost (State.m_pendingRoute, State.m_routePlanResponses));
pragma Loop_Invariant
(All_Pending_Plans_Sent (State.m_pendingRoute, State.m_routePlanResponses));
pragma Loop_Invariant
(for all Id of Model (PlanRequests) =>
PlanRequest_Processed (State.m_routePlanResponses, Id));
declare
Vehicle_Id : Int64 renames Get (Vehicle_Ids, K);
-- create a new route plan request
pragma Assume (State.m_routeRequestId < Int64'Last, "The request ID does not overflow");
planRequest : constant RoutePlanRequest :=
(AssociatedTaskID => Request.AssociatedTaskID,
IsCostOnlyRequest => Request.IsCostOnlyRequest,
OperatingRegion => Request.OperatingRegion,
VehicleID => Vehicle_Id,
RequestID => State.m_routeRequestId + 1,
RouteRequests => Request.RouteRequests);
begin
State.m_routeRequestId := State.m_routeRequestId + 1;
pragma Assume (Length (PlanRequests) < PlanRequests.Capacity, "We have enough room for all vehicles in planRequests");
Insert (PlanRequests, planRequest.RequestID);
if Contains (Data.m_groundVehicles, Vehicle_Id) then
if Data.m_fastPlan then
-- short-circuit and just plan with straight line planner
Euclidean_Plan (Data,
State.m_routePlanResponses,
State.m_routePlans,
planRequest);
else
-- send externally
sendLimitedCastMessage
(Mailbox, GroundPathPlanner, planRequest);
pragma Assume (Length (History) < Count_Type'Last, "We still have room for a new event in History");
History := Add (History, (Kind => Send_PlanRequest, Id => planRequest.RequestID));
pragma Assert (PlanRequest_Sent (planRequest.RequestID));
end if;
else
pragma Assert
(Contains (Data.m_airVehicles, Vehicle_Id)
or else Contains (Data.m_surfaceVehicles, Vehicle_Id));
-- send to aircraft planner
sendLimitedCastMessage
(Mailbox, AircraftPathPlanner, planRequest);
pragma Assume (Length (History) < Count_Type'Last, "We still have room for a new event in History");
History := Add (History, (Kind => Send_PlanRequest, Id => planRequest.RequestID));
pragma Assert (PlanRequest_Sent (planRequest.RequestID));
end if;
end;
pragma Assert
(for all Id of Model (PlanRequests) =>
PlanRequest_Processed (State.m_routePlanResponses, Id));
pragma Assert (All_Pending_Plans_Sent (State.m_pendingRoute, State.m_routePlanResponses));
end loop;
-- Restate part of the loop invariants after the loop
pragma Assert
(for all E of History =>
(if E.Kind = Receive_PlanResponse then not Contains (PlanRequests, E.Id)));
pragma Assert (All_Pending_Plans_Sent (State.m_pendingRoute, State.m_routePlanResponses));
pragma Assert
(No_Finished_Request (State.m_pendingRoute, State.m_pendingAutoReq, State.m_routePlanResponses));
pragma Assert
(for all R_Id of Model (State.m_pendingRoute) =>
(for all E of Int_Set_Maps_M.Get (Model (State.m_pendingRoute), R_Id) =>
not Contains (PlanRequests, E)));
pragma Assume (Length (State.m_pendingRoute) < State.m_pendingRoute.Capacity, "We have enough room for a new pending route request");
Insert_PendingRequest
(State.m_pendingRoute, State.m_pendingAutoReq, State.m_routeRequestId, Request.RequestID, PlanRequests);
-- System invariants have been reestablished
pragma Assert (All_Pending_Plans_Sent (State.m_pendingRoute, State.m_routePlanResponses));
pragma Assert (Valid_Plan_Responses (State.m_pendingRoute, State.m_pendingAutoReq, State.m_routePlanResponses));
pragma Assert
(No_PlanResponse_Lost (State.m_pendingRoute, State.m_routePlanResponses));
-- if fast planning, then all routes should be complete; kick off response
if Data.m_fastPlan then
Check_All_Route_Plans (Mailbox, State);
else
pragma Assert (Is_Pending (Model (State.m_pendingRoute), Model (State.m_routePlanResponses), Request.RequestID));
pragma Assert (No_Finished_Request (State.m_pendingRoute, State.m_pendingAutoReq, State.m_routePlanResponses));
end if;
end Handle_Route_Request;
------------------------------
-- Handle_Task_Plan_Options --
------------------------------
procedure Handle_Task_Plan_Options
(Mailbox : in out Route_Aggregator_Mailbox;
Data : Route_Aggregator_Configuration_Data;
State : in out Route_Aggregator_State;
Options : TaskPlanOptions)
with
SPARK_Mode => Off
is
Id : constant Int64 := Options.TaskID;
begin
Insert (State.m_taskOptions, Id, Options);
Check_All_Task_Options_Received (Mailbox, Data, State);
end Handle_Task_Plan_Options;
--------------------------------------
-- Handle_Unique_Automation_Request --
--------------------------------------
procedure Handle_Unique_Automation_Request
(Data : Route_Aggregator_Configuration_Data;
Mailbox : in out Route_Aggregator_Mailbox;
State : in out Route_Aggregator_State;
Areq : UniqueAutomationRequest)
is
begin
Insert (State.m_uniqueAutomationRequests,
State.m_autoRequestId + 1,
Areq);
State.m_autoRequestId := State.m_autoRequestId + 1;
Check_All_Task_Options_Received (Mailbox, Data, State);
end Handle_Unique_Automation_Request;
---------------------------
-- Insert_PendingRequest --
---------------------------
procedure Insert_PendingRequest
(m_pendingRequest : in out Int64_Formal_Set_Map;
otherPending : Int64_Formal_Set_Map;
m_routeRequestId : Int64;
RequestID : Int64;
PlanRequests : Int64_Formal_Set)
is
pragma Unreferenced (otherPending);
Old_pendingRequest : constant Int_Set_Maps_M.Map := Model (m_pendingRequest) with Ghost;
Old_pendingRequest_M : constant Int64_Formal_Set_Maps.Formal_Model.M.Map :=
Int64_Formal_Set_Maps.Formal_Model.Model (m_pendingRequest) with Ghost;
begin
Insert (m_pendingRequest, RequestID, PlanRequests);
-- Establish the effect on the redefined Model of maps of formal sets
Model_Include
(Old_pendingRequest_M, Int64_Formal_Set_Maps.Formal_Model.Model (m_pendingRequest),
Old_pendingRequest, Model (m_pendingRequest));
pragma Assert (No_Overlaps (Model (m_pendingRequest)));
pragma Assert (All_Pending_Requests_Seen (Model (m_pendingRequest), m_routeRequestId));
end Insert_PendingRequest;
-- Model functions used in contracts
-----------
-- Model --
-----------
function Model (M : Int64_Formal_Set_Map) return Int_Set_Maps_M.Map is
function Model (S : Int64_Formal_Set) return Int64_Set with
Post =>
(for all E of Model'Result => Contains (S, E))
and
(for all E of S => Contains (Model'Result, E));
function Model (S : Int64_Formal_Set) return Int64_Set is
Res : Int64_Set;
begin
for C in S loop
pragma Loop_Variant (Increases => Int_Set_P.Get (Positions (S), C));
pragma Loop_Invariant (Length (Res) = Int_Set_P.Get (Positions (S), C) - 1);
pragma Loop_Invariant (for all E of Res => Contains (S, E));
pragma Loop_Invariant
(for all K in 1 .. Int_Set_P.Get (Positions (S), C) - 1 =>
Contains (Res, Int_Set_E.Get (Elements (S), K)));
pragma Loop_Invariant
(for all K in Int_Set_P.Get (Positions (S), C) .. Length (S) =>
not Contains (Res, Int_Set_E.Get (Elements (S), K)));
Res := Add (Res, Element (S, C));
end loop;
return Res;
end Model;
Res : Int_Set_Maps_M.Map;
begin
for C in M loop
pragma Loop_Variant (Increases => Int_Set_Maps_P.Get (Positions (M), C));
pragma Loop_Invariant (Int_Set_Maps_M.Length (Res) = Int_Set_Maps_P.Get (Positions (M), C) - 1);
pragma Loop_Invariant (for all I of Res => Contains (M, I));
pragma Loop_Invariant
(for all I of Res =>
(for all E of Int_Set_Maps_M.Get (Res, I) =>
Contains (Element (M, I), E)));
pragma Loop_Invariant
(for all I of Res =>
(for all E of Element (M, I) =>
Contains (Int_Set_Maps_M.Get (Res, I), E)));
pragma Loop_Invariant
(for all K in 1 .. Int_Set_Maps_P.Get (Positions (M), C) - 1 =>
Int_Set_Maps_M.Has_Key (Res, Int_Set_Maps_K.Get (Keys (M), K)));
pragma Loop_Invariant
(for all K in Int_Set_Maps_P.Get (Positions (M), C) .. Length (M) =>
not Int_Set_Maps_M.Has_Key (Res, Int_Set_Maps_K.Get (Keys (M), K)));
Res := Int_Set_Maps_M.Add (Res, Key (M, C), Model (Element (M, C)));
end loop;
return Res;
end Model;
----------------
-- SendMatrix --
----------------
procedure SendMatrix
(Mailbox : in out Route_Aggregator_Mailbox;
m_uniqueAutomationRequests : Int64_UniqueAutomationRequest_Map;
m_pendingRoute : Int64_Formal_Set_Map;
m_pendingAutoReq : Int64_Formal_Set_Map;
m_routePlans : in out Int64_IdPlanPair_Map;
m_routeTaskPairing : in out Int64_TaskOptionPair_Map;
m_routePlanResponses : in out Int64_RouteResponse_Map;
m_taskOptions : in out Int64_TaskPlanOptions_Map;
autoKey : Int64)
is
areq : constant UniqueAutomationRequest :=
Element (m_uniqueAutomationRequests, autoKey);
matrix : AssignmentCostMatrix;
pendingRequests : Int64_Formal_Set renames Element (m_pendingAutoReq, autoKey);
Old_routePlanResponses : constant Int64_RouteResponse_Map := m_routePlanResponses with Ghost;
begin
matrix.CorrespondingAutomationRequestID := areq.RequestID;
matrix.OperatingRegion := areq.OperatingRegion;
matrix.TaskList := areq.TaskList;
for Cu in pendingRequests loop
pragma Loop_Invariant
(for all I in 1 .. Int_Set_P.Get (Positions (pendingRequests), Cu) - 1 =>
not Contains (m_routePlanResponses, Int_Set_E.Get (Elements (pendingRequests), I)));
pragma Loop_Invariant
(for all I in Int_Set_P.Get (Positions (pendingRequests), Cu) .. Length (pendingRequests) =>
Contains (m_routePlanResponses, Int_Set_E.Get (Elements (pendingRequests), I)));
pragma Loop_Invariant
(for all Id of Old_routePlanResponses =>
(if not Contains (pendingRequests, Id) then
Contains (m_routePlanResponses, Id)));
pragma Loop_Invariant
(for all Id of Model (m_routePlanResponses) =>
Contains (Old_routePlanResponses, Id));
-- Invariants
pragma Loop_Invariant
(Valid_Plan_Responses (m_pendingRoute, m_pendingAutoReq, m_routePlanResponses));
pragma Loop_Invariant
(All_Plans_Registered (m_routePlanResponses, m_routePlans));
pragma Loop_Invariant
(Only_Pending_Plans (m_routePlanResponses, m_routePlans));
-- History invariants
pragma Loop_Invariant (No_RouteRequest_Lost (m_pendingRoute));
pragma Loop_Invariant (No_PlanResponse_Lost (m_pendingRoute, m_routePlanResponses));
pragma Loop_Invariant (All_Pending_Plans_Sent (m_pendingRoute, m_routePlanResponses));
declare
rId : constant Int64 := Element (pendingRequests, Cu);
pragma Assert (Contains (m_routePlanResponses, rId));
begin
declare
plan : Int64_RouteResponse_Maps.Cursor := Find (m_routePlanResponses, rId);
-- NB. The if statement checking whether rId is in
-- routePlanResponses was removed as SendRouteResponse is only
-- called when all plan responses have been received.
pragma Assert (Has_Element (m_routePlanResponses, plan));
resps : RP_Seq renames Element (m_routePlanResponses, plan).RouteResponses;
begin
-- delete all individual routes from storage
for i in 1 .. Last (resps) loop
-- We have removed all elements of resps from routePlans
-- up to i.
pragma Loop_Invariant
(for all RP of Model (m_routePlanResponses) =>
(if RP /= rId then
(for all Pl of Element (m_routePlanResponses, RP).RouteResponses =>
Contains (m_routePlans, Pl.RouteID)
and then Element (m_routePlans, Pl.RouteID).Id = RP)));
pragma Loop_Invariant
(Only_Pending_Plans (m_routePlanResponses, m_routePlans));
pragma Loop_Invariant
(for all Pl of Model (m_routePlans) =>
(if Element (m_routePlans, Pl).Id = rId then
(for some K in i .. Last (resps) =>
Get (resps, K).RouteID = Pl)));
pragma Loop_Invariant
(for all K in i .. Last (resps) =>
Contains (m_routePlans, Get (resps, K).RouteID)
and then Element (m_routePlans, Get (resps, K).RouteID).Id = rId);
if Contains (m_routeTaskPairing, Get (resps, i).RouteID) then
declare
routeplan : constant IdPlanPair :=
Element (m_routePlans, Get (resps, i).RouteID);
taskpair : constant TaskOptionPair :=
Element (m_routeTaskPairing, Get (resps, i).RouteID);
toc : TaskOptionCost;
begin
if routeplan.Cost < 0 then
Put_Line ("Route not found: V[" &
taskpair.vehicleId'Image & "](" &
taskpair.prevTaskId'Image & "," &
taskpair.prevTaskOption'Image & ")-(" &
taskpair.taskId'Image & "," &
taskpair.taskOption'Image & ")");
end if;
toc.DestinationTaskID := taskpair.taskId;
toc.DestinationTaskOption := taskpair.taskOption;
toc.InitialTaskID := taskpair.prevTaskId;
toc.InitialTaskOption := taskpair.prevTaskOption;
toc.TimeToGo := routeplan.Cost;
toc.VehicleID := taskpair.vehicleId;
pragma Assume (Length (matrix.CostMatrix) < Count_Type'Last, "we still have room in the matrix");
matrix.CostMatrix := Add (matrix.CostMatrix, toc);
end;
Delete (m_routeTaskPairing, Get (resps, i).RouteID);
end if;
-- We only delete plans associated to rId
pragma Assert (Element (m_routePlans, Get (resps, i).RouteID).Id = rId);
Delete (m_routePlans, Get (resps, i).RouteID);
end loop;
pragma Assert
(for all Pl of Model (m_routePlans) => Element (m_routePlans, Pl).Id /= rId);
pragma Assert (All_Pending_Plans_Sent (m_pendingRoute, m_routePlanResponses));
pragma Assert (No_Overlaps (Model (m_pendingRoute), Model (m_pendingAutoReq)));
pragma Assert (for all Id of Plan_To_Route (m_pendingRoute) => Id /= Key (m_routePlanResponses, plan));
Delete (m_routePlanResponses, plan);
pragma Assert (All_Pending_Plans_Sent (m_pendingRoute, m_routePlanResponses));
pragma Assert
(Only_Pending_Plans (m_routePlanResponses, m_routePlans));
end;
end;
end loop;
sendBroadcastMessage (Mailbox, matrix);
Clear (m_taskOptions);
end SendMatrix;
-----------------------
-- SendRouteResponse --
-----------------------
procedure SendRouteResponse
(Mailbox : in out Route_Aggregator_Mailbox;
pendingRoute : Int64_Formal_Set_Map;
pendingAutoReq : Int64_Formal_Set_Map;
routePlanResponses : in out Int64_RouteResponse_Map;
routePlans : in out Int64_IdPlanPair_Map;
routeKey : Int64)
is
Response : RouteResponse;
PlanResponses : Int64_Formal_Set renames Element (pendingRoute, routeKey);
Old_routePlanResponses : constant RR_Maps_M.Map := Model (routePlanResponses) with Ghost;
begin
Response.ResponseID := routeKey;
for Cu in PlanResponses loop
-- Number of elements added to response.Routes
pragma Loop_Invariant (Length (Response.Routes) < Int_Set_P.Get (Positions (PlanResponses), Cu));
-- We have removed all elements of PlanResponses from routePlanResponses
-- up to Cu.
pragma Loop_Invariant
(for all I in 1 .. Int_Set_P.Get (Positions (PlanResponses), Cu) - 1 =>
not Contains (routePlanResponses, Int_Set_E.Get (Elements (PlanResponses), I)));
pragma Loop_Invariant
(for all I in Int_Set_P.Get (Positions (PlanResponses), Cu) .. Length (PlanResponses) =>
Contains (routePlanResponses, Int_Set_E.Get (Elements (PlanResponses), I)));
pragma Loop_Invariant
(for all Id of Old_routePlanResponses =>
(if not Contains (PlanResponses, Id) then
Contains (routePlanResponses, Id)));
pragma Loop_Invariant
(for all Id of Model (routePlanResponses) =>
Contains (Old_routePlanResponses, Id));
-- Invariants
pragma Loop_Invariant
(Valid_Plan_Responses (pendingRoute, pendingAutoReq, routePlanResponses));
pragma Loop_Invariant
(All_Plans_Registered (routePlanResponses, routePlans));
pragma Loop_Invariant
(Only_Pending_Plans (routePlanResponses, routePlans));
-- History invariants:
-- We have only removed responses associated to routeKey
pragma Loop_Invariant
(for all Id of Plan_To_Route (pendingRoute) =>
(if Get (Plan_To_Route (pendingRoute), Id) /= routeKey then
Contains (routePlanResponses, Id)
or else PlanRequest_Sent (Id)));
pragma Loop_Invariant
(for all E of History =>
(if E.Kind = Receive_PlanResponse
and then Has_Key (Plan_To_Route (pendingRoute), E.Id)
and then Get (Plan_To_Route (pendingRoute), E.Id) /= routeKey
then Contains (routePlanResponses, E.Id)));
declare
rId : Int64 renames Element (PlanResponses, Cu);
begin
declare
plan : Int64_RouteResponse_Maps.Cursor := Find (routePlanResponses, rId);
-- NB. The if statement checking whether rId is in
-- routePlanResponses was removed as SendRouteResponse is only
-- called when all plan responses have been received.
pragma Assert (Has_Element (routePlanResponses, plan));
resps : RP_Seq renames Element (routePlanResponses, plan).RouteResponses;
begin
Response.Routes := Add (Response.Routes, Element (routePlanResponses, plan));
-- delete all individual routes from storage
for i in 1 .. Last (resps) loop
-- We have removed all elements of resps from routePlans
-- up to i.
pragma Loop_Invariant
(for all RP of Model (routePlanResponses) =>
(if RP /= rId then
(for all Pl of Element (routePlanResponses, RP).RouteResponses =>
Contains (routePlans, Pl.RouteID)
and then Element (routePlans, Pl.RouteID).Id = RP)));
pragma Loop_Invariant
(Only_Pending_Plans (routePlanResponses, routePlans));
pragma Loop_Invariant
(for all Pl of Model (routePlans) =>
(if Element (routePlans, Pl).Id = rId then
(for some K in i .. Last (resps) =>
Get (resps, K).RouteID = Pl)));
pragma Loop_Invariant
(for all K in i .. Last (resps) =>
Contains (routePlans, Get (resps, K).RouteID)
and then Element (routePlans, Get (resps, K).RouteID).Id = rId);
-- We only delete plans associated to rId
pragma Assert (Element (routePlans, Get (resps, i).RouteID).Id = rId);
Delete (routePlans, Get (resps, i).RouteID);
end loop;
pragma Assert
(Only_Pending_Plans (routePlanResponses, routePlans));
pragma Assert (plan = Find (routePlanResponses, rId));
Delete (routePlanResponses, plan);
end;
end;
end loop;
pragma Assert (All_Plans_Registered (routePlanResponses, routePlans));
pragma Assert
(for all Id of Plan_To_Route (pendingRoute) =>
(if Get (Plan_To_Route (pendingRoute), Id) /= routeKey then
Contains (routePlanResponses, Id)
or else PlanRequest_Sent (Id)));
-- send the results of the query
sendBroadcastMessage (Mailbox, Response);
pragma Assume (Length (History) < Count_Type'Last, "We still have room for a new event in History");
History := Add (History, (Kind => Send_RouteResponse, Id => Response.ResponseID));
end SendRouteResponse;
-----------------
-- Plan_To_Route --
-----------------
function Plan_To_Route (pendingRoute : Int64_Formal_Set_Map) return Int64_Map is
Res : Int64_Map;
begin
for C in pendingRoute loop
pragma Loop_Variant (Increases => Int_Set_Maps_P.Get (Positions (pendingRoute), C));
pragma Loop_Invariant
(for all I of Res =>
Int_Set_Maps_M.Has_Key (Model (pendingRoute), Get (Res, I))
and then Contains (Int_Set_Maps_M.Get (Model (pendingRoute), Get (Res, I)), I));
pragma Loop_Invariant
(for all J in 1 .. Int_Set_Maps_P.Get (Positions (pendingRoute), C) - 1 =>
(for all K of Int_Set_Maps_M.Get (Model (pendingRoute), Int_Set_Maps_K.Get (Keys (pendingRoute), J)) =>
Has_Key (Res, K)
and then Get (Res, K) = Int_Set_Maps_K.Get (Keys (pendingRoute), J)));
pragma Loop_Invariant
(for all J in Int_Set_Maps_P.Get (Positions (pendingRoute), C) .. Length (pendingRoute) =>
(for all K of Int_Set_Maps_M.Get (Model (pendingRoute), Int_Set_Maps_K.Get (Keys (pendingRoute), J)) =>
not Has_Key (Res, K)));
declare
routePlans : Int64_Formal_Set renames Element (pendingRoute, C);
begin
for C2 in routePlans loop
pragma Loop_Variant (Increases => Int_Set_P.Get (Positions (routePlans), C2));
pragma Loop_Invariant
(for all I of Res =>
Int_Set_Maps_M.Has_Key (Model (pendingRoute), Get (Res, I))
and then Contains (Int_Set_Maps_M.Get (Model (pendingRoute), Get (Res, I)), I));
pragma Loop_Invariant
(for all J in 1 .. Int_Set_Maps_P.Get (Positions (pendingRoute), C) - 1 =>
(for all K of Int_Set_Maps_M.Get (Model (pendingRoute), Int_Set_Maps_K.Get (Keys (pendingRoute), J)) =>
Has_Key (Res, K)
and then Get (Res, K) = Int_Set_Maps_K.Get (Keys (pendingRoute), J)));
pragma Loop_Invariant
(for all J in Int_Set_Maps_P.Get (Positions (pendingRoute), C) + 1 .. Length (pendingRoute) =>
(for all K of Int_Set_Maps_M.Get (Model (pendingRoute), Int_Set_Maps_K.Get (Keys (pendingRoute), J)) =>
not Has_Key (Res, K)));
pragma Loop_Invariant
(for all J in 1 .. Int_Set_P.Get (Positions (routePlans), C2) - 1 =>
Has_Key (Res, Int_Set_E.Get (Elements (routePlans), J))
and then Get (Res, Int_Set_E.Get (Elements (routePlans), J)) = Key (pendingRoute, C));
pragma Loop_Invariant
(for all J in Int_Set_P.Get (Positions (routePlans), C2) .. Length (routePlans) =>
not Has_Key (Res, Int_Set_E.Get (Elements (routePlans), J)));
pragma Assume (Length (Res) < Count_Type'Last, "We have less than Count_Type'Last pending plan requests in total");
Res := Add (Res, Element (routePlans, C2), Key (pendingRoute, C));
end loop;
end;
end loop;
return Res;
end Plan_To_Route;
end Route_Aggregator;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS --
-- --
-- S Y S T E M . B B . B O A R D _ S U P P O R T --
-- --
-- B o d y --
-- --
-- Copyright (C) 1999-2002 Universidad Politecnica de Madrid --
-- Copyright (C) 2003-2005 The European Space Agency --
-- Copyright (C) 2003-2016, AdaCore --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
-- The port of GNARL to bare board targets was initially developed by the --
-- Real-Time Systems Group at the Technical University of Madrid. --
-- --
------------------------------------------------------------------------------
with Interfaces; use Interfaces;
with System.BB.Board_Parameters; use System.BB.Board_Parameters;
with System.BB.Parameters;
with System.BB.Protection;
package body System.BB.Board_Support is
-- Mapping between priorities and interrupt source.
-- HPI is not used; MIXA, MIXB, SYSA, SYSD groups are grouped.
-- All external and internal interrupts are routed to /int.
-- Interrupt ipp_ind_ext_int[0] is configured as an external maskable
-- interrupt (See initialization of SEMSR).
-- MCP interrupts are not handled by the runtime.
-- External IRQ interrupts are configured as level sensitive.
-- Here is the table between IPIC priority and Interrupt source. This is
-- extracted from Table 8-28, using the fact that only grouped scheme are
-- used. Interrupt_ID is the interrupt number for the IPIC, which according
-- to Table 8-6 is also the interrupt vector, which by definition is also
-- the Ada Interrupt_ID.
-- Priority Interrupt source Interrupt_ID
-- 1 (HPI)
-- 2 MIXA0 ipi_int_internal[32] 64
-- 3 MIXA1 ipi_int_internal[33] 65
-- 4 MIXA2 ipi_int_internal[34] 66
-- 5 MIXA3 ipi_int_internal[35] 67
-- 6 (MIXB0 - Spread)
-- 7-10 (Reserved)
-- 11 (MIXA1 - Spread)
-- 12-15 (Reserved)
-- 16 MIXB0 RTC ALR 68
-- 17 MIXB1 MU 69
-- 18 MIXB2 SBA 70
-- 19 MIXB3 DMA 71
-- 20 (MIXB1 - Spread)
-- 21 SYSA0 TSEC1 Tx 32
-- 22 SYSA1 TSEC1 Rx 33
-- 23 SYSA2 TSEC1 Err 34
-- 24 SYSA3 TSEC2 Tx 35
-- 25 (MIXA2 - Spread)
-- 26 SYSA4 TSEC2 Rx 36
-- 27 SYSA5 TSEC2 Err 37
-- 28 SYSA6 USB DR 38
-- 29 SYSA7 USB MPH 39
-- 30 MIXA4 ipp_ind_ext_int[0] 48
-- 31 MIXA5 ipp_ind_ext_int[1] 17
-- 32 MIXA6 ipp_ind_ext_int[2] 18
-- 33 MIXA7 ipp_ind_ext_int[3] 19
-- 34 (MIXB2 - Spread)
-- 35-38 (Reserved)
-- 39 (MIXA3 - Spread)
-- 40-43 (Reserved)
-- 44 MIXB4 IRQ4 20
-- 45 MIXB5 IRQ5 21
-- 46 MIXB6 IRQ6 22
-- 47 MIXB7 IRQ7 23
-- 48 (MIXB3 - Spread)
-- 49 SYSD0 UART1 9
-- 50 SYSD1 UART2 10
-- 51 SYSD2 SEC 11
-- 52 (SYSD3 - Reserved)
-- 53 (MIXA4 - Spread)
-- 54 (SYSD4 - Reserved)
-- 55 SYSD5 I2C1 14
-- 56 SYSD6 I2C2 15
-- 57 SYSD7 SPI 16
-- 58 (MIXB4 - Spread)
-- 59 GTM4 72
-- 60 (Reserved)
-- 61 (SYSA0 - Spread)
-- 62 GTM8 73
-- 63 (Reserved)
-- 64 (SYSD0 - Spread)
-- 65 (Reserved)
-- 66 GPIO1 74
-- 67 (MIXA5 - Spread)
-- 68 GPIO2 75
-- 69 (Reserved)
-- 70 (SYSA1 - Spread)
-- 71 DDR 76
-- 72 (Reserved)
-- 73 (SYSD1 - Spread)
-- 74 (Reserved)
-- 75 LBC 77
-- 76 (MIXB5 - Spread)
-- 77 GTM2 78
-- 78 (Reserved)
-- 79 (SYSA2 - Spread)
-- 80 GTM6 79
-- 81 (Reserved)
-- 82 (SYSD2 - Spread)
-- 83 (Reserved)
-- 84 PMC 80
-- 85 (MIXA6 - Spread)
-- 86 (Reserved)
-- 87 (Reserved)
-- 88 (SYSA3 - Spread)
-- 89 (Reserved)
-- 90 (Reserved)
-- 91 (SYSD3 (Spread))
-- 92 (Reserved)
-- 93 (Reserved)
-- 94 (MIXB6 (Spread))
-- 95 GTM3 84
-- 96 (Reserved)
-- 97 (SYSA4 (Spread))
-- 98 GTM7 85
-- 99 (Reserved)
-- 100 (SYSD4 - Spread)
-- 101 (Reserved)
-- 102 (Reserved)
-- 103 (MIXA7 - Spread)
-- 104 (Reserved)
-- 105 (Reserved)
-- 106 (SYSA5 - Spread)
-- 107 (Reserved)
-- 108 (Reserved)
-- 109 (SYSD5 - Spread)
-- 110 (Reserved)
-- 111 (Reserved)
-- 112 (MIXB7 - Spread)
-- 113 GTM1 90
-- 114 (Reserved)
-- 115 (SYSA6 - Spread)
-- 116 GTM5 91
-- 117 (Reserved)
-- 118 (SYSD6 - Spread)
-- 119 (Reserved)
-- 120 (Reserved)
-- 121 (Reserved)
-- 122 (Reserved)
-- 123 (SYSA7 - Spread)
-- 124 (Reserved)
-- 125 (Reserved)
-- 126 (SYSD7 - Spread)
-- 127 (Reserved)
-- 128 (Reserved)
procedure Define_Interrupt_Priority
(Interrupt : System.BB.Interrupts.Interrupt_ID;
Priority : Interrupt_Priority;
Mask_Bit : Natural);
pragma Export (Ada, Define_Interrupt_Priority,
"__gnat_define_interrupt_priority");
-- This is a user service to define the priority of interrupts and its
-- corresponding mask bit. It can be called at most once per interrupt.
use System.BB.Interrupts;
subtype Mask_Bit_Number is Natural range 0 .. 95;
-- Bit number in the SIMSR_H/SIMSR_L/SEMSR registers. Bit numbers 0 to 31
-- means bit 0 (MSB) to 31 (LSB) of SIMSR_H, bit numbers 32 to 63 means
-- bit 0 (MSB) to 31 (LSB) of SIMSR_L, and bit numbers 64 to 95 means
-- bit 0 (MSB) to 31 (LSB) of SEMSR.
type Interrupt_Priorities_Type is
array (System.BB.Interrupts.Interrupt_ID
range 0 .. System.BB.Parameters.Number_Of_Interrupt_ID - 1)
of Any_Priority;
-- Type for the interrupt to priority map
Interrupt_Priorities : Interrupt_Priorities_Type := (others => 0);
-- Map that associate an interrupt id with its priority
type Priority_Mask is record
SIMSR_H : Unsigned_32;
-- SIMSR_H value
SIMSR_L : Unsigned_32;
-- SIMSR_L value
SEMSR : Unsigned_32;
-- SEMSR value
end record;
type Priority_Mask_Map_Type is
array (Priority'Last .. Interrupt_Priority'Last) of Priority_Mask;
-- Interrupt mask values for each interrupt priority and for non-interrupt
-- priorities (Priority'Last is used for that case).
Priority_Masks : Priority_Mask_Map_Type := (others => (0, 0, 0));
-- Mask for eash priority. Initially all interrupts are masked
SEMSR : Unsigned_32;
for SEMSR'Address use IMMRBAR + 16#0738#;
pragma Volatile (SEMSR);
pragma Import (Ada, SEMSR);
-- System External interrupt Mask Register
SIMSR_H : Unsigned_32;
for SIMSR_H'Address use IMMRBAR + 16#0720#;
pragma Volatile (SIMSR_H);
pragma Import (Ada, SIMSR_H);
-- System Internal interrupt Mask Register (High)
SIMSR_L : Unsigned_32;
for SIMSR_L'Address use IMMRBAR + 16#0724#;
pragma Volatile (SIMSR_L);
pragma Import (Ada, SIMSR_L);
-- System Internal interrupt Mask Register (Low)
----------------------
-- Initialize_Board --
----------------------
procedure Initialize_Board is
SICFR : Unsigned_32;
for SICFR'Address use IMMRBAR + 16#0700#;
pragma Volatile (SICFR);
pragma Import (Ada, SICFR);
SIPRR_A : Unsigned_32;
for SIPRR_A'Address use IMMRBAR + 16#0710#;
pragma Volatile (SIPRR_A);
pragma Import (Ada, SIPRR_A);
SIPRR_D : Unsigned_32;
for SIPRR_D'Address use IMMRBAR + 16#071C#;
pragma Volatile (SIPRR_D);
pragma Import (Ada, SIPRR_D);
SICNR : Unsigned_32;
for SICNR'Address use IMMRBAR + 16#0728#;
pragma Volatile (SICNR);
pragma Import (Ada, SICNR);
SMPRR_A : Unsigned_32;
for SMPRR_A'Address use IMMRBAR + 16#0730#;
pragma Volatile (SMPRR_A);
pragma Import (Ada, SMPRR_A);
SMPRR_B : Unsigned_32;
for SMPRR_B'Address use IMMRBAR + 16#0734#;
pragma Volatile (SMPRR_B);
pragma Import (Ada, SMPRR_B);
SECNR : Unsigned_32;
for SECNR'Address use IMMRBAR + 16#073C#;
pragma Volatile (SECNR);
pragma Import (Ada, SECNR);
begin
-- Initialize IPIC
-- At that point, all interrupts should be masked in the MSR
-- H M M I I H
-- P P P P P P
-- I S S S S E
-- B A D A T
SICFR := 2#0_0000000_0_0_0_0_0_00_0_000000_00_00000000#;
-- SYSA 0P 1P 2P 3P -- 4P 5P 6P 7P --
SIPRR_A := 2#000_001_010_011_0000_100_101_110_111_0000#;
-- SYSD 0P 1P 2P 3P -- 4P 5P 6P 7P --
SIPRR_D := 2#000_001_010_011_0000_100_101_110_111_0000#;
-- SYSD0T 1T SYSA0T 1T
SICNR := 2#00_00_000000000000_00000000_00_00_0000#;
-- SMPRR_A 0P 1P 2P 3P -- 4P 5P 6P 7P --
SMPRR_A := 2#000_001_010_011_0000_100_101_110_111_0000#;
-- SMPRR_B 0P 1P 2P 3P -- 4P 5P 6P 7P --
SMPRR_B := 2#000_001_010_011_0000_100_101_110_111_0000#;
-- MIXB0T 1T MIXA0T 1T EDI
SECNR := 2#00_00_0000_00_00_0000_00000000_00000000#;
-- Mask all interrupts, and steer ipp_ind_ext_int[0] as external
-- interrupt request.
SIMSR_H := 2#00000000_00000000_00000000_000_00_000#;
SIMSR_L := 2#00000000_00000000_0_000_00_0000_00_0000#;
SEMSR := 2#00000000_00000000_0_000000000000000#;
end Initialize_Board;
---------------------------
-- Clear_Alarm_Interrupt --
---------------------------
procedure Clear_Alarm_Interrupt is
begin
-- Nothing to do on standard powerpc
null;
end Clear_Alarm_Interrupt;
---------------------------
-- Get_Interrupt_Request --
---------------------------
function Get_Interrupt_Request
(Vector : CPU_Specific.Vector_Id) return Interrupt_ID
is
pragma Unreferenced (Vector);
SIVCR : Unsigned_32;
for SIVCR'Address use IMMRBAR + 16#0704#;
pragma Volatile (SIVCR);
pragma Import (Ada, SIVCR);
-- The SIVCR register contains the regular unmasked interrupt source
-- of the highest priority level.
begin
return System.BB.Interrupts.Interrupt_ID (SIVCR and 16#7F#);
end Get_Interrupt_Request;
-------------------------------
-- Install_Interrupt_Handler --
-------------------------------
procedure Install_Interrupt_Handler
(Handler : Address;
Interrupt : Interrupts.Interrupt_ID;
Prio : Interrupt_Priority)
is
pragma Unreferenced (Interrupt, Prio);
begin
CPU_Specific.Install_Exception_Handler
(Handler, CPU_Specific.External_Interrupt_Excp);
end Install_Interrupt_Handler;
---------------------------
-- Priority_Of_Interrupt --
---------------------------
function Priority_Of_Interrupt
(Interrupt : System.BB.Interrupts.Interrupt_ID) return System.Any_Priority
is
Result : constant Any_Priority := Interrupt_Priorities (Interrupt);
begin
-- The priority of an interrupt should be in the Interrupt_Priority
-- range. A failure indicates a spurious interrupt, or an interrupt
-- that was unmasked directly.
pragma Assert (Result in Interrupt_Priority);
return Result;
end Priority_Of_Interrupt;
----------------
-- Power_Down --
----------------
procedure Power_Down is
begin
null;
end Power_Down;
-----------------------------
-- Clear_Interrupt_Request --
-----------------------------
procedure Clear_Interrupt_Request
(Interrupt : System.BB.Interrupts.Interrupt_ID)
is
begin
-- Nothing to do for the IPIC
null;
end Clear_Interrupt_Request;
--------------------------
-- Set_Current_Priority --
--------------------------
procedure Set_Current_Priority (Priority : Integer) is
begin
-- Note that Priority cannot be the last one, as this procedure is
-- unable to disable the decrementer interrupt.
pragma Assert (Priority /= Interrupt_Priority'Last);
-- Must be called with MSR.IE set to 0, to avoid unprioritized
-- interrupt delivery.
if Priority < System.Interrupt_Priority'First then
SIMSR_H := Priority_Masks (System.Priority'Last).SIMSR_H;
SIMSR_L := Priority_Masks (System.Priority'Last).SIMSR_L;
SEMSR := Priority_Masks (System.Priority'Last).SEMSR;
else
SIMSR_H := Priority_Masks (Priority).SIMSR_H;
SIMSR_L := Priority_Masks (Priority).SIMSR_L;
SEMSR := Priority_Masks (Priority).SEMSR;
end if;
end Set_Current_Priority;
-------------------------------
-- Define_Interrupt_Priority --
-------------------------------
procedure Define_Interrupt_Priority
(Interrupt : System.BB.Interrupts.Interrupt_ID;
Priority : Interrupt_Priority;
Mask_Bit : Natural)
is
Mask : Unsigned_32;
-- Bit to set in the mask register
subtype Int32_Bit_Number is Natural range 0 .. 31;
-- Constrain the right operand of exponentiation so that the compiler
-- is able to replace it by a shift.
begin
-- Check the priority was never defined for this interrupt
pragma Assert (Interrupt_Priorities (Interrupt) = 0);
Protection.Enter_Kernel;
-- Save the values
Interrupt_Priorities (Interrupt) := Priority;
-- Regenerate masks
case Mask_Bit_Number (Mask_Bit) is
when 0 .. 31 =>
Mask := 2 ** Int32_Bit_Number (31 - Mask_Bit);
for P in System.Priority'Last .. Priority - 1 loop
Priority_Masks (P).SIMSR_H :=
Priority_Masks (P).SIMSR_H or Mask;
end loop;
when 32 .. 63 =>
Mask := 2 ** Int32_Bit_Number (63 - Mask_Bit);
for P in System.Priority'Last .. Priority - 1 loop
Priority_Masks (P).SIMSR_L :=
Priority_Masks (P).SIMSR_L or Mask;
end loop;
when 64 .. 95 =>
Mask := 2 ** Int32_Bit_Number (95 - Mask_Bit);
for P in System.Priority'Last .. Priority - 1 loop
Priority_Masks (P).SEMSR :=
Priority_Masks (P).SEMSR or Mask;
end loop;
end case;
-- Will set mask registers
Protection.Leave_Kernel;
end Define_Interrupt_Priority;
end System.BB.Board_Support;
|
package body Test_Date.Read is
procedure Initialize (T : in out Test) is
begin
Set_Name (T, "Test_Date.Read");
Ahven.Framework.Add_Test_Routine (T, Date_1'Access, "1. date: date = 1");
Ahven.Framework.Add_Test_Routine (T, Date_2'Access, "2. date: date = -1");
end Initialize;
procedure Date_1 is
State : access Skill_State := new Skill_State;
begin
Skill.Read (State, "resources/date-example.sf");
declare
X : Date_Type_Access := Skill.Get_Date (State, 1);
begin
Ahven.Assert (X.Get_Date = 1, "'first date'.Get_Date is not 1.");
end;
end Date_1;
procedure Date_2 is
State : access Skill_State := new Skill_State;
begin
Skill.Read (State, "resources/date-example.sf");
declare
X : Date_Type_Access := Skill.Get_Date (State, 2);
begin
Ahven.Assert (X.Get_Date = -1, "'second date'.Get_Date is not -1.");
end;
end Date_2;
end Test_Date.Read;
|
-----------------------------------------------------------------------
-- security-oauth-clients -- OAuth Client Security
-- Copyright (C) 2012, 2013, 2017, 2018, 2020 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Exceptions;
with Util.Log.Loggers;
with Util.Strings;
with Util.Beans.Objects;
with Util.Http.Clients;
with Util.Properties.JSON;
with Util.Properties.Form;
with Util.Encoders.HMAC.SHA1;
with Security.Random;
package body Security.OAuth.Clients is
use Ada.Strings.Unbounded;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.OAuth.Clients");
procedure Do_Request_Token (URI : in String;
Data : in Util.Http.Clients.Form_Data'Class;
Cred : in out Grant_Type'Class);
function Get_Expires (Props : in Util.Properties.Manager) return Natural;
-- ------------------------------
-- Access Token
-- ------------------------------
Random_Generator : Security.Random.Generator;
-- ------------------------------
-- Generate a random nonce with at last the number of random bits.
-- The number of bits is rounded up to a multiple of 32.
-- The random bits are then converted to base64url in the returned string.
-- ------------------------------
function Create_Nonce (Bits : in Positive := 256) return String is
begin
-- Generate the random sequence.
return Random_Generator.Generate (Bits);
end Create_Nonce;
-- ------------------------------
-- Get the principal name. This is the OAuth access token.
-- ------------------------------
function Get_Name (From : in Access_Token) return String is
begin
return From.Access_Id;
end Get_Name;
-- ------------------------------
-- Get the id_token that was returned by the authentication process.
-- ------------------------------
function Get_Id_Token (From : in OpenID_Token) return String is
begin
return From.Id_Token;
end Get_Id_Token;
-- ------------------------------
-- Get the principal name. This is the OAuth access token.
-- ------------------------------
function Get_Name (From : in Grant_Type) return String is
begin
return To_String (From.Access_Token);
end Get_Name;
-- ------------------------------
-- Get the Authorization header to be used for accessing a protected resource.
-- (See RFC 6749 7. Accessing Protected Resources)
-- ------------------------------
function Get_Authorization (From : in Grant_Type) return String is
begin
return "Bearer " & To_String (From.Access_Token);
end Get_Authorization;
-- ------------------------------
-- Set the OAuth authorization server URI that the application must use
-- to exchange the OAuth code into an access token.
-- ------------------------------
procedure Set_Provider_URI (App : in out Application;
URI : in String) is
begin
App.Request_URI := Ada.Strings.Unbounded.To_Unbounded_String (URI);
end Set_Provider_URI;
-- ------------------------------
-- Build a unique opaque value used to prevent cross-site request forgery.
-- The <b>Nonce</b> parameters is an optional but recommended unique value
-- used only once. The state value will be returned back by the OAuth provider.
-- This protects the <tt>client_id</tt> and <tt>redirect_uri</tt> parameters.
-- ------------------------------
function Get_State (App : in Application;
Nonce : in String) return String is
Data : constant String := Nonce & To_String (App.Client_Id) & To_String (App.Callback);
Hmac : String := Util.Encoders.HMAC.SHA1.Sign_Base64 (Key => To_String (App.Secret),
Data => Data,
URL => True);
begin
-- Avoid the '=' at end of HMAC since it could be replaced by %C20 which is annoying...
Hmac (Hmac'Last) := '.';
return Hmac;
end Get_State;
-- ------------------------------
-- Get the authenticate parameters to build the URI to redirect the user to
-- the OAuth authorization form.
-- ------------------------------
function Get_Auth_Params (App : in Application;
State : in String;
Scope : in String := "") return String is
begin
return Security.OAuth.CLIENT_ID
& "=" & Ada.Strings.Unbounded.To_String (App.Client_Id)
& "&"
& Security.OAuth.REDIRECT_URI
& "=" & Ada.Strings.Unbounded.To_String (App.Callback)
& "&"
& Security.OAuth.SCOPE
& "=" & Scope
& "&"
& Security.OAuth.STATE
& "=" & State;
end Get_Auth_Params;
-- ------------------------------
-- Verify that the <b>State</b> opaque value was created by the <b>Get_State</b>
-- operation with the given client and redirect URL.
-- ------------------------------
function Is_Valid_State (App : in Application;
Nonce : in String;
State : in String) return Boolean is
Hmac : constant String := Application'Class (App).Get_State (Nonce);
begin
return Hmac = State;
end Is_Valid_State;
function Get_Expires (Props : in Util.Properties.Manager) return Natural is
Value : Util.Beans.Objects.Object;
begin
Value := Props.Get_Value ("expires_in");
if Util.Beans.Objects.Is_Null (Value) then
Value := Props.Get_Value ("refresh_token_expires_in");
if Util.Beans.Objects.Is_Null (Value) then
return 3600;
end if;
end if;
return Util.Beans.Objects.To_Integer (Value);
end Get_Expires;
-- ------------------------------
-- Exchange the OAuth code into an access token.
-- ------------------------------
function Request_Access_Token (App : in Application;
Code : in String) return Access_Token_Access is
Client : Util.Http.Clients.Client;
Response : Util.Http.Clients.Response;
Data : constant String
:= Security.OAuth.GRANT_TYPE & "=authorization_code"
& "&"
& Security.OAuth.CODE & "=" & Code
& "&"
& Security.OAuth.REDIRECT_URI & "=" & Ada.Strings.Unbounded.To_String (App.Callback)
& "&"
& Security.OAuth.CLIENT_ID & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id)
& "&"
& Security.OAuth.CLIENT_SECRET & "=" & Ada.Strings.Unbounded.To_String (App.Secret);
URI : constant String := Ada.Strings.Unbounded.To_String (App.Request_URI);
begin
Log.Info ("Getting access token from {0}", URI);
begin
Client.Post (URL => URI,
Data => Data,
Reply => Response);
if Response.Get_Status /= Util.Http.SC_OK then
Log.Warn ("Cannot get access token from {0}: status is {1} Body {2}",
URI, Natural'Image (Response.Get_Status), Response.Get_Body);
return null;
end if;
exception
-- Handle a Program_Error exception that could be raised by AWS when SSL
-- is not supported. Emit a log error so that we can trouble this kins of
-- problem more easily.
when E : Program_Error =>
Log.Error ("Cannot get access token from {0}: program error: {1}",
URI, Ada.Exceptions.Exception_Message (E));
raise;
end;
-- Decode the response.
declare
Content : constant String := Response.Get_Body;
Content_Type : constant String := Response.Get_Header ("Content-Type");
Pos : Natural := Util.Strings.Index (Content_Type, ';');
Last : Natural;
Expires : Natural;
begin
if Pos = 0 then
Pos := Content_Type'Last;
else
Pos := Pos - 1;
end if;
Log.Debug ("Content type: {0}", Content_Type);
Log.Debug ("Data: {0}", Content);
-- Facebook sends the access token as a 'text/plain' content.
if Content_Type (Content_Type'First .. Pos) = "text/plain" then
Pos := Util.Strings.Index (Content, '=');
if Pos = 0 then
Log.Error ("Invalid access token response: '{0}'", Content);
return null;
end if;
if Content (Content'First .. Pos) /= "access_token=" then
Log.Error ("The 'access_token' parameter is missing in response: '{0}'", Content);
return null;
end if;
Last := Util.Strings.Index (Content, '&', Pos + 1);
if Last = 0 then
Log.Error ("Invalid 'access_token' parameter: '{0}'", Content);
return null;
end if;
if Content (Last .. Last + 8) /= "&expires=" then
Log.Error ("Invalid 'expires' parameter: '{0}'", Content);
return null;
end if;
Expires := Natural'Value (Content (Last + 9 .. Content'Last));
return Application'Class (App).Create_Access_Token (Content (Pos + 1 .. Last - 1),
"", "",
Expires);
elsif Content_Type (Content_Type'First .. Pos) = "application/json" then
declare
P : Util.Properties.Manager;
begin
Util.Properties.JSON.Parse_JSON (P, Content);
Expires := Get_Expires (P);
return Application'Class (App).Create_Access_Token (P.Get ("access_token"),
P.Get ("refresh_token", ""),
P.Get ("id_token", ""),
Expires);
end;
elsif Content_Type (Content_Type'First .. Pos) = "application/x-www-form-urlencoded" then
declare
P : Util.Properties.Manager;
begin
Util.Properties.Form.Parse_Form (P, Content);
Expires := Get_Expires (P);
return Application'Class (App).Create_Access_Token (P.Get ("access_token"),
P.Get ("refresh_token", ""),
P.Get ("id_token", ""),
Expires);
end;
else
Log.Error ("Content type {0} not supported for access token response", Content_Type);
Log.Error ("Response: {0}", Content);
return null;
end if;
end;
end Request_Access_Token;
-- ------------------------------
-- Exchange the OAuth code into an access token.
-- ------------------------------
procedure Do_Request_Token (URI : in String;
Data : in Util.Http.Clients.Form_Data'Class;
Cred : in out Grant_Type'Class) is
Client : Util.Http.Clients.Client;
Response : Util.Http.Clients.Response;
begin
Log.Info ("Getting access token from {0}", URI);
Client.Post (URL => URI,
Data => Data,
Reply => Response);
if Response.Get_Status /= Util.Http.SC_OK then
Log.Warn ("Cannot get access token from {0}: status is {1} Body {2}",
URI, Natural'Image (Response.Get_Status), Response.Get_Body);
return;
end if;
-- Decode the response.
declare
Content : constant String := Response.Get_Body;
Content_Type : constant String := Response.Get_Header ("Content-Type");
Pos : Natural := Util.Strings.Index (Content_Type, ';');
Last : Natural;
begin
if Pos = 0 then
Pos := Content_Type'Last;
else
Pos := Pos - 1;
end if;
Log.Debug ("Content type: {0}", Content_Type);
Log.Debug ("Data: {0}", Content);
-- Facebook sends the access token as a 'text/plain' content.
if Content_Type (Content_Type'First .. Pos) = "text/plain" then
Pos := Util.Strings.Index (Content, '=');
if Pos = 0 then
Log.Error ("Invalid access token response: '{0}'", Content);
return;
end if;
if Content (Content'First .. Pos) /= "access_token=" then
Log.Error ("The 'access_token' parameter is missing in response: '{0}'", Content);
return;
end if;
Last := Util.Strings.Index (Content, '&', Pos + 1);
if Last = 0 then
Log.Error ("Invalid 'access_token' parameter: '{0}'", Content);
return;
end if;
if Content (Last .. Last + 8) /= "&expires=" then
Log.Error ("Invalid 'expires' parameter: '{0}'", Content);
return;
end if;
Cred.Expires := Natural'Value (Content (Last + 9 .. Content'Last));
Cred.Access_Token := To_Unbounded_String (Content (Pos + 1 .. Last - 1));
elsif Content_Type (Content_Type'First .. Pos) = "application/json" then
declare
P : Util.Properties.Manager;
begin
Util.Properties.JSON.Parse_JSON (P, Content);
Cred.Expires := Natural'Value (P.Get ("expires_in"));
Cred.Access_Token := P.Get ("access_token");
Cred.Refresh_Token := To_Unbounded_String (P.Get ("refresh_token", ""));
Cred.Id_Token := To_Unbounded_String (P.Get ("id_token", ""));
end;
else
Log.Error ("Content type {0} not supported for access token response", Content_Type);
Log.Error ("Response: {0}", Content);
return;
end if;
end;
exception
-- Handle a Program_Error exception that could be raised by AWS when SSL
-- is not supported. Emit a log error so that we can trouble this kins of
-- problem more easily.
when E : Program_Error =>
Log.Error ("Cannot get access token from {0}: program error: {1}",
URI, Ada.Exceptions.Exception_Message (E));
raise;
end Do_Request_Token;
-- ------------------------------
-- Get a request token with username and password.
-- RFC 6749: 4.3. Resource Owner Password Credentials Grant
-- ------------------------------
procedure Request_Token (App : in Application;
Username : in String;
Password : in String;
Scope : in String;
Token : in out Grant_Type'Class) is
URI : constant String := Ada.Strings.Unbounded.To_String (App.Request_URI);
Form : Util.Http.Clients.Form_Data;
begin
Log.Info ("Getting access token from {0} - resource owner password", URI);
Form.Initialize (Size => 1024);
Form.Write_Attribute (Security.OAuth.GRANT_TYPE, "password");
Form.Write_Attribute (Security.OAuth.CLIENT_ID, App.Client_Id);
Form.Write_Attribute (Security.OAuth.CLIENT_SECRET, App.Secret);
Form.Write_Attribute (Security.OAuth.USERNAME, Username);
Form.Write_Attribute (Security.OAuth.PASSWORD, Password);
Form.Write_Attribute (Security.OAuth.SCOPE, Scope);
Do_Request_Token (URI, Form, Token);
end Request_Token;
-- ------------------------------
-- Refresh the access token.
-- RFC 6749: 6. Refreshing an Access Token
-- ------------------------------
procedure Refresh_Token (App : in Application;
Scope : in String;
Token : in out Grant_Type'Class) is
URI : constant String := Ada.Strings.Unbounded.To_String (App.Request_URI);
Form : Util.Http.Clients.Form_Data;
begin
Log.Info ("Refresh access token from {0}", URI);
Form.Initialize (Size => 1024);
Form.Write_Attribute (Security.OAuth.GRANT_TYPE, "refresh_token");
Form.Write_Attribute (Security.OAuth.REFRESH_TOKEN, Token.Refresh_Token);
Form.Write_Attribute (Security.OAuth.CLIENT_ID, App.Client_Id);
Form.Write_Attribute (Security.OAuth.SCOPE, Scope);
Form.Write_Attribute (Security.OAuth.CLIENT_SECRET, App.Secret);
Do_Request_Token (URI, Form, Token);
end Refresh_Token;
-- ------------------------------
-- Create the access token
-- ------------------------------
function Create_Access_Token (App : in Application;
Token : in String;
Refresh : in String;
Id_Token : in String;
Expires : in Natural) return Access_Token_Access is
pragma Unreferenced (App, Expires);
begin
if Id_Token'Length > 0 then
declare
Result : constant OpenID_Token_Access
:= new OpenID_Token '(Len => Token'Length,
Id_Len => Id_Token'Length,
Refresh_Len => Refresh'Length,
Access_Id => Token,
Id_Token => Id_Token,
Refresh_Token => Refresh);
begin
return Result.all'Access;
end;
else
return new Access_Token '(Len => Token'Length,
Access_Id => Token);
end if;
end Create_Access_Token;
end Security.OAuth.Clients;
|
--
-- 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.Calendar;
with Database.Events;
with Database.Jobs;
with Navigate;
package body Commands is
procedure Create_Job (Job : in Types.Job_Id;
Title : in String;
Parent : in Types.Job_Id)
is
Id : Database.Events.Event_Id;
pragma Unreferenced (Id);
begin
Database.Jobs.Add_Job (Job, Title, Parent, "jquorning");
Database.Events.Add_Event (Job, Ada.Calendar.Clock,
Database.Events.Created, Id);
end Create_Job;
procedure Set_Current_Job (Job : in Types.Job_Id) is
begin
Database.Jobs.Set_Current_Job (Job);
Navigate.List.Current := Job;
Navigate.Refresh_List;
end Set_Current_Job;
end Commands;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- S T Y L E G . C --
-- --
-- B o d y --
-- --
-- Copyright (C) 1992-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 Atree; use Atree;
with Casing; use Casing;
with Csets; use Csets;
with Einfo; use Einfo;
with Err_Vars; use Err_Vars;
with Namet; use Namet;
with Sinfo; use Sinfo;
with Sinput; use Sinput;
with Stand; use Stand;
with Stylesw; use Stylesw;
package body Styleg.C is
-----------------------
-- Body_With_No_Spec --
-----------------------
-- If the check specs mode (-gnatys) is set, then all subprograms must
-- have specs unless they are parameterless procedures that are not child
-- units at the library level (i.e. they are possible main programs).
procedure Body_With_No_Spec (N : Node_Id) is
begin
if Style_Check_Specs then
if Nkind (Parent (N)) = N_Compilation_Unit then
declare
Spec : constant Node_Id := Specification (N);
Defnm : constant Node_Id := Defining_Unit_Name (Spec);
begin
if Nkind (Spec) = N_Procedure_Specification
and then Nkind (Defnm) = N_Defining_Identifier
and then No (First_Formal (Defnm))
then
return;
end if;
end;
end if;
Error_Msg_N ("(style) subprogram body has no previous spec", N);
end if;
end Body_With_No_Spec;
----------------------
-- Check_Identifier --
----------------------
-- In check references mode (-gnatyr), identifier uses must be cased
-- the same way as the corresponding identifier declaration.
procedure Check_Identifier
(Ref : Node_Or_Entity_Id;
Def : Node_Or_Entity_Id)
is
Sref : Source_Ptr := Sloc (Ref);
Sdef : Source_Ptr := Sloc (Def);
Tref : Source_Buffer_Ptr;
Tdef : Source_Buffer_Ptr;
Nlen : Nat;
Cas : Casing_Type;
begin
-- If reference does not come from source, nothing to check
if not Comes_From_Source (Ref) then
return;
-- If previous error on either node/entity, ignore
elsif Error_Posted (Ref) or else Error_Posted (Def) then
return;
-- Case of definition comes from source
elsif Comes_From_Source (Def) then
-- Check same casing if we are checking references
if Style_Check_References then
Tref := Source_Text (Get_Source_File_Index (Sref));
Tdef := Source_Text (Get_Source_File_Index (Sdef));
-- Ignore operator name case completely. This also catches the
-- case of where one is an operator and the other is not. This
-- is a phenomenon from rewriting of operators as functions,
-- and is to be ignored.
if Tref (Sref) = '"' or else Tdef (Sdef) = '"' then
return;
else
while Tref (Sref) = Tdef (Sdef) loop
-- If end of identifier, all done
if not Identifier_Char (Tref (Sref)) then
return;
-- Otherwise loop continues
else
Sref := Sref + 1;
Sdef := Sdef + 1;
end if;
end loop;
-- Fall through loop when mismatch between identifiers
-- If either identifier is not terminated, error.
if Identifier_Char (Tref (Sref))
or else
Identifier_Char (Tdef (Sdef))
then
Error_Msg_Node_1 := Def;
Error_Msg_Sloc := Sloc (Def);
Error_Msg
("(style) bad casing of & declared#", Sref);
return;
-- Else end of identifiers, and they match
else
return;
end if;
end if;
end if;
-- Case of definition in package Standard
elsif Sdef = Standard_Location then
-- Check case of identifiers in Standard
if Style_Check_Standard then
Tref := Source_Text (Get_Source_File_Index (Sref));
-- Ignore operators
if Tref (Sref) = '"' then
null;
-- Otherwise determine required casing of Standard entity
else
-- ASCII entities are in all upper case
if Entity (Ref) = Standard_ASCII then
Cas := All_Upper_Case;
-- Special names in ASCII are also all upper case
elsif Entity (Ref) in SE (S_LC_A) .. SE (S_LC_Z)
or else
Entity (Ref) in SE (S_NUL) .. SE (S_US)
or else
Entity (Ref) = SE (S_DEL)
then
Cas := All_Upper_Case;
-- All other entities are in mixed case
else
Cas := Mixed_Case;
end if;
Nlen := Length_Of_Name (Chars (Ref));
-- Now check if we have the right casing
if Determine_Casing
(Tref (Sref .. Sref + Source_Ptr (Nlen) - 1)) = Cas
then
null;
else
Name_Len := Integer (Nlen);
Name_Buffer (1 .. Name_Len) :=
String (Tref (Sref .. Sref + Source_Ptr (Nlen) - 1));
Set_Casing (Cas);
Error_Msg_Name_1 := Name_Enter;
Error_Msg_N
("(style) bad casing of { declared in Standard", Ref);
end if;
end if;
end if;
end if;
end Check_Identifier;
-----------------------------------
-- Subprogram_Not_In_Alpha_Order --
-----------------------------------
procedure Subprogram_Not_In_Alpha_Order (Name : Node_Id) is
begin
if Style_Check_Order_Subprograms then
Error_Msg_N
("(style) subprogram body& not in alphabetical order", Name);
end if;
end Subprogram_Not_In_Alpha_Order;
end Styleg.C;
|
-- Test QR least squares equation solving real valued square matrices.
with Ada.Numerics.Generic_elementary_functions;
with Givens_QR;
with Test_Matrices;
With Text_IO; use Text_IO;
procedure givens_qr_tst_3 is
type Real is digits 15;
subtype Index is Integer range 1..137;
subtype Row_Index is Index;
subtype Col_Index is Index;
Starting_Row : constant Row_Index := Index'First + 0;
Starting_Col : constant Col_Index := Index'First + 0;
Final_Row : constant Row_Index := Index'Last - 0;
Final_Col : constant Col_Index := Index'Last - 0;
type Matrix is array(Row_Index, Col_Index) of Real;
type Matrix_inv is array(Col_Index, Row_Index) of Real;
-- For inverses of A : Matrix; has shape of A_transpose.
type Matrix_normal is array(Col_Index, Col_Index) of Real;
-- For A_transpose * A: the Least Squares Normal Equations fit in here.
-- (A_transpose * A) * x = b are called the normal equations.
type Matrix_residual is array(Row_Index, Row_Index) of Real;
-- For A x A_transpose
--pragma Convention (Fortran, Matrix); --No! This QR prefers Ada convention.
package math is new Ada.Numerics.Generic_Elementary_Functions (Real);
use math;
package QR is new Givens_QR
(Real => Real,
R_Index => Index,
C_Index => Index,
A_Matrix => Matrix);
use QR;
-- QR exports Row_Vector and Col_Vector
package Make_Square_Matrix is new Test_Matrices (Real, Index, Matrix);
use Make_Square_Matrix;
package rio is new Float_IO(Real);
use rio;
subtype Longer_Real is Real; -- general case, and for best speed
--type Longer_Real is digits 18; -- 18 ok on intel, rarely useful
Min_Real :constant Real := 2.0 ** (Real'Machine_Emin/2 + Real'Machine_Emin/4);
Zero : constant Real := +0.0;
One : constant Real := +1.0;
Two : constant Real := +2.0;
--Desired_Matrix : Matrix_Id := Upper_Ones;
--Desired_Matrix : Matrix_Id := Lower_Ones;
--Desired_Matrix : Matrix_Id := All_Ones; -- singular
--Desired_Matrix : Matrix_Id := Zero_Cols_and_Rows; -- singular
--Desired_Matrix : Matrix_Id := Easy_Matrix;
--Desired_Matrix : Matrix_Id := Symmetric_Banded;
--Desired_Matrix : Matrix_Id := Pascal; -- eigval = x, 1/x all positive.
--Desired_Matrix : Matrix_Id := Forsythe_Symmetric; -- Small diag
--Desired_Matrix : Matrix_Id := Forsythe; -- eigs on circle of rad 2**(-m)
--Desired_Matrix : Matrix_Id := Small_Diagonal;
--Desired_Matrix : Matrix_Id := Zero_Diagonal_2;
--Desired_Matrix : Matrix_Id := Kahan;
--Desired_Matrix : Matrix_Id := Non_Diagonalizable; -- one eigval, one eigvec.
--Desired_Matrix : Matrix_Id := Peters_0; -- one small eig., but better than Moler
--Desired_Matrix : Matrix_Id := Peters_1; -- row pivoting likes this
--Desired_Matrix : Matrix_Id := Peters_2; -- max growth with row pivoting
--Desired_Matrix : Matrix_Id := Frank; -- eigenvals -> .25; at N=16, 64:1.00...0
--Desired_Matrix : Matrix_Id := Ring_Adjacency; -- singular at 4, 8, 12, 16, 24, 32 ..
--Desired_Matrix : Matrix_Id := Zero_Diagonal; -- Like Wilkinson, if N odd: 1 zero eig.
--Desired_Matrix : Matrix_Id := Wilkinson_minus; -- 1 zero eig N odd, else 1 small eig
--Desired_Matrix : Matrix_Id := Moler_0;
--Desired_Matrix : Matrix_Id := Moler_1;
--Desired_Matrix : Matrix_Id := Random;
--Desired_Matrix : Matrix_Id := Vandermonde; -- max size is 256 x 256; else overflows
--Desired_Matrix : Matrix_Id := Hilbert;
--Desired_Matrix : Matrix_Id := Ding_Dong; -- Eigs clustered near +/- Pi
A, R, A_lsq : Matrix;
A_inv_lsq : Matrix_inv;
A_x_A_inv_minus_I : Matrix_residual;
A_tr_x_Residual : Matrix_Normal; -- Col_Index x Col_Index
Q : Q_Matrix;
Err_in_Least_Squ_A, Frobenius_lsq_soln_err : Real;
Condition_Number_of_Least_Squ_A, Condition_Number_of_A : Real;
Sum : Longer_Real;
Scale : Col_Vector;
Permute : Permutation;
Cutoff_Threshold_1 : constant Real := Two**(-30);
Singularity_Cutoff_Threshold : Real;
--------------------
-- Frobenius_Norm --
--------------------
function Frobenius_Norm
(A : in Matrix_normal)
--Final_Row : in Index;
--Final_Col : in Index;
--Starting_Row : in Index;
--Starting_Col : in Index)
return Real
is
Max_A_Val : Real := Zero;
Sum, Scaling, tmp : Real := Zero;
begin
Max_A_Val := Zero;
for Row in Starting_Col .. Final_Col loop
for Col in Starting_Col .. Final_Col loop
if Max_A_Val < Abs A(Row, Col) then Max_A_Val := Abs A(Row, Col); end if;
end loop;
end loop;
Max_A_Val := Max_A_Val + Two ** (Real'Machine_Emin + 4);
Scaling := One / Max_A_Val;
Sum := Zero;
for Row in Starting_Col .. Final_Col loop
for Col in Starting_Col .. Final_Col loop
tmp := Scaling * A(Row, Col);
Sum := Sum + tmp * tmp;
end loop;
end loop;
return Sqrt (Sum) * Max_A_Val;
end Frobenius_Norm;
--------------------
-- Frobenius_Norm --
--------------------
function Frobenius_Norm
(A : in Matrix)
--Final_Row : in Index;
--Final_Col : in Index;
--Starting_Row : in Index;
--Starting_Col : in Index)
return Real
is
Max_A_Val : Real := Zero;
Sum, Scaling, tmp : Real := Zero;
begin
Max_A_Val := Zero;
for Row in Starting_Row .. Final_Row loop
for Col in Starting_Col .. Final_Col loop
if Max_A_Val < Abs A(Row, Col) then Max_A_Val := Abs A(Row, Col); end if;
end loop;
end loop;
Max_A_Val := Max_A_Val + Two ** (Real'Machine_Emin + 4);
Scaling := One / Max_A_Val;
Sum := Zero;
for Row in Starting_Row .. Final_Row loop
for Col in Starting_Col .. Final_Col loop
tmp := Scaling * A(Row, Col);
Sum := Sum + tmp * tmp;
end loop;
end loop;
return Sqrt (Sum) * Max_A_Val;
end Frobenius_Norm;
------------
-- Invert --
------------
-- Get Inverse of the Matrix:
procedure Get_Inverse
(R : in Matrix;
Q : in Q_Matrix;
Scale : in Col_Vector;
Permute : in Permutation;
Singularity_Cutoff : in Real;
A_inverse_lsq : out Matrix_inv) -- shape is A_transpose
is
Solution_Row_Vector : Row_Vector; -- X
Unit_Col_Vector : Col_Vector := (others => 0.0); -- B
-- We are going to solve for X in A*X = B
Final_Row : Row_Index renames Q.Final_Row;
Final_Col : Col_Index renames Q.Final_Col;
Starting_Row : Row_Index renames Q.Starting_Row;
Starting_Col : Col_Index renames Q.Starting_Col;
begin
A_inverse_lsq := (others => (others => Zero));
--new_line;
--for i in Starting_Row_Col..Max_Row_Col loop
--put(R(i,i));
--end loop;
for i in Starting_Row .. Final_Row loop
if i > Starting_Row then
Unit_Col_Vector(i-1) := 0.0;
end if;
Unit_Col_Vector(i) := 1.0;
-- Make all possible unit Col vectors: (Final_Row-Starting_Row+1) of them
QR_Solve
(X => Solution_Row_Vector,
B => Unit_Col_Vector,
R => R,
Q => Q,
Row_Scalings => Scale,
Col_Permutation => Permute,
Singularity_Cutoff => Singularity_Cutoff);
-- Solve equ. A*Solution_Row_Vector = Unit_Col_Vector (for Solution_Row...).
-- Q contains the Starting_Row, Final_Row, Starting_Col, etc.
for j in Starting_Col .. Final_Col loop
A_inverse_lsq (j,i) := Solution_Row_Vector(j);
end loop;
-- All vectors you multiply by A must be Row_Vectors,
-- So the cols of A_inv are Row_Vectors.
end loop;
end Get_Inverse;
procedure Get_Err_in_Least_Squares_A
(A : in Matrix;
R : in Matrix;
Q : in Q_Matrix;
Scale : in Col_Vector;
Permute : in Permutation;
Singularity_Cutoff : in Real;
A_lsq : out Matrix;
Err_in_Least_Squ_A : out Real;
Condition_Number_of_Least_Squ_A : out Real;
Condition_Number_of_A : out Real)
is
Max_Diag_Val_of_R : constant Real := Abs R(Starting_Col, Starting_Row);
Min_Allowed_Diag_Val_of_R : constant Real :=
Max_Diag_Val_of_R * Singularity_Cutoff;
Min_Diag_Val_of_Least_Squ_R : Real;
Least_Squares_Truncated_Final_Row : Row_Index := Final_Row; -- essential init
Product_Vector, Col_of_R : Col_Vector := (others => Zero);
Row : Row_Index;
Err_Matrix : Matrix := (others => (others => Zero));
Final_Row : Row_Index renames Q.Final_Row;
Final_Col : Col_Index renames Q.Final_Col;
Starting_Row : Row_Index renames Q.Starting_Row;
Starting_Col : Col_Index renames Q.Starting_Col;
begin
-- The Columns of R have been permuted; unpermute before comparison of A with Q*R
-- The Columns of R have been scaled. Before comparison of A with Q*R
-- Must unscale each col of R by multiplying them with 1/ScalePermute(Col).
Row := Starting_Row;
Find_Truncated_Final_Row:
for Col in Starting_Col .. Final_Col loop
Min_Diag_Val_of_Least_Squ_R := Abs R(Row, Col);
if Min_Diag_Val_of_Least_Squ_R < Min_Allowed_Diag_Val_of_R then
Least_Squares_Truncated_Final_Row := Row - 1;
Min_Diag_Val_of_Least_Squ_R := Abs R(Row-1, Col-1);
exit Find_Truncated_Final_Row;
end if;
if Row < Final_Row then Row := Row + 1; end if;
end loop Find_Truncated_Final_Row;
for Col in Starting_Col .. Final_Col loop
Col_of_R := (others => Zero);
for Row in Starting_Row .. Least_Squares_Truncated_Final_Row loop
Col_of_R(Row) := R(Row, Col);
end loop;
Product_Vector := Q_x_Col_Vector (Q, Col_of_R);
for Row in Starting_Row .. Final_Row loop
A_lsq(Row, Permute(Col))
:= Product_Vector(Row) / (Scale(Row) + Min_Real);
Err_Matrix(Row, Col) := A(Row, Permute(Col)) - A_lsq(Row, Permute(Col));
end loop;
end loop;
-- Froebenius norm fractional error = ||Err_Matrix|| / ||A||
Err_in_Least_Squ_A :=
Frobenius_Norm (Err_Matrix) / (Frobenius_Norm (A) + Min_Real);
Condition_Number_of_Least_Squ_A :=
Max_Diag_Val_of_R / (Min_Diag_Val_of_Least_Squ_R + Min_Real);
Condition_Number_of_A :=
Max_Diag_Val_of_R / (Abs R(Final_Row, Final_Col) + Min_Real);
end Get_Err_in_Least_Squares_A;
-----------
-- Pause --
-----------
procedure Pause (s0,s1,s2,s3,s4,s5,s6,s7,s8,s9,s10 : String := "") is
Continue : Character := ' ';
begin
New_Line;
if S0 /= "" then put_line (S0); end if;
if S1 /= "" then put_line (S1); end if;
if S2 /= "" then put_line (S2); end if;
if S3 /= "" then put_line (S3); end if;
if S4 /= "" then put_line (S4); end if;
if S5 /= "" then put_line (S5); end if;
if S6 /= "" then put_line (S6); end if;
if S7 /= "" then put_line (S7); end if;
if S8 /= "" then put_line (S8); end if;
if S9 /= "" then put_line (S9); end if;
if S10 /= "" then put_line (S10); end if;
new_line;
begin
put ("Type a character to continue: ");
get_immediate (Continue);
exception
when others => null;
end;
end Pause;
begin
Pause(
"More on equation solving using the QR decomposition of A. Below we see",
"if we can find useful solutions for x in A*x = b when the matrix A is",
"singular or ill-conditioned. If A is singular then there's a vector b such that",
"no choice of x satisfies A*x - b = 0. If A is not singular but has condition",
"number 10**40, the desired x exists, but it can have length ~10**40. Below",
"all equation solving will use the least squares A described in the previous",
"test. Another way to think of it: A*x = b is solved via R*x = Q'*b. By discarding",
"Q vectors associated with near-zero diagonal elements of R, we are removing the",
"component of b that is effectively in the null space of A, and then solving for x.",
"This doesn't work well unless the decomposition is rank-revealing. That's what we",
"test below on a test suite of (mostly) ill-conditioned or pathological matrices."
);
Pause(
"First pass through the matrix test suite: all equation solving will use a least",
"squares A. Should see: (1) all solutions are good to at least 8 sig. figures,",
"and (2) no matrix was modified by more than 1 part in 10**9 by the least",
"squares process. In most cases results are better than that in both categories."
);
-- we use Singularity_Cutoff => Two**(-30); default is Two**(-38)
for I in 1 .. 2 loop
Singularity_Cutoff_Threshold := Cutoff_Threshold_1;
if I > 1 then
Singularity_Cutoff_Threshold := Zero;
new_line(3);
Pause(
"Now one last pass through the matrix test suite. In this case there will be",
"no least squares modification of A. No Q column vectors are discarded. In",
"many cases the failure of the equation solving is catastrophic."
);
end if;
for Chosen_Matrix in Matrix_id loop
Init_Matrix (A, Chosen_Matrix, Index'First, Index'Last);
R := A; -- cp A to R, then leave A unmolested. R will be overwritten w/ real R
QR_Decompose
(A => R, -- input matrix A, but call it R.
Q => Q,
Row_Scalings => Scale,
Col_Permutation => Permute,
Final_Row => Final_Row,
Final_Col => Final_Col,
Starting_Row => Starting_Row,
Starting_Col => Starting_Col);
Get_Inverse
(R, Q, Scale, Permute, Singularity_Cutoff_Threshold, A_inv_lsq);
Get_Err_in_Least_Squares_A
(A, R, Q, Scale, Permute,
Singularity_Cutoff_Threshold,
A_lsq,
Err_in_Least_Squ_A, Condition_Number_of_Least_Squ_A, Condition_Number_of_A);
-- Least Squares solutions of A*x - b = 0 are solutions of the normal
-- equations (A_transpose*A) * x - A_transpose*b = 0.
-- In practice you don't get A*x - b = 0. You find an A*x - b that is
-- in the null space of A_transpose: A_transpose * (A*x - b) = 0
--
-- next use QR to solve A*x_i = unit_vec_i over of unit vectors,
-- The vectors unit_vec_i form the col vecs of I = Identity, and the
-- vectors x_i form the col vecs of A_Inv. A*A_Inv - Identity /= 0 in
-- general, but we can test A_transpose * (A*x - b) = 0, which will
-- be limited by the condition number of A, and quality of rank revelation.
--
-- Get: A_x_A_inv_minus_I = A*A_Inv - Identity
--
-- Cols of this mat are the desired residuals.
--
-- A_x_A_inv_minus_I is really Row_Index x Row_Index:
for j in Starting_Row .. Final_Row loop
for i in Starting_Row .. Final_Row loop
Sum := +0.0;
for k in Starting_Col .. Final_Col loop
Sum := Sum + Longer_Real(A_lsq(i, k)) * Longer_Real(A_inv_lsq(k,j));
end loop;
if i = j then
A_x_A_inv_minus_I(j, i) := Real (Sum - 1.0);
else
A_x_A_inv_minus_I(j, i) := Real (Sum);
end if;
end loop;
end loop;
-- Residual is: A*x - b, (where the x was obtained by solving A*x = b).
-- Residual /= 0 unless b is in the space spanned by the col vectors of A.
-- Residual won't be 0 in general unless A is full rank (non-singular),
-- (so that its cols span all space). This may be rare!
-- Remember, our least squares A_lsq, obtained by discarding Q vecs is
-- is not actually full rank; A_lsq_inverse * A_lsq /= I. However if you
-- restrict the calculation to the space spanned by the col vectors of A
-- (multiply on the left by A_tr), can use A_tr*(A_lsq_inverse * A_lsq - I)
-- as test of success of equation solving.
-- So we get
--
-- A_tr_x_Residual = A_transpose * (A * A_inv - I)
--
-- result has shape: Col_Index x Col_Index
for j in Starting_Col .. Final_Col loop
for i in Starting_Col .. Final_Col loop
Sum := +0.0;
for k in Starting_Col .. Final_Col loop
Sum := Sum + Longer_Real(A_lsq(k, i)) * Longer_Real(A_x_A_inv_minus_I(k,j));
end loop;
A_tr_x_Residual(j, i) := Real (Sum);
end loop;
end loop;
-- fractional error:
-- = |A_tr*Residual| / |A_tr| = |A_tr*(Ax - b)| / |A_tr|
-- Frobenius_lsq_soln_err
-- := Max_Col_Length (A_tr_x_Residual) / (Max_Row_Length (A_lsq) + Min_Real);
--
Frobenius_lsq_soln_err
:= Frobenius_Norm (A_tr_x_Residual) / (Frobenius_Norm (A_lsq) + Min_Real);
new_line;
put("For matrix A of type "); put(Matrix_id'Image(Chosen_Matrix)); put(":");
new_line;
put(" Approx condition number (lower bound) of original A =");
put(Condition_Number_of_A);
new_line;
put(" Approx condition number (lower bound) of least squ A =");
put(Condition_Number_of_Least_Squ_A);
new_line;
put(" Approx. of max|A'*(A*x-b)| / |A'*b| over unit vectors b =");
put(Frobenius_lsq_soln_err);
new_line(1);
-- actually, best to use a different norm to get max|A'*(A*x-b)| / |A'*b| over b's,
-- (max col length probably) but some other time maybe.
end loop;
end loop;
end;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- S E M _ R E S --
-- --
-- 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 Aspects; use Aspects;
with Atree; use Atree;
with Checks; use Checks;
with Debug; use Debug;
with Debug_A; use Debug_A;
with Einfo; use Einfo;
with Errout; use Errout;
with Expander; use Expander;
with Exp_Ch6; use Exp_Ch6;
with Exp_Ch7; use Exp_Ch7;
with Exp_Disp; use Exp_Disp;
with Exp_Tss; use Exp_Tss;
with Exp_Util; use Exp_Util;
with Freeze; use Freeze;
with Ghost; use Ghost;
with Inline; use Inline;
with Itypes; use Itypes;
with Lib; use Lib;
with Lib.Xref; use Lib.Xref;
with Namet; use Namet;
with Nmake; use Nmake;
with Nlists; use Nlists;
with Opt; use Opt;
with Output; use Output;
with Par_SCO; use Par_SCO;
with Restrict; use Restrict;
with Rident; use Rident;
with Rtsfind; use Rtsfind;
with Sem; use Sem;
with Sem_Aggr; use Sem_Aggr;
with Sem_Attr; use Sem_Attr;
with Sem_Aux; use Sem_Aux;
with Sem_Cat; use Sem_Cat;
with Sem_Ch3; use Sem_Ch3;
with Sem_Ch4; use Sem_Ch4;
with Sem_Ch6; use Sem_Ch6;
with Sem_Ch8; use Sem_Ch8;
with Sem_Ch13; use Sem_Ch13;
with Sem_Dim; use Sem_Dim;
with Sem_Disp; use Sem_Disp;
with Sem_Dist; use Sem_Dist;
with Sem_Elab; use Sem_Elab;
with Sem_Elim; use Sem_Elim;
with Sem_Eval; use Sem_Eval;
with Sem_Intr; use Sem_Intr;
with Sem_Mech; use Sem_Mech;
with Sem_Type; use Sem_Type;
with Sem_Util; use Sem_Util;
with Sem_Warn; use Sem_Warn;
with Sinfo; use Sinfo;
with Sinfo.CN; use Sinfo.CN;
with Snames; use Snames;
with Stand; use Stand;
with Stringt; use Stringt;
with Style; use Style;
with Targparm; use Targparm;
with Tbuild; use Tbuild;
with Uintp; use Uintp;
with Urealp; use Urealp;
package body Sem_Res is
-----------------------
-- Local Subprograms --
-----------------------
-- Second pass (top-down) type checking and overload resolution procedures
-- Typ is the type required by context. These procedures propagate the
-- type information recursively to the descendants of N. If the node is not
-- overloaded, its Etype is established in the first pass. If overloaded,
-- the Resolve routines set the correct type. For arithmetic operators, the
-- Etype is the base type of the context.
-- Note that Resolve_Attribute is separated off in Sem_Attr
procedure Check_Discriminant_Use (N : Node_Id);
-- Enforce the restrictions on the use of discriminants when constraining
-- a component of a discriminated type (record or concurrent type).
procedure Check_For_Visible_Operator (N : Node_Id; T : Entity_Id);
-- Given a node for an operator associated with type T, check that the
-- operator is visible. Operators all of whose operands are universal must
-- be checked for visibility during resolution because their type is not
-- determinable based on their operands.
procedure Check_Fully_Declared_Prefix
(Typ : Entity_Id;
Pref : Node_Id);
-- Check that the type of the prefix of a dereference is not incomplete
function Check_Infinite_Recursion (Call : Node_Id) return Boolean;
-- Given a call node, Call, which is known to occur immediately within the
-- subprogram being called, determines whether it is a detectable case of
-- an infinite recursion, and if so, outputs appropriate messages. Returns
-- True if an infinite recursion is detected, and False otherwise.
procedure Check_No_Direct_Boolean_Operators (N : Node_Id);
-- N is the node for a logical operator. If the operator is predefined, and
-- the root type of the operands is Standard.Boolean, then a check is made
-- for restriction No_Direct_Boolean_Operators. This procedure also handles
-- the style check for Style_Check_Boolean_And_Or.
function Is_Atomic_Ref_With_Address (N : Node_Id) return Boolean;
-- N is either an indexed component or a selected component. This function
-- returns true if the prefix refers to an object that has an address
-- clause (the case in which we may want to issue a warning).
function Is_Definite_Access_Type (E : Entity_Id) return Boolean;
-- Determine whether E is an access type declared by an access declaration,
-- and not an (anonymous) allocator type.
function Is_Predefined_Op (Nam : Entity_Id) return Boolean;
-- Utility to check whether the entity for an operator is a predefined
-- operator, in which case the expression is left as an operator in the
-- tree (else it is rewritten into a call). An instance of an intrinsic
-- conversion operation may be given an operator name, but is not treated
-- like an operator. Note that an operator that is an imported back-end
-- builtin has convention Intrinsic, but is expected to be rewritten into
-- a call, so such an operator is not treated as predefined by this
-- predicate.
procedure Preanalyze_And_Resolve
(N : Node_Id;
T : Entity_Id;
With_Freezing : Boolean);
-- Subsidiary of public versions of Preanalyze_And_Resolve.
procedure Replace_Actual_Discriminants (N : Node_Id; Default : Node_Id);
-- If a default expression in entry call N depends on the discriminants
-- of the task, it must be replaced with a reference to the discriminant
-- of the task being called.
procedure Resolve_Op_Concat_Arg
(N : Node_Id;
Arg : Node_Id;
Typ : Entity_Id;
Is_Comp : Boolean);
-- Internal procedure for Resolve_Op_Concat to resolve one operand of
-- concatenation operator. The operand is either of the array type or of
-- the component type. If the operand is an aggregate, and the component
-- type is composite, this is ambiguous if component type has aggregates.
procedure Resolve_Op_Concat_First (N : Node_Id; Typ : Entity_Id);
-- Does the first part of the work of Resolve_Op_Concat
procedure Resolve_Op_Concat_Rest (N : Node_Id; Typ : Entity_Id);
-- Does the "rest" of the work of Resolve_Op_Concat, after the left operand
-- has been resolved. See Resolve_Op_Concat for details.
procedure Resolve_Allocator (N : Node_Id; Typ : Entity_Id);
procedure Resolve_Arithmetic_Op (N : Node_Id; Typ : Entity_Id);
procedure Resolve_Call (N : Node_Id; Typ : Entity_Id);
procedure Resolve_Case_Expression (N : Node_Id; Typ : Entity_Id);
procedure Resolve_Character_Literal (N : Node_Id; Typ : Entity_Id);
procedure Resolve_Comparison_Op (N : Node_Id; Typ : Entity_Id);
procedure Resolve_Declare_Expression (N : Node_Id; Typ : Entity_Id);
procedure Resolve_Entity_Name (N : Node_Id; Typ : Entity_Id);
procedure Resolve_Equality_Op (N : Node_Id; Typ : Entity_Id);
procedure Resolve_Explicit_Dereference (N : Node_Id; Typ : Entity_Id);
procedure Resolve_Expression_With_Actions (N : Node_Id; Typ : Entity_Id);
procedure Resolve_If_Expression (N : Node_Id; Typ : Entity_Id);
procedure Resolve_Generalized_Indexing (N : Node_Id; Typ : Entity_Id);
procedure Resolve_Indexed_Component (N : Node_Id; Typ : Entity_Id);
procedure Resolve_Integer_Literal (N : Node_Id; Typ : Entity_Id);
procedure Resolve_Logical_Op (N : Node_Id; Typ : Entity_Id);
procedure Resolve_Membership_Op (N : Node_Id; Typ : Entity_Id);
procedure Resolve_Null (N : Node_Id; Typ : Entity_Id);
procedure Resolve_Operator_Symbol (N : Node_Id; Typ : Entity_Id);
procedure Resolve_Op_Concat (N : Node_Id; Typ : Entity_Id);
procedure Resolve_Op_Expon (N : Node_Id; Typ : Entity_Id);
procedure Resolve_Op_Not (N : Node_Id; Typ : Entity_Id);
procedure Resolve_Qualified_Expression (N : Node_Id; Typ : Entity_Id);
procedure Resolve_Raise_Expression (N : Node_Id; Typ : Entity_Id);
procedure Resolve_Range (N : Node_Id; Typ : Entity_Id);
procedure Resolve_Real_Literal (N : Node_Id; Typ : Entity_Id);
procedure Resolve_Reference (N : Node_Id; Typ : Entity_Id);
procedure Resolve_Selected_Component (N : Node_Id; Typ : Entity_Id);
procedure Resolve_Shift (N : Node_Id; Typ : Entity_Id);
procedure Resolve_Short_Circuit (N : Node_Id; Typ : Entity_Id);
procedure Resolve_Slice (N : Node_Id; Typ : Entity_Id);
procedure Resolve_String_Literal (N : Node_Id; Typ : Entity_Id);
procedure Resolve_Target_Name (N : Node_Id; Typ : Entity_Id);
procedure Resolve_Type_Conversion (N : Node_Id; Typ : Entity_Id);
procedure Resolve_Unary_Op (N : Node_Id; Typ : Entity_Id);
procedure Resolve_Unchecked_Expression (N : Node_Id; Typ : Entity_Id);
procedure Resolve_Unchecked_Type_Conversion (N : Node_Id; Typ : Entity_Id);
function Operator_Kind
(Op_Name : Name_Id;
Is_Binary : Boolean) return Node_Kind;
-- Utility to map the name of an operator into the corresponding Node. Used
-- by other node rewriting procedures.
procedure Resolve_Actuals (N : Node_Id; Nam : Entity_Id);
-- Resolve actuals of call, and add default expressions for missing ones.
-- N is the Node_Id for the subprogram call, and Nam is the entity of the
-- called subprogram.
procedure Resolve_Entry_Call (N : Node_Id; Typ : Entity_Id);
-- Called from Resolve_Call, when the prefix denotes an entry or element
-- of entry family. Actuals are resolved as for subprograms, and the node
-- is rebuilt as an entry call. Also called for protected operations. Typ
-- is the context type, which is used when the operation is a protected
-- function with no arguments, and the return value is indexed.
procedure Resolve_Implicit_Dereference (P : Node_Id);
-- Called when P is the prefix of an indexed component, or of a selected
-- component, or of a slice. If P is of an access type, we unconditionally
-- rewrite it as an explicit dereference. This ensures that the expander
-- and the code generator have a fully explicit tree to work with.
procedure Resolve_Intrinsic_Operator (N : Node_Id; Typ : Entity_Id);
-- A call to a user-defined intrinsic operator is rewritten as a call to
-- the corresponding predefined operator, with suitable conversions. Note
-- that this applies only for intrinsic operators that denote predefined
-- operators, not ones that are intrinsic imports of back-end builtins.
procedure Resolve_Intrinsic_Unary_Operator (N : Node_Id; Typ : Entity_Id);
-- Ditto, for arithmetic unary operators
procedure Rewrite_Operator_As_Call (N : Node_Id; Nam : Entity_Id);
-- If an operator node resolves to a call to a user-defined operator,
-- rewrite the node as a function call.
procedure Make_Call_Into_Operator
(N : Node_Id;
Typ : Entity_Id;
Op_Id : Entity_Id);
-- Inverse transformation: if an operator is given in functional notation,
-- then after resolving the node, transform into an operator node, so that
-- operands are resolved properly. Recall that predefined operators do not
-- have a full signature and special resolution rules apply.
procedure Rewrite_Renamed_Operator
(N : Node_Id;
Op : Entity_Id;
Typ : Entity_Id);
-- An operator can rename another, e.g. in an instantiation. In that
-- case, the proper operator node must be constructed and resolved.
procedure Set_String_Literal_Subtype (N : Node_Id; Typ : Entity_Id);
-- The String_Literal_Subtype is built for all strings that are not
-- operands of a static concatenation operation. If the argument is not
-- a N_String_Literal node, then the call has no effect.
procedure Set_Slice_Subtype (N : Node_Id);
-- Build subtype of array type, with the range specified by the slice
procedure Simplify_Type_Conversion (N : Node_Id);
-- Called after N has been resolved and evaluated, but before range checks
-- have been applied. This rewrites the conversion into a simpler form.
function Unique_Fixed_Point_Type (N : Node_Id) return Entity_Id;
-- A universal_fixed expression in an universal context is unambiguous if
-- there is only one applicable fixed point type. Determining whether there
-- is only one requires a search over all visible entities, and happens
-- only in very pathological cases (see 6115-006).
-------------------------
-- Ambiguous_Character --
-------------------------
procedure Ambiguous_Character (C : Node_Id) is
E : Entity_Id;
begin
if Nkind (C) = N_Character_Literal then
Error_Msg_N ("ambiguous character literal", C);
-- First the ones in Standard
Error_Msg_N ("\\possible interpretation: Character!", C);
Error_Msg_N ("\\possible interpretation: Wide_Character!", C);
-- Include Wide_Wide_Character in Ada 2005 mode
if Ada_Version >= Ada_2005 then
Error_Msg_N ("\\possible interpretation: Wide_Wide_Character!", C);
end if;
-- Now any other types that match
E := Current_Entity (C);
while Present (E) loop
Error_Msg_NE ("\\possible interpretation:}!", C, Etype (E));
E := Homonym (E);
end loop;
end if;
end Ambiguous_Character;
-------------------------
-- Analyze_And_Resolve --
-------------------------
procedure Analyze_And_Resolve (N : Node_Id) is
begin
Analyze (N);
Resolve (N);
end Analyze_And_Resolve;
procedure Analyze_And_Resolve (N : Node_Id; Typ : Entity_Id) is
begin
Analyze (N);
Resolve (N, Typ);
end Analyze_And_Resolve;
-- Versions with check(s) suppressed
procedure Analyze_And_Resolve
(N : Node_Id;
Typ : Entity_Id;
Suppress : Check_Id)
is
Scop : constant Entity_Id := Current_Scope;
begin
if Suppress = All_Checks then
declare
Sva : constant Suppress_Array := Scope_Suppress.Suppress;
begin
Scope_Suppress.Suppress := (others => True);
Analyze_And_Resolve (N, Typ);
Scope_Suppress.Suppress := Sva;
end;
else
declare
Svg : constant Boolean := Scope_Suppress.Suppress (Suppress);
begin
Scope_Suppress.Suppress (Suppress) := True;
Analyze_And_Resolve (N, Typ);
Scope_Suppress.Suppress (Suppress) := Svg;
end;
end if;
if Current_Scope /= Scop
and then Scope_Is_Transient
then
-- This can only happen if a transient scope was created for an inner
-- expression, which will be removed upon completion of the analysis
-- of an enclosing construct. The transient scope must have the
-- suppress status of the enclosing environment, not of this Analyze
-- call.
Scope_Stack.Table (Scope_Stack.Last).Save_Scope_Suppress :=
Scope_Suppress;
end if;
end Analyze_And_Resolve;
procedure Analyze_And_Resolve
(N : Node_Id;
Suppress : Check_Id)
is
Scop : constant Entity_Id := Current_Scope;
begin
if Suppress = All_Checks then
declare
Sva : constant Suppress_Array := Scope_Suppress.Suppress;
begin
Scope_Suppress.Suppress := (others => True);
Analyze_And_Resolve (N);
Scope_Suppress.Suppress := Sva;
end;
else
declare
Svg : constant Boolean := Scope_Suppress.Suppress (Suppress);
begin
Scope_Suppress.Suppress (Suppress) := True;
Analyze_And_Resolve (N);
Scope_Suppress.Suppress (Suppress) := Svg;
end;
end if;
if Current_Scope /= Scop and then Scope_Is_Transient then
Scope_Stack.Table (Scope_Stack.Last).Save_Scope_Suppress :=
Scope_Suppress;
end if;
end Analyze_And_Resolve;
----------------------------
-- Check_Discriminant_Use --
----------------------------
procedure Check_Discriminant_Use (N : Node_Id) is
PN : constant Node_Id := Parent (N);
Disc : constant Entity_Id := Entity (N);
P : Node_Id;
D : Node_Id;
begin
-- Any use in a spec-expression is legal
if In_Spec_Expression then
null;
elsif Nkind (PN) = N_Range then
-- Discriminant cannot be used to constrain a scalar type
P := Parent (PN);
if Nkind (P) = N_Range_Constraint
and then Nkind (Parent (P)) = N_Subtype_Indication
and then Nkind (Parent (Parent (P))) = N_Component_Definition
then
Error_Msg_N ("discriminant cannot constrain scalar type", N);
elsif Nkind (P) = N_Index_Or_Discriminant_Constraint then
-- The following check catches the unusual case where a
-- discriminant appears within an index constraint that is part
-- of a larger expression within a constraint on a component,
-- e.g. "C : Int range 1 .. F (new A(1 .. D))". For now we only
-- check case of record components, and note that a similar check
-- should also apply in the case of discriminant constraints
-- below. ???
-- Note that the check for N_Subtype_Declaration below is to
-- detect the valid use of discriminants in the constraints of a
-- subtype declaration when this subtype declaration appears
-- inside the scope of a record type (which is syntactically
-- illegal, but which may be created as part of derived type
-- processing for records). See Sem_Ch3.Build_Derived_Record_Type
-- for more info.
if Ekind (Current_Scope) = E_Record_Type
and then Scope (Disc) = Current_Scope
and then not
(Nkind (Parent (P)) = N_Subtype_Indication
and then
Nkind (Parent (Parent (P))) in N_Component_Definition
| N_Subtype_Declaration
and then Paren_Count (N) = 0)
then
Error_Msg_N
("discriminant must appear alone in component constraint", N);
return;
end if;
-- Detect a common error:
-- type R (D : Positive := 100) is record
-- Name : String (1 .. D);
-- end record;
-- The default value causes an object of type R to be allocated
-- with room for Positive'Last characters. The RM does not mandate
-- the allocation of the maximum size, but that is what GNAT does
-- so we should warn the programmer that there is a problem.
Check_Large : declare
SI : Node_Id;
T : Entity_Id;
TB : Node_Id;
CB : Entity_Id;
function Large_Storage_Type (T : Entity_Id) return Boolean;
-- Return True if type T has a large enough range that any
-- array whose index type covered the whole range of the type
-- would likely raise Storage_Error.
------------------------
-- Large_Storage_Type --
------------------------
function Large_Storage_Type (T : Entity_Id) return Boolean is
begin
-- The type is considered large if its bounds are known at
-- compile time and if it requires at least as many bits as
-- a Positive to store the possible values.
return Compile_Time_Known_Value (Type_Low_Bound (T))
and then Compile_Time_Known_Value (Type_High_Bound (T))
and then
Minimum_Size (T, Biased => True) >=
RM_Size (Standard_Positive);
end Large_Storage_Type;
-- Start of processing for Check_Large
begin
-- Check that the Disc has a large range
if not Large_Storage_Type (Etype (Disc)) then
goto No_Danger;
end if;
-- If the enclosing type is limited, we allocate only the
-- default value, not the maximum, and there is no need for
-- a warning.
if Is_Limited_Type (Scope (Disc)) then
goto No_Danger;
end if;
-- Check that it is the high bound
if N /= High_Bound (PN)
or else No (Discriminant_Default_Value (Disc))
then
goto No_Danger;
end if;
-- Check the array allows a large range at this bound. First
-- find the array
SI := Parent (P);
if Nkind (SI) /= N_Subtype_Indication then
goto No_Danger;
end if;
T := Entity (Subtype_Mark (SI));
if not Is_Array_Type (T) then
goto No_Danger;
end if;
-- Next, find the dimension
TB := First_Index (T);
CB := First (Constraints (P));
while True
and then Present (TB)
and then Present (CB)
and then CB /= PN
loop
Next_Index (TB);
Next (CB);
end loop;
if CB /= PN then
goto No_Danger;
end if;
-- Now, check the dimension has a large range
if not Large_Storage_Type (Etype (TB)) then
goto No_Danger;
end if;
-- Warn about the danger
Error_Msg_N
("??creation of & object may raise Storage_Error!",
Scope (Disc));
<<No_Danger>>
null;
end Check_Large;
end if;
-- Legal case is in index or discriminant constraint
elsif Nkind (PN) in N_Index_Or_Discriminant_Constraint
| N_Discriminant_Association
then
if Paren_Count (N) > 0 then
Error_Msg_N
("discriminant in constraint must appear alone", N);
elsif Nkind (N) = N_Expanded_Name
and then Comes_From_Source (N)
then
Error_Msg_N
("discriminant must appear alone as a direct name", N);
end if;
return;
-- Otherwise, context is an expression. It should not be within (i.e. a
-- subexpression of) a constraint for a component.
else
D := PN;
P := Parent (PN);
while Nkind (P) not in
N_Component_Declaration | N_Subtype_Indication | N_Entry_Declaration
loop
D := P;
P := Parent (P);
exit when No (P);
end loop;
-- If the discriminant is used in an expression that is a bound of a
-- scalar type, an Itype is created and the bounds are attached to
-- its range, not to the original subtype indication. Such use is of
-- course a double fault.
if (Nkind (P) = N_Subtype_Indication
and then Nkind (Parent (P)) in N_Component_Definition
| N_Derived_Type_Definition
and then D = Constraint (P))
-- The constraint itself may be given by a subtype indication,
-- rather than by a more common discrete range.
or else (Nkind (P) = N_Subtype_Indication
and then
Nkind (Parent (P)) = N_Index_Or_Discriminant_Constraint)
or else Nkind (P) = N_Entry_Declaration
or else Nkind (D) = N_Defining_Identifier
then
Error_Msg_N
("discriminant in constraint must appear alone", N);
end if;
end if;
end Check_Discriminant_Use;
--------------------------------
-- Check_For_Visible_Operator --
--------------------------------
procedure Check_For_Visible_Operator (N : Node_Id; T : Entity_Id) is
begin
if Is_Invisible_Operator (N, T) then
Error_Msg_NE -- CODEFIX
("operator for} is not directly visible!", N, First_Subtype (T));
Error_Msg_N -- CODEFIX
("use clause would make operation legal!", N);
end if;
end Check_For_Visible_Operator;
----------------------------------
-- Check_Fully_Declared_Prefix --
----------------------------------
procedure Check_Fully_Declared_Prefix
(Typ : Entity_Id;
Pref : Node_Id)
is
begin
-- Check that the designated type of the prefix of a dereference is
-- not an incomplete type. This cannot be done unconditionally, because
-- dereferences of private types are legal in default expressions. This
-- case is taken care of in Check_Fully_Declared, called below. There
-- are also 2005 cases where it is legal for the prefix to be unfrozen.
-- This consideration also applies to similar checks for allocators,
-- qualified expressions, and type conversions.
-- An additional exception concerns other per-object expressions that
-- are not directly related to component declarations, in particular
-- representation pragmas for tasks. These will be per-object
-- expressions if they depend on discriminants or some global entity.
-- If the task has access discriminants, the designated type may be
-- incomplete at the point the expression is resolved. This resolution
-- takes place within the body of the initialization procedure, where
-- the discriminant is replaced by its discriminal.
if Is_Entity_Name (Pref)
and then Ekind (Entity (Pref)) = E_In_Parameter
then
null;
-- Ada 2005 (AI-326): Tagged incomplete types allowed. The wrong usages
-- are handled by Analyze_Access_Attribute, Analyze_Assignment,
-- Analyze_Object_Renaming, and Freeze_Entity.
elsif Ada_Version >= Ada_2005
and then Is_Entity_Name (Pref)
and then Is_Access_Type (Etype (Pref))
and then Ekind (Directly_Designated_Type (Etype (Pref))) =
E_Incomplete_Type
and then Is_Tagged_Type (Directly_Designated_Type (Etype (Pref)))
then
null;
else
Check_Fully_Declared (Typ, Parent (Pref));
end if;
end Check_Fully_Declared_Prefix;
------------------------------
-- Check_Infinite_Recursion --
------------------------------
function Check_Infinite_Recursion (Call : Node_Id) return Boolean is
function Enclosing_Declaration_Or_Statement (N : Node_Id) return Node_Id;
-- Return the nearest enclosing declaration or statement that houses
-- arbitrary node N.
function Invoked_With_Different_Arguments (N : Node_Id) return Boolean;
-- Determine whether call N invokes the related enclosing subprogram
-- with actuals that differ from the subprogram's formals.
function Is_Conditional_Statement (N : Node_Id) return Boolean;
-- Determine whether arbitrary node N denotes a conditional construct
function Is_Control_Flow_Statement (N : Node_Id) return Boolean;
-- Determine whether arbitrary node N denotes a control flow statement
-- or a construct that may contains such a statement.
function Is_Immediately_Within_Body (N : Node_Id) return Boolean;
-- Determine whether arbitrary node N appears immediately within the
-- statements of an entry or subprogram body.
function Is_Raise_Idiom (N : Node_Id) return Boolean;
-- Determine whether arbitrary node N appears immediately within the
-- body of an entry or subprogram, and is preceded by a single raise
-- statement.
function Is_Raise_Statement (N : Node_Id) return Boolean;
-- Determine whether arbitrary node N denotes a raise statement
function Is_Sole_Statement (N : Node_Id) return Boolean;
-- Determine whether arbitrary node N is the sole source statement in
-- the body of the enclosing subprogram.
function Preceded_By_Control_Flow_Statement (N : Node_Id) return Boolean;
-- Determine whether arbitrary node N is preceded by a control flow
-- statement.
function Within_Conditional_Statement (N : Node_Id) return Boolean;
-- Determine whether arbitrary node N appears within a conditional
-- construct.
----------------------------------------
-- Enclosing_Declaration_Or_Statement --
----------------------------------------
function Enclosing_Declaration_Or_Statement
(N : Node_Id) return Node_Id
is
Par : Node_Id;
begin
Par := N;
while Present (Par) loop
if Is_Declaration (Par) or else Is_Statement (Par) then
return Par;
-- Prevent the search from going too far
elsif Is_Body_Or_Package_Declaration (Par) then
exit;
end if;
Par := Parent (Par);
end loop;
return N;
end Enclosing_Declaration_Or_Statement;
--------------------------------------
-- Invoked_With_Different_Arguments --
--------------------------------------
function Invoked_With_Different_Arguments (N : Node_Id) return Boolean is
Subp : constant Entity_Id := Entity (Name (N));
Actual : Node_Id;
Formal : Entity_Id;
begin
-- Determine whether the formals of the invoked subprogram are not
-- used as actuals in the call.
Actual := First_Actual (Call);
Formal := First_Formal (Subp);
while Present (Actual) and then Present (Formal) loop
-- The current actual does not match the current formal
if not (Is_Entity_Name (Actual)
and then Entity (Actual) = Formal)
then
return True;
end if;
Next_Actual (Actual);
Next_Formal (Formal);
end loop;
return False;
end Invoked_With_Different_Arguments;
------------------------------
-- Is_Conditional_Statement --
------------------------------
function Is_Conditional_Statement (N : Node_Id) return Boolean is
begin
return
Nkind (N) in N_And_Then
| N_Case_Expression
| N_Case_Statement
| N_If_Expression
| N_If_Statement
| N_Or_Else;
end Is_Conditional_Statement;
-------------------------------
-- Is_Control_Flow_Statement --
-------------------------------
function Is_Control_Flow_Statement (N : Node_Id) return Boolean is
begin
-- It is assumed that all statements may affect the control flow in
-- some way. A raise statement may be expanded into a non-statement
-- node.
return Is_Statement (N) or else Is_Raise_Statement (N);
end Is_Control_Flow_Statement;
--------------------------------
-- Is_Immediately_Within_Body --
--------------------------------
function Is_Immediately_Within_Body (N : Node_Id) return Boolean is
HSS : constant Node_Id := Parent (N);
begin
return
Nkind (HSS) = N_Handled_Sequence_Of_Statements
and then Nkind (Parent (HSS)) in N_Entry_Body | N_Subprogram_Body
and then Is_List_Member (N)
and then List_Containing (N) = Statements (HSS);
end Is_Immediately_Within_Body;
--------------------
-- Is_Raise_Idiom --
--------------------
function Is_Raise_Idiom (N : Node_Id) return Boolean is
Raise_Stmt : Node_Id;
Stmt : Node_Id;
begin
if Is_Immediately_Within_Body (N) then
-- Assume that no raise statement has been seen yet
Raise_Stmt := Empty;
-- Examine the statements preceding the input node, skipping
-- internally-generated constructs.
Stmt := Prev (N);
while Present (Stmt) loop
-- Multiple raise statements violate the idiom
if Is_Raise_Statement (Stmt) then
if Present (Raise_Stmt) then
return False;
end if;
Raise_Stmt := Stmt;
elsif Comes_From_Source (Stmt) then
exit;
end if;
Stmt := Prev (Stmt);
end loop;
-- At this point the node must be preceded by a raise statement,
-- and the raise statement has to be the sole statement within
-- the enclosing entry or subprogram body.
return
Present (Raise_Stmt) and then Is_Sole_Statement (Raise_Stmt);
end if;
return False;
end Is_Raise_Idiom;
------------------------
-- Is_Raise_Statement --
------------------------
function Is_Raise_Statement (N : Node_Id) return Boolean is
begin
-- A raise statement may be transfomed into a Raise_xxx_Error node
return
Nkind (N) = N_Raise_Statement
or else Nkind (N) in N_Raise_xxx_Error;
end Is_Raise_Statement;
-----------------------
-- Is_Sole_Statement --
-----------------------
function Is_Sole_Statement (N : Node_Id) return Boolean is
Stmt : Node_Id;
begin
-- The input node appears within the statements of an entry or
-- subprogram body. Examine the statements preceding the node.
if Is_Immediately_Within_Body (N) then
Stmt := Prev (N);
while Present (Stmt) loop
-- The statement is preceded by another statement or a source
-- construct. This indicates that the node does not appear by
-- itself.
if Is_Control_Flow_Statement (Stmt)
or else Comes_From_Source (Stmt)
then
return False;
end if;
Stmt := Prev (Stmt);
end loop;
return True;
end if;
-- The input node is within a construct nested inside the entry or
-- subprogram body.
return False;
end Is_Sole_Statement;
----------------------------------------
-- Preceded_By_Control_Flow_Statement --
----------------------------------------
function Preceded_By_Control_Flow_Statement
(N : Node_Id) return Boolean
is
Stmt : Node_Id;
begin
if Is_List_Member (N) then
Stmt := Prev (N);
-- Examine the statements preceding the input node
while Present (Stmt) loop
if Is_Control_Flow_Statement (Stmt) then
return True;
end if;
Stmt := Prev (Stmt);
end loop;
return False;
end if;
-- Assume that the node is part of some control flow statement
return True;
end Preceded_By_Control_Flow_Statement;
----------------------------------
-- Within_Conditional_Statement --
----------------------------------
function Within_Conditional_Statement (N : Node_Id) return Boolean is
Stmt : Node_Id;
begin
Stmt := Parent (N);
while Present (Stmt) loop
if Is_Conditional_Statement (Stmt) then
return True;
-- Prevent the search from going too far
elsif Is_Body_Or_Package_Declaration (Stmt) then
exit;
end if;
Stmt := Parent (Stmt);
end loop;
return False;
end Within_Conditional_Statement;
-- Local variables
Call_Context : constant Node_Id :=
Enclosing_Declaration_Or_Statement (Call);
-- Start of processing for Check_Infinite_Recursion
begin
-- The call is assumed to be safe when the enclosing subprogram is
-- invoked with actuals other than its formals.
--
-- procedure Proc (F1 : ...; F2 : ...; ...; FN : ...) is
-- begin
-- ...
-- Proc (A1, A2, ..., AN);
-- ...
-- end Proc;
if Invoked_With_Different_Arguments (Call) then
return False;
-- The call is assumed to be safe when the invocation of the enclosing
-- subprogram depends on a conditional statement.
--
-- procedure Proc (F1 : ...; F2 : ...; ...; FN : ...) is
-- begin
-- ...
-- if Some_Condition then
-- Proc (F1, F2, ..., FN);
-- end if;
-- ...
-- end Proc;
elsif Within_Conditional_Statement (Call) then
return False;
-- The context of the call is assumed to be safe when the invocation of
-- the enclosing subprogram is preceded by some control flow statement.
--
-- procedure Proc (F1 : ...; F2 : ...; ...; FN : ...) is
-- begin
-- ...
-- if Some_Condition then
-- ...
-- end if;
-- ...
-- Proc (F1, F2, ..., FN);
-- ...
-- end Proc;
elsif Preceded_By_Control_Flow_Statement (Call_Context) then
return False;
-- Detect an idiom where the context of the call is preceded by a single
-- raise statement.
--
-- procedure Proc (F1 : ...; F2 : ...; ...; FN : ...) is
-- begin
-- raise ...;
-- Proc (F1, F2, ..., FN);
-- end Proc;
elsif Is_Raise_Idiom (Call_Context) then
return False;
end if;
-- At this point it is certain that infinite recursion will take place
-- as long as the call is executed. Detect a case where the context of
-- the call is the sole source statement within the subprogram body.
--
-- procedure Proc (F1 : ...; F2 : ...; ...; FN : ...) is
-- begin
-- Proc (F1, F2, ..., FN);
-- end Proc;
--
-- Install an explicit raise to prevent the infinite recursion.
if Is_Sole_Statement (Call_Context) then
Error_Msg_Warn := SPARK_Mode /= On;
Error_Msg_N ("!infinite recursion<<", Call);
Error_Msg_N ("\!Storage_Error [<<", Call);
Insert_Action (Call,
Make_Raise_Storage_Error (Sloc (Call),
Reason => SE_Infinite_Recursion));
-- Otherwise infinite recursion could take place, considering other flow
-- control constructs such as gotos, exit statements, etc.
else
Error_Msg_Warn := SPARK_Mode /= On;
Error_Msg_N ("!possible infinite recursion<<", Call);
Error_Msg_N ("\!??Storage_Error ]<<", Call);
end if;
return True;
end Check_Infinite_Recursion;
---------------------------------------
-- Check_No_Direct_Boolean_Operators --
---------------------------------------
procedure Check_No_Direct_Boolean_Operators (N : Node_Id) is
begin
if Scope (Entity (N)) = Standard_Standard
and then Root_Type (Etype (Left_Opnd (N))) = Standard_Boolean
then
-- Restriction only applies to original source code
if Comes_From_Source (N) then
Check_Restriction (No_Direct_Boolean_Operators, N);
end if;
end if;
-- Do style check (but skip if in instance, error is on template)
if Style_Check then
if not In_Instance then
Check_Boolean_Operator (N);
end if;
end if;
end Check_No_Direct_Boolean_Operators;
------------------------------
-- Check_Parameterless_Call --
------------------------------
procedure Check_Parameterless_Call (N : Node_Id) is
Nam : Node_Id;
function Prefix_Is_Access_Subp return Boolean;
-- If the prefix is of an access_to_subprogram type, the node must be
-- rewritten as a call. Ditto if the prefix is overloaded and all its
-- interpretations are access to subprograms.
---------------------------
-- Prefix_Is_Access_Subp --
---------------------------
function Prefix_Is_Access_Subp return Boolean is
I : Interp_Index;
It : Interp;
begin
-- If the context is an attribute reference that can apply to
-- functions, this is never a parameterless call (RM 4.1.4(6)).
if Nkind (Parent (N)) = N_Attribute_Reference
and then Attribute_Name (Parent (N))
in Name_Address | Name_Code_Address | Name_Access
then
return False;
end if;
if not Is_Overloaded (N) then
return
Ekind (Etype (N)) = E_Subprogram_Type
and then Base_Type (Etype (Etype (N))) /= Standard_Void_Type;
else
Get_First_Interp (N, I, It);
while Present (It.Typ) loop
if Ekind (It.Typ) /= E_Subprogram_Type
or else Base_Type (Etype (It.Typ)) = Standard_Void_Type
then
return False;
end if;
Get_Next_Interp (I, It);
end loop;
return True;
end if;
end Prefix_Is_Access_Subp;
-- Start of processing for Check_Parameterless_Call
begin
-- Defend against junk stuff if errors already detected
if Total_Errors_Detected /= 0 then
if Nkind (N) in N_Has_Etype and then Etype (N) = Any_Type then
return;
elsif Nkind (N) in N_Has_Chars
and then not Is_Valid_Name (Chars (N))
then
return;
end if;
Require_Entity (N);
end if;
-- If the context expects a value, and the name is a procedure, this is
-- most likely a missing 'Access. Don't try to resolve the parameterless
-- call, error will be caught when the outer call is analyzed.
if Is_Entity_Name (N)
and then Ekind (Entity (N)) = E_Procedure
and then not Is_Overloaded (N)
and then
Nkind (Parent (N)) in N_Parameter_Association
| N_Function_Call
| N_Procedure_Call_Statement
then
return;
end if;
-- Rewrite as call if overloadable entity that is (or could be, in the
-- overloaded case) a function call. If we know for sure that the entity
-- is an enumeration literal, we do not rewrite it.
-- If the entity is the name of an operator, it cannot be a call because
-- operators cannot have default parameters. In this case, this must be
-- a string whose contents coincide with an operator name. Set the kind
-- of the node appropriately.
if (Is_Entity_Name (N)
and then Nkind (N) /= N_Operator_Symbol
and then Is_Overloadable (Entity (N))
and then (Ekind (Entity (N)) /= E_Enumeration_Literal
or else Is_Overloaded (N)))
-- Rewrite as call if it is an explicit dereference of an expression of
-- a subprogram access type, and the subprogram type is not that of a
-- procedure or entry.
or else
(Nkind (N) = N_Explicit_Dereference and then Prefix_Is_Access_Subp)
-- Rewrite as call if it is a selected component which is a function,
-- this is the case of a call to a protected function (which may be
-- overloaded with other protected operations).
or else
(Nkind (N) = N_Selected_Component
and then (Ekind (Entity (Selector_Name (N))) = E_Function
or else
(Ekind (Entity (Selector_Name (N))) in
E_Entry | E_Procedure
and then Is_Overloaded (Selector_Name (N)))))
-- If one of the above three conditions is met, rewrite as call. Apply
-- the rewriting only once.
then
if Nkind (Parent (N)) /= N_Function_Call
or else N /= Name (Parent (N))
then
-- This may be a prefixed call that was not fully analyzed, e.g.
-- an actual in an instance.
if Ada_Version >= Ada_2005
and then Nkind (N) = N_Selected_Component
and then Is_Dispatching_Operation (Entity (Selector_Name (N)))
then
Analyze_Selected_Component (N);
if Nkind (N) /= N_Selected_Component then
return;
end if;
end if;
-- The node is the name of the parameterless call. Preserve its
-- descendants, which may be complex expressions.
Nam := Relocate_Node (N);
-- If overloaded, overload set belongs to new copy
Save_Interps (N, Nam);
-- Change node to parameterless function call (note that the
-- Parameter_Associations associations field is left set to Empty,
-- its normal default value since there are no parameters)
Change_Node (N, N_Function_Call);
Set_Name (N, Nam);
Set_Sloc (N, Sloc (Nam));
Analyze_Call (N);
end if;
elsif Nkind (N) = N_Parameter_Association then
Check_Parameterless_Call (Explicit_Actual_Parameter (N));
elsif Nkind (N) = N_Operator_Symbol then
Change_Operator_Symbol_To_String_Literal (N);
Set_Is_Overloaded (N, False);
Set_Etype (N, Any_String);
end if;
end Check_Parameterless_Call;
--------------------------------
-- Is_Atomic_Ref_With_Address --
--------------------------------
function Is_Atomic_Ref_With_Address (N : Node_Id) return Boolean is
Pref : constant Node_Id := Prefix (N);
begin
if not Is_Entity_Name (Pref) then
return False;
else
declare
Pent : constant Entity_Id := Entity (Pref);
Ptyp : constant Entity_Id := Etype (Pent);
begin
return not Is_Access_Type (Ptyp)
and then (Is_Atomic (Ptyp) or else Is_Atomic (Pent))
and then Present (Address_Clause (Pent));
end;
end if;
end Is_Atomic_Ref_With_Address;
-----------------------------
-- Is_Definite_Access_Type --
-----------------------------
function Is_Definite_Access_Type (E : Entity_Id) return Boolean is
Btyp : constant Entity_Id := Base_Type (E);
begin
return Ekind (Btyp) = E_Access_Type
or else (Ekind (Btyp) = E_Access_Subprogram_Type
and then Comes_From_Source (Btyp));
end Is_Definite_Access_Type;
----------------------
-- Is_Predefined_Op --
----------------------
function Is_Predefined_Op (Nam : Entity_Id) return Boolean is
begin
-- Predefined operators are intrinsic subprograms
if not Is_Intrinsic_Subprogram (Nam) then
return False;
end if;
-- A call to a back-end builtin is never a predefined operator
if Is_Imported (Nam) and then Present (Interface_Name (Nam)) then
return False;
end if;
return not Is_Generic_Instance (Nam)
and then Chars (Nam) in Any_Operator_Name
and then (No (Alias (Nam)) or else Is_Predefined_Op (Alias (Nam)));
end Is_Predefined_Op;
-----------------------------
-- Make_Call_Into_Operator --
-----------------------------
procedure Make_Call_Into_Operator
(N : Node_Id;
Typ : Entity_Id;
Op_Id : Entity_Id)
is
Op_Name : constant Name_Id := Chars (Op_Id);
Act1 : Node_Id := First_Actual (N);
Act2 : Node_Id := Next_Actual (Act1);
Error : Boolean := False;
Func : constant Entity_Id := Entity (Name (N));
Is_Binary : constant Boolean := Present (Act2);
Op_Node : Node_Id;
Opnd_Type : Entity_Id := Empty;
Orig_Type : Entity_Id := Empty;
Pack : Entity_Id;
type Kind_Test is access function (E : Entity_Id) return Boolean;
function Operand_Type_In_Scope (S : Entity_Id) return Boolean;
-- If the operand is not universal, and the operator is given by an
-- expanded name, verify that the operand has an interpretation with a
-- type defined in the given scope of the operator.
function Type_In_P (Test : Kind_Test) return Entity_Id;
-- Find a type of the given class in package Pack that contains the
-- operator.
---------------------------
-- Operand_Type_In_Scope --
---------------------------
function Operand_Type_In_Scope (S : Entity_Id) return Boolean is
Nod : constant Node_Id := Right_Opnd (Op_Node);
I : Interp_Index;
It : Interp;
begin
if not Is_Overloaded (Nod) then
return Scope (Base_Type (Etype (Nod))) = S;
else
Get_First_Interp (Nod, I, It);
while Present (It.Typ) loop
if Scope (Base_Type (It.Typ)) = S then
return True;
end if;
Get_Next_Interp (I, It);
end loop;
return False;
end if;
end Operand_Type_In_Scope;
---------------
-- Type_In_P --
---------------
function Type_In_P (Test : Kind_Test) return Entity_Id is
E : Entity_Id;
function In_Decl return Boolean;
-- Verify that node is not part of the type declaration for the
-- candidate type, which would otherwise be invisible.
-------------
-- In_Decl --
-------------
function In_Decl return Boolean is
Decl_Node : constant Node_Id := Parent (E);
N2 : Node_Id;
begin
N2 := N;
if Etype (E) = Any_Type then
return True;
elsif No (Decl_Node) then
return False;
else
while Present (N2)
and then Nkind (N2) /= N_Compilation_Unit
loop
if N2 = Decl_Node then
return True;
else
N2 := Parent (N2);
end if;
end loop;
return False;
end if;
end In_Decl;
-- Start of processing for Type_In_P
begin
-- If the context type is declared in the prefix package, this is the
-- desired base type.
if Scope (Base_Type (Typ)) = Pack and then Test (Typ) then
return Base_Type (Typ);
else
E := First_Entity (Pack);
while Present (E) loop
if Test (E) and then not In_Decl then
return E;
end if;
Next_Entity (E);
end loop;
return Empty;
end if;
end Type_In_P;
-- Start of processing for Make_Call_Into_Operator
begin
Op_Node := New_Node (Operator_Kind (Op_Name, Is_Binary), Sloc (N));
-- Ensure that the corresponding operator has the same parent as the
-- original call. This guarantees that parent traversals performed by
-- the ABE mechanism succeed.
Set_Parent (Op_Node, Parent (N));
-- Binary operator
if Is_Binary then
Set_Left_Opnd (Op_Node, Relocate_Node (Act1));
Set_Right_Opnd (Op_Node, Relocate_Node (Act2));
Save_Interps (Act1, Left_Opnd (Op_Node));
Save_Interps (Act2, Right_Opnd (Op_Node));
Act1 := Left_Opnd (Op_Node);
Act2 := Right_Opnd (Op_Node);
-- Unary operator
else
Set_Right_Opnd (Op_Node, Relocate_Node (Act1));
Save_Interps (Act1, Right_Opnd (Op_Node));
Act1 := Right_Opnd (Op_Node);
end if;
-- If the operator is denoted by an expanded name, and the prefix is
-- not Standard, but the operator is a predefined one whose scope is
-- Standard, then this is an implicit_operator, inserted as an
-- interpretation by the procedure of the same name. This procedure
-- overestimates the presence of implicit operators, because it does
-- not examine the type of the operands. Verify now that the operand
-- type appears in the given scope. If right operand is universal,
-- check the other operand. In the case of concatenation, either
-- argument can be the component type, so check the type of the result.
-- If both arguments are literals, look for a type of the right kind
-- defined in the given scope. This elaborate nonsense is brought to
-- you courtesy of b33302a. The type itself must be frozen, so we must
-- find the type of the proper class in the given scope.
-- A final wrinkle is the multiplication operator for fixed point types,
-- which is defined in Standard only, and not in the scope of the
-- fixed point type itself.
if Nkind (Name (N)) = N_Expanded_Name then
Pack := Entity (Prefix (Name (N)));
-- If this is a package renaming, get renamed entity, which will be
-- the scope of the operands if operaton is type-correct.
if Present (Renamed_Entity (Pack)) then
Pack := Renamed_Entity (Pack);
end if;
-- If the entity being called is defined in the given package, it is
-- a renaming of a predefined operator, and known to be legal.
if Scope (Entity (Name (N))) = Pack
and then Pack /= Standard_Standard
then
null;
-- Visibility does not need to be checked in an instance: if the
-- operator was not visible in the generic it has been diagnosed
-- already, else there is an implicit copy of it in the instance.
elsif In_Instance then
null;
elsif Op_Name in Name_Op_Multiply | Name_Op_Divide
and then Is_Fixed_Point_Type (Etype (Act1))
and then Is_Fixed_Point_Type (Etype (Act2))
then
if Pack /= Standard_Standard then
Error := True;
end if;
-- Ada 2005 AI-420: Predefined equality on Universal_Access is
-- available.
elsif Ada_Version >= Ada_2005
and then Op_Name in Name_Op_Eq | Name_Op_Ne
and then (Is_Anonymous_Access_Type (Etype (Act1))
or else Is_Anonymous_Access_Type (Etype (Act2)))
then
null;
else
Opnd_Type := Base_Type (Etype (Right_Opnd (Op_Node)));
if Op_Name = Name_Op_Concat then
Opnd_Type := Base_Type (Typ);
elsif (Scope (Opnd_Type) = Standard_Standard
and then Is_Binary)
or else (Nkind (Right_Opnd (Op_Node)) = N_Attribute_Reference
and then Is_Binary
and then not Comes_From_Source (Opnd_Type))
then
Opnd_Type := Base_Type (Etype (Left_Opnd (Op_Node)));
end if;
if Scope (Opnd_Type) = Standard_Standard then
-- Verify that the scope contains a type that corresponds to
-- the given literal. Optimize the case where Pack is Standard.
if Pack /= Standard_Standard then
if Opnd_Type = Universal_Integer then
Orig_Type := Type_In_P (Is_Integer_Type'Access);
elsif Opnd_Type = Universal_Real then
Orig_Type := Type_In_P (Is_Real_Type'Access);
elsif Opnd_Type = Any_String then
Orig_Type := Type_In_P (Is_String_Type'Access);
elsif Opnd_Type = Any_Access then
Orig_Type := Type_In_P (Is_Definite_Access_Type'Access);
elsif Opnd_Type = Any_Composite then
Orig_Type := Type_In_P (Is_Composite_Type'Access);
if Present (Orig_Type) then
if Has_Private_Component (Orig_Type) then
Orig_Type := Empty;
else
Set_Etype (Act1, Orig_Type);
if Is_Binary then
Set_Etype (Act2, Orig_Type);
end if;
end if;
end if;
else
Orig_Type := Empty;
end if;
Error := No (Orig_Type);
end if;
elsif Ekind (Opnd_Type) = E_Allocator_Type
and then No (Type_In_P (Is_Definite_Access_Type'Access))
then
Error := True;
-- If the type is defined elsewhere, and the operator is not
-- defined in the given scope (by a renaming declaration, e.g.)
-- then this is an error as well. If an extension of System is
-- present, and the type may be defined there, Pack must be
-- System itself.
elsif Scope (Opnd_Type) /= Pack
and then Scope (Op_Id) /= Pack
and then (No (System_Aux_Id)
or else Scope (Opnd_Type) /= System_Aux_Id
or else Pack /= Scope (System_Aux_Id))
then
if not Is_Overloaded (Right_Opnd (Op_Node)) then
Error := True;
else
Error := not Operand_Type_In_Scope (Pack);
end if;
elsif Pack = Standard_Standard
and then not Operand_Type_In_Scope (Standard_Standard)
then
Error := True;
end if;
end if;
if Error then
Error_Msg_Node_2 := Pack;
Error_Msg_NE
("& not declared in&", N, Selector_Name (Name (N)));
Set_Etype (N, Any_Type);
return;
-- Detect a mismatch between the context type and the result type
-- in the named package, which is otherwise not detected if the
-- operands are universal. Check is only needed if source entity is
-- an operator, not a function that renames an operator.
elsif Nkind (Parent (N)) /= N_Type_Conversion
and then Ekind (Entity (Name (N))) = E_Operator
and then Is_Numeric_Type (Typ)
and then not Is_Universal_Numeric_Type (Typ)
and then Scope (Base_Type (Typ)) /= Pack
and then not In_Instance
then
if Is_Fixed_Point_Type (Typ)
and then Op_Name in Name_Op_Multiply | Name_Op_Divide
then
-- Already checked above
null;
-- Operator may be defined in an extension of System
elsif Present (System_Aux_Id)
and then Present (Opnd_Type)
and then Scope (Opnd_Type) = System_Aux_Id
then
null;
else
-- Could we use Wrong_Type here??? (this would require setting
-- Etype (N) to the actual type found where Typ was expected).
Error_Msg_NE ("expect }", N, Typ);
end if;
end if;
end if;
Set_Chars (Op_Node, Op_Name);
if not Is_Private_Type (Etype (N)) then
Set_Etype (Op_Node, Base_Type (Etype (N)));
else
Set_Etype (Op_Node, Etype (N));
end if;
-- If this is a call to a function that renames a predefined equality,
-- the renaming declaration provides a type that must be used to
-- resolve the operands. This must be done now because resolution of
-- the equality node will not resolve any remaining ambiguity, and it
-- assumes that the first operand is not overloaded.
if Op_Name in Name_Op_Eq | Name_Op_Ne
and then Ekind (Func) = E_Function
and then Is_Overloaded (Act1)
then
Resolve (Act1, Base_Type (Etype (First_Formal (Func))));
Resolve (Act2, Base_Type (Etype (First_Formal (Func))));
end if;
Set_Entity (Op_Node, Op_Id);
Generate_Reference (Op_Id, N, ' ');
-- Do rewrite setting Comes_From_Source on the result if the original
-- call came from source. Although it is not strictly the case that the
-- operator as such comes from the source, logically it corresponds
-- exactly to the function call in the source, so it should be marked
-- this way (e.g. to make sure that validity checks work fine).
declare
CS : constant Boolean := Comes_From_Source (N);
begin
Rewrite (N, Op_Node);
Set_Comes_From_Source (N, CS);
end;
-- If this is an arithmetic operator and the result type is private,
-- the operands and the result must be wrapped in conversion to
-- expose the underlying numeric type and expand the proper checks,
-- e.g. on division.
if Is_Private_Type (Typ) then
case Nkind (N) is
when N_Op_Add
| N_Op_Divide
| N_Op_Expon
| N_Op_Mod
| N_Op_Multiply
| N_Op_Rem
| N_Op_Subtract
=>
Resolve_Intrinsic_Operator (N, Typ);
when N_Op_Abs
| N_Op_Minus
| N_Op_Plus
=>
Resolve_Intrinsic_Unary_Operator (N, Typ);
when others =>
Resolve (N, Typ);
end case;
else
Resolve (N, Typ);
end if;
end Make_Call_Into_Operator;
-------------------
-- Operator_Kind --
-------------------
function Operator_Kind
(Op_Name : Name_Id;
Is_Binary : Boolean) return Node_Kind
is
Kind : Node_Kind;
begin
-- Use CASE statement or array???
if Is_Binary then
if Op_Name = Name_Op_And then
Kind := N_Op_And;
elsif Op_Name = Name_Op_Or then
Kind := N_Op_Or;
elsif Op_Name = Name_Op_Xor then
Kind := N_Op_Xor;
elsif Op_Name = Name_Op_Eq then
Kind := N_Op_Eq;
elsif Op_Name = Name_Op_Ne then
Kind := N_Op_Ne;
elsif Op_Name = Name_Op_Lt then
Kind := N_Op_Lt;
elsif Op_Name = Name_Op_Le then
Kind := N_Op_Le;
elsif Op_Name = Name_Op_Gt then
Kind := N_Op_Gt;
elsif Op_Name = Name_Op_Ge then
Kind := N_Op_Ge;
elsif Op_Name = Name_Op_Add then
Kind := N_Op_Add;
elsif Op_Name = Name_Op_Subtract then
Kind := N_Op_Subtract;
elsif Op_Name = Name_Op_Concat then
Kind := N_Op_Concat;
elsif Op_Name = Name_Op_Multiply then
Kind := N_Op_Multiply;
elsif Op_Name = Name_Op_Divide then
Kind := N_Op_Divide;
elsif Op_Name = Name_Op_Mod then
Kind := N_Op_Mod;
elsif Op_Name = Name_Op_Rem then
Kind := N_Op_Rem;
elsif Op_Name = Name_Op_Expon then
Kind := N_Op_Expon;
else
raise Program_Error;
end if;
-- Unary operators
else
if Op_Name = Name_Op_Add then
Kind := N_Op_Plus;
elsif Op_Name = Name_Op_Subtract then
Kind := N_Op_Minus;
elsif Op_Name = Name_Op_Abs then
Kind := N_Op_Abs;
elsif Op_Name = Name_Op_Not then
Kind := N_Op_Not;
else
raise Program_Error;
end if;
end if;
return Kind;
end Operator_Kind;
----------------------------
-- Preanalyze_And_Resolve --
----------------------------
procedure Preanalyze_And_Resolve
(N : Node_Id;
T : Entity_Id;
With_Freezing : Boolean)
is
Save_Full_Analysis : constant Boolean := Full_Analysis;
Save_Must_Not_Freeze : constant Boolean := Must_Not_Freeze (N);
Save_Preanalysis_Count : constant Nat :=
Inside_Preanalysis_Without_Freezing;
begin
pragma Assert (Nkind (N) in N_Subexpr);
if not With_Freezing then
Set_Must_Not_Freeze (N);
Inside_Preanalysis_Without_Freezing :=
Inside_Preanalysis_Without_Freezing + 1;
end if;
Full_Analysis := False;
Expander_Mode_Save_And_Set (False);
-- Normally, we suppress all checks for this preanalysis. There is no
-- point in processing them now, since they will be applied properly
-- and in the proper location when the default expressions reanalyzed
-- and reexpanded later on. We will also have more information at that
-- point for possible suppression of individual checks.
-- However, in SPARK mode, most expansion is suppressed, and this
-- later reanalysis and reexpansion may not occur. SPARK mode does
-- require the setting of checking flags for proof purposes, so we
-- do the SPARK preanalysis without suppressing checks.
-- This special handling for SPARK mode is required for example in the
-- case of Ada 2012 constructs such as quantified expressions, which are
-- expanded in two separate steps.
if GNATprove_Mode then
Analyze_And_Resolve (N, T);
else
Analyze_And_Resolve (N, T, Suppress => All_Checks);
end if;
Expander_Mode_Restore;
Full_Analysis := Save_Full_Analysis;
Set_Must_Not_Freeze (N, Save_Must_Not_Freeze);
if not With_Freezing then
Inside_Preanalysis_Without_Freezing :=
Inside_Preanalysis_Without_Freezing - 1;
end if;
pragma Assert
(Inside_Preanalysis_Without_Freezing = Save_Preanalysis_Count);
end Preanalyze_And_Resolve;
----------------------------
-- Preanalyze_And_Resolve --
----------------------------
procedure Preanalyze_And_Resolve (N : Node_Id; T : Entity_Id) is
begin
Preanalyze_And_Resolve (N, T, With_Freezing => False);
end Preanalyze_And_Resolve;
-- Version without context type
procedure Preanalyze_And_Resolve (N : Node_Id) is
Save_Full_Analysis : constant Boolean := Full_Analysis;
begin
Full_Analysis := False;
Expander_Mode_Save_And_Set (False);
Analyze (N);
Resolve (N, Etype (N), Suppress => All_Checks);
Expander_Mode_Restore;
Full_Analysis := Save_Full_Analysis;
end Preanalyze_And_Resolve;
------------------------------------------
-- Preanalyze_With_Freezing_And_Resolve --
------------------------------------------
procedure Preanalyze_With_Freezing_And_Resolve
(N : Node_Id;
T : Entity_Id)
is
begin
Preanalyze_And_Resolve (N, T, With_Freezing => True);
end Preanalyze_With_Freezing_And_Resolve;
----------------------------------
-- Replace_Actual_Discriminants --
----------------------------------
procedure Replace_Actual_Discriminants (N : Node_Id; Default : Node_Id) is
Loc : constant Source_Ptr := Sloc (N);
Tsk : Node_Id := Empty;
function Process_Discr (Nod : Node_Id) return Traverse_Result;
-- Comment needed???
-------------------
-- Process_Discr --
-------------------
function Process_Discr (Nod : Node_Id) return Traverse_Result is
Ent : Entity_Id;
begin
if Nkind (Nod) = N_Identifier then
Ent := Entity (Nod);
if Present (Ent)
and then Ekind (Ent) = E_Discriminant
then
Rewrite (Nod,
Make_Selected_Component (Loc,
Prefix => New_Copy_Tree (Tsk, New_Sloc => Loc),
Selector_Name => Make_Identifier (Loc, Chars (Ent))));
Set_Etype (Nod, Etype (Ent));
end if;
end if;
return OK;
end Process_Discr;
procedure Replace_Discrs is new Traverse_Proc (Process_Discr);
-- Start of processing for Replace_Actual_Discriminants
begin
if Expander_Active then
null;
-- Allow the replacement of concurrent discriminants in GNATprove even
-- though this is a light expansion activity. Note that generic units
-- are not modified.
elsif GNATprove_Mode and not Inside_A_Generic then
null;
else
return;
end if;
if Nkind (Name (N)) = N_Selected_Component then
Tsk := Prefix (Name (N));
elsif Nkind (Name (N)) = N_Indexed_Component then
Tsk := Prefix (Prefix (Name (N)));
end if;
if Present (Tsk) then
Replace_Discrs (Default);
end if;
end Replace_Actual_Discriminants;
-------------
-- Resolve --
-------------
procedure Resolve (N : Node_Id; Typ : Entity_Id) is
Ambiguous : Boolean := False;
Ctx_Type : Entity_Id := Typ;
Expr_Type : Entity_Id := Empty; -- prevent junk warning
Err_Type : Entity_Id := Empty;
Found : Boolean := False;
From_Lib : Boolean;
I : Interp_Index;
I1 : Interp_Index := 0; -- prevent junk warning
It : Interp;
It1 : Interp;
Seen : Entity_Id := Empty; -- prevent junk warning
function Comes_From_Predefined_Lib_Unit (Nod : Node_Id) return Boolean;
-- Determine whether a node comes from a predefined library unit or
-- Standard.
procedure Patch_Up_Value (N : Node_Id; Typ : Entity_Id);
-- Try and fix up a literal so that it matches its expected type. New
-- literals are manufactured if necessary to avoid cascaded errors.
procedure Report_Ambiguous_Argument;
-- Additional diagnostics when an ambiguous call has an ambiguous
-- argument (typically a controlling actual).
procedure Resolution_Failed;
-- Called when attempt at resolving current expression fails
------------------------------------
-- Comes_From_Predefined_Lib_Unit --
-------------------------------------
function Comes_From_Predefined_Lib_Unit (Nod : Node_Id) return Boolean is
begin
return
Sloc (Nod) = Standard_Location or else In_Predefined_Unit (Nod);
end Comes_From_Predefined_Lib_Unit;
--------------------
-- Patch_Up_Value --
--------------------
procedure Patch_Up_Value (N : Node_Id; Typ : Entity_Id) is
begin
if Nkind (N) = N_Integer_Literal and then Is_Real_Type (Typ) then
Rewrite (N,
Make_Real_Literal (Sloc (N),
Realval => UR_From_Uint (Intval (N))));
Set_Etype (N, Universal_Real);
Set_Is_Static_Expression (N);
elsif Nkind (N) = N_Real_Literal and then Is_Integer_Type (Typ) then
Rewrite (N,
Make_Integer_Literal (Sloc (N),
Intval => UR_To_Uint (Realval (N))));
Set_Etype (N, Universal_Integer);
Set_Is_Static_Expression (N);
elsif Nkind (N) = N_String_Literal
and then Is_Character_Type (Typ)
then
Set_Character_Literal_Name (Char_Code (Character'Pos ('A')));
Rewrite (N,
Make_Character_Literal (Sloc (N),
Chars => Name_Find,
Char_Literal_Value =>
UI_From_Int (Character'Pos ('A'))));
Set_Etype (N, Any_Character);
Set_Is_Static_Expression (N);
elsif Nkind (N) /= N_String_Literal and then Is_String_Type (Typ) then
Rewrite (N,
Make_String_Literal (Sloc (N),
Strval => End_String));
elsif Nkind (N) = N_Range then
Patch_Up_Value (Low_Bound (N), Typ);
Patch_Up_Value (High_Bound (N), Typ);
end if;
end Patch_Up_Value;
-------------------------------
-- Report_Ambiguous_Argument --
-------------------------------
procedure Report_Ambiguous_Argument is
Arg : constant Node_Id := First (Parameter_Associations (N));
I : Interp_Index;
It : Interp;
begin
if Nkind (Arg) = N_Function_Call
and then Is_Entity_Name (Name (Arg))
and then Is_Overloaded (Name (Arg))
then
Error_Msg_NE ("ambiguous call to&", Arg, Name (Arg));
-- Could use comments on what is going on here???
Get_First_Interp (Name (Arg), I, It);
while Present (It.Nam) loop
Error_Msg_Sloc := Sloc (It.Nam);
if Nkind (Parent (It.Nam)) = N_Full_Type_Declaration then
Error_Msg_N ("interpretation (inherited) #!", Arg);
else
Error_Msg_N ("interpretation #!", Arg);
end if;
Get_Next_Interp (I, It);
end loop;
end if;
end Report_Ambiguous_Argument;
-----------------------
-- Resolution_Failed --
-----------------------
procedure Resolution_Failed is
begin
Patch_Up_Value (N, Typ);
-- Set the type to the desired one to minimize cascaded errors. Note
-- that this is an approximation and does not work in all cases.
Set_Etype (N, Typ);
Debug_A_Exit ("resolving ", N, " (done, resolution failed)");
Set_Is_Overloaded (N, False);
-- The caller will return without calling the expander, so we need
-- to set the analyzed flag. Note that it is fine to set Analyzed
-- to True even if we are in the middle of a shallow analysis,
-- (see the spec of sem for more details) since this is an error
-- situation anyway, and there is no point in repeating the
-- analysis later (indeed it won't work to repeat it later, since
-- we haven't got a clear resolution of which entity is being
-- referenced.)
Set_Analyzed (N, True);
return;
end Resolution_Failed;
Literal_Aspect_Map :
constant array (N_Numeric_Or_String_Literal) of Aspect_Id :=
(N_Integer_Literal => Aspect_Integer_Literal,
N_Real_Literal => Aspect_Real_Literal,
N_String_Literal => Aspect_String_Literal);
-- Start of processing for Resolve
begin
if N = Error then
return;
end if;
-- Access attribute on remote subprogram cannot be used for a non-remote
-- access-to-subprogram type.
if Nkind (N) = N_Attribute_Reference
and then Attribute_Name (N) in Name_Access
| Name_Unrestricted_Access
| Name_Unchecked_Access
and then Comes_From_Source (N)
and then Is_Entity_Name (Prefix (N))
and then Is_Subprogram (Entity (Prefix (N)))
and then Is_Remote_Call_Interface (Entity (Prefix (N)))
and then not Is_Remote_Access_To_Subprogram_Type (Typ)
then
Error_Msg_N
("prefix must statically denote a non-remote subprogram", N);
end if;
From_Lib := Comes_From_Predefined_Lib_Unit (N);
-- If the context is a Remote_Access_To_Subprogram, access attributes
-- must be resolved with the corresponding fat pointer. There is no need
-- to check for the attribute name since the return type of an
-- attribute is never a remote type.
if Nkind (N) = N_Attribute_Reference
and then Comes_From_Source (N)
and then (Is_Remote_Call_Interface (Typ) or else Is_Remote_Types (Typ))
then
declare
Attr : constant Attribute_Id :=
Get_Attribute_Id (Attribute_Name (N));
Pref : constant Node_Id := Prefix (N);
Decl : Node_Id;
Spec : Node_Id;
Is_Remote : Boolean := True;
begin
-- Check that Typ is a remote access-to-subprogram type
if Is_Remote_Access_To_Subprogram_Type (Typ) then
-- Prefix (N) must statically denote a remote subprogram
-- declared in a package specification.
if Attr = Attribute_Access or else
Attr = Attribute_Unchecked_Access or else
Attr = Attribute_Unrestricted_Access
then
Decl := Unit_Declaration_Node (Entity (Pref));
if Nkind (Decl) = N_Subprogram_Body then
Spec := Corresponding_Spec (Decl);
if Present (Spec) then
Decl := Unit_Declaration_Node (Spec);
end if;
end if;
Spec := Parent (Decl);
if not Is_Entity_Name (Prefix (N))
or else Nkind (Spec) /= N_Package_Specification
or else
not Is_Remote_Call_Interface (Defining_Entity (Spec))
then
Is_Remote := False;
Error_Msg_N
("prefix must statically denote a remote subprogram ",
N);
end if;
-- If we are generating code in distributed mode, perform
-- semantic checks against corresponding remote entities.
if Expander_Active
and then Get_PCS_Name /= Name_No_DSA
then
Check_Subtype_Conformant
(New_Id => Entity (Prefix (N)),
Old_Id => Designated_Type
(Corresponding_Remote_Type (Typ)),
Err_Loc => N);
if Is_Remote then
Process_Remote_AST_Attribute (N, Typ);
end if;
end if;
end if;
end if;
end;
end if;
Debug_A_Entry ("resolving ", N);
if Debug_Flag_V then
Write_Overloads (N);
end if;
if Comes_From_Source (N) then
if Is_Fixed_Point_Type (Typ) then
Check_Restriction (No_Fixed_Point, N);
elsif Is_Floating_Point_Type (Typ)
and then Typ /= Universal_Real
and then Typ /= Any_Real
then
Check_Restriction (No_Floating_Point, N);
end if;
end if;
-- Return if already analyzed
if Analyzed (N) then
Debug_A_Exit ("resolving ", N, " (done, already analyzed)");
Analyze_Dimension (N);
return;
-- Any case of Any_Type as the Etype value means that we had a
-- previous error.
elsif Etype (N) = Any_Type then
Debug_A_Exit ("resolving ", N, " (done, Etype = Any_Type)");
return;
end if;
Check_Parameterless_Call (N);
-- The resolution of an Expression_With_Actions is determined by
-- its Expression, but if the node comes from source it is a
-- Declare_Expression and requires scope management.
if Nkind (N) = N_Expression_With_Actions then
if Comes_From_Source (N)
and then N = Original_Node (N)
then
Resolve_Declare_Expression (N, Typ);
else
Resolve (Expression (N), Typ);
end if;
Found := True;
Expr_Type := Etype (Expression (N));
-- If not overloaded, then we know the type, and all that needs doing
-- is to check that this type is compatible with the context.
elsif not Is_Overloaded (N) then
Found := Covers (Typ, Etype (N));
Expr_Type := Etype (N);
-- In the overloaded case, we must select the interpretation that
-- is compatible with the context (i.e. the type passed to Resolve)
else
-- Loop through possible interpretations
Get_First_Interp (N, I, It);
Interp_Loop : while Present (It.Typ) loop
if Debug_Flag_V then
Write_Str ("Interp: ");
Write_Interp (It);
end if;
-- We are only interested in interpretations that are compatible
-- with the expected type, any other interpretations are ignored.
if not Covers (Typ, It.Typ) then
if Debug_Flag_V then
Write_Str (" interpretation incompatible with context");
Write_Eol;
end if;
else
-- Skip the current interpretation if it is disabled by an
-- abstract operator. This action is performed only when the
-- type against which we are resolving is the same as the
-- type of the interpretation.
if Ada_Version >= Ada_2005
and then It.Typ = Typ
and then Typ /= Universal_Integer
and then Typ /= Universal_Real
and then Present (It.Abstract_Op)
then
if Debug_Flag_V then
Write_Line ("Skip.");
end if;
goto Continue;
end if;
-- First matching interpretation
if not Found then
Found := True;
I1 := I;
Seen := It.Nam;
Expr_Type := It.Typ;
-- Matching interpretation that is not the first, maybe an
-- error, but there are some cases where preference rules are
-- used to choose between the two possibilities. These and
-- some more obscure cases are handled in Disambiguate.
else
-- If the current statement is part of a predefined library
-- unit, then all interpretations which come from user level
-- packages should not be considered. Check previous and
-- current one.
if From_Lib then
if not Comes_From_Predefined_Lib_Unit (It.Nam) then
goto Continue;
elsif not Comes_From_Predefined_Lib_Unit (Seen) then
-- Previous interpretation must be discarded
I1 := I;
Seen := It.Nam;
Expr_Type := It.Typ;
Set_Entity (N, Seen);
goto Continue;
end if;
end if;
-- Otherwise apply further disambiguation steps
Error_Msg_Sloc := Sloc (Seen);
It1 := Disambiguate (N, I1, I, Typ);
-- Disambiguation has succeeded. Skip the remaining
-- interpretations.
if It1 /= No_Interp then
Seen := It1.Nam;
Expr_Type := It1.Typ;
while Present (It.Typ) loop
Get_Next_Interp (I, It);
end loop;
else
-- Before we issue an ambiguity complaint, check for the
-- case of a subprogram call where at least one of the
-- arguments is Any_Type, and if so suppress the message,
-- since it is a cascaded error. This can also happen for
-- a generalized indexing operation.
if Nkind (N) in N_Subprogram_Call
or else (Nkind (N) = N_Indexed_Component
and then Present (Generalized_Indexing (N)))
then
declare
A : Node_Id;
E : Node_Id;
begin
if Nkind (N) = N_Indexed_Component then
Rewrite (N, Generalized_Indexing (N));
end if;
A := First_Actual (N);
while Present (A) loop
E := A;
if Nkind (E) = N_Parameter_Association then
E := Explicit_Actual_Parameter (E);
end if;
if Etype (E) = Any_Type then
if Debug_Flag_V then
Write_Str ("Any_Type in call");
Write_Eol;
end if;
exit Interp_Loop;
end if;
Next_Actual (A);
end loop;
end;
elsif Nkind (N) in N_Binary_Op
and then (Etype (Left_Opnd (N)) = Any_Type
or else Etype (Right_Opnd (N)) = Any_Type)
then
exit Interp_Loop;
elsif Nkind (N) in N_Unary_Op
and then Etype (Right_Opnd (N)) = Any_Type
then
exit Interp_Loop;
end if;
-- Not that special case, so issue message using the flag
-- Ambiguous to control printing of the header message
-- only at the start of an ambiguous set.
if not Ambiguous then
if Nkind (N) = N_Function_Call
and then Nkind (Name (N)) = N_Explicit_Dereference
then
Error_Msg_N
("ambiguous expression (cannot resolve indirect "
& "call)!", N);
else
Error_Msg_NE -- CODEFIX
("ambiguous expression (cannot resolve&)!",
N, It.Nam);
end if;
Ambiguous := True;
if Nkind (Parent (Seen)) = N_Full_Type_Declaration then
Error_Msg_N
("\\possible interpretation (inherited)#!", N);
else
Error_Msg_N -- CODEFIX
("\\possible interpretation#!", N);
end if;
if Nkind (N) in N_Subprogram_Call
and then Present (Parameter_Associations (N))
then
Report_Ambiguous_Argument;
end if;
end if;
Error_Msg_Sloc := Sloc (It.Nam);
-- By default, the error message refers to the candidate
-- interpretation. But if it is a predefined operator, it
-- is implicitly declared at the declaration of the type
-- of the operand. Recover the sloc of that declaration
-- for the error message.
if Nkind (N) in N_Op
and then Scope (It.Nam) = Standard_Standard
and then not Is_Overloaded (Right_Opnd (N))
and then Scope (Base_Type (Etype (Right_Opnd (N)))) /=
Standard_Standard
then
Err_Type := First_Subtype (Etype (Right_Opnd (N)));
if Comes_From_Source (Err_Type)
and then Present (Parent (Err_Type))
then
Error_Msg_Sloc := Sloc (Parent (Err_Type));
end if;
elsif Nkind (N) in N_Binary_Op
and then Scope (It.Nam) = Standard_Standard
and then not Is_Overloaded (Left_Opnd (N))
and then Scope (Base_Type (Etype (Left_Opnd (N)))) /=
Standard_Standard
then
Err_Type := First_Subtype (Etype (Left_Opnd (N)));
if Comes_From_Source (Err_Type)
and then Present (Parent (Err_Type))
then
Error_Msg_Sloc := Sloc (Parent (Err_Type));
end if;
-- If this is an indirect call, use the subprogram_type
-- in the message, to have a meaningful location. Also
-- indicate if this is an inherited operation, created
-- by a type declaration.
elsif Nkind (N) = N_Function_Call
and then Nkind (Name (N)) = N_Explicit_Dereference
and then Is_Type (It.Nam)
then
Err_Type := It.Nam;
Error_Msg_Sloc :=
Sloc (Associated_Node_For_Itype (Err_Type));
else
Err_Type := Empty;
end if;
if Nkind (N) in N_Op
and then Scope (It.Nam) = Standard_Standard
and then Present (Err_Type)
then
-- Special-case the message for universal_fixed
-- operators, which are not declared with the type
-- of the operand, but appear forever in Standard.
if It.Typ = Universal_Fixed
and then Scope (It.Nam) = Standard_Standard
then
Error_Msg_N
("\\possible interpretation as universal_fixed "
& "operation (RM 4.5.5 (19))", N);
else
Error_Msg_N
("\\possible interpretation (predefined)#!", N);
end if;
elsif
Nkind (Parent (It.Nam)) = N_Full_Type_Declaration
then
Error_Msg_N
("\\possible interpretation (inherited)#!", N);
else
Error_Msg_N -- CODEFIX
("\\possible interpretation#!", N);
end if;
end if;
end if;
-- We have a matching interpretation, Expr_Type is the type
-- from this interpretation, and Seen is the entity.
-- For an operator, just set the entity name. The type will be
-- set by the specific operator resolution routine.
if Nkind (N) in N_Op then
Set_Entity (N, Seen);
Generate_Reference (Seen, N);
elsif Nkind (N) in N_Case_Expression
| N_Character_Literal
| N_Delta_Aggregate
| N_If_Expression
then
Set_Etype (N, Expr_Type);
-- AI05-0139-2: Expression is overloaded because type has
-- implicit dereference. The context may be the one that
-- requires implicit dereferemce.
elsif Has_Implicit_Dereference (Expr_Type) then
Set_Etype (N, Expr_Type);
Set_Is_Overloaded (N, False);
-- If the expression is an entity, generate a reference
-- to it, as this is not done for an overloaded construct
-- during analysis.
if Is_Entity_Name (N)
and then Comes_From_Source (N)
then
Generate_Reference (Entity (N), N);
-- Examine access discriminants of entity type,
-- to check whether one of them yields the
-- expected type.
declare
Disc : Entity_Id :=
First_Discriminant (Etype (Entity (N)));
begin
while Present (Disc) loop
exit when Is_Access_Type (Etype (Disc))
and then Has_Implicit_Dereference (Disc)
and then Designated_Type (Etype (Disc)) = Typ;
Next_Discriminant (Disc);
end loop;
if Present (Disc) then
Build_Explicit_Dereference (N, Disc);
end if;
end;
end if;
exit Interp_Loop;
elsif Is_Overloaded (N)
and then Present (It.Nam)
and then Ekind (It.Nam) = E_Discriminant
and then Has_Implicit_Dereference (It.Nam)
then
-- If the node is a general indexing, the dereference is
-- is inserted when resolving the rewritten form, else
-- insert it now.
if Nkind (N) /= N_Indexed_Component
or else No (Generalized_Indexing (N))
then
Build_Explicit_Dereference (N, It.Nam);
end if;
-- For an explicit dereference, attribute reference, range,
-- short-circuit form (which is not an operator node), or call
-- with a name that is an explicit dereference, there is
-- nothing to be done at this point.
elsif Nkind (N) in N_Attribute_Reference
| N_And_Then
| N_Explicit_Dereference
| N_Identifier
| N_Indexed_Component
| N_Or_Else
| N_Range
| N_Selected_Component
| N_Slice
or else Nkind (Name (N)) = N_Explicit_Dereference
then
null;
-- For procedure or function calls, set the type of the name,
-- and also the entity pointer for the prefix.
elsif Nkind (N) in N_Subprogram_Call
and then Is_Entity_Name (Name (N))
then
Set_Etype (Name (N), Expr_Type);
Set_Entity (Name (N), Seen);
Generate_Reference (Seen, Name (N));
elsif Nkind (N) = N_Function_Call
and then Nkind (Name (N)) = N_Selected_Component
then
Set_Etype (Name (N), Expr_Type);
Set_Entity (Selector_Name (Name (N)), Seen);
Generate_Reference (Seen, Selector_Name (Name (N)));
-- For all other cases, just set the type of the Name
else
Set_Etype (Name (N), Expr_Type);
end if;
end if;
<<Continue>>
-- Move to next interpretation
exit Interp_Loop when No (It.Typ);
Get_Next_Interp (I, It);
end loop Interp_Loop;
end if;
-- At this stage Found indicates whether or not an acceptable
-- interpretation exists. If not, then we have an error, except that if
-- the context is Any_Type as a result of some other error, then we
-- suppress the error report.
if not Found then
if Typ /= Any_Type then
-- If type we are looking for is Void, then this is the procedure
-- call case, and the error is simply that what we gave is not a
-- procedure name (we think of procedure calls as expressions with
-- types internally, but the user doesn't think of them this way).
if Typ = Standard_Void_Type then
-- Special case message if function used as a procedure
if Nkind (N) = N_Procedure_Call_Statement
and then Is_Entity_Name (Name (N))
and then Ekind (Entity (Name (N))) = E_Function
then
Error_Msg_NE
("cannot use call to function & as a statement",
Name (N), Entity (Name (N)));
Error_Msg_N
("\return value of a function call cannot be ignored",
Name (N));
-- Otherwise give general message (not clear what cases this
-- covers, but no harm in providing for them).
else
Error_Msg_N ("expect procedure name in procedure call", N);
end if;
Found := True;
-- Otherwise we do have a subexpression with the wrong type
-- Check for the case of an allocator which uses an access type
-- instead of the designated type. This is a common error and we
-- specialize the message, posting an error on the operand of the
-- allocator, complaining that we expected the designated type of
-- the allocator.
elsif Nkind (N) = N_Allocator
and then Is_Access_Type (Typ)
and then Is_Access_Type (Etype (N))
and then Designated_Type (Etype (N)) = Typ
then
Wrong_Type (Expression (N), Designated_Type (Typ));
Found := True;
-- Check for view mismatch on Null in instances, for which the
-- view-swapping mechanism has no identifier.
elsif (In_Instance or else In_Inlined_Body)
and then (Nkind (N) = N_Null)
and then Is_Private_Type (Typ)
and then Is_Access_Type (Full_View (Typ))
then
Resolve (N, Full_View (Typ));
Set_Etype (N, Typ);
return;
-- Check for an aggregate. Sometimes we can get bogus aggregates
-- from misuse of parentheses, and we are about to complain about
-- the aggregate without even looking inside it.
-- Instead, if we have an aggregate of type Any_Composite, then
-- analyze and resolve the component fields, and then only issue
-- another message if we get no errors doing this (otherwise
-- assume that the errors in the aggregate caused the problem).
elsif Nkind (N) = N_Aggregate
and then Etype (N) = Any_Composite
then
if Ada_Version >= Ada_2020
and then Has_Aspect (Typ, Aspect_Aggregate)
then
Resolve_Container_Aggregate (N, Typ);
if Expander_Active then
Expand (N);
end if;
return;
end if;
-- Disable expansion in any case. If there is a type mismatch
-- it may be fatal to try to expand the aggregate. The flag
-- would otherwise be set to false when the error is posted.
Expander_Active := False;
declare
procedure Check_Aggr (Aggr : Node_Id);
-- Check one aggregate, and set Found to True if we have a
-- definite error in any of its elements
procedure Check_Elmt (Aelmt : Node_Id);
-- Check one element of aggregate and set Found to True if
-- we definitely have an error in the element.
----------------
-- Check_Aggr --
----------------
procedure Check_Aggr (Aggr : Node_Id) is
Elmt : Node_Id;
begin
if Present (Expressions (Aggr)) then
Elmt := First (Expressions (Aggr));
while Present (Elmt) loop
Check_Elmt (Elmt);
Next (Elmt);
end loop;
end if;
if Present (Component_Associations (Aggr)) then
Elmt := First (Component_Associations (Aggr));
while Present (Elmt) loop
-- If this is a default-initialized component, then
-- there is nothing to check. The box will be
-- replaced by the appropriate call during late
-- expansion.
if Nkind (Elmt) /= N_Iterated_Component_Association
and then not Box_Present (Elmt)
then
Check_Elmt (Expression (Elmt));
end if;
Next (Elmt);
end loop;
end if;
end Check_Aggr;
----------------
-- Check_Elmt --
----------------
procedure Check_Elmt (Aelmt : Node_Id) is
begin
-- If we have a nested aggregate, go inside it (to
-- attempt a naked analyze-resolve of the aggregate can
-- cause undesirable cascaded errors). Do not resolve
-- expression if it needs a type from context, as for
-- integer * fixed expression.
if Nkind (Aelmt) = N_Aggregate then
Check_Aggr (Aelmt);
else
Analyze (Aelmt);
if not Is_Overloaded (Aelmt)
and then Etype (Aelmt) /= Any_Fixed
then
Resolve (Aelmt);
end if;
if Etype (Aelmt) = Any_Type then
Found := True;
end if;
end if;
end Check_Elmt;
begin
Check_Aggr (N);
end;
end if;
-- Rewrite Literal as a call if the corresponding literal aspect
-- is set.
if Nkind (N) in N_Numeric_Or_String_Literal
and then Present
(Find_Aspect (Typ, Literal_Aspect_Map (Nkind (N))))
then
declare
function Literal_Text (N : Node_Id) return String_Id;
-- Returns the text of a literal node
-------------------
-- Literal_Text --
-------------------
function Literal_Text (N : Node_Id) return String_Id is
begin
pragma Assert (Nkind (N) in N_Numeric_Or_String_Literal);
if Nkind (N) = N_String_Literal then
return Strval (N);
else
return String_From_Numeric_Literal (N);
end if;
end Literal_Text;
Lit_Aspect : constant Aspect_Id :=
Literal_Aspect_Map (Nkind (N));
Callee : constant Entity_Id :=
Entity (Expression (Find_Aspect (Typ, Lit_Aspect)));
Loc : constant Source_Ptr := Sloc (N);
Name : constant Node_Id :=
Make_Identifier (Loc, Chars (Callee));
Param : constant Node_Id :=
Make_String_Literal (Loc, Literal_Text (N));
Params : constant List_Id := New_List (Param);
Call : Node_Id :=
Make_Function_Call
(Sloc => Loc,
Name => Name,
Parameter_Associations => Params);
begin
Set_Entity (Name, Callee);
Set_Is_Overloaded (Name, False);
if Lit_Aspect = Aspect_String_Literal then
Set_Etype (Param, Standard_Wide_Wide_String);
else
Set_Etype (Param, Standard_String);
end if;
Set_Etype (Call, Etype (Callee));
-- Conversion needed in case of an inherited aspect
-- of a derived type.
--
-- ??? Need to do something different here for downward
-- tagged conversion case (which is only possible in the
-- case of a null extension); the current call to
-- Convert_To results in an error message about an illegal
-- downward conversion.
Call := Convert_To (Typ, Call);
Rewrite (N, Call);
end;
Analyze_And_Resolve (N, Typ);
return;
end if;
-- Looks like we have a type error, but check for special case
-- of Address wanted, integer found, with the configuration pragma
-- Allow_Integer_Address active. If we have this case, introduce
-- an unchecked conversion to allow the integer expression to be
-- treated as an Address. The reverse case of integer wanted,
-- Address found, is treated in an analogous manner.
if Address_Integer_Convert_OK (Typ, Etype (N)) then
Rewrite (N, Unchecked_Convert_To (Typ, Relocate_Node (N)));
Analyze_And_Resolve (N, Typ);
return;
-- Under relaxed RM semantics silently replace occurrences of null
-- by System.Null_Address.
elsif Null_To_Null_Address_Convert_OK (N, Typ) then
Replace_Null_By_Null_Address (N);
Analyze_And_Resolve (N, Typ);
return;
end if;
-- That special Allow_Integer_Address check did not apply, so we
-- have a real type error. If an error message was issued already,
-- Found got reset to True, so if it's still False, issue standard
-- Wrong_Type message.
if not Found then
if Is_Overloaded (N) and then Nkind (N) = N_Function_Call then
declare
Subp_Name : Node_Id;
begin
if Is_Entity_Name (Name (N)) then
Subp_Name := Name (N);
elsif Nkind (Name (N)) = N_Selected_Component then
-- Protected operation: retrieve operation name
Subp_Name := Selector_Name (Name (N));
else
raise Program_Error;
end if;
Error_Msg_Node_2 := Typ;
Error_Msg_NE
("no visible interpretation of& matches expected type&",
N, Subp_Name);
end;
if All_Errors_Mode then
declare
Index : Interp_Index;
It : Interp;
begin
Error_Msg_N ("\\possible interpretations:", N);
Get_First_Interp (Name (N), Index, It);
while Present (It.Nam) loop
Error_Msg_Sloc := Sloc (It.Nam);
Error_Msg_Node_2 := It.Nam;
Error_Msg_NE
("\\ type& for & declared#", N, It.Typ);
Get_Next_Interp (Index, It);
end loop;
end;
else
Error_Msg_N ("\use -gnatf for details", N);
end if;
else
Wrong_Type (N, Typ);
end if;
end if;
end if;
Resolution_Failed;
return;
-- Test if we have more than one interpretation for the context
elsif Ambiguous then
Resolution_Failed;
return;
-- Only one interpretation
else
-- In Ada 2005, if we have something like "X : T := 2 + 2;", where
-- the "+" on T is abstract, and the operands are of universal type,
-- the above code will have (incorrectly) resolved the "+" to the
-- universal one in Standard. Therefore check for this case and give
-- an error. We can't do this earlier, because it would cause legal
-- cases to get errors (when some other type has an abstract "+").
if Ada_Version >= Ada_2005
and then Nkind (N) in N_Op
and then Is_Overloaded (N)
and then Is_Universal_Numeric_Type (Etype (Entity (N)))
then
Get_First_Interp (N, I, It);
while Present (It.Typ) loop
if Present (It.Abstract_Op) and then
Etype (It.Abstract_Op) = Typ
then
Error_Msg_NE
("cannot call abstract subprogram &!", N, It.Abstract_Op);
return;
end if;
Get_Next_Interp (I, It);
end loop;
end if;
-- Here we have an acceptable interpretation for the context
-- Propagate type information and normalize tree for various
-- predefined operations. If the context only imposes a class of
-- types, rather than a specific type, propagate the actual type
-- downward.
if Typ = Any_Integer or else
Typ = Any_Boolean or else
Typ = Any_Modular or else
Typ = Any_Real or else
Typ = Any_Discrete
then
Ctx_Type := Expr_Type;
-- Any_Fixed is legal in a real context only if a specific fixed-
-- point type is imposed. If Norman Cohen can be confused by this,
-- it deserves a separate message.
if Typ = Any_Real
and then Expr_Type = Any_Fixed
then
Error_Msg_N ("illegal context for mixed mode operation", N);
Set_Etype (N, Universal_Real);
Ctx_Type := Universal_Real;
end if;
end if;
-- A user-defined operator is transformed into a function call at
-- this point, so that further processing knows that operators are
-- really operators (i.e. are predefined operators). User-defined
-- operators that are intrinsic are just renamings of the predefined
-- ones, and need not be turned into calls either, but if they rename
-- a different operator, we must transform the node accordingly.
-- Instantiations of Unchecked_Conversion are intrinsic but are
-- treated as functions, even if given an operator designator.
if Nkind (N) in N_Op
and then Present (Entity (N))
and then Ekind (Entity (N)) /= E_Operator
then
if not Is_Predefined_Op (Entity (N)) then
Rewrite_Operator_As_Call (N, Entity (N));
elsif Present (Alias (Entity (N)))
and then
Nkind (Parent (Parent (Entity (N)))) =
N_Subprogram_Renaming_Declaration
then
Rewrite_Renamed_Operator (N, Alias (Entity (N)), Typ);
-- If the node is rewritten, it will be fully resolved in
-- Rewrite_Renamed_Operator.
if Analyzed (N) then
return;
end if;
end if;
end if;
case N_Subexpr'(Nkind (N)) is
when N_Aggregate =>
Resolve_Aggregate (N, Ctx_Type);
when N_Allocator =>
Resolve_Allocator (N, Ctx_Type);
when N_Short_Circuit =>
Resolve_Short_Circuit (N, Ctx_Type);
when N_Attribute_Reference =>
Resolve_Attribute (N, Ctx_Type);
when N_Case_Expression =>
Resolve_Case_Expression (N, Ctx_Type);
when N_Character_Literal =>
Resolve_Character_Literal (N, Ctx_Type);
when N_Delta_Aggregate =>
Resolve_Delta_Aggregate (N, Ctx_Type);
when N_Expanded_Name =>
Resolve_Entity_Name (N, Ctx_Type);
when N_Explicit_Dereference =>
Resolve_Explicit_Dereference (N, Ctx_Type);
when N_Expression_With_Actions =>
Resolve_Expression_With_Actions (N, Ctx_Type);
when N_Extension_Aggregate =>
Resolve_Extension_Aggregate (N, Ctx_Type);
when N_Function_Call =>
Resolve_Call (N, Ctx_Type);
when N_Identifier =>
Resolve_Entity_Name (N, Ctx_Type);
when N_If_Expression =>
Resolve_If_Expression (N, Ctx_Type);
when N_Indexed_Component =>
Resolve_Indexed_Component (N, Ctx_Type);
when N_Integer_Literal =>
Resolve_Integer_Literal (N, Ctx_Type);
when N_Membership_Test =>
Resolve_Membership_Op (N, Ctx_Type);
when N_Null =>
Resolve_Null (N, Ctx_Type);
when N_Op_And
| N_Op_Or
| N_Op_Xor
=>
Resolve_Logical_Op (N, Ctx_Type);
when N_Op_Eq
| N_Op_Ne
=>
Resolve_Equality_Op (N, Ctx_Type);
when N_Op_Ge
| N_Op_Gt
| N_Op_Le
| N_Op_Lt
=>
Resolve_Comparison_Op (N, Ctx_Type);
when N_Op_Not =>
Resolve_Op_Not (N, Ctx_Type);
when N_Op_Add
| N_Op_Divide
| N_Op_Mod
| N_Op_Multiply
| N_Op_Rem
| N_Op_Subtract
=>
Resolve_Arithmetic_Op (N, Ctx_Type);
when N_Op_Concat =>
Resolve_Op_Concat (N, Ctx_Type);
when N_Op_Expon =>
Resolve_Op_Expon (N, Ctx_Type);
when N_Op_Abs
| N_Op_Minus
| N_Op_Plus
=>
Resolve_Unary_Op (N, Ctx_Type);
when N_Op_Shift =>
Resolve_Shift (N, Ctx_Type);
when N_Procedure_Call_Statement =>
Resolve_Call (N, Ctx_Type);
when N_Operator_Symbol =>
Resolve_Operator_Symbol (N, Ctx_Type);
when N_Qualified_Expression =>
Resolve_Qualified_Expression (N, Ctx_Type);
-- Why is the following null, needs a comment ???
when N_Quantified_Expression =>
null;
when N_Raise_Expression =>
Resolve_Raise_Expression (N, Ctx_Type);
when N_Raise_xxx_Error =>
Set_Etype (N, Ctx_Type);
when N_Range =>
Resolve_Range (N, Ctx_Type);
when N_Real_Literal =>
Resolve_Real_Literal (N, Ctx_Type);
when N_Reference =>
Resolve_Reference (N, Ctx_Type);
when N_Selected_Component =>
Resolve_Selected_Component (N, Ctx_Type);
when N_Slice =>
Resolve_Slice (N, Ctx_Type);
when N_String_Literal =>
Resolve_String_Literal (N, Ctx_Type);
when N_Target_Name =>
Resolve_Target_Name (N, Ctx_Type);
when N_Type_Conversion =>
Resolve_Type_Conversion (N, Ctx_Type);
when N_Unchecked_Expression =>
Resolve_Unchecked_Expression (N, Ctx_Type);
when N_Unchecked_Type_Conversion =>
Resolve_Unchecked_Type_Conversion (N, Ctx_Type);
end case;
-- Mark relevant use-type and use-package clauses as effective using
-- the original node because constant folding may have occured and
-- removed references that need to be examined.
if Nkind (Original_Node (N)) in N_Op then
Mark_Use_Clauses (Original_Node (N));
end if;
-- Ada 2012 (AI05-0149): Apply an (implicit) conversion to an
-- expression of an anonymous access type that occurs in the context
-- of a named general access type, except when the expression is that
-- of a membership test. This ensures proper legality checking in
-- terms of allowed conversions (expressions that would be illegal to
-- convert implicitly are allowed in membership tests).
if Ada_Version >= Ada_2012
and then Ekind (Base_Type (Ctx_Type)) = E_General_Access_Type
and then Ekind (Etype (N)) = E_Anonymous_Access_Type
and then Nkind (Parent (N)) not in N_Membership_Test
then
Rewrite (N, Convert_To (Ctx_Type, Relocate_Node (N)));
Analyze_And_Resolve (N, Ctx_Type);
end if;
-- If the subexpression was replaced by a non-subexpression, then
-- all we do is to expand it. The only legitimate case we know of
-- is converting procedure call statement to entry call statements,
-- but there may be others, so we are making this test general.
if Nkind (N) not in N_Subexpr then
Debug_A_Exit ("resolving ", N, " (done)");
Expand (N);
return;
end if;
-- The expression is definitely NOT overloaded at this point, so
-- we reset the Is_Overloaded flag to avoid any confusion when
-- reanalyzing the node.
Set_Is_Overloaded (N, False);
-- Freeze expression type, entity if it is a name, and designated
-- type if it is an allocator (RM 13.14(10,11,13)).
-- Now that the resolution of the type of the node is complete, and
-- we did not detect an error, we can expand this node. We skip the
-- expand call if we are in a default expression, see section
-- "Handling of Default Expressions" in Sem spec.
Debug_A_Exit ("resolving ", N, " (done)");
-- We unconditionally freeze the expression, even if we are in
-- default expression mode (the Freeze_Expression routine tests this
-- flag and only freezes static types if it is set).
-- Ada 2012 (AI05-177): The declaration of an expression function
-- does not cause freezing, but we never reach here in that case.
-- Here we are resolving the corresponding expanded body, so we do
-- need to perform normal freezing.
-- As elsewhere we do not emit freeze node within a generic. We make
-- an exception for entities that are expressions, only to detect
-- misuses of deferred constants and preserve the output of various
-- tests.
if not Inside_A_Generic or else Is_Entity_Name (N) then
Freeze_Expression (N);
end if;
-- Now we can do the expansion
Expand (N);
end if;
end Resolve;
-------------
-- Resolve --
-------------
-- Version with check(s) suppressed
procedure Resolve (N : Node_Id; Typ : Entity_Id; Suppress : Check_Id) is
begin
if Suppress = All_Checks then
declare
Sva : constant Suppress_Array := Scope_Suppress.Suppress;
begin
Scope_Suppress.Suppress := (others => True);
Resolve (N, Typ);
Scope_Suppress.Suppress := Sva;
end;
else
declare
Svg : constant Boolean := Scope_Suppress.Suppress (Suppress);
begin
Scope_Suppress.Suppress (Suppress) := True;
Resolve (N, Typ);
Scope_Suppress.Suppress (Suppress) := Svg;
end;
end if;
end Resolve;
-------------
-- Resolve --
-------------
-- Version with implicit type
procedure Resolve (N : Node_Id) is
begin
Resolve (N, Etype (N));
end Resolve;
---------------------
-- Resolve_Actuals --
---------------------
procedure Resolve_Actuals (N : Node_Id; Nam : Entity_Id) is
Loc : constant Source_Ptr := Sloc (N);
A : Node_Id;
A_Id : Entity_Id;
A_Typ : Entity_Id := Empty; -- init to avoid warning
F : Entity_Id;
F_Typ : Entity_Id;
Prev : Node_Id := Empty;
Orig_A : Node_Id;
Real_F : Entity_Id := Empty; -- init to avoid warning
Real_Subp : Entity_Id;
-- If the subprogram being called is an inherited operation for
-- a formal derived type in an instance, Real_Subp is the subprogram
-- that will be called. It may have different formal names than the
-- operation of the formal in the generic, so after actual is resolved
-- the name of the actual in a named association must carry the name
-- of the actual of the subprogram being called.
procedure Check_Aliased_Parameter;
-- Check rules on aliased parameters and related accessibility rules
-- in (RM 3.10.2 (10.2-10.4)).
procedure Check_Argument_Order;
-- Performs a check for the case where the actuals are all simple
-- identifiers that correspond to the formal names, but in the wrong
-- order, which is considered suspicious and cause for a warning.
procedure Check_Prefixed_Call;
-- If the original node is an overloaded call in prefix notation,
-- insert an 'Access or a dereference as needed over the first actual.
-- Try_Object_Operation has already verified that there is a valid
-- interpretation, but the form of the actual can only be determined
-- once the primitive operation is identified.
procedure Flag_Effectively_Volatile_Objects (Expr : Node_Id);
-- Emit an error concerning the illegal usage of an effectively volatile
-- object for reading in interfering context (SPARK RM 7.1.3(10)).
procedure Insert_Default;
-- If the actual is missing in a call, insert in the actuals list
-- an instance of the default expression. The insertion is always
-- a named association.
function Same_Ancestor (T1, T2 : Entity_Id) return Boolean;
-- Check whether T1 and T2, or their full views, are derived from a
-- common type. Used to enforce the restrictions on array conversions
-- of AI95-00246.
function Static_Concatenation (N : Node_Id) return Boolean;
-- Predicate to determine whether an actual that is a concatenation
-- will be evaluated statically and does not need a transient scope.
-- This must be determined before the actual is resolved and expanded
-- because if needed the transient scope must be introduced earlier.
-----------------------------
-- Check_Aliased_Parameter --
-----------------------------
procedure Check_Aliased_Parameter is
Nominal_Subt : Entity_Id;
begin
if Is_Aliased (F) then
if Is_Tagged_Type (A_Typ) then
null;
elsif Is_Aliased_View (A) then
if Is_Constr_Subt_For_U_Nominal (A_Typ) then
Nominal_Subt := Base_Type (A_Typ);
else
Nominal_Subt := A_Typ;
end if;
if Subtypes_Statically_Match (F_Typ, Nominal_Subt) then
null;
-- In a generic body assume the worst for generic formals:
-- they can have a constrained partial view (AI05-041).
elsif Has_Discriminants (F_Typ)
and then not Is_Constrained (F_Typ)
and then not Has_Constrained_Partial_View (F_Typ)
and then not Is_Generic_Type (F_Typ)
then
null;
else
Error_Msg_NE ("untagged actual does not match "
& "aliased formal&", A, F);
end if;
else
Error_Msg_NE ("actual for aliased formal& must be "
& "aliased object", A, F);
end if;
if Ekind (Nam) = E_Procedure then
null;
elsif Ekind (Etype (Nam)) = E_Anonymous_Access_Type then
if Nkind (Parent (N)) = N_Type_Conversion
and then Type_Access_Level (Etype (Parent (N))) <
Object_Access_Level (A)
then
Error_Msg_N ("aliased actual has wrong accessibility", A);
end if;
elsif Nkind (Parent (N)) = N_Qualified_Expression
and then Nkind (Parent (Parent (N))) = N_Allocator
and then Type_Access_Level (Etype (Parent (Parent (N)))) <
Object_Access_Level (A)
then
Error_Msg_N
("aliased actual in allocator has wrong accessibility", A);
end if;
end if;
end Check_Aliased_Parameter;
--------------------------
-- Check_Argument_Order --
--------------------------
procedure Check_Argument_Order is
begin
-- Nothing to do if no parameters, or original node is neither a
-- function call nor a procedure call statement (happens in the
-- operator-transformed-to-function call case), or the call is to an
-- operator symbol (which is usually in infix form), or the call does
-- not come from source, or this warning is off.
if not Warn_On_Parameter_Order
or else No (Parameter_Associations (N))
or else Nkind (Original_Node (N)) not in N_Subprogram_Call
or else (Nkind (Name (N)) = N_Identifier
and then Present (Entity (Name (N)))
and then Nkind (Entity (Name (N))) =
N_Defining_Operator_Symbol)
or else not Comes_From_Source (N)
then
return;
end if;
declare
Nargs : constant Nat := List_Length (Parameter_Associations (N));
begin
-- Nothing to do if only one parameter
if Nargs < 2 then
return;
end if;
-- Here if at least two arguments
declare
Actuals : array (1 .. Nargs) of Node_Id;
Actual : Node_Id;
Formal : Node_Id;
Wrong_Order : Boolean := False;
-- Set True if an out of order case is found
begin
-- Collect identifier names of actuals, fail if any actual is
-- not a simple identifier, and record max length of name.
Actual := First (Parameter_Associations (N));
for J in Actuals'Range loop
if Nkind (Actual) /= N_Identifier then
return;
else
Actuals (J) := Actual;
Next (Actual);
end if;
end loop;
-- If we got this far, all actuals are identifiers and the list
-- of their names is stored in the Actuals array.
Formal := First_Formal (Nam);
for J in Actuals'Range loop
-- If we ran out of formals, that's odd, probably an error
-- which will be detected elsewhere, but abandon the search.
if No (Formal) then
return;
end if;
-- If name matches and is in order OK
if Chars (Formal) = Chars (Actuals (J)) then
null;
else
-- If no match, see if it is elsewhere in list and if so
-- flag potential wrong order if type is compatible.
for K in Actuals'Range loop
if Chars (Formal) = Chars (Actuals (K))
and then
Has_Compatible_Type (Actuals (K), Etype (Formal))
then
Wrong_Order := True;
goto Continue;
end if;
end loop;
-- No match
return;
end if;
<<Continue>> Next_Formal (Formal);
end loop;
-- If Formals left over, also probably an error, skip warning
if Present (Formal) then
return;
end if;
-- Here we give the warning if something was out of order
if Wrong_Order then
Error_Msg_N
("?P?actuals for this call may be in wrong order", N);
end if;
end;
end;
end Check_Argument_Order;
-------------------------
-- Check_Prefixed_Call --
-------------------------
procedure Check_Prefixed_Call is
Act : constant Node_Id := First_Actual (N);
A_Type : constant Entity_Id := Etype (Act);
F_Type : constant Entity_Id := Etype (First_Formal (Nam));
Orig : constant Node_Id := Original_Node (N);
New_A : Node_Id;
begin
-- Check whether the call is a prefixed call, with or without
-- additional actuals.
if Nkind (Orig) = N_Selected_Component
or else
(Nkind (Orig) = N_Indexed_Component
and then Nkind (Prefix (Orig)) = N_Selected_Component
and then Is_Entity_Name (Prefix (Prefix (Orig)))
and then Is_Entity_Name (Act)
and then Chars (Act) = Chars (Prefix (Prefix (Orig))))
then
if Is_Access_Type (A_Type)
and then not Is_Access_Type (F_Type)
then
-- Introduce dereference on object in prefix
New_A :=
Make_Explicit_Dereference (Sloc (Act),
Prefix => Relocate_Node (Act));
Rewrite (Act, New_A);
Analyze (Act);
elsif Is_Access_Type (F_Type)
and then not Is_Access_Type (A_Type)
then
-- Introduce an implicit 'Access in prefix
if not Is_Aliased_View (Act) then
Error_Msg_NE
("object in prefixed call to& must be aliased "
& "(RM 4.1.3 (13 1/2))",
Prefix (Act), Nam);
end if;
Rewrite (Act,
Make_Attribute_Reference (Loc,
Attribute_Name => Name_Access,
Prefix => Relocate_Node (Act)));
end if;
Analyze (Act);
end if;
end Check_Prefixed_Call;
---------------------------------------
-- Flag_Effectively_Volatile_Objects --
---------------------------------------
procedure Flag_Effectively_Volatile_Objects (Expr : Node_Id) is
function Flag_Object (N : Node_Id) return Traverse_Result;
-- Determine whether arbitrary node N denotes an effectively volatile
-- object for reading and if it does, emit an error.
-----------------
-- Flag_Object --
-----------------
function Flag_Object (N : Node_Id) return Traverse_Result is
Id : Entity_Id;
begin
-- Do not consider nested function calls because they have already
-- been processed during their own resolution.
if Nkind (N) = N_Function_Call then
return Skip;
elsif Is_Entity_Name (N) and then Present (Entity (N)) then
Id := Entity (N);
if Is_Object (Id)
and then Is_Effectively_Volatile_For_Reading (Id)
then
Error_Msg_N
("volatile object cannot appear in this context (SPARK "
& "RM 7.1.3(10))", N);
return Skip;
end if;
end if;
return OK;
end Flag_Object;
procedure Flag_Objects is new Traverse_Proc (Flag_Object);
-- Start of processing for Flag_Effectively_Volatile_Objects
begin
Flag_Objects (Expr);
end Flag_Effectively_Volatile_Objects;
--------------------
-- Insert_Default --
--------------------
procedure Insert_Default is
Actval : Node_Id;
Assoc : Node_Id;
begin
-- Missing argument in call, nothing to insert
if No (Default_Value (F)) then
return;
else
-- Note that we do a full New_Copy_Tree, so that any associated
-- Itypes are properly copied. This may not be needed any more,
-- but it does no harm as a safety measure. Defaults of a generic
-- formal may be out of bounds of the corresponding actual (see
-- cc1311b) and an additional check may be required.
Actval :=
New_Copy_Tree
(Default_Value (F),
New_Scope => Current_Scope,
New_Sloc => Loc);
-- Propagate dimension information, if any.
Copy_Dimensions (Default_Value (F), Actval);
if Is_Concurrent_Type (Scope (Nam))
and then Has_Discriminants (Scope (Nam))
then
Replace_Actual_Discriminants (N, Actval);
end if;
if Is_Overloadable (Nam)
and then Present (Alias (Nam))
then
if Base_Type (Etype (F)) /= Base_Type (Etype (Actval))
and then not Is_Tagged_Type (Etype (F))
then
-- If default is a real literal, do not introduce a
-- conversion whose effect may depend on the run-time
-- size of universal real.
if Nkind (Actval) = N_Real_Literal then
Set_Etype (Actval, Base_Type (Etype (F)));
else
Actval := Unchecked_Convert_To (Etype (F), Actval);
end if;
end if;
if Is_Scalar_Type (Etype (F)) then
Enable_Range_Check (Actval);
end if;
Set_Parent (Actval, N);
-- Resolve aggregates with their base type, to avoid scope
-- anomalies: the subtype was first built in the subprogram
-- declaration, and the current call may be nested.
if Nkind (Actval) = N_Aggregate then
Analyze_And_Resolve (Actval, Etype (F));
else
Analyze_And_Resolve (Actval, Etype (Actval));
end if;
else
Set_Parent (Actval, N);
-- See note above concerning aggregates
if Nkind (Actval) = N_Aggregate
and then Has_Discriminants (Etype (Actval))
then
Analyze_And_Resolve (Actval, Base_Type (Etype (Actval)));
-- Resolve entities with their own type, which may differ from
-- the type of a reference in a generic context (the view
-- swapping mechanism did not anticipate the re-analysis of
-- default values in calls).
elsif Is_Entity_Name (Actval) then
Analyze_And_Resolve (Actval, Etype (Entity (Actval)));
else
Analyze_And_Resolve (Actval, Etype (Actval));
end if;
end if;
-- If default is a tag indeterminate function call, propagate tag
-- to obtain proper dispatching.
if Is_Controlling_Formal (F)
and then Nkind (Default_Value (F)) = N_Function_Call
then
Set_Is_Controlling_Actual (Actval);
end if;
end if;
-- If the default expression raises constraint error, then just
-- silently replace it with an N_Raise_Constraint_Error node, since
-- we already gave the warning on the subprogram spec. If node is
-- already a Raise_Constraint_Error leave as is, to prevent loops in
-- the warnings removal machinery.
if Raises_Constraint_Error (Actval)
and then Nkind (Actval) /= N_Raise_Constraint_Error
then
Rewrite (Actval,
Make_Raise_Constraint_Error (Loc,
Reason => CE_Range_Check_Failed));
Set_Raises_Constraint_Error (Actval);
Set_Etype (Actval, Etype (F));
end if;
Assoc :=
Make_Parameter_Association (Loc,
Explicit_Actual_Parameter => Actval,
Selector_Name => Make_Identifier (Loc, Chars (F)));
-- Case of insertion is first named actual
if No (Prev)
or else Nkind (Parent (Prev)) /= N_Parameter_Association
then
Set_Next_Named_Actual (Assoc, First_Named_Actual (N));
Set_First_Named_Actual (N, Actval);
if No (Prev) then
if No (Parameter_Associations (N)) then
Set_Parameter_Associations (N, New_List (Assoc));
else
Append (Assoc, Parameter_Associations (N));
end if;
else
Insert_After (Prev, Assoc);
end if;
-- Case of insertion is not first named actual
else
Set_Next_Named_Actual
(Assoc, Next_Named_Actual (Parent (Prev)));
Set_Next_Named_Actual (Parent (Prev), Actval);
Append (Assoc, Parameter_Associations (N));
end if;
Mark_Rewrite_Insertion (Assoc);
Mark_Rewrite_Insertion (Actval);
Prev := Actval;
end Insert_Default;
-------------------
-- Same_Ancestor --
-------------------
function Same_Ancestor (T1, T2 : Entity_Id) return Boolean is
FT1 : Entity_Id := T1;
FT2 : Entity_Id := T2;
begin
if Is_Private_Type (T1)
and then Present (Full_View (T1))
then
FT1 := Full_View (T1);
end if;
if Is_Private_Type (T2)
and then Present (Full_View (T2))
then
FT2 := Full_View (T2);
end if;
return Root_Type (Base_Type (FT1)) = Root_Type (Base_Type (FT2));
end Same_Ancestor;
--------------------------
-- Static_Concatenation --
--------------------------
function Static_Concatenation (N : Node_Id) return Boolean is
begin
case Nkind (N) is
when N_String_Literal =>
return True;
when N_Op_Concat =>
-- Concatenation is static when both operands are static and
-- the concatenation operator is a predefined one.
return Scope (Entity (N)) = Standard_Standard
and then
Static_Concatenation (Left_Opnd (N))
and then
Static_Concatenation (Right_Opnd (N));
when others =>
if Is_Entity_Name (N) then
declare
Ent : constant Entity_Id := Entity (N);
begin
return Ekind (Ent) = E_Constant
and then Present (Constant_Value (Ent))
and then
Is_OK_Static_Expression (Constant_Value (Ent));
end;
else
return False;
end if;
end case;
end Static_Concatenation;
-- Start of processing for Resolve_Actuals
begin
Check_Argument_Order;
if Is_Overloadable (Nam)
and then Is_Inherited_Operation (Nam)
and then In_Instance
and then Present (Alias (Nam))
and then Present (Overridden_Operation (Alias (Nam)))
then
Real_Subp := Alias (Nam);
else
Real_Subp := Empty;
end if;
if Present (First_Actual (N)) then
Check_Prefixed_Call;
end if;
A := First_Actual (N);
F := First_Formal (Nam);
if Present (Real_Subp) then
Real_F := First_Formal (Real_Subp);
end if;
while Present (F) loop
if No (A) and then Needs_No_Actuals (Nam) then
null;
-- If we have an error in any actual or formal, indicated by a type
-- of Any_Type, then abandon resolution attempt, and set result type
-- to Any_Type. Skip this if the actual is a Raise_Expression, whose
-- type is imposed from context.
elsif (Present (A) and then Etype (A) = Any_Type)
or else Etype (F) = Any_Type
then
if Nkind (A) /= N_Raise_Expression then
Set_Etype (N, Any_Type);
return;
end if;
end if;
-- Case where actual is present
-- If the actual is an entity, generate a reference to it now. We
-- do this before the actual is resolved, because a formal of some
-- protected subprogram, or a task discriminant, will be rewritten
-- during expansion, and the source entity reference may be lost.
if Present (A)
and then Is_Entity_Name (A)
and then Comes_From_Source (A)
then
-- Annotate the tree by creating a variable reference marker when
-- the actual denotes a variable reference, in case the reference
-- is folded or optimized away. The variable reference marker is
-- automatically saved for later examination by the ABE Processing
-- phase. The status of the reference is set as follows:
-- status mode
-- read IN, IN OUT
-- write IN OUT, OUT
if Needs_Variable_Reference_Marker
(N => A,
Calls_OK => True)
then
Build_Variable_Reference_Marker
(N => A,
Read => Ekind (F) /= E_Out_Parameter,
Write => Ekind (F) /= E_In_Parameter);
end if;
Orig_A := Entity (A);
if Present (Orig_A) then
if Is_Formal (Orig_A)
and then Ekind (F) /= E_In_Parameter
then
Generate_Reference (Orig_A, A, 'm');
elsif not Is_Overloaded (A) then
if Ekind (F) /= E_Out_Parameter then
Generate_Reference (Orig_A, A);
-- RM 6.4.1(12): For an out parameter that is passed by
-- copy, the formal parameter object is created, and:
-- * For an access type, the formal parameter is initialized
-- from the value of the actual, without checking that the
-- value satisfies any constraint, any predicate, or any
-- exclusion of the null value.
-- * For a scalar type that has the Default_Value aspect
-- specified, the formal parameter is initialized from the
-- value of the actual, without checking that the value
-- satisfies any constraint or any predicate.
-- I do not understand why this case is included??? this is
-- not a case where an OUT parameter is treated as IN OUT.
-- * For a composite type with discriminants or that has
-- implicit initial values for any subcomponents, the
-- behavior is as for an in out parameter passed by copy.
-- Hence for these cases we generate the read reference now
-- (the write reference will be generated later by
-- Note_Possible_Modification).
elsif Is_By_Copy_Type (Etype (F))
and then
(Is_Access_Type (Etype (F))
or else
(Is_Scalar_Type (Etype (F))
and then
Present (Default_Aspect_Value (Etype (F))))
or else
(Is_Composite_Type (Etype (F))
and then (Has_Discriminants (Etype (F))
or else Is_Partially_Initialized_Type
(Etype (F)))))
then
Generate_Reference (Orig_A, A);
end if;
end if;
end if;
end if;
if Present (A)
and then (Nkind (Parent (A)) /= N_Parameter_Association
or else Chars (Selector_Name (Parent (A))) = Chars (F))
then
-- If style checking mode on, check match of formal name
if Style_Check then
if Nkind (Parent (A)) = N_Parameter_Association then
Check_Identifier (Selector_Name (Parent (A)), F);
end if;
end if;
-- If the formal is Out or In_Out, do not resolve and expand the
-- conversion, because it is subsequently expanded into explicit
-- temporaries and assignments. However, the object of the
-- conversion can be resolved. An exception is the case of tagged
-- type conversion with a class-wide actual. In that case we want
-- the tag check to occur and no temporary will be needed (no
-- representation change can occur) and the parameter is passed by
-- reference, so we go ahead and resolve the type conversion.
-- Another exception is the case of reference to component or
-- subcomponent of a bit-packed array, in which case we want to
-- defer expansion to the point the in and out assignments are
-- performed.
if Ekind (F) /= E_In_Parameter
and then Nkind (A) = N_Type_Conversion
and then not Is_Class_Wide_Type (Etype (Expression (A)))
and then not Is_Interface (Etype (A))
then
declare
Expr_Typ : constant Entity_Id := Etype (Expression (A));
begin
-- Check RM 4.6 (24.2/2)
if Is_Array_Type (Etype (F))
and then Is_View_Conversion (A)
then
-- In a view conversion, the conversion must be legal in
-- both directions, and thus both component types must be
-- aliased, or neither (4.6 (8)).
-- Check RM 4.6 (24.8/2)
if Has_Aliased_Components (Expr_Typ) /=
Has_Aliased_Components (Etype (F))
then
-- This normally illegal conversion is legal in an
-- expanded instance body because of RM 12.3(11).
-- At runtime, conversion must create a new object.
if not In_Instance then
Error_Msg_N
("both component types in a view conversion must"
& " be aliased, or neither", A);
end if;
-- Check RM 4.6 (24/3)
elsif not Same_Ancestor (Etype (F), Expr_Typ) then
-- Check view conv between unrelated by ref array
-- types.
if Is_By_Reference_Type (Etype (F))
or else Is_By_Reference_Type (Expr_Typ)
then
Error_Msg_N
("view conversion between unrelated by reference "
& "array types not allowed ('A'I-00246)", A);
-- In Ada 2005 mode, check view conversion component
-- type cannot be private, tagged, or volatile. Note
-- that we only apply this to source conversions. The
-- generated code can contain conversions which are
-- not subject to this test, and we cannot extract the
-- component type in such cases since it is not
-- present.
elsif Comes_From_Source (A)
and then Ada_Version >= Ada_2005
then
declare
Comp_Type : constant Entity_Id :=
Component_Type (Expr_Typ);
begin
if (Is_Private_Type (Comp_Type)
and then not Is_Generic_Type (Comp_Type))
or else Is_Tagged_Type (Comp_Type)
or else Is_Volatile (Comp_Type)
then
Error_Msg_N
("component type of a view conversion " &
"cannot be private, tagged, or volatile" &
" (RM 4.6 (24))",
Expression (A));
end if;
end;
end if;
end if;
-- AI12-0074 & AI12-0377
-- Check 6.4.1: If the mode is out, the actual parameter is
-- a view conversion, and the type of the formal parameter
-- is a scalar type, then either:
-- - the target and operand type both do not have the
-- Default_Value aspect specified; or
-- - the target and operand type both have the
-- Default_Value aspect specified, and there shall exist
-- a type (other than a root numeric type) that is an
-- ancestor of both the target type and the operand
-- type.
elsif Ekind (F) = E_Out_Parameter
and then Is_Scalar_Type (Etype (F))
then
if Has_Default_Aspect (Etype (F)) /=
Has_Default_Aspect (Expr_Typ)
then
Error_Msg_N
("view conversion requires Default_Value on both " &
"types (RM 6.4.1)", A);
elsif Has_Default_Aspect (Expr_Typ)
and then not Same_Ancestor (Etype (F), Expr_Typ)
then
Error_Msg_N
("view conversion between unrelated types with "
& "Default_Value not allowed (RM 6.4.1)", A);
end if;
end if;
end;
-- Resolve expression if conversion is all OK
if (Conversion_OK (A)
or else Valid_Conversion (A, Etype (A), Expression (A)))
and then not Is_Ref_To_Bit_Packed_Array (Expression (A))
then
Resolve (Expression (A));
end if;
-- If the actual is a function call that returns a limited
-- unconstrained object that needs finalization, create a
-- transient scope for it, so that it can receive the proper
-- finalization list.
elsif Expander_Active
and then Nkind (A) = N_Function_Call
and then Is_Limited_Record (Etype (F))
and then not Is_Constrained (Etype (F))
and then (Needs_Finalization (Etype (F))
or else Has_Task (Etype (F)))
then
Establish_Transient_Scope (A, Manage_Sec_Stack => False);
Resolve (A, Etype (F));
-- A small optimization: if one of the actuals is a concatenation
-- create a block around a procedure call to recover stack space.
-- This alleviates stack usage when several procedure calls in
-- the same statement list use concatenation. We do not perform
-- this wrapping for code statements, where the argument is a
-- static string, and we want to preserve warnings involving
-- sequences of such statements.
elsif Expander_Active
and then Nkind (A) = N_Op_Concat
and then Nkind (N) = N_Procedure_Call_Statement
and then not (Is_Intrinsic_Subprogram (Nam)
and then Chars (Nam) = Name_Asm)
and then not Static_Concatenation (A)
then
Establish_Transient_Scope (A, Manage_Sec_Stack => False);
Resolve (A, Etype (F));
else
if Nkind (A) = N_Type_Conversion
and then Is_Array_Type (Etype (F))
and then not Same_Ancestor (Etype (F), Etype (Expression (A)))
and then
(Is_Limited_Type (Etype (F))
or else Is_Limited_Type (Etype (Expression (A))))
then
Error_Msg_N
("conversion between unrelated limited array types not "
& "allowed ('A'I-00246)", A);
if Is_Limited_Type (Etype (F)) then
Explain_Limited_Type (Etype (F), A);
end if;
if Is_Limited_Type (Etype (Expression (A))) then
Explain_Limited_Type (Etype (Expression (A)), A);
end if;
end if;
-- (Ada 2005: AI-251): If the actual is an allocator whose
-- directly designated type is a class-wide interface, we build
-- an anonymous access type to use it as the type of the
-- allocator. Later, when the subprogram call is expanded, if
-- the interface has a secondary dispatch table the expander
-- will add a type conversion to force the correct displacement
-- of the pointer.
if Nkind (A) = N_Allocator then
declare
DDT : constant Entity_Id :=
Directly_Designated_Type (Base_Type (Etype (F)));
begin
-- Displace the pointer to the object to reference its
-- secondary dispatch table.
if Is_Class_Wide_Type (DDT)
and then Is_Interface (DDT)
then
Rewrite (A, Convert_To (Etype (F), Relocate_Node (A)));
Analyze_And_Resolve (A, Etype (F),
Suppress => Access_Check);
end if;
-- Ada 2005, AI-162:If the actual is an allocator, the
-- innermost enclosing statement is the master of the
-- created object. This needs to be done with expansion
-- enabled only, otherwise the transient scope will not
-- be removed in the expansion of the wrapped construct.
if Expander_Active
and then (Needs_Finalization (DDT)
or else Has_Task (DDT))
then
Establish_Transient_Scope
(A, Manage_Sec_Stack => False);
end if;
end;
if Ekind (Etype (F)) = E_Anonymous_Access_Type then
Check_Restriction (No_Access_Parameter_Allocators, A);
end if;
end if;
-- (Ada 2005): The call may be to a primitive operation of a
-- tagged synchronized type, declared outside of the type. In
-- this case the controlling actual must be converted to its
-- corresponding record type, which is the formal type. The
-- actual may be a subtype, either because of a constraint or
-- because it is a generic actual, so use base type to locate
-- concurrent type.
F_Typ := Base_Type (Etype (F));
if Is_Tagged_Type (F_Typ)
and then (Is_Concurrent_Type (F_Typ)
or else Is_Concurrent_Record_Type (F_Typ))
then
-- If the actual is overloaded, look for an interpretation
-- that has a synchronized type.
if not Is_Overloaded (A) then
A_Typ := Base_Type (Etype (A));
else
declare
Index : Interp_Index;
It : Interp;
begin
Get_First_Interp (A, Index, It);
while Present (It.Typ) loop
if Is_Concurrent_Type (It.Typ)
or else Is_Concurrent_Record_Type (It.Typ)
then
A_Typ := Base_Type (It.Typ);
exit;
end if;
Get_Next_Interp (Index, It);
end loop;
end;
end if;
declare
Full_A_Typ : Entity_Id;
begin
if Present (Full_View (A_Typ)) then
Full_A_Typ := Base_Type (Full_View (A_Typ));
else
Full_A_Typ := A_Typ;
end if;
-- Tagged synchronized type (case 1): the actual is a
-- concurrent type.
if Is_Concurrent_Type (A_Typ)
and then Corresponding_Record_Type (A_Typ) = F_Typ
then
Rewrite (A,
Unchecked_Convert_To
(Corresponding_Record_Type (A_Typ), A));
Resolve (A, Etype (F));
-- Tagged synchronized type (case 2): the formal is a
-- concurrent type.
elsif Ekind (Full_A_Typ) = E_Record_Type
and then Present
(Corresponding_Concurrent_Type (Full_A_Typ))
and then Is_Concurrent_Type (F_Typ)
and then Present (Corresponding_Record_Type (F_Typ))
and then Full_A_Typ = Corresponding_Record_Type (F_Typ)
then
Resolve (A, Corresponding_Record_Type (F_Typ));
-- Common case
else
Resolve (A, Etype (F));
end if;
end;
-- Not a synchronized operation
else
Resolve (A, Etype (F));
end if;
end if;
A_Typ := Etype (A);
F_Typ := Etype (F);
-- An actual cannot be an untagged formal incomplete type
if Ekind (A_Typ) = E_Incomplete_Type
and then not Is_Tagged_Type (A_Typ)
and then Is_Generic_Type (A_Typ)
then
Error_Msg_N
("invalid use of untagged formal incomplete type", A);
end if;
-- has warnings suppressed, then we reset Never_Set_In_Source for
-- the calling entity. The reason for this is to catch cases like
-- GNAT.Spitbol.Patterns.Vstring_Var where the called subprogram
-- uses trickery to modify an IN parameter.
if Ekind (F) = E_In_Parameter
and then Is_Entity_Name (A)
and then Present (Entity (A))
and then Ekind (Entity (A)) = E_Variable
and then Has_Warnings_Off (F_Typ)
then
Set_Never_Set_In_Source (Entity (A), False);
end if;
-- Perform error checks for IN and IN OUT parameters
if Ekind (F) /= E_Out_Parameter then
-- Check unset reference. For scalar parameters, it is clearly
-- wrong to pass an uninitialized value as either an IN or
-- IN-OUT parameter. For composites, it is also clearly an
-- error to pass a completely uninitialized value as an IN
-- parameter, but the case of IN OUT is trickier. We prefer
-- not to give a warning here. For example, suppose there is
-- a routine that sets some component of a record to False.
-- It is perfectly reasonable to make this IN-OUT and allow
-- either initialized or uninitialized records to be passed
-- in this case.
-- For partially initialized composite values, we also avoid
-- warnings, since it is quite likely that we are passing a
-- partially initialized value and only the initialized fields
-- will in fact be read in the subprogram.
if Is_Scalar_Type (A_Typ)
or else (Ekind (F) = E_In_Parameter
and then not Is_Partially_Initialized_Type (A_Typ))
then
Check_Unset_Reference (A);
end if;
-- In Ada 83 we cannot pass an OUT parameter as an IN or IN OUT
-- actual to a nested call, since this constitutes a reading of
-- the parameter, which is not allowed.
if Ada_Version = Ada_83
and then Is_Entity_Name (A)
and then Ekind (Entity (A)) = E_Out_Parameter
then
Error_Msg_N ("(Ada 83) illegal reading of out parameter", A);
end if;
end if;
-- In -gnatd.q mode, forget that a given array is constant when
-- it is passed as an IN parameter to a foreign-convention
-- subprogram. This is in case the subprogram evilly modifies the
-- object. Of course, correct code would use IN OUT.
if Debug_Flag_Dot_Q
and then Ekind (F) = E_In_Parameter
and then Has_Foreign_Convention (Nam)
and then Is_Array_Type (F_Typ)
and then Nkind (A) in N_Has_Entity
and then Present (Entity (A))
then
Set_Is_True_Constant (Entity (A), False);
end if;
-- Case of OUT or IN OUT parameter
if Ekind (F) /= E_In_Parameter then
-- For an Out parameter, check for useless assignment. Note
-- that we can't set Last_Assignment this early, because we may
-- kill current values in Resolve_Call, and that call would
-- clobber the Last_Assignment field.
-- Note: call Warn_On_Useless_Assignment before doing the check
-- below for Is_OK_Variable_For_Out_Formal so that the setting
-- of Referenced_As_LHS/Referenced_As_Out_Formal properly
-- reflects the last assignment, not this one.
if Ekind (F) = E_Out_Parameter then
if Warn_On_Modified_As_Out_Parameter (F)
and then Is_Entity_Name (A)
and then Present (Entity (A))
and then Comes_From_Source (N)
then
Warn_On_Useless_Assignment (Entity (A), A);
end if;
end if;
-- Validate the form of the actual. Note that the call to
-- Is_OK_Variable_For_Out_Formal generates the required
-- reference in this case.
-- A call to an initialization procedure for an aggregate
-- component may initialize a nested component of a constant
-- designated object. In this context the object is variable.
if not Is_OK_Variable_For_Out_Formal (A)
and then not Is_Init_Proc (Nam)
then
Error_Msg_NE ("actual for& must be a variable", A, F);
if Is_Subprogram (Current_Scope) then
if Is_Invariant_Procedure (Current_Scope)
or else Is_Partial_Invariant_Procedure (Current_Scope)
then
Error_Msg_N
("function used in invariant cannot modify its "
& "argument", F);
elsif Is_Predicate_Function (Current_Scope) then
Error_Msg_N
("function used in predicate cannot modify its "
& "argument", F);
end if;
end if;
end if;
-- What's the following about???
if Is_Entity_Name (A) then
Kill_Checks (Entity (A));
else
Kill_All_Checks;
end if;
end if;
if A_Typ = Any_Type then
Set_Etype (N, Any_Type);
return;
end if;
-- Apply appropriate constraint/predicate checks for IN [OUT] case
if Ekind (F) in E_In_Parameter | E_In_Out_Parameter then
-- Apply predicate tests except in certain special cases. Note
-- that it might be more consistent to apply these only when
-- expansion is active (in Exp_Ch6.Expand_Actuals), as we do
-- for the outbound predicate tests ??? In any case indicate
-- the function being called, for better warnings if the call
-- leads to an infinite recursion.
if Predicate_Tests_On_Arguments (Nam) then
Apply_Predicate_Check (A, F_Typ, Nam);
end if;
-- Apply required constraint checks
if Is_Scalar_Type (A_Typ) then
Apply_Scalar_Range_Check (A, F_Typ);
elsif Is_Array_Type (A_Typ) then
Apply_Length_Check (A, F_Typ);
elsif Is_Record_Type (F_Typ)
and then Has_Discriminants (F_Typ)
and then Is_Constrained (F_Typ)
and then (not Is_Derived_Type (F_Typ)
or else Comes_From_Source (Nam))
then
Apply_Discriminant_Check (A, F_Typ);
-- For view conversions of a discriminated object, apply
-- check to object itself, the conversion alreay has the
-- proper type.
if Nkind (A) = N_Type_Conversion
and then Is_Constrained (Etype (Expression (A)))
then
Apply_Discriminant_Check (Expression (A), F_Typ);
end if;
elsif Is_Access_Type (F_Typ)
and then Is_Array_Type (Designated_Type (F_Typ))
and then Is_Constrained (Designated_Type (F_Typ))
then
Apply_Length_Check (A, F_Typ);
elsif Is_Access_Type (F_Typ)
and then Has_Discriminants (Designated_Type (F_Typ))
and then Is_Constrained (Designated_Type (F_Typ))
then
Apply_Discriminant_Check (A, F_Typ);
else
Apply_Range_Check (A, F_Typ);
end if;
-- Ada 2005 (AI-231): Note that the controlling parameter case
-- already existed in Ada 95, which is partially checked
-- elsewhere (see Checks), and we don't want the warning
-- message to differ.
if Is_Access_Type (F_Typ)
and then Can_Never_Be_Null (F_Typ)
and then Known_Null (A)
then
if Is_Controlling_Formal (F) then
Apply_Compile_Time_Constraint_Error
(N => A,
Msg => "null value not allowed here??",
Reason => CE_Access_Check_Failed);
elsif Ada_Version >= Ada_2005 then
Apply_Compile_Time_Constraint_Error
(N => A,
Msg => "(Ada 2005) null not allowed in "
& "null-excluding formal??",
Reason => CE_Null_Not_Allowed);
end if;
end if;
end if;
-- Checks for OUT parameters and IN OUT parameters
if Ekind (F) in E_Out_Parameter | E_In_Out_Parameter then
-- If there is a type conversion, make sure the return value
-- meets the constraints of the variable before the conversion.
if Nkind (A) = N_Type_Conversion then
if Is_Scalar_Type (A_Typ) then
-- Special case here tailored to Exp_Ch6.Is_Legal_Copy,
-- which would prevent the check from being generated.
-- This is for Starlet only though, so long obsolete.
if Mechanism (F) = By_Reference
and then Ekind (Nam) = E_Procedure
and then Is_Valued_Procedure (Nam)
then
null;
else
Apply_Scalar_Range_Check
(Expression (A), Etype (Expression (A)), A_Typ);
end if;
-- In addition the return value must meet the constraints
-- of the object type (see the comment below).
Apply_Scalar_Range_Check (A, A_Typ, F_Typ);
else
Apply_Range_Check
(Expression (A), Etype (Expression (A)), A_Typ);
end if;
-- If no conversion, apply scalar range checks and length check
-- based on the subtype of the actual (NOT that of the formal).
-- This indicates that the check takes place on return from the
-- call. During expansion the required constraint checks are
-- inserted. In GNATprove mode, in the absence of expansion,
-- the flag indicates that the returned value is valid.
else
if Is_Scalar_Type (F_Typ) then
Apply_Scalar_Range_Check (A, A_Typ, F_Typ);
elsif Is_Array_Type (F_Typ)
and then Ekind (F) = E_Out_Parameter
then
Apply_Length_Check (A, F_Typ);
else
Apply_Range_Check (A, A_Typ, F_Typ);
end if;
end if;
-- Note: we do not apply the predicate checks for the case of
-- OUT and IN OUT parameters. They are instead applied in the
-- Expand_Actuals routine in Exp_Ch6.
end if;
-- An actual associated with an access parameter is implicitly
-- converted to the anonymous access type of the formal and must
-- satisfy the legality checks for access conversions.
if Ekind (F_Typ) = E_Anonymous_Access_Type then
if not Valid_Conversion (A, F_Typ, A) then
Error_Msg_N
("invalid implicit conversion for access parameter", A);
end if;
-- If the actual is an access selected component of a variable,
-- the call may modify its designated object. It is reasonable
-- to treat this as a potential modification of the enclosing
-- record, to prevent spurious warnings that it should be
-- declared as a constant, because intuitively programmers
-- regard the designated subcomponent as part of the record.
if Nkind (A) = N_Selected_Component
and then Is_Entity_Name (Prefix (A))
and then not Is_Constant_Object (Entity (Prefix (A)))
then
Note_Possible_Modification (A, Sure => False);
end if;
end if;
-- Check illegal cases of atomic/volatile actual (RM C.6(12,13))
if (Is_By_Reference_Type (Etype (F)) or else Is_Aliased (F))
and then Comes_From_Source (N)
then
if Is_Atomic_Object (A)
and then not Is_Atomic (Etype (F))
then
Error_Msg_NE
("cannot pass atomic object to nonatomic formal&",
A, F);
Error_Msg_N
("\which is passed by reference (RM C.6(12))", A);
elsif Is_Volatile_Object (A)
and then not Is_Volatile (Etype (F))
then
Error_Msg_NE
("cannot pass volatile object to nonvolatile formal&",
A, F);
Error_Msg_N
("\which is passed by reference (RM C.6(12))", A);
end if;
if Ada_Version >= Ada_2020
and then Is_Subcomponent_Of_Atomic_Object (A)
and then not Is_Atomic_Object (A)
then
Error_Msg_N
("cannot pass nonatomic subcomponent of atomic object",
A);
Error_Msg_NE
("\to formal & which is passed by reference (RM C.6(13))",
A, F);
end if;
end if;
-- Check that subprograms don't have improper controlling
-- arguments (RM 3.9.2 (9)).
-- A primitive operation may have an access parameter of an
-- incomplete tagged type, but a dispatching call is illegal
-- if the type is still incomplete.
if Is_Controlling_Formal (F) then
Set_Is_Controlling_Actual (A);
if Ekind (Etype (F)) = E_Anonymous_Access_Type then
declare
Desig : constant Entity_Id := Designated_Type (Etype (F));
begin
if Ekind (Desig) = E_Incomplete_Type
and then No (Full_View (Desig))
and then No (Non_Limited_View (Desig))
then
Error_Msg_NE
("premature use of incomplete type& "
& "in dispatching call", A, Desig);
end if;
end;
end if;
elsif Nkind (A) = N_Explicit_Dereference then
Validate_Remote_Access_To_Class_Wide_Type (A);
end if;
-- Apply legality rule 3.9.2 (9/1)
if (Is_Class_Wide_Type (A_Typ) or else Is_Dynamically_Tagged (A))
and then not Is_Class_Wide_Type (F_Typ)
and then not Is_Controlling_Formal (F)
and then not In_Instance
then
Error_Msg_N ("class-wide argument not allowed here!", A);
if Is_Subprogram (Nam) and then Comes_From_Source (Nam) then
Error_Msg_Node_2 := F_Typ;
Error_Msg_NE
("& is not a dispatching operation of &!", A, Nam);
end if;
-- Apply the checks described in 3.10.2(27): if the context is a
-- specific access-to-object, the actual cannot be class-wide.
-- Use base type to exclude access_to_subprogram cases.
elsif Is_Access_Type (A_Typ)
and then Is_Access_Type (F_Typ)
and then not Is_Access_Subprogram_Type (Base_Type (F_Typ))
and then (Is_Class_Wide_Type (Designated_Type (A_Typ))
or else (Nkind (A) = N_Attribute_Reference
and then
Is_Class_Wide_Type (Etype (Prefix (A)))))
and then not Is_Class_Wide_Type (Designated_Type (F_Typ))
and then not Is_Controlling_Formal (F)
-- Disable these checks for call to imported C++ subprograms
and then not
(Is_Entity_Name (Name (N))
and then Is_Imported (Entity (Name (N)))
and then Convention (Entity (Name (N))) = Convention_CPP)
then
Error_Msg_N
("access to class-wide argument not allowed here!", A);
if Is_Subprogram (Nam) and then Comes_From_Source (Nam) then
Error_Msg_Node_2 := Designated_Type (F_Typ);
Error_Msg_NE
("& is not a dispatching operation of &!", A, Nam);
end if;
end if;
Check_Aliased_Parameter;
Eval_Actual (A);
-- If it is a named association, treat the selector_name as a
-- proper identifier, and mark the corresponding entity.
if Nkind (Parent (A)) = N_Parameter_Association
-- Ignore reference in SPARK mode, as it refers to an entity not
-- in scope at the point of reference, so the reference should
-- be ignored for computing effects of subprograms.
and then not GNATprove_Mode
then
-- If subprogram is overridden, use name of formal that
-- is being called.
if Present (Real_Subp) then
Set_Entity (Selector_Name (Parent (A)), Real_F);
Set_Etype (Selector_Name (Parent (A)), Etype (Real_F));
else
Set_Entity (Selector_Name (Parent (A)), F);
Generate_Reference (F, Selector_Name (Parent (A)));
Set_Etype (Selector_Name (Parent (A)), F_Typ);
Generate_Reference (F_Typ, N, ' ');
end if;
end if;
Prev := A;
if Ekind (F) /= E_Out_Parameter then
Check_Unset_Reference (A);
end if;
-- The following checks are only relevant when SPARK_Mode is on as
-- they are not standard Ada legality rule. Internally generated
-- temporaries are ignored.
if SPARK_Mode = On and then Comes_From_Source (A) then
-- An effectively volatile object for reading may act as an
-- actual when the corresponding formal is of a non-scalar
-- effectively volatile type for reading (SPARK RM 7.1.3(10)).
if not Is_Scalar_Type (Etype (F))
and then Is_Effectively_Volatile_For_Reading (Etype (F))
then
null;
-- An effectively volatile object for reading may act as an
-- actual in a call to an instance of Unchecked_Conversion.
-- (SPARK RM 7.1.3(10)).
elsif Is_Unchecked_Conversion_Instance (Nam) then
null;
-- The actual denotes an object
elsif Is_Effectively_Volatile_Object_For_Reading (A) then
Error_Msg_N
("volatile object cannot act as actual in a call (SPARK "
& "RM 7.1.3(10))", A);
-- Otherwise the actual denotes an expression. Inspect the
-- expression and flag each effectively volatile object
-- for reading as illegal because it apprears within an
-- interfering context. Note that this is usually done in
-- Resolve_Entity_Name, but when the effectively volatile
-- object for reading appears as an actual in a call, the
-- call must be resolved first.
else
Flag_Effectively_Volatile_Objects (A);
end if;
-- An effectively volatile variable cannot act as an actual
-- parameter in a procedure call when the variable has enabled
-- property Effective_Reads and the corresponding formal is of
-- mode IN (SPARK RM 7.1.3(10)).
if Ekind (Nam) = E_Procedure
and then Ekind (F) = E_In_Parameter
and then Is_Entity_Name (A)
then
A_Id := Entity (A);
if Ekind (A_Id) = E_Variable
and then Is_Effectively_Volatile_For_Reading (Etype (A_Id))
and then Effective_Reads_Enabled (A_Id)
then
Error_Msg_NE
("effectively volatile variable & cannot appear as "
& "actual in procedure call", A, A_Id);
Error_Msg_Name_1 := Name_Effective_Reads;
Error_Msg_N ("\\variable has enabled property %", A);
Error_Msg_N ("\\corresponding formal has mode IN", A);
end if;
end if;
end if;
-- A formal parameter of a specific tagged type whose related
-- subprogram is subject to pragma Extensions_Visible with value
-- "False" cannot act as an actual in a subprogram with value
-- "True" (SPARK RM 6.1.7(3)).
if Is_EVF_Expression (A)
and then Extensions_Visible_Status (Nam) =
Extensions_Visible_True
then
Error_Msg_N
("formal parameter cannot act as actual parameter when "
& "Extensions_Visible is False", A);
Error_Msg_NE
("\subprogram & has Extensions_Visible True", A, Nam);
end if;
-- The actual parameter of a Ghost subprogram whose formal is of
-- mode IN OUT or OUT must be a Ghost variable (SPARK RM 6.9(12)).
if Comes_From_Source (Nam)
and then Is_Ghost_Entity (Nam)
and then Ekind (F) in E_In_Out_Parameter | E_Out_Parameter
and then Is_Entity_Name (A)
and then Present (Entity (A))
and then not Is_Ghost_Entity (Entity (A))
then
Error_Msg_NE
("non-ghost variable & cannot appear as actual in call to "
& "ghost procedure", A, Entity (A));
if Ekind (F) = E_In_Out_Parameter then
Error_Msg_N ("\corresponding formal has mode `IN OUT`", A);
else
Error_Msg_N ("\corresponding formal has mode OUT", A);
end if;
end if;
Next_Actual (A);
-- Case where actual is not present
else
Insert_Default;
end if;
Next_Formal (F);
if Present (Real_Subp) then
Next_Formal (Real_F);
end if;
end loop;
end Resolve_Actuals;
-----------------------
-- Resolve_Allocator --
-----------------------
procedure Resolve_Allocator (N : Node_Id; Typ : Entity_Id) is
Desig_T : constant Entity_Id := Designated_Type (Typ);
E : constant Node_Id := Expression (N);
Subtyp : Entity_Id;
Discrim : Entity_Id;
Constr : Node_Id;
Aggr : Node_Id;
Assoc : Node_Id := Empty;
Disc_Exp : Node_Id;
procedure Check_Allocator_Discrim_Accessibility
(Disc_Exp : Node_Id;
Alloc_Typ : Entity_Id);
-- Check that accessibility level associated with an access discriminant
-- initialized in an allocator by the expression Disc_Exp is not deeper
-- than the level of the allocator type Alloc_Typ. An error message is
-- issued if this condition is violated. Specialized checks are done for
-- the cases of a constraint expression which is an access attribute or
-- an access discriminant.
procedure Check_Allocator_Discrim_Accessibility_Exprs
(Curr_Exp : Node_Id;
Alloc_Typ : Entity_Id);
-- Dispatch checks performed by Check_Allocator_Discrim_Accessibility
-- across all expressions within a given conditional expression.
function In_Dispatching_Context return Boolean;
-- If the allocator is an actual in a call, it is allowed to be class-
-- wide when the context is not because it is a controlling actual.
-------------------------------------------
-- Check_Allocator_Discrim_Accessibility --
-------------------------------------------
procedure Check_Allocator_Discrim_Accessibility
(Disc_Exp : Node_Id;
Alloc_Typ : Entity_Id)
is
begin
if Type_Access_Level (Etype (Disc_Exp)) >
Deepest_Type_Access_Level (Alloc_Typ)
then
Error_Msg_N
("operand type has deeper level than allocator type", Disc_Exp);
-- When the expression is an Access attribute the level of the prefix
-- object must not be deeper than that of the allocator's type.
elsif Nkind (Disc_Exp) = N_Attribute_Reference
and then Get_Attribute_Id (Attribute_Name (Disc_Exp)) =
Attribute_Access
and then Object_Access_Level (Prefix (Disc_Exp)) >
Deepest_Type_Access_Level (Alloc_Typ)
then
Error_Msg_N
("prefix of attribute has deeper level than allocator type",
Disc_Exp);
-- When the expression is an access discriminant the check is against
-- the level of the prefix object.
elsif Ekind (Etype (Disc_Exp)) = E_Anonymous_Access_Type
and then Nkind (Disc_Exp) = N_Selected_Component
and then Object_Access_Level (Prefix (Disc_Exp)) >
Deepest_Type_Access_Level (Alloc_Typ)
then
Error_Msg_N
("access discriminant has deeper level than allocator type",
Disc_Exp);
-- All other cases are legal
else
null;
end if;
end Check_Allocator_Discrim_Accessibility;
-------------------------------------------------
-- Check_Allocator_Discrim_Accessibility_Exprs --
-------------------------------------------------
procedure Check_Allocator_Discrim_Accessibility_Exprs
(Curr_Exp : Node_Id;
Alloc_Typ : Entity_Id)
is
Alt : Node_Id;
Expr : Node_Id;
Disc_Exp : constant Node_Id := Original_Node (Curr_Exp);
begin
-- When conditional expressions are constant folded we know at
-- compile time which expression to check - so don't bother with
-- the rest of the cases.
if Nkind (Curr_Exp) = N_Attribute_Reference then
Check_Allocator_Discrim_Accessibility (Curr_Exp, Alloc_Typ);
-- Non-constant-folded if expressions
elsif Nkind (Disc_Exp) = N_If_Expression then
-- Check both expressions if they are still present in the face
-- of expansion.
Expr := Next (First (Expressions (Disc_Exp)));
if Present (Expr) then
Check_Allocator_Discrim_Accessibility_Exprs (Expr, Alloc_Typ);
Next (Expr);
if Present (Expr) then
Check_Allocator_Discrim_Accessibility_Exprs
(Expr, Alloc_Typ);
end if;
end if;
-- Non-constant-folded case expressions
elsif Nkind (Disc_Exp) = N_Case_Expression then
-- Check all alternatives
Alt := First (Alternatives (Disc_Exp));
while Present (Alt) loop
Check_Allocator_Discrim_Accessibility_Exprs
(Expression (Alt), Alloc_Typ);
Next (Alt);
end loop;
-- Base case, check the accessibility of the original node of the
-- expression.
else
Check_Allocator_Discrim_Accessibility (Disc_Exp, Alloc_Typ);
end if;
end Check_Allocator_Discrim_Accessibility_Exprs;
----------------------------
-- In_Dispatching_Context --
----------------------------
function In_Dispatching_Context return Boolean is
Par : constant Node_Id := Parent (N);
begin
return Nkind (Par) in N_Subprogram_Call
and then Is_Entity_Name (Name (Par))
and then Is_Dispatching_Operation (Entity (Name (Par)));
end In_Dispatching_Context;
-- Start of processing for Resolve_Allocator
begin
-- Replace general access with specific type
if Ekind (Etype (N)) = E_Allocator_Type then
Set_Etype (N, Base_Type (Typ));
end if;
if Is_Abstract_Type (Typ) then
Error_Msg_N ("type of allocator cannot be abstract", N);
end if;
-- For qualified expression, resolve the expression using the given
-- subtype (nothing to do for type mark, subtype indication)
if Nkind (E) = N_Qualified_Expression then
if Is_Class_Wide_Type (Etype (E))
and then not Is_Class_Wide_Type (Desig_T)
and then not In_Dispatching_Context
then
Error_Msg_N
("class-wide allocator not allowed for this access type", N);
end if;
-- Do a full resolution to apply constraint and predicate checks
Resolve_Qualified_Expression (E, Etype (E));
Check_Unset_Reference (Expression (E));
-- Allocators generated by the build-in-place expansion mechanism
-- are explicitly marked as coming from source but do not need to be
-- checked for limited initialization. To exclude this case, ensure
-- that the parent of the allocator is a source node.
-- The return statement constructed for an Expression_Function does
-- not come from source but requires a limited check.
if Is_Limited_Type (Etype (E))
and then Comes_From_Source (N)
and then
(Comes_From_Source (Parent (N))
or else
(Ekind (Current_Scope) = E_Function
and then Nkind (Original_Node (Unit_Declaration_Node
(Current_Scope))) = N_Expression_Function))
and then not In_Instance_Body
then
if not OK_For_Limited_Init (Etype (E), Expression (E)) then
if Nkind (Parent (N)) = N_Assignment_Statement then
Error_Msg_N
("illegal expression for initialized allocator of a "
& "limited type (RM 7.5 (2.7/2))", N);
else
Error_Msg_N
("initialization not allowed for limited types", N);
end if;
Explain_Limited_Type (Etype (E), N);
end if;
end if;
-- Calls to build-in-place functions are not currently supported in
-- allocators for access types associated with a simple storage pool.
-- Supporting such allocators may require passing additional implicit
-- parameters to build-in-place functions (or a significant revision
-- of the current b-i-p implementation to unify the handling for
-- multiple kinds of storage pools). ???
if Is_Limited_View (Desig_T)
and then Nkind (Expression (E)) = N_Function_Call
then
declare
Pool : constant Entity_Id :=
Associated_Storage_Pool (Root_Type (Typ));
begin
if Present (Pool)
and then
Present (Get_Rep_Pragma
(Etype (Pool), Name_Simple_Storage_Pool_Type))
then
Error_Msg_N
("limited function calls not yet supported in simple "
& "storage pool allocators", Expression (E));
end if;
end;
end if;
-- A special accessibility check is needed for allocators that
-- constrain access discriminants. The level of the type of the
-- expression used to constrain an access discriminant cannot be
-- deeper than the type of the allocator (in contrast to access
-- parameters, where the level of the actual can be arbitrary).
-- We can't use Valid_Conversion to perform this check because in
-- general the type of the allocator is unrelated to the type of
-- the access discriminant.
if Ekind (Typ) /= E_Anonymous_Access_Type
or else Is_Local_Anonymous_Access (Typ)
then
Subtyp := Entity (Subtype_Mark (E));
Aggr := Original_Node (Expression (E));
if Has_Discriminants (Subtyp)
and then Nkind (Aggr) in N_Aggregate | N_Extension_Aggregate
then
Discrim := First_Discriminant (Base_Type (Subtyp));
-- Get the first component expression of the aggregate
if Present (Expressions (Aggr)) then
Disc_Exp := First (Expressions (Aggr));
elsif Present (Component_Associations (Aggr)) then
Assoc := First (Component_Associations (Aggr));
if Present (Assoc) then
Disc_Exp := Expression (Assoc);
else
Disc_Exp := Empty;
end if;
else
Disc_Exp := Empty;
end if;
while Present (Discrim) and then Present (Disc_Exp) loop
if Ekind (Etype (Discrim)) = E_Anonymous_Access_Type then
Check_Allocator_Discrim_Accessibility_Exprs
(Disc_Exp, Typ);
end if;
Next_Discriminant (Discrim);
if Present (Discrim) then
if Present (Assoc) then
Next (Assoc);
Disc_Exp := Expression (Assoc);
elsif Present (Next (Disc_Exp)) then
Next (Disc_Exp);
else
Assoc := First (Component_Associations (Aggr));
if Present (Assoc) then
Disc_Exp := Expression (Assoc);
else
Disc_Exp := Empty;
end if;
end if;
end if;
end loop;
end if;
end if;
-- For a subtype mark or subtype indication, freeze the subtype
else
Freeze_Expression (E);
if Is_Access_Constant (Typ) and then not No_Initialization (N) then
Error_Msg_N
("initialization required for access-to-constant allocator", N);
end if;
-- A special accessibility check is needed for allocators that
-- constrain access discriminants. The level of the type of the
-- expression used to constrain an access discriminant cannot be
-- deeper than the type of the allocator (in contrast to access
-- parameters, where the level of the actual can be arbitrary).
-- We can't use Valid_Conversion to perform this check because
-- in general the type of the allocator is unrelated to the type
-- of the access discriminant.
if Nkind (Original_Node (E)) = N_Subtype_Indication
and then (Ekind (Typ) /= E_Anonymous_Access_Type
or else Is_Local_Anonymous_Access (Typ))
then
Subtyp := Entity (Subtype_Mark (Original_Node (E)));
if Has_Discriminants (Subtyp) then
Discrim := First_Discriminant (Base_Type (Subtyp));
Constr := First (Constraints (Constraint (Original_Node (E))));
while Present (Discrim) and then Present (Constr) loop
if Ekind (Etype (Discrim)) = E_Anonymous_Access_Type then
if Nkind (Constr) = N_Discriminant_Association then
Disc_Exp := Expression (Constr);
else
Disc_Exp := Constr;
end if;
Check_Allocator_Discrim_Accessibility_Exprs
(Disc_Exp, Typ);
end if;
Next_Discriminant (Discrim);
Next (Constr);
end loop;
end if;
end if;
end if;
-- Ada 2005 (AI-344): A class-wide allocator requires an accessibility
-- check that the level of the type of the created object is not deeper
-- than the level of the allocator's access type, since extensions can
-- now occur at deeper levels than their ancestor types. This is a
-- static accessibility level check; a run-time check is also needed in
-- the case of an initialized allocator with a class-wide argument (see
-- Expand_Allocator_Expression).
if Ada_Version >= Ada_2005
and then Is_Class_Wide_Type (Desig_T)
then
declare
Exp_Typ : Entity_Id;
begin
if Nkind (E) = N_Qualified_Expression then
Exp_Typ := Etype (E);
elsif Nkind (E) = N_Subtype_Indication then
Exp_Typ := Entity (Subtype_Mark (Original_Node (E)));
else
Exp_Typ := Entity (E);
end if;
if Type_Access_Level (Exp_Typ) >
Deepest_Type_Access_Level (Typ)
then
if In_Instance_Body then
Error_Msg_Warn := SPARK_Mode /= On;
Error_Msg_N
("type in allocator has deeper level than designated "
& "class-wide type<<", E);
Error_Msg_N ("\Program_Error [<<", E);
Rewrite (N,
Make_Raise_Program_Error (Sloc (N),
Reason => PE_Accessibility_Check_Failed));
Set_Etype (N, Typ);
-- Do not apply Ada 2005 accessibility checks on a class-wide
-- allocator if the type given in the allocator is a formal
-- type. A run-time check will be performed in the instance.
elsif not Is_Generic_Type (Exp_Typ) then
Error_Msg_N
("type in allocator has deeper level than designated "
& "class-wide type", E);
end if;
end if;
end;
end if;
-- Check for allocation from an empty storage pool. But do not complain
-- if it's a return statement for a build-in-place function, because the
-- allocator is there just in case the caller uses an allocator. If the
-- caller does use an allocator, it will be caught at the call site.
if No_Pool_Assigned (Typ)
and then not Alloc_For_BIP_Return (N)
then
Error_Msg_N ("allocation from empty storage pool!", N);
-- If the context is an unchecked conversion, as may happen within an
-- inlined subprogram, the allocator is being resolved with its own
-- anonymous type. In that case, if the target type has a specific
-- storage pool, it must be inherited explicitly by the allocator type.
elsif Nkind (Parent (N)) = N_Unchecked_Type_Conversion
and then No (Associated_Storage_Pool (Typ))
then
Set_Associated_Storage_Pool
(Typ, Associated_Storage_Pool (Etype (Parent (N))));
end if;
if Ekind (Etype (N)) = E_Anonymous_Access_Type then
Check_Restriction (No_Anonymous_Allocators, N);
end if;
-- Check that an allocator with task parts isn't for a nested access
-- type when restriction No_Task_Hierarchy applies.
if not Is_Library_Level_Entity (Base_Type (Typ))
and then Has_Task (Base_Type (Desig_T))
then
Check_Restriction (No_Task_Hierarchy, N);
end if;
-- An illegal allocator may be rewritten as a raise Program_Error
-- statement.
if Nkind (N) = N_Allocator then
-- Avoid coextension processing for an allocator that is the
-- expansion of a build-in-place function call.
if Nkind (Original_Node (N)) = N_Allocator
and then Nkind (Expression (Original_Node (N))) =
N_Qualified_Expression
and then Nkind (Expression (Expression (Original_Node (N)))) =
N_Function_Call
and then Is_Expanded_Build_In_Place_Call
(Expression (Expression (Original_Node (N))))
then
null; -- b-i-p function call case
else
-- An anonymous access discriminant is the definition of a
-- coextension.
if Ekind (Typ) = E_Anonymous_Access_Type
and then Nkind (Associated_Node_For_Itype (Typ)) =
N_Discriminant_Specification
then
declare
Discr : constant Entity_Id :=
Defining_Identifier (Associated_Node_For_Itype (Typ));
begin
Check_Restriction (No_Coextensions, N);
-- Ada 2012 AI05-0052: If the designated type of the
-- allocator is limited, then the allocator shall not
-- be used to define the value of an access discriminant
-- unless the discriminated type is immutably limited.
if Ada_Version >= Ada_2012
and then Is_Limited_Type (Desig_T)
and then not Is_Limited_View (Scope (Discr))
then
Error_Msg_N
("only immutably limited types can have anonymous "
& "access discriminants designating a limited type",
N);
end if;
end;
-- Avoid marking an allocator as a dynamic coextension if it is
-- within a static construct.
if not Is_Static_Coextension (N) then
Set_Is_Dynamic_Coextension (N);
-- Finalization and deallocation of coextensions utilizes an
-- approximate implementation which does not directly adhere
-- to the semantic rules. Warn on potential issues involving
-- coextensions.
if Is_Controlled (Desig_T) then
Error_Msg_N
("??coextension will not be finalized when its "
& "associated owner is deallocated or finalized", N);
else
Error_Msg_N
("??coextension will not be deallocated when its "
& "associated owner is deallocated", N);
end if;
end if;
-- Cleanup for potential static coextensions
else
Set_Is_Dynamic_Coextension (N, False);
Set_Is_Static_Coextension (N, False);
-- Anonymous access-to-controlled objects are not finalized on
-- time because this involves run-time ownership and currently
-- this property is not available. In rare cases the object may
-- not be finalized at all. Warn on potential issues involving
-- anonymous access-to-controlled objects.
if Ekind (Typ) = E_Anonymous_Access_Type
and then Is_Controlled_Active (Desig_T)
then
Error_Msg_N
("??object designated by anonymous access object might "
& "not be finalized until its enclosing library unit "
& "goes out of scope", N);
Error_Msg_N ("\use named access type instead", N);
end if;
end if;
end if;
end if;
-- Report a simple error: if the designated object is a local task,
-- its body has not been seen yet, and its activation will fail an
-- elaboration check.
if Is_Task_Type (Desig_T)
and then Scope (Base_Type (Desig_T)) = Current_Scope
and then Is_Compilation_Unit (Current_Scope)
and then Ekind (Current_Scope) = E_Package
and then not In_Package_Body (Current_Scope)
then
Error_Msg_Warn := SPARK_Mode /= On;
Error_Msg_N ("cannot activate task before body seen<<", N);
Error_Msg_N ("\Program_Error [<<", N);
end if;
-- Ada 2012 (AI05-0111-3): Detect an attempt to allocate a task or a
-- type with a task component on a subpool. This action must raise
-- Program_Error at runtime.
if Ada_Version >= Ada_2012
and then Nkind (N) = N_Allocator
and then Present (Subpool_Handle_Name (N))
and then Has_Task (Desig_T)
then
Error_Msg_Warn := SPARK_Mode /= On;
Error_Msg_N ("cannot allocate task on subpool<<", N);
Error_Msg_N ("\Program_Error [<<", N);
Rewrite (N,
Make_Raise_Program_Error (Sloc (N),
Reason => PE_Explicit_Raise));
Set_Etype (N, Typ);
end if;
end Resolve_Allocator;
---------------------------
-- Resolve_Arithmetic_Op --
---------------------------
-- Used for resolving all arithmetic operators except exponentiation
procedure Resolve_Arithmetic_Op (N : Node_Id; Typ : Entity_Id) is
L : constant Node_Id := Left_Opnd (N);
R : constant Node_Id := Right_Opnd (N);
TL : constant Entity_Id := Base_Type (Etype (L));
TR : constant Entity_Id := Base_Type (Etype (R));
T : Entity_Id;
Rop : Node_Id;
B_Typ : constant Entity_Id := Base_Type (Typ);
-- We do the resolution using the base type, because intermediate values
-- in expressions always are of the base type, not a subtype of it.
function Expected_Type_Is_Any_Real (N : Node_Id) return Boolean;
-- Returns True if N is in a context that expects "any real type"
function Is_Integer_Or_Universal (N : Node_Id) return Boolean;
-- Return True iff given type is Integer or universal real/integer
procedure Set_Mixed_Mode_Operand (N : Node_Id; T : Entity_Id);
-- Choose type of integer literal in fixed-point operation to conform
-- to available fixed-point type. T is the type of the other operand,
-- which is needed to determine the expected type of N.
procedure Set_Operand_Type (N : Node_Id);
-- Set operand type to T if universal
-------------------------------
-- Expected_Type_Is_Any_Real --
-------------------------------
function Expected_Type_Is_Any_Real (N : Node_Id) return Boolean is
begin
-- N is the expression after "delta" in a fixed_point_definition;
-- see RM-3.5.9(6):
return Nkind (Parent (N)) in N_Ordinary_Fixed_Point_Definition
| N_Decimal_Fixed_Point_Definition
-- N is one of the bounds in a real_range_specification;
-- see RM-3.5.7(5):
| N_Real_Range_Specification
-- N is the expression of a delta_constraint;
-- see RM-J.3(3):
| N_Delta_Constraint;
end Expected_Type_Is_Any_Real;
-----------------------------
-- Is_Integer_Or_Universal --
-----------------------------
function Is_Integer_Or_Universal (N : Node_Id) return Boolean is
T : Entity_Id;
Index : Interp_Index;
It : Interp;
begin
if not Is_Overloaded (N) then
T := Etype (N);
return Base_Type (T) = Base_Type (Standard_Integer)
or else T = Universal_Integer
or else T = Universal_Real;
else
Get_First_Interp (N, Index, It);
while Present (It.Typ) loop
if Base_Type (It.Typ) = Base_Type (Standard_Integer)
or else It.Typ = Universal_Integer
or else It.Typ = Universal_Real
then
return True;
end if;
Get_Next_Interp (Index, It);
end loop;
end if;
return False;
end Is_Integer_Or_Universal;
----------------------------
-- Set_Mixed_Mode_Operand --
----------------------------
procedure Set_Mixed_Mode_Operand (N : Node_Id; T : Entity_Id) is
Index : Interp_Index;
It : Interp;
begin
if Universal_Interpretation (N) = Universal_Integer then
-- A universal integer literal is resolved as standard integer
-- except in the case of a fixed-point result, where we leave it
-- as universal (to be handled by Exp_Fixd later on)
if Is_Fixed_Point_Type (T) then
Resolve (N, Universal_Integer);
else
Resolve (N, Standard_Integer);
end if;
elsif Universal_Interpretation (N) = Universal_Real
and then (T = Base_Type (Standard_Integer)
or else T = Universal_Integer
or else T = Universal_Real)
then
-- A universal real can appear in a fixed-type context. We resolve
-- the literal with that context, even though this might raise an
-- exception prematurely (the other operand may be zero).
Resolve (N, B_Typ);
elsif Etype (N) = Base_Type (Standard_Integer)
and then T = Universal_Real
and then Is_Overloaded (N)
then
-- Integer arg in mixed-mode operation. Resolve with universal
-- type, in case preference rule must be applied.
Resolve (N, Universal_Integer);
elsif Etype (N) = T and then B_Typ /= Universal_Fixed then
-- If the operand is part of a fixed multiplication operation,
-- a conversion will be applied to each operand, so resolve it
-- with its own type.
if Nkind (Parent (N)) in N_Op_Divide | N_Op_Multiply then
Resolve (N);
else
-- Not a mixed-mode operation, resolve with context
Resolve (N, B_Typ);
end if;
elsif Etype (N) = Any_Fixed then
-- N may itself be a mixed-mode operation, so use context type
Resolve (N, B_Typ);
elsif Is_Fixed_Point_Type (T)
and then B_Typ = Universal_Fixed
and then Is_Overloaded (N)
then
-- Must be (fixed * fixed) operation, operand must have one
-- compatible interpretation.
Resolve (N, Any_Fixed);
elsif Is_Fixed_Point_Type (B_Typ)
and then (T = Universal_Real or else Is_Fixed_Point_Type (T))
and then Is_Overloaded (N)
then
-- C * F(X) in a fixed context, where C is a real literal or a
-- fixed-point expression. F must have either a fixed type
-- interpretation or an integer interpretation, but not both.
Get_First_Interp (N, Index, It);
while Present (It.Typ) loop
if Base_Type (It.Typ) = Base_Type (Standard_Integer) then
if Analyzed (N) then
Error_Msg_N ("ambiguous operand in fixed operation", N);
else
Resolve (N, Standard_Integer);
end if;
elsif Is_Fixed_Point_Type (It.Typ) then
if Analyzed (N) then
Error_Msg_N ("ambiguous operand in fixed operation", N);
else
Resolve (N, It.Typ);
end if;
end if;
Get_Next_Interp (Index, It);
end loop;
-- Reanalyze the literal with the fixed type of the context. If
-- context is Universal_Fixed, we are within a conversion, leave
-- the literal as a universal real because there is no usable
-- fixed type, and the target of the conversion plays no role in
-- the resolution.
declare
Op2 : Node_Id;
T2 : Entity_Id;
begin
if N = L then
Op2 := R;
else
Op2 := L;
end if;
if B_Typ = Universal_Fixed
and then Nkind (Op2) = N_Real_Literal
then
T2 := Universal_Real;
else
T2 := B_Typ;
end if;
Set_Analyzed (Op2, False);
Resolve (Op2, T2);
end;
-- A universal real conditional expression can appear in a fixed-type
-- context and must be resolved with that context to facilitate the
-- code generation in the back end. However, If the context is
-- Universal_fixed (i.e. as an operand of a multiplication/division
-- involving a fixed-point operand) the conditional expression must
-- resolve to a unique visible fixed_point type, normally Duration.
elsif Nkind (N) in N_Case_Expression | N_If_Expression
and then Etype (N) = Universal_Real
and then Is_Fixed_Point_Type (B_Typ)
then
if B_Typ = Universal_Fixed then
Resolve (N, Unique_Fixed_Point_Type (N));
else
Resolve (N, B_Typ);
end if;
else
Resolve (N);
end if;
end Set_Mixed_Mode_Operand;
----------------------
-- Set_Operand_Type --
----------------------
procedure Set_Operand_Type (N : Node_Id) is
begin
if Etype (N) = Universal_Integer
or else Etype (N) = Universal_Real
then
Set_Etype (N, T);
end if;
end Set_Operand_Type;
-- Start of processing for Resolve_Arithmetic_Op
begin
if Comes_From_Source (N)
and then Ekind (Entity (N)) = E_Function
and then Is_Imported (Entity (N))
and then Is_Intrinsic_Subprogram (Entity (N))
then
Resolve_Intrinsic_Operator (N, Typ);
return;
-- Special-case for mixed-mode universal expressions or fixed point type
-- operation: each argument is resolved separately. The same treatment
-- is required if one of the operands of a fixed point operation is
-- universal real, since in this case we don't do a conversion to a
-- specific fixed-point type (instead the expander handles the case).
-- Set the type of the node to its universal interpretation because
-- legality checks on an exponentiation operand need the context.
elsif (B_Typ = Universal_Integer or else B_Typ = Universal_Real)
and then Present (Universal_Interpretation (L))
and then Present (Universal_Interpretation (R))
then
Set_Etype (N, B_Typ);
Resolve (L, Universal_Interpretation (L));
Resolve (R, Universal_Interpretation (R));
elsif (B_Typ = Universal_Real
or else Etype (N) = Universal_Fixed
or else (Etype (N) = Any_Fixed
and then Is_Fixed_Point_Type (B_Typ))
or else (Is_Fixed_Point_Type (B_Typ)
and then (Is_Integer_Or_Universal (L)
or else
Is_Integer_Or_Universal (R))))
and then Nkind (N) in N_Op_Multiply | N_Op_Divide
then
if TL = Universal_Integer or else TR = Universal_Integer then
Check_For_Visible_Operator (N, B_Typ);
end if;
-- If context is a fixed type and one operand is integer, the other
-- is resolved with the type of the context.
if Is_Fixed_Point_Type (B_Typ)
and then (Base_Type (TL) = Base_Type (Standard_Integer)
or else TL = Universal_Integer)
then
Resolve (R, B_Typ);
Resolve (L, TL);
elsif Is_Fixed_Point_Type (B_Typ)
and then (Base_Type (TR) = Base_Type (Standard_Integer)
or else TR = Universal_Integer)
then
Resolve (L, B_Typ);
Resolve (R, TR);
-- If both operands are universal and the context is a floating
-- point type, the operands are resolved to the type of the context.
elsif Is_Floating_Point_Type (B_Typ) then
Resolve (L, B_Typ);
Resolve (R, B_Typ);
else
Set_Mixed_Mode_Operand (L, TR);
Set_Mixed_Mode_Operand (R, TL);
end if;
-- Check the rule in RM05-4.5.5(19.1/2) disallowing universal_fixed
-- multiplying operators from being used when the expected type is
-- also universal_fixed. Note that B_Typ will be Universal_Fixed in
-- some cases where the expected type is actually Any_Real;
-- Expected_Type_Is_Any_Real takes care of that case.
if Etype (N) = Universal_Fixed
or else Etype (N) = Any_Fixed
then
if B_Typ = Universal_Fixed
and then not Expected_Type_Is_Any_Real (N)
and then Nkind (Parent (N)) not in
N_Type_Conversion | N_Unchecked_Type_Conversion
then
Error_Msg_N ("type cannot be determined from context!", N);
Error_Msg_N ("\explicit conversion to result type required", N);
Set_Etype (L, Any_Type);
Set_Etype (R, Any_Type);
else
if Ada_Version = Ada_83
and then Etype (N) = Universal_Fixed
and then Nkind (Parent (N)) not in
N_Type_Conversion | N_Unchecked_Type_Conversion
then
Error_Msg_N
("(Ada 83) fixed-point operation needs explicit "
& "conversion", N);
end if;
-- The expected type is "any real type" in contexts like
-- type T is delta <universal_fixed-expression> ...
-- in which case we need to set the type to Universal_Real
-- so that static expression evaluation will work properly.
if Expected_Type_Is_Any_Real (N) then
Set_Etype (N, Universal_Real);
else
Set_Etype (N, B_Typ);
end if;
end if;
elsif Is_Fixed_Point_Type (B_Typ)
and then (Is_Integer_Or_Universal (L)
or else Nkind (L) = N_Real_Literal
or else Nkind (R) = N_Real_Literal
or else Is_Integer_Or_Universal (R))
then
Set_Etype (N, B_Typ);
elsif Etype (N) = Any_Fixed then
-- If no previous errors, this is only possible if one operand is
-- overloaded and the context is universal. Resolve as such.
Set_Etype (N, B_Typ);
end if;
else
if (TL = Universal_Integer or else TL = Universal_Real)
and then
(TR = Universal_Integer or else TR = Universal_Real)
then
Check_For_Visible_Operator (N, B_Typ);
end if;
-- If the context is Universal_Fixed and the operands are also
-- universal fixed, this is an error, unless there is only one
-- applicable fixed_point type (usually Duration).
if B_Typ = Universal_Fixed and then Etype (L) = Universal_Fixed then
T := Unique_Fixed_Point_Type (N);
if T = Any_Type then
Set_Etype (N, T);
return;
else
Resolve (L, T);
Resolve (R, T);
end if;
else
Resolve (L, B_Typ);
Resolve (R, B_Typ);
end if;
-- If one of the arguments was resolved to a non-universal type.
-- label the result of the operation itself with the same type.
-- Do the same for the universal argument, if any.
T := Intersect_Types (L, R);
Set_Etype (N, Base_Type (T));
Set_Operand_Type (L);
Set_Operand_Type (R);
end if;
Generate_Operator_Reference (N, Typ);
Analyze_Dimension (N);
Eval_Arithmetic_Op (N);
-- Set overflow and division checking bit
if Nkind (N) in N_Op then
if not Overflow_Checks_Suppressed (Etype (N)) then
Enable_Overflow_Check (N);
end if;
-- Give warning if explicit division by zero
if Nkind (N) in N_Op_Divide | N_Op_Rem | N_Op_Mod
and then not Division_Checks_Suppressed (Etype (N))
then
Rop := Right_Opnd (N);
if Compile_Time_Known_Value (Rop)
and then ((Is_Integer_Type (Etype (Rop))
and then Expr_Value (Rop) = Uint_0)
or else
(Is_Real_Type (Etype (Rop))
and then Expr_Value_R (Rop) = Ureal_0))
then
-- Specialize the warning message according to the operation.
-- When SPARK_Mode is On, force a warning instead of an error
-- in that case, as this likely corresponds to deactivated
-- code. The following warnings are for the case
case Nkind (N) is
when N_Op_Divide =>
-- For division, we have two cases, for float division
-- of an unconstrained float type, on a machine where
-- Machine_Overflows is false, we don't get an exception
-- at run-time, but rather an infinity or Nan. The Nan
-- case is pretty obscure, so just warn about infinities.
if Is_Floating_Point_Type (Typ)
and then not Is_Constrained (Typ)
and then not Machine_Overflows_On_Target
then
Error_Msg_N
("float division by zero, may generate "
& "'+'/'- infinity??", Right_Opnd (N));
-- For all other cases, we get a Constraint_Error
else
Apply_Compile_Time_Constraint_Error
(N, "division by zero??", CE_Divide_By_Zero,
Loc => Sloc (Right_Opnd (N)),
Warn => SPARK_Mode = On);
end if;
when N_Op_Rem =>
Apply_Compile_Time_Constraint_Error
(N, "rem with zero divisor??", CE_Divide_By_Zero,
Loc => Sloc (Right_Opnd (N)),
Warn => SPARK_Mode = On);
when N_Op_Mod =>
Apply_Compile_Time_Constraint_Error
(N, "mod with zero divisor??", CE_Divide_By_Zero,
Loc => Sloc (Right_Opnd (N)),
Warn => SPARK_Mode = On);
-- Division by zero can only happen with division, rem,
-- and mod operations.
when others =>
raise Program_Error;
end case;
-- In GNATprove mode, we enable the division check so that
-- GNATprove will issue a message if it cannot be proved.
if GNATprove_Mode then
Activate_Division_Check (N);
end if;
-- Otherwise just set the flag to check at run time
else
Activate_Division_Check (N);
end if;
end if;
-- If Restriction No_Implicit_Conditionals is active, then it is
-- violated if either operand can be negative for mod, or for rem
-- if both operands can be negative.
if Restriction_Check_Required (No_Implicit_Conditionals)
and then Nkind (N) in N_Op_Rem | N_Op_Mod
then
declare
Lo : Uint;
Hi : Uint;
OK : Boolean;
LNeg : Boolean;
RNeg : Boolean;
-- Set if corresponding operand might be negative
begin
Determine_Range
(Left_Opnd (N), OK, Lo, Hi, Assume_Valid => True);
LNeg := (not OK) or else Lo < 0;
Determine_Range
(Right_Opnd (N), OK, Lo, Hi, Assume_Valid => True);
RNeg := (not OK) or else Lo < 0;
-- Check if we will be generating conditionals. There are two
-- cases where that can happen, first for REM, the only case
-- is largest negative integer mod -1, where the division can
-- overflow, but we still have to give the right result. The
-- front end generates a test for this annoying case. Here we
-- just test if both operands can be negative (that's what the
-- expander does, so we match its logic here).
-- The second case is mod where either operand can be negative.
-- In this case, the back end has to generate additional tests.
if (Nkind (N) = N_Op_Rem and then (LNeg and RNeg))
or else
(Nkind (N) = N_Op_Mod and then (LNeg or RNeg))
then
Check_Restriction (No_Implicit_Conditionals, N);
end if;
end;
end if;
end if;
Check_Unset_Reference (L);
Check_Unset_Reference (R);
end Resolve_Arithmetic_Op;
------------------
-- Resolve_Call --
------------------
procedure Resolve_Call (N : Node_Id; Typ : Entity_Id) is
Loc : constant Source_Ptr := Sloc (N);
Subp : constant Node_Id := Name (N);
Body_Id : Entity_Id;
I : Interp_Index;
It : Interp;
Nam : Entity_Id;
Nam_Decl : Node_Id;
Nam_UA : Entity_Id;
Norm_OK : Boolean;
Rtype : Entity_Id;
Scop : Entity_Id;
begin
-- Preserve relevant elaboration-related attributes of the context which
-- are no longer available or very expensive to recompute once analysis,
-- resolution, and expansion are over.
Mark_Elaboration_Attributes
(N_Id => N,
Checks => True,
Modes => True,
Warnings => True);
-- The context imposes a unique interpretation with type Typ on a
-- procedure or function call. Find the entity of the subprogram that
-- yields the expected type, and propagate the corresponding formal
-- constraints on the actuals. The caller has established that an
-- interpretation exists, and emitted an error if not unique.
-- First deal with the case of a call to an access-to-subprogram,
-- dereference made explicit in Analyze_Call.
if Ekind (Etype (Subp)) = E_Subprogram_Type then
if not Is_Overloaded (Subp) then
Nam := Etype (Subp);
else
-- Find the interpretation whose type (a subprogram type) has a
-- return type that is compatible with the context. Analysis of
-- the node has established that one exists.
Nam := Empty;
Get_First_Interp (Subp, I, It);
while Present (It.Typ) loop
if Covers (Typ, Etype (It.Typ)) then
Nam := It.Typ;
exit;
end if;
Get_Next_Interp (I, It);
end loop;
if No (Nam) then
raise Program_Error;
end if;
end if;
-- If the prefix is not an entity, then resolve it
if not Is_Entity_Name (Subp) then
Resolve (Subp, Nam);
end if;
-- For an indirect call, we always invalidate checks, since we do not
-- know whether the subprogram is local or global. Yes we could do
-- better here, e.g. by knowing that there are no local subprograms,
-- but it does not seem worth the effort. Similarly, we kill all
-- knowledge of current constant values.
Kill_Current_Values;
-- If this is a procedure call which is really an entry call, do
-- the conversion of the procedure call to an entry call. Protected
-- operations use the same circuitry because the name in the call
-- can be an arbitrary expression with special resolution rules.
elsif Nkind (Subp) in N_Selected_Component | N_Indexed_Component
or else (Is_Entity_Name (Subp) and then Is_Entry (Entity (Subp)))
then
Resolve_Entry_Call (N, Typ);
if Legacy_Elaboration_Checks then
Check_Elab_Call (N);
end if;
-- Annotate the tree by creating a call marker in case the original
-- call is transformed by expansion. The call marker is automatically
-- saved for later examination by the ABE Processing phase.
Build_Call_Marker (N);
-- Kill checks and constant values, as above for indirect case
-- Who knows what happens when another task is activated?
Kill_Current_Values;
return;
-- Normal subprogram call with name established in Resolve
elsif not (Is_Type (Entity (Subp))) then
Nam := Entity (Subp);
Set_Entity_With_Checks (Subp, Nam);
-- Otherwise we must have the case of an overloaded call
else
pragma Assert (Is_Overloaded (Subp));
-- Initialize Nam to prevent warning (we know it will be assigned
-- in the loop below, but the compiler does not know that).
Nam := Empty;
Get_First_Interp (Subp, I, It);
while Present (It.Typ) loop
if Covers (Typ, It.Typ) then
Nam := It.Nam;
Set_Entity_With_Checks (Subp, Nam);
exit;
end if;
Get_Next_Interp (I, It);
end loop;
end if;
-- Check that a call to Current_Task does not occur in an entry body
if Is_RTE (Nam, RE_Current_Task) then
declare
P : Node_Id;
begin
P := N;
loop
P := Parent (P);
-- Exclude calls that occur within the default of a formal
-- parameter of the entry, since those are evaluated outside
-- of the body.
exit when No (P) or else Nkind (P) = N_Parameter_Specification;
if Nkind (P) = N_Entry_Body
or else (Nkind (P) = N_Subprogram_Body
and then Is_Entry_Barrier_Function (P))
then
Rtype := Etype (N);
Error_Msg_Warn := SPARK_Mode /= On;
Error_Msg_NE
("& should not be used in entry body (RM C.7(17))<<",
N, Nam);
Error_Msg_NE ("\Program_Error [<<", N, Nam);
Rewrite (N,
Make_Raise_Program_Error (Loc,
Reason => PE_Current_Task_In_Entry_Body));
Set_Etype (N, Rtype);
return;
end if;
end loop;
end;
end if;
-- Check that a procedure call does not occur in the context of the
-- entry call statement of a conditional or timed entry call. Note that
-- the case of a call to a subprogram renaming of an entry will also be
-- rejected. The test for N not being an N_Entry_Call_Statement is
-- defensive, covering the possibility that the processing of entry
-- calls might reach this point due to later modifications of the code
-- above.
if Nkind (Parent (N)) = N_Entry_Call_Alternative
and then Nkind (N) /= N_Entry_Call_Statement
and then Entry_Call_Statement (Parent (N)) = N
then
if Ada_Version < Ada_2005 then
Error_Msg_N ("entry call required in select statement", N);
-- Ada 2005 (AI-345): If a procedure_call_statement is used
-- for a procedure_or_entry_call, the procedure_name or
-- procedure_prefix of the procedure_call_statement shall denote
-- an entry renamed by a procedure, or (a view of) a primitive
-- subprogram of a limited interface whose first parameter is
-- a controlling parameter.
elsif Nkind (N) = N_Procedure_Call_Statement
and then not Is_Renamed_Entry (Nam)
and then not Is_Controlling_Limited_Procedure (Nam)
then
Error_Msg_N
("entry call or dispatching primitive of interface required", N);
end if;
end if;
-- Check that this is not a call to a protected procedure or entry from
-- within a protected function.
Check_Internal_Protected_Use (N, Nam);
-- Freeze the subprogram name if not in a spec-expression. Note that
-- we freeze procedure calls as well as function calls. Procedure calls
-- are not frozen according to the rules (RM 13.14(14)) because it is
-- impossible to have a procedure call to a non-frozen procedure in
-- pure Ada, but in the code that we generate in the expander, this
-- rule needs extending because we can generate procedure calls that
-- need freezing.
-- In Ada 2012, expression functions may be called within pre/post
-- conditions of subsequent functions or expression functions. Such
-- calls do not freeze when they appear within generated bodies,
-- (including the body of another expression function) which would
-- place the freeze node in the wrong scope. An expression function
-- is frozen in the usual fashion, by the appearance of a real body,
-- or at the end of a declarative part. However an implicit call to
-- an expression function may appear when it is part of a default
-- expression in a call to an initialization procedure, and must be
-- frozen now, even if the body is inserted at a later point.
-- Otherwise, the call freezes the expression if expander is active,
-- for example as part of an object declaration.
if Is_Entity_Name (Subp)
and then not In_Spec_Expression
and then not Is_Expression_Function_Or_Completion (Current_Scope)
and then
(not Is_Expression_Function_Or_Completion (Entity (Subp))
or else Expander_Active)
then
if Is_Expression_Function (Entity (Subp)) then
-- Force freeze of expression function in call
Set_Comes_From_Source (Subp, True);
Set_Must_Not_Freeze (Subp, False);
end if;
Freeze_Expression (Subp);
end if;
-- For a predefined operator, the type of the result is the type imposed
-- by context, except for a predefined operation on universal fixed.
-- Otherwise the type of the call is the type returned by the subprogram
-- being called.
if Is_Predefined_Op (Nam) then
if Etype (N) /= Universal_Fixed then
Set_Etype (N, Typ);
end if;
-- If the subprogram returns an array type, and the context requires the
-- component type of that array type, the node is really an indexing of
-- the parameterless call. Resolve as such. A pathological case occurs
-- when the type of the component is an access to the array type. In
-- this case the call is truly ambiguous. If the call is to an intrinsic
-- subprogram, it can't be an indexed component. This check is necessary
-- because if it's Unchecked_Conversion, and we have "type T_Ptr is
-- access T;" and "type T is array (...) of T_Ptr;" (i.e. an array of
-- pointers to the same array), the compiler gets confused and does an
-- infinite recursion.
elsif (Needs_No_Actuals (Nam) or else Needs_One_Actual (Nam))
and then
((Is_Array_Type (Etype (Nam))
and then Covers (Typ, Component_Type (Etype (Nam))))
or else
(Is_Access_Type (Etype (Nam))
and then Is_Array_Type (Designated_Type (Etype (Nam)))
and then
Covers (Typ, Component_Type (Designated_Type (Etype (Nam))))
and then not Is_Intrinsic_Subprogram (Entity (Subp))))
then
declare
Index_Node : Node_Id;
New_Subp : Node_Id;
Ret_Type : constant Entity_Id := Etype (Nam);
begin
-- If this is a parameterless call there is no ambiguity and the
-- call has the type of the function.
if No (First_Actual (N)) then
Set_Etype (N, Etype (Nam));
if Present (First_Formal (Nam)) then
Resolve_Actuals (N, Nam);
end if;
-- Annotate the tree by creating a call marker in case the
-- original call is transformed by expansion. The call marker
-- is automatically saved for later examination by the ABE
-- Processing phase.
Build_Call_Marker (N);
elsif Is_Access_Type (Ret_Type)
and then Ret_Type = Component_Type (Designated_Type (Ret_Type))
then
Error_Msg_N
("cannot disambiguate function call and indexing", N);
else
New_Subp := Relocate_Node (Subp);
-- The called entity may be an explicit dereference, in which
-- case there is no entity to set.
if Nkind (New_Subp) /= N_Explicit_Dereference then
Set_Entity (Subp, Nam);
end if;
if (Is_Array_Type (Ret_Type)
and then Component_Type (Ret_Type) /= Any_Type)
or else
(Is_Access_Type (Ret_Type)
and then
Component_Type (Designated_Type (Ret_Type)) /= Any_Type)
then
if Needs_No_Actuals (Nam) then
-- Indexed call to a parameterless function
Index_Node :=
Make_Indexed_Component (Loc,
Prefix =>
Make_Function_Call (Loc, Name => New_Subp),
Expressions => Parameter_Associations (N));
else
-- An Ada 2005 prefixed call to a primitive operation
-- whose first parameter is the prefix. This prefix was
-- prepended to the parameter list, which is actually a
-- list of indexes. Remove the prefix in order to build
-- the proper indexed component.
Index_Node :=
Make_Indexed_Component (Loc,
Prefix =>
Make_Function_Call (Loc,
Name => New_Subp,
Parameter_Associations =>
New_List
(Remove_Head (Parameter_Associations (N)))),
Expressions => Parameter_Associations (N));
end if;
-- Preserve the parenthesis count of the node
Set_Paren_Count (Index_Node, Paren_Count (N));
-- Since we are correcting a node classification error made
-- by the parser, we call Replace rather than Rewrite.
Replace (N, Index_Node);
Set_Etype (Prefix (N), Ret_Type);
Set_Etype (N, Typ);
if Legacy_Elaboration_Checks then
Check_Elab_Call (Prefix (N));
end if;
-- Annotate the tree by creating a call marker in case
-- the original call is transformed by expansion. The call
-- marker is automatically saved for later examination by
-- the ABE Processing phase.
Build_Call_Marker (Prefix (N));
Resolve_Indexed_Component (N, Typ);
end if;
end if;
return;
end;
else
-- If the called function is not declared in the main unit and it
-- returns the limited view of type then use the available view (as
-- is done in Try_Object_Operation) to prevent back-end confusion;
-- for the function entity itself. The call must appear in a context
-- where the nonlimited view is available. If the function entity is
-- in the extended main unit then no action is needed, because the
-- back end handles this case. In either case the type of the call
-- is the nonlimited view.
if From_Limited_With (Etype (Nam))
and then Present (Available_View (Etype (Nam)))
then
Set_Etype (N, Available_View (Etype (Nam)));
if not In_Extended_Main_Code_Unit (Nam) then
Set_Etype (Nam, Available_View (Etype (Nam)));
end if;
else
Set_Etype (N, Etype (Nam));
end if;
end if;
-- In the case where the call is to an overloaded subprogram, Analyze
-- calls Normalize_Actuals once per overloaded subprogram. Therefore in
-- such a case Normalize_Actuals needs to be called once more to order
-- the actuals correctly. Otherwise the call will have the ordering
-- given by the last overloaded subprogram whether this is the correct
-- one being called or not.
if Is_Overloaded (Subp) then
Normalize_Actuals (N, Nam, False, Norm_OK);
pragma Assert (Norm_OK);
end if;
-- In any case, call is fully resolved now. Reset Overload flag, to
-- prevent subsequent overload resolution if node is analyzed again
Set_Is_Overloaded (Subp, False);
Set_Is_Overloaded (N, False);
-- A Ghost entity must appear in a specific context
if Is_Ghost_Entity (Nam) and then Comes_From_Source (N) then
Check_Ghost_Context (Nam, N);
end if;
-- If we are calling the current subprogram from immediately within its
-- body, then that is the case where we can sometimes detect cases of
-- infinite recursion statically. Do not try this in case restriction
-- No_Recursion is in effect anyway, and do it only for source calls.
if Comes_From_Source (N) then
Scop := Current_Scope;
-- Issue warning for possible infinite recursion in the absence
-- of the No_Recursion restriction.
if Same_Or_Aliased_Subprograms (Nam, Scop)
and then not Restriction_Active (No_Recursion)
and then not Is_Static_Function (Scop)
and then Check_Infinite_Recursion (N)
then
-- Here we detected and flagged an infinite recursion, so we do
-- not need to test the case below for further warnings. Also we
-- are all done if we now have a raise SE node.
if Nkind (N) = N_Raise_Storage_Error then
return;
end if;
-- If call is to immediately containing subprogram, then check for
-- the case of a possible run-time detectable infinite recursion.
else
Scope_Loop : while Scop /= Standard_Standard loop
if Same_Or_Aliased_Subprograms (Nam, Scop) then
-- Ada 202x (AI12-0075): Static functions are never allowed
-- to make a recursive call, as specified by 6.8(5.4/5).
if Is_Static_Function (Scop) then
Error_Msg_N
("recursive call not allowed in static expression "
& "function", N);
Set_Error_Posted (Scop);
exit Scope_Loop;
end if;
-- Although in general case, recursion is not statically
-- checkable, the case of calling an immediately containing
-- subprogram is easy to catch.
if not Is_Ignored_Ghost_Entity (Nam) then
Check_Restriction (No_Recursion, N);
end if;
-- If the recursive call is to a parameterless subprogram,
-- then even if we can't statically detect infinite
-- recursion, this is pretty suspicious, and we output a
-- warning. Furthermore, we will try later to detect some
-- cases here at run time by expanding checking code (see
-- Detect_Infinite_Recursion in package Exp_Ch6).
-- If the recursive call is within a handler, do not emit a
-- warning, because this is a common idiom: loop until input
-- is correct, catch illegal input in handler and restart.
if No (First_Formal (Nam))
and then Etype (Nam) = Standard_Void_Type
and then not Error_Posted (N)
and then Nkind (Parent (N)) /= N_Exception_Handler
then
-- For the case of a procedure call. We give the message
-- only if the call is the first statement in a sequence
-- of statements, or if all previous statements are
-- simple assignments. This is simply a heuristic to
-- decrease false positives, without losing too many good
-- warnings. The idea is that these previous statements
-- may affect global variables the procedure depends on.
-- We also exclude raise statements, that may arise from
-- constraint checks and are probably unrelated to the
-- intended control flow.
if Nkind (N) = N_Procedure_Call_Statement
and then Is_List_Member (N)
then
declare
P : Node_Id;
begin
P := Prev (N);
while Present (P) loop
if Nkind (P) not in N_Assignment_Statement
| N_Raise_Constraint_Error
then
exit Scope_Loop;
end if;
Prev (P);
end loop;
end;
end if;
-- Do not give warning if we are in a conditional context
declare
K : constant Node_Kind := Nkind (Parent (N));
begin
if (K = N_Loop_Statement
and then Present (Iteration_Scheme (Parent (N))))
or else K = N_If_Statement
or else K = N_Elsif_Part
or else K = N_Case_Statement_Alternative
then
exit Scope_Loop;
end if;
end;
-- Here warning is to be issued
Set_Has_Recursive_Call (Nam);
Error_Msg_Warn := SPARK_Mode /= On;
Error_Msg_N ("possible infinite recursion<<!", N);
Error_Msg_N ("\Storage_Error ]<<!", N);
end if;
exit Scope_Loop;
end if;
Scop := Scope (Scop);
end loop Scope_Loop;
end if;
end if;
-- Check obsolescent reference to Ada.Characters.Handling subprogram
Check_Obsolescent_2005_Entity (Nam, Subp);
-- If subprogram name is a predefined operator, it was given in
-- functional notation. Replace call node with operator node, so
-- that actuals can be resolved appropriately.
if Is_Predefined_Op (Nam) or else Ekind (Nam) = E_Operator then
Make_Call_Into_Operator (N, Typ, Entity (Name (N)));
return;
elsif Present (Alias (Nam))
and then Is_Predefined_Op (Alias (Nam))
then
Resolve_Actuals (N, Nam);
Make_Call_Into_Operator (N, Typ, Alias (Nam));
return;
end if;
-- Create a transient scope if the resulting type requires it
-- There are several notable exceptions:
-- a) In init procs, the transient scope overhead is not needed, and is
-- even incorrect when the call is a nested initialization call for a
-- component whose expansion may generate adjust calls. However, if the
-- call is some other procedure call within an initialization procedure
-- (for example a call to Create_Task in the init_proc of the task
-- run-time record) a transient scope must be created around this call.
-- b) Enumeration literal pseudo-calls need no transient scope
-- c) Intrinsic subprograms (Unchecked_Conversion and source info
-- functions) do not use the secondary stack even though the return
-- type may be unconstrained.
-- d) Calls to a build-in-place function, since such functions may
-- allocate their result directly in a target object, and cases where
-- the result does get allocated in the secondary stack are checked for
-- within the specialized Exp_Ch6 procedures for expanding those
-- build-in-place calls.
-- e) Calls to inlinable expression functions do not use the secondary
-- stack (since the call will be replaced by its returned object).
-- f) If the subprogram is marked Inline_Always, then even if it returns
-- an unconstrained type the call does not require use of the secondary
-- stack. However, inlining will only take place if the body to inline
-- is already present. It may not be available if e.g. the subprogram is
-- declared in a child instance.
-- g) If the subprogram is a static expression function and the call is
-- a static call (the actuals are all static expressions), then we never
-- want to create a transient scope (this could occur in the case of a
-- static string-returning call).
if Is_Inlined (Nam)
and then Has_Pragma_Inline (Nam)
and then Nkind (Unit_Declaration_Node (Nam)) = N_Subprogram_Declaration
and then Present (Body_To_Inline (Unit_Declaration_Node (Nam)))
then
null;
elsif Ekind (Nam) = E_Enumeration_Literal
or else Is_Build_In_Place_Function (Nam)
or else Is_Intrinsic_Subprogram (Nam)
or else Is_Inlinable_Expression_Function (Nam)
or else Is_Static_Function_Call (N)
then
null;
-- A return statement from an ignored Ghost function does not use the
-- secondary stack (or any other one).
elsif Expander_Active
and then Ekind (Nam) in E_Function | E_Subprogram_Type
and then Requires_Transient_Scope (Etype (Nam))
and then not Is_Ignored_Ghost_Entity (Nam)
then
Establish_Transient_Scope (N, Manage_Sec_Stack => True);
-- If the call appears within the bounds of a loop, it will be
-- rewritten and reanalyzed, nothing left to do here.
if Nkind (N) /= N_Function_Call then
return;
end if;
end if;
-- A protected function cannot be called within the definition of the
-- enclosing protected type, unless it is part of a pre/postcondition
-- on another protected operation. This may appear in the entry wrapper
-- created for an entry with preconditions.
if Is_Protected_Type (Scope (Nam))
and then In_Open_Scopes (Scope (Nam))
and then not Has_Completion (Scope (Nam))
and then not In_Spec_Expression
and then not Is_Entry_Wrapper (Current_Scope)
then
Error_Msg_NE
("& cannot be called before end of protected definition", N, Nam);
end if;
-- Propagate interpretation to actuals, and add default expressions
-- where needed.
if Present (First_Formal (Nam)) then
Resolve_Actuals (N, Nam);
-- Overloaded literals are rewritten as function calls, for purpose of
-- resolution. After resolution, we can replace the call with the
-- literal itself.
elsif Ekind (Nam) = E_Enumeration_Literal then
Copy_Node (Subp, N);
Resolve_Entity_Name (N, Typ);
-- Avoid validation, since it is a static function call
Generate_Reference (Nam, Subp);
return;
end if;
-- If the subprogram is not global, then kill all saved values and
-- checks. This is a bit conservative, since in many cases we could do
-- better, but it is not worth the effort. Similarly, we kill constant
-- values. However we do not need to do this for internal entities
-- (unless they are inherited user-defined subprograms), since they
-- are not in the business of molesting local values.
-- If the flag Suppress_Value_Tracking_On_Calls is set, then we also
-- kill all checks and values for calls to global subprograms. This
-- takes care of the case where an access to a local subprogram is
-- taken, and could be passed directly or indirectly and then called
-- from almost any context.
-- Note: we do not do this step till after resolving the actuals. That
-- way we still take advantage of the current value information while
-- scanning the actuals.
-- We suppress killing values if we are processing the nodes associated
-- with N_Freeze_Entity nodes. Otherwise the declaration of a tagged
-- type kills all the values as part of analyzing the code that
-- initializes the dispatch tables.
if Inside_Freezing_Actions = 0
and then (not Is_Library_Level_Entity (Nam)
or else Suppress_Value_Tracking_On_Call
(Nearest_Dynamic_Scope (Current_Scope)))
and then (Comes_From_Source (Nam)
or else (Present (Alias (Nam))
and then Comes_From_Source (Alias (Nam))))
then
Kill_Current_Values;
end if;
-- If we are warning about unread OUT parameters, this is the place to
-- set Last_Assignment for OUT and IN OUT parameters. We have to do this
-- after the above call to Kill_Current_Values (since that call clears
-- the Last_Assignment field of all local variables).
if (Warn_On_Modified_Unread or Warn_On_All_Unread_Out_Parameters)
and then Comes_From_Source (N)
and then In_Extended_Main_Source_Unit (N)
then
declare
F : Entity_Id;
A : Node_Id;
begin
F := First_Formal (Nam);
A := First_Actual (N);
while Present (F) and then Present (A) loop
if Ekind (F) in E_Out_Parameter | E_In_Out_Parameter
and then Warn_On_Modified_As_Out_Parameter (F)
and then Is_Entity_Name (A)
and then Present (Entity (A))
and then Comes_From_Source (N)
and then Safe_To_Capture_Value (N, Entity (A))
then
Set_Last_Assignment (Entity (A), A);
end if;
Next_Formal (F);
Next_Actual (A);
end loop;
end;
end if;
-- If the subprogram is a primitive operation, check whether or not
-- it is a correct dispatching call.
if Is_Overloadable (Nam)
and then Is_Dispatching_Operation (Nam)
then
Check_Dispatching_Call (N);
elsif Ekind (Nam) /= E_Subprogram_Type
and then Is_Abstract_Subprogram (Nam)
and then not In_Instance
then
Error_Msg_NE ("cannot call abstract subprogram &!", N, Nam);
end if;
-- If this is a dispatching call, generate the appropriate reference,
-- for better source navigation in GNAT Studio.
if Is_Overloadable (Nam)
and then Present (Controlling_Argument (N))
then
Generate_Reference (Nam, Subp, 'R');
-- Normal case, not a dispatching call: generate a call reference
else
Generate_Reference (Nam, Subp, 's');
end if;
if Is_Intrinsic_Subprogram (Nam) then
Check_Intrinsic_Call (N);
end if;
-- Check for violation of restriction No_Specific_Termination_Handlers
-- and warn on a potentially blocking call to Abort_Task.
if Restriction_Check_Required (No_Specific_Termination_Handlers)
and then (Is_RTE (Nam, RE_Set_Specific_Handler)
or else
Is_RTE (Nam, RE_Specific_Handler))
then
Check_Restriction (No_Specific_Termination_Handlers, N);
elsif Is_RTE (Nam, RE_Abort_Task) then
Check_Potentially_Blocking_Operation (N);
end if;
-- A call to Ada.Real_Time.Timing_Events.Set_Handler to set a relative
-- timing event violates restriction No_Relative_Delay (AI-0211). We
-- need to check the second argument to determine whether it is an
-- absolute or relative timing event.
if Restriction_Check_Required (No_Relative_Delay)
and then Is_RTE (Nam, RE_Set_Handler)
and then Is_RTE (Etype (Next_Actual (First_Actual (N))), RE_Time_Span)
then
Check_Restriction (No_Relative_Delay, N);
end if;
-- Issue an error for a call to an eliminated subprogram. This routine
-- will not perform the check if the call appears within a default
-- expression.
Check_For_Eliminated_Subprogram (Subp, Nam);
-- Implement rule in 12.5.1 (23.3/2): In an instance, if the actual is
-- class-wide and the call dispatches on result in a context that does
-- not provide a tag, the call raises Program_Error.
if Nkind (N) = N_Function_Call
and then In_Instance
and then Is_Generic_Actual_Type (Typ)
and then Is_Class_Wide_Type (Typ)
and then Has_Controlling_Result (Nam)
and then Nkind (Parent (N)) = N_Object_Declaration
then
-- Verify that none of the formals are controlling
declare
Call_OK : Boolean := False;
F : Entity_Id;
begin
F := First_Formal (Nam);
while Present (F) loop
if Is_Controlling_Formal (F) then
Call_OK := True;
exit;
end if;
Next_Formal (F);
end loop;
if not Call_OK then
Error_Msg_Warn := SPARK_Mode /= On;
Error_Msg_N ("!cannot determine tag of result<<", N);
Error_Msg_N ("\Program_Error [<<!", N);
Insert_Action (N,
Make_Raise_Program_Error (Sloc (N),
Reason => PE_Explicit_Raise));
end if;
end;
end if;
-- Check for calling a function with OUT or IN OUT parameter when the
-- calling context (us right now) is not Ada 2012, so does not allow
-- OUT or IN OUT parameters in function calls. Functions declared in
-- a predefined unit are OK, as they may be called indirectly from a
-- user-declared instantiation.
if Ada_Version < Ada_2012
and then Ekind (Nam) = E_Function
and then Has_Out_Or_In_Out_Parameter (Nam)
and then not In_Predefined_Unit (Nam)
then
Error_Msg_NE ("& has at least one OUT or `IN OUT` parameter", N, Nam);
Error_Msg_N ("\call to this function only allowed in Ada 2012", N);
end if;
-- Check the dimensions of the actuals in the call. For function calls,
-- propagate the dimensions from the returned type to N.
Analyze_Dimension_Call (N, Nam);
-- All done, evaluate call and deal with elaboration issues
Eval_Call (N);
if Legacy_Elaboration_Checks then
Check_Elab_Call (N);
end if;
-- Annotate the tree by creating a call marker in case the original call
-- is transformed by expansion. The call marker is automatically saved
-- for later examination by the ABE Processing phase.
Build_Call_Marker (N);
Mark_Use_Clauses (Subp);
Warn_On_Overlapping_Actuals (Nam, N);
-- Ada 202x (AI12-0075): If the call is a static call to a static
-- expression function, then we want to "inline" the call, replacing
-- it with the folded static result. This is not done if the checking
-- for a potentially static expression is enabled or if an error has
-- been posted on the call (which may be due to the check for recursive
-- calls, in which case we don't want to fall into infinite recursion
-- when doing the inlining).
if not Checking_Potentially_Static_Expression
and then Is_Static_Function_Call (N)
and then not Is_Intrinsic_Subprogram (Ultimate_Alias (Nam))
and then not Error_Posted (Ultimate_Alias (Nam))
then
Inline_Static_Function_Call (N, Ultimate_Alias (Nam));
-- In GNATprove mode, expansion is disabled, but we want to inline some
-- subprograms to facilitate formal verification. Indirect calls through
-- a subprogram type or within a generic cannot be inlined. Inlining is
-- performed only for calls subject to SPARK_Mode on.
elsif GNATprove_Mode
and then SPARK_Mode = On
and then Is_Overloadable (Nam)
and then not Inside_A_Generic
then
Nam_UA := Ultimate_Alias (Nam);
Nam_Decl := Unit_Declaration_Node (Nam_UA);
if Nkind (Nam_Decl) = N_Subprogram_Declaration then
Body_Id := Corresponding_Body (Nam_Decl);
-- Nothing to do if the subprogram is not eligible for inlining in
-- GNATprove mode, or inlining is disabled with switch -gnatdm
if not Is_Inlined_Always (Nam_UA)
or else not Can_Be_Inlined_In_GNATprove_Mode (Nam_UA, Body_Id)
or else Debug_Flag_M
then
null;
-- Calls cannot be inlined inside assertions, as GNATprove treats
-- assertions as logic expressions. Only issue a message when the
-- body has been seen, otherwise this leads to spurious messages
-- on expression functions.
elsif In_Assertion_Expr /= 0 then
if Present (Body_Id) then
Cannot_Inline
("cannot inline & (in assertion expression)?", N, Nam_UA);
end if;
-- Calls cannot be inlined inside default expressions
elsif In_Default_Expr then
Cannot_Inline
("cannot inline & (in default expression)?", N, Nam_UA);
-- Calls cannot be inlined inside quantified expressions, which
-- are left in expression form for GNATprove. Since these
-- expressions are only preanalyzed, we need to detect the failure
-- to inline outside of the case for Full_Analysis below.
elsif In_Quantified_Expression (N) then
Cannot_Inline
("cannot inline & (in quantified expression)?", N, Nam_UA);
-- Inlining should not be performed during preanalysis
elsif Full_Analysis then
-- Do not inline calls inside expression functions or functions
-- generated by the front end for subtype predicates, as this
-- would prevent interpreting them as logical formulas in
-- GNATprove. Only issue a message when the body has been seen,
-- otherwise this leads to spurious messages on callees that
-- are themselves expression functions.
if Present (Current_Subprogram)
and then
(Is_Expression_Function_Or_Completion (Current_Subprogram)
or else Is_Predicate_Function (Current_Subprogram)
or else Is_Invariant_Procedure (Current_Subprogram)
or else Is_DIC_Procedure (Current_Subprogram))
then
if Present (Body_Id)
and then Present (Body_To_Inline (Nam_Decl))
then
if Is_Predicate_Function (Current_Subprogram) then
Cannot_Inline
("cannot inline & (inside predicate)?",
N, Nam_UA);
elsif Is_Invariant_Procedure (Current_Subprogram) then
Cannot_Inline
("cannot inline & (inside invariant)?",
N, Nam_UA);
elsif Is_DIC_Procedure (Current_Subprogram) then
Cannot_Inline
("cannot inline & (inside Default_Initial_Condition)?",
N, Nam_UA);
else
Cannot_Inline
("cannot inline & (inside expression function)?",
N, Nam_UA);
end if;
end if;
-- Cannot inline a call inside the definition of a record type,
-- typically inside the constraints of the type. Calls in
-- default expressions are also not inlined, but this is
-- filtered out above when testing In_Default_Expr.
elsif Is_Record_Type (Current_Scope) then
Cannot_Inline
("cannot inline & (inside record type)?", N, Nam_UA);
-- With the one-pass inlining technique, a call cannot be
-- inlined if the corresponding body has not been seen yet.
elsif No (Body_Id) then
Cannot_Inline
("cannot inline & (body not seen yet)?", N, Nam_UA);
-- Nothing to do if there is no body to inline, indicating that
-- the subprogram is not suitable for inlining in GNATprove
-- mode.
elsif No (Body_To_Inline (Nam_Decl)) then
null;
-- Calls cannot be inlined inside potentially unevaluated
-- expressions, as this would create complex actions inside
-- expressions, that are not handled by GNATprove.
elsif Is_Potentially_Unevaluated (N) then
Cannot_Inline
("cannot inline & (in potentially unevaluated context)?",
N, Nam_UA);
-- Calls cannot be inlined inside the conditions of while
-- loops, as this would create complex actions inside
-- the condition, that are not handled by GNATprove.
elsif In_While_Loop_Condition (N) then
Cannot_Inline
("cannot inline & (in while loop condition)?", N, Nam_UA);
-- Do not inline calls which would possibly lead to missing a
-- type conversion check on an input parameter.
elsif not Call_Can_Be_Inlined_In_GNATprove_Mode (N, Nam) then
Cannot_Inline
("cannot inline & (possible check on input parameters)?",
N, Nam_UA);
-- Otherwise, inline the call, issuing an info message when
-- -gnatd_f is set.
else
if Debug_Flag_Underscore_F then
Error_Msg_NE
("info: analyzing call to & in context?", N, Nam_UA);
end if;
Expand_Inlined_Call (N, Nam_UA, Nam);
end if;
end if;
end if;
end if;
end Resolve_Call;
-----------------------------
-- Resolve_Case_Expression --
-----------------------------
procedure Resolve_Case_Expression (N : Node_Id; Typ : Entity_Id) is
Alt : Node_Id;
Alt_Expr : Node_Id;
Alt_Typ : Entity_Id;
Is_Dyn : Boolean;
begin
Alt := First (Alternatives (N));
while Present (Alt) loop
Alt_Expr := Expression (Alt);
if Error_Posted (Alt_Expr) then
return;
end if;
Resolve (Alt_Expr, Typ);
Alt_Typ := Etype (Alt_Expr);
-- When the expression is of a scalar subtype different from the
-- result subtype, then insert a conversion to ensure the generation
-- of a constraint check.
if Is_Scalar_Type (Alt_Typ) and then Alt_Typ /= Typ then
Rewrite (Alt_Expr, Convert_To (Typ, Alt_Expr));
Analyze_And_Resolve (Alt_Expr, Typ);
end if;
Next (Alt);
end loop;
-- Apply RM 4.5.7 (17/3): whether the expression is statically or
-- dynamically tagged must be known statically.
if Is_Tagged_Type (Typ) and then not Is_Class_Wide_Type (Typ) then
Alt := First (Alternatives (N));
Is_Dyn := Is_Dynamically_Tagged (Expression (Alt));
while Present (Alt) loop
if Is_Dynamically_Tagged (Expression (Alt)) /= Is_Dyn then
Error_Msg_N
("all or none of the dependent expressions can be "
& "dynamically tagged", N);
end if;
Next (Alt);
end loop;
end if;
Set_Etype (N, Typ);
Eval_Case_Expression (N);
Analyze_Dimension (N);
end Resolve_Case_Expression;
-------------------------------
-- Resolve_Character_Literal --
-------------------------------
procedure Resolve_Character_Literal (N : Node_Id; Typ : Entity_Id) is
B_Typ : constant Entity_Id := Base_Type (Typ);
C : Entity_Id;
begin
-- Verify that the character does belong to the type of the context
Set_Etype (N, B_Typ);
Eval_Character_Literal (N);
-- Wide_Wide_Character literals must always be defined, since the set
-- of wide wide character literals is complete, i.e. if a character
-- literal is accepted by the parser, then it is OK for wide wide
-- character (out of range character literals are rejected).
if Root_Type (B_Typ) = Standard_Wide_Wide_Character then
return;
-- Always accept character literal for type Any_Character, which
-- occurs in error situations and in comparisons of literals, both
-- of which should accept all literals.
elsif B_Typ = Any_Character then
return;
-- For Standard.Character or a type derived from it, check that the
-- literal is in range.
elsif Root_Type (B_Typ) = Standard_Character then
if In_Character_Range (UI_To_CC (Char_Literal_Value (N))) then
return;
end if;
-- For Standard.Wide_Character or a type derived from it, check that the
-- literal is in range.
elsif Root_Type (B_Typ) = Standard_Wide_Character then
if In_Wide_Character_Range (UI_To_CC (Char_Literal_Value (N))) then
return;
end if;
-- If the entity is already set, this has already been resolved in a
-- generic context, or comes from expansion. Nothing else to do.
elsif Present (Entity (N)) then
return;
-- Otherwise we have a user defined character type, and we can use the
-- standard visibility mechanisms to locate the referenced entity.
else
C := Current_Entity (N);
while Present (C) loop
if Etype (C) = B_Typ then
Set_Entity_With_Checks (N, C);
Generate_Reference (C, N);
return;
end if;
C := Homonym (C);
end loop;
end if;
-- If we fall through, then the literal does not match any of the
-- entries of the enumeration type. This isn't just a constraint error
-- situation, it is an illegality (see RM 4.2).
Error_Msg_NE
("character not defined for }", N, First_Subtype (B_Typ));
end Resolve_Character_Literal;
---------------------------
-- Resolve_Comparison_Op --
---------------------------
-- Context requires a boolean type, and plays no role in resolution.
-- Processing identical to that for equality operators. The result type is
-- the base type, which matters when pathological subtypes of booleans with
-- limited ranges are used.
procedure Resolve_Comparison_Op (N : Node_Id; Typ : Entity_Id) is
L : constant Node_Id := Left_Opnd (N);
R : constant Node_Id := Right_Opnd (N);
T : Entity_Id;
begin
-- If this is an intrinsic operation which is not predefined, use the
-- types of its declared arguments to resolve the possibly overloaded
-- operands. Otherwise the operands are unambiguous and specify the
-- expected type.
if Scope (Entity (N)) /= Standard_Standard then
T := Etype (First_Entity (Entity (N)));
else
T := Find_Unique_Type (L, R);
if T = Any_Fixed then
T := Unique_Fixed_Point_Type (L);
end if;
end if;
Set_Etype (N, Base_Type (Typ));
Generate_Reference (T, N, ' ');
-- Skip remaining processing if already set to Any_Type
if T = Any_Type then
return;
end if;
-- Deal with other error cases
if T = Any_String or else
T = Any_Composite or else
T = Any_Character
then
if T = Any_Character then
Ambiguous_Character (L);
else
Error_Msg_N ("ambiguous operands for comparison", N);
end if;
Set_Etype (N, Any_Type);
return;
end if;
-- Resolve the operands if types OK
Resolve (L, T);
Resolve (R, T);
Check_Unset_Reference (L);
Check_Unset_Reference (R);
Generate_Operator_Reference (N, T);
Check_Low_Bound_Tested (N);
-- Check comparison on unordered enumeration
if Bad_Unordered_Enumeration_Reference (N, Etype (L)) then
Error_Msg_Sloc := Sloc (Etype (L));
Error_Msg_NE
("comparison on unordered enumeration type& declared#?U?",
N, Etype (L));
end if;
Analyze_Dimension (N);
-- Evaluate the relation (note we do this after the above check since
-- this Eval call may change N to True/False. Skip this evaluation
-- inside assertions, in order to keep assertions as written by users
-- for tools that rely on these, e.g. GNATprove for loop invariants.
-- Except evaluation is still performed even inside assertions for
-- comparisons between values of universal type, which are useless
-- for static analysis tools, and not supported even by GNATprove.
if In_Assertion_Expr = 0
or else (Is_Universal_Numeric_Type (Etype (L))
and then
Is_Universal_Numeric_Type (Etype (R)))
then
Eval_Relational_Op (N);
end if;
end Resolve_Comparison_Op;
--------------------------------
-- Resolve_Declare_Expression --
--------------------------------
procedure Resolve_Declare_Expression
(N : Node_Id;
Typ : Entity_Id)
is
Decl : Node_Id;
begin
-- Install the scope created for local declarations, if
-- any. The syntax allows a Declare_Expression with no
-- declarations, in analogy with block statements.
-- Note that that scope has no explicit declaration, but
-- appears as the scope of all entities declared therein.
Decl := First (Actions (N));
while Present (Decl) loop
exit when Nkind (Decl)
in N_Object_Declaration | N_Object_Renaming_Declaration;
Next (Decl);
end loop;
if Present (Decl) then
Push_Scope (Scope (Defining_Identifier (Decl)));
declare
E : Entity_Id := First_Entity (Current_Scope);
begin
while Present (E) loop
Set_Current_Entity (E);
Set_Is_Immediately_Visible (E);
Next_Entity (E);
end loop;
end;
Resolve (Expression (N), Typ);
End_Scope;
else
Resolve (Expression (N), Typ);
end if;
end Resolve_Declare_Expression;
-----------------------------------------
-- Resolve_Discrete_Subtype_Indication --
-----------------------------------------
procedure Resolve_Discrete_Subtype_Indication
(N : Node_Id;
Typ : Entity_Id)
is
R : Node_Id;
S : Entity_Id;
begin
Analyze (Subtype_Mark (N));
S := Entity (Subtype_Mark (N));
if Nkind (Constraint (N)) /= N_Range_Constraint then
Error_Msg_N ("expect range constraint for discrete type", N);
Set_Etype (N, Any_Type);
else
R := Range_Expression (Constraint (N));
if R = Error then
return;
end if;
Analyze (R);
if Base_Type (S) /= Base_Type (Typ) then
Error_Msg_NE
("expect subtype of }", N, First_Subtype (Typ));
-- Rewrite the constraint as a range of Typ
-- to allow compilation to proceed further.
Set_Etype (N, Typ);
Rewrite (Low_Bound (R),
Make_Attribute_Reference (Sloc (Low_Bound (R)),
Prefix => New_Occurrence_Of (Typ, Sloc (R)),
Attribute_Name => Name_First));
Rewrite (High_Bound (R),
Make_Attribute_Reference (Sloc (High_Bound (R)),
Prefix => New_Occurrence_Of (Typ, Sloc (R)),
Attribute_Name => Name_First));
else
Resolve (R, Typ);
Set_Etype (N, Etype (R));
-- Additionally, we must check that the bounds are compatible
-- with the given subtype, which might be different from the
-- type of the context.
Apply_Range_Check (R, S);
-- ??? If the above check statically detects a Constraint_Error
-- it replaces the offending bound(s) of the range R with a
-- Constraint_Error node. When the itype which uses these bounds
-- is frozen the resulting call to Duplicate_Subexpr generates
-- a new temporary for the bounds.
-- Unfortunately there are other itypes that are also made depend
-- on these bounds, so when Duplicate_Subexpr is called they get
-- a forward reference to the newly created temporaries and Gigi
-- aborts on such forward references. This is probably sign of a
-- more fundamental problem somewhere else in either the order of
-- itype freezing or the way certain itypes are constructed.
-- To get around this problem we call Remove_Side_Effects right
-- away if either bounds of R are a Constraint_Error.
declare
L : constant Node_Id := Low_Bound (R);
H : constant Node_Id := High_Bound (R);
begin
if Nkind (L) = N_Raise_Constraint_Error then
Remove_Side_Effects (L);
end if;
if Nkind (H) = N_Raise_Constraint_Error then
Remove_Side_Effects (H);
end if;
end;
Check_Unset_Reference (Low_Bound (R));
Check_Unset_Reference (High_Bound (R));
end if;
end if;
end Resolve_Discrete_Subtype_Indication;
-------------------------
-- Resolve_Entity_Name --
-------------------------
-- Used to resolve identifiers and expanded names
procedure Resolve_Entity_Name (N : Node_Id; Typ : Entity_Id) is
function Is_Assignment_Or_Object_Expression
(Context : Node_Id;
Expr : Node_Id) return Boolean;
-- Determine whether node Context denotes an assignment statement or an
-- object declaration whose expression is node Expr.
function Is_Attribute_Expression (Expr : Node_Id) return Boolean;
-- Determine whether Expr is part of an N_Attribute_Reference
-- expression.
----------------------------------------
-- Is_Assignment_Or_Object_Expression --
----------------------------------------
function Is_Assignment_Or_Object_Expression
(Context : Node_Id;
Expr : Node_Id) return Boolean
is
begin
if Nkind (Context) in
N_Assignment_Statement | N_Object_Declaration
and then Expression (Context) = Expr
then
return True;
-- Check whether a construct that yields a name is the expression of
-- an assignment statement or an object declaration.
elsif (Nkind (Context) in N_Attribute_Reference
| N_Explicit_Dereference
| N_Indexed_Component
| N_Selected_Component
| N_Slice
and then Prefix (Context) = Expr)
or else
(Nkind (Context) in N_Type_Conversion
| N_Unchecked_Type_Conversion
and then Expression (Context) = Expr)
then
return
Is_Assignment_Or_Object_Expression
(Context => Parent (Context),
Expr => Context);
-- Otherwise the context is not an assignment statement or an object
-- declaration.
else
return False;
end if;
end Is_Assignment_Or_Object_Expression;
-----------------------------
-- Is_Attribute_Expression --
-----------------------------
function Is_Attribute_Expression (Expr : Node_Id) return Boolean is
N : Node_Id := Expr;
begin
while Present (N) loop
if Nkind (N) = N_Attribute_Reference then
return True;
end if;
N := Parent (N);
end loop;
return False;
end Is_Attribute_Expression;
-- Local variables
E : constant Entity_Id := Entity (N);
Par : Node_Id;
-- Start of processing for Resolve_Entity_Name
begin
-- If garbage from errors, set to Any_Type and return
if No (E) and then Total_Errors_Detected /= 0 then
Set_Etype (N, Any_Type);
return;
end if;
-- Replace named numbers by corresponding literals. Note that this is
-- the one case where Resolve_Entity_Name must reset the Etype, since
-- it is currently marked as universal.
if Ekind (E) = E_Named_Integer then
Set_Etype (N, Typ);
Eval_Named_Integer (N);
elsif Ekind (E) = E_Named_Real then
Set_Etype (N, Typ);
Eval_Named_Real (N);
-- For enumeration literals, we need to make sure that a proper style
-- check is done, since such literals are overloaded, and thus we did
-- not do a style check during the first phase of analysis.
elsif Ekind (E) = E_Enumeration_Literal then
Set_Entity_With_Checks (N, E);
Eval_Entity_Name (N);
-- Case of (sub)type name appearing in a context where an expression
-- is expected. This is legal if occurrence is a current instance.
-- See RM 8.6 (17/3).
elsif Is_Type (E) then
if Is_Current_Instance (N) then
null;
-- Any other use is an error
else
Error_Msg_N
("invalid use of subtype mark in expression or call", N);
end if;
-- Check discriminant use if entity is discriminant in current scope,
-- i.e. discriminant of record or concurrent type currently being
-- analyzed. Uses in corresponding body are unrestricted.
elsif Ekind (E) = E_Discriminant
and then Scope (E) = Current_Scope
and then not Has_Completion (Current_Scope)
then
Check_Discriminant_Use (N);
-- A parameterless generic function cannot appear in a context that
-- requires resolution.
elsif Ekind (E) = E_Generic_Function then
Error_Msg_N ("illegal use of generic function", N);
-- In Ada 83 an OUT parameter cannot be read, but attributes of
-- array types (i.e. bounds and length) are legal.
elsif Ekind (E) = E_Out_Parameter
and then (Is_Scalar_Type (Etype (E))
or else not Is_Attribute_Expression (Parent (N)))
and then (Nkind (Parent (N)) in N_Op
or else Nkind (Parent (N)) = N_Explicit_Dereference
or else Is_Assignment_Or_Object_Expression
(Context => Parent (N),
Expr => N))
then
if Ada_Version = Ada_83 then
Error_Msg_N ("(Ada 83) illegal reading of out parameter", N);
end if;
-- In all other cases, just do the possible static evaluation
else
-- A deferred constant that appears in an expression must have a
-- completion, unless it has been removed by in-place expansion of
-- an aggregate. A constant that is a renaming does not need
-- initialization.
if Ekind (E) = E_Constant
and then Comes_From_Source (E)
and then No (Constant_Value (E))
and then Is_Frozen (Etype (E))
and then not In_Spec_Expression
and then not Is_Imported (E)
and then Nkind (Parent (E)) /= N_Object_Renaming_Declaration
then
if No_Initialization (Parent (E))
or else (Present (Full_View (E))
and then No_Initialization (Parent (Full_View (E))))
then
null;
else
Error_Msg_N
("deferred constant is frozen before completion", N);
end if;
end if;
Eval_Entity_Name (N);
end if;
Par := Parent (N);
-- When the entity appears in a parameter association, retrieve the
-- related subprogram call.
if Nkind (Par) = N_Parameter_Association then
Par := Parent (Par);
end if;
if Comes_From_Source (N) then
-- The following checks are only relevant when SPARK_Mode is on as
-- they are not standard Ada legality rules.
if SPARK_Mode = On then
-- An effectively volatile object for reading must appear in
-- non-interfering context (SPARK RM 7.1.3(10)).
if Is_Object (E)
and then Is_Effectively_Volatile_For_Reading (E)
and then not Is_OK_Volatile_Context (Par, N)
then
SPARK_Msg_N
("volatile object cannot appear in this context "
& "(SPARK RM 7.1.3(10))", N);
end if;
-- Check for possible elaboration issues with respect to reads of
-- variables. The act of renaming the variable is not considered a
-- read as it simply establishes an alias.
if Legacy_Elaboration_Checks
and then Ekind (E) = E_Variable
and then Dynamic_Elaboration_Checks
and then Nkind (Par) /= N_Object_Renaming_Declaration
then
Check_Elab_Call (N);
end if;
end if;
-- The variable may eventually become a constituent of a single
-- protected/task type. Record the reference now and verify its
-- legality when analyzing the contract of the variable
-- (SPARK RM 9.3).
if Ekind (E) = E_Variable then
Record_Possible_Part_Of_Reference (E, N);
end if;
-- A Ghost entity must appear in a specific context
if Is_Ghost_Entity (E) then
Check_Ghost_Context (E, N);
end if;
end if;
-- We may be resolving an entity within expanded code, so a reference to
-- an entity should be ignored when calculating effective use clauses to
-- avoid inappropriate marking.
if Comes_From_Source (N) then
Mark_Use_Clauses (E);
end if;
end Resolve_Entity_Name;
-------------------
-- Resolve_Entry --
-------------------
procedure Resolve_Entry (Entry_Name : Node_Id) is
Loc : constant Source_Ptr := Sloc (Entry_Name);
Nam : Entity_Id;
New_N : Node_Id;
S : Entity_Id;
Tsk : Entity_Id;
E_Name : Node_Id;
Index : Node_Id;
function Actual_Index_Type (E : Entity_Id) return Entity_Id;
-- If the bounds of the entry family being called depend on task
-- discriminants, build a new index subtype where a discriminant is
-- replaced with the value of the discriminant of the target task.
-- The target task is the prefix of the entry name in the call.
-----------------------
-- Actual_Index_Type --
-----------------------
function Actual_Index_Type (E : Entity_Id) return Entity_Id is
Typ : constant Entity_Id := Entry_Index_Type (E);
Tsk : constant Entity_Id := Scope (E);
Lo : constant Node_Id := Type_Low_Bound (Typ);
Hi : constant Node_Id := Type_High_Bound (Typ);
New_T : Entity_Id;
function Actual_Discriminant_Ref (Bound : Node_Id) return Node_Id;
-- If the bound is given by a discriminant, replace with a reference
-- to the discriminant of the same name in the target task. If the
-- entry name is the target of a requeue statement and the entry is
-- in the current protected object, the bound to be used is the
-- discriminal of the object (see Apply_Range_Check for details of
-- the transformation).
-----------------------------
-- Actual_Discriminant_Ref --
-----------------------------
function Actual_Discriminant_Ref (Bound : Node_Id) return Node_Id is
Typ : constant Entity_Id := Etype (Bound);
Ref : Node_Id;
begin
Remove_Side_Effects (Bound);
if not Is_Entity_Name (Bound)
or else Ekind (Entity (Bound)) /= E_Discriminant
then
return Bound;
elsif Is_Protected_Type (Tsk)
and then In_Open_Scopes (Tsk)
and then Nkind (Parent (Entry_Name)) = N_Requeue_Statement
then
-- Note: here Bound denotes a discriminant of the corresponding
-- record type tskV, whose discriminal is a formal of the
-- init-proc tskVIP. What we want is the body discriminal,
-- which is associated to the discriminant of the original
-- concurrent type tsk.
return New_Occurrence_Of
(Find_Body_Discriminal (Entity (Bound)), Loc);
else
Ref :=
Make_Selected_Component (Loc,
Prefix => New_Copy_Tree (Prefix (Prefix (Entry_Name))),
Selector_Name => New_Occurrence_Of (Entity (Bound), Loc));
Analyze (Ref);
Resolve (Ref, Typ);
return Ref;
end if;
end Actual_Discriminant_Ref;
-- Start of processing for Actual_Index_Type
begin
if not Has_Discriminants (Tsk)
or else (not Is_Entity_Name (Lo) and then not Is_Entity_Name (Hi))
then
return Entry_Index_Type (E);
else
New_T := Create_Itype (Ekind (Typ), Parent (Entry_Name));
Set_Etype (New_T, Base_Type (Typ));
Set_Size_Info (New_T, Typ);
Set_RM_Size (New_T, RM_Size (Typ));
Set_Scalar_Range (New_T,
Make_Range (Sloc (Entry_Name),
Low_Bound => Actual_Discriminant_Ref (Lo),
High_Bound => Actual_Discriminant_Ref (Hi)));
return New_T;
end if;
end Actual_Index_Type;
-- Start of processing for Resolve_Entry
begin
-- Find name of entry being called, and resolve prefix of name with its
-- own type. The prefix can be overloaded, and the name and signature of
-- the entry must be taken into account.
if Nkind (Entry_Name) = N_Indexed_Component then
-- Case of dealing with entry family within the current tasks
E_Name := Prefix (Entry_Name);
else
E_Name := Entry_Name;
end if;
if Is_Entity_Name (E_Name) then
-- Entry call to an entry (or entry family) in the current task. This
-- is legal even though the task will deadlock. Rewrite as call to
-- current task.
-- This can also be a call to an entry in an enclosing task. If this
-- is a single task, we have to retrieve its name, because the scope
-- of the entry is the task type, not the object. If the enclosing
-- task is a task type, the identity of the task is given by its own
-- self variable.
-- Finally this can be a requeue on an entry of the same task or
-- protected object.
S := Scope (Entity (E_Name));
for J in reverse 0 .. Scope_Stack.Last loop
if Is_Task_Type (Scope_Stack.Table (J).Entity)
and then not Comes_From_Source (S)
then
-- S is an enclosing task or protected object. The concurrent
-- declaration has been converted into a type declaration, and
-- the object itself has an object declaration that follows
-- the type in the same declarative part.
Tsk := Next_Entity (S);
while Etype (Tsk) /= S loop
Next_Entity (Tsk);
end loop;
S := Tsk;
exit;
elsif S = Scope_Stack.Table (J).Entity then
-- Call to current task. Will be transformed into call to Self
exit;
end if;
end loop;
New_N :=
Make_Selected_Component (Loc,
Prefix => New_Occurrence_Of (S, Loc),
Selector_Name =>
New_Occurrence_Of (Entity (E_Name), Loc));
Rewrite (E_Name, New_N);
Analyze (E_Name);
elsif Nkind (Entry_Name) = N_Selected_Component
and then Is_Overloaded (Prefix (Entry_Name))
then
-- Use the entry name (which must be unique at this point) to find
-- the prefix that returns the corresponding task/protected type.
declare
Pref : constant Node_Id := Prefix (Entry_Name);
Ent : constant Entity_Id := Entity (Selector_Name (Entry_Name));
I : Interp_Index;
It : Interp;
begin
Get_First_Interp (Pref, I, It);
while Present (It.Typ) loop
if Scope (Ent) = It.Typ then
Set_Etype (Pref, It.Typ);
exit;
end if;
Get_Next_Interp (I, It);
end loop;
end;
end if;
if Nkind (Entry_Name) = N_Selected_Component then
Resolve (Prefix (Entry_Name));
Resolve_Implicit_Dereference (Prefix (Entry_Name));
else pragma Assert (Nkind (Entry_Name) = N_Indexed_Component);
Nam := Entity (Selector_Name (Prefix (Entry_Name)));
Resolve (Prefix (Prefix (Entry_Name)));
Resolve_Implicit_Dereference (Prefix (Prefix (Entry_Name)));
-- We do not resolve the prefix because an Entry_Family has no type,
-- although it has the semantics of an array since it can be indexed.
-- In order to perform the associated range check, we would need to
-- build an array type on the fly and set it on the prefix, but this
-- would be wasteful since only the index type matters. Therefore we
-- attach this index type directly, so that Actual_Index_Expression
-- can pick it up later in order to generate the range check.
Set_Etype (Prefix (Entry_Name), Actual_Index_Type (Nam));
Index := First (Expressions (Entry_Name));
Resolve (Index, Entry_Index_Type (Nam));
-- Generate a reference for the index when it denotes an entity
if Is_Entity_Name (Index) then
Generate_Reference (Entity (Index), Nam);
end if;
-- Up to this point the expression could have been the actual in a
-- simple entry call, and be given by a named association.
if Nkind (Index) = N_Parameter_Association then
Error_Msg_N ("expect expression for entry index", Index);
else
Apply_Scalar_Range_Check (Index, Etype (Prefix (Entry_Name)));
end if;
end if;
end Resolve_Entry;
------------------------
-- Resolve_Entry_Call --
------------------------
procedure Resolve_Entry_Call (N : Node_Id; Typ : Entity_Id) is
Entry_Name : constant Node_Id := Name (N);
Loc : constant Source_Ptr := Sloc (Entry_Name);
Nam : Entity_Id;
Norm_OK : Boolean;
Obj : Node_Id;
Was_Over : Boolean;
begin
-- We kill all checks here, because it does not seem worth the effort to
-- do anything better, an entry call is a big operation.
Kill_All_Checks;
-- Processing of the name is similar for entry calls and protected
-- operation calls. Once the entity is determined, we can complete
-- the resolution of the actuals.
-- The selector may be overloaded, in the case of a protected object
-- with overloaded functions. The type of the context is used for
-- resolution.
if Nkind (Entry_Name) = N_Selected_Component
and then Is_Overloaded (Selector_Name (Entry_Name))
and then Typ /= Standard_Void_Type
then
declare
I : Interp_Index;
It : Interp;
begin
Get_First_Interp (Selector_Name (Entry_Name), I, It);
while Present (It.Typ) loop
if Covers (Typ, It.Typ) then
Set_Entity (Selector_Name (Entry_Name), It.Nam);
Set_Etype (Entry_Name, It.Typ);
Generate_Reference (It.Typ, N, ' ');
end if;
Get_Next_Interp (I, It);
end loop;
end;
end if;
Resolve_Entry (Entry_Name);
if Nkind (Entry_Name) = N_Selected_Component then
-- Simple entry or protected operation call
Nam := Entity (Selector_Name (Entry_Name));
Obj := Prefix (Entry_Name);
if Is_Subprogram (Nam) then
Check_For_Eliminated_Subprogram (Entry_Name, Nam);
end if;
Was_Over := Is_Overloaded (Selector_Name (Entry_Name));
else pragma Assert (Nkind (Entry_Name) = N_Indexed_Component);
-- Call to member of entry family
Nam := Entity (Selector_Name (Prefix (Entry_Name)));
Obj := Prefix (Prefix (Entry_Name));
Was_Over := Is_Overloaded (Selector_Name (Prefix (Entry_Name)));
end if;
-- We cannot in general check the maximum depth of protected entry calls
-- at compile time. But we can tell that any protected entry call at all
-- violates a specified nesting depth of zero.
if Is_Protected_Type (Scope (Nam)) then
Check_Restriction (Max_Entry_Queue_Length, N);
end if;
-- Use context type to disambiguate a protected function that can be
-- called without actuals and that returns an array type, and where the
-- argument list may be an indexing of the returned value.
if Ekind (Nam) = E_Function
and then Needs_No_Actuals (Nam)
and then Present (Parameter_Associations (N))
and then
((Is_Array_Type (Etype (Nam))
and then Covers (Typ, Component_Type (Etype (Nam))))
or else (Is_Access_Type (Etype (Nam))
and then Is_Array_Type (Designated_Type (Etype (Nam)))
and then
Covers
(Typ,
Component_Type (Designated_Type (Etype (Nam))))))
then
declare
Index_Node : Node_Id;
begin
Index_Node :=
Make_Indexed_Component (Loc,
Prefix =>
Make_Function_Call (Loc, Name => Relocate_Node (Entry_Name)),
Expressions => Parameter_Associations (N));
-- Since we are correcting a node classification error made by the
-- parser, we call Replace rather than Rewrite.
Replace (N, Index_Node);
Set_Etype (Prefix (N), Etype (Nam));
Set_Etype (N, Typ);
Resolve_Indexed_Component (N, Typ);
return;
end;
end if;
if Is_Entry (Nam)
and then Present (Contract_Wrapper (Nam))
and then Current_Scope /= Contract_Wrapper (Nam)
then
-- Note the entity being called before rewriting the call, so that
-- it appears used at this point.
Generate_Reference (Nam, Entry_Name, 'r');
-- Rewrite as call to the precondition wrapper, adding the task
-- object to the list of actuals. If the call is to a member of an
-- entry family, include the index as well.
declare
New_Call : Node_Id;
New_Actuals : List_Id;
begin
New_Actuals := New_List (Obj);
if Nkind (Entry_Name) = N_Indexed_Component then
Append_To (New_Actuals,
New_Copy_Tree (First (Expressions (Entry_Name))));
end if;
Append_List (Parameter_Associations (N), New_Actuals);
New_Call :=
Make_Procedure_Call_Statement (Loc,
Name =>
New_Occurrence_Of (Contract_Wrapper (Nam), Loc),
Parameter_Associations => New_Actuals);
Rewrite (N, New_Call);
-- Preanalyze and resolve new call. Current procedure is called
-- from Resolve_Call, after which expansion will take place.
Preanalyze_And_Resolve (N);
return;
end;
end if;
-- The operation name may have been overloaded. Order the actuals
-- according to the formals of the resolved entity, and set the return
-- type to that of the operation.
if Was_Over then
Normalize_Actuals (N, Nam, False, Norm_OK);
pragma Assert (Norm_OK);
Set_Etype (N, Etype (Nam));
-- Reset the Is_Overloaded flag, since resolution is now completed
-- Simple entry call
if Nkind (Entry_Name) = N_Selected_Component then
Set_Is_Overloaded (Selector_Name (Entry_Name), False);
-- Call to a member of an entry family
else pragma Assert (Nkind (Entry_Name) = N_Indexed_Component);
Set_Is_Overloaded (Selector_Name (Prefix (Entry_Name)), False);
end if;
end if;
Resolve_Actuals (N, Nam);
Check_Internal_Protected_Use (N, Nam);
-- Create a call reference to the entry
Generate_Reference (Nam, Entry_Name, 's');
if Is_Entry (Nam) then
Check_Potentially_Blocking_Operation (N);
end if;
-- Verify that a procedure call cannot masquerade as an entry
-- call where an entry call is expected.
if Ekind (Nam) = E_Procedure then
if Nkind (Parent (N)) = N_Entry_Call_Alternative
and then N = Entry_Call_Statement (Parent (N))
then
Error_Msg_N ("entry call required in select statement", N);
elsif Nkind (Parent (N)) = N_Triggering_Alternative
and then N = Triggering_Statement (Parent (N))
then
Error_Msg_N ("triggering statement cannot be procedure call", N);
elsif Ekind (Scope (Nam)) = E_Task_Type
and then not In_Open_Scopes (Scope (Nam))
then
Error_Msg_N ("task has no entry with this name", Entry_Name);
end if;
end if;
-- After resolution, entry calls and protected procedure calls are
-- changed into entry calls, for expansion. The structure of the node
-- does not change, so it can safely be done in place. Protected
-- function calls must keep their structure because they are
-- subexpressions.
if Ekind (Nam) /= E_Function then
-- A protected operation that is not a function may modify the
-- corresponding object, and cannot apply to a constant. If this
-- is an internal call, the prefix is the type itself.
if Is_Protected_Type (Scope (Nam))
and then not Is_Variable (Obj)
and then (not Is_Entity_Name (Obj)
or else not Is_Type (Entity (Obj)))
then
Error_Msg_N
("prefix of protected procedure or entry call must be variable",
Entry_Name);
end if;
declare
Entry_Call : Node_Id;
begin
Entry_Call :=
Make_Entry_Call_Statement (Loc,
Name => Entry_Name,
Parameter_Associations => Parameter_Associations (N));
-- Inherit relevant attributes from the original call
Set_First_Named_Actual
(Entry_Call, First_Named_Actual (N));
Set_Is_Elaboration_Checks_OK_Node
(Entry_Call, Is_Elaboration_Checks_OK_Node (N));
Set_Is_Elaboration_Warnings_OK_Node
(Entry_Call, Is_Elaboration_Warnings_OK_Node (N));
Set_Is_SPARK_Mode_On_Node
(Entry_Call, Is_SPARK_Mode_On_Node (N));
Rewrite (N, Entry_Call);
Set_Analyzed (N, True);
end;
-- Protected functions can return on the secondary stack, in which case
-- we must trigger the transient scope mechanism.
elsif Expander_Active
and then Requires_Transient_Scope (Etype (Nam))
then
Establish_Transient_Scope (N, Manage_Sec_Stack => True);
end if;
-- Now we know that this is not a call to a function that returns an
-- array type; moreover, we know the name of the called entry. Detect
-- overlapping actuals, just like for a subprogram call.
Warn_On_Overlapping_Actuals (Nam, N);
end Resolve_Entry_Call;
-------------------------
-- Resolve_Equality_Op --
-------------------------
-- Both arguments must have the same type, and the boolean context does
-- not participate in the resolution. The first pass verifies that the
-- interpretation is not ambiguous, and the type of the left argument is
-- correctly set, or is Any_Type in case of ambiguity. If both arguments
-- are strings or aggregates, allocators, or Null, they are ambiguous even
-- though they carry a single (universal) type. Diagnose this case here.
procedure Resolve_Equality_Op (N : Node_Id; Typ : Entity_Id) is
L : constant Node_Id := Left_Opnd (N);
R : constant Node_Id := Right_Opnd (N);
T : Entity_Id := Find_Unique_Type (L, R);
procedure Check_If_Expression (Cond : Node_Id);
-- The resolution rule for if expressions requires that each such must
-- have a unique type. This means that if several dependent expressions
-- are of a non-null anonymous access type, and the context does not
-- impose an expected type (as can be the case in an equality operation)
-- the expression must be rejected.
procedure Explain_Redundancy (N : Node_Id);
-- Attempt to explain the nature of a redundant comparison with True. If
-- the expression N is too complex, this routine issues a general error
-- message.
function Find_Unique_Access_Type return Entity_Id;
-- In the case of allocators and access attributes, the context must
-- provide an indication of the specific access type to be used. If
-- one operand is of such a "generic" access type, check whether there
-- is a specific visible access type that has the same designated type.
-- This is semantically dubious, and of no interest to any real code,
-- but c48008a makes it all worthwhile.
-------------------------
-- Check_If_Expression --
-------------------------
procedure Check_If_Expression (Cond : Node_Id) is
Then_Expr : Node_Id;
Else_Expr : Node_Id;
begin
if Nkind (Cond) = N_If_Expression then
Then_Expr := Next (First (Expressions (Cond)));
Else_Expr := Next (Then_Expr);
if Nkind (Then_Expr) /= N_Null
and then Nkind (Else_Expr) /= N_Null
then
Error_Msg_N ("cannot determine type of if expression", Cond);
end if;
end if;
end Check_If_Expression;
------------------------
-- Explain_Redundancy --
------------------------
procedure Explain_Redundancy (N : Node_Id) is
Error : Name_Id;
Val : Node_Id;
Val_Id : Entity_Id;
begin
Val := N;
-- Strip the operand down to an entity
loop
if Nkind (Val) = N_Selected_Component then
Val := Selector_Name (Val);
else
exit;
end if;
end loop;
-- The construct denotes an entity
if Is_Entity_Name (Val) and then Present (Entity (Val)) then
Val_Id := Entity (Val);
-- Do not generate an error message when the comparison is done
-- against the enumeration literal Standard.True.
if Ekind (Val_Id) /= E_Enumeration_Literal then
-- Build a customized error message
Name_Len := 0;
Add_Str_To_Name_Buffer ("?r?");
if Ekind (Val_Id) = E_Component then
Add_Str_To_Name_Buffer ("component ");
elsif Ekind (Val_Id) = E_Constant then
Add_Str_To_Name_Buffer ("constant ");
elsif Ekind (Val_Id) = E_Discriminant then
Add_Str_To_Name_Buffer ("discriminant ");
elsif Is_Formal (Val_Id) then
Add_Str_To_Name_Buffer ("parameter ");
elsif Ekind (Val_Id) = E_Variable then
Add_Str_To_Name_Buffer ("variable ");
end if;
Add_Str_To_Name_Buffer ("& is always True!");
Error := Name_Find;
Error_Msg_NE (Get_Name_String (Error), Val, Val_Id);
end if;
-- The construct is too complex to disect, issue a general message
else
Error_Msg_N ("?r?expression is always True!", Val);
end if;
end Explain_Redundancy;
-----------------------------
-- Find_Unique_Access_Type --
-----------------------------
function Find_Unique_Access_Type return Entity_Id is
Acc : Entity_Id;
E : Entity_Id;
S : Entity_Id;
begin
if Ekind (Etype (R)) in E_Allocator_Type | E_Access_Attribute_Type
then
Acc := Designated_Type (Etype (R));
elsif Ekind (Etype (L)) in E_Allocator_Type | E_Access_Attribute_Type
then
Acc := Designated_Type (Etype (L));
else
return Empty;
end if;
S := Current_Scope;
while S /= Standard_Standard loop
E := First_Entity (S);
while Present (E) loop
if Is_Type (E)
and then Is_Access_Type (E)
and then Ekind (E) /= E_Allocator_Type
and then Designated_Type (E) = Base_Type (Acc)
then
return E;
end if;
Next_Entity (E);
end loop;
S := Scope (S);
end loop;
return Empty;
end Find_Unique_Access_Type;
-- Start of processing for Resolve_Equality_Op
begin
Set_Etype (N, Base_Type (Typ));
Generate_Reference (T, N, ' ');
if T = Any_Fixed then
T := Unique_Fixed_Point_Type (L);
end if;
if T /= Any_Type then
if T = Any_String or else
T = Any_Composite or else
T = Any_Character
then
if T = Any_Character then
Ambiguous_Character (L);
else
Error_Msg_N ("ambiguous operands for equality", N);
end if;
Set_Etype (N, Any_Type);
return;
elsif T = Any_Access
or else Ekind (T) in E_Allocator_Type | E_Access_Attribute_Type
then
T := Find_Unique_Access_Type;
if No (T) then
Error_Msg_N ("ambiguous operands for equality", N);
Set_Etype (N, Any_Type);
return;
end if;
-- If expressions must have a single type, and if the context does
-- not impose one the dependent expressions cannot be anonymous
-- access types.
-- Why no similar processing for case expressions???
elsif Ada_Version >= Ada_2012
and then Is_Anonymous_Access_Type (Etype (L))
and then Is_Anonymous_Access_Type (Etype (R))
then
Check_If_Expression (L);
Check_If_Expression (R);
end if;
Resolve (L, T);
Resolve (R, T);
-- If the unique type is a class-wide type then it will be expanded
-- into a dispatching call to the predefined primitive. Therefore we
-- check here for potential violation of such restriction.
if Is_Class_Wide_Type (T) then
Check_Restriction (No_Dispatching_Calls, N);
end if;
-- Only warn for redundant equality comparison to True for objects
-- (e.g. "X = True") and operations (e.g. "(X < Y) = True"). For
-- other expressions, it may be a matter of preference to write
-- "Expr = True" or "Expr".
if Warn_On_Redundant_Constructs
and then Comes_From_Source (N)
and then Comes_From_Source (R)
and then Is_Entity_Name (R)
and then Entity (R) = Standard_True
and then
((Is_Entity_Name (L) and then Is_Object (Entity (L)))
or else
Nkind (L) in N_Op)
then
Error_Msg_N -- CODEFIX
("?r?comparison with True is redundant!", N);
Explain_Redundancy (Original_Node (R));
end if;
-- If the equality is overloaded and the operands have resolved
-- properly, set the proper equality operator on the node. The
-- current setting is the first one found during analysis, which
-- is not necessarily the one to which the node has resolved.
if Is_Overloaded (N) then
declare
I : Interp_Index;
It : Interp;
begin
Get_First_Interp (N, I, It);
-- If the equality is user-defined, the type of the operands
-- matches that of the formals. For a predefined operator,
-- it is the scope that matters, given that the predefined
-- equality has Any_Type formals. In either case the result
-- type (most often Boolean) must match the context. The scope
-- is either that of the type, if there is a generated equality
-- (when there is an equality for the component type), or else
-- Standard otherwise.
while Present (It.Typ) loop
if Etype (It.Nam) = Typ
and then
(Etype (First_Entity (It.Nam)) = Etype (L)
or else Scope (It.Nam) = Standard_Standard
or else Scope (It.Nam) = Scope (T))
then
Set_Entity (N, It.Nam);
Set_Is_Overloaded (N, False);
exit;
end if;
Get_Next_Interp (I, It);
end loop;
-- If expansion is active and this is an inherited operation,
-- replace it with its ancestor. This must not be done during
-- preanalysis because the type may not be frozen yet, as when
-- the context is a precondition or postcondition.
if Present (Alias (Entity (N))) and then Expander_Active then
Set_Entity (N, Alias (Entity (N)));
end if;
end;
end if;
Check_Unset_Reference (L);
Check_Unset_Reference (R);
Generate_Operator_Reference (N, T);
Check_Low_Bound_Tested (N);
-- If this is an inequality, it may be the implicit inequality
-- created for a user-defined operation, in which case the corres-
-- ponding equality operation is not intrinsic, and the operation
-- cannot be constant-folded. Else fold.
if Nkind (N) = N_Op_Eq
or else Comes_From_Source (Entity (N))
or else Ekind (Entity (N)) = E_Operator
or else Is_Intrinsic_Subprogram
(Corresponding_Equality (Entity (N)))
then
Analyze_Dimension (N);
Eval_Relational_Op (N);
elsif Nkind (N) = N_Op_Ne
and then Is_Abstract_Subprogram (Entity (N))
then
Error_Msg_NE ("cannot call abstract subprogram &!", N, Entity (N));
end if;
-- Ada 2005: If one operand is an anonymous access type, convert the
-- other operand to it, to ensure that the underlying types match in
-- the back-end. Same for access_to_subprogram, and the conversion
-- verifies that the types are subtype conformant.
-- We apply the same conversion in the case one of the operands is a
-- private subtype of the type of the other.
-- Why the Expander_Active test here ???
if Expander_Active
and then
(Ekind (T) in E_Anonymous_Access_Type
| E_Anonymous_Access_Subprogram_Type
or else Is_Private_Type (T))
then
if Etype (L) /= T then
Rewrite (L,
Make_Unchecked_Type_Conversion (Sloc (L),
Subtype_Mark => New_Occurrence_Of (T, Sloc (L)),
Expression => Relocate_Node (L)));
Analyze_And_Resolve (L, T);
end if;
if (Etype (R)) /= T then
Rewrite (R,
Make_Unchecked_Type_Conversion (Sloc (R),
Subtype_Mark => New_Occurrence_Of (Etype (L), Sloc (R)),
Expression => Relocate_Node (R)));
Analyze_And_Resolve (R, T);
end if;
end if;
end if;
end Resolve_Equality_Op;
----------------------------------
-- Resolve_Explicit_Dereference --
----------------------------------
procedure Resolve_Explicit_Dereference (N : Node_Id; Typ : Entity_Id) is
Loc : constant Source_Ptr := Sloc (N);
New_N : Node_Id;
P : constant Node_Id := Prefix (N);
P_Typ : Entity_Id;
-- The candidate prefix type, if overloaded
I : Interp_Index;
It : Interp;
begin
Check_Fully_Declared_Prefix (Typ, P);
P_Typ := Empty;
-- A useful optimization: check whether the dereference denotes an
-- element of a container, and if so rewrite it as a call to the
-- corresponding Element function.
-- Disabled for now, on advice of ARG. A more restricted form of the
-- predicate might be acceptable ???
-- if Is_Container_Element (N) then
-- return;
-- end if;
if Is_Overloaded (P) then
-- Use the context type to select the prefix that has the correct
-- designated type. Keep the first match, which will be the inner-
-- most.
Get_First_Interp (P, I, It);
while Present (It.Typ) loop
if Is_Access_Type (It.Typ)
and then Covers (Typ, Designated_Type (It.Typ))
then
if No (P_Typ) then
P_Typ := It.Typ;
end if;
-- Remove access types that do not match, but preserve access
-- to subprogram interpretations, in case a further dereference
-- is needed (see below).
elsif Ekind (It.Typ) /= E_Access_Subprogram_Type then
Remove_Interp (I);
end if;
Get_Next_Interp (I, It);
end loop;
if Present (P_Typ) then
Resolve (P, P_Typ);
Set_Etype (N, Designated_Type (P_Typ));
else
-- If no interpretation covers the designated type of the prefix,
-- this is the pathological case where not all implementations of
-- the prefix allow the interpretation of the node as a call. Now
-- that the expected type is known, Remove other interpretations
-- from prefix, rewrite it as a call, and resolve again, so that
-- the proper call node is generated.
Get_First_Interp (P, I, It);
while Present (It.Typ) loop
if Ekind (It.Typ) /= E_Access_Subprogram_Type then
Remove_Interp (I);
end if;
Get_Next_Interp (I, It);
end loop;
New_N :=
Make_Function_Call (Loc,
Name =>
Make_Explicit_Dereference (Loc,
Prefix => P),
Parameter_Associations => New_List);
Save_Interps (N, New_N);
Rewrite (N, New_N);
Analyze_And_Resolve (N, Typ);
return;
end if;
-- If not overloaded, resolve P with its own type
else
Resolve (P);
end if;
-- If the prefix might be null, add an access check
if Is_Access_Type (Etype (P))
and then not Can_Never_Be_Null (Etype (P))
then
Apply_Access_Check (N);
end if;
-- If the designated type is a packed unconstrained array type, and the
-- explicit dereference is not in the context of an attribute reference,
-- then we must compute and set the actual subtype, since it is needed
-- by Gigi. The reason we exclude the attribute case is that this is
-- handled fine by Gigi, and in fact we use such attributes to build the
-- actual subtype. We also exclude generated code (which builds actual
-- subtypes directly if they are needed).
if Is_Array_Type (Etype (N))
and then Is_Packed (Etype (N))
and then not Is_Constrained (Etype (N))
and then Nkind (Parent (N)) /= N_Attribute_Reference
and then Comes_From_Source (N)
then
Set_Etype (N, Get_Actual_Subtype (N));
end if;
Analyze_Dimension (N);
-- Note: No Eval processing is required for an explicit dereference,
-- because such a name can never be static.
end Resolve_Explicit_Dereference;
-------------------------------------
-- Resolve_Expression_With_Actions --
-------------------------------------
procedure Resolve_Expression_With_Actions (N : Node_Id; Typ : Entity_Id) is
function OK_For_Static (Act : Node_Id) return Boolean;
-- True if Act is an action of a declare_expression that is allowed in a
-- static declare_expression.
function All_OK_For_Static return Boolean;
-- True if all actions of N are allowed in a static declare_expression.
function Get_Literal (Expr : Node_Id) return Node_Id;
-- Expr is an expression with compile-time-known value. This returns the
-- literal node that reprsents that value.
function OK_For_Static (Act : Node_Id) return Boolean is
begin
case Nkind (Act) is
when N_Object_Declaration =>
if Constant_Present (Act)
and then Is_Static_Expression (Expression (Act))
then
return True;
end if;
when N_Object_Renaming_Declaration =>
if Statically_Names_Object (Name (Act)) then
return True;
end if;
when others =>
-- No other declarations, nor even pragmas, are allowed in a
-- declare expression, so if we see something else, it must be
-- an internally generated expression_with_actions.
null;
end case;
return False;
end OK_For_Static;
function All_OK_For_Static return Boolean is
Act : Node_Id := First (Actions (N));
begin
while Present (Act) loop
if not OK_For_Static (Act) then
return False;
end if;
Next (Act);
end loop;
return True;
end All_OK_For_Static;
function Get_Literal (Expr : Node_Id) return Node_Id is
pragma Assert (Compile_Time_Known_Value (Expr));
Result : Node_Id;
begin
case Nkind (Expr) is
when N_Has_Entity =>
if Ekind (Entity (Expr)) = E_Enumeration_Literal then
Result := Expr;
else
Result := Constant_Value (Entity (Expr));
end if;
when N_Numeric_Or_String_Literal =>
Result := Expr;
when others =>
raise Program_Error;
end case;
pragma Assert
(Nkind (Result) in N_Numeric_Or_String_Literal
or else Ekind (Entity (Result)) = E_Enumeration_Literal);
return Result;
end Get_Literal;
Loc : constant Source_Ptr := Sloc (N);
begin
Set_Etype (N, Typ);
if Is_Empty_List (Actions (N)) then
pragma Assert (All_OK_For_Static); null;
end if;
-- If the value of the expression is known at compile time, and all
-- of the actions (if any) are suitable, then replace the declare
-- expression with its expression. This allows the declare expression
-- as a whole to be static if appropriate. See AI12-0368.
if Compile_Time_Known_Value (Expression (N)) then
if Is_Empty_List (Actions (N)) then
Rewrite (N, Expression (N));
elsif All_OK_For_Static then
Rewrite
(N, New_Copy_Tree
(Get_Literal (Expression (N)), New_Sloc => Loc));
end if;
end if;
end Resolve_Expression_With_Actions;
----------------------------------
-- Resolve_Generalized_Indexing --
----------------------------------
procedure Resolve_Generalized_Indexing (N : Node_Id; Typ : Entity_Id) is
Indexing : constant Node_Id := Generalized_Indexing (N);
begin
Rewrite (N, Indexing);
Resolve (N, Typ);
end Resolve_Generalized_Indexing;
---------------------------
-- Resolve_If_Expression --
---------------------------
procedure Resolve_If_Expression (N : Node_Id; Typ : Entity_Id) is
procedure Apply_Check (Expr : Node_Id);
-- When a dependent expression is of a subtype different from
-- the context subtype, then insert a qualification to ensure
-- the generation of a constraint check. This was previously
-- for scalar types. For array types apply a length check, given
-- that the context in general allows sliding, while a qualified
-- expression forces equality of bounds.
-----------------
-- Apply_Check --
-----------------
procedure Apply_Check (Expr : Node_Id) is
Expr_Typ : constant Entity_Id := Etype (Expr);
Loc : constant Source_Ptr := Sloc (Expr);
begin
if Expr_Typ = Typ
or else Is_Tagged_Type (Typ)
or else Is_Access_Type (Typ)
or else not Is_Constrained (Typ)
or else Inside_A_Generic
then
null;
elsif Is_Array_Type (Typ) then
Apply_Length_Check (Expr, Typ);
else
Rewrite (Expr,
Make_Qualified_Expression (Loc,
Subtype_Mark => New_Occurrence_Of (Typ, Loc),
Expression => Relocate_Node (Expr)));
Analyze_And_Resolve (Expr, Typ);
end if;
end Apply_Check;
-- Local variables
Condition : constant Node_Id := First (Expressions (N));
Else_Expr : Node_Id;
Then_Expr : Node_Id;
-- Start of processing for Resolve_If_Expression
begin
-- Defend against malformed expressions
if No (Condition) then
return;
end if;
Then_Expr := Next (Condition);
if No (Then_Expr) then
return;
end if;
Else_Expr := Next (Then_Expr);
Resolve (Condition, Any_Boolean);
Resolve (Then_Expr, Typ);
Apply_Check (Then_Expr);
-- If ELSE expression present, just resolve using the determined type
-- If type is universal, resolve to any member of the class.
if Present (Else_Expr) then
if Typ = Universal_Integer then
Resolve (Else_Expr, Any_Integer);
elsif Typ = Universal_Real then
Resolve (Else_Expr, Any_Real);
else
Resolve (Else_Expr, Typ);
end if;
Apply_Check (Else_Expr);
-- Apply RM 4.5.7 (17/3): whether the expression is statically or
-- dynamically tagged must be known statically.
if Is_Tagged_Type (Typ) and then not Is_Class_Wide_Type (Typ) then
if Is_Dynamically_Tagged (Then_Expr) /=
Is_Dynamically_Tagged (Else_Expr)
then
Error_Msg_N ("all or none of the dependent expressions "
& "can be dynamically tagged", N);
end if;
end if;
-- If no ELSE expression is present, root type must be Standard.Boolean
-- and we provide a Standard.True result converted to the appropriate
-- Boolean type (in case it is a derived boolean type).
elsif Root_Type (Typ) = Standard_Boolean then
Else_Expr :=
Convert_To (Typ, New_Occurrence_Of (Standard_True, Sloc (N)));
Analyze_And_Resolve (Else_Expr, Typ);
Append_To (Expressions (N), Else_Expr);
else
Error_Msg_N ("can only omit ELSE expression in Boolean case", N);
Append_To (Expressions (N), Error);
end if;
Set_Etype (N, Typ);
if not Error_Posted (N) then
Eval_If_Expression (N);
end if;
Analyze_Dimension (N);
end Resolve_If_Expression;
----------------------------------
-- Resolve_Implicit_Dereference --
----------------------------------
procedure Resolve_Implicit_Dereference (P : Node_Id) is
Desig_Typ : Entity_Id;
begin
-- In an instance the proper view may not always be correct for
-- private types, see e.g. Sem_Type.Covers for similar handling.
if Is_Private_Type (Etype (P))
and then Present (Full_View (Etype (P)))
and then Is_Access_Type (Full_View (Etype (P)))
and then In_Instance
then
Set_Etype (P, Full_View (Etype (P)));
end if;
if Is_Access_Type (Etype (P)) then
Desig_Typ := Implicitly_Designated_Type (Etype (P));
Insert_Explicit_Dereference (P);
Analyze_And_Resolve (P, Desig_Typ);
end if;
end Resolve_Implicit_Dereference;
-------------------------------
-- Resolve_Indexed_Component --
-------------------------------
procedure Resolve_Indexed_Component (N : Node_Id; Typ : Entity_Id) is
Name : constant Node_Id := Prefix (N);
Expr : Node_Id;
Array_Type : Entity_Id := Empty; -- to prevent junk warning
Index : Node_Id;
begin
if Present (Generalized_Indexing (N)) then
Resolve_Generalized_Indexing (N, Typ);
return;
end if;
if Is_Overloaded (Name) then
-- Use the context type to select the prefix that yields the correct
-- component type.
declare
I : Interp_Index;
It : Interp;
I1 : Interp_Index := 0;
P : constant Node_Id := Prefix (N);
Found : Boolean := False;
begin
Get_First_Interp (P, I, It);
while Present (It.Typ) loop
if (Is_Array_Type (It.Typ)
and then Covers (Typ, Component_Type (It.Typ)))
or else (Is_Access_Type (It.Typ)
and then Is_Array_Type (Designated_Type (It.Typ))
and then
Covers
(Typ,
Component_Type (Designated_Type (It.Typ))))
then
if Found then
It := Disambiguate (P, I1, I, Any_Type);
if It = No_Interp then
Error_Msg_N ("ambiguous prefix for indexing", N);
Set_Etype (N, Typ);
return;
else
Found := True;
Array_Type := It.Typ;
I1 := I;
end if;
else
Found := True;
Array_Type := It.Typ;
I1 := I;
end if;
end if;
Get_Next_Interp (I, It);
end loop;
end;
else
Array_Type := Etype (Name);
end if;
Resolve (Name, Array_Type);
Array_Type := Get_Actual_Subtype_If_Available (Name);
-- If the prefix's type is an access type, get to the real array type.
-- Note: we do not apply an access check because an explicit dereference
-- will be introduced later, and the check will happen there.
if Is_Access_Type (Array_Type) then
Array_Type := Implicitly_Designated_Type (Array_Type);
end if;
-- If name was overloaded, set component type correctly now.
-- If a misplaced call to an entry family (which has no index types)
-- return. Error will be diagnosed from calling context.
if Is_Array_Type (Array_Type) then
Set_Etype (N, Component_Type (Array_Type));
else
return;
end if;
Index := First_Index (Array_Type);
Expr := First (Expressions (N));
-- The prefix may have resolved to a string literal, in which case its
-- etype has a special representation. This is only possible currently
-- if the prefix is a static concatenation, written in functional
-- notation.
if Ekind (Array_Type) = E_String_Literal_Subtype then
Resolve (Expr, Standard_Positive);
else
while Present (Index) and then Present (Expr) loop
Resolve (Expr, Etype (Index));
Check_Unset_Reference (Expr);
Apply_Scalar_Range_Check (Expr, Etype (Index));
Next_Index (Index);
Next (Expr);
end loop;
end if;
Resolve_Implicit_Dereference (Prefix (N));
Analyze_Dimension (N);
-- Do not generate the warning on suspicious index if we are analyzing
-- package Ada.Tags; otherwise we will report the warning with the
-- Prims_Ptr field of the dispatch table.
if Scope (Etype (Prefix (N))) = Standard_Standard
or else not
Is_RTU (Cunit_Entity (Get_Source_Unit (Etype (Prefix (N)))),
Ada_Tags)
then
Warn_On_Suspicious_Index (Name, First (Expressions (N)));
Eval_Indexed_Component (N);
end if;
-- If the array type is atomic and the component is not, then this is
-- worth a warning before Ada 2020, since we have a situation where the
-- access to the component may cause extra read/writes of the atomic
-- object, or partial word accesses, both of which may be unexpected.
if Nkind (N) = N_Indexed_Component
and then Is_Atomic_Ref_With_Address (N)
and then not (Has_Atomic_Components (Array_Type)
or else (Is_Entity_Name (Prefix (N))
and then Has_Atomic_Components
(Entity (Prefix (N)))))
and then not Is_Atomic (Component_Type (Array_Type))
and then Ada_Version < Ada_2020
then
Error_Msg_N
("??access to non-atomic component of atomic array", Prefix (N));
Error_Msg_N
("??\may cause unexpected accesses to atomic object", Prefix (N));
end if;
end Resolve_Indexed_Component;
-----------------------------
-- Resolve_Integer_Literal --
-----------------------------
procedure Resolve_Integer_Literal (N : Node_Id; Typ : Entity_Id) is
begin
Set_Etype (N, Typ);
Eval_Integer_Literal (N);
end Resolve_Integer_Literal;
--------------------------------
-- Resolve_Intrinsic_Operator --
--------------------------------
procedure Resolve_Intrinsic_Operator (N : Node_Id; Typ : Entity_Id) is
Btyp : constant Entity_Id := Base_Type (Underlying_Type (Typ));
Op : Entity_Id;
Arg1 : Node_Id;
Arg2 : Node_Id;
function Convert_Operand (Opnd : Node_Id) return Node_Id;
-- If the operand is a literal, it cannot be the expression in a
-- conversion. Use a qualified expression instead.
---------------------
-- Convert_Operand --
---------------------
function Convert_Operand (Opnd : Node_Id) return Node_Id is
Loc : constant Source_Ptr := Sloc (Opnd);
Res : Node_Id;
begin
if Nkind (Opnd) in N_Integer_Literal | N_Real_Literal then
Res :=
Make_Qualified_Expression (Loc,
Subtype_Mark => New_Occurrence_Of (Btyp, Loc),
Expression => Relocate_Node (Opnd));
Analyze (Res);
else
Res := Unchecked_Convert_To (Btyp, Opnd);
end if;
return Res;
end Convert_Operand;
-- Start of processing for Resolve_Intrinsic_Operator
begin
-- We must preserve the original entity in a generic setting, so that
-- the legality of the operation can be verified in an instance.
if not Expander_Active then
return;
end if;
Op := Entity (N);
while Scope (Op) /= Standard_Standard loop
Op := Homonym (Op);
pragma Assert (Present (Op));
end loop;
Set_Entity (N, Op);
Set_Is_Overloaded (N, False);
-- If the result or operand types are private, rewrite with unchecked
-- conversions on the operands and the result, to expose the proper
-- underlying numeric type.
if Is_Private_Type (Typ)
or else Is_Private_Type (Etype (Left_Opnd (N)))
or else Is_Private_Type (Etype (Right_Opnd (N)))
then
Arg1 := Convert_Operand (Left_Opnd (N));
if Nkind (N) = N_Op_Expon then
Arg2 := Unchecked_Convert_To (Standard_Integer, Right_Opnd (N));
else
Arg2 := Convert_Operand (Right_Opnd (N));
end if;
if Nkind (Arg1) = N_Type_Conversion then
Save_Interps (Left_Opnd (N), Expression (Arg1));
end if;
if Nkind (Arg2) = N_Type_Conversion then
Save_Interps (Right_Opnd (N), Expression (Arg2));
end if;
Set_Left_Opnd (N, Arg1);
Set_Right_Opnd (N, Arg2);
Set_Etype (N, Btyp);
Rewrite (N, Unchecked_Convert_To (Typ, N));
Resolve (N, Typ);
elsif Typ /= Etype (Left_Opnd (N))
or else Typ /= Etype (Right_Opnd (N))
then
-- Add explicit conversion where needed, and save interpretations in
-- case operands are overloaded.
Arg1 := Convert_To (Typ, Left_Opnd (N));
Arg2 := Convert_To (Typ, Right_Opnd (N));
if Nkind (Arg1) = N_Type_Conversion then
Save_Interps (Left_Opnd (N), Expression (Arg1));
else
Save_Interps (Left_Opnd (N), Arg1);
end if;
if Nkind (Arg2) = N_Type_Conversion then
Save_Interps (Right_Opnd (N), Expression (Arg2));
else
Save_Interps (Right_Opnd (N), Arg2);
end if;
Rewrite (Left_Opnd (N), Arg1);
Rewrite (Right_Opnd (N), Arg2);
Analyze (Arg1);
Analyze (Arg2);
Resolve_Arithmetic_Op (N, Typ);
else
Resolve_Arithmetic_Op (N, Typ);
end if;
end Resolve_Intrinsic_Operator;
--------------------------------------
-- Resolve_Intrinsic_Unary_Operator --
--------------------------------------
procedure Resolve_Intrinsic_Unary_Operator
(N : Node_Id;
Typ : Entity_Id)
is
Btyp : constant Entity_Id := Base_Type (Underlying_Type (Typ));
Op : Entity_Id;
Arg2 : Node_Id;
begin
Op := Entity (N);
while Scope (Op) /= Standard_Standard loop
Op := Homonym (Op);
pragma Assert (Present (Op));
end loop;
Set_Entity (N, Op);
if Is_Private_Type (Typ) then
Arg2 := Unchecked_Convert_To (Btyp, Right_Opnd (N));
Save_Interps (Right_Opnd (N), Expression (Arg2));
Set_Right_Opnd (N, Arg2);
Set_Etype (N, Btyp);
Rewrite (N, Unchecked_Convert_To (Typ, N));
Resolve (N, Typ);
else
Resolve_Unary_Op (N, Typ);
end if;
end Resolve_Intrinsic_Unary_Operator;
------------------------
-- Resolve_Logical_Op --
------------------------
procedure Resolve_Logical_Op (N : Node_Id; Typ : Entity_Id) is
B_Typ : Entity_Id;
begin
Check_No_Direct_Boolean_Operators (N);
-- Predefined operations on scalar types yield the base type. On the
-- other hand, logical operations on arrays yield the type of the
-- arguments (and the context).
if Is_Array_Type (Typ) then
B_Typ := Typ;
else
B_Typ := Base_Type (Typ);
end if;
-- The following test is required because the operands of the operation
-- may be literals, in which case the resulting type appears to be
-- compatible with a signed integer type, when in fact it is compatible
-- only with modular types. If the context itself is universal, the
-- operation is illegal.
if not Valid_Boolean_Arg (Typ) then
Error_Msg_N ("invalid context for logical operation", N);
Set_Etype (N, Any_Type);
return;
elsif Typ = Any_Modular then
Error_Msg_N
("no modular type available in this context", N);
Set_Etype (N, Any_Type);
return;
elsif Is_Modular_Integer_Type (Typ)
and then Etype (Left_Opnd (N)) = Universal_Integer
and then Etype (Right_Opnd (N)) = Universal_Integer
then
Check_For_Visible_Operator (N, B_Typ);
end if;
-- Replace AND by AND THEN, or OR by OR ELSE, if Short_Circuit_And_Or
-- is active and the result type is standard Boolean (do not mess with
-- ops that return a nonstandard Boolean type, because something strange
-- is going on).
-- Note: you might expect this replacement to be done during expansion,
-- but that doesn't work, because when the pragma Short_Circuit_And_Or
-- is used, no part of the right operand of an "and" or "or" operator
-- should be executed if the left operand would short-circuit the
-- evaluation of the corresponding "and then" or "or else". If we left
-- the replacement to expansion time, then run-time checks associated
-- with such operands would be evaluated unconditionally, due to being
-- before the condition prior to the rewriting as short-circuit forms
-- during expansion.
if Short_Circuit_And_Or
and then B_Typ = Standard_Boolean
and then Nkind (N) in N_Op_And | N_Op_Or
then
-- Mark the corresponding putative SCO operator as truly a logical
-- (and short-circuit) operator.
if Generate_SCO and then Comes_From_Source (N) then
Set_SCO_Logical_Operator (N);
end if;
if Nkind (N) = N_Op_And then
Rewrite (N,
Make_And_Then (Sloc (N),
Left_Opnd => Relocate_Node (Left_Opnd (N)),
Right_Opnd => Relocate_Node (Right_Opnd (N))));
Analyze_And_Resolve (N, B_Typ);
-- Case of OR changed to OR ELSE
else
Rewrite (N,
Make_Or_Else (Sloc (N),
Left_Opnd => Relocate_Node (Left_Opnd (N)),
Right_Opnd => Relocate_Node (Right_Opnd (N))));
Analyze_And_Resolve (N, B_Typ);
end if;
-- Return now, since analysis of the rewritten ops will take care of
-- other reference bookkeeping and expression folding.
return;
end if;
Resolve (Left_Opnd (N), B_Typ);
Resolve (Right_Opnd (N), B_Typ);
Check_Unset_Reference (Left_Opnd (N));
Check_Unset_Reference (Right_Opnd (N));
Set_Etype (N, B_Typ);
Generate_Operator_Reference (N, B_Typ);
Eval_Logical_Op (N);
end Resolve_Logical_Op;
---------------------------
-- Resolve_Membership_Op --
---------------------------
-- The context can only be a boolean type, and does not determine the
-- arguments. Arguments should be unambiguous, but the preference rule for
-- universal types applies.
procedure Resolve_Membership_Op (N : Node_Id; Typ : Entity_Id) is
pragma Warnings (Off, Typ);
L : constant Node_Id := Left_Opnd (N);
R : constant Node_Id := Right_Opnd (N);
T : Entity_Id;
procedure Resolve_Set_Membership;
-- Analysis has determined a unique type for the left operand. Use it as
-- the basis to resolve the disjuncts.
----------------------------
-- Resolve_Set_Membership --
----------------------------
procedure Resolve_Set_Membership is
Alt : Node_Id;
begin
-- If the left operand is overloaded, find type compatible with not
-- overloaded alternative of the right operand.
Alt := First (Alternatives (N));
if Is_Overloaded (L) then
T := Empty;
while Present (Alt) loop
if not Is_Overloaded (Alt) then
T := Intersect_Types (L, Alt);
exit;
else
Next (Alt);
end if;
end loop;
-- Unclear how to resolve expression if all alternatives are also
-- overloaded.
if No (T) then
Error_Msg_N ("ambiguous expression", N);
end if;
else
T := Intersect_Types (L, Alt);
end if;
Resolve (L, T);
Alt := First (Alternatives (N));
while Present (Alt) loop
-- Alternative is an expression, a range
-- or a subtype mark.
if not Is_Entity_Name (Alt)
or else not Is_Type (Entity (Alt))
then
Resolve (Alt, T);
end if;
Next (Alt);
end loop;
-- Check for duplicates for discrete case
if Is_Discrete_Type (T) then
declare
type Ent is record
Alt : Node_Id;
Val : Uint;
end record;
Alts : array (0 .. List_Length (Alternatives (N))) of Ent;
Nalts : Nat;
begin
-- Loop checking duplicates. This is quadratic, but giant sets
-- are unlikely in this context so it's a reasonable choice.
Nalts := 0;
Alt := First (Alternatives (N));
while Present (Alt) loop
if Is_OK_Static_Expression (Alt)
and then Nkind (Alt) in N_Integer_Literal
| N_Character_Literal
| N_Has_Entity
then
Nalts := Nalts + 1;
Alts (Nalts) := (Alt, Expr_Value (Alt));
for J in 1 .. Nalts - 1 loop
if Alts (J).Val = Alts (Nalts).Val then
Error_Msg_Sloc := Sloc (Alts (J).Alt);
Error_Msg_N ("duplicate of value given#??", Alt);
end if;
end loop;
end if;
Next (Alt);
end loop;
end;
end if;
-- RM 4.5.2 (28.1/3) specifies that for types other than records or
-- limited types, evaluation of a membership test uses the predefined
-- equality for the type. This may be confusing to users, and the
-- following warning appears useful for the most common case.
if Is_Scalar_Type (Etype (L))
and then Present (Get_User_Defined_Eq (Etype (L)))
then
Error_Msg_NE
("membership test on& uses predefined equality?", N, Etype (L));
Error_Msg_N
("\even if user-defined equality exists (RM 4.5.2 (28.1/3)?", N);
end if;
end Resolve_Set_Membership;
-- Start of processing for Resolve_Membership_Op
begin
if L = Error or else R = Error then
return;
end if;
if Present (Alternatives (N)) then
Resolve_Set_Membership;
goto SM_Exit;
elsif not Is_Overloaded (R)
and then
(Etype (R) = Universal_Integer
or else
Etype (R) = Universal_Real)
and then Is_Overloaded (L)
then
T := Etype (R);
-- Ada 2005 (AI-251): Support the following case:
-- type I is interface;
-- type T is tagged ...
-- function Test (O : I'Class) is
-- begin
-- return O in T'Class.
-- end Test;
-- In this case we have nothing else to do. The membership test will be
-- done at run time.
elsif Ada_Version >= Ada_2005
and then Is_Class_Wide_Type (Etype (L))
and then Is_Interface (Etype (L))
and then not Is_Interface (Etype (R))
then
return;
else
T := Intersect_Types (L, R);
end if;
-- If mixed-mode operations are present and operands are all literal,
-- the only interpretation involves Duration, which is probably not
-- the intention of the programmer.
if T = Any_Fixed then
T := Unique_Fixed_Point_Type (N);
if T = Any_Type then
return;
end if;
end if;
Resolve (L, T);
Check_Unset_Reference (L);
if Nkind (R) = N_Range
and then not Is_Scalar_Type (T)
then
Error_Msg_N ("scalar type required for range", R);
end if;
if Is_Entity_Name (R) then
Freeze_Expression (R);
else
Resolve (R, T);
Check_Unset_Reference (R);
end if;
-- Here after resolving membership operation
<<SM_Exit>>
Eval_Membership_Op (N);
end Resolve_Membership_Op;
------------------
-- Resolve_Null --
------------------
procedure Resolve_Null (N : Node_Id; Typ : Entity_Id) is
Loc : constant Source_Ptr := Sloc (N);
begin
-- Handle restriction against anonymous null access values This
-- restriction can be turned off using -gnatdj.
-- Ada 2005 (AI-231): Remove restriction
if Ada_Version < Ada_2005
and then not Debug_Flag_J
and then Ekind (Typ) = E_Anonymous_Access_Type
and then Comes_From_Source (N)
then
-- In the common case of a call which uses an explicitly null value
-- for an access parameter, give specialized error message.
if Nkind (Parent (N)) in N_Subprogram_Call then
Error_Msg_N
("null is not allowed as argument for an access parameter", N);
-- Standard message for all other cases (are there any?)
else
Error_Msg_N
("null cannot be of an anonymous access type", N);
end if;
end if;
-- Ada 2005 (AI-231): Generate the null-excluding check in case of
-- assignment to a null-excluding object.
if Ada_Version >= Ada_2005
and then Can_Never_Be_Null (Typ)
and then Nkind (Parent (N)) = N_Assignment_Statement
then
if Inside_Init_Proc then
-- Decide whether to generate an if_statement around our
-- null-excluding check to avoid them on certain internal object
-- declarations by looking at the type the current Init_Proc
-- belongs to.
-- Generate:
-- if T1b_skip_null_excluding_check then
-- [constraint_error "access check failed"]
-- end if;
if Needs_Conditional_Null_Excluding_Check
(Etype (First_Formal (Enclosing_Init_Proc)))
then
Insert_Action (N,
Make_If_Statement (Loc,
Condition =>
Make_Identifier (Loc,
New_External_Name
(Chars (Typ), "_skip_null_excluding_check")),
Then_Statements =>
New_List (
Make_Raise_Constraint_Error (Loc,
Reason => CE_Access_Check_Failed))));
-- Otherwise, simply create the check
else
Insert_Action (N,
Make_Raise_Constraint_Error (Loc,
Reason => CE_Access_Check_Failed));
end if;
else
Insert_Action
(Compile_Time_Constraint_Error (N,
"(Ada 2005) null not allowed in null-excluding objects??"),
Make_Raise_Constraint_Error (Loc,
Reason => CE_Access_Check_Failed));
end if;
end if;
-- In a distributed context, null for a remote access to subprogram may
-- need to be replaced with a special record aggregate. In this case,
-- return after having done the transformation.
if (Ekind (Typ) = E_Record_Type
or else Is_Remote_Access_To_Subprogram_Type (Typ))
and then Remote_AST_Null_Value (N, Typ)
then
return;
end if;
-- The null literal takes its type from the context
Set_Etype (N, Typ);
end Resolve_Null;
-----------------------
-- Resolve_Op_Concat --
-----------------------
procedure Resolve_Op_Concat (N : Node_Id; Typ : Entity_Id) is
-- We wish to avoid deep recursion, because concatenations are often
-- deeply nested, as in A&B&...&Z. Therefore, we walk down the left
-- operands nonrecursively until we find something that is not a simple
-- concatenation (A in this case). We resolve that, and then walk back
-- up the tree following Parent pointers, calling Resolve_Op_Concat_Rest
-- to do the rest of the work at each level. The Parent pointers allow
-- us to avoid recursion, and thus avoid running out of memory. See also
-- Sem_Ch4.Analyze_Concatenation, where a similar approach is used.
NN : Node_Id := N;
Op1 : Node_Id;
begin
-- The following code is equivalent to:
-- Resolve_Op_Concat_First (NN, Typ);
-- Resolve_Op_Concat_Arg (N, ...);
-- Resolve_Op_Concat_Rest (N, Typ);
-- where the Resolve_Op_Concat_Arg call recurses back here if the left
-- operand is a concatenation.
-- Walk down left operands
loop
Resolve_Op_Concat_First (NN, Typ);
Op1 := Left_Opnd (NN);
exit when not (Nkind (Op1) = N_Op_Concat
and then not Is_Array_Type (Component_Type (Typ))
and then Entity (Op1) = Entity (NN));
NN := Op1;
end loop;
-- Now (given the above example) NN is A&B and Op1 is A
-- First resolve Op1 ...
Resolve_Op_Concat_Arg (NN, Op1, Typ, Is_Component_Left_Opnd (NN));
-- ... then walk NN back up until we reach N (where we started), calling
-- Resolve_Op_Concat_Rest along the way.
loop
Resolve_Op_Concat_Rest (NN, Typ);
exit when NN = N;
NN := Parent (NN);
end loop;
end Resolve_Op_Concat;
---------------------------
-- Resolve_Op_Concat_Arg --
---------------------------
procedure Resolve_Op_Concat_Arg
(N : Node_Id;
Arg : Node_Id;
Typ : Entity_Id;
Is_Comp : Boolean)
is
Btyp : constant Entity_Id := Base_Type (Typ);
Ctyp : constant Entity_Id := Component_Type (Typ);
begin
if In_Instance then
if Is_Comp
or else (not Is_Overloaded (Arg)
and then Etype (Arg) /= Any_Composite
and then Covers (Ctyp, Etype (Arg)))
then
Resolve (Arg, Ctyp);
else
Resolve (Arg, Btyp);
end if;
-- If both Array & Array and Array & Component are visible, there is a
-- potential ambiguity that must be reported.
elsif Has_Compatible_Type (Arg, Ctyp) then
if Nkind (Arg) = N_Aggregate
and then Is_Composite_Type (Ctyp)
then
if Is_Private_Type (Ctyp) then
Resolve (Arg, Btyp);
-- If the operation is user-defined and not overloaded use its
-- profile. The operation may be a renaming, in which case it has
-- been rewritten, and we want the original profile.
elsif not Is_Overloaded (N)
and then Comes_From_Source (Entity (Original_Node (N)))
and then Ekind (Entity (Original_Node (N))) = E_Function
then
Resolve (Arg,
Etype
(Next_Formal (First_Formal (Entity (Original_Node (N))))));
return;
-- Otherwise an aggregate may match both the array type and the
-- component type.
else
Error_Msg_N ("ambiguous aggregate must be qualified", Arg);
Set_Etype (Arg, Any_Type);
end if;
else
if Is_Overloaded (Arg)
and then Has_Compatible_Type (Arg, Typ)
and then Etype (Arg) /= Any_Type
then
declare
I : Interp_Index;
It : Interp;
Func : Entity_Id;
begin
Get_First_Interp (Arg, I, It);
Func := It.Nam;
Get_Next_Interp (I, It);
-- Special-case the error message when the overloading is
-- caused by a function that yields an array and can be
-- called without parameters.
if It.Nam = Func then
Error_Msg_Sloc := Sloc (Func);
Error_Msg_N ("ambiguous call to function#", Arg);
Error_Msg_NE
("\\interpretation as call yields&", Arg, Typ);
Error_Msg_NE
("\\interpretation as indexing of call yields&",
Arg, Component_Type (Typ));
else
Error_Msg_N ("ambiguous operand for concatenation!", Arg);
Get_First_Interp (Arg, I, It);
while Present (It.Nam) loop
Error_Msg_Sloc := Sloc (It.Nam);
if Base_Type (It.Typ) = Btyp
or else
Base_Type (It.Typ) = Base_Type (Ctyp)
then
Error_Msg_N -- CODEFIX
("\\possible interpretation#", Arg);
end if;
Get_Next_Interp (I, It);
end loop;
end if;
end;
end if;
Resolve (Arg, Component_Type (Typ));
if Nkind (Arg) = N_String_Literal then
Set_Etype (Arg, Component_Type (Typ));
end if;
if Arg = Left_Opnd (N) then
Set_Is_Component_Left_Opnd (N);
else
Set_Is_Component_Right_Opnd (N);
end if;
end if;
else
Resolve (Arg, Btyp);
end if;
Check_Unset_Reference (Arg);
end Resolve_Op_Concat_Arg;
-----------------------------
-- Resolve_Op_Concat_First --
-----------------------------
procedure Resolve_Op_Concat_First (N : Node_Id; Typ : Entity_Id) is
Btyp : constant Entity_Id := Base_Type (Typ);
Op1 : constant Node_Id := Left_Opnd (N);
Op2 : constant Node_Id := Right_Opnd (N);
begin
-- The parser folds an enormous sequence of concatenations of string
-- literals into "" & "...", where the Is_Folded_In_Parser flag is set
-- in the right operand. If the expression resolves to a predefined "&"
-- operator, all is well. Otherwise, the parser's folding is wrong, so
-- we give an error. See P_Simple_Expression in Par.Ch4.
if Nkind (Op2) = N_String_Literal
and then Is_Folded_In_Parser (Op2)
and then Ekind (Entity (N)) = E_Function
then
pragma Assert (Nkind (Op1) = N_String_Literal -- should be ""
and then String_Length (Strval (Op1)) = 0);
Error_Msg_N ("too many user-defined concatenations", N);
return;
end if;
Set_Etype (N, Btyp);
if Is_Limited_Composite (Btyp) then
Error_Msg_N ("concatenation not available for limited array", N);
Explain_Limited_Type (Btyp, N);
end if;
end Resolve_Op_Concat_First;
----------------------------
-- Resolve_Op_Concat_Rest --
----------------------------
procedure Resolve_Op_Concat_Rest (N : Node_Id; Typ : Entity_Id) is
Op1 : constant Node_Id := Left_Opnd (N);
Op2 : constant Node_Id := Right_Opnd (N);
begin
Resolve_Op_Concat_Arg (N, Op2, Typ, Is_Component_Right_Opnd (N));
Generate_Operator_Reference (N, Typ);
if Is_String_Type (Typ) then
Eval_Concatenation (N);
end if;
-- If this is not a static concatenation, but the result is a string
-- type (and not an array of strings) ensure that static string operands
-- have their subtypes properly constructed.
if Nkind (N) /= N_String_Literal
and then Is_Character_Type (Component_Type (Typ))
then
Set_String_Literal_Subtype (Op1, Typ);
Set_String_Literal_Subtype (Op2, Typ);
end if;
end Resolve_Op_Concat_Rest;
----------------------
-- Resolve_Op_Expon --
----------------------
procedure Resolve_Op_Expon (N : Node_Id; Typ : Entity_Id) is
B_Typ : constant Entity_Id := Base_Type (Typ);
begin
-- Catch attempts to do fixed-point exponentiation with universal
-- operands, which is a case where the illegality is not caught during
-- normal operator analysis. This is not done in preanalysis mode
-- since the tree is not fully decorated during preanalysis.
if Full_Analysis then
if Is_Fixed_Point_Type (Typ) and then Comes_From_Source (N) then
Error_Msg_N ("exponentiation not available for fixed point", N);
return;
elsif Nkind (Parent (N)) in N_Op
and then Present (Etype (Parent (N)))
and then Is_Fixed_Point_Type (Etype (Parent (N)))
and then Etype (N) = Universal_Real
and then Comes_From_Source (N)
then
Error_Msg_N ("exponentiation not available for fixed point", N);
return;
end if;
end if;
if Comes_From_Source (N)
and then Ekind (Entity (N)) = E_Function
and then Is_Imported (Entity (N))
and then Is_Intrinsic_Subprogram (Entity (N))
then
Resolve_Intrinsic_Operator (N, Typ);
return;
end if;
if Etype (Left_Opnd (N)) = Universal_Integer
or else Etype (Left_Opnd (N)) = Universal_Real
then
Check_For_Visible_Operator (N, B_Typ);
end if;
-- We do the resolution using the base type, because intermediate values
-- in expressions are always of the base type, not a subtype of it.
Resolve (Left_Opnd (N), B_Typ);
Resolve (Right_Opnd (N), Standard_Integer);
-- For integer types, right argument must be in Natural range
if Is_Integer_Type (Typ) then
Apply_Scalar_Range_Check (Right_Opnd (N), Standard_Natural);
end if;
Check_Unset_Reference (Left_Opnd (N));
Check_Unset_Reference (Right_Opnd (N));
Set_Etype (N, B_Typ);
Generate_Operator_Reference (N, B_Typ);
Analyze_Dimension (N);
if Ada_Version >= Ada_2012 and then Has_Dimension_System (B_Typ) then
-- Evaluate the exponentiation operator for dimensioned type
Eval_Op_Expon_For_Dimensioned_Type (N, B_Typ);
else
Eval_Op_Expon (N);
end if;
-- Set overflow checking bit. Much cleverer code needed here eventually
-- and perhaps the Resolve routines should be separated for the various
-- arithmetic operations, since they will need different processing. ???
if Nkind (N) in N_Op then
if not Overflow_Checks_Suppressed (Etype (N)) then
Enable_Overflow_Check (N);
end if;
end if;
end Resolve_Op_Expon;
--------------------
-- Resolve_Op_Not --
--------------------
procedure Resolve_Op_Not (N : Node_Id; Typ : Entity_Id) is
B_Typ : Entity_Id;
function Parent_Is_Boolean return Boolean;
-- This function determines if the parent node is a boolean operator or
-- operation (comparison op, membership test, or short circuit form) and
-- the not in question is the left operand of this operation. Note that
-- if the not is in parens, then false is returned.
-----------------------
-- Parent_Is_Boolean --
-----------------------
function Parent_Is_Boolean return Boolean is
begin
if Paren_Count (N) /= 0 then
return False;
else
case Nkind (Parent (N)) is
when N_And_Then
| N_In
| N_Not_In
| N_Op_And
| N_Op_Eq
| N_Op_Ge
| N_Op_Gt
| N_Op_Le
| N_Op_Lt
| N_Op_Ne
| N_Op_Or
| N_Op_Xor
| N_Or_Else
=>
return Left_Opnd (Parent (N)) = N;
when others =>
return False;
end case;
end if;
end Parent_Is_Boolean;
-- Start of processing for Resolve_Op_Not
begin
-- Predefined operations on scalar types yield the base type. On the
-- other hand, logical operations on arrays yield the type of the
-- arguments (and the context).
if Is_Array_Type (Typ) then
B_Typ := Typ;
else
B_Typ := Base_Type (Typ);
end if;
-- Straightforward case of incorrect arguments
if not Valid_Boolean_Arg (Typ) then
Error_Msg_N ("invalid operand type for operator&", N);
Set_Etype (N, Any_Type);
return;
-- Special case of probable missing parens
elsif Typ = Universal_Integer or else Typ = Any_Modular then
if Parent_Is_Boolean then
Error_Msg_N
("operand of not must be enclosed in parentheses",
Right_Opnd (N));
else
Error_Msg_N
("no modular type available in this context", N);
end if;
Set_Etype (N, Any_Type);
return;
-- OK resolution of NOT
else
-- Warn if non-boolean types involved. This is a case like not a < b
-- where a and b are modular, where we will get (not a) < b and most
-- likely not (a < b) was intended.
if Warn_On_Questionable_Missing_Parens
and then not Is_Boolean_Type (Typ)
and then Parent_Is_Boolean
then
Error_Msg_N ("?q?not expression should be parenthesized here!", N);
end if;
-- Warn on double negation if checking redundant constructs
if Warn_On_Redundant_Constructs
and then Comes_From_Source (N)
and then Comes_From_Source (Right_Opnd (N))
and then Root_Type (Typ) = Standard_Boolean
and then Nkind (Right_Opnd (N)) = N_Op_Not
then
Error_Msg_N ("redundant double negation?r?", N);
end if;
-- Complete resolution and evaluation of NOT
-- If argument is an equality and expected type is boolean, that
-- expected type has no effect on resolution, and there are
-- special rules for resolution of Eq, Neq in the presence of
-- overloaded operands, so we directly call its resolution routines.
declare
Opnd : constant Node_Id := Right_Opnd (N);
Op_Id : Entity_Id;
begin
if B_Typ = Standard_Boolean
and then Nkind (Opnd) in N_Op_Eq | N_Op_Ne
and then Is_Overloaded (Opnd)
then
Resolve_Equality_Op (Opnd, B_Typ);
Op_Id := Entity (Opnd);
if Ekind (Op_Id) = E_Function
and then not Is_Intrinsic_Subprogram (Op_Id)
then
Rewrite_Operator_As_Call (Opnd, Op_Id);
end if;
if not Inside_A_Generic or else Is_Entity_Name (Opnd) then
Freeze_Expression (Opnd);
end if;
Expand (Opnd);
else
Resolve (Opnd, B_Typ);
end if;
Check_Unset_Reference (Opnd);
end;
Set_Etype (N, B_Typ);
Generate_Operator_Reference (N, B_Typ);
Eval_Op_Not (N);
end if;
end Resolve_Op_Not;
-----------------------------
-- Resolve_Operator_Symbol --
-----------------------------
-- Nothing to be done, all resolved already
procedure Resolve_Operator_Symbol (N : Node_Id; Typ : Entity_Id) is
pragma Warnings (Off, N);
pragma Warnings (Off, Typ);
begin
null;
end Resolve_Operator_Symbol;
----------------------------------
-- Resolve_Qualified_Expression --
----------------------------------
procedure Resolve_Qualified_Expression (N : Node_Id; Typ : Entity_Id) is
pragma Warnings (Off, Typ);
Target_Typ : constant Entity_Id := Entity (Subtype_Mark (N));
Expr : constant Node_Id := Expression (N);
begin
Resolve (Expr, Target_Typ);
-- A qualified expression requires an exact match of the type, class-
-- wide matching is not allowed. However, if the qualifying type is
-- specific and the expression has a class-wide type, it may still be
-- okay, since it can be the result of the expansion of a call to a
-- dispatching function, so we also have to check class-wideness of the
-- type of the expression's original node.
if (Is_Class_Wide_Type (Target_Typ)
or else
(Is_Class_Wide_Type (Etype (Expr))
and then Is_Class_Wide_Type (Etype (Original_Node (Expr)))))
and then Base_Type (Etype (Expr)) /= Base_Type (Target_Typ)
then
Wrong_Type (Expr, Target_Typ);
end if;
-- If the target type is unconstrained, then we reset the type of the
-- result from the type of the expression. For other cases, the actual
-- subtype of the expression is the target type. But we avoid doing it
-- for an allocator since this is not needed and might be problematic.
if Is_Composite_Type (Target_Typ)
and then not Is_Constrained (Target_Typ)
and then Nkind (Parent (N)) /= N_Allocator
then
Set_Etype (N, Etype (Expr));
end if;
Analyze_Dimension (N);
Eval_Qualified_Expression (N);
-- If we still have a qualified expression after the static evaluation,
-- then apply a scalar range check if needed. The reason that we do this
-- after the Eval call is that otherwise, the application of the range
-- check may convert an illegal static expression and result in warning
-- rather than giving an error (e.g Integer'(Integer'Last + 1)).
if Nkind (N) = N_Qualified_Expression
and then Is_Scalar_Type (Target_Typ)
then
Apply_Scalar_Range_Check (Expr, Target_Typ);
end if;
-- AI12-0100: Once the qualified expression is resolved, check whether
-- operand statisfies a static predicate of the target subtype, if any.
-- In the static expression case, a predicate check failure is an error.
if Has_Predicates (Target_Typ) then
Check_Expression_Against_Static_Predicate
(Expr, Target_Typ, Static_Failure_Is_Error => True);
end if;
end Resolve_Qualified_Expression;
------------------------------
-- Resolve_Raise_Expression --
------------------------------
procedure Resolve_Raise_Expression (N : Node_Id; Typ : Entity_Id) is
begin
if Typ = Raise_Type then
Error_Msg_N ("cannot find unique type for raise expression", N);
Set_Etype (N, Any_Type);
else
Set_Etype (N, Typ);
end if;
end Resolve_Raise_Expression;
-------------------
-- Resolve_Range --
-------------------
procedure Resolve_Range (N : Node_Id; Typ : Entity_Id) is
L : constant Node_Id := Low_Bound (N);
H : constant Node_Id := High_Bound (N);
function First_Last_Ref return Boolean;
-- Returns True if N is of the form X'First .. X'Last where X is the
-- same entity for both attributes.
--------------------
-- First_Last_Ref --
--------------------
function First_Last_Ref return Boolean is
Lorig : constant Node_Id := Original_Node (L);
Horig : constant Node_Id := Original_Node (H);
begin
if Nkind (Lorig) = N_Attribute_Reference
and then Nkind (Horig) = N_Attribute_Reference
and then Attribute_Name (Lorig) = Name_First
and then Attribute_Name (Horig) = Name_Last
then
declare
PL : constant Node_Id := Prefix (Lorig);
PH : constant Node_Id := Prefix (Horig);
begin
if Is_Entity_Name (PL)
and then Is_Entity_Name (PH)
and then Entity (PL) = Entity (PH)
then
return True;
end if;
end;
end if;
return False;
end First_Last_Ref;
-- Start of processing for Resolve_Range
begin
Set_Etype (N, Typ);
Resolve (L, Typ);
Resolve (H, Typ);
-- Reanalyze the lower bound after both bounds have been analyzed, so
-- that the range is known to be static or not by now. This may trigger
-- more compile-time evaluation, which is useful for static analysis
-- with GNATprove. This is not needed for compilation or static analysis
-- with CodePeer, as full expansion does that evaluation then.
if GNATprove_Mode then
Set_Analyzed (L, False);
Resolve (L, Typ);
end if;
-- Check for inappropriate range on unordered enumeration type
if Bad_Unordered_Enumeration_Reference (N, Typ)
-- Exclude X'First .. X'Last if X is the same entity for both
and then not First_Last_Ref
then
Error_Msg_Sloc := Sloc (Typ);
Error_Msg_NE
("subrange of unordered enumeration type& declared#?U?", N, Typ);
end if;
Check_Unset_Reference (L);
Check_Unset_Reference (H);
-- We have to check the bounds for being within the base range as
-- required for a non-static context. Normally this is automatic and
-- done as part of evaluating expressions, but the N_Range node is an
-- exception, since in GNAT we consider this node to be a subexpression,
-- even though in Ada it is not. The circuit in Sem_Eval could check for
-- this, but that would put the test on the main evaluation path for
-- expressions.
Check_Non_Static_Context (L);
Check_Non_Static_Context (H);
-- Check for an ambiguous range over character literals. This will
-- happen with a membership test involving only literals.
if Typ = Any_Character then
Ambiguous_Character (L);
Set_Etype (N, Any_Type);
return;
end if;
-- If bounds are static, constant-fold them, so size computations are
-- identical between front-end and back-end. Do not perform this
-- transformation while analyzing generic units, as type information
-- would be lost when reanalyzing the constant node in the instance.
if Is_Discrete_Type (Typ) and then Expander_Active then
if Is_OK_Static_Expression (L) then
Fold_Uint (L, Expr_Value (L), Is_OK_Static_Expression (L));
end if;
if Is_OK_Static_Expression (H) then
Fold_Uint (H, Expr_Value (H), Is_OK_Static_Expression (H));
end if;
end if;
end Resolve_Range;
--------------------------
-- Resolve_Real_Literal --
--------------------------
procedure Resolve_Real_Literal (N : Node_Id; Typ : Entity_Id) is
Actual_Typ : constant Entity_Id := Etype (N);
begin
-- Special processing for fixed-point literals to make sure that the
-- value is an exact multiple of small where this is required. We skip
-- this for the universal real case, and also for generic types.
if Is_Fixed_Point_Type (Typ)
and then Typ /= Universal_Fixed
and then Typ /= Any_Fixed
and then not Is_Generic_Type (Typ)
then
declare
Val : constant Ureal := Realval (N);
Cintr : constant Ureal := Val / Small_Value (Typ);
Cint : constant Uint := UR_Trunc (Cintr);
Den : constant Uint := Norm_Den (Cintr);
Stat : Boolean;
begin
-- Case of literal is not an exact multiple of the Small
if Den /= 1 then
-- For a source program literal for a decimal fixed-point type,
-- this is statically illegal (RM 4.9(36)).
if Is_Decimal_Fixed_Point_Type (Typ)
and then Actual_Typ = Universal_Real
and then Comes_From_Source (N)
then
Error_Msg_N ("value has extraneous low order digits", N);
end if;
-- Generate a warning if literal from source
if Is_OK_Static_Expression (N)
and then Warn_On_Bad_Fixed_Value
then
Error_Msg_N
("?b?static fixed-point value is not a multiple of Small!",
N);
end if;
-- Replace literal by a value that is the exact representation
-- of a value of the type, i.e. a multiple of the small value,
-- by truncation, since Machine_Rounds is false for all GNAT
-- fixed-point types (RM 4.9(38)).
Stat := Is_OK_Static_Expression (N);
Rewrite (N,
Make_Real_Literal (Sloc (N),
Realval => Small_Value (Typ) * Cint));
Set_Is_Static_Expression (N, Stat);
end if;
-- In all cases, set the corresponding integer field
Set_Corresponding_Integer_Value (N, Cint);
end;
end if;
-- Now replace the actual type by the expected type as usual
Set_Etype (N, Typ);
Eval_Real_Literal (N);
end Resolve_Real_Literal;
-----------------------
-- Resolve_Reference --
-----------------------
procedure Resolve_Reference (N : Node_Id; Typ : Entity_Id) is
P : constant Node_Id := Prefix (N);
begin
-- Replace general access with specific type
if Ekind (Etype (N)) = E_Allocator_Type then
Set_Etype (N, Base_Type (Typ));
end if;
Resolve (P, Designated_Type (Etype (N)));
-- If we are taking the reference of a volatile entity, then treat it as
-- a potential modification of this entity. This is too conservative,
-- but necessary because remove side effects can cause transformations
-- of normal assignments into reference sequences that otherwise fail to
-- notice the modification.
if Is_Entity_Name (P) and then Treat_As_Volatile (Entity (P)) then
Note_Possible_Modification (P, Sure => False);
end if;
end Resolve_Reference;
--------------------------------
-- Resolve_Selected_Component --
--------------------------------
procedure Resolve_Selected_Component (N : Node_Id; Typ : Entity_Id) is
Comp : Entity_Id;
Comp1 : Entity_Id := Empty; -- prevent junk warning
P : constant Node_Id := Prefix (N);
S : constant Node_Id := Selector_Name (N);
T : Entity_Id := Etype (P);
I : Interp_Index;
I1 : Interp_Index := 0; -- prevent junk warning
It : Interp;
It1 : Interp;
Found : Boolean;
function Init_Component return Boolean;
-- Check whether this is the initialization of a component within an
-- init proc (by assignment or call to another init proc). If true,
-- there is no need for a discriminant check.
--------------------
-- Init_Component --
--------------------
function Init_Component return Boolean is
begin
return Inside_Init_Proc
and then Nkind (Prefix (N)) = N_Identifier
and then Chars (Prefix (N)) = Name_uInit
and then Nkind (Parent (Parent (N))) = N_Case_Statement_Alternative;
end Init_Component;
-- Start of processing for Resolve_Selected_Component
begin
if Is_Overloaded (P) then
-- Use the context type to select the prefix that has a selector
-- of the correct name and type.
Found := False;
Get_First_Interp (P, I, It);
Search : while Present (It.Typ) loop
if Is_Access_Type (It.Typ) then
T := Designated_Type (It.Typ);
else
T := It.Typ;
end if;
-- Locate selected component. For a private prefix the selector
-- can denote a discriminant.
if Is_Record_Type (T) or else Is_Private_Type (T) then
-- The visible components of a class-wide type are those of
-- the root type.
if Is_Class_Wide_Type (T) then
T := Etype (T);
end if;
Comp := First_Entity (T);
while Present (Comp) loop
if Chars (Comp) = Chars (S)
and then Covers (Typ, Etype (Comp))
then
if not Found then
Found := True;
I1 := I;
It1 := It;
Comp1 := Comp;
else
It := Disambiguate (P, I1, I, Any_Type);
if It = No_Interp then
Error_Msg_N
("ambiguous prefix for selected component", N);
Set_Etype (N, Typ);
return;
else
It1 := It;
-- There may be an implicit dereference. Retrieve
-- designated record type.
if Is_Access_Type (It1.Typ) then
T := Designated_Type (It1.Typ);
else
T := It1.Typ;
end if;
if Scope (Comp1) /= T then
-- Resolution chooses the new interpretation.
-- Find the component with the right name.
Comp1 := First_Entity (T);
while Present (Comp1)
and then Chars (Comp1) /= Chars (S)
loop
Next_Entity (Comp1);
end loop;
end if;
exit Search;
end if;
end if;
end if;
Next_Entity (Comp);
end loop;
end if;
Get_Next_Interp (I, It);
end loop Search;
-- There must be a legal interpretation at this point
pragma Assert (Found);
Resolve (P, It1.Typ);
-- In general the expected type is the type of the context, not the
-- type of the candidate selected component.
Set_Etype (N, Typ);
Set_Entity_With_Checks (S, Comp1);
-- The type of the context and that of the component are
-- compatible and in general identical, but if they are anonymous
-- access-to-subprogram types, the relevant type is that of the
-- component. This matters in Unnest_Subprograms mode, where the
-- relevant context is the one in which the type is declared, not
-- the point of use. This determines what activation record to use.
if Ekind (Typ) = E_Anonymous_Access_Subprogram_Type then
Set_Etype (N, Etype (Comp1));
-- When the type of the component is an access to a class-wide type
-- the relevant type is that of the component (since in such case we
-- may need to generate implicit type conversions or dispatching
-- calls).
elsif Is_Access_Type (Typ)
and then not Is_Class_Wide_Type (Designated_Type (Typ))
and then Is_Class_Wide_Type (Designated_Type (Etype (Comp1)))
then
Set_Etype (N, Etype (Comp1));
end if;
else
-- Resolve prefix with its type
Resolve (P, T);
end if;
-- Generate cross-reference. We needed to wait until full overloading
-- resolution was complete to do this, since otherwise we can't tell if
-- we are an lvalue or not.
if May_Be_Lvalue (N) then
Generate_Reference (Entity (S), S, 'm');
else
Generate_Reference (Entity (S), S, 'r');
end if;
-- If the prefix's type is an access type, get to the real record type.
-- Note: we do not apply an access check because an explicit dereference
-- will be introduced later, and the check will happen there.
if Is_Access_Type (Etype (P)) then
T := Implicitly_Designated_Type (Etype (P));
Check_Fully_Declared_Prefix (T, P);
else
T := Etype (P);
-- If the prefix is an entity it may have a deferred reference set
-- during analysis of the selected component. After resolution we
-- can transform it into a proper reference. This prevents spurious
-- warnings on useless assignments when the same selected component
-- is the actual for an out parameter in a subsequent call.
if Is_Entity_Name (P)
and then Has_Deferred_Reference (Entity (P))
then
if May_Be_Lvalue (N) then
Generate_Reference (Entity (P), P, 'm');
else
Generate_Reference (Entity (P), P, 'r');
end if;
end if;
end if;
-- Set flag for expander if discriminant check required on a component
-- appearing within a variant.
if Has_Discriminants (T)
and then Ekind (Entity (S)) = E_Component
and then Present (Original_Record_Component (Entity (S)))
and then Ekind (Original_Record_Component (Entity (S))) = E_Component
and then
Is_Declared_Within_Variant (Original_Record_Component (Entity (S)))
and then not Discriminant_Checks_Suppressed (T)
and then not Init_Component
then
Set_Do_Discriminant_Check (N);
end if;
if Ekind (Entity (S)) = E_Void then
Error_Msg_N ("premature use of component", S);
end if;
-- If the prefix is a record conversion, this may be a renamed
-- discriminant whose bounds differ from those of the original
-- one, so we must ensure that a range check is performed.
if Nkind (P) = N_Type_Conversion
and then Ekind (Entity (S)) = E_Discriminant
and then Is_Discrete_Type (Typ)
then
Set_Etype (N, Base_Type (Typ));
end if;
-- Note: No Eval processing is required, because the prefix is of a
-- record type, or protected type, and neither can possibly be static.
-- If the record type is atomic and the component is not, then this is
-- worth a warning before Ada 2020, since we have a situation where the
-- access to the component may cause extra read/writes of the atomic
-- object, or partial word accesses, both of which may be unexpected.
if Nkind (N) = N_Selected_Component
and then Is_Atomic_Ref_With_Address (N)
and then not Is_Atomic (Entity (S))
and then not Is_Atomic (Etype (Entity (S)))
and then Ada_Version < Ada_2020
then
Error_Msg_N
("??access to non-atomic component of atomic record",
Prefix (N));
Error_Msg_N
("\??may cause unexpected accesses to atomic object",
Prefix (N));
end if;
Resolve_Implicit_Dereference (Prefix (N));
Analyze_Dimension (N);
end Resolve_Selected_Component;
-------------------
-- Resolve_Shift --
-------------------
procedure Resolve_Shift (N : Node_Id; Typ : Entity_Id) is
B_Typ : constant Entity_Id := Base_Type (Typ);
L : constant Node_Id := Left_Opnd (N);
R : constant Node_Id := Right_Opnd (N);
begin
-- We do the resolution using the base type, because intermediate values
-- in expressions always are of the base type, not a subtype of it.
Resolve (L, B_Typ);
Resolve (R, Standard_Natural);
Check_Unset_Reference (L);
Check_Unset_Reference (R);
Set_Etype (N, B_Typ);
Generate_Operator_Reference (N, B_Typ);
Eval_Shift (N);
end Resolve_Shift;
---------------------------
-- Resolve_Short_Circuit --
---------------------------
procedure Resolve_Short_Circuit (N : Node_Id; Typ : Entity_Id) is
B_Typ : constant Entity_Id := Base_Type (Typ);
L : constant Node_Id := Left_Opnd (N);
R : constant Node_Id := Right_Opnd (N);
begin
-- Ensure all actions associated with the left operand (e.g.
-- finalization of transient objects) are fully evaluated locally within
-- an expression with actions. This is particularly helpful for coverage
-- analysis. However this should not happen in generics or if option
-- Minimize_Expression_With_Actions is set.
if Expander_Active and not Minimize_Expression_With_Actions then
declare
Reloc_L : constant Node_Id := Relocate_Node (L);
begin
Save_Interps (Old_N => L, New_N => Reloc_L);
Rewrite (L,
Make_Expression_With_Actions (Sloc (L),
Actions => New_List,
Expression => Reloc_L));
-- Set Comes_From_Source on L to preserve warnings for unset
-- reference.
Preserve_Comes_From_Source (L, Reloc_L);
end;
end if;
Resolve (L, B_Typ);
Resolve (R, B_Typ);
-- Check for issuing warning for always False assert/check, this happens
-- when assertions are turned off, in which case the pragma Assert/Check
-- was transformed into:
-- if False and then <condition> then ...
-- and we detect this pattern
if Warn_On_Assertion_Failure
and then Is_Entity_Name (R)
and then Entity (R) = Standard_False
and then Nkind (Parent (N)) = N_If_Statement
and then Nkind (N) = N_And_Then
and then Is_Entity_Name (L)
and then Entity (L) = Standard_False
then
declare
Orig : constant Node_Id := Original_Node (Parent (N));
begin
-- Special handling of Asssert pragma
if Nkind (Orig) = N_Pragma
and then Pragma_Name (Orig) = Name_Assert
then
declare
Expr : constant Node_Id :=
Original_Node
(Expression
(First (Pragma_Argument_Associations (Orig))));
begin
-- Don't warn if original condition is explicit False,
-- since obviously the failure is expected in this case.
if Is_Entity_Name (Expr)
and then Entity (Expr) = Standard_False
then
null;
-- Issue warning. We do not want the deletion of the
-- IF/AND-THEN to take this message with it. We achieve this
-- by making sure that the expanded code points to the Sloc
-- of the expression, not the original pragma.
else
-- Note: Use Error_Msg_F here rather than Error_Msg_N.
-- The source location of the expression is not usually
-- the best choice here. For example, it gets located on
-- the last AND keyword in a chain of boolean expressiond
-- AND'ed together. It is best to put the message on the
-- first character of the assertion, which is the effect
-- of the First_Node call here.
Error_Msg_F
("?A?assertion would fail at run time!",
Expression
(First (Pragma_Argument_Associations (Orig))));
end if;
end;
-- Similar processing for Check pragma
elsif Nkind (Orig) = N_Pragma
and then Pragma_Name (Orig) = Name_Check
then
-- Don't want to warn if original condition is explicit False
declare
Expr : constant Node_Id :=
Original_Node
(Expression
(Next (First (Pragma_Argument_Associations (Orig)))));
begin
if Is_Entity_Name (Expr)
and then Entity (Expr) = Standard_False
then
null;
-- Post warning
else
-- Again use Error_Msg_F rather than Error_Msg_N, see
-- comment above for an explanation of why we do this.
Error_Msg_F
("?A?check would fail at run time!",
Expression
(Last (Pragma_Argument_Associations (Orig))));
end if;
end;
end if;
end;
end if;
-- Continue with processing of short circuit
Check_Unset_Reference (L);
Check_Unset_Reference (R);
Set_Etype (N, B_Typ);
Eval_Short_Circuit (N);
end Resolve_Short_Circuit;
-------------------
-- Resolve_Slice --
-------------------
procedure Resolve_Slice (N : Node_Id; Typ : Entity_Id) is
Drange : constant Node_Id := Discrete_Range (N);
Name : constant Node_Id := Prefix (N);
Array_Type : Entity_Id := Empty;
Dexpr : Node_Id := Empty;
Index_Type : Entity_Id;
begin
if Is_Overloaded (Name) then
-- Use the context type to select the prefix that yields the correct
-- array type.
declare
I : Interp_Index;
I1 : Interp_Index := 0;
It : Interp;
P : constant Node_Id := Prefix (N);
Found : Boolean := False;
begin
Get_First_Interp (P, I, It);
while Present (It.Typ) loop
if (Is_Array_Type (It.Typ)
and then Covers (Typ, It.Typ))
or else (Is_Access_Type (It.Typ)
and then Is_Array_Type (Designated_Type (It.Typ))
and then Covers (Typ, Designated_Type (It.Typ)))
then
if Found then
It := Disambiguate (P, I1, I, Any_Type);
if It = No_Interp then
Error_Msg_N ("ambiguous prefix for slicing", N);
Set_Etype (N, Typ);
return;
else
Found := True;
Array_Type := It.Typ;
I1 := I;
end if;
else
Found := True;
Array_Type := It.Typ;
I1 := I;
end if;
end if;
Get_Next_Interp (I, It);
end loop;
end;
else
Array_Type := Etype (Name);
end if;
Resolve (Name, Array_Type);
-- If the prefix's type is an access type, get to the real array type.
-- Note: we do not apply an access check because an explicit dereference
-- will be introduced later, and the check will happen there.
if Is_Access_Type (Array_Type) then
Array_Type := Implicitly_Designated_Type (Array_Type);
-- If the prefix is an access to an unconstrained array, we must use
-- the actual subtype of the object to perform the index checks. The
-- object denoted by the prefix is implicit in the node, so we build
-- an explicit representation for it in order to compute the actual
-- subtype.
if not Is_Constrained (Array_Type) then
Remove_Side_Effects (Prefix (N));
declare
Obj : constant Node_Id :=
Make_Explicit_Dereference (Sloc (N),
Prefix => New_Copy_Tree (Prefix (N)));
begin
Set_Etype (Obj, Array_Type);
Set_Parent (Obj, Parent (N));
Array_Type := Get_Actual_Subtype (Obj);
end;
end if;
elsif Is_Entity_Name (Name)
or else Nkind (Name) = N_Explicit_Dereference
or else (Nkind (Name) = N_Function_Call
and then not Is_Constrained (Etype (Name)))
then
Array_Type := Get_Actual_Subtype (Name);
-- If the name is a selected component that depends on discriminants,
-- build an actual subtype for it. This can happen only when the name
-- itself is overloaded; otherwise the actual subtype is created when
-- the selected component is analyzed.
elsif Nkind (Name) = N_Selected_Component
and then Full_Analysis
and then Depends_On_Discriminant (First_Index (Array_Type))
then
declare
Act_Decl : constant Node_Id :=
Build_Actual_Subtype_Of_Component (Array_Type, Name);
begin
Insert_Action (N, Act_Decl);
Array_Type := Defining_Identifier (Act_Decl);
end;
-- Maybe this should just be "else", instead of checking for the
-- specific case of slice??? This is needed for the case where the
-- prefix is an Image attribute, which gets expanded to a slice, and so
-- has a constrained subtype which we want to use for the slice range
-- check applied below (the range check won't get done if the
-- unconstrained subtype of the 'Image is used).
elsif Nkind (Name) = N_Slice then
Array_Type := Etype (Name);
end if;
-- Obtain the type of the array index
if Ekind (Array_Type) = E_String_Literal_Subtype then
Index_Type := Etype (String_Literal_Low_Bound (Array_Type));
else
Index_Type := Etype (First_Index (Array_Type));
end if;
-- If name was overloaded, set slice type correctly now
Set_Etype (N, Array_Type);
-- Handle the generation of a range check that compares the array index
-- against the discrete_range. The check is not applied to internally
-- built nodes associated with the expansion of dispatch tables. Check
-- that Ada.Tags has already been loaded to avoid extra dependencies on
-- the unit.
if Tagged_Type_Expansion
and then RTU_Loaded (Ada_Tags)
and then Nkind (Prefix (N)) = N_Selected_Component
and then Present (Entity (Selector_Name (Prefix (N))))
and then Entity (Selector_Name (Prefix (N))) =
RTE_Record_Component (RE_Prims_Ptr)
then
null;
-- The discrete_range is specified by a subtype indication. Create a
-- shallow copy and inherit the type, parent and source location from
-- the discrete_range. This ensures that the range check is inserted
-- relative to the slice and that the runtime exception points to the
-- proper construct.
elsif Is_Entity_Name (Drange) then
Dexpr := New_Copy (Scalar_Range (Entity (Drange)));
Set_Etype (Dexpr, Etype (Drange));
Set_Parent (Dexpr, Parent (Drange));
Set_Sloc (Dexpr, Sloc (Drange));
-- The discrete_range is a regular range. Resolve the bounds and remove
-- their side effects.
else
Resolve (Drange, Base_Type (Index_Type));
if Nkind (Drange) = N_Range then
Force_Evaluation (Low_Bound (Drange));
Force_Evaluation (High_Bound (Drange));
Dexpr := Drange;
end if;
end if;
if Present (Dexpr) then
Apply_Range_Check (Dexpr, Index_Type);
end if;
Set_Slice_Subtype (N);
-- Check bad use of type with predicates
declare
Subt : Entity_Id;
begin
if Nkind (Drange) = N_Subtype_Indication
and then Has_Predicates (Entity (Subtype_Mark (Drange)))
then
Subt := Entity (Subtype_Mark (Drange));
else
Subt := Etype (Drange);
end if;
if Has_Predicates (Subt) then
Bad_Predicated_Subtype_Use
("subtype& has predicate, not allowed in slice", Drange, Subt);
end if;
end;
-- Otherwise here is where we check suspicious indexes
if Nkind (Drange) = N_Range then
Warn_On_Suspicious_Index (Name, Low_Bound (Drange));
Warn_On_Suspicious_Index (Name, High_Bound (Drange));
end if;
Resolve_Implicit_Dereference (Prefix (N));
Analyze_Dimension (N);
Eval_Slice (N);
end Resolve_Slice;
----------------------------
-- Resolve_String_Literal --
----------------------------
procedure Resolve_String_Literal (N : Node_Id; Typ : Entity_Id) is
C_Typ : constant Entity_Id := Component_Type (Typ);
R_Typ : constant Entity_Id := Root_Type (C_Typ);
Loc : constant Source_Ptr := Sloc (N);
Str : constant String_Id := Strval (N);
Strlen : constant Nat := String_Length (Str);
Subtype_Id : Entity_Id;
Need_Check : Boolean;
begin
-- For a string appearing in a concatenation, defer creation of the
-- string_literal_subtype until the end of the resolution of the
-- concatenation, because the literal may be constant-folded away. This
-- is a useful optimization for long concatenation expressions.
-- If the string is an aggregate built for a single character (which
-- happens in a non-static context) or a is null string to which special
-- checks may apply, we build the subtype. Wide strings must also get a
-- string subtype if they come from a one character aggregate. Strings
-- generated by attributes might be static, but it is often hard to
-- determine whether the enclosing context is static, so we generate
-- subtypes for them as well, thus losing some rarer optimizations ???
-- Same for strings that come from a static conversion.
Need_Check :=
(Strlen = 0 and then Typ /= Standard_String)
or else Nkind (Parent (N)) /= N_Op_Concat
or else (N /= Left_Opnd (Parent (N))
and then N /= Right_Opnd (Parent (N)))
or else ((Typ = Standard_Wide_String
or else Typ = Standard_Wide_Wide_String)
and then Nkind (Original_Node (N)) /= N_String_Literal);
-- If the resolving type is itself a string literal subtype, we can just
-- reuse it, since there is no point in creating another.
if Ekind (Typ) = E_String_Literal_Subtype then
Subtype_Id := Typ;
elsif Nkind (Parent (N)) = N_Op_Concat
and then not Need_Check
and then Nkind (Original_Node (N)) not in N_Character_Literal
| N_Attribute_Reference
| N_Qualified_Expression
| N_Type_Conversion
then
Subtype_Id := Typ;
-- Do not generate a string literal subtype for the default expression
-- of a formal parameter in GNATprove mode. This is because the string
-- subtype is associated with the freezing actions of the subprogram,
-- however freezing is disabled in GNATprove mode and as a result the
-- subtype is unavailable.
elsif GNATprove_Mode
and then Nkind (Parent (N)) = N_Parameter_Specification
then
Subtype_Id := Typ;
-- Otherwise we must create a string literal subtype. Note that the
-- whole idea of string literal subtypes is simply to avoid the need
-- for building a full fledged array subtype for each literal.
else
Set_String_Literal_Subtype (N, Typ);
Subtype_Id := Etype (N);
end if;
if Nkind (Parent (N)) /= N_Op_Concat
or else Need_Check
then
Set_Etype (N, Subtype_Id);
Eval_String_Literal (N);
end if;
if Is_Limited_Composite (Typ)
or else Is_Private_Composite (Typ)
then
Error_Msg_N ("string literal not available for private array", N);
Set_Etype (N, Any_Type);
return;
end if;
-- The validity of a null string has been checked in the call to
-- Eval_String_Literal.
if Strlen = 0 then
return;
-- Always accept string literal with component type Any_Character, which
-- occurs in error situations and in comparisons of literals, both of
-- which should accept all literals.
elsif R_Typ = Any_Character then
return;
-- If the type is bit-packed, then we always transform the string
-- literal into a full fledged aggregate.
elsif Is_Bit_Packed_Array (Typ) then
null;
-- Deal with cases of Wide_Wide_String, Wide_String, and String
else
-- For Standard.Wide_Wide_String, or any other type whose component
-- type is Standard.Wide_Wide_Character, we know that all the
-- characters in the string must be acceptable, since the parser
-- accepted the characters as valid character literals.
if R_Typ = Standard_Wide_Wide_Character then
null;
-- For the case of Standard.String, or any other type whose component
-- type is Standard.Character, we must make sure that there are no
-- wide characters in the string, i.e. that it is entirely composed
-- of characters in range of type Character.
-- If the string literal is the result of a static concatenation, the
-- test has already been performed on the components, and need not be
-- repeated.
elsif R_Typ = Standard_Character
and then Nkind (Original_Node (N)) /= N_Op_Concat
then
for J in 1 .. Strlen loop
if not In_Character_Range (Get_String_Char (Str, J)) then
-- If we are out of range, post error. This is one of the
-- very few places that we place the flag in the middle of
-- a token, right under the offending wide character. Not
-- quite clear if this is right wrt wide character encoding
-- sequences, but it's only an error message.
Error_Msg
("literal out of range of type Standard.Character",
Source_Ptr (Int (Loc) + J));
return;
end if;
end loop;
-- For the case of Standard.Wide_String, or any other type whose
-- component type is Standard.Wide_Character, we must make sure that
-- there are no wide characters in the string, i.e. that it is
-- entirely composed of characters in range of type Wide_Character.
-- If the string literal is the result of a static concatenation,
-- the test has already been performed on the components, and need
-- not be repeated.
elsif R_Typ = Standard_Wide_Character
and then Nkind (Original_Node (N)) /= N_Op_Concat
then
for J in 1 .. Strlen loop
if not In_Wide_Character_Range (Get_String_Char (Str, J)) then
-- If we are out of range, post error. This is one of the
-- very few places that we place the flag in the middle of
-- a token, right under the offending wide character.
-- This is not quite right, because characters in general
-- will take more than one character position ???
Error_Msg
("literal out of range of type Standard.Wide_Character",
Source_Ptr (Int (Loc) + J));
return;
end if;
end loop;
-- If the root type is not a standard character, then we will convert
-- the string into an aggregate and will let the aggregate code do
-- the checking. Standard Wide_Wide_Character is also OK here.
else
null;
end if;
-- See if the component type of the array corresponding to the string
-- has compile time known bounds. If yes we can directly check
-- whether the evaluation of the string will raise constraint error.
-- Otherwise we need to transform the string literal into the
-- corresponding character aggregate and let the aggregate code do
-- the checking. We use the same transformation if the component
-- type has a static predicate, which will be applied to each
-- character when the aggregate is resolved.
if Is_Standard_Character_Type (R_Typ) then
-- Check for the case of full range, where we are definitely OK
if Component_Type (Typ) = Base_Type (Component_Type (Typ)) then
return;
end if;
-- Here the range is not the complete base type range, so check
declare
Comp_Typ_Lo : constant Node_Id :=
Type_Low_Bound (Component_Type (Typ));
Comp_Typ_Hi : constant Node_Id :=
Type_High_Bound (Component_Type (Typ));
Char_Val : Uint;
begin
if Compile_Time_Known_Value (Comp_Typ_Lo)
and then Compile_Time_Known_Value (Comp_Typ_Hi)
then
for J in 1 .. Strlen loop
Char_Val := UI_From_Int (Int (Get_String_Char (Str, J)));
if Char_Val < Expr_Value (Comp_Typ_Lo)
or else Char_Val > Expr_Value (Comp_Typ_Hi)
then
Apply_Compile_Time_Constraint_Error
(N, "character out of range??",
CE_Range_Check_Failed,
Loc => Source_Ptr (Int (Loc) + J));
end if;
end loop;
if not Has_Static_Predicate (C_Typ) then
return;
end if;
end if;
end;
end if;
end if;
-- If we got here we meed to transform the string literal into the
-- equivalent qualified positional array aggregate. This is rather
-- heavy artillery for this situation, but it is hard work to avoid.
declare
Lits : constant List_Id := New_List;
P : Source_Ptr := Loc + 1;
C : Char_Code;
begin
-- Build the character literals, we give them source locations that
-- correspond to the string positions, which is a bit tricky given
-- the possible presence of wide character escape sequences.
for J in 1 .. Strlen loop
C := Get_String_Char (Str, J);
Set_Character_Literal_Name (C);
Append_To (Lits,
Make_Character_Literal (P,
Chars => Name_Find,
Char_Literal_Value => UI_From_CC (C)));
if In_Character_Range (C) then
P := P + 1;
-- Should we have a call to Skip_Wide here ???
-- ??? else
-- Skip_Wide (P);
end if;
end loop;
Rewrite (N,
Make_Qualified_Expression (Loc,
Subtype_Mark => New_Occurrence_Of (Typ, Loc),
Expression =>
Make_Aggregate (Loc, Expressions => Lits)));
Analyze_And_Resolve (N, Typ);
end;
end Resolve_String_Literal;
-------------------------
-- Resolve_Target_Name --
-------------------------
procedure Resolve_Target_Name (N : Node_Id; Typ : Entity_Id) is
begin
Set_Etype (N, Typ);
end Resolve_Target_Name;
-----------------------------
-- Resolve_Type_Conversion --
-----------------------------
procedure Resolve_Type_Conversion (N : Node_Id; Typ : Entity_Id) is
Conv_OK : constant Boolean := Conversion_OK (N);
Operand : constant Node_Id := Expression (N);
Operand_Typ : constant Entity_Id := Etype (Operand);
Target_Typ : constant Entity_Id := Etype (N);
Rop : Node_Id;
Orig_N : Node_Id;
Orig_T : Node_Id;
Test_Redundant : Boolean := Warn_On_Redundant_Constructs;
-- Set to False to suppress cases where we want to suppress the test
-- for redundancy to avoid possible false positives on this warning.
begin
if not Conv_OK
and then not Valid_Conversion (N, Target_Typ, Operand)
then
return;
end if;
-- If the Operand Etype is Universal_Fixed, then the conversion is
-- never redundant. We need this check because by the time we have
-- finished the rather complex transformation, the conversion looks
-- redundant when it is not.
if Operand_Typ = Universal_Fixed then
Test_Redundant := False;
-- If the operand is marked as Any_Fixed, then special processing is
-- required. This is also a case where we suppress the test for a
-- redundant conversion, since most certainly it is not redundant.
elsif Operand_Typ = Any_Fixed then
Test_Redundant := False;
-- Mixed-mode operation involving a literal. Context must be a fixed
-- type which is applied to the literal subsequently.
-- Multiplication and division involving two fixed type operands must
-- yield a universal real because the result is computed in arbitrary
-- precision.
if Is_Fixed_Point_Type (Typ)
and then Nkind (Operand) in N_Op_Divide | N_Op_Multiply
and then Etype (Left_Opnd (Operand)) = Any_Fixed
and then Etype (Right_Opnd (Operand)) = Any_Fixed
then
Set_Etype (Operand, Universal_Real);
elsif Is_Numeric_Type (Typ)
and then Nkind (Operand) in N_Op_Multiply | N_Op_Divide
and then (Etype (Right_Opnd (Operand)) = Universal_Real
or else
Etype (Left_Opnd (Operand)) = Universal_Real)
then
-- Return if expression is ambiguous
if Unique_Fixed_Point_Type (N) = Any_Type then
return;
-- If nothing else, the available fixed type is Duration
else
Set_Etype (Operand, Standard_Duration);
end if;
-- Resolve the real operand with largest available precision
if Etype (Right_Opnd (Operand)) = Universal_Real then
Rop := New_Copy_Tree (Right_Opnd (Operand));
else
Rop := New_Copy_Tree (Left_Opnd (Operand));
end if;
Resolve (Rop, Universal_Real);
-- If the operand is a literal (it could be a non-static and
-- illegal exponentiation) check whether the use of Duration
-- is potentially inaccurate.
if Nkind (Rop) = N_Real_Literal
and then Realval (Rop) /= Ureal_0
and then abs (Realval (Rop)) < Delta_Value (Standard_Duration)
then
Error_Msg_N
("??universal real operand can only "
& "be interpreted as Duration!", Rop);
Error_Msg_N
("\??precision will be lost in the conversion!", Rop);
end if;
elsif Is_Numeric_Type (Typ)
and then Nkind (Operand) in N_Op
and then Unique_Fixed_Point_Type (N) /= Any_Type
then
Set_Etype (Operand, Standard_Duration);
else
Error_Msg_N ("invalid context for mixed mode operation", N);
Set_Etype (Operand, Any_Type);
return;
end if;
end if;
Resolve (Operand);
Analyze_Dimension (N);
-- Note: we do the Eval_Type_Conversion call before applying the
-- required checks for a subtype conversion. This is important, since
-- both are prepared under certain circumstances to change the type
-- conversion to a constraint error node, but in the case of
-- Eval_Type_Conversion this may reflect an illegality in the static
-- case, and we would miss the illegality (getting only a warning
-- message), if we applied the type conversion checks first.
Eval_Type_Conversion (N);
-- Even when evaluation is not possible, we may be able to simplify the
-- conversion or its expression. This needs to be done before applying
-- checks, since otherwise the checks may use the original expression
-- and defeat the simplifications. This is specifically the case for
-- elimination of the floating-point Truncation attribute in
-- float-to-int conversions.
Simplify_Type_Conversion (N);
-- If after evaluation we still have a type conversion, then we may need
-- to apply checks required for a subtype conversion.
-- Skip these type conversion checks if universal fixed operands
-- are involved, since range checks are handled separately for
-- these cases (in the appropriate Expand routines in unit Exp_Fixd).
if Nkind (N) = N_Type_Conversion
and then not Is_Generic_Type (Root_Type (Target_Typ))
and then Target_Typ /= Universal_Fixed
and then Operand_Typ /= Universal_Fixed
then
Apply_Type_Conversion_Checks (N);
end if;
-- Issue warning for conversion of simple object to its own type. We
-- have to test the original nodes, since they may have been rewritten
-- by various optimizations.
Orig_N := Original_Node (N);
-- Here we test for a redundant conversion if the warning mode is
-- active (and was not locally reset), and we have a type conversion
-- from source not appearing in a generic instance.
if Test_Redundant
and then Nkind (Orig_N) = N_Type_Conversion
and then Comes_From_Source (Orig_N)
and then not In_Instance
then
Orig_N := Original_Node (Expression (Orig_N));
Orig_T := Target_Typ;
-- If the node is part of a larger expression, the Target_Type
-- may not be the original type of the node if the context is a
-- condition. Recover original type to see if conversion is needed.
if Is_Boolean_Type (Orig_T)
and then Nkind (Parent (N)) in N_Op
then
Orig_T := Etype (Parent (N));
end if;
-- If we have an entity name, then give the warning if the entity
-- is the right type, or if it is a loop parameter covered by the
-- original type (that's needed because loop parameters have an
-- odd subtype coming from the bounds).
if (Is_Entity_Name (Orig_N)
and then Present (Entity (Orig_N))
and then
(Etype (Entity (Orig_N)) = Orig_T
or else
(Ekind (Entity (Orig_N)) = E_Loop_Parameter
and then Covers (Orig_T, Etype (Entity (Orig_N))))))
-- If not an entity, then type of expression must match
or else Etype (Orig_N) = Orig_T
then
-- One more check, do not give warning if the analyzed conversion
-- has an expression with non-static bounds, and the bounds of the
-- target are static. This avoids junk warnings in cases where the
-- conversion is necessary to establish staticness, for example in
-- a case statement.
if not Is_OK_Static_Subtype (Operand_Typ)
and then Is_OK_Static_Subtype (Target_Typ)
then
null;
-- Finally, if this type conversion occurs in a context requiring
-- a prefix, and the expression is a qualified expression then the
-- type conversion is not redundant, since a qualified expression
-- is not a prefix, whereas a type conversion is. For example, "X
-- := T'(Funx(...)).Y;" is illegal because a selected component
-- requires a prefix, but a type conversion makes it legal: "X :=
-- T(T'(Funx(...))).Y;"
-- In Ada 2012, a qualified expression is a name, so this idiom is
-- no longer needed, but we still suppress the warning because it
-- seems unfriendly for warnings to pop up when you switch to the
-- newer language version.
elsif Nkind (Orig_N) = N_Qualified_Expression
and then Nkind (Parent (N)) in N_Attribute_Reference
| N_Indexed_Component
| N_Selected_Component
| N_Slice
| N_Explicit_Dereference
then
null;
-- Never warn on conversion to Long_Long_Integer'Base since
-- that is most likely an artifact of the extended overflow
-- checking and comes from complex expanded code.
elsif Orig_T = Base_Type (Standard_Long_Long_Integer) then
null;
-- Here we give the redundant conversion warning. If it is an
-- entity, give the name of the entity in the message. If not,
-- just mention the expression.
else
if Is_Entity_Name (Orig_N) then
Error_Msg_Node_2 := Orig_T;
Error_Msg_NE -- CODEFIX
("?r?redundant conversion, & is of type &!",
N, Entity (Orig_N));
else
Error_Msg_NE
("?r?redundant conversion, expression is of type&!",
N, Orig_T);
end if;
end if;
end if;
end if;
-- Ada 2005 (AI-251): Handle class-wide interface type conversions.
-- No need to perform any interface conversion if the type of the
-- expression coincides with the target type.
if Ada_Version >= Ada_2005
and then Expander_Active
and then Operand_Typ /= Target_Typ
then
declare
Opnd : Entity_Id := Operand_Typ;
Target : Entity_Id := Target_Typ;
begin
-- If the type of the operand is a limited view, use nonlimited
-- view when available. If it is a class-wide type, recover the
-- class-wide type of the nonlimited view.
if From_Limited_With (Opnd)
and then Has_Non_Limited_View (Opnd)
then
Opnd := Non_Limited_View (Opnd);
Set_Etype (Expression (N), Opnd);
end if;
-- It seems that Non_Limited_View should also be applied for
-- Target when it has a limited view, but that leads to missing
-- error checks on interface conversions further below. ???
if Is_Access_Type (Opnd) then
Opnd := Designated_Type (Opnd);
-- If the type of the operand is a limited view, use nonlimited
-- view when available. If it is a class-wide type, recover the
-- class-wide type of the nonlimited view.
if From_Limited_With (Opnd)
and then Has_Non_Limited_View (Opnd)
then
Opnd := Non_Limited_View (Opnd);
end if;
end if;
if Is_Access_Type (Target_Typ) then
Target := Designated_Type (Target);
-- If the target type is a limited view, use nonlimited view
-- when available.
if From_Limited_With (Target)
and then Has_Non_Limited_View (Target)
then
Target := Non_Limited_View (Target);
end if;
end if;
if Opnd = Target then
null;
-- Conversion from interface type
-- It seems that it would be better for the error checks below
-- to be performed as part of Validate_Conversion (and maybe some
-- of the error checks above could be moved as well?). ???
elsif Is_Interface (Opnd) then
-- Ada 2005 (AI-217): Handle entities from limited views
if From_Limited_With (Opnd) then
Error_Msg_Qual_Level := 99;
Error_Msg_NE -- CODEFIX
("missing WITH clause on package &", N,
Cunit_Entity (Get_Source_Unit (Base_Type (Opnd))));
Error_Msg_N
("type conversions require visibility of the full view",
N);
elsif From_Limited_With (Target)
and then not
(Is_Access_Type (Target_Typ)
and then Present (Non_Limited_View (Etype (Target))))
then
Error_Msg_Qual_Level := 99;
Error_Msg_NE -- CODEFIX
("missing WITH clause on package &", N,
Cunit_Entity (Get_Source_Unit (Base_Type (Target))));
Error_Msg_N
("type conversions require visibility of the full view",
N);
else
Expand_Interface_Conversion (N);
end if;
-- Conversion to interface type
elsif Is_Interface (Target) then
-- Handle subtypes
if Ekind (Opnd) in E_Protected_Subtype | E_Task_Subtype then
Opnd := Etype (Opnd);
end if;
if Is_Class_Wide_Type (Opnd)
or else Interface_Present_In_Ancestor
(Typ => Opnd,
Iface => Target)
then
Expand_Interface_Conversion (N);
else
Error_Msg_Name_1 := Chars (Etype (Target));
Error_Msg_Name_2 := Chars (Opnd);
Error_Msg_N
("wrong interface conversion (% is not a progenitor "
& "of %)", N);
end if;
end if;
end;
end if;
-- Ada 2012: Once the type conversion is resolved, check whether the
-- operand statisfies a static predicate of the target subtype, if any.
-- In the static expression case, a predicate check failure is an error.
if Has_Predicates (Target_Typ) then
Check_Expression_Against_Static_Predicate
(N, Target_Typ, Static_Failure_Is_Error => True);
end if;
-- If at this stage we have a fixed point to integer conversion, make
-- sure that the Do_Range_Check flag is set which is not always done
-- by exp_fixd.adb.
if Nkind (N) = N_Type_Conversion
and then Is_Integer_Type (Target_Typ)
and then Is_Fixed_Point_Type (Operand_Typ)
and then not Range_Checks_Suppressed (Target_Typ)
and then not Range_Checks_Suppressed (Operand_Typ)
then
Set_Do_Range_Check (Operand);
end if;
-- Generating C code a type conversion of an access to constrained
-- array type to access to unconstrained array type involves building
-- a fat pointer which in general cannot be generated on the fly. We
-- remove side effects in order to store the result of the conversion
-- into a temporary.
if Modify_Tree_For_C
and then Nkind (N) = N_Type_Conversion
and then Nkind (Parent (N)) /= N_Object_Declaration
and then Is_Access_Type (Etype (N))
and then Is_Array_Type (Designated_Type (Etype (N)))
and then not Is_Constrained (Designated_Type (Etype (N)))
and then Is_Constrained (Designated_Type (Etype (Expression (N))))
then
Remove_Side_Effects (N);
end if;
end Resolve_Type_Conversion;
----------------------
-- Resolve_Unary_Op --
----------------------
procedure Resolve_Unary_Op (N : Node_Id; Typ : Entity_Id) is
B_Typ : constant Entity_Id := Base_Type (Typ);
R : constant Node_Id := Right_Opnd (N);
OK : Boolean;
Lo : Uint;
Hi : Uint;
begin
-- Deal with intrinsic unary operators
if Comes_From_Source (N)
and then Ekind (Entity (N)) = E_Function
and then Is_Imported (Entity (N))
and then Is_Intrinsic_Subprogram (Entity (N))
then
Resolve_Intrinsic_Unary_Operator (N, Typ);
return;
end if;
-- Deal with universal cases
if Etype (R) = Universal_Integer
or else
Etype (R) = Universal_Real
then
Check_For_Visible_Operator (N, B_Typ);
end if;
Set_Etype (N, B_Typ);
Resolve (R, B_Typ);
-- Generate warning for expressions like abs (x mod 2)
if Warn_On_Redundant_Constructs
and then Nkind (N) = N_Op_Abs
then
Determine_Range (Right_Opnd (N), OK, Lo, Hi);
if OK and then Hi >= Lo and then Lo >= 0 then
Error_Msg_N -- CODEFIX
("?r?abs applied to known non-negative value has no effect", N);
end if;
end if;
-- Deal with reference generation
Check_Unset_Reference (R);
Generate_Operator_Reference (N, B_Typ);
Analyze_Dimension (N);
Eval_Unary_Op (N);
-- Set overflow checking bit. Much cleverer code needed here eventually
-- and perhaps the Resolve routines should be separated for the various
-- arithmetic operations, since they will need different processing ???
if Nkind (N) in N_Op then
if not Overflow_Checks_Suppressed (Etype (N)) then
Enable_Overflow_Check (N);
end if;
end if;
-- Generate warning for expressions like -5 mod 3 for integers. No need
-- to worry in the floating-point case, since parens do not affect the
-- result so there is no point in giving in a warning.
declare
Norig : constant Node_Id := Original_Node (N);
Rorig : Node_Id;
Val : Uint;
HB : Uint;
LB : Uint;
Lval : Uint;
Opnd : Node_Id;
begin
if Warn_On_Questionable_Missing_Parens
and then Comes_From_Source (Norig)
and then Is_Integer_Type (Typ)
and then Nkind (Norig) = N_Op_Minus
then
Rorig := Original_Node (Right_Opnd (Norig));
-- We are looking for cases where the right operand is not
-- parenthesized, and is a binary operator, multiply, divide, or
-- mod. These are the cases where the grouping can affect results.
if Paren_Count (Rorig) = 0
and then Nkind (Rorig) in N_Op_Mod | N_Op_Multiply | N_Op_Divide
then
-- For mod, we always give the warning, since the value is
-- affected by the parenthesization (e.g. (-5) mod 315 /=
-- -(5 mod 315)). But for the other cases, the only concern is
-- overflow, e.g. for the case of 8 big signed (-(2 * 64)
-- overflows, but (-2) * 64 does not). So we try to give the
-- message only when overflow is possible.
if Nkind (Rorig) /= N_Op_Mod
and then Compile_Time_Known_Value (R)
then
Val := Expr_Value (R);
if Compile_Time_Known_Value (Type_High_Bound (Typ)) then
HB := Expr_Value (Type_High_Bound (Typ));
else
HB := Expr_Value (Type_High_Bound (Base_Type (Typ)));
end if;
if Compile_Time_Known_Value (Type_Low_Bound (Typ)) then
LB := Expr_Value (Type_Low_Bound (Typ));
else
LB := Expr_Value (Type_Low_Bound (Base_Type (Typ)));
end if;
-- Note that the test below is deliberately excluding the
-- largest negative number, since that is a potentially
-- troublesome case (e.g. -2 * x, where the result is the
-- largest negative integer has an overflow with 2 * x).
if Val > LB and then Val <= HB then
return;
end if;
end if;
-- For the multiplication case, the only case we have to worry
-- about is when (-a)*b is exactly the largest negative number
-- so that -(a*b) can cause overflow. This can only happen if
-- a is a power of 2, and more generally if any operand is a
-- constant that is not a power of 2, then the parentheses
-- cannot affect whether overflow occurs. We only bother to
-- test the left most operand
-- Loop looking at left operands for one that has known value
Opnd := Rorig;
Opnd_Loop : while Nkind (Opnd) = N_Op_Multiply loop
if Compile_Time_Known_Value (Left_Opnd (Opnd)) then
Lval := UI_Abs (Expr_Value (Left_Opnd (Opnd)));
-- Operand value of 0 or 1 skips warning
if Lval <= 1 then
return;
-- Otherwise check power of 2, if power of 2, warn, if
-- anything else, skip warning.
else
while Lval /= 2 loop
if Lval mod 2 = 1 then
return;
else
Lval := Lval / 2;
end if;
end loop;
exit Opnd_Loop;
end if;
end if;
-- Keep looking at left operands
Opnd := Left_Opnd (Opnd);
end loop Opnd_Loop;
-- For rem or "/" we can only have a problematic situation
-- if the divisor has a value of minus one or one. Otherwise
-- overflow is impossible (divisor > 1) or we have a case of
-- division by zero in any case.
if Nkind (Rorig) in N_Op_Divide | N_Op_Rem
and then Compile_Time_Known_Value (Right_Opnd (Rorig))
and then UI_Abs (Expr_Value (Right_Opnd (Rorig))) /= 1
then
return;
end if;
-- If we fall through warning should be issued
-- Shouldn't we test Warn_On_Questionable_Missing_Parens ???
Error_Msg_N
("??unary minus expression should be parenthesized here!", N);
end if;
end if;
end;
end Resolve_Unary_Op;
----------------------------------
-- Resolve_Unchecked_Expression --
----------------------------------
procedure Resolve_Unchecked_Expression
(N : Node_Id;
Typ : Entity_Id)
is
begin
Resolve (Expression (N), Typ, Suppress => All_Checks);
Set_Etype (N, Typ);
end Resolve_Unchecked_Expression;
---------------------------------------
-- Resolve_Unchecked_Type_Conversion --
---------------------------------------
procedure Resolve_Unchecked_Type_Conversion
(N : Node_Id;
Typ : Entity_Id)
is
pragma Warnings (Off, Typ);
Operand : constant Node_Id := Expression (N);
Opnd_Type : constant Entity_Id := Etype (Operand);
begin
-- Resolve operand using its own type
Resolve (Operand, Opnd_Type);
-- If the expression is a conversion to universal integer of an
-- an expression with an integer type, then we can eliminate the
-- intermediate conversion to universal integer.
if Nkind (Operand) = N_Type_Conversion
and then Entity (Subtype_Mark (Operand)) = Universal_Integer
and then Is_Integer_Type (Etype (Expression (Operand)))
then
Rewrite (Operand, Relocate_Node (Expression (Operand)));
Analyze_And_Resolve (Operand);
end if;
-- In an inlined context, the unchecked conversion may be applied
-- to a literal, in which case its type is the type of the context.
-- (In other contexts conversions cannot apply to literals).
if In_Inlined_Body
and then (Opnd_Type = Any_Character or else
Opnd_Type = Any_Integer or else
Opnd_Type = Any_Real)
then
Set_Etype (Operand, Typ);
end if;
Analyze_Dimension (N);
Eval_Unchecked_Conversion (N);
end Resolve_Unchecked_Type_Conversion;
------------------------------
-- Rewrite_Operator_As_Call --
------------------------------
procedure Rewrite_Operator_As_Call (N : Node_Id; Nam : Entity_Id) is
Loc : constant Source_Ptr := Sloc (N);
Actuals : constant List_Id := New_List;
New_N : Node_Id;
begin
if Nkind (N) in N_Binary_Op then
Append (Left_Opnd (N), Actuals);
end if;
Append (Right_Opnd (N), Actuals);
New_N :=
Make_Function_Call (Sloc => Loc,
Name => New_Occurrence_Of (Nam, Loc),
Parameter_Associations => Actuals);
Preserve_Comes_From_Source (New_N, N);
Preserve_Comes_From_Source (Name (New_N), N);
Rewrite (N, New_N);
Set_Etype (N, Etype (Nam));
end Rewrite_Operator_As_Call;
------------------------------
-- Rewrite_Renamed_Operator --
------------------------------
procedure Rewrite_Renamed_Operator
(N : Node_Id;
Op : Entity_Id;
Typ : Entity_Id)
is
Nam : constant Name_Id := Chars (Op);
Is_Binary : constant Boolean := Nkind (N) in N_Binary_Op;
Op_Node : Node_Id;
begin
-- Do not perform this transformation within a pre/postcondition,
-- because the expression will be reanalyzed, and the transformation
-- might affect the visibility of the operator, e.g. in an instance.
-- Note that fully analyzed and expanded pre/postconditions appear as
-- pragma Check equivalents.
if In_Pre_Post_Condition (N) then
return;
end if;
-- Likewise when an expression function is being preanalyzed, since the
-- expression will be reanalyzed as part of the generated body.
if In_Spec_Expression then
declare
S : constant Entity_Id := Current_Scope_No_Loops;
begin
if Ekind (S) = E_Function
and then Nkind (Original_Node (Unit_Declaration_Node (S))) =
N_Expression_Function
then
return;
end if;
end;
end if;
-- Rewrite the operator node using the real operator, not its renaming.
-- Exclude user-defined intrinsic operations of the same name, which are
-- treated separately and rewritten as calls.
if Ekind (Op) /= E_Function or else Chars (N) /= Nam then
Op_Node := New_Node (Operator_Kind (Nam, Is_Binary), Sloc (N));
Set_Chars (Op_Node, Nam);
Set_Etype (Op_Node, Etype (N));
Set_Entity (Op_Node, Op);
Set_Right_Opnd (Op_Node, Right_Opnd (N));
-- Indicate that both the original entity and its renaming are
-- referenced at this point.
Generate_Reference (Entity (N), N);
Generate_Reference (Op, N);
if Is_Binary then
Set_Left_Opnd (Op_Node, Left_Opnd (N));
end if;
Rewrite (N, Op_Node);
-- If the context type is private, add the appropriate conversions so
-- that the operator is applied to the full view. This is done in the
-- routines that resolve intrinsic operators.
if Is_Intrinsic_Subprogram (Op) and then Is_Private_Type (Typ) then
case Nkind (N) is
when N_Op_Add
| N_Op_Divide
| N_Op_Expon
| N_Op_Mod
| N_Op_Multiply
| N_Op_Rem
| N_Op_Subtract
=>
Resolve_Intrinsic_Operator (N, Typ);
when N_Op_Abs
| N_Op_Minus
| N_Op_Plus
=>
Resolve_Intrinsic_Unary_Operator (N, Typ);
when others =>
Resolve (N, Typ);
end case;
end if;
elsif Ekind (Op) = E_Function and then Is_Intrinsic_Subprogram (Op) then
-- Operator renames a user-defined operator of the same name. Use the
-- original operator in the node, which is the one Gigi knows about.
Set_Entity (N, Op);
Set_Is_Overloaded (N, False);
end if;
end Rewrite_Renamed_Operator;
-----------------------
-- Set_Slice_Subtype --
-----------------------
-- Build an implicit subtype declaration to represent the type delivered by
-- the slice. This is an abbreviated version of an array subtype. We define
-- an index subtype for the slice, using either the subtype name or the
-- discrete range of the slice. To be consistent with index usage elsewhere
-- we create a list header to hold the single index. This list is not
-- otherwise attached to the syntax tree.
procedure Set_Slice_Subtype (N : Node_Id) is
Loc : constant Source_Ptr := Sloc (N);
Index_List : constant List_Id := New_List;
Index : Node_Id;
Index_Subtype : Entity_Id;
Index_Type : Entity_Id;
Slice_Subtype : Entity_Id;
Drange : constant Node_Id := Discrete_Range (N);
begin
Index_Type := Base_Type (Etype (Drange));
if Is_Entity_Name (Drange) then
Index_Subtype := Entity (Drange);
else
-- We force the evaluation of a range. This is definitely needed in
-- the renamed case, and seems safer to do unconditionally. Note in
-- any case that since we will create and insert an Itype referring
-- to this range, we must make sure any side effect removal actions
-- are inserted before the Itype definition.
if Nkind (Drange) = N_Range then
Force_Evaluation (Low_Bound (Drange));
Force_Evaluation (High_Bound (Drange));
-- If the discrete range is given by a subtype indication, the
-- type of the slice is the base of the subtype mark.
elsif Nkind (Drange) = N_Subtype_Indication then
declare
R : constant Node_Id := Range_Expression (Constraint (Drange));
begin
Index_Type := Base_Type (Entity (Subtype_Mark (Drange)));
Force_Evaluation (Low_Bound (R));
Force_Evaluation (High_Bound (R));
end;
end if;
Index_Subtype := Create_Itype (Subtype_Kind (Ekind (Index_Type)), N);
-- Take a new copy of Drange (where bounds have been rewritten to
-- reference side-effect-free names). Using a separate tree ensures
-- that further expansion (e.g. while rewriting a slice assignment
-- into a FOR loop) does not attempt to remove side effects on the
-- bounds again (which would cause the bounds in the index subtype
-- definition to refer to temporaries before they are defined) (the
-- reason is that some names are considered side effect free here
-- for the subtype, but not in the context of a loop iteration
-- scheme).
Set_Scalar_Range (Index_Subtype, New_Copy_Tree (Drange));
Set_Parent (Scalar_Range (Index_Subtype), Index_Subtype);
Set_Etype (Index_Subtype, Index_Type);
Set_Size_Info (Index_Subtype, Index_Type);
Set_RM_Size (Index_Subtype, RM_Size (Index_Type));
Set_Is_Constrained (Index_Subtype);
end if;
Slice_Subtype := Create_Itype (E_Array_Subtype, N);
Index := New_Occurrence_Of (Index_Subtype, Loc);
Set_Etype (Index, Index_Subtype);
Append (Index, Index_List);
Set_First_Index (Slice_Subtype, Index);
Set_Etype (Slice_Subtype, Base_Type (Etype (N)));
Set_Is_Constrained (Slice_Subtype, True);
Check_Compile_Time_Size (Slice_Subtype);
-- The Etype of the existing Slice node is reset to this slice subtype.
-- Its bounds are obtained from its first index.
Set_Etype (N, Slice_Subtype);
-- For bit-packed slice subtypes, freeze immediately (except in the case
-- of being in a "spec expression" where we never freeze when we first
-- see the expression).
if Is_Bit_Packed_Array (Slice_Subtype) and not In_Spec_Expression then
Freeze_Itype (Slice_Subtype, N);
-- For all other cases insert an itype reference in the slice's actions
-- so that the itype is frozen at the proper place in the tree (i.e. at
-- the point where actions for the slice are analyzed). Note that this
-- is different from freezing the itype immediately, which might be
-- premature (e.g. if the slice is within a transient scope). This needs
-- to be done only if expansion is enabled.
elsif Expander_Active then
Ensure_Defined (Typ => Slice_Subtype, N => N);
end if;
end Set_Slice_Subtype;
--------------------------------
-- Set_String_Literal_Subtype --
--------------------------------
procedure Set_String_Literal_Subtype (N : Node_Id; Typ : Entity_Id) is
Loc : constant Source_Ptr := Sloc (N);
Low_Bound : constant Node_Id :=
Type_Low_Bound (Etype (First_Index (Typ)));
Subtype_Id : Entity_Id;
begin
if Nkind (N) /= N_String_Literal then
return;
end if;
Subtype_Id := Create_Itype (E_String_Literal_Subtype, N);
Set_String_Literal_Length (Subtype_Id, UI_From_Int
(String_Length (Strval (N))));
Set_Etype (Subtype_Id, Base_Type (Typ));
Set_Is_Constrained (Subtype_Id);
Set_Etype (N, Subtype_Id);
-- The low bound is set from the low bound of the corresponding index
-- type. Note that we do not store the high bound in the string literal
-- subtype, but it can be deduced if necessary from the length and the
-- low bound.
if Is_OK_Static_Expression (Low_Bound) then
Set_String_Literal_Low_Bound (Subtype_Id, Low_Bound);
-- If the lower bound is not static we create a range for the string
-- literal, using the index type and the known length of the literal.
-- If the length is 1, then the upper bound is set to a mere copy of
-- the lower bound; or else, if the index type is a signed integer,
-- then the upper bound is computed as Low_Bound + L - 1; otherwise,
-- the upper bound is computed as T'Val (T'Pos (Low_Bound) + L - 1).
else
declare
Length : constant Nat := String_Length (Strval (N));
Index_List : constant List_Id := New_List;
Index_Type : constant Entity_Id := Etype (First_Index (Typ));
Array_Subtype : Entity_Id;
Drange : Node_Id;
High_Bound : Node_Id;
Index : Node_Id;
Index_Subtype : Entity_Id;
begin
if Length = 1 then
High_Bound := New_Copy_Tree (Low_Bound);
elsif Is_Signed_Integer_Type (Index_Type) then
High_Bound :=
Make_Op_Add (Loc,
Left_Opnd => New_Copy_Tree (Low_Bound),
Right_Opnd => Make_Integer_Literal (Loc, Length - 1));
else
High_Bound :=
Make_Attribute_Reference (Loc,
Attribute_Name => Name_Val,
Prefix =>
New_Occurrence_Of (Index_Type, Loc),
Expressions => New_List (
Make_Op_Add (Loc,
Left_Opnd =>
Make_Attribute_Reference (Loc,
Attribute_Name => Name_Pos,
Prefix =>
New_Occurrence_Of (Index_Type, Loc),
Expressions =>
New_List (New_Copy_Tree (Low_Bound))),
Right_Opnd =>
Make_Integer_Literal (Loc, Length - 1))));
end if;
if Is_Integer_Type (Index_Type) then
Set_String_Literal_Low_Bound
(Subtype_Id, Make_Integer_Literal (Loc, 1));
else
-- If the index type is an enumeration type, build bounds
-- expression with attributes.
Set_String_Literal_Low_Bound
(Subtype_Id,
Make_Attribute_Reference (Loc,
Attribute_Name => Name_First,
Prefix =>
New_Occurrence_Of (Base_Type (Index_Type), Loc)));
end if;
Analyze_And_Resolve
(String_Literal_Low_Bound (Subtype_Id), Base_Type (Index_Type));
-- Build bona fide subtype for the string, and wrap it in an
-- unchecked conversion, because the back end expects the
-- String_Literal_Subtype to have a static lower bound.
Index_Subtype :=
Create_Itype (Subtype_Kind (Ekind (Index_Type)), N);
Drange := Make_Range (Loc, New_Copy_Tree (Low_Bound), High_Bound);
Set_Scalar_Range (Index_Subtype, Drange);
Set_Parent (Drange, N);
Analyze_And_Resolve (Drange, Index_Type);
-- In this context, the Index_Type may already have a constraint,
-- so use common base type on string subtype. The base type may
-- be used when generating attributes of the string, for example
-- in the context of a slice assignment.
Set_Etype (Index_Subtype, Base_Type (Index_Type));
Set_Size_Info (Index_Subtype, Index_Type);
Set_RM_Size (Index_Subtype, RM_Size (Index_Type));
Array_Subtype := Create_Itype (E_Array_Subtype, N);
Index := New_Occurrence_Of (Index_Subtype, Loc);
Set_Etype (Index, Index_Subtype);
Append (Index, Index_List);
Set_First_Index (Array_Subtype, Index);
Set_Etype (Array_Subtype, Base_Type (Typ));
Set_Is_Constrained (Array_Subtype, True);
Rewrite (N,
Make_Unchecked_Type_Conversion (Loc,
Subtype_Mark => New_Occurrence_Of (Array_Subtype, Loc),
Expression => Relocate_Node (N)));
Set_Etype (N, Array_Subtype);
end;
end if;
end Set_String_Literal_Subtype;
------------------------------
-- Simplify_Type_Conversion --
------------------------------
procedure Simplify_Type_Conversion (N : Node_Id) is
begin
if Nkind (N) = N_Type_Conversion then
declare
Operand : constant Node_Id := Expression (N);
Target_Typ : constant Entity_Id := Etype (N);
Opnd_Typ : constant Entity_Id := Etype (Operand);
begin
-- Special processing if the conversion is the expression of a
-- Rounding or Truncation attribute reference. In this case we
-- replace:
-- ityp (ftyp'Rounding (x)) or ityp (ftyp'Truncation (x))
-- by
-- ityp (x)
-- with the Float_Truncate flag set to False or True respectively,
-- which is more efficient. We reuse Rounding for Machine_Rounding
-- as System.Fat_Gen, which is a permissible behavior.
if Is_Floating_Point_Type (Opnd_Typ)
and then
(Is_Integer_Type (Target_Typ)
or else (Is_Fixed_Point_Type (Target_Typ)
and then Conversion_OK (N)))
and then Nkind (Operand) = N_Attribute_Reference
and then Attribute_Name (Operand) in Name_Rounding
| Name_Machine_Rounding
| Name_Truncation
then
declare
Truncate : constant Boolean :=
Attribute_Name (Operand) = Name_Truncation;
begin
Rewrite (Operand,
Relocate_Node (First (Expressions (Operand))));
Set_Float_Truncate (N, Truncate);
end;
-- Special processing for the conversion of an integer literal to
-- a dynamic type: we first convert the literal to the root type
-- and then convert the result to the target type, the goal being
-- to avoid doing range checks in universal integer.
elsif Is_Integer_Type (Target_Typ)
and then not Is_Generic_Type (Root_Type (Target_Typ))
and then Nkind (Operand) = N_Integer_Literal
and then Opnd_Typ = Universal_Integer
then
Convert_To_And_Rewrite (Root_Type (Target_Typ), Operand);
Analyze_And_Resolve (Operand);
-- If the expression is a conversion to universal integer of an
-- an expression with an integer type, then we can eliminate the
-- intermediate conversion to universal integer.
elsif Nkind (Operand) = N_Type_Conversion
and then Entity (Subtype_Mark (Operand)) = Universal_Integer
and then Is_Integer_Type (Etype (Expression (Operand)))
then
Rewrite (Operand, Relocate_Node (Expression (Operand)));
Analyze_And_Resolve (Operand);
end if;
end;
end if;
end Simplify_Type_Conversion;
-----------------------------
-- Unique_Fixed_Point_Type --
-----------------------------
function Unique_Fixed_Point_Type (N : Node_Id) return Entity_Id is
procedure Fixed_Point_Error (T1 : Entity_Id; T2 : Entity_Id);
-- Give error messages for true ambiguity. Messages are posted on node
-- N, and entities T1, T2 are the possible interpretations.
-----------------------
-- Fixed_Point_Error --
-----------------------
procedure Fixed_Point_Error (T1 : Entity_Id; T2 : Entity_Id) is
begin
Error_Msg_N ("ambiguous universal_fixed_expression", N);
Error_Msg_NE ("\\possible interpretation as}", N, T1);
Error_Msg_NE ("\\possible interpretation as}", N, T2);
end Fixed_Point_Error;
-- Local variables
ErrN : Node_Id;
Item : Node_Id;
Scop : Entity_Id;
T1 : Entity_Id;
T2 : Entity_Id;
-- Start of processing for Unique_Fixed_Point_Type
begin
-- The operations on Duration are visible, so Duration is always a
-- possible interpretation.
T1 := Standard_Duration;
-- Look for fixed-point types in enclosing scopes
Scop := Current_Scope;
while Scop /= Standard_Standard loop
T2 := First_Entity (Scop);
while Present (T2) loop
if Is_Fixed_Point_Type (T2)
and then Current_Entity (T2) = T2
and then Scope (Base_Type (T2)) = Scop
then
if Present (T1) then
Fixed_Point_Error (T1, T2);
return Any_Type;
else
T1 := T2;
end if;
end if;
Next_Entity (T2);
end loop;
Scop := Scope (Scop);
end loop;
-- Look for visible fixed type declarations in the context
Item := First (Context_Items (Cunit (Current_Sem_Unit)));
while Present (Item) loop
if Nkind (Item) = N_With_Clause then
Scop := Entity (Name (Item));
T2 := First_Entity (Scop);
while Present (T2) loop
if Is_Fixed_Point_Type (T2)
and then Scope (Base_Type (T2)) = Scop
and then (Is_Potentially_Use_Visible (T2) or else In_Use (T2))
then
if Present (T1) then
Fixed_Point_Error (T1, T2);
return Any_Type;
else
T1 := T2;
end if;
end if;
Next_Entity (T2);
end loop;
end if;
Next (Item);
end loop;
if Nkind (N) = N_Real_Literal then
Error_Msg_NE ("??real literal interpreted as }!", N, T1);
else
-- When the context is a type conversion, issue the warning on the
-- expression of the conversion because it is the actual operation.
if Nkind (N) in N_Type_Conversion | N_Unchecked_Type_Conversion then
ErrN := Expression (N);
else
ErrN := N;
end if;
Error_Msg_NE
("??universal_fixed expression interpreted as }!", ErrN, T1);
end if;
return T1;
end Unique_Fixed_Point_Type;
----------------------
-- Valid_Conversion --
----------------------
function Valid_Conversion
(N : Node_Id;
Target : Entity_Id;
Operand : Node_Id;
Report_Errs : Boolean := True) return Boolean
is
Target_Type : constant Entity_Id := Base_Type (Target);
Opnd_Type : Entity_Id := Etype (Operand);
Inc_Ancestor : Entity_Id;
function Conversion_Check
(Valid : Boolean;
Msg : String) return Boolean;
-- Little routine to post Msg if Valid is False, returns Valid value
procedure Conversion_Error_N (Msg : String; N : Node_Or_Entity_Id);
-- If Report_Errs, then calls Errout.Error_Msg_N with its arguments
procedure Conversion_Error_NE
(Msg : String;
N : Node_Or_Entity_Id;
E : Node_Or_Entity_Id);
-- If Report_Errs, then calls Errout.Error_Msg_NE with its arguments
function In_Instance_Code return Boolean;
-- Return True if expression is within an instance but is not in one of
-- the actuals of the instantiation. Type conversions within an instance
-- are not rechecked because type visbility may lead to spurious errors,
-- but conversions in an actual for a formal object must be checked.
function Is_Discrim_Of_Bad_Access_Conversion_Argument
(Expr : Node_Id) return Boolean;
-- Implicit anonymous-to-named access type conversions are not allowed
-- if the "statically deeper than" relationship does not apply to the
-- type of the conversion operand. See RM 8.6(28.1) and AARM 8.6(28.d).
-- We deal with most such cases elsewhere so that we can emit more
-- specific error messages (e.g., if the operand is an access parameter
-- or a saooaaat (stand-alone object of an anonymous access type)), but
-- here is where we catch the case where the operand is an access
-- discriminant selected from a dereference of another such "bad"
-- conversion argument.
function Valid_Tagged_Conversion
(Target_Type : Entity_Id;
Opnd_Type : Entity_Id) return Boolean;
-- Specifically test for validity of tagged conversions
function Valid_Array_Conversion return Boolean;
-- Check index and component conformance, and accessibility levels if
-- the component types are anonymous access types (Ada 2005).
----------------------
-- Conversion_Check --
----------------------
function Conversion_Check
(Valid : Boolean;
Msg : String) return Boolean
is
begin
if not Valid
-- A generic unit has already been analyzed and we have verified
-- that a particular conversion is OK in that context. Since the
-- instance is reanalyzed without relying on the relationships
-- established during the analysis of the generic, it is possible
-- to end up with inconsistent views of private types. Do not emit
-- the error message in such cases. The rest of the machinery in
-- Valid_Conversion still ensures the proper compatibility of
-- target and operand types.
and then not In_Instance_Code
then
Conversion_Error_N (Msg, Operand);
end if;
return Valid;
end Conversion_Check;
------------------------
-- Conversion_Error_N --
------------------------
procedure Conversion_Error_N (Msg : String; N : Node_Or_Entity_Id) is
begin
if Report_Errs then
Error_Msg_N (Msg, N);
end if;
end Conversion_Error_N;
-------------------------
-- Conversion_Error_NE --
-------------------------
procedure Conversion_Error_NE
(Msg : String;
N : Node_Or_Entity_Id;
E : Node_Or_Entity_Id)
is
begin
if Report_Errs then
Error_Msg_NE (Msg, N, E);
end if;
end Conversion_Error_NE;
----------------------
-- In_Instance_Code --
----------------------
function In_Instance_Code return Boolean is
Par : Node_Id;
begin
if not In_Instance then
return False;
else
Par := Parent (N);
while Present (Par) loop
-- The expression is part of an actual object if it appears in
-- the generated object declaration in the instance.
if Nkind (Par) = N_Object_Declaration
and then Present (Corresponding_Generic_Association (Par))
then
return False;
else
exit when
Nkind (Par) in N_Statement_Other_Than_Procedure_Call
or else Nkind (Par) in N_Subprogram_Call
or else Nkind (Par) in N_Declaration;
end if;
Par := Parent (Par);
end loop;
-- Otherwise the expression appears within the instantiated unit
return True;
end if;
end In_Instance_Code;
--------------------------------------------------
-- Is_Discrim_Of_Bad_Access_Conversion_Argument --
--------------------------------------------------
function Is_Discrim_Of_Bad_Access_Conversion_Argument
(Expr : Node_Id) return Boolean
is
Exp_Type : Entity_Id := Base_Type (Etype (Expr));
pragma Assert (Is_Access_Type (Exp_Type));
Associated_Node : Node_Id;
Deref_Prefix : Node_Id;
begin
if not Is_Anonymous_Access_Type (Exp_Type) then
return False;
end if;
pragma Assert (Is_Itype (Exp_Type));
Associated_Node := Associated_Node_For_Itype (Exp_Type);
if Nkind (Associated_Node) /= N_Discriminant_Specification then
return False; -- not the type of an access discriminant
end if;
-- return False if Expr not of form <prefix>.all.Some_Component
if (Nkind (Expr) /= N_Selected_Component)
or else (Nkind (Prefix (Expr)) /= N_Explicit_Dereference)
then
-- conditional expressions, declare expressions ???
return False;
end if;
Deref_Prefix := Prefix (Prefix (Expr));
Exp_Type := Base_Type (Etype (Deref_Prefix));
-- The "statically deeper relationship" does not apply
-- to generic formal access types, so a prefix of such
-- a type is a "bad" prefix.
if Is_Generic_Formal (Exp_Type) then
return True;
-- The "statically deeper relationship" does apply to
-- any other named access type.
elsif not Is_Anonymous_Access_Type (Exp_Type) then
return False;
end if;
pragma Assert (Is_Itype (Exp_Type));
Associated_Node := Associated_Node_For_Itype (Exp_Type);
-- The "statically deeper relationship" applies to some
-- anonymous access types and not to others. Return
-- True for the cases where it does not apply. Also check
-- recursively for the
-- <prefix>.all.Access_Discrim.all.Access_Discrim case,
-- where the correct result depends on <prefix>.
return Nkind (Associated_Node) in
N_Procedure_Specification | -- access parameter
N_Function_Specification | -- access parameter
N_Object_Declaration -- saooaaat
or else Is_Discrim_Of_Bad_Access_Conversion_Argument (Deref_Prefix);
end Is_Discrim_Of_Bad_Access_Conversion_Argument;
----------------------------
-- Valid_Array_Conversion --
----------------------------
function Valid_Array_Conversion return Boolean is
Opnd_Comp_Type : constant Entity_Id := Component_Type (Opnd_Type);
Opnd_Comp_Base : constant Entity_Id := Base_Type (Opnd_Comp_Type);
Opnd_Index : Node_Id;
Opnd_Index_Type : Entity_Id;
Target_Comp_Type : constant Entity_Id :=
Component_Type (Target_Type);
Target_Comp_Base : constant Entity_Id :=
Base_Type (Target_Comp_Type);
Target_Index : Node_Id;
Target_Index_Type : Entity_Id;
begin
-- Error if wrong number of dimensions
if
Number_Dimensions (Target_Type) /= Number_Dimensions (Opnd_Type)
then
Conversion_Error_N
("incompatible number of dimensions for conversion", Operand);
return False;
-- Number of dimensions matches
else
-- Loop through indexes of the two arrays
Target_Index := First_Index (Target_Type);
Opnd_Index := First_Index (Opnd_Type);
while Present (Target_Index) and then Present (Opnd_Index) loop
Target_Index_Type := Etype (Target_Index);
Opnd_Index_Type := Etype (Opnd_Index);
-- Error if index types are incompatible
if not (Is_Integer_Type (Target_Index_Type)
and then Is_Integer_Type (Opnd_Index_Type))
and then (Root_Type (Target_Index_Type)
/= Root_Type (Opnd_Index_Type))
then
Conversion_Error_N
("incompatible index types for array conversion",
Operand);
return False;
end if;
Next_Index (Target_Index);
Next_Index (Opnd_Index);
end loop;
-- If component types have same base type, all set
if Target_Comp_Base = Opnd_Comp_Base then
null;
-- Here if base types of components are not the same. The only
-- time this is allowed is if we have anonymous access types.
-- The conversion of arrays of anonymous access types can lead
-- to dangling pointers. AI-392 formalizes the accessibility
-- checks that must be applied to such conversions to prevent
-- out-of-scope references.
elsif Ekind (Target_Comp_Base) in
E_Anonymous_Access_Type
| E_Anonymous_Access_Subprogram_Type
and then Ekind (Opnd_Comp_Base) = Ekind (Target_Comp_Base)
and then
Subtypes_Statically_Match (Target_Comp_Type, Opnd_Comp_Type)
then
if Type_Access_Level (Target_Type) <
Deepest_Type_Access_Level (Opnd_Type)
then
if In_Instance_Body then
Error_Msg_Warn := SPARK_Mode /= On;
Conversion_Error_N
("source array type has deeper accessibility "
& "level than target<<", Operand);
Conversion_Error_N ("\Program_Error [<<", Operand);
Rewrite (N,
Make_Raise_Program_Error (Sloc (N),
Reason => PE_Accessibility_Check_Failed));
Set_Etype (N, Target_Type);
return False;
-- Conversion not allowed because of accessibility levels
else
Conversion_Error_N
("source array type has deeper accessibility "
& "level than target", Operand);
return False;
end if;
else
null;
end if;
-- All other cases where component base types do not match
else
Conversion_Error_N
("incompatible component types for array conversion",
Operand);
return False;
end if;
-- Check that component subtypes statically match. For numeric
-- types this means that both must be either constrained or
-- unconstrained. For enumeration types the bounds must match.
-- All of this is checked in Subtypes_Statically_Match.
if not Subtypes_Statically_Match
(Target_Comp_Type, Opnd_Comp_Type)
then
Conversion_Error_N
("component subtypes must statically match", Operand);
return False;
end if;
end if;
return True;
end Valid_Array_Conversion;
-----------------------------
-- Valid_Tagged_Conversion --
-----------------------------
function Valid_Tagged_Conversion
(Target_Type : Entity_Id;
Opnd_Type : Entity_Id) return Boolean
is
begin
-- Upward conversions are allowed (RM 4.6(22))
if Covers (Target_Type, Opnd_Type)
or else Is_Ancestor (Target_Type, Opnd_Type)
then
return True;
-- Downward conversion are allowed if the operand is class-wide
-- (RM 4.6(23)).
elsif Is_Class_Wide_Type (Opnd_Type)
and then Covers (Opnd_Type, Target_Type)
then
return True;
elsif Covers (Opnd_Type, Target_Type)
or else Is_Ancestor (Opnd_Type, Target_Type)
then
return
Conversion_Check (False,
"downward conversion of tagged objects not allowed");
-- Ada 2005 (AI-251): The conversion to/from interface types is
-- always valid. The types involved may be class-wide (sub)types.
elsif Is_Interface (Etype (Base_Type (Target_Type)))
or else Is_Interface (Etype (Base_Type (Opnd_Type)))
then
return True;
-- If the operand is a class-wide type obtained through a limited_
-- with clause, and the context includes the nonlimited view, use
-- it to determine whether the conversion is legal.
elsif Is_Class_Wide_Type (Opnd_Type)
and then From_Limited_With (Opnd_Type)
and then Present (Non_Limited_View (Etype (Opnd_Type)))
and then Is_Interface (Non_Limited_View (Etype (Opnd_Type)))
then
return True;
elsif Is_Access_Type (Opnd_Type)
and then Is_Interface (Directly_Designated_Type (Opnd_Type))
then
return True;
else
Conversion_Error_NE
("invalid tagged conversion, not compatible with}",
N, First_Subtype (Opnd_Type));
return False;
end if;
end Valid_Tagged_Conversion;
-- Start of processing for Valid_Conversion
begin
Check_Parameterless_Call (Operand);
if Is_Overloaded (Operand) then
declare
I : Interp_Index;
I1 : Interp_Index;
It : Interp;
It1 : Interp;
N1 : Entity_Id;
T1 : Entity_Id;
begin
-- Remove procedure calls, which syntactically cannot appear in
-- this context, but which cannot be removed by type checking,
-- because the context does not impose a type.
-- The node may be labelled overloaded, but still contain only one
-- interpretation because others were discarded earlier. If this
-- is the case, retain the single interpretation if legal.
Get_First_Interp (Operand, I, It);
Opnd_Type := It.Typ;
Get_Next_Interp (I, It);
if Present (It.Typ)
and then Opnd_Type /= Standard_Void_Type
then
-- More than one candidate interpretation is available
Get_First_Interp (Operand, I, It);
while Present (It.Typ) loop
if It.Typ = Standard_Void_Type then
Remove_Interp (I);
end if;
-- When compiling for a system where Address is of a visible
-- integer type, spurious ambiguities can be produced when
-- arithmetic operations have a literal operand and return
-- System.Address or a descendant of it. These ambiguities
-- are usually resolved by the context, but for conversions
-- there is no context type and the removal of the spurious
-- operations must be done explicitly here.
if not Address_Is_Private
and then Is_Descendant_Of_Address (It.Typ)
then
Remove_Interp (I);
end if;
Get_Next_Interp (I, It);
end loop;
end if;
Get_First_Interp (Operand, I, It);
I1 := I;
It1 := It;
if No (It.Typ) then
Conversion_Error_N ("illegal operand in conversion", Operand);
return False;
end if;
Get_Next_Interp (I, It);
if Present (It.Typ) then
N1 := It1.Nam;
T1 := It1.Typ;
It1 := Disambiguate (Operand, I1, I, Any_Type);
if It1 = No_Interp then
Conversion_Error_N
("ambiguous operand in conversion", Operand);
-- If the interpretation involves a standard operator, use
-- the location of the type, which may be user-defined.
if Sloc (It.Nam) = Standard_Location then
Error_Msg_Sloc := Sloc (It.Typ);
else
Error_Msg_Sloc := Sloc (It.Nam);
end if;
Conversion_Error_N -- CODEFIX
("\\possible interpretation#!", Operand);
if Sloc (N1) = Standard_Location then
Error_Msg_Sloc := Sloc (T1);
else
Error_Msg_Sloc := Sloc (N1);
end if;
Conversion_Error_N -- CODEFIX
("\\possible interpretation#!", Operand);
return False;
end if;
end if;
Set_Etype (Operand, It1.Typ);
Opnd_Type := It1.Typ;
end;
end if;
-- Deal with conversion of integer type to address if the pragma
-- Allow_Integer_Address is in effect. We convert the conversion to
-- an unchecked conversion in this case and we are all done.
if Address_Integer_Convert_OK (Opnd_Type, Target_Type) then
Rewrite (N, Unchecked_Convert_To (Target_Type, Expression (N)));
Analyze_And_Resolve (N, Target_Type);
return True;
end if;
-- If we are within a child unit, check whether the type of the
-- expression has an ancestor in a parent unit, in which case it
-- belongs to its derivation class even if the ancestor is private.
-- See RM 7.3.1 (5.2/3).
Inc_Ancestor := Get_Incomplete_View_Of_Ancestor (Opnd_Type);
-- Numeric types
if Is_Numeric_Type (Target_Type) then
-- A universal fixed expression can be converted to any numeric type
if Opnd_Type = Universal_Fixed then
return True;
-- Also no need to check when in an instance or inlined body, because
-- the legality has been established when the template was analyzed.
-- Furthermore, numeric conversions may occur where only a private
-- view of the operand type is visible at the instantiation point.
-- This results in a spurious error if we check that the operand type
-- is a numeric type.
-- Note: in a previous version of this unit, the following tests were
-- applied only for generated code (Comes_From_Source set to False),
-- but in fact the test is required for source code as well, since
-- this situation can arise in source code.
elsif In_Instance_Code or else In_Inlined_Body then
return True;
-- Otherwise we need the conversion check
else
return Conversion_Check
(Is_Numeric_Type (Opnd_Type)
or else
(Present (Inc_Ancestor)
and then Is_Numeric_Type (Inc_Ancestor)),
"illegal operand for numeric conversion");
end if;
-- Array types
elsif Is_Array_Type (Target_Type) then
if not Is_Array_Type (Opnd_Type)
or else Opnd_Type = Any_Composite
or else Opnd_Type = Any_String
then
Conversion_Error_N
("illegal operand for array conversion", Operand);
return False;
else
return Valid_Array_Conversion;
end if;
-- Ada 2005 (AI-251): Internally generated conversions of access to
-- interface types added to force the displacement of the pointer to
-- reference the corresponding dispatch table.
elsif not Comes_From_Source (N)
and then Is_Access_Type (Target_Type)
and then Is_Interface (Designated_Type (Target_Type))
then
return True;
-- Ada 2005 (AI-251): Anonymous access types where target references an
-- interface type.
elsif Is_Access_Type (Opnd_Type)
and then Ekind (Target_Type) in
E_General_Access_Type | E_Anonymous_Access_Type
and then Is_Interface (Directly_Designated_Type (Target_Type))
then
-- Check the static accessibility rule of 4.6(17). Note that the
-- check is not enforced when within an instance body, since the
-- RM requires such cases to be caught at run time.
-- If the operand is a rewriting of an allocator no check is needed
-- because there are no accessibility issues.
if Nkind (Original_Node (N)) = N_Allocator then
null;
elsif Ekind (Target_Type) /= E_Anonymous_Access_Type then
if Type_Access_Level (Opnd_Type) >
Deepest_Type_Access_Level (Target_Type)
then
-- In an instance, this is a run-time check, but one we know
-- will fail, so generate an appropriate warning. The raise
-- will be generated by Expand_N_Type_Conversion.
if In_Instance_Body then
Error_Msg_Warn := SPARK_Mode /= On;
Conversion_Error_N
("cannot convert local pointer to non-local access type<<",
Operand);
Conversion_Error_N ("\Program_Error [<<", Operand);
else
Conversion_Error_N
("cannot convert local pointer to non-local access type",
Operand);
return False;
end if;
-- Special accessibility checks are needed in the case of access
-- discriminants declared for a limited type.
elsif Ekind (Opnd_Type) = E_Anonymous_Access_Type
and then not Is_Local_Anonymous_Access (Opnd_Type)
then
-- When the operand is a selected access discriminant the check
-- needs to be made against the level of the object denoted by
-- the prefix of the selected name (Object_Access_Level handles
-- checking the prefix of the operand for this case).
if Nkind (Operand) = N_Selected_Component
and then Object_Access_Level (Operand) >
Deepest_Type_Access_Level (Target_Type)
then
-- In an instance, this is a run-time check, but one we know
-- will fail, so generate an appropriate warning. The raise
-- will be generated by Expand_N_Type_Conversion.
if In_Instance_Body then
Error_Msg_Warn := SPARK_Mode /= On;
Conversion_Error_N
("cannot convert access discriminant to non-local "
& "access type<<", Operand);
Conversion_Error_N ("\Program_Error [<<", Operand);
-- Real error if not in instance body
else
Conversion_Error_N
("cannot convert access discriminant to non-local "
& "access type", Operand);
return False;
end if;
end if;
-- The case of a reference to an access discriminant from
-- within a limited type declaration (which will appear as
-- a discriminal) is always illegal because the level of the
-- discriminant is considered to be deeper than any (nameable)
-- access type.
if Is_Entity_Name (Operand)
and then not Is_Local_Anonymous_Access (Opnd_Type)
and then
Ekind (Entity (Operand)) in E_In_Parameter | E_Constant
and then Present (Discriminal_Link (Entity (Operand)))
then
Conversion_Error_N
("discriminant has deeper accessibility level than target",
Operand);
return False;
end if;
end if;
end if;
return True;
-- General and anonymous access types
elsif Ekind (Target_Type) in
E_General_Access_Type | E_Anonymous_Access_Type
and then
Conversion_Check
(Is_Access_Type (Opnd_Type)
and then
Ekind (Opnd_Type) not in
E_Access_Subprogram_Type |
E_Access_Protected_Subprogram_Type,
"must be an access-to-object type")
then
if Is_Access_Constant (Opnd_Type)
and then not Is_Access_Constant (Target_Type)
then
Conversion_Error_N
("access-to-constant operand type not allowed", Operand);
return False;
end if;
-- Check the static accessibility rule of 4.6(17). Note that the
-- check is not enforced when within an instance body, since the RM
-- requires such cases to be caught at run time.
if Ekind (Target_Type) /= E_Anonymous_Access_Type
or else Is_Local_Anonymous_Access (Target_Type)
or else Nkind (Associated_Node_For_Itype (Target_Type)) =
N_Object_Declaration
then
-- Ada 2012 (AI05-0149): Perform legality checking on implicit
-- conversions from an anonymous access type to a named general
-- access type. Such conversions are not allowed in the case of
-- access parameters and stand-alone objects of an anonymous
-- access type. The implicit conversion case is recognized by
-- testing that Comes_From_Source is False and that it's been
-- rewritten. The Comes_From_Source test isn't sufficient because
-- nodes in inlined calls to predefined library routines can have
-- Comes_From_Source set to False. (Is there a better way to test
-- for implicit conversions???).
--
-- Do not treat a rewritten 'Old attribute reference like other
-- rewrite substitutions. This makes a difference, for example,
-- in the case where we are generating the expansion of a
-- membership test of the form
-- Saooaaat'Old in Named_Access_Type
-- because in this case Valid_Conversion needs to return True
-- (otherwise the expansion will be False - see the call site
-- in exp_ch4.adb).
if Ada_Version >= Ada_2012
and then not Comes_From_Source (N)
and then Is_Rewrite_Substitution (N)
and then not Is_Attribute_Old (Original_Node (N))
and then Ekind (Base_Type (Target_Type)) = E_General_Access_Type
and then Ekind (Opnd_Type) = E_Anonymous_Access_Type
then
if Is_Itype (Opnd_Type) then
-- Implicit conversions aren't allowed for objects of an
-- anonymous access type, since such objects have nonstatic
-- levels in Ada 2012.
if Nkind (Associated_Node_For_Itype (Opnd_Type)) =
N_Object_Declaration
then
Conversion_Error_N
("implicit conversion of stand-alone anonymous "
& "access object not allowed", Operand);
return False;
-- Implicit conversions aren't allowed for anonymous access
-- parameters. We exclude anonymous access results as well
-- as universal_access "=".
elsif not Is_Local_Anonymous_Access (Opnd_Type)
and then Nkind (Associated_Node_For_Itype (Opnd_Type)) in
N_Function_Specification |
N_Procedure_Specification
and then Nkind (Parent (N)) not in N_Op_Eq | N_Op_Ne
then
Conversion_Error_N
("implicit conversion of anonymous access parameter "
& "not allowed", Operand);
return False;
-- Detect access discriminant values that are illegal
-- implicit anonymous-to-named access conversion operands.
elsif Is_Discrim_Of_Bad_Access_Conversion_Argument (Operand)
then
Conversion_Error_N
("implicit conversion of anonymous access value "
& "not allowed", Operand);
return False;
-- In other cases, the level of the operand's type must be
-- statically less deep than that of the target type, else
-- implicit conversion is disallowed (by RM12-8.6(27.1/3)).
elsif Type_Access_Level (Opnd_Type) >
Deepest_Type_Access_Level (Target_Type)
then
Conversion_Error_N
("implicit conversion of anonymous access value "
& "violates accessibility", Operand);
return False;
end if;
end if;
-- Check if the operand is deeper than the target type, taking
-- care to avoid the case where we are converting a result of a
-- function returning an anonymous access type since the "master
-- of the call" would be target type of the conversion unless
-- the target type is anonymous access as well - see RM 3.10.2
-- (10.3/3).
elsif Type_Access_Level (Opnd_Type) >
Deepest_Type_Access_Level (Target_Type)
and then (Nkind (Associated_Node_For_Itype (Opnd_Type)) /=
N_Function_Specification
or else Ekind (Target_Type) in
Anonymous_Access_Kind)
then
-- In an instance, this is a run-time check, but one we know
-- will fail, so generate an appropriate warning. The raise
-- will be generated by Expand_N_Type_Conversion.
if In_Instance_Body then
Error_Msg_Warn := SPARK_Mode /= On;
Conversion_Error_N
("cannot convert local pointer to non-local access type<<",
Operand);
Conversion_Error_N ("\Program_Error [<<", Operand);
-- If not in an instance body, this is a real error
else
-- Avoid generation of spurious error message
if not Error_Posted (N) then
Conversion_Error_N
("cannot convert local pointer to non-local access type",
Operand);
end if;
return False;
end if;
-- Special accessibility checks are needed in the case of access
-- discriminants declared for a limited type.
elsif Ekind (Opnd_Type) = E_Anonymous_Access_Type
and then not Is_Local_Anonymous_Access (Opnd_Type)
then
-- When the operand is a selected access discriminant the check
-- needs to be made against the level of the object denoted by
-- the prefix of the selected name (Object_Access_Level handles
-- checking the prefix of the operand for this case).
if Nkind (Operand) = N_Selected_Component
and then Object_Access_Level (Operand) >
Deepest_Type_Access_Level (Target_Type)
then
-- In an instance, this is a run-time check, but one we know
-- will fail, so generate an appropriate warning. The raise
-- will be generated by Expand_N_Type_Conversion.
if In_Instance_Body then
Error_Msg_Warn := SPARK_Mode /= On;
Conversion_Error_N
("cannot convert access discriminant to non-local "
& "access type<<", Operand);
Conversion_Error_N ("\Program_Error [<<", Operand);
-- If not in an instance body, this is a real error
else
Conversion_Error_N
("cannot convert access discriminant to non-local "
& "access type", Operand);
return False;
end if;
end if;
-- The case of a reference to an access discriminant from
-- within a limited type declaration (which will appear as
-- a discriminal) is always illegal because the level of the
-- discriminant is considered to be deeper than any (nameable)
-- access type.
if Is_Entity_Name (Operand)
and then
Ekind (Entity (Operand)) in E_In_Parameter | E_Constant
and then Present (Discriminal_Link (Entity (Operand)))
then
Conversion_Error_N
("discriminant has deeper accessibility level than target",
Operand);
return False;
end if;
end if;
end if;
-- In the presence of limited_with clauses we have to use nonlimited
-- views, if available.
Check_Limited : declare
function Full_Designated_Type (T : Entity_Id) return Entity_Id;
-- Helper function to handle limited views
--------------------------
-- Full_Designated_Type --
--------------------------
function Full_Designated_Type (T : Entity_Id) return Entity_Id is
Desig : constant Entity_Id := Designated_Type (T);
begin
-- Handle the limited view of a type
if From_Limited_With (Desig)
and then Has_Non_Limited_View (Desig)
then
return Available_View (Desig);
else
return Desig;
end if;
end Full_Designated_Type;
-- Local Declarations
Target : constant Entity_Id := Full_Designated_Type (Target_Type);
Opnd : constant Entity_Id := Full_Designated_Type (Opnd_Type);
Same_Base : constant Boolean :=
Base_Type (Target) = Base_Type (Opnd);
-- Start of processing for Check_Limited
begin
if Is_Tagged_Type (Target) then
return Valid_Tagged_Conversion (Target, Opnd);
else
if not Same_Base then
Conversion_Error_NE
("target designated type not compatible with }",
N, Base_Type (Opnd));
return False;
-- Ada 2005 AI-384: legality rule is symmetric in both
-- designated types. The conversion is legal (with possible
-- constraint check) if either designated type is
-- unconstrained.
elsif Subtypes_Statically_Match (Target, Opnd)
or else
(Has_Discriminants (Target)
and then
(not Is_Constrained (Opnd)
or else not Is_Constrained (Target)))
then
-- Special case, if Value_Size has been used to make the
-- sizes different, the conversion is not allowed even
-- though the subtypes statically match.
if Known_Static_RM_Size (Target)
and then Known_Static_RM_Size (Opnd)
and then RM_Size (Target) /= RM_Size (Opnd)
then
Conversion_Error_NE
("target designated subtype not compatible with }",
N, Opnd);
Conversion_Error_NE
("\because sizes of the two designated subtypes differ",
N, Opnd);
return False;
-- Normal case where conversion is allowed
else
return True;
end if;
else
Error_Msg_NE
("target designated subtype not compatible with }",
N, Opnd);
return False;
end if;
end if;
end Check_Limited;
-- Access to subprogram types. If the operand is an access parameter,
-- the type has a deeper accessibility that any master, and cannot be
-- assigned. We must make an exception if the conversion is part of an
-- assignment and the target is the return object of an extended return
-- statement, because in that case the accessibility check takes place
-- after the return.
elsif Is_Access_Subprogram_Type (Target_Type)
-- Note: this test of Opnd_Type is there to prevent entering this
-- branch in the case of a remote access to subprogram type, which
-- is internally represented as an E_Record_Type.
and then Is_Access_Type (Opnd_Type)
then
if Ekind (Base_Type (Opnd_Type)) = E_Anonymous_Access_Subprogram_Type
and then Is_Entity_Name (Operand)
and then Ekind (Entity (Operand)) = E_In_Parameter
and then
(Nkind (Parent (N)) /= N_Assignment_Statement
or else not Is_Entity_Name (Name (Parent (N)))
or else not Is_Return_Object (Entity (Name (Parent (N)))))
then
Conversion_Error_N
("illegal attempt to store anonymous access to subprogram",
Operand);
Conversion_Error_N
("\value has deeper accessibility than any master "
& "(RM 3.10.2 (13))",
Operand);
Error_Msg_NE
("\use named access type for& instead of access parameter",
Operand, Entity (Operand));
end if;
-- Check that the designated types are subtype conformant
Check_Subtype_Conformant (New_Id => Designated_Type (Target_Type),
Old_Id => Designated_Type (Opnd_Type),
Err_Loc => N);
-- Check the static accessibility rule of 4.6(20)
if Type_Access_Level (Opnd_Type) >
Deepest_Type_Access_Level (Target_Type)
then
Conversion_Error_N
("operand type has deeper accessibility level than target",
Operand);
-- Check that if the operand type is declared in a generic body,
-- then the target type must be declared within that same body
-- (enforces last sentence of 4.6(20)).
elsif Present (Enclosing_Generic_Body (Opnd_Type)) then
declare
O_Gen : constant Node_Id :=
Enclosing_Generic_Body (Opnd_Type);
T_Gen : Node_Id;
begin
T_Gen := Enclosing_Generic_Body (Target_Type);
while Present (T_Gen) and then T_Gen /= O_Gen loop
T_Gen := Enclosing_Generic_Body (T_Gen);
end loop;
if T_Gen /= O_Gen then
Conversion_Error_N
("target type must be declared in same generic body "
& "as operand type", N);
end if;
end;
end if;
return True;
-- Remote access to subprogram types
elsif Is_Remote_Access_To_Subprogram_Type (Target_Type)
and then Is_Remote_Access_To_Subprogram_Type (Opnd_Type)
then
-- It is valid to convert from one RAS type to another provided
-- that their specification statically match.
-- Note: at this point, remote access to subprogram types have been
-- expanded to their E_Record_Type representation, and we need to
-- go back to the original access type definition using the
-- Corresponding_Remote_Type attribute in order to check that the
-- designated profiles match.
pragma Assert (Ekind (Target_Type) = E_Record_Type);
pragma Assert (Ekind (Opnd_Type) = E_Record_Type);
Check_Subtype_Conformant
(New_Id =>
Designated_Type (Corresponding_Remote_Type (Target_Type)),
Old_Id =>
Designated_Type (Corresponding_Remote_Type (Opnd_Type)),
Err_Loc =>
N);
return True;
-- If it was legal in the generic, it's legal in the instance
elsif In_Instance_Body then
return True;
-- If both are tagged types, check legality of view conversions
elsif Is_Tagged_Type (Target_Type)
and then
Is_Tagged_Type (Opnd_Type)
then
return Valid_Tagged_Conversion (Target_Type, Opnd_Type);
-- Types derived from the same root type are convertible
elsif Root_Type (Target_Type) = Root_Type (Opnd_Type) then
return True;
-- In an instance or an inlined body, there may be inconsistent views of
-- the same type, or of types derived from a common root.
elsif (In_Instance or In_Inlined_Body)
and then
Root_Type (Underlying_Type (Target_Type)) =
Root_Type (Underlying_Type (Opnd_Type))
then
return True;
-- Special check for common access type error case
elsif Ekind (Target_Type) = E_Access_Type
and then Is_Access_Type (Opnd_Type)
then
Conversion_Error_N ("target type must be general access type!", N);
Conversion_Error_NE -- CODEFIX
("add ALL to }!", N, Target_Type);
return False;
-- Here we have a real conversion error
else
-- Check for missing regular with_clause when only a limited view of
-- target is available.
if From_Limited_With (Opnd_Type) and then In_Package_Body then
Conversion_Error_NE
("invalid conversion, not compatible with limited view of }",
N, Opnd_Type);
Conversion_Error_NE
("\add with_clause for& to current unit!", N, Scope (Opnd_Type));
elsif Is_Access_Type (Opnd_Type)
and then From_Limited_With (Designated_Type (Opnd_Type))
and then In_Package_Body
then
Conversion_Error_NE
("invalid conversion, not compatible with }", N, Opnd_Type);
Conversion_Error_NE
("\add with_clause for& to current unit!",
N, Scope (Designated_Type (Opnd_Type)));
else
Conversion_Error_NE
("invalid conversion, not compatible with }", N, Opnd_Type);
end if;
return False;
end if;
end Valid_Conversion;
end Sem_Res;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
with Definitions; use Definitions;
package Display is
subtype history_origin is String (1 .. 45);
subtype history_elapsed is String (1 .. 8);
subtype history_action is String (1 .. 8);
subtype fivelong is String (1 .. 5);
subtype fld_phase is String (1 .. 12);
subtype fld_origin is String (1 .. 40);
subtype fld_lines is String (1 .. 7);
subtype fld_slavid is String (1 .. 2);
type history_rec is
record
id : builders;
slavid : String (1 .. 2);
run_elapsed : history_elapsed;
action : history_action;
pkg_elapsed : history_elapsed;
origin : history_origin;
established : Boolean := False;
end record;
type summary_rec is
record
Initially : Natural;
Built : Natural;
Failed : Natural;
Ignored : Natural;
Skipped : Natural;
elapsed : history_elapsed;
impulse : Natural;
pkg_hour : Natural;
load : Float;
swap : Float;
end record;
type builder_rec is
record
id : builders;
shutdown : Boolean;
idle : Boolean;
slavid : fld_slavid;
Elapsed : history_elapsed;
LLines : fld_lines;
phase : fld_phase;
origin : fld_origin;
end record;
action_shutdown : constant history_action := "shutdown";
action_skipped : constant history_action := "skipped ";
action_ignored : constant history_action := "ignored ";
action_success : constant history_action := "success ";
action_failure : constant history_action := "failure ";
-- Insert history as builder finishes (shutdown, success, failure);
procedure insert_history (HR : history_rec);
-- Expose helper function that formats float values for www report
function fmtpc (f : Float; percent : Boolean) return fivelong;
-- Expose helper function that formats load values for www report
function fmtload (f : Float) return fivelong;
private
type cyclic_range is range 1 .. 50;
type dim_history is array (cyclic_range) of history_rec;
history : dim_history;
history_arrow : cyclic_range := cyclic_range'Last;
end Display;
|
private
with lumen.Window;
package gel.Window.lumen
--
-- Provides a window which uses 'Lumen' as the backend.
--
is
type Item is new gel.Window.item with private;
type View is access all Item'Class;
---------
--- Forge
--
procedure define (Self : in View; Title : in String;
Width : in Natural;
Height : in Natural);
overriding
procedure destroy (Self : in out Item);
package Forge
is
function new_Window (Title : in String;
Width : in Natural;
Height : in Natural) return Window.lumen.view;
end Forge;
--------------
--- Attributes
--
-- Nil.
--------------
--- Operations
--
overriding
procedure emit_Events (Self : in out Item);
overriding
procedure enable_GL (Self : in Item);
overriding
procedure disable_GL (Self : in Item);
overriding
procedure swap_GL (Self : in out Item);
private
type Item is new gel.Window.item with
record
Window_handle : standard.lumen.Window.Window_handle;
end record;
end gel.Window.lumen;
|
-- with Ada.Containers.Vectors;
-- with Ada.Text_IO;
with Ada.Long_Long_Integer_Text_IO;
with Ada.Strings;
with Ada.Strings.Bounded;
with Ada.Containers; use Ada.Containers;
-- Note that this package currently only handles positive numbers.
package body BigInteger is
use BigInteger.Int_Vector;
-- Sadly we can't use this in our type because the compiler doesn't support
-- modular types greater than 2**32. We have chosen a power of ten for now
-- because it allows us to give a base 10 printed representation without
-- needing to implement division.
Base : constant Long_Long_Integer := 1_000_000_000_000_000_000;
-- Used in multiplication to split the number into two halves
Half_Base : constant Long_Long_Integer := 1_000_000_000;
function Create(l : in Long_Long_Integer) return BigInt is
bi : BigInt;
num : Long_Long_Integer := l;
begin
-- The given Long_Long_Integer can be larger than our base, so we need
-- to normalize it.
if num >= Base then
bi.bits.append(num mod Base);
num := num / Base;
end if;
bi.bits.append(num);
return bi;
end Create;
function Create(s : in String) return BigInt is
bi : BigInt := Create(0);
multiplier : BigInt := Create(1);
begin
for index in reverse s'Range loop
declare
c : constant Character := s(index);
begin
case c is
when '0' .. '9' =>
declare
value : constant Long_Long_Integer := Character'Pos(c) - Character'Pos('0');
begin
bi := bi + multiplier * Create(value);
if index > 0 then
multiplier := multiplier * Create(10);
end if;
end;
when others =>
null;
end case;
end;
end loop;
return bi;
end Create;
function "+" (Left, Right: in BigInt) return BigInt is
result : BigInt;
carry : Long_Long_Integer := 0;
begin
-- Normalize the input such that |left.bits| >= |right.bits|
if Right.bits.Length > Left.bits.Length then
return Right + Left;
end if;
result.bits := Int_Vector.Empty_Vector;
result.negative := False;
-- Sum all the bits that the numbers have in common.
for index in 1 .. Integer(Right.bits.Length) loop
carry := carry + Left.bits.Element(index) + Right.bits.Element(index);
if carry >= Base then
result.bits.Append(carry - Base);
carry := 1;
else
result.bits.Append(carry);
carry := 0;
end if;
end loop;
-- Append all the bits that the left number has that the right number
-- does not (remembering to continue the carry)
for index in Integer(Right.bits.Length + 1) .. Integer(Left.bits.Length) loop
carry := carry + Left.bits.Element(index);
if carry >= Base then
result.bits.append(carry - Base);
carry := 1;
else
result.bits.append(carry);
carry := 0;
end if;
end loop;
-- Finally remember to add an extra '1' to the result if we ended up with
-- a carry bit.
if carry /= 0 then
result.bits.append(carry);
end if;
return result;
end "+";
function "-" (Left, Right: in BigInt) return BigInt is
result : BigInt;
carry_in : Long_Long_Integer := 0;
begin
-- Currently always assuming |left| >= |right|
result.bits := Int_Vector.Empty_Vector;
result.negative := False;
-- Subtract all the bits they have in common
for index in 1 .. Integer(Right.bits.Length) loop
carry_in := Left.bits.Element(index) - Right.bits.Element(index) - carry_in;
if carry_in < 0 then
result.bits.Append(Base + carry_in);
carry_in := 1;
else
result.bits.Append(carry_in);
carry_in := 0;
end if;
end loop;
-- Subtract the carry from any remaining bits in Left as neccessary
for index in Integer(Right.bits.Length + 1) .. Integer(Left.bits.Length) loop
carry_in := Left.bits.Element(index) - carry_in;
if carry_in < 0 then
result.bits.Append(Base + carry_in);
carry_in := 1;
else
result.bits.Append(carry_in);
carry_in := 0;
end if;
end loop;
-- Handle left over carry bit
-- Todo: We don't handle this right now
return result;
end "-";
function "*" (Left, Right: in BigInt) return BigInt is
result : BigInt;
Intermediate : Long_Long_Integer;
Temporary : Long_Long_Integer;
carry : Long_Long_Integer := 0;
double_carry : Boolean;
begin
-- Normalize the input such that |left.bits| >= |right.bits|
if Right.bits.Length > Left.bits.Length then
return Right * Left;
end if;
result.bits := Int_Vector.Empty_Vector;
result.negative := False;
-- Multiplication is done by splitting the Left and Right base units into
-- two half-base units representing the upper and lower bits of the
-- number. These portions are then multiplied pairwise
for left_index in 1 .. Integer(Left.bits.Length) loop
if Left.bits.Element(left_index) = 0 then
goto Next_Left;
end if;
declare
Left_Lower : constant Long_Long_Integer := Left.bits.Element(left_index) mod Half_Base;
Left_Upper : constant Long_Long_Integer := Left.bits.Element(left_index) / Half_Base;
begin
for right_index in 1 .. Integer(Right.bits.Length) loop
if Right.bits.Element(right_index) = 0 then
goto Next_Right;
end if;
declare
Right_Lower : constant Long_Long_Integer := Right.bits.Element(right_index) mod Half_Base;
Right_Upper : constant Long_Long_Integer := Right.bits.Element(right_index) / Half_Base;
result_index : constant Integer := left_index + right_index - 1;
begin
double_carry := False;
if Integer(result.bits.Length) > result_index then
carry := result.bits.Element(result_index + 1);
intermediate := result.bits.Element(result_index);
elsif Integer(result.bits.Length) >= result_index then
carry := 0;
intermediate := result.bits.Element(result_index);
else
carry := 0;
intermediate := 0;
while Integer(result.bits.Length) < result_index loop
result.bits.Append(0);
end loop;
end if;
-- Left_Lower * Right_Lower
Intermediate := Intermediate + Left_Lower * Right_Lower;
if Intermediate >= Base then
Intermediate := Intermediate - Base;
carry := carry + 1;
if carry = Base then
carry := 0;
double_carry := True;
end if;
end if;
-- Left_Lower * Right_Upper
Temporary := Left_Lower * Right_Upper;
if Temporary >= Half_Base then
Intermediate := Intermediate + (Temporary mod Half_Base) * Half_Base;
carry := carry + (Temporary / Half_Base);
if carry >= Base then
carry := carry - Base;
double_carry := True;
end if;
else
Intermediate := Intermediate + Temporary * Half_Base;
end if;
if Intermediate >= Base then
Intermediate := Intermediate - Base;
carry := carry + 1;
if carry = Base then
carry := 0;
double_carry := True;
end if;
end if;
-- Left_Upper * Right_Lower
Temporary := Left_Upper * Right_Lower;
if Temporary >= Half_Base then
Intermediate := Intermediate + (Temporary mod Half_Base) * Half_Base;
carry := carry + (Temporary / Half_Base);
if carry >= Base then
carry := carry - Base;
double_carry := True;
end if;
else
Intermediate := Intermediate + Temporary * Half_Base;
end if;
if Intermediate >= Base then
Intermediate := Intermediate - Base;
carry := carry + 1;
if carry = Base then
carry := 0;
double_carry := True;
end if;
end if;
result.bits.Replace_Element(result_index, Intermediate);
-- Left_Upper * Right_Upper
carry := carry + Left_Upper * Right_Upper;
if double_carry then
if Integer(result.bits.Length) >= result_index + 2 then
result.bits.Replace_Element(result_index + 2,
result.bits.Element(result_index + 2) + 1);
else
result.bits.Append(1);
end if;
-- If we have a double carry, we know we had at least
-- result_index + 1 elements in our vector because
-- otherwise we wouldn't have overflown the carry capacity.
result.bits.Replace_Element(result_index + 1, carry);
elsif carry > 0 then
if Integer(result.bits.Length ) > result_index then
result.bits.Replace_Element(result_index + 1, carry);
else
result.bits.Append(carry);
end if;
end if;
end;
<<Next_Right>>
null;
end loop;
end;
<<Next_Left>>
null;
end loop;
return result;
end "*";
function "**"(Left : in BigInt; Right: in Natural) return BigInt is
result : BigInt := Create(1);
current_base : BigInt := Left;
current_exponent : Long_Long_Integer := Long_Long_Integer(Right);
begin
while current_exponent > 0 loop
if current_exponent mod 2 = 0 then
current_base := current_base * current_base;
current_exponent := current_exponent / 2;
else
result := result * current_base;
current_exponent := current_exponent - 1;
end if;
end loop;
return result;
end;
function Magnitude(bi : in BigInt) return Positive is
function Log10(n : Long_Long_Integer) return Positive is
begin
if n >= 100_000_000_000_000_000 then
return 18;
elsif n >= 10_000_000_000_000_000 then
return 17;
elsif n >= 1_000_000_000_000_000 then
return 16;
elsif n >= 100_000_000_000_000 then
return 15;
elsif n >= 10_000_000_000_000 then
return 14;
elsif n >= 1_000_000_000_000 then
return 13;
elsif n >= 100_000_000_000 then
return 12;
elsif n >= 10_000_000_000 then
return 11;
elsif n >= 1_000_000_000 then
return 10;
elsif n >= 100_000_000 then
return 9;
elsif n >= 10_000_000 then
return 8;
elsif n >= 1_000_000 then
return 7;
elsif n >= 100_000 then
return 6;
elsif n >= 10_000 then
return 5;
elsif n >= 1_000 then
return 4;
elsif n >= 100 then
return 3;
elsif n >= 10 then
return 2;
else
return 1;
end if;
end Log10;
mag : constant Positive := Log10(bi.bits.Last_Element) + Natural(bi.bits.Length - 1) * 18;
begin
return mag;
end Magnitude;
function ToString(bi : in BigInt) return String is
begin
if bi.bits.Length > 0 then
declare
package Bounded is new Ada.Strings.Bounded.Generic_Bounded_Length(Integer(bi.bits.Length) * 18);
bs : Bounded.Bounded_String := Bounded.Null_Bounded_String;
temporary : String (1 .. 18);
begin
Ada.Long_Long_Integer_Text_IO.Put(temporary, bi.bits.Element(Integer(bi.bits.Length)));
Bounded.Append(bs, temporary);
Bounded.Trim(bs, Ada.Strings.Left);
for index in reverse 1 .. Integer(bi.bits.Length - 1) loop
Ada.Long_Long_Integer_Text_IO.Put(temporary, bi.bits.Element(index));
for ch_in in temporary'Range loop
if temporary(ch_in) = ' ' then
temporary(ch_in) := '0';
else
exit;
end if;
end loop;
Bounded.Append(bs, temporary);
end loop;
return Bounded.To_String(bs);
end;
else
return "0";
end if;
end;
end BigInteger;
|
with Ada.Text_IO; use Ada.Text_IO;
procedure param_out is
procedure test_2 (nb : in out Integer) is
begin
nb := 789;
end test_2;
ma_var : Integer := 123;
begin
Put_Line("avant : " & Integer'Image(ma_var));
test_2(ma_var);
Put_Line("après : " & Integer'Image(ma_var));
end param_out;
|
-- This spec has been automatically generated from STM32F303xE.svd
pragma Restrictions (No_Elaboration_Code);
pragma Ada_2012;
pragma Style_Checks (Off);
with System;
package STM32_SVD.OPAMP is
pragma Preelaborate;
---------------
-- Registers --
---------------
subtype OPAMP1_CR_OPAMP1_EN_Field is STM32_SVD.Bit;
subtype OPAMP1_CR_FORCE_VP_Field is STM32_SVD.Bit;
subtype OPAMP1_CR_VP_SEL_Field is STM32_SVD.UInt2;
subtype OPAMP1_CR_VM_SEL_Field is STM32_SVD.UInt2;
subtype OPAMP1_CR_TCM_EN_Field is STM32_SVD.Bit;
subtype OPAMP1_CR_VMS_SEL_Field is STM32_SVD.Bit;
subtype OPAMP1_CR_VPS_SEL_Field is STM32_SVD.UInt2;
subtype OPAMP1_CR_CALON_Field is STM32_SVD.Bit;
subtype OPAMP1_CR_CALSEL_Field is STM32_SVD.UInt2;
subtype OPAMP1_CR_PGA_GAIN_Field is STM32_SVD.UInt4;
subtype OPAMP1_CR_USER_TRIM_Field is STM32_SVD.Bit;
subtype OPAMP1_CR_TRIMOFFSETP_Field is STM32_SVD.UInt5;
subtype OPAMP1_CR_TRIMOFFSETN_Field is STM32_SVD.UInt5;
subtype OPAMP1_CR_TSTREF_Field is STM32_SVD.Bit;
subtype OPAMP1_CR_OUTCAL_Field is STM32_SVD.Bit;
subtype OPAMP1_CR_LOCK_Field is STM32_SVD.Bit;
-- OPAMP1 control register
type OPAMP1_CR_Register is record
-- OPAMP1 enable
OPAMP1_EN : OPAMP1_CR_OPAMP1_EN_Field := 16#0#;
-- FORCE_VP
FORCE_VP : OPAMP1_CR_FORCE_VP_Field := 16#0#;
-- OPAMP1 Non inverting input selection
VP_SEL : OPAMP1_CR_VP_SEL_Field := 16#0#;
-- unspecified
Reserved_4_4 : STM32_SVD.Bit := 16#0#;
-- OPAMP1 inverting input selection
VM_SEL : OPAMP1_CR_VM_SEL_Field := 16#0#;
-- Timer controlled Mux mode enable
TCM_EN : OPAMP1_CR_TCM_EN_Field := 16#0#;
-- OPAMP1 inverting input secondary selection
VMS_SEL : OPAMP1_CR_VMS_SEL_Field := 16#0#;
-- OPAMP1 Non inverting input secondary selection
VPS_SEL : OPAMP1_CR_VPS_SEL_Field := 16#0#;
-- Calibration mode enable
CALON : OPAMP1_CR_CALON_Field := 16#0#;
-- Calibration selection
CALSEL : OPAMP1_CR_CALSEL_Field := 16#0#;
-- Gain in PGA mode
PGA_GAIN : OPAMP1_CR_PGA_GAIN_Field := 16#0#;
-- User trimming enable
USER_TRIM : OPAMP1_CR_USER_TRIM_Field := 16#0#;
-- Offset trimming value (PMOS)
TRIMOFFSETP : OPAMP1_CR_TRIMOFFSETP_Field := 16#0#;
-- Offset trimming value (NMOS)
TRIMOFFSETN : OPAMP1_CR_TRIMOFFSETN_Field := 16#0#;
-- TSTREF
TSTREF : OPAMP1_CR_TSTREF_Field := 16#0#;
-- Read-only. OPAMP 1 ouput status flag
OUTCAL : OPAMP1_CR_OUTCAL_Field := 16#0#;
-- OPAMP 1 lock
LOCK : OPAMP1_CR_LOCK_Field := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for OPAMP1_CR_Register use record
OPAMP1_EN at 0 range 0 .. 0;
FORCE_VP at 0 range 1 .. 1;
VP_SEL at 0 range 2 .. 3;
Reserved_4_4 at 0 range 4 .. 4;
VM_SEL at 0 range 5 .. 6;
TCM_EN at 0 range 7 .. 7;
VMS_SEL at 0 range 8 .. 8;
VPS_SEL at 0 range 9 .. 10;
CALON at 0 range 11 .. 11;
CALSEL at 0 range 12 .. 13;
PGA_GAIN at 0 range 14 .. 17;
USER_TRIM at 0 range 18 .. 18;
TRIMOFFSETP at 0 range 19 .. 23;
TRIMOFFSETN at 0 range 24 .. 28;
TSTREF at 0 range 29 .. 29;
OUTCAL at 0 range 30 .. 30;
LOCK at 0 range 31 .. 31;
end record;
subtype OPAMP2_CR_OPAMP2EN_Field is STM32_SVD.Bit;
subtype OPAMP2_CR_FORCE_VP_Field is STM32_SVD.Bit;
subtype OPAMP2_CR_VP_SEL_Field is STM32_SVD.UInt2;
subtype OPAMP2_CR_VM_SEL_Field is STM32_SVD.UInt2;
subtype OPAMP2_CR_TCM_EN_Field is STM32_SVD.Bit;
subtype OPAMP2_CR_VMS_SEL_Field is STM32_SVD.Bit;
subtype OPAMP2_CR_VPS_SEL_Field is STM32_SVD.UInt2;
subtype OPAMP2_CR_CALON_Field is STM32_SVD.Bit;
subtype OPAMP2_CR_CAL_SEL_Field is STM32_SVD.UInt2;
subtype OPAMP2_CR_PGA_GAIN_Field is STM32_SVD.UInt4;
subtype OPAMP2_CR_USER_TRIM_Field is STM32_SVD.Bit;
subtype OPAMP2_CR_TRIMOFFSETP_Field is STM32_SVD.UInt5;
subtype OPAMP2_CR_TRIMOFFSETN_Field is STM32_SVD.UInt5;
subtype OPAMP2_CR_TSTREF_Field is STM32_SVD.Bit;
subtype OPAMP2_CR_OUTCAL_Field is STM32_SVD.Bit;
subtype OPAMP2_CR_LOCK_Field is STM32_SVD.Bit;
-- OPAMP2 control register
type OPAMP2_CR_Register is record
-- OPAMP2 enable
OPAMP2EN : OPAMP2_CR_OPAMP2EN_Field := 16#0#;
-- FORCE_VP
FORCE_VP : OPAMP2_CR_FORCE_VP_Field := 16#0#;
-- OPAMP2 Non inverting input selection
VP_SEL : OPAMP2_CR_VP_SEL_Field := 16#0#;
-- unspecified
Reserved_4_4 : STM32_SVD.Bit := 16#0#;
-- OPAMP2 inverting input selection
VM_SEL : OPAMP2_CR_VM_SEL_Field := 16#0#;
-- Timer controlled Mux mode enable
TCM_EN : OPAMP2_CR_TCM_EN_Field := 16#0#;
-- OPAMP2 inverting input secondary selection
VMS_SEL : OPAMP2_CR_VMS_SEL_Field := 16#0#;
-- OPAMP2 Non inverting input secondary selection
VPS_SEL : OPAMP2_CR_VPS_SEL_Field := 16#0#;
-- Calibration mode enable
CALON : OPAMP2_CR_CALON_Field := 16#0#;
-- Calibration selection
CAL_SEL : OPAMP2_CR_CAL_SEL_Field := 16#0#;
-- Gain in PGA mode
PGA_GAIN : OPAMP2_CR_PGA_GAIN_Field := 16#0#;
-- User trimming enable
USER_TRIM : OPAMP2_CR_USER_TRIM_Field := 16#0#;
-- Offset trimming value (PMOS)
TRIMOFFSETP : OPAMP2_CR_TRIMOFFSETP_Field := 16#0#;
-- Offset trimming value (NMOS)
TRIMOFFSETN : OPAMP2_CR_TRIMOFFSETN_Field := 16#0#;
-- TSTREF
TSTREF : OPAMP2_CR_TSTREF_Field := 16#0#;
-- Read-only. OPAMP 2 ouput status flag
OUTCAL : OPAMP2_CR_OUTCAL_Field := 16#0#;
-- OPAMP 2 lock
LOCK : OPAMP2_CR_LOCK_Field := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for OPAMP2_CR_Register use record
OPAMP2EN at 0 range 0 .. 0;
FORCE_VP at 0 range 1 .. 1;
VP_SEL at 0 range 2 .. 3;
Reserved_4_4 at 0 range 4 .. 4;
VM_SEL at 0 range 5 .. 6;
TCM_EN at 0 range 7 .. 7;
VMS_SEL at 0 range 8 .. 8;
VPS_SEL at 0 range 9 .. 10;
CALON at 0 range 11 .. 11;
CAL_SEL at 0 range 12 .. 13;
PGA_GAIN at 0 range 14 .. 17;
USER_TRIM at 0 range 18 .. 18;
TRIMOFFSETP at 0 range 19 .. 23;
TRIMOFFSETN at 0 range 24 .. 28;
TSTREF at 0 range 29 .. 29;
OUTCAL at 0 range 30 .. 30;
LOCK at 0 range 31 .. 31;
end record;
subtype OPAMP3_CR_OPAMP3EN_Field is STM32_SVD.Bit;
subtype OPAMP3_CR_FORCE_VP_Field is STM32_SVD.Bit;
subtype OPAMP3_CR_VP_SEL_Field is STM32_SVD.UInt2;
subtype OPAMP3_CR_VM_SEL_Field is STM32_SVD.UInt2;
subtype OPAMP3_CR_TCM_EN_Field is STM32_SVD.Bit;
subtype OPAMP3_CR_VMS_SEL_Field is STM32_SVD.Bit;
subtype OPAMP3_CR_VPS_SEL_Field is STM32_SVD.UInt2;
subtype OPAMP3_CR_CALON_Field is STM32_SVD.Bit;
subtype OPAMP3_CR_CALSEL_Field is STM32_SVD.UInt2;
subtype OPAMP3_CR_PGA_GAIN_Field is STM32_SVD.UInt4;
subtype OPAMP3_CR_USER_TRIM_Field is STM32_SVD.Bit;
subtype OPAMP3_CR_TRIMOFFSETP_Field is STM32_SVD.UInt5;
subtype OPAMP3_CR_TRIMOFFSETN_Field is STM32_SVD.UInt5;
subtype OPAMP3_CR_TSTREF_Field is STM32_SVD.Bit;
subtype OPAMP3_CR_OUTCAL_Field is STM32_SVD.Bit;
subtype OPAMP3_CR_LOCK_Field is STM32_SVD.Bit;
-- OPAMP3 control register
type OPAMP3_CR_Register is record
-- OPAMP3 enable
OPAMP3EN : OPAMP3_CR_OPAMP3EN_Field := 16#0#;
-- FORCE_VP
FORCE_VP : OPAMP3_CR_FORCE_VP_Field := 16#0#;
-- OPAMP3 Non inverting input selection
VP_SEL : OPAMP3_CR_VP_SEL_Field := 16#0#;
-- unspecified
Reserved_4_4 : STM32_SVD.Bit := 16#0#;
-- OPAMP3 inverting input selection
VM_SEL : OPAMP3_CR_VM_SEL_Field := 16#0#;
-- Timer controlled Mux mode enable
TCM_EN : OPAMP3_CR_TCM_EN_Field := 16#0#;
-- OPAMP3 inverting input secondary selection
VMS_SEL : OPAMP3_CR_VMS_SEL_Field := 16#0#;
-- OPAMP3 Non inverting input secondary selection
VPS_SEL : OPAMP3_CR_VPS_SEL_Field := 16#0#;
-- Calibration mode enable
CALON : OPAMP3_CR_CALON_Field := 16#0#;
-- Calibration selection
CALSEL : OPAMP3_CR_CALSEL_Field := 16#0#;
-- Gain in PGA mode
PGA_GAIN : OPAMP3_CR_PGA_GAIN_Field := 16#0#;
-- User trimming enable
USER_TRIM : OPAMP3_CR_USER_TRIM_Field := 16#0#;
-- Offset trimming value (PMOS)
TRIMOFFSETP : OPAMP3_CR_TRIMOFFSETP_Field := 16#0#;
-- Offset trimming value (NMOS)
TRIMOFFSETN : OPAMP3_CR_TRIMOFFSETN_Field := 16#0#;
-- TSTREF
TSTREF : OPAMP3_CR_TSTREF_Field := 16#0#;
-- Read-only. OPAMP 3 ouput status flag
OUTCAL : OPAMP3_CR_OUTCAL_Field := 16#0#;
-- OPAMP 3 lock
LOCK : OPAMP3_CR_LOCK_Field := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for OPAMP3_CR_Register use record
OPAMP3EN at 0 range 0 .. 0;
FORCE_VP at 0 range 1 .. 1;
VP_SEL at 0 range 2 .. 3;
Reserved_4_4 at 0 range 4 .. 4;
VM_SEL at 0 range 5 .. 6;
TCM_EN at 0 range 7 .. 7;
VMS_SEL at 0 range 8 .. 8;
VPS_SEL at 0 range 9 .. 10;
CALON at 0 range 11 .. 11;
CALSEL at 0 range 12 .. 13;
PGA_GAIN at 0 range 14 .. 17;
USER_TRIM at 0 range 18 .. 18;
TRIMOFFSETP at 0 range 19 .. 23;
TRIMOFFSETN at 0 range 24 .. 28;
TSTREF at 0 range 29 .. 29;
OUTCAL at 0 range 30 .. 30;
LOCK at 0 range 31 .. 31;
end record;
subtype OPAMP4_CR_OPAMP4EN_Field is STM32_SVD.Bit;
subtype OPAMP4_CR_FORCE_VP_Field is STM32_SVD.Bit;
subtype OPAMP4_CR_VP_SEL_Field is STM32_SVD.UInt2;
subtype OPAMP4_CR_VM_SEL_Field is STM32_SVD.UInt2;
subtype OPAMP4_CR_TCM_EN_Field is STM32_SVD.Bit;
subtype OPAMP4_CR_VMS_SEL_Field is STM32_SVD.Bit;
subtype OPAMP4_CR_VPS_SEL_Field is STM32_SVD.UInt2;
subtype OPAMP4_CR_CALON_Field is STM32_SVD.Bit;
subtype OPAMP4_CR_CALSEL_Field is STM32_SVD.UInt2;
subtype OPAMP4_CR_PGA_GAIN_Field is STM32_SVD.UInt4;
subtype OPAMP4_CR_USER_TRIM_Field is STM32_SVD.Bit;
subtype OPAMP4_CR_TRIMOFFSETP_Field is STM32_SVD.UInt5;
subtype OPAMP4_CR_TRIMOFFSETN_Field is STM32_SVD.UInt5;
subtype OPAMP4_CR_TSTREF_Field is STM32_SVD.Bit;
subtype OPAMP4_CR_OUTCAL_Field is STM32_SVD.Bit;
subtype OPAMP4_CR_LOCK_Field is STM32_SVD.Bit;
-- OPAMP4 control register
type OPAMP4_CR_Register is record
-- OPAMP4 enable
OPAMP4EN : OPAMP4_CR_OPAMP4EN_Field := 16#0#;
-- FORCE_VP
FORCE_VP : OPAMP4_CR_FORCE_VP_Field := 16#0#;
-- OPAMP4 Non inverting input selection
VP_SEL : OPAMP4_CR_VP_SEL_Field := 16#0#;
-- unspecified
Reserved_4_4 : STM32_SVD.Bit := 16#0#;
-- OPAMP4 inverting input selection
VM_SEL : OPAMP4_CR_VM_SEL_Field := 16#0#;
-- Timer controlled Mux mode enable
TCM_EN : OPAMP4_CR_TCM_EN_Field := 16#0#;
-- OPAMP4 inverting input secondary selection
VMS_SEL : OPAMP4_CR_VMS_SEL_Field := 16#0#;
-- OPAMP4 Non inverting input secondary selection
VPS_SEL : OPAMP4_CR_VPS_SEL_Field := 16#0#;
-- Calibration mode enable
CALON : OPAMP4_CR_CALON_Field := 16#0#;
-- Calibration selection
CALSEL : OPAMP4_CR_CALSEL_Field := 16#0#;
-- Gain in PGA mode
PGA_GAIN : OPAMP4_CR_PGA_GAIN_Field := 16#0#;
-- User trimming enable
USER_TRIM : OPAMP4_CR_USER_TRIM_Field := 16#0#;
-- Offset trimming value (PMOS)
TRIMOFFSETP : OPAMP4_CR_TRIMOFFSETP_Field := 16#0#;
-- Offset trimming value (NMOS)
TRIMOFFSETN : OPAMP4_CR_TRIMOFFSETN_Field := 16#0#;
-- TSTREF
TSTREF : OPAMP4_CR_TSTREF_Field := 16#0#;
-- Read-only. OPAMP 4 ouput status flag
OUTCAL : OPAMP4_CR_OUTCAL_Field := 16#0#;
-- OPAMP 4 lock
LOCK : OPAMP4_CR_LOCK_Field := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for OPAMP4_CR_Register use record
OPAMP4EN at 0 range 0 .. 0;
FORCE_VP at 0 range 1 .. 1;
VP_SEL at 0 range 2 .. 3;
Reserved_4_4 at 0 range 4 .. 4;
VM_SEL at 0 range 5 .. 6;
TCM_EN at 0 range 7 .. 7;
VMS_SEL at 0 range 8 .. 8;
VPS_SEL at 0 range 9 .. 10;
CALON at 0 range 11 .. 11;
CALSEL at 0 range 12 .. 13;
PGA_GAIN at 0 range 14 .. 17;
USER_TRIM at 0 range 18 .. 18;
TRIMOFFSETP at 0 range 19 .. 23;
TRIMOFFSETN at 0 range 24 .. 28;
TSTREF at 0 range 29 .. 29;
OUTCAL at 0 range 30 .. 30;
LOCK at 0 range 31 .. 31;
end record;
-----------------
-- Peripherals --
-----------------
-- Operational amplifier
type OPAMP_Peripheral is record
-- OPAMP1 control register
OPAMP1_CR : aliased OPAMP1_CR_Register;
-- OPAMP2 control register
OPAMP2_CR : aliased OPAMP2_CR_Register;
-- OPAMP3 control register
OPAMP3_CR : aliased OPAMP3_CR_Register;
-- OPAMP4 control register
OPAMP4_CR : aliased OPAMP4_CR_Register;
end record
with Volatile;
for OPAMP_Peripheral use record
OPAMP1_CR at 16#0# range 0 .. 31;
OPAMP2_CR at 16#4# range 0 .. 31;
OPAMP3_CR at 16#8# range 0 .. 31;
OPAMP4_CR at 16#C# range 0 .. 31;
end record;
-- Operational amplifier
OPAMP_Periph : aliased OPAMP_Peripheral
with Import, Address => System'To_Address (16#40010038#);
end STM32_SVD.OPAMP;
|
-- { dg-do compile }
-- { dg-options "-Os -g" }
with Opt7_Pkg;
package body Opt7 is
procedure Parse (Str : String;
Time_Type : out time_t;
Abs_Time : out Time;
Delt_Time : out Duration) is
Year : Year_Number;
Month : Month_Number;
Day : Day_Number;
Minute : Integer := 0;
Idx : Integer := Str'First;
Ch : Character := Str (Idx);
Current_Time : Time;
begin
if Ch = '-' then
Time_Type := Absolute_Time;
Current_Time := Clock;
Day := Ada.Calendar.Day (Current_Time);
Month := Ada.Calendar.Month (Current_Time);
Year := Ada.Calendar.Year (Current_Time);
else
Time_Type := Delta_Time;
end if;
while Ch in '0' .. '9' loop
Minute := Minute + Character'Pos (Ch);
Idx := Idx + 1;
Ch := Str (Idx);
end loop;
if Time_Type = Absolute_Time then
Abs_Time := Time_Of (Year, Month, Day, Day_Duration (1));
else
Delt_Time := Duration (Float (Minute));
end if;
exception
when others => Opt7_Pkg.My_Raise_Exception;
end;
end Opt7;
|
procedure prueba2 is
x:Integer := 0;
procedure Minimo2 () is
y:Integer;
function Minimo (a, b: Integer) return Integer is
yy:Integer;
begin
az := 12;
end Minimo;
begin
az := 12;
end Minimo2;
procedure Minimo4 () is
yt:Integer;
begin
az := 12;
end Minimo4;
begin
x := 1;
end prueba2; |
-----------------------------------------------------------------------
-- package body A_Legendre. Data structure for Associated Legendre Polynomials.
-- Copyright (C) 2018 Jonathan S. Parker
--
-- Permission to use, copy, modify, and/or distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---------------------------------------------------------------------------
with Factorial;
package body A_Legendre is
package F is new Factorial (Real); use F;
Zero : constant Real := +0.0;
Half : constant Real := +0.5;
One : constant Real := +1.0;
Two : constant Real := +2.0;
Log_base_e_of_2 : constant Real :=
+0.69314718055994530941723212145817656807550013436025525412068;
function X_Lower_Bound return Real is
begin
return -One;
end;
function X_Upper_Bound return Real is
begin
return One;
end;
-------------------
-- Log_of_1_plus --
-------------------
-- More accurate than using Log (1 + x) for Abs x << 1.
function Log_of_1_plus
(x : Real)
return Real
is
u : constant Real := One + x;
Sqrt_Eps : constant Real := Two ** (-Real'Machine_Mantissa / 2 - 6);
begin
if u <= Zero then
raise Constraint_Error;
end if;
-- Use Log(1+x) = x - x^2/2 + x^3/3 - ... = x*(1 - x/2 + x^2/3 ...)
-- So if x is somewhat smaller than Sqrt (Real'Epsilon) then 1 + x^3/3 = 1:
if Abs (u - One) < Sqrt_Eps then
return x - Half * x * x;
end if;
--return Log(u) * x / (u - One); -- more accurate? (u /= One; see above).
return Log(u);
end Log_of_1_plus;
-----------
-- Alpha --
-----------
-- Alpha (k, m, X) = X * (2*(m+k) - 1) / k
--
function Alpha (k : Base_Poly_ID; m : Real; X : Real) return Real is
Result : Real;
Real_k : constant Real := +Real (k);
Real_k_plus_m : constant Real := Real_k + m;
begin
if (m < Zero or k < 1) then raise Constraint_Error; end if;
Result := X * (Real_k_plus_m + Real_k_plus_m - One) / Real_k;
return Result;
end Alpha;
----------
-- Beta --
----------
-- Beta (k, m, X) = -(k + 2*m - 1) / k
--
function Beta (k : Base_Poly_ID; m : Real; X : Real) return Real is
Real_k : constant Real := Real (k);
begin
if (m < Zero or k < 1) then raise Constraint_Error; end if;
return -(Real_k + m + m - One) / Real_k;
end Beta;
---------
-- Q_0 --
---------
-- Q_0 (m, X) = (-1)**m * Sqrt(1-X*X)**m
--
function Q_0 (m : Real; X : Real) return Real is
Arg, Factor, Result : Real;
m_int : constant Integer := Integer (m); -- Important init.
begin
if m_int = 0 then return One ; end if;
if Abs (X) = One then return Zero ; end if;
if m_int < 0 then raise Constraint_Error; end if;
if Abs (X) > One then raise Constraint_Error; end if;
-- Result := (-Sqrt ((One - X) * (One + X))) ** m_int;
Arg := 0.5 * m * Log_of_1_plus(-X*X); -- Arg always < 0
if Abs (Arg) > 600.0 then -- Exp(-600.0) ~ 10^(-262)
Result := Zero;
else
-- Factor = (-1)**m_int:
if 2*(m_int/2) = m_int then
Factor := One;
else
Factor := -One;
end if;
Result := Factor * Exp (Arg);
end if;
return Result;
end Q_0;
-----------------
-- Poly_Weight --
-----------------
function Poly_Weight (X : Real) return Real is
begin
return One;
end;
--------------------------
-- Normalization_Factor --
--------------------------
--
-- Int (Q_k(m, X) * Q_k(m, X) * W(X))
-- = ((k+2*m)! / (k!*(2*m-1)!!**2)) / (k + m + 0.5)
--
-- Function should be multiplied by the inverse Sqrt of the above
-- quantity in order to normalize the Legendre Function generated by the
-- recurrance relation. The function returns the inverse Sqrt of the
-- above quantity.
--
-- 7!! = 7*5*3*1
-- (2*m-1)!! = (2m)!/(m!2^m) so we can (and should) use log_factorial
-- to do this.
--
-- Ratio = k! * (2*m-1)!!**2) * (k + m + 0.5) / (k+2*m)!
-- = k! * (2m)! * (2m)! * (k + m + 0.5) / [2^(2m) * m! * m! * (k+2*m)!]
--
-- Want Normalization_Factor to be the Sqrt (Ratio) of the above.
--
-- Perceptibly less accurate than alternative (see below), but
-- very safe and possibly faster.
--
function Normalization_Factor_0
(k : Base_Poly_ID;
m : Real)
return Real
is
Log_Ratio : Real := Zero;
m_int : constant Natural := Natural (m);
k_int : constant Natural := Natural (k);
begin
if (m_int < 0 or k < 0) then raise Constraint_Error; end if;
-- if m = 0, then Log_Ratio is already correctly set to 0.0.
if m_int > 0 then
-- leaving out the (k + m + 0.5) for now:
Log_Ratio := Log_Factorial (2*m_int) * Two - Log_Factorial (m_int) * Two;
Log_Ratio := Log_Ratio +
Log_Factorial (k_int)
- Log_Factorial (k_int + 2*m_int)
- Log_base_e_of_2 * m * Two;
end if;
return Sqrt (Real (k) + m + Half) * Exp (Half * Log_Ratio);
end Normalization_Factor_0;
-- Method is much less safe at high l, m ?
function Norm_more_accurate_but_Slower
(k : Base_Poly_ID;
m : Real)
return Real
is
Two_m_minus_1_plus_k, Two_m_minus_1 : Real;
Real_k : constant Real := +Real (k);
Real_k_plus_m : constant Real := Real_k + m;
Ratio : Real := One;
Result : Real := One;
m_int : constant Integer := Integer (m);
begin
if (m_int < 0 or k < 0) then raise Constraint_Error; end if;
-- Get 1 / Ratio = (2*m-1)!!**2 * k! / (2*m + k)!.
-- if m = 0, then Ratio is already 1.0.
for m_index in 1 .. m_int loop
Two_m_minus_1 := +Real (2 * m_index - 1);
Two_m_minus_1_plus_k := Two_m_minus_1 + Real_k;
Ratio := Ratio / Sqrt (Two_m_minus_1_plus_k*(Two_m_minus_1_plus_k + One));
Ratio := Ratio * Two_m_minus_1;
end loop;
Result := Ratio * Sqrt (Real_k_plus_m + Half);
return Result;
end Norm_more_accurate_but_Slower;
function Normalization_Factor
(k : Base_Poly_ID;
m : Real)
return Real
renames Norm_more_accurate_but_Slower;
end A_Legendre;
|
procedure Enumeration is
type MyColor is (Blue, Red, Green, Yellow);
for MyColor use (Blue => 11,
Red => 22,
Green => 33,
Yellow => 44);
type YourColor is (Blue, White, Red);
for YourColor use (0, 1, 2);
begin
null;
end Enumeration;
|
------------------------------------------------------------------------------
-- Copyright (c) 2017, 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.Comment_Cookies provides an object to store persitent --
-- information for comment forms. --
------------------------------------------------------------------------------
with Natools.S_Expressions.Atom_Refs;
with Natools.S_Expressions.Lockable;
private with Natools.Constant_Indefinite_Ordered_Maps;
package Natools.Web.Comment_Cookies is
pragma Preelaborate;
Cookie_Name : constant String := "c_info";
type Comment_Info is private;
Null_Info : constant Comment_Info;
function Create
(Name : in S_Expressions.Atom_Refs.Immutable_Reference;
Mail : in S_Expressions.Atom_Refs.Immutable_Reference;
Link : in S_Expressions.Atom_Refs.Immutable_Reference;
Filter : in S_Expressions.Atom_Refs.Immutable_Reference)
return Comment_Info;
function Create
(Expression : in out S_Expressions.Lockable.Descriptor'Class)
return Comment_Info;
function Name (Info : in Comment_Info)
return S_Expressions.Atom_Refs.Immutable_Reference;
function Mail (Info : in Comment_Info)
return S_Expressions.Atom_Refs.Immutable_Reference;
function Link (Info : in Comment_Info)
return S_Expressions.Atom_Refs.Immutable_Reference;
function Filter (Info : in Comment_Info)
return S_Expressions.Atom_Refs.Immutable_Reference;
function Named_Serialization (Info : in Comment_Info)
return S_Expressions.Atom;
function Positional_Serialization (Info : in Comment_Info)
return S_Expressions.Atom;
type Serialization_Kind is (Named, Positional);
type Encoder is access function (Data : in S_Expressions.Atom)
return String;
type Decoder is access function (Data : in String)
return S_Expressions.Atom;
type Codec_DB is private;
procedure Register
(DB : in out Codec_DB;
Key : in Character;
Filter : in not null Decoder);
procedure Set_Encoder
(DB : in out Codec_DB;
Filter : in not null Encoder;
Serialization : in Serialization_Kind);
function Encode
(DB : in Codec_DB;
Info : in Comment_Info)
return String;
function Decode
(DB : in Codec_DB;
Cookie : in String)
return Comment_Info;
private
type Atom_Kind is (Filter, Name, Mail, Link);
type Ref_Array is array (Atom_Kind)
of S_Expressions.Atom_Refs.Immutable_Reference;
type Comment_Info is record
Refs : Ref_Array;
end record;
package Decoder_Maps is new Constant_Indefinite_Ordered_Maps
(Character, Decoder);
type Codec_DB is record
Enc : Encoder := null;
Dec : Decoder_Maps.Constant_Map;
Serialization : Serialization_Kind := Named;
end record;
function Name (Info : in Comment_Info)
return S_Expressions.Atom_Refs.Immutable_Reference
is (Info.Refs (Name));
function Mail (Info : in Comment_Info)
return S_Expressions.Atom_Refs.Immutable_Reference
is (Info.Refs (Mail));
function Link (Info : in Comment_Info)
return S_Expressions.Atom_Refs.Immutable_Reference
is (Info.Refs (Link));
function Filter (Info : in Comment_Info)
return S_Expressions.Atom_Refs.Immutable_Reference
is (Info.Refs (Filter));
Null_Info : constant Comment_Info
:= (Refs => (others => S_Expressions.Atom_Refs.Null_Immutable_Reference));
end Natools.Web.Comment_Cookies;
|
-------------------------------------------------------------------------------
-- package body Orthogonal_Polys, Gram-Schmidt polynomials on discrete grid points.
-- Copyright (C) 2018 Jonathan S. Parker
--
-- Permission to use, copy, modify, and/or distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-------------------------------------------------------------------------------
with Text_IO; use Text_IO;
package body Orthogonal_Polys is
-- Global range for operations on data vectors:
Data_First : Points_Index := Points_index'First;
Data_Last : Points_Index := Points_index'Last;
-------------
-- Make_Re --
-------------
-- Converts Coeff_Index to Real in a way that simplifies things
-- when Real is a private extended precision floating point type.
-- It's slow, but it doesn't slow down any critical inner loops.
function Make_Re (N : Coeff_Index) return Real is
Result : Real := Zero;
begin
for i in 1 .. N loop
Result := Result + One;
end loop;
return Result;
end Make_Re;
------------------------------
-- Set_Limits_On_Vector_Ops --
------------------------------
procedure Set_Limits_On_Vector_Ops (First, Last : Points_Index) is
begin
Data_First := First;
Data_Last := Last;
end;
--------------------------------
-- Max_Permissable_Degree_Of --
--------------------------------
function Max_Permissable_Degree_Of (P : Polynomials) return Coeff_Index is
begin
return P.Max_Permissable_Degree_Of_Poly;
end Max_Permissable_Degree_Of;
-------------------
-- Inner product --
-------------------
function Inner_Product
(X, Y : in Data;
First, Last : in Points_Index;
Weights : in Data)
return Real
is
Sum : Real := Zero;
begin
for i in First .. Last loop
Sum := Sum + Weights(i) * Y(i) * X(i);
end loop;
return Sum;
end Inner_Product;
---------
-- "-" --
---------
function "-"
(Left : in Data;
Right : in Data)
return Data
is
Result : Data;
begin
for i in Data_First .. Data_Last loop
Result(i) := Left(i) - Right(i);
end loop;
return Result;
end "-";
---------
-- "+" --
---------
function "+"
(Left : in Data;
Right : in Data)
return Data
is
Result : Data;
begin
for i in Data_First .. Data_Last loop
Result(i) := Left(i) + Right(i);
end loop;
return Result;
end "+";
---------
-- "-" --
---------
function "-"
(Left : in Data;
Right : in Real)
return Data
is
Result : Data;
begin
for i in Data_First .. Data_Last loop
Result(i) := Left(i) - Right;
end loop;
return Result;
end "-";
---------
-- "*" --
---------
function "*"
(Left : in Real;
Right : in Data)
return Data
is
Result : Data;
begin
for i in Data_First .. Data_Last loop
Result(i) := Left * Right(i);
end loop;
return Result;
end "*";
---------
-- "*" --
---------
-- fortran 90 Array * Array multiplication.
function "*"
(Left : in Data;
Right : in Data)
return Data
is
Result : Data;
begin
for i in Data_First .. Data_Last loop
Result(i) := Left(i) * Right(i);
end loop;
return Result;
end "*";
----------------------------------------
-- Start_Gram_Schmidt_Poly_Recursion --
----------------------------------------
-- Given a set of discrete points X
-- X = (X1, X2, ...)
-- and the weights
-- W = (W1, W2, ...)
-- the Gram-Schmidt recurrance method yield a unique set of
-- orthogonal polynomials (functions defined at the grid points Xj).
-- It is assumed that the the zeroth order poly is constant 1,
-- and the 1st order poly is X. (Both have normalization factors
-- that are not applied to the polys here...instead the norm factor
-- is calculated and returned as field in the poly data structure.)
procedure Start_Gram_Schmidt_Poly_Recursion
(X_axis, Weights : in Data;
First, Last : in Points_Index;
Poly_0, Poly_1 : in out Poly_Data;
Poly_Set : out Polynomials)
is
X_max, X_min, Max_Delta_X : Real;
Slope, Const : Real;
X_Poly_0 : Data;
Alpha, Beta : Real;
X_Scaled : Data;
type Local_Float is digits 9;
Data_Length, No_Of_Weightless_Data_Points : Local_Float := 0.0;
begin
Set_Limits_On_Vector_Ops (First, Last);
-- Step 0. Make sure we have enough data points to calculate
-- a polynomial of the desired degree. For example we don't want
-- to try to fit a parabola to just two data points. So we start by
-- calculating the number of data points to be used. if Weight(i) is
-- less than Smallest_Weight then don't count this as a data
-- point. (However the data point will be used
-- in the calculation below.) We require a minimum of 2 data points.
No_Of_Weightless_Data_Points := 0.0;
for i in First .. Last loop
if Weights(i) < Smallest_Weight then
No_Of_Weightless_Data_Points := No_Of_Weightless_Data_Points - 1.0;
end if;
end loop;
Data_Length := Local_Float (Last) - Local_Float (First) + 1.0;
Data_length := Data_Length - No_Of_Weightless_Data_Points;
if Data_Length < 2.0 then
put_line ("Need at last 2 data points with positive weight.");
raise Constraint_Error;
end if;
-- Because we make a first order poly in this procedure.
if Data_Length - 1.0 <= Local_Float (Max_Order_Of_Poly) then
Poly_Set.Max_Permissable_Degree_Of_Poly := Coeff_Index(Data_Length-1.0);
else
Poly_Set.Max_Permissable_Degree_Of_Poly := Max_Order_Of_Poly;
end if;
Poly_Set.Degree_Of_Poly := 1; -- Below we make 0 and 1.
-- Step 1. Make sure that the DeltaX is > Smallest_Delta_X for all
-- all X. So no two points can have the same X, and we can't
-- have Data_X(i+1) < Data_X(i) for any i.
for i in First+1 .. Last loop
if X_axis (i) - X_axis (i-1) < Smallest_Delta_X then
put_line("Data Points Must Be Ordered In X and Distinct.");
raise Constraint_Error;
end if;
end loop;
-- Step 2. Accuracy can be much improved if X is in the interval
-- [-2,2], so the X axis is scaled such that the X values lie in
-- the interval [-2,2]. We
-- scale X with the following equation: X_new = X * Slope + Const,
-- where
-- Slope = 4.0 / (X_max - X_min)
-- and
-- Const = -2.0 * (X_max + X_min) / (X_max - X_min).
--
-- The final poly for Y will be correct, but the coefficients
-- of powers of X in the power form of Poly calculated below
-- must be scaled.
--
-- The results will be stored in Poly_Set, for subsequent use in
-- generating polynomials, and unscaling the calculations done on
-- these polynomials.
X_max := X_axis (First);
X_min := X_axis (First);
for i in First+1 .. Last loop
if not (X_axis (i) < X_max) then
X_max := X_axis (i);
end if;
if X_axis(i) < X_min then
X_min := X_axis (i);
end if;
end loop;
Max_Delta_X := (X_max - X_min);
if Max_Delta_X < Smallest_Delta_X then
put_line ("Data Points Too Close Together In X");
raise Constraint_Error;
end if;
Slope := Four / Max_Delta_X;
Const := -Two * ((X_max + X_min) / Max_Delta_X);
X_scaled := Slope * X_axis - (-Const); -- Vector operations.
-- Store the results in Poly_Set:
Poly_Set.X_scaled := X_scaled;
Poly_Set.Scale_Factors := X_Axis_Scale'(Slope, Const);
-- Step 3. Get the Polynomials. Vector op limits have been set above.
-- The zeroth order poly (unnormalized) is just 1.0:
Poly_Set.Alpha(0) := Zero;
Poly_Set.Beta(0) := Zero;
Poly_0.Points := (others => One);
Poly_0.First := First;
Poly_0.Last := Last;
Poly_0.Squared :=
Inner_Product (Poly_0.Points, Poly_0.Points, First, Last, Weights);
Poly_0.Degree := 0;
-- Get the 1st order Polynomial. Unnormalized, it's just X - alpha;
X_Poly_0 := X_Scaled * Poly_0.Points;
Alpha :=
Inner_Product(X_Poly_0, Poly_0.Points, First, Last, Weights) / Poly_0.Squared;
Beta := Zero;
Poly_Set.Alpha(1) := Alpha;
Poly_Set.Beta(1) := Beta;
Poly_1.Points := X_scaled - Alpha;
Poly_1.Squared :=
Inner_Product (Poly_1.Points, Poly_1.Points, First, Last, Weights);
Poly_1.First := First;
Poly_1.Last := Last;
Poly_1.Degree := 1;
end Start_Gram_Schmidt_Poly_Recursion;
-------------------
-- Get_Next_Poly --
-------------------
-- We want Q_m, Alpha_m, and Beta_m, given the previous values.
--
-- Q_0 = 1
-- Q_1 = (X - Alpha_1)
-- Q_m = (X - Alpha_m) * Q_m-1 - Beta_m*Q_m-2
-- where
-- Alpha_m = (X*Q_m-1, Q_m-1) / (Q_m-1, Q_m-1)
-- Beta_m = (X*Q_m-1, Q_m-2) / (Q_m-2, Q_m-2)
--
-- Can be shown: Beta_m = (Q_m-1, Q_m-1) / (Q_m-2, Q_m-2) which is
-- the form used below.
procedure Get_Next_Poly
(Poly_0, Poly_1 : in Poly_Data;
Weights : in Data;
Poly_2 : in out Poly_Data;
Poly_Set : in out Polynomials)
is
X_Poly_1 : Data;
Alpha, Beta : Real;
X_scaled : Data renames Poly_Set.X_scaled;
Degree_2 : Coeff_Index;
First : Points_Index renames Poly_1.First;
Last : Points_Index renames Poly_1.Last;
begin
Set_Limits_On_Vector_Ops (First, Last);
-- Have to tell the vector ops that the data goes from First..Last.
-- Not really necessary, because Start_Gram_.. has already done this.
-- But we do it anyway. Next some checks:
if Poly_0.First /= Poly_1.First or Poly_0.Last /= Poly_1.Last then
put_line ("Some error in input polys for Get_Next_Poly.");
raise Constraint_Error;
end if;
-- Must have Poly_Set.Degree_Of_Poly = Poly_1.Degree = Poly_0.Degree+1
if Poly_Set.Degree_Of_Poly /= Poly_0.Degree + 1 or
Poly_Set.Degree_Of_Poly /= Poly_1.Degree then
put_line ("Some error in input polys for Get_Next_Poly.");
raise Constraint_Error;
end if;
-- The purpose of this is to raise the degree of poly_set by one.
-- Can we do that?
if Poly_Set.Degree_Of_Poly >= Poly_Set.Max_Permissable_Degree_Of_Poly then
put_line ("Cannot make a poly of that order with so few points.");
raise Constraint_Error;
end if;
-- Now we can construct the next higher order polynomial: Poly_2
X_Poly_1 := X_Scaled * Poly_1.Points;
Alpha := Inner_Product(X_Poly_1, Poly_1.Points,
First, Last, Weights) / Poly_1.Squared;
Beta := Poly_1.Squared / Poly_0.Squared;
Degree_2 := Poly_Set.Degree_Of_Poly + 1;
Poly_Set.Degree_Of_Poly := Degree_2;
Poly_Set.Beta (Degree_2) := Beta;
Poly_Set.Alpha (Degree_2) := Alpha;
Poly_2.Points := (X_scaled - Alpha) * Poly_1.Points
- Beta * Poly_0.Points;
Poly_2.Squared := Inner_Product (Poly_2.Points, Poly_2.Points,
First, Last, Weights);
Poly_2.First := Poly_1.First;
Poly_2.Last := Poly_1.Last;
Poly_2.Degree := Poly_1.Degree + 1;
end Get_Next_Poly;
-------------------------------
-- Get_Coeffs_Of_Powers_Of_X --
-------------------------------
-- Calculate the Coefficients of powers of X in the best fit poly, using
-- Alpha, Beta, C as calculated above and the following formula for
-- the orthogonal polynomials:
-- Q_0 = 1
-- Q_1 = (X - Alpha_1)
-- Q_k = (X - Alpha_k) * Q_k-1 - Beta_k*Q_k-2
-- and the best fit poly is SUM {C_k * Q_k}. The Coefficients of X**k
-- are put in array Poly_Coefficients(k), which is set to 0.0 initially,
-- since the formula may assign values to only a small subset of it.
-- the E_k's in SUM {E_k * X**k} go into Poly_Coefficients(k).
-- Clenshaw's formula is used to get Poly_Coefficients. The
-- coefficients of the following D polynomials are put into arrays
-- D_0, D_1, and D_2, and advanced recursively until the final
-- D_0 = SUM {C_k * Q_k} is found. This will be named Poly_Coefficients.
-- The recursion formula for the Coefficients follows from the formula for D(X):
--
-- D_n+2(X) = 0
-- D_n+1(X) = 0
-- D_m(X) = C_m + (X - Alpha_m+1)*D_m+1(X) - Beta_m+2*D_m+2(X)
--
-- where n = Desired_Poly_Degree and m is in 0..n.
--
-- Now suppose we want the coefficients of powers of X for the above D polys.
-- (In the end that will give us the coeffs of the actual poly, D_0.)
-- Well, the first poly D_n is 0-th order and equals C(n). The second poly, D_n-1,
-- gets a contribution to its coefficient of X**1 from the X*D_n term. That
-- contribution is the coefficient of X**0 in D_n. Its X**0 coeff gets a
-- contribution from C(n-1) and one from -Alpha(n)*D_n at X**0, or -Alpha(n)*D_n(0).
-- Now we re-use the D
-- polynomial arrays to store these coefficients in the obvious place.
-- The arrays D_0, D_1, and D_2 are initialized to 0.0.
-- D_0, D_1, and D_2 contain be the coeff's of powers of X in the orthogonal
-- polynomials D_m, D_m+1, D_m+2, respectively. The formulas above
-- imply: for m in Desired_Poly_Degree .. 0:
--
-- D_0(0) := C(m);
-- for k in 1 .. Desired_Poly_Degree loop
-- D_0(k) := D_1(k-1);
-- end loop;
-- -- The above initalizes D_0.
--
-- for k in 0 .. Desired_Poly_Degree loop
-- D_0(k) := D_0(k) - Alpha(m+1)*D_1(k) - Beta(m+2)*D_2(k);
-- end loop;
--
-- So if we define shl_1 = Shift_Array_Left_by_1_and_Put_0_at_Index_0, the
-- formula in vector notation is:
--
-- D_0 = Y(m) + shl_1 (D_1) - Alpha(m+1)*D_1 - Beta(m+2)*D_2
--
-- where Y(m) = (C(m),0,0,....).
-- the above step is repeated recursivly using D_2 = D_1, and D_1 = D_0.
-- Notice that the above formula must be modified at m = n and m = n-1.
-- In matrix notation, using vector D, and vector Y this becomes:
--
--
-- | 1 0 0 0 | |D(n) | | Y(n) |
-- | A_n 1 0 0 | |D(n-1)| = | Y(n-1) |
-- | B_n A_n-1 1 0 | |D(n-2)| | Y(n-2) |
-- | 0 B_n-1 A_n-2 1 | |D(n-3)| | Y(n-3) |
--
-- where A_m = -(shl_1 - Alpha_m), B_m = Beta_m, and Y(m) = (C(m),0,0,....).
-- In the end, D(0) should be an array that contains the Coefficients of Powers
-- of X. The operator is not a standard matrix operator, but it's linear and we
-- know its inverse and forward operation, so Newton's method gives the
-- iterative refinement. The array D(k)(m) is possibly very large!
procedure Get_Coeffs_Of_Powers_Of_X
(Coeffs : out Powers_Of_X_Coeffs;
C : in Poly_Sum_Coeffs;
Poly_Set : in Polynomials)
is
D_1, D_2 : Recursion_Coeffs := (others => Zero);
D_0 : Recursion_Coeffs := (others => Zero);
m : Coeff_Index;
Const2 : Real := Zero;
A : Recursion_Coeffs renames Poly_Set.Alpha;
B : Recursion_Coeffs renames Poly_Set.Beta;
Scale_Factors : X_Axis_Scale renames Poly_Set.Scale_Factors;
Poly_Degree : Coeff_Index renames Poly_Set.Degree_Of_Poly;
begin
Coeffs := (others => Zero);
-- Special Case. Calculate D_2 (i.e. the D_m+2 poly):
m := Poly_Degree;
D_2(0) := C(m);
if Poly_Degree = 0 then
D_0 := D_2;
end if;
-- Special Case. Calculate D_1 (i.e. the D_m+1 poly):
if Poly_Degree > 0 then
m := Poly_Degree - 1;
D_1(0) := C(m);
for k in Coeff_Index range 1 .. Poly_Degree-m loop
D_1(k) := D_2(k-1);
end loop;
-- The previous 2 assigments have initialized D_1. Now:
for k in Coeff_Index'First .. Poly_Degree-m-1 loop
D_1(k) := D_1(k) - A(m+1) * D_2(k);
end loop;
end if;
if Poly_Degree = 1 then
D_0 := D_1;
end if;
-- Calculate D's for D_n-2 and lower:
if Poly_Degree > 1 then
for m in reverse Coeff_Index'First .. Poly_Degree-2 loop
D_0(0) := C(m);
for k in Coeff_Index range 1 .. Poly_Degree-m loop
D_0(k) := D_1(k-1);
end loop;
-- The previous 2 assigments have initialized D_0. Now:
for k in Coeff_Index'First .. Poly_Degree-m-1 loop
D_0(k) := D_0(k) - A(m+1) * D_1(k);
end loop;
for k in Coeff_Index'First .. Poly_Degree-m-2 loop
D_0(k) := D_0(k) - B(m+2) * D_2(k);
end loop;
D_2 := D_1;
D_1 := D_0;
end loop;
end if;
-- Now we have the coefficients of powers of X for the poly P1 (Z(X))
-- whose Z is in the range [-2,2]. How do we get the coeffs of
-- poly P2 (X) = P1 (Z(X)) whose X is in the range [a, b]. The
-- relation between Z and X is Z = 2*(2*X - (a + b)) / (a - b).
-- or Z = Slope * (X - Const2) where Slope = 4 / (a - b) and
-- Const2 = (a + b) / 2. We have P1 (Z). The first step in getting
-- P2 (X) is to get P1 (X - Const2) by multiplying the Coeffs of
-- of P1 by powers of Slope.
-- This is a common source of overflow.
-- The following method is slower but slightly more overflow resistant
-- than the more obvious method.
for j in 1 .. Poly_Degree loop
for k in Coeff_Index'First+j .. Poly_Degree loop
D_0(k) := D_0(k) * Scale_Factors.Slope;
end loop;
end loop;
-- Next we want coefficients of powers of X in P2 where P2 (X) is
-- defined P2 (X) = P1 (X - Const2). In other words we want the
-- coefficients E_n in
--
-- P2 (X) = E_n*X**n + E_n-1*X**n-1 .. + E_1*X + E_0.
--
-- We know that
--
-- P1 (X) = F_n*X**n + F_n-1*X**n-1 .. + F_1*X + F_0,
--
-- where the F's are given by Coeff_0 above,
-- and P2 (X + Const2) = P1 (X). Use synthetic division to
-- shift P1 in X as follows. (See Mathew and Walker).
-- P2 (X + Const2) = E_n*(X + Const2)**n + .. + E_0.
-- So if we divide P2 (X + Const2) by (X + Const2) the remainder
-- is E_0. if we repeat the division, the remainder is E_1.
-- So we use synthetic division to divide P1 (X) by (X + Const2).
-- Synthetic division: multiply (X + Const2) by
-- F_n*X**(n-1) = D_0(n)*X**(n-1) and subtract from P1.
-- Repeat as required.
-- What is Const2?
-- Slope := 4.0 / Max_Delta_X;
-- Const := -2.0 * (X_max + X_min) / Max_Delta_X; -- 2 (a + b)/(b - a)
-- X_scaled = Z = X * Slope + Const.
-- Want Z = Slope * (X - Const2). Therefore Const2 = - Const/Slope
Const2 := -Scale_Factors.Const / Scale_Factors.Slope;
for m in Coeff_Index range 1 .. Poly_Degree loop
for k in reverse Coeff_Index range m .. Poly_Degree loop
D_0 (k-1) := D_0 (k-1) - D_0 (k) * Const2;
end loop;
Coeffs (m-1) := D_0 (m-1);
end loop;
Coeffs (Poly_Degree) := D_0 (Poly_Degree);
end Get_Coeffs_Of_Powers_Of_X;
----------------
-- Horner_Sum --
----------------
-- Want Sum = a_0 + a_1*X + a_2*X**2 + ... + a_n*X**n.
-- or in Horner's form: Sum = a_0 + X*(a_1 + ... + X*(a_n-1 + X*a_n)))))).
-- This is easily written as matrix equation, with Sum = S_0:
--
-- S_n = a_n; S_n-1 = a_n-1 + X*S_n; S_1 = a_1 + X*S_2; S_0 = a_0 + X*S_1;
--
-- In matrix form, vector S is the solution to matrix equation M*S = A,
-- where A = (a_0,...,a_n), S = (S_0,...,S_n) and matrix M is equal to
-- the unit matrix i minus X*O1, where O1 is all 1's on the 1st lower off-
-- diagonal. The reason this form is chosen is that the solution vector
-- S can be improved numerically by iterative refinement with Newton's
-- method:
-- S(k+1) = S(k) + M_inverse * (A - M*S(k))
--
-- where S = M_inverse * A is the calculation of S given above. if the
-- said calculation of S is numerically imperfect, then the iteration above
-- will produce improved values of S. Of course, if the Coefficients of
-- the polynomial A are numerically poor, then this effort may be wasted.
--
function Horner_Sum
(A : in Recursion_Coeffs;
Coeff_Last : in Coeff_Index;
X : in Real;
No_Of_Iterations : in Natural)
return Real
is
S : Recursion_Coeffs := (others => Zero);
Del, Product : Recursion_Coeffs;
begin
if Coeff_Last = Coeff_Index'First then
return A(Coeff_Index'First);
end if;
-- Poly is zeroth order = A(Index'First). No work to do. Go home.
-- Now solve for S in the matrix equation M*S = A. first iteration:
S(Coeff_Last) := A(Coeff_Last);
for n in reverse Coeff_Index'First .. Coeff_Last-1 loop
S(n) := A(n) + X * S(n+1);
end loop;
-- Now iterate as required. We have the first S, S(1), now get S(2) from
-- S(k+1) = S(k) + M_inverse * (A - M*S(k))
Iterate: for k in 1..No_Of_Iterations loop
-- Get Product = M*S(k):
Product(Coeff_Last) := S(Coeff_Last);
for n in reverse Coeff_Index'First..Coeff_Last-1 loop
Product(n) := S(n) - X * S(n+1);
end loop;
-- Get Product = Residual = A - M*S(k):
for n in Coeff_Index'First .. Coeff_Last loop
Product(n) := A(n) - Product(n);
end loop;
-- Get Del = M_inverse * (A - M*S(k)) = M_inverse * Product:
Del(Coeff_Last) := Product(Coeff_Last);
for n in reverse Coeff_Index'First .. Coeff_Last-1 loop
Del(n) := Product(n) + X * Del(n+1);
end loop;
-- Get S(k+1) = S(k) + Del;
for n in Coeff_Index'First .. Coeff_Last loop
S(n) := S(n) + Del(n);
end loop;
end loop Iterate;
return S(Coeff_Index'First);
end Horner_Sum;
-------------------
-- Poly_Integral --
-------------------
-- Use Clenshaw summation to get coefficients of powers of X,
-- then sum analytically integrated polynomial using Horner's rule.
-- Poly_Integral returns the indefinite integral. Integral on an
-- interval [A, B] is Poly_Integral(B) - Poly_Integral(A).
--
function Poly_Integral
(X : in Real;
C : in Poly_Sum_Coeffs;
Poly_Set : in Polynomials;
Order_Of_Integration : in Coeff_Index := 1)
return Real
is
D_1, D_2 : Recursion_Coeffs := (others => Zero);
D_0 : Recursion_Coeffs := (others => Zero);
m : Coeff_Index;
Result : Real := Zero;
Denom, X_scaled : Real := Zero;
A : Recursion_Coeffs renames Poly_Set.Alpha;
B : Recursion_Coeffs renames Poly_Set.Beta;
Poly_Degree : Coeff_Index renames Poly_Set.Degree_Of_Poly;
begin
-- Special Case. Calculate D_2 (i.e. the D_m+2 poly):
m := Poly_Degree;
D_2(0) := C(m);
if Poly_Degree = 0 then
D_0 := D_2;
end if;
-- Special Case. Calculate D_1 (i.e. the D_m+1 poly):
if Poly_Degree > 0 then
m := Poly_Degree - 1;
D_1(0) := C(m);
for k in Coeff_Index range 1 .. Poly_Degree-m loop
D_1(k) := D_2(k-1);
end loop;
-- The previous 2 assigments have initialized D_1. Now:
for k in Coeff_Index'First .. Poly_Degree-m-1 loop
D_1(k) := D_1(k) - A(m+1) * D_2(k);
end loop;
end if;
if Poly_Degree = 1 then
D_0 := D_1;
end if;
-- Calculate D's for D_n-2 and lower:
if Poly_Degree > 1 then
for m in reverse Coeff_Index'First .. Poly_Degree-2 loop
D_0(0) := C(m);
for k in Coeff_Index range 1 .. Poly_Degree-m loop
D_0(k) := D_1(k-1);
end loop;
-- The previous 2 assigments have initialized D_0. Now:
for k in Coeff_Index'First .. Poly_Degree-m-1 loop
D_0(k) := D_0(k) - A(m+1) * D_1(k);
end loop;
for k in Coeff_Index'First .. Poly_Degree-m-2 loop
D_0(k) := D_0(k) - B(m+2) * D_2(k);
end loop;
D_2 := D_1;
D_1 := D_0;
end loop;
end if;
-- The unscaled Coeffs of X**m are D_0(m). Integrate once,
-- (brings a 1/(m+1) down) then use Horner's rule for poly sum:
-- First scale X from [a, b] to [-2, 2]:
X_Scaled := X * Poly_Set.Scale_Factors.Slope + Poly_Set.Scale_Factors.Const;
for m in reverse Coeff_Index'First .. Poly_Degree loop
Denom := One;
for i in 1 .. Order_Of_Integration loop
Denom := Denom * (Make_Re (m + i));
end loop;
D_0(m) := D_0(m) / Denom;
end loop;
Result :=
Horner_Sum
(A => D_0,
Coeff_Last => Poly_Degree,
X => X_scaled,
No_Of_Iterations => 1);
Result := Result * X_scaled ** Integer(Order_Of_Integration);
-- This X was neglected above in Horner_Sum.
-- The integral was on a scaled interval [-2, X]. Unscale the result:
Result :=
Result / Poly_Set.Scale_Factors.Slope ** Integer(Order_Of_Integration);
return Result;
end Poly_Integral;
----------------------
-- Poly_Derivatives --
----------------------
-- How do we get the derivatives of the best-fit polynomial? Just
-- take the derivative of the Clenshaw recurrence formula given above.
-- In the special case of orthogonal polynomials it is particularly
-- easy. By differentiating the formula given above p times it's easy
-- to see that the p-th derivative of the D_m functions of X satisfy:
--
-- p = order of derivative = 0:
--
-- D_n+2(0,X) = 0
-- D_n+1(0,X) = 0
-- D_m(0,X) = C_m + (X - Alpha(m+1)) * D_m+1(0,X) + Beta(m+2) * D_m+2(0,X)
--
-- p = order of derivative > 0:
--
-- D_n+2(p,X) = 0
-- D_n+1(p,X) = 0
-- D_m(p,X)
-- = p*D_m+1(p-1,X) + (X - Alpha(m+1))*D_m+1(p,X) - Beta(m+2)*D_m+2(p,X)
--
-- for m in 0..n,
-- where D(p,X) is the pth derivative of D(X). It follows that the
-- p-th derivative of the sum over m of C_m*Q_m(X) equals D_0(p,X).
--
-- We still aren't finished. What we really want is the derivative
-- respect the UNSCALED variable, Y. Here X = X_Scaled is in the range
-- [-2,2] and X_scaled = Slope * Y + Constant. So d/dY = Slope * d/dX.
-- Usually Y is in (say) 1..100, and X is in -2..2, so Slope is << 1.
-- It follows that the recurrence relation for the p-th derivative
-- of the D polynomials respect Y is
--
-- D_n+2(p,X) = 0
-- D_n+1(p,X) = 0
-- D_m(p,X) = p * Slope * D_m+1(p-1,X)
-- + (X - Alpha(m+1))*D_m+1(p,X) - Beta(m+2)*D_m+2(p,X)
--
-- for m in 0..n,
-- where D(p,X) is the p-th derivative of D(X). It follows that the
-- p-th derivative the sum over m of C_m*Q_m(X) equals D_0(p,X).
--
-- To perform the calculation, the 0th derivative (p=0) D is calculated
-- first, then used as a constant in the recursion relation to get the
-- p=1 D. These steps are repeated recursively.
--
-- In the code that follows D is an array only in "m". X is a constant,
-- input by the user of the procedure, and p is reduced to 2 values,
-- "Hi" and "Low". So we calculate D_low(m) where derivative order
-- p = Low, which starts at 0, and use D_low(m) to get D_hi(m), where
-- Hi = Low + 1.
--
-- p = order of derivative == Low = 0:
--
-- D_low(n+2) = 0
-- D_low(n+1) = 0
-- D_low(m) = C_m + (X - Alpha(m+1)) * D_low(m+1) + Beta(m+2) * D_low(m+2)
--
-- p = order of derivative == hi > 0
--
-- D_hi(n+2) = 0
-- D_hi(n+1) = 0
-- D_hi(m) = p * Slope * D_low(m+1)
-- + (X - Alpha(m+1))*D_hi(m+1) - Beta(m+2)*D_hi(m+2)
--
-- Next iterative refinement is optionally performed. For each value of
-- of p, the following matrix equation represents the recursive equations
-- above. Remember, in the following, D_low is a previously calculated
-- constant:
--
-- | 1 0 0 0 | |D_hi(n) | | Y(n) |
-- | A_n 1 0 0 | |D_hi(n-1)| = | Y(n-1) |
-- | B_n A_n-1 1 0 | |D_hi(n-2)| | Y(n-2) |
-- | 0 B_n-1 A_n-2 1 | |D_hi(n-3)| | Y(n-3) |
--
-- where A_m = -(X - Alpha_m), B_m = Beta_m, and Y(m) = C(m) if p=0, and
-- Y(m) = p * Slope * D_low(m+1) if p > 0. (Remember, D_any(n+1) = 0.0).
-- So the refinement is in the m iteration not the p iteration.
-- The iteration can actually be done in both p and m, but in that case D
-- must be stored as a 2-d array. In that case the matrix equation
-- is a block Lower triangular matrix. We do it the less sophisticated way
-- here.
procedure Poly_Derivatives
(Derivatives : in out Derivative_List;
X : in Real;
Order_Of_Deriv : in Derivatives_Index;
C : in Poly_Sum_Coeffs;
Poly_Set : in Polynomials)
is
Order : Real;
Order_times_Slope : Real;
X_Scaled : Real;
D_Hi, D_Low : Recursion_Coeffs;
-- D_Hi is the higher deriv. in the recurrence relation.
Local_Order_Of_Deriv : Derivatives_Index;
A : Recursion_Coeffs renames Poly_Set.Alpha;
B : Recursion_Coeffs renames Poly_Set.Beta;
Scale_Factors : X_Axis_Scale renames Poly_Set.Scale_Factors;
Poly_Degree : Coeff_Index renames Poly_Set.Degree_Of_Poly;
begin
-- The derivatives of a polynomial are zero if their order is
-- greater than the degree of the polynomial, so in that case
-- don't bother to get them:
Derivatives := (others => Zero);
if Order_Of_Deriv > Poly_Degree then
Local_Order_Of_Deriv := Poly_Degree;
else
Local_Order_Of_Deriv := Order_Of_Deriv;
end if;
-- Scale X to the interval [-2,2].
X_Scaled := X * Scale_Factors.Slope + Scale_Factors.Const;
-- Step 1. We need a 0th order poly to start off the recurrence
-- relation. Start by getting undifferentiated D's (p=0).
-- Store them in array D_Low. The Low is for "Lower Order".
-- Use recurrence relation to get Poly at X.
-- Start with special formulas for the 1st 2 D-Polys:
D_Low(Poly_Degree) := C(Poly_Degree);
if Poly_Degree > Coeff_Index'First then
D_low(Poly_Degree-1) := C(Poly_Degree-1) +
(X_Scaled - A(Poly_Degree)) * D_low(Poly_Degree);
end if;
for m in reverse Coeff_Index'First+2 .. Poly_Degree loop
D_Low(m-2) := C(m-2) +
(X_Scaled - A(m-1))*D_Low(m-1) - B(m)*D_low(m);
end loop;
Derivatives (Derivatives_Index'First) := D_Low(Coeff_Index'First);
-- Step 2. Use the recurrence relation to get next higher
-- higher derivative. Store it in array D_Hi.
for p in Derivatives_Index'First+1 .. Local_Order_Of_Deriv loop
Order := Make_Re (p);
D_Hi(Poly_Degree) := Zero;
Order_times_Slope := Order * Scale_Factors.Slope;
if Poly_Degree > Coeff_Index'First then
D_Hi(Poly_Degree-1) := Order_times_Slope * D_Low(Poly_Degree) +
(X_Scaled - A(Poly_Degree)) * D_Hi(Poly_Degree);
end if;
for m in reverse Coeff_Index'First+2 .. Poly_Degree loop
D_Hi(m-2) := Order_times_Slope * D_low(m-1) +
(X_Scaled - A(m-1))*D_Hi(m-1) - B(m)*D_Hi(m);
end loop;
Derivatives (p) := D_Hi(Coeff_Index'First);
D_Low := D_Hi;
end loop;
end Poly_Derivatives;
----------------
-- Poly_Value --
----------------
-- This is easily written as matrix equation, with Sum = S_0:
--
-- D_n = C_n;
-- D_n-1 = C_n-1 + (X - A_n)*D_n;
-- D_n-2 = C_n-2 + (X - A_n-1)*D_n-1 - B_n-2*D_n-2;
-- ...
-- D_0 = C_0 + (X - A_1)*D_1 - B_2*D_2
--
-- In matrix form, M*D = C, this becomes:
--
-- | 1 0 0 0 | |D(n) | | C(n) |
-- | E_n 1 0 0 | |D(n-1)| = | C(n-1) |
-- | B_n E_n-1 1 0 | |D(n-2)| | C(n-2) |
-- | 0 B_n-1 E_n-2 1 | |D(n-3)| | C(n-3) |
--
-- where E_m = (A_m - X), B_m = B_m.
--
-- D can be improved numerically by iterative refinement with Newton's
-- method:
-- D_new = D_old + M_inverse * (C - M*D_old)
--
-- where D = M_inverse * C is the calculation of D given at the top. if the
-- said calculation of D is numerically imperfect, then the iteration above
-- will produce improved values of D. Of course, if the Coefficients of
-- the polynomials C are numerically poor, then this effort may be wasted.
function Poly_Value
(X : in Real;
C : in Poly_Sum_Coeffs;
Poly_Set : in Polynomials)
return Real
is
D, Product, Del : Recursion_Coeffs := (others => Zero);
X_Scaled : Real;
m : Coeff_Index;
A : Recursion_Coeffs renames Poly_Set.Alpha;
B : Recursion_Coeffs renames Poly_Set.Beta;
Scale_Factors : X_Axis_Scale renames Poly_Set.Scale_Factors;
Poly_Degree : Coeff_Index renames Poly_Set.Degree_Of_Poly;
No_Of_Iterations : constant Natural := 0;
begin
-- Scale X to the interval [-2,2].
X_Scaled := X * Scale_Factors.Slope + Scale_Factors.Const;
-- Step 0. Poly is zeroth order = C(Index'First). No work to do.
if Poly_Degree = Coeff_Index'First then
m := Poly_Degree;
D(m) := C(m);
return D(Coeff_Index'First);
end if;
-- Step 0b. Poly is 1st order. Almost no work to do.
-- Don't do any iteration.
if Poly_Degree = Coeff_Index'First + 1 then
m := Poly_Degree;
D(m) := C(m);
m := Poly_Degree - 1;
D(m) := C(m) - (A(m+1) - X_Scaled)*D(m+1);
return D(Coeff_Index'First);
end if;
-- Step 1. We now know henceforth that Poly_Degree > 1.
-- Start by getting starting value of D by solving M*D = C.
-- Use recurrence relation to get Poly at X.
-- Start with special formulas for the 1st two Polys:
m := Poly_Degree;
D(m) := C(m);
m := Poly_Degree - 1;
D(m) := C(m) - (A(m+1) - X_Scaled)*D(m+1);
for m in reverse Coeff_Index'First .. Poly_Degree-2 loop
D(m) := C(m) - (A(m+1) - X_Scaled)*D(m+1) - B(m+2)*D(m+2);
end loop;
-- Step 2. Improve D numerically through Newton iteration.
-- D_new = D_old + M_inverse * (C - M*D_old)
Iterate: for k in 1 .. No_Of_Iterations loop
-- Get Product = M*D(k):
m := Poly_Degree;
Product(m) := D(m);
m := Poly_Degree - 1;
Product(m) := D(m) + (A(m+1) - X_Scaled)*D(m+1);
for m in reverse Coeff_Index'First .. Poly_Degree-2 loop
Product(m) := D(m) + (A(m+1) - X_Scaled)*D(m+1) + B(m+2)*D(m+2);
end loop;
-- Get Residual = C - M*D(k) and set it equal to Product:
for m in Coeff_Index'First .. Poly_Degree loop
Product(m) := C(m) - Product(m);
end loop;
-- Get Del = M_inverse * (A - M*S(k)) = M_inverse * Product:
m := Poly_Degree;
Del(m) := Product(m);
m := Poly_Degree - 1;
Del(m) := Product(m) - (A(m+1) - X_Scaled)*Del(m+1);
for m in reverse Coeff_Index'First .. Poly_Degree-2 loop
Del(m) := Product(m) - (A(m+1) - X_Scaled)*Del(m+1) - B(m+2)*Del(m+2);
end loop;
-- Get D(k+1) = D(k) + Del;
for m in Coeff_Index'First .. Poly_Degree loop
D(m) := D(m) + Del(m);
end loop;
end loop Iterate;
return D(Coeff_Index'First);
end Poly_Value;
--------------
-- Poly_Fit --
--------------
-- Generate orthogonal polys and project them onto the data
-- with the Inner_Product function in order to calculate
-- C_k, the Best_Fit_Coefficients.
procedure Poly_Fit
(Data_To_Fit : in Data;
X_axis, Weights : in Data;
First, Last : in Points_Index;
Desired_Poly_Degree : in Coeff_Index;
Best_Fit_Poly : in out Poly_Data;
Best_Fit_Coeffs : in out Poly_Sum_Coeffs;
Poly_Set : in out Polynomials;
Mean_Square_Error : out Real)
is
Poly_0, Poly_1, Poly_2 : Poly_Data;
Local_Poly_Degree : Coeff_Index := Desired_Poly_Degree;
Data_Length : Real;
C : Poly_Sum_Coeffs renames Best_Fit_Coeffs;
Dat : Data renames Data_To_Fit;
Best_Fit : Data renames Best_Fit_Poly.Points;
begin
Start_Gram_Schmidt_Poly_Recursion
(X_axis, Weights, First, Last, Poly_0, Poly_1, Poly_Set);
-- Get Degree of poly: may be less than the desired degree
-- if too few points exist in the subset defined by X.
if Local_Poly_Degree > Poly_Set.Max_Permissable_Degree_Of_Poly then
Local_Poly_Degree := Poly_Set.Max_Permissable_Degree_Of_Poly;
end if;
Data_Length := Make_Re (Local_Poly_Degree) + (One);
-- By definition of Local_Poly_Degree.
Set_Limits_On_Vector_Ops (First, Last);
-- Get C(0) = Coefficient of 0th orthog. poly.
C(0) :=
Inner_Product (Poly_0.Points, Dat, First, Last, Weights) / Poly_0.Squared;
Best_Fit := C(0) * Poly_0.Points;
-- Get C(1) = Coefficient of 1st orthog. poly.
if Local_Poly_Degree > 0 then
C(1) := Inner_Product (Poly_1.Points, Dat - Best_Fit,
First, Last, Weights) / Poly_1.Squared;
Best_Fit := Best_Fit + C(1) * Poly_1.Points;
end if;
-- Get C(2) = Coefficient of 2nd orthog. poly.
if Local_Poly_Degree > 1 then
Get_Next_Poly (Poly_0, Poly_1, Weights, Poly_2, Poly_Set);
C(2) :=
Inner_Product
(Poly_2.Points, Dat - Best_Fit, First, Last, Weights) / Poly_2.Squared;
Best_Fit := Best_Fit + C(2) * Poly_2.Points;
end if;
-- Higher order Polynomials: get C(i) which is the coefficient of
-- the Ith orthogonal polynomial. Also get the Best_Fit_Polynomial.
-- Notice that the formula used to get C(i) is a little more complicated
-- than the the one written in the prologue above. The formula used
-- below gives substantially better numerical results, and is
-- mathematically identical to formula given in the prologue.
for N in Coeff_Index range 3 .. Local_Poly_Degree loop
Poly_0 := Poly_1;
Poly_1 := Poly_2;
Get_Next_Poly (Poly_0, Poly_1, Weights, Poly_2, Poly_Set);
C(N) :=
Inner_Product
(Poly_2.Points, Dat - Best_Fit, First, Last, Weights) / Poly_2.Squared;
Best_Fit := Best_Fit + C(N) * Poly_2.Points;
end loop;
-- Reuse Poly_0 to calculate Error**2 per Point = Mean_Square_Error:
Poly_0.Points := Dat - Best_Fit;
Mean_Square_Error := Inner_Product (Poly_0.Points, Poly_0.Points,
First, Last, Weights) / Data_Length;
-- Finish filling Best_Fit_Poly and Poly_Set:
Poly_Set.Degree_Of_Poly := Local_Poly_Degree;
--Best_Fit_Poly.Points := Best_Fit; -- through renaming.
Best_Fit_Poly.First := First;
Best_Fit_Poly.Last := Last;
Best_Fit_Poly.Degree := Local_Poly_Degree;
Best_Fit_Poly.Squared :=
Inner_Product (Best_Fit, Best_Fit, First, Last, Weights);
end Poly_Fit;
begin
if Max_Order_Of_Poly > Max_No_Of_Data_Points - 1 then
put_line("Max poly order must be less than max number of data points.");
raise Constraint_Error;
end if;
end Orthogonal_Polys;
|
-- Abstract :
--
-- Types and operations for generating parsers, common to all parser
-- types.
--
-- The wisi* packages deal with reading *.wy files and generating
-- source code files. The wisitoken-generate* packages deal with
-- computing parser properties from the grammar. (For historical
-- reasons, not all packages follow this naming convention yet).
--
-- References :
--
-- See wisitoken.ads
--
-- Copyright (C) 2018 - 2020 Free Software Foundation, Inc.
--
-- This library is free software; you can redistribute it and/or modify it
-- under terms of the GNU General Public License as published by the Free
-- Software Foundation; either version 3, or (at your option) any later
-- version. This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN-
-- TABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-- As a special exception under Section 7 of GPL version 3, you are granted
-- additional permissions described in the GCC Runtime Library Exception,
-- version 3.1, as published by the Free Software Foundation.
pragma License (Modified_GPL);
with Ada.Containers.Doubly_Linked_Lists;
with SAL.Ada_Containers.Gen_Doubly_Linked_Lists_Image;
with SAL.Gen_Graphs;
with WisiToken.Productions;
package WisiToken.Generate is
Error : Boolean := False;
-- Set True by errors during grammar generation
function Error_Message
(File_Name : in String;
File_Line : in WisiToken.Line_Number_Type;
Message : in String)
return String;
procedure Put_Error (Message : in String);
-- Set Error True, output Message to Standard_Error
procedure Check_Consistent
(Grammar : in WisiToken.Productions.Prod_Arrays.Vector;
Descriptor : in WisiToken.Descriptor;
Source_File_Name : in String);
-- Check requirements on Descriptor values.
function Check_Unused_Tokens
(Descriptor : in WisiToken.Descriptor;
Grammar : in WisiToken.Productions.Prod_Arrays.Vector)
return Boolean;
-- Return False if there is a terminal or nonterminal that is not
-- used in the grammar.
--
-- Raises Grammar_Error if there is a non-grammar token used in the
-- grammar.
function Nullable (Grammar : in WisiToken.Productions.Prod_Arrays.Vector) return Token_Array_Production_ID;
-- If ID is nullable, Result (ID) is the production that should be
-- reduced to produce the null. Otherwise Result (ID) is
-- Invalid_Production_ID.
function Has_Empty_Production (Nullable : in Token_Array_Production_ID) return Token_ID_Set;
function Has_Empty_Production (Grammar : in WisiToken.Productions.Prod_Arrays.Vector) return Token_ID_Set;
-- Result (ID) is True if any production for ID can be an empty
-- production, recursively.
function First
(Grammar : in WisiToken.Productions.Prod_Arrays.Vector;
Has_Empty_Production : in Token_ID_Set;
First_Terminal : in Token_ID)
return Token_Array_Token_Set;
-- For each nonterminal in Grammar, find the set of tokens
-- (terminal or nonterminal) that any string derived from it can
-- start with. Together with Has_Empty_Production, implements
-- algorithm FIRST from [dragon], augmented with nonterminals.
--
-- LALR, LR1 generate want First as both Token_Sequence_Arrays.Vector
-- and Token_Array_Token_Set, Packrat wants Token_Array_Token_Set,
-- existing tests all use Token_Array_Token_Set. So for LR1 we use
-- To_Terminal_Sequence_Array.
function To_Terminal_Sequence_Array
(First : in Token_Array_Token_Set;
Descriptor : in WisiToken.Descriptor)
return Token_Sequence_Arrays.Vector;
-- Only includes terminals.
function Follow
(Grammar : in WisiToken.Productions.Prod_Arrays.Vector;
Descriptor : in WisiToken.Descriptor;
First : in Token_Array_Token_Set;
Has_Empty_Production : in Token_ID_Set)
return Token_Array_Token_Set;
-- For each nonterminal in Grammar, find the set of terminal
-- tokens that can follow it. Implements algorithm FOLLOW from
-- [dragon] pg 189.
----------
-- Recursion
-- Recursion is the result of a cycle in the grammar. We can form a
-- graph representing the grammar by taking the nonterminals as the
-- graph vertices, and the occurrence of a nonterminal in a
-- production right hand side as a directed edge from the left hand
-- side of the production to that nonterminal. Then recursion is
-- represented by a cycle in the graph.
type Edge_Data is record
-- The edge leading to this node.
RHS : Natural := Natural'Last;
Token_Index : Positive := Positive'Last;
end record;
function Edge_Image (Edge : in Edge_Data) return String is (Trimmed_Image (Edge.RHS));
type Base_Recursion_Index is range 0 .. Integer'Last;
subtype Recursion_Index is Base_Recursion_Index range 1 .. Base_Recursion_Index'Last;
Invalid_Recursion_Index : constant Base_Recursion_Index := 0;
function Trimmed_Image is new SAL.Gen_Trimmed_Image (Base_Recursion_Index);
package Grammar_Graphs is new SAL.Gen_Graphs
(Edge_Data => Generate.Edge_Data,
Default_Edge_Data => (others => <>),
Vertex_Index => Token_ID,
Invalid_Vertex => Invalid_Token_ID,
Path_Index => Recursion_Index,
Edge_Image => Edge_Image);
subtype Recursion_Cycle is Grammar_Graphs.Path;
-- A recursion, with lowest numbered production first. If there is
-- only one element, the recursion is direct; otherwise indirect.
subtype Recursion_Array is Grammar_Graphs.Path_Arrays.Vector;
-- For the collection of all cycles.
type Recursions is record
Full : Boolean;
Recursions : Recursion_Array;
-- If Full, elements are paths; edges at path (I) are to path (I). If
-- not Full, elements are strongly connected components; edges at
-- path (I) are from path (I).
end record;
package Recursion_Lists is new Ada.Containers.Doubly_Linked_Lists (Recursion_Index);
function Image is new SAL.Ada_Containers.Gen_Doubly_Linked_Lists_Image
(Recursion_Index, "=", Recursion_Lists, Trimmed_Image);
function To_Graph (Grammar : in WisiToken.Productions.Prod_Arrays.Vector) return Grammar_Graphs.Graph;
function Compute_Full_Recursion
(Grammar : in out WisiToken.Productions.Prod_Arrays.Vector;
Descriptor : in WisiToken.Descriptor)
return Recursions;
-- Each element of result is a cycle in the grammar. Also sets
-- Recursive components in Grammar.
function Compute_Partial_Recursion
(Grammar : in out WisiToken.Productions.Prod_Arrays.Vector;
Descriptor : in WisiToken.Descriptor)
return Recursions;
-- Each element of the result contains all members of a non-trivial
-- strongly connected component in the grammar, in arbitrary order.
-- This is an approximation to the full recursion, when that is too
-- hard to compute (ie for Java).
--
-- Also sets Recursive components in Grammar.
----------
-- Indented text output. Mostly used for code generation in wisi,
-- also used in outputing the parse_table and other debug stuff.
Max_Line_Length : constant := 120;
Indent : Standard.Ada.Text_IO.Positive_Count := 1;
Line_Count : Integer;
procedure Indent_Line (Text : in String);
-- Put Text, indented to Indent, to Current_Output, with newline.
procedure Indent_Start (Text : in String);
-- Put Text indented to Indent to Current_Output, without newline.
-- Should be followed by Put_Line, not Indent_Line.
procedure Indent_Wrap (Text : in String);
-- Put Text, indented to Indent, wrapped at Max_Line_Length, to
-- Current_Output, ending with newline.
procedure Indent_Wrap_Comment (Text : in String; Comment_Syntax : in String);
-- Put Text, prefixed by Comment_Syntax and two spaces, indented to
-- Indent, wrapped at Max_Line_Length, to Current_Output, ending with
-- newline.
end WisiToken.Generate;
|
------------------------------------------------------------------------------
-- --
-- GNAT LIBRARY COMPONENTS --
-- --
-- ADA.CONTAINERS.INDEFINITE_ORDERED_SETS --
-- --
-- B o d y --
-- --
-- Copyright (C) 2004-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/>. --
-- --
-- This unit was originally developed by Matthew J Heaney. --
------------------------------------------------------------------------------
with Ada.Containers.Helpers; use Ada.Containers.Helpers;
with Ada.Containers.Red_Black_Trees.Generic_Operations;
pragma Elaborate_All (Ada.Containers.Red_Black_Trees.Generic_Operations);
with Ada.Containers.Red_Black_Trees.Generic_Keys;
pragma Elaborate_All (Ada.Containers.Red_Black_Trees.Generic_Keys);
with Ada.Containers.Red_Black_Trees.Generic_Set_Operations;
pragma Elaborate_All (Ada.Containers.Red_Black_Trees.Generic_Set_Operations);
with Ada.Unchecked_Deallocation;
with System; use type System.Address;
package body Ada.Containers.Indefinite_Ordered_Sets is
pragma Warnings (Off, "variable ""Busy*"" is not referenced");
pragma Warnings (Off, "variable ""Lock*"" is not referenced");
-- See comment in Ada.Containers.Helpers
-----------------------
-- Local Subprograms --
-----------------------
function Color (Node : Node_Access) return Color_Type;
pragma Inline (Color);
function Copy_Node (Source : Node_Access) return Node_Access;
pragma Inline (Copy_Node);
procedure Free (X : in out Node_Access);
procedure Insert_Sans_Hint
(Tree : in out Tree_Type;
New_Item : Element_Type;
Node : out Node_Access;
Inserted : out Boolean);
procedure Insert_With_Hint
(Dst_Tree : in out Tree_Type;
Dst_Hint : Node_Access;
Src_Node : Node_Access;
Dst_Node : out Node_Access);
function Is_Greater_Element_Node
(Left : Element_Type;
Right : Node_Access) return Boolean;
pragma Inline (Is_Greater_Element_Node);
function Is_Less_Element_Node
(Left : Element_Type;
Right : Node_Access) return Boolean;
pragma Inline (Is_Less_Element_Node);
function Is_Less_Node_Node (L, R : Node_Access) return Boolean;
pragma Inline (Is_Less_Node_Node);
function Left (Node : Node_Access) return Node_Access;
pragma Inline (Left);
function Parent (Node : Node_Access) return Node_Access;
pragma Inline (Parent);
procedure Replace_Element
(Tree : in out Tree_Type;
Node : Node_Access;
Item : Element_Type);
function Right (Node : Node_Access) return Node_Access;
pragma Inline (Right);
procedure Set_Color (Node : Node_Access; Color : Color_Type);
pragma Inline (Set_Color);
procedure Set_Left (Node : Node_Access; Left : Node_Access);
pragma Inline (Set_Left);
procedure Set_Parent (Node : Node_Access; Parent : Node_Access);
pragma Inline (Set_Parent);
procedure Set_Right (Node : Node_Access; Right : Node_Access);
pragma Inline (Set_Right);
--------------------------
-- Local Instantiations --
--------------------------
procedure Free_Element is
new Ada.Unchecked_Deallocation (Element_Type, Element_Access);
package Tree_Operations is
new Red_Black_Trees.Generic_Operations (Tree_Types);
procedure Delete_Tree is
new Tree_Operations.Generic_Delete_Tree (Free);
function Copy_Tree is
new Tree_Operations.Generic_Copy_Tree (Copy_Node, Delete_Tree);
use Tree_Operations;
package Element_Keys is
new Red_Black_Trees.Generic_Keys
(Tree_Operations => Tree_Operations,
Key_Type => Element_Type,
Is_Less_Key_Node => Is_Less_Element_Node,
Is_Greater_Key_Node => Is_Greater_Element_Node);
package Set_Ops is
new Generic_Set_Operations
(Tree_Operations => Tree_Operations,
Insert_With_Hint => Insert_With_Hint,
Copy_Tree => Copy_Tree,
Delete_Tree => Delete_Tree,
Is_Less => Is_Less_Node_Node,
Free => Free);
---------
-- "<" --
---------
function "<" (Left, Right : Cursor) return Boolean is
begin
if Checks and then Left.Node = null then
raise Constraint_Error with "Left cursor equals No_Element";
end if;
if Checks and then Right.Node = null then
raise Constraint_Error with "Right cursor equals No_Element";
end if;
if Checks and then Left.Node.Element = null then
raise Program_Error with "Left cursor is bad";
end if;
if Checks and then Right.Node.Element = null then
raise Program_Error with "Right cursor is bad";
end if;
pragma Assert (Vet (Left.Container.Tree, Left.Node),
"bad Left cursor in ""<""");
pragma Assert (Vet (Right.Container.Tree, Right.Node),
"bad Right cursor in ""<""");
return Left.Node.Element.all < Right.Node.Element.all;
end "<";
function "<" (Left : Cursor; Right : Element_Type) return Boolean is
begin
if Checks and then Left.Node = null then
raise Constraint_Error with "Left cursor equals No_Element";
end if;
if Checks and then Left.Node.Element = null then
raise Program_Error with "Left cursor is bad";
end if;
pragma Assert (Vet (Left.Container.Tree, Left.Node),
"bad Left cursor in ""<""");
return Left.Node.Element.all < Right;
end "<";
function "<" (Left : Element_Type; Right : Cursor) return Boolean is
begin
if Checks and then Right.Node = null then
raise Constraint_Error with "Right cursor equals No_Element";
end if;
if Checks and then Right.Node.Element = null then
raise Program_Error with "Right cursor is bad";
end if;
pragma Assert (Vet (Right.Container.Tree, Right.Node),
"bad Right cursor in ""<""");
return Left < Right.Node.Element.all;
end "<";
---------
-- "=" --
---------
function "=" (Left, Right : Set) return Boolean is
function Is_Equal_Node_Node (L, R : Node_Access) return Boolean;
pragma Inline (Is_Equal_Node_Node);
function Is_Equal is
new Tree_Operations.Generic_Equal (Is_Equal_Node_Node);
------------------------
-- Is_Equal_Node_Node --
------------------------
function Is_Equal_Node_Node (L, R : Node_Access) return Boolean is
begin
return L.Element.all = R.Element.all;
end Is_Equal_Node_Node;
-- Start of processing for "="
begin
return Is_Equal (Left.Tree, Right.Tree);
end "=";
---------
-- ">" --
---------
function ">" (Left, Right : Cursor) return Boolean is
begin
if Checks and then Left.Node = null then
raise Constraint_Error with "Left cursor equals No_Element";
end if;
if Checks and then Right.Node = null then
raise Constraint_Error with "Right cursor equals No_Element";
end if;
if Checks and then Left.Node.Element = null then
raise Program_Error with "Left cursor is bad";
end if;
if Checks and then Right.Node.Element = null then
raise Program_Error with "Right cursor is bad";
end if;
pragma Assert (Vet (Left.Container.Tree, Left.Node),
"bad Left cursor in "">""");
pragma Assert (Vet (Right.Container.Tree, Right.Node),
"bad Right cursor in "">""");
-- L > R same as R < L
return Right.Node.Element.all < Left.Node.Element.all;
end ">";
function ">" (Left : Cursor; Right : Element_Type) return Boolean is
begin
if Checks and then Left.Node = null then
raise Constraint_Error with "Left cursor equals No_Element";
end if;
if Checks and then Left.Node.Element = null then
raise Program_Error with "Left cursor is bad";
end if;
pragma Assert (Vet (Left.Container.Tree, Left.Node),
"bad Left cursor in "">""");
return Right < Left.Node.Element.all;
end ">";
function ">" (Left : Element_Type; Right : Cursor) return Boolean is
begin
if Checks and then Right.Node = null then
raise Constraint_Error with "Right cursor equals No_Element";
end if;
if Checks and then Right.Node.Element = null then
raise Program_Error with "Right cursor is bad";
end if;
pragma Assert (Vet (Right.Container.Tree, Right.Node),
"bad Right cursor in "">""");
return Right.Node.Element.all < Left;
end ">";
------------
-- Adjust --
------------
procedure Adjust is new Tree_Operations.Generic_Adjust (Copy_Tree);
procedure Adjust (Container : in out Set) is
begin
Adjust (Container.Tree);
end Adjust;
------------
-- Assign --
------------
procedure Assign (Target : in out Set; Source : Set) is
begin
if Target'Address = Source'Address then
return;
end if;
Target.Clear;
Target.Union (Source);
end Assign;
-------------
-- Ceiling --
-------------
function Ceiling (Container : Set; Item : Element_Type) return Cursor is
Node : constant Node_Access :=
Element_Keys.Ceiling (Container.Tree, Item);
begin
return (if Node = null then No_Element
else Cursor'(Container'Unrestricted_Access, Node));
end Ceiling;
-----------
-- Clear --
-----------
procedure Clear is
new Tree_Operations.Generic_Clear (Delete_Tree);
procedure Clear (Container : in out Set) is
begin
Clear (Container.Tree);
end Clear;
-----------
-- Color --
-----------
function Color (Node : Node_Access) return Color_Type is
begin
return Node.Color;
end Color;
------------------------
-- Constant_Reference --
------------------------
function Constant_Reference
(Container : aliased Set;
Position : Cursor) return Constant_Reference_Type
is
begin
if Checks and then Position.Container = null then
raise Constraint_Error with "Position cursor has no element";
end if;
if Checks and then Position.Container /= Container'Unrestricted_Access
then
raise Program_Error with
"Position cursor designates wrong container";
end if;
if Checks and then Position.Node.Element = null then
raise Program_Error with "Node has no element";
end if;
pragma Assert
(Vet (Container.Tree, Position.Node),
"bad cursor in Constant_Reference");
declare
Tree : Tree_Type renames Position.Container.all.Tree;
TC : constant Tamper_Counts_Access :=
Tree.TC'Unrestricted_Access;
begin
return R : constant Constant_Reference_Type :=
(Element => Position.Node.Element.all'Access,
Control => (Controlled with TC))
do
Lock (TC.all);
end return;
end;
end Constant_Reference;
--------------
-- Contains --
--------------
function Contains (Container : Set; Item : Element_Type) return Boolean is
begin
return Find (Container, Item) /= No_Element;
end Contains;
----------
-- Copy --
----------
function Copy (Source : Set) return Set is
begin
return Target : Set do
Target.Assign (Source);
end return;
end Copy;
---------------
-- Copy_Node --
---------------
function Copy_Node (Source : Node_Access) return Node_Access is
Element : Element_Access := new Element_Type'(Source.Element.all);
begin
return new Node_Type'(Parent => null,
Left => null,
Right => null,
Color => Source.Color,
Element => Element);
exception
when others =>
Free_Element (Element);
raise;
end Copy_Node;
------------
-- Delete --
------------
procedure Delete (Container : in out Set; Position : in out Cursor) is
begin
if Checks and then Position.Node = null then
raise Constraint_Error with "Position cursor equals No_Element";
end if;
if Checks and then Position.Node.Element = null then
raise Program_Error with "Position cursor is bad";
end if;
if Checks and then Position.Container /= Container'Unrestricted_Access
then
raise Program_Error with "Position cursor designates wrong set";
end if;
pragma Assert (Vet (Container.Tree, Position.Node),
"bad cursor in Delete");
Tree_Operations.Delete_Node_Sans_Free (Container.Tree, Position.Node);
Free (Position.Node);
Position.Container := null;
end Delete;
procedure Delete (Container : in out Set; Item : Element_Type) is
X : Node_Access := Element_Keys.Find (Container.Tree, Item);
begin
if Checks and then X = null then
raise Constraint_Error with "attempt to delete element not in set";
end if;
Tree_Operations.Delete_Node_Sans_Free (Container.Tree, X);
Free (X);
end Delete;
------------------
-- Delete_First --
------------------
procedure Delete_First (Container : in out Set) is
Tree : Tree_Type renames Container.Tree;
X : Node_Access := Tree.First;
begin
if X /= null then
Tree_Operations.Delete_Node_Sans_Free (Tree, X);
Free (X);
end if;
end Delete_First;
-----------------
-- Delete_Last --
-----------------
procedure Delete_Last (Container : in out Set) is
Tree : Tree_Type renames Container.Tree;
X : Node_Access := Tree.Last;
begin
if X /= null then
Tree_Operations.Delete_Node_Sans_Free (Tree, X);
Free (X);
end if;
end Delete_Last;
----------------
-- Difference --
----------------
procedure Difference (Target : in out Set; Source : Set) is
begin
Set_Ops.Difference (Target.Tree, Source.Tree);
end Difference;
function Difference (Left, Right : Set) return Set is
Tree : constant Tree_Type := Set_Ops.Difference (Left.Tree, Right.Tree);
begin
return Set'(Controlled with Tree);
end Difference;
-------------
-- Element --
-------------
function Element (Position : Cursor) return Element_Type is
begin
if Checks and then Position.Node = null then
raise Constraint_Error with "Position cursor equals No_Element";
end if;
if Checks and then Position.Node.Element = null then
raise Program_Error with "Position cursor is bad";
end if;
if Checks
and then (Left (Position.Node) = Position.Node
or else
Right (Position.Node) = Position.Node)
then
raise Program_Error with "dangling cursor";
end if;
pragma Assert (Vet (Position.Container.Tree, Position.Node),
"bad cursor in Element");
return Position.Node.Element.all;
end Element;
-------------------------
-- Equivalent_Elements --
-------------------------
function Equivalent_Elements (Left, Right : Element_Type) return Boolean is
begin
if Left < Right or else Right < Left then
return False;
else
return True;
end if;
end Equivalent_Elements;
---------------------
-- Equivalent_Sets --
---------------------
function Equivalent_Sets (Left, Right : Set) return Boolean is
function Is_Equivalent_Node_Node (L, R : Node_Access) return Boolean;
pragma Inline (Is_Equivalent_Node_Node);
function Is_Equivalent is
new Tree_Operations.Generic_Equal (Is_Equivalent_Node_Node);
-----------------------------
-- Is_Equivalent_Node_Node --
-----------------------------
function Is_Equivalent_Node_Node (L, R : Node_Access) return Boolean is
begin
if L.Element.all < R.Element.all then
return False;
elsif R.Element.all < L.Element.all then
return False;
else
return True;
end if;
end Is_Equivalent_Node_Node;
-- Start of processing for Equivalent_Sets
begin
return Is_Equivalent (Left.Tree, Right.Tree);
end Equivalent_Sets;
-------------
-- Exclude --
-------------
procedure Exclude (Container : in out Set; Item : Element_Type) is
X : Node_Access := Element_Keys.Find (Container.Tree, Item);
begin
if X /= null then
Tree_Operations.Delete_Node_Sans_Free (Container.Tree, X);
Free (X);
end if;
end Exclude;
--------------
-- Finalize --
--------------
procedure Finalize (Object : in out Iterator) is
begin
if Object.Container /= null then
Unbusy (Object.Container.Tree.TC);
end if;
end Finalize;
----------
-- Find --
----------
function Find (Container : Set; Item : Element_Type) return Cursor is
Node : constant Node_Access := Element_Keys.Find (Container.Tree, Item);
begin
if Node = null then
return No_Element;
else
return Cursor'(Container'Unrestricted_Access, Node);
end if;
end Find;
-----------
-- First --
-----------
function First (Container : Set) return Cursor is
begin
return
(if Container.Tree.First = null then No_Element
else Cursor'(Container'Unrestricted_Access, Container.Tree.First));
end First;
function First (Object : Iterator) return Cursor is
begin
-- The value of the iterator object's Node component influences the
-- behavior of the First (and Last) selector function.
-- When the Node component is null, this means the iterator object was
-- constructed without a start expression, in which case the (forward)
-- iteration starts from the (logical) beginning of the entire sequence
-- of items (corresponding to Container.First, for a forward iterator).
-- Otherwise, this is iteration over a partial sequence of items. When
-- the Node component is non-null, the iterator object was constructed
-- with a start expression, that specifies the position from which the
-- (forward) partial iteration begins.
if Object.Node = null then
return Object.Container.First;
else
return Cursor'(Object.Container, Object.Node);
end if;
end First;
-------------------
-- First_Element --
-------------------
function First_Element (Container : Set) return Element_Type is
begin
if Checks and then Container.Tree.First = null then
raise Constraint_Error with "set is empty";
end if;
return Container.Tree.First.Element.all;
end First_Element;
-----------
-- Floor --
-----------
function Floor (Container : Set; Item : Element_Type) return Cursor is
Node : constant Node_Access := Element_Keys.Floor (Container.Tree, Item);
begin
return (if Node = null then No_Element
else Cursor'(Container'Unrestricted_Access, Node));
end Floor;
----------
-- Free --
----------
procedure Free (X : in out Node_Access) is
procedure Deallocate is
new Ada.Unchecked_Deallocation (Node_Type, Node_Access);
begin
if X = null then
return;
end if;
X.Parent := X;
X.Left := X;
X.Right := X;
begin
Free_Element (X.Element);
exception
when others =>
X.Element := null;
Deallocate (X);
raise;
end;
Deallocate (X);
end Free;
------------------
-- Generic_Keys --
------------------
package body Generic_Keys is
-----------------------
-- Local Subprograms --
-----------------------
function Is_Greater_Key_Node
(Left : Key_Type;
Right : Node_Access) return Boolean;
pragma Inline (Is_Greater_Key_Node);
function Is_Less_Key_Node
(Left : Key_Type;
Right : Node_Access) return Boolean;
pragma Inline (Is_Less_Key_Node);
--------------------------
-- Local Instantiations --
--------------------------
package Key_Keys is
new Red_Black_Trees.Generic_Keys
(Tree_Operations => Tree_Operations,
Key_Type => Key_Type,
Is_Less_Key_Node => Is_Less_Key_Node,
Is_Greater_Key_Node => Is_Greater_Key_Node);
-------------
-- Ceiling --
-------------
function Ceiling (Container : Set; Key : Key_Type) return Cursor is
Node : constant Node_Access := Key_Keys.Ceiling (Container.Tree, Key);
begin
return (if Node = null then No_Element
else Cursor'(Container'Unrestricted_Access, Node));
end Ceiling;
------------------------
-- Constant_Reference --
------------------------
function Constant_Reference
(Container : aliased Set;
Key : Key_Type) return Constant_Reference_Type
is
Node : constant Node_Access := Key_Keys.Find (Container.Tree, Key);
begin
if Checks and then Node = null then
raise Constraint_Error with "Key not in set";
end if;
if Checks and then Node.Element = null then
raise Program_Error with "Node has no element";
end if;
declare
Tree : Tree_Type renames Container'Unrestricted_Access.all.Tree;
TC : constant Tamper_Counts_Access :=
Tree.TC'Unrestricted_Access;
begin
return R : constant Constant_Reference_Type :=
(Element => Node.Element.all'Access,
Control => (Controlled with TC))
do
Lock (TC.all);
end return;
end;
end Constant_Reference;
--------------
-- Contains --
--------------
function Contains (Container : Set; Key : Key_Type) return Boolean is
begin
return Find (Container, Key) /= No_Element;
end Contains;
------------
-- Delete --
------------
procedure Delete (Container : in out Set; Key : Key_Type) is
X : Node_Access := Key_Keys.Find (Container.Tree, Key);
begin
if Checks and then X = null then
raise Constraint_Error with "attempt to delete key not in set";
end if;
Tree_Operations.Delete_Node_Sans_Free (Container.Tree, X);
Free (X);
end Delete;
-------------
-- Element --
-------------
function Element (Container : Set; Key : Key_Type) return Element_Type is
Node : constant Node_Access := Key_Keys.Find (Container.Tree, Key);
begin
if Checks and then Node = null then
raise Constraint_Error with "key not in set";
end if;
return Node.Element.all;
end Element;
---------------------
-- Equivalent_Keys --
---------------------
function Equivalent_Keys (Left, Right : Key_Type) return Boolean is
begin
if Left < Right or else Right < Left then
return False;
else
return True;
end if;
end Equivalent_Keys;
-------------
-- Exclude --
-------------
procedure Exclude (Container : in out Set; Key : Key_Type) is
X : Node_Access := Key_Keys.Find (Container.Tree, Key);
begin
if X /= null then
Tree_Operations.Delete_Node_Sans_Free (Container.Tree, X);
Free (X);
end if;
end Exclude;
--------------
-- Finalize --
--------------
procedure Finalize (Control : in out Reference_Control_Type) is
begin
if Control.Container /= null then
Impl.Reference_Control_Type (Control).Finalize;
if Checks and then not (Key (Control.Pos) = Control.Old_Key.all)
then
Delete (Control.Container.all, Key (Control.Pos));
raise Program_Error;
end if;
Control.Container := null;
Control.Old_Key := null;
end if;
end Finalize;
----------
-- Find --
----------
function Find (Container : Set; Key : Key_Type) return Cursor is
Node : constant Node_Access := Key_Keys.Find (Container.Tree, Key);
begin
return (if Node = null then No_Element
else Cursor'(Container'Unrestricted_Access, Node));
end Find;
-----------
-- Floor --
-----------
function Floor (Container : Set; Key : Key_Type) return Cursor is
Node : constant Node_Access := Key_Keys.Floor (Container.Tree, Key);
begin
return (if Node = null then No_Element
else Cursor'(Container'Unrestricted_Access, Node));
end Floor;
-------------------------
-- Is_Greater_Key_Node --
-------------------------
function Is_Greater_Key_Node
(Left : Key_Type;
Right : Node_Access) return Boolean
is
begin
return Key (Right.Element.all) < Left;
end Is_Greater_Key_Node;
----------------------
-- Is_Less_Key_Node --
----------------------
function Is_Less_Key_Node
(Left : Key_Type;
Right : Node_Access) return Boolean
is
begin
return Left < Key (Right.Element.all);
end Is_Less_Key_Node;
---------
-- Key --
---------
function Key (Position : Cursor) return Key_Type is
begin
if Checks and then Position.Node = null then
raise Constraint_Error with
"Position cursor equals No_Element";
end if;
if Checks and then Position.Node.Element = null then
raise Program_Error with
"Position cursor is bad";
end if;
pragma Assert (Vet (Position.Container.Tree, Position.Node),
"bad cursor in Key");
return Key (Position.Node.Element.all);
end Key;
-------------
-- Replace --
-------------
procedure Replace
(Container : in out Set;
Key : Key_Type;
New_Item : Element_Type)
is
Node : constant Node_Access := Key_Keys.Find (Container.Tree, Key);
begin
if Checks and then Node = null then
raise Constraint_Error with
"attempt to replace key not in set";
end if;
Replace_Element (Container.Tree, Node, New_Item);
end Replace;
----------
-- Read --
----------
procedure Read
(Stream : not null access Root_Stream_Type'Class;
Item : out Reference_Type)
is
begin
raise Program_Error with "attempt to stream reference";
end Read;
------------------------------
-- Reference_Preserving_Key --
------------------------------
function Reference_Preserving_Key
(Container : aliased in out Set;
Position : Cursor) return Reference_Type
is
begin
if Checks and then Position.Container = null then
raise Constraint_Error with "Position cursor has no element";
end if;
if Checks and then Position.Container /= Container'Unrestricted_Access
then
raise Program_Error with
"Position cursor designates wrong container";
end if;
if Checks and then Position.Node.Element = null then
raise Program_Error with "Node has no element";
end if;
pragma Assert
(Vet (Container.Tree, Position.Node),
"bad cursor in function Reference_Preserving_Key");
declare
Tree : Tree_Type renames Container.Tree;
begin
return R : constant Reference_Type :=
(Element => Position.Node.Element.all'Unchecked_Access,
Control =>
(Controlled with
Tree.TC'Unrestricted_Access,
Container => Container'Access,
Pos => Position,
Old_Key => new Key_Type'(Key (Position))))
do
Lock (Tree.TC);
end return;
end;
end Reference_Preserving_Key;
function Reference_Preserving_Key
(Container : aliased in out Set;
Key : Key_Type) return Reference_Type
is
Node : constant Node_Access := Key_Keys.Find (Container.Tree, Key);
begin
if Checks and then Node = null then
raise Constraint_Error with "Key not in set";
end if;
if Checks and then Node.Element = null then
raise Program_Error with "Node has no element";
end if;
declare
Tree : Tree_Type renames Container.Tree;
begin
return R : constant Reference_Type :=
(Element => Node.Element.all'Unchecked_Access,
Control =>
(Controlled with
Tree.TC'Unrestricted_Access,
Container => Container'Access,
Pos => Find (Container, Key),
Old_Key => new Key_Type'(Key)))
do
Lock (Tree.TC);
end return;
end;
end Reference_Preserving_Key;
-----------------------------------
-- Update_Element_Preserving_Key --
-----------------------------------
procedure Update_Element_Preserving_Key
(Container : in out Set;
Position : Cursor;
Process : not null access
procedure (Element : in out Element_Type))
is
Tree : Tree_Type renames Container.Tree;
begin
if Checks and then Position.Node = null then
raise Constraint_Error with "Position cursor equals No_Element";
end if;
if Checks and then Position.Node.Element = null then
raise Program_Error with "Position cursor is bad";
end if;
if Checks and then Position.Container /= Container'Unrestricted_Access
then
raise Program_Error with "Position cursor designates wrong set";
end if;
pragma Assert (Vet (Container.Tree, Position.Node),
"bad cursor in Update_Element_Preserving_Key");
declare
E : Element_Type renames Position.Node.Element.all;
K : constant Key_Type := Key (E);
Lock : With_Lock (Tree.TC'Unrestricted_Access);
begin
Process (E);
if Equivalent_Keys (K, Key (E)) then
return;
end if;
end;
declare
X : Node_Access := Position.Node;
begin
Tree_Operations.Delete_Node_Sans_Free (Tree, X);
Free (X);
end;
raise Program_Error with "key was modified";
end Update_Element_Preserving_Key;
-----------
-- Write --
-----------
procedure Write
(Stream : not null access Root_Stream_Type'Class;
Item : Reference_Type)
is
begin
raise Program_Error with "attempt to stream reference";
end Write;
end Generic_Keys;
------------------------
-- Get_Element_Access --
------------------------
function Get_Element_Access
(Position : Cursor) return not null Element_Access is
begin
return Position.Node.Element;
end Get_Element_Access;
-----------------
-- Has_Element --
-----------------
function Has_Element (Position : Cursor) return Boolean is
begin
return Position /= No_Element;
end Has_Element;
-------------
-- Include --
-------------
procedure Include (Container : in out Set; New_Item : Element_Type) is
Position : Cursor;
Inserted : Boolean;
X : Element_Access;
begin
Insert (Container, New_Item, Position, Inserted);
if not Inserted then
TE_Check (Container.Tree.TC);
declare
-- The element allocator may need an accessibility check in the
-- case the actual type is class-wide or has access discriminants
-- (see RM 4.8(10.1) and AI12-0035).
pragma Unsuppress (Accessibility_Check);
begin
X := Position.Node.Element;
Position.Node.Element := new Element_Type'(New_Item);
Free_Element (X);
end;
end if;
end Include;
------------
-- Insert --
------------
procedure Insert
(Container : in out Set;
New_Item : Element_Type;
Position : out Cursor;
Inserted : out Boolean)
is
begin
Insert_Sans_Hint
(Container.Tree,
New_Item,
Position.Node,
Inserted);
Position.Container := Container'Unrestricted_Access;
end Insert;
procedure Insert (Container : in out Set; New_Item : Element_Type) is
Position : Cursor;
pragma Unreferenced (Position);
Inserted : Boolean;
begin
Insert (Container, New_Item, Position, Inserted);
if Checks and then not Inserted then
raise Constraint_Error with
"attempt to insert element already in set";
end if;
end Insert;
----------------------
-- Insert_Sans_Hint --
----------------------
procedure Insert_Sans_Hint
(Tree : in out Tree_Type;
New_Item : Element_Type;
Node : out Node_Access;
Inserted : out Boolean)
is
function New_Node return Node_Access;
pragma Inline (New_Node);
procedure Insert_Post is
new Element_Keys.Generic_Insert_Post (New_Node);
procedure Conditional_Insert_Sans_Hint is
new Element_Keys.Generic_Conditional_Insert (Insert_Post);
--------------
-- New_Node --
--------------
function New_Node return Node_Access is
-- The element allocator may need an accessibility check in the case
-- the actual type is class-wide or has access discriminants (see
-- RM 4.8(10.1) and AI12-0035).
pragma Unsuppress (Accessibility_Check);
Element : Element_Access := new Element_Type'(New_Item);
begin
return new Node_Type'(Parent => null,
Left => null,
Right => null,
Color => Red_Black_Trees.Red,
Element => Element);
exception
when others =>
Free_Element (Element);
raise;
end New_Node;
-- Start of processing for Insert_Sans_Hint
begin
Conditional_Insert_Sans_Hint
(Tree,
New_Item,
Node,
Inserted);
end Insert_Sans_Hint;
----------------------
-- Insert_With_Hint --
----------------------
procedure Insert_With_Hint
(Dst_Tree : in out Tree_Type;
Dst_Hint : Node_Access;
Src_Node : Node_Access;
Dst_Node : out Node_Access)
is
Success : Boolean;
pragma Unreferenced (Success);
function New_Node return Node_Access;
procedure Insert_Post is
new Element_Keys.Generic_Insert_Post (New_Node);
procedure Insert_Sans_Hint is
new Element_Keys.Generic_Conditional_Insert (Insert_Post);
procedure Insert_With_Hint is
new Element_Keys.Generic_Conditional_Insert_With_Hint
(Insert_Post,
Insert_Sans_Hint);
--------------
-- New_Node --
--------------
function New_Node return Node_Access is
Element : Element_Access := new Element_Type'(Src_Node.Element.all);
Node : Node_Access;
begin
begin
Node := new Node_Type;
exception
when others =>
Free_Element (Element);
raise;
end;
Node.Element := Element;
return Node;
end New_Node;
-- Start of processing for Insert_With_Hint
begin
Insert_With_Hint
(Dst_Tree,
Dst_Hint,
Src_Node.Element.all,
Dst_Node,
Success);
end Insert_With_Hint;
------------------
-- Intersection --
------------------
procedure Intersection (Target : in out Set; Source : Set) is
begin
Set_Ops.Intersection (Target.Tree, Source.Tree);
end Intersection;
function Intersection (Left, Right : Set) return Set is
Tree : constant Tree_Type :=
Set_Ops.Intersection (Left.Tree, Right.Tree);
begin
return Set'(Controlled with Tree);
end Intersection;
--------------
-- Is_Empty --
--------------
function Is_Empty (Container : Set) return Boolean is
begin
return Container.Tree.Length = 0;
end Is_Empty;
-----------------------------
-- Is_Greater_Element_Node --
-----------------------------
function Is_Greater_Element_Node
(Left : Element_Type;
Right : Node_Access) return Boolean
is
begin
-- e > node same as node < e
return Right.Element.all < Left;
end Is_Greater_Element_Node;
--------------------------
-- Is_Less_Element_Node --
--------------------------
function Is_Less_Element_Node
(Left : Element_Type;
Right : Node_Access) return Boolean
is
begin
return Left < Right.Element.all;
end Is_Less_Element_Node;
-----------------------
-- Is_Less_Node_Node --
-----------------------
function Is_Less_Node_Node (L, R : Node_Access) return Boolean is
begin
return L.Element.all < R.Element.all;
end Is_Less_Node_Node;
---------------
-- Is_Subset --
---------------
function Is_Subset (Subset : Set; Of_Set : Set) return Boolean is
begin
return Set_Ops.Is_Subset (Subset => Subset.Tree, Of_Set => Of_Set.Tree);
end Is_Subset;
-------------
-- Iterate --
-------------
procedure Iterate
(Container : Set;
Process : not null access procedure (Position : Cursor))
is
procedure Process_Node (Node : Node_Access);
pragma Inline (Process_Node);
procedure Local_Iterate is
new Tree_Operations.Generic_Iteration (Process_Node);
------------------
-- Process_Node --
------------------
procedure Process_Node (Node : Node_Access) is
begin
Process (Cursor'(Container'Unrestricted_Access, Node));
end Process_Node;
T : Tree_Type renames Container'Unrestricted_Access.all.Tree;
Busy : With_Busy (T.TC'Unrestricted_Access);
-- Start of processing for Iterate
begin
Local_Iterate (T);
end Iterate;
function Iterate
(Container : Set)
return Set_Iterator_Interfaces.Reversible_Iterator'class
is
begin
-- The value of the Node component influences the behavior of the First
-- and Last selector functions of the iterator object. When the Node
-- component is null (as is the case here), this means the iterator
-- object was constructed without a start expression. This is a complete
-- iterator, meaning that the iteration starts from the (logical)
-- beginning of the sequence of items.
-- Note: For a forward iterator, Container.First is the beginning, and
-- for a reverse iterator, Container.Last is the beginning.
return It : constant Iterator :=
Iterator'(Limited_Controlled with
Container => Container'Unrestricted_Access,
Node => null)
do
Busy (Container.Tree.TC'Unrestricted_Access.all);
end return;
end Iterate;
function Iterate
(Container : Set;
Start : Cursor)
return Set_Iterator_Interfaces.Reversible_Iterator'class
is
begin
-- It was formerly the case that when Start = No_Element, the partial
-- iterator was defined to behave the same as for a complete iterator,
-- and iterate over the entire sequence of items. However, those
-- semantics were unintuitive and arguably error-prone (it is too easy
-- to accidentally create an endless loop), and so they were changed,
-- per the ARG meeting in Denver on 2011/11. However, there was no
-- consensus about what positive meaning this corner case should have,
-- and so it was decided to simply raise an exception. This does imply,
-- however, that it is not possible to use a partial iterator to specify
-- an empty sequence of items.
if Checks and then Start = No_Element then
raise Constraint_Error with
"Start position for iterator equals No_Element";
end if;
if Checks and then Start.Container /= Container'Unrestricted_Access then
raise Program_Error with
"Start cursor of Iterate designates wrong set";
end if;
pragma Assert (Vet (Container.Tree, Start.Node),
"Start cursor of Iterate is bad");
-- The value of the Node component influences the behavior of the First
-- and Last selector functions of the iterator object. When the Node
-- component is non-null (as is the case here), it means that this is a
-- partial iteration, over a subset of the complete sequence of
-- items. The iterator object was constructed with a start expression,
-- indicating the position from which the iteration begins. Note that
-- the start position has the same value irrespective of whether this is
-- a forward or reverse iteration.
return It : constant Iterator :=
(Limited_Controlled with
Container => Container'Unrestricted_Access,
Node => Start.Node)
do
Busy (Container.Tree.TC'Unrestricted_Access.all);
end return;
end Iterate;
----------
-- Last --
----------
function Last (Container : Set) return Cursor is
begin
return
(if Container.Tree.Last = null then No_Element
else Cursor'(Container'Unrestricted_Access, Container.Tree.Last));
end Last;
function Last (Object : Iterator) return Cursor is
begin
-- The value of the iterator object's Node component influences the
-- behavior of the Last (and First) selector function.
-- When the Node component is null, this means the iterator object was
-- constructed without a start expression, in which case the (reverse)
-- iteration starts from the (logical) beginning of the entire sequence
-- (corresponding to Container.Last, for a reverse iterator).
-- Otherwise, this is iteration over a partial sequence of items. When
-- the Node component is non-null, the iterator object was constructed
-- with a start expression, that specifies the position from which the
-- (reverse) partial iteration begins.
if Object.Node = null then
return Object.Container.Last;
else
return Cursor'(Object.Container, Object.Node);
end if;
end Last;
------------------
-- Last_Element --
------------------
function Last_Element (Container : Set) return Element_Type is
begin
if Checks and then Container.Tree.Last = null then
raise Constraint_Error with "set is empty";
end if;
return Container.Tree.Last.Element.all;
end Last_Element;
----------
-- Left --
----------
function Left (Node : Node_Access) return Node_Access is
begin
return Node.Left;
end Left;
------------
-- Length --
------------
function Length (Container : Set) return Count_Type is
begin
return Container.Tree.Length;
end Length;
----------
-- Move --
----------
procedure Move is new Tree_Operations.Generic_Move (Clear);
procedure Move (Target : in out Set; Source : in out Set) is
begin
Move (Target => Target.Tree, Source => Source.Tree);
end Move;
----------
-- Next --
----------
procedure Next (Position : in out Cursor) is
begin
Position := Next (Position);
end Next;
function Next (Position : Cursor) return Cursor is
begin
if Position = No_Element then
return No_Element;
end if;
if Checks and then Position.Node.Element = null then
raise Program_Error with "Position cursor is bad";
end if;
pragma Assert (Vet (Position.Container.Tree, Position.Node),
"bad cursor in Next");
declare
Node : constant Node_Access := Tree_Operations.Next (Position.Node);
begin
return (if Node = null then No_Element
else Cursor'(Position.Container, Node));
end;
end Next;
function Next
(Object : Iterator;
Position : Cursor) return Cursor
is
begin
if Position.Container = null then
return No_Element;
end if;
if Checks and then Position.Container /= Object.Container then
raise Program_Error with
"Position cursor of Next designates wrong set";
end if;
return Next (Position);
end Next;
-------------
-- Overlap --
-------------
function Overlap (Left, Right : Set) return Boolean is
begin
return Set_Ops.Overlap (Left.Tree, Right.Tree);
end Overlap;
------------
-- Parent --
------------
function Parent (Node : Node_Access) return Node_Access is
begin
return Node.Parent;
end Parent;
--------------
-- Previous --
--------------
procedure Previous (Position : in out Cursor) is
begin
Position := Previous (Position);
end Previous;
function Previous (Position : Cursor) return Cursor is
begin
if Position = No_Element then
return No_Element;
end if;
if Checks and then Position.Node.Element = null then
raise Program_Error with "Position cursor is bad";
end if;
pragma Assert (Vet (Position.Container.Tree, Position.Node),
"bad cursor in Previous");
declare
Node : constant Node_Access :=
Tree_Operations.Previous (Position.Node);
begin
return (if Node = null then No_Element
else Cursor'(Position.Container, Node));
end;
end Previous;
function Previous
(Object : Iterator;
Position : Cursor) return Cursor
is
begin
if Position.Container = null then
return No_Element;
end if;
if Checks and then Position.Container /= Object.Container then
raise Program_Error with
"Position cursor of Previous designates wrong set";
end if;
return Previous (Position);
end Previous;
----------------------
-- Pseudo_Reference --
----------------------
function Pseudo_Reference
(Container : aliased Set'Class) return Reference_Control_Type
is
TC : constant Tamper_Counts_Access :=
Container.Tree.TC'Unrestricted_Access;
begin
return R : constant Reference_Control_Type := (Controlled with TC) do
Lock (TC.all);
end return;
end Pseudo_Reference;
-------------------
-- Query_Element --
-------------------
procedure Query_Element
(Position : Cursor;
Process : not null access procedure (Element : Element_Type))
is
begin
if Checks and then Position.Node = null then
raise Constraint_Error with "Position cursor equals No_Element";
end if;
if Checks and then Position.Node.Element = null then
raise Program_Error with "Position cursor is bad";
end if;
pragma Assert (Vet (Position.Container.Tree, Position.Node),
"bad cursor in Query_Element");
declare
T : Tree_Type renames Position.Container.Tree;
Lock : With_Lock (T.TC'Unrestricted_Access);
begin
Process (Position.Node.Element.all);
end;
end Query_Element;
----------
-- Read --
----------
procedure Read
(Stream : not null access Root_Stream_Type'Class;
Container : out Set)
is
function Read_Node
(Stream : not null access Root_Stream_Type'Class) return Node_Access;
pragma Inline (Read_Node);
procedure Read is
new Tree_Operations.Generic_Read (Clear, Read_Node);
---------------
-- Read_Node --
---------------
function Read_Node
(Stream : not null access Root_Stream_Type'Class) return Node_Access
is
Node : Node_Access := new Node_Type;
begin
Node.Element := new Element_Type'(Element_Type'Input (Stream));
return Node;
exception
when others =>
Free (Node); -- Note that Free deallocates elem too
raise;
end Read_Node;
-- Start of processing for Read
begin
Read (Stream, Container.Tree);
end Read;
procedure Read
(Stream : not null access Root_Stream_Type'Class;
Item : out Cursor)
is
begin
raise Program_Error with "attempt to stream set cursor";
end Read;
procedure Read
(Stream : not null access Root_Stream_Type'Class;
Item : out Constant_Reference_Type)
is
begin
raise Program_Error with "attempt to stream reference";
end Read;
-------------
-- Replace --
-------------
procedure Replace (Container : in out Set; New_Item : Element_Type) is
Node : constant Node_Access :=
Element_Keys.Find (Container.Tree, New_Item);
X : Element_Access;
pragma Warnings (Off, X);
begin
if Checks and then Node = null then
raise Constraint_Error with "attempt to replace element not in set";
end if;
TE_Check (Container.Tree.TC);
declare
-- The element allocator may need an accessibility check in the case
-- the actual type is class-wide or has access discriminants (see
-- RM 4.8(10.1) and AI12-0035).
pragma Unsuppress (Accessibility_Check);
begin
X := Node.Element;
Node.Element := new Element_Type'(New_Item);
Free_Element (X);
end;
end Replace;
---------------------
-- Replace_Element --
---------------------
procedure Replace_Element
(Tree : in out Tree_Type;
Node : Node_Access;
Item : Element_Type)
is
pragma Assert (Node /= null);
pragma Assert (Node.Element /= null);
function New_Node return Node_Access;
pragma Inline (New_Node);
procedure Local_Insert_Post is
new Element_Keys.Generic_Insert_Post (New_Node);
procedure Local_Insert_Sans_Hint is
new Element_Keys.Generic_Conditional_Insert (Local_Insert_Post);
procedure Local_Insert_With_Hint is
new Element_Keys.Generic_Conditional_Insert_With_Hint
(Local_Insert_Post,
Local_Insert_Sans_Hint);
--------------
-- New_Node --
--------------
function New_Node return Node_Access is
-- The element allocator may need an accessibility check in the case
-- the actual type is class-wide or has access discriminants (see
-- RM 4.8(10.1) and AI12-0035).
pragma Unsuppress (Accessibility_Check);
begin
Node.Element := new Element_Type'(Item); -- OK if fails
Node.Color := Red;
Node.Parent := null;
Node.Right := null;
Node.Left := null;
return Node;
end New_Node;
Hint : Node_Access;
Result : Node_Access;
Inserted : Boolean;
Compare : Boolean;
X : Element_Access := Node.Element;
-- Start of processing for Replace_Element
begin
-- Replace_Element assigns value Item to the element designated by Node,
-- per certain semantic constraints, described as follows.
-- If Item is equivalent to the element, then element is replaced and
-- there's nothing else to do. This is the easy case.
-- If Item is not equivalent, then the node will (possibly) have to move
-- to some other place in the tree. This is slighly more complicated,
-- because we must ensure that Item is not equivalent to some other
-- element in the tree (in which case, the replacement is not allowed).
-- Determine whether Item is equivalent to element on the specified
-- node.
declare
Lock : With_Lock (Tree.TC'Unrestricted_Access);
begin
Compare := (if Item < Node.Element.all then False
elsif Node.Element.all < Item then False
else True);
end;
if Compare then
-- Item is equivalent to the node's element, so we will not have to
-- move the node.
TE_Check (Tree.TC);
declare
-- The element allocator may need an accessibility check in the
-- case the actual type is class-wide or has access discriminants
-- (see RM 4.8(10.1) and AI12-0035).
pragma Unsuppress (Accessibility_Check);
begin
Node.Element := new Element_Type'(Item);
Free_Element (X);
end;
return;
end if;
-- The replacement Item is not equivalent to the element on the
-- specified node, which means that it will need to be re-inserted in a
-- different position in the tree. We must now determine whether Item is
-- equivalent to some other element in the tree (which would prohibit
-- the assignment and hence the move).
-- Ceiling returns the smallest element equivalent or greater than the
-- specified Item; if there is no such element, then it returns null.
Hint := Element_Keys.Ceiling (Tree, Item);
if Hint /= null then
declare
Lock : With_Lock (Tree.TC'Unrestricted_Access);
begin
Compare := Item < Hint.Element.all;
end;
-- Item >= Hint.Element
if Checks and then not Compare then
-- Ceiling returns an element that is equivalent or greater
-- than Item. If Item is "not less than" the element, then
-- by elimination we know that Item is equivalent to the element.
-- But this means that it is not possible to assign the value of
-- Item to the specified element (on Node), because a different
-- element (on Hint) equivalent to Item already exsits. (Were we
-- to change Node's element value, we would have to move Node, but
-- we would be unable to move the Node, because its new position
-- in the tree is already occupied by an equivalent element.)
raise Program_Error with "attempt to replace existing element";
end if;
-- Item is not equivalent to any other element in the tree, so it is
-- safe to assign the value of Item to Node.Element. This means that
-- the node will have to move to a different position in the tree
-- (because its element will have a different value).
-- The nearest (greater) neighbor of Item is Hint. This will be the
-- insertion position of Node (because its element will have Item as
-- its new value).
-- If Node equals Hint, the relative position of Node does not
-- change. This allows us to perform an optimization: we need not
-- remove Node from the tree and then reinsert it with its new value,
-- because it would only be placed in the exact same position.
if Hint = Node then
TE_Check (Tree.TC);
declare
-- The element allocator may need an accessibility check in the
-- case actual type is class-wide or has access discriminants
-- (see RM 4.8(10.1) and AI12-0035).
pragma Unsuppress (Accessibility_Check);
begin
Node.Element := new Element_Type'(Item);
Free_Element (X);
end;
return;
end if;
end if;
-- If we get here, it is because Item was greater than all elements in
-- the tree (Hint = null), or because Item was less than some element at
-- a different place in the tree (Item < Hint.Element.all). In either
-- case, we remove Node from the tree (without actually deallocating
-- it), and then insert Item into the tree, onto the same Node (so no
-- new node is actually allocated).
Tree_Operations.Delete_Node_Sans_Free (Tree, Node); -- Checks busy-bit
Local_Insert_With_Hint
(Tree => Tree,
Position => Hint,
Key => Item,
Node => Result,
Inserted => Inserted);
pragma Assert (Inserted);
pragma Assert (Result = Node);
Free_Element (X);
end Replace_Element;
procedure Replace_Element
(Container : in out Set;
Position : Cursor;
New_Item : Element_Type)
is
begin
if Checks and then Position.Node = null then
raise Constraint_Error with "Position cursor equals No_Element";
end if;
if Checks and then Position.Node.Element = null then
raise Program_Error with "Position cursor is bad";
end if;
if Checks and then Position.Container /= Container'Unrestricted_Access
then
raise Program_Error with "Position cursor designates wrong set";
end if;
pragma Assert (Vet (Container.Tree, Position.Node),
"bad cursor in Replace_Element");
Replace_Element (Container.Tree, Position.Node, New_Item);
end Replace_Element;
---------------------
-- Reverse_Iterate --
---------------------
procedure Reverse_Iterate
(Container : Set;
Process : not null access procedure (Position : Cursor))
is
procedure Process_Node (Node : Node_Access);
pragma Inline (Process_Node);
procedure Local_Reverse_Iterate is
new Tree_Operations.Generic_Reverse_Iteration (Process_Node);
------------------
-- Process_Node --
------------------
procedure Process_Node (Node : Node_Access) is
begin
Process (Cursor'(Container'Unrestricted_Access, Node));
end Process_Node;
T : Tree_Type renames Container.Tree'Unrestricted_Access.all;
Busy : With_Busy (T.TC'Unrestricted_Access);
-- Start of processing for Reverse_Iterate
begin
Local_Reverse_Iterate (T);
end Reverse_Iterate;
-----------
-- Right --
-----------
function Right (Node : Node_Access) return Node_Access is
begin
return Node.Right;
end Right;
---------------
-- Set_Color --
---------------
procedure Set_Color (Node : Node_Access; Color : Color_Type) is
begin
Node.Color := Color;
end Set_Color;
--------------
-- Set_Left --
--------------
procedure Set_Left (Node : Node_Access; Left : Node_Access) is
begin
Node.Left := Left;
end Set_Left;
----------------
-- Set_Parent --
----------------
procedure Set_Parent (Node : Node_Access; Parent : Node_Access) is
begin
Node.Parent := Parent;
end Set_Parent;
---------------
-- Set_Right --
---------------
procedure Set_Right (Node : Node_Access; Right : Node_Access) is
begin
Node.Right := Right;
end Set_Right;
--------------------------
-- Symmetric_Difference --
--------------------------
procedure Symmetric_Difference (Target : in out Set; Source : Set) is
begin
Set_Ops.Symmetric_Difference (Target.Tree, Source.Tree);
end Symmetric_Difference;
function Symmetric_Difference (Left, Right : Set) return Set is
Tree : constant Tree_Type :=
Set_Ops.Symmetric_Difference (Left.Tree, Right.Tree);
begin
return Set'(Controlled with Tree);
end Symmetric_Difference;
------------
-- To_Set --
------------
function To_Set (New_Item : Element_Type) return Set is
Tree : Tree_Type;
Node : Node_Access;
Inserted : Boolean;
pragma Unreferenced (Node, Inserted);
begin
Insert_Sans_Hint (Tree, New_Item, Node, Inserted);
return Set'(Controlled with Tree);
end To_Set;
-----------
-- Union --
-----------
procedure Union (Target : in out Set; Source : Set) is
begin
Set_Ops.Union (Target.Tree, Source.Tree);
end Union;
function Union (Left, Right : Set) return Set is
Tree : constant Tree_Type := Set_Ops.Union (Left.Tree, Right.Tree);
begin
return Set'(Controlled with Tree);
end Union;
-----------
-- Write --
-----------
procedure Write
(Stream : not null access Root_Stream_Type'Class;
Container : Set)
is
procedure Write_Node
(Stream : not null access Root_Stream_Type'Class;
Node : Node_Access);
pragma Inline (Write_Node);
procedure Write is
new Tree_Operations.Generic_Write (Write_Node);
----------------
-- Write_Node --
----------------
procedure Write_Node
(Stream : not null access Root_Stream_Type'Class;
Node : Node_Access)
is
begin
Element_Type'Output (Stream, Node.Element.all);
end Write_Node;
-- Start of processing for Write
begin
Write (Stream, Container.Tree);
end Write;
procedure Write
(Stream : not null access Root_Stream_Type'Class;
Item : Cursor)
is
begin
raise Program_Error with "attempt to stream set cursor";
end Write;
procedure Write
(Stream : not null access Root_Stream_Type'Class;
Item : Constant_Reference_Type)
is
begin
raise Program_Error with "attempt to stream reference";
end Write;
end Ada.Containers.Indefinite_Ordered_Sets;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- U I N T P --
-- --
-- B o d y --
-- --
-- $Revision$
-- --
-- Copyright (C) 1992-2001 Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, --
-- MA 02111-1307, USA. --
-- --
-- As a special exception, if other files instantiate generics from this --
-- unit, or you link this unit with other files to produce an executable, --
-- this unit does not by itself cause the resulting executable to be --
-- covered by the GNU General Public License. This exception does not --
-- however invalidate any other reasons why the executable file might be --
-- covered by the GNU Public License. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Output; use Output;
with Tree_IO; use Tree_IO;
package body Uintp is
------------------------
-- Local Declarations --
------------------------
Uint_Int_First : Uint := Uint_0;
-- Uint value containing Int'First value, set by Initialize. The initial
-- value of Uint_0 is used for an assertion check that ensures that this
-- value is not used before it is initialized. This value is used in the
-- UI_Is_In_Int_Range predicate, and it is right that this is a host
-- value, since the issue is host representation of integer values.
Uint_Int_Last : Uint;
-- Uint value containing Int'Last value set by Initialize.
UI_Power_2 : array (Int range 0 .. 64) of Uint;
-- This table is used to memoize exponentiations by powers of 2. The Nth
-- entry, if set, contains the Uint value 2 ** N. Initially UI_Power_2_Set
-- is zero and only the 0'th entry is set, the invariant being that all
-- entries in the range 0 .. UI_Power_2_Set are initialized.
UI_Power_2_Set : Nat;
-- Number of entries set in UI_Power_2;
UI_Power_10 : array (Int range 0 .. 64) of Uint;
-- This table is used to memoize exponentiations by powers of 10 in the
-- same manner as described above for UI_Power_2.
UI_Power_10_Set : Nat;
-- Number of entries set in UI_Power_10;
Uints_Min : Uint;
Udigits_Min : Int;
-- These values are used to make sure that the mark/release mechanism
-- does not destroy values saved in the U_Power tables. Whenever an
-- entry is made in the U_Power tables, Uints_Min and Udigits_Min are
-- updated to protect the entry, and Release never cuts back beyond
-- these minimum values.
Int_0 : constant Int := 0;
Int_1 : constant Int := 1;
Int_2 : constant Int := 2;
-- These values are used in some cases where the use of numeric literals
-- would cause ambiguities (integer vs Uint).
-----------------------
-- Local Subprograms --
-----------------------
function Direct (U : Uint) return Boolean;
pragma Inline (Direct);
-- Returns True if U is represented directly
function Direct_Val (U : Uint) return Int;
-- U is a Uint for is represented directly. The returned result
-- is the value represented.
function GCD (Jin, Kin : Int) return Int;
-- Compute GCD of two integers. Assumes that Jin >= Kin >= 0
procedure Image_Out
(Input : Uint;
To_Buffer : Boolean;
Format : UI_Format);
-- Common processing for UI_Image and UI_Write, To_Buffer is set
-- True for UI_Image, and false for UI_Write, and Format is copied
-- from the Format parameter to UI_Image or UI_Write.
procedure Init_Operand (UI : Uint; Vec : out UI_Vector);
pragma Inline (Init_Operand);
-- This procedure puts the value of UI into the vector in canonical
-- multiple precision format. The parameter should be of the correct
-- size as determined by a previous call to N_Digits (UI). The first
-- digit of Vec contains the sign, all other digits are always non-
-- negative. Note that the input may be directly represented, and in
-- this case Vec will contain the corresponding one or two digit value.
function Least_Sig_Digit (Arg : Uint) return Int;
pragma Inline (Least_Sig_Digit);
-- Returns the Least Significant Digit of Arg quickly. When the given
-- Uint is less than 2**15, the value returned is the input value, in
-- this case the result may be negative. It is expected that any use
-- will mask off unnecessary bits. This is used for finding Arg mod B
-- where B is a power of two. Hence the actual base is irrelevent as
-- long as it is a power of two.
procedure Most_Sig_2_Digits
(Left : Uint;
Right : Uint;
Left_Hat : out Int;
Right_Hat : out Int);
-- Returns leading two significant digits from the given pair of Uint's.
-- Mathematically: returns Left / (Base ** K) and Right / (Base ** K)
-- where K is as small as possible S.T. Right_Hat < Base * Base.
-- It is required that Left > Right for the algorithm to work.
function N_Digits (Input : Uint) return Int;
pragma Inline (N_Digits);
-- Returns number of "digits" in a Uint
function Sum_Digits (Left : Uint; Sign : Int) return Int;
-- If Sign = 1 return the sum of the "digits" of Abs (Left). If the
-- total has more then one digit then return Sum_Digits of total.
function Sum_Double_Digits (Left : Uint; Sign : Int) return Int;
-- Same as above but work in New_Base = Base * Base
function Vector_To_Uint
(In_Vec : UI_Vector;
Negative : Boolean)
return Uint;
-- Functions that calculate values in UI_Vectors, call this function
-- to create and return the Uint value. In_Vec contains the multiple
-- precision (Base) representation of a non-negative value. Leading
-- zeroes are permitted. Negative is set if the desired result is
-- the negative of the given value. The result will be either the
-- appropriate directly represented value, or a table entry in the
-- proper canonical format is created and returned.
--
-- Note that Init_Operand puts a signed value in the result vector,
-- but Vector_To_Uint is always presented with a non-negative value.
-- The processing of signs is something that is done by the caller
-- before calling Vector_To_Uint.
------------
-- Direct --
------------
function Direct (U : Uint) return Boolean is
begin
return Int (U) <= Int (Uint_Direct_Last);
end Direct;
----------------
-- Direct_Val --
----------------
function Direct_Val (U : Uint) return Int is
begin
pragma Assert (Direct (U));
return Int (U) - Int (Uint_Direct_Bias);
end Direct_Val;
---------
-- GCD --
---------
function GCD (Jin, Kin : Int) return Int is
J, K, Tmp : Int;
begin
pragma Assert (Jin >= Kin);
pragma Assert (Kin >= Int_0);
J := Jin;
K := Kin;
while K /= Uint_0 loop
Tmp := J mod K;
J := K;
K := Tmp;
end loop;
return J;
end GCD;
---------------
-- Image_Out --
---------------
procedure Image_Out
(Input : Uint;
To_Buffer : Boolean;
Format : UI_Format)
is
Marks : constant Uintp.Save_Mark := Uintp.Mark;
Base : Uint;
Ainput : Uint;
Digs_Output : Natural := 0;
-- Counts digits output. In hex mode, but not in decimal mode, we
-- put an underline after every four hex digits that are output.
Exponent : Natural := 0;
-- If the number is too long to fit in the buffer, we switch to an
-- approximate output format with an exponent. This variable records
-- the exponent value.
function Better_In_Hex return Boolean;
-- Determines if it is better to generate digits in base 16 (result
-- is true) or base 10 (result is false). The choice is purely a
-- matter of convenience and aesthetics, so it does not matter which
-- value is returned from a correctness point of view.
procedure Image_Char (C : Character);
-- Internal procedure to output one character
procedure Image_Exponent (N : Natural);
-- Output non-zero exponent. Note that we only use the exponent
-- form in the buffer case, so we know that To_Buffer is true.
procedure Image_Uint (U : Uint);
-- Internal procedure to output characters of non-negative Uint
-------------------
-- Better_In_Hex --
-------------------
function Better_In_Hex return Boolean is
T16 : constant Uint := Uint_2 ** Int'(16);
A : Uint;
begin
A := UI_Abs (Input);
-- Small values up to 2**16 can always be in decimal
if A < T16 then
return False;
end if;
-- Otherwise, see if we are a power of 2 or one less than a power
-- of 2. For the moment these are the only cases printed in hex.
if A mod Uint_2 = Uint_1 then
A := A + Uint_1;
end if;
loop
if A mod T16 /= Uint_0 then
return False;
else
A := A / T16;
end if;
exit when A < T16;
end loop;
while A > Uint_2 loop
if A mod Uint_2 /= Uint_0 then
return False;
else
A := A / Uint_2;
end if;
end loop;
return True;
end Better_In_Hex;
----------------
-- Image_Char --
----------------
procedure Image_Char (C : Character) is
begin
if To_Buffer then
if UI_Image_Length + 6 > UI_Image_Max then
Exponent := Exponent + 1;
else
UI_Image_Length := UI_Image_Length + 1;
UI_Image_Buffer (UI_Image_Length) := C;
end if;
else
Write_Char (C);
end if;
end Image_Char;
--------------------
-- Image_Exponent --
--------------------
procedure Image_Exponent (N : Natural) is
begin
if N >= 10 then
Image_Exponent (N / 10);
end if;
UI_Image_Length := UI_Image_Length + 1;
UI_Image_Buffer (UI_Image_Length) :=
Character'Val (Character'Pos ('0') + N mod 10);
end Image_Exponent;
----------------
-- Image_Uint --
----------------
procedure Image_Uint (U : Uint) is
H : array (Int range 0 .. 15) of Character := "0123456789ABCDEF";
begin
if U >= Base then
Image_Uint (U / Base);
end if;
if Digs_Output = 4 and then Base = Uint_16 then
Image_Char ('_');
Digs_Output := 0;
end if;
Image_Char (H (UI_To_Int (U rem Base)));
Digs_Output := Digs_Output + 1;
end Image_Uint;
-- Start of processing for Image_Out
begin
if Input = No_Uint then
Image_Char ('?');
return;
end if;
UI_Image_Length := 0;
if Input < Uint_0 then
Image_Char ('-');
Ainput := -Input;
else
Ainput := Input;
end if;
if Format = Hex
or else (Format = Auto and then Better_In_Hex)
then
Base := Uint_16;
Image_Char ('1');
Image_Char ('6');
Image_Char ('#');
Image_Uint (Ainput);
Image_Char ('#');
else
Base := Uint_10;
Image_Uint (Ainput);
end if;
if Exponent /= 0 then
UI_Image_Length := UI_Image_Length + 1;
UI_Image_Buffer (UI_Image_Length) := 'E';
Image_Exponent (Exponent);
end if;
Uintp.Release (Marks);
end Image_Out;
-------------------
-- Init_Operand --
-------------------
procedure Init_Operand (UI : Uint; Vec : out UI_Vector) is
Loc : Int;
begin
if Direct (UI) then
Vec (1) := Direct_Val (UI);
if Vec (1) >= Base then
Vec (2) := Vec (1) rem Base;
Vec (1) := Vec (1) / Base;
end if;
else
Loc := Uints.Table (UI).Loc;
for J in 1 .. Uints.Table (UI).Length loop
Vec (J) := Udigits.Table (Loc + J - 1);
end loop;
end if;
end Init_Operand;
----------------
-- Initialize --
----------------
procedure Initialize is
begin
Uints.Init;
Udigits.Init;
Uint_Int_First := UI_From_Int (Int'First);
Uint_Int_Last := UI_From_Int (Int'Last);
UI_Power_2 (0) := Uint_1;
UI_Power_2_Set := 0;
UI_Power_10 (0) := Uint_1;
UI_Power_10_Set := 0;
Uints_Min := Uints.Last;
Udigits_Min := Udigits.Last;
end Initialize;
---------------------
-- Least_Sig_Digit --
---------------------
function Least_Sig_Digit (Arg : Uint) return Int is
V : Int;
begin
if Direct (Arg) then
V := Direct_Val (Arg);
if V >= Base then
V := V mod Base;
end if;
-- Note that this result may be negative
return V;
else
return
Udigits.Table
(Uints.Table (Arg).Loc + Uints.Table (Arg).Length - 1);
end if;
end Least_Sig_Digit;
----------
-- Mark --
----------
function Mark return Save_Mark is
begin
return (Save_Uint => Uints.Last, Save_Udigit => Udigits.Last);
end Mark;
-----------------------
-- Most_Sig_2_Digits --
-----------------------
procedure Most_Sig_2_Digits
(Left : Uint;
Right : Uint;
Left_Hat : out Int;
Right_Hat : out Int)
is
begin
pragma Assert (Left >= Right);
if Direct (Left) then
Left_Hat := Direct_Val (Left);
Right_Hat := Direct_Val (Right);
return;
else
declare
L1 : constant Int :=
Udigits.Table (Uints.Table (Left).Loc);
L2 : constant Int :=
Udigits.Table (Uints.Table (Left).Loc + 1);
begin
-- It is not so clear what to return when Arg is negative???
Left_Hat := abs (L1) * Base + L2;
end;
end if;
declare
Length_L : constant Int := Uints.Table (Left).Length;
Length_R : Int;
R1 : Int;
R2 : Int;
T : Int;
begin
if Direct (Right) then
T := Direct_Val (Left);
R1 := abs (T / Base);
R2 := T rem Base;
Length_R := 2;
else
R1 := abs (Udigits.Table (Uints.Table (Right).Loc));
R2 := Udigits.Table (Uints.Table (Right).Loc + 1);
Length_R := Uints.Table (Right).Length;
end if;
if Length_L = Length_R then
Right_Hat := R1 * Base + R2;
elsif Length_L = Length_R + Int_1 then
Right_Hat := R1;
else
Right_Hat := 0;
end if;
end;
end Most_Sig_2_Digits;
---------------
-- N_Digits --
---------------
-- Note: N_Digits returns 1 for No_Uint
function N_Digits (Input : Uint) return Int is
begin
if Direct (Input) then
if Direct_Val (Input) >= Base then
return 2;
else
return 1;
end if;
else
return Uints.Table (Input).Length;
end if;
end N_Digits;
--------------
-- Num_Bits --
--------------
function Num_Bits (Input : Uint) return Nat is
Bits : Nat;
Num : Nat;
begin
if UI_Is_In_Int_Range (Input) then
Num := UI_To_Int (Input);
Bits := 0;
else
Bits := Base_Bits * (Uints.Table (Input).Length - 1);
Num := abs (Udigits.Table (Uints.Table (Input).Loc));
end if;
while Types.">" (Num, 0) loop
Num := Num / 2;
Bits := Bits + 1;
end loop;
return Bits;
end Num_Bits;
---------
-- pid --
---------
procedure pid (Input : Uint) is
begin
UI_Write (Input, Decimal);
Write_Eol;
end pid;
---------
-- pih --
---------
procedure pih (Input : Uint) is
begin
UI_Write (Input, Hex);
Write_Eol;
end pih;
-------------
-- Release --
-------------
procedure Release (M : Save_Mark) is
begin
Uints.Set_Last (Uint'Max (M.Save_Uint, Uints_Min));
Udigits.Set_Last (Int'Max (M.Save_Udigit, Udigits_Min));
end Release;
----------------------
-- Release_And_Save --
----------------------
procedure Release_And_Save (M : Save_Mark; UI : in out Uint) is
begin
if Direct (UI) then
Release (M);
else
declare
UE_Len : Pos := Uints.Table (UI).Length;
UE_Loc : Int := Uints.Table (UI).Loc;
UD : Udigits.Table_Type (1 .. UE_Len) :=
Udigits.Table (UE_Loc .. UE_Loc + UE_Len - 1);
begin
Release (M);
Uints.Increment_Last;
UI := Uints.Last;
Uints.Table (UI) := (UE_Len, Udigits.Last + 1);
for J in 1 .. UE_Len loop
Udigits.Increment_Last;
Udigits.Table (Udigits.Last) := UD (J);
end loop;
end;
end if;
end Release_And_Save;
procedure Release_And_Save (M : Save_Mark; UI1, UI2 : in out Uint) is
begin
if Direct (UI1) then
Release_And_Save (M, UI2);
elsif Direct (UI2) then
Release_And_Save (M, UI1);
else
declare
UE1_Len : Pos := Uints.Table (UI1).Length;
UE1_Loc : Int := Uints.Table (UI1).Loc;
UD1 : Udigits.Table_Type (1 .. UE1_Len) :=
Udigits.Table (UE1_Loc .. UE1_Loc + UE1_Len - 1);
UE2_Len : Pos := Uints.Table (UI2).Length;
UE2_Loc : Int := Uints.Table (UI2).Loc;
UD2 : Udigits.Table_Type (1 .. UE2_Len) :=
Udigits.Table (UE2_Loc .. UE2_Loc + UE2_Len - 1);
begin
Release (M);
Uints.Increment_Last;
UI1 := Uints.Last;
Uints.Table (UI1) := (UE1_Len, Udigits.Last + 1);
for J in 1 .. UE1_Len loop
Udigits.Increment_Last;
Udigits.Table (Udigits.Last) := UD1 (J);
end loop;
Uints.Increment_Last;
UI2 := Uints.Last;
Uints.Table (UI2) := (UE2_Len, Udigits.Last + 1);
for J in 1 .. UE2_Len loop
Udigits.Increment_Last;
Udigits.Table (Udigits.Last) := UD2 (J);
end loop;
end;
end if;
end Release_And_Save;
----------------
-- Sum_Digits --
----------------
-- This is done in one pass
-- Mathematically: assume base congruent to 1 and compute an equivelent
-- integer to Left.
-- If Sign = -1 return the alternating sum of the "digits".
-- D1 - D2 + D3 - D4 + D5 . . .
-- (where D1 is Least Significant Digit)
-- Mathematically: assume base congruent to -1 and compute an equivelent
-- integer to Left.
-- This is used in Rem and Base is assumed to be 2 ** 15
-- Note: The next two functions are very similar, any style changes made
-- to one should be reflected in both. These would be simpler if we
-- worked base 2 ** 32.
function Sum_Digits (Left : Uint; Sign : Int) return Int is
begin
pragma Assert (Sign = Int_1 or Sign = Int (-1));
-- First try simple case;
if Direct (Left) then
declare
Tmp_Int : Int := Direct_Val (Left);
begin
if Tmp_Int >= Base then
Tmp_Int := (Tmp_Int / Base) +
Sign * (Tmp_Int rem Base);
-- Now Tmp_Int is in [-(Base - 1) .. 2 * (Base - 1)]
if Tmp_Int >= Base then
-- Sign must be 1.
Tmp_Int := (Tmp_Int / Base) + 1;
end if;
-- Now Tmp_Int is in [-(Base - 1) .. (Base - 1)]
end if;
return Tmp_Int;
end;
-- Otherwise full circuit is needed
else
declare
L_Length : Int := N_Digits (Left);
L_Vec : UI_Vector (1 .. L_Length);
Tmp_Int : Int;
Carry : Int;
Alt : Int;
begin
Init_Operand (Left, L_Vec);
L_Vec (1) := abs L_Vec (1);
Tmp_Int := 0;
Carry := 0;
Alt := 1;
for J in reverse 1 .. L_Length loop
Tmp_Int := Tmp_Int + Alt * (L_Vec (J) + Carry);
-- Tmp_Int is now between [-2 * Base + 1 .. 2 * Base - 1],
-- since old Tmp_Int is between [-(Base - 1) .. Base - 1]
-- and L_Vec is in [0 .. Base - 1] and Carry in [-1 .. 1]
if Tmp_Int >= Base then
Tmp_Int := Tmp_Int - Base;
Carry := 1;
elsif Tmp_Int <= -Base then
Tmp_Int := Tmp_Int + Base;
Carry := -1;
else
Carry := 0;
end if;
-- Tmp_Int is now between [-Base + 1 .. Base - 1]
Alt := Alt * Sign;
end loop;
Tmp_Int := Tmp_Int + Alt * Carry;
-- Tmp_Int is now between [-Base .. Base]
if Tmp_Int >= Base then
Tmp_Int := Tmp_Int - Base + Alt * Sign * 1;
elsif Tmp_Int <= -Base then
Tmp_Int := Tmp_Int + Base + Alt * Sign * (-1);
end if;
-- Now Tmp_Int is in [-(Base - 1) .. (Base - 1)]
return Tmp_Int;
end;
end if;
end Sum_Digits;
-----------------------
-- Sum_Double_Digits --
-----------------------
-- Note: This is used in Rem, Base is assumed to be 2 ** 15
function Sum_Double_Digits (Left : Uint; Sign : Int) return Int is
begin
-- First try simple case;
pragma Assert (Sign = Int_1 or Sign = Int (-1));
if Direct (Left) then
return Direct_Val (Left);
-- Otherwise full circuit is needed
else
declare
L_Length : Int := N_Digits (Left);
L_Vec : UI_Vector (1 .. L_Length);
Most_Sig_Int : Int;
Least_Sig_Int : Int;
Carry : Int;
J : Int;
Alt : Int;
begin
Init_Operand (Left, L_Vec);
L_Vec (1) := abs L_Vec (1);
Most_Sig_Int := 0;
Least_Sig_Int := 0;
Carry := 0;
Alt := 1;
J := L_Length;
while J > Int_1 loop
Least_Sig_Int := Least_Sig_Int + Alt * (L_Vec (J) + Carry);
-- Least is in [-2 Base + 1 .. 2 * Base - 1]
-- Since L_Vec in [0 .. Base - 1] and Carry in [-1 .. 1]
-- and old Least in [-Base + 1 .. Base - 1]
if Least_Sig_Int >= Base then
Least_Sig_Int := Least_Sig_Int - Base;
Carry := 1;
elsif Least_Sig_Int <= -Base then
Least_Sig_Int := Least_Sig_Int + Base;
Carry := -1;
else
Carry := 0;
end if;
-- Least is now in [-Base + 1 .. Base - 1]
Most_Sig_Int := Most_Sig_Int + Alt * (L_Vec (J - 1) + Carry);
-- Most is in [-2 Base + 1 .. 2 * Base - 1]
-- Since L_Vec in [0 .. Base - 1] and Carry in [-1 .. 1]
-- and old Most in [-Base + 1 .. Base - 1]
if Most_Sig_Int >= Base then
Most_Sig_Int := Most_Sig_Int - Base;
Carry := 1;
elsif Most_Sig_Int <= -Base then
Most_Sig_Int := Most_Sig_Int + Base;
Carry := -1;
else
Carry := 0;
end if;
-- Most is now in [-Base + 1 .. Base - 1]
J := J - 2;
Alt := Alt * Sign;
end loop;
if J = Int_1 then
Least_Sig_Int := Least_Sig_Int + Alt * (L_Vec (J) + Carry);
else
Least_Sig_Int := Least_Sig_Int + Alt * Carry;
end if;
if Least_Sig_Int >= Base then
Least_Sig_Int := Least_Sig_Int - Base;
Most_Sig_Int := Most_Sig_Int + Alt * 1;
elsif Least_Sig_Int <= -Base then
Least_Sig_Int := Least_Sig_Int + Base;
Most_Sig_Int := Most_Sig_Int + Alt * (-1);
end if;
if Most_Sig_Int >= Base then
Most_Sig_Int := Most_Sig_Int - Base;
Alt := Alt * Sign;
Least_Sig_Int :=
Least_Sig_Int + Alt * 1; -- cannot overflow again
elsif Most_Sig_Int <= -Base then
Most_Sig_Int := Most_Sig_Int + Base;
Alt := Alt * Sign;
Least_Sig_Int :=
Least_Sig_Int + Alt * (-1); -- cannot overflow again.
end if;
return Most_Sig_Int * Base + Least_Sig_Int;
end;
end if;
end Sum_Double_Digits;
---------------
-- Tree_Read --
---------------
procedure Tree_Read is
begin
Uints.Tree_Read;
Udigits.Tree_Read;
Tree_Read_Int (Int (Uint_Int_First));
Tree_Read_Int (Int (Uint_Int_Last));
Tree_Read_Int (UI_Power_2_Set);
Tree_Read_Int (UI_Power_10_Set);
Tree_Read_Int (Int (Uints_Min));
Tree_Read_Int (Udigits_Min);
for J in 0 .. UI_Power_2_Set loop
Tree_Read_Int (Int (UI_Power_2 (J)));
end loop;
for J in 0 .. UI_Power_10_Set loop
Tree_Read_Int (Int (UI_Power_10 (J)));
end loop;
end Tree_Read;
----------------
-- Tree_Write --
----------------
procedure Tree_Write is
begin
Uints.Tree_Write;
Udigits.Tree_Write;
Tree_Write_Int (Int (Uint_Int_First));
Tree_Write_Int (Int (Uint_Int_Last));
Tree_Write_Int (UI_Power_2_Set);
Tree_Write_Int (UI_Power_10_Set);
Tree_Write_Int (Int (Uints_Min));
Tree_Write_Int (Udigits_Min);
for J in 0 .. UI_Power_2_Set loop
Tree_Write_Int (Int (UI_Power_2 (J)));
end loop;
for J in 0 .. UI_Power_10_Set loop
Tree_Write_Int (Int (UI_Power_10 (J)));
end loop;
end Tree_Write;
-------------
-- UI_Abs --
-------------
function UI_Abs (Right : Uint) return Uint is
begin
if Right < Uint_0 then
return -Right;
else
return Right;
end if;
end UI_Abs;
-------------
-- UI_Add --
-------------
function UI_Add (Left : Int; Right : Uint) return Uint is
begin
return UI_Add (UI_From_Int (Left), Right);
end UI_Add;
function UI_Add (Left : Uint; Right : Int) return Uint is
begin
return UI_Add (Left, UI_From_Int (Right));
end UI_Add;
function UI_Add (Left : Uint; Right : Uint) return Uint is
begin
-- Simple cases of direct operands and addition of zero
if Direct (Left) then
if Direct (Right) then
return UI_From_Int (Direct_Val (Left) + Direct_Val (Right));
elsif Int (Left) = Int (Uint_0) then
return Right;
end if;
elsif Direct (Right) and then Int (Right) = Int (Uint_0) then
return Left;
end if;
-- Otherwise full circuit is needed
declare
L_Length : Int := N_Digits (Left);
R_Length : Int := N_Digits (Right);
L_Vec : UI_Vector (1 .. L_Length);
R_Vec : UI_Vector (1 .. R_Length);
Sum_Length : Int;
Tmp_Int : Int;
Carry : Int;
Borrow : Int;
X_Bigger : Boolean := False;
Y_Bigger : Boolean := False;
Result_Neg : Boolean := False;
begin
Init_Operand (Left, L_Vec);
Init_Operand (Right, R_Vec);
-- At least one of the two operands is in multi-digit form.
-- Calculate the number of digits sufficient to hold result.
if L_Length > R_Length then
Sum_Length := L_Length + 1;
X_Bigger := True;
else
Sum_Length := R_Length + 1;
if R_Length > L_Length then Y_Bigger := True; end if;
end if;
-- Make copies of the absolute values of L_Vec and R_Vec into
-- X and Y both with lengths equal to the maximum possibly
-- needed. This makes looping over the digits much simpler.
declare
X : UI_Vector (1 .. Sum_Length);
Y : UI_Vector (1 .. Sum_Length);
Tmp_UI : UI_Vector (1 .. Sum_Length);
begin
for J in 1 .. Sum_Length - L_Length loop
X (J) := 0;
end loop;
X (Sum_Length - L_Length + 1) := abs L_Vec (1);
for J in 2 .. L_Length loop
X (J + (Sum_Length - L_Length)) := L_Vec (J);
end loop;
for J in 1 .. Sum_Length - R_Length loop
Y (J) := 0;
end loop;
Y (Sum_Length - R_Length + 1) := abs R_Vec (1);
for J in 2 .. R_Length loop
Y (J + (Sum_Length - R_Length)) := R_Vec (J);
end loop;
if (L_Vec (1) < Int_0) = (R_Vec (1) < Int_0) then
-- Same sign so just add
Carry := 0;
for J in reverse 1 .. Sum_Length loop
Tmp_Int := X (J) + Y (J) + Carry;
if Tmp_Int >= Base then
Tmp_Int := Tmp_Int - Base;
Carry := 1;
else
Carry := 0;
end if;
X (J) := Tmp_Int;
end loop;
return Vector_To_Uint (X, L_Vec (1) < Int_0);
else
-- Find which one has bigger magnitude
if not (X_Bigger or Y_Bigger) then
for J in L_Vec'Range loop
if abs L_Vec (J) > abs R_Vec (J) then
X_Bigger := True;
exit;
elsif abs R_Vec (J) > abs L_Vec (J) then
Y_Bigger := True;
exit;
end if;
end loop;
end if;
-- If they have identical magnitude, just return 0, else
-- swap if necessary so that X had the bigger magnitude.
-- Determine if result is negative at this time.
Result_Neg := False;
if not (X_Bigger or Y_Bigger) then
return Uint_0;
elsif Y_Bigger then
if R_Vec (1) < Int_0 then
Result_Neg := True;
end if;
Tmp_UI := X;
X := Y;
Y := Tmp_UI;
else
if L_Vec (1) < Int_0 then
Result_Neg := True;
end if;
end if;
-- Subtract Y from the bigger X
Borrow := 0;
for J in reverse 1 .. Sum_Length loop
Tmp_Int := X (J) - Y (J) + Borrow;
if Tmp_Int < Int_0 then
Tmp_Int := Tmp_Int + Base;
Borrow := -1;
else
Borrow := 0;
end if;
X (J) := Tmp_Int;
end loop;
return Vector_To_Uint (X, Result_Neg);
end if;
end;
end;
end UI_Add;
--------------------------
-- UI_Decimal_Digits_Hi --
--------------------------
function UI_Decimal_Digits_Hi (U : Uint) return Nat is
begin
-- The maximum value of a "digit" is 32767, which is 5 decimal
-- digits, so an N_Digit number could take up to 5 times this
-- number of digits. This is certainly too high for large
-- numbers but it is not worth worrying about.
return 5 * N_Digits (U);
end UI_Decimal_Digits_Hi;
--------------------------
-- UI_Decimal_Digits_Lo --
--------------------------
function UI_Decimal_Digits_Lo (U : Uint) return Nat is
begin
-- The maximum value of a "digit" is 32767, which is more than four
-- decimal digits, but not a full five digits. The easily computed
-- minimum number of decimal digits is thus 1 + 4 * the number of
-- digits. This is certainly too low for large numbers but it is
-- not worth worrying about.
return 1 + 4 * (N_Digits (U) - 1);
end UI_Decimal_Digits_Lo;
------------
-- UI_Div --
------------
function UI_Div (Left : Int; Right : Uint) return Uint is
begin
return UI_Div (UI_From_Int (Left), Right);
end UI_Div;
function UI_Div (Left : Uint; Right : Int) return Uint is
begin
return UI_Div (Left, UI_From_Int (Right));
end UI_Div;
function UI_Div (Left, Right : Uint) return Uint is
begin
pragma Assert (Right /= Uint_0);
-- Cases where both operands are represented directly
if Direct (Left) and then Direct (Right) then
return UI_From_Int (Direct_Val (Left) / Direct_Val (Right));
end if;
declare
L_Length : constant Int := N_Digits (Left);
R_Length : constant Int := N_Digits (Right);
Q_Length : constant Int := L_Length - R_Length + 1;
L_Vec : UI_Vector (1 .. L_Length);
R_Vec : UI_Vector (1 .. R_Length);
D : Int;
Remainder : Int;
Tmp_Divisor : Int;
Carry : Int;
Tmp_Int : Int;
Tmp_Dig : Int;
begin
-- Result is zero if left operand is shorter than right
if L_Length < R_Length then
return Uint_0;
end if;
Init_Operand (Left, L_Vec);
Init_Operand (Right, R_Vec);
-- Case of right operand is single digit. Here we can simply divide
-- each digit of the left operand by the divisor, from most to least
-- significant, carrying the remainder to the next digit (just like
-- ordinary long division by hand).
if R_Length = Int_1 then
Remainder := 0;
Tmp_Divisor := abs R_Vec (1);
declare
Quotient : UI_Vector (1 .. L_Length);
begin
for J in L_Vec'Range loop
Tmp_Int := Remainder * Base + abs L_Vec (J);
Quotient (J) := Tmp_Int / Tmp_Divisor;
Remainder := Tmp_Int rem Tmp_Divisor;
end loop;
return
Vector_To_Uint
(Quotient, (L_Vec (1) < Int_0 xor R_Vec (1) < Int_0));
end;
end if;
-- The possible simple cases have been exhausted. Now turn to the
-- algorithm D from the section of Knuth mentioned at the top of
-- this package.
Algorithm_D : declare
Dividend : UI_Vector (1 .. L_Length + 1);
Divisor : UI_Vector (1 .. R_Length);
Quotient : UI_Vector (1 .. Q_Length);
Divisor_Dig1 : Int;
Divisor_Dig2 : Int;
Q_Guess : Int;
begin
-- [ NORMALIZE ] (step D1 in the algorithm). First calculate the
-- scale d, and then multiply Left and Right (u and v in the book)
-- by d to get the dividend and divisor to work with.
D := Base / (abs R_Vec (1) + 1);
Dividend (1) := 0;
Dividend (2) := abs L_Vec (1);
for J in 3 .. L_Length + Int_1 loop
Dividend (J) := L_Vec (J - 1);
end loop;
Divisor (1) := abs R_Vec (1);
for J in Int_2 .. R_Length loop
Divisor (J) := R_Vec (J);
end loop;
if D > Int_1 then
-- Multiply Dividend by D
Carry := 0;
for J in reverse Dividend'Range loop
Tmp_Int := Dividend (J) * D + Carry;
Dividend (J) := Tmp_Int rem Base;
Carry := Tmp_Int / Base;
end loop;
-- Multiply Divisor by d.
Carry := 0;
for J in reverse Divisor'Range loop
Tmp_Int := Divisor (J) * D + Carry;
Divisor (J) := Tmp_Int rem Base;
Carry := Tmp_Int / Base;
end loop;
end if;
-- Main loop of long division algorithm.
Divisor_Dig1 := Divisor (1);
Divisor_Dig2 := Divisor (2);
for J in Quotient'Range loop
-- [ CALCULATE Q (hat) ] (step D3 in the algorithm).
Tmp_Int := Dividend (J) * Base + Dividend (J + 1);
-- Initial guess
if Dividend (J) = Divisor_Dig1 then
Q_Guess := Base - 1;
else
Q_Guess := Tmp_Int / Divisor_Dig1;
end if;
-- Refine the guess
while Divisor_Dig2 * Q_Guess >
(Tmp_Int - Q_Guess * Divisor_Dig1) * Base +
Dividend (J + 2)
loop
Q_Guess := Q_Guess - 1;
end loop;
-- [ MULTIPLY & SUBTRACT] (step D4). Q_Guess * Divisor is
-- subtracted from the remaining dividend.
Carry := 0;
for K in reverse Divisor'Range loop
Tmp_Int := Dividend (J + K) - Q_Guess * Divisor (K) + Carry;
Tmp_Dig := Tmp_Int rem Base;
Carry := Tmp_Int / Base;
if Tmp_Dig < Int_0 then
Tmp_Dig := Tmp_Dig + Base;
Carry := Carry - 1;
end if;
Dividend (J + K) := Tmp_Dig;
end loop;
Dividend (J) := Dividend (J) + Carry;
-- [ TEST REMAINDER ] & [ ADD BACK ] (steps D5 and D6)
-- Here there is a slight difference from the book: the last
-- carry is always added in above and below (cancelling each
-- other). In fact the dividend going negative is used as
-- the test.
-- If the Dividend went negative, then Q_Guess was off by
-- one, so it is decremented, and the divisor is added back
-- into the relevant portion of the dividend.
if Dividend (J) < Int_0 then
Q_Guess := Q_Guess - 1;
Carry := 0;
for K in reverse Divisor'Range loop
Tmp_Int := Dividend (J + K) + Divisor (K) + Carry;
if Tmp_Int >= Base then
Tmp_Int := Tmp_Int - Base;
Carry := 1;
else
Carry := 0;
end if;
Dividend (J + K) := Tmp_Int;
end loop;
Dividend (J) := Dividend (J) + Carry;
end if;
-- Finally we can get the next quotient digit
Quotient (J) := Q_Guess;
end loop;
return Vector_To_Uint
(Quotient, (L_Vec (1) < Int_0 xor R_Vec (1) < Int_0));
end Algorithm_D;
end;
end UI_Div;
------------
-- UI_Eq --
------------
function UI_Eq (Left : Int; Right : Uint) return Boolean is
begin
return not UI_Ne (UI_From_Int (Left), Right);
end UI_Eq;
function UI_Eq (Left : Uint; Right : Int) return Boolean is
begin
return not UI_Ne (Left, UI_From_Int (Right));
end UI_Eq;
function UI_Eq (Left : Uint; Right : Uint) return Boolean is
begin
return not UI_Ne (Left, Right);
end UI_Eq;
--------------
-- UI_Expon --
--------------
function UI_Expon (Left : Int; Right : Uint) return Uint is
begin
return UI_Expon (UI_From_Int (Left), Right);
end UI_Expon;
function UI_Expon (Left : Uint; Right : Int) return Uint is
begin
return UI_Expon (Left, UI_From_Int (Right));
end UI_Expon;
function UI_Expon (Left : Int; Right : Int) return Uint is
begin
return UI_Expon (UI_From_Int (Left), UI_From_Int (Right));
end UI_Expon;
function UI_Expon (Left : Uint; Right : Uint) return Uint is
begin
pragma Assert (Right >= Uint_0);
-- Any value raised to power of 0 is 1
if Right = Uint_0 then
return Uint_1;
-- 0 to any positive power is 0.
elsif Left = Uint_0 then
return Uint_0;
-- 1 to any power is 1
elsif Left = Uint_1 then
return Uint_1;
-- Any value raised to power of 1 is that value
elsif Right = Uint_1 then
return Left;
-- Cases which can be done by table lookup
elsif Right <= Uint_64 then
-- 2 ** N for N in 2 .. 64
if Left = Uint_2 then
declare
Right_Int : constant Int := Direct_Val (Right);
begin
if Right_Int > UI_Power_2_Set then
for J in UI_Power_2_Set + Int_1 .. Right_Int loop
UI_Power_2 (J) := UI_Power_2 (J - Int_1) * Int_2;
Uints_Min := Uints.Last;
Udigits_Min := Udigits.Last;
end loop;
UI_Power_2_Set := Right_Int;
end if;
return UI_Power_2 (Right_Int);
end;
-- 10 ** N for N in 2 .. 64
elsif Left = Uint_10 then
declare
Right_Int : constant Int := Direct_Val (Right);
begin
if Right_Int > UI_Power_10_Set then
for J in UI_Power_10_Set + Int_1 .. Right_Int loop
UI_Power_10 (J) := UI_Power_10 (J - Int_1) * Int (10);
Uints_Min := Uints.Last;
Udigits_Min := Udigits.Last;
end loop;
UI_Power_10_Set := Right_Int;
end if;
return UI_Power_10 (Right_Int);
end;
end if;
end if;
-- If we fall through, then we have the general case (see Knuth 4.6.3)
declare
N : Uint := Right;
Squares : Uint := Left;
Result : Uint := Uint_1;
M : constant Uintp.Save_Mark := Uintp.Mark;
begin
loop
if (Least_Sig_Digit (N) mod Int_2) = Int_1 then
Result := Result * Squares;
end if;
N := N / Uint_2;
exit when N = Uint_0;
Squares := Squares * Squares;
end loop;
Uintp.Release_And_Save (M, Result);
return Result;
end;
end UI_Expon;
------------------
-- UI_From_Dint --
------------------
function UI_From_Dint (Input : Dint) return Uint is
begin
if Dint (Min_Direct) <= Input and then Input <= Dint (Max_Direct) then
return Uint (Dint (Uint_Direct_Bias) + Input);
-- For values of larger magnitude, compute digits into a vector and
-- call Vector_To_Uint.
else
declare
Max_For_Dint : constant := 5;
-- Base is defined so that 5 Uint digits is sufficient
-- to hold the largest possible Dint value.
V : UI_Vector (1 .. Max_For_Dint);
Temp_Integer : Dint;
begin
for J in V'Range loop
V (J) := 0;
end loop;
Temp_Integer := Input;
for J in reverse V'Range loop
V (J) := Int (abs (Temp_Integer rem Dint (Base)));
Temp_Integer := Temp_Integer / Dint (Base);
end loop;
return Vector_To_Uint (V, Input < Dint'(0));
end;
end if;
end UI_From_Dint;
-----------------
-- UI_From_Int --
-----------------
function UI_From_Int (Input : Int) return Uint is
begin
if Min_Direct <= Input and then Input <= Max_Direct then
return Uint (Int (Uint_Direct_Bias) + Input);
-- For values of larger magnitude, compute digits into a vector and
-- call Vector_To_Uint.
else
declare
Max_For_Int : constant := 3;
-- Base is defined so that 3 Uint digits is sufficient
-- to hold the largest possible Int value.
V : UI_Vector (1 .. Max_For_Int);
Temp_Integer : Int;
begin
for J in V'Range loop
V (J) := 0;
end loop;
Temp_Integer := Input;
for J in reverse V'Range loop
V (J) := abs (Temp_Integer rem Base);
Temp_Integer := Temp_Integer / Base;
end loop;
return Vector_To_Uint (V, Input < Int_0);
end;
end if;
end UI_From_Int;
------------
-- UI_GCD --
------------
-- Lehmer's algorithm for GCD.
-- The idea is to avoid using multiple precision arithmetic wherever
-- possible, substituting Int arithmetic instead. See Knuth volume II,
-- Algorithm L (page 329).
-- We use the same notation as Knuth (U_Hat standing for the obvious!)
function UI_GCD (Uin, Vin : Uint) return Uint is
U, V : Uint;
-- Copies of Uin and Vin
U_Hat, V_Hat : Int;
-- The most Significant digits of U,V
A, B, C, D, T, Q, Den1, Den2 : Int;
Tmp_UI : Uint;
Marks : constant Uintp.Save_Mark := Uintp.Mark;
Iterations : Integer := 0;
begin
pragma Assert (Uin >= Vin);
pragma Assert (Vin >= Uint_0);
U := Uin;
V := Vin;
loop
Iterations := Iterations + 1;
if Direct (V) then
if V = Uint_0 then
return U;
else
return
UI_From_Int (GCD (Direct_Val (V), UI_To_Int (U rem V)));
end if;
end if;
Most_Sig_2_Digits (U, V, U_Hat, V_Hat);
A := 1;
B := 0;
C := 0;
D := 1;
loop
-- We might overflow and get division by zero here. This just
-- means we can not take the single precision step
Den1 := V_Hat + C;
Den2 := V_Hat + D;
exit when (Den1 * Den2) = Int_0;
-- Compute Q, the trial quotient
Q := (U_Hat + A) / Den1;
exit when Q /= ((U_Hat + B) / Den2);
-- A single precision step Euclid step will give same answer as
-- a multiprecision one.
T := A - (Q * C);
A := C;
C := T;
T := B - (Q * D);
B := D;
D := T;
T := U_Hat - (Q * V_Hat);
U_Hat := V_Hat;
V_Hat := T;
end loop;
-- Take a multiprecision Euclid step
if B = Int_0 then
-- No single precision steps take a regular Euclid step.
Tmp_UI := U rem V;
U := V;
V := Tmp_UI;
else
-- Use prior single precision steps to compute this Euclid step.
-- Fixed bug 1415-008 spends 80% of its time working on this
-- step. Perhaps we need a special case Int / Uint dot
-- product to speed things up. ???
-- Alternatively we could increase the single precision
-- iterations to handle Uint's of some small size ( <5
-- digits?). Then we would have more iterations on small Uint.
-- Fixed bug 1415-008 only gets 5 (on average) single
-- precision iterations per large iteration. ???
Tmp_UI := (UI_From_Int (A) * U) + (UI_From_Int (B) * V);
V := (UI_From_Int (C) * U) + (UI_From_Int (D) * V);
U := Tmp_UI;
end if;
-- If the operands are very different in magnitude, the loop
-- will generate large amounts of short-lived data, which it is
-- worth removing periodically.
if Iterations > 100 then
Release_And_Save (Marks, U, V);
Iterations := 0;
end if;
end loop;
end UI_GCD;
------------
-- UI_Ge --
------------
function UI_Ge (Left : Int; Right : Uint) return Boolean is
begin
return not UI_Lt (UI_From_Int (Left), Right);
end UI_Ge;
function UI_Ge (Left : Uint; Right : Int) return Boolean is
begin
return not UI_Lt (Left, UI_From_Int (Right));
end UI_Ge;
function UI_Ge (Left : Uint; Right : Uint) return Boolean is
begin
return not UI_Lt (Left, Right);
end UI_Ge;
------------
-- UI_Gt --
------------
function UI_Gt (Left : Int; Right : Uint) return Boolean is
begin
return UI_Lt (Right, UI_From_Int (Left));
end UI_Gt;
function UI_Gt (Left : Uint; Right : Int) return Boolean is
begin
return UI_Lt (UI_From_Int (Right), Left);
end UI_Gt;
function UI_Gt (Left : Uint; Right : Uint) return Boolean is
begin
return UI_Lt (Right, Left);
end UI_Gt;
---------------
-- UI_Image --
---------------
procedure UI_Image (Input : Uint; Format : UI_Format := Auto) is
begin
Image_Out (Input, True, Format);
end UI_Image;
-------------------------
-- UI_Is_In_Int_Range --
-------------------------
function UI_Is_In_Int_Range (Input : Uint) return Boolean is
begin
-- Make sure we don't get called before Initialize
pragma Assert (Uint_Int_First /= Uint_0);
if Direct (Input) then
return True;
else
return Input >= Uint_Int_First
and then Input <= Uint_Int_Last;
end if;
end UI_Is_In_Int_Range;
------------
-- UI_Le --
------------
function UI_Le (Left : Int; Right : Uint) return Boolean is
begin
return not UI_Lt (Right, UI_From_Int (Left));
end UI_Le;
function UI_Le (Left : Uint; Right : Int) return Boolean is
begin
return not UI_Lt (UI_From_Int (Right), Left);
end UI_Le;
function UI_Le (Left : Uint; Right : Uint) return Boolean is
begin
return not UI_Lt (Right, Left);
end UI_Le;
------------
-- UI_Lt --
------------
function UI_Lt (Left : Int; Right : Uint) return Boolean is
begin
return UI_Lt (UI_From_Int (Left), Right);
end UI_Lt;
function UI_Lt (Left : Uint; Right : Int) return Boolean is
begin
return UI_Lt (Left, UI_From_Int (Right));
end UI_Lt;
function UI_Lt (Left : Uint; Right : Uint) return Boolean is
begin
-- Quick processing for identical arguments
if Int (Left) = Int (Right) then
return False;
-- Quick processing for both arguments directly represented
elsif Direct (Left) and then Direct (Right) then
return Int (Left) < Int (Right);
-- At least one argument is more than one digit long
else
declare
L_Length : constant Int := N_Digits (Left);
R_Length : constant Int := N_Digits (Right);
L_Vec : UI_Vector (1 .. L_Length);
R_Vec : UI_Vector (1 .. R_Length);
begin
Init_Operand (Left, L_Vec);
Init_Operand (Right, R_Vec);
if L_Vec (1) < Int_0 then
-- First argument negative, second argument non-negative
if R_Vec (1) >= Int_0 then
return True;
-- Both arguments negative
else
if L_Length /= R_Length then
return L_Length > R_Length;
elsif L_Vec (1) /= R_Vec (1) then
return L_Vec (1) < R_Vec (1);
else
for J in 2 .. L_Vec'Last loop
if L_Vec (J) /= R_Vec (J) then
return L_Vec (J) > R_Vec (J);
end if;
end loop;
return False;
end if;
end if;
else
-- First argument non-negative, second argument negative
if R_Vec (1) < Int_0 then
return False;
-- Both arguments non-negative
else
if L_Length /= R_Length then
return L_Length < R_Length;
else
for J in L_Vec'Range loop
if L_Vec (J) /= R_Vec (J) then
return L_Vec (J) < R_Vec (J);
end if;
end loop;
return False;
end if;
end if;
end if;
end;
end if;
end UI_Lt;
------------
-- UI_Max --
------------
function UI_Max (Left : Int; Right : Uint) return Uint is
begin
return UI_Max (UI_From_Int (Left), Right);
end UI_Max;
function UI_Max (Left : Uint; Right : Int) return Uint is
begin
return UI_Max (Left, UI_From_Int (Right));
end UI_Max;
function UI_Max (Left : Uint; Right : Uint) return Uint is
begin
if Left >= Right then
return Left;
else
return Right;
end if;
end UI_Max;
------------
-- UI_Min --
------------
function UI_Min (Left : Int; Right : Uint) return Uint is
begin
return UI_Min (UI_From_Int (Left), Right);
end UI_Min;
function UI_Min (Left : Uint; Right : Int) return Uint is
begin
return UI_Min (Left, UI_From_Int (Right));
end UI_Min;
function UI_Min (Left : Uint; Right : Uint) return Uint is
begin
if Left <= Right then
return Left;
else
return Right;
end if;
end UI_Min;
-------------
-- UI_Mod --
-------------
function UI_Mod (Left : Int; Right : Uint) return Uint is
begin
return UI_Mod (UI_From_Int (Left), Right);
end UI_Mod;
function UI_Mod (Left : Uint; Right : Int) return Uint is
begin
return UI_Mod (Left, UI_From_Int (Right));
end UI_Mod;
function UI_Mod (Left : Uint; Right : Uint) return Uint is
Urem : constant Uint := Left rem Right;
begin
if (Left < Uint_0) = (Right < Uint_0)
or else Urem = Uint_0
then
return Urem;
else
return Right + Urem;
end if;
end UI_Mod;
------------
-- UI_Mul --
------------
function UI_Mul (Left : Int; Right : Uint) return Uint is
begin
return UI_Mul (UI_From_Int (Left), Right);
end UI_Mul;
function UI_Mul (Left : Uint; Right : Int) return Uint is
begin
return UI_Mul (Left, UI_From_Int (Right));
end UI_Mul;
function UI_Mul (Left : Uint; Right : Uint) return Uint is
begin
-- Simple case of single length operands
if Direct (Left) and then Direct (Right) then
return
UI_From_Dint
(Dint (Direct_Val (Left)) * Dint (Direct_Val (Right)));
end if;
-- Otherwise we have the general case (Algorithm M in Knuth)
declare
L_Length : constant Int := N_Digits (Left);
R_Length : constant Int := N_Digits (Right);
L_Vec : UI_Vector (1 .. L_Length);
R_Vec : UI_Vector (1 .. R_Length);
Neg : Boolean;
begin
Init_Operand (Left, L_Vec);
Init_Operand (Right, R_Vec);
Neg := (L_Vec (1) < Int_0) xor (R_Vec (1) < Int_0);
L_Vec (1) := abs (L_Vec (1));
R_Vec (1) := abs (R_Vec (1));
Algorithm_M : declare
Product : UI_Vector (1 .. L_Length + R_Length);
Tmp_Sum : Int;
Carry : Int;
begin
for J in Product'Range loop
Product (J) := 0;
end loop;
for J in reverse R_Vec'Range loop
Carry := 0;
for K in reverse L_Vec'Range loop
Tmp_Sum :=
L_Vec (K) * R_Vec (J) + Product (J + K) + Carry;
Product (J + K) := Tmp_Sum rem Base;
Carry := Tmp_Sum / Base;
end loop;
Product (J) := Carry;
end loop;
return Vector_To_Uint (Product, Neg);
end Algorithm_M;
end;
end UI_Mul;
------------
-- UI_Ne --
------------
function UI_Ne (Left : Int; Right : Uint) return Boolean is
begin
return UI_Ne (UI_From_Int (Left), Right);
end UI_Ne;
function UI_Ne (Left : Uint; Right : Int) return Boolean is
begin
return UI_Ne (Left, UI_From_Int (Right));
end UI_Ne;
function UI_Ne (Left : Uint; Right : Uint) return Boolean is
begin
-- Quick processing for identical arguments. Note that this takes
-- care of the case of two No_Uint arguments.
if Int (Left) = Int (Right) then
return False;
end if;
-- See if left operand directly represented
if Direct (Left) then
-- If right operand directly represented then compare
if Direct (Right) then
return Int (Left) /= Int (Right);
-- Left operand directly represented, right not, must be unequal
else
return True;
end if;
-- Right operand directly represented, left not, must be unequal
elsif Direct (Right) then
return True;
end if;
-- Otherwise both multi-word, do comparison
declare
Size : constant Int := N_Digits (Left);
Left_Loc : Int;
Right_Loc : Int;
begin
if Size /= N_Digits (Right) then
return True;
end if;
Left_Loc := Uints.Table (Left).Loc;
Right_Loc := Uints.Table (Right).Loc;
for J in Int_0 .. Size - Int_1 loop
if Udigits.Table (Left_Loc + J) /=
Udigits.Table (Right_Loc + J)
then
return True;
end if;
end loop;
return False;
end;
end UI_Ne;
----------------
-- UI_Negate --
----------------
function UI_Negate (Right : Uint) return Uint is
begin
-- Case where input is directly represented. Note that since the
-- range of Direct values is non-symmetrical, the result may not
-- be directly represented, this is taken care of in UI_From_Int.
if Direct (Right) then
return UI_From_Int (-Direct_Val (Right));
-- Full processing for multi-digit case. Note that we cannot just
-- copy the value to the end of the table negating the first digit,
-- since the range of Direct values is non-symmetrical, so we can
-- have a negative value that is not Direct whose negation can be
-- represented directly.
else
declare
R_Length : constant Int := N_Digits (Right);
R_Vec : UI_Vector (1 .. R_Length);
Neg : Boolean;
begin
Init_Operand (Right, R_Vec);
Neg := R_Vec (1) > Int_0;
R_Vec (1) := abs R_Vec (1);
return Vector_To_Uint (R_Vec, Neg);
end;
end if;
end UI_Negate;
-------------
-- UI_Rem --
-------------
function UI_Rem (Left : Int; Right : Uint) return Uint is
begin
return UI_Rem (UI_From_Int (Left), Right);
end UI_Rem;
function UI_Rem (Left : Uint; Right : Int) return Uint is
begin
return UI_Rem (Left, UI_From_Int (Right));
end UI_Rem;
function UI_Rem (Left, Right : Uint) return Uint is
Sign : Int;
Tmp : Int;
subtype Int1_12 is Integer range 1 .. 12;
begin
pragma Assert (Right /= Uint_0);
if Direct (Right) then
if Direct (Left) then
return UI_From_Int (Direct_Val (Left) rem Direct_Val (Right));
else
-- Special cases when Right is less than 13 and Left is larger
-- larger than one digit. All of these algorithms depend on the
-- base being 2 ** 15 We work with Abs (Left) and Abs(Right)
-- then multiply result by Sign (Left)
if (Right <= Uint_12) and then (Right >= Uint_Minus_12) then
if (Left < Uint_0) then
Sign := -1;
else
Sign := 1;
end if;
-- All cases are listed, grouped by mathematical method
-- It is not inefficient to do have this case list out
-- of order since GCC sorts the cases we list.
case Int1_12 (abs (Direct_Val (Right))) is
when 1 =>
return Uint_0;
-- Powers of two are simple AND's with LS Left Digit
-- GCC will recognise these constants as powers of 2
-- and replace the rem with simpler operations where
-- possible.
-- Least_Sig_Digit might return Negative numbers.
when 2 =>
return UI_From_Int (
Sign * (Least_Sig_Digit (Left) mod 2));
when 4 =>
return UI_From_Int (
Sign * (Least_Sig_Digit (Left) mod 4));
when 8 =>
return UI_From_Int (
Sign * (Least_Sig_Digit (Left) mod 8));
-- Some number theoretical tricks:
-- If B Rem Right = 1 then
-- Left Rem Right = Sum_Of_Digits_Base_B (Left) Rem Right
-- Note: 2^32 mod 3 = 1
when 3 =>
return UI_From_Int (
Sign * (Sum_Double_Digits (Left, 1) rem Int (3)));
-- Note: 2^15 mod 7 = 1
when 7 =>
return UI_From_Int (
Sign * (Sum_Digits (Left, 1) rem Int (7)));
-- Note: 2^32 mod 5 = -1
-- Alternating sums might be negative, but rem is always
-- positive hence we must use mod here.
when 5 =>
Tmp := Sum_Double_Digits (Left, -1) mod Int (5);
return UI_From_Int (Sign * Tmp);
-- Note: 2^15 mod 9 = -1
-- Alternating sums might be negative, but rem is always
-- positive hence we must use mod here.
when 9 =>
Tmp := Sum_Digits (Left, -1) mod Int (9);
return UI_From_Int (Sign * Tmp);
-- Note: 2^15 mod 11 = -1
-- Alternating sums might be negative, but rem is always
-- positive hence we must use mod here.
when 11 =>
Tmp := Sum_Digits (Left, -1) mod Int (11);
return UI_From_Int (Sign * Tmp);
-- Now resort to Chinese Remainder theorem
-- to reduce 6, 10, 12 to previous special cases
-- There is no reason we could not add more cases
-- like these if it proves useful.
-- Perhaps we should go up to 16, however
-- I have no "trick" for 13.
-- To find u mod m we:
-- Pick m1, m2 S.T.
-- GCD(m1, m2) = 1 AND m = (m1 * m2).
-- Next we pick (Basis) M1, M2 small S.T.
-- (M1 mod m1) = (M2 mod m2) = 1 AND
-- (M1 mod m2) = (M2 mod m1) = 0
-- So u mod m = (u1 * M1 + u2 * M2) mod m
-- Where u1 = (u mod m1) AND u2 = (u mod m2);
-- Under typical circumstances the last mod m
-- can be done with a (possible) single subtraction.
-- m1 = 2; m2 = 3; M1 = 3; M2 = 4;
when 6 =>
Tmp := 3 * (Least_Sig_Digit (Left) rem 2) +
4 * (Sum_Double_Digits (Left, 1) rem 3);
return UI_From_Int (Sign * (Tmp rem 6));
-- m1 = 2; m2 = 5; M1 = 5; M2 = 6;
when 10 =>
Tmp := 5 * (Least_Sig_Digit (Left) rem 2) +
6 * (Sum_Double_Digits (Left, -1) mod 5);
return UI_From_Int (Sign * (Tmp rem 10));
-- m1 = 3; m2 = 4; M1 = 4; M2 = 9;
when 12 =>
Tmp := 4 * (Sum_Double_Digits (Left, 1) rem 3) +
9 * (Least_Sig_Digit (Left) rem 4);
return UI_From_Int (Sign * (Tmp rem 12));
end case;
end if;
-- Else fall through to general case.
-- ???This needs to be improved. We have the Rem when we do the
-- Div. Div throws it away!
-- The special case Length (Left) = Length(right) = 1 in Div
-- looks slow. It uses UI_To_Int when Int should suffice. ???
end if;
end if;
return Left - (Left / Right) * Right;
end UI_Rem;
------------
-- UI_Sub --
------------
function UI_Sub (Left : Int; Right : Uint) return Uint is
begin
return UI_Add (Left, -Right);
end UI_Sub;
function UI_Sub (Left : Uint; Right : Int) return Uint is
begin
return UI_Add (Left, -Right);
end UI_Sub;
function UI_Sub (Left : Uint; Right : Uint) return Uint is
begin
if Direct (Left) and then Direct (Right) then
return UI_From_Int (Direct_Val (Left) - Direct_Val (Right));
else
return UI_Add (Left, -Right);
end if;
end UI_Sub;
----------------
-- UI_To_Int --
----------------
function UI_To_Int (Input : Uint) return Int is
begin
if Direct (Input) then
return Direct_Val (Input);
-- Case of input is more than one digit
else
declare
In_Length : constant Int := N_Digits (Input);
In_Vec : UI_Vector (1 .. In_Length);
Ret_Int : Int;
begin
-- Uints of more than one digit could be outside the range for
-- Ints. Caller should have checked for this if not certain.
-- Fatal error to attempt to convert from value outside Int'Range.
pragma Assert (UI_Is_In_Int_Range (Input));
-- Otherwise, proceed ahead, we are OK
Init_Operand (Input, In_Vec);
Ret_Int := 0;
-- Calculate -|Input| and then negates if value is positive.
-- This handles our current definition of Int (based on
-- 2s complement). Is it secure enough?
for Idx in In_Vec'Range loop
Ret_Int := Ret_Int * Base - abs In_Vec (Idx);
end loop;
if In_Vec (1) < Int_0 then
return Ret_Int;
else
return -Ret_Int;
end if;
end;
end if;
end UI_To_Int;
--------------
-- UI_Write --
--------------
procedure UI_Write (Input : Uint; Format : UI_Format := Auto) is
begin
Image_Out (Input, False, Format);
end UI_Write;
---------------------
-- Vector_To_Uint --
---------------------
function Vector_To_Uint
(In_Vec : UI_Vector;
Negative : Boolean)
return Uint
is
Size : Int;
Val : Int;
begin
-- The vector can contain leading zeros. These are not stored in the
-- table, so loop through the vector looking for first non-zero digit
for J in In_Vec'Range loop
if In_Vec (J) /= Int_0 then
-- The length of the value is the length of the rest of the vector
Size := In_Vec'Last - J + 1;
-- One digit value can always be represented directly
if Size = Int_1 then
if Negative then
return Uint (Int (Uint_Direct_Bias) - In_Vec (J));
else
return Uint (Int (Uint_Direct_Bias) + In_Vec (J));
end if;
-- Positive two digit values may be in direct representation range
elsif Size = Int_2 and then not Negative then
Val := In_Vec (J) * Base + In_Vec (J + 1);
if Val <= Max_Direct then
return Uint (Int (Uint_Direct_Bias) + Val);
end if;
end if;
-- The value is outside the direct representation range and
-- must therefore be stored in the table. Expand the table
-- to contain the count and tigis. The index of the new table
-- entry will be returned as the result.
Uints.Increment_Last;
Uints.Table (Uints.Last).Length := Size;
Uints.Table (Uints.Last).Loc := Udigits.Last + 1;
Udigits.Increment_Last;
if Negative then
Udigits.Table (Udigits.Last) := -In_Vec (J);
else
Udigits.Table (Udigits.Last) := +In_Vec (J);
end if;
for K in 2 .. Size loop
Udigits.Increment_Last;
Udigits.Table (Udigits.Last) := In_Vec (J + K - 1);
end loop;
return Uints.Last;
end if;
end loop;
-- Dropped through loop only if vector contained all zeros
return Uint_0;
end Vector_To_Uint;
end Uintp;
|
with Gnat.Regpat;
package body Parse_Lines is
procedure Search_For_Pattern(Pattern: Gnat.Regpat.Pattern_Matcher;
Search_In: String;
First, Last: out Positive;
Found: out Boolean) is
use Gnat.Regpat;
Result: Match_Array (0 .. 1);
begin
Match(Pattern, Search_In, Result);
Found := Result(1) /= No_Match;
if Found then
First := Result(1).First;
Last := Result(1).Last;
end if;
end Search_For_Pattern;
function Compile(Raw: String) return Gnat.Regpat.Pattern_Matcher is
begin
return Gnat.Regpat.Compile(Raw);
end Compile;
procedure Iterate_Words(S: String) is
Current_First: Positive := S'First;
First, Last: Positive;
Found: Boolean;
use Parse_Lines;
Compiled_P: Gnat.Regpat.Pattern_Matcher := Compile(Pattern);
begin
loop
Search_For_Pattern(Compiled_P,
S(Current_First .. S'Last),
First, Last, Found);
exit when not Found;
Do_Something(S(First .. Last));
Current_First := Last+1;
end loop;
end Iterate_Words;
end Parse_Lines;
|
with
Shell,
Ada.Text_IO;
procedure Test_Wait_On_Process
is
use Ada.Text_IO;
begin
Put_Line ("Begin 'Wait_On_Process' test.");
New_Line (2);
declare
use Shell;
Sleep : Shell.Process := Start (Program => "sleep",
Arguments => (1 => (+"3")));
begin
Put_Line ("Waiting on process ('sleep 3') ...");
Wait_On (Sleep);
end;
New_Line (2);
Put_Line ("End 'Wait_On_Process' test.");
end Test_Wait_On_Process;
|
-- Ada_GUI implementation based on Gnoga. Adapted 2021
-- --
-- GNOGA - The GNU Omnificent GUI for Ada --
-- --
-- G N O G A . G U I . V I E W . G R I D --
-- --
-- S p e c --
-- --
-- --
-- Copyright (C) 2014 David Botton --
-- --
-- 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/>. --
-- --
-- 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. --
-- --
-- For more information please go to http://www.gnoga.com --
------------------------------------------------------------------------------
package Ada_GUI.Gnoga.Gui.View.Grid is
-------------------------------------------------------------------------
-- Grid_View_Types
-------------------------------------------------------------------------
type Grid_View_Type is new View_Base_Type with private;
type Grid_View_Access is access all Grid_View_Type;
type Pointer_To_Grid_View_Class is access all Grid_View_Type'Class;
-------------------------------------------------------------------------
-- Grid_View_Type - Creation Methods
-------------------------------------------------------------------------
type Grid_Element_Type is (COL, SPN);
-- COL = A single column
-- SPN = Span previous column through this column
type Grid_Rows_Type is
array (Positive range <>, Positive range <>) of Grid_Element_Type;
Vertical_Split : constant Grid_Rows_Type := ((1 => COL), (1 => COL));
Horizontal_Split : constant Grid_Rows_Type := (1 => (COL, COL));
procedure Create
(Grid : in out Grid_View_Type;
Parent : in out Gnoga.Gui.Base_Type'Class;
Layout : in Grid_Rows_Type;
Fill_Parent : in Boolean := True;
Set_Sizes : in Boolean := True;
ID : in String := "");
-- Create a grid of views using Layout. If Set_Sizes is true then default
-- equal size columns and rows will be created and widths set as
-- percentages.
--
-- Example:
-- Grid.Create (Main_Window,
-- ((COL, SPN),
-- (COL, COL),
-- (COL, SPN)),
-- Fill_Parent => True);
-- This will create a top view two columns wide, left and right middle
-- views and a bottom view two columns wide. Provided Main_Window is a
-- window type, since Fill_Parent is True the grid will fill the entire browser
-- window.
--
-- Note: If Set_Sizes is used any change in size of panels should be
-- done using percentages, e.g. Box_Width ("20%"). In all cases
-- changing the size of individual panels but not others may not
-- always give the expected results.
-------------------------------------------------------------------------
-- Grid_View_Type - Properties
-------------------------------------------------------------------------
function Panel (Grid : Grid_View_Type; Row, Column : Positive)
return Pointer_To_View_Base_Class;
-- Return the Panel view at Row, Column. Every member of a column span
-- will return a pointer to the same view.
private
type Grid_View_Type is new View_Type with null record;
end Ada_GUI.Gnoga.Gui.View.Grid;
|
with Ada.Text_IO; use Ada.Text_IO;
package body base_type is
procedure method(Self : The_Type) is
begin
Put_Line(" bt:method");
end;
end base_type;
|
with Ada.Numerics.Generic_Elementary_Functions;
package body Math is
package Float_Elementary_Functions is new Ada.Numerics.Generic_Elementary_Functions (Float);
use Float_Elementary_Functions;
function Hypot(P : Point2D) return Float is
X : constant Float := abs P(P'First);
Y : constant Float := abs P(P'Last);
Min_Coord : constant Float := Float'Min(X, Y);
Max_Coord : constant Float := Float'Max(X, Y);
Ratio : constant Float := Min_Coord / Max_Coord;
begin
return Max_Coord * Sqrt (1.0 + Ratio ** 2);
end;
end;
|
-- Copyright (c) 2019-2020 Maxim Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-- License-Filename: LICENSE
-------------------------------------------------------------
with Ada.Containers.Ordered_Maps;
with Ada.Containers.Vectors;
with Ada.Finalization;
with GNAT.Sockets;
with League.Strings;
with Torrent.Connections;
with Torrent.Metainfo_Files;
with Torrent.Storages;
limited with Torrent.Contexts;
package Torrent.Downloaders is
type Downloader
(Context : access Torrent.Contexts.Context'Class;
Meta : not null Torrent.Metainfo_Files.Metainfo_File_Access;
File_Count : Ada.Containers.Count_Type;
Piece_Count : Piece_Index) is
tagged limited private;
-- The downloader tracks one torrent file and all connections
-- related to it.
type Downloader_Access is access all Downloader'Class
with Storage_Size => 0;
procedure Initialize
(Self : in out Downloader'Class;
Peer : SHA1;
Path : League.Strings.Universal_String);
procedure Start (Self : aliased in out Downloader'Class);
procedure Stop (Self : in out Downloader'Class);
procedure Update (Self : in out Downloader'Class);
function Completed (Self : Downloader'Class)
return Torrent.Connections.Piece_Index_Array
with Inline;
function Create_Session
(Self : in out Downloader'Class;
Address : GNAT.Sockets.Sock_Addr_Type)
return Torrent.Connections.Connection_Access;
function Is_Leacher (Self : Downloader'Class) return Boolean;
private
package Connection_Vectors is new Ada.Containers.Vectors
(Index_Type => Positive,
Element_Type => Torrent.Connections.Connection_Access,
"=" => Torrent.Connections."=");
package Piece_State_Maps is new Ada.Containers.Ordered_Maps
(Key_Type => Piece_Index,
Element_Type => Torrent.Connections.Interval_Vectors.Vector,
"<" => "<",
"=" => Torrent.Connections.Interval_Vectors."=");
protected type Tracked_Pieces
(Downloader : not null access Downloaders.Downloader;
Piece_Count : Piece_Index) is
new Torrent.Connections.Connection_State_Listener with
procedure Initialize
(Piece_Length : Piece_Offset;
Last_Piece_Length : Piece_Offset);
overriding procedure Reserve_Intervals
(Map : Boolean_Array;
Value : out Torrent.Connections.Piece_State);
overriding function We_Are_Intrested
(Map : Boolean_Array) return Boolean;
overriding procedure Interval_Saved
(Piece : Piece_Index;
Value : Torrent.Connections.Interval;
Last : out Boolean);
overriding procedure Piece_Completed
(Piece : Piece_Index;
Ok : Boolean);
overriding procedure Unreserve_Intervals
(Value : Torrent.Connections.Piece_Interval_Array);
overriding procedure Interval_Sent (Size : Piece_Offset);
private
Our_Map : Boolean_Array (1 .. Piece_Count) := (others => False);
Piece_Size : Piece_Offset;
Last_Piece_Size : Piece_Offset;
Finished : Piece_State_Maps.Map;
Unfinished : Piece_State_Maps.Map;
end Tracked_Pieces;
type Downloader
(Context : access Torrent.Contexts.Context'Class;
Meta : not null Torrent.Metainfo_Files.Metainfo_File_Access;
File_Count : Ada.Containers.Count_Type;
Piece_Count : Piece_Index) is
new Ada.Finalization.Limited_Controlled with
record
Tracked : aliased Tracked_Pieces
(Downloader'Unchecked_Access, Piece_Count);
Peer_Id : SHA1;
Port : Positive;
Uploaded : Ada.Streams.Stream_Element_Count;
Downloaded : Ada.Streams.Stream_Element_Count;
Left : Ada.Streams.Stream_Element_Count;
Completed : Torrent.Connections.Piece_Index_Array
(1 .. Piece_Count);
Last_Completed : Torrent.Piece_Count;
Storage : aliased Torrent.Storages.Storage (Meta, File_Count);
end record;
end Torrent.Downloaders;
|
with Ada.Numerics;
with System.Long_Long_Elementary_Functions;
package body System.Long_Long_Complex_Elementary_Functions is
-- libgcc
function mulxc3 (Left_Re, Left_Im, Right_Re, Right_Im : Long_Long_Float)
return Long_Long_Complex
with Import, Convention => C, External_Name => "__mulxc3";
function divxc3 (Left_Re, Left_Im, Right_Re, Right_Im : Long_Long_Float)
return Long_Long_Complex
with Import, Convention => C, External_Name => "__divxc3";
pragma Pure_Function (mulxc3);
pragma Pure_Function (divxc3);
function "-" (Left : Long_Long_Float; Right : Long_Long_Complex)
return Long_Long_Complex
with Convention => Intrinsic;
function "*" (Left : Long_Long_Float; Right : Long_Long_Complex)
return Long_Long_Complex
with Convention => Intrinsic;
function "*" (Left, Right : Long_Long_Complex) return Long_Long_Complex
with Convention => Intrinsic;
function "/" (Left, Right : Long_Long_Complex) return Long_Long_Complex
with Convention => Intrinsic;
pragma Inline_Always ("-");
pragma Inline_Always ("*");
pragma Inline_Always ("/");
function "-" (Left : Long_Long_Float; Right : Long_Long_Complex)
return Long_Long_Complex is
begin
return (Re => Left - Right.Re, Im => -Right.Im);
end "-";
function "*" (Left : Long_Long_Float; Right : Long_Long_Complex)
return Long_Long_Complex is
begin
return (Re => Left * Right.Re, Im => Left * Right.Im);
end "*";
function "*" (Left, Right : Long_Long_Complex) return Long_Long_Complex is
begin
return mulxc3 (Left.Re, Left.Im, Right.Re, Right.Im);
end "*";
function "/" (Left, Right : Long_Long_Complex) return Long_Long_Complex is
begin
return divxc3 (Left.Re, Left.Im, Right.Re, Right.Im);
end "/";
-- Complex
function To_Complex (X : Long_Long_Complex) return Complex;
function To_Complex (X : Long_Long_Complex) return Complex is
begin
return (Re => Float (X.Re), Im => Float (X.Im));
end To_Complex;
function To_Long_Long_Complex (X : Complex) return Long_Long_Complex;
function To_Long_Long_Complex (X : Complex) return Long_Long_Complex is
begin
return (Re => Long_Long_Float (X.Re), Im => Long_Long_Float (X.Im));
end To_Long_Long_Complex;
function Fast_Log (X : Complex) return Complex is
begin
return To_Complex (Fast_Log (To_Long_Long_Complex (X)));
end Fast_Log;
function Fast_Exp (X : Complex) return Complex is
begin
return To_Complex (Fast_Exp (To_Long_Long_Complex (X)));
end Fast_Exp;
function Fast_Exp (X : Imaginary) return Complex is
begin
return To_Complex (Fast_Exp (Long_Long_Imaginary (X)));
end Fast_Exp;
function Fast_Pow (Left, Right : Complex) return Complex is
begin
return To_Complex (
Fast_Pow (To_Long_Long_Complex (Left), To_Long_Long_Complex (Right)));
end Fast_Pow;
function Fast_Sin (X : Complex) return Complex is
begin
return To_Complex (Fast_Sin (To_Long_Long_Complex (X)));
end Fast_Sin;
function Fast_Cos (X : Complex) return Complex is
begin
return To_Complex (Fast_Cos (To_Long_Long_Complex (X)));
end Fast_Cos;
function Fast_Tan (X : Complex) return Complex is
begin
return To_Complex (Fast_Tan (To_Long_Long_Complex (X)));
end Fast_Tan;
function Fast_Arcsin (X : Complex) return Complex is
begin
return To_Complex (Fast_Arcsin (To_Long_Long_Complex (X)));
end Fast_Arcsin;
function Fast_Arccos (X : Complex) return Complex is
begin
return To_Complex (Fast_Arccos (To_Long_Long_Complex (X)));
end Fast_Arccos;
function Fast_Arctan (X : Complex) return Complex is
begin
return To_Complex (Fast_Arctan (To_Long_Long_Complex (X)));
end Fast_Arctan;
function Fast_Sinh (X : Complex) return Complex is
begin
return To_Complex (Fast_Sinh (To_Long_Long_Complex (X)));
end Fast_Sinh;
function Fast_Cosh (X : Complex) return Complex is
begin
return To_Complex (Fast_Cosh (To_Long_Long_Complex (X)));
end Fast_Cosh;
function Fast_Tanh (X : Complex) return Complex is
begin
return To_Complex (Fast_Tanh (To_Long_Long_Complex (X)));
end Fast_Tanh;
function Fast_Arcsinh (X : Complex) return Complex is
begin
return To_Complex (Fast_Arcsinh (To_Long_Long_Complex (X)));
end Fast_Arcsinh;
function Fast_Arccosh (X : Complex) return Complex is
begin
return To_Complex (Fast_Arccosh (To_Long_Long_Complex (X)));
end Fast_Arccosh;
function Fast_Arctanh (X : Complex) return Complex is
begin
return To_Complex (Fast_Arctanh (To_Long_Long_Complex (X)));
end Fast_Arctanh;
-- Long_Complex
function To_Long_Complex (X : Long_Long_Complex) return Long_Complex;
function To_Long_Complex (X : Long_Long_Complex) return Long_Complex is
begin
return (Re => Long_Float (X.Re), Im => Long_Float (X.Im));
end To_Long_Complex;
function To_Long_Long_Complex (X : Long_Complex) return Long_Long_Complex;
function To_Long_Long_Complex (X : Long_Complex) return Long_Long_Complex is
begin
return (Re => Long_Long_Float (X.Re), Im => Long_Long_Float (X.Im));
end To_Long_Long_Complex;
function Fast_Log (X : Long_Complex) return Long_Complex is
begin
return To_Long_Complex (Fast_Log (To_Long_Long_Complex (X)));
end Fast_Log;
function Fast_Exp (X : Long_Complex) return Long_Complex is
begin
return To_Long_Complex (Fast_Exp (To_Long_Long_Complex (X)));
end Fast_Exp;
function Fast_Exp (X : Long_Imaginary) return Long_Complex is
begin
return To_Long_Complex (Fast_Exp (Long_Long_Imaginary (X)));
end Fast_Exp;
function Fast_Pow (Left, Right : Long_Complex) return Long_Complex is
begin
return To_Long_Complex (
Fast_Pow (To_Long_Long_Complex (Left), To_Long_Long_Complex (Right)));
end Fast_Pow;
function Fast_Sin (X : Long_Complex) return Long_Complex is
begin
return To_Long_Complex (Fast_Sin (To_Long_Long_Complex (X)));
end Fast_Sin;
function Fast_Cos (X : Long_Complex) return Long_Complex is
begin
return To_Long_Complex (Fast_Cos (To_Long_Long_Complex (X)));
end Fast_Cos;
function Fast_Tan (X : Long_Complex) return Long_Complex is
begin
return To_Long_Complex (Fast_Tan (To_Long_Long_Complex (X)));
end Fast_Tan;
function Fast_Arcsin (X : Long_Complex) return Long_Complex is
begin
return To_Long_Complex (Fast_Arcsin (To_Long_Long_Complex (X)));
end Fast_Arcsin;
function Fast_Arccos (X : Long_Complex) return Long_Complex is
begin
return To_Long_Complex (Fast_Arccos (To_Long_Long_Complex (X)));
end Fast_Arccos;
function Fast_Arctan (X : Long_Complex) return Long_Complex is
begin
return To_Long_Complex (Fast_Arctan (To_Long_Long_Complex (X)));
end Fast_Arctan;
function Fast_Sinh (X : Long_Complex) return Long_Complex is
begin
return To_Long_Complex (Fast_Sinh (To_Long_Long_Complex (X)));
end Fast_Sinh;
function Fast_Cosh (X : Long_Complex) return Long_Complex is
begin
return To_Long_Complex (Fast_Cosh (To_Long_Long_Complex (X)));
end Fast_Cosh;
function Fast_Tanh (X : Long_Complex) return Long_Complex is
begin
return To_Long_Complex (Fast_Tanh (To_Long_Long_Complex (X)));
end Fast_Tanh;
function Fast_Arcsinh (X : Long_Complex) return Long_Complex is
begin
return To_Long_Complex (Fast_Arcsinh (To_Long_Long_Complex (X)));
end Fast_Arcsinh;
function Fast_Arccosh (X : Long_Complex) return Long_Complex is
begin
return To_Long_Complex (Fast_Arccosh (To_Long_Long_Complex (X)));
end Fast_Arccosh;
function Fast_Arctanh (X : Long_Complex) return Long_Complex is
begin
return To_Long_Complex (Fast_Arctanh (To_Long_Long_Complex (X)));
end Fast_Arctanh;
-- Long_Long_Complex
Pi : constant := Ada.Numerics.Pi;
Pi_Div_2 : constant := Pi / 2.0;
Sqrt_2 : constant := 1.4142135623730950488016887242096980785696;
Log_2 : constant := 0.6931471805599453094172321214581765680755;
Square_Root_Epsilon : constant Long_Long_Float :=
Sqrt_2 ** (1 - Long_Long_Float'Model_Mantissa);
Inv_Square_Root_Epsilon : constant Long_Long_Float :=
Sqrt_2 ** (Long_Long_Float'Model_Mantissa - 1);
Root_Root_Epsilon : constant Long_Long_Float :=
Sqrt_2 ** ((1 - Long_Long_Float'Model_Mantissa) / 2);
Log_Inverse_Epsilon_2 : constant Long_Long_Float :=
Long_Long_Float (Long_Long_Float'Model_Mantissa - 1) / 2.0;
function Fast_Log (X : Long_Long_Complex) return Long_Long_Complex is
begin
if abs (1.0 - X.Re) < Root_Root_Epsilon
and then abs X.Im < Root_Root_Epsilon
then
declare
Z : constant Long_Long_Complex := (Re => X.Re - 1.0, Im => X.Im);
-- X - 1.0
Result : constant Long_Long_Complex :=
(1.0 - (1.0 / 2.0 - (1.0 / 3.0 - (1.0 / 4.0) * Z) * Z) * Z) * Z;
begin
return Result;
end;
else
declare
Result_Re : constant Long_Long_Float :=
Long_Long_Elementary_Functions.Fast_Log (
Long_Long_Complex_Types.Fast_Modulus (X));
Result_Im : constant Long_Long_Float :=
Long_Long_Elementary_Functions.Fast_Arctan (X.Im, X.Re);
begin
if Result_Im > Pi then
return (Re => Result_Re, Im => Result_Im - 2.0 * Pi);
else
return (Re => Result_Re, Im => Result_Im);
end if;
end;
end if;
end Fast_Log;
function Fast_Exp (X : Long_Long_Complex) return Long_Long_Complex is
Y : constant Long_Long_Float :=
Long_Long_Elementary_Functions.Fast_Exp (X.Re);
begin
return (
Re => Y * Long_Long_Elementary_Functions.Fast_Cos (X.Im),
Im => Y * Long_Long_Elementary_Functions.Fast_Sin (X.Im));
end Fast_Exp;
function Fast_Exp (X : Long_Long_Imaginary) return Long_Long_Complex is
begin
return (
Re => Long_Long_Elementary_Functions.Fast_Cos (Long_Long_Float (X)),
Im => Long_Long_Elementary_Functions.Fast_Sin (Long_Long_Float (X)));
end Fast_Exp;
function Fast_Pow (Left, Right : Long_Long_Complex)
return Long_Long_Complex is
begin
if (Left.Re = 0.0 or else Left.Re = 1.0) and then Left.Im = 0.0 then
return Left;
else
return Fast_Exp (Right * Fast_Log (Left));
end if;
end Fast_Pow;
function Fast_Sin (X : Long_Long_Complex) return Long_Long_Complex is
begin
if abs X.Re < Square_Root_Epsilon
and then abs X.Im < Square_Root_Epsilon
then
return X;
else
return (
Re =>
Long_Long_Elementary_Functions.Fast_Sin (X.Re)
* Long_Long_Elementary_Functions.Fast_Cosh (X.Im),
Im =>
Long_Long_Elementary_Functions.Fast_Cos (X.Re)
* Long_Long_Elementary_Functions.Fast_Sinh (X.Im));
end if;
end Fast_Sin;
function Fast_Cos (X : Long_Long_Complex) return Long_Long_Complex is
begin
return (
Re =>
Long_Long_Elementary_Functions.Fast_Cos (X.Re)
* Long_Long_Elementary_Functions.Fast_Cosh (X.Im),
Im =>
-(Long_Long_Elementary_Functions.Fast_Sin (X.Re)
* Long_Long_Elementary_Functions.Fast_Sinh (X.Im)));
end Fast_Cos;
function Fast_Tan (X : Long_Long_Complex) return Long_Long_Complex is
begin
if abs X.Re < Square_Root_Epsilon
and then abs X.Im < Square_Root_Epsilon
then
return X;
elsif X.Im > Log_Inverse_Epsilon_2 then
return (Re => 0.0, Im => 1.0);
elsif X.Im < -Log_Inverse_Epsilon_2 then
return (Re => 0.0, Im => -1.0);
else
return Fast_Sin (X) / Fast_Cos (X);
end if;
end Fast_Tan;
function Fast_Arcsin (X : Long_Long_Complex) return Long_Long_Complex is
begin
if abs X.Re < Square_Root_Epsilon
and then abs X.Im < Square_Root_Epsilon
then
return X;
elsif abs X.Re > Inv_Square_Root_Epsilon
or else abs X.Im > Inv_Square_Root_Epsilon
then
declare
iX : constant Long_Long_Complex := (Re => -X.Im, Im => X.Re);
Log_2i : constant Long_Long_Complex :=
Fast_Log ((Re => 0.0, Im => 2.0));
A : constant Long_Long_Complex :=
(Re => iX.Re + Log_2i.Re, Im => iX.Im + Log_2i.Im);
-- iX + Log_2i
Result : constant Long_Long_Complex := (Re => A.Im, Im => -A.Re);
-- -i * A
begin
if Result.Im > Pi_Div_2 then
return (Re => Result.Re, Im => Pi - X.Im);
elsif Result.Im < -Pi_Div_2 then
return (Re => Result.Re, Im => -(Pi + X.Im));
else
return Result;
end if;
end;
else
declare
iX : constant Long_Long_Complex := (Re => -X.Im, Im => X.Re);
X_X : constant Long_Long_Complex := X * X;
A : constant Long_Long_Complex :=
(Re => 1.0 - X_X.Re, Im => -X_X.Im);
-- 1.0 - X_X
Sqrt_A : constant Long_Long_Complex := Fast_Sqrt (A);
B : constant Long_Long_Complex :=
(Re => iX.Re + Sqrt_A.Re, Im => iX.Im + Sqrt_A.Im);
-- iX + Sqrt_A
Log_B : constant Long_Long_Complex := Fast_Log (B);
Result : constant Long_Long_Complex :=
(Re => Log_B.Im, Im => -Log_B.Re);
-- -i * Log_B
begin
if X.Re = 0.0 then
return (Re => X.Re, Im => Result.Im);
elsif X.Im = 0.0 and then abs X.Re <= 1.00 then
return (Re => Result.Re, Im => X.Im);
else
return Result;
end if;
end;
end if;
end Fast_Arcsin;
function Fast_Arccos (X : Long_Long_Complex) return Long_Long_Complex is
begin
if X.Re = 1.0 and then X.Im = 0.0 then
return (Re => 0.0, Im => 0.0);
elsif abs X.Re < Square_Root_Epsilon
and then abs X.Im < Square_Root_Epsilon
then
return (Re => Pi_Div_2 - X.Re, Im => -X.Im);
elsif abs X.Re > Inv_Square_Root_Epsilon
or else abs X.Im > Inv_Square_Root_Epsilon
then
declare
A : constant Long_Long_Complex := (Re => 1.0 - X.Re, Im => -X.Im);
-- 1.0 - X
B : constant Long_Long_Complex :=
(Re => A.Re / 2.0, Im => A.Im / 2.0);
-- A / 2.0
Sqrt_B : constant Long_Long_Complex := Fast_Sqrt (B);
i_Sqrt_B : constant Long_Long_Complex :=
(Re => -Sqrt_B.Im, Im => Sqrt_B.Re);
C : constant Long_Long_Complex := (Re => 1.0 + X.Re, Im => X.Im);
-- 1.0 + X
D : constant Long_Long_Complex :=
(Re => C.Re / 2.0, Im => C.Im / 2.0);
-- C / 2.0
Sqrt_D : constant Long_Long_Complex := Fast_Sqrt (D);
E : constant Long_Long_Complex :=
(Re => Sqrt_D.Re + i_Sqrt_B.Re, Im => Sqrt_D.Im + i_Sqrt_B.Im);
-- Sqrt_D + i_Sqrt_B
Log_E : constant Long_Long_Complex := Fast_Log (E);
Result : constant Long_Long_Complex :=
(Re => 2.0 * Log_E.Im, Im => -2.0 * Log_E.Re);
-- -2.0 * i * Log_E
begin
return Result;
end;
else
declare
X_X : constant Long_Long_Complex := X * X;
A : constant Long_Long_Complex :=
(Re => 1.0 - X_X.Re, Im => -X_X.Im);
-- 1.0 - X_X
Sqrt_A : constant Long_Long_Complex := Fast_Sqrt (A);
i_Sqrt_A : constant Long_Long_Complex :=
(Re => -Sqrt_A.Im, Im => Sqrt_A.Re);
B : constant Long_Long_Complex :=
(Re => X.Re + i_Sqrt_A.Re, Im => X.Im + i_Sqrt_A.Im);
-- X + i_Sqrt_A
Log_B : constant Long_Long_Complex := Fast_Log (B);
Result : constant Long_Long_Complex :=
(Re => Log_B.Im, Im => -Log_B.Re);
-- -i * Log_B
begin
if X.Im = 0.0 and then abs X.Re <= 1.00 then
return (Re => Result.Re, Im => X.Im);
else
return Result;
end if;
end;
end if;
end Fast_Arccos;
function Fast_Arctan (X : Long_Long_Complex) return Long_Long_Complex is
begin
if abs X.Re < Square_Root_Epsilon
and then abs X.Im < Square_Root_Epsilon
then
return X;
else
declare
iX : constant Long_Long_Complex := (Re => -X.Im, Im => X.Re);
A : constant Long_Long_Complex := (Re => 1.0 + iX.Re, Im => iX.Im);
-- 1.0 + iX
Log_A : constant Long_Long_Complex := Fast_Log (A);
B : constant Long_Long_Complex :=
(Re => 1.0 - iX.Re, Im => -iX.Im);
-- 1.0 - iX
Log_B : constant Long_Long_Complex := Fast_Log (B);
C : constant Long_Long_Complex :=
(Re => Log_A.Re - Log_B.Re, Im => Log_A.Im - Log_B.Im);
-- Log_A - Log_B
Result : constant Long_Long_Complex :=
(Re => C.Im / 2.0, Im => -C.Re / 2.0);
-- -i * C / 2.0
begin
return Result;
end;
end if;
end Fast_Arctan;
function Fast_Sinh (X : Long_Long_Complex) return Long_Long_Complex is
begin
if abs X.Re < Square_Root_Epsilon
and then abs X.Re < Square_Root_Epsilon
then
return X;
else
return (
Re =>
Long_Long_Elementary_Functions.Fast_Sinh (X.Re)
* Long_Long_Elementary_Functions.Fast_Cos (X.Im),
Im =>
Long_Long_Elementary_Functions.Fast_Cosh (X.Re)
* Long_Long_Elementary_Functions.Fast_Sin (X.Im));
end if;
end Fast_Sinh;
function Fast_Cosh (X : Long_Long_Complex) return Long_Long_Complex is
begin
return (
Re =>
Long_Long_Elementary_Functions.Fast_Cosh (X.Re)
* Long_Long_Elementary_Functions.Fast_Cos (X.Im),
Im =>
Long_Long_Elementary_Functions.Fast_Sinh (X.Re)
* Long_Long_Elementary_Functions.Fast_Sin (X.Im));
end Fast_Cosh;
function Fast_Tanh (X : Long_Long_Complex) return Long_Long_Complex is
begin
if abs X.Re < Square_Root_Epsilon
and then abs X.Im < Square_Root_Epsilon
then
return X;
elsif X.Re > Log_Inverse_Epsilon_2 then
return (Re => 1.0, Im => 0.0);
elsif X.Re < -Log_Inverse_Epsilon_2 then
return (Re => -1.0, Im => 0.0);
else
return Fast_Sinh (X) / Fast_Cosh (X);
end if;
end Fast_Tanh;
function Fast_Arcsinh (X : Long_Long_Complex) return Long_Long_Complex is
begin
if abs X.Re < Square_Root_Epsilon
and then abs X.Im < Square_Root_Epsilon
then
return X;
elsif abs X.Re > Inv_Square_Root_Epsilon
or else abs X.Im > Inv_Square_Root_Epsilon
then
declare
Log_X : constant Long_Long_Complex := Fast_Log (X);
Result : constant Long_Long_Complex :=
(Re => Log_2 + Log_X.Re, Im => Log_X.Im);
-- Log_2 + Log_X
begin
if (X.Re < 0.0 and then Result.Re > 0.0)
or else (X.Re > 0.0 and then Result.Re < 0.0)
then
return (Re => -Result.Re, Im => Result.Im);
else
return Result;
end if;
end;
else
declare
X_X : constant Long_Long_Complex := X * X;
A : constant Long_Long_Complex :=
(Re => 1.0 + X_X.Re, Im => X_X.Im);
-- 1.0 + X_X
Sqrt_A : constant Long_Long_Complex := Fast_Sqrt (A);
B : constant Long_Long_Complex :=
(Re => X.Re + Sqrt_A.Re, Im => X.Im + Sqrt_A.Im);
-- X + Sqrt_A
Result : constant Long_Long_Complex := Fast_Log (B);
begin
if X.Re = 0.0 then
return (Re => X.Re, Im => Result.Im);
elsif X.Im = 0.0 then
return (Re => Result.Re, Im => X.Im);
else
return Result;
end if;
end;
end if;
end Fast_Arcsinh;
function Fast_Arccosh (X : Long_Long_Complex) return Long_Long_Complex is
begin
if X.Re = 1.0 and then X.Im = 0.0 then
return (Re => 0.0, Im => 0.0);
elsif abs X.Re < Square_Root_Epsilon
and then abs X.Im < Square_Root_Epsilon
then
declare
Result : constant Long_Long_Complex :=
(Re => -X.Im, Im => X.Re - Pi_Div_2);
-- i * X - i * (Pi / 2)
begin
if Result.Re <= 0.0 then
return (Re => -Result.Re, Im => -Result.Im);
else
return Result;
end if;
end;
elsif abs X.Re > Inv_Square_Root_Epsilon
or else abs X.Im > Inv_Square_Root_Epsilon
then
declare
Log_X : constant Long_Long_Complex := Fast_Log (X);
Result : constant Long_Long_Complex :=
(Re => Log_2 + Log_X.Re, Im => Log_X.Im);
-- Log_2 + Log_X
begin
if Result.Re <= 0.0 then
return (Re => -Result.Re, Im => -Result.Im);
else
return Result;
end if;
end;
else
declare
A : constant Long_Long_Complex := (Re => X.Re + 1.0, Im => X.Im);
-- X + 1.0
B : constant Long_Long_Complex :=
(Re => A.Re / 2.0, Im => A.Im / 2.0);
-- A / 2.0
Sqrt_B : constant Long_Long_Complex := Fast_Sqrt (B);
C : constant Long_Long_Complex := (Re => X.Re - 1.0, Im => X.Im);
-- X - 1.0
D : constant Long_Long_Complex :=
(Re => C.Re / 2.0, Im => C.Im / 2.0);
-- C / 2.0
Sqrt_D : constant Long_Long_Complex := Fast_Sqrt (D);
E : constant Long_Long_Complex :=
(Re => Sqrt_B.Re + Sqrt_D.Re, Im => Sqrt_B.Im + Sqrt_D.Im);
-- Sqrt_B + Sqrt_D
Log_E : constant Long_Long_Complex := Fast_Log (E);
Result : constant Long_Long_Complex :=
(Re => 2.0 * Log_E.Re, Im => 2.0 * Log_E.Im);
-- 2.0 * Log_E
begin
if Result.Re <= 0.0 then
return (Re => -Result.Re, Im => -Result.Im);
else
return Result;
end if;
end;
end if;
end Fast_Arccosh;
function Fast_Arctanh (X : Long_Long_Complex) return Long_Long_Complex is
begin
if abs X.Re < Square_Root_Epsilon
and then abs X.Im < Square_Root_Epsilon
then
return X;
else
declare
A : constant Long_Long_Complex := (Re => 1.0 + X.Re, Im => X.Im);
-- 1.0 + X
Log_A : constant Long_Long_Complex := Fast_Log (A);
B : constant Long_Long_Complex := (Re => 1.0 - X.Re, Im => -X.Im);
-- 1.0 - X
Log_B : constant Long_Long_Complex := Fast_Log (B);
C : constant Long_Long_Complex :=
(Re => Log_A.Re - Log_B.Re, Im => Log_A.Im - Log_B.Im);
-- Log_A - Log_B
Result : constant Long_Long_Complex :=
(Re => C.Re / 2.0, Im => C.Im / 2.0);
-- C / 2.0
begin
return Result;
end;
end if;
end Fast_Arctanh;
end System.Long_Long_Complex_Elementary_Functions;
|
------------------------------------------------------------------------------
-- File: apackdemo.adb
-- Description: aPLib binding demo (Q&D!)
-- Date/version: 24-Feb-2001 ; ... ; 9.III.1999
-- Author: Gautier de Montmollin - gdemont@hotmail.com
------------------------------------------------------------------------------
with APLib;
with Ada.Calendar; use Ada.Calendar;
with Ada.Command_Line; use Ada.Command_Line;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Float_Text_IO; use Ada.Float_Text_IO;
with Ada.Direct_IO;
procedure APacDemo is
type byte is mod 2 ** 8; for byte'size use 8; -- could be any basic data
type t_data_array is array(integer range <>) of byte;
type p_data_array is access t_data_array;
-- NB: File management is simpler with Ada95 Stream_IO - it's to test...
package DBIO is new Ada.Direct_IO(byte); use DBIO;
subtype file_of_byte is DBIO.File_type;
procedure Read_file(n: String; d: out p_data_array) is
f : file_of_byte; b: byte;
begin
d:= null;
Open(f, in_file, n);
d:= New t_data_array(1..integer(size(f)));
for i in d'range loop Read(f,b); d(i):= b; end loop;
Close(f);
exception
when DBIO.Name_Error => Put_Line("File " & n & " not found !");
end;
procedure Write_file(n: String; d: t_data_array) is
f : file_of_byte;
begin
Create(f, out_file, n);
for i in d'range loop Write(f,d(i)); end loop;
Close(f);
end;
procedure Test_pack_unpack(name: string; id: natural) is
ext1: constant string:= integer'image(id+1000);
ext: constant string:= ext1(ext1'last-2..ext1'last); -- 000 001 002 etc.
name_p: constant string:= "packed." & ext;
name_pu: constant string:= "pack_unp." & ext;
frog, frog2, frog3: p_data_array;
pl, ul, plmax: integer; -- packed / unpacked sizes in _bytes_
pack_occur: natural:= 0;
T0, T1, T2, T3: Time;
procedure Packometer(u,p: integer; continue: out boolean) is
li: constant:= 50;
pli: constant integer:= (p*li)/ul;
uli: constant integer:= (u*li)/ul;
fancy_1: constant string:=" .oO";
fancy_2: constant string:="|/-\";
fancy: string renames fancy_2; -- choose one...
begin
Put(" [");
for i in 0..pli-1 loop put('='); end loop;
put(fancy(fancy'first+pack_occur mod fancy'length));
pack_occur:= pack_occur + 1;
for i in pli+1..uli loop put('.'); end loop;
for i in uli+1..li loop put(' '); end loop;
Put("] " & integer'image((100*p)/u)); Put("% " & ASCII.CR);
continue:= true;
end Packometer;
procedure Pack(u: t_data_array; p: out t_data_array; pl: out integer) is
subtype tp is t_data_array(p'range);
subtype tu is t_data_array(u'range);
procedure Pa is new APLib.Pack(tp, tu, Packometer);
begin
Pa(u,p,pl);
end Pack;
procedure Depack(p: t_data_array; u: out t_data_array) is
subtype tp is t_data_array(p'range);
subtype tu is t_data_array(u'range);
procedure De is new APLib.Depack(tp, tu);
begin
De(p,u);
end Depack;
bytes_per_element: constant integer:= byte'size/8;
begin
New_Line;
Read_file(name, frog);
if frog /= null then
ul:= frog.all'size / 8; -- frog.all is the array; ul= size in bytes
plmax:= aPLib.Evaluate_max_packed_space(ul);
frog2:= New t_data_array( 1 .. plmax / bytes_per_element );
Put_Line("File name: " & name);
New_Line;
T0:= Clock;
Pack(frog.all, frog2.all, pl);
T1:= Clock;
New_Line;
New_Line;
Put("Unpacked size : "); Put(ul); New_Line;
Put("Res. for packing : "); Put(plmax); New_Line;
Put("Packed size : "); Put(pl); New_Line;
Put("Work memory size : "); Put(aPLib.aP_workmem_size(ul)); New_Line;
Put("Compression ratio: "); Put((100*pl)/ul,0); Put_Line("%");
Put_Line("Packed file name : " & name_p);
Put_Line("Re-depacked file name : " & name_pu);
New_Line;
Put_Line("Real time for compression : " & Duration'Image(T1-T0));
Write_file(name_p, frog2(1..pl));
frog3:= New t_data_array(frog'range);
T2:= Clock;
Depack( frog2(1..pl), frog3.all );
T3:= Clock;
Put("Real time for decompression: " & Duration'Image(T3-T2) &
" - time ratio :" );
Put(Float(T3-T2) / Float(T1-T0),2,4,0);
New_Line;
Write_file(name_pu, frog3.all);
Put_Line("Are unpacked and original files identical ? " &
Boolean'image( frog.all = frog3.all ));
end if;
end Test_pack_unpack;
begin
Put_Line("APack_Demo");
New_Line;
Put_Line("Command: apacdemo file1 file2 file3 ...");
Put_Line("In a GUI drop the file(s) on the apacdemo application");
New_Line;
Put_Line("When no file is specified, 'apacdemo.exe' is used");
Put_Line("The data are packed, unpacked and compared with originals.");
if Argument_count=0 then
Test_pack_unpack( "apacdemo.exe",0 );
else
for i in 1..Argument_count loop
Test_pack_unpack( Argument(i),i );
end loop;
end if;
New_Line;
Put("Finished - press return please"); Skip_Line;
end APacDemo;
|
-- =============================================================================
-- Package AVR.POWER_MANAGEMENT
--
-- Handles the power management.
-- - Sleep mode
-- - Power reduction
-- =============================================================================
package AVR.POWER_MANAGEMENT is
type Sleep_Mode_Control_Register_Type is
record
SE : Boolean; -- Sleep Enable
SM0 : Boolean; -- Sleep Mode Select Bit 0
SM1 : Boolean; -- Sleep Mode Select Bit 1
SM2 : Boolean; -- Sleep Mode Select Bit 2
Spare : Spare_Type (0 .. 3);
end record;
pragma Pack (Sleep_Mode_Control_Register_Type);
for Sleep_Mode_Control_Register_Type'Size use BYTE_SIZE;
Reg_SMCR : Sleep_Mode_Control_Register_Type;
for Reg_SMCR'Address use System'To_Address (16#53#);
type Power_Reduction_Register_0_Type is
record
PRADC : Boolean; -- Power Reduction ADC
PRUSART0 : Boolean; -- Power Reduction USART0
PRSPI : Boolean; -- Power Reduction Serial Peripheral Interface
PRTIM1 : Boolean; -- Power Reduction Timer/Counter 1
Spare : Spare_Type (0 .. 0);
PRTIM0 : Boolean; -- Power Reduction Timer/Counter 0
PRTIM2 : Boolean; -- Power Reduction Timer/Counter 2
PRTWI : Boolean; -- Power Reduction TWI
end record;
pragma Pack (Power_Reduction_Register_0_Type);
for Power_Reduction_Register_0_Type'Size use BYTE_SIZE;
#if MCU="ATMEGA2560" then
type Power_Reduction_Register_1_Type is
record
PRUSART1 : Boolean; -- Power Reduction USART 1
PRUSART2 : Boolean; -- Power Reduction USART 2
PRUSART3 : Boolean; -- Power Reduction USART 3
PRTIM3 : Boolean; -- Power Reductin Timer/Counter 3
PRTIM4 : Boolean; -- Power Reductin Timer/Counter 4
PRTIM5 : Boolean; -- Power Reductin Timer/Counter 5
Spare : Spare_Type (0 .. 1);
end record;
pragma Pack (Power_Reduction_Register_1_Type);
for Power_Reduction_Register_1_Type'Size use BYTE_SIZE;
#end if;
Reg_PRR0 : Power_Reduction_Register_0_Type;
for Reg_PRR0'Address use System'To_Address (16#64#);
#if MCU="ATMEGA2560" then
Reg_PRR1 : Power_Reduction_Register_0_Type;
for Reg_PRR1'Address use System'To_Address (16#65#);
#end if;
end AVR.POWER_MANAGEMENT;
|
-----------------------------------------------------------------------
-- Sessions Tests - Unit tests for ASF.Sessions
-- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Measures;
with ASF.Applications;
with ASF.Streams;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
package body ASF.Servlets.Tests is
use Util.Tests;
procedure Do_Get (Server : in Test_Servlet1;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
pragma Unreferenced (Server);
Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream;
begin
Output.Write ("URI: " & Request.Get_Request_URI);
Response.Set_Status (Responses.SC_OK);
end Do_Get;
procedure Do_Post (Server : in Test_Servlet2;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
begin
null;
end Do_Post;
S1 : aliased Test_Servlet1;
S2 : aliased Test_Servlet2;
-- ------------------------------
-- Check that the request is done on the good servlet and with the correct servlet path
-- and path info.
-- ------------------------------
procedure Check_Request (T : in out Test;
Ctx : in Servlet_Registry;
URI : in String;
Servlet_Path : in String;
Path_Info : in String) is
Dispatcher : constant Request_Dispatcher
:= Ctx.Get_Request_Dispatcher (Path => URI);
Req : ASF.Requests.Mockup.Request;
Resp : ASF.Responses.Mockup.Response;
Result : Unbounded_String;
begin
T.Assert (Dispatcher.Mapping /= null, "No mapping found");
Req.Set_Request_URI ("test1");
Req.Set_Method ("GET");
Forward (Dispatcher, Req, Resp);
Assert_Equals (T, Servlet_Path, Req.Get_Servlet_Path, "Invalid servlet path");
Assert_Equals (T, Path_Info, Req.Get_Path_Info,
"The request path info is invalid");
-- Check the response after the Test_Servlet1.Do_Get method execution.
Resp.Read_Content (Result);
Assert_Equals (T, ASF.Responses.SC_OK, Resp.Get_Status, "Invalid status");
Assert_Equals (T, "URI: test1", Result, "Invalid content");
Req.Set_Method ("POST");
Forward (Dispatcher, Req, Resp);
Assert_Equals (T, ASF.Responses.SC_METHOD_NOT_ALLOWED, Resp.Get_Status,
"Invalid status for an operation not implemented");
end Check_Request;
-- ------------------------------
-- Test request dispatcher and servlet invocation
-- ------------------------------
procedure Test_Request_Dispatcher (T : in out Test) is
Ctx : Servlet_Registry;
S1 : aliased Test_Servlet1;
begin
Ctx.Add_Servlet ("Faces", S1'Unchecked_Access);
Ctx.Add_Mapping (Pattern => "*.jsf", Name => "Faces");
Ctx.Add_Mapping (Pattern => "/p1/p2/p3/*", Name => "Faces");
Check_Request (T, Ctx, "/home/test.jsf", "", "/home/test.jsf");
end Test_Request_Dispatcher;
-- ------------------------------
-- Test mapping and servlet path on a request.
-- ------------------------------
procedure Test_Servlet_Path (T : in out Test) is
Ctx : Servlet_Registry;
S1 : aliased Test_Servlet1;
begin
Ctx.Add_Servlet ("Faces", S1'Unchecked_Access);
Ctx.Add_Mapping (Pattern => "*.jsf", Name => "Faces");
Ctx.Add_Mapping (Pattern => "/p1/p2/p3/*", Name => "Faces");
Check_Request (T, Ctx, "/p1/p2/p3/home/test.html", "/p1/p2/p3", "/home/test.html");
end Test_Servlet_Path;
-- ------------------------------
-- Test add servlet
-- ------------------------------
procedure Test_Add_Servlet (T : in out Test) is
Ctx : Servlet_Registry;
S1 : aliased Test_Servlet1;
begin
Ctx.Add_Servlet ("Faces", S1'Unchecked_Access);
Assert_Equals (T, "Faces", S1.Get_Name, "Invalid name for the servlet");
begin
Ctx.Add_Servlet ("Faces", S1'Unchecked_Access);
T.Assert (False, "No exception raised if the servlet is registered several times");
exception
when Servlet_Error =>
null;
end;
end Test_Add_Servlet;
-- ------------------------------
-- Test getting a resource path
-- ------------------------------
procedure Test_Get_Resource (T : in out Test) is
Ctx : Servlet_Registry;
Conf : Applications.Config;
S1 : aliased Test_Servlet1;
Dir : constant String := "regtests/files";
Path : constant String := Util.Tests.Get_Path (Dir);
begin
Conf.Load_Properties ("regtests/view.properties");
Conf.Set ("view.dir", Path);
Ctx.Set_Init_Parameters (Conf);
Ctx.Add_Servlet ("Faces", S1'Unchecked_Access);
-- Resource exist, check the returned path.
declare
P : constant String := Ctx.Get_Resource ("/tests/form-text.xhtml");
begin
Assert_Matches (T, ".*/regtests/files/tests/form-text.xhtml",
P, "Invalid resource path");
end;
-- Resource does not exist
declare
P : constant String := Ctx.Get_Resource ("/tests/form-text-missing.xhtml");
begin
Assert_Equals (T, "", P, "Invalid resource path for missing resource");
end;
end Test_Get_Resource;
-- ------------------------------
-- Check that the mapping for the given URI matches the server.
-- ------------------------------
procedure Check_Mapping (T : in out Test;
Ctx : in Servlet_Registry;
URI : in String;
Server : in Servlet_Access) is
Map : constant Mapping_Access := Ctx.Find_Mapping (URI);
begin
if Map = null then
T.Assert (Server = null, "No mapping returned for URI: " & URI);
else
T.Assert (Server /= null, "A mapping is returned for URI: " & URI);
T.Assert (Map.Servlet = Server, "Invalid mapping returned for URI: " & URI);
end if;
end Check_Mapping;
-- ------------------------------
-- Test session creation.
-- ------------------------------
procedure Test_Create_Servlet (T : in out Test) is
Ctx : Servlet_Registry;
Map : Mapping_Access;
begin
Ctx.Add_Servlet (Name => "Faces", Server => S1'Access);
Ctx.Add_Servlet (Name => "Text", Server => S2'Access);
Ctx.Add_Mapping (Pattern => "*.jsf", Name => "Faces");
Ctx.Add_Mapping (Pattern => "*.html", Name => "Faces");
Ctx.Add_Mapping (Pattern => "*.txt", Name => "Text");
-- Ctx.Add_Mapping (Pattern => "/server", Server => S2'Access);
Ctx.Add_Mapping (Pattern => "/server/john/*", Server => S2'Access);
Ctx.Add_Mapping (Pattern => "/server/info", Server => S1'Access);
Ctx.Add_Mapping (Pattern => "/server/list", Server => S1'Access);
Ctx.Add_Mapping (Pattern => "/server/list2", Server => S2'Access);
Ctx.Add_Mapping (Pattern => "/1/2/3/4/5/6/7/8/9/server/list2", Server => S2'Access);
Ctx.Add_Mapping (Pattern => "/1/2/3/4/5/6/7/8/A/server/list2", Server => S1'Access);
Ctx.Mappings.Dump_Map (" ");
T.Check_Mapping (Ctx, "/joe/black/joe.jsf", S1'Access);
T.Check_Mapping (Ctx, "/joe/black/joe.txt", S2'Access);
T.Check_Mapping (Ctx, "/server/info", S1'Access);
T.Check_Mapping (Ctx, "/server/list2", S2'Access);
T.Check_Mapping (Ctx, "/1/2/3/4/5/6/7/8/9/server/list2", S2'Access);
T.Check_Mapping (Ctx, "/1/2/3/4/5/6/7/8/A/server/list2", S1'Access);
declare
St : Util.Measures.Stamp;
begin
for I in 1 .. 1000 loop
Map := Ctx.Find_Mapping (URI => "/joe/black/joe.jsf");
end loop;
Util.Measures.Report (St, "Find 1000 mapping (extension)");
end;
T.Assert (Map /= null, "No mapping for 'joe.jsf'");
T.Assert (Map.Servlet /= null, "No servlet for mapping for 'joe.jsf'");
T.Assert (Map.Servlet = S1'Access, "Invalid servlet");
-- Util.Measures.Report (St, "10 Session create");
declare
St : Util.Measures.Stamp;
begin
for I in 1 .. 1000 loop
Map := Ctx.Find_Mapping (URI => "/1/2/3/4/5/6/7/8/9/server/list2");
end loop;
Util.Measures.Report (St, "Find 1000 mapping (path)");
end;
T.Assert (Map /= null, "No mapping for '/server/john/joe.jsf'");
T.Assert (Map.Servlet /= null, "No servlet for mapping for 'joe.jsf'");
T.Assert (Map.Servlet = S2'Access, "Invalid servlet");
-- Util.Measures.Report (St, "10 Session create");
end Test_Create_Servlet;
package Caller is new Util.Test_Caller (Test, "Servlets");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
-- To document what is tested, register the test methods for each
-- operation that is tested.
Caller.Add_Test (Suite, "Test ASF.Servlets.Add_Mapping,Find_Mapping",
Test_Create_Servlet'Access);
Caller.Add_Test (Suite, "Test ASF.Servlets.Add_Servlet",
Test_Add_Servlet'Access);
Caller.Add_Test (Suite, "Test ASF.Servlets.Get_Request_Dispatcher",
Test_Request_Dispatcher'Access);
Caller.Add_Test (Suite, "Test ASF.Servlets.Get_Resource",
Test_Get_Resource'Access);
Caller.Add_Test (Suite, "Test ASF.Requests.Get_Servlet_Path",
Test_Servlet_Path'Access);
end Add_Tests;
end ASF.Servlets.Tests;
|
However, I have found the following bug, having to do with end_of_file
detection:
-----8<-----CUT-HERE-----8<-----
BUG #1: The following is returned:
Rule 5: COMP ->
** parse returned OK
main task terminated due to unhandled exception END_ERROR
propagated from GET_TOKEN at line 104 (End of file on TEXT_IO input)
GET_TOKEN: the lines
[lines deleted from GET_TOKEN]
if end_of_file then
state := eof;
exit;
end if;
get(ch); -- line 104
[further lines deleted]
Sample data:
this is where er 74 68 69 73 20 69 73 20-77 68 65 72 65 20 65 72
ror > 8pm and th 72 6F 72 20 3E 20 38 70-6D 20 61 6E 64 20 74 68
e rest.. 65 20 72 65 73 74 0D 0A
However, when the trailing CRLF is removed, the above works with no
problems.
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
with Ada.Command_Line;
with PortScan.Ops;
with Signals;
with Unix;
package body PortScan.Packages is
package CLI renames Ada.Command_Line;
package OPS renames PortScan.Ops;
package SIG renames Signals;
---------------------------
-- wipe_out_repository --
---------------------------
procedure wipe_out_repository (repository : String)
is
pkg_search : AD.Search_Type;
dirent : AD.Directory_Entry_Type;
begin
AD.Start_Search (Search => pkg_search,
Directory => repository,
Filter => (AD.Ordinary_File => True, others => False),
Pattern => "*.txz");
while AD.More_Entries (Search => pkg_search) loop
AD.Get_Next_Entry (Search => pkg_search,
Directory_Entry => dirent);
declare
pkgname : String := repository & "/" & AD.Simple_Name (dirent);
begin
AD.Delete_File (pkgname);
end;
end loop;
end wipe_out_repository;
-----------------------------
-- remove_queue_packages --
-----------------------------
procedure remove_queue_packages (repository : String)
is
procedure remove_package (cursor : ranking_crate.Cursor);
procedure remove_package (cursor : ranking_crate.Cursor)
is
QR : constant queue_record := ranking_crate.Element (cursor);
fullpath : constant String := repository & "/" &
JT.USS (all_ports (QR.ap_index).package_name);
begin
if AD.Exists (fullpath) then
AD.Delete_File (fullpath);
end if;
end remove_package;
begin
rank_queue.Iterate (remove_package'Access);
end remove_queue_packages;
----------------------------
-- initial_package_scan --
----------------------------
procedure initial_package_scan (repository : String; id : port_id) is
begin
if id = port_match_failed then
return;
end if;
if not all_ports (id).scanned then
return;
end if;
declare
pkgname : constant String := JT.USS (all_ports (id).package_name);
fullpath : constant String := repository & "/" & pkgname;
msg_opt : constant String := pkgname & " failed option check.";
msg_abi : constant String := pkgname & " failed architecture (ABI) check.";
begin
if AD.Exists (fullpath) then
all_ports (id).pkg_present := True;
else
return;
end if;
if not passed_option_check (repository, id, True) then
obsolete_notice (msg_opt, True);
all_ports (id).deletion_due := True;
return;
end if;
if not passed_abi_check (repository, id, True) then
obsolete_notice (msg_abi, True);
all_ports (id).deletion_due := True;
return;
end if;
end;
all_ports (id).pkg_dep_query := result_of_dependency_query (repository, id);
end initial_package_scan;
---------------------------
-- remote_package_scan --
---------------------------
procedure remote_package_scan (id : port_id) is
begin
if passed_abi_check (repository => "", id => id,
skip_exist_check => True)
then
all_ports (id).remote_pkg := True;
else
return;
end if;
if not passed_option_check (repository => "", id => id,
skip_exist_check => True)
then
all_ports (id).remote_pkg := False;
return;
end if;
all_ports (id).pkg_dep_query :=
result_of_dependency_query (repository => "", id => id);
end remote_package_scan;
----------------------------
-- limited_sanity_check --
----------------------------
procedure limited_sanity_check (repository : String; dry_run : Boolean;
suppress_remote : Boolean)
is
procedure prune_packages (cursor : ranking_crate.Cursor);
procedure check_package (cursor : ranking_crate.Cursor);
procedure prune_queue (cursor : subqueue.Cursor);
procedure print (cursor : subqueue.Cursor);
procedure fetch (cursor : subqueue.Cursor);
procedure check (cursor : subqueue.Cursor);
already_built : subqueue.Vector;
fetch_list : subqueue.Vector;
fetch_fail : Boolean := False;
clean_pass : Boolean := False;
listlog : TIO.File_Type;
goodlog : Boolean;
using_screen : constant Boolean := Unix.screen_attached;
filename : constant String := "/var/synth/synth_prefetch_list.txt";
package_list : JT.Text := JT.blank;
procedure check_package (cursor : ranking_crate.Cursor)
is
target : port_id := ranking_crate.Element (cursor).ap_index;
pkgname : String := JT.USS (all_ports (target).package_name);
available : constant Boolean := all_ports (target).remote_pkg or else
(all_ports (target).pkg_present and then
not all_ports (target).deletion_due);
begin
if not available then
return;
end if;
if passed_dependency_check
(query_result => all_ports (target).pkg_dep_query, id => target)
then
already_built.Append (New_Item => target);
if all_ports (target).remote_pkg then
fetch_list.Append (New_Item => target);
end if;
else
if all_ports (target).remote_pkg then
-- silently fail, remote packages are a bonus anyway
all_ports (target).remote_pkg := False;
else
obsolete_notice (pkgname & " failed dependency check.", True);
all_ports (target).deletion_due := True;
end if;
clean_pass := False;
end if;
end check_package;
procedure prune_queue (cursor : subqueue.Cursor)
is
id : constant port_index := subqueue.Element (cursor);
begin
OPS.cascade_successful_build (id);
end prune_queue;
procedure prune_packages (cursor : ranking_crate.Cursor)
is
target : port_id := ranking_crate.Element (cursor).ap_index;
delete_it : Boolean := all_ports (target).deletion_due;
pkgname : String := JT.USS (all_ports (target).package_name);
fullpath : constant String := repository & "/" & pkgname;
begin
if delete_it then
AD.Delete_File (fullpath);
end if;
exception
when others => null;
end prune_packages;
procedure print (cursor : subqueue.Cursor)
is
id : constant port_index := subqueue.Element (cursor);
line : constant String := JT.USS (all_ports (id).package_name) &
" (" & get_catport (all_ports (id)) & ")";
begin
TIO.Put_Line (" => " & line);
if goodlog then
TIO.Put_Line (listlog, line);
end if;
end print;
procedure fetch (cursor : subqueue.Cursor)
is
id : constant port_index := subqueue.Element (cursor);
begin
JT.SU.Append (package_list, " " & id2pkgname (id));
end fetch;
procedure check (cursor : subqueue.Cursor)
is
id : constant port_index := subqueue.Element (cursor);
name : constant String := JT.USS (all_ports (id).package_name);
loc : constant String := JT.USS (PM.configuration.dir_repository) &
"/" & name;
begin
if not AD.Exists (loc) then
TIO.Put_Line ("Download failed: " & name);
fetch_fail := True;
end if;
end check;
begin
if Unix.env_variable_defined ("WHYFAIL") then
activate_debugging_code;
end if;
establish_package_architecture;
original_queue_len := rank_queue.Length;
for m in scanners'Range loop
mq_progress (m) := 0;
end loop;
start_obsolete_package_logging;
parallel_package_scan (repository, False, using_screen);
if SIG.graceful_shutdown_requested then
TIO.Close (obsolete_pkg_log);
return;
end if;
while not clean_pass loop
clean_pass := True;
already_built.Clear;
rank_queue.Iterate (check_package'Access);
end loop;
if not suppress_remote and then PM.configuration.defer_prebuilt then
-- The defer_prebuilt options has been elected, so check all the
-- missing and to-be-pruned ports for suitable prebuilt packages
-- So we need to an incremental scan (skip valid, present packages)
for m in scanners'Range loop
mq_progress (m) := 0;
end loop;
parallel_package_scan (repository, True, using_screen);
if SIG.graceful_shutdown_requested then
TIO.Close (obsolete_pkg_log);
return;
end if;
clean_pass := False;
while not clean_pass loop
clean_pass := True;
already_built.Clear;
fetch_list.Clear;
rank_queue.Iterate (check_package'Access);
end loop;
end if;
TIO.Close (obsolete_pkg_log);
if SIG.graceful_shutdown_requested then
return;
end if;
if dry_run then
if not fetch_list.Is_Empty then
begin
-- Try to defend malicious symlink: https://en.wikipedia.org/wiki/Symlink_race
if AD.Exists (filename) then
AD.Delete_File (filename);
end if;
TIO.Create (File => listlog, Mode => TIO.Out_File, Name => filename);
goodlog := True;
exception
when others => goodlog := False;
end;
TIO.Put_Line ("These are the packages that would be fetched:");
fetch_list.Iterate (print'Access);
TIO.Put_Line ("Total packages that would be fetched:" &
fetch_list.Length'Img);
if goodlog then
TIO.Close (listlog);
TIO.Put_Line ("The complete build list can also be found at:"
& LAT.LF & filename);
end if;
else
if PM.configuration.defer_prebuilt then
TIO.Put_Line ("No packages qualify for prefetching from " &
"official package repository.");
end if;
end if;
else
rank_queue.Iterate (prune_packages'Access);
fetch_list.Iterate (fetch'Access);
if not JT.equivalent (package_list, JT.blank) then
declare
cmd : constant String := host_pkg8 & " fetch -r " &
JT.USS (external_repository) & " -U -y --output " &
JT.USS (PM.configuration.dir_packages) & JT.USS (package_list);
begin
if Unix.external_command (cmd) then
null;
end if;
end;
fetch_list.Iterate (check'Access);
end if;
end if;
if fetch_fail then
TIO.Put_Line ("At least one package failed to fetch, aborting build!");
rank_queue.Clear;
else
already_built.Iterate (prune_queue'Access);
end if;
end limited_sanity_check;
---------------------------
-- preclean_repository --
---------------------------
procedure preclean_repository (repository : String)
is
procedure insert (cursor : string_crate.Cursor);
using_screen : constant Boolean := Unix.screen_attached;
uniqid : PortScan.port_id := 0;
procedure insert (cursor : string_crate.Cursor)
is
key2 : JT.Text := string_crate.Element (cursor);
begin
if not portlist.Contains (key2) then
uniqid := uniqid + 1;
portlist.Insert (key2, uniqid);
end if;
end insert;
begin
if not scan_repository (repository) then
return;
end if;
parallel_preliminary_package_scan (repository, using_screen);
for ndx in scanners'Range loop
stored_origins (ndx).Iterate (insert'Access);
stored_origins (ndx).Clear;
end loop;
end preclean_repository;
-----------------------
-- scan_repository --
-----------------------
function scan_repository (repository : String) return Boolean
is
pkg_search : AD.Search_Type;
dirent : AD.Directory_Entry_Type;
pkg_index : scanners := scanners'First;
result : Boolean := False;
begin
AD.Start_Search (Search => pkg_search,
Directory => repository,
Filter => (AD.Ordinary_File => True, others => False),
Pattern => "*.txz");
while AD.More_Entries (Search => pkg_search) loop
AD.Get_Next_Entry (Search => pkg_search,
Directory_Entry => dirent);
declare
pkgname : JT.Text := JT.SUS (AD.Simple_Name (dirent));
begin
stored_packages (pkg_index).Append (New_Item => pkgname);
if pkg_index = scanners (number_cores) then
pkg_index := scanners'First;
else
pkg_index := pkg_index + 1;
end if;
pkgscan_total := pkgscan_total + 1;
result := True;
end;
end loop;
return result;
end scan_repository;
-----------------------------
-- generic_system_command --
-----------------------------
function generic_system_command (command : String) return JT.Text
is
content : JT.Text;
status : Integer;
begin
content := Unix.piped_command (command, status);
if status /= 0 then
raise pkgng_execution with "pkg options query cmd: " & command &
" (return code =" & status'Img & ")";
end if;
return content;
end generic_system_command;
---------------------------
-- passed_option_check --
---------------------------
function passed_option_check (repository : String; id : port_id;
skip_exist_check : Boolean := False)
return Boolean
is
begin
if id = port_match_failed or else not all_ports (id).scanned then
return False;
end if;
declare
pkg_base : constant String := id2pkgname (id);
pkg_name : constant String := JT.USS (all_ports (id).package_name);
fullpath : constant String := repository & "/" & pkg_name;
command : constant String := host_pkg8 & " query -F " & fullpath &
" %Ok:%Ov";
remocmd : constant String := host_pkg8 & " rquery -r " &
JT.USS (external_repository) & " -U %Ok:%Ov " & pkg_base;
content : JT.Text;
topline : JT.Text;
colon : Natural;
required : Natural := Natural (all_ports (id).options.Length);
counter : Natural := 0;
begin
if not skip_exist_check and then not AD.Exists (Name => fullpath)
then
return False;
end if;
declare
begin
if repository = "" then
content := generic_system_command (remocmd);
else
content := generic_system_command (command);
end if;
exception
when pkgng_execution => return False;
end;
loop
JT.nextline (lineblock => content, firstline => topline);
exit when JT.IsBlank (topline);
colon := JT.SU.Index (Source => topline, Pattern => ":");
if colon < 2 then
raise unknown_format with JT.USS (topline);
end if;
declare
knob : String := JT.SU.Slice (Source => topline,
Low => colon + 1,
High => JT.SU.Length (topline));
namekey : JT.Text := JT.SUS (JT.SU.Slice (Source => topline,
Low => 1,
High => colon - 1));
knobval : Boolean;
begin
if knob = "on" then
knobval := True;
elsif knob = "off" then
knobval := False;
else
raise unknown_format
with "knob=" & knob & "(" & JT.USS (topline) & ")";
end if;
counter := counter + 1;
if counter > required then
-- package has more options than we are looking for
declare
msg : String := "options " & JT.USS (namekey) & LAT.LF &
pkg_name & " has more options than required " &
"(" & JT.int2str (required) & ")";
begin
obsolete_notice (msg, debug_opt_check);
end;
return False;
end if;
if all_ports (id).options.Contains (namekey) then
if knobval /= all_ports (id).options.Element (namekey) then
-- port option value doesn't match package option value
declare
msg_on : String := pkg_name & " " & JT.USS (namekey) &
" is ON but port says it must be OFF";
msg_off : String := pkg_name & " " & JT.USS (namekey) &
" is OFF but port says it must be ON";
begin
if knobval then
obsolete_notice (msg_on, debug_opt_check);
else
obsolete_notice (msg_off, debug_opt_check);
end if;
end;
return False;
end if;
else
-- Name of package option not found in port options
declare
msg : String := pkg_name & " option " & JT.USS (namekey) &
" is no longer present in the port";
begin
obsolete_notice (msg, debug_opt_check);
end;
return False;
end if;
end;
end loop;
if counter < required then
-- The ports tree has more options than the existing package
declare
msg : String := pkg_name & " has less options than required "
& "(" & JT.int2str (required) & ")";
begin
obsolete_notice (msg, debug_opt_check);
end;
return False;
end if;
-- If we get this far, the package options must match port options
return True;
end;
exception
when issue : others =>
obsolete_notice ("option check exception" & LAT.LF &
EX.Exception_Message (issue), debug_opt_check);
return False;
end passed_option_check;
----------------------------------
-- result_of_dependency_query --
----------------------------------
function result_of_dependency_query (repository : String; id : port_id)
return JT.Text
is
pkg_base : constant String := id2pkgname (id);
pkg_name : constant String := JT.USS (all_ports (id).package_name);
fullpath : constant String := repository & "/" & pkg_name;
command : constant String := host_pkg8 & " query -F " & fullpath & " %do:%dn-%dv";
remocmd : constant String := host_pkg8 & " rquery -r " &
JT.USS (external_repository) & " -U %do:%dn-%dv " & pkg_base;
begin
if repository = "" then
return generic_system_command (remocmd);
else
return generic_system_command (command);
end if;
exception
when others => return JT.blank;
end result_of_dependency_query;
-------------------------------
-- passed_dependency_check --
-------------------------------
function passed_dependency_check (query_result : JT.Text; id : port_id)
return Boolean
is
begin
declare
content : JT.Text := query_result;
topline : JT.Text;
colon : Natural;
min_deps : constant Natural := all_ports (id).min_librun;
max_deps : constant Natural := Natural (all_ports (id).librun.Length);
headport : constant String := get_catport (all_ports (id));
counter : Natural := 0;
begin
loop
JT.nextline (lineblock => content, firstline => topline);
exit when JT.IsBlank (topline);
colon := JT.SU.Index (Source => topline, Pattern => ":");
if colon < 2 then
raise unknown_format with JT.USS (topline);
end if;
declare
line : constant String := JT.USS (topline);
origin : constant String := JT.part_1 (line, ":");
deppkg : constant String := JT.part_2 (line, ":") & ".txz";
origintxt : JT.Text := JT.SUS (origin);
target_id : port_index;
target_pkg : JT.Text;
available : Boolean;
begin
-- The packages contain only the origin. We have no idea about which
-- flavor is used if that origin features flavors. We have to probe all
-- flavors and deduce the correct flavor (Definitely, FPC flavors are inferior
-- to Ravenports variants).
--
-- The original implementation looked up the first listed flavor. If it had
-- flavors defined, it would iterate through the list to match packages. We
-- can't use this approach because the "rebuild-repository" routine only does
-- a partial scan, so the first flavor may not be populated. Instead, we
-- linearly go through the serial list until we find a match (or first part
-- of origin doesn't match.
if so_porthash.Contains (origintxt) then
declare
probe_id : port_index := so_porthash.Element (origintxt);
base_pkg : String := JT.head (deppkg, "-");
found_it : Boolean := False;
maxprobe : port_index := port_index (so_serial.Length) - 1;
begin
loop
if all_ports (probe_id).scanned then
declare
pkg_file : String := JT.USS (all_ports (probe_id).package_name);
test_pkg : String := JT.head (pkg_file, "-");
begin
if test_pkg = base_pkg then
found_it := True;
target_id := probe_id;
exit;
end if;
end;
end if;
probe_id := probe_id + 1;
exit when probe_id > maxprobe;
exit when not JT.leads (so_serial.Element (probe_id), origin);
end loop;
if not found_it then
obsolete_notice (origin & " package unmatched", debug_dep_check);
return False;
end if;
end;
target_pkg := all_ports (target_id).package_name;
available := all_ports (target_id).remote_pkg or else
(all_ports (target_id).pkg_present and then
not all_ports (target_id).deletion_due);
else
-- package has a dependency that has been removed from the ports tree
declare
msg : String := origin & " has been removed from the ports tree";
begin
obsolete_notice (msg, debug_dep_check);
end;
return False;
end if;
counter := counter + 1;
if counter > max_deps then
-- package has more dependencies than we are looking for
declare
msg : String := headport & " package has more dependencies than the port " &
"requires (" & JT.int2str (max_deps) & ")" & LAT.LF &
"Query: " & JT.USS (query_result) & LAT.LF &
"Tripped on: " & JT.USS (target_pkg) & ":" & origin;
begin
obsolete_notice (msg, debug_dep_check);
end;
return False;
end if;
if deppkg /= JT.USS (target_pkg)
then
-- The version that the package requires differs from the
-- version that the ports tree will now produce
declare
msg : String :=
"Current " & headport & " package depends on " & deppkg &
", but this is a different version than requirement of " &
JT.USS (target_pkg) & " (from " & origin & ")";
begin
obsolete_notice (msg, debug_dep_check);
end;
return False;
end if;
if not available then
-- Even if all the versions are matching, we still need
-- the package to be in repository.
declare
msg : String :=
headport & " package depends on " & JT.USS (target_pkg) &
" which doesn't exist or has been scheduled " &
"for deletion";
begin
obsolete_notice (msg, debug_dep_check);
end;
return False;
end if;
end;
end loop;
if counter < min_deps then
-- The ports tree requires more dependencies than the existing
-- package does
declare
msg : String :=
headport & " package has less dependencies than the port " &
"requires (" & JT.int2str (min_deps) & ")" & LAT.LF &
"Query: " & JT.USS (query_result);
begin
obsolete_notice (msg, debug_dep_check);
end;
return False;
end if;
-- If we get this far, the package dependencies match what the
-- port tree requires exactly. This package passed sanity check.
return True;
end;
exception
when issue : others =>
obsolete_notice ("Dependency check exception" & LAT.LF &
EX.Exception_Message (issue), debug_dep_check);
return False;
end passed_dependency_check;
------------------
-- id2pkgname --
------------------
function id2pkgname (id : port_id) return String
is
pkg_name : constant String := JT.USS (all_ports (id).package_name);
len : constant Natural := pkg_name'Length - 4;
begin
return pkg_name (1 .. len);
end id2pkgname;
------------------------
-- passed_abi_check --
------------------------
function passed_abi_check (repository : String; id : port_id;
skip_exist_check : Boolean := False)
return Boolean
is
pkg_base : constant String := id2pkgname (id);
pkg_name : constant String := JT.USS (all_ports (id).package_name);
fullpath : constant String := repository & "/" & pkg_name;
command : constant String := host_pkg8 & " query -F " & fullpath & " %q";
remocmd : constant String := host_pkg8 & " rquery -r " &
JT.USS (external_repository) & " -U %q " & pkg_base;
content : JT.Text;
topline : JT.Text;
begin
if not skip_exist_check and then not AD.Exists (Name => fullpath)
then
return False;
end if;
declare
begin
if repository = "" then
content := generic_system_command (remocmd);
else
content := generic_system_command (command);
end if;
exception
when pkgng_execution => return False;
end;
JT.nextline (lineblock => content, firstline => topline);
if JT.equivalent (topline, abi_formats.calculated_abi) then
return True;
end if;
if JT.equivalent (topline, abi_formats.calc_abi_noarch) then
return True;
end if;
if JT.equivalent (topline, abi_formats.calculated_alt_abi) then
return True;
end if;
if JT.equivalent (topline, abi_formats.calc_alt_abi_noarch) then
return True;
end if;
return False;
exception
when others => return False;
end passed_abi_check;
----------------------
-- queue_is_empty --
----------------------
function queue_is_empty return Boolean is
begin
return rank_queue.Is_Empty;
end queue_is_empty;
--------------------------------------
-- establish_package_architecture --
--------------------------------------
procedure establish_package_architecture is
begin
abi_formats := Replicant.Platform.determine_package_architecture;
end establish_package_architecture;
---------------------------
-- original_queue_size --
---------------------------
function original_queue_size return Natural is
begin
return Natural (original_queue_len);
end original_queue_size;
----------------------------------
-- passed_options_cache_check --
----------------------------------
function passed_options_cache_check (id : port_id) return Boolean
is
target_dname : String := JT.replace (get_catport (all_ports (id)),
reject => LAT.Solidus,
shiny => LAT.Low_Line);
target_path : constant String := JT.USS (PM.configuration.dir_options) &
LAT.Solidus & target_dname & LAT.Solidus & "options";
marker : constant String := "+=";
option_file : TIO.File_Type;
required : Natural := Natural (all_ports (id).options.Length);
counter : Natural := 0;
result : Boolean := False;
begin
if not AD.Exists (target_path) then
return True;
end if;
TIO.Open (File => option_file,
Mode => TIO.In_File,
Name => target_path);
while not TIO.End_Of_File (option_file) loop
declare
Line : String := TIO.Get_Line (option_file);
namekey : JT.Text;
valid : Boolean := False;
begin
-- If "marker" starts at 17, it's OPTIONS_FILES_SET
-- if "marker" starts at 19, it's OPTIONS_FILES_UNSET
-- if neither, we don't care.
if Line (17 .. 18) = marker then
namekey := JT.SUS (Line (19 .. Line'Last));
valid := True;
elsif Line (19 .. 20) = marker then
namekey := JT.SUS (Line (21 .. Line'Last));
valid := True;
end if;
if valid then
counter := counter + 1;
if counter > required then
-- The port used to have more options, abort!
goto clean_exit;
end if;
if not all_ports (id).options.Contains (namekey) then
-- cached option not found in port anymore, abort!
goto clean_exit;
end if;
end if;
end;
end loop;
if counter = required then
result := True;
end if;
<<clean_exit>>
TIO.Close (option_file);
return result;
end passed_options_cache_check;
------------------------------------
-- limited_cached_options_check --
------------------------------------
function limited_cached_options_check return Boolean
is
procedure check_port (cursor : ranking_crate.Cursor);
fail_count : Natural := 0;
first_fail : queue_record;
procedure check_port (cursor : ranking_crate.Cursor)
is
QR : constant queue_record := ranking_crate.Element (cursor);
id : port_index := QR.ap_index;
prelude : constant String := "Cached options obsolete: ";
begin
if not passed_options_cache_check (id) then
if fail_count = 0 then
first_fail := QR;
end if;
fail_count := fail_count + 1;
TIO.Put_Line (prelude & get_catport (all_ports (id)));
end if;
end check_port;
begin
rank_queue.Iterate (Process => check_port'Access);
if fail_count > 0 then
CLI.Set_Exit_Status (1);
TIO.Put (LAT.LF & "A preliminary scan has revealed the cached " &
"options of");
if fail_count = 1 then
TIO.Put_Line (" one port are");
else
TIO.Put_Line (fail_count'Img & " ports are");
end if;
TIO.Put_Line ("obsolete. Please update or remove the saved " &
"options and try again.");
declare
portsdir : String := JT.USS (PM.configuration.dir_portsdir) &
LAT.Solidus;
catport : String := get_catport (all_ports (first_fail.ap_index));
begin
TIO.Put_Line (" e.g. make -C " & portsdir & catport & " config");
TIO.Put_Line (" e.g. make -C " & portsdir & catport & " rmconfig");
end;
end if;
return (fail_count = 0);
end limited_cached_options_check;
-----------------------------
-- parallel_package_scan --
-----------------------------
procedure parallel_package_scan (repository : String; remote_scan : Boolean;
show_progress : Boolean)
is
task type scan (lot : scanners);
finished : array (scanners) of Boolean := (others => False);
combined_wait : Boolean := True;
label_shown : Boolean := False;
aborted : Boolean := False;
task body scan
is
procedure populate (cursor : subqueue.Cursor);
procedure populate (cursor : subqueue.Cursor)
is
target_port : port_index := subqueue.Element (cursor);
important : constant Boolean := all_ports (target_port).scanned;
begin
if not aborted and then important then
if remote_scan and then
not all_ports (target_port).never_remote
then
if not all_ports (target_port).pkg_present or else
all_ports (target_port).deletion_due
then
remote_package_scan (target_port);
end if;
else
initial_package_scan (repository, target_port);
end if;
end if;
mq_progress (lot) := mq_progress (lot) + 1;
end populate;
begin
make_queue (lot).Iterate (populate'Access);
finished (lot) := True;
end scan;
scan_01 : scan (lot => 1);
scan_02 : scan (lot => 2);
scan_03 : scan (lot => 3);
scan_04 : scan (lot => 4);
scan_05 : scan (lot => 5);
scan_06 : scan (lot => 6);
scan_07 : scan (lot => 7);
scan_08 : scan (lot => 8);
scan_09 : scan (lot => 9);
scan_10 : scan (lot => 10);
scan_11 : scan (lot => 11);
scan_12 : scan (lot => 12);
scan_13 : scan (lot => 13);
scan_14 : scan (lot => 14);
scan_15 : scan (lot => 15);
scan_16 : scan (lot => 16);
scan_17 : scan (lot => 17);
scan_18 : scan (lot => 18);
scan_19 : scan (lot => 19);
scan_20 : scan (lot => 20);
scan_21 : scan (lot => 21);
scan_22 : scan (lot => 22);
scan_23 : scan (lot => 23);
scan_24 : scan (lot => 24);
scan_25 : scan (lot => 25);
scan_26 : scan (lot => 26);
scan_27 : scan (lot => 27);
scan_28 : scan (lot => 28);
scan_29 : scan (lot => 29);
scan_30 : scan (lot => 30);
scan_31 : scan (lot => 31);
scan_32 : scan (lot => 32);
begin
while combined_wait loop
delay 1.0;
combined_wait := False;
for j in scanners'Range loop
if not finished (j) then
combined_wait := True;
exit;
end if;
end loop;
if combined_wait then
if not label_shown then
label_shown := True;
TIO.Put_Line ("Scanning existing packages.");
end if;
if show_progress then
TIO.Put (scan_progress);
end if;
if SIG.graceful_shutdown_requested then
aborted := True;
end if;
end if;
end loop;
end parallel_package_scan;
-----------------------------------------
-- parallel_preliminary_package_scan --
-----------------------------------------
procedure parallel_preliminary_package_scan (repository : String;
show_progress : Boolean)
is
task type scan (lot : scanners);
finished : array (scanners) of Boolean := (others => False);
combined_wait : Boolean := True;
label_shown : Boolean := False;
aborted : Boolean := False;
task body scan
is
procedure check (csr : string_crate.Cursor);
procedure check (csr : string_crate.Cursor) is
begin
if aborted then
return;
end if;
declare
pkgname : constant String := JT.USS (string_crate.Element (csr));
pkgpath : constant String := repository & "/" & pkgname;
origin : constant String := query_origin (pkgpath);
path1 : constant String := JT.USS (PM.configuration.dir_portsdir) & "/" & origin;
remove : Boolean := True;
begin
if AD.Exists (path1) then
declare
full_origin : constant String := query_full_origin (pkgpath, origin);
begin
if current_package_name (full_origin, pkgname) then
stored_origins (lot).Append (New_Item => JT.SUS (full_origin));
remove := False;
end if;
end;
end if;
if remove then
AD.Delete_File (pkgpath);
TIO.Put_Line ("Removed: " & pkgname);
end if;
exception
when others =>
TIO.Put_Line (" Failed to remove " & pkgname);
end;
pkgscan_progress (lot) := pkgscan_progress (lot) + 1;
end check;
begin
stored_packages (lot).Iterate (check'Access);
stored_packages (lot).Clear;
finished (lot) := True;
end scan;
scan_01 : scan (lot => 1);
scan_02 : scan (lot => 2);
scan_03 : scan (lot => 3);
scan_04 : scan (lot => 4);
scan_05 : scan (lot => 5);
scan_06 : scan (lot => 6);
scan_07 : scan (lot => 7);
scan_08 : scan (lot => 8);
scan_09 : scan (lot => 9);
scan_10 : scan (lot => 10);
scan_11 : scan (lot => 11);
scan_12 : scan (lot => 12);
scan_13 : scan (lot => 13);
scan_14 : scan (lot => 14);
scan_15 : scan (lot => 15);
scan_16 : scan (lot => 16);
scan_17 : scan (lot => 17);
scan_18 : scan (lot => 18);
scan_19 : scan (lot => 19);
scan_20 : scan (lot => 20);
scan_21 : scan (lot => 21);
scan_22 : scan (lot => 22);
scan_23 : scan (lot => 23);
scan_24 : scan (lot => 24);
scan_25 : scan (lot => 25);
scan_26 : scan (lot => 26);
scan_27 : scan (lot => 27);
scan_28 : scan (lot => 28);
scan_29 : scan (lot => 29);
scan_30 : scan (lot => 30);
scan_31 : scan (lot => 31);
scan_32 : scan (lot => 32);
begin
while combined_wait loop
delay 1.0;
if show_progress then
TIO.Put (package_scan_progress);
end if;
combined_wait := False;
for j in scanners'Range loop
if not finished (j) then
combined_wait := True;
exit;
end if;
end loop;
if combined_wait then
if not label_shown then
label_shown := True;
TIO.Put_Line ("Stand by, prescanning existing packages.");
end if;
if SIG.graceful_shutdown_requested then
aborted := True;
end if;
end if;
end loop;
end parallel_preliminary_package_scan;
-----------------------------------
-- located_external_repository --
-----------------------------------
function located_external_repository return Boolean
is
command : constant String := host_pkg8 & " -vv";
dump : JT.Text;
topline : JT.Text;
crlen1 : Natural;
crlen2 : Natural;
found : Boolean := False;
inspect : Boolean := False;
begin
declare
begin
dump := generic_system_command (command);
exception
when pkgng_execution => return False;
end;
crlen1 := JT.SU.Length (dump);
loop
JT.nextline (lineblock => dump, firstline => topline);
crlen2 := JT.SU.Length (dump);
exit when crlen1 = crlen2;
crlen1 := crlen2;
if inspect then
declare
line : constant String := JT.USS (topline);
len : constant Natural := line'Length;
begin
if len > 7 and then
line (1 .. 2) = " " and then
line (len - 3 .. len) = ": { " and then
line (3 .. len - 4) /= "Synth"
then
found := True;
external_repository := JT.SUS (line (3 .. len - 4));
exit;
end if;
end;
else
if JT.equivalent (topline, "Repositories:") then
inspect := True;
end if;
end if;
end loop;
return found;
end located_external_repository;
-------------------------------
-- top_external_repository --
-------------------------------
function top_external_repository return String is
begin
return JT.USS (external_repository);
end top_external_repository;
-------------------------------
-- activate_debugging_code --
-------------------------------
procedure activate_debugging_code is
begin
debug_opt_check := True;
debug_dep_check := True;
end activate_debugging_code;
--------------------
-- query_origin --
--------------------
function query_origin (fullpath : String) return String
is
command : constant String := host_pkg8 & " query -F " & fullpath & " %o";
content : JT.Text;
topline : JT.Text;
begin
content := generic_system_command (command);
JT.nextline (lineblock => content, firstline => topline);
return JT.USS (topline);
exception
when others => return "";
end query_origin;
---------------------
-- query_pkgbase --
---------------------
function query_pkgbase (fullpath : String) return String
is
command : constant String := host_pkg8 & " query -F " & fullpath & " %n";
content : JT.Text;
topline : JT.Text;
begin
content := generic_system_command (command);
JT.nextline (lineblock => content, firstline => topline);
return JT.USS (topline);
exception
when others => return "";
end query_pkgbase;
-------------------------
-- query_full_origin --
-------------------------
function query_full_origin (fullpath, origin : String) return String
is
command : constant String := host_pkg8 & " query -F " & fullpath & " %At:%Av";
content : JT.Text;
begin
content := generic_system_command (command);
declare
contents : constant String := JT.USS (content);
markers : JT.Line_Markers;
begin
JT.initialize_markers (contents, markers);
if JT.next_line_with_content_present (contents, "flavor:", markers) then
declare
line : constant String := JT.extract_line (contents, markers);
begin
return origin & "@" & JT.part_2 (line, ":");
end;
else
return origin;
end if;
end;
exception
when others => return origin;
end query_full_origin;
----------------------------
-- current_package_name --
----------------------------
function current_package_name (origin, file_name : String) return Boolean
is
cpn : constant String := get_pkg_name (origin);
begin
return cpn = file_name;
end current_package_name;
-----------------------------
-- package_scan_progress --
-----------------------------
function package_scan_progress return String
is
type percent is delta 0.01 digits 5;
complete : port_index := 0;
pc : percent;
total : constant Float := Float (pkgscan_total);
begin
for k in scanners'Range loop
complete := complete + pkgscan_progress (k);
end loop;
pc := percent (100.0 * Float (complete) / total);
return " progress:" & pc'Img & "% " & LAT.CR;
end package_scan_progress;
--------------------------------------
-- start_obsolete_package_logging --
--------------------------------------
procedure start_obsolete_package_logging
is
logpath : constant String := JT.USS (PM.configuration.dir_logs)
& "/06_obsolete_packages.log";
begin
-- Try to defend malicious symlink: https://en.wikipedia.org/wiki/Symlink_race
if AD.Exists (logpath) then
AD.Delete_File (logpath);
end if;
TIO.Create (File => obsolete_pkg_log,
Mode => TIO.Out_File,
Name => logpath);
obsolete_log_open := True;
exception
when others =>
obsolete_log_open := False;
end start_obsolete_package_logging;
-----------------------
-- obsolete_notice --
-----------------------
procedure obsolete_notice (message : String; write_to_screen : Boolean)
is
begin
if obsolete_log_open then
TIO.Put_Line (obsolete_pkg_log, message);
end if;
if write_to_screen then
TIO.Put_Line (message);
end if;
end obsolete_notice;
end PortScan.Packages;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2013 Felix Krause <contact@flyx.org>
-- Copyright (c) 2017 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 GL.Types;
private with GL.Low_Level;
package GL.Viewports is
pragma Preelaborate;
use GL.Types;
-----------------------------------------------------------------------------
-- Viewports --
-----------------------------------------------------------------------------
type Viewport is record
X, Y, Width, Height : Single;
end record;
type Depth_Range is record
Near, Far : Double;
end record;
type Scissor_Rectangle is record
Left, Bottom : Int;
Width, Height : Size;
end record;
type Viewport_List is array (UInt range <>) of Viewport
with Convention => C;
type Depth_Range_List is array (UInt range <>) of Depth_Range
with Convention => C;
type Scissor_Rectangle_List is array (UInt range <>) of Scissor_Rectangle
with Convention => C;
function Maximum_Viewports return Size
with Post => Maximum_Viewports'Result >= 16;
function Viewport_Subpixel_Bits return Size;
function Origin_Range return Singles.Vector2;
-- Return the minimum and maximum X and Y of the origin (lower left
-- corner) of a viewport
function Maximum_Extent return Singles.Vector2;
-- Return the maximum width and height of a viewport
procedure Set_Viewports (List : Viewport_List);
function Get_Viewport (Index : UInt) return Viewport;
procedure Set_Depth_Ranges (List : Depth_Range_List);
function Get_Depth_Range (Index : UInt) return Depth_Range;
procedure Set_Scissor_Rectangles (List : Scissor_Rectangle_List);
function Get_Scissor_Rectangle (Index : UInt) return Scissor_Rectangle;
-----------------------------------------------------------------------------
-- Clipping --
-----------------------------------------------------------------------------
type Viewport_Origin is (Lower_Left, Upper_Left);
type Depth_Mode is (Negative_One_To_One, Zero_To_One);
procedure Set_Clipping (Origin : Viewport_Origin; Depth : Depth_Mode);
-- Set the origin of the viewport and the range of the clip planes
--
-- Controls how clip space is mapped to window space. Both Direct3D and
-- OpenGL expect a vertex position of (-1, -1) to map to the lower-left
-- corner of the viewport.
--
-- Direct3D expects the UV coordinate of (0, 0) to correspond to the
-- upper-left corner of a randered image, while OpenGL expects it in
-- the lower-left corner.
function Origin return Viewport_Origin;
function Depth return Depth_Mode;
private
for Viewport_Origin use
(Lower_Left => 16#8CA1#,
Upper_Left => 16#8CA2#);
for Viewport_Origin'Size use Low_Level.Enum'Size;
for Depth_Mode use
(Negative_One_To_One => 16#935E#,
Zero_To_One => 16#935F#);
for Depth_Mode'Size use Low_Level.Enum'Size;
end GL.Viewports;
|
with Ada.Command_Line;
with Trie;
procedure SevenWords is
words : constant Trie.Trie := Trie.Make_Trie("../american-english-filtered");
argument_length : Natural := 0;
fragment_ends : Trie.Fragment_Endpoint_Array(1 .. Ada.Command_Line.Argument_Count);
begin
if Ada.Command_Line.Argument_Count = 0 then
raise Constraint_Error;
end if;
for index in 1 .. Ada.Command_Line.Argument_Count loop
fragment_ends(index).first := argument_length + 1;
argument_length := argument_length + Ada.Command_Line.Argument(index)'Length;
fragment_ends(index).last := argument_length;
end loop;
declare
argument_string : String(1 .. argument_length);
begin
for index in 1 .. Ada.Command_Line.Argument_Count loop
argument_string(fragment_ends(index).first .. fragment_ends(index).last) := Ada.Command_Line.Argument(index);
end loop;
Trie.find_words(words, argument_string, fragment_ends);
end;
end SevenWords;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.