content stringlengths 23 1.05M |
|---|
------------------------------------------------------------------------------
-- buffers.ads
--
-- A generic package for bounded, blocking FIFO queues (buffers). It exports
-- a proected type called 'Buffer'. Note that the maximum size of any buffer
-- of this type is taken from a single generic package parameter.
--
-- Generic Parameters:
--
-- Item the desired type of the buffer elements.
-- Size the maximum size of a buffer of type Buffer.
--
-- Entries:
--
-- Write (I) write item I to the buffer.
-- Read (I) read into item I from the buffer.
------------------------------------------------------------------------------
generic
type Item is private;
Size: Positive;
package Buffers is
subtype Index is Integer range 0..Size-1;
type Item_Array is array (Index) of Item;
protected type Buffer is
entry Write (I: Item);
entry Read (I: out Item);
private
Data : Item_Array;
Front : Index := 0; -- index of head (when not empty)
Back : Index := 0; -- index of next free slot
Count : Integer range 0..Size := 0; -- number of items currently in
end Buffer;
end Buffers;
|
with Ada.Text_IO;
use Ada.Text_IO;
with Ada.Containers.Ordered_Maps;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
package body CSV is
package Associative_Str is new Ada.Containers.Ordered_Maps(Integer, Unbounded_String);
package Associative_Data is new Ada.Containers.Ordered_Maps(Unbounded_String, Float);
use Associative_Data;
Col_Map : Associative_Str.Map; -- maps column number to column name
Data_Map : Associative_Data.Map; -- maps column name to current data
function Parse_Line(S: String; filesep: Character)
return Row is
(Length => S'Length, Str => S,
Fst => S'First, Lst => S'Last, Nxt => S'First, Sep => filesep);
function End_Of_File return Boolean is
begin
return Ada.Text_IO.End_Of_File (file);
end End_Of_File;
procedure Dump_Columns is
Index : Associative_Data.Cursor := Data_Map.First;
begin
while Index /= Associative_Data.No_Element loop
Put (To_String (Key (Index)) & "=" & Float'Image (Element (Index)));
Index := Next (Index);
if Index /= Associative_Data.No_Element then
Put (", ");
end if;
end loop;
New_Line;
end;
function Get_Column (name : String) return Float is
colname : Unbounded_String := To_Unbounded_String (name);
begin
if not Data_Map.Contains (colname) then
Put_Line ("ERROR: no column '" & name & "' in file " & filename);
return 0.0;
else
return Data_Map.Element (colname);
end if;
end Get_Column;
function Parse_Row return Boolean is
Line : constant String := Get_Line (file);
r : Row := Parse_Line (Line, filesep);
k : Positive := 1;
begin
while r.Next loop
declare
colname : Unbounded_String := Col_Map.Element (k); -- get column name by index
Data_Cursor : Associative_Data.Cursor;
succ : Boolean;
value : Float;
begin
value := Float'Value (r.Item);
if not Data_Map.Contains (colname) then
Data_Map.Insert (colname, value, Data_Cursor, succ);
else
Data_Map.Replace (colname, value);
end if;
--Put_Line ("CSV Parse: col=" & Ada.Strings.Unbounded.To_String (colname) & ", val=" & value'img);
end;
k := k + 1;
end loop;
return True;
end Parse_Row;
procedure Parse_Header is
Line : String := Get_Line (file);
head : Row := Parse_Line (Line, filesep);
k : Positive := 1;
Col_Cursor_Rev : Associative_Str.Cursor;
Success : Boolean;
begin
-- Put ("Header: ");
while head.Next loop
Col_Map.Insert (k,To_Unbounded_String (head.Item), Col_Cursor_Rev, Success);
-- Put (k'img & " => " & head.Item & ",");
k := k + 1;
end loop;
--New_Line;
end Parse_Header;
function Item(R: Row) return String is
(R.Str(R.Fst .. R.Lst));
procedure Close is
begin
Ada.Text_IO.Close (file);
end Close;
function Next(R : in out Row) return Boolean is
Last: Natural := R.Nxt;
begin
R.Fst := R.Nxt;
while Last <= R.Str'Last and then R.Str(Last) /= R.Sep loop
-- find Separator
Last := Last + 1;
end loop;
R.Lst := Last - 1;
R.Nxt := Last + 1;
return (R.Fst <= R.Str'Last);
end Next;
function Open return Boolean is
begin
Ada.Text_IO.Open (File => file,
Mode => Ada.Text_IO.In_File,
Name => filename);
return Ada.Text_IO.Is_Open (file);
end Open;
end CSV;
|
-- C47007A.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.
--*
-- WHEN THE TYPE MARK IN A QUALIFIED EXPRESSION DENOTES A CONSTRAINED
-- ARRAY TYPE, CHECK THAT CONSTRAINT_ERROR IS RAISED WHEN THE BOUNDS
-- OF THE OPERAND ARE NOT THE SAME AS THE BOUNDS OF THE TYPE MARK.
-- RJW 7/23/86
WITH REPORT; USE REPORT;
PROCEDURE C47007A IS
TYPE ARR IS ARRAY (NATURAL RANGE <>) OF INTEGER;
TYPE TARR IS ARRAY (NATURAL RANGE <>, NATURAL RANGE <>)
OF INTEGER;
TYPE NARR IS NEW ARR;
TYPE NTARR IS NEW TARR;
BEGIN
TEST( "C47007A", "WHEN THE TYPE MARK IN A QUALIFIED EXPRESSION " &
"DENOTES A CONSTRAINED ARRAY TYPE, CHECK THAT " &
"CONSTRAINT_ERROR IS RAISED WHEN THE BOUNDS " &
"OF THE OPERAND ARE NOT THE SAME AS THE " &
"BOUNDS OF THE TYPE MARK" );
DECLARE
SUBTYPE SARR IS ARR (IDENT_INT (1) .. IDENT_INT (1));
A : ARR (IDENT_INT (2) .. IDENT_INT (2));
BEGIN
A := SARR'(A'RANGE => 0);
FAILED ( "NO EXCEPTION RAISED WHEN BOUNDS NOT THE SAME AS " &
"THOSE OF SUBTYPE SARR" );
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED WHEN BOUNDS NOT " &
"THE SAME AS THOSE OF SUBTYPE SARR" );
END;
DECLARE
SUBTYPE NULLA IS ARR (IDENT_INT (1) .. IDENT_INT (0));
A : ARR (IDENT_INT (2) .. IDENT_INT (1));
BEGIN
A := NULLA'(A'FIRST .. A'LAST => 0);
FAILED ( "NO EXCEPTION RAISED WHEN BOUNDS NOT THE SAME AS " &
"THOSE OF SUBTYPE NULLA" );
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED WHEN BOUNDS NOT " &
"THE SAME AS THOSE OF SUBTYPE NULLA" );
END;
DECLARE
SUBTYPE STARR IS TARR (IDENT_INT (1) .. IDENT_INT (1),
IDENT_INT (1) .. IDENT_INT (5));
A : TARR (IDENT_INT (2) .. IDENT_INT (6),
IDENT_INT (1) .. IDENT_INT (1));
BEGIN
A := STARR'(A'RANGE => (A'RANGE (2) => 0));
FAILED ( "NO EXCEPTION RAISED WHEN BOUNDS NOT THE SAME AS " &
"THOSE OF SUBTYPE STARR" );
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED WHEN BOUNDS NOT " &
"THE SAME AS THOSE OF SUBTYPE STARR" );
END;
DECLARE
SUBTYPE NULLT IS TARR (IDENT_INT (1) .. IDENT_INT (5),
IDENT_INT (1) .. IDENT_INT (0));
A : TARR (IDENT_INT (1) .. IDENT_INT (5),
IDENT_INT (2) .. IDENT_INT (1));
BEGIN
A := NULLT'(A'FIRST .. A'LAST =>
(A'FIRST (2) .. A'LAST (2) => 0));
FAILED ( "NO EXCEPTION RAISED WHEN BOUNDS NOT THE SAME AS " &
"THOSE OF SUBTYPE NULLT" );
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED WHEN BOUNDS NOT " &
"THE SAME AS THOSE OF SUBTYPE NULLT" );
END;
DECLARE
SUBTYPE SNARR IS NARR (IDENT_INT (1) .. IDENT_INT (1));
A : NARR (IDENT_INT (2) .. IDENT_INT (2));
BEGIN
A := SNARR'(A'RANGE => 0);
FAILED ( "NO EXCEPTION RAISED WHEN BOUNDS NOT THE SAME AS " &
"THOSE OF SUBTYPE SNARR" );
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED WHEN BOUNDS NOT " &
"THE SAME AS THOSE OF SUBTYPE SNARR" );
END;
DECLARE
SUBTYPE NULLNA IS NARR (IDENT_INT (1) .. IDENT_INT (0));
A : NARR (IDENT_INT (2) .. IDENT_INT (1));
BEGIN
A := NULLNA'(A'RANGE => 0);
FAILED ( "NO EXCEPTION RAISED WHEN BOUNDS NOT THE SAME AS " &
"THOSE OF SUBTYPE NULLNA" );
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED WHEN BOUNDS NOT " &
"THE SAME AS THOSE OF SUBTYPE NULLNA" );
END;
DECLARE
SUBTYPE SNTARR IS NTARR (IDENT_INT (1) .. IDENT_INT (1),
IDENT_INT (1) .. IDENT_INT (5));
A : NTARR (IDENT_INT (2) .. IDENT_INT (2),
IDENT_INT (1) .. IDENT_INT (5));
BEGIN
A := SNTARR'(A'RANGE => (A'RANGE (2) => 0));
FAILED ( "NO EXCEPTION RAISED WHEN BOUNDS NOT THE SAME AS " &
"THOSE OF SUBTYPE SNTARR" );
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED WHEN BOUNDS NOT " &
"THE SAME AS THOSE OF SUBTYPE SNTARR" );
END;
DECLARE
SUBTYPE NULLNT IS NTARR (IDENT_INT (1) .. IDENT_INT (5),
IDENT_INT (1) .. IDENT_INT (0));
A : NTARR (IDENT_INT (1) .. IDENT_INT (5),
IDENT_INT (1) .. IDENT_INT (1));
BEGIN
A := NULLNT'(A'RANGE => (A'RANGE (2) => 0));
FAILED ( "NO EXCEPTION RAISED WHEN BOUNDS NOT THE SAME AS " &
"THOSE OF SUBTYPE NULLNT" );
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED WHEN BOUNDS NOT " &
"THE SAME AS THOSE OF SUBTYPE NULLNT" );
END;
RESULT;
END C47007A;
|
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Float_Text_IO; use Ada.Float_Text_IO;
package body Histograms is
procedure Reset(hist : in out Histogram_Type) is
begin
hist.data.Clear;
end Reset;
procedure Increment(hist : in out Histogram_Type;
key : in Key_Type) is
value : Long_Integer := 1;
pos : constant Histogram_Maps.Cursor := hist.data.Find(key);
begin
if Histogram_Maps.Has_Element(pos) then
value := hist.data.Element(key) + 1;
hist.data.Replace_Element(pos, value);
else
hist.data.Insert(key, value);
end if;
end Increment;
function Get_Total(hist : Histogram_Type) return Float is
total : Float := 0.0;
procedure Helper(pos : in Histogram_Maps.Cursor) is
begin
total := total + Float(Histogram_Maps.Element(pos));
end Helper;
begin
hist.data.Iterate(Helper'Access);
if total = 0.0 then
return 1.0;
else
return total;
end if;
end Get_Total;
procedure Show(hist : in Histogram_Type;
label : in String) is
total : constant Float := Get_Total(hist);
procedure Helper(pos : in Histogram_Maps.Cursor) is
key : constant Key_Type := Histogram_Maps.Key(pos);
value : constant Long_Integer := Histogram_Maps.Element(pos);
percent : constant Float := 100.0 * Float(value) / total;
begin
if percent >= 1.0 then
Put(" " & Key_Type'Image(key) & ":");
Put(percent, Fore => 3, Aft => 0, Exp => 0);
Put("%");
New_Line;
end if;
end Helper;
begin
Put_Line(label & ":");
hist.data.Iterate(Helper'Access);
end Show;
end Histograms;
|
-----------------------------------------------------------------------
-- keystore-passwords -- Password provider
-- Copyright (C) 2019 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package Keystore.Passwords is
type Provider is limited interface;
type Provider_Access is access all Provider'Class;
-- Get the password through the Getter operation.
procedure Get_Password (From : in Provider;
Getter : not null
access procedure (Password : in Secret_Key)) is abstract;
subtype Tag_Type is Interfaces.Unsigned_32;
type Slot_Provider is limited interface and Provider;
function Get_Tag (From : in Slot_Provider) return Tag_Type is abstract;
function Has_Password (From : in Slot_Provider) return Boolean is abstract;
procedure Next (From : in out Slot_Provider) is abstract;
-- Get the key and IV through the Getter operation.
procedure Get_Key (From : in Slot_Provider;
Getter : not null access procedure (Key : in Secret_Key;
IV : in Secret_Key)) is abstract;
procedure To_Provider (Secret : in Secret_Key;
Process : not null access procedure (P : in out Provider'Class));
private
type Internal_Key_Provider is limited interface;
procedure Save_Key (Provider : in Internal_Key_Provider;
Data : out Ada.Streams.Stream_Element_Array) is abstract;
end Keystore.Passwords;
|
-- part of OpenGLAda, (c) 2017 Felix Krause
-- released under the terms of the MIT license, see the file "COPYING"
with Ada.Strings.Unbounded;
with Ada.Text_IO;
with GL.Context;
with GL_Test.Display_Backend;
procedure GL_Test.Context is
procedure Display_Context_Information is
use Ada.Strings.Unbounded;
use Ada.Text_IO;
begin
begin
Put_Line ("Major version: " & GL.Context.Major_Version'Img);
Put_Line ("Minor version: " & GL.Context.Minor_Version'Img);
exception
when others =>
Put_Line ("OpenGL version too old for querying major and minor");
end;
Put_Line ("Whole version string: " & GL.Context.Version_String);
Put_Line ("Vendor: " & GL.Context.Renderer);
Put_Line ("Renderer: " & GL.Context.Renderer);
Put_Line ("Extensions: ");
declare
List : constant GL.Context.String_List := GL.Context.Extensions;
begin
for I in List'Range loop
declare
Name : constant String := To_String (List (I));
begin
Put_Line (" " & Name);
if not GL.Context.Has_Extension (Name) then
Put_Line
("!!! Has_Extension returns false (should not happen)");
end if;
end;
end loop;
end;
begin
Put_Line ("Primary shading language version: " &
GL.Context.Primary_Shading_Language_Version);
exception
when others =>
Put_Line ("OpenGL version too old for querying " &
"Primary shading language version");
return;
end;
begin
declare
List : constant GL.Context.String_List :=
GL.Context.Supported_Shading_Language_Versions;
begin
Put_Line ("Supported shading language versions:");
for I in List'Range loop
declare
Version : constant String := To_String (List (I));
begin
Put_Line (" " & Version);
if not GL.Context.Supports_Shading_Language_Version
(Version)
then
Put_Line ("!!! Supports_Shading_Language_Version " &
"returns false (should not happen)");
end if;
end;
end loop;
end;
exception
when others =>
Put_Line ("OpenGL version too old for querying supported versions");
end;
end Display_Context_Information;
begin
Display_Backend.Init;
Ada.Text_IO.Put_Line
("Getting information without request for OpenGL version.");
-- create a window so we have a context
Display_Backend.Open_Window (Width => 500, Height => 500);
Display_Context_Information;
Ada.Text_IO.New_Line;
Display_Backend.Close_Window;
Ada.Text_IO.Put_Line
("Getting information with requested OpenGL version 2.1:");
Display_Backend.Configure_Minimum_OpenGL_Version (Major => 2, Minor => 1);
Display_Backend.Open_Window (Width => 500, Height => 500);
Display_Context_Information;
Display_Backend.Close_Window;
Ada.Text_IO.Put_Line
("Getting information with requested OpenGL version 3.2:");
Display_Backend.Configure_Minimum_OpenGL_Version (Major => 3, Minor => 2);
Display_Backend.Open_Window (Width => 500, Height => 500);
Display_Context_Information;
Display_Backend.Shutdown;
end GL_Test.Context;
|
with Ada.Text_IO, Ada.Containers.Generic_Array_Sort;
procedure Largest_Int_From_List is
function Img(N: Natural) return String is
S: String := Integer'Image(N);
begin
return S(S'First+1 .. S'Last); -- First character is ' '
end Img;
function Order(Left, Right: Natural) return Boolean is
( (Img(Left) & Img(Right)) > (Img(Right) & Img(Left)) );
type Arr_T is array(Positive range <>) of Natural;
procedure Sort is new Ada.Containers.Generic_Array_Sort
(Positive, Natural, Arr_T, Order);
procedure Print_Sorted(A: Arr_T) is
B: Arr_T := A;
begin
Sort(B);
for Number of B loop
Ada.Text_IO.Put(Img(Number));
end loop;
Ada.Text_IO.New_Line;
end Print_Sorted;
begin
Print_Sorted((1, 34, 3, 98, 9, 76, 45, 4));
Print_Sorted((54, 546, 548, 60));
end Largest_Int_From_List;
|
-- $Header: /cf/ua/arcadia/alex-ayacc/ayacc/src/RCS/file_names.a,v 1.2 88/11/28 13:38:59 arcadia Exp $
-- Copyright (c) 1990 Regents of the University of California.
-- All rights reserved.
--
-- The primary authors of ayacc were David Taback and Deepak Tolani.
-- Enhancements were made by Ronald J. Schmalz.
--
-- Send requests for ayacc information to ayacc-info@ics.uci.edu
-- Send bug reports for ayacc to ayacc-bugs@ics.uci.edu
--
-- Redistribution and use in source and binary forms are permitted
-- provided that the above copyright notice and this paragraph are
-- duplicated in all such forms and that any documentation,
-- advertising materials, and other materials related to such
-- distribution and use acknowledge that the software was developed
-- by the University of California, Irvine. The name of the
-- University may not be used to endorse or promote products derived
-- from this software without specific prior written permission.
-- THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
-- IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
-- WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
-- Module : file_names.ada
-- Component of : ayacc
-- Version : 1.2
-- Date : 11/21/86 12:29:16
-- SCCS File : disk21~/rschm/hasee/sccs/ayacc/sccs/sxfile_names.ada
-- $Header: /cf/ua/arcadia/alex-ayacc/ayacc/src/RCS/file_names.a,v 1.2 88/11/28 13:38:59 arcadia Exp $
-- $Log: file_names.a,v $
--Revision 1.2 88/11/28 13:38:59 arcadia
--Modified Get_Unit_Name function to accept legal Ada identifiers.
--
--Revision 1.1 88/08/08 12:11:56 arcadia
--Initial revision
--
-- Revision 0,2 88/03/16
-- Set file names modified to include a file extension parameter.
-- Revision 0.1 86/04/01 15:04:19 ada
-- This version fixes some minor bugs with empty grammars
-- and $$ expansion. It also uses vads5.1b enhancements
-- such as pragma inline.
--
--
-- Revision 0.0 86/02/19 18:36:22 ada
--
-- These files comprise the initial version of Ayacc
-- designed and implemented by David Taback and Deepak Tolani.
-- Ayacc has been compiled and tested under the Verdix Ada compiler
-- version 4.06 on a vax 11/750 running Unix 4.2BSD.
--
-- The collection of all file names used by Ayacc --
with Ada.Characters.Handling; use Ada.Characters.Handling;
package Ayacc_File_Names is
procedure Set_File_Names(Input_File, Extension: in String);
-- Sets the initial value of the file names
-- according to the INPUT_FILE.
function Get_Source_File_Name return String;
function Get_Out_File_Name return String;
function Get_Verbose_File_Name return String;
function Get_Template_File_Name return String;
function Get_Actions_File_Name return String;
function Get_Shift_Reduce_File_Name return String;
function Get_Goto_File_Name return String;
function Get_Tokens_File_Name return String;
-- UMASS CODES :
function Get_Error_Report_File_Name return String;
function Get_Listing_File_Name return String;
-- END OF UMASS CODES.
function Get_C_Lex_File_Name return String;
function Get_Include_File_Name return String;
--RJS ==========================================
function C_Lex_Unit_Name return String;
function Goto_Tables_Unit_Name return String;
function Shift_Reduce_Tables_Unit_Name return String;
function Tokens_Unit_Name return String;
function Main_Unit_Name return String;
-- UMASS CODES :
function Error_Report_Unit_Name return String;
-- END OF UMASS CODES.
--RJS ==========================================
Illegal_File_Name: exception;
-- Raised if the file name does not end with ".y"
end Ayacc_File_Names;
|
with Ada.Command_Line;
with Ada.Text_IO.Unbounded_IO;
with Ada.Strings.Unbounded;
with Markov;
procedure Test_Markov is
use Ada.Strings.Unbounded;
package IO renames Ada.Text_IO.Unbounded_IO;
Rule_File : Ada.Text_IO.File_Type;
Line_Count : Natural := 0;
begin
if Ada.Command_Line.Argument_Count /= 2 then
Ada.Text_IO.Put_Line ("Usage: test_markov ruleset_file source_file");
return;
end if;
Ada.Text_IO.Open
(File => Rule_File,
Mode => Ada.Text_IO.In_File,
Name => Ada.Command_Line.Argument (1));
while not Ada.Text_IO.End_Of_File (Rule_File) loop
Ada.Text_IO.Skip_Line (Rule_File);
Line_Count := Line_Count + 1;
end loop;
declare
Lines : Markov.String_Array (1 .. Line_Count);
begin
Ada.Text_IO.Reset (Rule_File);
for I in Lines'Range loop
Lines (I) := IO.Get_Line (Rule_File);
end loop;
Ada.Text_IO.Close (Rule_File);
declare
Ruleset : Markov.Ruleset := Markov.Parse (Lines);
Source_File : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Open
(File => Source_File,
Mode => Ada.Text_IO.In_File,
Name => Ada.Command_Line.Argument (2));
while not Ada.Text_IO.End_Of_File (Source_File) loop
Ada.Text_IO.Put_Line
(Markov.Apply (Ruleset, Ada.Text_IO.Get_Line (Source_File)));
end loop;
Ada.Text_IO.Close (Source_File);
end;
end;
end Test_Markov;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Ada Modeling Framework --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2011-2012, Vadim Godunko <vgodunko@gmail.com> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
-- This file is generated, don't edit it.
------------------------------------------------------------------------------
-- A redefinable element is an element that, when defined in the context of a
-- classifier, can be redefined more specifically or differently in the
-- context of another classifier that specializes (directly or indirectly)
-- the context classifier.
------------------------------------------------------------------------------
limited with AMF.UML.Classifiers.Collections;
with AMF.UML.Named_Elements;
limited with AMF.UML.Redefinable_Elements.Collections;
package AMF.UML.Redefinable_Elements is
pragma Preelaborate;
type UML_Redefinable_Element is limited interface
and AMF.UML.Named_Elements.UML_Named_Element;
type UML_Redefinable_Element_Access is
access all UML_Redefinable_Element'Class;
for UML_Redefinable_Element_Access'Storage_Size use 0;
not overriding function Get_Is_Leaf
(Self : not null access constant UML_Redefinable_Element)
return Boolean is abstract;
-- Getter of RedefinableElement::isLeaf.
--
-- Indicates whether it is possible to further redefine a
-- RedefinableElement. If the value is true, then it is not possible to
-- further redefine the RedefinableElement. Note that this property is
-- preserved through package merge operations; that is, the capability to
-- redefine a RedefinableElement (i.e., isLeaf=false) must be preserved in
-- the resulting RedefinableElement of a package merge operation where a
-- RedefinableElement with isLeaf=false is merged with a matching
-- RedefinableElement with isLeaf=true: the resulting RedefinableElement
-- will have isLeaf=false. Default value is false.
not overriding procedure Set_Is_Leaf
(Self : not null access UML_Redefinable_Element;
To : Boolean) is abstract;
-- Setter of RedefinableElement::isLeaf.
--
-- Indicates whether it is possible to further redefine a
-- RedefinableElement. If the value is true, then it is not possible to
-- further redefine the RedefinableElement. Note that this property is
-- preserved through package merge operations; that is, the capability to
-- redefine a RedefinableElement (i.e., isLeaf=false) must be preserved in
-- the resulting RedefinableElement of a package merge operation where a
-- RedefinableElement with isLeaf=false is merged with a matching
-- RedefinableElement with isLeaf=true: the resulting RedefinableElement
-- will have isLeaf=false. Default value is false.
not overriding function Get_Redefined_Element
(Self : not null access constant UML_Redefinable_Element)
return AMF.UML.Redefinable_Elements.Collections.Set_Of_UML_Redefinable_Element is abstract;
-- Getter of RedefinableElement::redefinedElement.
--
-- The redefinable element that is being redefined by this element.
not overriding function Get_Redefinition_Context
(Self : not null access constant UML_Redefinable_Element)
return AMF.UML.Classifiers.Collections.Set_Of_UML_Classifier is abstract;
-- Getter of RedefinableElement::redefinitionContext.
--
-- References the contexts that this element may be redefined from.
not overriding function Is_Consistent_With
(Self : not null access constant UML_Redefinable_Element;
Redefinee : AMF.UML.Redefinable_Elements.UML_Redefinable_Element_Access)
return Boolean is abstract;
-- Operation RedefinableElement::isConsistentWith.
--
-- The query isConsistentWith() specifies, for any two RedefinableElements
-- in a context in which redefinition is possible, whether redefinition
-- would be logically consistent. By default, this is false; this
-- operation must be overridden for subclasses of RedefinableElement to
-- define the consistency conditions.
not overriding function Is_Redefinition_Context_Valid
(Self : not null access constant UML_Redefinable_Element;
Redefined : AMF.UML.Redefinable_Elements.UML_Redefinable_Element_Access)
return Boolean is abstract;
-- Operation RedefinableElement::isRedefinitionContextValid.
--
-- The query isRedefinitionContextValid() specifies whether the
-- redefinition contexts of this RedefinableElement are properly related
-- to the redefinition contexts of the specified RedefinableElement to
-- allow this element to redefine the other. By default at least one of
-- the redefinition contexts of this element must be a specialization of
-- at least one of the redefinition contexts of the specified element.
end AMF.UML.Redefinable_Elements;
|
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Containers; use Ada.Containers;
with Ada.Containers.Vectors;
with Utils; use Utils;
package body Parser is
-- The parse procedure
procedure Parse_Input(Input : String; All_Parts : in out Parts_Vector.Vector) is
Input_Parts : Parts;
buf : Unbounded_String := To_Unbounded_String("");
c : Character;
pos : Integer := 0;
begin
if Input'Length = 0 then
return;
end if;
for i in Input'Range loop
c := Input(i);
if c = ' ' or c = ',' then
if Length(buf) > 0 then
Input_Parts(pos) := buf;
pos := pos + 1;
end if;
buf := To_Unbounded_String("");
else
Append(buf, c);
end if;
end loop;
if Length(buf) > 0 then
Input_Parts(pos) := buf;
end if;
All_Parts.Append(Input_Parts);
end Parse_Input;
-- Loads an parses a file
function Load_File(Path : String) return Parts_Vector.Vector is
F : File_Type;
Parsed_Lines : Parts_Vector.Vector;
begin
Open(F, In_File, Path);
while not End_Of_File(F) loop
Parse_Input(Get_Line(F), Parsed_Lines);
end loop;
Close(F);
-- Return
return Parsed_Lines;
end Load_File;
-- Gets a subset of a file based on section
function Get_Part(All_Lines : Parts_Vector.Vector; Name : String) return Parts_Vector.Vector is
In_Sec : Boolean := False;
Section : Parts_Vector.Vector;
begin
for Ln of All_Lines loop
if Ln(0) = "section" then
if To_String(Ln(1)) = Name then
In_Sec := True;
else
In_Sec := False;
end if;
elsif In_Sec then
Section.Append(Ln);
end if;
end loop;
return Section;
end Get_Part;
-- The debugging procedure
procedure Parser_Debug(All_Lines : Parts_Vector.Vector) is
begin
--debug
for Ln of All_Lines loop
for Ln2 of Ln loop
Put(To_String(Ln2) & " ");
end loop;
New_Line;
end loop;
end Parser_Debug;
end Parser;
|
pragma Ada_2012;
pragma Style_Checks (Off);
pragma Warnings ("U");
with Interfaces.C; use Interfaces.C;
with System;
package stddef_h is
-- unsupported macro: NULL __null
-- arg-macro: procedure offsetof (TYPE, MEMBER)
-- __builtin_offsetof (TYPE, MEMBER)
subtype ptrdiff_t is int; -- /opt/gcc-11.2.0/lib/gcc/arm-eabi/11.2.0/include/stddef.h:143
subtype size_t is unsigned; -- /opt/gcc-11.2.0/lib/gcc/arm-eabi/11.2.0/include/stddef.h:209
-- skipped anonymous struct anon_anon_0
type max_align_t is record
uu_max_align_ll : aliased Long_Long_Integer; -- /opt/gcc-11.2.0/lib/gcc/arm-eabi/11.2.0/include/stddef.h:416
uu_max_align_ld : aliased long_double; -- /opt/gcc-11.2.0/lib/gcc/arm-eabi/11.2.0/include/stddef.h:417
end record
with Convention => C_Pass_By_Copy; -- /opt/gcc-11.2.0/lib/gcc/arm-eabi/11.2.0/include/stddef.h:426
subtype nullptr_t is System.Address; -- /opt/gcc-11.2.0/lib/gcc/arm-eabi/11.2.0/include/stddef.h:433
end stddef_h;
|
package body Hofstadter_Figure_Figure is
type Positive_Array is array (Positive range <>) of Positive;
function FFR(P: Positive) return Positive_Array is
Figures: Positive_Array(1 .. P+1);
Space: Positive := 2;
Space_Index: Positive := 2;
begin
Figures(1) := 1;
for I in 2 .. P loop
Figures(I) := Figures(I-1) + Space;
Space := Space+1;
while Space = Figures(Space_Index) loop
Space := Space + 1;
Space_Index := Space_Index + 1;
end loop;
end loop;
return Figures(1 .. P);
end FFR;
function FFR(P: Positive) return Positive is
Figures: Positive_Array(1 .. P) := FFR(P);
begin
return Figures(P);
end FFR;
function FFS(P: Positive) return Positive_Array is
Spaces: Positive_Array(1 .. P);
Figures: Positive_Array := FFR(P+1);
J: Positive := 1;
K: Positive := 1;
begin
for I in Spaces'Range loop
while J = Figures(K) loop
J := J + 1;
K := K + 1;
end loop;
Spaces(I) := J;
J := J + 1;
end loop;
return Spaces;
end FFS;
function FFS(P: Positive) return Positive is
Spaces: Positive_Array := FFS(P);
begin
return Spaces(P);
end FFS;
end Hofstadter_Figure_Figure;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../../License.txt
package AdaBase.Results.Generic_Converters is
generic
type IntType is (<>);
function convertstr (nv : Textual) return IntType;
generic
type RealType is digits <>;
function convertst2 (nv : Textual) return RealType;
generic
type IntType is (<>);
function convertst3 (nv : Textwide) return IntType;
generic
type RealType is digits <>;
function convertst4 (nv : Textwide) return RealType;
generic
type IntType is (<>);
function convertst5 (nv : Textsuper) return IntType;
generic
type RealType is digits <>;
function convertst6 (nv : Textsuper) return RealType;
generic
type IntType is (<>);
function convert2str1 (nv : IntType) return String;
generic
type IntType is (<>);
function convert2utf8 (nv : IntType) return Text_UTF8;
generic
type IntType is (<>);
function convert2str2 (nv : IntType) return Wide_String;
generic
type IntType is (<>);
function convert2str3 (nv : IntType) return Wide_Wide_String;
generic
type RealType is digits <>;
function convert3utf8 (nv : RealType) return Text_UTF8;
generic
type RealType is digits <>;
function convert3str1 (nv : RealType) return String;
generic
type RealType is digits <>;
function convert3str2 (nv : RealType) return Wide_String;
generic
type RealType is digits <>;
function convert3str3 (nv : RealType) return Wide_Wide_String;
generic
type IntType is (<>);
function convert4str (nv : String) return IntType;
generic
type RealType is digits <>;
function convert4st2 (nv : String) return RealType;
generic
type ModType is mod <>;
width : Natural;
function convert2bits (nv : ModType) return Bits;
generic
type ModType is mod <>;
width : Positive;
function convert2chain (nv : ModType) return Chain;
generic
type ModType is mod <>;
MSB : Positive;
function convert_bits (nv : Bits) return ModType;
generic
type ModType is mod <>;
width : Positive;
function convert_chain (nv : Chain) return ModType;
private
function ctrim (raw : String) return String;
function wtrim (raw : String) return Wide_String;
function strim (raw : String) return Wide_Wide_String;
end AdaBase.Results.Generic_Converters;
|
with System;
with STM32_SVD; use STM32_SVD;
with STM32_SVD.PWR; use STM32_SVD.PWR;
with STM32_SVD.SCB; use STM32_SVD.SCB;
with STM32_SVD.ADC; use STM32_SVD.ADC;
package body STM32GD.Power is
procedure Enable_Sleep is
begin
PWR_Periph.CR.LPDS := 0;
PWR_Periph.CR.PDDS := 0;
SCB_Periph.SCR.SLEEPDEEP := 0;
end Enable_Sleep;
procedure Enable_Stop is
begin
PWR_Periph.CR.LPDS := 1;
PWR_Periph.CR.PDDS := 0;
SCB_Periph.SCR.SLEEPDEEP := 1;
end Enable_Stop;
procedure Enable_Standby is
begin
PWR_Periph.CR.LPDS := 1;
PWR_Periph.CR.PDDS := 1;
SCB_Periph.SCR.SLEEPDEEP := 1;
end Enable_Standby;
function Supply_Voltage return Millivolts is
V : Millivolts;
VREFINT_CAL : aliased STM32_SVD.UInt16
with Address => System'To_Address (16#1FF8_0078#);
begin
ADC_Periph.CR.ADCAL := 1;
while ADC_Periph.CR.ADCAL = 1 loop
null;
end loop;
ADC_Periph.CCR.VREFEN := 1;
ADC_Periph.ISR.ADRDY := 1;
ADC_Periph.CR.ADEN := 1;
while ADC_Periph.ISR.ADRDY = 0 loop
null;
end loop;
ADC_Periph.CHSELR.CHSEL.Arr (17) := 1;
ADC_Periph.CR.ADSTART := 1;
while ADC_Periph.ISR.EOC = 0 loop
null;
end loop;
V := 3000 * Standard.Integer (VREFINT_CAL) / Standard.Integer (ADC_Periph.DR.Data);
ADC_Periph.CR.ADDIS := 1;
ADC_Periph.CCR.VREFEN := 0;
return V;
end Supply_Voltage;
end STM32GD.Power;
|
with Memory.Perfect_Prefetch;
separate (Parser)
procedure Parse_Perfect_Prefetch(parser : in out Parser_Type;
result : out Memory_Pointer) is
mem : Memory_Pointer := null;
begin
Parse_Memory(parser, mem);
if mem = null then
Raise_Error(parser, "memory not set in perfect_prefetch");
end if;
result := Memory_Pointer(Perfect_Prefetch.Create_Perfect_Prefetch(mem));
end Parse_Perfect_Prefetch;
|
package Railway with SPARK_Mode is
type One_Signal_State is (Red, Green);
type Route_Type is (Route_Left_Middle, -- lewy do srodkowego
Route_Middle_Right, -- srodkowy do prawego
Route_Right_Middle, -- prawy do srodkowego
Route_Middle_Left, -- srodkowy do lewego
Route_Enter_Left, -- wjazd z lewej
Route_Leave_Right, -- wyjazd z prawej
Route_Enter_Right, -- wjazd z prawej
Route_Leave_Left); -- wyjazd z lewej
type One_Segment_State is (Occupied_Standing, -- zajety, stoi
Occupied_Moving_Left, -- zajety, w lewo
Occupied_Moving_Right, -- zajety, w prawo
Reserved_Moving_From_Left, -- resvd, mv z lew
Reserved_Moving_From_Right, -- rsvd, mv z praw
Free); -- WOLNE
type Segment_State_Type is
record
Left, -- lewy segment
Middle, -- srodkowy segment
Right : One_Segment_State; -- prawy segment
end record;
type Signal_State_Type is
record
Left_Middle, -- lewy do srodkowego stan
Middle_Left, -- srodkowy do lewego stan
Middle_Right, -- srodkowy do prawego stan
Right_Middle: One_Signal_State; -- prawy do srodkowego stan
end record;
Segment_State : Segment_State_Type := (others => Free); -- stan segmentu
Signal_State : Signal_State_Type := (others => Red); -- stan sygnalizatora
function Correct_Signals return Boolean
is
(
(if Signal_State.Left_Middle = Green then
Segment_State.Left = Occupied_Moving_Right and
Segment_State.Middle = Reserved_Moving_From_Left) and then
(if Signal_state.Middle_Left = Green then
Segment_State.Middle = Occupied_Moving_Left and
Segment_State.Left = Reserved_Moving_From_Right) and then
(if Signal_state.Middle_Right = Green then
Segment_State.Middle = Occupied_Moving_Right and
Segment_State.Right = Reserved_Moving_From_Left) and then
(if Signal_state.Right_Middle = Green then
Segment_State.Right = Occupied_Moving_Left and
Segment_State.Middle = Reserved_Moving_From_Right));
function Correct_Segments return Boolean
is
(
(if Segment_State.Left /= Reserved_Moving_From_Right then
Signal_State.Middle_Left = Red) and
(if Segment_State.Middle /= Reserved_Moving_From_Left then
Signal_State.Left_Middle = Red) and
(if Segment_State.Middle /= Reserved_Moving_From_Right then
Signal_State.Right_Middle = Red) and
(if Segment_State.Right /= Reserved_Moving_From_Left then
Signal_State.Middle_Right = Red));
procedure Open_Route (Route: in Route_Type; Success: out Boolean)
with
Global => (In_Out => (Segment_State, Signal_State)),
Pre => Correct_Signals and Correct_Segments,
Depends => ((Segment_State, Success) => (Route, Segment_State),
Signal_State => (Segment_State, Route, Signal_State)),
Post => Correct_Signals and Correct_Segments;
procedure Move_Train (Route: in Route_Type; Success: out Boolean)
with
Global => (In_Out => (Segment_State, Signal_State)),
Pre => Correct_Signals and Correct_Segments,
Depends => ((Segment_State, Success) => (Route, Segment_State),
Signal_State => (Segment_State, Route, Signal_State)),
Post => Correct_Signals and Correct_Segments;
--Just to Open_Route and then if possible Move_Train.
procedure Train (Route : in Route_Type; retval : in out Boolean);
end Railway;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Localization, Internationalization, Globalization for Ada --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2011-2017, Vadim Godunko <vgodunko@gmail.com> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
package body Matreshka.Internals.Calendars.Gregorian is
-- Gregorian_Epoch : constant := 1_721_426;
Min_Year : constant := -10_000;
Julian_Epoch : constant := 1_931_305;
-- days from Min_Year to zero julian day
Days_In_4_Years : constant := 365 * 4 + 1;
Days_In_400_Years : constant := ((365 * 4 + 1) * 25 - 1) * 4 + 1;
procedure Split
(Julian_Day : Julian_Day_Number;
Shifted_Year : out Julian_Day_Number;
Day_In_Year : out Julian_Day_Number);
---------
-- Day --
---------
function Day (Julian_Day : Julian_Day_Number) return Day_Number is
Days : Julian_Day_Number;
Years : Julian_Day_Number;
Shifted_Month : Julian_Day_Number;
begin
Split (Julian_Day, Shifted_Year => Years, Day_In_Year => Days);
Shifted_Month := (5 * Days + 2) / 153;
return Day_Number (Days - (153 * Shifted_Month + 2) / 5 + 1);
end Day;
-----------------
-- Day_Of_Week --
-----------------
function Day_Of_Week
(Julian_Day : Julian_Day_Number) return Day_Of_Week_Number is
begin
return Day_Of_Week_Number ((Julian_Day mod 7) + 1);
end Day_Of_Week;
-----------------
-- Day_Of_Year --
-----------------
function Day_Of_Year
(Julian_Day : Julian_Day_Number) return Day_Of_Year_Number
is
Days : Julian_Day_Number;
Years : Julian_Day_Number;
begin
Split (Julian_Day, Shifted_Year => Years, Day_In_Year => Days);
return Day_Of_Year_Number (Days + 1);
end Day_Of_Year;
-------------------
-- Days_In_Month --
-------------------
function Days_In_Month (Date : Julian_Day_Number) return Day_Number is
begin
return Days_In_Month (Year (Date), Month (Date));
end Days_In_Month;
-------------------
-- Days_In_Month --
-------------------
function Days_In_Month
(Year : Year_Number; Month : Year_Number) return Day_Number
is
-- Length of months has some kind of regularity and circularity:
--
-- 12 31 7 31
-- 1 31 8 31
-- 2 28/29 9 30
-- 3 31 10 31
-- 4 30 11 30
-- 5 31
-- 6 30
--
-- To make December be first month the reminder of 12 of Month is
-- computed. Reminder of 7 is used to compute number of month in cycle.
-- Now, base number of days can be computed as:
--
-- Base := 30 + Month_In_Cycle mod 2
--
-- Later, correction is computed:
--
-- +1, then month_in_cycle = 0, so, for July and December.
-- -1, then Month = 2 and Is_Leap_Year (Year), so for February of leap
-- year
-- -2, then Month = 2 and not Is_Leap_Year (Year), so for February of
-- non leap year.
-- 0, otherwise
Month_In_Cycle : constant Integer := (Month mod 12) mod 7;
Base : Integer := 30 + (Month_In_Cycle mod 2);
begin
if Month_In_Cycle = 0 then
Base := Base + 1;
elsif Month = 2 then
Base := Base - 1;
if not Is_Leap_Year (Year) then
Base := Base - 1;
end if;
end if;
return Base;
end Days_In_Month;
------------------
-- Days_In_Year --
------------------
function Days_In_Year
(Date : Julian_Day_Number) return Day_Of_Year_Number is
begin
return Days_In_Year (Year (Date));
end Days_In_Year;
------------------
-- Days_In_Year --
------------------
function Days_In_Year (Year : Year_Number) return Day_Of_Year_Number is
begin
if Is_Leap_Year (Year) then
return 366;
else
return 365;
end if;
end Days_In_Year;
------------------
-- Is_Leap_Year --
------------------
function Is_Leap_Year (Date : Julian_Day_Number) return Boolean is
begin
return Is_Leap_Year (Year (Date));
end Is_Leap_Year;
------------------
-- Is_Leap_Year --
------------------
function Is_Leap_Year (Year : Year_Number) return Boolean is
begin
return Year mod 4 = 0 and (Year mod 100 /= 0 or Year mod 400 = 0);
end Is_Leap_Year;
----------------
-- Julian_Day --
----------------
function Julian_Day
(Year : Year_Number;
Month : Month_Number;
Day : Day_Number) return Julian_Day_Number
is
Shifted_Year : constant Julian_Day_Number
:= Julian_Day_Number (Year - Min_Year) - Boolean'Pos (Month <= 2);
Shifted_Month : constant Julian_Day_Number
:= Julian_Day_Number (Month - 3) mod 12;
begin
return
Julian_Day_Number (Day - 1)
+ (153 * Shifted_Month + 2) / 5 -- first day of year for month
+ 365 * Shifted_Year
+ Shifted_Year / 4 -- number of leap years
- Shifted_Year / 100 -- excluding 100
+ Shifted_Year / 400 -- includeing 400
- Julian_Epoch; -- days from Min_Year to zero julian day
end Julian_Day;
-----------
-- Month --
-----------
function Month (Julian_Day : Julian_Day_Number) return Month_Number is
Days : Julian_Day_Number;
Years : Julian_Day_Number;
Shifted_Month : Julian_Day_Number;
begin
Split (Julian_Day, Shifted_Year => Years, Day_In_Year => Days);
Shifted_Month := (5 * Days + 2) / 153;
return Month_Number (((Shifted_Month + 2) mod 12) + 1);
end Month;
-----------
-- Split --
-----------
procedure Split
(Date : Julian_Day_Number;
Year : out Year_Number;
Month : out Month_Number;
Day : out Day_Number)
is
Days : Julian_Day_Number;
Years : Julian_Day_Number;
Shifted_Month : Julian_Day_Number;
begin
Split (Date, Shifted_Year => Years, Day_In_Year => Days);
Shifted_Month := (5 * Days + 2) / 153;
Year := Year_Number (Years + Boolean'Pos (Days > 305) + Min_Year);
Month := Month_Number (((Shifted_Month + 2) mod 12) + 1);
Day := Day_Number (Days - (153 * Shifted_Month + 2) / 5 + 1);
end Split;
-----------
-- Split --
-----------
procedure Split
(Julian_Day : Julian_Day_Number;
Shifted_Year : out Julian_Day_Number;
Day_In_Year : out Julian_Day_Number)
is
Days : Julian_Day_Number := Julian_Day + Julian_Epoch;
Years : Julian_Day_Number;
Centuries : constant Julian_Day_Number
:= (4 * Days + 3) / Days_In_400_Years;
begin
Days := Days - Centuries * Days_In_400_Years / 4;
Years := (Days * 4 + 3) / Days_In_4_Years;
Day_In_Year := Days - Years * Days_In_4_Years / 4;
Shifted_Year := 100 * Centuries + Years;
end Split;
----------
-- Year --
----------
function Year (Julian_Day : Julian_Day_Number) return Year_Number is
Days : Julian_Day_Number;
Years : Julian_Day_Number;
begin
Split (Julian_Day, Shifted_Year => Years, Day_In_Year => Days);
return Year_Number (Years + Boolean'Pos (Days > 305) + Min_Year);
end Year;
end Matreshka.Internals.Calendars.Gregorian;
|
--
-- Copyright 2021 (C) Jeremy Grosser <jeremy@synack.me>
--
-- SPDX-License-Identifier: Apache-2.0
--
with Interfaces.C; use Interfaces.C;
with Interfaces.C_Streams;
package body Notcurses.Context is
procedure Initialize is
begin
Default_Context := Notcurses_Context
(Thin.notcurses_init (Default_Options'Access, Interfaces.C_Streams.NULL_Stream));
end Initialize;
procedure Render
(Context : Notcurses_Context)
is
Result : int;
begin
Result := Thin.notcurses_render (Context);
if Result /= 0 then
raise Notcurses_Error with "Failed to render notcurses context";
end if;
end Render;
procedure Enable_Cursor
(Context : Notcurses_Context;
Y, X : Integer := 0)
is
begin
if Thin.notcurses_cursor_enable (Context, int (Y), int (X)) /= 0 then
raise Notcurses_Error with "Failed to enable cursor";
end if;
end Enable_Cursor;
procedure Enable_Mouse
(Context : Notcurses_Context)
is
begin
if Thin.notcurses_mouse_enable (Context) /= 0 then
raise Notcurses_Error with "Failed to enable mouse";
end if;
end Enable_Mouse;
function Get
(Context : Notcurses_Context)
return Notcurses_Input
is
NI : aliased Thin.ncinput;
Char : Wide_Wide_Character with Unreferenced;
begin
Char := Wide_Wide_Character'Val (Thin.notcurses_get (Context, null, NI'Access));
return To_Ada (NI);
end Get;
function Palette_Size
(Context : Notcurses_Context)
return Natural
is
begin
return Natural (Thin.notcurses_palette_size (Context)) - 1;
end Palette_Size;
procedure Stop
(Context : in out Notcurses_Context)
is
Result : int;
begin
Result := Thin.notcurses_stop (Context);
if Result /= 0 then
raise Notcurses_Error with "Failed to stop notcurses context";
end if;
Context := null;
end Stop;
procedure Stop is
begin
Stop (Default_Context);
Default_Context := null;
end Stop;
end Notcurses.Context;
|
--
-- Uwe R. Zimmer, Australia, 2013
--
with Ada.Unchecked_Deallocation;
generic
type Element is private;
Default_Value : Element;
package Generic_Protected is
protected type Monitor is
function Read return Element;
procedure Write (E : Element);
entry Wait_for_Update (E : out Element);
private
Value : Element := Default_Value;
Touched : Boolean := False;
end Monitor;
type Monitor_Ptr is access Monitor;
function Allocate (Value : Element := Default_Value) return Monitor_Ptr;
procedure Free is
new Ada.Unchecked_Deallocation (Object => Monitor, Name => Monitor_Ptr);
end Generic_Protected;
|
package Loop_Optimization6 is
A : Integer := 0;
procedure Main;
end Loop_Optimization6;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUNTIME COMPONENTS --
-- --
-- S Y S T E M . I M G _ B I U --
-- --
-- S p e c --
-- --
-- $Revision: 2 $ --
-- --
-- Copyright (c) 1992,1993,1994 NYU, All Rights Reserved --
-- --
-- The GNAT library is free software; you can redistribute it and/or modify --
-- it under terms of the GNU Library General Public License as published by --
-- the Free Software Foundation; either version 2, or (at your option) any --
-- later version. The GNAT 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 --
-- the GNAT library; see the file COPYING.LIB. If not, write to the Free --
-- Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. --
-- --
------------------------------------------------------------------------------
-- Contains the routine for computing the image in based format of signed and
-- unsigned integers whose size <= Integer'Size for use by Text_Io.Integer_Io,
-- Text_Io.Modular_Io, and the Img attribute.
with System.Unsigned_Types;
package System.Img_BIU is
pragma Preelaborate (Img_BIU);
procedure Set_Image_Based_Integer
(V : Integer;
B : Natural;
W : Integer;
S : out String;
P : in out Natural);
-- Sets the signed image of V in based format, using base value B (2..16)
-- starting at S (P + 1), updating P to point to the last character stored.
-- The image includes a leading minus sign if necessary, but no leading
-- spaces unless W is positive, in which case leading spaces are output if
-- necessary to ensure that the output string is no less than W characters
-- long. The caller promises that the buffer is large enough and no check
-- is made for this. Constraint_Error will not necessarily be raised if
-- this is violated, since it is perfectly valid to compile this unit with
-- checks off.
procedure Set_Image_Based_Unsigned
(V : System.Unsigned_Types.Unsigned;
B : Natural;
W : Integer;
S : out String;
P : in out Natural);
-- Sets the unsigned image of V in based format, using base value B (2..16)
-- starting at S (P + 1), updating P to point to the last character stored.
-- The image includes no leading spaces unless W is positive, in which case
-- leading spaces are output if necessary to ensure that the output string
-- is no less than W characters long. The caller promises that the buffer
-- is large enough and no check is made for this. Constraint_Error will not
-- necessarily be raised if this is violated, since it is perfectly valid
-- to compile this unit with checks off).
end System.Img_BIU;
|
with Ada.Text_IO, Ada.Numerics.Discrete_Random, HTML_Table;
procedure Test_HTML_Table is
-- define the Item_Type and the random generator
type Four_Digits is mod 10_000;
package Rand is new Ada.Numerics.Discrete_Random(Four_Digits);
Gen: Rand.Generator;
-- now we instantiate the generic package HTML_Table
package T is new HTML_Table
(Item_Type => Four_Digits,
To_String => Four_Digits'Image,
Put => Ada.Text_IO.Put,
Put_Line => Ada.Text_IO.Put_Line);
-- define the object that will the values that the table contains
The_Table: T.Item_Array(1 .. 4, 1..3);
begin
-- fill The_Table with random values
Rand.Reset(Gen);
for Rows in The_Table'Range(1) loop
for Cols in The_Table'Range(2) loop
The_Table(Rows, Cols) := Rand.Random(Gen);
end loop;
end loop;
-- output The_Table
T.Print(Items => The_Table,
Column_Heads => (T.Convert("X"), T.Convert("Y"), T.Convert("Z")));
end Test_HTML_Table;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
package Signals is
-- Returns True if Interrupt signal (control-C) has been detected
function graceful_shutdown_requested return Boolean;
-- Enable exception handlers to initiate a shutdown upon detecting an issue
procedure initiate_shutdown;
private
control_q_break : Boolean := False;
end Signals;
|
-- { dg-do compile }
-- { dg-options "-cargs -g -fgnat-encodings=minimal -dA -margs" }
-- { dg-final { scan-assembler-not "DW_OP_const4u" } }
-- { dg-final { scan-assembler-not "DW_OP_const8u" } }
-- The DW_AT_byte_size attribute DWARF expression for the
-- DW_TAG_structure_type DIE that describes Rec_Type contains the -4u literal.
-- Check that it is not created using an inefficient encoding (DW_OP_const1s
-- is expected).
procedure Debug8 is
type Rec_Type (I : Integer) is record
B : Boolean;
case I is
when 0 =>
null;
when 1 .. 10 =>
C : Character;
when others =>
N : Natural;
end case;
end record;
R : access Rec_Type := null;
begin
null;
end Debug8;
|
-------------------------------------------------------------------------------
-- File: adaid.ads
-- Description: A UUID type for Ada
-- Author: Anthony Arnold
-- License: Simplified BSD License (see LICENSE)
-------------------------------------------------------------------------------
with Ada.Finalization;
with Interfaces; use Interfaces; -- for Unsigned_n
-- AdaID defines the types and accessor/miscellaneous functions for
-- the UUID type.
package AdaID is
uuid_size : constant Integer := 16;
-- This many bytes in a UUID
subtype HashType is Unsigned_32;
-- Represents a "Hash Code" of a UUID
type Byte is mod 2 ** 8;
-- Byte Type (2^8)
type ByteArray is array (0 .. uuid_size - 1) of Byte;
-- Byte Array for UUID data storage
type VersionType is (
Unknown,
Time_Based,
DCE_Security,
Name_Based_MD5,
Random_Number_Based,
Name_Based_SHA1
);
-- The Version of the UUID
type VariantType is (
NCS,
RFC_4122,
Microsoft,
Future
);
-- The UUID Variant
type UUID is new Ada.Finalization.Controlled with
record
data : ByteArray;
end record;
-- The main type for the package
function Is_Nil (This : in UUID) return Boolean;
-- Determine if UUID is NIL (All Zeros)
function Get_Version (This : in UUID) return VersionType;
-- Get the UUID Version
function Get_Variant (This : in UUID) return VariantType;
-- Get the UUID Variant
function "="(Left, Right : in UUID) return Boolean;
-- Test for equality between Left and Right
function Get_Hash_Value (This : in UUID) return HashType;
-- Get the hash code for the UUID
function To_String (This : in UUID) return String;
-- Convert the UUID to a common string representation
private
overriding procedure Initialize (This : in out UUID);
-- Default "constructor", initializes to NIL
end AdaID;
|
-- This unit provides sub-programs to encode/decode COBS from arrays in
-- memory. The entire encoded/decoded frame must be available in a
-- contiguous array.
with System.Storage_Elements; use System.Storage_Elements;
package COBS
with Preelaborate
is
function Max_Encoding_Length (Data_Len : Storage_Count)
return Storage_Count;
-- Return the worst case output size for a given data length
procedure Encode (Data : Storage_Array;
Output : in out Storage_Array;
Output_Last : out Storage_Offset;
Success : out Boolean);
-- Encode input Data into the Output buffer without adding a delimiter.
-- Output_Last is the index of the last encoded byte in the Output
-- buffer. The procedure will return with Success = False if the Output
-- buffer is not large enough to encode the input. You can use the
-- Max_Encoding_Length function to get the worst case output size for
-- a given data length.
procedure Decode (Data : Storage_Array;
Output : in out Storage_Array;
Output_Last : out Storage_Offset;
Success : out Boolean);
-- Decode input Data into the Output buffer. Output_Last is the index of
-- the last decoded byte in the Output buffer. The procedure will return
-- with Success = False if the Output buffer is not large enough to decode
-- the input, or if the COBS frame is not correctly encoded.
procedure Decode_In_Place (Data : in out Storage_Array;
Last : out Storage_Offset;
Success : out Boolean);
-- Decode input Data inside the Data buffer itself. Last is the index of
-- the last decoded byte in the Data buffer. The procedure will return
-- with Success = False if the COBS frame is not correctly encoded.
end COBS;
|
-- part of OpenGLAda, (c) 2017 Felix Krause
-- released under the terms of the MIT license, see the file "COPYING"
with Interfaces.C.Strings;
with Interfaces.C.Pointers;
with System;
with Glfw.Input.Keys;
with Glfw.Input.Mouse;
with Glfw.Input.Joysticks;
with Glfw.Monitors;
with Glfw.Errors;
with Glfw.Enums;
with Glfw.Windows.Context;
private package Glfw.API is
-----------------------------------------------------------------------------
-- Types
-----------------------------------------------------------------------------
type Address_List is array (Positive range <>) of aliased System.Address;
pragma Convention (C, Address_List);
package Address_List_Pointers is new Interfaces.C.Pointers
(Positive, System.Address, Address_List, System.Null_Address);
package VMode_List_Pointers is new Interfaces.C.Pointers
(Positive, Monitors.Video_Mode, Monitors.Video_Mode_List, (others => 0));
package Axis_Position_List_Pointers is new Interfaces.C.Pointers
(Positive, Input.Joysticks.Axis_Position, Input.Joysticks.Axis_Positions,
0.0);
package Joystick_Button_State_List_Pointers is new Interfaces.C.Pointers
(Positive, Input.Joysticks.Joystick_Button_State,
Input.Joysticks.Joystick_Button_States, Input.Joysticks.Released);
type Unsigned_Short_List is array (Positive range <>) of aliased
Interfaces.C.unsigned_short;
package Unsigned_Short_List_Pointers is new Interfaces.C.Pointers
(Positive, Interfaces.C.unsigned_short, Unsigned_Short_List, 0);
type Raw_Gamma_Ramp is record
Red, Green, Blue : Unsigned_Short_List_Pointers.Pointer;
Size : Interfaces.C.unsigned;
end record;
pragma Convention (C, Raw_Gamma_Ramp);
-----------------------------------------------------------------------------
-- Callbacks
-----------------------------------------------------------------------------
type Error_Callback is access procedure (Code : Errors.Kind;
Description : C.Strings.chars_ptr);
type Window_Position_Callback is access procedure
(Window : System.Address; X, Y : C.int);
type Window_Size_Callback is access procedure
(Window : System.Address; Width, Height : C.int);
type Window_Close_Callback is access procedure
(Window : System.Address);
type Window_Refresh_Callback is access procedure
(Window : System.Address);
type Window_Focus_Callback is access procedure
(Window : System.Address; Focussed : Bool);
type Window_Iconify_Callback is access procedure
(Window : System.Address; Iconified : Bool);
type Framebuffer_Size_Callback is access procedure
(Window : System.Address; Width, Height : C.int);
type Mouse_Button_Callback is access procedure (Window : System.Address;
Button : Input.Mouse.Button;
State : Input.Button_State;
Mods : Input.Keys.Modifiers);
type Cursor_Position_Callback is access procedure
(Window : System.Address; X, Y : Input.Mouse.Coordinate);
type Cursor_Enter_Callback is access procedure
(Window : System.Address; Action : Input.Mouse.Enter_Action);
type Scroll_Callback is access procedure
(Window : System.Address; X, Y : Input.Mouse.Scroll_Offset);
type Key_Callback is access procedure (Window : System.Address;
Key : Input.Keys.Key;
Scancode : Input.Keys.Scancode;
Action : Input.Keys.Action;
Mods : Input.Keys.Modifiers);
type Character_Callback is access procedure
(Window : System.Address; Unicode_Char : Interfaces.C.unsigned);
type Monitor_Callback is access procedure
(Monitor : System.Address; Event : Monitors.Event);
pragma Convention (C, Error_Callback);
pragma Convention (C, Window_Position_Callback);
pragma Convention (C, Window_Size_Callback);
pragma Convention (C, Window_Close_Callback);
pragma Convention (C, Window_Refresh_Callback);
pragma Convention (C, Window_Focus_Callback);
pragma Convention (C, Window_Iconify_Callback);
pragma Convention (C, Framebuffer_Size_Callback);
pragma Convention (C, Mouse_Button_Callback);
pragma Convention (C, Cursor_Position_Callback);
pragma Convention (C, Cursor_Enter_Callback);
pragma Convention (C, Scroll_Callback);
pragma Convention (C, Key_Callback);
pragma Convention (C, Character_Callback);
pragma Convention (C, Monitor_Callback);
-----------------------------------------------------------------------------
-- Basics
-----------------------------------------------------------------------------
function Init return C.int;
pragma Import (Convention => C, Entity => Init,
External_Name => "glfwInit");
procedure Glfw_Terminate;
pragma Import (Convention => C, Entity => Glfw_Terminate,
External_Name => "glfwTerminate");
procedure Get_Version (Major, Minor, Revision : out C.int);
pragma Import (Convention => C, Entity => Get_Version,
External_Name => "glfwGetVersion");
function Get_Version_String return C.Strings.chars_ptr;
pragma Import (Convention => C, Entity => Get_Version_String,
External_Name => "glfwGetVersionString");
function Get_Time return C.double;
pragma Import (Convention => C, Entity => Get_Time,
External_Name => "glfwGetTime");
procedure Set_Time (Value : C.double);
pragma Import (Convention => C, Entity => Set_Time,
External_Name => "glfwSetTime");
procedure Sleep (Time : C.double);
pragma Import (Convention => C, Entity => Sleep,
External_Name => "glfwSleep");
function Extension_Supported (Name : C.char_array) return Bool;
pragma Import (Convention => C, Entity => Extension_Supported,
External_Name => "glfwExtensionSupported");
function Set_Error_Callback (CB_Fun : Error_Callback) return Error_Callback;
pragma Import (Convention => C, Entity => Set_Error_Callback,
External_Name => "glfwSetErrorCallback");
-----------------------------------------------------------------------------
-- Monitors
-----------------------------------------------------------------------------
function Get_Monitors (Count : access Interfaces.C.int)
return Address_List_Pointers.Pointer;
pragma Import (Convention => C, Entity => Get_Monitors,
External_Name => "glfwGetMonitors");
function Get_Primary_Monitor return System.Address;
pragma Import (Convention => C, Entity => Get_Primary_Monitor,
External_Name => "glfwGetPrimaryMonitor");
procedure Get_Monitor_Pos (Monitor : System.Address;
XPos, YPos : out Interfaces.C.int);
pragma Import (Convention => C, Entity => Get_Monitor_Pos,
External_Name => "glfwGetMonitorPos");
procedure Get_Monitor_Physical_Size (Monitor : System.Address;
Width, Height : out Interfaces.C.int);
pragma Import (Convention => C, Entity => Get_Monitor_Physical_Size,
External_Name => "glfwGetMonitorPhysicalSize");
function Get_Monitor_Name (Monitor : System.Address)
return Interfaces.C.Strings.chars_ptr;
pragma Import (Convention => C, Entity => Get_Monitor_Name,
External_Name => "glfwGetMonitorName");
function Set_Monitor_Callback (Monitor : System.Address;
CB_Fun : Monitor_Callback)
return Monitor_Callback;
pragma Import (Convention => C, Entity => Set_Monitor_Callback,
External_Name => "glfwSetMonitorCallback");
function Get_Video_Modes (Monitor : System.Address;
Count : access Interfaces.C.int)
return VMode_List_Pointers.Pointer;
pragma Import (Convention => C, Entity => Get_Video_Modes,
External_Name => "glfwGetVideoModes");
function Get_Video_Mode (Monitor : System.Address)
return access constant Monitors.Video_Mode;
pragma Import (Convention => C, Entity => Get_Video_Mode,
External_Name => "glfwGetVideoMode");
procedure Set_Gamma (Monitor : System.Address; Gamma : Interfaces.C.C_float);
pragma Import (Convention => C, Entity => Set_Gamma,
External_Name => "glfwSetGamma");
function Get_Gamma_Ramp (Monitor : System.Address)
return access constant Raw_Gamma_Ramp;
pragma Import (Convention => C, Entity => Get_Gamma_Ramp,
External_Name => "glfwGetGammaRamp");
procedure Set_Gamma_Ramp (Monitor : System.Address;
Value : access constant Raw_Gamma_Ramp);
pragma Import (Convention => C, Entity => Set_Gamma_Ramp,
External_Name => "glfwSetGammaRamp");
-----------------------------------------------------------------------------
-- Windows
-----------------------------------------------------------------------------
procedure Default_Window_Hints;
pragma Import (Convention => C, Entity => Default_Window_Hints,
External_Name => "glfwDefaultWindowHints");
procedure Window_Hint (Target : Glfw.Enums.Window_Hint; Info : C.int);
procedure Window_Hint (Target : Glfw.Enums.Window_Hint; Info : Bool);
procedure Window_Hint (Target : Glfw.Enums.Window_Hint;
Info : Windows.Context.OpenGL_Profile_Kind);
procedure Window_Hint (Target : Glfw.Enums.Window_Hint;
Info : Windows.Context.API_Kind);
procedure Window_Hint (Target : Glfw.Enums.Window_Hint;
Info : Glfw.Windows.Context.Robustness_Kind);
pragma Import (Convention => C, Entity => Window_Hint,
External_Name => "glfwWindowHint");
function Create_Window (Width, Height : Interfaces.C.int;
Title : Interfaces.C.char_array;
Monitor : System.Address;
Share : System.Address)
return System.Address;
pragma Import (Convention => C, Entity => Create_Window,
External_Name => "glfwCreateWindow");
procedure Destroy_Window (Window : System.Address);
pragma Import (Convention => C, Entity => Destroy_Window,
External_Name => "glfwDestroyWindow");
function Window_Should_Close (Window : System.Address)
return Bool;
pragma Import (Convention => C, Entity => Window_Should_Close,
External_Name => "glfwWindowShouldClose");
procedure Set_Window_Should_Close (Window : System.Address;
Value : Bool);
pragma Import (Convention => C, Entity => Set_Window_Should_Close,
External_Name => "glfwSetWindowShouldClose");
procedure Set_Window_Title (Window : System.Address;
Title : Interfaces.C.char_array);
pragma Import (Convention => C, Entity => Set_Window_Title,
External_Name => "glfwSetWindowTitle");
procedure Get_Window_Pos (Window : System.Address;
Xpos, Ypos : out Windows.Coordinate);
pragma Import (Convention => C, Entity => Get_Window_Pos,
External_Name => "glfwGetWindowPos");
procedure Set_Window_Pos (Window : System.Address;
Xpos, Ypos : Windows.Coordinate);
pragma Import (Convention => C, Entity => Set_Window_Pos,
External_Name => "glfwSetWindowPos");
procedure Get_Window_Size (Window : System.Address;
Width, Height : out Size);
pragma Import (Convention => C, Entity => Get_Window_Size,
External_Name => "glfwGetWindowSize");
procedure Set_Window_Size (Window : System.Address;
Width, Height : Size);
pragma Import (Convention => C, Entity => Set_Window_Size,
External_Name => "glfwSetWindowSize");
procedure Get_Framebuffer_Size (Window : System.Address;
Width, Height : out Size);
pragma Import (Convention => C, Entity => Get_Framebuffer_Size,
External_Name => "glfwGetFramebufferSize");
procedure Iconify_Window (Window : System.Address);
pragma Import (Convention => C, Entity => Iconify_Window,
External_Name => "glfwIconifyWindow");
procedure Restore_Window (Window : System.Address);
pragma Import (Convention => C, Entity => Restore_Window,
External_Name => "glfwRestoreWindow");
procedure Show_Window (Window : System.Address);
pragma Import (Convention => C, Entity => Show_Window,
External_Name => "glfwShowWindow");
procedure Hide_Window (Window : System.Address);
pragma Import (Convention => C, Entity => Hide_Window,
External_Name => "glfwHideWindow");
function Get_Window_Monitor (Window : System.Address) return System.Address;
pragma Import (Convention => C, Entity => Get_Window_Monitor,
External_Name => "glfwGetWindowMonitor");
function Get_Window_Attrib (Window : System.Address;
Attrib : Enums.Window_Info) return C.int;
function Get_Window_Attrib (Window : System.Address;
Attrib : Enums.Window_Info) return Bool;
function Get_Window_Attrib (Window : System.Address;
Attrib : Enums.Window_Info)
return Windows.Context.API_Kind;
function Get_Window_Attrib (Window : System.Address;
Attrib : Enums.Window_Info)
return Windows.Context.OpenGL_Profile_Kind;
function Get_Window_Attrib (Window : System.Address;
Attrib : Enums.Window_Info)
return Windows.Context.Robustness_Kind;
pragma Import (Convention => C, Entity => Get_Window_Attrib,
External_Name => "glfwGetWindowAttrib");
procedure Set_Window_User_Pointer (Window : System.Address;
Pointer : System.Address);
pragma Import (Convention => C, Entity => Set_Window_User_Pointer,
External_Name => "glfwSetWindowUserPointer");
function Get_Window_User_Pointer (Window : System.Address)
return System.Address;
pragma Import (Convention => C, Entity => Get_Window_User_Pointer,
External_Name => "glfwGetWindowUserPointer");
-- The callback setters in the C header are defined as returning the
-- previous callback pointer. This is rather low-level and not applicable
-- in the object-oriented interface of this binding. So we define the setters
-- as procedures, the return value will just get thrown away.
procedure Set_Window_Pos_Callback (Window : System.Address;
CB_Fun : Window_Position_Callback);
--return Window_Position_Callback;
pragma Import (Convention => C, Entity => Set_Window_Pos_Callback,
External_Name => "glfwSetWindowPosCallback");
procedure Set_Window_Size_Callback (Window : System.Address;
CB_Fun : Window_Size_Callback);
--return Window_Size_Callback;
pragma Import (Convention => C, Entity => Set_Window_Size_Callback,
External_Name => "glfwSetWindowSizeCallback");
procedure Set_Window_Close_Callback (Window : System.Address;
CB_Fun : Window_Close_Callback);
--return Window_Close_Callback;
pragma Import (Convention => C, Entity => Set_Window_Close_Callback,
External_Name => "glfwSetWindowCloseCallback");
procedure Set_Window_Refresh_Callback (Window : System.Address;
CB_Fun : Window_Refresh_Callback);
--return Window_Refresh_Callback;
pragma Import (Convention => C, Entity => Set_Window_Refresh_Callback,
External_Name => "glfwSetWindowRefreshCallback");
procedure Set_Window_Focus_Callback (Window : System.Address;
CB_Fun : Window_Focus_Callback);
--return Window_Focus_Callback;
pragma Import (Convention => C, Entity => Set_Window_Focus_Callback,
External_Name => "glfwSetWindowFocusCallback");
procedure Set_Window_Iconify_Callback (Window : System.Address;
CB_Fun : Window_Iconify_Callback);
--return Window_Iconify_Callback;
pragma Import (Convention => C, Entity => Set_Window_Iconify_Callback,
External_Name => "glfwSetWindowIconifyCallback");
procedure Set_Framebuffer_Size_Callback (Window : System.Address;
CB_Fun : Framebuffer_Size_Callback);
--return Framebuffer_Size_Callback;
pragma Import (Convention => C, Entity => Set_Framebuffer_Size_Callback,
External_Name => "glfwSetFramebufferSizeCallback");
-----------------------------------------------------------------------------
-- Input
-----------------------------------------------------------------------------
function Get_Input_Mode (Window : System.Address;
Mode : Enums.Input_Toggle) return Bool;
function Get_Input_Mode (Window : System.Address;
Mode : Enums.Input_Toggle)
return Input.Mouse.Cursor_Mode;
pragma Import (Convention => C, Entity => Get_Input_Mode,
External_Name => "glfwGetInputMode");
procedure Set_Input_Mode (Window : System.Address;
Mode : Input.Sticky_Toggle;
Value : Bool);
procedure Set_Input_Mode (Window : System.Address;
Mode : Enums.Input_Toggle;
Value : Input.Mouse.Cursor_Mode);
pragma Import (Convention => C, Entity => Set_Input_Mode,
External_Name => "glfwSetInputMode");
function Get_Key (Window : System.Address; Key : Input.Keys.Key)
return Input.Button_State;
pragma Import (Convention => C, Entity => Get_Key,
External_Name => "glfwGetKey");
function Get_Mouse_Button (Window : System.Address;
Button : Input.Mouse.Button)
return Input.Button_State;
pragma Import (Convention => C, Entity => Get_Mouse_Button,
External_Name => "glfwGetMouseButton");
procedure Get_Cursor_Pos (Window : System.Address;
Xpos, Ypos : out Input.Mouse.Coordinate);
pragma Import (Convention => C, Entity => Get_Cursor_Pos,
External_Name => "glfwGetCursorPos");
procedure Set_Cursor_Pos (Window : System.Address;
Xpos, Ypos : Input.Mouse.Coordinate);
pragma Import (Convention => C, Entity => Set_Cursor_Pos,
External_Name => "glfwSetCursorPos");
procedure Set_Key_Callback (Window : System.Address;
CB_Fun : Key_Callback);
--return Key_Callback
pragma Import (Convention => C, Entity => Set_Key_Callback,
External_Name => "glfwSetKeyCallback");
procedure Set_Char_Callback (Window : System.Address;
CB_Fun : Character_Callback);
--return Character_Callback;
pragma Import (Convention => C, Entity => Set_Char_Callback,
External_Name => "glfwSetCharCallback");
procedure Set_Mouse_Button_Callback (Window : System.Address;
CB_Fun : Mouse_Button_Callback);
--return Mouse_Button_Callback;
pragma Import (Convention => C, Entity => Set_Mouse_Button_Callback,
External_Name => "glfwSetMouseButtonCallback");
procedure Set_Cursor_Pos_Callback (Window : System.Address;
CB_Fun : Cursor_Position_Callback);
--return Cursor_Position_Callback;
pragma Import (Convention => C, Entity => Set_Cursor_Pos_Callback,
External_Name => "glfwSetCursorPosCallback");
procedure Set_Cursor_Enter_Callback (Window : System.Address;
CB_Fun : Cursor_Enter_Callback);
--return Cursor_Enter_Callback;
pragma Import (Convention => C, Entity => Set_Cursor_Enter_Callback,
External_Name => "glfwSetCursorEnterCallback");
procedure Set_Scroll_Callback (Window : System.Address;
CB_Fun : Scroll_Callback);
--return Scroll_Callback;
pragma Import (Convention => C, Entity => Set_Scroll_Callback,
External_Name => "glfwSetScrollCallback");
function Joystick_Present (Joy : Enums.Joystick_ID) return Bool;
pragma Import (Convention => C, Entity => Joystick_Present,
External_Name => "glfwJoystickPresent");
function Get_Joystick_Axes (Joy : Enums.Joystick_ID;
Count : access Interfaces.C.int)
return Axis_Position_List_Pointers.Pointer;
pragma Import (Convention => C, Entity => Get_Joystick_Axes,
External_Name => "glfwGetJoystickAxes");
function Get_Joystick_Buttons (Joy : Enums.Joystick_ID;
Count : access Interfaces.C.int)
return Joystick_Button_State_List_Pointers.Pointer;
pragma Import (Convention => C, Entity => Get_Joystick_Buttons,
External_Name => "glfwGetJoystickButtons");
function Get_Joystick_Name (Joy : Enums.Joystick_ID)
return Interfaces.C.Strings.chars_ptr;
pragma Import (Convention => C, Entity => Get_Joystick_Name,
External_Name => "glfwGetJoystickName");
procedure Poll_Events;
pragma Import (Convention => C, Entity => Poll_Events,
External_Name => "glfwPollEvents");
procedure Wait_Events;
pragma Import (Convention => C, Entity => Wait_Events,
External_Name => "glfwWaitEvents");
-----------------------------------------------------------------------------
-- Context
-----------------------------------------------------------------------------
procedure Make_Context_Current (Window : System.Address);
pragma Import (Convention => C, Entity => Make_Context_Current,
External_Name => "glfwMakeContextCurrent");
function Get_Current_Context return System.Address;
pragma Import (Convention => C, Entity => Get_Current_Context,
External_Name => "glfwGetCurrentContext");
procedure Swap_Buffers (Window : System.Address);
pragma Import (Convention => C, Entity => Swap_Buffers,
External_Name => "glfwSwapBuffers");
procedure Swap_Interval (Value : Windows.Context.Swap_Interval);
pragma Import (Convention => C, Entity => Swap_Interval,
External_Name => "glfwSwapInterval");
-----------------------------------------------------------------------------
-- Clipboard
-----------------------------------------------------------------------------
function Get_Clipboard_String (Window : System.Address)
return Interfaces.C.Strings.chars_ptr;
pragma Import (Convention => C, Entity => Get_Clipboard_String,
External_Name => "glfwGetClipboardString");
procedure Set_Clipboard_String (Window : System.Address;
Value : Interfaces.C.char_array);
pragma Import (Convention => C, Entity => Set_Clipboard_String,
External_Name => "glfwSetClipboardString");
end Glfw.API;
|
with Ada.Integer_Text_IO;
procedure Euler1 is
Sum: Integer := 0;
begin
for I in Integer range 1 .. 999 loop
if I mod 3 = 0 or I mod 5 = 0 then
Sum := Sum + I;
end if;
end loop;
Ada.Integer_Text_IO.Put(Sum);
end Euler1;
|
with
float_Math,
c_math_c.Vector_2,
c_math_c.Vector_3,
c_math_c.Matrix_3x3,
c_math_c.Matrix_4x4,
Interfaces;
package c_math_C.Conversion
--
-- Provide a set of conversion utilities.
--
is
package Math renames float_Math;
use Interfaces;
function "+" (Self : in Integer) return C.int;
function "+" (Self : in C.int) return Integer;
function "+" (Self : in math .Real) return c_math_c.Real;
function "+" (Self : in c_math_c.Real) return math .Real;
function "+" (Self : in math .Vector_2) return c_math_c.Vector_2.item;
function "+" (Self : in c_math_c.Vector_2.item) return math .Vector_2;
function "+" (Self : in math .Vector_3) return c_math_c.Vector_3.item;
function "+" (Self : in c_math_c.Vector_3.item) return math .Vector_3;
function "+" (Self : in math .Matrix_3x3) return c_math_c.Matrix_3x3.item;
function "+" (Self : in c_math_c.Matrix_3x3.item) return math .Matrix_3x3;
function "+" (Self : in math .Matrix_4x4) return c_math_c.Matrix_4x4.item;
function "+" (Self : in c_math_c.Matrix_4x4.item) return math .Matrix_4x4;
function to_Math (Self : in c_math_c.Matrix_4x4.item) return math.Matrix_4x4
renames "+";
end c_math_C.Conversion;
|
-- Copyright (c) 2013, Nordic Semiconductor ASA
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice, this
-- list of conditions and the following disclaimer.
--
-- * Redistributions in binary form must reproduce the above copyright notice,
-- this list of conditions and the following disclaimer in the documentation
-- and/or other materials provided with the distribution.
--
-- * Neither the name of Nordic Semiconductor ASA nor the names of its
-- contributors may be used to endorse or promote products derived from
-- this software without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--
-- This spec has been automatically generated from nrf51.svd
pragma Restrictions (No_Elaboration_Code);
pragma Ada_2012;
pragma Style_Checks (Off);
with HAL;
with System;
package NRF51_SVD.SWI is
pragma Preelaborate;
---------------
-- Registers --
---------------
-----------------
-- Peripherals --
-----------------
-- SW Interrupts.
type SWI_Peripheral is record
-- Unused.
UNUSED : aliased HAL.UInt32;
end record
with Volatile;
for SWI_Peripheral use record
UNUSED at 0 range 0 .. 31;
end record;
-- SW Interrupts.
SWI_Periph : aliased SWI_Peripheral
with Import, Address => System'To_Address (16#40014000#);
end NRF51_SVD.SWI;
|
pragma Ada_2012;
with Interfaces;
with System;
package body PBKDF2_Generic is
function PBKDF2
(Password : String; Salt : String; Iterations : Positive;
Derived_Key_Length : Index) return Element_Array
is
Password_Buffer : Element_Array
(Index (Password'First) .. Index (Password'Last));
for Password_Buffer'Address use Password'Address;
pragma Import (Ada, Password_Buffer);
Salt_Buffer : Element_Array (Index (Salt'First) .. Index (Salt'Last));
for Salt_Buffer'Address use Salt'Address;
pragma Import (Ada, Salt_Buffer);
begin
return
PBKDF2 (Password_Buffer, Salt_Buffer, Iterations, Derived_Key_Length);
end PBKDF2;
function PBKDF2
(Password : Element_Array; Salt : Element_Array; Iterations : Positive;
Derived_Key_Length : Index) return Element_Array
is
Result : Element_Array (0 .. Derived_Key_Length - 1);
Current : Index := Result'First;
Blocks_Needed : constant Index :=
Index
(Float'Ceiling (Float (Derived_Key_Length) / Float (Hash_Length)));
begin
for I in 1 .. Blocks_Needed loop
declare
Ctx : Hash_Context := Hash_Initialize (Password);
Temporary, Last : Element_Array (0 .. Hash_Length - 1);
begin
-- First iteration
Hash_Update (Ctx, Salt);
Hash_Update (Ctx, Write_Big_Endian (I));
Temporary := Hash_Finalize (Ctx);
Last := Temporary;
-- Subsequent iterations
for Unused in 2 .. Iterations loop
Ctx := Hash_Initialize (Password);
Hash_Update (Ctx, Last);
Last := Hash_Finalize (Ctx);
XOR_In_Place (Temporary, Last);
end loop;
declare
Bytes_To_Copy : constant Index :=
Index'Min
(Index'Min (Derived_Key_Length, Hash_Length),
Result'Last - Current + 1);
begin
Result (Current .. Current + Bytes_To_Copy - 1) :=
Temporary (0 .. Bytes_To_Copy - 1);
Current := Current + Bytes_To_Copy;
end;
end;
end loop;
return Result;
end PBKDF2;
function Write_Big_Endian (Input : Index) return Element_Array is
use Interfaces;
use System;
Int : constant Unsigned_32 := Unsigned_32 (Input);
begin
if Default_Bit_Order = High_Order_First then
return
(0 => Element (Int and 16#FF#),
1 => Element (Shift_Right (Int, 8) and 16#FF#),
2 => Element (Shift_Right (Int, 16) and 16#FF#),
3 => Element (Shift_Right (Int, 24) and 16#FF#));
else
return
(0 => Element (Shift_Right (Int, 24) and 16#FF#),
1 => Element (Shift_Right (Int, 16) and 16#FF#),
2 => Element (Shift_Right (Int, 8) and 16#FF#),
3 => Element (Int and 16#FF#));
end if;
end Write_Big_Endian;
procedure XOR_In_Place (L : in out Element_Array; R : Element_Array) is
begin
pragma Assert (L'Length = R'Length);
for I in L'Range loop
L (I) := L (I) xor R (I);
end loop;
end XOR_In_Place;
end PBKDF2_Generic;
|
with
AdaM.context_Line,
AdaM.Context,
gtk.Widget,
gtk.Button;
private
with
gtk.Check_Button,
gtk.Box;
package aIDE.Editor.of_context_line
is
type Item is new Editor.item with private;
type View is access all Item'Class;
package Forge
is
function to_context_line_Editor (the_Context : in AdaM.Context .view;
the_Context_Line : in AdaM.context_Line.view) return View;
end Forge;
overriding
function top_Widget (Self : in Item) return gtk.Widget.gtk_Widget;
function name_Button (Self : in Item) return gtk.Button.gtk_Button;
function context_Line (Self : in Item) return AdaM.context_Line.view;
private
use gtk.Check_Button,
gtk.Button,
gtk.Box;
type Item is new Editor.item with
record
Context : AdaM.Context .view;
context_Line : AdaM.context_Line.view;
Top : Gtk_Box;
name_Button : gtk_Button;
used_Button : gtk_Check_Button;
rid_Button : gtk_Button;
end record;
end aIDE.Editor.of_context_line;
|
-- $Id: ErrorsDrv.mi,v 1.0 1993/01/16 11:25:41 grosch Exp $
-- $Log: ErrorsDrv.mi,v $
-- Ich, Doktor Josef Grosch, Informatiker, Sept. 1994
with Text_Io, Sets, Strings, Idents, Position, Errors;
use Text_Io, Sets, Strings, Idents, Position, Errors;
procedure ErrorsDr is
Int : Integer;
Short : Integer range 0 .. 2 ** 16 - 1;
Long : Integer;
Real : Float;
Bool : Boolean;
Char : Character;
Str : tString;
Set : tSet;
Ident : tIdent;
procedure do_errors is
begin
MessageI ("Integer ", Errors.Error, NoPosition, Errors.cInteger , Int 'Address);
MessageI ("Short ", Errors.Error, NoPosition, Errors.cShort , Short 'Address);
MessageI ("Long ", Errors.Error, NoPosition, Errors.cLong , Long 'Address);
MessageI ("Real ", Errors.Error, NoPosition, Errors.cFloat , Real 'Address);
MessageI ("Boolean ", Errors.Error, NoPosition, Errors.cBoolean , Bool 'Address);
MessageI ("Character ", Errors.Error, NoPosition, Errors.cCharacter , Char 'Address);
MessageI ("String ", Errors.Error, NoPosition, Errors.cString , Str 'Address);
MessageI ("Set ", Errors.Error, NoPosition, Errors.cSet , Set 'Address);
MessageI ("Ident ", Errors.Error, NoPosition, Errors.cIdent , Ident 'Address);
end do_errors;
begin
Int := 1;
Short := 2;
Long := 3;
Real := 4.0;
Bool := False;
Char := 'a';
MakeSet (Set, 10); Include (Set, 5); Include (Set, 6);
To_tString ("def", Str); Ident := MakeIdent (Str);
do_errors; New_Line (Standard_Error);
StoreMessages (True);
do_errors;
WriteMessages (Standard_Error); New_Line (Standard_Error);
WriteMessages (Standard_Output); New_Line (Standard_Error);
StoreMessages (True);
WriteMessages (Standard_Output);
end ErrorsDr;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2018 onox <denkpadje@gmail.com>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Orka.Loggers;
with Orka.Transforms.Singles.Vectors;
with Orka.Transforms.Doubles.Vectors;
package Orka.Logging is
pragma Preelaborate;
subtype Source is Loggers.Source;
subtype Message_Type is Loggers.Message_Type;
subtype Severity is Loggers.Severity;
-----------------------------------------------------------------------------
function Image (Value : Duration) return String;
-- Return the image of the given duration with an appropriate suffix
function Image (Value : Orka.Transforms.Singles.Vectors.Vector4) return String;
function Image (Value : Orka.Transforms.Doubles.Vectors.Vector4) return String;
function Trim (Value : String) return String;
-----------------------------------------------------------------------------
procedure Set_Logger (Logger : Loggers.Logger_Ptr);
procedure Log
(From : Source;
Kind : Message_Type;
Level : Severity;
Message : String);
-- Log the message using the logger
--
-- If no logger has been set, it will log the message to the terminal.
generic
From : Source;
package Messages is
procedure Log (Level : Severity; Message : String);
end Messages;
end Orka.Logging;
|
with Ada.Exception_Identification.From_Here;
with System.Zero_Terminated_Strings;
with C.errno;
with C.fcntl;
with C.stdio; -- rename(2)
with C.sys.sendfile;
with C.unistd;
package body System.Native_Directories.Copying is
use Ada.Exception_Identification.From_Here;
use type Ada.Exception_Identification.Exception_Id;
use type C.signed_int;
use type C.unsigned_short; -- mode_t in FreeBSD
use type C.unsigned_int; -- open flag, and mode_t in Linux
use type C.signed_long; -- 64bit ssize_t
use type C.size_t;
-- implementation
procedure Copy_File (
Source_Name : String;
Target_Name : String;
Overwrite : Boolean := True)
is
Exception_Id : Ada.Exception_Identification.Exception_Id :=
Ada.Exception_Identification.Null_Id;
C_Source_Name : C.char_array (
0 ..
Source_Name'Length * Zero_Terminated_Strings.Expanding);
Source : C.signed_int;
C_Target_Name : C.char_array (
0 ..
Target_Name'Length * Zero_Terminated_Strings.Expanding);
Target : C.signed_int;
Flag : C.unsigned_int;
Data : aliased C.sys.stat.struct_stat;
Written : C.sys.types.ssize_t;
begin
Zero_Terminated_Strings.To_C (Source_Name, C_Source_Name (0)'Access);
Zero_Terminated_Strings.To_C (Target_Name, C_Target_Name (0)'Access);
Source := C.fcntl.open (C_Source_Name (0)'Access, C.fcntl.O_RDONLY);
if Source < 0 then
Exception_Id := Named_IO_Exception_Id (C.errno.errno);
else
if C.sys.stat.fstat (Source, Data'Access) < 0 then
Exception_Id := IO_Exception_Id (C.errno.errno);
else
Flag := C.fcntl.O_WRONLY or C.fcntl.O_CREAT or C.fcntl.O_EXLOCK;
if not Overwrite then
Flag := Flag or C.fcntl.O_EXCL;
end if;
Target := C.fcntl.open (
C_Target_Name (0)'Access,
C.signed_int (Flag),
Data.st_mode);
if Target < 0 then
Exception_Id := Named_IO_Exception_Id (C.errno.errno);
else
if C.unistd.ftruncate (Target, Data.st_size) < 0 then
null;
end if;
Written := C.sys.sendfile.sendfile (
Target,
Source,
null,
C.size_t (Data.st_size));
if Written < C.sys.types.ssize_t (Data.st_size) then
Exception_Id := Device_Error'Identity;
end if;
-- close target
if C.unistd.close (Target) < 0
and then Exception_Id = Ada.Exception_Identification.Null_Id
then
Exception_Id := IO_Exception_Id (C.errno.errno);
end if;
end if;
end if;
-- close source
if C.unistd.close (Source) < 0
and then Exception_Id = Ada.Exception_Identification.Null_Id
then
Exception_Id := IO_Exception_Id (C.errno.errno);
end if;
end if;
-- raising
if Exception_Id /= Ada.Exception_Identification.Null_Id then
Raise_Exception (Exception_Id);
end if;
end Copy_File;
procedure Replace_File (
Source_Name : String;
Target_Name : String)
is
C_Source_Name : C.char_array (
0 ..
Source_Name'Length * Zero_Terminated_Strings.Expanding);
C_Target_Name : C.char_array (
0 ..
Target_Name'Length * Zero_Terminated_Strings.Expanding);
Target_Info : aliased C.sys.stat.struct_stat;
Error : Boolean;
begin
Zero_Terminated_Strings.To_C (Source_Name, C_Source_Name (0)'Access);
Zero_Terminated_Strings.To_C (Target_Name, C_Target_Name (0)'Access);
-- if the target is already existing,
-- copy attributes from the target to the source.
Error := False;
if C.sys.stat.lstat (C_Target_Name (0)'Access, Target_Info'Access) = 0
and then (Target_Info.st_mode and C.sys.stat.S_IFMT) /=
C.sys.stat.S_IFLNK -- Linux does not have lchmod
then
Error := C.sys.stat.chmod (
C_Source_Name (0)'Access,
Target_Info.st_mode and C.sys.stat.ALLPERMS) < 0;
end if;
if not Error then
-- overwrite the target with the source.
Error := C.stdio.rename (
C_Source_Name (0)'Access,
C_Target_Name (0)'Access) < 0;
end if;
if Error then
Raise_Exception (Named_IO_Exception_Id (C.errno.errno));
end if;
end Replace_File;
end System.Native_Directories.Copying;
|
-- { dg-do run }
procedure Interface_Conv is
package Pkg is
type I1 is interface;
procedure Prim (X : I1) is null;
type I2 is interface;
procedure Prim (X : I2) is null;
type DT is new I1 and I2 with null record;
end Pkg;
use Pkg;
Obj : DT;
CW_3 : I2'Class := Obj;
CW_5 : I1'Class := I1'Class (CW_3); -- test
begin
null;
end;
|
with MyCommandLine;
with MyStringTokeniser;
with PasswordDatabase;
-- utility is a helper function with the aim to reduce code repetition within
-- the main file
package Utility with SPARK_Mode is
Max_Line_Length : constant Natural := 2048;
Put_Length : constant Natural := 3;
Get_Rem_Pin_Length : constant Natural := 2;
Max_Command_Length : constant Natural := 3;
end Utility;
|
-- SipHash.Discrete
-- Implementing SipHash over a generic (relatively small) discrete type
-- Copyright (c) 2015, James Humphry - see LICENSE file for details
with Interfaces;
use all type Interfaces.Unsigned_64;
function SipHash.Discrete (m : T_Array) return Hash_Type is
subtype T_Array_8 is T_Array(T_Index'First..T_Index'First+7);
T_Offset : constant Integer := T'Pos(T'First);
function T_Array_8_to_U64_LE (S : in T_Array_8) return U64 with Inline;
function T_Array_Tail_to_U64_LE (S : in T_Array)
return U64
with Inline, Pre => (S'Length <= 7 and then S'Length > 0);
function T_Array_8_to_U64_LE (S : in T_Array_8) return U64 is
(U64(T'Pos(S(S'First)) - T_Offset)
or Shift_Left(U64(T'Pos(S(S'First+1)) - T_Offset), 8)
or Shift_Left(U64(T'Pos(S(S'First+2)) - T_Offset), 16)
or Shift_Left(U64(T'Pos(S(S'First+3)) - T_Offset), 24)
or Shift_Left(U64(T'Pos(S(S'First+4)) - T_Offset), 32)
or Shift_Left(U64(T'Pos(S(S'First+5)) - T_Offset), 40)
or Shift_Left(U64(T'Pos(S(S'First+6)) - T_Offset), 48)
or Shift_Left(U64(T'Pos(S(S'First+7)) - T_Offset), 56));
function T_Array_Tail_to_U64_LE (S : in T_Array)
return U64 is
R : U64 := 0;
Shift : Natural := 0;
T_I : T;
begin
for I in 0..S'Length-1 loop
pragma Loop_Invariant (Shift = I * 8);
T_I := S(S'First + T_Index'Base(I));
R := R or Shift_Left(U64(T'Pos(T_I) - T_Offset), Shift);
Shift := Shift + 8;
end loop;
return R;
end T_Array_Tail_to_U64_LE;
m_pos : T_Index'Base := 0;
m_i : U64;
v : SipHash_State := Get_Initial_State;
w : constant Natural := (m'Length / 8) + 1;
begin
-- This compile-time check is useful for GNAT but in GNATprove it currently
-- just generates a warning that it can not yet prove them correct.
pragma Warnings (GNATprove, Off, "Compile_Time_Error");
pragma Compile_Time_Error ((T'Size > 8),
"SipHash.Discrete only works for discrete " &
"types which fit into one byte.");
pragma Warnings (GNATprove, On, "Compile_Time_Error");
for I in 1..w-1 loop
pragma Loop_Invariant (m_pos = T_Index'Base(I - 1) * 8);
m_i := T_Array_8_to_U64_LE(m(m'First + m_pos..m'First + m_pos + 7));
v(3) := v(3) xor m_i;
for J in 1..c_rounds loop
Sip_Round(v);
end loop;
v(0) := v(0) xor m_i;
m_pos := m_pos + 8;
end loop;
if m_pos < m'Length then
m_i := T_Array_Tail_to_U64_LE(m(m'First + m_pos .. m'Last));
else
m_i := 0;
end if;
m_i := m_i or Shift_Left(U64(m'Length mod 256), 56);
v(3) := v(3) xor m_i;
for J in 1..c_rounds loop
Sip_Round(v);
end loop;
v(0) := v(0) xor m_i;
return Hash_Type'Mod(Sip_Finalization(v));
end SipHash.Discrete;
|
------------------------------------------------------------------------------
-- Copyright (c) 2014-2015, 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. --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- IMPLEMENTATION NOTES --
-- Counter is a "simple" protected holding a natural value that can be --
-- incremented, and for which a given threshold can be waited. --
-- It should be free of race conditions. --
-- The general architecture of Counter can be explained by considering two --
-- states: a long-lived "base" state, when `Release_Block` queue is empty, --
-- and a short-lived "pulsing" state, when `Release_Block` holds a task in --
-- its queue. --
-- In base state, waiting tasks call `Wait_Version`, which either exists --
-- immediately or requeues them in `Block_Until_Increment` where they stay --
-- blocked until entering the pulsing state. --
-- In pulsing state, public entries are blocked, and all tasks in --
-- `Block_Until_Increment` queue are requeued in `Wait_Version`. When this --
-- is done, pulsing state ends. --
-- Immediately after coming back to base state, waiting tasks execute --
-- `Wait_Version`, which unlocks them or requeues them again in --
-- `Block_Until_Increment`. --
-- Note that right after coming back to base state, there might be both --
-- waiting tasks queued on `Wait_Version` and updating tasks queued on --
-- `Increment`. The order in which they are serviced should be semantically --
-- equivalent, but servicing `Increment` first lowers the number of --
-- requeues and should therefore be a bit more efficient. --
------------------------------------------------------------------------------
with Ada.Calendar.Formatting;
with Ada.Text_IO;
with Natools.Web.Exchanges;
with Natools.Web.Sites.Test_Updates;
with Syslog;
package body Common is
protected body Counter is
function Get_Value return Natural is
begin
return Value;
end Get_Value;
entry Wait_Version (Minimum : in Natural)
when Release_Block'Count = 0 and then Increment'Count = 0 is
begin
if Minimum > Value then
requeue Block_Until_Increment;
end if;
end Wait_Version;
entry Increment when Release_Block'Count = 0 is
begin
Value := Value + 1;
requeue Release_Block;
end Increment;
entry Block_Until_Increment (Minimum : in Natural)
when Release_Block'Count > 0 is
begin
requeue Wait_Version;
end Block_Until_Increment;
entry Release_Block when Block_Until_Increment'Count = 0 is
begin
null;
end Release_Block;
end Counter;
overriding procedure Queue
(Object : in out Holder;
Update : in Natools.Web.Sites.Updates.Site_Update'Class)
is
package Holders renames Natools.Web.Sites.Holders;
begin
Holders.Queue (Holders.Holder (Object), Update);
Holders.Queue (Holders.Holder (Object), Increment_Count'(null record));
end Queue;
overriding procedure Load
(Self : in out Holder;
File_Name : in String)
is
package Holders renames Natools.Web.Sites.Holders;
begin
Holders.Load (Holders.Holder (Self), File_Name);
Holders.Queue
(Holders.Holder (Self),
Natools.Web.Sites.Test_Updates.Load_Date_Override'
(New_Date => Ada.Calendar.Formatting.Time_Of
(1980, 1, 1, 10, 30, 42)));
end Load;
not overriding procedure Purge (Self : in out Holder) is
package Holders renames Natools.Web.Sites.Holders;
Update : Natools.Web.Sites.Updates.Expiration_Purger;
begin
Holders.Queue (Holders.Holder (Self), Update);
end Purge;
overriding procedure Update
(Self : in Increment_Count;
Object : in out Natools.Web.Sites.Site)
is
pragma Unreferenced (Self, Object);
begin
Counter.Increment;
end Update;
function Respond (Request : AWS.Status.Data) return AWS.Response.Data is
Aliased_Request : aliased constant AWS.Status.Data := Request;
Exchange : aliased Natools.Web.Exchanges.Exchange
(Aliased_Request'Access);
begin
Site.Respond (Exchange);
return Natools.Web.Exchanges.Response (Exchange);
end Respond;
procedure Text_IO_Log
(Severity : in Natools.Web.Severities.Code;
Message : in String) is
begin
Ada.Text_IO.Put_Line
('[' & Natools.Web.Severities.Code'Image (Severity) & "] "
& Message);
end Text_IO_Log;
Severity_Table : constant array (Natools.Web.Severities.Code)
of Syslog.Severities.Code
:= (Natools.Web.Severities.Critical => Syslog.Severities.Critical,
Natools.Web.Severities.Error => Syslog.Severities.Error,
Natools.Web.Severities.Warning => Syslog.Severities.Warning,
Natools.Web.Severities.Info => Syslog.Severities.Informational);
procedure Syslog_Log
(Severity : in Natools.Web.Severities.Code;
Message : in String) is
begin
Syslog.Log (Severity_Table (Severity), Message);
end Syslog_Log;
end Common;
|
pragma SPARK_Mode;
with Types; use Types;
-- These are visible to the spec for SPARK Globals
with Geo_Filter;
-- with Pwm;
with Zumo_LED;
with Zumo_LSM303;
with Zumo_L3gd20h;
with Zumo_Motion;
with Zumo_Motors;
with Zumo_Pushbutton;
with Zumo_QTR;
with Wire;
with Line_Finder;
-- @summary
-- The main entry point to the application
--
-- @description
-- This is the main entry point to the application. The Setup and Workloop
-- functions are called from the Arduino sketch
--
package SPARKZumo is
-- True if we have called all necessary inits
Initd : Boolean := False;
-- The mode to use to read the IR sensors
ReadMode : constant Sensor_Read_Mode := Emitters_On;
-- A quick utility test to work with the RISC board
procedure RISC_Test;
-- The main workloop of the application. This is called from the loop
-- function of the Arduino sketch
procedure WorkLoop
with Global => (Proof_In => (Initd,
Zumo_LED.Initd,
Zumo_Motors.Initd,
Zumo_QTR.Initd),
Input => (Zumo_Motors.FlipLeft,
Zumo_Motors.FlipRight,
Zumo_QTR.Calibrated_On,
Zumo_QTR.Calibrated_Off),
In_Out => (Line_Finder.BotState,
Line_Finder.Fast_Speed,
Line_Finder.Slow_Speed,
Zumo_QTR.Cal_Vals_On,
Zumo_QTR.Cal_Vals_Off,
Geo_Filter.Window,
Geo_Filter.Window_Index)),
Pre => (Initd and
Zumo_LED.Initd and
Zumo_Motors.Initd and
Zumo_QTR.Initd);
-- This setup procedure is called from the setup function in the Arduino
-- sketch
procedure Setup
with Pre => (not Initd and
not Zumo_LED.Initd and
not Zumo_Pushbutton.Initd and
not Zumo_Motors.Initd and
not Zumo_QTR.Initd and
not Zumo_Motion.Initd),
Post => (Initd and
Zumo_LED.Initd and
Zumo_Pushbutton.Initd and
Zumo_Motors.Initd and
Zumo_QTR.Initd and
Zumo_Motion.Initd);
private
-- The actual calibration sequence to run. This called calibration many
-- times while moving the robot around. The robot should be place around
-- a line so that it can calibrate on what is a line and what isnt.
procedure Calibration_Sequence
with Global => (Proof_In => (Initd,
Zumo_Motors.Initd,
Zumo_QTR.Initd),
Input => (Zumo_Motors.FlipLeft,
Zumo_Motors.FlipRight),
Output => (Zumo_QTR.Calibrated_On,
Zumo_QTR.Calibrated_Off),
In_Out => (Zumo_QTR.Cal_Vals_On,
Zumo_QTR.Cal_Vals_Off)),
Pre => (Initd and
Zumo_Motors.Initd and
Zumo_QTR.Initd);
-- This handles init'ing everything that needs to be init'd in the app
procedure Inits
with Global => (Input => (Wire.Transmission_Status),
-- Output => (Pwm.Register_State),
In_Out => (Initd,
Zumo_LED.Initd,
Zumo_LSM303.Initd,
Zumo_L3gd20h.Initd,
Zumo_Motion.Initd,
Zumo_Motors.Initd,
Zumo_Pushbutton.Initd,
Zumo_QTR.Initd)),
Pre => (not Initd and
not Zumo_LED.Initd and
not Zumo_Pushbutton.Initd and
not Zumo_Motors.Initd and
not Zumo_QTR.Initd and
not Zumo_Motion.Initd),
Post => (Initd and
Zumo_LED.Initd and
Zumo_Pushbutton.Initd and
Zumo_Motors.Initd and
Zumo_QTR.Initd and
Zumo_Motion.Initd);
-- This is the exception handler that ends in a infinite loop. This is
-- called from the Ardunio sketch when an exception is thrown.
procedure Exception_Handler
with Pre => (Zumo_LED.Initd and Zumo_Motors.Initd);
end SPARKZumo;
|
-----------------------------------------------------------------------
-- Copyright 2021 Lev Kujawski --
-- --
-- This file is part of B2SSUM. --
-- --
-- B2SSUM 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. --
-- --
-- B2SSUM 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 B2SSUM. --
-- If not, see <https://www.gnu.org/licenses/>. --
-- --
-- SPDX-License-Identifier: GPL-3.0-or-later --
-- --
-- File: b2ssum.adb (Ada Subprogram Body) --
-- Language: Ada (1995) [1] --
-- Author: Lev Kujawski --
-- Description: BLAKE2s [2] file hash utility --
-- --
-- References: --
-- [1] Information technology - Programming languages - Ada, --
-- ISO/IEC 8652:1995(E), 15 Feb. 1995. --
-- [2] M-J. Saarinen and J-P. Aumasson, "The BLAKE2 Cryptographic --
-- Hash and Message Authentication Code (MAC)", RFC 7693, --
-- Nov. 2015. --
-----------------------------------------------------------------------
-- NOTE: Unlike the rest of the BLAKE2s for Ada package, B2SSUM is --
-- written in non-SPARK Ada (1995) so that streaming I/O may --
-- be utilized. --
--! rule off Exception_Rule
with Ada.Characters.Handling;
with Ada.Command_Line;
with Ada.Streams;
use type Ada.Streams.Stream_Element_Offset;
with Ada.Streams.Stream_IO;
with Ada.Text_IO;
with Ada.Text_IO.Text_Streams;
with Ada.Strings.Unbounded;
with BLAKE2S;
use type BLAKE2S.Digest_T;
-- Quash false positive from AdaControl:
--! rule off Use_Rule
use type BLAKE2S.Status_T;
--! rule on Use_Rule
with Octets;
use type Octets.T;
with Octet_Arrays;
procedure B2SSUM is
package ACH renames Ada.Characters.Handling;
package ACL renames Ada.Command_Line;
package ATI renames Ada.Text_IO;
package ATS renames Ada.Text_IO.Text_Streams;
package AST renames Ada.Streams;
package ASI renames Ada.Streams.Stream_IO;
package UST renames Ada.Strings.Unbounded;
subtype Hex_Index_T is Positive range 1 .. 2;
subtype Hex_T is String (Hex_Index_T);
subtype Hex_Digit_T is Natural range 0 .. 15;
function Character_To_Hex_Digit
(Hex_Character : in Character)
return Hex_Digit_T;
procedure Hash_File
(File_Name : in String);
procedure Hash_Files;
function Hex
(Value : in Octets.T)
return Hex_T;
function Hex_Digit_To_Character
(Hex_Digit : in Hex_Digit_T)
return Character;
procedure Verify_Lists;
Buffer_Octets : constant := 16384;
Buffer_Bits : constant := Buffer_Octets * Octets.Bits;
subtype Buffer_Index_T is Positive range 1 .. Buffer_Octets;
subtype SEA_Buffer_Index_T is AST.Stream_Element_Offset
range 1 .. Buffer_Octets;
subtype Buffer_T is Octet_Arrays.T (Buffer_Index_T);
subtype SEA_Buffer_T is
AST.Stream_Element_Array (SEA_Buffer_Index_T);
Buffer : SEA_Buffer_T;
for Buffer'Size use Buffer_Bits;
View : Buffer_T;
for View'Address use Buffer'Address;
for View'Size use Buffer_Bits;
Invalid_Hash_List : exception;
Digest : BLAKE2S.Digest_Default_T;
function Character_To_Hex_Digit
(Hex_Character : in Character)
return Hex_Digit_T
is
Normal : constant Character := ACH.To_Upper (Hex_Character);
Result : Hex_Digit_T;
begin
case Normal is
when '0' =>
Result := 0;
when '1' =>
Result := 1;
when '2' =>
Result := 2;
when '3' =>
Result := 3;
when '4' =>
Result := 4;
when '5' =>
Result := 5;
when '6' =>
Result := 6;
when '7' =>
Result := 7;
when '8' =>
Result := 8;
when '9' =>
Result := 9;
when 'A' =>
Result := 10;
when 'B' =>
Result := 11;
when 'C' =>
Result := 12;
when 'D' =>
Result := 13;
when 'E' =>
Result := 14;
when 'F' =>
Result := 15;
when others =>
raise Constraint_Error;
end case;
return Result;
end Character_To_Hex_Digit;
procedure Hash_File
(File_Name : in String)
is
procedure Hash_Stream;
File : ASI.File_Type;
Stream : ASI.Stream_Access;
First : constant Positive := Positive (Buffer'First);
procedure Hash_Stream
is
Context : BLAKE2S.T;
Last : AST.Stream_Element_Offset;
begin
Context := BLAKE2S.Initial (BLAKE2S.Digest_Length_Default);
loop
AST.Read (Stream.all, Buffer, Last);
BLAKE2S.Incorporate_Flex
(Context, View, First, Natural (Last));
exit when Last < Buffer'Last;
end loop;
BLAKE2S.Finalize (Context, Digest);
end Hash_Stream;
begin -- Hash_File
if File_Name = "-" then
Stream := ASI.Stream_Access (ATS.Stream (ATI.Standard_Input));
Hash_Stream;
else
ASI.Open (File, ASI.In_File, File_Name);
Stream := ASI.Stream (File);
Hash_Stream;
ASI.Close (File);
end if;
end Hash_File;
procedure Hash_Files
is
procedure Print_Hash
(File_Name : in String);
procedure Print_Hash
(File_Name : in String)
is
begin
for J in Digest'Range loop
ATI.Put (Item => Hex (Digest (J)));
end loop;
ATI.Put (" ");
ATI.Put (File_Name);
ATI.New_Line;
end Print_Hash;
begin -- Hash_Files
for I in Positive range 1 .. ACL.Argument_Count loop
Hash_File (ACL.Argument (I));
Print_Hash (ACL.Argument (I));
end loop;
end Hash_Files;
function Hex
(Value : in Octets.T)
return Hex_T
is
begin
return
Hex_T'
(1 => Hex_Digit_To_Character (Hex_Digit_T (Value / 16)),
2 => Hex_Digit_To_Character (Hex_Digit_T (Value mod 16)));
end Hex;
function Hex_Digit_To_Character
(Hex_Digit : in Hex_Digit_T)
return Character
is
Result : Character;
begin
case Hex_Digit is
when 0 =>
Result := '0';
when 1 =>
Result := '1';
when 2 =>
Result := '2';
when 3 =>
Result := '3';
when 4 =>
Result := '4';
when 5 =>
Result := '5';
when 6 =>
Result := '6';
when 7 =>
Result := '7';
when 8 =>
Result := '8';
when 9 =>
Result := '9';
when 10 =>
Result := 'a';
when 11 =>
Result := 'b';
when 12 =>
Result := 'c';
when 13 =>
Result := 'd';
when 14 =>
Result := 'e';
when 15 =>
Result := 'f';
end case;
return Result;
end Hex_Digit_To_Character;
procedure Verify_Lists
is
procedure Verify_List;
List_File : ATI.File_Type;
procedure Verify_List
is
Hash : BLAKE2S.Digest_Default_T;
Hex_1 : Character;
Hex_2 : Character;
begin
while not ATI.End_Of_Line loop
for I in Positive range Hash'Range loop
ATI.Get (Hex_1);
ATI.Get (Hex_2);
if not ACH.Is_Hexadecimal_Digit (Hex_1)
or else not ACH.Is_Hexadecimal_Digit (Hex_2)
then
raise Invalid_Hash_List;
end if;
Hash (I) :=
Octets.T (Character_To_Hex_Digit (Hex_1)) * 16
+ Octets.T (Character_To_Hex_Digit (Hex_2));
end loop;
ATI.Get (Hex_1);
ATI.Get (Hex_2);
if Hex_1 /= ' ' or else Hex_2 /= ' ' then
raise Invalid_Hash_List;
end if;
declare
subtype Partial_Index_T is Positive range 1 .. 256;
Unbounded_File_Name : UST.Unbounded_String :=
UST.Null_Unbounded_String;
Partial : String (Partial_Index_T);
Last : Natural;
begin
loop
ATI.Get_Line (Partial, Last);
UST.Append
(Unbounded_File_Name, Partial (1 .. Last));
exit when Last < Partial'Last;
end loop;
declare
File_Name : constant String :=
UST.To_String (Unbounded_File_Name);
begin
ATI.Put (File_Name & ": ");
Hash_File (File_Name);
if Digest = Hash then
ATI.Put_Line ("OK");
else
ATI.Put_Line ("FAILED");
end if;
end;
end;
end loop;
end Verify_List;
begin -- Verify_Lists
for I in Positive range 2 .. ACL.Argument_Count loop
declare
begin
if ACL.Argument (I) = "-" then
Verify_List;
else
ATI.Open (List_File, ATI.In_File, ACL.Argument (I));
ATI.Set_Input (List_File);
Verify_List;
ATI.Set_Input (ATI.Standard_Input);
ATI.Close (List_File);
end if;
exception
when Invalid_Hash_List =>
ATI.Put_Line
("Error on line "
& ATI.Positive_Count'Image (ATI.Line)
& ", skipping invalid hash list: "
& ACL.Argument (I));
end;
end loop;
end Verify_Lists;
begin -- B2SSum
pragma Assert (BLAKE2S.Self_Test = BLAKE2S.Success);
if ACL.Argument_Count = 0 then
-- Print usage
ATI.Put_Line
("Usage: " & Ada.Command_Line.Command_Name
& " [OPTION]... [FILE]...");
elsif ACL.Argument (1) = "-c" then
Verify_Lists;
else
Hash_Files;
end if;
end B2SSUM;
|
-- Generated at 2017-03-27 17:51:44 +0000 by Natools.Static_Hash_Maps
-- from src/natools-web-acl-maps.sx
with Natools.Static_Maps.Web.ACL.Commands;
package body Natools.Static_Maps.Web.ACL is
function To_Command (Key : String) return Command is
N : constant Natural
:= Natools.Static_Maps.Web.ACL.Commands.Hash (Key);
begin
if Map_1_Keys (N).all = Key then
return Map_1_Elements (N);
else
return Unknown_Command;
end if;
end To_Command;
end Natools.Static_Maps.Web.ACL;
|
pragma License (Unrestricted);
-- implementation unit specialized for Windows
with Ada.IO_Exceptions;
with System.Storage_Elements;
package System.Random_Initiators is
pragma Preelaborate;
procedure Get (
Item : Address;
Size : Storage_Elements.Storage_Count);
-- Exceptions
Use_Error : exception
renames Ada.IO_Exceptions.Use_Error;
end System.Random_Initiators;
|
with
ada.Streams.stream_IO;
with mmi.Forge,
mmi.Window.lumen,
mmi.Applet.gui_world,
mmi.Camera;
with mmi.Sprite,
openGL.Model.box.lit_colored_textured,
openGL.Model.sphere;
with opengl.Palette,
float_Math,
ada.Calendar;
procedure launch_add_rid_sprite_Test
--
-- drops a ball onto a box terrain.
--
--
is
use mmi.Applet, --mmi.box_Model,
openGL, opengl.Palette,
ada.Calendar;
package Math renames float_Math;
use type math.Real;
-- the_Window : mmi.Window.View := mmi.window.sdl.Forge.new_Window ("memory leak Test", 500, 500);
the_Applet : mmi.Applet.gui_world.view := mmi.forge.new_gui_Applet ("memory leak Test", 500, 500); --the_Window);
-- the_box_Model : aliased mmi.box_Model.item
-- := (mmi.Model.item with
-- scale => (10.0, 0.5, 10.0),
-- faces => (front => (colors => (others => (Red, Opaque))),
-- rear => (colors => (others => (Blue, Opaque))),
-- upper => (colors => (others => (Green, Opaque))),
-- lower => (colors => (others => (Yellow, Opaque))),
-- left => (colors => (others => (Cyan, Opaque))),
-- right => (colors => (others => (Magenta, Opaque)))));
the_Box : mmi.Sprite.view
:= mmi.forge.new_box_Sprite (the_Applet.gui_World, mass => 0.0);
-- the_ball_Model : aliased mmi.sphere_Model.item
-- := (mmi.Model.item with
-- scale => (1.0, 1.0, 1.0),
-- Image => mmi.to_Asset ("../assets/balls.tga"));
the_Balls : mmi.Sprite.views (1 .. 1)
:= (others => mmi.forge.new_ball_Sprite (the_Applet.gui_World, mass => 1.0));
next_render_Time : ada.calendar.Time;
begin
the_Applet.gui_Camera.Site_is ((0.0, 5.0, 15.0)); -- Position the camera
the_Applet.enable_simple_Dolly (1); -- Enable user camera control via keyboards
the_Applet.enable_Mouse (detect_Motion => False); -- Enable mouse events.
the_Applet.gui_World.add (the_Box); -- add the ground box
the_Box.Site_is ((0.0, 0.0, 0.0)); --
for Each in the_Balls'range
loop
the_Applet.gui_World.add (the_Balls (Each)); -- add ball
the_Balls (Each).Site_is ((0.0, 10.0, 0.0)); --
end loop;
for Each in 1 .. 100
loop
the_Applet.gui_World.evolve (by => 1.0/60.0); -- evolve the world
the_Applet.freshen; -- handle any new events and update the screen
end loop;
for Each in the_Balls'range
loop
the_Applet.gui_World.rid (the_Balls (Each)); -- rid ball
mmi.Sprite.free (the_Balls (Each));
end loop;
next_render_Time := ada.Calendar.clock;
while the_Applet.is_open
loop
the_Applet.gui_World.evolve (by => 1.0/60.0); -- evolve the world
the_Applet.freshen; -- handle any new events and update the screen
next_render_Time := next_render_Time + 1.0/60.0;
delay until next_render_Time;
end loop;
the_Applet.destroy;
end launch_add_rid_sprite_Test;
|
pragma License (Unrestricted);
-- extended unit
private with Ada.Finalization;
private with System.Native_Directories.Volumes;
package Ada.Directories.Volumes is
-- File system information.
type File_System is limited private;
-- subtype Assigned_File_System is File_System
-- with
-- Dynamic_Predicate => Is_Assigned (Assigned_File_System),
-- Predicate_Failure => raise Status_Error;
function Is_Assigned (FS : File_System) return Boolean;
function Where (Name : String) return File_System;
pragma Inline (Where); -- renamed
function Size (
FS : File_System) -- Assigned_File_System
return File_Size;
function Free_Space (
FS : File_System) -- Assigned_File_System
return File_Size;
function Owner (
FS : File_System) -- Assigned_File_System
return String;
function Format_Name (
FS : File_System) -- Assigned_File_System
return String;
function Directory (
FS : File_System) -- Assigned_File_System
return String; -- mounted to
function Device (
FS : File_System) -- Assigned_File_System
return String; -- mounted from
function Case_Preserving (
FS : File_System) -- Assigned_File_System
return Boolean;
function Case_Sensitive (
FS : File_System) -- Assigned_File_System
return Boolean;
function Is_HFS (
FS : File_System) -- Assigned_File_System
return Boolean;
type File_System_Id is private;
function Identity (
FS : File_System) -- Assigned_File_System
return File_System_Id;
private
package Controlled is
type File_System is limited private;
function Reference (Object : Volumes.File_System)
return not null
access System.Native_Directories.Volumes.File_System;
pragma Inline (Reference);
function Where (Name : String) return Volumes.File_System;
-- [gcc-7] strange error if this function is placed outside of
-- the package Controlled, and Disable_Controlled => True
private
type File_System is
limited new Finalization.Limited_Controlled with
record
Data : aliased System.Native_Directories.Volumes.File_System :=
(others => <>);
end record
with
Disable_Controlled =>
System.Native_Directories.Volumes.Disable_Controlled;
overriding procedure Finalize (Object : in out File_System);
end Controlled;
type File_System is new Controlled.File_System;
function Where (Name : String) return File_System
renames Controlled.Where;
type File_System_Id is new System.Native_Directories.Volumes.File_System_Id;
end Ada.Directories.Volumes;
|
pragma Ada_2012;
pragma Warnings (Off, "no entities");
with Ada.Text_Io; use Ada.Text_Io;
with Ada.Exceptions;
with Protypo.Tokens; use Protypo.Tokens;
with Readable_Sequences.Generic_Sequences; use Readable_Sequences;
package body Protypo.Parsing is
use Ada.Strings.Unbounded;
package Statement_Sequences is
new Generic_Sequences (Element_Type => Code_Trees.Parsed_Code,
Element_Array => Code_Trees.Tree_Array);
type Token_Mask is array (Token_Class) of Boolean;
-----------
-- Image --
-----------
function Image (X : Token_Mask) return String is
Result : Unbounded_String;
begin
for Tk in X'Range loop
if X (Tk) then
if Result = Null_Unbounded_String then
Result := To_Unbounded_String (Tk'Image);
else
Result := Result & " or " & Tk'Image;
end if;
end if;
end loop;
if Result = Null_Unbounded_String then
return "(nothing)";
else
return To_String (Result);
end if;
end Image;
procedure Unexpected_Token (Found : Token_Class;
Expected : Token_Mask;
Position : Token_Position)
is
begin
raise Parsing_Error
with "Unexpected "
& Found'Image & " instead of " & Image (Expected)
& " at " & Image (Position);
end Unexpected_Token;
procedure Unexpected_Token (Found : Token_Class;
Expected : Token_Class;
Position : Token_Position)
is
begin
raise Parsing_Error
with "Unexpected "
& Found'Image & " instead of " & Expected'Image
& " at " & Image (Position);
end Unexpected_Token;
------------
-- Expect --
------------
procedure Expect (Input : in Scanning.Token_List;
Expected : Token_Mask)
is
begin
if not Expected (Class (Input.Read)) then
Unexpected_Token (Class (Input.Read), Expected, Position (Input.Read));
end if;
end Expect;
------------
-- Expect --
------------
procedure Expect (Input : in Scanning.Token_List;
Expected : Token_Class)
is
Mask : Token_Mask := (others => False);
begin
Mask (Expected) := True;
Expect (Input, Mask);
end Expect;
pragma Unreferenced (Expect);
------------
-- Expect --
------------
procedure Expect_And_Eat (Input : in out Scanning.Token_List;
Expected : Token_Class;
Context : String := "")
is
begin
if Class (Input.Read) /= Expected then
raise Parsing_Error
with "Expecting "
& Expected'Image
& " found "
& Class (Input.Read)'Image
& " at " & Image (Position (Input.Read))
& (if Context /= "" then " (" & Context & ")" else "");
end if;
Input.Next;
end Expect_And_Eat;
function Parse_Expression_List
(Input : in out Scanning.Token_List)
return Statement_Sequences.Sequence;
-------------------
-- Parse_Primary --
-------------------
function Parse_Name
(Input : in out Scanning.Token_List)
return Code_Trees.Parsed_Code
is
Result : Code_Trees.Parsed_Code := Code_Trees.Empty_Tree;
procedure Parse_Indexed_Name is
begin
Expect_And_Eat (Input, Open_Parenthesis);
declare
Indexes : constant Statement_Sequences.Sequence :=
Parse_Expression_List (Input);
begin
Result := Code_Trees.Indexed_Name (Result, Indexes.Dump);
end;
Expect_And_Eat (Input, Close_Parenthesis);
end Parse_Indexed_Name;
procedure Parse_Selector is
begin
Expect_And_Eat (Input, Dot);
if Class (Input.Read) /= Identifier then
raise Parsing_Error
with "Unexpected token "
& Class (Input.Read)'Image
& " in FIELD part"
& " at " & Image (Position (Input.Read)) ;
end if;
Result := Code_Trees.Selector (Result, Value (Input.Next));
end Parse_Selector;
begin
pragma Assert (Class (Input.Read) = Identifier);
Result := Code_Trees.Identifier (Value (Input.Next));
loop
if Class (Input.Read) = Open_Parenthesis then
Parse_Indexed_Name;
end if;
if Class (Input.Read) /= Dot then
exit;
else
Parse_Selector;
end if;
end loop;
return Result;
end Parse_Name;
-------------------
-- Parse_Primary --
-------------------
function Parse_Primary
(Input : in out Scanning.Token_List)
return Code_Trees.Parsed_Code
is
subtype Primary_Head is Token_Class
with Static_Predicate =>
Primary_Head in Open_Parenthesis | Identifier | Text | Int | Real | Kw_Capture;
Result : Code_Trees.Parsed_Code;
begin
-- Put_Line (">> parse primary");
if not (Class (Input.Read) in Primary_Head) then
raise Parsing_Error
with "Unexpected token "
& Class (Input.Read)'Image
& " in primary expression"
& " at " & Image (Position (Input.Read));
end if;
-- Put_Line (Image (Input.Read));
case Primary_Head (Class (Input.Read)) is
when Open_Parenthesis =>
Input.Next;
Result := Parse_Expression (Input);
Expect_And_Eat (Input, Close_Parenthesis, "PRIMARY");
when Identifier =>
Result := Parse_Name (Input);
when Text =>
Result := Code_Trees.String_Constant (Value (Input.Next));
when Int =>
Result := Code_Trees.Integer_Constant (Value (Input.Next));
when Real =>
Result := Code_Trees.Float_Constant (Value (Input.Next));
when Kw_Capture =>
Input.Next;
Expect_And_Eat (Input, Open_Parenthesis, "PRIMARY 2");
if Class (Input.Read) /= Identifier then
raise Parsing_Error with "Expected identifier inside CAPTURE call at " & Image (Position (Input.Read));
end if;
declare
Here : constant Tokens.Token_Position := Tokens.Position (Input.Read);
Name : constant Unbounded_Id :=
Unbounded_Id'(To_Unbounded_String (Value (Input.Next)));
begin
Expect_And_Eat (Input, Open_Parenthesis, "PRIMARY 3");
declare
Parameters : constant Statement_Sequences.Sequence :=
Parse_Expression_List (Input);
begin
Result := Code_Trees.Capture (Name, Parameters.Dump, Here);
end;
-- The close parenthesis of the called function
Expect_And_Eat (Input, Close_Parenthesis, "PRIMARY 4");
-- Close of CAPTURE
Expect_And_Eat (Input, Close_Parenthesis, "PRIMARY 5");
-- Put_Line (">> done capture");
end;
end case;
return Result;
end Parse_Primary;
------------------
-- Parse_factor --
------------------
function Parse_Factor
(Input : in out Scanning.Token_List)
return Code_Trees.Parsed_Code
is
Result : Code_Trees.Parsed_Code;
Op : Unary_Operator;
Has_Unary : Boolean;
begin
if Class (Input.Read) in Unary_Operator then
Op := Class (Input.Next);
Has_Unary := True;
end if;
Result := Parse_Primary (Input);
if not Has_Unary then
return Result;
else
return Code_Trees.Unary_Operation (Result, Op);
end if;
end Parse_Factor;
----------------
-- Parse_Term --
----------------
function Parse_Term
(Input : in out Scanning.Token_List)
return Code_Trees.Parsed_Code
is
Result : Code_Trees.Parsed_Code;
Op : Binary_Operator;
begin
Result := Parse_Factor (Input);
while Class (Input.Read) in Mult | Div | Kw_Mod loop
Op := Class (Input.Next);
Result := Code_Trees.Binary_Operation
(Left => Result,
Right => Parse_Factor (Input),
Operation => Op);
end loop;
return Result;
end Parse_Term;
-----------------------
-- Parse_Simple_Expr --
-----------------------
function Parse_Simple_Expr
(Input : in out Scanning.Token_List)
return Code_Trees.Parsed_Code
is
Result : Code_Trees.Parsed_Code;
Op : Binary_Operator;
begin
Result := Parse_Term (Input);
while Class (Input.Read) in Plus | Minus loop
Op := Class (Input.Next);
Result := Code_Trees.Binary_Operation (Left => Result,
Right => Parse_Term (Input),
Operation => Op);
end loop;
return Result;
end Parse_Simple_Expr;
--------------------
-- Parse_relation --
--------------------
function Parse_Relation
(Input : in out Scanning.Token_List)
return Code_Trees.Parsed_Code
is
Result : Code_Trees.Parsed_Code;
Op : Comp_Operator;
begin
Result := Parse_Simple_Expr (Input);
if Class (Input.Read) in Comp_Operator then
Op := Class (Input.Next);
Result := Code_Trees.Binary_Operation
(Left => Result,
Right => Parse_Simple_Expr (Input),
Operation => Op);
end if;
return Result;
end Parse_Relation;
----------------------
-- Parse_Expression --
----------------------
function Parse_Expression
(Input : in out Scanning.Token_List)
return Code_Trees.Parsed_Code
is
Result : Code_Trees.Parsed_Code;
Op : Logical_Operator;
Here : constant Tokens.Token_Position := Tokens.Position (Input.Read);
begin
-- Put_Line (">> Parse expression");
Result := Parse_Relation (Input);
if Class (Input.Read) in Logical_Operator then
Op := Class (Input.Read);
while Class (Input.Read) = Op loop
Input.Next;
Result := Code_Trees.Binary_Operation (Left => Result,
Right => Parse_Relation (Input),
Operation => Op,
Position => Here);
end loop;
end if;
return Result;
end Parse_Expression;
---------------------------
-- Parse_Expression_List --
---------------------------
function Parse_Expression_List
(Input : in out Scanning.Token_List)
return Statement_Sequences.Sequence
is
use Statement_Sequences;
begin
return Result : Sequence := Empty_Sequence do
Result.Append (Parse_Expression (Input));
while Class (Input.Read) = Comma loop
Input.Next;
Result.Append (Parse_Expression (Input));
end loop;
end return;
end Parse_Expression_List;
---------------------
-- Parse_name_List --
---------------------
function Parse_Name_List
(Input : in out Scanning.Token_List) return Statement_Sequences.Sequence
is
use Statement_Sequences;
begin
return Result : Sequence := Empty_Sequence do
Result.Append (Parse_Name (Input));
while Class (Input.Read) = Comma loop
Input.Next;
Result.Append (Parse_Name (Input));
end loop;
end return;
end Parse_Name_List;
------------------
-- Parse_Assign --
------------------
function Parse_Assign (Input : in out Scanning.Token_List)
return Code_Trees.Parsed_Code
is
Names : constant Statement_Sequences.Sequence := Parse_Name_List (Input);
begin
Expect_And_Eat (Input, Assign, "ASSIGN 1");
declare
Values : constant Statement_Sequences.Sequence :=
Parse_Expression_List (Input);
begin
Expect_And_Eat (Input, End_Of_Statement, "ASSIGN 2");
return Code_Trees.Assignment (Lhs => Names.Dump,
Value => Values.Dump);
end;
end Parse_Assign;
-----------------------
-- Parse_Conditional --
-----------------------
function Parse_Conditional (Input : in out Scanning.Token_List)
return Code_Trees.Parsed_Code
is
Branches : Statement_Sequences.Sequence := Statement_Sequences.Empty_Sequence;
Conditions : Statement_Sequences.Sequence := Statement_Sequences.Empty_Sequence;
Else_Branch : Code_Trees.Parsed_Code := Code_Trees.Empty_Tree;
begin
Expect_And_Eat (Input, Kw_If);
Conditions.Append (Parse_Expression (Input));
Expect_And_Eat (Input, Kw_Then);
Branches.Append (Parse_Statement_Sequence (Input));
while Class (Input.Read) = Kw_Elsif loop
Input.Next;
Conditions.Append (Parse_Expression (Input));
Expect_And_Eat (Input, Kw_Then);
Branches.Append (Parse_Statement_Sequence (Input));
end loop;
if Class (Input.Read) = Kw_Else then
Input.Next;
Else_Branch := Parse_Statement_Sequence (Input);
end if;
Expect_And_Eat (Input, Kw_End);
Expect_And_Eat (Input, Kw_If);
Expect_And_Eat (Input, End_Of_Statement);
return Code_Trees.If_Then_Else (Conditions => Conditions.Dump,
Then_Branches => Branches.Dump,
Else_Branch => Else_Branch);
end Parse_Conditional;
----------------
-- Parse_Exit --
----------------
function Parse_Exit (Input : in out Scanning.Token_List)
return Code_Trees.Parsed_Code
is
begin
Expect_And_Eat (Input, Kw_Exit);
declare
Label : constant String := (if Class (Input.Read) = Identifier then
Value (Input.Next)
else
"");
begin
Expect_And_Eat (Input, End_Of_Statement);
return Code_Trees.Loop_Exit (Label);
end;
end Parse_Exit;
----------------
-- Parse_Loop --
----------------
function Parse_Loop (Input : in out Scanning.Token_List;
Label : String := "")
return Code_Trees.Parsed_Code
is
Loop_Body : Code_Trees.Parsed_Code;
begin
Expect_And_Eat (Input, Kw_Loop);
-- Put_Line ("In parse loop" & Image (Input.Read));
Loop_Body := Parse_Statement_Sequence (Input);
Expect_And_Eat (Input, Kw_End);
Expect_And_Eat (Input, Kw_Loop);
Expect_And_Eat (Input, End_Of_Statement);
return Code_Trees.Basic_Loop (Loop_Body, Label);
end Parse_Loop;
--------------------
-- Parse_For_Loop --
--------------------
function Parse_For_Loop (Input : in out Scanning.Token_List;
Label : String := "")
return Code_Trees.Parsed_Code
is
Iterator : Code_Trees.Parsed_Code;
Loop_Body : Code_Trees.Parsed_Code;
Here : constant Tokens.Token_Position := Tokens.Position (Input.Read);
begin
Expect_And_Eat (Input, Kw_For);
if Class (Input.Read) /= Identifier then
raise Parsing_Error
with "Expecting FOR variable, found "
& Class (Input.Read)'Image
& " at " & Image (Here);
end if;
declare
Variable : constant String := Value (Input.Next);
begin
Expect_And_Eat (Input, Kw_In);
Iterator := Parse_Expression (Input);
Loop_Body := Parse_Loop (Input, Label);
return Code_Trees.For_Loop (Variable => Variable,
Iterator => Iterator,
Loop_Body => Loop_Body,
Position => Here);
end;
end Parse_For_Loop;
----------------------
-- Parse_While_Loop --
----------------------
function Parse_While_Loop (Input : in out Scanning.Token_List;
Label : String := "")
return Code_Trees.Parsed_Code
is
Condition : Code_Trees.Parsed_Code;
Loop_Body : Code_Trees.Parsed_Code;
Here : constant Tokens.Token_Position := Tokens.Position (Input.Read);
begin
Expect_And_Eat (Input, Kw_While);
Condition := Parse_Expression (Input);
Loop_Body := Parse_Loop (Input, Label);
return Code_Trees.While_Loop (Condition => Condition,
Loop_Body => Loop_Body,
Position => Here);
end Parse_While_Loop;
------------------
-- Parse_Return --
------------------
function Parse_Return (Input : in out Scanning.Token_List)
return Code_Trees.Parsed_Code
is
Here : constant Tokens.Token_Position := Tokens.Position (Input.Read);
begin
Expect_And_Eat (Input, Kw_Return);
declare
Return_List : constant Statement_Sequences.Sequence :=
(if Class (Input.Read) = End_Of_Statement then
Statement_Sequences.Empty_Sequence
else
Parse_Expression_List (Input));
begin
Expect_And_Eat (Input, End_Of_Statement);
return Code_Trees.Return_To_Caller (Return_List.Dump, Here);
end;
end Parse_Return;
------------------------------
-- Parse_Statement_Sequence --
------------------------------
function Parse_Statement_Sequence
(Input : in out Scanning.Token_List)
return Code_Trees.Parsed_Code
is
subtype Labeled_Construct is Unvalued_Token
with
Static_Predicate => Labeled_Construct in Kw_Loop | Kw_While | Kw_For;
function Parse_Labeled_Construct (Input : in out Scanning.Token_List)
return Code_Trees.Parsed_Code
is
Label : constant String := Value (Input.Next);
begin
Expect_And_Eat (Input, Label_Separator);
case Labeled_Construct (Class (Input.Read)) is
when Kw_Loop =>
return Parse_Loop (Input, Label);
when Kw_For =>
return Parse_For_Loop (Input, Label);
when Kw_While =>
return Parse_While_Loop (Input, Label);
end case;
end Parse_Labeled_Construct;
function Parse_Assign_Or_Call (Input : in out Scanning.Token_List)
return Code_Trees.Parsed_Code
with
Pre => Class (Input.Read) = Identifier;
function Parse_Assign_Or_Call (Input : in out Scanning.Token_List)
return Code_Trees.Parsed_Code
is
subtype Id_Follower is Unvalued_Token
with
Static_Predicate =>
Id_Follower in
End_Of_Statement | Assign | Open_Parenthesis | Dot | Comma;
Follower : constant Token_Class := Class (Input.Read (1));
Here : constant Tokens.Token_Position := Tokens.Position (Input.Read);
begin
--
-- Here we are at the beginning of a statement and the current
-- token is an identifier. We can have several cases
--
-- * A procedure call with parameter, e.g., foo(2);
-- * A procedure call without parameter, e.g., foo;
-- * An assignment to a vecto, e.g., foo(2) := 1.3;
-- * Other assignments, i.e., foo.bar := 4; bar := 0;
--
-- It follows that the identifier can be followed by
-- * A semicolon (call, no parameters)
-- * A dot (assignment)
-- * An assignment (assignment)
-- * A parenthesis (call or assignment?)
-- In the last case we need to look after the closed parenthesis
-- in order to decied
--
-- Put_Line ("Assign or call " & Follower'Image & ", " & Image (Input.Read));
if not (Follower in Id_Follower) then
raise Parsing_Error
with "Unexpected token "
& Class (Input.Read)'Image
& " after IDENTIFIER"
& " at " & Image (Here);
end if;
case Id_Follower (Follower) is
when End_Of_Statement =>
declare
Result : constant Code_Trees.Parsed_Code :=
Code_Trees.Procedure_Call (Value (Input.Next));
begin
Expect_And_Eat (Input, End_Of_Statement, "END OF STATEMENT");
return Result;
end;
when Assign | Dot | Comma =>
return Parse_Assign (Input);
when Open_Parenthesis =>
--
-- This is the ambigous case. We use back-track, so we
-- first try the call alternative, if it does not work
-- we backtrack to current position and try assignment
--
Input.Save_Position;
declare
Id : constant String := Value (Input.Read);
begin
Input.Next;
Expect_And_Eat (Input, Open_Parenthesis, "OPEN 1");
declare
Parameters : constant Statement_Sequences.Sequence :=
Parse_Expression_List (Input);
begin
Expect_And_Eat (Input, Close_Parenthesis, "OPEN 2");
case Class (Input.Read) is
when End_Of_Statement | End_Of_Text =>
Input.Clear_Position;
Expect_And_Eat (Input, Class (Input.Read), "OPEN 3");
return Code_Trees.Procedure_Call (Id,
Parameters.Dump,
Here);
when Assign | Dot =>
Input.Restore_Position;
return Parse_Assign (Input);
when others =>
raise Parsing_Error
with "Unexpected token "
& Class (Input.Read)'Image
& " after indexed identifier"
& " at " & Image (Here);
end case;
end;
end;
end case;
end Parse_Assign_Or_Call;
function Parse_Id_List (Input : in out Scanning.Token_List)
return Code_Trees.Parsed_Code
is
In_Optional_Section : Boolean := False;
Default : Statement_Sequences.Sequence :=
Statement_Sequences.Empty_Sequence;
Parameter_Names : Code_Trees.Id_List;
begin
loop
if Class (Input.Read) /= Identifier then
-- Put_Line (">>>" & Class (Input.Read)'Image);
raise Parsing_Error
with "Expected IDENTIFIER in ID list"
& " found " & Class (Input.Read)'Image
& " at " & Image (Position (Input.Read));
end if;
Parameter_Names.Append (Id (Value (Input.Next)));
if Class (Input.Read) = Assign then
Input.Next;
Default.Append (Parse_Expression (Input));
In_Optional_Section := True;
else
Default.Append (Code_Trees.Empty_Tree);
if In_Optional_Section then
raise Parsing_Error
with "Mandatory parameter in optional parameter part"
& " at " & Image (Position (Input.Read));
end if;
end if;
exit when Class (Input.Read) /= End_Of_Statement;
Input.Next;
end loop;
return Code_Trees.Parameter_List (Parameter_Names, Default.Dump);
end Parse_Id_List;
function Parse_Defun (Input : in out Scanning.Token_List)
return Code_Trees.Parsed_Code;
-- with Post => Code_Trees.Class (Parse_Defun'Result) = Code_Trees.Defun;
function Parse_Defun (Input : in out Scanning.Token_List)
return Code_Trees.Parsed_Code
is
Is_Function : constant Boolean :=
(case Class (Input.Read) is
when Kw_Procedure => False,
when Kw_Function => True,
when others => raise Program_Error);
Name : Unbounded_String;
Parameter_Names : Code_Trees.Parsed_Code;
Function_Body : Code_Trees.Parsed_Code;
Here : constant Tokens.Token_Position := Tokens.Position (Input.Read);
begin
Input.Next;
if Class (Input.Read) /= Identifier then
raise Parsing_Error
with "Expected IDENTIFIER in function/procedure definition"
& " found " & Class (Input.Read)'Image
& " at " & Image (Here);
else
Name := To_Unbounded_String (Value (Input.Next));
end if;
if Class (Input.Read) = Open_Parenthesis then
Expect_And_Eat (Input, Open_Parenthesis);
Parameter_Names := Parse_Id_List (Input);
Expect_And_Eat (Input, Close_Parenthesis);
else
Parameter_Names := Code_Trees.Empty_Parameter_List;
end if;
Expect_And_Eat (Input, Kw_Is);
Expect_And_Eat (Input, Kw_Begin);
Function_Body := Parse_Statement_Sequence (Input);
Expect_And_Eat (Input, Kw_End);
if not (Class (Input.Read) = Identifier
and then
Value (Input.Read) = To_String (Name))
then
raise Parsing_Error
with "end " & To_String (Name) & "; expected at " & Image (Here);
else
Input.Next;
end if;
Expect_And_Eat (Input, End_Of_Statement);
return Code_Trees.Definition (Name => To_String (Name),
Parameter_List => Parameter_Names,
Function_Body => Function_Body,
Is_Function => Is_Function,
Position => Here);
end Parse_Defun;
Result : Statement_Sequences.Sequence :=
Statement_Sequences.Empty_Sequence;
Here : constant Token_Position := Position (Input.Read);
begin
-- Scanning.Dump (Input);
-- Put_Line ("We are back!");
loop
-- Put_Line (Image (Input.read));
case Class (Input.Read) is
when Identifier =>
-- Put_Line ("Below identifier");
if Class (Input.Read (1)) = Label_Separator then
if not (Class (Input.Read (2)) in Labeled_Construct) then
raise Constraint_Error;
else
Result.Append (Parse_Labeled_Construct (Input));
end if;
else
Result.Append (Parse_Assign_Or_Call (Input));
end if;
when Kw_If =>
Result.Append (Parse_Conditional (Input));
when Kw_Case =>
raise Program_Error with "Unimplemented";
-- Result.Append (Parse_Case (Input));
when Kw_Procedure | Kw_Function =>
Result.Append (Parse_Defun (Input));
when Kw_For =>
Result.Append (Parse_For_Loop (Input));
when Kw_While =>
Result.Append (Parse_While_Loop (Input));
when Kw_Loop =>
Result.Append (Parse_Loop (Input));
when Kw_Exit =>
Result.Append (Parse_Exit (Input));
when Kw_Return =>
Result.Append (Parse_Return (Input));
when Kw_Else | Kw_Elsif | Kw_End | End_Of_Text =>
exit;
when Int | Text | Plus | Minus |
Mult | Div | Equal | Different |
Less_Than | Greater_Than | Less_Or_Equal |
Greater_Or_Equal | Assign | Dot |
Comma | End_Of_Statement | Close_Parenthesis |
Kw_Then | Kw_And | Kw_Or |
Open_Parenthesis | Label_Separator |
Kw_When | Kw_In | Kw_Of |
Real | Kw_Xor | Kw_Not |
Kw_Begin | Kw_Is | Kw_Capture |
Kw_Mod =>
Unexpected_Token (Class (Input.Read), End_Of_Text, Position (Input.Read));
exit;
end case;
end loop;
return Code_Trees.Statement_Sequence (Statement_Sequences.Dump (Result), Here);
exception
when E : Scanning.Scanning_Error =>
raise Parsing_Error with Ada.Exceptions.Exception_Message (E);
end Parse_Statement_Sequence;
end Protypo.Parsing;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- S Y S T E M . L I B M _ D O U B L E --
-- --
-- B o d y --
-- --
-- Copyright (C) 2014-2021, 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. --
-- --
-- --
-- --
-- --
-- --
-- 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 is the Ada Cert Math specific version of s-libdou.adb
-- When Cody and Waite implementation is cited, it refers to the
-- Software Manual for the Elementary Functions by William J. Cody, Jr.
-- and William Waite, published by Prentice-Hall Series in Computational
-- Mathematics. Copyright 1980. ISBN 0-13-822064-6.
-- When Hart implementation is cited, it refers to
-- "Computer Approximations" by John F. Hart, published by Krieger.
-- Copyright 1968, Reprinted 1978 w/ corrections. ISBN 0-88275-642-7.
with Ada.Numerics; use Ada.Numerics;
with System.Libm; use System.Libm;
with System.Libm_Double.Squareroot;
package body System.Libm_Double is
subtype LF is Long_Float;
pragma Assert (LF'Machine_Radix = 2);
pragma Assert (LF'Machine_Mantissa = 53);
LF_HM : constant Integer := Long_Float'Machine_Mantissa / 2;
Sqrt_Epsilon_LF : constant Long_Float :=
Sqrt_2 ** (1 - Long_Float'Machine_Mantissa);
type Long_Float_Table is array (Positive range <>) of Long_Float;
-- A1 (i) = Float (2**((1-i)/16))
A1_Tab_LF : constant Long_Float_Table :=
(1.0,
Long_Float'Machine (Root16_Half),
Long_Float'Machine (Root16_Half**2),
Long_Float'Machine (Root16_Half**3),
Long_Float'Machine (Root16_Half**4),
Long_Float'Machine (Root16_Half**5),
Long_Float'Machine (Root16_Half**6),
Long_Float'Machine (Root16_Half**7),
Long_Float'Machine (Root16_Half**8),
Long_Float'Machine (Root16_Half**9),
Long_Float'Machine (Root16_Half**10),
Long_Float'Machine (Root16_Half**11),
Long_Float'Machine (Root16_Half**12),
Long_Float'Machine (Root16_Half**13),
Long_Float'Machine (Root16_Half**14),
Long_Float'Machine (Root16_Half**15),
0.5);
-- A2 (i) = 2**((1-2i)/16) - A1(2i)
A2_Tab_LF : constant Long_Float_Table :=
(Root16_Half - Long_Float'Machine (Root16_Half),
Root16_Half**3 - Long_Float'Machine (Root16_Half**3),
Root16_Half**5 - Long_Float'Machine (Root16_Half**5),
Root16_Half**7 - Long_Float'Machine (Root16_Half**7),
Root16_Half**9 - Long_Float'Machine (Root16_Half**9),
Root16_Half**11 - Long_Float'Machine (Root16_Half**11),
Root16_Half**13 - Long_Float'Machine (Root16_Half**13),
Root16_Half**15 - Long_Float'Machine (Root16_Half**15));
-- Intermediary functions
function Reconstruct_Pow
(Z : Long_Float;
P : Integer;
M : Integer) return Long_Float;
procedure Reduce_044
(X : Long_Float;
Reduced_X : out Long_Float;
P : out Integer)
with Post => abs (Reduced_X) < 0.044;
function Reduce_1_16 (X : Long_Float) return Long_Float
with Post => abs (X - Reduce_1_16'Result) <= 0.0625;
function Reduce_1_16 (X : Long_Float) return Long_Float is
(LF'Machine_Rounding (X * 16.0) * (1.0 / 16.0));
package Long_Float_Approximations is
new Generic_Approximations (Long_Float, Mantissa => 53);
use Long_Float_Approximations;
-- Local declarations
procedure Reduce_Half_Pi_Large (X : in out LF; N : LF; Q : out Quadrant);
procedure Split_Veltkamp (X : Long_Float; X_Hi, X_Lo : out Long_Float)
with Post => X = X_Hi + X_Lo;
function Multiply_Add (X, Y, Z : LF) return LF is (X * Y + Z);
-- The following functions reduce a positive X into the range
-- -ln (2) / 2 .. ln (2) / 2
-- It returns a reduced X and an integer N such that:
-- X'Old = X'New + N * Log (2)
-- It is used by Exp function
-- The result should be correctly rounded
procedure Reduce_Ln_2 (X : in out Long_Float; N : out Integer)
with Pre => abs (X) <= Long_Float'Ceiling
(Long_Float'Pred (709.78271_28337_79350_29149_8) * Inv_Ln_2);
-- @llr Reduce_Ln_2 Long_Float
-- The following is postcondition doesn't hold. Suspicious "=" ???
-- Post => abs (X) <= Ln_2 / 2.0 and
-- X'Old = X + Long_Float (N) * Ln_2;
-- The reduction is used by the Sin, Cos and Tan functions.
procedure Reduce_Half_Pi (X : in out Long_Float; Q : out Quadrant)
with Pre => X >= 0.0,
Post => abs (X) <= Max_Red_Trig_Arg;
-- @llr Reduce_Half_Pi Long_Float
-- The following functions reduce a positive X into the range
-- -(Pi/4 + E) .. Pi/4 + E, with E a small fraction of Pi.
--
-- The reason the normalization is not strict is that the computation of
-- the number of times to subtract half Pi is not exact. The rounding
-- error is worst for large arguments, where the number of bits behind
-- the radix point reduces to half the mantissa bits.
-- While it would be possible to correct for this, the polynomial
-- approximations work well for values slightly outside the -Pi/4 .. Pi/4
-- interval, so it is easier for both error analysis and implementation
-- to leave the reduction non-strict, and assume the reduced argument is
-- within -0.26 * Pi .. 0.26 * Pi rather than a quarter of pi.
-- The reduction is guaranteed to be correct to within 0.501 ulp for
-- values of X for which Ada's accuracy guarantees apply:
-- abs X <= 2.0**(T'Machine_Mantissa / 2)
-- For values outside this range, an attempt is made to have significance
-- decrease only proportionally with increase of magnitued. In any case,
-- for all finite arguments, the reduction will succeed, though the reduced
-- value may not agree with the mathematically correct value in even its
-- sign.
---------------------
-- Reconstruct_Pow --
---------------------
function Reconstruct_Pow
(Z : Long_Float;
P : Integer;
M : Integer) return Long_Float
is
-- Cody and Waite implementation (in "**" function page 84)
-- The following computation is carried out in two steps. First add 1 to
-- Z and multiply by 2**(-P/16). Then multiply the result by 2**M.
Result : Long_Float;
begin
Result := A1_Tab_LF (P + 1) * Z;
return Long_Float'Scaling (Result, M);
end Reconstruct_Pow;
----------------
-- Reduce_044 --
----------------
procedure Reduce_044
(X : Long_Float;
Reduced_X : out Long_Float;
P : out Integer)
is
-- Cody and Waite implementation (in "**" function page 84)
-- The output is:
-- P is the biggest odd Integer in range 1 .. 15 such that
-- 2^((1-P)/16) <= X.
-- Reduced_X equals 2 * (X-2^(-P/16)) / (X + 2^(-P/16)).
-- abs (Reduced_X) <= max (2^(2-P/16)-2^(1-P/16)) <= 0.443.
begin
P := 1;
if X <= A1_Tab_LF (9) then
P := 9;
end if;
if X <= A1_Tab_LF (P + 4) then
P := P + 4;
end if;
if X <= A1_Tab_LF (P + 2) then
P := P + 2;
end if;
Reduced_X := (X - A1_Tab_LF (P + 1)) - A2_Tab_LF ((P + 1) / 2);
Reduced_X := Reduced_X / (X + A1_Tab_LF (P + 1));
Reduced_X := Reduced_X + Reduced_X;
end Reduce_044;
--------------------
-- Instantiations --
--------------------
package Instantiations is
function Acos is new Generic_Acos (LF);
function Atan2 is new Generic_Atan2 (LF);
end Instantiations;
--------------------
-- Split_Veltkamp --
--------------------
procedure Split_Veltkamp (X : Long_Float; X_Hi, X_Lo : out Long_Float) is
M : constant LF := 0.5 + 2.0**(1 - LF'Machine_Mantissa / 2);
begin
X_Hi := X * M - (X * M - X);
X_Lo := X - X_Hi;
end Split_Veltkamp;
-----------------
-- Reduce_Ln_2 --
-----------------
procedure Reduce_Ln_2 (X : in out Long_Float; N : out Integer) is
L1 : constant := Long_Float'Leading_Part (Ln_2, LF_HM);
L2 : constant := Long_Float'Leading_Part (Ln_2 - L1, LF_HM);
L3 : constant := Ln_2 - L2 - L1;
XN : constant Long_Float := Long_Float'Rounding (X * Inv_Ln_2);
begin
-- The argument passed to the function is smaller than Ymax * 1/log(2)
-- No overflow is possible for N (Ymax is the largest machine number
-- less than Log (LF'Last)).
N := Integer (XN);
X := ((X - XN * L1) - XN * L2) - XN * L3;
if X < -Ln_2 / 2.0 then
X := X + Ln_2;
N := N - 1;
end if;
if X > Ln_2 / 2.0 then
X := X - Ln_2;
N := N + 1;
end if;
end Reduce_Ln_2;
--------------------
-- Reduce_Half_Pi --
--------------------
procedure Reduce_Half_Pi (X : in out Long_Float; Q : out Quadrant) is
K : constant := Pi / 2.0;
Bits_N : constant := 3;
Max_N : constant := 2.0**Bits_N - 1.0;
Max_X : constant LF := LF'Pred (K * Max_N); -- About 3.5 * Pi
Bits_C : constant := LF'Machine_Mantissa - Bits_N;
C1 : constant LF := LF'Leading_Part (K, Bits_C);
C2 : constant LF := K - C1;
N : constant LF := LF'Machine_Rounding (X * K**(-1));
begin
if not X'Valid then
X := X - X;
Q := 0;
elsif abs X > Max_X then
Reduce_Half_Pi_Large (X, N, Q);
else
pragma Assert (if X'Valid then abs N <= Max_N);
X := (X - N * C1) - N * C2;
Q := Integer (N) mod 4;
end if;
end Reduce_Half_Pi;
--------------------------
-- Reduce_Half_Pi_Large --
--------------------------
procedure Reduce_Half_Pi_Large (X : in out LF; N : LF; Q : out Quadrant) is
type Int_64 is range -2**63 .. 2**63 - 1; -- used for conversions
HM : constant Positive := LF'Machine_Mantissa / 2;
C1 : constant LF := LF'Leading_Part (Half_Pi, HM);
C2 : constant LF := LF'Leading_Part (Half_Pi - C1, HM);
C3 : constant LF := LF'Leading_Part (Half_Pi - C1 - C2, HM);
C4 : constant LF := Half_Pi - C1 - C2 - C3;
K : LF := N;
K_Hi : LF;
K_Lo : LF;
begin
Q := 0;
loop
Split_Veltkamp (X => K, X_Hi => K_Hi, X_Lo => K_Lo);
X := Multiply_Add (-K_Hi, C1, X);
X := Multiply_Add (-K_Hi, C2, Multiply_Add (-K_Lo, C1, X));
X := Multiply_Add (-K_Hi, C3, Multiply_Add (-K_Lo, C2, X));
X := Multiply_Add (-K_Hi, C4, Multiply_Add (-K_Lo, C3, X));
X := Multiply_Add (-K_Lo, C4, X);
if abs K < 2.0**62 or else abs K_Lo <= 2.0**62 then
Q := Quadrant ((Int_64 (Q) + Int_64 (N)) mod 4);
end if;
exit when X in -0.26 * Pi .. 0.26 * Pi;
K := LF'Machine_Rounding (X * Half_Pi**(-1));
end loop;
end Reduce_Half_Pi_Large;
----------
-- Acos --
----------
function Acos (X : LF) return LF is (Instantiations.Acos (X));
-----------
-- Acosh --
-----------
function Acosh (X : LF) return LF is
-- Math based implementation using Log1p: x-> Log (1+x)
T : constant LF := X - 1.0;
begin
if X > 1.0 / Sqrt_Epsilon_LF then
return Log (X) + Ln_2;
elsif X < 2.0 then
return Log1p (T + Sqrt (2.0 * T + T * T));
else
return Log (X + Sqrt ((X - 1.0) * (X + 1.0)));
end if;
end Acosh;
----------
-- Asin --
----------
function Asin (X : LF) return LF is (Long_Float_Approximations.Asin (X));
-----------
-- Asinh --
-----------
function Asinh (X : LF) return LF is
-- Math based implementation using Log1p: x-> Log (1+x)
Y : constant LF := abs X;
G : constant LF := X * X;
Res : LF;
begin
if Y < Sqrt_Epsilon_LF then
Res := Y;
elsif Y > 1.0 / Sqrt_Epsilon_LF then
Res := Log (Y) + Ln_2;
elsif Y < 2.0 then
Res := Log1p (Y + G / (1.0 + Sqrt (G + 1.0)));
else
Res := Log (Y + Sqrt (G + 1.0));
end if;
return LF'Copy_Sign (Res, X);
end Asinh;
----------
-- Atan --
----------
function Atan (X : LF) return LF is (Instantiations.Atan2 (X, 1.0));
-----------
-- Atan2 --
-----------
function Atan2 (Y, X : LF) return LF is (Instantiations.Atan2 (Y, X));
-----------
-- Atanh --
-----------
function Atanh (X : LF) return LF is
-- Math based implementation using Log1p: x-> Log (1+x)
(if X >= 0.0
then Log1p (2.0 * X / (1.0 - X)) / 2.0
else -Log1p (-2.0 * X / (1.0 + X)) / 2.0);
---------
-- Cos --
---------
function Cos (X : LF) return LF is
-- Math based implementation using Hart constants
Y : LF := abs (X);
Q : Quadrant;
Result : LF;
begin
Reduce_Half_Pi (Y, Q);
if Q mod 2 = 0 then
Result := Approx_Cos (Y);
else
Result := Approx_Sin (Y);
end if;
return (if Q = 1 or else Q = 2 then -Result else Result);
end Cos;
----------
-- Cosh --
----------
function Cosh (X : LF) return LF is
-- Cody and Waite implementation (page 217)
Y : constant LF := abs (X);
-- Because the overflow threshold for cosh(X) is beyond the overflow
-- threshold for exp(X), it appears natural to reformulate the
-- computation as:
-- Cosh (X) = Exp (X - Log (2))
-- But because Log (2) is not an exact machine number, the finite word
-- length of the machine implies that the absolute error in X - Log (2),
-- hence the transmitted error in Cosh (X) is proportional to the
-- magnitude of X even when X is error-free.
-- To avoid this problem, we revise the computation to
-- Cosh (X) = V/2 * exp(X - Log (V))
-- where Log (V) is an exact machine number slightly larger than Log (2)
-- with the last few digits of its significand zero.
Ln_V : constant := 8#0.542714#;
-- Machine value slightly above Ln_2
V_2 : constant := 0.24999_30850_04514_99336;
-- V**(-2)
V_2_1 : constant := 0.13830_27787_96019_02638E-4;
-- V / 2 - 1
Y_Bar : constant Long_Float := 709.78271_28933_83973_096;
-- Y_Bar is the last floating point for which exp (Y) does not overflow
-- and exp (-Y) does not underflow
W : LF;
Z : LF;
begin
if Y >= Y_Bar then
W := Y - Ln_V;
Z := Exp (W);
Z := Z + V_2 / Z;
return Z + V_2_1 * Z; -- rewriting of V/2 * Z
else
Z := Exp (Y);
return (Z + 1.0 / Z) / 2.0;
end if;
end Cosh;
---------
-- Exp --
---------
function Exp (X : LF) return LF is
-- Cody and Waite implementation (page 60)
N : Integer;
Y : LF := X;
R : LF;
Ymax : constant LF := LF'Pred (709.78271_28337_79350_29149_8);
-- The largest machine number less than Log (LF'Last)
begin
if abs (Y) < 2.0**(-LF'Machine_Mantissa - 1) then
return 1.0;
end if;
if abs Y > Ymax then
return (if Y > 0.0 then Infinity else 0.0);
end if;
Reduce_Ln_2 (Y, N);
R := Approx_Exp (Y);
return Long_Float'Scaling (R, N);
end Exp;
----------
-- Exp2 --
----------
function Exp2 (X : LF) return LF is
-- Implementation based on Cody and Waite Exp implementation (page 217)
-- but using Hart constants
N : Integer;
Y : LF := X;
R : LF;
Result : LF;
begin
if abs Y < 2.0**(-LF'Machine_Mantissa - 1) then
return 1.0;
end if;
if abs Y > LF'Pred (LF (LF'Machine_Emax)) then
return (if Y > 0.0 then Infinity else 0.0);
end if;
-- If X > Log(LF'Emax) ???
N := Integer (X);
Y := Y - Long_Float (N);
R := Approx_Exp2 (Y);
Result := Long_Float'Scaling (R, N + 1);
if Result /= Result then
Result := (if X < LF'First then 0.0 else Infinity);
end if;
return Result;
end Exp2;
---------
-- Log --
---------
function Log (X : LF) return LF is
-- Cody and Waite implementation (page 35)
Exponent_X : constant Integer := LF'Exponent (X);
XN : LF := LF (Exponent_X);
Mantissa_X : LF := LF'Scaling (X, -Exponent_X);
HM : constant Integer := LF'Machine_Mantissa / 2;
L1 : constant LF := LF'Leading_Part (Ln_2, HM);
L2 : constant LF := Ln_2 - L1;
Result : LF;
begin
if X <= 0.0 then
if X < 0.0 then
return NaN;
else
return -Infinity;
end if;
-- Making sure X is in Sqrt (0.5) .. Sqrt (2)
elsif X > Long_Float'Last then
return X;
elsif Mantissa_X <= Sqrt_Half then
XN := XN - 1.0;
Mantissa_X := Mantissa_X * 2.0;
end if;
Result := Approx_Log (Mantissa_X);
Result := (XN * L2 + Result) + XN * L1;
return Result;
end Log;
-----------
-- Log1p --
-----------
function Log1p (X : LF) return LF is
-- Quick implementation of Log1p not accurate to the Ada regular Log
-- requirements, but accurate enough to compute inverse hyperbolic
-- functions.
begin
if 1.0 + X = 1.0 then
return X;
elsif X > LF'Last then
return X;
else
return Log (1.0 + X) * (X / ((1.0 + X) - 1.0));
end if;
end Log1p;
----------
-- Log2 --
----------
function Log2 (X : LF) return LF is
-- Quick implementation of Log2 not accurate to the Ada regular Log
-- (base e) requirement on the whole definition interval but accurate
-- enough on 0 .. 2**(-1/16).
(Log (X) * (1.0 / Ln_2));
---------
-- Pow --
---------
function Pow (Left, Right : LF) return LF is
-- Cody and Waite implementation (page 84)
-- The implementation seems restricted to positive base, so we use
-- the absolute value and remember the even/oddness of the exponent.
One_Over_Sixteen : constant := 0.0625;
Abs_Left : constant LF := abs (Left);
M : constant Integer := LF'Exponent (Abs_Left);
G : constant LF := LF'Fraction (Abs_Left);
Y : constant LF := Right;
Z : LF;
P : Integer;
U2, U1, Y1, Y2, W1, W2, W : LF;
MM, PP, IW1, I : Integer;
Is_Special : Boolean;
Negate : Boolean;
Special_Result : LF;
procedure Pow_Special_Cases is new Generic_Pow_Special_Cases (LF);
begin
-- Special values
Pow_Special_Cases (Left, Right, Is_Special, Negate, Special_Result);
if Is_Special then
return Special_Result;
else
-- Left**Right is calculated using the formula
-- 2**(Right * Log2 (Left))
Reduce_044 (G, Z, P);
-- At this point, Z <= 0.044
U2 := Approx_Power_Log (Z);
U1 := LF (M * 16 - P) * 0.0625; -- U2 + U1 = Log2 (Left)
-- Forming the pseudo extended precision product of U * Right
Y1 := Reduce_1_16 (Y);
Y2 := Y - Y1;
W := U2 * Y + U1 * Y2;
W1 := Reduce_1_16 (W);
W2 := W - W1;
W := W1 + U1 * Y1;
W1 := Reduce_1_16 (W);
W2 := W2 + (W - W1);
W := Reduce_1_16 (W2);
IW1 := Integer (16.0 * (W1 + W));
W2 := W2 - W;
if W2 > 0.0 then
W2 := W2 - One_Over_Sixteen;
IW1 := 1 + IW1;
end if;
if IW1 < 0 then
I := 0;
else
I := 1;
end if;
MM := Integer (IW1 / 16) + I;
PP := 16 * MM - IW1;
Z := Approx_Exp2 (W2);
Special_Result := Reconstruct_Pow (Z, PP, MM);
if Negate then
return -Special_Result;
else
return Special_Result;
end if;
end if;
end Pow;
---------
-- Sin --
---------
function Sin (X : LF) return LF is
-- Math based implementation using Hart constants
Y : LF := abs X;
Q : Quadrant;
Result : LF;
begin
Reduce_Half_Pi (Y, Q);
if Q mod 2 = 0 then
Result := Approx_Sin (Y);
else
Result := Approx_Cos (Y);
end if;
return LF'Copy_Sign (1.0, X) * (if Q >= 2 then -Result else Result);
end Sin;
----------
-- Sinh --
----------
function Sinh (X : LF) return LF is
-- Cody and Waite implementation (page 217)
Sign : constant LF := LF'Copy_Sign (1.0, X);
Y : constant LF := abs X;
-- Because the overflow threshold for sinh(X) is beyond the overflow
-- threshold for exp(X), it appears natural to reformulate the
-- computation as:
-- Sinh (X) = Exp (X - Log (2))
-- But because Log (2) is not an exact machine number, the finite word
-- length of the machine implies that the absolute error in X - Log (2),
-- hence the transmitted error in Sinh (X) is proportional to the
-- magnitude of X even when X is error-free. To avoid this problem, we
-- revise the computation to:
-- Sinh (X) = V/2 * exp(X - Log (V))
-- where Log (V) is an exact machine number slightly larger than Log (2)
-- with the last few digits of its significand zero.
Ln_V : constant := 8#0.542714#;
-- Machine value slightly above Ln_2
V_2 : constant := 0.24999_30850_04514_99336;
-- V**(-2)
V_2_1 : constant := 0.13830_27787_96019_02638E-4;
-- V / 2 - 1
Y_Bar : constant Long_Float := 709.78271_28933_83973_096;
-- The last floating point for which exp (X) does not overflow and
-- exp (-x) does not underflow
W : LF;
Z : LF;
begin
if Y <= 1.0 then
return Approx_Sinh (X);
end if;
if Y >= Y_Bar then
W := Y - Ln_V;
Z := Exp (W);
Z := Z - V_2 / Z;
return Sign * (Z + V_2_1 * Z); -- rewriting of V/2 * Z
else
Z := Exp (Y);
return Sign * ((Z - 1.0 / Z) / 2.0);
end if;
end Sinh;
----------
-- Sqrt --
----------
function Sqrt (X : Long_Float) return Long_Float renames
System.Libm_Double.Squareroot.Sqrt;
---------
-- Tan --
---------
function Tan (X : LF) return LF is
-- Math based implementation using Hart constants
Y : LF := abs X;
N : Integer;
begin
if abs X < LF'Last then
Reduce_Half_Pi (Y, N);
else
return Infinity / Infinity;
end if;
-- The reconstruction is included in the algebraic fraction in
-- Approx_Tan function.
if N mod 2 = 0 then
return Approx_Tan (Y) * LF'Copy_Sign (1.0, X);
else
return Approx_Cot (Y) * LF'Copy_Sign (1.0, X);
end if;
end Tan;
----------
-- Tanh --
----------
function Tanh (X : LF) return LF is
-- Cody and Waite implementation (page 239)
F : constant LF := abs (X);
Xbig : constant := Ln_2 * LF (1 + LF'Machine_Mantissa);
LN_3_2 : constant := 0.54930_61443_34054_84570;
Result : LF;
begin
if F > Xbig then
Result := 1.0;
else
if F > LN_3_2 then
Result := 1.0 - 2.0 / (Exp (2.0 * F) + 1.0);
else
Result := Approx_Tanh (F);
end if;
end if;
return LF'Copy_Sign (Result, X);
end Tanh;
end System.Libm_Double;
|
WITH P_StepHandler;
USE P_StepHandler;
with P_StructuralTypes;
use P_StructuralTypes;
package P_StepHandler.FeistelHandler is
type T_BinaryIntegerArray is array (0..15) of T_BinaryUnit (1..4);
type T_SBox is array (0..3, 0..15) of Integer;
type T_SBoxArray is array (1..8) of T_SBox;
type FeistelHandler is new T_StepHandler with private;
type Ptr_FeistelHandler is access all FeistelHandler;
--- CONSTRUCTOR ---
function Make (Handler : in out FeistelHandler) return FeistelHandler;
--- PROCEDURE ---
procedure Handle (Self : in out FeistelHandler);
function Process_Block (Self : in FeistelHandler;
Block : in out T_BinaryBlock)
return T_BinaryBlock;
procedure Feistel_Round (Self : in FeistelHandler;
Block : in out T_BinaryBlock;
Round : in Integer);
function Feistel_Function (Self : in FeistelHandler;
HalfBlock : T_BinaryHalfBlock;
SubKey : T_BinarySubKey)
return T_BinaryHalfBlock;
function Expansion (HalfBlock : T_BinaryHalfBlock)
return T_BinaryExpandedBlock;
function SBox_Substitution (Self : in FeistelHandler;
ExpandedBlock : T_BinaryExpandedBlock)
return T_BinaryHalfBlock;
function SBox_Output (Self : in FeistelHandler;
Input : T_BinaryUnit;
SBoxNumber : Integer) return T_BinaryUnit;
function Permutation (HalfBlock : T_BinaryHalfBlock)
return T_BinaryHalfBlock;
procedure FinalInversion (Block : in out T_BinaryBlock);
---- GETTER ----
function Get_SBoxArray (Self : in out FeistelHandler) return T_SBoxArray;
function Get_SBoxOutputArray (Self : in out FeistelHandler)
return T_BinaryIntegerArray;
---- SETTER ----
procedure Set_SubKeyArrayAccess (Self : in out FeistelHandler;
Ptr : in BinarySubKeyArray_Access);
procedure Set_Mode (Self : in out FeistelHandler;
Mode : Character);
PRIVATE
type FeistelHandler is new P_StepHandler.T_StepHandler with record
Ptr_SubKeyArray : BinarySubKeyArray_Access;
SBoxOutputArray : T_BinaryIntegerArray;
SBoxArray : T_SBoxArray;
Mode : Character;
end record;
end P_StepHandler.FeistelHandler;
|
------------------------------------------------------------------------------
-- --
-- GNAT EXAMPLE --
-- --
-- Copyright (C) 2013, AdaCore --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
-- Boston, MA 02110-1301, USA. --
-- --
-- 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 Cache; use Cache;
with System.Machine_Code; use System.Machine_Code;
with Flash;
package body Memwrite is
Invalid_Addr : constant Unsigned_32 := 1;
-- An invalid address to mark the buffer as uninitialized.
Buffer_Addr : Unsigned_32 := Invalid_Addr;
-- Address at which the buffer must be written in memory. Use Invalid_Addr
-- to mark the address invalid (in that case the buffer is considered as
-- empty).
Buffer_Len : constant := 32;
Addr_Mask : constant Unsigned_32 := not (Buffer_Len - 1);
Buffer : Storage_Array (0 .. Storage_Count (Buffer_Len - 1));
for Buffer'Alignment use 4;
-- Buffer of data to be written at Buffer_Addr
procedure Init is
begin
Buffer_Addr := Invalid_Addr;
Buffer := (others => 16#ff#);
end Init;
procedure Flush is
use Flash;
Off : Unsigned_32;
Off1 : Storage_Count;
In_Flash : constant Boolean := Flash.In_Flash (Buffer_Addr);
begin
if In_Flash then
-- Invalidate corresponding cache entries (if any).
-- Note that the flash is cache inhibited when unlocked
Off := 0;
while Off < Buffer'Length loop
Asm ("dcbi 0,%0",
Inputs => Unsigned_32'Asm_Input ("r", Buffer_Addr + Off),
Volatile => True);
Off := Off + Cache.Cache_Line;
end loop;
Flash_Start_Prog;
end if;
-- Write buffer. Copy per word, for FLASH.
Off1 := 0;
while Off1 < Storage_Count (Buffer_Len) loop
declare
D : Unsigned_32;
for D'Address use
System'To_Address (Buffer_Addr + Unsigned_32 (Off1));
pragma Import (Ada, D);
pragma Volatile (D);
pragma Warnings (Off, "specified address*");
S : Unsigned_32;
for S'Address use Buffer (Off1)'Address;
pragma Warnings (On, "specified address*");
begin
D := S;
end;
Off1 := Off1 + 4;
end loop;
if In_Flash then
Flash_Wait_Prog;
end if;
Buffer := (others => 16#ff#);
-- Flush and sync caches
-- Not strictly needed on mpc5566, as the cache is unified
Cache.Cache_Flush_Range
(System'To_Address (Buffer_Addr),
System'To_Address (Buffer_Addr + Buffer_Len - 1));
end Flush;
procedure Write (Addr : Unsigned_32; Content : Storage_Array) is
Cur_Addr : Unsigned_32 := Addr;
begin
for I in Content'Range loop
if Buffer_Addr = Invalid_Addr then
Buffer_Addr := Cur_Addr and Addr_Mask;
elsif (Buffer_Addr and Addr_Mask) /= (Cur_Addr and Addr_Mask) then
Flush;
Buffer_Addr := Cur_Addr and Addr_Mask;
end if;
Buffer (Storage_Count (Cur_Addr and not Addr_Mask)) := Content (I);
Cur_Addr := Cur_Addr + 1;
end loop;
end Write;
end Memwrite;
|
pragma Ada_2020;
with Interfaces; use Interfaces;
with Ada.Numerics;
with Ada.Numerics.Generic_Elementary_Functions;
package body Fmt.Generic_Ordinary_Fixed_Point_Argument is
package Math is
new Ada.Numerics.Generic_Elementary_Functions(Long_Float);
Exp : constant Long_Long_Float := 10.0 ** Fixed_Point_Type'Aft;
Scale : constant Long_Long_Float := Fixed_Point_Type'Small * Exp;
Int_Scale : constant Long_Long_Integer := Long_Long_Integer(Scale);
To_Char : constant array(Unsigned_64 range 0 .. 9) of Character := "0123456789";
type Display_Goal is record
N : Unsigned_64; -- a number maybe very big
M : Unsigned_64; -- a scale number, maybe very big
P : Unsigned_64; -- a patch value, at most two digits
end record;
type Decimal is record
K : Unsigned_64; -- coefficient
R : Unsigned_64; -- remainder, one digit
end record;
-- Dec_Cache : array (Long_Long_Integer range 0 .. 1000) of Decimal :=
-- [for I in Long_Long_Integer range 0 .. 1000 => (I / 10, I mod 10)];
function To_Long_Long_Integer (X : Fixed_Point_Type) return Long_Long_Integer
with Pre => Fixed_Point_Type'Base'Size in 8 | 16 | 32 | 64;
function To_Long_Long_Integer (X : Fixed_Point_Type) return Long_Long_Integer
is
BX : Fixed_Point_Type'Base := X;
begin
case Fixed_Point_Type'Base'Size is
when 8 =>
declare
i : Integer_8 with Address => BX'Address;
begin
return Long_Long_Integer(i);
end;
when 16 =>
declare
i : Integer_16 with Address => BX'Address;
begin
return Long_Long_Integer(i);
end;
when 32 =>
declare
i : Integer_32 with Address => BX'Address;
begin
return Long_Long_Integer(i);
end;
when 64 =>
declare
i : Integer_64 with Address => BX'Address;
begin
return Long_Long_Integer(i);
end;
when others =>
raise Storage_Error;
end case;
end To_Long_Long_Integer;
function Compute_Multiply_Result_Length (
N, M : Long_Long_Integer)
return Natural
is
L : Natural := 0;
X : Unsigned_64 := Safe_Abs(N);
begin
loop
L := L + 1;
X := X / 10;
exit when X = 0;
end loop;
X := Safe_Abs(M);
loop
L := L + 1;
X := X / 10;
exit when X = 0;
end loop;
if N < 0 then
L := L + 1;
end if;
return L;
end Compute_Multiply_Result_Length;
function To_Argument (X : Fixed_Point_Type) return Argument_Type'Class
is
begin
return Fixed_Point_Argument_Type'(Value => X, others => <>);
end To_Argument;
function "&" (Args : Arguments; X : Fixed_Point_Type) return Arguments
is
begin
return Args & To_Argument(X);
end "&";
overriding
procedure Parse (Self : in out Fixed_Point_Argument_Type; Edit : String)
is
procedure Conf (K, V : String)
is
begin
if K'Length /= 1 or else V'Length = 0 then
return;
end if;
case K(K'First) is
when 'a' =>
if Is_Decimal_Number(V) then
Self.Aft := Natural'Value(V);
end if;
when 'w' =>
if Is_Decimal_Number(V) then
Self.Width := Natural'Value(V);
end if;
when others =>
null;
end case;
end Conf;
begin
Parse_KV_Edit(Edit, Conf'Access);
end Parse;
overriding
function Get_Length (Self : in out Fixed_Point_Argument_Type) return Natural
is
begin
if Self.Width /= 0 then
return Self.Width;
else
return Compute_Multiply_Result_Length(
N => To_Long_Long_Integer(Self.Value),
M => Int_Scale);
end if;
end Get_Length;
function Split (X : Unsigned_64) return Decimal
is
pragma Inline(Split);
begin
return (K => X / 10, R => X mod 10);
end Split;
overriding
procedure Put (
Self : in out Fixed_Point_Argument_Type;
Edit : String;
To : in out String)
is
Dot_Pos : constant Integer := To'Last - Fixed_Point_Type'Aft;
H : constant Natural := To'First;
L : Natural := To'Last;
V : constant Long_Long_Integer := To_Long_Long_Integer(Self.Value);
G : Display_Goal := (Safe_Abs(V), Safe_Abs(Int_Scale), 0);
N, M, R, Y : Decimal;
procedure Display (Digit : Unsigned_64)
is
pragma Inline(Display);
begin
if L = Dot_Pos then
To(L) := '.';
L := L - 1;
if L < H then
return;
end if;
end if;
To(L) := To_Char(Digit);
-- To(L) := Character'Val(Digit + Character'Pos('0'));
L := L - 1;
end Display;
begin
loop
N := Split(G.N);
M := Split(G.M);
R := Split(N.R * M.R + G.P);
Y := Split(N.K * M.R + M.K * N.R + R.K);
Display(R.R);
exit when L < H; -- To'First;
Display(Y.R);
exit when L < H; -- To'First;
-- adjust next goal
G := (N.K, M.K, Y.K);
exit when G = (0, 0, 0);
end loop;
while L + 1 < To'Last loop
exit when To(L + 1) /= '0';
To(L + 1) := ' ';
L := L + 1;
end loop;
if V < 0 then
To(L) := '-';
L := L - 1;
end if;
if L >= To'First then
To(To'First .. L) := (others => Self.Fill);
end if;
end Put;
end Fmt.Generic_Ordinary_Fixed_Point_Argument;
|
-- Ada_GUI implementation based on Gnoga. Adapted 2021
-- --
-- GNOGA - The GNU Omnificent GUI for Ada --
-- --
-- G N O G A . S E R V E R . C O N N E C I O N --
-- --
-- B o d y --
-- --
-- --
-- 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 --
------------------------------------------------------------------------------
with Ada.Directories;
with Ada.Strings.Fixed;
with Ada.Unchecked_Deallocation;
with Ada.Exceptions;
with Ada.Containers.Ordered_Maps;
with Ada_GUI.Gnoga.Server.Mime;
with Ada_GUI.Gnoga.Application;
with Strings_Edit.Quoted;
with GNAT.Sockets.Server; use GNAT.Sockets.Server;
with GNAT.Sockets.Connection_State_Machine.HTTP_Server;
use GNAT.Sockets.Connection_State_Machine.HTTP_Server;
with Ada.Text_IO;
with Ada.Streams.Stream_IO;
with Ada_GUI.Gnoga.Server.Connection.Common; use Ada_GUI.Gnoga.Server.Connection.Common;
with Ada_GUI.Gnoga.Server.Template_Parser.Simple;
with Strings_Edit.UTF8.Handling;
with Strings_Edit.Streams;
with Ada.Streams;
package body Ada_GUI.Gnoga.Server.Connection is
On_Connect_Event : Connect_Event := null;
On_Post_Event : Post_Event := null;
On_Post_Request_Event : Post_Request_Event := null;
On_Post_File_Event : Post_File_Event := null;
Exit_Application_Requested : Boolean := False;
function Global_Gnoga_Client_Factory
(Listener : access Connections_Server'Class;
Request_Length : Positive;
Input_Size : Buffer_Length;
Output_Size : Buffer_Length)
return Connection_Ptr;
-- Passed to Gnoga.Server.Connection.Common.Gnoga_Client_Factory
-- This allows a common HTTP client for secure and insecure connections
-- and when desired the secure libraries connection need not be linked in.
-------------------------------------------------------------------------
-- Private Types
-------------------------------------------------------------------------
protected type String_Buffer is
procedure Buffering (Value : Boolean);
function Buffering return Boolean;
procedure Add (S : in String);
-- Add to end of buffer
procedure Preface (S : in String);
-- Preface to buffer
function Get return String;
-- Retrieve buffer
procedure Get_And_Clear (S : out Ada.Strings.Unbounded.Unbounded_String);
-- Retrieve and clear buffer
function Length return Natural;
-- Size of buffer
procedure Clear;
-- Clear buffer
private
Is_Buffering : Boolean := False;
Buffer : Ada.Strings.Unbounded.Unbounded_String;
end String_Buffer;
task type Watchdog_Type is
entry Start;
entry Stop;
end Watchdog_Type;
type Watchdog_Access is access Watchdog_Type;
Watchdog : Watchdog_Access := null;
-- Keep alive and check connection status
-------------------------------------------------------------------------
-- HTTP Server Setup for Gnoga_HTTP_Server
-------------------------------------------------------------------------
-- Gnoga_HTTP_Content --
-- Per http connection data
type Gnoga_HTTP_Client;
type Socket_Type is access all Gnoga_HTTP_Client;
type Gnoga_HTTP_Content is new Content_Source with
record
Socket : Socket_Type := null;
Connection_Type : Gnoga_Connection_Type := HTTP;
Connection_Path : Ada.Strings.Unbounded.Unbounded_String;
FS : Ada.Streams.Stream_IO.File_Type;
Input_Overflow : String_Buffer;
Buffer : String_Buffer;
Finalized : Boolean := False;
Text : aliased Strings_Edit.Streams.String_Stream (500);
end record;
overriding
function Get (Source : access Gnoga_HTTP_Content) return String;
-- Handle long polling method
pragma Warnings (Off);
procedure Write (Stream : access Ada.Streams.Root_Stream_Type'Class;
Item : in Gnoga_HTTP_Content);
for Gnoga_HTTP_Content'Write use Write;
pragma Warnings (On);
-- Gnoga_HTTP_Factory --
-- Creates Gnoga_HTTP_Client objects on incoming connections
-- from Gnoga_HTTP_Connection
type Gnoga_HTTP_Factory (Request_Length : Positive;
Input_Size : Buffer_Length;
Output_Size : Buffer_Length;
Max_Connections : Positive)
is new Connections_Factory with null record;
overriding
function Create (Factory : access Gnoga_HTTP_Factory;
Listener : access Connections_Server'Class;
From : GNAT.Sockets.Sock_Addr_Type)
return Connection_Ptr;
-- Gnoga_HTTP_Connection --
type Gnoga_HTTP_Connection is
new GNAT.Sockets.Server.Connections_Server with null record;
overriding
function Get_Server_Address (Listener : Gnoga_HTTP_Connection)
return GNAT.Sockets.Sock_Addr_Type;
-- Set the listening host if was set in Initialize
overriding
procedure Create_Socket
(Listener : in out Gnoga_HTTP_Connection;
Socket : in out GNAT.Sockets.Socket_Type;
Address : GNAT.Sockets.Sock_Addr_Type);
-- Create socket with exception handler
-- Gnoga_HTTP_Client --
type Gnoga_HTTP_Client is new HTTP_Client with
record
Content : aliased Gnoga_HTTP_Content;
end record;
-- type Socket_Type is access all Gnoga_HTTP_Client;
overriding
procedure Finalize (Client : in out Gnoga_HTTP_Client);
-- Handle browser crashes or webkit abrupt closes
overriding
function Get_Name (Client : Gnoga_HTTP_Client) return String;
overriding
procedure Do_Get (Client : in out Gnoga_HTTP_Client);
overriding
procedure Do_Post (Client : in out Gnoga_HTTP_Client);
overriding
procedure Body_Received (Client : in out Gnoga_HTTP_Client;
Content : in out CGI_Keys.Table'Class);
overriding
procedure Body_Received (Client : in out Gnoga_HTTP_Client;
Content : in out Ada.Streams.Root_Stream_Type'Class);
overriding
procedure Do_Body (Client : in out Gnoga_HTTP_Client);
overriding
procedure Do_Head (Client : in out Gnoga_HTTP_Client);
overriding
function WebSocket_Open (Client : access Gnoga_HTTP_Client)
return WebSocket_Accept;
overriding
procedure WebSocket_Initialize (Client : in out Gnoga_HTTP_Client);
overriding
procedure WebSocket_Received_Part (Client : in out Gnoga_HTTP_Client;
Message : in String);
overriding
procedure WebSocket_Received (Client : in out Gnoga_HTTP_Client;
Message : in String);
overriding
procedure WebSocket_Closed (Client : in out Gnoga_HTTP_Client;
Status : in WebSocket_Status;
Message : in String);
overriding
procedure WebSocket_Error
(Client : in out Gnoga_HTTP_Client;
Error : in Ada.Exceptions.Exception_Occurrence);
-------------------------------------------------------------------------
-- Connection Helpers
-------------------------------------------------------------------------
pragma Warnings (Off);
procedure Start_Long_Polling_Connect
(Client : in out Gnoga_HTTP_Client;
ID : out Gnoga.Connection_ID);
-- Start a long polling connection alternative to websocket
pragma Warnings (On);
function Buffer_Add (ID : Gnoga.Connection_ID;
Script : String)
return Boolean;
-- If buffering add Script to the buffer for ID and return true, if not
-- buffering return false;
procedure Dispatch_Message (Message : in String);
-- Dispatch an incoming message from browser to event system
-----------------------
-- Gnoga_HTTP_Server --
-----------------------
Server_Wait : Connection_Holder_Type;
task type Gnoga_HTTP_Server_Type is
entry Start;
entry Stop;
end Gnoga_HTTP_Server_Type;
type Gnoga_HTTP_Server_Access is access Gnoga_HTTP_Server_Type;
Gnoga_HTTP_Server : Gnoga_HTTP_Server_Access := null;
task body Gnoga_HTTP_Server_Type is
begin
accept Start;
declare
Factory : aliased Gnoga_HTTP_Factory
(Request_Length => Max_HTTP_Request_Length,
Input_Size => Max_HTTP_Input_Chunk,
Output_Size => Max_HTTP_Output_Chunk,
Max_Connections => Max_HTTP_Connections);
begin
if Verbose_Output then
Gnoga.Log ("HTTP Server Started");
-- Trace_On (Factory => Factory,
-- Received => Trace_Any,
-- Sent => Trace_Any);
end if;
if not Secure_Server then
declare
Server : Gnoga_HTTP_Connection (Factory'Access, Server_Port);
pragma Unreferenced (Server);
begin
accept Stop;
end;
else
if not Secure_Only then
declare
Server1 : Gnoga_HTTP_Connection
(Factory'Access, Server_Port);
pragma Unreferenced (Server1);
Server2 : Gnoga_HTTP_Connection
(Gnoga.Server.Connection.Common.Gnoga_Secure_Factory.all,
Secure_Port);
pragma Unreferenced (Server2);
begin
accept Stop;
end;
else
declare
Server : Gnoga_HTTP_Connection
(Gnoga.Server.Connection.Common.Gnoga_Secure_Factory.all,
Secure_Port);
pragma Unreferenced (Server);
begin
accept Stop;
end;
end if;
end if;
Server_Wait.Release;
if Verbose_Output then
Gnoga.Log ("HTTP Server Stopping");
end if;
end;
end Gnoga_HTTP_Server_Type;
------------
-- Create --
------------
function Global_Gnoga_Client_Factory
(Listener : access Connections_Server'Class;
Request_Length : Positive;
Input_Size : Buffer_Length;
Output_Size : Buffer_Length)
return Connection_Ptr
is
Socket : constant Socket_Type := new Gnoga_HTTP_Client
(Listener => Listener.all'Unchecked_Access,
Request_Length => Request_Length,
Input_Size => Input_Size,
Output_Size => Output_Size);
begin
Socket.Content.Socket := Socket;
return Connection_Ptr (Socket);
end Global_Gnoga_Client_Factory;
overriding
function Create (Factory : access Gnoga_HTTP_Factory;
Listener : access Connections_Server'Class;
From : GNAT.Sockets.Sock_Addr_Type)
return Connection_Ptr
is
pragma Unreferenced (From);
begin
return Gnoga.Server.Connection.Common.Gnoga_Client_Factory
(Listener => Listener.all'Unchecked_Access,
Request_Length => Factory.Request_Length,
Input_Size => Factory.Input_Size,
Output_Size => Factory.Output_Size);
end Create;
-------------------------
-- Get_Server_Address --
-------------------------
overriding
function Get_Server_Address (Listener : Gnoga_HTTP_Connection)
return GNAT.Sockets.Sock_Addr_Type
is
use GNAT.Sockets;
use type Ada.Strings.Unbounded.Unbounded_String;
Address : Sock_Addr_Type;
Host : constant String :=
(if Server_Host = "localhost" then "127.0.0.1" else Ada.Strings.Unbounded.To_String (Server_Host));
begin
if Host = "" then
Address.Addr := Any_Inet_Addr;
else
Address.Addr := Inet_Addr (Host);
end if;
Address.Port := Listener.Port;
return Address;
end Get_Server_Address;
--------------------
-- Create_Socket --
--------------------
overriding
procedure Create_Socket
(Listener : in out Gnoga_HTTP_Connection;
Socket : in out GNAT.Sockets.Socket_Type;
Address : GNAT.Sockets.Sock_Addr_Type)
is
use type GNAT.Sockets.Socket_Type;
begin
Create_Socket (Connections_Server (Listener), Socket, Address);
exception
when Error : others =>
Gnoga.Log (Error);
if Socket /= GNAT.Sockets.No_Socket then
begin
GNAT.Sockets.Shutdown_Socket (Socket);
exception
when others =>
null;
end;
begin
GNAT.Sockets.Close_Socket (Socket);
exception
when others =>
null;
end;
Socket := GNAT.Sockets.No_Socket;
end if;
Stop;
end Create_Socket;
--------------
-- Get_Name --
--------------
overriding
function Get_Name (Client : Gnoga_HTTP_Client) return String is
pragma Unreferenced (Client);
begin
return Gnoga.HTTP_Server_Name;
end Get_Name;
-----------------
-- Do_Get_Head --
-----------------
procedure Do_Get_Head (Client : in out Gnoga_HTTP_Client;
Get : in Boolean);
procedure Do_Get_Head (Client : in out Gnoga_HTTP_Client;
Get : in Boolean)
is
use Ada.Strings;
use Ada.Strings.Unbounded;
use Ada.Strings.Fixed;
use Strings_Edit.Quoted;
Status : Status_Line renames Get_Status_Line (Client);
function Adjust_Name return String;
function Adjust_Name return String is
function Start_Path return String;
function After_Start_Path return String;
File_Name : constant String := Status.File;
function Start_Path return String is
Q : constant Integer := Index (File_Name, "/");
begin
if Q = 0 then
return "";
else
return File_Name (File_Name'First .. Q - 1);
end if;
end Start_Path;
function After_Start_Path return String is
Q : constant Integer := Index (File_Name, "/");
begin
if Q = 0 then
return File_Name;
else
return File_Name (Q + 1 .. File_Name'Last);
end if;
end After_Start_Path;
Start : constant String := Start_Path;
Path_Adjusted_Name : constant String := After_Start_Path;
begin
if File_Name = "gnoga_ajax" then
return File_Name;
elsif Start = "" and File_Name = "" then
return Gnoga.Server.HTML_Directory & To_String (Boot_HTML);
elsif Start = "js" then
return Gnoga.Server.JS_Directory & Path_Adjusted_Name;
elsif Start = "css" then
return Gnoga.Server.CSS_Directory & Path_Adjusted_Name;
elsif Start = "img" then
return Gnoga.Server.IMG_Directory & Path_Adjusted_Name;
else
if Ada.Directories.Exists
(Gnoga.Server.HTML_Directory & File_Name)
then
return Gnoga.Server.HTML_Directory & File_Name;
else
return Gnoga.Server.HTML_Directory & To_String (Boot_HTML);
end if;
end if;
end Adjust_Name;
begin
case Status.Kind is
when None =>
if Verbose_Output then
Gnoga.Log ("Requested: Kind: " & Status.Kind'Img & ", Query: " & Status.Query);
Gnoga.Log ("Reply: Not found");
end if;
Reply_Text (Client, 404, "Not found", "Not found");
when File =>
if Verbose_Output then
Gnoga.Log ("Requested: Kind: " & Status.Kind'Img & ", File: " & Status.File
& ", Query: " & Status.Query);
end if;
Client.Content.Connection_Path :=
To_Unbounded_String (Status.File);
Send_Status_Line (Client, 200, "OK");
Send_Date (Client);
Send (Client,
"Cache-Control: no-cache, no-store, must-revalidate" &
Gnoga.Server.Connection.Common.CRLF);
Send (Client, "Pragma: no-cache" &
Gnoga.Server.Connection.Common.CRLF);
Send (Client, "Expires: 0" &
Gnoga.Server.Connection.Common.CRLF);
Send_Connection (Client, Persistent => True);
Send_Server (Client);
declare
F : constant String := Adjust_Name;
M : constant String := Gnoga.Server.Mime.Mime_Type (F);
begin
if F = "gnoga_ajax" then
Send_Body (Client, "", Get);
declare
MH : constant String := "?m=";
Q : constant Integer := Index
(Status.Query, MH, Going => Forward);
Message : constant String := Status.Query
(Q + MH'Length .. Status.Query'Last);
begin
Dispatch_Message (Message);
end;
else
if M = "text/html" then
Client.Content.Finalized := False;
declare
ID : Gnoga.Connection_ID;
F : Unbounded_String := To_Unbounded_String
(Gnoga.Server.Template_Parser.Simple.Load_View
(Adjust_Name));
begin
if Gnoga.Application.Favicon /= Null_Unbounded_String and
Index (F, "<meta name=""generator"" content=""Gnoga"" />") > 0 and
Index (F, "favicon.ico") > 0
then
String_Replace (Source => F,
Pattern => "favicon.ico",
Replacement => Gnoga.Application.Favicon);
end if;
if Index (F, "/js/ajax.js") > 0 then
Client.Content.Connection_Type := Long_Polling;
Client.Content.Buffer.Add (To_String (F));
Send_Body (Client, Client.Content'Access, Get);
Start_Long_Polling_Connect (Client, ID);
elsif Index (F, "/js/auto.js") > 0 then
Client.Content.Connection_Type := Long_Polling;
Start_Long_Polling_Connect (Client, ID);
String_Replace (Source => F,
Pattern => "@@Connection_ID@@",
Replacement => ID'Img);
Client.Content.Buffer.Add (To_String (F));
Send_Body (Client, Client.Content'Access, Get);
else
Client.Content.Connection_Type := HTTP;
Client.Content.Buffer.Add (To_String (F));
Send_Body (Client, Client.Content'Access, Get);
end if;
end;
else
Send_Content_Type (Client, M);
declare
use Ada.Streams.Stream_IO;
begin
if Is_Open (Client.Content.FS) then
Close (Client.Content.FS);
end if;
Open (Client.Content.FS, In_File, F,
Form => "shared=no");
Send_Body (Client,
Stream (Client.Content.FS),
Get);
end;
end if;
end if;
if Verbose_Output then
Gnoga.Log ("Reply: " & F & " (" & M & ')');
end if;
exception
when Ada.Text_IO.Name_Error =>
if Verbose_Output then
Gnoga.Log ("Reply: Not found");
end if;
Reply_Text (Client,
404,
"Not found",
"No file " & Quote (Status.File) & " found");
end;
when URI =>
if Verbose_Output then
Gnoga.Log ("Requested: Kind: " & Status.Kind'Img & ", Path: " & Status.Path
& ", Query: " & Status.Query);
Gnoga.Log ("Reply: Not found");
end if;
Reply_Text (Client,
404,
"Not found",
"No URI " & Quote (Status.Path) & " found");
end case;
exception
when E : others =>
Log ("Do_Get_Head Error");
Log (Ada.Exceptions.Exception_Information (E));
end Do_Get_Head;
------------
-- Do_Get --
------------
overriding
procedure Do_Get (Client : in out Gnoga_HTTP_Client) is
begin
Do_Get_Head (Client, True);
end Do_Get;
-------------
-- Do_Post --
-------------
overriding
procedure Do_Post (Client : in out Gnoga_HTTP_Client) is
begin
Do_Get_Head (Client, True);
end Do_Post;
-------------------
-- Body_Received --
-------------------
overriding
procedure Body_Received (Client : in out Gnoga_HTTP_Client;
Content : in out CGI_Keys.Table'Class)
is
pragma Unreferenced (Content);
Status : Status_Line renames Get_Status_Line (Client);
Parameters : Gnoga.Data_Map_Type;
begin
if On_Post_Event /= null and Status.Kind = File then
for i in 1 .. Client.Get_CGI_Size loop
Parameters.Insert (Strings_Edit.UTF8.Handling.To_String (Client.Get_CGI_Key (i),
Substitution_Character),
Strings_Edit.UTF8.Handling.To_String (Client.Get_CGI_Value (i),
Substitution_Character));
end loop;
On_Post_Event (Status.File & Status.Query, Parameters);
end if;
end Body_Received;
-------------------
-- Body_Received --
-------------------
overriding
procedure Body_Received (Client : in out Gnoga_HTTP_Client;
Content : in out Ada.Streams.Root_Stream_Type'Class)
is
pragma Unreferenced (Content);
Status : Status_Line renames Get_Status_Line (Client);
Disposition : constant String := Client.Get_Multipart_Header (Content_Disposition_Header);
Field_ID : constant String := "name=""";
n : constant Natural := Ada.Strings.Fixed.Index (Disposition, Field_ID);
Eq : constant Natural := Ada.Strings.Fixed.Index (Disposition, """", n + Field_ID'Length);
Field_Name : constant String := Disposition (n + Field_ID'Length .. Eq - 1);
Content_Type : constant String :=
Client.Get_Multipart_Header (Content_Type_Header);
Parameters : Gnoga.Data_Map_Type;
begin
if On_Post_Event /= null and Status.Kind = File and Content_Type = "" then
Parameters.Insert (Strings_Edit.UTF8.Handling.To_String (Field_Name, Substitution_Character),
Strings_Edit.UTF8.Handling.To_String (Client.Content.Text.Get, Substitution_Character));
On_Post_Event (Status.File & Status.Query, Parameters);
end if;
end Body_Received;
-------------
-- Do_Post --
-------------
overriding
procedure Do_Body (Client : in out Gnoga_HTTP_Client) is
use Ada.Strings.Fixed;
use Ada.Strings.Unbounded;
use Ada.Streams.Stream_IO;
Status : Status_Line renames Get_Status_Line (Client);
Param_List : Unbounded_String;
Content_Type : constant String :=
Client.Get_Header (Content_Type_Header);
Disposition : constant String := Client.Get_Multipart_Header
(Content_Disposition_Header);
begin
-- Gnoga.Log ("Content_Type: " & Content_Type & ", Disposition: " & Disposition);
if On_Post_Request_Event /= null then
On_Post_Request_Event (Status.File & Status.Query, Param_List);
end if;
if Content_Type = "application/x-www-form-urlencoded" then
Client.Receive_Body (Strings_Edit.UTF8.Handling.To_UTF8 (To_String (Param_List)));
end if;
if Index (Content_Type, "multipart/form-data") = Content_Type'First then
if Index (Disposition, "form-data") = Disposition'First then
declare
Field_ID : constant String := "name=""";
File_ID : constant String := "filename=""";
n : constant Natural := Index (Disposition, Field_ID);
f : constant Natural := Index (Disposition, File_ID);
begin
if n /= 0 then
declare
Eq : constant Natural := Index
(Disposition, """", n + Field_ID'Length);
Field_Name : constant String := Disposition
(n + Field_ID'Length .. Eq - 1);
begin
if Index (Strings_Edit.UTF8.Handling.To_UTF8 (To_String (Param_List)), Field_Name) > 0 then
if f /= 0 then
declare
Eq : constant Natural := Index
(Disposition, """", f + File_ID'Length);
File_Name : constant String := Disposition
(f + File_ID'Length .. Eq - 1);
begin
if On_Post_File_Event = null then
Gnoga.Log ("Attempt to upload file without" &
" an On_Post_File_Event set");
else
if Is_Open (Client.Content.FS) then
Close (Client.Content.FS);
end if;
Create (Client.Content.FS,
Out_File,
Gnoga.Server.Upload_Directory &
File_Name & ".tmp",
"Text_Translation=No");
Receive_Body
(Client, Stream (Client.Content.FS));
On_Post_File_Event (Status.File & Status.Query,
Strings_Edit.UTF8.Handling.To_String
(File_Name, Substitution_Character),
Strings_Edit.UTF8.Handling.To_String
(File_Name, Substitution_Character) & ".tmp");
end if;
end;
else
Client.Content.Text.Rewind;
Client.Receive_Body (Client.Content.Text'Access);
end if;
end if;
end;
end if;
end;
end if;
end if;
exception
when E : others =>
Log ("Do_Body Error");
Log (Ada.Exceptions.Exception_Information (E));
end Do_Body;
-------------
-- Do_Head --
-------------
overriding
procedure Do_Head (Client : in out Gnoga_HTTP_Client) is
begin
Do_Get_Head (Client, False);
end Do_Head;
-------------------------------------------------------------------------
-- Gnoga Server Connection Methods
-------------------------------------------------------------------------
----------------
-- Initialize --
----------------
procedure Initialize (Host : in String := "";
Port : in Integer := 8080;
Boot : in String := "boot.html";
Verbose : in Boolean := True)
is
begin
Verbose_Output := Verbose;
Boot_HTML := Ada.Strings.Unbounded.To_Unbounded_String (Boot);
Server_Port := GNAT.Sockets.Port_Type (Port);
Server_Host := Ada.Strings.Unbounded.To_Unbounded_String (Host);
if Verbose then
Write_To_Console ("Gnoga :" & Gnoga.Version);
Write_To_Console ("Application root :" & Application_Directory);
Write_To_Console ("Executable at :" & Executable_Directory);
Write_To_Console ("HTML root :" & HTML_Directory);
Write_To_Console ("Upload directory :" & Upload_Directory);
Write_To_Console ("Templates root :" & Templates_Directory);
Write_To_Console ("/js at :" & JS_Directory);
Write_To_Console ("/css at :" & CSS_Directory);
Write_To_Console ("/img at :" & IMG_Directory);
if not Secure_Only then
Write_To_Console ("Boot file :" & Boot);
Write_To_Console ("HTTP listen on :" & Host & ":" &
Left_Trim (Server_Port'Img));
end if;
if Secure_Server then
Write_To_Console ("HTTPS listen on :" & Host & ":" &
Left_Trim (Secure_Port'Img));
end if;
end if;
Watchdog := new Watchdog_Type;
Watchdog.Start;
end Initialize;
---------
-- Run --
---------
procedure Run is
begin
Gnoga_HTTP_Server := new Gnoga_HTTP_Server_Type;
Gnoga_HTTP_Server.Start;
Server_Wait.Hold;
Exit_Application_Requested := True;
end Run;
-------------------
-- Shutting_Down --
-------------------
function Shutting_Down return Boolean is
begin
return Exit_Application_Requested;
end Shutting_Down;
----------------------------
-- Connection_Holder_Type --
----------------------------
protected body Connection_Holder_Type is
entry Hold when not Connected is
begin
null;
-- Semaphore does not reset itself to a blocking state.
-- This ensures that if Released before Hold that Hold
-- will not block and connection will be released.
-- It also allows for On_Connect Handler to not have to use
-- Connection.Hold unless there is a desire code such as to
-- clean up after a connection is ended.
end Hold;
procedure Release is
begin
Connected := False;
end Release;
end Connection_Holder_Type;
type Connection_Holder_Access is access all Connection_Holder_Type;
package Connection_Holder_Maps is new Ada.Containers.Ordered_Maps
(Gnoga.Unique_ID, Connection_Holder_Access);
package Connection_Data_Maps is new Ada.Containers.Ordered_Maps
(Gnoga.Unique_ID, Gnoga.Pointer_to_Connection_Data_Class);
---------------------
-- Event_Task_Type --
---------------------
task type Event_Task_Type (TID : Gnoga.Connection_ID);
type Event_Task_Access is access all Event_Task_Type;
procedure Free_Event_Task is
new Ada.Unchecked_Deallocation (Event_Task_Type,
Event_Task_Access);
package Event_Task_Maps is new Ada.Containers.Ordered_Maps
(Gnoga.Unique_ID, Event_Task_Access);
------------------------
-- Connection Manager --
------------------------
package Socket_Maps is new Ada.Containers.Ordered_Maps
(Gnoga.Connection_ID, Socket_Type);
-- Socket Maps are used for the Connection Manager to map connection IDs
-- to web sockets.
protected Connection_Manager is
procedure Add_Connection (Socket : in Socket_Type;
New_ID : out Gnoga.Connection_ID);
-- Adds Socket to managed Connections and generates a New_ID.
procedure Start_Connection (New_ID : in Gnoga.Connection_ID);
-- Start event task on connection
procedure Swap_Connection (New_ID : in Gnoga.Connection_ID;
Old_ID : in Gnoga.Connection_ID);
-- Reconnect old connection
procedure Add_Connection_Holder (ID : in Gnoga.Connection_ID;
Holder : in Connection_Holder_Access);
-- Adds a connection holder to the connection
-- Can only be one at any given time.
procedure Add_Connection_Data
(ID : in Gnoga.Connection_ID;
Data : in Gnoga.Pointer_to_Connection_Data_Class);
-- Adds data to be associated with connection
function Connection_Data
(ID : in Gnoga.Connection_ID)
return Gnoga.Pointer_to_Connection_Data_Class;
-- Returns the Connection_Data associated with ID
procedure Delete_Connection_Holder (ID : in Gnoga.Connection_ID);
-- Delete connection holder
procedure Delete_Connection (ID : in Gnoga.Connection_ID);
-- Delete Connection with ID.
-- Releases connection holder if present.
procedure Finalize_Connection (ID : in Gnoga.Connection_ID);
-- Mark Connection with ID for deletion.
function Valid (ID : in Gnoga.Connection_ID) return Boolean;
-- Return True if ID is in connection map.
procedure First (ID : out Gnoga.Connection_ID);
-- Return first ID if ID is in connection map else 0.
procedure Next (ID : out Gnoga.Connection_ID);
-- Return next ID if ID is in connection map else 0.
function Connection_Socket (ID : in Gnoga.Connection_ID)
return Socket_Type;
-- Return the Socket_Type associated with ID
-- Raises Connection_Error if ID is not Valid
function Find_Connection_ID (Socket : Socket_Type)
return Gnoga.Connection_ID;
-- Find the Connection_ID related to Socket.
procedure Delete_All_Connections;
-- Called by Stop to close down server
function Active_Connections return Ada.Containers.Count_Type;
-- Returns the number of active connections
private
Socket_Count : Gnoga.Connection_ID := 0;
Connection_Holder_Map : Connection_Holder_Maps.Map;
Connection_Data_Map : Connection_Data_Maps.Map;
Event_Task_Map : Event_Task_Maps.Map;
Socket_Map : Socket_Maps.Map;
Shadow_Socket_Map : Socket_Maps.Map;
Current_Socket : Socket_Maps.Cursor := Socket_Maps.No_Element;
end Connection_Manager;
protected body Connection_Manager is
procedure Add_Connection (Socket : in Socket_Type;
New_ID : out Gnoga.Connection_ID)
is
begin
Socket_Count := Socket_Count + 1;
New_ID := Socket_Count;
Socket_Map.Insert (New_ID, Socket);
end Add_Connection;
procedure Start_Connection (New_ID : in Gnoga.Connection_ID)
is
begin
Event_Task_Map.Insert (New_ID, new Event_Task_Type (New_ID));
end Start_Connection;
procedure Swap_Connection (New_ID : in Gnoga.Connection_ID;
Old_ID : in Gnoga.Connection_ID)
is
begin
if Socket_Map.Contains (Old_ID) then
declare
Old_Socket : constant Socket_Type :=
Socket_Map.Element (Old_ID);
New_Socket : constant Socket_Type :=
Socket_Map.Element (New_ID);
begin
New_Socket.Content.Connection_Path :=
Old_Socket.Content.Connection_Path;
Socket_Map.Replace (Old_ID, New_Socket);
Socket_Map.Replace (New_ID, Old_Socket);
Old_Socket.Content.Finalized := True;
end;
else
raise Connection_Error with
"Old connection " & Old_ID'Img & " already gone";
end if;
end Swap_Connection;
procedure Add_Connection_Holder (ID : in Gnoga.Connection_ID;
Holder : in Connection_Holder_Access)
is
begin
Connection_Holder_Map.Insert (ID, Holder);
end Add_Connection_Holder;
procedure Delete_Connection_Holder (ID : in Gnoga.Connection_ID)
is
begin
if Connection_Holder_Map.Contains (ID) then
Connection_Holder_Map.Delete (ID);
end if;
end Delete_Connection_Holder;
procedure Add_Connection_Data
(ID : in Gnoga.Connection_ID;
Data : in Gnoga.Pointer_to_Connection_Data_Class)
is
begin
Connection_Data_Map.Include (ID, Data);
end Add_Connection_Data;
function Connection_Data
(ID : in Gnoga.Connection_ID)
return Gnoga.Pointer_to_Connection_Data_Class
is
begin
if Connection_Data_Map.Contains (ID) then
return Connection_Data_Map.Element (ID);
else
return null;
end if;
end Connection_Data;
procedure Delete_Connection (ID : in Gnoga.Connection_ID) is
begin
if (ID > 0) then
Gnoga.Log ("Deleting connection -" & ID'Img);
if Connection_Holder_Map.Contains (ID) then
Connection_Holder_Map.Element (ID).Release;
Connection_Holder_Map.Delete (ID);
end if;
if Connection_Data_Map.Contains (ID) then
Connection_Data_Map.Delete (ID);
end if;
if Socket_Map.Contains (ID) then
Socket_Map.Delete (ID);
end if;
if Event_Task_Map.Contains (ID) then
declare
E : Event_Task_Access := Event_Task_Map.Element (ID);
begin
Free_Event_Task (E);
Event_Task_Map.Delete (ID);
end;
end if;
end if;
exception
when E : others =>
Log ("Delete_Connection " & ID'Img & " error.");
Log (Ada.Exceptions.Exception_Information (E));
end Delete_Connection;
procedure Finalize_Connection (ID : in Gnoga.Connection_ID) is
begin
if (ID > 0) and Socket_Map.Contains (ID) then
if Verbose_Output then
Gnoga.Log ("Finalizing connection -" & ID'Img);
end if;
Socket_Map.Element (ID).Content.Finalized := True;
end if;
end Finalize_Connection;
function Valid (ID : in Gnoga.Connection_ID) return Boolean is
begin
return Socket_Map.Contains (ID);
end Valid;
procedure First (ID : out Gnoga.Connection_ID) is
use type Socket_Maps.Cursor;
begin
Shadow_Socket_Map := Socket_Map;
Current_Socket := Shadow_Socket_Map.First;
if Current_Socket /= Socket_Maps.No_Element then
ID := Socket_Maps.Key (Current_Socket);
else
ID := 0;
end if;
end First;
procedure Next (ID : out Gnoga.Connection_ID) is
use type Socket_Maps.Cursor;
begin
Current_Socket := Socket_Maps.Next (Current_Socket);
if Current_Socket /= Socket_Maps.No_Element then
ID := Socket_Maps.Key (Current_Socket);
else
ID := 0;
end if;
end Next;
function Connection_Socket (ID : in Gnoga.Connection_ID)
return Socket_Type
is
use type Socket_Maps.Cursor;
Connection_Cursor : constant Socket_Maps.Cursor := Socket_Map.Find (ID);
begin
if Connection_Cursor = Socket_Maps.No_Element then
Log ("Error Connection_Socket - " & ID'Img & " not found in connection map. ");
raise Connection_Error with
"Connection ID" & ID'Img & " not found in connection map. " &
"Connection most likely was previously closed.";
else
return Socket_Maps.Element (Connection_Cursor);
end if;
end Connection_Socket;
function Find_Connection_ID (Socket : Socket_Type)
return Gnoga.Connection_ID
is
use type Socket_Maps.Cursor;
Cursor : Socket_Maps.Cursor := Socket_Map.First;
begin
while Cursor /= Socket_Maps.No_Element loop
if Socket_Maps.Element (Cursor) = Socket then
return Socket_Maps.Key (Cursor);
else
Socket_Maps.Next (Cursor);
end if;
end loop;
return Gnoga.No_Connection;
end Find_Connection_ID;
procedure Delete_All_Connections is
procedure Do_Delete (C : in Socket_Maps.Cursor);
procedure Do_Delete (C : in Socket_Maps.Cursor) is
begin
Delete_Connection (Socket_Maps.Key (C));
end Do_Delete;
begin
-- Socket_Map.Iterate (Do_Delete'Access); -- provoque PROGRAM_ERROR
-- Message: Gnoga.Server.Connection.Socket_Maps.Tree_Operations.
-- Delete_Node_Sans_Free: attempt to tamper with cursors
-- (container is busy)
while not Socket_Map.Is_Empty loop
Do_Delete (Socket_Map.First);
end loop;
end Delete_All_Connections;
function Active_Connections return Ada.Containers.Count_Type is
begin
return Socket_Map.Length;
end Active_Connections;
end Connection_Manager;
task body Event_Task_Type is
Connection_Holder : aliased Connection_Holder_Type;
ID : Gnoga.Connection_ID;
begin
ID := TID;
-- Insure that TID is retained even if task is "deleted"
Connection_Manager.Add_Connection_Holder
(ID, Connection_Holder'Unchecked_Access);
begin
delay 0.3;
-- Give time to finish handshaking
Execute_Script (ID, "gnoga['Connection_ID']=" & ID'Img);
Execute_Script (ID, "TRUE=true");
Execute_Script (ID, "FALSE=false");
-- By setting the variable TRUE and FALSE it is possible to set
-- a property or attribute with Boolean'Img which will result
-- in TRUE or FALSE not the case sensitive true or false
-- expected.
On_Connect_Event (ID, Connection_Holder'Unchecked_Access);
exception
when E : Connection_Error =>
-- Browser was closed by user
Log ("Error browser was closed by user -" & ID'Img);
Log (Ada.Exceptions.Exception_Information (E));
Connection_Holder.Release;
when E : others =>
Connection_Holder.Release;
Log ("Error on Connection ID =" & ID'Img);
Log (Ada.Exceptions.Exception_Information (E));
end;
Connection_Manager.Delete_Connection_Holder (ID);
Connection_Manager.Finalize_Connection (ID);
-- Insure cleanup even if socket not closed by external connection
exception
when E : others =>
Log ("Connection Manager Error Connection ID =" & ID'Img);
Log (Ada.Exceptions.Exception_Information (E));
end Event_Task_Type;
--------------
-- Watchdog --
--------------
task body Watchdog_Type is
procedure Ping (ID : in Gnoga.Connection_ID);
procedure Ping (ID : in Gnoga.Connection_ID) is
Socket : Socket_Type := Connection_Manager.Connection_Socket (ID);
begin
if Socket.Content.Finalized then
if Verbose_Output then
Gnoga.Log ("Ping on Finalized -" & ID'Img);
end if;
Connection_Manager.Delete_Connection (ID);
Socket.Shutdown;
elsif Socket.Content.Connection_Type = Long_Polling then
if Verbose_Output then
Gnoga.Log ("Ping on long polling -" & ID'Img);
end if;
Execute_Script (ID, "0");
elsif Socket.Content.Connection_Type = WebSocket then
if Verbose_Output then
Gnoga.Log ("Ping on websocket -" & ID'Img);
end if;
Socket.WebSocket_Send ("0");
end if;
exception
when E : Storage_Error =>
Gnoga.Log ("Invalid socket, Deleting ID -" & ID'Img);
Log (Ada.Exceptions.Exception_Information (E));
Connection_Manager.Delete_Connection (ID);
when E : others =>
Log ("Ping" & ID'Img & " error.");
Log (Ada.Exceptions.Exception_Information (E));
if Socket.Content.Connection_Type = Long_Polling then
Gnoga.Log ("Long polling error closing ID " & ID'Img);
Socket.Content.Finalized := True;
Socket.Shutdown;
else
begin
delay 3.0;
Socket := Connection_Manager.Connection_Socket (ID);
Socket.WebSocket_Send ("0");
exception
when E : others =>
Log ("Watchdog closed connection ID " & ID'Img);
Log (Ada.Exceptions.Exception_Information (E));
begin
Connection_Manager.Delete_Connection (ID);
exception
when E : others =>
Log ("Watchdog ping error - " & ID'Img);
Log (Ada.Exceptions.Exception_Information (E));
end;
end;
end if;
end Ping;
begin
accept Start;
loop
declare
ID : Gnoga.Connection_ID;
begin
Connection_Manager.First (ID);
while ID /= 0 loop
Ping (ID);
Connection_Manager.Next (ID);
end loop;
exception
when E : others =>
Log ("Watchdog error on websocket - " & ID'Img);
Log (Ada.Exceptions.Exception_Information (E));
end;
select
accept Stop;
exit;
or
delay 60.0;
end select;
end loop;
end Watchdog_Type;
---------------------------
-- Message Queue Manager --
---------------------------
No_Object : exception;
function "=" (Left, Right : Gnoga.Gui.Pointer_To_Base_Class)
return Boolean;
-- Properly identify equivalent objects
function "=" (Left, Right : Gnoga.Gui.Pointer_To_Base_Class)
return Boolean
is
begin
return Left.Unique_ID = Right.Unique_ID;
end "=";
package Object_Maps is new Ada.Containers.Ordered_Maps
(Gnoga.Unique_ID, Gnoga.Gui.Pointer_To_Base_Class);
protected Object_Manager is
function Get_Object (ID : Gnoga.Unique_ID)
return Gnoga.Gui.Pointer_To_Base_Class;
procedure Insert
(ID : in Gnoga.Unique_ID;
Object : in Gnoga.Gui.Pointer_To_Base_Class);
procedure Delete (ID : Gnoga.Unique_ID);
private
Object_Map : Object_Maps.Map;
end Object_Manager;
protected body Object_Manager is
function Get_Object (ID : Gnoga.Unique_ID)
return Gnoga.Gui.Pointer_To_Base_Class
is
begin
if Object_Map.Contains (ID) then
return Object_Map.Element (ID);
else
raise No_Object with "ID:" & ID'Img;
end if;
end Get_Object;
procedure Insert
(ID : in Gnoga.Unique_ID;
Object : in Gnoga.Gui.Pointer_To_Base_Class)
is
begin
Object_Map.Insert (Key => ID,
New_Item => Object);
end Insert;
procedure Delete (ID : Gnoga.Unique_ID) is
begin
if Object_Map.Contains (ID) then
Object_Map.Delete (ID);
end if;
end Delete;
end Object_Manager;
--------------------
-- WebSocket_Open --
--------------------
overriding
function WebSocket_Open (Client : access Gnoga_HTTP_Client)
return WebSocket_Accept
is
Status : Status_Line renames Get_Status_Line (Client.all);
F : constant String := Status.File;
begin
if F /= "gnoga" then
Gnoga.Log ("Invalid URL for Websocket: " & F);
declare
Reason : constant String := "Invalid URL";
begin
return (Accepted => False,
Length => Reason'Length,
Code => 400,
Reason => Reason);
end;
end if;
Client.Content.Connection_Type := WebSocket;
if On_Connect_Event /= null then
return (Accepted => True,
Length => 0,
Size => Max_Websocket_Message,
Duplex => True,
Chunked => True,
Protocols => "");
else
Gnoga.Log ("No Connection event set.");
declare
Reason : constant String := "No connection event set";
begin
return (Accepted => False,
Length => Reason'Length,
Code => 400,
Reason => Reason);
end;
end if;
end WebSocket_Open;
--------------------------
-- WebSocket_Initialize --
--------------------------
overriding
procedure WebSocket_Initialize (Client : in out Gnoga_HTTP_Client)
is
Status : Status_Line renames Get_Status_Line (Client);
F : constant String := Status.Query;
S : constant Socket_Type := Client'Unchecked_Access;
ID : Gnoga.Connection_ID := Gnoga.No_Connection;
function Get_Old_ID return String;
function Get_Old_ID return String is
use Ada.Strings.Fixed;
C : constant String := "Old_ID=";
I : constant Integer := Index (F, C);
begin
if I > 0 then
return F (I + C'Length .. F'Last);
else
return "";
end if;
end Get_Old_ID;
Old_ID : constant String := Get_Old_ID;
begin
Connection_Manager.Add_Connection (Socket => S,
New_ID => ID);
if Old_ID /= "" and Old_ID /= "undefined" then
if Verbose_Output then
Gnoga.Log ("Swapping websocket connection " &
ID'Img & " <=> " & Old_ID);
end if;
begin
Connection_Manager.Swap_Connection
(ID, Gnoga.Connection_ID'Value (Old_ID));
exception
when E : Connection_Error =>
Gnoga.Log ("Connection error - " & ID'Img);
Gnoga.Log (Ada.Exceptions.Exception_Message (E));
Client.Content.Finalized := True;
Connection_Manager.Delete_Connection (ID);
Gnoga.Log ("Connection aborted - " & ID'Img);
end;
else
Connection_Manager.Start_Connection (ID);
if Verbose_Output then
Gnoga.Log ("New connection - ID" & ID'Img);
end if;
end if;
exception
when E : others =>
Gnoga.Log ("Open error ID" & ID'Img);
Gnoga.Log (Ada.Exceptions.Exception_Information (E));
end WebSocket_Initialize;
----------------------
-- WebSocket_Closed --
----------------------
overriding
procedure WebSocket_Closed (Client : in out Gnoga_HTTP_Client;
Status : in WebSocket_Status;
Message : in String)
is
pragma Unreferenced (Status);
S : constant Socket_Type := Client'Unchecked_Access;
ID : constant Gnoga.Connection_ID :=
Connection_Manager.Find_Connection_ID (S);
begin
if ID /= Gnoga.No_Connection then
S.Content.Finalized := True;
if Verbose_Output then
if Message /= "" then
Gnoga.Log ("Websocket connection closed - ID" & ID'Img &
" with message : " & Message);
else
Gnoga.Log ("Websocket connection closed - ID" & ID'Img);
end if;
end if;
Connection_Manager.Delete_Connection (ID);
end if;
end WebSocket_Closed;
---------------------
-- WebSocket_Error --
---------------------
overriding
procedure WebSocket_Error
(Client : in out Gnoga_HTTP_Client;
Error : in Ada.Exceptions.Exception_Occurrence)
is
S : constant Socket_Type := Client'Unchecked_Access;
ID : constant Gnoga.Connection_ID :=
Connection_Manager.Find_Connection_ID (S);
begin
S.Content.Finalized := True;
Gnoga.Log ("Connection error ID" & ID'Img &
" with message : " &
Ada.Exceptions.Exception_Information (Error));
-- If not reconnected by next watchdog ping connection will be deleted.
end WebSocket_Error;
--------------------------------
-- Start_Long_Polling_Connect --
--------------------------------
procedure Start_Long_Polling_Connect
(Client : in out Gnoga_HTTP_Client;
ID : out Gnoga.Connection_ID)
is
S : constant Socket_Type := Client'Unchecked_Access;
begin
Connection_Manager.Add_Connection (Socket => S,
New_ID => ID);
Connection_Manager.Start_Connection (ID);
if Verbose_Output then
Gnoga.Log ("New long polling connection - ID" & ID'Img);
end if;
end Start_Long_Polling_Connect;
--------------------
-- Script_Manager --
--------------------
protected type Script_Holder_Type is
entry Hold;
procedure Release (Result : in String);
function Result return String;
private
Connected : Boolean := True;
Script_Result : Ada.Strings.Unbounded.Unbounded_String;
end Script_Holder_Type;
protected body Script_Holder_Type is
entry Hold when not Connected is
begin
null;
-- Semaphore does not reset itself to a blocking state.
-- This ensures that if Released before Hold that Hold
-- will not block and connection will be released.
end Hold;
procedure Release (Result : in String) is
begin
Connected := False;
Script_Result := Ada.Strings.Unbounded.To_Unbounded_String (Result);
end Release;
function Result return String is
begin
return Ada.Strings.Unbounded.To_String (Script_Result);
end Result;
end Script_Holder_Type;
type Script_Holder_Access is access all Script_Holder_Type;
package Script_Holder_Maps is new Ada.Containers.Ordered_Maps
(Gnoga.Unique_ID, Script_Holder_Access);
protected type Script_Manager_Type is
procedure Add_Script_Holder (ID : out Gnoga.Unique_ID;
Holder : in Script_Holder_Access);
-- Adds a script holder to wait for script execution to end
-- and return results;
procedure Delete_Script_Holder (ID : in Gnoga.Unique_ID);
-- Delete script holder
procedure Release_Hold (ID : in Gnoga.Unique_ID;
Result : in String);
-- Delete connection hold with ID.
private
Script_Holder_Map : Script_Holder_Maps.Map;
Script_ID : Gnoga.Unique_ID := 0;
end Script_Manager_Type;
protected body Script_Manager_Type is
procedure Add_Script_Holder (ID : out Gnoga.Connection_ID;
Holder : in Script_Holder_Access)
is
begin
Script_ID := Script_ID + 1;
Script_Holder_Map.Insert (Script_ID, Holder);
ID := Script_ID;
end Add_Script_Holder;
procedure Delete_Script_Holder (ID : in Gnoga.Connection_ID) is
begin
Script_Holder_Map.Delete (ID);
end Delete_Script_Holder;
procedure Release_Hold (ID : in Gnoga.Unique_ID;
Result : in String)
is
begin
if Script_Holder_Map.Contains (ID) then
Script_Holder_Map.Element (ID).Release (Result);
end if;
end Release_Hold;
end Script_Manager_Type;
Script_Manager : Script_Manager_Type;
-----------------------------
-- WebSocket_Received_Part --
-----------------------------
overriding
procedure WebSocket_Received_Part (Client : in out Gnoga_HTTP_Client;
Message : in String)
is
begin
Client.Content.Input_Overflow.Add (Message);
end WebSocket_Received_Part;
------------------------
-- WebSocket_Received --
------------------------
overriding
procedure WebSocket_Received (Client : in out Gnoga_HTTP_Client;
Message : in String)
is
Full_Message : constant String :=
Client.Content.Input_Overflow.Get & Message;
begin
Client.Content.Input_Overflow.Clear;
if Full_Message = "0" then
return;
end if;
Dispatch_Message (Strings_Edit.UTF8.Handling.To_String (Full_Message,
Substitution_Character));
exception
when E : others =>
Log ("Websocket Message Error");
Log (Ada.Exceptions.Exception_Information (E));
end WebSocket_Received;
----------------------
-- Dispatch_Message --
----------------------
procedure Dispatch_Message (Message : in String) is
use Ada.Strings.Fixed;
begin
if Message (Message'First) = 'S' then
declare
P1 : constant Integer := Index (Source => Message,
Pattern => "|");
UID : constant String := Message (Message'First + 2 .. (P1 - 1));
Result : constant String := Message ((P1 + 1) .. Message'Last);
begin
Script_Manager.Release_Hold (Gnoga.Unique_ID'Value (UID),
Result);
end;
else
declare
P1 : constant Integer := Index (Source => Message,
Pattern => "|");
P2 : constant Integer := Index (Source => Message,
Pattern => "|",
From => P1 + 1);
UID : constant String := Message (Message'First .. (P1 - 1));
Event : constant String := Message ((P1 + 1) .. (P2 - 1));
Event_Data : constant String := Message ((P2 + 1) .. Message'Last);
Object : constant Gnoga.Gui.Pointer_To_Base_Class :=
Object_Manager.Get_Object (Integer'Value (UID));
begin
Gui.Event_Queue.Enqueue (New_Item => (Event => Ada.Strings.Unbounded.To_Unbounded_String (Event),
Object => Object,
Data => Ada.Strings.Unbounded.To_Unbounded_String (Event_Data) ) );
end;
end if;
exception
when E : No_Object =>
Log ("Request to dispatch message to non-existant object");
Log (Ada.Exceptions.Exception_Information (E));
return;
when E : others =>
Log ("Dispatch Message Error");
Log (Ada.Exceptions.Exception_Information (E));
end Dispatch_Message;
-------------------
-- String_Buffer --
-------------------
protected body String_Buffer is
procedure Buffering (Value : Boolean) is
begin
Is_Buffering := Value;
end Buffering;
function Buffering return Boolean is
begin
return Is_Buffering;
end Buffering;
procedure Add (S : in String) is
use type Ada.Strings.Unbounded.Unbounded_String;
begin
Buffer := Buffer & S;
end Add;
procedure Preface (S : in String) is
use type Ada.Strings.Unbounded.Unbounded_String;
begin
Buffer := S & Buffer;
end Preface;
function Length return Natural is
begin
return Ada.Strings.Unbounded.Length (Buffer);
end Length;
function Get return String is
begin
return Ada.Strings.Unbounded.To_String (Buffer);
end Get;
procedure Get_And_Clear (S : out Ada.Strings.Unbounded.Unbounded_String)
is
begin
S := Buffer;
Buffer := Ada.Strings.Unbounded.To_Unbounded_String ("");
end Get_And_Clear;
procedure Clear is
begin
Buffer := Ada.Strings.Unbounded.To_Unbounded_String ("");
end Clear;
end String_Buffer;
----------------
-- Buffer_Add --
----------------
function Buffer_Add (ID : Gnoga.Connection_ID;
Script : String)
return Boolean
is
Socket : constant Socket_Type :=
Connection_Manager.Connection_Socket (ID);
begin
if Socket.Content.Buffer.Buffering then
if Socket.Content.Buffer.Length + Script'Length >=
Max_Buffer_Length
then
Flush_Buffer (ID);
end if;
if Socket.Content.Connection_Type = WebSocket then
Socket.Content.Buffer.Add (Script &
Gnoga.Server.Connection.Common.CRLF);
elsif Socket.Content.Connection_Type = Long_Polling then
Socket.Content.Buffer.Add
("<script>" & Script & "</script>");
else
Gnoga.Log ("Buffer_Add called on unsupported connection type.");
end if;
return True;
else
return False;
end if;
end Buffer_Add;
-----------------------
-- Buffer_Connection --
-----------------------
function Buffer_Connection (ID : Gnoga.Connection_ID) return Boolean
is
Socket : constant Socket_Type :=
Connection_Manager.Connection_Socket (ID);
begin
return Socket.Content.Buffer.Buffering;
end Buffer_Connection;
procedure Buffer_Connection (ID : in Gnoga.Connection_ID;
Value : in Boolean)
is
Socket : constant Socket_Type :=
Connection_Manager.Connection_Socket (ID);
begin
if Value = False then
Flush_Buffer (ID);
end if;
Socket.Content.Buffer.Buffering (Value);
end Buffer_Connection;
------------------
-- Flush_Buffer --
------------------
procedure Flush_Buffer (ID : in Gnoga.Connection_ID)
is
Socket : Socket_Type;
begin
if Connection_Manager.Valid (ID) then
Socket :=
Connection_Manager.Connection_Socket (ID);
if Socket.Content.Buffer.Buffering and
Socket.Content.Connection_Type = WebSocket
then
Socket.Content.Buffer.Buffering (False);
Execute_Script (ID, Socket.Content.Buffer.Get);
Socket.Content.Buffer.Clear;
Socket.Content.Buffer.Buffering (True);
elsif Socket.Content.Connection_Type = Long_Polling then
Socket.Unblock_Send;
end if;
end if;
exception
when E : Connection_Error =>
-- Connection already closed.
Log ("Connection" & ID'Img & " already closed.");
Log (Ada.Exceptions.Exception_Information (E));
when E : others =>
Log ("Flush_Buffer Error -" & ID'Img);
Log (Ada.Exceptions.Exception_Information (E));
end Flush_Buffer;
-------------------
-- Buffer_Append --
-------------------
procedure Buffer_Append (ID : in Gnoga.Connection_ID;
Value : in String)
is
Socket : constant Socket_Type :=
Connection_Manager.Connection_Socket (ID);
begin
Socket.Content.Buffer.Add (Value);
end Buffer_Append;
--------------------
-- Execute_Script --
--------------------
procedure Execute_Script (ID : in Gnoga.Connection_ID;
Script : in String)
is
UTF8_Script : constant String :=
Strings_Edit.UTF8.Handling.To_UTF8 (Script);
procedure Try_Execute;
procedure Try_Execute is
Socket : constant Socket_Type :=
Connection_Manager.Connection_Socket (ID);
begin
if Socket.Content.Connection_Type = Long_Polling then
Socket.Content.Buffer.Add ("<script>" & UTF8_Script & "</script>");
if not Socket.Content.Buffer.Buffering then
Socket.Unblock_Send;
end if;
elsif Socket.Content.Connection_Type = WebSocket then
Socket.WebSocket_Send (UTF8_Script);
end if;
exception
when E : Ada.Text_IO.End_Error =>
Log ("Error Try_Execute - " & ID'Img);
Log (Ada.Exceptions.Exception_Information (E));
raise Connection_Error with
"Socket Closed before execute of : " & Script;
when E : others =>
Log ("Error Try_Execute - " & ID'Img);
Log (Ada.Exceptions.Exception_Information (E));
raise Connection_Error with
"Socket Error during execute of : " & Script;
end Try_Execute;
begin
if Connection_Manager.Valid (ID) and UTF8_Script /= "" then
if not Buffer_Add (ID, UTF8_Script) then
Try_Execute;
end if;
end if;
exception
when E : others =>
Log ("Error Execute_Script -" & ID'Img);
Log (Ada.Exceptions.Exception_Information (E));
delay 2.0;
Try_Execute;
end Execute_Script;
function Execute_Script (ID : in Gnoga.Connection_ID;
Script : in String)
return String
is
UTF8_Script : constant String :=
Strings_Edit.UTF8.Handling.To_UTF8 (Script);
function Try_Execute return String;
function Try_Execute return String is
Script_Holder : aliased Script_Holder_Type;
begin
declare
Script_ID : Gnoga.Unique_ID;
Socket : constant Socket_Type :=
Connection_Manager.Connection_Socket (ID);
begin
Script_Manager.Add_Script_Holder
(ID => Script_ID,
Holder => Script_Holder'Unchecked_Access);
declare
Message : constant String := "ws.send (" &
"""S" & Script_ID'Img & "|""+" &
"eval (""" & UTF8_Script & """)" &
");";
begin
if Socket.Content.Connection_Type = Long_Polling then
Socket.Content.Buffer.Add ("<script>" &
Message &
"</script>");
Socket.Unblock_Send;
elsif Socket.Content.Connection_Type = WebSocket then
Socket.WebSocket_Send (Message);
end if;
select
delay Script_Time_Out; -- Timeout for browser answer
Script_Manager.Delete_Script_Holder (Script_ID);
raise Script_Error with
"Timeout error, no browser response for: " & Message;
then abort
Script_Holder.Hold;
end select;
end;
declare
Result : constant String := Script_Holder.Result;
begin
Script_Manager.Delete_Script_Holder (Script_ID);
return Result;
end;
end;
exception
when E : Ada.Text_IO.End_Error =>
Log ("Error Try_Execute -" & ID'Img);
Log (Ada.Exceptions.Exception_Information (E));
raise Connection_Error with
"Socket Closed before execute of : " & Script;
when E : others =>
Log ("Error Try_Execute -" & ID'Img);
Log (Ada.Exceptions.Exception_Information (E));
raise Connection_Error with
"Socket Error during execute of : " & Script;
end Try_Execute;
begin
begin
if Connection_Manager.Valid (ID) then
Flush_Buffer (ID);
return Try_Execute;
else
raise Connection_Error with "Invalid ID " & ID'Img;
end if;
exception
when E : others =>
Log ("Error Execute_Script -" & ID'Img);
Log (Ada.Exceptions.Exception_Information (E));
begin
delay 2.0;
return Try_Execute;
exception
when E : others =>
Log ("Error Execute_Script after retrying -" & ID'Img);
Log (Ada.Exceptions.Exception_Information (E));
Close (ID);
raise Connection_Error with "Invalid ID " & ID'Img;
end;
end;
end Execute_Script;
---------------------
-- Connection_Data --
---------------------
procedure Connection_Data
(ID : in Gnoga.Connection_ID;
Data : access Gnoga.Connection_Data_Type'Class)
is
begin
Connection_Manager.Add_Connection_Data
(ID,
Gnoga.Pointer_to_Connection_Data_Class (Data));
end Connection_Data;
function Connection_Data
(ID : in Gnoga.Connection_ID)
return Gnoga.Pointer_to_Connection_Data_Class
is
begin
return Connection_Manager.Connection_Data (ID);
end Connection_Data;
------------------------
-- On_Connect_Handler --
------------------------
procedure On_Connect_Handler (Event : in Connect_Event) is
begin
On_Connect_Event := Event;
end On_Connect_Handler;
---------------------
-- Connection_Type --
---------------------
function Connection_Type (ID : Gnoga.Connection_ID)
return Gnoga_Connection_Type
is
Socket : constant Socket_Type :=
Connection_Manager.Connection_Socket (ID);
begin
return Socket.Content.Connection_Type;
exception
when E : Connection_Error =>
Log ("Error Connection_Type -" & ID'Img);
Log (Ada.Exceptions.Exception_Information (E));
return None;
end Connection_Type;
---------------------
-- Connection_Path --
---------------------
function Connection_Path (ID : Gnoga.Connection_ID)
return String
is
use Ada.Strings.Unbounded;
Socket : constant Socket_Type :=
Connection_Manager.Connection_Socket (ID);
S : constant String := To_String (Socket.Content.Connection_Path);
begin
if Socket.Content.Connection_Type = Long_Polling then
return S;
else
if S = "" then
Socket.Content.Connection_Path :=
To_Unbounded_String (Left_Trim_Slashes
(Execute_Script
(ID, "window.location.pathname")));
return To_String (Socket.Content.Connection_Path);
else
return S;
end if;
end if;
exception
when E : Connection_Error =>
Log ("Error Connection_Path -" & ID'Img);
Log (Ada.Exceptions.Exception_Information (E));
return "";
end Connection_Path;
-------------------------------
-- Connection_Client_Address --
-------------------------------
function Connection_Client_Address (ID : Gnoga.Connection_ID)
return String
is
Socket : constant Socket_Type :=
Connection_Manager.Connection_Socket (ID);
Client_Address : constant GNAT.Sockets.Sock_Addr_Type := Get_Client_Address (Socket.all);
begin
return GNAT.Sockets.Image (Client_Address);
exception
when E : Connection_Error =>
Log ("Error Connection_Client_Address -" & ID'Img);
Log (Ada.Exceptions.Exception_Information (E));
return "";
end Connection_Client_Address;
------------------------
-- Active_Connections --
------------------------
function Active_Connections return Natural is
begin
return Natural (Connection_Manager.Active_Connections);
end Active_Connections;
-----------------------------
-- On_Post_Request_Handler --
-----------------------------
procedure On_Post_Request_Handler (Event : Post_Request_Event) is
begin
On_Post_Request_Event := Event;
end On_Post_Request_Handler;
---------------------
-- On_Post_Handler --
---------------------
procedure On_Post_Handler (Event : in Post_Event) is
begin
On_Post_Event := Event;
end On_Post_Handler;
--------------------------
-- On_Post_File_Handler --
--------------------------
procedure On_Post_File_Handler (Event : in Post_File_Event) is
begin
On_Post_File_Event := Event;
end On_Post_File_Handler;
--------------------
-- Form_Parameter --
--------------------
function Form_Parameter (ID : Gnoga.Connection_ID;
Name : String)
return String
is
begin
return Execute_Script (ID, "params['" & Name & "'];");
end Form_Parameter;
-----------
-- Valid --
-----------
function Valid (ID : Gnoga.Connection_ID) return Boolean is
begin
if ID = Gnoga.No_Connection then
return False;
else
return Connection_Manager.Valid (ID);
end if;
end Valid;
-----------
-- Close --
-----------
procedure Close (ID : Gnoga.Connection_ID) is
begin
if Valid (ID) then
declare
Socket : constant Socket_Type :=
Connection_Manager.Connection_Socket (ID);
begin
if Socket.Content.Connection_Type = Long_Polling then
Socket.Content.Finalized := True;
else
Execute_Script (ID, "ws.close()");
end if;
exception
when E : others =>
Log ("Error Close - " & ID'Img);
Log (Ada.Exceptions.Exception_Information (E));
end;
end if;
end Close;
-------------------
-- HTML_On_Close --
-------------------
procedure HTML_On_Close (ID : in Gnoga.Connection_ID;
HTML : in String)
is
begin
Execute_Script (ID => ID,
Script => "gnoga['html_on_close']='" &
Escape_Quotes (HTML) & "';");
end HTML_On_Close;
---------------------
-- ID_Machine_Type --
---------------------
protected type ID_Machine_Type is
procedure Next_ID (ID : out Gnoga.Unique_ID);
private
Current_ID : Gnoga.Unique_ID := 0;
end ID_Machine_Type;
protected body ID_Machine_Type is
procedure Next_ID (ID : out Gnoga.Unique_ID) is
begin
Current_ID := Current_ID + 1;
ID := Current_ID;
end Next_ID;
end ID_Machine_Type;
ID_Machine : ID_Machine_Type;
-------------------
-- New_Unique_ID --
-------------------
procedure New_Unique_ID (New_ID : out Gnoga.Unique_ID) is
begin
ID_Machine.Next_ID (New_ID);
end New_Unique_ID;
-------------
-- New_GID --
-------------
function New_GID return String is
New_ID : Gnoga.Unique_ID;
begin
New_Unique_ID (New_ID);
return "g" & Left_Trim (New_ID'Img);
end New_GID;
--------------------------
-- Add_To_Message_Queue --
--------------------------
procedure Add_To_Message_Queue
(Object : in out Gnoga.Gui.Base_Type'Class)
is
begin
Object_Manager.Insert (Object.Unique_ID, Object'Unchecked_Access);
end Add_To_Message_Queue;
-------------------------------
-- Delete_From_Message_Queue --
-------------------------------
procedure Delete_From_Message_Queue
(Object : in out Gnoga.Gui.Base_Type'Class) is
begin
Object_Manager.Delete (Object.Unique_ID);
end Delete_From_Message_Queue;
----------
-- Stop --
----------
procedure Stop is
ID : Gnoga.Connection_ID;
procedure Free is new Ada.Unchecked_Deallocation (Watchdog_Type, Watchdog_Access);
procedure Free is new Ada.Unchecked_Deallocation (Gnoga_HTTP_Server_Type, Gnoga_HTTP_Server_Access);
begin
if not Exit_Application_Requested and
Watchdog /= null and
Gnoga_HTTP_Server /= null
then
Exit_Application_Requested := True;
Watchdog.Stop;
Free (Watchdog);
Connection_Manager.First (ID);
while ID /= 0 loop
begin
Close (ID);
Connection_Manager.Next (ID);
exception
when others =>
Connection_Manager.First (ID);
end;
end loop;
Connection_Manager.Delete_All_Connections;
Gnoga_HTTP_Server.Stop;
Free (Gnoga_HTTP_Server);
end if;
end Stop;
-----------
-- Write --
-----------
procedure Write (Stream : access Ada.Streams.Root_Stream_Type'Class;
Item : in Gnoga_HTTP_Content)
is
begin
null;
end Write;
---------
-- Get --
---------
overriding
function Get (Source : access Gnoga_HTTP_Content) return String is
begin
if Source.Buffer.Length = 0 then
if Source.Connection_Type = HTTP then
return "";
elsif Source.Finalized then
declare
ID : constant Gnoga.Connection_ID :=
Connection_Manager.Find_Connection_ID
(Source.Socket);
begin
Gnoga.Log ("Shutting down long polling connection -" & ID'Img);
return "";
end;
else
raise Content_Not_Ready;
end if;
else
declare
use Ada.Strings.Unbounded;
Chunk_Size : constant := Max_HTTP_Output_Chunk - 80;
S : Ada.Strings.Unbounded.Unbounded_String;
begin
Source.Buffer.Get_And_Clear (S);
if Length (S) > Chunk_Size then
Source.Buffer.Preface (Slice (Source => S,
Low => 1 + Chunk_Size,
High => Length (S)));
return Slice (Source => S,
Low => 1,
High => Chunk_Size);
else
return To_String (S);
end if;
end;
end if;
end Get;
--------------
-- Finalize --
--------------
overriding
procedure Finalize (Client : in out Gnoga_HTTP_Client) is
ID : constant Gnoga.Connection_ID :=
Connection_Manager.Find_Connection_ID (Client'Unchecked_Access);
begin
if Ada.Streams.Stream_IO.Is_Open (Client.Content.FS) then
Ada.Streams.Stream_IO.Close (Client.Content.FS);
end if;
if ID /= Gnoga.No_Connection then
Gnoga.Log ("Deleting connection during finalize -" & ID'Img);
Connection_Manager.Delete_Connection (ID);
end if;
HTTP_Client (Client).Finalize;
exception
when E : others =>
Log ("Error Finalize Gnoga_HTTP_Client -" & ID'Img);
Log (Ada.Exceptions.Exception_Information (E));
end Finalize;
begin
Gnoga.Server.Connection.Common.Gnoga_Client_Factory :=
Global_Gnoga_Client_Factory'Access;
end Ada_GUI.Gnoga.Server.Connection;
|
pragma License (Unrestricted);
-- implementation unit specialized for Windows
with C.windef;
package System.Native_Time is
pragma Preelaborate;
-- representation
type Nanosecond_Number is
range -(2 ** (Duration'Size - 1)) .. 2 ** (Duration'Size - 1) - 1;
for Nanosecond_Number'Size use Duration'Size;
-- convert time span
function To_Duration (D : C.windef.FILETIME) return Duration;
pragma Pure_Function (To_Duration);
-- for delay
procedure Simple_Delay_For (D : Duration);
type Delay_For_Handler is access procedure (D : Duration);
pragma Favor_Top_Level (Delay_For_Handler);
-- equivalent to Timed_Delay (s-soflin.ads)
Delay_For_Hook : not null Delay_For_Handler := Simple_Delay_For'Access;
procedure Delay_For (D : Duration);
end System.Native_Time;
|
-- Abstract :
--
-- Trace output to Ada.Text_IO
--
-- Copyright (C) 2017, 2019, 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.Text_IO;
package WisiToken.Text_IO_Trace is
type Trace is limited new WisiToken.Trace with private;
-- Defaults to Ada.Text_IO.Standard_Output
overriding
procedure Set_Prefix (Trace : in out Text_IO_Trace.Trace; Prefix : in String);
overriding
procedure Put (Trace : in out Text_IO_Trace.Trace; Item : in String; Prefix : in Boolean := True);
overriding
procedure Put_Line (Trace : in out Text_IO_Trace.Trace; Item : in String);
-- If Item contains ASCII.LF, Prefix is output after each one.
overriding
procedure New_Line (Trace : in out Text_IO_Trace.Trace);
overriding
procedure Put_Clock (Trace : in out Text_IO_Trace.Trace; Label : in String);
procedure Set_File (Trace : in out Text_IO_Trace.Trace; File : in Ada.Text_IO.File_Access);
-- Set file for trace output. Default is Text_IO.Current_Output.
procedure Clear_File (Trace : in out Text_IO_Trace.Trace);
-- Clear internal file; output to Text_IO.Current_Output.
private
type Trace is limited new WisiToken.Trace with record
File : Ada.Text_IO.File_Access;
Prefix : Ada.Strings.Unbounded.Unbounded_String;
end record;
end WisiToken.Text_IO_Trace;
|
Pragma Ada_2012;
Pragma Wide_Character_Encoding( UTF8 );
Package Risi_Script.Types with Pure is
Enumeration_Prefix : Constant String:= "RT_";
------------------------------------
-- Main Type Forward Declarration --
------------------------------------
Type Extended_Enumeration;
Type Indicator;
Type Subprogram_Type;
------------------
-- MAIN TYPES --
------------------
Type Subprogram_Type is (RF_Function, RF_As_Procedure, RF_With_Procedure);
Type Extended_Enumeration is (
RT_Integer, RT_Array, RT_Hash, RT_String, RT_Real,
RT_Pointer, RT_Reference, RT_Fixed, RT_Boolean, RT_Func,
RT_Node
);
SubType Enumeration is Extended_Enumeration Range RT_Integer..RT_Func;
-- Defines the sigils that prefix variables.
Type Indicator is ('!', '@', '#', '$', '%',
'^', '&', '`', '?', 'ß')
with Object_Size => 8;
For Indicator use
(
'!' => Enumeration'Pos( RT_Integer ),
'@' => Enumeration'Pos( RT_Array ),
'#' => Enumeration'Pos( RT_Hash ),
'$' => Enumeration'Pos( RT_String ),
'%' => Enumeration'Pos( RT_Real ),
'^' => Enumeration'Pos( RT_Pointer ),
'&' => Enumeration'Pos( RT_Reference ),
'`' => Enumeration'Pos( RT_Fixed ),
'?' => Enumeration'Pos( RT_Boolean ),
'ß' => Enumeration'Pos( RT_Func )
);
Type Indicator_String is Array(Positive Range <>) of Indicator;
Function "+"( Right : Indicator_String ) Return String;
Function "+"( Right : Character ) return Indicator;
Function "+"( Right : Indicator ) return Character;
Function "+"( Right : Indicator ) return Enumeration;
Function "+"( Right : Enumeration ) return Indicator;
Function "+"( Right : Enumeration ) return Character;
Private
Function "+"( Right : Indicator_String ) Return String is
(case Right'Length is
When 0 => "",
When 1 => ( 1 => +Right(Right'First) ),
When others => (+Right(Right'First)) &
(+Right(Positive'Succ(Right'First)..Right'Last))
);
Function "+"( Right : Enumeration ) return Character is
( +(+Right) );
Function "+"( Right : Indicator ) return Enumeration is
( Enumeration'Val(Indicator'Pos( Right )) );
Function "+"( Right : Enumeration ) return Indicator is
( Indicator'Val(Enumeration'Pos( Right )) );
Function "+"( Right : Indicator ) return Character is
(case Right is
When '!' => '!',
When '@' => '@',
When '#' => '#',
When '$' => '$',
When '%' => '%',
When '^' => '^',
When '&' => '^',
When '`' => '`',
When '?' => '?',
When 'ß' => 'ß'
);
Function "+"( Right : Character ) return Indicator is
(case Right is
When '!' => '!',
When '@' => '@',
When '#' => '#',
When '$' => '$',
When '%' => '%',
When '^' => '^',
When '&' => '^',
When '`' => '`',
When '?' => '?',
When 'ß' => 'ß',
When others => Raise Parse_Error
with "Invalid type-sigil: '" & Right & "'."
);
End Risi_Script.Types;
|
with agar.core.types;
with agar.gui.surface;
with agar.gui.types;
package agar.gui.widget.icon is
use type c.unsigned;
subtype flags_t is agar.gui.types.widget_icon_flags_t;
ICON_REGEN_LABEL : constant flags_t := 16#01#;
ICON_DND : constant flags_t := 16#02#;
ICON_DBLCLICKED : constant flags_t := 16#04#;
ICON_BGFILL : constant flags_t := 16#08#;
subtype icon_t is agar.gui.types.widget_icon_t;
subtype icon_access_t is agar.gui.types.widget_icon_access_t;
-- API
function allocate
(parent : widget_access_t;
flags : flags_t) return icon_access_t;
pragma import (c, allocate, "AG_IconNew");
function allocate_from_surface
(surface : agar.gui.surface.surface_access_t) return icon_access_t;
pragma import (c, allocate_from_surface, "AG_IconFromSurface");
function allocate_from_bitmap
(filename : string) return icon_access_t;
pragma inline (allocate_from_bitmap);
-- procedure set_padding
-- (icon : icon_access_t;
-- left : natural;
-- right : natural;
-- top : natural;
-- bottom : natural);
-- pragma inline (set_padding);
procedure set_surface
(icon : icon_access_t;
surface : agar.gui.surface.surface_access_t);
pragma import (c, set_surface, "AG_IconSetSurface");
procedure set_surface_no_copy
(icon : icon_access_t;
surface : agar.gui.surface.surface_access_t);
pragma import (c, set_surface_no_copy, "AG_IconSetSurfaceNODUP");
procedure set_text
(icon : icon_access_t;
text : string);
pragma inline (set_text);
procedure set_background_fill
(icon : icon_access_t;
fill : boolean;
color : agar.core.types.uint32_t);
pragma inline (set_background_fill);
function widget (icon : icon_access_t) return widget_access_t renames
agar.gui.types.widget_icon_widget;
end agar.gui.widget.icon;
|
-- MIT License
--
-- Copyright (c) 2021 Glen Cornell <glen.m.cornell@gmail.com>
--
-- 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.
-- SETUP:
--
-- The Linux kernel must be compiled with support for SocketCAN
-- ("can" and "can_raw" modules) with a driver for your specific CAN
-- controller interface. There is a virtual CAN driver for testing
-- purposes which can be loaded and created in Linux with the
-- commands below.
--
-- $ modprobe can
-- $ modprobe can_raw
-- $ modprobe vcan
-- $ sudo ip link add dev vcan0 type vcan
-- $ sudo ip link set up vcan0
-- $ ip link show vcan0
-- 3: vcan0: <NOARP,UP,LOWER_UP> mtu 16 qdisc noqueue state UNKNOWN
-- link/can
--
-- EXAMPLES:
--
-- The following code snippet is a working example of the SocketCAN
-- API that sends a packet using the raw interface. It is based on
-- the notes documented in the Linux Kernel.
--
-- with Gnat.Sockets;
-- with Sockets.Can;
-- with Sockets.Can_Frame;
-- procedure Socketcan_Test is
-- Socket : Sockets.Can.Socket_Type;
-- Address : Sockets.Can.Sock_Addr_Type;
-- Frame : Sockets.Can_Frame.Can_Frame;
-- begin
-- Sockets.Can.Create_Socket(Socket);
-- Address.If_Index := Sockets.Can.If_Name_To_Index("vcan0");
-- Sockets.Can.Bind_Socket(Socket, Address);
-- frame.can_id := 16#123#;
-- frame.can_dlc := 2;
-- frame.Data(0) := 16#11#;
-- frame.Data(1) := 16#22#;
-- Sockets.Can.Send_Socket(Socket, Frame);
-- end Socketcan_Test;
--
-- The packet can be analyzed on the vcan0 interface using the
-- candump utility which is part of the SocketCAN can-utils package.
-- On another shell, type the following command to view the output of
-- the program ablve.
--
-- $ candump vcan0
-- vcan0 123 [2] 11 22
with Ada.Streams;
with Gnat.Sockets;
with Sockets.Can_Frame;
package Sockets.Can is
subtype Socket_Type is Gnat.Sockets.Socket_Type;
-- Sockets are used to implement a reliable bi-directional
-- point-to-point, datagram-based connection between
-- hosts.
subtype Request_Flag_Type is Gnat.Sockets.Request_Flag_Type;
No_Request_Flag : constant Request_Flag_Type := Gnat.Sockets.No_Request_Flag;
Socket_Error : exception;
-- There is only one exception in this package to deal with an error during
-- a socket routine. Once raised, its message contains a string describing
-- the error code.
type Family_Type is (Family_Can);
-- Address family (or protocol family) identifies the
-- communication domain and groups protocols with similar address
-- formats. This is represented as the "domain" parameter in the
-- socket(2) man page.
type Mode_Type is (Socket_Dgram, Socket_Raw);
type Protocol_Type is (Can_Raw, Can_Bcm);
type Sock_Addr_Type (Family : Family_Type := Family_Can) is record
case Family is
when Family_Can =>
If_Index : Natural := 0;
end case;
end record;
-- Socket addresses fully define a socket connection with protocol family,
-- an Internet address and a port.
-- CAN ID based filter in can_register().
-- Description:
-- A filter matches, when
--
-- <received_can_id> & mask == can_id & mask
--
-- The filter can be inverted (CAN_INV_FILTER bit set in can_id) or it can
-- filter for error message frames (CAN_ERR_FLAG bit set in mask).
type Can_Filter is record
Can_Id : aliased Can_Frame.Can_Id_Type; -- relevant bits of CAN ID which are not masked out.
Can_Mask : aliased Can_Frame.Can_Id_Type; -- CAN mask (see description)
end record;
type Can_Filter_Array_Type is array (Positive range <>) of Can_Filter;
function If_Name_To_Index (If_Name : String) return Natural;
-- Return the index for the given interface name. Raises
-- Socket_Error on error.
procedure Create_Socket
(Socket : out Socket_Type;
Family : in Family_Type := Family_Can;
Mode : in Mode_Type := Socket_Raw;
Protocol : in Protocol_Type := Can_Raw);
-- Create an endpoint for communication. Raises Socket_Error on error
procedure Bind_Socket
(Socket : Socket_Type;
Address : Sock_Addr_Type);
-- Once a socket is created, assign a local address to it. Raise
-- Socket_Error on error.
procedure Connect_Socket
(Socket : Socket_Type;
Address : Sock_Addr_Type);
-- Connect to a SOCK_DGRAM CAN socket. Raise Socket_Error on
-- error.
function Open (If_Name : String) return Socket_Type;
-- Convenience routine to create a socket and bind to a named
-- interface (eg: "can0"). This is the same as the following code
-- segment:
-- Sockets.Can.Create_Socket(Socket);
-- Address.If_Index := Sockets.Can.If_Name_To_Index("vcan0");
-- Sockets.Can.Bind_Socket(Socket, Address);
-- return Socket;
procedure Receive_Socket
(Socket : Socket_Type;
Item : out Sockets.Can_Frame.Can_Frame);
-- Convenience routine to receive a raw CAN frame from
-- Socket. Raise Socket_Error on error.
procedure Send_Socket
(Socket : Socket_Type;
Item : Sockets.Can_Frame.Can_Frame);
-- Convenience routine to transmit a raw CAN frame over a socket.
-- Raises Socket_Error on any detected error condition.
procedure Apply_Filters
(Socket : Socket_Type;
Filters : Can_Filter_Array_Type;
Are_Can_Fd_Frames_Enabled : Boolean := False);
-- Ask the kernel to filter inbound CAN packets on a given socket
-- (family_can, socket_raw) according to the supplied list.
-- Additionally, tell the kernel that you want to receive CAN FD
-- frames that match the given filters.
type Can_Stream is new Ada.Streams.Root_Stream_Type with private;
procedure Create_Stream (Stream : in out Can_Stream; Socket : Socket_Type);
-- Initialize the stream to the created socket.
procedure Open (Stream : in out Can_Stream; If_Name : in String);
-- Convenience routine to open a socketcan socket, bind to the raw
-- interface and create a can_stream object.
procedure Read (Stream : in out Can_Stream;
Item : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
-- Read data from the stream
procedure Write (Stream : in out Can_Stream;
Item : Ada.Streams.Stream_Element_Array);
-- Write data to the stream
procedure Flush_Read (Stream : in out Can_Stream);
-- Reset the read buffer
procedure Flush_Write (Stream : in out Can_Stream);
-- Send anything in the write buffer and reset it. If the write
-- buffer is empty, then no message is written to the CAN
-- interface.
procedure Raise_Socket_Error (Error : Integer);
-- Raise Socket_Error with an exception message describing the
-- error code from errno.
function Err_Code_Image (E : Integer) return String;
-- Return the value of E surrounded with brackets
private
pragma No_Component_Reordering (Sock_Addr_Type);
pragma Convention (C_Pass_By_Copy, Can_Filter);
pragma Convention (C, Can_Filter_Array_Type);
use type Ada.Streams.Stream_Element_Offset;
Sizeof_Frame : constant Ada.Streams.Stream_Element_Offset := (Sockets.Can_Frame.Can_Frame'Size + 7) / 8;
Read_Buffer_First : constant Ada.Streams.Stream_Element_Offset := 1;
Read_Buffer_Last : constant Ada.Streams.Stream_Element_Offset := Sizeof_Frame;
Write_Buffer_First : constant Ada.Streams.Stream_Element_Offset := 1;
Write_Buffer_Last : constant Ada.Streams.Stream_Element_Offset := Sizeof_Frame;
-- Read_Buffer_End is a sentinel one stream element beyond the
-- last element in the buffer, when the read_offset is set to
-- this, then the read_buffer is empty and we need to read another
-- CAN frame.
Read_Buffer_End : constant Ada.Streams.Stream_Element_Offset := Read_Buffer_Last + 1;
type Can_Stream is new Ada.Streams.Root_Stream_Type with record
Socket : Socket_Type := Gnat.Sockets.No_Socket;
Read_Buffer : aliased Ada.Streams.Stream_Element_Array (Read_Buffer_First .. Read_Buffer_Last);
Read_Offset : Ada.Streams.Stream_Element_Offset := Read_Buffer_End;
Write_Buffer : aliased Ada.Streams.Stream_Element_Array (Write_Buffer_First .. Write_Buffer_Last);
Write_Offset : Ada.Streams.Stream_Element_Offset := Write_Buffer_First;
end record;
end Sockets.Can;
|
-- { dg-do run }
-- { dg-options "-O2" }
procedure Opt5 is
type Varray is array (1 .. 4) of Natural;
procedure Check_All_Ones (A : Varray) is
begin
for J in A'Range loop
if (A (J)) /= 1 then
raise Program_Error;
end if;
end loop;
end;
X : constant Varray := (1, 1, 1, 1);
begin
Check_All_Ones (X);
end;
|
with Ada.Text_Io; use Ada.Text_Io;
with Interfaces; use Interfaces;
procedure Bitwise is
subtype Byte is Unsigned_8;
package Byte_Io is new Ada.Text_Io.Modular_Io(Byte);
A : Byte := 255;
B : Byte := 170;
X : Byte := 128;
N : Natural := 1;
begin
Put_Line("A and B = "); Byte_Io.Put(Item => A and B, Base => 2);
Put_Line("A or B = "); Byte_IO.Put(Item => A or B, Base => 2);
Put_Line("A xor B = "); Byte_Io.Put(Item => A xor B, Base => 2);
Put_Line("Not A = "); Byte_IO.Put(Item => not A, Base => 2);
New_Line(2);
Put_Line(Unsigned_8'Image(Shift_Left(X, N))); -- Left shift
Put_Line(Unsigned_8'Image(Shift_Right(X, N))); -- Right shift
Put_Line(Unsigned_8'Image(Shift_Right_Arithmetic(X, N))); -- Right Shift Arithmetic
Put_Line(Unsigned_8'Image(Rotate_Left(X, N))); -- Left rotate
Put_Line(Unsigned_8'Image(Rotate_Right(X, N))); -- Right rotate
end bitwise;
|
-----------------------------------------------------------------------
-- are-installer-bundles -- Merge bundles for distribution artifact
-- Copyright (C) 2013, 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.
-----------------------------------------------------------------------
-- == Install mode: bundles ==
-- The `Are.Installer.Bundles` package provides distribution rules
-- to merge a list of bundles to the distribution area. The rule is
-- created by using the following XML definition:
--
-- <install mode='bundles' source-timestamp='true'>
-- <fileset dir='bundles'>
-- <include name="**/*.properties"/>
-- </fileset>
-- </install>
--
private package Are.Installer.Bundles is
-- Create a distribution rule to concatenate a set of files.
function Create_Rule (Node : in DOM.Core.Node) return Distrib_Rule_Access;
-- ------------------------------
-- Distribution artifact
-- ------------------------------
type Bundle_Rule is new Distrib_Rule with private;
type Bundle_Rule_Access is access all Bundle_Rule'Class;
-- Get a name to qualify the installation rule (used for logs).
overriding
function Get_Install_Name (Rule : in Bundle_Rule) return String;
-- Install the file <b>File</b> according to the distribution rule.
-- Merge all the files listed in <b>Files</b> in the target path specified by <b>Path</b>.
overriding
procedure Install (Rule : in Bundle_Rule;
Path : in String;
Files : in File_Vector;
Context : in out Context_Type'Class);
private
type Bundle_Rule is new Distrib_Rule with null record;
end Are.Installer.Bundles;
|
with utils, ada.Text_IO; use utils, Ada.Text_IO;
package body read_preflop is
Function Get_Winning_Chance (card1 : T_card; card2 : T_card) return Float is
x,y : Integer;
Begin
if get_colour(card1) = get_colour(card2) then
y := integer'Min(get_rank(card1),get_rank(card2));
x := integer'Max(get_rank(card1),get_rank(card2));
else
x := integer'Min(get_rank(card1),get_rank(card2));
y := integer'Max(get_rank(card1),get_rank(card2));
end if;
return float(getFromArray(WIN_ARRAY,x,y)) / 2097572400.0;
end Get_Winning_Chance;
Function Get_Losing_Chance (card1 : T_card; card2 : T_card) return Float is
x,y : Integer;
Begin
if get_colour(card1) = get_colour(card2) then
y := integer'Min(get_rank(card1),get_rank(card2));
x := integer'Max(get_rank(card1),get_rank(card2));
else
x := integer'Min(get_rank(card1),get_rank(card2));
y := integer'Max(get_rank(card1),get_rank(card2));
end if;
return float(getFromArray(LOSE_ARRAY,x,y)) / 2097572400.0;
end Get_Losing_Chance;
Function Get_Tie_Chance (card1 : T_card; card2 : T_card) return Float is
x,y : Integer;
Begin
if get_colour(card1) = get_colour(card2) then
y := integer'Min(get_rank(card1),get_rank(card2));
x := integer'Max(get_rank(card1),get_rank(card2));
else
x := integer'Min(get_rank(card1),get_rank(card2));
y := integer'Max(get_rank(card1),get_rank(card2));
end if;
return float(getFromArray(TIE_ARRAY,x,y)) / 2097572400.0;
end Get_Tie_Chance;
function getFromArray(lst : T_array_chance; x : Integer; y : Integer) return Integer is
begin
return lst(13*(12-x)+(12-y));
end getFromArray;
end read_preflop;
|
package CompStats_Statistics is
type Values_Array is array (Integer range <>) of Float;
function Get_Count (Values : in Values_Array) return Integer;
function Get_Minimum (Values : in Values_Array) return Float;
function Get_Maximum (Values : Values_Array) return Float;
function Get_Range (Values : Values_Array) return Float;
function Get_Sum (Values : Values_Array) return Float;
function Get_Mean (Values : Values_Array) return Float;
function Get_Sum_Of_Squares (Values: Values_Array) return Float;
function Get_Population_Variance (Values: Values_Array) return Float;
function Get_Sample_Variance (Values: Values_Array) return Float;
function Get_Population_Standard_Deviation (Values: Values_Array) return Float;
function Get_Sample_Standard_Deviation (Values: Values_Array) return Float;
function Get_Standard_Error_Of_Mean (Values: Values_Array) return Float;
function Get_Coefficient_Of_Variation (Values: Values_Array) return Float;
function Get_Unique_Values (Values : Values_Array) return Values_Array;
-- function Get_Slice (Values : Values_Array) return Integer;
private
function Is_Value_In_Array (Values : Values_Array; Value : Float) return Boolean;
end CompStats_Statistics;
|
with Ada.Text_IO;
use Ada.Text_IO;
with kv.avm.Instructions;
procedure kv.avm.test_a is
x : instruction.overlay_type := (instruction.directive, instruction.no_op, false, false, 0);
begin
Put_Line("Hello there.");
end kv.avm.test_a;
|
pragma Ada_2012;
with Ada.Text_IO.Text_Streams;
with Ada.Streams;
with Ada.Streams.Stream_IO;
with Ada.Strings.Unbounded;
with Natools.Getopt_Long;
with Natools.String_Slices;
with Markup.Parsers.Markdown.Extensions;
with Instances;
with Markup.Parsers.Markdown.Extensions;
package body Generator.Markdown is
package Options is
type Action is (Error, Print_Help, Run);
type Input_Format is (Official, Discount, Special_Extended);
type Id is
(Discount_Input,
Help,
Markdown_Input,
Newline_Format,
Html_Output,
Special_Extended_Input,
Xhtml_Output);
package Getopt is new Natools.Getopt_Long (Id);
function Config return Getopt.Configuration;
function Value (Image : String)
return Instances.Html_Stream.Newline_Format;
type State is new Getopt.Handlers.Callback with record
Action : Options.Action := Run;
Arg_Count : Natural := 0;
Output_Format : Instances.Html_Stream.Output_Format
:= Instances.Html_Stream.Html;
Input_Format : Options.Input_Format := Official;
Newline_Format : Instances.Html_Stream.Newline_Format
:= Instances.Html_Stream.Autodetect;
end record;
overriding procedure Option
(Handler : in out State;
Id : Options.Id;
Argument : iString);
overriding procedure Argument
(Handler : in out State;
Argument : String);
end Options;
procedure Print_Help
(Config : Options.Getopt.Configuration;
Output : Ada.Text_IO.File_Type);
package body Options is
function Config return Getopt.Configuration is
use Getopt;
Result : Getopt.Configuration;
begin
Result.Add_Option ("discount", 'd', No_Argument, Discount_Input);
Result.Add_Option ("help", 'h', No_Argument, Help);
Result.Add_Option ("html", 'H', No_Argument, Html_Output);
Result.Add_Option ("markdown", 'm', No_Argument, Markdown_Input);
Result.Add_Option ("newline", 'n',
Required_Argument, Newline_Format);
Result.Add_Option ("nl",
Required_Argument, Newline_Format);
Result.Add_Option ("special", 's', No_Argument,
Special_Extended_Input);
Result.Add_Option ("xhtml", 'x', No_Argument, Xhtml_Output);
return Result;
end Config;
overriding procedure Option
(Handler : in out State;
Id : Options.Id;
Argument : String) is
begin
case Id is
when Discount_Input =>
Handler.Input_Format := Discount;
when Help =>
Handler.Action := Print_Help;
when Html_Output =>
Handler.Output_Format := Instances.Html_Stream.Html;
when Markdown_Input =>
Handler.Input_Format := Official;
when Newline_Format =>
begin
Handler.Newline_Format := Value (Argument);
exception
when Constraint_Error =>
Handler.Action := Error;
Ada.Text_IO.Put_Line
(Ada.Text_IO.Current_Error,
"Unable to parse newline format """ & Argument & '"');
end;
when Special_Extended_Input =>
Handler.Input_Format := Special_Extended;
when Xhtml_Output =>
Handler.Output_Format := Instances.Html_Stream.Xhtml;
end case;
end Option;
overriding procedure Argument
(Handler : in out State;
Argument : String) is
begin
if Handler.Action = Run then
-- Process_File (Argument);
Handler.Arg_Count := Handler.Arg_Count + 1;
end if;
end Argument;
function Value (Image : String)
return Instances.Html_Stream.Newline_Format
is
function Is_Autodetect return Boolean;
function Is_Autodetect return Boolean is
Reconstructed : constant String := "autodetect";
Length : constant Natural
:= Natural'Min (Image'Length, Reconstructed'Length);
use type Instances.Html_Stream.Newline_Format;
begin
Reconstructed
(Reconstructed'First .. Reconstructed'First + Length - 1)
:= Image (Image'First .. Image'First + Length - 1);
return Instances.Html_Stream.Newline_Format'Value (Reconstructed)
= Instances.Html_Stream.Autodetect;
exception
when Constraint_Error => return False;
end Is_Autodetect;
begin
if Is_Autodetect then
return Instances.Html_Stream.Autodetect;
end if;
case Image'Length is
when 5 =>
declare
Reconstructed : String (1 .. 5) := Image;
begin
Reconstructed (3) := '_';
return Instances.Html_Stream.Newline_Format'Value
(Reconstructed);
end;
when 4 =>
declare
Reconstructed : String (1 .. 5);
begin
Reconstructed (1 .. 2)
:= Image (Image'First .. Image'First + 1);
Reconstructed (3) := '_';
Reconstructed (4 .. 5)
:= Image (Image'Last - 1 .. Image'Last);
return Instances.Html_Stream.Newline_Format'Value
(Reconstructed);
end;
when 2 =>
return Instances.Html_Stream.Newline_Format'Value (Image);
when others =>
raise Constraint_Error;
end case;
end Value;
end Options;
procedure Print_Help
(Config : Options.Getopt.Configuration;
Output : Ada.Text_IO.File_Type)
is
use Ada.Text_IO;
Indent : constant String := " ";
begin
null;
end Print_Help;
Renderer : Instances.Html_Stream.Renderer_Ref;
Opt : Options.State;
function Make_Parser return Markup.Parsers.Markdown.Markdown_Parser'Class is
use type Options.Input_Format;
begin
return Parser : Markup.Parsers.Markdown.Extensions.Extended_Parser do
Parser.Atx_Header (Renderer.Header);
Parser.Code_Block (Renderer.Code_Block);
Parser.Horizontal_Rule (Renderer.Horizontal_Rule);
Parser.Html_Block (Renderer.Raw_Html_Block);
Parser.Html_Tag_Block (Renderer.Raw_Html_Block);
Parser.Html_Comment_Block (Renderer.Raw_Html_Block);
Parser.List (Renderer.Ordered_List, Renderer.List_Item,
Markup.Parsers.Markdown.Styles.Ordered);
Parser.List (Renderer.Unordered_List, Renderer.List_Item,
Markup.Parsers.Markdown.Styles.Unordered);
Parser.Paragraph (Renderer.Paragraph);
Parser.Quote_Block (Renderer.Quote_Block);
Parser.Setext_Header (Renderer.Header);
Parser.Emphasis (Renderer.Emphasis, 1);
Parser.Emphasis (Renderer.Strong, 2);
Parser.Emphasis (Renderer.Strong_Emphasis, 3);
Parser.Entity (Renderer.Raw_Html_Span);
Parser.Escape (Renderer.Raw_Text_Span);
Parser.Code_Span (Renderer.Code_Span);
Parser.Discount_Image (Renderer.Image);
Parser.Auto_Link (Renderer.Anchor);
Parser.Html_Span (Renderer.Raw_Html_Span);
if Opt.Input_Format < Options.Discount then
return;
end if;
Parser.Discount_Definition_List
(Renderer.Definition_List,
Renderer.Definition_Title,
Renderer.Definition_Description);
Parser.PME_Definition_List
(Renderer.Definition_List,
Renderer.Definition_Title,
Renderer.Definition_Description);
Parser.PME_Table
(Renderer.Table,
Renderer.Table_Row,
Renderer.Table_Header_Cell,
Renderer.Table_Data_Cell);
Parser.Discount_Centered (Renderer.Paragraph);
Parser.Discount_Class_Block (Renderer.Division);
Parser.Discount_Fenced_Code_Block (Renderer.Code_Block);
Parser.Pseudoprotocol_Link (Renderer.Anchor);
Parser.Pseudoprotocol_Abbr (Renderer.Abbreviation);
Parser.Pseudoprotocol_Class (Renderer.Span);
Parser.Pseudoprotocol_Id (Renderer.Anchor);
Parser.Pseudoprotocol_Raw (Renderer.Raw_Html_Span);
if Opt.Input_Format < Options.Special_Extended then
return;
end if;
Parser.Atx_Header_With_Id (Renderer.Header);
Parser.Paragraph_With_Class (Renderer.Paragraph, '(', ')');
Parser.Emphasis (Renderer.Deleted, 2, "-");
Parser.Emphasis (Renderer.Inserted, 2, "+");
Parser.Emphasis (Renderer.Span, 1, "|");
end return;
end Make_Parser;
procedure Process_Stream
(Input : in out Ada.Streams.Root_Stream_Type'Class)
is
Text : Natools.String_Slices.Slice;
begin
Renderer.Set_Format (Opt.Output_Format);
Renderer.Set_Newline (Opt.Newline_Format);
Read_Text : declare
use Ada.Streams;
Chunk : Stream_Element_Array (1 .. 1024);
Chunk_As_String : String (1 .. 1024);
for Chunk_As_String'Address use Chunk'Address;
Last : Stream_Element_Offset;
Input_Text : Ada.Strings.Unbounded.Unbounded_String;
begin
loop
Input.Read (Chunk, Last);
exit when Last + 1 = Chunk'First;
Ada.Strings.Unbounded.Append
(Input_Text, Chunk_As_String (1 .. Positive (Last)));
exit when Last < Chunk'Last;
end loop;
Text := Natools.String_Slices.To_Slice
(Ada.Strings.Unbounded.To_String (Input_Text));
end Read_Text;
Process_Text : declare
Parser : Markup.Parsers.Markdown.Markdown_Parser'Class := Make_Parser;
begin
Parser.Process (Text);
end Process_Text;
end Process_Stream;
-------------
-- To_HTML --
-------------
procedure To_HTML (Filein : in out Ada.Streams.Stream_IO.File_Type) is
begin
Process_Stream (Ada.Streams.Stream_IO.Stream (Filein).all);
Ada.Streams.Stream_IO.Close (Filein);
end To_HTML;
end Generator.Markdown;
|
with System;
package body TLV is
type Base_Type is (Base_Integer, Base_Float, Base_String, Base_Sequence)
with Size => 2;
for Base_Type use (
Base_Integer => 0,
Base_Float => 1,
Base_String => 2,
Base_Sequence => 3);
type Tag_Value_Type is new Integer range 0 .. 63 with Size => 6;
type Tag_Specifier (As_Value : Boolean := False) is
record
case As_Value is
when True =>
Val : Byte;
when False =>
Base : UInt2;
Value : UInt6;
end case;
end record
with Unchecked_Union, Size => 8, Bit_Order => System.Low_Order_First;
for Tag_Specifier use
record
Base at 0 range 6 .. 7;
Value at 0 range 0 .. 5;
end record;
procedure Encode (Tag : Tag_Type; Value : Integer;
Buffer : in out Buffer_Type; Position : in out Buffer_Size_Type) is
begin
Buffer (Position) := Tag'Enum_Rep;
Buffer (Position + 1) := 1;
Buffer (Position + 2) := 0;
Position := Position + 6;
end Encode;
procedure Encode (Tag : Tag_Type; Value : String;
Buffer : in out Buffer_Type; Position : in out Buffer_Size_Type) is
begin
Buffer (Position) := Tag'Enum_Rep;
Buffer (Position + 1) := 1;
Position := Position + 2;
for C of Value loop
Buffer (Position) := Character'Pos (C);
Position := Position + 1;
end loop;
end Encode;
procedure Encode (Tag : Tag_Type; Value : Short_Float;
Buffer : in out Buffer_Type; Position : in out Buffer_Size_Type) is
begin
Buffer (Position) := Tag'Enum_Rep;
Buffer (Position + 1) := 1;
Buffer (Position + 2) := 0;
Position := Position + 6;
end Encode;
procedure Start_Sequence (
Tag : Tag_Type;
Buffer : in out Buffer_Type;
Length_Position : out Buffer_Size_Type;
Position : in out Buffer_Size_Type) is
begin
Buffer (Position) := Tag'Enum_Rep;
Length_Position := Position + 1;
Position := Position + 2;
end Start_Sequence;
procedure End_Sequence (
Buffer : in out Buffer_Type;
Length_Position : in Buffer_Size_Type;
Position : in out Buffer_Size_Type) is
begin
Buffer (Length_Position) := Byte (Position - Length_Position - 1);
end End_Sequence;
end TLV;
|
with Text_IO;
use Text_IO;
with Ada.Integer_Text_IO;
use Ada.Integer_Text_IO;
-- Afficher le plus petit et le plus grand élément d'une série d'entiers
-- naturels lus au clavier. La saisie de la série se termine par 0
-- (qui n'appartient pas à la série).
-- Exemple : 2, 9, 3, 6, 3, 0 -> min = 2 et max = 9
procedure Min_Max_Serie is
Entier: Integer; -- un entier lu au clavier
Min, Max: Integer; -- le plus petit et le plus grand élément de la série
begin
-- Afficher la consigne
Put("Saisir les valeurs de la série (-1 pour terminer) : ");
-- Saisir un premier entier
Put("Saisir les valeurs de la série (-1 pour terminer) : ");
Get(Entier);
if Entier = 0 then --{ entier n'est pas une valeur de la série }
Put_Line("Pas de valeurs dans la série");
else -- Entier est le premier élément de la série
-- initialiser Min et Max avec le premier entier
Min := Entier;
Max := Entier;
-- traiter les autres éléments de la série
Get(Entier); -- saisir un nouvel entier
while Entier /= 0 loop -- Entier est une valeur de la série
-- mettre à jour le Min et le Max
if Entier > Max then -- nouveau max
-- mettre à jour le max avec Entier
Max := Entier;
elsif Entier < Min then -- nouveau Min
-- mettre à jour le min avec Entier
Min := Entier;
else
null;
end if;
-- saisir un nouvel entier
Get(Entier);
end loop;
-- afficher le min et le max de la série
Put("Min = ");
Put(Min, 1);
New_Line;
Put_Line("Max =" & Integer'Image(Max));
end if;
end Min_Max_Serie;
|
------------------------------------------------------------------------------
-- --
-- Common UUID Handling Package --
-- - RFC 4122 Implementation - --
-- --
-- ------------------------------------------------------------------------ --
-- --
-- Version 5 (SHA-1 Name-Based) UUID Generation Package --
-- --
-- ------------------------------------------------------------------------ --
-- --
-- Copyright (C) 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 ANNEXI-STRAYLINE 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 ANNEXI-STRAYLINE --
-- BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR --
-- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF --
-- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR --
-- BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, --
-- WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR --
-- OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF --
-- ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with Interfaces; use Interfaces;
with Modular_Hashing.SHA1; use Modular_Hashing, Modular_Hashing.SHA1;
function UUIDs.Version_5 (Namespace: UUIDs.UUID; Name: String)
return UUIDs.UUID
is
Engine : aliased SHA1_Engine;
Name_Hash : SHA1_Hash;
Name_Hash_Binary_LE: Hash_Binary_Value (1 .. SHA1_Hash_Bytes);
Accumulator: Unsigned_64;
Result: UUID;
begin
-- From RFC 4122:
-- The algorithm for generating a UUID from a name and a name space are
-- as follows:
-- o Allocate a UUID to use as a "name space ID" for all UUIDs
-- generated from names in that name space; see Appendix C for some
-- pre-defined values.
-- => User-supplied by the Namespace parameter
-- o Choose either MD5 [4] or SHA-1 [8] as the hash algorithm; If
-- backward compatibility is not an issue, SHA-1 is preferred.
-- => Version 5 mandates SHA-1
-- o Convert the name to a canonical sequence of octets (as defined by
-- the standards or conventions of its name space); put the name
-- space ID in network byte order.
-- => This is done implicitly. Name is a String, which is should always
-- be an array of octets. When we stream Namespace to the Hash engine,
-- it will be in "network byte order" (big endian)
-- o Compute the hash of the name space ID concatenated with the name.
UUID'Write (Engine'Access, Namespace);
String'Write (Engine'Access, Name);
Name_Hash := SHA1_Hash (Engine.Digest);
Name_Hash_Binary_LE := Name_Hash.Binary; -- This is little endian
-- Note
-- ----
--
-- The way the RFC describes this is really awkward, with a switch between
-- network byte order and local byte order all over the place. Only by
-- looking at the reference implementation can we see that the (big endian)
-- hash first (most significant) 16 octets of the SHA1 hash is direcly
-- overlayed ontop of the binary UUID, for which each feild is then
-- converted to local host order.
--
-- What this really means is that the conversions cancel eachother out,
-- and if we consider a binary UUID in big endian, the BE SHA1 hash is
-- just dropped ontop of it, with a few bits twiddled.
-- o Set octets zero through 3 of the time_low field to octets zero
-- through 3 of the hash.
Accumulator := 0;
for Octet of reverse
Name_Hash_Binary_LE (SHA1_Hash_Bytes - 3 .. SHA1_Hash_Bytes - 0)
loop
Accumulator := Shift_Left (Value => Accumulator, Amount => 8);
Accumulator := Accumulator + Unsigned_64 (Octet);
end loop;
Result.time_low := Bitfield_32 (Accumulator);
-- o Set octets zero and one of the time_mid field to octets 4 and 5 of
-- the hash.
Accumulator := 0;
for Octet of reverse
Name_Hash_Binary_LE (SHA1_Hash_Bytes - 5 .. SHA1_Hash_Bytes - 4)
loop
Accumulator := Shift_Left (Value => Accumulator, Amount => 8);
Accumulator := Accumulator + Unsigned_64 (Octet);
end loop;
Result.time_mid := Bitfield_16 (Accumulator);
-- o Set octets zero and one of the time_hi_and_version field to octets
-- 6 and 7 of the hash.
Accumulator := 0;
for Octet of reverse
Name_Hash_Binary_LE (SHA1_Hash_Bytes - 7 .. SHA1_Hash_Bytes - 6)
loop
Accumulator := Shift_Left (Value => Accumulator, Amount => 8);
Accumulator := Accumulator + Unsigned_64 (Octet);
end loop;
Result.time_hi_and_version := Bitfield_16 (Accumulator);
-- o Set the four most significant bits (bits 12 through 15) of the
-- time_hi_and_version field to the appropriate 4-bit version number
-- from Section 4.1.3.
Result.time_hi_and_version
:= (Result.time_hi_and_version and 16#0FFF#) + 16#5000#;
-- o Set the clock_seq_hi_and_reserved field to octet 8 of the hash.
--
-- o Set the two most significant bits (bits 6 and 7) of the
-- clock_seq_hi_and_reserved to zero and one, respectively.
Result.clock_seq_hi_and_reserved
:= (Bitfield_8 (Name_Hash_Binary_LE(SHA1_Hash_Bytes - 8))
and 2#0011_1111#) + 2#1000_0000#;
-- o Set the clock_seq_low field to octet 9 of the hash.
Result.clock_seq_low
:= Bitfield_8 (Name_Hash_Binary_LE(SHA1_Hash_Bytes - 9));
-- o Set octets zero through five of the node field to octets 10
-- through 15 of the hash.
Accumulator := 0;
for Octet of reverse
Name_Hash_Binary_LE (SHA1_Hash_Bytes - 15 .. SHA1_Hash_Bytes - 10)
loop
Accumulator := Shift_Left (Value => Accumulator, Amount => 8);
Accumulator := Accumulator + Unsigned_64 (Octet);
end loop;
Result.node := Bitfield_48 (Accumulator);
-- o Convert the resulting UUID to local byte order.
--
-- => This is done implicitly by UUID'Write, but otherwise the fields are
-- stored distinctly
return Result;
end UUIDs.Version_5;
|
function Diff (Left, Right : Image) return Float is
Offs_I : constant Integer := Right'First (1) - Left'First (1);
Offs_J : constant Integer := Right'First (2) - Left'First (2);
Sum : Count := 0;
begin
if Left'Length (1) /= Right'Length (1) or else Left'Length (2) /= Right'Length (2) then
raise Constraint_Error;
end if;
for I in Left'Range (1) loop
for J in Left'Range (2) loop
Sum := Sum + (Left (I, J) - Right (I + Offs_I, J + Offs_J));
end loop;
end loop;
return Float (Sum) / (3.0 * Float (Left'Length (1) * Left'Length (2)));
end Diff;
|
package body System.UTF_Conversions is
pragma Suppress (All_Checks);
procedure unreachable
with Import,
Convention => Intrinsic, External_Name => "__builtin_unreachable";
pragma No_Return (unreachable);
procedure UTF_8_Length (
Code : UCS_4;
Leading : out Character;
Length : out Natural;
Status : out Sequence_Status_Type);
procedure UTF_8_Length (
Code : UCS_4;
Leading : out Character;
Length : out Natural;
Status : out Sequence_Status_Type) is
begin
case Code is
when 0 .. 16#7f# =>
Leading := Character'Val (Code);
Length := 1;
Status := Success;
when 16#80# .. 2 ** (5 + 6) - 1 =>
Leading := Character'Val (2#11000000# or Code / (2 ** 6));
Length := 2;
Status := Success;
when 16#d800# .. 16#dfff# =>
Leading := Character'Val (2#11100000# or Code / (2 ** 12));
Length := 3;
Status := Illegal_Sequence; -- range of surrogate pair
when 2 ** (5 + 6) .. 16#d7ff# | 16#e000# .. 2 ** (4 + 6 + 6) - 1 =>
Leading := Character'Val (2#11100000# or Code / (2 ** 12));
Length := 3;
Status := Success;
when 2 ** (4 + 6 + 6) .. 2 ** (3 + 6 + 6 + 6) - 1 =>
Leading := Character'Val (2#11110000# or Code / (2 ** 18));
Length := 4;
Status := Success;
when 2 ** (3 + 6 + 6 + 6) .. 2 ** (2 + 6 + 6 + 6 + 6) - 1 =>
Leading := Character'Val (2#11111000# or Code / (2 ** 24));
Length := 5;
Status := Success;
when 2 ** (2 + 6 + 6 + 6 + 6) .. 2 ** (1 + 6 + 6 + 6 + 6 + 6) - 1 =>
Leading := Character'Val (2#11111100# or Code / (2 ** 30));
Length := 6;
Status := Success;
end case;
end UTF_8_Length;
-- implementation
procedure To_UTF_8 (
Code : UCS_4;
Result : out String;
Last : out Natural;
Status : out To_Status_Type)
is
I : constant Natural := Result'First;
Length : Natural;
Code_2 : UCS_4;
-- without checking surrogate pair in To_XXX
begin
if I > Result'Last then
Last := Result'Last;
Status := Overflow;
return; -- error
end if;
declare
Dummy_Sequence_Status : Sequence_Status_Type;
begin
UTF_8_Length (Code, Result (I), Length, Dummy_Sequence_Status);
end;
Code_2 := Code;
if I > Result'Last - (Length - 1) then
declare
Shortage : constant Positive := Length - 1 - (Result'Last - I);
Offset : constant Positive := 6 * Shortage;
begin
if Offset not in 6 .. 30 then
unreachable;
end if;
Code_2 := Code_2 / (2 ** Offset);
end;
Length := Result'Last - I + 1;
Last := Result'Last;
Status := Overflow;
else
Last := I + (Length - 1);
Status := Success;
end if;
for J in reverse 1 .. Length - 1 loop
Result (I + J) :=
Character'Val (2#10000000# or (Code_2 and (2 ** 6 - 1)));
Code_2 := Code_2 / (2 ** 6);
end loop;
end To_UTF_8;
procedure From_UTF_8 (
Data : String;
Last : out Natural;
Result : out UCS_4;
Status : out From_Status_Type)
is
I : Natural := Data'First;
First : constant Character := Data (I);
Trail : Character;
Length : Natural;
Shortest_Leading : Character;
Shortest_Length : Natural;
Code : UCS_4;
begin
Status := Success;
-- leading byte
case First is
when Character'Val (2#00000000#) .. Character'Val (2#01111111#) =>
Last := I;
Result := Character'Pos (First);
return;
when Character'Val (2#11000000#) .. Character'Val (2#11011111#) =>
Code := Character'Pos (First) and 2#00011111#;
Length := 2;
when Character'Val (2#11100000#) .. Character'Val (2#11101111#) =>
Code := Character'Pos (First) and 2#00001111#;
Length := 3;
when Character'Val (2#11110000#) .. Character'Val (2#11110111#) =>
Code := Character'Pos (First) and 2#00000111#;
Length := 4;
when Character'Val (2#11111000#) .. Character'Val (2#11111011#) =>
Code := Character'Pos (First) and 2#00000011#;
Length := 5;
when Character'Val (2#11111100#) .. Character'Val (2#11111101#) =>
Code := Character'Pos (First) and 2#00000001#;
Length := 6;
when others =>
Last := I;
Result := Character'Pos (First) + (UCS_4'Last - 16#ff#); -- dummy
Status := Illegal_Sequence; -- trailing byte or invalid code
return; -- error
end case;
-- trailing bytes
for J in reverse 1 .. Length - 1 loop
if I >= Data'Last then
Code := Code * 2 ** (6 * J);
Status := Truncated; -- trailing byte is nothing
exit;
else
I := I + 1;
Trail := Data (I);
if Trail not in
Character'Val (2#10000000#) .. Character'Val (2#10111111#)
then
I := I - 1;
Code := Code * 2 ** (6 * J);
Status := Illegal_Sequence; -- trailing byte is invalid
exit;
end if;
end if;
Code := Code * (2 ** 6) or (Character'Pos (Trail) and (2 ** 6 - 1));
end loop;
if Status = Success then
UTF_8_Length (
Code,
Shortest_Leading,
Shortest_Length,
Status); -- set Illegal_Sequence if surrogate pair
if Length > Shortest_Length then
Status := Non_Shortest;
end if;
end if;
Last := I;
Result := Code;
end From_UTF_8;
procedure From_UTF_8_Reverse (
Data : String;
First : out Positive;
Result : out UCS_4;
Status : out From_Status_Type)
is
Last : Natural;
begin
First := Data'Last;
while Data (First) in
Character'Val (2#10000000#) .. Character'Val (2#10111111#)
loop
if First = Data'First then
First := Data'Last; -- take 1 element
Result := Character'Pos (Data (First)) + (UCS_4'Last - 16#ff#);
Status := Truncated;
return; -- error
elsif Data'Last - First + 1 = 6 then
First := Data'Last; -- take 1 element
Result := Character'Pos (Data (First)) + (UCS_4'Last - 16#ff#);
Status := Illegal_Sequence;
return; -- error
end if;
First := First - 1;
end loop;
From_UTF_8 (Data (First .. Data'Last), Last, Result, Status);
if Last /= Data'Last then
First := Data'Last;
Result := Character'Pos (Data (First)) + (UCS_4'Last - 16#ff#);
Status := Illegal_Sequence; -- not Truncated
end if;
end From_UTF_8_Reverse;
procedure UTF_8_Sequence (
Leading : Character;
Result : out Positive;
Status : out Sequence_Status_Type) is
begin
case Leading is
when Character'Val (2#00000000#) .. Character'Val (2#01111111#) =>
Result := 1;
Status := Success;
when Character'Val (2#11000000#) .. Character'Val (2#11011111#) =>
Result := 2;
Status := Success;
when Character'Val (2#11100000#) .. Character'Val (2#11101111#) =>
Result := 3;
Status := Success;
when Character'Val (2#11110000#) .. Character'Val (2#11110111#) =>
Result := 4;
Status := Success;
when Character'Val (2#11111000#) .. Character'Val (2#11111011#) =>
Result := 5;
Status := Success;
when Character'Val (2#11111100#) .. Character'Val (2#11111101#) =>
Result := 6;
Status := Success;
when others =>
Result := 1;
Status := Illegal_Sequence; -- trailing byte or invalid code
end case;
end UTF_8_Sequence;
procedure To_UTF_16 (
Code : UCS_4;
Result : out Wide_String;
Last : out Natural;
Status : out To_Status_Type) is
begin
case Code is
when 16#0000# .. 16#d7ff#
| 16#d800# .. 16#dfff# -- without checking surrogate pair in To_XXX
| 16#e000# .. 16#ffff# =>
Last := Result'First;
if Last <= Result'Last then
Result (Last) := Wide_Character'Val (Code);
Status := Success;
else
Last := Result'Last;
Status := Overflow;
end if;
when 16#00010000# .. UCS_4'Last =>
Last := Result'First;
if Last <= Result'Last then
declare
Code_2 : UCS_4 := Code - 16#00010000#;
begin
if Code_2 >= 2 ** 20 then -- over range of UTF-16
Code_2 := 2 ** 20 - 1; -- dummy
Status := Unmappable;
else
Status := Success;
end if;
Result (Last) := Wide_Character'Val (
16#d800# or ((Code_2 / (2 ** 10)) and (2 ** 10 - 1)));
if Last <= Result'Last - 1 then
Last := Last + 1;
Result (Last) := Wide_Character'Val (
16#dc00# or (Code_2 and (2 ** 10 - 1)));
else
Status := Overflow;
end if;
end;
else
Last := Result'Last;
Status := Overflow;
end if;
end case;
end To_UTF_16;
procedure From_UTF_16 (
Data : Wide_String;
Last : out Natural;
Result : out UCS_4;
Status : out From_Status_Type)
is
I : Natural := Data'First;
First : constant Wide_Character := Data (I);
begin
case First is
when Wide_Character'Val (16#0000#) .. Wide_Character'Val (16#d7ff#)
| Wide_Character'Val (16#e000#) .. Wide_Character'Val (16#ffff#) =>
Last := I;
Result := Wide_Character'Pos (First);
Status := Success;
when Wide_Character'Val (16#d800#) .. Wide_Character'Val (16#dbff#) =>
declare
Second : Wide_Character;
begin
if I >= Data'Last then
Status := Truncated; -- trailing byte is nothing
Second := Wide_Character'Val (0);
else
I := I + 1;
Second := Data (I);
if Second not in
Wide_Character'Val (16#dc00#) ..
Wide_Character'Val (16#dfff#)
then
I := I - 1;
Second := Wide_Character'Val (0);
Status := Illegal_Sequence; -- trailing byte is invalid
else
Status := Success;
end if;
end if;
Last := I;
declare
High : constant UCS_4 :=
Wide_Character'Pos (First) and (2 ** 10 - 1);
Low : constant UCS_4 :=
Wide_Character'Pos (Second) and (2 ** 10 - 1);
begin
Result := ((High * (2 ** 10)) or Low) + 16#00010000#;
end;
end;
when Wide_Character'Val (16#dc00#) .. Wide_Character'Val (16#dfff#) =>
Last := I;
Result := Wide_Character'Pos (First);
Status := Illegal_Sequence; -- trailing byte
end case;
end From_UTF_16;
procedure From_UTF_16_Reverse (
Data : Wide_String;
First : out Positive;
Result : out UCS_4;
Status : out From_Status_Type)
is
Last : Natural; -- ignore
begin
if Data (Data'Last) in
Wide_Character'Val (16#dc00#) .. Wide_Character'Val (16#dfff#)
then
if Data'First < Data'Last
and then Data (Data'Last - 1) in
Wide_Character'Val (16#d800#) .. Wide_Character'Val (16#dbff#)
then
First := Data'Last - 1;
else
First := Data'Last;
Result := Wide_Character'Pos (Data (First));
Status := Truncated;
return; -- error
end if;
else
First := Data'Last;
end if;
From_UTF_16 (Data (First .. Data'Last), Last, Result, Status);
end From_UTF_16_Reverse;
procedure UTF_16_Sequence (
Leading : Wide_Character;
Result : out Positive;
Status : out Sequence_Status_Type) is
begin
case Leading is
when Wide_Character'Val (16#0000#) .. Wide_Character'Val (16#d7ff#)
| Wide_Character'Val (16#e000#) .. Wide_Character'Val (16#ffff#) =>
Result := 1;
Status := Success;
when Wide_Character'Val (16#d800#) .. Wide_Character'Val (16#dbff#) =>
Result := 2;
Status := Success;
when Wide_Character'Val (16#dc00#) .. Wide_Character'Val (16#dfff#) =>
Result := 1;
Status := Illegal_Sequence; -- trailing byte
end case;
end UTF_16_Sequence;
procedure To_UTF_32 (
Code : UCS_4;
Result : out Wide_Wide_String;
Last : out Natural;
Status : out To_Status_Type) is
begin
Last := Result'First;
if Last <= Result'Last then
Result (Last) := Wide_Wide_Character'Val (Code);
Status := Success;
else
Last := Result'Last;
Status := Overflow;
end if;
end To_UTF_32;
procedure From_UTF_32 (
Data : Wide_Wide_String;
Last : out Natural;
Result : out UCS_4;
Status : out From_Status_Type)
is
type Unsigned_32 is mod 2 ** Wide_Wide_Character'Size;
Code : constant Unsigned_32 :=
Wide_Wide_Character'Pos (Data (Data'First));
begin
Last := Data'First;
Result := UCS_4'Mod (Code);
case Code is
when 16#d800# .. 16#dfff# | 16#80000000# .. 16#ffffffff# =>
Status := Illegal_Sequence;
when others =>
Status := Success;
end case;
end From_UTF_32;
procedure From_UTF_32_Reverse (
Data : Wide_Wide_String;
First : out Positive;
Result : out UCS_4;
Status : out From_Status_Type)
is
Last : Natural; -- ignored
begin
First := Data'Last;
From_UTF_32 (Data (First .. Data'Last), Last, Result, Status);
end From_UTF_32_Reverse;
procedure UTF_32_Sequence (
Leading : Wide_Wide_Character;
Result : out Positive;
Status : out Sequence_Status_Type) is
begin
Result := 1;
case Wide_Wide_Character'Pos (Leading) is
when 16#d800# .. 16#dfff# | 16#80000000# .. 16#ffffffff# =>
Status := Illegal_Sequence;
when others =>
Status := Success;
end case;
end UTF_32_Sequence;
procedure Convert_Procedure (
Source : Source_Type;
Result : out Target_Type;
Last : out Natural;
Substitute : Target_Type :=
(1 => Target_Element_Type'Val (Character'Pos ('?'))))
is
Source_Last : Natural := Source'First - 1;
begin
Last := Result'First - 1;
while Source_Last < Source'Last loop
declare
Code : UCS_4;
From_Status : From_Status_Type;
To_Status : To_Status_Type; -- ignore
begin
From_UTF (
Source (Source_Last + 1 .. Source'Last),
Source_Last,
Code,
From_Status);
if From_Status /= Success then
declare
Substitute_Length : constant Natural := Substitute'Length;
begin
Result (Last + 1 .. Last + Substitute_Length) := Substitute;
Last := Last + Substitute_Length;
end;
else
To_UTF (
Code,
Result (Last + 1 .. Result'Last),
Last,
To_Status);
-- ignore error
end if;
end;
end loop;
end Convert_Procedure;
function Convert_Function (
Source : Source_Type;
Substitute : Target_Type :=
(1 => Target_Element_Type'Val (Character'Pos ('?'))))
return Target_Type
is
Result : Target_Type (
1 ..
Source'Length * Integer'Max (Expanding, Substitute'Length));
Last : Natural;
begin
Convert_Procedure (Source, Result, Last, Substitute);
return Result (1 .. Last);
end Convert_Function;
end System.UTF_Conversions;
|
--
-- The author disclaims copyright to this source code. In place of
-- a legal notice, here is a blessing:
--
-- May you do good and not evil.
-- May you find forgiveness for yourself and forgive others.
-- May you share freely, not taking more than you give.
--
with Ada.Strings.Unbounded;
with Ada.Text_IO;
with Types;
package Errors is
use Ada.Strings.Unbounded;
subtype Line_Number is Types.Line_Number;
Default_File_Name : Unbounded_String := To_Unbounded_String ("<null>");
Error_Count : Natural := 0;
type Error_Id is
(E001,
E002,
E003,
E004,
E005,
E006,
E007,
E008,
E009,
E010,
E011,
E012,
E013,
E014,
E015,
E016,
E101,
E102,
E103,
E201,
E202,
E203,
E204,
E205,
E206,
E207,
E208,
E209,
E210,
E211,
E212,
E213,
E214,
E215,
E216,
E217,
E218,
E301,
E401
);
procedure Set_File_Name
(File_Name : in Ada.Strings.Unbounded.Unbounded_String);
procedure Parser_Error
(Id : in Error_Id;
Line : in Line_Number;
Argument_1 : in String := "";
Argument_2 : in String := "");
procedure Emit_Error (File : in Ada.Text_IO.File_Type;
File_Name : in String;
Line : in Line_Number;
Message : in String);
end Errors;
|
with Symbols;
with States;
-- with Rules;
package body Action_Lists is
procedure Append (Action_List : in out List;
Kind : in Actions.Action_Kind;
Symbol : in Symbols.Symbol_Access;
State : in States.State_Access;
Rule : in Rule_Access)
is
use Actions;
-- New_Action : Action_Access;
Union : X_Union;
begin
if Kind = Shift then
Union.State := State;
else
Union.Rule := Rule;
end if;
Action_List.Append (Action_Record'(Kind => Kind,
Symbol => Symbol,
Symbol_Link => null,
X => Union,
Collide => null));
-- New_Action := new Action_Record; -- Action_New ();
-- New_Action.Next := Action;
-- Action := New_Action;
-- New_Action.Kind := Kind;
-- New_Action.Symbol := Symbol;
-- New_Action.spOpt := null;
-- if Kind = Shift then
-- New_Action.X.stp := State;
-- else
-- New_Action.X.Rule := Rule;
-- end if;
end Append;
package Action_Sorting is
new Action_DLLs.Generic_Sorting ("<" => Actions.Action_Cmp);
procedure Sort (Action_List : in out List)
-- procedure Action_Sort (Action_List : in out List)
-- function Action_Sort (Action : in Action_Access) return Action_Access
is
begin
Action_Sorting.Sort (Action_List);
-- static struct action *Action_sort(
-- struct action *ap
-- ){
-- ap = (struct action *)msort((char *)ap,(char **)&ap->next,
-- (int(*)(const char*,const char*))actioncmp);
-- return ap;
-- }
-- end Action_Sort;
end Sort;
end Action_Lists;
|
package body openGL.Program.colored_textured
is
overriding
procedure set_Uniforms (Self : in Item)
is
the_scale_Uniform : constant openGL.Variable.uniform.vec3
:= Self.uniform_Variable ("uScale");
begin
Self.set_mvp_Uniform;
the_scale_Uniform.Value_is (Self.Scale);
end set_Uniforms;
end openGL.Program.colored_textured;
|
pragma License (Unrestricted);
-- implementation unit specialized for POSIX (Darwin, FreeBSD, or Linux)
with C.sys.types;
with C.unistd;
package System.Native_Credentials is
pragma Preelaborate;
subtype User_Id is C.sys.types.uid_t;
subtype Group_Id is C.sys.types.gid_t;
function Current_User return User_Id
renames C.unistd.getuid;
function Current_Group return Group_Id
renames C.unistd.getgid;
function User_Name (Id : User_Id := Current_User) return String;
function Group_Name (Id : Group_Id := Current_Group) return String;
-- Check which a resouce belongs
function Belongs_To_Current_User (Id : User_Id) return Boolean;
function Belongs_To_Current_Group (Id : Group_Id) return Boolean;
pragma Inline (Belongs_To_Current_User);
end System.Native_Credentials;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- G N A T S Y M --
-- --
-- B o d y --
-- --
-- Copyright (C) 2003-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. --
-- --
------------------------------------------------------------------------------
-- This utility application creates symbol files in a format that is
-- platform-dependent.
-- A symbol file is a text file that lists the symbols to be exported from
-- a shared library. The format of a symbol file depends on the platform;
-- it may be a simple enumeration of the symbol (one per line) or a more
-- elaborate format (on VMS, for example). A symbol file may be used as an
-- input to the platform linker when building a shared library.
-- This utility is not available on all platforms. It is currently supported
-- only on OpenVMS.
-- gnatsym takes as parameters:
-- - the name of the symbol file to create
-- - (optional) the policy to create the symbol file
-- - (optional) the name of the reference symbol file
-- - the names of one or more object files where the symbols are found
with GNAT.Command_Line; use GNAT.Command_Line;
with GNAT.OS_Lib; use GNAT.OS_Lib;
with Gnatvsn; use Gnatvsn;
with Osint; use Osint;
with Output; use Output;
with Symbols; use Symbols;
with Table;
procedure Gnatsym is
Empty_String : aliased String := "";
Empty : constant String_Access := Empty_String'Unchecked_Access;
-- To initialize variables Reference and Version_String
Copyright_Displayed : Boolean := False;
-- A flag to prevent multiple display of the Copyright notice
Success : Boolean := True;
Symbol_Policy : Policy := Autonomous;
Verbose : Boolean := False;
-- True when -v switch is used
Quiet : Boolean := False;
-- True when -q switch is used
Symbol_File_Name : String_Access := null;
-- The name of the symbol file
Reference_Symbol_File_Name : String_Access := Empty;
-- The name of the reference symbol file
Version_String : String_Access := Empty;
-- The version of the library (used on VMS)
package Object_Files is new Table.Table
(Table_Component_Type => String_Access,
Table_Index_Type => Natural,
Table_Low_Bound => 0,
Table_Initial => 10,
Table_Increment => 10,
Table_Name => "Gnatsymb.Object_Files");
-- A table to store the object file names
Object_File : Natural := 0;
-- An index to traverse the Object_Files table
procedure Display_Copyright;
-- Display Copyright notice
procedure Parse_Cmd_Line;
-- Parse the command line switches and file names
procedure Usage;
-- Display the usage
-----------------------
-- Display_Copyright --
-----------------------
procedure Display_Copyright is
begin
if not Copyright_Displayed then
Write_Eol;
Write_Str ("GNATSYMB ");
Write_Str (Gnat_Version_String);
Write_Eol;
Write_Str ("Copyright 2003-2004 Free Software Foundation, Inc");
Write_Eol;
Copyright_Displayed := True;
end if;
end Display_Copyright;
--------------------
-- Parse_Cmd_Line --
--------------------
procedure Parse_Cmd_Line is
begin
loop
case GNAT.Command_Line.Getopt ("c C q r: R s: v V:") is
when ASCII.NUL =>
exit;
when 'c' =>
Symbol_Policy := Compliant;
when 'C' =>
Symbol_Policy := Controlled;
when 'q' =>
Quiet := True;
when 'r' =>
Reference_Symbol_File_Name :=
new String'(GNAT.Command_Line.Parameter);
when 'R' =>
Symbol_Policy := Restricted;
when 's' =>
Symbol_File_Name := new String'(GNAT.Command_Line.Parameter);
when 'v' =>
Verbose := True;
when 'V' =>
Version_String := new String'(GNAT.Command_Line.Parameter);
when others =>
Fail ("invalid switch: ", Full_Switch);
end case;
end loop;
-- Get the file names
loop
declare
S : constant String_Access :=
new String'(GNAT.Command_Line.Get_Argument);
begin
exit when S'Length = 0;
Object_Files.Increment_Last;
Object_Files.Table (Object_Files.Last) := S;
end;
end loop;
exception
when Invalid_Switch =>
Usage;
Fail ("invalid switch : ", Full_Switch);
end Parse_Cmd_Line;
-----------
-- Usage --
-----------
procedure Usage is
begin
Write_Line ("gnatsym [options] object_file {object_file}");
Write_Eol;
Write_Line (" -c Compliant symbol policy");
Write_Line (" -C Controlled symbol policy");
Write_Line (" -q Quiet mode");
Write_Line (" -r<ref> Reference symbol file name");
Write_Line (" -R Restricted symbol policy");
Write_Line (" -s<sym> Symbol file name");
Write_Line (" -v Verbose mode");
Write_Line (" -V<ver> Version");
Write_Eol;
Write_Line ("Specifying a symbol file with -s<sym> is compulsory");
Write_Eol;
end Usage;
-- Start of processing of Gnatsym
begin
-- Initialize Object_Files table
Object_Files.Set_Last (0);
-- Parse the command line
Parse_Cmd_Line;
if Verbose then
Display_Copyright;
end if;
-- If there is no symbol file or no object files on the command line,
-- display the usage and exit with an error status.
if Symbol_File_Name = null or else Object_Files.Last = 0 then
Usage;
OS_Exit (1);
else
if Verbose then
Write_Str ("Initializing symbol file """);
Write_Str (Symbol_File_Name.all);
Write_Line ("""");
end if;
-- Initialize symbol file and, if specified, read reference file
Symbols.Initialize
(Symbol_File => Symbol_File_Name.all,
Reference => Reference_Symbol_File_Name.all,
Symbol_Policy => Symbol_Policy,
Quiet => Quiet,
Version => Version_String.all,
Success => Success);
-- Process the object files in order. Stop as soon as there is
-- something wrong.
Object_File := 0;
while Success and then Object_File < Object_Files.Last loop
Object_File := Object_File + 1;
if Verbose then
Write_Str ("Processing object file """);
Write_Str (Object_Files.Table (Object_File).all);
Write_Line ("""");
end if;
Processing.Process (Object_Files.Table (Object_File).all, Success);
end loop;
-- Finalize the object file
if Success then
if Verbose then
Write_Str ("Finalizing """);
Write_Str (Symbol_File_Name.all);
Write_Line ("""");
end if;
Finalize (Quiet, Success);
end if;
-- Fail if there was anything wrong
if not Success then
Fail ("unable to build symbol file");
end if;
end if;
end Gnatsym;
|
package body Lto19_Pkg1 is
procedure Proc (R : Rec) is begin null; end;
end Lto19_Pkg1;
|
------------------------------------------------------------------------------
-- --
-- GNU ADA RUNTIME LIBRARY (GNARL) COMPONENTS --
-- --
-- S Y S T E M . T A S K _ T I M E R _ S E R V I C E --
-- --
-- S p e c --
-- --
-- $Revision: 2 $ --
-- --
-- Copyright (c) 1991,1992,1993,1994, FSU, All Rights Reserved --
-- --
-- GNARL is free software; you can redistribute it and/or modify it under --
-- terms of the GNU Library General Public License as published by the --
-- Free Software Foundation; either version 2, or (at your option) any --
-- later version. GNARL is distributed in the hope that it will be use- --
-- ful, but but WITHOUT ANY WARRANTY; without even the implied warranty of --
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Gen- --
-- eral Library Public License for more details. You should have received --
-- a copy of the GNU Library General Public License along with GNARL; see --
-- file COPYING.LIB. If not, write to the Free Software Foundation, 675 --
-- Mass Ave, Cambridge, MA 02139, USA. --
-- --
------------------------------------------------------------------------------
-- Server to manage delays. Written in terms of System.Real_Time.Time
-- and System.Task_Clock.Time.
with Ada.Calendar;
-- Used for, Calendar.Time
with Ada.Real_Time;
-- Used for, Real_Time.Time
-- Real_Time.Time_Span
with System.Task_Clock;
-- Used for, Stimespec
package System.Task_Timer.Service is
protected Timer is
pragma Priority (Priority'Last);
-- The following Enqueue entries enqueue elements in wake-up time
-- order using a single timer queue (time in System.Real_Time.Time).
entry Enqueue_Time_Span
(T : in Ada.Real_Time.Time_Span;
D : access Delay_Block);
entry Enqueue_Duration
(T : in Duration;
D : access Delay_Block);
entry Enqueue_Real_Time
(T : in Ada.Real_Time.Time;
D : access Delay_Block);
entry Enqueue_Calendar_Time
(T : in Ada.Calendar.Time;
D : access Delay_Block);
-- private
-- Private protected operations are not currently supported by the
-- compiler.
procedure Service (T : out System.Task_Clock.Stimespec);
procedure Time_Enqueue
(T : in Task_Clock.Stimespec;
D : access Delay_Block);
end Timer;
end System.Task_Timer.Service;
|
-- Copyright (c) 2020 Raspberry Pi (Trading) Ltd.
--
-- SPDX-License-Identifier: BSD-3-Clause
-- This spec has been automatically generated from rp2040.svd
pragma Restrictions (No_Elaboration_Code);
pragma Ada_2012;
pragma Style_Checks (Off);
with HAL;
with System;
package RP_SVD.CLOCKS is
pragma Preelaborate;
---------------
-- Registers --
---------------
-- Selects the auxiliary clock source, will glitch when switching
type CLK_GPOUT0_CTRL_AUXSRC_Field is
(CLKSRC_PLL_SYS,
CLKSRC_GPIN0,
CLKSRC_GPIN1,
CLKSRC_PLL_USB,
ROSC_CLKSRC,
XOSC_CLKSRC,
CLK_SYS,
CLK_USB,
CLK_ADC,
CLK_RTC,
CLK_REF)
with Size => 4;
for CLK_GPOUT0_CTRL_AUXSRC_Field use
(CLKSRC_PLL_SYS => 0,
CLKSRC_GPIN0 => 1,
CLKSRC_GPIN1 => 2,
CLKSRC_PLL_USB => 3,
ROSC_CLKSRC => 4,
XOSC_CLKSRC => 5,
CLK_SYS => 6,
CLK_USB => 7,
CLK_ADC => 8,
CLK_RTC => 9,
CLK_REF => 10);
subtype CLK_GPOUT0_CTRL_PHASE_Field is HAL.UInt2;
-- Clock control, can be changed on-the-fly (except for auxsrc)
type CLK_GPOUT0_CTRL_Register is record
-- unspecified
Reserved_0_4 : HAL.UInt5 := 16#0#;
-- Selects the auxiliary clock source, will glitch when switching
AUXSRC : CLK_GPOUT0_CTRL_AUXSRC_Field :=
RP_SVD.CLOCKS.CLKSRC_PLL_SYS;
-- unspecified
Reserved_9_9 : HAL.Bit := 16#0#;
-- Asynchronously kills the clock generator
KILL : Boolean := False;
-- Starts and stops the clock generator cleanly
ENABLE : Boolean := False;
-- Enables duty cycle correction for odd divisors
DC50 : Boolean := False;
-- unspecified
Reserved_13_15 : HAL.UInt3 := 16#0#;
-- This delays the enable signal by up to 3 cycles of the input clock\n
-- This must be set before the clock is enabled to have any effect
PHASE : CLK_GPOUT0_CTRL_PHASE_Field := 16#0#;
-- unspecified
Reserved_18_19 : HAL.UInt2 := 16#0#;
-- An edge on this signal shifts the phase of the output by 1 cycle of
-- the input clock\n This can be done at any time
NUDGE : Boolean := False;
-- unspecified
Reserved_21_31 : HAL.UInt11 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for CLK_GPOUT0_CTRL_Register use record
Reserved_0_4 at 0 range 0 .. 4;
AUXSRC at 0 range 5 .. 8;
Reserved_9_9 at 0 range 9 .. 9;
KILL at 0 range 10 .. 10;
ENABLE at 0 range 11 .. 11;
DC50 at 0 range 12 .. 12;
Reserved_13_15 at 0 range 13 .. 15;
PHASE at 0 range 16 .. 17;
Reserved_18_19 at 0 range 18 .. 19;
NUDGE at 0 range 20 .. 20;
Reserved_21_31 at 0 range 21 .. 31;
end record;
subtype CLK_GPOUT0_DIV_FRAC_Field is HAL.UInt8;
subtype CLK_GPOUT0_DIV_INT_Field is HAL.UInt24;
-- Clock divisor, can be changed on-the-fly
type CLK_GPOUT0_DIV_Register is record
-- Fractional component of the divisor
FRAC : CLK_GPOUT0_DIV_FRAC_Field := 16#0#;
-- Integer component of the divisor, 0 -> divide by 2^16
INT : CLK_GPOUT0_DIV_INT_Field := 16#1#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for CLK_GPOUT0_DIV_Register use record
FRAC at 0 range 0 .. 7;
INT at 0 range 8 .. 31;
end record;
-- Selects the auxiliary clock source, will glitch when switching
type CLK_GPOUT1_CTRL_AUXSRC_Field is
(CLKSRC_PLL_SYS,
CLKSRC_GPIN0,
CLKSRC_GPIN1,
CLKSRC_PLL_USB,
ROSC_CLKSRC,
XOSC_CLKSRC,
CLK_SYS,
CLK_USB,
CLK_ADC,
CLK_RTC,
CLK_REF)
with Size => 4;
for CLK_GPOUT1_CTRL_AUXSRC_Field use
(CLKSRC_PLL_SYS => 0,
CLKSRC_GPIN0 => 1,
CLKSRC_GPIN1 => 2,
CLKSRC_PLL_USB => 3,
ROSC_CLKSRC => 4,
XOSC_CLKSRC => 5,
CLK_SYS => 6,
CLK_USB => 7,
CLK_ADC => 8,
CLK_RTC => 9,
CLK_REF => 10);
subtype CLK_GPOUT1_CTRL_PHASE_Field is HAL.UInt2;
-- Clock control, can be changed on-the-fly (except for auxsrc)
type CLK_GPOUT1_CTRL_Register is record
-- unspecified
Reserved_0_4 : HAL.UInt5 := 16#0#;
-- Selects the auxiliary clock source, will glitch when switching
AUXSRC : CLK_GPOUT1_CTRL_AUXSRC_Field :=
RP_SVD.CLOCKS.CLKSRC_PLL_SYS;
-- unspecified
Reserved_9_9 : HAL.Bit := 16#0#;
-- Asynchronously kills the clock generator
KILL : Boolean := False;
-- Starts and stops the clock generator cleanly
ENABLE : Boolean := False;
-- Enables duty cycle correction for odd divisors
DC50 : Boolean := False;
-- unspecified
Reserved_13_15 : HAL.UInt3 := 16#0#;
-- This delays the enable signal by up to 3 cycles of the input clock\n
-- This must be set before the clock is enabled to have any effect
PHASE : CLK_GPOUT1_CTRL_PHASE_Field := 16#0#;
-- unspecified
Reserved_18_19 : HAL.UInt2 := 16#0#;
-- An edge on this signal shifts the phase of the output by 1 cycle of
-- the input clock\n This can be done at any time
NUDGE : Boolean := False;
-- unspecified
Reserved_21_31 : HAL.UInt11 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for CLK_GPOUT1_CTRL_Register use record
Reserved_0_4 at 0 range 0 .. 4;
AUXSRC at 0 range 5 .. 8;
Reserved_9_9 at 0 range 9 .. 9;
KILL at 0 range 10 .. 10;
ENABLE at 0 range 11 .. 11;
DC50 at 0 range 12 .. 12;
Reserved_13_15 at 0 range 13 .. 15;
PHASE at 0 range 16 .. 17;
Reserved_18_19 at 0 range 18 .. 19;
NUDGE at 0 range 20 .. 20;
Reserved_21_31 at 0 range 21 .. 31;
end record;
subtype CLK_GPOUT1_DIV_FRAC_Field is HAL.UInt8;
subtype CLK_GPOUT1_DIV_INT_Field is HAL.UInt24;
-- Clock divisor, can be changed on-the-fly
type CLK_GPOUT1_DIV_Register is record
-- Fractional component of the divisor
FRAC : CLK_GPOUT1_DIV_FRAC_Field := 16#0#;
-- Integer component of the divisor, 0 -> divide by 2^16
INT : CLK_GPOUT1_DIV_INT_Field := 16#1#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for CLK_GPOUT1_DIV_Register use record
FRAC at 0 range 0 .. 7;
INT at 0 range 8 .. 31;
end record;
-- Selects the auxiliary clock source, will glitch when switching
type CLK_GPOUT2_CTRL_AUXSRC_Field is
(CLKSRC_PLL_SYS,
CLKSRC_GPIN0,
CLKSRC_GPIN1,
CLKSRC_PLL_USB,
ROSC_CLKSRC_PH,
XOSC_CLKSRC,
CLK_SYS,
CLK_USB,
CLK_ADC,
CLK_RTC,
CLK_REF)
with Size => 4;
for CLK_GPOUT2_CTRL_AUXSRC_Field use
(CLKSRC_PLL_SYS => 0,
CLKSRC_GPIN0 => 1,
CLKSRC_GPIN1 => 2,
CLKSRC_PLL_USB => 3,
ROSC_CLKSRC_PH => 4,
XOSC_CLKSRC => 5,
CLK_SYS => 6,
CLK_USB => 7,
CLK_ADC => 8,
CLK_RTC => 9,
CLK_REF => 10);
subtype CLK_GPOUT2_CTRL_PHASE_Field is HAL.UInt2;
-- Clock control, can be changed on-the-fly (except for auxsrc)
type CLK_GPOUT2_CTRL_Register is record
-- unspecified
Reserved_0_4 : HAL.UInt5 := 16#0#;
-- Selects the auxiliary clock source, will glitch when switching
AUXSRC : CLK_GPOUT2_CTRL_AUXSRC_Field :=
RP_SVD.CLOCKS.CLKSRC_PLL_SYS;
-- unspecified
Reserved_9_9 : HAL.Bit := 16#0#;
-- Asynchronously kills the clock generator
KILL : Boolean := False;
-- Starts and stops the clock generator cleanly
ENABLE : Boolean := False;
-- Enables duty cycle correction for odd divisors
DC50 : Boolean := False;
-- unspecified
Reserved_13_15 : HAL.UInt3 := 16#0#;
-- This delays the enable signal by up to 3 cycles of the input clock\n
-- This must be set before the clock is enabled to have any effect
PHASE : CLK_GPOUT2_CTRL_PHASE_Field := 16#0#;
-- unspecified
Reserved_18_19 : HAL.UInt2 := 16#0#;
-- An edge on this signal shifts the phase of the output by 1 cycle of
-- the input clock\n This can be done at any time
NUDGE : Boolean := False;
-- unspecified
Reserved_21_31 : HAL.UInt11 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for CLK_GPOUT2_CTRL_Register use record
Reserved_0_4 at 0 range 0 .. 4;
AUXSRC at 0 range 5 .. 8;
Reserved_9_9 at 0 range 9 .. 9;
KILL at 0 range 10 .. 10;
ENABLE at 0 range 11 .. 11;
DC50 at 0 range 12 .. 12;
Reserved_13_15 at 0 range 13 .. 15;
PHASE at 0 range 16 .. 17;
Reserved_18_19 at 0 range 18 .. 19;
NUDGE at 0 range 20 .. 20;
Reserved_21_31 at 0 range 21 .. 31;
end record;
subtype CLK_GPOUT2_DIV_FRAC_Field is HAL.UInt8;
subtype CLK_GPOUT2_DIV_INT_Field is HAL.UInt24;
-- Clock divisor, can be changed on-the-fly
type CLK_GPOUT2_DIV_Register is record
-- Fractional component of the divisor
FRAC : CLK_GPOUT2_DIV_FRAC_Field := 16#0#;
-- Integer component of the divisor, 0 -> divide by 2^16
INT : CLK_GPOUT2_DIV_INT_Field := 16#1#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for CLK_GPOUT2_DIV_Register use record
FRAC at 0 range 0 .. 7;
INT at 0 range 8 .. 31;
end record;
-- Selects the auxiliary clock source, will glitch when switching
type CLK_GPOUT3_CTRL_AUXSRC_Field is
(CLKSRC_PLL_SYS,
CLKSRC_GPIN0,
CLKSRC_GPIN1,
CLKSRC_PLL_USB,
ROSC_CLKSRC_PH,
XOSC_CLKSRC,
CLK_SYS,
CLK_USB,
CLK_ADC,
CLK_RTC,
CLK_REF)
with Size => 4;
for CLK_GPOUT3_CTRL_AUXSRC_Field use
(CLKSRC_PLL_SYS => 0,
CLKSRC_GPIN0 => 1,
CLKSRC_GPIN1 => 2,
CLKSRC_PLL_USB => 3,
ROSC_CLKSRC_PH => 4,
XOSC_CLKSRC => 5,
CLK_SYS => 6,
CLK_USB => 7,
CLK_ADC => 8,
CLK_RTC => 9,
CLK_REF => 10);
subtype CLK_GPOUT3_CTRL_PHASE_Field is HAL.UInt2;
-- Clock control, can be changed on-the-fly (except for auxsrc)
type CLK_GPOUT3_CTRL_Register is record
-- unspecified
Reserved_0_4 : HAL.UInt5 := 16#0#;
-- Selects the auxiliary clock source, will glitch when switching
AUXSRC : CLK_GPOUT3_CTRL_AUXSRC_Field :=
RP_SVD.CLOCKS.CLKSRC_PLL_SYS;
-- unspecified
Reserved_9_9 : HAL.Bit := 16#0#;
-- Asynchronously kills the clock generator
KILL : Boolean := False;
-- Starts and stops the clock generator cleanly
ENABLE : Boolean := False;
-- Enables duty cycle correction for odd divisors
DC50 : Boolean := False;
-- unspecified
Reserved_13_15 : HAL.UInt3 := 16#0#;
-- This delays the enable signal by up to 3 cycles of the input clock\n
-- This must be set before the clock is enabled to have any effect
PHASE : CLK_GPOUT3_CTRL_PHASE_Field := 16#0#;
-- unspecified
Reserved_18_19 : HAL.UInt2 := 16#0#;
-- An edge on this signal shifts the phase of the output by 1 cycle of
-- the input clock\n This can be done at any time
NUDGE : Boolean := False;
-- unspecified
Reserved_21_31 : HAL.UInt11 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for CLK_GPOUT3_CTRL_Register use record
Reserved_0_4 at 0 range 0 .. 4;
AUXSRC at 0 range 5 .. 8;
Reserved_9_9 at 0 range 9 .. 9;
KILL at 0 range 10 .. 10;
ENABLE at 0 range 11 .. 11;
DC50 at 0 range 12 .. 12;
Reserved_13_15 at 0 range 13 .. 15;
PHASE at 0 range 16 .. 17;
Reserved_18_19 at 0 range 18 .. 19;
NUDGE at 0 range 20 .. 20;
Reserved_21_31 at 0 range 21 .. 31;
end record;
subtype CLK_GPOUT3_DIV_FRAC_Field is HAL.UInt8;
subtype CLK_GPOUT3_DIV_INT_Field is HAL.UInt24;
-- Clock divisor, can be changed on-the-fly
type CLK_GPOUT3_DIV_Register is record
-- Fractional component of the divisor
FRAC : CLK_GPOUT3_DIV_FRAC_Field := 16#0#;
-- Integer component of the divisor, 0 -> divide by 2^16
INT : CLK_GPOUT3_DIV_INT_Field := 16#1#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for CLK_GPOUT3_DIV_Register use record
FRAC at 0 range 0 .. 7;
INT at 0 range 8 .. 31;
end record;
-- Selects the clock source glitchlessly, can be changed on-the-fly
type CLK_REF_CTRL_SRC_Field is
(ROSC_CLKSRC_PH,
CLKSRC_CLK_REF_AUX,
XOSC_CLKSRC)
with Size => 2;
for CLK_REF_CTRL_SRC_Field use
(ROSC_CLKSRC_PH => 0,
CLKSRC_CLK_REF_AUX => 1,
XOSC_CLKSRC => 2);
-- Selects the auxiliary clock source, will glitch when switching
type CLK_REF_CTRL_AUXSRC_Field is
(CLKSRC_PLL_USB,
CLKSRC_GPIN0,
CLKSRC_GPIN1)
with Size => 2;
for CLK_REF_CTRL_AUXSRC_Field use
(CLKSRC_PLL_USB => 0,
CLKSRC_GPIN0 => 1,
CLKSRC_GPIN1 => 2);
-- Clock control, can be changed on-the-fly (except for auxsrc)
type CLK_REF_CTRL_Register is record
-- Selects the clock source glitchlessly, can be changed on-the-fly
SRC : CLK_REF_CTRL_SRC_Field := RP_SVD.CLOCKS.ROSC_CLKSRC_PH;
-- unspecified
Reserved_2_4 : HAL.UInt3 := 16#0#;
-- Selects the auxiliary clock source, will glitch when switching
AUXSRC : CLK_REF_CTRL_AUXSRC_Field :=
RP_SVD.CLOCKS.CLKSRC_PLL_USB;
-- unspecified
Reserved_7_31 : HAL.UInt25 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for CLK_REF_CTRL_Register use record
SRC at 0 range 0 .. 1;
Reserved_2_4 at 0 range 2 .. 4;
AUXSRC at 0 range 5 .. 6;
Reserved_7_31 at 0 range 7 .. 31;
end record;
subtype CLK_REF_DIV_INT_Field is HAL.UInt2;
-- Clock divisor, can be changed on-the-fly
type CLK_REF_DIV_Register is record
-- unspecified
Reserved_0_7 : HAL.UInt8 := 16#0#;
-- Integer component of the divisor, 0 -> divide by 2^16
INT : CLK_REF_DIV_INT_Field := 16#1#;
-- unspecified
Reserved_10_31 : HAL.UInt22 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for CLK_REF_DIV_Register use record
Reserved_0_7 at 0 range 0 .. 7;
INT at 0 range 8 .. 9;
Reserved_10_31 at 0 range 10 .. 31;
end record;
-- Selects the clock source glitchlessly, can be changed on-the-fly
type CLK_SYS_CTRL_SRC_Field is
(CLK_REF,
CLKSRC_CLK_SYS_AUX)
with Size => 1;
for CLK_SYS_CTRL_SRC_Field use
(CLK_REF => 0,
CLKSRC_CLK_SYS_AUX => 1);
-- Selects the auxiliary clock source, will glitch when switching
type CLK_SYS_CTRL_AUXSRC_Field is
(CLKSRC_PLL_SYS,
CLKSRC_PLL_USB,
ROSC_CLKSRC,
XOSC_CLKSRC,
CLKSRC_GPIN0,
CLKSRC_GPIN1)
with Size => 3;
for CLK_SYS_CTRL_AUXSRC_Field use
(CLKSRC_PLL_SYS => 0,
CLKSRC_PLL_USB => 1,
ROSC_CLKSRC => 2,
XOSC_CLKSRC => 3,
CLKSRC_GPIN0 => 4,
CLKSRC_GPIN1 => 5);
-- Clock control, can be changed on-the-fly (except for auxsrc)
type CLK_SYS_CTRL_Register is record
-- Selects the clock source glitchlessly, can be changed on-the-fly
SRC : CLK_SYS_CTRL_SRC_Field := RP_SVD.CLOCKS.CLK_REF;
-- unspecified
Reserved_1_4 : HAL.UInt4 := 16#0#;
-- Selects the auxiliary clock source, will glitch when switching
AUXSRC : CLK_SYS_CTRL_AUXSRC_Field :=
RP_SVD.CLOCKS.CLKSRC_PLL_SYS;
-- unspecified
Reserved_8_31 : HAL.UInt24 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for CLK_SYS_CTRL_Register use record
SRC at 0 range 0 .. 0;
Reserved_1_4 at 0 range 1 .. 4;
AUXSRC at 0 range 5 .. 7;
Reserved_8_31 at 0 range 8 .. 31;
end record;
subtype CLK_SYS_DIV_FRAC_Field is HAL.UInt8;
subtype CLK_SYS_DIV_INT_Field is HAL.UInt24;
-- Clock divisor, can be changed on-the-fly
type CLK_SYS_DIV_Register is record
-- Fractional component of the divisor
FRAC : CLK_SYS_DIV_FRAC_Field := 16#0#;
-- Integer component of the divisor, 0 -> divide by 2^16
INT : CLK_SYS_DIV_INT_Field := 16#1#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for CLK_SYS_DIV_Register use record
FRAC at 0 range 0 .. 7;
INT at 0 range 8 .. 31;
end record;
-- Selects the auxiliary clock source, will glitch when switching
type CLK_PERI_CTRL_AUXSRC_Field is
(CLK_SYS,
CLKSRC_PLL_SYS,
CLKSRC_PLL_USB,
ROSC_CLKSRC_PH,
XOSC_CLKSRC,
CLKSRC_GPIN0,
CLKSRC_GPIN1)
with Size => 3;
for CLK_PERI_CTRL_AUXSRC_Field use
(CLK_SYS => 0,
CLKSRC_PLL_SYS => 1,
CLKSRC_PLL_USB => 2,
ROSC_CLKSRC_PH => 3,
XOSC_CLKSRC => 4,
CLKSRC_GPIN0 => 5,
CLKSRC_GPIN1 => 6);
-- Clock control, can be changed on-the-fly (except for auxsrc)
type CLK_PERI_CTRL_Register is record
-- unspecified
Reserved_0_4 : HAL.UInt5 := 16#0#;
-- Selects the auxiliary clock source, will glitch when switching
AUXSRC : CLK_PERI_CTRL_AUXSRC_Field := RP_SVD.CLOCKS.CLK_SYS;
-- unspecified
Reserved_8_9 : HAL.UInt2 := 16#0#;
-- Asynchronously kills the clock generator
KILL : Boolean := False;
-- Starts and stops the clock generator cleanly
ENABLE : Boolean := False;
-- unspecified
Reserved_12_31 : HAL.UInt20 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for CLK_PERI_CTRL_Register use record
Reserved_0_4 at 0 range 0 .. 4;
AUXSRC at 0 range 5 .. 7;
Reserved_8_9 at 0 range 8 .. 9;
KILL at 0 range 10 .. 10;
ENABLE at 0 range 11 .. 11;
Reserved_12_31 at 0 range 12 .. 31;
end record;
-- Selects the auxiliary clock source, will glitch when switching
type CLK_USB_CTRL_AUXSRC_Field is
(CLKSRC_PLL_USB,
CLKSRC_PLL_SYS,
ROSC_CLKSRC_PH,
XOSC_CLKSRC,
CLKSRC_GPIN0,
CLKSRC_GPIN1)
with Size => 3;
for CLK_USB_CTRL_AUXSRC_Field use
(CLKSRC_PLL_USB => 0,
CLKSRC_PLL_SYS => 1,
ROSC_CLKSRC_PH => 2,
XOSC_CLKSRC => 3,
CLKSRC_GPIN0 => 4,
CLKSRC_GPIN1 => 5);
subtype CLK_USB_CTRL_PHASE_Field is HAL.UInt2;
-- Clock control, can be changed on-the-fly (except for auxsrc)
type CLK_USB_CTRL_Register is record
-- unspecified
Reserved_0_4 : HAL.UInt5 := 16#0#;
-- Selects the auxiliary clock source, will glitch when switching
AUXSRC : CLK_USB_CTRL_AUXSRC_Field :=
RP_SVD.CLOCKS.CLKSRC_PLL_USB;
-- unspecified
Reserved_8_9 : HAL.UInt2 := 16#0#;
-- Asynchronously kills the clock generator
KILL : Boolean := False;
-- Starts and stops the clock generator cleanly
ENABLE : Boolean := False;
-- unspecified
Reserved_12_15 : HAL.UInt4 := 16#0#;
-- This delays the enable signal by up to 3 cycles of the input clock\n
-- This must be set before the clock is enabled to have any effect
PHASE : CLK_USB_CTRL_PHASE_Field := 16#0#;
-- unspecified
Reserved_18_19 : HAL.UInt2 := 16#0#;
-- An edge on this signal shifts the phase of the output by 1 cycle of
-- the input clock\n This can be done at any time
NUDGE : Boolean := False;
-- unspecified
Reserved_21_31 : HAL.UInt11 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for CLK_USB_CTRL_Register use record
Reserved_0_4 at 0 range 0 .. 4;
AUXSRC at 0 range 5 .. 7;
Reserved_8_9 at 0 range 8 .. 9;
KILL at 0 range 10 .. 10;
ENABLE at 0 range 11 .. 11;
Reserved_12_15 at 0 range 12 .. 15;
PHASE at 0 range 16 .. 17;
Reserved_18_19 at 0 range 18 .. 19;
NUDGE at 0 range 20 .. 20;
Reserved_21_31 at 0 range 21 .. 31;
end record;
subtype CLK_USB_DIV_INT_Field is HAL.UInt2;
-- Clock divisor, can be changed on-the-fly
type CLK_USB_DIV_Register is record
-- unspecified
Reserved_0_7 : HAL.UInt8 := 16#0#;
-- Integer component of the divisor, 0 -> divide by 2^16
INT : CLK_USB_DIV_INT_Field := 16#1#;
-- unspecified
Reserved_10_31 : HAL.UInt22 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for CLK_USB_DIV_Register use record
Reserved_0_7 at 0 range 0 .. 7;
INT at 0 range 8 .. 9;
Reserved_10_31 at 0 range 10 .. 31;
end record;
-- Selects the auxiliary clock source, will glitch when switching
type CLK_ADC_CTRL_AUXSRC_Field is
(CLKSRC_PLL_USB,
CLKSRC_PLL_SYS,
ROSC_CLKSRC_PH,
XOSC_CLKSRC,
CLKSRC_GPIN0,
CLKSRC_GPIN1)
with Size => 3;
for CLK_ADC_CTRL_AUXSRC_Field use
(CLKSRC_PLL_USB => 0,
CLKSRC_PLL_SYS => 1,
ROSC_CLKSRC_PH => 2,
XOSC_CLKSRC => 3,
CLKSRC_GPIN0 => 4,
CLKSRC_GPIN1 => 5);
subtype CLK_ADC_CTRL_PHASE_Field is HAL.UInt2;
-- Clock control, can be changed on-the-fly (except for auxsrc)
type CLK_ADC_CTRL_Register is record
-- unspecified
Reserved_0_4 : HAL.UInt5 := 16#0#;
-- Selects the auxiliary clock source, will glitch when switching
AUXSRC : CLK_ADC_CTRL_AUXSRC_Field :=
RP_SVD.CLOCKS.CLKSRC_PLL_USB;
-- unspecified
Reserved_8_9 : HAL.UInt2 := 16#0#;
-- Asynchronously kills the clock generator
KILL : Boolean := False;
-- Starts and stops the clock generator cleanly
ENABLE : Boolean := False;
-- unspecified
Reserved_12_15 : HAL.UInt4 := 16#0#;
-- This delays the enable signal by up to 3 cycles of the input clock\n
-- This must be set before the clock is enabled to have any effect
PHASE : CLK_ADC_CTRL_PHASE_Field := 16#0#;
-- unspecified
Reserved_18_19 : HAL.UInt2 := 16#0#;
-- An edge on this signal shifts the phase of the output by 1 cycle of
-- the input clock\n This can be done at any time
NUDGE : Boolean := False;
-- unspecified
Reserved_21_31 : HAL.UInt11 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for CLK_ADC_CTRL_Register use record
Reserved_0_4 at 0 range 0 .. 4;
AUXSRC at 0 range 5 .. 7;
Reserved_8_9 at 0 range 8 .. 9;
KILL at 0 range 10 .. 10;
ENABLE at 0 range 11 .. 11;
Reserved_12_15 at 0 range 12 .. 15;
PHASE at 0 range 16 .. 17;
Reserved_18_19 at 0 range 18 .. 19;
NUDGE at 0 range 20 .. 20;
Reserved_21_31 at 0 range 21 .. 31;
end record;
subtype CLK_ADC_DIV_INT_Field is HAL.UInt2;
-- Clock divisor, can be changed on-the-fly
type CLK_ADC_DIV_Register is record
-- unspecified
Reserved_0_7 : HAL.UInt8 := 16#0#;
-- Integer component of the divisor, 0 -> divide by 2^16
INT : CLK_ADC_DIV_INT_Field := 16#1#;
-- unspecified
Reserved_10_31 : HAL.UInt22 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for CLK_ADC_DIV_Register use record
Reserved_0_7 at 0 range 0 .. 7;
INT at 0 range 8 .. 9;
Reserved_10_31 at 0 range 10 .. 31;
end record;
-- Selects the auxiliary clock source, will glitch when switching
type CLK_RTC_CTRL_AUXSRC_Field is
(CLKSRC_PLL_USB,
CLKSRC_PLL_SYS,
ROSC_CLKSRC_PH,
XOSC_CLKSRC,
CLKSRC_GPIN0,
CLKSRC_GPIN1)
with Size => 3;
for CLK_RTC_CTRL_AUXSRC_Field use
(CLKSRC_PLL_USB => 0,
CLKSRC_PLL_SYS => 1,
ROSC_CLKSRC_PH => 2,
XOSC_CLKSRC => 3,
CLKSRC_GPIN0 => 4,
CLKSRC_GPIN1 => 5);
subtype CLK_RTC_CTRL_PHASE_Field is HAL.UInt2;
-- Clock control, can be changed on-the-fly (except for auxsrc)
type CLK_RTC_CTRL_Register is record
-- unspecified
Reserved_0_4 : HAL.UInt5 := 16#0#;
-- Selects the auxiliary clock source, will glitch when switching
AUXSRC : CLK_RTC_CTRL_AUXSRC_Field :=
RP_SVD.CLOCKS.CLKSRC_PLL_USB;
-- unspecified
Reserved_8_9 : HAL.UInt2 := 16#0#;
-- Asynchronously kills the clock generator
KILL : Boolean := False;
-- Starts and stops the clock generator cleanly
ENABLE : Boolean := False;
-- unspecified
Reserved_12_15 : HAL.UInt4 := 16#0#;
-- This delays the enable signal by up to 3 cycles of the input clock\n
-- This must be set before the clock is enabled to have any effect
PHASE : CLK_RTC_CTRL_PHASE_Field := 16#0#;
-- unspecified
Reserved_18_19 : HAL.UInt2 := 16#0#;
-- An edge on this signal shifts the phase of the output by 1 cycle of
-- the input clock\n This can be done at any time
NUDGE : Boolean := False;
-- unspecified
Reserved_21_31 : HAL.UInt11 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for CLK_RTC_CTRL_Register use record
Reserved_0_4 at 0 range 0 .. 4;
AUXSRC at 0 range 5 .. 7;
Reserved_8_9 at 0 range 8 .. 9;
KILL at 0 range 10 .. 10;
ENABLE at 0 range 11 .. 11;
Reserved_12_15 at 0 range 12 .. 15;
PHASE at 0 range 16 .. 17;
Reserved_18_19 at 0 range 18 .. 19;
NUDGE at 0 range 20 .. 20;
Reserved_21_31 at 0 range 21 .. 31;
end record;
subtype CLK_RTC_DIV_FRAC_Field is HAL.UInt8;
subtype CLK_RTC_DIV_INT_Field is HAL.UInt24;
-- Clock divisor, can be changed on-the-fly
type CLK_RTC_DIV_Register is record
-- Fractional component of the divisor
FRAC : CLK_RTC_DIV_FRAC_Field := 16#0#;
-- Integer component of the divisor, 0 -> divide by 2^16
INT : CLK_RTC_DIV_INT_Field := 16#1#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for CLK_RTC_DIV_Register use record
FRAC at 0 range 0 .. 7;
INT at 0 range 8 .. 31;
end record;
subtype CLK_SYS_RESUS_CTRL_TIMEOUT_Field is HAL.UInt8;
type CLK_SYS_RESUS_CTRL_Register is record
-- This is expressed as a number of clk_ref cycles\n and must be >= 2x
-- clk_ref_freq/min_clk_tst_freq
TIMEOUT : CLK_SYS_RESUS_CTRL_TIMEOUT_Field := 16#FF#;
-- Enable resus
ENABLE : Boolean := False;
-- unspecified
Reserved_9_11 : HAL.UInt3 := 16#0#;
-- Force a resus, for test purposes only
FRCE : Boolean := False;
-- unspecified
Reserved_13_15 : HAL.UInt3 := 16#0#;
-- For clearing the resus after the fault that triggered it has been
-- corrected
CLEAR : Boolean := False;
-- unspecified
Reserved_17_31 : HAL.UInt15 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for CLK_SYS_RESUS_CTRL_Register use record
TIMEOUT at 0 range 0 .. 7;
ENABLE at 0 range 8 .. 8;
Reserved_9_11 at 0 range 9 .. 11;
FRCE at 0 range 12 .. 12;
Reserved_13_15 at 0 range 13 .. 15;
CLEAR at 0 range 16 .. 16;
Reserved_17_31 at 0 range 17 .. 31;
end record;
type CLK_SYS_RESUS_STATUS_Register is record
-- Read-only. Clock has been resuscitated, correct the error then send
-- ctrl_clear=1
RESUSSED : Boolean;
-- unspecified
Reserved_1_31 : HAL.UInt31;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for CLK_SYS_RESUS_STATUS_Register use record
RESUSSED at 0 range 0 .. 0;
Reserved_1_31 at 0 range 1 .. 31;
end record;
subtype FC0_REF_KHZ_FC0_REF_KHZ_Field is HAL.UInt20;
-- Reference clock frequency in kHz
type FC0_REF_KHZ_Register is record
FC0_REF_KHZ : FC0_REF_KHZ_FC0_REF_KHZ_Field := 16#0#;
-- unspecified
Reserved_20_31 : HAL.UInt12 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for FC0_REF_KHZ_Register use record
FC0_REF_KHZ at 0 range 0 .. 19;
Reserved_20_31 at 0 range 20 .. 31;
end record;
subtype FC0_MIN_KHZ_FC0_MIN_KHZ_Field is HAL.UInt25;
-- Minimum pass frequency in kHz. This is optional. Set to 0 if you are not
-- using the pass/fail flags
type FC0_MIN_KHZ_Register is record
FC0_MIN_KHZ : FC0_MIN_KHZ_FC0_MIN_KHZ_Field := 16#0#;
-- unspecified
Reserved_25_31 : HAL.UInt7 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for FC0_MIN_KHZ_Register use record
FC0_MIN_KHZ at 0 range 0 .. 24;
Reserved_25_31 at 0 range 25 .. 31;
end record;
subtype FC0_MAX_KHZ_FC0_MAX_KHZ_Field is HAL.UInt25;
-- Maximum pass frequency in kHz. This is optional. Set to 0x1ffffff if you
-- are not using the pass/fail flags
type FC0_MAX_KHZ_Register is record
FC0_MAX_KHZ : FC0_MAX_KHZ_FC0_MAX_KHZ_Field := 16#1FFFFFF#;
-- unspecified
Reserved_25_31 : HAL.UInt7 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for FC0_MAX_KHZ_Register use record
FC0_MAX_KHZ at 0 range 0 .. 24;
Reserved_25_31 at 0 range 25 .. 31;
end record;
subtype FC0_DELAY_FC0_DELAY_Field is HAL.UInt3;
-- Delays the start of frequency counting to allow the mux to settle\n
-- Delay is measured in multiples of the reference clock period
type FC0_DELAY_Register is record
FC0_DELAY : FC0_DELAY_FC0_DELAY_Field := 16#1#;
-- unspecified
Reserved_3_31 : HAL.UInt29 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for FC0_DELAY_Register use record
FC0_DELAY at 0 range 0 .. 2;
Reserved_3_31 at 0 range 3 .. 31;
end record;
subtype FC0_INTERVAL_FC0_INTERVAL_Field is HAL.UInt4;
-- The test interval is 0.98us * 2**interval, but let's call it 1us *
-- 2**interval\n The default gives a test interval of 250us
type FC0_INTERVAL_Register is record
FC0_INTERVAL : FC0_INTERVAL_FC0_INTERVAL_Field := 16#8#;
-- unspecified
Reserved_4_31 : HAL.UInt28 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for FC0_INTERVAL_Register use record
FC0_INTERVAL at 0 range 0 .. 3;
Reserved_4_31 at 0 range 4 .. 31;
end record;
type FC0_SRC_FC0_SRC_Field is
(Null_k,
PLL_SYS_CLKSRC_PRIMARY,
PLL_USB_CLKSRC_PRIMARY,
ROSC_CLKSRC,
ROSC_CLKSRC_PH,
XOSC_CLKSRC,
CLKSRC_GPIN0,
CLKSRC_GPIN1,
CLK_REF,
CLK_SYS,
CLK_PERI,
CLK_USB,
CLK_ADC,
CLK_RTC)
with Size => 8;
for FC0_SRC_FC0_SRC_Field use
(Null_k => 0,
PLL_SYS_CLKSRC_PRIMARY => 1,
PLL_USB_CLKSRC_PRIMARY => 2,
ROSC_CLKSRC => 3,
ROSC_CLKSRC_PH => 4,
XOSC_CLKSRC => 5,
CLKSRC_GPIN0 => 6,
CLKSRC_GPIN1 => 7,
CLK_REF => 8,
CLK_SYS => 9,
CLK_PERI => 10,
CLK_USB => 11,
CLK_ADC => 12,
CLK_RTC => 13);
-- Clock sent to frequency counter, set to 0 when not required\n Writing to
-- this register initiates the frequency count
type FC0_SRC_Register is record
FC0_SRC : FC0_SRC_FC0_SRC_Field := RP_SVD.CLOCKS.Null_k;
-- unspecified
Reserved_8_31 : HAL.UInt24 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for FC0_SRC_Register use record
FC0_SRC at 0 range 0 .. 7;
Reserved_8_31 at 0 range 8 .. 31;
end record;
-- Frequency counter status
type FC0_STATUS_Register is record
-- Read-only. Test passed
PASS : Boolean;
-- unspecified
Reserved_1_3 : HAL.UInt3;
-- Read-only. Test complete
DONE : Boolean;
-- unspecified
Reserved_5_7 : HAL.UInt3;
-- Read-only. Test running
RUNNING : Boolean;
-- unspecified
Reserved_9_11 : HAL.UInt3;
-- Read-only. Waiting for test clock to start
WAITING : Boolean;
-- unspecified
Reserved_13_15 : HAL.UInt3;
-- Read-only. Test failed
FAIL : Boolean;
-- unspecified
Reserved_17_19 : HAL.UInt3;
-- Read-only. Test clock slower than expected, only valid when
-- status_done=1
SLOW : Boolean;
-- unspecified
Reserved_21_23 : HAL.UInt3;
-- Read-only. Test clock faster than expected, only valid when
-- status_done=1
FAST : Boolean;
-- unspecified
Reserved_25_27 : HAL.UInt3;
-- Read-only. Test clock stopped during test
DIED : Boolean;
-- unspecified
Reserved_29_31 : HAL.UInt3;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for FC0_STATUS_Register use record
PASS at 0 range 0 .. 0;
Reserved_1_3 at 0 range 1 .. 3;
DONE at 0 range 4 .. 4;
Reserved_5_7 at 0 range 5 .. 7;
RUNNING at 0 range 8 .. 8;
Reserved_9_11 at 0 range 9 .. 11;
WAITING at 0 range 12 .. 12;
Reserved_13_15 at 0 range 13 .. 15;
FAIL at 0 range 16 .. 16;
Reserved_17_19 at 0 range 17 .. 19;
SLOW at 0 range 20 .. 20;
Reserved_21_23 at 0 range 21 .. 23;
FAST at 0 range 24 .. 24;
Reserved_25_27 at 0 range 25 .. 27;
DIED at 0 range 28 .. 28;
Reserved_29_31 at 0 range 29 .. 31;
end record;
subtype FC0_RESULT_FRAC_Field is HAL.UInt5;
subtype FC0_RESULT_KHZ_Field is HAL.UInt25;
-- Result of frequency measurement, only valid when status_done=1
type FC0_RESULT_Register is record
-- Read-only.
FRAC : FC0_RESULT_FRAC_Field;
-- Read-only.
KHZ : FC0_RESULT_KHZ_Field;
-- unspecified
Reserved_30_31 : HAL.UInt2;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for FC0_RESULT_Register use record
FRAC at 0 range 0 .. 4;
KHZ at 0 range 5 .. 29;
Reserved_30_31 at 0 range 30 .. 31;
end record;
-- WAKE_EN0_clk_sys_i2c array
type WAKE_EN0_clk_sys_i2c_Field_Array is array (0 .. 1) of Boolean
with Component_Size => 1, Size => 2;
-- Type definition for WAKE_EN0_clk_sys_i2c
type WAKE_EN0_clk_sys_i2c_Field
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- clk_sys_i2c as a value
Val : HAL.UInt2;
when True =>
-- clk_sys_i2c as an array
Arr : WAKE_EN0_clk_sys_i2c_Field_Array;
end case;
end record
with Unchecked_Union, Size => 2;
for WAKE_EN0_clk_sys_i2c_Field use record
Val at 0 range 0 .. 1;
Arr at 0 range 0 .. 1;
end record;
-- WAKE_EN0_clk_sys_pio array
type WAKE_EN0_clk_sys_pio_Field_Array is array (0 .. 1) of Boolean
with Component_Size => 1, Size => 2;
-- Type definition for WAKE_EN0_clk_sys_pio
type WAKE_EN0_clk_sys_pio_Field
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- clk_sys_pio as a value
Val : HAL.UInt2;
when True =>
-- clk_sys_pio as an array
Arr : WAKE_EN0_clk_sys_pio_Field_Array;
end case;
end record
with Unchecked_Union, Size => 2;
for WAKE_EN0_clk_sys_pio_Field use record
Val at 0 range 0 .. 1;
Arr at 0 range 0 .. 1;
end record;
-- WAKE_EN0_clk_sys_sram array
type WAKE_EN0_clk_sys_sram_Field_Array is array (0 .. 3) of Boolean
with Component_Size => 1, Size => 4;
-- Type definition for WAKE_EN0_clk_sys_sram
type WAKE_EN0_clk_sys_sram_Field
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- clk_sys_sram as a value
Val : HAL.UInt4;
when True =>
-- clk_sys_sram as an array
Arr : WAKE_EN0_clk_sys_sram_Field_Array;
end case;
end record
with Unchecked_Union, Size => 4;
for WAKE_EN0_clk_sys_sram_Field use record
Val at 0 range 0 .. 3;
Arr at 0 range 0 .. 3;
end record;
-- enable clock in wake mode
type WAKE_EN0_Register is record
clk_sys_clocks : Boolean := True;
clk_adc_adc : Boolean := True;
clk_sys_adc : Boolean := True;
clk_sys_busctrl : Boolean := True;
clk_sys_busfabric : Boolean := True;
clk_sys_dma : Boolean := True;
clk_sys_i2c : WAKE_EN0_clk_sys_i2c_Field :=
(As_Array => False, Val => 16#1#);
clk_sys_io : Boolean := True;
clk_sys_jtag : Boolean := True;
clk_sys_vreg_and_chip_reset : Boolean := True;
clk_sys_pads : Boolean := True;
clk_sys_pio : WAKE_EN0_clk_sys_pio_Field :=
(As_Array => False, Val => 16#1#);
clk_sys_pll_sys : Boolean := True;
clk_sys_pll_usb : Boolean := True;
clk_sys_psm : Boolean := True;
clk_sys_pwm : Boolean := True;
clk_sys_resets : Boolean := True;
clk_sys_rom : Boolean := True;
clk_sys_rosc : Boolean := True;
clk_rtc_rtc : Boolean := True;
clk_sys_rtc : Boolean := True;
clk_sys_sio : Boolean := True;
clk_peri_spi0 : Boolean := True;
clk_sys_spi0 : Boolean := True;
clk_peri_spi1 : Boolean := True;
clk_sys_spi1 : Boolean := True;
clk_sys_sram : WAKE_EN0_clk_sys_sram_Field :=
(As_Array => False, Val => 16#1#);
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for WAKE_EN0_Register use record
clk_sys_clocks at 0 range 0 .. 0;
clk_adc_adc at 0 range 1 .. 1;
clk_sys_adc at 0 range 2 .. 2;
clk_sys_busctrl at 0 range 3 .. 3;
clk_sys_busfabric at 0 range 4 .. 4;
clk_sys_dma at 0 range 5 .. 5;
clk_sys_i2c at 0 range 6 .. 7;
clk_sys_io at 0 range 8 .. 8;
clk_sys_jtag at 0 range 9 .. 9;
clk_sys_vreg_and_chip_reset at 0 range 10 .. 10;
clk_sys_pads at 0 range 11 .. 11;
clk_sys_pio at 0 range 12 .. 13;
clk_sys_pll_sys at 0 range 14 .. 14;
clk_sys_pll_usb at 0 range 15 .. 15;
clk_sys_psm at 0 range 16 .. 16;
clk_sys_pwm at 0 range 17 .. 17;
clk_sys_resets at 0 range 18 .. 18;
clk_sys_rom at 0 range 19 .. 19;
clk_sys_rosc at 0 range 20 .. 20;
clk_rtc_rtc at 0 range 21 .. 21;
clk_sys_rtc at 0 range 22 .. 22;
clk_sys_sio at 0 range 23 .. 23;
clk_peri_spi0 at 0 range 24 .. 24;
clk_sys_spi0 at 0 range 25 .. 25;
clk_peri_spi1 at 0 range 26 .. 26;
clk_sys_spi1 at 0 range 27 .. 27;
clk_sys_sram at 0 range 28 .. 31;
end record;
-- WAKE_EN1_clk_sys_sram array
type WAKE_EN1_clk_sys_sram_Field_Array is array (4 .. 5) of Boolean
with Component_Size => 1, Size => 2;
-- Type definition for WAKE_EN1_clk_sys_sram
type WAKE_EN1_clk_sys_sram_Field
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- clk_sys_sram as a value
Val : HAL.UInt2;
when True =>
-- clk_sys_sram as an array
Arr : WAKE_EN1_clk_sys_sram_Field_Array;
end case;
end record
with Unchecked_Union, Size => 2;
for WAKE_EN1_clk_sys_sram_Field use record
Val at 0 range 0 .. 1;
Arr at 0 range 0 .. 1;
end record;
-- enable clock in wake mode
type WAKE_EN1_Register is record
clk_sys_sram : WAKE_EN1_clk_sys_sram_Field :=
(As_Array => False, Val => 16#1#);
clk_sys_syscfg : Boolean := True;
clk_sys_sysinfo : Boolean := True;
clk_sys_tbman : Boolean := True;
clk_sys_timer : Boolean := True;
clk_peri_uart0 : Boolean := True;
clk_sys_uart0 : Boolean := True;
clk_peri_uart1 : Boolean := True;
clk_sys_uart1 : Boolean := True;
clk_sys_usbctrl : Boolean := True;
clk_usb_usbctrl : Boolean := True;
clk_sys_watchdog : Boolean := True;
clk_sys_xip : Boolean := True;
clk_sys_xosc : Boolean := True;
-- unspecified
Reserved_15_31 : HAL.UInt17 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for WAKE_EN1_Register use record
clk_sys_sram at 0 range 0 .. 1;
clk_sys_syscfg at 0 range 2 .. 2;
clk_sys_sysinfo at 0 range 3 .. 3;
clk_sys_tbman at 0 range 4 .. 4;
clk_sys_timer at 0 range 5 .. 5;
clk_peri_uart0 at 0 range 6 .. 6;
clk_sys_uart0 at 0 range 7 .. 7;
clk_peri_uart1 at 0 range 8 .. 8;
clk_sys_uart1 at 0 range 9 .. 9;
clk_sys_usbctrl at 0 range 10 .. 10;
clk_usb_usbctrl at 0 range 11 .. 11;
clk_sys_watchdog at 0 range 12 .. 12;
clk_sys_xip at 0 range 13 .. 13;
clk_sys_xosc at 0 range 14 .. 14;
Reserved_15_31 at 0 range 15 .. 31;
end record;
-- SLEEP_EN0_clk_sys_i2c array
type SLEEP_EN0_clk_sys_i2c_Field_Array is array (0 .. 1) of Boolean
with Component_Size => 1, Size => 2;
-- Type definition for SLEEP_EN0_clk_sys_i2c
type SLEEP_EN0_clk_sys_i2c_Field
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- clk_sys_i2c as a value
Val : HAL.UInt2;
when True =>
-- clk_sys_i2c as an array
Arr : SLEEP_EN0_clk_sys_i2c_Field_Array;
end case;
end record
with Unchecked_Union, Size => 2;
for SLEEP_EN0_clk_sys_i2c_Field use record
Val at 0 range 0 .. 1;
Arr at 0 range 0 .. 1;
end record;
-- SLEEP_EN0_clk_sys_pio array
type SLEEP_EN0_clk_sys_pio_Field_Array is array (0 .. 1) of Boolean
with Component_Size => 1, Size => 2;
-- Type definition for SLEEP_EN0_clk_sys_pio
type SLEEP_EN0_clk_sys_pio_Field
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- clk_sys_pio as a value
Val : HAL.UInt2;
when True =>
-- clk_sys_pio as an array
Arr : SLEEP_EN0_clk_sys_pio_Field_Array;
end case;
end record
with Unchecked_Union, Size => 2;
for SLEEP_EN0_clk_sys_pio_Field use record
Val at 0 range 0 .. 1;
Arr at 0 range 0 .. 1;
end record;
-- SLEEP_EN0_clk_sys_sram array
type SLEEP_EN0_clk_sys_sram_Field_Array is array (0 .. 3) of Boolean
with Component_Size => 1, Size => 4;
-- Type definition for SLEEP_EN0_clk_sys_sram
type SLEEP_EN0_clk_sys_sram_Field
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- clk_sys_sram as a value
Val : HAL.UInt4;
when True =>
-- clk_sys_sram as an array
Arr : SLEEP_EN0_clk_sys_sram_Field_Array;
end case;
end record
with Unchecked_Union, Size => 4;
for SLEEP_EN0_clk_sys_sram_Field use record
Val at 0 range 0 .. 3;
Arr at 0 range 0 .. 3;
end record;
-- enable clock in sleep mode
type SLEEP_EN0_Register is record
clk_sys_clocks : Boolean := True;
clk_adc_adc : Boolean := True;
clk_sys_adc : Boolean := True;
clk_sys_busctrl : Boolean := True;
clk_sys_busfabric : Boolean := True;
clk_sys_dma : Boolean := True;
clk_sys_i2c : SLEEP_EN0_clk_sys_i2c_Field :=
(As_Array => False, Val => 16#1#);
clk_sys_io : Boolean := True;
clk_sys_jtag : Boolean := True;
clk_sys_vreg_and_chip_reset : Boolean := True;
clk_sys_pads : Boolean := True;
clk_sys_pio : SLEEP_EN0_clk_sys_pio_Field :=
(As_Array => False, Val => 16#1#);
clk_sys_pll_sys : Boolean := True;
clk_sys_pll_usb : Boolean := True;
clk_sys_psm : Boolean := True;
clk_sys_pwm : Boolean := True;
clk_sys_resets : Boolean := True;
clk_sys_rom : Boolean := True;
clk_sys_rosc : Boolean := True;
clk_rtc_rtc : Boolean := True;
clk_sys_rtc : Boolean := True;
clk_sys_sio : Boolean := True;
clk_peri_spi0 : Boolean := True;
clk_sys_spi0 : Boolean := True;
clk_peri_spi1 : Boolean := True;
clk_sys_spi1 : Boolean := True;
clk_sys_sram : SLEEP_EN0_clk_sys_sram_Field :=
(As_Array => False, Val => 16#1#);
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for SLEEP_EN0_Register use record
clk_sys_clocks at 0 range 0 .. 0;
clk_adc_adc at 0 range 1 .. 1;
clk_sys_adc at 0 range 2 .. 2;
clk_sys_busctrl at 0 range 3 .. 3;
clk_sys_busfabric at 0 range 4 .. 4;
clk_sys_dma at 0 range 5 .. 5;
clk_sys_i2c at 0 range 6 .. 7;
clk_sys_io at 0 range 8 .. 8;
clk_sys_jtag at 0 range 9 .. 9;
clk_sys_vreg_and_chip_reset at 0 range 10 .. 10;
clk_sys_pads at 0 range 11 .. 11;
clk_sys_pio at 0 range 12 .. 13;
clk_sys_pll_sys at 0 range 14 .. 14;
clk_sys_pll_usb at 0 range 15 .. 15;
clk_sys_psm at 0 range 16 .. 16;
clk_sys_pwm at 0 range 17 .. 17;
clk_sys_resets at 0 range 18 .. 18;
clk_sys_rom at 0 range 19 .. 19;
clk_sys_rosc at 0 range 20 .. 20;
clk_rtc_rtc at 0 range 21 .. 21;
clk_sys_rtc at 0 range 22 .. 22;
clk_sys_sio at 0 range 23 .. 23;
clk_peri_spi0 at 0 range 24 .. 24;
clk_sys_spi0 at 0 range 25 .. 25;
clk_peri_spi1 at 0 range 26 .. 26;
clk_sys_spi1 at 0 range 27 .. 27;
clk_sys_sram at 0 range 28 .. 31;
end record;
-- SLEEP_EN1_clk_sys_sram array
type SLEEP_EN1_clk_sys_sram_Field_Array is array (4 .. 5) of Boolean
with Component_Size => 1, Size => 2;
-- Type definition for SLEEP_EN1_clk_sys_sram
type SLEEP_EN1_clk_sys_sram_Field
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- clk_sys_sram as a value
Val : HAL.UInt2;
when True =>
-- clk_sys_sram as an array
Arr : SLEEP_EN1_clk_sys_sram_Field_Array;
end case;
end record
with Unchecked_Union, Size => 2;
for SLEEP_EN1_clk_sys_sram_Field use record
Val at 0 range 0 .. 1;
Arr at 0 range 0 .. 1;
end record;
-- enable clock in sleep mode
type SLEEP_EN1_Register is record
clk_sys_sram : SLEEP_EN1_clk_sys_sram_Field :=
(As_Array => False, Val => 16#1#);
clk_sys_syscfg : Boolean := True;
clk_sys_sysinfo : Boolean := True;
clk_sys_tbman : Boolean := True;
clk_sys_timer : Boolean := True;
clk_peri_uart0 : Boolean := True;
clk_sys_uart0 : Boolean := True;
clk_peri_uart1 : Boolean := True;
clk_sys_uart1 : Boolean := True;
clk_sys_usbctrl : Boolean := True;
clk_usb_usbctrl : Boolean := True;
clk_sys_watchdog : Boolean := True;
clk_sys_xip : Boolean := True;
clk_sys_xosc : Boolean := True;
-- unspecified
Reserved_15_31 : HAL.UInt17 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for SLEEP_EN1_Register use record
clk_sys_sram at 0 range 0 .. 1;
clk_sys_syscfg at 0 range 2 .. 2;
clk_sys_sysinfo at 0 range 3 .. 3;
clk_sys_tbman at 0 range 4 .. 4;
clk_sys_timer at 0 range 5 .. 5;
clk_peri_uart0 at 0 range 6 .. 6;
clk_sys_uart0 at 0 range 7 .. 7;
clk_peri_uart1 at 0 range 8 .. 8;
clk_sys_uart1 at 0 range 9 .. 9;
clk_sys_usbctrl at 0 range 10 .. 10;
clk_usb_usbctrl at 0 range 11 .. 11;
clk_sys_watchdog at 0 range 12 .. 12;
clk_sys_xip at 0 range 13 .. 13;
clk_sys_xosc at 0 range 14 .. 14;
Reserved_15_31 at 0 range 15 .. 31;
end record;
-- ENABLED0_clk_sys_i2c array
type ENABLED0_clk_sys_i2c_Field_Array is array (0 .. 1) of Boolean
with Component_Size => 1, Size => 2;
-- Type definition for ENABLED0_clk_sys_i2c
type ENABLED0_clk_sys_i2c_Field
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- clk_sys_i2c as a value
Val : HAL.UInt2;
when True =>
-- clk_sys_i2c as an array
Arr : ENABLED0_clk_sys_i2c_Field_Array;
end case;
end record
with Unchecked_Union, Size => 2;
for ENABLED0_clk_sys_i2c_Field use record
Val at 0 range 0 .. 1;
Arr at 0 range 0 .. 1;
end record;
-- ENABLED0_clk_sys_pio array
type ENABLED0_clk_sys_pio_Field_Array is array (0 .. 1) of Boolean
with Component_Size => 1, Size => 2;
-- Type definition for ENABLED0_clk_sys_pio
type ENABLED0_clk_sys_pio_Field
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- clk_sys_pio as a value
Val : HAL.UInt2;
when True =>
-- clk_sys_pio as an array
Arr : ENABLED0_clk_sys_pio_Field_Array;
end case;
end record
with Unchecked_Union, Size => 2;
for ENABLED0_clk_sys_pio_Field use record
Val at 0 range 0 .. 1;
Arr at 0 range 0 .. 1;
end record;
-- ENABLED0_clk_sys_sram array
type ENABLED0_clk_sys_sram_Field_Array is array (0 .. 3) of Boolean
with Component_Size => 1, Size => 4;
-- Type definition for ENABLED0_clk_sys_sram
type ENABLED0_clk_sys_sram_Field
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- clk_sys_sram as a value
Val : HAL.UInt4;
when True =>
-- clk_sys_sram as an array
Arr : ENABLED0_clk_sys_sram_Field_Array;
end case;
end record
with Unchecked_Union, Size => 4;
for ENABLED0_clk_sys_sram_Field use record
Val at 0 range 0 .. 3;
Arr at 0 range 0 .. 3;
end record;
-- indicates the state of the clock enable
type ENABLED0_Register is record
-- Read-only.
clk_sys_clocks : Boolean;
-- Read-only.
clk_adc_adc : Boolean;
-- Read-only.
clk_sys_adc : Boolean;
-- Read-only.
clk_sys_busctrl : Boolean;
-- Read-only.
clk_sys_busfabric : Boolean;
-- Read-only.
clk_sys_dma : Boolean;
-- Read-only.
clk_sys_i2c : ENABLED0_clk_sys_i2c_Field;
-- Read-only.
clk_sys_io : Boolean;
-- Read-only.
clk_sys_jtag : Boolean;
-- Read-only.
clk_sys_vreg_and_chip_reset : Boolean;
-- Read-only.
clk_sys_pads : Boolean;
-- Read-only.
clk_sys_pio : ENABLED0_clk_sys_pio_Field;
-- Read-only.
clk_sys_pll_sys : Boolean;
-- Read-only.
clk_sys_pll_usb : Boolean;
-- Read-only.
clk_sys_psm : Boolean;
-- Read-only.
clk_sys_pwm : Boolean;
-- Read-only.
clk_sys_resets : Boolean;
-- Read-only.
clk_sys_rom : Boolean;
-- Read-only.
clk_sys_rosc : Boolean;
-- Read-only.
clk_rtc_rtc : Boolean;
-- Read-only.
clk_sys_rtc : Boolean;
-- Read-only.
clk_sys_sio : Boolean;
-- Read-only.
clk_peri_spi0 : Boolean;
-- Read-only.
clk_sys_spi0 : Boolean;
-- Read-only.
clk_peri_spi1 : Boolean;
-- Read-only.
clk_sys_spi1 : Boolean;
-- Read-only.
clk_sys_sram : ENABLED0_clk_sys_sram_Field;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for ENABLED0_Register use record
clk_sys_clocks at 0 range 0 .. 0;
clk_adc_adc at 0 range 1 .. 1;
clk_sys_adc at 0 range 2 .. 2;
clk_sys_busctrl at 0 range 3 .. 3;
clk_sys_busfabric at 0 range 4 .. 4;
clk_sys_dma at 0 range 5 .. 5;
clk_sys_i2c at 0 range 6 .. 7;
clk_sys_io at 0 range 8 .. 8;
clk_sys_jtag at 0 range 9 .. 9;
clk_sys_vreg_and_chip_reset at 0 range 10 .. 10;
clk_sys_pads at 0 range 11 .. 11;
clk_sys_pio at 0 range 12 .. 13;
clk_sys_pll_sys at 0 range 14 .. 14;
clk_sys_pll_usb at 0 range 15 .. 15;
clk_sys_psm at 0 range 16 .. 16;
clk_sys_pwm at 0 range 17 .. 17;
clk_sys_resets at 0 range 18 .. 18;
clk_sys_rom at 0 range 19 .. 19;
clk_sys_rosc at 0 range 20 .. 20;
clk_rtc_rtc at 0 range 21 .. 21;
clk_sys_rtc at 0 range 22 .. 22;
clk_sys_sio at 0 range 23 .. 23;
clk_peri_spi0 at 0 range 24 .. 24;
clk_sys_spi0 at 0 range 25 .. 25;
clk_peri_spi1 at 0 range 26 .. 26;
clk_sys_spi1 at 0 range 27 .. 27;
clk_sys_sram at 0 range 28 .. 31;
end record;
-- ENABLED1_clk_sys_sram array
type ENABLED1_clk_sys_sram_Field_Array is array (4 .. 5) of Boolean
with Component_Size => 1, Size => 2;
-- Type definition for ENABLED1_clk_sys_sram
type ENABLED1_clk_sys_sram_Field
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- clk_sys_sram as a value
Val : HAL.UInt2;
when True =>
-- clk_sys_sram as an array
Arr : ENABLED1_clk_sys_sram_Field_Array;
end case;
end record
with Unchecked_Union, Size => 2;
for ENABLED1_clk_sys_sram_Field use record
Val at 0 range 0 .. 1;
Arr at 0 range 0 .. 1;
end record;
-- indicates the state of the clock enable
type ENABLED1_Register is record
-- Read-only.
clk_sys_sram : ENABLED1_clk_sys_sram_Field;
-- Read-only.
clk_sys_syscfg : Boolean;
-- Read-only.
clk_sys_sysinfo : Boolean;
-- Read-only.
clk_sys_tbman : Boolean;
-- Read-only.
clk_sys_timer : Boolean;
-- Read-only.
clk_peri_uart0 : Boolean;
-- Read-only.
clk_sys_uart0 : Boolean;
-- Read-only.
clk_peri_uart1 : Boolean;
-- Read-only.
clk_sys_uart1 : Boolean;
-- Read-only.
clk_sys_usbctrl : Boolean;
-- Read-only.
clk_usb_usbctrl : Boolean;
-- Read-only.
clk_sys_watchdog : Boolean;
-- Read-only.
clk_sys_xip : Boolean;
-- Read-only.
clk_sys_xosc : Boolean;
-- unspecified
Reserved_15_31 : HAL.UInt17;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for ENABLED1_Register use record
clk_sys_sram at 0 range 0 .. 1;
clk_sys_syscfg at 0 range 2 .. 2;
clk_sys_sysinfo at 0 range 3 .. 3;
clk_sys_tbman at 0 range 4 .. 4;
clk_sys_timer at 0 range 5 .. 5;
clk_peri_uart0 at 0 range 6 .. 6;
clk_sys_uart0 at 0 range 7 .. 7;
clk_peri_uart1 at 0 range 8 .. 8;
clk_sys_uart1 at 0 range 9 .. 9;
clk_sys_usbctrl at 0 range 10 .. 10;
clk_usb_usbctrl at 0 range 11 .. 11;
clk_sys_watchdog at 0 range 12 .. 12;
clk_sys_xip at 0 range 13 .. 13;
clk_sys_xosc at 0 range 14 .. 14;
Reserved_15_31 at 0 range 15 .. 31;
end record;
-- Raw Interrupts
type INTR_Register is record
-- Read-only.
CLK_SYS_RESUS : Boolean;
-- unspecified
Reserved_1_31 : HAL.UInt31;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for INTR_Register use record
CLK_SYS_RESUS at 0 range 0 .. 0;
Reserved_1_31 at 0 range 1 .. 31;
end record;
-- Interrupt Enable
type INTE_Register is record
CLK_SYS_RESUS : Boolean := False;
-- unspecified
Reserved_1_31 : HAL.UInt31 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for INTE_Register use record
CLK_SYS_RESUS at 0 range 0 .. 0;
Reserved_1_31 at 0 range 1 .. 31;
end record;
-- Interrupt Force
type INTF_Register is record
CLK_SYS_RESUS : Boolean := False;
-- unspecified
Reserved_1_31 : HAL.UInt31 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for INTF_Register use record
CLK_SYS_RESUS at 0 range 0 .. 0;
Reserved_1_31 at 0 range 1 .. 31;
end record;
-- Interrupt status after masking & forcing
type INTS_Register is record
-- Read-only.
CLK_SYS_RESUS : Boolean;
-- unspecified
Reserved_1_31 : HAL.UInt31;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for INTS_Register use record
CLK_SYS_RESUS at 0 range 0 .. 0;
Reserved_1_31 at 0 range 1 .. 31;
end record;
-----------------
-- Peripherals --
-----------------
type CLOCKS_Peripheral is record
-- Clock control, can be changed on-the-fly (except for auxsrc)
CLK_GPOUT0_CTRL : aliased CLK_GPOUT0_CTRL_Register;
-- Clock divisor, can be changed on-the-fly
CLK_GPOUT0_DIV : aliased CLK_GPOUT0_DIV_Register;
-- Indicates which src is currently selected (one-hot)
CLK_GPOUT0_SELECTED : aliased HAL.UInt32;
-- Clock control, can be changed on-the-fly (except for auxsrc)
CLK_GPOUT1_CTRL : aliased CLK_GPOUT1_CTRL_Register;
-- Clock divisor, can be changed on-the-fly
CLK_GPOUT1_DIV : aliased CLK_GPOUT1_DIV_Register;
-- Indicates which src is currently selected (one-hot)
CLK_GPOUT1_SELECTED : aliased HAL.UInt32;
-- Clock control, can be changed on-the-fly (except for auxsrc)
CLK_GPOUT2_CTRL : aliased CLK_GPOUT2_CTRL_Register;
-- Clock divisor, can be changed on-the-fly
CLK_GPOUT2_DIV : aliased CLK_GPOUT2_DIV_Register;
-- Indicates which src is currently selected (one-hot)
CLK_GPOUT2_SELECTED : aliased HAL.UInt32;
-- Clock control, can be changed on-the-fly (except for auxsrc)
CLK_GPOUT3_CTRL : aliased CLK_GPOUT3_CTRL_Register;
-- Clock divisor, can be changed on-the-fly
CLK_GPOUT3_DIV : aliased CLK_GPOUT3_DIV_Register;
-- Indicates which src is currently selected (one-hot)
CLK_GPOUT3_SELECTED : aliased HAL.UInt32;
-- Clock control, can be changed on-the-fly (except for auxsrc)
CLK_REF_CTRL : aliased CLK_REF_CTRL_Register;
-- Clock divisor, can be changed on-the-fly
CLK_REF_DIV : aliased CLK_REF_DIV_Register;
-- Indicates which src is currently selected (one-hot)
CLK_REF_SELECTED : aliased HAL.UInt32;
-- Clock control, can be changed on-the-fly (except for auxsrc)
CLK_SYS_CTRL : aliased CLK_SYS_CTRL_Register;
-- Clock divisor, can be changed on-the-fly
CLK_SYS_DIV : aliased CLK_SYS_DIV_Register;
-- Indicates which src is currently selected (one-hot)
CLK_SYS_SELECTED : aliased HAL.UInt32;
-- Clock control, can be changed on-the-fly (except for auxsrc)
CLK_PERI_CTRL : aliased CLK_PERI_CTRL_Register;
-- Indicates which src is currently selected (one-hot)
CLK_PERI_SELECTED : aliased HAL.UInt32;
-- Clock control, can be changed on-the-fly (except for auxsrc)
CLK_USB_CTRL : aliased CLK_USB_CTRL_Register;
-- Clock divisor, can be changed on-the-fly
CLK_USB_DIV : aliased CLK_USB_DIV_Register;
-- Indicates which src is currently selected (one-hot)
CLK_USB_SELECTED : aliased HAL.UInt32;
-- Clock control, can be changed on-the-fly (except for auxsrc)
CLK_ADC_CTRL : aliased CLK_ADC_CTRL_Register;
-- Clock divisor, can be changed on-the-fly
CLK_ADC_DIV : aliased CLK_ADC_DIV_Register;
-- Indicates which src is currently selected (one-hot)
CLK_ADC_SELECTED : aliased HAL.UInt32;
-- Clock control, can be changed on-the-fly (except for auxsrc)
CLK_RTC_CTRL : aliased CLK_RTC_CTRL_Register;
-- Clock divisor, can be changed on-the-fly
CLK_RTC_DIV : aliased CLK_RTC_DIV_Register;
-- Indicates which src is currently selected (one-hot)
CLK_RTC_SELECTED : aliased HAL.UInt32;
CLK_SYS_RESUS_CTRL : aliased CLK_SYS_RESUS_CTRL_Register;
CLK_SYS_RESUS_STATUS : aliased CLK_SYS_RESUS_STATUS_Register;
-- Reference clock frequency in kHz
FC0_REF_KHZ : aliased FC0_REF_KHZ_Register;
-- Minimum pass frequency in kHz. This is optional. Set to 0 if you are
-- not using the pass/fail flags
FC0_MIN_KHZ : aliased FC0_MIN_KHZ_Register;
-- Maximum pass frequency in kHz. This is optional. Set to 0x1ffffff if
-- you are not using the pass/fail flags
FC0_MAX_KHZ : aliased FC0_MAX_KHZ_Register;
-- Delays the start of frequency counting to allow the mux to settle\n
-- Delay is measured in multiples of the reference clock period
FC0_DELAY : aliased FC0_DELAY_Register;
-- The test interval is 0.98us * 2**interval, but let's call it 1us *
-- 2**interval\n The default gives a test interval of 250us
FC0_INTERVAL : aliased FC0_INTERVAL_Register;
-- Clock sent to frequency counter, set to 0 when not required\n Writing
-- to this register initiates the frequency count
FC0_SRC : aliased FC0_SRC_Register;
-- Frequency counter status
FC0_STATUS : aliased FC0_STATUS_Register;
-- Result of frequency measurement, only valid when status_done=1
FC0_RESULT : aliased FC0_RESULT_Register;
-- enable clock in wake mode
WAKE_EN0 : aliased WAKE_EN0_Register;
-- enable clock in wake mode
WAKE_EN1 : aliased WAKE_EN1_Register;
-- enable clock in sleep mode
SLEEP_EN0 : aliased SLEEP_EN0_Register;
-- enable clock in sleep mode
SLEEP_EN1 : aliased SLEEP_EN1_Register;
-- indicates the state of the clock enable
ENABLED0 : aliased ENABLED0_Register;
-- indicates the state of the clock enable
ENABLED1 : aliased ENABLED1_Register;
-- Raw Interrupts
INTR : aliased INTR_Register;
-- Interrupt Enable
INTE : aliased INTE_Register;
-- Interrupt Force
INTF : aliased INTF_Register;
-- Interrupt status after masking & forcing
INTS : aliased INTS_Register;
end record
with Volatile;
for CLOCKS_Peripheral use record
CLK_GPOUT0_CTRL at 16#0# range 0 .. 31;
CLK_GPOUT0_DIV at 16#4# range 0 .. 31;
CLK_GPOUT0_SELECTED at 16#8# range 0 .. 31;
CLK_GPOUT1_CTRL at 16#C# range 0 .. 31;
CLK_GPOUT1_DIV at 16#10# range 0 .. 31;
CLK_GPOUT1_SELECTED at 16#14# range 0 .. 31;
CLK_GPOUT2_CTRL at 16#18# range 0 .. 31;
CLK_GPOUT2_DIV at 16#1C# range 0 .. 31;
CLK_GPOUT2_SELECTED at 16#20# range 0 .. 31;
CLK_GPOUT3_CTRL at 16#24# range 0 .. 31;
CLK_GPOUT3_DIV at 16#28# range 0 .. 31;
CLK_GPOUT3_SELECTED at 16#2C# range 0 .. 31;
CLK_REF_CTRL at 16#30# range 0 .. 31;
CLK_REF_DIV at 16#34# range 0 .. 31;
CLK_REF_SELECTED at 16#38# range 0 .. 31;
CLK_SYS_CTRL at 16#3C# range 0 .. 31;
CLK_SYS_DIV at 16#40# range 0 .. 31;
CLK_SYS_SELECTED at 16#44# range 0 .. 31;
CLK_PERI_CTRL at 16#48# range 0 .. 31;
CLK_PERI_SELECTED at 16#50# range 0 .. 31;
CLK_USB_CTRL at 16#54# range 0 .. 31;
CLK_USB_DIV at 16#58# range 0 .. 31;
CLK_USB_SELECTED at 16#5C# range 0 .. 31;
CLK_ADC_CTRL at 16#60# range 0 .. 31;
CLK_ADC_DIV at 16#64# range 0 .. 31;
CLK_ADC_SELECTED at 16#68# range 0 .. 31;
CLK_RTC_CTRL at 16#6C# range 0 .. 31;
CLK_RTC_DIV at 16#70# range 0 .. 31;
CLK_RTC_SELECTED at 16#74# range 0 .. 31;
CLK_SYS_RESUS_CTRL at 16#78# range 0 .. 31;
CLK_SYS_RESUS_STATUS at 16#7C# range 0 .. 31;
FC0_REF_KHZ at 16#80# range 0 .. 31;
FC0_MIN_KHZ at 16#84# range 0 .. 31;
FC0_MAX_KHZ at 16#88# range 0 .. 31;
FC0_DELAY at 16#8C# range 0 .. 31;
FC0_INTERVAL at 16#90# range 0 .. 31;
FC0_SRC at 16#94# range 0 .. 31;
FC0_STATUS at 16#98# range 0 .. 31;
FC0_RESULT at 16#9C# range 0 .. 31;
WAKE_EN0 at 16#A0# range 0 .. 31;
WAKE_EN1 at 16#A4# range 0 .. 31;
SLEEP_EN0 at 16#A8# range 0 .. 31;
SLEEP_EN1 at 16#AC# range 0 .. 31;
ENABLED0 at 16#B0# range 0 .. 31;
ENABLED1 at 16#B4# range 0 .. 31;
INTR at 16#B8# range 0 .. 31;
INTE at 16#BC# range 0 .. 31;
INTF at 16#C0# range 0 .. 31;
INTS at 16#C4# range 0 .. 31;
end record;
CLOCKS_Periph : aliased CLOCKS_Peripheral
with Import, Address => CLOCKS_Base;
end RP_SVD.CLOCKS;
|
with
AdaM.compilation_Unit,
AdaM.a_Package,
AdaM.a_Type,
AdaM.Declaration.of_exception;
package AdaM.Environment
--
--
--
is
type Item is tagged private;
procedure add_package_Standard (Self : in out Item);
procedure add (Self : in out Item; Unit : in compilation_Unit.view);
procedure clear (Self : in out Item);
function Length (Self : in Item) return Natural;
function Unit (Self : in Item; Index : Positive) return compilation_Unit.View;
function all_Types (Self : in Item) return AdaM.a_Type.Vector;
procedure print (Self : in Item);
procedure print_Entities (Self : in Item);
procedure standard_package_is (Self : in out Item; Now : in AdaM.a_Package.view);
function standard_Package (Self : in Item) return AdaM.a_Package.view;
function find (Self : in Item; Identifier : in AdaM.Identifier) return AdaM.a_Type.view;
function find (Self : in Item; Identifier : in AdaM.Identifier) return AdaM.Declaration.of_exception.view;
function find (Self : in Item; Identifier : in AdaM.Identifier) return AdaM.a_Package.view;
function fetch (Self : in Item; Identifier : in AdaM.Identifier) return AdaM.a_Package.view;
-- function parent_Name (Identifier : in String) return String;
-- function simple_Name (Identifier : in String) return String;
private
type Item is tagged
record
Units : Compilation_Unit.Vector;
standard_Package : AdaM.a_Package.view;
end record;
end AdaM.Environment;
|
with Ada.Text_Io; use Ada.Text_Io;
with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
with BT; use BT;
procedure TestBT is
Result, A, B, C : Balanced_Ternary;
begin
A := To_Balanced_Ternary("+-0++0+");
B := To_Balanced_Ternary(-436);
C := To_Balanced_Ternary("+-++-");
Result := A * (B - C);
Put("a = "); Put(To_integer(A), 4); New_Line;
Put("b = "); Put(To_integer(B), 4); New_Line;
Put("c = "); Put(To_integer(C), 4); New_Line;
Put("a * (b - c) = "); Put(To_integer(Result), 4);
Put_Line (" " & To_String(Result));
end TestBT;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2017-2018 Universidad Politécnica de Madrid --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
-------------------------------------------------------------------------------
-- Implementation of TTC subsystem
-- TTC messages are exchanged as streams on a serial interface
with User_Interface;
with GNAT.IO; use GNAT.IO;
with GNAT.Serial_Communications; use GNAT.Serial_Communications;
with Ada.Real_Time; use Ada.Real_Time;
with Ada.IO_Exceptions;
with Ada.Exceptions; use Ada.Exceptions;
with System.IO;
package body TTC is
----------------------
-- Port definitions --
----------------------
COM : aliased Serial_Port;
USB : constant Port_Name := "/dev/ttyUSB0";
----------
-- Init --
----------
procedure Init is
begin
COM.Open (USB);
COM.Set (Rate => B115200, Block => True);
end Init;
----------
-- Send --
----------
procedure Send (TC : TC_Type := HK) is
begin
null;
end Send;
-----------------
-- TM_Receiver --
-----------------
task body TM_Receiver is
begin
Init;
loop
--delay 10.0; -- let USART interface recover
receive:
begin
declare
Message : TM_Message := TM_Message'Input (COM'Access);
begin
User_Interface.Put (Message);
end;
exception
when E : others =>
User_Interface.Put (TM_Message'(Kind =>Error, Timestamp => 0));
--User_Interface.Put ("TM receive: " & Exception_Name (E));
end receive;
end loop;
exception
when E : others =>
User_Interface.Put ("TM " & Exception_Information (E));
end TM_Receiver;
---------------
-- TC_Sender --
---------------
task body TC_Sender is
begin
loop
delay 30.0;
send:
declare
Message : TC_Message := (Kind => HK, Timestamp => 0);
begin
System.IO.Put_Line("Send TC");
TC_Message'Output (COM'Access, Message);
end send;
end loop;
exception
when E : others =>
User_Interface.Put ("TC " & Exception_Information (E));
end TC_Sender;
----------------
-- TC Request --
----------------
-- protected body TC_Request
-- is
--
-- procedure Put (TC : TC_Type) is
-- begin
-- Waiting := True;
-- Next_TC := TC;
-- end Put;
--
-- function Next return TC_Type is
-- begin
-- return Next_TC;
-- end Next;
--
-- function Pending return Boolean is
-- begin
-- return Waiting;
-- end Pending;
--
-- procedure Clear is
-- begin
-- Waiting := False;
-- end Clear;
--
-- end TC_Request;
end TTC;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- S E M _ C H 4 --
-- --
-- B o d y --
-- --
-- Copyright (C) 1992-2006, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
-- Boston, MA 02110-1301, USA. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Atree; use Atree;
with Debug; use Debug;
with Einfo; use Einfo;
with Elists; use Elists;
with Errout; use Errout;
with Exp_Util; use Exp_Util;
with Fname; use Fname;
with Itypes; use Itypes;
with Lib; use Lib;
with Lib.Xref; use Lib.Xref;
with Namet; use Namet;
with Nlists; use Nlists;
with Nmake; use Nmake;
with Opt; use Opt;
with Output; use Output;
with Restrict; use Restrict;
with Rident; use Rident;
with Rtsfind; use Rtsfind;
with Sem; use Sem;
with Sem_Cat; use Sem_Cat;
with Sem_Ch3; use Sem_Ch3;
with Sem_Ch8; use Sem_Ch8;
with Sem_Dist; use Sem_Dist;
with Sem_Eval; use Sem_Eval;
with Sem_Res; use Sem_Res;
with Sem_Util; use Sem_Util;
with Sem_Type; use Sem_Type;
with Stand; use Stand;
with Sinfo; use Sinfo;
with Snames; use Snames;
with Tbuild; use Tbuild;
with GNAT.Spelling_Checker; use GNAT.Spelling_Checker;
package body Sem_Ch4 is
-----------------------
-- Local Subprograms --
-----------------------
procedure Analyze_Expression (N : Node_Id);
-- For expressions that are not names, this is just a call to analyze.
-- If the expression is a name, it may be a call to a parameterless
-- function, and if so must be converted into an explicit call node
-- and analyzed as such. This deproceduring must be done during the first
-- pass of overload resolution, because otherwise a procedure call with
-- overloaded actuals may fail to resolve. See 4327-001 for an example.
procedure Analyze_Operator_Call (N : Node_Id; Op_Id : Entity_Id);
-- Analyze a call of the form "+"(x, y), etc. The prefix of the call
-- is an operator name or an expanded name whose selector is an operator
-- name, and one possible interpretation is as a predefined operator.
procedure Analyze_Overloaded_Selected_Component (N : Node_Id);
-- If the prefix of a selected_component is overloaded, the proper
-- interpretation that yields a record type with the proper selector
-- name must be selected.
procedure Analyze_User_Defined_Binary_Op (N : Node_Id; Op_Id : Entity_Id);
-- Procedure to analyze a user defined binary operator, which is resolved
-- like a function, but instead of a list of actuals it is presented
-- with the left and right operands of an operator node.
procedure Analyze_User_Defined_Unary_Op (N : Node_Id; Op_Id : Entity_Id);
-- Procedure to analyze a user defined unary operator, which is resolved
-- like a function, but instead of a list of actuals, it is presented with
-- the operand of the operator node.
procedure Ambiguous_Operands (N : Node_Id);
-- for equality, membership, and comparison operators with overloaded
-- arguments, list possible interpretations.
procedure Analyze_One_Call
(N : Node_Id;
Nam : Entity_Id;
Report : Boolean;
Success : out Boolean;
Skip_First : Boolean := False);
-- Check one interpretation of an overloaded subprogram name for
-- compatibility with the types of the actuals in a call. If there is a
-- single interpretation which does not match, post error if Report is
-- set to True.
--
-- Nam is the entity that provides the formals against which the actuals
-- are checked. Nam is either the name of a subprogram, or the internal
-- subprogram type constructed for an access_to_subprogram. If the actuals
-- are compatible with Nam, then Nam is added to the list of candidate
-- interpretations for N, and Success is set to True.
--
-- The flag Skip_First is used when analyzing a call that was rewritten
-- from object notation. In this case the first actual may have to receive
-- an explicit dereference, depending on the first formal of the operation
-- being called. The caller will have verified that the object is legal
-- for the call. If the remaining parameters match, the first parameter
-- will rewritten as a dereference if needed, prior to completing analysis.
procedure Check_Misspelled_Selector
(Prefix : Entity_Id;
Sel : Node_Id);
-- Give possible misspelling diagnostic if Sel is likely to be
-- a misspelling of one of the selectors of the Prefix.
-- This is called by Analyze_Selected_Component after producing
-- an invalid selector error message.
function Defined_In_Scope (T : Entity_Id; S : Entity_Id) return Boolean;
-- Verify that type T is declared in scope S. Used to find intepretations
-- for operators given by expanded names. This is abstracted as a separate
-- function to handle extensions to System, where S is System, but T is
-- declared in the extension.
procedure Find_Arithmetic_Types
(L, R : Node_Id;
Op_Id : Entity_Id;
N : Node_Id);
-- L and R are the operands of an arithmetic operator. Find
-- consistent pairs of interpretations for L and R that have a
-- numeric type consistent with the semantics of the operator.
procedure Find_Comparison_Types
(L, R : Node_Id;
Op_Id : Entity_Id;
N : Node_Id);
-- L and R are operands of a comparison operator. Find consistent
-- pairs of interpretations for L and R.
procedure Find_Concatenation_Types
(L, R : Node_Id;
Op_Id : Entity_Id;
N : Node_Id);
-- For the four varieties of concatenation
procedure Find_Equality_Types
(L, R : Node_Id;
Op_Id : Entity_Id;
N : Node_Id);
-- Ditto for equality operators
procedure Find_Boolean_Types
(L, R : Node_Id;
Op_Id : Entity_Id;
N : Node_Id);
-- Ditto for binary logical operations
procedure Find_Negation_Types
(R : Node_Id;
Op_Id : Entity_Id;
N : Node_Id);
-- Find consistent interpretation for operand of negation operator
procedure Find_Non_Universal_Interpretations
(N : Node_Id;
R : Node_Id;
Op_Id : Entity_Id;
T1 : Entity_Id);
-- For equality and comparison operators, the result is always boolean,
-- and the legality of the operation is determined from the visibility
-- of the operand types. If one of the operands has a universal interpre-
-- tation, the legality check uses some compatible non-universal
-- interpretation of the other operand. N can be an operator node, or
-- a function call whose name is an operator designator.
procedure Find_Unary_Types
(R : Node_Id;
Op_Id : Entity_Id;
N : Node_Id);
-- Unary arithmetic types: plus, minus, abs
procedure Check_Arithmetic_Pair
(T1, T2 : Entity_Id;
Op_Id : Entity_Id;
N : Node_Id);
-- Subsidiary procedure to Find_Arithmetic_Types. T1 and T2 are valid
-- types for left and right operand. Determine whether they constitute
-- a valid pair for the given operator, and record the corresponding
-- interpretation of the operator node. The node N may be an operator
-- node (the usual case) or a function call whose prefix is an operator
-- designator. In both cases Op_Id is the operator name itself.
procedure Diagnose_Call (N : Node_Id; Nam : Node_Id);
-- Give detailed information on overloaded call where none of the
-- interpretations match. N is the call node, Nam the designator for
-- the overloaded entity being called.
function Junk_Operand (N : Node_Id) return Boolean;
-- Test for an operand that is an inappropriate entity (e.g. a package
-- name or a label). If so, issue an error message and return True. If
-- the operand is not an inappropriate entity kind, return False.
procedure Operator_Check (N : Node_Id);
-- Verify that an operator has received some valid interpretation. If none
-- was found, determine whether a use clause would make the operation
-- legal. The variable Candidate_Type (defined in Sem_Type) is set for
-- every type compatible with the operator, even if the operator for the
-- type is not directly visible. The routine uses this type to emit a more
-- informative message.
procedure Process_Implicit_Dereference_Prefix
(E : Entity_Id;
P : Node_Id);
-- Called when P is the prefix of an implicit dereference, denoting an
-- object E. If in semantics only mode (-gnatc or generic), record that is
-- a reference to E. Normally, such a reference is generated only when the
-- implicit dereference is expanded into an explicit one. E may be empty,
-- in which case this procedure does nothing.
procedure Remove_Abstract_Operations (N : Node_Id);
-- Ada 2005: implementation of AI-310. An abstract non-dispatching
-- operation is not a candidate interpretation.
function Try_Indexed_Call
(N : Node_Id;
Nam : Entity_Id;
Typ : Entity_Id) return Boolean;
-- If a function has defaults for all its actuals, a call to it may
-- in fact be an indexing on the result of the call. Try_Indexed_Call
-- attempts the interpretation as an indexing, prior to analysis as
-- a call. If both are possible, the node is overloaded with both
-- interpretations (same symbol but two different types).
function Try_Indirect_Call
(N : Node_Id;
Nam : Entity_Id;
Typ : Entity_Id) return Boolean;
-- Similarly, a function F that needs no actuals can return an access
-- to a subprogram, and the call F (X) interpreted as F.all (X). In
-- this case the call may be overloaded with both interpretations.
function Try_Object_Operation (N : Node_Id) return Boolean;
-- Ada 2005 (AI-252): Give support to the object operation notation
------------------------
-- Ambiguous_Operands --
------------------------
procedure Ambiguous_Operands (N : Node_Id) is
procedure List_Operand_Interps (Opnd : Node_Id);
--------------------------
-- List_Operand_Interps --
--------------------------
procedure List_Operand_Interps (Opnd : Node_Id) is
Nam : Node_Id;
Err : Node_Id := N;
begin
if Is_Overloaded (Opnd) then
if Nkind (Opnd) in N_Op then
Nam := Opnd;
elsif Nkind (Opnd) = N_Function_Call then
Nam := Name (Opnd);
else
return;
end if;
else
return;
end if;
if Opnd = Left_Opnd (N) then
Error_Msg_N
("\left operand has the following interpretations", N);
else
Error_Msg_N
("\right operand has the following interpretations", N);
Err := Opnd;
end if;
List_Interps (Nam, Err);
end List_Operand_Interps;
-- Start of processing for Ambiguous_Operands
begin
if Nkind (N) = N_In
or else Nkind (N) = N_Not_In
then
Error_Msg_N ("ambiguous operands for membership", N);
elsif Nkind (N) = N_Op_Eq
or else Nkind (N) = N_Op_Ne
then
Error_Msg_N ("ambiguous operands for equality", N);
else
Error_Msg_N ("ambiguous operands for comparison", N);
end if;
if All_Errors_Mode then
List_Operand_Interps (Left_Opnd (N));
List_Operand_Interps (Right_Opnd (N));
else
Error_Msg_N ("\use -gnatf switch for details", N);
end if;
end Ambiguous_Operands;
-----------------------
-- Analyze_Aggregate --
-----------------------
-- Most of the analysis of Aggregates requires that the type be known,
-- and is therefore put off until resolution.
procedure Analyze_Aggregate (N : Node_Id) is
begin
if No (Etype (N)) then
Set_Etype (N, Any_Composite);
end if;
end Analyze_Aggregate;
-----------------------
-- Analyze_Allocator --
-----------------------
procedure Analyze_Allocator (N : Node_Id) is
Loc : constant Source_Ptr := Sloc (N);
Sav_Errs : constant Nat := Serious_Errors_Detected;
E : Node_Id := Expression (N);
Acc_Type : Entity_Id;
Type_Id : Entity_Id;
begin
Check_Restriction (No_Allocators, N);
if Nkind (E) = N_Qualified_Expression then
Acc_Type := Create_Itype (E_Allocator_Type, N);
Set_Etype (Acc_Type, Acc_Type);
Init_Size_Align (Acc_Type);
Find_Type (Subtype_Mark (E));
Type_Id := Entity (Subtype_Mark (E));
Check_Fully_Declared (Type_Id, N);
Set_Directly_Designated_Type (Acc_Type, Type_Id);
if Is_Limited_Type (Type_Id)
and then Comes_From_Source (N)
and then not In_Instance_Body
then
-- Ada 2005 (AI-287): Do not post an error if the expression
-- corresponds to a limited aggregate. Limited aggregates
-- are checked in sem_aggr in a per-component manner
-- (compare with handling of Get_Value subprogram).
if Ada_Version >= Ada_05
and then Nkind (Expression (E)) = N_Aggregate
then
null;
else
Error_Msg_N ("initialization not allowed for limited types", N);
Explain_Limited_Type (Type_Id, N);
end if;
end if;
Analyze_And_Resolve (Expression (E), Type_Id);
-- A qualified expression requires an exact match of the type,
-- class-wide matching is not allowed.
if Is_Class_Wide_Type (Type_Id)
and then Base_Type (Etype (Expression (E))) /= Base_Type (Type_Id)
then
Wrong_Type (Expression (E), Type_Id);
end if;
Check_Non_Static_Context (Expression (E));
-- We don't analyze the qualified expression itself because it's
-- part of the allocator
Set_Etype (E, Type_Id);
-- Case where no qualified expression is present
else
declare
Def_Id : Entity_Id;
Base_Typ : Entity_Id;
begin
-- If the allocator includes a N_Subtype_Indication then a
-- constraint is present, otherwise the node is a subtype mark.
-- Introduce an explicit subtype declaration into the tree
-- defining some anonymous subtype and rewrite the allocator to
-- use this subtype rather than the subtype indication.
-- It is important to introduce the explicit subtype declaration
-- so that the bounds of the subtype indication are attached to
-- the tree in case the allocator is inside a generic unit.
if Nkind (E) = N_Subtype_Indication then
-- A constraint is only allowed for a composite type in Ada
-- 95. In Ada 83, a constraint is also allowed for an
-- access-to-composite type, but the constraint is ignored.
Find_Type (Subtype_Mark (E));
Base_Typ := Entity (Subtype_Mark (E));
if Is_Elementary_Type (Base_Typ) then
if not (Ada_Version = Ada_83
and then Is_Access_Type (Base_Typ))
then
Error_Msg_N ("constraint not allowed here", E);
if Nkind (Constraint (E))
= N_Index_Or_Discriminant_Constraint
then
Error_Msg_N
("\if qualified expression was meant, " &
"use apostrophe", Constraint (E));
end if;
end if;
-- Get rid of the bogus constraint:
Rewrite (E, New_Copy_Tree (Subtype_Mark (E)));
Analyze_Allocator (N);
return;
-- Ada 2005, AI-363: if the designated type has a constrained
-- partial view, it cannot receive a discriminant constraint,
-- and the allocated object is unconstrained.
elsif Ada_Version >= Ada_05
and then Has_Constrained_Partial_View (Base_Typ)
then
Error_Msg_N
("constraint no allowed when type " &
"has a constrained partial view", Constraint (E));
end if;
if Expander_Active then
Def_Id :=
Make_Defining_Identifier (Loc, New_Internal_Name ('S'));
Insert_Action (E,
Make_Subtype_Declaration (Loc,
Defining_Identifier => Def_Id,
Subtype_Indication => Relocate_Node (E)));
if Sav_Errs /= Serious_Errors_Detected
and then Nkind (Constraint (E))
= N_Index_Or_Discriminant_Constraint
then
Error_Msg_N
("if qualified expression was meant, " &
"use apostrophe!", Constraint (E));
end if;
E := New_Occurrence_Of (Def_Id, Loc);
Rewrite (Expression (N), E);
end if;
end if;
Type_Id := Process_Subtype (E, N);
Acc_Type := Create_Itype (E_Allocator_Type, N);
Set_Etype (Acc_Type, Acc_Type);
Init_Size_Align (Acc_Type);
Set_Directly_Designated_Type (Acc_Type, Type_Id);
Check_Fully_Declared (Type_Id, N);
-- Ada 2005 (AI-231)
if Can_Never_Be_Null (Type_Id) then
Error_Msg_N ("(Ada 2005) qualified expression required",
Expression (N));
end if;
-- Check restriction against dynamically allocated protected
-- objects. Note that when limited aggregates are supported,
-- a similar test should be applied to an allocator with a
-- qualified expression ???
if Is_Protected_Type (Type_Id) then
Check_Restriction (No_Protected_Type_Allocators, N);
end if;
-- Check for missing initialization. Skip this check if we already
-- had errors on analyzing the allocator, since in that case these
-- are probably cascaded errors
if Is_Indefinite_Subtype (Type_Id)
and then Serious_Errors_Detected = Sav_Errs
then
if Is_Class_Wide_Type (Type_Id) then
Error_Msg_N
("initialization required in class-wide allocation", N);
else
Error_Msg_N
("initialization required in unconstrained allocation", N);
end if;
end if;
end;
end if;
if Is_Abstract (Type_Id) then
Error_Msg_N ("cannot allocate abstract object", E);
end if;
if Has_Task (Designated_Type (Acc_Type)) then
Check_Restriction (No_Tasking, N);
Check_Restriction (Max_Tasks, N);
Check_Restriction (No_Task_Allocators, N);
end if;
-- If the No_Streams restriction is set, check that the type of the
-- object is not, and does not contain, any subtype derived from
-- Ada.Streams.Root_Stream_Type. Note that we guard the call to
-- Has_Stream just for efficiency reasons. There is no point in
-- spending time on a Has_Stream check if the restriction is not set.
if Restrictions.Set (No_Streams) then
if Has_Stream (Designated_Type (Acc_Type)) then
Check_Restriction (No_Streams, N);
end if;
end if;
Set_Etype (N, Acc_Type);
if not Is_Library_Level_Entity (Acc_Type) then
Check_Restriction (No_Local_Allocators, N);
end if;
if Serious_Errors_Detected > Sav_Errs then
Set_Error_Posted (N);
Set_Etype (N, Any_Type);
end if;
end Analyze_Allocator;
---------------------------
-- Analyze_Arithmetic_Op --
---------------------------
procedure Analyze_Arithmetic_Op (N : Node_Id) is
L : constant Node_Id := Left_Opnd (N);
R : constant Node_Id := Right_Opnd (N);
Op_Id : Entity_Id;
begin
Candidate_Type := Empty;
Analyze_Expression (L);
Analyze_Expression (R);
-- If the entity is already set, the node is the instantiation of
-- a generic node with a non-local reference, or was manufactured
-- by a call to Make_Op_xxx. In either case the entity is known to
-- be valid, and we do not need to collect interpretations, instead
-- we just get the single possible interpretation.
Op_Id := Entity (N);
if Present (Op_Id) then
if Ekind (Op_Id) = E_Operator then
if (Nkind (N) = N_Op_Divide or else
Nkind (N) = N_Op_Mod or else
Nkind (N) = N_Op_Multiply or else
Nkind (N) = N_Op_Rem)
and then Treat_Fixed_As_Integer (N)
then
null;
else
Set_Etype (N, Any_Type);
Find_Arithmetic_Types (L, R, Op_Id, N);
end if;
else
Set_Etype (N, Any_Type);
Add_One_Interp (N, Op_Id, Etype (Op_Id));
end if;
-- Entity is not already set, so we do need to collect interpretations
else
Op_Id := Get_Name_Entity_Id (Chars (N));
Set_Etype (N, Any_Type);
while Present (Op_Id) loop
if Ekind (Op_Id) = E_Operator
and then Present (Next_Entity (First_Entity (Op_Id)))
then
Find_Arithmetic_Types (L, R, Op_Id, N);
-- The following may seem superfluous, because an operator cannot
-- be generic, but this ignores the cleverness of the author of
-- ACVC bc1013a.
elsif Is_Overloadable (Op_Id) then
Analyze_User_Defined_Binary_Op (N, Op_Id);
end if;
Op_Id := Homonym (Op_Id);
end loop;
end if;
Operator_Check (N);
end Analyze_Arithmetic_Op;
------------------
-- Analyze_Call --
------------------
-- Function, procedure, and entry calls are checked here. The Name in
-- the call may be overloaded. The actuals have been analyzed and may
-- themselves be overloaded. On exit from this procedure, the node N
-- may have zero, one or more interpretations. In the first case an
-- error message is produced. In the last case, the node is flagged
-- as overloaded and the interpretations are collected in All_Interp.
-- If the name is an Access_To_Subprogram, it cannot be overloaded, but
-- the type-checking is similar to that of other calls.
procedure Analyze_Call (N : Node_Id) is
Actuals : constant List_Id := Parameter_Associations (N);
Nam : Node_Id := Name (N);
X : Interp_Index;
It : Interp;
Nam_Ent : Entity_Id;
Success : Boolean := False;
function Name_Denotes_Function return Boolean;
-- If the type of the name is an access to subprogram, this may be
-- the type of a name, or the return type of the function being called.
-- If the name is not an entity then it can denote a protected function.
-- Until we distinguish Etype from Return_Type, we must use this
-- routine to resolve the meaning of the name in the call.
---------------------------
-- Name_Denotes_Function --
---------------------------
function Name_Denotes_Function return Boolean is
begin
if Is_Entity_Name (Nam) then
return Ekind (Entity (Nam)) = E_Function;
elsif Nkind (Nam) = N_Selected_Component then
return Ekind (Entity (Selector_Name (Nam))) = E_Function;
else
return False;
end if;
end Name_Denotes_Function;
-- Start of processing for Analyze_Call
begin
-- Initialize the type of the result of the call to the error type,
-- which will be reset if the type is successfully resolved.
Set_Etype (N, Any_Type);
if not Is_Overloaded (Nam) then
-- Only one interpretation to check
if Ekind (Etype (Nam)) = E_Subprogram_Type then
Nam_Ent := Etype (Nam);
-- If the prefix is an access_to_subprogram, this may be an indirect
-- call. This is the case if the name in the call is not an entity
-- name, or if it is a function name in the context of a procedure
-- call. In this latter case, we have a call to a parameterless
-- function that returns a pointer_to_procedure which is the entity
-- being called.
elsif Is_Access_Type (Etype (Nam))
and then Ekind (Designated_Type (Etype (Nam))) = E_Subprogram_Type
and then
(not Name_Denotes_Function
or else Nkind (N) = N_Procedure_Call_Statement)
then
Nam_Ent := Designated_Type (Etype (Nam));
Insert_Explicit_Dereference (Nam);
-- Selected component case. Simple entry or protected operation,
-- where the entry name is given by the selector name.
elsif Nkind (Nam) = N_Selected_Component then
Nam_Ent := Entity (Selector_Name (Nam));
if Ekind (Nam_Ent) /= E_Entry
and then Ekind (Nam_Ent) /= E_Entry_Family
and then Ekind (Nam_Ent) /= E_Function
and then Ekind (Nam_Ent) /= E_Procedure
then
Error_Msg_N ("name in call is not a callable entity", Nam);
Set_Etype (N, Any_Type);
return;
end if;
-- If the name is an Indexed component, it can be a call to a member
-- of an entry family. The prefix must be a selected component whose
-- selector is the entry. Analyze_Procedure_Call normalizes several
-- kinds of call into this form.
elsif Nkind (Nam) = N_Indexed_Component then
if Nkind (Prefix (Nam)) = N_Selected_Component then
Nam_Ent := Entity (Selector_Name (Prefix (Nam)));
else
Error_Msg_N ("name in call is not a callable entity", Nam);
Set_Etype (N, Any_Type);
return;
end if;
elsif not Is_Entity_Name (Nam) then
Error_Msg_N ("name in call is not a callable entity", Nam);
Set_Etype (N, Any_Type);
return;
else
Nam_Ent := Entity (Nam);
-- If no interpretations, give error message
if not Is_Overloadable (Nam_Ent) then
declare
L : constant Boolean := Is_List_Member (N);
K : constant Node_Kind := Nkind (Parent (N));
begin
-- If the node is in a list whose parent is not an
-- expression then it must be an attempted procedure call.
if L and then K not in N_Subexpr then
if Ekind (Entity (Nam)) = E_Generic_Procedure then
Error_Msg_NE
("must instantiate generic procedure& before call",
Nam, Entity (Nam));
else
Error_Msg_N
("procedure or entry name expected", Nam);
end if;
-- Check for tasking cases where only an entry call will do
elsif not L
and then (K = N_Entry_Call_Alternative
or else K = N_Triggering_Alternative)
then
Error_Msg_N ("entry name expected", Nam);
-- Otherwise give general error message
else
Error_Msg_N ("invalid prefix in call", Nam);
end if;
return;
end;
end if;
end if;
Analyze_One_Call (N, Nam_Ent, True, Success);
-- If this is an indirect call, the return type of the access_to
-- subprogram may be an incomplete type. At the point of the call,
-- use the full type if available, and at the same time update
-- the return type of the access_to_subprogram.
if Success
and then Nkind (Nam) = N_Explicit_Dereference
and then Ekind (Etype (N)) = E_Incomplete_Type
and then Present (Full_View (Etype (N)))
then
Set_Etype (N, Full_View (Etype (N)));
Set_Etype (Nam_Ent, Etype (N));
end if;
else
-- An overloaded selected component must denote overloaded
-- operations of a concurrent type. The interpretations are
-- attached to the simple name of those operations.
if Nkind (Nam) = N_Selected_Component then
Nam := Selector_Name (Nam);
end if;
Get_First_Interp (Nam, X, It);
while Present (It.Nam) loop
Nam_Ent := It.Nam;
-- Name may be call that returns an access to subprogram, or more
-- generally an overloaded expression one of whose interpretations
-- yields an access to subprogram. If the name is an entity, we
-- do not dereference, because the node is a call that returns
-- the access type: note difference between f(x), where the call
-- may return an access subprogram type, and f(x)(y), where the
-- type returned by the call to f is implicitly dereferenced to
-- analyze the outer call.
if Is_Access_Type (Nam_Ent) then
Nam_Ent := Designated_Type (Nam_Ent);
elsif Is_Access_Type (Etype (Nam_Ent))
and then not Is_Entity_Name (Nam)
and then Ekind (Designated_Type (Etype (Nam_Ent)))
= E_Subprogram_Type
then
Nam_Ent := Designated_Type (Etype (Nam_Ent));
end if;
Analyze_One_Call (N, Nam_Ent, False, Success);
-- If the interpretation succeeds, mark the proper type of the
-- prefix (any valid candidate will do). If not, remove the
-- candidate interpretation. This only needs to be done for
-- overloaded protected operations, for other entities disambi-
-- guation is done directly in Resolve.
if Success then
Set_Etype (Nam, It.Typ);
elsif Nkind (Name (N)) = N_Selected_Component
or else Nkind (Name (N)) = N_Function_Call
then
Remove_Interp (X);
end if;
Get_Next_Interp (X, It);
end loop;
-- If the name is the result of a function call, it can only
-- be a call to a function returning an access to subprogram.
-- Insert explicit dereference.
if Nkind (Nam) = N_Function_Call then
Insert_Explicit_Dereference (Nam);
end if;
if Etype (N) = Any_Type then
-- None of the interpretations is compatible with the actuals
Diagnose_Call (N, Nam);
-- Special checks for uninstantiated put routines
if Nkind (N) = N_Procedure_Call_Statement
and then Is_Entity_Name (Nam)
and then Chars (Nam) = Name_Put
and then List_Length (Actuals) = 1
then
declare
Arg : constant Node_Id := First (Actuals);
Typ : Entity_Id;
begin
if Nkind (Arg) = N_Parameter_Association then
Typ := Etype (Explicit_Actual_Parameter (Arg));
else
Typ := Etype (Arg);
end if;
if Is_Signed_Integer_Type (Typ) then
Error_Msg_N
("possible missing instantiation of " &
"'Text_'I'O.'Integer_'I'O!", Nam);
elsif Is_Modular_Integer_Type (Typ) then
Error_Msg_N
("possible missing instantiation of " &
"'Text_'I'O.'Modular_'I'O!", Nam);
elsif Is_Floating_Point_Type (Typ) then
Error_Msg_N
("possible missing instantiation of " &
"'Text_'I'O.'Float_'I'O!", Nam);
elsif Is_Ordinary_Fixed_Point_Type (Typ) then
Error_Msg_N
("possible missing instantiation of " &
"'Text_'I'O.'Fixed_'I'O!", Nam);
elsif Is_Decimal_Fixed_Point_Type (Typ) then
Error_Msg_N
("possible missing instantiation of " &
"'Text_'I'O.'Decimal_'I'O!", Nam);
elsif Is_Enumeration_Type (Typ) then
Error_Msg_N
("possible missing instantiation of " &
"'Text_'I'O.'Enumeration_'I'O!", Nam);
end if;
end;
end if;
elsif not Is_Overloaded (N)
and then Is_Entity_Name (Nam)
then
-- Resolution yields a single interpretation. Verify that
-- is has the proper capitalization.
Set_Entity_With_Style_Check (Nam, Entity (Nam));
Generate_Reference (Entity (Nam), Nam);
Set_Etype (Nam, Etype (Entity (Nam)));
else
Remove_Abstract_Operations (N);
end if;
End_Interp_List;
end if;
end Analyze_Call;
---------------------------
-- Analyze_Comparison_Op --
---------------------------
procedure Analyze_Comparison_Op (N : Node_Id) is
L : constant Node_Id := Left_Opnd (N);
R : constant Node_Id := Right_Opnd (N);
Op_Id : Entity_Id := Entity (N);
begin
Set_Etype (N, Any_Type);
Candidate_Type := Empty;
Analyze_Expression (L);
Analyze_Expression (R);
if Present (Op_Id) then
if Ekind (Op_Id) = E_Operator then
Find_Comparison_Types (L, R, Op_Id, N);
else
Add_One_Interp (N, Op_Id, Etype (Op_Id));
end if;
if Is_Overloaded (L) then
Set_Etype (L, Intersect_Types (L, R));
end if;
else
Op_Id := Get_Name_Entity_Id (Chars (N));
while Present (Op_Id) loop
if Ekind (Op_Id) = E_Operator then
Find_Comparison_Types (L, R, Op_Id, N);
else
Analyze_User_Defined_Binary_Op (N, Op_Id);
end if;
Op_Id := Homonym (Op_Id);
end loop;
end if;
Operator_Check (N);
end Analyze_Comparison_Op;
---------------------------
-- Analyze_Concatenation --
---------------------------
-- If the only one-dimensional array type in scope is String,
-- this is the resulting type of the operation. Otherwise there
-- will be a concatenation operation defined for each user-defined
-- one-dimensional array.
procedure Analyze_Concatenation (N : Node_Id) is
L : constant Node_Id := Left_Opnd (N);
R : constant Node_Id := Right_Opnd (N);
Op_Id : Entity_Id := Entity (N);
LT : Entity_Id;
RT : Entity_Id;
begin
Set_Etype (N, Any_Type);
Candidate_Type := Empty;
Analyze_Expression (L);
Analyze_Expression (R);
-- If the entity is present, the node appears in an instance,
-- and denotes a predefined concatenation operation. The resulting
-- type is obtained from the arguments when possible. If the arguments
-- are aggregates, the array type and the concatenation type must be
-- visible.
if Present (Op_Id) then
if Ekind (Op_Id) = E_Operator then
LT := Base_Type (Etype (L));
RT := Base_Type (Etype (R));
if Is_Array_Type (LT)
and then (RT = LT or else RT = Base_Type (Component_Type (LT)))
then
Add_One_Interp (N, Op_Id, LT);
elsif Is_Array_Type (RT)
and then LT = Base_Type (Component_Type (RT))
then
Add_One_Interp (N, Op_Id, RT);
-- If one operand is a string type or a user-defined array type,
-- and the other is a literal, result is of the specific type.
elsif
(Root_Type (LT) = Standard_String
or else Scope (LT) /= Standard_Standard)
and then Etype (R) = Any_String
then
Add_One_Interp (N, Op_Id, LT);
elsif
(Root_Type (RT) = Standard_String
or else Scope (RT) /= Standard_Standard)
and then Etype (L) = Any_String
then
Add_One_Interp (N, Op_Id, RT);
elsif not Is_Generic_Type (Etype (Op_Id)) then
Add_One_Interp (N, Op_Id, Etype (Op_Id));
else
-- Type and its operations must be visible
Set_Entity (N, Empty);
Analyze_Concatenation (N);
end if;
else
Add_One_Interp (N, Op_Id, Etype (Op_Id));
end if;
else
Op_Id := Get_Name_Entity_Id (Name_Op_Concat);
while Present (Op_Id) loop
if Ekind (Op_Id) = E_Operator then
-- Do not consider operators declared in dead code, they can
-- not be part of the resolution.
if Is_Eliminated (Op_Id) then
null;
else
Find_Concatenation_Types (L, R, Op_Id, N);
end if;
else
Analyze_User_Defined_Binary_Op (N, Op_Id);
end if;
Op_Id := Homonym (Op_Id);
end loop;
end if;
Operator_Check (N);
end Analyze_Concatenation;
------------------------------------
-- Analyze_Conditional_Expression --
------------------------------------
procedure Analyze_Conditional_Expression (N : Node_Id) is
Condition : constant Node_Id := First (Expressions (N));
Then_Expr : constant Node_Id := Next (Condition);
Else_Expr : constant Node_Id := Next (Then_Expr);
begin
Analyze_Expression (Condition);
Analyze_Expression (Then_Expr);
Analyze_Expression (Else_Expr);
Set_Etype (N, Etype (Then_Expr));
end Analyze_Conditional_Expression;
-------------------------
-- Analyze_Equality_Op --
-------------------------
procedure Analyze_Equality_Op (N : Node_Id) is
Loc : constant Source_Ptr := Sloc (N);
L : constant Node_Id := Left_Opnd (N);
R : constant Node_Id := Right_Opnd (N);
Op_Id : Entity_Id;
begin
Set_Etype (N, Any_Type);
Candidate_Type := Empty;
Analyze_Expression (L);
Analyze_Expression (R);
-- If the entity is set, the node is a generic instance with a non-local
-- reference to the predefined operator or to a user-defined function.
-- It can also be an inequality that is expanded into the negation of a
-- call to a user-defined equality operator.
-- For the predefined case, the result is Boolean, regardless of the
-- type of the operands. The operands may even be limited, if they are
-- generic actuals. If they are overloaded, label the left argument with
-- the common type that must be present, or with the type of the formal
-- of the user-defined function.
if Present (Entity (N)) then
Op_Id := Entity (N);
if Ekind (Op_Id) = E_Operator then
Add_One_Interp (N, Op_Id, Standard_Boolean);
else
Add_One_Interp (N, Op_Id, Etype (Op_Id));
end if;
if Is_Overloaded (L) then
if Ekind (Op_Id) = E_Operator then
Set_Etype (L, Intersect_Types (L, R));
else
Set_Etype (L, Etype (First_Formal (Op_Id)));
end if;
end if;
else
Op_Id := Get_Name_Entity_Id (Chars (N));
while Present (Op_Id) loop
if Ekind (Op_Id) = E_Operator then
Find_Equality_Types (L, R, Op_Id, N);
else
Analyze_User_Defined_Binary_Op (N, Op_Id);
end if;
Op_Id := Homonym (Op_Id);
end loop;
end if;
-- If there was no match, and the operator is inequality, this may
-- be a case where inequality has not been made explicit, as for
-- tagged types. Analyze the node as the negation of an equality
-- operation. This cannot be done earlier, because before analysis
-- we cannot rule out the presence of an explicit inequality.
if Etype (N) = Any_Type
and then Nkind (N) = N_Op_Ne
then
Op_Id := Get_Name_Entity_Id (Name_Op_Eq);
while Present (Op_Id) loop
if Ekind (Op_Id) = E_Operator then
Find_Equality_Types (L, R, Op_Id, N);
else
Analyze_User_Defined_Binary_Op (N, Op_Id);
end if;
Op_Id := Homonym (Op_Id);
end loop;
if Etype (N) /= Any_Type then
Op_Id := Entity (N);
Rewrite (N,
Make_Op_Not (Loc,
Right_Opnd =>
Make_Op_Eq (Loc,
Left_Opnd => Relocate_Node (Left_Opnd (N)),
Right_Opnd => Relocate_Node (Right_Opnd (N)))));
Set_Entity (Right_Opnd (N), Op_Id);
Analyze (N);
end if;
end if;
Operator_Check (N);
end Analyze_Equality_Op;
----------------------------------
-- Analyze_Explicit_Dereference --
----------------------------------
procedure Analyze_Explicit_Dereference (N : Node_Id) is
Loc : constant Source_Ptr := Sloc (N);
P : constant Node_Id := Prefix (N);
T : Entity_Id;
I : Interp_Index;
It : Interp;
New_N : Node_Id;
function Is_Function_Type return Boolean;
-- Check whether node may be interpreted as an implicit function call
----------------------
-- Is_Function_Type --
----------------------
function Is_Function_Type return Boolean is
I : Interp_Index;
It : Interp;
begin
if not Is_Overloaded (N) then
return Ekind (Base_Type (Etype (N))) = E_Subprogram_Type
and then Etype (Base_Type (Etype (N))) /= Standard_Void_Type;
else
Get_First_Interp (N, I, It);
while Present (It.Nam) loop
if Ekind (Base_Type (It.Typ)) /= E_Subprogram_Type
or else Etype (Base_Type (It.Typ)) = Standard_Void_Type
then
return False;
end if;
Get_Next_Interp (I, It);
end loop;
return True;
end if;
end Is_Function_Type;
-- Start of processing for Analyze_Explicit_Dereference
begin
Analyze (P);
Set_Etype (N, Any_Type);
-- Test for remote access to subprogram type, and if so return
-- after rewriting the original tree.
if Remote_AST_E_Dereference (P) then
return;
end if;
-- Normal processing for other than remote access to subprogram type
if not Is_Overloaded (P) then
if Is_Access_Type (Etype (P)) then
-- Set the Etype. We need to go thru Is_For_Access_Subtypes
-- to avoid other problems caused by the Private_Subtype
-- and it is safe to go to the Base_Type because this is the
-- same as converting the access value to its Base_Type.
declare
DT : Entity_Id := Designated_Type (Etype (P));
begin
if Ekind (DT) = E_Private_Subtype
and then Is_For_Access_Subtype (DT)
then
DT := Base_Type (DT);
end if;
Set_Etype (N, DT);
end;
elsif Etype (P) /= Any_Type then
Error_Msg_N ("prefix of dereference must be an access type", N);
return;
end if;
else
Get_First_Interp (P, I, It);
while Present (It.Nam) loop
T := It.Typ;
if Is_Access_Type (T) then
Add_One_Interp (N, Designated_Type (T), Designated_Type (T));
end if;
Get_Next_Interp (I, It);
end loop;
-- Error if no interpretation of the prefix has an access type
if Etype (N) = Any_Type then
Error_Msg_N
("access type required in prefix of explicit dereference", P);
Set_Etype (N, Any_Type);
return;
end if;
end if;
if Is_Function_Type
and then Nkind (Parent (N)) /= N_Indexed_Component
and then (Nkind (Parent (N)) /= N_Function_Call
or else N /= Name (Parent (N)))
and then (Nkind (Parent (N)) /= N_Procedure_Call_Statement
or else N /= Name (Parent (N)))
and then Nkind (Parent (N)) /= N_Subprogram_Renaming_Declaration
and then (Nkind (Parent (N)) /= N_Attribute_Reference
or else
(Attribute_Name (Parent (N)) /= Name_Address
and then
Attribute_Name (Parent (N)) /= Name_Access))
then
-- Name is a function call with no actuals, in a context that
-- requires deproceduring (including as an actual in an enclosing
-- function or procedure call). There are some pathological cases
-- where the prefix might include functions that return access to
-- subprograms and others that return a regular type. Disambiguation
-- of those has to take place in Resolve.
-- See e.g. 7117-014 and E317-001.
New_N :=
Make_Function_Call (Loc,
Name => Make_Explicit_Dereference (Loc, P),
Parameter_Associations => New_List);
-- If the prefix is overloaded, remove operations that have formals,
-- we know that this is a parameterless call.
if Is_Overloaded (P) then
Get_First_Interp (P, I, It);
while Present (It.Nam) loop
T := It.Typ;
if No (First_Formal (Base_Type (Designated_Type (T)))) then
Set_Etype (P, T);
else
Remove_Interp (I);
end if;
Get_Next_Interp (I, It);
end loop;
end if;
Rewrite (N, New_N);
Analyze (N);
elsif not Is_Function_Type
and then Is_Overloaded (N)
then
-- The prefix may include access to subprograms and other access
-- types. If the context selects the interpretation that is a call,
-- we cannot rewrite the node yet, but we include the result of
-- the call interpretation.
Get_First_Interp (N, I, It);
while Present (It.Nam) loop
if Ekind (Base_Type (It.Typ)) = E_Subprogram_Type
and then Etype (Base_Type (It.Typ)) /= Standard_Void_Type
then
Add_One_Interp (N, Etype (It.Typ), Etype (It.Typ));
end if;
Get_Next_Interp (I, It);
end loop;
end if;
-- A value of remote access-to-class-wide must not be dereferenced
-- (RM E.2.2(16)).
Validate_Remote_Access_To_Class_Wide_Type (N);
end Analyze_Explicit_Dereference;
------------------------
-- Analyze_Expression --
------------------------
procedure Analyze_Expression (N : Node_Id) is
begin
Analyze (N);
Check_Parameterless_Call (N);
end Analyze_Expression;
------------------------------------
-- Analyze_Indexed_Component_Form --
------------------------------------
procedure Analyze_Indexed_Component_Form (N : Node_Id) is
P : constant Node_Id := Prefix (N);
Exprs : constant List_Id := Expressions (N);
Exp : Node_Id;
P_T : Entity_Id;
E : Node_Id;
U_N : Entity_Id;
procedure Process_Function_Call;
-- Prefix in indexed component form is an overloadable entity,
-- so the node is a function call. Reformat it as such.
procedure Process_Indexed_Component;
-- Prefix in indexed component form is actually an indexed component.
-- This routine processes it, knowing that the prefix is already
-- resolved.
procedure Process_Indexed_Component_Or_Slice;
-- An indexed component with a single index may designate a slice if
-- the index is a subtype mark. This routine disambiguates these two
-- cases by resolving the prefix to see if it is a subtype mark.
procedure Process_Overloaded_Indexed_Component;
-- If the prefix of an indexed component is overloaded, the proper
-- interpretation is selected by the index types and the context.
---------------------------
-- Process_Function_Call --
---------------------------
procedure Process_Function_Call is
Actual : Node_Id;
begin
Change_Node (N, N_Function_Call);
Set_Name (N, P);
Set_Parameter_Associations (N, Exprs);
Actual := First (Parameter_Associations (N));
while Present (Actual) loop
Analyze (Actual);
Check_Parameterless_Call (Actual);
Next_Actual (Actual);
end loop;
Analyze_Call (N);
end Process_Function_Call;
-------------------------------
-- Process_Indexed_Component --
-------------------------------
procedure Process_Indexed_Component is
Exp : Node_Id;
Array_Type : Entity_Id;
Index : Node_Id;
Pent : Entity_Id := Empty;
begin
Exp := First (Exprs);
if Is_Overloaded (P) then
Process_Overloaded_Indexed_Component;
else
Array_Type := Etype (P);
if Is_Entity_Name (P) then
Pent := Entity (P);
elsif Nkind (P) = N_Selected_Component
and then Is_Entity_Name (Selector_Name (P))
then
Pent := Entity (Selector_Name (P));
end if;
-- Prefix must be appropriate for an array type, taking into
-- account a possible implicit dereference.
if Is_Access_Type (Array_Type) then
Array_Type := Designated_Type (Array_Type);
Error_Msg_NW (Warn_On_Dereference, "?implicit dereference", N);
Process_Implicit_Dereference_Prefix (Pent, P);
end if;
if Is_Array_Type (Array_Type) then
null;
elsif Present (Pent) and then Ekind (Pent) = E_Entry_Family then
Analyze (Exp);
Set_Etype (N, Any_Type);
if not Has_Compatible_Type
(Exp, Entry_Index_Type (Pent))
then
Error_Msg_N ("invalid index type in entry name", N);
elsif Present (Next (Exp)) then
Error_Msg_N ("too many subscripts in entry reference", N);
else
Set_Etype (N, Etype (P));
end if;
return;
elsif Is_Record_Type (Array_Type)
and then Remote_AST_I_Dereference (P)
then
return;
elsif Array_Type = Any_Type then
Set_Etype (N, Any_Type);
return;
-- Here we definitely have a bad indexing
else
if Nkind (Parent (N)) = N_Requeue_Statement
and then Present (Pent) and then Ekind (Pent) = E_Entry
then
Error_Msg_N
("REQUEUE does not permit parameters", First (Exprs));
elsif Is_Entity_Name (P)
and then Etype (P) = Standard_Void_Type
then
Error_Msg_NE ("incorrect use of&", P, Entity (P));
else
Error_Msg_N ("array type required in indexed component", P);
end if;
Set_Etype (N, Any_Type);
return;
end if;
Index := First_Index (Array_Type);
while Present (Index) and then Present (Exp) loop
if not Has_Compatible_Type (Exp, Etype (Index)) then
Wrong_Type (Exp, Etype (Index));
Set_Etype (N, Any_Type);
return;
end if;
Next_Index (Index);
Next (Exp);
end loop;
Set_Etype (N, Component_Type (Array_Type));
if Present (Index) then
Error_Msg_N
("too few subscripts in array reference", First (Exprs));
elsif Present (Exp) then
Error_Msg_N ("too many subscripts in array reference", Exp);
end if;
end if;
end Process_Indexed_Component;
----------------------------------------
-- Process_Indexed_Component_Or_Slice --
----------------------------------------
procedure Process_Indexed_Component_Or_Slice is
begin
Exp := First (Exprs);
while Present (Exp) loop
Analyze_Expression (Exp);
Next (Exp);
end loop;
Exp := First (Exprs);
-- If one index is present, and it is a subtype name, then the
-- node denotes a slice (note that the case of an explicit range
-- for a slice was already built as an N_Slice node in the first
-- place, so that case is not handled here).
-- We use a replace rather than a rewrite here because this is one
-- of the cases in which the tree built by the parser is plain wrong.
if No (Next (Exp))
and then Is_Entity_Name (Exp)
and then Is_Type (Entity (Exp))
then
Replace (N,
Make_Slice (Sloc (N),
Prefix => P,
Discrete_Range => New_Copy (Exp)));
Analyze (N);
-- Otherwise (more than one index present, or single index is not
-- a subtype name), then we have the indexed component case.
else
Process_Indexed_Component;
end if;
end Process_Indexed_Component_Or_Slice;
------------------------------------------
-- Process_Overloaded_Indexed_Component --
------------------------------------------
procedure Process_Overloaded_Indexed_Component is
Exp : Node_Id;
I : Interp_Index;
It : Interp;
Typ : Entity_Id;
Index : Node_Id;
Found : Boolean;
begin
Set_Etype (N, Any_Type);
Get_First_Interp (P, I, It);
while Present (It.Nam) loop
Typ := It.Typ;
if Is_Access_Type (Typ) then
Typ := Designated_Type (Typ);
Error_Msg_NW (Warn_On_Dereference, "?implicit dereference", N);
end if;
if Is_Array_Type (Typ) then
-- Got a candidate: verify that index types are compatible
Index := First_Index (Typ);
Found := True;
Exp := First (Exprs);
while Present (Index) and then Present (Exp) loop
if Has_Compatible_Type (Exp, Etype (Index)) then
null;
else
Found := False;
Remove_Interp (I);
exit;
end if;
Next_Index (Index);
Next (Exp);
end loop;
if Found and then No (Index) and then No (Exp) then
Add_One_Interp (N,
Etype (Component_Type (Typ)),
Etype (Component_Type (Typ)));
end if;
end if;
Get_Next_Interp (I, It);
end loop;
if Etype (N) = Any_Type then
Error_Msg_N ("no legal interpetation for indexed component", N);
Set_Is_Overloaded (N, False);
end if;
End_Interp_List;
end Process_Overloaded_Indexed_Component;
-- Start of processing for Analyze_Indexed_Component_Form
begin
-- Get name of array, function or type
Analyze (P);
if Nkind (N) = N_Function_Call
or else Nkind (N) = N_Procedure_Call_Statement
then
-- If P is an explicit dereference whose prefix is of a
-- remote access-to-subprogram type, then N has already
-- been rewritten as a subprogram call and analyzed.
return;
end if;
pragma Assert (Nkind (N) = N_Indexed_Component);
P_T := Base_Type (Etype (P));
if Is_Entity_Name (P)
or else Nkind (P) = N_Operator_Symbol
then
U_N := Entity (P);
if Ekind (U_N) in Type_Kind then
-- Reformat node as a type conversion
E := Remove_Head (Exprs);
if Present (First (Exprs)) then
Error_Msg_N
("argument of type conversion must be single expression", N);
end if;
Change_Node (N, N_Type_Conversion);
Set_Subtype_Mark (N, P);
Set_Etype (N, U_N);
Set_Expression (N, E);
-- After changing the node, call for the specific Analysis
-- routine directly, to avoid a double call to the expander.
Analyze_Type_Conversion (N);
return;
end if;
if Is_Overloadable (U_N) then
Process_Function_Call;
elsif Ekind (Etype (P)) = E_Subprogram_Type
or else (Is_Access_Type (Etype (P))
and then
Ekind (Designated_Type (Etype (P))) = E_Subprogram_Type)
then
-- Call to access_to-subprogram with possible implicit dereference
Process_Function_Call;
elsif Is_Generic_Subprogram (U_N) then
-- A common beginner's (or C++ templates fan) error
Error_Msg_N ("generic subprogram cannot be called", N);
Set_Etype (N, Any_Type);
return;
else
Process_Indexed_Component_Or_Slice;
end if;
-- If not an entity name, prefix is an expression that may denote
-- an array or an access-to-subprogram.
else
if Ekind (P_T) = E_Subprogram_Type
or else (Is_Access_Type (P_T)
and then
Ekind (Designated_Type (P_T)) = E_Subprogram_Type)
then
Process_Function_Call;
elsif Nkind (P) = N_Selected_Component
and then Is_Overloadable (Entity (Selector_Name (P)))
then
Process_Function_Call;
else
-- Indexed component, slice, or a call to a member of a family
-- entry, which will be converted to an entry call later.
Process_Indexed_Component_Or_Slice;
end if;
end if;
end Analyze_Indexed_Component_Form;
------------------------
-- Analyze_Logical_Op --
------------------------
procedure Analyze_Logical_Op (N : Node_Id) is
L : constant Node_Id := Left_Opnd (N);
R : constant Node_Id := Right_Opnd (N);
Op_Id : Entity_Id := Entity (N);
begin
Set_Etype (N, Any_Type);
Candidate_Type := Empty;
Analyze_Expression (L);
Analyze_Expression (R);
if Present (Op_Id) then
if Ekind (Op_Id) = E_Operator then
Find_Boolean_Types (L, R, Op_Id, N);
else
Add_One_Interp (N, Op_Id, Etype (Op_Id));
end if;
else
Op_Id := Get_Name_Entity_Id (Chars (N));
while Present (Op_Id) loop
if Ekind (Op_Id) = E_Operator then
Find_Boolean_Types (L, R, Op_Id, N);
else
Analyze_User_Defined_Binary_Op (N, Op_Id);
end if;
Op_Id := Homonym (Op_Id);
end loop;
end if;
Operator_Check (N);
end Analyze_Logical_Op;
---------------------------
-- Analyze_Membership_Op --
---------------------------
procedure Analyze_Membership_Op (N : Node_Id) is
L : constant Node_Id := Left_Opnd (N);
R : constant Node_Id := Right_Opnd (N);
Index : Interp_Index;
It : Interp;
Found : Boolean := False;
I_F : Interp_Index;
T_F : Entity_Id;
procedure Try_One_Interp (T1 : Entity_Id);
-- Routine to try one proposed interpretation. Note that the context
-- of the operation plays no role in resolving the arguments, so that
-- if there is more than one interpretation of the operands that is
-- compatible with a membership test, the operation is ambiguous.
--------------------
-- Try_One_Interp --
--------------------
procedure Try_One_Interp (T1 : Entity_Id) is
begin
if Has_Compatible_Type (R, T1) then
if Found
and then Base_Type (T1) /= Base_Type (T_F)
then
It := Disambiguate (L, I_F, Index, Any_Type);
if It = No_Interp then
Ambiguous_Operands (N);
Set_Etype (L, Any_Type);
return;
else
T_F := It.Typ;
end if;
else
Found := True;
T_F := T1;
I_F := Index;
end if;
Set_Etype (L, T_F);
end if;
end Try_One_Interp;
-- Start of processing for Analyze_Membership_Op
begin
Analyze_Expression (L);
if Nkind (R) = N_Range
or else (Nkind (R) = N_Attribute_Reference
and then Attribute_Name (R) = Name_Range)
then
Analyze (R);
if not Is_Overloaded (L) then
Try_One_Interp (Etype (L));
else
Get_First_Interp (L, Index, It);
while Present (It.Typ) loop
Try_One_Interp (It.Typ);
Get_Next_Interp (Index, It);
end loop;
end if;
-- If not a range, it can only be a subtype mark, or else there
-- is a more basic error, to be diagnosed in Find_Type.
else
Find_Type (R);
if Is_Entity_Name (R) then
Check_Fully_Declared (Entity (R), R);
end if;
end if;
-- Compatibility between expression and subtype mark or range is
-- checked during resolution. The result of the operation is Boolean
-- in any case.
Set_Etype (N, Standard_Boolean);
if Comes_From_Source (N)
and then Is_CPP_Class (Etype (Etype (Right_Opnd (N))))
then
Error_Msg_N ("membership test not applicable to cpp-class types", N);
end if;
end Analyze_Membership_Op;
----------------------
-- Analyze_Negation --
----------------------
procedure Analyze_Negation (N : Node_Id) is
R : constant Node_Id := Right_Opnd (N);
Op_Id : Entity_Id := Entity (N);
begin
Set_Etype (N, Any_Type);
Candidate_Type := Empty;
Analyze_Expression (R);
if Present (Op_Id) then
if Ekind (Op_Id) = E_Operator then
Find_Negation_Types (R, Op_Id, N);
else
Add_One_Interp (N, Op_Id, Etype (Op_Id));
end if;
else
Op_Id := Get_Name_Entity_Id (Chars (N));
while Present (Op_Id) loop
if Ekind (Op_Id) = E_Operator then
Find_Negation_Types (R, Op_Id, N);
else
Analyze_User_Defined_Unary_Op (N, Op_Id);
end if;
Op_Id := Homonym (Op_Id);
end loop;
end if;
Operator_Check (N);
end Analyze_Negation;
------------------
-- Analyze_Null --
------------------
procedure Analyze_Null (N : Node_Id) is
begin
Set_Etype (N, Any_Access);
end Analyze_Null;
----------------------
-- Analyze_One_Call --
----------------------
procedure Analyze_One_Call
(N : Node_Id;
Nam : Entity_Id;
Report : Boolean;
Success : out Boolean;
Skip_First : Boolean := False)
is
Actuals : constant List_Id := Parameter_Associations (N);
Prev_T : constant Entity_Id := Etype (N);
Formal : Entity_Id;
Actual : Node_Id;
Is_Indexed : Boolean := False;
Subp_Type : constant Entity_Id := Etype (Nam);
Norm_OK : Boolean;
procedure Indicate_Name_And_Type;
-- If candidate interpretation matches, indicate name and type of
-- result on call node.
----------------------------
-- Indicate_Name_And_Type --
----------------------------
procedure Indicate_Name_And_Type is
begin
Add_One_Interp (N, Nam, Etype (Nam));
Success := True;
-- If the prefix of the call is a name, indicate the entity
-- being called. If it is not a name, it is an expression that
-- denotes an access to subprogram or else an entry or family. In
-- the latter case, the name is a selected component, and the entity
-- being called is noted on the selector.
if not Is_Type (Nam) then
if Is_Entity_Name (Name (N))
or else Nkind (Name (N)) = N_Operator_Symbol
then
Set_Entity (Name (N), Nam);
elsif Nkind (Name (N)) = N_Selected_Component then
Set_Entity (Selector_Name (Name (N)), Nam);
end if;
end if;
if Debug_Flag_E and not Report then
Write_Str (" Overloaded call ");
Write_Int (Int (N));
Write_Str (" compatible with ");
Write_Int (Int (Nam));
Write_Eol;
end if;
end Indicate_Name_And_Type;
-- Start of processing for Analyze_One_Call
begin
Success := False;
-- If the subprogram has no formals, or if all the formals have
-- defaults, and the return type is an array type, the node may
-- denote an indexing of the result of a parameterless call.
if Needs_No_Actuals (Nam)
and then Present (Actuals)
then
if Is_Array_Type (Subp_Type) then
Is_Indexed := Try_Indexed_Call (N, Nam, Subp_Type);
elsif Is_Access_Type (Subp_Type)
and then Is_Array_Type (Designated_Type (Subp_Type))
then
Is_Indexed :=
Try_Indexed_Call (N, Nam, Designated_Type (Subp_Type));
-- The prefix can also be a parameterless function that returns an
-- access to subprogram. in which case this is an indirect call.
elsif Is_Access_Type (Subp_Type)
and then Ekind (Designated_Type (Subp_Type)) = E_Subprogram_Type
then
Is_Indexed := Try_Indirect_Call (N, Nam, Subp_Type);
end if;
end if;
Normalize_Actuals (N, Nam, (Report and not Is_Indexed), Norm_OK);
if not Norm_OK then
-- Mismatch in number or names of parameters
if Debug_Flag_E then
Write_Str (" normalization fails in call ");
Write_Int (Int (N));
Write_Str (" with subprogram ");
Write_Int (Int (Nam));
Write_Eol;
end if;
-- If the context expects a function call, discard any interpretation
-- that is a procedure. If the node is not overloaded, leave as is for
-- better error reporting when type mismatch is found.
elsif Nkind (N) = N_Function_Call
and then Is_Overloaded (Name (N))
and then Ekind (Nam) = E_Procedure
then
return;
-- Ditto for function calls in a procedure context
elsif Nkind (N) = N_Procedure_Call_Statement
and then Is_Overloaded (Name (N))
and then Etype (Nam) /= Standard_Void_Type
then
return;
elsif No (Actuals) then
-- If Normalize succeeds, then there are default parameters for
-- all formals.
Indicate_Name_And_Type;
elsif Ekind (Nam) = E_Operator then
if Nkind (N) = N_Procedure_Call_Statement then
return;
end if;
-- This can occur when the prefix of the call is an operator
-- name or an expanded name whose selector is an operator name.
Analyze_Operator_Call (N, Nam);
if Etype (N) /= Prev_T then
-- There may be a user-defined operator that hides the
-- current interpretation. We must check for this independently
-- of the analysis of the call with the user-defined operation,
-- because the parameter names may be wrong and yet the hiding
-- takes place. Fixes b34014o.
if Is_Overloaded (Name (N)) then
declare
I : Interp_Index;
It : Interp;
begin
Get_First_Interp (Name (N), I, It);
while Present (It.Nam) loop
if Ekind (It.Nam) /= E_Operator
and then Hides_Op (It.Nam, Nam)
and then
Has_Compatible_Type
(First_Actual (N), Etype (First_Formal (It.Nam)))
and then (No (Next_Actual (First_Actual (N)))
or else Has_Compatible_Type
(Next_Actual (First_Actual (N)),
Etype (Next_Formal (First_Formal (It.Nam)))))
then
Set_Etype (N, Prev_T);
return;
end if;
Get_Next_Interp (I, It);
end loop;
end;
end if;
-- If operator matches formals, record its name on the call.
-- If the operator is overloaded, Resolve will select the
-- correct one from the list of interpretations. The call
-- node itself carries the first candidate.
Set_Entity (Name (N), Nam);
Success := True;
elsif Report and then Etype (N) = Any_Type then
Error_Msg_N ("incompatible arguments for operator", N);
end if;
else
-- Normalize_Actuals has chained the named associations in the
-- correct order of the formals.
Actual := First_Actual (N);
Formal := First_Formal (Nam);
-- If we are analyzing a call rewritten from object notation,
-- skip first actual, which may be rewritten later as an
-- explicit dereference.
if Skip_First then
Next_Actual (Actual);
Next_Formal (Formal);
end if;
while Present (Actual) and then Present (Formal) loop
if Nkind (Parent (Actual)) /= N_Parameter_Association
or else Chars (Selector_Name (Parent (Actual))) = Chars (Formal)
then
if Has_Compatible_Type (Actual, Etype (Formal)) then
Next_Actual (Actual);
Next_Formal (Formal);
else
if Debug_Flag_E then
Write_Str (" type checking fails in call ");
Write_Int (Int (N));
Write_Str (" with formal ");
Write_Int (Int (Formal));
Write_Str (" in subprogram ");
Write_Int (Int (Nam));
Write_Eol;
end if;
if Report and not Is_Indexed then
-- Ada 2005 (AI-251): Complete the error notification
-- to help new Ada 2005 users
if Is_Class_Wide_Type (Etype (Formal))
and then Is_Interface (Etype (Etype (Formal)))
and then not Interface_Present_In_Ancestor
(Typ => Etype (Actual),
Iface => Etype (Etype (Formal)))
then
Error_Msg_NE
("(Ada 2005) does not implement interface }",
Actual, Etype (Etype (Formal)));
end if;
Wrong_Type (Actual, Etype (Formal));
if Nkind (Actual) = N_Op_Eq
and then Nkind (Left_Opnd (Actual)) = N_Identifier
then
Formal := First_Formal (Nam);
while Present (Formal) loop
if Chars (Left_Opnd (Actual)) = Chars (Formal) then
Error_Msg_N
("possible misspelling of `='>`!", Actual);
exit;
end if;
Next_Formal (Formal);
end loop;
end if;
if All_Errors_Mode then
Error_Msg_Sloc := Sloc (Nam);
if Is_Overloadable (Nam)
and then Present (Alias (Nam))
and then not Comes_From_Source (Nam)
then
Error_Msg_NE
(" =='> in call to &#(inherited)!", Actual, Nam);
elsif Ekind (Nam) = E_Subprogram_Type then
declare
Access_To_Subprogram_Typ :
constant Entity_Id :=
Defining_Identifier
(Associated_Node_For_Itype (Nam));
begin
Error_Msg_NE (
" =='> in call to dereference of &#!",
Actual, Access_To_Subprogram_Typ);
end;
else
Error_Msg_NE (" =='> in call to &#!", Actual, Nam);
end if;
end if;
end if;
return;
end if;
else
-- Normalize_Actuals has verified that a default value exists
-- for this formal. Current actual names a subsequent formal.
Next_Formal (Formal);
end if;
end loop;
-- On exit, all actuals match
Indicate_Name_And_Type;
end if;
end Analyze_One_Call;
---------------------------
-- Analyze_Operator_Call --
---------------------------
procedure Analyze_Operator_Call (N : Node_Id; Op_Id : Entity_Id) is
Op_Name : constant Name_Id := Chars (Op_Id);
Act1 : constant Node_Id := First_Actual (N);
Act2 : constant Node_Id := Next_Actual (Act1);
begin
-- Binary operator case
if Present (Act2) then
-- If more than two operands, then not binary operator after all
if Present (Next_Actual (Act2)) then
return;
elsif Op_Name = Name_Op_Add
or else Op_Name = Name_Op_Subtract
or else Op_Name = Name_Op_Multiply
or else Op_Name = Name_Op_Divide
or else Op_Name = Name_Op_Mod
or else Op_Name = Name_Op_Rem
or else Op_Name = Name_Op_Expon
then
Find_Arithmetic_Types (Act1, Act2, Op_Id, N);
elsif Op_Name = Name_Op_And
or else Op_Name = Name_Op_Or
or else Op_Name = Name_Op_Xor
then
Find_Boolean_Types (Act1, Act2, Op_Id, N);
elsif Op_Name = Name_Op_Lt
or else Op_Name = Name_Op_Le
or else Op_Name = Name_Op_Gt
or else Op_Name = Name_Op_Ge
then
Find_Comparison_Types (Act1, Act2, Op_Id, N);
elsif Op_Name = Name_Op_Eq
or else Op_Name = Name_Op_Ne
then
Find_Equality_Types (Act1, Act2, Op_Id, N);
elsif Op_Name = Name_Op_Concat then
Find_Concatenation_Types (Act1, Act2, Op_Id, N);
-- Is this else null correct, or should it be an abort???
else
null;
end if;
-- Unary operator case
else
if Op_Name = Name_Op_Subtract or else
Op_Name = Name_Op_Add or else
Op_Name = Name_Op_Abs
then
Find_Unary_Types (Act1, Op_Id, N);
elsif
Op_Name = Name_Op_Not
then
Find_Negation_Types (Act1, Op_Id, N);
-- Is this else null correct, or should it be an abort???
else
null;
end if;
end if;
end Analyze_Operator_Call;
-------------------------------------------
-- Analyze_Overloaded_Selected_Component --
-------------------------------------------
procedure Analyze_Overloaded_Selected_Component (N : Node_Id) is
Nam : constant Node_Id := Prefix (N);
Sel : constant Node_Id := Selector_Name (N);
Comp : Entity_Id;
I : Interp_Index;
It : Interp;
T : Entity_Id;
begin
Set_Etype (Sel, Any_Type);
Get_First_Interp (Nam, I, It);
while Present (It.Typ) loop
if Is_Access_Type (It.Typ) then
T := Designated_Type (It.Typ);
Error_Msg_NW (Warn_On_Dereference, "?implicit dereference", N);
else
T := It.Typ;
end if;
if Is_Record_Type (T) then
Comp := First_Entity (T);
while Present (Comp) loop
if Chars (Comp) = Chars (Sel)
and then Is_Visible_Component (Comp)
then
Set_Entity_With_Style_Check (Sel, Comp);
Generate_Reference (Comp, Sel);
Set_Etype (Sel, Etype (Comp));
Add_One_Interp (N, Etype (Comp), Etype (Comp));
-- This also specifies a candidate to resolve the name.
-- Further overloading will be resolved from context.
Set_Etype (Nam, It.Typ);
end if;
Next_Entity (Comp);
end loop;
elsif Is_Concurrent_Type (T) then
Comp := First_Entity (T);
while Present (Comp)
and then Comp /= First_Private_Entity (T)
loop
if Chars (Comp) = Chars (Sel) then
if Is_Overloadable (Comp) then
Add_One_Interp (Sel, Comp, Etype (Comp));
else
Set_Entity_With_Style_Check (Sel, Comp);
Generate_Reference (Comp, Sel);
end if;
Set_Etype (Sel, Etype (Comp));
Set_Etype (N, Etype (Comp));
Set_Etype (Nam, It.Typ);
-- For access type case, introduce explicit deference for
-- more uniform treatment of entry calls.
if Is_Access_Type (Etype (Nam)) then
Insert_Explicit_Dereference (Nam);
Error_Msg_NW
(Warn_On_Dereference, "?implicit dereference", N);
end if;
end if;
Next_Entity (Comp);
end loop;
Set_Is_Overloaded (N, Is_Overloaded (Sel));
end if;
Get_Next_Interp (I, It);
end loop;
if Etype (N) = Any_Type then
Error_Msg_NE ("undefined selector& for overloaded prefix", N, Sel);
Set_Entity (Sel, Any_Id);
Set_Etype (Sel, Any_Type);
end if;
end Analyze_Overloaded_Selected_Component;
----------------------------------
-- Analyze_Qualified_Expression --
----------------------------------
procedure Analyze_Qualified_Expression (N : Node_Id) is
Mark : constant Entity_Id := Subtype_Mark (N);
T : Entity_Id;
begin
Set_Etype (N, Any_Type);
Find_Type (Mark);
T := Entity (Mark);
if T = Any_Type then
return;
end if;
Check_Fully_Declared (T, N);
Analyze_Expression (Expression (N));
Set_Etype (N, T);
end Analyze_Qualified_Expression;
-------------------
-- Analyze_Range --
-------------------
procedure Analyze_Range (N : Node_Id) is
L : constant Node_Id := Low_Bound (N);
H : constant Node_Id := High_Bound (N);
I1, I2 : Interp_Index;
It1, It2 : Interp;
procedure Check_Common_Type (T1, T2 : Entity_Id);
-- Verify the compatibility of two types, and choose the
-- non universal one if the other is universal.
procedure Check_High_Bound (T : Entity_Id);
-- Test one interpretation of the low bound against all those
-- of the high bound.
procedure Check_Universal_Expression (N : Node_Id);
-- In Ada83, reject bounds of a universal range that are not
-- literals or entity names.
-----------------------
-- Check_Common_Type --
-----------------------
procedure Check_Common_Type (T1, T2 : Entity_Id) is
begin
if Covers (T1, T2) or else Covers (T2, T1) then
if T1 = Universal_Integer
or else T1 = Universal_Real
or else T1 = Any_Character
then
Add_One_Interp (N, Base_Type (T2), Base_Type (T2));
elsif T1 = T2 then
Add_One_Interp (N, T1, T1);
else
Add_One_Interp (N, Base_Type (T1), Base_Type (T1));
end if;
end if;
end Check_Common_Type;
----------------------
-- Check_High_Bound --
----------------------
procedure Check_High_Bound (T : Entity_Id) is
begin
if not Is_Overloaded (H) then
Check_Common_Type (T, Etype (H));
else
Get_First_Interp (H, I2, It2);
while Present (It2.Typ) loop
Check_Common_Type (T, It2.Typ);
Get_Next_Interp (I2, It2);
end loop;
end if;
end Check_High_Bound;
-----------------------------
-- Is_Universal_Expression --
-----------------------------
procedure Check_Universal_Expression (N : Node_Id) is
begin
if Etype (N) = Universal_Integer
and then Nkind (N) /= N_Integer_Literal
and then not Is_Entity_Name (N)
and then Nkind (N) /= N_Attribute_Reference
then
Error_Msg_N ("illegal bound in discrete range", N);
end if;
end Check_Universal_Expression;
-- Start of processing for Analyze_Range
begin
Set_Etype (N, Any_Type);
Analyze_Expression (L);
Analyze_Expression (H);
if Etype (L) = Any_Type or else Etype (H) = Any_Type then
return;
else
if not Is_Overloaded (L) then
Check_High_Bound (Etype (L));
else
Get_First_Interp (L, I1, It1);
while Present (It1.Typ) loop
Check_High_Bound (It1.Typ);
Get_Next_Interp (I1, It1);
end loop;
end if;
-- If result is Any_Type, then we did not find a compatible pair
if Etype (N) = Any_Type then
Error_Msg_N ("incompatible types in range ", N);
end if;
end if;
if Ada_Version = Ada_83
and then
(Nkind (Parent (N)) = N_Loop_Parameter_Specification
or else Nkind (Parent (N)) = N_Constrained_Array_Definition)
then
Check_Universal_Expression (L);
Check_Universal_Expression (H);
end if;
end Analyze_Range;
-----------------------
-- Analyze_Reference --
-----------------------
procedure Analyze_Reference (N : Node_Id) is
P : constant Node_Id := Prefix (N);
Acc_Type : Entity_Id;
begin
Analyze (P);
Acc_Type := Create_Itype (E_Allocator_Type, N);
Set_Etype (Acc_Type, Acc_Type);
Init_Size_Align (Acc_Type);
Set_Directly_Designated_Type (Acc_Type, Etype (P));
Set_Etype (N, Acc_Type);
end Analyze_Reference;
--------------------------------
-- Analyze_Selected_Component --
--------------------------------
-- Prefix is a record type or a task or protected type. In the
-- later case, the selector must denote a visible entry.
procedure Analyze_Selected_Component (N : Node_Id) is
Name : constant Node_Id := Prefix (N);
Sel : constant Node_Id := Selector_Name (N);
Comp : Entity_Id;
Entity_List : Entity_Id;
Prefix_Type : Entity_Id;
Pent : Entity_Id := Empty;
Act_Decl : Node_Id;
In_Scope : Boolean;
Parent_N : Node_Id;
-- Start of processing for Analyze_Selected_Component
begin
Set_Etype (N, Any_Type);
if Is_Overloaded (Name) then
Analyze_Overloaded_Selected_Component (N);
return;
elsif Etype (Name) = Any_Type then
Set_Entity (Sel, Any_Id);
Set_Etype (Sel, Any_Type);
return;
else
Prefix_Type := Etype (Name);
end if;
if Is_Access_Type (Prefix_Type) then
-- A RACW object can never be used as prefix of a selected
-- component since that means it is dereferenced without
-- being a controlling operand of a dispatching operation
-- (RM E.2.2(15)).
if Is_Remote_Access_To_Class_Wide_Type (Prefix_Type)
and then Comes_From_Source (N)
then
Error_Msg_N
("invalid dereference of a remote access to class-wide value",
N);
-- Normal case of selected component applied to access type
else
Error_Msg_NW (Warn_On_Dereference, "?implicit dereference", N);
if Is_Entity_Name (Name) then
Pent := Entity (Name);
elsif Nkind (Name) = N_Selected_Component
and then Is_Entity_Name (Selector_Name (Name))
then
Pent := Entity (Selector_Name (Name));
end if;
Process_Implicit_Dereference_Prefix (Pent, Name);
end if;
Prefix_Type := Designated_Type (Prefix_Type);
end if;
if Ekind (Prefix_Type) = E_Private_Subtype then
Prefix_Type := Base_Type (Prefix_Type);
end if;
Entity_List := Prefix_Type;
-- For class-wide types, use the entity list of the root type. This
-- indirection is specially important for private extensions because
-- only the root type get switched (not the class-wide type).
if Is_Class_Wide_Type (Prefix_Type) then
Entity_List := Root_Type (Prefix_Type);
end if;
Comp := First_Entity (Entity_List);
-- If the selector has an original discriminant, the node appears in
-- an instance. Replace the discriminant with the corresponding one
-- in the current discriminated type. For nested generics, this must
-- be done transitively, so note the new original discriminant.
if Nkind (Sel) = N_Identifier
and then Present (Original_Discriminant (Sel))
then
Comp := Find_Corresponding_Discriminant (Sel, Prefix_Type);
-- Mark entity before rewriting, for completeness and because
-- subsequent semantic checks might examine the original node.
Set_Entity (Sel, Comp);
Rewrite (Selector_Name (N),
New_Occurrence_Of (Comp, Sloc (N)));
Set_Original_Discriminant (Selector_Name (N), Comp);
Set_Etype (N, Etype (Comp));
if Is_Access_Type (Etype (Name)) then
Insert_Explicit_Dereference (Name);
Error_Msg_NW (Warn_On_Dereference, "?implicit dereference", N);
end if;
elsif Is_Record_Type (Prefix_Type) then
-- Find component with given name
while Present (Comp) loop
if Chars (Comp) = Chars (Sel)
and then Is_Visible_Component (Comp)
then
Set_Entity_With_Style_Check (Sel, Comp);
Generate_Reference (Comp, Sel);
Set_Etype (Sel, Etype (Comp));
if Ekind (Comp) = E_Discriminant then
if Is_Unchecked_Union (Base_Type (Prefix_Type)) then
Error_Msg_N
("cannot reference discriminant of Unchecked_Union",
Sel);
end if;
if Is_Generic_Type (Prefix_Type)
or else
Is_Generic_Type (Root_Type (Prefix_Type))
then
Set_Original_Discriminant (Sel, Comp);
end if;
end if;
-- Resolve the prefix early otherwise it is not possible to
-- build the actual subtype of the component: it may need
-- to duplicate this prefix and duplication is only allowed
-- on fully resolved expressions.
Resolve (Name);
-- Ada 2005 (AI-50217): Check wrong use of incomplete type.
-- Example:
-- limited with Pkg;
-- package Pkg is
-- type Acc_Inc is access Pkg.T;
-- X : Acc_Inc;
-- N : Natural := X.all.Comp; -- ERROR
-- end Pkg;
if Nkind (Name) = N_Explicit_Dereference
and then From_With_Type (Etype (Prefix (Name)))
and then not Is_Potentially_Use_Visible (Etype (Name))
then
Error_Msg_NE
("premature usage of incomplete}", Prefix (Name),
Etype (Prefix (Name)));
end if;
-- We never need an actual subtype for the case of a selection
-- for a indexed component of a non-packed array, since in
-- this case gigi generates all the checks and can find the
-- necessary bounds information.
-- We also do not need an actual subtype for the case of
-- a first, last, length, or range attribute applied to a
-- non-packed array, since gigi can again get the bounds in
-- these cases (gigi cannot handle the packed case, since it
-- has the bounds of the packed array type, not the original
-- bounds of the type). However, if the prefix is itself a
-- selected component, as in a.b.c (i), gigi may regard a.b.c
-- as a dynamic-sized temporary, so we do generate an actual
-- subtype for this case.
Parent_N := Parent (N);
if not Is_Packed (Etype (Comp))
and then
((Nkind (Parent_N) = N_Indexed_Component
and then Nkind (Name) /= N_Selected_Component)
or else
(Nkind (Parent_N) = N_Attribute_Reference
and then (Attribute_Name (Parent_N) = Name_First
or else
Attribute_Name (Parent_N) = Name_Last
or else
Attribute_Name (Parent_N) = Name_Length
or else
Attribute_Name (Parent_N) = Name_Range)))
then
Set_Etype (N, Etype (Comp));
-- If full analysis is not enabled, we do not generate an
-- actual subtype, because in the absence of expansion
-- reference to a formal of a protected type, for example,
-- will not be properly transformed, and will lead to
-- out-of-scope references in gigi.
-- In all other cases, we currently build an actual subtype.
-- It seems likely that many of these cases can be avoided,
-- but right now, the front end makes direct references to the
-- bounds (e.g. in generating a length check), and if we do
-- not make an actual subtype, we end up getting a direct
-- reference to a discriminant, which will not do.
elsif Full_Analysis then
Act_Decl :=
Build_Actual_Subtype_Of_Component (Etype (Comp), N);
Insert_Action (N, Act_Decl);
if No (Act_Decl) then
Set_Etype (N, Etype (Comp));
else
-- Component type depends on discriminants. Enter the
-- main attributes of the subtype.
declare
Subt : constant Entity_Id :=
Defining_Identifier (Act_Decl);
begin
Set_Etype (Subt, Base_Type (Etype (Comp)));
Set_Ekind (Subt, Ekind (Etype (Comp)));
Set_Etype (N, Subt);
end;
end if;
-- If Full_Analysis not enabled, just set the Etype
else
Set_Etype (N, Etype (Comp));
end if;
return;
end if;
Next_Entity (Comp);
end loop;
-- Ada 2005 (AI-252)
if Ada_Version >= Ada_05
and then Is_Tagged_Type (Prefix_Type)
and then Try_Object_Operation (N)
then
return;
-- If the transformation fails, it will be necessary to redo the
-- analysis with all errors enabled, to indicate candidate
-- interpretations and reasons for each failure ???
end if;
elsif Is_Private_Type (Prefix_Type) then
-- Allow access only to discriminants of the type. If the type has
-- no full view, gigi uses the parent type for the components, so we
-- do the same here.
if No (Full_View (Prefix_Type)) then
Entity_List := Root_Type (Base_Type (Prefix_Type));
Comp := First_Entity (Entity_List);
end if;
while Present (Comp) loop
if Chars (Comp) = Chars (Sel) then
if Ekind (Comp) = E_Discriminant then
Set_Entity_With_Style_Check (Sel, Comp);
Generate_Reference (Comp, Sel);
Set_Etype (Sel, Etype (Comp));
Set_Etype (N, Etype (Comp));
if Is_Generic_Type (Prefix_Type)
or else
Is_Generic_Type (Root_Type (Prefix_Type))
then
Set_Original_Discriminant (Sel, Comp);
end if;
else
Error_Msg_NE
("invisible selector for }",
N, First_Subtype (Prefix_Type));
Set_Entity (Sel, Any_Id);
Set_Etype (N, Any_Type);
end if;
return;
end if;
Next_Entity (Comp);
end loop;
elsif Is_Concurrent_Type (Prefix_Type) then
-- Prefix is concurrent type. Find visible operation with given name
-- For a task, this can only include entries or discriminants if the
-- task type is not an enclosing scope. If it is an enclosing scope
-- (e.g. in an inner task) then all entities are visible, but the
-- prefix must denote the enclosing scope, i.e. can only be a direct
-- name or an expanded name.
Set_Etype (Sel, Any_Type);
In_Scope := In_Open_Scopes (Prefix_Type);
while Present (Comp) loop
if Chars (Comp) = Chars (Sel) then
if Is_Overloadable (Comp) then
Add_One_Interp (Sel, Comp, Etype (Comp));
elsif Ekind (Comp) = E_Discriminant
or else Ekind (Comp) = E_Entry_Family
or else (In_Scope
and then Is_Entity_Name (Name))
then
Set_Entity_With_Style_Check (Sel, Comp);
Generate_Reference (Comp, Sel);
else
goto Next_Comp;
end if;
Set_Etype (Sel, Etype (Comp));
Set_Etype (N, Etype (Comp));
if Ekind (Comp) = E_Discriminant then
Set_Original_Discriminant (Sel, Comp);
end if;
-- For access type case, introduce explicit deference for more
-- uniform treatment of entry calls.
if Is_Access_Type (Etype (Name)) then
Insert_Explicit_Dereference (Name);
Error_Msg_NW
(Warn_On_Dereference, "?implicit dereference", N);
end if;
end if;
<<Next_Comp>>
Next_Entity (Comp);
exit when not In_Scope
and then
Comp = First_Private_Entity (Base_Type (Prefix_Type));
end loop;
Set_Is_Overloaded (N, Is_Overloaded (Sel));
else
-- Invalid prefix
Error_Msg_NE ("invalid prefix in selected component&", N, Sel);
end if;
-- If N still has no type, the component is not defined in the prefix
if Etype (N) = Any_Type then
-- If the prefix is a single concurrent object, use its name in the
-- error message, rather than that of its anonymous type.
if Is_Concurrent_Type (Prefix_Type)
and then Is_Internal_Name (Chars (Prefix_Type))
and then not Is_Derived_Type (Prefix_Type)
and then Is_Entity_Name (Name)
then
Error_Msg_Node_2 := Entity (Name);
Error_Msg_NE ("no selector& for&", N, Sel);
Check_Misspelled_Selector (Entity_List, Sel);
elsif Is_Generic_Type (Prefix_Type)
and then Ekind (Prefix_Type) = E_Record_Type_With_Private
and then Prefix_Type /= Etype (Prefix_Type)
and then Is_Record_Type (Etype (Prefix_Type))
then
-- If this is a derived formal type, the parent may have
-- different visibility at this point. Try for an inherited
-- component before reporting an error.
Set_Etype (Prefix (N), Etype (Prefix_Type));
Analyze_Selected_Component (N);
return;
elsif Ekind (Prefix_Type) = E_Record_Subtype_With_Private
and then Is_Generic_Actual_Type (Prefix_Type)
and then Present (Full_View (Prefix_Type))
then
-- Similarly, if this the actual for a formal derived type, the
-- component inherited from the generic parent may not be visible
-- in the actual, but the selected component is legal.
declare
Comp : Entity_Id;
begin
Comp :=
First_Component (Generic_Parent_Type (Parent (Prefix_Type)));
while Present (Comp) loop
if Chars (Comp) = Chars (Sel) then
Set_Entity_With_Style_Check (Sel, Comp);
Set_Etype (Sel, Etype (Comp));
Set_Etype (N, Etype (Comp));
return;
end if;
Next_Component (Comp);
end loop;
pragma Assert (Etype (N) /= Any_Type);
end;
else
if Ekind (Prefix_Type) = E_Record_Subtype then
-- Check whether this is a component of the base type
-- which is absent from a statically constrained subtype.
-- This will raise constraint error at run-time, but is
-- not a compile-time error. When the selector is illegal
-- for base type as well fall through and generate a
-- compilation error anyway.
Comp := First_Component (Base_Type (Prefix_Type));
while Present (Comp) loop
if Chars (Comp) = Chars (Sel)
and then Is_Visible_Component (Comp)
then
Set_Entity_With_Style_Check (Sel, Comp);
Generate_Reference (Comp, Sel);
Set_Etype (Sel, Etype (Comp));
Set_Etype (N, Etype (Comp));
-- Emit appropriate message. Gigi will replace the
-- node subsequently with the appropriate Raise.
Apply_Compile_Time_Constraint_Error
(N, "component not present in }?",
CE_Discriminant_Check_Failed,
Ent => Prefix_Type, Rep => False);
Set_Raises_Constraint_Error (N);
return;
end if;
Next_Component (Comp);
end loop;
end if;
Error_Msg_Node_2 := First_Subtype (Prefix_Type);
Error_Msg_NE ("no selector& for}", N, Sel);
Check_Misspelled_Selector (Entity_List, Sel);
end if;
Set_Entity (Sel, Any_Id);
Set_Etype (Sel, Any_Type);
end if;
end Analyze_Selected_Component;
---------------------------
-- Analyze_Short_Circuit --
---------------------------
procedure Analyze_Short_Circuit (N : Node_Id) is
L : constant Node_Id := Left_Opnd (N);
R : constant Node_Id := Right_Opnd (N);
Ind : Interp_Index;
It : Interp;
begin
Analyze_Expression (L);
Analyze_Expression (R);
Set_Etype (N, Any_Type);
if not Is_Overloaded (L) then
if Root_Type (Etype (L)) = Standard_Boolean
and then Has_Compatible_Type (R, Etype (L))
then
Add_One_Interp (N, Etype (L), Etype (L));
end if;
else
Get_First_Interp (L, Ind, It);
while Present (It.Typ) loop
if Root_Type (It.Typ) = Standard_Boolean
and then Has_Compatible_Type (R, It.Typ)
then
Add_One_Interp (N, It.Typ, It.Typ);
end if;
Get_Next_Interp (Ind, It);
end loop;
end if;
-- Here we have failed to find an interpretation. Clearly we
-- know that it is not the case that both operands can have
-- an interpretation of Boolean, but this is by far the most
-- likely intended interpretation. So we simply resolve both
-- operands as Booleans, and at least one of these resolutions
-- will generate an error message, and we do not need to give
-- a further error message on the short circuit operation itself.
if Etype (N) = Any_Type then
Resolve (L, Standard_Boolean);
Resolve (R, Standard_Boolean);
Set_Etype (N, Standard_Boolean);
end if;
end Analyze_Short_Circuit;
-------------------
-- Analyze_Slice --
-------------------
procedure Analyze_Slice (N : Node_Id) is
P : constant Node_Id := Prefix (N);
D : constant Node_Id := Discrete_Range (N);
Array_Type : Entity_Id;
procedure Analyze_Overloaded_Slice;
-- If the prefix is overloaded, select those interpretations that
-- yield a one-dimensional array type.
------------------------------
-- Analyze_Overloaded_Slice --
------------------------------
procedure Analyze_Overloaded_Slice is
I : Interp_Index;
It : Interp;
Typ : Entity_Id;
begin
Set_Etype (N, Any_Type);
Get_First_Interp (P, I, It);
while Present (It.Nam) loop
Typ := It.Typ;
if Is_Access_Type (Typ) then
Typ := Designated_Type (Typ);
Error_Msg_NW (Warn_On_Dereference, "?implicit dereference", N);
end if;
if Is_Array_Type (Typ)
and then Number_Dimensions (Typ) = 1
and then Has_Compatible_Type (D, Etype (First_Index (Typ)))
then
Add_One_Interp (N, Typ, Typ);
end if;
Get_Next_Interp (I, It);
end loop;
if Etype (N) = Any_Type then
Error_Msg_N ("expect array type in prefix of slice", N);
end if;
end Analyze_Overloaded_Slice;
-- Start of processing for Analyze_Slice
begin
Analyze (P);
Analyze (D);
if Is_Overloaded (P) then
Analyze_Overloaded_Slice;
else
Array_Type := Etype (P);
Set_Etype (N, Any_Type);
if Is_Access_Type (Array_Type) then
Array_Type := Designated_Type (Array_Type);
Error_Msg_NW (Warn_On_Dereference, "?implicit dereference", N);
end if;
if not Is_Array_Type (Array_Type) then
Wrong_Type (P, Any_Array);
elsif Number_Dimensions (Array_Type) > 1 then
Error_Msg_N
("type is not one-dimensional array in slice prefix", N);
elsif not
Has_Compatible_Type (D, Etype (First_Index (Array_Type)))
then
Wrong_Type (D, Etype (First_Index (Array_Type)));
else
Set_Etype (N, Array_Type);
end if;
end if;
end Analyze_Slice;
-----------------------------
-- Analyze_Type_Conversion --
-----------------------------
procedure Analyze_Type_Conversion (N : Node_Id) is
Expr : constant Node_Id := Expression (N);
T : Entity_Id;
begin
-- If Conversion_OK is set, then the Etype is already set, and the
-- only processing required is to analyze the expression. This is
-- used to construct certain "illegal" conversions which are not
-- allowed by Ada semantics, but can be handled OK by Gigi, see
-- Sinfo for further details.
if Conversion_OK (N) then
Analyze (Expr);
return;
end if;
-- Otherwise full type analysis is required, as well as some semantic
-- checks to make sure the argument of the conversion is appropriate.
Find_Type (Subtype_Mark (N));
T := Entity (Subtype_Mark (N));
Set_Etype (N, T);
Check_Fully_Declared (T, N);
Analyze_Expression (Expr);
Validate_Remote_Type_Type_Conversion (N);
-- Only remaining step is validity checks on the argument. These
-- are skipped if the conversion does not come from the source.
if not Comes_From_Source (N) then
return;
elsif Nkind (Expr) = N_Null then
Error_Msg_N ("argument of conversion cannot be null", N);
Error_Msg_N ("\use qualified expression instead", N);
Set_Etype (N, Any_Type);
elsif Nkind (Expr) = N_Aggregate then
Error_Msg_N ("argument of conversion cannot be aggregate", N);
Error_Msg_N ("\use qualified expression instead", N);
elsif Nkind (Expr) = N_Allocator then
Error_Msg_N ("argument of conversion cannot be an allocator", N);
Error_Msg_N ("\use qualified expression instead", N);
elsif Nkind (Expr) = N_String_Literal then
Error_Msg_N ("argument of conversion cannot be string literal", N);
Error_Msg_N ("\use qualified expression instead", N);
elsif Nkind (Expr) = N_Character_Literal then
if Ada_Version = Ada_83 then
Resolve (Expr, T);
else
Error_Msg_N ("argument of conversion cannot be character literal",
N);
Error_Msg_N ("\use qualified expression instead", N);
end if;
elsif Nkind (Expr) = N_Attribute_Reference
and then
(Attribute_Name (Expr) = Name_Access or else
Attribute_Name (Expr) = Name_Unchecked_Access or else
Attribute_Name (Expr) = Name_Unrestricted_Access)
then
Error_Msg_N ("argument of conversion cannot be access", N);
Error_Msg_N ("\use qualified expression instead", N);
end if;
end Analyze_Type_Conversion;
----------------------
-- Analyze_Unary_Op --
----------------------
procedure Analyze_Unary_Op (N : Node_Id) is
R : constant Node_Id := Right_Opnd (N);
Op_Id : Entity_Id := Entity (N);
begin
Set_Etype (N, Any_Type);
Candidate_Type := Empty;
Analyze_Expression (R);
if Present (Op_Id) then
if Ekind (Op_Id) = E_Operator then
Find_Unary_Types (R, Op_Id, N);
else
Add_One_Interp (N, Op_Id, Etype (Op_Id));
end if;
else
Op_Id := Get_Name_Entity_Id (Chars (N));
while Present (Op_Id) loop
if Ekind (Op_Id) = E_Operator then
if No (Next_Entity (First_Entity (Op_Id))) then
Find_Unary_Types (R, Op_Id, N);
end if;
elsif Is_Overloadable (Op_Id) then
Analyze_User_Defined_Unary_Op (N, Op_Id);
end if;
Op_Id := Homonym (Op_Id);
end loop;
end if;
Operator_Check (N);
end Analyze_Unary_Op;
----------------------------------
-- Analyze_Unchecked_Expression --
----------------------------------
procedure Analyze_Unchecked_Expression (N : Node_Id) is
begin
Analyze (Expression (N), Suppress => All_Checks);
Set_Etype (N, Etype (Expression (N)));
Save_Interps (Expression (N), N);
end Analyze_Unchecked_Expression;
---------------------------------------
-- Analyze_Unchecked_Type_Conversion --
---------------------------------------
procedure Analyze_Unchecked_Type_Conversion (N : Node_Id) is
begin
Find_Type (Subtype_Mark (N));
Analyze_Expression (Expression (N));
Set_Etype (N, Entity (Subtype_Mark (N)));
end Analyze_Unchecked_Type_Conversion;
------------------------------------
-- Analyze_User_Defined_Binary_Op --
------------------------------------
procedure Analyze_User_Defined_Binary_Op
(N : Node_Id;
Op_Id : Entity_Id)
is
begin
-- Only do analysis if the operator Comes_From_Source, since otherwise
-- the operator was generated by the expander, and all such operators
-- always refer to the operators in package Standard.
if Comes_From_Source (N) then
declare
F1 : constant Entity_Id := First_Formal (Op_Id);
F2 : constant Entity_Id := Next_Formal (F1);
begin
-- Verify that Op_Id is a visible binary function. Note that since
-- we know Op_Id is overloaded, potentially use visible means use
-- visible for sure (RM 9.4(11)).
if Ekind (Op_Id) = E_Function
and then Present (F2)
and then (Is_Immediately_Visible (Op_Id)
or else Is_Potentially_Use_Visible (Op_Id))
and then Has_Compatible_Type (Left_Opnd (N), Etype (F1))
and then Has_Compatible_Type (Right_Opnd (N), Etype (F2))
then
Add_One_Interp (N, Op_Id, Etype (Op_Id));
if Debug_Flag_E then
Write_Str ("user defined operator ");
Write_Name (Chars (Op_Id));
Write_Str (" on node ");
Write_Int (Int (N));
Write_Eol;
end if;
end if;
end;
end if;
end Analyze_User_Defined_Binary_Op;
-----------------------------------
-- Analyze_User_Defined_Unary_Op --
-----------------------------------
procedure Analyze_User_Defined_Unary_Op
(N : Node_Id;
Op_Id : Entity_Id)
is
begin
-- Only do analysis if the operator Comes_From_Source, since otherwise
-- the operator was generated by the expander, and all such operators
-- always refer to the operators in package Standard.
if Comes_From_Source (N) then
declare
F : constant Entity_Id := First_Formal (Op_Id);
begin
-- Verify that Op_Id is a visible unary function. Note that since
-- we know Op_Id is overloaded, potentially use visible means use
-- visible for sure (RM 9.4(11)).
if Ekind (Op_Id) = E_Function
and then No (Next_Formal (F))
and then (Is_Immediately_Visible (Op_Id)
or else Is_Potentially_Use_Visible (Op_Id))
and then Has_Compatible_Type (Right_Opnd (N), Etype (F))
then
Add_One_Interp (N, Op_Id, Etype (Op_Id));
end if;
end;
end if;
end Analyze_User_Defined_Unary_Op;
---------------------------
-- Check_Arithmetic_Pair --
---------------------------
procedure Check_Arithmetic_Pair
(T1, T2 : Entity_Id;
Op_Id : Entity_Id;
N : Node_Id)
is
Op_Name : constant Name_Id := Chars (Op_Id);
function Has_Fixed_Op (Typ : Entity_Id; Op : Entity_Id) return Boolean;
-- Check whether the fixed-point type Typ has a user-defined operator
-- (multiplication or division) that should hide the corresponding
-- predefined operator. Used to implement Ada 2005 AI-264, to make
-- such operators more visible and therefore useful.
function Specific_Type (T1, T2 : Entity_Id) return Entity_Id;
-- Get specific type (i.e. non-universal type if there is one)
------------------
-- Has_Fixed_Op --
------------------
function Has_Fixed_Op (Typ : Entity_Id; Op : Entity_Id) return Boolean is
Ent : Entity_Id;
F1 : Entity_Id;
F2 : Entity_Id;
begin
-- The operation is treated as primitive if it is declared in the
-- same scope as the type, and therefore on the same entity chain.
Ent := Next_Entity (Typ);
while Present (Ent) loop
if Chars (Ent) = Chars (Op) then
F1 := First_Formal (Ent);
F2 := Next_Formal (F1);
-- The operation counts as primitive if either operand or
-- result are of the given type, and both operands are fixed
-- point types.
if (Etype (F1) = Typ
and then Is_Fixed_Point_Type (Etype (F2)))
or else
(Etype (F2) = Typ
and then Is_Fixed_Point_Type (Etype (F1)))
or else
(Etype (Ent) = Typ
and then Is_Fixed_Point_Type (Etype (F1))
and then Is_Fixed_Point_Type (Etype (F2)))
then
return True;
end if;
end if;
Next_Entity (Ent);
end loop;
return False;
end Has_Fixed_Op;
-------------------
-- Specific_Type --
-------------------
function Specific_Type (T1, T2 : Entity_Id) return Entity_Id is
begin
if T1 = Universal_Integer or else T1 = Universal_Real then
return Base_Type (T2);
else
return Base_Type (T1);
end if;
end Specific_Type;
-- Start of processing for Check_Arithmetic_Pair
begin
if Op_Name = Name_Op_Add or else Op_Name = Name_Op_Subtract then
if Is_Numeric_Type (T1)
and then Is_Numeric_Type (T2)
and then (Covers (T1, T2) or else Covers (T2, T1))
then
Add_One_Interp (N, Op_Id, Specific_Type (T1, T2));
end if;
elsif Op_Name = Name_Op_Multiply or else Op_Name = Name_Op_Divide then
if Is_Fixed_Point_Type (T1)
and then (Is_Fixed_Point_Type (T2)
or else T2 = Universal_Real)
then
-- If Treat_Fixed_As_Integer is set then the Etype is already set
-- and no further processing is required (this is the case of an
-- operator constructed by Exp_Fixd for a fixed point operation)
-- Otherwise add one interpretation with universal fixed result
-- If the operator is given in functional notation, it comes
-- from source and Fixed_As_Integer cannot apply.
if (Nkind (N) not in N_Op
or else not Treat_Fixed_As_Integer (N))
and then
(not (Ada_Version >= Ada_05 and then Has_Fixed_Op (T1, Op_Id))
or else Nkind (Parent (N)) = N_Type_Conversion)
then
Add_One_Interp (N, Op_Id, Universal_Fixed);
end if;
elsif Is_Fixed_Point_Type (T2)
and then (Nkind (N) not in N_Op
or else not Treat_Fixed_As_Integer (N))
and then T1 = Universal_Real
and then
(not (Ada_Version >= Ada_05 and then Has_Fixed_Op (T1, Op_Id))
or else Nkind (Parent (N)) = N_Type_Conversion)
then
Add_One_Interp (N, Op_Id, Universal_Fixed);
elsif Is_Numeric_Type (T1)
and then Is_Numeric_Type (T2)
and then (Covers (T1, T2) or else Covers (T2, T1))
then
Add_One_Interp (N, Op_Id, Specific_Type (T1, T2));
elsif Is_Fixed_Point_Type (T1)
and then (Base_Type (T2) = Base_Type (Standard_Integer)
or else T2 = Universal_Integer)
then
Add_One_Interp (N, Op_Id, T1);
elsif T2 = Universal_Real
and then Base_Type (T1) = Base_Type (Standard_Integer)
and then Op_Name = Name_Op_Multiply
then
Add_One_Interp (N, Op_Id, Any_Fixed);
elsif T1 = Universal_Real
and then Base_Type (T2) = Base_Type (Standard_Integer)
then
Add_One_Interp (N, Op_Id, Any_Fixed);
elsif Is_Fixed_Point_Type (T2)
and then (Base_Type (T1) = Base_Type (Standard_Integer)
or else T1 = Universal_Integer)
and then Op_Name = Name_Op_Multiply
then
Add_One_Interp (N, Op_Id, T2);
elsif T1 = Universal_Real and then T2 = Universal_Integer then
Add_One_Interp (N, Op_Id, T1);
elsif T2 = Universal_Real
and then T1 = Universal_Integer
and then Op_Name = Name_Op_Multiply
then
Add_One_Interp (N, Op_Id, T2);
end if;
elsif Op_Name = Name_Op_Mod or else Op_Name = Name_Op_Rem then
-- Note: The fixed-point operands case with Treat_Fixed_As_Integer
-- set does not require any special processing, since the Etype is
-- already set (case of operation constructed by Exp_Fixed).
if Is_Integer_Type (T1)
and then (Covers (T1, T2) or else Covers (T2, T1))
then
Add_One_Interp (N, Op_Id, Specific_Type (T1, T2));
end if;
elsif Op_Name = Name_Op_Expon then
if Is_Numeric_Type (T1)
and then not Is_Fixed_Point_Type (T1)
and then (Base_Type (T2) = Base_Type (Standard_Integer)
or else T2 = Universal_Integer)
then
Add_One_Interp (N, Op_Id, Base_Type (T1));
end if;
else pragma Assert (Nkind (N) in N_Op_Shift);
-- If not one of the predefined operators, the node may be one
-- of the intrinsic functions. Its kind is always specific, and
-- we can use it directly, rather than the name of the operation.
if Is_Integer_Type (T1)
and then (Base_Type (T2) = Base_Type (Standard_Integer)
or else T2 = Universal_Integer)
then
Add_One_Interp (N, Op_Id, Base_Type (T1));
end if;
end if;
end Check_Arithmetic_Pair;
-------------------------------
-- Check_Misspelled_Selector --
-------------------------------
procedure Check_Misspelled_Selector
(Prefix : Entity_Id;
Sel : Node_Id)
is
Max_Suggestions : constant := 2;
Nr_Of_Suggestions : Natural := 0;
Suggestion_1 : Entity_Id := Empty;
Suggestion_2 : Entity_Id := Empty;
Comp : Entity_Id;
begin
-- All the components of the prefix of selector Sel are matched
-- against Sel and a count is maintained of possible misspellings.
-- When at the end of the analysis there are one or two (not more!)
-- possible misspellings, these misspellings will be suggested as
-- possible correction.
if not (Is_Private_Type (Prefix) or else Is_Record_Type (Prefix)) then
-- Concurrent types should be handled as well ???
return;
end if;
Get_Name_String (Chars (Sel));
declare
S : constant String (1 .. Name_Len) := Name_Buffer (1 .. Name_Len);
begin
Comp := First_Entity (Prefix);
while Nr_Of_Suggestions <= Max_Suggestions
and then Present (Comp)
loop
if Is_Visible_Component (Comp) then
Get_Name_String (Chars (Comp));
if Is_Bad_Spelling_Of (Name_Buffer (1 .. Name_Len), S) then
Nr_Of_Suggestions := Nr_Of_Suggestions + 1;
case Nr_Of_Suggestions is
when 1 => Suggestion_1 := Comp;
when 2 => Suggestion_2 := Comp;
when others => exit;
end case;
end if;
end if;
Comp := Next_Entity (Comp);
end loop;
-- Report at most two suggestions
if Nr_Of_Suggestions = 1 then
Error_Msg_NE ("\possible misspelling of&", Sel, Suggestion_1);
elsif Nr_Of_Suggestions = 2 then
Error_Msg_Node_2 := Suggestion_2;
Error_Msg_NE ("\possible misspelling of& or&",
Sel, Suggestion_1);
end if;
end;
end Check_Misspelled_Selector;
----------------------
-- Defined_In_Scope --
----------------------
function Defined_In_Scope (T : Entity_Id; S : Entity_Id) return Boolean
is
S1 : constant Entity_Id := Scope (Base_Type (T));
begin
return S1 = S
or else (S1 = System_Aux_Id and then S = Scope (S1));
end Defined_In_Scope;
-------------------
-- Diagnose_Call --
-------------------
procedure Diagnose_Call (N : Node_Id; Nam : Node_Id) is
Actual : Node_Id;
X : Interp_Index;
It : Interp;
Success : Boolean;
Err_Mode : Boolean;
New_Nam : Node_Id;
Void_Interp_Seen : Boolean := False;
begin
if Ada_Version >= Ada_05 then
Actual := First_Actual (N);
while Present (Actual) loop
-- Ada 2005 (AI-50217): Post an error in case of premature
-- usage of an entity from the limited view.
if not Analyzed (Etype (Actual))
and then From_With_Type (Etype (Actual))
then
Error_Msg_Qual_Level := 1;
Error_Msg_NE
("missing with_clause for scope of imported type&",
Actual, Etype (Actual));
Error_Msg_Qual_Level := 0;
end if;
Next_Actual (Actual);
end loop;
end if;
-- Analyze each candidate call again, with full error reporting
-- for each.
Error_Msg_N
("no candidate interpretations match the actuals:!", Nam);
Err_Mode := All_Errors_Mode;
All_Errors_Mode := True;
-- If this is a call to an operation of a concurrent type,
-- the failed interpretations have been removed from the
-- name. Recover them to provide full diagnostics.
if Nkind (Parent (Nam)) = N_Selected_Component then
Set_Entity (Nam, Empty);
New_Nam := New_Copy_Tree (Parent (Nam));
Set_Is_Overloaded (New_Nam, False);
Set_Is_Overloaded (Selector_Name (New_Nam), False);
Set_Parent (New_Nam, Parent (Parent (Nam)));
Analyze_Selected_Component (New_Nam);
Get_First_Interp (Selector_Name (New_Nam), X, It);
else
Get_First_Interp (Nam, X, It);
end if;
while Present (It.Nam) loop
if Etype (It.Nam) = Standard_Void_Type then
Void_Interp_Seen := True;
end if;
Analyze_One_Call (N, It.Nam, True, Success);
Get_Next_Interp (X, It);
end loop;
if Nkind (N) = N_Function_Call then
Get_First_Interp (Nam, X, It);
while Present (It.Nam) loop
if Ekind (It.Nam) = E_Function
or else Ekind (It.Nam) = E_Operator
then
return;
else
Get_Next_Interp (X, It);
end if;
end loop;
-- If all interpretations are procedures, this deserves a
-- more precise message. Ditto if this appears as the prefix
-- of a selected component, which may be a lexical error.
Error_Msg_N
("\context requires function call, found procedure name", Nam);
if Nkind (Parent (N)) = N_Selected_Component
and then N = Prefix (Parent (N))
then
Error_Msg_N (
"\period should probably be semicolon", Parent (N));
end if;
elsif Nkind (N) = N_Procedure_Call_Statement
and then not Void_Interp_Seen
then
Error_Msg_N (
"\function name found in procedure call", Nam);
end if;
All_Errors_Mode := Err_Mode;
end Diagnose_Call;
---------------------------
-- Find_Arithmetic_Types --
---------------------------
procedure Find_Arithmetic_Types
(L, R : Node_Id;
Op_Id : Entity_Id;
N : Node_Id)
is
Index1 : Interp_Index;
Index2 : Interp_Index;
It1 : Interp;
It2 : Interp;
procedure Check_Right_Argument (T : Entity_Id);
-- Check right operand of operator
--------------------------
-- Check_Right_Argument --
--------------------------
procedure Check_Right_Argument (T : Entity_Id) is
begin
if not Is_Overloaded (R) then
Check_Arithmetic_Pair (T, Etype (R), Op_Id, N);
else
Get_First_Interp (R, Index2, It2);
while Present (It2.Typ) loop
Check_Arithmetic_Pair (T, It2.Typ, Op_Id, N);
Get_Next_Interp (Index2, It2);
end loop;
end if;
end Check_Right_Argument;
-- Start processing for Find_Arithmetic_Types
begin
if not Is_Overloaded (L) then
Check_Right_Argument (Etype (L));
else
Get_First_Interp (L, Index1, It1);
while Present (It1.Typ) loop
Check_Right_Argument (It1.Typ);
Get_Next_Interp (Index1, It1);
end loop;
end if;
end Find_Arithmetic_Types;
------------------------
-- Find_Boolean_Types --
------------------------
procedure Find_Boolean_Types
(L, R : Node_Id;
Op_Id : Entity_Id;
N : Node_Id)
is
Index : Interp_Index;
It : Interp;
procedure Check_Numeric_Argument (T : Entity_Id);
-- Special case for logical operations one of whose operands is an
-- integer literal. If both are literal the result is any modular type.
----------------------------
-- Check_Numeric_Argument --
----------------------------
procedure Check_Numeric_Argument (T : Entity_Id) is
begin
if T = Universal_Integer then
Add_One_Interp (N, Op_Id, Any_Modular);
elsif Is_Modular_Integer_Type (T) then
Add_One_Interp (N, Op_Id, T);
end if;
end Check_Numeric_Argument;
-- Start of processing for Find_Boolean_Types
begin
if not Is_Overloaded (L) then
if Etype (L) = Universal_Integer
or else Etype (L) = Any_Modular
then
if not Is_Overloaded (R) then
Check_Numeric_Argument (Etype (R));
else
Get_First_Interp (R, Index, It);
while Present (It.Typ) loop
Check_Numeric_Argument (It.Typ);
Get_Next_Interp (Index, It);
end loop;
end if;
-- If operands are aggregates, we must assume that they may be
-- boolean arrays, and leave disambiguation for the second pass.
-- If only one is an aggregate, verify that the other one has an
-- interpretation as a boolean array
elsif Nkind (L) = N_Aggregate then
if Nkind (R) = N_Aggregate then
Add_One_Interp (N, Op_Id, Etype (L));
elsif not Is_Overloaded (R) then
if Valid_Boolean_Arg (Etype (R)) then
Add_One_Interp (N, Op_Id, Etype (R));
end if;
else
Get_First_Interp (R, Index, It);
while Present (It.Typ) loop
if Valid_Boolean_Arg (It.Typ) then
Add_One_Interp (N, Op_Id, It.Typ);
end if;
Get_Next_Interp (Index, It);
end loop;
end if;
elsif Valid_Boolean_Arg (Etype (L))
and then Has_Compatible_Type (R, Etype (L))
then
Add_One_Interp (N, Op_Id, Etype (L));
end if;
else
Get_First_Interp (L, Index, It);
while Present (It.Typ) loop
if Valid_Boolean_Arg (It.Typ)
and then Has_Compatible_Type (R, It.Typ)
then
Add_One_Interp (N, Op_Id, It.Typ);
end if;
Get_Next_Interp (Index, It);
end loop;
end if;
end Find_Boolean_Types;
---------------------------
-- Find_Comparison_Types --
---------------------------
procedure Find_Comparison_Types
(L, R : Node_Id;
Op_Id : Entity_Id;
N : Node_Id)
is
Index : Interp_Index;
It : Interp;
Found : Boolean := False;
I_F : Interp_Index;
T_F : Entity_Id;
Scop : Entity_Id := Empty;
procedure Try_One_Interp (T1 : Entity_Id);
-- Routine to try one proposed interpretation. Note that the context
-- of the operator plays no role in resolving the arguments, so that
-- if there is more than one interpretation of the operands that is
-- compatible with comparison, the operation is ambiguous.
--------------------
-- Try_One_Interp --
--------------------
procedure Try_One_Interp (T1 : Entity_Id) is
begin
-- If the operator is an expanded name, then the type of the operand
-- must be defined in the corresponding scope. If the type is
-- universal, the context will impose the correct type.
if Present (Scop)
and then not Defined_In_Scope (T1, Scop)
and then T1 /= Universal_Integer
and then T1 /= Universal_Real
and then T1 /= Any_String
and then T1 /= Any_Composite
then
return;
end if;
if Valid_Comparison_Arg (T1)
and then Has_Compatible_Type (R, T1)
then
if Found
and then Base_Type (T1) /= Base_Type (T_F)
then
It := Disambiguate (L, I_F, Index, Any_Type);
if It = No_Interp then
Ambiguous_Operands (N);
Set_Etype (L, Any_Type);
return;
else
T_F := It.Typ;
end if;
else
Found := True;
T_F := T1;
I_F := Index;
end if;
Set_Etype (L, T_F);
Find_Non_Universal_Interpretations (N, R, Op_Id, T1);
end if;
end Try_One_Interp;
-- Start processing for Find_Comparison_Types
begin
-- If left operand is aggregate, the right operand has to
-- provide a usable type for it.
if Nkind (L) = N_Aggregate
and then Nkind (R) /= N_Aggregate
then
Find_Comparison_Types (R, L, Op_Id, N);
return;
end if;
if Nkind (N) = N_Function_Call
and then Nkind (Name (N)) = N_Expanded_Name
then
Scop := Entity (Prefix (Name (N)));
-- The prefix may be a package renaming, and the subsequent test
-- requires the original package.
if Ekind (Scop) = E_Package
and then Present (Renamed_Entity (Scop))
then
Scop := Renamed_Entity (Scop);
Set_Entity (Prefix (Name (N)), Scop);
end if;
end if;
if not Is_Overloaded (L) then
Try_One_Interp (Etype (L));
else
Get_First_Interp (L, Index, It);
while Present (It.Typ) loop
Try_One_Interp (It.Typ);
Get_Next_Interp (Index, It);
end loop;
end if;
end Find_Comparison_Types;
----------------------------------------
-- Find_Non_Universal_Interpretations --
----------------------------------------
procedure Find_Non_Universal_Interpretations
(N : Node_Id;
R : Node_Id;
Op_Id : Entity_Id;
T1 : Entity_Id)
is
Index : Interp_Index;
It : Interp;
begin
if T1 = Universal_Integer
or else T1 = Universal_Real
then
if not Is_Overloaded (R) then
Add_One_Interp
(N, Op_Id, Standard_Boolean, Base_Type (Etype (R)));
else
Get_First_Interp (R, Index, It);
while Present (It.Typ) loop
if Covers (It.Typ, T1) then
Add_One_Interp
(N, Op_Id, Standard_Boolean, Base_Type (It.Typ));
end if;
Get_Next_Interp (Index, It);
end loop;
end if;
else
Add_One_Interp (N, Op_Id, Standard_Boolean, Base_Type (T1));
end if;
end Find_Non_Universal_Interpretations;
------------------------------
-- Find_Concatenation_Types --
------------------------------
procedure Find_Concatenation_Types
(L, R : Node_Id;
Op_Id : Entity_Id;
N : Node_Id)
is
Op_Type : constant Entity_Id := Etype (Op_Id);
begin
if Is_Array_Type (Op_Type)
and then not Is_Limited_Type (Op_Type)
and then (Has_Compatible_Type (L, Op_Type)
or else
Has_Compatible_Type (L, Component_Type (Op_Type)))
and then (Has_Compatible_Type (R, Op_Type)
or else
Has_Compatible_Type (R, Component_Type (Op_Type)))
then
Add_One_Interp (N, Op_Id, Op_Type);
end if;
end Find_Concatenation_Types;
-------------------------
-- Find_Equality_Types --
-------------------------
procedure Find_Equality_Types
(L, R : Node_Id;
Op_Id : Entity_Id;
N : Node_Id)
is
Index : Interp_Index;
It : Interp;
Found : Boolean := False;
I_F : Interp_Index;
T_F : Entity_Id;
Scop : Entity_Id := Empty;
procedure Try_One_Interp (T1 : Entity_Id);
-- The context of the operator plays no role in resolving the
-- arguments, so that if there is more than one interpretation
-- of the operands that is compatible with equality, the construct
-- is ambiguous and an error can be emitted now, after trying to
-- disambiguate, i.e. applying preference rules.
--------------------
-- Try_One_Interp --
--------------------
procedure Try_One_Interp (T1 : Entity_Id) is
begin
-- If the operator is an expanded name, then the type of the operand
-- must be defined in the corresponding scope. If the type is
-- universal, the context will impose the correct type. An anonymous
-- type for a 'Access reference is also universal in this sense, as
-- the actual type is obtained from context.
-- In Ada 2005, the equality operator for anonymous access types
-- is declared in Standard, and preference rules apply to it.
if Present (Scop) then
if Defined_In_Scope (T1, Scop)
or else T1 = Universal_Integer
or else T1 = Universal_Real
or else T1 = Any_Access
or else T1 = Any_String
or else T1 = Any_Composite
or else (Ekind (T1) = E_Access_Subprogram_Type
and then not Comes_From_Source (T1))
then
null;
elsif Ekind (T1) = E_Anonymous_Access_Type
and then Scop = Standard_Standard
then
null;
else
-- The scope does not contain an operator for the type
return;
end if;
end if;
-- Ada 2005 (AI-230): Keep restriction imposed by Ada 83 and 95:
-- Do not allow anonymous access types in equality operators.
if Ada_Version < Ada_05
and then Ekind (T1) = E_Anonymous_Access_Type
then
return;
end if;
if T1 /= Standard_Void_Type
and then not Is_Limited_Type (T1)
and then not Is_Limited_Composite (T1)
and then Has_Compatible_Type (R, T1)
then
if Found
and then Base_Type (T1) /= Base_Type (T_F)
then
It := Disambiguate (L, I_F, Index, Any_Type);
if It = No_Interp then
Ambiguous_Operands (N);
Set_Etype (L, Any_Type);
return;
else
T_F := It.Typ;
end if;
else
Found := True;
T_F := T1;
I_F := Index;
end if;
if not Analyzed (L) then
Set_Etype (L, T_F);
end if;
Find_Non_Universal_Interpretations (N, R, Op_Id, T1);
-- Case of operator was not visible, Etype still set to Any_Type
if Etype (N) = Any_Type then
Found := False;
end if;
elsif Scop = Standard_Standard
and then Ekind (T1) = E_Anonymous_Access_Type
then
Found := True;
end if;
end Try_One_Interp;
-- Start of processing for Find_Equality_Types
begin
-- If left operand is aggregate, the right operand has to
-- provide a usable type for it.
if Nkind (L) = N_Aggregate
and then Nkind (R) /= N_Aggregate
then
Find_Equality_Types (R, L, Op_Id, N);
return;
end if;
if Nkind (N) = N_Function_Call
and then Nkind (Name (N)) = N_Expanded_Name
then
Scop := Entity (Prefix (Name (N)));
-- The prefix may be a package renaming, and the subsequent test
-- requires the original package.
if Ekind (Scop) = E_Package
and then Present (Renamed_Entity (Scop))
then
Scop := Renamed_Entity (Scop);
Set_Entity (Prefix (Name (N)), Scop);
end if;
end if;
if not Is_Overloaded (L) then
Try_One_Interp (Etype (L));
else
Get_First_Interp (L, Index, It);
while Present (It.Typ) loop
Try_One_Interp (It.Typ);
Get_Next_Interp (Index, It);
end loop;
end if;
end Find_Equality_Types;
-------------------------
-- Find_Negation_Types --
-------------------------
procedure Find_Negation_Types
(R : Node_Id;
Op_Id : Entity_Id;
N : Node_Id)
is
Index : Interp_Index;
It : Interp;
begin
if not Is_Overloaded (R) then
if Etype (R) = Universal_Integer then
Add_One_Interp (N, Op_Id, Any_Modular);
elsif Valid_Boolean_Arg (Etype (R)) then
Add_One_Interp (N, Op_Id, Etype (R));
end if;
else
Get_First_Interp (R, Index, It);
while Present (It.Typ) loop
if Valid_Boolean_Arg (It.Typ) then
Add_One_Interp (N, Op_Id, It.Typ);
end if;
Get_Next_Interp (Index, It);
end loop;
end if;
end Find_Negation_Types;
----------------------
-- Find_Unary_Types --
----------------------
procedure Find_Unary_Types
(R : Node_Id;
Op_Id : Entity_Id;
N : Node_Id)
is
Index : Interp_Index;
It : Interp;
begin
if not Is_Overloaded (R) then
if Is_Numeric_Type (Etype (R)) then
Add_One_Interp (N, Op_Id, Base_Type (Etype (R)));
end if;
else
Get_First_Interp (R, Index, It);
while Present (It.Typ) loop
if Is_Numeric_Type (It.Typ) then
Add_One_Interp (N, Op_Id, Base_Type (It.Typ));
end if;
Get_Next_Interp (Index, It);
end loop;
end if;
end Find_Unary_Types;
------------------
-- Junk_Operand --
------------------
function Junk_Operand (N : Node_Id) return Boolean is
Enode : Node_Id;
begin
if Error_Posted (N) then
return False;
end if;
-- Get entity to be tested
if Is_Entity_Name (N)
and then Present (Entity (N))
then
Enode := N;
-- An odd case, a procedure name gets converted to a very peculiar
-- function call, and here is where we detect this happening.
elsif Nkind (N) = N_Function_Call
and then Is_Entity_Name (Name (N))
and then Present (Entity (Name (N)))
then
Enode := Name (N);
-- Another odd case, there are at least some cases of selected
-- components where the selected component is not marked as having
-- an entity, even though the selector does have an entity
elsif Nkind (N) = N_Selected_Component
and then Present (Entity (Selector_Name (N)))
then
Enode := Selector_Name (N);
else
return False;
end if;
-- Now test the entity we got to see if it is a bad case
case Ekind (Entity (Enode)) is
when E_Package =>
Error_Msg_N
("package name cannot be used as operand", Enode);
when Generic_Unit_Kind =>
Error_Msg_N
("generic unit name cannot be used as operand", Enode);
when Type_Kind =>
Error_Msg_N
("subtype name cannot be used as operand", Enode);
when Entry_Kind =>
Error_Msg_N
("entry name cannot be used as operand", Enode);
when E_Procedure =>
Error_Msg_N
("procedure name cannot be used as operand", Enode);
when E_Exception =>
Error_Msg_N
("exception name cannot be used as operand", Enode);
when E_Block | E_Label | E_Loop =>
Error_Msg_N
("label name cannot be used as operand", Enode);
when others =>
return False;
end case;
return True;
end Junk_Operand;
--------------------
-- Operator_Check --
--------------------
procedure Operator_Check (N : Node_Id) is
begin
Remove_Abstract_Operations (N);
-- Test for case of no interpretation found for operator
if Etype (N) = Any_Type then
declare
L : Node_Id;
R : Node_Id;
begin
R := Right_Opnd (N);
if Nkind (N) in N_Binary_Op then
L := Left_Opnd (N);
else
L := Empty;
end if;
-- If either operand has no type, then don't complain further,
-- since this simply means that we have a propagated error.
if R = Error
or else Etype (R) = Any_Type
or else (Nkind (N) in N_Binary_Op and then Etype (L) = Any_Type)
then
return;
-- We explicitly check for the case of concatenation of component
-- with component to avoid reporting spurious matching array types
-- that might happen to be lurking in distant packages (such as
-- run-time packages). This also prevents inconsistencies in the
-- messages for certain ACVC B tests, which can vary depending on
-- types declared in run-time interfaces. Another improvement when
-- aggregates are present is to look for a well-typed operand.
elsif Present (Candidate_Type)
and then (Nkind (N) /= N_Op_Concat
or else Is_Array_Type (Etype (L))
or else Is_Array_Type (Etype (R)))
then
if Nkind (N) = N_Op_Concat then
if Etype (L) /= Any_Composite
and then Is_Array_Type (Etype (L))
then
Candidate_Type := Etype (L);
elsif Etype (R) /= Any_Composite
and then Is_Array_Type (Etype (R))
then
Candidate_Type := Etype (R);
end if;
end if;
Error_Msg_NE
("operator for} is not directly visible!",
N, First_Subtype (Candidate_Type));
Error_Msg_N ("use clause would make operation legal!", N);
return;
-- If either operand is a junk operand (e.g. package name), then
-- post appropriate error messages, but do not complain further.
-- Note that the use of OR in this test instead of OR ELSE is
-- quite deliberate, we may as well check both operands in the
-- binary operator case.
elsif Junk_Operand (R)
or (Nkind (N) in N_Binary_Op and then Junk_Operand (L))
then
return;
-- If we have a logical operator, one of whose operands is
-- Boolean, then we know that the other operand cannot resolve to
-- Boolean (since we got no interpretations), but in that case we
-- pretty much know that the other operand should be Boolean, so
-- resolve it that way (generating an error)
elsif Nkind (N) = N_Op_And
or else
Nkind (N) = N_Op_Or
or else
Nkind (N) = N_Op_Xor
then
if Etype (L) = Standard_Boolean then
Resolve (R, Standard_Boolean);
return;
elsif Etype (R) = Standard_Boolean then
Resolve (L, Standard_Boolean);
return;
end if;
-- For an arithmetic operator or comparison operator, if one
-- of the operands is numeric, then we know the other operand
-- is not the same numeric type. If it is a non-numeric type,
-- then probably it is intended to match the other operand.
elsif Nkind (N) = N_Op_Add or else
Nkind (N) = N_Op_Divide or else
Nkind (N) = N_Op_Ge or else
Nkind (N) = N_Op_Gt or else
Nkind (N) = N_Op_Le or else
Nkind (N) = N_Op_Lt or else
Nkind (N) = N_Op_Mod or else
Nkind (N) = N_Op_Multiply or else
Nkind (N) = N_Op_Rem or else
Nkind (N) = N_Op_Subtract
then
if Is_Numeric_Type (Etype (L))
and then not Is_Numeric_Type (Etype (R))
then
Resolve (R, Etype (L));
return;
elsif Is_Numeric_Type (Etype (R))
and then not Is_Numeric_Type (Etype (L))
then
Resolve (L, Etype (R));
return;
end if;
-- Comparisons on A'Access are common enough to deserve a
-- special message.
elsif (Nkind (N) = N_Op_Eq or else
Nkind (N) = N_Op_Ne)
and then Ekind (Etype (L)) = E_Access_Attribute_Type
and then Ekind (Etype (R)) = E_Access_Attribute_Type
then
Error_Msg_N
("two access attributes cannot be compared directly", N);
Error_Msg_N
("\they must be converted to an explicit type for comparison",
N);
return;
-- Another one for C programmers
elsif Nkind (N) = N_Op_Concat
and then Valid_Boolean_Arg (Etype (L))
and then Valid_Boolean_Arg (Etype (R))
then
Error_Msg_N ("invalid operands for concatenation", N);
Error_Msg_N ("\maybe AND was meant", N);
return;
-- A special case for comparison of access parameter with null
elsif Nkind (N) = N_Op_Eq
and then Is_Entity_Name (L)
and then Nkind (Parent (Entity (L))) = N_Parameter_Specification
and then Nkind (Parameter_Type (Parent (Entity (L)))) =
N_Access_Definition
and then Nkind (R) = N_Null
then
Error_Msg_N ("access parameter is not allowed to be null", L);
Error_Msg_N ("\(call would raise Constraint_Error)", L);
return;
end if;
-- If we fall through then just give general message. Note that in
-- the following messages, if the operand is overloaded we choose
-- an arbitrary type to complain about, but that is probably more
-- useful than not giving a type at all.
if Nkind (N) in N_Unary_Op then
Error_Msg_Node_2 := Etype (R);
Error_Msg_N ("operator& not defined for}", N);
return;
else
if Nkind (N) in N_Binary_Op then
if not Is_Overloaded (L)
and then not Is_Overloaded (R)
and then Base_Type (Etype (L)) = Base_Type (Etype (R))
then
Error_Msg_Node_2 := First_Subtype (Etype (R));
Error_Msg_N ("there is no applicable operator& for}", N);
else
Error_Msg_N ("invalid operand types for operator&", N);
if Nkind (N) /= N_Op_Concat then
Error_Msg_NE ("\left operand has}!", N, Etype (L));
Error_Msg_NE ("\right operand has}!", N, Etype (R));
end if;
end if;
end if;
end if;
end;
end if;
end Operator_Check;
-----------------------------------------
-- Process_Implicit_Dereference_Prefix --
-----------------------------------------
procedure Process_Implicit_Dereference_Prefix
(E : Entity_Id;
P : Entity_Id)
is
Ref : Node_Id;
begin
if Present (E)
and then (Operating_Mode = Check_Semantics or else not Expander_Active)
then
-- We create a dummy reference to E to ensure that the reference
-- is not considered as part of an assignment (an implicit
-- dereference can never assign to its prefix). The Comes_From_Source
-- attribute needs to be propagated for accurate warnings.
Ref := New_Reference_To (E, Sloc (P));
Set_Comes_From_Source (Ref, Comes_From_Source (P));
Generate_Reference (E, Ref);
end if;
end Process_Implicit_Dereference_Prefix;
--------------------------------
-- Remove_Abstract_Operations --
--------------------------------
procedure Remove_Abstract_Operations (N : Node_Id) is
I : Interp_Index;
It : Interp;
Abstract_Op : Entity_Id := Empty;
-- AI-310: If overloaded, remove abstract non-dispatching operations. We
-- activate this if either extensions are enabled, or if the abstract
-- operation in question comes from a predefined file. This latter test
-- allows us to use abstract to make operations invisible to users. In
-- particular, if type Address is non-private and abstract subprograms
-- are used to hide its operators, they will be truly hidden.
type Operand_Position is (First_Op, Second_Op);
Univ_Type : constant Entity_Id := Universal_Interpretation (N);
procedure Remove_Address_Interpretations (Op : Operand_Position);
-- Ambiguities may arise when the operands are literal and the address
-- operations in s-auxdec are visible. In that case, remove the
-- interpretation of a literal as Address, to retain the semantics of
-- Address as a private type.
------------------------------------
-- Remove_Address_Interpretations --
------------------------------------
procedure Remove_Address_Interpretations (Op : Operand_Position) is
Formal : Entity_Id;
begin
if Is_Overloaded (N) then
Get_First_Interp (N, I, It);
while Present (It.Nam) loop
Formal := First_Entity (It.Nam);
if Op = Second_Op then
Formal := Next_Entity (Formal);
end if;
if Is_Descendent_Of_Address (Etype (Formal)) then
Remove_Interp (I);
end if;
Get_Next_Interp (I, It);
end loop;
end if;
end Remove_Address_Interpretations;
-- Start of processing for Remove_Abstract_Operations
begin
if Is_Overloaded (N) then
Get_First_Interp (N, I, It);
while Present (It.Nam) loop
if not Is_Type (It.Nam)
and then Is_Abstract (It.Nam)
and then not Is_Dispatching_Operation (It.Nam)
then
Abstract_Op := It.Nam;
-- In Ada 2005, this operation does not participate in Overload
-- resolution. If the operation is defined in in a predefined
-- unit, it is one of the operations declared abstract in some
-- variants of System, and it must be removed as well.
if Ada_Version >= Ada_05
or else Is_Predefined_File_Name
(Unit_File_Name (Get_Source_Unit (It.Nam)))
or else Is_Descendent_Of_Address (It.Typ)
then
Remove_Interp (I);
exit;
end if;
end if;
Get_Next_Interp (I, It);
end loop;
if No (Abstract_Op) then
-- If some interpretation yields an integer type, it is still
-- possible that there are address interpretations. Remove them
-- if one operand is a literal, to avoid spurious ambiguities
-- on systems where Address is a visible integer type.
if Is_Overloaded (N)
and then Nkind (N) in N_Op
and then Is_Integer_Type (Etype (N))
then
if Nkind (N) in N_Binary_Op then
if Nkind (Right_Opnd (N)) = N_Integer_Literal then
Remove_Address_Interpretations (Second_Op);
elsif Nkind (Right_Opnd (N)) = N_Integer_Literal then
Remove_Address_Interpretations (First_Op);
end if;
end if;
end if;
elsif Nkind (N) in N_Op then
-- Remove interpretations that treat literals as addresses. This
-- is never appropriate, even when Address is defined as a visible
-- Integer type. The reason is that we would really prefer Address
-- to behave as a private type, even in this case, which is there
-- only to accomodate oddities of VMS address sizes. If Address is
-- a visible integer type, we get lots of overload ambiguities.
if Nkind (N) in N_Binary_Op then
declare
U1 : constant Boolean :=
Present (Universal_Interpretation (Right_Opnd (N)));
U2 : constant Boolean :=
Present (Universal_Interpretation (Left_Opnd (N)));
begin
if U1 then
Remove_Address_Interpretations (Second_Op);
end if;
if U2 then
Remove_Address_Interpretations (First_Op);
end if;
if not (U1 and U2) then
-- Remove corresponding predefined operator, which is
-- always added to the overload set.
Get_First_Interp (N, I, It);
while Present (It.Nam) loop
if Scope (It.Nam) = Standard_Standard
and then Base_Type (It.Typ) =
Base_Type (Etype (Abstract_Op))
then
Remove_Interp (I);
end if;
Get_Next_Interp (I, It);
end loop;
elsif Is_Overloaded (N)
and then Present (Univ_Type)
then
-- If both operands have a universal interpretation,
-- it is still necessary to remove interpretations that
-- yield Address. Any remaining ambiguities will be
-- removed in Disambiguate.
Get_First_Interp (N, I, It);
while Present (It.Nam) loop
if Is_Descendent_Of_Address (It.Typ) then
Remove_Interp (I);
elsif not Is_Type (It.Nam) then
Set_Entity (N, It.Nam);
end if;
Get_Next_Interp (I, It);
end loop;
end if;
end;
end if;
elsif Nkind (N) = N_Function_Call
and then
(Nkind (Name (N)) = N_Operator_Symbol
or else
(Nkind (Name (N)) = N_Expanded_Name
and then
Nkind (Selector_Name (Name (N))) = N_Operator_Symbol))
then
declare
Arg1 : constant Node_Id := First (Parameter_Associations (N));
U1 : constant Boolean :=
Present (Universal_Interpretation (Arg1));
U2 : constant Boolean :=
Present (Next (Arg1)) and then
Present (Universal_Interpretation (Next (Arg1)));
begin
if U1 then
Remove_Address_Interpretations (First_Op);
end if;
if U2 then
Remove_Address_Interpretations (Second_Op);
end if;
if not (U1 and U2) then
Get_First_Interp (N, I, It);
while Present (It.Nam) loop
if Scope (It.Nam) = Standard_Standard
and then It.Typ = Base_Type (Etype (Abstract_Op))
then
Remove_Interp (I);
end if;
Get_Next_Interp (I, It);
end loop;
end if;
end;
end if;
-- If the removal has left no valid interpretations, emit
-- error message now and label node as illegal.
if Present (Abstract_Op) then
Get_First_Interp (N, I, It);
if No (It.Nam) then
-- Removal of abstract operation left no viable candidate
Set_Etype (N, Any_Type);
Error_Msg_Sloc := Sloc (Abstract_Op);
Error_Msg_NE
("cannot call abstract operation& declared#", N, Abstract_Op);
end if;
end if;
end if;
end Remove_Abstract_Operations;
-----------------------
-- Try_Indirect_Call --
-----------------------
function Try_Indirect_Call
(N : Node_Id;
Nam : Entity_Id;
Typ : Entity_Id) return Boolean
is
Actual : Node_Id;
Formal : Entity_Id;
Call_OK : Boolean;
begin
Normalize_Actuals (N, Designated_Type (Typ), False, Call_OK);
Actual := First_Actual (N);
Formal := First_Formal (Designated_Type (Typ));
while Present (Actual) and then Present (Formal) loop
if not Has_Compatible_Type (Actual, Etype (Formal)) then
return False;
end if;
Next (Actual);
Next_Formal (Formal);
end loop;
if No (Actual) and then No (Formal) then
Add_One_Interp (N, Nam, Etype (Designated_Type (Typ)));
-- Nam is a candidate interpretation for the name in the call,
-- if it is not an indirect call.
if not Is_Type (Nam)
and then Is_Entity_Name (Name (N))
then
Set_Entity (Name (N), Nam);
end if;
return True;
else
return False;
end if;
end Try_Indirect_Call;
----------------------
-- Try_Indexed_Call --
----------------------
function Try_Indexed_Call
(N : Node_Id;
Nam : Entity_Id;
Typ : Entity_Id) return Boolean
is
Actuals : constant List_Id := Parameter_Associations (N);
Actual : Node_Id;
Index : Entity_Id;
begin
Actual := First (Actuals);
Index := First_Index (Typ);
while Present (Actual) and then Present (Index) loop
-- If the parameter list has a named association, the expression
-- is definitely a call and not an indexed component.
if Nkind (Actual) = N_Parameter_Association then
return False;
end if;
if not Has_Compatible_Type (Actual, Etype (Index)) then
return False;
end if;
Next (Actual);
Next_Index (Index);
end loop;
if No (Actual) and then No (Index) then
Add_One_Interp (N, Nam, Component_Type (Typ));
-- Nam is a candidate interpretation for the name in the call,
-- if it is not an indirect call.
if not Is_Type (Nam)
and then Is_Entity_Name (Name (N))
then
Set_Entity (Name (N), Nam);
end if;
return True;
else
return False;
end if;
end Try_Indexed_Call;
--------------------------
-- Try_Object_Operation --
--------------------------
function Try_Object_Operation (N : Node_Id) return Boolean is
K : constant Node_Kind := Nkind (Parent (N));
Loc : constant Source_Ptr := Sloc (N);
Is_Subprg_Call : constant Boolean := K = N_Procedure_Call_Statement
or else K = N_Function_Call;
Obj : constant Node_Id := Prefix (N);
Subprog : constant Node_Id := Selector_Name (N);
Actual : Node_Id;
New_Call_Node : Node_Id := Empty;
Node_To_Replace : Node_Id;
Obj_Type : Entity_Id := Etype (Obj);
procedure Complete_Object_Operation
(Call_Node : Node_Id;
Node_To_Replace : Node_Id;
Subprog : Node_Id);
-- Make Subprog the name of Call_Node, replace Node_To_Replace with
-- Call_Node, insert the object (or its dereference) as the first actual
-- in the call, and complete the analysis of the call.
procedure Transform_Object_Operation
(Call_Node : out Node_Id;
Node_To_Replace : out Node_Id;
Subprog : Node_Id);
-- Transform Obj.Operation (X, Y,,) into Operation (Obj, X, Y ..)
-- Call_Node is the resulting subprogram call,
-- Node_To_Replace is either N or the parent of N, and Subprog
-- is a reference to the subprogram we are trying to match.
function Try_Class_Wide_Operation
(Call_Node : Node_Id;
Node_To_Replace : Node_Id) return Boolean;
-- Traverse all ancestor types looking for a class-wide subprogram
-- for which the current operation is a valid non-dispatching call.
function Try_Primitive_Operation
(Call_Node : Node_Id;
Node_To_Replace : Node_Id) return Boolean;
-- Traverse the list of primitive subprograms looking for a dispatching
-- operation for which the current node is a valid call .
-------------------------------
-- Complete_Object_Operation --
-------------------------------
procedure Complete_Object_Operation
(Call_Node : Node_Id;
Node_To_Replace : Node_Id;
Subprog : Node_Id)
is
Formal_Type : constant Entity_Id :=
Etype (First_Formal (Entity (Subprog)));
First_Actual : Node_Id;
begin
First_Actual := First (Parameter_Associations (Call_Node));
Set_Name (Call_Node, Subprog);
if Nkind (N) = N_Selected_Component
and then not Inside_A_Generic
then
Set_Entity (Selector_Name (N), Entity (Subprog));
end if;
-- If need be, rewrite first actual as an explicit dereference
if not Is_Access_Type (Formal_Type)
and then Is_Access_Type (Etype (Obj))
then
Rewrite (First_Actual,
Make_Explicit_Dereference (Sloc (Obj), Obj));
Analyze (First_Actual);
-- Conversely, if the formal is an access parameter and the
-- object is not, replace the actual with a 'Access reference.
-- Its analysis will check that the object is aliased.
elsif Is_Access_Type (Formal_Type)
and then not Is_Access_Type (Etype (Obj))
then
Rewrite (First_Actual,
Make_Attribute_Reference (Loc,
Attribute_Name => Name_Access,
Prefix => Relocate_Node (Obj)));
Analyze (First_Actual);
else
Rewrite (First_Actual, Obj);
end if;
Rewrite (Node_To_Replace, Call_Node);
Analyze (Node_To_Replace);
end Complete_Object_Operation;
--------------------------------
-- Transform_Object_Operation --
--------------------------------
procedure Transform_Object_Operation
(Call_Node : out Node_Id;
Node_To_Replace : out Node_Id;
Subprog : Node_Id)
is
Parent_Node : constant Node_Id := Parent (N);
Dummy : constant Node_Id := New_Copy (Obj);
-- Placeholder used as a first parameter in the call, replaced
-- eventually by the proper object.
Actuals : List_Id;
Actual : Node_Id;
begin
-- Common case covering 1) Call to a procedure and 2) Call to a
-- function that has some additional actuals.
if (Nkind (Parent_Node) = N_Function_Call
or else
Nkind (Parent_Node) = N_Procedure_Call_Statement)
-- N is a selected component node containing the name of the
-- subprogram. If N is not the name of the parent node we must
-- not replace the parent node by the new construct. This case
-- occurs when N is a parameterless call to a subprogram that
-- is an actual parameter of a call to another subprogram. For
-- example:
-- Some_Subprogram (..., Obj.Operation, ...)
and then Name (Parent_Node) = N
then
Node_To_Replace := Parent_Node;
Actuals := Parameter_Associations (Parent_Node);
if Present (Actuals) then
Prepend (Dummy, Actuals);
else
Actuals := New_List (Dummy);
end if;
if Nkind (Parent_Node) = N_Procedure_Call_Statement then
Call_Node :=
Make_Procedure_Call_Statement (Loc,
Name => New_Copy_Tree (Subprog),
Parameter_Associations => Actuals);
else
Call_Node :=
Make_Function_Call (Loc,
Name => New_Copy_Tree (Subprog),
Parameter_Associations => Actuals);
end if;
-- Before analysis, the function call appears as an indexed component
-- if there are no named associations.
elsif Nkind (Parent_Node) = N_Indexed_Component
and then N = Prefix (Parent_Node)
then
Node_To_Replace := Parent_Node;
Actuals := Expressions (Parent_Node);
Actual := First (Actuals);
while Present (Actual) loop
Analyze (Actual);
Next (Actual);
end loop;
Prepend (Dummy, Actuals);
Call_Node :=
Make_Function_Call (Loc,
Name => New_Copy_Tree (Subprog),
Parameter_Associations => Actuals);
-- Parameterless call: Obj.F is rewritten as F (Obj)
else
Node_To_Replace := N;
Call_Node :=
Make_Function_Call (Loc,
Name => New_Copy_Tree (Subprog),
Parameter_Associations => New_List (Dummy));
end if;
end Transform_Object_Operation;
------------------------------
-- Try_Class_Wide_Operation --
------------------------------
function Try_Class_Wide_Operation
(Call_Node : Node_Id;
Node_To_Replace : Node_Id) return Boolean
is
Anc_Type : Entity_Id;
Hom : Entity_Id;
Hom_Ref : Node_Id;
Success : Boolean;
begin
-- Loop through ancestor types, traverse the homonym chain of the
-- subprogram, and try out those homonyms whose first formal has the
-- class-wide type of the ancestor.
-- Should we verify that it is declared in the same package as the
-- ancestor type ???
Anc_Type := Obj_Type;
loop
Hom := Current_Entity (Subprog);
while Present (Hom) loop
if (Ekind (Hom) = E_Procedure
or else
Ekind (Hom) = E_Function)
and then Present (First_Formal (Hom))
and then Etype (First_Formal (Hom)) =
Class_Wide_Type (Anc_Type)
then
Hom_Ref := New_Reference_To (Hom, Sloc (Subprog));
Set_Etype (Call_Node, Any_Type);
Set_Parent (Call_Node, Parent (Node_To_Replace));
Set_Name (Call_Node, Hom_Ref);
Analyze_One_Call
(N => Call_Node,
Nam => Hom,
Report => False,
Success => Success,
Skip_First => True);
if Success then
-- Reformat into the proper call
Complete_Object_Operation
(Call_Node => Call_Node,
Node_To_Replace => Node_To_Replace,
Subprog => Hom_Ref);
return True;
end if;
end if;
Hom := Homonym (Hom);
end loop;
-- Examine other ancestor types
exit when Etype (Anc_Type) = Anc_Type;
Anc_Type := Etype (Anc_Type);
end loop;
-- Nothing matched
return False;
end Try_Class_Wide_Operation;
-----------------------------
-- Try_Primitive_Operation --
-----------------------------
function Try_Primitive_Operation
(Call_Node : Node_Id;
Node_To_Replace : Node_Id) return Boolean
is
Elmt : Elmt_Id;
Prim_Op : Entity_Id;
Prim_Op_Ref : Node_Id := Empty;
Success : Boolean := False;
Op_Exists : Boolean := False;
function Valid_First_Argument_Of (Op : Entity_Id) return Boolean;
-- Verify that the prefix, dereferenced if need be, is a valid
-- controlling argument in a call to Op. The remaining actuals
-- are checked in the subsequent call to Analyze_One_Call.
-----------------------------
-- Valid_First_Argument_Of --
-----------------------------
function Valid_First_Argument_Of (Op : Entity_Id) return Boolean is
Typ : constant Entity_Id := Etype (First_Formal (Op));
begin
-- Simple case
return Base_Type (Obj_Type) = Typ
-- Prefix can be dereferenced
or else
(Is_Access_Type (Obj_Type)
and then Designated_Type (Obj_Type) = Typ)
-- Formal is an access parameter, for which the object
-- can provide an access.
or else
(Ekind (Typ) = E_Anonymous_Access_Type
and then Designated_Type (Typ) = Obj_Type);
end Valid_First_Argument_Of;
-- Start of processing for Try_Primitive_Operation
begin
-- Look for subprograms in the list of primitive operations
-- The name must be identical, and the kind of call indicates
-- the expected kind of operation (function or procedure).
Elmt := First_Elmt (Primitive_Operations (Obj_Type));
while Present (Elmt) loop
Prim_Op := Node (Elmt);
if Chars (Prim_Op) = Chars (Subprog)
and then Present (First_Formal (Prim_Op))
and then Valid_First_Argument_Of (Prim_Op)
and then
(Nkind (Call_Node) = N_Function_Call)
= (Ekind (Prim_Op) = E_Function)
then
-- If this primitive operation corresponds with an immediate
-- ancestor interface there is no need to add it to the list
-- of interpretations; the corresponding aliased primitive is
-- also in this list of primitive operations and will be
-- used instead.
if Present (Abstract_Interface_Alias (Prim_Op))
and then Present (DTC_Entity (Alias (Prim_Op)))
and then Etype (DTC_Entity (Alias (Prim_Op))) = RTE (RE_Tag)
then
goto Continue;
end if;
if not Success then
Prim_Op_Ref := New_Reference_To (Prim_Op, Sloc (Subprog));
Set_Etype (Call_Node, Any_Type);
Set_Parent (Call_Node, Parent (Node_To_Replace));
Set_Name (Call_Node, Prim_Op_Ref);
Analyze_One_Call
(N => Call_Node,
Nam => Prim_Op,
Report => False,
Success => Success,
Skip_First => True);
if Success then
Op_Exists := True;
-- If the operation is a procedure call, there can only
-- be one candidate and we found it. If it is a function
-- we must collect all interpretations, because there
-- may be several primitive operations that differ only
-- in the return type.
if Nkind (Call_Node) = N_Procedure_Call_Statement then
exit;
end if;
end if;
elsif Ekind (Prim_Op) = E_Function then
-- Collect remaining function interpretations, to be
-- resolved from context.
Add_One_Interp (Prim_Op_Ref, Prim_Op, Etype (Prim_Op));
end if;
end if;
<<Continue>>
Next_Elmt (Elmt);
end loop;
if Op_Exists then
Complete_Object_Operation
(Call_Node => Call_Node,
Node_To_Replace => Node_To_Replace,
Subprog => Prim_Op_Ref);
end if;
return Op_Exists;
end Try_Primitive_Operation;
-- Start of processing for Try_Object_Operation
begin
if Is_Access_Type (Obj_Type) then
Obj_Type := Designated_Type (Obj_Type);
end if;
if Ekind (Obj_Type) = E_Private_Subtype then
Obj_Type := Base_Type (Obj_Type);
end if;
if Is_Class_Wide_Type (Obj_Type) then
Obj_Type := Etype (Class_Wide_Type (Obj_Type));
end if;
-- The type may have be obtained through a limited_with clause,
-- in which case the primitive operations are available on its
-- non-limited view.
if Ekind (Obj_Type) = E_Incomplete_Type
and then From_With_Type (Obj_Type)
then
Obj_Type := Non_Limited_View (Obj_Type);
end if;
if not Is_Tagged_Type (Obj_Type) then
return False;
end if;
-- Analyze the actuals if node is know to be a subprogram call
if Is_Subprg_Call and then N = Name (Parent (N)) then
Actual := First (Parameter_Associations (Parent (N)));
while Present (Actual) loop
Analyze_Expression (Actual);
Next (Actual);
end loop;
end if;
Analyze_Expression (Obj);
-- Build a subprogram call node, using a copy of Obj as its first
-- actual. This is a placeholder, to be replaced by an explicit
-- dereference when needed.
Transform_Object_Operation
(Call_Node => New_Call_Node,
Node_To_Replace => Node_To_Replace,
Subprog => Subprog);
Set_Etype (New_Call_Node, Any_Type);
Set_Parent (New_Call_Node, Parent (Node_To_Replace));
return
Try_Primitive_Operation
(Call_Node => New_Call_Node,
Node_To_Replace => Node_To_Replace)
or else
Try_Class_Wide_Operation
(Call_Node => New_Call_Node,
Node_To_Replace => Node_To_Replace);
end Try_Object_Operation;
end Sem_Ch4;
|
------------------------------------------------------------------------------
-- Copyright (c) 2015-2019, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Natools.Web.Comments provides an implementation of user-posted comments --
-- like is commonly found on blogs. --
------------------------------------------------------------------------------
with Ada.Characters.Handling;
with Ada.Containers.Indefinite_Ordered_Maps;
with Ada.Exceptions;
with Ada.Streams.Stream_IO;
with Natools.File_Streams;
with Natools.S_Expressions.Atom_Buffers;
with Natools.S_Expressions.Atom_Ref_Constructors;
with Natools.S_Expressions.Caches;
with Natools.S_Expressions.Conditionals.Generic_Evaluate;
with Natools.S_Expressions.Conditionals.Strings;
with Natools.S_Expressions.Enumeration_IO;
with Natools.S_Expressions.Interpreter_Loop;
with Natools.S_Expressions.Parsers;
with Natools.S_Expressions.Printers.Pretty;
with Natools.S_Expressions.Templates.Dates;
with Natools.S_Expressions.Templates.Integers;
with Natools.Static_Maps.Web.Comments;
with Natools.Time_IO.RFC_3339;
with Natools.Time_Keys;
with Natools.Web.Backends;
with Natools.Web.Comment_Cookies;
with Natools.Web.Error_Pages;
with Natools.Web.Escapes;
with Natools.Web.Exchanges;
with Natools.Web.Fallback_Render;
with Natools.Web.Filters.Stores;
with Natools.Web.Filters.Text_Blocks;
with Natools.Web.Is_Valid_URL;
with Natools.Web.List_Templates;
with Natools.Web.Render_Default;
package body Natools.Web.Comments is
package Static_Maps renames Natools.Static_Maps.Web.Comments;
package Comment_Flag_IO is new S_Expressions.Enumeration_IO.Typed_IO
(Comment_Flags.Enum);
package List_Flag_IO is new S_Expressions.Enumeration_IO.Typed_IO
(List_Flags.Enum);
package String_Maps is new Ada.Containers.Indefinite_Ordered_Maps
(String, String);
type Post_Action is (Save_Comment, Force_Preview, Parent_Redirect);
package Post_Action_IO is new S_Expressions.Enumeration_IO.Typed_IO
(Post_Action);
type Comment_Builder is record
Core : Comment_Data;
Extra_Fields, Raw_Fields : String_Maps.Map;
Has_Unknown_Field : Boolean := False;
Cookie_Save : Boolean := False;
Action : Post_Action;
Reason : S_Expressions.Atom_Refs.Immutable_Reference;
Anchor : S_Expressions.Atom_Refs.Immutable_Reference;
Redirect_Base : S_Expressions.Atom_Refs.Immutable_Reference;
end record;
Invalid_Condition : exception;
Ignore_Button : constant String := "ignore";
Preview_Button : constant String := "preview";
Preview_Id_Ref : S_Expressions.Atom_Refs.Immutable_Reference;
Submit_Button : constant String := "submit";
Auto_Class_Prefix : constant S_Expressions.Atom
:= (1 => Character'Pos ('c'), 2 => Character'Pos ('o'),
3 => Character'Pos ('m'), 4 => Character'Pos ('m'),
5 => Character'Pos ('c'), 6 => Character'Pos ('l'),
7 => Character'Pos ('a'), 8 => Character'Pos ('s'),
9 => Character'Pos ('s'), 10 => Character'Pos ('-'));
procedure Append
(Exchange : in out Sites.Exchange;
Context : in Comment_List;
Data : in S_Expressions.Atom);
-- Append Data to Exchange, ignoring Context
procedure Append
(Exchange : in out Sites.Exchange;
Context : in Comment_Data;
Data : in S_Expressions.Atom);
-- Append Data to Exchange, ignoring Context
function Create (Data : S_Expressions.Atom)
return S_Expressions.Atom_Refs.Immutable_Reference
renames S_Expressions.Atom_Ref_Constructors.Create;
-- Atom expression constructor
function Evaluate_Parametric
(Builder : in Comment_Builder;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class)
return Boolean;
-- Evaluate a condition on a comment builder with arguments
function Evaluate_Simple
(Builder : in Comment_Builder;
Name : in S_Expressions.Atom)
return Boolean;
-- Evaluate a condition on a comment builder without argument
function Get_Class (Exchange : in Sites.Exchange)
return S_Expressions.Atom_Refs.Immutable_Reference;
-- Look for comment class in Exchange
function Get_Safe_Filter
(Site : in Sites.Site;
Name_Ref : in S_Expressions.Atom_Refs.Immutable_Reference;
Default : in S_Expressions.Atom_Refs.Immutable_Reference)
return Filters.Filter'Class;
function Get_Safe_Filter
(Builder : in Sites.Site_Builder;
Name_Ref : in S_Expressions.Atom_Refs.Immutable_Reference;
Default : in S_Expressions.Atom_Refs.Immutable_Reference)
return Filters.Filter'Class;
-- Return the filter designated by Name_Ref, falling back on raw
-- text when Name_Ref is empty or named filter is not found.
function Image (Name : Comment_Atoms.Enum) return String;
-- Return a string representation of Name
function Next_Rank (List : Comment_List) return Positive;
-- Return the next rank for a comment in List (i.e. length + 1)
procedure Parse_Action
(Builder : in out Comment_Builder;
Site : in Sites.Site;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class);
-- Evluate action with parameter
procedure Parse_Action_Simple
(Builder : in out Comment_Builder;
Site : in Sites.Site;
Name : in S_Expressions.Atom);
-- Evaluate parameterless action
procedure Process_Actions
(Builder : in out Comment_Builder;
Site : in Sites.Site;
Filter_Name : in S_Expressions.Atom_Refs.Immutable_Reference);
-- Evaluate the filter whose name is given
procedure Preprocess
(Comment : in out Comment_Data;
Text_Filter : in Filters.Filter'Class);
-- Common preprocessing code, after Text_Filter is determined
function Preview_Id return S_Expressions.Atom_Refs.Immutable_Reference;
-- Return the comment id of temporary previews
procedure Process_Form
(Data : in out Comment_Builder;
Exchange : in Sites.Exchange;
List : in Comment_List);
-- Read form data in Exchange to fill Data
procedure Render
(Exchange : in out Sites.Exchange;
Position : in Comment_Maps.Cursor;
Expression : in out S_Expressions.Lockable.Descriptor'Class);
procedure Render_Comment
(Exchange : in out Sites.Exchange;
Comment : in Comment_Data;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class);
procedure Render_List_Element
(Exchange : in out Sites.Exchange;
List : in Comment_List;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class);
-- Render a command
procedure Reset_If_Blank
(Ref : in out S_Expressions.Atom_Refs.Immutable_Reference);
-- Reset Ref if it only contains blank characters
function String_Fallback_Parametric
(Settings : in S_Expressions.Conditionals.Strings.Settings;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class)
return Boolean;
-- Raise Invalid_Condition
function String_Fallback_Simple
(Settings : in S_Expressions.Conditionals.Strings.Settings;
Name : in S_Expressions.Atom)
return Boolean;
-- Raise Invalid_Condition
procedure Update_Item
(Comment : in out Comment_Data;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class);
-- Update comment with the given expression
procedure Update_List
(List : in out Comment_List;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class);
-- Update comment list with the given expression
function Value (Name : S_Expressions.Atom) return Comment_Atoms.Enum;
-- Convert Name into a comment atom reference, raising Constraint_Error
-- when Name is not valid.
procedure Write
(Builder : in Comment_Builder;
Output : in out S_Expressions.Printers.Printer'Class);
-- Serialize a builder into the given S_Expression stream
procedure Write
(Builder : in Comment_Builder;
Site : in Sites.Site;
Arguments : in out S_Expressions.Lockable.Descriptor'Class);
-- Serialize a builder into the file named by Arguments.Current_Atom.
-- The Site argument is useless for now, but kept for a future
-- backend-based implementation.
function Evaluate is new S_Expressions.Conditionals.Generic_Evaluate
(Comment_Builder, Evaluate_Parametric, Evaluate_Simple);
procedure Parse is new S_Expressions.Interpreter_Loop
(Comment_Builder, Sites.Site, Parse_Action, Parse_Action_Simple);
procedure Render is new S_Expressions.Interpreter_Loop
(Sites.Exchange, Comment_List, Render_List_Element, Append);
procedure Render is new S_Expressions.Interpreter_Loop
(Sites.Exchange, Comment_Data, Render_Comment, Append);
procedure Render_List is new List_Templates.Render
(Comment_Maps.Cursor, Comment_Maps.Map_Iterator_Interfaces);
procedure Update is new S_Expressions.Interpreter_Loop
(Comment_Data, Meaningless_Type, Update_Item);
procedure Update is new S_Expressions.Interpreter_Loop
(Comment_List, Meaningless_Type, Update_List);
------------------------------
-- Local Helper Subprograms --
------------------------------
function Get_Class (Exchange : in Sites.Exchange)
return S_Expressions.Atom_Refs.Immutable_Reference
is
Groups : constant Containers.Atom_Array_Refs.Immutable_Reference
:= Containers.Elements (Sites.Identity (Exchange).Groups);
begin
if not Groups.Is_Empty then
for Ref of Groups.Query loop
if not Ref.Is_Empty then
declare
use type S_Expressions.Atom;
use type S_Expressions.Offset;
Contents : constant S_Expressions.Atom := Ref.Query;
begin
if Contents'Length > Auto_Class_Prefix'Length
and then Contents (Contents'First
.. Contents'First + Auto_Class_Prefix'Length - 1)
= Auto_Class_Prefix
then
return Create (Contents
(Contents'First + Auto_Class_Prefix'Length
.. Contents'Last));
end if;
end;
end if;
end loop;
end if;
return S_Expressions.Atom_Refs.Null_Immutable_Reference;
end Get_Class;
function Image (Name : Comment_Atoms.Enum) return String is
begin
return Ada.Characters.Handling.To_Lower
(Comment_Atoms.Enum'Image (Name));
end Image;
function Next_Rank (List : Comment_List) return Positive is
begin
return List.Comments.Query.Length + 1;
end Next_Rank;
function Value (Name : S_Expressions.Atom) return Comment_Atoms.Enum is
begin
return Comment_Atoms.Enum'Value (S_Expressions.To_String (Name));
end Value;
---------------
-- Renderers --
---------------
procedure Append
(Exchange : in out Sites.Exchange;
Context : in Comment_List;
Data : in S_Expressions.Atom)
is
pragma Unreferenced (Context);
begin
Exchange.Append (Data);
end Append;
procedure Append
(Exchange : in out Sites.Exchange;
Context : in Comment_Data;
Data : in S_Expressions.Atom)
is
pragma Unreferenced (Context);
begin
Exchange.Append (Data);
end Append;
procedure Render
(Exchange : in out Sites.Exchange;
Position : in Comment_Maps.Cursor;
Expression : in out S_Expressions.Lockable.Descriptor'Class) is
begin
Render (Expression, Exchange, Comment_Maps.Element (Position));
end Render;
procedure Render_Comment
(Exchange : in out Sites.Exchange;
Comment : in Comment_Data;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class)
is
use type Tags.Visible_Access;
use Static_Maps.Item.Command;
procedure Re_Enter
(Exchange : in out Sites.Exchange;
Expression : in out S_Expressions.Lockable.Descriptor'Class);
procedure Render_Ref
(Ref : in S_Expressions.Atom_Refs.Immutable_Reference);
procedure Value
(Image : in String;
Found : out Boolean;
Id : out Comment_Atoms.Enum);
procedure Re_Enter
(Exchange : in out Sites.Exchange;
Expression : in out S_Expressions.Lockable.Descriptor'Class) is
begin
Render (Expression, Exchange, Comment);
end Re_Enter;
procedure Render_Ref
(Ref : in S_Expressions.Atom_Refs.Immutable_Reference) is
begin
if not Ref.Is_Empty then
Exchange.Append (Ref.Query);
elsif Arguments.Current_Event
in S_Expressions.Events.Add_Atom | S_Expressions.Events.Open_List
then
Render (Arguments, Exchange, Comment);
end if;
end Render_Ref;
procedure Value
(Image : in String;
Found : out Boolean;
Id : out Comment_Atoms.Enum) is
begin
Id := Comment_Atoms.Enum'Value (Image);
Found := True;
exception
when Constraint_Error =>
Found := False;
end Value;
S_Name : constant String := S_Expressions.To_String (Name);
begin
pragma Assert (Comment.Flags (Comment_Flags.Preprocessed));
case Static_Maps.To_Item_Command (S_Name) is
when Unknown =>
declare
Has_Id : Boolean;
Atom_Id : Comment_Atoms.Enum;
begin
if S_Name'Length > 6
and then S_Name (S_Name'First .. S_Name'First + 5) = "if-no-"
then
Value
(S_Name (S_Name'First + 6 .. S_Name'Last),
Has_Id, Atom_Id);
if Has_Id and then Comment.Atoms (Atom_Id).Is_Empty then
Render (Arguments, Exchange, Comment);
end if;
elsif S_Name'Length > 3
and then S_Name (S_Name'First .. S_Name'First + 2) = "if-"
then
Value
(S_Name (S_Name'First + 3 .. S_Name'Last),
Has_Id, Atom_Id);
if Has_Id and then not Comment.Atoms (Atom_Id).Is_Empty then
Render (Arguments, Exchange, Comment);
end if;
elsif S_Name /= "filter" then
Value (S_Name, Has_Id, Atom_Id);
if Has_Id then
Render_Ref (Comment.Atoms (Atom_Id));
end if;
end if;
if not Has_Id then
Fallback_Render
(Exchange, Name, Arguments, "comment", Re_Enter'Access);
end if;
end;
when Date =>
S_Expressions.Templates.Dates.Render
(Exchange, Arguments, Comment.Date, Comment.Offset);
when Id =>
Exchange.Append (Comment.Id.Query);
when Parent =>
if Comment.Parent /= null then
Tags.Render (Exchange, Comment.Parent.all, Arguments);
end if;
when Rank =>
S_Expressions.Templates.Integers.Render
(Exchange, Arguments, Comment.Rank);
end case;
end Render_Comment;
procedure Render_List_Element
(Exchange : in out Sites.Exchange;
List : in Comment_List;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class)
is
use Static_Maps.List.Command;
procedure Re_Enter
(Exchange : in out Sites.Exchange;
Expression : in out S_Expressions.Lockable.Descriptor'Class);
procedure Re_Enter
(Exchange : in out Sites.Exchange;
Expression : in out S_Expressions.Lockable.Descriptor'Class) is
begin
Render (Expression, Exchange, List);
end Re_Enter;
begin
case Static_Maps.To_List_Command (S_Expressions.To_String (Name)) is
when Unknown =>
Fallback_Render
(Exchange, Name, Arguments, "comment list", Re_Enter'Access);
when If_Closed =>
if List.Flags (List_Flags.Closed) then
Render (Arguments, Exchange, List);
end if;
when If_Not_Closed =>
if not List.Flags (List_Flags.Closed) then
Render (Arguments, Exchange, List);
end if;
when Static_Maps.List.Command.List =>
Render_List
(Exchange,
List.Comments.Query.Iterate,
List_Templates.Read_Parameters (Arguments));
when Parent =>
if not Tags."=" (List.Parent, null) then
Tags.Render (Exchange, List.Parent.all, Arguments);
end if;
when Preview =>
if Exchange.Parameter (Preview_Button) = ""
and then Exchange.Parameter (Submit_Button) = ""
then
return;
end if;
declare
Builder : Comment_Builder;
begin
Builder.Core.Date := Ada.Calendar.Clock;
Builder.Core.Offset := Ada.Calendar.Time_Zones.UTC_Time_Offset
(Builder.Core.Date);
Builder.Core.Id := Preview_Id;
Builder.Core.Parent := List.Parent;
Builder.Core.Rank := Next_Rank (List);
Process_Form (Builder, Exchange, List);
Preprocess (Builder.Core, List, Exchange.Site.all);
Render (Arguments, Exchange, Builder.Core);
end;
when Size =>
S_Expressions.Templates.Integers.Render
(Exchange, Arguments, List.Comments.Query.Length);
end case;
end Render_List_Element;
------------------
-- Interpreters --
------------------
procedure Update_Item
(Comment : in out Comment_Data;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class)
is
pragma Unreferenced (Context);
use Static_Maps.Item.Element;
use type S_Expressions.Events.Event;
begin
pragma Assert (not Comment.Flags (Comment_Flags.Preprocessed));
if Arguments.Current_Event /= S_Expressions.Events.Add_Atom then
return;
end if;
case Static_Maps.To_Item_Element (S_Expressions.To_String (Name)) is
when Unknown =>
Set_Atom :
begin
Comment.Atoms (Value (Name)) := Create (Arguments.Current_Atom);
exception
when Constraint_Error =>
Log (Severities.Error,
"Unknown comment element """
& S_Expressions.To_String (Name) & '"');
end Set_Atom;
when Date =>
declare
Image : constant String
:= S_Expressions.To_String (Arguments.Current_Atom);
begin
Time_IO.RFC_3339.Value (Image, Comment.Date, Comment.Offset);
exception
when others =>
Log (Severities.Error, "Invalid date """
& Image & """ for comment "
& S_Expressions.To_String (Comment.Id.Query));
end;
when Flags =>
while Arguments.Current_Event in S_Expressions.Events.Add_Atom loop
begin
Comment.Flags
(Comment_Flag_IO.Value (Arguments.Current_Atom))
:= True;
exception
when Constraint_Error =>
Log (Severities.Error, "Invalid comment flag value """
& S_Expressions.To_String (Arguments.Current_Atom)
& '"');
end;
Arguments.Next;
end loop;
end case;
end Update_Item;
procedure Update_List
(List : in out Comment_List;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class)
is
pragma Unreferenced (Context);
use Static_Maps.List.Element;
use type S_Expressions.Events.Event;
Event : S_Expressions.Events.Event;
begin
if Arguments.Current_Event /= S_Expressions.Events.Add_Atom then
return;
end if;
case Static_Maps.To_List_Element (S_Expressions.To_String (Name)) is
when Unknown =>
null;
when Backend =>
List.Backend_Name := Create (Arguments.Current_Atom);
Arguments.Next (Event);
if Event = S_Expressions.Events.Add_Atom then
List.Backend_Path := Create (Arguments.Current_Atom);
end if;
when Default_Text_Filter =>
List.Default_Text_Filter := Create (Arguments.Current_Atom);
when Flags =>
while Arguments.Current_Event in S_Expressions.Events.Add_Atom loop
begin
List.Flags
(List_Flag_IO.Value (Arguments.Current_Atom))
:= True;
exception
when Constraint_Error =>
Log (Severities.Error, "Invalid comment list flag """
& S_Expressions.To_String (Arguments.Current_Atom)
& '"');
end;
Arguments.Next;
end loop;
when Post_Filter =>
List.Post_Filter := Create (Arguments.Current_Atom);
when Static_Maps.List.Element.Tags =>
declare
List_Builder : Containers.Unsafe_Atom_Lists.List;
begin
Containers.Append_Atoms (List_Builder, Arguments);
List.Tags := Containers.Create (List_Builder);
end;
when Text_Filters =>
declare
List_Builder : Containers.Unsafe_Atom_Lists.List;
begin
Containers.Append_Atoms (List_Builder, Arguments);
List.Text_Filters := Containers.Create (List_Builder);
end;
end case;
end Update_List;
--------------------------------
-- Conditionals and Filtering --
--------------------------------
function Evaluate_Parametric
(Builder : in Comment_Builder;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class)
return Boolean
is
function Dereference
(Ref : in S_Expressions.Atom_Refs.Immutable_Reference)
return String;
function String_Evaluate
(Ref : in S_Expressions.Atom_Refs.Immutable_Reference;
Arg : in out S_Expressions.Lockable.Descriptor'Class)
return Boolean;
function Dereference
(Ref : in S_Expressions.Atom_Refs.Immutable_Reference)
return String is
begin
if Ref.Is_Empty then
return "";
else
return S_Expressions.To_String (Ref.Query);
end if;
end Dereference;
function String_Evaluate
(Ref : in S_Expressions.Atom_Refs.Immutable_Reference;
Arg : in out S_Expressions.Lockable.Descriptor'Class)
return Boolean
is
Value : aliased constant String := Dereference (Ref);
Context : constant S_Expressions.Conditionals.Strings.Context
:= (Data => Value'Access,
Parametric_Fallback => String_Fallback_Parametric'Access,
Simple_Fallback => String_Fallback_Simple'Access,
Settings => <>);
begin
return S_Expressions.Conditionals.Strings.Evaluate (Context, Arg);
end String_Evaluate;
use Static_Maps.Item.Condition;
use type S_Expressions.Events.Event;
begin
case Static_Maps.To_Item_Condition (S_Expressions.To_String (Name)) is
when Unknown =>
Evaluate_Atom :
begin
return String_Evaluate
(Builder.Core.Atoms (Value (Name)), Arguments);
exception
when Constraint_Error => null;
end Evaluate_Atom;
raise Invalid_Condition with "Unknown parametric conditional """
& S_Expressions.To_String (Name) & '"';
when Action_Is =>
declare
Action : Post_Action;
Event : S_Expressions.Events.Event := Arguments.Current_Event;
begin
while Event = S_Expressions.Events.Add_Atom loop
begin
Action := Post_Action_IO.Value (Arguments.Current_Atom);
if Action = Builder.Action then
return True;
end if;
exception
when Constraint_Error =>
Log (Severities.Error, "Invalid post action string """
& S_Expressions.To_String (Arguments.Current_Atom)
& '"');
end;
Arguments.Next (Event);
end loop;
return False;
end;
when Field_List_Is =>
declare
Cursor : String_Maps.Cursor := Builder.Raw_Fields.First;
Event : S_Expressions.Events.Event := Arguments.Current_Event;
begin
loop
if not String_Maps.Has_Element (Cursor)
or else Event /= S_Expressions.Events.Add_Atom
then
return String_Maps.Has_Element (Cursor)
= (Event = S_Expressions.Events.Add_Atom);
end if;
if String_Maps.Key (Cursor)
/= S_Expressions.To_String (Arguments.Current_Atom)
then
return False;
end if;
Arguments.Next (Event);
String_Maps.Next (Cursor);
end loop;
end;
when Field_List_Contains =>
declare
Event : S_Expressions.Events.Event := Arguments.Current_Event;
begin
while Event = S_Expressions.Events.Add_Atom loop
if not Builder.Raw_Fields.Contains
(S_Expressions.To_String (Arguments.Current_Atom))
then
return False;
end if;
Arguments.Next (Event);
end loop;
return True;
end;
when Field_List_Among =>
declare
Cursor : String_Maps.Cursor := Builder.Raw_Fields.First;
Event : S_Expressions.Events.Event := Arguments.Current_Event;
begin
while String_Maps.Has_Element (Cursor) loop
if Event /= S_Expressions.Events.Add_Atom then
return False;
end if;
if String_Maps.Key (Cursor)
= S_Expressions.To_String (Arguments.Current_Atom)
then
String_Maps.Next (Cursor);
end if;
Arguments.Next (Event);
end loop;
return True;
end;
when Fields_Equal =>
if Arguments.Current_Event /= S_Expressions.Events.Add_Atom then
return True;
end if;
declare
function Current_Field return String;
function Current_Field return String is
Cursor : constant String_Maps.Cursor
:= Builder.Raw_Fields.Find
(S_Expressions.To_String (Arguments.Current_Atom));
begin
if String_Maps.Has_Element (Cursor) then
return String_Maps.Element (Cursor);
else
return "";
end if;
end Current_Field;
Reference : constant String := Current_Field;
Event : S_Expressions.Events.Event;
begin
loop
Arguments.Next (Event);
exit when Event /= S_Expressions.Events.Add_Atom;
if Current_Field /= Reference then
return False;
end if;
end loop;
return True;
end;
when Has_Extra_Fields =>
return not Builder.Extra_Fields.Is_Empty;
when Has_Unknown_Field =>
return Builder.Has_Unknown_Field;
end case;
end Evaluate_Parametric;
function Evaluate_Simple
(Builder : in Comment_Builder;
Name : in S_Expressions.Atom)
return Boolean
is
use Static_Maps.Item.Condition;
begin
case Static_Maps.To_Item_Condition (S_Expressions.To_String (Name)) is
when Unknown
| Action_Is | Field_List_Is | Field_List_Contains | Field_List_Among
| Fields_Equal
=>
Evaluate_Atom :
begin
return not Builder.Core.Atoms (Value (Name)).Is_Empty;
exception
when Constraint_Error => null;
end Evaluate_Atom;
raise Invalid_Condition with "Unknown simple conditional """
& S_Expressions.To_String (Name) & '"';
when Has_Extra_Fields =>
return not Builder.Extra_Fields.Is_Empty;
when Has_Unknown_Field =>
return Builder.Has_Unknown_Field;
end case;
end Evaluate_Simple;
procedure Parse_Action
(Builder : in out Comment_Builder;
Site : in Sites.Site;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class)
is
use type S_Expressions.Atom;
use type S_Expressions.Events.Event;
procedure Append
(Ref : in out S_Expressions.Atom_Refs.Immutable_Reference;
Separator : in S_Expressions.Atom;
Data : in S_Expressions.Atom);
procedure Update_Reason;
procedure Append
(Ref : in out S_Expressions.Atom_Refs.Immutable_Reference;
Separator : in S_Expressions.Atom;
Data : in S_Expressions.Atom) is
begin
if Ref.Is_Empty then
Ref := Create (Data);
else
Ref := Create (Ref.Query & Separator & Data);
end if;
end Append;
procedure Update_Reason is
use type S_Expressions.Octet;
use type S_Expressions.Offset;
begin
if Arguments.Current_Event /= S_Expressions.Events.Add_Atom then
return;
end if;
declare
Text : constant S_Expressions.Atom := Arguments.Current_Atom;
Event : S_Expressions.Events.Event;
O : S_Expressions.Offset;
begin
Arguments.Next (Event);
if Event = S_Expressions.Events.Add_Atom then
Append (Builder.Reason, Text, Arguments.Current_Atom);
else
if Text'Length > 1
and then Text (Text'First) = Character'Pos ('+')
then
case Text (Text'First + 1) is
when Character'Pos ('\') =>
Append
(Builder.Reason,
S_Expressions.Null_Atom,
Text (Text'First + 2 .. Text'Last));
when Character'Pos ('(') =>
O := Text'First + 2;
while O in Text'Range
and then Text (O) /= Character'Pos (')')
loop
O := O + 1;
end loop;
if O in Text'Range then
Append
(Builder.Reason,
Text (Text'First + 2 .. O - 1),
Text (O + 1 .. Text'Last));
else
Append
(Builder.Reason,
S_Expressions.Null_Atom,
Text (Text'First + 1 .. Text'Last));
end if;
when others =>
Append
(Builder.Reason,
S_Expressions.Null_Atom,
Text (Text'First + 1 .. Text'Last));
end case;
else
Builder.Reason := Create (Text);
end if;
end if;
end;
end Update_Reason;
use Static_Maps.Item.Post_Action;
S_Name : constant String := S_Expressions.To_String (Name);
begin
if S_Name = "if"
and then Arguments.Current_Event
in S_Expressions.Events.Add_Atom | S_Expressions.Events.Open_List
then
begin
if Evaluate (Builder, Arguments) then
Arguments.Next;
Parse (Arguments, Builder, Site);
end if;
exception
when Ex : Invalid_Condition =>
Log (Severities.Error, "Invalid comment condition: "
& Ada.Exceptions.Exception_Message (Ex));
end;
return;
end if;
case Static_Maps.To_Item_Action (S_Name) is
when Unknown =>
Log (Severities.Error, "Unknown comment action """ & S_Name & '"');
when Anchor =>
if Arguments.Current_Event = S_Expressions.Events.Add_Atom then
Builder.Anchor := Create (Arguments.Current_Atom);
else
Builder.Anchor.Reset;
end if;
when Append_Reason =>
if Arguments.Current_Event = S_Expressions.Events.Add_Atom then
declare
First_Part : constant S_Expressions.Atom
:= Arguments.Current_Atom;
Event : S_Expressions.Events.Event;
begin
Arguments.Next (Event);
if Event = S_Expressions.Events.Add_Atom then
Append
(Builder.Reason, First_Part, Arguments.Current_Atom);
else
Append
(Builder.Reason, S_Expressions.Null_Atom, First_Part);
end if;
end;
end if;
when Dump =>
Write (Builder, Site, Arguments);
when Force_Preview =>
Builder.Action := Force_Preview;
Update_Reason;
when Force_Redirect =>
if Arguments.Current_Event = S_Expressions.Events.Add_Atom then
Builder.Redirect_Base := Create (Arguments.Current_Atom);
else
Builder.Redirect_Base.Reset;
end if;
when Ignore =>
Builder.Core.Flags (Comment_Flags.Ignored) := True;
Update_Reason;
when Reason =>
Update_Reason;
when Reject =>
Builder.Action := Parent_Redirect;
Update_Reason;
when Save =>
Builder.Action := Save_Comment;
Update_Reason;
when Set_Reason =>
if Arguments.Current_Event = S_Expressions.Events.Add_Atom then
Builder.Reason := Create (Arguments.Current_Atom);
end if;
when Unignore =>
Builder.Core.Flags (Comment_Flags.Ignored) := False;
Update_Reason;
end case;
end Parse_Action;
procedure Parse_Action_Simple
(Builder : in out Comment_Builder;
Site : in Sites.Site;
Name : in S_Expressions.Atom)
is
pragma Unreferenced (Site);
use Static_Maps.Item.Post_Action;
S_Name : constant String := S_Expressions.To_String (Name);
begin
case Static_Maps.To_Item_Action (S_Name) is
when Unknown | Dump =>
Log (Severities.Error, "Unknown comment action """ & S_Name & '"');
when Anchor =>
Builder.Anchor.Reset;
when Append_Reason =>
null;
when Force_Preview =>
Builder.Action := Force_Preview;
when Force_Redirect =>
Builder.Redirect_Base.Reset;
when Ignore =>
Builder.Core.Flags (Comment_Flags.Ignored) := True;
when Reason | Set_Reason =>
Builder.Reason.Reset;
when Reject =>
Builder.Action := Parent_Redirect;
when Save =>
Builder.Action := Save_Comment;
when Unignore =>
Builder.Core.Flags (Comment_Flags.Ignored) := False;
end case;
end Parse_Action_Simple;
procedure Process_Actions
(Builder : in out Comment_Builder;
Site : in Sites.Site;
Filter_Name : in S_Expressions.Atom_Refs.Immutable_Reference)
is
Expression : Containers.Optional_Expression;
begin
if Filter_Name.Is_Empty then
return;
end if;
Expression := Site.Get_Template (Filter_Name.Query);
if not Expression.Is_Empty then
Parse (Expression.Value, Builder, Site);
end if;
end Process_Actions;
procedure Reset_If_Blank
(Ref : in out S_Expressions.Atom_Refs.Immutable_Reference) is
begin
if Ref.Is_Empty then
return;
end if;
Abort_If_Not_Blank :
declare
Accessor : constant S_Expressions.Atom_Refs.Accessor := Ref.Query;
begin
for I in Accessor.Data.all'Range loop
if Accessor.Data (I) not in 9 | 10 | 13 | 32 then
return;
end if;
end loop;
end Abort_If_Not_Blank;
Ref.Reset;
end Reset_If_Blank;
function String_Fallback_Parametric
(Settings : in S_Expressions.Conditionals.Strings.Settings;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class)
return Boolean
is
pragma Unreferenced (Settings, Arguments);
begin
raise Invalid_Condition with "Unknown string parametric conditional """
& S_Expressions.To_String (Name) & '"';
return False;
end String_Fallback_Parametric;
function String_Fallback_Simple
(Settings : in S_Expressions.Conditionals.Strings.Settings;
Name : in S_Expressions.Atom)
return Boolean
is
pragma Unreferenced (Settings);
begin
raise Invalid_Condition with "Unknown string simple conditional """
& S_Expressions.To_String (Name) & '"';
return False;
end String_Fallback_Simple;
------------------------
-- Comment Suprograms --
------------------------
function Get_Safe_Filter
(Site : in Sites.Site;
Name_Ref : in S_Expressions.Atom_Refs.Immutable_Reference;
Default : in S_Expressions.Atom_Refs.Immutable_Reference)
return Filters.Filter'Class is
begin
if not Name_Ref.Is_Empty then
begin
return Site.Get_Filter (Name_Ref.Query);
exception
when Filters.Stores.No_Filter => null;
end;
end if;
if not Default.Is_Empty then
begin
return Site.Get_Filter (Default.Query);
exception
when Filters.Stores.No_Filter => null;
end;
end if;
declare
Fallback : Filters.Text_Blocks.Filter;
begin
return Fallback;
end;
end Get_Safe_Filter;
function Get_Safe_Filter
(Builder : in Sites.Site_Builder;
Name_Ref : in S_Expressions.Atom_Refs.Immutable_Reference;
Default : in S_Expressions.Atom_Refs.Immutable_Reference)
return Filters.Filter'Class is
begin
if not Name_Ref.Is_Empty then
begin
return Sites.Get_Filter (Builder, Name_Ref.Query);
exception
when Filters.Stores.No_Filter => null;
end;
end if;
if not Default.Is_Empty then
begin
return Sites.Get_Filter (Builder, Default.Query);
exception
when Filters.Stores.No_Filter => null;
end;
end if;
declare
Fallback : Filters.Text_Blocks.Filter;
begin
return Fallback;
end;
end Get_Safe_Filter;
procedure Preprocess
(Comment : in out Comment_Data;
List : in Comment_List;
Site : in Sites.Site)
is
use Comment_Atoms;
begin
Preprocess
(Comment,
Get_Safe_Filter
(Site, Comment.Atoms (Filter), List.Default_Text_Filter));
end Preprocess;
procedure Preprocess
(Comment : in out Comment_Data;
List : in Comment_List;
Builder : in Sites.Site_Builder)
is
use Comment_Atoms;
begin
Preprocess
(Comment,
Get_Safe_Filter
(Builder, Comment.Atoms (Filter), List.Default_Text_Filter));
end Preprocess;
procedure Preprocess
(Comment : in out Comment_Data;
Text_Filter : in Filters.Filter'Class)
is
procedure Preprocess_Atom
(Ref : in out S_Expressions.Atom_Refs.Immutable_Reference);
procedure Preprocess_Link
(Ref : in out S_Expressions.Atom_Refs.Immutable_Reference;
Value : in S_Expressions.Atom);
procedure Preprocess_Atom
(Ref : in out S_Expressions.Atom_Refs.Immutable_Reference) is
begin
Reset_If_Blank (Ref);
if not Ref.Is_Empty then
Ref := Escapes.Escape (Ref, Escapes.HTML_Attribute);
end if;
end Preprocess_Atom;
procedure Preprocess_Link
(Ref : in out S_Expressions.Atom_Refs.Immutable_Reference;
Value : in S_Expressions.Atom)
is
use type S_Expressions.Atom;
begin
if Is_Valid_URL (S_Expressions.To_String (Value)) then
Ref := Escapes.Escape (Ref, Escapes.HTML_Attribute);
elsif Is_Valid_URL ("//" & S_Expressions.To_String (Value)) then
Ref := Escapes.Escape
((1 .. 2 => Character'Pos ('/')) & Value,
Escapes.HTML_Attribute);
else
Ref.Reset;
end if;
end Preprocess_Link;
use Comment_Atoms;
begin
if Comment.Flags (Comment_Flags.Preprocessed) then
return;
end if;
for I in Comment_Atoms.Enum loop
case I is
when Filter =>
null;
when Link =>
if not Comment.Atoms (I).Is_Empty then
Preprocess_Link (Comment.Atoms (I), Comment.Atoms (I).Query);
end if;
when Text =>
Reset_If_Blank (Comment.Atoms (I));
if not Comment.Atoms (I).Is_Empty then
declare
Buffer : S_Expressions.Atom_Buffers.Atom_Buffer;
begin
Text_Filter.Apply (Buffer, Comment.Atoms (I).Query);
Comment.Atoms (I) := Create (Buffer.Data);
end;
end if;
when Name | Mail | Class | Note | Title =>
Preprocess_Atom (Comment.Atoms (I));
end case;
end loop;
Comment.Flags (Comment_Flags.Preprocessed) := True;
end Preprocess;
function Preview_Id return S_Expressions.Atom_Refs.Immutable_Reference is
begin
if Preview_Id_Ref.Is_Empty then
Preview_Id_Ref := Create (S_Expressions.To_Atom ("preview"));
end if;
return Preview_Id_Ref;
end Preview_Id;
procedure Process_Form
(Data : in out Comment_Builder;
Exchange : in Sites.Exchange;
List : in Comment_List)
is
procedure Process (Field, Value : String);
procedure Process (Field, Value : String) is
use Static_Maps.Item.Form;
begin
Data.Raw_Fields.Insert (Field, Value);
case Static_Maps.To_Item_Form (Field) is
when Unknown =>
Data.Extra_Fields.Insert (Field, Value);
if Field /= Submit_Button and then Field /= Preview_Button then
Data.Has_Unknown_Field := True;
end if;
when Cookie_Save =>
if Value = "yes" then
Data.Cookie_Save := True;
else
Log (Severities.Info, "Unexpected cookie_save value """
& Value & '"');
end if;
when Date =>
if List.Flags (List_Flags.Allow_Date_Override) then
begin
Time_IO.RFC_3339.Value
(Value, Data.Core.Date, Data.Core.Offset);
exception
when others => null;
end;
else
Data.Extra_Fields.Insert (Field, Value);
Data.Has_Unknown_Field := True;
end if;
when Filter =>
if List.Text_Filters.Is_Empty then
Data.Extra_Fields.Insert (Field, Value);
Data.Has_Unknown_Field := True;
else
for Name_Ref of List.Text_Filters.Query.Data.all loop
if S_Expressions.To_String (Name_Ref.Query) = Value then
Data.Core.Atoms (Comment_Atoms.Filter) := Name_Ref;
exit;
end if;
end loop;
end if;
when Atom =>
pragma Assert (Field'Length > 2
and then Field (Field'First .. Field'First + 1) = "c_");
Data.Core.Atoms
(Comment_Atoms.Enum'Value
(Field (Field'First + 2 .. Field'Last)))
:= Create (S_Expressions.To_Atom (Value));
end case;
end Process;
begin
Data.Core.Atoms (Comment_Atoms.Class) := Get_Class (Exchange);
Exchange.Iterate_Parameters (Process'Access);
end Process_Form;
overriding procedure Render
(Exchange : in out Sites.Exchange;
Object : in Comment_Ref;
Expression : in out S_Expressions.Lockable.Descriptor'Class) is
begin
Render
(Expression, Exchange,
Comment_Maps.Element (Object.Container.Query.Find (Object.Id)));
end Render;
procedure Write
(Comment : in Comment_Data;
Output : in out S_Expressions.Printers.Printer'Class)
is
procedure Print (Key : in String; Value : in S_Expressions.Atom);
procedure Print
(Key : in String;
Value : in S_Expressions.Atom_Refs.Immutable_Reference);
procedure Print (Key : in String; Value : in S_Expressions.Atom) is
begin
Output.Open_List;
Output.Append_Atom (S_Expressions.To_Atom (Key));
Output.Append_Atom (Value);
Output.Close_List;
end Print;
procedure Print
(Key : in String;
Value : in S_Expressions.Atom_Refs.Immutable_Reference) is
begin
if not Value.Is_Empty then
Print (Key, Value.Query);
end if;
end Print;
use type Comment_Atoms.Enum;
begin
pragma Assert (not Comment.Flags (Comment_Flags.Preprocessed));
Print ("date", S_Expressions.To_Atom
(Time_IO.RFC_3339.Image (Comment.Date, Comment.Offset)));
for I in Comment_Atoms.Enum loop
Print (Image (I), Comment.Atoms (I));
end loop;
Print_Flags :
declare
Flag_Printed : Boolean := False;
begin
for Flag in Comment_Flags.Enum loop
if Comment.Flags (Flag) then
if not Flag_Printed then
Output.Open_List;
Output.Append_String ("flags");
Flag_Printed := True;
end if;
Output.Append_Atom (Comment_Flag_IO.Image (Flag));
end if;
end loop;
if Flag_Printed then
Output.Close_List;
end if;
end Print_Flags;
end Write;
procedure Write
(Builder : in Comment_Builder;
Output : in out S_Expressions.Printers.Printer'Class) is
begin
Output.Open_List;
Output.Append_Atom (Builder.Core.Id.Query);
Write (Builder.Core, Output);
Write_Extra_Fields :
declare
Cursor : String_Maps.Cursor := Builder.Extra_Fields.First;
begin
Output.Open_List;
Output.Append_String ("extra-fields");
while String_Maps.Has_Element (Cursor) loop
Output.Open_List;
Output.Append_String (String_Maps.Key (Cursor));
Output.Append_String (String_Maps.Element (Cursor));
Output.Close_List;
String_Maps.Next (Cursor);
end loop;
Output.Close_List;
end Write_Extra_Fields;
Output.Open_List;
Output.Append_String ("has-unknown-field");
Output.Append_String (Boolean'Image (Builder.Has_Unknown_Field));
Output.Close_List;
Output.Open_List;
Output.Append_String ("action");
Output.Append_Atom (Post_Action_IO.Image (Builder.Action));
if not Builder.Reason.Is_Empty then
Output.Append_Atom (Builder.Reason.Query);
end if;
Output.Close_List;
if not Builder.Anchor.Is_Empty then
Output.Open_List;
Output.Append_String ("anchor");
Output.Append_Atom (Builder.Anchor.Query);
Output.Close_List;
end if;
Output.Close_List;
end Write;
procedure Write
(Builder : in Comment_Builder;
Site : in Sites.Site;
Arguments : in out S_Expressions.Lockable.Descriptor'Class)
is
use type S_Expressions.Events.Event;
begin
if Arguments.Current_Event /= S_Expressions.Events.Add_Atom then
Log (Severities.Error,
"Invalid write target: first name is not an atom");
return;
end if;
declare
Stream : aliased File_Streams.File_Stream := File_Streams.Open
(Ada.Streams.Stream_IO.Append_File,
S_Expressions.To_String (Arguments.Current_Atom));
Printer : S_Expressions.Printers.Pretty.Stream_Printer
(Stream'Access);
begin
Site.Set_Parameters (Printer);
Write (Builder, Printer);
Printer.Newline;
end;
end Write;
------------------------------
-- Comment List Subprograms --
------------------------------
overriding procedure Finalize (Object : in out Comment_List) is
begin
if not Object.Comments.Is_Empty then
Object.Comments.Update.Orphan;
Object.Comments.Reset;
end if;
end Finalize;
procedure Live_Load
(Object : in out Comment_List;
Site : in Sites.Site;
Parent : in Tags.Visible_Access := null;
Parent_Path : in S_Expressions.Atom_Refs.Immutable_Reference
:= S_Expressions.Atom_Refs.Null_Immutable_Reference) is
begin
if Object.Backend_Name.Is_Empty or else Object.Backend_Path.Is_Empty then
return;
end if;
Object.Parent_Path := Parent_Path;
declare
procedure Process (Name : in S_Expressions.Atom);
Backend : constant Backends.Backend'Class
:= Site.Get_Backend (Object.Backend_Name.Query);
Directory : constant S_Expressions.Atom_Refs.Accessor
:= Object.Backend_Path.Query;
Map : Comment_Maps.Unsafe_Maps.Map;
procedure Process (Name : in S_Expressions.Atom) is
Input_Stream : aliased Ada.Streams.Root_Stream_Type'Class
:= Backend.Read (Directory, Name);
Reader : S_Expressions.Parsers.Stream_Parser (Input_Stream'Access);
Comment : Comment_Data;
Position : Comment_Maps.Unsafe_Maps.Cursor;
Inserted : Boolean;
begin
Reader.Next;
Update (Reader, Comment, Meaningless_Value);
if not Comment.Flags (Comment_Flags.Ignored) then
Comment.Id := Create (Name);
Comment.Parent := Parent;
Preprocess (Comment, Object, Site);
Map.Insert (Name, Comment, Position, Inserted);
if not Inserted then
Log (Severities.Error, "Duplicate comment id """
& S_Expressions.To_String (Name) & '"');
end if;
end if;
end Process;
begin
Backend.Iterate (Directory, Process'Access);
Object.Comments := Container_Refs.Create (new Comment_Container);
Object.Comments.Update.Initialize (Map, Parent);
Object.Parent := Parent;
end;
if not Object.Tags.Is_Empty then
declare
C : Comment_Maps.Cursor := Object.Comments.Query.First;
Id : S_Expressions.Atom_Refs.Immutable_Reference;
begin
while Comment_Maps.Has_Element (C) loop
Id := Comment_Maps.Element (C).Id;
Site.Queue_Update (Comment_Inserter'
(Container => Object.Comments,
Id => Id,
Tags => Object.Tags));
Comment_Maps.Next (C);
end loop;
end;
end if;
end Live_Load;
procedure Load
(Object : in out Comment_List;
Builder : in out Sites.Site_Builder;
Parent : in Tags.Visible_Access := null;
Parent_Path : in S_Expressions.Atom_Refs.Immutable_Reference
:= S_Expressions.Atom_Refs.Null_Immutable_Reference) is
begin
if Object.Backend_Name.Is_Empty or else Object.Backend_Path.Is_Empty then
return;
end if;
Object.Parent_Path := Parent_Path;
declare
procedure Process (Name : in S_Expressions.Atom);
Backend : constant Backends.Backend'Class
:= Sites.Get_Backend (Builder, Object.Backend_Name.Query);
Directory : constant S_Expressions.Atom_Refs.Accessor
:= Object.Backend_Path.Query;
Map : Comment_Maps.Unsafe_Maps.Map;
procedure Process (Name : in S_Expressions.Atom) is
Input_Stream : aliased Ada.Streams.Root_Stream_Type'Class
:= Backend.Read (Directory, Name);
Reader : S_Expressions.Parsers.Stream_Parser (Input_Stream'Access);
Comment : Comment_Data;
Position : Comment_Maps.Unsafe_Maps.Cursor;
Inserted : Boolean;
begin
Reader.Next;
Update (Reader, Comment, Meaningless_Value);
if not Comment.Flags (Comment_Flags.Ignored) then
Comment.Id := Create (Name);
Comment.Parent := Parent;
Preprocess (Comment, Object, Builder);
Map.Insert (Name, Comment, Position, Inserted);
if not Inserted then
Log (Severities.Error, "Duplicate comment id """
& S_Expressions.To_String (Name) & '"');
end if;
end if;
end Process;
begin
Backend.Iterate (Directory, Process'Access);
Object.Comments := Container_Refs.Create (new Comment_Container);
Object.Comments.Update.Initialize (Map, Parent);
Object.Parent := Parent;
end;
if not Object.Tags.Is_Empty then
declare
C : Comment_Maps.Cursor := Object.Comments.Query.First;
Id : S_Expressions.Atom_Refs.Immutable_Reference;
begin
while Comment_Maps.Has_Element (C) loop
Id := Comment_Maps.Element (C).Id;
Sites.Insert
(Builder,
Tags.Create (Object.Tags.Query, Id),
Comment_Ref'(Object.Comments, Id));
Comment_Maps.Next (C);
end loop;
end;
end if;
end Load;
procedure Render
(Exchange : in out Sites.Exchange;
Object : in Comment_List;
Expression : in out S_Expressions.Lockable.Descriptor'Class) is
begin
if not Object.Backend_Name.Is_Empty
and then not Object.Backend_Path.Is_Empty
then
Render (Expression, Exchange, Object);
end if;
end Render;
procedure Respond
(List : in out Comment_List;
Exchange : in out Sites.Exchange;
Extra_Path : in S_Expressions.Atom)
is
function Get_Anchor
(Builder : Comment_Builder;
Default : S_Expressions.Atom)
return S_Expressions.Atom;
function Redirect_Base
(Builder : Comment_Builder)
return S_Expressions.Atom;
function Redirect_Location
(Default_Anchor : S_Expressions.Atom := S_Expressions.Null_Atom)
return S_Expressions.Atom;
function Get_Anchor
(Builder : Comment_Builder;
Default : S_Expressions.Atom)
return S_Expressions.Atom is
begin
if Builder.Anchor.Is_Empty then
return Default;
else
return Builder.Anchor.Query;
end if;
end Get_Anchor;
function Redirect_Base
(Builder : Comment_Builder)
return S_Expressions.Atom is
begin
if Builder.Redirect_Base.Is_Empty then
return List.Parent_Path.Query;
else
return Builder.Redirect_Base.Query;
end if;
end Redirect_Base;
Builder : Comment_Builder;
function Redirect_Location
(Default_Anchor : S_Expressions.Atom := S_Expressions.Null_Atom)
return S_Expressions.Atom
is
use type Ada.Streams.Stream_Element_Array;
Anchor : constant S_Expressions.Atom
:= Get_Anchor (Builder, Default_Anchor);
begin
if Anchor'Length > 0 then
return Redirect_Base (Builder) & Character'Pos ('#') & Anchor;
else
return Redirect_Base (Builder);
end if;
end Redirect_Location;
begin
if Extra_Path'Length > 0
or else List.Flags (List_Flags.Closed)
or else List.Backend_Name.Is_Empty
or else List.Backend_Path.Is_Empty
or else List.Parent_Path.Is_Empty
then
return;
end if;
Check_Method :
declare
Allowed : Boolean;
begin
Error_Pages.Check_Method (Exchange, Exchanges.POST, Allowed);
if not Allowed then
return;
end if;
end Check_Method;
if Exchange.Parameter (Preview_Button) /= "" then
if not Tags."=" (List.Parent, null) then
Render_Default (Exchange, List.Parent.all);
end if;
return;
elsif Exchange.Parameter (Ignore_Button) /= ""
and then List.Flags (List_Flags.Allow_Ignore)
then
declare
procedure Process (Name, Value : in String);
Ids : Id_Lists.List;
procedure Process (Name, Value : in String) is
Ref : S_Expressions.Atom_Refs.Immutable_Reference;
begin
if Name /= "id" then
return;
end if;
List.Comments.Update.Ignore
(S_Expressions.To_Atom (Value), Ref);
if Ref.Is_Empty then
return;
end if;
Ids.Append (Ref);
Update_Stored_Comment :
declare
Backend : Backends.Backend'Class
:= Exchange.Site.Get_Backend (List.Backend_Name.Query);
Stream : aliased Ada.Streams.Root_Stream_Type'Class
:= Backend.Append
(List.Backend_Path.Query,
Ref.Query);
Printer : S_Expressions.Printers.Pretty.Stream_Printer
(Stream'Access);
begin
Exchange.Site.Set_Parameters (Printer);
Printer.Open_List;
Printer.Append_String ("flags");
Printer.Append_Atom
(Comment_Flag_IO.Image (Comment_Flags.Ignored));
Printer.Close_List;
end Update_Stored_Comment;
end Process;
begin
Exchange.Iterate_Parameters (Process'Access);
if not List.Tags.Is_Empty and then not Ids.Is_Empty then
Exchange.Site.Queue_Update (Comment_Remover'
(Container => List.Comments,
Ids => Ids,
Tags => List.Tags));
end if;
end;
Error_Pages.See_Other (Exchange, Redirect_Location);
return;
elsif Exchange.Parameter (Submit_Button) = "" then
return;
end if;
Builder.Action := Save_Comment;
Builder.Core.Date := Ada.Calendar.Clock;
Builder.Core.Offset := Ada.Calendar.Time_Zones.UTC_Time_Offset
(Builder.Core.Date);
Builder.Core.Id := Create (S_Expressions.To_Atom
(Time_Keys.To_Key (Builder.Core.Date)));
Builder.Core.Flags (Comment_Flags.Ignored)
:= List.Flags (List_Flags.Ignore_By_Default);
Process_Form (Builder, Exchange, List);
Process_Actions (Builder, Exchange.Site.all, List.Post_Filter);
if not Builder.Reason.Is_Empty then
Log (Severities.Info, "Comment tagged "
& Post_Action'Image (Builder.Action)
& " because "
& S_Expressions.To_String (Builder.Reason.Query));
end if;
case Builder.Action is
when Force_Preview =>
if not Tags."=" (List.Parent, null) then
Render_Default (Exchange, List.Parent.all);
end if;
when Parent_Redirect =>
Error_Pages.See_Other (Exchange, Redirect_Location);
when Save_Comment =>
Write_Comment :
declare
Backend : Backends.Backend'Class
:= Exchange.Site.Get_Backend (List.Backend_Name.Query);
Stream : aliased Ada.Streams.Root_Stream_Type'Class
:= Backend.Create
(List.Backend_Path.Query,
Builder.Core.Id.Query);
Printer : S_Expressions.Printers.Pretty.Stream_Printer
(Stream'Access);
begin
Exchange.Site.Set_Parameters (Printer);
Write (Builder.Core, Printer);
end Write_Comment;
if Builder.Cookie_Save then
Set_Cookie :
declare
Info : constant Comment_Cookies.Comment_Info
:= Comment_Cookies.Create
(Name => Builder.Core.Atoms (Comment_Atoms.Name),
Mail => Builder.Core.Atoms (Comment_Atoms.Mail),
Link => Builder.Core.Atoms (Comment_Atoms.Link),
Filter => Builder.Core.Atoms (Comment_Atoms.Filter));
begin
Sites.Set_Comment_Cookie (Exchange, Info);
end Set_Cookie;
end if;
Error_Pages.See_Other
(Exchange,
Redirect_Location (Builder.Core.Id.Query));
if not Builder.Core.Flags (Comment_Flags.Ignored) then
Preprocess (Builder.Core, List, Exchange.Site.all);
List.Comments.Update.Insert (Builder.Core);
if not List.Tags.Is_Empty then
Exchange.Site.Queue_Update (Comment_Inserter'
(Container => List.Comments,
Id => Builder.Core.Id,
Tags => List.Tags));
end if;
end if;
end case;
end Respond;
procedure Set
(List : out Comment_List;
Expression : in out S_Expressions.Lockable.Descriptor'Class) is
begin
List := Empty_List;
Update (Expression, List, Meaningless_Value);
end Set;
procedure Set
(List : out Comment_List;
Template : in out S_Expressions.Lockable.Descriptor'Class;
Expression : in out S_Expressions.Lockable.Descriptor'Class;
Path_Override : in S_Expressions.Atom_Refs.Immutable_Reference
:= S_Expressions.Atom_Refs.Null_Immutable_Reference) is
begin
List := Empty_List;
Update (Template, List, Meaningless_Value);
Update (Expression, List, Meaningless_Value);
if not Path_Override.Is_Empty then
List.Backend_Path := Path_Override;
end if;
end Set;
procedure Set_Parent
(Container : in out Comment_Maps.Updatable_Map;
Parent : in Tags.Visible_Access) is
begin
for E of Container loop
E.Parent := Parent;
end loop;
end Set_Parent;
procedure Update_Ranks (Container : in out Comment_Maps.Updatable_Map) is
Current_Rank : Positive := 1;
begin
for E of Container loop
E.Rank := Current_Rank;
Current_Rank := Current_Rank + 1;
end loop;
pragma Assert (Current_Rank = Natural (Container.Length) + 1);
end Update_Ranks;
-----------------------
-- Comment Container --
-----------------------
protected body Comment_Container is
procedure Initialize
(Data : in Comment_Maps.Unsafe_Maps.Map;
Parent : in Tags.Visible_Access) is
begin
Map := Comment_Maps.Create (Data);
Set_Parent (Map, Parent);
Update_Ranks (Map);
Comment_Container.Parent := Parent;
end Initialize;
procedure Insert (Data : in Comment_Data) is
New_Item : Comment_Data := Data;
begin
New_Item.Parent := Parent;
Map := Comment_Maps.Insert (Map, New_Item.Id.Query, New_Item);
Update_Ranks (Map);
end Insert;
procedure Ignore
(Id : in S_Expressions.Atom;
Ref : out S_Expressions.Atom_Refs.Immutable_Reference)
is
Position : constant Comment_Maps.Cursor := Map.Find (Id);
begin
if Comment_Maps.Has_Element (Position) then
Ref := Comment_Maps.Element (Position).Id;
Map := Comment_Maps.Delete (Map, Position);
Update_Ranks (Map);
else
Ref := S_Expressions.Atom_Refs.Null_Immutable_Reference;
Log (Severities.Error,
"Unknown comment id """
& S_Expressions.To_String (Id)
& """ to ignore");
end if;
end Ignore;
procedure Orphan is
begin
Set_Parent (Map, null);
Parent := null;
end Orphan;
function Find (Id : S_Expressions.Atom_Refs.Immutable_Reference)
return Comment_Maps.Cursor is
begin
return Map.Find (Id.Query);
end Find;
function First return Comment_Maps.Cursor is
begin
return Map.First;
end First;
function Iterate return
Comment_Maps.Map_Iterator_Interfaces.Reversible_Iterator'Class is
begin
return Map.Iterate;
end Iterate;
function Length return Natural is
begin
return Natural (Map.Length);
end Length;
end Comment_Container;
-------------------
-- Site Updaters --
-------------------
overriding procedure Update
(Self : in Comment_Inserter;
Site : in out Sites.Site) is
begin
pragma Assert (not Self.Tags.Is_Empty);
Site.Insert
(Tags.Create (Self.Tags.Query, Self.Id),
Comment_Ref'(Self.Container, Self.Id));
end Update;
overriding procedure Update
(Self : in Comment_Remover;
Site : in out Sites.Site) is
begin
pragma Assert (not Self.Tags.Is_Empty);
for Id of Self.Ids loop
Site.Remove
(Tags.Create (Self.Tags.Query, Id),
Comment_Ref'(Self.Container, Id));
end loop;
end Update;
end Natools.Web.Comments;
|
-- CC3016F.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.
--*
-- OFFICE, 3E 114, THE PENTAGON, WASHINGTON DC 20301-3081.
-- OBJECTIVE:
-- CHECK THAT AN INSTANTIATED PACKAGE HAS THE PROPERTIES REQUIRED
-- OF A PACKAGE.
-- CHECK THAT IF THE PARENT TYPE IN A DERIVED TYPE DEFINITION IS
-- A GENERIC FORMAL TYPE, THE OPERATIONS DECLARED FOR THE DERIVED
-- TYPE IN THE TEMPLATE ARE DETERMINED BY THE DECLARATION OF THE
-- FORMAL TYPE. THE OPERATIONS DECLARED FOR DERIVED TYPE IN THE
-- INSTANCE ARE DETERMINED BY THE ACTUAL TYPE DENOTED BY THE FORMAL
-- PARAMETER. SEE AI-00398.
-- HISTORY:
-- DAS 8 OCT 90 INITIAL VERSION.
-- JRL 02/19/93 ADDED USE CLAUSES FOR INSTANCES TO ENSURE DIRECT
-- OPERATOR VISIBILITY. CHANGED NT4'LAST TO P4.NT4'LAST
-- IN ASSIGNMENT STATEMENT FOR P4.X IN EXAMPLE_4.
-- CORRECTED ABE ERRORS IN EXAMPLE_2 AND EXAMPLE_3.
-- CHANGED R3."+" FROM MULTIPLICATION TO SUBTRACTION TO
-- AVOID CONSTRAINT_ERROR.
WITH REPORT;
PROCEDURE CC3016F IS
BEGIN
REPORT.TEST ("CC3016F", "CHECK THAT IF THE PARENT TYPE IN A " &
"DERIVED TYPE DEFINITION IS A GENERIC " &
"FORMAL TYPE, THE OPERATIONS DECLARED " &
"FOR THE DERIVED TYPE IN THE TEMPLATE " &
"ARE DETERMINED BY THE DECLARATION OF " &
"THE FORMAL TYPE, AND THAT THE " &
"OPERATIONS DECLARED FOR THE DERIVED " &
"TYPE IN THE INSTANCE ARE DETERMINED BY " &
"THE ACTUAL TYPE DENOTED BY THE FORMAL " &
"PARAMETER (AI-00398)");
EXAMPLE_2:
DECLARE
GENERIC
TYPE PRIV IS PRIVATE;
PACKAGE GP2 IS
TYPE NT2 IS NEW PRIV;
END GP2;
PACKAGE R2 IS
TYPE T2 IS RANGE 1..10;
FUNCTION F RETURN T2;
END R2;
PACKAGE P2 IS NEW GP2 (PRIV => R2.T2);
USE P2;
XX1 : P2.NT2;
XX2 : P2.NT2;
XX3 : P2.NT2;
PACKAGE BODY R2 IS
FUNCTION F RETURN T2 IS
BEGIN
RETURN T2'LAST;
END F;
END R2;
BEGIN
XX1 := 5; -- IMPLICIT CONVERSION FROM
-- UNIVERSAL INTEGER TO P2.NT2
-- IN P2.
XX2 := XX1 + XX1; -- PREDEFINED "+" DECLARED FOR
-- P2.NT2.
XX3 := P2.F; -- FUNCTION F DERIVED WITH THE
-- INSTANCE.
END EXAMPLE_2;
EXAMPLE_3:
DECLARE
GENERIC
TYPE T3 IS RANGE <>;
PACKAGE GP3 IS
TYPE NT3 IS NEW T3;
X : NT3 := 5;
Y : NT3 := X + 3; -- USES PREDEFINED "+" EVEN IN
-- INSTANCES
END GP3;
PACKAGE R3 IS
TYPE S IS RANGE 1..10;
FUNCTION "+" (LEFT : IN S; RIGHT : IN S) RETURN S;
END R3;
PACKAGE P3 IS NEW GP3 ( T3 => R3.S );
USE P3;
Z : P3.NT3;
PACKAGE BODY R3 IS
FUNCTION "+" (LEFT : IN S; RIGHT : IN S) RETURN S IS
BEGIN -- IMPLEMENT AS SUBTRACTION, NOT ADDITION
RETURN LEFT - RIGHT;
END "+";
END R3;
BEGIN
Z := P3.X + 3; -- USES REDEFINED "+"
IF ( P3.Y /= P3.NT3'(8) ) THEN
REPORT.FAILED ("PREDEFINED ""+"" NOT USED TO COMPUTE " &
"P3.Y");
END IF;
IF (Z /= P3.NT3'(2) ) THEN
REPORT.FAILED ("REDEFINED ""+"" NOT USED TO COMPUTE Z");
END IF;
END EXAMPLE_3;
EXAMPLE_4:
DECLARE
GENERIC
TYPE T4 IS LIMITED PRIVATE;
PACKAGE GP4 IS
TYPE NT4 IS NEW T4;
X : NT4;
END GP4;
PACKAGE P4 IS NEW GP4 (BOOLEAN);
USE P4;
BEGIN
P4.X := P4.NT4'LAST;
IF ( P4.X OR (NOT P4.X) ) THEN
REPORT.COMMENT ("P4.X CORRECTLY HAS A BOOLEAN TYPE");
END IF;
END EXAMPLE_4;
EXAMPLE_5:
DECLARE
GENERIC
TYPE T5 (D : POSITIVE) IS PRIVATE;
PACKAGE GP5 IS
TYPE NT5 IS NEW T5;
X : NT5 (D => 5);
Y : POSITIVE := X.D; -- REFERS TO DISCRIMINANT OF NT5
END GP5;
TYPE REC (A : POSITIVE) IS
RECORD
D : POSITIVE := 7;
END RECORD;
PACKAGE P5 IS NEW GP5 (T5 => REC);
-- P5.Y INITIALIZED WITH VALUE USING COMPONENT SELECTION
-- OPERATION FOR THE DISCRIMINANT, I.E. FOR PARENT TYPE
-- T5 WHICH DENOTES REC.
W1 : POSITIVE := P5.X.D; -- VALUE IS 7
W2 : POSITIVE := P5.X.A; -- VALUE IS 5
W3 : POSITIVE := P5.Y; -- VALUE IS 5;
BEGIN
IF ( ( W1 /= 7 ) OR ( W2 /= 5 ) OR (W3 /= 5 ) ) THEN
REPORT.FAILED ("INCORRECT COMPONENT SELECTION");
END IF;
END EXAMPLE_5;
REPORT.RESULT;
END CC3016F;
|
package body casillero is
procedure set_estado(c : in out t_casillero;e : in t_estado_casillero) is
begin
c.estado := e;
end set_estado;
function get_estado(c: in t_casillero) return t_estado_casillero is
begin
return c.estado;
end get_estado;
end casillero;
|
with Ada.Finalization;
with Ada.Text_IO;
with System.Address_Image;
with System.Storage_Elements;
with GC.Pools;
procedure try_gc_controlled is
package Dummies is
type Dummy is new Ada.Finalization.Controlled with null record;
overriding procedure Initialize (Object : in out Dummy);
overriding procedure Finalize (Object : in out Dummy);
end Dummies;
package body Dummies is
overriding procedure Initialize (Object : in out Dummy) is
begin
Ada.Text_IO.Put_Line (
"Initialize (" & System.Address_Image (Object'Address) & ")");
end Initialize;
overriding procedure Finalize (Object : in out Dummy) is
begin
Ada.Text_IO.Put_Line (
"Finalize (" & System.Address_Image (Object'Address) & ")");
end Finalize;
end Dummies;
type Dummy_Access is access Dummies.Dummy;
for Dummy_Access'Storage_Pool use GC.Pools.Controlled_Pool;
begin
loop
for I in 1 .. 1000 loop
declare
Gomi : constant Dummy_Access := new Dummies.Dummy;
pragma Unreferenced (Gomi);
begin
null;
end;
end loop;
Ada.Text_IO.Put_Line (
System.Storage_Elements.Storage_Count'Image (GC.Heap_Size));
end loop;
end try_gc_controlled;
|
pragma Ada_2012;
pragma Style_Checks (Off);
with Interfaces.C; use Interfaces.C;
with bits_types_h;
package bits_types_time_t_h is
-- Returned by `time'.
subtype time_t is bits_types_h.uu_time_t; -- /usr/include/bits/types/time_t.h:7
end bits_types_time_t_h;
|
-------------------------------------------------------------------------------
-- GPS
--
-- Copyright © 2016 Eric Laursen
--
-- This code is available under the "MIT License".
-- Please see the file COPYING in this distribution for license terms.
--
-- Purpose:
-- This package interfaces to the Adafruit Ultimate GPS Breakout v3
-- (https://www.adafruit.com/product/746) based on the MediaTek MT3339
-- chipset.
-------------------------------------------------------------------------------
package body GPS is
----------------------------------------------------------------------------
function Get_Position return Position_Type is
Position : Position_Type;
Seconds_Of_Day : Day_Duration; -- Used to round the time down to the
-- nearest minute for testing
begin
-- GPS interface will be built once the toolchain for the Tiva-C ARM
-- is in place and functioning. Hard setting position to Rogue Hall,
-- Portland, Oregon (1717-C SW Park Ave, 97201).
-- Position.Latitude := 45.512_850_3;
-- Position.Longitude := -122.685_360_3;
-- Everything rounded down to the nearest minute for testing against
-- http://www.pveducation.org/pvcdrom/properties-of-sunlight/
-- sun-position-calculator
Position.Latitude := 45.0;
Position.Longitude := -122.0;
Position.Current_Time := Clock;
Seconds_Of_Day := Seconds (Position.Current_Time);
Position.Current_Time :=
Position.Current_time -
Day_Duration ((Integer (Seconds_Of_Day) mod 60));
-- ---------------
-- -- Debugging --
-- ---------------
-- Put ("Lat: "); Put (Position.Latitude, 4, 3, 0);
-- Put (" Long: "); Put (Position.Longitude, 4, 3, 0);
-- New_Line (2);
-- Put ("Seconds: "); Put (Integer (Seconds_Of_Day)); New_Line;
-- Put ("Difference: "); Put (Integer (Seconds_Of_Day) mod 60); New_Line;
-- Put ("Adjusted: "); Put (Integer (Seconds (Position.Current_Time)));
-- New_Line;
return Position;
end Get_Position;
end GPS;
|
pragma Style_Checks (Off);
package USB.Lang is
Invalid : constant Lang_ID := 16#0000#; -- Invalid LANG ID
Afrikaans : constant Lang_ID := 16#0436#; -- Afrikaans
Albanian : constant Lang_ID := 16#041c#; -- Albanian
Arabic_Saudi_Arabia : constant Lang_ID := 16#0401#; -- Arabic (Saudi Arabia)
Arabic_Irak : constant Lang_ID := 16#0801#; -- Arabic (Irak)
Arabic_Egypt : constant Lang_ID := 16#0c01#; -- Arabic (Egypt)
Arabic_Lybya : constant Lang_ID := 16#1001#; -- Arabic (Libya)
Arabic_Algeria : constant Lang_ID := 16#1401#; -- Arabic (Algeria)
Arabic_Morocco : constant Lang_ID := 16#1801#; -- Arabic (Morocco)
Arabic_Tunisia : constant Lang_ID := 16#1c01#; -- Arabic (Tunisia)
Arabic_Oman : constant Lang_ID := 16#2001#; -- Arabic (Oman)
Arabic_Yemen : constant Lang_ID := 16#2401#; -- Arabic (Yemen)
Arabic_Syria : constant Lang_ID := 16#2801#; -- Arabic (Syria)
Arabic_Jordan : constant Lang_ID := 16#2c01#; -- Arabic (Jordan)
Arabic_Lebanon : constant Lang_ID := 16#3001#; -- Arabic (Lebanon)
Arabic_Kuwait : constant Lang_ID := 16#3401#; -- Arabic (Kuwait)
Arabic_Uae : constant Lang_ID := 16#3801#; -- Arabic (U.A.E.)
Arabic_Bahrain : constant Lang_ID := 16#3c01#; -- Arabic (Bahrain)
Arabic_Qatar : constant Lang_ID := 16#4001#; -- Arabic (Qatar)
Armenian : constant Lang_ID := 16#042b#; -- Armenian
Assamese : constant Lang_ID := 16#044d#; -- Assamese
Azeri_Latin : constant Lang_ID := 16#042c#; -- Azeri (Latin)
Azeri_Cyrillic : constant Lang_ID := 16#082c#; -- Azeri (Cyrillic)
Basque : constant Lang_ID := 16#042d#; -- Basque
Belarussian : constant Lang_ID := 16#0423#; -- Belarussian
Bengali : constant Lang_ID := 16#0445#; -- Bengali
Bulgarian : constant Lang_ID := 16#0402#; -- Bulgarian
Burmese : constant Lang_ID := 16#0455#; -- Burmese
Catalan : constant Lang_ID := 16#0403#; -- Catalan
Chinese_Taiwan : constant Lang_ID := 16#0404#; -- Chinese (Taiwan)
Chinese_Prc : constant Lang_ID := 16#0804#; -- Chinese (PRC = People Republic of Chinese)
Chinese_Hong_Kong : constant Lang_ID := 16#0c04#; -- Chinese (Hong Kong)
Chinese_Singapore : constant Lang_ID := 16#1004#; -- Chinese (Singapore)
Chinese_Macau_Sar : constant Lang_ID := 16#1404#; -- Chinese (Macau SAR)
Croatian : constant Lang_ID := 16#041a#; -- Croatian
Czech : constant Lang_ID := 16#0405#; -- Czech
Danish : constant Lang_ID := 16#0406#; -- Danish
Dutch_Netherlands : constant Lang_ID := 16#0413#; -- Dutch (Netherlands)
Dutch_Belgium : constant Lang_ID := 16#0813#; -- Dutch (Belgium)
English_United_States : constant Lang_ID := 16#0409#; -- English (United States)
English_United_Kingdom : constant Lang_ID := 16#0809#; -- English (United Kingdom)
English_Australian : constant Lang_ID := 16#0c09#; -- English (Australian)
English_Canadian : constant Lang_ID := 16#1009#; -- English (Canadian)
English_New_Zealand : constant Lang_ID := 16#1409#; -- English (New Zealand)
English_Ireland : constant Lang_ID := 16#1809#; -- English (Ireland)
English_South_Africa : constant Lang_ID := 16#1c09#; -- English (South Africa)
English_Jamaica : constant Lang_ID := 16#2009#; -- English (Jamaica)
English_Caribbean : constant Lang_ID := 16#2409#; -- English (Caribbean)
English_Belize : constant Lang_ID := 16#2809#; -- English (Belize)
English_Trinidad : constant Lang_ID := 16#2c09#; -- English (Trinidad)
English_Zimbabwe : constant Lang_ID := 16#3009#; -- English (Zimbabwe)
English_Phlippines : constant Lang_ID := 16#3409#; -- English (Philippines)
Estonian : constant Lang_ID := 16#0425#; -- Estonian
Faeroese : constant Lang_ID := 16#0438#; -- Faeroese
Farsi : constant Lang_ID := 16#0429#; -- Farsi
Finnish : constant Lang_ID := 16#040b#; -- Finnish
French_Standard : constant Lang_ID := 16#040c#; -- French (Standard)
French_Belgian : constant Lang_ID := 16#080c#; -- French (Belgian)
French_Canadian : constant Lang_ID := 16#0c0c#; -- French (Canadian)
French_Switzerland : constant Lang_ID := 16#100c#; -- French (Switzerland)
French_Luxembourg : constant Lang_ID := 16#140c#; -- French (Luxembourg)
French_Monaco : constant Lang_ID := 16#180c#; -- French (Monaco)
Georgian : constant Lang_ID := 16#0437#; -- Georgian
German_Standard : constant Lang_ID := 16#0407#; -- German (Standard)
German_Switzerland : constant Lang_ID := 16#0807#; -- German (Switzerland)
German_Austria : constant Lang_ID := 16#0c07#; -- German (Austria)
German_Luxembourg : constant Lang_ID := 16#1007#; -- German (Luxembourg)
German_Liechtenstein : constant Lang_ID := 16#1407#; -- German (Liechtenstein)
Greek : constant Lang_ID := 16#0408#; -- Greek
Gujarati : constant Lang_ID := 16#0447#; -- Gujarati
Hebrew : constant Lang_ID := 16#040d#; -- Hebrew
Hindi : constant Lang_ID := 16#0439#; -- Hindi
Hungarian : constant Lang_ID := 16#040e#; -- Hungarian
Icelandic : constant Lang_ID := 16#040f#; -- Icelandic
Indonesian : constant Lang_ID := 16#0421#; -- Indonesian
Italian_Standard : constant Lang_ID := 16#0410#; -- Italian (Standard)
Italian_Switzerland : constant Lang_ID := 16#0810#; -- Italian (Switzerland)
Japanese : constant Lang_ID := 16#0411#; -- Japanese
Kannada : constant Lang_ID := 16#044b#; -- Kannada
Kashmiri_India : constant Lang_ID := 16#0860#; -- Kashmiri (India)
Kazakh : constant Lang_ID := 16#043f#; -- Kazakh
Konkani : constant Lang_ID := 16#0457#; -- Konkani
Korean_Johab : constant Lang_ID := 16#0412#; -- Korean (Johab)
Latvian : constant Lang_ID := 16#0426#; -- Latvian
Lithuanian : constant Lang_ID := 16#0427#; -- Lithuanian
Lithuanian_Classic : constant Lang_ID := 16#0827#; -- Lithuanian (Classic)
Macedonian : constant Lang_ID := 16#042f#; -- Macedonian
Malay_Malaysian : constant Lang_ID := 16#043e#; -- Malay (Malaysian)
Malay_Brunei_Darussalam : constant Lang_ID := 16#083e#; -- Malay (Brunei Darussalam)
Malayalam : constant Lang_ID := 16#044c#; -- Malayalam
Manipuri : constant Lang_ID := 16#0458#; -- Manipuri
Marathi : constant Lang_ID := 16#044e#; -- Marathi
Nepali_India : constant Lang_ID := 16#0861#; -- Nepali (India)
Norwegian_Bokmal : constant Lang_ID := 16#0414#; -- Norwegian (Bokmal)
Norwegian_Nynorsk : constant Lang_ID := 16#0814#; -- Norwegian (Nynorsk)
Oriya : constant Lang_ID := 16#0448#; -- Oriya
Polish : constant Lang_ID := 16#0415#; -- Polish
Portuguese_Brazil : constant Lang_ID := 16#0416#; -- Portuguese (Brazil)
Portuguese_Standard : constant Lang_ID := 16#0816#; -- Portuguese (Standard)
Punjabi : constant Lang_ID := 16#0446#; -- Punjabi
Romanian : constant Lang_ID := 16#0418#; -- Romanian
Russian : constant Lang_ID := 16#0419#; -- Russiane
Sanskrit : constant Lang_ID := 16#044f#; -- Sanskrit
Serbian_Cyrillic : constant Lang_ID := 16#0c1a#; -- Serbian (Cyrillic)
Serbian_Latin : constant Lang_ID := 16#081a#; -- Serbian (Latin)
Sindhi : constant Lang_ID := 16#0459#; -- Sindhi
Slovak : constant Lang_ID := 16#041b#; -- Slovak
Slovenian : constant Lang_ID := 16#0424#; -- Slovenian
Spannish_Traditional_Sort : constant Lang_ID := 16#040a#; -- Spannish (Traditional Sort)
Spannish_Mexican : constant Lang_ID := 16#080a#; -- Spannish (Mexican)
Spannish_Modern_Sort : constant Lang_ID := 16#0c0a#; -- Spannish (Modern Sort)
Spannish_Guatemala : constant Lang_ID := 16#100a#; -- Spannish (Guatemala)
Spannish_Costa_Rica : constant Lang_ID := 16#140a#; -- Spannish (Costa Rica)
Spannish_Panama : constant Lang_ID := 16#180a#; -- Spannish (Panama)
Spannish_Dominican_Republic : constant Lang_ID := 16#1c0a#; -- Spannish (Dominican Republic)
Spannish_Venezuela : constant Lang_ID := 16#200a#; -- Spannish (Venezuela)
Spannish_Colombia : constant Lang_ID := 16#240a#; -- Spannish (Colombia)
Spannish_Peru : constant Lang_ID := 16#280a#; -- Spannish (Peru)
Spannish_Argentina : constant Lang_ID := 16#2c0a#; -- Spannish (Argentina)
Spannish_Ecuador : constant Lang_ID := 16#300a#; -- Spannish (Ecuador)
Spannish_Chile : constant Lang_ID := 16#340a#; -- Spannish (Chile)
Spannish_Uruguay : constant Lang_ID := 16#380a#; -- Spannish (Uruguay)
Spannish_Paraguay : constant Lang_ID := 16#3c0a#; -- Spannish (Paraguay)
Spannish_Bolivia : constant Lang_ID := 16#400a#; -- Spannish (Bolivia)
Spannish_El_Salvador : constant Lang_ID := 16#440a#; -- Spannish (El Salvador)
Spannish_Honduras : constant Lang_ID := 16#480a#; -- Spannish (Honduras)
Spannish_Nicaragua : constant Lang_ID := 16#4c0a#; -- Spannish (Nicaragua)
Spannish_Puerto_Rico : constant Lang_ID := 16#500a#; -- Spannish (Puerto Rico)
Sutu : constant Lang_ID := 16#0430#; -- Sutu
Swahili_Kenya : constant Lang_ID := 16#0441#; -- Swahili (Kenya)
Swedish : constant Lang_ID := 16#041d#; -- Swedish
Swedish_Finland : constant Lang_ID := 16#081d#; -- Swedish (Finland)
Tamil : constant Lang_ID := 16#0449#; -- Tamil
Tatar_Tatarstan : constant Lang_ID := 16#0444#; -- Tatar (Tatarstan)
Telugu : constant Lang_ID := 16#044a#; -- Telugu
Thai : constant Lang_ID := 16#041e#; -- Thai
Turkish : constant Lang_ID := 16#041f#; -- Turkish
Ukrainian : constant Lang_ID := 16#0422#; -- Ukrainian
Urdu_Pakistan : constant Lang_ID := 16#0420#; -- Urdu (Pakistan)
Urdu_India : constant Lang_ID := 16#0820#; -- Urdu (India)
Uzbek_Latin : constant Lang_ID := 16#0443#; -- Uzbek (Latin)
Uzbek_Cyrillic : constant Lang_ID := 16#0843#; -- Uzbek (Cyrillic)
Vietnamese : constant Lang_ID := 16#042a#; -- Vietnamese
Hid_Udd : constant Lang_ID := 16#04ff#; -- HID (Usage Data Descriptor)
Hid1 : constant Lang_ID := 16#f0ff#; -- HID (Vendor Defined 1)
Hid2 : constant Lang_ID := 16#f4ff#; -- HID (Vendor Defined 2)
Hid3 : constant Lang_ID := 16#f8ff#; -- HID (Vendor Defined 3)
Hid4 : constant Lang_ID := 16#fcff#; -- HID (Vendor Defined 4)
end USB.Lang;
|
package Successeur is
function plus(t1: Integer; t2: Integer) return Integer;
end Successeur;
|
with Ada.Text_IO; use Ada.Text_IO;
procedure Main is
subtype Year_T is Positive range 1_900 .. 2_099;
subtype Month_T is Positive range 1 .. 12;
subtype Day_T is Positive range 1 .. 31;
type Date_T is record
Year : Positive;
Month : Positive;
Day : Positive;
end record;
-- implement correctly as an expression function
function Is_Leap_Year
(Year : Positive)
return Boolean is (False);
-- implement correctly as an expression function
-- (case expression would be helpful)
function Days_In_Month
(Month : Positive;
Year : Positive)
return Positive is (1);
-- Implement correctly as an expression function
function Is_Valid
(Date : Date_T)
return Boolean is (False);
List : array (1 .. 5) of Date_T;
Item : Date_T;
function Number
(Prompt : String)
return Positive is
begin
Put (Prompt & "> ");
return Positive'value (Get_Line);
end Number;
begin
for I in List'range loop
Item.Year := Number ("Year");
Item.Month := Number ("Month");
Item.Day := Number ("Day");
List (I) := Item;
end loop;
-- Print True/False if any date in the list is not valid
Put_Line ("Any invalid: " & Boolean'image (False));
-- Print True/False if all dates in the list are in the same year
Put_Line ("Same Year: " & Boolean'image (False));
end Main;
|
-- Copyright 2019-2021 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/>.
with Pck; use Pck;
with System.Storage_Elements; use System.Storage_Elements;
procedure Storage is
subtype Some_Range is Natural range 0..127;
subtype Another_Range is Natural range 0..15;
type Rec is record
Value : Some_Range;
Another_Value : Another_Range;
end record;
for Rec use record
Value at 0 range 0..6;
Another_Value at 0 range 7..10;
end record;
type Rec_LE is new Rec;
for Rec_LE'Bit_Order use System.Low_Order_First;
for Rec_LE'Scalar_Storage_Order use System.Low_Order_First;
type Rec_BE is new Rec;
for Rec_BE'Bit_Order use System.High_Order_First;
for Rec_BE'Scalar_Storage_Order use System.High_Order_First;
V_LE : Rec_LE;
V_BE : Rec_BE;
begin
V_LE := (126, 12);
V_BE := (126, 12);
Do_Nothing (V_LE'Address); -- START
Do_Nothing (V_BE'Address);
end Storage;
|
-- Smart_Ptrs_Tests
-- Unit tests for Auto_Counters Smart_Ptrs package
-- Copyright (c) 2016, James Humphry - see LICENSE file for details
with AUnit.Assertions;
with Smart_Ptrs;
with Auto_Counters_Tests_Config;
package body Smart_Ptrs_Tests is
use AUnit.Assertions;
Resources_Released : Natural := 0;
procedure Deletion_Recorder (X : in out String) is
pragma Unreferenced (X);
begin
Resources_Released := Resources_Released + 1;
end Deletion_Recorder;
type String_Ptr is access String;
package String_Ptrs is new Smart_Ptrs(T => String,
T_Ptr => String_Ptr,
Counters => Counters,
Delete => Deletion_Recorder
);
use String_Ptrs;
--------------------
-- Register_Tests --
--------------------
procedure Register_Tests (T: in out Smart_Ptrs_Test) is
use AUnit.Test_Cases.Registration;
begin
for I of Test_Details_List loop
Register_Routine(T, I.T, To_String(I.D));
end loop;
end Register_Tests;
----------
-- Name --
----------
function Name (T : Smart_Ptrs_Test) return Test_String is
pragma Unreferenced (T);
begin
return Format ("Tests of Smart_Ptrs with " &
Counter_Type_Name);
end Name;
------------
-- Set_Up --
------------
procedure Set_Up (T : in out Smart_Ptrs_Test) is
begin
null;
end Set_Up;
---------------------
-- Check_Smart_Ptr --
---------------------
procedure Check_Smart_Ptr (T : in out Test_Cases.Test_Case'Class) is
pragma Unreferenced(T);
SP1 : Smart_Ptr := Make_Smart_Ptr(new String'("Hello, World!"));
SP2 : Smart_Ptr;
begin
Assert(Null_Smart_Ptr.Is_Null,
"Null_Smart_Ptr.Is_Null is not true");
Assert((not SP1.Is_Null and
SP1.Use_Count = 1 and
SP1.Unique and
SP1.Weak_Ptr_Count = 0),
"Initialized non-null Smart_Ptr has incorrect properties");
Assert((SP2.Is_Null and
SP2.Use_Count = 1 and
SP2.Unique and
SP2.Weak_Ptr_Count = 0),
"Initialized null Smart_Ptr has incorrect properties");
SP2 := SP1;
Assert(SP1 = SP2, "Assignment of Smart_Ptrs does not make them equal");
Assert(SP1.Use_Count = 2 and
not SP1.Unique and
SP1.Weak_Ptr_Count = 0,
"Assignment does not increase reference counts properly");
SP1.P := "World, Hello!";
Assert(SP2.P = "World, Hello!",
"Changing a value via a reference from one Smart_Ptr does not " &
"change the value accessed via an equal Smart_Ptr");
SP2.Get(6) := ':';
Assert(SP1.Get.all = "World: Hello!",
"Changing a value via an access value from one Smart_Ptr does " &
"not change the value accessed via an equal Smart_Ptr");
Resources_Released := 0;
declare
SP3 : constant Smart_Ptr := SP1;
begin
Assert(SP1 = SP3, "Creation of a Smart_Ptr in an inner block failed");
Assert(SP3.Use_Count = 3,
"Creation of a Smart_Ptr in a block fails to set counts");
end;
Assert(SP1.Use_Count = 2,
"Destruction of inner block Smart_Ptr does not reduce Use_Count");
Assert(Resources_Released = 0,
"Resources released incorrectly when 2 Smart_Ptr remain");
Resources_Released := 0;
SP2 := Null_Smart_Ptr;
Assert((SP2.Is_Null and
SP2.Use_Count = 1 and
SP2.Unique and
SP2.Weak_Ptr_Count = 0),
"Assigning null to a Smart_Ptr does not give correct properties");
Assert(Resources_Released = 0,
"Resources released incorrectly when 1 Smart_Ptr remains");
SP1 := Null_Smart_Ptr;
Assert((SP1.Is_Null and
SP1.Use_Count = 1 and
SP1.Unique and
SP1.Weak_Ptr_Count = 0),
"Assigning null to a Smart_Ptr does not give correct properties");
Assert(Resources_Released = 1,
"Resources were not released when last Smart_Ptr destroyed");
Assert(SP1 = SP2, "Null Smart_Ptrs are not equal");
end Check_Smart_Ptr;
---------------------
-- Check_Weak_Ptrs --
---------------------
procedure Check_Weak_Ptrs (T : in out Test_Cases.Test_Case'Class) is
pragma Unreferenced(T);
SP1 : Smart_Ptr := Make_Smart_Ptr(new String'("Hello, World!"));
SP2 : Smart_Ptr;
WP1 : constant Weak_Ptr := Make_Weak_Ptr(SP1);
procedure Make_WP_From_Null_SP is
WP2 : constant Weak_Ptr := Make_Weak_Ptr(SP2);
pragma Unreferenced (WP2);
begin
null;
end Make_WP_From_Null_SP;
Caught_Making_WP_From_Null_SP : Boolean := False;
Caught_Lock_On_Expired_WP : Boolean := False;
begin
Assert(SP1.Weak_Ptr_Count = 1,
"Initialized Weak_Ptr not reflected in Smart_Ptr");
Assert(WP1.Use_Count = 1,
"Weak_Ptr not reflecting the correct Use_Count");
Assert(not WP1.Expired,
"Weak_Ptr is (incorrectly) already expired just after creation");
if Auto_Counters_Tests_Config.Assertions_Enabled then
begin
Make_WP_From_Null_SP;
exception
when Smart_Ptr_Error =>
Caught_Making_WP_From_Null_SP := True;
end;
Assert(Caught_Making_WP_From_Null_SP,
"Make_Weak_ptr failed to raise exception when called on a null" &
"Smart_Ptr");
end if;
SP2 := WP1.Lock;
Assert(SP1 = SP2,
"Smart_Ptr recovered from Weak_Ptr /= original Smart_Ptr");
Assert(WP1.Use_Count = 2,
"Weak_Ptr has incorrect Use_Count after making new Smart_Ptr");
Assert(SP1.Use_Count = 2,
"Smart_Ptr made from Weak_Ptr has incorrect Use_Count");
SP2 := WP1.Lock_Or_Null;
Assert(SP1 = SP2,
"Smart_Ptr recovered from Weak_Ptr.Get /= original Smart_Ptr");
Assert(WP1.Use_Count = 2,
"Weak_Ptr has incorrect Use_Count after new Smart_Ptr via Get");
Assert(SP1.Use_Count = 2,
"Smart_Ptr made from Weak_Ptr.Get has incorrect Use_Count");
Resources_Released := 0;
SP2 := Null_Smart_Ptr;
Assert(SP1.Weak_Ptr_Count = 1,
"Weak_Ptr_Count incorrect after discarding Smart_Ptr");
Assert(WP1.Use_Count = 1,
"Weak_Ptr not reflecting the correct Use_Count");
Assert(not WP1.Expired,
"Weak_Ptr is already expired after only 1/2 Smart_Ptrs deleted");
Assert(Resources_Released = 0,
"Resources released incorrectly when 1 Smart_Ptr remains");
SP1 := Null_Smart_Ptr;
Assert(SP1.Weak_Ptr_Count = 0,
"Smart_Ptr does not have correct Weak_Ptr_Count after nulling");
Assert(Resources_Released = 1,
"Resources released incorrectly when only a Weak_Ptr remains");
Assert(WP1.Expired,
"Weak_Ptr should be expired as all Smart_Ptrs deleted");
Assert(WP1.Weak_Ptr_Count = 1,
"Weak_Ptr_Count incorrect after discarding all Smart_Ptr");
Assert(WP1.Use_Count = 0,
"Weak_Ptr not reflecting the correct Use_Count of 0");
begin
SP1 := WP1.Lock;
exception
when Smart_Ptr_Error =>
Caught_Lock_On_Expired_WP := True;
end;
Assert(Caught_Lock_On_Expired_WP,
"Weak_Ptr.Lock failed to raise exception when Lock was called " &
"on an expired Weak_Ptr");
SP1 := WP1.Lock_Or_Null;
Assert(SP1 = Null_Smart_Ptr,
"Weak_Ptr.Get failed to return a null Smart_Ptr when Get was " &
"called on an expired Weak_Ptr");
end Check_Weak_Ptrs;
-----------------
-- Check_WP_SR --
-----------------
procedure Check_WP_SR (T : in out Test_Cases.Test_Case'Class) is
pragma Unreferenced(T);
SR1 : constant Smart_Ref := Make_Smart_Ref(new String'("Hello, World!"));
WP1 : Weak_Ptr := Make_Weak_Ptr(SR1);
SP1 : Smart_Ptr;
Caught_Lock_On_Expired_WP : Boolean := False;
begin
Assert(SR1.Weak_Ptr_Count = 1,
"Initialized Weak_Ptr not reflected in Smart_Ref");
Assert(WP1.Use_Count = 1,
"Weak_Ptr not reflecting the correct Use_Count");
Assert(not WP1.Expired,
"Weak_Ptr is (incorrectly) already expired just after creation");
SP1 := WP1.Lock;
Assert(SR1 = SP1.P,
"Smart_Ptr recovered from Weak_Ptr /= original Smart_Ref");
Assert(WP1.Use_Count = 2,
"Weak_Ptr has incorrect Use_Count after making new Smart_Ptr");
Assert(SP1.Use_Count = 2,
"Smart_Ptr made from Weak_Ptr has incorrect Use_Count");
Resources_Released := 0;
declare
SR2 : constant Smart_Ref := WP1.Lock;
begin
Assert(SR2 = String'(SR1),
"Smart_Ref recovered from Weak_Ptr /= original Smart_Ref");
Assert(SR2.Use_Count = 3,
"Smart_Ref recovered from Weak_Ptr not adjusting Use_Count");
end;
Assert(Resources_Released = 0,
"Recovering and destroying Smart_Ref from Weak_Ptr has released " &
"resources despite remaining Smart_Ref and Smart_Ptr");
Assert(SR1.Use_Count = 2,
"Recovering and destroying Smart_Ref from Weak_Ptr has resulted " &
"in incorrect Use_Count on remaining Smart_Ref ");
Resources_Released := 0;
declare
SR3 : constant Smart_Ref
:= Make_Smart_Ref(new String'("Goodbye, World!"));
begin
WP1 := SR3.Make_Weak_Ptr;
end;
Assert(Resources_Released = 1,
"Creation of Weak_Ptr from Smart_Ref prevented resources from " &
"being released.");
Assert(WP1.Expired,
"Weak_Ptr not expired when source Smart_Ref is destroyed");
Assert(WP1.Use_Count = 0,
"Expired Weak_Ptr has incorrect Use_Count");
begin
declare
SR4 : constant Smart_Ref := WP1.Lock;
pragma Unreferenced (SR4);
begin
null;
end;
exception
when Smart_Ptr_Error =>
Caught_Lock_On_Expired_WP := True;
end;
Assert(Caught_Lock_On_Expired_WP,
"Weak_Ptr.Lock failed to raise exception when Lock was called " &
"on an expired Weak_Ptr");
end Check_WP_SR;
---------------------
-- Check_Smart_Ref --
---------------------
procedure Check_Smart_Ref (T : in out Test_Cases.Test_Case'Class) is
pragma Unreferenced(T);
SR1 : constant Smart_Ref := Make_Smart_Ref(new String'("Hello, World!"));
procedure Make_SR_from_Local is
S : aliased String := "Test";
SR : Smart_Ref(Element => S'Access);
pragma Unreferenced (SR);
begin
null;
end Make_SR_from_Local;
procedure Make_SR_from_null is
SR : Smart_Ref := Make_Smart_Ref(null);
pragma Unreferenced (SR);
begin
null;
end Make_SR_from_null;
Caught_Make_SR_from_Local : Boolean := False;
Caught_Make_SR_from_Null : Boolean := False;
begin
Assert((SR1.Use_Count = 1 and
SR1.Unique and
SR1.Weak_Ptr_Count = 0),
"Initialized Smart_Ref has incorrect properties");
Resources_Released := 0;
declare
SR2 : constant Smart_Ref := SR1;
begin
Assert(SR1.Element = SR2.Element,
"Assignment of Smart_Ref does not make them equal");
Assert(SR1.Use_Count = 2 and
not SR1.Unique and
SR1.Weak_Ptr_Count = 0,
"Assignment does not increase reference counts properly");
SR1 := "World, Hello!";
Assert(SR2 = "World, Hello!",
"Changing a value via a reference from one Smart_Ref does " &
"not change the value accessed via an equal Smart_Ref");
SR2.Get(6) := ':';
Assert(SR1.Get.all = "World: Hello!",
"Changing a value via an access value from one Smart_Ref " &
"does not change the value accessed via an equal Smart_Ref");
end;
Assert(SR1.Use_Count = 1,
"Destruction of inner block Smart_Ref does not reduce Use_Count");
Assert(Resources_Released = 0,
"Resources released incorrectly when 1 Smart_Ref remains");
Resources_Released := 0;
declare
SR3 : constant Smart_Ref := Make_Smart_Ref(new String'("Goodbye, World!"));
begin
Assert(SR3 = "Goodbye, World!", "Create of Smart_Ref not working");
end;
Assert(Resources_Released = 1,
"Resources not released when no Smart_Ref remain");
begin
Make_SR_from_Local;
exception
when Smart_Ptr_Error =>
Caught_Make_SR_from_Local := True;
end;
Assert(Caught_Make_SR_from_Local,
"Failed to identify Smart_Ref being set to a local");
if Auto_Counters_Tests_Config.Assertions_Enabled then
begin
Make_SR_from_null;
exception
when Smart_Ptr_Error =>
Caught_Make_SR_from_Null := True;
end;
Assert(Caught_Make_SR_from_Null,
"Failed to identify Smart_Ref being made from a null");
end if;
end Check_Smart_Ref;
-----------------
-- Check_SP_SR --
-----------------
procedure Check_SP_SR (T : in out Test_Cases.Test_Case'Class) is
pragma Unreferenced(T);
SR1 : constant Smart_Ref := Make_Smart_Ref(new String'("Smart_Ref"));
SP1 : constant Smart_Ptr := Make_Smart_Ptr(SR1);
SP2 : constant Smart_Ptr := Make_Smart_Ptr(new String'("Smart_Ptr"));
procedure Make_SR_from_null_SP is
SP : Smart_Ptr;
SR : Smart_Ref := Make_Smart_Ref(SP);
pragma Unreferenced (SR);
begin
null;
end Make_SR_from_null_SP;
Caught_Make_SR_from_Null_SP : Boolean := False;
begin
Assert(SR1 = SP1.P,
"Smart_Ptr and Smart_Ref do not have same contents after " &
"assignment");
Assert(SR1 = SP1.Get.all,
"Smart_Ptr and Smart_Ref do not have same contents after " &
"assignment (using Smart_Ptr.Get.all)");
Assert(SR1.Use_Count = 2 and SP1.Use_Count = 2,
"Smart_Ptr and Smart_Ref do not have correct Use_Count");
Resources_Released := 0;
declare
SR2 : constant Smart_Ref := Make_Smart_Ref(SP2);
begin
Assert(SR2.Use_Count = 2 and SP2.Use_Count = 2,
"Smart_Ptr and Smart_Ref do not have correct Use_Count");
end;
Assert(Resources_Released = 0,
"Destruction of Smart_Ref released storage despite remaining "&
"Smart_Ptr");
Assert(SP2.Use_Count = 1,
"Smart_Ptr does not have correct Use_Count after creation and" &
"destruction of a Smart_Ref linked to it");
if Auto_Counters_Tests_Config.Assertions_Enabled then
begin
Make_SR_from_null_SP;
exception
when Smart_Ptr_Error =>
Caught_Make_SR_from_Null_SP := True;
end;
Assert(Caught_Make_SR_from_Null_SP,
"Failed to identify Smart_Ref being made from a null Smart_Ptr");
end if;
end Check_SP_SR;
end Smart_Ptrs_Tests;
|
with Ada.Text_IO; use Ada.Text_IO;
with Increment_By;
procedure Show_Increment is
A, B, C : Integer;
begin
C := Increment_By;
-- ^ Parameterless call, value of I is 0
-- and Incr is 1
Put_Line ("Using defaults for Increment_By is " & Integer'Image (C));
A := 10;
B := 3;
C := Increment_by (A, B);
-- Regular parameter passing
Put_Line ("Increment of " & Integer'Image (A)
& " with " & Integer'Image (B)
& " is " & Integer'Image (C));
A := 20;
B := 5;
C := Increment_By (I => A,
Incr => B);
-- ^ Named parmeter passing
Put_Line ("Increment of " & Integer'Image (A)
& " with " & Integer'Image (B)
& " is " & Integer'Image (C));
end Show_Increment; |
pragma Ada_2005;
pragma Style_Checks (Off);
with Interfaces.C; use Interfaces.C;
with SDL_stdinc_h;
package SDL_cpuinfo_h is
SDL_CACHELINE_SIZE : constant := 128; -- ..\SDL2_tmp\SDL_cpuinfo.h:95
-- Simple DirectMedia Layer
-- Copyright (C) 1997-2018 Sam Lantinga <slouken@libsdl.org>
-- This software is provided 'as-is', without any express or implied
-- warranty. In no event will the authors be held liable for any damages
-- arising from the use of this software.
-- Permission is granted to anyone to use this software for any purpose,
-- including commercial applications, and to alter it and redistribute it
-- freely, subject to the following restrictions:
-- 1. The origin of this software must not be misrepresented; you must not
-- claim that you wrote the original software. If you use this software
-- in a product, an acknowledgment in the product documentation would be
-- appreciated but is not required.
-- 2. Altered source versions must be plainly marked as such, and must not be
-- misrepresented as being the original software.
-- 3. This notice may not be removed or altered from any source distribution.
--
--*
-- * \file SDL_cpuinfo.h
-- *
-- * CPU feature detection for SDL.
--
-- Need to do this here because intrin.h has C++ code in it
-- Visual Studio 2005 has a bug where intrin.h conflicts with winnt.h
-- Many of the intrinsics SDL uses are not implemented by clang with Visual Studio
-- Set up for C function definitions, even when using C++
-- This is a guess for the cacheline size used for padding.
-- * Most x86 processors have a 64 byte cache line.
-- * The 64-bit PowerPC processors have a 128 byte cache line.
-- * We'll use the larger value to be generally safe.
--
--*
-- * This function returns the number of CPU cores available.
--
function SDL_GetCPUCount return int; -- ..\SDL2_tmp\SDL_cpuinfo.h:100
pragma Import (C, SDL_GetCPUCount, "SDL_GetCPUCount");
--*
-- * This function returns the L1 cache line size of the CPU
-- *
-- * This is useful for determining multi-threaded structure padding
-- * or SIMD prefetch sizes.
--
function SDL_GetCPUCacheLineSize return int; -- ..\SDL2_tmp\SDL_cpuinfo.h:108
pragma Import (C, SDL_GetCPUCacheLineSize, "SDL_GetCPUCacheLineSize");
--*
-- * This function returns true if the CPU has the RDTSC instruction.
--
function SDL_HasRDTSC return SDL_stdinc_h.SDL_bool; -- ..\SDL2_tmp\SDL_cpuinfo.h:113
pragma Import (C, SDL_HasRDTSC, "SDL_HasRDTSC");
--*
-- * This function returns true if the CPU has AltiVec features.
--
function SDL_HasAltiVec return SDL_stdinc_h.SDL_bool; -- ..\SDL2_tmp\SDL_cpuinfo.h:118
pragma Import (C, SDL_HasAltiVec, "SDL_HasAltiVec");
--*
-- * This function returns true if the CPU has MMX features.
--
function SDL_HasMMX return SDL_stdinc_h.SDL_bool; -- ..\SDL2_tmp\SDL_cpuinfo.h:123
pragma Import (C, SDL_HasMMX, "SDL_HasMMX");
--*
-- * This function returns true if the CPU has 3DNow! features.
--
function SDL_Has3DNow return SDL_stdinc_h.SDL_bool; -- ..\SDL2_tmp\SDL_cpuinfo.h:128
pragma Import (C, SDL_Has3DNow, "SDL_Has3DNow");
--*
-- * This function returns true if the CPU has SSE features.
--
function SDL_HasSSE return SDL_stdinc_h.SDL_bool; -- ..\SDL2_tmp\SDL_cpuinfo.h:133
pragma Import (C, SDL_HasSSE, "SDL_HasSSE");
--*
-- * This function returns true if the CPU has SSE2 features.
--
function SDL_HasSSE2 return SDL_stdinc_h.SDL_bool; -- ..\SDL2_tmp\SDL_cpuinfo.h:138
pragma Import (C, SDL_HasSSE2, "SDL_HasSSE2");
--*
-- * This function returns true if the CPU has SSE3 features.
--
function SDL_HasSSE3 return SDL_stdinc_h.SDL_bool; -- ..\SDL2_tmp\SDL_cpuinfo.h:143
pragma Import (C, SDL_HasSSE3, "SDL_HasSSE3");
--*
-- * This function returns true if the CPU has SSE4.1 features.
--
function SDL_HasSSE41 return SDL_stdinc_h.SDL_bool; -- ..\SDL2_tmp\SDL_cpuinfo.h:148
pragma Import (C, SDL_HasSSE41, "SDL_HasSSE41");
--*
-- * This function returns true if the CPU has SSE4.2 features.
--
function SDL_HasSSE42 return SDL_stdinc_h.SDL_bool; -- ..\SDL2_tmp\SDL_cpuinfo.h:153
pragma Import (C, SDL_HasSSE42, "SDL_HasSSE42");
--*
-- * This function returns true if the CPU has AVX features.
--
function SDL_HasAVX return SDL_stdinc_h.SDL_bool; -- ..\SDL2_tmp\SDL_cpuinfo.h:158
pragma Import (C, SDL_HasAVX, "SDL_HasAVX");
--*
-- * This function returns true if the CPU has AVX2 features.
--
function SDL_HasAVX2 return SDL_stdinc_h.SDL_bool; -- ..\SDL2_tmp\SDL_cpuinfo.h:163
pragma Import (C, SDL_HasAVX2, "SDL_HasAVX2");
--*
-- * This function returns true if the CPU has AVX-512F (foundation) features.
--
function SDL_HasAVX512F return SDL_stdinc_h.SDL_bool; -- ..\SDL2_tmp\SDL_cpuinfo.h:168
pragma Import (C, SDL_HasAVX512F, "SDL_HasAVX512F");
--*
-- * This function returns true if the CPU has NEON (ARM SIMD) features.
--
function SDL_HasNEON return SDL_stdinc_h.SDL_bool; -- ..\SDL2_tmp\SDL_cpuinfo.h:173
pragma Import (C, SDL_HasNEON, "SDL_HasNEON");
--*
-- * This function returns the amount of RAM configured in the system, in MB.
--
function SDL_GetSystemRAM return int; -- ..\SDL2_tmp\SDL_cpuinfo.h:178
pragma Import (C, SDL_GetSystemRAM, "SDL_GetSystemRAM");
-- Ends C function definitions when using C++
-- vi: set ts=4 sw=4 expandtab:
end SDL_cpuinfo_h;
|
With
Risi_Script.Interfaces,
Ada.Containers.Indefinite_Vectors;
Package Risi_Script.Parameter_Stack is
Package Interfaces renames Risi_Script.Types.Interfaces;
Package Implementation is new Ada.Containers.Indefinite_Vectors(
"=" => Risi_Script.Types."=",
Index_Type => positive,
Element_Type => Risi_Script.Types.Representation
);
Type Vector is new Implementation.Vector and Interfaces.Stack_Interface
with null record;
End Risi_Script.Parameter_Stack;
|
with Imago; with Imago.IL;
use Imago;
with WFC;
with GNAT.Command_Line;
use GNAT.Command_Line;
package Util is
Argument_Error : exception;
Execution_Error : exception;
type Image_Color is (R, G, B);
type Image_Pixel is
array (Image_Color) of IL.UByte
with Pack;
type Image_Matrix is
array (Natural range <>, Natural range <>) of Image_Pixel
with Pack;
package Image_WFC is new WFC(Image_Pixel, Image_Matrix);
-- The generic instantiation we will use
-- when provided an image at the command line.
type Character_Matrix is
array (Natural range <>, Natural range <>) of Character;
package Character_WFC is new WFC(Character, Character_Matrix);
-- The generic instantiation we will use
-- when instead provided a simple text file.
procedure Define_CLI_Switches (Config : in out Command_Line_Configuration);
procedure Process_Command_Arguments;
end; |
with Ada.Text_IO;
with GNAT.Sockets;
with Interfaces;
with Interfaces.C;
with Kafka;
with Kafka.Config;
with Kafka.Consumer;
with Kafka.Message;
with Kafka.Topic;
with Kafka.Topic.Partition;
with Signal;
with System;
--
-- Basic Kafka consumer
--
procedure Simple_Consumer is
use type System.Address;
use type Interfaces.C.size_t;
Config : Kafka.Config_Type;
Handle : Kafka.Handle_Type;
Handler : Signal.Handler; -- basic Signal handler to stop on CTRL + C
begin
-- Create configuration
Config := Kafka.Config.Create;
-- Configure
-- see librdkafka documentation on how to configure your Kafka consumer
-- Kafka-Ada does not add any configuration entries of its own
Kafka.Config.Set(Config, "group.id", GNAT.Sockets.Host_name);
Kafka.Config.Set(Config, "bootstrap.servers", "localhost:9092");
Kafka.Config.Set(Config, "auto.offset.reset", "earliest");
Handle := Kafka.Create_Handle(Kafka.RD_KAFKA_CONSUMER, Config);
Kafka.Consumer.Poll_Set_Consumer(Handle);
declare
Partition_List : Kafka.Partition_List_Type;
begin
Partition_List := Kafka.Topic.Partition.Create_List(1);
Kafka.Topic.Partition.List_Add(Partition_List, "test_topic", Kafka.RD_KAFKA_PARTITION_UA);
Kafka.Subscribe(Handle, Partition_List);
Kafka.Topic.Partition.Destroy_List(Partition_List);
end;
while not Handler.Triggered loop
declare
Message : access Kafka.Message_Type;
begin
Message := Kafka.Consumer.Poll(Handle, Duration(0.1)); -- 100ms
if Message = null then
goto Continue;
end if;
if Message.Error /= 0 then
Ada.Text_IO.Put_Line("Consumer error: " & Kafka.Message.Get_Error(Message));
Kafka.Message.Destroy(Message);
goto Continue;
end if;
Ada.Text_IO.Put_Line("A message was received");
Ada.Text_IO.Put_Line("Topic: " & Kafka.Topic.Get_Name(Message.Topic));
if Message.Key /= System.Null_Address and Message.Key_Length > 0 then
declare
Key : aliased String(1 .. Integer(Message.Key_Length));
for Key'Address use Message.Key;
begin
Ada.Text_IO.Put_Line("Key:");
Ada.Text_IO.Put_Line(Key);
end;
else
Ada.Text_IO.Put_Line("Key is null");
end if;
if Message.Payload /= System.Null_Address and Message.Payload_Length > 0 then
declare
Payload : aliased String(1 .. Integer(Message.Payload_Length));
for Payload'Address use Message.Payload;
begin
Ada.Text_IO.Put_Line("Payload:");
Ada.Text_IO.Put_Line(Payload);
end;
else
Ada.Text_IO.Put_Line("Payload is null");
end if;
Kafka.Message.Destroy(Message);
end;
<<Continue>>
end loop;
Kafka.Consumer.Close(Handle);
Kafka.Destroy_Handle(Handle);
end Simple_Consumer; |
with Types; use Types;
with Communication; use Communication;
package Algorithm is
type Algorithm_Type is
(Pong);
Safety_Exception : exception;
Default_Velocity : Velocity := 320;
type Abstract_Algorithm is abstract tagged record
null;
end record;
type Algorithm_Ptr is access Abstract_Algorithm'Class;
procedure Process (Self : in out Abstract_Algorithm;
Port : in Serial_Port;
Sensors : in Sensor_Collection) is abstract;
procedure Safety_Check (Self : in Abstract_Algorithm;
Sensors : in Sensor_Collection) is abstract;
type Algorithm_State is
(Drive,
Passive_Driving,
Collision,
Recover,
Passive_Recover);
type Pong_Algorithm is new Abstract_Algorithm with record
State : Algorithm_State := Drive;
Collision : Boolean := False;
Reported_Angle : Radius;
Last_Turn : Boolean := False;
end record;
procedure Process (Self : in out Pong_Algorithm;
Port : in Serial_Port;
Sensors : in Sensor_Collection);
function Detect_Collision (Self : in Pong_Algorithm;
Sensors : in Sensor_Collection)
return Boolean;
procedure Safety_Check (Self : in Pong_Algorithm;
Sensors : in Sensor_Collection);
end Algorithm;
|
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Buffer_Package; use Buffer_Package;
with Utilities_Package; use Utilities_Package;
package Editor_Package is
type KEYSTROKE is record
O : ERR_TYPE;
C : Character;
end record;
type Editor is record
Name : Unbounded_String;
Doc : Integer;
Cmd : Integer;
Doc_View : View;
Focus_View : View;
Running : Boolean;
Error: Unbounded_String;
end record;
function Open_Editor
(Name : Unbounded_String; Doc : Integer; Cmd : Integer) return Editor;
procedure Load_File (File_Name : Unbounded_String; E : in out Editor);
procedure Run_Startup (Name : String);
procedure Run_Startup_Files (File_Name : Unbounded_String);
procedure Run (E : Editor);
procedure Status_Callback (E : Editor; V : View);
procedure Redisplay (V : View);
procedure Fix_Loc (E : Editor);
function Get_Key_Stroke (E : Editor; D : Boolean) return KEYSTROKE;
procedure Dispatch (E : Editor; F : View; K : KEYSTROKE);
end Editor_Package;
|
private package GID.Decoding_GIF is
--------------------
-- Image decoding --
--------------------
generic
type Primary_color_range is mod <>;
with procedure Set_X_Y (x, y: Natural);
with procedure Put_Pixel (
red, green, blue : Primary_color_range;
alpha : Primary_color_range
);
with procedure Feedback (percents: Natural);
mode: Display_mode;
--
procedure Load (
image : in out Image_descriptor;
next_frame: out Ada.Calendar.Day_Duration
);
end GID.Decoding_GIF;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.