content
stringlengths
23
1.05M
---------------------------------------- -- Copyright (C) 2019 Dmitriy Shadrin -- -- All rights reserved. -- ---------------------------------------- with Pal; use Pal; with Ada.Finalization; with ConfigTree; with Logging; -------------------------------------------------------------------------------- package Proxy is ----------------------------------------------------------------------------- type Configurator is limited private; type ConfiguratorPtr is access Configurator; function GetChild (ptr : in out Configurator; path : in String) return ConfigTree.NodePtr; function GetValue (ptr : in out Configurator; path : in String; default : in String := "") return String; ----------------------------------------------------------------------------- type Manager is tagged limited private; type ManagerPtr is access all Manager; ----------------------------------------------------------------------------- function GetManager return ManagerPtr with inline; function GetConfig return ConfiguratorPtr with inline; function GetLogger return Logging.LoggerPtr with inline; procedure DeleteManager with inline; procedure Start (Object : in out Manager); private mgrPtr : ManagerPtr; --------------------------------- -- Configurator declaration -- --------------------------------- type Configurator is new Ada.Finalization.Limited_Controlled with record data : ConfigTree.Tree; end record; procedure Initialize (Object : in out Configurator); procedure Finalize (Object : in out Configurator); --------------------------------- -- Manager declaration -- --------------------------------- type Manager is new Ada.Finalization.Limited_Controlled with record config : ConfiguratorPtr; logger : Logging.LoggerPtr; end record; procedure Initialize (Object : in out Manager); procedure Finalize (Object : in out Manager); end Proxy;
-- Abstract : -- -- A simple bounded sorted vector of definite items, in Spark. -- -- Copyright (C) 2018 - 2020 Free Software Foundation, Inc. -- -- This library is free software; you can redistribute it and/or modify it -- under terms of the GNU General Public License as published by the Free -- Software Foundation; either version 3, or (at your option) any later -- version. This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN- -- TABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- As a special exception under Section 7 of GPL version 3, you are granted -- additional permissions described in the GCC Runtime Library Exception, -- version 3.1, as published by the Free Software Foundation. pragma License (Modified_GPL); generic type Element_Type is private; with function Element_Compare (Left, Right : in Element_Type) return Compare_Result; Capacity : in Ada.Containers.Count_Type; package SAL.Gen_Bounded_Definite_Vectors_Sorted with Spark_Mode is use all type Ada.Containers.Count_Type; No_Index : constant Base_Peek_Type := 0; type Vector is private with Default_Initial_Condition => Last_Index (Vector) = No_Index; function Length (Container : in Vector) return Ada.Containers.Count_Type with Post => Length'Result in 0 .. Capacity; function Is_Full (Container : in Vector) return Boolean with Post => Is_Full'Result = (Length (Container) = Capacity); procedure Clear (Container : in out Vector) with Post => Last_Index (Container) = No_Index; function First_Index (Container : in Vector) return Peek_Type is (Peek_Type'First) with Depends => (First_Index'Result => null, null => Container); function Last_Index (Container : in Vector) return Base_Peek_Type with Inline; function Element (Container : in Vector; Index : in Peek_Type) return Element_Type with Pre => Index in First_Index (Container) .. Last_Index (Container); function Is_Sorted (Container : in Vector) return Boolean is -- See comment on similar Is_Sorted below (for all I in First_Index (Container) .. Last_Index (Container) - 1 => (for all J in I + 1 .. Last_Index (Container) => Element_Compare (Element (Container, I), Element (Container, J)) in Less | Equal)); procedure Insert (Container : in out Vector; New_Item : in Element_Type; Ignore_If_Equal : in Boolean := False) with Pre => Last_Index (Container) < Peek_Type (Capacity), Post => Is_Sorted (Container) and (if Ignore_If_Equal then (Last_Index (Container) = Last_Index (Container'Old) or Last_Index (Container) = Last_Index (Container'Old) + 1) else Last_Index (Container) = Last_Index (Container'Old) + 1); -- Insert New_Item in sorted position. Items are sorted in increasing -- order according to Element_Compare. New_Item is inserted after -- Equal items, unless Ignore_If_Equal is true, in which case -- New_Item is not inserted. private type Array_Type is array (Peek_Type range 1 .. Peek_Type (Capacity)) of aliased Element_Type; function Is_Sorted (Container : in Array_Type; Last : in Base_Peek_Type) return Boolean -- This is too hard for gnatprove (in 2019): -- is (for all I in Container'First .. Last - 1 => -- Element_Compare (Container (I), Container (I + 1)) in Less | Equal) -- This works: is (for all I in Container'First .. Last - 1 => (for all J in I + 1 .. Last => Element_Compare (Container (I), Container (J)) in Less | Equal)) with Pre => Last <= Container'Last; subtype Index_Type is Base_Peek_Type range No_Index .. Base_Peek_Type (Capacity); -- Helps with proofs type Vector is record Elements : Array_Type; Last : Index_Type := No_Index; end record with Type_Invariant => Last <= Elements'Last and Is_Sorted (Vector.Elements, Vector.Last); pragma Annotate (GNATprove, Intentional, "type ""Vector"" is not fully initialized", "Only items in Elements with index <= Last are accessed"); end SAL.Gen_Bounded_Definite_Vectors_Sorted;
with Ada.Text_IO; use Ada.Text_IO; with Ada.Text_IO.Text_Streams; use Ada.Text_IO.Text_Streams; with Editor_Package; use Editor_Package; package body Utilities_Package is function Read_File (Name : Unbounded_String; V : View) return Boolean is Input : File_Type; BFFR : Character; begin Open (File => Input, Mode => In_File, Name => To_String (Name)); loop BFFR := Character'Input (Stream (Input)); Put (BFFR); exit when End_Of_File; end loop; Close (Input); return True; exception when End_Error => if Is_Open (Input) then Close (Input); end if; return False; when Name_Error => Put_Line ("No such file"); return False; end Read_File; end Utilities_Package;
-- This package has been generated automatically by GNATtest. -- You are allowed to add your code to the bodies of test routines. -- Such changes will be kept during further regeneration of this file. -- All code placed outside of test routine bodies will be lost. The -- code intended to set up and tear down the test environment should be -- placed into Messages.Test_Data. with AUnit.Assertions; use AUnit.Assertions; with System.Assertions; -- begin read only -- id:2.2/00/ -- -- This section can be used to add with clauses if necessary. -- -- end read only -- begin read only -- end read only package body Messages.Test_Data.Tests is -- begin read only -- id:2.2/01/ -- -- This section can be used to add global variables and other elements. -- -- end read only -- begin read only -- end read only -- begin read only function Wrap_Test_FormatedTime_5bb1ad_97dea1 (Time: Date_Record := Game_Date) return String is begin begin pragma Assert(True); null; exception when System.Assertions.Assert_Failure => AUnit.Assertions.Assert (False, "req_sloc(messages.ads:0):Test_FormattedTime test requirement violated"); end; declare Test_FormatedTime_5bb1ad_97dea1_Result: constant String := GNATtest_Generated.GNATtest_Standard.Messages.FormatedTime(Time); begin begin pragma Assert(Test_FormatedTime_5bb1ad_97dea1_Result'Length > 0); null; exception when System.Assertions.Assert_Failure => AUnit.Assertions.Assert (False, "ens_sloc(messages.ads:0:):Test_FormattedTime test commitment violated"); end; return Test_FormatedTime_5bb1ad_97dea1_Result; end; end Wrap_Test_FormatedTime_5bb1ad_97dea1; -- end read only -- begin read only procedure Test_FormatedTime_test_formattedtime(Gnattest_T: in out Test); procedure Test_FormatedTime_5bb1ad_97dea1(Gnattest_T: in out Test) renames Test_FormatedTime_test_formattedtime; -- id:2.2/5bb1ad5dbd52690f/FormatedTime/1/0/test_formattedtime/ procedure Test_FormatedTime_test_formattedtime(Gnattest_T: in out Test) is function FormatedTime (Time: Date_Record := Game_Date) return String renames Wrap_Test_FormatedTime_5bb1ad_97dea1; -- end read only pragma Unreferenced(Gnattest_T); begin Assert(FormatedTime /= "", "Failed to get formated game time."); -- begin read only end Test_FormatedTime_test_formattedtime; -- end read only -- begin read only procedure Wrap_Test_AddMessage_508d2e_c15a00 (Message: String; MType: Message_Type; Color: Message_Color := WHITE) is begin begin pragma Assert(Message'Length > 0); null; exception when System.Assertions.Assert_Failure => AUnit.Assertions.Assert (False, "req_sloc(messages.ads:0):Test_AddMessage test requirement violated"); end; GNATtest_Generated.GNATtest_Standard.Messages.AddMessage (Message, MType, Color); begin pragma Assert(True); null; exception when System.Assertions.Assert_Failure => AUnit.Assertions.Assert (False, "ens_sloc(messages.ads:0:):Test_AddMessage test commitment violated"); end; end Wrap_Test_AddMessage_508d2e_c15a00; -- end read only -- begin read only procedure Test_AddMessage_test_addmessage(Gnattest_T: in out Test); procedure Test_AddMessage_508d2e_c15a00(Gnattest_T: in out Test) renames Test_AddMessage_test_addmessage; -- id:2.2/508d2ebb71c5d14a/AddMessage/1/0/test_addmessage/ procedure Test_AddMessage_test_addmessage(Gnattest_T: in out Test) is procedure AddMessage (Message: String; MType: Message_Type; Color: Message_Color := WHITE) renames Wrap_Test_AddMessage_508d2e_c15a00; -- end read only pragma Unreferenced(Gnattest_T); Amount: constant Natural := MessagesAmount; begin AddMessage("Test message.", Default); Assert(Amount < MessagesAmount, "Failed to add new message."); -- begin read only end Test_AddMessage_test_addmessage; -- end read only -- begin read only function Wrap_Test_GetMessage_56cd5a_0b2a8d (MessageIndex: Integer; MType: Message_Type := Default) return Message_Data is begin declare Test_GetMessage_56cd5a_0b2a8d_Result: constant Message_Data := GNATtest_Generated.GNATtest_Standard.Messages.GetMessage (MessageIndex, MType); begin return Test_GetMessage_56cd5a_0b2a8d_Result; end; end Wrap_Test_GetMessage_56cd5a_0b2a8d; -- end read only -- begin read only procedure Test_GetMessage_test_getmessage(Gnattest_T: in out Test); procedure Test_GetMessage_56cd5a_0b2a8d(Gnattest_T: in out Test) renames Test_GetMessage_test_getmessage; -- id:2.2/56cd5ac704cead2b/GetMessage/1/0/test_getmessage/ procedure Test_GetMessage_test_getmessage(Gnattest_T: in out Test) is function GetMessage (MessageIndex: Integer; MType: Message_Type := Default) return Message_Data renames Wrap_Test_GetMessage_56cd5a_0b2a8d; -- end read only pragma Unreferenced(Gnattest_T); begin Assert (GetMessage(1).Message /= Null_Unbounded_String, "Failed to get message."); Assert (GetMessage(1_000).Message = Null_Unbounded_String, "Failed to not get non-existing message."); -- begin read only end Test_GetMessage_test_getmessage; -- end read only -- begin read only procedure Wrap_Test_ClearMessages_aeb026_267040 is begin GNATtest_Generated.GNATtest_Standard.Messages.ClearMessages; end Wrap_Test_ClearMessages_aeb026_267040; -- end read only -- begin read only procedure Test_ClearMessages_test_clearmessages(Gnattest_T: in out Test); procedure Test_ClearMessages_aeb026_267040(Gnattest_T: in out Test) renames Test_ClearMessages_test_clearmessages; -- id:2.2/aeb0266c09a96d71/ClearMessages/1/0/test_clearmessages/ procedure Test_ClearMessages_test_clearmessages(Gnattest_T: in out Test) is procedure ClearMessages renames Wrap_Test_ClearMessages_aeb026_267040; -- end read only pragma Unreferenced(Gnattest_T); begin ClearMessages; Assert(MessagesAmount = 0, "Failed to clear all messages."); AddMessage("Test message.", Default); -- begin read only end Test_ClearMessages_test_clearmessages; -- end read only -- begin read only function Wrap_Test_MessagesAmount_922f17_8e4cbf (MType: Message_Type := Default) return Natural is begin declare Test_MessagesAmount_922f17_8e4cbf_Result: constant Natural := GNATtest_Generated.GNATtest_Standard.Messages.MessagesAmount(MType); begin return Test_MessagesAmount_922f17_8e4cbf_Result; end; end Wrap_Test_MessagesAmount_922f17_8e4cbf; -- end read only -- begin read only procedure Test_MessagesAmount_test_messagesamount(Gnattest_T: in out Test); procedure Test_MessagesAmount_922f17_8e4cbf(Gnattest_T: in out Test) renames Test_MessagesAmount_test_messagesamount; -- id:2.2/922f1712ec778778/MessagesAmount/1/0/test_messagesamount/ procedure Test_MessagesAmount_test_messagesamount (Gnattest_T: in out Test) is function MessagesAmount (MType: Message_Type := Default) return Natural renames Wrap_Test_MessagesAmount_922f17_8e4cbf; -- end read only pragma Unreferenced(Gnattest_T); begin Assert (MessagesAmount = Natural(Messages_List.Length), "Failed to count properly amount of messages."); -- begin read only end Test_MessagesAmount_test_messagesamount; -- end read only -- begin read only procedure Wrap_Test_RestoreMessage_c0c9bd_0f207a (Message: Unbounded_String; MType: Message_Type := Default; Color: Message_Color := WHITE) is begin begin pragma Assert(Message /= Null_Unbounded_String); null; exception when System.Assertions.Assert_Failure => AUnit.Assertions.Assert (False, "req_sloc(messages.ads:0):Test_RestoreMessage test requirement violated"); end; GNATtest_Generated.GNATtest_Standard.Messages.RestoreMessage (Message, MType, Color); begin pragma Assert(True); null; exception when System.Assertions.Assert_Failure => AUnit.Assertions.Assert (False, "ens_sloc(messages.ads:0:):Test_RestoreMessage test commitment violated"); end; end Wrap_Test_RestoreMessage_c0c9bd_0f207a; -- end read only -- begin read only procedure Test_RestoreMessage_test_restoremessage(Gnattest_T: in out Test); procedure Test_RestoreMessage_c0c9bd_0f207a(Gnattest_T: in out Test) renames Test_RestoreMessage_test_restoremessage; -- id:2.2/c0c9bd3a9b2621df/RestoreMessage/1/0/test_restoremessage/ procedure Test_RestoreMessage_test_restoremessage (Gnattest_T: in out Test) is procedure RestoreMessage (Message: Unbounded_String; MType: Message_Type := Default; Color: Message_Color := WHITE) renames Wrap_Test_RestoreMessage_c0c9bd_0f207a; -- end read only pragma Unreferenced(Gnattest_T); Amount: constant Natural := MessagesAmount; begin RestoreMessage(To_Unbounded_String("Test message")); Assert (MessagesAmount = Amount + 1, "Failed to restore the game message."); -- begin read only end Test_RestoreMessage_test_restoremessage; -- end read only -- begin read only function Wrap_Test_GetLastMessageIndex_ee1f16_517343 return Natural is begin declare Test_GetLastMessageIndex_ee1f16_517343_Result: constant Natural := GNATtest_Generated.GNATtest_Standard.Messages.GetLastMessageIndex; begin return Test_GetLastMessageIndex_ee1f16_517343_Result; end; end Wrap_Test_GetLastMessageIndex_ee1f16_517343; -- end read only -- begin read only procedure Test_GetLastMessageIndex_test_getlastmessageindex (Gnattest_T: in out Test); procedure Test_GetLastMessageIndex_ee1f16_517343 (Gnattest_T: in out Test) renames Test_GetLastMessageIndex_test_getlastmessageindex; -- id:2.2/ee1f163ccc085b43/GetLastMessageIndex/1/0/test_getlastmessageindex/ procedure Test_GetLastMessageIndex_test_getlastmessageindex (Gnattest_T: in out Test) is function GetLastMessageIndex return Natural renames Wrap_Test_GetLastMessageIndex_ee1f16_517343; -- end read only pragma Unreferenced(Gnattest_T); begin Assert (GetLastMessageIndex = Messages_List.Last_Index, "Failed to get last message index."); -- begin read only end Test_GetLastMessageIndex_test_getlastmessageindex; -- end read only -- begin read only -- id:2.2/02/ -- -- This section can be used to add elaboration code for the global state. -- begin -- end read only null; -- begin read only -- end read only end Messages.Test_Data.Tests;
with System.Unwind.Backtrace; -- implementation unit package body GNAT.Traceback is procedure Call_Chain ( Traceback : out Tracebacks_Array; Len : out Natural) is X : System.Unwind.Exception_Occurrence; T_Index : Integer; begin System.Unwind.Backtrace.Call_Chain (X); Len := Integer'Min (X.Num_Tracebacks, Traceback'Length); T_Index := Traceback'First; for I in 1 .. Len loop Traceback (T_Index) := X.Tracebacks (I); T_Index := T_Index + 1; end loop; end Call_Chain; end GNAT.Traceback;
-- Institution: AdaCore / Technische Universitaet Muenchen -- Department: * / Realtime Computer Systems (RCS) -- Project: StratoX -- Module: MPU 6000 Driver for SPI -- -- Authors: Anthony Leonardo Gracio, -- Emanuel Regnath (emanuel.regnath@tum.de) with Interfaces; use Interfaces; with Ada.Real_Time; use Ada.Real_Time; with HIL.SPI; use HIL; use type HIL.SPI.Data_Type; package MPU6000.Driver with SPARK_Mode, Abstract_State => State, Initializes => State is -- Types and subtypes -- Type used to represent teh data we want to send via I2C -- FIXME: Data_Type not allowed in SPARK?!? subtype Data_Type is HIL.SPI.Data_Type; -- Type reprensnting all the different clock sources of the MPU6000. -- See the MPU6000 register map section 4.4 for more details. type MPU6000_Clock_Source is (Internal_Clk, X_Gyro_Clk, Y_Gyro_Clk, Z_Gyro_Clk, External_32K_Clk, External_19M_Clk, Reserved_Clk, Stop_Clk); for MPU6000_Clock_Source use (Internal_Clk => 16#00#, X_Gyro_Clk => 16#01#, Y_Gyro_Clk => 16#02#, Z_Gyro_Clk => 16#03#, External_32K_Clk => 16#04#, External_19M_Clk => 16#05#, Reserved_Clk => 16#06#, Stop_Clk => 16#07#); for MPU6000_Clock_Source'Size use 3; -- Type representing the allowed full scale ranges -- for MPU6000 gyroscope. type MPU6000_FS_Gyro_Range is (MPU6000_Gyro_FS_250, MPU6000_Gyro_FS_500, MPU6000_Gyro_FS_1000, MPU6000_Gyro_FS_2000); for MPU6000_FS_Gyro_Range use (MPU6000_Gyro_FS_250 => 16#00#, MPU6000_Gyro_FS_500 => 16#01#, MPU6000_Gyro_FS_1000 => 16#02#, MPU6000_Gyro_FS_2000 => 16#03#); for MPU6000_FS_Gyro_Range'Size use 2; -- Type representing the allowed full scale ranges -- for MPU6000 accelerometer. type MPU6000_FS_Accel_Range is (MPU6000_Accel_FS_2, MPU6000_Accel_FS_4, MPU6000_Accel_FS_8, MPU6000_Accel_FS_16); for MPU6000_FS_Accel_Range use (MPU6000_Accel_FS_2 => 16#00#, MPU6000_Accel_FS_4 => 16#01#, MPU6000_Accel_FS_8 => 16#02#, MPU6000_Accel_FS_16 => 16#03#); for MPU6000_FS_Accel_Range'Size use 2; type MPU6000_DLPF_Bandwidth_Mode is (MPU6000_DLPF_BW_256, MPU6000_DLPF_BW_188, MPU6000_DLPF_BW_98, MPU6000_DLPF_BW_42, MPU6000_DLPF_BW_20, MPU6000_DLPF_BW_10, MPU6000_DLPF_BW_5); for MPU6000_DLPF_Bandwidth_Mode use (MPU6000_DLPF_BW_256 => 16#00#, MPU6000_DLPF_BW_188 => 16#01#, MPU6000_DLPF_BW_98 => 16#02#, MPU6000_DLPF_BW_42 => 16#03#, MPU6000_DLPF_BW_20 => 16#04#, MPU6000_DLPF_BW_10 => 16#05#, MPU6000_DLPF_BW_5 => 16#06#); for MPU6000_DLPF_Bandwidth_Mode'Size use 3; -- Use to convert MPU6000 registers in degrees (gyro) and G (acc). MPU6000_DEG_PER_LSB_250 : constant := (2.0 * 250.0) / 65536.0; MPU6000_DEG_PER_LSB_500 : constant := (2.0 * 500.0) / 65536.0; MPU6000_DEG_PER_LSB_1000 : constant := (2.0 * 1000.0) / 65536.0; MPU6000_DEG_PER_LSB_2000 : constant := (2.0 * 2000.0) / 65536.0; MPU6000_G_PER_LSB_2 : constant := (2.0 * 2.0) / 65536.0; MPU6000_G_PER_LSB_4 : constant := (2.0 * 4.0) / 65536.0; MPU6000_G_PER_LSB_8 : constant := (2.0 * 8.0) / 65536.0; MPU6000_G_PER_LSB_16 : constant := (2.0 * 16.0) / 65536.0; -- Procedures and functions -- Initialize the MPU6000 Device via I2C. procedure Init; -- Test if the MPU6000 is initialized and connected. function Test return Boolean; -- Test if we are connected to MPU6000 via I2C. procedure Test_Connection (success : out Boolean); -- MPU6000 self test procedure Self_Test (Test_Status : out Boolean); -- Extended test, maybe altering the config of the device procedure Self_Test_Extended (Test_Status : out Boolean); -- Reset the MPU6000 device. -- A small delay of ~50ms may be desirable after triggering a reset. procedure Reset; -- Get raw 6-axis motion sensor readings (accel/gyro). -- Retrieves all currently available motion sensor values. procedure Get_Motion_6 (Acc_X : out Integer_16; Acc_Y : out Integer_16; Acc_Z : out Integer_16; Gyro_X : out Integer_16; Gyro_Y : out Integer_16; Gyro_Z : out Integer_16); -- Set clock source setting. -- 3 bits allowed to choose the source. The different -- clock sources are enumerated in the MPU6000 register map. procedure Set_Clock_Source (Clock_Source : MPU6000_Clock_Source); -- Set digital low-pass filter configuration. procedure Set_DLPF_Mode (DLPF_Mode : MPU6000_DLPF_Bandwidth_Mode); -- Set full-scale gyroscope range. procedure Set_Full_Scale_Gyro_Range (FS_Range : MPU6000_FS_Gyro_Range); -- Set full-scale acceler range. procedure Set_Full_Scale_Accel_Range (FS_Range : MPU6000_FS_Accel_Range); -- Set I2C bypass enabled status. -- When this bit is equal to 1 and I2C_MST_EN (Register 106 bit[5]) is -- equal to 0, the host application processor -- will be able to directly access the -- auxiliary I2C bus of the MPU-60X0. When this bit is equal to 0, -- the host application processor will not be able to directly -- access the auxiliary I2C bus of the MPU-60X0 regardless of the state -- of I2C_MST_EN (Register 106 bit[5]). procedure Set_I2C_Bypass_Enabled (Value : Boolean); -- Set interrupts enabled status. procedure Set_Int_Enabled (Value : Boolean); -- Set gyroscope sample rate divider procedure Set_Rate (Rate_Div : HIL.Byte); -- Set sleep mode status. procedure Set_Sleep_Enabled (Value : Boolean); -- Set temperature sensor enabled status. procedure Set_Temp_Sensor_Enabled (Value : Boolean); -- Get temperature sensor enabled status. procedure Get_Temp_Sensor_Enabled (ret : out Boolean); private -- Global variables and constants Is_Init : Boolean := False with Part_Of => State; -- MPU6000 Device ID. MPU6000_DEVICE_ID : constant := 16#68#; -- Address pin low (GND), default for InvenSense evaluation board MPU6000_ADDRESS_AD0_LOW : constant := 16#68#; -- Address pin high (VCC) MPU6000_ADDRESS_AD0_HIGH : constant := 16#69#; MPU6000_STARTUP_TIME_MS : constant Time := Time_First + Milliseconds (1_000); -- Procedures and functions -- Evaluate the self test and print the result of this evluation -- with the given string prepended function Evaluate_Self_Test (Low : Float; High : Float; Value : Float; Debug_String : String) return Boolean; -- Read data to the specified MPU6000 register procedure Read_Register (Reg_Addr : Byte; Data : in out Data_Type); -- Read one byte at the specified MPU6000 register procedure Read_Byte_At_Register (Reg_Addr : Byte; Data : in out Byte); -- Read one but at the specified MPU6000 register procedure Read_Bit_At_Register (Reg_Addr : Byte; Bit_Pos : Unsigned_8_Bit_Index; Bit_Value : out Boolean); -- Write data to the specified MPU6000 register procedure Write_Register (Reg_Addr : Byte; Data : Data_Type); -- Write one byte at the specified MPU6000 register procedure Write_Byte_At_Register (Reg_Addr : Byte; Data : Byte); -- Write one bit at the specified MPU6000 register procedure Write_Bit_At_Register (Reg_Addr : Byte; Bit_Pos : Unsigned_8_Bit_Index; Bit_Value : Boolean); -- Write data in the specified register, starting from the -- bit specified in Start_Bit_Pos procedure Write_Bits_At_Register (Reg_Addr : Byte; Start_Bit_Pos : Unsigned_8_Bit_Index; Data : Byte; Length : Unsigned_8_Bit_Index); function Fuse_Low_And_High_Register_Parts (High : Byte; Low : Byte) return Integer_16; pragma Inline (Fuse_Low_And_High_Register_Parts); end MPU6000.Driver;
-- Copyright 2017-2021 Bartek thindil Jasicki -- -- This file is part of Steam Sky. -- -- Steam Sky is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- Steam Sky is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with Steam Sky. If not, see <http://www.gnu.org/licenses/>. --## rule off REDUCEABLE_SCOPE with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; --## rule on REDUCEABLE_SCOPE with Game; use Game; -- ****h* Utils/Utils -- FUNCTION -- Provided various uncategorized code -- SOURCE package Utils with SPARK_Mode is -- **** -- ****f* Utils/Utils.GetRandom -- FUNCTION -- Return random number from Min to Max range. This one can't be formaly -- verified as is depends on random number generator. -- PARAMETERS -- Min - Starting value from which generate random number -- Max - End value from which generate random number -- RESULT -- Random number between Min and Max -- SOURCE function Get_Random(Min, Max: Integer) return Integer with Global => null, Pre => Min <= Max, Post => Get_Random'Result in Min .. Max, Test_Case => (Name => "Test_GetRandom", Mode => Nominal); -- **** --## rule off SIMPLIFIABLE_EXPRESSIONS -- ****f* Utils/Utils.DaysDifference -- FUNCTION -- Count days difference between selected date and current game date -- PARAMETERS -- DateToCompare - In game date to compare with current game date -- RESULT -- Amount of days difference between DateToCompare and current game date -- SOURCE function Days_Difference(Date_To_Compare: Date_Record) return Integer is ((Game_Date.Day + (30 * Game_Date.Month) + (Game_Date.Year * 360)) - (Date_To_Compare.Day + (30 * Date_To_Compare.Month) + (Date_To_Compare.Year * 360))) with Global => Game_Date, Test_Case => (Name => "Test_DaysDifference", Mode => Robustness); -- **** --## rule on SIMPLIFIABLE_EXPRESSIONS -- ****f* Utils/Utils.GenerateRoboticName -- FUNCTION -- Generate robotic type name for bases, mobs, ships, etc -- RESULT -- Random robotic name -- SOURCE function Generate_Robotic_Name return Unbounded_String with Global => null, Post => Length(Source => Generate_Robotic_Name'Result) > 0, Test_Case => (Name => "Test_GenerateRoboticName", Mode => Nominal); -- **** end Utils;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- G N A T . S E R I A L _ C O M M U N I C A T I O N S -- -- -- -- B o d y -- -- -- -- Copyright (C) 2007-2019, AdaCore -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- This is the Windows implementation of this package with Ada.Streams; use Ada.Streams; with Ada.Unchecked_Deallocation; use Ada; with System; use System; with System.Communication; use System.Communication; with System.CRTL; use System.CRTL; with System.OS_Constants; with System.Win32; use System.Win32; with System.Win32.Ext; use System.Win32.Ext; with GNAT.OS_Lib; package body GNAT.Serial_Communications is package OSC renames System.OS_Constants; -- Common types type Port_Data is new HANDLE; C_Bits : constant array (Data_Bits) of Interfaces.C.unsigned := (8, 7); C_Parity : constant array (Parity_Check) of Interfaces.C.unsigned := (None => NOPARITY, Odd => ODDPARITY, Even => EVENPARITY); C_Stop_Bits : constant array (Stop_Bits_Number) of Interfaces.C.unsigned := (One => ONESTOPBIT, Two => TWOSTOPBITS); ----------- -- Files -- ----------- procedure Raise_Error (Message : String; Error : DWORD := GetLastError); pragma No_Return (Raise_Error); ----------- -- Close -- ----------- procedure Close (Port : in out Serial_Port) is procedure Unchecked_Free is new Unchecked_Deallocation (Port_Data, Port_Data_Access); Success : BOOL; begin if Port.H /= null then Success := CloseHandle (HANDLE (Port.H.all)); Unchecked_Free (Port.H); if Success = Win32.FALSE then Raise_Error ("error closing the port"); end if; end if; end Close; ---------- -- Name -- ---------- function Name (Number : Positive) return Port_Name is N_Img : constant String := Positive'Image (Number); begin if Number > 9 then return Port_Name ("\\.\COM" & N_Img (N_Img'First + 1 .. N_Img'Last)); else return Port_Name ("COM" & N_Img (N_Img'First + 1 .. N_Img'Last) & ':'); end if; end Name; ---------- -- Open -- ---------- procedure Open (Port : out Serial_Port; Name : Port_Name) is C_Name : constant String := String (Name) & ASCII.NUL; Success : BOOL; pragma Unreferenced (Success); begin if Port.H = null then Port.H := new Port_Data; else Success := CloseHandle (HANDLE (Port.H.all)); end if; Port.H.all := CreateFileA (lpFileName => C_Name (C_Name'First)'Address, dwDesiredAccess => GENERIC_READ or GENERIC_WRITE, dwShareMode => 0, lpSecurityAttributes => null, dwCreationDisposition => OPEN_EXISTING, dwFlagsAndAttributes => 0, hTemplateFile => 0); if Port.H.all = Port_Data (INVALID_HANDLE_VALUE) then Raise_Error ("cannot open com port"); end if; end Open; ----------------- -- Raise_Error -- ----------------- procedure Raise_Error (Message : String; Error : DWORD := GetLastError) is begin raise Serial_Error with Message & (if Error /= 0 then " (" & GNAT.OS_Lib.Errno_Message (Err => Integer (Error)) & ')' else ""); end Raise_Error; ---------- -- Read -- ---------- overriding procedure Read (Port : in out Serial_Port; Buffer : out Stream_Element_Array; Last : out Stream_Element_Offset) is Success : BOOL; Read_Last : aliased DWORD; begin if Port.H = null then Raise_Error ("read: port not opened", 0); end if; Success := ReadFile (hFile => HANDLE (Port.H.all), lpBuffer => Buffer (Buffer'First)'Address, nNumberOfBytesToRead => DWORD (Buffer'Length), lpNumberOfBytesRead => Read_Last'Access, lpOverlapped => null); if Success = Win32.FALSE then Raise_Error ("read error"); end if; Last := Last_Index (Buffer'First, size_t (Read_Last)); end Read; --------- -- Set -- --------- procedure Set (Port : Serial_Port; Rate : Data_Rate := B9600; Bits : Data_Bits := CS8; Stop_Bits : Stop_Bits_Number := One; Parity : Parity_Check := None; Block : Boolean := True; Local : Boolean := True; Flow : Flow_Control := None; Timeout : Duration := 10.0) is pragma Unreferenced (Local); Success : BOOL; Com_Time_Out : aliased COMMTIMEOUTS; Com_Settings : aliased DCB; begin if Port.H = null then Raise_Error ("set: port not opened", 0); end if; Success := GetCommState (HANDLE (Port.H.all), Com_Settings'Access); if Success = Win32.FALSE then Success := CloseHandle (HANDLE (Port.H.all)); Port.H.all := 0; Raise_Error ("set: cannot get comm state"); end if; Com_Settings.BaudRate := DWORD (Data_Rate_Value (Rate)); Com_Settings.fParity := 1; Com_Settings.fBinary := Bits1 (System.Win32.TRUE); Com_Settings.fOutxDsrFlow := 0; Com_Settings.fDsrSensitivity := 0; Com_Settings.fDtrControl := OSC.DTR_CONTROL_ENABLE; Com_Settings.fInX := 0; Com_Settings.fRtsControl := OSC.RTS_CONTROL_ENABLE; case Flow is when None => Com_Settings.fOutX := 0; Com_Settings.fOutxCtsFlow := 0; when RTS_CTS => Com_Settings.fOutX := 0; Com_Settings.fOutxCtsFlow := 1; when Xon_Xoff => Com_Settings.fOutX := 1; Com_Settings.fOutxCtsFlow := 0; end case; Com_Settings.fAbortOnError := 0; Com_Settings.ByteSize := BYTE (C_Bits (Bits)); Com_Settings.Parity := BYTE (C_Parity (Parity)); Com_Settings.StopBits := BYTE (C_Stop_Bits (Stop_Bits)); Success := SetCommState (HANDLE (Port.H.all), Com_Settings'Access); if Success = Win32.FALSE then Success := CloseHandle (HANDLE (Port.H.all)); Port.H.all := 0; Raise_Error ("cannot set comm state"); end if; -- Set the timeout status, to honor our spec with respect to read -- timeouts. Always disconnect write timeouts. -- Blocking reads - no timeout at all if Block then Com_Time_Out := (others => 0); -- Non-blocking reads and null timeout - immediate return with what we -- have - set ReadIntervalTimeout to MAXDWORD. elsif Timeout = 0.0 then Com_Time_Out := (ReadIntervalTimeout => DWORD'Last, others => 0); -- Non-blocking reads with timeout - set total read timeout accordingly else Com_Time_Out := (ReadTotalTimeoutConstant => DWORD (1000 * Timeout), others => 0); end if; Success := SetCommTimeouts (hFile => HANDLE (Port.H.all), lpCommTimeouts => Com_Time_Out'Access); if Success = Win32.FALSE then Raise_Error ("cannot set the timeout"); end if; end Set; ----------- -- Write -- ----------- overriding procedure Write (Port : in out Serial_Port; Buffer : Stream_Element_Array) is Success : BOOL; Temp_Last : aliased DWORD; begin if Port.H = null then Raise_Error ("write: port not opened", 0); end if; Success := WriteFile (hFile => HANDLE (Port.H.all), lpBuffer => Buffer'Address, nNumberOfBytesToWrite => DWORD (Buffer'Length), lpNumberOfBytesWritten => Temp_Last'Access, lpOverlapped => null); if Success = Win32.FALSE or else Stream_Element_Offset (Temp_Last) /= Buffer'Length then Raise_Error ("failed to write data"); end if; end Write; end GNAT.Serial_Communications;
-- Copyright 2019-2021 Bartek thindil Jasicki -- -- This file is part of Steam Sky. -- -- Steam Sky is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- Steam Sky is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with Steam Sky. If not, see <http://www.gnu.org/licenses/>. with Ada.Characters.Handling; use Ada.Characters.Handling; with DOM.Core; use DOM.Core; with DOM.Core.Documents; with DOM.Core.Nodes; use DOM.Core.Nodes; with DOM.Core.Elements; use DOM.Core.Elements; with Bases; use Bases; with Crafts; use Crafts; with Log; use Log; package body BasesTypes is procedure Load_Bases_Types(Reader: Tree_Reader) is Temp_Record: Base_Type_Data; Nodes_List, Child_Nodes: Node_List; Bases_Data: Document; Tmp_Trades: BasesTrade_Container.Map; Tmp_Recipes: UnboundedString_Container.Vector; Tmp_Flags: UnboundedString_Container.Vector; Base_Node, Child_Node: Node; Base_Index, Item_Index: Unbounded_String; Action, Sub_Action: Data_Action; Buy_Price, Sell_Price: Natural; procedure Add_Child_Node (Data: in out UnboundedString_Container.Vector; Name: String; Index: Natural) is Value: Unbounded_String; Delete_Index: Positive; begin Child_Nodes := DOM.Core.Elements.Get_Elements_By_Tag_Name (Elem => Item(List => Nodes_List, Index => Index), Name => Name); Read_Child_Node_Loop : for J in 0 .. Length(List => Child_Nodes) - 1 loop Child_Node := Item(List => Child_Nodes, Index => J); Value := (if Name = "flag" then To_Unbounded_String (Source => Get_Attribute(Elem => Child_Node, Name => "name")) else To_Unbounded_String (Source => Get_Attribute(Elem => Child_Node, Name => "index"))); Sub_Action := (if Get_Attribute(Elem => Child_Node, Name => "action")'Length > 0 then Data_Action'Value (Get_Attribute(Elem => Child_Node, Name => "action")) else ADD); if Name = "recipe" then if not Recipes_List.Contains(Key => Value) then raise Data_Loading_Error with "Can't " & To_Lower(Item => Data_Action'Image(Action)) & " base type '" & To_String(Source => Base_Index) & "', no recipe with index '" & To_String(Source => Value) & "'."; end if; if Data.Contains(Item => Value) and Sub_Action = ADD then raise Data_Loading_Error with "Can't " & To_Lower(Item => Data_Action'Image(Action)) & " base type '" & To_String(Source => Base_Index) & "', recipe '" & To_String(Source => Value) & "' already added."; end if; end if; if Sub_Action /= REMOVE then Data.Append(New_Item => Value); else Delete_Index := Data.First_Index; Delete_Child_Data_Loop : while Delete_Index <= Data.Last_Index loop if Data(Delete_Index) = Value then Data.Delete(Index => Delete_Index); exit Delete_Child_Data_Loop; end if; Delete_Index := Delete_Index + 1; end loop Delete_Child_Data_Loop; end if; end loop Read_Child_Node_Loop; end Add_Child_Node; begin Bases_Data := Get_Tree(Read => Reader); Nodes_List := DOM.Core.Documents.Get_Elements_By_Tag_Name (Doc => Bases_Data, Tag_Name => "base"); Read_Bases_Types_Loop : for I in 0 .. Length(List => Nodes_List) - 1 loop Temp_Record := (Name => Null_Unbounded_String, Color => "ffffff", Trades => Tmp_Trades, Recipes => Tmp_Recipes, Flags => Tmp_Flags, Description => Null_Unbounded_String); Base_Node := Item(List => Nodes_List, Index => I); Base_Index := To_Unbounded_String (Source => Get_Attribute(Elem => Base_Node, Name => "index")); Action := (if Get_Attribute(Elem => Base_Node, Name => "action")'Length > 0 then Data_Action'Value (Get_Attribute(Elem => Base_Node, Name => "action")) else ADD); if Action in UPDATE | REMOVE then if not BasesTypes_Container.Contains (Container => Bases_Types_List, Key => Base_Index) then raise Data_Loading_Error with "Can't " & To_Lower(Item => Data_Action'Image(Action)) & " base type '" & To_String(Source => Base_Index) & "', there no base type with that index."; end if; elsif BasesTypes_Container.Contains (Container => Bases_Types_List, Key => Base_Index) then raise Data_Loading_Error with "Can't add base type '" & To_String(Source => Base_Index) & "', there is one with that index."; end if; if Action /= REMOVE then if Action = UPDATE then Temp_Record := Bases_Types_List(Base_Index); end if; if Get_Attribute(Elem => Base_Node, Name => "name") /= "" then Temp_Record.Name := To_Unbounded_String (Source => Get_Attribute(Elem => Base_Node, Name => "name")); end if; if Get_Attribute(Elem => Base_Node, Name => "color") /= "" then Temp_Record.Color := Get_Attribute(Elem => Base_Node, Name => "color"); end if; Child_Nodes := DOM.Core.Elements.Get_Elements_By_Tag_Name (Elem => Base_Node, Name => "description"); if Length(List => Child_Nodes) > 0 then Temp_Record.Description := To_Unbounded_String (Source => Node_Value (N => First_Child (N => Item(List => Child_Nodes, Index => 0)))); end if; Child_Nodes := DOM.Core.Elements.Get_Elements_By_Tag_Name (Elem => Item(List => Nodes_List, Index => I), Name => "item"); Read_Items_Loop : for J in 0 .. Length(List => Child_Nodes) - 1 loop Child_Node := Item(List => Child_Nodes, Index => J); Item_Index := To_Unbounded_String (Source => Get_Attribute(Elem => Child_Node, Name => "index")); Sub_Action := (if Get_Attribute(Elem => Child_Node, Name => "action")' Length > 0 then Data_Action'Value (Get_Attribute(Elem => Child_Node, Name => "action")) else ADD); if not Items_List.Contains(Key => Item_Index) then raise Data_Loading_Error with "Can't " & To_Lower(Item => Data_Action'Image(Action)) & " base type '" & To_String(Source => Base_Index) & "', no item with index '" & To_String(Source => Item_Index) & "'."; end if; if Sub_Action = ADD and then Temp_Record.Trades.Contains(Key => Item_Index) then raise Data_Loading_Error with "Can't " & To_Lower(Item => Data_Action'Image(Action)) & " base type '" & To_String(Source => Base_Index) & "', item with index '" & To_String(Source => Item_Index) & "' already added."; end if; if Sub_Action /= REMOVE then Sell_Price := 0; if Get_Attribute(Elem => Child_Node, Name => "sellprice") /= "" then Sell_Price := Natural'Value (Get_Attribute (Elem => Child_Node, Name => "sellprice")); end if; Buy_Price := 0; if Get_Attribute(Elem => Child_Node, Name => "buyprice") /= "" then Buy_Price := Natural'Value (Get_Attribute (Elem => Child_Node, Name => "buyprice")); end if; Temp_Record.Trades.Include (Key => Item_Index, New_Item => (1 => Sell_Price, 2 => Buy_Price)); else Temp_Record.Trades.Delete(Key => Item_Index); end if; end loop Read_Items_Loop; Add_Child_Node (Data => Temp_Record.Recipes, Name => "recipe", Index => I); Add_Child_Node (Data => Temp_Record.Flags, Name => "flag", Index => I); if Action /= UPDATE then BasesTypes_Container.Include (Container => Bases_Types_List, Key => Base_Index, New_Item => Temp_Record); Log_Message (Message => "Base type added: " & To_String(Source => Temp_Record.Name), Message_Type => EVERYTHING); else Bases_Types_List(Base_Index) := Temp_Record; Log_Message (Message => "Base type updated: " & To_String(Source => Temp_Record.Name), Message_Type => EVERYTHING); end if; else BasesTypes_Container.Exclude (Container => Bases_Types_List, Key => Base_Index); Log_Message (Message => "Base type removed: " & To_String(Source => Base_Index), Message_Type => EVERYTHING); end if; end loop Read_Bases_Types_Loop; end Load_Bases_Types; function Is_Buyable (Base_Type, Item_Index: Unbounded_String; Check_Flag: Boolean := True; Base_Index: Extended_Base_Range := 0) return Boolean is begin if Base_Index > 0 and then Sky_Bases(Base_Index).Reputation(1) < Items_List(Item_Index).Reputation then return False; end if; if Check_Flag and then (Bases_Types_List(Base_Type).Flags.Contains (Item => To_Unbounded_String(Source => "blackmarket")) and Get_Price(Base_Type => Base_Type, Item_Index => Item_Index) > 0) then return True; end if; if not Bases_Types_List(Base_Type).Trades.Contains (Key => Item_Index) then return False; end if; if Bases_Types_List(Base_Type).Trades(Item_Index)(1) = 0 then return False; end if; return True; end Is_Buyable; function Get_Price (Base_Type, Item_Index: Unbounded_String) return Natural is begin if Items_List(Item_Index).Price = 0 then return 0; end if; if Bases_Types_List(Base_Type).Trades.Contains(Key => Item_Index) then if Bases_Types_List(Base_Type).Trades(Item_Index)(1) > 0 then return Bases_Types_List(Base_Type).Trades(Item_Index)(1); elsif Bases_Types_List(Base_Type).Trades(Item_Index)(2) > 0 then return Bases_Types_List(Base_Type).Trades(Item_Index)(2); end if; end if; return Items_List(Item_Index).Price; end Get_Price; end BasesTypes;
with System; with STM32.F4.EXTI; with STM32.F4.FSMC; with STM32.F4.GPIO; with STM32.F4.RCC; with STM32.F4.SYSCFG; with STM32.F4.USART; with STM32.F4.Address_Map; package STM32.F407Z is pragma Preelaborate; package Address_Map renames STM32.F4.Address_Map; package Modules is package EXTI renames STM32.F4.EXTI; package FSMC renames STM32.F4.FSMC; package GPIO renames STM32.F4.GPIO; --package GPIO_Ports renames STM32.STM32F4.GPIO.Ports; package RCC renames STM32.F4.RCC; package SYSCFG renames STM32.F4.SYSCFG; package USART renames STM32.F4.USART; end Modules; --pragma Warnings (Off, "* may call Last_Chance_Handler"); --pragma Warnings (Off, "* may be incompatible with alignment of object"); EXTI: Modules.EXTI.EXTI_Registers with Volatile, Import, Address => System'To_Address(Address_Map.EXTI); FSMC: Modules.FSMC.FSMC_Registers with Volatile, Import, Address => System'To_Address(Address_Map.FMC_FSMC); GPIOA: Modules.GPIO.GPIO_Registers with Volatile, Import, Address => System'To_Address(Address_Map.GPIOA); GPIOC: Modules.GPIO.GPIO_Registers with Volatile, Import, Address => System'To_Address(Address_Map.GPIOC); GPIOD: Modules.GPIO.GPIO_Registers with Volatile, Import, Address => System'To_Address(Address_Map.GPIOD); GPIOE: Modules.GPIO.GPIO_Registers with Volatile, Import, Address => System'To_Address(Address_Map.GPIOE); GPIOF: Modules.GPIO.GPIO_Registers with Volatile, Import, Address => System'To_Address(Address_Map.GPIOF); GPIOG: Modules.GPIO.GPIO_Registers with Volatile, Import, Address => System'To_Address(Address_Map.GPIOG); RCC: Modules.RCC.RCC_Registers with Volatile, Import, Address => System'To_Address(Address_Map.RCC); SYSCFG: Modules.SYSCFG.SYSCFG_Registers with Volatile, Import, Address => System'To_Address(Address_Map.SYSCFG); USART1: Modules.USART.USART_Registers with Volatile, Import, Address => System'To_Address(Address_Map.USART1); USART2: Modules.USART.USART_Registers with Volatile, Import, Address => System'To_Address(Address_Map.USART2); USART3: Modules.USART.USART_Registers with Volatile, Import, Address => System'To_Address(Address_Map.USART3); UART4: Modules.USART.USART_Registers with Volatile, Import, Address => System'To_Address(Address_Map.UART4); UART5: Modules.USART.USART_Registers with Volatile, Import, Address => System'To_Address(Address_Map.UART5); USART6: Modules.USART.USART_Registers with Volatile, Import, Address => System'To_Address(Address_Map.USART6); --pragma Warnings (On, "* may call Last_Chance_Handler"); --pragma Warnings (On, "* may be incompatible with alignment of object"); end STM32.F407Z;
procedure Line (Picture : in out Image; Start, Stop : Point; Color : Pixel) is DX : constant Float := abs Float (Stop.X - Start.X); DY : constant Float := abs Float (Stop.Y - Start.Y); Err : Float; X : Positive := Start.X; Y : Positive := Start.Y; Step_X : Integer := 1; Step_Y : Integer := 1; begin if Start.X > Stop.X then Step_X := -1; end if; if Start.Y > Stop.Y then Step_Y := -1; end if; if DX > DY then Err := DX / 2.0; while X /= Stop.X loop Picture (X, Y) := Color; Err := Err - DY; if Err < 0.0 then Y := Y + Step_Y; Err := Err + DX; end if; X := X + Step_X; end loop; else Err := DY / 2.0; while Y /= Stop.Y loop Picture (X, Y) := Color; Err := Err - DX; if Err < 0.0 then X := X + Step_X; Err := Err + DY; end if; Y := Y + Step_Y; end loop; end if; Picture (X, Y) := Color; -- Ensure dots to be drawn end Line;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2016 onox <denkpadje@gmail.com> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Numerics.Generic_Elementary_Functions; package body Orka.Transforms.SIMD_Matrices is package EF is new Ada.Numerics.Generic_Elementary_Functions (Element_Type); function Diagonal (Elements : Vector_Type) return Matrix_Type is Result : Matrix_Type := Identity_Matrix; begin for Index in Elements'Range loop Result (Index) (Index) := Elements (Index); end loop; return Result; end Diagonal; function Main_Diagonal (Matrix : Matrix_Type) return Vector_Type is (Matrix (X) (X), Matrix (Y) (Y), Matrix (Z) (Z), Matrix (W) (W)); function Trace (Matrix : Matrix_Type) return Element_Type is (Vectors.Sum (Main_Diagonal (Matrix))); function "*" (Left : Vector_Type; Right : Matrix_Type) return Vector_Type is Result : Vector_Type; begin for Column in Right'Range loop Result (Column) := Vectors.Dot (Left, Right (Column)); end loop; return Result; end "*"; function Outer (Left, Right : Vector_Type) return Matrix_Type is use Vectors; Result : Matrix_Type; begin for Index in Right'Range loop Result (Index) := Right (Index) * Left; end loop; return Result; end Outer; ---------------------------------------------------------------------------- function T (Offset : Vectors.Point) return Matrix_Type is Result : Matrix_Type := Identity_Matrix; begin Result (W) := Vector_Type (Offset); return Result; end T; function T (Offset : Vector_Type) return Matrix_Type is Result : Matrix_Type := Identity_Matrix; begin Result (W) := Offset; Result (W) (W) := 1.0; return Result; end T; function Rx (Angle : Element_Type) return Matrix_Type is CA : constant Element_Type := EF.Cos (Angle); SA : constant Element_Type := EF.Sin (Angle); Result : Matrix_Type := Identity_Matrix; begin Result (Y) := (0.0, CA, SA, 0.0); Result (Z) := (0.0, -SA, CA, 0.0); return Result; end Rx; function Ry (Angle : Element_Type) return Matrix_Type is CA : constant Element_Type := EF.Cos (Angle); SA : constant Element_Type := EF.Sin (Angle); Result : Matrix_Type := Identity_Matrix; begin Result (X) := (CA, 0.0, -SA, 0.0); Result (Z) := (SA, 0.0, CA, 0.0); return Result; end Ry; function Rz (Angle : Element_Type) return Matrix_Type is CA : constant Element_Type := EF.Cos (Angle); SA : constant Element_Type := EF.Sin (Angle); Result : Matrix_Type := Identity_Matrix; begin Result (X) := (CA, SA, 0.0, 0.0); Result (Y) := (-SA, CA, 0.0, 0.0); return Result; end Rz; function R (Axis : Vector_Type; Angle : Element_Type) return Matrix_Type is CA : constant Element_Type := EF.Cos (Angle); SA : constant Element_Type := EF.Sin (Angle); MCA : constant Element_Type := 1.0 - CA; MCARXY : constant Element_Type := MCA * Axis (X) * Axis (Y); MCARXZ : constant Element_Type := MCA * Axis (X) * Axis (Z); MCARYZ : constant Element_Type := MCA * Axis (Y) * Axis (Z); RXSA : constant Element_Type := Axis (X) * SA; RYSA : constant Element_Type := Axis (Y) * SA; RZSA : constant Element_Type := Axis (Z) * SA; R11 : constant Element_Type := CA + MCA * Axis (X)**2; R12 : constant Element_Type := MCARXY + RZSA; R13 : constant Element_Type := MCARXZ - RYSA; R21 : constant Element_Type := MCARXY - RZSA; R22 : constant Element_Type := CA + MCA * Axis (Y)**2; R23 : constant Element_Type := MCARYZ + RXSA; R31 : constant Element_Type := MCARXZ + RYSA; R32 : constant Element_Type := MCARYZ - RXSA; R33 : constant Element_Type := CA + MCA * Axis (Z)**2; Result : Matrix_Type; begin Result (X) := (R11, R12, R13, 0.0); Result (Y) := (R21, R22, R23, 0.0); Result (Z) := (R31, R32, R33, 0.0); Result (W) := (0.0, 0.0, 0.0, 1.0); return Result; end R; function R (Quaternion : Vector_Type) return Matrix_Type is Result : Matrix_Type := Identity_Matrix; begin Result (X) (X) := 1.0 - 2.0 * (Quaternion (Y) * Quaternion (Y) + Quaternion (Z) * Quaternion (Z)); Result (X) (Y) := 2.0 * (Quaternion (X) * Quaternion (Y) - Quaternion (Z) * Quaternion (W)); Result (X) (Z) := 2.0 * (Quaternion (X) * Quaternion (Z) + Quaternion (Y) * Quaternion (W)); Result (Y) (X) := 2.0 * (Quaternion (X) * Quaternion (Y) + Quaternion (Z) * Quaternion (W)); Result (Y) (Y) := 1.0 - 2.0 * (Quaternion (X) * Quaternion (X) + Quaternion (Z) * Quaternion (Z)); Result (Y) (Z) := 2.0 * (Quaternion (Y) * Quaternion (Z) - Quaternion (X) * Quaternion (W)); Result (Z) (X) := 2.0 * (Quaternion (X) * Quaternion (Z) - Quaternion (Y) * Quaternion (W)); Result (Z) (Y) := 2.0 * (Quaternion (Y) * Quaternion (Z) + Quaternion (X) * Quaternion (W)); Result (Z) (Z) := 1.0 - 2.0 * (Quaternion (X) * Quaternion (X) + Quaternion (Y) * Quaternion (Y)); return Result; end R; function S (Factors : Vector_Type) return Matrix_Type is Result : Matrix_Type := Identity_Matrix; begin Result (X) (X) := Factors (X); Result (Y) (Y) := Factors (Y); Result (Z) (Z) := Factors (Z); return Result; end S; ---------------------------------------------------------------------------- function FOV (Width, Distance : Element_Type) return Element_Type is (2.0 * EF.Arctan (Width / (2.0 * Distance))); function Finite_Perspective (FOV, Aspect, Z_Near, Z_Far : Element_Type) return Matrix_Type is F : constant Element_Type := 1.0 / EF.Tan (0.5 * FOV); Result : Matrix_Type := Identity_Matrix; begin Result (X) (X) := F / Aspect; Result (Y) (Y) := F; -- Depth normalized to [0, 1] instead of [-1 , 1] Result (Z) (Z) := Z_Far / (Z_Near - Z_Far); Result (W) (Z) := (Z_Near * Z_Far) / (Z_Near - Z_Far); Result (Z) (W) := Element_Type (-1.0); Result (W) (W) := Element_Type (0.0); return Result; end Finite_Perspective; function Infinite_Perspective (FOV, Aspect, Z_Near : Element_Type) return Matrix_Type is F : constant Element_Type := 1.0 / EF.Tan (0.5 * FOV); Result : Matrix_Type := Identity_Matrix; begin Result (X) (X) := F / Aspect; Result (Y) (Y) := F; -- Depth normalized to [0, 1] instead of [-1 , 1] Result (Z) (Z) := Element_Type (-1.0); Result (W) (Z) := -Z_Near; Result (Z) (W) := Element_Type (-1.0); Result (W) (W) := Element_Type (0.0); return Result; end Infinite_Perspective; function Infinite_Perspective_Reversed_Z (FOV, Aspect, Z_Near : Element_Type) return Matrix_Type is F : constant Element_Type := 1.0 / EF.Tan (0.5 * FOV); Result : Matrix_Type := Identity_Matrix; begin Result (X) (X) := F / Aspect; Result (Y) (Y) := F; -- Depth normalized to [1, 0] instead of [-1 , 1] Result (Z) (Z) := Element_Type (0.0); Result (W) (Z) := Z_Near; Result (Z) (W) := Element_Type (-1.0); Result (W) (W) := Element_Type (0.0); return Result; end Infinite_Perspective_Reversed_Z; function Orthographic (X_Mag, Y_Mag, Z_Near, Z_Far : Element_Type) return Matrix_Type is Result : Matrix_Type := Identity_Matrix; begin Result (X) (X) := 2.0 / X_Mag; Result (Y) (Y) := 2.0 / Y_Mag; -- Depth normalized to [0, 1] instead of [-1, 1] Result (Z) (Z) := -1.0 / (Z_Far - Z_Near); Result (W) (Z) := -Z_Near / (Z_Far - Z_Near); return Result; end Orthographic; end Orka.Transforms.SIMD_Matrices;
with Ada.Containers.Indefinite_Ordered_Maps; with Symbolic_Expressions.Solving; package EU_Projects.Times.Time_Expressions.Solving is type Time_Equation_System is private; function Contains_Left_Term (Equations : Time_Equation_System; Left : Dotted_Identifier) return Boolean; procedure Add_Equation (Equations : in out Time_Equation_System; Left : Dotted_Identifier; Right : Symbolic_Duration) with Pre => not Contains_Left_Term (Equations, Left), Post => Contains_Left_Term (Equations, Left); procedure Add_Equation (Equations : in out Time_Equation_System; Left : Dotted_Identifier; Right : Symbolic_Instant) with Pre => not Contains_Left_Term (Equations, Left), Post => Contains_Left_Term (Equations, Left); type Variable_Map is tagged private with Constant_Indexing => Get; function Contains (Map : Variable_Map; ID : Dotted_Identifier) return Boolean; function Value_Class (Map : Variable_Map; Id : Dotted_Identifier) return Time_Type with Pre => Contains (Map, Id); function Get (Map : Variable_Map; ID : Dotted_Identifier) return Duration with Pre => Contains (Map, ID) and then Value_Class (Map, Id) = Duration_Value; function Get (Map : Variable_Map; ID : Dotted_Identifier) return Instant with Pre => Contains (Map, ID) and then Value_Class (Map, Id) = Instant_Value; function Solve (Equations : Time_Equation_System) return Variable_Map; Unsolvable : exception; private package Time_Equations is new Time_Expr.Solving; type Equation_Right_Side is record Class : Time_Type; Val : Time_Expr.Symbolic_Expression; end record; package Equation_Maps is new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => Dotted_Identifier, Element_Type => Equation_Right_Side); type Time_Equation_System is record M : Equation_Maps.Map; end record; type Variable_Value (Class : Time_Type) is record case Class is when Instant_Value => I : Instant; when Duration_Value => D : Duration; end case; end record; package Variable_Maps is new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => Dotted_Identifier, Element_Type => Variable_Value); type Variable_Map is tagged record M : Variable_Maps.Map; end record; function Contains (Map : Variable_Map; ID : Dotted_Identifier) return Boolean is (Map.M.Contains (ID)); function Value_Class (Map : Variable_Map; Id : Dotted_Identifier) return Time_Type is (Map.M (Id).Class); function Get (Map : Variable_Map; ID : Dotted_Identifier) return Duration is (Map.M.Element (ID).D); function Get (Map : Variable_Map; ID : Dotted_Identifier) return Instant is (Map.M.Element (ID).I); function Contains_Left_Term (Equations : Time_Equation_System; Left : Dotted_Identifier) return Boolean is (Equations.M.Contains (Left)); end EU_Projects.Times.Time_Expressions.Solving;
-- Procedure tests Fourier8. Code fragments -- demonstrate some features of FFT's. with Fourier8; with Text_IO; use Text_IO; with Ada.Numerics.Generic_Elementary_Functions; procedure fourier8_demo_1 is type Real is digits 15; package math is new Ada.Numerics.Generic_Elementary_Functions (Real); use math; package rio is new Float_IO(Real); use rio; package iio is new Integer_IO(Integer); use iio; Log_Of_Max_Data_Length : constant := 12; -- NOTICE this means max data array size is 2**Log_Of_Max_Data_Length. -- The larger you make this array, the slower program might run. type Array_Index is range 0..2**(Log_Of_Max_Data_Length+1)-1; type Data_Array is array(Array_Index) of Real; package fft8 is new Fourier8 (Real, Array_Index, Data_Array, Log_Of_Max_Data_Length); use fft8; D_Re, D_Im : Data_Array; Data_Set_Last : Data_Index; Basis_Function_Last : Data_Index; Transformed_Data_Last : Data_Index; Theta, Frequency, Norm : Real; Two_Pi_Over_N : Real; Num, Mode : Integer; Area1, Area2 : Real; DeltaRE, DeltaIM : Real; Dat_Re, Dat_Im : Real; Exp_Table : Exp_Storage; -- And put the following in calls to FFT: -- Exp_Table => Exp_Table, Max_Error, Del : Real; Pii : constant Real := 3.14159_26535_89793_23846; ----------- -- Pause -- ----------- procedure Pause (s1,s2,s3,s4,s5,s6,s7,s8,s9,s10 : string := "") is Continue : Character := ' '; begin new_line(2); if S1 /= "" then put_line (S1); end if; if S2 /= "" then put_line (S2); end if; if S3 /= "" then put_line (S3); end if; if S4 /= "" then put_line (S4); end if; if S5 /= "" then put_line (S5); end if; if S6 /= "" then put_line (S6); end if; if S7 /= "" then put_line (S7); end if; if S8 /= "" then put_line (S8); end if; if S9 /= "" then put_line (S9); end if; if S10 /= "" then put_line (S10); end if; dialog: loop begin new_line(1); put ("Type a character to continue: "); get_immediate (Continue); exit dialog; exception when others => null; end; end loop dialog; new_line(2); end pause; begin new_line; put ("Input number of data points to use in the following tests."); new_line; put ("The maximum allowed number is "); put (Integer'Image(2**Log_Of_Max_Data_Length)); new_line; put ("A good number to start with is 37"); new_line; put ("Enter the desired number: "); get (Num); Data_Set_Last := Data_Index (Num - 1); -- Get nearest power of 2. declare Pow : Integer := 0; begin for I in Integer range 0..Log_Of_Max_Data_Length loop if 2**I >= Num then Pow := I; exit; end if; end loop; Basis_Function_Last := Data_Index (2**Pow - 1); end; new_line; put ("You requested an FFT on the first "); put (Integer'Image (Num)); put (" data points."); new_line; put ("The actual FFT will be performed on "); put (Integer'Image (Integer (Basis_Function_Last)+1)); put (" data points."); new_line; put ("Data is set to 0 beyond the first "); put (Integer'Image (Num)); put (" data points."); new_line(2); --***************************************************************** -- Test 1. -- Make a basis element of the set of Fourier basis states: -- Its FFT should zero everywhere except for the element = Mode. -- There, the value of the FFT should be (1.0, 0.0). Below -- we normalize the basis element with the factor Norm = 1/Sqrt(N). --***************************************************************** Pause ("Test 1: take the FFT of the Fourier basis function:", " ", " Exp (i*T*Mode*2*Pi/N) / SQRT(N),", " ", "where N is the number of points. The result of the FFT", "should be a delta-function peaked at position Mode."); put_line ("Input Mode (0, 1, 2, ...) of the basis function you wish to FFT: "); Get (Mode); Frequency := Real (Mode); --***************************************************************** Two_Pi_Over_N := 2.0 * Pii / (Real (Basis_Function_Last) + 1.0); Norm := 1.0 / SQRT ((Real (Basis_Function_Last) + 1.0)); for I in 0..Basis_Function_Last loop Theta := Two_Pi_Over_N * Frequency * Real (I); D_Re(I) := Norm * Cos (Theta); D_Im(I) := Norm * Sin (Theta); end loop; put_line ("Starting Test 1:"); new_line; put ("Basis function was constructed using "); put(Num); put(" data points."); FFT (Data_Re => D_Re, Data_Im => D_Im, Transformed_Data_Last => Transformed_Data_Last, Input_Data_Last => Basis_Function_Last, Exp_Table => Exp_Table, Inverse_FFT_Desired => False, Normalized_Data_Desired => True); Pause ("Ending FFT.", "We have taken the FFT of Exp (i*T*Mode*2*Pi/N) / SQRT(N).", "The result should be (0.0, 0.0) everywhere except for ", "a (1.0, 0.0) at data point Mode."); for I in Data_Index range 0..Basis_Function_Last loop new_line; put (Integer(I)); put(' '); put (D_Re(I)); put(' '); put(D_Im(I)); end loop; --***************************************************************** -- test 1b. -- We 1st make a basis element of the set of Fourier basis states: -- Its FFT should zero everywhere except for the element = Mode. -- There, the value of the FFT should be (1.0, 0.0). Below -- we normalize the basis element with the factor Norm = 1/Sqrt(N). --***************************************************************** Pause ("Test 1b: take the inverse FFT of the Fourier basis function:", " ", " Exp (-i*T*Mode*2*Pi/N) / SQRT(N),", " ", "where N is the number of points. The result of the FFT", "should be a delta-function peaked at position Mode."); put_line ("Input Mode (0, 1, 2, ...) of the basis function you wish to FFT: "); Get (Mode); Frequency := Real (Mode); --***************************************************************** Two_Pi_Over_N := 2.0 * Pii / (Real (Basis_Function_Last) + 1.0); Norm := 1.0 / SQRT ((Real (Basis_Function_Last) + 1.0)); for I in 0..Basis_Function_Last loop Theta := Two_Pi_Over_N * Frequency * Real (I); D_Re(I) := Norm * Cos (Theta); D_Im(I) := -Norm * Sin (Theta); end loop; put_line ("Starting Test 1b:"); new_Line; put ("Basis function was constructed using "); put(Integer(Basis_Function_Last)+1); put(" data points."); new_line(2); FFT (Data_Re => D_Re, Data_Im => D_Im, Transformed_Data_Last => Transformed_Data_Last, Input_Data_Last => Basis_Function_Last, Exp_Table => Exp_Table, Inverse_FFT_Desired => True, Normalized_Data_Desired => True); Pause ("Ending FFT.", "We have taken the inverse FFT of Exp (-i*T*Mode*2*Pi/N) / SQRT(N).", "The result should be (0.0, 0.0) everywhere except for ", "a (1.0, 0.0) at data point Mode."); for I in Data_Index range 0..Basis_Function_Last loop new_line; put (Integer(I)); put(' '); put (D_Re(I)); put(' '); put(D_Im(I)); end loop; --***************************************************************** -- Test2. -- Verify Parceval's Theorem. The area under the FFT coefficients -- should equal the area under the data. Notice that was true in the -- above test, because Sum (|exp(i*T*Mode*2*Pi/N) / Sqrt(N)|**2) is -- one on the interval [0,N-1]. -- First we create a new data set: --***************************************************************** for I in 0..Data_Set_Last loop Theta := Real (I); D_Re(I) := 1.0 / (Theta + 1.0); D_Im(I) := Theta**2; end loop; Area1 := 0.0; for I in 0..Data_Set_Last loop Area1 := Area1 + D_Re(I)*D_Re(I) + D_Im(I)*D_Im(I); end loop; Pause ("Test 2: test of Parceval's theorem. The area under the", "FFT curve (sum of coefficients modulus squared) should equal", "area under the original curve. This requires the use of the", "normalized version of the FFT."); put_line ("Starting Test 2:"); FFT (Data_Re => D_Re, Data_Im => D_Im, Transformed_Data_Last => Transformed_Data_Last, --output padded data length-1 Input_Data_Last => Data_Set_Last, --input desired data length-1 Exp_Table => Exp_Table, Inverse_FFT_Desired => False, Normalized_Data_Desired => True); put_line ("Ending FFT"); Area2 := 0.0; for I in 0..Transformed_Data_Last loop Area2 := Area2 + D_Re(I)*D_Re(I) + D_Im(I)*D_Im(I); end loop; new_line; put ("Area under the original curve: "); put(Area1); new_line; put ("Area under Fourier transformed curve: "); put(Area2); -- Test3. -- Inverse FFT of the FFT. Pause ("Test 3: take the inverse FFT of the FFT of some", "artificial data, and compare with the original data.", "The test calculates: Data - Inverse_FFT (FFT (Data),", "then prints the max error."); for I in 0..Data_Set_Last loop Theta := Real (I); D_Re(I) := Sqrt (Theta) / (Theta + 1.0); D_Im(I) := Cos (0.03737*Theta**2/(Theta + 1.0)) * Theta / (Theta + 1.0); end loop; put_line("Starting Test 3:"); FFT (Data_Re => D_Re, Data_Im => D_Im, Transformed_Data_Last => Transformed_Data_Last, Input_Data_Last => Data_Set_Last, Exp_Table => Exp_Table, Inverse_FFT_Desired => False, Normalized_Data_Desired => True); FFT (Data_Re => D_Re, Data_Im => D_Im, Transformed_Data_Last => Transformed_Data_Last, Input_Data_Last => Transformed_Data_Last, Exp_Table => Exp_Table, Inverse_FFT_Desired => True, Normalized_Data_Desired => True); Max_Error := 0.0; for I in 0..Data_Set_Last loop Theta := Real (I); Dat_Re := Sqrt (Theta) / (Theta + 1.0); Dat_Im := Cos (0.03737*Theta**2/(Theta + 1.0)) * Theta / (Theta + 1.0); Del := Abs (Dat_Re - D_Re(I)); if Max_Error < Del then Max_Error := Del; end if; Del := Abs (Dat_Im - D_Im(I)); if Max_Error < Del then Max_Error := Del; end if; end loop; new_line(2); put ("Max error in Data - Inverse_FFT (FFT (Data)):"); put (Max_Error); new_line; Pause ("If the number of data points FFT'd was not a power", "of 2 in length, then the data set was padded with zeros", "out to the nearest power of 2. To see if these data", "values were preserved by the two transformations, type", "a character. Should get a number near 10.0**(-15):"); -- These points were padded with zero's in the FFT routine, prior -- to being FFT'd. The application of the inverse FFT should -- bring them back to zero again. if Data_Set_Last < Data_Index'Last then Max_Error := 0.0; for I in Data_Set_Last+1 .. Transformed_Data_Last loop Del := Abs (D_Re(I) - 0.0); if Max_Error < Del then Max_Error := Del; end if; Del := Abs (D_Im(I) - 0.0); if Max_Error < Del then Max_Error := Del; end if; end loop; put ("Max error in [Data - Inverse_FFT (FFT (Data))]: "); put (Max_Error); end if; Pause ("Test 4 is a long test..runs through entire range of Array_Index ", "to see if FFT_Inverse (FFT (Data)) = Data. Nothing is printed", "unless large errors are detected. (Use 15 digit floating point.)", "Interrupt the program here if you do not want a long wait."); for N in Array_Index range 0..Basis_Function_Last loop for I in Array_Index range 0..N loop Theta := Real (I); D_Re(I) := 1.0 / (Theta + 1.0); D_Im(I) := Cos (0.03737 * Theta**2 / (Theta + 1.0)); end loop; FFT (Data_Re => D_Re, Data_Im => D_Im, Transformed_Data_Last => Transformed_Data_Last, --output padded data length-1 Input_Data_Last => N, --input desired data length-1 Exp_Table => Exp_Table, Inverse_FFT_Desired => False, Normalized_Data_Desired => True); FFT (Data_Re => D_Re, Data_Im => D_Im, Transformed_Data_Last => Transformed_Data_Last, Input_Data_Last => Transformed_Data_Last, Exp_Table => Exp_Table, Inverse_FFT_Desired => True, Normalized_Data_Desired => True); for I in Array_Index range 0..N loop Theta := Real (I); Dat_Re := 1.0 / (Theta + 1.0); Dat_Im := Cos (0.03737 * Theta**2 / (Theta + 1.0)); DeltaRE := Abs (Dat_Re - D_Re(I)); DeltaIM := Abs (Dat_Im - D_Im(I)); if DeltaRE > 1.0E-11 then new_line; put("FAILURE: "); put (DeltaRE); put(" at "); put(Real(I)); end if; if DeltaIM > 1.0E-11 then new_line; put("FAILURE: "); put (DeltaIM); put(" at "); put(Real(I)); end if; end loop; end loop; end;
-- Copyright (c) 2017 Maxim Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- with Ada_Pretty.Definitions; with Ada_Pretty.Clauses; with Ada_Pretty.Declarations; with Ada_Pretty.Expressions; with Ada_Pretty.Joins; with Ada_Pretty.Statements; with Ada_Pretty.Units; package body Ada_Pretty is -------------- -- Document -- -------------- not overriding function Document (Self : Node; Printer : not null access League.Pretty_Printers.Printer'Class; Pad : Natural) return League.Pretty_Printers.Document is begin raise Program_Error; return Printer.New_Document; end Document; ---------- -- Join -- ---------- overriding function Join (Self : Declaration; List : Node_Access_Array; Pad : Natural; Printer : not null access League.Pretty_Printers.Printer'Class) return League.Pretty_Printers.Document is Result : League.Pretty_Printers.Document := Printer.New_Document; begin Result.Append (Node'Class (Self).Document (Printer, Pad)); for J in List'Range loop Result.New_Line; Result.Append (List (J).Document (Printer, Pad)); end loop; return Result; end Join; ---------- -- Join -- ---------- not overriding function Join (Self : Node; List : Node_Access_Array; Pad : Natural; Printer : not null access League.Pretty_Printers.Printer'Class) return League.Pretty_Printers.Document is Result : League.Pretty_Printers.Document := Printer.New_Document; begin Result.Append (Node'Class (Self).Document (Printer, Pad)); for J in List'Range loop Result.Append (List (J).Document (Printer, Pad)); end loop; return Result; end Join; ---------- -- Join -- ---------- overriding function Join (Self : Expression; List : Node_Access_Array; Pad : Natural; Printer : not null access League.Pretty_Printers.Printer'Class) return League.Pretty_Printers.Document is Result : League.Pretty_Printers.Document := Printer.New_Document; begin Result.Append (Node'Class (Self).Document (Printer, Pad)); for J in List'Range loop if List (J).all not in Expressions.Infix then Result.Put (","); Result.New_Line; end if; Result.Append (List (J).Document (Printer, Pad)); end loop; Result.Group; return Result; end Join; ---------------- -- New_Access -- ---------------- not overriding function New_Access (Self : access Factory; Modifier : Access_Modifier := Unspecified; Target : not null Node_Access) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Definitions.New_Access (Modifier => Modifier, Target => Target)); end New_Access; --------------- -- New_Apply -- --------------- not overriding function New_Apply (Self : access Factory; Prefix : not null Node_Access; Arguments : not null Node_Access) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Expressions.New_Apply (Prefix, Arguments)); end New_Apply; ------------------------------ -- New_Argument_Association -- ------------------------------ not overriding function New_Argument_Association (Self : access Factory; Value : not null Node_Access; Choice : Node_Access := null) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Expressions.New_Argument_Association (Choice, Value)); end New_Argument_Association; --------------- -- New_Array -- --------------- not overriding function New_Array (Self : access Factory; Indexes : not null Node_Access; Component : not null Node_Access) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Definitions.New_Array (Indexes, Component)); end New_Array; ---------------- -- New_Aspect -- ---------------- not overriding function New_Aspect (Self : access Factory; Name : not null Node_Access; Value : Node_Access := null) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Clauses.New_Aspect (Name, Value)); end New_Aspect; -------------------- -- New_Assignment -- -------------------- not overriding function New_Assignment (Self : access Factory; Left : not null Node_Access; Right : not null Node_Access) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Statements.New_Assignment (Left, Right)); end New_Assignment; --------------- -- New_Block -- --------------- not overriding function New_Block (Self : access Factory; Declarations : Node_Access := null; Statements : Node_Access := null; Exceptions : Node_Access := null) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Ada_Pretty.Statements.New_Block_Statement (Declarations, Statements, Exceptions)); end New_Block; -------------- -- New_Case -- -------------- not overriding function New_Case (Self : access Factory; Expression : not null Node_Access; List : not null Node_Access) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Statements.New_Case (Expression, List)); end New_Case; ------------------- -- New_Case_Path -- ------------------- not overriding function New_Case_Path (Self : access Factory; Choice : not null Node_Access; List : not null Node_Access) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Statements.New_Case_Path (Choice, List)); end New_Case_Path; -------------------------- -- New_Compilation_Unit -- -------------------------- not overriding function New_Compilation_Unit (Self : access Factory; Root : not null Node_Access; Clauses : Node_Access := null; License : League.Strings.Universal_String := League.Strings.Empty_Universal_String) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Units.New_Compilation_Unit (Root, Clauses, License)); end New_Compilation_Unit; ------------------------------- -- New_Component_Association -- ------------------------------- not overriding function New_Component_Association (Self : access Factory; Value : not null Node_Access; Choices : Node_Access := null) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Expressions.New_Component_Association (Choices, Value)); end New_Component_Association; ----------------- -- New_Derived -- ----------------- not overriding function New_Derived (Self : access Factory; Parent : not null Node_Access) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Definitions.New_Derived (Parent)); end New_Derived; --------------- -- New_Elsif -- --------------- not overriding function New_Elsif (Self : access Factory; Condition : not null Node_Access; List : not null Node_Access) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Statements.New_Elsif (Condition, List)); end New_Elsif; ------------------------- -- New_Extended_Return -- ------------------------- not overriding function New_Extended_Return (Self : access Factory; Name : not null Node_Access; Type_Definition : not null Node_Access; Initialization : Node_Access := null; Statements : not null Node_Access) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Ada_Pretty.Statements.New_Extended_Return (Name, Type_Definition, Initialization, Statements)); end New_Extended_Return; ------------- -- New_For -- ------------- not overriding function New_For (Self : access Factory; Name : not null Node_Access; Iterator : not null Node_Access; Statements : not null Node_Access) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Ada_Pretty.Statements.New_For (Name, Iterator, Statements)); end New_For; ---------------------- -- New_If_Statement -- ---------------------- not overriding function New_If (Self : access Factory; Condition : not null Node_Access; Then_Path : not null Node_Access; Elsif_List : Node_Access := null; Else_Path : Node_Access := null) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Statements.New_If (Condition, Then_Path, Elsif_List, Else_Path)); end New_If; ----------------------- -- New_If_Expression -- ----------------------- not overriding function New_If_Expression (Self : access Factory; Condition : not null Node_Access; Then_Path : not null Node_Access; Elsif_List : Node_Access := null; Else_Path : Node_Access := null) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Expressions.New_If (Condition, Then_Path, Elsif_List, Else_Path)); end New_If_Expression; --------------- -- New_Infix -- --------------- not overriding function New_Infix (Self : access Factory; Operator : League.Strings.Universal_String; Left : not null Node_Access) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Expressions.New_Infix (Operator, Left)); end New_Infix; ------------------- -- New_Interface -- ------------------- not overriding function New_Interface (Self : access Factory; Is_Limited : Boolean := False; Parents : Node_Access := null) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Definitions.New_Interface (Is_Limited, Parents)); end New_Interface; -------------- -- New_List -- -------------- not overriding function New_List (Self : access Factory; Head : Node_Access; Tail : not null Node_Access) return not null Node_Access is pragma Unreferenced (Self); begin if Head = null then return Tail; else return new Node'Class'(Joins.New_Join (Head, Tail)); end if; end New_List; -------------- -- New_List -- -------------- not overriding function New_List (Self : access Factory; List : Node_Access_Array) return not null Node_Access is Result : Node_Access := List (List'First); begin for J in List'First + 1 .. List'Last loop Result := Self.New_List (Result, List (J)); end loop; return Result; end New_List; ----------------- -- New_Literal -- ----------------- not overriding function New_Literal (Self : access Factory; Value : Natural; Base : Positive := 10) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Expressions.New_Literal (Value, Base)); end New_Literal; -------------- -- New_Loop -- -------------- not overriding function New_Loop (Self : access Factory; Condition : Node_Access; Statements : not null Node_Access) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Ada_Pretty.Statements.New_Loop (Condition, Statements)); end New_Loop; -------------- -- New_Name -- -------------- not overriding function New_Name (Self : access Factory; Name : League.Strings.Universal_String) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Expressions.New_Name (Name)); end New_Name; ------------------------ -- New_Null_Exclusion -- ------------------------ not overriding function New_Null_Exclusion (Self : access Factory; Definition : not null Node_Access; Exclude : Boolean := True) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Definitions.New_Null_Exclusion (Definition, Exclude)); end New_Null_Exclusion; ----------------- -- New_Package -- ----------------- not overriding function New_Package (Self : access Factory; Name : not null Node_Access; Public_Part : Node_Access := null; Private_Part : Node_Access := null; Comment : League.Strings.Universal_String := League.Strings.Empty_Universal_String) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Declarations.New_Package (Name, Public_Part, Private_Part, Comment)); end New_Package; ---------------------- -- New_Package_Body -- ---------------------- not overriding function New_Package_Body (Self : access Factory; Name : not null Node_Access; List : Node_Access := null) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Declarations.New_Package_Body (Name, List)); end New_Package_Body; ------------------------------- -- New_Package_Instantiation -- ------------------------------- not overriding function New_Package_Instantiation (Self : access Factory; Name : not null Node_Access; Template : not null Node_Access; Actual_Part : Node_Access := null; Comment : League.Strings.Universal_String := League.Strings.Empty_Universal_String) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Declarations.New_Package_Instantiation (Name, Template, Actual_Part, Comment)); end New_Package_Instantiation; ------------------- -- New_Parameter -- ------------------- not overriding function New_Parameter (Self : access Factory; Name : not null Node_Access; Type_Definition : not null Node_Access; Initialization : Node_Access := null; Is_In : Boolean := False; Is_Out : Boolean := False; Is_Aliased : Boolean := False; Comment : League.Strings.Universal_String := League.Strings.Empty_Universal_String) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Declarations.New_Parameter (Name, Type_Definition, Initialization, Is_In, Is_Out, Is_Aliased, Comment)); end New_Parameter; --------------------- -- New_Parentheses -- --------------------- not overriding function New_Parentheses (Self : access Factory; Child : not null Node_Access) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Expressions.New_Parentheses (Child)); end New_Parentheses; ---------------- -- New_Pragma -- ---------------- not overriding function New_Pragma (Self : access Factory; Name : not null Node_Access; Arguments : Node_Access := null; Comment : League.Strings.Universal_String := League.Strings.Empty_Universal_String) return not null Node_Access is pragma Unreferenced (Self, Comment); begin return new Node'Class'(Clauses.New_Pragma (Name, Arguments)); end New_Pragma; ------------------------ -- New_Private_Record -- ------------------------ not overriding function New_Private_Record (Self : access Factory; Is_Tagged : Boolean := False; Is_Limited : Boolean := False; Parents : Node_Access := null) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Definitions.New_Private_Record (Is_Tagged, Is_Limited, Parents)); end New_Private_Record; ----------------------------- -- New_Qualified_Expession -- ----------------------------- not overriding function New_Qualified_Expession (Self : access Factory; Prefix : not null Node_Access; Argument : not null Node_Access) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Expressions.New_Qualified (Prefix, Argument)); end New_Qualified_Expession; ---------------- -- New_Record -- ---------------- not overriding function New_Record (Self : access Factory; Parent : Node_Access := null; Components : Node_Access := null; Is_Abstract : Boolean := False; Is_Tagged : Boolean := False; Is_Limited : Boolean := False) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Definitions.New_Record (Parent, Components, Is_Abstract, Is_Tagged, Is_Limited)); end New_Record; ---------------- -- New_Return -- ---------------- not overriding function New_Return (Self : access Factory; Expression : Node_Access := null) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Statements.New_Return (Expression)); end New_Return; ----------------------- -- New_Selected_Name -- ----------------------- not overriding function New_Selected_Name (Self : access Factory; Prefix : not null Node_Access; Selector : not null Node_Access) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Expressions.New_Selected_Name (Prefix, Selector)); end New_Selected_Name; not overriding function New_Selected_Name (Self : access Factory; Name : League.Strings.Universal_String) return not null Node_Access is List : constant League.String_Vectors.Universal_String_Vector := Name.Split ('.'); Result : Node_Access := Self.New_Name (List.Element (1)); begin for J in 2 .. List.Length loop Result := Self.New_Selected_Name (Result, Self.New_Name (List.Element (J))); end loop; return Result; end New_Selected_Name; ------------------- -- New_Statement -- ------------------- not overriding function New_Statement (Self : access Factory; Expression : Node_Access := null) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Statements.New_Statement (Expression)); end New_Statement; ------------------------ -- New_String_Literal -- ------------------------ not overriding function New_String_Literal (Self : access Factory; Text : League.Strings.Universal_String) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Expressions.New_String (Text)); end New_String_Literal; ------------------------- -- New_Subprogram_Body -- ------------------------- not overriding function New_Subprogram_Body (Self : access Factory; Specification : not null Node_Access; Declarations : Node_Access := null; Statements : Node_Access := null; Exceptions : Node_Access := null) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Ada_Pretty.Declarations.New_Subprogram_Body (Specification, Declarations, Statements, Exceptions)); end New_Subprogram_Body; -------------------------------- -- New_Subprogram_Declaration -- -------------------------------- not overriding function New_Subprogram_Declaration (Self : access Factory; Specification : not null Node_Access; Aspects : Node_Access := null; Is_Abstract : Boolean := False; Is_Null : Boolean := False; Expression : Node_Access := null; Renamed : Node_Access := null; Comment : League.Strings.Universal_String := League.Strings.Empty_Universal_String) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Declarations.New_Subprogram_Declaration (Specification, Aspects, Is_Abstract, Is_Null, Expression, Renamed, Comment)); end New_Subprogram_Declaration; -------------------- -- New_Subprogram -- -------------------- not overriding function New_Subprogram_Specification (Self : access Factory; Is_Overriding : Trilean := Unspecified; Name : Node_Access := null; Parameters : Node_Access := null; Result : Node_Access := null) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Definitions.New_Subprogram (Is_Overriding, Name, Parameters, Result)); end New_Subprogram_Specification; ----------------- -- New_Subtype -- ----------------- pragma Warnings (Off); not overriding function New_Subtype (Self : access Factory; Name : not null Node_Access; Definition : not null Node_Access; Constrain : Node_Access := null; Comment : League.Strings.Universal_String := League.Strings.Empty_Universal_String) return not null Node_Access is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "New_Subtype unimplemented"); return raise Program_Error with "Unimplemented function New_Subtype"; end New_Subtype; pragma Warnings (On); ----------------- -- New_Subunit -- ----------------- not overriding function New_Subunit (Self : access Factory; Parent_Name : not null Node_Access; Proper_Body : not null Node_Access) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Units.New_Subunit (Parent_Name, Proper_Body)); end New_Subunit; -------------- -- New_Type -- -------------- not overriding function New_Type (Self : access Factory; Name : not null Node_Access; Discriminants : Node_Access := null; Definition : Node_Access := null; Aspects : Node_Access := null; Comment : League.Strings.Universal_String := League.Strings.Empty_Universal_String) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Declarations.New_Type (Name, Discriminants, Definition, Aspects, Comment)); end New_Type; ------------- -- New_Use -- ------------- not overriding function New_Use (Self : access Factory; Name : not null Node_Access; Use_Type : Boolean := False) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Clauses.New_Use (Name, Use_Type)); end New_Use; ------------------ -- New_Variable -- ------------------ not overriding function New_Variable (Self : access Factory; Name : not null Node_Access; Type_Definition : Node_Access := null; Initialization : Node_Access := null; Rename : Node_Access := null; Is_Constant : Boolean := False; Is_Aliased : Boolean := False; Aspects : Node_Access := null; Comment : League.Strings.Universal_String := League.Strings.Empty_Universal_String) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Declarations.New_Variable (Name, Type_Definition, Initialization, Rename, Is_Constant, Is_Aliased, Aspects, Comment)); end New_Variable; -------------- -- New_With -- -------------- not overriding function New_With (Self : access Factory; Name : not null Node_Access; Is_Limited : Boolean := False; Is_Private : Boolean := False) return not null Node_Access is pragma Unreferenced (Self); begin return new Node'Class'(Clauses.New_With (Name, Is_Limited, Is_Private)); end New_With; ------------------ -- Print_Aspect -- ------------------ function Print_Aspect (Aspect : Node_Access; Printer : not null access League.Pretty_Printers.Printer'Class) return League.Pretty_Printers.Document is Result : League.Pretty_Printers.Document := Printer.New_Document; Pad : constant Natural := 0; begin if Aspect = null then return Result; end if; Result.New_Line; Result.Put ("with "); Result.Append (Aspect.Document (Printer, Pad)); Result.Nest (2); if Aspect.all in Clauses.Aspect then Result.Group; end if; return Result; end Print_Aspect; ------------- -- To_Text -- ------------- not overriding function To_Text (Self : access Factory; Unit : not null Node_Access) return League.String_Vectors.Universal_String_Vector is pragma Unreferenced (Self); Printer : aliased League.Pretty_Printers.Printer; Document : constant League.Pretty_Printers.Document := Unit.Document (Printer'Access, 0); begin return Printer.Pretty (Width => 79, Input => Document); end To_Text; end Ada_Pretty;
-- WORDS, a Latin dictionary, by Colonel William Whitaker (USAF, Retired) -- -- Copyright William A. Whitaker (1936–2010) -- -- This is a free program, which means it is proper to copy it and pass -- it on to your friends. Consider it a developmental item for which -- there is no charge. However, just for form, it is Copyrighted -- (c). Permission is hereby freely given for any and all use of program -- and data. You can sell it as your own, but at least tell me. -- -- This version is distributed without obligation, but the developer -- would appreciate comments and suggestions. -- -- All parts of the WORDS system, source code and data files, are made freely -- available to anyone who wishes to use them, for whatever purpose. with Ada.Exceptions; use Ada.Exceptions; with Latin_Utils.Strings_Package; use Latin_Utils.Strings_Package; with Support_Utils.Word_Parameters; use Support_Utils.Word_Parameters; with Latin_Utils.Inflections_Package; use Latin_Utils.Inflections_Package; with Support_Utils.Uniques_Package; use Support_Utils.Uniques_Package; with Support_Utils.Developer_Parameters; use Support_Utils.Developer_Parameters; with Support_Utils.Word_Support_Package; use Support_Utils.Word_Support_Package; use Latin_Utils; package body Words_Engine.List_Sweep is function Allowed_Stem (Pr : Parse_Record) return Boolean is Allowed : Boolean := True; -- modify as necessary and return it De : Dictionary_Entry; begin -- TEXT_IO.PUT ("ALLOWED? >"); -- PARSE_RECORD_IO.PUT (PR); -- TEXT_IO.NEW_LINE; -- FIXME: duplicates (commented) code below if Pr.D_K not in General .. Local then return True; end if; Dict_IO.Read (Dict_File (Pr.D_K), De, Pr.MNPC); -- NOUN CHECKS case Pr.IR.Qual.Pofs is when N => if Words_Mdev (For_Word_List_Check) then if (Nom <= Pr.IR.Qual.Noun.Of_Case) and then (S <= Pr.IR.Qual.Noun.Number) then Allowed := True; elsif (Nom <= Pr.IR.Qual.Noun.Of_Case) and then (Pr.IR.Qual.Noun.Number = P) then Search_For_Pl : declare De : Dictionary_Entry; Mean : Meaning_Type := Null_Meaning_Type; begin Allowed := False; Dict_IO.Read (Dict_File (Pr.D_K), De, Pr.MNPC); Mean := De.Mean; for J in Meaning_Type'First .. Meaning_Type'Last - 2 loop if Mean (J .. J + 2) = "pl." then Allowed := True; exit; end if; end loop; end Search_For_Pl; else Allowed := False; end if; end if; when Adj => if Words_Mdev (For_Word_List_Check) then Allowed := (Nom <= Pr.IR.Qual.Adj.Of_Case) and then (S <= Pr.IR.Qual.Adj.Number) and then (M <= Pr.IR.Qual.Adj.Gender); end if; -- VERB CHECKS when V => --TEXT_IO.PUT ("VERB "); -- Check for Verb 3 1 dic/duc/fac/fer shortened imperative -- See G&L 130.5 declare Stem : constant String := Trim (Pr.Stem); Last_Three : String (1 .. 3); begin if (Pr.IR.Qual.Verb = ((3, 1), (Pres, Active, Imp), 2, S)) and (Pr.IR.Ending.Size = 0) then -- For this special case if Stem'Length >= 3 then Last_Three := Stem (Stem'Last - 2 .. Stem'Last); if not ((Last_Three = "dic") or (Last_Three = "duc") or (Last_Three = "fac") or (Last_Three = "fer")) then Allowed := False; end if; else Allowed := False; end if; end if; end; -- Check for Verb Imperative being in permitted person if Pr.IR.Qual.Verb.Tense_Voice_Mood.Mood = Imp and then not (((Pr.IR.Qual.Verb.Tense_Voice_Mood.Tense = Pres) and (Pr.IR.Qual.Verb.Person = 2)) or else ((Pr.IR.Qual.Verb.Tense_Voice_Mood.Tense = Fut) and (Pr.IR.Qual.Verb.Person = 2 or Pr.IR.Qual.Verb.Person = 3))) then Allowed := False; end if; -- Check for V IMPERS and demand that only 3rd person if De.Part.V.Kind = Impers and then Pr.IR.Qual.Verb.Person /= 3 then Allowed := False; end if; -- Check for V DEP and demand PASSIVE if De.Part.V.Kind = Dep then --TEXT_IO.PUT ("DEP "); if (Pr.IR.Qual.Verb.Tense_Voice_Mood.Voice = Active) and (Pr.IR.Qual.Verb.Tense_Voice_Mood.Mood = Inf) and (Pr.IR.Qual.Verb.Tense_Voice_Mood.Tense = Fut) then --TEXT_IO.PUT ("PASSIVE "); Allowed := True; elsif (Pr.IR.Qual.Verb.Tense_Voice_Mood.Voice = Active) and (Pr.IR.Qual.Verb.Tense_Voice_Mood.Mood in Ind .. Inf) then --TEXT_IO.PUT ("ACTIVE "); Allowed := False; else --TEXT_IO.PUT ("?????? "); null; end if; end if; -- Check for V SEMIDEP and demand PASSIVE ex Perf if De.Part.V.Kind = Semidep and (Pr.IR.Qual.Verb.Tense_Voice_Mood.Mood in Ind .. Imp) and (((Pr.IR.Qual.Verb.Tense_Voice_Mood.Voice = Passive) and (Pr.IR.Qual.Verb.Tense_Voice_Mood.Tense in Pres .. Fut)) or ((Pr.IR.Qual.Verb.Tense_Voice_Mood.Voice = Active) and (Pr.IR.Qual.Verb.Tense_Voice_Mood.Tense in Perf .. Futp))) then Allowed := False; end if; if Words_Mdev (For_Word_List_Check) then if (Pr.IR.Qual.Verb.Person = 1) and then (Pr.IR.Qual.Verb.Number = S) then Allowed := (Pr.IR.Qual.Verb.Tense_Voice_Mood = (Pres, Active, Ind)) and ((De.Part.V.Kind in X .. Intrans) or else (De.Part.V.Kind = Dep) or else (De.Part.V.Kind = Semidep) or else (De.Part.V.Kind = Perfdef)); elsif De.Part.V.Kind = Impers then Allowed := (Pr.IR.Qual.Verb.Person = 3) and then (Pr.IR.Qual.Verb.Number = S) and then (Pr.IR.Qual.Verb.Tense_Voice_Mood = (Pres, Active, Ind)); else Allowed := False; end if; end if; when others => null; end case; if Words_Mdev (For_Word_List_Check) then -- Non parts if Pr.IR.Qual.Pofs in Vpar .. Supine then Allowed := False; end if; end if; -- Non parts return Allowed; end Allowed_Stem; -- FIXME: Pa is effectively passed in twice; Sl is often a slice of Pa procedure Order_Parse_Array (Sl : in out Parse_Array; Diff_J : out Integer; Pa : in Parse_Array) is use Dict_IO; Hits : Integer := 0; Sl_Last : Integer := Sl'Last; Sl_Last_Initial : constant Integer := Sl_Last; Sm : Parse_Record; Has_Noun_Abbreviation : Boolean := False; Not_Only_Archaic : Boolean := False; Not_Only_Medieval : Boolean := False; Not_Only_Uncommon : Boolean := False; function Depr (Pr : Parse_Record) return Dictionary_Entry is De : Dictionary_Entry; begin -- TEXT_IO.PUT ("DEPR "); -- PARSE_RECORD_IO.PUT (PR); -- TEXT_IO.NEW_LINE; -- FIXME: duplicates (commented) code above if Pr.MNPC = Null_MNPC then return Null_Dictionary_Entry; else if Pr.D_K in General .. Local then --if PR.MNPC /= OMNPC then Dict_IO.Set_Index (Dict_File (Pr.D_K), Pr.MNPC); Dict_IO.Read (Dict_File (Pr.D_K), De); --OMNPC := PR.MNPC; --ODE := DE; --else --DE := ODE; --end if; elsif Pr.D_K = Unique then De := Uniques_De (Pr.MNPC); end if; end if; return De; end Depr; begin if Sl'Length = 0 then Diff_J := Sl_Last_Initial - Sl_Last; return; end if; -- FIXME: this code looks like it's duplicated in another file -- Bubble sort since this list should usually be very small (1-5) Hit_Loop : loop Hits := 0; -------------------------------------------------- Switch : declare function "<" (Left, Right : Quality_Record) return Boolean is begin if Left.Pofs = Right.Pofs and then Left.Pofs = Pron and then Left.Pron.Decl.Which = 1 then return (Left.Pron.Decl.Var < Right.Pron.Decl.Var); else return Inflections_Package."<"(Left, Right); end if; end "<"; function Equ (Left, Right : Quality_Record) return Boolean is begin if Left.Pofs = Right.Pofs and then Left.Pofs = Pron and then Left.Pron.Decl.Which = 1 then return (Left.Pron.Decl.Var = Right.Pron.Decl.Var); else return Inflections_Package."="(Left, Right); end if; end Equ; function Meaning (Pr : Parse_Record) return Meaning_Type is begin return Depr (Pr).Mean; end Meaning; function Compare (L : Parse_Record; R : Parse_Record) return Boolean is begin -- Maybe < = on PR.STEM - will have to make up "<" -- Actually STEM and PART -- and check that later in print return R.D_K > L.D_K or else -- Let DICT.LOC list first (R.D_K = L.D_K and then R.MNPC < L.MNPC) or else (R.D_K = L.D_K and then R.MNPC = L.MNPC and then R.IR.Qual < L.IR.Qual) or else (R.D_K = L.D_K and then R.MNPC = L.MNPC and then Equ (R.IR.Qual, L.IR.Qual) and then Meaning (R) < Meaning (L)) or else -- | is > letter (R.D_K = L.D_K and then R.MNPC = L.MNPC and then Equ (R.IR.Qual, L.IR.Qual) and then Meaning (R) = Meaning (L) and then R.IR.Ending.Size < L.IR.Ending.Size) or else (R.D_K = L.D_K and then R.MNPC = L.MNPC and then Equ (R.IR.Qual, L.IR.Qual) and then Meaning (R) = Meaning (L) and then R.IR.Ending.Size = L.IR.Ending.Size and then Inflections_Package."<"(R.IR.Qual, L.IR.Qual)); end Compare; begin -- Need to remove duplicates in ARRAY_STEMS -- This sort is very sloppy -- One problem is that it can mix up some of the order of -- PREFIX, XXX, LOC -- I ought to do this for every set of results from -- different approaches not just in one fell swoop -- at the end !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Inner_Loop : for I in Sl'First .. Sl_Last - 1 loop if Compare (Sl (I), Sl (I + 1)) then Sm := Sl (I); Sl (I) := Sl (I + 1); Sl (I + 1) := Sm; Hits := Hits + 1; end if; end loop Inner_Loop; end Switch; -------------------------------------------------- exit Hit_Loop when Hits = 0; end loop Hit_Loop; -- Fix up the Archaic/Medieval if Words_Mode (Trim_Output) then -- Check to see if we can afford to TRIM, -- if there will be something left over for I in Sl'First .. Sl_Last loop declare De : Dictionary_Entry; begin if Sl (I).D_K in General .. Local then Dict_IO.Set_Index (Dict_File (Sl (I).D_K), Sl (I).MNPC); --TEXT_IO.PUT (INTEGER'IMAGE (INTEGER (SL (I).MNPC))); Dict_IO.Read (Dict_File (Sl (I).D_K), De); --DICTIONARY_ENTRY_IO.PUT (DE); TEXT_IO.NEW_LINE; if ((Sl (I).IR.Age = X) or else (Sl (I).IR.Age > A)) and ((De.Tran.Age = X) or else (De.Tran.Age > A)) then Not_Only_Archaic := True; end if; if ((Sl (I).IR.Age = X) or else (Sl (I).IR.Age < F)) and -- Or E???? ((De.Tran.Age = X) or else (De.Tran.Age < F)) then Not_Only_Medieval := True; end if; if ((Sl (I).IR.Freq = X) or else (Sl (I).IR.Freq < C)) and -- A/X < C -- C for inflections is uncommon !!!! ((De.Tran.Freq = X) or else (De.Tran.Freq < D)) -- -- E for DICTLINE is uncommon !!!! then Not_Only_Uncommon := True; end if; if Sl (I).IR.Qual.Pofs = N and then Sl (I).IR.Qual.Noun.Decl = (9, 8) then Has_Noun_Abbreviation := True; end if; end if; end; end loop; -- We order and Trim within a subset SL, but have to correct the -- big set PA also -- Kill not ALLOWED first, then check the remaining from the top -- I am assuming there is no Trim ming of FIXES for AGE/ .. . for I in reverse Sl'First .. Sl_Last loop -- Remove not ALLOWED_STEM & null if not Allowed_Stem (Sl (I)) or (Pa (I) = Null_Parse_Record) then Sl (I .. Sl_Last - 1) := Sl (I + 1 .. Sl_Last); Sl_Last := Sl_Last - 1; Trimmed := True; elsif (Not_Only_Archaic and Words_Mdev (Omit_Archaic)) and then Sl (I).IR.Age = A then Sl (I .. Sl_Last - 1) := Sl (I + 1 .. Sl_Last); Sl_Last := Sl_Last - 1; Trimmed := True; elsif (Not_Only_Medieval and Words_Mdev (Omit_Medieval)) and then Sl (I).IR.Age >= F then Sl (I .. Sl_Last - 1) := Sl (I + 1 .. Sl_Last); Sl_Last := Sl_Last - 1; Trimmed := True; elsif (Not_Only_Uncommon and Words_Mdev (Omit_Uncommon)) and then Sl (I).IR.Freq >= C then -- Remember A < C Sl (I .. Sl_Last - 1) := Sl (I + 1 .. Sl_Last); Sl_Last := Sl_Last - 1; Trimmed := True; ----Big problem. This area has been generaing exceptions. ----At least one difficulty is that suffixes change POFS. ----So one has a N inflection (SL) but a V DE ----When the program checks for VOC, it wants a N ---- and then asks about KIND (P, N, T, .. .) ---- But the DE (v) does not have those ---- The solution would be to fix ADD SUFFIX ---- to do somethnig about -- passing the ADDON KIND ---- I do not want to face that now ---- It is likely that all this VOC/LOC is worthless anyway. --- Maybe lower FREQ in INFLECTS ---- ---- A further complication is the GANT and AO give -- different results (AO no exception) ---- That is probably because the program is in -- error and the result threrfore unspecified ---- ---- -- This is really working much too hard! -- just to kill Roman numeral for three single letters -- Also strange in that code depends on dictionary knowledge elsif Has_Noun_Abbreviation and then (All_Caps and Followed_By_Period) then if (Sl (I).IR.Qual.Pofs /= N) or ((Sl (I).IR.Qual /= (N, ((9, 8), X, X, M))) and (Trim (Sl (I).Stem)'Length = 1 and then (Sl (I).Stem (1) = 'A' or Sl (I).Stem (1) = 'C' or Sl (I).Stem (1) = 'D' or --SL (I).STEM (1) = 'K' or -- No problem here Sl (I).Stem (1) = 'L' or Sl (I).Stem (1) = 'M' -- or ))) then Sl (I .. Sl_Last - 1) := Sl (I + 1 .. Sl_Last); Sl_Last := Sl_Last - 1; Trimmed := True; end if; end if; end loop; end if; -- On TRIM Diff_J := Sl_Last_Initial - Sl_Last; end Order_Parse_Array; procedure List_Sweep (Pa : in out Parse_Array; Pa_Last : in out Integer) is -- This procedure is supposed to process the Output PARSE_ARRAY at -- PA level -- before it gets turned into SIRAA and DMNPCA in LIST_PACKAGE -- Since it does only PARSE_ARRAY it is just cheaking INFLECTIONS, not -- DICTIONARY ----------------------------------------------------------- begin -- LIST_SWEEP if Pa'Length = 0 then return; end if; Reset_Pronoun_Kind : declare De : Dictionary_Entry; begin for I in 1 .. Pa_Last loop if Pa (I).D_K = General then Dict_IO.Set_Index (Dict_File (Pa (I).D_K), Pa (I).MNPC); Dict_IO.Read (Dict_File (Pa (I).D_K), De); if De.Part.Pofs = Pron and then De.Part.Pron.Decl.Which = 1 then Pa (I).IR.Qual.Pron.Decl.Var := Pronoun_Kind_Type'Pos (De.Part.Pron.Kind); end if; end if; end loop; end Reset_Pronoun_Kind; --------------------------------------------------- -- NEED TO REMOVE DISALLOWED BEFORE DOING ANYTHING - BUT -- WITHOUT REORDERING -- The problem I seem to have to face first, if not the first problem, -- is the situation in which there are several sets of identical IRs -- with different MNPC. These may be variants with some other stem -- (e.g., K=3) not affecting the (K=1) word. Or they might be -- identical forms with different meanings (| additional meanings) -- I need to group such common inflections - and pass this on somehow Sweeping : -- To remove disallowed stems/inflections and resulting dangling fixes declare Internal_Loop_Error : exception; Fix_On : Boolean := False; Pw_On : Boolean := False; P_First : Integer := 1; P_Last : Integer := 0; Jj : Integer := 0; Diff_J : Integer := 0; subtype Xons is Part_Of_Speech_Type range Tackon .. Suffix; begin for J in reverse 1 .. Pa_Last loop -- Sweep backwards over PA if ((Pa (J).D_K in Addons .. Yyy) or (Pa (J).IR.Qual.Pofs in Xons)) and then (Pw_On) then -- first FIX/TRICK after regular Fix_On := True; Pw_On := False; P_First := J + 1; Jj := J; while Pa (Jj + 1).IR.Qual.Pofs = Pa (Jj).IR.Qual.Pofs loop P_Last := Jj + 1; Raise_Exception (Internal_Loop_Error'Identity, "Programming error; known bug, #70"); end loop; ----Order internal to this set of inflections Order_Parse_Array (Pa (P_First .. P_Last), Diff_J, Pa); Pa (P_Last - Diff_J + 1 .. Pa_Last - Diff_J) := Pa (P_Last + 1 .. Pa_Last); Pa_Last := Pa_Last - Diff_J; P_First := 1; P_Last := 0; elsif ((Pa (J).D_K in Addons .. Yyy) or (Pa (J).IR.Qual.Pofs in Xons)) and then (Fix_On) then -- another FIX null; elsif ((Pa (J).D_K in Addons .. Yyy) or (Pa (J).IR.Qual.Pofs = X)) and then -- Kills TRICKS stuff (not Pw_On) then Pa (P_Last - Diff_J + 1 .. Pa_Last - Diff_J) := Pa (P_Last + 1 .. Pa_Last); Pa_Last := Pa_Last - Diff_J; P_Last := P_Last - 1; else Pw_On := True; Fix_On := False; if P_Last <= 0 then P_Last := J; end if; if J = 1 then Order_Parse_Array (Pa (1 .. P_Last), Diff_J, Pa); Pa (P_Last - Diff_J + 1 .. Pa_Last - Diff_J) := Pa (P_Last + 1 .. Pa_Last); Pa_Last := Pa_Last - Diff_J; end if; end if; -- check PART end loop; -- loop sweep over PA end Sweeping; -- Last chance to weed out duplicates declare Pr : Parse_Record := Null_Parse_Record; Opr : Parse_Record := Pa (1); J : Integer := 2; begin Compress_Loop : loop exit Compress_Loop when J > Pa_Last; Pr := Pa (J); if Pr /= Opr then Supress_Key_Check : declare function "<=" (A, B : Parse_Record) return Boolean is use Dict_IO; begin -- !!!!!!!!!!!!!!!!!!!!!!!!!! return A.IR.Qual = B.IR.Qual and A.MNPC = B.MNPC; end "<="; begin if (Pr.D_K /= Xxx) and (Pr.D_K /= Yyy) and (Pr.D_K /= Ppp) then if Pr <= Opr then -- Get rid of duplicates, if ORDER is OK Pa (J .. Pa_Last - 1) := Pa (J + 1 .. Pa_Last); -- Shift PA down 1 Pa_Last := Pa_Last - 1; -- because found key duplicate end if; else J := J + 1; end if; end Supress_Key_Check; else J := J + 1; end if; Opr := Pr; end loop Compress_Loop; end; for I in 1 .. Pa_Last loop -- Destroy the artificial VAR for PRON 1 X if Pa (I).IR.Qual.Pofs = Pron and then Pa (I).IR.Qual.Pron.Decl.Which = 1 then Pa (I).IR.Qual.Pron.Decl.Var := 0; end if; if Pa (I).IR.Qual.Pofs = V then if Pa (I).IR.Qual.Verb.Con = (3, 4) then -- Fix V 3 4 to be 4th conjugation Pa (I).IR.Qual.Verb.Con := (4, 1); -- else -- -- Set to 0 other VAR for V -- PA (I).IR.QUAL.V.CON.VAR := 0; end if; end if; end loop; end List_Sweep; end Words_Engine.List_Sweep;
with Asis; package Unit_Processing is -- Translate all FP operations in the body of a compilation unit -- to PolyPaver-friendly function calls. procedure Process_Unit (The_Unit : Asis.Compilation_Unit; Trace : Boolean := False; Output_Path : String); end Unit_Processing;
function Is_Palindrome(S: Seq) return Boolean is J: Index := S'Last; begin for I in S'Range loop if S(I) /= S(J) then return False; end if; exit when I = S'Last; J := Index'Pred(J); end loop; return True; end Is_Palindrome;
----------------------------------------------------------------------- -- awa-permissions -- Permissions module -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Security.Permissions; with Security.Policies; with Util.Serialize.Mappers; private with Util.Beans.Objects; with ADO; with ADO.Objects; private with ADO.Sessions; -- == AWA Permissions == -- The *AWA.Permissions* framework defines and controls the permissions used by an application -- to verify and grant access to the data and application service. The framework provides a -- set of services and API that helps an application in enforcing its specific permissions. -- Permissions are verified by a permission controller which uses the service context to -- have information about the user and other context. The framework allows to use different -- kinds of permission controllers. The `Entity_Controller` is the default permission -- controller which uses the database and an XML configuration to verify a permission. -- -- === Declaration === -- To be used in the application, the first step is to declare the permission. -- This is a static definition of the permission that will be used to ask to verify the -- permission. The permission is given a unique name that will be used in configuration files: -- -- with Security.Permissions; -- ... -- package ACL_Create_Post is new Security.Permissions.Definition ("blog-create-post"); -- -- === Checking for a permission === -- A permission can be checked in Ada as well as in the presentation pages. -- This is done by using the `Check` procedure and the permission definition. This operation -- acts as a barrier: it does not return anything but returns normally if the permission is -- granted. If the permission is denied, it raises the `NO_PERMISSION` exception. -- -- Several `Check` operation exists. Some require no argument and some others need a context -- such as some entity identifier to perform the check. -- -- with AWA.Permissions; -- ... -- AWA.Permissions.Check (Permission => ACL_Create_Post.Permission, -- Entity => Blog_Id); -- -- === Configuring a permission === -- The *AWA.Permissions* framework supports a simple permission model -- The application configuration file must provide some information to help in checking the -- permission. The permission name is referenced by the `name` XML entity. The `entity-type` -- refers to the database entity (ie, the table) that the permission concerns. -- The `sql` XML entity represents the SQL statement that must be used to verify the permission. -- -- <entity-permission> -- <name>blog-create-post</name> -- <entity-type>blog</entity-type> -- <description>Permission to create a new post.</description> -- <sql> -- SELECT acl.id FROM acl -- WHERE acl.entity_type = :entity_type -- AND acl.user_id = :user_id -- AND acl.entity_id = :entity_id -- </sql> -- </entity-permission> -- -- === Adding a permission === -- Adding a permission means to create an `ACL` database record that links a given database -- entity to the user. This is done easily with the `Add_Permission` procedure: -- -- with AWA.Permissions.Services; -- ... -- AWA.Permissions.Services.Add_Permission (Session => DB, -- User => User, -- Entity => Blog); -- -- === Data Model === -- [images/awa_permissions_model.png] -- -- === Queries === -- @include permissions.xml -- package AWA.Permissions is NAME : constant String := "Entity-Policy"; -- Exception raised by the <b>Check</b> procedure if the user does not have -- the permission. NO_PERMISSION : exception; -- Maximum number of entity types that can be defined in the XML entity-permission. -- Most permission need only one entity type. Keep that number small. MAX_ENTITY_TYPES : constant Positive := 5; type Entity_Type_Array is array (1 .. MAX_ENTITY_TYPES) of ADO.Entity_Type; type Permission_Type is (READ, WRITE); type Entity_Permission is new Security.Permissions.Permission with private; -- Verify that the permission represented by <b>Permission</b> is granted. -- procedure Check (Permission : in Security.Permissions.Permission_Index); -- Verify that the permission represented by <b>Permission</b> is granted to access the -- database entity represented by <b>Entity</b>. procedure Check (Permission : in Security.Permissions.Permission_Index; Entity : in ADO.Identifier); -- Verify that the permission represented by <b>Permission</b> is granted to access the -- database entity represented by <b>Entity</b>. procedure Check (Permission : in Security.Permissions.Permission_Index; Entity : in ADO.Objects.Object_Ref'Class); private type Entity_Permission is new Security.Permissions.Permission with record Entity : ADO.Identifier; end record; type Entity_Policy; type Entity_Policy_Access is access all Entity_Policy'Class; type Controller_Config is record Name : Util.Beans.Objects.Object; SQL : Util.Beans.Objects.Object; Grant : Util.Beans.Objects.Object; Entity : ADO.Entity_Type := 0; Entities : Entity_Type_Array := (others => ADO.NO_ENTITY_TYPE); Count : Natural := 0; Manager : Entity_Policy_Access; Session : ADO.Sessions.Session; end record; type Entity_Policy is new Security.Policies.Policy with record Config : aliased Controller_Config; end record; -- Get the policy name. overriding function Get_Name (From : in Entity_Policy) return String; -- Setup the XML parser to read the <b>policy</b> description. overriding procedure Prepare_Config (Policy : in out Entity_Policy; Mapper : in out Util.Serialize.Mappers.Processing); end AWA.Permissions;
------------------------------------------------------------------------------ -- -- -- GNAT EXAMPLE -- -- -- -- Copyright (C) 2013, AdaCore -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, -- -- Boston, MA 02110-1301, USA. -- -- -- -- As a special exception, if other files instantiate generics from this -- -- unit, or you link this unit with other files to produce an executable, -- -- this unit does not by itself cause the resulting executable to be -- -- covered by the GNU General Public License. This exception does not -- -- however invalidate any other reasons why the executable file might be -- -- covered by the GNU Public License. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with System; with Interfaces; use Interfaces; with Lm3s8962; use Lm3s8962; package body Oled is PORT_OLED_CS : constant := 2#0000_1000#; -- GPIOA3 PORT_OLED_DC : constant := 2#0100_0000#; -- GPIOA6 PORT_OLED_15V : constant := 2#1000_0000#; -- GPIOA7 procedure Oled_Init is begin -- Enable SSI0, GPIO port A (for CS, D/C and +15V) RCGC2 := RCGC2 or 16#1#; RCGC1 := RCGC1 or 16#10#; -- Configure SSI0 CLK, TX and RX for SSI, /CS, D/C, +15V GPIOA_AFSEL := (GPIOA_AFSEL or 2#110100#) and not (PORT_OLED_CS or PORT_OLED_15V or PORT_OLED_DC); GPIOA_DEN := GPIOA_DEN or 2#110100# or PORT_OLED_CS or PORT_OLED_15V or PORT_OLED_DC; GPIOA_DIR := GPIOA_DIR or PORT_OLED_CS or PORT_OLED_15V or PORT_OLED_DC; -- Enable power, no select GPIOA_DATA (PORT_OLED_15V + PORT_OLED_CS) := PORT_OLED_15V or PORT_OLED_CS; -- Configure SSI0. SSICR1 := 2#000#; -- Master, disable SSICPSR := 10; -- 10 for 1 Mhz, 20 for 500 Khz SSICR0 := 16#4_C_7#; -- SCR=4, SPH=1, SPO=1, FRF=SPI, DSS=8bit SSICR1 := 2#010#; -- Master, Enable Oled_Cmd ((16#fd#, 16#12#, 16#e3#, -- Unlock + Nop 16#ae#, 16#e3#, -- Display off, sleep + Nop 16#94#, 16#00#, 16#e3#, -- Icon off + Nop 16#a8#, 95, 16#e3#, -- Multiplex = 95 + 1 + Nop 16#81#, 16#b7#, 16#e3#, -- Contrast 16#82#, 16#3f#, 16#e3#, -- Pre-charge current + Nop 16#a0#, 16#52#, 16#e3#, -- Init re-map 16#a1#, 0, 16#e3#, -- Display start line 16#a2#, 0, 16#e3#, -- Display offset 16#a4#, 16#e3#, -- Normal display 16#b1#, 16#11#, 16#e3#, -- Phase length 16#b2#, 16#23#, 16#e3#, -- Frame frequency 16#b3#, 16#e2#, 16#e3#, -- Front clock divider 16#b7#, 16#e3#, -- Default gray scale table 16#bb#, 16#01#, 16#e3#, -- Second pre-charge period 16#bc#, 16#3f#, 16#e3#, -- First pre-charge voltage 16#af#, 16#e3#, -- Display on 16#e3#)); Oled_Clear; end Oled_Init; procedure Oled_Write (Byte : Unsigned_8) is Dummy : Unsigned_32; begin SSIDR := Unsigned_32 (Byte); -- Wait until empty while (SSISR and SSISR_TFE) = 0 loop null; end loop; -- Wait until receive not empty while (SSISR and SSISR_RNE) = 0 loop null; end loop; -- Drain RX fifo Dummy := SSIDR; end Oled_Write; procedure Oled_Write (Bytes : Byte_Array) is begin -- Write bytes. for I in Bytes'Range loop Oled_Write (Bytes (I)); end loop; end Oled_Write; procedure Oled_Cmd (Bytes : Byte_Array) is begin -- Set D/C to command, enable /CS GPIOA_DATA (PORT_OLED_CS + PORT_OLED_DC) := 0; Oled_Write (Bytes); end Oled_Cmd; procedure Oled_Select_Data is begin -- Set D/C to data, enable /CS GPIOA_DATA (PORT_OLED_CS + PORT_OLED_DC) := PORT_OLED_DC; end Oled_Select_Data; procedure Oled_Data (Bytes : Byte_Array) is begin Oled_Select_Data; Oled_Write (Bytes); end Oled_Data; procedure Oled_Clear is begin Oled_Cmd ((16#15#, 0, 63, -- Columns 0-63 16#75#, 0, 127, -- Lines 0-127 16#a0#, 16#52#, -- Horizontal inc 16#e3#)); Oled_Select_Data; for I in 1 .. 96 loop for J in 1 .. 128 / 16 loop Oled_Write ((0 .. 7 => 0)); end loop; end loop; end Oled_Clear; procedure Draw_Image (X : Col_Type; Y : Line_Type; Image : Image_Type) is begin -- Define box Oled_Cmd ((16#15#, Unsigned_8 (X), Unsigned_8 (X) + Image'Length (2) - 1, 16#75#, Unsigned_8 (Y), Unsigned_8 (Y) + Image'Length (1) - 1, 16#a0#, 16#52#, -- Horizontal inc 16#e3#)); Oled_Select_Data; for I in Image'Range (1) loop for J in Image'Range (2) loop Oled_Write (Image (I, J)); end loop; end loop; end Draw_Image; end Oled;
--=========================================================================== -- -- This package defines the four 5x7 matrix elements used for the -- DOUBLE WORD sized display capability -- --=========================================================================== -- Copyright 2021 (C) Holger Rodriguez -- -- SPDX-License-Identifier: BSD-3-Clause -- with HAL; use HAL; with HAL.I2C; with RP.I2C_Master; with RP.Device; with ItsyBitsy; with Hex_2Digits_Display; package Matrix_Area_Double_Word is I2C_1 : RP.I2C_Master.I2C_Master_Port renames ItsyBitsy.I2C; -------------------------------------------------------------------------- -- Byte 1: this display is in the right side of the two displays -- represents the higher byte of the lower word -------------------------------------------------------------------------- Byte_0_I2C : HAL.I2C.Any_I2C_Port := I2C_1'Access; Byte_0_Address : HAL.I2C.I2C_Address := 16#63# * 2; package Byte_0 is new Hex_2Digits_Display (Byte_0_I2C, Byte_0_Address); I2C_0 : RP.I2C_Master.I2C_Master_Port renames RP.Device.I2C_0; -------------------------------------------------------------------------- -- Byte 1: this display is in the right side of the two displays -- represents the higher byte of the lower word -------------------------------------------------------------------------- Byte_1_I2C : HAL.I2C.Any_I2C_Port := I2C_0'Access; Byte_1_Address : HAL.I2C.I2C_Address := 16#61# * 2; package Byte_1 is new Hex_2Digits_Display (Byte_1_I2C, Byte_1_Address); -------------------------------------------------------------------------- -- Byte 2: this display is in the right side of the two displays -- represents the lower byte of the higher word -------------------------------------------------------------------------- Byte_2_I2C : HAL.I2C.Any_I2C_Port := I2C_0'Access; Byte_2_Address : HAL.I2C.I2C_Address := 16#62# * 2; package Byte_2 is new Hex_2Digits_Display (Byte_2_I2C, Byte_2_Address); -------------------------------------------------------------------------- -- Byte 3: this display is in the left side of the two displays -- represents the higher byte of the higher word -------------------------------------------------------------------------- Byte_3_I2C : HAL.I2C.Any_I2C_Port := I2C_0'Access; Byte_3_Address : HAL.I2C.I2C_Address := 16#63# * 2; package Byte_3 is new Hex_2Digits_Display (Byte_3_I2C, Byte_3_Address); -------------------------------------------------------------------------- -- Initializes the Double Word Matrix Block -- Must be called before anything else regarding the matrix. -------------------------------------------------------------------------- procedure Initialize; end Matrix_Area_Double_Word;
-- This file is generated by SWIG. Do *not* modify by hand. -- package LLVM_bit_Writer is end LLVM_bit_Writer;
package Overload is function Minus(x, y : in integer) return integer; end Overload;
-- { dg-do compile } package Atomic1 is type Arr is array (Integer range <>) of Boolean; type UA is access all Arr; U : UA; pragma Atomic (U); -- { dg-error "atomic access" "" { xfail mips*-*-* } } type R is record U : UA; pragma Atomic (U); -- { dg-error "atomic access" "" { xfail mips*-*-* } } end record; end Atomic1;
with Eval; package My_Custom_Int is type My_Custom_Int is record Int_Val : Integer range 1 .. 100; end record; function Image (E: in My_Custom_Int) return String; function "=" (L, R : in My_Custom_Int) return Boolean; function "+" (L, R : in My_Custom_Int) return My_Custom_Int; function "-" (L, R : in My_Custom_Int) return My_Custom_Int; function "*" (L, R : in My_Custom_Int) return My_Custom_Int; function "/" (L, R : in My_Custom_Int) return My_Custom_Int; end My_Custom_Int;
with U_Lexica; use U_Lexica; package body Semantica.Ctipus is procedure Mt_Atom (L, C : in Natural; A : out Atribut) is begin A := (Atom, L, C); end Mt_Atom; procedure Mt_Identificador (L, C : in Natural; S : in String; A : out Atribut) is Id : Id_Nom; begin Id := Id_Nul; Posa_Id(Tn, Id, S); A := (A_Ident, L, C, Id); end Mt_Identificador; procedure Mt_String (L, C : in Natural; S : in String; A : out Atribut) is Id : Rang_Tcar; begin Posa_Str(Tn, Id, S); A := (A_Lit_S, L, C, Valor(Id)); end Mt_String; procedure Mt_Caracter (L, C : in Natural; Car : in String; A : out Atribut) is begin A := (A_Lit_C, L, C, Valor(Character'Pos(Car(Car'First+1)))); end Mt_Caracter; procedure Mt_Numero (L, C : in Natural; S : in String; A : out Atribut) is begin A := (A_Lit_N, L, C, Valor(Integer'Value(S))); end Mt_Numero; -- Taula de simbols procedure Inicia_Enter is D : Descrip; Dt : Descriptipus; Idn, Ida, Idint : Id_Nom; E : Boolean; Ipr : Info_Proc; Idpr : Num_Proc; Iv : Info_Var; Idv : Num_Var; begin -- Constants inicials Posa_Id(Tn, Idn, "_zero"); Iv := (Idn, Tp.Np, Integer'Size/8, 0, Tsent, False, True, 0); Nv := Nv + 1; Posa(Tv, Iv, Zero); Posa_Id(Tn, Idn, "_menysu"); Iv := (Idn, Tp.Np, Integer'Size/8, 0, Tsent, False, True, -1); Posa(Tv, Iv, Menysu); Nv := Nv + 1; -- "Integer" Posa_Id(Tn, Idint, "integer"); Dt := (Tsent, Integer'Size/8, Valor(Integer'First), Valor(Integer'Last)); D := (Dtipus, Dt); Posa(Ts, Idint, D, E); -- "puti" Posa_Id(Tn, Idn, "puti"); Ipr := (Extern, 4, Idn); Posa(Tp, Ipr, Idpr); Np := Np + 1; D := (Dproc, Idpr); Posa(Ts, Idn, D, E); Posa_Id(Tn, Ida, "_arg_puti"); Iv := (Ida, Idpr, Integer'Size/8, Ipr.Ocup_Param, Tsent, True, False, 0); Posa(Tv, Iv, Idv); Nv := Nv + 1; D := (Dargc, Idv, Idint); Posa(Ts, Ida, D, E); Posa_Arg(Ts, Idn, Ida, D, E); Ipr.Ocup_Param := Ipr.Ocup_Param + Iv.Ocup; -- "geti" Posa_Id(Tn, Idn, "geti"); Ipr := (Extern, 4, Idn); Posa(Tp, Ipr, Idpr); Np := Np + 1; D := (Dproc, Idpr); Posa(Ts, Idn, D, E); Posa_Id(Tn, Ida, "_arg_geti"); Iv := (Ida, Idpr, Integer'Size/8, Ipr.Ocup_Param, Tsent, True, False, 0); Posa(Tv, Iv, Idv); Nv := Nv + 1; D := (Dargc, Idv, Idint); Posa(Ts, Ida, D, E); Posa_Arg(Ts, Idn, Ida, D, E); Ipr.Ocup_Param := Ipr.Ocup_Param + Iv.Ocup; end Inicia_Enter; procedure Inicia_Boolea is D : Descrip; Dt : Descriptipus; Idb, Idt, Idf : Id_Nom; E : Boolean; Iv : Info_Var; Idv : Num_Var; begin Posa_Id(Tn, Idb, "boolean"); Dt := (Tsbool, Integer'Size/8, -1, 0); D := (Dtipus, Dt); Posa(Ts, Idb, D, E); Posa_Id(Tn, Idt, "true"); Iv := (Idt, 0, Integer'Size/8, 0, Tsbool, False, True, -1); Posa(Tv, Iv, Idv); Nv := Nv+1; D := (Dconst, Idb, -1, Nv); Posa(Ts, Idt, D, E); Posa_Id(Tn, Idf, "false"); Iv.Id := Idf; Iv.Valconst := 0; Posa(Tv, Iv, Idv); Nv := Nv+1; D := (Dconst, Idb, 0, Nv); Posa(Ts, Idf, D, E); end Inicia_Boolea; procedure Inicia_Caracter is D : Descrip; Dt : Descriptipus; Idn, Idstring, Ida, Idchar : Id_Nom; E : Boolean; Ipr : Info_Proc; Idpr : Num_Proc; Iv : Info_Var; Idv : Num_Var; begin -- "character" Posa_Id(Tn, Idchar, "character"); Dt := (Tscar, 4, Valor(Character'Pos(Character'First)), Valor(Character'Pos(Character'Last))); D := (Dtipus, Dt); Posa(Ts, Idchar, D, E); -- "string" Posa_Id(Tn, Idstring, "string"); Dt := (Tsstr, 4, Idchar, 0); --0 es la base D := (Dtipus, Dt); Posa(Ts, Idstring, D, E); -- putc Posa_Id(Tn, Idn, "putc"); Ipr := (Extern, 4, Idn); Posa(Tp, Ipr, Idpr); Np := Np + 1; D := (Dproc, Idpr); Posa(Ts, Idn, D, E); Posa_Id(Tn, Ida, "_arg_putc"); Iv := (Ida, Idpr, Integer'Size/8, Ipr.Ocup_Param, Tscar, True, False, 0); Posa(Tv, Iv, Idv); nv:= nv +1; D := (Dargc, Idv, Idchar); Posa(Ts, Ida, D, E); Posa_Arg(Ts, Idn, Ida, D, E); Ipr.Ocup_Param := Ipr.Ocup_Param + Iv.Ocup; -- getc Posa_Id(Tn, Idn, "getc"); Ipr := (Extern, 4, Idn); Posa(Tp, Ipr, Idpr); Np := Np + 1; D := (Dproc, Idpr); Posa(Ts, Idn, D, E); Posa_Id(Tn, Ida, "_arg_getc"); Iv := (Ida, Idpr, Integer'Size/8, Ipr.Ocup_Param, Tscar, True, False, 0); Posa(Tv, Iv, Idv); nv:= nv +1; D := (Dargc, Idv, Idchar); Posa(Ts, Ida, D, E); Posa_Arg(Ts, Idn, Ida, D, E); Ipr.Ocup_Param := Ipr.Ocup_Param + Iv.Ocup; -- getcc Posa_Id(Tn, Idn, "getcc"); Ipr := (Extern, 4, Idn); Posa(Tp, Ipr, Idpr); Np := Np + 1; D := (Dproc, Idpr); Posa(Ts, Idn, D, E); Posa_Id(Tn, Ida, "_arg_getcc"); Iv := (Ida, Idpr, 1, Ipr.Ocup_Param, Tscar, True, False, 0); Posa(Tv, Iv, Idv); nv:= nv +1; D := (Dargc, Idv, Idchar); Posa(Ts, Ida, D, E); Posa_Arg(Ts, Idn, Ida, D, E); -- puts Posa_Id(Tn, Idn, "puts"); Ipr := (Extern, 4, Idn); Posa(Tp, Ipr, Idpr); Np := Np + 1; Id_Puts := Idpr; D := (Dproc, Idpr); Posa(Ts, Idn, D, E); --arg_puts Posa_Id(Tn, Ida, "_arg_puts"); Iv := (Ida, Idpr, 4, Ipr.Ocup_Param, Tsstr, True, False, 0);--16 * Integer'Size Posa(Tv, Iv, Idv); nv:= nv +1; D := (Dargc, Idv, Idstring); Posa(Ts, Ida, D, E); Posa_Arg(Ts, Idn, Ida, D, E); Ipr.Ocup_Param := Ipr.Ocup_Param + Iv.Ocup; -- gets Posa_Id(Tn, Idn, "gets"); Ipr := (Extern, 4, Idn); Posa(Tp, Ipr, Idpr); Np := Np + 1; Id_Gets := Idpr; D := (Dproc, Idpr); Posa(Ts, Idn, D, E); --arg_gets Posa_Id(Tn, Ida, "_arg_gets"); Iv := (Ida, Idpr, 4, Ipr.Ocup_Param, Tsstr, True, False, 0); Posa(Tv, Iv, Idv); Nv := Nv +1; D := (Dargc, Idv, Idstring); Posa(Ts, Ida, D, E); Posa_Arg(Ts, Idn, Ida, D, E); Ipr.Ocup_Param := Ipr.Ocup_Param + Iv.Ocup; -- nova linea Posa_Id(Tn, Idn, "new_line"); Ipr := (Extern, 0, Idn); Posa(Tp, Ipr, Idpr); Np := Np + 1; D := (Dproc, Idpr); Posa(Ts, Idn, D, E); end Inicia_Caracter; procedure Inicia_Analisi (Nomfitxer : in String) is begin Nv := 0; Np := 0; Tbuida(Tn); Tbuida(Ts); -- Iniciam les Taules Noves_Taules(Tp, Tv); Inicia_Enter; Inicia_Boolea; Inicia_Caracter; Obre_Fitxer(nomFitxer); end Inicia_analisi; -- Procediments interns procedure Posa_Idvar (Idvar : in Id_Nom; Idtipus : in Id_Nom; L, C : in Natural; E : out Boolean) is Tassig : Descrip; begin Nv := Nv + 1; Tassig := (Dvar, Idtipus, Nv); Posa(Ts, Idvar, Tassig, E); if E then Error(Id_Existent, L, C, Cons_Nom(Tn, Idvar)); Esem := True; end if; end Posa_Idvar; -- Comprovacio de tipus procedure Ct_Programa (A : in Pnode) is D : Descrip; Idproc : Id_nom renames A.Fid5.Id12; Ida : Cursor_Arg; begin Ct_Decprocediment(A); Ida := Primer_Arg(Ts, Idproc); if (Arg_Valid(Ida)) then Error(Paramspprincipal, Cons_Nom(Tn, Idproc)); Esem := True; end if; Tts(Proc_Nul) := Ts; Tanca_Fitxer; end Ct_Programa; procedure Ct_Decprocediment (A : in Pnode) is Encap : Pnode renames A.Fe5; Decls : Pnode renames A.Fc5; Bloc : Pnode renames A.Fd5; Id : Pnode renames A.Fid5; Id_Inf : Id_Nom renames A.Fid5.Id12; Id_Sup : Id_Nom; Tdecls : Tipusnode; np_propi : num_proc; begin Ct_Encap(Encap, Id_Sup); Np_Propi := Np; if Id_Inf /= Id_Sup then Error(Idprogdiferents, A.Fid5.l1, A.Fid5.c1, Cons_Nom(Tn, Id_Sup)); Esem := True; end if; Cons_Tnode(Decls, Tdecls); if Tdecls /= Tnul then Ct_Declaracions(Decls); end if; Ct_Bloc(Bloc); Tts(Np_Propi) := Ts; Surtbloc(Ts,tn); end Ct_Decprocediment; procedure Ct_Encap (A : in Pnode; I : out Id_Nom) is Tproc : Descrip; E : Boolean; Idx_Arg : Cursor_Arg; Ida : Id_Nom; Dn : Descrip; begin if A.Tipus = Pencap then Ct_Pencap(A, I); Idx_Arg := Primer_Arg(Ts, I); while Arg_Valid(Idx_Arg) loop Cons_Arg(Ts, Idx_Arg, Ida, Dn); Posa(Ts, Ida, Dn, E); if E then Error(Enregarg, 3, 3, Cons_Nom(Tn, Ida)); Esem := True; end if; Idx_Arg := Succ_Arg(Ts, Idx_Arg); end loop; else I := A.Id12; Np := Np + 1; Tproc := (Dproc, Np); Posa(Ts, I, Tproc, E); Entrabloc(Ts); if E then Error(Id_Existent, A.l1, A.C1, Cons_Nom(Tn, I)); Esem := True; end if; end if; end Ct_Encap; procedure Ct_Pencap (A : in Pnode; I : out Id_Nom) is Param : Pnode renames A.Fd1; Fesq : Pnode renames A.Fe1; Tproc : Descrip; E : Boolean; begin if Fesq.Tipus = Identificador then Np := Np + 1; Tproc := (Dproc, Np); Posa(Ts, Fesq.Id12, Tproc, E); if E then Error(Id_Existent, Fesq.L1, Fesq.C1, Cons_Nom(Tn, Fesq.Id12)); Esem := True; end if; Entrabloc(Ts); I := Fesq.Id12; else Ct_Pencap(Fesq, I); end if; Ct_Param(Param, I); end Ct_Pencap; procedure Ct_Param (A : in Pnode; I : in Id_Nom) is Idpar : Id_Nom renames A.Fe2.id12; Marg : Mmode renames A.Fc2.M12; Idtipus : Id_Nom renames A.Fd2.id12; D : Descrip; Darg : Descrip; E : Boolean; begin D := Cons(Ts, Idtipus); if D.Td /= Dtipus then Error(Tipusparam, A.Fd2.l1, A.Fd2.c1, Cons_Nom(Tn, Idtipus)); Esem := True; end if; case Marg is when Surt | Entrasurt => Nv := Nv + 1; Darg := (Dvar, Idtipus, Nv); when Entra => Nv := Nv + 1; Darg := (Dargc, Nv, Idtipus); when others => null; end case; Posa_Arg(Ts, I, Idpar, Darg, E); if E then Error(Enregarg, A.Fe2.l1, A.Fe2.c1, Cons_Nom(Tn, IdPar)); Esem := True; end if; end Ct_Param; procedure Ct_Declaracions (A : in Pnode) is Decl : Pnode renames A.Fd1; Decls : Pnode renames A.Fe1; Tnode : Tipusnode; Idrec : Id_Nom; Ocup : Despl; begin if Decls.Tipus = Declaracions then Ct_Declaracions(Decls); end if; Cons_Tnode(Decl, Tnode); case Tnode is when Dvariable => Ct_Decvar(Decl); when Dconstant => Ct_Decconst(Decl); when Dcoleccio => Ct_Deccol(Decl); when Dregistre | Dencapregistre | Firecord => Ocup := 0; Ct_Decregistre(Decl, Idrec,Ocup); when Dsubrang => Ct_Decsubrang(Decl); when Procediment => Ct_Decprocediment(Decl); when others => Esem := True; null; end case; end Ct_Declaracions; procedure Ct_Decvar (A : in Pnode) is Dvariable : Pnode renames A.Fd1; Id : Id_Nom renames A.Fe1.Id12; L : Natural renames A.Fe1.L1; C : Natural renames A.Fe1.C1; Tassig : Descrip; Idtipus : Id_nom; E : Boolean; begin Ct_Declsvar(Dvariable, Idtipus); Posa_Idvar(Id, Idtipus, L, C, E); end Ct_Decvar; procedure Ct_Declsvar (A : in Pnode; Idtipus : out Id_Nom) is Tnode : Tipusnode renames A.Tipus; E : Boolean; Tdecl : Descrip; begin if Tnode = Identificador then Tdecl := Cons(Ts, A.Id12); if (Tdecl.Td /= Dtipus) then Error(Tipusinexistent, A.L1, A.C1, Cons_Nom(Tn, A.Id12)); Esem := True; end if; Idtipus := A.Id12; elsif Tnode = Declmultvar then Ct_Declsvar(A.Fd1, Idtipus); Posa_Idvar(A.Fe1.Id12, Idtipus, A.Fe1.L1, A.Fe1.C1, E); end if; end Ct_Declsvar; procedure Ct_Decconst (A : in Pnode) is Id : Id_Nom renames A.Fe2.Id12; Idtipus : Id_Nom renames A.Fc2.Id12; Val : Pnode renames A.Fd2; E : Boolean; Tdecl : Descrip; Tconst : Descrip; Tsubj : Tipussubjacent; Ids : Id_Nom; L, C : Natural := 0; begin Tdecl := Cons(Ts, Idtipus); if (Tdecl.Td /= Dtipus) then Error(Tipusinexistent, A.Fc2.L1, A.Fc2.C1, Cons_Nom(Tn, Idtipus)); Esem := True; else Ct_Constant(Val, Tsubj, Ids, L, C); if (Tsubj /= Tdecl.Dt.Tt) then Error(Tipussubdiferents, A.Fc2.L1, A.Fc2.C1, Cons_Nom(Tn, Idtipus)); Esem := True; end if; if (Tdecl.Dt.Tt > Tsent) then Error(Tsub_No_Escalar, A.Fc2.L1, A.Fc2.C1, Cons_Nom(Tn, Idtipus)); Esem := True; end if; if (Tsubj = Tsent or Tsubj = Tsbool or Tsubj = Tscar) then if (Val.Val < Tdecl.Dt.Linf) or (Val.Val > Tdecl.Dt.Lsup) then Error(Rang_Sobrepassat, A.Fe2.L1, A.Fe2.C1, Cons_Nom(Tn, Id)); Esem := True; end if; end if; Nv := Nv + 1; Tconst := (Dconst, Idtipus, Val.Val, Nv); Posa(Ts, Id, Tconst, E); if E then Error(Id_Existent, A.Fe2.L1, A.Fe2.C1, Cons_Nom(Tn, Id)); Esem := True; end if; end if; end Ct_Decconst; procedure Ct_Deccol (A : in Pnode) is Darray : Descrip; Dtarray : Descrip; Fesq : Pnode renames A.Fe1; Idtipus_Array : Id_Nom renames A.Fd1.Id12; Idarray : Id_Nom; Ncomponents : Despl; begin Dtarray := Cons(Ts, Idtipus_Array); if (Dtarray.Td /= Dtipus) then Error(Tipusinexistent, A.Fd1.L1, A.Fd1.C1, Cons_Nom(Tn, Idtipus_Array)); Esem := True; else Ct_Pcoleccio(Fesq, Idtipus_Array, Idarray, Ncomponents); Darray := Cons(Ts, Idarray); Darray.Dt.Tcamp := Idtipus_Array; Darray.Dt.Ocup := Ncomponents * Dtarray.Dt.Ocup; Actualitza(Ts, Idarray, Darray); end if; end Ct_Deccol; procedure Ct_Pcoleccio (A : in Pnode; Idtipus_Array : in Id_Nom; Idarray : out Id_Nom; Ncomponents : out Despl) is Fesq : Pnode renames A.Fe1; Idrang : Id_Nom renames A.Fd1.Id12; E : Boolean; Dtarray : Descriptipus; Darray : Descrip; Di : Descrip; begin if (A.Tipus = Pcoleccio) then Ct_Pcoleccio(Fesq, Idtipus_Array, Idarray, Ncomponents); Posa_Idx(Ts, Idarray, Idrang, E); if E then Error(Posaidxarray, A.Fd1.L1, A.Fd1.C1, Cons_Nom(Tn, Idrang)); Esem := True; else Di := Cons(Ts, Idrang); if Di.Td = Dtipus then Ncomponents := Ncomponents * Despl(Di.Dt.Lsup - Di.Dt.Linf + 1); else Error(Tipusidxerroniarray, A.Fd1.L1, A.Fd1.C1, Cons_Nom(Tn, Idrang)); Esem := True; end if; end if; elsif (A.Tipus = Pdimcoleccio) then Dtarray := (Tsarr, 0, Idtipus_Array, 0); Darray := (Dtipus, Dtarray); Idarray := Fesq.Id12; Posa(Ts, Idarray, Darray, E); if E then Error(Tipusinexistent, Fesq.L1, Fesq.C1, Cons_Nom(Tn, Idtipus_Array)); Esem := True; Ncomponents := 0; end if; Di := Cons(Ts, Idrang); if not (Di.Td = Dtipus and then Di.Dt.Tt <= Tsent) then Error(Tipusidxerroniarray, A.Fd1.L1, A.Fd1.C1, Cons_Nom(Tn, Idrang)); Esem := True; Ncomponents := 0; else Posa_Idx(Ts, Idarray, Idrang, E); if E then Put_Line("ERROR CT-pdimcoleccio (DEBUG): "& "error al posa_idx, error "& "del compilador, array no creat,"& " idarr: "&Idarray'Img); Esem := True; end if; Ncomponents := Despl(Di.Dt.Lsup - Di.Dt.Linf + 1); end if; end if; end Ct_Pcoleccio; procedure Ct_Decregistre (A : in Pnode; Idrecord : out Id_Nom; Ocup: in out despl) is Drecord : Descrip; Dtrecord : Descriptipus; E : Boolean; begin if (A.Tipus = Dregistre) then Dtrecord := (Tsrec, 0); Drecord := (Dtipus, Dtrecord); Posa(Ts, A.Fe2.Id12, Drecord, E); Idrecord := A.Fe2.Id12; if E then Error(Id_Existent, A.Fe2.L1, A.Fe2.C1, Cons_Nom(Tn, Idrecord)); Esem := True; end if; Ct_Dregistre_Camp(A.Fe2.Id12, A.Fc2, A.Fd2, Ocup); elsif (A.Tipus = Dencapregistre) then Ct_Decregistre(A.Fe2, Idrecord, Ocup); Ct_Dregistre_Camp(Idrecord, A.Fc2, A.Fd2, Ocup); elsif (A.Tipus = Firecord) then Ct_Decregistre(A.F6, Idrecord, Ocup); Drecord := Cons(Ts, Idrecord); Drecord.Dt.Ocup := Ocup; Actualitza(Ts, Idrecord, Drecord); end if; end Ct_Decregistre; procedure Ct_Dregistre_Camp (Idrecord : in Id_Nom; Camp : in Pnode; Tcamp : in Pnode; Ocup: in out Despl) is Idtcamp : Id_Nom renames Tcamp.Id12; Dtcamp : Descrip; Idcamp : Id_Nom renames Camp.Id12; Desc_Camp : Descrip; E : Boolean; begin Dtcamp := Cons(Ts, Idtcamp); if (Dtcamp.Td /= Dtipus) then Error(Tipusinexistent, Camp.L1, Camp.C1, Cons_Nom(Tn, Idtcamp)); Esem := True; else Desc_Camp := (Dcamp, Idtcamp, Ocup); Posacamp(Ts, Idrecord, Idcamp, Desc_Camp, E); Ocup := Ocup + Dtcamp.Dt.Ocup; if E then Error(IdCampRecordExistent, Camp.L1, Camp.C1, Cons_Nom(Tn, Idcamp)); Esem := True; end if; end if; end Ct_Dregistre_Camp; procedure Ct_Decsubrang (A : in Pnode) is Idsubrang : Id_Nom renames A.Fe5.Id12; Idtsubrang : Id_Nom renames A.Fc5.Id12; Rang_Esq : Pnode renames A.Fd5; Rang_Dret : Pnode renames A.Fid5; Tsub : Tipussubjacent; Tsesq : Tipussubjacent; Tsdret : Tipussubjacent; Idesq : Id_Nom; Iddret : Id_Nom; Valesq : Valor; Valdret : Valor; Tdecl : Descrip; Tdescrip_decl : Descrip; Tdescript_decl : Descriptipus; L, C : Natural := 0; E : Boolean; begin Tdecl := Cons(Ts, Idtsubrang); if(Tdecl.Td /= Dtipus) then Error(TipusInexistent, A.Fc5.L1, A.Fc5.C1, Cons_Nom(Tn, Idtsubrang)); Esem := True; else --Miram el fill esquerra Ct_Constant(Rang_Esq, Tsesq, Idesq, L, C); Valesq := Rang_Esq.Val; --Miram el fill dret Ct_Constant(Rang_Dret, Tsdret, Iddret, L, C); Valdret := Rang_Dret.Val; -- Comparam els tipus if (Tsesq /= Tsdret) then Error(Tipussubdiferents, A.Fc5.L1, A.Fc5.C1, ""&Tsesq'Img&"/"&Tsdret'Img); Esem := True; end if; Tsub := Tsesq; if (Tsub /= Tdecl.Dt.Tt) then Error(Tipussubdiferents, A.Fc5.L1, A.Fc5.C1, ""&Tsub'Img&"/"&Tdecl.Dt.Tt'Img); Esem := True; end if; if (Valesq > Valdret) then Error(ValEsqMajorDret, A.Fc5.L1, A.Fc5.C1, ""&Valesq'Img&" >"&Valdret'Img); Esem := True; end if; if (Valesq < Tdecl.Dt.Linf) then Error(ValEsqMenor, A.Fc5.L1, A.Fc5.C1, Cons_Nom(Tn, Idtsubrang)); Esem := True; end if; if (Valdret > Tdecl.Dt.Lsup) then Error(ValDretMajor, A.Fc5.L1, A.Fc5.C1, Cons_Nom(Tn, Idtsubrang)); Esem := True; end if; case Tsub is when Tsent => Tdescript_Decl := (Tsent, 4, Valesq, Valdret); when Tscar => Tdescript_Decl := (Tscar, 4, Valesq, Valdret); when others => Put_Line("ERROR Ct_subrang: (Sub)Tipus no "& "valid per a un subrang"); Esem := True; end case; Tdescrip_Decl := (Dtipus, Tdescript_Decl); Posa(Ts, Idsubrang, Tdescrip_Decl, E); if E then Error(Id_Existent, A.Fe5.L1, A.Fe5.C1, Cons_Nom(Tn, Idsubrang)); Esem := True; end if; end if; end Ct_Decsubrang; procedure Ct_Expressio (A : in Pnode; T : out Tipussubjacent; Idtipus : out Id_Nom; L, C : in out Natural) is Tipus : Tipusnode renames A.Tipus; Tps : Tipussubjacent; Id : Id_Nom; begin case Tipus is when Expressio => Ct_Expressioc(A, Tps, Id, L, C); when ExpressioUnaria => Ct_Expressiou(A, Tps, Id, L, C); when Identificador => Ct_Identificador(A, Tps, Id, L, C); when Const => Ct_Constant(A, Tps, Id, L, C); when Fireferencia | Referencia => Ct_Referencia_Var(A, Tps, Id); when others => Put_Line("ERROR CT-exp: tipus expressio no "& "trobat :S "&Tipus'Img); Esem := True; end case; T := Tps; Idtipus := Id; end Ct_Expressio; procedure Ct_Operand_Exp (A : in Pnode; T : out Tipussubjacent; Idtipus : out Id_Nom; L, C : in out Natural) is Tipus : Tipusnode renames A.Tipus; begin case Tipus is when Expressio => Ct_Expressioc(A, T, Idtipus, L, C); when ExpressioUnaria => Ct_Expressiou(A, T, Idtipus, L, C); when Referencia | Fireferencia=> Ct_Referencia_var(A, T, IdTipus); when Const => Ct_Constant(A, T, Idtipus, L, C); when Identificador => Ct_Identificador(A, T, Idtipus, L, C); when others => Esem := True; null; end case; end Ct_Operand_Exp; procedure Ct_Expressioc (A : in Pnode; T : out Tipussubjacent; Idtipus : out Id_Nom; L, C : in out Natural) is Fesq : Pnode renames A.Fe3; Fdret : Pnode renames A.Fd3; Op : Operacio renames A.Op3; Tesq : Tipussubjacent; Idesq : Id_Nom; Tdret : Tipussubjacent; Iddret : Id_Nom; begin --Analitzam l'operand esquerra Ct_Operand_Exp(Fesq, Tesq, Idesq, L, C); --Analitzam l'operand dret Ct_Operand_Exp(Fdret, Tdret, Iddret, L, C); -- Comparam els tipus case Op is when Unio | Interseccio => Ct_Exp_Logica(Tesq, Tdret, Idesq, Iddret, T, Idtipus, L, C); when Menor | Menorig | Major | Majorig | Igual | Distint => Ct_Exp_Relacional(Tesq, Tdret, Idesq, Iddret, T, Idtipus, L, C); when Suma | Resta | Mult | Div | Modul => Ct_Exp_Aritmetica(Tesq, Tdret, Idesq, Iddret, T, Idtipus, L, C); when others => Esem := True; null; end case; end Ct_Expressioc; procedure Ct_Exp_Logica (Tesq, Tdret : in Tipussubjacent; Idesq, Iddret : in Id_Nom; T : out Tipussubjacent; Idtipus : out Id_Nom; L, C : in out Natural) is begin if Tesq /= Tsbool then Error(Tsub_No_Bool, L, C, "esquerra"); Esem := True; end if; if Tdret /= Tsbool then Error(Tsub_No_Bool, L, C, "dret"); Esem := True; end if; if Idesq /= Id_Nul and Iddret /= Id_Nul then if Idesq /= Iddret then Error(Tops_Diferents, L, C, ""); Esem := True; end if; end if; if Idesq = Id_Nul then Idtipus := Iddret; else Idtipus := Idesq; end if; T := Tsbool; end Ct_Exp_Logica; procedure Ct_Exp_Relacional (Tesq, Tdret : in Tipussubjacent; Idesq, Iddret : in Id_Nom; T : out Tipussubjacent; Idtipus : out Id_Nom; L, C : in out Natural) is begin if Tesq /= Tdret then Error(Tsubs_Diferents, L, C, ""); Esem := True; end if; if Tesq > Tsent then Error(Tsub_No_Escalar, L, C, "esquerra"); Esem := True; end if; if Tdret > Tsent then Error(Tsub_No_Escalar, L, C, "dret"); Esem := True; end if; if Idesq /= Id_Nul and Iddret /= Id_Nul then if Idesq /= Iddret then Error(Tops_Diferents, L, C, ""); Esem := True; end if; end if; T := Tsbool; Idtipus := Id_Nul; end Ct_Exp_Relacional; procedure Ct_Exp_Aritmetica (Tesq, Tdret : in Tipussubjacent; Idesq, Iddret : in Id_Nom; T : out Tipussubjacent; Idtipus : out Id_Nom; L, C : in out Natural) is begin if Tesq /= Tsent then Error(Tsub_No_Sencer, L, C, "esquerra"); Esem := True; end if; if Tdret /= Tsent then Error(Tsub_No_Sencer, L, C, "dret"); Esem := True; end if; if Idesq /= Id_Nul and Iddret /= Id_Nul then if Idesq /= Iddret then Error(Tops_Diferents, L, C, ""); Esem := True; end if; end if; T := Tsent; if Idesq = Id_Nul then Idtipus := Iddret; else Idtipus := Idesq; end if; end Ct_Exp_Aritmetica; procedure Ct_Expressiou (A : in Pnode; T : out Tipussubjacent; Idtipus : out Id_Nom; L, C : in out Natural) is Fdret : Pnode renames A.F4; Op : Operacio renames A.Op4; Tdret : Tipussubjacent; Iddret : Id_Nom; begin Ct_Operand_Exp(Fdret, Tdret, Iddret, L, C); case Op is when Resta => Ct_Exp_Negacio(Tdret, Iddret, T, Idtipus, L, C); when Negacio => Ct_Exp_Neglogica(Tdret, Iddret, T, Idtipus, L, C); when others => Esem := True; null; end case; end Ct_Expressiou; procedure Ct_Exp_Negacio (Ts : in Tipussubjacent; Id : in Id_Nom; T : out Tipussubjacent; Idtipus : out Id_Nom; L, C : in out Natural) is begin if Ts /= Tsent then Error(Tsub_No_Sencer, L, C, ""); Esem := True; end if; Idtipus := Id; T := Tsent; end Ct_Exp_Negacio; procedure Ct_Exp_Neglogica (Ts : in Tipussubjacent; Id : in Id_Nom; T : out Tipussubjacent; Idtipus : out Id_Nom; L, C: in out Natural) is begin if Ts /= Tsbool then Error(Tsub_No_Bool, L, C, ""); Esem := True; end if; Idtipus := Id; T := Tsbool; end Ct_Exp_Neglogica; procedure Ct_Constant (A : in Pnode; T : out Tipussubjacent; Idtipus : out Id_Nom; L, C : in out Natural) is Tatr : Tipus_Atribut renames A.Tconst; Lin : Natural renames A.L2; Col : Natural renames A.C2; D : Descrip; begin Idtipus := Id_Nul; case (Tatr) is when A_Lit_C => T := Tscar; when A_Lit_N => T := Tsent; when A_Lit_S => T := Tsstr; when others => Put_Line("ERROR CT-constant: tipus constant "& "erroni"); Esem := True; end case; L := Lin; C := Col; end Ct_Constant; procedure Ct_Identificador (A : in Pnode; T : out Tipussubjacent; Idtipus : out Id_Nom; L, C : in out Natural) is Id : Id_Nom renames A.Id12; D : Descrip; Desc : Tdescrip renames D.Td; Lin : Natural renames A.L1; Col : Natural renames A.C1; Carg : Cursor_Arg; begin D := Cons(Ts, Id); case Desc is when Dvar => Idtipus := D.Tr; D := Cons(Ts, Idtipus); if (D.Td = Dtipus) then T := D.Dt.Tt; else Error(Tipus_No_Desc, L, C, D.Td'Img); Esem := True; end if; when Dconst => Idtipus := D.Tc; D := Cons(Ts, Idtipus); if (D.Td = Dtipus) then T := D.Dt.Tt; else Error(Tipus_No_Desc, L, C, D.Td'Img); Esem := True; end if; when Dproc => Carg := Primer_Arg(Ts, Id); if Arg_Valid(Carg) then T := Tsarr; else T := Tsnul; end if; Idtipus := Id; when Dargc => Idtipus := D.Targ; D := Cons(Ts, Idtipus); if (D.Td = Dtipus) then T := D.Dt.Tt; else Error(Tipus_No_Desc, L, C, D.Td'Img); Esem := True; end if; when others => Error(Id_No_Reconegut, L, C, Desc'Img); Esem := True; Idtipus := Id; T := tsnul; end case; L := Lin; C := Col; end Ct_Identificador; procedure Ct_Bloc (A : in Pnode) is D : Descrip; T : Tipussubjacent; Idbase : Id_Nom; Idtipus : Id_Nom; Tsexp : Tipussubjacent; Idexp : Id_Nom; Tsvar : Tipussubjacent; Idvar : Id_Nom; L, C : Natural := 0; begin case (A.Tipus) is when Bloc => Ct_Bloc(A.Fe1); Ct_Bloc(A.Fd1); when Repeticio => Ct_Srep(A); when Identificador => Ct_Identificador(A, T, Idtipus, L, C); if T /= Tsnul then Error(Id_No_Cridaproc, L, C, Cons_Nom(Tn, A.Id12)); Esem := True; end if; when Fireferencia => Ct_Referencia_Proc(A, T, Idbase); when condicionalS => Ct_Sconds(A); when condicionalC => Ct_Scondc(A); when Assignacio => Ct_Referencia_Var(A.Fe1, Tsvar, Idvar); Ct_Expressio(A.Fd1, Tsexp, Idexp, L, C); if Tsvar /= Tsexp then Error(Assig_Tipus_Diferents, L, C, ""); Esem := True; end if; if Idexp /= Id_Nul and Idexp /= Idvar then Error(Assig_Tipus_Diferents, L, C, ""); Esem := True; end if; when others => Esem := True; end case; end Ct_Bloc; procedure Ct_Srep (A : in Pnode) is Tsexp : Tipussubjacent; Idtipus_exp : Id_Nom; Exp : Pnode renames A.Fe1; Bloc : Pnode renames A.fd1; L, C : Natural := 0; begin Ct_Expressio(Exp, Tsexp, Idtipus_Exp, L, C); if tsexp /= tsbool then Error(Exp_No_Bool, L, C, "bucle"); Esem := True; end if; Ct_Bloc(Bloc); end Ct_Srep; procedure Ct_Sconds (A : in Pnode) is Tsexp : Tipussubjacent; Idtipus_exp : Id_Nom; Cond : Pnode renames A.Fe1; Bloc : Pnode renames A.fd1; L, C : Natural := 0; begin Ct_Expressio(Cond, Tsexp, Idtipus_Exp, L, C); if tsexp /= tsbool then Error(Exp_No_Bool, L, C, "condicional"); Esem := True; end if; Ct_Bloc(Bloc); end Ct_Sconds; procedure Ct_Scondc (A : in Pnode) is Tsexp : Tipussubjacent; Idtipus_exp : Id_Nom; Cond : Pnode renames A.Fe2; Bloc : Pnode renames A.fc2; Blocelse : Pnode renames A.fd2; L, C : Natural := 0; begin Ct_Expressio(Cond, Tsexp, Idtipus_Exp, L, C); if tsexp /= tsbool then Error(Exp_No_Bool, L, C, "condicional compost"); Esem := True; end if; Ct_Bloc(Bloc); Ct_Bloc(Blocelse); end Ct_Scondc; procedure Ct_Referencia_Proc (A : in Pnode; T : out Tipussubjacent; Id : out Id_Nom) is Tipus : Tipusnode renames A.Tipus; It_Arg : Cursor_Arg; L, C : Natural := 0; begin case Tipus is when Identificador => Ct_Identificador(A, T, Id, L, C); when Referencia => Error(Rec_No_Cridaproc, L, C, ""); Esem := True; when Fireferencia => Ct_Ref_Pri(A.F6, T, It_Arg); if Arg_Valid(It_Arg) then Error(Falta_Param_Proc, L, C, ""); Esem := True; end if; when others => Put_Line("ERROR CT-referencia: node "& "no reconegut"); Esem := True; end case; end Ct_Referencia_Proc; procedure Ct_Referencia_Var (A : in Pnode; T : out Tipussubjacent; Id : out Id_Nom) is Tipus : Tipusnode renames A.Tipus; Idtipus : Id_Nom; It_Idx : Cursor_Idx; D : Descrip; L, C : Natural := 0; begin case Tipus is when Identificador => Ct_Identificador(A, T, Id, L, C); D := Cons(Ts, Id); if D.Td = Dproc then Error(Refvar_No_Proc, L, C, ""); Esem := True; end if; when Referencia => Ct_Ref_Rec(A, T, Id, Idtipus); when Fireferencia => Ct_Ref_Pri(A.F6, T, Id, It_Idx); if Idx_Valid(It_Idx) then Error(Falta_Param_Array, L, C, ""); Esem := True; end if; if T = Tsarr then D := Cons(Ts, Id); Id := D.Dt.Tcamp; D := Cons(Ts, Id); T := D.Dt.Tt; end if; when others => Esem := True; null; end case; end Ct_Referencia_Var; procedure Ct_Ref_Rec (A : in Pnode; T : out Tipussubjacent; Idtipus : out Id_Nom; Idbase : out Id_Nom) is Fesq : Pnode renames A.Fe1; Tesq : Tipussubjacent; Idbase_Esq : Id_Nom; Dcamp : Descrip; Dtcamp : Descrip; Idcamp : Id_Nom renames A.Fd1.Id12; L, C : Natural := 0; begin Ct_Referencia_Var(Fesq, Tesq, Idbase_Esq); if Tesq /= Tsrec then Error(Reccamp_No_Valid, L, C, ""); Esem := True; end if; Dcamp := Conscamp(Ts, Idbase_Esq, Idcamp); if Dcamp.Td = Dnula then Error(Idrec_No_Valid, L, C, Cons_Nom(Tn, Idcamp)); Esem := True; end if; Idtipus := Dcamp.Tcamp; Dtcamp := Cons(Ts, Dcamp.Tcamp); T := Dtcamp.Dt.Tt; Idbase := Idbase_Esq; end Ct_Ref_Rec; procedure Ct_Ref_Pri (A : in Pnode; T : out Tipussubjacent; Id : out Id_Nom; It_Idx : out Cursor_Idx) is Tipus : Tipusnode renames A.Tipus; Fesq : Pnode renames A.Fe1; Fdret : Pnode renames A.Fd1; Tsub : Tipussubjacent; Idvar : Id_Nom; Tsref : Tipussubjacent; Idref : Id_Nom; Id_Cursor : Id_Nom; Dtipoarg : Descrip; Dbase : Descrip; L, C : Natural := 0; begin case Tipus is when Pri => Ct_Ref_Pri(Fesq, T, Id, It_Idx); Ct_Expressio(Fdret, Tsref, Idref, L, C); if not Idx_Valid(It_Idx) then Error(Sobren_Parametres, L, C, ""); Esem := True; else Id_Cursor := Cons_Idx(Ts, It_Idx); Dtipoarg := Cons(Ts, Id_Cursor); if Idref = Id_Nul then if Dtipoarg.Dt.Tt /= Tsref then Error(Tparam_No_Coincident, L, C, ""); Esem := True; end if; elsif Idref /= Id_cursor then Error(Tparam_No_Coincident, L, C, Cons_Nom(Tn, Idref)&"/"& Cons_Nom(Tn, Id_Cursor)); Esem := True; end if; It_Idx := Succ_Idx(Ts, It_Idx); end if; when Encappri => Ct_Referencia_Var(Fesq, Tsub, Idvar); Ct_Expressio(Fdret, Tsref, Idref, L, C); Dbase := Cons (Ts, Idvar); if Tsub = Tsarr then It_Idx := Primer_Idx(Ts, Idvar); if Idx_Valid(It_Idx) then Id_Cursor := Cons_Idx(Ts, It_Idx); Dtipoarg := Cons(Ts, Id_Cursor); if Idref = Id_Nul then if Dtipoarg.Dt.Tt /= Tsref then Error(Tparam_No_Coincident, L, C, ""); Esem := True; end if; elsif Idref /= Id_Cursor then Error(Tparam_No_Coincident, L, C, Cons_Nom(Tn, Idref)&"/"& Cons_Nom(Tn, Id_Cursor)); Esem := True; end if; end if; else Error(Tipus_No_Array, L, C, Tsub'Img); Esem := True; end if; It_Idx := Succ_Idx(Ts, It_Idx); T := Tsub; Id := Idvar; when others => Esem := True; null; end case; end Ct_Ref_Pri; procedure Ct_Ref_Pri (A : in Pnode; T : out Tipussubjacent; It_Arg : out Cursor_Arg) is Tipus : Tipusnode renames A.Tipus; Fesq : Pnode renames A.Fe1; Fdret : Pnode renames A.Fd1; Tsub : Tipussubjacent; Id : Id_Nom; Tsref : Tipussubjacent; Idref : Id_Nom; Id_Cursor : Id_Nom; Dparam : Descrip; Dtipoarg : Descrip; Dbase : Descrip; L, C : Natural := 0; begin case Tipus is when Pri => -- pri , E Ct_Ref_Pri(Fesq, T, It_Arg); Ct_Expressio(Fdret, Tsref, Idref, L, C); if not Arg_Valid(It_Arg) then Error(Sobren_Parametres, L, C, ""); Esem := True; else Cons_Arg(Ts, It_Arg, Id_Cursor, Dparam); if Idref = Id_Nul then Dtipoarg := Cons(ts, Dparam.targ); if Dtipoarg.Dt.Tt /= Tsref then Error(Tparam_No_Coincident, L, C, Dtipoarg.Dt.Tt'Img); Esem := True; end if; elsif Dparam.td = Dargc then if Idref /= Dparam.targ then Error(Tparam_No_Coincident, L, C, Cons_Nom(Tn, Idref)&"/"& Cons_Nom(Tn, Id_Cursor)); Esem := True; end if; elsif Dparam.td = Dvar then if Idref /= Dparam.Tr then Error(Tparam_No_Coincident, L, C, Cons_Nom(Tn, Idref)&"/"& Cons_Nom(Tn, Id_Cursor)); Esem := True; end if; end if; It_Arg := Succ_Arg(Ts, It_Arg); end if; when Encappri => -- r(E Ct_Referencia_Proc(Fesq, Tsub, Id); Ct_Expressio(Fdret, Tsref, Idref, L, C); Dbase := Cons (Ts, Id); if Tsub = Tsarr and Dbase.td = Dproc then It_Arg := Primer_Arg(Ts, Id); if Arg_Valid(It_Arg) then Cons_Arg(Ts, It_Arg, Id_Cursor, Dparam); if Idref = Id_Nul then if(Dtipoarg.Td /= Dnula) then Dtipoarg := Cons(Ts, Dparam.Targ); if Dtipoarg.Dt.Tt /= Tsref then Error(Tparam_No_Coincident, L, C, ""); Esem := True; end if; end if; elsif Dparam.Td = Dargc then if Idref /= Dparam.Targ then Error(Tparam_No_Coincident, L, C, Cons_Nom(Tn, Idref)&"/"& Cons_Nom(Tn, Id_Cursor)); Esem := True; end if; elsif Dparam.Td = Dvar then if Idref /= Dparam.Tr then Error(Tparam_No_Coincident, L, C, Cons_Nom(Tn, Idref)&"/"& Cons_Nom(Tn, Id_Cursor)); Esem := True; end if; end if; end if; It_Arg := Succ_Arg(Ts, It_Arg); else Error(Tproc_No_Param, L, C, Tsub'Img); Esem := True; end if; T := Tsub; when others => Esem := True; end case; end Ct_Ref_Pri; end Semantica.Ctipus;
-- part of OpenGLAda, (c) 2017 Felix Krause -- released under the terms of the MIT license, see the file "COPYING" with Interfaces.C.Pointers; package GL.Types.Colors is pragma Preelaborate; type Color_Index is (R, G, B, A); subtype Basic_Color_Index is Color_Index range R .. B; subtype Component is Single range 0.0 .. 1.0; type Color is array (Color_Index) of aliased Component; type Basic_Color is array (Basic_Color_Index) of Component; pragma Convention (C, Color); pragma Convention (C, Basic_Color); type Color_Array is array (Size range <>) of aliased Color; type Basic_Color_Array is array (Size range <>) of aliased Basic_Color; package Color_Pointers is new Interfaces.C.Pointers (Size, Color, Color_Array, Color'(others => 0.0)); package Basic_Color_Pointers is new Interfaces.C.Pointers (Size, Basic_Color, Basic_Color_Array, Basic_Color'(others => 0.0)); end GL.Types.Colors;
pragma Profile(Restricted); pragma Restrictions (No_Abort_Statements); pragma Restrictions (Max_Asynchronous_Select_Nesting => 0); pragma Restrictions (No_Exceptions); pragma Restrictions (No_Direct_Boolean_Operators); with Ada.Text_IO; use Ada.Text_IO; with Ada.Characters.Latin_1; use Ada.Characters.Latin_1; with Ada.Real_Time; use Ada.Real_Time; with Interfaces; use Interfaces; with System.Storage_Elements; use System.Storage_Elements; with System.Address_To_Access_Conversions; procedure Go is generic type Element_Type is private; procedure Swap(Left, Right : in out Element_Type) with Inline; procedure Swap(Left, Right : in out Element_Type) is Temporary : constant Element_Type := Left; begin Left := Right; Right := Temporary; end Swap; generic type Element_Type is private; with function "+" (Left, Right : Element_Type) return Element_Type is <>; procedure Generic_Add(X : in out Element_Type; Y : in Element_Type) with Inline; procedure Generic_Add(X : in out Element_Type; Y : in Element_Type) is begin X := X + Y; end Generic_Add; procedure Add is new Generic_Add(Element_Type => Integer); package Int_IO is new Integer_IO(Integer); -------------------------------------------------------------------------- -- Random Signature Package generic type Random_Type; with function Next( Random : in out Random_Type; Size : in Unsigned_32 ) return Unsigned_32 is <>; package Signature_Random is end; -------------------------------------------------------------------------- -- XorShiftPlus Packages implementing Random Signature package XorShiftPlus is type Random_Type is limited private; function Init(X, Y : in Unsigned_64) return Random_Type with Inline; function Next( Random : in out Random_Type; Size : in Unsigned_32 ) return Unsigned_32 with Inline; package Signature is new Signature_Random( Random_Type => Random_Type ); private type Random_Type is limited record S0 : Unsigned_64 := 123456789362436069; S1 : Unsigned_64 := 52128862988675123; end record; end XorShiftPlus; package body XorShiftPlus is function Init(X, Y : in Unsigned_64) return Random_Type is begin return (S0 => X, S1 => Y); end Init; function Next( Random : in out Random_Type; Size : in Unsigned_32 ) return Unsigned_32 is S1 : Unsigned_64 := Random.S0; S0 : constant Unsigned_64 := Random.S1; begin S1 := S1 xor (Shift_Left(S1, 23)); Random.S0 := S0; S1 := S1 xor S0 xor Shift_Right(S1, 17) xor Shift_Right(S0, 26); Random.S1 := S1; return Unsigned_32(Shift_Right((((S1 + S0) and 16#ffffffff#) * Unsigned_64(Size)), 32)); end Next; end XorShiftPlus; -------------------------------------------------------------------------- -- Disjointset Signature Package generic type Element_Type; type Index; type Set_Type; type Cursor; with function None return Cursor is <>; with function Find(Node : in Cursor) return Cursor is <>; with procedure Makeset(Node : in Cursor) is <>; with function Link(C1, C2 : in Cursor) return Cursor is <>; with procedure Link_Circular(Left, Right : in Cursor) is <>; with function Succ(Node : in Cursor) return Cursor is <>; with procedure Set_Succ(Node, Succ : in Cursor) is <>; with function First(Set : access Set_Type) return Cursor is <>; with function Element(Node : in Cursor) return access Element_Type is <>; with function Index_Of(Set : access Set_Type; Node : in Cursor) return Index is <>; with procedure Next(Node : in out Cursor) is <>; with function Step return Integer is <>; with function "+" (Left : in Cursor; Right : in Integer) return Cursor is <>; with function "-" (Left : in Cursor; Right : in Integer) return Cursor is <>; package Signature_Disjointsets is end; -------------------------------------------------------------------------- -- Disjoint_Eager Packages implementing Disjointset Signature generic type Element_Type is limited private; type Index is range <>; package Eager_Disjointsets is type Set_Type is limited private; type Node_Type is limited private; type Cursor is access all Node_Type; function None return Cursor with Inline; function Find(Node : in Cursor) return Cursor with Inline; procedure Makeset(Node : in Cursor) with Inline; function Link(C1, C2 : in Cursor) return Cursor with Inline; procedure Link_Circular(Left, Right : in Cursor) with Inline; function Succ(Node : in Cursor) return Cursor with Inline; procedure Set_Succ(Node, Succ : in Cursor) with Inline; function First(Set : access Set_Type) return Cursor with Inline; function Element(Node : in Cursor) return access Element_Type with Inline; function Index_Of(Set : access Set_Type; Node : in Cursor) return Index with Inline; procedure Next(Node : in out Cursor) with Inline; function Step return Integer with Inline; function "+" (Left : in Cursor; Right : in Integer) return Cursor with Inline; function "-" (Left : in Cursor; Right : in Integer) return Cursor with Inline; package Signature is new Signature_Disjointsets( Element_Type => Element_Type, Set_Type => Set_Type, Index => Index, Cursor => Cursor ); private type Node_Type is limited record Canonical : Cursor; Successor : Cursor; Size : Unsigned_32; Value : aliased Element_Type; end record; type Set_Type is array (Index) of aliased Node_Type; package Node_Address is new System.Address_To_Access_Conversions(Node_Type); Node_Size : constant Storage_Offset := Node_Type'Object_Size / System.Storage_Elements.Storage_Element'Size; end Eager_Disjointsets; package body Eager_Disjointsets is function To_Access(A : System.Address) return access Node_Type with Inline is begin return Node_Address.To_Pointer(A); end To_Access; function To_Address(C : access Node_Type) return System.Address with Inline is begin return Node_Address.To_Address(Node_Address.Object_Pointer(C)); end To_Address; function None return Cursor is begin return null; end None; procedure Makeset( Node : in Cursor ) is begin Node.Canonical := Node; Node.Size := 1; end Makeset; function Find( Node : in Cursor ) return Cursor is begin return Node.Canonical; end Find; procedure Swap_Cursors is new Swap(Cursor); procedure Link_Circular(Left, Right : Cursor) is begin Swap_Cursors(Left.Successor, Right.Successor); end Link_Circular; procedure Link_Head(Head, Tail : in Cursor) with Inline; procedure Link_Head(Head, Tail : in Cursor) is C : Cursor := Tail; begin Link_Loop : loop C.Canonical := Head; C := C.Successor; exit Link_Loop when C = Tail; end loop Link_Loop; Head.Size := Head.Size + Tail.Size; end Link_Head; function Link(C1, C2 : in Cursor) return Cursor is begin if C1.Size < C2.Size then Link_Head(C2, C1); return C2; else Link_Head(C1, C2); return C1; end if; end Link; function Succ( Node : in Cursor ) return Cursor is begin return Node.Successor; end Succ; procedure Set_Succ( Node, Succ : in Cursor ) is begin Node.Successor := Succ; end Set_Succ; function First( Set : access Set_Type ) return Cursor is begin return Set(Set_Type'First)'Access; end First; function Element( Node : in Cursor ) return access Element_Type is begin return Node.Value'Access; end Element; function Index_Of( Set : access Set_Type; Node : in Cursor ) return Index is begin return Index((To_Address(Node) - To_Address(First(Set))) / Node_Size); end Index_Of; procedure Next( Node : in out Cursor ) is begin Node := To_Access(To_Address(Node) + Node_Size); end Next; function Step return Integer is begin return Integer(Node_Size); end Step; function "+" (Left : in Cursor; Right : in Integer) return Cursor is begin return To_Access(To_Address(Left) + Storage_Offset(Right)); end "+"; function "-" (Left : in Cursor; Right : in Integer) return Cursor is begin return To_Access(To_Address(Left) - Storage_Offset(Right)); end "-"; begin Put_Line("region size:" & Storage_Offset'Image(Node_Size) & "B"); end Eager_Disjointsets; -------------------------------------------------------------------------- -- Sack Signaure Package generic type Sack; type Element; type Index; type Cursor; with function None return Cursor is <>; with function Has_Element(C : Cursor) return Boolean is <>; with function Size(S : access Sack) return Integer is <>; with function Get(S : access Sack; I : in Index) return Cursor is <>; with function Deref(C : in Cursor) return Element is <>; with function First(S : access Sack) return Cursor is <>; with function Last(S : access Sack) return Cursor is <>; with function Index_Of(S: access Sack; C : in Cursor) return Index is <>; with function Step return Integer is <>; with function "+" (C : in Cursor; I : in Integer) return Cursor is <>; with function "-" (C : in Cursor; I : in Integer) return Cursor is <>; with procedure Reset(S : access Sack) is <>; with procedure Add(S : access Sack; E : in Element) is <>; with procedure Remove(S : access Sack; C: in Cursor) is <>; with procedure Next(C : in out Cursor) is <>; package Signature_Sack is end; -------------------------------------------------------------------------- -- Array_Sacks Packages implementing Sack Signature generic type Element is private; type Index is range <>; package Array_Sacks is type Sack is limited private; type Cursor is access all Element; function None return Cursor with Inline; function Has_Element(A : Cursor) return Boolean with Inline; function Size(S: access Sack) return Integer with Inline; function Get(S : access Sack; I : in Index) return Cursor with Inline; function Deref(A : in Cursor) return Element with Inline; function First(S : access Sack) return Cursor with Inline; function Last(S : access Sack) return Cursor with Inline; function Index_Of(S : access Sack; A : in Cursor) return Index with Inline; function Step return Integer with Inline; function "+" (A : in Cursor; I : in Integer) return Cursor with Inline; function "-" (A : in Cursor; I : in Integer) return Cursor with Inline; procedure Reset(S : access Sack) with Inline; procedure Add(S : access Sack; E : in Element) with Inline; procedure Remove(S : access Sack; A : in Cursor) with Inline; procedure Next(A : in out Cursor) with Inline; package Signature is new Signature_Sack( Element => Element, Index => Index, Sack => Sack, Cursor => Cursor ); private type Element_Array is array (Index) of aliased Element; type Sack is limited record Used : Integer := Integer(Index'First); Elements : Element_Array; end record; end Array_Sacks; package body Array_Sacks is package Element_Address is new System.Address_To_Access_Conversions(Element); Element_Size : constant Storage_Offset := Element'Object_Size / System.Storage_Elements.Storage_Element'Size; function To_Cursor(A : System.Address) return Cursor with Inline is begin return Cursor(Element_Address.To_Pointer(A)); end To_Cursor; function To_Address(A : Cursor) return System.Address with Inline is begin return Element_Address.To_Address(Element_Address.Object_Pointer(A)); end To_Address; function None return Cursor is begin return null; end None; function Has_Element(A : in Cursor) return Boolean is begin return A = null; end Has_Element; function Size(S : access Sack) return Integer is begin return S.Used; end Size; function Deref(A : in Cursor) return Element is begin return A.all; end Deref; procedure Reset(S : access Sack) is begin S.Used := Integer(Index'First); end Reset; procedure Add(S : access Sack; E : in Element) is pragma Precondition(S.Used >= Integer(Index'First)); pragma Precondition(S.Used <= Integer(Index'Last)); begin S.Elements(Index(S.Used)) := E; S.Used := Integer(Index'Succ(Index(S.Used))); end Add; procedure Remove(S : access Sack; A : in Cursor) is begin S.Used := Integer(Index'Pred(Index(S.Used))); A.all := S.Elements(Index(S.Used)); end Remove; function Get(S : access Sack; I : in Index) return Cursor is begin return S.Elements(I)'Access; end Get; function First(S : access Sack) return Cursor is begin return S.Elements(Index'First)'Access; end First; function Last(S : access Sack) return Cursor is begin return S.Elements(Index(S.Used))'Access; end Last; procedure Next(A : in out Cursor) is begin A := To_Cursor(To_Address(A) + Element_Size); end Next; function Index_Of(S : access Sack; A : in Cursor) return Index is begin return Index((To_Address(A) - To_Address(First(S))) / Element_Size); end Index_Of; function Step return Integer is begin return Integer(Element_Size); end Step; function "+" (A : in Cursor; I : in Integer) return Cursor is begin return To_Cursor(To_Address(A) + Storage_Offset(I)); end "+"; function "-" (A : in Cursor; I : in Integer) return Cursor is begin return To_Cursor(To_Address(A) - Storage_Offset(I)); end "-"; end Array_Sacks; -------------------------------------------------------------------------- package Colours is type Colour_Type is (Black, White, Red, None); for Colour_Type use (Black => 0, White => 1, Red => 2, None => 3); function Opposite(Colour : Colour_Type) return Colour_Type with Inline; end Colours; package body Colours is function Opposite(Colour : Colour_Type) return Colour_Type is begin return Colour_Type'Val(1 - Colour_Type'Pos(Colour)); end Opposite; end Colours; -------------------------------------------------------------------------- package Nodes is use Colours; type Neighbour_Count is new Unsigned_8; type Neighbour_Count_Access is not null access all Neighbour_Count; type Neighbours_Array is array (Colour_Type) of aliased Neighbour_Count; type Neighbours_Access is not null access all Neighbours_Array; type Node_Type is limited record Pseudo_Liberties : Integer; Colour : Colour_Type; Neighbours : aliased Neighbours_Array; end record; type Node_Access is not null access all Node_Type; procedure Add is new Generic_Add(Element_Type => Neighbour_Count) with Inline; function Get( N : in Neighbours_Access; C : in Colour_Type ) return Neighbour_Count_Access with Inline; end Nodes; package body Nodes is function Get( N : in Neighbours_Access; C : in Colour_Type ) return Neighbour_Count_Access is begin return N(C)'Access; end Get; end Nodes; -------------------------------------------------------------------------- -- note: board rows and cols include borders. generic Width : Integer := 9; Height : Integer := 9; package Board_Config is Cols : constant Integer := Width + 2; Rows : constant Integer := Height + 2; Action_Area : constant Integer := Width * Height; Total_Area : constant Integer := Cols * Rows; Max_Moves : constant Integer := 3 * Action_Area; subtype Col is Integer range 1 .. Cols; subtype Row is Integer range 1 .. Rows; subtype Region_Index is Integer range 0 .. Total_Area - 1; subtype Moves_Index is Integer range 0 .. Action_Area - 1; end Board_Config; generic type Random_type is limited private; type Set_Type is limited private; type Set_Cursor is private; type Sack_Type is limited private; type Sack_Cursor is private; with package Config is new Board_Config(<>); with package Regions is new Signature_Disjointsets( Element_Type => Nodes.Node_Type, Index => Config.Region_Index, Set_Type => Set_Type, Cursor => Set_Cursor, others => <> ); with package Moves is new Signature_Sack( Element => Set_Cursor, Index => Config.Moves_Index, Sack => Sack_Type, Cursor => Sack_Cursor, others => <> ); with package Random is new Signature_Random( Random_Type => Random_Type, others => <> ); package Boards is type Board_Type is limited private; type Board_Access is not null access all Board_Type; procedure Reset( Board : in out Board_Type ); procedure Show( Board : in out Board_Type ); procedure Benchmark_Monte_Carlo( Board : in out Board_Type; Rand : in out Random_Type; Reps : in Integer ); procedure Show_Actions( Board : in out Board_Type ); private use Config; use Colours; use Regions; use Moves; use Nodes; type Point_Array is array (0 .. 1) of Integer; type Board_Type is limited record Regions : aliased Set_Type; Moves : aliased Sack_Type; Ko : Set_Cursor; Points : Point_Array; Passes : Integer; Plies : Integer; Player : Colour_Type; end record; Board_Size : constant Storage_Offset := Board_Type'Object_Size / System.Storage_Elements.Storage_Element'Size; Region_DX : constant Integer := Regions.Step; Region_DY : constant Integer := Region_DX * Config.Cols; end Boards; package body Boards is procedure Show_Action( Board : in out Board_Type; C : in Set_Cursor ) is subtype Heading_Index is Integer range Config.Col'First .. Integer'Last; H : constant array (Heading_Index range <>) of Character := "ABCDEFGHJKLMNOPQRSTUVWXYZ"; K : constant Config.Region_Index := Regions.Index_Of(Board.Regions'Access, C); X : constant Integer := K mod Config.Cols; Y : constant Integer := K / Config.Cols; begin Put("[" & H(X)); Int_IO.Put(Config.Cols - Y - 1, 0); Put("]"); end Show_Action; procedure Show_Actions(Board : in out Board_Type) is M : constant access Sack_Type := Board.Moves'Access; begin Int_IO.Put(Size(M), 0); Put(" : "); for J in Config.Moves_Index'First .. Size(M) - 1 loop Show_Action(Board, Deref(Moves.Get(M, J))); end loop; New_Line; end Show_Actions; procedure Reset( c : in Set_Cursor; Colour : in Colour_Type; Pseudo_Liberties : in Integer ) with Inline; procedure Reset( C : in Set_Cursor; Colour : in Colour_Type; Pseudo_Liberties : in Integer ) is Neighbours : constant Neighbour_Count := Neighbour_Count(4 - Pseudo_Liberties); begin Makeset(C); Set_Succ(C, C); declare N : constant Node_Access := Regions.Element(C); M : constant Neighbours_Access := N.Neighbours'Access; begin N.Pseudo_Liberties := Pseudo_Liberties; N.Colour := Colour; Get(M, Black).all := Neighbours; Get(M, White).all := Neighbours; Get(M, Red).all := Neighbours; end; end Reset; procedure Reset(Board : in out Board_Type) is M : constant access Sack_Type := Board.Moves'Access; C : Set_Cursor := First(Board.Regions'Access); begin Reset(M); Reset(C, Red, 0); Next(C); for X in 3 .. Config.Cols loop Reset(C, Red, 1); Next(C); end loop; Reset(C, Red, 0); Next(C); Reset(C, Red, 1); Next(C); Reset(C, None, 2); Add(M, C); Next(C); for X in 5 .. Config.Cols loop Reset(C, None, 3); Add(M, C); Next(C); end loop; Reset(C, None, 2); Add(M, C); Next(C); Reset(C, Red, 1); Next(C); for Y in 5 .. Config.Rows loop Reset(C, Red, 1); Next(C); Reset(C, None, 3); Add(M, C); Next(C); for X in 5 .. Config.Cols loop Reset(C, None, 4); Add(M, C); Next(C); end loop; Reset(C, None, 3); Add(M, C); Next(C); Reset(C, Red, 1); Next(C); end loop; Reset(C, Red, 1); Next(C); Reset(C, None, 2); Add(M, C); Next(C); for X in 5 .. Config.Cols loop Reset(C, None, 3); Add(M, C); Next(C); end loop; Reset(C, None, 2); Add(M, C); Next(C); Reset(C, Red, 1); Next(C); Reset(C, Red, 0); Next(C); for X in 3 .. Config.Cols loop Reset(C, Red, 1); Next(C); end loop; Reset(C, Red, 0); Board.Ko := None; Board.Points := (0, 0); Board.Passes := 0; Board.Plies := 0; Board.Player := Black; end Reset; procedure Show(Board : in out Board_Type) is Esc: Character renames Ada.Characters.Latin_1.ESC; subtype Heading_Index is Integer range Config.Col'First .. Integer'Last; H : constant array (Heading_Index range <>) of Character := "ABCDEFGHJKLMNOPQRSTUVWXYZ"; C : Set_Cursor := First(Board.Regions'Access); begin Put(" "); for X in Config.Col'First .. Config.Col'Last - 2 loop Put(" " & H(X)); end loop; New_Line; for Y in Row'First .. Row'Last loop if (Config.Row'Last > Y) and then (Y > 1) then Int_IO.Put(Integer(Config.Row'Last) - Integer(Y), 2); else Put(" "); end if; for X in Config.Col'First .. Config.Col'Last loop declare N : constant Node_Access := Regions.Element(Find(C)); begin case N.Colour is when Black => Put(Esc & "[7m"); when Red => Put(Esc & "[41;30;2m"); when None => Put(Esc & "[47;2m"); when White => null; end case; Int_IO.Put(N.Pseudo_Liberties, 2); Put(Esc & "[0m"); end; Next(C); end loop; New_Line; end loop; end Show; procedure Remove( C : in Set_Cursor; Colour : in Colour_Type ) with Inline is N : constant Neighbour_Count_Access := Get(Regions.Element(C).Neighbours'Access, Colour); P : constant Node_Access := Regions.Element(Find(C)); begin N.all := Neighbour_Count'Pred(N.all); P.Pseudo_Liberties := Integer'Succ(P.Pseudo_Liberties); end Remove; function Check_Suicide( Node : in Node_Access; Colour : in Colour_Type ) return Boolean with Inline is begin return (Node.Colour = Red) or else ((Node.Colour = Colour) = (Node.Pseudo_Liberties = 0)); end Check_Suicide; function Is_Ko( Board : in Board_Type; C : in Set_Cursor ) return Boolean with Inline is begin return C = Board.Ko; end Is_Ko; function Is_Suicide( Board : in Board_Type; C : in Set_Cursor ) return Boolean with Inline is begin if Regions.Element(C).Pseudo_Liberties /= 0 then return false; end if; declare NA : constant Node_Access := Regions.Element(Find(C - Region_DY)); WA : constant Node_Access := Regions.Element(Find(C - Region_DX)); EA : constant Node_Access := Regions.Element(Find(C + Region_DX)); SA : constant Node_Access := Regions.Element(Find(C + Region_DY)); NP : constant Integer := NA.Pseudo_Liberties; WP : constant Integer := WA.Pseudo_Liberties; EP : constant Integer := EA.Pseudo_Liberties; SP : constant Integer := SA.Pseudo_Liberties; begin NA.Pseudo_Liberties := Integer'Pred(NA.Pseudo_Liberties); WA.Pseudo_Liberties := Integer'Pred(WA.Pseudo_Liberties); EA.Pseudo_Liberties := Integer'Pred(EA.Pseudo_Liberties); SA.Pseudo_Liberties := Integer'Pred(SA.Pseudo_Liberties); declare Suicide : constant Boolean := Check_Suicide(NA, Board.Player) and then Check_Suicide(WA, Board.Player) and then Check_Suicide(EA, Board.Player) and then Check_Suicide(SA, Board.Player); begin NA.Pseudo_Liberties := NP; WA.Pseudo_Liberties := WP; EA.Pseudo_Liberties := EP; SA.Pseudo_Liberties := SP; return Suicide; end; end; end Is_Suicide; function Is_Eyelike( Board : in Board_Type; C : in Set_Cursor ) return boolean is N : constant Node_Access := Regions.Element(C); M : constant Neighbours_Access := N.Neighbours'Access; begin if (N.Pseudo_Liberties /= 0) or else (Get(M, Board.Player).all /= 4) then return false; end if; declare Op_Colour : constant Colour_Type := Opposite(Board.Player); NWSE : constant Integer := Region_DY + Region_DX; NESW : constant Integer := Region_DY - Region_DX; begin return Boolean'Pos(Regions.Element(C - NWSE).Colour = Op_Colour) + Boolean'Pos(Regions.Element(C - NESW).Colour = Op_Colour) + Boolean'Pos(Regions.Element(C + NESW).Colour = Op_Colour) + Boolean'Pos(Regions.Element(C + NWSE).Colour = Op_Colour) < 1 + Boolean'Pos(Get(M, Red).all < 1); end; end Is_Eyelike; pragma Inline(Is_Eyelike); procedure Capture( Board : in out Board_Type; C : in Set_Cursor; Colour : in Colour_Type ) is M : constant access Sack_Type := Board.Moves'Access; D : Set_Cursor := C; N : Node_Access := Regions.Element(C); begin pragma Debug(Put("Capture: ")); pragma Debug(Show_Action(Board, C)); pragma Debug(Ada.Text_IO.New_Line); Pass1 : loop N.Colour := None; N.Pseudo_Liberties := 0; Makeset(D); Add(M, D); Add(Board.Points(Colour_Type'Pos(Colour)), -1); D := Succ(D); N := Regions.Element(D); exit Pass1 when D = C; end loop Pass1; Pass2 : loop Remove(D - Region_DY, Colour); Remove(D - Region_DX, Colour); Remove(D + Region_DX, Colour); Remove(D + Region_DY, Colour); declare E : constant Set_Cursor := Succ(D); begin Set_Succ(D, D); D := E; end; exit Pass2 when D = C; end loop Pass2; end Capture; pragma Inline(Capture); procedure Update_Neighbour_Ko( Board : in out Board_Type; D : in Set_Cursor; My_Colour : in Colour_Type; Ko : in out Set_Cursor ) is E : constant Set_Cursor := Find(D); Root : constant Node_Access := Regions.Element(E); begin Add(Get(Regions.Element(D).Neighbours'Access, My_Colour).all, 1); Add(Root.Pseudo_Liberties, -1); if (Root.Colour /= Red) and then (Root.Pseudo_Liberties = 0) then Capture(Board, E, Root.Colour); Ko := E; end if; end Update_Neighbour_Ko; pragma Inline(Update_Neighbour_Ko); procedure Update_Neighbour_Hd( Board : in out Board_Type; D : in Set_Cursor; My_Colour : in Colour_Type; Op_Colour : in Colour_Type; Hd : in out Set_Cursor ) is E : constant Set_Cursor := Find(D); Root : constant Node_Access := Regions.Element(E); begin Add(Get(Regions.Element(D).Neighbours'Access, My_Colour).all, 1); Add(Root.Pseudo_Liberties, -1); if Root.Colour = My_Colour then if E /= Hd then declare New_Hd : constant Set_Cursor := Link(E, Hd); begin Link_Circular(Hd, E); Regions.Element(New_Hd).Pseudo_Liberties := Regions.Element(Hd).Pseudo_Liberties + Root.Pseudo_Liberties; Hd := New_Hd; end; end if; elsif (Root.Colour = Op_Colour) and then (Root.Pseudo_Liberties = 0) then Capture(Board, E, Root.Colour); end if; end Update_Neighbour_Hd; pragma Inline(Update_Neighbour_Hd); procedure Result( Board : in out Board_Type; Action : in Sack_Cursor ) is begin if Has_Element(Action) then Board.Player := Opposite(Board.Player); Add(Board.Passes, 1); Add(Board.Plies, 1); return; end if; declare M : constant access Sack_Type := Board.Moves'Access; C : constant Set_Cursor := Deref(Action); Node : constant Node_Access := Regions.Element(C); My_Colour : constant Colour_Type := Board.Player; Op_Colour : constant Colour_Type := Opposite(My_Colour); N : constant Set_Cursor := C - Region_DY; W : constant Set_Cursor := C - Region_DX; E : constant Set_Cursor := C + Region_DX; S : constant Set_Cursor := C + Region_DY; begin Remove(M, Action); Node.Colour := My_Colour; Add(Board.Points(Colour_Type'Pos(My_Colour)), 1); if Get(Node.Neighbours'Access, Op_Colour).all = 4 then declare Single_Capture : constant Integer := Size(M) + 1; Ko : Set_Cursor := None; begin Update_Neighbour_Ko(Board, N, My_Colour, Ko); Update_Neighbour_Ko(Board, W, My_Colour, Ko); Update_Neighbour_Ko(Board, E, My_Colour, Ko); Update_Neighbour_Ko(Board, S, My_Colour, Ko); if Single_Capture = Size(M) then Board.Ko := Ko; else Board.Ko := None; end if; end; else declare Hd : Set_Cursor := C; begin Update_Neighbour_Hd(Board, N, My_Colour, Op_Colour, Hd); Update_Neighbour_Hd(Board, W, My_Colour, Op_Colour, Hd); Update_Neighbour_Hd(Board, E, My_Colour, Op_Colour, Hd); Update_Neighbour_Hd(Board, S, My_Colour, Op_Colour, Hd); Board.Ko := None; end; end if; Board.Player := Op_Colour; Board.Passes := 0; Add(Board.Plies, 1); end; end Result; pragma Inline(Result); function Not_Terminal( Board : in out Board_Type ) return Boolean is begin return Board.Passes < 2 and then Board.Plies < Config.Max_Moves; end Not_Terminal; pragma Inline(Not_Terminal); function Utility( Board : in out Board_Type; My_Colour : in Colour_Type ) return Integer is M : constant access Sack_Type := Board.Moves'Access; Op_Colour : constant Colour_Type := Opposite(My_Colour); S : Integer := Board.Points(Colour_Type'Pos(My_Colour)) - Board.Points(Colour_Type'Pos(Op_Colour)); begin for J in Config.Moves_Index'First .. Size(M) - 1 loop declare N : constant Neighbours_Access := Regions.Element(Deref(Get(M, J))).Neighbours'Access; begin if Get(N, My_Colour).all = 4 then S := S + 1; elsif Get(N, Op_Colour).all = 4 then S := S - 1; end if; end; end loop; return S; end Utility; function Is_Illegal( Board : in Board_Type; C : in Set_Cursor ) return Boolean is begin return Is_Eyelike(Board, C) or else Is_Suicide(Board, C) or else Is_Ko(Board, C); end Is_Illegal; pragma Inline(Is_Illegal); function Genmove( Board : in out Board_Type; Rand : in out Random_Type ) return Sack_Cursor is M : constant access Sack_Type := Board.Moves'Access; -- C : Sack_Cursor := Get(M, Config.Moves_Index(Random.Next(Rand, -- Unsigned_32(Size(M)) - Unsigned_32(Config.Moves_Index'First) -- ) + Unsigned_32(Config.Moves_Index'First) -- )); C : Sack_Cursor := Get(M, Config.Moves_Index( Random.Next(Rand, Unsigned_32(Size(M))) )); D : constant Sack_Cursor := C; E : constant Sack_Cursor := Last(M); begin pragma Debug(Put("->")); while Is_Illegal(Board, Deref(C)) loop pragma Debug(Show_Action(Board, Deref(C))); Next(C); if C = E then pragma Debug(Put("/")); C := Moves.First(M); end if; if C = D then pragma Debug(Put("[]")); return Moves.None; end if; end loop; pragma Debug(Show_Action(Board, Deref(C))); pragma Debug(Ada.Text_IO.New_Line); return C; --pragma Debug(Put("->")); --while C /= E loop -- pragma Debug(Show_Action(Board, Deref(C))); -- if not Is_Illegal(Board, Deref(C)) then -- pragma Debug(Ada.Text_IO.New_Line); -- return C; -- end if; -- Next(C); --end loop; --C := Moves.First(M); --pragma Debug(Put("/")); --while C /= D loop -- pragma Debug(Show_Action(Board, Deref(C))); -- if not Is_Illegal(Board, Deref(C)) then -- pragma Debug(Ada.Text_IO.New_Line); -- return C; -- end if; -- Next(C); --end loop; --pragma Debug(Put("[]")); --pragma Debug(Ada.Text_IO.New_Line); --return Moves.None; end Genmove; pragma Inline(Genmove); procedure Playout( Board : in out Board_Type; R : in out Random_Type ) is begin while Not_Terminal(Board) loop pragma Debug(Show(Board)); pragma Debug(Show_Actions(Board)); declare C : constant Sack_Cursor := Genmove(Board, R); begin Result(Board, C); end; end loop; end Playout; procedure Benchmark_Monte_Carlo( Board : in out Board_Type; Rand : in out Random_Type; Reps : in Integer ) is Plies : Integer := 0; Games : Integer := 0; Black_Wins : Integer := 0; White_Wins : Integer := 0; T1, T2 : Time; begin T1 := Clock; while Games < Reps loop Reset(Board); Playout(Board, Rand); if Board.Plies < Config.Max_Moves then Plies := Plies + Board.Plies; Games := Games + 1; declare type Score is delta 0.5 range -500.0 .. 500.0; --package Scr_IO is new Fixed_IO(Score); S : constant Score := Score(Utility(Board, Black)) - 6.5; begin -- Int_IO.Put(Integer(S), 0); -- Put(" "); if S > 0.0 then Black_Wins := Black_Wins + 1; elsif S < 0.0 then White_Wins := White_Wins + 1; end if; end; else Put_Line("MAX MOVES EXCEEDED"); end if; end loop; T2 := Clock; declare package Flt_IO is new Float_IO(Long_Float); DT : constant Long_Float := Long_Float(To_Duration(T2 - T1)); begin Int_IO.Put(Plies, 0); Put(" plies over "); Int_IO.Put(Games, 0); Put(" games in "); Flt_IO.Put(DT, 0, 3, 0); Put(" seconds."); New_Line; Flt_IO.Put(Long_Float(Plies) / Long_Float(Reps), 0, 3, 0); Put(" plies per game, "); Flt_IO.Put(Long_Float(Reps) / (1000.0 * DT), 0, 3, 0); Put("k games per second."); New_Line; Flt_IO.Put(100.0 * Long_Float(Black_Wins) / Long_Float(Reps), 0, 3, 0); Put("% black / "); Flt_IO.Put(100.0 * Long_Float(White_Wins) / Long_Float(Reps), 0, 3, 0); Put("% white wins."); New_Line; end; end Benchmark_Monte_Carlo; begin Put_Line("board size:" & Storage_Offset'Image(Board_Size) & "B"); end Boards; -------------------------------------------------------------------------- -- Configure Boards to use Eager_Disjointsets and Array_Sacks package Config is new Board_Config; package My_Eager_Disjointsets is new Eager_Disjointsets( Element_Type => Nodes.Node_Type, Index => Config.Region_Index ); package My_Array_Sacks is new Array_Sacks( Element => My_Eager_Disjointsets.Cursor, Index => Config.Moves_Index ); package Board is new Boards( Config => Config, Random => XorShiftPlus.Signature, Random_Type => XorShiftPlus.Random_Type, Regions => My_Eager_Disjointsets.Signature, Set_Type => My_Eager_Disjointsets.Set_Type, Set_Cursor => My_Eager_Disjointsets.Cursor, Moves => My_Array_Sacks.Signature, Sack_Type => My_Array_Sacks.Sack, Sack_Cursor => My_Array_Sacks.Cursor ); -------------------------------------------------------------------------- -- Benchmark Procedure using Random Signature generic type Random_Type is limited private; with package Random is new Signature_Random( Random_type => Random_Type, others => <>); procedure Benchmark_Random(R : in out Random_Type; Reps : in Long_Integer); procedure Benchmark_Random(R : in out Random_Type; Reps : in Long_Integer) is T1, T2 : Time; X : Unsigned_32 := 0; begin T1 := Clock; for I in 1 .. Reps loop X := X + Random.Next(R, 400); end loop; T2 := Clock; declare package U32_IO is new Modular_IO(Unsigned_32); package Flt_IO is new Float_IO(Long_Float); T : constant Long_Float := (Long_Float(Reps) / 1000000.0) / Long_Float(To_Duration(T2 - T1)); begin U32_IO.Put(X, 0); Put(" "); Flt_IO.Put(T, 0, 3, 0); Put("M pseudo-random numbers per second."); New_Line; end; end Benchmark_Random; -------------------------------------------------------------------------- -- Benchmark Monte-Carlo Engine -------------------------------------------------------------------------- -- Example use of Test with XorShift implementation of Random Signature procedure Benchmark_XorShift is new Benchmark_Random( Random_Type => XorShiftPlus.Random_Type, Random => XorShiftPlus.Signature ); --package My_Board is new My_Boards(Config => My_Config); --use My_Board; B : Board.Board_Type; X : XorShiftPlus.Random_Type; begin Board.Reset(B); --Board.Show(B'Access); --Board.Show_Actions(B'Access); --Benchmark_XorShift(X, 1000000000); Board.Benchmark_Monte_Carlo(B, X, 1000000); end Go;
with Ada.Streams; package ACO.Log is pragma Preelaborate; use Ada.Streams; type Log_Level is (Debug, Info, Warning, Error, Off); procedure Put (Level : in Log_Level; Message : in String); procedure Put_Line (Level : in Log_Level; Message : in String); procedure Set_Level (Level : in Log_Level); procedure Set_Stream (Stream : access Root_Stream_Type'Class); type Stream_Access is access all Root_Stream_Type'Class; function Get_Stream return Stream_Access; private Logger_Level : Log_Level := Debug; Logger_Stream : access Root_Stream_Type'Class := null; function Build_String (Level : Log_Level; Message : String) return String; end ACO.Log;
with Ada.Text_IO; procedure Hello is begin Ada.Text_IO.Put_Line("Hello, world!"); end Hello;
-------------------------------------------------------------------------------- -- * Body name vector.adb -- * Project name ctffttest -- * -- * Version 1.0 -- * Last update 11/5/08 -- * -- * Created by Adrian Hoe on 11/5/08. -- * Copyright (c) 2008 AdaStar Informatics http://adastarinformatics.com -- * All rights reserved. -- * -------------------------------------------------------------------------------- with Ada.Text_IO; use Ada.Text_IO; package body Vector is package Io_Double is new Float_Io (Real_Number); use Io_Double; procedure Put (Data : in Real_Vector_Type; Width : in Integer := 1) is Counter : Integer := 1; begin for I in Data'Range loop Put (Item => Data (I), Aft => 5, Exp => 0); if Counter mod Width = 0 then New_Line; else Put (" "); end if; Counter := Counter + 1; end loop; end Put; end Vector;
with SPARKNaCl; use SPARKNaCl; with SPARKNaCl.Debug; use SPARKNaCl.Debug; with SPARKNaCl.Sign; use SPARKNaCl.Sign; with Ada.Text_IO; use Ada.Text_IO; with Interfaces; use Interfaces; with Random; procedure Sign is Raw_SK : Bytes_32; PK : Signing_PK; SK : Signing_SK; M : constant Byte_Seq (0 .. 255) := (0 => 16#55#, others => 16#aa#); SM : Byte_Seq (0 .. 319) := (others => 0); M2 : Byte_Seq (0 .. 319) := (others => 0); M3 : Byte_Seq (0 .. 255); ML : I32; S : Boolean; -- I : I64 := 1; begin -- loop -- Put_Line ("Iteration " & I'Img); Random.Random_Bytes (Raw_SK); Keypair (Raw_SK, PK, SK); begin Sign (SM, M, SK); exception when Constraint_Error => Debug.DH ("In Sign, SK was ", Serialize (SK)); raise; end; begin Open (M2, S, ML, SM, PK); exception when Constraint_Error => Debug.DH ("In Open, PK was ", Serialize (PK)); Debug.DH ("In Open, SM was ", SM); raise; end; M3 := M2 (0 .. 255); -- I := I + 1; DH ("M3 is ", M3); Put_Line ("Status is " & Img (S)); Put_Line ("ML is " & ML'Img); -- end loop; end Sign;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2019, Fabien Chouteau -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ package LibRISCV.Instructions with SPARK_Mode => On is type Insn_Kind is ( Invalid, -- R-type Insn_ADD, Insn_SUB, Insn_SLL, Insn_SLT, Insn_SLTU, Insn_XOR, Insn_SRL, Insn_SRA, Insn_OR, Insn_AND, -- B-Type Insn_BEQ, Insn_BNE, Insn_BLT, Insn_BGE, Insn_BLTU, Insn_BGEU, -- S-Type Insn_SB, Insn_SH, Insn_SW, -- I-Type Insn_SLLI, Insn_SRLI, Insn_SRAI, Insn_JALR, Insn_LB, Insn_LH, Insn_LW, Insn_LBU, Insn_LHU, Insn_ADDI, Insn_SLTI, Insn_SLTIU, Insn_XORI, Insn_ORI, Insn_ANDI, Insn_FENCE, Insn_FENCE_I, Insn_ECALL, Insn_EBREAK, Insn_CSRRW, Insn_CSRRS, Insn_CSRRC, Insn_CSRRWI, Insn_CSRRSI, Insn_CSRRCI, Insn_URET, Insn_SRET, Insn_MRET, -- U-type Insn_LUI, Insn_AUIPC, -- J-Type Insn_JAL ); subtype R_Insn_Kind is Insn_Kind range Insn_ADD .. Insn_AND; subtype I_Insn_Kind is Insn_Kind range Insn_SLLI .. Insn_MRET; subtype S_Insn_Kind is Insn_Kind range Insn_SB .. Insn_SW; subtype B_Insn_Kind is Insn_Kind range Insn_BEQ .. Insn_BGEU; subtype U_Insn_Kind is Insn_Kind range Insn_LUI .. Insn_AUIPC; subtype J_Insn_Kind is Insn_Kind range Insn_JAL .. Insn_JAL; type Raw_Opcode is mod 2 ** 7 with Size => 7; type Raw_Imm8 is mod 2 ** 8 with Size => 8; type Raw_Imm12 is mod 2 ** 12 with Size => 12; type Raw_Imm13 is mod 2 ** 13 with Size => 13; type Raw_Imm16 is mod 2 ** 16 with Size => 16; type Raw_Imm19 is mod 2 ** 19 with Size => 19; type Raw_Imm21 is mod 2 ** 21 with Size => 21; type Instruction (Kind : Insn_Kind := Invalid) is record case Kind is when Invalid => Raw : Word; when R_Insn_Kind => R_RD, R_RS1, R_RS2 : GPR_Id; when I_Insn_Kind => I_RD, I_RS1 : GPR_Id; I_Imm : Raw_Imm12; when S_Insn_Kind => S_RS1, S_RS2 : GPR_Id; S_Imm : Raw_Imm12; when B_Insn_Kind => B_RS1, B_RS2 : GPR_Id; B_Imm : Raw_Imm13; when U_Insn_Kind => U_RD : GPR_Id; U_Imm : Word; when J_Insn_Kind => J_RD : GPR_Id; J_Imm : Raw_Imm21; end case; end record; function Decode (Raw : Word) return Instruction; function Encode (Insn : Instruction) return Word; function Img (Insn : Instruction; Addr : Address) return String; function Img (Kind : Insn_Kind) return String; function Sign_Extend (Imm : Raw_Imm13) return Register; function Sign_Extend (Imm : Raw_Imm12) return Register; function Sign_Extend (Imm : Raw_Imm21) return Register; type Raw_Funct7 is mod 2 ** 7 with Size => 7; type Raw_Funct3 is mod 2 ** 3 with Size => 3; OP_LUI : constant Raw_Opcode := 2#0110111#; OP_AUIPC : constant Raw_Opcode := 2#0010111#; OP_JAL : constant Raw_Opcode := 2#1101111#; OP_JALR : constant Raw_Opcode := 2#1100111#; OP_Branch : constant Raw_Opcode := 2#1100011#; OP_Load : constant Raw_Opcode := 2#0000011#; OP_Store : constant Raw_Opcode := 2#0100011#; OP_OP_IMM : constant Raw_Opcode := 2#0010011#; OP_OP : constant Raw_Opcode := 2#0110011#; OP_Misc_Mem : constant Raw_Opcode := 2#0001111#; OP_System : constant Raw_Opcode := 2#1110011#; Funct3_JALR : constant Raw_Funct3 := 2#000#; Funct3_BEQ : constant Raw_Funct3 := 2#000#; Funct3_BNE : constant Raw_Funct3 := 2#001#; Funct3_BLT : constant Raw_Funct3 := 2#100#; Funct3_BGE : constant Raw_Funct3 := 2#101#; Funct3_BLTU : constant Raw_Funct3 := 2#110#; Funct3_BGEU : constant Raw_Funct3 := 2#111#; Funct3_LB : constant Raw_Funct3 := 2#000#; Funct3_LH : constant Raw_Funct3 := 2#001#; Funct3_LW : constant Raw_Funct3 := 2#010#; Funct3_LBU : constant Raw_Funct3 := 2#100#; Funct3_LHU : constant Raw_Funct3 := 2#101#; Funct3_SB : constant Raw_Funct3 := 2#000#; Funct3_SH : constant Raw_Funct3 := 2#001#; Funct3_SW : constant Raw_Funct3 := 2#010#; Funct3_ADDI : constant Raw_Funct3 := 2#000#; Funct3_SLLI : constant Raw_Funct3 := 2#001#; Funct3_SLTI : constant Raw_Funct3 := 2#010#; Funct3_SLTIU : constant Raw_Funct3 := 2#011#; Funct3_XORI : constant Raw_Funct3 := 2#100#; Funct3_SRLI : constant Raw_Funct3 := 2#101#; Funct3_ORI : constant Raw_Funct3 := 2#110#; Funct3_ANDI : constant Raw_Funct3 := 2#111#; Funct3_FENCE : constant Raw_Funct3 := 2#000#; Funct3_FENCE_I : constant Raw_Funct3 := 2#001#; Funct3_ECALL : constant Raw_Funct3 := 2#000#; Funct3_EBREAK : constant Raw_Funct3 := 2#000#; Funct3_ADD_SUB : constant Raw_Funct3 := 2#000#; Funct3_SLL : constant Raw_Funct3 := 2#001#; Funct3_SLT : constant Raw_Funct3 := 2#010#; Funct3_SLTU : constant Raw_Funct3 := 2#011#; Funct3_XOR : constant Raw_Funct3 := 2#100#; Funct3_SR : constant Raw_Funct3 := 2#101#; Funct3_OR : constant Raw_Funct3 := 2#110#; Funct3_AND : constant Raw_Funct3 := 2#111#; Funct3_PRIV : constant Raw_Funct3 := 2#000#; Funct3_CSRRW : constant Raw_Funct3 := 2#001#; Funct3_CSRRS : constant Raw_Funct3 := 2#010#; Funct3_CSRRC : constant Raw_Funct3 := 2#011#; Funct3_CSRRWI : constant Raw_Funct3 := 2#101#; Funct3_CSRRSI : constant Raw_Funct3 := 2#110#; Funct3_CSRRCI : constant Raw_Funct3 := 2#111#; Funct7_ADD : constant Raw_Funct7 := 2#0000000#; Funct7_SUB : constant Raw_Funct7 := 2#0100000#; Funct7_SLL : constant Raw_Funct7 := 2#0000000#; Funct7_SLT : constant Raw_Funct7 := 2#0000000#; Funct7_SLTU : constant Raw_Funct7 := 2#0000000#; Funct7_XOR : constant Raw_Funct7 := 2#0000000#; Funct7_OR : constant Raw_Funct7 := 2#0000000#; Funct7_AND : constant Raw_Funct7 := 2#0000000#; Funct7_SRL : constant Raw_Funct7 := 2#0000000#; Funct7_SRA : constant Raw_Funct7 := 2#0100000#; Funct7_SLLI : constant Raw_Funct7 := 2#0000000#; Funct7_SRLI : constant Raw_Funct7 := 2#0000000#; Funct7_SRAI : constant Raw_Funct7 := 2#0100000#; private procedure Add_Opcode (Raw : in out Word; Op : Raw_Opcode); procedure Add_Funct3 (Raw : in out Word; Funct : Raw_Funct3); procedure Add_Funct7 (Raw : in out Word; Funct : Raw_Funct7); procedure Add_RD (Raw : in out Word; Id : GPR_Id); procedure Add_RS1 (Raw : in out Word; Id : GPR_Id); procedure Add_RS2 (Raw : in out Word; Id : GPR_Id); procedure Add_Imm13_B (Raw : in out Word; Imm : Raw_Imm13); procedure Add_Imm12_I (Raw : in out Word; Imm : Raw_Imm12); procedure Add_Imm12_S (Raw : in out Word; Imm : Raw_Imm12); procedure Add_Imm21_J (Raw : in out Word; Imm : Raw_Imm21); function Encode_R (Insn : Instruction) return Word with Pre => Insn.Kind in R_Insn_Kind; function Encode_I (Insn : Instruction) return Word with Pre => Insn.Kind in I_Insn_Kind; function Encode_S (Insn : Instruction) return Word with Pre => Insn.Kind in S_Insn_Kind; function Encode_B (Insn : Instruction) return Word with Pre => Insn.Kind in B_Insn_Kind; function Encode_U (Insn : Instruction) return Word with Pre => Insn.Kind in U_Insn_Kind; function Encode_J (Insn : Instruction) return Word with Pre => Insn.Kind in J_Insn_Kind; end LibRISCV.Instructions;
---------------------------------------- -- Copyright (C) 2019 Dmitriy Shadrin -- -- All rights reserved. -- ---------------------------------------- with Pal; with ConfigTree; with Sinks; with Logging_Message; use Logging_Message; with Ada.Containers.Ordered_Multisets; with Ada.Containers.Vectors; -------------------------------------------------------------------------------- package Logging is -------------------------------------------------------------------------------- procedure SendLogMessage (msg : LogMessage); ----------------------------------------------------------------------------- package LogsMultiset is new Ada.Containers.Ordered_Multisets (LogMessage); type SinksArray is array (1 .. 10) of aliased Sinks.Sink; protected type LogRecords is entry Push (item : in LogMessage); entry Pop (items : in Sinks.LogMessages); entry WaitEmpty; private entry Discard; messages : LogsMultiset.Set; isWorked : Pal.bool := true; end LogRecords; type LogRecordsPtr is access all LogRecords; ----------------------------------------------------------------------------- type Logger is tagged limited private; type LoggerPtr is access Logger; procedure Init (lg : in out Logger; cfg : in ConfigTree.NodePtr); function StartLogger (cfg : in ConfigTree.NodePtr) return LoggerPtr; procedure StopLogger; procedure CreateSinks (sArray : access SinksArray; sArraySize : in out Pal.uint32_t; cfg : in ConfigTree.NodePtr); ----------------------------------------------------------------------------- task type LogMultiplexer is entry Start (cfg : in ConfigTree.NodePtr); entry Stop; end LogMultiplexer; private type Logger is tagged limited record isWorked : Pal.bool; logs : LogRecords; mp : LogMultiplexer; end record; ----------------------------------------------------------------------------- loggerInstance : LoggerPtr; end Logging;
-- parse_args_suite-parse_args_tests.adb -- Unit tests for the Parse_Args project -- Copyright (c) 2016, James Humphry -- -- Permission to use, copy, modify, and/or distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE -- OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -- PERFORMANCE OF THIS SOFTWARE. with System.Assertions; with AUnit.Assertions; with Parse_Args; with Parse_Args.Testable; package body Parse_Args_Suite.Parse_Args_Tests is use AUnit.Assertions; use Parse_Args; use Parse_Args.Testable; -------------------- -- Register_Tests -- -------------------- procedure Register_Tests (T: in out Parse_Args_Test) is use AUnit.Test_Cases.Registration; begin Register_Routine (T, Check_Basics'Access, "Check basic functionality"); Register_Routine (T, Check_Boolean_Usage'Access, "Check Boolean option functionality"); Register_Routine (T, Check_Repeated_Usage'Access, "Check Repeated option functionality"); Register_Routine (T, Check_Integer_Usage'Access, "Check Integer option functionality"); Register_Routine (T, Check_String_Usage'Access, "Check String option functionality"); end Register_Tests; ---------- -- Name -- ---------- function Name (T : Parse_Args_Test) return Test_String is pragma Unreferenced (T); begin return Format ("Tests of Parse_Args package functionality"); end Name; ------------ -- Set_Up -- ------------ procedure Set_Up (T : in out Parse_Args_Test) is pragma Unreferenced (T); begin null; end Set_Up; ------------------ -- Check_Basics -- ------------------ procedure Check_Basics (T : in out Test_Cases.Test_Case'Class) is pragma Unreferenced(T); function Setup_AP return Testable_Argument_Parser is begin return Result : Testable_Argument_Parser do Result.Add_Option(O => Make_Boolean_Option(False), Name => "foo", Short_Option => 'f'); Result.Add_Option(O => Make_Boolean_Option(False), Name => "bar", Short_Option => 'b'); Result.Add_Option(O => Make_Boolean_Option(False), Name => "baz", Short_Option => 'z'); Result.Set_Command_Name("parse_args_tests"); end return; end Setup_AP; begin declare AP : Testable_Argument_Parser := Setup_AP; Catch_Message_Too_Soon : Boolean := False; Catch_Repeated_Parsing : Boolean := False; Catch_No_Such_Argument : Boolean := False; begin AP.Clear_Arguments; AP.Append_Arguments((+"--foo", +"-b")); Assert(AP.Ready, "New Argument_Parser not ready for use"); begin declare Dummy : String := AP.Parse_Message; begin null; end; exception when Program_Error | System.Assertions.Assert_Failure => Catch_Message_Too_Soon := True; end; Assert(Catch_Message_Too_Soon, "Returned a parse message before the parse has taken place"); AP.Parse_Command_Line; Assert(AP.Parse_Success, "Argument_Parser did not parse successfully: " & AP.Parse_Message); begin AP.Parse_Command_Line; exception when Program_Error | System.Assertions.Assert_Failure => Catch_Repeated_Parsing := True; end; Assert(Catch_Repeated_Parsing, "Did not object to Parse_Command_Line being called twice"); Assert(AP.Command_Name = "parse_args_tests", "Cannot retrieve command name"); Assert(AP.Get("foo").Set, "Boolean option bar incorrectly not marked as set"); Assert(AP.Get("bar").Set, "Boolean option bar incorrectly not marked as set"); Assert(not AP.Get("baz").Set, "Boolean option baz incorrectly marked as set"); begin declare Dummy : Boolean := AP.Boolean_Value("nosuch"); begin null; end; exception when Constraint_Error => Catch_No_Such_Argument := True; end; Assert(Catch_No_Such_Argument, "Returned a value for a non-existent option"); end; end Check_Basics; ------------------------- -- Check_Boolean_Usage -- ------------------------- procedure Check_Boolean_Usage (T : in out Test_Cases.Test_Case'Class) is pragma Unreferenced(T); function Setup_AP return Testable_Argument_Parser is begin return Result : Testable_Argument_Parser do Result.Add_Option(O => Make_Boolean_Option(False), Name => "foo", Short_Option => 'f'); Result.Add_Option(O => Make_Boolean_Option(True), Name => "bar", Short_Option => 'b'); Result.Add_Option(O => Make_Boolean_Option(False), Name => "baz", Short_Option => 'z', Long_Option => "-"); Result.Add_Option(O => Make_Boolean_Option(False), Name => "bork", Short_Option => '-', Long_Option => "borkable"); Result.Set_Command_Name("parse_args_tests"); end return; end Setup_AP; begin declare AP : Testable_Argument_Parser := Setup_AP; begin AP.Clear_Arguments; AP.Append_Arguments((+"--foo", +"-b", +"--borkable")); AP.Parse_Command_Line; Assert(AP.Parse_Success, "Argument_Parser did not parse successfully: " & AP.Parse_Message); Assert(AP.Boolean_Value("foo"), "Boolean option foo (default false) not toggled"); Assert(not AP.Boolean_Value("bar"), "Boolean option bar (default true) not toggled via short option"); Assert(AP.Boolean_Value("bork"), "Boolean option bork (default false) not toggled via renamed long option"); end; declare AP : Testable_Argument_Parser := Setup_AP; begin AP.Clear_Arguments; AP.Append_Argument("-bz"); AP.Parse_Command_Line; Assert(AP.Parse_Success, "Argument_Parser did not parse successfully"); Assert(not AP.Boolean_Value("foo"), "Boolean option foo (default false) set despite not being present in option group"); Assert(not AP.Boolean_Value("bar"), "Boolean option bar (default true) not toggled via short option group"); Assert(AP.Get("baz").Set, "Boolean option baz (default false) not toggled via short option group"); end; declare AP : Testable_Argument_Parser := Setup_AP; begin AP.Clear_Arguments; AP.Append_Arguments((+"--nonesuch", +"--foo")); AP.Parse_Command_Line; Assert(not AP.Parse_Success, "Parse successful despite passing non-existent long option"); end; declare AP : Testable_Argument_Parser := Setup_AP; begin AP.Clear_Arguments; AP.Append_Arguments((+"-n", +"--foo")); AP.Parse_Command_Line; Assert(not AP.Parse_Success, "Parse successful despite passing non-existent short option"); end; declare AP : Testable_Argument_Parser := Setup_AP; begin AP.Clear_Arguments; AP.Append_Argument("-fnz"); AP.Parse_Command_Line; Assert(not AP.Parse_Success, "Parse successful despite passing non-existent grouped short option"); end; declare AP : Testable_Argument_Parser := Setup_AP; begin AP.Clear_Arguments; AP.Append_Arguments((+"--foo", +"invalidarg")); AP.Parse_Command_Line; Assert(not AP.Parse_Success, "Parse successful despite passing an argument to a Boolean option"); end; declare AP : Testable_Argument_Parser := Setup_AP; begin AP.Clear_Arguments; AP.Append_Argument("--baz"); AP.Parse_Command_Line; Assert(not AP.Parse_Success, "Parse successful despite using a long option name on a short-name only option"); end; declare AP : Testable_Argument_Parser := Setup_AP; begin AP.Clear_Arguments; AP.Append_Argument("--bork"); AP.Parse_Command_Line; Assert(not AP.Parse_Success, "Parse successful despite using the underlying option name for a renamed long option"); end; end Check_Boolean_Usage; -------------------------- -- Check_Repeated_Usage -- -------------------------- procedure Check_Repeated_Usage (T : in out Test_Cases.Test_Case'Class) is pragma Unreferenced(T); function Setup_AP return Testable_Argument_Parser is begin return Result : Testable_Argument_Parser do Result.Add_Option(O => Make_Repeated_Option, Name => "foo", Short_Option => 'f'); Result.Add_Option(O => Make_Repeated_Option, Name => "bar", Short_Option => 'b'); Result.Add_Option(O => Make_Repeated_Option(5), Name => "baz", Short_Option => 'z'); Result.Add_Option(O => Make_Boolean_Option, Name => "snafu", Short_Option => 's'); Result.Set_Command_Name("parse_args_tests"); end return; end Setup_AP; begin declare AP : Testable_Argument_Parser := Setup_AP; begin AP.Clear_Arguments; AP.Append_Arguments((+"--foo", +"--foo", +"-b", +"-b")); AP.Parse_Command_Line; Assert(AP.Parse_Success, "Argument_Parser did not parse successfully: " & AP.Parse_Message); Assert(AP.Integer_Value("foo") = 2, "Repeated options (using long option type) not working"); Assert(AP.Integer_Value("bar") = 2, "Repeated options (using short option type) not working"); Assert(AP.Integer_Value("baz") = 5, "Repeated options defaults not working"); end; declare AP : Testable_Argument_Parser := Setup_AP; begin AP.Clear_Arguments; AP.Append_Arguments((+"-fbfb", +"--baz", +"-z", +"-z")); AP.Parse_Command_Line; Assert(AP.Parse_Success, "Argument_Parser did not parse successfully: " & AP.Parse_Message); Assert(AP.Integer_Value("foo") = 2, "Repeated options (using short option group) not working"); Assert(AP.Integer_Value("bar") = 2, "Repeated options (using short option group) not working"); Assert(AP.Integer_Value("baz") = 8, "Repeated optionsw with a default and mixed long and short " & "options are not working"); end; declare AP : Testable_Argument_Parser := Setup_AP; begin AP.Clear_Arguments; AP.Append_Arguments((+"-fz", +"--snafu", +"--baz", +"-z", +"-z", +"--foo")); AP.Parse_Command_Line; Assert(AP.Parse_Success, "Argument_Parser did not parse successfully: " & AP.Parse_Message); Assert(AP.Integer_Value("foo") = 2, "Repeated options (using short option group) not working"); Assert(AP.Integer_Value("bar") = 0, "Repeated options (with no default set and not invoked) not " & "returning 0 when retrieved"); Assert(AP.Integer_Value("baz") = 9, "Repeated optionsw with a default and mixed long and short " & "options are not working"); end; end Check_Repeated_Usage; ------------------------- -- Check_Integer_Usage -- ------------------------- procedure Check_Integer_Usage (T : in out Test_Cases.Test_Case'Class) is pragma Unreferenced(T); function Setup_AP return Testable_Argument_Parser is begin return Result : Testable_Argument_Parser do Result.Add_Option(O => Make_Integer_Option, Name => "foo", Short_Option => 'f'); Result.Add_Option(O => Make_Natural_Option, Name => "bar", Short_Option => 'b'); Result.Add_Option(O => Make_Positive_Option, Name => "baz", Short_Option => 'z'); Result.Add_Option(O => Make_Integer_Option(Default => 15, Min => 10, Max => 20), Name => "coz", Short_Option => 'c'); Result.Add_Option(O => Make_Boolean_Option, Name => "door", Short_Option => 'd'); Result.Set_Command_Name("parse_args_tests"); end return; end Setup_AP; Catch_No_Such_Argument : Boolean := False; begin declare AP : Testable_Argument_Parser := Setup_AP; begin AP.Clear_Arguments; AP.Append_Arguments((+"--foo", +"5", +"-c", +"12")); AP.Parse_Command_Line; Assert(AP.Parse_Success, "Argument_Parser did not parse successfully: " & AP.Parse_Message); Assert(AP.Integer_Value("foo") = 5, "Integer option (long form) not working"); Assert(AP.Integer_Value("bar") = 0, "Natural Option default not correct"); Assert(AP.Integer_Value("baz") = 1, "Positive option default not correct"); Assert(AP.Integer_Value("coz") = 12, "Integer option (short form) with custom range not working"); end; declare AP : Testable_Argument_Parser := Setup_AP; begin AP.Clear_Arguments; AP.Append_Arguments((+"-f", +"-7")); AP.Append_Arguments((+"-z", +"16#FF#")); AP.Parse_Command_Line; Assert(AP.Parse_Success, "Argument_Parser did not parse successfully: " & AP.Parse_Message); Assert(AP.Integer_Value("foo") = -7, "Positive option did not accept negative input"); Assert(AP.Integer_Value("baz") = 255, "Positive option did not accept hex input"); end; declare AP : Testable_Argument_Parser := Setup_AP; begin AP.Clear_Arguments; AP.Append_Arguments((+"-df", +"8")); AP.Parse_Command_Line; Assert(AP.Parse_Success, "Argument_Parser did not parse successfully: " & AP.Parse_Message); Assert(AP.Integer_Value("foo") = 8, "Integer option (short group) not working"); end; declare AP : Testable_Argument_Parser := Setup_AP; begin AP.Clear_Arguments; AP.Append_Arguments((+"-z", +"0")); AP.Parse_Command_Line; Assert(not AP.Parse_Success, "Argument parser did not reject 0 as input for Positive option"); end; declare AP : Testable_Argument_Parser := Setup_AP; begin AP.Clear_Arguments; AP.Append_Arguments((+"-c", +"8")); AP.Parse_Command_Line; Assert(not AP.Parse_Success, "Argument parser did not reject out-of range value for " & "customised Integer option"); end; declare AP : Testable_Argument_Parser := Setup_AP; begin AP.Clear_Arguments; AP.Append_Arguments((+"-f", +"--bar", +"8")); AP.Parse_Command_Line; Assert(not AP.Parse_Success, "Argument parser did not reject missing option value for an" & "Integer option"); end; declare AP : Testable_Argument_Parser := Setup_AP; begin AP.Clear_Arguments; AP.Append_Arguments((+"-fb", +"8")); AP.Parse_Command_Line; Assert(not AP.Parse_Success, "Argument parser did not reject missing option value for an" & "Integer option as part of a short option group"); end; declare AP : Testable_Argument_Parser := Setup_AP; begin AP.Clear_Arguments; AP.Append_Arguments((+"-f", +"8", +"--foo", +"9")); AP.Parse_Command_Line; Assert(not AP.Parse_Success, "Argument parser did not reject specifying an Integer option" & "twice."); end; declare AP : Testable_Argument_Parser := Setup_AP; begin AP.Parse_Command_Line; declare Dummy : Integer := AP.Integer_Value("nosuch"); begin null; end; exception when Constraint_Error => Catch_No_Such_Argument := True; end; Assert(Catch_No_Such_Argument, "Returned a value for a non-existent integer option"); end Check_Integer_Usage; ------------------------ -- Check_String_Usage -- ------------------------ procedure Check_String_Usage (T : in out Test_Cases.Test_Case'Class) is pragma Unreferenced(T); function Setup_AP return Testable_Argument_Parser is begin return Result : Testable_Argument_Parser do Result.Add_Option(O => Make_String_Option, Name => "foo", Short_Option => 'f'); Result.Add_Option(O => Make_String_Option(Default => "Hello"), Name => "bar", Short_Option => 'b'); Result.Add_Option(O => Make_String_Option, Name => "baz", Short_Option => 'z'); Result.Set_Command_Name("parse_args_tests"); end return; end Setup_AP; Catch_No_Such_Argument : Boolean := False; begin declare AP : Testable_Argument_Parser := Setup_AP; begin AP.Clear_Arguments; AP.Append_Arguments((+"--foo", +"5", +"-z", +"Goodbye")); AP.Parse_Command_Line; Assert(AP.Parse_Success, "Argument_Parser did not parse successfully: " & AP.Parse_Message); Assert(AP.String_Value("foo") = "5", "String option (long form) not working"); Assert(AP.String_Value("bar") = "Hello", "String Option default not correct"); Assert(AP.String_Value("baz") = "Goodbye", "String option (short form) not working"); end; declare AP : Testable_Argument_Parser := Setup_AP; begin AP.Parse_Command_Line; declare Dummy :String := AP.String_Value("nosuch"); begin null; end; exception when Constraint_Error => Catch_No_Such_Argument := True; end; Assert(Catch_No_Such_Argument, "Returned a value for a non-existent string option"); end Check_String_Usage; end Parse_Args_Suite.Parse_Args_Tests;
-- Abstract : -- -- Types and operatorion for LR(1) items. -- -- Copyright (C) 2003, 2008, 2013 - 2015, 2017 - 2019 Free Software Foundation, Inc. -- -- This file is part of the WisiToken package. -- -- The WisiToken package 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, or -- (at your option) any later version. The WisiToken package 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 the WisiToken package; -- see file GPL.txt. If not, write to the Free Software Foundation, -- 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -- -- As a special exception, if other files instantiate generics from -- this unit, or you link this unit with other files to produce an -- executable, this unit does not by itself cause the resulting -- executable to be covered by the GNU General Public License. This -- exception does not however invalidate any other reasons why the -- executable file might be covered by the GNU Public License. pragma License (Modified_GPL); with Interfaces; with SAL.Gen_Definite_Doubly_Linked_Lists_Sorted; with SAL.Gen_Unbounded_Definite_Red_Black_Trees; with SAL.Gen_Unbounded_Definite_Vectors.Gen_Comparable; with WisiToken.Productions; package WisiToken.Generate.LR1_Items is use all type Interfaces.Integer_16; subtype Lookahead is Token_ID_Set; -- Picking a type for Lookahead is not straight-forward. The -- operations required are (called numbers are for LR1 generate -- ada_lite): -- -- to_lookahead (token_id) -- Requires allocating memory dynamically: -- an unconstrained array range (first_terminal .. last_terminal) for (1), -- a smaller unconstrained array for (2), that grows as items are added -- individual list elements for (3). -- -- lr1_items.to_lookahead called 4_821_256 times in (2) -- sorted_token_id_lists.to_list called 4_821_256 times in (3) -- -- for tok_id of lookaheads loop -- sorted_token_id_lists__iterate called 5_687 times in (3) -- -- if lookaheads.contains (tok_id) then -- token_id_arrays__contains called 22_177_109 in (2) -- -- new_item := (... , lookaheads => old_item.lookaheads) -- new_item := (... , lookaheads => null_lookaheads) -- new_item := (... , lookaheads => propagate_lookahead) -- token_id_arrays.adjust called 8_437_967 times in (2) -- sorted_token_id_lists.adjust 8_435_797 times in (3) -- -- include: add tok_id to lookaheads -- -- keep sorted in token_id order, so rest of algorithm is -- stable/faster -- -- lr1_items.include called 6_818_725 times in (2) -- -- lookaheads /= lookaheads -- if using a container, container must override "=" -- -- We've tried: -- -- (1) Token_ID_Set (unconstrained array of boolean, allocated directly) - fastest -- -- Allocates more memory than (2), but everything else is fast, -- and it's not enough memory to matter. -- -- Loop over lookaheads is awkward: -- for tok_id in lookaheads'range loop -- if lookaheads (tok_id) then -- ... -- But apparently it's fast enough. -- -- (2) Instantiation of SAL.Gen_Unbounded_Definite_Vectors (token_id_arrays) - slower than (1). -- -- Productions RHS is also token_id_arrays, so gprof numbers are -- hard to sort out. Could be improved with a custom container, that -- does sort and insert internally. Insert is inherently slow. -- -- (3) Instantiation of SAL.Gen_Definite_Doubly_Linked_Lists_Sorted - slower than (2) type Item is record Prod : Production_ID; Dot : Token_ID_Arrays.Cursor; -- token after item Dot Lookaheads : Token_ID_Set_Access := null; -- Programmer must remember to copy Item.Lookaheads.all, not -- Item.Lookaheads. Wrapping this in Ada.Finalization.Controlled -- would just slow it down. -- -- We don't free Lookaheads; we assume the user is running -- wisi-generate, and not keeping LR1_Items around. end record; function To_Lookahead (Item : in Token_ID; Descriptor : in WisiToken.Descriptor) return Lookahead; function Contains (Item : in Lookahead; ID : in Token_ID) return Boolean is (Item (ID)); function Lookahead_Image (Item : in Lookahead; Descriptor : in WisiToken.Descriptor) return String; -- Returns the format used in parse table output. function Item_Compare (Left, Right : in Item) return SAL.Compare_Result; -- Sort Item_Lists in ascending order of Prod.Nonterm, Prod.RHS, Dot; -- ignores Lookaheads. package Item_Lists is new SAL.Gen_Definite_Doubly_Linked_Lists_Sorted (Item, Item_Compare); procedure Include (Item : in out LR1_Items.Item; Value : in Lookahead; Added : out Boolean); -- Add Value to Item.Lookahead, if not already present. -- -- Added is True if Value was not already present. -- -- Does not exclude Propagate_ID. procedure Include (Item : in out LR1_Items.Item; Value : in Lookahead; Descriptor : in WisiToken.Descriptor); -- Add Value to Item.Lookahead. Does not check if already present. -- Excludes Propagate_ID. procedure Include (Item : in out LR1_Items.Item; Value : in Lookahead; Added : out Boolean; Descriptor : in WisiToken.Descriptor); -- Add Value to Item.Lookahead. type Goto_Item is record Symbol : Token_ID; -- If Symbol is a terminal, this is a shift and goto state action. -- If Symbol is a non-terminal, this is a post-reduce goto state action. State : State_Index; end record; function Goto_Item_Compare (Left, Right : in Goto_Item) return SAL.Compare_Result is (if Left.Symbol > Right.Symbol then SAL.Greater elsif Left.Symbol < Right.Symbol then SAL.Less else SAL.Equal); -- Sort Goto_Item_Lists in ascending order of Symbol. package Goto_Item_Lists is new SAL.Gen_Definite_Doubly_Linked_Lists_Sorted (Goto_Item, Goto_Item_Compare); type Item_Set is record Set : Item_Lists.List; Goto_List : Goto_Item_Lists.List; Dot_IDs : Token_ID_Arrays.Vector; State : Unknown_State_Index := Unknown_State; end record; function Filter (Set : in Item_Set; Grammar : in WisiToken.Productions.Prod_Arrays.Vector; Descriptor : in WisiToken.Descriptor; Include : access function (Grammar : in WisiToken.Productions.Prod_Arrays.Vector; Descriptor : in WisiToken.Descriptor; Item : in LR1_Items.Item) return Boolean) return Item_Set; -- Return a deep copy of Set, including only items for which Include returns True. function In_Kernel (Grammar : in WisiToken.Productions.Prod_Arrays.Vector; Descriptor : in WisiToken.Descriptor; Item : in LR1_Items.Item) return Boolean; -- For use with Filter; [dragon] sec 4.7 pg 240 function Find (Item : in LR1_Items.Item; Set : in Item_Set) return Item_Lists.Cursor; -- Return an item from Set that matches Item.Prod, Item.Dot. -- -- Return No_Element if not found. function Find (Prod : in Production_ID; Dot : in Token_ID_Arrays.Cursor; Right : in Item_Set) return Item_Lists.Cursor; -- Return an item from Right that matches Prod, Dot. -- -- Return No_Element if not found. function Find (Prod : in Production_ID; Dot : in Token_ID_Arrays.Cursor; Right : in Item_Set; Lookaheads : in Lookahead) return Item_Lists.Cursor; -- Return an item from Right that matches Prod, Dot, and -- Lookaheads. -- -- Return No_Element if not found. -- -- Not combined with non-Lookaheads version for speed; this is called -- a lot. package Item_Set_Arrays is new SAL.Gen_Unbounded_Definite_Vectors (State_Index, Item_Set, Default_Element => (others => <>)); subtype Item_Set_List is Item_Set_Arrays.Vector; package Int_Arrays is new SAL.Gen_Unbounded_Definite_Vectors (Positive, Interfaces.Integer_16, Default_Element => Interfaces.Integer_16'Last); function Compare_Integer_16 (Left, Right : in Interfaces.Integer_16) return SAL.Compare_Result is (if Left > Right then SAL.Greater elsif Left < Right then SAL.Less else SAL.Equal); package Int_Arrays_Comparable is new Int_Arrays.Gen_Comparable (Compare_Integer_16); subtype Item_Set_Tree_Key is Int_Arrays_Comparable.Vector; -- We want a key that is fast to compare, and has enough info to -- significantly speed the search for an item set. So we convert all -- relevant data in an item into a string of integers. We need 16 bit -- because Ada token_ids max is 332. LR1 keys include lookaheads, -- LALR keys do not. type Item_Set_Tree_Node is record Key : Item_Set_Tree_Key; State : Unknown_State_Index; end record; function To_Item_Set_Tree_Key (Item_Set : in LR1_Items.Item_Set; Include_Lookaheads : in Boolean) return Item_Set_Tree_Key; function To_Item_Set_Tree_Key (Node : in Item_Set_Tree_Node) return Item_Set_Tree_Key is (Node.Key); package Item_Set_Trees is new SAL.Gen_Unbounded_Definite_Red_Black_Trees (Element_Type => Item_Set_Tree_Node, Key_Type => Item_Set_Tree_Key, Key => To_Item_Set_Tree_Key, Key_Compare => Int_Arrays_Comparable.Compare); -- Item_Set_Arrays.Vector holds state item sets indexed by state, for -- iterating in state order. Item_Set_Trees.Tree holds lists of state -- indices sorted by LR1 item info, for fast Find in LR1_Item_Sets -- and LALR_Kernels. function Find (New_Item_Set : in Item_Set; Item_Set_Tree : in Item_Set_Trees.Tree; Match_Lookaheads : in Boolean) return Unknown_State_Index; -- Return the State of an element in Item_Set_Tree matching -- New_Item_Set, Unknown_State if not found. -- -- Match_Lookaheads is True in LR1_Generate. procedure Add (New_Item_Set : in out Item_Set; Item_Set_Vector : in out Item_Set_List; Item_Set_Tree : in out Item_Set_Trees.Tree; Descriptor : in WisiToken.Descriptor; Include_Lookaheads : in Boolean); -- Set New_Item_Set.Dot_IDs, add New_Item_Set to Item_Set_Vector, Item_Set_Tree function Is_In (Item : in Goto_Item; Goto_List : in Goto_Item_Lists.List) return Boolean; -- Return True if a goto on Symbol to State is found in Goto_List function Goto_State (From : in Item_Set; Symbol : in Token_ID) return Unknown_State_Index; -- Return state from From.Goto_List where the goto symbol is -- Symbol; Unknown_State if not found. function Closure (Set : in Item_Set; Has_Empty_Production : in Token_ID_Set; First_Terminal_Sequence : in Token_Sequence_Arrays.Vector; Grammar : in WisiToken.Productions.Prod_Arrays.Vector; Descriptor : in WisiToken.Descriptor) return Item_Set; -- Return the closure of Set over Grammar. First must be the -- result of First above. Makes a deep copy of Goto_List. -- Implements 'closure' from [dragon] algorithm 4.9 pg 232, but -- allows merging lookaheads into one item.. function Productions (Set : in Item_Set) return Production_ID_Arrays.Vector; procedure Put (Grammar : in WisiToken.Productions.Prod_Arrays.Vector; Descriptor : in WisiToken.Descriptor; Item : in LR1_Items.Item; Show_Lookaheads : in Boolean := True); procedure Put (Grammar : in WisiToken.Productions.Prod_Arrays.Vector; Descriptor : in WisiToken.Descriptor; Item : in Item_Lists.List; Show_Lookaheads : in Boolean := True; Kernel_Only : in Boolean := False); procedure Put (Grammar : in WisiToken.Productions.Prod_Arrays.Vector; Descriptor : in WisiToken.Descriptor; Item : in Item_Set; Show_Lookaheads : in Boolean := True; Kernel_Only : in Boolean := False; Show_Goto_List : in Boolean := False); procedure Put (Descriptor : in WisiToken.Descriptor; List : in Goto_Item_Lists.List); procedure Put (Grammar : in WisiToken.Productions.Prod_Arrays.Vector; Descriptor : in WisiToken.Descriptor; Item : in Item_Set_List; Show_Lookaheads : in Boolean := True); -- Put Item to Ada.Text_IO.Standard_Output. Does not end with New_Line. end WisiToken.Generate.LR1_Items;
-- Copyright (c) 2019 Maxim Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- with Program.Elements.Anonymous_Access_Definitions; with Program.Lexical_Elements; with Program.Elements.Parameter_Specifications; package Program.Elements.Anonymous_Access_To_Procedures is pragma Pure (Program.Elements.Anonymous_Access_To_Procedures); type Anonymous_Access_To_Procedure is limited interface and Program.Elements.Anonymous_Access_Definitions .Anonymous_Access_Definition; type Anonymous_Access_To_Procedure_Access is access all Anonymous_Access_To_Procedure'Class with Storage_Size => 0; not overriding function Parameters (Self : Anonymous_Access_To_Procedure) return Program.Elements.Parameter_Specifications .Parameter_Specification_Vector_Access is abstract; not overriding function Has_Not_Null (Self : Anonymous_Access_To_Procedure) return Boolean is abstract; not overriding function Has_Protected (Self : Anonymous_Access_To_Procedure) return Boolean is abstract; type Anonymous_Access_To_Procedure_Text is limited interface; type Anonymous_Access_To_Procedure_Text_Access is access all Anonymous_Access_To_Procedure_Text'Class with Storage_Size => 0; not overriding function To_Anonymous_Access_To_Procedure_Text (Self : aliased in out Anonymous_Access_To_Procedure) return Anonymous_Access_To_Procedure_Text_Access is abstract; not overriding function Not_Token (Self : Anonymous_Access_To_Procedure_Text) return Program.Lexical_Elements.Lexical_Element_Access is abstract; not overriding function Null_Token (Self : Anonymous_Access_To_Procedure_Text) return Program.Lexical_Elements.Lexical_Element_Access is abstract; not overriding function Access_Token (Self : Anonymous_Access_To_Procedure_Text) return not null Program.Lexical_Elements.Lexical_Element_Access is abstract; not overriding function Protected_Token (Self : Anonymous_Access_To_Procedure_Text) return Program.Lexical_Elements.Lexical_Element_Access is abstract; not overriding function Procedure_Token (Self : Anonymous_Access_To_Procedure_Text) return not null Program.Lexical_Elements.Lexical_Element_Access is abstract; not overriding function Left_Bracket_Token (Self : Anonymous_Access_To_Procedure_Text) return Program.Lexical_Elements.Lexical_Element_Access is abstract; not overriding function Right_Bracket_Token (Self : Anonymous_Access_To_Procedure_Text) return Program.Lexical_Elements.Lexical_Element_Access is abstract; end Program.Elements.Anonymous_Access_To_Procedures;
------------------------------------------------------------------------------ -- -- -- GNAT ncurses Binding Samples -- -- -- -- Sample.Curses_Demo.Mouse -- -- -- -- B O D Y -- -- -- ------------------------------------------------------------------------------ -- Copyright 2020 Thomas E. Dickey -- -- Copyright 1998-2006,2008 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: Juergen Pfeifer, 1996 -- Version Control -- $Revision: 1.17 $ -- $Date: 2020/02/02 23:34:34 $ -- Binding Version 01.00 ------------------------------------------------------------------------------ with Terminal_Interface.Curses; use Terminal_Interface.Curses; with Terminal_Interface.Curses.Panels; use Terminal_Interface.Curses.Panels; with Terminal_Interface.Curses.Mouse; use Terminal_Interface.Curses.Mouse; with Terminal_Interface.Curses.Text_IO; use Terminal_Interface.Curses.Text_IO; with Terminal_Interface.Curses.Text_IO.Integer_IO; with Terminal_Interface.Curses.Text_IO.Enumeration_IO; with Sample.Helpers; use Sample.Helpers; with Sample.Manifest; use Sample.Manifest; with Sample.Keyboard_Handler; use Sample.Keyboard_Handler; with Sample.Function_Key_Setting; use Sample.Function_Key_Setting; with Sample.Explanation; use Sample.Explanation; package body Sample.Curses_Demo.Mouse is package Int_IO is new Terminal_Interface.Curses.Text_IO.Integer_IO (Integer); use Int_IO; package Button_IO is new Terminal_Interface.Curses.Text_IO.Enumeration_IO (Mouse_Button); use Button_IO; package State_IO is new Terminal_Interface.Curses.Text_IO.Enumeration_IO (Button_State); use State_IO; procedure Demo is type Controls is array (1 .. 3) of Panel; Frame : Window; Msg : Window; Ctl : Controls; Pan : Panel; K : Real_Key_Code; V : Cursor_Visibility := Invisible; W : Window; Note : Window; Msg_L : constant Line_Count := 8; Lins : Line_Position := Lines; Cols : Column_Position; Mask : Event_Mask; procedure Show_Mouse_Event; procedure Show_Mouse_Event is Evt : constant Mouse_Event := Get_Mouse; Y : Line_Position; X : Column_Position; Button : Mouse_Button; State : Button_State; W : Window; begin Get_Event (Evt, Y, X, Button, State); Put (Msg, "Event at"); Put (Msg, " X="); Put (Msg, Integer (X), 3); Put (Msg, ", Y="); Put (Msg, Integer (Y), 3); Put (Msg, ", Btn="); Put (Msg, Button, 10); Put (Msg, ", Stat="); Put (Msg, State, 15); for I in Ctl'Range loop W := Get_Window (Ctl (I)); if Enclosed_In_Window (W, Evt) then Transform_Coordinates (W, Y, X, From_Screen); Put (Msg, ",Box("); Put (Msg, (I), 1); Put (Msg, ","); Put (Msg, Integer (Y), 1); Put (Msg, ","); Put (Msg, Integer (X), 1); Put (Msg, ")"); end if; end loop; New_Line (Msg); Flush (Msg); Update_Panels; Update_Screen; end Show_Mouse_Event; begin Push_Environment ("MOUSE00"); Notepad ("MOUSE-PAD00"); Default_Labels; Set_Cursor_Visibility (V); Note := Notepad_Window; if Note /= Null_Window then Get_Window_Position (Note, Lins, Cols); end if; Frame := Create (Msg_L, Columns, Lins - Msg_L, 0); if Has_Colors then Set_Background (Win => Frame, Ch => (Color => Default_Colors, Attr => Normal_Video, Ch => ' ')); Set_Character_Attributes (Win => Frame, Attr => Normal_Video, Color => Default_Colors); Erase (Frame); end if; Msg := Derived_Window (Frame, Msg_L - 2, Columns - 2, 1, 1); Pan := Create (Frame); Set_Meta_Mode; Set_KeyPad_Mode; Mask := Start_Mouse; Box (Frame); Window_Title (Frame, "Mouse Protocol"); Refresh_Without_Update (Frame); Allow_Scrolling (Msg, True); declare Middle_Column : constant Integer := Integer (Columns) / 2; Middle_Index : constant Natural := Ctl'First + (Ctl'Length / 2); Width : constant Column_Count := 5; Height : constant Line_Count := 3; Half : constant Column_Count := Width / 2; Space : constant Column_Count := 3; Position : Integer; W : Window; begin for I in Ctl'Range loop Position := ((I) - Integer (Middle_Index)) * Integer (Half + Space + Width) + Middle_Column; W := Create (Height, Width, 1, Column_Position (Position)); if Has_Colors then Set_Background (Win => W, Ch => (Color => Menu_Back_Color, Attr => Normal_Video, Ch => ' ')); Set_Character_Attributes (Win => W, Attr => Normal_Video, Color => Menu_Fore_Color); Erase (W); end if; Ctl (I) := Create (W); Box (W); Move_Cursor (W, 1, Half); Put (W, (I), 1); Refresh_Without_Update (W); end loop; end; Update_Panels; Update_Screen; loop K := Get_Key; if K in Special_Key_Code'Range then case K is when QUIT_CODE => exit; when HELP_CODE => Explain_Context; when EXPLAIN_CODE => Explain ("MOUSEKEYS"); when Key_Mouse => Show_Mouse_Event; when others => null; end case; end if; end loop; for I in Ctl'Range loop W := Get_Window (Ctl (I)); Clear (W); Delete (Ctl (I)); Delete (W); end loop; Clear (Frame); Delete (Pan); Delete (Msg); Delete (Frame); Set_Cursor_Visibility (V); End_Mouse (Mask); Pop_Environment; Update_Panels; Update_Screen; end Demo; end Sample.Curses_Demo.Mouse;
private with Ada.Calendar; package Stopwatch is type Instance is tagged private; procedure Reset (This : in out Instance); function Elapsed (This : Instance) return Duration; procedure Hold (This : in out Instance; Enable : Boolean := True); -- Stop counting time, or re-start if not Enable procedure Release (This : in out Instance); -- Equivalent to Hold (Enable => False) function Is_Held (This : Instance) return Boolean; function Image (This : Instance; Decimals : Natural := 2) return String; -- Elapsed time in seconds, without leading space, without units function Image (Elapsed : Duration; Decimals : Natural := 2) return String; -- Convenience to format durations even without a stopwatch private use Ada.Calendar; type Instance is tagged record Start : Time := Clock; -- Last moment the timer was released/started Held : Boolean := False; Elapsed : Duration := 0.0; -- Track elapsed time when held end record; end Stopwatch;
with Units; use Units; with Ulog; use Ulog; with Ulog.GPS; use Ulog.Gps; with Ada.Text_IO; use Ada.Text_IO; with Ada.Tags; with Interfaces; -- Rules for conversion in OO programming: -- 1. SPECIFIC TYPES: only up-cast (towards ancestors/base) possible -- * view conversion, i.e., components not in parent are hidden -- * tag stays untouched (really? then why no dispatching?) -- * no initialization necessary -- * not dispatching -- 2. CLASS-WIDE TYPES: both directions (ancestors <> descendant) possible -- * view conversions -- * requires initialization with specific -- * dispatch works -- 3. VIEW RENAMING: to rename result of a view conversion -- * view the result as target type -- * optimal performance -- * requires "initialization" with specific -- * dispatch works -- X. VIEW CONVERSION: if both source and target type are tagged, or -- if appearing in a call as IN OUT or OUT paramete. -- Y. VALUE CONVERSION: everything else -- Z. DYAMIC DISPATCHING -- procedure main is l : Length_Type; begin consume (msg_gps); -- consume (msg); -- msg_gps.Describe; end main;
with LV; with LV.Font; with LV.Theme; with LV.Tasks; with LV.HAL.Tick; with Test_Theme_1; with Disaply_Simulator; procedure Main is begin LV.Init; Disaply_Simulator.Initialize; Test_Theme_1.Init; loop LV.Tasks.Handler; delay 0.005; lV.HAL.Tick.Inc (5); end loop; end Main;
-- { dg-do compile } -- { dg-options "-gnatD" } with System; with Ada.Unchecked_Conversion; procedure gnatg is subtype Address is System.Address; type T is access procedure; function Cvt is new Ada.Unchecked_Conversion (Address, T); X : T; begin X := Cvt (Gnatg'Address); end gnatg;
with Ada.Text_IO, Ada.Containers.Vectors; procedure RPN_Calculator is package IIO is new Ada.Text_IO.Float_IO(Float); package Float_Vec is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Float); Stack: Float_Vec.Vector; Input: String := Ada.Text_IO.Get_Line; Cursor: Positive := Input'First; New_Cursor: Positive; begin loop -- read spaces while Cursor <= Input'Last and then Input(Cursor)=' ' loop Cursor := Cursor + 1; end loop; exit when Cursor > Input'Last; New_Cursor := Cursor; while New_Cursor <= Input'Last and then Input(New_Cursor) /= ' ' loop New_Cursor := New_Cursor + 1; end loop; -- try to read a number and push it to the stack declare Last: Positive; Value: Float; X, Y: Float; begin IIO.Get(From => Input(Cursor .. New_Cursor - 1), Item => Value, Last => Last); Stack.Append(Value); Cursor := New_Cursor; exception -- if reading the number fails, try to read an operator token when others => Y := Stack.Last_Element; Stack.Delete_Last; -- pick two elements X := Stack.Last_Element; Stack.Delete_Last; -- from the stack case Input(Cursor) is when '+' => Stack.Append(X+Y); when '-' => Stack.Append(X-Y); when '*' => Stack.Append(X*Y); when '/' => Stack.Append(X/Y); when '^' => Stack.Append(X ** Integer(Float'Rounding(Y))); when others => raise Program_Error with "unecpected token '" & Input(Cursor) & "' at column" & Integer'Image(Cursor); end case; Cursor := New_Cursor; end; for I in Stack.First_Index .. Stack.Last_Index loop Ada.Text_IO.Put(" "); IIO.Put(Stack.Element(I), Aft => 5, Exp => 0); end loop; Ada.Text_IO.New_Line; end loop; Ada.Text_IO.Put("Result = "); IIO.Put(Item => Stack.Last_Element, Aft => 5, Exp => 0); end RPN_Calculator;
with Ada.Numerics.Discrete_Random; package body Noise is type Color is (Black, White); package Color_Random is new Ada.Numerics.Discrete_Random (Color); Color_Gen : Color_Random.Generator; function Create_Image (Width, Height : Natural) return Lumen.Image.Descriptor is Result : Lumen.Image.Descriptor; begin Color_Random.Reset (Color_Gen); Result.Width := Width; Result.Height := Height; Result.Complete := True; Result.Values := new Lumen.Image.Pixel_Matrix (1 .. Width, 1 .. Height); for X in 1 .. Width loop for Y in 1 .. Height loop if Color_Random.Random (Color_Gen) = Black then Result.Values (X, Y) := (R => 0, G => 0, B => 0, A => 0); else Result.Values (X, Y) := (R => 255, G => 255, B => 255, A => 0); end if; end loop; end loop; return Result; end Create_Image; end Noise;
-- part of OpenGLAda, (c) 2017 Felix Krause -- released under the terms of the MIT license, see the file "COPYING" package Glfw.Windows.Clipboard is -- strings are UTF-8 encoded function Get (Object : not null access Window'Class) return String; procedure Set (Object : not null access Window'Class; Value : String); end Glfw.Windows.Clipboard;
with Ada.Text_IO; use Ada.Text_IO; with Input; procedure Day03 is type Fabric_Piece_Array is array (Natural range 1 .. 1000, Natural range 1 .. 1000) of Natural; Fabric_Piece : Fabric_Piece_Array := (others => (others => 0)); begin -- Part 1 declare Claim_Counter : Integer := 0; begin for Claim of Input.Claims loop for I in (Claim.X + 1) .. (Claim.X + Claim.Width) loop for J in (Claim.Y + 1) .. (Claim.Y + Claim.Height) loop if Fabric_Piece (I, J) = 1 then Claim_Counter := Claim_Counter + 1; end if; Fabric_Piece (I, J) := Fabric_Piece (I, J) + 1; end loop; end loop; end loop; Put_Line ("Part 1 =" & Integer'Image (Claim_Counter)); end; -- Part 2 Outer_Loop : for Claim of Input.Claims loop declare Is_Intact : Boolean := True; begin Check_Loop : for I in (Claim.X + 1) .. (Claim.X + Claim.Width) loop for J in (Claim.Y + 1) .. (Claim.Y + Claim.Height) loop if Fabric_Piece (I, J) /= 1 then Is_Intact := False; exit Check_Loop; end if; end loop; end loop Check_Loop; if Is_Intact then Put_Line ("Part 2 =" & Integer'Image (Claim.ID)); exit Outer_Loop; end if; end; end loop Outer_Loop; end Day03;
------------------------------------------------------------------------------ -- -- -- ASIS-for-GNAT IMPLEMENTATION COMPONENTS -- -- -- -- A 4 G . M A P P I N G -- -- -- -- S p e c -- -- -- -- Copyright (C) 1995-2011, Free Software Foundation, Inc. -- -- -- -- ASIS-for-GNAT is free software; you can redistribute it and/or modify it -- -- under terms of the GNU General Public License as published by the Free -- -- Software Foundation; either version 2, or (at your option) any later -- -- version. ASIS-for-GNAT is distributed in the hope that it will be use- -- -- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- -- -- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General -- -- Public License for more details. You should have received a copy of the -- -- GNU General Public License distributed with ASIS-for-GNAT; see file -- -- COPYING. If not, write to the Free Software Foundation, 51 Franklin -- -- Street, Fifth Floor, Boston, MA 02110-1301, USA. -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the -- -- Software Engineering Laboratory of the Swiss Federal Institute of -- -- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the -- -- Scientific Research Computer Center of Moscow State University (SRCC -- -- MSU), Russia, with funding partially provided by grants from the Swiss -- -- National Science Foundation and the Swiss Academy of Engineering -- -- Sciences. ASIS-for-GNAT is now maintained by AdaCore -- -- (http://www.adacore.com). -- -- -- ------------------------------------------------------------------------------ -- This package defines and implements the mapping from the nodes in the -- tree created by the front-end nodes onto ASIS Elements. -- The main part of this mapping are: -- -- - the function constructing an ASIS Element from a tree -- node; -- - the function constructing an ASIS Element_List from a tree node -- list; -- - a set of functions defining the ASIS kind (or, more exactly, the -- corresponding value of the Internal_Element_Kinds type) of an Element -- which can be built on the base of a given node. Most of these functions -- are hidden in the package body, but for some of them their -- specifications are placed in the package spec in order to make them -- visible for the implementation of some ASIS queries (for example, -- sometimes we have to know the exact kind of an operator symbol or -- of an attribute reference. -- The functions defined in this package are of relatively low level. In -- particular, as a rule, they do not check the correctness of their -- arguments, and a caller is responsible for the correct usage of these -- functions. with Asis; with A4G.A_Types; use A4G.A_Types; with A4G.Int_Knds; use A4G.Int_Knds; with Types; use Types; with Sinfo; use Sinfo; package A4G.Mapping is Parent_Node : Node_Id; -- The determination of the ASIS Internal Element Kind is based on -- the original tree nodes. Sometimes it requires information about -- the "context" of a node, that is, about its the parent node. -- If the node is rewritten, its original node has Parent field -- set to N_Empty. The global variable Parent_Node is used to -- transfer the parent node from Node_To_Element function to -- Asis_Internal_Element_Kind function. -- -- ??? -- For now, it is defined in the package spec, because it is needed -- by the current implementation of Enclosing_Element. As soon as -- the implementation of Enclosing _Element is rewritten on top of -- Traverse_Element, the declaration of Parent_Node should be -- moved in the body of the package. function Asis_Internal_Element_Kind (Node : Node_Id) return Internal_Element_Kinds; -- This function is the kernel of the tree node -> Asis Element -- mapping. Taking a tree Node, it defines the Internal_Element_Kinds -- value for the Element which may be constructed on the base of this -- node. Node should be an original, but not the rewritten node in case -- if tree rewriting takes place for a given construct. -- -- This function does not check, whether or not an Element could be -- really construct for a given Node, a caller is responsible for -- obtaining the proper node for Element construction, or for filtering -- out inappropriate nodes in case when this function is applied -- to construct an Element_List. -- -- If no Asis_Element could be constructed on the base of the Node, then -- ASIS_Failed is raised. -- -- This function is placed in the package spec, because it is needed -- by A4G.CU_Info2 routines function N_Operator_Symbol_Mapping (Node : Node_Id) return Internal_Element_Kinds; -- One of the functional components of the general -- Asis_Internal_Element_Kind function, it is placed in the package spec -- because it is needed by Asis.Expressions.Prefix. -- function. function Is_Not_Duplicated_Decl (Node : Node_Id) return Boolean; -- This function checks if Node does not correspond to the declaration -- which is included in the tree twice - first on its own and then -- as an original node for some rewritten structure. For instance, this -- is the case for a type derived from private type and having no -- explicit constrain. -- -- This function return False for the second of the two duplicated -- declarations. -- -- This function is placed in the package spec, because it is used by -- A4G.Decl_Sem.Serach_First_View function Subprogram_Attribute_Kind (Node : Node_Id) return Internal_Element_Kinds; -- This function defines the kind of an Element which can be built on -- N_Attribute_Reference node corresponding to a reference to -- attribute-subprogram, but opposite to the general attribute kind -- determination implemented by N_Attribute_Reference_Mapping, it does -- not classify an Element as a function or a procedure call, but it -- defines the corresponding Attribute_Kinds value. function Is_GNAT_Attribute_Routine (N : Node_Id) return Boolean; -- Checks if N represents a GNAT-specific attribute which is a function or -- a procedure function Is_Rewritten_Function_Prefix_Notation (N : Node_Id) return Boolean; -- Checks if N represents a function call given in Object.Operation [(...)] -- form. In this case N is a rewritten node, and the original subtree -- is not decorated and the original node is not even classified as -- a function call function Is_Rewritten_Impl_Deref_Function_Prefix_Notation (N : Node_Id) return Boolean; -- Checks if N represents a function call given in Object.Operation [(...)] -- for a special case when the call is used in implicit dereference (the -- caller is responsible to call this function only for nodes corresponding -- to implicit dereference!) function Node_To_Element_New (Node : Node_Id; Node_Field_1 : Node_Id := Empty; Node_Field_2 : Node_Id := Empty; Starting_Element : Asis.Element := Asis.Nil_Element; Internal_Kind : Internal_Element_Kinds := Not_An_Element; Spec_Case : Special_Cases := Not_A_Special_Case; Norm_Case : Normalization_Cases := Is_Not_Normalized; Considering_Parent_Count : Boolean := True; Using_Original_Node : Boolean := True; Inherited : Boolean := False; In_Unit : Asis.Compilation_Unit := Asis.Nil_Compilation_Unit) return Asis.Element; -- This functions creates the ASIS Element which could be built on the -- basis of Node. Its other parameters have the following meaning (the -- wording "the parameter is set" means below that some non-nil value -- is explicitly passed in the call): -- -- Starting_Element - if this parameter is set, the following fields -- of the result Element are set as being equal to the corresponding -- fields of Starting_Element: -- -- - Enclosing_Unit (unless the In_Unit parameter is set); -- - Enclosing_Context (unless the In_Unit parameter is set); -- - Is_Part_Of_Implicit; -- - Is_Part_Of_Inherited; -- - Is_Part_Of_Instance; -- - Special_Case (unless the Special_Case parameter is set); -- - Node_Field_1 (unless the Node_Field_1 parameter is set) -- - Node_Field_2 (unless the Node_Field_2 parameter is set) -- The typical situation of using this function in the implementations of -- ASIS (structural) queries is to set Starting_Element as being equal to -- the argument Element of the ASIS query. -- -- If Starting_Element is not set, the corresponding fields of the -- result are computed from Node. -- -- Internal_Kind - if this parameter is set, its value is set as the -- value of the Internal_Kind field of the result Element. Otherwise -- the kind of the result Element is determined automatically -- -- Spec_Case - if this parameter is set, its value is set as the -- value of the Special_Case field of the result Element. Otherwise -- the value of the Special_Case field of the result Element is set -- from Starting_Element, if Starting_Element itself is set, or as -- being equal to Not_A_Special_Case, if Starting_Element is not set. -- -- Norm_Case - This parameter represents if the Element to create is a -- normalized association. It is not processed by this routine and it -- is transferred as-is to the low-level Element construction routine. -- -- Considering_Parent_Count - boolean flag indicating if the value of the -- Parent_Count field of the Node should be taken into account for the -- definition of the kind of the Asis Element to be returned by the -- function. -- -- Using_Original_Node - boolean flag indicating if the original node -- should be used as the basis of the Element being constructed. -- Usually the default True is used, but sometimes we have to -- avoid using the original node, for example, when constructing the -- expanded spec for a generic instantiation in case of a library_item -- -- Inherited - boolean flag indicating if the element being constructed -- represents a declaration of an implicit inherited subprogram or a -- subcomponent thereof. -- ??? why do we need it??? -- -- In_Unit - The Asis Compilation Unit, to which the Element being -- constructed belongs. It is an error not to set both Starting_Element -- and In_Unit parameters. If both of them are set, the value of -- the Enclosing_Unit and Enclosing_Context fields of the result -- Element are set from In_Unit -- -- NOTE, that if Starting_Element is NOT set, the Is_Part_Of_Implicit and -- the Is_Part_Of_Inherited fields of the result are set off (equal to -- False), therefore the caller (that is, the implementation of the -- corresponding ASIS query) is responsible for correct setting of these -- fields. As for the Is_Part_Of_Instance field, it is set on the base of -- Sloc field of the corresponding Node. (???) -- -- An Empty node is not an expected parameter for this function. But if it -- is passed as an actual for Node, the result of the function is -- Nil_Element, independently of all the other parameters. function N_To_E_List_New (List : List_Id; Include_Pragmas : Boolean := False; Starting_Element : Asis.Element := Asis.Nil_Element; Node_Knd : Node_Kind := N_Empty; Internal_Kind : Internal_Element_Kinds := Not_An_Element; Special_Case : Special_Cases := Not_A_Special_Case; Norm_Case : Normalization_Cases := Is_Not_Normalized; In_Unit : Asis.Compilation_Unit := Asis.Nil_Compilation_Unit) return Asis.Element_List; -- This function converts tree Node list into the corresponding ASIS -- Element List. -- -- This function is intended to be used to create lists of EXPLICIT -- ASIS Elements. It checks Comes_From_Source Flag of the tree nodes from -- its List argument to test if the node should be used to create an -- Element in the result Element list -- -- The parameters have the following meaning (we say "if the parameter -- is set" with the meaning "if some actual different from the default -- nil value is passed for the parameter") -- -- List - specifies the tree node list to be converted into an ASIS -- Element List; -- -- Include_Pragmas - boolean flags signifying if pragmas should be -- included in the result list; -- -- Node_Knd - if this parameter is set, only those nodes from List -- which have this node kind are used to construct Elements in -- the result Element List; -- -- Internal_Kind - if this parameter is set, all the Elements of the -- result list are set having this kind, otherwise the kind -- of each element of the result list is determined -- automatically; -- -- Special_Case - if this parameter is set, all the Elements of the -- result list are set having this special case; -- -- Norm_Case - if this parameter is set, all the Elements of the -- result list are set having this normalization case; -- -- Starting_Element - the following fields of all the Elements in -- the result Element List are set as being equal to the -- corresponding fields of Starting_Element: -- - Enclosing_Unit (unless the In_Unit parameter is set); -- - Enclosing_Context (unless the In_Unit parameter is set); -- - Is_Part_Of_Implicit; -- - Is_Part_Of_Inherited; -- - Is_Part_Of_Instance; -- - Special_Case (unless the Special_Case parameter is set); -- Setting Starting_Element as being equal to the argument -- Element of the ASIS query where N_To_E_List is called -- to form the result of the query is the common case for the -- ASIS structural queries -- -- In_Unit - The Asis Compilation Unit, to which the Elements being -- constructed belong. It is an error not to set both -- Starting_Element and In_Unit parameters. If both of them -- are set, the value of the Enclosing_Unit and -- Enclosing_Context fields of the result Elements are set -- from In_Unit procedure Set_Element_List (List : List_Id; Include_Pragmas : Boolean := False; Starting_Element : Asis.Element := Asis.Nil_Element; Node_Knd : Node_Kind := N_Empty; Internal_Kind : Internal_Element_Kinds := Not_An_Element; Special_Case : Special_Cases := Not_A_Special_Case; Norm_Case : Normalization_Cases := Is_Not_Normalized; In_Unit : Asis.Compilation_Unit := Asis.Nil_Compilation_Unit; Append : Boolean := False); -- Does exactly the same as the function N_To_E_List_New, but places -- its result into A4G.Asis_Tables.Internal_Asis_Element_Table. -- -- If Append parameter is set ON, the list created as the result of the -- call to this procedure is appended to the current content of the -- Element Table -- -- ??? -- It seems that we will have to get rid of functions creating Element -- Lists and to build Element lists only with Element Table. Moreover, now -- N_To_E_List_New just calls Set_Element_List with Append OFF and returns -- the content of Internal_Asis_Element_Table procedure Set_Inherited_Discriminants (Type_Def : Asis.Element); -- Provided that Type_Def represents the definition of a derived -- type which may inherit discriminants, this procedure creates in -- the Element Table the list of declarations representing inherited -- discriminants. -- Note, that this function may not set properly Node_Field_1, -- Is_Part_Of_Implicit and Is_Part_Of_Inherited fields of the result -- Elements. procedure Set_Inherited_Components (Type_Def : Asis.Element; Include_Discs : Boolean := True); -- Provided that Type_Def represents the definition of a derived -- record type, this procedure creates in -- A4G.Asis_Tables.Asis_Element_Table the list of declarations representing -- inherited components. If Include_Discs parameter is set ON, this list -- also contain discriminants, otherwise it does not. That is, this -- procedure does not determine itself whether or not the discriminants are -- inherited by the type, it should be done at the caller side. -- Note, that this procedure may not set properly Node_Field_1, -- Is_Part_Of_Implicit and Is_Part_Of_Inherited fields of the result -- Elements. procedure Set_Concurrent_Inherited_Components (Type_Def : Asis.Element; Include_Discs : Boolean := True); -- Similar to the previous Set_Inherited_Components procedure, but woks -- on defininitions of derived concurrent types. procedure Set_Inherited_Literals (Type_Def : Asis.Element); -- Provided that Type_Def represents the definition of a derived -- enumeration type, this procedure creates in -- A4G.Asis_Tables.Asis_Element_Table the list of enumeration literal -- specifications representing inherited literals function Discrete_Choice_Node_To_Element_List (Choice_List : List_Id; Starting_Element : Asis.Element) return Asis.Element_List; -- This function is a special variant of the Node_To_Element_List -- function, it constructs the ASIS Element list for an Ada -- discrete_choice_list. We need a special Note-to-Element list -- constructor for discrete_choice_list, because the automatic -- determination of the ASIS kinds for the elements of the resulting -- ASIS list does not work in this case. -- -- Starting_Element has the same meaning as in general Node-to-Element -- and Node-to-Element list constructors. function Defining_Id_List_From_Normalized (N : Node_Id; From_Declaration : Asis.Element) return Asis.Defining_Name_List; -- This function constructs an (ASIS) list of A_Defining_Identifier -- ASIS Elements from a normalized sequence of one-identified -- declarations or specifications. N should be of one of the -- following kinds: -- N_Object_Declaration -- N_Number_Declaration -- N_Discriminant_Specification -- N_Component_Declaration -- N_Parameter_Specification -- N_Exception_Declaration -- N_Formal_Object_Declaration -- This function is intended to be used in the implementation of -- Asis.Declarations.Names query function Normalized_Namet_String (Node : Node_Id) return String; -- Returns the string representation of the construct representing by -- Node (assuming that Node represents some terminal Ada construct, such -- as an identifier) on the base of the information contained in the -- front-end Name Table and obtained by the value of the Chars field of -- the Node. This representation is "normalized" by capitalizing the first -- letter and every letter after underscore (except for some defining names -- from Standard, such as ASCII, for theses names all the letters are -- converted to upper case) function Ureal_Image (N : Node_Id) return String; -- Returns the string representation of a value represented by an -- N_Real_Literal node. function Is_Statement (N : Node_Id) return Boolean; -- Checks if N is a statement node. function Parenth_Count (N : Node_Id; Original_N : Node_Id) return Nat; -- This function is the same as Atree.Paren_Count, except that in case of -- the argument of a qualified expression, it decreases the level of -- parentheses to return the result corresponding to the syntax defined -- in RM 4.7(2) (see 9114-002) function Get_Next_Configuration_Pragma (N : Node_Id) return Node_Id; -- Returns the next configuration pragma node in the list. (If the argument -- is a configuration pragma node, returns the argument). If there is no -- more configuration pragmas in the list or if N is an empty node, returns -- Empty. A caller is responsible for calling this function for list -- elements only. end A4G.Mapping;
pragma Ada_2012; package body Protypo.Api.Engine_Values.Record_Wrappers is type Record_Access_Handler is new Handlers.Constant_Interface with record Pos : Record_Maps.Cursor; end record; function Read (X : Record_Access_Handler) return Engine_Value is begin return Record_Maps.Element (X.Pos); end Read; function To_Handler (Pos : Record_Maps.Cursor) return Engine_Value with Post => To_Handler'Result.Class = Constant_Handler; ---------------- -- To_Handler -- ---------------- function To_Handler (Pos : Record_Maps.Cursor) return Engine_Value is use Handlers; begin return Create (Constant_Interface_Access'(new Record_Access_Handler'(Pos => Pos))); end To_Handler; --------- -- Get -- --------- function Get (X : Record_Wrapper; Field : ID) return Handler_Value is begin if not X.Map.Contains (Field) then raise Handlers.Unknown_Field with String (Field); end if; declare Result : constant Engine_Value := X.Map (Field); begin if Result.Class in Handler_Classes then return Result; else return To_Handler (X.Map.Find (Field)); end if; end; end Get; end Protypo.Api.Engine_Values.Record_Wrappers;
-- This file was generated automatically: DO NOT MODIFY IT ! with Base_Types; use Base_Types; with TASTE_ExtendedTypes; use TASTE_ExtendedTypes; with TASTE_BasicTypes; use TASTE_BasicTypes; with UserDefs_Base_Types; use UserDefs_Base_Types; with adaasn1rtl; use adaasn1rtl; package blsclient is -- Provided interface "mot_cmd" procedure mot_cmd(cmd_val: access asn1SccBase_commands_Motion2D); pragma Export(C, mot_cmd, "blsclient_PI_mot_cmd"); end blsclient;
-- SPDX-FileCopyrightText: 2020-2021 Max Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT ------------------------------------------------------------- with Program.Element_Vectors; with Program.Element_Visitors; with Program.Elements.Call_Statements; with Program.Elements.Expressions; with Program.Elements.Function_Calls; with Program.Elements.Parameter_Associations; with Program.Elements.Record_Aggregates; with Program.Elements.Record_Component_Associations; with Program.Elements.Discrete_Ranges; with Program.Elements.Discriminant_Associations; with Program.Elements.Discriminant_Constraints; with Program.Elements.Index_Constraints; with Program.Lexical_Elements; package Program.Nodes.Proxy_Calls is pragma Preelaborate; type Proxy_Call is new Program.Nodes.Node and Program.Elements.Call_Statements.Call_Statement and Program.Elements.Call_Statements.Call_Statement_Text and Program.Elements.Function_Calls.Function_Call and Program.Elements.Function_Calls.Function_Call_Text and Program.Elements.Discriminant_Constraints.Discriminant_Constraint and Program.Elements.Index_Constraints.Index_Constraint and Program.Elements.Record_Aggregates.Record_Aggregate with private; -- Internal common representation of -- * Call_Statement -- * Function_Call -- * Record_Aggregate -- * Discriminant_Constraint -- * TODO Function_Call, Slice, Type_Conv, etc type Proxy_Call_Access is access all Proxy_Call; function Create (Called_Name : Program.Elements.Expressions.Expression_Access; Left_Bracket_Token : Program.Lexical_Elements.Lexical_Element_Access; Parameters : Program.Element_Vectors.Element_Vector_Access; Right_Bracket_Token : Program.Lexical_Elements.Lexical_Element_Access) return Proxy_Call; -- Return Proxy_Call configured as a record_aggregate procedure Turn_To_Function_Call (Self : in out Proxy_Call'Class; Called_Name : not null Program.Elements.Expressions.Expression_Access); procedure Turn_To_Procedure_Call (Self : in out Proxy_Call'Class; Semicolon_Token : Program.Lexical_Elements.Lexical_Element_Access); procedure Turn_To_Discriminant_Constraint (Self : in out Proxy_Call'Class; Mark : out Program.Elements.Expressions.Expression_Access); procedure Turn_To_Index_Constraint (Self : in out Proxy_Call'Class); function Can_Be_Parenthesized_Expression (Self : Proxy_Call'Class) return Boolean; procedure Turn_To_Parenthesized_Expression (Self : in out Proxy_Call'Class); private type Kind is (A_Call_Statement, A_Function_Call, A_Discriminant_Constraint, An_Index_Constraint, A_Record_Aggregate); type Proxy_Call_Text (Parent : not null Proxy_Call_Access) is new Program.Elements.Record_Aggregates.Record_Aggregate_Text and Program.Elements.Discriminant_Constraints.Discriminant_Constraint_Text and Program.Elements.Index_Constraints.Index_Constraint_Text with null record; type Base_Vector (Parent : not null Proxy_Call_Access) is abstract new Program.Element_Vectors.Element_Vector with null record; overriding function Get_Length (Self : Base_Vector) return Positive; overriding function Delimiter (Self : Base_Vector; Index : Positive) return Program.Lexical_Elements.Lexical_Element_Access; type Parameter_Vector is new Base_Vector and Program.Elements.Parameter_Associations.Parameter_Association_Vector with null record; overriding function Element (Self : Parameter_Vector; Index : Positive) return not null Program.Elements.Element_Access; type Discriminant_Association_Vector is new Base_Vector and Program.Elements.Discriminant_Associations .Discriminant_Association_Vector with null record; overriding function Element (Self : Discriminant_Association_Vector; Index : Positive) return not null Program.Elements.Element_Access; type Record_Component_Association_Vector is new Base_Vector and Program.Elements.Record_Component_Associations .Record_Component_Association_Vector with null record; overriding function Element (Self : Record_Component_Association_Vector; Index : Positive) return not null Program.Elements.Element_Access; type Discrete_Range_Vector is new Base_Vector and Program.Elements.Discrete_Ranges.Discrete_Range_Vector with null record; overriding function Element (Self : Discrete_Range_Vector; Index : Positive) return not null Program.Elements.Element_Access; type Proxy_Call is new Program.Nodes.Node and Program.Elements.Call_Statements.Call_Statement and Program.Elements.Call_Statements.Call_Statement_Text and Program.Elements.Function_Calls.Function_Call and Program.Elements.Function_Calls.Function_Call_Text and Program.Elements.Discriminant_Constraints.Discriminant_Constraint and Program.Elements.Index_Constraints.Index_Constraint and Program.Elements.Record_Aggregates.Record_Aggregate with record This : Proxy_Call_Access := Proxy_Call'Unchecked_Access; -- to get r/w access from constant Self parameter Current : Kind; Text : aliased Proxy_Call_Text (Proxy_Call'Unchecked_Access); Called_Name : Program.Elements.Expressions.Expression_Access; Elements : Program.Element_Vectors.Element_Vector_Access; Components : aliased Record_Component_Association_Vector (Proxy_Call'Unchecked_Access); Parameters : aliased Parameter_Vector (Proxy_Call'Unchecked_Access); Discr : aliased Discriminant_Association_Vector (Proxy_Call'Unchecked_Access); Ranges : aliased Discrete_Range_Vector (Proxy_Call'Unchecked_Access); Left_Bracket_Token : Program.Lexical_Elements.Lexical_Element_Access; Right_Bracket_Token : Program.Lexical_Elements.Lexical_Element_Access; Semicolon_Token : Program.Lexical_Elements.Lexical_Element_Access; end record; overriding procedure Visit (Self : not null access Proxy_Call; Visitor : in out Program.Element_Visitors.Element_Visitor'Class); overriding function Called_Name (Self : Proxy_Call) return not null Program.Elements.Expressions.Expression_Access; overriding function Parameters (Self : Proxy_Call) return Program.Elements.Parameter_Associations .Parameter_Association_Vector_Access; overriding function Is_Call_Statement (Self : Proxy_Call) return Boolean; overriding function Is_Statement (Self : Proxy_Call) return Boolean; overriding function To_Call_Statement_Text (Self : in out Proxy_Call) return Program.Elements.Call_Statements.Call_Statement_Text_Access; overriding function Left_Bracket_Token (Self : Proxy_Call) return Program.Lexical_Elements.Lexical_Element_Access; overriding function Right_Bracket_Token (Self : Proxy_Call) return Program.Lexical_Elements.Lexical_Element_Access; overriding function Semicolon_Token (Self : Proxy_Call) return not null Program.Lexical_Elements.Lexical_Element_Access; -- function call overriding function Prefix (Self : Proxy_Call) return not null Program.Elements.Expressions.Expression_Access; overriding function Is_Function_Call (Self : Proxy_Call) return Boolean; overriding function To_Function_Call_Text (Self : in out Proxy_Call) return Program.Elements.Function_Calls.Function_Call_Text_Access; -- Record aggregate overriding function Components (Self : Proxy_Call) return Program.Elements.Record_Component_Associations .Record_Component_Association_Vector_Access; overriding function Is_Record_Aggregate (Self : Proxy_Call) return Boolean; overriding function Is_Expression (Self : Proxy_Call) return Boolean; overriding function To_Record_Aggregate_Text (Self : in out Proxy_Call) return Program.Elements.Record_Aggregates.Record_Aggregate_Text_Access; overriding function Left_Bracket_Token (Self : Proxy_Call_Text) return not null Program.Lexical_Elements.Lexical_Element_Access; overriding function Right_Bracket_Token (Self : Proxy_Call_Text) return not null Program.Lexical_Elements.Lexical_Element_Access; -- Discriminant constraint overriding function Is_Definition (Self : Proxy_Call) return Boolean; overriding function Is_Constraint (Self : Proxy_Call) return Boolean; overriding function Is_Discriminant_Constraint (Self : Proxy_Call) return Boolean; overriding function Discriminants (Self : Proxy_Call) return not null Program.Elements.Discriminant_Associations .Discriminant_Association_Vector_Access; overriding function To_Discriminant_Constraint_Text (Self : in out Proxy_Call) return Program.Elements.Discriminant_Constraints .Discriminant_Constraint_Text_Access; -- Index constraint overriding function Is_Index_Constraint (Self : Proxy_Call) return Boolean; overriding function Ranges (Self : Proxy_Call) return not null Program.Elements.Discrete_Ranges .Discrete_Range_Vector_Access; overriding function To_Index_Constraint_Text (Self : in out Proxy_Call) return Program.Elements.Index_Constraints.Index_Constraint_Text_Access; end Program.Nodes.Proxy_Calls;
package body MOS is -- Load Program into Memory procedure Load_Program_Into_Memory(This : in out MOS_T; Program_Path : in String) is Program_Length : Short_T := Get_Program_Length(Program_Path); Program : Program_T := Read_File(Program_Path, Program_Length); I : Short_T := This.PC; begin for J in Program'Range loop This.Mem(I+J) := Program(J); end loop; end Load_Program_Into_Memory; procedure Print_Status(This : in MOS_T) is begin Put_Line("=== Status ==="); Put_Register("A", Integer(This.A)); Put_Register("X", Integer(This.X)); Put_Register("Y", Integer(This.Y)); Put_Register("PC", Integer(This.PC)); Put_Register("S", Integer(This.S)); Print_Memory(This, This.PC-2, This.PC+2); Put_Line("=== End ==="); end Print_Status; function Get_Program_Length(File_Name : String) return Short_T is File : File_Type; I : Short_T := 0; s : Unbounded_String; begin Open(File => File, Mode => In_File, Name => File_Name); loop exit when End_Of_File (File); s := To_Unbounded_String(Get_Line (File)); I := I + 1; end loop; Close (File); return I; end; function Read_File(File_Name : String; Program_Length : Short_T) return Program_T is File : File_Type; Program : Program_T(0..Program_Length) := (others => 0); s : Unbounded_String; I : Short_T := 0; begin Open(File => File, Mode => In_File, Name => File_Name); Put("Opened"); New_Line; Put(Integer(MOS_MAX_PROGRAM_SIZE-1)); New_Line; loop exit when End_Of_File (File); s := To_Unbounded_String(Get_Line (File)); Put(Integer(I)); Put_Hex(Integer'Value(To_String(s))); New_Line; Program(I) := Byte_T(Integer'Value(To_String(s))); I := I + 1; end loop; Close (File); return Program; end Read_File; -- Print Memory from IntervalStart to Interval End procedure Print_Memory (This : in MOS_T; Interval_Start : in Short_T; Interval_End : in Short_T) is begin for K in Interval_Start..Interval_End loop Put("Mem["); Put_Hex(Integer(K)); Put("] = "); Put_Hex(Integer(This.Mem(K))); New_Line; end loop; end Print_Memory; procedure Put_Hex(Num : in Integer) is begin Put(Num, Base => 16); end Put_Hex; procedure Put_Register(Name : in String; Val : in Integer) is begin Put(Name); Put_Hex(Val); New_Line; end Put_Register; end MOS;
-- SET10112 2018-9 TR2 001 - Formal Approaches to Software Engineering -- Trident - Submarine Coursework -- Version 0.3.1 -- Alexander Barker -- 40333139 -- Last Updated on 19th April 2019 -- main.adb with Trident; use Trident; with Ada.Text_IO; use Ada.Text_IO; procedure Main is begin Put_Line("--------------------------------------------------------"); Put_Line(" ___ _ _ "); Put_Line(" / __|_ _| |__ _ __ __ _ _ _(_)_ _ ___ "); Put_Line(" \__ \ || | '_ \ ' \/ _` | '_| | ' \/ -_) "); Put_Line(" |___/\_,_|_.__/_|_|_\__,_|_| |_|_||_\___| "); Put_Line(" ___ _ _ ___ _ "); Put_Line(" / __|___ _ _| |_ _ _ ___| | / __|_ _ __| |_ ___ _ __ "); Put_Line("| (__/ _ \ ' \ _| '_/ _ \ | \__ \ || (_-< _/ -_) ' \ "); Put_Line(" \___\___/_||_\__|_| \___/_| |___/\_, /__/\__\___|_|_|_|"); Put_Line(" |__/ "); Put_Line("--------------------------------------------------------"); Put_Line("Attempting to Start Submarine..."); OperateSubmarine; Put("Is Nuclear Submarine Operational?: "); Put_Line(TridentSubmarine.operating'Image); Put("Is Weapons System Available?: "); WeaponsSystemCheck; Put_Line(TridentSubmarine.WeaponsAvailablity'Image); Put_Line("---------------------------------------------------"); Put("Airlock Door One is: "); Put_Line(TridentSubmarine.CloseAirlockOne'Image); Put("Airlock Door Two is: "); Put_Line(TridentSubmarine.CloseAirlockTwo'Image); Put_Line("---------------------------------------------------"); Put_Line("Attempting to Open both Doors..."); OpenAirlockTwo; Put("Airlock Door One is: "); Put_Line(TridentSubmarine.CloseAirlockOne'Image); Put("Airlock Door Two is: "); Put_Line(TridentSubmarine.CloseAirlockTwo'Image); Put_Line("---------------------------------------------------"); Put_Line("Closing Airlock Door One..."); CloseAirlockOne; Put("Airlock Door One is: "); Put_Line(TridentSubmarine.CloseAirlockOne'Image); Put_Line("Closing Airlock Door Two..."); CloseAirlockTwo; Put("Airlock Door Two is: "); Put_Line(TridentSubmarine.CloseAirlockTwo'Image); Put_Line("---------------------------------------------------"); Put("Is Nuclear Submarine Operational?: "); OperateSubmarine; Put_Line(TridentSubmarine.operating'Image); Put("Is Weapons System Available?: "); WeaponsSystemCheck; Put_Line(TridentSubmarine.WeaponsAvailablity'Image); Put_Line("---------------------------------------------------"); Put("Airlock Door one lock is: "); Put_Line(TridentSubmarine.LockAirlockOne'Image); Put("Airlock Door two lock is: "); Put_Line(TridentSubmarine.LockAirlockTwo'Image); Put_Line("---------------------------------------------------"); Put_Line("Locking both Airlock Doors"); LockAirlockOne; LockAirlockTwo; Put("Airlock Door One is: "); Put_Line(TridentSubmarine.LockAirlockOne'Image); Put("Airlock Door Two is: "); Put_Line(TridentSubmarine.LockAirlockTwo'Image); Put_Line("---------------------------------------------------"); Put_Line("Attempting to Open Airlock Door One..."); OpenAirlockOne; Put("Status of Airlock Door one: "); Put(TridentSubmarine.CloseAirlockOne'Image); Put(" and "); Put_Line(TridentSubmarine.LockAirlockOne'Image); Put_Line("Attempting to Open Airlock Door Two..."); OpenAirlockTwo; Put("Status of Airlock Door Two: "); Put(TridentSubmarine.CloseAirlockTwo'Image); Put(" and "); Put_Line(TridentSubmarine.LockAirlockTwo'Image); Put_Line("---------------------------------------------------"); Put("Is Nuclear Submarine Operational?: "); OperateSubmarine; Put_Line(TridentSubmarine.operating'Image); Put("Is Weapons System Available?: "); WeaponsSystemCheck; Put_Line(TridentSubmarine.WeaponsAvailablity'Image); Put_Line("---------------------------------------------------"); Put("Is Weapons System Ready to Fire?: "); ReadyToFire; Put_Line(TridentSubmarine.loaded'Image); Put_Line("Attempting to Store Torpedoes..."); Store; Put(TridentSubmarine.storedTorpedoes'Image); Put(" Torpedo: "); Put_Line(TridentSubmarine.torpedoes'Image); Store; Put(TridentSubmarine.storedTorpedoes'Image); Put(" Torpedo: "); Put_Line(TridentSubmarine.torpedoes'Image); Store; Put(TridentSubmarine.storedTorpedoes'Image); Put(" Torpedo: "); Put_Line(TridentSubmarine.torpedoes'Image); Store; Put(TridentSubmarine.storedTorpedoes'Image); Put(" Torpedo: "); Put_Line(TridentSubmarine.torpedoes'Image); Store; Put(TridentSubmarine.storedTorpedoes'Image); Put(" Torpedo: "); Put_Line(TridentSubmarine.torpedoes'Image); Store; Put(TridentSubmarine.storedTorpedoes'Image); Put(" Torpedo: "); Put_Line(TridentSubmarine.torpedoes'Image); Put_Line("---------------------------------------------------"); Put("Is Weapons System Ready to Fire?: "); Put_Line(TridentSubmarine.loadedTorpedoes'Image); Put("Number of Torpedoes Stored: "); Put_Line(TridentSubmarine.torpedoes'Image); Put_Line("---------------------------------------------------"); -- One; Put_Line("Attempting to Load Torpedo..."); Load; Put("Loading Torpedo: "); Put_Line(TridentSubmarine.loaded'Image); Put_Line("Attempting to Fire Torpedo..."); Put("Is Weapons System Ready to Fire?: "); Put_Line(TridentSubmarine.loadedTorpedoes'Image); Fire; Put(TridentSubmarine.firingTorpedoes'Image); Put(" Torpedo! Remaining "); Put_Line(TridentSubmarine.torpedoes'Image); Put_Line("---------------------------------------------------"); -- Two; Put_Line("Attempting to Load Torpedo..."); Load; Put("Loading Torpedo: "); Put_Line(TridentSubmarine.loaded'Image); Put_Line("Attempting to Fire Torpedo..."); Put("Is Weapons System Ready to Fire?: "); Put_Line(TridentSubmarine.loadedTorpedoes'Image); Fire; Put(TridentSubmarine.firingTorpedoes'Image); Put(" Torpedo! Remaining "); Put_Line(TridentSubmarine.torpedoes'Image); Put_Line("---------------------------------------------------"); -- Three; Put_Line("Attempting to Load Torpedo..."); Load; Put("Loading Torpedo: "); Put_Line(TridentSubmarine.loaded'Image); Put_Line("Attempting to Fire Torpedo..."); Put("Is Weapons System Ready to Fire?: "); Put_Line(TridentSubmarine.loadedTorpedoes'Image); Fire; Put(TridentSubmarine.firingTorpedoes'Image); Put(" Torpedo! Remaining "); Put_Line(TridentSubmarine.torpedoes'Image); Put_Line("---------------------------------------------------"); -- Four; Put_Line("Attempting to Load Torpedo..."); Load; Put("Loading Torpedo: "); Put_Line(TridentSubmarine.loaded'Image); Put_Line("Attempting to Fire Torpedo..."); Put("Is Weapons System Ready to Fire?: "); Put_Line(TridentSubmarine.loadedTorpedoes'Image); Fire; Put(TridentSubmarine.firingTorpedoes'Image); Put(" Torpedo! Remaining "); Put_Line(TridentSubmarine.torpedoes'Image); Put_Line("---------------------------------------------------"); -- Five; Put_Line("Attempting to Load Torpedo..."); Load; Put("Loading Torpedo: "); Put_Line(TridentSubmarine.loaded'Image); Put_Line("Attempting to Fire Torpedo..."); Put("Is Weapons System Ready to Fire?: "); Put_Line(TridentSubmarine.loadedTorpedoes'Image); Fire; Put(TridentSubmarine.firingTorpedoes'Image); Put(" Torpedo! Remaining "); Put_Line(TridentSubmarine.torpedoes'Image); Put_Line("---------------------------------------------------"); -- Six; Put_Line("Attempting to Load Torpedo..."); Load; Put("Loading Torpedo: "); Put_Line(TridentSubmarine.loaded'Image); Put_Line("Attempting to Fire Torpedo..."); Put("Is Weapons System Ready to Fire?: "); Put_Line(TridentSubmarine.loadedTorpedoes'Image); Fire; Put(TridentSubmarine.firingTorpedoes'Image); Put(" Torpedo! Remaining "); Put_Line(TridentSubmarine.torpedoes'Image); Put_Line("---------------------------------------------------"); Put_Line("Attempting to Dive!"); Put("Depth Status: "); DepthPosition; Put_Line(TridentSubmarine.depthPositionCheck'Image); DepthTest; Put(TridentSubmarine.diveOperational'Image); Put(" at "); Put(TridentSubmarine.depthRange'Image); Put_Line(" metres..."); Put_Line("---------------------------------------------------"); DiveCheck; Put(TridentSubmarine.diveOperational'Image); Put(" from "); Put(TridentSubmarine.depthRange'Image); Put_Line(" metres..."); Put("Depth Status: "); DepthPosition; Put_Line(TridentSubmarine.depthPositionCheck'Image); DepthTest; Put(TridentSubmarine.diveOperational'Image); Put(" from "); Put(TridentSubmarine.depthRange'Image); Put_Line(" metres..."); Put("Depth Status: "); DepthPosition; Put_Line(TridentSubmarine.depthPositionCheck'Image); DepthTest; Put(TridentSubmarine.diveOperational'Image); Put(" from "); Put(TridentSubmarine.depthRange'Image); Put_Line(" metres..."); Put("Depth Status: "); DepthPosition; Put_Line(TridentSubmarine.depthPositionCheck'Image); DepthTest; Put(TridentSubmarine.diveOperational'Image); Put(" from "); Put(TridentSubmarine.depthRange'Image); Put_Line(" metres..."); Put("Depth Status: "); DepthPosition; Put_Line(TridentSubmarine.depthPositionCheck'Image); DepthTest; Put(TridentSubmarine.diveOperational'Image); Put(" from "); Put(TridentSubmarine.depthRange'Image); Put_Line(" metres..."); Put("Depth Status: "); DepthPosition; Put_Line(TridentSubmarine.depthPositionCheck'Image); Put_Line("---------------------------------------------------"); Put_Line("Resurfacing..."); EmergencySurface; Put("Depth Status: "); DepthPosition; Put_Line(TridentSubmarine.depthPositionCheck'Image); DepthTest; Put(TridentSubmarine.diveOperational'Image); Put(" at "); Put(TridentSubmarine.depthRange'Image); Put_Line(" metres..."); Put_Line("---------------------------------------------------"); Put_Line("Attempting Life Support Check!"); DiveCheck; Put("Life Support System: "); --100 LifeSupportCheck; Put(TridentSubmarine.lifeSupportStatus'Image); Put(" - Oxygen Percentage: "); Put_Line(TridentSubmarine.oxygenRange'Image); Put("Life Support System: "); LifeSupportCheck; Put(TridentSubmarine.lifeSupportStatus'Image); OxygenTest; Put(" - Oxygen Percentage: "); Put_Line(TridentSubmarine.oxygenRange'Image); Put("Life Support System: "); --90 LifeSupportCheck; Put(TridentSubmarine.lifeSupportStatus'Image); OxygenTest; Put(" - Oxygen Percentage: "); Put_Line(TridentSubmarine.oxygenRange'Image); Put("Life Support System: "); --80 LifeSupportCheck; Put(TridentSubmarine.lifeSupportStatus'Image); OxygenTest; Put(" - Oxygen Percentage: "); Put_Line(TridentSubmarine.oxygenRange'Image); Put("Life Support System: "); --70 LifeSupportCheck; Put(TridentSubmarine.lifeSupportStatus'Image); OxygenTest; Put(" - Oxygen Percentage: "); Put_Line(TridentSubmarine.oxygenRange'Image); Put("Life Support System: "); --60 LifeSupportCheck; Put(TridentSubmarine.lifeSupportStatus'Image); OxygenTest; Put(" - Oxygen Percentage: "); Put_Line(TridentSubmarine.oxygenRange'Image); Put("Life Support System: "); --50 LifeSupportCheck; Put(TridentSubmarine.lifeSupportStatus'Image); OxygenTest; Put(" - Oxygen Percentage: "); Put_Line(TridentSubmarine.oxygenRange'Image); Put("Life Support System: "); --40 LifeSupportCheck; Put(TridentSubmarine.lifeSupportStatus'Image); OxygenTest; Put(" - Oxygen Percentage: "); Put_Line(TridentSubmarine.oxygenRange'Image); Put("Life Support System: "); --30 LifeSupportCheck; Put(TridentSubmarine.lifeSupportStatus'Image); OxygenTest; Put(" - Oxygen Percentage: "); Put_Line(TridentSubmarine.oxygenRange'Image); Put("Life Support System: "); --20 LifeSupportCheck; Put(TridentSubmarine.lifeSupportStatus'Image); OxygenTest; Put(" - Oxygen Percentage: "); Put_Line(TridentSubmarine.oxygenRange'Image); Put("Life Support System: "); --10 LifeSupportCheck; Put(TridentSubmarine.lifeSupportStatus'Image); OxygenTest; Put(" - Oxygen Percentage: "); Put_Line(TridentSubmarine.oxygenRange'Image); Put("Life Support System: "); --0 LifeSupportCheck; Put(TridentSubmarine.lifeSupportStatus'Image); OxygenTest; Put(" - Oxygen Percentage: "); Put_Line(TridentSubmarine.oxygenRange'Image); LifeSupportCheck; Put_Line(TridentSubmarine.lifeSupportStatus'Image); Put_Line("---------------------------------------------------"); Put_Line("Attempting Reactor Temperature Check!"); DiveCheck; ReactorCheck; Put_Line("---------------------------------------------------"); end Main;
GLUT 3.4 was the first release of GLUT to support an Ada language binding for SGI's Ada run-time and development environment. (With a bit of work, GLUT could probably be easily be adapted to other Ada development environments, assuming the environment already has an OpenGL binding.) To use the SGI Ada binding, please make sure that the following GNAT (SGI's Ada compiler) subsystems are installed on your system: Ada Execution-only Environment (eoe) ------------------------------------- gnat_eoe.sw.lib Ada Development Option (dev) ----------------------------- gnat_dev.bindings.GL gnat_dev.bindings.std gnat_dev.lib.src gnat_dev.lib.obj gnat_dev.sw.gnat The GLUT Ada binding was developed and tested with the IRIX 5.3 and 6.2 gnat_dev and gnat_eoe images (v3.07, built 960827). Some fairly simple GLUT examples written in Ada can be found in the progs/ada subdirectory. GLUT 3.6 expanded the number of Ada example programs included in the GLUT source code distribution. GLUT's actual Ada binding is found in the adainclude/GL subdirectory. To build the Ada binding and example programs, first build GLUT normally, then: cd adainclude/GL make glut.o cd ../../progs/ada make Good luck! - Mark Kilgard November 12, 1997
with Ada.Text_Io; use Ada.Text_Io; with Ada.Unchecked_Deallocation; with Ada.Containers.Doubly_Linked_Lists; procedure Tree_Traversal is type Node; type Node_Access is access Node; type Node is record Left : Node_Access := null; Right : Node_Access := null; Data : Integer; end record; procedure Destroy_Tree(N : in out Node_Access) is procedure free is new Ada.Unchecked_Deallocation(Node, Node_Access); begin if N.Left /= null then Destroy_Tree(N.Left); end if; if N.Right /= null then Destroy_Tree(N.Right); end if; Free(N); end Destroy_Tree; function Tree(Value : Integer; Left : Node_Access; Right : Node_Access) return Node_Access is Temp : Node_Access := new Node; begin Temp.Data := Value; Temp.Left := Left; Temp.Right := Right; return Temp; end Tree; procedure Preorder(N : Node_Access) is begin Put(Integer'Image(N.Data)); if N.Left /= null then Preorder(N.Left); end if; if N.Right /= null then Preorder(N.Right); end if; end Preorder; procedure Inorder(N : Node_Access) is begin if N.Left /= null then Inorder(N.Left); end if; Put(Integer'Image(N.Data)); if N.Right /= null then Inorder(N.Right); end if; end Inorder; procedure Postorder(N : Node_Access) is begin if N.Left /= null then Postorder(N.Left); end if; if N.Right /= null then Postorder(N.Right); end if; Put(Integer'Image(N.Data)); end Postorder; procedure Levelorder(N : Node_Access) is package Queues is new Ada.Containers.Doubly_Linked_Lists(Node_Access); use Queues; Node_Queue : List; Next : Node_Access; begin Node_Queue.Append(N); while not Is_Empty(Node_Queue) loop Next := First_Element(Node_Queue); Delete_First(Node_Queue); Put(Integer'Image(Next.Data)); if Next.Left /= null then Node_Queue.Append(Next.Left); end if; if Next.Right /= null then Node_Queue.Append(Next.Right); end if; end loop; end Levelorder; N : Node_Access; begin N := Tree(1, Tree(2, Tree(4, Tree(7, null, null), null), Tree(5, null, null)), Tree(3, Tree(6, Tree(8, null, null), Tree(9, null, null)), null)); Put("preorder: "); Preorder(N); New_Line; Put("inorder: "); Inorder(N); New_Line; Put("postorder: "); Postorder(N); New_Line; Put("level order: "); Levelorder(N); New_Line; Destroy_Tree(N); end Tree_traversal;
------------------------------------------------------------------------------ -- -- -- Simple HTTP -- -- -- -- Basic HTTP 1.1 support for API endpoints -- -- -- -- ------------------------------------------------------------------------ -- -- -- -- Copyright (C) 2021, ANNEXI-STRAYLINE Trans-Human Ltd. -- -- All rights reserved. -- -- -- -- Original Contributors: -- -- * Richard Wai (ANNEXI-STRAYLINE) -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- -- -- * Neither the name of 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 handles parsing of HTTP-schemed URIs (RFC 3986) with Ada.Strings.Bounded; with Ada.Characters.Handling; package Simple_HTTP.RFC_3986 is -- RFC 3986 1.6 function Is_alpha (Item: in Character) return Boolean renames Ada.Characters.Handling.Is_Letter; -- "ALPHA" function Is_digit (Item: in Character) return Boolean renames Ada.Characters.Handling.Is_Digit; -- "DIGIT" function Is_alphanum (Item: in Character) return Boolean renames Ada.Characters.Handling.Is_Alphanumeric; -- "ALPHA" | "DIGIT" function Is_gen_delim (Item: in Character) return Boolean is (Item in ':' | '/' | '?' | '#' | '[' | ']' | '@'); -- gen-delims function Is_sub_delim (Item: in Character) return Boolean is (Item in '!' | '$' | '&' | ''' | '(' | ')' | '*' | '+' | ',' | ';' | '='); -- sub-delims function Is_reserved (Item: in Character) return Boolean is (Is_gen_delim (Item) or else Is_sub_delim (Item)); function Is_unreserved (Item: in Character) return Boolean is (Is_alphanum (Item) or else (Item in '-' | '.' | '_' | '~')); Escape_Preamble: constant Character := '%'; ---------------- -- URI_Parser -- ---------------- -- The URI_Parser package provides facilities designed for handling URI -- inputs of an external origin, and therefore provide safe checking of -- URI syntax, avoiding the raising of exceptions on invalid input. generic with package URI_Strings is new Ada.Strings.Bounded.Generic_Bounded_Length (<>); package URI_Parser is subtype URI_String is URI_Strings.Bounded_String; type Port_Number is range 0 .. 2**16 - 1; procedure Unescape (Sequence: in out URI_String; Valid : out Boolean); -- Converts any escape codes in Sequence to their encoded Character, in- -- line. If the process is successful, the unescaped sequence is assigned -- to Sequence, and Valid is set to True. If there are any mal-formed -- escape sequences (such as "%%" or invalid hex characters), Sequence is -- not modified, and Valid is set to False procedure Scheme (URI : in URI_String; Scheme: out URI_String; Valid : out Boolean); -- Attempts to retrieve the sceme, and also normalizes it to lower-case. -- The scheme will be everything up to the first ':'. -- -- If no scheme is found, Scheme is set to Null_Bounded_String, and -- Valid is set to True. -- -- If the scheme component violates RFC 3986, Valid is set to False, and -- Scheme is set to a Null_Bounded_String. procedure Parse_Authority (URI : in URI_String; Default_Port: in Port_Number := 80; Valid : out Boolean; userinfo : out URI_String; host : out URI_String; port : out Port_Number); -- Dissects the authority portion of a URI (if present), setting the -- output parameters accordingly. -- -- The authority component is between the scheme and path. In practical -- terms, it typically looks like this: "scheme://authority/path" -- -- Sequence must be the full URI. Dissected_Authority invokes Authority -- on Sequence. -- -- If there is no authority component, userinfo and host will be set to -- Null_Bounded_String. If userinfo and host do not exist in the -- authority, the respective output parameter is set to -- Null_Bounded_String. -- -- If the URI is not valid (according to RFC 3986), Valid is set to -- False, and userinfo, host, and port are set to Null_Bounded_String. -- Parse_Authority does _full_ checking against RFC 3986. -- -- If there is no port component (including the case of "abc@xyz.net:"), -- port is set to the value given for Default_Port. The default value of -- Default_Port (80) is as specified by RFC 2616 (HTTP 1.1). function Path (Sequence: URI_String) return URI_String; -- Returns the entire path-abempty part of a URI (RFC 3986-3.3). -- This including the leading '/' (if any), but not including the first -- '?' of the query part, or '#' of the first fragment, if any. -- -- The returned path is not normalized. -- -- if the path violates RFC 3986 (Section 3), Constraint_Error is -- raised. procedure First_Query (URI : in URI_String; Query : out URI_String; Next_Query_Start: out Natural; Valid : out Boolean); -- Sets Query to the first query value, if any. This value is the text -- that follows the first '?', and extends until '&', '#', or the end of -- Sequence (exclusive). -- -- Note that RFC 3986 does not actually provision the '&' separation, -- but this is the common convention on the web, and particularily for -- APIs. -- -- If there is something incorrect about the query structure (such as a -- pattern like "&&", or query text that does not meet the requirements -- of RFC 3986, Query will be set to Null_Bounded_String, -- Next_Query_Start will be set to zero, and Value will be set to False. -- -- If there is an '&' ending the query, Next_Query_Start is the index of -- Sequence that yields the first character immediately following the -- '&', otherwise Next_Query_Start is set to zero. -- -- If there is no query (no '?'), a Null_Bounded_String is returned, -- Next_Query_Start is set to zero, and Valid is set to True. -- -- Note that any empty query (such as the sequence "?&" or "&&") -- is considered to be invalid. procedure Next_Query (URI : in URI_String; Query : out URI_String; Next_Query_Start: in out Natural; Valid : out Boolean); -- Sets Query to the next query that is expected to start at -- Next_Query_Start as set by a previous call to First_Query or -- Next_Query. -- -- If Next_Query_Start = 0, or is not in the rage of URI, Valid is set to -- False. -- -- Otherwise, the mechanics follow those of First_Query. end URI_Parser; end Simple_HTTP.RFC_3986;
-- This spec has been automatically generated from STM32L151.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with HAL; with System; package STM32_SVD.PWR is pragma Preelaborate; --------------- -- Registers -- --------------- subtype CR_PLS_Field is HAL.UInt3; subtype CR_VOS_Field is HAL.UInt2; -- power control register type CR_Register is record -- Low-power deep sleep LPSDSR : Boolean := False; -- Power down deepsleep PDDS : Boolean := False; -- Clear wakeup flag CWUF : Boolean := False; -- Clear standby flag CSBF : Boolean := False; -- Power voltage detector enable PVDE : Boolean := False; -- PVD level selection PLS : CR_PLS_Field := 16#0#; -- Disable backup domain write protection DBP : Boolean := False; -- Ultralow power mode ULP : Boolean := False; -- Fast wakeup FWU : Boolean := False; -- Voltage scaling range selection VOS : CR_VOS_Field := 16#2#; -- unspecified Reserved_13_13 : HAL.Bit := 16#0#; -- Low power run mode LPRUN : Boolean := False; -- unspecified Reserved_15_31 : HAL.UInt17 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CR_Register use record LPSDSR at 0 range 0 .. 0; PDDS at 0 range 1 .. 1; CWUF at 0 range 2 .. 2; CSBF at 0 range 3 .. 3; PVDE at 0 range 4 .. 4; PLS at 0 range 5 .. 7; DBP at 0 range 8 .. 8; ULP at 0 range 9 .. 9; FWU at 0 range 10 .. 10; VOS at 0 range 11 .. 12; Reserved_13_13 at 0 range 13 .. 13; LPRUN at 0 range 14 .. 14; Reserved_15_31 at 0 range 15 .. 31; end record; -- CSR_EWUP array type CSR_EWUP_Field_Array is array (1 .. 3) of Boolean with Component_Size => 1, Size => 3; -- Type definition for CSR_EWUP type CSR_EWUP_Field (As_Array : Boolean := False) is record case As_Array is when False => -- EWUP as a value Val : HAL.UInt3; when True => -- EWUP as an array Arr : CSR_EWUP_Field_Array; end case; end record with Unchecked_Union, Size => 3; for CSR_EWUP_Field use record Val at 0 range 0 .. 2; Arr at 0 range 0 .. 2; end record; -- power control/status register type CSR_Register is record -- Read-only. Wakeup flag WUF : Boolean := False; -- Read-only. Standby flag SBF : Boolean := False; -- Read-only. PVD output PVDO : Boolean := False; -- Read-only. Internal voltage reference (VREFINT) ready flag VREFINTRDYF : Boolean := True; -- Read-only. Voltage Scaling select flag VOSF : Boolean := False; -- Read-only. Regulator LP flag REGLPF : Boolean := False; -- unspecified Reserved_6_7 : HAL.UInt2 := 16#0#; -- Enable WKUP pin 1 EWUP : CSR_EWUP_Field := (As_Array => False, Val => 16#0#); -- unspecified Reserved_11_31 : HAL.UInt21 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CSR_Register use record WUF at 0 range 0 .. 0; SBF at 0 range 1 .. 1; PVDO at 0 range 2 .. 2; VREFINTRDYF at 0 range 3 .. 3; VOSF at 0 range 4 .. 4; REGLPF at 0 range 5 .. 5; Reserved_6_7 at 0 range 6 .. 7; EWUP at 0 range 8 .. 10; Reserved_11_31 at 0 range 11 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- Power control type PWR_Peripheral is record -- power control register CR : aliased CR_Register; -- power control/status register CSR : aliased CSR_Register; end record with Volatile; for PWR_Peripheral use record CR at 16#0# range 0 .. 31; CSR at 16#4# range 0 .. 31; end record; -- Power control PWR_Periph : aliased PWR_Peripheral with Import, Address => System'To_Address (16#40007000#); end STM32_SVD.PWR;
with Semihosting; with Ada.Real_Time; with HAL.I2C; with VL53L1X; with VL53L1X_Demo.Hardware; use VL53L1X_Demo.Hardware; procedure VL53L1X_Demo.Main is -- Override the default task stack sizes used by Cortex GNAT RTS, -- which aren't enough for this code. -- For the environment task. Environment_Task_Storage_Size : constant Natural := 3072 with Export, Convention => Ada, External_Name => "_environment_task_storage_size"; procedure Setup_Sensor (Sensor : in out VL53L1X.VL53L1X_Ranging_Sensor; Address : HAL.I2C.I2C_Address := 16#52#); -- (a) only one sensor can have a given I2C address, which -- initializes to 16#52#. Start off with all but one shut down, -- configure it to the required address, then do the rest one by -- one. -- -- (b) the address is only reset by cycling power to the device. procedure Setup_Sensor (Sensor : in out VL53L1X.VL53L1X_Ranging_Sensor; Address : HAL.I2C.I2C_Address := 16#52#) is Status : VL53L1X.Boot_Status; use type VL53L1X.Boot_Status; begin VL53L1X.Boot_Device (Sensor, Status => Status); pragma Assert (Status = VL53L1X.Ok, "couldn't boot device: " & Status'Image); VL53L1X.Set_Device_Address (Sensor, Addr => Address); VL53L1X.Sensor_Init (Sensor); Semihosting.Log_Line ("timing budget:" & VL53L1X.Get_Measurement_Budget (Sensor)'Image & ", interval:" & VL53L1X.Get_Inter_Measurement_Time (Sensor)'Image); Semihosting.Log_Line ("distance mode: " & VL53L1X.Get_Distance_Mode (Sensor)'Image); VL53L1X.Set_Distance_Mode (Sensor, Mode => VL53L1X.Short); Semihosting.Log_Line ("distance mode: " & VL53L1X.Get_Distance_Mode (Sensor)'Image); VL53L1X.Set_Distance_Mode (Sensor, Mode => VL53L1X.Long); Semihosting.Log_Line ("distance mode: " & VL53L1X.Get_Distance_Mode (Sensor)'Image); Semihosting.Log_Line ("timing budget:" & VL53L1X.Get_Measurement_Budget (Sensor)'Image & ", interval:" & VL53L1X.Get_Inter_Measurement_Time (Sensor)'Image); VL53L1X.Set_Measurement_Budget (Sensor, Budget => 500); VL53L1X.Set_Inter_Measurement_Time (Sensor, Interval => 1_500); end Setup_Sensor; begin Semihosting.Log_Line ("vl53l1x_demo"); Initialize_I2C_GPIO (Sensor_Port); Configure_I2C (Sensor_Port); Configure_Pimoroni; Configure_Polulu; Semihosting.Log_Line ("Setting up the Pimoroni breakout"); Disable_Polulu; Setup_Sensor (Pimoroni, Address => 16#50#); Semihosting.Log_Line ("Setting up the Polulu breakout"); Enable_Polulu; Setup_Sensor (Polulu, Address => 16#54#); Exercise : declare use type Ada.Real_Time.Time; -- Note, Semihosting output, being done via the debugger, -- suspends the program while the output is going on; this -- effectively stops the clock, so the program runs about 2 -- times slower overall; the exercise takes about 20 seconds. Stop_Time : constant Ada.Real_Time.Time := Ada.Real_Time.Clock + Ada.Real_Time.Seconds (10); begin VL53L1X.Start_Ranging (Pimoroni); VL53L1X.Start_Ranging (Polulu); loop exit when Ada.Real_Time.Clock >= Stop_Time; declare Breakout_Available : Data_Available; Measurement : VL53L1X.Measurement; use all type VL53L1X.Ranging_Status; begin Wait_For_Data_Available (Breakout_Available); if Breakout_Available (On_Pimoroni) then if not VL53L1X.Is_Measurement_Ready (Pimoroni) then -- Is this right? VL53L1X.Clear_Interrupt (Pimoroni); Semihosting.Log_Line ("pimoroni: not ready"); else Measurement := VL53L1X.Get_Measurement (Pimoroni); VL53L1X.Clear_Interrupt (Pimoroni); Semihosting.Log_Line ("pimoroni: distance:" & (if Measurement.Status = Ok then Measurement.Distance'Image else " ---") & ", status: " & Measurement.Status'Image); end if; end if; if Breakout_Available (On_Polulu) then if not VL53L1X.Is_Measurement_Ready (Polulu) then -- Is this right? VL53L1X.Clear_Interrupt (Polulu); Semihosting.Log_Line ("polulu: not ready"); else Measurement := VL53L1X.Get_Measurement (Polulu); VL53L1X.Clear_Interrupt (Polulu); Semihosting.Log_Line ("polulu: distance:" & (if Measurement.Status = Ok then Measurement.Distance'Image else " ---") & ", status: " & Measurement.Status'Image); end if; end if; end; end loop; end Exercise; Semihosting.Log_Line ("stopping the exercise & resetting the breakouts"); VL53L1X.Stop_Ranging (Pimoroni); VL53L1X.Stop_Ranging (Polulu); VL53L1X.Set_Device_Address (Pimoroni, 16#52#); VL53L1X.Set_Device_Address (Polulu, 16#52#); -- Now we can restart the program without having to power cycle -- the breakouts. delay until Ada.Real_Time.Time_Last; end VL53L1X_Demo.Main;
package OpenGL.Light is type Light_Index_t is (Light_0, Light_1, Light_2, Light_3, Light_4, Light_5, Light_6, Light_7); -- proc_map : glEnable procedure Enable (Index : in Light_Index_t); pragma Inline (Enable); -- proc_map : glDisable procedure Disable (Index : in Light_Index_t); pragma Inline (Disable); -- proc_map : glIsEnabled function Is_Enabled (Index : in Light_Index_t) return Boolean; pragma Inline (Is_Enabled); end OpenGL.Light;
package body Xmlhelpers is procedure Add_Node (Node_Name, Node_Value : String; Parent_Node : DOM.Core.Element; Feed : Node) is Feed_Text : Text; Feed_Data : DOM.Core.Element; begin Feed_Data := Append_Child (Parent_Node, Create_Element (Feed, Node_Name)); Feed_Text := Create_Text_Node (Feed, Node_Value); if Append_Child (Feed_Data, Feed_Text) /= null then return; end if; end Add_Node; procedure Add_Link (Parent_Node : DOM.Core.Element; Url, Relationship : String; Feed : Node) is Link_Node : DOM.Core.Element; begin Link_Node := Append_Child (Parent_Node, Create_Element (Feed, "link")); Set_Attribute (Link_Node, "rel", Relationship); Set_Attribute (Link_Node, "href", Url); end Add_Link; procedure Add_Generator (Parent_Node : DOM.Core.Element; Feed : Node) is Generator_Node : DOM.Core.Element; Feed_Text : Text; begin Generator_Node := Append_Child (Parent_Node, Create_Element (Feed, "generator")); Set_Attribute (Generator_Node, "uri", Version.Link); Set_Attribute (Generator_Node, "version", Version.Current); Feed_Text := Create_Text_Node (Feed, Version.Name); if Append_Child (Generator_Node, Feed_Text) /= null then return; end if; end Add_Generator; procedure Add_Author (Parent_Node : DOM.Core.Element; Name, Email : String; Feed : Node) is Author_Node : DOM.Core.Element; begin Author_Node := Append_Child (Parent_Node, Create_Element (Feed, "author")); if Name'Length > 0 then Add_Node ("name", Name, Author_Node, Feed); end if; if Email'Length > 0 then Add_Node ("email", Email, Author_Node, Feed); end if; end Add_Author; end Xmlhelpers;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- G N A T . E X C E P T I O N S -- -- -- -- S p e c -- -- -- -- Copyright (C) 2000-2019, AdaCore -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- This package provides an interface for raising predefined exceptions -- with an exception message. It can be used from Pure units. -- There is no prohibition in Ada that prevents exceptions being raised -- from within pure units. The raise statement is perfectly acceptable. -- However, it is not normally possible to raise an exception with a -- message because the routine Ada.Exceptions.Raise_Exception is not in -- a Pure unit. This is an annoying and unnecessary restriction and this -- package allows for raising the standard predefined exceptions at least. package GNAT.Exceptions is pragma Pure; type Exception_Type is limited null record; -- Type used to specify which exception to raise -- Really Exception_Type is Exception_Id, but Exception_Id can't be -- used directly since it is declared in the non-pure unit Ada.Exceptions, -- Exception_Id is in fact simply a pointer to the type Exception_Data -- declared in System.Standard_Library (which is also non-pure). So what -- we do is to define it here as a by reference type (any by reference -- type would do), and then Import the definitions from Standard_Library. -- Since this is a by reference type, these will be passed by reference, -- which has the same effect as passing a pointer. -- This type is not private because keeping it by reference would require -- defining it in a way (e.g. using a tagged type) that would drag in other -- run-time files, which is unwanted in the case of e.g. Ravenscar where we -- want to minimize the number of run-time files needed by default. CE : constant Exception_Type; -- Constraint_Error PE : constant Exception_Type; -- Program_Error SE : constant Exception_Type; -- Storage_Error TE : constant Exception_Type; -- Tasking_Error -- One of these constants is used in the call to specify the exception procedure Raise_Exception (E : Exception_Type; Message : String); pragma Import (Ada, Raise_Exception, "__gnat_raise_exception"); pragma No_Return (Raise_Exception); -- Raise specified exception with specified message private pragma Import (C, CE, "constraint_error"); pragma Import (C, PE, "program_error"); pragma Import (C, SE, "storage_error"); pragma Import (C, TE, "tasking_error"); -- References to the exception structures in the standard library end GNAT.Exceptions;
pragma License (Unrestricted); package Ada.Calendar is type Time is private; subtype Year_Number is Integer range 1901 .. 2399; subtype Month_Number is Integer range 1 .. 12; subtype Day_Number is Integer range 1 .. 31; subtype Day_Duration is Duration range 0.0 .. 86_400.0; function Clock return Time; function Year (Date : Time) return Year_Number; function Month (Date : Time) return Month_Number; function Day (Date : Time) return Day_Number; function Seconds (Date : Time) return Day_Duration; pragma Pure_Function (Year); pragma Pure_Function (Month); pragma Pure_Function (Day); pragma Pure_Function (Seconds); pragma Inline (Year); pragma Inline (Month); pragma Inline (Day); -- Note: Year, Month, and Day would be optimized, -- but Seconds is inefficient. procedure Split ( Date : Time; Year : out Year_Number; Month : out Month_Number; Day : out Day_Number; Seconds : out Day_Duration); function Time_Of ( Year : Year_Number; Month : Month_Number; Day : Day_Number; Seconds : Day_Duration := 0.0) return Time; function "+" (Left : Time; Right : Duration) return Time with Convention => Intrinsic; function "+" (Left : Duration; Right : Time) return Time with Convention => Intrinsic; function "-" (Left : Time; Right : Duration) return Time with Convention => Intrinsic; function "-" (Left : Time; Right : Time) return Duration with Convention => Intrinsic; pragma Pure_Function ("+"); pragma Pure_Function ("-"); pragma Inline_Always ("+"); pragma Inline_Always ("-"); function "<" (Left, Right : Time) return Boolean with Import, Convention => Intrinsic; function "<=" (Left, Right : Time) return Boolean with Import, Convention => Intrinsic; function ">" (Left, Right : Time) return Boolean with Import, Convention => Intrinsic; function ">=" (Left, Right : Time) return Boolean with Import, Convention => Intrinsic; Time_Error : exception; private type Time is new Duration; -- 0 = 2150-01-01 00:00:00 end Ada.Calendar;
with Ada.Containers.Doubly_Linked_Lists; with Ada.Text_Io; use Ada.Text_Io; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; procedure List_Insertion is package String_List is new Ada.Containers.Doubly_Linked_Lists(Unbounded_String); use String_List; procedure Print(Position : Cursor) is begin Put_Line(To_String(Element(Position))); end Print; The_List : List; begin The_List.Append(To_Unbounded_String("A")); The_List.Append(To_Unbounded_String("B")); The_List.Insert(Before => The_List.Find(To_Unbounded_String("B")), New_Item => To_Unbounded_String("C")); The_List.Iterate(Print'access); end List_Insertion;
with reg; package body pinconfig is use type reg.Word; procedure Enable_Input (Pin : in Pin_ID; Mode : in Input_Mode) is begin case Pin is when Pin_2 => reg.RCC_AHB1ENR := reg.RCC_AHB1ENR or 2#10_0000#; -- bit 5 reg.GPIOF_MODER := reg.GPIOF_MODER and 2#0011_1111_1111_1111_1111_1111_1111_1111#; -- bits 30-31 if Mode = Pulled_Up then reg.GPIOF_PUPDR := (reg.GPIOF_PUPDR and 2#0011_1111_1111_1111_1111_1111_1111_1111#) or 2#0100_0000_0000_0000_0000_0000_0000_0000#; else reg.GPIOF_PUPDR := reg.GPIOF_PUPDR and 2#0011_1111_1111_1111_1111_1111_1111_1111#; end if; when Pin_3 => reg.RCC_AHB1ENR := reg.RCC_AHB1ENR or 2#1_0000#; -- bit 4 reg.GPIOE_MODER := reg.GPIOE_MODER and 2#1111_0011_1111_1111_1111_1111_1111_1111#; -- bits 26-27 if Mode = Pulled_Up then reg.GPIOE_PUPDR := (reg.GPIOE_PUPDR and 2#1111_0011_1111_1111_1111_1111_1111_1111#) or 2#0000_0100_0000_0000_0000_0000_0000_0000#; else reg.GPIOE_PUPDR := reg.GPIOE_PUPDR and 2#1111_0011_1111_1111_1111_1111_1111_1111#; end if; when Pin_4 => reg.RCC_AHB1ENR := reg.RCC_AHB1ENR or 2#10_0000#; -- bit 5 reg.GPIOF_MODER := reg.GPIOF_MODER and 2#1100_1111_1111_1111_1111_1111_1111_1111#; -- bits 28-29 if Mode = Pulled_Up then reg.GPIOF_PUPDR := (reg.GPIOF_PUPDR and 2#1100_1111_1111_1111_1111_1111_1111_1111#) or 2#0001_0000_0000_0000_0000_0000_0000_0000#; else reg.GPIOF_PUPDR := reg.GPIOF_PUPDR and 2#1100_1111_1111_1111_1111_1111_1111_1111#; end if; when Pin_5 => reg.RCC_AHB1ENR := reg.RCC_AHB1ENR or 2#1_0000#; -- bit 4 reg.GPIOE_MODER := reg.GPIOE_MODER and 2#1111_1111_0011_1111_1111_1111_1111_1111#; -- bits 22-23 if Mode = Pulled_Up then reg.GPIOE_PUPDR := (reg.GPIOE_PUPDR and 2#1111_1111_0011_1111_1111_1111_1111_1111#) or 2#0000_0000_0100_0000_0000_0000_0000_0000#; else reg.GPIOE_PUPDR := reg.GPIOE_PUPDR and 2#1111_1111_0011_1111_1111_1111_1111_1111#; end if; when Pin_6 => reg.RCC_AHB1ENR := reg.RCC_AHB1ENR or 2#1_0000#; -- bit 4 reg.GPIOE_MODER := reg.GPIOE_MODER and 2#1111_1111_1111_0011_1111_1111_1111_1111#; -- bits 18-19 if Mode = Pulled_Up then reg.GPIOE_PUPDR := (reg.GPIOE_PUPDR and 2#1111_1111_1111_0011_1111_1111_1111_1111#) or 2#0000_0000_0000_0100_0000_0000_0000_0000#; else reg.GPIOE_PUPDR := reg.GPIOE_PUPDR and 2#1111_1111_1111_0011_1111_1111_1111_1111#; end if; when Pin_7 => reg.RCC_AHB1ENR := reg.RCC_AHB1ENR or 2#10_0000#; -- bit 5 reg.GPIOF_MODER := reg.GPIOF_MODER and 2#1111_0011_1111_1111_1111_1111_1111_1111#; -- bits 26-27 if Mode = Pulled_Up then reg.GPIOF_PUPDR := (reg.GPIOF_PUPDR and 2#1111_0011_1111_1111_1111_1111_1111_1111#) or 2#0000_0100_0000_0000_0000_0000_0000_0000#; else reg.GPIOF_PUPDR := reg.GPIOF_PUPDR and 2#1111_0011_1111_1111_1111_1111_1111_1111#; end if; when Pin_8 => reg.RCC_AHB1ENR := reg.RCC_AHB1ENR or 2#10_0000#; -- bit 5 reg.GPIOF_MODER := reg.GPIOF_MODER and 2#1111_1100_1111_1111_1111_1111_1111_1111#; -- bits 24-25 if Mode = Pulled_Up then reg.GPIOF_PUPDR := (reg.GPIOF_PUPDR and 2#1111_1100_1111_1111_1111_1111_1111_1111#) or 2#0000_0001_0000_0000_0000_0000_0000_0000#; else reg.GPIOF_PUPDR := reg.GPIOF_PUPDR and 2#1111_1100_1111_1111_1111_1111_1111_1111#; end if; when Pin_9 => reg.RCC_AHB1ENR := reg.RCC_AHB1ENR or 2#1000#; -- bit 3 reg.GPIOD_MODER := reg.GPIOD_MODER and 2#0011_1111_1111_1111_1111_1111_1111_1111#; -- bit pair 30-31 if Mode = Pulled_Up then reg.GPIOD_PUPDR := (reg.GPIOD_PUPDR and 2#0011_1111_1111_1111_1111_1111_1111_1111#) or 2#0100_0000_0000_0000_0000_0000_0000_0000#; else reg.GPIOD_PUPDR := reg.GPIOD_PUPDR and 2#0011_1111_1111_1111_1111_1111_1111_1111#; end if; when Pin_10 => reg.RCC_AHB1ENR := reg.RCC_AHB1ENR or 2#1000#; -- bit 3 reg.GPIOD_MODER := reg.GPIOD_MODER and 2#1100_1111_1111_1111_1111_1111_1111_1111#; -- bit pair 28-29 if Mode = Pulled_Up then reg.GPIOD_PUPDR := (reg.GPIOD_PUPDR and 2#1100_1111_1111_1111_1111_1111_1111_1111#) or 2#0001_0000_0000_0000_0000_0000_0000_0000#; else reg.GPIOD_PUPDR := reg.GPIOD_PUPDR and 2#1100_1111_1111_1111_1111_1111_1111_1111#; end if; when Pin_11 => reg.RCC_AHB1ENR := reg.RCC_AHB1ENR or 2#1#; -- bit 0 reg.GPIOA_MODER := reg.GPIOA_MODER and 2#1111_1111_1111_1111_0011_1111_1111_1111#; -- bit pair 14-15 if Mode = Pulled_Up then reg.GPIOA_PUPDR := (reg.GPIOA_PUPDR and 2#1111_1111_1111_1111_0011_1111_1111_1111#) or 2#0000_0000_0000_0000_0100_0000_0000_0000#; else reg.GPIOA_PUPDR := reg.GPIOA_PUPDR and 2#1111_1111_1111_1111_0011_1111_1111_1111#; end if; when Pin_12 => reg.RCC_AHB1ENR := reg.RCC_AHB1ENR or 2#1#; -- bit 0 reg.GPIOA_MODER := reg.GPIOA_MODER and 2#1111_1111_1111_1111_1100_1111_1111_1111#; -- bit pair 12-13 if Mode = Pulled_Up then reg.GPIOA_PUPDR := (reg.GPIOA_PUPDR and 2#1111_1111_1111_1111_1100_1111_1111_1111#) or 2#0000_0000_0000_0000_0001_0000_0000_0000#; else reg.GPIOA_PUPDR := reg.GPIOA_PUPDR and 2#1111_1111_1111_1111_1100_1111_1111_1111#; end if; when Pin_13 => reg.RCC_AHB1ENR := reg.RCC_AHB1ENR or 2#1#; -- bit 0 reg.GPIOA_MODER := reg.GPIOA_MODER and 2#1111_1111_1111_1111_1111_0011_1111_1111#; -- bit pair 10-11 if Mode = Pulled_Up then reg.GPIOA_PUPDR := (reg.GPIOA_PUPDR and 2#1111_1111_1111_1111_1111_0011_1111_1111#) or 2#0000_0000_0000_0000_0000_0100_0000_0000#; else reg.GPIOA_PUPDR := reg.GPIOA_PUPDR and 2#1111_1111_1111_1111_1111_0011_1111_1111#; end if; end case; end Enable_Input; procedure Enable_Output (Pin : in Pin_ID) is begin case Pin is when Pin_2 => reg.RCC_AHB1ENR := reg.RCC_AHB1ENR or 2#10_0000#; -- bit 5 reg.GPIOF_MODER := (reg.GPIOF_MODER and 2#0011_1111_1111_1111_1111_1111_1111_1111#) or 2#0100_0000_0000_0000_0000_0000_0000_0000#; -- bits 30-31 when Pin_3 => reg.RCC_AHB1ENR := reg.RCC_AHB1ENR or 2#1_0000#; -- bit 4 reg.GPIOE_MODER := (reg.GPIOE_MODER and 2#1111_0011_1111_1111_1111_1111_1111_1111#) or 2#0000_0100_0000_0000_0000_0000_0000_0000#; -- bits 26-27 when Pin_4 => reg.RCC_AHB1ENR := reg.RCC_AHB1ENR or 2#10_0000#; -- bit 5 reg.GPIOF_MODER := (reg.GPIOF_MODER and 2#1100_1111_1111_1111_1111_1111_1111_1111#) or 2#0001_0000_0000_0000_0000_0000_0000_0000#; -- bits 28-29 when Pin_5 => reg.RCC_AHB1ENR := reg.RCC_AHB1ENR or 2#1_0000#; -- bit 4 reg.GPIOE_MODER := (reg.GPIOE_MODER and 2#1111_1111_0011_1111_1111_1111_1111_1111#) or 2#0000_0000_0100_0000_0000_0000_0000_0000#; -- bits 22-23 when Pin_6 => reg.RCC_AHB1ENR := reg.RCC_AHB1ENR or 2#1_0000#; -- bit 4 reg.GPIOE_MODER := (reg.GPIOE_MODER and 2#1111_1111_1111_0011_1111_1111_1111_1111#) or 2#0000_0000_0000_0100_0000_0000_0000_0000#; -- bits 18-19 when Pin_7 => reg.RCC_AHB1ENR := reg.RCC_AHB1ENR or 2#10_0000#; -- bit 5 reg.GPIOF_MODER := (reg.GPIOF_MODER and 2#1111_0011_1111_1111_1111_1111_1111_1111#) or 2#0000_0100_0000_0000_0000_0000_0000_0000#; -- bits 26-27 when Pin_8 => reg.RCC_AHB1ENR := reg.RCC_AHB1ENR or 2#10_0000#; -- bit 5 reg.GPIOF_MODER := (reg.GPIOF_MODER and 2#1111_1100_1111_1111_1111_1111_1111_1111#) or 2#0000_0001_0000_0000_0000_0000_0000_0000#; -- bits 24-25 when Pin_9 => reg.RCC_AHB1ENR := reg.RCC_AHB1ENR or 2#1000#; -- bit 3 reg.GPIOD_MODER := (reg.GPIOD_MODER and 2#0011_1111_1111_1111_1111_1111_1111_1111#) or 2#0100_0000_0000_0000_0000_0000_0000_0000#; -- bits 30-31 when Pin_10 => reg.RCC_AHB1ENR := reg.RCC_AHB1ENR or 2#1000#; -- bit 3 reg.GPIOD_MODER := (reg.GPIOD_MODER and 2#1100_1111_1111_1111_1111_1111_1111_1111#) or 2#0001_0000_0000_0000_0000_0000_0000_0000#; -- bits 28-29 when Pin_11 => reg.RCC_AHB1ENR := reg.RCC_AHB1ENR or 2#1#; -- bit 0 reg.GPIOA_MODER := (reg.GPIOA_MODER and 2#1111_1111_1111_1111_0011_1111_1111_1111#) or 2#0000_0000_0000_0000_0100_0000_0000_0000#; -- bits 14-15 when Pin_12 => reg.RCC_AHB1ENR := reg.RCC_AHB1ENR or 2#1#; -- bit 0 reg.GPIOA_MODER := (reg.GPIOA_MODER and 2#1111_1111_1111_1111_1100_1111_1111_1111#) or 2#0000_0000_0000_0000_0001_0000_0000_0000#; -- bits 12-13 when Pin_13 => reg.RCC_AHB1ENR := reg.RCC_AHB1ENR or 2#1#; -- bit 0 reg.GPIOA_MODER := (reg.GPIOA_MODER and 2#1111_1111_1111_1111_1111_0011_1111_1111#) or 2#0000_0000_0000_0000_0000_0100_0000_0000#; -- bits 10-11 end case; end Enable_Output; procedure Read (Pin : in Pin_ID; State : out Boolean) is Data : reg.Word; begin case Pin is when Pin_2 => Data := reg.GPIOF_IDR; State := (Data and 2#1000_0000_0000_0000#) /= 0; -- bit 15 when Pin_3 => Data := reg.GPIOE_IDR; State := (Data and 2#10_0000_0000_0000#) /= 0; -- bit 13 when Pin_4 => Data := reg.GPIOF_IDR; State := (Data and 2#100_0000_0000_0000#) /= 0; -- bit 14 when Pin_5 => Data := reg.GPIOE_IDR; State := (Data and 2#1000_0000_0000#) /= 0; -- bit 11 when Pin_6 => Data := reg.GPIOE_IDR; State := (Data and 2#10_0000_0000#) /= 0; -- bit 9 when Pin_7 => Data := reg.GPIOF_IDR; State := (Data and 2#10_0000_0000_0000#) /= 0; -- bit 13 when Pin_8 => Data := reg.GPIOF_IDR; State := (Data and 2#1_0000_0000_0000#) /= 0; -- bit 12 when Pin_9 => Data := reg.GPIOD_IDR; State := (Data and 2#1000_0000_0000_0000#) /= 0; -- bit 15 when Pin_10 => Data := reg.GPIOD_IDR; State := (Data and 2#100_0000_0000_0000#) /= 0; -- bit 14 when Pin_11 => Data := reg.GPIOA_IDR; State := (Data and 2#1000_0000#) /= 0; -- bit 7 when Pin_12 => Data := reg.GPIOA_IDR; State := (Data and 2#100_0000#) /= 0; -- bit 6 when Pin_13 => Data := reg.GPIOA_IDR; State := (Data and 2#10_0000#) /= 0; -- bit 5 end case; end Read; procedure Write (Pin : in Pin_ID; State : Boolean) is begin case Pin is when Pin_2 => if State then reg.GPIOF_BSRR := 2#1000_0000_0000_0000#; -- bit 15 else reg.GPIOF_BSRR := 2#1000_0000_0000_0000_0000_0000_0000_0000#; end if; when Pin_3 => if State then reg.GPIOE_BSRR := 2#10_0000_0000_0000#; -- bit 13 else reg.GPIOE_BSRR := 2#10_0000_0000_0000_0000_0000_0000_0000#; end if; when Pin_4 => if State then reg.GPIOF_BSRR := 2#100_0000_0000_0000#; -- bit 14 else reg.GPIOF_BSRR := 2#100_0000_0000_0000_0000_0000_0000_0000#; end if; when Pin_5 => if State then reg.GPIOE_BSRR := 2#1000_0000_0000#; -- bit 11 else reg.GPIOE_BSRR := 2#1000_0000_0000_0000_0000_0000_0000#; end if; when Pin_6 => if State then reg.GPIOE_BSRR := 2#10_0000_0000#; -- bit 9 else reg.GPIOE_BSRR := 2#10_0000_0000_0000_0000_0000_0000#; end if; when Pin_7 => if State then reg.GPIOF_BSRR := 2#10_0000_0000_0000#; -- bit 13 else reg.GPIOF_BSRR := 2#10_0000_0000_0000_0000_0000_0000_0000#; end if; when Pin_8 => if State then reg.GPIOF_BSRR := 2#1_0000_0000_0000#; -- bit 12 else reg.GPIOF_BSRR := 2#1_0000_0000_0000_0000_0000_0000_0000#; end if; when Pin_9 => if State then reg.GPIOD_BSRR := 2#1000_0000_0000_0000#; -- bit 15 else reg.GPIOD_BSRR := 2#1000_0000_0000_0000_0000_0000_0000_0000#; end if; when Pin_10 => if State then reg.GPIOD_BSRR := 2#100_0000_0000_0000#; -- bit 14 else reg.GPIOD_BSRR := 2#100_0000_0000_0000_0000_0000_0000_0000#; end if; when Pin_11 => if State then reg.GPIOA_BSRR := 2#1000_0000#; -- bit 7 else reg.GPIOA_BSRR := 2#1000_0000_0000_0000_0000_0000#; end if; when Pin_12 => if State then reg.GPIOA_BSRR := 2#100_0000#; -- bit 6 else reg.GPIOA_BSRR := 2#100_0000_0000_0000_0000_0000#; end if; when Pin_13 => if State then reg.GPIOA_BSRR := 2#10_0000#; -- bit 5 else reg.GPIOA_BSRR := 2#10_0000_0000_0000_0000_0000#; end if; end case; end Write; end reg;
-- This package has been generated automatically by GNATtest. -- You are allowed to add your code to the bodies of test routines. -- Such changes will be kept during further regeneration of this file. -- All code placed outside of test routine bodies will be lost. The -- code intended to set up and tear down the test environment should be -- placed into Ships.Crew.Test_Data. with AUnit.Assertions; use AUnit.Assertions; with System.Assertions; -- begin read only -- id:2.2/00/ -- -- This section can be used to add with clauses if necessary. -- -- end read only -- begin read only -- end read only package body Ships.Crew.Test_Data.Tests is -- begin read only -- id:2.2/01/ -- -- This section can be used to add global variables and other elements. -- -- end read only -- begin read only -- end read only -- begin read only function Wrap_Test_GetSkillLevel_f7e690_420873 (Member: Member_Data; SkillIndex: Skills_Amount_Range) return Skill_Range is begin begin pragma Assert(SkillIndex in 1 .. Skills_Amount); null; exception when System.Assertions.Assert_Failure => AUnit.Assertions.Assert (False, "req_sloc(ships-crew.ads:0):Test_GetSkillLevel test requirement violated"); end; declare Test_GetSkillLevel_f7e690_420873_Result: constant Skill_Range := GNATtest_Generated.GNATtest_Standard.Ships.Crew.GetSkillLevel (Member, SkillIndex); begin begin pragma Assert(True); null; exception when System.Assertions.Assert_Failure => AUnit.Assertions.Assert (False, "ens_sloc(ships-crew.ads:0:):Test_GetSkillLevel test commitment violated"); end; return Test_GetSkillLevel_f7e690_420873_Result; end; end Wrap_Test_GetSkillLevel_f7e690_420873; -- end read only -- begin read only procedure Test_GetSkillLevel_test_getskilllevel(Gnattest_T: in out Test); procedure Test_GetSkillLevel_f7e690_420873(Gnattest_T: in out Test) renames Test_GetSkillLevel_test_getskilllevel; -- id:2.2/f7e690bba6071759/GetSkillLevel/1/0/test_getskilllevel/ procedure Test_GetSkillLevel_test_getskilllevel(Gnattest_T: in out Test) is function GetSkillLevel (Member: Member_Data; SkillIndex: Skills_Amount_Range) return Skill_Range renames Wrap_Test_GetSkillLevel_f7e690_420873; -- end read only pragma Unreferenced(Gnattest_T); begin Assert (GetSkillLevel(Player_Ship.Crew(1), 1) = 0, "Failed to get real level of not owned skill."); Assert (GetSkillLevel(Player_Ship.Crew(1), 4) = 9, "Failed to get real level of skill."); -- begin read only end Test_GetSkillLevel_test_getskilllevel; -- end read only -- begin read only procedure Wrap_Test_Death_af2fea_acf44b (MemberIndex: Crew_Container.Extended_Index; Reason: Unbounded_String; Ship: in out Ship_Record; CreateBody: Boolean := True) is begin begin pragma Assert ((MemberIndex in Ship.Crew.First_Index .. Ship.Crew.Last_Index and Reason /= Null_Unbounded_String)); null; exception when System.Assertions.Assert_Failure => AUnit.Assertions.Assert (False, "req_sloc(ships-crew.ads:0):Test_Death test requirement violated"); end; GNATtest_Generated.GNATtest_Standard.Ships.Crew.Death (MemberIndex, Reason, Ship, CreateBody); begin pragma Assert(True); null; exception when System.Assertions.Assert_Failure => AUnit.Assertions.Assert (False, "ens_sloc(ships-crew.ads:0:):Test_Death test commitment violated"); end; end Wrap_Test_Death_af2fea_acf44b; -- end read only -- begin read only procedure Test_Death_test_death(Gnattest_T: in out Test); procedure Test_Death_af2fea_acf44b(Gnattest_T: in out Test) renames Test_Death_test_death; -- id:2.2/af2fea911992db88/Death/1/0/test_death/ procedure Test_Death_test_death(Gnattest_T: in out Test) is procedure Death (MemberIndex: Crew_Container.Extended_Index; Reason: Unbounded_String; Ship: in out Ship_Record; CreateBody: Boolean := True) renames Wrap_Test_Death_af2fea_acf44b; -- end read only pragma Unreferenced(Gnattest_T); Crew: constant Crew_Container.Vector := Player_Ship.Crew; Amount: constant Positive := Positive(Player_Ship.Cargo.Length); begin Death(2, To_Unbounded_String("Test death"), Player_Ship); Assert (Player_Ship.Crew.Length + 1 = Crew.Length, "Failed to remove crew member on death."); Assert (Amount + 1 = Positive(Player_Ship.Cargo.Length), "Failed to add body of dead crew member."); Player_Ship.Crew := Crew; -- begin read only end Test_Death_test_death; -- end read only -- begin read only procedure Wrap_Test_DeleteMember_9fa01a_2b7835 (MemberIndex: Crew_Container.Extended_Index; Ship: in out Ship_Record) is begin begin pragma Assert (MemberIndex in Ship.Crew.First_Index .. Ship.Crew.Last_Index); null; exception when System.Assertions.Assert_Failure => AUnit.Assertions.Assert (False, "req_sloc(ships-crew.ads:0):Test_DeleteMember test requirement violated"); end; GNATtest_Generated.GNATtest_Standard.Ships.Crew.DeleteMember (MemberIndex, Ship); begin pragma Assert(True); null; exception when System.Assertions.Assert_Failure => AUnit.Assertions.Assert (False, "ens_sloc(ships-crew.ads:0:):Test_DeleteMember test commitment violated"); end; end Wrap_Test_DeleteMember_9fa01a_2b7835; -- end read only -- begin read only procedure Test_DeleteMember_test_deletemember(Gnattest_T: in out Test); procedure Test_DeleteMember_9fa01a_2b7835(Gnattest_T: in out Test) renames Test_DeleteMember_test_deletemember; -- id:2.2/9fa01a2852ec5515/DeleteMember/1/0/test_deletemember/ procedure Test_DeleteMember_test_deletemember(Gnattest_T: in out Test) is procedure DeleteMember (MemberIndex: Crew_Container.Extended_Index; Ship: in out Ship_Record) renames Wrap_Test_DeleteMember_9fa01a_2b7835; -- end read only pragma Unreferenced(Gnattest_T); Crew: constant Crew_Container.Vector := Player_Ship.Crew; begin DeleteMember(2, Player_Ship); Assert (Crew.Length = Player_Ship.Crew.Length + 1, "Failed to delete member from the player ship crew."); Player_Ship.Crew := Crew; -- begin read only end Test_DeleteMember_test_deletemember; -- end read only -- begin read only function Wrap_Test_FindMember_b270de_fa15b4 (Order: Crew_Orders; Crew: Crew_Container.Vector := Player_Ship.Crew) return Crew_Container.Extended_Index is begin begin pragma Assert(True); null; exception when System.Assertions.Assert_Failure => AUnit.Assertions.Assert (False, "req_sloc(ships-crew.ads:0):Test_FindMember test requirement violated"); end; declare Test_FindMember_b270de_fa15b4_Result: constant Crew_Container .Extended_Index := GNATtest_Generated.GNATtest_Standard.Ships.Crew.FindMember (Order, Crew); begin begin pragma Assert (Test_FindMember_b270de_fa15b4_Result <= Crew.Last_Index); null; exception when System.Assertions.Assert_Failure => AUnit.Assertions.Assert (False, "ens_sloc(ships-crew.ads:0:):Test_FindMember test commitment violated"); end; return Test_FindMember_b270de_fa15b4_Result; end; end Wrap_Test_FindMember_b270de_fa15b4; -- end read only -- begin read only procedure Test_FindMember_test_findmember(Gnattest_T: in out Test); procedure Test_FindMember_b270de_fa15b4(Gnattest_T: in out Test) renames Test_FindMember_test_findmember; -- id:2.2/b270debda44d8b87/FindMember/1/0/test_findmember/ procedure Test_FindMember_test_findmember(Gnattest_T: in out Test) is function FindMember (Order: Crew_Orders; Crew: Crew_Container.Vector := Player_Ship.Crew) return Crew_Container.Extended_Index renames Wrap_Test_FindMember_b270de_fa15b4; -- end read only pragma Unreferenced(Gnattest_T); begin Assert (FindMember(Talk) = 1, "Failed to find crew member with selected order."); Assert (FindMember(Defend) = 0, "Failed to not find crew member with selected order."); -- begin read only end Test_FindMember_test_findmember; -- end read only -- begin read only procedure Wrap_Test_GiveOrders_fd3de0_56eedb (Ship: in out Ship_Record; MemberIndex: Crew_Container.Extended_Index; GivenOrder: Crew_Orders; ModuleIndex: Modules_Container.Extended_Index := 0; CheckPriorities: Boolean := True) is begin begin pragma Assert ((MemberIndex in Ship.Crew.First_Index .. Ship.Crew.Last_Index and ModuleIndex <= Ship.Modules.Last_Index)); null; exception when System.Assertions.Assert_Failure => AUnit.Assertions.Assert (False, "req_sloc(ships-crew.ads:0):Test_GiveOrders test requirement violated"); end; GNATtest_Generated.GNATtest_Standard.Ships.Crew.GiveOrders (Ship, MemberIndex, GivenOrder, ModuleIndex, CheckPriorities); begin pragma Assert(True); null; exception when System.Assertions.Assert_Failure => AUnit.Assertions.Assert (False, "ens_sloc(ships-crew.ads:0:):Test_GiveOrders test commitment violated"); end; end Wrap_Test_GiveOrders_fd3de0_56eedb; -- end read only -- begin read only procedure Test_GiveOrders_test_giveorders(Gnattest_T: in out Test); procedure Test_GiveOrders_fd3de0_56eedb(Gnattest_T: in out Test) renames Test_GiveOrders_test_giveorders; -- id:2.2/fd3de09254cf8892/GiveOrders/1/0/test_giveorders/ procedure Test_GiveOrders_test_giveorders(Gnattest_T: in out Test) is procedure GiveOrders (Ship: in out Ship_Record; MemberIndex: Crew_Container.Extended_Index; GivenOrder: Crew_Orders; ModuleIndex: Modules_Container.Extended_Index := 0; CheckPriorities: Boolean := True) renames Wrap_Test_GiveOrders_fd3de0_56eedb; -- end read only pragma Unreferenced(Gnattest_T); EnemyShip: Ship_Record := Create_Ship (To_Unbounded_String("2"), Null_Unbounded_String, 10, 10, FULL_SPEED); begin GiveOrders(Player_Ship, 1, Rest); Assert (Player_Ship.Crew(1).Order = Talk, "Failed to give order to player."); GiveOrders(Player_Ship, 4, Rest); Assert (Player_Ship.Crew(4).Order = Rest, "Failed to give order to gunner."); EnemyShip.Crew(1).Morale(1) := 5; GiveOrders(EnemyShip, 1, Talk); Assert(True, "This test can only crash"); -- begin read only end Test_GiveOrders_test_giveorders; -- end read only -- begin read only procedure Wrap_Test_UpdateOrders_388ab3_cad1b0 (Ship: in out Ship_Record; Combat: Boolean := False) is begin GNATtest_Generated.GNATtest_Standard.Ships.Crew.UpdateOrders (Ship, Combat); end Wrap_Test_UpdateOrders_388ab3_cad1b0; -- end read only -- begin read only procedure Test_UpdateOrders_test_updateorders(Gnattest_T: in out Test); procedure Test_UpdateOrders_388ab3_cad1b0(Gnattest_T: in out Test) renames Test_UpdateOrders_test_updateorders; -- id:2.2/388ab351ab0e26d6/UpdateOrders/1/0/test_updateorders/ procedure Test_UpdateOrders_test_updateorders(Gnattest_T: in out Test) is procedure UpdateOrders (Ship: in out Ship_Record; Combat: Boolean := False) renames Wrap_Test_UpdateOrders_388ab3_cad1b0; -- end read only pragma Unreferenced(Gnattest_T); begin GiveOrders(Player_Ship, 1, Rest, 0, False); UpdateOrders(Player_Ship); Assert (Player_Ship.Crew(1).Order = Talk, "Failed to update orders for player ship crew."); -- begin read only end Test_UpdateOrders_test_updateorders; -- end read only -- begin read only procedure Wrap_Test_UpdateMorale_5618e2_5147b1 (Ship: in out Ship_Record; MemberIndex: Crew_Container.Extended_Index; Value: Integer) is begin begin pragma Assert (MemberIndex in Ship.Crew.First_Index .. Ship.Crew.Last_Index); null; exception when System.Assertions.Assert_Failure => AUnit.Assertions.Assert (False, "req_sloc(ships-crew.ads:0):Test_UpdateMorale test requirement violated"); end; GNATtest_Generated.GNATtest_Standard.Ships.Crew.UpdateMorale (Ship, MemberIndex, Value); begin pragma Assert(True); null; exception when System.Assertions.Assert_Failure => AUnit.Assertions.Assert (False, "ens_sloc(ships-crew.ads:0:):Test_UpdateMorale test commitment violated"); end; end Wrap_Test_UpdateMorale_5618e2_5147b1; -- end read only -- begin read only procedure Test_UpdateMorale_test_updatemorale(Gnattest_T: in out Test); procedure Test_UpdateMorale_5618e2_5147b1(Gnattest_T: in out Test) renames Test_UpdateMorale_test_updatemorale; -- id:2.2/5618e2d744921821/UpdateMorale/1/0/test_updatemorale/ procedure Test_UpdateMorale_test_updatemorale(Gnattest_T: in out Test) is procedure UpdateMorale (Ship: in out Ship_Record; MemberIndex: Crew_Container.Extended_Index; Value: Integer) renames Wrap_Test_UpdateMorale_5618e2_5147b1; -- end read only pragma Unreferenced(Gnattest_T); OldMorale: constant Natural := Player_Ship.Crew(1).Morale(2); OldLevel: constant Natural := Player_Ship.Crew(1).Morale(1); begin UpdateMorale(Player_Ship, 1, 1); Assert (Player_Ship.Crew(1).Morale(2) - 1 = OldMorale or Player_Ship.Crew(1).Morale(1) - 1 = OldLevel, "Failed to raise player morale."); UpdateMorale(Player_Ship, 1, -1); Assert (Player_Ship.Crew(1).Morale(2) = OldMorale, "Failed to lower player morale."); -- begin read only end Test_UpdateMorale_test_updatemorale; -- end read only -- begin read only -- id:2.2/02/ -- -- This section can be used to add elaboration code for the global state. -- begin -- end read only null; -- begin read only -- end read only end Ships.Crew.Test_Data.Tests;
package body Int64_Parsing with SPARK_Mode is function Char_To_Int (C : Character) return Int64 is (case C is when '0' => 0, when '1' => 1, when '2' => 2, when '3' => 3, when '4' => 4, when '5' => 5, when '6' => 6, when '7' => 7, when '8' => 8, when '9' => 9, when others => raise Program_Error) with Pre => C in '0' .. '9'; subtype Digit is Int64 range 0 .. 9; function Int_To_Char (V : Digit) return Character is (case V is when 0 => '0', when 1 => '1', when 2 => '2', when 3 => '3', when 4 => '4', when 5 => '5', when 6 => '6', when 7 => '7', when 8 => '8', when 9 => '9'); procedure Parse_Int64 (S : String; V : out Int64; Error : out Boolean) is Is_Pos : constant Boolean := S'Length = 0 or else S (S'First) /= '-'; FirstZ : constant Integer := (if Is_Pos then S'First else S'First + 1); First : Integer; begin V := 0; Error := True; if FirstZ > S'Last then return; end if; First := (if FirstZ > S'Last or else S'Last - FirstZ <= 18 then FirstZ else S'Last - 18); for I in FirstZ .. First - 1 loop if S (I) /= '0' then return; end if; pragma Loop_Invariant (for all K in FirstZ .. I => S (K) = '0'); end loop; for I in 1 .. 19 loop if S (I - 1 + First) not in '0' .. '9' then return; end if; if I = 19 and then (abs (V) > Int64'Last / 10 or else (abs (V) = Int64'Last / 10 and then S (I - 1 + First) > (if Is_Pos then '7' else '8'))) then return; end if; V := V * 10 + (if Is_Pos then 1 else -1) * Char_To_Int (S (I - 1 + First)); if I - 1 + First = S'Last then Error := False; return; end if; end loop; end Parse_Int64; function Print_Int64 (V : Int64) return String is res : String (1 .. 20) := (others => '0'); X : Int64 := V; top : Natural := 20; begin if V = 0 then return "0"; end if; for I in 1 .. 19 loop res (top) := Int_To_Char (abs (X rem 10)); top := top - 1; X := X / 10; exit when X = 0; end loop; if V < 0 then res (top) := '-'; top := top - 1; end if; return (res (top + 1 .. 20)); end Print_Int64; end Int64_Parsing;
-- part of AdaYaml, (c) 2017 Felix Krause -- released under the terms of the MIT license, see the file "copying.txt" with Ada.Unchecked_Deallocation; with Yaml.Tags; package body Yaml is function Version_Major return Natural is (1); function Version_Minor return Natural is (3); function Version_Patch return Natural is (0); use type Text.Reference; function Default_Properties return Properties is ((Anchor => Text.Empty, Tag => Tags.Question_Mark)); function Is_Empty (Props : Properties) return Boolean is ((Props.Anchor = Text.Empty and then Props.Tag = Tags.Question_Mark)); function To_String (E : Event) return String is function Prop_String (A : Properties) return String is ((if A.Anchor = Text.Empty then "" else " &" & A.Anchor.Value) & (if A.Tag = Tags.Question_Mark then "" else " <" & A.Tag.Value & '>')); function Scalar_Indicator (S : Scalar_Style_Type) return String is ((case S is when Plain | Any => " :", when Single_Quoted => " '", when Double_Quoted => " """, when Literal => " |", when Folded => " >")); function Escaped (C : Text.Reference) return String is Ret : String (1 .. C.Length * 2); Pos : Positive := 1; begin for I in C.Value.Data'Range loop case C.Value.Data (I) is when Character'Val (7) => Ret (Pos .. Pos + 1) := "\a"; Pos := Pos + 2; when Character'Val (8) => Ret (Pos .. Pos + 1) := "\b"; Pos := Pos + 2; when Character'Val (9) => Ret (Pos .. Pos + 1) := "\t"; Pos := Pos + 2; when Character'Val (10) => Ret (Pos .. Pos + 1) := "\n"; Pos := Pos + 2; when Character'Val (13) => Ret (Pos .. Pos + 1) := "\r"; Pos := Pos + 2; when '\' => Ret (Pos .. Pos + 1) := "\\"; Pos := Pos + 2; when others => Ret (Pos) := C.Value.Data (I); Pos := Pos + 1; end case; end loop; return Ret (1 .. Pos - 1); end Escaped; begin case E.Kind is when Stream_Start => return "+STR"; when Stream_End => return "-STR"; when Document_Start => return "+DOC" & (if E.Implicit_Start then "" else " ---"); when Document_End => return "-DOC" & (if E.Implicit_End then "" else " ..."); when Mapping_Start => return "+MAP" & Prop_String (E.Collection_Properties); when Mapping_End => return "-MAP"; when Sequence_Start => return "+SEQ" & Prop_String (E.Collection_Properties); when Sequence_End => return "-SEQ"; when Scalar => return "=VAL" & Prop_String (E.Scalar_Properties) & Scalar_Indicator (E.Scalar_Style) & Escaped (E.Content); when Alias => return "=ALI *" & E.Target.Value; when Annotation_Start => return "+ANN" & Prop_String (E.Annotation_Properties) & ' ' & E.Namespace & E.Name; when Annotation_End => return "-ANN"; end case; end To_String; procedure Increase_Refcount (Object : not null access Refcount_Base'Class) is begin Object.Refcount := Object.Refcount + 1; end Increase_Refcount; procedure Decrease_Refcount (Object : not null access Refcount_Base'Class) is type Base_Access is access all Refcount_Base'Class; Ptr : Base_Access := Base_Access (Object); procedure Free is new Ada.Unchecked_Deallocation (Refcount_Base'Class, Base_Access); begin Ptr.Refcount := Ptr.Refcount - 1; if Ptr.Refcount = 0 then Free (Ptr); end if; end Decrease_Refcount; end Yaml;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- F N A M E . U F -- -- -- -- S p e c -- -- -- -- $Revision$ -- -- -- Copyright (C) 1992-2000 Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, -- -- MA 02111-1307, USA. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- This child package contains the routines to translate a unit name to -- a file name taking into account Source_File_Name pragmas. It also -- contains the auxiliary routines used to record data from the pragmas. -- Note: the reason we split this into a child unit is that the routines -- for unit name translation have a significant number of additional -- dependencies, including osint, and hence sdefault. There are a number -- of tools that use utility subprograms in the Fname parent, but do not -- need the functionality in this child package (and certainly do not want -- to deal with the extra dependencies). with Casing; use Casing; package Fname.UF is ----------------- -- Subprograms -- ----------------- function Get_File_Name (Uname : Unit_Name_Type; Subunit : Boolean) return File_Name_Type; -- This function returns the file name that corresponds to a given unit -- name, Uname. The Subunit parameter is set True for subunits, and -- false for all other kinds of units. The caller is responsible for -- ensuring that the unit name meets the requirements given in package -- Uname and described above. procedure Initialize; -- Initialize internal tables. This is called automatically when the -- package body is elaborated, so an explicit call to Initialize is -- only required if it is necessary to reinitialize the source file -- name pragma tables. procedure Lock; -- Lock tables before calling back end function File_Name_Of_Spec (Name : Name_Id) return File_Name_Type; -- Returns the file name that corresponds to the spec of a given unit -- name. The unit name here is not encoded as a Unit_Name_Type, but is -- rather just a normal form name in lower case, e.g. "xyz.def". function File_Name_Of_Body (Name : Name_Id) return File_Name_Type; -- Returns the file name that corresponds to the body of a given unit -- name. The unit name here is not encoded as a Unit_Name_Type, but is -- rather just a normal form name in lower case, e.g. "xyz.def". procedure Set_File_Name (U : Unit_Name_Type; F : File_Name_Type); -- Make association between given unit name, U, and the given file name, -- F. This is the routine called to process a Source_File_Name pragma. procedure Set_File_Name_Pattern (Pat : String_Ptr; Typ : Character; Dot : String_Ptr; Cas : Casing_Type); -- This is called to process a Source_File_Name pragma whose first -- argument is a file name pattern string. Pat is this pattern string, -- which contains an asterisk to correspond to the unit. Typ is one of -- 'b'/'s'/'u' for body/spec/subunit, Dot is the separator string -- for child/subunit names, and Cas is one of Lower/Upper/Mixed -- indicating the required case for the file name. end Fname.UF;
with Ada.Text_IO; use Ada.Text_IO; procedure Test is procedure P(A, A: integer) is begin New_Line; end; begin P(0,1); end;
--pragma SPARK_Mode; with Types; use Types; -- @summary -- Interface to the robot's buzzer -- -- @description -- This is not totally implemented yet. DO NOT USE!! -- package Zumo_Buzzer is -- True if the interface is init'd Initd : Boolean := False; -- Init the interface procedure Init with Pre => not Initd, Post => Initd; -- Play a note at a frequency -- @param Freq the frequency to play -- @param Dur the duration to the play the note -- @param Vol the volume to play the note procedure PlayFrequency (Freq : Frequency; Dur : Duration; Vol : Volume) with Pre => Initd; -- Play a specific note -- @param Note which note to play -- @param Dur the duration of the note to play -- @param Vol the volume of the note to play procedure PlayNote (Note : Integer; Dur : Duration; Vol : Volume) with Pre => Initd; function PlayCheck return Boolean; -- Am I currently playing a note? -- @return true if I am playing a note function IsPlaying return Boolean; -- Enough already! Stop playing loud annoying noises. procedure StopPlaying; end Zumo_Buzzer;
-- This spec has been automatically generated from STM32WB55x.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with HAL; with System; package STM32_SVD.EXTI is pragma Preelaborate; --------------- -- Registers -- --------------- subtype RTSR1_RT_Field is HAL.UInt22; type RTSR1_Register is record RT : RTSR1_RT_Field := 16#0#; -- unspecified Reserved_22_30 : HAL.UInt9 := 16#0#; RT_1 : Boolean := False; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for RTSR1_Register use record RT at 0 range 0 .. 21; Reserved_22_30 at 0 range 22 .. 30; RT_1 at 0 range 31 .. 31; end record; subtype FTSR1_FT_Field is HAL.UInt22; type FTSR1_Register is record FT : FTSR1_FT_Field := 16#0#; -- unspecified Reserved_22_30 : HAL.UInt9 := 16#0#; FT_1 : Boolean := False; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for FTSR1_Register use record FT at 0 range 0 .. 21; Reserved_22_30 at 0 range 22 .. 30; FT_1 at 0 range 31 .. 31; end record; subtype SWIER1_SWI_Field is HAL.UInt22; type SWIER1_Register is record SWI : SWIER1_SWI_Field := 16#0#; -- unspecified Reserved_22_30 : HAL.UInt9 := 16#0#; SWI_1 : Boolean := False; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for SWIER1_Register use record SWI at 0 range 0 .. 21; Reserved_22_30 at 0 range 22 .. 30; SWI_1 at 0 range 31 .. 31; end record; subtype PR1_PIF_Field is HAL.UInt22; type PR1_Register is record PIF : PR1_PIF_Field := 16#0#; -- unspecified Reserved_22_30 : HAL.UInt9 := 16#0#; PIF_1 : Boolean := False; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for PR1_Register use record PIF at 0 range 0 .. 21; Reserved_22_30 at 0 range 22 .. 30; PIF_1 at 0 range 31 .. 31; end record; subtype RTSR2_RT_Field is HAL.UInt2; type RTSR2_Register is record -- unspecified Reserved_0_0 : HAL.Bit := 16#0#; RT33 : Boolean := False; -- unspecified Reserved_2_7 : HAL.UInt6 := 16#0#; RT : RTSR2_RT_Field := 16#0#; -- unspecified Reserved_10_31 : HAL.UInt22 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for RTSR2_Register use record Reserved_0_0 at 0 range 0 .. 0; RT33 at 0 range 1 .. 1; Reserved_2_7 at 0 range 2 .. 7; RT at 0 range 8 .. 9; Reserved_10_31 at 0 range 10 .. 31; end record; subtype FTSR2_FT_Field is HAL.UInt2; type FTSR2_Register is record -- unspecified Reserved_0_0 : HAL.Bit := 16#0#; FT33 : Boolean := False; -- unspecified Reserved_2_7 : HAL.UInt6 := 16#0#; FT : FTSR2_FT_Field := 16#0#; -- unspecified Reserved_10_31 : HAL.UInt22 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for FTSR2_Register use record Reserved_0_0 at 0 range 0 .. 0; FT33 at 0 range 1 .. 1; Reserved_2_7 at 0 range 2 .. 7; FT at 0 range 8 .. 9; Reserved_10_31 at 0 range 10 .. 31; end record; subtype SWIER2_SWI_Field is HAL.UInt2; type SWIER2_Register is record -- unspecified Reserved_0_0 : HAL.Bit := 16#0#; SWI33 : Boolean := False; -- unspecified Reserved_2_7 : HAL.UInt6 := 16#0#; SWI : SWIER2_SWI_Field := 16#0#; -- unspecified Reserved_10_31 : HAL.UInt22 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for SWIER2_Register use record Reserved_0_0 at 0 range 0 .. 0; SWI33 at 0 range 1 .. 1; Reserved_2_7 at 0 range 2 .. 7; SWI at 0 range 8 .. 9; Reserved_10_31 at 0 range 10 .. 31; end record; subtype PR2_PIF_Field is HAL.UInt2; type PR2_Register is record -- unspecified Reserved_0_0 : HAL.Bit := 16#0#; PIF33 : Boolean := False; -- unspecified Reserved_2_7 : HAL.UInt6 := 16#0#; PIF : PR2_PIF_Field := 16#0#; -- unspecified Reserved_10_31 : HAL.UInt22 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for PR2_Register use record Reserved_0_0 at 0 range 0 .. 0; PIF33 at 0 range 1 .. 1; Reserved_2_7 at 0 range 2 .. 7; PIF at 0 range 8 .. 9; Reserved_10_31 at 0 range 10 .. 31; end record; subtype EMR1_EM_Field is HAL.UInt16; subtype EMR1_EM_Field_1 is HAL.UInt5; type EMR1_Register is record EM : EMR1_EM_Field := 16#0#; -- unspecified Reserved_16_16 : HAL.Bit := 16#0#; EM_1 : EMR1_EM_Field_1 := 16#0#; -- unspecified Reserved_22_31 : HAL.UInt10 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for EMR1_Register use record EM at 0 range 0 .. 15; Reserved_16_16 at 0 range 16 .. 16; EM_1 at 0 range 17 .. 21; Reserved_22_31 at 0 range 22 .. 31; end record; subtype IMR2_IM_Field is HAL.UInt17; type IMR2_Register is record IM : IMR2_IM_Field := 16#0#; -- unspecified Reserved_17_31 : HAL.UInt15 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for IMR2_Register use record IM at 0 range 0 .. 16; Reserved_17_31 at 0 range 17 .. 31; end record; subtype EMR2_EM_Field is HAL.UInt2; type EMR2_Register is record -- unspecified Reserved_0_0 : HAL.Bit := 16#0#; EM33 : Boolean := False; -- unspecified Reserved_2_7 : HAL.UInt6 := 16#0#; EM : EMR2_EM_Field := 16#0#; -- unspecified Reserved_10_31 : HAL.UInt22 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for EMR2_Register use record Reserved_0_0 at 0 range 0 .. 0; EM33 at 0 range 1 .. 1; Reserved_2_7 at 0 range 2 .. 7; EM at 0 range 8 .. 9; Reserved_10_31 at 0 range 10 .. 31; end record; subtype C2EMR1_EM_Field is HAL.UInt16; subtype C2EMR1_EM_Field_1 is HAL.UInt5; type C2EMR1_Register is record EM : C2EMR1_EM_Field := 16#0#; -- unspecified Reserved_16_16 : HAL.Bit := 16#0#; EM_1 : C2EMR1_EM_Field_1 := 16#0#; -- unspecified Reserved_22_31 : HAL.UInt10 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for C2EMR1_Register use record EM at 0 range 0 .. 15; Reserved_16_16 at 0 range 16 .. 16; EM_1 at 0 range 17 .. 21; Reserved_22_31 at 0 range 22 .. 31; end record; subtype C2IMR2_IM_Field is HAL.UInt17; type C2IMR2_Register is record IM : C2IMR2_IM_Field := 16#0#; -- unspecified Reserved_17_31 : HAL.UInt15 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for C2IMR2_Register use record IM at 0 range 0 .. 16; Reserved_17_31 at 0 range 17 .. 31; end record; subtype C2EMR2_EM_Field is HAL.UInt2; type C2EMR2_Register is record -- unspecified Reserved_0_0 : HAL.Bit := 16#0#; EM33 : Boolean := False; -- unspecified Reserved_2_7 : HAL.UInt6 := 16#0#; EM : C2EMR2_EM_Field := 16#0#; -- unspecified Reserved_10_31 : HAL.UInt22 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for C2EMR2_Register use record Reserved_0_0 at 0 range 0 .. 0; EM33 at 0 range 1 .. 1; Reserved_2_7 at 0 range 2 .. 7; EM at 0 range 8 .. 9; Reserved_10_31 at 0 range 10 .. 31; end record; ----------------- -- Peripherals -- ----------------- type EXTI_Peripheral is record RTSR1 : aliased RTSR1_Register; FTSR1 : aliased FTSR1_Register; SWIER1 : aliased SWIER1_Register; PR1 : aliased PR1_Register; RTSR2 : aliased RTSR2_Register; FTSR2 : aliased FTSR2_Register; SWIER2 : aliased SWIER2_Register; PR2 : aliased PR2_Register; IMR1 : aliased HAL.UInt32; EMR1 : aliased EMR1_Register; IMR2 : aliased IMR2_Register; EMR2 : aliased EMR2_Register; C2IMR1 : aliased HAL.UInt32; C2EMR1 : aliased C2EMR1_Register; C2IMR2 : aliased C2IMR2_Register; C2EMR2 : aliased C2EMR2_Register; end record with Volatile; for EXTI_Peripheral use record RTSR1 at 16#0# range 0 .. 31; FTSR1 at 16#4# range 0 .. 31; SWIER1 at 16#8# range 0 .. 31; PR1 at 16#C# range 0 .. 31; RTSR2 at 16#20# range 0 .. 31; FTSR2 at 16#24# range 0 .. 31; SWIER2 at 16#28# range 0 .. 31; PR2 at 16#2C# range 0 .. 31; IMR1 at 16#80# range 0 .. 31; EMR1 at 16#84# range 0 .. 31; IMR2 at 16#90# range 0 .. 31; EMR2 at 16#94# range 0 .. 31; C2IMR1 at 16#C0# range 0 .. 31; C2EMR1 at 16#C4# range 0 .. 31; C2IMR2 at 16#D0# range 0 .. 31; C2EMR2 at 16#D4# range 0 .. 31; end record; EXTI_Periph : aliased EXTI_Peripheral with Import, Address => System'To_Address (16#58000800#); end STM32_SVD.EXTI;
with Ada.Characters.Conversions; with Ada.UCD.Combining_Class; package body Ada.Strings.Composites is use type UCD.UCS_4; type Long_Boolean is new Boolean; for Long_Boolean'Size use Long_Integer'Size; function expect (exp, c : Long_Boolean) return Long_Boolean with Import, Convention => Intrinsic, External_Name => "__builtin_expect"; function Search ( Table : UCD.Combining_Class.Table_16_Type; Code : UCD.UCS_4) return UCD.Combining_Class_Type; function Search ( Table : UCD.Combining_Class.Table_16_Type; Code : UCD.UCS_4) return UCD.Combining_Class_Type is L : Positive := Table'First; H : Natural := Table'Last; begin loop declare type Unsigned is mod 2 ** Integer'Size; M : constant Positive := Integer (Unsigned (L + H) / 2); M_Item : UCD.Combining_Class.Table_16_Item_Type renames Table (M); begin if Code < M_Item.Start then H := M - 1; elsif expect ( Long_Boolean (Code >= M_Item.Start + UCD.UCS_4 (M_Item.Length)), True) then L := M + 1; else return M_Item.Combining_Class; end if; end; exit when L > H; end loop; return 0; end Search; generic type Character_Type is (<>); type String_Type is array (Positive range <>) of Character_Type; with procedure Get ( Data : String_Type; Last : out Natural; Result : out Wide_Wide_Character; Is_Illegal_Sequence : out Boolean); package Generic_Composites is procedure Start_No_Length_Check ( Item : String_Type; State : out Composites.State); procedure Get_Combined_No_Length_Check ( State : in out Composites.State; Item : String_Type; Last : out Natural; Is_Illegal_Sequence : out Boolean); end Generic_Composites; package body Generic_Composites is procedure Start_No_Length_Check ( Item : String_Type; State : out Composites.State) is begin Get ( Item, State.Next_Last, State.Next_Character, State.Next_Is_Illegal_Sequence); if State.Next_Is_Illegal_Sequence then State.Next_Combining_Class := 0; else State.Next_Combining_Class := Combining_Class (State.Next_Character); end if; end Start_No_Length_Check; procedure Get_Combined_No_Length_Check ( State : in out Composites.State; Item : String_Type; Last : out Natural; Is_Illegal_Sequence : out Boolean) is begin Last := State.Next_Last; -- skip first code point Is_Illegal_Sequence := State.Next_Is_Illegal_Sequence; if not Is_Illegal_Sequence -- combining class of illegal sequence = 0 and then State.Next_Combining_Class = 0 then declare New_Last : Natural; Combining_Code : Wide_Wide_Character; Combining_Is_Illegal_Sequence : Boolean; begin if Wide_Wide_Character'Pos (State.Next_Character) in UCD.Hangul.LBase .. UCD.Hangul.LBase + UCD.Hangul.LCount - 1 then Get ( Item (Last + 1 .. Item'Last), New_Last, Combining_Code, Combining_Is_Illegal_Sequence); if not Combining_Is_Illegal_Sequence and then Wide_Wide_Character'Pos (Combining_Code) in UCD.Hangul.VBase .. UCD.Hangul.VBase + UCD.Hangul.VCount - 1 then Last := New_Last; -- LV Get ( Item (Last + 1 .. Item'Last), New_Last, Combining_Code, Combining_Is_Illegal_Sequence); if not Combining_Is_Illegal_Sequence and then Wide_Wide_Character'Pos (Combining_Code) in UCD.Hangul.TBase .. UCD.Hangul.TBase + UCD.Hangul.TCount - 1 then Last := New_Last; -- LVT end if; end if; elsif Wide_Wide_Character'Pos (State.Next_Character) in UCD.Hangul.SBase .. UCD.Hangul.SBase + UCD.Hangul.SCount - 1 then Get ( Item (Last + 1 .. Item'Last), New_Last, Combining_Code, Combining_Is_Illegal_Sequence); if not Combining_Is_Illegal_Sequence and then Wide_Wide_Character'Pos (Combining_Code) in UCD.Hangul.TBase .. UCD.Hangul.TBase + UCD.Hangul.TCount - 1 then Last := New_Last; -- ST end if; end if; end; end if; declare Current_Class : Class := State.Next_Combining_Class; begin State.Next_Character := Wide_Wide_Character'Val (0); State.Next_Combining_Class := 0; State.Next_Is_Illegal_Sequence := False; State.Next_Last := Last; while Last < Item'Last loop Start_No_Length_Check (Item (Last + 1 .. Item'Last), State); if State.Next_Is_Illegal_Sequence or else State.Next_Combining_Class < Current_Class then exit; elsif State.Next_Combining_Class = 0 then if Is_Variation_Selector (State.Next_Character) then -- get one variation selector Last := State.Next_Last; if Last >= Item'Last then State.Next_Character := Wide_Wide_Character'Val (0); State.Next_Combining_Class := 0; State.Next_Is_Illegal_Sequence := False; else Start_No_Length_Check ( Item (Last + 1 .. Item'Last), State); end if; end if; exit; end if; Current_Class := State.Next_Combining_Class; Last := State.Next_Last; end loop; end; end Get_Combined_No_Length_Check; end Generic_Composites; generic type Character_Type is (<>); type String_Type is array (Positive range <>) of Character_Type; with procedure Start_No_Length_Check ( Item : String_Type; State : out Composites.State); procedure Generic_Start ( Item : String_Type; State : out Composites.State); procedure Generic_Start ( Item : String_Type; State : out Composites.State) is begin if Item'Length = 0 then State.Next_Character := Wide_Wide_Character'Val (0); State.Next_Combining_Class := 0; State.Next_Last := Item'Last; else Start_No_Length_Check (Item, State); end if; end Generic_Start; generic type Character_Type is (<>); type String_Type is array (Positive range <>) of Character_Type; with package C is new Generic_Composites (Character_Type, String_Type, others => <>); procedure Generic_Get_Combined ( Item : String_Type; Last : out Natural; Is_Illegal_Sequence : out Boolean); procedure Generic_Get_Combined ( Item : String_Type; Last : out Natural; Is_Illegal_Sequence : out Boolean) is begin if Item'Length = 0 then -- finished Last := Item'Last; Is_Illegal_Sequence := True; -- ?? else declare St : State; begin C.Start_No_Length_Check (Item, St); C.Get_Combined_No_Length_Check ( St, Item, Last, Is_Illegal_Sequence); end; end if; end Generic_Get_Combined; generic type Character_Type is (<>); type String_Type is array (Positive range <>) of Character_Type; with package C is new Generic_Composites (Character_Type, String_Type, others => <>); procedure Generic_Get_Combined_With_State ( State : in out Composites.State; Item : String_Type; Last : out Natural; Is_Illegal_Sequence : out Boolean); procedure Generic_Get_Combined_With_State ( State : in out Composites.State; Item : String_Type; Last : out Natural; Is_Illegal_Sequence : out Boolean) is begin if Item'Length = 0 then -- finished Last := Item'Last; Is_Illegal_Sequence := True; -- ?? State.Next_Character := Wide_Wide_Character'Val (0); State.Next_Combining_Class := 0; State.Next_Is_Illegal_Sequence := False; State.Next_Last := Last; else C.Get_Combined_No_Length_Check ( State, Item, Last, Is_Illegal_Sequence); end if; end Generic_Get_Combined_With_State; package Strings is new Generic_Composites ( Character, String, Characters.Conversions.Get); package Wide_Strings is new Generic_Composites ( Wide_Character, Wide_String, Characters.Conversions.Get); package Wide_Wide_Strings is new Generic_Composites ( Wide_Wide_Character, Wide_Wide_String, Characters.Conversions.Get); -- implementation function Combining_Class (Item : Wide_Wide_Character) return Class is Code : constant UCD.UCS_4 := Wide_Wide_Character'Pos (Item); begin if Code > 16#ffff# then return Class ( Search (UCD.Combining_Class.Table_1XXXX, Code - 16#10000#)); else return Class (Search (UCD.Combining_Class.Table_XXXX, Code)); end if; end Combining_Class; procedure Iterate ( Process : not null access procedure ( Item : Wide_Wide_Character; Combining_Class : Class)) is begin for I in UCD.Combining_Class.Table_XXXX'Range loop declare E : UCD.Combining_Class.Table_16_Item_Type renames UCD.Combining_Class.Table_XXXX (I); begin for J in E.Start .. E.Start + UCD.UCS_4 (E.Length) - 1 loop Process ( Wide_Wide_Character'Val (J), Class (E.Combining_Class)); end loop; end; end loop; for I in UCD.Combining_Class.Table_1XXXX'Range loop declare E : UCD.Combining_Class.Table_16_Item_Type renames UCD.Combining_Class.Table_1XXXX (I); begin for J in E.Start .. E.Start + UCD.UCS_4 (E.Length) - 1 loop Process ( Wide_Wide_Character'Val (J + 16#10000#), Class (E.Combining_Class)); end loop; end; end loop; end Iterate; function Is_Variation_Selector (Item : Wide_Wide_Character) return Boolean is subtype WWC is Wide_Wide_Character; -- for the case statement begin case Item is when WWC'Val (16#180B#) .. WWC'Val (16#180D#) -- MONGOLIAN FREE VARIATION SELECTOR (1..3) | WWC'Val (16#FE00#) .. WWC'Val (16#FE0F#) -- VARIATION SELECTOR (1..16) | WWC'Val (16#E0100#) .. WWC'Val (16#E01EF#) => -- VARIATION SELECTOR (17..256) return True; when others => return False; end case; end Is_Variation_Selector; procedure Start (Item : String; State : out Composites.State) is procedure Start_String is new Generic_Start (Character, String, Strings.Start_No_Length_Check); begin Start_String (Item, State); end Start; procedure Start (Item : Wide_String; State : out Composites.State) is procedure Start_Wide_String is new Generic_Start ( Wide_Character, Wide_String, Wide_Strings.Start_No_Length_Check); begin Start_Wide_String (Item, State); end Start; procedure Start (Item : Wide_Wide_String; State : out Composites.State) is procedure Start_Wide_Wide_String is new Generic_Start ( Wide_Wide_Character, Wide_Wide_String, Wide_Wide_Strings.Start_No_Length_Check); begin Start_Wide_Wide_String (Item, State); end Start; procedure Get_Combined ( Item : String; Last : out Natural; Is_Illegal_Sequence : out Boolean) is procedure Get_Combined_String is new Generic_Get_Combined (Character, String, Strings); begin Get_Combined_String (Item, Last, Is_Illegal_Sequence); end Get_Combined; procedure Get_Combined ( State : in out Composites.State; Item : String; Last : out Natural; Is_Illegal_Sequence : out Boolean) is procedure Get_Combined_String is new Generic_Get_Combined_With_State (Character, String, Strings); begin Get_Combined_String (State, Item, Last, Is_Illegal_Sequence); end Get_Combined; procedure Get_Combined ( Item : Wide_String; Last : out Natural; Is_Illegal_Sequence : out Boolean) is procedure Get_Combined_Wide_String is new Generic_Get_Combined (Wide_Character, Wide_String, Wide_Strings); begin Get_Combined_Wide_String (Item, Last, Is_Illegal_Sequence); end Get_Combined; procedure Get_Combined ( State : in out Composites.State; Item : Wide_String; Last : out Natural; Is_Illegal_Sequence : out Boolean) is procedure Get_Combined_Wide_String is new Generic_Get_Combined_With_State ( Wide_Character, Wide_String, Wide_Strings); begin Get_Combined_Wide_String (State, Item, Last, Is_Illegal_Sequence); end Get_Combined; procedure Get_Combined ( Item : Wide_Wide_String; Last : out Natural; Is_Illegal_Sequence : out Boolean) is procedure Get_Combined_Wide_Wide_String is new Generic_Get_Combined ( Wide_Wide_Character, Wide_Wide_String, Wide_Wide_Strings); begin Get_Combined_Wide_Wide_String (Item, Last, Is_Illegal_Sequence); end Get_Combined; procedure Get_Combined ( State : in out Composites.State; Item : Wide_Wide_String; Last : out Natural; Is_Illegal_Sequence : out Boolean) is procedure Get_Combined_Wide_Wide_String is new Generic_Get_Combined_With_State ( Wide_Wide_Character, Wide_Wide_String, Wide_Wide_Strings); begin Get_Combined_Wide_Wide_String (State, Item, Last, Is_Illegal_Sequence); end Get_Combined; end Ada.Strings.Composites;
package SPARKNaCl.Scalar with Pure, SPARK_Mode => On is -------------------------------------------------------- -- Scalar multiplication -------------------------------------------------------- function Mult (N : in Bytes_32; P : in Bytes_32) return Bytes_32 with Global => null, Pure_Function; function Mult_Base (N : in Bytes_32) return Bytes_32 with Global => null, Pure_Function; end SPARKNaCl.Scalar;
-- { dg-do run } -- with Init12; use Init12; with Text_IO; use Text_IO; with Dump; procedure T12 is Local_A11 : Arr11; Local_A22 : Arr22; begin Local_A11(1,1) := My_A11(1,1) + 1; Local_A11(1,2) := My_A11(1,2) + 1; Local_A11(2,1) := My_A11(2,1) + 1; Local_A11(2,2) := My_A11(2,2) + 1; Put ("Local_A11 :"); Dump (Local_A11'Address, Arr11'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "Local_A11 : 13 00 ab 00 35 00 cd 00 13 00 ab 00 35 00 cd 00.*\n" } Local_A22(1,1) := My_A22(1,1) + 1; Local_A22(1,2) := My_A22(1,2) + 1; Local_A22(2,1) := My_A22(2,1) + 1; Local_A22(2,2) := My_A22(2,2) + 1; Put ("Local_A22 :"); Dump (Local_A22'Address, Arr22'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "Local_A22 : 00 ab 00 13 00 cd 00 35 00 ab 00 13 00 cd 00 35.*\n" } Local_A11 := (1 => (16#AB0012#, 16#CD0034#), 2 => (16#AB0012#, 16#CD0034#)); Put ("Local_A11 :"); Dump (Local_A11'Address, Arr11'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "Local_A11 : 12 00 ab 00 34 00 cd 00 12 00 ab 00 34 00 cd 00.*\n" } Local_A22 := (1 => (16#AB0012#, 16#CD0034#), 2 => (16#AB0012#, 16#CD0034#)); Put ("Local_A22 :"); Dump (Local_A22'Address, Arr22'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "Local_A22 : 00 ab 00 12 00 cd 00 34 00 ab 00 12 00 cd 00 34.*\n" } Local_A11(1,1) := Local_A11(1,1) + 1; Local_A11(1,2) := Local_A11(1,2) + 1; Local_A11(2,1) := Local_A11(2,1) + 1; Local_A11(2,2) := Local_A11(2,2) + 1; Put ("Local_A11 :"); Dump (Local_A11'Address, Arr11'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "Local_A11 : 13 00 ab 00 35 00 cd 00 13 00 ab 00 35 00 cd 00.*\n" } Local_A22(1,1) := Local_A22(1,1) + 1; Local_A22(1,2) := Local_A22(1,2) + 1; Local_A22(2,1) := Local_A22(2,1) + 1; Local_A22(2,2) := Local_A22(2,2) + 1; Put ("Local_A22 :"); Dump (Local_A22'Address, Arr22'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "Local_A22 : 00 ab 00 13 00 cd 00 35 00 ab 00 13 00 cd 00 35.*\n" } end;
with Ada.Numerics.Long_Elementary_Functions; with Ada.Text_IO; use Ada.Text_IO; procedure Sequence_Of_Non_Squares_Test is use Ada.Numerics.Long_Elementary_Functions; function Non_Square (N : Positive) return Positive is begin return N + Positive (Long_Float'Rounding (Sqrt (Long_Float (N)))); end Non_Square; I : Positive; begin for N in 1..22 loop -- First 22 non-squares Put (Natural'Image (Non_Square (N))); end loop; New_Line; for N in 1..1_000_000 loop -- Check first million of I := Non_Square (N); if I = Positive (Sqrt (Long_Float (I)))**2 then Put_Line ("Found a square:" & Positive'Image (N)); end if; end loop; end Sequence_Of_Non_Squares_Test;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with System.Pool_Local; generic File_Size : Natural; -- handle empty file package File_Operations.Heap is localPool : System.Pool_Local.Unbounded_Reclaim_Pool; subtype HM_File_String is String (1 .. File_Size); type contents_ref is access HM_File_String; for contents_ref'Storage_Pool use localPool; file_contents : contents_ref; procedure slurp_file (dossier : String); end File_Operations.Heap;
with Ada.Text_IO; with Max2; procedure Main is V : Max2.Vector := (4, 4, 4, 4); begin Ada.Text_IO.Put_Line(Max2.FindMax2 (V)'Image); end Main;
-- -- Copyright (C) 2017, AdaCore -- -- This spec has been automatically generated from ATSAMG55J19.svd -- This is a version for the Atmel ATSAMG55J19 Microcontroller MCU package Ada.Interrupts.Names is -- All identifiers in this unit are implementation defined pragma Implementation_Defined; ---------------- -- Interrupts -- ---------------- -- System tick Sys_Tick_Interrupt : constant Interrupt_ID := -1; SUPC_Interrupt : constant Interrupt_ID := 0; RSTC_Interrupt : constant Interrupt_ID := 1; RTC_Interrupt : constant Interrupt_ID := 2; RTT_Interrupt : constant Interrupt_ID := 3; WDT_Interrupt : constant Interrupt_ID := 4; PMC_Interrupt : constant Interrupt_ID := 5; EFC_Interrupt : constant Interrupt_ID := 6; SPI7_Interrupt : constant Interrupt_ID := 7; TWI7_Interrupt : constant Interrupt_ID := 7; USART7_Interrupt : constant Interrupt_ID := 7; SPI0_Interrupt : constant Interrupt_ID := 8; USART0_Interrupt : constant Interrupt_ID := 8; SPI1_Interrupt : constant Interrupt_ID := 9; TWI1_Interrupt : constant Interrupt_ID := 9; USART1_Interrupt : constant Interrupt_ID := 9; PIOA_Interrupt : constant Interrupt_ID := 11; PIOB_Interrupt : constant Interrupt_ID := 12; PDMIC0_Interrupt : constant Interrupt_ID := 13; SPI2_Interrupt : constant Interrupt_ID := 14; TWI2_Interrupt : constant Interrupt_ID := 14; USART2_Interrupt : constant Interrupt_ID := 14; MEM2MEM_Interrupt : constant Interrupt_ID := 15; I2SC0_Interrupt : constant Interrupt_ID := 16; I2SC1_Interrupt : constant Interrupt_ID := 17; PDMIC1_Interrupt : constant Interrupt_ID := 18; SPI3_Interrupt : constant Interrupt_ID := 19; TWI3_Interrupt : constant Interrupt_ID := 19; USART3_Interrupt : constant Interrupt_ID := 19; SPI4_Interrupt : constant Interrupt_ID := 20; TWI4_Interrupt : constant Interrupt_ID := 20; USART4_Interrupt : constant Interrupt_ID := 20; SPI5_Interrupt : constant Interrupt_ID := 21; TWI5_Interrupt : constant Interrupt_ID := 21; USART5_Interrupt : constant Interrupt_ID := 21; SPI6_Interrupt : constant Interrupt_ID := 22; TWI6_Interrupt : constant Interrupt_ID := 22; USART6_Interrupt : constant Interrupt_ID := 22; TC0_Interrupt : constant Interrupt_ID := 23; TC1_Interrupt : constant Interrupt_ID := 24; TC2_Interrupt : constant Interrupt_ID := 25; TC3_Interrupt : constant Interrupt_ID := 26; TC4_Interrupt : constant Interrupt_ID := 27; TC5_Interrupt : constant Interrupt_ID := 28; ADC_Interrupt : constant Interrupt_ID := 29; FPU_Interrupt : constant Interrupt_ID := 30; WKUP0_Interrupt : constant Interrupt_ID := 31; WKUP1_Interrupt : constant Interrupt_ID := 32; WKUP2_Interrupt : constant Interrupt_ID := 33; WKUP3_Interrupt : constant Interrupt_ID := 34; WKUP4_Interrupt : constant Interrupt_ID := 35; WKUP5_Interrupt : constant Interrupt_ID := 36; WKUP6_Interrupt : constant Interrupt_ID := 37; WKUP7_Interrupt : constant Interrupt_ID := 38; WKUP8_Interrupt : constant Interrupt_ID := 39; WKUP9_Interrupt : constant Interrupt_ID := 40; WKUP10_Interrupt : constant Interrupt_ID := 41; WKUP11_Interrupt : constant Interrupt_ID := 42; WKUP12_Interrupt : constant Interrupt_ID := 43; WKUP13_Interrupt : constant Interrupt_ID := 44; WKUP14_Interrupt : constant Interrupt_ID := 45; WKUP15_Interrupt : constant Interrupt_ID := 46; UHP_Interrupt : constant Interrupt_ID := 47; UDP_Interrupt : constant Interrupt_ID := 48; CRCCU_Interrupt : constant Interrupt_ID := 49; end Ada.Interrupts.Names;
with Ada.Text_IO; use Ada.Text_IO; with Ada.Float_Text_IO; use Ada.Float_Text_IO; procedure Lab1 is FP, LP, Steps, Momsproc, Moms: Float; begin loop Put("Första pris: "); Get(FP); exit when FP >= 0.0; end loop; loop Put("Sista pris: "); Get(LP); exit when LP >= FP; end loop; loop Put("Steg: "); Get(Steps); exit when Steps > 0.0; end loop; loop Put("Momsprocent: "); Get(Momsproc); exit when Momsproc >= 0.0 and Momsproc <= 100; end loop; Put("=== Momstabell ==="); New_Line(1); Put("Pris utan moms Moms Pris med moms"); New_Line(1); while FP <= LP loop --- for Moms := FP * Momsproc / 100.0; Put(FP,6,2,0); Put(Moms,8,2,0); Put(FP + Moms,8,2,0); New_Line(1); FP := FP + Steps; end loop; end Lab1;
pragma Style_Checks (Off); -- This spec has been automatically generated from STM32H743x.svd pragma Restrictions (No_Elaboration_Code); with HAL; with System; package STM32_SVD.VREFBUF is pragma Preelaborate; --------------- -- Registers -- --------------- subtype CSR_VRS_Field is HAL.UInt3; -- VREFBUF control and status register type CSR_Register is record -- Voltage reference buffer mode enable This bit is used to enable the -- voltage reference buffer mode. ENVR : Boolean := False; -- High impedance mode This bit controls the analog switch to connect or -- not the VREF+ pin. Refer to Table196: VREF buffer modes for the mode -- descriptions depending on ENVR bit configuration. HIZ : Boolean := True; -- unspecified Reserved_2_2 : HAL.Bit := 16#0#; -- Read-only. Voltage reference buffer ready VRR : Boolean := False; -- Voltage reference scale These bits select the value generated by the -- voltage reference buffer. Other: Reserved VRS : CSR_VRS_Field := 16#0#; -- unspecified Reserved_7_31 : HAL.UInt25 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CSR_Register use record ENVR at 0 range 0 .. 0; HIZ at 0 range 1 .. 1; Reserved_2_2 at 0 range 2 .. 2; VRR at 0 range 3 .. 3; VRS at 0 range 4 .. 6; Reserved_7_31 at 0 range 7 .. 31; end record; subtype CCR_TRIM_Field is HAL.UInt6; -- VREFBUF calibration control register type CCR_Register is record -- Trimming code These bits are automatically initialized after reset -- with the trimming value stored in the Flash memory during the -- production test. Writing into these bits allows to tune the internal -- reference buffer voltage. TRIM : CCR_TRIM_Field := 16#0#; -- unspecified Reserved_6_31 : HAL.UInt26 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CCR_Register use record TRIM at 0 range 0 .. 5; Reserved_6_31 at 0 range 6 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- VREFBUF type VREFBUF_Peripheral is record -- VREFBUF control and status register CSR : aliased CSR_Register; -- VREFBUF calibration control register CCR : aliased CCR_Register; end record with Volatile; for VREFBUF_Peripheral use record CSR at 16#0# range 0 .. 31; CCR at 16#4# range 0 .. 31; end record; -- VREFBUF VREFBUF_Periph : aliased VREFBUF_Peripheral with Import, Address => VREFBUF_Base; end STM32_SVD.VREFBUF;
private with Ada.Containers.Indefinite_Holders; private with Ada.Containers.Indefinite_Ordered_Maps; private with Ada.Containers.Indefinite_Vectors; package Yeison_Single with Preelaborate is subtype Text is String; type Any is tagged private with Integer_Literal => To_Int, Real_Literal => To_Real, String_Literal => To_String, Constant_Indexing => Constant_Reference, Aggregate => (Empty => Empty, Add_Named => Insert); function Image (This : Any) return Text; function To_Int (Img : String) return Any; function To_Real (Img : String) return Any; function To_String (Img : Wide_Wide_String) return Any; function Constant_Reference (This : Any; Pos : Positive) return access constant Any; function Constant_Reference (This : Any; Key : String) return access constant Any; function Empty return Any; procedure Insert (This : in out Any; Key : Text; Val : Any); function True return Any; function False return Any; type Vec_Aux is private with Aggregate => (Empty => Empty, Add_Unnamed => Append); function Empty return Vec_Aux; procedure Append (This : in out Vec_Aux; Val : Any); package Operators is function "+" (This : Vec_Aux) return Any; end Operators; private type Inner_Any is interface; function Image (This : Inner_Any) return Text is abstract; type Inner_Bool is new Inner_Any with record Value : Boolean; end record; overriding function Image (This : Inner_Bool) return Text is (This.Value'Image); type Inner_Int is new Inner_Any with record Value : Integer; end record; overriding function Image (This : Inner_Int) return Text is (This.Value'Image); type Inner_Real is new Inner_Any with record Value : Float; end record; overriding function Image (This : Inner_Real) return Text is (This.Value'Image); type Inner_Str is new Inner_Any with record Value : access Text; end record; overriding function Image (This : Inner_Str) return Text is (This.Value.all); package Inner_Maps is new Ada.Containers.Indefinite_Ordered_Maps (String, Inner_Any'Class); type Inner_Map is new Inner_Any with record Value : Inner_Maps.Map; end record; overriding function Image (This : Inner_Map) return Text; package Inner_Vectors is new Ada.Containers.Indefinite_Vectors (Positive, Inner_Any'Class); type Inner_Vec is new Inner_Any with record Value : Inner_Vectors.Vector; end record; overriding function Image (This : Inner_Vec) return Text; package Inner_Holders is new Ada.Containers.Indefinite_Holders (Inner_Any'Class); type Any is new Inner_Holders.Holder with null record; function Image (This : Any) return Text is (This.Element.Image); type Vec_Aux is record Value : Inner_Vec; end record; end Yeison_Single;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Ada.Text_IO; use Ada.Text_IO; with Randomise; use Randomise; procedure Main is C : Character; S : R_String.Bounded_String; Are_Inside_Tag : Boolean := False; begin while not End_Of_File loop Get_Immediate(C); if Are_Inside_Tag then if C in '<'|'"' then Are_Inside_Tag := False; Randomise_String(S); Put(R_String.To_String(S)); S := R_String.To_Bounded_String(""); Put(C); else R_String.Append(S, C); end if; elsif C in '>'|'"' then Are_Inside_Tag := True; S := R_String.To_Bounded_String(""); Put(C); else Put(C); end if; end loop; end Main;
------------------------------------------------------------------------------ -- cooks.adb -- -- Implementation of the cooks. ------------------------------------------------------------------------------ with Ada.Strings.Unbounded, Randoms, Meals, Reporter; use Ada.Strings.Unbounded, Randoms, Meals, Reporter; package body Cooks is task body Cook is My_Name : Unbounded_String; -- Identification of the cook Current_Order : Order; -- What she's currently preparing procedure Cook_The_Order is begin Report (My_Name & " is cooking " & Current_Order.Food); delay Duration(Random(3.0, 8.0)); Report (My_Name & " puts " & Current_Order.Food & " under heat lamp"); Heat_Lamp.Write (Current_Order); end Cook_The_Order; procedure Coffee_Break is begin Report (My_Name & " on coffee break"); delay 10.0; Report (My_Name & " returns from coffee break"); end Coffee_Break; begin accept Here_Is_Your_Name (Name: Cook_Name) do My_Name := To_Unbounded_String(Cook_Name'Image(Name)); end Here_Is_Your_Name; Report (My_Name & " clocking in"); Life_Cycle: loop for I in 1..4 loop -- coffee break every fourth meal select accept Prepare (O: Order) do Current_Order := O; -- small critical section, end Prepare; -- ... don't hold waiter up!! Cook_The_Order; or accept Pink_Slip; -- fired! exit Life_Cycle; end select; end loop; -- end of cooking four meals Coffee_Break; -- now take a break end loop Life_Cycle; -- end of 4-meal--break cycle Report (My_Name & " clocking out"); exception when others => Report ("Error: Cook unexpectedly dead from heart attack"); end Cook; end Cooks;
with Mismatch; with Default_Value; use Mismatch; with Prefix_Notation; use Prefix_Notation; with Ada.Text_IO; use Ada.Text_IO; with Ada.Characters; -- With Comment and Whitespaces use Ada.Characters; with Ada.Containers.Vectors; use Ada.Containers; with Ada.Calendar, Ada.Directories; use Ada.Calendar, Ada.Directories; package Import_Examples is end Import_Examples;
-------------------------------------------------------------------------------- -- Fichier : arbre_binaire.ads -- Auteur : MOUDDENE Hamza & CAZES Noa -- Objectif : Test du module Arbre_Binaire. -- Créé : Dimanche Nov 25 2019 -------------------------------------------------------------------------------- with Ada.Text_IO; use Ada.Text_IO; with Arbre_Binaire; procedure Test_Arbre_Binaire is -- Instantiation du package Arbre_Binaire avec T_DATA comme Entier. package AB_Entier is New Arbre_Binaire (T_DATA => Integer); use AB_Entier; -- gt est la fonction > qui compare deux DATAs. -- -- Param DATA1|2 : Est l'DATA qu'on va comparer. -- -- Return Boolean : retourne True si DATA1 > DATA2, sinon False. function gt (DATA1, DATA2: in Integer) return Boolean is begin return (DATA1 > DATA2); end gt; procedure Insert is new AB_Entier.Insert (gt); -- Initialisation des variables. Nb_Donnees : constant Integer := 10; -- Height du tableau DATAs. DATAs : constant array (1..Nb_Donnees) of Integer -- DATAs est un tableau := (56, 78, 76, 27, 90, 23, 12, 43, 24, 39); -- contenant des DATAs. -- Initialize un ABR avec 5 puis 3 et 6 ajoutés dans un Tree vDATAe. procedure Init (Tree : out T_BT) is begin Initialize (Tree); -- Créer un Tree vDATAe. Insert (Tree, 5); -- Ajouter 5 à Tree. Insert (Tree, 3); -- Ajouter 3 à Tree. Insert (Tree, 6); -- Ajouter 6 à Tree. end Init; -- Tester la fonction Is_Empty avec différents arbres. procedure Tester_Is_Empty is Tree1, Tree2 : T_BT; begin Initialize (Tree1); pragma Assert (Is_Empty (Tree1)); -- Tree1 est vDATAe. Insert (Tree1, 12); pragma Assert (not Is_Empty (Tree1)); -- Tree1 n'est pas vDATAe. Destruct (Tree1); -- Libérer la mémoire. Init (Tree2); pragma Assert (not Is_Empty (Tree2)); -- Tree2 n'est pas vDATAe. Destruct (Tree2); -- Libérer la mémoire. Put_line("Fonction Tester_Is_Empty est exécutée avec succès."); New_Line; end Tester_Is_Empty; -- Tester la procédure Height avec deux arbres différents. procedure Tester_Height is Tree1, Tree2 : T_BT; begin Initialize (Tree1); pragma assert (Height (Tree1) = 0); -- Height = 0. Insert (Tree1, 99); pragma assert (Height ( Tree1) /= 0); -- Height = 1. Destruct (Tree1); -- Libérer la mémoire. Init (Tree2); pragma Assert (Height (Tree2) = 3); -- Height = 3. Insert (Tree2, 33); pragma Assert (Height (Tree2) /= 3); -- Height = 4. Destruct (Tree2); -- Libérer la mémoire. Put_line("Fonction Tester_Height est exécutée avec succès."); New_Line; end Tester_Height; -- Tester la procédure Insert. procedure Tester_Insert is Tree : T_BT; begin Init (Tree); pragma Assert (not Is_Empty (Tree)); -- Tree n'est pas vDATAe. Insert (Tree, 16); pragma Assert (not Is_Empty (Tree)); -- Tree n'est pas vDATAe. Destruct (Tree); -- Libérer la mémoire. Put_Line ("Procédure Tester_Insert est exécutée avec succès."); New_Line; end Tester_Insert; -- Initialise l'ABR Tree comme un ABR vDATAe dans lequel ont été insérées -- les cles DATAs ci-dessus. procedure Construire_Exemple_Arbre (Annuaire : out T_BT) is begin Initialize (Annuaire); pragma Assert (Is_Empty (Annuaire)); pragma Assert (Height (Annuaire) = 0); for i in 1..Nb_Donnees loop Insert (Annuaire, DATAs (i)); pragma Assert (not Is_Empty (Annuaire)); pragma Assert (Height (Annuaire) = i); end loop; Destruct (Annuaire); pragma Assert (Is_Empty (Annuaire)); pragma Assert (Height (Annuaire) = 0); end Construire_Exemple_Arbre; procedure Tester_Exemple_Arbre is Annuaire : T_BT; begin Construire_Exemple_Arbre (Annuaire); Destruct (Annuaire); pragma Assert (Is_Empty (Annuaire)); pragma Assert (Height (Annuaire) = 0); Put_Line ("Procédure Tester_Exemple_Arbre est exécutée avec succès."); New_Line; end Tester_Exemple_Arbre; begin New_Line; Put_Line("*************************** Début ****************************"); New_Line; -- Tester la fonction Is_Empty. Tester_Is_Empty; -- Tester la fonction Height. Tester_Height; -- Tester la procédure Insert. Tester_Insert; -- Tester la procédure Tester_Exemple_Arbre. Tester_Exemple_Arbre; New_Line; Put_Line("***************************** Fin ****************************"); New_Line; end Test_Arbre_Binaire;
with Ada.Unchecked_Deallocation; with Physics; use Physics; with Materials; with Circles; package body Worlds is -- init world procedure Init(This : in out World; dt : in Float; MaxEnts : Natural := 32) is VecZero : constant Vec2D := (0.0, 0.0); begin This.MaxEntities := MaxEnts; This.dt := dt; This.Invdt := 1.0 / dt; This.Entities := new EntsList.List; This.Environments := new EntsList.List; This.Links := new LinksList.List; This.Cols := new ColsList.List; This.InvalidChecker := null; This.MaxSpeed := VecZero; This.StaticEnt := Circles.Create(VecZero, VecZero, VecZero, 1.0, Materials.STATIC.SetFriction.SetRestitution(LinkTypesFactors(LTRope))); end Init; procedure IncreaseMaxEntities(This : in out World; Count : Positive) is begin This.MaxEntities := This.MaxEntities + Count; end IncreaseMaxEntities; procedure Step(This : in out World; Mode : StepModes := Step_Normal) is begin if Mode = Step_LowRAM then StepLowRAM(This); else StepNormal(This); end if; end Step; -- Add entity to the world procedure AddEntity(This : in out World; Ent : not null EntityClassAcc) is begin if This.MaxEntities = 0 or else Integer(This.Entities.Length) + Integer(This.Environments.Length) + Integer(This.Links.Length) < This.MaxEntities then This.Entities.Append(Ent); end if; end AddEntity; procedure SetMaxSpeed(This : in out World; Speed : Vec2D) is begin This.MaxSpeed := Speed; end SetMaxSpeed; -- Add env to the world procedure AddEnvironment(This : in out World; Ent : not null EntityClassAcc) is begin if This.MaxEntities = 0 or else Integer(This.Entities.Length) + Integer(This.Environments.Length) + Integer(This.Links.Length) < This.MaxEntities then This.Environments.Append(Ent); end if; end AddEnvironment; procedure LinkEntities(This : in out World; A, B : EntityClassAcc; LinkType : LinkTypes; Factor : Float := 0.0) is begin if This.MaxEntities = 0 or else Integer(This.Entities.Length) + Integer(This.Environments.Length) + Integer(This.Links.Length) < This.MaxEntities then This.Links.Append(CreateLink(A, B, LinkType, Factor)); end if; end LinkEntities; procedure UnlinkEntity(This : in out World; E : EntityClassAcc) is CurLink : LinkAcc; Edited : Boolean := False; begin loop Edited := False; declare use LinksList; Curs : LinksList.Cursor := This.Links.First; begin while Curs /= LinksList.No_Element loop CurLink := LinksList.Element(Curs); if CurLink.A = E or CurLink.B = E then This.Links.Delete(Curs); FreeLink(CurLink); Edited := True; end if; exit when Edited; Curs := LinksList.Next(Curs); end loop; end; exit when not Edited; end loop; end UnlinkEntity; -- clear the world (deep free) procedure Free(This : in out World) is use EntsList; use LinksList; procedure FreeEntList is new Ada.Unchecked_Deallocation(EntsList.List, EntsListAcc); procedure FreeLinkList is new Ada.Unchecked_Deallocation(LinksList.List, LinksListAcc); procedure FreeColsList is new Ada.Unchecked_Deallocation(ColsList.List, ColsListAcc); Curs : EntsList.Cursor := This.Entities.First; CursL : LinksList.Cursor := This.Links.First; TmpLink : LinkAcc; begin while CursL /= LinksList.No_Element loop TmpLink := LinksList.Element(CursL); FreeLink(TmpLink); CursL := LinksList.Next(CursL); end loop; while Curs /= EntsList.No_Element loop FreeEnt(EntsList.Element(Curs)); Curs := EntsList.Next(Curs); end loop; Curs := This.Environments.First; while Curs /= EntsList.No_Element loop FreeEnt(EntsList.Element(Curs)); Curs := EntsList.Next(Curs); end loop; FreeEnt(This.StaticEnt); This.Entities.Clear; This.Environments.Clear; This.Links.Clear; This.Cols.Clear; FreeEntList(This.Entities); FreeEntList(This.Environments); FreeLinkList(This.Links); FreeColsList(This.Cols); end Free; -- Gives the world a function to check if entities are valid or not procedure SetInvalidChecker(This : in out World; Invalider : EntCheckerAcc) is begin if Invalider /= null then This.InvalidChecker := Invalider; end if; end SetInvalidChecker; -- Remove entity from the world procedure RemoveEntity(This : in out World; Ent : EntityClassAcc; Destroy : Boolean) is Curs : EntsList.Cursor := This.Entities.Find(Ent); begin This.Entities.Delete(Curs); This.UnlinkEntity(Ent); if Destroy then FreeEnt(Ent); end if; end RemoveEntity; -- Remove entity from the world procedure RemoveEnvironment(This : in out World; Ent : not null EntityClassAcc; Destroy : Boolean) is Curs : EntsList.Cursor := This.Environments.Find(Ent); begin This.Environments.Delete(Curs); if Destroy then FreeEnt(Ent); end if; end RemoveEnvironment; function GetEntities(This : in World) return EntsListAcc is begin return This.Entities; end GetEntities; function GetClosest(This : in out World; Pos : Vec2D; SearchMode : SearchModes := SM_All) return EntityClassAcc is use EntsList; EntList : constant EntsListAcc := (if SearchMode = SM_All or SearchMode = SM_Entity then This.Entities else This.Environments); Curs : EntsList.Cursor := EntList.First; Ent : EntityClassAcc; begin while Curs /= EntsList.No_Element loop Ent := EntsList.Element(Curs); if IsInside(Pos, Ent) then return Ent; end if; Curs := EntsList.Next(Curs); end loop; if SearchMode = SM_All then return This.GetClosest(Pos, SM_Environment); end if; return null; end GetClosest; function GetEnvironments(This : in World) return EntsListAcc is begin return This.Environments; end GetEnvironments; function GetLinks(This : in World) return LinksListAcc is begin return This.Links; end GetLinks; procedure CheckEntities(This : in out World) is begin if This.InvalidChecker /= null then declare E : EntityClassAcc; Edited : Boolean := False; begin loop Edited := False; declare use EntsList; Curs : EntsList.Cursor := This.Entities.First; begin while Curs /= EntsList.No_Element loop E := EntsList.Element(Curs); if This.InvalidChecker.all(E) then This.RemoveEntity(E, True); Edited := True; end if; exit when Edited; Curs := EntsList.Next(Curs); end loop; end; exit when not Edited; end loop; end; end if; end CheckEntities; end Worlds;
pragma License (Unrestricted); -- implementation unit generic package Ada.Containers.Ordered_Sets.Debug is pragma Preelaborate; procedure Dump (Source : Set; Message : String := ""); function Valid (Source : Set) return Boolean; end Ada.Containers.Ordered_Sets.Debug;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2020, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of 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. -- -- -- ------------------------------------------------------------------------------ -- Olimex STM32-H405 -- Digi-Key part no. 1188-1167-ND -- https://www.olimex.com/Products/ARM/ST/STM32-H405/resources/STM32-H405_sch.pdf with STM32.GPIO; use STM32.GPIO; with STM32.Device; package STM32_H405 is EXT1_1 : GPIO_Point renames STM32.Device.PA11; EXT1_2 : GPIO_Point renames STM32.Device.PA8; EXT1_3 : GPIO_Point renames STM32.Device.PA12; EXT1_4 : GPIO_Point renames STM32.Device.PA9; -- EXT1_5 : 3.3V -- EXT1_6 : GND EXT1_7 : GPIO_Point renames STM32.Device.PA10; EXT1_8 : GPIO_Point renames STM32.Device.PC10; EXT1_9 : GPIO_Point renames STM32.Device.PC11; EXT1_10 : GPIO_Point renames STM32.Device.PC12; EXT1_11 : GPIO_Point renames STM32.Device.PD2; EXT1_12 : GPIO_Point renames STM32.Device.PB5; EXT1_13 : GPIO_Point renames STM32.Device.PB6; EXT1_14 : GPIO_Point renames STM32.Device.PA6; EXT1_15 : GPIO_Point renames STM32.Device.PB7; EXT1_16 : GPIO_Point renames STM32.Device.PB8; EXT1_17 : GPIO_Point renames STM32.Device.PB9; EXT1_18 : GPIO_Point renames STM32.Device.PA5; EXT1_19 : GPIO_Point renames STM32.Device.PC0; EXT1_20 : GPIO_Point renames STM32.Device.PC1; EXT1_21 : GPIO_Point renames STM32.Device.PB0; EXT1_22 : GPIO_Point renames STM32.Device.PA7; -- EXT1_23 : VBAT EXT1_24 : GPIO_Point renames STM32.Device.PC13; -- EXT1_25 : NRST EXT1_26 : GPIO_Point renames STM32.Device.PB1; -- EXT2_1 : VDDA EXT2_2 : GPIO_Point renames STM32.Device.PC2; -- EXT2_3 : GNDA EXT2_4 : GPIO_Point renames STM32.Device.PA0; -- EXT2_5 : 3.3V -- EXT2_6 : GND EXT2_7 : GPIO_Point renames STM32.Device.PA2; EXT2_8 : GPIO_Point renames STM32.Device.PA1; EXT2_9 : GPIO_Point renames STM32.Device.PC3; EXT2_10 : GPIO_Point renames STM32.Device.PA3; EXT2_11 : GPIO_Point renames STM32.Device.PA4; EXT2_12 : GPIO_Point renames STM32.Device.PC4; EXT2_13 : GPIO_Point renames STM32.Device.PC5; EXT2_14 : GPIO_Point renames STM32.Device.PB10; EXT2_15 : GPIO_Point renames STM32.Device.PB11; EXT2_16 : GPIO_Point renames STM32.Device.PB13; EXT2_17 : GPIO_Point renames STM32.Device.PB12; EXT2_18 : GPIO_Point renames STM32.Device.PB14; EXT2_19 : GPIO_Point renames STM32.Device.PB15; EXT2_20 : GPIO_Point renames STM32.Device.PC6; EXT2_21 : GPIO_Point renames STM32.Device.PC7; EXT2_22 : GPIO_Point renames STM32.Device.PC8; -- EXT2_23 : VUSB EXT2_24 : GPIO_Point renames STM32.Device.PC9; -- EXT2_25 : GND -- EXT2_26 : VIN OSC32_IN : GPIO_Point renames STM32.Device.PC14; OSC32_OUT : GPIO_Point renames STM32.Device.PC15; OSC8M_IN : GPIO_Point renames STM32.Device.PD0; OSC8M_OUT : GPIO_Point renames STM32.Device.PD1; TMS : GPIO_Point renames STM32.Device.PA13; TCK : GPIO_Point renames STM32.Device.PA14; TDI : GPIO_Point renames STM32.Device.PA15; TDO : GPIO_Point renames STM32.Device.PB3; TRST : GPIO_Point renames STM32.Device.PB4; Button : GPIO_Point renames STM32.Device.PA0; User_LED : GPIO_Point renames STM32.Device.PC12; USB_DM : GPIO_Point renames STM32.Device.PA11; USB_DP : GPIO_Point renames STM32.Device.PA12; end STM32_H405;
with Ada.Containers.Doubly_Linked_Lists; use Ada.Containers; package Marble_Mania is package Nat_List is new Ada.Containers.Doubly_Linked_Lists (Natural); type List_Ptr is access all Nat_List.List; type Score_Count is mod 2**64; type Player_Scores is array (Positive range <>) of Score_Count; type Circle_Game (Players : Positive) is tagged record Round : Natural := 0; Current : Nat_List.Cursor; Scores : Player_Scores (1 .. Players) := (others => 0); Board : not null List_Ptr := new Nat_List.List; end record; procedure Start (Game : in out Circle_Game) with Pre => Game.Board.Length = 0, Post => Game.Board.Length = 1 and Game.Round = 1; procedure Play (Player : in Positive; Game : in out Circle_Game) with Pre => Player <= Game.Scores'Last and Game.Board.Length > 0, Post => Game'Old.Round + 1 = Game.Round; function Play_Until (Players : in Positive; Last_Marble : in Positive) return Score_Count; end Marble_Mania;
-- todo: initialize in several functions: initGPIO, initI2C, use HAL with HIL.GPIO; with HIL.Clock; with HIL.SPI; with HIL.UART; package body CPU is -- configures hardware registers procedure initialize is begin -- Configure GPIO HIL.Clock.configure; HIL.GPIO.configure; HIL.UART.configure; HIL.SPI.configure; -- HIL.I2C.initialize; end initialize; end CPU;
----------------------------------------------------------------------- -- jobs-tests -- Unit tests for AWA jobs -- Copyright (C) 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Log.Loggers; with Security.Contexts; with AWA.Tests.Helpers.Users; with AWA.Jobs.Modules; with AWA.Services.Contexts; package body AWA.Jobs.Services.Tests is package ASC renames AWA.Services.Contexts; My_Exception : exception; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Jobs.Services.Tests"); package Caller is new Util.Test_Caller (Test, "Jobs.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Jobs.Modules.Register", Test_Job_Schedule'Access); Caller.Add_Test (Suite, "Test AWA.Jobs.Schedule", Test_Job_Execute_Get_Status'Access); Caller.Add_Test (Suite, "Test AWA.Jobs.Get_Parameter", Test_Job_Execute_Get_Parameter'Access); Caller.Add_Test (Suite, "Test AWA.Jobs.Schedule with job exception", Test_Job_Execute_Exception'Access); Caller.Add_Test (Suite, "Test AWA.Jobs.Schedule with user context", Test_Job_Execute_Get_User'Access); end Add_Tests; procedure Work_1 (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is Msg : constant String := Job.Get_Parameter ("message"); Cnt : constant Natural := Job.Get_Parameter ("count", 0); begin Log.Info ("Execute work_1 {0}, count {1}", Msg, Natural'Image (Cnt)); end Work_1; procedure Work_2 (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is pragma Unreferenced (Job); begin Log.Info ("Execute work_2"); end Work_2; -- ------------------------------ -- Check the job status while the job is running. -- ------------------------------ procedure Work_Check_Status (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is use type AWA.Jobs.Models.Job_Status_Type; Status : constant AWA.Jobs.Models.Job_Status_Type := Job.Get_Status; begin Log.Info ("Execute work_check_status"); if Status /= AWA.Jobs.Models.RUNNING then Job.Set_Status (AWA.Jobs.Models.FAILED); Job.Set_Result ("result", "fail"); else Job.Set_Result ("result", "ok"); end if; end Work_Check_Status; -- ------------------------------ -- Check the job parameter while the job is running. -- ------------------------------ procedure Work_Check_Parameter (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is Count : constant Natural := Job.Get_Parameter ("count", 0); begin Log.Info ("Execute work_check_status"); if Count /= 1 then Job.Set_Status (AWA.Jobs.Models.FAILED); Job.Set_Result ("result", "fail"); else Job.Set_Result ("result", "ok"); end if; end Work_Check_Parameter; -- ------------------------------ -- Check the job raising an exception. -- ------------------------------ procedure Work_Check_Exception (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is begin raise My_Exception; end Work_Check_Exception; -- ------------------------------ -- Check the job is executed under the context of the user. -- ------------------------------ procedure Work_Check_User (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is use type ASC.Service_Context_Access; use type ADO.Identifier; Ctx : constant ASC.Service_Context_Access := ASC.Current; User : constant ADO.Identifier := ADO.Identifier (Job.Get_Parameter ("user", 0)); begin if Ctx = null then Job.Set_Status (AWA.Jobs.Models.FAILED); Job.Set_Result ("result", "fail-no-context"); elsif Ctx.Get_User.Is_Null then Job.Set_Status (AWA.Jobs.Models.FAILED); Job.Set_Result ("result", "fail-no-user"); elsif Ctx.Get_User.Get_Id /= User then Job.Set_Status (AWA.Jobs.Models.FAILED); Job.Set_Result ("result", "fail-bad-user"); else Job.Set_Status (AWA.Jobs.Models.TERMINATED); Job.Set_Result ("result", "ok"); end if; end Work_Check_User; -- ------------------------------ -- Wait for the job to be executed and verify its stats. -- ------------------------------ procedure Wait_Job (T : in out Test; Id : in ADO.Identifier; Expect : in AWA.Jobs.Models.Job_Status_Type) is use type AWA.Jobs.Models.Job_Status_Type; Context : AWA.Services.Contexts.Service_Context; Status : AWA.Jobs.Models.Job_Status_Type; begin Context.Set_Context (AWA.Tests.Get_Application, null); -- Wait for the job to be executed for I in 1 .. 20 loop delay 0.5; Status := Get_Job_Status (Id); if Status = AWA.Jobs.Models.TERMINATED then T.Assert (Status = Expect, "Job status is not terminated"); return; end if; if Status = AWA.Jobs.Models.FAILED then T.Assert (Status = Expect, "Job status is not terminated"); return; end if; end loop; T.Assert (Status = AWA.Jobs.Models.TERMINATED, "Job execution time out"); end Wait_Job; -- ------------------------------ -- Test the job factory. -- ------------------------------ procedure Run_Job (T : in out Test; Factory : in Job_Factory_Access; Id : out ADO.Identifier) is use type AWA.Jobs.Models.Job_Status_Type; use type ADO.Identifier; J : AWA.Jobs.Services.Job_Type; M : constant AWA.Jobs.Modules.Job_Module_Access := AWA.Jobs.Modules.Get_Job_Module; Context : AWA.Services.Contexts.Service_Context; begin Context.Set_Context (AWA.Tests.Get_Application, null); M.Register (Definition => Factory); J.Set_Parameter ("count", 1); Util.Tests.Assert_Equals (T, 1, J.Get_Parameter ("count", 0), "Invalid count param"); J.Set_Parameter ("message", "Hello"); Util.Tests.Assert_Equals (T, "Hello", J.Get_Parameter ("message"), "Invalid message param"); J.Schedule (Factory.all); T.Assert (J.Get_Status = AWA.Jobs.Models.SCHEDULED, "Job is not scheduled"); T.Assert (J.Get_Identifier /= ADO.NO_IDENTIFIER, "Job has an identified"); Id := J.Get_Identifier; end Run_Job; -- ------------------------------ -- Test the Get_Status operation within a job. -- ------------------------------ procedure Test_Job_Execute_Get_Status (T : in out Test) is Id : ADO.Identifier; begin Run_Job (T, Work_Check_Status_Definition.Factory, Id); Wait_Job (T, Id, AWA.Jobs.Models.TERMINATED); end Test_Job_Execute_Get_Status; -- ------------------------------ -- Test the Get_Parameter operation within a job. -- ------------------------------ procedure Test_Job_Execute_Get_Parameter (T : in out Test) is Id : ADO.Identifier; begin Run_Job (T, Work_Check_Parameter_Definition.Factory, Id); Wait_Job (T, Id, AWA.Jobs.Models.TERMINATED); end Test_Job_Execute_Get_Parameter; -- ------------------------------ -- Test the job that raise some exception. -- ------------------------------ procedure Test_Job_Execute_Exception (T : in out Test) is Id : ADO.Identifier; begin Run_Job (T, Work_Check_Exception_Definition.Factory, Id); Wait_Job (T, Id, AWA.Jobs.Models.FAILED); end Test_Job_Execute_Exception; -- ------------------------------ -- Test the job and verify that the job is executed under the user who created the job. -- ------------------------------ procedure Test_Job_Execute_Get_User (T : in out Test) is Id : ADO.Identifier; M : constant AWA.Jobs.Modules.Job_Module_Access := AWA.Jobs.Modules.Get_Job_Module; begin declare Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; J : AWA.Jobs.Services.Job_Type; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "test-job@test.com"); M.Register (Definition => Work_Check_User_Definition.Factory); J.Set_Parameter ("count", 1); Util.Tests.Assert_Equals (T, 1, J.Get_Parameter ("count", 0), "Invalid count param"); J.Set_Parameter ("user", Natural (Context.Get_User.Get_Id)); J.Schedule (Work_Check_User_Definition.Factory.all); Id := J.Get_Identifier; end; Wait_Job (T, Id, AWA.Jobs.Models.TERMINATED); end Test_Job_Execute_Get_User; -- ------------------------------ -- Test the job factory. -- ------------------------------ procedure Test_Job_Schedule (T : in out Test) is use type AWA.Jobs.Models.Job_Status_Type; J : AWA.Jobs.Services.Job_Type; M : constant AWA.Jobs.Modules.Job_Module_Access := AWA.Jobs.Modules.Get_Job_Module; Context : AWA.Services.Contexts.Service_Context; begin Context.Set_Context (AWA.Tests.Get_Application, null); M.Register (Definition => Services.Tests.Work_1_Definition.Factory); J.Set_Parameter ("count", 1); Util.Tests.Assert_Equals (T, 1, J.Get_Parameter ("count", 0), "Invalid count param"); J.Set_Parameter ("message", "Hello"); Util.Tests.Assert_Equals (T, "Hello", J.Get_Parameter ("message"), "Invalid message param"); J.Schedule (Work_1_Definition.Factory.all); T.Assert (J.Get_Status = AWA.Jobs.Models.SCHEDULED, "Job is not scheduled"); -- for I in 1 .. 10 loop delay 0.1; end loop; end Test_Job_Schedule; -- Execute the job. This operation must be implemented and should perform the work -- represented by the job. It should use the <tt>Get_Parameter</tt> function to retrieve -- the job parameter and it can use the <tt>Set_Result</tt> operation to save the result. overriding procedure Execute (Job : in out Test_Job) is begin null; end Execute; end AWA.Jobs.Services.Tests;
with gel.Sprite, gel.World, ada.unchecked_Deallocation; package body gel.Joint is function to_GEL (the_Joint : standard.physics.Joint.view) return gel.Joint.view is begin return gel.Joint.view (the_Joint.user_Data); end to_GEL; --------- --- Forge -- procedure define (Self : access Item; Sprite_A, Sprite_B : access gel.Sprite.item'class) is begin Self.Sprite_A := Sprite_A; Self.Sprite_B := Sprite_B; end define; procedure free (Self : in out View) is procedure deallocate is new ada.unchecked_Deallocation (Joint.item'Class, Joint.view); begin if Self /= null then Self.destroy; end if; deallocate (Self); end free; -------------- --- Attributes -- function Sprite_A (Self : in Item'Class) return access gel.Sprite.item'class is begin return Self.Sprite_A; end Sprite_A; function Sprite_B (Self : in Item'Class) return access gel.Sprite.item'class is begin return Self.Sprite_B; end Sprite_B; ---------- --- Hinges -- function local_Anchor_on_A (Self : in Item) return Vector_3 is begin return Self.local_Anchor_on_A; end local_Anchor_on_A; function local_Anchor_on_B (Self : in Item) return Vector_3 is begin return Self.local_Anchor_on_B; end local_Anchor_on_B; procedure local_Anchor_on_A_is (Self : out Item; Now : in Vector_3) is begin Self.local_Anchor_on_A := Now; if Self.Sprite_A.World /= null then Self.Sprite_A.World.set_local_Anchor_on_A (for_Joint => Self'unchecked_Access, To => Now); end if; end local_Anchor_on_A_is; procedure local_Anchor_on_B_is (Self : out Item; Now : in Vector_3) is begin Self.local_Anchor_on_B := Now; if Self.Sprite_B.World /= null then Self.Sprite_B.World.set_local_Anchor_on_B (for_Joint => Self'unchecked_Access, To => Now); end if; end local_Anchor_on_B_is; function reaction_Force (Self : in Item'Class) return Vector_3 is begin return Self.Physics.reaction_Force; end reaction_Force; function reaction_Torque (Self : in Item'Class) return Real is begin return Self.Physics.reaction_Torque; end reaction_Torque; end gel.Joint;
with System; package body Flash is FCTL1 : Unsigned_16 with Import, Address => System'To_Address (16#0128#); FCTL2 : Unsigned_16 with Import, Address => System'To_Address (16#012A#); FCTL3 : Unsigned_16 with Import, Address => System'To_Address (16#012C#); Flash_Memory : array (Unsigned_16 range 0 .. 32767) of Unsigned_16 with Import, Address => System'To_Address (0); procedure Init is begin FCTL2 := 16#A553#; end Init; procedure Unlock is begin FCTL3 := 16#A500#; end Unlock; pragma Linker_Section (Unlock, ".text.lower"); procedure Lock is begin FCTL1 := 16#A500#; FCTL3 := 16#A510#; end Lock; pragma Linker_Section (Lock, ".text.lower"); procedure Enable_Erase is begin FCTL1 := 16#A502#; end Enable_Erase; pragma Linker_Section (Enable_Erase, ".text.lower"); procedure Erase (Addr : Unsigned_16) is begin Enable_Erase; Write (Addr, 0); end Erase; pragma Linker_Section (Enable_Erase, ".text.lower"); procedure Enable_Write is begin FCTL1 := 16#A540#; end Enable_Write; pragma Linker_Section (Enable_Write, ".text.lower"); procedure Write (Addr : Unsigned_16; Value : Unsigned_16) is begin Flash_Memory (Addr / 2) := Value; end Write; pragma Linker_Section (Write, ".text.lower"); function Read (Addr : Unsigned_16) return Unsigned_16 is begin return Flash_Memory (Addr / 2); end Read; pragma Linker_Section (Read, ".text.lower"); procedure Wait_Until_Ready is begin while (FCTL3 and 2 ** 3) = 0 loop null; end loop; end Wait_Until_Ready; pragma Linker_Section (Read, ".text.lower"); end Flash;
-- EE3203A.ADA -- Grant of Unlimited Rights -- -- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687, -- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained -- unlimited rights in the software and documentation contained herein. -- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making -- this public release, the Government intends to confer upon all -- recipients unlimited rights equal to those held by the Government. -- These rights include rights to use, duplicate, release or disclose the -- released technical data and computer software in whole or in part, in -- any manner and for any purpose whatsoever, and to have or permit others -- to do so. -- -- DISCLAIMER -- -- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR -- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED -- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE -- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE -- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A -- PARTICULAR PURPOSE OF SAID MATERIAL. --* -- OBJECTIVE: -- CHECK THAT SET_INPUT AND SET_OUTPUT CAN BE USED, AND THAT THEY -- DO NOT REDEFINE OR CLOSE THE CORRESPONDING STANDARD FILES. -- APPLICABILITY CRITERIA: -- THIS TEST IS APPLICABLE ONLY TO IMPLEMENTATIONS WHICH SUPPORT -- TEXT FILES. -- PASS/FAIL CRITERIA: -- THIS TEST IS PASSED IF IT EXECUTES AND THE STANDARD OUTPUT FILE -- CONTAINS THE LINE "INITIAL TEXT OF STANDARD_OUTPUT". -- HISTORY: -- ABW 08/25/82 -- SPS 11/19/82 -- VKG 02/15/83 -- TBN 11/04/86 REVISED TEST TO OUTPUT A NOT_APPLICABLE -- RESULT WHEN FILES ARE NOT SUPPORTED. -- JLH 08/19/87 CORRECTED EXCEPTION HANDLING, REMOVED DEPENDENCE -- ON RESET, AND ADDED CHECKS FOR USE_ERROR ON DELETE. WITH REPORT; USE REPORT; WITH TEXT_IO; USE TEXT_IO; WITH CHECK_FILE; PROCEDURE EE3203A IS INCOMPLETE : EXCEPTION; FILE_IN, FILE_OUT : FILE_TYPE; LST : NATURAL; IN_STR : STRING (1 .. 50); BEGIN TEST ("EE3203A", "CHECK THAT SET_INPUT AND SET_OUTPUT " & "CAN BE USED, AND THAT CORRESPONDING " & "STANDARD FILES ARE UNCHANGED"); BEGIN CREATE (FILE_IN, OUT_FILE, LEGAL_FILE_NAME); EXCEPTION WHEN USE_ERROR => NOT_APPLICABLE ("USE_ERROR RAISED ON TEXT CREATE WITH " & "OUT_FILE MODE - 1"); RAISE INCOMPLETE; WHEN NAME_ERROR => NOT_APPLICABLE ("NAME_ERROR RAISED ON TEXT CREATE " & "WITH OUT_FILE MODE - 1"); RAISE INCOMPLETE; WHEN OTHERS => FAILED ("UNEXPECTED EXCEPTION RAISED ON TEXT CREATE"); RAISE INCOMPLETE; END; BEGIN CREATE (FILE_OUT, OUT_FILE, LEGAL_FILE_NAME(2)); EXCEPTION WHEN USE_ERROR => NOT_APPLICABLE ("USE_ERROR RAISED ON TEXT CREATE WITH " & "OUT_FILE MODE - 2"); RAISE INCOMPLETE; WHEN NAME_ERROR => NOT_APPLICABLE ("NAME_ERROR RAISED ON TEXT CREATE " & "WITH OUT_FILE MODE - 2"); RAISE INCOMPLETE; WHEN OTHERS => FAILED ("UNEXPECTED EXCEPTION RAISED ON TEXT CREATE"); RAISE INCOMPLETE; END; PUT (FILE_IN, "INITIAL TEXT OF FILE_IN"); PUT (FILE_OUT, "INITIAL TEXT OF FILE_OUT"); PUT ("INITIAL TEXT OF STANDARD_OUTPUT"); CLOSE (FILE_IN); BEGIN OPEN (FILE_IN, IN_FILE, LEGAL_FILE_NAME); EXCEPTION WHEN USE_ERROR => NOT_APPLICABLE ("USE_ERROR RAISED ON TEXT OPEN WITH " & "IN_FILE MODE"); RAISE INCOMPLETE; END; SET_INPUT (FILE_IN); SET_OUTPUT (FILE_OUT); IF NOT IS_OPEN (STANDARD_INPUT) THEN FAILED ("STANDARD_INPUT NOT OPEN"); END IF; IF NOT IS_OPEN (FILE_IN) THEN FAILED ("FILE_IN NOT OPEN"); END IF; IF NOT IS_OPEN (STANDARD_OUTPUT) THEN FAILED ("STANDARD_OUTPUT NOT OPEN"); END IF; IF NOT IS_OPEN (FILE_OUT) THEN FAILED ("FILE_OUT NOT OPEN"); END IF; NEW_LINE; PUT ("SECOND LINE OF OUTPUT"); GET_LINE (IN_STR, LST); IF IN_STR (1 .. LST) /= "INITIAL TEXT OF FILE_IN" THEN FAILED ("DEFAULT INPUT INCORRECT"); END IF; CHECK_FILE (FILE_IN, "INITIAL TEXT OF FILE_IN#@%"); SET_OUTPUT (FILE => STANDARD_OUTPUT); SET_INPUT (FILE => STANDARD_INPUT); CHECK_FILE (FILE_OUT, "INITIAL TEXT OF FILE_OUT#" & "SECOND LINE OF OUTPUT#@%"); SPECIAL_ACTION ("THE STANDARD OUTPUT FILE SHOULD CONTAIN " & "THE LINE : INITIAL TEXT OF STANDARD_OUTPUT"); BEGIN DELETE (FILE_IN); EXCEPTION WHEN USE_ERROR => NULL; END; BEGIN DELETE (FILE_OUT); EXCEPTION WHEN USE_ERROR => NULL; END; RESULT; EXCEPTION WHEN INCOMPLETE => RESULT; END EE3203A;
-- Score PIXAL le 07/10/2020 à 17:34 : 100% with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; -- Lire et écrire un tableau d'entiers. procedure Tableau_IO is Capacite: constant Integer := 10; -- Cette taille est arbitraire type T_TableauBrut is array (1..Capacite) of Integer; type T_Tableau is record Elements: T_TableauBrut; Taille: Integer; -- Invariant: 0 <= Taille and Taille <= Capacite; end record; --------------------[ Ne pas changer le code qui précède ]--------------------- procedure Lire (Tableau: out T_Tableau; Default: in Integer) is Indice: Integer; begin Tableau.Taille := 0; for J in 1..Capacite loop Tableau.Elements(J) := Default; end loop; Put("Indice (-1 pour arrêter) ? "); Get(Indice); while Indice /= -1 loop if Indice > Capacite or Indice < 1 then Put("Erreur : l'indice doit être entre 1 et "); Put(Capacite, 0); Put_Line("."); else Put("Valeur ? "); Get(Tableau.Elements(Indice)); if Indice > Tableau.Taille then Tableau.Taille := Indice; end if; end if; Put("Indice (-1 pour arrêter) ? "); Get(Indice); end loop; end Lire; procedure Ecrire (Tableau: in T_Tableau) is begin Put("["); for J in 1..Tableau.Taille loop if J > 1 then Put(", "); end if; Put(Tableau.Elements(J), 1); end loop; Put("]"); end Ecrire; ----[ Ne pas changer le code qui suit, sauf pour la question optionnelle ]---- Tab1: T_Tableau; -- Un tableau Defaut: Integer; -- Valeur par défaut begin -- Demander la valeur par défaut Put ("Valeur par défaut ? "); Get (Defaut); Lire (Tab1, Defaut); -- Afficher le tableau lu Put ("Tableau lu : "); Ecrire (Tab1); New_Line; end Tableau_IO;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2018 onox <denkpadje@gmail.com> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Text_IO; package body Package_9_Jobs is function Clone_Job (Job : Orka.Jobs.Parallel_Job_Ptr; Length : Positive) return Orka.Jobs.Dependency_Array is Object : constant Test_Parallel_Job := Test_Parallel_Job (Job.all); begin return Result : constant Orka.Jobs.Dependency_Array (1 .. Length) := (others => new Test_Parallel_Job'(Object)); end Clone_Job; overriding procedure Execute (Object : Test_Sequential_Job; Context : Orka.Jobs.Execution_Context'Class) is begin Ada.Text_IO.Put_Line ("Sequential job " & Object.ID'Image); end Execute; overriding procedure Execute (Object : Test_Parallel_Job; Context : Orka.Jobs.Execution_Context'Class; From, To : Positive) is begin Ada.Text_IO.Put_Line ("Parallel job (" & From'Image & " .. " & To'Image & ")"); end Execute; end Package_9_Jobs;
with Ada.Containers.Array_Sorting; with System.Long_Long_Integer_Types; package body Ada.Containers.Generic_Array_Access_Types is subtype Word_Integer is System.Long_Long_Integer_Types.Word_Integer; -- implementation function Length (Container : Array_Access) return Count_Type is begin if Container = null then return 0; else return Container'Length; end if; end Length; procedure Set_Length ( Container : in out Array_Access; Length : Count_Type) is begin if Container = null then if Length > 0 then Container := new Array_Type ( Index_Type'First .. Index_Type'First + Index_Type'Base (Length) - 1); end if; elsif Length = 0 then Free (Container); else declare Old_Length : constant Count_Type := Container'Length; begin if Length < Old_Length then declare S : Array_Access := Container; begin Container := new Array_Type'( S (S'First .. S'First + Index_Type'Base (Length) - 1)); Free (S); end; elsif Length > Old_Length then declare S : Array_Access := Container; begin Container := new Array_Type ( S'First .. S'First + Index_Type'Base (Length) - 1); Container (S'Range) := S.all; Free (S); end; end if; end; end if; end Set_Length; procedure Assign (Target : in out Array_Access; Source : Array_Access) is begin if Target /= Source then Free (Target); if Source /= null and then Source'Length > 0 then Target := new Array_Type'(Source.all); end if; end if; end Assign; procedure Move ( Target : in out Array_Access; Source : in out Array_Access) is begin if Target /= Source then Free (Target); Target := Source; Source := null; end if; end Move; procedure Insert ( Container : in out Array_Access; Before : Extended_Index; New_Item : Array_Type) is pragma Check (Pre, Check => Before in First_Index (Container) .. Last_Index (Container) + 1 or else raise Constraint_Error); begin if New_Item'Length > 0 then if Container = null then declare subtype T is Array_Type (Before .. Before + (New_Item'Length - 1)); begin Container := new Array_Type'(T (New_Item)); end; else declare New_Item_Length : constant Index_Type'Base := New_Item'Length; Following : constant Index_Type := Before + New_Item_Length; S : Array_Access := Container; begin Container := new Array_Type (S'First .. S'Last + New_Item_Length); Container (S'First .. Before - 1) := S (S'First .. Before - 1); Container (Before .. Following - 1) := New_Item; Container (Following .. Container'Last) := S (Before .. S'Last); Free (S); end; end if; end if; end Insert; procedure Insert ( Container : in out Array_Access; Before : Extended_Index; New_Item : Array_Access) is pragma Check (Pre, Check => Before in First_Index (Container) .. Last_Index (Container) + 1 or else raise Constraint_Error); begin if New_Item /= null then Insert (Container, Before, New_Item.all); end if; end Insert; procedure Insert ( Container : in out Array_Access; Before : Extended_Index; New_Item : Element_Type; Count : Count_Type := 1) is begin Insert ( Container, Before, -- checking Constraint_Error Count); for I in Before .. Before + Index_Type'Base (Count) - 1 loop Container (I) := New_Item; end loop; end Insert; procedure Insert ( Container : in out Array_Access; Before : Extended_Index; Count : Count_Type := 1) is pragma Check (Pre, Check => Before in First_Index (Container) .. Last_Index (Container) + 1 or else raise Constraint_Error); begin if Count > 0 then if Container = null then Container := new Array_Type (Before .. Before + Index_Type'Base (Count) - 1); else declare Following : constant Index_Type := Before + Index_Type'Base (Count); S : Array_Access := Container; begin Container := new Array_Type (S'First .. S'Last + Index_Type'Base (Count)); Container (S'First .. Before - 1) := S (S'First .. Before - 1); Container (Following .. Container'Last) := S (Before .. S'Last); Free (S); end; end if; end if; end Insert; procedure Prepend ( Container : in out Array_Access; New_Item : Array_Type) is begin Insert (Container, First_Index (Container), New_Item); end Prepend; procedure Prepend ( Container : in out Array_Access; New_Item : Array_Access) is begin Insert (Container, First_Index (Container), New_Item); end Prepend; procedure Prepend ( Container : in out Array_Access; New_Item : Element_Type; Count : Count_Type := 1) is begin Insert (Container, First_Index (Container), New_Item, Count); end Prepend; procedure Prepend ( Container : in out Array_Access; Count : Count_Type := 1) is begin Insert (Container, First_Index (Container), Count); end Prepend; procedure Append ( Container : in out Array_Access; New_Item : Array_Type) is begin Insert (Container, Last_Index (Container) + 1, New_Item); end Append; procedure Append ( Container : in out Array_Access; New_Item : Array_Access) is begin Insert (Container, Last_Index (Container) + 1, New_Item); end Append; procedure Append ( Container : in out Array_Access; New_Item : Element_Type; Count : Count_Type := 1) is begin Insert (Container, Last_Index (Container) + 1, New_Item, Count); end Append; procedure Append ( Container : in out Array_Access; Count : Count_Type := 1) is begin Insert (Container, Last_Index (Container) + 1, Count); end Append; procedure Delete ( Container : in out Array_Access; Index : Extended_Index; Count : Count_Type := 1) is pragma Check (Pre, Check => (Index >= First_Index (Container) and then Index + Index_Type'Base (Count) - 1 <= Last_Index (Container)) or else raise Constraint_Error); begin if Count > 0 then if Index = Container'First and then Count = Container'Length then Free (Container); else declare Following : constant Index_Type := Index + Index_Type'Base (Count); S : Array_Access := Container; begin Container := new Array_Type (S'First .. S'Last - Index_Type'Base (Count)); Container (S'First .. Index - 1) := S (S'First .. Index - 1); Container (Index .. Container'Last) := S (Following .. S'Last); Free (S); end; end if; end if; end Delete; procedure Delete_First ( Container : in out Array_Access; Count : Count_Type := 1) is begin Delete (Container, Container'First, Count); end Delete_First; procedure Delete_Last ( Container : in out Array_Access; Count : Count_Type := 1) is begin Delete (Container, Container'Last - Index_Type'Base (Count) + 1, Count); end Delete_Last; procedure Swap (Container : in out Array_Access; I, J : Index_Type) is pragma Check (Pre, Check => (I in First_Index (Container) .. Last_Index (Container) and then J in First_Index (Container) .. Last_Index (Container)) or else raise Constraint_Error); pragma Unmodified (Container); begin if I /= J then declare Temp : constant Element_Type := Container (I); begin Container.all (I) := Container (J); Container.all (J) := Temp; end; end if; end Swap; function First_Index (Container : Array_Access) return Index_Type is begin if Container = null then return Index_Type'First; else return Container'First; end if; end First_Index; function Last_Index (Container : Array_Access) return Extended_Index is begin if Container = null then return Index_Type'First - 1; else return Container'Last; end if; end Last_Index; package body Generic_Reversing is type Context_Type is limited record Container : Array_Access; end record; pragma Suppress_Initialization (Context_Type); procedure Swap (I, J : Word_Integer; Params : System.Address); procedure Swap (I, J : Word_Integer; Params : System.Address) is Context : Context_Type; for Context'Address use Params; begin Swap (Context.Container, Index_Type'Val (I), Index_Type'Val (J)); end Swap; -- implementation procedure Reverse_Elements (Container : in out Array_Access) is pragma Unmodified (Container); Context : aliased Context_Type := (Container => Container); begin if Container /= null then Array_Sorting.In_Place_Reverse ( Index_Type'Pos (Container'First), Index_Type'Pos (Container'Last), Context'Address, Swap => Swap'Access); end if; end Reverse_Elements; procedure Reverse_Rotate_Elements ( Container : in out Array_Access; Before : Extended_Index) is pragma Check (Pre, Check => Before in First_Index (Container) .. Last_Index (Container) + 1 or else raise Constraint_Error); pragma Unmodified (Container); Context : aliased Context_Type := (Container => Container); begin if Container /= null then Array_Sorting.Reverse_Rotate ( Index_Type'Pos (Container'First), Index_Type'Pos (Before), Index_Type'Pos (Container'Last), Context'Address, Swap => Swap'Access); end if; end Reverse_Rotate_Elements; procedure Juggling_Rotate_Elements ( Container : in out Array_Access; Before : Extended_Index) is pragma Check (Pre, Check => Before in First_Index (Container) .. Last_Index (Container) + 1 or else raise Constraint_Error); pragma Unmodified (Container); Context : aliased Context_Type := (Container => Container); begin if Container /= null then Array_Sorting.Juggling_Rotate ( Index_Type'Pos (Container'First), Index_Type'Pos (Before), Index_Type'Pos (Container'Last), Context'Address, Swap => Swap'Access); end if; end Juggling_Rotate_Elements; end Generic_Reversing; package body Generic_Sorting is type Context_Type is limited record Container : Array_Access; end record; pragma Suppress_Initialization (Context_Type); function LT (Left, Right : Word_Integer; Params : System.Address) return Boolean; function LT (Left, Right : Word_Integer; Params : System.Address) return Boolean is Context : Context_Type; for Context'Address use Params; begin return Context.Container (Index_Type'Val (Left)) < Context.Container (Index_Type'Val (Right)); end LT; procedure Swap (I, J : Word_Integer; Params : System.Address); procedure Swap (I, J : Word_Integer; Params : System.Address) is Context : Context_Type; for Context'Address use Params; begin Swap (Context.Container, Index_Type'Val (I), Index_Type'Val (J)); end Swap; -- implementation function Is_Sorted (Container : Array_Access) return Boolean is Context : aliased Context_Type := (Container => Container); begin return Container = null or else Array_Sorting.Is_Sorted ( Index_Type'Pos (Container'First), Index_Type'Pos (Container'Last), Context'Address, LT => LT'Access); end Is_Sorted; procedure Insertion_Sort (Container : in out Array_Access) is pragma Unmodified (Container); Context : aliased Context_Type := (Container => Container); begin if Container /= null then Array_Sorting.Insertion_Sort ( Index_Type'Pos (Container'First), Index_Type'Pos (Container'Last), Context'Address, LT => LT'Access, Swap => Swap'Access); end if; end Insertion_Sort; procedure Merge_Sort (Container : in out Array_Access) is pragma Unmodified (Container); Context : aliased Context_Type := (Container => Container); begin if Container /= null then Array_Sorting.In_Place_Merge_Sort ( Index_Type'Pos (Container'First), Index_Type'Pos (Container'Last), Context'Address, LT => LT'Access, Swap => Swap'Access); end if; end Merge_Sort; procedure Merge ( Target : in out Array_Access; Source : in out Array_Access) is begin if Target = null then Move (Target, Source); else declare Before : constant Index_Type'Base := Target'Last + 1; begin Insert (Target, Before, Source); Free (Source); declare Context : aliased Context_Type := (Container => Target); begin Array_Sorting.In_Place_Merge ( Index_Type'Pos (Target'First), Index_Type'Pos (Before), Index_Type'Pos (Target'Last), Context'Address, LT => LT'Access, Swap => Swap'Access); end; end; end if; end Merge; end Generic_Sorting; procedure Assign (Target : in out Array_Access; Source : New_Array) is begin Free (Target); Target := Array_Access (Source); end Assign; package body Operators is function Start ( Left : Array_Access; Right : Element_Type; Space : Count_Type) return New_Array_1; function Start ( Left : Array_Access; Right : Element_Type; Space : Count_Type) return New_Array_1 is Data : Array_Access; Last : Extended_Index; begin if Left = null then Data := new Array_Type ( Index_Type'First .. Index_Type'First + Index_Type'Base (Space)); Last := Index_Type'First; Data (Last) := Right; else Data := new Array_Type ( Left'First .. Left'Last + 1 + Index_Type'Base (Space)); Last := Left'Last + 1; Data (Left'Range) := Left.all; Data (Last) := Right; end if; return (Data => Data, Last => Last); end Start; function Step ( Left : New_Array_1; Right : Element_Type; Space : Count_Type) return New_Array_1; function Step ( Left : New_Array_1; Right : Element_Type; Space : Count_Type) return New_Array_1 is Data : Array_Access; Last : Extended_Index; begin if Left.Last + 1 <= Left.Data'Last then Data := Left.Data; Last := Left.Last + 1; Left.Data (Last) := Right; else Data := new Array_Type ( Left.Data'First .. Left.Last + 1 + Index_Type'Base (Space)); Last := Left.Last + 1; Data (Left.Data'Range) := Left.Data.all; Data (Last) := Right; declare Left_Data : Array_Access := Left.Data; begin Free (Left_Data); end; end if; return (Data => Data, Last => Last); end Step; -- implementation function "&" (Left : Array_Access; Right : Element_Type) return New_Array is begin return New_Array (Start (Left, Right, Space => 0).Data); end "&"; function "&" (Left : New_Array_1; Right : Element_Type) return New_Array is Data : Array_Access := Left.Data; begin if Left.Last + 1 = Data'Last then Data (Data'Last) := Right; return New_Array (Data); else declare Result : constant New_Array := new Array_Type (Data'First .. Data'Last + 1); begin Result (Data'Range) := Data.all; Result (Data'Last + 1) := Right; Free (Data); return Result; end; end if; end "&"; function "&" (Left : Array_Access; Right : Element_Type) return New_Array_1 is begin return Start (Left, Right, Space => 1); end "&"; function "&" (Left : New_Array_2; Right : Element_Type) return New_Array_1 is begin return Step (New_Array_1 (Left), Right, Space => 1); end "&"; function "&" (Left : Array_Access; Right : Element_Type) return New_Array_2 is begin return New_Array_2 (Start (Left, Right, Space => 2)); end "&"; end Operators; end Ada.Containers.Generic_Array_Access_Types;
----------------------------------------------------------------------- -- druss-gateways -- Gateway management -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Vectors; with Ada.Strings.Hash; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Properties; with Util.Refs; with Bbox.API; package Druss.Gateways is Not_Found : exception; type State_Type is (IDLE, READY, BUSY); protected type Gateway_State is function Get_State return State_Type; private State : State_Type := IDLE; end Gateway_State; type Gateway_Type is limited new Util.Refs.Ref_Entity with record -- Gateway IP address. Ip : Ada.Strings.Unbounded.Unbounded_String; -- API password. Passwd : Ada.Strings.Unbounded.Unbounded_String; -- The Bbox serial number. Serial : Ada.Strings.Unbounded.Unbounded_String; -- Directory that contains the images. Images : Ada.Strings.Unbounded.Unbounded_String; -- Whether the gateway entry is enabled or not. Enable : Boolean := True; -- The gateway state. State : Gateway_State; -- Current WAN information (from api/v1/wan). Wan : Util.Properties.Manager; -- Current LAN information (from api/v1/lan). Lan : Util.Properties.Manager; -- Wireless information (From api/v1/wireless). Wifi : Util.Properties.Manager; -- Voip information (From api/v1/voip). Voip : Util.Properties.Manager; -- IPtv information (From api/v1/iptv). IPtv : Util.Properties.Manager; -- Hosts information (From api/v1/hosts). Hosts : Util.Properties.Manager; -- Current Device information (from api/v1/device). Device : Util.Properties.Manager; -- The Bbox API client. Client : Bbox.API.Client_Type; end record; type Gateway_Type_Access is access all Gateway_Type; -- Refresh the information by using the Bbox API. procedure Refresh (Gateway : in out Gateway_Type); package Gateway_Refs is new Util.Refs.References (Element_Type => Gateway_Type, Element_Access => Gateway_Type_Access); subtype Gateway_Ref is Gateway_Refs.Ref; function "=" (Left, Right : in Gateway_Ref) return Boolean; package Gateway_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Gateway_Ref, "=" => "="); subtype Gateway_Vector is Gateway_Vectors.Vector; subtype Gateway_Cursor is Gateway_Vectors.Cursor; package Gateway_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Gateway_Ref, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); -- Initalize the list of gateways from the property list. procedure Initialize (Config : in Util.Properties.Manager; List : in out Gateway_Vector); -- Save the list of gateways. procedure Save_Gateways (Config : in out Util.Properties.Manager; List : in Druss.Gateways.Gateway_Vector); -- Refresh the information by using the Bbox API. procedure Refresh (Gateway : in Gateway_Ref) with pre => not Gateway.Is_Null; type Iterate_Type is (ITER_ALL, ITER_ENABLE, ITER_DISABLE); -- Iterate over the list of gateways and execute the <tt>Process</tt> procedure. procedure Iterate (List : in Gateway_Vector; Mode : in Iterate_Type := ITER_ALL; Process : not null access procedure (G : in out Gateway_Type)); -- Find the gateway with the given IP address. function Find_IP (List : in Gateway_Vector; IP : in String) return Gateway_Ref; end Druss.Gateways;
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- XML Processor -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2013-2014, Vadim Godunko <vgodunko@gmail.com> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with Matreshka.DOM_Documents; with Matreshka.DOM_Nodes; with XML.DOM.Attributes; with XML.DOM.Elements; with XML.DOM.Texts; package body Matreshka.DOM_Builders is procedure Push (Self : in out DOM_Builder'Class); procedure Pop (Self : in out DOM_Builder'Class); ---------------- -- Characters -- ---------------- overriding procedure Characters (Self : in out DOM_Builder; Text : League.Strings.Universal_String; Success : in out Boolean) is Aux : XML.DOM.Texts.DOM_Text_Access := Self.Document.Create_Text_Node (Text); begin Self.Current.Append_Child (XML.DOM.Nodes.DOM_Node_Access (Aux)); -- XML.DOM.Nodes.Dereference (XML.DOM.Nodes.DOM_Node_Access (Aux)); end Characters; ----------------- -- End_Element -- ----------------- overriding procedure End_Element (Self : in out DOM_Builder; Namespace_URI : League.Strings.Universal_String; Local_Name : League.Strings.Universal_String; Qualified_Name : League.Strings.Universal_String; Success : in out Boolean) is begin Self.Pop; end End_Element; ------------------ -- Error_String -- ------------------ overriding function Error_String (Self : DOM_Builder) return League.Strings.Universal_String is begin return League.Strings.Empty_Universal_String; end Error_String; ------------------ -- Get_Document -- ------------------ function Get_Document (Self : DOM_Builder'Class) return XML.DOM.Documents.DOM_Document_Access is begin return Self.Document; end Get_Document; --------- -- Pop -- --------- procedure Pop (Self : in out DOM_Builder'Class) is begin Self.Current := Self.Parent; if not Self.Stack.Is_Empty then Self.Parent := Self.Stack.Last_Element; Self.Stack.Delete_Last; else Self.Parent := null; end if; end Pop; ---------- -- Push -- ---------- procedure Push (Self : in out DOM_Builder'Class) is begin Self.Stack.Append (Self.Parent); Self.Parent := Self.Current; Self.Current := null; end Push; ------------------ -- Set_Document -- ------------------ procedure Set_Document (Self : in out DOM_Builder'Class; Document : not null XML.DOM.Documents.DOM_Document_Access) is begin Self.Document := Document; end Set_Document; -------------------- -- Start_Document -- -------------------- overriding procedure Start_Document (Self : in out DOM_Builder; Success : in out Boolean) is use type XML.DOM.Documents.DOM_Document_Access; Document : Matreshka.DOM_Nodes.Document_Access; begin if Self.Document = null then -- Create new document when it was not specified by application. Document := new Matreshka.DOM_Documents.Document_Node; Matreshka.DOM_Documents.Constructors.Initialize (Document); Self.Document := XML.DOM.Documents.DOM_Document_Access (Document); end if; Self.Current := XML.DOM.Nodes.DOM_Node_Access (Self.Document); end Start_Document; ------------------- -- Start_Element -- ------------------- overriding procedure Start_Element (Self : in out DOM_Builder; Namespace_URI : League.Strings.Universal_String; Local_Name : League.Strings.Universal_String; Qualified_Name : League.Strings.Universal_String; Attributes : XML.SAX.Attributes.SAX_Attributes; Success : in out Boolean) is Element : XML.DOM.Elements.DOM_Element_Access; Attribute : XML.DOM.Attributes.DOM_Attribute_Access; begin Self.Push; if Local_Name.Is_Empty then raise Program_Error; else Element := Self.Document.Create_Element_NS (Namespace_URI, Qualified_Name); Self.Current := XML.DOM.Nodes.DOM_Node_Access (Element); Self.Parent.Append_Child (Self.Current); -- XML.DOM.Nodes.Dereference (XML.DOM.Nodes.DOM_Node_Access (Element)); end if; -- Process attributes. for J in 1 .. Attributes.Length loop if Attributes.Local_Name (J).Is_Empty then raise Program_Error; else Attribute := Self.Document.Create_Attribute_NS (Attributes.Namespace_URI (J), Attributes.Qualified_Name (J)); XML.DOM.Elements.DOM_Element_Access (Self.Current).Set_Attribute_Node_NS (Attribute); Attribute.Set_Value (Attributes.Value (J)); -- XML.DOM.Nodes.Dereference -- (XML.DOM.Nodes.DOM_Node_Access (Attribute)); end if; end loop; end Start_Element; end Matreshka.DOM_Builders;
package CSS.Analysis.Parser.Parser_Tokens is subtype yystype is CSS.Analysis.Parser.YYstype; YYLVal, YYVal : YYSType; type Token is (END_OF_INPUT, ERROR, R_PROPERTY, R_DEF_NAME, R_IDENT, R_NAME, R_DEFINE, R_FOLLOW, R_ANY, R_NUM, '(', ')', '{', '}', '[', ']', '=', '|', '!', '?', '#', '+', '*', ',', '/', S); Syntax_Error : exception; end CSS.Analysis.Parser.Parser_Tokens;
with System; private with Ada.Synchronous_Task_Control; private with ACO.Utils.DS.Generic_Queue; generic type Item_Type is private; Maximum_Nof_Items : Positive; package ACO.Utils.DS.Generic_Protected_Queue is -- A protected queue pragma Preelaborate; type Protected_Queue (Ceiling : System.Priority) is tagged limited private; procedure Put_Blocking (This : in out Protected_Queue; Item : in Item_Type); procedure Put (This : in out Protected_Queue; Item : in Item_Type; Success : out Boolean); procedure Get_Blocking (This : in out Protected_Queue; Item : out Item_Type); procedure Get (This : in out Protected_Queue; Item : out Item_Type) with Pre => not This.Is_Empty; function Count (This : Protected_Queue) return Natural; function Is_Empty (This : Protected_Queue) return Boolean; function Is_Full (This : Protected_Queue) return Boolean; private package Q is new ACO.Utils.DS.Generic_Queue (Item_Type); protected type Buffer_Type (Ceiling : System.Priority) is procedure Put (Item : in Item_Type; Success : out Boolean); procedure Get (Item : out Item_Type; Success : out Boolean); function Nof_Items return Natural; private pragma Priority (Ceiling); Queue : Q.Queue (Max_Nof_Items => Maximum_Nof_Items); end Buffer_Type; type Protected_Queue (Ceiling : System.Priority) is tagged limited record Buffer : Buffer_Type (Ceiling); Non_Full : Ada.Synchronous_Task_Control.Suspension_Object; Non_Empty : Ada.Synchronous_Task_Control.Suspension_Object; end record; end ACO.Utils.DS.Generic_Protected_Queue;