repo_name
stringlengths
9
74
language
stringclasses
1 value
length_bytes
int64
11
9.34M
extension
stringclasses
2 values
content
stringlengths
11
9.34M
BrickBot/Bound-T-H8-300
Ada
2,679
adb
-- Programs.Execution.Paths.Opt (body) -- -- A component of the Bound-T Worst-Case Execution Time Tool. -- ------------------------------------------------------------------------------- -- Copyright (c) 1999 .. 2015 Tidorum Ltd -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- 1. Redistributions of source code must retain the above copyright notice, this -- list of conditions and the following disclaimer. -- 2. Redistributions in binary form 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. -- -- This software is provided by the copyright holders and contributors "as is" and -- any express or implied warranties, including, but not limited to, the implied -- warranties of merchantability and fitness for a particular purpose are -- disclaimed. In no event shall the copyright owner or contributors be liable for -- any direct, indirect, incidental, special, exemplary, or consequential damages -- (including, but not limited to, procurement of substitute goods or services; -- loss of use, data, or profits; or business interruption) however caused and -- on any theory of liability, whether in contract, strict liability, or tort -- (including negligence or otherwise) arising in any way out of the use of this -- software, even if advised of the possibility of such damage. -- -- Other modules (files) of this software composition should contain their -- own copyright statements, which may have different copyright and usage -- conditions. The above conditions apply to this file. ------------------------------------------------------------------------------- -- -- $Revision: 1.2 $ -- $Date: 2015/10/24 20:05:50 $ -- -- $Log: programs-execution-paths-opt.adb,v $ -- Revision 1.2 2015/10/24 20:05:50 niklas -- Moved to free licence. -- -- Revision 1.1 2011-08-31 04:17:14 niklas -- Added for BT-CH-0222: Option registry. Option -dump. External help files. -- with Options.Groups; package body Programs.Execution.Paths.Opt is begin Options.Register ( Option => Split_Time_Opt'access, Name => "split", Group => Options.Groups.Outputs); Options.Register ( Option => Loop_Times_Opt'access, Name => "loop_time", Group => Options.Groups.Outputs); Options.Register ( Option => Trace_Callee_Bounds_Opt'access, Name => Options.Trace_Item ("call_bounds"), Group => Options.Groups.Trace); end Programs.Execution.Paths.Opt;
luk9400/nsi
Ada
405
adb
package body Smallest_Factor with SPARK_Mode is procedure SmallestF (N : in out Positive; Factor : out Positive) is begin Factor := 2; for I in Positive range 2 .. N loop pragma Loop_Invariant (for all J in 2 .. I - 1 => N rem J /= 0); Factor := I; if N rem I = 0 then exit; end if; end loop; N := N / Factor; end SmallestF; end Smallest_Factor;
ekoeppen/STM32_Generic_Ada_Drivers
Ada
6,082
ads
pragma Style_Checks (Off); -- This spec has been automatically generated from STM32L0x3.svd pragma Restrictions (No_Elaboration_Code); with System; package STM32_SVD.DBGMCU is pragma Preelaborate; --------------- -- Registers -- --------------- subtype IDCODE_DEV_ID_Field is STM32_SVD.UInt12; subtype IDCODE_REV_ID_Field is STM32_SVD.UInt16; -- MCU Device ID Code Register type IDCODE_Register is record -- Read-only. Device Identifier DEV_ID : IDCODE_DEV_ID_Field; -- unspecified Reserved_12_15 : STM32_SVD.UInt4; -- Read-only. Revision Identifier REV_ID : IDCODE_REV_ID_Field; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for IDCODE_Register use record DEV_ID at 0 range 0 .. 11; Reserved_12_15 at 0 range 12 .. 15; REV_ID at 0 range 16 .. 31; end record; subtype CR_DBG_SLEEP_Field is STM32_SVD.Bit; subtype CR_DBG_STOP_Field is STM32_SVD.Bit; subtype CR_DBG_STANDBY_Field is STM32_SVD.Bit; -- Debug MCU Configuration Register type CR_Register is record -- Debug Sleep Mode DBG_SLEEP : CR_DBG_SLEEP_Field := 16#0#; -- Debug Stop Mode DBG_STOP : CR_DBG_STOP_Field := 16#0#; -- Debug Standby Mode DBG_STANDBY : CR_DBG_STANDBY_Field := 16#0#; -- unspecified Reserved_3_31 : STM32_SVD.UInt29 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CR_Register use record DBG_SLEEP at 0 range 0 .. 0; DBG_STOP at 0 range 1 .. 1; DBG_STANDBY at 0 range 2 .. 2; Reserved_3_31 at 0 range 3 .. 31; end record; subtype APB1_FZ_DBG_TIMER2_STOP_Field is STM32_SVD.Bit; subtype APB1_FZ_DBG_TIMER6_STOP_Field is STM32_SVD.Bit; subtype APB1_FZ_DBG_RTC_STOP_Field is STM32_SVD.Bit; subtype APB1_FZ_DBG_WWDG_STOP_Field is STM32_SVD.Bit; subtype APB1_FZ_DBG_IWDG_STOP_Field is STM32_SVD.Bit; subtype APB1_FZ_DBG_I2C1_STOP_Field is STM32_SVD.Bit; subtype APB1_FZ_DBG_I2C2_STOP_Field is STM32_SVD.Bit; subtype APB1_FZ_DBG_LPTIMER_STOP_Field is STM32_SVD.Bit; -- APB Low Freeze Register type APB1_FZ_Register is record -- Debug Timer 2 stopped when Core is halted DBG_TIMER2_STOP : APB1_FZ_DBG_TIMER2_STOP_Field := 16#0#; -- unspecified Reserved_1_3 : STM32_SVD.UInt3 := 16#0#; -- Debug Timer 6 stopped when Core is halted DBG_TIMER6_STOP : APB1_FZ_DBG_TIMER6_STOP_Field := 16#0#; -- unspecified Reserved_5_9 : STM32_SVD.UInt5 := 16#0#; -- Debug RTC stopped when Core is halted DBG_RTC_STOP : APB1_FZ_DBG_RTC_STOP_Field := 16#0#; -- Debug Window Wachdog stopped when Core is halted DBG_WWDG_STOP : APB1_FZ_DBG_WWDG_STOP_Field := 16#0#; -- Debug Independent Wachdog stopped when Core is halted DBG_IWDG_STOP : APB1_FZ_DBG_IWDG_STOP_Field := 16#0#; -- unspecified Reserved_13_20 : STM32_SVD.Byte := 16#0#; -- I2C1 SMBUS timeout mode stopped when core is halted DBG_I2C1_STOP : APB1_FZ_DBG_I2C1_STOP_Field := 16#0#; -- I2C2 SMBUS timeout mode stopped when core is halted DBG_I2C2_STOP : APB1_FZ_DBG_I2C2_STOP_Field := 16#0#; -- unspecified Reserved_23_30 : STM32_SVD.Byte := 16#0#; -- LPTIM1 counter stopped when core is halted DBG_LPTIMER_STOP : APB1_FZ_DBG_LPTIMER_STOP_Field := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for APB1_FZ_Register use record DBG_TIMER2_STOP at 0 range 0 .. 0; Reserved_1_3 at 0 range 1 .. 3; DBG_TIMER6_STOP at 0 range 4 .. 4; Reserved_5_9 at 0 range 5 .. 9; DBG_RTC_STOP at 0 range 10 .. 10; DBG_WWDG_STOP at 0 range 11 .. 11; DBG_IWDG_STOP at 0 range 12 .. 12; Reserved_13_20 at 0 range 13 .. 20; DBG_I2C1_STOP at 0 range 21 .. 21; DBG_I2C2_STOP at 0 range 22 .. 22; Reserved_23_30 at 0 range 23 .. 30; DBG_LPTIMER_STOP at 0 range 31 .. 31; end record; subtype APB2_FZ_DBG_TIMER21_STOP_Field is STM32_SVD.Bit; subtype APB2_FZ_DBG_TIMER22_STO_Field is STM32_SVD.Bit; -- APB High Freeze Register type APB2_FZ_Register is record -- unspecified Reserved_0_1 : STM32_SVD.UInt2 := 16#0#; -- Debug Timer 21 stopped when Core is halted DBG_TIMER21_STOP : APB2_FZ_DBG_TIMER21_STOP_Field := 16#0#; -- unspecified Reserved_3_5 : STM32_SVD.UInt3 := 16#0#; -- Debug Timer 22 stopped when Core is halted DBG_TIMER22_STO : APB2_FZ_DBG_TIMER22_STO_Field := 16#0#; -- unspecified Reserved_7_31 : STM32_SVD.UInt25 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for APB2_FZ_Register use record Reserved_0_1 at 0 range 0 .. 1; DBG_TIMER21_STOP at 0 range 2 .. 2; Reserved_3_5 at 0 range 3 .. 5; DBG_TIMER22_STO at 0 range 6 .. 6; Reserved_7_31 at 0 range 7 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- Debug support type DBGMCU_Peripheral is record -- MCU Device ID Code Register IDCODE : aliased IDCODE_Register; -- Debug MCU Configuration Register CR : aliased CR_Register; -- APB Low Freeze Register APB1_FZ : aliased APB1_FZ_Register; -- APB High Freeze Register APB2_FZ : aliased APB2_FZ_Register; end record with Volatile; for DBGMCU_Peripheral use record IDCODE at 16#0# range 0 .. 31; CR at 16#4# range 0 .. 31; APB1_FZ at 16#8# range 0 .. 31; APB2_FZ at 16#C# range 0 .. 31; end record; -- Debug support DBGMCU_Periph : aliased DBGMCU_Peripheral with Import, Address => DBGMCU_Base; end STM32_SVD.DBGMCU;
AdaCore/gpr
Ada
1,945
ads
------------------------------------------------------------------------------ -- -- -- GPR2 PROJECT MANAGER -- -- -- -- Copyright (C) 2019-2023, AdaCore -- -- -- -- This 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. This software is distributed in the hope that it will be useful, -- -- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN- -- -- TABILITY or FITNESS FOR A PARTICULAR PURPOSE. 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, -- -- see <http://www.gnu.org/licenses/>. -- -- -- ------------------------------------------------------------------------------ package GPRname.Pattern.Language is type Object is new GPRname.Pattern.Object with private; -- Extension of Compiled_Pattern_Object in which we associate a language -- to the pattern. function Create (Pattern : Pattern_Type; Language : Language_Type) return Object'Class; -- Constructor for Compiled_Pattern_Language_Object function Language (Self : Object) return Language_Type; -- Returns the language for Self private type Object is new GPRname.Pattern.Object with record Language : Unbounded_String; end record; end GPRname.Pattern.Language;
Ximalas/synth
Ada
15,184
adb
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Ada.Strings.Fixed; with Ada.Characters.Latin_1; package body JohnnyText is package LAT renames Ada.Characters.Latin_1; ----------- -- USS -- ----------- function USS (US : Text) return String is begin return SU.To_String (US); end USS; ----------- -- SUS -- ----------- function SUS (S : String) return Text is begin return SU.To_Unbounded_String (S); end SUS; ----------------- -- IsBlank #1 -- ----------------- function IsBlank (US : Text) return Boolean is begin return SU.Length (US) = 0; end IsBlank; ----------------- -- IsBlank #2 -- ----------------- function IsBlank (S : String) return Boolean is begin return S'Length = 0; end IsBlank; ------------------ -- equivalent -- ------------------ function equivalent (A, B : Text) return Boolean is use type Text; begin return A = B; end equivalent; ------------------ -- equivalent -- ------------------ function equivalent (A : Text; B : String) return Boolean is AS : constant String := USS (A); begin return AS = B; end equivalent; -------------- -- trim #1 -- -------------- function trim (US : Text) return Text is begin return SU.Trim (US, AS.Both); end trim; -------------- -- trim #2 -- -------------- function trim (S : String) return String is begin return AS.Fixed.Trim (S, AS.Both); end trim; --------------- -- int2str -- --------------- function int2str (A : Integer) return String is raw : constant String := A'Img; len : constant Natural := raw'Length; begin if A < 0 then return raw; else return raw (2 .. len); end if; end int2str; ---------------- -- int2text -- ---------------- function int2text (A : Integer) return Text is begin return SUS (int2str (A)); end int2text; ---------------- -- bool2str -- ---------------- function bool2str (A : Boolean) return String is begin if A then return "true"; end if; return "false"; end bool2str; ----------------- -- bool2text -- ----------------- function bool2text (A : Boolean) return Text is begin return SUS (bool2str (A)); end bool2text; ---------------- -- nextline -- ---------------- procedure nextline (lineblock, firstline : out Text) is CR_loc : Natural; CR : constant String (1 .. 1) := (1 => Character'Val (10)); begin CR_loc := SU.Index (Source => lineblock, Pattern => CR); if CR_loc = 0 then firstline := lineblock; return; end if; firstline := SUS (SU.Slice (Source => lineblock, Low => 1, High => CR_loc - 1)); SU.Delete (Source => lineblock, From => 1, Through => CR_loc); end nextline; -------------------- -- contains #1 -- -------------------- function contains (S : String; fragment : String) return Boolean is begin return (AS.Fixed.Index (Source => S, Pattern => fragment) > 0); end contains; -------------------- -- contains #2 -- -------------------- function contains (US : Text; fragment : String) return Boolean is begin return (SU.Index (Source => US, Pattern => fragment) > 0); end contains; -------------- -- part_1 -- -------------- function part_1 (S : String; separator : String := "/") return String is slash : Integer := AS.Fixed.Index (S, separator); begin if slash = 0 then return S; end if; return S (S'First .. slash - 1); end part_1; -------------- -- part_2 -- -------------- function part_2 (S : String; separator : String := "/") return String is slash : Integer := AS.Fixed.Index (S, separator); begin if slash = 0 then return S; end if; return S (slash + separator'Length .. S'Last); end part_2; --------------- -- replace -- --------------- function replace (S : String; reject, shiny : Character) return String is rejectstr : constant String (1 .. 1) := (1 => reject); focus : constant Natural := AS.Fixed.Index (Source => S, Pattern => rejectstr); returnstr : String := S; begin if focus > 0 then returnstr (focus) := shiny; end if; return returnstr; end replace; --------------- -- zeropad -- --------------- function zeropad (N : Natural; places : Positive) return String is template : String (1 .. places) := (others => '0'); myimage : constant String := trim (N'Img); startpos : constant Natural := 1 + places - myimage'Length; begin template (startpos .. places) := myimage; return template; end zeropad; ------------------ -- count_char -- ------------------ function count_char (S : String; focus : Character) return Natural is result : Natural := 0; begin for x in S'Range loop if S (x) = focus then result := result + 1; end if; end loop; return result; end count_char; -------------------- -- replace_char -- -------------------- function replace_char (S : String; focus : Character; substring : String) return String is num_to_replace : constant Natural := count_char (S, focus); begin if num_to_replace = 0 then return S; end if; declare ssm1 : constant Natural := substring'Length - 1; strlen : constant Natural := S'Length + (num_to_replace * ssm1); product : String (1 .. strlen); ndx : Positive := 1; begin for x in S'Range loop if S (x) = focus then product (ndx .. ndx + ssm1) := substring; ndx := ndx + substring'Length; else product (ndx) := S (x); ndx := ndx + 1; end if; end loop; return product; end; end replace_char; --------------------- -- strip_control -- --------------------- function strip_control (S : String) return String is product : String (1 .. S'Length); ndx : Natural := 0; begin for x in S'Range loop if Character'Pos (S (x)) >= 32 then ndx := ndx + 1; product (ndx) := S (x); end if; end loop; return product (1 .. ndx); end strip_control; -------------------------------------------------------------------------------------------- -- specific_field -------------------------------------------------------------------------------------------- function specific_field (S : String; field_number : Positive; delimiter : String := " ") return String is back : Integer; dsize : Natural := delimiter'Length; front : Integer := S'First; begin for field in 1 .. field_number - 1 loop back := AS.Fixed.Index (Source => S, Pattern => delimiter, From => front); if back <= 0 then return ""; end if; front := back + dsize; end loop; back := AS.Fixed.Index (Source => S, Pattern => delimiter, From => front); if back > 0 then return S (front .. back - 1); else return S (front .. S'Last); end if; end specific_field; -------------------------------------------------------------------------------------------- -- leads #1 -------------------------------------------------------------------------------------------- function leads (S : String; fragment : String) return Boolean is begin if fragment'Length > S'Length then return False; end if; return (S (S'First .. S'First + fragment'Length - 1) = fragment); end leads; -------------------------------------------------------------------------------------------- -- leads #2 -------------------------------------------------------------------------------------------- function leads (US : Text; fragment : String) return Boolean is begin return leads (USS (US), fragment); end leads; -------------------------------------------------------------------------------------------- -- initialize_markers -------------------------------------------------------------------------------------------- procedure initialize_markers (block_text : in String; shuttle : out Line_Markers) is begin shuttle.back_marker := block_text'First; shuttle.front_marker := block_text'First; if block_text'Length > 0 then shuttle.zero_length := block_text (shuttle.back_marker) = LAT.LF; end if; shuttle.utilized := False; end initialize_markers; -------------------------------------------------------------------------------------------- -- extract_line -------------------------------------------------------------------------------------------- function extract_line (block_text : in String; shuttle : in Line_Markers) return String is begin if shuttle.zero_length or else shuttle.back_marker < block_text'First or else shuttle.front_marker < shuttle.back_marker or else shuttle.front_marker > block_text'Last then return ""; end if; return block_text (shuttle.back_marker .. shuttle.front_marker); end extract_line; -------------------------------------------------------------------------------------------- -- next_line_present -------------------------------------------------------------------------------------------- function next_line_present (block_text : in String; shuttle : in out Line_Markers) return Boolean is begin if shuttle.front_marker + 2 > block_text'Last then return False; end if; if shuttle.utilized then if shuttle.zero_length then shuttle.back_marker := shuttle.front_marker + 1; else shuttle.back_marker := shuttle.front_marker + 2; end if; shuttle.front_marker := shuttle.back_marker; shuttle.zero_length := block_text (shuttle.back_marker) = LAT.LF; else if block_text'Length = 0 then return False; end if; end if; loop shuttle.utilized := True; exit when shuttle.front_marker = block_text'Last; exit when block_text (shuttle.back_marker) = LAT.LF; exit when block_text (shuttle.front_marker + 1) = LAT.LF; shuttle.front_marker := shuttle.front_marker + 1; end loop; return True; end next_line_present; -------------------------------------------------------------------------------------------- -- next_line_with_content_present -------------------------------------------------------------------------------------------- function next_line_with_content_present (block_text : in String; start_with : in String; shuttle : in out Line_Markers) return Boolean is ndx : Natural; begin if shuttle.front_marker + 2 > block_text'Last then return False; end if; if shuttle.utilized then ndx := AS.Fixed.Index (Source => block_text, Pattern => LAT.LF & start_with, From => shuttle.front_marker + 1); if ndx = 0 then return False; else shuttle.back_marker := ndx + 1; end if; else if start_with'Length = 0 then return False; end if; if leads (block_text, start_with) then shuttle.back_marker := block_text'First; else ndx := AS.Fixed.Index (block_text, LAT.LF & start_with); if ndx = 0 then return False; else shuttle.back_marker := ndx + 1; end if; end if; end if; shuttle.utilized := True; shuttle.zero_length := False; ndx := AS.Fixed.Index (Source => block_text, Pattern => single_LF, From => shuttle.back_marker + 1); if ndx = 0 then shuttle.front_marker := block_text'Last; else shuttle.front_marker := ndx - 1; end if; return True; end next_line_with_content_present; -------------------------------------------------------------------------------------------- -- head #1 -------------------------------------------------------------------------------------------- function head (US : Text; delimiter : Text) return Text is result : constant String := head (USS (US), USS (delimiter)); begin return SUS (result); end head; -------------------------------------------------------------------------------------------- -- head #2 -------------------------------------------------------------------------------------------- function head (S : String; delimiter : String) return String is dl_size : constant Natural := delimiter'Length; back_marker : constant Natural := S'First; front_marker : Natural := S'Last - dl_size + 1; begin loop if front_marker < back_marker then -- delimiter never found return ""; end if; if S (front_marker .. front_marker + dl_size - 1) = delimiter then return S (back_marker .. front_marker - 1); end if; front_marker := front_marker - 1; end loop; end head; -------------------------------------------------------------------------------------------- -- tail #1 -------------------------------------------------------------------------------------------- function tail (US : Text; delimiter : Text) return Text is result : constant String := tail (USS (US), USS (delimiter)); begin return SUS (result); end tail; -------------------------------------------------------------------------------------------- -- tail #2 -------------------------------------------------------------------------------------------- function tail (S : String; delimiter : String) return String is dl_size : constant Natural := delimiter'Length; back_marker : constant Natural := S'First; front_marker : Natural := S'Last - dl_size + 1; begin loop if front_marker < back_marker then -- delimiter never found return S; end if; if S (front_marker .. front_marker + dl_size - 1) = delimiter then return S (front_marker + dl_size .. S'Last); end if; front_marker := front_marker - 1; end loop; end tail; end JohnnyText;
annexi-strayline/AURA
Ada
10,126
ads
------------------------------------------------------------------------------ -- -- -- Ada User Repository Annex (AURA) -- -- ANNEXI-STRAYLINE Reference Implementation -- -- -- -- ------------------------------------------------------------------------ -- -- -- -- Copyright (C) 2019-2021, ANNEXI-STRAYLINE Trans-Human Ltd. -- -- All rights reserved. -- -- -- -- Original Contributors: -- -- * Richard Wai (ANNEXI-STRAYLINE) -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- -- -- * Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -- -- PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- This package contains the core worker pool which executes queued -- "work orders". -- -- The intent is that "work orders" are used internally within various -- subsystems, rather than acting as a general calling convention. -- -- In general, derrivatives of Work_Order should not appear in package -- specifications (except in private parts or private packages) with Ada.Containers; with Progress; package Workers is ----------------- -- Work Orders -- ----------------- type Work_Order is abstract tagged record Tracker: Progress.Progress_Tracker_Access := null; -- If non-null, the Work_Order will invoke Increment_Completed_Items -- on the successful completion of the Order, or -- Increment_Failed_Items otherwise end record; -- Any derrivative of the Work_Order interface may be submitted to -- Queue_Order for a Worker task to call Execute on the order. function Image (Order: Work_Order) return String is abstract; -- Return a string describing the details of the work order, used by -- work tasks to create reports when Execute raises an exception. procedure Execute (Order: in out Work_Order) is abstract; -- Dispatching operation to execute the work of the work order. Called by -- a worker tasks when executing an order procedure Phase_Trigger (Order: in out Work_Order) is null; -- If Order has a non-null tracker, and at completion of the order -- when the tracker is incremented, if the tracker is completed -- (Is_Complete) evaluates True, the worker executes Phase_Trigger -- -- The concept for a phase trigger is essentially equivalent to the join -- in a fork-join concurrency model. -- -- If Phase_Trigger raises an exception, the worker files a failure report -- using image of the triggering order, with a worker note of -- "Phase Trigger failed" -- -- Since Phase_Triggers are often used to schedule (enqueue) more work, -- and since that work can sometimes include deallocating concurrent shared -- memory for the just completed task, it is important that any work -- submitted during a phase trigger is not executed until the phase trigger -- completes. Therefore all workers will be held while a phase trigger -- executes - again this is conformant with the fork-join model. -- -- Note that the worker will not interact with tracker after executing -- an associated Phase_Trigger. ---------------- -- Work Queue -- ---------------- subtype Count_Type is Ada.Containers.Count_Type; use type Count_Type; procedure Enqueue_Order (Order: in Work_Order'Class); -- Enqueus a (normal) Work_Order on the work queue. procedure Defer_Order (Order : in Work_Order'Class; Wait_Tracker: not null Progress.Progress_Tracker_Access); -- Order Deferral -- ============== -- -- Each deferred order is dependent on a Progress_Tracker on which the -- deferred order is waiting completion. -- -- Deferred orders are intended to act as triggers pending some other -- process. It is expected that a given Work Order completes a tracker -- on which a deferred work order is waiting. That/those Work Orders -- can then be executed. This ensures that the workers are not exhausted -- blocking on a progress tracker happening inside of a normal work order. -- -- When submitted, Deferred Orders are enqueued on to the main work queue. -- When a worker dequeues a Deferred Order, it immediately checks the -- Wait_Tracker for completion. If the tracker indicates completion, -- the worker immediately executes the Deferred Order as it would a -- regular Work Order. If the tracker does not indicate completion, the -- Order is then enqueued on a separate "deferral queue". -- -- Every worker that completes any work order always drains the deferral -- queue back to the main queue, so that each deferred order may then -- be re-checked. -- -- The design of this algorithm has a number of features: -- -- * It ensures that the minimum time is spent re-checking Deferred Orders -- that likely have not had their tracker completed, and that the Orders -- that release Deferred Orders will tend to be processed before the -- related Deferred Order is processed -- -- * Once the main queue is empty, all workers will wait for new orders to -- be enqueued, and will not spin, even if there remains Deferred Orders -- that have not been released. This is desireable because, if such -- Deferred Orders remained in this case, it should be impossible for -- them to complete anyways. -- -- * In theory, any erroneous Deferred Orders (who's tracker will never -- complete) will accumulate on the deferral queue after the main queue -- has been empty. This should be easy to spot since a higher-level -- process will stall on the Deferred Order, but there will not be -- misleading behaviour such as high CPU usage, or random performance -- (and potential live lock) due to spinning. function Queue_Level return Count_Type; function Peak_Queue_Level return Count_Type; -- Number of work order in the Queue, or the peak recorded number, not -- including deferred orders that have been moved to the deferral queue function Deferred return Count_Type; function Peak_Deferred return Count_Type; -- Number of work orders in the deferral queue ----------------- -- Worker Pool -- ----------------- -- All Workers simply Execute work orders off the Work Queue or Deferral -- Queue -- -- Any exception encountered is contained and reported via the failure -- reporting facilities subtype Worker_Count is Natural; task type Worker_Task; type Worker_Pool is array (Worker_Count range <>) of Worker_Task; -- The environment task is expected to initialize an appropriate pool of -- workers procedure Enable_Completion_Reports; procedure Disable_Completion_Reports; -- If enabled, all workers submit a report on completion of a work order. -- This setting is Disabled by default procedure Wait_Workers; procedure Wait_Workers (Timeout: in Duration; Timedout: out Boolean); -- Wait until all workers are Idle (no more jobs on the work queue), -- or until Timeout expires procedure Disband_Workers; -- Perminantly terminates all worker tasks in the partition. -- This cannot be reversed. function Busy_Workers return Worker_Count; function Peak_Busy_Workers return Worker_Count; -- Total number of Worker tasks currently executing a Work_Order end Workers;
reznikmm/matreshka
Ada
3,779
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- 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 XML.DOM.Elements; package ODF.DOM.Text_Table_Of_Content_Entry_Template_Elements is pragma Preelaborate; type ODF_Text_Table_Of_Content_Entry_Template is limited interface and XML.DOM.Elements.DOM_Element; type ODF_Text_Table_Of_Content_Entry_Template_Access is access all ODF_Text_Table_Of_Content_Entry_Template'Class with Storage_Size => 0; end ODF.DOM.Text_Table_Of_Content_Entry_Template_Elements;
Gabriel-Degret/adalib
Ada
6,864
ads
-- Standard Ada library specification -- Copyright (c) 2003-2018 Maxim Reznik <[email protected]> -- Copyright (c) 2004-2016 AXE Consultants -- Copyright (c) 2004, 2005, 2006 Ada-Europe -- Copyright (c) 2000 The MITRE Corporation, Inc. -- Copyright (c) 1992, 1993, 1994, 1995 Intermetrics, Inc. -- SPDX-License-Identifier: BSD-3-Clause and LicenseRef-AdaReferenceManual --------------------------------------------------------------------------- with Ada.Iterator_Interfaces; generic type Key_Type is private; type Element_Type is private; with function "<" (Left, Right : Key_Type) return Boolean is <>; with function "=" (Left, Right : Element_Type) return Boolean is <>; package Ada.Containers.Ordered_Maps is pragma Preelaborate(Ordered_Maps); pragma Remote_Types(Ordered_Maps); function Equivalent_Keys (Left, Right : Key_Type) return Boolean; type Map is tagged private with Constant_Indexing => Constant_Reference, Variable_Indexing => Reference, Default_Iterator => Iterate, Iterator_Element => Element_Type; pragma Preelaborable_Initialization(Map); type Cursor is private; pragma Preelaborable_Initialization(Cursor); Empty_Map : constant Map; No_Element : constant Cursor; function Has_Element (Position : Cursor) return Boolean; package Map_Iterator_Interfaces is new Ada.Iterator_Interfaces (Cursor, Has_Element); function "=" (Left, Right : Map) return Boolean; function Length (Container : Map) return Count_Type; function Is_Empty (Container : Map) return Boolean; procedure Clear (Container : in out Map); function Key (Position : Cursor) return Key_Type; function Element (Position : Cursor) return Element_Type; procedure Replace_Element (Container : in out Map; Position : in Cursor; New_Item : in Element_Type); procedure Query_Element (Position : in Cursor; Process : not null access procedure (Key : in Key_Type; Element : in Element_Type)); procedure Update_Element (Container : in out Map; Position : in Cursor; Process : not null access procedure (Key : in Key_Type; Element : in out Element_Type)); type Constant_Reference_Type (Element : not null access constant Element_Type) is private with Implicit_Dereference => Element; type Reference_Type (Element : not null access Element_Type) is private with Implicit_Dereference => Element; function Constant_Reference (Container : aliased in Map; Position : in Cursor) return Constant_Reference_Type; function Reference (Container : aliased in out Map; Position : in Cursor) return Reference_Type; function Constant_Reference (Container : aliased in Map; Key : in Key_Type) return Constant_Reference_Type; function Reference (Container : aliased in out Map; Key : in Key_Type) return Reference_Type; procedure Assign (Target : in out Map; Source : in Map); function Copy (Source : Map) return Map; procedure Move (Target : in out Map; Source : in out Map); procedure Insert (Container : in out Map; Key : in Key_Type; New_Item : in Element_Type; Position : out Cursor; Inserted : out Boolean); procedure Insert (Container : in out Map; Key : in Key_Type; Position : out Cursor; Inserted : out Boolean); procedure Insert (Container : in out Map; Key : in Key_Type; New_Item : in Element_Type); procedure Include (Container : in out Map; Key : in Key_Type; New_Item : in Element_Type); procedure Replace (Container : in out Map; Key : in Key_Type; New_Item : in Element_Type); procedure Exclude (Container : in out Map; Key : in Key_Type); procedure Delete (Container : in out Map; Key : in Key_Type); procedure Delete (Container : in out Map; Position : in out Cursor); procedure Delete_First (Container : in out Map); procedure Delete_Last (Container : in out Map); function First (Container : Map) return Cursor; function First_Element (Container : Map) return Element_Type; function First_Key (Container : Map) return Key_Type; function Last (Container : Map) return Cursor; function Last_Element (Container : Map) return Element_Type; function Last_Key (Container : Map) return Key_Type; function Next (Position : Cursor) return Cursor; procedure Next (Position : in out Cursor); function Previous (Position : Cursor) return Cursor; procedure Previous (Position : in out Cursor); function Find (Container : Map; Key : Key_Type) return Cursor; function Element (Container : Map; Key : Key_Type) return Element_Type; function Floor (Container : Map; Key : Key_Type) return Cursor; function Ceiling (Container : Map; Key : Key_Type) return Cursor; function Contains (Container : Map; Key : Key_Type) return Boolean; function "<" (Left, Right : Cursor) return Boolean; function ">" (Left, Right : Cursor) return Boolean; function "<" (Left : Cursor; Right : Key_Type) return Boolean; function ">" (Left : Cursor; Right : Key_Type) return Boolean; function "<" (Left : Key_Type; Right : Cursor) return Boolean; function ">" (Left : Key_Type; Right : Cursor) return Boolean; procedure Iterate (Container : in Map; Process : not null access procedure (Position : in Cursor)); procedure Reverse_Iterate (Container : in Map; Process : not null access procedure (Position : in Cursor)); function Iterate (Container : in Map) return Map_Iterator_Interfaces.Reversible_Iterator'Class; function Iterate (Container : in Map; Start : in Cursor) return Map_Iterator_Interfaces.Reversible_Iterator'Class; private -- not specified by the language type Map is tagged null record; Empty_Map : constant Map := (null record); type Cursor is null record; No_Element : constant Cursor := (null record); end Ada.Containers.Ordered_Maps;
jhumphry/SPARK_SipHash
Ada
366
ads
-- SipHash24.System_Entropy -- An instantiation of SipHash.Entropy to allow the SipHash key to be set from -- a system entropy source (if possible). -- Copyright (c) 2015, James Humphry - see LICENSE file for details pragma Spark_Mode (On); with SipHash.Entropy; pragma Elaborate_All(SipHash.Entropy); package SipHash24.System_Entropy is new SipHash24.Entropy;
charlie5/cBound
Ada
1,545
ads
-- This file is generated by SWIG. Please do not modify by hand. -- with Interfaces.C; with xcb.xcb_render_pictvisual_t; with Interfaces.C; with Interfaces.C.Pointers; package xcb.xcb_render_pictvisual_iterator_t is -- Item -- type Item is record data : access xcb.xcb_render_pictvisual_t.Item; the_rem : aliased Interfaces.C.int; index : aliased Interfaces.C.int; end record; -- Item_Array -- type Item_Array is array (Interfaces.C .size_t range <>) of aliased xcb.xcb_render_pictvisual_iterator_t .Item; -- Pointer -- package C_Pointers is new Interfaces.C.Pointers (Index => Interfaces.C.size_t, Element => xcb.xcb_render_pictvisual_iterator_t.Item, Element_Array => xcb.xcb_render_pictvisual_iterator_t.Item_Array, Default_Terminator => (others => <>)); subtype Pointer is C_Pointers.Pointer; -- Pointer_Array -- type Pointer_Array is array (Interfaces.C .size_t range <>) of aliased xcb.xcb_render_pictvisual_iterator_t .Pointer; -- Pointer_Pointer -- package C_Pointer_Pointers is new Interfaces.C.Pointers (Index => Interfaces.C.size_t, Element => xcb.xcb_render_pictvisual_iterator_t.Pointer, Element_Array => xcb.xcb_render_pictvisual_iterator_t.Pointer_Array, Default_Terminator => null); subtype Pointer_Pointer is C_Pointer_Pointers.Pointer; end xcb.xcb_render_pictvisual_iterator_t;
jrcarter/Ada_GUI
Ada
3,870
adb
-- Ada_GUI version of Random_Int -- -- Copyright (C) 2021 by PragmAda Software Engineering -- -- Released under the terms of the 3-Clause BSD License. See https://opensource.org/licenses/BSD-3-Clause -- -- The (application-specific) user interface with Ada.Strings.Fixed; with Ada_GUI; package body Random_Int.UI is Min_Entry : Ada_GUI.Widget_ID; Max_Entry : Ada_GUI.Widget_ID; Result : Ada_GUI.Widget_ID; Generator : Ada_GUI.Widget_ID; Quitter : Ada_GUI.Widget_ID; Finished : Boolean := False with Atomic; function Ended return Boolean is (Finished); task Event_Handler is entry Start; -- Delay the task until the GUI is set up entry Get (Event : out Event_ID); end Event_Handler; function Next_Event return Event_ID is Result : Event_ID; begin -- Next_Event Event_Handler.Get (Event => Result); return Result; end Next_Event; function Min_Text return String Is (Min_Entry.Text); function Max_Text return String Is (Max_Entry.Text); function Image (Value : Integer) return String is (Ada.Strings.Fixed.Trim (Value'Image, Ada.Strings.Both) ); procedure Set_Min (Value : in Integer) is -- Empty begin -- Set_Min Min_Entry.Set_Text (Text => Image (Value) ); end Set_Min; procedure Set_Max (Value : in Integer) is -- Empty begin -- Set_Max Max_Entry.Set_Text (Text => Image (Value) ); end Set_Max; procedure Min_Error is -- Empty begin -- Min_Error Min_Entry.Set_Text (Text => ""); end Min_Error; procedure Max_Error is -- Empty begin -- Max_Error Max_Entry.Set_Text (Text => ""); end Max_Error; procedure Show_Result (Value : in Integer) is -- Empty begin -- Show_Result Result.Set_Text (Text => Image (Value) ); end Show_Result; task body Event_Handler is Event : Ada_GUI.Next_Result_Info; ID : Ada_GUI.Widget_ID; use type Ada_GUI.Event_Kind_ID; use type Ada_GUI.Widget_ID; begin -- Event_Handler accept Start; Forever : loop Event := Ada_GUI.Next_Event (Timeout => 1.0); if not Event.Timed_Out then if Event.Event.Kind = Ada_GUI.Window_Closed then accept Get (Event : out Event_ID) do Event := Quit; end Get; Finished := True; exit Forever; elsif Event.Event.Kind = Ada_GUI.Left_Click then ID := Event.Event.ID; if ID = Generator or ID = Quitter then accept Get (Event : out Event_ID) do if ID = Generator then Event := Generate; else Event := Quit; Finished := True; end if; end Get; end if; exit Forever when ID = Quitter; end if; end if; end loop Forever; Ada_GUI.End_GUI; end Event_Handler; Placeholder : constant String := "Enter an integer"; begin -- Random_Int.UI Ada_GUI.Set_Up (Grid => (1 => (1 .. 2 => (Kind => Ada_GUI.Area, Alignment => Ada_GUI.Right) ) ), Title => "Random Integers"); Min_Entry := Ada_GUI.New_Text_Box (Label => "Minimum value", Placeholder => Placeholder); Min_Entry.Set_Text_Alignment (Alignment => Ada_GUI.Right); Max_Entry := Ada_GUI.New_Text_Box (Break_Before => True, Label => "Maximum value", Placeholder => Placeholder); Max_Entry.Set_Text_Alignment (Alignment => Ada_GUI.Right); Result := Ada_GUI.New_Text_Box (Break_Before => True); Result.Set_Text_Alignment (Alignment => Ada_GUI.Right); Generator := Ada_GUI.New_Button (Text => "Generate"); Quitter := Ada_GUI.New_Button (Text => "Quit", Break_Before => True); Event_Handler.Start; end Random_Int.UI;
zhmu/ananas
Ada
16,429
adb
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- S Y S T E M . F I N A L I Z A T I O N _ M A S T E R S -- -- -- -- B o d y -- -- -- -- Copyright (C) 2015-2022, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Ada.Exceptions; use Ada.Exceptions; with System.Address_Image; with System.HTable; use System.HTable; with System.IO; use System.IO; with System.Soft_Links; use System.Soft_Links; with System.Storage_Elements; use System.Storage_Elements; package body System.Finalization_Masters is -- Finalize_Address hash table types. In general, masters are homogeneous -- collections of controlled objects. Rare cases such as allocations on a -- subpool require heterogeneous masters. The following table provides a -- relation between object address and its Finalize_Address routine. type Header_Num is range 0 .. 127; function Hash (Key : System.Address) return Header_Num; -- Address --> Finalize_Address_Ptr package Finalize_Address_Table is new Simple_HTable (Header_Num => Header_Num, Element => Finalize_Address_Ptr, No_Element => null, Key => System.Address, Hash => Hash, Equal => "="); --------------------------- -- Add_Offset_To_Address -- --------------------------- function Add_Offset_To_Address (Addr : System.Address; Offset : System.Storage_Elements.Storage_Offset) return System.Address is begin return System.Storage_Elements."+" (Addr, Offset); end Add_Offset_To_Address; ------------ -- Attach -- ------------ procedure Attach (N : not null FM_Node_Ptr; L : not null FM_Node_Ptr) is begin Lock_Task.all; Attach_Unprotected (N, L); Unlock_Task.all; -- Note: No need to unlock in case of an exception because the above -- code can never raise one. end Attach; ------------------------ -- Attach_Unprotected -- ------------------------ procedure Attach_Unprotected (N : not null FM_Node_Ptr; L : not null FM_Node_Ptr) is begin L.Next.Prev := N; N.Next := L.Next; L.Next := N; N.Prev := L; end Attach_Unprotected; --------------- -- Base_Pool -- --------------- function Base_Pool (Master : Finalization_Master) return Any_Storage_Pool_Ptr is begin return Master.Base_Pool; end Base_Pool; ----------------------------------------- -- Delete_Finalize_Address_Unprotected -- ----------------------------------------- procedure Delete_Finalize_Address_Unprotected (Obj : System.Address) is begin Finalize_Address_Table.Remove (Obj); end Delete_Finalize_Address_Unprotected; ------------------------ -- Detach_Unprotected -- ------------------------ procedure Detach_Unprotected (N : not null FM_Node_Ptr) is begin if N.Prev /= null and then N.Next /= null then N.Prev.Next := N.Next; N.Next.Prev := N.Prev; N.Prev := null; N.Next := null; end if; end Detach_Unprotected; -------------- -- Finalize -- -------------- overriding procedure Finalize (Master : in out Finalization_Master) is Cleanup : Finalize_Address_Ptr; Curr_Ptr : FM_Node_Ptr; Ex_Occur : Exception_Occurrence; Obj_Addr : Address; Raised : Boolean := False; function Is_Empty_List (L : not null FM_Node_Ptr) return Boolean; -- Determine whether a list contains only one element, the dummy head ------------------- -- Is_Empty_List -- ------------------- function Is_Empty_List (L : not null FM_Node_Ptr) return Boolean is begin return L.Next = L and then L.Prev = L; end Is_Empty_List; -- Start of processing for Finalize begin Lock_Task.all; -- Synchronization: -- Read - allocation, finalization -- Write - finalization if Master.Finalization_Started then Unlock_Task.all; -- Double finalization may occur during the handling of stand alone -- libraries or the finalization of a pool with subpools. Due to the -- potential aliasing of masters in these two cases, do not process -- the same master twice. return; end if; -- Lock the master to prevent any allocations while the objects are -- being finalized. The master remains locked because either the master -- is explicitly deallocated or the associated access type is about to -- go out of scope. -- Synchronization: -- Read - allocation, finalization -- Write - finalization Master.Finalization_Started := True; while not Is_Empty_List (Master.Objects'Unchecked_Access) loop Curr_Ptr := Master.Objects.Next; -- Synchronization: -- Write - allocation, deallocation, finalization Detach_Unprotected (Curr_Ptr); -- Skip the list header in order to offer proper object layout for -- finalization. Obj_Addr := Curr_Ptr.all'Address + Header_Size; -- Retrieve TSS primitive Finalize_Address depending on the master's -- mode of operation. -- Synchronization: -- Read - allocation, finalization -- Write - outside if Master.Is_Homogeneous then -- Synchronization: -- Read - finalization -- Write - allocation, outside Cleanup := Master.Finalize_Address; else -- Synchronization: -- Read - finalization -- Write - allocation, deallocation Cleanup := Finalize_Address_Unprotected (Obj_Addr); end if; begin Cleanup (Obj_Addr); exception when Fin_Occur : others => if not Raised then Raised := True; Save_Occurrence (Ex_Occur, Fin_Occur); end if; end; -- When the master is a heterogeneous collection, destroy the object -- - Finalize_Address pair since it is no longer needed. -- Synchronization: -- Read - finalization -- Write - outside if not Master.Is_Homogeneous then -- Synchronization: -- Read - finalization -- Write - allocation, deallocation, finalization Delete_Finalize_Address_Unprotected (Obj_Addr); end if; end loop; Unlock_Task.all; -- If the finalization of a particular object failed or Finalize_Address -- was not set, reraise the exception now. if Raised then Reraise_Occurrence (Ex_Occur); end if; end Finalize; ---------------------- -- Finalize_Address -- ---------------------- function Finalize_Address (Master : Finalization_Master) return Finalize_Address_Ptr is begin return Master.Finalize_Address; end Finalize_Address; ---------------------------------- -- Finalize_Address_Unprotected -- ---------------------------------- function Finalize_Address_Unprotected (Obj : System.Address) return Finalize_Address_Ptr is begin return Finalize_Address_Table.Get (Obj); end Finalize_Address_Unprotected; -------------------------- -- Finalization_Started -- -------------------------- function Finalization_Started (Master : Finalization_Master) return Boolean is begin return Master.Finalization_Started; end Finalization_Started; ---------- -- Hash -- ---------- function Hash (Key : System.Address) return Header_Num is begin return Header_Num (To_Integer (Key) mod Integer_Address (Header_Num'Range_Length)); end Hash; ----------------- -- Header_Size -- ----------------- function Header_Size return System.Storage_Elements.Storage_Count is begin return FM_Node'Size / Storage_Unit; end Header_Size; ---------------- -- Initialize -- ---------------- overriding procedure Initialize (Master : in out Finalization_Master) is begin -- The dummy head must point to itself in both directions Master.Objects.Next := Master.Objects'Unchecked_Access; Master.Objects.Prev := Master.Objects'Unchecked_Access; end Initialize; -------------------- -- Is_Homogeneous -- -------------------- function Is_Homogeneous (Master : Finalization_Master) return Boolean is begin return Master.Is_Homogeneous; end Is_Homogeneous; ------------- -- Objects -- ------------- function Objects (Master : Finalization_Master) return FM_Node_Ptr is begin return Master.Objects'Unrestricted_Access; end Objects; ------------------ -- Print_Master -- ------------------ procedure Print_Master (Master : Finalization_Master) is Head : constant FM_Node_Ptr := Master.Objects'Unrestricted_Access; Head_Seen : Boolean := False; N_Ptr : FM_Node_Ptr; begin -- Output the basic contents of a master -- Master : 0x123456789 -- Is_Hmgen : TURE <or> FALSE -- Base_Pool: null <or> 0x123456789 -- Fin_Addr : null <or> 0x123456789 -- Fin_Start: TRUE <or> FALSE Put ("Master : "); Put_Line (Address_Image (Master'Address)); Put ("Is_Hmgen : "); Put_Line (Master.Is_Homogeneous'Img); Put ("Base_Pool: "); if Master.Base_Pool = null then Put_Line ("null"); else Put_Line (Address_Image (Master.Base_Pool'Address)); end if; Put ("Fin_Addr : "); if Master.Finalize_Address = null then Put_Line ("null"); else Put_Line (Address_Image (Master.Finalize_Address'Address)); end if; Put ("Fin_Start: "); Put_Line (Master.Finalization_Started'Img); -- Output all chained elements. The format is the following: -- ^ <or> ? <or> null -- |Header: 0x123456789 (dummy head) -- | Prev: 0x123456789 -- | Next: 0x123456789 -- V -- ^ - the current element points back to the correct element -- ? - the current element points back to an erroneous element -- n - the current element points back to null -- Header - the address of the list header -- Prev - the address of the list header which the current element -- points back to -- Next - the address of the list header which the current element -- points to -- (dummy head) - present if dummy head N_Ptr := Head; while N_Ptr /= null loop -- Should never be null Put_Line ("V"); -- We see the head initially; we want to exit when we see the head a -- second time. if N_Ptr = Head then exit when Head_Seen; Head_Seen := True; end if; -- The current element is null. This should never happen since the -- list is circular. if N_Ptr.Prev = null then Put_Line ("null (ERROR)"); -- The current element points back to the correct element elsif N_Ptr.Prev.Next = N_Ptr then Put_Line ("^"); -- The current element points to an erroneous element else Put_Line ("? (ERROR)"); end if; -- Output the header and fields Put ("|Header: "); Put (Address_Image (N_Ptr.all'Address)); -- Detect the dummy head if N_Ptr = Head then Put_Line (" (dummy head)"); else Put_Line (""); end if; Put ("| Prev: "); if N_Ptr.Prev = null then Put_Line ("null"); else Put_Line (Address_Image (N_Ptr.Prev.all'Address)); end if; Put ("| Next: "); if N_Ptr.Next = null then Put_Line ("null"); else Put_Line (Address_Image (N_Ptr.Next.all'Address)); end if; N_Ptr := N_Ptr.Next; end loop; end Print_Master; ------------------- -- Set_Base_Pool -- ------------------- procedure Set_Base_Pool (Master : in out Finalization_Master; Pool_Ptr : Any_Storage_Pool_Ptr) is begin Master.Base_Pool := Pool_Ptr; end Set_Base_Pool; -------------------------- -- Set_Finalize_Address -- -------------------------- procedure Set_Finalize_Address (Master : in out Finalization_Master; Fin_Addr_Ptr : Finalize_Address_Ptr) is begin -- Synchronization: -- Read - finalization -- Write - allocation, outside Lock_Task.all; Set_Finalize_Address_Unprotected (Master, Fin_Addr_Ptr); Unlock_Task.all; end Set_Finalize_Address; -------------------------------------- -- Set_Finalize_Address_Unprotected -- -------------------------------------- procedure Set_Finalize_Address_Unprotected (Master : in out Finalization_Master; Fin_Addr_Ptr : Finalize_Address_Ptr) is begin if Master.Finalize_Address = null then Master.Finalize_Address := Fin_Addr_Ptr; end if; end Set_Finalize_Address_Unprotected; ---------------------------------------------------- -- Set_Heterogeneous_Finalize_Address_Unprotected -- ---------------------------------------------------- procedure Set_Heterogeneous_Finalize_Address_Unprotected (Obj : System.Address; Fin_Addr_Ptr : Finalize_Address_Ptr) is begin Finalize_Address_Table.Set (Obj, Fin_Addr_Ptr); end Set_Heterogeneous_Finalize_Address_Unprotected; -------------------------- -- Set_Is_Heterogeneous -- -------------------------- procedure Set_Is_Heterogeneous (Master : in out Finalization_Master) is begin -- Synchronization: -- Read - finalization -- Write - outside Lock_Task.all; Master.Is_Homogeneous := False; Unlock_Task.all; end Set_Is_Heterogeneous; end System.Finalization_Masters;
stcarrez/ada-util
Ada
6,005
adb
----------------------------------------------------------------------- -- util-locales -- Locale support -- Copyright (C) 2001 - 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- 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.Hash; package body Util.Locales is -- ------------------------------ -- Get the lowercase two-letter ISO-639 code. -- ------------------------------ function Get_Language (Loc : in Locale) return String is begin if Loc = null then return ""; else return Loc (1 .. 2); end if; end Get_Language; -- ------------------------------ -- Get the ISO 639-2 language code. -- ------------------------------ function Get_ISO3_Language (Loc : in Locale) return String is begin if Loc = null or else Loc'Length <= 3 then return ""; end if; if Loc'Length <= 6 then return Loc (4 .. 6); end if; if Loc'Length <= 13 then return Loc (7 .. 9); end if; return Loc (10 .. 15); end Get_ISO3_Language; -- ------------------------------ -- Get the uppercase two-letter ISO-3166 code. -- ------------------------------ function Get_Country (Loc : in Locale) return String is begin if Loc = null or else Loc'Length <= 2 or else Loc (3) /= '_' then return ""; else return Loc (4 .. 5); end if; end Get_Country; -- ------------------------------ -- Get the ISO-3166-2 country code. -- ------------------------------ function Get_ISO3_Country (Loc : in Locale) return String is begin if Loc = null or else Loc'Length <= 9 then return ""; else return Loc (Loc'Last - 2 .. Loc'Last); end if; end Get_ISO3_Country; -- ------------------------------ -- Get the variant code -- ------------------------------ function Get_Variant (Loc : in Locale) return String is begin if Loc = null or else Loc'Length <= 13 then return ""; else return Loc (7 .. 8); end if; end Get_Variant; -- ------------------------------ -- Get the locale for the given language code -- ------------------------------ function Get_Locale (Language : in String) return Locale is Length : constant Natural := Language'Length; Lower : Natural := Locales'First; Upper : Natural := Locales'Last; Pos : Natural; Result : Locale; begin while Lower <= Upper loop Pos := (Lower + Upper) / 2; Result := Locales (Pos); if Result'Length < Length then if Result.all < Language (Language'First .. Language'First + Result'Length - 1) then Lower := Pos + 1; else Upper := Pos - 1; end if; elsif Result'Length > Length and then Result (Length + 1) = '.' and then Result (1 .. Length) = Language then return Result; elsif Result (1 .. Length) < Language then Lower := Pos + 1; else Upper := Pos - 1; end if; end loop; return NULL_LOCALE; end Get_Locale; -- ------------------------------ -- Get the locale for the given language and country code -- ------------------------------ function Get_Locale (Language : in String; Country : in String) return Locale is begin if Language'Length /= 2 or else (Country'Length /= 0 and then Country'Length /= 2) then return NULL_LOCALE; elsif Country'Length = 0 then return Get_Locale (Language); else return Get_Locale (Language & "_" & Country); end if; end Get_Locale; -- ------------------------------ -- Get the locale for the given language, country and variant code -- ------------------------------ function Get_Locale (Language : in String; Country : in String; Variant : in String) return Locale is begin if Language'Length /= 2 or else (Country'Length /= 0 and then Country'Length /= 2) or else (Variant'Length /= 0 and then Variant'Length /= 2) then return NULL_LOCALE; end if; if Country'Length = 0 and then Variant'Length = 0 then return Get_Locale (Language); elsif Variant'Length = 0 then return Get_Locale (Language, Country); else return Get_Locale (Language & "_" & Country & "_" & Variant); end if; end Get_Locale; -- ------------------------------ -- Get the locale code in the form <i>language</i>_<i>country</i>_<i>variant</i>. -- ------------------------------ function To_String (Loc : in Locale) return String is begin if Loc = null then return ""; elsif Loc'Length > 3 and then Loc (3) = '.' then return Loc (1 .. 2); elsif Loc'Length > 6 and then Loc (6) = '.' then return Loc (1 .. 5); else return Loc (1 .. 8); end if; end To_String; -- ------------------------------ -- Compute the hash value of the locale. -- ------------------------------ function Hash (Loc : in Locale) return Ada.Containers.Hash_Type is begin return Ada.Strings.Hash (Loc.all); end Hash; end Util.Locales;
reznikmm/matreshka
Ada
5,559
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Ada Modeling Framework -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2011-2012, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ -- This file is generated, don't edit it. ------------------------------------------------------------------------------ with AMF.Generic_Collections; package AMF.UML.Operation_Template_Parameters.Collections is pragma Preelaborate; package UML_Operation_Template_Parameter_Collections is new AMF.Generic_Collections (UML_Operation_Template_Parameter, UML_Operation_Template_Parameter_Access); type Set_Of_UML_Operation_Template_Parameter is new UML_Operation_Template_Parameter_Collections.Set with null record; Empty_Set_Of_UML_Operation_Template_Parameter : constant Set_Of_UML_Operation_Template_Parameter; type Ordered_Set_Of_UML_Operation_Template_Parameter is new UML_Operation_Template_Parameter_Collections.Ordered_Set with null record; Empty_Ordered_Set_Of_UML_Operation_Template_Parameter : constant Ordered_Set_Of_UML_Operation_Template_Parameter; type Bag_Of_UML_Operation_Template_Parameter is new UML_Operation_Template_Parameter_Collections.Bag with null record; Empty_Bag_Of_UML_Operation_Template_Parameter : constant Bag_Of_UML_Operation_Template_Parameter; type Sequence_Of_UML_Operation_Template_Parameter is new UML_Operation_Template_Parameter_Collections.Sequence with null record; Empty_Sequence_Of_UML_Operation_Template_Parameter : constant Sequence_Of_UML_Operation_Template_Parameter; private Empty_Set_Of_UML_Operation_Template_Parameter : constant Set_Of_UML_Operation_Template_Parameter := (UML_Operation_Template_Parameter_Collections.Set with null record); Empty_Ordered_Set_Of_UML_Operation_Template_Parameter : constant Ordered_Set_Of_UML_Operation_Template_Parameter := (UML_Operation_Template_Parameter_Collections.Ordered_Set with null record); Empty_Bag_Of_UML_Operation_Template_Parameter : constant Bag_Of_UML_Operation_Template_Parameter := (UML_Operation_Template_Parameter_Collections.Bag with null record); Empty_Sequence_Of_UML_Operation_Template_Parameter : constant Sequence_Of_UML_Operation_Template_Parameter := (UML_Operation_Template_Parameter_Collections.Sequence with null record); end AMF.UML.Operation_Template_Parameters.Collections;
gspu/synth
Ada
61,286
adb
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Ada.Strings.Hash; with Ada.Calendar.Formatting; with GNAT.Regpat; with GNAT.String_Split; with Signals; with Unix; package body PortScan is package ACF renames Ada.Calendar.Formatting; package RGX renames GNAT.Regpat; package GSS renames GNAT.String_Split; package SIG renames Signals; ------------------------------ -- scan_entire_ports_tree -- ------------------------------ function scan_entire_ports_tree (portsdir : String) return Boolean is good_scan : Boolean; using_screen : constant Boolean := Unix.screen_attached; begin -- tree must be already mounted in the scan slave. -- However, prescan works on the real ports tree, not the mount. if not prescanned then read_flavor_index; end if; scan_start := CAL.Clock; parallel_deep_scan (success => good_scan, show_progress => using_screen); scan_stop := CAL.Clock; return good_scan; end scan_entire_ports_tree; ------------------------ -- scan_single_port -- ------------------------ function scan_single_port (catport : String; always_build : Boolean; fatal : out Boolean) return Boolean is xports : constant String := JT.USS (PM.configuration.dir_buildbase) & ss_base & dir_ports; procedure dig (cursor : block_crate.Cursor); target : port_index; aborted : Boolean := False; indy500 : Boolean := False; uscatport : JT.Text := JT.SUS (catport); procedure dig (cursor : block_crate.Cursor) is new_target : port_index := block_crate.Element (cursor); begin if not aborted then if all_ports (new_target).scan_locked then -- We've already seen this (circular dependency) raise circular_logic; end if; if not all_ports (new_target).scanned then populate_port_data (new_target); all_ports (new_target).scan_locked := True; all_ports (new_target).blocked_by.Iterate (dig'Access); all_ports (new_target).scan_locked := False; if indy500 then TIO.Put_Line ("... backtrace " & get_catport (all_ports (new_target))); end if; end if; end if; exception when issue : nonexistent_port => aborted := True; TIO.Put_Line (LAT.LF & get_catport (all_ports (new_target)) & " scan aborted because dependency could " & "not be located."); TIO.Put_Line (EX.Exception_Message (issue)); when issue : bmake_execution => aborted := True; TIO.Put_Line (LAT.LF & get_catport (all_ports (new_target)) & " scan aborted because 'make' encounted " & "an error in the Makefile."); TIO.Put_Line (EX.Exception_Message (issue)); when issue : make_garbage => aborted := True; TIO.Put_Line (LAT.LF & get_catport (all_ports (new_target)) & " scan aborted because dependency is malformed."); TIO.Put_Line (EX.Exception_Message (issue)); when issue : circular_logic => aborted := True; indy500 := True; TIO.Put_Line (LAT.LF & catport & " scan aborted because a circular dependency on " & get_catport (all_ports (new_target)) & " was detected."); when issue : others => aborted := True; declare why : constant String := obvious_problem (xports, get_catport (all_ports (new_target))); begin if why = "" then TIO.Put_Line (LAT.LF & get_catport (all_ports (new_target)) & " scan aborted for an unknown reason."); TIO.Put_Line (EX.Exception_Message (issue)); else TIO.Put_Line (LAT.LF & get_catport (all_ports (new_target)) & " scan aborted" & why); end if; end; end dig; begin fatal := False; if not AD.Exists (xports & "/" & JT.part_1 (catport, "@") & "/Makefile") then return False; end if; if not prescanned then read_flavor_index; end if; if ports_keys.Contains (Key => uscatport) then target := ports_keys.Element (Key => uscatport); else return False; end if; begin if all_ports (target).scanned then -- This can happen when a dependency is also on the build list. return True; else populate_port_data (target); all_ports (target).never_remote := always_build; end if; exception when issue : others => TIO.Put ("Encountered issue with " & catport & " or its dependencies" & LAT.LF & " => "); TIO.Put_Line (EX.Exception_Message (issue)); return False; end; all_ports (target).scan_locked := True; all_ports (target).blocked_by.Iterate (dig'Access); all_ports (target).scan_locked := False; if indy500 then TIO.Put_Line ("... backtrace " & catport); fatal := True; end if; return not aborted; end scan_single_port; -------------------------- -- set_build_priority -- -------------------------- procedure set_build_priority is begin iterate_reverse_deps; iterate_drill_down; end set_build_priority; ------------------------ -- reset_ports_tree -- ------------------------ procedure reset_ports_tree is PR : port_record_access; begin for k in dim_all_ports'Range loop PR := all_ports (k)'Access; PR.sequence_id := 0; PR.key_cursor := portkey_crate.No_Element; PR.jobs := 1; PR.ignore_reason := JT.blank; PR.port_version := JT.blank; PR.package_name := JT.blank; PR.pkg_dep_query := JT.blank; PR.ignored := False; PR.scanned := False; PR.rev_scanned := False; PR.unlist_failed := False; PR.work_locked := False; PR.scan_locked := False; PR.pkg_present := False; PR.remote_pkg := False; PR.never_remote := False; PR.deletion_due := False; PR.use_procfs := False; PR.use_linprocfs := False; PR.reverse_score := 0; PR.min_librun := 0; PR.librun.Clear; PR.blocks.Clear; PR.blocked_by.Clear; PR.all_reverse.Clear; PR.options.Clear; PR.flavors.Clear; end loop; ports_keys.Clear; rank_queue.Clear; lot_number := 1; lot_counter := 0; last_port := 0; prescanned := False; wipe_make_queue; for m in scanners'Range loop mq_progress (m) := 0; end loop; end reset_ports_tree; -- PRIVATE FUNCTIONS -- -------------------------- -- iterate_drill_down -- -------------------------- procedure iterate_drill_down is begin rank_queue.Clear; for port in port_index'First .. last_port loop if all_ports (port).scanned then drill_down (next_target => port, original_target => port); declare ndx : constant port_index := port_index (all_ports (port).reverse_score); QR : constant queue_record := (ap_index => port, reverse_score => ndx); begin rank_queue.Insert (New_Item => QR); end; end if; end loop; end iterate_drill_down; -------------------------- -- parallel_deep_scan -- -------------------------- procedure parallel_deep_scan (success : out Boolean; show_progress : Boolean) is finished : array (scanners) of Boolean := (others => False); combined_wait : Boolean := True; aborted : Boolean := False; task type scan (lot : scanners); task body scan is procedure populate (cursor : subqueue.Cursor); procedure abort_now (culprit, issue_msg, exmsg : String); procedure populate (cursor : subqueue.Cursor) is target_port : port_index := subqueue.Element (cursor); begin if not aborted then populate_port_data (target_port); mq_progress (lot) := mq_progress (lot) + 1; end if; exception when issue : nonexistent_port => abort_now (culprit => get_catport (all_ports (target_port)), issue_msg => "because dependency could not be located", exmsg => EX.Exception_Message (issue)); when issue : bmake_execution => abort_now (culprit => get_catport (all_ports (target_port)), issue_msg => "because 'make' encounted an error in the Makefile", exmsg => EX.Exception_Message (issue)); when issue : make_garbage => abort_now (culprit => get_catport (all_ports (target_port)), issue_msg => "because dependency is malformed", exmsg => EX.Exception_Message (issue)); when issue : others => abort_now (culprit => get_catport (all_ports (target_port)), issue_msg => "for an unknown reason", exmsg => EX.Exception_Message (issue)); end populate; procedure abort_now (culprit, issue_msg, exmsg : String) is begin aborted := True; TIO.Put_Line (LAT.LF & "culprit: " & culprit); TIO.Put_Line (" Scan aborted " & issue_msg & "."); TIO.Put_Line (" " & exmsg); end abort_now; begin make_queue (lot).Iterate (populate'Access); finished (lot) := True; end scan; scan_01 : scan (lot => 1); scan_02 : scan (lot => 2); scan_03 : scan (lot => 3); scan_04 : scan (lot => 4); scan_05 : scan (lot => 5); scan_06 : scan (lot => 6); scan_07 : scan (lot => 7); scan_08 : scan (lot => 8); scan_09 : scan (lot => 9); scan_10 : scan (lot => 10); scan_11 : scan (lot => 11); scan_12 : scan (lot => 12); scan_13 : scan (lot => 13); scan_14 : scan (lot => 14); scan_15 : scan (lot => 15); scan_16 : scan (lot => 16); scan_17 : scan (lot => 17); scan_18 : scan (lot => 18); scan_19 : scan (lot => 19); scan_20 : scan (lot => 20); scan_21 : scan (lot => 21); scan_22 : scan (lot => 22); scan_23 : scan (lot => 23); scan_24 : scan (lot => 24); scan_25 : scan (lot => 25); scan_26 : scan (lot => 26); scan_27 : scan (lot => 27); scan_28 : scan (lot => 28); scan_29 : scan (lot => 29); scan_30 : scan (lot => 30); scan_31 : scan (lot => 31); scan_32 : scan (lot => 32); -- Expansion of cpu_range from 32 to 64 means 64 possible scanners scan_33 : scan (lot => 33); scan_34 : scan (lot => 34); scan_35 : scan (lot => 35); scan_36 : scan (lot => 36); scan_37 : scan (lot => 37); scan_38 : scan (lot => 38); scan_39 : scan (lot => 39); scan_40 : scan (lot => 40); scan_41 : scan (lot => 41); scan_42 : scan (lot => 42); scan_43 : scan (lot => 43); scan_44 : scan (lot => 44); scan_45 : scan (lot => 45); scan_46 : scan (lot => 46); scan_47 : scan (lot => 47); scan_48 : scan (lot => 48); scan_49 : scan (lot => 49); scan_50 : scan (lot => 50); scan_51 : scan (lot => 51); scan_52 : scan (lot => 52); scan_53 : scan (lot => 53); scan_54 : scan (lot => 54); scan_55 : scan (lot => 55); scan_56 : scan (lot => 56); scan_57 : scan (lot => 57); scan_58 : scan (lot => 58); scan_59 : scan (lot => 59); scan_60 : scan (lot => 60); scan_61 : scan (lot => 61); scan_62 : scan (lot => 62); scan_63 : scan (lot => 63); scan_64 : scan (lot => 64); begin TIO.Put_Line ("Scanning entire ports tree."); while combined_wait loop delay 1.0; if show_progress then TIO.Put (scan_progress); end if; combined_wait := False; for j in scanners'Range loop if not finished (j) then combined_wait := True; exit; end if; end loop; if SIG.graceful_shutdown_requested then aborted := True; end if; end loop; success := not aborted; if show_progress then TIO.Put (scan_progress); end if; end parallel_deep_scan; ----------------------- -- wipe_make_queue -- ----------------------- procedure wipe_make_queue is begin for j in scanners'Range loop make_queue (j).Clear; end loop; end wipe_make_queue; ------------------ -- drill_down -- ------------------ procedure drill_down (next_target : port_index; original_target : port_index) is PR : port_record_access := all_ports (next_target)'Access; procedure stamp_and_drill (cursor : block_crate.Cursor); procedure slurp_scanned (cursor : block_crate.Cursor); procedure slurp_scanned (cursor : block_crate.Cursor) is rev_id : port_index := block_crate.Element (Position => cursor); begin if not all_ports (original_target).all_reverse.Contains (rev_id) then all_ports (original_target).all_reverse.Insert (Key => rev_id, New_Item => rev_id); end if; end slurp_scanned; procedure stamp_and_drill (cursor : block_crate.Cursor) is pmc : port_index := block_crate.Element (Position => cursor); begin if not all_ports (original_target).all_reverse.Contains (pmc) then all_ports (original_target).all_reverse.Insert (Key => pmc, New_Item => pmc); end if; if pmc = original_target then declare top_port : constant String := get_catport (all_ports (original_target)); this_port : constant String := get_catport (all_ports (next_target)); begin raise circular_logic with top_port & " <=> " & this_port; end; end if; if not all_ports (pmc).rev_scanned then drill_down (next_target => pmc, original_target => pmc); end if; all_ports (pmc).all_reverse.Iterate (slurp_scanned'Access); end stamp_and_drill; begin if not PR.scanned then return; end if; if PR.rev_scanned then -- It is possible to get here if an earlier port scanned this port -- as a reverse dependencies return; end if; PR.blocks.Iterate (stamp_and_drill'Access); PR.reverse_score := port_index (PR.all_reverse.Length); PR.rev_scanned := True; end drill_down; ---------------------------- -- iterate_reverse_deps -- ----------------------------- procedure iterate_reverse_deps is madre : port_index; procedure set_reverse (cursor : block_crate.Cursor); procedure set_reverse (cursor : block_crate.Cursor) is begin -- Using conditional insert here causes a finalization error when -- the program exists. Reluctantly, do the condition check manually if not all_ports (block_crate.Element (cursor)).blocks.Contains (Key => madre) then all_ports (block_crate.Element (cursor)).blocks.Insert (Key => madre, New_Item => madre); end if; end set_reverse; begin for port in port_index'First .. last_port loop if all_ports (port).scanned then madre := port; all_ports (port).blocked_by.Iterate (set_reverse'Access); end if; end loop; end iterate_reverse_deps; -------------------- -- get_pkg_name -- -------------------- function get_pkg_name (origin : String) return String is function get_fullport return String; function get_fullport return String is begin -- if format is cat/port@something then -- return "cat/port FLAVOR=something" -- else -- return $catport if JT.contains (origin, "@") then return dir_ports & "/" & JT.part_1 (origin, "@") & " FLAVOR=" & JT.part_2 (origin, "@"); else return dir_ports & "/" & origin; end if; end get_fullport; scanenv : constant String := scan_environment; fullport : constant String := get_fullport; ssroot : constant String := chroot & JT.USS (PM.configuration.dir_buildbase) & ss_base; command : constant String := scanenv & ssroot & " " & chroot_make_program & " .MAKE.EXPAND_VARIABLES=yes -C " & fullport & " -VPKGFILE:T"; content : JT.Text; topline : JT.Text; status : Integer; begin -- Same command for both ports collection and pkgsrc content := Unix.piped_command (command, status); if status /= 0 then raise bmake_execution with origin & " (return code =" & status'Img & ")"; end if; JT.nextline (lineblock => content, firstline => topline); return JT.USS (topline); end get_pkg_name; ---------------------------- -- populate_set_depends -- ---------------------------- procedure populate_set_depends (target : port_index; catport : String; line : JT.Text; dtype : dependency_type) is subs : GSS.Slice_Set; deps_found : GSS.Slice_Number; trimline : constant JT.Text := JT.trimtab (line); zero_deps : constant GSS.Slice_Number := GSS.Slice_Number (0); dirlen : constant Natural := dir_ports'Length; bracketed : Natural := 0; use type GSS.Slice_Number; begin if not fullpop or else JT.IsBlank (trimline) then return; end if; GSS.Create (S => subs, From => JT.USS (trimline), Separators => " " & LAT.HT, Mode => GSS.Multiple); deps_found := GSS.Slice_Count (S => subs); if deps_found = zero_deps then return; end if; for j in 1 .. deps_found loop declare workdep : constant String := GSS.Slice (subs, j); fulldep : constant String (1 .. workdep'Length) := workdep; flen : constant Natural := fulldep'Length; colon : constant Natural := find_colon (fulldep); colon1 : constant Natural := colon + 1; DNE : Boolean := True; deprec : portkey_crate.Cursor; pkey : JT.Text; use type portkey_crate.Cursor; begin if colon < 2 then raise make_garbage with dtype'Img & ": " & JT.USS (trimline) & " (" & catport & ")"; end if; if flen > colon1 + dirlen + 1 and then fulldep (colon1 .. colon1 + dirlen) = dir_ports & "/" then pkey := scrub_phase (fulldep (colon + dirlen + 2 .. fulldep'Last)); elsif flen > colon1 + 5 and then fulldep (colon1 .. colon1 + 5) = "../../" then pkey := scrub_phase (fulldep (colon1 + 6 .. fulldep'Last)); else pkey := scrub_phase (fulldep (colon1 .. fulldep'Last)); end if; deprec := ports_keys.Find (pkey); if deprec = portkey_crate.No_Element then -- This dependency apparently does not exist. -- However, it could be flavored port that doesn't specify the flavor, so -- in this case, we have to look up the FIRST defined flavor (the default) -- The flavor order of the flavor index is therefore critical declare flport : port_index; begin if so_porthash.Contains (pkey) then flport := so_porthash.Element (pkey); deprec := all_ports (flport).key_cursor; if deprec /= portkey_crate.No_Element then DNE := False; end if; end if; end; if DNE then raise nonexistent_port with fulldep & " (required dependency of " & catport & ") does not exist."; end if; end if; declare depindex : port_index := portkey_crate.Element (deprec); begin if not all_ports (target).blocked_by.Contains (depindex) then all_ports (target).blocked_by.Insert (Key => depindex, New_Item => depindex); end if; if dtype in LR_set then if not all_ports (target).librun.Contains (depindex) then all_ports (target).librun.Insert (Key => depindex, New_Item => depindex); all_ports (target).min_librun := all_ports (target).min_librun + 1; case software_framework is when ports_collection => null; when pkgsrc => if fulldep (1) = '{' then bracketed := bracketed + 1; end if; end case; end if; end if; end; end; end loop; if bracketed > 0 and then all_ports (target).min_librun > 1 then declare newval : Integer := all_ports (target).min_librun - bracketed; begin if newval <= 1 then all_ports (target).min_librun := 1; else all_ports (target).min_librun := newval; end if; end; end if; end populate_set_depends; ---------------------------- -- populate_set_options -- ---------------------------- procedure populate_set_options (target : port_index; line : JT.Text; on : Boolean) is subs : GSS.Slice_Set; opts_found : GSS.Slice_Number; trimline : constant JT.Text := JT.trim (line); zero_opts : constant GSS.Slice_Number := GSS.Slice_Number (0); use type GSS.Slice_Number; begin if not fullpop or else JT.IsBlank (trimline) then return; end if; GSS.Create (S => subs, From => JT.USS (trimline), Separators => " ", Mode => GSS.Multiple); opts_found := GSS.Slice_Count (S => subs); if opts_found = zero_opts then return; end if; for j in 1 .. opts_found loop declare opt : JT.Text := JT.SUS (GSS.Slice (subs, j)); begin if not all_ports (target).options.Contains (opt) then all_ports (target).options.Insert (Key => opt, New_Item => on); end if; end; end loop; end populate_set_options; -------------------------- -- populate_flavors -- -------------------------- procedure populate_flavors (target : port_index; line : JT.Text) is subs : GSS.Slice_Set; flav_found : GSS.Slice_Number; trimline : constant JT.Text := JT.trimtab (line); zero_flav : constant GSS.Slice_Number := GSS.Slice_Number (0); use type GSS.Slice_Number; begin if JT.IsBlank (trimline) then return; end if; GSS.Create (S => subs, From => JT.USS (trimline), Separators => " " & LAT.HT, Mode => GSS.Multiple); flav_found := GSS.Slice_Count (S => subs); if flav_found = zero_flav then return; end if; for j in 1 .. flav_found loop declare flavor : JT.Text := JT.SUS (GSS.Slice (subs, j)); begin if not all_ports (target).flavors.Contains (flavor) then all_ports (target).flavors.Append (flavor); end if; end; end loop; end populate_flavors; -------------------------- -- populate_port_data -- -------------------------- procedure populate_port_data (target : port_index) is begin case software_framework is when ports_collection => populate_port_data_fpc (target); when pkgsrc => populate_port_data_nps (target); end case; end populate_port_data; ------------------------------ -- populate_port_data_fpc -- ------------------------------ procedure populate_port_data_fpc (target : port_index) is function get_fullport return String; catport : constant String := get_catport (all_ports (target)); function get_fullport return String is begin -- if format is cat/port@something then -- return "cat/port FLAVOR=something" -- else -- return $catport if JT.contains (catport, "@") then return dir_ports & "/" & JT.part_1 (catport, "@") & " FLAVOR=" & JT.part_2 (catport, "@"); else return dir_ports & "/" & catport; end if; end get_fullport; scanenv : constant String := scan_environment; fullport : constant String := get_fullport; ssroot : constant String := chroot & JT.USS (PM.configuration.dir_buildbase) & ss_base; command : constant String := scanenv & ssroot & " " & chroot_make_program & " -C " & fullport & " -VPKGVERSION -VPKGFILE:T -VMAKE_JOBS_NUMBER -VIGNORE" & " -VFETCH_DEPENDS -VEXTRACT_DEPENDS -VPATCH_DEPENDS" & " -VBUILD_DEPENDS -VLIB_DEPENDS -VRUN_DEPENDS" & " -VSELECTED_OPTIONS -VDESELECTED_OPTIONS -VUSE_LINUX" & " -VFLAVORS"; content : JT.Text; topline : JT.Text; status : Integer; type result_range is range 1 .. 14; begin content := Unix.piped_command (command, status); if status /= 0 then raise bmake_execution with catport & " (return code =" & status'Img & ")"; end if; for k in result_range loop JT.nextline (lineblock => content, firstline => topline); case k is when 1 => all_ports (target).port_version := topline; when 2 => all_ports (target).package_name := topline; when 3 => begin all_ports (target).jobs := builders (Integer'Value (JT.USS (topline))); exception when others => all_ports (target).jobs := PM.configuration.num_builders; end; when 4 => all_ports (target).ignore_reason := topline; all_ports (target).ignored := not JT.IsBlank (topline); when 5 => populate_set_depends (target, catport, topline, fetch); when 6 => populate_set_depends (target, catport, topline, extract); when 7 => populate_set_depends (target, catport, topline, patch); when 8 => populate_set_depends (target, catport, topline, build); when 9 => populate_set_depends (target, catport, topline, library); when 10 => populate_set_depends (target, catport, topline, runtime); when 11 => populate_set_options (target, topline, True); when 12 => populate_set_options (target, topline, False); when 13 => if not JT.IsBlank (JT.trim (topline)) then all_ports (target).use_linprocfs := True; end if; when 14 => populate_flavors (target, topline); end case; end loop; all_ports (target).scanned := True; if catport = "x11-toolkits/gnustep-gui" then all_ports (target).use_procfs := True; end if; if catport = "emulators/linux_base-c6" or else catport = "emulators/linux_base-f10" then all_ports (target).use_linprocfs := True; end if; exception when issue : others => EX.Reraise_Occurrence (issue); end populate_port_data_fpc; ------------------------------ -- populate_port_data_nps -- ------------------------------ procedure populate_port_data_nps (target : port_index) is catport : String := get_catport (all_ports (target)); fullport : constant String := dir_ports & "/" & catport; scanenv : constant String := scan_environment; ssroot : constant String := chroot & JT.USS (PM.configuration.dir_buildbase) & ss_base; command : constant String := scanenv & ssroot & " " & chroot_make_program & " -C " & fullport & " .MAKE.EXPAND_VARIABLES=yes " & " -VPKGVERSION -VPKGFILE:T -V_MAKE_JOBS:C/^-j//" & " -V_CBBH_MSGS -VTOOL_DEPENDS -VBUILD_DEPENDS -VDEPENDS" & " -VPKG_OPTIONS -VPKG_DISABLED_OPTIONS" & " -VEMUL_PLATFORMS"; content : JT.Text; topline : JT.Text; status : Integer; type result_range is range 1 .. 10; begin content := Unix.piped_command (command, status); if status /= 0 then raise bmake_execution with catport & " (return code =" & status'Img & ")"; end if; for k in result_range loop JT.nextline (lineblock => content, firstline => topline); case k is when 1 => all_ports (target).port_version := topline; when 2 => all_ports (target).package_name := topline; when 3 => if JT.IsBlank (topline) then all_ports (target).jobs := PM.configuration.num_builders; else begin all_ports (target).jobs := builders (Integer'Value (JT.USS (topline))); exception when others => all_ports (target).jobs := PM.configuration.num_builders; end; end if; when 4 => all_ports (target).ignore_reason := clean_up_pkgsrc_ignore_reason (JT.USS (topline)); all_ports (target).ignored := not JT.IsBlank (topline); when 5 => populate_set_depends (target, catport, topline, build); when 6 => populate_set_depends (target, catport, topline, build); when 7 => populate_set_depends (target, catport, topline, runtime); when 8 => populate_set_options (target, topline, True); when 9 => populate_set_options (target, topline, False); when 10 => if JT.contains (topline, "linux") then all_ports (target).use_linprocfs := True; end if; end case; end loop; all_ports (target).scanned := True; if catport = "x11/gnustep-gui" then all_ports (target).use_procfs := True; end if; exception when issue : others => EX.Reraise_Occurrence (issue); end populate_port_data_nps; ----------------- -- set_cores -- ----------------- procedure set_cores is number : constant Positive := Replicant.Platform.get_number_cpus; begin if number > Positive (cpu_range'Last) then number_cores := cpu_range'Last; else number_cores := cpu_range (number); end if; end set_cores; ----------------------- -- cores_available -- ----------------------- function cores_available return cpu_range is begin return number_cores; end cores_available; -------------------------- -- prescan_ports_tree -- -------------------------- procedure prescan_ports_tree (portsdir : String) is package sorter is new string_crate.Generic_Sorting ("<" => JT.SU."<"); procedure quick_scan (cursor : string_crate.Cursor); Search : AD.Search_Type; Dir_Ent : AD.Directory_Entry_Type; categories : string_crate.Vector; -- scan entire ports tree, and for each port hooked into the build, -- push an initial port_rec into the all_ports container procedure quick_scan (cursor : string_crate.Cursor) is category : constant String := JT.USS (string_crate.Element (Position => cursor)); begin if AD.Exists (portsdir & "/" & category & "/Makefile") then grep_Makefile (portsdir => portsdir, category => category); else walk_all_subdirectories (portsdir => portsdir, category => category); end if; end quick_scan; begin AD.Start_Search (Search => Search, Directory => portsdir, Filter => (AD.Directory => True, others => False), Pattern => "[a-z]*"); while AD.More_Entries (Search => Search) loop AD.Get_Next_Entry (Search => Search, Directory_Entry => Dir_Ent); declare category : constant String := AD.Simple_Name (Dir_Ent); good_directory : Boolean := True; begin case software_framework is when ports_collection => if category = "base" or else category = "distfiles" or else category = "packages" then good_directory := False; end if; when pkgsrc => if category = "bootstrap" or else category = "distfiles" or else category = "doc" or else category = "licenses" or else category = "mk" or else category = "packages" or else category = "regress" then good_directory := False; end if; end case; if good_directory then categories.Append (New_Item => JT.SUS (category)); end if; end; end loop; AD.End_Search (Search => Search); sorter.Sort (Container => categories); categories.Iterate (Process => quick_scan'Access); prescanned := True; end prescan_ports_tree; --------------------------------- -- tree_newer_than_reference -- --------------------------------- function tree_newer_than_reference (portsdir : String; reference : CAL.Time; valid : out Boolean) return Boolean is procedure quick_scan (cursor : string_crate.Cursor); Search : AD.Search_Type; Dir_Ent : AD.Directory_Entry_Type; categories : string_crate.Vector; top_modtime : CAL.Time; keep_going : Boolean := True; procedure quick_scan (cursor : string_crate.Cursor) is category : constant String := JT.USS (string_crate.Element (Position => cursor)); begin if keep_going then keep_going := subdirectory_is_older (portsdir => portsdir, category => category, reference => reference); end if; end quick_scan; use type CAL.Time; begin valid := True; top_modtime := AD.Modification_Time (portsdir); if reference < top_modtime then return True; end if; AD.Start_Search (Search => Search, Directory => portsdir, Filter => (AD.Directory => True, others => False), Pattern => "[a-z]*"); while keep_going and then AD.More_Entries (Search => Search) loop AD.Get_Next_Entry (Search => Search, Directory_Entry => Dir_Ent); declare category : constant String := AD.Simple_Name (Dir_Ent); good_directory : Boolean := True; begin case software_framework is when ports_collection => if category = "base" or else category = "distfiles" or else category = "packages" then good_directory := False; end if; when pkgsrc => if category = "bootstrap" or else category = "distfiles" or else category = "doc" or else category = "licenses" or else category = "mk" or else category = "packages" or else category = "regress" then good_directory := False; end if; end case; if good_directory then if reference < AD.Modification_Time (Dir_Ent) then keep_going := False; else categories.Append (New_Item => JT.SUS (category)); end if; end if; end; end loop; AD.End_Search (Search => Search); if not keep_going then return True; end if; categories.Iterate (Process => quick_scan'Access); return not keep_going; exception when others => valid := False; return False; end tree_newer_than_reference; ------------------ -- find_colon -- ------------------ function find_colon (Source : String) return Natural is result : Natural := 0; strlen : constant Natural := Source'Length; begin for j in 1 .. strlen loop if Source (j) = LAT.Colon then result := j; exit; end if; end loop; return result; end find_colon; ------------------- -- scrub_phase -- ------------------- function scrub_phase (Source : String) return JT.Text is reset : constant String (1 .. Source'Length) := Source; colon : constant Natural := find_colon (reset); begin if colon = 0 then return JT.SUS (reset); end if; return JT.SUS (reset (1 .. colon - 1)); end scrub_phase; -------------------------- -- determine_max_lots -- -------------------------- function get_max_lots return scanners is first_try : constant Positive := Positive (number_cores) * 3; begin if first_try > Positive (scanners'Last) then return scanners'Last; else return scanners (first_try); end if; end get_max_lots; --------------------- -- grep_Makefile -- --------------------- procedure grep_Makefile (portsdir, category : String) is archive : TIO.File_Type; matches : RGX.Match_Array (0 .. 1); pattern : constant String := "^SUBDIR[[:space:]]*[:+:]=[[:space:]]*([[:graph:]]*)"; regex : constant RGX.Pattern_Matcher := RGX.Compile (pattern); max_lots : constant scanners := get_max_lots; begin TIO.Open (File => archive, Mode => TIO.In_File, Name => portsdir & "/" & category & "/Makefile"); while not TIO.End_Of_File (File => archive) loop declare line : constant String := JT.trim (TIO.Get_Line (File => archive)); blank_rec : port_record; kc : portkey_crate.Cursor; success : Boolean; use type RGX.Match_Location; begin RGX.Match (Self => regex, Data => line, Matches => matches); if matches (0) /= RGX.No_Match then declare portkey : constant JT.Text := JT.SUS (category & '/' & line (matches (1).First .. matches (1).Last)); begin ports_keys.Insert (Key => portkey, New_Item => lot_counter, Position => kc, Inserted => success); last_port := lot_counter; all_ports (lot_counter).sequence_id := lot_counter; all_ports (lot_counter).key_cursor := kc; make_queue (lot_number).Append (lot_counter); lot_counter := lot_counter + 1; if lot_number = max_lots then lot_number := 1; else lot_number := lot_number + 1; end if; end; end if; end; end loop; TIO.Close (File => archive); end grep_Makefile; ------------------------------- -- walk_all_subdirectories -- ------------------------------- procedure walk_all_subdirectories (portsdir, category : String) is inner_search : AD.Search_Type; inner_dirent : AD.Directory_Entry_Type; max_lots : constant scanners := get_max_lots; begin AD.Start_Search (Search => inner_search, Directory => portsdir & "/" & category, Filter => (AD.Directory => True, others => False), Pattern => ""); while AD.More_Entries (Search => inner_search) loop AD.Get_Next_Entry (Search => inner_search, Directory_Entry => inner_dirent); declare portname : constant String := AD.Simple_Name (inner_dirent); portkey : constant JT.Text := JT.SUS (category & "/" & portname); kc : portkey_crate.Cursor; success : Boolean; begin if portname /= "." and then portname /= ".." then ports_keys.Insert (Key => portkey, New_Item => lot_counter, Position => kc, Inserted => success); last_port := lot_counter; all_ports (lot_counter).sequence_id := lot_counter; all_ports (lot_counter).key_cursor := kc; make_queue (lot_number).Append (lot_counter); lot_counter := lot_counter + 1; if lot_number = max_lots then lot_number := 1; else lot_number := lot_number + 1; end if; end if; end; end loop; AD.End_Search (inner_search); end walk_all_subdirectories; ----------------------------- -- subdirectory_is_older -- ----------------------------- function subdirectory_is_older (portsdir, category : String; reference : CAL.Time) return Boolean is inner_search : AD.Search_Type; inner_dirent : AD.Directory_Entry_Type; already_newer : Boolean := False; use type CAL.Time; begin AD.Start_Search (Search => inner_search, Directory => portsdir & "/" & category, Filter => (others => True), Pattern => ""); while not already_newer and then AD.More_Entries (Search => inner_search) loop AD.Get_Next_Entry (Search => inner_search, Directory_Entry => inner_dirent); -- We're going to get "." and "..". It's faster to check them (always older) -- than convert to simple name and exclude them. if reference < AD.Modification_Time (inner_dirent) then already_newer := True; end if; end loop; AD.End_Search (inner_search); return not already_newer; end subdirectory_is_older; ----------------- -- port_hash -- ----------------- function port_hash (key : JT.Text) return AC.Hash_Type is begin return Ada.Strings.Hash (JT.USS (key)); end port_hash; ------------------ -- block_hash -- ------------------ function block_hash (key : port_index) return AC.Hash_Type is preresult : constant AC.Hash_Type := AC.Hash_Type (key); use type AC.Hash_Type; begin -- Equivalent to mod 128 return preresult and 2#1111111#; end block_hash; ------------------ -- block_ekey -- ------------------ function block_ekey (left, right : port_index) return Boolean is begin return left = right; end block_ekey; -------------------------------------- -- "<" function for ranking_crate -- -------------------------------------- function "<" (L, R : queue_record) return Boolean is begin if L.reverse_score = R.reverse_score then return R.ap_index > L.ap_index; end if; return L.reverse_score > R.reverse_score; end "<"; ------------------- -- get_catport -- ------------------- function get_catport (PR : port_record) return String is use type portkey_crate.Cursor; begin if PR.key_cursor = portkey_crate.No_Element then return "get_catport: invalid key_cursor"; end if; return JT.USS (portkey_crate.Key (PR.key_cursor)); end get_catport; --------------------- -- scan_progress -- --------------------- function scan_progress return String is type percent is delta 0.01 digits 5; complete : port_index := 0; pc : percent; begin for k in scanners'Range loop complete := complete + mq_progress (k); end loop; pc := percent (100.0 * Float (complete) / Float (last_port)); return " progress:" & pc'Img & "% " & LAT.CR; end scan_progress; ----------------------- -- obvious_problem -- ----------------------- function obvious_problem (portsdir, catport : String) return String is fullpath : constant String := portsdir & "/" & JT.part_1 (catport, "@"); begin if AD.Exists (fullpath) then declare Search : AD.Search_Type; dirent : AD.Directory_Entry_Type; has_contents : Boolean := False; begin AD.Start_Search (Search => Search, Directory => fullpath, Filter => (others => True), Pattern => "*"); while AD.More_Entries (Search => Search) loop AD.Get_Next_Entry (Search => Search, Directory_Entry => dirent); if AD.Simple_Name (dirent) /= "." and then AD.Simple_Name (dirent) /= ".." then has_contents := True; exit; end if; end loop; AD.End_Search (Search => Search); if not has_contents then return " (directory empty)"; end if; if AD.Exists (fullpath & "/Makefile") then return ""; else return " (Makefile missing)"; end if; end; else return " (port deleted)"; end if; end obvious_problem; ------------------------------------- -- clean_up_pkgsrc_ignore_reason -- ------------------------------------- function clean_up_pkgsrc_ignore_reason (dirty_string : String) return JT.Text is -- 1. strip out all double-quotation marks -- 2. strip out all single reverse solidus ("\") -- 3. condense contiguous spaces to a single space function strip_this_package_has_set (raw : String) return String; function strip_this_package_has_set (raw : String) return String is pattern : constant String := "This package has set "; begin if JT.contains (raw, pattern) then declare uno : String := JT.part_1 (raw, pattern); duo : String := JT.part_2 (raw, pattern); begin return strip_this_package_has_set (uno & duo); end; else return raw; end if; end strip_this_package_has_set; product : String (1 .. dirty_string'Length); dstx : Natural := 0; keep_it : Boolean; last_was_slash : Boolean := False; last_was_space : Boolean := False; begin for srcx in dirty_string'Range loop keep_it := True; case dirty_string (srcx) is when LAT.Quotation | LAT.LF => keep_it := False; when LAT.Reverse_Solidus => if not last_was_slash then keep_it := False; end if; last_was_slash := not last_was_slash; when LAT.Space => if last_was_space then keep_it := False; end if; last_was_space := True; last_was_slash := False; when others => last_was_space := False; last_was_slash := False; end case; if keep_it then dstx := dstx + 1; product (dstx) := dirty_string (srcx); end if; end loop; return JT.SUS (strip_this_package_has_set (product (1 .. dstx))); end clean_up_pkgsrc_ignore_reason; ----------------- -- timestamp -- ----------------- function timestamp (hack : CAL.Time; www_format : Boolean := False) return String is function MON (num : CAL.Month_Number) return String; function WKDAY (day : ACF.Day_Name) return String; function MON (num : CAL.Month_Number) return String is begin case num is when 1 => return "JAN"; when 2 => return "FEB"; when 3 => return "MAR"; when 4 => return "APR"; when 5 => return "MAY"; when 6 => return "JUN"; when 7 => return "JUL"; when 8 => return "AUG"; when 9 => return "SEP"; when 10 => return "OCT"; when 11 => return "NOV"; when 12 => return "DEC"; end case; end MON; function WKDAY (day : ACF.Day_Name) return String is begin case day is when ACF.Monday => return "Monday"; when ACF.Tuesday => return "Tuesday"; when ACF.Wednesday => return "Wednesday"; when ACF.Thursday => return "Thursday"; when ACF.Friday => return "Friday"; when ACF.Saturday => return "Saturday"; when ACF.Sunday => return "Sunday"; end case; end WKDAY; begin if www_format then return CAL.Day (hack)'Img & " " & MON (CAL.Month (hack)) & CAL.Year (hack)'Img & ", " & ACF.Image (hack)(11 .. 19) & " UTC"; end if; return WKDAY (ACF.Day_Of_Week (hack)) & "," & CAL.Day (hack)'Img & " " & MON (CAL.Month (hack)) & CAL.Year (hack)'Img & " at" & ACF.Image (hack)(11 .. 19) & " UTC"; end timestamp; ---------------------------- -- generate_ports_index -- ---------------------------- function generate_ports_index (index_file, portsdir : String) return Boolean is procedure add_flavor (cursor : string_crate.Cursor); procedure write_line (cursor : string_crate.Cursor); good_scan : Boolean; handle : TIO.File_Type; all_flavors : string_crate.Vector; basecatport : JT.Text; noprocs : constant REP.slave_options := (others => False); using_screen : constant Boolean := Unix.screen_attached; error_prefix : constant String := "Flavor index generation failed: "; index_full : constant String := index_path & "/" & JT.USS (PM.configuration.profile) & "-index"; procedure add_flavor (cursor : string_crate.Cursor) is line : JT.Text := basecatport; begin JT.SU.Append (line, "@"); JT.SU.Append (line, string_crate.Element (Position => cursor)); all_flavors.Append (line); end add_flavor; procedure write_line (cursor : string_crate.Cursor) is line : constant String := JT.USS (string_crate.Element (Position => cursor)); begin TIO.Put_Line (handle, line); end write_line; begin begin AD.Create_Path (index_path); exception when others => TIO.Put_Line (error_prefix & "could not create " & index_path); return False; end; TIO.Put_Line ("Regenerating flavor index: this may take a while ..."); prescan_ports_tree (portsdir); case software_framework is when ports_collection => REP.initialize (testmode => False, num_cores => cores_available); REP.launch_slave (id => scan_slave, opts => noprocs); fullpop := False; scan_start := CAL.Clock; parallel_deep_scan (success => good_scan, show_progress => using_screen); scan_stop := CAL.Clock; fullpop := True; REP.destroy_slave (id => scan_slave, opts => noprocs); REP.finalize; if not good_scan then TIO.Put_Line (error_prefix & "ports scan"); return False; end if; when pkgsrc => null; end case; begin for port in port_index'First .. last_port loop basecatport := portkey_crate.Key (all_ports (port).key_cursor); if not all_ports (port).flavors.Is_Empty then all_ports (port).flavors.Iterate (add_flavor'Access); else all_flavors.Append (basecatport); end if; end loop; TIO.Create (File => handle, Mode => TIO.Out_File, Name => index_full); all_flavors.Iterate (write_line'Access); TIO.Close (handle); exception when others => if TIO.Is_Open (handle) then TIO.Close (handle); end if; TIO.Put_Line (error_prefix & "writing out index"); return False; end; reset_ports_tree; return True; end generate_ports_index; -------------------------- -- read_flavor_index -- -------------------------- procedure read_flavor_index is handle : TIO.File_Type; max_lots : constant scanners := get_max_lots; index_full : constant String := index_path & "/" & JT.USS (PM.configuration.profile) & "-index"; begin so_porthash.Clear; so_serial.Clear; TIO.Open (File => handle, Mode => TIO.In_File, Name => index_full); while not TIO.End_Of_File (handle) loop declare line : constant String := JT.trim (TIO.Get_Line (handle)); baseport : JT.Text := JT.SUS (JT.part_1 (line, "@")); portkey : JT.Text := JT.SUS (line); blank_rec : port_record; kc : portkey_crate.Cursor; success : Boolean; begin ports_keys.Insert (Key => portkey, New_Item => lot_counter, Position => kc, Inserted => success); so_serial.Append (portkey); last_port := lot_counter; all_ports (last_port).sequence_id := last_port; all_ports (last_port).key_cursor := kc; make_queue (lot_number).Append (last_port); -- Map baseport name to first encounted flavor -- This is used to lookup default flavor when @ modifier is not provided if not so_porthash.Contains (baseport) then so_porthash.Insert (Key => baseport, New_Item => last_port); end if; end; lot_counter := lot_counter + 1; if lot_number = max_lots then lot_number := 1; else lot_number := lot_number + 1; end if; end loop; TIO.Close (handle); prescanned := True; exception when others => if TIO.Is_Open (handle) then TIO.Close (handle); end if; end read_flavor_index; ------------------------------------- -- load_index_for_store_origins -- ------------------------------------- procedure load_index_for_store_origins is handle : TIO.File_Type; index_full : constant String := index_path & "/" & JT.USS (PM.configuration.profile) & "-index"; ndx : port_id := 0; begin TIO.Open (File => handle, Mode => TIO.In_File, Name => index_full); while not TIO.End_Of_File (handle) loop declare portkey : JT.Text := JT.SUS (JT.trim (TIO.Get_Line (handle))); begin so_serial.Append (portkey); so_porthash.Insert (Key => portkey, New_Item => ndx); ndx := ndx + 1; end; end loop; TIO.Close (handle); exception when others => if TIO.Is_Open (handle) then TIO.Close (handle); end if; end load_index_for_store_origins; -------------------------------- -- clear_store_origin_data -- -------------------------------- procedure clear_store_origin_data is begin so_serial.Clear; so_porthash.Clear; end clear_store_origin_data; --------------------------- -- input_origin_valid -- --------------------------- function input_origin_valid (candidate : String) return Boolean is begin return so_porthash.Contains (JT.SUS (candidate)); end input_origin_valid; -------------------------------------- -- suggest_flavor_for_bad_origin -- -------------------------------------- procedure suggest_flavor_for_bad_origin (candidate : String) is procedure suggest (cursor : string_crate.Cursor); adjusted_candidate : String (1 .. candidate'Length + 1) := (others => ' '); pretext : Boolean := False; canlast : Natural := adjusted_candidate'Last; procedure suggest (cursor : string_crate.Cursor) is payload : constant String := JT.USS (string_crate.Element (Position => cursor)); begin if JT.leads (S => payload, fragment => adjusted_candidate (1 .. canlast)) then if not pretext then TIO.Put_Line ("Perhaps you intended one of the following port flavors?"); pretext := True; end if; TIO.Put_Line (" - " & payload); end if; end suggest; begin if JT.contains (candidate, "@") then declare catport : constant String := JT.part_1 (candidate, "@"); begin canlast := catport'Length + 1; adjusted_candidate (1 .. canlast) := catport & "@"; end; else adjusted_candidate := candidate & "@"; end if; TIO.Put_Line ("Error: port origin '" & candidate & "' is not recognized."); so_serial.Iterate (suggest'Access); end suggest_flavor_for_bad_origin; -------------------------------------- -- scan_environment -- -------------------------------------- function scan_environment return String is PATH : constant String := "PATH=/sbin:/bin:/usr/sbin:/usr/bin "; TERM : constant String := "TERM=dumb "; USER : constant String := "USER=root "; HOME : constant String := "HOME=/root "; LANG : constant String := "LANG=C "; begin return " /usr/bin/env -i " & PATH & TERM & USER & HOME & LANG; end scan_environment; end PortScan;
micahwelf/FLTK-Ada
Ada
7,006
adb
with Interfaces.C.Strings, System; use type System.Address; package body FLTK.Widgets.Valuators.Counters is procedure counter_set_draw_hook (W, D : in System.Address); pragma Import (C, counter_set_draw_hook, "counter_set_draw_hook"); pragma Inline (counter_set_draw_hook); procedure counter_set_handle_hook (W, H : in System.Address); pragma Import (C, counter_set_handle_hook, "counter_set_handle_hook"); pragma Inline (counter_set_handle_hook); function new_fl_counter (X, Y, W, H : in Interfaces.C.int; Text : in Interfaces.C.char_array) return System.Address; pragma Import (C, new_fl_counter, "new_fl_counter"); pragma Inline (new_fl_counter); procedure free_fl_counter (A : in System.Address); pragma Import (C, free_fl_counter, "free_fl_counter"); pragma Inline (free_fl_counter); function fl_counter_get_step (C : in System.Address) return Interfaces.C.double; pragma Import (C, fl_counter_get_step, "fl_counter_get_step"); pragma Inline (fl_counter_get_step); procedure fl_counter_set_step (C : in System.Address; T : in Interfaces.C.double); pragma Import (C, fl_counter_set_step, "fl_counter_set_step"); pragma Inline (fl_counter_set_step); procedure fl_counter_set_lstep (C : in System.Address; T : in Interfaces.C.double); pragma Import (C, fl_counter_set_lstep, "fl_counter_set_lstep"); pragma Inline (fl_counter_set_lstep); function fl_counter_get_textcolor (C : in System.Address) return Interfaces.C.unsigned; pragma Import (C, fl_counter_get_textcolor, "fl_counter_get_textcolor"); pragma Inline (fl_counter_get_textcolor); procedure fl_counter_set_textcolor (C : in System.Address; T : in Interfaces.C.unsigned); pragma Import (C, fl_counter_set_textcolor, "fl_counter_set_textcolor"); pragma Inline (fl_counter_set_textcolor); function fl_counter_get_textfont (C : in System.Address) return Interfaces.C.int; pragma Import (C, fl_counter_get_textfont, "fl_counter_get_textfont"); pragma Inline (fl_counter_get_textfont); procedure fl_counter_set_textfont (C : in System.Address; T : in Interfaces.C.int); pragma Import (C, fl_counter_set_textfont, "fl_counter_set_textfont"); pragma Inline (fl_counter_set_textfont); function fl_counter_get_textsize (C : in System.Address) return Interfaces.C.int; pragma Import (C, fl_counter_get_textsize, "fl_counter_get_textsize"); pragma Inline (fl_counter_get_textsize); procedure fl_counter_set_textsize (C : in System.Address; T : in Interfaces.C.int); pragma Import (C, fl_counter_set_textsize, "fl_counter_set_textsize"); pragma Inline (fl_counter_set_textsize); procedure fl_counter_draw (W : in System.Address); pragma Import (C, fl_counter_draw, "fl_counter_draw"); pragma Inline (fl_counter_draw); function fl_counter_handle (W : in System.Address; E : in Interfaces.C.int) return Interfaces.C.int; pragma Import (C, fl_counter_handle, "fl_counter_handle"); pragma Inline (fl_counter_handle); procedure Finalize (This : in out Counter) is begin if This.Void_Ptr /= System.Null_Address and then This in Counter'Class then free_fl_counter (This.Void_Ptr); This.Void_Ptr := System.Null_Address; end if; Finalize (Valuator (This)); end Finalize; package body Forge is function Create (X, Y, W, H : in Integer; Text : in String) return Counter is begin return This : Counter do This.Void_Ptr := new_fl_counter (Interfaces.C.int (X), Interfaces.C.int (Y), Interfaces.C.int (W), Interfaces.C.int (H), Interfaces.C.To_C (Text)); fl_widget_set_user_data (This.Void_Ptr, Widget_Convert.To_Address (This'Unchecked_Access)); counter_set_draw_hook (This.Void_Ptr, Draw_Hook'Address); counter_set_handle_hook (This.Void_Ptr, Handle_Hook'Address); end return; end Create; end Forge; function Get_Step (This : in Counter) return Long_Float is begin return Long_Float (fl_counter_get_step (This.Void_Ptr)); end Get_Step; procedure Set_Step (This : in out Counter; To : in Long_Float) is begin fl_counter_set_step (This.Void_Ptr, Interfaces.C.double (To)); end Set_Step; function Get_Long_Step (This : in Counter) return Long_Float is begin return This.Long_Step; end Get_Long_Step; procedure Set_Long_Step (This : in out Counter; To : in Long_Float) is begin This.Long_Step := To; fl_counter_set_lstep (This.Void_Ptr, Interfaces.C.double (To)); end Set_Long_Step; function Get_Text_Color (This : in Counter) return Color is begin return Color (fl_counter_get_textcolor (This.Void_Ptr)); end Get_Text_Color; procedure Set_Text_Color (This : in out Counter; To : in Color) is begin fl_counter_set_textcolor (This.Void_Ptr, Interfaces.C.unsigned (To)); end Set_Text_Color; function Get_Text_Font (This : in Counter) return Font_Kind is begin return Font_Kind'Val (fl_counter_get_textfont (This.Void_Ptr)); end Get_Text_Font; procedure Set_Text_Font (This : in out Counter; To : in Font_Kind) is begin fl_counter_set_textfont (This.Void_Ptr, Font_Kind'Pos (To)); end Set_Text_Font; function Get_Text_Size (This : in Counter) return Font_Size is begin return Font_Size (fl_counter_get_textsize (This.Void_Ptr)); end Get_Text_Size; procedure Set_Text_Size (This : in out Counter; To : in Font_Size) is begin fl_counter_set_textsize (This.Void_Ptr, Interfaces.C.int (To)); end Set_Text_Size; procedure Draw (This : in out Counter) is begin fl_counter_draw (This.Void_Ptr); end Draw; function Handle (This : in out Counter; Event : in Event_Kind) return Event_Outcome is begin return Event_Outcome'Val (fl_counter_handle (This.Void_Ptr, Event_Kind'Pos (Event))); end Handle; end FLTK.Widgets.Valuators.Counters;
stcarrez/bbox-ada-api
Ada
1,986
ads
----------------------------------------------------------------------- -- druss-commands-wifi -- Wifi related commands -- Copyright (C) 2017, 2018, 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Druss.Commands.Wifi is type Command_Type is new Druss.Commands.Drivers.Command_Type with null record; -- Enable or disable with wifi radio. procedure Do_Enable (Command : in Command_Type; Args : in Argument_List'Class; Context : in out Context_Type); -- Execute the wifi 'status' command to print the Wifi current status. procedure Do_Status (Command : in Command_Type; Args : in Argument_List'Class; Context : in out Context_Type); -- Execute a command to control or get status about the Wifi. overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Write the help associated with the command. overriding procedure Help (Command : in out Command_Type; Name : in String; Context : in out Context_Type); end Druss.Commands.Wifi;
reznikmm/matreshka
Ada
3,729
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- 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 XML.DOM.Attributes; package ODF.DOM.Table_Is_Selection_Attributes is pragma Preelaborate; type ODF_Table_Is_Selection_Attribute is limited interface and XML.DOM.Attributes.DOM_Attribute; type ODF_Table_Is_Selection_Attribute_Access is access all ODF_Table_Is_Selection_Attribute'Class with Storage_Size => 0; end ODF.DOM.Table_Is_Selection_Attributes;
reznikmm/matreshka
Ada
1,511
adb
with Ada.Wide_Wide_Text_IO; with AMF.Facility; with AMF.Elements.Collections; with AMF.Extents.Collections; with AMF.Internals.Modules.MOFEXT_Module; with AMF.Internals.Modules.OCL_Module; with AMF.Internals.Modules.UML_Module; with AMF.Internals.Modules.UTP_Module; with AMF.URI_Stores; with League.Application; with XMI.Reader; with XMI.Writer; procedure XMI.Main is Store : AMF.URI_Stores.URI_Store_Access; procedure Output_URI (Position : AMF.Extents.Collections.Extent_Sets.Cursor); ---------------- -- Output_URI -- ---------------- procedure Output_URI (Position : AMF.Extents.Collections.Extent_Sets.Cursor) is begin Ada.Wide_Wide_Text_IO.Put_Line (" " & AMF.URI_Stores.URI_Store'Class (AMF.Extents.Collections.Extent_Sets.Element (Position).all).Context_URI.To_Wide_Wide_String); end Output_URI; begin -- Initialize facility AMF.Facility.Initialize; -- Load model Store := XMI.Reader.Read_URI (League.Application.Arguments.Element (1)); -- Output list of actually loaded models Ada.Wide_Wide_Text_IO.Put_Line ("Loaded models:"); AMF.Facility.Extent.Iterate (Output_URI'Access); declare Elements : AMF.Elements.Collections.Set_Of_Element := Store.Elements; begin Ada.Wide_Wide_Text_IO.Put_Line (Store.URI (Elements.Element (1)).To_Wide_Wide_String); end; Ada.Wide_Wide_Text_IO.Put_Line (XMI.Writer (Store).To_Wide_Wide_String); end XMI.Main;
io7m/coreland-serial_io
Ada
826
adb
with Ada.Streams.Stream_IO; with Serial_IO; with Test; procedure T_UTF8_03 is package Stream_IO renames Ada.Streams.Stream_IO; type S_t is new Serial_IO.UTF8_String_t (1 .. 8); S : S_t; T : S_t; Output : Stream_IO.File_Type; Input : Stream_IO.File_Type; begin Stream_IO.Create (Name => "t_utf8_03.dat", Mode => Stream_IO.Out_File, File => Output); S (1 .. 8) := ('A', 'B', 'C', 'D', '1', '2', '3', '4'); S_t'Write (Stream_IO.Stream (Output), S); pragma Warnings (Off); Stream_IO.Close (Output); pragma Warnings (On); Stream_IO.Open (Name => "t_utf8_03.dat", Mode => Stream_IO.In_File, File => Input); T := S_t'Input (Stream_IO.Stream (Input)); Test.Assert (S = T); pragma Warnings (Off); Stream_IO.Close (Input); pragma Warnings (On); end T_UTF8_03;
onox/json-ada
Ada
1,731
adb
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2016 onox <[email protected]> -- -- 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 AUnit.Assertions; with AUnit.Test_Caller; with JSON.Parsers; with JSON.Types; package body Test_Streams is package Types is new JSON.Types (Long_Integer, Long_Float); package Parsers is new JSON.Parsers (Types); use AUnit.Assertions; package Caller is new AUnit.Test_Caller (Test); Test_Suite : aliased AUnit.Test_Suites.Test_Suite; function Suite return AUnit.Test_Suites.Access_Test_Suite is Name : constant String := "(Streams) "; begin Test_Suite.Add_Test (Caller.Create (Name & "Parse float_number.txt", Test_Stream_IO'Access)); return Test_Suite'Access; end Suite; use Types; procedure Test_Stream_IO (Object : in out Test) is File_Name : constant String := "float_number.txt"; Parser : Parsers.Parser := Parsers.Create_From_File (File_Name); Value : constant JSON_Value := Parser.Parse; begin Assert (Value.Kind = Float_Kind, "Not a float"); Assert (Value.Value = 3.14, "Expected float value to be equal to 3.14"); end Test_Stream_IO; end Test_Streams;
ekoeppen/STM32_Generic_Ada_Drivers
Ada
2,658
ads
with STM32_SVD.GPIO; use STM32_SVD.GPIO; with STM32_SVD.USART; use STM32_SVD.USART; with STM32_SVD.SPI; use STM32_SVD.SPI; with STM32_SVD.I2C; use STM32_SVD.I2C; with STM32GD.GPIO; with STM32GD.USART; with STM32GD.SPI; with STM32GD.I2C; with STM32GD.RTC; with STM32GD.Clock; with STM32GD.Clock.Tree; with Drivers.Text_IO; with Drivers.RFM69; package STM32GD.Board is package CLOCKS is new STM32GD.Clock.Tree; package BUTTON is new STM32GD.GPIO (Pin => 0, Port => GPIOA_Periph); package LED is new STM32GD.GPIO (Pin => 1, Port => GPIOB_Periph, Output => True); package LED2 is new STM32GD.GPIO (Pin => 0, Port => GPIOB_Periph, Output => True); package LED3 is new STM32GD.GPIO (Pin => 3, Port => GPIOB_Periph, Output => True); package SCLK is new STM32GD.GPIO (Pin => 5, Port => GPIOA_Periph, Alternate => True); package MISO is new STM32GD.GPIO (Pin => 6, Port => GPIOA_Periph, Alternate => True); package MOSI is new STM32GD.GPIO (Pin => 7, Port => GPIOA_Periph, Alternate => True); package CSN is new STM32GD.GPIO (Pin => 4, Port => GPIOA_Periph, Output => True); package TX is new STM32GD.GPIO (Pin => 9, Port => GPIOA_Periph, Pull_Up => True, Alternate => True, Alternate_Function => 1); package RX is new STM32GD.GPIO (Pin => 10, Port => GPIOA_Periph, Pull_Up => True, Alternate => True, Alternate_Function => 1); package RFM69_RESET is new STM32GD.GPIO (Pin => 2, Port => GPIOA_Periph, Output => True); package IRQ is new STM32GD.GPIO (Pin => 3, Port => GPIOA_Periph); package SCL is new STM32GD.GPIO (Pin => 6, Port => GPIOB_Periph, Alternate => True, Alternate_Function => 1); package SCL_OUT is new STM32GD.GPIO (Pin => 6, Port => GPIOB_Periph, Output => True); package SDA is new STM32GD.GPIO (Pin => 7, Port => GPIOB_Periph, Alternate => True, Alternate_Function => 1); package SPI is new STM32GD.SPI (SPI => SPI1_Periph); package I2C is new STM32GD.I2C ( I2C => I2C1_Periph); package USART is new STM32GD.USART (USART => USART1_Periph, Speed => 115200, Clock_Tree => CLOCKS, Clock => STM32GD.Clock.PCLK1); package RTC is new STM32GD.RTC (Clock_Tree => STM32GD.Board.Clocks, Clock => STM32GD.Clock.LSI); package Radio is new Drivers.RFM69 (SPI => SPI, Chip_Select => CSN, IRQ => IRQ, Frequency => 868_000_000); package Text_IO is new Drivers.Text_IO (USART => STM32GD.Board.USART); procedure Init; procedure Enable_Peripherals; procedure Disable_Peripherals; procedure Stop; end STM32GD.Board;
charlie5/aIDE
Ada
336
ads
with Ada.Containers.Vectors; package AdaM.program_Unit is type Item is interface; -- View -- type View is access all Item'Class; -- Vector -- package Vectors is new ada.Containers.Vectors (Positive, View); subtype Vector is Vectors.Vector; private procedure dummy; end AdaM.program_Unit;
wookey-project/ewok-legacy
Ada
42
ads
../../stm32f439/Ada/soc-dwt-interfaces.ads
PThierry/ewok-kernel
Ada
963
ads
-- -- Copyright 2018 The wookey project team <[email protected]> -- - Ryad Benadjila -- - Arnauld Michelizza -- - Mathieu Renard -- - Philippe Thierry -- - Philippe Trebuchet -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- package ewok.exported.ticks with spark_mode => off is type t_precision is (PRECISION_MILLI_SEC, PRECISION_MICRO_SEC, PRECISION_CYCLE); end ewok.exported.ticks;
damaki/libkeccak
Ada
4,380
ads
------------------------------------------------------------------------------- -- 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 Keccak.Generic_Parallel_Sponge; with Keccak.Padding; pragma Elaborate_All (Keccak.Generic_Parallel_Sponge); package Keccak.Parallel_Keccak_1600.Rounds_14 with SPARK_Mode => On is procedure Permute_All_P2 is new KeccakF_1600_P2.Permute_All (First_Round => 10, Num_Rounds => 14); procedure Permute_All_P4 is new KeccakF_1600_P4.Permute_All (Permute_All_P2); procedure Permute_All_P8 is new KeccakF_1600_P8.Permute_All (Permute_All_P2); package Parallel_Sponge_P2 is new Keccak.Generic_Parallel_Sponge (State_Size => 1600, State_Type => KeccakF_1600_P2.Parallel_State, Parallelism => 2, Init => KeccakF_1600_P2.Init, Permute_All => Permute_All_P2, XOR_Bits_Into_State_Separate => KeccakF_1600_P2.XOR_Bits_Into_State_Separate, XOR_Bits_Into_State_All => KeccakF_1600_P2.XOR_Bits_Into_State_All, Extract_Bytes => KeccakF_1600_P2.Extract_Bytes, Pad => Keccak.Padding.Pad101_Single_Block, Min_Padding_Bits => Keccak.Padding.Pad101_Min_Bits); package Parallel_Sponge_P4 is new Keccak.Generic_Parallel_Sponge (State_Size => 1600, State_Type => KeccakF_1600_P4.Parallel_State, Parallelism => 4, Init => KeccakF_1600_P4.Init, Permute_All => Permute_All_P4, XOR_Bits_Into_State_Separate => KeccakF_1600_P4.XOR_Bits_Into_State_Separate, XOR_Bits_Into_State_All => KeccakF_1600_P4.XOR_Bits_Into_State_All, Extract_Bytes => KeccakF_1600_P4.Extract_Bytes, Pad => Keccak.Padding.Pad101_Single_Block, Min_Padding_Bits => Keccak.Padding.Pad101_Min_Bits); package Parallel_Sponge_P8 is new Keccak.Generic_Parallel_Sponge (State_Size => 1600, State_Type => KeccakF_1600_P8.Parallel_State, Parallelism => 8, Init => KeccakF_1600_P8.Init, Permute_All => Permute_All_P8, XOR_Bits_Into_State_Separate => KeccakF_1600_P8.XOR_Bits_Into_State_Separate, XOR_Bits_Into_State_All => KeccakF_1600_P8.XOR_Bits_Into_State_All, Extract_Bytes => KeccakF_1600_P8.Extract_Bytes, Pad => Keccak.Padding.Pad101_Single_Block, Min_Padding_Bits => Keccak.Padding.Pad101_Min_Bits); end Keccak.Parallel_Keccak_1600.Rounds_14;
seL4/isabelle
Ada
238
ads
with Complex_Types; --# inherit Complex_Types; package Complex_Types_App is procedure Initialize (A : in out Complex_Types.Array_Type2); --# derives A from A; --# post Complex_Types.Initialized (A, 10); end Complex_Types_App;
iyan22/AprendeAda
Ada
971
adb
with ada.text_io, ada.integer_text_io; use ada.text_io, ada.integer_text_io; with numtriangular; procedure prueba_numtriangular is n1, resultado:integer:=0; begin -- caso de prueba 1: n1:=4; put("El resultado deberia de ser: 10"); new_line; put("Y tu programa dice que:"); numtriangular(n1, resultado); put(resultado); new_line; -- caso de prueba 2: n1:=10; put("El resultado deberia de ser: 55"); new_line; put("Y tu programa dice que:"); numtriangular(n1, resultado); put(resultado); new_line; -- caso de prueba 3: n1:=1; put("El resultado deberia de ser: 1"); new_line; put("Y tu programa dice que:"); numtriangular(n1, resultado); put(resultado); new_line; -- caso de prueba 4: n1:=7; put("El resultado deberia de ser: 28"); new_line; put("Y tu programa dice que:"); numtriangular(n1, resultado); put(resultado); new_line; end prueba_numtriangular;
albinjal/Ada_Project
Ada
22,833
adb
with TJa.Sockets; use TJa.Sockets; with Ada.Exceptions; use Ada.Exceptions; with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Yatzy_graphics_package; use Yatzy_graphics_package; with TJa.Window.Text; use TJa.Window.Text; with TJa.Window.Elementary; use TJa.Window.Elementary; with TJa.Window.Graphic; use TJa.Window.Graphic; with TJa.Keyboard; use TJa.Keyboard; package body Klient_Assets_Package is -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- procedure Fill_Protocoll_Empty(Proto: in out Protocoll_Type) is begin Proto(1) := 12; Proto(2) := -1; Proto(3) := -1; Proto(4) := -1; Proto(5) := -1; Proto(6) := -1; Proto(7) := -1; Proto(8) := -1; Proto(9) := -1; Proto(10) := -1; Proto(11) := -1; Proto(12) := -1; Proto(13) := -1; Proto(14) := -1; Proto(15) := -1; end Fill_Protocoll_Empty; -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- procedure Bootup(Socket: out Socket_Type; Adress: in String; Port: in Positive) is begin Initiate(Socket); Connect(Socket, Adress, Port); Put("Ansluten till servern"); New_Line; end Bootup; -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- procedure graphics is begin Clear_Window; Set_Graphical_Mode(On); background; protocoll_background(125, 4); logo_background(24, 4); logo(24, 4); end graphics; -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- procedure Start_Game(Socket: in Socket_Type; Player: out Positive; Prot1, Prot2: out Protocoll_Type) is TX : String(1..100); TL : Natural; begin -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- for I in 1..15 loop Prot1(I) := -1; end loop; Prot2 := Prot1; Get_Line(Socket, TX, TL); if TX(1) = '1' then message(33, 18, "Du är spelare 1, väntar på spelare 2"); Player := 1; Get_Line(Socket, TX, TL); New_Line; if TX(1) = '3' then message(33, 18, "Båda spelare anslutna"); end if; elsif TX(1) = '2' then message(33, 18, "Du är spelare 2"); Player := 2; else raise DATATYPE_ERROR; end if; New_Line; message(33, 18, "Nu startar spelet"); New_Line; end Start_Game; -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- function Read(C: in Character) return Natural is S: String(1..1); begin S(1) := C; return Integer'Value(S); end Read; -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- procedure Get_Rolls(Socket: in Socket_Type; Roll: out Rolls_Type) is TX: String(1..100); TL: Natural; begin Get_Line(Socket, TX, TL); New_Line; if TX(1) = '4' then -- 4 betyder inkomande tärningar Roll.I := Read(TX(2)); for X in 1..Roll.I loop -- A betyder här antalet tärningar Roll.Rolls(X) := Read(TX(X+2)); end loop; elsif TX(1) = '5' then -- 5 betyder info om gamestate if TX(2) = '0' then -- Annan spelare slår Roll.I := 6; elsif TX(2) = '1' then -- Annan spelare har slagit Roll.I := 7; for X in 1..5 loop Roll.Rolls(X) := Read(TX(X+2)); end loop; elsif TX(2) = '2' then -- Annan spelare vill placera Roll.I := 8; for X in 1..5 loop Roll.Rolls(X) := Read(TX(X+2)); end loop; end if; else raise DATATYPE_ERROR; end if; end Get_Rolls; -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- function GetI(Roll: in Rolls_Type) return Integer is begin return Roll.I; end GetI; -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- function GetR(Roll: in Rolls_Type) return Arr is begin return Roll.Rolls; end GetR; -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- procedure Playerroll(Socket: in Socket_Type) is begin Put_Line(Socket, "51"); end Playerroll; -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- procedure Sort(Arrayen_Med_Talen: in out Arr) is -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- procedure Swap(Tal_1,Tal_2: in out Integer) is Tal_B : Integer; -- Temporary buffer begin Tal_B := Tal_1; Tal_1 := Tal_2; Tal_2 := Tal_B; end Swap; -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Minsta_Talet, Minsta_Talet_Index : Integer; begin Minsta_Talet := 0; for IOuter in Arrayen_Med_Talen'Range loop for I in IOuter..Arrayen_Med_Talen'Last loop if I = IOuter or Arrayen_Med_Talen(I) > Minsta_Talet then Minsta_Talet := Arrayen_Med_Talen(I); Minsta_Talet_Index := I; end if; end loop; Swap(Arrayen_Med_Talen(IOuter), Arrayen_Med_Talen(Minsta_Talet_Index)); end loop; end Sort; -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- function Calcpoints(Prot: Protocoll_Type; Rolls: Arr) -- -- -- return Protocoll_Type is -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- function Ental(I: Integer; Rolls: Arr) -- -- -- return Integer is -- -- -- -- -- -- C : Integer := 0; -- -- -- begin -- -- -- for X in 1..5 loop -- -- -- if Rolls(X) = I then -- -- -- C := C + I; -- -- -- end if; -- -- -- end loop; -- -- -- return C; -- -- -- end Ental; -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- function FourPair(Rolls: Arr) -- -- -- return Integer is -- -- -- -- -- -- begin -- -- -- for I in 1..2 loop -- -- -- if Rolls(I) = Rolls(I+1) and Rolls(I) = Rolls(I+2) and Rolls(I) = Rolls(I+3) then -- -- -- return 4 * Rolls(I); -- -- -- end if; -- -- -- end loop; -- -- -- -- -- -- return 0; -- -- -- end FourPair; -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- function Pair(Rolls: Arr) -- -- -- return Integer is -- -- -- begin -- -- -- for I in 1..4 loop if Rolls(I) = Rolls(I+1) then return 2 * Rolls(I); end if; end loop; return 0; end; -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- function TwoPair(Rolls: Arr) return Integer is begin if FourPair(Rolls) /= 0 then return 0; end if; for I in 1..2 loop if Rolls(I) = Rolls(I+1) then for X in (I+2)..4 loop if Rolls(X) = Rolls(X+1) then return 2 * ( Rolls(I) + Rolls(X) ); end if; end loop; return 0; end if; end loop; return 0; end; -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- function Triss(Rolls: Arr) return Integer is begin for I in 1..3 loop if Rolls(I) = Rolls(I+1) and Rolls(I) = Rolls(I+2) then return 3 * Rolls(I); end if; end loop; return 0; end; -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- function Stege(I: Integer; Rolls: Arr) return Integer is begin case I is when 11 => --Liten for X in 1..5 loop if Rolls(6-X) /= X then return 0; end if; end loop; return 15; when 12 => --Stor for X in 2..6 loop if Rolls(7-X) /= X then return 0; end if; end loop; return 20; when others => null; return 0; end case; end; -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- function Chans(Rolls: Arr) return Integer is X : Integer := 0; begin for I in 1..5 loop X := X + Rolls(I); end loop; return X; end; -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- function Kaok(Rolls: Arr) return Integer is begin for X in 1..2 loop exit when Rolls(X) /= Rolls(X+1); if X = 2 then if Rolls(4) = Rolls(5) and Rolls(5) /= Rolls(1) then return Chans(Rolls); else return 0; end if; end if; end loop; if Rolls(1) = Rolls(2) then if Rolls(3) = Rolls(4) and Rolls(3) = Rolls(5) then return Chans(Rolls); end if; end if; return 0; end; -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- function Yatzy(Rolls: Arr) return Integer is begin for X in 1..4 loop if Rolls(X) /= Rolls(X+1) then return 0; end if; end loop; return 50; end; -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- TRolls: Arr := Rolls; Result: Protocoll_Type; begin Sort(TRolls); for I in 1..15 loop if Prot(I) /= -1 then Result(I) := -1; else case I is when 1..6 => Result(I) := Ental(I, TRolls); when 7 => Result(I) := Pair(TRolls); when 8 => Result(I) := TwoPair(TRolls); when 9 => Result(I) := Triss(Trolls); when 10 => Result(I) := FourPair(Trolls); when 11..12 => Result(I) := Stege(I, Trolls); when 13 => Result(I) := Kaok(Trolls); when 14 => Result(I) := Chans(Trolls); when 15 => Result(I) := Yatzy(Trolls); when others => Result(I) := 0; end case; end if; end loop; return Result; end; -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- function Roll_loop(Socket: Socket_Type; Player: Positive) return Rolls_Type is type Rerolls is array(1..5) of Integer; B: Integer; Continue, Switches: Integer; Reroll: Rerolls; Result : Arr; Roll: Rolls_Type; Key : Key_Type; temp_resp_int: Integer; --C0 : Character := 0; --C1 : Character := 1; begin -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Get_Rolls(Socket, Roll); -- Slår Jag? if GetI(Roll) > 5 then -- Jag slår inte - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - loop if GetI(Roll) = 6 then message(33, 18, "Spelare " & Integer'Image(3-Player) & " slår"); elsif GetI(Roll) = 7 then message(33, 18, "Spelare " & Integer'Image(3-Player) & " har slagit:"); Result := GetR(Roll); dice_placement(Roll.Rolls(1), Roll.Rolls(2), Roll.Rolls(3), Roll.Rolls(4), Roll.Rolls(5)); end if; Get_Rolls(Socket, Roll); exit when Roll.I = 8; end loop; else -- Jag slår - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - for I in 1..5 loop Reroll(I) := 0; end loop; message(33, 18, "Din tur"); for I in 1..3 loop -- Man kan slå max 3 gånger totalt per omgång Result := GetR(Roll); message(33, 18, "Tryck enter för att slå..."); -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Set_Buffer_Mode(Off); Set_Echo_Mode(Off); loop -- Infinite loop waiting for return key Get_Immediate(Key); if Is_Return(Key) then exit; end if; end loop; Set_Echo_Mode(On); Set_Buffer_Mode(On); -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- message(33, 18, "Wow, du fick:"); dice_placement(Roll.Rolls(1), Roll.Rolls(2), Roll.Rolls(3), Roll.Rolls(4), Roll.Rolls(5)); -- If third time, exit loop and do not allow user to roll again exit when I = 3; message(33, 18, "Tryck 1 för att slå igen och 0 för att placera: "); -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Set_Buffer_Mode(Off); Set_Echo_Mode(Off); loop -- Infinite loop waiting for either 1 or 0 Get_Immediate(Key); if To_String(Key) = "0" then temp_resp_int := 0; exit; elsif To_String(Key) = "1" then temp_resp_int := 1; exit; end if; end loop; Set_Echo_Mode(On); Set_Buffer_Mode(On); -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- if temp_resp_int = 0 then exit; -- exit loop, move to placement elsif temp_resp_int = 1 then message(33, 18, "Välj hur många tätningar du vill slå om: "); Get(Switches); for A in 1..Switches loop message(33, 18, "Välj en tärning att slå om: "); Get(B); Reroll(B) := 1; end loop; Put(Socket,'6'); Put(Socket,Switches,0); for A in 1..5 loop Put(Socket,Reroll(A),0); end loop; New_Line(Socket); Get_Rolls(Socket, Roll); end if; end loop; Put_Line(Socket, "7"); end if; return Roll; end Roll_loop; -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- procedure Watch_Placement(Socket: Socket_Type; Dices: Rolls_Type; Protocoll: Protocoll_Type) is begin message(33, 18, "Annan spelare ska placera"); Skip_Line; end Watch_Placement; -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- procedure Place(Socket: Socket_Type; Dices: Rolls_Type; Protocoll: Protocoll_Type) is selected_index: Integer; begin message(33, 18, "Du ska placera"); New_Line; New_Line; Put("-FFS " & Integer'Image(GetR(Dices)(1)) & "+" & Integer'Image(GetR(Dices)(2)) & "+" & Integer'Image(GetR(Dices)(3)) & "+" & Integer'Image(GetR(Dices)(4)) & "+" & Integer'Image(GetR(Dices)(5)) & " FFS-"); place_graphics( Calcpoints(Protocoll, GetR(Dices)), selected_index ); end Place; ----------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------- end Klient_Assets_Package;
jwarwick/aoc_2019_ada
Ada
4,231
adb
with Ada.Text_IO; use Ada.Text_IO; with AUnit.Assertions; use AUnit.Assertions; with Ada.Containers; use type Ada.Containers.Count_Type; package body IntCode.Test is type Memory_Array is array(Integer range <>) of Integer; function to_memory(a : Memory_Array) return Memory_Vector.Vector is m : Memory_Vector.Vector; begin for val of a loop m.append(val); end loop; return m; end to_memory; procedure Test_Load (T : in out AUnit.Test_Cases.Test_Case'Class) is pragma Unreferenced (T); begin Assert(memory.length = 0, "Vector before load should be size 0, got: " & Ada.Containers.Count_Type'Image(memory.length)); load("99"); Assert(memory.length = 1, "Vector after load should be size 1, got: " & Ada.Containers.Count_Type'Image(memory.length)); Assert(memory(0) = 99, "First element of vector should be 99, got: " & Integer'Image(memory(0))); load("16,42,0,-1"); Assert(memory.length = 4, "Vector after load should be size 4, got: " & Ada.Containers.Count_Type'Image(memory.length)); Assert(memory(0) = 16, "First element of vector should be 16, got: " & Integer'Image(memory(0))); Assert(memory(1) = 42, "First element of vector should be 16, got: " & Integer'Image(memory(1))); Assert(memory(2) = 0, "First element of vector should be 16, got: " & Integer'Image(memory(2))); Assert(memory(3) = -1, "First element of vector should be 16, got: " & Integer'Image(memory(3))); end Test_Load; procedure Test_Poke (T : in out AUnit.Test_Cases.Test_Case'Class) is pragma Unreferenced (T); begin load("16,42,0,-1"); Assert(memory.length = 4, "Vector after load should be size 4, got: " & Ada.Containers.Count_Type'Image(memory.length)); Assert(memory(0) = 16, "First element of vector should be 16, got: " & Integer'Image(memory(0))); Assert(memory(1) = 42, "First element of vector should be 16, got: " & Integer'Image(memory(1))); Assert(memory(2) = 0, "First element of vector should be 16, got: " & Integer'Image(memory(2))); Assert(memory(3) = -1, "First element of vector should be 16, got: " & Integer'Image(memory(3))); poke(0, -5); Assert(memory(0) = -5, "Poked element of vector should be -5, got: " & Integer'Image(memory(0))); -- XXX - test exception -- poke(10, 11); Assert(peek(3) = -1, "Peeking element of vector should be -1, got: " & Integer'Image(memory(3))); end Test_Poke; procedure Test_Eval (T : in out AUnit.Test_Cases.Test_Case'Class) is pragma Unreferenced (T); procedure eval_test(input : in Memory_Array; expected : in Memory_Array; desc : in String) is use type Memory_Vector.Vector; m : Memory_Vector.Vector := to_memory(input); e : Memory_Vector.Vector := to_memory(expected); begin memory := m; eval; Assert(memory = e, desc & ", got: " & dump); end eval_test; begin eval_test((1, 0, 0, 0, 99), (2, 0, 0, 0, 99), "Simple add test"); eval_test((2,3,0,3,99), (2,3,0,6,99), "Simple mult test"); eval_test((2,4,4,5,99,0), (2,4,4,5,99,9801), "Bigger mult test"); eval_test((1,1,1,4,99,5,6,0,99), (30,1,1,4,2,5,6,0,99), "Multiple write test"); end Test_Eval; procedure Test_Input (T : in out AUnit.Test_Cases.Test_Case'Class) is pragma Unreferenced (T); m : Memory_Vector.Vector := to_memory((3,0,4,0,99)); val : constant Integer := 17; out_val : Integer; begin memory := m; append_input(val); eval; out_val := take_output; Assert(out_val = val, "Expected: " & Integer'IMAGE(val) & ", got: " & Integer'IMAGE(out_val)); end Test_Input; function Name (T : Test) return AUnit.Message_String is pragma Unreferenced (T); begin return AUnit.Format ("IntCode Package"); end Name; procedure Register_Tests (T : in out Test) is use AUnit.Test_Cases.Registration; begin Register_Routine (T, Test_Load'Access, "Loading"); Register_Routine (T, Test_Poke'Access, "Peek/Poke"); Register_Routine (T, Test_Eval'Access, "Evaluation"); Register_Routine (T, Test_Input'Access, "Input"); end Register_Tests; end IntCode.Test;
mirror/ncurses
Ada
3,083
ads
------------------------------------------------------------------------------ -- -- -- GNAT ncurses Binding Samples -- -- -- -- ncurses -- -- -- -- B O D Y -- -- -- ------------------------------------------------------------------------------ -- Copyright 2020 Thomas E. Dickey -- -- Copyright 2000 Free Software Foundation, Inc. -- -- -- -- 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, distribute with modifications, 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 ABOVE 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. -- -- -- -- Except as contained in this notice, the name(s) of the above copyright -- -- holders shall not be used in advertising or otherwise to promote the -- -- sale, use or other dealings in this Software without prior written -- -- authorization. -- ------------------------------------------------------------------------------ -- Author: Eugene V. Melaragno <[email protected]> 2000 -- Version Control -- $Revision: 1.2 $ -- Binding Version 01.00 ------------------------------------------------------------------------------ procedure ncurses2.acs_display;
tum-ei-rcs/StratoX
Ada
1,105
ads
package Mission with SPARK_Mode is -- the mission can only go forward type Mission_State_Type is ( UNKNOWN, INITIALIZING, WAITING_FOR_GPS, STARTING, WAITING_FOR_ASCEND, ASCENDING, DETACHING, DESCENDING, WAITING_ON_GROUND, WAITING_FOR_RESET ); type Mission_Event_Type is ( NONE, INITIALIZED, SELF_TEST_OK, ARMED, RELEASED, BALLOON_DETACHED, LANDED, FOUND, EVALUATED ); procedure start_New_Mission; procedure load_Mission; procedure run_Mission; function Is_Resumed return Boolean; function get_state return Mission_State_Type; private procedure perform_Initialization; procedure wait_for_GPSfix; procedure perform_Start; -- screws with timing procedure wait_For_Ascend; procedure monitor_Ascend with Pre => True; -- workaround got GNATprove bug P811-036 procedure perform_Detach; -- screws with timing procedure control_Descend; procedure wait_On_Ground; procedure wait_For_Reset; end Mission;
AdaCore/training_material
Ada
6,058
adb
with Ada.Real_Time; use Ada.Real_Time; with STM32F4; use STM32F4; with STM32F4.GPIO; use STM32F4.GPIO; with STM32F4.RCC; use STM32F4.RCC; with STM32F429_Discovery; use STM32F429_Discovery; package body STM32F4.SDRAM is -------------------- -- Configure_GPIO -- -------------------- procedure Configure_GPIO is Conf : GPIO_Port_Configuration; begin Enable_Clock (GPIO_B); Enable_Clock (GPIO_C); Enable_Clock (GPIO_D); Enable_Clock (GPIO_E); Enable_Clock (GPIO_F); Enable_Clock (GPIO_G); Conf.Speed := Speed_50MHz; Conf.Mode := Mode_AF; Conf.Output_Type := Push_Pull; Conf.Resistors := Floating; Conf.Locked := True; Configure_Alternate_Function (GPIO_B, (Pin_5, Pin_6), GPIO_AF_FMC); Configure_IO (GPIO_B, (Pin_5, Pin_6), Conf); Configure_Alternate_Function (GPIO_C, Pin_0, GPIO_AF_FMC); Configure_IO (GPIO_C, Pin_0, Conf); Configure_Alternate_Function (GPIO_D, (Pin_0, Pin_1, Pin_8, Pin_9, Pin_10, Pin_14, Pin_15), GPIO_AF_FMC); Configure_IO (GPIO_D, (Pin_0, Pin_1, Pin_8, Pin_9, Pin_10, Pin_14, Pin_15), Conf); Configure_Alternate_Function (GPIO_E, (Pin_0, Pin_1, Pin_7, Pin_8, Pin_9, Pin_10, Pin_11, Pin_12, Pin_13, Pin_14, Pin_15), GPIO_AF_FMC); Configure_IO (GPIO_E, (Pin_0, Pin_1, Pin_7, Pin_8, Pin_9, Pin_10, Pin_11, Pin_12, Pin_13, Pin_14, Pin_15), Conf); Configure_Alternate_Function (GPIO_F, (Pin_0, Pin_1, Pin_2, Pin_3, Pin_4, Pin_5, Pin_11, Pin_12, Pin_13, Pin_14, Pin_15), GPIO_AF_FMC); Configure_IO (GPIO_F, (Pin_0, Pin_1, Pin_2, Pin_3, Pin_4, Pin_5, Pin_11, Pin_12, Pin_13, Pin_14, Pin_15), Conf); Configure_Alternate_Function (GPIO_G, (Pin_0, Pin_1, Pin_4, Pin_5, Pin_8, Pin_15), GPIO_AF_FMC); Configure_IO (GPIO_G, (Pin_0, Pin_1, Pin_4, Pin_5, Pin_8, Pin_15), Conf); end Configure_GPIO; -------------------- -- Relative_Delay -- -------------------- procedure Relative_Delay (Ms : Integer) is Next_Start : Time := Clock; Period : constant Time_Span := Milliseconds (Ms); begin Next_Start := Next_Start + Period; delay until Next_Start; end Relative_Delay; ------------------------ -- SDRAM_InitSequence -- ------------------------ procedure SDRAM_InitSequence is Cmd : FMC_SDRAM_Cmd_Conf; begin Cmd.CommandMode := FMC_Command_Mode_CLK_Enabled; Cmd.CommandTarget := FMC_Command_Target_bank2; Cmd.AutoRefreshNumber := 1; Cmd.ModeRegisterDefinition := 0; loop exit when not FMC_Get_Flag (FMC_Bank2_SDRAM, FMC_FLAG_Busy); end loop; FMC_SDRAM_Cmd (Cmd); Relative_Delay (100); Cmd.CommandMode := FMC_Command_Mode_PALL; Cmd.CommandTarget := FMC_Command_Target_bank2; Cmd.AutoRefreshNumber := 1; Cmd.ModeRegisterDefinition := 0; loop exit when not FMC_Get_Flag (FMC_Bank2_SDRAM, FMC_FLAG_Busy); end loop; FMC_SDRAM_Cmd (Cmd); Cmd.CommandMode := FMC_Command_Mode_AutoRefresh; Cmd.CommandTarget := FMC_Command_Target_bank2; Cmd.AutoRefreshNumber := 4; Cmd.ModeRegisterDefinition := 0; loop exit when not FMC_Get_Flag (FMC_Bank2_SDRAM, FMC_FLAG_Busy); end loop; FMC_SDRAM_Cmd (Cmd); loop exit when not FMC_Get_Flag (FMC_Bank2_SDRAM, FMC_FLAG_Busy); end loop; FMC_SDRAM_Cmd (Cmd); Cmd.CommandMode := FMC_Command_Mode_LoadMode; Cmd.CommandTarget := FMC_Command_Target_bank2; Cmd.AutoRefreshNumber := 1; Cmd.ModeRegisterDefinition := SDRAM_MODEREG_BURST_LENGTH_2 or SDRAM_MODEREG_BURST_TYPE_SEQUENTIAL or SDRAM_MODEREG_CAS_LATENCY_3 or SDRAM_MODEREG_OPERATING_MODE_STANDARD or SDRAM_MODEREG_WRITEBURST_MODE_SINGLE; loop exit when not FMC_Get_Flag (FMC_Bank2_SDRAM, FMC_FLAG_Busy); end loop; FMC_SDRAM_Cmd (Cmd); FMC_Set_Refresh_Count (1386); loop exit when not FMC_Get_Flag (FMC_Bank2_SDRAM, FMC_FLAG_Busy); end loop; end SDRAM_InitSequence; ---------------- -- Initialize -- ---------------- procedure Initialize is Timing_Conf : FMC_SDRAM_TimingInit_Config; SDRAM_Conf : FMC_SDRAM_Init_Config; begin Configure_GPIO; FSMC_Clock_Enable; Timing_Conf.LoadToActiveDelay := 2; Timing_Conf.ExitSelfRefreshDelay := 7; Timing_Conf.SelfRefreshTime := 4; Timing_Conf.RowCycleDelay := 7; Timing_Conf.WriteRecoveryTime := 2; Timing_Conf.RPDelay := 2; Timing_Conf.RCDDelay := 2; SDRAM_Conf.Bank := FMC_Bank2_SDRAM; SDRAM_Conf.ColumnBitsNumber := FMC_ColumnBits_Number_8b; SDRAM_Conf.RowBitsNumber := FMC_RowBits_Number_12b; SDRAM_Conf.SDMemoryDataWidth := SDRAM_MEMORY_WIDTH; SDRAM_Conf.InternalBankNumber := FMC_InternalBank_Number_4; SDRAM_Conf.CASLatency := SDRAM_CAS_LATENCY; SDRAM_Conf.WriteProtection := FMC_Write_Protection_Disable; SDRAM_Conf.SDClockPeriod := SDCLOCK_PERIOD; SDRAM_Conf.ReadBurst := SDRAM_READBURST; SDRAM_Conf.ReadPipeDelay := FMC_ReadPipe_Delay_1; SDRAM_Conf.Timing_Conf := Timing_Conf; FMC_SDRAM_Init (SDRAM_Conf); SDRAM_InitSequence; end Initialize; end STM32F4.SDRAM;
BrickBot/Bound-T-H8-300
Ada
12,102
adb
-- Symbols.Text (body) -- -- Author: Niklas Holsti, Tidorum Ltd -- -- A component of the Bound-T Worst-Case Execution Time Tool. -- ------------------------------------------------------------------------------- -- Copyright (c) 1999 .. 2015 Tidorum Ltd -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- 1. Redistributions of source code must retain the above copyright notice, this -- list of conditions and the following disclaimer. -- 2. Redistributions in binary form 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. -- -- This software is provided by the copyright holders and contributors "as is" and -- any express or implied warranties, including, but not limited to, the implied -- warranties of merchantability and fitness for a particular purpose are -- disclaimed. In no event shall the copyright owner or contributors be liable for -- any direct, indirect, incidental, special, exemplary, or consequential damages -- (including, but not limited to, procurement of substitute goods or services; -- loss of use, data, or profits; or business interruption) however caused and -- on any theory of liability, whether in contract, strict liability, or tort -- (including negligence or otherwise) arising in any way out of the use of this -- software, even if advised of the possibility of such damage. -- -- Other modules (files) of this software composition should contain their -- own copyright statements, which may have different copyright and usage -- conditions. The above conditions apply to this file. ------------------------------------------------------------------------------- -- -- $Revision: 1.3 $ -- $Date: 2015/10/24 20:05:52 $ -- -- $Log: symbols-text.adb,v $ -- Revision 1.3 2015/10/24 20:05:52 niklas -- Moved to free licence. -- -- Revision 1.2 2011-08-31 04:23:34 niklas -- BT-CH-0222: Option registry. Option -dump. External help files. -- -- Revision 1.1 2008/10/11 08:16:14 niklas -- BT-CH-0148: Symbols from text files and the -symbols option. -- with Ada.Characters.Latin_1; with Ada.Strings; with Ada.Strings.Fixed; with Ada.Strings.Maps; with Ada.Text_IO; with Output; with Processor.Properties; with Options.String_Sets; with Symbols.Opt; package body Symbols.Text is -- File syntax: -- -- The syntax of the symbols file is the following: -- -- > Any line beginning with "--" is a comment and is ignored. -- Blanks may precede the "--". -- -- > Any blank or empty line is ignored. -- -- > Any other line should contain a symbol definition. -- -- A symbol definition contains three strings, without embedded -- blanks and separated by one or more blanks, as follows: -- -- > The first string is either they keyword "subprogram" -- or the keyword "variable". -- -- > The second string is the identifier, possibly qualified -- by a scope, using the default scope delimiter. -- -- > The third string is the numerical or mnemonic faddress of the symbol. -- For a subprogram symbol, the form is defined by the function -- Processor.Properties.Subprogram_Address. -- For a variable (cell) symbol, the form is defined by the -- function Processsor.Properties.Variable_Cell. -- -- The strings should *not* be quoted. -- -- Leading and trailing blanks are ignored. -- Tab characters are equivalent to blanks. -- -- Example: -- -- This is a comment. -- subprogram rom|init_mem 16#1234# -- subprogram rom|boot|startup 0 -- variable count mw032a procedure Define ( Kind : in String; Identifier : in String; Address : in String; Table : in Symbol_Table_T; Valid : in out Boolean) -- -- Defines the Identifier at Address in the Table as a subprogram -- or a variable, depending on the Kind. -- Sets Valid to False if some error is detected. -- is Cell : Storage.Cell_T; -- The cell defined by this Address, when Kind = "variable". begin if Kind = "subprogram" then Connect_Subprogram ( Scope => Scope_Of (Identifier), Name => Name_Of (Identifier), Address => Processor.Properties.Subprogram_Address (Address), Within => Table); elsif Kind = "variable" then Cell := Processor.Properties.Variable_Cell (Address); Connect_Variable ( Scope => Scope_Of (Identifier), Name => Name_Of (Identifier), Location => Storage.Spec_Of (Cell), Within => Table); else Output.Error ( "Unknown symbol kind """ & Kind & """ for the symbol """ & Identifier & """ at """ & Address & """."); Valid := False; end if; exception when Constraint_Error | Processor.Properties.Address_Error => -- Probably the Address is wrong in some way. Output.Error ( "Could not define the " & Kind & " """ & Identifier & """ at """ & Address & """."); Valid := False; end Define; Tab_To_Blank : constant Ada.Strings.Maps.Character_Mapping := Ada.Strings.Maps.To_Mapping ( From => (1 => Ada.Characters.Latin_1.HT), To => (1 => ' ')); -- -- Translates tabs (HT) to blanks. White_Space : constant Ada.Strings.Maps.Character_Set := Ada.Strings.Maps.To_Set ( String'((' ', Ada.Characters.Latin_1.HT))); -- -- The white-space characters that separate tokens on the -- input lines. (It is not necessary to include HT, if the -- Tab_To_Blank translation is applied first.) type Slice_T is record First : Positive; Last : Natural; end record; -- -- The first and last indices of a slice of a string. -- The slice is "null" if Last < First. function Is_Null (Item : Slice_T) return Boolean is begin return Item.Last < Item.First; end Is_Null; function Length (Item : Slice_T) return Integer is begin return Item.Last - Item.First + 1; end Length; function Next_Token (Within : String; From : Positive) return Slice_T -- -- The slice of Within(From..) that contains the first -- blank-separated blank-free substring. However, if From is -- not in Within'Range, a null slice is returned. -- is use Ada.Strings; use Ada.Strings.Fixed; Slice : Slice_T; -- The result. begin if From in Within'Range then Find_Token ( Source => Within(From .. Within'Last), Set => White_Space, Test => Outside, First => Slice.First, Last => Slice.Last); else Slice := (First => Within'First, Last => 0); end if; return Slice; end Next_Token; procedure Parse_And_Define ( Line : in String; Table : in Symbol_Table_T; Valid : in out Boolean) -- -- Parses the input Line (which has been stripped of leading -- and trailing blanks) and defines the symbol -- if any -- in -- the Table. Sets Valid to False if any error is detected. -- is use Ada.Strings; use Ada.Strings.Fixed; Keyword, Identifier, Address : Slice_T; -- The parts of the line that contain the keyword, the -- identifier, and the address, respectively. begin Keyword := Next_Token (Within => Line, From => Line'First); if Is_Null (Keyword) or else ( Length (Keyword) >= 2 and then Line(Keyword.First .. Keyword.First + 1) = "--") then -- A blank or empty line or a comment line. null; else -- The Line consists of a keyword, an identifier, and the -- address value, separated by blanks. Identifier := Next_Token (Within => Line, From => Keyword.Last + 1); Address := Next_Token (Within => Line, From => Identifier.Last + 1); if Is_Null (Identifier) or Is_Null (Address) or Address.Last /= Line'Last then Output.Error ( "Syntax error in symbol-file line" & Output.Field_Separator & Line); Valid := False; else Define ( Kind => Line(Keyword.First .. Keyword.Last), Identifier => Line(Identifier.First .. Identifier.Last), Address => Line(Address.First .. Address.Last), Table => Table, Valid => Valid); end if; end if; end Parse_And_Define; procedure Read ( File_Name : in String; Symbol_Table : in Symbol_Table_T; Valid : out Boolean) is use Ada.Strings; use Ada.Strings.Fixed; use type Ada.Text_IO.Positive_Count; File : Ada.Text_IO.File_Type; -- The file named File_Name. Max_Line_Length : constant := 300; -- The maximum length of a line in the file. Line : String (1 .. Max_Line_Length); Last : Natural; -- Line(1..Last) is the current line. Number : Output.Line_Number_T; -- The number of the current Line in the File. Mark : Output.Nest_Mark_T; -- Marks the locus File:Number. begin Valid := True; -- We know nothing to the contrary as yet. Output.Note ( "Reading symbols from " & File_Name & "."); Ada.Text_IO.Open ( File => File, Name => File_Name, Mode => Ada.Text_IO.In_File); while not Ada.Text_IO.End_Of_File (File) loop Number := Output.Line_Number_T (Ada.Text_IO.Line (File)); Mark := Output.Nest (Output.Locus ( Statements => Output."+" (Output.Locus ( Source_File => File_Name, Line_Number => Number)))); Ada.Text_IO.Get_Line (File, Line, Last); if Ada.Text_IO.Col (File) = 1 then -- Good, we read all of a line. Parse_And_Define ( Line => Trim ( Translate (Line(1 .. Last), Tab_To_Blank), Both), Table => Symbol_Table, Valid => Valid); else Output.Error ( "Symbol-file line is too long (over" & Natural'Image (Line'Length) & " characters)."); Valid := False; end if; Output.Unnest (Mark); end loop; Ada.Text_IO.Close (File); Output.Note ( "Finished symbols from " & File_Name & "."); exception when Ada.Text_IO.Name_Error => Output.Error ( "Could not open the symbol-file """ & File_Name & """."); if Ada.Text_IO.Is_Open (File) then Ada.Text_IO.Close (File); end if; Valid := False; end Read; procedure Read_From_Files (Symbol_Table : in Symbol_Table_T) is Files : Options.String_Sets.String_List_T := Options.String_Sets.To_List (Opt.Symbol_File_Names); -- All the symbol-file names. Valid : Boolean; -- Whether a symbol-file was good. All_Valid : Boolean := True; -- Whether all symbol-files files were good. begin for F in Files'Range loop Read ( File_Name => String_Pool.To_String (Files(F)), Symbol_Table => Symbol_Table, Valid => Valid); All_Valid := All_Valid and Valid; end loop; if not All_Valid then null; -- TBD raise Input_Error; end if; end Read_From_Files; end Symbols.Text;
Lyanf/pok
Ada
1,296
ads
-- --------------------------------------------------------------------------- -- -- -- MODULE_SCHEDULES constant and type definitions and management services -- -- -- -- --------------------------------------------------------------------------- package APEX.Module_Schedules is type Schedule_Id_Type is private; Null_Schedule_Id : constant Schedule_Id_Type; subtype Schedule_Name_Type is Name_Type; type Schedule_Status_Type is record Time_Of_Last_Schedule_Switch : System_Time_Type; Current_Schedule : Schedule_Id_Type; Next_Schedule : Schedule_Id_Type; end record; procedure Set_Module_Schedule (Schedule_Id : in Schedule_Id_Type; Return_Code : out Return_Code_Type); procedure Get_Module_Schedule_Status (Schedule_Status : out Schedule_Status_Type; Return_Code : out Return_Code_Type); procedure Get_Module_Schedule_Id (Schedule_Name : in Schedule_Name_Type; Schedule_Id : out Schedule_Id_Type; Return_Code : out Return_Code_Type); private Type Schedule_Id_Type is new APEX_Integer; Null_Schedule_Id : constant Schedule_Id_Type := 0; pragma Convention (C, Schedule_Status_Type); end APEX.Module_Schedules;
Gabriel-Degret/adalib
Ada
690
ads
-- Standard Ada library specification -- Copyright (c) 2003-2018 Maxim Reznik <[email protected]> -- Copyright (c) 2004-2016 AXE Consultants -- Copyright (c) 2004, 2005, 2006 Ada-Europe -- Copyright (c) 2000 The MITRE Corporation, Inc. -- Copyright (c) 1992, 1993, 1994, 1995 Intermetrics, Inc. -- SPDX-License-Identifier: BSD-3-Clause and LicenseRef-AdaReferenceManual --------------------------------------------------------------------------- package Ada.Assertions is pragma Pure (Assertions); Assertion_Error : exception; procedure Assert (Check : in Boolean); procedure Assert (Check : in Boolean; Message : in String); end Ada.Assertions;
twdroeger/ada-awa
Ada
5,670
adb
----------------------------------------------------------------------- -- awa-events-queues -- AWA Event Queues -- Copyright (C) 2012, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Serialize.Mappers; with AWA.Events.Queues.Fifos; with AWA.Events.Queues.Persistents; with AWA.Events.Queues.Observers; package body AWA.Events.Queues is -- ------------------------------ -- Queue the event. -- ------------------------------ procedure Enqueue (Into : in Queue_Ref; Event : in AWA.Events.Module_Event'Class) is begin if not Into.Is_Null then declare Q : constant Queue_Info_Accessor := Into.Value; begin if Q.Queue /= null then Q.Queue.Enqueue (Event); Observers.Notify (Q.Listeners, Into); end if; end; end if; end Enqueue; -- ------------------------------ -- Dequeue an event and process it with the <b>Process</b> procedure. -- ------------------------------ procedure Dequeue (From : in Queue_Ref; Process : access procedure (Event : in Module_Event'Class)) is begin if not From.Is_Null then declare Q : constant Queue_Info_Accessor := From.Value; begin if Q.Queue /= null then From.Value.Queue.Dequeue (Process); end if; end; end if; end Dequeue; -- ------------------------------ -- Add a listener that will be called each time an event is queued. -- ------------------------------ procedure Add_Listener (Into : in Queue_Ref; Listener : in Util.Listeners.Listener_Access) is begin if not Into.Is_Null then declare Q : constant Queue_Info_Accessor := Into.Value; begin Q.Listeners.Append (Listener); end; end if; end Add_Listener; -- ------------------------------ -- Returns true if the queue is available. -- ------------------------------ function Has_Queue (Queue : in Queue_Ref'Class) return Boolean is begin return not Queue.Is_Null and then Queue.Value.Queue /= null; end Has_Queue; -- ------------------------------ -- Returns the queue name. -- ------------------------------ function Get_Name (Queue : in Queue_Ref'Class) return String is begin if Queue.Is_Null then return ""; else return Queue.Value.Name; end if; end Get_Name; -- ------------------------------ -- Get the model queue reference object. -- Returns a null object if the queue is not persistent. -- ------------------------------ function Get_Queue (Queue : in Queue_Ref'Class) return AWA.Events.Models.Queue_Ref is begin if Queue.Is_Null or else Queue.Value.Queue = null then return AWA.Events.Models.Null_Queue; else return Queue.Value.Queue.Get_Queue; end if; end Get_Queue; -- ------------------------------ -- Create the event queue identified by the name <b>Name</b>. The queue factory -- identified by <b>Kind</b> is called to create the event queue instance. -- Returns a reference to the queue. -- ------------------------------ function Create_Queue (Name : in String; Kind : in String; Props : in EL.Beans.Param_Vectors.Vector; Context : in EL.Contexts.ELContext'Class) return Queue_Ref is Result : Queue_Ref; Q : constant Queue_Info_Access := new Queue_Info '(Util.Refs.Ref_Entity with Length => Name'Length, Name => Name, others => <>); begin Queue_Refs.Ref (Result) := Queue_Refs.Create (Q); if Kind = FIFO_QUEUE_TYPE then Q.Queue := Queues.Fifos.Create_Queue (Name, Props, Context); elsif Kind = PERSISTENT_QUEUE_TYPE then Q.Queue := Queues.Persistents.Create_Queue (Name, Props, Context); else raise Util.Serialize.Mappers.Field_Error with "Invalid queue type: " & Kind; end if; return Result; end Create_Queue; function Null_Queue return Queue_Ref is Result : Queue_Ref; begin return Result; end Null_Queue; -- ------------------------------ -- Finalize the referenced object. This is called before the object is freed. -- ------------------------------ overriding procedure Finalize (Object : in out Queue_Info) is procedure Free is new Ada.Unchecked_Deallocation (Object => Queue'Class, Name => Queue_Access); begin if Object.Queue /= null then Object.Queue.Finalize; Free (Object.Queue); end if; end Finalize; end AWA.Events.Queues;
reznikmm/matreshka
Ada
3,916
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Ada Modeling Framework -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2011-2012, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ -- This file is generated, don't edit it. ------------------------------------------------------------------------------ -- An output pin is a pin that holds output values produced by an action. ------------------------------------------------------------------------------ with AMF.UML.Pins; package AMF.UML.Output_Pins is pragma Preelaborate; type UML_Output_Pin is limited interface and AMF.UML.Pins.UML_Pin; type UML_Output_Pin_Access is access all UML_Output_Pin'Class; for UML_Output_Pin_Access'Storage_Size use 0; end AMF.UML.Output_Pins;
stcarrez/ada-wiki
Ada
3,947
ads
----------------------------------------------------------------------- -- wiki-helpers -- Helper operations for wiki parsers and renderer -- Copyright (C) 2016, 2020, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- 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 Wiki.Strings; package Wiki.Helpers is pragma Preelaborate; LF : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#0A#); CR : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#0D#); HT : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#09#); NBSP : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#A0#); -- Returns True if the character is a space or tab. function Is_Space (C : in Wiki.Strings.WChar) return Boolean; -- Returns True if the character is a space, tab or a newline. function Is_Space_Or_Newline (C : in Wiki.Strings.WChar) return Boolean; -- Returns True if the character is a punctuation character. function Is_Punctuation (C : in Wiki.Strings.WChar) return Boolean; -- Returns True if the character is a line terminator. function Is_Newline (C : in Wiki.Strings.WChar) return Boolean; -- Returns True if the text is a valid URL function Is_Url (Text : in Wiki.Strings.WString) return Boolean; -- Returns True if the extension part correspond to an image. -- Recognized extension are: .png, .gif, .jpg, .jpeg. -- The extension case is ignored. function Is_Image_Extension (Ext : in Wiki.Strings.WString) return Boolean; -- Given the current tag on the top of the stack and the new tag that will be pushed, -- decide whether the current tag must be closed or not. -- Returns True if the current tag must be closed. function Need_Close (Tag : in Html_Tag; Current_Tag : in Html_Tag) return Boolean; -- Get the dimension represented by the string. The string has one of the following -- formats: -- original -> Width, Height := Natural'Last -- default -> Width := 800, Height := 0 -- upright -> Width := 800, Height := 0 -- <width>px -> Width := <width>, Height := 0 -- x<height>px -> Width := 0, Height := <height> -- <width>x<height>px -> Width := <width>, Height := <height> procedure Get_Sizes (Dimension : in Wiki.Strings.WString; Width : out Natural; Height : out Natural); -- Find the position of the first non space character in the text starting at the -- given position. Returns Text'Last + 1 if the text only contains spaces. function Skip_Spaces (Text : in Wiki.Strings.WString; From : in Positive) return Positive; -- Find the position of the last non space character scanning the text backward -- from the given position. Returns Text'First - 1 if the text only contains spaces. function Trim_Spaces (Text : in Wiki.Strings.WString; From : in Positive) return Natural; -- Find the position of the given character in the string starting at the given position. function Index (Text : in Wiki.Strings.WString; Item : in Wiki.Strings.WChar; From : in Positive) return Natural; end Wiki.Helpers;
Skyfold/aws_sorter
Ada
715
ads
with GNAT.Sockets; with common_types; package Job_Types_Package is subtype Number_Array is common_types.Number_Array; type Job_Record (Job_Array_A_Length : Natural) is abstract tagged private; function Receive_Job (Channel : GNAT.Sockets.Stream_Access) return Job_Record is abstract; function Process_Job (E : in Job_Record) return Job_Record is abstract; procedure Return_Job (Channel : GNAT.Sockets.Stream_Access; E : Job_Record'Class); private type Job_Record (Job_Array_A_Length : Natural) is abstract tagged record Job_Array_A : Number_Array (1 .. Job_Array_A_Length); end record; end Job_Types_Package;
reznikmm/matreshka
Ada
4,199
adb
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2013, Vadim Godunko <[email protected]> -- -- 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 Matreshka.DOM_Nodes; with XML.DOM.Elements.Internals; package body ODF.DOM.Elements.Office.Bodies.Internals is ------------ -- Create -- ------------ function Create (Node : Matreshka.ODF_Elements.Office.Bodies.Office_Body_Access) return ODF.DOM.Elements.Office.Bodies.ODF_Office_Body is begin return (XML.DOM.Elements.Internals.Create (Matreshka.DOM_Nodes.Element_Access (Node)) with null record); end Create; ---------- -- Wrap -- ---------- function Wrap (Node : Matreshka.ODF_Elements.Office.Bodies.Office_Body_Access) return ODF.DOM.Elements.Office.Bodies.ODF_Office_Body is begin return (XML.DOM.Elements.Internals.Wrap (Matreshka.DOM_Nodes.Element_Access (Node)) with null record); end Wrap; end ODF.DOM.Elements.Office.Bodies.Internals;
Martin-Molinero/coinapi-sdk
Ada
6,138
adb
-- OEML _ REST API -- This section will provide necessary information about the `CoinAPI OEML REST API` protocol. This API is also available in the Postman application: <a href=\"https://postman.coinapi.io/\" target=\"_blank\">https://postman.coinapi.io/</a> -- -- The version of the OpenAPI document: v1 -- Contact: [email protected] -- -- NOTE: This package is auto generated by OpenAPI-Generator 5.1.1. -- https://openapi-generator.tech -- Do not edit the class manually. pragma Warnings (Off, "*is not referenced"); with Swagger.Streams; package body .Clients is pragma Style_Checks ("-mr"); -- Get balances -- Get current currency balance from all or single exchange. procedure V_1Balances_Get (Client : in out Client_Type; Exchange_Id : in Swagger.Nullable_UString; Result : out .Models.Balance_Type_Vectors.Vector) is URI : Swagger.Clients.URI_Type; Reply : Swagger.Value_Type; begin Client.Set_Accept ((Swagger.Clients.APPLICATION_JSON, Swagger.Clients.APPLICTION_JSON)); URI.Add_Param ("exchange_id", Exchange_Id); URI.Set_Path ("/v1/balances"); Client.Call (Swagger.Clients.GET, URI, Reply); .Models.Deserialize (Reply, "", Result); end V_1Balances_Get; -- Cancel all orders request -- This request cancels all open orders on single specified exchange. procedure V_1Orders_Cancel_All_Post (Client : in out Client_Type; Order_Cancel_All_Request_Type : in .Models.OrderCancelAllRequest_Type; Result : out .Models.Message_Type) is URI : Swagger.Clients.URI_Type; Req : Swagger.Clients.Request_Type; Reply : Swagger.Value_Type; begin Client.Set_Accept ((Swagger.Clients.APPLICATION_JSON, Swagger.Clients.APPLICTION_JSON)); Client.Initialize (Req, (1 => Swagger.Clients.APPLICATION_JSON)); .Models.Serialize (Req.Stream, "", Order_Cancel_All_Request_Type); URI.Set_Path ("/v1/orders/cancel/all"); Client.Call (Swagger.Clients.POST, URI, Req, Reply); .Models.Deserialize (Reply, "", Result); end V_1Orders_Cancel_All_Post; -- Cancel order request -- Request cancel for an existing order. The order can be canceled using the `client_order_id` or `exchange_order_id`. procedure V_1Orders_Cancel_Post (Client : in out Client_Type; Order_Cancel_Single_Request_Type : in .Models.OrderCancelSingleRequest_Type; Result : out .Models.OrderExecutionReport_Type) is URI : Swagger.Clients.URI_Type; Req : Swagger.Clients.Request_Type; Reply : Swagger.Value_Type; begin Client.Set_Accept ((Swagger.Clients.APPLICATION_JSON, Swagger.Clients.APPLICTION_JSON)); Client.Initialize (Req, (1 => Swagger.Clients.APPLICATION_JSON)); .Models.Serialize (Req.Stream, "", Order_Cancel_Single_Request_Type); URI.Set_Path ("/v1/orders/cancel"); Client.Call (Swagger.Clients.POST, URI, Req, Reply); .Models.Deserialize (Reply, "", Result); end V_1Orders_Cancel_Post; -- Get open orders -- Get last execution reports for open orders across all or single exchange. procedure V_1Orders_Get (Client : in out Client_Type; Exchange_Id : in Swagger.Nullable_UString; Result : out .Models.OrderExecutionReport_Type_Vectors.Vector) is URI : Swagger.Clients.URI_Type; Reply : Swagger.Value_Type; begin Client.Set_Accept ((Swagger.Clients.APPLICATION_JSON, Swagger.Clients.APPLICTION_JSON)); URI.Add_Param ("exchange_id", Exchange_Id); URI.Set_Path ("/v1/orders"); Client.Call (Swagger.Clients.GET, URI, Reply); .Models.Deserialize (Reply, "", Result); end V_1Orders_Get; -- Send new order -- This request creating new order for the specific exchange. procedure V_1Orders_Post (Client : in out Client_Type; Order_New_Single_Request_Type : in .Models.OrderNewSingleRequest_Type; Result : out .Models.OrderExecutionReport_Type) is URI : Swagger.Clients.URI_Type; Req : Swagger.Clients.Request_Type; Reply : Swagger.Value_Type; begin Client.Set_Accept ((Swagger.Clients.APPLICATION_JSON, Swagger.Clients.APPLICTION_JSON)); Client.Initialize (Req, (1 => Swagger.Clients.APPLICATION_JSON)); .Models.Serialize (Req.Stream, "", Order_New_Single_Request_Type); URI.Set_Path ("/v1/orders"); Client.Call (Swagger.Clients.POST, URI, Req, Reply); .Models.Deserialize (Reply, "", Result); end V_1Orders_Post; -- Get order execution report -- Get the last order execution report for the specified order. The requested order does not need to be active or opened. procedure V_1Orders_Status_Client_Order_Id_Get (Client : in out Client_Type; Client_Order_Id : in Swagger.UString; Result : out .Models.OrderExecutionReport_Type) is URI : Swagger.Clients.URI_Type; Reply : Swagger.Value_Type; begin Client.Set_Accept ((1 => Swagger.Clients.APPLICATION_JSON)); URI.Set_Path ("/v1/orders/status/{client_order_id}"); URI.Set_Path_Param ("client_order_id", Client_Order_Id); Client.Call (Swagger.Clients.GET, URI, Reply); .Models.Deserialize (Reply, "", Result); end V_1Orders_Status_Client_Order_Id_Get; -- Get open positions -- Get current open positions across all or single exchange. procedure V_1Positions_Get (Client : in out Client_Type; Exchange_Id : in Swagger.Nullable_UString; Result : out .Models.Position_Type_Vectors.Vector) is URI : Swagger.Clients.URI_Type; Reply : Swagger.Value_Type; begin Client.Set_Accept ((Swagger.Clients.APPLICATION_JSON, Swagger.Clients.APPLICTION_JSON)); URI.Add_Param ("exchange_id", Exchange_Id); URI.Set_Path ("/v1/positions"); Client.Call (Swagger.Clients.GET, URI, Reply); .Models.Deserialize (Reply, "", Result); end V_1Positions_Get; end .Clients;
AdaCore/training_material
Ada
1,387
adb
--Simple_IO_Spec --Simple_IO_Body with Ada.Text_IO; package body Simple_Io is function Get_String (Prompt : String) return String is Str : String (1 .. 1_000); Last : Integer; begin Ada.Text_IO.Put (Prompt & "> "); Ada.Text_IO.Get_Line (Str, Last); return Str (1 .. Last); end Get_String; function Get_Number (Prompt : String) return Integer is Str : constant String := Get_String (Prompt); begin return Integer'value (Str); end Get_Number; function Get_Character (Prompt : String) return Character is Str : constant String := Get_String (Prompt); begin return Str (Str'first); end Get_Character; procedure Print_String (Str : String) is begin Ada.Text_IO.Put_Line (Str); end Print_String; procedure Print_Number (Num : Integer) is begin Ada.Text_IO.Put_Line (Integer'image (Num)); end Print_Number; procedure Print_Character (Char : Character) is begin Ada.Text_IO.Put_Line (Character'image (Char)); end Print_Character; function Get_String (Prompt : String) return Unbounded_String is begin return To_Unbounded_String (Get_String (Prompt)); end Get_String; procedure Print_String (Str : Unbounded_String) is begin Print_String (To_String (Str)); end Print_String; end Simple_Io;
sparre/Ada-2012-Examples
Ada
1,342
adb
with Ada.Strings.Unbounded; package body Big_Integer is function "*" (Left, Right : in Instance) return Instance is Carry : Extended_Digit := 0; Sum : Extended_Digit; begin return Product : Instance := (others => 0) do for I in Left'Range loop for J in Right'Range loop if I + J in Product'Range then Sum := Left (I) * Right (J) + Carry + Product (I + J); Product (I + J) := Sum mod Base; Carry := Sum / Base; else Sum := Left (I) * Right (J) + Carry; if Sum = 0 then Carry := 0; else raise Constraint_Error with "Big integer overflow."; end if; end if; end loop; if Carry /= 0 then raise Constraint_Error with "Big integer overflow."; end if; end loop; end return; end "*"; function Image (Item : in Instance) return String is Buffer : Ada.Strings.Unbounded.Unbounded_String; begin for E of reverse Item loop Ada.Strings.Unbounded.Append (Buffer, Digit'Image (E)); end loop; return Ada.Strings.Unbounded.To_String (Buffer); end Image; end Big_Integer;
zhmu/ananas
Ada
9,263
ads
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- G N A T . A R R A Y _ S P L I T -- -- -- -- S p e c -- -- -- -- Copyright (C) 2002-2022, 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. -- -- -- ------------------------------------------------------------------------------ -- Useful array-manipulation routines: given a set of separators, split -- an array wherever the separators appear, and provide direct access -- to the resulting slices. with Ada.Finalization; generic type Element is (<>); -- Element of the array, this must be a discrete type type Element_Sequence is array (Positive range <>) of Element; -- The array which is a sequence of element type Element_Set is private; -- This type represent a set of elements. This set does not define a -- specific order of the elements. The conversion of a sequence to a -- set and membership tests in the set is performed using the routines -- To_Set and Is_In defined below. with function To_Set (Sequence : Element_Sequence) return Element_Set; -- Returns an Element_Set given an Element_Sequence. Duplicate elements -- can be ignored during this conversion. with function Is_In (Item : Element; Set : Element_Set) return Boolean; -- Returns True if Item is found in Set, False otherwise package GNAT.Array_Split is pragma Preelaborate; Index_Error : exception; -- Raised by all operations below if Index > Field_Count (S) type Separator_Mode is (Single, -- In this mode the array is cut at each element in the separator -- set. If two separators are contiguous the result at that position -- is an empty slice. Multiple -- In this mode contiguous separators are handled as a single -- separator and no empty slice is created. ); type Slice_Set is private with Iterable => (First => First_Cursor, Next => Advance, Has_Element => Has_Element, Element => Slice); -- This type uses by-reference semantics. This is a set of slices as -- returned by Create or Set routines below. The abstraction represents -- a set of items. Each item is a part of the original array named a -- Slice. It is possible to access individual slices by using the Slice -- routine below. The first slice in the Set is at the position/index -- 1. The total number of slices in the set is returned by Slice_Count. procedure Create (S : out Slice_Set; From : Element_Sequence; Separators : Element_Sequence; Mode : Separator_Mode := Single); function Create (From : Element_Sequence; Separators : Element_Sequence; Mode : Separator_Mode := Single) return Slice_Set; -- Create a cut array object. From is the source array, and Separators -- is a sequence of Element along which to split the array. The source -- array is sliced at separator boundaries. The separators are not -- included as part of the resulting slices. -- -- Note that if From is terminated by a separator an extra empty element -- is added to the slice set. If From only contains a separator the slice -- set contains two empty elements. procedure Create (S : out Slice_Set; From : Element_Sequence; Separators : Element_Set; Mode : Separator_Mode := Single); function Create (From : Element_Sequence; Separators : Element_Set; Mode : Separator_Mode := Single) return Slice_Set; -- Same as above but using a Element_Set procedure Set (S : in out Slice_Set; Separators : Element_Sequence; Mode : Separator_Mode := Single); -- Change the set of separators. The source array will be split according -- to this new set of separators. procedure Set (S : in out Slice_Set; Separators : Element_Set; Mode : Separator_Mode := Single); -- Same as above but using a Element_Set type Slice_Number is new Natural; -- Type used to count number of slices function Slice_Count (S : Slice_Set) return Slice_Number with Inline; -- Returns the number of slices (fields) in S function First_Cursor (Unused : Slice_Set) return Slice_Number is (1); function Advance (Unused : Slice_Set; Position : Slice_Number) return Slice_Number is (Position + 1); function Has_Element (Cont : Slice_Set; Position : Slice_Number) return Boolean is (Position <= Slice_Count (Cont)); -- Functions used to iterate over a Slice_Set function Slice (S : Slice_Set; Index : Slice_Number) return Element_Sequence with Inline; -- Returns the slice at position Index. First slice is 1. If Index is 0 -- the whole array is returned including the separators (this is the -- original source array). type Position is (Before, After); -- Used to designate position of separator type Slice_Separators is array (Position) of Element; -- Separators found before and after the slice Array_End : constant Element; -- This is the separator returned for the start or the end of the array function Separators (S : Slice_Set; Index : Slice_Number) return Slice_Separators; -- Returns the separators used to slice (front and back) the slice at -- position Index. For slices at start and end of the original array, the -- Array_End value is returned for the corresponding outer bound. In -- Multiple mode only the element closest to the slice is returned. -- if Index = 0, returns (Array_End, Array_End). type Separators_Indexes is array (Positive range <>) of Positive; function Separators (S : Slice_Set) return Separators_Indexes; -- Returns indexes of all separators used to slice original source array S private Array_End : constant Element := Element'First; type Element_Access is access Element_Sequence; type Indexes_Access is access Separators_Indexes; type Slice_Info is record Start : Positive; Stop : Natural; end record; -- Starting/Ending position of a slice. This does not include separators type Slices_Indexes is array (Slice_Number range <>) of Slice_Info; type Slices_Access is access Slices_Indexes; -- All indexes for fast access to slices. In the Slice_Set we keep only -- the original array and the indexes where each slice start and stop. type Data is record Ref_Counter : Natural; -- Reference counter, by-address sem Source : Element_Access; N_Slice : Slice_Number := 0; -- Number of slices found Indexes : Indexes_Access; Slices : Slices_Access; end record; type Data_Access is access all Data; type Slice_Set is new Ada.Finalization.Controlled with record D : Data_Access; end record; overriding procedure Initialize (S : in out Slice_Set); overriding procedure Adjust (S : in out Slice_Set); overriding procedure Finalize (S : in out Slice_Set); end GNAT.Array_Split;
AdaCore/libadalang
Ada
285
ads
package Gen is generic type T is private; package Opt_Types is type Opt_Type (Present : Boolean) is record case Present is when True => Value : T; when False => null; end case; end record; end Opt_Types; end Gen;
tum-ei-rcs/StratoX
Ada
325
ads
-- Institution: Technische Universität München -- Department: Realtime Computer Systems (RCS) -- Project: StratoX -- Module: LSM303D Driver -- -- Authors: Emanuel Regnath ([email protected]) -- -- Description: SPI Driver for the LSM303D -- -- ToDo: -- [ ] Implementation package LSM303D is end LSM303D;
reznikmm/matreshka
Ada
3,588
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Ada Modeling Framework -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2011-2012, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ -- This file is generated, don't edit it. ------------------------------------------------------------------------------ with AMF.Elements.Generic_Hash; function AMF.UML.Nodes.Hash is new AMF.Elements.Generic_Hash (UML_Node, UML_Node_Access);
Gabriel-Degret/adalib
Ada
981
ads
-- Standard Ada library specification -- Copyright (c) 2004-2016 AXE Consultants -- Copyright (c) 2004, 2005, 2006 Ada-Europe -- Copyright (c) 2000 The MITRE Corporation, Inc. -- Copyright (c) 1992, 1993, 1994, 1995 Intermetrics, Inc. -- SPDX-License-Identifier: BSD-3-Clause and LicenseRef-AdaReferenceManual --------------------------------------------------------------------------- package Ada.Locales is pragma Preelaborate(Locales); pragma Remote_Types(Locales); type Language_Code is new String (1 .. 3) with Dynamic_Predicate => (for all E of Language_Code => E in 'a' .. 'z'); type Country_Code is new String (1 .. 2) with Dynamic_Predicate => (for all E of Country_Code => E in 'A' .. 'Z'); Language_Unknown : constant Language_Code := "und"; Country_Unknown : constant Country_Code := "ZZ"; function Language return Language_Code; function Country return Country_Code; end Ada.Locales;
ekoeppen/STM32_Generic_Ada_Drivers
Ada
2,044
adb
with Ada.Real_Time; use Ada.Real_Time; with STM32_SVD; use STM32_SVD; with STM32_SVD.TIM; use STM32_SVD.TIM; with STM32_SVD.RCC; use STM32_SVD.RCC; package body STM32GD.Timer.Peripheral is Timer_Callback : Timer_Callback_Type := null; Frequency : constant Natural := 1_000; CK_INT : constant Natural := 8_000_000; Repeat : Boolean; First : Boolean; procedure Start (Time : Time_Span; Callback : Timer_Callback_Type); protected body IRQ_Handler is procedure Handler is begin if Timer = Timer_3 then TIM3_Periph.SR.UIF := 0; end if; if Timer_Callback /= null then if not First then if not Repeat then Stop; end if; Timer_Callback.all; else First := False; end if; end if; end Handler; end IRQ_Handler; procedure Init is begin if Timer = Timer_3 then RCC_Periph.APB1ENR.TIM3EN := 1; TIM3_Periph.PSC.PSC := UInt16 (CK_INT / Frequency); TIM3_Periph.CR1.ARPE := 1; end if; end Init; procedure Start (Time : Time_Span; Callback : Timer_Callback_Type) is MS : UInt16; begin MS := UInt16 (To_Duration (Time) * 1_000); Timer_Callback := Callback; First := True; if Timer = Timer_3 then TIM3_Periph.CNT.CNT_L := 0; TIM3_Periph.ARR.ARR_L := MS; TIM3_Periph.CR1.CEN := 1; TIM3_Periph.DIER.UIE := 1; end if; end Start; procedure Stop is begin if Timer = Timer_3 then TIM3_Periph.CR1.CEN := 0; TIM3_Periph.DIER.UIE := 0; end if; end Stop; procedure After (Time : Time_Span; Callback : Timer_Callback_Type) is begin Repeat := False; Start (Time, Callback); end After; procedure Every (Interval : Time_Span; Callback : Timer_Callback_Type) is begin Repeat := True; Start (Interval, Callback); end Every; end STM32GD.Timer.Peripheral;
onox/orka
Ada
869
ads
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2022 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Orka.Transforms.Singles.Vectors; with Generic_Test_Transforms_Vectors; package Test_Transforms_Singles_Vectors is new Generic_Test_Transforms_Vectors ("Singles", Orka.Transforms.Singles.Vectors);
reznikmm/matreshka
Ada
3,454
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Localization, Internationalization, Globalization for Ada -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2009 Vadim Godunko <[email protected]> -- -- -- -- Matreshka 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. Matreshka 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 distributed with Matreshka; see file COPYING. -- -- If not, write to the Free Software Foundation, 51 Franklin Street, -- -- Fifth Floor, Boston, MA 02110-1301, USA. -- -- -- -- As a special exception, if other files instantiate generics from this -- -- unit, or you link this unit with other files to produce an executable, -- -- this unit does not by itself cause the resulting executable to be -- -- covered by the GNU General Public License. This exception does not -- -- however invalidate any other reasons why the executable file might be -- -- covered by the GNU Public License. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ -- This package is an equivalent for System.Address_To_Access_Conversions -- except it operates on markable addresses. with System; with Matreshka.Internals.Host_Types; generic type Object (<>) is limited private; package Matreshka.Internals.Markable_Address_To_Access_Conversions is pragma Preelaborate; pragma Assert (Object'Alignment > 1); -- Lower bit is used for mark. type Object_Pointer is access all Object; for Object_Pointer'Size use Matreshka.Internals.Host_Types.Address_Size; function To_Pointer (Value : System.Address) return Object_Pointer; pragma Inline (To_Pointer); function To_Address (Value : Object_Pointer) return System.Address; pragma Inline (To_Address); function To_Marked_Address (Value : Object_Pointer) return System.Address; pragma Inline (To_Marked_Address); end Matreshka.Internals.Markable_Address_To_Access_Conversions;
clinta/synth
Ada
33,342
adb
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Ada.Strings.Hash; with GNAT.Regpat; with GNAT.String_Split; with Ada.Exceptions; with Signals; with Unix; package body PortScan is package EX renames Ada.Exceptions; package RGX renames GNAT.Regpat; package GSS renames GNAT.String_Split; package SIG renames Signals; ------------------------------ -- scan_entire_ports_tree -- ------------------------------ function scan_entire_ports_tree (portsdir : String) return Boolean is good_scan : Boolean; using_screen : constant Boolean := Unix.screen_attached; begin -- tree must be already mounted in the scan slave. -- However, prescan works on the real ports tree, not the mount. if not prescanned then prescan_ports_tree (portsdir); end if; parallel_deep_scan (success => good_scan, show_progress => using_screen); return good_scan; end scan_entire_ports_tree; ------------------------ -- scan_single_port -- ------------------------ function scan_single_port (catport : String; always_build : Boolean) return Boolean is xports : constant String := JT.USS (PM.configuration.dir_buildbase) & ss_base & "/xports"; procedure dig (cursor : block_crate.Cursor); target : port_index; aborted : Boolean := False; uscatport : JT.Text := JT.SUS (catport); procedure dig (cursor : block_crate.Cursor) is new_target : port_index := block_crate.Element (cursor); begin if not aborted then if not all_ports (new_target).scanned then populate_port_data (new_target); all_ports (new_target).blocked_by.Iterate (dig'Access); end if; end if; exception when issue : nonexistent_port => aborted := True; TIO.Put_Line (LAT.LF & get_catport (all_ports (new_target)) & " scan aborted because dependency could " & "not be located."); TIO.Put_Line (EX.Exception_Message (issue)); when issue : bmake_execution => aborted := True; TIO.Put_Line (LAT.LF & get_catport (all_ports (new_target)) & " scan aborted because 'make' encounted " & "an error in the Makefile."); TIO.Put_Line (EX.Exception_Message (issue)); when issue : make_garbage => aborted := True; TIO.Put_Line (LAT.LF & get_catport (all_ports (new_target)) & " scan aborted because dependency is malformed."); TIO.Put_Line (EX.Exception_Message (issue)); when issue : others => aborted := True; declare why : constant String := obvious_problem (xports, get_catport (all_ports (new_target))); begin if why = "" then TIO.Put_Line (LAT.LF & get_catport (all_ports (new_target)) & " scan aborted for an unknown reason."); TIO.Put_Line (EX.Exception_Message (issue)); else TIO.Put_Line (LAT.LF & get_catport (all_ports (new_target)) & " scan aborted" & why); end if; end; end dig; begin if not AD.Exists (xports & "/" & catport & "/Makefile") then return False; end if; if not prescanned then prescan_ports_tree (xports); end if; if ports_keys.Contains (Key => uscatport) then target := ports_keys.Element (Key => uscatport); else return False; end if; declare begin populate_port_data (target); all_ports (target).never_remote := always_build; exception when issue : others => TIO.Put ("Encountered issue with " & catport & " or its dependencies" & LAT.LF & " => "); TIO.Put_Line (EX.Exception_Message (issue)); return False; end; all_ports (target).blocked_by.Iterate (dig'Access); return not aborted; end scan_single_port; -------------------------- -- set_build_priority -- -------------------------- procedure set_build_priority is begin iterate_reverse_deps; iterate_drill_down; end set_build_priority; ------------------------ -- reset_ports_tree -- ------------------------ procedure reset_ports_tree is PR : port_record_access; begin for k in dim_all_ports'Range loop PR := all_ports (k)'Access; PR.sequence_id := 0; PR.key_cursor := portkey_crate.No_Element; PR.jobs := 1; PR.ignore_reason := JT.blank; PR.port_version := JT.blank; PR.package_name := JT.blank; PR.pkg_dep_query := JT.blank; PR.ignored := False; PR.scanned := False; PR.rev_scanned := False; PR.unlist_failed := False; PR.work_locked := False; PR.pkg_present := False; PR.remote_pkg := False; PR.never_remote := False; PR.deletion_due := False; PR.use_procfs := False; PR.use_linprocfs := False; PR.use_watchdog := watchdog_active; PR.reverse_score := 0; PR.librun.Clear; PR.blocks.Clear; PR.blocked_by.Clear; PR.all_reverse.Clear; PR.options.Clear; end loop; ports_keys.Clear; rank_queue.Clear; lot_number := 1; lot_counter := 0; last_port := 0; prescanned := False; wipe_make_queue; for m in scanners'Range loop mq_progress (m) := 0; end loop; end reset_ports_tree; -- PRIVATE FUNCTIONS -- -------------------------- -- iterate_drill_down -- -------------------------- procedure iterate_drill_down is begin rank_queue.Clear; for port in port_index'First .. last_port loop if all_ports (port).scanned then drill_down (next_target => port, original_target => port); declare ndx : constant port_index := port_index (all_ports (port).reverse_score); QR : constant queue_record := (ap_index => port, reverse_score => ndx); begin rank_queue.Insert (New_Item => QR); end; end if; end loop; end iterate_drill_down; -------------------------- -- parallel_deep_scan -- -------------------------- procedure parallel_deep_scan (success : out Boolean; show_progress : Boolean) is finished : array (scanners) of Boolean := (others => False); combined_wait : Boolean := True; aborted : Boolean := False; task type scan (lot : scanners); task body scan is procedure populate (cursor : subqueue.Cursor); procedure populate (cursor : subqueue.Cursor) is target_port : port_index := subqueue.Element (cursor); begin if not aborted then populate_port_data (target_port); mq_progress (lot) := mq_progress (lot) + 1; end if; exception when issue : others => TIO.Put_Line (LAT.LF & "culprit: " & get_catport (all_ports (target_port))); EX.Reraise_Occurrence (issue); end populate; begin make_queue (lot).Iterate (populate'Access); finished (lot) := True; exception when issue : nonexistent_port => aborted := True; TIO.Put_Line ("Scan aborted because dependency could " & "not be located."); TIO.Put_Line (EX.Exception_Message (issue)); when issue : bmake_execution => aborted := True; TIO.Put_Line ("Scan aborted because 'make' encounted " & "an error in the Makefile."); TIO.Put_Line (EX.Exception_Message (issue)); when issue : make_garbage => aborted := True; TIO.Put_Line ("Scan aborted because dependency is malformed."); TIO.Put_Line (EX.Exception_Message (issue)); when issue : others => aborted := True; TIO.Put_Line ("Scan aborted for an unknown reason."); TIO.Put_Line (EX.Exception_Message (issue)); end scan; scan_01 : scan (lot => 1); scan_02 : scan (lot => 2); scan_03 : scan (lot => 3); scan_04 : scan (lot => 4); scan_05 : scan (lot => 5); scan_06 : scan (lot => 6); scan_07 : scan (lot => 7); scan_08 : scan (lot => 8); scan_09 : scan (lot => 9); scan_10 : scan (lot => 10); scan_11 : scan (lot => 11); scan_12 : scan (lot => 12); scan_13 : scan (lot => 13); scan_14 : scan (lot => 14); scan_15 : scan (lot => 15); scan_16 : scan (lot => 16); scan_17 : scan (lot => 17); scan_18 : scan (lot => 18); scan_19 : scan (lot => 19); scan_20 : scan (lot => 20); scan_21 : scan (lot => 21); scan_22 : scan (lot => 22); scan_23 : scan (lot => 23); scan_24 : scan (lot => 24); scan_25 : scan (lot => 25); scan_26 : scan (lot => 26); scan_27 : scan (lot => 27); scan_28 : scan (lot => 28); scan_29 : scan (lot => 29); scan_30 : scan (lot => 30); scan_31 : scan (lot => 31); scan_32 : scan (lot => 32); begin TIO.Put_Line ("Scanning entire ports tree."); while combined_wait loop delay 1.0; if show_progress then TIO.Put (scan_progress); end if; combined_wait := False; for j in scanners'Range loop if not finished (j) then combined_wait := True; exit; end if; end loop; if SIG.graceful_shutdown_requested then aborted := True; end if; end loop; success := not aborted; end parallel_deep_scan; ----------------------- -- wipe_make_queue -- ----------------------- procedure wipe_make_queue is begin for j in scanners'Range loop make_queue (j).Clear; end loop; end wipe_make_queue; ------------------ -- drill_down -- ------------------ procedure drill_down (next_target : port_index; original_target : port_index) is PR : port_record_access := all_ports (next_target)'Access; procedure stamp_and_drill (cursor : block_crate.Cursor); procedure slurp_scanned (cursor : block_crate.Cursor); procedure slurp_scanned (cursor : block_crate.Cursor) is rev_id : port_index := block_crate.Element (Position => cursor); begin if not all_ports (original_target).all_reverse.Contains (rev_id) then all_ports (original_target).all_reverse.Insert (Key => rev_id, New_Item => rev_id); end if; end slurp_scanned; procedure stamp_and_drill (cursor : block_crate.Cursor) is pmc : port_index := block_crate.Element (Position => cursor); begin if not all_ports (original_target).all_reverse.Contains (pmc) then all_ports (original_target).all_reverse.Insert (Key => pmc, New_Item => pmc); end if; if pmc = original_target then declare top_port : constant String := get_catport (all_ports (original_target)); this_port : constant String := get_catport (all_ports (next_target)); begin raise circular_logic with top_port & " <=> " & this_port; end; end if; if not all_ports (pmc).rev_scanned then drill_down (next_target => pmc, original_target => pmc); end if; all_ports (pmc).all_reverse.Iterate (slurp_scanned'Access); end stamp_and_drill; begin if not PR.scanned then return; end if; if PR.rev_scanned then -- It is possible to get here if an earlier port scanned this port -- as a reverse dependencies return; end if; PR.blocks.Iterate (stamp_and_drill'Access); PR.reverse_score := port_index (PR.all_reverse.Length); PR.rev_scanned := True; end drill_down; ---------------------------- -- iterate_reverse_deps -- ----------------------------- procedure iterate_reverse_deps is madre : port_index; procedure set_reverse (cursor : block_crate.Cursor); procedure set_reverse (cursor : block_crate.Cursor) is begin -- Using conditional insert here causes a finalization error when -- the program exists. Reluctantly, do the condition check manually if not all_ports (block_crate.Element (cursor)).blocks.Contains (Key => madre) then all_ports (block_crate.Element (cursor)).blocks.Insert (Key => madre, New_Item => madre); end if; end set_reverse; begin for port in port_index'First .. last_port loop if all_ports (port).scanned then madre := port; all_ports (port).blocked_by.Iterate (set_reverse'Access); end if; end loop; end iterate_reverse_deps; -------------------- -- get_pkg_name -- -------------------- function get_pkg_name (origin : String) return String is xports : constant String := "/xports"; fullport : constant String := xports & "/" & origin; chroot : constant String := "/usr/sbin/chroot " & JT.USS (PM.configuration.dir_buildbase) & ss_base; command : constant String := chroot & " /usr/bin/make -C " & fullport & " -VPKGFILE:T"; content : JT.Text; topline : JT.Text; status : Integer; begin content := Unix.piped_command (command, status); if status /= 0 then raise bmake_execution with origin & " (return code =" & status'Img & ")"; end if; JT.nextline (lineblock => content, firstline => topline); return JT.USS (topline); end get_pkg_name; -------------------------- -- populate_port_data -- -------------------------- procedure populate_port_data (target : port_index) is xports : constant String := "/xports"; catport : String := get_catport (all_ports (target)); fullport : constant String := xports & "/" & catport; chroot : constant String := "/usr/sbin/chroot " & JT.USS (PM.configuration.dir_buildbase) & ss_base; command : constant String := chroot & " /usr/bin/make -C " & fullport & " -VPKGVERSION -VPKGFILE:T -VMAKE_JOBS_NUMBER -VIGNORE" & " -VFETCH_DEPENDS -VEXTRACT_DEPENDS -VPATCH_DEPENDS" & " -VBUILD_DEPENDS -VLIB_DEPENDS -VRUN_DEPENDS" & " -VSELECTED_OPTIONS -VDESELECTED_OPTIONS" & " -V_INCLUDE_USES_SCONS_MK -VUSE_LINUX"; content : JT.Text; topline : JT.Text; status : Integer; type result_range is range 1 .. 14; -- prototypes procedure set_depends (line : JT.Text; dtype : dependency_type); procedure set_options (line : JT.Text; on : Boolean); procedure set_depends (line : JT.Text; dtype : dependency_type) is subs : GSS.Slice_Set; deps_found : GSS.Slice_Number; trimline : constant JT.Text := JT.trim (line); zero_deps : constant GSS.Slice_Number := GSS.Slice_Number (0); dirlen : constant Natural := xports'Length; use type GSS.Slice_Number; begin if JT.IsBlank (trimline) then return; end if; GSS.Create (S => subs, From => JT.USS (trimline), Separators => " " & LAT.HT, Mode => GSS.Multiple); deps_found := GSS.Slice_Count (S => subs); if deps_found = zero_deps then return; end if; for j in 1 .. deps_found loop declare workdep : constant String := GSS.Slice (subs, j); fulldep : constant String (1 .. workdep'Length) := workdep; colon : constant Natural := find_colon (fulldep); colon1 : constant Natural := colon + 1; deprec : portkey_crate.Cursor; use type portkey_crate.Cursor; begin if colon < 2 then raise make_garbage with dtype'Img & ": " & JT.USS (trimline) & " (" & catport & ")"; end if; if fulldep'Length > colon1 + dirlen + 5 and then fulldep (colon1 .. colon1 + dirlen) = xports & "/" then deprec := ports_keys.Find (Key => scrub_phase (fulldep (colon + dirlen + 2 .. fulldep'Last))); else deprec := ports_keys.Find (Key => scrub_phase (fulldep (colon1 .. fulldep'Last))); end if; if deprec = portkey_crate.No_Element then raise nonexistent_port with fulldep (colon1 + 8 .. fulldep'Last) & " (required dependency of " & catport & ") does not exist."; end if; declare depindex : port_index := portkey_crate.Element (deprec); begin if not all_ports (target).blocked_by.Contains (depindex) then all_ports (target).blocked_by.Insert (Key => depindex, New_Item => depindex); end if; if dtype in LR_set then if not all_ports (target).librun.Contains (depindex) then all_ports (target).librun.Insert (Key => depindex, New_Item => depindex); end if; end if; end; end; end loop; end set_depends; procedure set_options (line : JT.Text; on : Boolean) is subs : GSS.Slice_Set; opts_found : GSS.Slice_Number; trimline : constant JT.Text := JT.trim (line); zero_opts : constant GSS.Slice_Number := GSS.Slice_Number (0); use type GSS.Slice_Number; begin if JT.IsBlank (trimline) then return; end if; GSS.Create (S => subs, From => JT.USS (trimline), Separators => " ", Mode => GSS.Multiple); opts_found := GSS.Slice_Count (S => subs); if opts_found = zero_opts then return; end if; for j in 1 .. opts_found loop declare opt : JT.Text := JT.SUS (GSS.Slice (subs, j)); begin if not all_ports (target).options.Contains (opt) then all_ports (target).options.Insert (Key => opt, New_Item => on); end if; end; end loop; end set_options; begin content := Unix.piped_command (command, status); if status /= 0 then raise bmake_execution with catport & " (return code =" & status'Img & ")"; end if; for k in result_range loop JT.nextline (lineblock => content, firstline => topline); case k is when 1 => all_ports (target).port_version := topline; when 2 => all_ports (target).package_name := topline; when 3 => declare begin all_ports (target).jobs := builders (Integer'Value (JT.USS (topline))); exception when others => all_ports (target).jobs := PM.configuration.num_builders; end; when 4 => all_ports (target).ignore_reason := topline; all_ports (target).ignored := not JT.IsBlank (topline); when 5 => set_depends (topline, fetch); when 6 => set_depends (topline, extract); when 7 => set_depends (topline, patch); when 8 => set_depends (topline, build); when 9 => set_depends (topline, library); when 10 => set_depends (topline, runtime); when 11 => set_options (topline, True); when 12 => set_options (topline, False); when 13 => if JT.equivalent (topline, "yes") then all_ports (target).use_watchdog := False; end if; when 14 => if not JT.IsBlank (JT.trim (topline)) then all_ports (target).use_linprocfs := True; end if; end case; end loop; all_ports (target).scanned := True; if catport = "x11-toolkits/gnustep-gui" or else catport = "lang/rust" or else catport = "lang/rust-nightly" then all_ports (target).use_procfs := True; end if; if catport = "emulators/linux_base-c6" or else catport = "emulators/linux_base-f10" or else catport = "sysutils/htop" then all_ports (target).use_linprocfs := True; end if; exception when issue : others => EX.Reraise_Occurrence (issue); end populate_port_data; ----------------- -- set_cores -- ----------------- procedure set_cores is command : constant String := "/sbin/sysctl hw.ncpu"; content : JT.Text; status : Integer; begin -- expected output: "hw.ncpu: C" where C is integer content := Unix.piped_command (command, status); if status /= 0 then number_cores := cpu_range'First; return; end if; declare str_content : String := JT.USS (content); ncpu : String := str_content (10 .. str_content'Last - 1); number : Positive := Integer'Value (ncpu); begin if number > Positive (cpu_range'Last) then number_cores := cpu_range'Last; else number_cores := cpu_range (number); end if; end; end set_cores; ----------------------- -- cores_available -- ----------------------- function cores_available return cpu_range is begin return number_cores; end cores_available; -------------------------- -- prescan_ports_tree -- -------------------------- procedure prescan_ports_tree (portsdir : String) is procedure quick_scan (cursor : string_crate.Cursor); Search : AD.Search_Type; Dir_Ent : AD.Directory_Entry_Type; categories : string_crate.Vector; -- scan entire ports tree, and for each port hooked into the build, -- push an initial port_rec into the all_ports container procedure quick_scan (cursor : string_crate.Cursor) is category : constant String := JT.USS (string_crate.Element (Position => cursor)); begin if AD.Exists (portsdir & "/" & category & "/Makefile") then grep_Makefile (portsdir => portsdir, category => category); else walk_all_subdirectories (portsdir => portsdir, category => category); end if; end quick_scan; begin AD.Start_Search (Search => Search, Directory => portsdir, Filter => (AD.Directory => True, others => False), Pattern => "[a-z]*"); while AD.More_Entries (Search => Search) loop AD.Get_Next_Entry (Search => Search, Directory_Entry => Dir_Ent); declare category : constant String := AD.Simple_Name (Dir_Ent); begin if category /= "distfiles" and then category /= "packages" then categories.Append (New_Item => JT.SUS (category)); end if; end; end loop; AD.End_Search (Search => Search); categories.Iterate (Process => quick_scan'Access); prescanned := True; end prescan_ports_tree; ------------------ -- find_colon -- ------------------ function find_colon (Source : String) return Natural is result : Natural := 0; strlen : constant Natural := Source'Length; begin for j in 1 .. strlen loop if Source (j) = LAT.Colon then result := j; exit; end if; end loop; return result; end find_colon; ------------------- -- scrub_phase -- ------------------- function scrub_phase (Source : String) return JT.Text is reset : constant String (1 .. Source'Length) := Source; colon : constant Natural := find_colon (reset); begin if colon = 0 then return JT.SUS (reset); end if; return JT.SUS (reset (1 .. colon - 1)); end scrub_phase; -------------------------- -- determine_max_lots -- -------------------------- function get_max_lots return scanners is first_try : constant Positive := Positive (number_cores) * 3; begin if first_try > Positive (scanners'Last) then return scanners'Last; else return scanners (first_try); end if; end get_max_lots; --------------------- -- grep_Makefile -- --------------------- procedure grep_Makefile (portsdir, category : String) is archive : TIO.File_Type; matches : RGX.Match_Array (0 .. 1); pattern : constant String := "SUBDIR[[:space:]]*[:+:]=[[:space:]]*(.*)"; regex : constant RGX.Pattern_Matcher := RGX.Compile (pattern); max_lots : constant scanners := get_max_lots; begin TIO.Open (File => archive, Mode => TIO.In_File, Name => portsdir & "/" & category & "/Makefile"); while not TIO.End_Of_File (File => archive) loop declare line : constant String := TIO.Get_Line (File => archive); blank_rec : port_record; kc : portkey_crate.Cursor; success : Boolean; use type RGX.Match_Location; begin RGX.Match (Self => regex, Data => line, Matches => matches); if matches (0) /= RGX.No_Match then declare portkey : constant JT.Text := JT.SUS (category & '/' & line (matches (1).First .. matches (1).Last)); begin ports_keys.Insert (Key => portkey, New_Item => lot_counter, Position => kc, Inserted => success); last_port := lot_counter; all_ports (lot_counter).sequence_id := lot_counter; all_ports (lot_counter).key_cursor := kc; make_queue (lot_number).Append (lot_counter); end; end if; end; lot_counter := lot_counter + 1; if lot_number = max_lots then lot_number := 1; else lot_number := lot_number + 1; end if; end loop; TIO.Close (File => archive); end grep_Makefile; ------------------------------- -- walk_all_subdirectories -- ------------------------------- procedure walk_all_subdirectories (portsdir, category : String) is inner_search : AD.Search_Type; inner_dirent : AD.Directory_Entry_Type; max_lots : constant scanners := get_max_lots; begin AD.Start_Search (Search => inner_search, Directory => portsdir & "/" & category, Filter => (AD.Directory => True, others => False), Pattern => ""); while AD.More_Entries (Search => inner_search) loop AD.Get_Next_Entry (Search => inner_search, Directory_Entry => inner_dirent); declare portname : constant String := AD.Simple_Name (inner_dirent); portkey : constant JT.Text := JT.SUS (category & "/" & portname); kc : portkey_crate.Cursor; success : Boolean; begin if portname /= "." and then portname /= ".." then ports_keys.Insert (Key => portkey, New_Item => lot_counter, Position => kc, Inserted => success); last_port := lot_counter; all_ports (lot_counter).sequence_id := lot_counter; all_ports (lot_counter).key_cursor := kc; make_queue (lot_number).Append (lot_counter); lot_counter := lot_counter + 1; if lot_number = max_lots then lot_number := 1; else lot_number := lot_number + 1; end if; end if; end; end loop; end walk_all_subdirectories; ----------------- -- port_hash -- ----------------- function port_hash (key : JT.Text) return AC.Hash_Type is begin return Ada.Strings.Hash (JT.USS (key)); end port_hash; ------------------ -- block_hash -- ------------------ function block_hash (key : port_index) return AC.Hash_Type is preresult : constant AC.Hash_Type := AC.Hash_Type (key); use type AC.Hash_Type; begin -- Equivalent to mod 128 return preresult and 2#1111111#; end block_hash; ------------------ -- block_ekey -- ------------------ function block_ekey (left, right : port_index) return Boolean is begin return left = right; end block_ekey; -------------------------------------- -- "<" function for ranking_crate -- -------------------------------------- function "<" (L, R : queue_record) return Boolean is begin if L.reverse_score = R.reverse_score then return R.ap_index > L.ap_index; end if; return L.reverse_score > R.reverse_score; end "<"; ------------------- -- get_catport -- ------------------- function get_catport (PR : port_record) return String is use type portkey_crate.Cursor; begin if PR.key_cursor = portkey_crate.No_Element then return "get_catport: invalid key_cursor"; end if; return JT.USS (portkey_crate.Key (PR.key_cursor)); end get_catport; --------------------- -- scan_progress -- --------------------- function scan_progress return String is type percent is delta 0.01 digits 5; complete : port_index := 0; pc : percent; begin for k in scanners'Range loop complete := complete + mq_progress (k); end loop; pc := percent (100.0 * Float (complete) / Float (last_port)); return " progress:" & pc'Img & "% " & LAT.CR; end scan_progress; ----------------------- -- obvious_problem -- ----------------------- function obvious_problem (portsdir, catport : String) return String is fullpath : constant String := portsdir & "/" & catport; begin if AD.Exists (fullpath) then declare Search : AD.Search_Type; dirent : AD.Directory_Entry_Type; has_contents : Boolean := False; begin AD.Start_Search (Search => Search, Directory => fullpath, Filter => (others => True), Pattern => "*"); while AD.More_Entries (Search => Search) loop AD.Get_Next_Entry (Search => Search, Directory_Entry => dirent); if AD.Simple_Name (dirent) /= "." and then AD.Simple_Name (dirent) /= ".." then has_contents := True; exit; end if; end loop; AD.End_Search (Search => Search); if not has_contents then return " (directory empty)"; end if; if AD.Exists (fullpath & "/Makefile") then return ""; else return " (Makefile missing)"; end if; end; else return " (port deleted)"; end if; end obvious_problem; end PortScan;
AdaCore/ada-traits-containers
Ada
856
ads
-- -- Copyright (C) 2016, AdaCore -- -- SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -- pragma Ada_2012; with Conts.Elements; with Conts.Vectors.Generics; with Conts.Vectors.Storage; package Support is subtype Index_Type is Positive; generic with package Elements is new Conts.Elements.Traits (Element_Type => Integer, others => <>); with package Storage is new Conts.Vectors.Storage.Traits (Elements => Elements, others => <>); with package Vectors is new Conts.Vectors.Generics (Storage => Storage, Index_Type => Index_Type); with function Image (Self : Elements.Constant_Returned) return String; procedure Test (V1 : in out Vectors.Vector); -- Perform various tests. -- All vectors should be empty on input. This is used to handle bounded -- vectors. end Support;
MinimSecure/unum-sdk
Ada
833
adb
-- Copyright 2011-2019 Free Software Foundation, Inc. -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. package body Pck is procedure Do_Nothing (A : System.Address) is begin null; end Do_Nothing; end Pck;
Samsung/TizenRT
Ada
3,820
adb
--------------------------------------------------------------- - -- ZLib for Ada thick binding. -- -- -- -- Copyright(C) 2002 - 2004 Dmitriy Anisimkov -- -- -- -- Open source license information is in the zlib.ads file. -- ---------------------------------------------------------------- -- -- $Id: buffer_demo.adb, v 1.3 2004 / 09 / 06 06:55:35 vagul Exp $ -- This demo program provided by Dr Steve Sangwine < [email protected] > -- -- Demonstration of a problem with Zlib - Ada(already fixed) when a buffer -- of exactly the correct size is used for decompressed data, and the last -- few bytes passed in to Zlib are checksum bytes. -- This program compresses a string of text, and then decompresses the -- compressed text into a buffer of the same size as the original text. with Ada.Streams; use Ada.Streams; with Ada.Text_IO; with ZLib; use ZLib; procedure Buffer_Demo is EOL : Character renames ASCII.LF; Text : constant String : = "Four score and seven years ago our fathers brought forth," &EOL & "upon this continent, a new nation, conceived in liberty," &EOL & "and dedicated to the proposition that `all men are created equal'."; Source : Stream_Element_Array(1 .. Text'Length); for Source'Address use Text'Address; begin Ada.Text_IO.Put(Text); Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line ("Uncompressed size : " & Positive'Image (Text'Length) & " bytes"); declare Compressed_Data : Stream_Element_Array(1 .. Text'Length); L : Stream_Element_Offset; begin Compress : declare Compressor : Filter_Type; I : Stream_Element_Offset; begin Deflate_Init(Compressor); - - Compress the whole of T at once. Translate(Compressor, Source, I, Compressed_Data, L, Finish); pragma Assert(I = Source'Last); Close(Compressor); Ada.Text_IO.Put_Line ("Compressed size : " & Stream_Element_Offset'Image (L) & " bytes"); end Compress; - - Now we decompress the data, passing short blocks of data to Zlib -- (because this demonstrates the problem - the last block passed will -- contain checksum information and there will be no output, only a -- check inside Zlib that the checksum is correct). Decompress : declare Decompressor : Filter_Type; Uncompressed_Data : Stream_Element_Array(1 .. Text'Length); Block_Size : constant : = 4; - - This makes sure that the last block contains -- only Adler checksum data. P : Stream_Element_Offset : = Compressed_Data'First - 1; O : Stream_Element_Offset; begin Inflate_Init(Decompressor); loop Translate (Decompressor, Compressed_Data (P + 1 .. Stream_Element_Offset'Min (P + Block_Size, L)), P, Uncompressed_Data (Total_Out(Decompressor) + 1 .. Uncompressed_Data'Last), O, No_Flush); Ada.Text_IO.Put_Line ("Total in : " & Count'Image (Total_In (Decompressor)) & ", out : " & Count'Image (Total_Out (Decompressor))); exit when P = L; end loop; Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line ("Decompressed text matches original text : " & Boolean'Image (Uncompressed_Data = Source)); end Decompress; end; end Buffer_Demo;
AdaCore/Ada_Drivers_Library
Ada
6,555
adb
------------------------------------------------------------------------------ -- -- -- 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. -- -- -- ------------------------------------------------------------------------------ -- The file declares the main procedure for the demonstration. -- The main program uses the DMA controller to send a block of characters -- to a USART. The characters are sent continuously as long as the program -- executes. Note that all the LEDs flash initially, before any characters -- are sent, as a confirmation of overall execution. with STM32; use STM32; with STM32.DMA; use STM32.DMA; with STM32.GPIO; use STM32.GPIO; with STM32.USARTs; use STM32.USARTs; with STM32.Device; use STM32.Device; with STM32.Board; use STM32.Board; with Ada.Real_Time; use Ada.Real_Time; with Peripherals; use Peripherals; procedure Demo_USART_DMA_Continuous is type Data is array (1 .. 26) of Character; -- arbitrary size, component type for Data'Component_Size use 8; -- confirming Bytes_To_Transfer : constant := Data'Length; Source_Block : constant Data := "abcdefghijklmnopqrstuvwxyz"; procedure Initialize_GPIO_Port_Pins; procedure Initialize_USART; procedure Initialize_DMA; procedure Blink_LEDs; ------------------------------- -- Initialize_GPIO_Port_Pins -- ------------------------------- procedure Initialize_GPIO_Port_Pins is begin Enable_Clock (RX_Pin & TX_Pin); Configure_IO (RX_Pin & TX_Pin, (Mode => Mode_AF, AF => Transceiver_AF, AF_Speed => Speed_50MHz, AF_Output_Type => Push_Pull, Resistors => Pull_Up)); end Initialize_GPIO_Port_Pins; ---------------------- -- Initialize_USART -- ---------------------- procedure Initialize_USART is begin Enable_Clock (Transceiver); Enable (Transceiver); Set_Baud_Rate (Transceiver, 115_200); Set_Mode (Transceiver, Tx_Mode); Set_Stop_Bits (Transceiver, Stopbits_1); Set_Word_Length (Transceiver, Word_Length_8); Set_Parity (Transceiver, No_Parity); Set_Flow_Control (Transceiver, No_Flow_Control); end Initialize_USART; -------------------- -- Initialize_DMA -- -------------------- procedure Initialize_DMA is Configuration : DMA_Stream_Configuration; begin Enable_Clock (Controller); Reset (Controller, Tx_Stream); Configuration.Channel := Tx_Channel; Configuration.Direction := Memory_To_Peripheral; Configuration.Increment_Peripheral_Address := False; Configuration.Increment_Memory_Address := True; Configuration.Peripheral_Data_Format := Bytes; Configuration.Memory_Data_Format := Bytes; Configuration.Operation_Mode := Circular_Mode; Configuration.Priority := Priority_Very_High; Configuration.FIFO_Enabled := True; Configuration.FIFO_Threshold := FIFO_Threshold_Full_Configuration; Configuration.Memory_Burst_Size := Memory_Burst_Inc4; Configuration.Peripheral_Burst_Size := Peripheral_Burst_Single; Configure (Controller, Tx_Stream, Configuration); -- note the controller is disabled by the call to Configure end Initialize_DMA; ---------------- -- Blink_LEDs -- ---------------- procedure Blink_LEDs is begin for K in 1 .. 3 loop All_LEDs_On; delay until Clock + Milliseconds (200); All_LEDs_Off; delay until Clock + Milliseconds (200); end loop; end Blink_LEDs; begin Initialize_LEDs; Blink_LEDs; -- just to signal that we are indeed running... Initialize_GPIO_Port_Pins; Initialize_USART; Initialize_DMA; Enable (Transceiver); Start_Transfer (Controller, Tx_Stream, Source => Source_Block'Address, Destination => Data_Register_Address (Transceiver), Data_Count => Bytes_To_Transfer); -- also enables the stream Enable_DMA_Transmit_Requests (Transceiver); -- at this point the characters will be coming continuously from the USART Turn_On (Green_LED); loop null; end loop; end Demo_USART_DMA_Continuous;
hannawaage/TTK4145_Exercises
Ada
3,889
adb
with Ada.Text_IO, Ada.Integer_Text_IO, Ada.Numerics.Float_Random; use Ada.Text_IO, Ada.Integer_Text_IO, Ada.Numerics.Float_Random; procedure exercise8 is Count_Failed : exception; -- Exception to be raised when counting fails Gen : Generator; -- Random number generator protected type Transaction_Manager (N : Positive) is entry Finished; entry Wait_Until_Aborted; procedure Signal_Abort; private Finished_Gate_Open : Boolean := False; Aborted : Boolean := False; end Transaction_Manager; protected body Transaction_Manager is entry Finished when Finished_Gate_Open or Finished'Count = N is begin ------------------------------------------ -- PART 3: Modify the Finished entry ------------------------------------------ Finished_Gate_Open := Finished'Count /= 0; if not Finished_Gate_Open then Aborted := False; end if; ----- -------- end Finished; procedure Signal_Abort is begin Aborted := True; end Signal_Abort; ------------------------------------------ -- PART 2: Create the Wait_Until_Aborted entry ------------------------------------------ entry Wait_Until_Aborted when Aborted is begin if Wait_Until_Aborted'Count = 0 then Aborted := False; end if; end; end Transaction_Manager; function Unreliable_Slow_Add (x : Integer) return Integer is Error_Rate : Constant := 0.15; -- (between 0 and 1) begin if Random(Gen) > Error_Rate then delay Duration(Random(Gen) * 5.0); return X + 10; else delay Duration(Random(Gen) * 1.0); raise Count_Failed; end if; end Unreliable_Slow_Add; function Add_Five (x : Integer) return Integer is begin return X + 5; end Add_Five; task type Transaction_Worker (Initial : Integer; Manager : access Transaction_Manager); task body Transaction_Worker is Num : Integer := Initial; Prev : Integer := Num; Round_Num : Integer := 0; begin Put_Line ("Worker" & Integer'Image(Initial) & " started"); loop Put_Line ("Worker" & Integer'Image(Initial) & " started round" & Integer'Image(Round_Num)); Round_Num := Round_Num + 1; ------------------------------------------ -- PART 1: Select-Then-Abort statement ------------------------------------------ Prev := Num; select -- eg. X.Entry_Call; -- code that is run when the triggering_alternative has triggered -- (forward ER code goes here) Manager.Wait_Until_Aborted; Num := Add_Five(Num); Put_Line (" Worker" & Integer'Image(Initial) & " comitting" & Integer'Image(Num)); then abort begin Num := Unreliable_Slow_Add(Num); exception when Count_Failed => Manager.Signal_Abort; end; Put_Line (" Worker" & Integer'Image(Initial) & " comitting" & Integer'Image(Num)); Manager.Finished; -- code that is run when nothing has triggered -- (main functionality) end select; Prev := Num; delay 0.5; end loop; end Transaction_Worker; Manager : aliased Transaction_Manager (3); Worker_1 : Transaction_Worker (0, Manager'Access); Worker_2 : Transaction_Worker (1, Manager'Access); Worker_3 : Transaction_Worker (2, Manager'Access); begin Reset(Gen); -- Seed the random number generator end exercise8;
righthalfplane/SdrGlut
Ada
19,369
adb
---------------------------------------------------------------- -- ZLib for Ada thick binding. -- -- -- -- Copyright (C) 2002-2003 Dmitriy Anisimkov -- -- -- -- Open source license information is in the zlib.ads file. -- ---------------------------------------------------------------- -- $Id: zlib.adb,v 1.19 2003/07/13 16:02:19 vagul Exp $ with Ada.Exceptions; with Ada.Unchecked_Conversion; with Ada.Unchecked_Deallocation; with Interfaces.C.Strings; with ZLib.Thin; package body ZLib is use type Thin.Int; type Z_Stream is new Thin.Z_Stream; type Return_Code_Enum is (OK, STREAM_END, NEED_DICT, ERRNO, STREAM_ERROR, DATA_ERROR, MEM_ERROR, BUF_ERROR, VERSION_ERROR); type Flate_Step_Function is access function (Strm : Thin.Z_Streamp; flush : Thin.Int) return Thin.Int; pragma Convention (C, Flate_Step_Function); type Flate_End_Function is access function (Ctrm : in Thin.Z_Streamp) return Thin.Int; pragma Convention (C, Flate_End_Function); type Flate_Type is record Step : Flate_Step_Function; Done : Flate_End_Function; end record; subtype Footer_Array is Stream_Element_Array (1 .. 8); Simple_GZip_Header : constant Stream_Element_Array (1 .. 10) := (16#1f#, 16#8b#, -- Magic header 16#08#, -- Z_DEFLATED 16#00#, -- Flags 16#00#, 16#00#, 16#00#, 16#00#, -- Time 16#00#, -- XFlags 16#03# -- OS code ); -- The simplest gzip header is not for informational, but just for -- gzip format compatibility. -- Note that some code below is using assumption -- Simple_GZip_Header'Last > Footer_Array'Last, so do not make -- Simple_GZip_Header'Last <= Footer_Array'Last. Return_Code : constant array (Thin.Int range <>) of Return_Code_Enum := (0 => OK, 1 => STREAM_END, 2 => NEED_DICT, -1 => ERRNO, -2 => STREAM_ERROR, -3 => DATA_ERROR, -4 => MEM_ERROR, -5 => BUF_ERROR, -6 => VERSION_ERROR); Flate : constant array (Boolean) of Flate_Type := (True => (Step => Thin.Deflate'Access, Done => Thin.DeflateEnd'Access), False => (Step => Thin.Inflate'Access, Done => Thin.InflateEnd'Access)); Flush_Finish : constant array (Boolean) of Flush_Mode := (True => Finish, False => No_Flush); procedure Raise_Error (Stream : Z_Stream); pragma Inline (Raise_Error); procedure Raise_Error (Message : String); pragma Inline (Raise_Error); procedure Check_Error (Stream : Z_Stream; Code : Thin.Int); procedure Free is new Ada.Unchecked_Deallocation (Z_Stream, Z_Stream_Access); function To_Thin_Access is new Ada.Unchecked_Conversion (Z_Stream_Access, Thin.Z_Streamp); procedure Translate_GZip (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); -- Separate translate routine for make gzip header. procedure Translate_Auto (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); -- translate routine without additional headers. ----------------- -- Check_Error -- ----------------- procedure Check_Error (Stream : Z_Stream; Code : Thin.Int) is use type Thin.Int; begin if Code /= Thin.Z_OK then Raise_Error (Return_Code_Enum'Image (Return_Code (Code)) & ": " & Last_Error_Message (Stream)); end if; end Check_Error; ----------- -- Close -- ----------- procedure Close (Filter : in out Filter_Type; Ignore_Error : in Boolean := False) is Code : Thin.Int; begin Code := Flate (Filter.Compression).Done (To_Thin_Access (Filter.Strm)); Filter.Opened := False; if Ignore_Error or else Code = Thin.Z_OK then Free (Filter.Strm); else declare Error_Message : constant String := Last_Error_Message (Filter.Strm.all); begin Free (Filter.Strm); Ada.Exceptions.Raise_Exception (ZLib_Error'Identity, Return_Code_Enum'Image (Return_Code (Code)) & ": " & Error_Message); end; end if; end Close; ----------- -- CRC32 -- ----------- function CRC32 (CRC : in Unsigned_32; Data : in Ada.Streams.Stream_Element_Array) return Unsigned_32 is use Thin; begin return Unsigned_32 (crc32 (ULong (CRC), Bytes.To_Pointer (Data'Address), Data'Length)); end CRC32; procedure CRC32 (CRC : in out Unsigned_32; Data : in Ada.Streams.Stream_Element_Array) is begin CRC := CRC32 (CRC, Data); end CRC32; ------------------ -- Deflate_Init -- ------------------ 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 := 15; Memory_Level : in Memory_Level_Type := 8; Header : in Header_Type := Default) is use type Thin.Int; Win_Bits : Thin.Int := Thin.Int (Window_Bits); begin -- We allow ZLib to make header only in case of default header type. -- Otherwise we would either do header by ourselfs, or do not do -- header at all. if Header = None or else Header = GZip then Win_Bits := -Win_Bits; end if; -- For the GZip CRC calculation and make headers. if Header = GZip then Filter.CRC := 0; Filter.Offset := Simple_GZip_Header'First; else Filter.Offset := Simple_GZip_Header'Last + 1; end if; Filter.Strm := new Z_Stream; Filter.Compression := True; Filter.Stream_End := False; Filter.Opened := True; Filter.Header := Header; if Thin.Deflate_Init (To_Thin_Access (Filter.Strm), Level => Thin.Int (Level), method => Thin.Int (Method), windowBits => Win_Bits, memLevel => Thin.Int (Memory_Level), strategy => Thin.Int (Strategy)) /= Thin.Z_OK then Raise_Error (Filter.Strm.all); end if; end Deflate_Init; ----------- -- Flush -- ----------- 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) is No_Data : Stream_Element_Array := (1 .. 0 => 0); Last : Stream_Element_Offset; begin Translate (Filter, No_Data, Last, Out_Data, Out_Last, Flush); end Flush; ----------------------- -- Generic_Translate -- ----------------------- procedure Generic_Translate (Filter : in out ZLib.Filter_Type; In_Buffer_Size : Integer := Default_Buffer_Size; Out_Buffer_Size : Integer := Default_Buffer_Size) is In_Buffer : Stream_Element_Array (1 .. Stream_Element_Offset (In_Buffer_Size)); Out_Buffer : Stream_Element_Array (1 .. Stream_Element_Offset (Out_Buffer_Size)); Last : Stream_Element_Offset; In_Last : Stream_Element_Offset; In_First : Stream_Element_Offset; Out_Last : Stream_Element_Offset; begin Main : loop Data_In (In_Buffer, Last); In_First := In_Buffer'First; loop Translate (Filter, In_Buffer (In_First .. Last), In_Last, Out_Buffer, Out_Last, Flush_Finish (Last < In_Buffer'First)); Data_Out (Out_Buffer (Out_Buffer'First .. Out_Last)); exit Main when Stream_End (Filter); -- The end of in buffer. exit when In_Last = Last; In_First := In_Last + 1; end loop; end loop Main; end Generic_Translate; ------------------ -- Inflate_Init -- ------------------ procedure Inflate_Init (Filter : in out Filter_Type; Window_Bits : in Window_Bits_Type := 15; Header : in Header_Type := Default) is use type Thin.Int; Win_Bits : Thin.Int := Thin.Int (Window_Bits); procedure Check_Version; -- Check the latest header types compatibility. procedure Check_Version is begin if Version <= "1.1.4" then Raise_Error ("Inflate header type " & Header_Type'Image (Header) & " incompatible with ZLib version " & Version); end if; end Check_Version; begin case Header is when None => Check_Version; -- Inflate data without headers determined -- by negative Win_Bits. Win_Bits := -Win_Bits; when GZip => Check_Version; -- Inflate gzip data defined by flag 16. Win_Bits := Win_Bits + 16; when Auto => Check_Version; -- Inflate with automatic detection -- of gzip or native header defined by flag 32. Win_Bits := Win_Bits + 32; when Default => null; end case; Filter.Strm := new Z_Stream; Filter.Compression := False; Filter.Stream_End := False; Filter.Opened := True; Filter.Header := Header; if Thin.Inflate_Init (To_Thin_Access (Filter.Strm), Win_Bits) /= Thin.Z_OK then Raise_Error (Filter.Strm.all); end if; end Inflate_Init; ----------------- -- Raise_Error -- ----------------- procedure Raise_Error (Message : String) is begin Ada.Exceptions.Raise_Exception (ZLib_Error'Identity, Message); end Raise_Error; procedure Raise_Error (Stream : Z_Stream) is begin Raise_Error (Last_Error_Message (Stream)); end Raise_Error; ---------- -- Read -- ---------- procedure Read (Filter : in out Filter_Type; Item : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is In_Last : Stream_Element_Offset; Item_First : Ada.Streams.Stream_Element_Offset := Item'First; begin pragma Assert (Rest_First in Buffer'First .. Buffer'Last + 1); loop if Rest_First > Buffer'Last then Read (Buffer, Rest_Last); Rest_First := Buffer'First; end if; pragma Assert (Rest_Last in Buffer'First - 1 .. Buffer'Last); Translate (Filter => Filter, In_Data => Buffer (Rest_First .. Rest_Last), In_Last => In_Last, Out_Data => Item (Item_First .. Item'Last), Out_Last => Last, Flush => Flush_Finish (Rest_Last < Rest_First)); Rest_First := In_Last + 1; exit when Last = Item'Last or else Stream_End (Filter); Item_First := Last + 1; end loop; end Read; ---------------- -- Stream_End -- ---------------- function Stream_End (Filter : in Filter_Type) return Boolean is begin if Filter.Header = GZip and Filter.Compression then return Filter.Stream_End and then Filter.Offset = Footer_Array'Last + 1; else return Filter.Stream_End; end if; end Stream_End; -------------- -- Total_In -- -------------- function Total_In (Filter : in Filter_Type) return Count is begin return Count (Thin.Total_In (To_Thin_Access (Filter.Strm).all)); end Total_In; --------------- -- Total_Out -- --------------- function Total_Out (Filter : in Filter_Type) return Count is begin return Count (Thin.Total_Out (To_Thin_Access (Filter.Strm).all)); end Total_Out; --------------- -- Translate -- --------------- 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) is begin if Filter.Header = GZip and then Filter.Compression then Translate_GZip (Filter => Filter, In_Data => In_Data, In_Last => In_Last, Out_Data => Out_Data, Out_Last => Out_Last, Flush => Flush); else Translate_Auto (Filter => Filter, In_Data => In_Data, In_Last => In_Last, Out_Data => Out_Data, Out_Last => Out_Last, Flush => Flush); end if; end Translate; -------------------- -- Translate_Auto -- -------------------- procedure Translate_Auto (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) is use type Thin.Int; Code : Thin.Int; begin if Filter.Opened = False then raise ZLib_Error; end if; if Out_Data'Length = 0 then raise Constraint_Error; end if; Set_Out (Filter.Strm.all, Out_Data'Address, Out_Data'Length); Set_In (Filter.Strm.all, In_Data'Address, In_Data'Length); Code := Flate (Filter.Compression).Step (To_Thin_Access (Filter.Strm), Thin.Int (Flush)); if Code = Thin.Z_STREAM_END then Filter.Stream_End := True; else Check_Error (Filter.Strm.all, Code); end if; In_Last := In_Data'Last - Stream_Element_Offset (Avail_In (Filter.Strm.all)); Out_Last := Out_Data'Last - Stream_Element_Offset (Avail_Out (Filter.Strm.all)); end Translate_Auto; -------------------- -- Translate_GZip -- -------------------- procedure Translate_GZip (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) is Out_First : Stream_Element_Offset; procedure Add_Data (Data : in Stream_Element_Array); -- Add data to stream from the Filter.Offset till necessary, -- used for add gzip headr/footer. procedure Put_32 (Item : in out Stream_Element_Array; Data : in Unsigned_32); pragma Inline (Put_32); -------------- -- Add_Data -- -------------- procedure Add_Data (Data : in Stream_Element_Array) is Data_First : Stream_Element_Offset renames Filter.Offset; Data_Last : Stream_Element_Offset; Data_Len : Stream_Element_Offset; -- -1 Out_Len : Stream_Element_Offset; -- -1 begin Out_First := Out_Last + 1; if Data_First > Data'Last then return; end if; Data_Len := Data'Last - Data_First; Out_Len := Out_Data'Last - Out_First; if Data_Len <= Out_Len then Out_Last := Out_First + Data_Len; Data_Last := Data'Last; else Out_Last := Out_Data'Last; Data_Last := Data_First + Out_Len; end if; Out_Data (Out_First .. Out_Last) := Data (Data_First .. Data_Last); Data_First := Data_Last + 1; Out_First := Out_Last + 1; end Add_Data; ------------ -- Put_32 -- ------------ procedure Put_32 (Item : in out Stream_Element_Array; Data : in Unsigned_32) is D : Unsigned_32 := Data; begin for J in Item'First .. Item'First + 3 loop Item (J) := Stream_Element (D and 16#FF#); D := Shift_Right (D, 8); end loop; end Put_32; begin Out_Last := Out_Data'First - 1; if not Filter.Stream_End then Add_Data (Simple_GZip_Header); Translate_Auto (Filter => Filter, In_Data => In_Data, In_Last => In_Last, Out_Data => Out_Data (Out_First .. Out_Data'Last), Out_Last => Out_Last, Flush => Flush); CRC32 (Filter.CRC, In_Data (In_Data'First .. In_Last)); end if; if Filter.Stream_End and then Out_Last <= Out_Data'Last then -- This detection method would work only when -- Simple_GZip_Header'Last > Footer_Array'Last if Filter.Offset = Simple_GZip_Header'Last + 1 then Filter.Offset := Footer_Array'First; end if; declare Footer : Footer_Array; begin Put_32 (Footer, Filter.CRC); Put_32 (Footer (Footer'First + 4 .. Footer'Last), Unsigned_32 (Total_In (Filter))); Add_Data (Footer); end; end if; end Translate_GZip; ------------- -- Version -- ------------- function Version return String is begin return Interfaces.C.Strings.Value (Thin.zlibVersion); end Version; ----------- -- Write -- ----------- procedure Write (Filter : in out Filter_Type; Item : in Ada.Streams.Stream_Element_Array; Flush : in Flush_Mode) is Buffer : Stream_Element_Array (1 .. Buffer_Size); In_Last, Out_Last : Stream_Element_Offset; In_First : Stream_Element_Offset := Item'First; begin if Item'Length = 0 and Flush = No_Flush then return; end if; loop Translate (Filter => Filter, In_Data => Item (In_First .. Item'Last), In_Last => In_Last, Out_Data => Buffer, Out_Last => Out_Last, Flush => Flush); if Out_Last >= Buffer'First then Write (Buffer (1 .. Out_Last)); end if; exit when In_Last = Item'Last or Stream_End (Filter); In_First := In_Last + 1; end loop; end Write; end ZLib;
onox/orka
Ada
1,525
ads
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2016 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. package Orka.SIMD.SSE2.Doubles.Math is pragma Pure; function Min (Left, Right : m128d) return m128d with Import, Convention => Intrinsic, External_Name => "__builtin_ia32_minpd"; -- Compare each 64-bit double in Left and Right and take the minimum values. -- -- Result (I) := Double'Min (Left (I), Right (I)) for I in 1 ..4 function Max (Left, Right : m128d) return m128d with Import, Convention => Intrinsic, External_Name => "__builtin_ia32_maxpd"; -- Compare each 64-bit double in Left and Right and take the maximum values. -- -- Result (I) := Double'Max (Left (I), Right (I)) for I in 1 ..4 function Sqrt (Elements : m128d) return m128d with Import, Convention => Intrinsic, External_Name => "__builtin_ia32_sqrtpd"; -- Return the square root (Sqrt(X)) of each element end Orka.SIMD.SSE2.Doubles.Math;
adamnemecek/GA_Ada
Ada
1,813
ads
with GL.Types.Colors; with GL.Objects.Programs; with GA_Draw; with GA_Maths; with Multivector; package E2GA_Draw is -- procedure Draw (X : E2GA.Multivector, Method : Integer := 0; -- Palet : Integer'access := null); -- Method is dependent on what 'X' represents. -- It is forwarded to drawVector, drawBivector, drawTrivector. -- Currently, 'method' is some integer in range [0, n), where each -- integer indicates a different way of drawing the multivector. -- Palet can be used to specify foreground, background and outline color. -- Uses g_drawState for some extra flags or allow DrawState to be -- passed as an argument (and also integrate 'Palet') -- Each procedure Draw implements a separate case of the draw in e2ga_Draw.cpp procedure Draw (Render_Program : GL.Objects.Programs.Program; Model_View_Matrix : GL.Types.Singles.Matrix4; MV : in out Multivector.Multivector; Method : GA_Draw.Bivector_Method_Type := GA_Draw.Draw_Bivector_Circle; Colour : GL.Types.Colors.Color := (0.0, 0.5, 0.5, 1.0)); procedure Draw_Bivector (Render_Program : GL.Objects.Programs.Program; Translation_Matrix : GL.Types.Singles.Matrix4; BV : Multivector.Bivector; Colour : GL.Types.Colors.Color; Method_Type : GA_Draw.Bivector_Method_Type := GA_Draw.Draw_Bivector_Circle); procedure Draw_Vector (Render_Program : GL.Objects.Programs.Program; Model_View_Matrix : GL.Types.Singles.Matrix4; Direction : Multivector.Vector; Colour : GL.Types.Colors.Color; Scale : float := 1.0); end E2GA_Draw;
zhmu/ananas
Ada
6,246
adb
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- S Y S T E M . P A C K _ 0 3 -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2022, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with System.Storage_Elements; with System.Unsigned_Types; package body System.Pack_03 is subtype Bit_Order is System.Bit_Order; Reverse_Bit_Order : constant Bit_Order := Bit_Order'Val (1 - Bit_Order'Pos (System.Default_Bit_Order)); subtype Ofs is System.Storage_Elements.Storage_Offset; subtype Uns is System.Unsigned_Types.Unsigned; subtype N07 is System.Unsigned_Types.Unsigned range 0 .. 7; use type System.Storage_Elements.Storage_Offset; use type System.Unsigned_Types.Unsigned; type Cluster is record E0, E1, E2, E3, E4, E5, E6, E7 : Bits_03; end record; for Cluster use record E0 at 0 range 0 * Bits .. 0 * Bits + Bits - 1; E1 at 0 range 1 * Bits .. 1 * Bits + Bits - 1; E2 at 0 range 2 * Bits .. 2 * Bits + Bits - 1; E3 at 0 range 3 * Bits .. 3 * Bits + Bits - 1; E4 at 0 range 4 * Bits .. 4 * Bits + Bits - 1; E5 at 0 range 5 * Bits .. 5 * Bits + Bits - 1; E6 at 0 range 6 * Bits .. 6 * Bits + Bits - 1; E7 at 0 range 7 * Bits .. 7 * Bits + Bits - 1; end record; for Cluster'Size use Bits * 8; for Cluster'Alignment use Integer'Min (Standard'Maximum_Alignment, 1 + 1 * Boolean'Pos (Bits mod 2 = 0) + 2 * Boolean'Pos (Bits mod 4 = 0)); -- Use maximum possible alignment, given the bit field size, since this -- will result in the most efficient code possible for the field. type Cluster_Ref is access Cluster; type Rev_Cluster is new Cluster with Bit_Order => Reverse_Bit_Order, Scalar_Storage_Order => Reverse_Bit_Order; type Rev_Cluster_Ref is access Rev_Cluster; ------------ -- Get_03 -- ------------ function Get_03 (Arr : System.Address; N : Natural; Rev_SSO : Boolean) return Bits_03 is A : constant System.Address := Arr + Bits * Ofs (Uns (N) / 8); C : Cluster_Ref with Address => A'Address, Import; RC : Rev_Cluster_Ref with Address => A'Address, Import; begin if Rev_SSO then case N07 (Uns (N) mod 8) is when 0 => return RC.E0; when 1 => return RC.E1; when 2 => return RC.E2; when 3 => return RC.E3; when 4 => return RC.E4; when 5 => return RC.E5; when 6 => return RC.E6; when 7 => return RC.E7; end case; else case N07 (Uns (N) mod 8) is when 0 => return C.E0; when 1 => return C.E1; when 2 => return C.E2; when 3 => return C.E3; when 4 => return C.E4; when 5 => return C.E5; when 6 => return C.E6; when 7 => return C.E7; end case; end if; end Get_03; ------------ -- Set_03 -- ------------ procedure Set_03 (Arr : System.Address; N : Natural; E : Bits_03; Rev_SSO : Boolean) is A : constant System.Address := Arr + Bits * Ofs (Uns (N) / 8); C : Cluster_Ref with Address => A'Address, Import; RC : Rev_Cluster_Ref with Address => A'Address, Import; begin if Rev_SSO then case N07 (Uns (N) mod 8) is when 0 => RC.E0 := E; when 1 => RC.E1 := E; when 2 => RC.E2 := E; when 3 => RC.E3 := E; when 4 => RC.E4 := E; when 5 => RC.E5 := E; when 6 => RC.E6 := E; when 7 => RC.E7 := E; end case; else case N07 (Uns (N) mod 8) is when 0 => C.E0 := E; when 1 => C.E1 := E; when 2 => C.E2 := E; when 3 => C.E3 := E; when 4 => C.E4 := E; when 5 => C.E5 := E; when 6 => C.E6 := E; when 7 => C.E7 := E; end case; end if; end Set_03; end System.Pack_03;
onox/orka
Ada
956
adb
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2016 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. package body Orka.SIMD.SSE2.Doubles.Compare is function Is_True (Elements : m128d; Position : Index_2D) return Boolean is begin return Elements (Position) /= 0.0; exception when Constraint_Error => return True; end Is_True; end Orka.SIMD.SSE2.Doubles.Compare;
reznikmm/matreshka
Ada
4,631
adb
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- 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 Matreshka.DOM_Documents; with Matreshka.ODF_String_Constants; with ODF.DOM.Iterators; with ODF.DOM.Visitors; package body Matreshka.ODF_Dr3d.Edge_Rounding_Attributes is ------------ -- Create -- ------------ overriding function Create (Parameters : not null access Matreshka.DOM_Attributes.Attribute_L2_Parameters) return Dr3d_Edge_Rounding_Attribute_Node is begin return Self : Dr3d_Edge_Rounding_Attribute_Node do Matreshka.ODF_Dr3d.Constructors.Initialize (Self'Unchecked_Access, Parameters.Document, Matreshka.ODF_String_Constants.Dr3d_Prefix); end return; end Create; -------------------- -- Get_Local_Name -- -------------------- overriding function Get_Local_Name (Self : not null access constant Dr3d_Edge_Rounding_Attribute_Node) return League.Strings.Universal_String is pragma Unreferenced (Self); begin return Matreshka.ODF_String_Constants.Edge_Rounding_Attribute; end Get_Local_Name; begin Matreshka.DOM_Documents.Register_Attribute (Matreshka.ODF_String_Constants.Dr3d_URI, Matreshka.ODF_String_Constants.Edge_Rounding_Attribute, Dr3d_Edge_Rounding_Attribute_Node'Tag); end Matreshka.ODF_Dr3d.Edge_Rounding_Attributes;
melwyncarlo/ProjectEuler
Ada
1,310
adb
with Ada.Integer_Text_IO; with Ada.Numerics.Elementary_Functions; -- Copyright 2021 Melwyn Francis Carlo procedure A044 is use Ada.Integer_Text_IO; use Ada.Numerics.Elementary_Functions; Max_N : constant Integer := 5E3; Min_Pd : Integer := 1E7; P1, P2, P1pp2, P1mp2 : Integer; Sqrt_term : Float; begin for I in 1 .. Max_N loop P1 := Integer (Float'Floor (0.5E0 * Float (I) * ((3.0E0 * Float (I)) - 1.0E0))); for J in (I + 1) .. Max_N loop P2 := Integer (Float'Floor ((0.5E0 * Float (J) * ((3.0E0 * Float (J)) - 1.0E0)))); P1pp2 := P1 + P2; Sqrt_term := Sqrt (1.0E0 + (24.0E0 * Float (P1pp2))); if Sqrt_term = Float'Floor (Sqrt_term) then if ((Integer (Sqrt_term) + 1) mod 6) = 0 then P1mp2 := P2 - P1; Sqrt_term := Sqrt (1.0E0 + (24.0E0 * Float (P1mp2))); if Sqrt_term = Float'Floor (Sqrt_term) then if ((Integer (Sqrt_term) + 1) mod 6) = 0 then if P1mp2 < Min_Pd then Min_Pd := P1mp2; end if; end if; end if; end if; end if; end loop; end loop; Put (Min_Pd, Width => 0); end A044;
reznikmm/matreshka
Ada
4,009
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Web Framework -- -- -- -- Tools Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2015-2018, Vadim Godunko <[email protected]> -- -- 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 Asis; with Engines.Contexts; with League.Strings; package Properties.Declarations.Private_Type is function Initialize (Engine : access Engines.Contexts.Context; Element : Asis.Declaration; Name : Engines.Text_Property) return League.Strings.Universal_String; function Is_Simple_Type (Engine : access Engines.Contexts.Context; Element : Asis.Declaration; Name : Engines.Boolean_Property) return Boolean; function Alignment (Engine : access Engines.Contexts.Context; Element : Asis.Declaration; Name : Engines.Integer_Property) return Integer; end Properties.Declarations.Private_Type;
reznikmm/matreshka
Ada
5,820
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Ada Modeling Framework -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2011-2012, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ -- This file is generated, don't edit it. ------------------------------------------------------------------------------ -- ActivityGroup is an abstract class for defining sets of nodes and edges in -- an activity. ------------------------------------------------------------------------------ limited with AMF.UML.Activities; limited with AMF.UML.Activity_Edges.Collections; limited with AMF.UML.Activity_Groups.Collections; limited with AMF.UML.Activity_Nodes.Collections; with AMF.UML.Named_Elements; package AMF.UML.Activity_Groups is pragma Preelaborate; type UML_Activity_Group is limited interface and AMF.UML.Named_Elements.UML_Named_Element; type UML_Activity_Group_Access is access all UML_Activity_Group'Class; for UML_Activity_Group_Access'Storage_Size use 0; not overriding function Get_Contained_Edge (Self : not null access constant UML_Activity_Group) return AMF.UML.Activity_Edges.Collections.Set_Of_UML_Activity_Edge is abstract; -- Getter of ActivityGroup::containedEdge. -- -- Edges immediately contained in the group. not overriding function Get_Contained_Node (Self : not null access constant UML_Activity_Group) return AMF.UML.Activity_Nodes.Collections.Set_Of_UML_Activity_Node is abstract; -- Getter of ActivityGroup::containedNode. -- -- Nodes immediately contained in the group. not overriding function Get_In_Activity (Self : not null access constant UML_Activity_Group) return AMF.UML.Activities.UML_Activity_Access is abstract; -- Getter of ActivityGroup::inActivity. -- -- Activity containing the group. not overriding procedure Set_In_Activity (Self : not null access UML_Activity_Group; To : AMF.UML.Activities.UML_Activity_Access) is abstract; -- Setter of ActivityGroup::inActivity. -- -- Activity containing the group. not overriding function Get_Subgroup (Self : not null access constant UML_Activity_Group) return AMF.UML.Activity_Groups.Collections.Set_Of_UML_Activity_Group is abstract; -- Getter of ActivityGroup::subgroup. -- -- Groups immediately contained in the group. not overriding function Get_Super_Group (Self : not null access constant UML_Activity_Group) return AMF.UML.Activity_Groups.UML_Activity_Group_Access is abstract; -- Getter of ActivityGroup::superGroup. -- -- Group immediately containing the group. end AMF.UML.Activity_Groups;
ohenley/ada-util
Ada
7,854
adb
----------------------------------------------------------------------- -- util-listeners-tests -- Unit tests for listeners -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- 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.Measures; with Util.Test_Caller; with Util.Listeners.Observers; with Util.Listeners.Lifecycles; package body Util.Listeners.Tests is use Util.Tests; Test_Error : exception; Count : Natural := 0; package String_Observers is new Util.Listeners.Observers (String); package Integer_Observers is new Util.Listeners.Observers (Integer); type String_Listener is new String_Observers.Observer with record Expect : Ada.Strings.Unbounded.Unbounded_String; end record; overriding procedure Update (Listener : in String_Listener; Item : in String); type Integer_Listener is new Integer_Observers.Observer with record Expect : Integer; end record; overriding procedure Update (Listener : in Integer_Listener; Item : in Integer); package Caller is new Util.Test_Caller (Test, "Listeners"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Listeners.Publish", Test_Publish'Access); Caller.Add_Test (Suite, "Test Util.Listeners.Publish_Perf", Test_Publish_Perf'Access); Caller.Add_Test (Suite, "Test Util.Listeners.Lifecycles", Test_Lifecycles'Access); end Add_Tests; overriding procedure Update (Listener : in String_Listener; Item : in String) is use type Ada.Strings.Unbounded.Unbounded_String; begin if Item /= Listener.Expect then raise Test_Error; end if; Count := Count + 1; end Update; overriding procedure Update (Listener : in Integer_Listener; Item : in Integer) is use type Ada.Strings.Unbounded.Unbounded_String; begin if Item /= Listener.Expect then raise Test_Error; end if; Count := Count + 1; end Update; -- ------------------------------ -- Test the listeners and the publish operation. -- ------------------------------ procedure Test_Publish (T : in out Test) is Listeners : Util.Listeners.List; L1 : aliased String_Listener; L2 : aliased Integer_Listener; L3 : aliased Integer_Listener; begin Listeners.Append (L1'Unchecked_Access); Listeners.Append (L2'Unchecked_Access); Listeners.Append (L3'Unchecked_Access); L1.Expect := Ada.Strings.Unbounded.To_Unbounded_String ("Hello"); String_Observers.Notify (Listeners, "Hello"); Util.Tests.Assert_Equals (T, 1, Count, "Invalid number of calls"); L2.Expect := 3; L3.Expect := 3; Integer_Observers.Notify (Listeners, 3); end Test_Publish; -- ------------------------------ -- Performance test for the listeners. -- ------------------------------ procedure Test_Publish_Perf (T : in out Test) is procedure Test_Basic (Item : in Integer); Listeners : Util.Listeners.List; L1 : aliased Integer_Listener; procedure Test_Basic (Item : in Integer) is begin Util.Tests.Assert_Equals (T, 3, Item); end Test_Basic; begin Listeners.Append (L1'Unchecked_Access); L1.Expect := 3; declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop Integer_Observers.Notify (Listeners, 3); end loop; Util.Measures.Report (S, "Observers.Notify", 1000); end; declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop Test_Basic (3); end loop; Util.Measures.Report (S, "Call basic procedure", 1000); end; end Test_Publish_Perf; -- ------------------------------ -- Test the lifecycles listener. -- ------------------------------ procedure Test_Lifecycles (T : in out Test) is package TL is new Util.Listeners.Lifecycles (Util.Measures.Stamp); Create_Count : Natural := 0; Update_Count : Natural := 0; Delete_Count : Natural := 0; type Listener is new TL.Listener with null record; -- The `On_Create` procedure is called by `Notify_Create` to notify the creation -- of the item. overriding procedure On_Create (Instance : in Listener; Item : in Util.Measures.Stamp); -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the item. overriding procedure On_Update (Instance : in Listener; Item : in Util.Measures.Stamp); -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion -- of the item. overriding procedure On_Delete (Instance : in Listener; Item : in Util.Measures.Stamp); -- ------------------------------ -- The `On_Create` procedure is called by `Notify_Create` to notify the creation -- of the item. -- ------------------------------ overriding procedure On_Create (Instance : in Listener; Item : in Util.Measures.Stamp) is pragma Unreferenced (Instance, Item); begin Create_Count := Create_Count + 1; end On_Create; -- ------------------------------ -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the item. -- ------------------------------ overriding procedure On_Update (Instance : in Listener; Item : in Util.Measures.Stamp) is pragma Unreferenced (Instance, Item); begin Update_Count := Update_Count + 1; end On_Update; -- ------------------------------ -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion -- of the item. -- ------------------------------ overriding procedure On_Delete (Instance : in Listener; Item : in Util.Measures.Stamp) is pragma Unreferenced (Instance, Item); begin Delete_Count := Delete_Count + 1; end On_Delete; Listeners : Util.Listeners.List; L1 : aliased Integer_Listener; L2 : aliased Listener; begin Listeners.Append (L1'Unchecked_Access); Listeners.Append (L2'Unchecked_Access); declare S : Util.Measures.Stamp; begin TL.Notify_Create (Listeners, S); TL.Notify_Update (Listeners, S); TL.Notify_Delete (Listeners, S); Util.Measures.Report (S, "Notify Create, Update, Delete"); end; Util.Tests.Assert_Equals (T, 1, Create_Count, "On_Create not called"); Util.Tests.Assert_Equals (T, 1, Update_Count, "On_Update not called"); Util.Tests.Assert_Equals (T, 1, Delete_Count, "On_Delete not called"); end Test_Lifecycles; end Util.Listeners.Tests;
Kidev/Ada_Drivers_Library
Ada
4,993
adb
with Ada.Text_IO; use Ada.Text_IO; with Test_Directories; with File_Block_Drivers; use File_Block_Drivers; with File_IO; use File_IO; with Filesystem.FAT; use Filesystem.FAT; with HAL.Filesystem; use HAL.Filesystem; with Compare_Files; procedure TC_FAT_Read is function Check_Dir (Dirname : String) return Boolean; function Check_File (Basename : String; Dirname : String) return Boolean; function Check_Expected_Number return Boolean; Number_Of_Files_Checked : Natural := 0; --------------- -- Check_Dir -- --------------- function Check_Dir (Dirname : String) return Boolean is DD : Directory_Descriptor; Status : File_IO.Status_Code; begin Put_Line ("Checking directory: '" & Dirname & "'"); Status := Open (DD, Dirname); if Status /= OK then Put_Line ("Cannot open directory: '" & Dirname & "'"); Put_Line ("Status: " & Status'Img); return False; end if; loop declare Ent : constant Directory_Entry := Read (DD); begin if Ent /= Invalid_Dir_Entry then if Ent.Name = "." or else Ent.Name = ".." then null; -- do nothing elsif Ent.Subdirectory then if not Check_Dir (Dirname & "/" & Ent.Name) then return False; end if; elsif not Ent.Symlink then if not Check_File (Ent.Name, Dirname) then return False; end if; end if; else exit; end if; end; end loop; return True; end Check_Dir; ---------------- -- Check_File -- ---------------- function Check_File (Basename : String; Dirname : String) return Boolean is FD : File_Descriptor; Status : File_IO.Status_Code; Path : constant String := Dirname & "/" & Basename; begin Status := Open (FD, Path, Read_Only); if Status /= OK then Put_Line ("Cannot open file: '" & Path & "'"); Put_Line ("Status: " & Status'Img); return False; end if; declare Hash_Str : constant String := Compare_Files.Compute_Hash (FD); begin if Hash_Str /= Basename then Put_Line ("Error: Hash is different than filename"); return False; else Number_Of_Files_Checked := Number_Of_Files_Checked + 1; return True; end if; end; end Check_File; --------------------------- -- Check_Expected_Number -- --------------------------- function Check_Expected_Number return Boolean is FD : File_Descriptor; Status : File_IO.Status_Code; Path : constant String := "/disk_img/number_of_files_to_check"; C : Character; Amount : File_IO.File_Size; begin Status := Open (FD, Path, Read_Only); if Status /= OK then Put_Line ("Cannot open file: '" & Path & "'"); Put_Line ("Status: " & Status'Img); return False; end if; Amount := 1; if Read (FD, C'Address, Amount) /= Amount then Put_Line ("Cannot read file: '" & Path & "'"); Put_Line ("Status: " & Status'Img); return False; end if; if C in '0' .. '9' and then Number_Of_Files_Checked = (Character'Pos (C) - Character'Pos ('0')) then return True; else Put_Line ("Incorrect number of files"); return False; end if; end Check_Expected_Number; Disk_Img_Path : constant String := "/test_dir/fat.fs"; Disk : aliased File_Block_Driver; FAT_FS : access FAT_Filesystem; FIO_Status : File_IO.Status_Code; HALFS_Status : HAL.Filesystem.Status_Code; begin Test_Directories.Mount_Test_Directory ("test_dir"); FIO_Status := Disk.Open (Disk_Img_Path, Read_Only); if FIO_Status /= OK then Put_Line ("Cannot open disk image '" & Disk_Img_Path & "': " & FIO_Status'Img); return; end if; FAT_FS := new FAT_Filesystem; HALFS_Status := Open (Controller => Disk'Unchecked_Access, LBA => 0, FS => FAT_FS.all); if HALFS_Status /= OK then Put_Line ("Cannot open FAT FS - Status:" & HALFS_Status'Img); return; end if; FIO_Status := File_IO.Mount_Volume (Mount_Point => "disk_img", FS => FAT_FS); if FIO_Status /= OK then Put_Line ("Cannot mount volume - Status: " & FIO_Status'Img); return; end if; if Check_Dir ("/disk_img/read_test") and then Check_Expected_Number then Put_Line ("PASS"); else Put_Line ("FAIL"); end if; end TC_FAT_Read;
persan/a-cups
Ada
28,263
ads
pragma Ada_2005; pragma Style_Checks (Off); with Interfaces.C; use Interfaces.C; with CUPS.stdint_h; with CUPS.bits_sockaddr_h; with CUPS.bits_socket_h; with System; with CUPS.unistd_h; private package CUPS.netinet_in_h is -- unsupported macro: IPPROTO_IP IPPROTO_IP -- unsupported macro: IPPROTO_ICMP IPPROTO_ICMP -- unsupported macro: IPPROTO_IGMP IPPROTO_IGMP -- unsupported macro: IPPROTO_IPIP IPPROTO_IPIP -- unsupported macro: IPPROTO_TCP IPPROTO_TCP -- unsupported macro: IPPROTO_EGP IPPROTO_EGP -- unsupported macro: IPPROTO_PUP IPPROTO_PUP -- unsupported macro: IPPROTO_UDP IPPROTO_UDP -- unsupported macro: IPPROTO_IDP IPPROTO_IDP -- unsupported macro: IPPROTO_TP IPPROTO_TP -- unsupported macro: IPPROTO_DCCP IPPROTO_DCCP -- unsupported macro: IPPROTO_IPV6 IPPROTO_IPV6 -- unsupported macro: IPPROTO_RSVP IPPROTO_RSVP -- unsupported macro: IPPROTO_GRE IPPROTO_GRE -- unsupported macro: IPPROTO_ESP IPPROTO_ESP -- unsupported macro: IPPROTO_AH IPPROTO_AH -- unsupported macro: IPPROTO_MTP IPPROTO_MTP -- unsupported macro: IPPROTO_BEETPH IPPROTO_BEETPH -- unsupported macro: IPPROTO_ENCAP IPPROTO_ENCAP -- unsupported macro: IPPROTO_PIM IPPROTO_PIM -- unsupported macro: IPPROTO_COMP IPPROTO_COMP -- unsupported macro: IPPROTO_SCTP IPPROTO_SCTP -- unsupported macro: IPPROTO_UDPLITE IPPROTO_UDPLITE -- unsupported macro: IPPROTO_MPLS IPPROTO_MPLS -- unsupported macro: IPPROTO_RAW IPPROTO_RAW -- unsupported macro: IPPROTO_HOPOPTS IPPROTO_HOPOPTS -- unsupported macro: IPPROTO_ROUTING IPPROTO_ROUTING -- unsupported macro: IPPROTO_FRAGMENT IPPROTO_FRAGMENT -- unsupported macro: IPPROTO_ICMPV6 IPPROTO_ICMPV6 -- unsupported macro: IPPROTO_NONE IPPROTO_NONE -- unsupported macro: IPPROTO_DSTOPTS IPPROTO_DSTOPTS -- unsupported macro: IPPROTO_MH IPPROTO_MH -- arg-macro: function IN_CLASSA ((((in_addr_t)(a)) and 16#80000000#) = 0 -- return (((in_addr_t)(a)) and 16#80000000#) = 0; IN_CLASSA_NET : constant := 16#ff000000#; -- netinet/in.h:167 IN_CLASSA_NSHIFT : constant := 24; -- netinet/in.h:168 -- unsupported macro: IN_CLASSA_HOST (0xffffffff & ~IN_CLASSA_NET) IN_CLASSA_MAX : constant := 128; -- netinet/in.h:170 -- arg-macro: function IN_CLASSB ((((in_addr_t)(a)) and 16#c0000000#) = 16#80000000# -- return (((in_addr_t)(a)) and 16#c0000000#) = 16#80000000#; IN_CLASSB_NET : constant := 16#ffff0000#; -- netinet/in.h:173 IN_CLASSB_NSHIFT : constant := 16; -- netinet/in.h:174 -- unsupported macro: IN_CLASSB_HOST (0xffffffff & ~IN_CLASSB_NET) IN_CLASSB_MAX : constant := 65536; -- netinet/in.h:176 -- arg-macro: function IN_CLASSC ((((in_addr_t)(a)) and 16#e0000000#) = 16#c0000000# -- return (((in_addr_t)(a)) and 16#e0000000#) = 16#c0000000#; IN_CLASSC_NET : constant := 16#ffffff00#; -- netinet/in.h:179 IN_CLASSC_NSHIFT : constant := 8; -- netinet/in.h:180 -- unsupported macro: IN_CLASSC_HOST (0xffffffff & ~IN_CLASSC_NET) -- arg-macro: function IN_CLASSD ((((in_addr_t)(a)) and 16#f0000000#) = 16#e0000000# -- return (((in_addr_t)(a)) and 16#f0000000#) = 16#e0000000#; -- arg-macro: procedure IN_MULTICAST IN_CLASSD(a) -- IN_CLASSD(a) -- arg-macro: function IN_EXPERIMENTAL ((((in_addr_t)(a)) and 16#e0000000#) = 16#e0000000# -- return (((in_addr_t)(a)) and 16#e0000000#) = 16#e0000000#; -- arg-macro: function IN_BADCLASS ((((in_addr_t)(a)) and 16#f0000000#) = 16#f0000000# -- return (((in_addr_t)(a)) and 16#f0000000#) = 16#f0000000#; -- unsupported macro: INADDR_ANY ((in_addr_t) 0x00000000) -- unsupported macro: INADDR_BROADCAST ((in_addr_t) 0xffffffff) -- unsupported macro: INADDR_NONE ((in_addr_t) 0xffffffff) IN_LOOPBACKNET : constant := 127; -- netinet/in.h:197 -- unsupported macro: INADDR_LOOPBACK ((in_addr_t) 0x7f000001) -- unsupported macro: INADDR_UNSPEC_GROUP ((in_addr_t) 0xe0000000) -- unsupported macro: INADDR_ALLHOSTS_GROUP ((in_addr_t) 0xe0000001) -- unsupported macro: INADDR_ALLRTRS_GROUP ((in_addr_t) 0xe0000002) -- unsupported macro: INADDR_MAX_LOCAL_GROUP ((in_addr_t) 0xe00000ff) -- unsupported macro: s6_addr __in6_u.__u6_addr8 -- unsupported macro: s6_addr16 __in6_u.__u6_addr16 -- unsupported macro: s6_addr32 __in6_u.__u6_addr32 -- unsupported macro: IN6ADDR_ANY_INIT { { { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } } } -- unsupported macro: IN6ADDR_LOOPBACK_INIT { { { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1 } } } INET_ADDRSTRLEN : constant := 16; -- netinet/in.h:234 INET6_ADDRSTRLEN : constant := 46; -- netinet/in.h:235 -- arg-macro: function IP_MSFILTER_SIZE (sizeof (struct ip_msfilter) - sizeof (struct in_addr) + (numsrc) * sizeof (struct in_addr) -- return sizeof (struct ip_msfilter) - sizeof (struct in_addr) + (numsrc) * sizeof (struct in_addr); -- arg-macro: function GROUP_FILTER_SIZE (sizeof (struct group_filter) - sizeof (struct sockaddr_storage) + ((numsrc) * sizeof (struct sockaddr_storage)) -- return sizeof (struct group_filter) - sizeof (struct sockaddr_storage) + ((numsrc) * sizeof (struct sockaddr_storage)); -- arg-macro: function IN6_IS_ADDR_UNSPECIFIED (__extension__ ({ const struct in6_addr *__a := (const struct in6_addr *) (a); __a.s6_addr32(0) = 0 and then __a.s6_addr32(1) = 0 and then __a.s6_addr32(2) = 0 and then __a.s6_addr32(3) = 0; }) -- return __extension__ ({ const struct in6_addr *__a := (const struct in6_addr *) (a); __a.s6_addr32(0) = 0 and then __a.s6_addr32(1) = 0 and then __a.s6_addr32(2) = 0 and then __a.s6_addr32(3) = 0; }); -- arg-macro: function IN6_IS_ADDR_LOOPBACK (__extension__ ({ const struct in6_addr *__a := (const struct in6_addr *) (a); __a.s6_addr32(0) = 0 and then __a.s6_addr32(1) = 0 and then __a.s6_addr32(2) = 0 and then __a.s6_addr32(3) = htonl (1); }) -- return __extension__ ({ const struct in6_addr *__a := (const struct in6_addr *) (a); __a.s6_addr32(0) = 0 and then __a.s6_addr32(1) = 0 and then __a.s6_addr32(2) = 0 and then __a.s6_addr32(3) = htonl (1); }); -- arg-macro: function IN6_IS_ADDR_LINKLOCAL (__extension__ ({ const struct in6_addr *__a := (const struct in6_addr *) (a); (__a.s6_addr32(0) and htonl (16#ffc00000#)) = htonl (16#fe800000#); }) -- return __extension__ ({ const struct in6_addr *__a := (const struct in6_addr *) (a); (__a.s6_addr32(0) and htonl (16#ffc00000#)) = htonl (16#fe800000#); }); -- arg-macro: function IN6_IS_ADDR_SITELOCAL (__extension__ ({ const struct in6_addr *__a := (const struct in6_addr *) (a); (__a.s6_addr32(0) and htonl (16#ffc00000#)) = htonl (16#fec00000#); }) -- return __extension__ ({ const struct in6_addr *__a := (const struct in6_addr *) (a); (__a.s6_addr32(0) and htonl (16#ffc00000#)) = htonl (16#fec00000#); }); -- arg-macro: function IN6_IS_ADDR_V4MAPPED (__extension__ ({ const struct in6_addr *__a := (const struct in6_addr *) (a); __a.s6_addr32(0) = 0 and then __a.s6_addr32(1) = 0 and then __a.s6_addr32(2) = htonl (16#ffff#); }) -- return __extension__ ({ const struct in6_addr *__a := (const struct in6_addr *) (a); __a.s6_addr32(0) = 0 and then __a.s6_addr32(1) = 0 and then __a.s6_addr32(2) = htonl (16#ffff#); }); -- arg-macro: function IN6_IS_ADDR_V4COMPAT (__extension__ ({ const struct in6_addr *__a := (const struct in6_addr *) (a); __a.s6_addr32(0) = 0 and then __a.s6_addr32(1) = 0 and then __a.s6_addr32(2) = 0 and then ntohl (__a.s6_addr32(3)) > 1; }) -- return __extension__ ({ const struct in6_addr *__a := (const struct in6_addr *) (a); __a.s6_addr32(0) = 0 and then __a.s6_addr32(1) = 0 and then __a.s6_addr32(2) = 0 and then ntohl (__a.s6_addr32(3)) > 1; }); -- arg-macro: function IN6_ARE_ADDR_EQUAL (__extension__ ({ const struct in6_addr *__a := (const struct in6_addr *) (a); const struct in6_addr *__b := (const struct in6_addr *) (b); __a.s6_addr32(0) = __b.s6_addr32(0) and then __a.s6_addr32(1) = __b.s6_addr32(1) and then __a.s6_addr32(2) = __b.s6_addr32(2) and then __a.s6_addr32(3) = __b.s6_addr32(3); }) -- return __extension__ ({ const struct in6_addr *__a := (const struct in6_addr *) (a); const struct in6_addr *__b := (const struct in6_addr *) (b); __a.s6_addr32(0) = __b.s6_addr32(0) and then __a.s6_addr32(1) = __b.s6_addr32(1) and then __a.s6_addr32(2) = __b.s6_addr32(2) and then __a.s6_addr32(3) = __b.s6_addr32(3); }); -- arg-macro: function IN6_IS_ADDR_MULTICAST (((const uint8_t *) (a))(0) = 16#ff# -- return ((const uint8_t *) (a))(0) = 16#ff#; -- arg-macro: function IN6_IS_ADDR_MC_NODELOCAL (IN6_IS_ADDR_MULTICAST(a) and then ((((const uint8_t *) (a))(1) and 16#f#) = 16#1#) -- return IN6_IS_ADDR_MULTICAST(a) and then ((((const uint8_t *) (a))(1) and 16#f#) = 16#1#); -- arg-macro: function IN6_IS_ADDR_MC_LINKLOCAL (IN6_IS_ADDR_MULTICAST(a) and then ((((const uint8_t *) (a))(1) and 16#f#) = 16#2#) -- return IN6_IS_ADDR_MULTICAST(a) and then ((((const uint8_t *) (a))(1) and 16#f#) = 16#2#); -- arg-macro: function IN6_IS_ADDR_MC_SITELOCAL (IN6_IS_ADDR_MULTICAST(a) and then ((((const uint8_t *) (a))(1) and 16#f#) = 16#5#) -- return IN6_IS_ADDR_MULTICAST(a) and then ((((const uint8_t *) (a))(1) and 16#f#) = 16#5#); -- arg-macro: function IN6_IS_ADDR_MC_ORGLOCAL (IN6_IS_ADDR_MULTICAST(a) and then ((((const uint8_t *) (a))(1) and 16#f#) = 16#8#) -- return IN6_IS_ADDR_MULTICAST(a) and then ((((const uint8_t *) (a))(1) and 16#f#) = 16#8#); -- arg-macro: function IN6_IS_ADDR_MC_GLOBAL (IN6_IS_ADDR_MULTICAST(a) and then ((((const uint8_t *) (a))(1) and 16#f#) = 16#e#) -- return IN6_IS_ADDR_MULTICAST(a) and then ((((const uint8_t *) (a))(1) and 16#f#) = 16#e#); -- Copyright (C) 1991-2016 Free Software Foundation, Inc. -- This file is part of the GNU C Library. -- The GNU C Library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- The GNU C 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 -- Lesser General Public License for more details. -- You should have received a copy of the GNU Lesser General Public -- License along with the GNU C Library; if not, see -- <http://www.gnu.org/licenses/>. -- Internet address. subtype in_addr_t is CUPS.stdint_h.uint32_t; -- netinet/in.h:30 type in_addr is record s_addr : aliased in_addr_t; -- netinet/in.h:33 end record; pragma Convention (C_Pass_By_Copy, in_addr); -- netinet/in.h:31 -- Get system-specific definitions. -- Standard well-defined IP protocols. -- Dummy protocol for TCP. -- Internet Control Message Protocol. -- Internet Group Management Protocol. -- IPIP tunnels (older KA9Q tunnels use 94). -- Transmission Control Protocol. -- Exterior Gateway Protocol. -- PUP protocol. -- User Datagram Protocol. -- XNS IDP protocol. -- SO Transport Protocol Class 4. -- Datagram Congestion Control Protocol. -- IPv6 header. -- Reservation Protocol. -- General Routing Encapsulation. -- encapsulating security payload. -- authentication header. -- Multicast Transport Protocol. -- IP option pseudo header for BEET. -- Encapsulation Header. -- Protocol Independent Multicast. -- Compression Header Protocol. -- Stream Control Transmission Protocol. -- UDP-Lite protocol. -- MPLS in IP. -- Raw IP packets. -- If __USE_KERNEL_IPV6_DEFS is defined then the user has included the kernel -- network headers first and we should use those ABI-identical definitions -- instead of our own. -- IPv6 Hop-by-Hop options. -- IPv6 routing header. -- IPv6 fragmentation header. -- ICMPv6. -- IPv6 no next header. -- IPv6 destination options. -- IPv6 mobility header. -- Type to represent a port. subtype in_port_t is CUPS.stdint_h.uint16_t; -- netinet/in.h:119 -- Standard well-known ports. -- Echo service. -- Discard transmissions service. -- System status service. -- Time of day service. -- Network status service. -- File Transfer Protocol. -- Telnet protocol. -- Simple Mail Transfer Protocol. -- Timeserver service. -- Domain Name Service. -- Internet Whois service. -- Trivial File Transfer Protocol. -- Finger service. -- SUPDUP protocol. -- execd service. -- rlogind service. -- UDP ports. -- Ports less than this value are reserved for privileged processes. -- Ports greater this value are reserved for (non-privileged) servers. -- Definitions of the bits in an Internet address integer. -- On subnets, host and network parts are found according to -- the subnet mask, not these masks. -- Address to accept any incoming messages. -- Address to send to all hosts. -- Address indicating an error return. -- Network number for local host loopback. -- Address to loopback in software to local host. -- Defines for Multicast INADDR. -- IPv6 address type in6_addr; type in6_addr_uu_u6_addr8_array is array (0 .. 15) of aliased CUPS.stdint_h.uint8_t; type in6_addr_uu_u6_addr16_array is array (0 .. 7) of aliased CUPS.stdint_h.uint16_t; type in6_addr_uu_u6_addr32_array is array (0 .. 3) of aliased CUPS.stdint_h.uint32_t; type anon_32 (discr : unsigned := 0) is record case discr is when 0 => uu_u6_addr8 : aliased in6_addr_uu_u6_addr8_array; -- netinet/in.h:215 when 1 => uu_u6_addr16 : aliased in6_addr_uu_u6_addr16_array; -- netinet/in.h:217 when others => uu_u6_addr32 : aliased in6_addr_uu_u6_addr32_array; -- netinet/in.h:218 end case; end record; pragma Convention (C_Pass_By_Copy, anon_32); pragma Unchecked_Union (anon_32);type in6_addr is record uu_in6_u : aliased anon_32; -- netinet/in.h:220 end record; pragma Convention (C_Pass_By_Copy, in6_addr); -- netinet/in.h:211 -- :: in6addr_any : aliased in6_addr; -- netinet/in.h:229 pragma Import (C, in6addr_any, "in6addr_any"); -- ::1 in6addr_loopback : aliased in6_addr; -- netinet/in.h:230 pragma Import (C, in6addr_loopback, "in6addr_loopback"); -- Structure describing an Internet socket address. type sockaddr_in_sin_zero_array is array (0 .. 7) of aliased unsigned_char; type sockaddr_in is record sin_family : aliased CUPS.bits_sockaddr_h.sa_family_t; -- netinet/in.h:241 sin_port : aliased in_port_t; -- netinet/in.h:242 sin_addr : aliased in_addr; -- netinet/in.h:243 sin_zero : aliased sockaddr_in_sin_zero_array; -- netinet/in.h:249 end record; pragma Convention (C_Pass_By_Copy, sockaddr_in); -- netinet/in.h:239 -- Port number. -- Internet address. -- Pad to size of `struct sockaddr'. -- Ditto, for IPv6. type sockaddr_in6 is record sin6_family : aliased CUPS.bits_sockaddr_h.sa_family_t; -- netinet/in.h:256 sin6_port : aliased in_port_t; -- netinet/in.h:257 sin6_flowinfo : aliased CUPS.stdint_h.uint32_t; -- netinet/in.h:258 sin6_addr : aliased in6_addr; -- netinet/in.h:259 sin6_scope_id : aliased CUPS.stdint_h.uint32_t; -- netinet/in.h:260 end record; pragma Convention (C_Pass_By_Copy, sockaddr_in6); -- netinet/in.h:254 -- Transport layer port # -- IPv6 flow information -- IPv6 address -- IPv6 scope-id -- IPv4 multicast request. -- IP multicast address of group. type ip_mreq is record imr_multiaddr : aliased in_addr; -- netinet/in.h:269 imr_interface : aliased in_addr; -- netinet/in.h:272 end record; pragma Convention (C_Pass_By_Copy, ip_mreq); -- netinet/in.h:266 -- Local IP address of interface. -- IP multicast address of group. type ip_mreq_source is record imr_multiaddr : aliased in_addr; -- netinet/in.h:278 imr_interface : aliased in_addr; -- netinet/in.h:281 imr_sourceaddr : aliased in_addr; -- netinet/in.h:284 end record; pragma Convention (C_Pass_By_Copy, ip_mreq_source); -- netinet/in.h:275 -- IP address of source. -- IP address of interface. -- Likewise, for IPv6. -- IPv6 multicast address of group type ipv6_mreq is record ipv6mr_multiaddr : aliased in6_addr; -- netinet/in.h:293 ipv6mr_interface : aliased unsigned; -- netinet/in.h:296 end record; pragma Convention (C_Pass_By_Copy, ipv6_mreq); -- netinet/in.h:290 -- Address data. -- Structure large enough to hold any socket address (with the historical -- exception of AF_UNIX). -- Address family, etc. subtype sockaddr_storage_uu_ss_padding_array is Interfaces.C.char_array (0 .. 117); type sockaddr_storage is record ss_family : aliased CUPS.bits_sockaddr_h.sa_family_t; -- bits/socket.h:168 uu_ss_padding : aliased sockaddr_storage_uu_ss_padding_array; -- bits/socket.h:169 uu_ss_align : aliased unsigned_long; -- bits/socket.h:170 end record; pragma Convention (C_Pass_By_Copy, sockaddr_storage); -- bits/socket.h:166 -- local interface -- Multicast group request. -- Interface index. type group_req is record gr_interface : aliased CUPS.stdint_h.uint32_t; -- netinet/in.h:305 gr_group : aliased sockaddr_storage; -- netinet/in.h:308 end record; pragma Convention (C_Pass_By_Copy, group_req); -- netinet/in.h:302 -- Group address. -- Interface index. type group_source_req is record gsr_interface : aliased CUPS.stdint_h.uint32_t; -- netinet/in.h:314 gsr_group : aliased sockaddr_storage; -- netinet/in.h:317 gsr_source : aliased sockaddr_storage; -- netinet/in.h:320 end record; pragma Convention (C_Pass_By_Copy, group_source_req); -- netinet/in.h:311 -- Group address. -- Source address. -- Full-state filter operations. -- IP multicast address of group. type ip_msfilter_imsf_slist_array is array (0 .. 0) of aliased in_addr; type ip_msfilter is record imsf_multiaddr : aliased in_addr; -- netinet/in.h:328 imsf_interface : aliased in_addr; -- netinet/in.h:331 imsf_fmode : aliased CUPS.stdint_h.uint32_t; -- netinet/in.h:334 imsf_numsrc : aliased CUPS.stdint_h.uint32_t; -- netinet/in.h:337 imsf_slist : aliased ip_msfilter_imsf_slist_array; -- netinet/in.h:339 end record; pragma Convention (C_Pass_By_Copy, ip_msfilter); -- netinet/in.h:325 -- Local IP address of interface. -- Filter mode. -- Number of source addresses. -- Source addresses. -- Interface index. type group_filter_gf_slist_array is array (0 .. 0) of aliased sockaddr_storage; type group_filter is record gf_interface : aliased CUPS.stdint_h.uint32_t; -- netinet/in.h:349 gf_group : aliased sockaddr_storage; -- netinet/in.h:352 gf_fmode : aliased CUPS.stdint_h.uint32_t; -- netinet/in.h:355 gf_numsrc : aliased CUPS.stdint_h.uint32_t; -- netinet/in.h:358 gf_slist : aliased group_filter_gf_slist_array; -- netinet/in.h:360 end record; pragma Convention (C_Pass_By_Copy, group_filter); -- netinet/in.h:346 -- Group address. -- Filter mode. -- Number of source addresses. -- Source addresses. -- Functions to convert between host and network byte order. -- Please note that these functions normally take `unsigned long int' or -- `unsigned short int' values as arguments and also return them. But -- this was a short-sighted decision since on different systems the types -- may have different representations but the values are always the same. function ntohl (uu_netlong : CUPS.stdint_h.uint32_t) return CUPS.stdint_h.uint32_t; -- netinet/in.h:376 pragma Import (C, ntohl, "ntohl"); function ntohs (uu_netshort : CUPS.stdint_h.uint16_t) return CUPS.stdint_h.uint16_t; -- netinet/in.h:377 pragma Import (C, ntohs, "ntohs"); function htonl (uu_hostlong : CUPS.stdint_h.uint32_t) return CUPS.stdint_h.uint32_t; -- netinet/in.h:379 pragma Import (C, htonl, "htonl"); function htons (uu_hostshort : CUPS.stdint_h.uint16_t) return CUPS.stdint_h.uint16_t; -- netinet/in.h:381 pragma Import (C, htons, "htons"); -- Get machine dependent optimized versions of byte swapping functions. -- We can optimize calls to the conversion functions. Either nothing has -- to be done or we are using directly the byte-swapping functions which -- often can be inlined. -- The host byte order is the same as network byte order, -- so these functions are all just identity. -- Bind socket to a privileged IP port. function bindresvport (uu_sockfd : int; uu_sock_in : access sockaddr_in) return int; -- netinet/in.h:503 pragma Import (C, bindresvport, "bindresvport"); -- The IPv6 version of this function. function bindresvport6 (uu_sockfd : int; uu_sock_in : access sockaddr_in6) return int; -- netinet/in.h:506 pragma Import (C, bindresvport6, "bindresvport6"); -- Forward declaration. -- IPv6 packet information. -- src/dst IPv6 address type in6_pktinfo is record ipi6_addr : aliased in6_addr; -- netinet/in.h:539 ipi6_ifindex : aliased unsigned; -- netinet/in.h:540 end record; pragma Convention (C_Pass_By_Copy, in6_pktinfo); -- netinet/in.h:537 -- send/recv interface index -- IPv6 MTU information. -- dst address including zone ID type ip6_mtuinfo is record ip6m_addr : aliased sockaddr_in6; -- netinet/in.h:546 ip6m_mtu : aliased CUPS.stdint_h.uint32_t; -- netinet/in.h:547 end record; pragma Convention (C_Pass_By_Copy, ip6_mtuinfo); -- netinet/in.h:544 -- path MTU in host byte order -- Obsolete hop-by-hop and Destination Options Processing (RFC 2292). function inet6_option_space (uu_nbytes : int) return int; -- netinet/in.h:552 pragma Import (C, inet6_option_space, "inet6_option_space"); function inet6_option_init (uu_bp : System.Address; uu_cmsgp : System.Address; uu_type : int) return int; -- netinet/in.h:554 pragma Import (C, inet6_option_init, "inet6_option_init"); function inet6_option_append (uu_cmsg : access CUPS.bits_socket_h.cmsghdr; uu_typep : access CUPS.stdint_h.uint8_t; uu_multx : int; uu_plusy : int) return int; -- netinet/in.h:556 pragma Import (C, inet6_option_append, "inet6_option_append"); function inet6_option_alloc (uu_cmsg : access CUPS.bits_socket_h.cmsghdr; uu_datalen : int; uu_multx : int; uu_plusy : int) return access CUPS.stdint_h.uint8_t; -- netinet/in.h:559 pragma Import (C, inet6_option_alloc, "inet6_option_alloc"); function inet6_option_next (uu_cmsg : access constant CUPS.bits_socket_h.cmsghdr; uu_tptrp : System.Address) return int; -- netinet/in.h:562 pragma Import (C, inet6_option_next, "inet6_option_next"); function inet6_option_find (uu_cmsg : access constant CUPS.bits_socket_h.cmsghdr; uu_tptrp : System.Address; uu_type : int) return int; -- netinet/in.h:565 pragma Import (C, inet6_option_find, "inet6_option_find"); -- Hop-by-Hop and Destination Options Processing (RFC 3542). function inet6_opt_init (uu_extbuf : System.Address; uu_extlen : CUPS.unistd_h.socklen_t) return int; -- netinet/in.h:571 pragma Import (C, inet6_opt_init, "inet6_opt_init"); function inet6_opt_append (uu_extbuf : System.Address; uu_extlen : CUPS.unistd_h.socklen_t; uu_offset : int; uu_type : CUPS.stdint_h.uint8_t; uu_len : CUPS.unistd_h.socklen_t; uu_align : CUPS.stdint_h.uint8_t; uu_databufp : System.Address) return int; -- netinet/in.h:572 pragma Import (C, inet6_opt_append, "inet6_opt_append"); function inet6_opt_finish (uu_extbuf : System.Address; uu_extlen : CUPS.unistd_h.socklen_t; uu_offset : int) return int; -- netinet/in.h:575 pragma Import (C, inet6_opt_finish, "inet6_opt_finish"); function inet6_opt_set_val (uu_databuf : System.Address; uu_offset : int; uu_val : System.Address; uu_vallen : CUPS.unistd_h.socklen_t) return int; -- netinet/in.h:577 pragma Import (C, inet6_opt_set_val, "inet6_opt_set_val"); function inet6_opt_next (uu_extbuf : System.Address; uu_extlen : CUPS.unistd_h.socklen_t; uu_offset : int; uu_typep : access CUPS.stdint_h.uint8_t; uu_lenp : access CUPS.unistd_h.socklen_t; uu_databufp : System.Address) return int; -- netinet/in.h:579 pragma Import (C, inet6_opt_next, "inet6_opt_next"); function inet6_opt_find (uu_extbuf : System.Address; uu_extlen : CUPS.unistd_h.socklen_t; uu_offset : int; uu_type : CUPS.stdint_h.uint8_t; uu_lenp : access CUPS.unistd_h.socklen_t; uu_databufp : System.Address) return int; -- netinet/in.h:582 pragma Import (C, inet6_opt_find, "inet6_opt_find"); function inet6_opt_get_val (uu_databuf : System.Address; uu_offset : int; uu_val : System.Address; uu_vallen : CUPS.unistd_h.socklen_t) return int; -- netinet/in.h:585 pragma Import (C, inet6_opt_get_val, "inet6_opt_get_val"); -- Routing Header Option (RFC 3542). function inet6_rth_space (uu_type : int; uu_segments : int) return CUPS.unistd_h.socklen_t; -- netinet/in.h:590 pragma Import (C, inet6_rth_space, "inet6_rth_space"); function inet6_rth_init (uu_bp : System.Address; uu_bp_len : CUPS.unistd_h.socklen_t; uu_type : int; uu_segments : int) return System.Address; -- netinet/in.h:591 pragma Import (C, inet6_rth_init, "inet6_rth_init"); function inet6_rth_add (uu_bp : System.Address; uu_addr : access constant in6_addr) return int; -- netinet/in.h:593 pragma Import (C, inet6_rth_add, "inet6_rth_add"); function inet6_rth_reverse (uu_in : System.Address; uu_out : System.Address) return int; -- netinet/in.h:594 pragma Import (C, inet6_rth_reverse, "inet6_rth_reverse"); function inet6_rth_segments (uu_bp : System.Address) return int; -- netinet/in.h:595 pragma Import (C, inet6_rth_segments, "inet6_rth_segments"); function inet6_rth_getaddr (uu_bp : System.Address; uu_index : int) return access in6_addr; -- netinet/in.h:596 pragma Import (C, inet6_rth_getaddr, "inet6_rth_getaddr"); -- Multicast source filter support. -- Get IPv4 source filter. function getipv4sourcefilter (uu_s : int; uu_interface_addr : in_addr; uu_group : in_addr; uu_fmode : access CUPS.stdint_h.uint32_t; uu_numsrc : access CUPS.stdint_h.uint32_t; uu_slist : access in_addr) return int; -- netinet/in.h:603 pragma Import (C, getipv4sourcefilter, "getipv4sourcefilter"); -- Set IPv4 source filter. function setipv4sourcefilter (uu_s : int; uu_interface_addr : in_addr; uu_group : in_addr; uu_fmode : CUPS.stdint_h.uint32_t; uu_numsrc : CUPS.stdint_h.uint32_t; uu_slist : access constant in_addr) return int; -- netinet/in.h:609 pragma Import (C, setipv4sourcefilter, "setipv4sourcefilter"); -- Get source filter. function getsourcefilter (uu_s : int; uu_interface_addr : CUPS.stdint_h.uint32_t; uu_group : access constant CUPS.bits_socket_h.sockaddr; uu_grouplen : CUPS.unistd_h.socklen_t; uu_fmode : access CUPS.stdint_h.uint32_t; uu_numsrc : access CUPS.stdint_h.uint32_t; uu_slist : access sockaddr_storage) return int; -- netinet/in.h:617 pragma Import (C, getsourcefilter, "getsourcefilter"); -- Set source filter. function setsourcefilter (uu_s : int; uu_interface_addr : CUPS.stdint_h.uint32_t; uu_group : access constant CUPS.bits_socket_h.sockaddr; uu_grouplen : CUPS.unistd_h.socklen_t; uu_fmode : CUPS.stdint_h.uint32_t; uu_numsrc : CUPS.stdint_h.uint32_t; uu_slist : access constant sockaddr_storage) return int; -- netinet/in.h:624 pragma Import (C, setsourcefilter, "setsourcefilter"); end CUPS.netinet_in_h;
io7m/coreland-lua-ada-load
Ada
573
adb
with Ada.Text_IO; with Test; procedure test0002 is package IO renames Ada.Text_IO; begin Test.Init ("test0002.lua"); begin declare x : constant Long_Float := Test.Load.Named_Local (Test.Loader_Access, "x"); begin IO.Put_Line ("x: " & Long_Float'Image (x)); end; exception when Test.Load.Load_Error => IO.Put_Line (Test.Load.Error_String (Test.Loader_Access)); end; exception when Test.Load.Load_Error => IO.Put_Line ("fail: " & Test.Load.Error_String (Test.Loader_Access)); raise Test.Load.Load_Error; end test0002;
reznikmm/matreshka
Ada
4,003
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- 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 ODF.DOM.Style_Condition_Attributes; package Matreshka.ODF_Style.Condition_Attributes is type Style_Condition_Attribute_Node is new Matreshka.ODF_Style.Abstract_Style_Attribute_Node and ODF.DOM.Style_Condition_Attributes.ODF_Style_Condition_Attribute with null record; overriding function Create (Parameters : not null access Matreshka.DOM_Attributes.Attribute_L2_Parameters) return Style_Condition_Attribute_Node; overriding function Get_Local_Name (Self : not null access constant Style_Condition_Attribute_Node) return League.Strings.Universal_String; end Matreshka.ODF_Style.Condition_Attributes;
reznikmm/matreshka
Ada
3,704
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- 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 XML.DOM.Elements; package ODF.DOM.Number_Currency_Style_Elements is pragma Preelaborate; type ODF_Number_Currency_Style is limited interface and XML.DOM.Elements.DOM_Element; type ODF_Number_Currency_Style_Access is access all ODF_Number_Currency_Style'Class with Storage_Size => 0; end ODF.DOM.Number_Currency_Style_Elements;
stcarrez/babel
Ada
2,262
adb
----------------------------------------------------------------------- -- babel-files-queues -- File and directory queues -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Directories; with Ada.Containers.Vectors; with Util.Encoders.SHA1; with Util.Concurrent.Fifos; with Util.Strings.Vectors; with ADO; with Babel.Base.Models; package body Babel.Files.Queues is procedure Add_File (Into : in out File_Queue; File : in File_Type) is begin Into.Queue.Enqueue (File); end Add_File; -- ------------------------------ -- Returns true if there is a directory in the queue. -- ------------------------------ function Has_Directory (Queue : in Directory_Queue) return Boolean is begin return not Queue.Directories.Is_Empty; end Has_Directory; -- ------------------------------ -- Get the next directory from the queue. -- ------------------------------ procedure Peek_Directory (Queue : in out Directory_Queue; Directory : out Directory_Type) is begin Directory := Queue.Directories.Last_Element; Queue.Directories.Delete_Last; end Peek_Directory; -- ------------------------------ -- Add the directory in the queue. -- ------------------------------ procedure Add_Directory (Queue : in out Directory_Queue; Directory : in Directory_Type) is begin Queue.Directories.Append (Directory); end Add_Directory; end Babel.Files.Queues;
charlie5/cBound
Ada
1,755
ads
-- This file is generated by SWIG. Please do not modify by hand. -- with Interfaces; with Interfaces.C; with Interfaces.C.Pointers; package xcb.xcb_glx_get_minmax_parameteriv_request_t is -- Item -- type Item is record major_opcode : aliased Interfaces.Unsigned_8; minor_opcode : aliased Interfaces.Unsigned_8; length : aliased Interfaces.Unsigned_16; context_tag : aliased xcb.xcb_glx_context_tag_t; target : aliased Interfaces.Unsigned_32; pname : aliased Interfaces.Unsigned_32; end record; -- Item_Array -- type Item_Array is array (Interfaces.C .size_t range <>) of aliased xcb .xcb_glx_get_minmax_parameteriv_request_t .Item; -- Pointer -- package C_Pointers is new Interfaces.C.Pointers (Index => Interfaces.C.size_t, Element => xcb.xcb_glx_get_minmax_parameteriv_request_t.Item, Element_Array => xcb.xcb_glx_get_minmax_parameteriv_request_t.Item_Array, Default_Terminator => (others => <>)); subtype Pointer is C_Pointers.Pointer; -- Pointer_Array -- type Pointer_Array is array (Interfaces.C .size_t range <>) of aliased xcb .xcb_glx_get_minmax_parameteriv_request_t .Pointer; -- Pointer_Pointer -- package C_Pointer_Pointers is new Interfaces.C.Pointers (Index => Interfaces.C.size_t, Element => xcb.xcb_glx_get_minmax_parameteriv_request_t.Pointer, Element_Array => xcb.xcb_glx_get_minmax_parameteriv_request_t.Pointer_Array, Default_Terminator => null); subtype Pointer_Pointer is C_Pointer_Pointers.Pointer; end xcb.xcb_glx_get_minmax_parameteriv_request_t;
Lucretia/Cherry
Ada
5,093
adb
-- -- The author disclaims copyright to this source code. In place of -- a legal notice, here is a blessing: -- -- May you do good and not evil. -- May you find forgiveness for yourself and forgive others. -- May you share freely, not taking more than you give. -- with Ada.Text_IO; with Ada.Directories; with Setup; with Auxiliary; package body Generate_Ada is procedure Open_Template (Context : in out Context_Type; File_Name : in out Ada.Strings.Unbounded.Unbounded_String; User_Template : in String; Error_Count : in out Integer) is use Ada.Strings.Unbounded; use Ada.Text_IO; Default_Template : String renames Setup.Default_Template_Ada; Template_Name : Unbounded_String; begin Ada.Text_IO.Put_Line ("### AOT 1"); -- First, see if user specified a template filename on the command line. if User_Template /= "" then -- Eksisterer den angivede template fil if not Ada.Directories.Exists (User_Template) then Ada.Text_IO.Put_Line (Ada.Text_IO.Standard_Error, "Can not find the parser driver template file '" & User_Template & "'."); Error_Count := Error_Count + 1; Template_Name := Null_Unbounded_String; return; end if; -- Can User_Template open. begin Open (Context.File_Template, In_File, User_Template); exception when others => -- No it could not open User_Template. Put_Line (Standard_Error, "Can not open the template file '" & User_Template & "'."); Error_Count := Error_Count + 1; Template_Name := Null_Unbounded_String; return; end; return; -- User template open with success. end if; -- No user template. declare -- use Ada.Strings.Fixed; Point : constant Natural := Index (File_Name, "."); Buf : Unbounded_String; begin if Point = 0 then Buf := File_Name & ".lt"; -- Buf (Buf_0'Range) := Buf_0; Last := Buf_0'Last; else Buf := File_Name & ".lt"; -- Buf (Buf_X'Range) := Buf_X; Last := Buf_X'Last; end if; if Ada.Directories.Exists (To_String (Buf)) then Ada.Text_IO.Put_Line ("### 3-1"); Template_Name := Buf; elsif Ada.Directories.Exists (Default_Template) then Ada.Text_IO.Put_Line ("### 3-2"); Template_Name := To_Unbounded_String (Default_Template); else Ada.Text_IO.Put_Line ("### 3-3"); null; -- Template_Name := Pathsearch (Lemp.Argv0, Templatename, 0); end if; end; Ada.Text_IO.Put_Line ("### 3-4"); if Template_Name = Null_Unbounded_String then Ada.Text_IO.Put_Line ("### 3-5"); Put_Line (Standard_Error, "Can not find then parser driver template file '" & To_String (Template_Name) & "'."); Error_Count := Error_Count + 1; return; end if; begin Ada.Text_IO.Put_Line ("### 6-1"); Open (Context.File_Template, In_File, To_String (Template_Name)); Ada.Text_IO.Put_Line ("### 6-2"); exception when others => Ada.Text_IO.Put_Line ("### 3-6"); Put_Line (Standard_Error, "Can not open then template file '" & To_String (Template_Name) & "."); Error_Count := Error_Count + 1; return; end; -- Template_Name := New_String (Tem end Open_Template; procedure Generate_Spec (Context : in out Context_Type; Base_Name : in String; Module : in String; Prefix : in String; First : in Integer; Last : in Integer) is pragma Unreferenced (Context); use Auxiliary, Ada.Text_IO; -- Module : constant String := Auxiliary.To_Ada_Symbol (Base_Name); File : File_Type; begin Put_Line ("GENERATE_SPEC"); Recreate (File, Out_File, Base_Name & ".ads"); Set_Output (File); -- Prolog Put_Line ("--"); Put_Line ("-- Generated by cherrylemon"); Put_Line ("--"); New_Line; Put_Line ("package " & Module & " is"); Set_Output (File); for I in First .. Last loop declare Symbol : constant String := Prefix; -- & Lime.Get_Token (I); begin Set_Col (File, 4); -- ..Put (File, " "); Put (File, Symbol); Set_Col (File, 20); Put (File, " : constant Token_Type := "); Put (File, Integer'Image (I)); Put (File, ";"); New_Line (File); end; end loop; -- Epilog Put_Line (File, "end " & Module & ";"); Close (File); Set_Output (Standard_Output); end Generate_Spec; end Generate_Ada;
stcarrez/ada-el
Ada
1,196
ads
----------------------------------------------------------------------- -- el-utils-tests - Tests the EL utils -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- 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.Tests; package EL.Utils.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Expand_Properties (T : in out Test); procedure Test_Expand_Recursion (T : in out Test); procedure Test_Eval (T : in out Test); end EL.Utils.Tests;
AdaCore/libadalang
Ada
186
adb
with Ada.Integer_Wide_Text_IO; use Ada.Integer_Wide_Text_IO; procedure Test is X : Integer; Last : Positive; begin Get ("12", X, Last); pragma Test_Statement_UID; end Test;
reznikmm/matreshka
Ada
3,782
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Ada Modeling Framework -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2011, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with League.Holders; with AMF.Internals; package AMF.Boolean_Collections.Internals is pragma Preelaborate; function To_Holder (Item : Collection_Of_Boolean'Class) return League.Holders.Holder; -- Converts specified collection into holder of reflective collection type. function Wrap (Collection : AMF.Internals.AMF_Collection_Of_Boolean) return Collection_Of_Boolean; end AMF.Boolean_Collections.Internals;
BrickBot/Bound-T-H8-300
Ada
2,590
adb
-- List_Filters (body) -- -- A component of the Bound-T Worst-Case Execution Time Tool. -- ------------------------------------------------------------------------------- -- Copyright (c) 1999 .. 2015 Tidorum Ltd -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- 1. Redistributions of source code must retain the above copyright notice, this -- list of conditions and the following disclaimer. -- 2. Redistributions in binary form 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. -- -- This software is provided by the copyright holders and contributors "as is" and -- any express or implied warranties, including, but not limited to, the implied -- warranties of merchantability and fitness for a particular purpose are -- disclaimed. In no event shall the copyright owner or contributors be liable for -- any direct, indirect, incidental, special, exemplary, or consequential damages -- (including, but not limited to, procurement of substitute goods or services; -- loss of use, data, or profits; or business interruption) however caused and -- on any theory of liability, whether in contract, strict liability, or tort -- (including negligence or otherwise) arising in any way out of the use of this -- software, even if advised of the possibility of such damage. -- -- Other modules (files) of this software composition should contain their -- own copyright statements, which may have different copyright and usage -- conditions. The above conditions apply to this file. ------------------------------------------------------------------------------- -- -- $Revision: 1.2 $ -- $Date: 2015/10/24 20:05:49 $ -- -- $Log: list_filters.adb,v $ -- Revision 1.2 2015/10/24 20:05:49 niklas -- Moved to free licence. -- -- Revision 1.1 2000-07-14 20:34:13 holsti -- First version. -- package body List_Filters is function Chosen (From : List_Type; Pick : Value_Type) return List_Type is Picked : List_Type (1 .. From'Length); Last : Natural := 0; -- Accumulate the results in Picked(1 .. Last). begin for I in From'range loop if Value (From(I)) = Pick then -- This item to be included. Last := Last + 1; Picked(Last) := From(I); end if; end loop; return Picked(1 .. Last); end Chosen; end List_Filters;
shintakezou/langkit
Ada
83,577
adb
-- -- Copyright (C) 2014-2022, AdaCore -- SPDX-License-Identifier: Apache-2.0 -- with Ada.Containers.Generic_Array_Sort; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Strings.Wide_Wide_Unbounded; use Ada.Strings.Wide_Wide_Unbounded; with Ada.Text_IO; use Ada.Text_IO; with System.Address_Image; with System.Assertions; with Langkit_Support.Errors; use Langkit_Support.Errors; with Langkit_Support.Images; use Langkit_Support.Images; package body Langkit_Support.Lexical_Envs_Impl is procedure Invalidate_Cache (Env : Lexical_Env_Access); procedure Initialize_Foreign_Nodes (El : in out Internal_Map_Element) with Inline_Always; -- Initialize foreign nodes map in ``El`` function Image (E : Entity) return String is (Image (Node_Text_Image (E.Node, False))); function Entity_Vectors_Image is new Entity_Vectors.Image (Image); No_Entity_Info : constant Entity_Info := (Empty_Metadata, null, False); function Is_Lookup_Cache_Valid (Self : Lexical_Env) return Boolean with Pre => Self.Kind = Static_Primary; -- Return whether Env's lookup cache is valid. This will check every -- Lookup_Cache_Valid flag up Env's parent chain. function Wrap (Env : Lexical_Env_Access; Owner : Generic_Unit_Ptr := No_Generic_Unit) return Lexical_Env is ((Env => Wrap (Env), Hash => Hash (Env), Kind => (if Env = null then Static_Primary else Env.Kind), Owner => Owner, Version => (if Owner /= No_Generic_Unit then Get_Unit_Version (Owner) else 0))); function OK_For_Rebindings (Self : Lexical_Env) return Boolean is (Self.Kind in Primary_Kind and then Env_Node (Self) /= No_Node); function Extract_Rebinding (Rebindings : in out Env_Rebindings; Rebound_Env : Lexical_Env; Found : out Boolean) return Lexical_Env; -- Look for a pair in Rebindings whose Old_Env field is "Rebound_Env". -- -- If there is one, return the env it is associated to, and put the -- remaining set of rebindings in rebindings. Otherwise, return -- "Rebound_Env". -- -- If Rebindings is bound to a new set of rebindings upon return, the -- ownership share of the old rebinding set will have been forfeited. function Shed_Rebindings (From_Env : Lexical_Env; Rebindings : Env_Rebindings) return Env_Rebindings with Inline; -- Shed env rebindings that are not in the parent chain for From_Env procedure Check_Rebindings_Unicity (Self : Env_Rebindings); -- Perform a unicity check on the various rebindings in Self. In -- particular, check that there are no two identical Old_Env and no two -- identical New_Env in the set of rebindings. If there are, raise a -- property error. procedure Get_Internal_Impl (Self : Lexical_Env; Key : Symbol_Type; Lookup_Kind : Lookup_Kind_Type := Recursive; Rebindings : Env_Rebindings := null; Metadata : Node_Metadata := Empty_Metadata; Categories : Ref_Categories; Local_Results : in out Lookup_Result_Vector; Toplevel : Boolean := True; Recursive_Check_Reached : in out Boolean); -- This is the real Env.Get implementation. -- -- ``Toplevel`` is used to discriminate between the toplevel call and -- further calls, for the ``Toplevel_Only`` cache mode. -- -- ``Recursive_Check_Reached`` is an helper variable passed down to -- recursive calls, to down propagate to parent calls when the recursion -- protection is activated, i.e. when an lexical environment is visited a -- second time in a recursive call. When this recursive check is reached, -- all intermediate calls won't be cached because the origin of the request -- has potentially changed the results. See the Ada example below:: -- -- package R is -- package N is -- type O is ...; -- -- <- Original env request on "O" from here -- end N; -- -- <- When exploring parents, env_get will get here. The cache -- -- is empty. -- use N; -- -- <- When traversing the "use", since the request originates -- -- from `N`, the recursion protection will stop it's -- -- re-traversal -- -- <- If we cache, we'll cache a wrong result for the request -- -- `R_env.get("O")`, when the request starts from `R`'s env -- end R; procedure Get_Internal (Self : Lexical_Env; Key : Symbol_Type; Lookup_Kind : Lookup_Kind_Type := Recursive; Rebindings : Env_Rebindings := null; Metadata : Node_Metadata := Empty_Metadata; Categories : Ref_Categories; Local_Results : in out Lookup_Result_Vector); -- This is the ``Get_Internal_Impl`` wrapper. It is used to forward default -- values to some internal parameters used by ``Get_Internal_Impl``. We're -- not using a nested function for ``Get_Internal_Impl`` because the level -- of nesting is bad enough already. -- -- ``Local_Results`` is the vector in which results will be accumulated by -- the recursive calls. -- -- TODO: It might be exactly the same to return Local_Result rather than -- make it an in out param, now that we have a wrapper. procedure Reset_Lookup_Cache (Self : Lexical_Env); -- Reset Self's lexical environment lookup cache ---------------- -- Text_Image -- ---------------- function Text_Image (Cats : Ref_Categories) return Text_Type is Ret : Unbounded_Text_Type; begin Append (Ret, "("); for Cat in Ref_Category'Range loop Append (Ret, To_Text (Cat'Image & " => " & Cats (Cat)'Image & ", ")); end loop; Append (Ret, ")"); return To_Text (Ret); end Text_Image; --------------------------- -- Is_Lookup_Cache_Valid -- --------------------------- function Is_Lookup_Cache_Valid (Self : Lexical_Env) return Boolean is P : Lexical_Env; begin if Unwrap (Self).Lookup_Cache_Valid then P := Parent (Self); return (P in Null_Lexical_Env | Empty_Env or else Is_Lookup_Cache_Valid (P)); else return False; end if; end Is_Lookup_Cache_Valid; ------------------------ -- Reset_Lookup_Cache -- ------------------------ procedure Reset_Lookup_Cache (Self : Lexical_Env) is Env : constant Lexical_Env_Access := Unwrap (Self); begin for C of Env.Lookup_Cache loop C.Elements.Destroy; end loop; Env.Lookup_Cache.Clear; Env.Lookup_Cache_Valid := True; end Reset_Lookup_Cache; ----------------------- -- Simple_Env_Getter -- ----------------------- function Simple_Env_Getter (E : Lexical_Env) return Env_Getter is begin Inc_Ref (E); return Env_Getter'(Dynamic => False, Env => E); end Simple_Env_Getter; -------------------- -- Dyn_Env_Getter -- -------------------- function Dyn_Env_Getter (Resolver : Lexical_Env_Resolver; Node : Node_Type) return Env_Getter is begin return Env_Getter'(True, Null_Lexical_Env, Node, Resolver); end Dyn_Env_Getter; ------------- -- Resolve -- ------------- procedure Resolve (Self : in out Env_Getter; Info : Entity_Info) is Env : Lexical_Env; begin case Self.Dynamic is when True => Env := Get_Env (Self, Info); -- Get_Env returns an ownership share for the returned reference, -- but we don't use it here, so dec ref. Dec_Ref (Env); when False => null; end case; exception when Exc : others => -- Resolution failed. If ``Exc`` is an exception that properties are -- allowed to raise, there is nothing else to do as ``Get_Env`` took -- care of invalidating the cache. -- -- Note that in that case there is no need to propagate the error, as -- the job of this procedure is just to do precomputation for -- ``Get_Env``. The next call to ``Get_Env`` will propagate this -- error, so all is fine. if not Properties_May_Raise (Exc) then raise; end if; end Resolve; ------------- -- Get_Env -- ------------- function Get_Env (Self : in out Env_Getter; Info : Entity_Info) return Lexical_Env is Cache_Enabled : constant Boolean := Info = No_Entity_Info; -- The cache (Self.Env) can be used only if No_Entity_Info is passed -- Note: in this whole function, we take special care for empty -- environments: while these are represented using the ``Empty_Env`` -- constant through the whole codebase, here rules are sligtly twisted -- for performance and appropriate cache invalidation (see documentation -- for the ``Env_Getter.Env`` field). -- -- The bottom line is: cached empty environments differ from the -- ``Empty_Env`` constant: the ``Version`` component is not 0 and is -- used to determine if the cached empty environment is stale (see -- ``Is_Stale``), and we must not returned these "twisted" empty -- environments to ``Get_Env``'s caller, but rather return the -- ``Empty_Env`` constant instead (the version hack shall not go to the -- outside world). function Is_Stale (Env : Lexical_Env) return Boolean with Pre => Self.Dynamic; -- Return whether the ``Env`` cached environment refers to an obsolete. -- ``Node`` is the node used to compute it. -------------- -- Is_Stale -- -------------- function Is_Stale (Env : Lexical_Env) return Boolean is E : constant Lexical_Env_Access := Unwrap (Env); L : Lexical_Env; begin -- Take care of the special case of empty environments, which may -- differ from ``Empty_Env`` in ``Env.Version`` (see above). if Env.Env = Empty_Env.Env then return Env.Version < Get_Context_Version (Self.Node); end if; case Env.Kind is when Primary_Kind => if Env.Owner /= No_Generic_Unit then -- If there is an owner, check that the unit version has not -- been incremented since then. return Get_Unit_Version (Env.Owner) > Env.Version; end if; for I in E.Referenced_Envs.First_Index .. E.Referenced_Envs.Last_Index loop L := Get_Env (E.Referenced_Envs.Get_Access (I).Getter, No_Entity_Info); if Is_Stale (L) then return True; end if; Dec_Ref (L); end loop; return False; when Orphaned => pragma Assert (Env.Owner = No_Generic_Unit); return Is_Stale (E.Orphaned_Env); when Grouped => pragma Assert (Env.Owner = No_Generic_Unit); return (for some GE of E.Grouped_Envs.all => Is_Stale (GE)); when Rebound => -- This env is stale as soon as either the rebound env or the -- rebindings are stale. return Is_Stale (E.Rebound_Env) or else E.Rebindings.Version /= E.Rebindings_Version; end case; end Is_Stale; begin if Self.Dynamic then -- Resolve the dynamic lexical env getter. For this, use the cache if -- possible. if Cache_Enabled and then Self.Env /= Null_Lexical_Env then -- If it is not stale, return it. Make sure to return genuine -- ``Empty_Env`` copies for empty environments. if not Is_Stale (Self.Env) then if Self.Env.Env = Empty_Env.Env then return Empty_Env; else Inc_Ref (Self.Env); return Self.Env; end if; end if; -- If it is stale, release and clear it Dec_Ref (Self.Env); end if; -- For some reason we could not use the cache: do the resolution and -- cache its result if applicable. declare E : constant Entity := (Node => Self.Node, Info => Info); Result : constant Lexical_Env := Self.Resolver.all (E); begin if Cache_Enabled then -- Since the call to Self.Resolver above may have invoked -- Get_Env on the same Env_Getter object (Self), we need to be -- re-entrant. This means that though called Dec_Ref on -- Self.Env above, once we got here, Self.Env may have another -- value: we need to remove its ownership share before -- overriding below. Dec_Ref (Self.Env); -- The ownership share returned by the resolver goes to the -- cache: the call to Inc_Ref below will create a new one for -- the returned value. Self.Env := Result; -- Don't forget to record the context version for caches in the -- case of Empty_Env (see Env_Getter.Env and the cache hit code -- above). if Self.Env.Env = Empty_Env.Env then Self.Env.Version := Get_Context_Version (Self.Node); end if; else return Result; end if; end; end if; -- Return a copy of the cached resolved lexical env, so create a new -- ownership share. Inc_Ref (Self.Env); return Self.Env; end Get_Env; ---------------- -- Equivalent -- ---------------- function Equivalent (L, R : Env_Getter) return Boolean is begin if L.Dynamic or else R.Dynamic then raise Constraint_Error with "trying to compare dynamic env getters"; else return L.Env = R.Env; end if; end Equivalent; ------------- -- Inc_Ref -- ------------- procedure Inc_Ref (Self : Env_Getter) is begin Inc_Ref (Self.Env); end Inc_Ref; ------------- -- Dec_Ref -- ------------- procedure Dec_Ref (Self : in out Env_Getter) is begin Dec_Ref (Self.Env); end Dec_Ref; ------------- -- Combine -- ------------- function Combine (L, R : Env_Rebindings) return Env_Rebindings is function Append_All (Cur : Env_Rebindings) return Env_Rebindings; -- Given Cur = C1 -> C2 .. -> Cn, return C1 -> C2 .. -> Cn -> L ---------------- -- Append_All -- ---------------- function Append_All (Cur : Env_Rebindings) return Env_Rebindings is begin if Cur = null then return L; end if; return Append (Append_All (Cur.Parent), Cur.Old_Env, Cur.New_Env); end Append_All; begin if L = null then return R; elsif R = null then return L; end if; return Result : constant Env_Rebindings := Append_All (R) do Check_Rebindings_Unicity (Result); end return; end Combine; ------------ -- Append -- ------------ function Append (Self : Env_Rebindings; Old_Env, New_Env : Lexical_Env) return Env_Rebindings is O : constant Lexical_Env_Access := Unwrap (Old_Env); begin -- Look for an existing rebinding for the result: in the Old_Env's pool -- if there is no parent, otherwise in the parent's children. if Self = null then if O.Rebindings_Pool /= null then declare use Env_Rebindings_Pools; Cur : constant Cursor := O.Rebindings_Pool.Find (New_Env); begin if Cur /= Env_Rebindings_Pools.No_Element then return Element (Cur); end if; end; end if; else for C of Self.Children loop if C.Old_Env = Old_Env and then C.New_Env = New_Env then return C; end if; end loop; end if; -- No luck? then create a new rebinding and register it where required declare Result : constant Env_Rebindings := Acquire_Rebinding (Env_Node (Old_Env), Self, Old_Env, New_Env); begin if Self /= null then Self.Children.Append (Result); else if O.Rebindings_Pool = null then O.Rebindings_Pool := new Env_Rebindings_Pools.Map; end if; O.Rebindings_Pool.Insert (New_Env, Result); end if; Register_Rebinding (Env_Node (Old_Env), Result); Register_Rebinding (Env_Node (New_Env), Result); Check_Rebindings_Unicity (Result); return Result; end; end Append; ---------------------- -- Append_Rebinding -- ---------------------- function Append_Rebinding (Self : Env_Rebindings; Old_Env : Lexical_Env; New_Env : Lexical_Env) return Env_Rebindings is begin if not Is_Rebindable (Env_Node (Old_Env)) then raise Property_Error with "Illegal lexical environment rebinding"; end if; return Append (Self, Old_Env, New_Env); end Append_Rebinding; ------------------- -- Create_Entity -- ------------------- function Create_Entity (Node : Node_Type; Md : Node_Metadata) return Entity is begin return Entity' (Node => Node, Info => (Md => Md, Rebindings => null, From_Rebound => False)); end Create_Entity; ---------------- -- Equivalent -- ---------------- function Equivalent (L, R : Entity_Info) return Boolean is begin return L.Md = R.Md and then L.Rebindings = R.Rebindings; end Equivalent; ---------------- -- Equivalent -- ---------------- function Equivalent (L, R : Entity) return Boolean is begin if L.Node /= R.Node then return False; end if; -- All null nodes are equals, regardless of their entity info if L.Node = No_Node then return True; end if; -- For all other cases, make sure the entity info is equivalent return Equivalent (L.Info, R.Info); end Equivalent; ------------------------ -- Create_Lexical_Env -- ------------------------ function Create_Lexical_Env (Parent : Lexical_Env; Node : Node_Type; Transitive_Parent : Boolean := False; Owner : Generic_Unit_Ptr) return Lexical_Env is begin if Parent /= Null_Lexical_Env then Inc_Ref (Parent); end if; return Wrap (new Lexical_Env_Record' (Kind => Static_Primary, Parent => Parent, Transitive_Parent => Transitive_Parent, Node => Node, Referenced_Envs => <>, Map => new Internal_Envs.Map, Rebindings_Pool => null, Lookup_Cache_Valid => True, Lookup_Cache => Lookup_Cache_Maps.Empty_Map, Rebindings_Assoc_Ref_Env => -1), Owner => Owner); end Create_Lexical_Env; -------------------------------- -- Create_Dynamic_Lexical_Env -- -------------------------------- function Create_Dynamic_Lexical_Env (Parent : Lexical_Env; Node : Node_Type; Transitive_Parent : Boolean := False; Owner : Generic_Unit_Ptr; Assocs_Getter : Inner_Env_Assocs_Resolver; Assoc_Resolver : Entity_Resolver := null) return Lexical_Env is begin if Parent /= Null_Lexical_Env then Inc_Ref (Parent); end if; return Wrap (new Lexical_Env_Record' (Kind => Dynamic_Primary, Parent => Parent, Transitive_Parent => Transitive_Parent, Node => Node, Rebindings_Pool => null, Assocs_Getter => Assocs_Getter, Assoc_Resolver => Assoc_Resolver), Owner => Owner); end Create_Dynamic_Lexical_Env; ------------------------------ -- Initialize_Foreign_Nodes -- ------------------------------ procedure Initialize_Foreign_Nodes (El : in out Internal_Map_Element) is begin if El.Foreign_Nodes = null then El.Foreign_Nodes := new Internal_Map_Node_Maps.Map; end if; end Initialize_Foreign_Nodes; --------- -- Add -- --------- procedure Add (Self : Lexical_Env; Key : Symbol_Type; Value : Node_Type; Md : Node_Metadata := Empty_Metadata; Resolver : Entity_Resolver := null) is use Internal_Envs; Env : constant Lexical_Env_Access := Unwrap (Self); Node : constant Internal_Map_Node := (Value, Md, Resolver); C : Cursor; Dummy : Boolean; Map : Internal_Envs.Map renames Env.Map.all; begin -- See Empty_Env's documentation if Self = Empty_Env then return; end if; Me.Trace ("ADDING VAL key=""" & Image (Key) & """, env=" & Env_Image (Self)); -- Invalidate the cache, and make sure we have an entry in the internal -- map for the given key. Invalidate_Cache (Env); Map.Insert (Key, Empty_Internal_Map_Element, C, Dummy); declare E : Internal_Map_Element renames Reference (Map, C).Element.all; begin -- If Self and Value belong to the same analysis unit, consider Node -- as native. In all other cases, it's a foreign node. if Is_Foreign (Self, Value) then Initialize_Foreign_Nodes (E); E.Foreign_Nodes.Insert (Node.Node, Node); else E.Native_Nodes.Append (Node); end if; end; end Add; ------------ -- Remove -- ------------ procedure Remove (Self : Lexical_Env; Key : Symbol_Type; Value : Node_Type) is Env : constant Lexical_Env_Access := Unwrap (Self); begin if Self = Empty_Env then return; end if; declare Ref : constant Internal_Envs.Reference_Type := Env.Map.Reference (Key); V : Internal_Map_Node_Vectors.Vector renames Ref.Native_Nodes; begin if Is_Foreign (Self, Value) then Ref.Foreign_Nodes.Delete (Value); else -- Get rid of the element. Do this in reverse order so that -- removing one element does not make us "step over" the next -- item. Also don't do this in place (using V.Pop) as we need to -- preserve the order of elements. for I in reverse 1 .. V.Length loop if V.Get (I).Node = Value then V.Remove_At (I); exit; end if; end loop; end if; Invalidate_Cache (Env); end; end Remove; --------------- -- Reference -- --------------- procedure Reference (Self : Lexical_Env; Referenced_From : Node_Type; Resolver : Lexical_Env_Resolver; Kind : Ref_Kind := Normal; Categories : Ref_Categories := All_Cats; Rebindings_Assoc : Boolean := False) is Env : constant Lexical_Env_Access := Unwrap (Self); Refd_Env : Referenced_Env := (Kind, Dyn_Env_Getter (Resolver, Referenced_From), False, Inactive, Categories); begin if Self = Empty_Env then return; end if; if Has_Trace then Rec.Trace ("REFERENCE " & Env_Image (Self)); end if; Resolve (Refd_Env.Getter, No_Entity_Info); Refd_Env.State := Active; Referenced_Envs_Vectors.Append (Env.Referenced_Envs, Refd_Env); if Rebindings_Assoc then if Env.Rebindings_Assoc_Ref_Env /= -1 then raise Property_Error with "Env already has a rebindings associated reference env"; end if; Env.Rebindings_Assoc_Ref_Env := Env.Referenced_Envs.Last_Index; end if; Invalidate_Cache (Env); end Reference; --------------- -- Reference -- --------------- procedure Reference (Self : Lexical_Env; To_Reference : Lexical_Env; Kind : Ref_Kind := Normal; Categories : Ref_Categories := All_Cats; Rebindings_Assoc : Boolean := False) is Env : constant Lexical_Env_Access := Unwrap (Self); Ref : constant Referenced_Env := (Kind, Simple_Env_Getter (To_Reference), False, Active, Categories); begin if Has_Trace then Rec.Trace ("REFERENCE" & Env_Image (Self)); end if; if Self = Empty_Env then return; end if; Referenced_Envs_Vectors.Append (Env.Referenced_Envs, Ref); if Rebindings_Assoc then Env.Rebindings_Assoc_Ref_Env := Env.Referenced_Envs.Last_Index; end if; Invalidate_Cache (Env); end Reference; ------------------ -- Get_Internal -- ------------------ procedure Get_Internal (Self : Lexical_Env; Key : Symbol_Type; Lookup_Kind : Lookup_Kind_Type := Recursive; Rebindings : Env_Rebindings := null; Metadata : Node_Metadata := Empty_Metadata; Categories : Ref_Categories; Local_Results : in out Lookup_Result_Vector) is Dummy : Boolean := False; begin Get_Internal_Impl (Self, Key, Lookup_Kind, Rebindings, Metadata, Categories, Local_Results, Toplevel => True, Recursive_Check_Reached => Dummy); end Get_Internal; ----------------------- -- Get_Internal_Impl -- ----------------------- procedure Get_Internal_Impl (Self : Lexical_Env; Key : Symbol_Type; Lookup_Kind : Lookup_Kind_Type := Recursive; Rebindings : Env_Rebindings := null; Metadata : Node_Metadata := Empty_Metadata; Categories : Ref_Categories; Local_Results : in out Lookup_Result_Vector; Toplevel : Boolean := True; Recursive_Check_Reached : in out Boolean) is function Do_Cache return Boolean is (Has_Lookup_Cache (Self) and then (Lookup_Cache_Mode = Full or else (Lookup_Cache_Mode = Toplevel_Only and then Toplevel))); -- Return whether to cache a particular request or not function Log_Id return String is ("env=" & Env_Image (Self) & ", key=" & Image (Key.all)); Env : constant Lexical_Env_Access := Unwrap (Self); Outer_Results : Lookup_Result_Vector := Lookup_Result_Item_Vectors.Empty_Vector; Need_Cache : Boolean := False; Current_Rebindings : Env_Rebindings; procedure Get_Refd_Nodes (Self : in out Referenced_Env); procedure Append_Result (Node : Internal_Map_Node; Md : Node_Metadata; Rebindings : Env_Rebindings; From_Rebound : Boolean := False); -- Add E to results, if it passes the Can_Reach filter. Return whether -- result was appended or not. use Internal_Envs; procedure Append_All_Nodes (Self : Lexical_Env; From_Rebound : Boolean); -- Add all nodes of the given Env to the results. Make sure the output -- is deterministic using a sorting procedure. function Get_Nodes (Self : Lexical_Env; From_Rebound : Boolean := False) return Boolean; -- Lookup for matching nodes in Env's internal map and append them to -- Local_Results. Return whether we found some. procedure Recurse (Self : Lexical_Env; Key : Symbol_Type; Lookup_Kind : Lookup_Kind_Type := Recursive; Rebindings : Env_Rebindings := null; Metadata : Node_Metadata := Empty_Metadata; Categories : Ref_Categories; Local_Results : in out Lookup_Result_Vector); -- Helper procedure for all env lookup recursions, so that the Toplevel -- argument is automatically passed to False for recursive calls, and -- ``Recursive_Check_Reached`` is automatically passed down the call -- chain. -- -- NOTE: Every recursive call to ``Get_Internal_Impl`` should go through -- this helper. ------------- -- Recurse -- ------------- procedure Recurse (Self : Lexical_Env; Key : Symbol_Type; Lookup_Kind : Lookup_Kind_Type := Recursive; Rebindings : Env_Rebindings := null; Metadata : Node_Metadata := Empty_Metadata; Categories : Ref_Categories; Local_Results : in out Lookup_Result_Vector) is begin Get_Internal_Impl (Self, Key, Lookup_Kind, Rebindings, Metadata, Categories, Local_Results, Toplevel => False, Recursive_Check_Reached => Recursive_Check_Reached); end Recurse; ---------------------- -- Append_All_Nodes -- ---------------------- procedure Append_All_Nodes (Self : Lexical_Env; From_Rebound : Boolean) is Env : constant Lexical_Env_Access := Unwrap (Self); type Cursor_Array is array (Natural range <>) of Internal_Envs.Cursor; function "<" (A, B : Internal_Envs.Cursor) return Boolean is (Internal_Envs.Key (A).all < Internal_Envs.Key (B).all); procedure Cursor_Array_Sort is new Ada.Containers.Generic_Array_Sort (Index_Type => Natural, Element_Type => Internal_Envs.Cursor, Array_Type => Cursor_Array); All_Elements : Cursor_Array (1 .. Natural (Env.Map.Length)); I : Positive := All_Elements'First; begin for C in Env.Map.Iterate loop All_Elements (I) := C; I := I + 1; end loop; Cursor_Array_Sort (All_Elements); for C of All_Elements loop declare I_Nodes : constant Internal_Map_Node_Vectors.Vector := Internal_Envs.Element (C).Native_Nodes; F_Nodes : constant Internal_Map_Node_Map := Internal_Envs.Element (C).Foreign_Nodes; begin -- Append internal nodes for I in reverse I_Nodes.First_Index .. I_Nodes.Last_Index loop Append_Result (I_Nodes.Get (I), Metadata, Current_Rebindings, From_Rebound); end loop; -- Append foreign nodes if F_Nodes /= null then for C in F_Nodes.Iterate loop Append_Result (Internal_Map_Node_Maps.Element (C), Metadata, Current_Rebindings, From_Rebound); end loop; end if; end; end loop; end Append_All_Nodes; --------------- -- Get_Nodes -- --------------- function Get_Nodes (Self : Lexical_Env; From_Rebound : Boolean := False) return Boolean is Env : constant Lexical_Env_Access := Unwrap (Self); Map : Internal_Map; C : Cursor; begin if Self.Kind = Static_Primary then Map := Env.Map; C := Internal_Envs.No_Element; if Env.Map /= null then -- If Key is null, we want to get every entity stored in the -- map regardless of the symbol. if Key = null then Append_All_Nodes (Self, From_Rebound); return True; end if; -- Else, find the elements in the map corresponding to Key C := Map.Find (Key); end if; if Has_Element (C) then declare E : Internal_Map_Element renames Reference (Map.all, C); begin -- First add nodes that belong to the same environment as -- Self. Add them in reverse order, so that last inserted -- results are returned first. for I in reverse 1 .. E.Native_Nodes.Last_Index loop Append_Result (E.Native_Nodes.Get (I), Metadata, Current_Rebindings, From_Rebound); end loop; -- Then add foreign nodes: just iterate on the ordered map if E.Foreign_Nodes /= null then for Pos in E.Foreign_Nodes.Iterate loop Append_Result (Internal_Map_Node_Maps.Element (Pos), Metadata, Current_Rebindings, From_Rebound); end loop; end if; end; return True; end if; else pragma Assert (Self.Kind = Dynamic_Primary); declare -- Query the dynamic list of associations for this env Assocs : Inner_Env_Assoc_Array := Env.Assocs_Getter.all ((Env.Node, No_Entity_Info)); A : Inner_Env_Assoc; begin for I in 1 .. Length (Assocs) loop -- For each individual assoc: add it if Key is null, or only -- assocs with matching symbols. A := Get (Assocs, I); if Key = null or else Key = Get_Key (A) then declare IMN : constant Internal_Map_Node := (Get_Node (A), Get_Metadata (A), Env.Assoc_Resolver); begin Append_Result (IMN, Metadata, Current_Rebindings, From_Rebound); end; end if; end loop; Dec_Ref (Assocs); end; end if; return False; end Get_Nodes; ------------------- -- Append_Result -- ------------------- procedure Append_Result (Node : Internal_Map_Node; Md : Node_Metadata; Rebindings : Env_Rebindings; From_Rebound : Boolean := False) is E : constant Entity := (Node => Node.Node, Info => (Md => Combine (Node.Md, Md), Rebindings => Rebindings, From_Rebound => From_Rebound)); begin if Has_Trace then Rec.Trace ("Found " & Image (Node_Text_Image (E.Node, False)) & " from_rebound => " & From_Rebound'Img); end if; declare Resolved_Entity : Entity := (if Node.Resolver = null then E else Node.Resolver.all (E)); begin Resolved_Entity.Info.From_Rebound := From_Rebound; Local_Results.Append (Lookup_Result_Item' (E => Resolved_Entity, Filter_From => Node.Resolver = null, Override_Filter_Node => No_Node)); end; end Append_Result; -------------------- -- Get_Refd_Nodes -- -------------------- procedure Get_Refd_Nodes (Self : in out Referenced_Env) is Env : Lexical_Env := Empty_Env; -- Make sure this holds a valid environment at all times so that the -- exception handler below can always call Dec_Ref on it. begin -- Don't follow the referenced environment if either: -- * the node from which this reference starts cannot reach From; -- * the node that created this environment reference is a parent of -- From. if (Lookup_Kind /= Recursive and then Self.Kind /= Transitive) or else Self.Being_Visited or else Self.State = Inactive then -- We reached a loop in the env graph, propagate the information -- back to callers. Recursive_Check_Reached := True; return; end if; if Self.Categories /= All_Cats and then Categories /= All_Cats and then not (for some C of Ref_Categories'(Categories and Self.Categories) => C) then return; end if; Self.Being_Visited := True; -- Get the env for the referenced env getter. Pass the metadata and -- the relevant rebindings. Env := Get_Env (Self.Getter, Entity_Info'(Metadata, Rebindings, False)); -- TODO: Do not create a temp vector here, rather keep track of prior -- size, and only modify appended elements if the getter is dynamic. declare Refd_Results : Lookup_Result_Vector; begin Recurse (Env, Key, Lookup_Kind => (if Lookup_Kind = Recursive and then Self.Kind = Transitive then Recursive elsif Lookup_Kind = Minimal then raise System.Assertions.Assert_Failure with "Should not happen" else Flat), -- We do not force the propagation of rebindings here: -- the call to ``Get_Env`` above also receives them, and -- therefore can decide itself how they should be propagated -- by returning a Rebound_Env. If it doesn't return a -- Rebound_Env, we propagate them normally. Rebindings => (if Env.Kind in Rebound then null else Shed_Rebindings (Env, Current_Rebindings)), Metadata => Metadata, Categories => Categories, Local_Results => Refd_Results); if Self.Getter.Dynamic then for Res of Refd_Results loop declare New_Res : Lookup_Result_Item := Res; begin New_Res.Override_Filter_Node := Self.Getter.Node; Local_Results.Append (New_Res); end; end loop; else Local_Results.Concat (Refd_Results); end if; Refd_Results.Destroy; end; Self.Being_Visited := False; Dec_Ref (Env); exception when others => -- Make sure that we always Dec_Ref the returned environment so we -- don't leak in case of error. Dec_Ref (Env); Self.Being_Visited := False; raise; end Get_Refd_Nodes; Extracted : Lexical_Env; Res_Key : constant Lookup_Cache_Key := (Key, Rebindings, Metadata, Categories); Cached_Res_Cursor : Lookup_Cache_Maps.Cursor; Res_Val : Lookup_Cache_Entry; Inserted, Dummy : Boolean; use Lookup_Cache_Maps; Found_Rebinding : Boolean := False; begin if Self in Empty_Env then return; end if; if Has_Trace then Rec.Trace ("GET_INTERNAL " & Log_Id & " lookup kind = " & Lookup_Kind_Type'Image (Lookup_Kind)); end if; case Self.Kind is when Orphaned => Recurse (Env.Orphaned_Env, Key, Flat, Rebindings, Metadata, Categories, Local_Results); return; when Grouped => -- Just concatenate lookups for all grouped environments if Has_Trace then Rec.Increase_Indent; end if; declare Md : constant Node_Metadata := Combine (Env.Default_Md, Metadata); begin for E of Env.Grouped_Envs.all loop Recurse (E, Key, Lookup_Kind, Rebindings, Md, Categories, Local_Results); end loop; end; if Has_Trace then Rec.Decrease_Indent; end if; return; when Rebound => Recurse (Env.Rebound_Env, Key, Lookup_Kind, Combine (Env.Rebindings, Rebindings), Metadata, Categories, Local_Results); return; when Primary_Kind => -- Handled below to avoid extra nesting levels null; end case; -- At this point, we know that Self is a primary lexical environment if Do_Cache and then Lookup_Kind = Recursive then if not Is_Lookup_Cache_Valid (Self) then Reset_Lookup_Cache (Self); end if; declare Val : constant Lookup_Cache_Entry := (Computing, Empty_Lookup_Result_Vector); begin Env.Lookup_Cache.Insert (Res_Key, Val, Cached_Res_Cursor, Inserted); end; if Inserted then Need_Cache := True; Outer_Results := Local_Results; Local_Results := Lookup_Result_Item_Vectors.Empty_Vector; else Res_Val := Element (Cached_Res_Cursor); if Has_Trace then Caches_Trace.Trace ("CACHE ENTRY " & Log_Id & ": " & Lookup_Cache_Entry_State'Image (Res_Val.State)); end if; case Res_Val.State is when Computing => -- When the cache state is "Computing", it means that we're -- doing a given env request inside the same env request. -- This is a thing that legitimately happens in some cases, -- and in this case you need to return the correct results, -- not using the cache mechanism at all. So we just bail out -- of the caching setup, and this will behave like a no -- cache request. null; when Computed => Local_Results.Concat (Res_Val.Elements); return; when None => Need_Cache := True; Outer_Results := Local_Results; Local_Results := Lookup_Result_Item_Vectors.Empty_Vector; end case; end if; end if; -- If there is an environment corresponding to Self in env rebindings, -- we'll get it here. We'll also shed it from the set of current -- rebindings. Current_Rebindings := Rebindings; -- Phase 1: Get nodes in own env if there are any Extracted := Extract_Rebinding (Current_Rebindings, Self, Found_Rebinding); if not Get_Nodes (Extracted, Found_Rebinding) and then Extracted /= Self then -- Getting the nodes in Self (env before extract rebinding) should -- still have the proper env rebindings, so we do Get_Nodes in the -- context of Old rebindings. TODO??? This code is kludgy ugly. There -- might be a better way, for example, passing rebindings to -- Get_Nodes explicitly. declare Tmp : Env_Rebindings; begin Tmp := Current_Rebindings; Current_Rebindings := Rebindings; Dummy := Get_Nodes (Self); Current_Rebindings := Tmp; end; end if; if Lookup_Kind /= Minimal then -- Phase 2: Get nodes in transitive and prioritary referenced envs if Self.Kind = Static_Primary then for I in Env.Referenced_Envs.First_Index .. Env.Referenced_Envs.Last_Index loop if Env.Referenced_Envs.Get_Access (I).Kind in Transitive | Prioritary then Get_Refd_Nodes (Env.Referenced_Envs.Get_Access (I).all); end if; end loop; end if; -- Phase 3: Get nodes in parent envs if Lookup_Kind = Recursive or else Env.Transitive_Parent then declare Parent_Env : Lexical_Env := Parent (Self); Parent_Rebindings : constant Env_Rebindings := Shed_Rebindings (Parent_Env, Current_Rebindings); begin if Has_Trace then Rec.Trace ("Recursing on parent environments"); Rec.Increase_Indent; end if; Recurse (Parent_Env, Key, Lookup_Kind, Parent_Rebindings, Metadata, Categories, Local_Results); if Has_Trace then Rec.Decrease_Indent; end if; Dec_Ref (Parent_Env); end; end if; -- Phase 4: Get nodes in normal referenced envs if Self.Kind = Static_Primary and then Lookup_Kind = Recursive then if Has_Trace then Rec.Trace ("Recursing on non transitive referenced environments"); Rec.Increase_Indent; end if; for I in Env.Referenced_Envs.First_Index .. Env.Referenced_Envs.Last_Index loop if Env.Referenced_Envs.Get_Access (I).Kind not in Transitive | Prioritary then Get_Refd_Nodes (Env.Referenced_Envs.Get_Access (I).all); end if; end loop; if Has_Trace then Rec.Decrease_Indent; end if; end if; end if; Dec_Ref (Extracted); if Do_Cache and then Lookup_Kind = Recursive and then Need_Cache then -- Only cache if there was no loop in the env graph (see comment on -- ``Get_Internal_Impl``). if Recursive_Check_Reached then Env.Lookup_Cache.Include (Res_Key, (None, Empty_Lookup_Result_Vector)); Outer_Results.Concat (Local_Results); -- We won't keep the local results in the cache, so destroy them Local_Results.Destroy; Local_Results := Outer_Results; else if Has_Trace then Caches_Trace.Trace ("INSERTING CACHE ENTRY " & Log_Id); end if; Env.Lookup_Cache.Include (Res_Key, (Computed, Local_Results)); Outer_Results.Concat (Local_Results); Local_Results := Outer_Results; end if; end if; exception when Exc : others => -- If ``Exc`` is an exception that properties are allowed to raise, -- free the locally allocated resources and propagate the exception. -- All bets are off for other kinds of exceptions: just propagate in -- that case. if Properties_May_Raise (Exc) then Local_Results.Destroy; end if; raise; end Get_Internal_Impl; function Get (Self : Lexical_Env; Key : Symbol_Type; From : Node_Type := No_Node; Lookup_Kind : Lookup_Kind_Type := Recursive; Categories : Ref_Categories := All_Cats) return Entity_Array is Vec : Entity_Vectors.Vector := Get (Self, Key, From, Lookup_Kind, Categories); begin return Ret : constant Entity_Array := Vec.To_Array do Vec.Destroy; end return; end Get; --------- -- Get -- --------- function Get (Self : Lexical_Env; Key : Symbol_Type; From : Node_Type := No_Node; Lookup_Kind : Lookup_Kind_Type := Recursive; Categories : Ref_Categories := All_Cats) return Entity_Vectors.Vector is FV : Entity_Vectors.Vector; begin if Has_Trace then Me.Trace ("===== In Env get, key=" & Image (Key) & ", env=" & Lexical_Env_Image (Self, Dump_Content => False) & " ====="); Me.Increase_Indent; end if; declare Results : Lookup_Result_Vector; begin Get_Internal (Self, Key, Lookup_Kind, null, Empty_Metadata, Categories, Results); for El of Results loop if From = No_Node or else (if El.Override_Filter_Node /= No_Node then Can_Reach (El.Override_Filter_Node, From) else Can_Reach (El.E.Node, From)) or else not El.Filter_From then FV.Append (El.E); end if; end loop; if Has_Trace then Me.Trace ("Returning vector " & Entity_Vectors_Image (FV)); end if; if Min.Active then Min.Trace ("Env.Get(" & (if Self.Kind = Static_Primary then Image (Node_Text_Image (Lexical_Env_Record (Self.Env.all).Node)) else Env_Image (Self)) & ", " & Image (Key.all) & ") -> " & Entity_Vectors_Image (FV)); end if; if Has_Trace then Me.Decrease_Indent; Me.Trace ("===== Out Env get ====="); end if; Results.Destroy; return FV; end; end Get; --------------- -- Get_First -- --------------- function Get_First (Self : Lexical_Env; Key : Symbol_Type; From : Node_Type := No_Node; Lookup_Kind : Lookup_Kind_Type := Recursive; Categories : Ref_Categories := All_Cats) return Entity is FV : Entity_Vectors.Vector; begin if Has_Trace then Me.Trace ("==== In Env Get_First, key=" & Image (Key) & " ===="); Me.Increase_Indent; end if; declare V : Lookup_Result_Vector; begin Get_Internal (Self, Key, Lookup_Kind, null, Empty_Metadata, Categories, V); for El of V loop if From = No_Node or else (if El.Override_Filter_Node /= No_Node then Can_Reach (El.Override_Filter_Node, From) else Can_Reach (El.E.Node, From)) or else not El.Filter_From then FV.Append (El.E); end if; end loop; V.Destroy; if Has_Trace then Me.Trace ("Returning vector with length " & FV.Length'Image); end if; return Ret : constant Entity := (if FV.Length > 0 then FV.First_Element else (No_Node, No_Entity_Info)) do FV.Destroy; if Has_Trace then Me.Decrease_Indent; Me.Trace ("===== Out Env Get_First ====="); end if; end return; end; end Get_First; ------------ -- Orphan -- ------------ function Orphan (Self : Lexical_Env) return Lexical_Env is procedure Check_Valid (Self : Lexical_Env); -- Raise a property error if we can't create an orphan for Env. Do -- nothing otherwise. ----------------- -- Check_Valid -- ----------------- procedure Check_Valid (Self : Lexical_Env) is Env : constant Lexical_Env_Access := Unwrap (Self); begin case Env.Kind is when Primary_Kind => if Env.Transitive_Parent then raise Property_Error with "Cannot create an orphan for an environment with a" & " transitive parent"; end if; when Orphaned => null; when Grouped => raise Property_Error with "Cannot create an orphan for a grouped environment"; when Rebound => Check_Valid (Env.Rebound_Env); end case; end Check_Valid; begin Check_Valid (Self); -- If Self is already an orphan, don't create yet another lexical env -- wrapper: just return Self itself. Inc_Ref (Self); return (if Self.Kind = Orphaned then Self else Wrap (new Lexical_Env_Record' (Kind => Orphaned, Ref_Count => <>, Orphaned_Env => Self), Owner => Self.Owner)); end Orphan; ----------- -- Group -- ----------- function Group (Envs : Lexical_Env_Array; With_Md : Node_Metadata := Empty_Metadata) return Lexical_Env is V : Lexical_Env_Vectors.Vector; procedure Append_Envs (E : Lexical_Env); -- Append envs from E to the envs vector. This takes care of flattening -- potential grouped envs. function Already_Has (E : Lexical_Env) return Boolean; -- Returns whether the results already contain E ----------------- -- Already_Has -- ----------------- function Already_Has (E : Lexical_Env) return Boolean is begin for El of V loop if Equivalent (El, E) then return True; end if; end loop; return False; end Already_Has; ----------------- -- Append_Envs -- ----------------- procedure Append_Envs (E : Lexical_Env) is begin -- Flatten grouped envs only when we don't lose the `default_md` -- field of a nested grouped env. if E.Kind in Grouped and then Unwrap (E).Default_Md in Empty_Metadata | With_Md then for C of Unwrap (E).Grouped_Envs.all loop Append_Envs (C); end loop; elsif not Already_Has (E) then Inc_Ref (E); V.Append (E); end if; end Append_Envs; begin if Envs'Length = 0 then return Empty_Env; end if; for E of Envs loop Append_Envs (E); end loop; return L : constant Lexical_Env := Wrap (new Lexical_Env_Record' (Kind => Grouped, Ref_Count => <>, Grouped_Envs => new Lexical_Env_Array'(Lexical_Env_Array (V.To_Array)), Default_Md => With_Md)) do Lexical_Env_Vectors.Destroy (V); end return; end Group; ---------------- -- Rebind_Env -- ---------------- function Rebind_Env (Base_Env : Lexical_Env; Rebindings : Env_Rebindings) return Lexical_Env is begin -- If no rebindings were passed, just return the original base env Inc_Ref (Base_Env); return (if Rebindings = null then Base_Env else Wrap (new Lexical_Env_Record' (Kind => Rebound, Ref_Count => <>, Rebound_Env => Base_Env, Rebindings => Rebindings, Rebindings_Version => Rebindings.Version), Owner => Base_Env.Owner)); end Rebind_Env; ---------------- -- Rebind_Env -- ---------------- function Rebind_Env (Base_Env : Lexical_Env; E_Info : Entity_Info) return Lexical_Env is begin return Rebind_Env (Base_Env, E_Info.Rebindings); end Rebind_Env; ------------- -- Destroy -- ------------- procedure Destroy (Self : in out Lexical_Env) is Env : Lexical_Env_Access := Unwrap (Self); procedure Free is new Ada.Unchecked_Deallocation (Lexical_Env_Record, Lexical_Env_Access); procedure Free is new Ada.Unchecked_Deallocation (Lexical_Env_Array, Lexical_Env_Array_Access); procedure Free is new Ada.Unchecked_Deallocation (Internal_Map_Node_Maps.Map, Internal_Map_Node_Map); begin if Self in Null_Lexical_Env | Empty_Env then return; end if; case Self.Kind is when Primary_Kind => -- Release the reference to the parent environment Dec_Ref (Env.Parent); -- Release the pool of rebindings Destroy (Env.Rebindings_Pool); if Self.Kind = Static_Primary then -- Release referenced environments for Ref_Env of Env.Referenced_Envs loop declare Getter : Env_Getter := Ref_Env.Getter; begin Dec_Ref (Getter); end; end loop; Env.Referenced_Envs.Destroy; -- Release the internal map. Don't assume it was allocated, as -- it's convenient for testing not to allocate it. if Env.Map /= null then for Element of Env.Map.all loop Internal_Map_Node_Vectors.Destroy (Element.Native_Nodes); Free (Element.Foreign_Nodes); end loop; Destroy (Env.Map); end if; -- Release the lookup cache Reset_Lookup_Cache (Self); end if; when Orphaned => Dec_Ref (Env.Orphaned_Env); when Grouped => for E of Env.Grouped_Envs.all loop Dec_Ref (E); end loop; Free (Env.Grouped_Envs); when Rebound => Dec_Ref (Env.Rebound_Env); end case; Free (Env); Self := Null_Lexical_Env; end Destroy; ------------- -- Inc_Ref -- ------------- procedure Inc_Ref (Self : Lexical_Env) is Env : constant Lexical_Env_Access := Unwrap (Self); begin if Self.Kind not in Primary_Kind then Env.Ref_Count := Env.Ref_Count + 1; end if; end Inc_Ref; ------------- -- Dec_Ref -- ------------- procedure Dec_Ref (Self : in out Lexical_Env) is Env : constant Lexical_Env_Access := Unwrap (Self); begin if Self.Kind in Primary_Kind then return; end if; Env.Ref_Count := Env.Ref_Count - 1; if Env.Ref_Count = 0 then Destroy (Self); end if; Self := Null_Lexical_Env; end Dec_Ref; function Pop (Rebindings : Env_Rebindings) return Env_Rebindings is (if Rebindings = null then null else Rebindings.Parent); ----------------------- -- Extract_Rebinding -- ----------------------- function Extract_Rebinding (Rebindings : in out Env_Rebindings; Rebound_Env : Lexical_Env; Found : out Boolean) return Lexical_Env is Return_Env : Lexical_Env := Rebound_Env; begin Found := False; if Rebindings /= null then -- Look for a rebinding in the chain whose Old_Env is Rebound_Env. -- The correct behavior is to extract the *last* rebinding, because -- due to the stacked nature of rebindings, the user is never -- supposed to extract a rebinding other than the last one that was -- added. -- -- TODO: We're still doing a full for-loop to check if this invariant -- is consistently respected. This means that the case where the env -- is not found is linear, which is probably the most common case. -- Ideally we would have the loop only in debug builds. declare R : Env_Rebindings := Rebindings; begin while R /= null loop declare R_Old_Env : constant Lexical_Env := R.Old_Env; begin if Rebound_Env = R_Old_Env then Return_Env := R.New_Env; Found := True; -- Extracted rebinding *must* be the last one if R /= Rebindings then raise Property_Error with "Incorrect rebindings"; end if; exit; end if; end; R := R.Parent; end loop; end; end if; Inc_Ref (Return_Env); -- If we found the rebinding to extract, create the new rebindings set if Return_Env /= Rebound_Env then Rebindings := Pop (Rebindings); end if; return Return_Env; end Extract_Rebinding; --------------------- -- Shed_Rebindings -- --------------------- function Shed_Rebindings (From_Env : Lexical_Env; Rebindings : Env_Rebindings) return Env_Rebindings is First_Rebindable_Parent : Lexical_Env; Assoc_Ref_Env : Lexical_Env; Result : Env_Rebindings := Rebindings; begin -- If there is no bindings, nothing to do here if Rebindings = null then return null; end if; -- Look for the first environment in From_Env's parent chain whose Node -- is rebindable. Use null if there is no such env. First_Rebindable_Parent := From_Env; Inc_Ref (First_Rebindable_Parent); while First_Rebindable_Parent /= Empty_Env and then (Env_Node (First_Rebindable_Parent) = No_Node or else not Is_Rebindable (Env_Node (First_Rebindable_Parent))) loop -- Search for an environment that would be associated to this one and -- that is rebindable. if First_Rebindable_Parent.Kind in Primary_Kind and then Unwrap (First_Rebindable_Parent).Rebindings_Assoc_Ref_Env /= -1 then Assoc_Ref_Env := Get_Env (Unwrap (First_Rebindable_Parent).Referenced_Envs.Get_Access (Unwrap (First_Rebindable_Parent).Rebindings_Assoc_Ref_Env) .Getter, No_Entity_Info); declare N : Node_Type renames Env_Node (Assoc_Ref_Env); begin if N /= No_Node and then Is_Rebindable (N) then Dec_Ref (First_Rebindable_Parent); First_Rebindable_Parent := Assoc_Ref_Env; exit; end if; end; end if; declare Next : constant Lexical_Env := Parent (First_Rebindable_Parent); begin Dec_Ref (First_Rebindable_Parent); First_Rebindable_Parent := Next; end; end loop; -- If there is no rebindable parent anywhere, it means we cannot have -- rebindings. In that case, shed them all, i.e. return null rebindings. if First_Rebindable_Parent = Empty_Env then return null; end if; -- If we found a rebindable parent, then we will shed all rebindings -- between the top of the rebinding stack and the corresponding -- rebinding. while Result /= null and then Result.Old_Env /= First_Rebindable_Parent loop Result := Result.Parent; end loop; Dec_Ref (First_Rebindable_Parent); return Result; end Shed_Rebindings; --------------------- -- Shed_Rebindings -- --------------------- function Shed_Rebindings (E_Info : Entity_Info; Env : Lexical_Env) return Entity_Info is begin return (Md => E_Info.Md, Rebindings => Shed_Rebindings (Env, E_Info.Rebindings), From_Rebound => False); end Shed_Rebindings; ------------------------------ -- Check_Rebindings_Unicity -- ------------------------------ procedure Check_Rebindings_Unicity (Self : Env_Rebindings) is L, R : Env_Rebindings := Self; begin while L /= null loop R := L.Parent; while R /= null loop if L.Old_Env = R.Old_Env then raise Property_Error with "Old_Env present twice in rebindings"; elsif L.New_Env = R.New_Env then raise Property_Error with "New_Env present twice in rebindings"; end if; R := R.Parent; end loop; L := L.Parent; end loop; end Check_Rebindings_Unicity; ---------------- -- Text_Image -- ---------------- function Text_Image (Self : Env_Rebindings) return Text_Type is function Text_Image (Self : Lexical_Env) return Text_Type is (Node_Text_Image (Env_Node (Self))); function Text_Image (Self : Env_Rebindings) return Text_Type is (Text_Image (Self.New_Env)); begin if Self = null then return "<null>"; end if; declare use Env_Rebindings_Vectors; Rebindings_Vector : Vector := Empty_Vector; Cur : Env_Rebindings := Self; Buffer : Unbounded_Wide_Wide_String; begin -- Get rebindings in reverse order: older first, most recent last while Cur /= null loop Rebindings_Vector.Append (Cur); Cur := Cur.Parent; end loop; Append (Buffer, "["); for I in reverse 1 .. Rebindings_Vector.Last_Index loop if I < Rebindings_Vector.Last_Index then Append (Buffer, ", "); end if; Append (Buffer, Text_Image (Rebindings_Vector.Get (I))); end loop; Append (Buffer, "]"); Rebindings_Vector.Destroy; return To_Wide_Wide_String (Buffer); end; end Text_Image; ---------------- -- Equivalent -- ---------------- function Equivalent (Left, Right : Lexical_Env) return Boolean is L : constant Lexical_Env_Access := Unwrap (Left); R : constant Lexical_Env_Access := Unwrap (Right); begin if L = R then return True; elsif L.Kind /= R.Kind then return False; end if; case L.Kind is when Primary_Kind => -- If we have two primary environments, don't go through -- structural comparison: we can use pointer equality as each -- instance has its own identity. return False; when Orphaned => return Equivalent (L.Orphaned_Env, R.Orphaned_Env); when Grouped => return (L.Grouped_Envs'Length = R.Grouped_Envs'Length and then L.Default_Md = R.Default_Md and then (for all I in L.Grouped_Envs'Range => Equivalent (L.Grouped_Envs (I), R.Grouped_Envs (I)))); when Rebound => return (L.Rebindings = R.Rebindings and then Equivalent (L.Rebound_Env, R.Rebound_Env)); end case; end Equivalent; ---------- -- Hash -- ---------- function Hash (Env : Lexical_Env_Access) return Hash_Type is function Convert is new Ada.Unchecked_Conversion (Lexical_Env_Resolver, System.Address); function Hash is new Hash_Address (System.Word_Size / System.Storage_Unit); function Hash is new Hash_Access (Internal_Envs.Map, Internal_Map); function Hash (Getter : Env_Getter) return Hash_Type; function Hash (Ref : Referenced_Env) return Hash_Type; function Hash (Refs : Referenced_Envs_Vectors.Vector) return Hash_Type; ---------- -- Hash -- ---------- function Hash (Getter : Env_Getter) return Hash_Type is begin case Getter.Dynamic is when True => return Combine ((1, Node_Hash (Getter.Node), Hash (Convert (Getter.Resolver)))); when False => return Combine (0, Hash (Getter.Env)); end case; end Hash; ---------- -- Hash -- ---------- function Hash (Ref : Referenced_Env) return Hash_Type is begin return Combine ((Ref_Kind'Pos (Ref.Kind), Hash (Ref.Getter))); end Hash; ---------- -- Hash -- ---------- function Hash (Refs : Referenced_Envs_Vectors.Vector) return Hash_Type is Hashes : Hash_Array (1 .. Refs.Length); begin for I in Hashes'Range loop Hashes (I) := Hash (Refs.Get (I)); end loop; return Combine (Hashes); end Hash; Base_Hash : constant Hash_Type := (if Env = null then Initial_Hash else Lexical_Env_Kind'Pos (Env.Kind)); begin if Env = null then return Base_Hash; end if; case Env.Kind is when Static_Primary => return Combine ((Base_Hash, Hash (Env.Parent), (if Env.Transitive_Parent then 1 else 0), Node_Hash (Env.Node), Hash (Env.Referenced_Envs), Hash (Env.Map))); when Dynamic_Primary => return Combine ((Base_Hash, Hash (Env.Parent), (if Env.Transitive_Parent then 1 else 0), Node_Hash (Env.Node))); when Orphaned => return Combine (Base_Hash, Hash (Env.Orphaned_Env)); when Grouped => declare Result : Hash_Type := Base_Hash; begin for E of Env.Grouped_Envs.all loop Result := Combine (Result, Hash (E)); end loop; return Combine (Result, Metadata_Hash (Env.Default_Md)); end; when Rebound => return Combine ((Base_Hash, Hash (Env.Rebound_Env), Hash (Env.Rebindings))); end case; end Hash; -- We want lexical env dumps to be deterministic, so sort maps before -- iterating through their key/value pairs. type Env_Pair is record Key : Symbol_Type; Value : Internal_Map_Node_Vectors.Vector; end record; function "<" (L, R : Env_Pair) return Boolean is (L.Key.all < R.Key.all); package Env_Pair_Vectors is new Langkit_Support.Vectors (Env_Pair); procedure Sort is new Env_Pair_Vectors.Generic_Sort; function To_Sorted_Env (Env : Internal_Envs.Map) return Env_Pair_Vectors.Vector; ------------------- -- To_Sorted_Env -- ------------------- function To_Sorted_Env (Env : Internal_Envs.Map) return Env_Pair_Vectors.Vector is use Internal_Envs; begin return Vector : Env_Pair_Vectors.Vector do for Pos in Env.Iterate loop -- Append a new entry, and then fill it in place to avoid needless -- copying. Vector.Append ((Key (Pos), Internal_Map_Node_Vectors.Empty_Vector)); declare Element : Internal_Map_Element renames Env.Constant_Reference (Pos); V : Internal_Map_Node_Vectors.Vector renames Vector.Last_Element.all.Value; begin V.Concat (Element.Native_Nodes); if Element.Foreign_Nodes /= null then for Node of Element.Foreign_Nodes.all loop V.Append (Node); end loop; end if; end; end loop; Sort (Vector); end return; end To_Sorted_Env; ---------- -- Dump -- ---------- function Lexical_Env_Image (Self : Lexical_Env; Env_Id : String := ""; Parent_Env_Id : String := ""; Dump_Addresses : Boolean := False; Dump_Content : Boolean := True; Prefix : String := ""; Short_Node : Boolean := False) return String is Env : constant Lexical_Env_Access := Unwrap (Self); Result : Unbounded_String; Sub_Prefix : constant String := Prefix & " "; function Image (N : Node_Type) return String is (if N = No_Node then "<null>" else Image (Node_Text_Image (N, Short => Short_Node))); -- Wrapper around Node_Text_Image to handle null nodes. -- -- TODO??? This is slightly hackish, because we're converting a wide -- string back to string. But since we're using this solely for -- test/debug purposes, it should not matter. Still, would be good to -- have Text_Type everywhere at some point. function Image (Node : Internal_Map_Node) return String is (Image (Node.Node)); -- Wrapper around Node_Text_Image to format a lexical env map node function Image is new Internal_Map_Node_Vectors.Image (Image); procedure New_Arg; -- Helper to be called before emitting a new lexical env. "argument". -- Used to separate each argument with a comma in Result. ------------- -- New_Arg -- ------------- procedure New_Arg is begin Append (Result, ", "); end New_Arg; begin if Self = Null_Lexical_Env then return ""; end if; -- No matter what, emit a short description of this environment: kind, -- whether it's empty, parent/node/... if asked. if Env_Id'Length /= 0 then Append (Result, Env_Id & " = "); end if; Append (Result, "LexEnv(" & (case Self.Kind is when Static_Primary => "Static_Primary", when Dynamic_Primary => "Dynamic_Primary", when Orphaned => "Orphaned", when Grouped => "Grouped", when Rebound => "Rebound")); if Self = Empty_Env then New_Arg; Append (Result, "Empty"); end if; if Self.Kind in Primary_Kind then if Parent_Env_Id'Length > 0 then New_Arg; Append (Result, "Parent=" & (if Parent (Self) /= Empty_Env then Parent_Env_Id else "null")); end if; if Env_Node (Self) /= No_Node then New_Arg; Append (Result, "Node=" & Image (Env_Node (Self))); end if; end if; if Dump_Addresses then New_Arg; Append (Result, "0x" & System.Address_Image (Env.all'Address)); end if; Append (Result, ")"); -- If that was all that was asked, stop here if not Dump_Content then return To_String (Result); end if; -- Otherwise, go to details... Append (Result, ":" & ASCII.LF); case Self.Kind is when Static_Primary => declare Refs : Referenced_Envs_Vectors.Vector renames Env.Referenced_Envs; begin for I in Refs.First_Index .. Refs.Last_Index loop declare G : Env_Getter renames Refs.Get_Access (I).Getter; Env : Lexical_Env := Get_Env (G, No_Entity_Info); begin if Env /= Empty_Env then Append (Result, Sub_Prefix & "Referenced: "); if G.Dynamic then Append (Result, Image (G.Node) & ": "); end if; Append (Result, Lexical_Env_Image (Self => Env, Dump_Addresses => Dump_Addresses, Dump_Content => False)); Append (Result, ASCII.LF); Dec_Ref (Env); end if; end; end loop; end; if Env.Map.Is_Empty then Append (Result, Sub_Prefix & " <empty>" & ASCII.LF); else declare V : Env_Pair_Vectors.Vector := To_Sorted_Env (Env.Map.all); begin for I in V.First_Index .. V.Last_Index loop declare Pair : Env_Pair renames V.Get_Access (I).all; begin Append (Result, Sub_Prefix & " " & Langkit_Support.Text.Image (Pair.Key.all) & ": " & Image (Pair.Value) & ASCII.LF); Internal_Map_Node_Vectors.Destroy (Pair.Value); end; end loop; V.Destroy; end; end if; when Dynamic_Primary => Append (Result, Sub_Prefix & "... dynamic"); when Orphaned => Append (Result, Sub_Prefix & "Orphaned: " & Lexical_Env_Image (Self => Env.Orphaned_Env, Dump_Addresses => Dump_Addresses, Dump_Content => Dump_Content, Prefix => Sub_Prefix)); when Grouped => for E of Env.Grouped_Envs.all loop Append (Result, Sub_Prefix & "Grouped: " & Lexical_Env_Image (Self => E, Dump_Addresses => Dump_Addresses, Dump_Content => Dump_Content, Prefix => Sub_Prefix)); end loop; when Rebound => Append (Result, Sub_Prefix & "Rebindings: " & Image (Text_Image (Env.Rebindings)) & ASCII.LF); Append (Result, Sub_Prefix & "Rebound: " & Lexical_Env_Image (Self => Env.Rebound_Env, Dump_Addresses => Dump_Addresses, Dump_Content => Dump_Content, Prefix => Sub_Prefix)); end case; return To_String (Result); end Lexical_Env_Image; ------------------------------ -- Lexical_Env_Parent_Chain -- ------------------------------ function Lexical_Env_Parent_Chain (Self : Lexical_Env) return String is Id : Positive := 1; E : Lexical_Env := Self; Result : Unbounded_String; begin if E = Null_Lexical_Env then Append (Result, "<null>" & ASCII.LF); end if; while E /= Empty_Env loop declare Id_Str : constant String := '@' & Stripped_Image (Id); begin Append (Result, Lexical_Env_Image (Self => E, Env_Id => Id_Str, Parent_Env_Id => '@' & Stripped_Image (Id + 1), Dump_Addresses => True)); end; Id := Id + 1; E := Parent (E); end loop; return To_String (Result); end Lexical_Env_Parent_Chain; -------------------------- -- Dump_One_Lexical_Env -- -------------------------- procedure Dump_One_Lexical_Env (Self : Lexical_Env; Env_Id : String := ""; Parent_Env_Id : String := ""; Dump_Addresses : Boolean := False; Dump_Content : Boolean := True) is begin Put_Line (Lexical_Env_Image (Self, Env_Id, Parent_Env_Id, Dump_Addresses, Dump_Content)); end Dump_One_Lexical_Env; ----------------------------------- -- Dump_Lexical_Env_Parent_Chain -- ----------------------------------- procedure Dump_Lexical_Env_Parent_Chain (Self : Lexical_Env) is begin Put_Line (Lexical_Env_Parent_Chain (Self)); end Dump_Lexical_Env_Parent_Chain; ------------ -- Parent -- ------------ function Parent (Self : Lexical_Env) return Lexical_Env is Env : constant Lexical_Env_Access := Unwrap (Self); begin case Self.Kind is when Primary_Kind => return (if Env.Parent = Null_Lexical_Env then Empty_Env else Env.Parent); when Orphaned => return Parent (Env.Orphaned_Env); when Grouped => return Empty_Env; when Rebound => return Parent (Env.Rebound_Env); end case; end Parent; -------------- -- Env_Node -- -------------- function Env_Node (Self : Lexical_Env) return Node_Type is Env : constant Lexical_Env_Access := Unwrap (Self); begin return (case Self.Kind is when Primary_Kind => Env.Node, when Orphaned => Env_Node (Env.Orphaned_Env), when Grouped => No_Node, when Rebound => Env_Node (Env.Rebound_Env)); end Env_Node; -------------------------------- -- Deactivate_Referenced_Envs -- -------------------------------- procedure Deactivate_Referenced_Envs (Self : Lexical_Env) is Env : constant Lexical_Env_Access := Unwrap (Self); R : access Referenced_Env; begin if Self in Null_Lexical_Env | Empty_Env then return; end if; Invalidate_Cache (Env); for I in Env.Referenced_Envs.First_Index .. Env.Referenced_Envs.Last_Index loop R := Env.Referenced_Envs.Get_Access (I); R.State := Inactive; end loop; end Deactivate_Referenced_Envs; ------------------------------- -- Recompute_Referenced_Envs -- ------------------------------- procedure Recompute_Referenced_Envs (Self : Lexical_Env) is Env : constant Lexical_Env_Access := Unwrap (Self); R : access Referenced_Env; begin if Self in Null_Lexical_Env | Empty_Env then return; end if; for I in Env.Referenced_Envs.First_Index .. Env.Referenced_Envs.Last_Index loop R := Env.Referenced_Envs.Get_Access (I); Resolve (R.Getter, No_Entity_Info); R.State := Active; end loop; end Recompute_Referenced_Envs; ------------------ -- Reset_Caches -- ------------------ procedure Reset_Caches (Self : Lexical_Env) is begin Unwrap (Self).Lookup_Cache_Valid := False; end Reset_Caches; ---------------------- -- Invalidate_Cache -- ---------------------- procedure Invalidate_Cache (Env : Lexical_Env_Access) is begin if Has_Trace and then Env.Lookup_Cache_Valid = True then Caches_Trace.Trace ("INVALIDATING CACHES " & Env_Image (Wrap (Env))); end if; Env.Lookup_Cache_Valid := False; end Invalidate_Cache; end Langkit_Support.Lexical_Envs_Impl;
BrickBot/Bound-T-H8-300
Ada
2,389
adb
-- Flow.Computation.Opt (body) -- -- A component of the Bound-T Worst-Case Execution Time Tool. -- ------------------------------------------------------------------------------- -- Copyright (c) 1999 .. 2015 Tidorum Ltd -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- 1. Redistributions of source code must retain the above copyright notice, this -- list of conditions and the following disclaimer. -- 2. Redistributions in binary form 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. -- -- This software is provided by the copyright holders and contributors "as is" and -- any express or implied warranties, including, but not limited to, the implied -- warranties of merchantability and fitness for a particular purpose are -- disclaimed. In no event shall the copyright owner or contributors be liable for -- any direct, indirect, incidental, special, exemplary, or consequential damages -- (including, but not limited to, procurement of substitute goods or services; -- loss of use, data, or profits; or business interruption) however caused and -- on any theory of liability, whether in contract, strict liability, or tort -- (including negligence or otherwise) arising in any way out of the use of this -- software, even if advised of the possibility of such damage. -- -- Other modules (files) of this software composition should contain their -- own copyright statements, which may have different copyright and usage -- conditions. The above conditions apply to this file. ------------------------------------------------------------------------------- -- -- $Revision: 1.2 $ -- $Date: 2015/10/24 20:05:47 $ -- -- $Log: flow-computation-opt.adb,v $ -- Revision 1.2 2015/10/24 20:05:47 niklas -- Moved to free licence. -- -- Revision 1.1 2011-08-31 04:17:12 niklas -- Added for BT-CH-0222: Option registry. Option -dump. External help files. -- with Options; with Options.Groups; package body Flow.Computation.Opt is begin Options.Register ( Option => Trace_Models_Opt'access, Name => Options.Trace_Item ("models"), Group => Options.Groups.Trace); end Flow.Computation.Opt;
reznikmm/matreshka
Ada
5,163
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Ada Modeling Framework -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2012-2013, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ -- This file is generated, don't edit it. ------------------------------------------------------------------------------ with AMF.Generic_Collections; package AMF.OCL.Ordered_Set_Types.Collections is pragma Preelaborate; package OCL_Ordered_Set_Type_Collections is new AMF.Generic_Collections (OCL_Ordered_Set_Type, OCL_Ordered_Set_Type_Access); type Set_Of_OCL_Ordered_Set_Type is new OCL_Ordered_Set_Type_Collections.Set with null record; Empty_Set_Of_OCL_Ordered_Set_Type : constant Set_Of_OCL_Ordered_Set_Type; type Ordered_Set_Of_OCL_Ordered_Set_Type is new OCL_Ordered_Set_Type_Collections.Ordered_Set with null record; Empty_Ordered_Set_Of_OCL_Ordered_Set_Type : constant Ordered_Set_Of_OCL_Ordered_Set_Type; type Bag_Of_OCL_Ordered_Set_Type is new OCL_Ordered_Set_Type_Collections.Bag with null record; Empty_Bag_Of_OCL_Ordered_Set_Type : constant Bag_Of_OCL_Ordered_Set_Type; type Sequence_Of_OCL_Ordered_Set_Type is new OCL_Ordered_Set_Type_Collections.Sequence with null record; Empty_Sequence_Of_OCL_Ordered_Set_Type : constant Sequence_Of_OCL_Ordered_Set_Type; private Empty_Set_Of_OCL_Ordered_Set_Type : constant Set_Of_OCL_Ordered_Set_Type := (OCL_Ordered_Set_Type_Collections.Set with null record); Empty_Ordered_Set_Of_OCL_Ordered_Set_Type : constant Ordered_Set_Of_OCL_Ordered_Set_Type := (OCL_Ordered_Set_Type_Collections.Ordered_Set with null record); Empty_Bag_Of_OCL_Ordered_Set_Type : constant Bag_Of_OCL_Ordered_Set_Type := (OCL_Ordered_Set_Type_Collections.Bag with null record); Empty_Sequence_Of_OCL_Ordered_Set_Type : constant Sequence_Of_OCL_Ordered_Set_Type := (OCL_Ordered_Set_Type_Collections.Sequence with null record); end AMF.OCL.Ordered_Set_Types.Collections;
kjseefried/coreland-cgbc
Ada
826
adb
with Ada.Strings; with CGBC.Bounded_Wide_Wide_Strings; with Test; procedure T_WWBstr_Append_L01 is package BS renames CGBC.Bounded_Wide_Wide_Strings; TC : Test.Context_t; S1 : BS.Bounded_String (8); begin Test.Initialize (Test_Context => TC, Program => "t_wwbstr_append_l01", Test_DB => "TEST_DB", Test_Results => "TEST_RESULTS"); BS.Append (S1, "ABCD"); -- Requires truncation and Right'Length >= Left.Data_Size BS.Append (Source => S1, New_Item => "012345678", Drop => Ada.Strings.Left); Test.Check (TC, 2209, BS.Length (S1) = 8, "BS.Length (S1) = 8"); Test.Check (TC, 2210, BS.Maximum_Length (S1) = 8, "BS.Maximum_Length (S1) = 8"); Test.Check (TC, 2211, BS.To_String (S1) = "12345678", "BS.To_String (S1) = ""12345678"""); end T_WWBstr_Append_L01;
Intelligente-sanntidssystemer/Ada-prosjekt
Ada
2,663
ads
pragma Warnings (Off); pragma Ada_95; pragma Restrictions (No_Exception_Propagation); with System; with System.Parameters; with System.Secondary_Stack; package ada_main is GNAT_Version : constant String := "GNAT Version: Community 2020 (20200429-93)" & ASCII.NUL; pragma Export (C, GNAT_Version, "__gnat_version"); Ada_Main_Program_Name : constant String := "_ada_main" & ASCII.NUL; pragma Export (C, Ada_Main_Program_Name, "__gnat_ada_main_program_name"); procedure adainit; pragma Export (C, adainit, "adainit"); procedure main; pragma Export (C, main, "main"); -- BEGIN ELABORATION ORDER -- ada%s -- interfaces%s -- system%s -- ada.exceptions%s -- ada.exceptions%b -- system.machine_code%s -- system.parameters%s -- system.storage_elements%s -- system.storage_elements%b -- system.secondary_stack%s -- system.secondary_stack%b -- ada.tags%s -- ada.tags%b -- system.unsigned_types%s -- system.assertions%s -- system.assertions%b -- cortex_m%s -- cortex_m_svd%s -- hal%s -- cortex_m_svd.debug%s -- nrf_svd%s -- nrf_svd.aar%s -- nrf_svd.ccm%s -- nrf_svd.clock%s -- nrf_svd.ecb%s -- nrf_svd.ficr%s -- nrf_svd.gpio%s -- nrf_svd.gpiote%s -- nrf_svd.power%s -- nrf_svd.ppi%s -- nrf_svd.qdec%s -- nrf_svd.radio%s -- nrf_svd.rng%s -- nrf_svd.rtc%s -- nrf_svd.saadc%s -- nrf_svd.spi%s -- nrf_svd.temp%s -- nrf_svd.timer%s -- nrf_svd.twi%s -- nrf_svd.uart%s -- nrf_svd.wdt%s -- hal.gpio%s -- hal.i2c%s -- hal.spi%s -- hal.time%s -- hal.uart%s -- memory_barriers%s -- memory_barriers%b -- cortex_m.nvic%s -- cortex_m.nvic%b -- nrf%s -- nrf.events%s -- nrf.events%b -- nrf.gpio%s -- nrf.gpio%b -- nrf.gpio.tasks_and_events%s -- nrf.gpio.tasks_and_events%b -- nrf.interrupts%s -- nrf.interrupts%b -- nrf.rtc%s -- nrf.rtc%b -- nrf.spi_master%s -- nrf.spi_master%b -- nrf.tasks%s -- nrf.tasks%b -- nrf.adc%s -- nrf.adc%b -- nrf.clock%s -- nrf.clock%b -- nrf.ppi%s -- nrf.ppi%b -- nrf.timers%s -- nrf.timers%b -- nrf.twi%s -- nrf.twi%b -- nrf.uart%s -- nrf.uart%b -- nrf.device%s -- nrf.device%b -- nrf52_dk%s -- nrf52_dk.ios%s -- nrf52_dk.ios%b -- nrf52_dk.time%s -- nrf52_dk.time%b -- sensor%s -- sensor%b -- main%b -- END ELABORATION ORDER end ada_main;
stcarrez/helios
Ada
1,236
ads
----------------------------------------------------------------------- -- helios-tools-formats -- Formatting utilities for the agent -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- 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.Calendar; package Helios.Tools.Formats is -- Format the date by using the given pattern. -- @see Utils.Dates.Formats function Format (Pattern : in String; Date : in Ada.Calendar.Time) return String; -- Initialize the resource bundle directory. procedure Initialize (Path : in String); end Helios.Tools.Formats;
AdaCore/libadalang
Ada
219
adb
package body Foo is procedure Put_Line (S : String) is begin null; end Put_Line; procedure Print_Int_Gen (I : Integer) is begin Put_Line (Integer'Image (I)); end Print_Int_Gen; end Foo;
reznikmm/matreshka
Ada
3,734
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- 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 XML.DOM.Attributes; package ODF.DOM.Presentation_Action_Attributes is pragma Preelaborate; type ODF_Presentation_Action_Attribute is limited interface and XML.DOM.Attributes.DOM_Attribute; type ODF_Presentation_Action_Attribute_Access is access all ODF_Presentation_Action_Attribute'Class with Storage_Size => 0; end ODF.DOM.Presentation_Action_Attributes;
jwarwick/aoc_2020
Ada
1,118
adb
with AUnit.Assertions; use AUnit.Assertions; with Ada.Text_IO; package body Day.Test is procedure Test_Part1 (T : in out AUnit.Test_Cases.Test_Case'Class) is pragma Unreferenced (T); t1 : constant Natural := combat("test1.txt"); begin Assert(t1 = 306, "Wrong number, expected 306, got" & t1'IMAGE); end Test_Part1; procedure Test_Part2 (T : in out AUnit.Test_Cases.Test_Case'Class) is pragma Unreferenced (T); t1 : constant Natural := recursive_combat("test1.txt"); t2 : constant Natural := recursive_combat("test2.txt"); begin Ada.Text_IO.put_line("Infinite game ended" & t2'IMAGE); Assert(t1 = 291, "Wrong number, expected 291, got" & t1'IMAGE); end Test_Part2; function Name (T : Test) return AUnit.Message_String is pragma Unreferenced (T); begin return AUnit.Format ("Test Day package"); end Name; procedure Register_Tests (T : in out Test) is use AUnit.Test_Cases.Registration; begin Register_Routine (T, Test_Part1'Access, "Test Part 1"); Register_Routine (T, Test_Part2'Access, "Test Part 2"); end Register_Tests; end Day.Test;
hergin/ada2fuml
Ada
431
ads
with Globals_Example1; package Md_Example4 is type T is tagged record Attribute : Globals_Example1.Itype; end record; -- Ada Rules state that all tagged operations must be defined here function Unrelated (The_I : Globals_Example1.Itype) return Globals_Example1.Itype; -- No tagged operations can be defined here because the previous -- function dosn't involve the tagged type. end Md_Example4;
Tim-Tom/scratch
Ada
1,300
adb
with Ada.Sequential_IO; with Expressions; use Expressions; procedure RandomArt is type Byte is mod 256; for Byte'Size use 8; package Byte_IO is new Ada.Sequential_IO(Byte); Scale : constant := 150; Size : constant := 2*Scale + 1; procedure GreyScale(node : not null Expression_Node_Access) is file : Byte_IO.File_Type; filename : constant String := "test.pgm"; header : constant String := "P5 301 301 255"; begin Byte_IO.Create(File => file, Name => filename); for i in header'Range loop Byte_IO.Write(file, Byte(Character'Pos(header(i)))); end loop; Byte_IO.Write(file, 10); -- newline for yi in -Scale .. Scale loop for xi in -Scale .. Scale loop declare x : constant Expression_Value := Float(xi) / Float(Scale); y : constant Expression_Value := Float(yi) / Float(Scale); intensity : constant Byte := Byte(127.5 + 127.5*Evaluate_Expression(node, x, y)); begin Byte_IO.Write(file, intensity); end; end loop; end loop; end GreyScale; gen : Rand.Generator; root : Expression_Node_Access; begin Rand.reset(gen); root := Build_Expression_tree(10, gen); GreyScale(root); end RandomArt;
reznikmm/matreshka
Ada
3,481
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Web Framework -- -- -- -- Web API Definition -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2016, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ -- This is root package to expose XMLHttpRequest API to Ada applications. package WebAPI.XHR is pragma Preelaborate; end WebAPI.XHR;
reznikmm/matreshka
Ada
6,901
adb
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- 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 Matreshka.DOM_Documents; with Matreshka.ODF_String_Constants; with ODF.DOM.Iterators; with ODF.DOM.Visitors; package body Matreshka.ODF_Table.Label_Range_Elements is ------------ -- Create -- ------------ overriding function Create (Parameters : not null access Matreshka.DOM_Elements.Element_L2_Parameters) return Table_Label_Range_Element_Node is begin return Self : Table_Label_Range_Element_Node do Matreshka.ODF_Table.Constructors.Initialize (Self'Unchecked_Access, Parameters.Document, Matreshka.ODF_String_Constants.Table_Prefix); end return; end Create; ---------------- -- Enter_Node -- ---------------- overriding procedure Enter_Node (Self : not null access Table_Label_Range_Element_Node; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control) is begin if Visitor in ODF.DOM.Visitors.Abstract_ODF_Visitor'Class then ODF.DOM.Visitors.Abstract_ODF_Visitor'Class (Visitor).Enter_Table_Label_Range (ODF.DOM.Table_Label_Range_Elements.ODF_Table_Label_Range_Access (Self), Control); else Matreshka.DOM_Elements.Abstract_Element_Node (Self.all).Enter_Node (Visitor, Control); end if; end Enter_Node; -------------------- -- Get_Local_Name -- -------------------- overriding function Get_Local_Name (Self : not null access constant Table_Label_Range_Element_Node) return League.Strings.Universal_String is pragma Unreferenced (Self); begin return Matreshka.ODF_String_Constants.Label_Range_Element; end Get_Local_Name; ---------------- -- Leave_Node -- ---------------- overriding procedure Leave_Node (Self : not null access Table_Label_Range_Element_Node; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control) is begin if Visitor in ODF.DOM.Visitors.Abstract_ODF_Visitor'Class then ODF.DOM.Visitors.Abstract_ODF_Visitor'Class (Visitor).Leave_Table_Label_Range (ODF.DOM.Table_Label_Range_Elements.ODF_Table_Label_Range_Access (Self), Control); else Matreshka.DOM_Elements.Abstract_Element_Node (Self.all).Leave_Node (Visitor, Control); end if; end Leave_Node; ---------------- -- Visit_Node -- ---------------- overriding procedure Visit_Node (Self : not null access Table_Label_Range_Element_Node; Iterator : in out XML.DOM.Visitors.Abstract_Iterator'Class; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control) is begin if Iterator in ODF.DOM.Iterators.Abstract_ODF_Iterator'Class then ODF.DOM.Iterators.Abstract_ODF_Iterator'Class (Iterator).Visit_Table_Label_Range (Visitor, ODF.DOM.Table_Label_Range_Elements.ODF_Table_Label_Range_Access (Self), Control); else Matreshka.DOM_Elements.Abstract_Element_Node (Self.all).Visit_Node (Iterator, Visitor, Control); end if; end Visit_Node; begin Matreshka.DOM_Documents.Register_Element (Matreshka.ODF_String_Constants.Table_URI, Matreshka.ODF_String_Constants.Label_Range_Element, Table_Label_Range_Element_Node'Tag); end Matreshka.ODF_Table.Label_Range_Elements;
reznikmm/matreshka
Ada
4,691
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- 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 XML.DOM.Visitors; with ODF.DOM.Db_Table_Type_Elements; package Matreshka.ODF_Db.Table_Type_Elements is type Db_Table_Type_Element_Node is new Matreshka.ODF_Db.Abstract_Db_Element_Node and ODF.DOM.Db_Table_Type_Elements.ODF_Db_Table_Type with null record; overriding function Create (Parameters : not null access Matreshka.DOM_Elements.Element_L2_Parameters) return Db_Table_Type_Element_Node; overriding function Get_Local_Name (Self : not null access constant Db_Table_Type_Element_Node) return League.Strings.Universal_String; overriding procedure Enter_Node (Self : not null access Db_Table_Type_Element_Node; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control); overriding procedure Leave_Node (Self : not null access Db_Table_Type_Element_Node; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control); overriding procedure Visit_Node (Self : not null access Db_Table_Type_Element_Node; Iterator : in out XML.DOM.Visitors.Abstract_Iterator'Class; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control); end Matreshka.ODF_Db.Table_Type_Elements;
reznikmm/matreshka
Ada
4,227
adb
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2013, Vadim Godunko <[email protected]> -- -- 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 Matreshka.DOM_Nodes; with XML.DOM.Elements.Internals; package body ODF.DOM.Elements.Style.Tab_Stops.Internals is ------------ -- Create -- ------------ function Create (Node : Matreshka.ODF_Elements.Style.Tab_Stops.Style_Tab_Stops_Access) return ODF.DOM.Elements.Style.Tab_Stops.ODF_Style_Tab_Stops is begin return (XML.DOM.Elements.Internals.Create (Matreshka.DOM_Nodes.Element_Access (Node)) with null record); end Create; ---------- -- Wrap -- ---------- function Wrap (Node : Matreshka.ODF_Elements.Style.Tab_Stops.Style_Tab_Stops_Access) return ODF.DOM.Elements.Style.Tab_Stops.ODF_Style_Tab_Stops is begin return (XML.DOM.Elements.Internals.Wrap (Matreshka.DOM_Nodes.Element_Access (Node)) with null record); end Wrap; end ODF.DOM.Elements.Style.Tab_Stops.Internals;
docandrew/troodon
Ada
342
ads
pragma Ada_2012; pragma Style_Checks (Off); with Interfaces.C; use Interfaces.C; with bits_types_u_sigset_t_h; package bits_types_sigset_t_h is -- A set of signals to be blocked, unblocked, or waited for. subtype sigset_t is bits_types_u_sigset_t_h.uu_sigset_t; -- /usr/include/bits/types/sigset_t.h:7 end bits_types_sigset_t_h;
reznikmm/markdown
Ada
2,574
adb
-- SPDX-FileCopyrightText: 2020 Max Reznik <[email protected]> -- -- SPDX-License-Identifier: MIT ---------------------------------------------------------------- with League.Regexps; with Markdown.Visitors; package body Markdown.ATX_Headings is Prefix : constant League.Regexps.Regexp_Pattern := League.Regexps.Compile (League.Strings.To_Universal_String ("^\ {0,3}(\#{1,6})(\ |$)")); Suffix : constant League.Regexps.Regexp_Pattern := League.Regexps.Compile (League.Strings.To_Universal_String ("\ +\#*\ *$")); ------------ -- Create -- ------------ overriding function Create (Line : not null access Markdown.Blocks.Text_Line) return ATX_Heading is Prefix_Match : constant League.Regexps.Regexp_Match := Prefix.Find_Match (Line.Line); Suffix_Match : constant League.Regexps.Regexp_Match := Suffix.Find_Match (Line.Line); begin pragma Assert (Prefix_Match.Is_Matched); return Result : ATX_Heading do Result.Level := 1 + Prefix_Match.Last_Index (1) - Prefix_Match.First_Index (1); if Suffix_Match.Is_Matched and then Suffix_Match.Last_Index >= Suffix_Match.First_Index then Result.Title := Line.Line.Slice (Prefix_Match.Last_Index + 1, Suffix_Match.First_Index - 1); else Result.Title := Line.Line.Tail_From (Prefix_Match.Last_Index + 1); end if; Line.Line.Clear; end return; end Create; ------------ -- Filter -- ------------ procedure Filter (Line : Markdown.Blocks.Text_Line; Tag : in out Ada.Tags.Tag; CIP : out Can_Interrupt_Paragraph) is Prefix_Match : constant League.Regexps.Regexp_Match := Prefix.Find_Match (Line.Line); begin if Prefix_Match.Is_Matched then Tag := ATX_Heading'Tag; CIP := True; end if; end Filter; ----------- -- Level -- ----------- function Level (Self : ATX_Heading'Class) return Heading_Level is begin return Self.Level; end Level; ----------- -- Title -- ----------- function Title (Self : ATX_Heading'Class) return League.Strings.Universal_String is begin return Self.Title; end Title; ----------- -- Visit -- ----------- overriding procedure Visit (Self : in out ATX_Heading; Visitor : in out Markdown.Visitors.Visitor'Class) is begin Visitor.ATX_Heading (Self); end Visit; end Markdown.ATX_Headings;
zhmu/ananas
Ada
33,982
adb
------------------------------------------------------------------------------ -- -- -- GNAT LIBRARY COMPONENTS -- -- -- -- ADA.CONTAINERS.RED_BLACK_TREES.GENERIC_BOUNDED_OPERATIONS -- -- -- -- B o d y -- -- -- -- Copyright (C) 2004-2022, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- This unit was originally developed by Matthew J Heaney. -- ------------------------------------------------------------------------------ -- The references in this file to "CLR" refer to the following book, from -- which several of the algorithms here were adapted: -- Introduction to Algorithms -- by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest -- Publisher: The MIT Press (June 18, 1990) -- ISBN: 0262031418 with System; use type System.Address; package body Ada.Containers.Red_Black_Trees.Generic_Bounded_Operations is pragma Warnings (Off, "variable ""Busy*"" is not referenced"); pragma Warnings (Off, "variable ""Lock*"" is not referenced"); -- See comment in Ada.Containers.Helpers ----------------------- -- Local Subprograms -- ----------------------- procedure Delete_Fixup (Tree : in out Tree_Type'Class; Node : Count_Type); procedure Delete_Swap (Tree : in out Tree_Type'Class; Z, Y : Count_Type); procedure Left_Rotate (Tree : in out Tree_Type'Class; X : Count_Type); procedure Right_Rotate (Tree : in out Tree_Type'Class; Y : Count_Type); ---------------- -- Clear_Tree -- ---------------- procedure Clear_Tree (Tree : in out Tree_Type'Class) is begin TC_Check (Tree.TC); Tree.First := 0; Tree.Last := 0; Tree.Root := 0; Tree.Length := 0; Tree.Free := -1; end Clear_Tree; ------------------ -- Delete_Fixup -- ------------------ procedure Delete_Fixup (Tree : in out Tree_Type'Class; Node : Count_Type) is -- CLR p. 274 X : Count_Type; W : Count_Type; N : Nodes_Type renames Tree.Nodes; begin X := Node; while X /= Tree.Root and then Color (N (X)) = Black loop if X = Left (N (Parent (N (X)))) then W := Right (N (Parent (N (X)))); if Color (N (W)) = Red then Set_Color (N (W), Black); Set_Color (N (Parent (N (X))), Red); Left_Rotate (Tree, Parent (N (X))); W := Right (N (Parent (N (X)))); end if; if (Left (N (W)) = 0 or else Color (N (Left (N (W)))) = Black) and then (Right (N (W)) = 0 or else Color (N (Right (N (W)))) = Black) then Set_Color (N (W), Red); X := Parent (N (X)); else if Right (N (W)) = 0 or else Color (N (Right (N (W)))) = Black then -- As a condition for setting the color of the left child to -- black, the left child access value must be non-null. A -- truth table analysis shows that if we arrive here, that -- condition holds, so there's no need for an explicit test. -- The assertion is here to document what we know is true. pragma Assert (Left (N (W)) /= 0); Set_Color (N (Left (N (W))), Black); Set_Color (N (W), Red); Right_Rotate (Tree, W); W := Right (N (Parent (N (X)))); end if; Set_Color (N (W), Color (N (Parent (N (X))))); Set_Color (N (Parent (N (X))), Black); Set_Color (N (Right (N (W))), Black); Left_Rotate (Tree, Parent (N (X))); X := Tree.Root; end if; else pragma Assert (X = Right (N (Parent (N (X))))); W := Left (N (Parent (N (X)))); if Color (N (W)) = Red then Set_Color (N (W), Black); Set_Color (N (Parent (N (X))), Red); Right_Rotate (Tree, Parent (N (X))); W := Left (N (Parent (N (X)))); end if; if (Left (N (W)) = 0 or else Color (N (Left (N (W)))) = Black) and then (Right (N (W)) = 0 or else Color (N (Right (N (W)))) = Black) then Set_Color (N (W), Red); X := Parent (N (X)); else if Left (N (W)) = 0 or else Color (N (Left (N (W)))) = Black then -- As a condition for setting the color of the right child -- to black, the right child access value must be non-null. -- A truth table analysis shows that if we arrive here, that -- condition holds, so there's no need for an explicit test. -- The assertion is here to document what we know is true. pragma Assert (Right (N (W)) /= 0); Set_Color (N (Right (N (W))), Black); Set_Color (N (W), Red); Left_Rotate (Tree, W); W := Left (N (Parent (N (X)))); end if; Set_Color (N (W), Color (N (Parent (N (X))))); Set_Color (N (Parent (N (X))), Black); Set_Color (N (Left (N (W))), Black); Right_Rotate (Tree, Parent (N (X))); X := Tree.Root; end if; end if; end loop; Set_Color (N (X), Black); end Delete_Fixup; --------------------------- -- Delete_Node_Sans_Free -- --------------------------- procedure Delete_Node_Sans_Free (Tree : in out Tree_Type'Class; Node : Count_Type) is -- CLR p. 273 X, Y : Count_Type; Z : constant Count_Type := Node; N : Nodes_Type renames Tree.Nodes; begin TC_Check (Tree.TC); -- If node is not present, return (exception will be raised in caller) if Z = 0 then return; end if; pragma Assert (Tree.Length > 0); pragma Assert (Tree.Root /= 0); pragma Assert (Tree.First /= 0); pragma Assert (Tree.Last /= 0); pragma Assert (Parent (N (Tree.Root)) = 0); pragma Assert ((Tree.Length > 1) or else (Tree.First = Tree.Last and then Tree.First = Tree.Root)); pragma Assert ((Left (N (Node)) = 0) or else (Parent (N (Left (N (Node)))) = Node)); pragma Assert ((Right (N (Node)) = 0) or else (Parent (N (Right (N (Node)))) = Node)); pragma Assert (((Parent (N (Node)) = 0) and then (Tree.Root = Node)) or else ((Parent (N (Node)) /= 0) and then ((Left (N (Parent (N (Node)))) = Node) or else (Right (N (Parent (N (Node)))) = Node)))); if Left (N (Z)) = 0 then if Right (N (Z)) = 0 then if Z = Tree.First then Tree.First := Parent (N (Z)); end if; if Z = Tree.Last then Tree.Last := Parent (N (Z)); end if; if Color (N (Z)) = Black then Delete_Fixup (Tree, Z); end if; pragma Assert (Left (N (Z)) = 0); pragma Assert (Right (N (Z)) = 0); if Z = Tree.Root then pragma Assert (Tree.Length = 1); pragma Assert (Parent (N (Z)) = 0); Tree.Root := 0; elsif Z = Left (N (Parent (N (Z)))) then Set_Left (N (Parent (N (Z))), 0); else pragma Assert (Z = Right (N (Parent (N (Z))))); Set_Right (N (Parent (N (Z))), 0); end if; else pragma Assert (Z /= Tree.Last); X := Right (N (Z)); if Z = Tree.First then Tree.First := Min (Tree, X); end if; if Z = Tree.Root then Tree.Root := X; elsif Z = Left (N (Parent (N (Z)))) then Set_Left (N (Parent (N (Z))), X); else pragma Assert (Z = Right (N (Parent (N (Z))))); Set_Right (N (Parent (N (Z))), X); end if; Set_Parent (N (X), Parent (N (Z))); if Color (N (Z)) = Black then Delete_Fixup (Tree, X); end if; end if; elsif Right (N (Z)) = 0 then pragma Assert (Z /= Tree.First); X := Left (N (Z)); if Z = Tree.Last then Tree.Last := Max (Tree, X); end if; if Z = Tree.Root then Tree.Root := X; elsif Z = Left (N (Parent (N (Z)))) then Set_Left (N (Parent (N (Z))), X); else pragma Assert (Z = Right (N (Parent (N (Z))))); Set_Right (N (Parent (N (Z))), X); end if; Set_Parent (N (X), Parent (N (Z))); if Color (N (Z)) = Black then Delete_Fixup (Tree, X); end if; else pragma Assert (Z /= Tree.First); pragma Assert (Z /= Tree.Last); Y := Next (Tree, Z); pragma Assert (Left (N (Y)) = 0); X := Right (N (Y)); if X = 0 then if Y = Left (N (Parent (N (Y)))) then pragma Assert (Parent (N (Y)) /= Z); Delete_Swap (Tree, Z, Y); Set_Left (N (Parent (N (Z))), Z); else pragma Assert (Y = Right (N (Parent (N (Y))))); pragma Assert (Parent (N (Y)) = Z); Set_Parent (N (Y), Parent (N (Z))); if Z = Tree.Root then Tree.Root := Y; elsif Z = Left (N (Parent (N (Z)))) then Set_Left (N (Parent (N (Z))), Y); else pragma Assert (Z = Right (N (Parent (N (Z))))); Set_Right (N (Parent (N (Z))), Y); end if; Set_Left (N (Y), Left (N (Z))); Set_Parent (N (Left (N (Y))), Y); Set_Right (N (Y), Z); Set_Parent (N (Z), Y); Set_Left (N (Z), 0); Set_Right (N (Z), 0); declare Y_Color : constant Color_Type := Color (N (Y)); begin Set_Color (N (Y), Color (N (Z))); Set_Color (N (Z), Y_Color); end; end if; if Color (N (Z)) = Black then Delete_Fixup (Tree, Z); end if; pragma Assert (Left (N (Z)) = 0); pragma Assert (Right (N (Z)) = 0); if Z = Right (N (Parent (N (Z)))) then Set_Right (N (Parent (N (Z))), 0); else pragma Assert (Z = Left (N (Parent (N (Z))))); Set_Left (N (Parent (N (Z))), 0); end if; else if Y = Left (N (Parent (N (Y)))) then pragma Assert (Parent (N (Y)) /= Z); Delete_Swap (Tree, Z, Y); Set_Left (N (Parent (N (Z))), X); Set_Parent (N (X), Parent (N (Z))); else pragma Assert (Y = Right (N (Parent (N (Y))))); pragma Assert (Parent (N (Y)) = Z); Set_Parent (N (Y), Parent (N (Z))); if Z = Tree.Root then Tree.Root := Y; elsif Z = Left (N (Parent (N (Z)))) then Set_Left (N (Parent (N (Z))), Y); else pragma Assert (Z = Right (N (Parent (N (Z))))); Set_Right (N (Parent (N (Z))), Y); end if; Set_Left (N (Y), Left (N (Z))); Set_Parent (N (Left (N (Y))), Y); declare Y_Color : constant Color_Type := Color (N (Y)); begin Set_Color (N (Y), Color (N (Z))); Set_Color (N (Z), Y_Color); end; end if; if Color (N (Z)) = Black then Delete_Fixup (Tree, X); end if; end if; end if; Tree.Length := Tree.Length - 1; end Delete_Node_Sans_Free; ----------------- -- Delete_Swap -- ----------------- procedure Delete_Swap (Tree : in out Tree_Type'Class; Z, Y : Count_Type) is N : Nodes_Type renames Tree.Nodes; pragma Assert (Z /= Y); pragma Assert (Parent (N (Y)) /= Z); Y_Parent : constant Count_Type := Parent (N (Y)); Y_Color : constant Color_Type := Color (N (Y)); begin Set_Parent (N (Y), Parent (N (Z))); Set_Left (N (Y), Left (N (Z))); Set_Right (N (Y), Right (N (Z))); Set_Color (N (Y), Color (N (Z))); if Tree.Root = Z then Tree.Root := Y; elsif Right (N (Parent (N (Y)))) = Z then Set_Right (N (Parent (N (Y))), Y); else pragma Assert (Left (N (Parent (N (Y)))) = Z); Set_Left (N (Parent (N (Y))), Y); end if; if Right (N (Y)) /= 0 then Set_Parent (N (Right (N (Y))), Y); end if; if Left (N (Y)) /= 0 then Set_Parent (N (Left (N (Y))), Y); end if; Set_Parent (N (Z), Y_Parent); Set_Color (N (Z), Y_Color); Set_Left (N (Z), 0); Set_Right (N (Z), 0); end Delete_Swap; ---------- -- Free -- ---------- procedure Free (Tree : in out Tree_Type'Class; X : Count_Type) is pragma Assert (X > 0); pragma Assert (X <= Tree.Capacity); N : Nodes_Type renames Tree.Nodes; -- pragma Assert (N (X).Prev >= 0); -- node is active -- Find a way to mark a node as active vs. inactive; we could -- use a special value in Color_Type for this. ??? begin -- The set container actually contains two data structures: a list for -- the "active" nodes that contain elements that have been inserted -- onto the tree, and another for the "inactive" nodes of the free -- store. -- -- We desire that merely declaring an object should have only minimal -- cost; specially, we want to avoid having to initialize the free -- store (to fill in the links), especially if the capacity is large. -- -- The head of the free list is indicated by Container.Free. If its -- value is non-negative, then the free store has been initialized -- in the "normal" way: Container.Free points to the head of the list -- of free (inactive) nodes, and the value 0 means the free list is -- empty. Each node on the free list has been initialized to point -- to the next free node (via its Parent component), and the value 0 -- means that this is the last free node. -- -- If Container.Free is negative, then the links on the free store -- have not been initialized. In this case the link values are -- implied: the free store comprises the components of the node array -- started with the absolute value of Container.Free, and continuing -- until the end of the array (Nodes'Last). -- -- ??? -- It might be possible to perform an optimization here. Suppose that -- the free store can be represented as having two parts: one -- comprising the non-contiguous inactive nodes linked together -- in the normal way, and the other comprising the contiguous -- inactive nodes (that are not linked together, at the end of the -- nodes array). This would allow us to never have to initialize -- the free store, except in a lazy way as nodes become inactive. -- When an element is deleted from the list container, its node -- becomes inactive, and so we set its Prev component to a negative -- value, to indicate that it is now inactive. This provides a useful -- way to detect a dangling cursor reference. -- The comment above is incorrect; we need some other way to -- indicate a node is inactive, for example by using a special -- Color_Type value. ??? -- N (X).Prev := -1; -- Node is deallocated (not on active list) if Tree.Free >= 0 then -- The free store has previously been initialized. All we need to -- do here is link the newly-free'd node onto the free list. Set_Parent (N (X), Tree.Free); Tree.Free := X; elsif X + 1 = abs Tree.Free then -- The free store has not been initialized, and the node becoming -- inactive immediately precedes the start of the free store. All -- we need to do is move the start of the free store back by one. Tree.Free := Tree.Free + 1; else -- The free store has not been initialized, and the node becoming -- inactive does not immediately precede the free store. Here we -- first initialize the free store (meaning the links are given -- values in the traditional way), and then link the newly-free'd -- node onto the head of the free store. -- ??? -- See the comments above for an optimization opportunity. If the -- next link for a node on the free store is negative, then this -- means the remaining nodes on the free store are physically -- contiguous, starting as the absolute value of that index value. Tree.Free := abs Tree.Free; if Tree.Free > Tree.Capacity then Tree.Free := 0; else for I in Tree.Free .. Tree.Capacity - 1 loop Set_Parent (N (I), I + 1); end loop; Set_Parent (N (Tree.Capacity), 0); end if; Set_Parent (N (X), Tree.Free); Tree.Free := X; end if; end Free; ----------------------- -- Generic_Allocate -- ----------------------- procedure Generic_Allocate (Tree : in out Tree_Type'Class; Node : out Count_Type) is N : Nodes_Type renames Tree.Nodes; begin if Tree.Free >= 0 then Node := Tree.Free; -- We always perform the assignment first, before we -- change container state, in order to defend against -- exceptions duration assignment. Set_Element (N (Node)); Tree.Free := Parent (N (Node)); else -- A negative free store value means that the links of the nodes -- in the free store have not been initialized. In this case, the -- nodes are physically contiguous in the array, starting at the -- index that is the absolute value of the Container.Free, and -- continuing until the end of the array (Nodes'Last). Node := abs Tree.Free; -- As above, we perform this assignment first, before modifying -- any container state. Set_Element (N (Node)); Tree.Free := Tree.Free - 1; end if; -- When a node is allocated from the free store, its pointer components -- (the links to other nodes in the tree) must also be initialized (to -- 0, the equivalent of null). This simplifies the post-allocation -- handling of nodes inserted into terminal positions. Set_Parent (N (Node), Parent => 0); Set_Left (N (Node), Left => 0); Set_Right (N (Node), Right => 0); end Generic_Allocate; ------------------- -- Generic_Equal -- ------------------- function Generic_Equal (Left, Right : Tree_Type'Class) return Boolean is -- Per AI05-0022, the container implementation is required to detect -- element tampering by a generic actual subprogram. Lock_Left : With_Lock (Left.TC'Unrestricted_Access); Lock_Right : With_Lock (Right.TC'Unrestricted_Access); L_Node : Count_Type; R_Node : Count_Type; begin if Left'Address = Right'Address then return True; end if; if Left.Length /= Right.Length then return False; end if; -- If the containers are empty, return a result immediately, so as to -- not manipulate the tamper bits unnecessarily. if Left.Length = 0 then return True; end if; L_Node := Left.First; R_Node := Right.First; while L_Node /= 0 loop if not Is_Equal (Left.Nodes (L_Node), Right.Nodes (R_Node)) then return False; end if; L_Node := Next (Left, L_Node); R_Node := Next (Right, R_Node); end loop; return True; end Generic_Equal; ----------------------- -- Generic_Iteration -- ----------------------- procedure Generic_Iteration (Tree : Tree_Type'Class) is procedure Iterate (P : Count_Type); ------------- -- Iterate -- ------------- procedure Iterate (P : Count_Type) is X : Count_Type := P; begin while X /= 0 loop Iterate (Left (Tree.Nodes (X))); Process (X); X := Right (Tree.Nodes (X)); end loop; end Iterate; -- Start of processing for Generic_Iteration begin Iterate (Tree.Root); end Generic_Iteration; ------------------ -- Generic_Read -- ------------------ procedure Generic_Read (Stream : not null access Root_Stream_Type'Class; Tree : in out Tree_Type'Class) is Len : Count_Type'Base; Node, Last_Node : Count_Type; N : Nodes_Type renames Tree.Nodes; begin Clear_Tree (Tree); Count_Type'Base'Read (Stream, Len); if Checks and then Len < 0 then raise Program_Error with "bad container length (corrupt stream)"; end if; if Len = 0 then return; end if; if Checks and then Len > Tree.Capacity then raise Constraint_Error with "length exceeds capacity"; end if; -- Use Unconditional_Insert_With_Hint here instead ??? Allocate (Tree, Node); pragma Assert (Node /= 0); Set_Color (N (Node), Black); Tree.Root := Node; Tree.First := Node; Tree.Last := Node; Tree.Length := 1; for J in Count_Type range 2 .. Len loop Last_Node := Node; pragma Assert (Last_Node = Tree.Last); Allocate (Tree, Node); pragma Assert (Node /= 0); Set_Color (N (Node), Red); Set_Right (N (Last_Node), Right => Node); Tree.Last := Node; Set_Parent (N (Node), Parent => Last_Node); Rebalance_For_Insert (Tree, Node); Tree.Length := Tree.Length + 1; end loop; end Generic_Read; ------------------------------- -- Generic_Reverse_Iteration -- ------------------------------- procedure Generic_Reverse_Iteration (Tree : Tree_Type'Class) is procedure Iterate (P : Count_Type); ------------- -- Iterate -- ------------- procedure Iterate (P : Count_Type) is X : Count_Type := P; begin while X /= 0 loop Iterate (Right (Tree.Nodes (X))); Process (X); X := Left (Tree.Nodes (X)); end loop; end Iterate; -- Start of processing for Generic_Reverse_Iteration begin Iterate (Tree.Root); end Generic_Reverse_Iteration; ------------------- -- Generic_Write -- ------------------- procedure Generic_Write (Stream : not null access Root_Stream_Type'Class; Tree : Tree_Type'Class) is procedure Process (Node : Count_Type); pragma Inline (Process); procedure Iterate is new Generic_Iteration (Process); ------------- -- Process -- ------------- procedure Process (Node : Count_Type) is begin Write_Node (Stream, Tree.Nodes (Node)); end Process; -- Start of processing for Generic_Write begin Count_Type'Base'Write (Stream, Tree.Length); Iterate (Tree); end Generic_Write; ----------------- -- Left_Rotate -- ----------------- procedure Left_Rotate (Tree : in out Tree_Type'Class; X : Count_Type) is -- CLR p. 266 N : Nodes_Type renames Tree.Nodes; Y : constant Count_Type := Right (N (X)); pragma Assert (Y /= 0); begin Set_Right (N (X), Left (N (Y))); if Left (N (Y)) /= 0 then Set_Parent (N (Left (N (Y))), X); end if; Set_Parent (N (Y), Parent (N (X))); if X = Tree.Root then Tree.Root := Y; elsif X = Left (N (Parent (N (X)))) then Set_Left (N (Parent (N (X))), Y); else pragma Assert (X = Right (N (Parent (N (X))))); Set_Right (N (Parent (N (X))), Y); end if; Set_Left (N (Y), X); Set_Parent (N (X), Y); end Left_Rotate; --------- -- Max -- --------- function Max (Tree : Tree_Type'Class; Node : Count_Type) return Count_Type is -- CLR p. 248 X : Count_Type := Node; Y : Count_Type; begin loop Y := Right (Tree.Nodes (X)); if Y = 0 then return X; end if; X := Y; end loop; end Max; --------- -- Min -- --------- function Min (Tree : Tree_Type'Class; Node : Count_Type) return Count_Type is -- CLR p. 248 X : Count_Type := Node; Y : Count_Type; begin loop Y := Left (Tree.Nodes (X)); if Y = 0 then return X; end if; X := Y; end loop; end Min; ---------- -- Next -- ---------- function Next (Tree : Tree_Type'Class; Node : Count_Type) return Count_Type is begin -- CLR p. 249 if Node = 0 then return 0; end if; if Right (Tree.Nodes (Node)) /= 0 then return Min (Tree, Right (Tree.Nodes (Node))); end if; declare X : Count_Type := Node; Y : Count_Type := Parent (Tree.Nodes (Node)); begin while Y /= 0 and then X = Right (Tree.Nodes (Y)) loop X := Y; Y := Parent (Tree.Nodes (Y)); end loop; return Y; end; end Next; -------------- -- Previous -- -------------- function Previous (Tree : Tree_Type'Class; Node : Count_Type) return Count_Type is begin if Node = 0 then return 0; end if; if Left (Tree.Nodes (Node)) /= 0 then return Max (Tree, Left (Tree.Nodes (Node))); end if; declare X : Count_Type := Node; Y : Count_Type := Parent (Tree.Nodes (Node)); begin while Y /= 0 and then X = Left (Tree.Nodes (Y)) loop X := Y; Y := Parent (Tree.Nodes (Y)); end loop; return Y; end; end Previous; -------------------------- -- Rebalance_For_Insert -- -------------------------- procedure Rebalance_For_Insert (Tree : in out Tree_Type'Class; Node : Count_Type) is -- CLR p. 268 N : Nodes_Type renames Tree.Nodes; X : Count_Type := Node; pragma Assert (X /= 0); pragma Assert (Color (N (X)) = Red); Y : Count_Type; begin while X /= Tree.Root and then Color (N (Parent (N (X)))) = Red loop if Parent (N (X)) = Left (N (Parent (N (Parent (N (X)))))) then Y := Right (N (Parent (N (Parent (N (X)))))); if Y /= 0 and then Color (N (Y)) = Red then Set_Color (N (Parent (N (X))), Black); Set_Color (N (Y), Black); Set_Color (N (Parent (N (Parent (N (X))))), Red); X := Parent (N (Parent (N (X)))); else if X = Right (N (Parent (N (X)))) then X := Parent (N (X)); Left_Rotate (Tree, X); end if; Set_Color (N (Parent (N (X))), Black); Set_Color (N (Parent (N (Parent (N (X))))), Red); Right_Rotate (Tree, Parent (N (Parent (N (X))))); end if; else pragma Assert (Parent (N (X)) = Right (N (Parent (N (Parent (N (X))))))); Y := Left (N (Parent (N (Parent (N (X)))))); if Y /= 0 and then Color (N (Y)) = Red then Set_Color (N (Parent (N (X))), Black); Set_Color (N (Y), Black); Set_Color (N (Parent (N (Parent (N (X))))), Red); X := Parent (N (Parent (N (X)))); else if X = Left (N (Parent (N (X)))) then X := Parent (N (X)); Right_Rotate (Tree, X); end if; Set_Color (N (Parent (N (X))), Black); Set_Color (N (Parent (N (Parent (N (X))))), Red); Left_Rotate (Tree, Parent (N (Parent (N (X))))); end if; end if; end loop; Set_Color (N (Tree.Root), Black); end Rebalance_For_Insert; ------------------ -- Right_Rotate -- ------------------ procedure Right_Rotate (Tree : in out Tree_Type'Class; Y : Count_Type) is N : Nodes_Type renames Tree.Nodes; X : constant Count_Type := Left (N (Y)); pragma Assert (X /= 0); begin Set_Left (N (Y), Right (N (X))); if Right (N (X)) /= 0 then Set_Parent (N (Right (N (X))), Y); end if; Set_Parent (N (X), Parent (N (Y))); if Y = Tree.Root then Tree.Root := X; elsif Y = Left (N (Parent (N (Y)))) then Set_Left (N (Parent (N (Y))), X); else pragma Assert (Y = Right (N (Parent (N (Y))))); Set_Right (N (Parent (N (Y))), X); end if; Set_Right (N (X), Y); Set_Parent (N (Y), X); end Right_Rotate; --------- -- Vet -- --------- function Vet (Tree : Tree_Type'Class; Index : Count_Type) return Boolean is Nodes : Nodes_Type renames Tree.Nodes; Node : Node_Type renames Nodes (Index); begin if Parent (Node) = Index or else Left (Node) = Index or else Right (Node) = Index then return False; end if; if Tree.Length = 0 or else Tree.Root = 0 or else Tree.First = 0 or else Tree.Last = 0 then return False; end if; if Parent (Nodes (Tree.Root)) /= 0 then return False; end if; if Left (Nodes (Tree.First)) /= 0 then return False; end if; if Right (Nodes (Tree.Last)) /= 0 then return False; end if; if Tree.Length = 1 then if Tree.First /= Tree.Last or else Tree.First /= Tree.Root then return False; end if; if Index /= Tree.First then return False; end if; if Parent (Node) /= 0 or else Left (Node) /= 0 or else Right (Node) /= 0 then return False; end if; return True; end if; if Tree.First = Tree.Last then return False; end if; if Tree.Length = 2 then if Tree.First /= Tree.Root and then Tree.Last /= Tree.Root then return False; end if; if Tree.First /= Index and then Tree.Last /= Index then return False; end if; end if; if Left (Node) /= 0 and then Parent (Nodes (Left (Node))) /= Index then return False; end if; if Right (Node) /= 0 and then Parent (Nodes (Right (Node))) /= Index then return False; end if; if Parent (Node) = 0 then if Tree.Root /= Index then return False; end if; elsif Left (Nodes (Parent (Node))) /= Index and then Right (Nodes (Parent (Node))) /= Index then return False; end if; return True; end Vet; end Ada.Containers.Red_Black_Trees.Generic_Bounded_Operations;
zhmu/ananas
Ada
134
adb
-- { dg-do compile } -- { dg-excess-errors "instantiation abandoned" } with Incomplete1; package body Incomplete2 is end Incomplete2;
zhmu/ananas
Ada
2,801
adb
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- S Y S T E M . T R A C E B A C K _ E N T R I E S -- -- -- -- B o d y -- -- -- -- Copyright (C) 2003-2022, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ package body System.Traceback_Entries is ------------ -- PC_For -- ------------ function PC_For (TB_Entry : Traceback_Entry) return System.Address is begin return TB_Entry; end PC_For; ------------------ -- TB_Entry_For -- ------------------ function TB_Entry_For (PC : System.Address) return Traceback_Entry is begin return PC; end TB_Entry_For; end System.Traceback_Entries;