content stringlengths 23 1.05M |
|---|
with Ada.Text_IO; use Ada.Text_IO;
procedure Power is
procedure PrintInt(N: Integer) is
C: Integer := N rem 10;
begin
if N > 9 then PrintInt(N / 10); end if;
Put(Character'Val(48 + C));
end;
procedure PrintSInt(N: Integer) is
C: Integer := N rem 10;
begin
if N >= 0 then Printint(N); return; end if;
Put('-');
if N < -9 then Printint(- N / 10); end if;
Put(Character'Val(48 - C));
end;
function Power(X, N: Integer) return Integer is
P: Integer;
begin
if N = 0 then return 1; end if;
P := Power(X, N / 2);
P := P * P;
if N rem 2 = 1 then P := X * P; end if;
return P;
end;
begin
PrintSInt(Power(2, 0)); New_Line;
PrintSInt(Power(2, 8)); New_Line;
PrintsInt(Power(2, 30)); New_Line;
PrintsInt(Power(2, 31)); New_Line;
end;
-- Local Variables:
-- compile-command: "gnatmake power.adb && ./power"
-- End:
|
-----------------------------------------------------------------------
-- applications -- Ada Web Application
-- Copyright (C) 2009, 2010, 2013, 2015, 2020 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Strings;
with Util.Properties;
package ASF.Applications is
use Util.Properties;
type Config is new Util.Properties.Manager with private;
type Config_Param is private;
-- Directory where the facelet files are stored.
VIEW_DIR_PARAM : constant Config_Param;
VIEW_DIR : aliased constant String := "view.dir";
DEF_VIEW_DIR : aliased constant String := "web";
-- Extension used by requests
VIEW_EXT_PARAM : constant Config_Param;
VIEW_EXT : aliased constant String := "view.ext";
DEF_VIEW_EXT : aliased constant String := "";
-- Extension used by facelet files
VIEW_FILE_EXT_PARAM : constant Config_Param;
VIEW_FILE_EXT : aliased constant String := "view.file_ext";
DEF_VIEW_FILE_EXT : aliased constant String := ".xhtml";
-- Whether white spaces in XHTML files are ignored.
VIEW_IGNORE_WHITE_SPACES_PARAM : constant Config_Param;
VIEW_IGNORE_WHITE_SPACES : aliased constant String := "view.ignore_white_spaces";
DEF_IGNORE_WHITE_SPACES : aliased constant String := "false";
-- Whether empty lines in XHTML files are ignored.
VIEW_IGNORE_EMPTY_LINES_PARAM : constant Config_Param;
VIEW_IGNORE_EMPTY_LINES : aliased constant String := "view.ignore_empty_lines";
DEF_IGNORE_EMPTY_LINES : aliased constant String := "false";
-- Whether the unknown tags are escaped in the output
VIEW_ESCAPE_UNKNOWN_TAGS_PARAM : constant Config_Param;
VIEW_ESCAPE_UNKNOWN_TAGS : aliased constant String := "view.escape_unknown_tags";
DEF_ESCAPE_UNKNOWN_TAGS : aliased constant String := "false";
-- Extensions used by static pages
VIEW_STATIC_EXT_PARAM : constant Config_Param;
VIEW_STATIC_EXT : aliased constant String := "view.static.ext";
DEF_STATIC_EXT : aliased constant String := "";
-- Directories which contain static pages
VIEW_STATIC_DIR_PARAM : constant Config_Param;
VIEW_STATIC_DIR : aliased constant String := "view.static.dir";
DEF_STATIC_DIR : aliased constant String := "css,js,scripts,themes";
-- The 404 error page to render
ERROR_404_PARAM : constant Config_Param;
ERROR_404_PAGE : aliased constant String := "view.error.404";
DEF_ERROR_404 : aliased constant String := "errors/404";
-- The 500 error page to render
ERROR_500_PARAM : constant Config_Param;
ERROR_500_PAGE : aliased constant String := "view.error.500";
DEF_ERROR_500 : aliased constant String := "errors/500";
-- Get the configuration parameter;
function Get (Self : Config;
Param : Config_Param) return String;
-- Get the configuration parameter;
function Get (Self : Config;
Param : Config_Param) return Ada.Strings.Unbounded.Unbounded_String;
-- Get the configuration parameter;
function Get (Self : Config;
Param : Config_Param) return Boolean;
function Get (Self : Config;
Param : Config_Param) return Integer;
-- Create the configuration parameter definition instance.
generic
-- The parameter name.
Name : in String;
-- The default value.
Default : in String;
package Parameter is
-- Returns the configuration parameter.
function P return Config_Param;
pragma Inline_Always (P);
PARAM_NAME : aliased constant String := Name;
PARAM_VALUE : aliased constant String := Default;
end Parameter;
private
type Config_Param is record
Name : Util.Strings.Name_Access;
Default : Util.Strings.Name_Access;
end record;
subtype P is Config_Param;
VIEW_DIR_PARAM : constant Config_Param := P '(Name => VIEW_DIR'Access,
Default => DEF_VIEW_DIR'Access);
VIEW_EXT_PARAM : constant Config_Param := P '(Name => VIEW_EXT'Access,
Default => DEF_VIEW_EXT'Access);
VIEW_FILE_EXT_PARAM : constant Config_Param := P '(Name => VIEW_FILE_EXT'Access,
Default => DEF_VIEW_FILE_EXT'Access);
VIEW_IGNORE_WHITE_SPACES_PARAM : constant Config_Param
:= P '(Name => VIEW_IGNORE_WHITE_SPACES'Access,
Default => DEF_IGNORE_WHITE_SPACES'Access);
VIEW_IGNORE_EMPTY_LINES_PARAM : constant Config_Param
:= P '(Name => VIEW_IGNORE_EMPTY_LINES'Access,
Default => DEF_IGNORE_EMPTY_LINES'Access);
VIEW_ESCAPE_UNKNOWN_TAGS_PARAM : constant Config_Param
:= P '(Name => VIEW_ESCAPE_UNKNOWN_TAGS'Access,
Default => DEF_ESCAPE_UNKNOWN_TAGS'Access);
VIEW_STATIC_EXT_PARAM : constant Config_Param := P '(Name => VIEW_STATIC_EXT'Access,
Default => DEF_STATIC_EXT'Access);
VIEW_STATIC_DIR_PARAM : constant Config_Param := P '(Name => VIEW_STATIC_DIR'Access,
Default => DEF_STATIC_DIR'Access);
ERROR_404_PARAM : constant Config_Param := P '(Name => ERROR_404_PAGE'Access,
Default => DEF_ERROR_404'Access);
ERROR_500_PARAM : constant Config_Param := P '(Name => ERROR_500_PAGE'Access,
Default => DEF_ERROR_500'Access);
type Config is new Util.Properties.Manager with null record;
end ASF.Applications;
|
with AUnit;
with AUnit.Test_Fixtures;
package UA_Append_Tests is
type Test_Fixture is new AUnit.Test_Fixtures.Test_Fixture with record
V1 : Integer;
V2 : Integer;
V3 : Integer;
V4 : Integer;
end record;
procedure Set_Up (T : in out Test_Fixture);
procedure TestAppend_WithEnoughCapacity_ResultAppended(T : in out Test_Fixture);
procedure TestAppend_WithSmallCapacity_ResultAppended(T : in out Test_Fixture);
procedure TestAppend_WithIndexEndReached_ResultNotAppended(T : in out Test_Fixture);
end UA_Append_Tests;
|
-----------------------------------------------------------------------
-- auth_cb -- Authentication callback examples
-- Copyright (C) 2013, 2020 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Fixed;
with AWS.Session;
with AWS.Messages;
with AWS.Templates;
with AWS.Services.Web_Block.Registry;
with Util.Log.Loggers;
package body Auth_CB is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Auth_CB");
-- Name of the session attribute which holds information about the active authentication.
OPENID_ASSOC_ATTRIBUTE : constant String := "openid-assoc";
USER_INFO_ATTRIBUTE : constant String := "user-info";
Null_Association : Security.Auth.Association;
Null_Auth : Security.Auth.Authentication;
package Auth_Session is
new AWS.Session.Generic_Data (Security.Auth.Association, Null_Association);
package User_Session is
new AWS.Session.Generic_Data (Security.Auth.Authentication, Null_Auth);
function Get_Auth_Name (Request : in AWS.Status.Data) return String;
overriding
function Get_Parameter (Params : in Auth_Config;
Name : in String) return String is
begin
if Params.Exists (Name) then
return Params.Get (Name);
else
return "";
end if;
end Get_Parameter;
function Get_Auth_Name (Request : in AWS.Status.Data) return String is
URI : constant String := AWS.Status.URI (Request);
Pos : constant Natural := Ada.Strings.Fixed.Index (URI, "/", Ada.Strings.Backward);
begin
if Pos = 0 then
return "";
else
Log.Info ("OpenID authentication with {0}", URI);
return URI (Pos + 1 .. URI'Last);
end if;
end Get_Auth_Name;
-- ------------------------------
-- Implement the first step of authentication: discover the OpenID (if any) provider,
-- create the authorization request and redirect the user to the authorization server.
-- Some authorization data is saved in the session for the verify process.
-- ------------------------------
function Get_Authorization (Request : in AWS.Status.Data) return AWS.Response.Data is
Name : constant String := Get_Auth_Name (Request);
URL : constant String := Config.Get_Parameter ("auth.url." & Name);
Mgr : Security.Auth.Manager;
OP : Security.Auth.End_Point;
Assoc : Security.Auth.Association;
begin
if URL'Length = 0 or Name'Length = 0 then
return AWS.Response.URL (Location => "/login.html");
end if;
Mgr.Initialize (Config, Name);
-- Yadis discovery (get the XRDS file). This step does nothing for OAuth.
Mgr.Discover (URL, OP);
-- Associate to the OpenID provider and get an end-point with a key.
Mgr.Associate (OP, Assoc);
-- Save the association in the HTTP session and
-- redirect the user to the OpenID provider.
declare
Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc);
SID : constant AWS.Session.Id := AWS.Status.Session (Request);
begin
Log.Info ("Redirect to auth URL: {0}", Auth_URL);
Auth_Session.Set (SID, OPENID_ASSOC_ATTRIBUTE, Assoc);
return AWS.Response.URL (Location => Auth_URL);
end;
end Get_Authorization;
-- ------------------------------
-- Second step of authentication: verify the authorization response. The authorization
-- data saved in the session is extracted and checked against the response. If it matches
-- the response is verified to check if the authentication succeeded or not.
-- The user is then redirected to the success page.
-- ------------------------------
function Verify_Authorization (Request : in AWS.Status.Data) return AWS.Response.Data is
use type Security.Auth.Auth_Result;
-- Give access to the request parameters.
type Auth_Params is limited new Security.Auth.Parameters with null record;
overriding
function Get_Parameter (Params : in Auth_Params;
Name : in String) return String;
overriding
function Get_Parameter (Params : in Auth_Params;
Name : in String) return String is
pragma Unreferenced (Params);
begin
return AWS.Status.Parameter (Request, Name);
end Get_Parameter;
Mgr : Security.Auth.Manager;
Assoc : Security.Auth.Association;
Credential : Security.Auth.Authentication;
Params : Auth_Params;
SID : constant AWS.Session.Id := AWS.Status.Session (Request);
begin
Log.Info ("Verify openid authentication");
if not AWS.Session.Exist (SID, OPENID_ASSOC_ATTRIBUTE) then
Log.Warn ("Session has expired during OpenID authentication process");
return AWS.Response.Build ("text/html", "Session has expired", AWS.Messages.S403);
end if;
Assoc := Auth_Session.Get (SID, OPENID_ASSOC_ATTRIBUTE);
-- Cleanup the session and drop the association end point.
AWS.Session.Remove (SID, OPENID_ASSOC_ATTRIBUTE);
Mgr.Initialize (Name => Security.Auth.Get_Provider (Assoc),
Params => Config);
-- Verify that what we receive through the callback matches the association key.
Mgr.Verify (Assoc, Params, Credential);
if Security.Auth.Get_Status (Credential) /= Security.Auth.AUTHENTICATED then
Log.Info ("Authentication has failed");
return AWS.Response.Build ("text/html", "Authentication failed", AWS.Messages.S403);
end if;
Log.Info ("Authentication succeeded for {0}", Security.Auth.Get_Email (Credential));
Log.Info ("Claimed id: {0}", Security.Auth.Get_Claimed_Id (Credential));
Log.Info ("Email: {0}", Security.Auth.Get_Email (Credential));
Log.Info ("Name: {0}", Security.Auth.Get_Full_Name (Credential));
-- Save the user information in the session (for the purpose of this demo).
User_Session.Set (SID, USER_INFO_ATTRIBUTE, Credential);
declare
URL : constant String := Config.Get_Parameter ("openid.success_url");
begin
Log.Info ("Redirect user to success URL: {0}", URL);
return AWS.Response.URL (Location => URL);
end;
end Verify_Authorization;
function User_Info (Request : in AWS.Status.Data) return AWS.Response.Data is
SID : constant AWS.Session.Id := AWS.Status.Session (Request);
Credential : Security.Auth.Authentication;
Set : AWS.Templates.Translate_Set;
begin
if AWS.Session.Exist (SID, USER_INFO_ATTRIBUTE) then
Credential := User_Session.Get (SID, USER_INFO_ATTRIBUTE);
AWS.Templates.Insert (Set,
AWS.Templates.Assoc ("ID",
Security.Auth.Get_Claimed_Id (Credential)));
AWS.Templates.Insert (Set, AWS.Templates.Assoc ("EMAIL",
Security.Auth.Get_Email (Credential)));
AWS.Templates.Insert (Set, AWS.Templates.Assoc ("NAME",
Security.Auth.Get_Full_Name (Credential)));
end if;
return AWS.Services.Web_Block.Registry.Build ("success", Request, Set);
end User_Info;
end Auth_CB;
|
--------------------------------------------------------------------------------
-- Copyright (C) 2020 by Heisenbug Ltd. (gh+si_units@heisenbug.eu)
--
-- This work is free. You can redistribute it and/or modify it under the
-- terms of the Do What The Fuck You Want To Public License, Version 2,
-- as published by Sam Hocevar. See the LICENSE file for more details.
--------------------------------------------------------------------------------
pragma License (Unrestricted);
with Ada.Text_IO;
--------------------------------------------------------------------------------
-- SI_Units, internal support package.
--
-- To ease implementation and avoid duplicating code, most generic subprograms
-- implementing value/string conversion for different types will work by first
-- converting the input value into a floating point value and then call a
-- common subprogram to do the actual conversion.
--------------------------------------------------------------------------------
private package SI_Units.Float_IO is
type General_Float is new Standard.Long_Long_Float;
-- General_Float can be replaced by any other float type. For now, we use
-- Long_Long_Float which is standard Ada and should have a sufficient
-- precision for all practical purposes.
package General_Float_IO is new Ada.Text_IO.Float_IO (Num => General_Float);
-- Instantiate the appropriate IO package for the type.
end SI_Units.Float_IO;
|
package Termbox is
procedure Tb_Init; -- initialization
pragma Import (C, Tb_Init, "tb_init");
procedure Tb_Shutdown; -- shutdown
pragma Import (C, Tb_Shutdown, "tb_shutdown");
procedure TB_Width; -- width of the terminal screen
pragma Import (C, TB_Width, "tb_width");
procedure TB_Height; -- height of the terminal screen
pragma Import (C, TB_Height, "tb_height");
procedure TB_Clear; -- clear buffer
pragma Import (C, TB_Clear, "tb_clear");
procedure TB_Present; -- sync internal buffer with terminal
pragma Import (C, TB_Present, "tb_present");
procedure TB_Put_Cell;
pragma Import (C, TB_Put_Cell, "tb_put_cell");
procedure TB_Change_Cell;
pragma Import (C, TB_Change_Cell, "tb_change_cell");
procedure TB_Blit; -- drawing functions
pragma Import (C, TB_Blit, "tb_blit");
procedure TB_Select_Input_Mode; -- change input mode
pragma Import (C, TB_Select_Input_Mode, "tb_select_input_mode");
procedure TB_Peek_Event; -- peek a keyboard event
pragma Import (C, TB_Peek_Event, "tb_peek_event");
procedure TB_Poll_Event; -- wait for a keyboard event
pragma Import (C, TB_Poll_Event, "tb_poll_event");
end Termbox;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- A D A . W I D E _ C H A R A C T E R S . U N I C O D E --
-- --
-- S p e c --
-- --
-- Copyright (C) 2005-2019, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- Unicode categorization routines for Wide_Character. Note that this
-- package is strictly speaking Ada 2005 (since it is a child of an
-- Ada 2005 unit), but we make it available in Ada 95 mode, since it
-- only deals with wide characters.
with System.UTF_32;
package Ada.Wide_Characters.Unicode is
pragma Pure;
-- The following type defines the categories from the unicode definitions.
-- The one addition we make is Fe, which represents the characters FFFE
-- and FFFF in any of the planes.
type Category is new System.UTF_32.Category;
-- Cc Other, Control
-- Cf Other, Format
-- Cn Other, Not Assigned
-- Co Other, Private Use
-- Cs Other, Surrogate
-- Ll Letter, Lowercase
-- Lm Letter, Modifier
-- Lo Letter, Other
-- Lt Letter, Titlecase
-- Lu Letter, Uppercase
-- Mc Mark, Spacing Combining
-- Me Mark, Enclosing
-- Mn Mark, Nonspacing
-- Nd Number, Decimal Digit
-- Nl Number, Letter
-- No Number, Other
-- Pc Punctuation, Connector
-- Pd Punctuation, Dash
-- Pe Punctuation, Close
-- Pf Punctuation, Final quote
-- Pi Punctuation, Initial quote
-- Po Punctuation, Other
-- Ps Punctuation, Open
-- Sc Symbol, Currency
-- Sk Symbol, Modifier
-- Sm Symbol, Math
-- So Symbol, Other
-- Zl Separator, Line
-- Zp Separator, Paragraph
-- Zs Separator, Space
-- Fe relative position FFFE/FFFF in plane
function Get_Category (U : Wide_Character) return Category;
pragma Inline (Get_Category);
-- Given a Wide_Character, returns corresponding Category, or Cn if the
-- code does not have an assigned unicode category.
-- The following functions perform category tests corresponding to lexical
-- classes defined in the Ada standard. There are two interfaces for each
-- function. The second takes a Category (e.g. returned by Get_Category).
-- The first takes a Wide_Character. The form taking the Wide_Character is
-- typically more efficient than calling Get_Category, but if several
-- different tests are to be performed on the same code, it is more
-- efficient to use Get_Category to get the category, then test the
-- resulting category.
function Is_Letter (U : Wide_Character) return Boolean;
function Is_Letter (C : Category) return Boolean;
pragma Inline (Is_Letter);
-- Returns true iff U is a letter that can be used to start an identifier,
-- or if C is one of the corresponding categories, which are the following:
-- Letter, Uppercase (Lu)
-- Letter, Lowercase (Ll)
-- Letter, Titlecase (Lt)
-- Letter, Modifier (Lm)
-- Letter, Other (Lo)
-- Number, Letter (Nl)
function Is_Digit (U : Wide_Character) return Boolean;
function Is_Digit (C : Category) return Boolean;
pragma Inline (Is_Digit);
-- Returns true iff U is a digit that can be used to extend an identifer,
-- or if C is one of the corresponding categories, which are the following:
-- Number, Decimal_Digit (Nd)
function Is_Line_Terminator (U : Wide_Character) return Boolean;
pragma Inline (Is_Line_Terminator);
-- Returns true iff U is an allowed line terminator for source programs,
-- if U is in the category Zp (Separator, Paragaph), or Zs (Separator,
-- Line), or if U is a conventional line terminator (CR, LF, VT, FF).
-- There is no category version for this function, since the set of
-- characters does not correspond to a set of Unicode categories.
function Is_Mark (U : Wide_Character) return Boolean;
function Is_Mark (C : Category) return Boolean;
pragma Inline (Is_Mark);
-- Returns true iff U is a mark character which can be used to extend an
-- identifier, or if C is one of the corresponding categories, which are
-- the following:
-- Mark, Non-Spacing (Mn)
-- Mark, Spacing Combining (Mc)
function Is_Other (U : Wide_Character) return Boolean;
function Is_Other (C : Category) return Boolean;
pragma Inline (Is_Other);
-- Returns true iff U is an other format character, which means that it
-- can be used to extend an identifier, but is ignored for the purposes of
-- matching of identiers, or if C is one of the corresponding categories,
-- which are the following:
-- Other, Format (Cf)
function Is_Punctuation (U : Wide_Character) return Boolean;
function Is_Punctuation (C : Category) return Boolean;
pragma Inline (Is_Punctuation);
-- Returns true iff U is a punctuation character that can be used to
-- separate pices of an identifier, or if C is one of the corresponding
-- categories, which are the following:
-- Punctuation, Connector (Pc)
function Is_Space (U : Wide_Character) return Boolean;
function Is_Space (C : Category) return Boolean;
pragma Inline (Is_Space);
-- Returns true iff U is considered a space to be ignored, or if C is one
-- of the corresponding categories, which are the following:
-- Separator, Space (Zs)
function Is_Non_Graphic (U : Wide_Character) return Boolean;
function Is_Non_Graphic (C : Category) return Boolean;
pragma Inline (Is_Non_Graphic);
-- Returns true iff U is considered to be a non-graphic character, or if C
-- is one of the corresponding categories, which are the following:
-- Other, Control (Cc)
-- Other, Private Use (Co)
-- Other, Surrogate (Cs)
-- Separator, Line (Zl)
-- Separator, Paragraph (Zp)
-- FFFE or FFFF positions in any plane (Fe)
--
-- Note that the Ada category format effector is subsumed by the above
-- list of Unicode categories.
--
-- Note that Other, Unassiged (Cn) is quite deliberately not included
-- in the list of categories above. This means that should any of these
-- code positions be defined in future with graphic characters they will
-- be allowed without a need to change implementations or the standard.
--
-- Note that Other, Format (Cf) is also quite deliberately not included
-- in the list of categories above. This means that these characters can
-- be included in character and string literals.
-- The following function is used to fold to upper case, as required by
-- the Ada 2005 standard rules for identifier case folding. Two
-- identifiers are equivalent if they are identical after folding all
-- letters to upper case using this routine. A corresponding function to
-- fold to lower case is also provided.
function To_Lower_Case (U : Wide_Character) return Wide_Character;
pragma Inline (To_Lower_Case);
-- If U represents an upper case letter, returns the corresponding lower
-- case letter, otherwise U is returned unchanged. The folding is locale
-- independent as defined by documents referenced in the note in section
-- 1 of ISO/IEC 10646:2003
function To_Upper_Case (U : Wide_Character) return Wide_Character;
pragma Inline (To_Upper_Case);
-- If U represents a lower case letter, returns the corresponding upper
-- case letter, otherwise U is returned unchanged. The folding is locale
-- independent as defined by documents referenced in the note in section
-- 1 of ISO/IEC 10646:2003
end Ada.Wide_Characters.Unicode;
|
-- Copyright 2016,2017 Steven Stewart-Gallus
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-- implied. See the License for the specific language governing
-- permissions and limitations under the License.
private with Ada.Strings.Unbounded;
private with Interfaces.C;
private with Interfaces.C.Strings;
private with Libc.Unistd;
private with Linted.Env;
private with Linted.Errors;
private with Linted.KOs;
private with Linted.Process;
private with Linted.Stdio;
private with Linted.Settings;
private with Linted.Logs;
private with Linted.Last_Chance;
procedure Main with
Spark_Mode => Off is
package U renames Ada.Strings.Unbounded;
use type Linted.Errors.Error;
type Envvar is record
Key : U.Unbounded_String;
Value : U.Unbounded_String;
end record;
Envvars_Count : constant Positive := 18;
function Default_Envvars (X : Positive) return Envvar with
Pre => X <= Envvars_Count;
function Default_Envvars
(X : Positive) return Envvar is
(case X is
when 1 =>
(U.To_Unbounded_String ("LINTED_PROCESS_NAME"),
U.To_Unbounded_String ("linted")),
when 2 =>
(U.To_Unbounded_String ("LINTED_SYSTEM_CONF_PATH"),
U.To_Unbounded_String (Linted.Settings.LNTD_SYSTEM_CONF_PATH)),
when 3 =>
(U.To_Unbounded_String ("LINTED_UNIT_PATH"),
U.To_Unbounded_String (Linted.Settings.LNTD_UNIT_PATH)),
when 4 =>
(U.To_Unbounded_String ("LINTED_INIT"),
U.To_Unbounded_String (Linted.Settings.LNTD_INIT)),
when 5 =>
(U.To_Unbounded_String ("LINTED_MONITOR"),
U.To_Unbounded_String (Linted.Settings.LNTD_MONITOR)),
when 6 =>
(U.To_Unbounded_String ("LINTED_STARTUP"),
U.To_Unbounded_String (Linted.Settings.LNTD_STARTUP)),
when 7 =>
(U.To_Unbounded_String ("LINTED_SANDBOX"),
U.To_Unbounded_String (Linted.Settings.LNTD_SANDBOX)),
when 8 =>
(U.To_Unbounded_String ("LINTED_WAITER"),
U.To_Unbounded_String (Linted.Settings.LNTD_WAITER)),
when 9 =>
(U.To_Unbounded_String ("LINTED_AUDIO"),
U.To_Unbounded_String (Linted.Settings.LNTD_AUDIO)),
when 10 =>
(U.To_Unbounded_String ("LINTED_AUDIO_FSTAB"),
U.To_Unbounded_String (Linted.Settings.LNTD_AUDIO_FSTAB)),
when 11 =>
(U.To_Unbounded_String ("LINTED_GUI"),
U.To_Unbounded_String (Linted.Settings.LNTD_GUI)),
when 12 =>
(U.To_Unbounded_String ("LINTED_GUI_FSTAB"),
U.To_Unbounded_String (Linted.Settings.LNTD_GUI_FSTAB)),
when 13 =>
(U.To_Unbounded_String ("LINTED_SIMULATOR"),
U.To_Unbounded_String (Linted.Settings.LNTD_SIMULATOR)),
when 14 =>
(U.To_Unbounded_String ("LINTED_SIMULATOR_FSTAB"),
U.To_Unbounded_String (Linted.Settings.LNTD_SIMULATOR_FSTAB)),
when 15 =>
(U.To_Unbounded_String ("LINTED_DRAWER"),
U.To_Unbounded_String (Linted.Settings.LNTD_DRAWER)),
when 16 =>
(U.To_Unbounded_String ("LINTED_DRAWER_FSTAB"),
U.To_Unbounded_String (Linted.Settings.LNTD_DRAWER_FSTAB)),
when 17 =>
(U.To_Unbounded_String ("LINTED_WINDOW"),
U.To_Unbounded_String (Linted.Settings.LNTD_WINDOW)),
when 18 =>
(U.To_Unbounded_String ("LINTED_WINDOW_FSTAB"),
U.To_Unbounded_String (Linted.Settings.LNTD_WINDOW_FSTAB)),
when others => raise Constraint_Error);
Pid : Linted.Process.Id;
Err : Linted.Errors.Error;
begin
for II in 1 .. Envvars_Count loop
declare
Key : U.Unbounded_String;
Default_Value : U.Unbounded_String;
begin
declare
E : Envvar := Default_Envvars (II);
begin
Key := E.Key;
Default_Value := E.Value;
end;
Linted.Env.Set
(U.To_String (Key),
U.To_String (Default_Value),
False,
Err);
if Err /= 0 then
goto On_Err;
end if;
end;
end loop;
Pid := Linted.Process.Current;
declare
P : String := Linted.Process.Id'Image (Pid);
V : String := P (2 .. P'Last);
begin
Linted.Env.Set ("MANAGERPID", V, True, Err);
if Err /= 0 then
goto On_Err;
end if;
Linted.Stdio.Write_Line (Linted.KOs.Standard_Output, "LINTED_PID=" & V);
end;
declare
Init : String := Linted.Env.Get ("LINTED_INIT");
Arr : aliased Interfaces.C.char_array := Interfaces.C.To_C (Init);
P : Interfaces.C.Strings.chars_ptr :=
Interfaces.C.Strings.To_Chars_Ptr (Arr'Unchecked_Access);
Argv : aliased array
(1 .. 2) of aliased Interfaces.C.Strings.chars_ptr :=
(P, Interfaces.C.Strings.Null_Ptr);
begin
Err := Linted.Errors.Error (Libc.Unistd.execv (P, Argv (1)'Address));
end;
<<On_Err>>
Linted.Logs.Log (Linted.Logs.Error, Linted.Errors.To_String (Err));
Libc.Unistd.u_exit (1);
end Main;
|
with Interfaces; use Interfaces;
with Ada.Text_IO; use Ada.Text_IO;
with Ringbuffers;
procedure Test_Ringbuffer is
package FIFO_Package is new Ringbuffers (256, Unsigned_8);
subtype FIFO is FIFO_Package.Ringbuffer;
Test : FIFO;
begin
Test.Write (1);
Test.Write (7);
while not Test.Is_Empty loop
Put_Line (Unsigned_8'Image (Test.Read));
end loop;
end Test_Ringbuffer;
|
with Ada.Containers.Indefinite_Ordered_Maps;
generic
with procedure Read_Scalar (Input : in String;
Success : out Boolean;
Consumed : out Natural;
Result : out Scalar_Type);
-- If Input begins with a valid scalar value, set Success to True,
-- Result to the corresponding scalar value and Consumed to the
-- number of chars that make the text representation of the scalar.
-- This procedure is used by parse.
with procedure Read_Identifier (Input : in String;
Success : out Boolean;
Consumed : out Natural;
Result : out Identifier);
with function Join (Prefix, Name : Identifier) return Identifier;
package Symbolic_Expressions.Parsing is
type ID_Table_Type is private;
-- The parsing function accepts, as an optional parameter, an "ID
-- table" that specifies if an ID is a variable or a function and,
-- in the latter case, how many parameters it accepts.
--
-- The behaviour of the Parse function in the presence of an ID that
-- is not in the ID table can be one of the following
--
-- * Always accept
-- (This is default) The ID is considered a variable or a
-- function according to the presence of a '(' following the ID.
--
-- * Always raise an error
--
-- * Accept undefined variables, but not undefined functions.
--
-- Note that "Always accept" means "Always accept *undefined* IDs." If,
-- for example, the ID is registered as a function, but a '(' does not
-- follow an error is raised.
--
Empty_ID_Table : constant ID_Table_Type;
type Parameter_Count is private;
-- A Parameter_Count stores the spec of a function in terms of number
-- of accepted parameters. All the combinations are possible: no
-- parameter, an exact number of parameters, a range or any number of
-- parameters. To create a Parameter_Count you can use the constructors
-- Exactly, At_Least and Between or use the constants Any_Number or
-- No_Parameter.
--
function Exactly (N : Natural) return Parameter_Count;
function At_Least (N : Natural) return Parameter_Count;
function Between (Min, Max : Natural) return Parameter_Count;
Any_Number : constant Parameter_Count;
No_Parameter : constant Parameter_Count;
procedure Define_Variable (Container : in out ID_Table_Type;
Name : Variable_Name);
-- Declare a variable with the given name
procedure Define_Function (Container : in out ID_Table_Type;
Name : Function_Name;
N_Params : Parameter_Count);
-- Declare a function with the given name, accepting the given number
-- of parameters. Examples:
--
-- Define_Function(Table, "sin", Exactly(1));
-- Define_Function(Table, "max", Any_Number);
-- Define_Function(Table, "rnd", No_Parameter);
--
function Is_Acceptable (N_Param : Natural;
Limits : Parameter_Count)
return Boolean;
-- Return True if N_Param lies in Limits
-- What to do when the parser finds an ID that is not in the
-- ID_Table given to the parser
type Unknown_ID_Action_Type is
(OK, -- Always accept the ID
Accept_As_Var, -- Accept it, only if used as a variable
Die); -- Never accept it
Parsing_Error : exception;
type Multiple_Match_Action is (Die, Allow, Allow_Unprefixed);
function Parse (Input : String;
ID_Table : ID_Table_Type := Empty_ID_Table;
On_Unknown_ID : Unknown_ID_Action_Type := OK;
Prefixes : String := "";
Prefix_Separator : String := ".";
On_Multiple_Match : Multiple_Match_Action := Allow_Unprefixed)
return Symbolic_Expression;
-- Parse a string with an expression and return the result. The grammar
-- of the expression is the usual one
--
-- Expr = Term *(('+' | '-') Term)
-- Term = Fact *(('*' | '/') Fact)
-- Fact = [('+' | '-')] Simple
-- Simple = Id [ '(' List ')' ] | Scalar | '(' Expr ')'
-- List = Expr *(',' Expr)
--
-- As usual, [...] denote an optional part, *(...) means
-- one or more repetition of something and '|' means
-- alternatives.
--
-- Note that
--
-- * In the production for Simple a single Id (without a
-- following list) represents a variabile, while an Id with a following
-- list represents a function call.
--
-- (Yes, folks, a call without arguments is something like foo(),
-- C-like .. . I know, I know, but with this convention parsing is
-- a bit easier since the difference is implicit in the syntax)
--
-- * Id follows the usual name syntax: letters, digits,
-- underscores and (in addition) the '.', so that "foo.end" is a
-- valid identifier. The first char must be a letter.
--
-- * The syntax of Scalar is implicitely defined by the function
-- Read_Scalar used in the instantiation. In order to avoid the risk
-- that the grammar above becomes ambiguous, a scalar should not begin
-- with a letter, a '(' or a sign.
--
-- * If Prefixes is not empty, it is expected to be a sequence of
-- identifiers separated by spaces. If an identifier is not found
-- "as it is," it is searched by prefixing it with the prefixes
-- in the order given. For example, if
--
-- Prefixes="Ada.Strings Ada.Foo Ada"
--
-- and the identifier is "bar," the following strings are searched
-- in order
--
-- Bar
-- Ada.Strings.Bar
-- Ada.Foo.Bar
-- Ada.Bar
--
-- It is possible to change the separator used between the identifier
-- and the prefix by specifyint Prefix_Separator. For example, if
-- Prefix_Separator = "::" the following identifiers are searched
-- for
--
-- Bar
-- Ada.Strings::Bar
-- Ada.Foo::Bar
-- Ada::Bar
--
-- * If Prefixes is not empty, all prefixes are tried. The behaviour
-- used when more than one prefix matches depends on
-- On_Multiple_Match
--
-- - if On_Multiple_Match = Die,
-- an exception is always raised
--
-- - if On_Multiple_Match = Allow,
-- the first match is taken
--
-- - if On_Multiple_Match = Allow_Unprefixed,
-- if the unprefixed name matches, the unprefixed name
-- is taken, otherwise an exception is raised
private
type Parameter_Count is
record
Min : Natural;
Max : Natural;
end record;
Any_Number : constant Parameter_Count := (Natural'First, Natural'Last);
No_Parameter : constant Parameter_Count := (0, 0);
type ID_Class is (Funct, Var);
type ID_Descriptor (Class : ID_Class) is
record
case Class is
when Funct =>
N_Param : Parameter_Count;
when Var =>
null;
end case;
end record;
package ID_Tables is
new Ada.Containers.Indefinite_Ordered_Maps
(Key_Type => Identifier,
Element_Type => ID_Descriptor);
type ID_Table_Type is
record
T : ID_Tables.Map := ID_Tables.Empty_Map;
end record;
Empty_ID_Table : constant ID_Table_Type := (T => ID_Tables.Empty_Map);
end Symbolic_Expressions.Parsing;
|
-- --
-- package Copyright (c) Dmitry A. Kazakov --
-- Parsers.Multiline_Source.Text_IO Luebeck --
-- Implementation Winter, 2004 --
-- --
-- Last revision : 13:13 14 Sep 2019 --
-- --
-- This library is free software; you can redistribute it and/or --
-- modify it under the terms of the GNU General Public License as --
-- published by the Free Software Foundation; either version 2 of --
-- the License, or (at your option) any later version. This 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 --
-- General Public License for more details. You should have --
-- received a copy of the GNU General Public License along with --
-- this library; if not, write to the Free Software Foundation, --
-- Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. --
-- --
-- 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. --
--____________________________________________________________________--
package body Parsers.Multiline_Source.Text_IO is
Increment : constant Integer := 512;
procedure Get_Line (Code : in out Source) is
Size : Natural;
begin
if Code.Buffer = null then
raise End_Error;
end if;
Get_Line (Code.File.all, Code.Buffer.all, Size);
Code.Length := Size;
while Code.Length = Code.Buffer'Last loop
declare
Old_Line : String_Ptr := Code.Buffer;
begin
Code.Buffer := new String (1..Old_Line'Length + Increment);
Code.Buffer (1..Old_Line'Length) := Old_Line.all;
Free (Old_Line);
end;
Get_Line
( Code.File.all,
Code.Buffer (Code.Length + 1..Code.Buffer'Last),
Size
);
Code.Length := Size;
end loop;
exception
when others =>
Free (Code.Buffer);
raise;
end Get_Line;
end Parsers.Multiline_Source.Text_IO;
|
-- { dg-do compile }
-- { dg-options "-gnatws -fdump-tree-original" }
procedure Derived_Type1 is
type Root is tagged null record;
type Derived1 is new Root with record
I1 : Integer;
end record;
type Derived2 is new Derived1 with record
I2: Integer;
end record;
R : Root;
D1 : Derived1;
D2 : Derived2;
begin
R := Root(D1);
R := Root(D2);
D1 := Derived1(D2);
end;
-- { dg-final { scan-tree-dump-not "VIEW_CONVERT_EXPR<struct derived_type1__root>" "original" } }
-- { dg-final { scan-tree-dump-not "VIEW_CONVERT_EXPR<struct derived_type1__derived1>" "original" } }
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- S Y S T E M . A R I T H _ 6 4 --
-- --
-- S p e c --
-- --
-- Copyright (C) 1992-2009, 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 unit provides software routines for doing arithmetic on 64-bit
-- signed integer values in cases where either overflow checking is
-- required, or intermediate results are longer than 64 bits.
with Interfaces;
package System.Arith_64 is
pragma Pure;
subtype Int64 is Interfaces.Integer_64;
function Add_With_Ovflo_Check (X, Y : Int64) return Int64;
-- Raises Constraint_Error if sum of operands overflows 64 bits,
-- otherwise returns the 64-bit signed integer sum.
function Subtract_With_Ovflo_Check (X, Y : Int64) return Int64;
-- Raises Constraint_Error if difference of operands overflows 64
-- bits, otherwise returns the 64-bit signed integer difference.
function Multiply_With_Ovflo_Check (X, Y : Int64) return Int64;
-- Raises Constraint_Error if product of operands overflows 64
-- bits, otherwise returns the 64-bit signed integer product.
procedure Scaled_Divide
(X, Y, Z : Int64;
Q, R : out Int64;
Round : Boolean);
-- Performs the division of (X * Y) / Z, storing the quotient in Q
-- and the remainder in R. Constraint_Error is raised if Z is zero,
-- or if the quotient does not fit in 64-bits. Round indicates if
-- the result should be rounded. If Round is False, then Q, R are
-- the normal quotient and remainder from a truncating division.
-- If Round is True, then Q is the rounded quotient. The remainder
-- R is not affected by the setting of the Round flag.
procedure Double_Divide
(X, Y, Z : Int64;
Q, R : out Int64;
Round : Boolean);
-- Performs the division X / (Y * Z), storing the quotient in Q and
-- the remainder in R. Constraint_Error is raised if Y or Z is zero,
-- or if the quotient does not fit in 64-bits. Round indicates if the
-- result should be rounded. If Round is False, then Q, R are the normal
-- quotient and remainder from a truncating division. If Round is True,
-- then Q is the rounded quotient. The remainder R is not affected by the
-- setting of the Round flag.
end System.Arith_64;
|
with Ada.Wide_Characters.Unicode; -- GNAT Specific.
-- with Ada.Text_IO;
package body Symbex.Lex is
package Unicode renames Ada.Wide_Characters.Unicode;
--
-- Private subprograms.
--
procedure Set_State
(Lexer : in out Lexer_t;
State : in State_Stage_t) is
begin
Lexer.State (State) := True;
end Set_State;
procedure Unset_State
(Lexer : in out Lexer_t;
State : in State_Stage_t) is
begin
Lexer.State (State) := False;
end Unset_State;
function State_Is_Set
(Lexer : in Lexer_t;
State : in State_Stage_t) return Boolean is
begin
return Lexer.State (State);
end State_Is_Set;
--
-- Return true if internal token buffer contains data.
--
function Token_Is_Nonzero_Length
(Lexer : in Lexer_t) return Boolean is
begin
-- Ada.Text_IO.Put_Line ("length: " & Natural'Image (UBW_Strings.Length (Lexer.Token_Buffer)));
return UBW_Strings.Length (Lexer.Token_Buffer) /= 0;
end Token_Is_Nonzero_Length;
--
-- Append item to internal token buffer.
--
procedure Append_To_Token
(Lexer : in out Lexer_t;
Item : in Wide_Character) is
begin
UBW_Strings.Append (Lexer.Token_Buffer, Item);
end Append_To_Token;
--
-- Finish token in buffer and assign kind Kind.
--
procedure Complete_Token
(Lexer : in out Lexer_t;
Kind : in Token_Kind_t;
Token : out Token_t) is
begin
Token := Token_t'
(Is_Valid => True,
Line_Number => Lexer.Current_Line,
Text => Lexer.Token_Buffer,
Kind => Kind);
Lexer.Token_Buffer := UBW_Strings.Null_Unbounded_Wide_String;
end Complete_Token;
--
-- Categorize Item into character class.
--
function Categorize_Character
(Item : in Wide_Character) return Character_Class_t
is
Class : Character_Class_t := Ordinary_Text;
begin
case Item is
when '(' => Class := List_Open_Delimiter;
when ')' => Class := List_Close_Delimiter;
when '"' => Class := String_Delimiter;
when ';' => Class := Comment_Delimiter;
when '\' => Class := Escape_Character;
when others =>
if Unicode.Is_Line_Terminator (Item) then
Class := Line_Break;
else
if Unicode.Is_Space (Item) then
Class := Whitespace;
end if;
end if;
end case;
return Class;
end Categorize_Character;
--
-- Public API.
--
function Initialized (Lexer : in Lexer_t) return Boolean is
begin
return Lexer.Inited;
end Initialized;
--
-- Initialize the lexer.
--
procedure Initialize_Lexer
(Lexer : out Lexer_t;
Status : out Lexer_Status_t) is
begin
Lexer := Lexer_t'
(Inited => True,
Current_Line => Line_Number_t'First,
Token_Buffer => UBW_Strings.Null_Unbounded_Wide_String,
Input_Buffer => Input_Buffer_t'(others => Wide_Character'Val (0)),
State => State_t'(others => False));
Status := Lexer_OK;
end Initialize_Lexer;
--
-- Retrieve token from input stream.
--
procedure Get_Token
(Lexer : in out Lexer_t;
Token : out Token_t;
Status : out Lexer_Status_t)
is
--
-- Stream characters via Read_Item.
--
procedure Fetch_Characters
(Lexer : in out Lexer_t;
Item : out Wide_Character;
Item_Next : out Wide_Character;
Status : out Stream_Status_t)
is
Null_Item : constant Wide_Character := Wide_Character'Val (0);
begin
if Lexer.Input_Buffer (Next) /= Null_Item then
Lexer.Input_Buffer (Current) := Lexer.Input_Buffer (Next);
Read_Item
(Item => Lexer.Input_Buffer (Next),
Status => Status);
case Status is
when Stream_EOF =>
Lexer.Input_Buffer (Next) := Null_Item;
Status := Stream_OK;
when Stream_Error => null;
when Stream_OK => null;
end case;
else
Read_Item
(Item => Lexer.Input_Buffer (Current),
Status => Status);
case Status is
when Stream_EOF => null;
when Stream_Error => null;
when Stream_OK =>
Read_Item
(Item => Lexer.Input_Buffer (Next),
Status => Status);
case Status is
when Stream_EOF =>
Lexer.Input_Buffer (Next) := Null_Item;
Status := Stream_OK;
when Stream_Error => null;
when Stream_OK => null;
end case;
end case;
end if;
Item := Lexer.Input_Buffer (Current);
Item_Next := Lexer.Input_Buffer (Next);
end Fetch_Characters;
Item : Wide_Character;
Item_Next : Wide_Character;
Stream_Status : Stream_Status_t;
begin
-- Default status.
Status := Lexer_Needs_More_Data;
Token := Invalid_Token;
-- Fetch characters from input stream.
Fetch_Characters
(Lexer => Lexer,
Item => Item,
Item_Next => Item_Next,
Status => Stream_Status);
case Stream_Status is
when Stream_OK => null;
when Stream_Error =>
Status := Lexer_Error_Stream_Error;
return;
when Stream_EOF =>
if State_Is_Set (Lexer, Inside_String) or
State_Is_Set (Lexer, Inside_Escape) then
Status := Lexer_Error_Early_EOF;
else
-- Reached upon EOF with no preceding newline/whitespace.
Status := Lexer_OK;
-- Have unfinished token?
if Token_Is_Nonzero_Length (Lexer) then
Complete_Token
(Lexer => Lexer,
Token => Token,
Kind => Token_Symbol);
else
Append_To_Token (Lexer, 'E');
Complete_Token
(Lexer => Lexer,
Token => Token,
Kind => Token_EOF);
end if;
end if;
return;
end case;
pragma Assert (Stream_Status = Stream_OK);
-- Process character.
case Categorize_Character (Item) is
when Comment_Delimiter =>
if State_Is_Set (Lexer, Inside_String) or
State_Is_Set (Lexer, Inside_Escape) then
Append_To_Token (Lexer, Item);
else
if not State_Is_Set (Lexer, Inside_Comment) then
Set_State (Lexer, Inside_Comment);
end if;
end if;
when Escape_Character =>
if not State_Is_Set (Lexer, Inside_Comment) then
if State_Is_Set (Lexer, Inside_String) then
if State_Is_Set (Lexer, Inside_Escape) then
Append_To_Token (Lexer, Item);
Unset_State (Lexer, Inside_Escape);
else
Set_State (Lexer, Inside_Escape);
end if;
end if;
end if;
when Line_Break =>
if State_Is_Set (Lexer, Inside_Comment) then
Unset_State (Lexer, Inside_Comment);
else
begin
-- Potential overflow.
Lexer.Current_Line := Lexer.Current_Line + 1;
if State_Is_Set (Lexer, Inside_Escape) then
Unset_State (Lexer, Inside_Escape);
end if;
if State_Is_Set (Lexer, Inside_String) then
Append_To_Token (Lexer, Item);
else
if Token_Is_Nonzero_Length (Lexer) then
Status := Lexer_OK;
Complete_Token
(Lexer => Lexer,
Token => Token,
Kind => Token_Symbol);
end if;
end if;
exception
when Constraint_Error =>
Status := Lexer_Error_Line_Overflow;
Token := Invalid_Token;
end;
end if;
when List_Open_Delimiter =>
if not State_Is_Set (Lexer, Inside_Comment) then
Append_To_Token (Lexer, Item);
if not State_Is_Set (Lexer, Inside_String) then
Status := Lexer_OK;
Complete_Token
(Lexer => Lexer,
Token => Token,
Kind => Token_List_Open);
end if;
end if;
when List_Close_Delimiter =>
if not State_Is_Set (Lexer, Inside_Comment) then
Append_To_Token (Lexer, Item);
if not State_Is_Set (Lexer, Inside_String) then
Status := Lexer_OK;
Complete_Token
(Lexer => Lexer,
Token => Token,
Kind => Token_List_Close);
end if;
end if;
when String_Delimiter =>
if not State_Is_Set (Lexer, Inside_Comment) then
if State_Is_Set (Lexer, Inside_String) then
if State_Is_Set (Lexer, Inside_Escape) then
Append_To_Token (Lexer, Item);
Unset_State (Lexer, Inside_Escape);
else
Status := Lexer_OK;
Complete_Token
(Lexer => Lexer,
Token => Token,
Kind => Token_Quoted_String);
Unset_State (Lexer, Inside_String);
end if;
else
Set_State (Lexer, Inside_String);
end if;
end if;
when Whitespace =>
if not State_Is_Set (Lexer, Inside_Comment) then
if State_Is_Set (Lexer, Inside_Escape) then
Unset_State (Lexer, Inside_Escape);
end if;
if State_Is_Set (Lexer, Inside_String) then
Append_To_Token (Lexer, Item);
else
if Token_Is_Nonzero_Length (Lexer) then
Status := Lexer_OK;
Complete_Token
(Lexer => Lexer,
Token => Token,
Kind => Token_Symbol);
end if;
end if;
end if;
when Ordinary_Text =>
if not State_Is_Set (Lexer, Inside_Comment) then
if State_Is_Set (Lexer, Inside_Escape) then
Unset_State (Lexer, Inside_Escape);
end if;
Append_To_Token (Lexer, Item);
-- End of token if not inside a string.
case Categorize_Character (Item_Next) is
when List_Open_Delimiter | List_Close_Delimiter | String_Delimiter =>
if not State_Is_Set (Lexer, Inside_String) then
Status := Lexer_OK;
Complete_Token
(Lexer => Lexer,
Token => Token,
Kind => Token_Symbol);
end if;
when others => null;
end case;
end if;
end case;
exception
when Storage_Error =>
Status := Lexer_Error_Out_Of_Memory;
Token := Invalid_Token;
end Get_Token;
end Symbex.Lex;
|
package Edit_Line is
function Read_Line (Prompt : in String) return String;
procedure Add_History (Input : in String);
end Edit_Line; |
pragma License (Unrestricted);
-- implementation unit for Generic_Real_Arrays and Generic_Complex_Arrays
private package Ada.Numerics.Generic_Arrays is
pragma Pure;
-- vector selection, conversion, and composition operations
generic
type Number is private;
type Vector is array (Integer range <>) of Number;
type Parameter_Type is private;
type Parameter_Vector is array (Integer range <>) of Parameter_Type;
with procedure Apply (X : in out Number; Param : Parameter_Type);
procedure Apply_Vector (X : in out Vector; Param : Parameter_Vector);
-- vector arithmetic operations
generic
type Number is private;
type Vector is array (Integer range <>) of Number;
type Result_Type is private;
type Result_Vector is array (Integer range <>) of Result_Type;
with function Operator (Right : Number) return Result_Type;
function Operator_Vector (Right : Vector) return Result_Vector;
generic
type Number is private;
type Vector is array (Integer range <>) of Number;
type Parameter_Type is private;
type Result_Type is private;
type Result_Vector is array (Integer range <>) of Result_Type;
with function Operator (X : Number; Y : Parameter_Type)
return Result_Type;
function Operator_Vector_Param (X : Vector; Y : Parameter_Type)
return Result_Vector;
generic
type Left_Type is private;
type Left_Vector is array (Integer range <>) of Left_Type;
type Right_Type is private;
type Right_Vector is array (Integer range <>) of Right_Type;
type Result_Type is private;
type Result_Vector is array (Integer range <>) of Result_Type;
with function Operator (Left : Left_Type; Right : Right_Type)
return Result_Type;
function Operator_Vector_Vector (Left : Left_Vector; Right : Right_Vector)
return Result_Vector;
generic
type Number is private;
type Vector is array (Integer range <>) of Number;
type Parameter_Type is private;
type Result_Type is private;
type Result_Vector is array (Integer range <>) of Result_Type;
with function Operator (X, Y : Number; Param : Parameter_Type)
return Result_Type;
function Operator_Vector_Vector_Param (X, Y : Vector; Z : Parameter_Type)
return Result_Vector;
generic
type Number is private;
type Vector is array (Integer range <>) of Number;
type Result_Type is private;
Zero : Result_Type;
with function Sqrt (X : Result_Type) return Result_Type is <>;
with function "abs" (Right : Number) return Result_Type is <>;
with function "+" (Left, Right : Result_Type) return Result_Type is <>;
with function "*" (Left, Right : Result_Type) return Result_Type is <>;
function Absolute (Right : Vector) return Result_Type;
generic
type Left_Type is private;
type Left_Vector is array (Integer range <>) of Left_Type;
type Right_Type is private;
type Right_Vector is array (Integer range <>) of Right_Type;
type Result_Type is private;
Zero : Result_Type;
with function "+" (Left, Right : Result_Type) return Result_Type is <>;
with function "*" (Left : Left_Type; Right : Right_Type)
return Result_Type is <>;
function Inner_Production (Left : Left_Vector; Right : Right_Vector)
return Result_Type;
-- other vector operations
generic
type Number is private;
type Vector is array (Integer range <>) of Number;
Zero : Number;
One : Number;
function Unit_Vector (
Index : Integer;
Order : Positive;
First : Integer := 1)
return Vector;
-- matrix selection, conversion, and composition operations
generic
type Number is private;
type Matrix is array (Integer range <>, Integer range <>) of Number;
type Parameter_Type is private;
type Parameter_Matrix is
array (Integer range <>, Integer range <>) of Parameter_Type;
with procedure Apply (X : in out Number; Param : Parameter_Type);
procedure Apply_Matrix (X : in out Matrix; Param : Parameter_Matrix);
-- matrix arithmetic operations
generic
type Number is private;
type Matrix is array (Integer range <>, Integer range <>) of Number;
type Result_Type is private;
type Result_Matrix is
array (Integer range <>, Integer range <>) of Result_Type;
with function Operator (Right : Number) return Result_Type;
function Operator_Matrix (Right : Matrix) return Result_Matrix;
generic
type Number is private;
type Matrix is array (Integer range <>, Integer range <>) of Number;
type Parameter_Type is private;
type Result_Type is private;
type Result_Matrix is
array (Integer range <>, Integer range <>) of Result_Type;
with function Operator (X : Number; Y : Parameter_Type)
return Result_Type;
function Operator_Matrix_Param (X : Matrix; Y : Parameter_Type)
return Result_Matrix;
generic
type Left_Type is private;
type Left_Matrix is
array (Integer range <>, Integer range <>) of Left_Type;
type Right_Type is private;
type Right_Matrix is
array (Integer range <>, Integer range <>) of Right_Type;
type Result_Type is private;
type Result_Matrix is
array (Integer range <>, Integer range <>) of Result_Type;
with function Operator (Left : Left_Type; Right : Right_Type)
return Result_Type;
function Operator_Matrix_Matrix (Left : Left_Matrix; Right : Right_Matrix)
return Result_Matrix;
generic
type Number is private;
type Matrix is array (Integer range <>, Integer range <>) of Number;
type Parameter_Type is private;
type Result_Type is private;
type Result_Matrix is
array (Integer range <>, Integer range <>) of Result_Type;
with function Operator (X, Y : Number; Z : Parameter_Type)
return Result_Type;
function Operator_Matrix_Matrix_Param (X, Y : Matrix; Z : Parameter_Type)
return Result_Matrix;
generic
type Number is private;
type Matrix is array (Integer range <>, Integer range <>) of Number;
function Transpose (X : Matrix) return Matrix;
generic
type Left_Type is private;
type Left_Matrix is
array (Integer range <>, Integer range <>) of Left_Type;
type Right_Type is private;
type Right_Matrix is
array (Integer range <>, Integer range <>) of Right_Type;
type Result_Type is private;
type Result_Matrix is
array (Integer range <>, Integer range <>) of Result_Type;
Zero : Result_Type;
with function "+" (Left, Right : Result_Type) return Result_Type is <>;
with function "*" (Left : Left_Type; Right : Right_Type)
return Result_Type is <>;
function Multiply_Matrix_Matrix (Left : Left_Matrix; Right : Right_Matrix)
return Result_Matrix;
generic
type Left_Type is private;
type Left_Vector is array (Integer range <>) of Left_Type;
type Right_Type is private;
type Right_Vector is array (Integer range <>) of Right_Type;
type Result_Type is private;
type Result_Matrix is
array (Integer range <>, Integer range <>) of Result_Type;
with function "*" (Left : Left_Type; Right : Right_Type)
return Result_Type is <>;
function Multiply_Vector_Vector (Left : Left_Vector; Right : Right_Vector)
return Result_Matrix;
generic
type Left_Type is private;
type Left_Vector is array (Integer range <>) of Left_Type;
type Right_Type is private;
type Right_Matrix is
array (Integer range <>, Integer range <>) of Right_Type;
type Result_Type is private;
type Result_Vector is array (Integer range <>) of Result_Type;
Zero : Result_Type;
with function "+" (Left, Right : Result_Type) return Result_Type is <>;
with function "*" (Left : Left_Type; Right : Right_Type)
return Result_Type is <>;
function Multiply_Vector_Matrix (Left : Left_Vector; Right : Right_Matrix)
return Result_Vector;
generic
type Left_Type is private;
type Left_Matrix is
array (Integer range <>, Integer range <>) of Left_Type;
type Right_Type is private;
type Right_Vector is array (Integer range <>) of Right_Type;
type Result_Type is private;
type Result_Vector is array (Integer range <>) of Result_Type;
Zero : Result_Type;
with function "+" (Left, Right : Result_Type) return Result_Type is <>;
with function "*" (Left : Left_Type; Right : Right_Type)
return Result_Type is <>;
function Multiply_Matrix_Vector (Left : Left_Matrix; Right : Right_Vector)
return Result_Vector;
-- matrix inversion and related operations
generic
type Number is private;
type Matrix is array (Integer range <>, Integer range <>) of Number;
function Minor (A : Matrix; I, J : Integer) return Matrix;
generic
type Number is private;
type Matrix is array (Integer range <>, Integer range <>) of Number;
One : Number;
with function Minor (A : Matrix; I, J : Integer) return Matrix is <>;
with function Determinant (A : Matrix) return Number is <>;
with function "-" (Right : Number) return Number is <>;
with function "*" (Left, Right : Number) return Number is <>;
with function "/" (Left, Right : Number) return Number is <>;
function Inverse (A : Matrix) return Matrix;
generic
type Number is private;
type Matrix is array (Integer range <>, Integer range <>) of Number;
Zero : Number;
One : Number;
with function Minor (A : Matrix; I, J : Integer) return Matrix is <>;
with function "+" (Left, Right : Number) return Number is <>;
with function "-" (Right : Number) return Number is <>;
with function "-" (Left, Right : Number) return Number is <>;
with function "*" (Left, Right : Number) return Number is <>;
function Determinant (A : Matrix) return Number;
-- eigenvalues and vectors of a hermitian matrix
generic
type Real is private;
type Real_Vector is array (Integer range <>) of Real;
type Number is private;
type Matrix is array (Integer range <>, Integer range <>) of Number;
Zero : Number;
One : Number;
Two : Number;
with function Sqrt (X : Number) return Number is <>;
with function Is_Minus (X : Number) return Boolean is <>;
with function Is_Small (X : Number) return Boolean is <>;
with function To_Real (X : Number) return Real is <>;
with function "+" (Left, Right : Number) return Number is <>;
with function "-" (Right : Number) return Number is <>;
with function "-" (Left, Right : Number) return Number is <>;
with function "*" (Left, Right : Number) return Number is <>;
with function "/" (Left, Right : Number) return Number is <>;
procedure Eigensystem (
A : Matrix;
Values : out Real_Vector;
Vectors : out Matrix);
-- other matrix operations
generic
type Number is private;
type Matrix is array (Integer range <>, Integer range <>) of Number;
Zero : Number;
One : Number;
function Unit_Matrix (Order : Positive; First_1, First_2 : Integer := 1)
return Matrix;
end Ada.Numerics.Generic_Arrays;
|
with Libtcod.Maps, Libtcod.Input;
with Actors, Engines, Ada.Numerics.Elementary_Functions;
use Libtcod;
package body Components.AIs is
package Float_Math renames Ada.Numerics.Elementary_Functions;
---------------------------
-- player_move_or_attack --
---------------------------
function player_move_or_attack(owner : in out Actors.Actor;
target_x : Maps.X_Pos; target_y : Maps.Y_Pos;
engine : in out Engines.Engine) return Boolean is
use type Maps.X_Pos, Maps.Y_Pos, Actors.Actor;
procedure move_to_target is
begin
owner.x := target_x;
owner.y := target_y;
end move_to_target;
begin
if engine.map.is_wall(target_x, target_y) then
return False;
end if;
for target of engine.actor_list loop
if target.x = target_x and then target.y = target_y and then target.is_destructible
and then target /= owner then
if target.destructible.is_dead then
engine.gui.log("There is a " & target.get_name & " corpse here");
move_to_target;
return True;
else
owner.attacker.attack(owner, target, engine);
return False;
end if;
end if;
end loop;
-- Space is free to move to
move_to_target;
return True;
end player_move_or_attack;
------------
-- update --
------------
overriding
procedure update(self : in out Player_AI; owner : in out Actors.Actor; engine : in out Engines.Engine) is
dx : Maps.X_Diff := 0;
dy : Maps.Y_Diff := 0;
use Libtcod.Input, Maps;
begin
if owner.is_destructible and then owner.destructible.is_dead then
return;
end if;
case engine.last_key_type is
when Key_Up => dy := -1;
when Key_Down => dy := 1;
when Key_Left => dx := -1;
when Key_Right => dx := 1;
end case;
if dx /= 0 or else dy /= 0 then
engine.status := Engines.Status_New_Turn;
if player_move_or_attack(owner, owner.x + dx, owner.y + dy, engine) then
engine.map.compute_fov(owner.x, owner.y, engine.fov_radius);
end if;
end if;
end update;
--------------------
-- move_or_attack --
--------------------
procedure move_or_attack(self : in out Monster_AI; owner : in out Actors.Actor;
target_x : Maps.X_Pos; target_y : Maps.Y_Pos;
engine : in out Engines.Engine) is
use type Maps.X_Pos, Maps.Y_Pos, Maps.X_Diff, Maps.Y_Diff;
dx, step_x : Maps.X_Diff;
dy, step_y : Maps.Y_Diff;
distance : Float;
begin
if engine.map.is_wall(target_x, target_y) then
return;
end if;
dx := target_x - owner.x;
dy := target_y - owner.y;
step_x := (if dx > 0 then 1 else -1);
step_y := (if dy > 0 then 1 else -1);
distance := Float_Math.Sqrt(Float(Integer(dx**2) + Integer(dy**2)));
if distance >= 2.0 then
dx := Maps.X_Diff(Float'Rounding(Float(dx) / distance));
dy := Maps.Y_Diff(Float'Rounding(Float(dy) / distance));
if engine.can_walk(owner.x + dx, owner.y + dy) then
owner.x := owner.x + dx;
owner.y := owner.y + dy;
elsif engine.can_walk(owner.x + step_x, owner.y) then
owner.x := owner.x + step_x;
elsif engine.can_walk(owner.x, owner.y + step_y) then
owner.y := owner.y + step_y;
end if;
elsif owner.is_attacker then
owner.attacker.attack(owner, engine.player, engine);
end if;
end move_or_attack;
------------
-- update --
------------
overriding
procedure update(self : in out Monster_AI; owner : in out Actors.Actor; engine : in out Engines.Engine) is
begin
if owner.is_destructible and then owner.destructible.is_dead then
return;
end if;
if engine.map.in_fov(owner.x, owner.y) then
self.move_count := Turns_To_Track;
elsif self.move_count = 0 then
return;
else
self.move_count := self.move_count - 1;
end if;
self.move_or_attack(owner, engine.player.x, engine.player.y, engine);
end update;
end Components.AIs;
|
-----------------------------------------------------------------------
-- servlet-responses -- Servlet Responses
-- Copyright (C) 2010, 2011, 2018 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
with Util.Dates.RFC7231;
package body Servlet.Responses is
-- Returns the name of the character encoding (MIME charset) used for the body
-- sent in this response. The character encoding may have been specified explicitly
-- using the setCharacterEncoding(String) or setContentType(String) methods,
-- or implicitly using the setLocale(java.util.Locale) method. Explicit
-- specifications take precedence over implicit specifications. Calls made
-- to these methods after getWriter has been called or after the response has
-- been committed have no effect on the character encoding. If no character
-- encoding has been specified, ISO-8859-1 is returned.
function Get_Character_Encoding (Resp : in Response) return String is
pragma Unreferenced (Resp);
begin
return "";
end Get_Character_Encoding;
-- ------------------------------
-- Returns the content type used for the MIME body sent in this response.
-- The content type proper must have been specified using
-- setContentType(String) before the response is committed. If no content type
-- has been specified, this method returns null. If a content type has been
-- specified, and a character encoding has been explicitly or implicitly specified
-- as described in getCharacterEncoding() or getWriter() has been called,
-- the charset parameter is included in the string returned. If no character
-- encoding has been specified, the charset parameter is omitted.
-- ------------------------------
function Get_Content_Type (Resp : in Response) return String is
begin
return Ada.Strings.Unbounded.To_String (Resp.Content_Type);
end Get_Content_Type;
-- Sets the character encoding (MIME charset) of the response being sent to the
-- client, for example, to UTF-8. If the character encoding has already been
-- set by setContentType(java.lang.String) or setLocale(java.util.Locale),
-- this method overrides it. Calling setContentType(java.lang.String) with the
-- String of text/html and calling this method with the String of UTF-8 is
-- equivalent with calling setContentType with the String of text/html; charset=UTF-8.
--
-- This method can be called repeatedly to change the character encoding.
-- This method has no effect if it is called after getWriter has been called or
-- after the response has been committed.
--
-- Containers must communicate the character encoding used for the servlet
-- response's writer to the client if the protocol provides a way for doing so.
-- In the case of HTTP, the character encoding is communicated as part of the
-- Content-Type header for text media types. Note that the character encoding
-- cannot be communicated via HTTP headers if the servlet does not specify
-- a content type; however, it is still used to encode text written via the servlet
-- response's writer.
procedure Set_Character_Encoding (Resp : in out Response;
Encoding : in String) is
pragma Unreferenced (Encoding, Resp);
begin
null;
end Set_Character_Encoding;
-- ------------------------------
-- Sets the length of the content body in the response In HTTP servlets,
-- this method sets the HTTP Content-Length header.
-- ------------------------------
procedure Set_Content_Length (Resp : in out Response;
Length : in Integer) is
begin
Response'Class (Resp).Set_Header ("Content-Length", Util.Strings.Image (Length));
end Set_Content_Length;
-- ------------------------------
-- Sets the content type of the response being sent to the client, if the response
-- has not been committed yet. The given content type may include a character
-- encoding specification, for example, text/html;charset=UTF-8. The response's
-- character encoding is only set from the given content type if this method is
-- called before getWriter is called.
--
-- This method may be called repeatedly to change content type and character
-- encoding. This method has no effect if called after the response has been
-- committed. It does not set the response's character encoding if it is called
-- after getWriter has been called or after the response has been committed.
--
-- Containers must communicate the content type and the character encoding used
-- for the servlet response's writer to the client if the protocol provides a way
-- for doing so. In the case of HTTP, the Content-Type header is used.
-- ------------------------------
procedure Set_Content_Type (Resp : in out Response;
Content : in String) is
begin
Resp.Content_Type := Ada.Strings.Unbounded.To_Unbounded_String (Content);
end Set_Content_Type;
-- ------------------------------
-- Returns a boolean indicating if the response has been committed.
-- A committed response has already had its status code and headers written.
-- ------------------------------
function Is_Committed (Resp : in Response) return Boolean is
begin
return Resp.Committed or else Resp.Stream.Get_Size > 0;
end Is_Committed;
-- ------------------------------
-- Sets the locale of the response, if the response has not been committed yet.
-- It also sets the response's character encoding appropriately for the locale,
-- if the character encoding has not been explicitly set using
-- setContentType(java.lang.String) or setCharacterEncoding(java.lang.String),
-- getWriter hasn't been called yet, and the response hasn't been committed yet.
-- If the deployment descriptor contains a locale-encoding-mapping-list element,
-- and that element provides a mapping for the given locale, that mapping is used.
-- Otherwise, the mapping from locale to character encoding is container dependent.
--
-- This method may be called repeatedly to change locale and character encoding.
-- The method has no effect if called after the response has been committed.
-- It does not set the response's character encoding if it is called after
-- setContentType(java.lang.String) has been called with a charset specification,
-- after setCharacterEncoding(java.lang.String) has been called,
-- after getWriter has been called, or after the response has been committed.
--
-- Containers must communicate the locale and the character encoding used for
-- the servlet response's writer to the client if the protocol provides a way
-- for doing so. In the case of HTTP, the locale is communicated via the
-- Content-Language header, the character encoding as part of the Content-Type
-- header for text media types. Note that the character encoding cannot be
-- communicated via HTTP headers if the servlet does not specify a content type;
-- however, it is still used to encode text written via the servlet response's writer.
-- ------------------------------
procedure Set_Locale (Resp : in out Response;
Loc : in Util.Locales.Locale) is
begin
Resp.Locale := Loc;
end Set_Locale;
-- ------------------------------
-- Returns the locale specified for this response using the
-- setLocale(java.util.Locale) method. Calls made to setLocale after the
-- response is committed have no effect. If no locale has been specified,
-- the container's default locale is returned.
-- ------------------------------
function Get_Locale (Resp : in Response) return Util.Locales.Locale is
begin
return Resp.Locale;
end Get_Locale;
-- ------------------------------
-- Adds the specified cookie to the response. This method can be called multiple
-- times to set more than one cookie.
-- ------------------------------
procedure Add_Cookie (Resp : in out Response;
Cookie : in Servlet.Cookies.Cookie) is
begin
Response'Class (Resp).Add_Header (Name => "Set-Cookie",
Value => Servlet.Cookies.To_Http_Header (Cookie));
end Add_Cookie;
-- Encodes the specified URL by including the session ID in it, or, if encoding
-- is not needed, returns the URL unchanged. The implementation of this method
-- includes the logic to determine whether the session ID needs to be encoded
-- in the URL. For example, if the browser supports cookies, or session tracking
-- is turned off, URL encoding is unnecessary.
--
-- For robust session tracking, all URLs emitted by a servlet should be run through
-- this method. Otherwise, URL rewriting cannot be used with browsers which do not
-- support cookies.
function Encode_URL (Resp : in Response;
URL : in String) return String is
pragma Unreferenced (Resp);
begin
return URL;
end Encode_URL;
-- Encodes the specified URL for use in the sendRedirect method or, if encoding
-- is not needed, returns the URL unchanged. The implementation of this method
-- includes the logic to determine whether the session ID needs to be encoded
-- in the URL. Because the rules for making this determination can differ from
-- those used to decide whether to encode a normal link, this method is separated
-- from the encodeURL method.
--
-- All URLs sent to the HttpServletResponse.sendRedirect method should be run
-- through this method. Otherwise, URL rewriting cannot be used with browsers
-- which do not support cookies.
function Encode_Redirect_URL (Resp : in Response;
URL : in String) return String is
pragma Unreferenced (Resp);
begin
return URL;
end Encode_Redirect_URL;
-- ------------------------------
-- Sends an error response to the client using the specified status. The server
-- defaults to creating the response to look like an HTML-formatted server error
-- page containing the specified message, setting the content type to "text/html",
-- leaving cookies and other headers unmodified. If an error-page declaration
-- has been made for the web application corresponding to the status code passed
-- in, it will be served back in preference to the suggested msg parameter.
--
-- If the response has already been committed, this method throws an
-- IllegalStateException. After using this method, the response should be
-- considered to be committed and should not be written to.
-- ------------------------------
procedure Send_Error (Resp : in out Response;
Error : in Integer;
Message : in String) is
pragma Unreferenced (Message);
begin
Resp.Status := Error;
end Send_Error;
-- Sends an error response to the client using the specified status code
-- and clearing the buffer.
--
-- If the response has already been committed, this method throws an
-- IllegalStateException. After using this method, the response should be
-- considered to be committed and should not be written to.
procedure Send_Error (Resp : in out Response;
Error : in Integer) is
begin
Resp.Status := Error;
end Send_Error;
-- ------------------------------
-- Sends a temporary redirect response to the client using the specified redirect
-- location URL. This method can accept relative URLs; the servlet container must
-- convert the relative URL to an absolute URL before sending the response to the
-- client. If the location is relative without a leading '/' the container
-- interprets it as relative to the current request URI. If the location is relative
-- with a leading '/' the container interprets it as relative to the servlet
-- container root.
--
-- If the response has already been committed, this method throws an
-- IllegalStateException. After using this method, the response should be
-- considered to be committed and should not be written to.
-- ------------------------------
procedure Send_Redirect (Resp : in out Response;
Location : in String) is
begin
Response'Class (Resp).Set_Status (SC_FOUND);
Response'Class (Resp).Set_Header (Name => "Location",
Value => Location);
end Send_Redirect;
-- ------------------------------
-- Sets a response header with the given name and date-value.
-- The date is specified in terms of milliseconds since the epoch.
-- If the header had already been set, the new value overwrites the previous one.
-- The containsHeader method can be used to test for the presence of a header
-- before setting its value.
-- ------------------------------
procedure Set_Date_Header (Resp : in out Response;
Name : in String;
Date : in Ada.Calendar.Time) is
begin
Response'Class (Resp).Set_Header (Name, Util.Dates.RFC7231.Image (Date));
end Set_Date_Header;
-- ------------------------------
-- Adds a response header with the given name and date-value. The date is specified
-- in terms of milliseconds since the epoch. This method allows response headers
-- to have multiple values.
-- ------------------------------
procedure Add_Date_Header (Resp : in out Response;
Name : in String;
Date : in Ada.Calendar.Time) is
begin
Response'Class (Resp).Add_Header (Name, Util.Dates.RFC7231.Image (Date));
end Add_Date_Header;
-- ------------------------------
-- Sets a response header with the given name and integer value.
-- If the header had already been set, the new value overwrites the previous one.
-- The containsHeader method can be used to test for the presence of a header
-- before setting its value.
-- ------------------------------
procedure Set_Int_Header (Resp : in out Response;
Name : in String;
Value : in Integer) is
begin
Response'Class (Resp).Set_Header (Name => Name,
Value => Util.Strings.Image (Value));
end Set_Int_Header;
-- ------------------------------
-- Adds a response header with the given name and integer value. This method
-- allows response headers to have multiple values.
-- ------------------------------
procedure Add_Int_Header (Resp : in out Response;
Name : in String;
Value : in Integer) is
begin
Response'Class (Resp).Add_Header (Name => Name,
Value => Util.Strings.Image (Value));
end Add_Int_Header;
-- ------------------------------
-- Sets the status code for this response. This method is used to set the
-- return status code when there is no error (for example, for the status
-- codes SC_OK or SC_MOVED_TEMPORARILY). If there is an error, and the caller
-- wishes to invoke an error-page defined in the web application, the sendError
-- method should be used instead.
--
-- The container clears the buffer and sets the Location header,
-- preserving cookies and other headers.
-- ------------------------------
procedure Set_Status (Resp : in out Response;
Status : in Natural) is
begin
Resp.Status := Status;
end Set_Status;
-- ------------------------------
-- Get the status code that will be returned by this response.
-- ------------------------------
function Get_Status (Resp : in Response) return Natural is
begin
return Resp.Status;
end Get_Status;
-- ------------------------------
-- Get the output stream
-- ------------------------------
function Get_Output_Stream (Resp : in Response) return Servlet.Streams.Print_Stream is
begin
return Result : Servlet.Streams.Print_Stream do
Result.Initialize (Resp.Stream.all'Access);
end return;
end Get_Output_Stream;
-- ------------------------------
-- Mark the response as being committed.
-- ------------------------------
procedure Set_Committed (Resp : in out Response) is
begin
Resp.Committed := True;
end Set_Committed;
end Servlet.Responses;
|
-----------------------------------------------------------------------
-- asf-beans-injections -- Injection of parameters, headers, cookies in beans
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Objects;
with ASF.Cookies;
package body ASF.Beans.Injections is
-- ------------------------------
-- Inject the request header whose name is defined by Descriptor.Param.
-- ------------------------------
procedure Header (Bean : in out Util.Beans.Basic.Bean'Class;
Descriptor : in Inject_Type;
Request : in ASF.Requests.Request'Class) is
Value : constant String := Request.Get_Header (Descriptor.Param.all);
begin
Bean.Set_Value (Descriptor.Name.all, Util.Beans.Objects.To_Object (Value));
end Header;
-- ------------------------------
-- Inject the request query string parameter whose name is defined by Descriptor.Param.
-- ------------------------------
procedure Query_Param (Bean : in out Util.Beans.Basic.Bean'Class;
Descriptor : in Inject_Type;
Request : in ASF.Requests.Request'Class) is
Value : constant String := Request.Get_Parameter (Descriptor.Param.all);
begin
Bean.Set_Value (Descriptor.Name.all, Util.Beans.Objects.To_Object (Value));
end Query_Param;
-- ------------------------------
-- Inject the request cookie whose name is defined by Descriptor.Param.
-- ------------------------------
procedure Cookie (Bean : in out Util.Beans.Basic.Bean'Class;
Descriptor : in Inject_Type;
Request : in ASF.Requests.Request'Class) is
Cookies : constant ASF.Cookies.Cookie_Array := Request.Get_Cookies;
begin
for I in Cookies'Range loop
if ASF.Cookies.Get_Name (Cookies (I)) = Descriptor.Param.all then
Bean.Set_Value (Descriptor.Name.all,
Util.Beans.Objects.To_Object (ASF.Cookies.Get_Value (Cookies (I))));
end if;
end loop;
end Cookie;
-- ------------------------------
-- Inject the request URI path component whose position is defined by Descriptor.Pos.
-- ------------------------------
procedure Path_Param (Bean : in out Util.Beans.Basic.Bean'Class;
Descriptor : in Inject_Type;
Request : in ASF.Requests.Request'Class) is
URI : constant String := Request.Get_Path_Info;
Pos : Natural := URI'First;
Count : Natural := Descriptor.Pos;
Next_Pos : Natural;
begin
while Count > 0 and Pos < URI'Last loop
Next_Pos := Util.Strings.Index (URI, '/', Pos + 1);
Count := Count - 1;
if Count = 0 then
if Next_Pos = 0 then
Next_Pos := URI'Last;
else
Next_Pos := Next_Pos - 1;
end if;
Bean.Set_Value (Descriptor.Name.all,
Util.Beans.Objects.To_Object (URI (Pos + 1 .. Next_Pos)));
return;
end if;
Pos := Next_Pos;
end loop;
end Path_Param;
-- ------------------------------
-- Inject into the Ada bean a set of information extracted from the request object.
-- The value is obtained from a request header, a cookie, a query string parameter or
-- from a URI path component. The value is injected by using the bean operation
-- <tt>Set_Value</tt>.
-- ------------------------------
procedure Inject (Into : in out Util.Beans.Basic.Bean'Class;
List : in Inject_Array_Type;
Request : in ASF.Requests.Request'Class) is
begin
for I in List'Range loop
List (I).Handler (Into, List (I), Request);
end loop;
end Inject;
end ASF.Beans.Injections;
|
with Ada.Text_IO;
with Ada.Containers.Indefinite_Ordered_Maps;
with PrimeInstances;
with Ada.Numerics.Elementary_Functions;
package body Problem_39 is
package IO renames Ada.Text_IO;
package Math renames Ada.Numerics.Elementary_Functions;
package Positive_Primes renames PrimeInstances.Positive_Primes;
package Positive_Map is new Ada.Containers.Indefinite_Ordered_Maps(Key_Type => Positive,
Element_Type => Positive);
procedure Solve is
maximum : constant Positive := 1_000;
max_f : constant Float := Float(maximum);
-- To generate max_uv, we set u or v to 1 in the formula and solve for the other one.
max_u : constant Positive := Positive((Math.Sqrt(2.0*max_f + 1.0) - 3.0) / 2.0);
max_v : constant Positive := Positive((Math.Sqrt(4.0*max_f + 1.0) - 3.0) / 4.0);
-- This ends up super small. On the order of max ** (1/4)
primes : constant Positive_Primes.Sieve := Positive_Primes.Generate_Sieve(Positive(Math.Sqrt(Float(max_u))));
counts : Positive_Map.Map;
max_count : Positive := 1;
max_number : Positive := 12; -- 3 + 4 + 5
function Coprime(u,v : in Positive) return Boolean is
begin
for prime_index in primes'Range loop
declare
prime : constant Positive := primes(prime_index);
begin
if u mod prime = 0 and v mod prime = 0 then
return False;
end if;
end;
end loop;
return True;
end CoPrime;
procedure Add_Count(sum : in Positive) is
use Positive_Map;
location : constant Positive_Map.Cursor := counts.Find(sum);
begin
if location /= Positive_Map.No_Element then
declare
new_count : constant Positive := Positive_Map.Element(location) + 1;
begin
if new_count > max_count then
max_count := new_count;
max_number := sum;
end if;
counts.Replace_Element(location, new_count);
end;
else
counts.Insert(sum, 1);
end if;
end;
begin
for u in 1 .. max_u loop
-- Not primitive is u is odd
if u mod 2 = 1 then
V_Loop:
for v in 1 .. max_v loop
-- Not primitive unless the numbers are coprime.
if Coprime(u, v) then
declare
sum : constant Positive := 2*(u**2 + 3*u*v + 2*v**2);
begin
if sum <= maximum then
declare
scaled_sum : Positive := sum;
begin
loop
Add_Count(scaled_sum);
scaled_sum := scaled_sum + sum;
exit when scaled_sum > maximum;
end loop;
end;
else
exit V_Loop;
end if;
end;
end if;
end loop V_Loop;
end if;
end loop;
IO.Put_Line(Positive'Image(max_number));
end Solve;
end Problem_39;
|
package body EU_Projects.Identifiers is
-----------
-- To_ID --
-----------
function To_ID
(X : String)
return Identifier
is
begin
if not Is_Valid_Identifier (X) then
raise Bad_Identifier with X;
end if;
return Identifier'(ID => ID_Names.To_Bounded_String (To_Lower (X)));
end To_ID;
end EU_Projects.Identifiers;
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . K N D _ C O N V --
-- --
-- S p e c --
-- --
-- Copyright (C) 1995-2011, Free Software Foundation, Inc. --
-- --
-- ASIS-for-GNAT is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 2, or (at your option) any later --
-- version. ASIS-for-GNAT is distributed in the hope that it will be use- --
-- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- --
-- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General --
-- Public License for more details. You should have received a copy of the --
-- GNU General Public License distributed with ASIS-for-GNAT; see file --
-- COPYING. If not, write to the Free Software Foundation, 51 Franklin --
-- Street, Fifth Floor, Boston, MA 02110-1301, USA. --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the --
-- Software Engineering Laboratory of the Swiss Federal Institute of --
-- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the --
-- Scientific Research Computer Center of Moscow State University (SRCC --
-- MSU), Russia, with funding partially provided by grants from the Swiss --
-- National Science Foundation and the Swiss Academy of Engineering --
-- Sciences. ASIS-for-GNAT is now maintained by AdaCore --
-- (http://www.adacore.com). --
-- --
------------------------------------------------------------------------------
with Asis;
with A4G.Int_Knds; use A4G.Int_Knds;
package A4G.Knd_Conv is
--------------------------------------
-- Element Classification Functions --
--------------------------------------
-- The following functions convert the Internal Element Kind value
-- given as their argument into the corresponding value of the
-- corresponding Asis Element Classification subordinate kind.
-- Not_A_XXX is returned if the argument does not belong to the
-- corresponding internal classification subtype.
function Asis_From_Internal_Kind
(Internal_Kind : Internal_Element_Kinds)
return Asis.Element_Kinds;
function Pragma_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Pragma_Kinds;
function Defining_Name_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Defining_Name_Kinds;
function Declaration_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Declaration_Kinds;
function Definition_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Definition_Kinds;
function Type_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Type_Kinds;
function Formal_Type_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Formal_Type_Kinds;
function Access_Type_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Access_Type_Kinds;
function Root_Type_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Root_Type_Kinds;
-- --|A2005 start
function Access_Definition_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Access_Definition_Kinds;
function Interface_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Interface_Kinds;
-- --|A2005 end
function Constraint_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Constraint_Kinds;
function Discrete_Range_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Discrete_Range_Kinds;
function Expression_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Expression_Kinds;
function Operator_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Operator_Kinds;
function Attribute_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Attribute_Kinds;
function Association_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Association_Kinds;
function Statement_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Statement_Kinds;
function Path_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Path_Kinds;
function Clause_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Clause_Kinds;
function Representation_Clause_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Representation_Clause_Kinds;
-------------------------------------
-- Additional Classification items --
-------------------------------------
function Def_Operator_Kind
(Op_Kind : Internal_Element_Kinds)
return Internal_Element_Kinds;
-- this function "converts" the value of Internal_Operator_Symbol_Kinds
-- into the corresponding value of Internal_Defining_Operator_Kinds
-- It is an error to call it to an Internal_Element_Kinds value which
-- does not belong to Internal_Operator_Symbol_Kinds
end A4G.Knd_Conv;
|
-------------------------------------------------------------------------------
-- --
-- 0MQ Ada-binding --
-- --
-- Z M Q --
-- --
-- B o d y --
-- --
-- Copyright (C) 2020-2030, per.s.sandberg@bahnhof.se --
-- --
-- Permission is hereby granted, free of charge, to any person obtaining a --
-- copy of this software and associated documentation files --
-- (the "Software"), to deal in the Software without restriction, including --
-- without limitation the rights to use, copy, modify, merge, publish, --
-- distribute, sublicense, and / or sell copies of the Software, and to --
-- permit persons to whom the Software is furnished to do so, subject to --
-- the following conditions : --
-- --
-- The above copyright notice and this permission notice shall be included --
-- in all copies or substantial portions of the Software. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS --
-- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF --
-- MERCHANTABILITY, --
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL --
-- THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR --
-- OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, --
-- ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR --
-- OTHER DEALINGS IN THE SOFTWARE. --
-------------------------------------------------------------------------------
with Interfaces.C;
with Interfaces.C.Strings;
with ZMQ.Low_Level;
with GNAT.IO;
package body ZMQ is
use Interfaces.C;
-------------------
-- Error_Message --
-------------------
function Error_Message (No : Integer) return String is
S : constant String := No'Img;
use all type Interfaces.C.Strings.chars_ptr;
begin
return "[" & S (S'First + 1 .. S'Last) & "] " &
Value (ZMQ.Low_Level.zmq_strerror (int (No)));
end Error_Message;
function Library_Version return Version_Type is
Major : aliased int;
Minor : aliased int;
Patch : aliased int;
begin
return Ret : Version_Type do
Low_Level.zmq_version (Major'Access,
Minor'Access,
Patch'Access);
Ret := (Natural (Major), Natural (Minor), Natural (Patch));
end return;
end Library_Version;
function Image (Item : Version_Type) return String is
S1 : constant String := Item.Major'Img;
S2 : constant String := Item.Minor'Img;
S3 : constant String := Item.Patch'Img;
begin
return S1 (S1'First + 1 .. S1'Last) & "." &
S2 (S2'First + 1 .. S2'Last) & "." &
S3 (S3'First + 1 .. S3'Last);
end Image;
procedure Validate_Library_Version is
Lib_Version : constant Version_Type := Library_Version;
begin
if Binding_Version.Major /= Lib_Version.Major then
GNAT.IO.Put_Line
("Warning libzmq: " & Image (Lib_Version) &
" found, binding version is: " & Image (Binding_Version));
end if;
end Validate_Library_Version;
end ZMQ;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- S Y S T E M . T E X T _ I O --
-- --
-- S p e c --
-- --
-- Copyright (C) 2011-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 package defines the console I/O interface for the simplified version
-- of Ada.Text_IO used in ZFP runtimes or bare board platforms.
package System.Text_IO is
pragma No_Elaboration_Code_All;
pragma Preelaborate;
-- The interface uses two subprograms for each direction: one for the ready
-- status and one for the action. This is done on purpose to avoid busy
-- waiting loops in the body.
procedure Initialize;
-- Must be called before all other subprograms to initialize the service.
-- We avoid the use of elaboration to make this package preelaborated.
Initialized : Boolean := False;
-- Set to True (by Initialize) when the service is initialized. Having this
-- variable outside allows reinitialization of the service.
--------------
-- Output --
--------------
function Is_Tx_Ready return Boolean;
-- Return True if it is possible to call Put. This function can be used for
-- checking that the output register of an UART is empty before write a
-- new character on it. For non blocking output system, this function can
-- always return True. Once this function has returned True, it must always
-- return True before the next call to Put.
procedure Put (C : Character);
-- Write a character on the console. Must be called only when Is_Tx_Ready
-- has returned True before, otherwise its behavior is undefined.
function Use_Cr_Lf_For_New_Line return Boolean;
-- Return True if New_Line should output CR + LF, otherwise it will output
-- only LF.
-------------
-- Input --
-------------
function Is_Rx_Ready return Boolean;
-- Return True is a character can be read by Get. On systems where is it
-- difficult or impossible to know wether a character is available, this
-- function can always return True and Get will be blocking.
function Get return Character;
-- Read a character from the console. Must be called only when Is_Rx_Ready
-- has returned True, otherwise behavior is undefined.
end System.Text_IO;
|
-- { dg-do run }
-- { dg-options "-O" }
with Loop_Optimization3_Pkg; use Loop_Optimization3_Pkg;
procedure Loop_Optimization3 is
type Arr is array (Integer range -3 .. 3) of Integer;
C : constant Arr := (1, others => F(2));
begin
if C /= (1, 2, 2, 2, 2, 2, 2) then
raise Program_Error;
end if;
end;
|
package Example1 is
procedure Sense ;
procedure Handle_Deadline;
end Example1;
|
-- BinToAsc.Base85
-- Various binary data to ASCII codecs known as Base85, ASCII85 etc
-- Copyright (c) 2015, James Humphry - see LICENSE file for details
package body BinToAsc.Base85 is
Reverse_Alphabet : constant Reverse_Alphabet_Lookup
:= Make_Reverse_Alphabet(Alphabet, True);
type Bin_Frame is mod 2**32;
subtype String_Frame is String(1..5);
--
-- Base85_To_String
--
procedure Reset (C : out Base85_To_String) is
begin
C := (State => Ready,
Next_Index => 0,
Buffer => (others => 0));
end Reset;
procedure Process
(C : in out Base85_To_String;
Input : in Bin;
Output : out String;
Output_Length : out Natural)
is
Input_Frame : Bin_Frame;
Output_Frame : String_Frame;
begin
C.Buffer(C.Next_Index) := Input;
if C.Next_Index /= 3 then
Output := (others => ' ');
Output_Length := 0;
C.Next_Index := C.Next_Index + 1;
else
C.Next_Index := 0;
Input_Frame := Bin_Frame(C.Buffer(0)) * 2**24 or
Bin_Frame(C.Buffer(1)) * 2**16 or
Bin_Frame(C.Buffer(2)) * 2**8 or
Bin_Frame(C.Buffer(3));
for I in reverse 1..5 loop
Output_Frame(I) := Alphabet(Bin(Input_Frame mod 85));
Input_Frame := Input_Frame / 85;
end loop;
Output(Output'First..Output'First + 4) := Output_Frame;
Output_Length := 5;
end if;
end Process;
procedure Process
(C : in out Base85_To_String;
Input : in Bin_Array;
Output : out String;
Output_Length : out Natural)
is
Input_Frame : Bin_Frame;
Output_Frame : String_Frame;
Output_Index : Integer := Output'First;
begin
for I in Input'Range loop
C.Buffer(C.Next_Index) := Input(I);
if C.Next_Index /= 3 then
C.Next_Index := C.Next_Index + 1;
else
C.Next_Index := 0;
Input_Frame := Bin_Frame(C.Buffer(0)) * 2**24 or
Bin_Frame(C.Buffer(1)) * 2**16 or
Bin_Frame(C.Buffer(2)) * 2**8 or
Bin_Frame(C.Buffer(3));
for I in reverse 1..5 loop
Output_Frame(I) := Alphabet(Bin(Input_Frame mod 85));
Input_Frame := Input_Frame / 85;
end loop;
Output (Output_Index .. Output_Index + 4) := Output_Frame;
Output_Index := Output_Index + 5;
end if;
end loop;
Output_Length := Output_Index - Output'First;
end Process;
procedure Complete
(C : in out Base85_To_String;
Output : out String;
Output_Length : out Natural)
is
Input_Frame : Bin_Frame;
Output_Frame : String_Frame;
begin
C.State := Completed;
if C.Next_Index = 0 then
Output_Length := 0;
Output := (others => ' ');
else
C.Buffer(C.Next_Index .. 3) := (others => 0);
Input_Frame := Bin_Frame(C.Buffer(0)) * 2**24 or
Bin_Frame(C.Buffer(1)) * 2**16 or
Bin_Frame(C.Buffer(2)) * 2**8 or
Bin_Frame(C.Buffer(3));
for I in reverse 1..5 loop
Output_Frame(I) := Alphabet(Bin(Input_Frame mod 85));
Input_Frame := Input_Frame / 85;
end loop;
Output(Output'First..Output'First + 4) := Output_Frame;
Output_Length := 5 - (4 - Integer(C.Next_Index));
end if;
end Complete;
function To_String_Private is
new BinToAsc.To_String(Codec => Base85_To_String);
function To_String (Input : in Bin_Array) return String
renames To_String_Private;
--
-- Base85_To_Bin
--
procedure Reset (C : out Base85_To_Bin) is
begin
C := (State => Ready,
Next_Index => 0,
Buffer => (others => 0));
end Reset;
procedure Process (C : in out Base85_To_Bin;
Input : in Character;
Output : out Bin_Array;
Output_Length : out Bin_Array_Index)
is
Input_Bin : Bin;
Output_Frame : Bin_Frame;
MSB_Limit : Bin_Frame;
begin
Input_Bin := Reverse_Alphabet(Input);
if Input_Bin = Invalid_Character_Input then
C.State := Failed;
Output := (others => 0);
Output_Length := 0;
else
C.Buffer(C.Next_Index) := Input_Bin;
if C.Next_Index /= 4 then
Output := (others => 0);
Output_Length := 0;
C.Next_Index := C.Next_Index + 1;
else
C.Next_Index := 0;
Output_Frame := Bin_Frame(C.Buffer(4)) +
Bin_Frame(C.Buffer(3)) * 85 +
Bin_Frame(C.Buffer(2)) * 85 * 85 +
Bin_Frame(C.Buffer(1)) * 85 * 85 * 85;
MSB_Limit := (not Output_Frame) / (85*85*85*85);
if Bin_Frame(C.Buffer(0)) > MSB_Limit then
C.State := Failed;
Output := (others => 0);
Output_Length := 0;
else
Output_Frame := Output_Frame +
Bin_Frame(C.Buffer(0))*85*85*85*85;
Output(Output'First..Output'First+3) :=
(Bin((Output_Frame / 2**24)),
Bin((Output_Frame / 2**16) and 255),
Bin((Output_Frame / 2**8) and 255),
Bin((Output_Frame) and 255),
others => 0);
Output_Length := 4;
end if;
end if;
end if;
end Process;
procedure Process (C : in out Base85_To_Bin;
Input : in String;
Output : out Bin_Array;
Output_Length : out Bin_Array_Index)
is
Input_Bin : Bin;
Output_Frame : Bin_Frame;
MSB_Limit : Bin_Frame;
Output_Index : Bin_Array_Index := Output'First;
begin
for I in Input'Range loop
Input_Bin := Reverse_Alphabet(Input(I));
if Input_Bin = Invalid_Character_Input then
C.State := Failed;
exit;
end if;
C.Buffer(C.Next_Index) := Input_Bin;
if C.Next_Index /= 4 then
C.Next_Index := C.Next_Index + 1;
else
C.Next_Index := 0;
Output_Frame := Bin_Frame(C.Buffer(4)) +
Bin_Frame(C.Buffer(3)) * 85 +
Bin_Frame(C.Buffer(2)) * 85 * 85 +
Bin_Frame(C.Buffer(1)) * 85 * 85 * 85;
MSB_Limit := (not Output_Frame) / (85*85*85*85);
if Bin_Frame(C.Buffer(0)) > MSB_Limit then
C.State := Failed;
exit;
else
Output_Frame := Output_Frame +
Bin_Frame(C.Buffer(0))*85*85*85*85;
Output(Output_Index..Output_Index+3) :=
(
Bin((Output_Frame / 2**24)),
Bin((Output_Frame / 2**16) and 255),
Bin((Output_Frame / 2**8) and 255),
Bin((Output_Frame) and 255)
);
Output_Index := Output_Index + 4;
end if;
end if;
end loop;
if C.State = Failed then
Output := (others => 0);
Output_Length := 0;
else
Output(Output_Index .. Output'Last) := (others => 0);
Output_Length := Output_Index - Output'First;
end if;
end Process;
procedure Complete (C : in out Base85_To_Bin;
Output : out Bin_Array;
Output_Length : out Bin_Array_Index)
is
Output_Frame : Bin_Frame;
MSB_Limit : Bin_Frame;
begin
if C.State = Ready then
if C.Next_Index = 0 then
Output := (others => 0);
Output_Length := 0;
C.State := Completed;
elsif C.Next_Index = 1 then
-- This is an invalid state as one Base85 character is not enough
-- to represent a single byte.
Output := (others => 0);
Output_Length := 0;
C.State := Failed;
else
C.Buffer(C.Next_Index .. 4) := (others => 84);
-- Note padding must be all ones for decoding even though it
-- was all zeros for encoding. Base85 <-> Binary is not a
-- simple rearrangement of bits so high and low bits can interact.
Output_Frame := Bin_Frame(C.Buffer(4)) +
Bin_Frame(C.Buffer(3)) * 85 +
Bin_Frame(C.Buffer(2)) * 85 * 85 +
Bin_Frame(C.Buffer(1)) * 85 * 85 * 85;
MSB_Limit := (not Output_Frame) / (85*85*85*85);
if Bin_Frame(C.Buffer(0)) > MSB_Limit then
Output := (others => 0);
Output_Length := 0;
C.State := Failed;
else
Output_Frame := Output_Frame +
Bin_Frame(C.Buffer(0))*85*85*85*85;
Output :=
(Bin((Output_Frame / 2**24)),
Bin((Output_Frame / 2**16) and 255),
Bin((Output_Frame / 2**8) and 255),
Bin((Output_Frame) and 255),
others => 0);
Output_Length := Bin_Array_Index(C.Next_Index - 1);
C.State := Completed;
end if;
end if;
else
Output := (others => 0);
Output_Length := 0;
end if;
end Complete;
function To_Bin_Private is new BinToAsc.To_Bin(Codec => Base85_To_Bin);
function To_Bin (Input : in String) return Bin_Array renames To_Bin_Private;
begin
-- The following Compile_Time_Error test is silently ignored by GNAT GPL 2015,
-- although it does appear to be a static boolean expression as required by
-- the user guide. It works if converted to a run-time test so it has been
-- left in, in the hope that in a future version of GNAT it will actually be
-- tested.
pragma Warnings (GNATprove, Off, "Compile_Time_Error");
pragma Compile_Time_Error ((for some X in 1..Alphabet'Last =>
(for some Y in 0..X-1 =>
Alphabet(Y) = Alphabet(X)
)
),
"Duplicate letter in alphabet for Base85 codec.");
pragma Warnings (GNATprove, On, "Compile_Time_Error");
end BinToAsc.Base85;
|
--//////////////////////////////////////////////////////////
-- SFML - Simple and Fast Multimedia Library
-- Copyright (C) 2007-2015 Laurent Gomila (laurent@sfml-dev.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.
--//////////////////////////////////////////////////////////
--//////////////////////////////////////////////////////////
with Sf.Audio.SoundStatus;
with Sf.System.Vector3;
with Sf.System.Time;
package Sf.Audio.Sound is
--//////////////////////////////////////////////////////////
--/ @brief Create a new sound
--/
--/ @return A new sfSound object
--/
--//////////////////////////////////////////////////////////
function create return sfSound_Ptr;
--//////////////////////////////////////////////////////////
--/ @brief Create a new sound by copying an existing one
--/
--/ @param sound Sound to copy
--/
--/ @return A new sfSound object which is a copy of @a sound
--/
--//////////////////////////////////////////////////////////
function copy (sound : sfSound_Ptr) return sfSound_Ptr;
--//////////////////////////////////////////////////////////
--/ @brief Destroy a sound
--/
--/ @param sound Sound to destroy
--/
--//////////////////////////////////////////////////////////
procedure destroy (sound : sfSound_Ptr);
--//////////////////////////////////////////////////////////
--/ @brief Start or resume playing a sound
--/
--/ This function starts the sound if it was stopped, resumes
--/ it if it was paused, and restarts it from beginning if it
--/ was it already playing.
--/ This function uses its own thread so that it doesn't block
--/ the rest of the program while the sound is played.
--/
--/ @param sound Sound object
--/
--//////////////////////////////////////////////////////////
procedure play (sound : sfSound_Ptr);
--//////////////////////////////////////////////////////////
--/ @brief Pause a sound
--/
--/ This function pauses the sound if it was playing,
--/ otherwise (sound already paused or stopped) it has no effect.
--/
--/ @param sound Sound object
--/
--//////////////////////////////////////////////////////////
procedure pause (sound : sfSound_Ptr);
--//////////////////////////////////////////////////////////
--/ @brief Stop playing a sound
--/
--/ This function stops the sound if it was playing or paused,
--/ and does nothing if it was already stopped.
--/ It also resets the playing position (unlike sfSound_pause).
--/
--/ @param sound Sound object
--/
--//////////////////////////////////////////////////////////
procedure stop (sound : sfSound_Ptr);
--//////////////////////////////////////////////////////////
--/ @brief Set the source buffer containing the audio data to play
--/
--/ It is important to note that the sound buffer is not copied,
--/ thus the sfSoundBuffer object must remain alive as long
--/ as it is attached to the sound.
--/
--/ @param sound Sound object
--/ @param buffer Sound buffer to attach to the sound
--/
--//////////////////////////////////////////////////////////
procedure setBuffer (sound : sfSound_Ptr;
buffer : sfSoundBuffer_Ptr);
--//////////////////////////////////////////////////////////
--/ @brief Get the audio buffer attached to a sound
--/
--/ @param sound Sound object
--/
--/ @return Sound buffer attached to the sound (can be NULL)
--/
--//////////////////////////////////////////////////////////
function getBuffer (sound : sfSound_Ptr) return sfSoundBuffer_Ptr;
--//////////////////////////////////////////////////////////
--/ @brief Set whether or not a sound should loop after reaching the end
--/
--/ If set, the sound will restart from beginning after
--/ reaching the end and so on, until it is stopped or
--/ sfSound_setLoop(sound, sfFalse) is called.
--/ The default looping state for sounds is false.
--/
--/ @param sound Sound object
--/ @param inLoop sfTrue to play in loop, sfFalse to play once
--/
--//////////////////////////////////////////////////////////
procedure setLoop (sound : sfSound_Ptr; inLoop : sfBool);
--//////////////////////////////////////////////////////////
--/ @brief Tell whether or not a sound is in loop mode
--/
--/ @param sound Sound object
--/
--/ @return sfTrue if the sound is looping, sfFalse otherwise
--/
--//////////////////////////////////////////////////////////
function getLoop (sound : sfSound_Ptr) return sfBool;
--//////////////////////////////////////////////////////////
--/ @brief Get the current status of a sound (stopped, paused, playing)
--/
--/ @param sound Sound object
--/
--/ @return Current status
--/
--//////////////////////////////////////////////////////////
function getStatus (sound : sfSound_Ptr) return Sf.Audio.SoundStatus.sfSoundStatus;
--//////////////////////////////////////////////////////////
--/ @brief Set the pitch of a sound
--/
--/ The pitch represents the perceived fundamental frequency
--/ of a sound; thus you can make a sound more acute or grave
--/ by changing its pitch. A side effect of changing the pitch
--/ is to modify the playing speed of the sound as well.
--/ The default value for the pitch is 1.
--/
--/ @param sound Sound object
--/ @param pitch New pitch to apply to the sound
--/
--//////////////////////////////////////////////////////////
procedure setPitch (sound : sfSound_Ptr; pitch : float);
--//////////////////////////////////////////////////////////
--/ @brief Set the volume of a sound
--/
--/ The volume is a value between 0 (mute) and 100 (full volume).
--/ The default value for the volume is 100.
--/
--/ @param sound Sound object
--/ @param volume Volume of the sound
--/
--//////////////////////////////////////////////////////////
procedure setVolume (sound : sfSound_Ptr; volume : float);
--//////////////////////////////////////////////////////////
--/ @brief Set the 3D position of a sound in the audio scene
--/
--/ Only sounds with one channel (mono sounds) can be
--/ spatialized.
--/ The default position of a sound is (0, 0, 0).
--/
--/ @param sound Sound object
--/ @param position Position of the sound in the scene
--/
--//////////////////////////////////////////////////////////
procedure setPosition (sound : sfSound_Ptr; position : Sf.System.Vector3.sfVector3f);
--//////////////////////////////////////////////////////////
--/ @brief Make the sound's position relative to the listener or absolute
--/
--/ Making a sound relative to the listener will ensure that it will always
--/ be played the same way regardless the position of the listener.
--/ This can be useful for non-spatialized sounds, sounds that are
--/ produced by the listener, or sounds attached to it.
--/ The default value is false (position is absolute).
--/
--/ @param sound Sound object
--/ @param relative sfTrue to set the position relative, sfFalse to set it absolute
--/
--//////////////////////////////////////////////////////////
procedure setRelativeToListener (sound : sfSound_Ptr; relative : sfBool);
--//////////////////////////////////////////////////////////
--/ @brief Set the minimum distance of a sound
--/
--/ The "minimum distance" of a sound is the maximum
--/ distance at which it is heard at its maximum volume. Further
--/ than the minimum distance, it will start to fade out according
--/ to its attenuation factor. A value of 0 ("inside the head
--/ of the listener") is an invalid value and is forbidden.
--/ The default value of the minimum distance is 1.
--/
--/ @param sound Sound object
--/ @param distance New minimum distance of the sound
--/
--//////////////////////////////////////////////////////////
procedure setMinDistance (sound : sfSound_Ptr; distance : float);
--//////////////////////////////////////////////////////////
--/ @brief Set the attenuation factor of a sound
--/
--/ The attenuation is a multiplicative factor which makes
--/ the sound more or less loud according to its distance
--/ from the listener. An attenuation of 0 will produce a
--/ non-attenuated sound, i.e. its volume will always be the same
--/ whether it is heard from near or from far. On the other hand,
--/ an attenuation value such as 100 will make the sound fade out
--/ very quickly as it gets further from the listener.
--/ The default value of the attenuation is 1.
--/
--/ @param sound Sound object
--/ @param attenuation New attenuation factor of the sound
--/
--//////////////////////////////////////////////////////////
procedure setAttenuation (sound : sfSound_Ptr; attenuation : float);
--//////////////////////////////////////////////////////////
--/ @brief Change the current playing position of a sound
--/
--/ The playing position can be changed when the sound is
--/ either paused or playing.
--/
--/ @param sound Sound object
--/ @param timeOffset New playing position
--/
--//////////////////////////////////////////////////////////
procedure setPlayingOffset (sound : sfSound_Ptr; timeOffset : Sf.System.Time.sfTime);
--//////////////////////////////////////////////////////////
--/ @brief Get the pitch of a sound
--/
--/ @param sound Sound object
--/
--/ @return Pitch of the sound
--/
--//////////////////////////////////////////////////////////
function getPitch (sound : sfSound_Ptr) return float;
--//////////////////////////////////////////////////////////
--/ @brief Get the volume of a sound
--/
--/ @param sound Sound object
--/
--/ @return Volume of the sound, in the range [0, 100]
--/
--//////////////////////////////////////////////////////////
function getVolume (sound : sfSound_Ptr) return float;
--//////////////////////////////////////////////////////////
--/ @brief Get the 3D position of a sound in the audio scene
--/
--/ @param sound Sound object
--/
--/ @return Position of the sound in the world
--/
--//////////////////////////////////////////////////////////
function getPosition (sound : sfSound_Ptr) return Sf.System.Vector3.sfVector3f;
--//////////////////////////////////////////////////////////
--/ @brief Tell whether a sound's position is relative to the
--/ listener or is absolute
--/
--/ @param sound Sound object
--/
--/ @return sfTrue if the position is relative, sfFalse if it's absolute
--/
--//////////////////////////////////////////////////////////
function isRelativeToListener (sound : sfSound_Ptr) return sfBool;
--//////////////////////////////////////////////////////////
--/ @brief Get the minimum distance of a sound
--/
--/ @param sound Sound object
--/
--/ @return Minimum distance of the sound
--/
--//////////////////////////////////////////////////////////
function getMinDistance (sound : sfSound_Ptr) return float;
--//////////////////////////////////////////////////////////
--/ @brief Get the attenuation factor of a sound
--/
--/ @param sound Sound object
--/
--/ @return Attenuation factor of the sound
--/
--//////////////////////////////////////////////////////////
function getAttenuation (sound : sfSound_Ptr) return float;
--//////////////////////////////////////////////////////////
--/ @brief Get the current playing position of a sound
--/
--/ @param sound Sound object
--/
--/ @return Current playing position
--/
--//////////////////////////////////////////////////////////
function getPlayingOffset (sound : sfSound_Ptr) return Sf.System.Time.sfTime;
private
pragma Import (C, create, "sfSound_create");
pragma Import (C, copy, "sfSound_copy");
pragma Import (C, destroy, "sfSound_destroy");
pragma Import (C, play, "sfSound_play");
pragma Import (C, pause, "sfSound_pause");
pragma Import (C, stop, "sfSound_stop");
pragma Import (C, setBuffer, "sfSound_setBuffer");
pragma Import (C, getBuffer, "sfSound_getBuffer");
pragma Import (C, setLoop, "sfSound_setLoop");
pragma Import (C, getLoop, "sfSound_getLoop");
pragma Import (C, getStatus, "sfSound_getStatus");
pragma Import (C, setPitch, "sfSound_setPitch");
pragma Import (C, setVolume, "sfSound_setVolume");
pragma Import (C, setPosition, "sfSound_setPosition");
pragma Import (C, setRelativeToListener, "sfSound_setRelativeToListener");
pragma Import (C, setMinDistance, "sfSound_setMinDistance");
pragma Import (C, setAttenuation, "sfSound_setAttenuation");
pragma Import (C, setPlayingOffset, "sfSound_setPlayingOffset");
pragma Import (C, getPitch, "sfSound_getPitch");
pragma Import (C, getVolume, "sfSound_getVolume");
pragma Import (C, getPosition, "sfSound_getPosition");
pragma Import (C, isRelativeToListener, "sfSound_isRelativeToListener");
pragma Import (C, getMinDistance, "sfSound_getMinDistance");
pragma Import (C, getAttenuation, "sfSound_getAttenuation");
pragma Import (C, getPlayingOffset, "sfSound_getPlayingOffset");
end Sf.Audio.Sound;
|
package My_Package is
-- @summary
-- Test package.
--
subtype Count is Long_Long_Integer range 0 .. Long_Long_Integer'Last;
type Arr is array (Positive range <>) of Natural;
type Enum is (One, Two, Three);
----------------------------------------------------------------------------
function My_Function (A : Arr) return Boolean
with Post =>
My_Function'Result = (for all Z in A'Range => A(Z) = A(A'First));
-- @param A An array.
-- @return True if all array elements are equal, False otherwise.
----------------------------------------------------------------------------
type My_Interface is interface;
not overriding
function My_Primitive (Obj : in out My_Interface) return Count is abstract;
-- @param Obj My_Interface object.
-- @return Next term of the Fibonacci Sequence.
----------------------------------------------------------------------------
type My_Implementation is new My_Interface with private;
not overriding function Create return My_Implementation;
-- @return My_Implementation object.
overriding
function My_Primitive (Obj : in out My_Implementation) return Count;
-- @param Obj My_Implementation object.
-- @return Next term of the Fibonacci Sequence.
----------------------------------------------------------------------------
private
My_Package_Range_Error : exception;
type My_Implementation is new My_Interface with
record
K : Count := 0;
Prev_Prev_Term, Prev_Term : Count := 1;
end record;
end My_Package;
|
with Numerics, Numerics.Dense_Matrices, Ada.Text_IO, Dense_AD;
use Numerics, Numerics.Dense_Matrices, Ada.Text_IO;
procedure LU_Test is
use Real_IO, Int_IO;
N : constant Nat := 5;
package AD is new Dense_AD (N); use AD;
Example_1 : constant Real_Matrix := ((1.0, 3.0, 5.0),
(2.0, 4.0, 7.0),
(1.0, 1.0, 0.0));
Inv, L1, U1 : Real_Matrix (Example_1'Range (1), Example_1'Range (2));
P1 : Int_Array (Example_1'Range (1));
Example_2 : constant Real_Matrix := ((11.0, 9.0, 24.0, 2.0),
(1.0, 5.0, 2.0, 6.0),
(3.0, 17.0, 18.0, 1.0),
(2.0, 5.0, 7.0, 1.0));
L2, U2 : Real_Matrix (Example_2'Range (1), Example_2'Range (2));
P2 : Int_Array (Example_2'Range (1));
X : Real_Vector := (-1.0, 3.0, 2.0);
begin
LU_Decomposition (A => Example_1,
P => P1,
L => L1,
U => U1);
LU_Decomposition (A => Example_2,
P => P2,
L => L2,
U => U2);
Put_Line ("Example 1: ");
Print (Example_1);
Put_Line ("P: ");
for P of P1 loop
Put (P, 3); Put (", ");
end loop;
New_Line;
Put_Line ("L: ");
Print (L1);
Put_Line ("U: ");
Print (U1);
Put ("Det = "); Put (Determinant (P1, L1, U1), Exp => 0); New_Line;
Inv := Inverse (Example_1);
Put_Line ("Inv: ");
Print (Inv);
Inv := Inv * Example_1;
New_Line;
Print (Inv);
New_Line;
X := Solve (P1, L1, U1, X);
Put_Line ("X: ");
for Item of X loop
Put (Item, Aft => 3, Exp => 0); New_Line;
end loop;
New_Line;
-- Put_Line ("Example 2: ");
-- Print (Example_2);
-- Put_Line ("P: ");
-- for P of P2 loop
-- Put (P, 3); Put (", ");
-- end loop;
-- New_Line;
-- Put_Line ("L: ");
-- Print (L2);
-- Put_Line ("U: ");
-- Print (U2);
-- Put ("Det = "); Put (Determinant (P2, L2, U2), Exp => 0); New_Line;
-- Put ("Det = "); Put (Determinant (Example_2), Exp => 0); New_Line;
-- New_Line;
-- Put_Line ("----------------------------------------");
-- Num := Number_Of_Swaps ((1, 2, 3, 4, 5));
-- Put ("Number of swaps = "); Put (Num); New_Line;
-- Put_Line ("----------------------------------------");
end LU_Test;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2016 onox <denkpadje@gmail.com>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Strings.Bounded;
with Ada.Strings.Unbounded;
with JSON.Types;
with GL.Types;
private package Orka.glTF is
pragma Preelaborate;
package SU renames Ada.Strings.Unbounded;
Maximum_Name_Length : constant := 64;
package Name_Strings is new Ada.Strings.Bounded.Generic_Bounded_Length
(Max => Maximum_Name_Length);
function To_String (Value : Name_Strings.Bounded_String) return String
renames Name_Strings.To_String;
package Types is new JSON.Types (Long_Integer, GL.Types.Single);
subtype Natural_Optional is Integer range -1 .. Integer'Last;
Undefined : constant := Natural_Optional'First;
end Orka.glTF;
|
separate (Command_Line_Interface)
procedure Read_Command_Line (Command_Args : out Command_Line_Type) is
procedure Get_Foreign (P : out String);
pragma Interface (External, Get_Foreign);
pragma Import_Valued_Procedure (Get_Foreign,
"LIB$GET_FOREIGN",
(String), (Descriptor (S)));
begin
Get_Foreign (Command_Args);
end Read_Command_Line;
|
-- { dg-do compile }
pragma Warnings (Off, "*bits of*unused");
package warnstar is
type r is record
a : integer;
end record;
for r use record
a at 0 range 0 .. 1023;
end record;
end warnstar;
|
-- { dg-do compile }
with Array17_Pkg; use Array17_Pkg;
procedure Array17 is
X : aliased Varray := (1 .. 8 => 1.0);
Y : Varray (1 .. 8) := (others => -1.0);
R : Varray (1 .. 8);
begin
R (1 .. 4) := Y (1 .. 4) + X (1 .. 4);
end;
|
with Es_Primo;
with Listas;
procedure Crear_Sublista_4Primos is new Listas.Crear_Sublista(Cuantos => 4, Filtro => Es_Primo); |
-- see OpenUxAS\src\Communications\MessageAttributes.h
package UxAS.Comms.Data is
type Message_Attributes is tagged private;
type Message_Attributes_Ref is access all Message_Attributes;
type Message_Attributes_View is access constant Message_Attributes;
type Any_Message_Attributes is access Message_Attributes'Class;
Minimum_Delimited_Address_Attribute_Message_String_Length : constant := 8;
Attribute_Count : constant := 5;
-- static const std::string&
-- s_typeName() { static std::string s_string("MessageAttributes"); return (s_string); };
Type_Name : constant String := "MessageAttributes";
-- bool
-- setAttributes(const std::string contentType,
-- const std::string descriptor,
-- const std::string sourceGroup,
-- const std::string sourceEntityId,
-- const std::string sourceServiceId)
procedure Set_Attributes
(This : in out Message_Attributes;
Content_Type : String;
Descriptor : String;
Source_Group : String; -- can be an empty string
Source_Entity_Id : String;
Source_Service_Id : String;
Result : out Boolean);
-- with Pre'Class =>
-- Content_Type'Length in 1 .. Content_Type_Max_Length and then
-- Descriptor'Length in 1 .. Descriptor_Max_Length and then
-- Source_Group'Length <= Source_Group_Max_Length and then
-- Source_Entity_Id'Length in 1 .. Source_Entity_Id_Max_Length and then
-- Source_Service_Id'Length in 1 .. Source_Service_Id_Max_Length;
-- bool
-- updateSourceAttributes(const std::string sourceGroup, const std::string sourceEntityId, const std::string sourceServiceId)
procedure Update_Source_Attributes
(This : in out Message_Attributes;
Source_Group : String;
Source_Entity_Id : String; -- can be empty
Source_Service_Id : String;
Result : out Boolean)
with Pre'Class =>
Source_Group'Length <= Source_Group_Max_Length and then
Source_Entity_Id'Length in 1 .. Source_Entity_Id_Max_Length and then
Source_Service_Id'Length in 1 .. Source_Service_Id_Max_Length;
-- bool
-- setAttributesFromDelimitedString(const std::string delimitedString)
procedure Set_Attributes_From_Delimited_String
(This : in out Message_Attributes;
Delimited_String : String;
Result : out Boolean)
with Pre'Class =>
Delimited_String'Length >= Minimum_Delimited_Address_Attribute_Message_String_Length;
-- bool
-- isValid()
function Is_Valid (This : Message_Attributes) return Boolean;
-- Content type of payload (e.g., "json", "lmcp", "text", "xml").
-- Valid values for content type are a controlled list. Cannot be an empty
-- string.
-- const std::string&
-- getContentType() const
function Payload_Content_Type (This : Message_Attributes) return String with
Post'Class => Payload_Content_Type'Result'Length > 0;
-- Descriptive qualifier for the payload.
-- Example values: "AFRL.CMASI.AirVehicleState" (LMCP full type name)
-- for case LMCP payload; json qualifying descriptor. Generally, is additional
-- description of the payload beyond the content type value. Valid values
-- for descriptor are a controlled list - but less constrained than content
-- type. TODO REVIEW Cannot be an empty string.
--
-- const std::string&
-- getDescriptor() const
function Payload_Descriptor (This : Message_Attributes) return String;
-- Multi-cast address to which the sending service subscribes. Can be an empty string.
-- const std::string&
-- getSourceGroup() const
function Source_Group (This : Message_Attributes) return String;
-- Entity ID of the host of the sending service.
-- Cannot be an empty string.
-- const std::string&
-- getSourceEntityId() const
function Source_Entity_Id (This : Message_Attributes) return String with
Post'Class => Source_Entity_Id'Result'Length > 0;
-- Service ID of the sending service. Cannot be an empty string.
-- const std::string&
-- getSourceServiceId() const
function Source_Service_Id (This : Message_Attributes) return String with
Post'Class => Source_Service_Id'Result'Length > 0;
-- Attribute fields combined into a single, delimited string.
-- Returns concatenated attribute fields.
-- const std::string&
-- getString() const
function Content_String (This : Message_Attributes) return String;
private
-- bool
-- parseMessageAttributesStringAndSetFields(const std::string delimitedString)
procedure Parse_Message_Attributes_String_And_Set_Fields
(This : in out Message_Attributes;
Delimited_String : String;
Result : out Boolean);
type Message_Attributes is tagged record
Is_Valid : Boolean := False;
Content_String : Dynamic_String (Capacity => Content_String_Max_Length); -- note different name (not m_string)
Content_Type : Dynamic_String (Capacity => Content_Type_Max_Length);
Descriptor : Dynamic_String (Capacity => Content_Type_Max_Length);
Source_Group : Dynamic_String (Capacity => Source_Group_Max_Length);
Source_Entity_Id : Dynamic_String (Capacity => Source_Entity_Id_Max_Length);
Source_Service_Id : Dynamic_String (Capacity => Source_Service_Id_Max_Length);
end record;
end UxAS.Comms.Data;
|
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
package MOS is
type Byte_T is mod 2**8; --[0,255]
type Short_T is mod 2**16; -- 2 Byte
MOS_START_PC : constant Short_T := 16#600#;
MOS_MAX_MEMORY : constant Short_T := 16#1000#;
MOS_MAX_PROGRAM_SIZE : constant Short_T := MOS_MAX_MEMORY - 1 - MOS_START_PC;
-- the Range of the stack pointer is fixed!!
-- otherwise an exception will be thrown. Thank You Ada :)
type StackPointer_T is range 16#100#..16#1FF#;
type Program_T is array(Short_T range <>) of Byte_T;
-- Initializing RAM
type Ram_T is array(Short_T range <>) of Byte_T;
type MOS_T is tagged
record
-- Registers
A : Byte_T := 0; -- Accumulator
X : Byte_T := 0; -- Index Register X
Y : Byte_T := 0; -- Index Register Y
P : Byte_T := 0; -- Process Status Register (N V - B D I Z C)
PC : Short_T := MOS_START_PC; -- Program Counter
S : StackPointer_T := 16#1FF#; -- Stack Pointer from 0x1FF to 0x100
Mem : Ram_T(0..MOS_MAX_MEMORY-1) := (others => 0);
end record;
-- type MOS_T_REF is access all MOS_T'Class;
procedure Load_Program_Into_Memory ( This : in out MOS_T;
Program_Path : in String);
procedure Put_Hex(Num : in Integer);
procedure Print_Status (This : in MOS_T);
procedure Print_Memory (This : in MOS_T;
Interval_Start : in Short_T;
Interval_End : in Short_T);
procedure Put_Register(Name : in String; Val : in Integer);
-- This low level/debug functions must be only accessible withing the package
private
function Read_File(File_Name : String; Program_Length : Short_T) return Program_T;
function Get_Program_Length(File_Name : String) return Short_T;
-----------------------------------------
-- Debug Functions
-----------------------------------------
end MOS;
|
-----------------------------------------------------------------------
-- facebook -- Get information about a Facebook user using the Facebook API
-- Copyright (C) 2012, 2014 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Command_Line;
with Ada.Strings.Unbounded;
with Util.Http.Clients.AWS;
with Util.Http.Rest;
with Mapping;
-- This example shows how to invoke a REST service, retrieve and extract a JSON content
-- into some Ada record. It uses the Facebook Graph API which does not need any
-- authentication (ie, the public Facebook API).
procedure Facebook is
procedure Print (P : in Mapping.Person);
procedure Print (P : in Mapping.Person) is
use Ada.Strings.Unbounded;
begin
Ada.Text_IO.Put_Line ("Id : " & Long_Long_Integer'Image (P.Id));
Ada.Text_IO.Put_Line ("Name : " & To_String (P.Name));
Ada.Text_IO.Put_Line ("First name : " & To_String (P.First_Name));
Ada.Text_IO.Put_Line ("Last name : " & To_String (P.Last_Name));
Ada.Text_IO.Put_Line ("Username : " & To_String (P.Username));
Ada.Text_IO.Put_Line ("Gender : " & To_String (P.Gender));
Ada.Text_IO.Put_Line ("Link : " & To_String (P.Link));
end Print;
procedure Get_User is new Util.Http.Rest.Rest_Get (Mapping.Person_Mapper);
Count : constant Natural := Ada.Command_Line.Argument_Count;
-- Mapping for the Person record.
Person_Mapping : aliased Mapping.Person_Mapper.Mapper;
begin
if Count = 0 then
Ada.Text_IO.Put_Line ("Usage: facebook username ...");
Ada.Text_IO.Put_Line ("Example: facebook btaylor");
return;
end if;
Person_Mapping.Add_Mapping ("id", Mapping.FIELD_ID);
Person_Mapping.Add_Mapping ("name", Mapping.FIELD_NAME);
Person_Mapping.Add_Mapping ("first_name", Mapping.FIELD_FIRST_NAME);
Person_Mapping.Add_Mapping ("last_name", Mapping.FIELD_LAST_NAME);
Person_Mapping.Add_Mapping ("link", Mapping.FIELD_LINK);
Person_Mapping.Add_Mapping ("username", Mapping.FIELD_USER_NAME);
Person_Mapping.Add_Mapping ("gender", Mapping.FIELD_GENDER);
Util.Http.Clients.AWS.Register;
for I in 1 .. Count loop
declare
URI : constant String := Ada.Command_Line.Argument (I);
P : aliased Mapping.Person;
begin
Get_User (URI => "https://graph.facebook.com/" & URI,
Mapping => Person_Mapping'Unchecked_Access,
Into => P'Unchecked_Access);
Print (P);
end;
end loop;
end Facebook;
|
--
-- Copyright (C) 2015-2016 secunet Security Networks AG
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
with HW.GFX.GMA.Config;
with HW.GFX.GMA.Registers;
with HW.GFX.GMA.PCH.Sideband;
with HW.Debug;
with GNAT.Source_Info;
use type HW.Word64;
package body HW.GFX.GMA.PCH.VGA is
PCH_ADPA_DAC_ENABLE : constant := 1 * 2 ** 31;
PCH_ADPA_VSYNC_DISABLE : constant := 1 * 2 ** 11;
PCH_ADPA_HSYNC_DISABLE : constant := 1 * 2 ** 10;
PCH_ADPA_VSYNC_ACTIVE_HIGH : constant := 1 * 2 ** 4;
PCH_ADPA_HSYNC_ACTIVE_HIGH : constant := 1 * 2 ** 3;
PCH_ADPA_MASK : constant Word32 :=
PCH_TRANSCODER_SELECT_MASK or
PCH_ADPA_DAC_ENABLE or
PCH_ADPA_VSYNC_DISABLE or
PCH_ADPA_HSYNC_DISABLE or
PCH_ADPA_VSYNC_ACTIVE_HIGH or
PCH_ADPA_HSYNC_ACTIVE_HIGH;
----------------------------------------------------------------------------
procedure On
(Port : FDI_Port_Type;
Mode : Mode_Type)
is
Polarity : Word32 := 0;
begin
pragma Debug (Debug.Put_Line (GNAT.Source_Info.Enclosing_Entity));
if Mode.H_Sync_Active_High then
Polarity := Polarity or PCH_ADPA_HSYNC_ACTIVE_HIGH;
end if;
if Mode.V_Sync_Active_High then
Polarity := Polarity or PCH_ADPA_VSYNC_ACTIVE_HIGH;
end if;
Registers.Unset_And_Set_Mask
(Register => Registers.PCH_ADPA,
Mask_Unset => PCH_ADPA_MASK,
Mask_Set => PCH_ADPA_DAC_ENABLE or
PCH_TRANSCODER_SELECT (Port) or
Polarity);
end On;
----------------------------------------------------------------------------
procedure Off
is
Sync_Disable : Word32 := 0;
begin
pragma Debug (Debug.Put_Line (GNAT.Source_Info.Enclosing_Entity));
if Config.VGA_Has_Sync_Disable then
Sync_Disable := PCH_ADPA_HSYNC_DISABLE or PCH_ADPA_VSYNC_DISABLE;
end if;
Registers.Unset_And_Set_Mask
(Register => Registers.PCH_ADPA,
Mask_Unset => PCH_ADPA_DAC_ENABLE,
Mask_Set => Sync_Disable);
end Off;
----------------------------------------------------------------------------
PCH_PIXCLK_GATE_GATE : constant := 0 * 2 ** 0;
PCH_PIXCLK_GATE_UNGATE : constant := 1 * 2 ** 0;
SBI_SSCCTL_DISABLE : constant := 1 * 2 ** 0;
SBI_SSCDIVINTPHASE_DIVSEL_SHIFT : constant := 1;
SBI_SSCDIVINTPHASE_DIVSEL_MASK : constant := 16#7f# * 2 ** 1;
SBI_SSCDIVINTPHASE_INCVAL_SHIFT : constant := 8;
SBI_SSCDIVINTPHASE_INCVAL_MASK : constant := 16#7f# * 2 ** 8;
SBI_SSCDIVINTPHASE_DIR_SHIFT : constant := 15;
SBI_SSCDIVINTPHASE_DIR_MASK : constant := 16#01# * 2 ** 15;
SBI_SSCDIVINTPHASE_PROPAGATE : constant := 1 * 2 ** 0;
SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT : constant := 4;
SBI_SSCAUXDIV_FINALDIV2SEL_MASK : constant := 16#01# * 2 ** 4;
function SBI_SSCDIVINTPHASE_DIVSEL (Val : Word32) return Word32 is
begin
return Shift_Left (Val, SBI_SSCDIVINTPHASE_DIVSEL_SHIFT);
end SBI_SSCDIVINTPHASE_DIVSEL;
function SBI_SSCDIVINTPHASE_INCVAL (Val : Word32) return Word32 is
begin
return Shift_Left (Val, SBI_SSCDIVINTPHASE_INCVAL_SHIFT);
end SBI_SSCDIVINTPHASE_INCVAL;
function SBI_SSCDIVINTPHASE_DIR (Val : Word32) return Word32 is
begin
return Shift_Left (Val, SBI_SSCDIVINTPHASE_DIR_SHIFT);
end SBI_SSCDIVINTPHASE_DIR;
function SBI_SSCAUXDIV_FINALDIV2SEL (Val : Word32) return Word32 is
begin
return Shift_Left (Val, SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT);
end SBI_SSCAUXDIV_FINALDIV2SEL;
procedure Clock_On (Mode : Mode_Type)
is
Refclock : constant := 2_700_000_000;
Aux_Div,
Div_Sel,
Phase_Inc,
Phase_Dir : Word32;
begin
pragma Debug (Debug.Put_Line (GNAT.Source_Info.Enclosing_Entity));
Registers.Write (Registers.PCH_PIXCLK_GATE, PCH_PIXCLK_GATE_GATE);
Sideband.Set_Mask
(Dest => Sideband.SBI_ICLK,
Register => Sideband.SBI_SSCCTL6,
Mask => SBI_SSCCTL_DISABLE);
Aux_Div := 16#0000_0000#;
Div_Sel := Word32 (Refclock / Mode.Dotclock - 2);
Phase_Inc := Word32 ((Refclock * 64) / Mode.Dotclock) and 16#0000_003f#;
Phase_Dir := 16#0000_0000#;
pragma Debug (Debug.Put_Reg32 ("Aux_Div ", Aux_Div));
pragma Debug (Debug.Put_Reg32 ("Div_Sel ", Div_Sel));
pragma Debug (Debug.Put_Reg32 ("Phase_Inc", Phase_Inc));
pragma Debug (Debug.Put_Reg32 ("Phase_Dir", Phase_Dir));
Sideband.Unset_And_Set_Mask
(Dest => Sideband.SBI_ICLK,
Register => Sideband.SBI_SSCDIVINTPHASE6,
Mask_Unset => SBI_SSCDIVINTPHASE_DIVSEL_MASK or
SBI_SSCDIVINTPHASE_INCVAL_MASK or
SBI_SSCDIVINTPHASE_DIR_MASK,
Mask_Set => SBI_SSCDIVINTPHASE_DIVSEL (Div_Sel) or
SBI_SSCDIVINTPHASE_INCVAL (Phase_Inc) or
SBI_SSCDIVINTPHASE_DIR (Phase_Dir) or
SBI_SSCDIVINTPHASE_PROPAGATE);
Sideband.Unset_And_Set_Mask
(Dest => Sideband.SBI_ICLK,
Register => Sideband.SBI_SSCAUXDIV,
Mask_Unset => SBI_SSCAUXDIV_FINALDIV2SEL_MASK,
Mask_Set => SBI_SSCAUXDIV_FINALDIV2SEL (Aux_Div));
Sideband.Unset_Mask
(Dest => Sideband.SBI_ICLK,
Register => Sideband.SBI_SSCCTL6,
Mask => SBI_SSCCTL_DISABLE);
Registers.Write (Registers.PCH_PIXCLK_GATE, PCH_PIXCLK_GATE_UNGATE);
end Clock_On;
end HW.GFX.GMA.PCH.VGA;
|
with System.Storage_Elements;
package body Counter
with SPARK_Mode
is
procedure Bump_And_Monitor (Alarm : out Boolean)
is
Calc : Integer;
begin
Calc := Port;
Alarm := Limit < Calc;
end Bump_And_Monitor;
end Counter;
|
-- part of AdaYaml, (c) 2017 Felix Krause
-- released under the terms of the MIT license, see the file "copying.txt"
private with Ada.Containers.Indefinite_Hashed_Maps;
package Yaml.Dom.Mapping_Data is
type Instance is tagged limited private
with Constant_Indexing => Element;
type Cursor is private;
function Length (Object : Instance) return Count_Type;
function Is_Empty (Container : Instance) return Boolean;
procedure Clear (Container : in out Instance);
function Has_Element (Position : Cursor) return Boolean;
function First (Object : Instance) return Cursor;
function Next (Position : Cursor) return Cursor;
procedure Iterate (Object : Instance;
Process : not null access procedure
(Key, Value : not null access Node.Instance));
function Key (Position : Cursor) return Node_Reference
with Pre => Has_Element (Position);
function Value (Position : Cursor) return Node_Reference
with Pre => Has_Element (Position);
function Find (Object : Instance; Key : Node_Reference) return Cursor;
function Element (Object : Instance; Key : Node_Reference)
return Node_Reference;
-- convenience method for retrieving values of keys that are !!str scalars.
-- the key value is given as String.
function Element (Object : Instance; Key : String) return Node_Reference;
procedure Insert (Container : in out Instance;
Key : in Node_Reference;
New_Item : in Node_Reference;
Position : out Cursor;
Inserted : out Boolean);
procedure Insert (Container : in out Instance;
Key : in Node_Reference;
New_Item : in Node_Reference);
procedure Include (Container : in out Instance;
Key : in Node_Reference;
New_Item : in Node_Reference);
procedure Replace (Container : in out Instance;
Key : in Node_Reference;
New_Item : in Node_Reference);
procedure Exclude (Container : in out Instance;
Key : in Node_Reference);
procedure Delete (Container : in out Instance;
Key : in Node_Reference);
procedure Delete (Container : in out Instance;
Position : in out Cursor);
No_Element : constant Cursor;
private
function Hash (Object : Node_Pointer) return Ada.Containers.Hash_Type;
package Node_Maps is new Ada.Containers.Indefinite_Hashed_Maps
(Node_Pointer, Node_Pointer, Hash, Dom."=", Dom."=");
type Instance is tagged limited record
Document : not null access Document_Instance;
Data : Node_Maps.Map;
end record;
type Cursor is record
Container : access Instance;
Position : Node_Maps.Cursor;
end record;
No_Element : constant Cursor := (Container => null,
Position => Node_Maps.No_Element);
package Friend_Interface is
function For_Document (Document : not null access Document_Instance)
return Instance with Export, Convention => Ada,
Link_Name => "AdaYaml__Mapping_Data__For_Document";
procedure Raw_Insert (Container : in out Instance;
Key, Value : not null access Node.Instance)
with Export, Convention => Ada,
Link_Name => "AdaYaml__Mapping_Data__Raw_Insert";
end Friend_Interface;
end Yaml.Dom.Mapping_Data;
|
-----------------------------------------------------------------------
-- awa-wikis-modules-tests -- Unit tests for wikis service
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Measures;
with Util.Test_Caller;
with AWA.Tests.Helpers;
with AWA.Tests.Helpers.Users;
with AWA.Services.Contexts;
with AWA.Counters.Definition;
with AWA.Users.Models;
with Security.Contexts;
package body AWA.Counters.Modules.Tests is
package User_Counter is
new AWA.Counters.Definition (AWA.Users.Models.USER_TABLE);
package Session_Counter is
new AWA.Counters.Definition (AWA.Users.Models.SESSION_TABLE);
package Global_Counter is
new AWA.Counters.Definition (null, "count");
package Caller is new Util.Test_Caller (Test, "Counters.Modules");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Counters.Modules.Increment",
Test_Increment'Access);
Caller.Add_Test (Suite, "Test AWA.Counters.Modules.Increment (global counter)",
Test_Global_Counter'Access);
end Add_Tests;
-- ------------------------------
-- Test incrementing counters and flushing.
-- ------------------------------
procedure Test_Increment (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Before : Integer;
After : Integer;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "test-wiki@test.com");
T.Manager := AWA.Counters.Modules.Get_Counter_Module;
T.Assert (T.Manager /= null, "There is no counter plugin");
T.Manager.Get_Counter (User_Counter.Index, Context.Get_User, Before);
AWA.Counters.Increment (User_Counter.Index, Context.Get_User);
T.Manager.Flush;
T.Manager.Get_Counter (User_Counter.Index, Context.Get_User, After);
Util.Tests.Assert_Equals (T, Before + 1, After, "The counter must have been incremented");
declare
S : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
AWA.Counters.Increment (User_Counter.Index, Context.Get_User);
end loop;
Util.Measures.Report (S, "AWA.Counters.Increment", 1000);
end;
AWA.Counters.Increment (User_Counter.Index, Context.Get_User);
declare
S : Util.Measures.Stamp;
begin
T.Manager.Flush;
Util.Measures.Report (S, "AWA.Counters.Flush");
end;
T.Manager.Get_Counter (User_Counter.Index, Context.Get_User, After);
Util.Tests.Assert_Equals (T, Before + 2 + 1_000, After,
"The counter must have been incremented");
end Test_Increment;
-- ------------------------------
-- Test creation of a wiki page.
-- ------------------------------
-- Test incrementing a global counter.
procedure Test_Global_Counter (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "test-wiki@test.com");
T.Manager := AWA.Counters.Modules.Get_Counter_Module;
T.Assert (T.Manager /= null, "There is no counter plugin");
-- T.Manager.Get_Counter (Global_Counter.Index, Before);
AWA.Counters.Increment (Global_Counter.Index);
T.Manager.Flush;
end Test_Global_Counter;
end AWA.Counters.Modules.Tests;
|
-------------------------------------------------------------------------
-- GL.Geometry - GL vertex buffer Object
--
-- Copyright (c) Rod Kay 2007
-- AUSTRALIA
-- Permission granted to use this software, without any warranty,
-- for any purpose, provided this copyright note remains attached
-- and unmodified if sources are distributed further.
-------------------------------------------------------------------------
-- with GL.Geometry;
-- with GL.Textures;
package GL.Buffer is
subtype vbo_Name is GL.Uint; -- an openGL vertex buffer 'name', which is a natural integer.
-- buffer object
--
type Object is abstract tagged private;
procedure Enable (Self : Object'Class);
procedure Destroy (Self : in out Object'Class);
function Extract_VBO_Target (Self : Object) return GL.VBO_Target is abstract;
-- 'array' and 'element array' base classes
--
type array_Object is new Object with private;
type element_array_Object is new Object with private;
-- refer to child packages, for specific buffers:
--
-- - GL.Buffer.vertex
-- - GL.Buffer.texture_coords
-- - GL.Buffer.normals
-- - GL.Buffer.indices
--
-- (tbd : pixel pack/unpack buffers)
no_platform_Support : exception;
--
-- raised by buffer 'Map' functions when OS platform does not support GL Buffer objects.
private
type Object is abstract tagged
record
Name : aliased vbo_Name := 0;
Length : Positive;
end record;
overriding function Extract_VBO_Target (Self : array_Object) return GL.VBO_Target;
overriding function Extract_VBO_Target (Self : element_array_Object) return GL.VBO_Target;
type array_Object is new Object with null record;
type element_array_Object is new Object with null record;
type vertex_buffer_Object is new array_Object with null record;
-- support
procedure Verify_Name (Self : in out Object'Class);
end GL.Buffer;
|
with Ada.Text_IO, Ada.Integer_Text_IO;
use Ada.Text_IO, Ada.Integer_Text_IO;
procedure Swap is
A, B : Integer;
procedure Swap_It (A, B: in out Integer) is
Temp : Integer;
begin
Temp := B;
B := A;
A := Temp;
end Swap_It;
begin
Put("A=");
Get(A); Skip_Line;
Put("B=");
Get(B); Skip_Line;
Swap_It(A, B);
Put_Line("A=" & A'Img & " B=" & B'Img);
end Swap;
|
-- { dg-do compile }
procedure Test_Unknown_Discrs is
package Display is
type Component_Id (<>) is limited private;
Deferred_Const : constant Component_Id;
private
type Component_Id is (Clock);
type Rec1 is record
C : Component_Id := Deferred_Const;
end record;
Priv_Cid_Object : Component_Id := Component_Id'First;
type Rec2 is record
C : Component_Id := Priv_Cid_Object;
end record;
Deferred_Const : constant Component_Id := Priv_Cid_Object;
end Display;
begin
null;
end Test_Unknown_Discrs;
|
-- SPDX-FileCopyrightText: 2021 Max Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-------------------------------------------------------------
with League.Strings;
with WebIDL.Arguments;
with WebIDL.Constructors;
with WebIDL.Definitions;
with WebIDL.Enumerations;
with WebIDL.Interface_Members;
with WebIDL.Interfaces;
with WebIDL.Types;
package body WebIDL.Parsers is
function "+" (Text : Wide_Wide_String)
return League.Strings.Universal_String
renames League.Strings.To_Universal_String;
-----------
-- Parse --
-----------
procedure Parse
(Self : in out Parser'Class;
Lexer : in out Abstract_Lexer'Class;
Factory : in out WebIDL.Factories.Factory'Class;
Errors : out League.String_Vectors.Universal_String_Vector)
is
pragma Unreferenced (Self);
use all type WebIDL.Tokens.Token_Kind;
Next : WebIDL.Tokens.Token;
procedure Expect
(Kind : WebIDL.Tokens.Token_Kind;
Ok : in out Boolean)
with Inline;
procedure Argument
(Result : out WebIDL.Arguments.Argument_Access;
Ok : in out Boolean);
procedure ArgumentList
(Result : out WebIDL.Factories.Argument_Vector_Access;
Ok : in out Boolean);
procedure ArgumentName
(Result : out League.Strings.Universal_String;
Ok : in out Boolean);
procedure CallbackOrInterfaceOrMixin
(Result : out WebIDL.Definitions.Definition_Access;
Ok : in out Boolean);
procedure Constructor
(Result : out WebIDL.Constructors.Constructor_Access;
Ok : in out Boolean);
procedure Definition
(Result : out WebIDL.Definitions.Definition_Access;
Ok : in out Boolean);
procedure Enum
(Result : out WebIDL.Enumerations.Enumeration_Access;
Ok : in out Boolean);
procedure EnumValueList
(Result : out League.String_Vectors.Universal_String_Vector;
Ok : in out Boolean);
procedure Inheritance
(Result : out League.Strings.Universal_String;
Ok : in out Boolean);
procedure InterfaceMembers
(Result : out WebIDL.Factories.Interface_Member_Vector_Access;
Ok : in out Boolean);
procedure InterfaceMember
(Result : out WebIDL.Interface_Members.Interface_Member_Access;
Ok : in out Boolean);
procedure InterfaceOrMixin
(Result : out WebIDL.Definitions.Definition_Access;
Ok : in out Boolean);
procedure InterfaceRest
(Result : out WebIDL.Interfaces.Interface_Access;
Ok : in out Boolean);
procedure PromiseType
(Result : out WebIDL.Types.Type_Access;
Ok : in out Boolean);
procedure DistinguishableType
(Result : out WebIDL.Types.Type_Access;
Ok : in out Boolean);
procedure UnionType
(Result : out WebIDL.Types.Type_Access;
Ok : in out Boolean);
procedure UnionMemberType
(Result : out WebIDL.Types.Type_Access;
Ok : in out Boolean);
procedure SingleType
(Result : out WebIDL.Types.Type_Access;
Ok : in out Boolean);
procedure ParseType
(Result : out WebIDL.Types.Type_Access;
Ok : in out Boolean);
procedure RecordType
(Result : out WebIDL.Types.Type_Access;
Ok : in out Boolean);
procedure UnrestrictedFloatType
(Result : out WebIDL.Types.Type_Access;
Ok : in out Boolean);
procedure UnsignedIntegerType
(Result : out WebIDL.Types.Type_Access;
Ok : in out Boolean);
--------------
-- Argument --
--------------
procedure Argument
(Result : out WebIDL.Arguments.Argument_Access;
Ok : in out Boolean)
is
Name : League.Strings.Universal_String;
Type_Def : WebIDL.Types.Type_Access;
Opt : Boolean := False;
Ellipsis : Boolean := False;
begin
if not Ok then
return;
elsif Next.Kind = Optional_Token then
Opt := True;
raise Program_Error;
else
ParseType (Type_Def, Ok);
if Next.Kind = Ellipsis_Token then
Expect (Ellipsis_Token, Ok);
Ellipsis := True;
end if;
ArgumentName (Name, Ok);
end if;
Result := Factory.Argument
(Type_Def => Type_Def,
Name => Name,
Is_Options => Opt,
Has_Ellipsis => Ellipsis);
end Argument;
------------------
-- ArgumentList --
------------------
procedure ArgumentList
(Result : out WebIDL.Factories.Argument_Vector_Access;
Ok : in out Boolean) is
begin
Result := Factory.Arguments;
loop
declare
Item : WebIDL.Arguments.Argument_Access;
begin
Argument (Item, Ok);
exit when not Ok;
Result.Append (Item);
exit when Next.Kind /= ',';
Expect (',', Ok);
end;
end loop;
Ok := True;
end ArgumentList;
------------------
-- ArgumentName --
------------------
procedure ArgumentName
(Result : out League.Strings.Universal_String;
Ok : in out Boolean) is
begin
Expect (Identifier_Token, Ok);
Result := Next.Text;
end ArgumentName;
-----------------
-- Constructor --
-----------------
procedure Constructor
(Result : out WebIDL.Constructors.Constructor_Access;
Ok : in out Boolean)
is
Args : WebIDL.Factories.Argument_Vector_Access;
begin
if not Ok then
return;
end if;
Expect (Constructor_Token, Ok);
Expect ('(', Ok);
ArgumentList (Args, Ok);
Expect (')', Ok);
Expect (';', Ok);
Result := Factory.Constructor (Args);
end Constructor;
--------------------------------
-- CallbackOrInterfaceOrMixin --
--------------------------------
procedure CallbackOrInterfaceOrMixin
(Result : out WebIDL.Definitions.Definition_Access;
Ok : in out Boolean) is
begin
case Next.Kind is
when Callback_Token =>
-- Expect (Callback_Token, Ok);
raise Program_Error;
when Interface_Token =>
Expect (Interface_Token, Ok);
InterfaceOrMixin (Result, Ok);
when others =>
Ok := False;
end case;
end CallbackOrInterfaceOrMixin;
----------------
-- Definition --
----------------
procedure Definition
(Result : out WebIDL.Definitions.Definition_Access;
Ok : in out Boolean) is
begin
case Next.Kind is
when Callback_Token | Interface_Token =>
CallbackOrInterfaceOrMixin (Result, Ok);
when Enum_Token =>
declare
Node : WebIDL.Enumerations.Enumeration_Access;
begin
Enum (Node, Ok);
Result := WebIDL.Definitions.Definition_Access (Node);
end;
when others =>
Ok := False;
end case;
end Definition;
-------------------------
-- DistinguishableType --
-------------------------
procedure DistinguishableType
(Result : out WebIDL.Types.Type_Access;
Ok : in out Boolean) is
begin
case Next.Kind is
when Short_Token | Long_Token | Unsigned_Token =>
UnsignedIntegerType (Result, Ok);
when Unrestricted_Token | Float_Token | Double_Token =>
UnrestrictedFloatType (Result, Ok);
when Undefined_Token =>
Expect (Undefined_Token, Ok);
Result := Factory.Undefined;
when Boolean_Token =>
Expect (Boolean_Token, Ok);
Result := Factory.Bool;
when Byte_Token =>
Expect (Byte_Token, Ok);
Result := Factory.Byte;
when Octet_Token =>
Expect (Octet_Token, Ok);
Result := Factory.Octet;
when Bigint_Token =>
Expect (Bigint_Token, Ok);
Result := Factory.BigInt;
when DOMString_Token =>
Expect (DOMString_Token, Ok);
Result := Factory.DOMString;
when ByteString_Token =>
Expect (ByteString_Token, Ok);
Result := Factory.ByteString;
when USVString_Token =>
Expect (USVString_Token, Ok);
Result := Factory.USVString;
when Identifier_Token =>
raise Program_Error;
when Sequence_Token =>
declare
T : WebIDL.Types.Type_Access;
begin
Expect (Sequence_Token, Ok);
Expect ('<', Ok);
ParseType (T, Ok);
Expect ('>', Ok);
if Ok then
Result := Factory.Sequence (T);
end if;
end;
when Object_Token =>
Expect (Object_Token, Ok);
Result := Factory.Object;
when Symbol_Token =>
Expect (Symbol_Token, Ok);
Result := Factory.Symbol;
when ArrayBuffer_Token |
DataView_Token |
Int8Array_Token |
Int16Array_Token |
Int32Array_Token |
Uint8Array_Token |
Uint16Array_Token |
Uint32Array_Token |
Uint8ClampedArray_Token |
Float32Array_Token |
Float64Array_Token =>
Result := Factory.Buffer_Related_Type (Next.Text);
Expect (Next.Kind, Ok);
when FrozenArray_Token =>
declare
T : WebIDL.Types.Type_Access;
begin
Expect (FrozenArray_Token, Ok);
Expect ('<', Ok);
ParseType (T, Ok);
Expect ('>', Ok);
if Ok then
Result := Factory.Frozen_Array (T);
end if;
end;
when ObservableArray_Token =>
declare
T : WebIDL.Types.Type_Access;
begin
Expect (ObservableArray_Token, Ok);
Expect ('<', Ok);
ParseType (T, Ok);
Expect ('>', Ok);
if Ok then
Result := Factory.Observable_Array (T);
end if;
end;
when Record_Token =>
RecordType (Result, Ok);
when others =>
raise Program_Error;
end case;
if Ok and Next.Kind = '?' then
Expect ('?', Ok);
Result := Factory.Nullable (Result);
end if;
end DistinguishableType;
----------
-- Enum --
----------
procedure Enum
(Result : out WebIDL.Enumerations.Enumeration_Access;
Ok : in out Boolean)
is
Name : League.Strings.Universal_String;
Values : League.String_Vectors.Universal_String_Vector;
begin
if not Ok then
return;
end if;
Expect (Enum_Token, Ok);
Expect (Identifier_Token, Ok);
Name := Next.Text;
Expect ('{', Ok);
EnumValueList (Values, Ok);
Expect ('}', Ok);
Expect (';', Ok);
if Ok then
Result := Factory.Enumeration (Name, Values);
end if;
end Enum;
procedure EnumValueList
(Result : out League.String_Vectors.Universal_String_Vector;
Ok : in out Boolean) is
begin
if not Ok then
return;
end if;
Expect (String_Token, Ok);
Result.Append (Next.Text);
while Ok and Next.Kind = ',' loop
Expect (',', Ok);
Expect (String_Token, Ok);
Result.Append (Next.Text);
end loop;
end EnumValueList;
------------
-- Expect --
------------
procedure Expect
(Kind : WebIDL.Tokens.Token_Kind;
Ok : in out Boolean) is
begin
if Ok and Next.Kind = Kind then
Lexer.Next_Token (Next);
elsif Ok then
Errors.Append (+"Expecing ");
Errors.Append (+Kind'Wide_Wide_Image);
Ok := False;
end if;
end Expect;
procedure Inheritance
(Result : out League.Strings.Universal_String;
Ok : in out Boolean) is
begin
if Next.Kind = ':' then
Expect (':', Ok);
Expect (Identifier_Token, Ok);
Result := Next.Text;
end if;
end Inheritance;
---------------------
-- InterfaceMember --
---------------------
procedure InterfaceMember
(Result : out WebIDL.Interface_Members.Interface_Member_Access;
Ok : in out Boolean) is
pragma Unreferenced (Result);
begin
case Next.Kind is
when Constructor_Token =>
declare
Item : WebIDL.Constructors.Constructor_Access;
begin
Constructor (Item, Ok);
Result := WebIDL.Interface_Members.Interface_Member_Access
(Item);
end;
when others =>
Ok := False;
end case;
end InterfaceMember;
----------------------
-- InterfaceMembers --
----------------------
procedure InterfaceMembers
(Result : out WebIDL.Factories.Interface_Member_Vector_Access;
Ok : in out Boolean)
is
begin
Result := Factory.Interface_Members;
while Ok loop
declare
Item : WebIDL.Interface_Members.Interface_Member_Access;
begin
InterfaceMember (Item, Ok);
if Ok then
Result.Append (Item);
end if;
end;
end loop;
Ok := True;
end InterfaceMembers;
----------------------
-- InterfaceOrMixin --
----------------------
procedure InterfaceOrMixin
(Result : out WebIDL.Definitions.Definition_Access;
Ok : in out Boolean) is
begin
if Next.Kind = Mixin_Token then
raise Program_Error;
else
declare
Value : WebIDL.Interfaces.Interface_Access;
begin
InterfaceRest (Value, Ok);
Result := WebIDL.Definitions.Definition_Access (Value);
end;
end if;
end InterfaceOrMixin;
-------------------
-- InterfaceRest --
-------------------
procedure InterfaceRest
(Result : out WebIDL.Interfaces.Interface_Access;
Ok : in out Boolean)
is
Name : League.Strings.Universal_String;
Parent : League.Strings.Universal_String;
Members : WebIDL.Factories.Interface_Member_Vector_Access;
begin
if not Ok then
return;
end if;
Expect (Identifier_Token, Ok);
Name := Next.Text;
Inheritance (Parent, Ok);
Expect ('{', Ok);
InterfaceMembers (Members, Ok);
Expect ('}', Ok);
Expect (';', Ok);
if Ok then
Result := Factory.New_Interface
(Name => Name,
Parent => Parent,
Members => Members);
end if;
end InterfaceRest;
procedure ParseType
(Result : out WebIDL.Types.Type_Access;
Ok : in out Boolean)
is
begin
if Next.Kind = '(' then
UnionType (Result, Ok);
if Ok and Next.Kind = '?' then
Expect ('?', Ok);
Result := Factory.Nullable (Result);
end if;
else
SingleType (Result, Ok);
end if;
end ParseType;
procedure PromiseType
(Result : out WebIDL.Types.Type_Access;
Ok : in out Boolean)
is
T : WebIDL.Types.Type_Access;
begin
Expect (Promise_Token, Ok);
Expect ('<', Ok);
ParseType (T, Ok);
Expect ('>', Ok);
if Ok then
Result := Factory.Promise (T);
end if;
end PromiseType;
procedure RecordType
(Result : out WebIDL.Types.Type_Access;
Ok : in out Boolean)
is
Key : WebIDL.Types.Type_Access;
Value : WebIDL.Types.Type_Access;
begin
Expect (Record_Token, Ok);
Expect ('<', Ok);
ParseType (Key, Ok);
Expect (',', Ok);
ParseType (Value, Ok);
Expect ('>', Ok);
if Ok then
Result := Factory.Record_Type (Key, Value);
end if;
end RecordType;
procedure SingleType
(Result : out WebIDL.Types.Type_Access;
Ok : in out Boolean) is
begin
case Next.Kind is
when Short_Token | Long_Token | Unsigned_Token |
Unrestricted_Token | Float_Token | Double_Token |
Undefined_Token |
Boolean_Token |
Byte_Token |
Octet_Token |
Bigint_Token |
DOMString_Token |
ByteString_Token |
USVString_Token |
Identifier_Token |
Sequence_Token |
Object_Token |
Symbol_Token |
ArrayBuffer_Token |
DataView_Token |
Int8Array_Token |
Int16Array_Token |
Int32Array_Token |
Uint8Array_Token |
Uint16Array_Token |
Uint32Array_Token |
Uint8ClampedArray_Token |
Float32Array_Token |
Float64Array_Token |
FrozenArray_Token |
ObservableArray_Token |
Record_Token =>
DistinguishableType (Result, Ok);
when Any_Token =>
Expect (Any_Token, Ok);
Result := Factory.Any;
when Promise_Token =>
PromiseType (Result, Ok);
when others =>
raise Program_Error;
end case;
end SingleType;
---------------------
-- UnionMemberType --
---------------------
procedure UnionMemberType
(Result : out WebIDL.Types.Type_Access;
Ok : in out Boolean) is
begin
if not Ok then
return;
end if;
case Next.Kind is
when '(' =>
UnionType (Result, Ok);
if Ok and Next.Kind = '?' then
Expect ('?', Ok);
Result := Factory.Nullable (Result);
end if;
when others =>
DistinguishableType (Result, Ok);
end case;
end UnionMemberType;
---------------
-- UnionType --
---------------
procedure UnionType
(Result : out WebIDL.Types.Type_Access;
Ok : in out Boolean)
is
Item : WebIDL.Types.Type_Access;
Vector : constant WebIDL.Factories.Union_Member_Vector_Access :=
Factory.Union_Members;
begin
Expect ('(', Ok);
UnionMemberType (Item, Ok);
if Ok then
Vector.Append (Item);
end if;
Expect (Or_Token, Ok);
UnionMemberType (Item, Ok);
if Ok then
Vector.Append (Item);
end if;
while Next.Kind = Or_Token loop
Expect (Or_Token, Ok);
UnionMemberType (Item, Ok);
if Ok then
Vector.Append (Item);
else
exit;
end if;
end loop;
Expect (')', Ok);
if Ok then
Result := Factory.Union (Vector);
end if;
end UnionType;
---------------------------
-- UnrestrictedFloatType --
---------------------------
procedure UnrestrictedFloatType
(Result : out WebIDL.Types.Type_Access;
Ok : in out Boolean)
is
Restricted : Boolean := True;
Double : Boolean := False;
begin
if Next.Kind = Unrestricted_Token then
Expect (Unrestricted_Token, Ok);
Restricted := False;
end if;
if Next.Kind = Float_Token then
Expect (Float_Token, Ok);
else
Expect (Double_Token, Ok);
Double := True;
end if;
if Ok then
Result := Factory.Float (Restricted, Double);
end if;
end UnrestrictedFloatType;
procedure UnsignedIntegerType
(Result : out WebIDL.Types.Type_Access;
Ok : in out Boolean)
is
Unsigned : Boolean := False;
Long : Natural := 0;
begin
if Next.Kind = Unsigned_Token then
Unsigned := True;
Expect (Unsigned_Token, Ok);
end if;
case Next.Kind is
when Short_Token =>
Expect (Short_Token, Ok);
when others =>
Expect (Long_Token, Ok);
Long := Boolean'Pos (Ok);
if Ok and Next.Kind = Long_Token then
Expect (Long_Token, Ok);
Long := 2;
end if;
end case;
if Ok then
Result := Factory.Integer (Unsigned, Long);
end if;
end UnsignedIntegerType;
begin
Lexer.Next_Token (Next);
loop
declare
Ok : Boolean := True;
Result : WebIDL.Definitions.Definition_Access;
begin
Definition (Result, Ok);
exit when not Ok;
end;
end loop;
if Next.Kind /= End_Of_Stream_Token then
Errors.Append (+"EOF expected");
end if;
end Parse;
end WebIDL.Parsers;
|
package Loop_Optimization14 is
type Rec is record
A : Boolean;
pragma Atomic (A);
B : Boolean;
end record;
procedure Finalize_Pool (Pool : in out Rec);
end Loop_Optimization14;
|
-- C32115A.ADA
-- Grant of Unlimited Rights
--
-- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687,
-- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained
-- unlimited rights in the software and documentation contained herein.
-- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making
-- this public release, the Government intends to confer upon all
-- recipients unlimited rights equal to those held by the Government.
-- These rights include rights to use, duplicate, release or disclose the
-- released technical data and computer software in whole or in part, in
-- any manner and for any purpose whatsoever, and to have or permit others
-- to do so.
--
-- DISCLAIMER
--
-- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR
-- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED
-- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE
-- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE
-- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A
-- PARTICULAR PURPOSE OF SAID MATERIAL.
--*
-- OBJECTIVE:
-- CHECK THAT WHEN A VARIABLE OR CONSTANT HAVING A CONSTRAINED
-- ACCESS TYPE IS DECLARED WITH AN INITIAL NON-NULL ACCESS VALUE,
-- CONSTRAINT_ERROR IS RAISED IF AN INDEX BOUND OR A DISCRIMINANT
-- VALUE OF THE DESIGNATED OBJECT DOES NOT EQUAL THE CORRESPONDING
-- VALUE SPECIFIED FOR THE ACCESS SUBTYPE.
-- HISTORY:
-- RJW 07/20/86 CREATED ORIGINAL TEST.
-- JET 08/05/87 ADDED DEFEAT OF DEAD VARIABLE OPTIMIZATION.
-- PWN 11/30/94 REMOVED TEST ILLEGAL IN ADA 9X.
WITH REPORT; USE REPORT;
PROCEDURE C32115A IS
PACKAGE PKG IS
TYPE PRIV (D : INTEGER) IS PRIVATE;
PRIVATE
TYPE PRIV (D : INTEGER) IS
RECORD
NULL;
END RECORD;
END PKG;
USE PKG;
TYPE ACCP IS ACCESS PRIV (IDENT_INT (1));
TYPE REC (D : INTEGER) IS
RECORD
NULL;
END RECORD;
TYPE ACCR IS ACCESS REC (IDENT_INT (2));
TYPE ARR IS ARRAY (NATURAL RANGE <>) OF INTEGER;
TYPE ACCA IS ACCESS ARR (IDENT_INT (1) .. IDENT_INT (2));
TYPE ACCN IS ACCESS ARR (IDENT_INT (1) .. IDENT_INT (0));
BEGIN
TEST ("C32115A", "CHECK THAT WHEN A VARIABLE OR CONSTANT " &
"HAVING A CONSTRAINED ACCESS TYPE IS " &
"DECLARED WITH AN INITIAL NON-NULL ACCESS " &
"VALUE, CONSTRAINT_ERROR IS RAISED IF AN " &
"INDEX BOUND OR A DISCRIMINANT VALUE OF THE " &
"DESIGNATED OBJECT DOES NOT EQUAL THE " &
"CORRESPONDING VALUE SPECIFIED FOR THE " &
"ACCESS SUBTYPE" );
BEGIN
DECLARE
AC1 : CONSTANT ACCP := NEW PRIV (D => (IDENT_INT (2)));
BEGIN
FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " &
"OF CONSTANT 'AC1'" );
IF AC1 /= NULL THEN
COMMENT ("DEFEAT 'AC1' OPTIMIZATION");
END IF;
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " &
"OF CONSTANT 'AC1'" );
END;
BEGIN
DECLARE
AC2 : ACCP := NEW PRIV (D => (IDENT_INT (2)));
BEGIN
FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " &
"OF VARIABLE 'AC2'" );
IF AC2 /= NULL THEN
COMMENT ("DEFEAT 'AC2' OPTIMIZATION");
END IF;
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " &
"OF VARIABLE 'AC2'" );
END;
BEGIN
DECLARE
AC3 : CONSTANT ACCP := NEW PRIV (D => (IDENT_INT (0)));
BEGIN
FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " &
"OF CONSTANT 'AC3'" );
IF AC3 /= NULL THEN
COMMENT ("DEFEAT 'AC3' OPTIMIZATION");
END IF;
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " &
"OF CONSTANT 'AC3'" );
END;
BEGIN
DECLARE
AC4 : ACCP := NEW PRIV (D => (IDENT_INT (0)));
BEGIN
FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " &
"OF VARIABLE 'AC4'" );
IF AC4 /= NULL THEN
COMMENT ("DEFEAT 'AC4' OPTIMIZATION");
END IF;
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " &
"OF VARIABLE 'AC4'" );
END;
BEGIN
DECLARE
AC5 : CONSTANT ACCR := NEW REC'(D => (IDENT_INT (1)));
BEGIN
FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " &
"OF CONSTANT 'AC5'" );
IF AC5 /= NULL THEN
COMMENT ("DEFEAT 'AC5' OPTIMIZATION");
END IF;
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " &
"OF CONSTANT 'AC5'" );
END;
BEGIN
DECLARE
AC6 : ACCR := NEW REC' (D => (IDENT_INT (1)));
BEGIN
FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " &
"OF VARIABLE 'AC6'" );
IF AC6 /= NULL THEN
COMMENT ("DEFEAT 'AC6' OPTIMIZATION");
END IF;
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " &
"OF VARIABLE 'AC6'" );
END;
BEGIN
DECLARE
AC7 : CONSTANT ACCR := NEW REC'(D => (IDENT_INT (3)));
BEGIN
FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " &
"OF CONSTANT 'AC7'" );
IF AC7 /= NULL THEN
COMMENT ("DEFEAT 'AC7' OPTIMIZATION");
END IF;
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " &
"OF CONSTANT 'AC7'" );
END;
BEGIN
DECLARE
AC8 : ACCR := NEW REC' (D => (IDENT_INT (3)));
BEGIN
FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " &
"OF VARIABLE 'AC8'" );
IF AC8 /= NULL THEN
COMMENT ("DEFEAT 'AC8' OPTIMIZATION");
END IF;
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " &
"OF VARIABLE 'AC8'" );
END;
BEGIN
DECLARE
AC9 : CONSTANT ACCA :=
NEW ARR'(IDENT_INT (1) .. IDENT_INT (1) => 0);
BEGIN
FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " &
"OF CONSTANT 'AC9'" );
IF AC9 /= NULL THEN
COMMENT ("DEFEAT 'AC9' OPTIMIZATION");
END IF;
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " &
"OF CONSTANT 'AC9'" );
END;
BEGIN
DECLARE
AC10 : ACCA :=
NEW ARR'(IDENT_INT (1) .. IDENT_INT (1) => 0);
BEGIN
FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " &
"OF VARIABLE 'AC10'" );
IF AC10 /= NULL THEN
COMMENT ("DEFEAT 'AC10' OPTIMIZATION");
END IF;
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " &
"OF VARIABLE 'AC10'" );
END;
BEGIN
DECLARE
AC11 : CONSTANT ACCA :=
NEW ARR' (IDENT_INT (0) .. IDENT_INT (2) => 0);
BEGIN
FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " &
"OF CONSTANT 'AC11'" );
IF AC11 /= NULL THEN
COMMENT ("DEFEAT 'AC11' OPTIMIZATION");
END IF;
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " &
"OF CONSTANT 'AC11'" );
END;
BEGIN
DECLARE
AC12 : ACCA :=
NEW ARR'(IDENT_INT (0) .. IDENT_INT (2) => 0);
BEGIN
FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " &
"OF VARIABLE 'AC12'" );
IF AC12 /= NULL THEN
COMMENT ("DEFEAT 'AC12' OPTIMIZATION");
END IF;
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " &
"OF VARIABLE 'AC12'" );
END;
BEGIN
DECLARE
AC15 : CONSTANT ACCN :=
NEW ARR' (IDENT_INT (0) .. IDENT_INT (0) => 0);
BEGIN
FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " &
"OF CONSTANT 'AC15'" );
IF AC15 /= NULL THEN
COMMENT ("DEFEAT 'AC15' OPTIMIZATION");
END IF;
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " &
"OF CONSTANT 'AC15'" );
END;
BEGIN
DECLARE
AC16 : ACCN :=
NEW ARR'(IDENT_INT (0) .. IDENT_INT (0) => 0);
BEGIN
FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " &
"OF VARIABLE 'AC16'" );
IF AC16 /= NULL THEN
COMMENT ("DEFEAT 'AC16' OPTIMIZATION");
END IF;
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " &
"OF VARIABLE 'AC16'" );
END;
RESULT;
END C32115A;
|
pragma License (Unrestricted);
-- implementation unit required by compiler
with Ada.Interrupts;
with System.Interrupt_Handlers;
with System.Tasking.Protected_Objects.Entries;
package System.Interrupts is
type Previous_Handler_Item is record
Interrupt : Ada.Interrupts.Interrupt_Id;
Handler : Ada.Interrupts.Parameterless_Handler;
-- Static : Boolean;
end record;
pragma Suppress_Initialization (Previous_Handler_Item);
type Previous_Handler_Array is
array (Positive range <>) of Previous_Handler_Item;
pragma Suppress_Initialization (Previous_Handler_Array);
type New_Handler_Item is record
Interrupt : Ada.Interrupts.Interrupt_Id;
Handler : Ada.Interrupts.Parameterless_Handler;
end record;
pragma Suppress_Initialization (New_Handler_Item);
type New_Handler_Array is array (Positive range <>) of New_Handler_Item;
pragma Suppress_Initialization (New_Handler_Array);
-- required by compiler
subtype System_Interrupt_Id is Ada.Interrupts.Interrupt_Id;
Default_Interrupt_Priority : constant Interrupt_Priority :=
Interrupt_Priority'Last;
-- required to attach a protected handler by compiler
type Static_Interrupt_Protection (
Num_Entries : Tasking.Protected_Objects.Protected_Entry_Index;
Num_Attach_Handler : Natural) is
limited new Tasking.Protected_Objects.Entries.Protection_Entries
with private;
procedure Register_Interrupt_Handler (Handler_Addr : Address)
renames Interrupt_Handlers.Register_Interrupt_Handler;
procedure Install_Handlers (
Object : not null access Static_Interrupt_Protection;
New_Handlers : New_Handler_Array);
type Dynamic_Interrupt_Protection is
limited new Tasking.Protected_Objects.Entries.Protection_Entries
with null record;
-- unimplemented subprograms required by compiler
-- Bind_Interrupt_To_Entry
-- Install_Restricted_Handlers
private
type Static_Interrupt_Protection (
Num_Entries : Tasking.Protected_Objects.Protected_Entry_Index;
Num_Attach_Handler : Natural) is
limited new Tasking.Protected_Objects.Entries.Protection_Entries (
Num_Entries) with
record
Previous_Handlers : Previous_Handler_Array (1 .. Num_Attach_Handler);
end record;
overriding procedure Finalize (
Object : in out Static_Interrupt_Protection);
end System.Interrupts;
|
-----------------------------------------------------------------------
-- ado-schemas-postgresql -- Postgresql Database Schemas
-- Copyright (C) 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Statements;
with ADO.Statements.Create;
package body ADO.Schemas.Postgresql is
use ADO.Statements;
procedure Load_Table_Schema (C : in ADO.Connections.Database_Connection'Class;
Database : in String;
Table : in Table_Definition);
procedure Load_Table_Keys (C : in ADO.Connections.Database_Connection'Class;
Database : in String;
Table : in Table_Definition);
function String_To_Type (Value : in String) return Column_Type;
function String_To_Type (Value : in String) return Column_Type is
begin
if Value = "date" then
return T_DATE;
elsif Value = "timestamp without time zone" then
return T_DATE_TIME;
elsif Value = "timestamp with time zone" then
return T_DATE_TIME;
elsif Value = "integer" then
return T_INTEGER;
elsif Value = "bigint" then
return T_LONG_INTEGER;
elsif Value = "bytea" then
return T_BLOB;
elsif Value = "character varying" then
return T_VARCHAR;
end if;
return T_UNKNOWN;
end String_To_Type;
-- ------------------------------
-- Load the table definition
-- ------------------------------
procedure Load_Table_Schema (C : in ADO.Connections.Database_Connection'Class;
Database : in String;
Table : in Table_Definition) is
Name : constant String := Get_Name (Table);
SQL : constant String
:= "SELECT column_name, column_default, data_type, is_nullable, "
& "character_maximum_length, collation_name FROM information_schema.columns "
& "WHERE table_catalog = ? AND table_name = ?";
Stmt : Query_Statement
:= Create.Create_Statement (C.Create_Statement (SQL));
Last : Column_Definition := null;
Col : Column_Definition;
Value : Unbounded_String;
begin
Stmt.Add_Param (Database);
Stmt.Add_Param (Name);
Stmt.Execute;
while Stmt.Has_Elements loop
Col := new Column;
Col.Name := Stmt.Get_Unbounded_String (0);
if not Stmt.Is_Null (5) then
Col.Collation := Stmt.Get_Unbounded_String (5);
end if;
if not Stmt.Is_Null (1) then
Col.Default := Stmt.Get_Unbounded_String (1);
end if;
if Last /= null then
Last.Next_Column := Col;
else
Table.First_Column := Col;
end if;
if not Stmt.Is_Null (4) then
Col.Size := Stmt.Get_Integer (4);
end if;
Value := Stmt.Get_Unbounded_String (2);
Col.Col_Type := String_To_Type (To_String (Value));
Value := Stmt.Get_Unbounded_String (3);
Col.Is_Null := Value = "YES";
Last := Col;
Stmt.Next;
end loop;
end Load_Table_Schema;
-- ------------------------------
-- Load the table definition
-- ------------------------------
procedure Load_Table_Keys (C : in ADO.Connections.Database_Connection'Class;
Database : in String;
Table : in Table_Definition) is
Name : constant String := Get_Name (Table);
SQL : constant String
:= "SELECT column_name FROM"
& " information_schema.table_constraints tc, "
& " information_schema.key_column_usage kc "
& "WHERE tc.constraint_type = 'PRIMARY KEY' "
& " AND kc.table_name = tc.table_name "
& " AND kc.table_schema = tc.table_schema "
& " AND kc.constraint_name = tc.constraint_name "
& " AND tc.table_catalog = ? and tc.table_name = ?";
Stmt : Query_Statement
:= Create.Create_Statement (C.Create_Statement (SQL));
Col : Column_Definition;
begin
Stmt.Add_Param (Database);
Stmt.Add_Param (Name);
Stmt.Execute;
while Stmt.Has_Elements loop
declare
Col_Name : constant String := Stmt.Get_String (0);
begin
Col := Find_Column (Table, Col_Name);
if Col /= null then
Col.Is_Primary := True;
end if;
end;
Stmt.Next;
end loop;
end Load_Table_Keys;
-- ------------------------------
-- Load the database schema
-- ------------------------------
procedure Load_Schema (C : in ADO.Connections.Database_Connection'Class;
Schema : out Schema_Definition;
Database : in String) is
SQL : constant String
:= "SELECT tablename FROM pg_catalog.pg_tables "
& "WHERE schemaname != 'pg_catalog' AND schemaname != 'information_schema'";
Stmt : Query_Statement
:= Create.Create_Statement (C.Create_Statement (SQL));
Table : Table_Definition;
Last : Table_Definition := null;
begin
Schema.Schema := new ADO.Schemas.Schema;
Stmt.Execute;
while Stmt.Has_Elements loop
Table := new ADO.Schemas.Table;
Table.Name := Stmt.Get_Unbounded_String (0);
if Last /= null then
Last.Next_Table := Table;
else
Schema.Schema.First_Table := Table;
end if;
Load_Table_Schema (C, Database, Table);
Load_Table_Keys (C, Database, Table);
Last := Table;
Stmt.Next;
end loop;
end Load_Schema;
end ADO.Schemas.Postgresql;
|
pragma Ada_2012;
-- with Ada.Text_Io; use Ada.Text_Io;
package body Protypo.Api.Engine_Values.Constant_Wrappers is
----------------
-- To_Handler --
----------------
function To_Handler_Value (Value : Engine_Value) return Handler_Value is
begin
if Value in Handler_Value then
return value;
else
declare
Result : constant Engine_Value :=
Handlers.Create (Handlers.Constant_Interface_Access (Make_Wrapper (Value)));
begin
-- Put_Line (Result.Class'Image);
-- Put_Line (Boolean'image(Result.Class in Handler_Classes));
-- Put_Line (Boolean'Image (Result in Handler_Value));
return Result;
end;
end if;
end To_Handler_Value;
end Protypo.Api.Engine_Values.Constant_Wrappers;
|
with Ada;
with Ada.Text_IO;
with Ada.Command_Line;
with GNAT.Command_Line;
with Ada.Environment_Variables;
with Ada.Directories;
with Ada.Directories.Hierarchical_File_Names;
with GNAT.OS_Lib;
with Ada.Containers.Indefinite_Ordered_Maps;
with Ada.Containers.Indefinite_Vectors;
with Ada.Characters.Latin_1;
package Ada_Launch is
-- Ada 2012 Tools for launching other applications in a specific way, or
-- with a specific environment. This is an example and practical
-- application of Ada being used in a similar way to a scripting/shell
-- language, except that one has the full power, efficiency, and accesibility
-- found only in a compiled language!
--
-- Arguments, Options, or array words are viewed as a vector of strings in
-- package Arguments. Such Vectors can be be instantly created and
-- composed with the '+' operator: +"word1" +str_variable +"word three".
-- This allows the '&' operator to continue to be used for concatenating
-- to create individual arguments:
-- +"word " & "one" + "word2" => "word one", "word2"
use Ada.Command_Line;
use Ada.Containers;
use Ada.Characters.Latin_1;
use GNAT.Command_Line;
use GNAT.OS_Lib;
use Ada.Directories;
package Hfs renames Ada.Directories.Hierarchical_File_Names;
package Os renames GNAT.OS_Lib;
-- type Float is new Standard.Long_Long_Float;
Empty_Argument_List : constant Argument_List (1 .. 0) :=
(others => new String'(""));
package Env renames Ada.Environment_Variables;
-- System Environment Variables.
type Os_Type is (Unix, Dos, Mac, Marte, Other_Os);
function Current_Os return Os_Type;
package App_Env is new Ada.Containers.Indefinite_Ordered_Maps
(Key_Type => String,
Element_Type => String);
-- More easily managed environment variable list for use with commands
-- launched.
function Current_Environment return App_Env.Map;
Original_Env : constant App_Env.Map := Current_Environment;
procedure Set_Environment (New_Env : App_Env.Map);
package X_Resources is new Ada.Containers.Indefinite_Ordered_Maps
(Key_Type => String,
Element_Type => String);
-- Similar to environment variable list, but X Resources apply only to
-- Xorg/X11 applications and are typically added with "-xrm", an option
-- only supported by Xorg apps.
package Arguments is new Ada.Containers.Indefinite_Vectors
(Index_Type => Positive,
Element_Type => String);
-- A flat array of Arguments given to the application, typically after
-- other command arguments automatically generated by the other
-- variables.
function "="
(Left : Arguments.Vector;
Right : Arguments.Vector) return Boolean renames
Arguments."=";
function "&"
(Left : Arguments.Vector;
Right : Arguments.Vector) return Arguments.Vector renames
Arguments."&";
function "+" (Right : String) return Arguments.Vector;
function "&"
(Left : Arguments.Vector;
Right : String) return Arguments.Vector;
function "+"
(Left : Arguments.Vector;
Right : String) return Arguments.Vector;
function "+"
(Left : String;
Right : Arguments.Vector) return Arguments.Vector;
function "+" (S : String) return GNAT.OS_Lib.String_Access;
function "+" (S : String) return GNAT.OS_Lib.Argument_List;
function "+" (V : Arguments.Vector) return GNAT.OS_Lib.Argument_List;
function Clone_Arguments return Arguments.Vector;
procedure Put_Error (Message : String := "");
-- Message to report to Standard Error. Only provided for convenience.
type Id_String is new String (1 .. 32) with
Default_Component_Value => NUL;
Null_Id : constant Id_String := (others => NUL);
procedure Chromium_App
-- A Chromium_App with the App_ID is launched, if it is a valid length; else,
-- the URL is launched as an app. Because some apps are set to open in new
-- tabs rather than in their own window, New_Window specifies that the
-- new-window option argument will be added.
(Profile : String := "";
-- Chromium / Google Chrome defaults to "Default", "Profile 1", etc.
-- If your profile directories are all custom, you must always give
-- the correct Profile.
App_Id : Id_String := Null_Id;
-- App_ID should be 32 alpha-numeric characters. If it is not, it
-- the URL String will be taken instead.
Url : String := "";
-- URL is for Chromium application windows without browser controls,
-- only with the application not locally installed. URL specifies
-- any URL as the source for the web app.
New_Window : Boolean := True;
-- In case an installed app has a "New Tab" setting rather than a new
-- window, this option will make the new tab have it's own window as
-- well.
Options : in Arguments.Vector := Arguments.Empty_Vector.Copy
-- Options to Chromium to be passed after the built-in Profile and
-- App_ID options. Currently, only special --<alnum<>> options and
-- file names are accepted. For now, Chromium is not .known to pass
-- any options (other than valid filenames) to the app for in-app
-- handling.
);
procedure Xapp
-- Specifically for Xorg applications in order to pass X resources to them.
-- New_Env will be merged info System Environment, but with higher priority.
(X_Command : String := "xterm";
-- Xorg executable that accepts "-xrm" option.
Options : Arguments.Vector := Arguments.Empty_Vector.Copy;
-- Command line options. "-xrm" options specified here will be listed
-- after resoures in Xrm, therefore should have higher presidence.
New_Env : App_Env.Map := App_Env.Empty_Map.Copy;
-- Environment that will be merged into current and therefore the
-- inherited environment.
Xrm : X_Resources.Map := X_Resources.Empty_Map.Copy
-- X Resources organized as an Ada Native map: Key is String of name of
-- resource and Element is String containing the complete resource spec.
);
procedure Xterm_App
(Command : in String := "top";
Options : in Arguments.Vector := Arguments.Empty_Vector.Copy;
Geometry : in String := "";
Managed : in Boolean := True;
New_Env : in App_Env.Map := App_Env.Empty_Map.Copy;
Xrm : in X_Resources.Map := X_Resources.Empty_Map.Copy);
-- Command is a shell script list exactly as passed at an SH statement for
-- the xterm -e option. Options are passed to xterm, not to the application,
-- so keep this in mind when handling arguments.
-- Geometry is X geometry. Managed is whether (true) to allow the window to
-- be managed by a window manager or (false) be embedded in the screen a
-- little like a desktop-background app.
-- New_Env is for app-specific environment variables and Xrm is the X-app-
-- specific resource variables.
procedure Clone_Launch
(Command : in String := "/usr/bin/" & Simple_Name (Command_Name);
Prepend_Arguments : in Arguments.Vector := Arguments.Empty_Vector.Copy;
Append_Arguments : in Arguments.Vector := Arguments.Empty_Vector.Copy);
-- Clone arguments from current execution arguments.
-- This, used as is without arguments simply relaunches itself from /usr/bin
-- This can be placed in a folder not in the PATH variable, but
-- for creating executables for /usr/bin or somewhere listed in PATH,
-- you should explicitely give a command that has a different name as the
-- current executable.
-- This is the best procedure to use for basic Success/Failure execution
-- where a custom environment is needed and can be setup before launching
-- the command.
procedure Command
(Command : String := "true";
Args : Arguments.Vector := Arguments.Empty_Vector.Copy);
-- Simple system command. PATH will be searched for command.
-- setting the Ada program's, return of success or failure is still supported.
procedure Practice;
private
Saved_Os : Os_Type := Other_Os;
end Ada_Launch;
|
------------------------------------------------------------------------------
-- ZLib for Ada thick binding. --
-- --
-- Copyright (C) 2002-2004 Dmitriy Anisimkov --
-- --
-- This library is free software; you can redistribute it and/or modify --
-- it under the terms of the GNU General Public License as published by --
-- the Free Software Foundation; either version 2 of the License, or (at --
-- your option) any later version. --
-- --
-- This 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 --
-- General Public License for more details. --
-- --
-- You should have received a copy of the GNU General Public License --
-- along with this library; if not, write to the Free Software Foundation, --
-- Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. --
-- --
-- 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. --
------------------------------------------------------------------------------
-- $Id: zlib.ads,v 1.26 2004/09/06 06:53:19 vagul Exp $
with Ada.Streams;
with Interfaces;
package ZLib is
ZLib_Error : exception;
Status_Error : exception;
type Compression_Level is new Integer range -1 .. 9;
type Flush_Mode is private;
type Compression_Method is private;
type Window_Bits_Type is new Integer range 8 .. 15;
type Memory_Level_Type is new Integer range 1 .. 9;
type Unsigned_32 is new Interfaces.Unsigned_32;
type Strategy_Type is private;
type Header_Type is (None, Auto, Default, GZip);
-- Header type usage have a some limitation for inflate.
-- See comment for Inflate_Init.
subtype Count is Ada.Streams.Stream_Element_Count;
Default_Memory_Level : constant Memory_Level_Type := 8;
Default_Window_Bits : constant Window_Bits_Type := 15;
----------------------------------
-- Compression method constants --
----------------------------------
Deflated : constant Compression_Method;
-- Only one method allowed in this ZLib version
---------------------------------
-- Compression level constants --
---------------------------------
No_Compression : constant Compression_Level := 0;
Best_Speed : constant Compression_Level := 1;
Best_Compression : constant Compression_Level := 9;
Default_Compression : constant Compression_Level := -1;
--------------------------
-- Flush mode constants --
--------------------------
No_Flush : constant Flush_Mode;
-- Regular way for compression, no flush
Partial_Flush : constant Flush_Mode;
-- Will be removed, use Z_SYNC_FLUSH instead
Sync_Flush : constant Flush_Mode;
-- All pending output is flushed to the output buffer and the output
-- is aligned on a byte boundary, so that the decompressor can get all
-- input data available so far. (In particular avail_in is zero after the
-- call if enough output space has been provided before the call.)
-- Flushing may degrade compression for some compression algorithms and so
-- it should be used only when necessary.
Block_Flush : constant Flush_Mode;
-- Z_BLOCK requests that inflate() stop
-- if and when it get to the next deflate block boundary. When decoding the
-- zlib or gzip format, this will cause inflate() to return immediately
-- after the header and before the first block. When doing a raw inflate,
-- inflate() will go ahead and process the first block, and will return
-- when it gets to the end of that block, or when it runs out of data.
Full_Flush : constant Flush_Mode;
-- All output is flushed as with SYNC_FLUSH, and the compression state
-- is reset so that decompression can restart from this point if previous
-- compressed data has been damaged or if random access is desired. Using
-- Full_Flush too often can seriously degrade the compression.
Finish : constant Flush_Mode;
-- Just for tell the compressor that input data is complete.
------------------------------------
-- Compression strategy constants --
------------------------------------
-- RLE stategy could be used only in version 1.2.0 and later.
Filtered : constant Strategy_Type;
Huffman_Only : constant Strategy_Type;
RLE : constant Strategy_Type;
Default_Strategy : constant Strategy_Type;
Default_Buffer_Size : constant := 4096;
type Filter_Type is tagged limited private;
-- The filter is for compression and for decompression.
-- The usage of the type is depend of its initialization.
function Version return String;
pragma Inline (Version);
-- Return string representation of the ZLib version.
procedure Deflate_Init
(Filter : in out Filter_Type;
Level : in Compression_Level := Default_Compression;
Strategy : in Strategy_Type := Default_Strategy;
Method : in Compression_Method := Deflated;
Window_Bits : in Window_Bits_Type := Default_Window_Bits;
Memory_Level : in Memory_Level_Type := Default_Memory_Level;
Header : in Header_Type := Default);
-- Compressor initialization.
-- When Header parameter is Auto or Default, then default zlib header
-- would be provided for compressed data.
-- When Header is GZip, then gzip header would be set instead of
-- default header.
-- When Header is None, no header would be set for compressed data.
procedure Inflate_Init
(Filter : in out Filter_Type;
Window_Bits : in Window_Bits_Type := Default_Window_Bits;
Header : in Header_Type := Default);
-- Decompressor initialization.
-- Default header type mean that ZLib default header is expecting in the
-- input compressed stream.
-- Header type None mean that no header is expecting in the input stream.
-- GZip header type mean that GZip header is expecting in the
-- input compressed stream.
-- Auto header type mean that header type (GZip or Native) would be
-- detected automatically in the input stream.
-- Note that header types parameter values None, GZip and Auto are
-- supported for inflate routine only in ZLib versions 1.2.0.2 and later.
-- Deflate_Init is supporting all header types.
function Is_Open (Filter : in Filter_Type) return Boolean;
pragma Inline (Is_Open);
-- Is the filter opened for compression or decompression.
procedure Close
(Filter : in out Filter_Type;
Ignore_Error : in Boolean := False);
-- Closing the compression or decompressor.
-- If stream is closing before the complete and Ignore_Error is False,
-- The exception would be raised.
generic
with procedure Data_In
(Item : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
with procedure Data_Out
(Item : in Ada.Streams.Stream_Element_Array);
procedure Generic_Translate
(Filter : in out Filter_Type;
In_Buffer_Size : in Integer := Default_Buffer_Size;
Out_Buffer_Size : in Integer := Default_Buffer_Size);
-- Compress/decompress data fetch from Data_In routine and pass the result
-- to the Data_Out routine. User should provide Data_In and Data_Out
-- for compression/decompression data flow.
-- Compression or decompression depend on Filter initialization.
function Total_In (Filter : in Filter_Type) return Count;
pragma Inline (Total_In);
-- Returns total number of input bytes read so far
function Total_Out (Filter : in Filter_Type) return Count;
pragma Inline (Total_Out);
-- Returns total number of bytes output so far
function CRC32
(CRC : in Unsigned_32;
Data : in Ada.Streams.Stream_Element_Array)
return Unsigned_32;
pragma Inline (CRC32);
-- Compute CRC32, it could be necessary for make gzip format
procedure CRC32
(CRC : in out Unsigned_32;
Data : in Ada.Streams.Stream_Element_Array);
pragma Inline (CRC32);
-- Compute CRC32, it could be necessary for make gzip format
-------------------------------------------------
-- Below is more complex low level routines. --
-------------------------------------------------
procedure Translate
(Filter : in out Filter_Type;
In_Data : in Ada.Streams.Stream_Element_Array;
In_Last : out Ada.Streams.Stream_Element_Offset;
Out_Data : out Ada.Streams.Stream_Element_Array;
Out_Last : out Ada.Streams.Stream_Element_Offset;
Flush : in Flush_Mode);
-- Compress/decompress the In_Data buffer and place the result into
-- Out_Data. In_Last is the index of last element from In_Data accepted by
-- the Filter. Out_Last is the last element of the received data from
-- Filter. To tell the filter that incoming data are complete put the
-- Flush parameter to Finish.
function Stream_End (Filter : in Filter_Type) return Boolean;
pragma Inline (Stream_End);
-- Return the true when the stream is complete.
procedure Flush
(Filter : in out Filter_Type;
Out_Data : out Ada.Streams.Stream_Element_Array;
Out_Last : out Ada.Streams.Stream_Element_Offset;
Flush : in Flush_Mode);
pragma Inline (Flush);
-- Flushing the data from the compressor.
generic
with procedure Write
(Item : in Ada.Streams.Stream_Element_Array);
-- User should provide this routine for accept
-- compressed/decompressed data.
Buffer_Size : in Ada.Streams.Stream_Element_Offset
:= Default_Buffer_Size;
-- Buffer size for Write user routine.
procedure Write
(Filter : in out Filter_Type;
Item : in Ada.Streams.Stream_Element_Array;
Flush : in Flush_Mode := No_Flush);
-- Compress/Decompress data from Item to the generic parameter procedure
-- Write. Output buffer size could be set in Buffer_Size generic parameter.
generic
with procedure Read
(Item : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
-- User should provide data for compression/decompression
-- thru this routine.
Buffer : in out Ada.Streams.Stream_Element_Array;
-- Buffer for keep remaining data from the previous
-- back read.
Rest_First, Rest_Last : in out Ada.Streams.Stream_Element_Offset;
-- Rest_First have to be initialized to Buffer'Last + 1
-- Rest_Last have to be initialized to Buffer'Last
-- before usage.
Allow_Read_Some : in Boolean := False;
-- Is it allowed to return Last < Item'Last before end of data.
procedure Read
(Filter : in out Filter_Type;
Item : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Flush : in Flush_Mode := No_Flush);
-- Compress/Decompress data from generic parameter procedure Read to the
-- Item. User should provide Buffer and initialized Rest_First, Rest_Last
-- indicators. If Allow_Read_Some is True, Read routines could return
-- Last < Item'Last only at end of stream.
private
use Ada.Streams;
pragma Assert (Ada.Streams.Stream_Element'Size = 8);
pragma Assert (Ada.Streams.Stream_Element'Modulus = 2**8);
type Flush_Mode is new Integer range 0 .. 5;
type Compression_Method is new Integer range 8 .. 8;
type Strategy_Type is new Integer range 0 .. 3;
No_Flush : constant Flush_Mode := 0;
Partial_Flush : constant Flush_Mode := 1;
Sync_Flush : constant Flush_Mode := 2;
Full_Flush : constant Flush_Mode := 3;
Finish : constant Flush_Mode := 4;
Block_Flush : constant Flush_Mode := 5;
Filtered : constant Strategy_Type := 1;
Huffman_Only : constant Strategy_Type := 2;
RLE : constant Strategy_Type := 3;
Default_Strategy : constant Strategy_Type := 0;
Deflated : constant Compression_Method := 8;
type Z_Stream;
type Z_Stream_Access is access all Z_Stream;
type Filter_Type is tagged limited record
Strm : Z_Stream_Access;
Compression : Boolean;
Stream_End : Boolean;
Header : Header_Type;
CRC : Unsigned_32;
Offset : Stream_Element_Offset;
-- Offset for gzip header/footer output.
end record;
end ZLib;
|
----------------------------------------------------------------
-- ZLib for Ada thick binding. --
-- --
-- Copyright (C) 2002-2003 Dmitriy Anisimkov --
-- --
-- Open source license information is in the zlib.ads file. --
----------------------------------------------------------------
-- Continuous test for ZLib multithreading. If the test is fail
-- Wou should provide thread safe allocation routines for the Z_Stream.
--
-- $Id: mtest.adb,v 1.2 2003/08/12 12:11:05 vagul Exp $
with ZLib;
with Ada.Streams;
with Ada.Numerics.Discrete_Random;
with Ada.Text_IO;
with Ada.Exceptions;
with Ada.Task_Identification;
procedure MTest is
use Ada.Streams;
use ZLib;
Stop : Boolean := False;
pragma Atomic (Stop);
subtype Visible_Symbols is Stream_Element range 16#20# .. 16#7E#;
package Random_Elements is
new Ada.Numerics.Discrete_Random (Visible_Symbols);
task type Test_Task;
task body Test_Task is
Buffer : Stream_Element_Array (1 .. 100_000);
Gen : Random_Elements.Generator;
Buffer_First : Stream_Element_Offset;
Compare_First : Stream_Element_Offset;
Deflate : Filter_Type;
Inflate : Filter_Type;
procedure Further (Item : in Stream_Element_Array);
procedure Read_Buffer
(Item : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
-------------
-- Further --
-------------
procedure Further (Item : in Stream_Element_Array) is
procedure Compare (Item : in Stream_Element_Array);
-------------
-- Compare --
-------------
procedure Compare (Item : in Stream_Element_Array) is
Next_First : Stream_Element_Offset := Compare_First + Item'Length;
begin
if Buffer (Compare_First .. Next_First - 1) /= Item then
raise Program_Error;
end if;
Compare_First := Next_First;
end Compare;
procedure Compare_Write is new ZLib.Write (Write => Compare);
begin
Compare_Write (Inflate, Item, No_Flush);
end Further;
-----------------
-- Read_Buffer --
-----------------
procedure Read_Buffer
(Item : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset)
is
Buff_Diff : Stream_Element_Offset := Buffer'Last - Buffer_First;
Next_First : Stream_Element_Offset;
begin
if Item'Length <= Buff_Diff then
Last := Item'Last;
Next_First := Buffer_First + Item'Length;
Item := Buffer (Buffer_First .. Next_First - 1);
Buffer_First := Next_First;
else
Last := Item'First + Buff_Diff;
Item (Item'First .. Last) := Buffer (Buffer_First .. Buffer'Last);
Buffer_First := Buffer'Last + 1;
end if;
end Read_Buffer;
procedure Translate is new Generic_Translate
(Data_In => Read_Buffer,
Data_Out => Further);
begin
Random_Elements.Reset (Gen);
Buffer := (others => 20);
Main : loop
for J in Buffer'Range loop
Buffer (J) := Random_Elements.Random (Gen);
Deflate_Init (Deflate);
Inflate_Init (Inflate);
Buffer_First := Buffer'First;
Compare_First := Buffer'First;
Translate (Deflate);
if Compare_First /= Buffer'Last + 1 then
raise Program_Error;
end if;
Ada.Text_IO.Put_Line
(Ada.Task_Identification.Image
(Ada.Task_Identification.Current_Task)
& Stream_Element_Offset'Image (J)
& ZLib.Count'Image (Total_Out (Deflate)));
Close (Deflate);
Close (Inflate);
exit Main when Stop;
end loop;
end loop Main;
exception
when E : others =>
Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Information (E));
Stop := True;
end Test_Task;
Test : array (1 .. 4) of Test_Task;
pragma Unreferenced (Test);
begin
null;
end MTest;
|
with Ada.Command_Line;
with Ada.Text_IO;
with ZMQ;
procedure Version is
function Main return Ada.Command_Line.Exit_Status
is
Major, Minor, Patch : Natural;
begin
ZMQ.Version (Major, Minor, Patch);
Ada.Text_IO.Put_Line ("Current 0MQ version is "&Major'Img&"."&Minor'Img&"."&Patch'Img);
return 0;
end Main;
begin
Ada.Command_Line.Set_Exit_Status (Main);
end Version;
|
-- Shoot'n'loot
-- Copyright (c) 2020 Fabien Chouteau
package Menus is
procedure Run with No_Return;
end Menus;
|
with System.Native_Time;
with C.sys.resource;
with C.sys.time;
package body System.Native_Execution_Time is
use type C.signed_int;
function To_Duration (D : C.sys.time.struct_timeval) return Duration;
function To_Duration (D : C.sys.time.struct_timeval) return Duration is
begin
return Native_Time.To_Duration (Native_Time.To_timespec (D));
end To_Duration;
-- implementation
function Clock return CPU_Time is
rusage : aliased C.sys.resource.struct_rusage;
begin
if C.sys.resource.getrusage (
C.sys.resource.RUSAGE_SELF,
rusage'Access) < 0
then
raise Program_Error; -- ???
else
return To_Duration (rusage.ru_utime);
end if;
end Clock;
end System.Native_Execution_Time;
|
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Price_Fraction is
-- Put the declarations here
Value : Price := Price'First;
begin
loop
Put_Line (Price'Image (Value) & "->" & Price'Image (Scale (Value)));
exit when Value = Price'Last;
Value := Price'Succ (Value);
end loop;
end Test_Price_Fraction;
|
-----------------------------------------------------------------------
-- are-utils -- Utilities for model generator
-- Copyright (C) 2010, 2011, 2012, 2015, 2021 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with DOM.Core.Nodes;
with DOM.Core.Elements;
with DOM.Core.Character_Datas;
with Util.Strings;
package body Are.Utils is
-- ------------------------------
-- Generic procedure to iterate over the DOM nodes children of <b>node</b>
-- and having the entity name <b>name</b>.
-- ------------------------------
procedure Iterate_Nodes (Closure : in out T;
Node : in DOM.Core.Node;
Name : in String;
Recurse : in Boolean := True) is
begin
if Recurse then
declare
Nodes : DOM.Core.Node_List := DOM.Core.Elements.Get_Elements_By_Tag_Name (Node, Name);
Size : constant Natural := DOM.Core.Nodes.Length (Nodes);
begin
for I in 0 .. Size - 1 loop
declare
N : constant DOM.Core.Node := DOM.Core.Nodes.Item (Nodes, I);
begin
Process (Closure, N);
end;
end loop;
DOM.Core.Free (Nodes);
end;
else
declare
use type DOM.Core.Node_Types;
Nodes : constant DOM.Core.Node_List := DOM.Core.Nodes.Child_Nodes (Node);
Size : constant Natural := DOM.Core.Nodes.Length (Nodes);
begin
for I in 0 .. Size - 1 loop
declare
N : constant DOM.Core.Node := DOM.Core.Nodes.Item (Nodes, I);
T : constant DOM.Core.Node_Types := DOM.Core.Nodes.Node_Type (N);
begin
if T = DOM.Core.Element_Node and then Name = DOM.Core.Nodes.Node_Name (N) then
Process (Closure, N);
end if;
end;
end loop;
end;
end if;
end Iterate_Nodes;
-- ------------------------------
-- Get the first DOM child from the given entity tag
-- ------------------------------
function Get_Child (Node : DOM.Core.Node;
Name : String) return DOM.Core.Node is
Nodes : DOM.Core.Node_List :=
DOM.Core.Elements.Get_Elements_By_Tag_Name (Node, Name);
begin
if DOM.Core.Nodes.Length (Nodes) = 0 then
DOM.Core.Free (Nodes);
return null;
else
return Result : constant DOM.Core.Node := DOM.Core.Nodes.Item (Nodes, 0) do
DOM.Core.Free (Nodes);
end return;
end if;
end Get_Child;
-- ------------------------------
-- Get the content of the node
-- ------------------------------
function Get_Data_Content (Node : in DOM.Core.Node) return String is
Nodes : constant DOM.Core.Node_List := DOM.Core.Nodes.Child_Nodes (Node);
S : constant Natural := DOM.Core.Nodes.Length (Nodes);
Result : Unbounded_String;
begin
for J in 0 .. S - 1 loop
Append (Result, DOM.Core.Character_Datas.Data (DOM.Core.Nodes.Item (Nodes, J)));
end loop;
return To_String (Result);
end Get_Data_Content;
-- ------------------------------
-- Get the content of the node identified by <b>Name</b> under the given DOM node.
-- ------------------------------
function Get_Data_Content (Node : in DOM.Core.Node;
Name : in String) return String is
use type DOM.Core.Node;
N : constant DOM.Core.Node := Get_Child (Node, Name);
begin
if N = null then
return "";
else
return Are.Utils.Get_Data_Content (N);
end if;
end Get_Data_Content;
-- ------------------------------
-- Get a boolean attribute
-- ------------------------------
function Get_Attribute (Node : in DOM.Core.Node;
Name : in String;
Default : in Boolean := False) return Boolean is
V : constant DOM.Core.DOM_String := DOM.Core.Elements.Get_Attribute (Node, Name);
begin
if V = "yes" or V = "true" then
return True;
elsif V = "no" or V = "false" then
return False;
else
return Default;
end if;
end Get_Attribute;
-- ------------------------------
-- Get a string attribute
-- ------------------------------
function Get_Attribute (Node : in DOM.Core.Node;
Name : in String;
Default : in String := "") return String is
V : constant DOM.Core.DOM_String := DOM.Core.Elements.Get_Attribute (Node, Name);
begin
if V = "" then
return Default;
else
return V;
end if;
end Get_Attribute;
-- ------------------------------
-- Returns True if the file name must be ignored (.svn, CVS, .git, are ignored).
-- ------------------------------
function Is_File_Ignored (Name : in String) return Boolean is
begin
if Name = ".svn" then
return True;
elsif Name = ".git" then
return True;
elsif Name = "CVS" then
return True;
elsif Name = "." or else Name = ".." then
return True;
elsif Name'Length = 0 then
return True;
elsif Name (Name'Last) = '~' then
return True;
elsif Name (Name'First) = '#' and Name (Name'Last) = '#' then
return True;
else
return False;
end if;
end Is_File_Ignored;
-- ------------------------------
-- Get a string attribute
-- ------------------------------
function Get_Attribute (Node : DOM.Core.Node;
Name : String;
Default : String := "") return Ada.Strings.Unbounded.Unbounded_String is
V : constant DOM.Core.DOM_String := DOM.Core.Elements.Get_Attribute (Node, Name);
begin
if V = "" then
return To_Unbounded_String (Default);
else
return To_Unbounded_String (V);
end if;
end Get_Attribute;
end Are.Utils;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Web Framework --
-- --
-- Tools Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2012-2013, 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$
------------------------------------------------------------------------------
-- Root package for AST of WSDL.
------------------------------------------------------------------------------
with Ada.Containers;
with League.Strings;
limited with WSDL.AST.Bindings;
limited with WSDL.AST.Descriptions;
limited with WSDL.AST.Faults;
limited with WSDL.AST.Interfaces;
limited with WSDL.AST.Messages;
limited with WSDL.AST.Operations;
limited with WSDL.Iterators;
limited with WSDL.Visitors;
package WSDL.AST is
pragma Preelaborate;
type Qualified_Name is record
Namespace_URI : League.Strings.Universal_String;
Local_Name : League.Strings.Universal_String;
end record;
function Image
(Item : Qualified_Name) return League.Strings.Universal_String;
function Hash (Item : Qualified_Name) return Ada.Containers.Hash_Type;
type Message_Content_Models is (Element, Any, None, Other);
type Message_Directions is (In_Message, Out_Message);
-------------------
-- Abstract Node --
-------------------
type Abstract_Node is abstract tagged record
null;
end record;
type Node_Access is access all Abstract_Node'Class;
not overriding procedure Enter
(Self : not null access Abstract_Node;
Visitor : in out WSDL.Visitors.WSDL_Visitor'Class;
Control : in out WSDL.Iterators.Traverse_Control) is abstract;
not overriding procedure Leave
(Self : not null access Abstract_Node;
Visitor : in out WSDL.Visitors.WSDL_Visitor'Class;
Control : in out WSDL.Iterators.Traverse_Control) is abstract;
not overriding procedure Visit
(Self : not null access Abstract_Node;
Iterator : in out WSDL.Iterators.WSDL_Iterator'Class;
Visitor : in out WSDL.Visitors.WSDL_Visitor'Class;
Control : in out WSDL.Iterators.Traverse_Control) is abstract;
type Binding_Access is access all WSDL.AST.Bindings.Binding_Node'Class;
type Binding_Fault_Access is
access all WSDL.AST.Faults.Binding_Fault_Node'Class;
type Binding_Operation_Access is
access all WSDL.AST.Operations.Binding_Operation_Node'Class;
type Description_Access is
access all WSDL.AST.Descriptions.Description_Node'Class;
type Interface_Access is
access all WSDL.AST.Interfaces.Interface_Node'Class;
type Interface_Fault_Access is
access all WSDL.AST.Faults.Interface_Fault_Node'Class;
type Interface_Message_Access is
access all WSDL.AST.Messages.Interface_Message_Node'Class;
type Interface_Operation_Access is
access all WSDL.AST.Operations.Interface_Operation_Node'Class;
type Interface_Fault_Reference_Access is
access all WSDL.AST.Faults.Interface_Fault_Reference_Node'Class;
end WSDL.AST;
|
procedure Entry_Body_Declaration is
protected Obj is
entry Start;
private
Is_Set : Boolean := False;
end Obj;
protected body Obj is
entry Start when Is_Set is
begin
null;
end;
end Obj;
begin
null;
end Entry_Body_Declaration;
|
with Ada.Exception_Identification.From_Here;
with Ada.Exceptions.Finally;
with Ada.Unchecked_Deallocation;
with System.Form_Parameters;
with System.UTF_Conversions;
package body Ada.Naked_Text_IO is
use Exception_Identification.From_Here;
use type IO_Modes.File_External;
use type IO_Modes.File_External_Spec;
use type IO_Modes.File_Mode;
use type IO_Modes.File_New_Line;
use type IO_Modes.File_New_Line_Spec;
use type Streams.Stream_Element_Offset;
use type System.UTF_Conversions.UCS_4;
procedure unreachable
with Import,
Convention => Intrinsic, External_Name => "__builtin_unreachable";
pragma No_Return (unreachable);
function To_Pointer (Value : System.Address)
return access Streams.Root_Stream_Type'Class
with Import, Convention => Intrinsic;
-- the parameter Form
function Select_External (Spec : IO_Modes.File_External_Spec)
return IO_Modes.File_External;
function Select_External (Spec : IO_Modes.File_External_Spec)
return IO_Modes.File_External is
begin
case Spec is
when IO_Modes.UTF_8 =>
return IO_Modes.UTF_8;
when IO_Modes.Locale =>
declare
Locale_Support : constant Boolean :=
System.Native_Text_IO.Default_External = IO_Modes.Locale;
begin
if Locale_Support then
return IO_Modes.Locale; -- Windows
else
return IO_Modes.UTF_8; -- POSIX
end if;
end;
when IO_Modes.By_Target =>
return System.Native_Text_IO.Default_External;
end case;
end Select_External;
function Select_New_Line (Spec : IO_Modes.File_New_Line_Spec)
return IO_Modes.File_New_Line;
function Select_New_Line (Spec : IO_Modes.File_New_Line_Spec)
return IO_Modes.File_New_Line is
begin
case Spec is
when IO_Modes.LF | IO_Modes.CR | IO_Modes.CR_LF =>
return IO_Modes.File_New_Line (Spec);
when IO_Modes.By_Target =>
return System.Native_Text_IO.Default_New_Line;
end case;
end Select_New_Line;
-- implementation of the parameter Form
procedure Set (
Form : in out System.Native_Text_IO.Packed_Form;
Keyword : String;
Item : String) is
begin
if Keyword = "external" then
if Item'Length > 0 and then Item (Item'First) = 'd' then -- dbcs
Form.External := IO_Modes.Locale;
elsif Item'Length > 0
and then Item (Item'First) = 'u'
and then Item (Item'Last) = '8'
then -- utf-8
Form.External := IO_Modes.UTF_8;
end if;
elsif Keyword = "wcem" then
-- compatibility with GNAT runtime
if Item'Length > 0 and then Item (Item'First) = '8' then
Form.External := IO_Modes.UTF_8;
end if;
elsif Keyword = "nl" then -- abbr or new_line
if Item'Length > 0 and then Item (Item'First) = 'l' then -- lf
Form.New_Line := IO_Modes.LF;
elsif Item'Length > 0 and then Item (Item'First) = 'c' then -- cr
Form.New_Line := IO_Modes.CR;
elsif Item'Length > 0 and then Item (Item'First) = 'm' then
Form.New_Line := IO_Modes.CR_LF;
end if;
else
Streams.Naked_Stream_IO.Set (Form.Stream_Form, Keyword, Item);
end if;
end Set;
function Pack (Form : String) return System.Native_Text_IO.Packed_Form is
Keyword_First : Positive;
Keyword_Last : Natural;
Item_First : Positive;
Item_Last : Natural;
Last : Natural;
begin
return Result : System.Native_Text_IO.Packed_Form := Default_Form do
Last := Form'First - 1;
while Last < Form'Last loop
System.Form_Parameters.Get (
Form (Last + 1 .. Form'Last),
Keyword_First,
Keyword_Last,
Item_First,
Item_Last,
Last);
Set (
Result,
Form (Keyword_First .. Keyword_Last),
Form (Item_First .. Item_Last));
end loop;
end return;
end Pack;
procedure Unpack (
Form : System.Native_Text_IO.Packed_Form;
Result : out Streams.Naked_Stream_IO.Form_String;
Last : out Natural)
is
subtype Valid_File_External_Spec is
IO_Modes.File_External_Spec range IO_Modes.UTF_8 .. IO_Modes.Locale;
New_Last : Natural;
begin
Streams.Naked_Stream_IO.Unpack (Form.Stream_Form, Result, Last);
if Form.External /= IO_Modes.By_Target then
if Last /= Streams.Naked_Stream_IO.Form_String'First - 1 then
New_Last := Last + 1;
Result (New_Last) := ',';
Last := New_Last;
end if;
case Valid_File_External_Spec (Form.External) is
when IO_Modes.UTF_8 =>
New_Last := Last + 14;
Result (Last + 1 .. New_Last) := "external=utf-8";
when IO_Modes.Locale =>
New_Last := Last + 13;
Result (Last + 1 .. New_Last) := "external=dbcs";
end case;
Last := New_Last;
end if;
if Form.New_Line /= IO_Modes.By_Target then
if Last /= Streams.Naked_Stream_IO.Form_String'First - 1 then
New_Last := Last + 1;
Result (New_Last) := ',';
Last := New_Last;
end if;
case IO_Modes.File_New_Line (Form.New_Line) is
when IO_Modes.LF =>
New_Last := Last + 5;
Result (Last + 1 .. New_Last) := "lm=lf";
Last := New_Last;
when IO_Modes.CR =>
New_Last := Last + 5;
Result (Last + 1 .. New_Last) := "lm=cr";
Last := New_Last;
when IO_Modes.CR_LF =>
New_Last := Last + 4;
Result (Last + 1 .. New_Last) := "lm=m";
Last := New_Last;
end case;
end if;
end Unpack;
-- non-controlled
procedure Free (X : in out Non_Controlled_File_Type);
procedure Free (X : in out Non_Controlled_File_Type) is
procedure Raw_Free is
new Unchecked_Deallocation (Text_Type, Non_Controlled_File_Type);
begin
System.Native_IO.Free (X.Name);
Raw_Free (X);
end Free;
type Open_Access is not null access procedure (
File : in out Streams.Naked_Stream_IO.Non_Controlled_File_Type;
Mode : IO_Modes.File_Mode;
Name : String;
Form : System.Native_IO.Packed_Form);
pragma Favor_Top_Level (Open_Access);
procedure Open_File (
Open_Proc : Open_Access;
File : in out Non_Controlled_File_Type;
Mode : IO_Modes.File_Mode;
Name : String;
Form : System.Native_Text_IO.Packed_Form);
procedure Open_File (
Open_Proc : Open_Access;
File : in out Non_Controlled_File_Type;
Mode : IO_Modes.File_Mode;
Name : String;
Form : System.Native_Text_IO.Packed_Form)
is
New_File : aliased Non_Controlled_File_Type := new Text_Type'(
Stream => System.Null_Address,
Name => null,
Mode => Mode,
External => <>,
New_Line => <>,
others => <>);
package Holder is
new Exceptions.Finally.Scoped_Holder (Non_Controlled_File_Type, Free);
begin
Holder.Assign (New_File);
-- open
Open_Proc (
File => New_File.File,
Mode => Mode,
Name => Name,
Form => Form.Stream_Form);
-- select encoding
if System.Native_IO.Is_Terminal (
Streams.Naked_Stream_IO.Handle (New_File.File))
then
New_File.External := IO_Modes.Terminal;
New_File.New_Line := System.Native_Text_IO.Default_New_Line;
else
New_File.External := Select_External (Form.External);
New_File.New_Line := Select_New_Line (Form.New_Line);
end if;
-- complete
Holder.Clear;
File := New_File;
end Open_File;
-- Input
-- * Read_Buffer sets (or keeps) Ahead_Col.
-- * Get adds Ahead_Col to current Col.
-- * Take_Buffer clears Ahead_Col.
procedure Read (
File : not null Non_Controlled_File_Type;
Item : out Streams.Stream_Element_Array;
Last : out Streams.Stream_Element_Offset);
procedure Read (
File : not null Non_Controlled_File_Type;
Item : out Streams.Stream_Element_Array;
Last : out Streams.Stream_Element_Offset) is
begin
if not Streams.Naked_Stream_IO.Is_Open (File.File) then
-- external stream mode
Streams.Read (To_Pointer (File.Stream).all, Item, Last);
else
Streams.Naked_Stream_IO.Read (File.File, Item, Last);
end if;
end Read;
procedure Read_Buffer (
File : Non_Controlled_File_Type;
Wanted : Positive := 1;
Wait : Boolean := True);
procedure Take_Buffer (
File : Non_Controlled_File_Type;
Length : Positive := 1);
procedure Take_Sequence (File : Non_Controlled_File_Type);
procedure Take_Page (File : Non_Controlled_File_Type);
procedure Take_Line (File : Non_Controlled_File_Type);
procedure Take_Line_Immediate (File : Non_Controlled_File_Type);
procedure Read_Buffer (
File : Non_Controlled_File_Type;
Wanted : Positive := 1;
Wait : Boolean := True) is
begin
if not File.End_Of_File and then File.Ahead_Last < Wanted then
if File.External = IO_Modes.Terminal then
declare
Read_Length : Streams.Stream_Element_Offset;
begin
if Wait then
System.Native_Text_IO.Terminal_Get (
Streams.Naked_Stream_IO.Handle (File.File),
File.Buffer (File.Last + 1)'Address,
1,
Read_Length);
if Read_Length = 0 then
File.End_Of_File := True;
end if;
else
System.Native_Text_IO.Terminal_Get_Immediate (
Streams.Naked_Stream_IO.Handle (File.File),
File.Buffer (File.Last + 1)'Address,
1,
Read_Length); -- Read_Length can be > 1
end if;
if Read_Length < 0 then
Raise_Exception (Device_Error'Identity);
end if;
File.Last := File.Last + Natural (Read_Length);
end;
else
-- read next single character
declare
Old_Last : constant Natural := File.Last;
Buffer : Streams.Stream_Element_Array (
Streams.Stream_Element_Offset (Old_Last + 1) ..
Streams.Stream_Element_Offset (Old_Last + 1));
for Buffer'Address use File.Buffer (Old_Last + 1)'Address;
Last : Streams.Stream_Element_Offset;
begin
Read (File, Buffer, Last);
File.Last := Natural'Base (Last);
if Wait and then File.Last = Old_Last then
File.End_Of_File := True;
end if;
end;
end if;
end if;
if File.Last > 0 and then File.Ahead_Last = 0 then
if File.External = IO_Modes.Terminal then
File.Ahead_Last := File.Last;
elsif File.External = IO_Modes.Locale
and then File.Buffer (1) >= Character'Val (16#80#)
then
declare
Locale_Support : constant Boolean :=
System.Native_Text_IO.Default_External = IO_Modes.Locale;
begin
if not Locale_Support then
unreachable;
end if;
end;
declare
DBCS_Buffer : aliased System.Native_Text_IO.DBCS_Buffer_Type;
New_Last : Natural;
begin
DBCS_Buffer (1) := File.Buffer (1);
DBCS_Buffer (2) := File.Buffer (2);
System.Native_Text_IO.To_UTF_8 (
DBCS_Buffer,
File.Last,
File.Buffer,
New_Last);
if New_Last > 0 then
-- all elements in buffer are converted
File.Ahead_Last := New_Last;
File.Ahead_Col := File.Last;
File.Last := New_Last;
elsif File.End_Of_File then
-- expected trailing byte is missing
File.Ahead_Last := File.Last;
File.Ahead_Col := File.Last;
end if;
end;
else
File.Ahead_Last := 1;
File.Ahead_Col := 1;
end if;
end if;
end Read_Buffer;
procedure Take_Buffer (
File : Non_Controlled_File_Type;
Length : Positive := 1)
is
New_Last : constant Natural := File.Last - Length;
begin
File.Buffer (1 .. New_Last) := File.Buffer (1 + Length .. File.Last);
File.Last := New_Last;
File.Ahead_Last := File.Ahead_Last - Length;
File.Ahead_Col := 0;
File.Looked_Ahead_Last := 0;
File.Virtual_Mark := None;
end Take_Buffer;
procedure Take_Sequence (File : Non_Controlled_File_Type) is
begin
File.Col := File.Col + File.Ahead_Col;
Take_Buffer (File, Length => File.Looked_Ahead_Last);
if File.Looked_Ahead_Second (1) /= Character'Val (0) then
-- Prepend a second of surrogate pair to the buffer.
declare
New_Last : constant Natural := File.Last + 3;
begin
File.Buffer (4 .. New_Last) := File.Buffer (1 .. File.Last);
File.Buffer (1 .. 3) := File.Looked_Ahead_Second;
File.Last := New_Last;
File.Ahead_Last := File.Ahead_Last + 3;
end;
end if;
end Take_Sequence;
procedure Take_Page (File : Non_Controlled_File_Type) is
begin
Take_Buffer (File);
File.Virtual_Mark := EOP;
File.Line := 1;
File.Page := File.Page + 1;
File.Col := 1;
end Take_Page;
procedure Take_Line (File : Non_Controlled_File_Type) is
C : constant Character := File.Buffer (1);
begin
File.Line := File.Line + 1;
File.Col := 1;
Take_Buffer (File);
if C = Character'Val (16#0d#) then
Read_Buffer (File);
if File.Buffer (1) = Character'Val (16#0a#) then
Take_Buffer (File);
end if;
end if;
end Take_Line;
procedure Take_Line_Immediate (File : Non_Controlled_File_Type) is
C : constant Character := File.Buffer (1);
begin
Take_Buffer (File);
if C = Character'Val (16#0d#) then
Read_Buffer (File);
if File.Buffer (1) = Character'Val (16#0a#) then
File.Col := File.Col + 1; -- do not get LF here
else
File.Line := File.Line + 1; -- CR without LF
File.Col := 1;
end if;
else
File.Line := File.Line + 1; -- LF
File.Col := 1;
end if;
end Take_Line_Immediate;
type Restore_Type is record
Handle : System.Native_IO.Handle_Type;
Old_Settings : aliased System.Native_Text_IO.Setting;
end record;
pragma Suppress_Initialization (Restore_Type);
procedure Finally (X : in out Restore_Type);
procedure Finally (X : in out Restore_Type) is
begin
System.Native_Text_IO.Restore (X.Handle, X.Old_Settings);
end Finally;
procedure Look_Ahead_Immediate (
File : Non_Controlled_File_Type;
Item : out Character;
Available : out Boolean;
Wait : Boolean);
procedure Skip_Ahead_Immediate (File : Non_Controlled_File_Type);
procedure Look_Ahead_Immediate (
File : Non_Controlled_File_Type;
Item : out Character;
Available : out Boolean;
Wait : Boolean) is
begin
loop
Read_Buffer (File, Wait => Wait);
if File.Ahead_Last > 0 then
File.Looked_Ahead_Last := 1; -- implies CR-LF sequence
File.Looked_Ahead_Second (1) := Character'Val (0);
Item := File.Buffer (1);
Available := True;
exit;
elsif File.End_Of_File then
File.Looked_Ahead_Last := 1;
File.Looked_Ahead_Second (1) := Character'Val (0);
Raise_Exception (End_Error'Identity);
elsif not Wait then
Item := Character'Val (0);
Available := False;
exit;
end if;
end loop;
end Look_Ahead_Immediate;
procedure Skip_Ahead_Immediate (File : Non_Controlled_File_Type) is
begin
if File.External = IO_Modes.Terminal then
-- Do not wait CR-LF sequence, nor update Col and Line.
Take_Buffer (File, Length => File.Looked_Ahead_Last);
else
-- Update Col and Line.
declare
C : constant Character := File.Buffer (1);
begin
case C is
when Character'Val (16#0d#) | Character'Val (16#0a#) =>
Take_Line_Immediate (File);
when Character'Val (16#0c#) =>
Take_Page (File);
when others =>
Take_Sequence (File);
end case;
end;
end if;
end Skip_Ahead_Immediate;
procedure Get_Immediate (
File : Non_Controlled_File_Type;
Item : out Character;
Available : out Boolean;
Wait : Boolean);
procedure Get_Immediate (
File : Non_Controlled_File_Type;
Item : out Wide_Character;
Available : out Boolean;
Wait : Boolean);
procedure Get_Immediate (
File : Non_Controlled_File_Type;
Item : out Wide_Wide_Character;
Available : out Boolean;
Wait : Boolean);
procedure Get_Immediate (
File : Non_Controlled_File_Type;
Item : out Character;
Available : out Boolean;
Wait : Boolean)
is
package Holder is
new Exceptions.Finally.Scoped_Holder (Restore_Type, Finally);
X : aliased Restore_Type;
begin
if File.External = IO_Modes.Terminal then
X.Handle := Streams.Naked_Stream_IO.Handle (File.File);
System.Native_Text_IO.Set_Non_Canonical_Mode (
X.Handle,
Wait, -- only POSIX
X.Old_Settings);
Holder.Assign (X);
end if;
Look_Ahead_Immediate (File, Item, Available, Wait);
if Available then
Skip_Ahead_Immediate (File);
end if;
end Get_Immediate;
procedure Get_Immediate (
File : Non_Controlled_File_Type;
Item : out Wide_Character;
Available : out Boolean;
Wait : Boolean)
is
package Holder is
new Exceptions.Finally.Scoped_Holder (Restore_Type, Finally);
X : aliased Restore_Type;
C : Character;
begin
if File.External = IO_Modes.Terminal then
X.Handle := Streams.Naked_Stream_IO.Handle (File.File);
System.Native_Text_IO.Set_Non_Canonical_Mode (
X.Handle,
Wait, -- only POSIX
X.Old_Settings);
Holder.Assign (X);
end if;
Look_Ahead_Immediate (File, C, Available, Wait);
if Available then
declare
End_Of_Line : Boolean;
begin
if Character'Pos (C) < 16#80# then
-- Get_Immediate returns CR, LF, and FF.
Item := Wide_Character'Val (Character'Pos (C));
else
-- Waiting is OK for trailing bytes.
Look_Ahead (File, Item, End_Of_Line); -- Wide
end if;
end;
Skip_Ahead_Immediate (File);
else
Item := Wide_Character'Val (0);
end if;
end Get_Immediate;
procedure Get_Immediate (
File : Non_Controlled_File_Type;
Item : out Wide_Wide_Character;
Available : out Boolean;
Wait : Boolean)
is
package Holder is
new Exceptions.Finally.Scoped_Holder (Restore_Type, Finally);
X : aliased Restore_Type;
C : Character;
begin
if File.External = IO_Modes.Terminal then
X.Handle := Streams.Naked_Stream_IO.Handle (File.File);
System.Native_Text_IO.Set_Non_Canonical_Mode (
X.Handle,
Wait, -- only POSIX
X.Old_Settings);
Holder.Assign (X);
end if;
Look_Ahead_Immediate (File, C, Available, Wait);
if Available then
declare
End_Of_Line : Boolean;
begin
if Character'Pos (C) < 16#80# then
-- Get_Immediate returns CR, LF, and FF.
Item := Wide_Wide_Character'Val (Character'Pos (C));
else
-- Waiting is OK for trailing bytes.
Look_Ahead (File, Item, End_Of_Line); -- Wide_Wide
end if;
end;
Skip_Ahead_Immediate (File);
else
Item := Wide_Wide_Character'Val (0);
end if;
end Get_Immediate;
-- Output
-- * Write_Buffer sets Ahead_Col to written width.
-- * Put adds Ahead_Col to current Col.
procedure Write (
File : not null Non_Controlled_File_Type;
Item : Streams.Stream_Element_Array);
procedure Write (
File : not null Non_Controlled_File_Type;
Item : Streams.Stream_Element_Array) is
begin
if not Streams.Naked_Stream_IO.Is_Open (File.File) then
-- external stream mode
Streams.Write (To_Pointer (File.Stream).all, Item);
else
Streams.Naked_Stream_IO.Write (File.File, Item);
end if;
end Write;
procedure Raw_New_Page (File : Non_Controlled_File_Type);
procedure Raw_New_Line (File : Non_Controlled_File_Type);
procedure Raw_New_Line (
File : Non_Controlled_File_Type;
Spacing : Positive);
procedure Write_Buffer (
File : Non_Controlled_File_Type;
Sequence_Length : Natural);
procedure Raw_New_Page (File : Non_Controlled_File_Type) is
begin
if File.External = IO_Modes.Terminal then
System.Native_Text_IO.Terminal_Clear (
Streams.Naked_Stream_IO.Handle (File.File));
else
declare
Code : constant Streams.Stream_Element_Array := (1 => 16#0c#);
begin
Write (File, Code);
end;
end if;
File.Line := 1;
File.Page := File.Page + 1;
File.Col := 1;
end Raw_New_Page;
procedure Raw_New_Line (File : Non_Controlled_File_Type) is
begin
if File.Page_Length /= 0 and then File.Line >= File.Page_Length then
Raw_New_Page (File);
else
declare
Line_Mark : constant Streams.Stream_Element_Array (0 .. 1) :=
(16#0d#, 16#0a#);
First, Last : Streams.Stream_Element_Offset;
begin
First := Boolean'Pos (File.New_Line = IO_Modes.LF);
Last := Boolean'Pos (File.New_Line /= IO_Modes.CR);
Write (File, Line_Mark (First .. Last));
end;
File.Line := File.Line + 1;
File.Col := 1;
end if;
end Raw_New_Line;
procedure Raw_New_Line (
File : Non_Controlled_File_Type;
Spacing : Positive) is
begin
for I in 1 .. Spacing loop
Raw_New_Line (File);
end loop;
end Raw_New_Line;
procedure Write_Buffer (
File : Non_Controlled_File_Type;
Sequence_Length : Natural)
is
Length : constant Natural := File.Last; -- >= Sequence_Length
begin
if File.External = IO_Modes.Terminal then
declare
Written_Length : Streams.Stream_Element_Offset;
begin
System.Native_Text_IO.Terminal_Put (
Streams.Naked_Stream_IO.Handle (File.File),
File.Buffer'Address,
Streams.Stream_Element_Offset (Sequence_Length),
Written_Length);
if Written_Length < 0 then
Raise_Exception (Device_Error'Identity);
end if;
end;
File.Ahead_Col := Sequence_Length; -- for fallback
elsif File.External = IO_Modes.Locale
and then File.Buffer (1) >= Character'Val (16#80#)
then
declare
Locale_Support : constant Boolean :=
System.Native_Text_IO.Default_External = IO_Modes.Locale;
begin
if not Locale_Support then
unreachable;
end if;
end;
declare
DBCS_Buffer : aliased System.Native_Text_IO.DBCS_Buffer_Type;
DBCS_Last : Natural;
begin
System.Native_Text_IO.To_DBCS (
File.Buffer,
Sequence_Length,
DBCS_Buffer,
DBCS_Last);
if DBCS_Last = 0 then
DBCS_Buffer (1) := '?';
DBCS_Last := 1;
end if;
if File.Line_Length /= 0
and then File.Col + Natural (DBCS_Last - 1) > File.Line_Length
then
Raw_New_Line (File);
end if;
declare
DBCS_Buffer_As_SEA : Streams.Stream_Element_Array (
1 ..
Streams.Stream_Element_Offset (DBCS_Last));
for DBCS_Buffer_As_SEA'Address use DBCS_Buffer'Address;
begin
Write (File, DBCS_Buffer_As_SEA);
end;
File.Ahead_Col := DBCS_Last;
end;
else
if File.Line_Length /= 0
and then File.Col + Sequence_Length - 1 > File.Line_Length
then
Raw_New_Line (File);
end if;
declare
Buffer : Streams.Stream_Element_Array (
1 ..
Streams.Stream_Element_Offset (Sequence_Length));
for Buffer'Address use File.Buffer'Address;
begin
Write (File, Buffer);
end;
File.Ahead_Col := Sequence_Length;
end if;
File.Last := Length - Sequence_Length;
File.Buffer (1 .. File.Last) :=
File.Buffer (Sequence_Length + 1 .. Length);
end Write_Buffer;
-- implementation of non-controlled
procedure Create (
File : in out Non_Controlled_File_Type;
Mode : IO_Modes.File_Mode := IO_Modes.Out_File;
Name : String := "";
Form : System.Native_Text_IO.Packed_Form := Default_Form)
is
pragma Check (Pre,
Check => not Is_Open (File) or else raise Status_Error);
begin
Open_File (
Open_Proc => Streams.Naked_Stream_IO.Create'Access,
File => File,
Mode => Mode,
Name => Name,
Form => Form);
end Create;
procedure Open (
File : in out Non_Controlled_File_Type;
Mode : IO_Modes.File_Mode;
Name : String;
Form : System.Native_Text_IO.Packed_Form := Default_Form)
is
pragma Check (Pre,
Check => not Is_Open (File) or else raise Status_Error);
begin
Open_File (
Open_Proc => Streams.Naked_Stream_IO.Open'Access,
File => File,
Mode => Mode,
Name => Name,
Form => Form);
end Open;
procedure Close (
File : aliased in out Non_Controlled_File_Type;
Raise_On_Error : Boolean := True)
is
pragma Check (Pre,
Check => Is_Open (File) or else raise Status_Error);
Internal : aliased Streams.Naked_Stream_IO.Non_Controlled_File_Type :=
File.File;
begin
if not Streams.Naked_Stream_IO.Is_Open (Internal)
or else not Streams.Naked_Stream_IO.Is_Standard (Internal)
then
Free (File);
end if;
if Streams.Naked_Stream_IO.Is_Open (Internal) then
Streams.Naked_Stream_IO.Close (
Internal,
Raise_On_Error => Raise_On_Error);
end if;
end Close;
procedure Delete (File : aliased in out Non_Controlled_File_Type) is
pragma Check (Pre,
Check =>
(Is_Open (File)
and then Streams.Naked_Stream_IO.Is_Open (File.File)
and then not Streams.Naked_Stream_IO.Is_Standard (File.File))
or else raise Status_Error);
Internal : aliased Streams.Naked_Stream_IO.Non_Controlled_File_Type :=
File.File;
begin
Free (File);
Streams.Naked_Stream_IO.Delete (Internal);
end Delete;
procedure Reset (
File : aliased in out Non_Controlled_File_Type;
Mode : IO_Modes.File_Mode)
is
pragma Check (Pre,
Check => Is_Open (File) or else raise Status_Error);
pragma Check (Pre,
Check =>
not Streams.Naked_Stream_IO.Is_Standard (File.File)
or else Naked_Text_IO.Mode (File) = Mode
or else raise Mode_Error);
pragma Check (Pre,
Check =>
Streams.Naked_Stream_IO.Is_Open (File.File)
or else raise Status_Error); -- external stream mode
Current_Mode : constant IO_Modes.File_Mode := Naked_Text_IO.Mode (File);
begin
if Current_Mode /= IO_Modes.In_File then
Flush (File);
end if;
declare
package Holder is
new Exceptions.Finally.Scoped_Holder (
Non_Controlled_File_Type,
Free);
begin
Holder.Assign (File);
Streams.Naked_Stream_IO.Reset (File.File, Mode);
Holder.Clear;
end;
File.Stream := System.Null_Address;
File.Line := 1;
File.Page := 1;
File.Col := 1;
File.Line_Length := 0;
File.Page_Length := 0;
File.Last := 0;
File.Ahead_Last := 0;
File.Ahead_Col := 0;
File.Looked_Ahead_Last := 0;
File.End_Of_File := False;
File.Virtual_Mark := None;
File.Mode := Mode;
end Reset;
function Mode (File : Non_Controlled_File_Type) return IO_Modes.File_Mode is
begin
if Streams.Naked_Stream_IO.Is_Open (File.File) then
return Streams.Naked_Stream_IO.Mode (File.File);
else
return File.Mode;
end if;
end Mode;
function Name (File : Non_Controlled_File_Type) return String is
begin
if Streams.Naked_Stream_IO.Is_Open (File.File) then
return Streams.Naked_Stream_IO.Name (File.File);
else
return System.Native_IO.Value (File.Name);
end if;
end Name;
function Form (File : Non_Controlled_File_Type)
return System.Native_Text_IO.Packed_Form
is
Stream_Form : System.Native_IO.Packed_Form;
External : IO_Modes.File_External_Spec;
begin
if Streams.Naked_Stream_IO.Is_Open (File.File) then
Stream_Form := Streams.Naked_Stream_IO.Form (File.File);
else
Stream_Form := Streams.Naked_Stream_IO.Default_Form;
end if;
if File.External = IO_Modes.Terminal then
External := IO_Modes.File_External_Spec (
System.Native_Text_IO.Default_External);
else
External := IO_Modes.File_External_Spec (File.External);
end if;
return (
Stream_Form,
External,
IO_Modes.File_New_Line_Spec (File.New_Line));
end Form;
function External (File : Non_Controlled_File_Type)
return IO_Modes.File_External is
begin
return File.External;
end External;
function Is_Open (File : Non_Controlled_File_Type) return Boolean is
begin
return File /= null;
end Is_Open;
procedure Flush (File : Non_Controlled_File_Type) is
begin
if File.Last > 0 then
Write_Buffer (File, File.Last);
File.Col := File.Col + File.Ahead_Col;
end if;
if Streams.Naked_Stream_IO.Is_Open (File.File) then
Streams.Naked_Stream_IO.Flush_Writing_Buffer (File.File);
end if;
end Flush;
procedure Set_Size (
File : Non_Controlled_File_Type;
Line_Length, Page_Length : Natural) is
begin
if File.External = IO_Modes.Terminal then
if Line_Length = 0 or else Page_Length = 0 then
Raise_Exception (Device_Error'Identity);
end if;
System.Native_Text_IO.Set_Terminal_Size (
Streams.Naked_Stream_IO.Handle (File.File),
Line_Length,
Page_Length);
else
File.Line_Length := Line_Length;
File.Page_Length := Page_Length;
end if;
end Set_Size;
procedure Set_Line_Length (File : Non_Controlled_File_Type; To : Natural) is
Current_Line_Length, Current_Page_Length : Natural;
begin
Size (File, Current_Line_Length, Current_Page_Length);
if File.External /= IO_Modes.Terminal or else To > 0 then
Set_Size (File, To, Current_Page_Length);
end if;
end Set_Line_Length;
procedure Set_Page_Length (File : Non_Controlled_File_Type; To : Natural) is
Current_Line_Length, Current_Page_Length : Natural;
begin
Size (File, Current_Line_Length, Current_Page_Length);
if File.External /= IO_Modes.Terminal or else To > 0 then
Set_Size (File, Current_Line_Length, To);
end if;
end Set_Page_Length;
procedure Size (
File : Non_Controlled_File_Type;
Line_Length, Page_Length : out Natural) is
begin
if File.External = IO_Modes.Terminal then
System.Native_Text_IO.Terminal_Size (
Streams.Naked_Stream_IO.Handle (File.File),
Line_Length,
Page_Length);
else
Line_Length := File.Line_Length;
Page_Length := File.Page_Length;
end if;
end Size;
function Line_Length (File : Non_Controlled_File_Type) return Natural is
Line_Length, Page_Length : Natural;
begin
Size (File, Line_Length, Page_Length);
return Line_Length;
end Line_Length;
function Page_Length (File : Non_Controlled_File_Type) return Natural is
Line_Length, Page_Length : Natural;
begin
Size (File, Line_Length, Page_Length);
return Page_Length;
end Page_Length;
procedure New_Line (
File : Non_Controlled_File_Type;
Spacing : Positive := 1) is
begin
if File.Last > 0 then
Write_Buffer (File, File.Last);
end if;
Raw_New_Line (File, Spacing);
end New_Line;
procedure Skip_Line (
File : Non_Controlled_File_Type;
Spacing : Positive := 1) is
begin
for I in 1 .. Spacing loop
loop
declare
C : Character;
End_Of_Line : Boolean;
begin
Look_Ahead (File, C, End_Of_Line);
Skip_Ahead (File);
exit when End_Of_Line;
end;
end loop;
end loop;
end Skip_Line;
function End_Of_Line (File : Non_Controlled_File_Type) return Boolean is
C : Character;
Result : Boolean;
begin
Look_Ahead (File, C, Result);
return Result;
end End_Of_Line;
procedure New_Page (File : Non_Controlled_File_Type) is
begin
if File.Last > 0 then
Write_Buffer (File, File.Last);
end if;
Raw_New_Page (File);
end New_Page;
procedure Skip_Page (File : Non_Controlled_File_Type) is
begin
while not End_Of_Page (File) loop
Skip_Line (File);
end loop;
case File.Virtual_Mark is
when EOF =>
Raise_Exception (End_Error'Identity);
when EOP =>
File.Virtual_Mark := None;
when EOP_EOF =>
File.Virtual_Mark := EOF;
when others =>
if End_Of_File (File) then
File.Virtual_Mark := EOF;
else
Take_Buffer (File);
end if;
File.Line := 1;
File.Page := File.Page + 1;
File.Col := 1;
end case;
end Skip_Page;
function End_Of_Page (File : Non_Controlled_File_Type) return Boolean is
begin
case File.Virtual_Mark is
when EOP | EOP_EOF =>
return True;
when others =>
return End_Of_File (File) -- End_Of_File calls Read_Buffer
or else (
File.Last > 0
and then File.Buffer (1) = Character'Val (16#0c#));
-- page mark is ASCII
end case;
end End_Of_Page;
function End_Of_File (File : Non_Controlled_File_Type) return Boolean is
begin
loop
Read_Buffer (File);
if File.Last > 0 then
return False;
elsif File.End_Of_File then
return True;
end if;
end loop;
end End_Of_File;
procedure Set_Col (File : Non_Controlled_File_Type; To : Positive) is
begin
if File.External = IO_Modes.Terminal
and then System.Native_Text_IO.Use_Terminal_Position (
Streams.Naked_Stream_IO.Handle (File.File))
then
System.Native_Text_IO.Set_Terminal_Col (
Streams.Naked_Stream_IO.Handle (File.File),
To);
else
if Mode (File) = IO_Modes.In_File then
-- In_File
loop
declare
C : Character;
End_Of_Line : Boolean;
begin
Look_Ahead (File, C, End_Of_Line);
exit when not End_Of_Line and then File.Col = To;
Skip_Ahead (File); -- raise End_Error when End_Of_File
end;
end loop;
else
-- Out_File (or Append_File)
if File.Line_Length /= 0 and then To > File.Line_Length then
Raise_Exception (Layout_Error'Identity);
end if;
if File.Col > To then
Raw_New_Line (File);
end if;
while File.Col < To loop
Put (File, Character'Val (16#20#));
end loop;
end if;
end if;
end Set_Col;
procedure Set_Line (File : Non_Controlled_File_Type; To : Positive) is
begin
if File.External = IO_Modes.Terminal
and then System.Native_Text_IO.Use_Terminal_Position (
Streams.Naked_Stream_IO.Handle (File.File))
then
System.Native_Text_IO.Set_Terminal_Position (
Streams.Naked_Stream_IO.Handle (File.File),
Col => 1,
Line => To);
else
if Mode (File) = IO_Modes.In_File then
-- In_File
while To /= File.Line or else End_Of_Page (File) loop
Skip_Line (File);
end loop;
else
-- Out_File (or Append_File)
if File.Page_Length /= 0 and then To > File.Page_Length then
Raise_Exception (Layout_Error'Identity);
end if;
if File.Line > To then
Raw_New_Page (File);
end if;
if File.Line < To then
Raw_New_Line (File, To - File.Line);
end if;
end if;
end if;
end Set_Line;
procedure Position (
File : Non_Controlled_File_Type;
Col, Line : out Positive) is
begin
if File.External = IO_Modes.Terminal
and then System.Native_Text_IO.Use_Terminal_Position (
Streams.Naked_Stream_IO.Handle (File.File))
then
System.Native_Text_IO.Terminal_Position (
Streams.Naked_Stream_IO.Handle (File.File),
Col,
Line);
else
Col := File.Col;
Line := File.Line;
end if;
end Position;
function Col (File : Non_Controlled_File_Type) return Positive is
Col, Line : Positive;
begin
Position (File, Col, Line);
return Col;
end Col;
function Line (File : Non_Controlled_File_Type) return Positive is
Col, Line : Positive;
begin
Position (File, Col, Line);
return Line;
end Line;
function Page (File : Non_Controlled_File_Type) return Positive is
begin
return File.Page;
end Page;
procedure Get (
File : Non_Controlled_File_Type;
Item : out Character) is
begin
loop
declare
End_Of_Line : Boolean;
begin
Look_Ahead (File, Item, End_Of_Line);
Skip_Ahead (File);
exit when not End_Of_Line;
end;
end loop;
end Get;
procedure Get (
File : Non_Controlled_File_Type;
Item : out Wide_Character) is
begin
loop
declare
End_Of_Line : Boolean;
begin
Look_Ahead (File, Item, End_Of_Line);
Skip_Ahead (File);
exit when not End_Of_Line;
end;
end loop;
end Get;
procedure Get (
File : Non_Controlled_File_Type;
Item : out Wide_Wide_Character) is
begin
loop
declare
End_Of_Line : Boolean;
begin
Look_Ahead (File, Item, End_Of_Line);
Skip_Ahead (File);
exit when not End_Of_Line;
end;
end loop;
end Get;
procedure Put (
File : Non_Controlled_File_Type;
Item : Character)
is
Sequence_Length : Natural;
Sequence_Status : System.UTF_Conversions.Sequence_Status_Type; -- ignore
begin
-- if Item is not trailing byte, flush the buffer
if (File.Line_Length /= 0 or else File.External /= IO_Modes.UTF_8)
and then File.Last > 0
and then Character'Pos (Item) not in 2#10000000# .. 2#10111111#
then
Write_Buffer (File, File.Last);
File.Col := File.Col + File.Ahead_Col;
end if;
-- write to the buffer
File.Last := File.Last + 1;
File.Buffer (File.Last) := Item;
if File.Line_Length /= 0 or else File.External /= IO_Modes.UTF_8 then
System.UTF_Conversions.UTF_8_Sequence (
File.Buffer (1),
Sequence_Length,
Sequence_Status);
if File.Last >= Sequence_Length then
Write_Buffer (File, Sequence_Length);
File.Col := File.Col + File.Ahead_Col;
end if;
else
Write_Buffer (File, File.Last);
File.Col := File.Col + File.Ahead_Col;
end if;
end Put;
procedure Put (
File : Non_Controlled_File_Type;
Item : Wide_Character)
is
From_Status : System.UTF_Conversions.From_Status_Type; -- ignore
begin
if File.Last > 0 then
if Item in
Wide_Character'Val (16#dc00#) .. Wide_Character'Val (16#dfff#)
then
declare
First : System.UTF_Conversions.UCS_4;
Code : System.UTF_Conversions.UCS_4;
Last : Natural;
Length : Natural;
Wide_Buffer : Wide_String (1 .. 2);
Wide_Last : Natural;
begin
-- restore first of surrogate pair
System.UTF_Conversions.From_UTF_8 (
File.Buffer (1 .. File.Last),
Last,
First,
From_Status);
System.UTF_Conversions.UTF_16_Sequence (
Wide_Character'Val (First),
Length,
From_Status);
if Length /= 2
or else First >= 16#ffff#
or else Last /= File.Last
then
-- previous data is wrong
Raise_Exception (Data_Error'Identity);
end if;
Wide_Buffer (1) := Wide_Character'Val (First);
Wide_Buffer (2) := Item;
System.UTF_Conversions.From_UTF_16 (
Wide_Buffer,
Wide_Last,
Code,
From_Status);
File.Last := 0;
Put (File, Wide_Wide_Character'Val (Code));
return;
end;
else
Write_Buffer (File, File.Last);
File.Col := File.Col + File.Ahead_Col;
end if;
end if;
declare
Length : Natural;
To_Status : System.UTF_Conversions.To_Status_Type; -- ignore
begin
System.UTF_Conversions.UTF_16_Sequence (Item, Length, From_Status);
if Length = 2 then
-- store first of surrogate pair
System.UTF_Conversions.To_UTF_8 (
Wide_Character'Pos (Item),
File.Buffer,
File.Last,
To_Status);
else
-- single character
Put (File, Wide_Wide_Character'Val (Wide_Character'Pos (Item)));
end if;
end;
end Put;
procedure Put (
File : Non_Controlled_File_Type;
Item : Wide_Wide_Character) is
begin
if File.Last > 0 then
-- previous data is rested
Write_Buffer (File, File.Last);
File.Col := File.Col + File.Ahead_Col;
end if;
declare
Buffer : String (1 .. System.UTF_Conversions.UTF_8_Max_Length);
Last : Natural;
To_Status : System.UTF_Conversions.To_Status_Type; -- ignore
begin
System.UTF_Conversions.To_UTF_8 (
Wide_Wide_Character'Pos (Item),
Buffer,
Last,
To_Status);
for I in 1 .. Last loop
Put (File, Buffer (I));
end loop;
end;
end Put;
procedure Look_Ahead (
File : Non_Controlled_File_Type;
Item : out Character;
End_Of_Line : out Boolean) is
begin
loop
Read_Buffer (File);
if File.Ahead_Last > 0 then
declare
C : constant Character := File.Buffer (1);
begin
case C is
when Character'Val (16#0d#) | Character'Val (16#0a#)
| Character'Val (16#0c#) =>
File.Looked_Ahead_Last := 1; -- implies CR-LF sequence
File.Looked_Ahead_Second (1) := Character'Val (0);
End_Of_Line := True;
Item := Character'Val (0);
exit;
when others =>
File.Looked_Ahead_Last := 1;
File.Looked_Ahead_Second (1) := Character'Val (0);
End_Of_Line := False;
Item := C;
exit;
end case;
end;
elsif File.End_Of_File then
File.Looked_Ahead_Last := 1; -- Look_Ahead is called
File.Looked_Ahead_Second (1) := Character'Val (0);
End_Of_Line := True;
Item := Character'Val (0);
exit;
end if;
end loop;
end Look_Ahead;
procedure Look_Ahead (
File : Non_Controlled_File_Type;
Item : out Wide_Character;
End_Of_Line : out Boolean)
is
C : Wide_Wide_Character;
begin
Look_Ahead (File, C, End_Of_Line); -- Wide_Wide
if End_Of_Line then
Item := Wide_Character'Val (0);
else
declare
Wide_Buffer : Wide_String (1 .. 2);
Wide_Last : Natural;
To_Status : System.UTF_Conversions.To_Status_Type; -- ignore
begin
System.UTF_Conversions.To_UTF_16 (
Wide_Wide_Character'Pos (C),
Wide_Buffer,
Wide_Last,
To_Status);
if Wide_Last > 1 then
declare
Last : Natural;
begin
System.UTF_Conversions.To_UTF_8 (
Wide_Character'Pos (Wide_Buffer (2)),
File.Looked_Ahead_Second,
Last,
To_Status);
end;
end if;
Item := Wide_Buffer (1);
end;
end if;
end Look_Ahead;
procedure Look_Ahead (
File : Non_Controlled_File_Type;
Item : out Wide_Wide_Character;
End_Of_Line : out Boolean)
is
C : Character;
begin
Look_Ahead (File, C, End_Of_Line);
-- File.Buffer is already converted even through File.External = Locale
if End_Of_Line then
Item := Wide_Wide_Character'Val (0);
else
if File.External = IO_Modes.Locale then
declare
Locale_Support : constant Boolean :=
System.Native_Text_IO.Default_External = IO_Modes.Locale;
begin
if not Locale_Support then
unreachable;
end if;
end;
File.Looked_Ahead_Last := File.Ahead_Last; -- shortcut
else
declare
Sequence_Length : Natural;
Buffer_Last : Natural;
From_Status : System.UTF_Conversions.From_Status_Type; -- ignore
begin
System.UTF_Conversions.UTF_8_Sequence (
C,
Sequence_Length,
From_Status);
Buffer_Last := 1;
while Buffer_Last < Sequence_Length loop
if File.Last < Sequence_Length then
Read_Buffer (File, Wanted => Sequence_Length);
end if;
if File.Last > Buffer_Last then
if File.Buffer (Buffer_Last + 1) in
Character'Val (2#10000000#) ..
Character'Val (2#10111111#)
then
Buffer_Last := Buffer_Last + 1;
else
exit;
end if;
elsif File.End_Of_File then
exit;
end if;
end loop;
File.Ahead_Last := Buffer_Last;
if File.Ahead_Col > 0 -- skip second element of UTF-16
and then File.External = IO_Modes.UTF_8
then
File.Ahead_Col := Buffer_Last;
end if;
File.Looked_Ahead_Last := Buffer_Last;
end;
end if;
declare
Conv_Last : Natural;
Code : System.UTF_Conversions.UCS_4;
From_Status : System.UTF_Conversions.From_Status_Type; -- ignore
begin
System.UTF_Conversions.From_UTF_8 (
File.Buffer (1 .. File.Looked_Ahead_Last),
Conv_Last,
Code,
From_Status);
Item := Wide_Wide_Character'Val (Code);
end;
end if;
end Look_Ahead;
procedure Skip_Ahead (File : Non_Controlled_File_Type) is
pragma Check (Pre,
Check =>
File.Looked_Ahead_Last /= 0
or else raise Status_Error); -- Look_Ahead should be called before
begin
if File.Ahead_Last = 0 then -- File.End_Of_File = True
-- Skip_Ahead can be used instead of Skip_Line
if File.Virtual_Mark <= EOP then
File.Virtual_Mark := EOP_EOF;
File.Line := 1;
File.Page := File.Page + 1;
File.Col := 1;
else
Raise_Exception (End_Error'Identity);
end if;
else
declare
C : constant Character := File.Buffer (1);
begin
case C is
when Character'Val (16#0d#) | Character'Val (16#0a#) =>
Take_Line (File);
when Character'Val (16#0c#) =>
Take_Page (File);
when others =>
Take_Sequence (File);
end case;
end;
end if;
end Skip_Ahead;
procedure Get_Immediate (
File : Non_Controlled_File_Type;
Item : out Character)
is
Available : Boolean;
begin
Get_Immediate (File, Item, Available, Wait => True);
end Get_Immediate;
procedure Get_Immediate (
File : Non_Controlled_File_Type;
Item : out Wide_Character)
is
Available : Boolean;
begin
Get_Immediate (File, Item, Available, Wait => True);
end Get_Immediate;
procedure Get_Immediate (
File : Non_Controlled_File_Type;
Item : out Wide_Wide_Character)
is
Available : Boolean;
begin
Get_Immediate (File, Item, Available, Wait => True);
end Get_Immediate;
procedure Get_Immediate (
File : Non_Controlled_File_Type;
Item : out Character;
Available : out Boolean) is
begin
Get_Immediate (File, Item, Available, Wait => False);
end Get_Immediate;
procedure Get_Immediate (
File : Non_Controlled_File_Type;
Item : out Wide_Character;
Available : out Boolean) is
begin
Get_Immediate (File, Item, Available, Wait => False);
end Get_Immediate;
procedure Get_Immediate (
File : Non_Controlled_File_Type;
Item : out Wide_Wide_Character;
Available : out Boolean) is
begin
Get_Immediate (File, Item, Available, Wait => False);
end Get_Immediate;
-- implementation of handle of stream for non-controlled
procedure Open (
File : in out Non_Controlled_File_Type;
Mode : IO_Modes.File_Mode;
Stream : not null access Streams.Root_Stream_Type'Class;
Name : String := "";
Form : System.Native_Text_IO.Packed_Form := Default_Form)
is
pragma Check (Pre,
Check => not Is_Open (File) or else raise Status_Error);
function To_Address (Value : access Streams.Root_Stream_Type'Class)
return System.Address
with Import, Convention => Intrinsic;
package Name_Holder is
new Exceptions.Finally.Scoped_Holder (
System.Native_IO.Name_Pointer,
System.Native_IO.Free);
Full_Name : aliased System.Native_IO.Name_Pointer;
begin
Name_Holder.Assign (Full_Name);
System.Native_IO.New_External_Name (Name, Full_Name); -- '*' & Name & NUL
File := new Text_Type'(
Stream => To_Address (Stream),
Name => Full_Name,
Mode => Mode,
External => Select_External (Form.External),
New_Line => Select_New_Line (Form.New_Line),
others => <>);
-- complete
Name_Holder.Clear;
end Open;
function Stream (File : not null Non_Controlled_File_Type)
return not null access Streams.Root_Stream_Type'Class
is
function To_Address (Value : access Streams.Root_Stream_Type'Class)
return System.Address
with Import, Convention => Intrinsic;
begin
if To_Pointer (File.Stream) = null then
File.Stream :=
To_Address (Streams.Naked_Stream_IO.Stream (File.File));
end if;
return To_Pointer (File.Stream);
end Stream;
function Stream_IO (File : Non_Controlled_File_Type)
return not null
access Streams.Naked_Stream_IO.Non_Controlled_File_Type
is
pragma Check (Pre,
Check =>
Streams.Naked_Stream_IO.Is_Open (File.File)
or else raise Status_Error); -- external stream mode
begin
return File.File'Access;
end Stream_IO;
function Terminal_Handle (File : Non_Controlled_File_Type)
return System.Native_IO.Handle_Type
is
pragma Check (Pre,
Check =>
Streams.Naked_Stream_IO.Is_Open (File.File)
or else raise Status_Error); -- external stream mode
begin
if File.External /= IO_Modes.Terminal then
Raise_Exception (Device_Error'Identity);
end if;
return Streams.Naked_Stream_IO.Handle (File.File);
end Terminal_Handle;
-- initialization
procedure Init_Standard_File (File : not null Non_Controlled_File_Type);
procedure Init_Standard_File (File : not null Non_Controlled_File_Type) is
begin
if System.Native_IO.Is_Terminal (
Streams.Naked_Stream_IO.Handle (File.File))
then
File.External := IO_Modes.Terminal;
end if;
end Init_Standard_File;
begin
Init_Standard_File (Standard_Input_Text'Access);
Init_Standard_File (Standard_Output_Text'Access);
Init_Standard_File (Standard_Error_Text'Access);
end Ada.Naked_Text_IO;
|
pragma License (Unrestricted);
with Ada.Containers;
generic
with package Bounded is new Generic_Bounded_Length (<>);
function Ada.Strings.Bounded.Hash (Key : Bounded.Bounded_String)
return Containers.Hash_Type;
pragma Preelaborate (Ada.Strings.Bounded.Hash);
|
--------------------------------------------------------------------------------
-- Copyright (c) 2013, Felix Krause <contact@flyx.org>
--
-- Permission to use, copy, modify, and/or distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
--------------------------------------------------------------------------------
with Ada.Strings.Fixed;
with Ada.Strings;
package body CL is
use Ada.Strings;
use Ada.Strings.Fixed;
function "=" (Left, Right : CL_Object) return Boolean is
use type System.Address;
begin
return Left.Location = Right.Location;
end "=";
function Initialized (Object : Runtime_Object) return Boolean is
use type System.Address;
begin
return Object.Location /= System.Null_Address;
end Initialized;
function Raw (Source : Runtime_Object) return System.Address is
begin
return Source.Location;
end Raw;
function To_String (Value : Char) return String is
begin
return Trim (Value'Img, Both);
end To_String;
function To_String (Value : Short) return String is
begin
return Trim (Value'Img, Both);
end To_String;
function To_String (Value : Int) return String is
begin
return Trim (Value'Img, Both);
end To_String;
function To_String (Value : Long) return String is
begin
return Trim (Value'Img, Both);
end To_String;
function To_String (Value : UChar) return String is
begin
return Trim (Value'Img, Both);
end To_String;
function To_String (Value : UShort) return String is
begin
return Trim (Value'Img, Both);
end To_String;
function To_String (Value : UInt) return String is
begin
return Trim (Value'Img, Both);
end To_String;
function To_String (Value : ULong) return String is
begin
return Trim (Value'Img, Both);
end To_String;
function To_String (Value : CL.Float) return String is
begin
return Trim (Value'Img, Both);
end To_String;
function Float_Equals (Left, Right : Float) return Boolean is
begin
return abs (Left - Right) <= Epsilon;
end Float_Equals;
end CL;
|
------------------------------------------------------------------------------
-- A d a r u n - t i m e s p e c i f i c a t i o n --
-- ASIS implementation for Gela project, a portable Ada compiler --
-- http://gela.ada-ru.org --
-- - - - - - - - - - - - - - - - --
-- Read copyright and license at the end of ada.ads file --
------------------------------------------------------------------------------
-- $Revision: 209 $ $Date: 2013-11-30 21:03:24 +0200 (Сб., 30 нояб. 2013) $
package Ada.Strings.Wide_Wide_Maps is
pragma Preelaborate(Wide_Wide_Maps);
-- Representation for a set of Wide_Wide_Character values:
type Wide_Wide_Character_Set is private;
pragma Preelaborable_Initialization(Wide_Wide_Character_Set);
Null_Set : constant Wide_Wide_Character_Set;
type Wide_Wide_Character_Range is
record
Low : Wide_Wide_Character;
High : Wide_Wide_Character;
end record;
-- Represents Wide_Wide_Character range Low..High
type Wide_Wide_Character_Ranges is array (Positive range <>)
of Wide_Wide_Character_Range;
function To_Set (Ranges : in Wide_Wide_Character_Ranges)
return Wide_Wide_Character_Set;
function To_Set (Span : in Wide_Wide_Character_Range)
return Wide_Wide_Character_Set;
function To_Ranges (Set : in Wide_Wide_Character_Set)
return Wide_Wide_Character_Ranges;
function "=" (Left, Right : in Wide_Wide_Character_Set) return Boolean;
function "not" (Right : in Wide_Wide_Character_Set)
return Wide_Wide_Character_Set;
function "and" (Left, Right : in Wide_Wide_Character_Set)
return Wide_Wide_Character_Set;
function "or" (Left, Right : in Wide_Wide_Character_Set)
return Wide_Wide_Character_Set;
function "xor" (Left, Right : in Wide_Wide_Character_Set)
return Wide_Wide_Character_Set;
function "-" (Left, Right : in Wide_Wide_Character_Set)
return Wide_Wide_Character_Set;
function Is_In (Element : in Wide_Wide_Character;
Set : in Wide_Wide_Character_Set)
return Boolean;
function Is_Subset (Elements : in Wide_Wide_Character_Set;
Set : in Wide_Wide_Character_Set)
return Boolean;
function "<=" (Left : in Wide_Wide_Character_Set;
Right : in Wide_Wide_Character_Set)
return Boolean renames Is_Subset;
-- Alternative representation for a set of Wide_Wide_Character values:
subtype Wide_Wide_Character_Sequence is Wide_Wide_String;
function To_Set (Sequence : in Wide_Wide_Character_Sequence)
return Wide_Wide_Character_Set;
function To_Set (Singleton : in Wide_Wide_Character)
return Wide_Wide_Character_Set;
function To_Sequence (Set : in Wide_Wide_Character_Set)
return Wide_Wide_Character_Sequence;
-- Representation for a Wide_Wide_Character to Wide_Wide_Character
-- mapping:
type Wide_Wide_Character_Mapping is private;
pragma Preelaborable_Initialization(Wide_Wide_Character_Mapping);
function Value (Map : in Wide_Wide_Character_Mapping;
Element : in Wide_Wide_Character)
return Wide_Wide_Character;
Identity : constant Wide_Wide_Character_Mapping;
function To_Mapping (From, To : in Wide_Wide_Character_Sequence)
return Wide_Wide_Character_Mapping;
function To_Domain (Map : in Wide_Wide_Character_Mapping)
return Wide_Wide_Character_Sequence;
function To_Range (Map : in Wide_Wide_Character_Mapping)
return Wide_Wide_Character_Sequence;
type Wide_Wide_Character_Mapping_Function is
access function (From : in Wide_Wide_Character)
return Wide_Wide_Character;
private
pragma Import (Ada, Wide_Wide_Character_Set);
pragma Import (Ada, Null_Set);
pragma Import (Ada, Wide_Wide_Character_Mapping);
pragma Import (Ada, Identity);
end Ada.Strings.Wide_Wide_Maps;
|
-----------------------------------------------------------------------
-- Util.beans.factory -- Bean Registration and Factory
-- Copyright (C) 2010 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Methods;
private with Ada.Containers.Indefinite_Hashed_Maps;
private with Ada.Strings.Unbounded.Hash;
-- The <b>EL.Beans.Factory</b> package is a registry for the creation
-- of request, session and application beans.
package Util.Beans.Factory is
-- The bean definition is a small descriptor used by the
-- factory to create the bean instance when it is needed.
-- It also defines the methods that can be specified and
-- invoked as part of a <b>Method_Expression</b>.
type Bean_Definition (Method_Count : Natural) is abstract tagged limited record
Methods : Util.Beans.Methods.Method_Binding_Array (1 .. Method_Count);
end record;
type Bean_Definition_Access is access constant Bean_Definition'Class;
-- Create a bean.
function Create (Def : in Bean_Definition)
return Util.Beans.Basic.Readonly_Bean_Access is abstract;
-- Free the bean instance.
procedure Destroy (Def : in Bean_Definition;
Bean : in out Util.Beans.Basic.Readonly_Bean_Access) is abstract;
-- Defines the scope of the bean instance.
type Scope_Type is
(
-- Application scope means the bean is shared by all sessions and requests
APPLICATION_SCOPE,
-- Session scope means the bean is created one for each session.
SESSION_SCOPE,
-- Request scope means the bean is created for each request
REQUEST_SCOPE,
ANY_SCOPE);
-- ------------------------------
-- Binding
-- ------------------------------
type Binding is interface;
type Binding_Access is access all Binding'Class;
procedure Create (Factory : in Binding;
Name : in Ada.Strings.Unbounded.Unbounded_String;
Result : out Util.Beans.Basic.Readonly_Bean_Access;
Definition : out Bean_Definition_Access;
Scope : out Scope_Type) is abstract;
-- ------------------------------
-- Bean Factory
-- ------------------------------
-- Factory for bean creation
type Bean_Factory is limited private;
-- Register under the given name a function to create the bean instance when
-- it is accessed for a first time. The scope defines the scope of the bean.
-- bean
procedure Register (Factory : in out Bean_Factory;
Name : in String;
Definition : in Bean_Definition_Access;
Scope : in Scope_Type := REQUEST_SCOPE);
-- Register under the given name a function to create the bean instance when
-- it is accessed for a first time. The scope defines the scope of the bean.
-- bean
procedure Register (Factory : in out Bean_Factory;
Name : in String;
Bind : in Binding_Access);
-- Register all the definitions from a factory to a main factory.
procedure Register (Factory : in out Bean_Factory;
From : in Bean_Factory);
-- Create a bean by using the create operation registered for the name
procedure Create (Factory : in Bean_Factory;
Name : in Ada.Strings.Unbounded.Unbounded_String;
Result : out Util.Beans.Basic.Readonly_Bean_Access;
Definition : out Bean_Definition_Access;
Scope : out Scope_Type);
type Simple_Binding is new Binding with private;
procedure Create (Factory : in Simple_Binding;
Name : in Ada.Strings.Unbounded.Unbounded_String;
Result : out Util.Beans.Basic.Readonly_Bean_Access;
Definition : out Bean_Definition_Access;
Scope : out Scope_Type);
private
type Simple_Binding is new Binding with record
Def : Bean_Definition_Access;
Scope : Scope_Type;
end record;
type Simple_Binding_Access is access all Simple_Binding;
use Ada.Strings.Unbounded;
package Bean_Maps is new
Ada.Containers.Indefinite_Hashed_Maps (Key_Type => Unbounded_String,
Element_Type => Binding_Access,
Hash => Ada.Strings.Unbounded.Hash,
Equivalent_Keys => "=");
type Bean_Factory is limited record
Map : Bean_Maps.Map;
end record;
end Util.Beans.Factory;
|
package Random_57 is
type Mod_7 is mod 7;
function Random7 return Mod_7;
-- a "fast" implementation, minimazing the calls to the Random5 generator
function Simple_Random7 return Mod_7;
-- a simple implementation
end Random_57;
|
-- { dg-do compile }
-- { dg-options "-O2 -gnatp" }
function Scalar_Mode_Agg_Compare_Loop return Boolean is
S : constant String (1 .. 4) := "ABCD";
F : constant Natural := S'First;
L : constant Natural := S'Last;
begin
for J in F .. L - 1 loop
if S (F .. F) = "X" or (J <= L - 2 and S (J .. J + 1) = "YY") then
return True;
end if;
end loop;
return False;
end;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Localization, Internationalization, Globalization for Ada --
-- --
-- Tools Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2011-2015, Vadim Godunko <vgodunko@gmail.com> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with Ada.Command_Line;
with Ada.Wide_Wide_Text_IO;
with League.Application;
with League.Strings;
with UAFLEX.Run;
procedure UAFLEX.Driver is
procedure Read_Arguments;
procedure Print_Usage;
function "+"
(Item : Wide_Wide_String)
return League.Strings.Universal_String
renames League.Strings.To_Universal_String;
Handler : League.Strings.Universal_String;
Input : League.Strings.Universal_String;
Tokens : League.Strings.Universal_String;
Types : League.Strings.Universal_String;
Scanner : League.Strings.Universal_String;
-----------------
-- Print_Usage --
-----------------
procedure Print_Usage is
use Ada.Wide_Wide_Text_IO;
begin
Put_Line
(Standard_Error,
"Usage: uaflex <unit-options> input_file");
Put_Line
(Standard_Error,
" where <unit-options> contains:");
Put_Line
(Standard_Error,
" --types Types_Unit - unit for type and condition declarations");
Put_Line
(Standard_Error,
" --handler Handler_Unit - unit for abstract handler declaration");
Put_Line
(Standard_Error,
" --scanner Scanner_Unit - unit where scanner is located");
Put_Line
(Standard_Error,
" --tokens Tokens_Unit - unit where Token type is declared");
end Print_Usage;
--------------------
-- Read_Arguments --
--------------------
procedure Read_Arguments is
use League.Strings;
Is_Types : constant Universal_String := +"--types";
Is_Scanner : constant Universal_String := +"--scanner";
Is_Tokens : constant Universal_String := +"--tokens";
Is_Handler : constant Universal_String := +"--handler";
Last : constant Natural := League.Application.Arguments.Length;
Index : Positive := 1;
begin
while Index <= Last loop
declare
Next : constant League.Strings.Universal_String :=
League.Application.Arguments.Element (Index);
begin
if Index = Last then
Input := Next;
elsif Next = Is_Types then
Index := Index + 1;
Types := League.Application.Arguments.Element (Index);
elsif Next = Is_Scanner then
Index := Index + 1;
Scanner := League.Application.Arguments.Element (Index);
elsif Next = Is_Tokens then
Index := Index + 1;
Tokens := League.Application.Arguments.Element (Index);
elsif Next = Is_Handler then
Index := Index + 1;
Handler := League.Application.Arguments.Element (Index);
end if;
Index := Index + 1;
end;
end loop;
end Read_Arguments;
Success : Boolean;
begin
Read_Arguments;
if Handler.Is_Empty or
Input.Is_Empty or
Tokens.Is_Empty or
Types.Is_Empty or
Scanner.Is_Empty
then
Print_Usage;
return;
end if;
UAFLEX.Run
(Handler,
Input,
Tokens,
Types,
Scanner,
Success);
if not Success then
Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
end if;
end UAFLEX.Driver;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- G N A T . S O C K E T S . T H I N _ C O M M O N --
-- --
-- S p e c --
-- --
-- Copyright (C) 2008-2019, AdaCore --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This is the target-independent part of the thin sockets mapping.
-- This package should not be directly with'ed by an applications program.
with Ada.Unchecked_Conversion;
with Interfaces.C.Strings;
package GNAT.Sockets.Thin_Common is
package C renames Interfaces.C;
package CS renames C.Strings;
Success : constant C.int := 0;
Failure : constant C.int := -1;
type time_t is
range -2 ** (8 * SOSC.SIZEOF_tv_sec - 1)
.. 2 ** (8 * SOSC.SIZEOF_tv_sec - 1) - 1;
for time_t'Size use 8 * SOSC.SIZEOF_tv_sec;
pragma Convention (C, time_t);
type suseconds_t is
range -2 ** (8 * SOSC.SIZEOF_tv_usec - 1)
.. 2 ** (8 * SOSC.SIZEOF_tv_usec - 1) - 1;
for suseconds_t'Size use 8 * SOSC.SIZEOF_tv_usec;
pragma Convention (C, suseconds_t);
type Timeval is record
Tv_Sec : time_t;
Tv_Usec : suseconds_t;
end record;
pragma Convention (C, Timeval);
type Timeval_Access is access all Timeval;
pragma Convention (C, Timeval_Access);
type socklen_t is mod 2 ** (8 * SOSC.SIZEOF_socklen_t);
for socklen_t'Size use (8 * SOSC.SIZEOF_socklen_t);
Immediat : constant Timeval := (0, 0);
-------------------------------------------
-- Mapping tables to low level constants --
-------------------------------------------
Families : constant array (Family_Type) of C.int :=
(Family_Unspec => SOSC.AF_UNSPEC,
Family_Inet => SOSC.AF_INET,
Family_Inet6 => SOSC.AF_INET6);
Lengths : constant array (Family_Type) of C.unsigned_char :=
(Family_Unspec => 0,
Family_Inet => SOSC.SIZEOF_sockaddr_in,
Family_Inet6 => SOSC.SIZEOF_sockaddr_in6);
----------------------------
-- Generic socket address --
----------------------------
-- Common header
-- All socket address types (struct sockaddr, struct sockaddr_storage,
-- and protocol specific address types) start with the same 2-byte header,
-- which is either a length and a family (one byte each) or just a two-byte
-- family. The following unchecked union describes the two possible layouts
-- and is meant to be constrained with SOSC.Have_Sockaddr_Len.
type Sockaddr_Length_And_Family
(Has_Sockaddr_Len : Boolean := False)
is record
case Has_Sockaddr_Len is
when True =>
Length : C.unsigned_char;
Char_Family : C.unsigned_char;
when False =>
Short_Family : C.unsigned_short;
end case;
end record;
pragma Unchecked_Union (Sockaddr_Length_And_Family);
pragma Convention (C, Sockaddr_Length_And_Family);
procedure Set_Family
(Length_And_Family : out Sockaddr_Length_And_Family;
Family : Family_Type);
-- Set the family component to the appropriate value for Family, and also
-- set Length accordingly if applicable on this platform.
----------------------------
-- AF_INET socket address --
----------------------------
type In_Addr is record
S_B1, S_B2, S_B3, S_B4 : C.unsigned_char;
end record;
for In_Addr'Alignment use C.int'Alignment;
pragma Convention (C, In_Addr);
-- IPv4 address, represented as a network-order C.int. Note that the
-- underlying operating system may assume that values of this type have
-- C.int alignment, so we need to provide a suitable alignment clause here.
function To_In_Addr is new Ada.Unchecked_Conversion (C.int, In_Addr);
function To_Int is new Ada.Unchecked_Conversion (In_Addr, C.int);
function To_In_Addr (Addr : Inet_Addr_Type) return In_Addr;
procedure To_Inet_Addr
(Addr : In_Addr;
Result : out Inet_Addr_Type);
-- Conversion functions
type In6_Addr is array (1 .. 16) of C.unsigned_char;
for In6_Addr'Alignment use C.int'Alignment;
pragma Convention (C, In6_Addr);
function To_In6_Addr (Addr : Inet_Addr_Type) return In6_Addr;
procedure To_Inet_Addr
(Addr : In6_Addr;
Result : out Inet_Addr_Type);
-- Conversion functions
type Sockaddr (Family : Family_Type := Family_Inet) is record
Sin_Family : Sockaddr_Length_And_Family;
-- Address family (and address length on some platforms)
Sin_Port : C.unsigned_short;
-- Port in network byte order
case Family is
when Family_Inet =>
Sin_Addr : In_Addr := (others => 0);
-- IPv4 address
Sin_Zero : C.char_array (1 .. 8) := (others => C.nul);
-- Padding
--
-- Note that some platforms require that all unused (reserved) bytes
-- in addresses be initialized to 0 (e.g. VxWorks).
when Family_Inet6 =>
Sin6_FlowInfo : Interfaces.Unsigned_32 := 0;
Sin6_Addr : In6_Addr := (others => 0);
Sin6_Scope_Id : Interfaces.Unsigned_32 := 0;
when Family_Unspec =>
null;
end case;
end record;
pragma Unchecked_Union (Sockaddr);
pragma Convention (C, Sockaddr);
-- Internet socket address
type Sockaddr_Access is access all Sockaddr;
pragma Convention (C, Sockaddr_Access);
-- Access to internet socket address
procedure Set_Address
(Sin : Sockaddr_Access;
Address : Sock_Addr_Type);
-- Initialise all necessary fields in Sin from Address.
-- Set appropriate Family, Port, and either Sin.Sin_Addr or Sin.Sin6_Addr
-- depend on family.
function Get_Address (Sin : Sockaddr) return Sock_Addr_Type;
-- Get Sock_Addr_Type from Sockaddr
------------------
-- Host entries --
------------------
type Hostent is new
System.Storage_Elements.Storage_Array (1 .. SOSC.SIZEOF_struct_hostent);
for Hostent'Alignment use 8;
-- Host entry. This is an opaque type used only via the following
-- accessor functions, because 'struct hostent' has different layouts on
-- different platforms.
type Hostent_Access is access all Hostent;
pragma Convention (C, Hostent_Access);
-- Access to host entry
function Hostent_H_Name
(E : Hostent_Access) return System.Address;
function Hostent_H_Alias
(E : Hostent_Access; I : C.int) return System.Address;
function Hostent_H_Addrtype
(E : Hostent_Access) return C.int;
function Hostent_H_Length
(E : Hostent_Access) return C.int;
function Hostent_H_Addr
(E : Hostent_Access; Index : C.int) return System.Address;
---------------------
-- Service entries --
---------------------
type Servent is new
System.Storage_Elements.Storage_Array (1 .. SOSC.SIZEOF_struct_servent);
for Servent'Alignment use 8;
-- Service entry. This is an opaque type used only via the following
-- accessor functions, because 'struct servent' has different layouts on
-- different platforms.
type Servent_Access is access all Servent;
pragma Convention (C, Servent_Access);
-- Access to service entry
function Servent_S_Name
(E : Servent_Access) return System.Address;
function Servent_S_Alias
(E : Servent_Access; Index : C.int) return System.Address;
function Servent_S_Port
(E : Servent_Access) return C.unsigned_short;
function Servent_S_Proto
(E : Servent_Access) return System.Address;
------------------
-- NetDB access --
------------------
-- There are three possible situations for the following NetDB access
-- functions:
-- - inherently thread safe (case of data returned in a thread specific
-- buffer);
-- - thread safe using user-provided buffer;
-- - thread unsafe.
--
-- In the first and third cases, the Buf and Buflen are ignored. In the
-- second case, the caller must provide a buffer large enough to
-- accommodate the returned data. In the third case, the caller must ensure
-- that these functions are called within a critical section.
function C_Gethostbyname
(Name : C.char_array;
Ret : not null access Hostent;
Buf : System.Address;
Buflen : C.int;
H_Errnop : not null access C.int) return C.int;
function C_Gethostbyaddr
(Addr : System.Address;
Addr_Len : C.int;
Addr_Type : C.int;
Ret : not null access Hostent;
Buf : System.Address;
Buflen : C.int;
H_Errnop : not null access C.int) return C.int;
function C_Getservbyname
(Name : C.char_array;
Proto : C.char_array;
Ret : not null access Servent;
Buf : System.Address;
Buflen : C.int) return C.int;
function C_Getservbyport
(Port : C.int;
Proto : C.char_array;
Ret : not null access Servent;
Buf : System.Address;
Buflen : C.int) return C.int;
Address_Size : constant := Standard'Address_Size;
type Addrinfo;
type Addrinfo_Access is access all Addrinfo;
type Addrinfo is record
ai_flags : C.int;
ai_family : C.int;
ai_socktype : C.int;
ai_protocol : C.int;
ai_addrlen : socklen_t;
ai_addr : Sockaddr_Access;
ai_canonname : CS.char_array_access;
ai_next : Addrinfo_Access;
end record with Convention => C;
for Addrinfo use record
ai_flags at SOSC.AI_FLAGS_OFFSET range 0 .. C.int'Size - 1;
ai_family at SOSC.AI_FAMILY_OFFSET range 0 .. C.int'Size - 1;
ai_socktype at SOSC.AI_SOCKTYPE_OFFSET range 0 .. C.int'Size - 1;
ai_protocol at SOSC.AI_PROTOCOL_OFFSET range 0 .. C.int'Size - 1;
ai_addrlen at SOSC.AI_ADDRLEN_OFFSET range 0 .. socklen_t'Size - 1;
ai_canonname at SOSC.AI_CANONNAME_OFFSET range 0 .. Address_Size - 1;
ai_addr at SOSC.AI_ADDR_OFFSET range 0 .. Address_Size - 1;
ai_next at SOSC.AI_NEXT_OFFSET range 0 .. Address_Size - 1;
end record;
function C_Getaddrinfo
(Node : CS.char_array_access;
Service : CS.char_array_access;
Hints : access constant Addrinfo;
Res : not null access Addrinfo_Access) return C.int;
procedure C_Freeaddrinfo (res : Addrinfo_Access);
function C_Getnameinfo
(sa : Sockaddr_Access;
salen : socklen_t;
host : CS.char_array_access;
hostlen : C.size_t;
serv : CS.char_array_access;
servlen : C.size_t;
flags : C.int) return C.int;
function C_GAI_Strerror (ecode : C.int) return CS.chars_ptr;
------------------------------------
-- Scatter/gather vector handling --
------------------------------------
type Msghdr is record
Msg_Name : System.Address;
Msg_Namelen : C.unsigned;
Msg_Iov : System.Address;
Msg_Iovlen : SOSC.Msg_Iovlen_T;
Msg_Control : System.Address;
Msg_Controllen : C.size_t;
Msg_Flags : C.int;
end record;
pragma Convention (C, Msghdr);
----------------------------
-- Socket sets management --
----------------------------
procedure Get_Socket_From_Set
(Set : access Fd_Set;
Last : access C.int;
Socket : access C.int);
-- Get last socket in Socket and remove it from the socket set. The
-- parameter Last is a maximum value of the largest socket. This hint is
-- used to avoid scanning very large socket sets. After a call to
-- Get_Socket_From_Set, Last is set back to the real largest socket in the
-- socket set.
procedure Insert_Socket_In_Set
(Set : access Fd_Set;
Socket : C.int);
-- Insert socket in the socket set
function Is_Socket_In_Set
(Set : access constant Fd_Set;
Socket : C.int) return C.int;
-- Check whether Socket is in the socket set, return a non-zero
-- value if it is, zero if it is not.
procedure Last_Socket_In_Set
(Set : access Fd_Set;
Last : access C.int);
-- Find the largest socket in the socket set. This is needed for select().
-- When Last_Socket_In_Set is called, parameter Last is a maximum value of
-- the largest socket. This hint is used to avoid scanning very large
-- socket sets. After the call, Last is set back to the real largest socket
-- in the socket set.
procedure Remove_Socket_From_Set (Set : access Fd_Set; Socket : C.int);
-- Remove socket from the socket set
procedure Reset_Socket_Set (Set : access Fd_Set);
-- Make Set empty
------------------------------------------
-- Pairs of signalling file descriptors --
------------------------------------------
type Two_Ints is array (0 .. 1) of C.int;
pragma Convention (C, Two_Ints);
-- Container for two int values
subtype Fd_Pair is Two_Ints;
-- Two_Ints as used for Create_Signalling_Fds: a pair of connected file
-- descriptors, one of which (the "read end" of the connection) being used
-- for reading, the other one (the "write end") being used for writing.
Read_End : constant := 0;
Write_End : constant := 1;
-- Indexes into an Fd_Pair value providing access to each of the connected
-- file descriptors.
function Inet_Pton
(Af : C.int;
Cp : System.Address;
Inp : System.Address) return C.int;
function Inet_Ntop
(Af : C.int;
Src : System.Address;
Dst : CS.char_array_access;
Size : socklen_t) return CS.char_array_access;
function C_Ioctl
(Fd : C.int;
Req : SOSC.IOCTL_Req_T;
Arg : access C.int) return C.int;
function Short_To_Network
(S : C.unsigned_short) return C.unsigned_short;
pragma Inline (Short_To_Network);
-- Convert a port number into a network port number
function Network_To_Short
(S : C.unsigned_short) return C.unsigned_short
renames Short_To_Network;
-- Symmetric operation
private
pragma Import (C, Get_Socket_From_Set, "__gnat_get_socket_from_set");
pragma Import (C, Is_Socket_In_Set, "__gnat_is_socket_in_set");
pragma Import (C, Last_Socket_In_Set, "__gnat_last_socket_in_set");
pragma Import (C, Insert_Socket_In_Set, "__gnat_insert_socket_in_set");
pragma Import (C, Remove_Socket_From_Set, "__gnat_remove_socket_from_set");
pragma Import (C, Reset_Socket_Set, "__gnat_reset_socket_set");
pragma Import (C, C_Ioctl, "__gnat_socket_ioctl");
pragma Import (C, Inet_Pton, SOSC.Inet_Pton_Linkname);
pragma Import (C, Inet_Ntop, SOSC.Inet_Ntop_Linkname);
pragma Import (C, C_Gethostbyname, "__gnat_gethostbyname");
pragma Import (C, C_Gethostbyaddr, "__gnat_gethostbyaddr");
pragma Import (C, C_Getservbyname, "__gnat_getservbyname");
pragma Import (C, C_Getservbyport, "__gnat_getservbyport");
pragma Import (C, C_Getaddrinfo, "__gnat_getaddrinfo");
pragma Import (C, C_Freeaddrinfo, "__gnat_freeaddrinfo");
pragma Import (C, C_Getnameinfo, "__gnat_getnameinfo");
pragma Import (C, C_GAI_Strerror, "__gnat_gai_strerror");
pragma Import (C, Servent_S_Name, "__gnat_servent_s_name");
pragma Import (C, Servent_S_Alias, "__gnat_servent_s_alias");
pragma Import (C, Servent_S_Port, "__gnat_servent_s_port");
pragma Import (C, Servent_S_Proto, "__gnat_servent_s_proto");
pragma Import (C, Hostent_H_Name, "__gnat_hostent_h_name");
pragma Import (C, Hostent_H_Alias, "__gnat_hostent_h_alias");
pragma Import (C, Hostent_H_Addrtype, "__gnat_hostent_h_addrtype");
pragma Import (C, Hostent_H_Length, "__gnat_hostent_h_length");
pragma Import (C, Hostent_H_Addr, "__gnat_hostent_h_addr");
end GNAT.Sockets.Thin_Common;
|
-------------------------------------------------------------------------------
-- Copyright (c) 2019, Daniel King
-- 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.
-- * The name of the copyright holder may not 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 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;
package body Keccak.Generic_KeccakF.Optimized_Permutation
is
-- This implementation is ported from the Optimized implementation by
-- the Keccak, Keyak, and Ketje teams provided in the Keccak Code Package.
procedure Permute (S : in out State)
is
type Round_Constants is array (Round_Index) of Interfaces.Unsigned_64;
Max_Rounds : constant Positive := 12 + (Lane_Size_Log * 2);
First_Round : constant Round_Index := Round_Index (Max_Rounds - 1)
- Round_Index (Num_Rounds - 1);
RC : constant Round_Constants :=
(
16#0000_0000_0000_0001#,
16#0000_0000_0000_8082#,
16#8000_0000_0000_808A#,
16#8000_0000_8000_8000#,
16#0000_0000_0000_808B#,
16#0000_0000_8000_0001#,
16#8000_0000_8000_8081#,
16#8000_0000_0000_8009#,
16#0000_0000_0000_008A#,
16#0000_0000_0000_0088#,
16#0000_0000_8000_8009#,
16#0000_0000_8000_000A#,
16#0000_0000_8000_808B#,
16#8000_0000_0000_008B#,
16#8000_0000_0000_8089#,
16#8000_0000_0000_8003#,
16#8000_0000_0000_8002#,
16#8000_0000_0000_0080#,
16#0000_0000_0000_800A#,
16#8000_0000_8000_000A#,
16#8000_0000_8000_8081#,
16#8000_0000_0000_8080#,
16#0000_0000_8000_0001#,
16#8000_0000_8000_8008#
);
Aba, Abe, Abi, Abo, Abu : Lane_Type;
Aga, Age, Agi, Ago, Agu : Lane_Type;
Aka, Ake, Aki, Ako, Aku : Lane_Type;
Ama, Ame, Ami, Amo, Amu : Lane_Type;
Asa, Ase, Asi, Aso, Asu : Lane_Type;
Ca, Ce, Ci, Co, Cu : Lane_Type;
Eba, Ebe, Ebi, Ebo, Ebu : Lane_Type;
Ega, Ege, Egi, Ego, Egu : Lane_Type;
Eka, Eke, Eki, Eko, Eku : Lane_Type;
Ema, Eme, Emi, Emo, Emu : Lane_Type;
Esa, Ese, Esi, Eso, Esu : Lane_Type;
procedure Copy_From_State
with Inline,
Global => (Input => S,
Output => (Aba, Abe, Abi, Abo, Abu,
Aga, Age, Agi, Ago, Agu,
Aka, Ake, Aki, Ako, Aku,
Ama, Ame, Ami, Amo, Amu,
Asa, Ase, Asi, Aso, Asu));
procedure Copy_To_State_From_A
with Inline,
Global => (Input => (Aba, Abe, Abi, Abo, Abu,
Aga, Age, Agi, Ago, Agu,
Aka, Ake, Aki, Ako, Aku,
Ama, Ame, Ami, Amo, Amu,
Asa, Ase, Asi, Aso, Asu),
Output => S);
procedure Copy_To_State_From_E
with Inline,
Global => (Input => (Eba, Ebe, Ebi, Ebo, Ebu,
Ega, Ege, Egi, Ego, Egu,
Eka, Eke, Eki, Eko, Eku,
Ema, Eme, Emi, Emo, Emu,
Esa, Ese, Esi, Eso, Esu),
Output => S);
procedure Prepare_Theta
with Inline,
Global => (Input => (Aba, Abe, Abi, Abo, Abu,
Aga, Age, Agi, Ago, Agu,
Aka, Ake, Aki, Ako, Aku,
Ama, Ame, Ami, Amo, Amu,
Asa, Ase, Asi, Aso, Asu),
Output => (Ca, Ce, Ci, Co, Cu));
procedure Theta_Rho_Pi_Chi_Iota_Prepare_Theta_AtoE (RI : in Round_Index)
with Inline,
Global => (In_Out => (Aba, Abe, Abi, Abo, Abu,
Aga, Age, Agi, Ago, Agu,
Aka, Ake, Aki, Ako, Aku,
Ama, Ame, Ami, Amo, Amu,
Asa, Ase, Asi, Aso, Asu,
Ca, Ce, Ci, Co, Cu),
Output => (Eba, Ebe, Ebi, Ebo, Ebu,
Ega, Ege, Egi, Ego, Egu,
Eka, Eke, Eki, Eko, Eku,
Ema, Eme, Emi, Emo, Emu,
Esa, Ese, Esi, Eso, Esu));
procedure Theta_Rho_Pi_Chi_Iota_Prepare_Theta_EtoA (RI : in Round_Index)
with Inline,
Global => (In_Out => (Eba, Ebe, Ebi, Ebo, Ebu,
Ega, Ege, Egi, Ego, Egu,
Eka, Eke, Eki, Eko, Eku,
Ema, Eme, Emi, Emo, Emu,
Esa, Ese, Esi, Eso, Esu,
Ca, Ce, Ci, Co, Cu),
Output => (Aba, Abe, Abi, Abo, Abu,
Aga, Age, Agi, Ago, Agu,
Aka, Ake, Aki, Ako, Aku,
Ama, Ame, Ami, Amo, Amu,
Asa, Ase, Asi, Aso, Asu));
procedure Copy_From_State
is
begin
Aba := S (0, 0);
Abe := S (1, 0);
Abi := S (2, 0);
Abo := S (3, 0);
Abu := S (4, 0);
Aga := S (0, 1);
Age := S (1, 1);
Agi := S (2, 1);
Ago := S (3, 1);
Agu := S (4, 1);
Aka := S (0, 2);
Ake := S (1, 2);
Aki := S (2, 2);
Ako := S (3, 2);
Aku := S (4, 2);
Ama := S (0, 3);
Ame := S (1, 3);
Ami := S (2, 3);
Amo := S (3, 3);
Amu := S (4, 3);
Asa := S (0, 4);
Ase := S (1, 4);
Asi := S (2, 4);
Aso := S (3, 4);
Asu := S (4, 4);
end Copy_From_State;
procedure Copy_To_State_From_A
is
begin
S := (0 => (0 => Aba,
1 => Aga,
2 => Aka,
3 => Ama,
4 => Asa),
1 => (0 => Abe,
1 => Age,
2 => Ake,
3 => Ame,
4 => Ase),
2 => (0 => Abi,
1 => Agi,
2 => Aki,
3 => Ami,
4 => Asi),
3 => (0 => Abo,
1 => Ago,
2 => Ako,
3 => Amo,
4 => Aso),
4 => (0 => Abu,
1 => Agu,
2 => Aku,
3 => Amu,
4 => Asu)
);
end Copy_To_State_From_A;
procedure Copy_To_State_From_E
is
begin
S := (0 => (0 => Eba,
1 => Ega,
2 => Eka,
3 => Ema,
4 => Esa),
1 => (0 => Ebe,
1 => Ege,
2 => Eke,
3 => Eme,
4 => Ese),
2 => (0 => Ebi,
1 => Egi,
2 => Eki,
3 => Emi,
4 => Esi),
3 => (0 => Ebo,
1 => Ego,
2 => Eko,
3 => Emo,
4 => Eso),
4 => (0 => Ebu,
1 => Egu,
2 => Eku,
3 => Emu,
4 => Esu)
);
end Copy_To_State_From_E;
procedure Prepare_Theta
is
begin
Ca := Aba xor Aga xor Aka xor Ama xor Asa;
Ce := Abe xor Age xor Ake xor Ame xor Ase;
Ci := Abi xor Agi xor Aki xor Ami xor Asi;
Co := Abo xor Ago xor Ako xor Amo xor Aso;
Cu := Abu xor Agu xor Aku xor Amu xor Asu;
end Prepare_Theta;
procedure Theta_Rho_Pi_Chi_Iota_Prepare_Theta_AtoE (RI : in Round_Index)
is
Da, De, Di, D0, Du : Lane_Type;
Bba, Bbe, Bbi, Bbo, Bbu : Lane_Type;
Bga, Bge, Bgi, Bgo, Bgu : Lane_Type;
Bka, Bke, Bki, Bko, Bku : Lane_Type;
Bma, Bme, Bmi, Bmo, Bmu : Lane_Type;
Bsa, Bse, Bsi, Bso, Bsu : Lane_Type;
begin
Da := Cu xor Rotate_Left (Ce, 1);
De := Ca xor Rotate_Left (Ci, 1);
Di := Ce xor Rotate_Left (Co, 1);
D0 := Ci xor Rotate_Left (Cu, 1);
Du := Co xor Rotate_Left (Ca, 1);
Aba := Aba xor Da;
Bba := Aba;
Age := Age xor De;
Bbe := Rotate_Left (Age, 300 mod Lane_Size_Bits);
Aki := Aki xor Di;
Bbi := Rotate_Left (Aki, 171 mod Lane_Size_Bits);
Amo := Amo xor D0;
Bbo := Rotate_Left (Amo, 21 mod Lane_Size_Bits);
Asu := Asu xor Du;
Bbu := Rotate_Left (Asu, 78 mod Lane_Size_Bits);
Eba := Bba xor ((not Bbe) and Bbi);
Eba := Eba xor Lane_Type (RC (RI) and (2**Lane_Size_Bits - 1));
Ca := Eba;
Ebe := Bbe xor ((not Bbi) and Bbo);
Ce := Ebe;
Ebi := Bbi xor ((not Bbo) and Bbu);
Ci := Ebi;
Ebo := Bbo xor ((not Bbu) and Bba);
Co := Ebo;
Ebu := Bbu xor ((not Bba) and Bbe);
Cu := Ebu;
Abo := Abo xor D0;
Bga := Rotate_Left (Abo, 28 mod Lane_Size_Bits);
Agu := Agu xor Du;
Bge := Rotate_Left (Agu, 276 mod Lane_Size_Bits);
Aka := Aka xor Da;
Bgi := Rotate_Left (Aka, 3 mod Lane_Size_Bits);
Ame := Ame xor De;
Bgo := Rotate_Left (Ame, 45 mod Lane_Size_Bits);
Asi := Asi xor Di;
Bgu := Rotate_Left (Asi, 253 mod Lane_Size_Bits);
Ega := Bga xor ((not Bge) and Bgi);
Ca := Ca xor Ega;
Ege := Bge xor ((not Bgi) and Bgo);
Ce := Ce xor Ege;
Egi := Bgi xor ((not Bgo) and Bgu);
Ci := Ci xor Egi;
Ego := Bgo xor ((not Bgu) and Bga);
Co := Co xor Ego;
Egu := Bgu xor ((not Bga) and Bge);
Cu := Cu xor Egu;
Abe := Abe xor De;
Bka := Rotate_Left (Abe, 1 mod Lane_Size_Bits);
Agi := Agi xor Di;
Bke := Rotate_Left (Agi, 6 mod Lane_Size_Bits);
Ako := Ako xor D0;
Bki := Rotate_Left (Ako, 153 mod Lane_Size_Bits);
Amu := Amu xor Du;
Bko := Rotate_Left (Amu, 136 mod Lane_Size_Bits);
Asa := Asa xor Da;
Bku := Rotate_Left (Asa, 210 mod Lane_Size_Bits);
Eka := Bka xor ((not Bke) and Bki);
Ca := Ca xor Eka;
Eke := Bke xor ((not Bki) and Bko);
Ce := Ce xor Eke;
Eki := Bki xor ((not Bko) and Bku);
Ci := Ci xor Eki;
Eko := Bko xor ((not Bku) and Bka);
Co := Co xor Eko;
Eku := Bku xor ((not Bka) and Bke);
Cu := Cu xor Eku;
Abu := Abu xor Du;
Bma := Rotate_Left (Abu, 91 mod Lane_Size_Bits);
Aga := Aga xor Da;
Bme := Rotate_Left (Aga, 36 mod Lane_Size_Bits);
Ake := Ake xor De;
Bmi := Rotate_Left (Ake, 10 mod Lane_Size_Bits);
Ami := Ami xor Di;
Bmo := Rotate_Left (Ami, 15 mod Lane_Size_Bits);
Aso := Aso xor D0;
Bmu := Rotate_Left (Aso, 120 mod Lane_Size_Bits);
Ema := Bma xor ((not Bme) and Bmi);
Ca := Ca xor Ema;
Eme := Bme xor ((not Bmi) and Bmo);
Ce := Ce xor Eme;
Emi := Bmi xor ((not Bmo) and Bmu);
Ci := Ci xor Emi;
Emo := Bmo xor ((not Bmu) and Bma);
Co := Co xor Emo;
Emu := Bmu xor ((not Bma) and Bme);
Cu := Cu xor Emu;
Abi := Abi xor Di;
Bsa := Rotate_Left (Abi, 190 mod Lane_Size_Bits);
Ago := Ago xor D0;
Bse := Rotate_Left (Ago, 55 mod Lane_Size_Bits);
Aku := Aku xor Du;
Bsi := Rotate_Left (Aku, 231 mod Lane_Size_Bits);
Ama := Ama xor Da;
Bso := Rotate_Left (Ama, 105 mod Lane_Size_Bits);
Ase := Ase xor De;
Bsu := Rotate_Left (Ase, 66 mod Lane_Size_Bits);
Esa := Bsa xor ((not Bse) and Bsi);
Ca := Ca xor Esa;
Ese := Bse xor ((not Bsi) and Bso);
Ce := Ce xor Ese;
Esi := Bsi xor ((not Bso) and Bsu);
Ci := Ci xor Esi;
Eso := Bso xor ((not Bsu) and Bsa);
Co := Co xor Eso;
Esu := Bsu xor ((not Bsa) and Bse);
Cu := Cu xor Esu;
end Theta_Rho_Pi_Chi_Iota_Prepare_Theta_AtoE;
procedure Theta_Rho_Pi_Chi_Iota_Prepare_Theta_EtoA (RI : in Round_Index)
is
Da, De, Di, D0, Du : Lane_Type;
Bba, Bbe, Bbi, Bbo, Bbu : Lane_Type;
Bga, Bge, Bgi, Bgo, Bgu : Lane_Type;
Bka, Bke, Bki, Bko, Bku : Lane_Type;
Bma, Bme, Bmi, Bmo, Bmu : Lane_Type;
Bsa, Bse, Bsi, Bso, Bsu : Lane_Type;
begin
Da := Cu xor Rotate_Left (Ce, 1);
De := Ca xor Rotate_Left (Ci, 1);
Di := Ce xor Rotate_Left (Co, 1);
D0 := Ci xor Rotate_Left (Cu, 1);
Du := Co xor Rotate_Left (Ca, 1);
Eba := Eba xor Da;
Bba := Eba;
Ege := Ege xor De;
Bbe := Rotate_Left (Ege, 300 mod Lane_Size_Bits);
Eki := Eki xor Di;
Bbi := Rotate_Left (Eki, 171 mod Lane_Size_Bits);
Emo := Emo xor D0;
Bbo := Rotate_Left (Emo, 21 mod Lane_Size_Bits);
Esu := Esu xor Du;
Bbu := Rotate_Left (Esu, 78 mod Lane_Size_Bits);
Aba := Bba xor ((not Bbe) and Bbi);
Aba := Aba xor Lane_Type (RC (RI) and (2**Lane_Size_Bits - 1));
Ca := Aba;
Abe := Bbe xor ((not Bbi) and Bbo);
Ce := Abe;
Abi := Bbi xor ((not Bbo) and Bbu);
Ci := Abi;
Abo := Bbo xor ((not Bbu) and Bba);
Co := Abo;
Abu := Bbu xor ((not Bba) and Bbe);
Cu := Abu;
Ebo := Ebo xor D0;
Bga := Rotate_Left (Ebo, 28 mod Lane_Size_Bits);
Egu := Egu xor Du;
Bge := Rotate_Left (Egu, 276 mod Lane_Size_Bits);
Eka := Eka xor Da;
Bgi := Rotate_Left (Eka, 3 mod Lane_Size_Bits);
Eme := Eme xor De;
Bgo := Rotate_Left (Eme, 45 mod Lane_Size_Bits);
Esi := Esi xor Di;
Bgu := Rotate_Left (Esi, 253 mod Lane_Size_Bits);
Aga := Bga xor ((not Bge) and Bgi);
Ca := Ca xor Aga;
Age := Bge xor ((not Bgi) and Bgo);
Ce := Ce xor Age;
Agi := Bgi xor ((not Bgo) and Bgu);
Ci := Ci xor Agi;
Ago := Bgo xor ((not Bgu) and Bga);
Co := Co xor Ago;
Agu := Bgu xor ((not Bga) and Bge);
Cu := Cu xor Agu;
Ebe := Ebe xor De;
Bka := Rotate_Left (Ebe, 1 mod Lane_Size_Bits);
Egi := Egi xor Di;
Bke := Rotate_Left (Egi, 6 mod Lane_Size_Bits);
Eko := Eko xor D0;
Bki := Rotate_Left (Eko, 153 mod Lane_Size_Bits);
Emu := Emu xor Du;
Bko := Rotate_Left (Emu, 136 mod Lane_Size_Bits);
Esa := Esa xor Da;
Bku := Rotate_Left (Esa, 210 mod Lane_Size_Bits);
Aka := Bka xor ((not Bke) and Bki);
Ca := Ca xor Aka;
Ake := Bke xor ((not Bki) and Bko);
Ce := Ce xor Ake;
Aki := Bki xor ((not Bko) and Bku);
Ci := Ci xor Aki;
Ako := Bko xor ((not Bku) and Bka);
Co := Co xor Ako;
Aku := Bku xor ((not Bka) and Bke);
Cu := Cu xor Aku;
Ebu := Ebu xor Du;
Bma := Rotate_Left (Ebu, 91 mod Lane_Size_Bits);
Ega := Ega xor Da;
Bme := Rotate_Left (Ega, 36 mod Lane_Size_Bits);
Eke := Eke xor De;
Bmi := Rotate_Left (Eke, 10 mod Lane_Size_Bits);
Emi := Emi xor Di;
Bmo := Rotate_Left (Emi, 15 mod Lane_Size_Bits);
Eso := Eso xor D0;
Bmu := Rotate_Left (Eso, 120 mod Lane_Size_Bits);
Ama := Bma xor ((not Bme) and Bmi);
Ca := Ca xor Ama;
Ame := Bme xor ((not Bmi) and Bmo);
Ce := Ce xor Ame;
Ami := Bmi xor ((not Bmo) and Bmu);
Ci := Ci xor Ami;
Amo := Bmo xor ((not Bmu) and Bma);
Co := Co xor Amo;
Amu := Bmu xor ((not Bma) and Bme);
Cu := Cu xor Amu;
Ebi := Ebi xor Di;
Bsa := Rotate_Left (Ebi, 190 mod Lane_Size_Bits);
Ego := Ego xor D0;
Bse := Rotate_Left (Ego, 55 mod Lane_Size_Bits);
Eku := Eku xor Du;
Bsi := Rotate_Left (Eku, 231 mod Lane_Size_Bits);
Ema := Ema xor Da;
Bso := Rotate_Left (Ema, 105 mod Lane_Size_Bits);
Ese := Ese xor De;
Bsu := Rotate_Left (Ese, 66 mod Lane_Size_Bits);
Asa := Bsa xor ((not Bse) and Bsi);
Ca := Ca xor Asa;
Ase := Bse xor ((not Bsi) and Bso);
Ce := Ce xor Ase;
Asi := Bsi xor ((not Bso) and Bsu);
Ci := Ci xor Asi;
Aso := Bso xor ((not Bsu) and Bsa);
Co := Co xor Aso;
Asu := Bsu xor ((not Bsa) and Bse);
Cu := Cu xor Asu;
end Theta_Rho_Pi_Chi_Iota_Prepare_Theta_EtoA;
begin
Copy_From_State;
Prepare_Theta;
for RI in 0 .. (Num_Rounds / 2) - 1 loop
pragma Warnings
(GNATprove, Off,
"unused assignment to ""A",
Reason => "Axx variables are also re-used as temporaries");
Theta_Rho_Pi_Chi_Iota_Prepare_Theta_AtoE (First_Round + Round_Index (RI * 2));
pragma Warnings (GNATprove, On);
pragma Warnings
(GNATprove, Off,
"unused assignment to ""E",
Reason => "Exx variables are also re-used as temporaries");
Theta_Rho_Pi_Chi_Iota_Prepare_Theta_EtoA (First_Round + Round_Index (RI * 2) + 1);
pragma Warnings (GNATprove, On);
end loop;
if Num_Rounds mod 2 /= 0 then
-- Number of rounds is an odd number, so we need to do the final step.
pragma Warnings
(GNATprove, Off,
"unused assignment to ""C",
Reason => "Cx variables are no longer needed");
Theta_Rho_Pi_Chi_Iota_Prepare_Theta_AtoE (First_Round + Round_Index (Num_Rounds - 1));
pragma Warnings (GNATprove, On);
Copy_To_State_From_E;
else
Copy_To_State_From_A;
end if;
end Permute;
end Keccak.Generic_KeccakF.Optimized_Permutation;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015-2017, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- This packages provide a low level driver for the FAT file system
-- architecture. It is recommended to _not_ use this interface directly but to
-- access the file system using the File_IO package. For more info, see the
-- file system chapter of the documentation.
with Ada.Unchecked_Conversion;
with Filesystem.FAT.Directories;
package body Filesystem.FAT.Files is
function Absolute_Block (File : in out FAT_File_Handle) return Block_Number
with Inline_Always;
function Ensure_Buffer (File : in out FAT_File_Handle) return Status_Code
with Inline_Always;
function Next_Block
(File : in out FAT_File_Handle;
Inc : Positive := 1) return Status_Code;
--------------------
-- Absolute_Block --
--------------------
function Absolute_Block (File : in out FAT_File_Handle) return Block_Number
is (File.FS.LBA +
File.FS.Cluster_To_Block (File.Current_Cluster) +
File.Current_Block);
-------------------
-- Ensure_Buffer --
-------------------
function Ensure_Buffer (File : in out FAT_File_Handle) return Status_Code
is
begin
if not File.Buffer_Filled and then File.Mode /= Write_Only then
if not File.FS.Controller.Read
(Absolute_Block (File),
File.Buffer)
then
-- Read error
return Disk_Error;
end if;
File.Buffer_Filled := True;
File.Buffer_Dirty := False;
end if;
return OK;
end Ensure_Buffer;
----------------
-- Next_Block --
----------------
function Next_Block
(File : in out FAT_File_Handle;
Inc : Positive := 1) return Status_Code
is
Todo : Block_Offset := Block_Offset (Inc);
Status : Status_Code;
Next : Cluster_Type;
begin
-- First take care of uninitialized handlers:
if File.Is_Free then
return Invalid_Parameter;
end if;
if File.Current_Cluster = 0 then
File.Current_Cluster := File.D_Entry.Start_Cluster;
File.Current_Block := 0;
Todo := Todo - 1;
if Todo = 0 then
return OK;
end if;
end if;
Status := Flush (File);
if Status /= OK then
return Status;
end if;
-- Invalidate the current block buffer
File.Buffer_Filled := False;
while Todo > 0 loop
-- Move to the next block
if File.Current_Block + Todo >= File.FS.Blocks_Per_Cluster then
Todo := Todo + File.Current_Block - File.FS.Blocks_Per_Cluster;
File.Current_Block := File.FS.Blocks_Per_Cluster;
else
File.Current_Block := File.Current_Block + Todo;
Todo := 0;
end if;
-- Check if we're still in the same cluster
if File.Current_Block = File.FS.Blocks_Per_Cluster then
-- Move on to the next cluster
File.Current_Block := 0;
Next := File.FS.Get_FAT (File.Current_Cluster);
if Next < 2 then
return Internal_Error;
elsif not File.FS.Is_Last_Cluster (Next) then
-- Nominal case: there's a next cluster
File.Current_Cluster := Next;
elsif File.Mode /= Read_Only then
-- Allocate a new cluster
File.Current_Cluster :=
File.FS.New_Cluster (File.Current_Cluster);
if File.Current_Cluster = INVALID_CLUSTER then
return Disk_Full;
end if;
else
-- Invalid operation: should not happen, so raise an internal
-- error
return Internal_Error;
end if;
end if;
end loop;
return OK;
end Next_Block;
----------
-- Open --
----------
function Open
(Parent : FAT_Node;
Name : FAT_Name;
Mode : File_Mode;
File : FAT_File_Handle_Access) return Status_Code
is
Node : FAT_Node;
Ret : Status_Code;
begin
Ret := Directories.Find (Parent, Name, Node);
if Ret /= OK then
if Mode = Read_Only then
return No_Such_File;
end if;
Ret := Directories.Create_File_Node (Parent, Name, Node);
end if;
if Ret /= OK then
return Ret;
end if;
if Mode = Write_Only then
Directories.Set_Size (Node, 0);
-- Free the cluster chain if > 1 cluster
Ret := Directories.Adjust_Clusters (Node);
if Ret /= OK then
return Ret;
end if;
end if;
File.Is_Free := False;
File.FS := Node.FS;
File.Mode := Mode;
File.Current_Cluster := Node.Start_Cluster;
File.Current_Block := 0;
File.Buffer := (others => 0);
File.Buffer_Filled := False;
File.Buffer_Dirty := False;
File.File_Index := 0;
File.D_Entry := Node;
File.Parent := Parent;
return OK;
end Open;
----------
-- Read --
----------
function Read
(File : in out FAT_File_Handle;
Addr : System.Address;
Length : in out FAT_File_Size) return Status_Code
is
type Address is mod 2 ** System.Word_Size;
function To_Address is new Ada.Unchecked_Conversion
(System.Address, Address);
Data : File_Data (1 .. Length) with Import, Address => Addr;
-- Byte array representation of the buffer to read
Addr_Int : constant Unsigned_64 := Unsigned_64 (To_Address (Addr));
Idx : FAT_File_Size;
-- Index from the current block
Data_Length : FAT_File_Size := Data'Length;
-- The total length to read
Data_Idx : FAT_File_Size := Data'First;
-- Index into the data array of the next bytes to read
R_Length : FAT_File_Size;
-- The size of the data to read in one operation
N_Blocks : Block_Offset;
Status : Status_Code;
begin
if File.Is_Free then
Length := 0;
return Invalid_Parameter;
end if;
if File.Mode = Write_Only then
Length := 0;
return Access_Denied;
end if;
-- Are we at then end of the file?
if File.File_Index = File.D_Entry.Size
or else Data_Length = 0
then
Length := 0;
return OK;
end if;
Status := Flush (File);
if Status /= OK then
Length := 0;
return Status;
end if;
-- Clamp the number of data to read to the size of the file
Data_Length := FAT_File_Size'Min
(File.D_Entry.Size - File.File_Index,
Data_Length);
loop
Idx := File.File_Index mod File.FS.Block_Size;
if Idx = 0 and then Data_Length >= File.FS.Block_Size then
-- Case where the data to read is aligned on a block, and
-- we have at least one block to read.
-- Check the compatibility of the User's buffer with DMA transfers
if (Addr_Int mod 4) = 0 then
-- User data is aligned on words: we can directly perform DMA
-- transfers to it
-- Read as many blocks as possible withing the current cluster
N_Blocks := Block_Offset'Min
(Block_Offset (Data_Length / File.FS.Block_Size),
File.FS.Blocks_Per_Cluster - File.Current_Block);
if not File.FS.Controller.Read
(Absolute_Block (File),
HAL.UInt8_Array
(Data
(Data_Idx ..
Data_Idx +
FAT_File_Size (N_Blocks) * File.FS.Block_Size - 1)))
then
-- Read error: return the number of data read so far
Length := Data_Idx - Data'First;
return Disk_Error;
end if;
Status := Next_Block (File, Positive (N_Blocks));
if Status /= OK then
Length := Data_Idx - Data'First;
return Status;
end if;
else
-- User data is not aligned: we thus have to use the Handle's
-- cache (512 bytes)
-- Reading one block
N_Blocks := 1;
-- Fill the buffer
Status := Ensure_Buffer (File);
if Status /= OK then
-- read error: return the number of bytes read so far
Length := Data_Idx - Data'First;
return Status;
end if;
Data (Data_Idx .. Data_Idx + 511) := File_Data (File.Buffer);
Status := Next_Block (File);
if Status /= OK then
Length := Data_Idx - Data'First;
return Status;
end if;
end if;
Data_Idx := Data_Idx + FAT_File_Size (N_Blocks) * 512;
File.File_Index :=
File.File_Index + FAT_File_Size (N_Blocks) * 512;
Data_Length := Data_Length - FAT_File_Size (N_Blocks) * 512;
else
-- Not aligned on a block, or less than 512 bytes to read
-- We thus need to use our internal buffer.
Status := Ensure_Buffer (File);
if Status /= OK then
-- read error: return the number of bytes read so far
Length := Data_Idx - Data'First;
return Status;
end if;
R_Length := FAT_File_Size'Min (File.Buffer'Length - Idx,
Data_Length);
Data (Data_Idx .. Data_Idx + R_Length - 1) := File_Data
(File.Buffer (Natural (Idx) .. Natural (Idx + R_Length - 1)));
Data_Idx := Data_Idx + R_Length;
File.File_Index := File.File_Index + R_Length;
Data_Length := Data_Length - R_Length;
if Idx + R_Length = File.FS.Block_Size then
Status := Next_Block (File);
if Status /= OK then
Length := Data_Idx - Data'First;
return Status;
end if;
end if;
end if;
exit when Data_Length = 0;
end loop;
-- Update the number of bytes we actually read
Length := Data_Idx - Data'First;
return OK;
end Read;
-----------
-- Write --
-----------
function Write
(File : in out FAT_File_Handle;
Addr : System.Address;
Length : FAT_File_Size) return Status_Code
is
procedure Inc_Size (Amount : FAT_File_Size);
Data : aliased File_Data (1 .. Length) with Address => Addr;
-- Byte array representation of the data to write
Idx : FAT_File_Size;
Data_Length : FAT_File_Size := Data'Length;
-- The total length to read
Data_Idx : FAT_File_Size := Data'First;
-- Index into the data array of the next bytes to write
N_Blocks : FAT_File_Size;
-- The number of blocks to read at once
W_Length : FAT_File_Size;
-- The size of the data to write in one operation
Status : Status_Code;
--------------
-- Inc_Size --
--------------
procedure Inc_Size (Amount : FAT_File_Size)
is
begin
Data_Idx := Data_Idx + Amount;
File.File_Index := File.File_Index + Amount;
Data_Length := Data_Length - Amount;
Directories.Set_Size (File.D_Entry, File.File_Index);
end Inc_Size;
begin
if File.Is_Free or File.Mode = Read_Only then
return Access_Denied;
end if;
if Data_Length = 0 then
return OK;
end if;
-- Initialize the current cluster if not already done
if File.Current_Cluster = 0 then
Status := Next_Block (File);
if Status /= OK then
return Status;
end if;
end if;
Idx := File.File_Index mod File.FS.Block_Size;
if Data_Length < File.FS.Block_Size then
-- First fill the buffer
if Ensure_Buffer (File) /= OK then
-- read error: return the number of bytes read so far
return Disk_Error;
end if;
W_Length := FAT_File_Size'Min
(File.Buffer'Length - Idx,
Data'Length);
File.Buffer (Natural (Idx) .. Natural (Idx + W_Length - 1)) :=
Block (Data (Data_Idx .. Data_Idx + W_Length - 1));
File.Buffer_Dirty := True;
Inc_Size (W_Length);
-- If we stopped on the boundaries of a new block, then move on to
-- the next block
if (File.File_Index mod File.FS.Block_Size) = 0 then
Status := Next_Block (File);
if Status /= OK then
return Status;
end if;
end if;
if Data_Length = 0 then
-- We've written all the data, let's exit right now
return OK;
end if;
end if;
-- At this point, the buffer is empty and a new block is ready to be
-- written. Check if we can write several blocks at once
while Data_Length >= File.FS.Block_Size loop
-- we have at least one full block to write.
-- Determine the number of full blocks we need to write:
N_Blocks := FAT_File_Size'Min
(FAT_File_Size (File.FS.Blocks_Per_Cluster) -
FAT_File_Size (File.Current_Block),
Data_Length / File.FS.Block_Size);
-- Writing all blocks in one operation
W_Length := N_Blocks * File.FS.Block_Size;
-- Fill directly the user data
if not File.FS.Controller.Write
(Absolute_Block (File),
Block (Data (Data_Idx .. Data_Idx + W_Length - 1)))
then
return Disk_Error;
end if;
Inc_Size (W_Length);
Status := Next_Block (File, Positive (N_Blocks));
if Status /= OK then
return Status;
end if;
end loop;
-- Now everything that remains is smaller than a block. Let's fill the
-- buffer with this data
if Data_Length > 0 then
-- First fill the buffer
if Ensure_Buffer (File) /= OK then
return Disk_Error;
end if;
File.Buffer (0 .. Natural (Data_Length - 1)) :=
Block (Data (Data_Idx .. Data'Last));
File.Buffer_Dirty := True;
Inc_Size (Data_Length);
end if;
return OK;
end Write;
-----------
-- Flush --
-----------
function Flush
(File : in out FAT_File_Handle) return Status_Code
is
begin
if File.Buffer_Dirty then
if not File.FS.Controller.Write
(Absolute_Block (File),
File.Buffer)
then
return Disk_Error;
end if;
File.Buffer_Dirty := False;
end if;
return Directories.Update_Entry (Parent => File.Parent,
Value => File.D_Entry);
end Flush;
----------
-- Seek --
----------
function Seek
(File : in out FAT_File_Handle;
Amount : in out FAT_File_Size;
Origin : Seek_Mode) return Status_Code
is
Status : Status_Code;
New_Pos : FAT_File_Size;
N_Blocks : FAT_File_Size;
begin
case Origin is
when From_Start =>
if Amount > File.D_Entry.Size then
Amount := File.D_Entry.Size;
end if;
New_Pos := Amount;
when From_End =>
if Amount > File.D_Entry.Size then
Amount := File.D_Entry.Size;
end if;
New_Pos := File.D_Entry.Size - Amount;
when Forward =>
if Amount + File.File_Index > File.D_Entry.Size then
Amount := File.D_Entry.Size - File.File_Index;
end if;
New_Pos := File.File_Index + Amount;
when Backward =>
if Amount > File.File_Index then
Amount := File.File_Index;
end if;
New_Pos := File.File_Index - Amount;
end case;
if New_Pos < File.File_Index then
-- Rewind the file pointer to the beginning of the file
-- ??? A better check would be to first check if we're still in the
-- same cluster, in which case we wouldn't need to do this rewind,
-- but even if it's the case, we're still safe here, although a bit
-- slower than we could.
File.File_Index := 0;
File.Current_Cluster := File.D_Entry.Start_Cluster;
File.Current_Block := 0;
File.Buffer_Filled := False;
end if;
N_Blocks := (New_Pos - File.File_Index) / File.FS.Block_Size;
if N_Blocks > 0 then
Status := Next_Block (File, Positive (N_Blocks));
if Status /= OK then
return Status;
end if;
end if;
File.File_Index := New_Pos;
if Ensure_Buffer (File) /= OK then
return Disk_Error;
end if;
return OK;
end Seek;
-----------
-- Close --
-----------
procedure Close (File : in out FAT_File_Handle)
is
Status : Status_Code with Unreferenced;
begin
Status := Flush (File);
end Close;
end Filesystem.FAT.Files;
|
with Ada.Real_Time;
with Ada.Text_IO;
with AWS.Default;
with AWS.Server;
with Router_Cb;
procedure Main
is
WS : AWS.Server.HTTP;
Port : constant Natural := AWS.Default.Server_Port;
begin
Ada.Text_IO.Put_Line
("Serving on 127.0.0.1:" & Port'Img);
Router_Cb.Init;
AWS.Server.Start (WS,
"Hello World",
Max_Connection => 1,
Callback => Router_Cb.Router'Access,
Port => Port);
while Router_Cb.Server_Alive loop
delay until Ada.Real_Time.Time_Last;
end loop;
AWS.Server.Shutdown (WS);
end Main;
|
pragma SPARK_Mode;
with Line_Finder_Types; use Line_Finder_Types;
with Geo_Filter;
with Types; use Types;
with Zumo_LED;
with Zumo_Motors;
with Zumo_QTR;
-- @summary
-- Line finder algorithm
--
-- @description
-- This package implements the line finder algorithm
--
package Line_Finder is
-- Amount of time to determine "Hey I'm lost". Used to switch decision type
Lost_Threshold : constant := 100;
BotState : RobotState;
-- Default fast speed used when "Hey I know where I am!!"
Default_Fast_Speed : constant := Motor_Speed'Last - 150;
-- Default slow speed used when "I'm not sure where I am!!"
Default_Slow_Speed : constant := 3 * Default_Fast_Speed / 4;
-- Default slowest speed used when "I have to make a decision,
-- lets oversample"
Default_Slowest_Speed : constant := Default_Slow_Speed / 2;
-- Current fast speed
Fast_Speed : Motor_Speed := Default_Fast_Speed;
-- Current slow speed
Slow_Speed : Motor_Speed := Default_Slow_Speed;
-- The line finder algorithm entry point
-- @param ReadMode the read mode to pass to read sensors
procedure LineFinder (ReadMode : Sensor_Read_Mode)
with Global => (Proof_In => (Zumo_QTR.Initd,
Zumo_LED.Initd,
Zumo_Motors.Initd),
Input => (Zumo_Motors.FlipLeft,
Zumo_Motors.FlipRight,
Zumo_QTR.Calibrated_On,
Zumo_QTR.Calibrated_Off),
Output => (Fast_Speed,
Slow_Speed),
In_Out => (BotState,
Zumo_QTR.Cal_Vals_On,
Zumo_QTR.Cal_Vals_Off,
Geo_Filter.Window,
Geo_Filter.Window_Index)),
Pre => (Zumo_LED.Initd and
Zumo_Motors.Initd and
Zumo_QTR.Initd);
private
-- This procedure reads the sensors and determine the bot position
-- @param WhiteLine am I looking for a white line or black line
-- @param ReadMode what mode to read to sensors with
-- @param State the computed LineState
procedure ReadLine (WhiteLine : Boolean;
ReadMode : Sensor_Read_Mode;
State : out LineState)
with Global => (Proof_In => Zumo_QTR.Initd,
Input => (Zumo_QTR.Calibrated_On,
Zumo_QTR.Calibrated_Off),
In_Out => (BotState,
Zumo_QTR.Cal_Vals_On,
Zumo_QTR.Cal_Vals_Off)),
Pre => (Zumo_QTR.Initd);
-- Calculates the bots position in relation to the line
-- @param Pos the computed position of the robot on the line
procedure CalculateBotPosition (Pos : out Robot_Position);
-- The complex decision matrix to decide the meaning of life
-- @param State the state computed previously to use in the decision
procedure DecisionMatrix (State : LineState)
with Global => (Proof_In => (Zumo_LED.Initd,
Zumo_Motors.Initd),
Input => (Fast_Speed,
Slow_Speed,
Zumo_Motors.FlipLeft,
Zumo_Motors.FlipRight),
In_Out => BotState),
Pre => (Zumo_LED.Initd and
Zumo_Motors.Initd);
-- The simple decision matrix to decide how to survive
-- See complex decision matrix for normal operation
-- @param State the state computed previously to use in the decision
procedure SimpleDecisionMatrix (State : LineState)
with Global => (Proof_In => (Zumo_LED.Initd,
Zumo_Motors.Initd),
Input => (Fast_Speed,
Zumo_Motors.FlipLeft,
Zumo_Motors.FlipRight),
In_Out => BotState),
Pre => (Zumo_LED.Initd and
Zumo_Motors.Initd);
-- This computes how to adjust the motors to bring the bot back centered
-- on the line.
-- @param Error the computed error since the last detection
-- @param Current_Speed the current speed of the bot
-- @param LeftSpeed the new computed speed for the left motor
-- @param RightSpeed the new computed speed for the right motor
procedure Error_Correct (Error : Robot_Position;
Current_Speed : Motor_Speed;
LeftSpeed : out Motor_Speed;
RightSpeed : out Motor_Speed)
with Global => (In_Out => (BotState));
end Line_Finder;
|
with HAL;
generic
with package USART is new HAL.USART (<>);
package Drivers.Text_IO is
procedure Put (C : Character);
procedure Put (S : String);
procedure Put_Line (S : String);
procedure Put_Integer (N : Integer; Width : Natural := 0);
procedure Put_Hex (N : Unsigned_32; Width : Unsigned_8 := 0);
procedure New_Line;
procedure Get_Line (S : out String; Count : out Natural);
procedure Hex_Dump (S : String);
end Drivers.Text_IO;
|
-- Demonstrates:
-- Declaring arrays
-- Passing arrays as parameters
-- Aggregate assignment
-- Attribute: 'first, 'last, 'range
with ada.integer_text_io; use ada.integer_text_io;
with ada.text_io; use ada.text_io;
procedure array_declare is
-- A CONSTRAINED array type. Bounds can be any values
type My_C_Array_T is array(-3 .. 3) of Natural;
-- A named array type as a parameter
procedure print1(a: My_C_Array_T) is
begin
for i in -3 .. 3 loop
put(a(i));
end loop;
end print1;
-- An UNCONSTRAINED array type: bounds must be naturals
type My_U_Array_T is array(Natural range <>) of Integer;
-- A named array type as a parameter
procedure print2(a: My_U_Array_T) is
begin
for i in a'range loop
put(a(i));
end loop;
end print2;
-- Declare some variables - declare them here so they are not global
-- a1 and a2 have anonymous types and can't be used in assignment or as parameters
a1: array(-3 .. 3) of Natural := (others => 0); -- Aggregate assignment
a2: array(a1'range) of Natural := (others => 0); -- Aggregate assignment
-- a3 and a4 have a named array type
a3: My_C_Array_T;
-- Different sizes, same named type
a4: My_U_Array_T(2 .. 5) := (others => 0);
a5: My_U_Array_T(12 .. 25) := (others => 0);
begin
-- Print a1 and a2:
for i in a1'range loop
put(a1(i));
put(a2(i));
new_line;
end loop;
a3 := (-2 | 2 => 1, others => 0); -- Aggregate assignment
print1(a3);
print2(a4);
print2(a5);
end array_declare;
|
with GNAT.Source_Info;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Memory; use Memory;
with Memory.Container; use Memory.Container;
with Util; use Util;
-- Base package for unit tests.
package Test is
-- Run the unit tests.
procedure Run_Tests;
private
-- A memory for monitoring accesses.
type Monitor_Type is new Container_Type with record
last_addr : Address_Type := Address_Type'Last;
last_size : Positive := Positive'Last;
reads : Natural := 0;
writes : Natural := 0;
cycles : Time_Type := 0;
latency : Time_Type := 0;
end record;
type Monitor_Pointer is access all Monitor_Type;
function Create_Monitor(latency : Time_Type := 0;
ram : Boolean := True)
return Monitor_Pointer;
overriding
function Clone(mem : Monitor_Type) return Memory_Pointer;
overriding
procedure Read(mem : in out Monitor_Type;
address : in Address_Type;
size : in Positive);
overriding
procedure Write(mem : in out Monitor_Type;
address : in Address_Type;
size : in Positive);
overriding
procedure Idle(mem : in out Monitor_Type;
cycles : in Time_Type);
overriding
procedure Generate(mem : in Monitor_Type;
sigs : in out Unbounded_String;
code : in out Unbounded_String);
-- Assert a condition.
-- This function will report the file and line number for failures.
procedure Check(cond : in Boolean;
source : in String := GNAT.Source_Info.File;
line : in Natural := GNAT.Source_Info.Line);
count : Natural := 0;
failed : Natural := 0;
end Test;
|
package body BBqueue.Buffers.framed
with SPARK_Mode
is
pragma Compile_Time_Error ((Count'Object_Size mod System.Storage_Unit) /= 0,
"Invalid Object_Size for Count");
procedure Write_Header (After_Hdr_Addr : System.Address;
Hdr_Size : Header_Count;
Value : Count);
procedure Read_Header (Before_Hdr_Addr : System.Address;
Hdr_Size : out Header_Count;
Frame_Size : out Framed_Count)
with Post => Hdr_Size = (Count'Object_Size / System.Storage_Unit);
function Header_Size (Unused : Count) return Header_Count
is (Count'Object_Size / System.Storage_Unit)
with Post => Header_Size'Result in 1 .. 9;
-- TODO: The size of the header can be optimized using variable-length
-- encoding.
------------------
-- Write_Header --
------------------
procedure Write_Header (After_Hdr_Addr : System.Address;
Hdr_Size : Header_Count;
Value : Count)
is
pragma SPARK_Mode (Off);
Header : Count
with Address =>
To_Address (To_Integer (After_Hdr_Addr) - Integer_Address (Hdr_Size));
begin
Header := Value;
end Write_Header;
-----------------
-- Read_Header --
-----------------
procedure Read_Header (Before_Hdr_Addr : System.Address;
Hdr_Size : out Header_Count;
Frame_Size : out Framed_Count)
is
pragma SPARK_Mode (Off);
Header : Count
with Address => Before_Hdr_Addr;
begin
Frame_Size := Header;
Hdr_Size := Header_Size (Frame_Size);
end Read_Header;
-----------
-- Grant --
-----------
procedure Grant (This : in out Framed_Buffer;
G : in out Write_Grant;
Size : Framed_Count)
is
Hdr_Size : constant Count := Header_Size (Size);
begin
if Size = 0 then
BBqueue.Buffers.Grant (This.Buffer, G.Grant, Size);
G.Header_Size := 0;
return;
end if;
-- Save the worst case header size
G.Header_Size := Hdr_Size;
-- Request Size + worst case header size
BBqueue.Buffers.Grant (This.Buffer, G.Grant, Size + Hdr_Size);
if State (G) = Valid then
pragma Assert (G.Grant.Slice.Length = Size + Hdr_Size);
-- Change the slice to skip the header
G.Grant.Slice.Length := G.Grant.Slice.Length - Hdr_Size;
G.Grant.Slice.Addr :=
To_Address (To_Integer (G.Grant.Slice.Addr) + Integer_Address (Hdr_Size));
else
-- Grant failed, no header
G.Header_Size := 0;
end if;
end Grant;
------------
-- Commit --
------------
procedure Commit (This : in out Framed_Buffer;
G : in out Write_Grant;
Size : Framed_Count := Framed_Count'Last)
is
begin
if Size = 0 then
-- Nothing to commit
BBqueue.Buffers.Commit (This.Buffer, G.Grant, 0);
else
-- Write the header in the buffer
Write_Header (Slice (G.Grant).Addr, G.Header_Size, Size);
-- Commit header + data
BBqueue.Buffers.Commit (This.Buffer, G.Grant, Size + G.Header_Size);
end if;
if State (G) = Empty then
G.Header_Size := 0;
end if;
end Commit;
--------------
-- Write_CB --
--------------
procedure Write_CB
(This : in out Framed_Buffer;
Size : Framed_Count;
Result : out Result_Kind)
is
G : Write_Grant := Empty;
begin
Grant (This, G, Size);
Result := State (G);
if Result = Valid then
declare
S : constant Slice_Rec := Slice (G);
B : Storage_Array (1 .. S.Length)
with Address => S.Addr;
To_Commit : Count;
begin
Process_Write (B, To_Commit);
Commit (This, G, To_Commit);
pragma Assert (State (G) = Empty);
end;
end if;
end Write_CB;
----------
-- Read --
----------
procedure Read (This : in out Framed_Buffer; G : in out Read_Grant) is
Frame_Size : Framed_Count;
Hdr_Size : Header_Count;
begin
BBqueue.Buffers.Read (This.Buffer, G.Grant);
if State (G) = Valid then
-- Get header size and value from the buffer
Read_Header (Slice (G.Grant).Addr, Hdr_Size, Frame_Size);
G.Header_Size := Hdr_Size;
-- Change the slice to skip the header and set the actuall value of
-- the frame.
G.Grant.Slice.Length := Frame_Size;
G.Grant.Slice.Addr :=
To_Address (To_Integer (G.Grant.Slice.Addr) + Integer_Address (Hdr_Size));
This.Current_Read_Size := Frame_Size;
end if;
end Read;
-------------
-- Release --
-------------
procedure Release (This : in out Framed_Buffer; G : in out Read_Grant) is
begin
BBqueue.Buffers.Release (This.Buffer,
G.Grant,
G.Header_Size + This.Current_Read_Size);
G.Header_Size := 0;
end Release;
-------------
-- Read_CB --
-------------
procedure Read_CB (This : in out Framed_Buffer; Result : out Result_Kind) is
G : Read_Grant := Empty;
procedure Call_CB (Addr : System.Address;
Length : Framed_Count);
procedure Call_CB (Addr : System.Address;
Length : Framed_Count)
is
pragma SPARK_Mode (Off);
B : Storage_Array (1 .. Length)
with Address => Addr;
begin
Process_Read (B);
end Call_CB;
begin
Read (This, G);
Result := State (G);
if Result = Valid then
Call_CB (Slice (G).Addr, This.Current_Read_Size);
Release (This, G);
pragma Assert (State (G) = Empty);
end if;
end Read_CB;
end BBqueue.Buffers.framed;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2018 - 2019 Joakim Strandberg <joakim@mequinox.se>
--
-- 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.
private with Interfaces.C;
private with System;
package Wayland is
pragma Pure;
type Unsigned_32 is mod 2 ** Integer'Size
with Size => Integer'Size;
type Unsigned_64 is mod 2 ** (Unsigned_32'Size * 2)
with Size => Unsigned_32'Size * 2;
type Unsigned_32_Array is array (Positive range <>) of Unsigned_32
with Convention => C;
type Fixed is delta 2.0 ** (-8) range -(2.0 ** 23) .. +(2.0 ** 23 - 1.0)
with Small => 2.0 ** (-8),
Size => Integer'Size;
type File_Descriptor is new Integer;
type Call_Result_Code is (Success, Error);
type Optional_Result (Is_Success : Boolean := False) is record
case Is_Success is
when True => Count : Natural;
when False => null;
end case;
end record;
subtype Unused_Type is Boolean range False .. False;
private
subtype Void_Ptr is System.Address;
type Wayland_Array is record
Size : Interfaces.C.size_t;
Alloc : Interfaces.C.size_t;
Data : Void_Ptr;
end record
with Convention => C;
end Wayland;
|
-- Ada regular expression library
-- (c) Kristian Klomsten Skordal 2020 <kristian.skordal@wafflemail.net>
-- Report bugs and issues on <https://github.com/skordal/ada-regex>
with Ada.Text_IO;
package body Regex.Debug is
procedure Print_Syntax_Tree (Root : in Regex.Syntax_Trees.Syntax_Tree_Node_Access) is
use Ada.Text_IO;
use Regex.Syntax_Trees;
-- Helper functions:
procedure Print_Set (Set : in Syntax_Tree_Node_Sets.Sorted_Set);
procedure Print_Node_Recursively (Node : in Syntax_Tree_Node_Access; Indentation : Natural);
procedure Print_Set (Set : in Syntax_Tree_Node_Sets.Sorted_Set) is
begin
Put ("{ ");
for Element of Set loop
Put (Natural'Image (Element.Id) & ", ");
end loop;
Put ("}");
end Print_Set;
procedure Print_Node_Recursively (Node : in Syntax_Tree_Node_Access; Indentation : Natural) is
begin
for I in 0 .. Indentation loop
Put (' ');
end loop;
Put ("node " & Natural'Image (Node.Id) & ": ");
case Node.Node_Type is
when Acceptance =>
Put_Line ("accept");
when Single_Character =>
Put ("character " & Character'Image (Node.Char)
& ", nullable = " & Boolean'Image (Nullable (Node))
& ", firstpos = ");
Print_Set (Firstpos (Node));
Put (", lastpos = ");
Print_Set (Lastpos (Node));
Put (", followpos = ");
Print_Set (Node.Followpos);
New_Line;
when Any_Character =>
Put ("any character, nullable = " & Boolean'Image (Nullable (Node))
& ", firstpos = ");
Print_Set (Firstpos (Node));
Put (", lastpos = ");
Print_Set (Lastpos (Node));
Put (", followpos = ");
Print_Set (Node.Followpos);
New_Line;
when Empty_Node =>
Put ("empty node, ε, nullable = " & Boolean'Image (Nullable (Node))
& ", firstpos = ");
Print_Set (Firstpos (Node));
Put (", lastpos = ");
Print_Set (Lastpos (Node));
Put (", followpos = ");
Print_Set (Node.Followpos);
New_Line;
when Alternation =>
Put ("alternation '|', nullable = " & Boolean'Image (Nullable (Node))
& ", firstpos = ");
Print_Set (Firstpos (Node));
Put (", lastpos = ");
Print_Set (Lastpos (Node));
Put (", followpos = ");
Print_Set (Node.Followpos);
New_Line;
Print_Node_Recursively (Node.Left_Child, Indentation + 3);
Print_Node_Recursively (Node.Right_Child, Indentation + 3);
when Concatenation =>
Put ("concatenation, nullable = " & Boolean'Image (Nullable (Node))
& ", firstpos = ");
Print_Set (Firstpos (Node));
Put (", lastpos = ");
Print_Set (Lastpos (Node));
Put (", followpos = ");
Print_Set (Node.Followpos);
New_Line;
Print_Node_Recursively (Node.Left_Child, Indentation + 3);
Print_Node_Recursively (Node.Right_Child, Indentation + 3);
when Kleene_Star =>
Put ("kleene star '*', nullable = " & Boolean'Image (Nullable (Node))
& ", firstpos = ");
Print_Set (Firstpos (Node));
Put (", lastpos = ");
Print_Set (Lastpos (Node));
Put (", followpos = ");
Print_Set (Node.Followpos);
New_Line;
Print_Node_Recursively (Node.Left_Child, Indentation + 3);
end case;
end Print_Node_Recursively;
begin
Put_Line ("Parse tree:");
if Root = null then
Put_Line (" null");
else
Print_Node_Recursively (Root, 3);
end if;
end Print_Syntax_Tree;
procedure Print_State_Machine (States : in Regex.State_Machines.State_Machine_State_Vectors.Vector) is
begin
for State of States loop
Print_State (State.all);
end loop;
end Print_State_Machine;
procedure Print_State (State : in Regex.State_Machines.State_Machine_State) is
use Ada.Text_IO;
use Regex.State_Machines;
begin
Put ("State machine node for {");
for Node of State.Syntax_Tree_Nodes loop
Put (Natural'Image (Node.Id) & ", ");
end loop;
Put_Line ("} (accepting = " & Boolean'Image (State.Accepting) & ")");
for Transition of State.Transitions loop
case Transition.Transition_On.Symbol_Type is
when Single_Character =>
Put (" transition on " & Character'Image (Transition.Transition_On.Char) & " to {");
for Node of Transition.Target_State.Syntax_Tree_Nodes loop
Put (Natural'Image (Node.Id) & ", ");
end loop;
Put_Line ("}");
when Any_Character =>
Put (" transition on any character to {");
for Node of Transition.Target_State.Syntax_Tree_Nodes loop
Put (Natural'Image (Node.Id) & ", ");
end loop;
Put_Line ("}");
end case;
end loop;
end Print_State;
end Regex.Debug;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS --
-- --
-- SYSTEM.TASKING.PROTECTED_OBJECTS.OPERATIONS --
-- --
-- B o d y --
-- --
-- Copyright (C) 1998-2021, Free Software Foundation, Inc. --
-- --
-- GNARL is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- --
-- --
-- --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNARL was developed by the GNARL team at Florida State University. --
-- Extensive contributions were provided by Ada Core Technologies, Inc. --
-- --
------------------------------------------------------------------------------
-- This package contains all extended primitives related to Protected_Objects
-- with entries.
-- The handling of protected objects with no entries is done in
-- System.Tasking.Protected_Objects, the simple routines for protected
-- objects with entries in System.Tasking.Protected_Objects.Entries.
-- The split between Entries and Operations is needed to break circular
-- dependencies inside the run time.
-- This package contains all primitives related to Protected_Objects.
-- Note: the compiler generates direct calls to this interface, via Rtsfind.
with System.Task_Primitives.Operations;
with System.Tasking.Queuing;
with System.Restrictions;
with System.Multiprocessors;
with System.Tasking.Protected_Objects.Multiprocessors;
package body System.Tasking.Protected_Objects.Operations is
package STPO renames System.Task_Primitives.Operations;
package STPOM renames System.Tasking.Protected_Objects.Multiprocessors;
use Ada.Exceptions;
use Entries;
use System.Multiprocessors;
use System.Restrictions;
use System.Restrictions.Rident;
Multiprocessor : constant Boolean := CPU'Range_Length /= 1;
procedure PO_Do_Or_Queue
(Self_ID : Task_Id;
Object : Entries.Protection_Entries_Access;
Entry_Call : Entry_Call_Link;
Queued : out Boolean);
-- This procedure either executes or queues an entry call, depending
-- on the status of the corresponding barrier. It assumes that abort
-- is deferred and that the specified object is locked.
procedure PO_Service_Entries
(Self_ID : Task_Id;
Object : Entries.Protection_Entries_Access);
-- Service all entry queues of the specified object, executing the
-- corresponding bodies of any queued entry calls that are waiting
-- on True barriers. This is used when the state of a protected
-- object may have changed, in particular after the execution of
-- the statement sequence of a protected procedure.
--
-- Note that servicing an entry may change the value of one or more
-- barriers, so this routine keeps checking barriers until all of
-- them are closed.
--
-- This must be called with the corresponding object locked. This
-- lock will be released at the end of the call.
-------------------------
-- Complete_Entry_Body --
-------------------------
procedure Complete_Entry_Body (Object : Protection_Entries_Access) is
begin
Exceptional_Complete_Entry_Body (Object, Ada.Exceptions.Null_Id);
end Complete_Entry_Body;
-------------------------------------
-- Exceptional_Complete_Entry_Body --
-------------------------------------
procedure Exceptional_Complete_Entry_Body
(Object : Protection_Entries_Access;
Ex : Ada.Exceptions.Exception_Id)
is
procedure Transfer_Occurrence
(Target : Ada.Exceptions.Exception_Occurrence_Access;
Source : Ada.Exceptions.Exception_Occurrence);
pragma Import (C, Transfer_Occurrence, "__gnat_transfer_occurrence");
-- Import a private declaration from Ada.Exceptions
Entry_Call : constant Entry_Call_Link := Object.Call_In_Progress;
Self_Id : Task_Id;
begin
pragma Assert (Entry_Call /= null);
Entry_Call.Exception_To_Raise := Ex;
if Ex /= Ada.Exceptions.Null_Id then
-- An exception was raised and abort was deferred, so adjust
-- before propagating, otherwise the task will stay with deferral
-- enabled for its remaining life.
Self_Id := STPO.Self;
Transfer_Occurrence
(Entry_Call.Self.Common.Compiler_Data.Current_Excep'Access,
Self_Id.Common.Compiler_Data.Current_Excep);
end if;
end Exceptional_Complete_Entry_Body;
--------------------
-- PO_Do_Or_Queue --
--------------------
procedure PO_Do_Or_Queue
(Self_ID : Task_Id;
Object : Protection_Entries_Access;
Entry_Call : Entry_Call_Link;
Queued : out Boolean)
is
pragma Unreferenced (Self_ID);
E : constant Protected_Entry_Index :=
Protected_Entry_Index (Entry_Call.E);
Index : constant Protected_Entry_Index :=
Object.Find_Body_Index (Object.Compiler_Info, E);
Barrier_Value : Boolean;
Queue_Length : Natural;
begin
Queued := False;
-- Evaluate barrier. Due to the Pure_Barrier restriction, this cannot
-- raise exception.
Barrier_Value :=
Object.Entry_Bodies (Index).Barrier (Object.Compiler_Info, E);
if Barrier_Value then
Object.Call_In_Progress := Entry_Call;
-- Execute the entry. Exceptions cannot propagate from the entry, as
-- they must be handled by Exceptional_Complete_Entry_Body.
Object.Entry_Bodies (Index).Action
(Object.Compiler_Info, Entry_Call.Uninterpreted_Data, E);
-- Body of current entry served call to completion
Object.Call_In_Progress := null;
else
if Run_Time_Restrictions.Set (Max_Entry_Queue_Length)
or else Object.Entry_Queue_Maxes /= null
then
-- Need to check the queue length. Computing the length is an
-- unusual case and is slow (need to walk the queue).
Queue_Length := Queuing.Count_Waiting (Object.Entry_Queues (E));
if (Run_Time_Restrictions.Set (Max_Entry_Queue_Length)
and then Queue_Length >=
Run_Time_Restrictions.Value (Max_Entry_Queue_Length))
or else
(Object.Entry_Queue_Maxes /= null
and then Object.Entry_Queue_Maxes (Index) /= 0
and then Queue_Length >= Object.Entry_Queue_Maxes (Index))
then
-- This violates the Max_Entry_Queue_Length restriction or the
-- Max_Queue_Length bound, raise Program_Error. The entry call
-- has completed.
Entry_Call.Exception_To_Raise := Program_Error'Identity;
return;
end if;
end if;
Queuing.Enqueue (Object.Entry_Queues (E), Entry_Call);
Queued := True;
end if;
end PO_Do_Or_Queue;
------------------------
-- PO_Service_Entries --
------------------------
procedure PO_Service_Entries
(Self_ID : Task_Id;
Object : Entries.Protection_Entries_Access)
is
E : Protected_Entry_Index;
Caller : Task_Id;
Entry_Call : Entry_Call_Link;
begin
loop
Queuing.Select_Protected_Entry_Call (Self_ID, Object, Entry_Call);
exit when Entry_Call = null;
E := Protected_Entry_Index (Entry_Call.E);
Object.Call_In_Progress := Entry_Call;
-- Execute the entry
Object.Entry_Bodies
(Object.Find_Body_Index (Object.Compiler_Info, E)).Action
(Object.Compiler_Info, Entry_Call.Uninterpreted_Data, E);
-- Signal the entry caller that the entry is completed (it it needs
-- to wake up and continue execution).
Caller := Entry_Call.Self;
if not Multiprocessor
or else Caller.Common.Base_CPU = STPO.Self.Common.Base_CPU
then
-- Entry caller and servicing tasks are on the same CPU.
-- We are allowed to directly wake up the task.
STPO.Wakeup (Caller, Entry_Caller_Sleep);
else
-- The entry caller is on a different CPU.
STPOM.Served (Entry_Call);
end if;
end loop;
-- End of exclusive access
Unlock_Entries (Object);
end PO_Service_Entries;
---------------------
-- Protected_Count --
---------------------
function Protected_Count
(Object : Protection_Entries;
E : Protected_Entry_Index) return Natural
is
begin
return Queuing.Count_Waiting (Object.Entry_Queues (E));
end Protected_Count;
--------------------------
-- Protected_Entry_Call --
--------------------------
-- Compiler interface only (do not call from within the RTS)
-- declare
-- X : protected_entry_index := 1;
-- B2b : communication_block;
-- communication_blockIP (B2b);
-- begin
-- protected_entry_call (R5b._object'unchecked_access, X,
-- null_address, simple_call, B2b);
-- end;
procedure Protected_Entry_Call
(Object : Protection_Entries_Access;
E : Protected_Entry_Index;
Uninterpreted_Data : System.Address;
Mode : Call_Modes;
Block : out Communication_Block)
is
pragma Unreferenced (Mode);
procedure Internal_Raise (X : Ada.Exceptions.Exception_Id);
pragma Import (C, Internal_Raise, "__gnat_raise_with_msg");
Self_ID : constant Task_Id := STPO.Self;
Entry_Call : Entry_Call_Link;
Queued : Boolean;
begin
-- For this run time, pragma Detect_Blocking is always active, so we
-- must raise Program_Error if this potentially blocking operation is
-- called from a protected action.
if Self_ID.Common.Protected_Action_Nesting > 0 then
raise Program_Error with "potentially blocking operation";
end if;
-- Exclusive access to the protected object
Lock_Entries (Object);
Block.Self := Self_ID;
-- Initialize Entry_Call. No need to clear Exception_To_Raise, as it is
-- cleared at the end of the entry by Complete_Entry_Body.
Entry_Call := Self_ID.Entry_Call'Access;
Entry_Call.Next := null;
Entry_Call.E := Entry_Index (E);
Entry_Call.Uninterpreted_Data := Uninterpreted_Data;
-- Execute the entry if the barrier is open, or enqueue the call until
-- the barrier opens.
PO_Do_Or_Queue (Self_ID, Object, Entry_Call, Queued);
-- Check whether there are entries pending (barriers may have changed).
-- Queuing entries can potentially open barriers (if they rely on queue
-- count). This might complete multiple entry calls, including the one
-- that was just queued.
-- The protected object lock will be released by the end of the call.
PO_Service_Entries (Self_ID, Object);
-- If the entry call was queued the task sleeps until it is woken by the
-- task servicing its entry.
if Queued then
-- Suspend until entry call has been completed. Note that it is
-- possible that the entry call was completed by the
-- PO_Service_Entries call above. In that case, the flag
-- Wakeup_Signaled is True and the call to Sleep below will return
-- immediately. However we cannot skip the call to Sleep, otherwise
-- Wakeup_Signaled is not cleared.
Self_ID.Common.State := Entry_Caller_Sleep;
STPO.Sleep (Self_ID, Entry_Caller_Sleep);
Self_ID.Common.State := Runnable;
end if;
-- Check if an exception has to be propagated from the entry to the
-- caller.
if Entry_Call.Exception_To_Raise /= Ada.Exceptions.Null_Id then
-- If this is the case, propagate it. A raise statement cannot be
-- used, as the call stack must not be modified.
Internal_Raise (Entry_Call.Exception_To_Raise);
end if;
end Protected_Entry_Call;
----------------------------
-- Protected_Entry_Caller --
----------------------------
function Protected_Entry_Caller
(Object : Protection_Entries) return Task_Id is
begin
return Object.Call_In_Progress.Self;
end Protected_Entry_Caller;
---------------------
-- Service_Entries --
---------------------
procedure Service_Entries (Object : Protection_Entries_Access) is
Self_ID : constant Task_Id := STPO.Self;
begin
PO_Service_Entries (Self_ID, Object);
end Service_Entries;
end System.Tasking.Protected_Objects.Operations;
|
with RASCAL.Memory; use RASCAL.Memory;
with RASCAL.OS; use RASCAL.OS;
with RASCAL.Utility; use RASCAL.Utility;
with RASCAL.FileExternal; use RASCAL.FileExternal;
with RASCAL.ToolboxMenu; use RASCAL.ToolboxMenu;
with RASCAL.Toolbox; use RASCAL.Toolbox;
with RASCAL.Bugz; use RASCAL.Bugz;
with RASCAL.WimpTask; use RASCAL.WimpTask;
with AcronymList; use AcronymList;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Interfaces.C; use Interfaces.C;
with Main; use Main;
with Ada.Exceptions;
with Ada.Characters.Handling;
with Reporter;
package body Controller_DataMenu is
--
package Memory renames RASCAL.Memory;
package OS renames RASCAL.OS;
package Utility renames RASCAL.Utility;
package FileExternal renames RASCAL.FileExternal;
package ToolboxMenu renames RASCAL.ToolboxMenu;
package Toolbox renames RASCAL.Toolbox;
package Bugz renames RASCAL.Bugz;
package WimpTask renames RASCAL.WimpTask;
--
procedure Handle (The : in TEL_DataMenuOpen_Type) is
Object : Object_ID := Get_Self_Id(Main_Task);
Dir_List : Directory_Type := Get_Directory_List(Choices_Write & ".Data");
begin
-- Delete old entries
if Data_Menu_Entries > 0 then
ToolboxMenu.Remove_Entries(Object,Data_Menu_Entries,1);
end if;
-- Insert new entries
for i in Dir_List'Range loop
ToolboxMenu.Add_Last_Entry(Object,S(Dir_List(i)),Component_ID(i),Click_Event => 16#35#);
end loop;
Data_Menu_Entries := Dir_List'Last;
exception
when e: others => Report_Error("OPENDATAMENU",Ada.Exceptions.Exception_Information (e));
end Handle;
--
procedure Handle (The : in TEL_DataEntrySelected_Type) is
Object : Object_ID := Get_Self_Id(Main_Task);
Component : Component_ID := Get_Self_Component(Main_Task);
FileName : String := ToolboxMenu.Get_Entry_Text(Object,Component);
begin
Call_OS_CLI("Filer_Run " & Choices_Write & ".Data." & FileName);
exception
when e: others => Report_Error("VIEWDATAENTRY",Ada.Exceptions.Exception_Information (e));
end Handle;
--
procedure Handle (The : in TEL_ViewDataDir_Type) is
begin
Call_OS_CLI ("Filer_OpenDir " & Choices_Write & ".Data");
exception
when e: others => Report_Error("VIEWDATA",Ada.Exceptions.Exception_Information (e));
end Handle;
--
end Controller_DataMenu;
|
package Generic_Subprogram_Calls is
generic
type TP is private;
procedure G1(T : TP);
generic
with procedure PP;
procedure G2;
generic
type TP is private;
package G3 is
procedure P(T : TP);
end G3;
generic
with procedure PP;
package G4 is
procedure P;
end G4;
generic
type TP is private;
function G5(T : TP) return TP;
generic
type TP is private;
T : TP;
function G6 return TP;
procedure Test;
generic
type T is private;
with function "="(L, R : T) return Boolean is <>;
function Equal_Generic(L, R : T) return Boolean;
generic
type T is private;
with function Foo(L, R : T) return Boolean is <>;
function Foo_Generic(L, R : T) return Boolean;
generic
type T is private;
with function "="(L, R : T) return Boolean is <>;
package Equal_Generic_Package is
end Equal_Generic_Package;
generic
type T is private;
with function Foo(L, R : T) return Boolean is <>;
package Foo_Generic_Package is
end Foo_Generic_Package;
end Generic_Subprogram_Calls;
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT INTERFACE COMPONENTS --
-- --
-- A S I S . C O M P I L A T I O N _ U N I T S --
-- --
-- S p e c --
-- --
-- Copyright (C) 2006-2010, Free Software Foundation, Inc. --
-- --
-- This specification is adapted from the Ada Semantic Interface --
-- Specification Standard (ISO/IEC 15291) for use with GNAT. In accordance --
-- with the copyright of that document, you can freely copy and modify this --
-- specification, provided that if you redistribute a modified version, any --
-- changes that you have made are clearly indicated. --
-- --
-- This specification also contains suggestions and discussion items --
-- related to revising the ASIS Standard according to the changes proposed --
-- for the new revision of the Ada standard. The copyright notice above, --
-- and the license provisions that follow apply solely to these suggestions --
-- and discussion items that are separated by the corresponding comment --
-- sentinels --
-- --
-- ASIS-for-GNAT is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 2, or (at your option) any later --
-- version. ASIS-for-GNAT is distributed in the hope that it will be use- --
-- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- --
-- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General --
-- Public License for more details. You should have received a copy of the --
-- GNU General Public License distributed with ASIS-for-GNAT; see file --
-- COPYING. If not, write to the Free Software Foundation, 51 Franklin --
-- Street, Fifth Floor, Boston, MA 02110-1301, USA. --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the --
-- Software Engineering Laboratory of the Swiss Federal Institute of --
-- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the --
-- Scientific Research Computer Center of Moscow State University (SRCC --
-- MSU), Russia, with funding partially provided by grants from the Swiss --
-- National Science Foundation and the Swiss Academy of Engineering --
-- Sciences. ASIS-for-GNAT is now maintained by AdaCore --
-- (http://www.adacore.com). --
-- --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- 10 package Asis.Compilation_Units
-- Suggestions related to changing this specification to accept new Ada
-- features as defined in incoming revision of the Ada Standard (ISO 8652)
-- are marked by following comment sentinels:
--
-- --|A2005 start
-- ... the suggestion goes here ...
-- --|A2005 end
--
-- and the discussion items are marked by the comment sentinels of the form:
--
-- --|D2005 start
-- ... the discussion item goes here ...
-- --|D2005 end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
with Asis.Ada_Environments.Containers;
package Asis.Compilation_Units is
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Asis.Compilation_Units encapsulates a set of queries that implement the
-- ASIS Compilation_Unit abstraction.
--
-- More than one compilation unit may be manipulated at one time. (The exact
-- number is subject to implementation specific limitations.)
--
-- A specific Compilation_Unit value is valid (usable) for as long as the ASIS
-- Context variable, used to create it, remains open. Once an ASIS Context is
-- closed, all associated Compilation_Unit values become invalid. It is
-- erroneous to use an invalid Compilation_Unit value.
--
------------------------------------------------------------------------------
-- 10.1 function Unit_Kind
------------------------------------------------------------------------------
function Unit_Kind
(Compilation_Unit : Asis.Compilation_Unit)
return Asis.Unit_Kinds;
------------------------------------------------------------------------------
-- Compilation_Unit - Specifies the compilation unit to query
--
-- Returns the Unit_Kinds value of the compilation unit.
-- Returns Not_A_Unit for a Nil_Compilation_Unit.
--
-- All Unit_Kinds are expected.
--
-- Returns An_Unknown_Unit for any compilation unit that exists, but that
-- does not have semantic element information available through ASIS.
--
-- Returns a nonexistent kind for units that have name-only entries in the
-- environment Context. Such entries may exist for names because:
--
-- - They represent an illegal compilation unit added to the environment.
--
-- - They are referenced by some existing unit, but the program text for the
-- referenced unit has never been supplied, compiled, or otherwise
-- inserted into the environment.
--
-- - They represent a separate subunit that has never been supplied,
-- compiled, or otherwise inserted into the environment.
--
-- - The unit may have existed at one time but the semantic information is no
-- longer available. It may be inconsistent, have been removed by some
-- user or Ada environment operations, or simply have been lost as the
-- result of some sort of failure.
--
------------------------------------------------------------------------------
-- 10.2 function Unit_Class
------------------------------------------------------------------------------
function Unit_Class
(Compilation_Unit : Asis.Compilation_Unit)
return Asis.Unit_Classes;
------------------------------------------------------------------------------
-- Compilation_Unit - Specifies the compilation unit to query
--
-- Returns the Unit_Classes value of the compilation unit.
-- Returns Not_A_Class for a Nil_Compilation_Unit.
--
-- All Unit_Kinds are expected.
--
------------------------------------------------------------------------------
-- 10.3 function Unit_Origin
------------------------------------------------------------------------------
function Unit_Origin
(Compilation_Unit : Asis.Compilation_Unit)
return Asis.Unit_Origins;
------------------------------------------------------------------------------
-- Compilation_Unit - Specifies the compilation unit to query
--
-- Returns the Unit_Origins value of the unit.
-- Returns Not_An_Origin for a compilation_unit whose Unit_Kind is
-- Not_A_Unit, An_Unknown_Unit, A_Nonexistent_Declaration, or
-- A_Nonexistent_Body.
--
-- All Unit_Kinds are expected.
--
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- 10.4 function Enclosing_Context
------------------------------------------------------------------------------
function Enclosing_Context
(Compilation_Unit : Asis.Compilation_Unit)
return Asis.Context;
------------------------------------------------------------------------------
-- Compilation_Unit - Specifies the unit whose Context is required
--
-- Returns the Context containing the compilation unit.
--
-- Compilation units always remember the ASIS Context and Container from
-- which they were obtained.
--
-- Because Context is limited private, this function is only intended to be
-- used to supply a Context parameter for other queries. This conveniently
-- eliminates the need to make the original Context visible at the place of
-- each call where a Context parameter is required.
--
-- Two Compilation_Unit values, that represent the same physical compilation
-- units (same Ada implementor Context implementation unit value) will test as
-- Is_Equal, but not Is_Identical, if they were obtained from different open
-- ASIS Context variables.
--
-- Raises ASIS_Inappropriate_Compilation_Unit if the unit is a
-- Nil_Compilation_Unit.
--
------------------------------------------------------------------------------
-- 10.5 function Enclosing_Container
------------------------------------------------------------------------------
function Enclosing_Container
(Compilation_Unit : Asis.Compilation_Unit)
return Asis.Ada_Environments.Containers.Container;
------------------------------------------------------------------------------
-- Compilation_Unit - Specifies the unit whose Container is required
--
-- Returns the Container of the Context containing the compilation unit.
-- Compilation units always remember the ASIS Context and Container from
-- which they were obtained.
--
-- Raises ASIS_Inappropriate_Compilation_Unit if the unit is a
-- Nil_Compilation_Unit.
--
------------------------------------------------------------------------------
-- 10.6 function Library_Unit_Declaration
------------------------------------------------------------------------------
function Library_Unit_Declaration
(Name : Wide_String;
The_Context : Asis.Context)
return Asis.Compilation_Unit;
------------------------------------------------------------------------------
-- Name - Specifies the defining program unit name
-- The_Context - Specifies a program Context environment
--
-- Returns the library_unit_declaration or library_unit_renaming_declaration
-- with the name, contained in The_Context.
--
-- This query will never return a unit with A_Configuration_Compilation or
-- a nonexistent unit kind. It will never return a unit with A_Procedure_Body
-- or A_Function_Body unit kind even though the unit is interpreted as both
-- the declaration and body of a library procedure or library function.
-- (Reference Manual 10.1.4(4).
--
-- A Nil_Compilation_Unit is returned if no such declaration exists.
--
-- Any non-Nil result will have an Enclosing_Context value that Is_Identical
-- to the Context. Never returns a unit with a nonexistent unit kind.
--
------------------------------------------------------------------------------
-- 10.7 function Compilation_Unit_Body
------------------------------------------------------------------------------
function Compilation_Unit_Body
(Name : Wide_String;
The_Context : Asis.Context)
return Asis.Compilation_Unit;
------------------------------------------------------------------------------
-- Name - Specifies the defining_program_unit_name
-- The_Context - Specifies a program Context environment
--
-- Returns the library_unit_body or subunit with the name, contained
-- in the library.
--
-- A Nil_Compilation_Unit is returned if no such body exists.
--
-- Any non-Nil result will have an Enclosing_Context value that Is_Identical
-- to The_Context. Never returns a unit with a nonexistent unit kind.
--
------------------------------------------------------------------------------
-- 10.8 function Library_Unit_Declarations
------------------------------------------------------------------------------
function Library_Unit_Declarations
(The_Context : Asis.Context)
return Asis.Compilation_Unit_List;
------------------------------------------------------------------------------
-- The_Context - Specifies a program Context environment
--
-- Returns a list of all library_unit_declaration and
-- library_unit_renaming_declaration elements contained in The_Context.
-- Individual units will appear only once in an order that is not defined.
--
-- A Nil_Compilation_Unit_List is returned if there are no declarations of
-- library units within The_Context.
--
-- This query will never return a unit with A_Configuration_Compilation or
-- a nonexistent unit kind. It will never return a unit with A_Procedure_Body
-- or A_Function_Body unit kind even though the unit is interpreted as both
-- the declaration and body of a library procedure or library function.
-- (Reference Manual 10.1.4(4).
--
-- All units in the result will have an Enclosing_Context value that
-- Is_Identical to The_Context.
--
------------------------------------------------------------------------------
-- 10.9 function Compilation_Unit_Bodies
------------------------------------------------------------------------------
function Compilation_Unit_Bodies
(The_Context : Asis.Context)
return Asis.Compilation_Unit_List;
------------------------------------------------------------------------------
-- The_Context - Specifies a program Context environment
--
-- Returns a list of all library_unit_body and subunit elements contained in
-- The_Context. Individual units will appear only once in an order that is not
-- defined.
--
-- A Nil_Compilation_Unit_List is returned if there are no bodies within
-- The_Context.
--
-- This query will never return a unit with A_Configuration_Compilation or
-- a nonexistent unit kind.
--
-- All units in the result will have an Enclosing_Context value that
-- Is_Identical to The_Context.
--
------------------------------------------------------------------------------
-- 10.10 function Compilation_Units
------------------------------------------------------------------------------
function Compilation_Units
(The_Context : Asis.Context)
return Asis.Compilation_Unit_List;
------------------------------------------------------------------------------
-- The_Context - Specifies a program Context environment
--
-- Returns a list of all compilation units contained in The_Context.
-- Individual units will appear only once in an order that is not defined.
--
-- A Nil_Compilation_Unit_List is returned if there are no units within
-- The_Context.
--
-- This query will never return a unit with A_Configuration_Compilation or
-- a nonexistent unit kind.
--
-- All units in the result will have an Enclosing_Context value that
-- Is_Identical to The_Context.
--
------------------------------------------------------------------------------
-- 10.11 function Corresponding_Children
------------------------------------------------------------------------------
function Corresponding_Children
(Library_Unit : Asis.Compilation_Unit)
return Asis.Compilation_Unit_List;
function Corresponding_Children
(Library_Unit : Asis.Compilation_Unit;
The_Context : Asis.Context)
return Asis.Compilation_Unit_List;
------------------------------------------------------------------------------
-- Library_Unit - Specifies the library unit whose children are desired
-- The_Context - Specifies a program Context environment
--
-- Returns a list of the child units for the given parent library unit.
--
-- Both the declaration and body (if any) of each child unit are returned.
-- Descendants beyond immediate children (i.e., children of children) are not
-- returned by this query.
--
-- Use the compilation unit relationship queries
-- with a Relation_Kinds of Descendants to create a list of children, children
-- of children, and so on.
--
-- Returns a Nil_Compilation_Unit_List for all library unit arguments that
-- do not have any child units contained in The_Context.
--
-- These two function calls will always produce identical results:
--
-- Units := Corresponding_Children ( Unit );
-- Units := Corresponding_Children ( Unit, Enclosing_Context ( Unit ));
--
-- Any non-Nil result will have an Enclosing_Context value that Is_Identical
-- to The_Context.
--
-- The Enclosing_Context for any non-Nil result will always be The_Context,
-- regardless of the Enclosing_Context value for the Library_Unit argument.
-- This query is one means of obtaining (Is_Equal) child units
-- from separate ASIS Context values whose underlying implementations
-- overlap.
--
-- Appropriate Unit_Kinds:
-- A_Package
-- A_Generic_Package
-- A_Package_Instance
--
-- Returns Unit_Kinds:
-- A_Procedure
-- A_Function
-- A_Package
-- A_Generic_Procedure
-- A_Generic_Function
-- A_Generic_Package
-- A_Procedure_Instance
-- A_Function_Instance
-- A_Package_Instance
-- A_Procedure_Renaming
-- A_Function_Renaming
-- A_Package_Renaming
-- A_Generic_Procedure_Renaming
-- A_Generic_Function_Renaming
-- A_Generic_Package_Renaming
-- A_Procedure_Body
-- A_Function_Body
-- A_Package_Body
-- An_Unknown_Unit
--
-- If the declaration of a child is inconsistent with the argument of the
-- query, neither the declaration nor the body is returned. If the
-- declaration of a child is consistent with the argument, but the body
-- is not, the declaration is returned, and for the body, the result of
-- the Corresponding_Body query applied to the declaration is returned.
--
------------------------------------------------------------------------------
-- 10.12 function Corresponding_Parent_Declaration
------------------------------------------------------------------------------
function Corresponding_Parent_Declaration
(Library_Unit : Asis.Compilation_Unit)
return Asis.Compilation_Unit;
function Corresponding_Parent_Declaration
(Library_Unit : Asis.Compilation_Unit;
The_Context : Asis.Context)
return Asis.Compilation_Unit;
------------------------------------------------------------------------------
-- Library_Unit - Specifies the unit whose parent is desired
-- The_Context - Specifies a program Context environment
--
-- Returns the parent unit of the given library unit.
--
-- Returns a Nil_Compilation_Unit if the Library_Unit argument represents
-- package Standard. Root Library_Unit arguments return the package Standard.
--
-- Returns A_Nonexistent_Declaration when the Library_Unit has a
-- parent_unit_name denoted in the defining_program_unit_name but the parent
-- unit is not contained in The_Context.
--
-- These two function calls will always produce identical results:
--
-- Unit := Corresponding_Parent_Declaration (Unit);
-- Unit := Corresponding_Parent_Declaration (Unit, Enclosing_Context (Unit));
--
-- Any non-Nil result will have an Enclosing_Context value that Is_Identical
-- to The_Context.
--
-- The Enclosing_Context for any non-Nil result will always be The_Context,
-- regardless of the Enclosing_Context value for the Library_Unit
-- argument. This query is one means of obtaining (Is_Equal) parent units
-- from separate ASIS Context values whose underlying implementations
-- overlap.
--
-- Appropriate Unit_Kinds:
-- A_Procedure
-- A_Function
-- A_Package
-- A_Generic_Procedure
-- A_Generic_Function
-- A_Generic_Package
-- A_Procedure_Instance
-- A_Function_Instance
-- A_Package_Instance
-- A_Procedure_Renaming
-- A_Function_Renaming
-- A_Package_Renaming
-- A_Generic_Procedure_Renaming
-- A_Generic_Function_Renaming
-- A_Generic_Package_Renaming
-- A_Procedure_Body
-- A_Function_Body
-- A_Package_Body
--
-- Returns Unit_Kinds:
-- Not_A_Unit
-- A_Package
-- A_Generic_Package
-- A_Package_Instance
-- A_Nonexistent_Declaration
-- An_Unknown_Unit
--
-- If a parent is inconsistent with a child passed as the argument,
-- A_Nonexistent_Declaration shall be returned.
--
------------------------------------------------------------------------------
-- 10.13 function Corresponding_Declaration
------------------------------------------------------------------------------
function Corresponding_Declaration
(Library_Item : Asis.Compilation_Unit)
return Asis.Compilation_Unit;
function Corresponding_Declaration
(Library_Item : Asis.Compilation_Unit;
The_Context : Asis.Context)
return Asis.Compilation_Unit;
------------------------------------------------------------------------------
-- Library_Item - Specifies the library_item whose declaration is desired
-- The_Context - Specifies a program Context environment
--
-- Returns the corresponding library_unit_declaration, if any, for the
-- library_unit_body. The corresponding library unit is the unit upon which
-- the library_unit_body depends semantically.
--
-- Returns a unit that Is_Equal to the argument if:
--
-- - the argument is a library_unit_declaration,
-- a library_unit_renaming_declaration, or a subunit.
--
-- - the argument is A_Nonexistent_Declaration or A_Nonexistent_Body.
--
-- Returns a Nil_Compilation_Unit for library_unit_body arguments that do
-- not have a corresponding library unit contained in The_Context.
--
-- All Unit_Kinds are appropriate except Not_A_Unit.
--
-- Appropriate Unit_Kinds:
-- A_Procedure_Body
-- A_Function_Body
-- A_Package_Body
-- An_Unknown_Unit -- See Implementation Permissions
--
-- Appropriate Unit_Kinds returning the argument Library_Item:
-- A_Procedure
-- A_Function
-- A_Package
-- A_Generic_Procedure
-- A_Generic_Function
-- A_Generic_Package
-- A_Procedure_Instance
-- A_Function_Instance
-- A_Package_Instance
-- A_Procedure_Renaming
-- A_Function_Renaming
-- A_Package_Renaming
-- A_Generic_Procedure_Renaming
-- A_Generic_Function_Renaming
-- A_Generic_Package_Renaming
-- A_Procedure_Body_Subunit
-- A_Function_Body_Subunit
-- A_Package_Body_Subunit
-- A_Task_Body_Subunit
-- A_Protected_Body_Subunit
-- A_Nonexistent_Declaration
-- A_Nonexistent_Body
--
-- Returns all Unit Kinds.
--
-- If the declaration of an argument Element is inconsistent with the
-- argument, A_Nonexistent_Declaration shall be returned. (For a unit
-- A_Procedure_Body or A_Function_Body kind, the solution may be in any
-- case, to return Nil_Compilation_Unit if the unit is of
-- A_Public_Declaration_And_Body kind.)
--
-- --|IR Implementation Requirements:
-- --|IR
-- --|IR Any non-Nil result will have an Enclosing_Context value that
-- --|IR Is_Identical to The_Context.
-- --|IR
-- --|IR These two function calls will always produce identical results:
-- --|IR
-- --|IR Unit := Corresponding_Declaration (Unit);
-- --|IR Unit := Corresponding_Declaration (Unit, Enclosing_Context (Unit));
-- --|IR
-- --|IR The Enclosing_Context for any non-Nil result will always be
-- --|IR The_Context, regardless of the Enclosing_Context value for the
-- --|IR Library_Item argument. This query is one means of obtaining
-- --|IR corresponding (Is_Equal) units from separate ASIS Context values
-- --|IR whose underlying implementations overlap.
-- --|IR
-- --|IP Implementation Permissions:
-- --|IP
-- --|IP The handling of An_Unknown_Unit is implementation specific. The
-- --|IP expected use for An_Unknown_Unit is to hide proprietary
-- --|IP implementation details contained within unit bodies. In these cases,
-- --|IP it should be possible to obtain an appropriate
-- --|IP library_unit_declaration when starting with An_Unknown_Unit. Some
-- --|IP implementors may choose to simply return the An_Unknown_Unit argument
-- --|IP in all cases.
------------------------------------------------------------------------------
-- 10.14 function Corresponding_Body
------------------------------------------------------------------------------
function Corresponding_Body
(Library_Item : Asis.Compilation_Unit)
return Asis.Compilation_Unit;
function Corresponding_Body
(Library_Item : Asis.Compilation_Unit;
The_Context : Asis.Context)
return Asis.Compilation_Unit;
------------------------------------------------------------------------------
-- Library_Item - Specifies the library_item whose body is desired
-- The_Context - Specifies a program Context environment
--
-- Returns the corresponding library_unit_body, if any, for the
-- library_unit_declaration. The corresponding library_unit_body is the unit
-- that depends semantically on the library_unit_declaration.
--
-- Returns a unit that Is_Equal to the argument if:
--
-- - the argument is a an instance of a library_unit_declaration,
-- a library_unit_body, a library_unit_renaming_declaration, or a subunit.
--
-- - the argument is A_Nonexistent_Declaration or A_Nonexistent_Body.
--
-- Returns a Nil_Compilation_Unit for library_unit_declaration arguments that
-- do not have a corresponding library_unit_body contained in The_Context.
--
-- All Unit_Kinds are appropriate except Not_A_Unit.
--
-- Appropriate Unit_Kinds:
-- A_Procedure
-- A_Function
-- A_Package
-- A_Generic_Procedure
-- A_Generic_Function
-- A_Generic_Package
-- An_Unknown_Unit -- See Implementation Permissions
--
-- Appropriate Unit_Kinds returning the argument Library_Item:
-- A_Procedure_Body
-- A_Function_Body
-- A_Package_Body
-- A_Procedure_Instance
-- A_Function_Instance
-- A_Package_Instance
-- A_Procedure_Renaming
-- A_Function_Renaming
-- A_Package_Renaming
-- A_Generic_Procedure_Renaming
-- A_Generic_Function_Renaming
-- A_Generic_Package_Renaming
-- A_Procedure_Body_Subunit
-- A_Function_Body_Subunit
-- A_Package_Body_Subunit
-- A_Task_Body_Subunit
-- A_Protected_Body_Subunit
-- A_Nonexistent_Declaration
-- A_Nonexistent_Body
--
-- Returns all Unit Kinds.
--
-- If the argument Element requires a body to be presented to make up a
-- complete partition containing this Element, but The_Context does not
-- contain the corresponding body, or the body contained in The_Context
-- is inconsistent with the argument Element, A_Nonexistent_Body shall
-- be returned.
--
-- --|IR Implementation Requirements:
-- --|IR
-- --|IR Any non-Nil result will have an Enclosing_Context value that
-- --|IR Is_Identical to The_Context.
-- --|IR
-- --|IR These two function calls will always produce identical results:
-- --|IR
-- --|IR Unit := Corresponding_Body( Unit );
-- --|IR Unit := Corresponding_Body( Unit, Enclosing_Context ( Unit ));
-- --|IR
-- --|IR The Enclosing_Context for any non-Nil result will always be
-- --|IR The_Context, regardless of the Enclosing_Context value for the
-- --|IR Library_Item argument. This query is one means of obtaining
-- --|IR corresponding (Is_Equal) units from separate ASIS Context values
-- --|IR whose underlying implementations overlap.
-- --|IR
-- --|IP Implementation Permissions:
-- --|IP
-- --|IP The handling of An_Unknown_Unit is implementation specific. The
-- --|IP expected use for An_Unknown_Unit is to hide proprietary
-- --|IP implementation details contained within unit bodies. In some cases,
-- --|IP it could be possible to obtain an appropriate library_unit_body when
-- --|IP starting with An_Unknown_Unit. Some implementors may choose to simply
-- --|IP return the An_Unknown_Unit argument in all cases.
------------------------------------------------------------------------------
-- 10.15 function Is_Nil
------------------------------------------------------------------------------
function Is_Nil (Right : Asis.Compilation_Unit) return Boolean;
------------------------------------------------------------------------------
-- Right - Specifies the unit to test
--
-- Returns True if the compilation_unit is a Nil_Compilation_Unit.
--
------------------------------------------------------------------------------
-- 10.16 function Is_Nil
------------------------------------------------------------------------------
function Is_Nil (Right : Asis.Compilation_Unit_List) return Boolean;
------------------------------------------------------------------------------
-- Right - Specifies the unit list to test
--
-- Returns True if the compilation_unit list has a length of zero.
--
------------------------------------------------------------------------------
-- 10.17 function Is_Equal
------------------------------------------------------------------------------
function Is_Equal
(Left : Asis.Compilation_Unit;
Right : Asis.Compilation_Unit)
return Boolean;
------------------------------------------------------------------------------
-- Left - Specifies the first unit to compare
-- Right - Specifies the second unit to compare
--
-- Returns True if Left and Right represent the same physical compilation unit
-- or if both are Nil_Compilation_Unit values. The two units may or may not
-- be from the same ASIS Context variable. ("The same physical compilation
-- unit" have the same version, as defined by Reference Manual E.3(5)
-- and the same program text.)
--
-- Two nonexistent units are Is_Equal if they have the same Name and
-- Unit_Kind.
--
------------------------------------------------------------------------------
-- 10.18 function Is_Identical
------------------------------------------------------------------------------
function Is_Identical
(Left : Asis.Compilation_Unit;
Right : Asis.Compilation_Unit)
return Boolean;
------------------------------------------------------------------------------
-- Left - Specifies the first unit to compare
-- Right - Specifies the second unit to compare
--
-- Returns True if Left and Right represent the same physical compilation
-- unit, from the same open ASIS Context variable, or, if both are
-- Nil_Compilation_Unit values. ("The same physical compilation
-- unit" have the same version, as defined by Reference Manual E.3(5)
-- and the same program text.)
--
-- Two nonexistent units are Is_Identical if they have the same
-- Unique_Name and the same Enclosing_Context.
--
------------------------------------------------------------------------------
-- 10.19 function Unit_Full_Name
------------------------------------------------------------------------------
function Unit_Full_Name
(Compilation_Unit : Asis.Compilation_Unit)
return Wide_String;
------------------------------------------------------------------------------
-- Compilation_Unit - Specifies the unit whose name is desired
--
-- Returns the string image of the fully expanded Ada name of the given
-- compilation unit. This may be a simple name ("A") of a root library
-- unit, or an expanded name ("A.B") of a subunit or non-root child unit.
-- An expanded name shall contain the full parent_unit_name as its prefix.
-- Returns a null string only if A_Configuration_Compilation or a
-- Nil_Compilation_Unit is given.
--
-- The case of names returned by this query may vary between implementations.
-- Implementors are encouraged, but not required, to return names in the
-- same case as was used in the original compilation text.
--
-- All Unit_Kinds are appropriate.
--
------------------------------------------------------------------------------
-- 10.20 function Unique_Name
------------------------------------------------------------------------------
function Unique_Name
(Compilation_Unit : Asis.Compilation_Unit)
return Wide_String;
------------------------------------------------------------------------------
-- Compilation_Unit - Specifies the unit whose name is desired
--
-- Returns a string that uniquely identifies the given compilation unit
-- within the underlying Ada Context implementation. The result may vary
-- depending on the ASIS implementation. The unique name may include the name
-- and parameters of the Context, file system paths, library files, version
-- numbers, kind, or any other information that an implementation may need
-- to uniquely identify the compilation unit.
--
-- Returns a null string only if a Nil_Compilation_Unit is given.
--
-- All Unit_Kinds are appropriate.
--
------------------------------------------------------------------------------
-- 10.21 function Exist
------------------------------------------------------------------------------
function Exists
(Compilation_Unit : Asis.Compilation_Unit)
return Boolean;
------------------------------------------------------------------------------
-- Compilation_Unit - Specifies the unit to test
--
-- Returns False for any unit with Not_A_Unit or nonexistent kind.
-- Returns True for all other unit kinds.
--
-- All Unit_Kinds are expected.
--
------------------------------------------------------------------------------
-- 10.22 function Can_Be_Main_Program
------------------------------------------------------------------------------
function Can_Be_Main_Program
(Compilation_Unit : Asis.Compilation_Unit)
return Boolean;
------------------------------------------------------------------------------
-- Compilation_Unit - Specifies the unit to test
--
-- Returns True if the Compilation_Unit exists and is a subprogram
-- library_unit_declaration, library_unit_renaming_declaration, or
-- library_unit_body that can be used as a main subprogram. See Reference
-- Manual 10.2(7).
--
-- Returns False otherwise.
--
-- Results of this function may vary according to the requirements an Ada
-- implementation may impose on a main subprogram.
--
-- All Unit_Kinds are expected.
--
------------------------------------------------------------------------------
-- 10.23 function Is_Body_Required
------------------------------------------------------------------------------
function Is_Body_Required
(Compilation_Unit : Asis.Compilation_Unit)
return Boolean;
------------------------------------------------------------------------------
-- Compilation_Unit - Specifies the unit to test
--
-- Returns True if the Compilation_Unit exists and is a library
-- package_declaration that requires a body. See Reference Manual 7.2(4).
--
-- All Unit_Kinds are expected.
--
------------------------------------------------------------------------------
-- 10.24 function Text_Name
------------------------------------------------------------------------------
function Text_Name
(Compilation_Unit : Asis.Compilation_Unit)
return Wide_String;
------------------------------------------------------------------------------
-- Compilation_Unit - Specifies the unit whose text name is desired
--
-- Returns the name of the text, or other structure, that was the source
-- of the compilation that resulted in this Compilation_Unit. Returns a
-- null string if the unit has a Nil or nonexistent kind, or if the text
-- name is not available for any reason.
--
-- Ada has no concept of source or text file.
-- Text_Name availability is a required feature of ASIS.
-- Results of this function may vary among implementations.
--
-- All Unit_Kinds are appropriate.
--
------------------------------------------------------------------------------
-- 10.25 function Text_Form
------------------------------------------------------------------------------
function Text_Form
(Compilation_Unit : Asis.Compilation_Unit)
return Wide_String;
------------------------------------------------------------------------------
-- Compilation_Unit - Specifies the unit whose text form is desired
--
-- Returns the Form parameter (as for Text_Io.Open) for the text, or
-- other structure, that was the source of the compilation that resulted in
-- this Compilation_Unit. Returns a null string if the unit has a Nil or
-- nonexistent kind, if the text was created with an empty Form parameter,
-- or if the text Form parameter value is not available for any reason.
--
-- Ada has no concept of source or text file.
-- Text_Form availability is a required feature of ASIS.
-- Results of this function may vary among implementations.
--
-- All Unit_Kinds are appropriate.
--
------------------------------------------------------------------------------
-- 10.26 function Object_Name
------------------------------------------------------------------------------
function Object_Name
(Compilation_Unit : Asis.Compilation_Unit)
return Wide_String;
------------------------------------------------------------------------------
-- Compilation_Unit - Specifies the unit whose object name is desired
--
-- Returns the name of the object, or other structure, that contains the
-- binary result of the compilation for this Compilation_Unit. Returns
-- a null string if the unit has a Nil or nonexistent kind, or if the
-- object name is not available for any reason.
--
-- All Unit_Kinds are appropriate.
--
------------------------------------------------------------------------------
-- 10.27 function Object_Form
------------------------------------------------------------------------------
function Object_Form
(Compilation_Unit : Asis.Compilation_Unit)
return Wide_String;
------------------------------------------------------------------------------
-- Compilation_Unit - Specifies the unit whose object form is desired
--
-- Returns the Form parameter (as for Text_Io.Open) for the object, or
-- other structure, that was the machine-code result of the compilation of
-- this Compilation_Unit. Returns a null string if the unit has a Nil or
-- nonexistent kind, if the object was created with an empty Form parameter,
-- or if the object Form parameter value is not available for any reason.
--
-- All Unit_Kinds are appropriate.
--
------------------------------------------------------------------------------
-- 10.28 function Compilation_Command_Line_Options
------------------------------------------------------------------------------
function Compilation_Command_Line_Options
(Compilation_Unit : Asis.Compilation_Unit)
return Wide_String;
------------------------------------------------------------------------------
-- Compilation_Unit - Specifies the unit to query
--
-- Returns the command line options used to compile the Compilation_Unit.
-- Returns null string if the unit has a Nil or nonexistent unit kind, or
-- if the command line options are not available for any reason.
--
-- All Unit_Kinds are appropriate.
--
------------------------------------------------------------------------------
-- 10.29 function Has_Attribute
------------------------------------------------------------------------------
function Has_Attribute
(Compilation_Unit : Asis.Compilation_Unit;
Attribute : Wide_String)
return Boolean;
------------------------------------------------------------------------------
-- Compilation_Unit - Specifies the unit to query
-- Attribute - Specifies the name of the attribute to query
--
-- Returns True if the compilation unit has the given attribute.
--
-- Returns False if the unit is a Nil_Compilation_Unit argument, the
-- Attribute does not exist, or the implementation does not support
-- attributes.
--
-- All Unit_Kinds are expected.
--
-- Results of this query may vary across ASIS implementations.
--
------------------------------------------------------------------------------
-- 10.30 function Attribute_Value_Delimiter
------------------------------------------------------------------------------
function Attribute_Value_Delimiter return Wide_String;
------------------------------------------------------------------------------
-- Returns the string used as a delimiter separating individual values
-- within the string Attribute_Values of a compilation unit.
--
-- Results of this query may vary across ASIS implementations. The result
-- can be a null string for implementations that do not support attributes,
-- or that do not support more than one attribute.
--
------------------------------------------------------------------------------
-- 10.31 function Attribute_Values
------------------------------------------------------------------------------
function Attribute_Values
(Compilation_Unit : Asis.Compilation_Unit;
Attribute : Wide_String)
return Wide_String;
------------------------------------------------------------------------------
-- Compilation_Unit - Specifies the unit to query
-- Attribute - Specifies the name of the attribute to query
--
-- Returns a string containing zero or more images of values that are
-- associated with the given attribute. When more than one value is returned,
-- the Attribute_Value_Delimiter string is used to separate the individual
-- values. Returns a null string if the unit is a Nil_Compilation_Unit
-- argument, the unit has no values for this Attribute, or the implementation
-- does not support attributes.
--
-- All Unit_Kinds are appropriate.
--
-- Results of this query may vary across ASIS implementations.
--
------------------------------------------------------------------------------
-- 10.32 function Subunits
------------------------------------------------------------------------------
function Subunits
(Parent_Body : Asis.Compilation_Unit)
return Asis.Compilation_Unit_List;
function Subunits
(Parent_Body : Asis.Compilation_Unit;
The_Context : Asis.Context)
return Asis.Compilation_Unit_List;
------------------------------------------------------------------------------
-- Parent_Body - Specifies the parent unit to query
-- The_Context - Specifies the program Context to use for context
--
-- Returns a complete list of subunit values, with one value for each body
-- stub that appears in the given Parent_Body. Returns a
-- Nil_Compilation_Unit_List if the parent unit does not contain any body
-- stubs. Every unit in the result will have an Enclosing_Context that
-- Is_Identical to The_Context.
--
-- These two function calls will always produce identical results:
--
-- SUnits := Subunits ( PUnit );
-- SUnits := Subunits ( PUnit, Enclosing_Context ( PUnit ));
--
-- The result may include unit values with a nonexistent unit kind. It
-- includes values for subunits that exist in The_Context as
-- well as values for subunits that do not exist, but whose name can be
-- deduced from the body stub and the name of the parent unit. These
-- nonexistent units are known to be library_unit_body elements so their unit
-- kind is A_Nonexistent_Body.
--
-- Subunit lists are also available through the Semantic_Dependence_Order
-- query using the Family relation.
--
-- Raises ASIS_Inappropriate_Compilation_Unit if the unit is a
-- Nil_Compilation_Unit.
--
-- If a subunit is absent or if it is inconsistent with the argument Element,
-- A_Nonexistent_Body shall be returned for it.
--
-- --|D2005 start
-- The list of appropriate unit kinds is missing here. It should be:
--
-- Appropriate Unit_Kinds:
-- A_Procedure_Body
-- A_Function_Body
-- A_Package_Body
-- A_Procedure_Body_Subunit
-- A_Function_Body_Subunit
-- A_Package_Body_Subunit
-- A_Task_Body_Subunit
-- A_Protected_Body_Subunit
-- --|D2005 end
--
-- Returns Unit_Kinds:
-- A_Nonexistent_Body
-- A_Procedure_Body_Subunit
-- A_Function_Body_Subunit
-- A_Package_Body_Subunit
-- A_Task_Body_Subunit
-- A_Protected_Body_Subunit
--
------------------------------------------------------------------------------
-- 10.33 function Corresponding_Subunit_Parent_Body
------------------------------------------------------------------------------
function Corresponding_Subunit_Parent_Body
(Subunit : Asis.Compilation_Unit)
return Asis.Compilation_Unit;
function Corresponding_Subunit_Parent_Body
(Subunit : Asis.Compilation_Unit;
The_Context : Asis.Context)
return Asis.Compilation_Unit;
------------------------------------------------------------------------------
-- Subunit - Specifies the subunit to query
-- The_Context - Specifies the program Context to use for context
--
-- Returns the Compilation_Unit containing the body stub of the given Subunit.
-- Returns a Nil_Compilation_Unit if the subunit parent is not contained in
-- The_Context. Any non-Nil result will have an Enclosing_Context value that
-- Is_Identical to The_Context.
--
-- These two function calls will always produce identical results:
--
-- PUnit := Corresponding_Subunit_Parent_Body ( SUnit );
-- PUnit := Corresponding_Subunit_Parent_Body ( SUnit,
-- Enclosing_Context ( SUnit ));
--
-- Appropriate Unit_Kinds:
-- A_Procedure_Body_Subunit
-- A_Function_Body_Subunit
-- A_Package_Body_Subunit
-- A_Task_Body_Subunit
-- A_Protected_Body_Subunit
--
-- Returns Unit_Kinds:
-- A_Procedure_Body
-- A_Function_Body
-- A_Package_Body
-- A_Procedure_Body_Subunit
-- A_Function_Body_Subunit
-- A_Package_Body_Subunit
-- A_Task_Body_Subunit
-- A_Protected_Body_Subunit
--
-- If the corresponding body does not exist in The_Context, or if it exists,
-- but is inconsistent with the argument Element, then A_Nonexistent_Body
-- shall be returned.
--
------------------------------------------------------------------------------
-- To locate the parent of a subunit that is not itself a subunit,
-- repeatedly call Corresponding_Subunit_Parent_Body until a unit that
-- is not a subunit is returned.
--
------------------------------------------------------------------------------
-- 10.34 function Debug_Image
------------------------------------------------------------------------------
function Debug_Image
(Compilation_Unit : Asis.Compilation_Unit)
return Wide_String;
------------------------------------------------------------------------------
-- Compilation_Unit - Specifies a unit to convert
--
-- Returns a string value containing implementation-defined debug
-- information associated with the compilation unit.
--
-- The return value uses Asis.Text.Delimiter_Image to separate the lines
-- of multi-line results. The return value does not end with
-- Asis.Text.Delimiter_Image.
--
-- These values are intended for two purposes. They are suitable for
-- inclusion in problem reports sent to the ASIS implementor. They can be
-- presumed to contain information useful when debugging the implementation
-- itself. They are also suitable for use by the ASIS application when
-- printing simple application debugging messages during application
-- development. They are intended to be, to some worthwhile degree,
-- intelligible to the user.
--
end Asis.Compilation_Units;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- S Y S T E M . E X C E P T I O N S --
-- --
-- S p e c --
-- --
-- $Revision$
-- --
-- Copyright (C) 1992-2000 Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, --
-- MA 02111-1307, USA. --
-- --
-- As a special exception, if other files instantiate generics from this --
-- unit, or you link this unit with other files to produce an executable, --
-- this unit does not by itself cause the resulting executable to be --
-- covered by the GNU General Public License. This exception does not --
-- however invalidate any other reasons why the executable file might be --
-- covered by the GNU Public License. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This package contains definitions used for zero cost exception handling.
-- See unit Ada.Exceptions for further details. Note that the reason that
-- we separate out these definitions is to avoid problems with recursion
-- in rtsfind. They must be in a unit which does not require any exception
-- table generation of any kind.
with Ada.Exceptions;
with System;
with System.Standard_Library;
with Unchecked_Conversion;
package System.Exceptions is
package SSL renames System.Standard_Library;
package AEX renames Ada.Exceptions;
-- The following section defines data structures used for zero cost
-- exception handling if System.Parameters.Zero_Cost_Exceptions is
-- set true (i.e. zero cost exceptions are implemented on this target).
-- The approach is to build tables that describe the PC ranges that
-- are covered by various exception frames. When an exception occurs,
-- these tables are searched to determine the address of the applicable
-- handler for the current exception.
subtype Handler_Loc is System.Address;
-- Code location representing entry address of a handler. Values of
-- this type are created using the N_Handler_Loc node, and then
-- passed to the Enter_Handler procedure to enter a handler.
subtype Code_Loc is System.Address;
-- Code location used in building exception tables and for call
-- addresses when propagating an exception (also traceback table)
-- Values of this type are created by using Label'Address or
-- extracted from machine states using Get_Code_Loc.
--------------------
-- Handler_Record --
--------------------
-- A Handler record is built for each choice for each exception handler
-- in a frame.
function To_Exception_Id is
new Unchecked_Conversion (SSL.Exception_Data_Ptr, AEX.Exception_Id);
Others_Dummy_Exception : aliased SSL.Exception_Data;
Others_Id : constant AEX.Exception_Id :=
To_Exception_Id (Others_Dummy_Exception'Access);
-- Dummy exception used to signal others exception
All_Others_Dummy_Exception : aliased SSL.Exception_Data;
All_Others_Id : constant AEX.Exception_Id :=
To_Exception_Id (All_Others_Dummy_Exception'Access);
-- Dummy exception used to signal all others exception (including
-- exceptions not normally handled by others, e.g. Abort_Signal)
type Handler_Record is record
Lo : Code_Loc;
Hi : Code_Loc;
-- Range of PC values of code covered by this handler record. The
-- handler covers all code addresses that are greater than the Lo
-- value, and less than or equal to the Hi value.
Id : AEX.Exception_Id;
-- Id of exception being handled, or one of the above special values
Handler : Handler_Loc;
-- Address of label at start of handler
end record;
type Handler_Record_Ptr is access all Handler_Record;
type Handler_Record_List is array (Natural range <>) of Handler_Record_Ptr;
---------------------------
-- Subprogram_Descriptor --
---------------------------
-- A Subprogram_Descriptor is built for each subprogram through which
-- exceptions may propagate, this includes all Ada subprograms,
-- and also all foreign language imported subprograms.
subtype Subprogram_Info_Type is System.Address;
-- This type is used to represent a value that is used to unwind stack
-- frames. It references target dependent data that provides sufficient
-- information (e.g. about the location of the return point, use of a
-- frame pointer, save-over-call registers etc) to unwind the machine
-- state to the caller. For some targets, this is simply a pointer to
-- the entry point of the procedure (and the routine to pop the machine
-- state disassembles the code at the entry point to obtain the required
-- information). On other targets, it is a pointer to data created by the
-- backend or assembler to represent the required information.
No_Info : constant Subprogram_Info_Type := System.Null_Address;
-- This is a special value used to indicate that it is not possible
-- to pop past this frame. This is used at the outer level (e.g. for
-- package elaboration procedures or the main procedure), and for any
-- other foreign language procedure for which propagation is known
-- to be impossible. An exception is considered unhandled if an
-- attempt is made to pop a frame whose Subprogram_Info_Type value
-- is set to No_Info.
type Subprogram_Descriptor (Num_Handlers : Natural) is record
Code : Code_Loc;
-- This is a code location used to determine which procedure we are
-- in. Most usually it is simply the entry address for the procedure.
-- hA given address is considered to be within the procedure referenced
-- by a Subprogram_Descriptor record if this is the descriptor for
-- which the Code value is as large as possible without exceeding
-- the given value.
Subprogram_Info : Subprogram_Info_Type;
-- This is a pointer to a target dependent data item that provides
-- sufficient information for unwinding the stack frame of this
-- procedure. A value of No_Info (zero) means that we are the
-- outer level procedure.
Handler_Records : Handler_Record_List (1 .. Num_Handlers);
-- List of pointers to Handler_Records for this procedure. The array
-- is sorted inside out, i.e. entries for inner frames appear before
-- entries for outer handlers. This ensures that a serial search
-- finds the innermost applicable handler
end record;
subtype Subprogram_Descriptor_0 is Subprogram_Descriptor (0);
subtype Subprogram_Descriptor_1 is Subprogram_Descriptor (1);
subtype Subprogram_Descriptor_2 is Subprogram_Descriptor (2);
subtype Subprogram_Descriptor_3 is Subprogram_Descriptor (3);
-- Predeclare commonly used subtypes for buildingt he tables
type Subprogram_Descriptor_Ptr is access all Subprogram_Descriptor;
type Subprogram_Descriptor_List
is array (Natural range <>) of Subprogram_Descriptor_Ptr;
type Subprogram_Descriptors_Record (Count : Natural) is record
SDesc : Subprogram_Descriptor_List (1 .. Count);
end record;
type Subprogram_Descriptors_Ptr is
access all Subprogram_Descriptors_Record;
--------------------------
-- Unit Exception_Table --
--------------------------
-- If a unit contains at least one subprogram, then a library level
-- declaration of the form:
-- Tnn : aliased constant Subprogram_Descriptors :=
-- (Count => n,
-- SDesc =>
-- (SD1'Unrestricted_Access,
-- SD2'Unrestricted_Access,
-- ...
-- SDn'Unrestricted_Access));
-- pragma Export (Ada, Tnn, "__gnat_unit_name__SDP");
-- is generated where the initializing expression is an array aggregate
-- whose elements are pointers to the generated subprogram descriptors
-- for the units.
-- Note: the ALI file contains the designation UX in each unit entry
-- if a unit exception table is generated.
-- The binder generates a list of addresses of pointers to these tables.
end System.Exceptions;
|
with Discr11_Pkg; use Discr11_Pkg;
package Discr11 is
type DT_2 is new DT_1 with record
More : Integer;
end record;
function Create return DT_2;
end Discr11;
|
package body Constant2_Pkg2 is
function F1 return Boolean is
begin
return False;
end;
function F2 return Boolean is
begin
return False;
end;
end Constant2_Pkg2;
|
package body Set_Cons is
function "+"(E: Element) return Set is
S: Set := (others => False);
begin
S(E) := True;
return S;
end "+";
function "+"(Left, Right: Element) return Set is
begin
return (+Left) + Right;
end "+";
function "+"(Left: Set; Right: Element) return Set is
S: Set := Left;
begin
S(Right) := True;
return S;
end "+";
function "-"(Left: Set; Right: Element) return Set is
S: Set := Left;
begin
S(Right) := False;
return S;
end "-";
function Nonempty_Intersection(Left, Right: Set) return Boolean is
begin
for E in Element'Range loop
if Left(E) and then Right(E) then return True;
end if;
end loop;
return False;
end Nonempty_Intersection;
function Union(Left, Right: Set) return Set is
S: Set := Left;
begin
for E in Right'Range loop
if Right(E) then S(E) := True;
end if;
end loop;
return S;
end Union;
function Image(S: Set) return String is
function Image(S: Set; Found: Natural) return String is
begin
for E in S'Range loop
if S(E) then
if Found = 0 then
return Image(E) & Image((S-E), Found+1);
else
return "," & Image(E) & Image((S-E), Found+1);
end if;
end if;
end loop;
return "";
end Image;
begin
return "{" & Image(S, 0) & "}";
end Image;
function Image(V: Set_Vec) return String is
begin
if V'Length = 0 then
return "";
else
return Image(V(V'First)) & Image(V(V'First+1 .. V'Last));
end if;
end Image;
end Set_Cons;
|
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Nth_Root is
generic
type Real is digits <>;
function Nth_Root (Value : Real; N : Positive) return Real;
function Nth_Root (Value : Real; N : Positive) return Real is
type Index is mod 2;
X : array (Index) of Real := (Value, Value);
K : Index := 0;
begin
loop
X (K + 1) := ( (Real (N) - 1.0) * X (K) + Value / X (K) ** (N-1) ) / Real (N);
exit when X (K + 1) >= X (K);
K := K + 1;
end loop;
return X (K + 1);
end Nth_Root;
function Long_Nth_Root is new Nth_Root (Long_Float);
begin
Put_Line ("1024.0 10th =" & Long_Float'Image (Long_Nth_Root (1024.0, 10)));
Put_Line (" 27.0 3rd =" & Long_Float'Image (Long_Nth_Root (27.0, 3)));
Put_Line (" 2.0 2nd =" & Long_Float'Image (Long_Nth_Root (2.0, 2)));
Put_Line ("5642.0 125th =" & Long_Float'Image (Long_Nth_Root (5642.0, 125)));
end Test_Nth_Root;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of STMicroelectronics nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
-- --
-- This file is based on: --
-- --
-- @file stm32f4xx_hal_spi.h --
-- @author MCD Application Team --
-- @version V1.1.0 --
-- @date 19-June-2014 --
-- @brief Header file of SPI HAL module. --
-- --
-- COPYRIGHT(c) 2014 STMicroelectronics --
------------------------------------------------------------------------------
-- This file provides definitions for the STM32G4 (ARM Cortex M4F
-- from ST Microelectronics) Serial Peripheral Interface (SPI) facility.
private with STM32_SVD.SPI;
with HAL.SPI;
with System;
package STM32.SPI is
type Internal_SPI_Port is private;
type SPI_Port (Periph : not null access Internal_SPI_Port) is
limited new HAL.SPI.SPI_Port with private;
type SPI_Data_Direction is
(D2Lines_FullDuplex,
D2Lines_RxOnly,
D1Line_Rx,
D1Line_Tx);
type SPI_Mode is (Master, Slave);
type SPI_Data_Size is
(Bits_4,
Bits_5,
Bits_6,
Bits_7,
Bits_8,
Bits_9,
Bits_10,
Bits_11,
Bits_12,
Bits_13,
Bits_14,
Bits_15,
Bits_16)
with Size => 4;
for SPI_Data_Size use
(Bits_4 => 2#0011#,
Bits_5 => 2#0100#,
Bits_6 => 2#0101#,
Bits_7 => 2#0110#,
Bits_8 => 2#0111#,
Bits_9 => 2#1000#,
Bits_10 => 2#1001#,
Bits_11 => 2#1010#,
Bits_12 => 2#1011#,
Bits_13 => 2#1100#,
Bits_14 => 2#1101#,
Bits_15 => 2#1110#,
Bits_16 => 2#1111#);
type SPI_Clock_Polarity is (High, Low);
type SPI_Clock_Phase is (P1Edge, P2Edge);
type SPI_Slave_Management is (Software_Managed, Hardware_Managed);
type SPI_Baud_Rate_Prescaler is
(BRP_2, BRP_4, BRP_8, BRP_16, BRP_32, BRP_64, BRP_128, BRP_256);
type SPI_First_Bit is (MSB, LSB);
type SPI_Configuration is record
Direction : SPI_Data_Direction;
Mode : SPI_Mode;
Data_Size : HAL.SPI.SPI_Data_Size;
Clock_Polarity : SPI_Clock_Polarity;
Clock_Phase : SPI_Clock_Phase;
Slave_Management : SPI_Slave_Management;
Baud_Rate_Prescaler : SPI_Baud_Rate_Prescaler;
First_Bit : SPI_First_Bit;
CRC_Poly : UInt16;
end record;
procedure Configure (This : in out SPI_Port; Conf : SPI_Configuration);
procedure Enable (This : in out SPI_Port);
procedure Disable (This : in out SPI_Port);
function Enabled (This : SPI_Port) return Boolean;
procedure Send (This : in out SPI_Port; Data : UInt16);
function Data (This : SPI_Port) return UInt16
with Inline;
procedure Send (This : in out SPI_Port; Data : UInt8);
function Data (This : SPI_Port) return UInt8
with Inline;
function Is_Busy (This : SPI_Port) return Boolean
with Inline;
function Rx_Is_Empty (This : SPI_Port) return Boolean
with Inline;
function Tx_Is_Empty (This : SPI_Port) return Boolean
with Inline;
function Busy (This : SPI_Port) return Boolean
with Inline;
function Underrun_Indicated (This : SPI_Port) return Boolean
with Inline;
function CRC_Error_Indicated (This : SPI_Port) return Boolean
with Inline;
function Mode_Fault_Indicated (This : SPI_Port) return Boolean
with Inline;
function Overrun_Indicated (This : SPI_Port) return Boolean
with Inline;
function Frame_Fmt_Error_Indicated (This : SPI_Port) return Boolean
with Inline;
procedure Clear_Overrun (This : SPI_Port);
procedure Reset_CRC (This : in out SPI_Port);
function CRC_Enabled (This : SPI_Port) return Boolean;
function Is_Data_Frame_16bit (This : SPI_Port) return Boolean;
function Current_Mode (This : SPI_Port) return SPI_Mode;
function Current_Data_Direction (This : SPI_Port) return SPI_Data_Direction;
-- The following I/O routines implement the higher level functionality for
-- CRC and data direction, among others.
type UInt8_Buffer is array (Natural range <>) of UInt8
with Alignment => 2;
-- The alignment is set to 2 because we treat component pairs as half_word
-- values when sending/receiving in 16-bit mode.
-- Blocking
overriding
function Data_Size (This : SPI_Port) return HAL.SPI.SPI_Data_Size;
overriding
procedure Transmit
(This : in out SPI_Port;
Data : HAL.SPI.SPI_Data_8b;
Status : out HAL.SPI.SPI_Status;
Timeout : Natural := 1000);
overriding
procedure Transmit
(This : in out SPI_Port;
Data : HAL.SPI.SPI_Data_16b;
Status : out HAL.SPI.SPI_Status;
Timeout : Natural := 1000);
procedure Transmit
(This : in out SPI_Port;
Outgoing : UInt8);
overriding
procedure Receive
(This : in out SPI_Port;
Data : out HAL.SPI.SPI_Data_8b;
Status : out HAL.SPI.SPI_Status;
Timeout : Natural := 1000);
overriding
procedure Receive
(This : in out SPI_Port;
Data : out HAL.SPI.SPI_Data_16b;
Status : out HAL.SPI.SPI_Status;
Timeout : Natural := 1000);
procedure Receive
(This : in out SPI_Port;
Incoming : out UInt8);
procedure Transmit_Receive
(This : in out SPI_Port;
Outgoing : UInt8_Buffer;
Incoming : out UInt8_Buffer;
Size : Positive);
procedure Transmit_Receive
(This : in out SPI_Port;
Outgoing : UInt8;
Incoming : out UInt8);
-- TODO: add the other higher-level HAL routines for interrupts and DMA
function Data_Register_Address
(This : SPI_Port)
return System.Address;
-- For DMA transfer
private
type Internal_SPI_Port is new STM32_SVD.SPI.SPI_Peripheral;
type SPI_Port (Periph : not null access Internal_SPI_Port) is
limited new HAL.SPI.SPI_Port with null record;
procedure Send_Receive_16bit_Mode
(This : in out SPI_Port;
Outgoing : UInt8_Buffer;
Incoming : out UInt8_Buffer;
Size : Positive);
procedure Send_Receive_8bit_Mode
(This : in out SPI_Port;
Outgoing : UInt8_Buffer;
Incoming : out UInt8_Buffer;
Size : Positive);
procedure Send_16bit_Mode
(This : in out SPI_Port;
Outgoing : HAL.SPI.SPI_Data_16b);
procedure Send_8bit_Mode
(This : in out SPI_Port;
Outgoing : HAL.SPI.SPI_Data_8b);
procedure Receive_16bit_Mode
(This : in out SPI_Port;
Incoming : out HAL.SPI.SPI_Data_16b);
procedure Receive_8bit_Mode
(This : in out SPI_Port;
Incoming : out HAL.SPI.SPI_Data_8b);
end STM32.SPI;
|
with AUnit.Assertions.Generic_Helpers;
package AUnit.Assertions.Typed is
procedure Assert is new Generic_Helpers.Assert_Integer_Image
(Num => Short_Short_Integer);
procedure Assert is new Generic_Helpers.Assert_Integer_Image
(Num => Short_Integer);
procedure Assert is new Generic_Helpers.Assert_Integer_Image
(Num => Integer);
procedure Assert is new Generic_Helpers.Assert_Integer_Image
(Num => Long_Integer);
procedure Assert is new Generic_Helpers.Assert_Integer_Image
(Num => Long_Long_Integer);
procedure Assert is new Generic_Helpers.Assert_Float_Image
(Num => Short_Float);
procedure Assert is new Generic_Helpers.Assert_Float_Image
(Num => Float);
procedure Assert is new Generic_Helpers.Assert_Float_Image
(Num => Long_Float);
procedure Assert is new Generic_Helpers.Assert_Float_Image
(Num => Long_Long_Float);
procedure Assert is new Generic_Helpers.Assert_Enumeration_Image
(Enum => Boolean);
end AUnit.Assertions.Typed;
|
with Ada.Text_IO; use Ada.Text_IO;
with Libadalang.Analysis; use Libadalang.Analysis;
with Libadalang.Common; use Libadalang.Common;
with Rejuvenation; use Rejuvenation;
with Rejuvenation.Finder; use Rejuvenation.Finder;
with Rejuvenation.Utils; use Rejuvenation.Utils;
package body Placeholder_Relations is
function Is_Referenced_In
(D_N : Defining_Name; Node : Ada_Node) return Boolean;
function Is_Referenced_In
(D_N : Defining_Name; Node : Ada_Node) return Boolean
is
Identifiers : constant Node_List.Vector := Find (Node, Ada_Identifier);
begin
return
(for some Identifier of Identifiers =>
Identifier.As_Identifier.P_Referenced_Defining_Name = D_N);
end Is_Referenced_In;
function Is_Referenced_In
(Match : Match_Pattern; Definition, Context : String) return Boolean
is
D_N : constant Defining_Name :=
Match.Get_Single_As_Node (Definition).As_Defining_Name;
Context_Nodes : constant Node_List.Vector :=
Match.Get_Placeholder_As_Nodes (Context);
begin
return
(for some Context_Node of Context_Nodes =>
Is_Referenced_In (D_N, Context_Node));
end Is_Referenced_In;
function Is_Constant_Expression (E : Expr) return Boolean;
function Is_Constant_Expression (E : Expr) return Boolean is
begin
case E.Kind is
when Ada_String_Literal | Ada_Int_Literal | Ada_Real_Literal =>
return True;
when Ada_Identifier =>
return False;
when Ada_Bin_Op =>
declare
B_O : constant Bin_Op := E.As_Bin_Op;
begin
return
Is_Constant_Expression (B_O.F_Left)
and then Is_Constant_Expression (B_O.F_Right);
end;
when Ada_Relation_Op =>
declare
R_O : constant Relation_Op := E.As_Relation_Op;
begin
return
Is_Constant_Expression (R_O.F_Left)
and then Is_Constant_Expression (R_O.F_Right);
end;
when Ada_Paren_Expr =>
return Is_Constant_Expression (E.As_Paren_Expr.F_Expr);
when others =>
Put_Line
("Is_Constant_Expression: Unhandled kind - " & E.Kind'Image);
return False;
end case;
end Is_Constant_Expression;
function Is_Constant_Expression
(Match : Match_Pattern; Expression : String) return Boolean
is
E : constant Expr := Match.Get_Single_As_Node (Expression).As_Expr;
begin
return Is_Constant_Expression (E);
end Is_Constant_Expression;
function Is_Within_Base_Subp_Body
(Match : Match_Pattern; Subp_Name : String) return Boolean
is
Nodes : constant Node_List.Vector := Get_Nodes (Match);
begin
-- Since Nodes are part of a sublist - checking a single node is enough
return
(for some Parent of Nodes.First_Element.Parents =>
Parent.Kind in Ada_Base_Subp_Body
and then Subp_Name =
Raw_Signature (Parent.As_Base_Subp_Body.F_Subp_Spec.F_Subp_Name));
end Is_Within_Base_Subp_Body;
end Placeholder_Relations;
|
-- SPDX-FileCopyrightText: 2019-2020 Max Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-------------------------------------------------------------
with Program.Units.Declarations;
package body Program.Units.Bodies is
--------------------
-- Append_Subunit --
--------------------
procedure Append_Subunit
(Self : in out Unit_Body;
Value : Program.Compilation_Units.Compilation_Unit_Access)
is
begin
Self.Subunits.Append (Value);
end Append_Subunit;
-------------------------------
-- Corresponding_Declaration --
-------------------------------
overriding function Corresponding_Declaration (Self : access Unit_Body)
return Program.Library_Unit_Declarations.Library_Unit_Declaration_Access is
begin
return Self.Declaration;
end Corresponding_Declaration;
----------------
-- Initialize --
----------------
procedure Initialize
(Self : in out Unit_Body;
Compilation : Program.Compilations.Compilation_Access;
Full_Name : Text;
Context_Clause : Program.Element_Vectors.Element_Vector_Access;
Unit_Declaration : not null Program.Elements.Element_Access;
Parent : Program.Library_Unit_Declarations
.Library_Unit_Declaration_Access;
Declaration : Program.Library_Unit_Declarations
.Library_Unit_Declaration_Access)
is
begin
Self.Initialize
(Compilation => Compilation,
Full_Name => Full_Name,
Context_Clause => Context_Clause,
Unit_Declaration => Unit_Declaration);
Self.Parent := Parent;
if Parent not in null then
Program.Units.Declarations.Unit_Declaration (Parent.all)
.Append_Child (Self'Unchecked_Access);
end if;
if Declaration not in null then
Program.Units.Declarations.Unit_Declaration (Declaration.all)
.Set_Body (Self'Unchecked_Access);
end if;
Self.Declaration := Declaration;
Self.Subunits.Clear;
end Initialize;
-------------------------------
-- Is_Library_Unit_Body_Unit --
-------------------------------
overriding function Is_Library_Unit_Body_Unit
(Self : Unit_Body) return Boolean
is
pragma Unreferenced (Self);
begin
return True;
end Is_Library_Unit_Body_Unit;
------------
-- Parent --
------------
overriding function Parent (Self : access Unit_Body)
return Program.Library_Unit_Declarations.Library_Unit_Declaration_Access
is
begin
return Self.Parent;
end Parent;
--------------
-- Subunits --
--------------
overriding function Subunits (Self : access Unit_Body)
return Program.Compilation_Unit_Vectors.Compilation_Unit_Vector_Access is
begin
if Self.Subunits.Is_Empty then
return null;
else
return Self.Subunits'Access;
end if;
end Subunits;
end Program.Units.Bodies;
|
--
-- 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 Symbols;
package body Decoration is
use Symbols;
subtype Mark_String is String (1 .. 3);
To_Mark : constant array (State_Type) of Mark_String :=
(Fresh => " - ",
Executing => " + ",
Done => UTF8 (White_Star), -- ;'*',
Omitted => " o ",
Deleted => " X ");
-- if Database.Events.Is_Done (Desc.Id) then
-- Put (Symbols.UTF8 (Symbols.Black_Star));
-- else
-- Put (Symbols.UTF8 (Symbols.White_Star));
-- end if;
Space : constant String := " ";
Left_Parenthesis : constant String :=
UTF8 (Medium_Flattened_Left_Parenthesis_Ornament);
Right_Parenthesis : constant String :=
UTF8 (Medium_Flattened_Right_Parenthesis_Ornament);
function Status_Image (Status : Status_Type)
return String
is
First : constant String :=
(if Status.Partly then Left_Parenthesis else Space);
Last : constant String :=
(if Status.Partly then Right_Parenthesis else Space);
Mark : constant String :=
To_Mark (Status.State);
begin
return First & Mark & Last;
end Status_Image;
function Title_Image (Title : String;
Status : Status_Type)
return String
is
First : constant Character := (if Status.Partly then '(' else ' ');
Last : constant Character := (if Status.Partly then ')' else ' ');
begin
return First & Title & Last;
end Title_Image;
function Current_Image (Status : Status_Type)
return String
is
pragma Unreferenced (Status);
begin
return "???";
end Current_Image;
end Decoration;
|
with
any_Math.any_Geometry.any_d3.any_Modeller;
package float_math.Geometry.d3.Modeller is new float_Math.Geometry.d3.any_Modeller;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2016 onox <denkpadje@gmail.com>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with GL.Types;
with Orka.Algebra;
with Orka.Transforms.Singles.Matrices;
with Orka.Transforms.Doubles.Matrices;
package Orka.Types is
pragma Pure;
type Element_Type is
-- Numeric types
(UByte_Type,
UShort_Type,
UInt_Type,
Byte_Type,
Short_Type,
Int_Type,
Half_Type,
Single_Type,
Double_Type,
-- Composite types
Single_Vector_Type,
Double_Vector_Type,
Single_Matrix_Type,
Double_Matrix_Type,
Arrays_Command_Type,
Elements_Command_Type,
Dispatch_Command_Type);
subtype Numeric_Type is Element_Type range UByte_Type .. Double_Type;
subtype Index_Type is Numeric_Type range UShort_Type .. UInt_Type;
subtype Composite_Type is Element_Type range Single_Vector_Type .. Dispatch_Command_Type;
function Convert (Kind : Numeric_Type) return GL.Types.Numeric_Type;
function Convert (Kind : Index_Type) return GL.Types.Index_Type;
-----------------------------------------------------------------------------
package Singles is new Orka.Algebra (Orka.Transforms.Singles.Matrices);
package Doubles is new Orka.Algebra (Orka.Transforms.Doubles.Matrices);
procedure Convert (Elements : GL.Types.Single_Array; Result : out GL.Types.Half_Array)
with Post => Elements'Length = Result'Length;
procedure Convert (Elements : GL.Types.Half_Array; Result : out GL.Types.Single_Array)
with Post => Elements'Length = Result'Length;
-----------------------------------------------------------------------------
function Is_Power_Of_Two (Value : Positive) return Boolean;
generic
type Source is digits <>;
type Target is digits <>;
function Clamp (Value : in Source) return Target;
generic
type Source is digits <>;
type Target is digits <>;
function Normalize_Periodic (Value : in Source) return Target;
end Orka.Types;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- A S P E C T S --
-- --
-- S p e c --
-- --
-- Copyright (C) 2010, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This package defines the aspects that are recognized by GNAT in aspect
-- specifications. It also contains the subprograms for storing/retrieving
-- aspect specifications from the tree. The semantic processing for aspect
-- specifications is found in Sem_Ch13.Analyze_Aspect_Specifications.
with Namet; use Namet;
with Types; use Types;
package Aspects is
-- Type defining recognized aspects
type Aspect_Id is
(No_Aspect, -- Dummy entry for no aspect
Aspect_Ada_2005, -- GNAT
Aspect_Ada_2012, -- GNAT
Aspect_Address,
Aspect_Alignment,
Aspect_Atomic,
Aspect_Atomic_Components,
Aspect_Bit_Order,
Aspect_Component_Size,
Aspect_Discard_Names,
Aspect_External_Tag,
Aspect_Favor_Top_Level, -- GNAT
Aspect_Inline,
Aspect_Inline_Always, -- GNAT
Aspect_Input,
Aspect_Invariant,
Aspect_Machine_Radix,
Aspect_No_Return,
Aspect_Object_Size, -- GNAT
Aspect_Output,
Aspect_Pack,
Aspect_Persistent_BSS, -- GNAT
Aspect_Post,
Aspect_Pre,
Aspect_Predicate, -- GNAT???
Aspect_Preelaborable_Initialization,
Aspect_Pure_Function, -- GNAT
Aspect_Read,
Aspect_Shared, -- GNAT (equivalent to Atomic)
Aspect_Size,
Aspect_Storage_Pool,
Aspect_Storage_Size,
Aspect_Stream_Size,
Aspect_Suppress,
Aspect_Suppress_Debug_Info, -- GNAT
Aspect_Unchecked_Union,
Aspect_Universal_Aliasing, -- GNAT
Aspect_Unmodified, -- GNAT
Aspect_Unreferenced, -- GNAT
Aspect_Unreferenced_Objects, -- GNAT
Aspect_Unsuppress,
Aspect_Value_Size, -- GNAT
Aspect_Volatile,
Aspect_Volatile_Components,
Aspect_Warnings,
Aspect_Write); -- GNAT
-- The following array indicates aspects that accept 'Class
Class_Aspect_OK : constant array (Aspect_Id) of Boolean :=
(Aspect_Invariant => True,
Aspect_Pre => True,
Aspect_Predicate => True,
Aspect_Post => True,
others => False);
-- The following type is used for indicating allowed expression forms
type Aspect_Expression is
(Optional, -- Optional boolean expression
Expression, -- Required non-boolean expression
Name); -- Required name
-- The following array indicates what argument type is required
Aspect_Argument : constant array (Aspect_Id) of Aspect_Expression :=
(No_Aspect => Optional,
Aspect_Ada_2005 => Optional,
Aspect_Ada_2012 => Optional,
Aspect_Address => Expression,
Aspect_Alignment => Expression,
Aspect_Atomic => Optional,
Aspect_Atomic_Components => Optional,
Aspect_Bit_Order => Expression,
Aspect_Component_Size => Expression,
Aspect_Discard_Names => Optional,
Aspect_External_Tag => Expression,
Aspect_Favor_Top_Level => Optional,
Aspect_Inline => Optional,
Aspect_Inline_Always => Optional,
Aspect_Input => Name,
Aspect_Invariant => Expression,
Aspect_Machine_Radix => Expression,
Aspect_No_Return => Optional,
Aspect_Object_Size => Expression,
Aspect_Output => Name,
Aspect_Persistent_BSS => Optional,
Aspect_Pack => Optional,
Aspect_Post => Expression,
Aspect_Pre => Expression,
Aspect_Predicate => Expression,
Aspect_Preelaborable_Initialization => Optional,
Aspect_Pure_Function => Optional,
Aspect_Read => Name,
Aspect_Shared => Optional,
Aspect_Size => Expression,
Aspect_Storage_Pool => Name,
Aspect_Storage_Size => Expression,
Aspect_Stream_Size => Expression,
Aspect_Suppress => Name,
Aspect_Suppress_Debug_Info => Optional,
Aspect_Unchecked_Union => Optional,
Aspect_Universal_Aliasing => Optional,
Aspect_Unmodified => Optional,
Aspect_Unreferenced => Optional,
Aspect_Unreferenced_Objects => Optional,
Aspect_Unsuppress => Name,
Aspect_Value_Size => Expression,
Aspect_Volatile => Optional,
Aspect_Volatile_Components => Optional,
Aspect_Warnings => Name,
Aspect_Write => Name);
function Get_Aspect_Id (Name : Name_Id) return Aspect_Id;
pragma Inline (Get_Aspect_Id);
-- Given a name Nam, returns the corresponding aspect id value. If the name
-- does not match any aspect, then No_Aspect is returned as the result.
---------------------------------------------------
-- Handling of Aspect Specifications in the Tree --
---------------------------------------------------
-- Several kinds of declaration node permit aspect specifications in Ada
-- 2012 mode. If there was room in all the corresponding declaration nodes,
-- we could just have a field Aspect_Specifications pointing to a list of
-- nodes for the aspects (N_Aspect_Specification nodes). But there isn't
-- room, so we adopt a different approach.
-- The following subprograms provide access to a specialized interface
-- implemented internally with a hash table in the body, that provides
-- access to aspect specifications.
function Permits_Aspect_Specifications (N : Node_Id) return Boolean;
-- Returns True if the node N is a declaration node that permits aspect
-- specifications in the grammar. It is possible for other nodes to have
-- aspect specifications as a result of Rewrite or Replace calls.
function Aspect_Specifications (N : Node_Id) return List_Id;
-- Given a node N, returns the list of N_Aspect_Specification nodes that
-- are attached to this declaration node. If the node is in the class of
-- declaration nodes that permit aspect specifications, as defined by the
-- predicate above, and if their Has_Aspects flag is set to True, then this
-- will always be a non-empty list. If this flag is set to False, then
-- No_List is returned. Normally, the only nodes that have Has_Aspects set
-- True are the nodes for which Permits_Aspect_Specifications would return
-- True (i.e. the declaration nodes defined in the RM as permitting the
-- presence of Aspect_Specifications). However, it is possible for the
-- flag Has_Aspects to be set on other nodes as a result of Rewrite and
-- Replace calls, and this function may be used to retrieve the aspect
-- specifications for the original rewritten node in such cases.
procedure Set_Aspect_Specifications (N : Node_Id; L : List_Id);
-- The node N must be in the class of declaration nodes that permit aspect
-- specifications and the Has_Aspects flag must be False on entry. L must
-- be a non-empty list of N_Aspect_Specification nodes. This procedure sets
-- the Has_Aspects flag to True, and makes an entry that can be retrieved
-- by a subsequent Aspect_Specifications call. It is an error to call this
-- procedure with a node that does not permit aspect specifications, or a
-- node that has its Has_Aspects flag set True on entry, or with L being an
-- empty list or No_List.
procedure Move_Aspects (From : Node_Id; To : Node_Id);
-- Moves aspects from 'From' node to 'To' node. Has_Aspects (To) must be
-- False on entry. If Has_Aspects (From) is False, the call has no effect.
-- Otherwise the aspects are moved and on return Has_Aspects (To) is True,
-- and Has_Aspects (From) is False.
procedure Tree_Write;
-- Writes contents of Aspect_Specifications hash table to the tree file
procedure Tree_Read;
-- Reads contents of Aspect_Specifications hash table from the tree file
end Aspects;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- Copyright (C) 2012-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. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This procedure is tailored for the STM32L5xx boards. It configures the
-- system for the maximum clock frequency of 110MHz.
pragma Suppress (All_Checks);
-- The procedure is called before the Ada runtime is initialized, so suppress
-- any runtime checks.
with Interfaces.STM32; use Interfaces, Interfaces.STM32;
with Interfaces.STM32.Flash; use Interfaces.STM32.Flash;
with Interfaces.STM32.RCC; use Interfaces.STM32.RCC;
with Interfaces.STM32.PWR; use Interfaces.STM32.PWR;
with System.BB.MCU_Parameters;
with System.BB.Board_Parameters; use System.BB.Board_Parameters;
with System.STM32; use System.STM32;
procedure Setup_PLL is
-- PLL parameters. STMCubeMX can be used to calculate these parameters for
-- a given clock source and the desired output frequency. Here the PLLCLK
-- and PPLQ is configured to 110 MHz while PLLP is configured 31.4 MHz
PLLM : constant := 12;
PLLN : constant := 55;
PLLP : constant := 7;
PLLQ : constant := 2;
PLLR : constant := 2;
SysClock_From_PLL : constant := SYSCLK_Source'Enum_Rep (SYSCLK_SRC_PLL);
RCC_PLL_Source_MSI : constant UInt2 := PLL_Source'Enum_Rep (PLL_SRC_MSI);
procedure Configure_RCC_Clocks;
-- Initialize the HCLK, SYSCLK, AHB and APB bus clocks. SYSCLK source is
-- the PLL. AHB and APB bus clocks are at max speed.
procedure Reset_Clocks;
procedure Enable_PWR_Clock;
procedure Disable_Backup_Domain_Protection;
procedure Configure_RCC_LSE_Drive_Low;
-- Set the External Low Speed oscillator (LSE) drive to Low
procedure Enable_LSE;
-- When configured in PLL-mode, the MSI automatically calibrates itself
-- via the LSE to better than +/- 0.25% accuracy. We enable the LSE
-- accordingly. See RM0438 Rev 6 pg 333/2194, section 9.3.3 "MSI
-- clock" LSESYSEN is disabled.
procedure Configure_HSI;
-- Enable the HSI and apply the calibration default
procedure Configure_MSI_To_Max_Speed;
-- Set up the multispeed internal oscillator to 48MHz so that it can feed
-- the main PLL to run the system at the maximum speed of 110 MHz. Sets the
-- FLASH latency from the contant declared in BB.Board_Parameters.
procedure Configure_PLL_From_MSI;
-- Set up the PLL driven by the MSI internal oscillator to run the system
-- at the maximum speed of 110 MHz
procedure Enable_MSI_PLL_Mode;
-- Enable MSI Auto calibration
procedure Select_Output_Voltage_Scale0;
-- Configure the main internal regulator output voltage for high
-- performance
procedure Configure_SYSCLK_From_PLL;
-- Set the system clock source to the PLL
procedure Configure_PCLK1_PCLK2;
-- Configure both AHB and APB clocks to run at max speed
procedure Await_PLL_Configuration_Complete;
procedure Await_Voltage_Supply_Scaling_Complete;
--------------------------
-- Configure_RCC_Clocks --
--------------------------
procedure Configure_RCC_Clocks is
begin
-- To correctly read data from FLASH memory, the number of wait states
-- (LATENCY) must be correctly programmed according to the frequency of
-- the CPU clock (HCLK) and the supply voltage of the device.
-- Increase the number of wait states if higher CPU frequency
if FLASH_Latency > FLASH_Periph.ACR.LATENCY then
FLASH_Periph.ACR.LATENCY := FLASH_Latency;
pragma Assert (FLASH_Periph.ACR.LATENCY = FLASH_Latency);
end if;
-- The PLL must be ready before we can configure the system clock
if not RCC_Periph.CR.PLLRDY then
raise Program_Error;
end if;
if Computed_SYSCLK_From_PLL > 80_000_000 then
-- Transition state management is required when selecting the PLL as
-- SYSCLK source with a target frequency above 80Mhz. See RM0438 Rev
-- 6, pg 336/2194, section 9.3.9 "System clock (SYSCLK) selection".
RCC_Periph.CFGR.HPRE := AHB_Prescalers'Enum_Rep (RCC_SYSCLK_DIV2);
end if;
Configure_SYSCLK_From_PLL;
-- Configure HCLK prescalar for max speed (110MHz)
RCC_Periph.CFGR.HPRE := AHB_Prescalers'Enum_Rep (RCC_SYSCLK_DIV1);
-- Note that Configure_HCLK happens to set the HPRE back to
-- RCC_SYSCLK_DIV1 in this configuration, thus ending the
-- state transition management section
Configure_PCLK1_PCLK2;
end Configure_RCC_Clocks;
-------------------------------
-- Configure_SYSCLK_From_PLL --
-------------------------------
procedure Configure_SYSCLK_From_PLL is
begin
RCC_Periph.CFGR.SW := SysClock_From_PLL;
-- Wait for clock source to be as requested
loop
exit when RCC_Periph.CFGR.SWS = SysClock_From_PLL;
end loop;
end Configure_SYSCLK_From_PLL;
---------------------------
-- Configure_PCLK1_PCLK2 --
---------------------------
procedure Configure_PCLK1_PCLK2 is
begin
-- In this specific BSP configuration, both APB1CLKDivider and
-- APB2CLKDivider are RCC_HCLK_DIV1.
RCC_Periph.CFGR.PPRE.Arr (1) := APB_Prescalers'Enum_Rep (RCC_HCLK_DIV1);
RCC_Periph.CFGR.PPRE.Arr (2) := APB_Prescalers'Enum_Rep (RCC_HCLK_DIV1);
end Configure_PCLK1_PCLK2;
---------------------------------
-- Configure_RCC_LSE_Drive_Low --
---------------------------------
procedure Configure_RCC_LSE_Drive_Low is
RCC_LSE_Drive_Low : constant UInt2 := 0;
begin
Disable_Backup_Domain_Protection;
-- Configure the External Low Speed oscillator (LSE) drive
RCC_Periph.BDCR.LSEDRV := RCC_LSE_Drive_Low;
end Configure_RCC_LSE_Drive_Low;
----------------------------
-- Configure_PLL_From_MSI --
----------------------------
procedure Configure_PLL_From_MSI is
begin
-- see RM0438 Rev 6, pg 334/2194 , section 9.3.5 PLL for the steps
-- required to configure the PLL
-- Disable the main PLL before configuring it
RCC_Periph.CR.PLLON := False;
loop
exit when not RCC_Periph.CR.PLLRDY;
end loop;
RCC_Periph.PLLCFGR :=
(PLLM => PLLM - 1, -- handle the encoding
PLLN => PLLN,
PLLPDIV => PLLP,
PLLQ => PLLQ / 2 - 1, -- handle the encoding
PLLR => PLLR / 2 - 1, -- handle the encoding
PLLSRC => RCC_PLL_Source_MSI,
others => <>);
-- Enable the main PLL
RCC_Periph.CR.PLLON := True;
-- Enable PLL System Clock output
RCC_Periph.PLLCFGR.PLLREN := True;
-- Wait until the PLL is ready
loop
exit when RCC_Periph.CR.PLLRDY;
end loop;
end Configure_PLL_From_MSI;
-------------------------
-- Enable_MSI_PLL_Mode --
-------------------------
procedure Enable_MSI_PLL_Mode is
begin
-- MSIPLLEN must be enabled after LSE is enabled (LSEON enabled) and
-- ready (LSERDY set by hardware). There is a hardware protection to
-- avoid enabling MSIPLLEN if LSE is not ready. This bit is cleared by
-- hardware when LSE is disabled (LSEON = 0) or when the Clock Security
-- System on LSE detects a LSE failure (refer to RCC_CSR register in
-- RM0438 Rev 6 pg 350/2194).
if RCC_Periph.BDCR.LSECSSD -- failure detected on LSE
or else not RCC_Periph.BDCR.LSEON
or else not RCC_Periph.BDCR.LSERDY
then
raise Program_Error;
end if;
RCC_Periph.CR.MSIPLLEN := True;
end Enable_MSI_PLL_Mode;
--------------------------------
-- Configure_MSI_To_Max_Speed --
--------------------------------
procedure Configure_MSI_To_Max_Speed is
-- RM0438, section 9.3 "Clocks" says that the MSI is used as system
-- clock source after startup from reset, configured at 4 MHz. We
-- reconfigure it to 48MHz.
MSI_Range_11 : constant := 2#1011#;
-- 48 MHz. See RM0438 Rev 6, page 349/2194
MSI_Range_From_RCC_CR : constant Boolean := True;
-- MSI Range is provided by MSIRANGE[3:0] in the RCC_CR register, as per
-- RM0438 Rev 6 pg 349/2194. It can also be set by another register but
-- not to 48MHz.
RCC_MSI_Calibration_Default : constant Byte := 0;
begin
-- Note: Warning: MSIRANGE can be modified when MSI is OFF (MSION=0)
-- or when MSI is ready (MSIRDY=1). MSIRANGE must NOT be modified when
-- MSI is ON and NOT ready (MSION=1 and MSIRDY=0). We document the
-- requirement with an assertion.
pragma Assert (not RCC_Periph.CR.MSION or else RCC_Periph.CR.MSIRDY);
-- To correctly read data from FLASH memory, the number of wait states
-- (latency) must be correctly programmed according to the frequency of
-- the CPU clock and the supply voltage of the device.
--
-- See RM0438 Rev 6, pg 180/2194, "Increasing the CPU frequency" for the
-- steps required
--
-- We are executing at powerup, at which point the MSI clock is at 4MHz
-- with zero wait states, and we are setting it to 48MHz.
--
-- Therefore, we first increase the number of wait states, if necessary:
FLASH_Periph.ACR.LATENCY := FLASH_Latency;
-- Select the Multiple Speed oscillator (MSI) clock range
RCC_Periph.CR.MSIRGSEL := MSI_Range_From_RCC_CR;
RCC_Periph.CR.MSIRANGE := MSI_Range_11;
-- Finally adjust the MSI calibration value
RCC_Periph.ICSCR.MSITRIM := RCC_MSI_Calibration_Default;
-- Check that the new number of wait states is taken into account. We
-- document the requirement with an assertion.
pragma Assert (FLASH_Periph.ACR.LATENCY = FLASH_Latency);
end Configure_MSI_To_Max_Speed;
--------------------------------------
-- Disable_Backup_Domain_Protection --
--------------------------------------
procedure Disable_Backup_Domain_Protection is
-- Note that when the "Disable Backup domain write Protection" bit is
-- set, access is enabled.
begin
PWR_Periph.CR1.DBP := True;
-- Wait for protection to be disabled
loop
exit when PWR_Periph.CR1.DBP;
end loop;
end Disable_Backup_Domain_Protection;
----------------
-- Enable_LSE --
----------------
procedure Enable_LSE is
begin
if not PWR_Periph.CR1.DBP then
Disable_Backup_Domain_Protection;
end if;
RCC_Periph.BDCR.LSEON := True;
loop
exit when RCC_Periph.BDCR.LSERDY;
end loop;
RCC_Periph.BDCR.LSESYSEN := False;
-- Wait until LSESYSRDY is cleared
loop
exit when not RCC_Periph.BDCR.LSESYSRDY;
end loop;
end Enable_LSE;
-------------------
-- Configure_HSI --
-------------------
procedure Configure_HSI is
RCC_HSICALIBRATION_DEFAULT : constant UInt7 := 40;
begin
-- Enable the Internal High Speed oscillator
RCC_Periph.CR.HSION := True;
-- Wait till HSI is ready
loop
exit when RCC_Periph.CR.HSIRDY;
end loop;
-- Adjust the Internal High Speed oscillator (HSI) calibration value
RCC_Periph.ICSCR.HSITRIM := RCC_HSICALIBRATION_DEFAULT;
end Configure_HSI;
-------------------------------------------------
-- Configure_Internal_Regulator_Output_Voltage --
-------------------------------------------------
procedure Select_Output_Voltage_Scale0 is
PWR_REGULATOR_VOLTAGE_SCALE0 : constant UInt2 := 0;
-- Allow 110MHz. At power-on reset or a system reset, the main regulator
-- voltage Range 2 is selected by default. The system clock is limited
-- to 110 MHz in Range 0 mode, 80 MHz in Range 1 mode, 26 MHz in Range
-- 2 mode, therefore we want Range 0.
begin
-- VOS shall not be changed in Low Power Mode, or if Low Power Mode is
-- requested but not yet established.
pragma Assert (PWR_Periph.SR1.SMPSHPRDY and -- High-power mode ready
not PWR_Periph.CR4.SMPSLPEN); -- Low-power mode enabled
PWR_Periph.CR1.VOS := PWR_REGULATOR_VOLTAGE_SCALE0;
Await_VOSF_Cleared : declare
At_Least_Once : Boolean := False;
begin
loop
exit when At_Least_Once and then PWR_Periph.SR2.VOSF;
At_Least_Once := True;
end loop;
end Await_VOSF_Cleared;
end Select_Output_Voltage_Scale0;
------------------
-- Reset_Clocks --
------------------
procedure Reset_Clocks is
begin
-- Switch on high speed internal clock
RCC_Periph.CR.HSION := True;
-- Reset CFGR register
RCC_Periph.CFGR := (others => <>);
-- Reset HSEON, CSSON and PLLON bits
RCC_Periph.CR.HSEON := False;
RCC_Periph.CR.CSSON := False;
RCC_Periph.CR.PLLON := False;
-- Reset PLL configuration register
RCC_Periph.PLLCFGR := (others => <>);
-- Reset HSE bypass bit
RCC_Periph.CR.HSEBYP := False;
-- Disable all interrupts
RCC_Periph.CIER := (others => <>);
end Reset_Clocks;
----------------------
-- Enable_PWR_Clock --
----------------------
procedure Enable_PWR_Clock is
Temp : Boolean
with Volatile, Unreferenced; -- Ensure the compiler actually reads it
begin
RCC_Periph.APB1ENR1.PWREN := True;
-- As per __HAL_RCC_PWR_CLK_ENABLE()
Temp := RCC_Periph.APB1ENR1.PWREN;
end Enable_PWR_Clock;
--------------------------------------
-- Await_PLL_Configuration_Complete --
--------------------------------------
procedure Await_PLL_Configuration_Complete is
begin
loop
exit when RCC_Periph.CFGR.SWS = SysClock_From_PLL;
end loop;
end Await_PLL_Configuration_Complete;
-------------------------------------------
-- Await_Voltage_Supply_Scaling_Complete --
-------------------------------------------
procedure Await_Voltage_Supply_Scaling_Complete is
begin
loop
exit when System.BB.MCU_Parameters.Is_PWR_Stabilized;
end loop;
end Await_Voltage_Supply_Scaling_Complete;
begin
Reset_Clocks;
Enable_PWR_Clock;
-- Reset the power interface
RCC_Periph.APB1RSTR1.PWRRST := True;
RCC_Periph.APB1RSTR1.PWRRST := False;
Select_Output_Voltage_Scale0;
Configure_RCC_LSE_Drive_Low;
-- Configure the MSI, HSI, LSE, and PLL. The PLL is clocked from MSI, which
-- is configured to run at 48 MHz. The PLL outputs PLLCLK and PPLQ are
-- configured to 110 MHz while PLLP is configured 31.4 MHz.
Configure_MSI_To_Max_Speed;
Configure_HSI;
Enable_LSE;
Configure_PLL_From_MSI;
Configure_RCC_Clocks;
Enable_MSI_PLL_Mode;
Await_PLL_Configuration_Complete;
Await_Voltage_Supply_Scaling_Complete;
end Setup_PLL;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- L I B . X R E F . S P A R K _ S P E C I F I C --
-- --
-- B o d y --
-- --
-- Copyright (C) 2011-2016, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING3. If not, go to --
-- http://www.gnu.org/licenses for a complete copy of the license. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Einfo; use Einfo;
with Nmake; use Nmake;
with SPARK_Xrefs; use SPARK_Xrefs;
with GNAT.HTable;
separate (Lib.Xref)
package body SPARK_Specific is
---------------------
-- Local Constants --
---------------------
-- Table of SPARK_Entities, True for each entity kind used in SPARK
SPARK_Entities : constant array (Entity_Kind) of Boolean :=
(E_Constant => True,
E_Entry => True,
E_Function => True,
E_In_Out_Parameter => True,
E_In_Parameter => True,
E_Loop_Parameter => True,
E_Operator => True,
E_Out_Parameter => True,
E_Procedure => True,
E_Variable => True,
others => False);
-- True for each reference type used in SPARK
SPARK_References : constant array (Character) of Boolean :=
('m' => True,
'r' => True,
's' => True,
others => False);
type Entity_Hashed_Range is range 0 .. 255;
-- Size of hash table headers
---------------------
-- Local Variables --
---------------------
Heap : Entity_Id := Empty;
-- A special entity which denotes the heap object
package Drefs is new Table.Table (
Table_Component_Type => Xref_Entry,
Table_Index_Type => Xref_Entry_Number,
Table_Low_Bound => 1,
Table_Initial => Alloc.Drefs_Initial,
Table_Increment => Alloc.Drefs_Increment,
Table_Name => "Drefs");
-- Table of cross-references for reads and writes through explicit
-- dereferences, that are output as reads/writes to the special variable
-- "Heap". These references are added to the regular references when
-- computing SPARK cross-references.
-----------------------
-- Local Subprograms --
-----------------------
procedure Add_SPARK_File (Uspec, Ubody : Unit_Number_Type; Dspec : Nat);
-- Add file and corresponding scopes for unit to the tables
-- SPARK_File_Table and SPARK_Scope_Table. When two units are present
-- for the same compilation unit, as it happens for library-level
-- instantiations of generics, then Ubody is the number of the body
-- unit; otherwise it is No_Unit.
procedure Add_SPARK_Xrefs;
-- Filter table Xrefs to add all references used in SPARK to the table
-- SPARK_Xref_Table.
function Entity_Hash (E : Entity_Id) return Entity_Hashed_Range;
-- Hash function for hash table
--------------------
-- Add_SPARK_File --
--------------------
procedure Add_SPARK_File (Uspec, Ubody : Unit_Number_Type; Dspec : Nat) is
File : constant Source_File_Index := Source_Index (Uspec);
From : constant Scope_Index := SPARK_Scope_Table.Last + 1;
Scope_Id : Pos := 1;
procedure Add_SPARK_Scope (N : Node_Id);
-- Add scope N to the table SPARK_Scope_Table
procedure Detect_And_Add_SPARK_Scope (N : Node_Id);
-- Call Add_SPARK_Scope on scopes
---------------------
-- Add_SPARK_Scope --
---------------------
procedure Add_SPARK_Scope (N : Node_Id) is
E : constant Entity_Id := Defining_Entity (N);
Loc : constant Source_Ptr := Sloc (E);
-- The character describing the kind of scope is chosen to be the
-- same as the one describing the corresponding entity in cross
-- references, see Xref_Entity_Letters in lib-xrefs.ads
Typ : Character;
begin
-- Ignore scopes without a proper location
if Sloc (N) = No_Location then
return;
end if;
case Ekind (E) is
when E_Entry
| E_Entry_Family
| E_Generic_Function
| E_Generic_Package
| E_Generic_Procedure
| E_Package
| E_Protected_Type
| E_Task_Type
=>
Typ := Xref_Entity_Letters (Ekind (E));
when E_Function
| E_Procedure
=>
-- In SPARK we need to distinguish protected functions and
-- procedures from ordinary subprograms, but there are no
-- special Xref letters for them. Since this distiction is
-- only needed to detect protected calls, we pretend that
-- such calls are entry calls.
if Ekind (Scope (E)) = E_Protected_Type then
Typ := Xref_Entity_Letters (E_Entry);
else
Typ := Xref_Entity_Letters (Ekind (E));
end if;
when E_Package_Body
| E_Protected_Body
| E_Subprogram_Body
| E_Task_Body
=>
Typ := Xref_Entity_Letters (Ekind (Unique_Entity (E)));
when E_Void =>
-- Compilation of prj-attr.adb with -gnatn creates a node with
-- entity E_Void for the package defined at a-charac.ads16:13.
-- ??? TBD
return;
when others =>
raise Program_Error;
end case;
-- File_Num and Scope_Num are filled later. From_Xref and To_Xref
-- are filled even later, but are initialized to represent an empty
-- range.
SPARK_Scope_Table.Append
((Scope_Name => new String'(Unique_Name (E)),
File_Num => Dspec,
Scope_Num => Scope_Id,
Spec_File_Num => 0,
Spec_Scope_Num => 0,
Line => Nat (Get_Logical_Line_Number (Loc)),
Stype => Typ,
Col => Nat (Get_Column_Number (Loc)),
From_Xref => 1,
To_Xref => 0,
Scope_Entity => E));
Scope_Id := Scope_Id + 1;
end Add_SPARK_Scope;
--------------------------------
-- Detect_And_Add_SPARK_Scope --
--------------------------------
procedure Detect_And_Add_SPARK_Scope (N : Node_Id) is
begin
-- Entries
if Nkind_In (N, N_Entry_Body, N_Entry_Declaration)
-- Packages
or else Nkind_In (N, N_Package_Body,
N_Package_Body_Stub,
N_Package_Declaration)
-- Protected units
or else Nkind_In (N, N_Protected_Body,
N_Protected_Body_Stub,
N_Protected_Type_Declaration)
-- Subprograms
or else Nkind_In (N, N_Subprogram_Body,
N_Subprogram_Body_Stub,
N_Subprogram_Declaration)
-- Task units
or else Nkind_In (N, N_Task_Body,
N_Task_Body_Stub,
N_Task_Type_Declaration)
then
Add_SPARK_Scope (N);
end if;
end Detect_And_Add_SPARK_Scope;
procedure Traverse_Scopes is new
Traverse_Compilation_Unit (Detect_And_Add_SPARK_Scope);
-- Local variables
File_Name : String_Ptr;
Unit_File_Name : String_Ptr;
-- Start of processing for Add_SPARK_File
begin
-- Source file could be inexistant as a result of an error, if option
-- gnatQ is used.
if File = No_Source_File then
return;
end if;
-- Subunits are traversed as part of the top-level unit to which they
-- belong.
if Nkind (Unit (Cunit (Uspec))) = N_Subunit then
return;
end if;
Traverse_Scopes (CU => Cunit (Uspec), Inside_Stubs => True);
-- When two units are present for the same compilation unit, as it
-- happens for library-level instantiations of generics, then add all
-- scopes to the same SPARK file.
if Ubody /= No_Unit then
Traverse_Scopes (CU => Cunit (Ubody), Inside_Stubs => True);
end if;
-- Make entry for new file in file table
Get_Name_String (Reference_Name (File));
File_Name := new String'(Name_Buffer (1 .. Name_Len));
-- For subunits, also retrieve the file name of the unit. Only do so if
-- unit has an associated compilation unit.
if Present (Cunit (Unit (File)))
and then Nkind (Unit (Cunit (Unit (File)))) = N_Subunit
then
Get_Name_String (Reference_Name (Main_Source_File));
Unit_File_Name := new String'(Name_Buffer (1 .. Name_Len));
else
Unit_File_Name := null;
end if;
SPARK_File_Table.Append (
(File_Name => File_Name,
Unit_File_Name => Unit_File_Name,
File_Num => Dspec,
From_Scope => From,
To_Scope => SPARK_Scope_Table.Last));
end Add_SPARK_File;
---------------------
-- Add_SPARK_Xrefs --
---------------------
procedure Add_SPARK_Xrefs is
function Entity_Of_Scope (S : Scope_Index) return Entity_Id;
-- Return the entity which maps to the input scope index
function Get_Entity_Type (E : Entity_Id) return Character;
-- Return a character representing the type of entity
function Get_Scope_Num (N : Entity_Id) return Nat;
-- Return the scope number associated to entity N
function Is_Constant_Object_Without_Variable_Input
(E : Entity_Id) return Boolean;
-- Return True if E is known to have no variable input, as defined in
-- SPARK RM.
function Is_Future_Scope_Entity
(E : Entity_Id;
S : Scope_Index) return Boolean;
-- Check whether entity E is in SPARK_Scope_Table at index S or higher
function Is_SPARK_Reference
(E : Entity_Id;
Typ : Character) return Boolean;
-- Return whether entity reference E meets SPARK requirements. Typ is
-- the reference type.
function Is_SPARK_Scope (E : Entity_Id) return Boolean;
-- Return whether the entity or reference scope meets requirements for
-- being a SPARK scope.
function Lt (Op1 : Natural; Op2 : Natural) return Boolean;
-- Comparison function for Sort call
procedure Move (From : Natural; To : Natural);
-- Move procedure for Sort call
procedure Set_Scope_Num (N : Entity_Id; Num : Nat);
-- Associate entity N to scope number Num
procedure Update_Scope_Range
(S : Scope_Index;
From : Xref_Index;
To : Xref_Index);
-- Update the scope which maps to S with the new range From .. To
package Sorting is new GNAT.Heap_Sort_G (Move, Lt);
No_Scope : constant Nat := 0;
-- Initial scope counter
type Scope_Rec is record
Num : Nat;
Entity : Entity_Id;
end record;
-- Type used to relate an entity and a scope number
package Scopes is new GNAT.HTable.Simple_HTable
(Header_Num => Entity_Hashed_Range,
Element => Scope_Rec,
No_Element => (Num => No_Scope, Entity => Empty),
Key => Entity_Id,
Hash => Entity_Hash,
Equal => "=");
-- Package used to build a correspondence between entities and scope
-- numbers used in SPARK cross references.
Nrefs : Nat := Xrefs.Last;
-- Number of references in table. This value may get reset (reduced)
-- when we eliminate duplicate reference entries as well as references
-- not suitable for local cross-references.
Nrefs_Add : constant Nat := Drefs.Last;
-- Number of additional references which correspond to dereferences in
-- the source code.
Rnums : array (0 .. Nrefs + Nrefs_Add) of Nat;
-- This array contains numbers of references in the Xrefs table. This
-- list is sorted in output order. The extra 0'th entry is convenient
-- for the call to sort. When we sort the table, we move the indices in
-- Rnums around, but we do not move the original table entries.
---------------------
-- Entity_Of_Scope --
---------------------
function Entity_Of_Scope (S : Scope_Index) return Entity_Id is
begin
return SPARK_Scope_Table.Table (S).Scope_Entity;
end Entity_Of_Scope;
---------------------
-- Get_Entity_Type --
---------------------
function Get_Entity_Type (E : Entity_Id) return Character is
begin
case Ekind (E) is
when E_Out_Parameter => return '<';
when E_In_Out_Parameter => return '=';
when E_In_Parameter => return '>';
when others => return '*';
end case;
end Get_Entity_Type;
-------------------
-- Get_Scope_Num --
-------------------
function Get_Scope_Num (N : Entity_Id) return Nat is
begin
return Scopes.Get (N).Num;
end Get_Scope_Num;
-----------------------------------------------
-- Is_Constant_Object_Without_Variable_Input --
-----------------------------------------------
function Is_Constant_Object_Without_Variable_Input
(E : Entity_Id) return Boolean
is
Result : Boolean;
begin
case Ekind (E) is
-- A constant is known to have no variable input if its
-- initializing expression is static (a value which is
-- compile-time-known is not guaranteed to have no variable input
-- as defined in the SPARK RM). Otherwise, the constant may or not
-- have variable input.
when E_Constant =>
declare
Decl : Node_Id;
begin
if Present (Full_View (E)) then
Decl := Parent (Full_View (E));
else
Decl := Parent (E);
end if;
if Is_Imported (E) then
Result := False;
else
pragma Assert (Present (Expression (Decl)));
Result := Is_Static_Expression (Expression (Decl));
end if;
end;
when E_In_Parameter
| E_Loop_Parameter
=>
Result := True;
when others =>
Result := False;
end case;
return Result;
end Is_Constant_Object_Without_Variable_Input;
----------------------------
-- Is_Future_Scope_Entity --
----------------------------
function Is_Future_Scope_Entity
(E : Entity_Id;
S : Scope_Index) return Boolean
is
function Is_Past_Scope_Entity return Boolean;
-- Check whether entity E is in SPARK_Scope_Table at index strictly
-- lower than S.
--------------------------
-- Is_Past_Scope_Entity --
--------------------------
function Is_Past_Scope_Entity return Boolean is
begin
for Index in SPARK_Scope_Table.First .. S - 1 loop
if SPARK_Scope_Table.Table (Index).Scope_Entity = E then
return True;
end if;
end loop;
return False;
end Is_Past_Scope_Entity;
-- Start of processing for Is_Future_Scope_Entity
begin
for Index in S .. SPARK_Scope_Table.Last loop
if SPARK_Scope_Table.Table (Index).Scope_Entity = E then
return True;
end if;
end loop;
-- If this assertion fails, this means that the scope which we are
-- looking for has been treated already, which reveals a problem in
-- the order of cross-references.
pragma Assert (not Is_Past_Scope_Entity);
return False;
end Is_Future_Scope_Entity;
------------------------
-- Is_SPARK_Reference --
------------------------
function Is_SPARK_Reference
(E : Entity_Id;
Typ : Character) return Boolean
is
begin
-- The only references of interest on callable entities are calls. On
-- uncallable entities, the only references of interest are reads and
-- writes.
if Ekind (E) in Overloadable_Kind then
return Typ = 's';
-- In all other cases, result is true for reference/modify cases,
-- and false for all other cases.
else
return Typ = 'r' or else Typ = 'm';
end if;
end Is_SPARK_Reference;
--------------------
-- Is_SPARK_Scope --
--------------------
function Is_SPARK_Scope (E : Entity_Id) return Boolean is
begin
return Present (E)
and then not Is_Generic_Unit (E)
and then Renamed_Entity (E) = Empty
and then Get_Scope_Num (E) /= No_Scope;
end Is_SPARK_Scope;
--------
-- Lt --
--------
function Lt (Op1 : Natural; Op2 : Natural) return Boolean is
T1 : constant Xref_Entry := Xrefs.Table (Rnums (Nat (Op1)));
T2 : constant Xref_Entry := Xrefs.Table (Rnums (Nat (Op2)));
begin
-- First test: if entity is in different unit, sort by unit. Note:
-- that we use Ent_Scope_File rather than Eun, as Eun may refer to
-- the file where the generic scope is defined, which may differ from
-- the file where the enclosing scope is defined. It is the latter
-- which matters for a correct order here.
if T1.Ent_Scope_File /= T2.Ent_Scope_File then
return Dependency_Num (T1.Ent_Scope_File) <
Dependency_Num (T2.Ent_Scope_File);
-- Second test: within same unit, sort by location of the scope of
-- the entity definition.
elsif Get_Scope_Num (T1.Key.Ent_Scope) /=
Get_Scope_Num (T2.Key.Ent_Scope)
then
return Get_Scope_Num (T1.Key.Ent_Scope) <
Get_Scope_Num (T2.Key.Ent_Scope);
-- Third test: within same unit and scope, sort by location of
-- entity definition.
elsif T1.Def /= T2.Def then
return T1.Def < T2.Def;
else
-- Both entities must be equal at this point
pragma Assert (T1.Key.Ent = T2.Key.Ent);
pragma Assert (T1.Key.Ent_Scope = T2.Key.Ent_Scope);
pragma Assert (T1.Ent_Scope_File = T2.Ent_Scope_File);
-- Fourth test: if reference is in same unit as entity definition,
-- sort first.
if T1.Key.Lun /= T2.Key.Lun
and then T1.Ent_Scope_File = T1.Key.Lun
then
return True;
elsif T1.Key.Lun /= T2.Key.Lun
and then T2.Ent_Scope_File = T2.Key.Lun
then
return False;
-- Fifth test: if reference is in same unit and same scope as
-- entity definition, sort first.
elsif T1.Ent_Scope_File = T1.Key.Lun
and then T1.Key.Ref_Scope /= T2.Key.Ref_Scope
and then T1.Key.Ent_Scope = T1.Key.Ref_Scope
then
return True;
elsif T2.Ent_Scope_File = T2.Key.Lun
and then T1.Key.Ref_Scope /= T2.Key.Ref_Scope
and then T2.Key.Ent_Scope = T2.Key.Ref_Scope
then
return False;
-- Sixth test: for same entity, sort by reference location unit
elsif T1.Key.Lun /= T2.Key.Lun then
return Dependency_Num (T1.Key.Lun) <
Dependency_Num (T2.Key.Lun);
-- Seventh test: for same entity, sort by reference location scope
elsif Get_Scope_Num (T1.Key.Ref_Scope) /=
Get_Scope_Num (T2.Key.Ref_Scope)
then
return Get_Scope_Num (T1.Key.Ref_Scope) <
Get_Scope_Num (T2.Key.Ref_Scope);
-- Eighth test: order of location within referencing unit
elsif T1.Key.Loc /= T2.Key.Loc then
return T1.Key.Loc < T2.Key.Loc;
-- Finally, for two locations at the same address prefer the one
-- that does NOT have the type 'r', so that a modification or
-- extension takes preference, when there are more than one
-- reference at the same location. As a result, in the case of
-- entities that are in-out actuals, the read reference follows
-- the modify reference.
else
return T2.Key.Typ = 'r';
end if;
end if;
end Lt;
----------
-- Move --
----------
procedure Move (From : Natural; To : Natural) is
begin
Rnums (Nat (To)) := Rnums (Nat (From));
end Move;
-------------------
-- Set_Scope_Num --
-------------------
procedure Set_Scope_Num (N : Entity_Id; Num : Nat) is
begin
Scopes.Set (K => N, E => Scope_Rec'(Num => Num, Entity => N));
end Set_Scope_Num;
------------------------
-- Update_Scope_Range --
------------------------
procedure Update_Scope_Range
(S : Scope_Index;
From : Xref_Index;
To : Xref_Index)
is
begin
SPARK_Scope_Table.Table (S).From_Xref := From;
SPARK_Scope_Table.Table (S).To_Xref := To;
end Update_Scope_Range;
-- Local variables
Col : Nat;
From_Index : Xref_Index;
Line : Nat;
Prev_Loc : Source_Ptr;
Prev_Typ : Character;
Ref_Count : Nat;
Ref_Id : Entity_Id;
Ref_Name : String_Ptr;
Scope_Id : Scope_Index;
-- Start of processing for Add_SPARK_Xrefs
begin
for Index in SPARK_Scope_Table.First .. SPARK_Scope_Table.Last loop
declare
S : SPARK_Scope_Record renames SPARK_Scope_Table.Table (Index);
begin
Set_Scope_Num (S.Scope_Entity, S.Scope_Num);
end;
end loop;
declare
Drefs_Table : Drefs.Table_Type
renames Drefs.Table (Drefs.First .. Drefs.Last);
begin
Xrefs.Append_All (Xrefs.Table_Type (Drefs_Table));
Nrefs := Nrefs + Drefs_Table'Length;
end;
-- Capture the definition Sloc values. As in the case of normal cross
-- references, we have to wait until now to get the correct value.
for Index in 1 .. Nrefs loop
Xrefs.Table (Index).Def := Sloc (Xrefs.Table (Index).Key.Ent);
end loop;
-- Eliminate entries not appropriate for SPARK. Done prior to sorting
-- cross-references, as it discards useless references which do not have
-- a proper format for the comparison function (like no location).
Ref_Count := Nrefs;
Nrefs := 0;
for Index in 1 .. Ref_Count loop
declare
Ref : Xref_Key renames Xrefs.Table (Index).Key;
begin
if SPARK_Entities (Ekind (Ref.Ent))
and then SPARK_References (Ref.Typ)
and then Is_SPARK_Scope (Ref.Ent_Scope)
and then Is_SPARK_Scope (Ref.Ref_Scope)
and then Is_SPARK_Reference (Ref.Ent, Ref.Typ)
-- Discard references from unknown scopes, e.g. generic scopes
and then Get_Scope_Num (Ref.Ent_Scope) /= No_Scope
and then Get_Scope_Num (Ref.Ref_Scope) /= No_Scope
then
Nrefs := Nrefs + 1;
Rnums (Nrefs) := Index;
end if;
end;
end loop;
-- Sort the references
Sorting.Sort (Integer (Nrefs));
-- Eliminate duplicate entries
-- We need this test for Ref_Count because if we force ALI file
-- generation in case of errors detected, it may be the case that
-- Nrefs is 0, so we should not reset it here.
if Nrefs >= 2 then
Ref_Count := Nrefs;
Nrefs := 1;
for Index in 2 .. Ref_Count loop
if Xrefs.Table (Rnums (Index)) /= Xrefs.Table (Rnums (Nrefs)) then
Nrefs := Nrefs + 1;
Rnums (Nrefs) := Rnums (Index);
end if;
end loop;
end if;
-- Eliminate the reference if it is at the same location as the previous
-- one, unless it is a read-reference indicating that the entity is an
-- in-out actual in a call.
Ref_Count := Nrefs;
Nrefs := 0;
Prev_Loc := No_Location;
Prev_Typ := 'm';
for Index in 1 .. Ref_Count loop
declare
Ref : Xref_Key renames Xrefs.Table (Rnums (Index)).Key;
begin
if Ref.Loc /= Prev_Loc
or else (Prev_Typ = 'm' and then Ref.Typ = 'r')
then
Prev_Loc := Ref.Loc;
Prev_Typ := Ref.Typ;
Nrefs := Nrefs + 1;
Rnums (Nrefs) := Rnums (Index);
end if;
end;
end loop;
-- The two steps have eliminated all references, nothing to do
if SPARK_Scope_Table.Last = 0 then
return;
end if;
Ref_Id := Empty;
Scope_Id := 1;
From_Index := 1;
-- Loop to output references
for Refno in 1 .. Nrefs loop
declare
Ref_Entry : Xref_Entry renames Xrefs.Table (Rnums (Refno));
Ref : Xref_Key renames Ref_Entry.Key;
Typ : Character;
begin
-- If this assertion fails, the scope which we are looking for is
-- not in SPARK scope table, which reveals either a problem in the
-- construction of the scope table, or an erroneous scope for the
-- current cross-reference.
pragma Assert (Is_Future_Scope_Entity (Ref.Ent_Scope, Scope_Id));
-- Update the range of cross references to which the current scope
-- refers to. This may be the empty range only for the first scope
-- considered.
if Ref.Ent_Scope /= Entity_Of_Scope (Scope_Id) then
Update_Scope_Range
(S => Scope_Id,
From => From_Index,
To => SPARK_Xref_Table.Last);
From_Index := SPARK_Xref_Table.Last + 1;
end if;
while Ref.Ent_Scope /= Entity_Of_Scope (Scope_Id) loop
Scope_Id := Scope_Id + 1;
pragma Assert (Scope_Id <= SPARK_Scope_Table.Last);
end loop;
if Ref.Ent /= Ref_Id then
Ref_Name := new String'(Unique_Name (Ref.Ent));
end if;
if Ref.Ent = Heap then
Line := 0;
Col := 0;
else
Line := Nat (Get_Logical_Line_Number (Ref_Entry.Def));
Col := Nat (Get_Column_Number (Ref_Entry.Def));
end if;
-- References to constant objects without variable inputs (see
-- SPARK RM 3.3.1) are considered specially in SPARK section,
-- because these will be translated as constants in the
-- intermediate language for formal verification, and should
-- therefore never appear in frame conditions. Other constants may
-- later be treated the same, up to GNATprove to decide based on
-- its flow analysis.
if Is_Constant_Object_Without_Variable_Input (Ref.Ent) then
Typ := 'c';
else
Typ := Ref.Typ;
end if;
SPARK_Xref_Table.Append (
(Entity_Name => Ref_Name,
Entity_Line => Line,
Etype => Get_Entity_Type (Ref.Ent),
Entity_Col => Col,
File_Num => Dependency_Num (Ref.Lun),
Scope_Num => Get_Scope_Num (Ref.Ref_Scope),
Line => Nat (Get_Logical_Line_Number (Ref.Loc)),
Rtype => Typ,
Col => Nat (Get_Column_Number (Ref.Loc))));
end;
end loop;
-- Update the range of cross references to which the scope refers to
Update_Scope_Range
(S => Scope_Id,
From => From_Index,
To => SPARK_Xref_Table.Last);
end Add_SPARK_Xrefs;
-------------------------
-- Collect_SPARK_Xrefs --
-------------------------
procedure Collect_SPARK_Xrefs
(Sdep_Table : Unit_Ref_Table;
Num_Sdep : Nat)
is
Sdep : Pos;
Sdep_Next : Pos;
-- Index of the current and next source dependency
Sdep_File : Pos;
-- Index of the file to which the scopes need to be assigned; for
-- library-level instances of generic units this points to the unit
-- of the body, because this is where references are assigned to.
Ubody : Unit_Number_Type;
Uspec : Unit_Number_Type;
-- Unit numbers for the dependency spec and possibly its body (only in
-- the case of library-level instance of a generic package).
begin
-- Cross-references should have been computed first
pragma Assert (Xrefs.Last /= 0);
Initialize_SPARK_Tables;
-- Generate file and scope SPARK cross-reference information
Sdep := 1;
while Sdep <= Num_Sdep loop
-- Skip dependencies with no entity node, e.g. configuration files
-- with pragmas (.adc) or target description (.atp), since they
-- present no interest for SPARK cross references.
if No (Cunit_Entity (Sdep_Table (Sdep))) then
Sdep_Next := Sdep + 1;
-- For library-level instantiation of a generic, two consecutive
-- units refer to the same compilation unit node and entity (one to
-- body, one to spec). In that case, treat them as a single unit for
-- the sake of SPARK cross references by passing to Add_SPARK_File.
else
if Sdep < Num_Sdep
and then Cunit_Entity (Sdep_Table (Sdep)) =
Cunit_Entity (Sdep_Table (Sdep + 1))
then
declare
Cunit1 : Node_Id renames Cunit (Sdep_Table (Sdep));
Cunit2 : Node_Id renames Cunit (Sdep_Table (Sdep + 1));
begin
-- Both Cunits point to compilation unit nodes
pragma Assert
(Nkind (Cunit1) = N_Compilation_Unit
and then Nkind (Cunit2) = N_Compilation_Unit);
-- Do not depend on the sorting order, which is based on
-- Unit_Name, and for library-level instances of nested
-- generic packages they are equal.
-- If declaration comes before the body
if Nkind (Unit (Cunit1)) = N_Package_Declaration
and then Nkind (Unit (Cunit2)) = N_Package_Body
then
Uspec := Sdep_Table (Sdep);
Ubody := Sdep_Table (Sdep + 1);
Sdep_File := Sdep + 1;
-- If body comes before declaration
elsif Nkind (Unit (Cunit1)) = N_Package_Body
and then Nkind (Unit (Cunit2)) = N_Package_Declaration
then
Uspec := Sdep_Table (Sdep + 1);
Ubody := Sdep_Table (Sdep);
Sdep_File := Sdep;
-- Otherwise it is an error
else
raise Program_Error;
end if;
Sdep_Next := Sdep + 2;
end;
-- ??? otherwise?
else
Uspec := Sdep_Table (Sdep);
Ubody := No_Unit;
Sdep_File := Sdep;
Sdep_Next := Sdep + 1;
end if;
Add_SPARK_File
(Uspec => Uspec,
Ubody => Ubody,
Dspec => Sdep_File);
end if;
Sdep := Sdep_Next;
end loop;
-- Fill in the spec information when relevant
declare
package Entity_Hash_Table is new
GNAT.HTable.Simple_HTable
(Header_Num => Entity_Hashed_Range,
Element => Scope_Index,
No_Element => 0,
Key => Entity_Id,
Hash => Entity_Hash,
Equal => "=");
begin
-- Fill in the hash-table
for S in SPARK_Scope_Table.First .. SPARK_Scope_Table.Last loop
declare
Srec : SPARK_Scope_Record renames SPARK_Scope_Table.Table (S);
begin
Entity_Hash_Table.Set (Srec.Scope_Entity, S);
end;
end loop;
-- Use the hash-table to locate spec entities
for S in SPARK_Scope_Table.First .. SPARK_Scope_Table.Last loop
declare
Srec : SPARK_Scope_Record renames SPARK_Scope_Table.Table (S);
Spec_Entity : constant Entity_Id :=
Unique_Entity (Srec.Scope_Entity);
Spec_Scope : constant Scope_Index :=
Entity_Hash_Table.Get (Spec_Entity);
begin
-- Generic spec may be missing in which case Spec_Scope is zero
if Spec_Entity /= Srec.Scope_Entity
and then Spec_Scope /= 0
then
Srec.Spec_File_Num :=
SPARK_Scope_Table.Table (Spec_Scope).File_Num;
Srec.Spec_Scope_Num :=
SPARK_Scope_Table.Table (Spec_Scope).Scope_Num;
end if;
end;
end loop;
end;
-- Generate SPARK cross-reference information
Add_SPARK_Xrefs;
end Collect_SPARK_Xrefs;
-------------------------------------
-- Enclosing_Subprogram_Or_Package --
-------------------------------------
function Enclosing_Subprogram_Or_Library_Package
(N : Node_Id) return Entity_Id
is
Context : Entity_Id;
begin
-- If N is the defining identifier for a subprogram, then return the
-- enclosing subprogram or package, not this subprogram.
if Nkind_In (N, N_Defining_Identifier, N_Defining_Operator_Symbol)
and then (Ekind (N) in Entry_Kind
or else Ekind (N) = E_Subprogram_Body
or else Ekind (N) in Generic_Subprogram_Kind
or else Ekind (N) in Subprogram_Kind)
then
Context := Parent (Unit_Declaration_Node (N));
-- If this was a library-level subprogram then replace Context with
-- its Unit, which points to N_Subprogram_* node.
if Nkind (Context) = N_Compilation_Unit then
Context := Unit (Context);
end if;
else
Context := N;
end if;
while Present (Context) loop
case Nkind (Context) is
when N_Package_Body
| N_Package_Specification
=>
-- Only return a library-level package
if Is_Library_Level_Entity (Defining_Entity (Context)) then
Context := Defining_Entity (Context);
exit;
else
Context := Parent (Context);
end if;
when N_Pragma =>
-- The enclosing subprogram for a precondition, postcondition,
-- or contract case should be the declaration preceding the
-- pragma (skipping any other pragmas between this pragma and
-- this declaration.
while Nkind (Context) = N_Pragma
and then Is_List_Member (Context)
and then Present (Prev (Context))
loop
Context := Prev (Context);
end loop;
if Nkind (Context) = N_Pragma then
Context := Parent (Context);
end if;
when N_Entry_Body
| N_Entry_Declaration
| N_Protected_Type_Declaration
| N_Subprogram_Body
| N_Subprogram_Declaration
| N_Subprogram_Specification
| N_Task_Body
| N_Task_Type_Declaration
=>
Context := Defining_Entity (Context);
exit;
when others =>
Context := Parent (Context);
end case;
end loop;
if Nkind (Context) = N_Defining_Program_Unit_Name then
Context := Defining_Identifier (Context);
end if;
-- Do not return a scope without a proper location
if Present (Context)
and then Sloc (Context) = No_Location
then
return Empty;
end if;
return Context;
end Enclosing_Subprogram_Or_Library_Package;
-----------------
-- Entity_Hash --
-----------------
function Entity_Hash (E : Entity_Id) return Entity_Hashed_Range is
begin
return
Entity_Hashed_Range (E mod (Entity_Id (Entity_Hashed_Range'Last) + 1));
end Entity_Hash;
--------------------------
-- Generate_Dereference --
--------------------------
procedure Generate_Dereference
(N : Node_Id;
Typ : Character := 'r')
is
procedure Create_Heap;
-- Create and decorate the special entity which denotes the heap
-----------------
-- Create_Heap --
-----------------
procedure Create_Heap is
begin
Name_Len := Name_Of_Heap_Variable'Length;
Name_Buffer (1 .. Name_Len) := Name_Of_Heap_Variable;
Heap := Make_Defining_Identifier (Standard_Location, Name_Enter);
Set_Ekind (Heap, E_Variable);
Set_Is_Internal (Heap, True);
Set_Has_Fully_Qualified_Name (Heap);
end Create_Heap;
-- Local variables
Loc : constant Source_Ptr := Sloc (N);
-- Start of processing for Generate_Dereference
begin
if Loc > No_Location then
Drefs.Increment_Last;
declare
Deref_Entry : Xref_Entry renames Drefs.Table (Drefs.Last);
Deref : Xref_Key renames Deref_Entry.Key;
begin
if No (Heap) then
Create_Heap;
end if;
Deref.Ent := Heap;
Deref.Loc := Loc;
Deref.Typ := Typ;
-- It is as if the special "Heap" was defined in the main unit,
-- in the scope of the entity for the main unit. This single
-- definition point is required to ensure that sorting cross
-- references works for "Heap" references as well.
Deref.Eun := Main_Unit;
Deref.Lun := Get_Top_Level_Code_Unit (Loc);
Deref.Ref_Scope := Enclosing_Subprogram_Or_Library_Package (N);
Deref.Ent_Scope := Cunit_Entity (Main_Unit);
Deref_Entry.Def := No_Location;
Deref_Entry.Ent_Scope_File := Main_Unit;
end;
end if;
end Generate_Dereference;
-------------------------------
-- Traverse_Compilation_Unit --
-------------------------------
procedure Traverse_Compilation_Unit
(CU : Node_Id;
Inside_Stubs : Boolean)
is
procedure Traverse_Block (N : Node_Id);
procedure Traverse_Declaration_Or_Statement (N : Node_Id);
procedure Traverse_Declarations_And_HSS (N : Node_Id);
procedure Traverse_Declarations_Or_Statements (L : List_Id);
procedure Traverse_Handled_Statement_Sequence (N : Node_Id);
procedure Traverse_Package_Body (N : Node_Id);
procedure Traverse_Visible_And_Private_Parts (N : Node_Id);
procedure Traverse_Protected_Body (N : Node_Id);
procedure Traverse_Subprogram_Body (N : Node_Id);
procedure Traverse_Task_Body (N : Node_Id);
-- Traverse corresponding construct, calling Process on all declarations
--------------------
-- Traverse_Block --
--------------------
procedure Traverse_Block (N : Node_Id) renames
Traverse_Declarations_And_HSS;
---------------------------------------
-- Traverse_Declaration_Or_Statement --
---------------------------------------
procedure Traverse_Declaration_Or_Statement (N : Node_Id) is
function Traverse_Stub (N : Node_Id) return Boolean;
-- Returns True iff stub N should be traversed
function Traverse_Stub (N : Node_Id) return Boolean is
begin
pragma Assert (Nkind_In (N, N_Package_Body_Stub,
N_Protected_Body_Stub,
N_Subprogram_Body_Stub,
N_Task_Body_Stub));
return Inside_Stubs and then Present (Library_Unit (N));
end Traverse_Stub;
-- Start of processing for Traverse_Declaration_Or_Statement
begin
case Nkind (N) is
when N_Package_Declaration =>
Traverse_Visible_And_Private_Parts (Specification (N));
when N_Package_Body =>
Traverse_Package_Body (N);
when N_Package_Body_Stub =>
if Traverse_Stub (N) then
Traverse_Package_Body (Get_Body_From_Stub (N));
end if;
when N_Subprogram_Body =>
Traverse_Subprogram_Body (N);
when N_Entry_Body =>
Traverse_Subprogram_Body (N);
when N_Subprogram_Body_Stub =>
if Traverse_Stub (N) then
Traverse_Subprogram_Body (Get_Body_From_Stub (N));
end if;
when N_Protected_Body =>
Traverse_Protected_Body (N);
when N_Protected_Body_Stub =>
if Traverse_Stub (N) then
Traverse_Protected_Body (Get_Body_From_Stub (N));
end if;
when N_Protected_Type_Declaration =>
Traverse_Visible_And_Private_Parts (Protected_Definition (N));
when N_Task_Definition =>
Traverse_Visible_And_Private_Parts (N);
when N_Task_Body =>
Traverse_Task_Body (N);
when N_Task_Body_Stub =>
if Traverse_Stub (N) then
Traverse_Task_Body (Get_Body_From_Stub (N));
end if;
when N_Block_Statement =>
Traverse_Block (N);
when N_If_Statement =>
-- Traverse the statements in the THEN part
Traverse_Declarations_Or_Statements (Then_Statements (N));
-- Loop through ELSIF parts if present
if Present (Elsif_Parts (N)) then
declare
Elif : Node_Id := First (Elsif_Parts (N));
begin
while Present (Elif) loop
Traverse_Declarations_Or_Statements
(Then_Statements (Elif));
Next (Elif);
end loop;
end;
end if;
-- Finally traverse the ELSE statements if present
Traverse_Declarations_Or_Statements (Else_Statements (N));
when N_Case_Statement =>
-- Process case branches
declare
Alt : Node_Id := First (Alternatives (N));
begin
loop
Traverse_Declarations_Or_Statements (Statements (Alt));
Next (Alt);
exit when No (Alt);
end loop;
end;
when N_Extended_Return_Statement =>
Traverse_Handled_Statement_Sequence
(Handled_Statement_Sequence (N));
when N_Loop_Statement =>
Traverse_Declarations_Or_Statements (Statements (N));
-- Generic declarations are ignored
when others =>
null;
end case;
end Traverse_Declaration_Or_Statement;
-----------------------------------
-- Traverse_Declarations_And_HSS --
-----------------------------------
procedure Traverse_Declarations_And_HSS (N : Node_Id) is
begin
Traverse_Declarations_Or_Statements (Declarations (N));
Traverse_Handled_Statement_Sequence (Handled_Statement_Sequence (N));
end Traverse_Declarations_And_HSS;
-----------------------------------------
-- Traverse_Declarations_Or_Statements --
-----------------------------------------
procedure Traverse_Declarations_Or_Statements (L : List_Id) is
N : Node_Id;
begin
-- Loop through statements or declarations
N := First (L);
while Present (N) loop
-- Call Process on all declarations
if Nkind (N) in N_Declaration
or else Nkind (N) in N_Later_Decl_Item
or else Nkind (N) = N_Entry_Body
then
Process (N);
end if;
Traverse_Declaration_Or_Statement (N);
Next (N);
end loop;
end Traverse_Declarations_Or_Statements;
-----------------------------------------
-- Traverse_Handled_Statement_Sequence --
-----------------------------------------
procedure Traverse_Handled_Statement_Sequence (N : Node_Id) is
Handler : Node_Id;
begin
if Present (N) then
Traverse_Declarations_Or_Statements (Statements (N));
if Present (Exception_Handlers (N)) then
Handler := First (Exception_Handlers (N));
while Present (Handler) loop
Traverse_Declarations_Or_Statements (Statements (Handler));
Next (Handler);
end loop;
end if;
end if;
end Traverse_Handled_Statement_Sequence;
---------------------------
-- Traverse_Package_Body --
---------------------------
procedure Traverse_Package_Body (N : Node_Id) is
Spec_E : constant Entity_Id := Unique_Defining_Entity (N);
begin
case Ekind (Spec_E) is
when E_Package =>
Traverse_Declarations_And_HSS (N);
when E_Generic_Package =>
null;
when others =>
raise Program_Error;
end case;
end Traverse_Package_Body;
-----------------------------
-- Traverse_Protected_Body --
-----------------------------
procedure Traverse_Protected_Body (N : Node_Id) is
begin
Traverse_Declarations_Or_Statements (Declarations (N));
end Traverse_Protected_Body;
------------------------------
-- Traverse_Subprogram_Body --
------------------------------
procedure Traverse_Subprogram_Body (N : Node_Id) is
Spec_E : constant Entity_Id := Unique_Defining_Entity (N);
begin
case Ekind (Spec_E) is
when Entry_Kind
| E_Function
| E_Procedure
=>
Traverse_Declarations_And_HSS (N);
when Generic_Subprogram_Kind =>
null;
when others =>
raise Program_Error;
end case;
end Traverse_Subprogram_Body;
------------------------
-- Traverse_Task_Body --
------------------------
procedure Traverse_Task_Body (N : Node_Id) renames
Traverse_Declarations_And_HSS;
----------------------------------------
-- Traverse_Visible_And_Private_Parts --
----------------------------------------
procedure Traverse_Visible_And_Private_Parts (N : Node_Id) is
begin
Traverse_Declarations_Or_Statements (Visible_Declarations (N));
Traverse_Declarations_Or_Statements (Private_Declarations (N));
end Traverse_Visible_And_Private_Parts;
-- Local variables
Lu : Node_Id;
-- Start of processing for Traverse_Compilation_Unit
begin
-- Get Unit (checking case of subunit)
Lu := Unit (CU);
if Nkind (Lu) = N_Subunit then
Lu := Proper_Body (Lu);
end if;
-- Do not add scopes for generic units
if Nkind (Lu) = N_Package_Body
and then Ekind (Corresponding_Spec (Lu)) in Generic_Unit_Kind
then
return;
end if;
-- Call Process on all declarations
if Nkind (Lu) in N_Declaration
or else Nkind (Lu) in N_Later_Decl_Item
then
Process (Lu);
end if;
-- Traverse the unit
Traverse_Declaration_Or_Statement (Lu);
end Traverse_Compilation_Unit;
end SPARK_Specific;
|
with
GL.lean,
GL.Binding,
openGL.Tasks,
openGL.Errors;
package body openGL.Frame_Buffer
is
package body Forge
is
function to_Frame_Buffer (Width,
Height : in Positive) return Item
is
use openGL.Texture,
GL,
GL.Binding,
GL.lean;
Self : Item;
begin
Tasks.check;
Self.Texture := openGL.Texture.Forge.to_Texture (Dimensions' (Width, Height));
glGenFramebuffers (1, Self.Name'Access);
-- Attach each texture to the first color buffer of an frame buffer object and clear it.
--
glBindFramebuffer (GL_FRAMEBUFFER, Self.Name);
glFramebufferTexture2D (GL_FRAMEBUFFER,
GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D,
Self.Texture.Name,
0);
glClear (GL_COLOR_BUFFER_BIT);
glBindFramebuffer (GL_FRAMEBUFFER, 0);
return Self;
end to_frame_Buffer;
function to_Frame_Buffer return Item
is
use openGL.Texture,
GL,
GL.lean;
Self : Item;
begin
Tasks.check;
Self.Texture := openGL.Texture.null_Object;
glGenFramebuffers (1, Self.Name'Access);
return Self;
end to_frame_Buffer;
end Forge;
procedure destruct (Self : in out Item)
is
use GL.lean;
begin
Tasks.check;
glDeleteFramebuffers (1, Self.Name'Access);
Self.Texture.destroy;
end destruct;
--------------
--- Attributes
--
function Name (Self : in Item) return Buffer_Name
is
begin
return Self.Name;
end Name;
function Texture (Self : in Item) return openGL.Texture.Object
is
begin
return Self.Texture;
end Texture;
procedure Texture_is (Self : in out Item; Now : in openGL.Texture.Object)
is
use GL,
GL.Binding,
GL.lean;
begin
Tasks.check;
openGL.Errors.log;
Self.Texture := Now;
-- Attach each texture to the first color buffer of an FBO and clear it.
--
glBindFramebuffer (GL_FRAMEBUFFER, Self.Name);
openGL.Errors.log;
glFramebufferTexture2D (GL_FRAMEBUFFER,
GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D,
Self.Texture.Name,
0);
openGL.Errors.log;
glClear (GL_COLOR_BUFFER_BIT);
openGL.Errors.log;
end Texture_is;
function is_complete (Self : in Item) return Boolean
is
use GL,
GL.lean;
use type GL.GLenum;
check_is_OK : constant Boolean := Tasks.check with Unreferenced;
Result : constant Boolean := glCheckFramebufferStatus (GL_FRAMEBUFFER) = GL_FRAMEBUFFER_COMPLETE;
begin
openGL.Errors.log;
return Result;
end is_complete;
--------------
--- Operations
--
procedure enable (Self : in Item)
is
use GL,
GL.lean;
check_is_OK : constant Boolean := Tasks.check with Unreferenced;
begin
glBindFramebuffer (GL_FRAMEBUFFER, Self.Name);
if not Self.is_Complete
then
raise openGL.Error with "GL_FRAMEBUFFER" & Self.Name'Image & " is not 'complete'";
end if;
end enable;
procedure disable (Self : in Item)
is
use GL,
GL.lean;
check_is_OK : constant Boolean := Tasks.check with Unreferenced;
begin
glBindFramebuffer (GL_FRAMEBUFFER, 0);
end disable;
end openGL.Frame_Buffer;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.