content
stringlengths
23
1.05M
-- part of AdaYaml, (c) 2017 Felix Krause -- released under the terms of the MIT license, see the file "copying.txt" with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Text.Pool; with Yaml.Events.Context; package Yaml.Transformator.Annotation is type Node_Context_Type is (Document_Root, Sequence_Item, Mapping_Key, Mapping_Value, Parameter_Item); -- constructs an instance of an annotation transformator. parameters: -- Pool: the text pool to use for creating new scalar events. -- Node_Context: describes the surroundings of the annotation occurrence -- inside the event stream. -- Processor_Context: current alias targets. -- Swallowes_Previous: may only be True in two cases: -- 1. Node_Context is Document_Root. in this case, the previous -- Document_Start as well as the succeeding Document_End event is -- swallowed. -- 2. Node_Context is Mapping_Value. in this case, the previous scalar -- mapping key is swallowed. if the previous mapping key was not a -- scalar, an Annotation_Error will be raised by the annotation -- processor. type Constructor is not null access function (Pool : Text.Pool.Reference; Node_Context : Node_Context_Type; Processor_Context : Events.Context.Reference; Swallows_Previous : out Boolean) return not null Pointer; package Maps is new Ada.Containers.Indefinite_Hashed_Maps (String, Constructor, Ada.Strings.Hash, Standard."="); Map : Maps.Map; end Yaml.Transformator.Annotation;
----------------------------------------------------------------------- -- gen-integration-tests -- Tests for integration -- Copyright (C) 2012, 2013, 2014, 2016, 2017, 2018, 2021 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Tests; package Gen.Integration.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Execute the command and get the output in a string. procedure Execute (T : in out Test; Command : in String; Result : out Ada.Strings.Unbounded.Unbounded_String; Status : in Natural := 0); -- Test dynamo create-project command. procedure Test_Create_Project (T : in out Test); -- Test dynamo create-project command --ado. procedure Test_Create_ADO_Project (T : in out Test); -- Test dynamo create-project command --gtk. procedure Test_Create_GTK_Project (T : in out Test); -- Test dynamo create-project command --lib. procedure Test_Create_Lib_Project (T : in out Test); -- Test project configure. procedure Test_Configure (T : in out Test); -- Test propset command. procedure Test_Change_Property (T : in out Test); -- Test add-module command. procedure Test_Add_Module (T : in out Test); -- Test add-model command. procedure Test_Add_Model (T : in out Test); -- Test add-module-operation command. procedure Test_Add_Module_Operation (T : in out Test); -- Test add-service command. procedure Test_Add_Service (T : in out Test); -- Test add-query command. procedure Test_Add_Query (T : in out Test); -- Test add-page command. procedure Test_Add_Page (T : in out Test); -- Test add-layout command. procedure Test_Add_Layout (T : in out Test); -- Test add-ajax-form command. procedure Test_Add_Ajax_Form (T : in out Test); -- Test generate command. procedure Test_Generate (T : in out Test); -- Test help command. procedure Test_Help (T : in out Test); -- Test dist command. procedure Test_Dist (T : in out Test); -- Test dist with exclude support command. procedure Test_Dist_Exclude (T : in out Test); -- Test dist command. procedure Test_Info (T : in out Test); -- Test build-doc command. procedure Test_Build_Doc (T : in out Test); -- Test build-doc command with -pandoc. procedure Test_Build_Pandoc (T : in out Test); -- Test generate command with Hibernate XML mapping files. procedure Test_Generate_Hibernate (T : in out Test); -- Test generate command (XMI enum). procedure Test_Generate_XMI_Enum (T : in out Test); -- Test generate command (XMI Ada Bean). procedure Test_Generate_XMI_Bean (T : in out Test); -- Test generate command (XMI Ada Bean with inheritance). procedure Test_Generate_XMI_Bean_Table (T : in out Test); -- Test generate command (XMI Ada Table). procedure Test_Generate_XMI_Table (T : in out Test); -- Test generate command (XMI Associations between Tables). procedure Test_Generate_XMI_Association (T : in out Test); -- Test generate command (XMI Datatype). procedure Test_Generate_XMI_Datatype (T : in out Test); -- Test generate command using the ArgoUML file directly (runs unzip -cq and parse the output). procedure Test_Generate_Zargo_Association (T : in out Test); -- Test UML with several tables that have dependencies between each of them (non circular). procedure Test_Generate_Zargo_Dependencies (T : in out Test); -- Test UML with several tables in several packages (non circular). procedure Test_Generate_Zargo_Packages (T : in out Test); -- Test UML with serialization code. procedure Test_Generate_Zargo_Serialization (T : in out Test); -- Test UML with several errors in the UML model. procedure Test_Generate_Zargo_Errors (T : in out Test); -- Test GNAT compilation of the final project. procedure Test_Build (T : in out Test); -- Test GNAT compilation of the generated model files. procedure Test_Build_Model (T : in out Test); end Gen.Integration.Tests;
-- RUN: %llvmgcc -c %s procedure Array_Constructor is A : array (Integer range <>) of Boolean := (True, False); begin null; end;
with Ada.Text_IO; use Ada.Text_IO; procedure Reverse_Video is Rev_Video : String := Ascii.ESC & "[7m"; Norm_Video : String := Ascii.ESC & "[m"; begin Put (Rev_Video & "Reversed"); Put (Norm_Video & " Normal"); end Reverse_Video;
----------------------------------------------------------------------- -- wiki-filters-toc -- Filter for the creation of Table Of Contents -- Copyright (C) 2016, 2018, 2020 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Fixed; with Wiki.Nodes.Lists; package body Wiki.Filters.TOC is -- ------------------------------ -- Add a text content with the given format to the document. -- ------------------------------ overriding procedure Add_Text (Filter : in out TOC_Filter; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map) is use Ada.Strings.Wide_Wide_Fixed; First : Natural := Text'First; Pos : Natural; begin while First <= Text'Last loop Pos := Index (Text (First .. Text'Last), "__TOC__"); if Pos > 0 then Filter_Type (Filter).Add_Text (Document, Text (First .. Pos - 1), Format); Filter.Add_Node (Document, Wiki.Nodes.N_TOC_DISPLAY); First := Pos + 7; else Pos := Index (Text (First .. Text'Last), "__NOTOC__"); if Pos > 0 then Filter_Type (Filter).Add_Text (Document, Text (First .. Pos - 1), Format); Document.Hide_TOC; First := Pos + 9; else Filter_Type (Filter).Add_Text (Document, Text (First .. Text'Last), Format); exit; end if; end if; end loop; end Add_Text; -- ------------------------------ -- Add a section header with the given level in the document. -- ------------------------------ overriding procedure Add_Header (Filter : in out TOC_Filter; Document : in out Wiki.Documents.Document; Header : in Wiki.Strings.WString; Level : in Natural) is T : Wiki.Nodes.Lists.Node_List_Ref; begin Document.Get_TOC (T); Wiki.Nodes.Lists.Append (T, new Wiki.Nodes.Node_Type '(Kind => Wiki.Nodes.N_TOC_ENTRY, Len => Header'Length, Header => Header, Parent => null, Level => Level)); Filter_Type (Filter).Add_Header (Document, Header, Level); end Add_Header; end Wiki.Filters.TOC;
-- { dg-do compile } -- { dg-options "-gnatws" } with Uninit_Array_Pkg; use Uninit_Array_Pkg; package body Uninit_Array is function F1 return Integer; pragma Inline_Always (F1); function F1 return Integer is Var : Arr; begin return F (Var(Var'First(1))); end; function F2 return Integer is begin return F1; end; end Uninit_Array;
with Ada.Numerics.Float_Random; with Ada.Containers.Vectors; use Ada.Containers; with Ada.Numerics.Generic_Elementary_Functions; package MathUtils is pragma Elaborate_Body(MathUtils); pragma Assertion_Policy (Pre => Check, Post => Check, Type_Invariant => Check); package Float_Vec is new Ada.Containers.Vectors(Index_Type => Positive, Element_Type => Float); package F is new Ada.Numerics.Generic_Elementary_Functions(Float_Type => Float); subtype Vector is Float_Vec.Vector; function rand01 return Float; function rand(min, max: Float) return Float with Pre => min < max; function mse(a, b: in Vector) return Float with Pre => a.Length = b.Length and b.Length > 0; function logLoss(target, predictions: in Vector) return Float with Pre => target.Length = predictions.Length and target.Length > 0; procedure multiply(vec: in out Vector; value: Float); procedure softmax(vec: in out Vector) with Pre => vec.Length /= 0; procedure print(vec: in Vector); private gen: Ada.Numerics.Float_Random.Generator; end MathUtils;
package Chat -- -- Provides a namespace for the chat family. -- is pragma Pure; end Chat;
package OpenAL.Context.Error is type Error_t is (No_Error, Invalid_Device, Invalid_Context, Invalid_Enumeration, Invalid_Value, Out_Of_Memory, Unknown_Error); -- proc_map : alcGetError function Get_Error (Device : in Device_t) return Error_t; private function Map_Constant_To_Error (Error : in Types.Enumeration_t) return Error_t; end OpenAL.Context.Error;
-- SPDX-License-Identifier: MIT -- -- Copyright (c) 2009 - 2018 Gautier de Montmollin -- Copyright (c) 2019 onox <denkpadje@gmail.com> -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. with Ada.Calendar.Formatting; with Ada.Calendar.Time_Zones; with Ada.Characters.Handling; with Ada.Command_Line; with Ada.Directories; with Ada.Streams; with Ada.Strings.Fixed; with Ada.Strings.Unbounded; with Ada.Text_IO; with DCF.Streams.Calendar; with DCF.Unzip.Streams; with DCF.Zip; use Ada.Command_Line; use Ada.Text_IO; procedure UnzipDCF is package Dirs renames Ada.Directories; package SU renames Ada.Strings.Unbounded; List_Files : Boolean := False; Test_Data : Boolean := False; Comment : Boolean := False; Quiet : Boolean := False; No_Directories : Boolean := False; Lower_Case : Boolean := False; Last_Option : Natural := 0; Extraction_Directory : SU.Unbounded_String := SU.To_Unbounded_String (Dirs.Current_Directory); Name_Conflict_Decision : DCF.Unzip.Name_Conflict_Intervention := DCF.Unzip.Yes; procedure Help is begin Put_Line ("UnZipDCF " & DCF.Zip.Version & " - unzip document container files"); New_Line; Put_Line ("Usage: unzipdcf [-options[modifiers]] [-d exdir] file [list]"); New_Line; Put_Line (" -l list files"); Put_Line (" -t test integrity of files, no write"); Put_Line (" -z display archive comment only"); Put_Line (" -d extract to ""exdir"""); Put_Line ("modifiers:"); Put_Line (" -n never overwrite existing files -q quiet mode"); Put_Line (" -o always overwrite existing files"); Put_Line (" -j junk archived directory structure -L make names lower case"); end Help; procedure Resolve_Conflict (Name : in String; Name_Encoding : in DCF.Zip.Zip_Name_Encoding; Action : out DCF.Unzip.Name_Conflict_Intervention; New_Name : out String; New_Name_Length : out Natural) is C : Character; use all type DCF.Unzip.Name_Conflict_Intervention; begin loop Put ("replace " & Name & "? [y]es, [n]o, [A]ll, [N]one, [r]ename: "); declare Input : constant String := Get_Line; begin C := Input (Input'First); exit when C = 'y' or C = 'n' or C = 'A' or C = 'N' or C = 'r'; Put_Line ("error: invalid response [" & Input & "]"); end; end loop; case C is when 'y' => Action := Yes; when 'n' => Action := No; when 'A' => Action := Yes_To_All; when 'N' => Action := None; when 'r' => Action := Rename_It; Put ("new name: "); Get_Line (New_Name, New_Name_Length); when others => raise Program_Error; end case; end Resolve_Conflict; function Get_Out_File (Containing_Directory : String; File : DCF.Zip.Archived_File; Name_Conflict_Decision : in out DCF.Unzip.Name_Conflict_Intervention) return String is pragma Assert (Containing_Directory (Containing_Directory'Last) /= '/'); use Ada.Characters.Handling; use all type DCF.Unzip.Name_Conflict_Intervention; use all type Dirs.File_Kind; function Maybe_Trash_Dir (File_Name : String) return String is Name : constant String := (if Lower_Case then To_Lower (File_Name) else File_Name); Index : constant Natural := Ada.Strings.Fixed.Index (Name, "/", Ada.Strings.Backward); begin return (if No_Directories then Name (Index + 1 .. Name'Last) else Name); end Maybe_Trash_Dir; -- Optionally trash the archived directory structure and then concatenate with -- extraction directory Possible_Name : constant String := Maybe_Trash_Dir (File.Name); Possible_Path : constant String := Containing_Directory & '/' & Possible_Name; -- TODO Use File.Name_Encoding New_Name : String (1 .. 1024); New_Name_Length : Natural; begin if Test_Data or else Possible_Name = "" or else not Dirs.Exists (Possible_Path) or else Dirs.Kind (Possible_Path) = Directory then return Possible_Name; end if; loop case Name_Conflict_Decision is when Yes | No | Rename_It => -- Then ask for this name too Resolve_Conflict (File.Name, File.Name_Encoding, Name_Conflict_Decision, New_Name, New_Name_Length); when Yes_To_All | None => -- Nothing to decide: previous decision was definitive exit; end case; exit when not (Name_Conflict_Decision = Rename_It and then -- New name exists too! Dirs.Exists (Containing_Directory & '/' & New_Name (1 .. New_Name_Length))); end loop; -- User has decided case Name_Conflict_Decision is when Yes | Yes_To_All => return Possible_Name; when No | None => return ""; when Rename_It => return New_Name (1 .. New_Name_Length); end case; end Get_Out_File; begin if Argument_Count = 0 then Help; return; end if; for I in 1 .. Argument_Count loop if Argument (I) (1) = '-' then if Last_Option = I then null; -- was in fact an argument for previous option (e.g. "-s") else Last_Option := I; if Argument (I)'Length = 1 then Help; return; end if; for J in 2 .. Argument (I)'Last loop case Argument (I) (J) is when 't' => Test_Data := True; when 'l' => List_Files := True; when 'j' => No_Directories := True; when 'd' => if I = Argument_Count then Help; return; -- "-d" without the directory or anything ?! end if; Extraction_Directory := SU.To_Unbounded_String (Dirs.Full_Name (Argument (I + 1))); Last_Option := I + 1; when 'L' => Lower_Case := True; when 'n' => Name_Conflict_Decision := DCF.Unzip.None; when 'o' => Name_Conflict_Decision := DCF.Unzip.Yes_To_All; when 'q' => Quiet := True; when 'z' => Comment := True; when others => Help; return; end case; end loop; end if; end if; end loop; if Argument_Count = Last_Option then Help; return; end if; declare Archive : constant String := Argument (Last_Option + 1); Extract_All : constant Boolean := Argument_Count = Last_Option + 1; begin if not Dirs.Exists (Archive) then Put_Line ("Archive file '" & Archive & "' not found"); return; end if; declare Archive_Stream : aliased DCF.Streams.File_Zipstream := DCF.Streams.Open (Archive); Info : DCF.Zip.Zip_Info; begin DCF.Zip.Load (Info, Archive_Stream); if not Quiet then Put_Line ("Archive: " & Info.Name); end if; if (Comment or not Quiet) and Info.Comment'Length > 0 then Put_Line (Info.Comment); end if; if Comment then null; elsif List_Files then declare package Mod_IO is new Modular_IO (DCF.Unzip.File_Size_Type); package Int_IO is new Integer_IO (Integer); use type DCF.Unzip.File_Size_Type; function Percentage (Left, Right : DCF.Unzip.File_Size_Type) return Integer is begin if Left = Right or else Right = 0 then return 0; else return Integer (100.0 - (100.0 * Float (Left)) / Float (Right)); end if; end Percentage; Total_Uncompressed_Size : DCF.Unzip.File_Size_Type := 0; Total_Compressed_Size : DCF.Unzip.File_Size_Type := 0; procedure List_File_From_Stream (File : DCF.Zip.Archived_File) is Date_Time : constant Ada.Calendar.Time := DCF.Streams.Calendar.Convert (File.Date_Time); Date : constant String := Ada.Calendar.Formatting.Image (Date_Time, Time_Zone => Ada.Calendar.Time_Zones.UTC_Time_Offset (Date_Time)); begin Total_Uncompressed_Size := Total_Uncompressed_Size + File.Uncompressed_Size; Total_Compressed_Size := Total_Compressed_Size + File.Compressed_Size; -- Print date and time without seconds Mod_IO.Put (File.Uncompressed_Size, 10); Int_IO.Put (Percentage (File.Compressed_Size, File.Uncompressed_Size), 4); Put_Line ("% " & Date (Date'First .. Date'Last - 3) & " " & File.Name); end List_File_From_Stream; procedure List_All_Files is new DCF.Zip.Traverse (List_File_From_Stream); begin Put_Line (" Length Cmpr Date Time Name"); Put_Line ("---------- ---- ---------- ----- ----"); List_All_Files (Info); Put_Line ("---------- ---- -------"); Mod_IO.Put (Total_Uncompressed_Size, 10); Int_IO.Put (Percentage (Total_Compressed_Size, Total_Uncompressed_Size), 4); Put ("% " & Info.Entries'Image); Put_Line (if Info.Entries > 1 then " files" else " file"); end; else declare Extraction_Folder : constant String := SU.To_String (Extraction_Directory); pragma Assert (Extraction_Folder (Extraction_Folder'Last) /= '/'); function No_Directory (Name : String) return String is (if Name (Name'Last) = '/' then Name (Name'First .. Name'Last - 1) else Name); procedure Extract_From_Stream (File : DCF.Zip.Archived_File) is Name : constant String := Get_Out_File (Extraction_Folder, File, Name_Conflict_Decision); File_Is_Directory : constant Boolean := File.Name (File.Name'Last) = '/'; begin if Name = "" then return; end if; declare Path : constant String := Extraction_Folder & "/" & No_Directory (Name); use type Dirs.File_Kind; begin if not Test_Data and then Path /= Dirs.Full_Name (Path) then raise DCF.Unzip.Write_Error with "Entry " & Name & " is located outside extraction directory"; -- TODO Ask to resolve conflict (rename) Name in Get_Out_File instead end if; if not Quiet then if Test_Data then Put (" testing: " & Name); elsif File_Is_Directory then pragma Assert (not No_Directories); if not Dirs.Exists (Path) or else Dirs.Kind (Path) /= Dirs.Directory then Put_Line (" creating: " & Name); Dirs.Create_Path (Path); end if; elsif File.Compressed then Put_Line (" inflating: " & Name); else Put_Line (" extracting: " & Name); end if; end if; if Test_Data then declare Stream_Writer : DCF.Unzip.Streams.Stream_Writer (null); begin DCF.Unzip.Streams.Extract (Destination => Stream_Writer, Archive_Info => Info, File => File, Verify_Integrity => Test_Data); Put_Line (" OK"); exception when DCF.Unzip.CRC_Error => Put_Line (" ERROR"); end; elsif not File_Is_Directory then declare Directory_Path : constant String := Dirs.Containing_Directory (Path); begin -- Create folder if necessary if not Dirs.Exists (Directory_Path) then Dirs.Create_Path (Directory_Path); end if; end; declare File_Stream : aliased DCF.Streams.File_Zipstream := DCF.Streams.Create (Path); Stream_Writer : DCF.Unzip.Streams.Stream_Writer (File_Stream'Access); begin DCF.Unzip.Streams.Extract (Destination => Stream_Writer, Archive_Info => Info, File => File, Verify_Integrity => Test_Data); end; end if; end; end Extract_From_Stream; procedure Extract_All_Files is new DCF.Zip.Traverse (Extract_From_Stream); procedure Extract_One_File is new DCF.Zip.Traverse_One_File (Extract_From_Stream); begin if not Test_Data and then not Dirs.Exists (Extraction_Folder) then Dirs.Create_Path (Extraction_Folder); end if; if Extract_All then Extract_All_Files (Info); else for I in Last_Option + 2 .. Argument_Count loop Extract_One_File (Info, Argument (I)); end loop; end if; end; end if; end; end; end UnzipDCF;
-- { dg-do compile } -- { dg-options "-gnatct" } with Discr1_Pkg; use Discr1_Pkg; package Discr1 is procedure Proc (V : Variable_String_Array); end Discr1;
separate (Numerics.Sparse_Matrices) function Mult_M_SV (A : in Sparse_Matrix; X : in Sparse_Vector) return Sparse_Vector is I : constant Int_Array := To_Array (X.I); B : constant Real_Vector := To_Array (X.X); V : Real_Vector (1 .. A.N_Row) := (others => 0.0); N : Pos; begin pragma Assert (A.Format = CSC); pragma Assert (I'Length = Pos (X.I.Length)); for K in I'Range loop for J in A.P (I (K)) .. A.P (I (K) + 1) - 1 loop N := A.I (J); V (N) := V (N) + A.X (J) * B (K); end loop; end loop; return Sparse (V, Tol => 1.0e-15); end Mult_M_SV;
----------------------------------------------------------------------- -- awa-wikis-parsers-tests -- Unit tests for wiki parsing -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with AWA.Wikis.Writers; package body AWA.Wikis.Parsers.Tests is package Caller is new Util.Test_Caller (Test, "Wikis.Parsers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (bold)", Test_Wiki_Bold'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (italic)", Test_Wiki_Italic'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (italic, bold)", Test_Wiki_Formats'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (headings)", Test_Wiki_Section'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (lists)", Test_Wiki_List'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (links)", Test_Wiki_Link'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (quote)", Test_Wiki_Quote'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (line break)", Test_Wiki_Line_Break'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (image)", Test_Wiki_Image'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (preformatted)", Test_Wiki_Preformatted'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Text.Renderer", Test_Wiki_Text_Renderer'Access); end Add_Tests; -- ------------------------------ -- Test bold rendering. -- ------------------------------ procedure Test_Wiki_Bold (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><b>bold</b></p>", Writers.To_Html ("*bold*", SYNTAX_GOOGLE), "Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <b>bold</b> y</p>", Writers.To_Html ("x *bold* y", SYNTAX_GOOGLE), "Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <b>bold y</b></p>", Writers.To_Html ("x *bold y", SYNTAX_MIX), "Bold rendering invalid (MIX)"); Util.Tests.Assert_Equals (T, "<p>x <b>item y</b> p</p>", Writers.To_Html ("x __item y__ p", SYNTAX_DOTCLEAR), "Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x _item y_ p</p>", Writers.To_Html ("x _item y_ p", SYNTAX_DOTCLEAR), "No bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <b>bold</b> y</p>", Writers.To_Html ("x '''bold''' y", SYNTAX_PHPBB), "Bold rendering invalid (PHPBB)"); end Test_Wiki_Bold; -- ------------------------------ -- Test italic rendering. -- ------------------------------ procedure Test_Wiki_Italic (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><i>item</i></p>", Writers.To_Html ("_item_", SYNTAX_GOOGLE), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item</i> y</p>", Writers.To_Html ("x _item_ y", SYNTAX_GOOGLE), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i></p>", Writers.To_Html ("x _item y", SYNTAX_MIX), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i> p</p>", Writers.To_Html ("x ''item y'' p", SYNTAX_DOTCLEAR), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i> p</p>", Writers.To_Html ("x ''item y'' p", SYNTAX_PHPBB), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x 'item y<i> p</i></p>", Writers.To_Html ("x 'item y'' p", SYNTAX_PHPBB), "Italic rendering invalid"); end Test_Wiki_Italic; -- ------------------------------ -- Test various format rendering. -- ------------------------------ procedure Test_Wiki_Formats (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><i>it</i><b><i>bold</i></b><i>em</i></p>", Writers.To_Html ("_it*bold*em_", SYNTAX_GOOGLE), "Italic+Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item</i> y</p>", Writers.To_Html ("x _item_ y", SYNTAX_GOOGLE), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i></p>", Writers.To_Html ("x _item y", SYNTAX_GOOGLE), "Italic rendering invalid"); end Test_Wiki_Formats; -- ------------------------------ -- Test heading rendering. -- ------------------------------ procedure Test_Wiki_Section (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<h1>item</h1>", Writers.To_Html ("= item =", SYNTAX_GOOGLE), "H1 rendering invalid"); Util.Tests.Assert_Equals (T, "<h2>item</h2>", Writers.To_Html ("== item == ", SYNTAX_GOOGLE), "H2 rendering invalid"); Util.Tests.Assert_Equals (T, "<h3>item</h3>", Writers.To_Html ("=== item === ", SYNTAX_GOOGLE), "H3 rendering invalid"); Util.Tests.Assert_Equals (T, "<h4>item</h4>", Writers.To_Html ("==== item ==== ", SYNTAX_GOOGLE), "H4 rendering invalid"); Util.Tests.Assert_Equals (T, "<h5>item</h5>", Writers.To_Html ("===== item =====", SYNTAX_GOOGLE), "H5 rendering invalid"); Util.Tests.Assert_Equals (T, "<h6>item</h6>", Writers.To_Html ("====== item ===", SYNTAX_GOOGLE), "H6 rendering invalid"); Util.Tests.Assert_Equals (T, "<h1>item</h1><h2>item2</h2>", Writers.To_Html ("= item =" & CR & "== item2 ==", SYNTAX_GOOGLE), "H1 rendering invalid"); Util.Tests.Assert_Equals (T, "<h1>item</h1><h2>item2</h2><h1>item3</h1>", Writers.To_Html ("= item =" & CR & "== item2 ==" & CR & "= item3 =", SYNTAX_GOOGLE), "H1 rendering invalid"); end Test_Wiki_Section; -- ------------------------------ -- Test list rendering. -- ------------------------------ procedure Test_Wiki_List (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<ol><li>item</li></ol>", Writers.To_Html ("# item", SYNTAX_GOOGLE), "Ordered list rendering invalid"); Util.Tests.Assert_Equals (T, "<ol><li>item item " & ASCII.LF & "</li><li>item2 item2" & ASCII.LF & "</li><li><ol>item3</li></ol></ol>", Writers.To_Html ("# item item " & LF & "# item2 item2" & LF & "## item3", SYNTAX_GOOGLE), "Ordered rendering invalid"); Util.Tests.Assert_Equals (T, "<ul><li>item</li></ul>", Writers.To_Html (" * item", SYNTAX_GOOGLE), "Bullet list rendering invalid"); Util.Tests.Assert_Equals (T, "<ul><li>item</li></ul>", Writers.To_Html ("* item", SYNTAX_DOTCLEAR), "Bullet list rendering invalid"); end Test_Wiki_List; -- ------------------------------ -- Test link rendering. -- ------------------------------ procedure Test_Wiki_Link (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><a href="""">name</a></p>", Writers.To_Html ("[name]", SYNTAX_GOOGLE), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p><a title=""some"" lang=""en"" " & "href=""http://www.joe.com/item"">name </a></p>", Writers.To_Html ("[name |http://www.joe.com/item|en|some]", SYNTAX_DOTCLEAR), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p><a href="""">name</a></p>", Writers.To_Html ("[[name]]", SYNTAX_CREOLE), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p>[d</p>", Writers.To_Html ("[d", SYNTAX_CREOLE), "No link rendering invalid"); end Test_Wiki_Link; -- ------------------------------ -- Test quote rendering. -- ------------------------------ procedure Test_Wiki_Quote (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><q>quote</q></p>", Writers.To_Html ("{{quote}}", SYNTAX_DOTCLEAR), "Quote rendering invalid"); Util.Tests.Assert_Equals (T, "<p><q lang=""en"">quote</q></p>", Writers.To_Html ("{{quote|en}}", SYNTAX_DOTCLEAR), "Quote rendering invalid"); Util.Tests.Assert_Equals (T, "<p><q lang=""en"" cite=""http://www.sun.com"">quote</q></p>", Writers.To_Html ("{{quote|en|http://www.sun.com}}", SYNTAX_DOTCLEAR), "Quote rendering invalid"); Util.Tests.Assert_Equals (T, "<p>{quote}}</p>", Writers.To_Html ("{quote}}", SYNTAX_DOTCLEAR), "No quote rendering invalid"); end Test_Wiki_Quote; -- ------------------------------ -- Test line break rendering. -- ------------------------------ procedure Test_Wiki_Line_Break (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p>a<br></br>b</p>", Writers.To_Html ("a%%%b", SYNTAX_DOTCLEAR), "Line break rendering invalid"); Util.Tests.Assert_Equals (T, "<p>a<br></br>b</p>", Writers.To_Html ("a\\b", SYNTAX_CREOLE), "Line break rendering invalid"); Util.Tests.Assert_Equals (T, "<p>a%%b</p>", Writers.To_Html ("a%%b", SYNTAX_DOTCLEAR), "No line break rendering invalid"); Util.Tests.Assert_Equals (T, "<p>a%b</p>", Writers.To_Html ("a%b", SYNTAX_DOTCLEAR), "No line break rendering invalid"); end Test_Wiki_Line_Break; -- ------------------------------ -- Test image rendering. -- ------------------------------ procedure Test_Wiki_Image (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><img src=""/image/t.png""></img></p>", Writers.To_Html ("((/image/t.png))", SYNTAX_DOTCLEAR), "Image rendering invalid"); Util.Tests.Assert_Equals (T, "<p><img alt=""title"" src=""/image/t.png""></img></p>", Writers.To_Html ("((/image/t.png|title))", SYNTAX_DOTCLEAR), "Image rendering invalid"); Util.Tests.Assert_Equals (T, "<p><img alt=""title"" longdesc=""describe"" " & "src=""/image/t.png""></img></p>", Writers.To_Html ("((/image/t.png|title|D|describe))", SYNTAX_DOTCLEAR), "Image rendering invalid"); end Test_Wiki_Image; -- ------------------------------ -- Test preformatted rendering. -- ------------------------------ procedure Test_Wiki_Preformatted (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><tt>code</tt></p>", Writers.To_Html ("{{{code}}}", SYNTAX_GOOGLE), "Preformat rendering invalid"); Util.Tests.Assert_Equals (T, "<pre>* code *" & ASCII.LF & "</pre>", Writers.To_Html ("///" & LF & "* code *" & LF & "///", SYNTAX_DOTCLEAR), "Preformat rendering invalid"); end Test_Wiki_Preformatted; -- ------------------------------ -- Test the text renderer. -- ------------------------------ procedure Test_Wiki_Text_Renderer (T : in out Test) is begin Util.Tests.Assert_Equals (T, ASCII.LF & "code", Writers.To_Text ("{{{code}}}", SYNTAX_GOOGLE), "Preformat rendering invalid"); Util.Tests.Assert_Equals (T, ASCII.LF & "bold item my_title" & ASCII.LF, Writers.To_Text ("_bold_ __item__ [my_title]", SYNTAX_GOOGLE), "Preformat rendering invalid"); end Test_Wiki_Text_Renderer; end AWA.Wikis.Parsers.Tests;
----------------------------------------------------------------------- -- mat-memory-tests -- Unit tests for MAT memory -- Copyright (C) 2014, 2015, 2019, 2021 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with MAT.Expressions; with MAT.Frames.Targets; with MAT.Memory.Targets; package body MAT.Memory.Tests is package Caller is new Util.Test_Caller (Test, "Memory"); -- Builtin and well known definition of test frames. Frame_1_0 : constant MAT.Frames.Frame_Table (1 .. 10) := (1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test MAT.Memory.Probe_Malloc", Test_Probe_Malloc'Access); Caller.Add_Test (Suite, "Test MAT.Memory.Probe_Free", Test_Probe_Free'Access); end Add_Tests; -- ------------------------------ -- Basic consistency checks when creating the test tree -- ------------------------------ procedure Test_Probe_Malloc (T : in out Test) is M : MAT.Memory.Targets.Target_Memory; S : Allocation; R : Allocation_Map; F : MAT.Frames.Targets.Target_Frames; begin S.Size := 4; F.Insert (Frame_1_0, S.Frame); -- Create memory slots: -- [10 .. 14] [20 .. 24] [30 ..34] .. [100 .. 104] for I in 1 .. 10 loop M.Probe_Malloc (MAT.Types.Target_Addr (10 * I), S); end loop; -- Search for a memory region that does not overlap a memory slot. M.Find (15, 19, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 0, Integer (R.Length), "Find must return 0 slots in range [15 .. 19]"); M.Find (1, 9, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 0, Integer (R.Length), "Find must return 0 slots in range [1 .. 9]"); M.Find (105, 1000, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 0, Integer (R.Length), "Find must return 0 slots in range [105 .. 1000]"); -- Search with an overlap. M.Find (1, 1000, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 10, Integer (R.Length), "Find must return 10 slots in range [1 .. 1000]"); R.Clear; M.Find (1, 19, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 1, Integer (R.Length), "Find must return 1 slot in range [1 .. 19]"); R.Clear; M.Find (13, 19, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 1, Integer (R.Length), "Find must return 1 slot in range [13 .. 19]"); R.Clear; M.Find (100, 1000, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 1, Integer (R.Length), "Find must return 1 slot in range [100 .. 1000]"); R.Clear; M.Find (101, 1000, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 1, Integer (R.Length), "Find must return 1 slot in range [101 .. 1000]"); end Test_Probe_Malloc; -- ------------------------------ -- Test Probe_Free with update of memory slots. -- ------------------------------ procedure Test_Probe_Free (T : in out Test) is M : MAT.Memory.Targets.Target_Memory; S : Allocation; R : Allocation_Map; Size : MAT.Types.Target_Size; Id : MAT.Events.Event_Id_Type with Unreferenced; F : MAT.Frames.Targets.Target_Frames; begin S.Size := 4; S.Event := 1; F.Insert (Frame_1_0, S.Frame); -- Malloc followed by a free. M.Probe_Malloc (10, S); Id := 12; M.Probe_Free (10, S, Size, Id); M.Find (1, 1000, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 0, Integer (R.Length), "Find must return 0 slot after a free"); -- Free the same slot a second time (free error). M.Probe_Free (10, S, Size, Id); -- Malloc followed by a free. M.Probe_Malloc (10, S); M.Probe_Malloc (20, S); M.Probe_Malloc (30, S); M.Probe_Free (20, S, Size, Id); M.Find (1, 1000, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 2, Integer (R.Length), "Find must return 2 slots after a malloc/free sequence"); end Test_Probe_Free; end MAT.Memory.Tests;
-- Module : string_lists.ada -- Component of : common_library -- Version : 1.2 -- Date : 11/21/86 16:34:39 -- SCCS File : disk21~/rschm/hasee/sccs/common_library/sccs/sxstring_lists.ada with String_Pkg; with Lists; package String_Lists is new Lists(String_Pkg.String_Type, String_Pkg.Equal);
-- Copyright (C) 2019 Thierry Rascle <thierr26@free.fr> -- MIT license. Please refer to the LICENSE file. with Apsepp.Test_Reporter_Data_Struct_Class.Impl; use Apsepp.Test_Reporter_Data_Struct_Class.Impl; use Apsepp.Test_Reporter_Data_Struct_Class; package Apsepp.Test_Reporter_Class.Struct_Builder is ---------------------------------------------------------------------------- protected type Test_Reporter_Struct_Builder (Processing : Test_Reporter_Data_Proc := null) is new Test_Reporter_Interfa with overriding function Is_Conflicting_Node_Tag (Node_Tag : Tag) return Boolean; overriding procedure Provide_Node_Lineage (Node_Lineage : Tag_Array); overriding procedure Report_Failed_Child_Test_Node_Access (Node_Tag : Tag; Previous_Child_Tag : Tag; E : Exception_Occurrence); overriding procedure Report_Unexpected_Node_Cond_Check_Error (Node_Tag : Tag; E : Exception_Occurrence); overriding procedure Report_Unexpected_Node_Run_Error (Node_Tag : Tag; E : Exception_Occurrence); overriding procedure Report_Node_Cond_Check_Start (Node_Tag : Tag); overriding procedure Report_Passed_Node_Cond_Check (Node_Tag : Tag); overriding procedure Report_Failed_Node_Cond_Check (Node_Tag : Tag); overriding procedure Report_Passed_Node_Cond_Assert (Node_Tag : Tag); overriding procedure Report_Failed_Node_Cond_Assert (Node_Tag : Tag); overriding procedure Report_Node_Run_Start (Node_Tag : Tag); overriding procedure Report_Test_Routine_Start (Node_Tag : Tag; K : Test_Node_Class.Test_Routine_Count); overriding procedure Report_Test_Routines_Cancellation (Node_Tag : Tag; First_K, Last_K : Test_Node_Class.Test_Routine_Count); overriding procedure Report_Failed_Test_Routine_Access (Node_Tag : Tag; K : Test_Node_Class.Test_Routine_Count; E : Exception_Occurrence); overriding procedure Report_Failed_Test_Routine_Setup (Node_Tag : Tag; K : Test_Node_Class.Test_Routine_Count; E : Exception_Occurrence); overriding procedure Report_Passed_Test_Assert (Node_Tag : Tag; K : Test_Node_Class.Test_Routine_Count; Assert_Num_Avail : Boolean; Assert_Num : Test_Node_Class.Test_Assert_Count); overriding procedure Report_Failed_Test_Assert (Node_Tag : Tag; K : Test_Node_Class.Test_Routine_Count; Assert_Num_Avail : Boolean; Assert_Num : Test_Node_Class.Test_Assert_Count; E : Exception_Occurrence); overriding procedure Report_Unexpected_Routine_Exception (Node_Tag : Tag; K : Test_Node_Class.Test_Routine_Count; E : Exception_Occurrence); overriding procedure Report_Passed_Test_Routine (Node_Tag : Tag; K : Test_Node_Class.Test_Routine_Count); overriding procedure Report_Failed_Test_Routine (Node_Tag : Tag; K : Test_Node_Class.Test_Routine_Count); overriding procedure Report_Passed_Node_Run (Node_Tag : Tag); overriding procedure Report_Failed_Node_Run (Node_Tag : Tag); overriding procedure Process; not overriding function Struct_Pointer return access constant Test_Reporter_Data; private Data : aliased Test_Reporter_Data; end Test_Reporter_Struct_Builder; ---------------------------------------------------------------------------- end Apsepp.Test_Reporter_Class.Struct_Builder;
with Ada.Text_IO, Ada.Command_Line, Ada.Numerics.Discrete_Random; procedure Flip_Bits is subtype Letter is Character range 'a' .. 'z'; Last_Col: constant letter := Ada.Command_Line.Argument(1)(1); Last_Row: constant Positive := Positive'Value(Ada.Command_Line.Argument(2)); package Boolean_Rand is new Ada.Numerics.Discrete_Random(Boolean); Gen: Boolean_Rand.Generator; type Matrix is array (Letter range 'a' .. Last_Col, Positive range 1 .. Last_Row) of Boolean; function Rand_Mat return Matrix is M: Matrix; begin for I in M'Range(1) loop for J in M'Range(2) loop M(I,J) := Boolean_Rand.Random(Gen); end loop; end loop; return M; end Rand_Mat; function Rand_Mat(Start: Matrix) return Matrix is M: Matrix := Start; begin for I in M'Range(1) loop if Boolean_Rand.Random(Gen) then for J in M'Range(2) loop M(I,J) := not M(I, J); end loop; end if; end loop; for I in M'Range(2) loop if Boolean_Rand.Random(Gen) then for J in M'Range(1) loop M(J,I) := not M(J, I); end loop; end if; end loop; return M; end Rand_Mat; procedure Print(Message: String; Mat: Matrix) is package NIO is new Ada.Text_IO.Integer_IO(Natural); begin Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line(Message); Ada.Text_IO.Put(" "); for Ch in Matrix'Range(1) loop Ada.Text_IO.Put(" " & Ch); end loop; Ada.Text_IO.New_Line; for I in Matrix'Range(2) loop NIO.Put(I, Width => 3); for Ch in Matrix'Range(1) loop Ada.Text_IO.Put(if Mat(Ch, I) then " 1" else " 0"); end loop; Ada.Text_IO.New_Line; end loop; end Print; Current, Target: Matrix; Moves: Natural := 0; begin -- choose random Target and start ("Current") matrices Boolean_Rand.Reset(Gen); Target := Rand_Mat; loop Current := Rand_Mat(Target); exit when Current /= Target; end loop; Print("Target:", Target); -- print and modify Current matrix, until it is identical to Target while Current /= Target loop Moves := Moves + 1; Print("Current move #" & Natural'Image(Moves), Current); Ada.Text_IO.Put_Line("Flip row 1 .." & Positive'Image(Last_Row) & " or column 'a' .. '" & Last_Col & "'"); declare S: String := Ada.Text_IO.Get_Line; function Let(S: String) return Character is (S(S'First)); function Val(Str: String) return Positive is (Positive'Value(Str)); begin if Let(S) in 'a' .. Last_Col then for I in Current'Range(2) loop Current(Let(S), I) := not Current(Let(S), I); end loop; else for I in Current'Range(1) loop Current(I, Val(S)) := not Current(I, Val(S)); end loop; end if; end; end loop; -- summarize the outcome Ada.Text_IO.Put_Line("Done after" & Natural'Image(Moves) & " Moves."); end Flip_Bits;
-- $Id: StringM.md,v 1.3 1992/08/07 14:45:41 grosch rel $ -- $Log: StringM.md,v $ -- Ich, Doktor Josef Grosch, Informatiker, Sept. 1994 with Text_Io, Strings; use Text_Io, Strings; package StringM is subtype tStringRef is Integer; function PutString (s: tString) return tStringRef; -- Stores string 's' in the string memory and -- returns a reference to the stored string. function GetString (r: tStringRef) return tString; -- Returns the string 's' from the string -- memory which is referenced by 'r'. function Length (r: tStringRef) return Integer; -- Returns the length of the string 's' -- which is referenced by 'r'. function IsEqual (r: tStringRef; s: tString) return Boolean; -- Compares the string referenced by 'r' and -- the string 's'. -- Returns True if both are equal. procedure WriteString (f: File_Type; r: tStringRef); -- The string referenced by 'r' is printed on -- file 'f'. procedure WriteStringMemory; -- The contents of the string memory is printed -- on the terminal. procedure InitStringMemory; -- The string memory is initialized. end StringM;
with openGL.Tasks, openGL.Server, sdl.Video.Windows.Makers, sdl.Video.gl, ada.Task_identification, ada.Text_IO; procedure launch_core_Test -- -- Exercise basic subprograms common to all GL profiles. -- -- TODO: Complete this. -- is use ada.Text_IO; use type sdl.Video.Windows.window_Flags; Error : exception; Window : sdl.Video.Windows.Window; gl_Context : sdl.Video.gl.Contexts; begin --------- --- Setup -- if not SDL.initialise then raise Error with "Unable to initialise SDL."; end if; sdl.Video.Windows.Makers.create (Win => Window, Title => "openGL Demo", X => 100, Y => 100, Width => 200, Height => 200, Flags => sdl.Video.Windows.openGL or sdl.Video.Windows.Resizable); sdl.Video.gl.create (gl_Context, From => Window); sdl.Video.gl.set_Current (gl_Context, To => Window); openGL.Tasks.renderer_Task := ada.Task_identification.current_Task; --------- --- Tests -- put_Line ("openGL Server: " & openGL.Server.Version); delay 2.0; end launch_core_Test;
-- Abstract: -- -- Root of WisiToken lexer/parser generator and exector. -- -- The token type is an integer subtype, not an enumeration type, to -- avoid making this package generic, which would make all other -- packages generic. -- -- Additional information about a token can be stored in the -- 'augmented' field of the syntax tree; see -- wisitoken-syntax_trees.ads. -- -- References: -- -- [dragon] "Compilers Principles, Techniques, and Tools" by Aho, -- Sethi, and Ullman (aka: "The [Red] Dragon Book" due to the dragon -- on the cover). -- -- Copyright (C) 2009, 2010, 2013 - 2015, 2017 - 2019 Free Software Foundation, Inc. -- -- This file is part of the WisiToken package. -- -- 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. -- -- This software was originally developed with the name OpenToken by -- the following company, and was released as open-source software as -- a service to the community: -- -- FlightSafety International Simulation Systems Division -- Broken Arrow, OK USA 918-259-4000 pragma License (Modified_GPL); with Ada.Containers; with Ada.Strings.Unbounded; with Ada.Text_IO; with Ada.Unchecked_Deallocation; with SAL.Gen_Trimmed_Image; with SAL.Gen_Unbounded_Definite_Queues; with SAL.Gen_Unbounded_Definite_Vectors.Gen_Image; with SAL.Gen_Unbounded_Definite_Vectors.Gen_Image_Aux; package WisiToken is Partial_Parse : exception; -- a partial parse terminated. Syntax_Error : exception; -- no recovery for a syntax error was found Parse_Error : exception; -- a non-recoverable non-fatal error was encountered; editing the input can fix the error. Fatal_Error : exception; -- Error in code or grammar; editing input cannot fix error. Grammar_Error : exception; -- Grammar file has bad syntax, or grammar is not consistent (ie -- unused tokens, missing productions, invalid actions) User_Error : exception; -- other user error (ie command line parameter) -- SAL.Programmer_Error : exception; -- a programming convention has been violated subtype Positive_Index_Type is SAL.Peek_Type; function Trimmed_Image is new SAL.Gen_Trimmed_Image (SAL.Base_Peek_Type); type Unknown_State_Index is new Integer range -1 .. Integer'Last; subtype State_Index is Unknown_State_Index range 0 .. Unknown_State_Index'Last; Unknown_State : constant Unknown_State_Index := -1; function Trimmed_Image is new SAL.Gen_Trimmed_Image (Unknown_State_Index); package State_Index_Queues is new SAL.Gen_Unbounded_Definite_Queues (State_Index); package State_Index_Arrays is new SAL.Gen_Unbounded_Definite_Vectors (Positive, State_Index, Default_Element => State_Index'Last); function Trimmed_Image is new SAL.Gen_Trimmed_Image (Integer); function Image is new State_Index_Arrays.Gen_Image (Trimmed_Image); ---------- -- Token IDs type Token_ID is range 0 .. Integer'Last; -- 0 origin to match elisp array Invalid_Token_ID : constant Token_ID := Token_ID'Last; type String_Access_Constant is access constant String; type Token_ID_Array_String is array (Token_ID range <>) of String_Access_Constant; type Token_ID_Array_Natural is array (Token_ID range <>) of Natural; type Descriptor (First_Terminal : Token_ID; Last_Terminal : Token_ID; First_Nonterminal : Token_ID; Last_Nonterminal : Token_ID; EOI_ID : Token_ID; Accept_ID : Token_ID) is record -- Tokens in the range Token_ID'First .. First_Terminal - 1 are -- non-reporting (comments, whitespace), and thus are not used in -- generating parse tables. -- -- Tokens in the range Last_Terminal + 1 .. Last_Nonterminal are -- the nonterminals of a grammar. -- -- Components are discriminants if they can be specified statically. Case_Insensitive : Boolean; -- keywords and names New_Line_ID : Token_ID; String_1_ID : Token_ID; String_2_ID : Token_ID; -- String_1 delimited by '; String_2 by ". -- -- Used by missing quote error recovery. If the language does not -- have two kinds of string literals, set one or both of these to -- Invalid_Token_ID. Image : Token_ID_Array_String (Token_ID'First .. Last_Nonterminal); -- User names for tokens. Terminal_Image_Width : Integer; Image_Width : Integer; -- max width of Image Last_Lookahead : Token_ID; -- LALR generate needs a 'Propagate_ID' lookahead that is distinct -- from all terminals. Since lookaheads are Token_ID_Set, we need to -- allocate First_Terminal .. Last_Terminal for LR1 generate, and -- First_Terminal .. Propagate_ID for LALR generate, so we define -- Last_Lookahead. After the LR table is generated, Last_Lookahead is -- no longer used. end record; type Descriptor_Access is access Descriptor; type Descriptor_Access_Constant is access constant Descriptor; function Padded_Image (Item : in Token_ID; Desc : in Descriptor) return String; -- Return Desc.Image (Item), padded to Terminal_Image_Width (if Item -- is a terminal) or to Image_Width. function Image (Item : in Token_ID; Desc : in Descriptor) return String; -- Return Desc.Image (Item), or empty string for Invalid_Token_ID. function Trimmed_Image is new SAL.Gen_Trimmed_Image (Token_ID); procedure Put_Tokens (Descriptor : in WisiToken.Descriptor); -- Put user readable token list (token_id'first .. -- descriptor.last_nonterminal) to Ada.Text_IO.Current_Output function Find_ID (Descriptor : in WisiToken.Descriptor; Name : in String) return Token_ID; -- Return index of Name in Descriptor.Image. If not found, raise Programmer_Error. type Token_ID_Array is array (Positive range <>) of Token_ID; -- Index is not Positive_Index_Type, mostly for historical reasons. package Token_ID_Arrays is new SAL.Gen_Unbounded_Definite_Vectors (Positive, Token_ID, Default_Element => Invalid_Token_ID); function Image is new Token_ID_Arrays.Gen_Image_Aux (Descriptor, Trimmed_Image, Image); function Trimmed_Image is new Token_ID_Arrays.Gen_Image (Trimmed_Image); procedure To_Vector (Item : in Token_ID_Array; Vector : in out Token_ID_Arrays.Vector); function To_Vector (Item : in Token_ID_Array) return Token_ID_Arrays.Vector; function Shared_Prefix (A, B : in Token_ID_Arrays.Vector) return Natural; -- Return last index in A of a prefix shared between A, B; 0 if none. type Token_ID_Set is array (Token_ID range <>) of Boolean; type Token_ID_Set_Access is access Token_ID_Set; function "&" (Left : in Token_ID_Set; Right : in Token_ID) return Token_ID_Set; -- Include Left and Right in result. function To_Token_ID_Set (First, Last : in Token_ID; Item : in Token_ID_Array) return Token_ID_Set; -- First, Last determine size of result. -- For each element in Item, set result (element) True. procedure To_Set (Item : in Token_ID_Arrays.Vector; Set : out Token_ID_Set); -- For each element of Item, set Set (element) True. function To_Array (Item : in Token_ID_Set) return Token_ID_Arrays.Vector; function Any (Item : in Token_ID_Set) return Boolean; function Count (Item : in Token_ID_Set) return Integer; -- Count of True elements. function Image (Item : in Token_ID_Set; Desc : in Descriptor; Max_Count : in Integer := Integer'Last; Inverted : in Boolean := False) return String; -- For diagnostics; not Ada syntax. type Token_Array_Token_Set is array (Token_ID range <>, Token_ID range <>) of Boolean; function Slice (Item : in Token_Array_Token_Set; I : in Token_ID) return Token_ID_Set; function Any (Item : in Token_Array_Token_Set; I : in Token_ID) return Boolean; function Any (Item : in Token_Array_Token_Set) return Boolean; procedure Or_Slice (Item : in out Token_Array_Token_Set; I : in Token_ID; Value : in Token_ID_Set); procedure Put (Descriptor : in WisiToken.Descriptor; Item : in Token_Array_Token_Set); -- Put Item to Ada.Text_IO.Current_Output, using valid Ada aggregate -- syntax. type Token_Array_Token_ID is array (Token_ID range <>) of Token_ID; package Token_Sequence_Arrays is new SAL.Gen_Unbounded_Definite_Vectors (Token_ID, Token_ID_Arrays.Vector, Default_Element => Token_ID_Arrays.Empty_Vector); ---------- -- Production IDs; see wisitoken-productions.ads for more type Production_ID is record LHS : Token_ID := Invalid_Token_ID; RHS : Natural := 0; -- Index into the production table. end record; Invalid_Production_ID : constant Production_ID := (others => <>); function Image (Item : in Production_ID) return String; -- Ada positional aggregate syntax, for code generation. function Trimmed_Image (Item : in Production_ID) return String; -- Nonterm.rhs_index, both integers, no leading or trailing space; -- for parse table output and diagnostics. Prod_ID_Image_Width : constant Integer := 7; -- Max width of Trimmed_Image function Padded_Image (Item : in Production_ID; Width : in Integer) return String; -- Trimmed_Image padded with leading spaces to Width package Production_ID_Arrays is new SAL.Gen_Unbounded_Definite_Vectors (Positive, Production_ID, Default_Element => Invalid_Production_ID); function Image is new Production_ID_Arrays.Gen_Image (Image); function Trimmed_Image is new Production_ID_Arrays.Gen_Image (Trimmed_Image); type Production_ID_Array is array (Natural range <>) of Production_ID; function To_Vector (Item : in Production_ID_Array) return Production_ID_Arrays.Vector; function "+" (Item : in Production_ID_Array) return Production_ID_Arrays.Vector renames To_Vector; function "+" (Item : in Production_ID) return Production_ID_Arrays.Vector is (To_Vector ((1 => Item))); type Recursion is (None, Single, -- Single token in right hand side is recursive. Middle, -- Multiple tokens in right hand side, recursive token not at either end. Right, -- Multiple tokens in right hand side, recursive token not at right end. Left -- Multiple tokens in right hand side, recursive token not at left end. ); -- In worst-case order; Left recursion causes the most -- problems in LR error recovery, and in Packrat. function Worst_Recursion (A, B : in Recursion) return Recursion is (Recursion'Max (A, B)); function Net_Recursion (A, B : in Recursion) return Recursion; -- For finding the net recursion of a chain; Middle dominates. ---------- -- Tokens type Base_Buffer_Pos is range 0 .. Integer'Last; subtype Buffer_Pos is Base_Buffer_Pos range 1 .. Base_Buffer_Pos'Last; -- match Emacs buffer origin. type Buffer_Region is record First : Buffer_Pos; Last : Base_Buffer_Pos; -- allow representing null range. end record; Invalid_Buffer_Pos : constant Buffer_Pos := Buffer_Pos'Last; Null_Buffer_Region : constant Buffer_Region := (Buffer_Pos'Last, Buffer_Pos'First); function Length (Region : in Buffer_Region) return Natural is (Natural (Region.Last - Region.First + 1)); function Inside (Pos : in Buffer_Pos; Region : in Buffer_Region) return Boolean is (Region.First <= Pos and Pos <= Region.Last); function Image (Item : in Buffer_Region) return String; function "and" (Left, Right : in Buffer_Region) return Buffer_Region; -- Return region enclosing both Left and Right. type Line_Number_Type is range 1 .. Natural'Last; -- Match Emacs buffer line numbers. function Trimmed_Image is new SAL.Gen_Trimmed_Image (Line_Number_Type); Invalid_Line_Number : constant Line_Number_Type := Line_Number_Type'Last; type Base_Token is tagged record -- Base_Token is used in the core parser. The parser only needs ID; -- semantic checks need Byte_Region to compare names. Line, Col, and -- Char_Region are included for error messages. ID : Token_ID := Invalid_Token_ID; Byte_Region : Buffer_Region := Null_Buffer_Region; -- Index into the Lexer buffer for the token text. Line : Line_Number_Type := Invalid_Line_Number; Column : Ada.Text_IO.Count := 0; -- At start of token. Char_Region : Buffer_Region := Null_Buffer_Region; -- Character position, useful for finding the token location in Emacs -- buffers. end record; type Base_Token_Class_Access is access all Base_Token'Class; type Base_Token_Class_Access_Constant is access constant Base_Token'Class; function Image (Item : in Base_Token; Descriptor : in WisiToken.Descriptor) return String; -- For debug/test messages. procedure Free is new Ada.Unchecked_Deallocation (Base_Token'Class, Base_Token_Class_Access); Invalid_Token : constant Base_Token := (others => <>); type Base_Token_Index is range 0 .. Integer'Last; subtype Token_Index is Base_Token_Index range 1 .. Base_Token_Index'Last; Invalid_Token_Index : constant Base_Token_Index := Base_Token_Index'First; function Trimmed_Image is new SAL.Gen_Trimmed_Image (Base_Token_Index); type Token_Index_Array is array (Natural range <>) of Token_Index; package Recover_Token_Index_Arrays is new SAL.Gen_Unbounded_Definite_Vectors (Natural, Base_Token_Index, Default_Element => Invalid_Token_Index); type Base_Token_Array is array (Positive_Index_Type range <>) of Base_Token; package Base_Token_Arrays is new SAL.Gen_Unbounded_Definite_Vectors (Token_Index, Base_Token, Default_Element => (others => <>)); type Base_Token_Array_Access is access all Base_Token_Arrays.Vector; function Image is new Base_Token_Arrays.Gen_Image_Aux (WisiToken.Descriptor, Trimmed_Image, Image); function Image (Token : in Base_Token_Index; Terminals : in Base_Token_Arrays.Vector; Descriptor : in WisiToken.Descriptor) return String; package Line_Begin_Token_Vectors is new SAL.Gen_Unbounded_Definite_Vectors (Line_Number_Type, Base_Token_Index, Default_Element => Invalid_Token_Index); type Recover_Token is record -- Maintaining a syntax tree during recover is too slow, so we store -- enough information in the recover stack to perform -- Semantic_Checks, Language_Fixes, and Push_Back operations. and to -- apply the solution to the main parser state. We make thousands of -- copies of the parse stack during recover, so minimizing size and -- compute time for this is critical. ID : Token_ID := Invalid_Token_ID; Byte_Region : Buffer_Region := Null_Buffer_Region; -- Byte_Region is used to detect empty tokens, for cost and other issues. Min_Terminal_Index : Base_Token_Index := Invalid_Token_Index; -- For terminals, index of this token in Shared_Parser.Terminals. For -- nonterminals, minimum of contained tokens (Invalid_Token_Index if -- empty). For virtuals, Invalid_Token_Index. Used for push_back of -- nonterminals. Name : Buffer_Region := Null_Buffer_Region; -- Set and used by semantic_checks. Virtual : Boolean := True; -- For terminals, True if inserted by recover. For nonterminals, True -- if any contained token has Virtual = True. end record; function Image (Item : in Recover_Token; Descriptor : in WisiToken.Descriptor) return String; type Recover_Token_Array is array (Positive_Index_Type range <>) of Recover_Token; package Recover_Token_Arrays is new SAL.Gen_Unbounded_Definite_Vectors (Token_Index, Recover_Token, Default_Element => (others => <>)); function Image is new Recover_Token_Arrays.Gen_Image_Aux (WisiToken.Descriptor, Trimmed_Image, Image); type Base_Identifier_Index is range 0 .. Integer'Last; subtype Identifier_Index is Base_Identifier_Index range 1 .. Base_Identifier_Index'Last; -- For virtual identifiers created during syntax tree rewrite. Invalid_Identifier_Index : constant Base_Identifier_Index := Base_Identifier_Index'First; ---------- -- Trace, debug Trace_Parse : Integer := 0; -- If Trace_Parse > 0, Parse prints messages helpful for debugging -- the grammar and/or the parser; higher value prints more. -- -- Trace_Parse levels; output info if Trace_Parse > than: -- Outline : constant := 0; -- spawn/terminate parallel parsers, error recovery enter/exit Detail : constant := 1; -- add each parser cycle Extra : constant := 2; -- add pending semantic state operations Lexer_Debug : constant := 3; -- add lexer debug Trace_McKenzie : Integer := 0; -- If Trace_McKenzie > 0, Parse prints messages helpful for debugging error recovery. -- -- Outline - error recovery enter/exit -- Detail - add each error recovery configuration -- Extra - add error recovery parse actions Trace_Action : Integer := 0; -- Output during Execute_Action, and unit tests. Trace_Generate : Integer := 0; -- Output during grammar generation. Debug_Mode : Boolean := False; -- If True, Output stack traces, propagate exceptions to top level. -- Otherwise, be robust to errors, so user does not notice them. type Trace (Descriptor : not null access constant WisiToken.Descriptor) is abstract tagged limited null record; -- Output for tests/debugging. Descriptor included here because many -- uses of Trace will use Image (Item, Descriptor); procedure Set_Prefix (Trace : in out WisiToken.Trace; Prefix : in String) is abstract; -- Prepend Prefix to all subsequent messages. Usefull for adding -- comment syntax. procedure Put (Trace : in out WisiToken.Trace; Item : in String; Prefix : in Boolean := True) is abstract; -- Put Item to the Trace display. If Prefix is True, prepend the stored prefix. procedure Put_Line (Trace : in out WisiToken.Trace; Item : in String) is abstract; -- Put Item to the Trace display, followed by a newline. procedure New_Line (Trace : in out WisiToken.Trace) is abstract; -- Put a newline to the Trace display. procedure Put_Clock (Trace : in out WisiToken.Trace; Label : in String) is abstract; -- Put Ada.Calendar.Clock to Trace. ---------- -- Misc function "+" (Item : in String) return Ada.Strings.Unbounded.Unbounded_String renames Ada.Strings.Unbounded.To_Unbounded_String; function "-" (Item : in Ada.Strings.Unbounded.Unbounded_String) return String renames Ada.Strings.Unbounded.To_String; function Trimmed_Image is new SAL.Gen_Trimmed_Image (Ada.Containers.Count_Type); function Error_Message (File_Name : in String; Line : in Line_Number_Type; Column : in Ada.Text_IO.Count; Message : in String) return String; -- Return Gnu-formatted error message. type Names_Array is array (Integer range <>) of String_Access_Constant; type Names_Array_Access is access Names_Array; type Names_Array_Array is array (WisiToken.Token_ID range <>) of Names_Array_Access; type Names_Array_Array_Access is access Names_Array_Array; end WisiToken;
-- PACKAGE Extended_Real.Elementary_Functions -- -- Taylor series are used to get Exp, Sin and Cos. Once these are calculated, -- Newton-Raphson iteration gives inverse functions: Log, Arccos, and Arcsin, -- Arctan. Similarly, starting with the function G(Y) = Y**(-N), -- Newton-Raphson iteration gives the inverse: F(X) = X**(-1/N), -- the reciprocal of the Nth root of X. Newton-Raphson is used directly to get -- Sqrt, Inverse, and Inverse_Nth_root. Inverse(X) is the reciprocal of -- of X. It's usually faster than the "/" function, (One / X). -- -- Newton-Raphson iteration is used to calculate Y = F(a) when F's inverse -- function G(Y) is known. (G satisfies G(F(a)) = a.) Say we want Y = F(a), -- We can't calculate F, but given a Y we can calculate G(Y) and we know a. Then -- use Newton-Raphson to solve for Y in equation G(Y) = a. The iteration is -- -- dG/dY(Y_0) = (G(Y_0) - a) / (Y_0 - Y_1), or, -- -- Y_1 = Y_0 - (G(Y_0) - a) / dG/dY(Y_0). -- -- For example, if want F(a) = Log(a), and we can get G(Y) = Exp(Y), then we -- iterate for Y = Log(a) using: -- -- Y_1 = Y_0 - (Exp(Y_0) - a) / Exp(Y_0). -- -- Similarly, if we want F(a) = a**(-1/N) and we know G(Y) = Y**(-N), then: -- -- Y_1 = Y_0 - (Y_0**(-N) - a) / (-N*Y**(-N-1), -- -- = Y_0 - (1 - a*Y_0**N) * Y / (-N). -- -- Argument reduction is necessary in most of the routines. Some of the -- arg reduction ideas come from Brent, D M Smith, D H Bailey. -- generic -- Functions for type Real. Must be correct to 48 bits. -- You should never have to enter these parameters, as long as -- they are visible at instantiation. Log is natural. with function Sqrt (X : Real) return Real is <>; with function Log (X : Real) return Real is <>; -- Natural log. (ln) with function Exp (X : Real) return Real is <>; -- inverse of log with function Arcsin (X : Real) return Real is <>; -- inverse of sin with function Arctan (Y : Real; X : Real := 1.0) return Real is <>; package Extended_Real.Elementary_Functions is function Sqrt (X : e_Real) return e_Real; function Exp (X : e_Real) return e_Real; function Log (X : e_Real) return e_Real; function Log (X : e_Real; Base : e_Real) return e_Real; function Sin (X : e_Real) return e_Real; function Sin (X : e_Real; Cycle : e_Real) return e_Real; function Cos (X : e_Real) return e_Real; function Cos (X : e_Real; Cycle : e_Real) return e_Real; function Arcsin (X : e_Real) return e_Real; function Arccos (X : e_Real) return e_Real; function "**" (Left : e_Real; Right : e_Real) return e_Real; function Arctan (X : e_Real) return e_Real; -- Output is in range [-Pi/2 .. Pi/2] only. Arctan (Infinity) = Pi/2. function Reciprocal (X : e_Real) return e_Real; -- Newton-Raphson inversion. Usually faster than One / X. function Divide (Z, X : e_Real) return e_Real; -- Newton-Raphson Z / X. function Reciprocal_Nth_Root (X : e_Real; N : Positive) return e_Real; -- Reciprocal of the N-th root of X: X**(-1/N) = 1 / X**(1/N). One way -- to get the N-th root of X is to take One / Reciprocal_Nth_Root(X, N). -- N must be less than Radix - 1, which is usually 2**29 - 1. -- (This function is non-standard, but is used by some of the other -- routines, so might as well export it.) function Reciprocal_Sqrt (X : e_Real) return e_Real; function e_Quarter_Pi return e_Real; -- returns Pi/4 by arcsin method. function e_Log_2 return e_Real; -- returns Log(2.0). function e_Inverse_Pi return e_Real; -- returns 1/Pi by arcsin method. function e_Inverse_Sqrt_2 return e_Real; -- returns 1/Sqrt(2.0). function e_Half_Inverse_Log_2 return e_Real; -- returns 0.5/Log(2.0). -- The above constants are calculated to max available precision. -- They are all slightly less than one - the the highest precision -- that this package is capable of. So the above versions are -- preferred to the ones given below, which are somewhat -- greater than one. function e_Pi return e_Real; -- returns Pi by arcsin method. E_Argument_Error : Exception; end Extended_Real.Elementary_Functions;
-- part of AdaYaml, (c) 2017 Felix Krause -- released under the terms of the MIT license, see the file "copying.txt" package body Yaml.Transformator.Annotation.Identity is procedure Put (Object : in out Instance; E : Event) is begin if Object.Current_Exists then raise Constraint_Error with "must remove event before inputting another one"; end if; Object.Current_Exists := True; Object.Current := E; end Put; function Has_Next (Object : Instance) return Boolean is (Object.Current_Exists); function Next (Object : in out Instance) return Event is begin if not Object.Current_Exists then raise Constraint_Error with "no event to retrieve"; end if; Object.Current_Exists := False; return Object.Current; end Next; function New_Identity return not null Pointer is (new Instance); end Yaml.Transformator.Annotation.Identity;
with Gtkada.Builder; use Gtkada.Builder; with Gtk.GEntry; with Gtk.Widget; with Gtk.Handlers; with Gtk.Text_View; with Gtk.Text_Buffer; with Glib.Values; package callbacks is package text is new Gtk.Handlers.Callback (Gtk.Text_Buffer.Gtk_Text_Buffer_Record); function tryQuit (Object : access Gtkada_Builder_Record'Class) return Boolean; procedure quit (Object : access Gtkada_Builder_Record'Class); procedure assembleCB (Object : access Gtkada_Builder_Record'Class); procedure stepCB (Object : access Gtkada_Builder_Record'Class); procedure runCB (Object : access Gtkada_Builder_Record'Class); procedure stopCB (Object : access Gtkada_Builder_Record'Class); procedure newCB (Object : access Gtkada_Builder_Record'Class); procedure openCB (Object : access Gtkada_Builder_Record'Class); procedure saveCB (Object : access Gtkada_Builder_Record'Class); procedure saveAsCB (Object : access Gtkada_Builder_Record'Class); procedure aboutCB (Object : access Gtkada_Builder_Record'Class); procedure editCB (Object : access Gtk.Text_Buffer.Gtk_Text_Buffer_Record'Class); function areYouSure return Boolean; end callbacks;
-- THIS GENERIC PROCEDURE IS INTENDED FOR USE IN CONJUNCTION WITH THE ACVC -- CHAPTER 13 C TESTS. IT IS INSTANTIATED WITH TWO TYPES. THE FIRST IS AN -- ENUMERATION TYPE FOR WHICH AN ENUMERATION CLAUSE HAS BEEN GIVEN, AND THE -- SECOND IS AN INTEGER TYPE WHOSE 'SIZE IS THE SAME AS THE 'SIZE OF THIS -- ENUMERATION TYPE. -- THE PROCEDURE ENUM_CHECK IS THEN CALLED WITH THREE ARGUMENTS. THE FIRST IS -- AN ENUMERATION LITERAL FROM THE ENUMERATION TYPE, THE SECOND IS AN INTEGER -- LITERAL WHICH IS THE VALUE OF THE EXPECTED REPRESENTATION (TAKEN FROM THE -- ENUMERATION REPRESENTATION CLAUSE), AND THE THIRD IS A STRING DESCRIBING OR -- NAMING THE TYPE (USED IN A CALL TO FAILED IF THE REPRESENTATION CHECK FAILS). -- THE CHECK IS TO CONVERT THE ENUMERATION VALUE TO A BOOLEAN ARRAY WITH A -- LENGTH CORRESONDING TO THE 'SIZE OF THE ENUMERATION TYPE. AN INTEGER TYPE -- IS THEN CREATED WITH THIS SAME 'SIZE, AND THE REQUIRED REPRESENTATION VALUE -- IS CONVERTED FROM THIS TYPE TO A BOOLEAN ARRAY WITH THE SAME LENGTH. THE -- TWO BOOLEAN ARRAYS ARE THEN COMPARED AND SHOULD BE EQUAL. THE CONVERSIONS -- ARE PERFORMED USING APPROPRIATE INSTANTIATIONS OF UNCHECKED_CONVERSION. -- AUTHOR: ROBERT B. K. DEWAR, UNCOPYRIGHTED, PUBLIC DOMAIN USE AUTHORIZED GENERIC TYPE ENUM_TYPE IS PRIVATE; TYPE INT_TYPE IS RANGE <>; PROCEDURE ENUM_CHECK (TEST_VALUE : ENUM_TYPE; REP_VALUE : INT_TYPE; TYPE_ID : STRING); WITH UNCHECKED_CONVERSION; WITH REPORT; USE REPORT; PROCEDURE ENUM_CHECK (TEST_VALUE : ENUM_TYPE; REP_VALUE : INT_TYPE; TYPE_ID : STRING) IS TYPE BIT_ARRAY_TYPE IS ARRAY (1 .. ENUM_TYPE'SIZE) OF BOOLEAN; PRAGMA PACK (BIT_ARRAY_TYPE); FUNCTION TO_BITS IS NEW UNCHECKED_CONVERSION (ENUM_TYPE, BIT_ARRAY_TYPE); FUNCTION TO_BITS IS NEW UNCHECKED_CONVERSION (INT_TYPE, BIT_ARRAY_TYPE); BIT_ARRAY_1 : BIT_ARRAY_TYPE; BIT_ARRAY_2 : BIT_ARRAY_TYPE; INT_VALUE : INT_TYPE := INT_TYPE (REP_VALUE); BEGIN -- VERIFY CORRECT CALL (THIS IS A SANITY CHECK ON THE TEST ITSELF) IF ENUM_TYPE'SIZE /= INT_TYPE'SIZE THEN FAILED ("ERROR IN ENUM_CHECK CALL: SIZES DO NOT MATCH"); END IF; BIT_ARRAY_1 := TO_BITS (TEST_VALUE); BIT_ARRAY_2 := TO_BITS (INT_VALUE); IF BIT_ARRAY_1 /= BIT_ARRAY_2 THEN FAILED ("CHECK ON REPRESENTATION OF TYPE " & TYPE_ID & " FAILED."); END IF; END ENUM_CHECK;
-- Standard Ada library specification -- Copyright (c) 2003-2018 Maxim Reznik <reznikmm@gmail.com> -- Copyright (c) 2004-2016 AXE Consultants -- Copyright (c) 2004, 2005, 2006 Ada-Europe -- Copyright (c) 2000 The MITRE Corporation, Inc. -- Copyright (c) 1992, 1993, 1994, 1995 Intermetrics, Inc. -- SPDX-License-Identifier: BSD-3-Clause and LicenseRef-AdaReferenceManual --------------------------------------------------------------------------- package Ada.Calendar.Arithmetic is -- Arithmetic on days: type Day_Count is range -366 * (1 + Year_Number'Last - Year_Number'First) .. 366 * (1 + Year_Number'Last - Year_Number'First); subtype Leap_Seconds_Count is Integer range -2047 .. 2047; procedure Difference (Left : in Time; Right : in Time; Days : out Day_Count; Seconds : out Duration; Leap_Seconds : out Leap_Seconds_Count); function "+" (Left : in Time; Right : in Day_Count) return Time; function "+" (Left : in Day_Count; Right : in Time) return Time; function "-" (Left : in Time; Right : in Day_Count) return Time; function "-" (Left : in Time; Right : in Time) return Day_Count; end Ada.Calendar.Arithmetic;
with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; package body P_StepHandler.KeyHandler is function Make (Self : in out KeyHandler) return KeyHandler is begin Self.Ptr_Key := null; Self.Ptr_SubKeyArray := null; return Self; end; overriding procedure Handle (Self : in out KeyHandler) is InitialBinaryKey : T_BinaryKey; TmpFormattedKey : T_BinaryFormattedKey; SubKey : T_BinarySubKey; begin InitialBinaryKey := TextBlock_To_Binary(Self.Ptr_Key.all); TmpFormattedKey := PermutationChoice1_Key(InitialBinaryKey); for Round in 1..16 loop KeyShift(TmpFormattedKey, Round); SubKey := PermutationChoice2_Key(TmpFormattedKey); Self.Ptr_SubKeyArray.all(Round) := SubKey; end loop; if Self.NextHandler /= null then Self.NextHandler.Handle; end if; end; function PermutationChoice1_Key (BinaryKey : in out T_BinaryKey) return T_BinaryFormattedKey is PermIndex : Integer; P1BinaryKey : T_BinaryFormattedKey; begin PermIndex := 57; for BitIndex in 1..28 loop P1BinaryKey(BitIndex) := BinaryKey(PermIndex); if (PermIndex-8 > 0) then PermIndex := PermIndex-8; else PermIndex := PermIndex + 57 ; end if; end loop; PermIndex := 63; for BitIndex in 29..52 loop P1BinaryKey(BitIndex) := BinaryKey(PermIndex); if (PermIndex-8 > 0) then PermIndex := PermIndex-8; else PermIndex := PermIndex + 55; end if; end loop; PermIndex := 28; for BitIndex in 53..56 loop P1BinaryKey(BitIndex) := BinaryKey(PermIndex); PermIndex := PermIndex-8; end loop; return P1BinaryKey; end; procedure KeyShift (Key : in out T_BinaryFormattedKey; Round : in Positive) is HalfLeft, HalfRight : T_BinaryHalfFormattedKey; Iteration : Integer; begin HalfLeft := Key(1..28); HalfRight := Key(29..56); if Round = 1 or Round = 2 or Round = 9 or Round = 16 then Iteration := 1; else Iteration := 2; end if; Left_Shift (HalfLeft, Iteration); Left_Shift (HalfRight, Iteration); Key(1..28) := HalfLeft; Key(29..56) := HalfRight; end; function PermutationChoice2_Key (Key : in out T_BinaryFormattedKey) return T_BinarySubKey is SubKey : T_BinarySubKey; begin SubKey(1) := Key(14); SubKey(2) := Key(17); SubKey(3) := Key(11); SubKey(4) := Key(24); SubKey(5) := Key(1); SubKey(6) := Key(5); SubKey(7) := Key(3); SubKey(8) := Key(28); SubKey(9) := Key(15); SubKey(10) := Key(6); SubKey(11) := Key(21); SubKey(12) := Key(10); SubKey(13) := Key(23); SubKey(14) := Key(19); SubKey(15) := Key(12); SubKey(16) := Key(4); SubKey(17) := Key(26); SubKey(18) := Key(8); SubKey(19) := Key(16); SubKey(20) := Key(7); SubKey(21) := Key(27); SubKey(22) := Key(20); SubKey(23) := Key(13); SubKey(24) := Key(2); SubKey(25) := Key(41); SubKey(26) := Key(52); SubKey(27) := Key(31); SubKey(28) := Key(37); SubKey(29) := Key(47); SubKey(30) := Key(55); SubKey(31) := Key(30); SubKey(32) := Key(40); SubKey(33) := Key(51); SubKey(34) := Key(45); SubKey(35) := Key(33); SubKey(36) := Key(48); SubKey(37) := Key(44); SubKey(38) := Key(49); SubKey(39) := Key(39); SubKey(40) := Key(56); SubKey(41) := Key(34); SubKey(42) := Key(53); SubKey(43) := Key(46); SubKey(44) := Key(42); SubKey(45) := Key(50); SubKey(46) := Key(36); SubKey(47) := Key(29); SubKey(48) := Key(32); return SubKey; end; procedure Set_SubKeyArrayAccess (Self : in out KeyHandler ; Ptr_SubKeyAray : in BinarySubKeyArray_Access) is begin Self.Ptr_SubKeyArray := Ptr_SubKeyAray; end; procedure Set_KeyAccess (Self : in out KeyHandler; Ptr_Key : in Key_Access) is begin Self.Ptr_Key := Ptr_Key; end; end P_StepHandler.KeyHandler;
with Some_Package; procedure main with SPARK_Mode is begin Some_Package.bar; end main;
----------------------------------------------------------------------- -- util-encoders-base64 -- Encode/Decode a stream in Base64 -- Copyright (C) 2009, 2010, 2011, 2012 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.Streams; with Interfaces; -- The <b>Util.Encodes.Base64</b> packages encodes and decodes streams -- in Base64 (See rfc4648: The Base16, Base32, and Base64 Data Encodings). package Util.Encoders.Base64 is pragma Preelaborate; -- ------------------------------ -- Base64 encoder -- ------------------------------ -- This <b>Encoder</b> translates the (binary) input stream into -- a Base64 ascii stream. type Encoder is new Util.Encoders.Transformer with private; -- Encodes the binary input stream represented by <b>Data</b> into -- the a base64 output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. overriding procedure Transform (E : in Encoder; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset); -- Set the encoder to use the base64 URL alphabet when <b>Mode</b> is True. -- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters. procedure Set_URL_Mode (E : in out Encoder; Mode : in Boolean); -- Create a base64 encoder using the URL alphabet. -- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters. function Create_URL_Encoder return Transformer_Access; -- ------------------------------ -- Base64 decoder -- ------------------------------ -- The <b>Decoder</b> decodes a Base64 ascii stream into a binary stream. type Decoder is new Util.Encoders.Transformer with private; -- Decodes the base64 input stream represented by <b>Data</b> into -- the binary output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. overriding procedure Transform (E : in Decoder; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset); -- Set the decoder to use the base64 URL alphabet when <b>Mode</b> is True. -- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters. procedure Set_URL_Mode (E : in out Decoder; Mode : in Boolean); -- Create a base64 decoder using the URL alphabet. -- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters. function Create_URL_Decoder return Transformer_Access; private type Alphabet is array (Interfaces.Unsigned_8 range 0 .. 63) of Ada.Streams.Stream_Element; type Alphabet_Access is not null access constant Alphabet; BASE64_ALPHABET : aliased constant Alphabet := (Character'Pos ('A'), Character'Pos ('B'), Character'Pos ('C'), Character'Pos ('D'), Character'Pos ('E'), Character'Pos ('F'), Character'Pos ('G'), Character'Pos ('H'), Character'Pos ('I'), Character'Pos ('J'), Character'Pos ('K'), Character'Pos ('L'), Character'Pos ('M'), Character'Pos ('N'), Character'Pos ('O'), Character'Pos ('P'), Character'Pos ('Q'), Character'Pos ('R'), Character'Pos ('S'), Character'Pos ('T'), Character'Pos ('U'), Character'Pos ('V'), Character'Pos ('W'), Character'Pos ('X'), Character'Pos ('Y'), Character'Pos ('Z'), Character'Pos ('a'), Character'Pos ('b'), Character'Pos ('c'), Character'Pos ('d'), Character'Pos ('e'), Character'Pos ('f'), Character'Pos ('g'), Character'Pos ('h'), Character'Pos ('i'), Character'Pos ('j'), Character'Pos ('k'), Character'Pos ('l'), Character'Pos ('m'), Character'Pos ('n'), Character'Pos ('o'), Character'Pos ('p'), Character'Pos ('q'), Character'Pos ('r'), Character'Pos ('s'), Character'Pos ('t'), Character'Pos ('u'), Character'Pos ('v'), Character'Pos ('w'), Character'Pos ('x'), Character'Pos ('y'), Character'Pos ('z'), Character'Pos ('0'), Character'Pos ('1'), Character'Pos ('2'), Character'Pos ('3'), Character'Pos ('4'), Character'Pos ('5'), Character'Pos ('6'), Character'Pos ('7'), Character'Pos ('8'), Character'Pos ('9'), Character'Pos ('+'), Character'Pos ('/')); BASE64_URL_ALPHABET : aliased constant Alphabet := (Character'Pos ('A'), Character'Pos ('B'), Character'Pos ('C'), Character'Pos ('D'), Character'Pos ('E'), Character'Pos ('F'), Character'Pos ('G'), Character'Pos ('H'), Character'Pos ('I'), Character'Pos ('J'), Character'Pos ('K'), Character'Pos ('L'), Character'Pos ('M'), Character'Pos ('N'), Character'Pos ('O'), Character'Pos ('P'), Character'Pos ('Q'), Character'Pos ('R'), Character'Pos ('S'), Character'Pos ('T'), Character'Pos ('U'), Character'Pos ('V'), Character'Pos ('W'), Character'Pos ('X'), Character'Pos ('Y'), Character'Pos ('Z'), Character'Pos ('a'), Character'Pos ('b'), Character'Pos ('c'), Character'Pos ('d'), Character'Pos ('e'), Character'Pos ('f'), Character'Pos ('g'), Character'Pos ('h'), Character'Pos ('i'), Character'Pos ('j'), Character'Pos ('k'), Character'Pos ('l'), Character'Pos ('m'), Character'Pos ('n'), Character'Pos ('o'), Character'Pos ('p'), Character'Pos ('q'), Character'Pos ('r'), Character'Pos ('s'), Character'Pos ('t'), Character'Pos ('u'), Character'Pos ('v'), Character'Pos ('w'), Character'Pos ('x'), Character'Pos ('y'), Character'Pos ('z'), Character'Pos ('0'), Character'Pos ('1'), Character'Pos ('2'), Character'Pos ('3'), Character'Pos ('4'), Character'Pos ('5'), Character'Pos ('6'), Character'Pos ('7'), Character'Pos ('8'), Character'Pos ('9'), Character'Pos ('-'), Character'Pos ('_')); type Encoder is new Util.Encoders.Transformer with record Alphabet : Alphabet_Access := BASE64_ALPHABET'Access; end record; type Alphabet_Values is array (Ada.Streams.Stream_Element) of Interfaces.Unsigned_8; type Alphabet_Values_Access is not null access constant Alphabet_Values; BASE64_VALUES : aliased constant Alphabet_Values := (Character'Pos ('A') => 0, Character'Pos ('B') => 1, Character'Pos ('C') => 2, Character'Pos ('D') => 3, Character'Pos ('E') => 4, Character'Pos ('F') => 5, Character'Pos ('G') => 6, Character'Pos ('H') => 7, Character'Pos ('I') => 8, Character'Pos ('J') => 9, Character'Pos ('K') => 10, Character'Pos ('L') => 11, Character'Pos ('M') => 12, Character'Pos ('N') => 13, Character'Pos ('O') => 14, Character'Pos ('P') => 15, Character'Pos ('Q') => 16, Character'Pos ('R') => 17, Character'Pos ('S') => 18, Character'Pos ('T') => 19, Character'Pos ('U') => 20, Character'Pos ('V') => 21, Character'Pos ('W') => 22, Character'Pos ('X') => 23, Character'Pos ('Y') => 24, Character'Pos ('Z') => 25, Character'Pos ('a') => 26, Character'Pos ('b') => 27, Character'Pos ('c') => 28, Character'Pos ('d') => 29, Character'Pos ('e') => 30, Character'Pos ('f') => 31, Character'Pos ('g') => 32, Character'Pos ('h') => 33, Character'Pos ('i') => 34, Character'Pos ('j') => 35, Character'Pos ('k') => 36, Character'Pos ('l') => 37, Character'Pos ('m') => 38, Character'Pos ('n') => 39, Character'Pos ('o') => 40, Character'Pos ('p') => 41, Character'Pos ('q') => 42, Character'Pos ('r') => 43, Character'Pos ('s') => 44, Character'Pos ('t') => 45, Character'Pos ('u') => 46, Character'Pos ('v') => 47, Character'Pos ('w') => 48, Character'Pos ('x') => 49, Character'Pos ('y') => 50, Character'Pos ('z') => 51, Character'Pos ('0') => 52, Character'Pos ('1') => 53, Character'Pos ('2') => 54, Character'Pos ('3') => 55, Character'Pos ('4') => 56, Character'Pos ('5') => 57, Character'Pos ('6') => 58, Character'Pos ('7') => 59, Character'Pos ('8') => 60, Character'Pos ('9') => 61, Character'Pos ('+') => 62, Character'Pos ('/') => 63, others => 16#FF#); BASE64_URL_VALUES : aliased constant Alphabet_Values := (Character'Pos ('A') => 0, Character'Pos ('B') => 1, Character'Pos ('C') => 2, Character'Pos ('D') => 3, Character'Pos ('E') => 4, Character'Pos ('F') => 5, Character'Pos ('G') => 6, Character'Pos ('H') => 7, Character'Pos ('I') => 8, Character'Pos ('J') => 9, Character'Pos ('K') => 10, Character'Pos ('L') => 11, Character'Pos ('M') => 12, Character'Pos ('N') => 13, Character'Pos ('O') => 14, Character'Pos ('P') => 15, Character'Pos ('Q') => 16, Character'Pos ('R') => 17, Character'Pos ('S') => 18, Character'Pos ('T') => 19, Character'Pos ('U') => 20, Character'Pos ('V') => 21, Character'Pos ('W') => 22, Character'Pos ('X') => 23, Character'Pos ('Y') => 24, Character'Pos ('Z') => 25, Character'Pos ('a') => 26, Character'Pos ('b') => 27, Character'Pos ('c') => 28, Character'Pos ('d') => 29, Character'Pos ('e') => 30, Character'Pos ('f') => 31, Character'Pos ('g') => 32, Character'Pos ('h') => 33, Character'Pos ('i') => 34, Character'Pos ('j') => 35, Character'Pos ('k') => 36, Character'Pos ('l') => 37, Character'Pos ('m') => 38, Character'Pos ('n') => 39, Character'Pos ('o') => 40, Character'Pos ('p') => 41, Character'Pos ('q') => 42, Character'Pos ('r') => 43, Character'Pos ('s') => 44, Character'Pos ('t') => 45, Character'Pos ('u') => 46, Character'Pos ('v') => 47, Character'Pos ('w') => 48, Character'Pos ('x') => 49, Character'Pos ('y') => 50, Character'Pos ('z') => 51, Character'Pos ('0') => 52, Character'Pos ('1') => 53, Character'Pos ('2') => 54, Character'Pos ('3') => 55, Character'Pos ('4') => 56, Character'Pos ('5') => 57, Character'Pos ('6') => 58, Character'Pos ('7') => 59, Character'Pos ('8') => 60, Character'Pos ('9') => 61, Character'Pos ('-') => 62, Character'Pos ('_') => 63, others => 16#FF#); type Decoder is new Util.Encoders.Transformer with record Values : Alphabet_Values_Access := BASE64_VALUES'Access; end record; end Util.Encoders.Base64;
with Regression_Library; use Regression_Library; package body Regression is function "&" (Left, Right : String) return String is begin return Left; end "&"; package body Outer is function OuterFun (Input : Boolean) return Boolean is begin return False; end OuterFun; procedure OuterProc (Input : in Boolean) is begin return; end OuterProc; package body Nested is procedure NestedProc (Input : in Boolean) is begin OuterProc(Input); end NestedProc; function NestedFun (Input : in Boolean; InputFun : FunctionType) return Boolean is begin return (LibraryFun(Input) or OuterFun(Input)) or InputFun(0); end NestedFun; end Nested; end Outer; end Regression;
----------------------------------------------------------------------- -- util-encodes-tests - Test for encoding -- Copyright (C) 2009, 2010, 2011, 2012 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.Tests; package Util.Encoders.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Hex (T : in out Test); procedure Test_Base64_Encode (T : in out Test); procedure Test_Base64_Decode (T : in out Test); procedure Test_Base64_URL_Encode (T : in out Test); procedure Test_Base64_URL_Decode (T : in out Test); procedure Test_Encoder (T : in out Test; C : in out Util.Encoders.Encoder); procedure Test_Base64_Benchmark (T : in out Test); procedure Test_SHA1_Encode (T : in out Test); -- Benchmark test for SHA1 procedure Test_SHA1_Benchmark (T : in out Test); -- Test HMAC-SHA1 procedure Test_HMAC_SHA1_RFC2202_T1 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T2 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T3 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T4 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T5 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T6 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T7 (T : in out Test); -- Test encoding leb128. procedure Test_LEB128 (T : in out Test); end Util.Encoders.Tests;
with Ada.Text_IO, Logic; procedure Twelve_Statements is package L is new Logic(Number_Of_Statements => 12); use L; -- formally define the 12 statements as expression function predicates function P01(T: Table) return Boolean is (T'Length = 12); -- list of 12 statements function P02(T: Table) return Boolean is (Sum(T(7 .. 12)) = 3); -- three of last six function P03(T: Table) return Boolean is (Sum(Half(T, Even)) = 2); -- two of the even function P04(T: Table) return Boolean is (if T(5) then T(6) and T(7)); -- if 5 is true, then ... function P05(T: Table) return Boolean is ( (not T(2)) and (not T(3)) and (not T(4)) ); -- none of preceding three function P06(T: Table) return Boolean is (Sum(Half(T, Odd)) = 4); -- four of the odd function P07(T: Table) return Boolean is (T(2) xor T(3)); -- either 2 or 3, not both function P08(T: Table) return Boolean is (if T(7) then T(5) and T(6)); -- if 7 is true, then ... function P09(T: Table) return Boolean is (Sum(T(1 .. 6)) = 3); -- three of first six function P10(T: Table) return Boolean is (T(11) and T(12)); -- next two function P11(T: Table) return Boolean is (Sum(T(7..9)) = 1); -- one of 7, 8, 9 function P12(T: Table) return Boolean is (Sum(T(1 .. 11)) = 4); -- four of the preding -- define a global list of statements Statement_List: constant Statements := (P01'Access, P02'Access, P03'Access, P04'Access, P05'Access, P06'Access, P07'Access, P08'Access, P09'Access, P10'Access, P11'Access, P12'Access); -- try out all 2^12 possible choices for the table procedure Try(T: Table; Fail: Natural; Idx: Indices'Base := Indices'First) is procedure Print_Table(T: Table) is use Ada.Text_IO; begin Put(" "); if Fail > 0 then Put("(wrong at"); for J in T'Range loop if Statement_List(J)(T) /= T(J) then Put(Integer'Image(J) & (if J < 10 then ") " else ") ")); end if; end loop; end if; if T = (1..12 => False) then Put_Line("All false!"); else Put("True are"); for J in T'Range loop if T(J) then Put(Integer'Image(J)); end if; end loop; New_Line; end if; end Print_Table; Wrong_Entries: Natural := 0; begin if Idx <= T'Last then Try(T(T'First .. Idx-1) & False & T(Idx+1 .. T'Last), Fail, Idx+1); Try(T(T'First .. Idx-1) & True & T(Idx+1 .. T'Last), Fail, Idx+1); else -- now Index > T'Last and we have one of the 2^12 choices to test for J in T'Range loop if Statement_List(J)(T) /= T(J) then Wrong_Entries := Wrong_Entries + 1; end if; end loop; if Wrong_Entries = Fail then Print_Table(T); end if; end if; end Try; begin Ada.Text_IO.Put_Line("Exact hits:"); Try(T => (1..12 => False), Fail => 0); Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line("Near Misses:"); Try(T => (1..12 => False), Fail => 1); end Twelve_Statements;
with Ada.Strings.Wide_Wide_Unbounded; with Ada.Characters.Conversions; with Ada.Strings.Wide_Wide_Maps.Wide_Wide_Constants; with Ada.Wide_Wide_Text_IO; -- Package to make it easier to deal with strings in general, but wide, -- international strings in particular. package Unicode_Strings is package Unbounded renames Ada.Strings.Wide_Wide_Unbounded; package Conversions renames Ada.Characters.Conversions; package IO renames Ada.Wide_Wide_Text_IO; package Character_Maps renames Ada.Strings.Wide_Wide_Maps.Wide_Wide_Constants; function W (Item : String) return Wide_Wide_String renames Conversions.To_Wide_Wide_String; function From_Unbounded (Item : Unbounded.Unbounded_Wide_Wide_String) return Wide_Wide_String renames Unbounded.To_Wide_Wide_String; function To_Unbounded (Item : Wide_Wide_String) return Unbounded.Unbounded_Wide_Wide_String renames Unbounded.To_Unbounded_Wide_Wide_String; function Un_W (Item : Wide_Wide_String) return String is (Conversions.To_String (Item, Substitute => '?')); package Characters is LF : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0a#); end Characters; end Unicode_Strings;
----------------------------------------------------------------------- -- awa-jobs-services -- Job services -- Copyright (C) 2012, 2014, 2015, 2020 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Objects.Maps; with Util.Refs; with ADO.Sessions; with ADO.Objects; with AWA.Events; with AWA.Jobs.Models; -- == Job Service == -- The `AWA.Jobs.Services` package defines the type abstractions and the -- core operation to define a job operation procedure, create and schedule -- a job and perform the job work when it is scheduled. -- -- @type Abstract_Job_Type -- -- @type package AWA.Jobs.Services is -- The job is closed. The status cannot be modified. Closed_Error : exception; -- The job is already scheduled. Schedule_Error : exception; -- The job had an execution error. Execute_Error : exception; -- The parameter value is invalid and cannot be set on the job instance. Invalid_Value : exception; -- Event posted when a job is created. package Job_Create_Event is new AWA.Events.Definition (Name => "job-create"); -- Get the job status. function Get_Job_Status (Id : in ADO.Identifier) return Models.Job_Status_Type; -- ------------------------------ -- Abstract_Job Type -- ------------------------------ -- The `Abstract_Job_Type` is an abstract tagged record which defines -- a job that can be scheduled and executed. This is the base type of -- any job implementation. It defines the `Execute` abstract procedure -- that must be implemented in concrete job types. -- It provides operation to setup and retrieve the job parameter. -- When the job `Execute` procedure is called, it allows to set the -- job execution status and result. type Abstract_Job_Type is abstract new Util.Refs.Ref_Entity and Util.Beans.Basic.Readonly_Bean with private; type Abstract_Job_Type_Access is access all Abstract_Job_Type'Class; type Work_Access is access procedure (Job : in out Abstract_Job_Type'Class); -- Execute the job. This operation must be implemented and should -- perform the work represented by the job. It should use the -- `Get_Parameter` function to retrieve the job parameter and it can -- use the `Set_Result` operation to save the result. procedure Execute (Job : in out Abstract_Job_Type) is abstract; -- Set the job parameter identified by the `Name` to the value -- given in `Value`. procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in String); -- Set the job parameter identified by the `Name` to the value -- given in `Value`. procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in Integer); -- Set the job parameter identified by the `Name` to the value -- given in `Value`. procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in ADO.Objects.Object_Ref'Class); -- Set the job parameter identified by the `Name` to the value -- given in `Value`. -- The value object can hold any kind of basic value type -- (integer, enum, date, strings). If the value represents -- a bean, the `Invalid_Value` exception is raised. procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in Util.Beans.Objects.Object); -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (Job : in Abstract_Job_Type; Name : in String) return Util.Beans.Objects.Object; -- Get the job parameter identified by the `Name` and convert -- the value into a string. function Get_Parameter (Job : in Abstract_Job_Type; Name : in String) return String; -- Get the job parameter identified by the `Name` and convert -- the value as an integer. If the parameter is not defined, -- return the default value passed in `Default`. function Get_Parameter (Job : in Abstract_Job_Type; Name : in String; Default : in Integer) return Integer; -- Get the job parameter identified by the `Name` and convert -- the value as a database identifier. If the parameter is not defined, -- return the `ADO.NO_IDENTIFIER`. function Get_Parameter (Job : in Abstract_Job_Type; Name : in String) return ADO.Identifier; -- Get the job parameter identified by the `Name` and return it as -- a typed object. function Get_Parameter (Job : in Abstract_Job_Type; Name : in String) return Util.Beans.Objects.Object; -- Get the job status. function Get_Status (Job : in Abstract_Job_Type) return Models.Job_Status_Type; -- Get the job identifier once the job was scheduled. -- The job identifier allows to retrieve the job and check its -- execution and completion status later on. function Get_Identifier (Job : in Abstract_Job_Type) return ADO.Identifier; -- Set the job status. When the job is terminated, it is closed -- and the job parameters or results cannot be changed. procedure Set_Status (Job : in out Abstract_Job_Type; Status : in AWA.Jobs.Models.Job_Status_Type); -- Set the job result identified by the `Name` to the value given -- in `Value`. The value object can hold any kind of basic value -- type (integer, enum, date, strings). If the value represents a bean, -- the `Invalid_Value` exception is raised. procedure Set_Result (Job : in out Abstract_Job_Type; Name : in String; Value : in Util.Beans.Objects.Object); -- Set the job result identified by the `Name` to the value given in `Value`. procedure Set_Result (Job : in out Abstract_Job_Type; Name : in String; Value : in String); -- Save the job information in the database. Use the database session -- defined by `DB` to save the job. procedure Save (Job : in out Abstract_Job_Type; DB : in out ADO.Sessions.Master_Session'Class); -- ------------------------------ -- Job Factory -- ------------------------------ -- The `Job_Factory` is the interface that allows to create a job -- instance in order to execute a scheduled job. The `Create` function -- is called to create a new job instance when the job is scheduled -- for execution. type Job_Factory is abstract tagged limited null record; type Job_Factory_Access is access all Job_Factory'Class; -- Create the job instance using the job factory. function Create (Factory : in Job_Factory) return Abstract_Job_Type_Access is abstract; -- Get the job factory name. function Get_Name (Factory : in Job_Factory'Class) return String; -- Schedule the job. procedure Schedule (Job : in out Abstract_Job_Type; Definition : in Job_Factory'Class); -- ------------------------------ -- Job Type -- ------------------------------ -- The `Job_Type` is a concrete job used by the `Work_Factory` to execute -- a simple `Work_Access` procedure. type Job_Type is new Abstract_Job_Type with private; overriding procedure Execute (Job : in out Job_Type); -- ------------------------------ -- Work Factory -- ------------------------------ -- The `Work_Factory` is a simplified `Job_Factory` that allows to register -- simple `Work_Access` procedures to execute the job. type Work_Factory (Work : Work_Access) is new Job_Factory with null record; -- Create the job instance to execute the associated `Work_Access` procedure. overriding function Create (Factory : in Work_Factory) return Abstract_Job_Type_Access; -- ------------------------------ -- Job Declaration -- ------------------------------ -- The `Definition` package must be instantiated with a given job type to -- register the new job definition. generic type T is new Abstract_Job_Type with private; package Definition is type Job_Type_Factory is new Job_Factory with null record; overriding function Create (Factory : in Job_Type_Factory) return Abstract_Job_Type_Access; -- The job factory. Factory : constant Job_Factory_Access; private Instance : aliased Job_Type_Factory; Factory : constant Job_Factory_Access := Instance'Access; end Definition; generic Work : in Work_Access; package Work_Definition is type S_Factory is new Work_Factory with null record; -- The job factory. Factory : constant Job_Factory_Access; private Instance : aliased S_Factory := S_Factory '(Work => Work); Factory : constant Job_Factory_Access := Instance'Access; end Work_Definition; type Job_Ref is private; -- Get the job parameter identified by the `Name` and return it as -- a typed object. Return the `Null_Object` if the job is empty -- or there is no such parameter. function Get_Parameter (Job : in Job_Ref; Name : in String) return Util.Beans.Objects.Object; -- Execute the job associated with the given event. procedure Execute (Event : in AWA.Events.Module_Event'Class; Result : in out Job_Ref); private -- Execute the job and save the job information in the database. procedure Execute (Job : in out Abstract_Job_Type'Class; DB : in out ADO.Sessions.Master_Session'Class); type Abstract_Job_Type is abstract new Util.Refs.Ref_Entity and Util.Beans.Basic.Readonly_Bean with record Job : AWA.Jobs.Models.Job_Ref; Props : Util.Beans.Objects.Maps.Map; Results : Util.Beans.Objects.Maps.Map; Props_Modified : Boolean := False; Results_Modified : Boolean := False; end record; -- ------------------------------ -- Job Type -- ------------------------------ -- The `Job_Type` is a concrete job used by the `Work_Factory` to execute -- a simple `Work_Access` procedure. type Job_Type is new Abstract_Job_Type with record Work : Work_Access; end record; package Job_Refs is new Util.Refs.Indefinite_References (Element_Type => Abstract_Job_Type'Class, Element_Access => Abstract_Job_Type_Access); type Job_Ref is new Job_Refs.Ref with null record; end AWA.Jobs.Services;
with Ada.Interrupts; with STM32_SVD.USART; with STM32_SVD; use STM32_SVD; generic Clock : Integer; USART : in out STM32_SVD.USART.USART_Peripheral; Speed : UInt32; IRQ : Ada.Interrupts.Interrupt_ID; RX_DMA_Buffer_Size : in Natural := 0; package STM32GD.USART.Peripheral is RX_DMA_Buffer: array (1 .. RX_DMA_Buffer_Size) of Byte; procedure Init; procedure Transmit (Data : in Byte); function Receive return Byte; protected IRQ_Handler is entry Wait; private procedure Handler; pragma Attach_Handler (Handler, IRQ); Data_Available : Boolean := False; end IRQ_Handler; end STM32GD.USART.Peripheral;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Common; use Common; with Ada.Unchecked_Deallocation; package Algebra with SPARK_Mode is Max_Children : constant := 50; type Node_Kind_Type is (Action, Operator, Undefined); -- Nodes can be either Action nodes or Operator nodes type Operator_Kind_Type is (Sequential, Alternative, Parallel, Undefined); -- In case of Operator nodes, there are 3 possibilities type Algebra_Tree_Cell (Node_Kind : Node_Kind_Type); type Algebra_Tree is access Algebra_Tree_Cell; -- Cell type and its corresponding pointer subtype Children_Number is Integer range 0 .. Max_Children; subtype Children_Index is Children_Number range 1 .. Children_Number'Last; type Algebra_Tree_Array is array (Children_Index range <>) of Algebra_Tree; type Children_Array is new Algebra_Tree_Array with Predicate => (for all Child of Children_Array => Child /= null); type Children_Collection (Num_Children : Children_Number := 0) is record Children : Children_Array (1 .. Num_Children); end record; -- This type is used to store the pointers to the children of an Operator -- node. type Algebra_Tree_Cell (Node_Kind : Node_Kind_Type) is record case Node_Kind is when Action => TaskOptionId : Int64; when Operator => Operator_Kind : Operator_Kind_Type; Collection : Children_Collection; when Undefined => null; end case; end record; procedure Parse_Formula (Formula : Unbounded_String; Algebra : out Algebra_Tree; Error : in out Boolean; Message : in out Unbounded_String) with Pre => Length (Formula) > 1, Post => (if not Error then Algebra /= null); procedure Print_Tree (Algebra : not null access constant Algebra_Tree_Cell); function Is_Present (Algebra : not null access constant Algebra_Tree_Cell; TaskOptionId : Int64) return Boolean is (case Algebra.Node_Kind is when Action => TaskOptionId = Algebra.TaskOptionId, when Operator => (for some J in 1 .. Algebra.Collection.Num_Children => Is_Present (Algebra.Collection.Children (J), TaskOptionId)), when Undefined => False); pragma Annotate (GNATprove, Terminating, Is_Present); function Get_Next_Objectives_Ids (Assignment : Int64_Seq; Algebra : not null access constant Algebra_Tree_Cell) return Int64_Seq with Post => (for all ObjectiveId of Get_Next_Objectives_Ids'Result => (Is_Present (Algebra, ObjectiveId) and then not Contains (Assignment, Int64_Sequences.First, Last (Assignment), ObjectiveId))); pragma Annotate (GNATprove, Terminating, Get_Next_Objectives_Ids); -- Returns a sequence of TaskOptionIds corresponding to the next possible -- actions considering Assignment. procedure Free_Tree (X : in out Algebra_Tree) with Depends => (X => X), Post => X = null; end Algebra;
with Ada.Text_IO; use Ada.Text_IO; package body Buffer is protected body CircularBuffer is entry WriteBuf(X: in INTEGER) --write data to buffer when count<N is --no writing to a full buffer begin A(In_Ptr):=X; In_Ptr:=In_Ptr+1; count:=count+1; end WriteBuf; entry ReadBuf(Y: out INTEGER) --read data from buffer when count>0 is --no reading from empty buffer begin Y:=A(Out_Ptr); if flag=0 then --increment Out_Ptr only when both consumers have read the data flag:=1; else Out_Ptr:=Out_Ptr+1; count:=count-1; flag:=0; end if; end ReadBuf; end CircularBuffer; end Buffer;
-- Example_Adafunctions -- A example of using the Ada 2012 interface to Lua for functions / closures etc -- Copyright (c) 2015, James Humphry - see LICENSE for terms with Lua; use Lua; package Example_AdaFunctions is function FooBar (L : Lua_State'Class) return Natural; function Multret (L : Lua_State'Class) return Natural; function Closure (L : Lua_State'Class) return Natural; end Example_AdaFunctions;
package Lto17 is type Chunk_List_Element; type Chunk_List is access Chunk_List_Element; type Arr is array (Natural range <>) of Integer; type Chunk(Size : Natural) is record Data : Arr(1 .. Size); Where : Natural; end record; type Chunk_List_Element(Size : Natural) is record Chnk : Chunk(Size); Link : Chunk_List; end record; function To_Chunk_List(C : Chunk) return Chunk_List; end Lto17;
-- part of OpenGLAda, (c) 2017 Felix Krause -- released under the terms of the MIT license, see the file "COPYING" package Glfw.Events.Mouse is type Button is new Interfaces.C.int range 0 .. 7; Left_Button : constant := 0; Right_Button : constant := 1; Middle_Button : constant := 2; subtype Coordinate is Interfaces.C.int; subtype Wheel_Position is Interfaces.C.int; type Button_Callback is access procedure (Subject : Button; Action : Button_State); type Position_Callback is access procedure (X, Y : Coordinate); type Wheel_Callback is access procedure (Pos : Wheel_Position); function Pressed (Query : Button) return Boolean; procedure Get_Position (X, Y : out Coordinate); procedure Set_Position (X, Y : Coordinate); function Wheel return Wheel_Position; procedure Set_Wheel (Value : Wheel_Position); procedure Set_Button_Callback (Callback : Button_Callback); procedure Set_Position_Callback (Callback : Position_Callback); procedure Set_Wheel_Callback (Callback : Wheel_Callback); procedure Toggle_Mouse_Cursor (Visible : Boolean); procedure Toggle_Sticky_Mouse_Buttons (Enable : Boolean); private for Button'Size use Interfaces.C.int'Size; end Glfw.Events.Mouse;
----------------------------------------------------------------------- -- This package generate Ada code from an XML definition file. -- Top level package -- ----------------------------------------------------------------------- package Glade3_Generate is Debug : Boolean := False; -- for internal use Old_Version : exception; -- raised when obsolete tags are found Bad_Xml : exception; -- raised when Xml parsing fails --------------------- -- Initialization -- --------------------- procedure Set_Template_Dir (Dir : in String); -- Set-up the directory where template files should be found. -- Dir must be a valid OS string -- Must be called at start-up --------------------- -- Code Generation -- --------------------- procedure Generate (Glade_File : in String; Project_Name : in String := ""; Output_Dir : in String := ""); -- Parse xml-file Glade_File and generate the corresponding Ada code. -- Glade_File usually looks like /mydir/myapp.glade or rel/myapp.xml -- Note : File must be a valid file name and may be case-sensitive. -- by default, project_name will be the base name of file. -- output is send in a file named <output_dir><base_name(file).ada> -- Any existing output file will be overwrittten. end Glade3_Generate;
package body Matrices is function "*" (Left, Right : Matrix) return Matrix is Result : Matrix (Left'Range (1), Right'Range (2)) := (others => (others => Zero)); begin if Left'Length (2) /= Right'Length (1) then raise Size_Mismatch; end if; for I in Result'Range (1) loop for K in Result'Range (2) loop for J in Left'Range (2) loop Result (I, K) := Result (I, K) + Left (I, J) * Right (J, K); end loop; end loop; end loop; return Result; end "*"; function Invert (Source : Matrix) return Matrix is Expanded : Matrix (Source'Range (1), Source'First (2) .. Source'Last (2) * 2); Result : Matrix (Source'Range (1), Source'Range (2)); begin -- Matrix has to be square. if Source'Length (1) /= Source'Length (2) then raise Not_Square_Matrix; end if; -- Copy Source into Expanded matrix and attach identity matrix to right for Row in Source'Range (1) loop for Col in Source'Range (2) loop Expanded (Row, Col) := Source (Row, Col); Expanded (Row, Source'Last (2) + Col) := Zero; end loop; Expanded (Row, Source'Last (2) + Row) := One; end loop; Expanded := Reduced_Row_Echelon_Form (Source => Expanded); -- Copy right side to Result (= inverted Source) for Row in Result'Range (1) loop for Col in Result'Range (2) loop Result (Row, Col) := Expanded (Row, Source'Last (2) + Col); end loop; end loop; return Result; end Invert; function Reduced_Row_Echelon_Form (Source : Matrix) return Matrix is procedure Divide_Row (From : in out Matrix; Row : Positive; Divisor : Element_Type) is begin for Col in From'Range (2) loop From (Row, Col) := From (Row, Col) / Divisor; end loop; end Divide_Row; procedure Subtract_Rows (From : in out Matrix; Subtrahend, Minuend : Positive; Factor : Element_Type) is begin for Col in From'Range (2) loop From (Minuend, Col) := From (Minuend, Col) - From (Subtrahend, Col) * Factor; end loop; end Subtract_Rows; procedure Swap_Rows (From : in out Matrix; First, Second : Positive) is Temporary : Element_Type; begin for Col in From'Range (2) loop Temporary := From (First, Col); From (First, Col) := From (Second, Col); From (Second, Col) := Temporary; end loop; end Swap_Rows; Result : Matrix := Source; Lead : Positive := Result'First (2); I : Positive; begin Rows : for Row in Result'Range (1) loop exit Rows when Lead > Result'Last (2); I := Row; while Result (I, Lead) = Zero loop I := I + 1; if I = Result'Last (1) then I := Row; Lead := Lead + 1; exit Rows when Lead = Result'Last (2); end if; end loop; if I /= Row then Swap_Rows (From => Result, First => I, Second => Row); end if; Divide_Row (From => Result, Row => Row, Divisor => Result (Row, Lead)); for Other_Row in Result'Range (1) loop if Other_Row /= Row then Subtract_Rows (From => Result, Subtrahend => Row, Minuend => Other_Row, Factor => Result (Other_Row, Lead)); end if; end loop; Lead := Lead + 1; end loop Rows; return Result; end Reduced_Row_Echelon_Form; function Regression_Coefficients (Source : Vector; Regressors : Matrix) return Vector is Result : Matrix (Regressors'Range (2), 1 .. 1); begin if Source'Length /= Regressors'Length (1) then raise Size_Mismatch; end if; declare Regressors_T : constant Matrix := Transpose (Regressors); begin Result := Invert (Regressors_T * Regressors) * Regressors_T * To_Matrix (Source); end; return To_Row_Vector (Source => Result); end Regression_Coefficients; function To_Column_Vector (Source : Matrix; Row : Positive := 1) return Vector is Result : Vector (Source'Range (2)); begin for Column in Result'Range loop Result (Column) := Source (Row, Column); end loop; return Result; end To_Column_Vector; function To_Matrix (Source : Vector; Column_Vector : Boolean := True) return Matrix is Result : Matrix (1 .. 1, Source'Range); begin for Column in Source'Range loop Result (1, Column) := Source (Column); end loop; if Column_Vector then return Transpose (Result); else return Result; end if; end To_Matrix; function To_Row_Vector (Source : Matrix; Column : Positive := 1) return Vector is Result : Vector (Source'Range (1)); begin for Row in Result'Range loop Result (Row) := Source (Row, Column); end loop; return Result; end To_Row_Vector; function Transpose (Source : Matrix) return Matrix is Result : Matrix (Source'Range (2), Source'Range (1)); begin for Row in Result'Range (1) loop for Column in Result'Range (2) loop Result (Row, Column) := Source (Column, Row); end loop; end loop; return Result; end Transpose; end Matrices;
----------------------------------------------------------------------- -- ADO Objects Tests -- Tests for ADO.Objects -- Copyright (C) 2011 - 2020 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Util.Test_Caller; with ADO.Sessions; with Regtests.Simple.Model; with Regtests.Comments; with Regtests.Statements.Model; with Regtests.Audits.Model; package body ADO.Objects.Tests is use Util.Tests; use type Ada.Containers.Hash_Type; TIME_VALUE1 : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1901, Month => 1, Day => 2, Seconds => 0.0); TIME_VALUE2 : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1981, Month => 3, Day => 22, Seconds => 40.0); -- Test the Set_xxx and Get_xxx operation on various simple times. generic Name : String; type Element_Type (<>) is private; with function "=" (Left, Right : in Element_Type) return Boolean is <>; with procedure Set_Value (Item : in out Regtests.Statements.Model.Nullable_Table_Ref; Val : in Element_Type); with function Get_Value (Item : in Regtests.Statements.Model.Nullable_Table_Ref) return Element_Type; Val1 : Element_Type; Val2 : Element_Type; Val3 : Element_Type; procedure Test_Op (T : in out Test); procedure Test_Op (T : in out Test) is Item1 : Regtests.Statements.Model.Nullable_Table_Ref; Item2 : Regtests.Statements.Model.Nullable_Table_Ref; Item3 : Regtests.Statements.Model.Nullable_Table_Ref; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin Set_Value (Item1, Val1); Item1.Save (DB); T.Assert (Item1.Is_Inserted, Name & " item is created"); -- Util.Tests.Assert_Equals (T, T'Image (Val), T'Image ( -- Load in a second item and check the value. Item2.Load (DB, Item1.Get_Id); T.Assert (Item2.Get_Id = Item1.Get_Id, Name & " item2 cannot be loaded"); -- T.Assert (Get_Value (Item2) = Val1, Name & " invalid value loaded in item2"); -- Change the item in database. Set_Value (Item2, Val2); Item2.Save (DB); T.Assert (Get_Value (Item2) = Val2, Name & " invalid value loaded in item2"); -- Load again and compare to check the update. Item3.Load (DB, Item2.Get_Id); T.Assert (Get_Value (Item3) = Val2, Name & " invalid value loaded in item3"); begin Set_Value (Item1, Val3); Item1.Save (DB); T.Fail ("No LAZY_LOCK exception was raised."); exception when ADO.Objects.LAZY_LOCK => null; end; Set_Value (Item3, Val3); Item3.Save (DB); T.Assert (Get_Value (Item3) = Val3, Name & " invalid value loaded in item3"); Item1.Load (DB, Item1.Get_Id); T.Assert (Get_Value (Item1) = Val3, Name & " invalid value loaded in item1"); end Test_Op; procedure Test_Object_Nullable_Integer is new Test_Op ("Nullable_Integer", Nullable_Integer, "=", Regtests.Statements.Model.Set_Int_Value, Regtests.Statements.Model.Get_Int_Value, Nullable_Integer '(Value => 123, Is_Null => False), Nullable_Integer '(Value => 0, Is_Null => True), Nullable_Integer '(Value => 231, Is_Null => False)); procedure Test_Object_Nullable_Entity_Type is new Test_Op ("Nullable_Entity_Type", Nullable_Entity_Type, "=", Regtests.Statements.Model.Set_Entity_Value, Regtests.Statements.Model.Get_Entity_Value, Nullable_Entity_Type '(Value => 456, Is_Null => False), Nullable_Entity_Type '(Value => 0, Is_Null => True), Nullable_Entity_Type '(Value => 564, Is_Null => False)); procedure Test_Object_Nullable_Time is new Test_Op ("Nullable_Time", Nullable_Time, "=", Regtests.Statements.Model.Set_Time_Value, Regtests.Statements.Model.Get_Time_Value, Nullable_Time '(Value => TIME_VALUE1, Is_Null => False), Nullable_Time '(Value => <>, Is_Null => True), Nullable_Time '(Value => TIME_VALUE2, Is_Null => False)); function Get_Allocate_Key (N : Identifier) return Object_Key; function Get_Allocate_Key (N : Identifier) return Object_Key is Result : Object_Key (Of_Type => KEY_INTEGER, Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE); begin Set_Value (Result, N); return Result; end Get_Allocate_Key; -- ------------------------------ -- Various tests on Hash and key comparison -- ------------------------------ procedure Test_Key (T : in out Test) is K1 : constant Object_Key := Get_Allocate_Key (1); K2 : Object_Key (Of_Type => KEY_STRING, Of_Class => Regtests.Simple.Model.USER_TABLE); K3 : Object_Key := K1; K4 : Object_Key (Of_Type => KEY_INTEGER, Of_Class => Regtests.Simple.Model.USER_TABLE); begin T.Assert (not (K1 = K2), "Key on different tables must be different"); T.Assert (not (K2 = K4), "Key with different type must be different"); T.Assert (K1 = K3, "Keys are identical"); T.Assert (Equivalent_Elements (K1, K3), "Keys are identical"); T.Assert (Equivalent_Elements (K3, K1), "Keys are identical"); T.Assert (Hash (K1) = Hash (K3), "Hash of identical keys should be identical"); Set_Value (K3, 2); T.Assert (not (K1 = K3), "Keys should be different"); T.Assert (Hash (K1) /= Hash (K3), "Hash should be different"); T.Assert (Hash (K1) /= Hash (K2), "Hash should be different"); Set_Value (K4, 1); T.Assert (Hash (K1) /= Hash (K4), "Hash on key with same value and different tables should be different"); T.Assert (not (K4 = K1), "Key on different tables should be different"); Set_Value (K2, 1); T.Assert (Hash (K1) /= Hash (K2), "Hash should be different"); end Test_Key; -- ------------------------------ -- Check: -- Object_Ref := (reference counting) -- Object_Ref.Copy -- Object_Ref.Get_xxx generated method -- Object_Ref.Set_xxx generated method -- Object_Ref.= -- ------------------------------ procedure Test_Object_Ref (T : in out Test) is use type Regtests.Simple.Model.User_Ref; Obj1 : Regtests.Simple.Model.User_Ref; Null_Obj : Regtests.Simple.Model.User_Ref; begin T.Assert (Obj1 = Null_Obj, "Two null objects are identical"); for I in 1 .. 10 loop Obj1.Set_Name ("User name"); T.Assert (Obj1.Get_Name = "User name", "User_Ref.Set_Name invalid result"); T.Assert (Obj1 /= Null_Obj, "Object is not identical as the null object"); declare Obj2 : constant Regtests.Simple.Model.User_Ref := Obj1; Obj3 : Regtests.Simple.Model.User_Ref; begin Obj1.Copy (Obj3); Obj3.Set_Id (2); -- Check the copy T.Assert (Obj2.Get_Name = "User name", "Object_Ref.Copy invalid copy"); T.Assert (Obj3.Get_Name = "User name", "Object_Ref.Copy invalid copy"); T.Assert (Obj2 = Obj1, "Object_Ref.'=' invalid comparison after assignment"); T.Assert (Obj3 /= Obj1, "Object_Ref.'=' invalid comparison after copy"); -- Change original, make sure it's the same of Obj2. Obj1.Set_Name ("Second name"); T.Assert (Obj2.Get_Name = "Second name", "Object_Ref.Copy invalid copy"); T.Assert (Obj2 = Obj1, "Object_Ref.'=' invalid comparison after assignment"); -- The copy is not modified T.Assert (Obj3.Get_Name = "User name", "Object_Ref.Copy invalid copy"); end; end loop; end Test_Object_Ref; -- ------------------------------ -- Test creation of an object with lazy loading. -- ------------------------------ procedure Test_Create_Object (T : in out Test) is User : Regtests.Simple.Model.User_Ref; Cmt : Regtests.Comments.Comment_Ref; begin -- Create an object within a transaction. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin S.Begin_Transaction; User.Set_Name ("Joe"); User.Set_Value (0); User.Save (S); S.Commit; end; -- Load it from another session. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; U2 : Regtests.Simple.Model.User_Ref; begin U2.Load (S, User.Get_Id); T.Assert (not U2.Get_Name.Is_Null, "Cannot load created object"); Assert_Equals (T, "Joe", Ada.Strings.Unbounded.To_String (U2.Get_Name.Value), "Cannot load created object"); Assert_Equals (T, Integer (0), Integer (U2.Get_Value), "Invalid load"); T.Assert (User.Get_Key = U2.Get_Key, "Invalid key after load"); end; -- Create a comment for the user. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin S.Begin_Transaction; Cmt.Set_Message (Ada.Strings.Unbounded.To_Unbounded_String ("A comment from Joe")); Cmt.Set_User (User); Cmt.Set_Entity_Id (2); Cmt.Set_Entity_Type (1); -- Cmt.Set_Date (ADO.DEFAULT_TIME); Cmt.Set_Date (Ada.Calendar.Clock); Cmt.Save (S); S.Commit; end; -- Load that comment. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; C2 : Regtests.Comments.Comment_Ref; begin T.Assert (not C2.Is_Loaded, "Object is not loaded"); C2.Load (S, Cmt.Get_Id); T.Assert (not C2.Is_Null, "Loading of object failed"); T.Assert (C2.Is_Loaded, "Object is loaded"); T.Assert (Cmt.Get_Key = C2.Get_Key, "Invalid key after load"); T.Assert_Equals ("A comment from Joe", Ada.Strings.Unbounded.To_String (C2.Get_Message), "Invalid message"); T.Assert (not C2.Get_User.Is_Null, "User associated with the comment should not be null"); -- T.Assert (not C2.Get_Entity_Type.Is_Null, "Entity type was not set"); -- Check that we can access the user name (lazy load) Assert_Equals (T, "Joe", Ada.Strings.Unbounded.To_String (C2.Get_User.Get_Name.Value), "Cannot load created object"); end; end Test_Create_Object; -- ------------------------------ -- Test creation and deletion of an object record -- ------------------------------ procedure Test_Delete_Object (T : in out Test) is User : Regtests.Simple.Model.User_Ref; begin -- Create an object within a transaction. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin S.Begin_Transaction; User.Set_Name ("Joe (delete)"); User.Set_Value (0); User.Save (S); S.Commit; end; -- Load it and delete it from another session. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; U2 : Regtests.Simple.Model.User_Ref; begin U2.Load (S, User.Get_Id); S.Begin_Transaction; U2.Delete (S); S.Commit; end; -- Try to load the deleted object. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; U2 : Regtests.Simple.Model.User_Ref; begin U2.Load (S, User.Get_Id); T.Assert (False, "Load of a deleted object should raise NOT_FOUND"); exception when ADO.Objects.NOT_FOUND => null; end; end Test_Delete_Object; -- ------------------------------ -- Test Is_Inserted and Is_Null -- ------------------------------ procedure Test_Is_Inserted (T : in out Test) is User : Regtests.Simple.Model.User_Ref; begin T.Assert (not User.Is_Inserted, "A null object should not be marked as INSERTED"); T.Assert (User.Is_Null, "A null object should be marked as NULL"); -- Create an object within a transaction. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin S.Begin_Transaction; User.Set_Name ("John"); T.Assert (not User.Is_Null, "User should not be NULL"); T.Assert (not User.Is_Inserted, "User was not saved and not yet inserted in database"); User.Set_Value (1); User.Save (S); S.Commit; T.Assert (User.Is_Inserted, "After a save operation, the user should be marked INSERTED"); T.Assert (not User.Is_Null, "User should not be NULL"); end; declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; John : Regtests.Simple.Model.User_Ref; begin John.Load (S, User.Get_Id); T.Assert (John.Is_Inserted, "After a load, the object should be marked INSERTED"); T.Assert (not John.Is_Null, "After a load, the object should not be NULL"); end; end Test_Is_Inserted; -- ------------------------------ -- Test Is_Modified -- ------------------------------ procedure Test_Is_Modified (T : in out Test) is User : Regtests.Simple.Model.User_Ref; begin T.Assert (not User.Is_Modified, "A null object should not be MODIFIED"); -- Create an object within a transaction. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin S.Begin_Transaction; User.Set_Name ("John"); T.Assert (User.Is_Modified, "User should be modified"); User.Set_Value (1); User.Save (S); T.Assert (not User.Is_Modified, "User should be not modified after save"); S.Commit; end; declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; John : Regtests.Simple.Model.User_Ref; begin John.Load (S, User.Get_Id); T.Assert (John.Is_Inserted, "After a load, the object should be marked INSERTED"); T.Assert (not John.Is_Null, "After a load, the object should not be NULL"); T.Assert (not John.Is_Modified, "After a load, the object should not be MODIFIED"); John.Set_Name ("John"); T.Assert (not User.Is_Modified, "User should be modified"); end; end Test_Is_Modified; -- ------------------------------ -- Test object creation/update/load with string as key. -- ------------------------------ procedure Test_String_Key (T : in out Test) is Item1 : Regtests.Audits.Model.Property_Ref; Item2 : Regtests.Audits.Model.Property_Ref; Item3 : Regtests.Audits.Model.Property_Ref; S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Uuid : constant String := Util.Tests.Get_Uuid; begin Item1.Set_Id ("name " & Uuid); Item1.Set_Value ((Is_Null => False, Value => 123)); Item1.Set_Float_Value (23.44); Item1.Save (S); T.Assert (Item1.Is_Inserted, "Object with string key is not inserted"); Util.Tests.Assert_Equals (T, "name " & Uuid, String '(Item1.Get_Id), "Object key is invalid"); Item2.Set_Id ("name2 " & Uuid); Item2.Set_Value ((Is_Null => True, Value => 0)); Item2.Set_Float_Value (34.23); Item2.Save (S); Item3.Load (S, Ada.Strings.Unbounded.To_Unbounded_String ("name " & Uuid)); T.Assert (Item3.Is_Loaded, "Item3 must be loaded"); T.Assert (not Item3.Get_Value.Is_Null, "Item3 value must not be null"); Util.Tests.Assert_Equals (T, 123, Item3.Get_Value.Value, "Item3 value is invalid"); end Test_String_Key; package Caller is new Util.Test_Caller (Test, "ADO.Objects"); -- ------------------------------ -- Add the tests in the test suite -- ------------------------------ procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Objects.Hash", Test_Key'Access); Caller.Add_Test (Suite, "Test Object_Ref.Get/Set", Test_Object_Ref'Access); Caller.Add_Test (Suite, "Test ADO.Objects.Create", Test_Create_Object'Access); Caller.Add_Test (Suite, "Test ADO.Objects.Delete", Test_Delete_Object'Access); Caller.Add_Test (Suite, "Test ADO.Objects.Is_Created", Test_Is_Inserted'Access); Caller.Add_Test (Suite, "Test ADO.Objects.Is_Modified", Test_Is_Modified'Access); Caller.Add_Test (Suite, "Test ADO.Objects (Nullable_Integer)", Test_Object_Nullable_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Objects (Nullable_Entity_Type)", Test_Object_Nullable_Entity_Type'Access); Caller.Add_Test (Suite, "Test ADO.Objects (Nullable_Time)", Test_Object_Nullable_Time'Access); Caller.Add_Test (Suite, "Test ADO.Objects.Create (String key)", Test_String_Key'Access); end Add_Tests; end ADO.Objects.Tests;
----------------------------------------------------------------------- -- akt-commands-create -- Create a keystore -- Copyright (C) 2019, 2021 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Keystore.Passwords.Files; with Keystore.Passwords.Input; package body AKT.Commands.Create is use GNAT.Strings; use type Keystore.Passwords.Provider_Access; use type Keystore.Passwords.Keys.Key_Provider_Access; -- ------------------------------ -- Create the keystore file. -- ------------------------------ overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Name); Path : constant String := Context.Get_Keystore_Path (Args); begin Setup_Password_Provider (Context); if Command.Counter_Range /= null and then Command.Counter_Range'Length > 0 then Parse_Range (Command.Counter_Range.all, Context.Config); end if; Context.Config.Overwrite := Command.Force; if Command.Storage_Count /= null and then Command.Storage_Count'Length > 0 then begin Context.Config.Storage_Count := Positive'Value (Command.Storage_Count.all); exception when others => AKT.Commands.Log.Error (-("split counter is invalid or out of range: {0}"), Command.Storage_Count.all); raise Error; end; end if; if Context.Data_Path'Length > 0 and Context.Config.Storage_Count = 1 then Context.Config.Storage_Count := 10; end if; if Command.Gpg_Mode then if Args.Get_Count < Context.First_Arg then AKT.Commands.Log.Error (-("missing GPG user name")); raise Error; end if; Context.GPG.Create_Secret; Context.Wallet.Set_Master_Key (Context.GPG); Context.Wallet.Create (Password => Context.GPG, Path => Path, Data_Path => Context.Data_Path.all, Config => Context.Config); Context.GPG.Save_Secret (Args.Get_Argument (Context.First_Arg), 1, Context.Wallet); for I in Context.First_Arg + 1 .. Args.Get_Count loop declare GPG2 : Keystore.Passwords.GPG.Context_Type; begin GPG2.Create_Secret (Image => Context.GPG); Context.Wallet.Set_Key (Context.GPG, GPG2, Context.Config, Keystore.KEY_ADD); GPG2.Save_Secret (Args.Get_Argument (I), Keystore.Header_Slot_Index_Type (I), Context.Wallet); end; end loop; else if Context.Wallet_Key_File'Length > 0 then Context.Key_Provider := Keystore.Passwords.Files.Generate (Context.Wallet_Key_File.all); end if; if Context.Key_Provider /= null then Context.Wallet.Set_Master_Key (Context.Key_Provider.all); end if; if Context.Provider = null then Context.Provider := Keystore.Passwords.Input.Create (-("Enter password: "), False); end if; Keystore.Files.Create (Container => Context.Wallet, Password => Context.Provider.all, Path => Path, Data_Path => Context.Data_Path.all, Config => Context.Config); end if; end Execute; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ procedure Setup (Command : in out Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type) is package GC renames GNAT.Command_Line; begin Setup (Config, Context); GC.Define_Switch (Config => Config, Output => Command.Counter_Range'Access, Switch => "-c:", Long_Switch => "--counter-range:", Argument => "RANGE", Help => -("Set the range for the PBKDF2 counter")); GC.Define_Switch (Config => Config, Output => Command.Storage_Count'Access, Switch => "-S:", Long_Switch => "--split:", Argument => "COUNT", Help => -("Split the data blocks in COUNT separate files")); GC.Define_Switch (Config => Config, Output => Command.Force'Access, Switch => "-f", Long_Switch => "--force", Help => -("Force the creation of the keystore")); GC.Define_Switch (Config => Config, Output => Command.Gpg_Mode'Access, Switch => "-g", Long_Switch => "--gpg", Help => -("Use gpg to protect the keystore access")); end Setup; end AKT.Commands.Create;
with MathUtils; package body Tensor is function Element_Count(d: in Var'Class) return Positive is begin return Positive(d.data.Length); end Element_Count; function Allocate(value_count: in Positive) return Var is begin return r: Var do r.size.Append(value_count); r.data.Set_Length(Ada.Containers.Count_Type(value_count)); end return; end Allocate; function Variable(values: in Float_Array) return Var is result: Var; idx_out: Natural := 1; begin result.size.Set_Length(1); result.data.Set_Length(values'Length); result.size(1) := values'Length; for idx_in in values'First .. values'Last loop result.data(idx_out) := values(idx_in); idx_out := idx_out + 1; end loop; return result; end Variable; function Matrix(row_length: in Positive; values: in Float_Array) return Var is result: Var; idx_out: Natural := 1; begin result.size.Set_Length(2); result.data.Set_Length(values'Length); result.size(1) := values'Length / row_length; result.size(2) := row_length; for idx_in in values'First .. values'Last loop result.data(idx_out) := values(idx_in); idx_out := idx_out + 1; end loop; return result; end Matrix; function Dimension_Count(v: in Var'Class) return Positive is begin return Positive(v.size.Length); end Dimension_Count; function Dimension(v: in Var'Class; n_dim: in Positive) return Positive is begin return v.size(n_dim); end Dimension; function Data(v: in Var) return MathUtils.Vector is begin return v.data; end Data; function Element(v: in Var; idx_0, idx_1: in Positive) return Float is begin if idx_0 = 1 then return v.data(idx_1); else return v.data( (idx_0 - 1) * v.size(2) + idx_1 ); end if; end Element; procedure Set(v: out Var; values: in Float_Array) is idx_out: Natural := 1; begin v.data.Set_Length(values'Length); for idx_in in values'First .. values'Last loop v.data(idx_out) := values(idx_in); idx_out := idx_out + 1; end loop; end Set; procedure Set(v: out Var; idx: Positive; value: in Float) is begin v.data(idx) := value; end Set; function Flatten(v: in Var'Class) return Var is result: Var; begin result.data := v.data; result.size.Append(Element_Count(v)); return result; end Flatten; procedure Flatten(v: in out Var'Class) is begin v.size.Clear; v.size.Append(Positive(v.data.Length)); end Flatten; procedure Reshape(v: in out Var'Class; s0, s1: Positive) is begin v.size.Clear; v.size.Append(s0); v.size.Append(s1); end Reshape; procedure Random(v: in out Var'Class) is begin for i in v.data.First_Index .. v.data.Last_Index loop v.data.Replace_Element(i, MathUtils.rand01); end loop; end Random; function Dot_Elem_Count(v0, v1: in Var'Class) return Positive is begin if v0.Dimension_Count = 1 and v1.Dimension_Count = 1 then return 1; else return v0.Dimension(1); end if; end Dot_Elem_Count; function Dot(v0, v1: in Var'Class) return Var is result: Var; begin result.size.Append(Dot_Elem_Count(v0, v1)); result.data.Set_Length(Ada.Containers.Count_Type(Dot_Elem_Count(v0, v1))); for r in 1 .. result.size.Element(1) loop declare row_result: Float := 0.0; begin for k in 1 .. v1.Dimension(1) loop row_result := row_result + v1.Data(k) * v0.Element(r, k); end loop; result.data.Replace_Element(r, row_result); end; end loop; return result; end Dot; function "+" (v0, v1: in Var'Class) return Var is result: Var; begin result.size := v0.size; result.data := v0.data; declare idx_0: Positive := result.data.First_Index; begin for val of v1.data loop result.data.Replace_Element(idx_0, result.data.Element(idx_0) + val); idx_0 := idx_0 + 1; end loop; end; return result; end "+"; function "-" (v0, v1: in Var'Class) return Var is result: Var; begin result.size := v0.size; result.data := v0.data; declare idx_0: Positive := result.data.First_Index; begin for val of v1.data loop result.data.Replace_Element(idx_0, result.data.Element(idx_0) - val); idx_0 := idx_0 + 1; end loop; end; return result; end "-"; procedure Apply(v: in out Var; fn: Lambda_Func) is begin for idx in v.data.First_Index .. v.data.Last_Index loop declare new_val: constant Float := fn(v.data(idx)); begin v.data.Replace_Element(idx, new_val); end; end loop; end Apply; end Tensor;
-- ___ _ ___ _ _ -- -- / __| |/ (_) | | Common SKilL implementation -- -- \__ \ ' <| | | |__ skills vector container implementation -- -- |___/_|\_\_|_|____| by: Dennis Przytarski, Timm Felden -- -- -- pragma Ada_2012; with Ada.Finalization; -- vector, can also be used as a stack -- vector element operation is total, i.e. it will never raise an exception -- instead of exception, Err_Val will be returned generic type Index_Type is range <>; type Element_Type is private; -- Err_Val : Element_Type; package Skill.Containers.Vectors is type Vector_T is tagged limited private; type Vector is access Vector_T; function Empty_Vector return Vector; procedure Free (This : access Vector_T); -- applies F for each element in this procedure Foreach (This : not null access Vector_T'Class; F : not null access procedure (I : Element_Type)); -- appends element to the vector procedure Append (This : not null access Vector_T'Class; New_Element : Element_Type); -- appends element to the vector and assumes that the vector has a spare slot procedure Append_Unsafe (This : not null access Vector_T'Class; New_Element : Element_Type); -- apppends all elements stored in argument vector procedure Append_All (This : access Vector_T'Class; Other : Vector); -- prepends all elements stored in argument vector procedure Prepend_All (This : access Vector_T'Class; Other : Vector); -- prepends a number of undefined elements to this vector procedure Append_Undefined (This : access Vector_T'Class; Count : Natural); -- prepends a number of undefined elements to this vector procedure Prepend_Undefined (This : access Vector_T'Class; Count : Natural); -- remove the last element function Pop (This : access Vector_T'Class) return Element_Type; -- get element at argument index function Element (This : access Vector_T'Class; Index : Index_Type) return Element_Type with Pre => Check_Index (This, Index); -- returns the last element in the vector or raises constraint error if empty function Last_Element (This : access Vector_T'Class) return Element_Type; -- returns the first element in the vector or raises constraint error if empty function First_Element (This : access Vector_T'Class) return Element_Type; -- ensures that an index can be allocated procedure Ensure_Index (This : access Vector_T'Class; New_Index : Index_Type); -- allocates an index, filling previous elements with random garbage! procedure Ensure_Allocation (This : access Vector_T'Class; New_Index : Index_Type); -- length of the container function Length (This : access Vector_T'Class) return Natural; -- true iff empty function Is_Empty (This : access Vector_T'Class) return Boolean; -- remove all elements procedure Clear (This : access Vector_T'Class); -- checks if an index is used function Check_Index (This : access Vector_T'Class; Index : Index_Type) return Boolean; -- replace element at given index procedure Replace_Element (This : access Vector_T'Class; Index : Index_Type; Element : Element_Type); pragma Inline (Foreach); -- pragma Inline (Append); pragma Inline (Append_Unsafe); pragma Inline (Pop); pragma Inline (Element); pragma Inline (Last_Element); pragma Inline (Ensure_Index); pragma Inline (Ensure_Allocation); pragma Inline (Length); pragma Inline (Is_Empty); pragma Inline (Clear); pragma Inline (Check_Index); pragma Inline (Replace_Element); private subtype Index_Base is Index_Type'Base; type Element_Array_T is array (Index_Type range <>) of Element_Type; type Element_Array is not null access Element_Array_T; type Element_Array_Access is access all Element_Array_T; type Vector_T is tagged limited record -- access to the actual data stored in the vector Data : Element_Array; -- the next index to be used, i.e. an exclusive border Next_Index : Index_Base; end record; end Skill.Containers.Vectors;
pragma Style_Checks (Off); pragma Warnings (Off); ------------------------------------------------------------------------- -- GL.Geometry - GL geometry primitives -- -- Copyright (c) Rod Kay 2007 -- AUSTRALIA -- Permission granted to use this software, without any warranty, -- for any purpose, provided this copyright note remains attached -- and unmodified if sources are distributed further. ------------------------------------------------------------------------- with Ada.Numerics.Generic_Elementary_functions; with Ada.Text_IO; use Ada.Text_IO; package body GL.Geometry.primal is function primitive_Id (Self : in primal_Geometry) return GL.ObjectTypeEnm is begin return self.primitive.primitive_Id; end; function vertex_Count (Self : in primal_Geometry) return GL.geometry.vertex_Id is begin return self.primitive.Vertices'Length; end; function indices_Count (Self : in primal_Geometry) return GL.positive_uInt is begin return self.primitive.Indices'Length; end; function Bounds (Self : in primal_Geometry) return GL.geometry.Bounds_record is begin return Bounds (self.Primitive.Vertices.all); end; function Vertices (Self : in primal_Geometry) return GL.geometry.GL_Vertex_array is begin return self.primitive.Vertices.all; end; procedure set_Vertices (Self : in out primal_Geometry; To : access GL.geometry.GL_Vertex_array) is begin self.primitive.set_Vertices (to => To); self.Bounds := Bounds (self.primitive.Vertices.all); end; function Indices (Self : in primal_Geometry) return GL.geometry.vertex_Id_array is the_Indices : GL.geometry.vertex_Id_array := self.primitive.Indices.all; begin increment (the_Indices); return the_Indices; end; procedure set_Indices (Self : in out primal_Geometry; To : access GL.geometry.vertex_Id_array) is begin self.primitive.set_Indices (to => To); end; procedure Draw (Self : in primal_Geometry) is begin self.Primitive.draw; end; procedure destroy (Self : in out primal_Geometry) is use Primitives; begin free (self.Primitive); end; end GL.Geometry.primal;
-- C53007A.ADA -- Grant of Unlimited Rights -- -- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687, -- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained -- unlimited rights in the software and documentation contained herein. -- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making -- this public release, the Government intends to confer upon all -- recipients unlimited rights equal to those held by the Government. -- These rights include rights to use, duplicate, release or disclose the -- released technical data and computer software in whole or in part, in -- any manner and for any purpose whatsoever, and to have or permit others -- to do so. -- -- DISCLAIMER -- -- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR -- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED -- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE -- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE -- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A -- PARTICULAR PURPOSE OF SAID MATERIAL. --* -- CHECK THAT CONTROL FLOWS CORRECTLY IN SIMPLE NESTED IF_STATEMENTS. -- JRK 7/23/80 -- SPS 3/4/83 WITH REPORT; PROCEDURE C53007A IS USE REPORT; CI1 : CONSTANT INTEGER := 1; CI9 : CONSTANT INTEGER := 9; CBT : CONSTANT BOOLEAN := TRUE; CBF : CONSTANT BOOLEAN := FALSE; VI1 : INTEGER := IDENT_INT(1); VI9 : INTEGER := IDENT_INT(9); VBT : BOOLEAN := IDENT_BOOL(TRUE); VBF : BOOLEAN := IDENT_BOOL(FALSE); FLOW_COUNT : INTEGER := 0; BEGIN TEST ("C53007A", "CHECK THAT CONTROL FLOWS CORRECTLY IN SIMPLE " & "NESTED IF_STATEMENTS"); IF VBF THEN -- (FALSE) FAILED ("INCORRECT CONTROL FLOW 1"); ELSIF CI9 < 20 THEN -- (TRUE) FLOW_COUNT := FLOW_COUNT + 1; IF VI1 /= 0 AND TRUE THEN -- (TRUE) FLOW_COUNT := FLOW_COUNT + 1; ELSE FAILED ("INCORRECT CONTROL FLOW 2"); END IF; ELSE FAILED ("INCORRECT CONTROL FLOW 3"); END IF; IF CBF OR ELSE VI9 = 9 THEN -- (TRUE) IF VI1 + CI9 > 0 OR (CBF AND VBT) THEN -- (TRUE) FLOW_COUNT := FLOW_COUNT + 1; END IF; ELSIF VBF OR VI1 > 10 THEN -- (FALSE) FAILED ("INCORRECT CONTROL FLOW 4"); END IF; IF NOT CBT AND THEN NOT VBT AND THEN CI9 < 0 THEN -- (FALSE) IF FALSE OR NOT TRUE THEN -- (FALSE) FAILED ("INCORRECT CONTROL FLOW 5"); ELSIF VI1 >= 0 THEN -- (TRUE) NULL; ELSE FAILED ("INCORRECT CONTROL FLOW 6"); END IF; FAILED ("INCORRECT CONTROL FLOW 7"); ELSIF (VI1 * CI9 + 3 < 0) OR (VBT AND NOT (CI1 < 0)) THEN -- (TRUE) FLOW_COUNT := FLOW_COUNT + 1; IF NOT CBT OR ELSE CI9 + 1 = 0 THEN -- (FALSE) FAILED ("INCORRECT CONTROL FLOW 8"); ELSE FLOW_COUNT := FLOW_COUNT + 1; IF VI1 * 2 > 0 THEN -- (TRUE) FLOW_COUNT := FLOW_COUNT + 1; ELSIF TRUE THEN -- (TRUE) FAILED ("INCORRECT CONTROL FLOW 9"); ELSE NULL; END IF; END IF; ELSIF FALSE AND CBF THEN -- (FALSE) FAILED ("INCORRECT CONTROL FLOW 10"); ELSE IF VBT THEN -- (TRUE) FAILED ("INCORRECT CONTROL FLOW 11"); ELSIF VI1 = 0 THEN -- (FALSE) FAILED ("INCORRECT CONTROL FLOW 12"); ELSE FAILED ("INCORRECT CONTROL FLOW 13"); END IF; END IF; IF 3 = 5 OR NOT VBT THEN -- (FALSE) FAILED ("INCORRECT CONTROL FLOW 14"); IF TRUE AND CBT THEN -- (TRUE) FAILED ("INCORRECT CONTROL FLOW 15"); ELSE FAILED ("INCORRECT CONTROL FLOW 16"); END IF; ELSIF CBF THEN -- (FALSE) IF VI9 >= 0 OR FALSE THEN -- (TRUE) IF VBT THEN -- (TRUE) FAILED ("INCORRECT CONTROL FLOW 17"); END IF; FAILED ("INCORRECT CONTROL FLOW 18"); ELSIF VI1 + CI9 /= 0 THEN -- (TRUE) FAILED ("INCORRECT CONTROL FLOW 19"); END IF; FAILED ("INCORRECT CONTROL FLOW 20"); ELSE IF VBT AND CI9 - 9 = 0 THEN -- (TRUE) IF FALSE THEN -- (FALSE) FAILED ("INCORRECT CONTROL FLOW 21"); ELSIF NOT VBF AND THEN CI1 > 0 THEN -- (TRUE) FLOW_COUNT := FLOW_COUNT + 1; ELSE FAILED ("INCORRECT CONTROL FLOW 22"); END IF; FLOW_COUNT := FLOW_COUNT + 1; ELSIF NOT CBF OR VI1 /= 0 THEN -- (TRUE) IF VBT THEN -- (TRUE) NULL; END IF; FAILED ("INCORRECT CONTROL FLOW 23"); ELSE FAILED ("INCORRECT CONTROL FLOW 24"); END IF; FLOW_COUNT := FLOW_COUNT + 1; END IF; IF FLOW_COUNT /= 9 THEN FAILED ("INCORRECT FLOW_COUNT VALUE"); END IF; RESULT; END C53007A;
separate (Numerics) function Abs_Max_RA (Item : in Real_Vector) return Real is Result : Real := 0.0; begin for N of Item loop Result := Real'Max (Result, abs (N)); end loop; return Result; end Abs_Max_RA;
with adaptive_quad; with Text_Io; -- always need these two lines for printing use Text_Io; with Ada.Float_Text_IO; use Ada.Float_Text_IO; with Ada.Numerics.Generic_Elementary_Functions; procedure AQMain is package FloatFunctions is new Ada.Numerics.Generic_Elementary_Functions(Float); use FloatFunctions; Epsilon:float := 0.000001; function MyF(x:float) return float is begin -- MyF return Sin(x*x); end MyF; package MyAdaptiveQuad is new Adaptive_Quad(MyF); use MyAdaptiveQuad; task type ReadPairs is entry Go(index:integer); end ReadPairs; task type ComputeArea is entry Go(x, y:float; index:integer); end ComputeArea; task type PrintResults is entry Print(x, y, z:float); end PrintResults; ReadPairsTask : array(1..5) of ReadPairs; ComputeAreaTask : array(1..5) of ComputeArea; PrintResultsTask : array(1..5) of PrintResults; task body ReadPairs is a, b:float; idx:integer; begin accept Go(index:integer) do Get(a); Get(b); idx := index; end Go; ComputeAreaTask(idx).Go(a, b, idx); end ReadPairs; task body ComputeArea is a, b:float; result:float; idx:integer; begin accept Go(x, y:float; index:integer) do a := x; b := y; idx := index; end Go; result := aquad(a, b, epsilon); PrintResultsTask(idx).Print(a, b, result); end ComputeArea; task body PrintResults is a, b:float; result:float; begin accept Print(x, y, z:float) do a := x; b := y; result := z; end Print; Put("The area under sin(x^2) for x = "); Put(a); Put(" to "); Put(b); Put(" is "); Put(result); New_Line; end PrintResults; begin -- AQMain for i in 1..5 loop ReadPairsTask(i).Go(i); end loop; end AQMain;
with Pck; use Pck; procedure Foo is C : Character := 'a'; WC : Wide_Character := 'b'; WWC : Wide_Wide_Character := 'c'; begin Do_Nothing (C'Address); -- START Do_Nothing (WC'Address); Do_Nothing (WWC'Address); end Foo;
----------------------------------------------------------------------- -- components-widgets-likes -- Social Likes Components -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with ASF.Applications; with ASF.Components.Html; with ASF.Contexts.Faces; package ASF.Components.Widgets.Likes is -- ------------------------------ -- UILike -- ------------------------------ -- The <b>UILike</b> component displays a social like button to recommend a page. type UILike is new ASF.Components.Html.UIHtmlComponent with null record; -- Get the link to submit in the like action. function Get_Link (UI : in UILike; Context : in ASF.Contexts.Faces.Faces_Context'Class) return String; -- Render the like button for Facebook or Google+. overriding procedure Encode_Begin (UI : in UILike; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- ------------------------------ -- Like Generator -- ------------------------------ -- The <tt>Like_Generator</tt> represents the specific method for the generation of -- a social like generator. A generator is registered under a given name with the -- <tt>Register_Like</tt> operation. The current implementation provides a Facebook -- like generator. type Like_Generator is limited interface; type Like_Generator_Access is access all Like_Generator'Class; -- Render the like button according to the generator and the component attributes. procedure Render_Like (Generator : in Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is abstract; -- Maximum number of generators that can be registered. MAX_LIKE_GENERATOR : constant Positive := 5; -- Register the like generator under the given name. procedure Register_Like (Name : in Util.Strings.Name_Access; Generator : in Like_Generator_Access); -- ------------------------------ -- Facebook like generator -- ------------------------------ type Facebook_Like_Generator is new Like_Generator with null record; overriding procedure Render_Like (Generator : in Facebook_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- The application configuration parameter that defines which Facebook client ID must be used. package P_Facebook_App_Id is new ASF.Applications.Parameter ("facebook.client_id", ""); -- ------------------------------ -- Google like generator -- ------------------------------ type Google_Like_Generator is new Like_Generator with null record; overriding procedure Render_Like (Generator : in Google_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- ------------------------------ -- Twitter like generator -- ------------------------------ type Twitter_Like_Generator is new Like_Generator with null record; overriding procedure Render_Like (Generator : in Twitter_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class); end ASF.Components.Widgets.Likes;
------------------------------------------------------------------------------ -- Copyright (c) 2011, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Ada.Strings; use Ada.Strings; procedure Natools.Chunked_Strings.Tests.CXA4010 (Report : in out Natools.Tests.Reporter'Class) is begin Natools.Tests.Section (Report, "Port of ACATS CXA4010"); declare Pamphlet_Paragraph_Count : constant := 2; Lines : constant := 4; Line_Length : constant := 40; type Document_Type is array (Positive range <>) of Chunked_String; type Camera_Ready_Copy_Type is array (1 .. Lines) of String (1 .. Line_Length); procedure Enter_Text_Into_Document (Document : in out Document_Type); procedure Create_Camera_Ready_Copy (Document : in Document_Type; Camera_Copy : out Camera_Ready_Copy_Type); procedure Valid_Proofread (Draft, Master : Camera_Ready_Copy_Type); Pamphlet : Document_Type (1 .. Pamphlet_Paragraph_Count); Camera_Ready_Copy : Camera_Ready_Copy_Type := (others => (others => Ada.Strings.Space)); TC_Finished_Product : constant Camera_Ready_Copy_Type := (1 => "Ada is a programming language designed ", 2 => "to support long-lived, reliable software", 3 => " systems. ", 4 => "Go with Ada! "); procedure Enter_Text_Into_Document (Document : in out Document_Type) is begin Document (1) := To_Chunked_String ("Ada is a language"); Document (1) := Insert (Document (1), Index (Document (1), "language"), To_String ("progra" & Chunked_Strings."*" (2, 'm') & "ing ")); Document (1) := Overwrite (Document (1), Index (Document (1), To_String (Tail (Document (1), 8, ' ')), Ada.Strings.Backward), "language designed to support long-lifed"); Document (1) := Overwrite (Document (1), Index (Document (1), To_String (Tail (Document (1), 5, ' ')), Ada.Strings.Backward), "lived, reliable software systems."); Document (2) := 'G' & To_Chunked_String ("o ") & To_Chunked_String ("with") & ' ' & "Ada!"; end Enter_Text_Into_Document; procedure Create_Camera_Ready_Copy (Document : in Document_Type; Camera_Copy : out Camera_Ready_Copy_Type) is begin Camera_Copy (1) := Slice (Document (1), 1, Index (To_Chunked_String (Slice (Document (1), 1, Line_Length)), Ada.Strings.Maps.To_Set (' '), Ada.Strings.Inside, Ada.Strings.Backward)) & ' '; Camera_Copy (2) := Slice (Document (1), 40, Index_Non_Blank (To_Chunked_String (Slice (Document (1), 40, 79)), Ada.Strings.Backward) + 39); Camera_Copy (3) (1 .. 9) := Slice (Document (1), 80, Length (Document (1))); Camera_Copy (4) (1 .. Length (Document (2))) := To_String (Head (Document (2), Length (Document (2)))); end Create_Camera_Ready_Copy; procedure Valid_Proofread (Draft, Master : Camera_Ready_Copy_Type) is begin for I in Draft'Range loop declare Name : constant String := "Slice" & Positive'Image (I); begin if Draft (I) = Master (I) then Natools.Tests.Item (Report, Name, Natools.Tests.Success); else Natools.Tests.Item (Report, Name, Natools.Tests.Fail); Natools.Tests.Info (Report, "Draft: """ & Draft (I) & '"'); Natools.Tests.Info (Report, "Master: """ & Master (I) & '"'); end if; exception when Error : others => Natools.Tests.Report_Exception (Report, Name, Error); end; end loop; end Valid_Proofread; begin Enter_Text_Into_Document (Pamphlet); Create_Camera_Ready_Copy (Document => Pamphlet, Camera_Copy => Camera_Ready_Copy); Valid_Proofread (Draft => Camera_Ready_Copy, Master => TC_Finished_Product); exception when Error : others => Natools.Tests.Report_Exception (Report, "Preparation", Error); end; Natools.Tests.End_Section (Report); end Natools.Chunked_Strings.Tests.CXA4010;
package body openGL.Surface.privvy is function to_GLX (Self : in Surface.item'Class) return glx.Drawable is begin return Self.glx_Surface; end to_GLX; end openGL.Surface.privvy;
<with Ada.Text_IO, Simple_Parse; procedure Phrase_Reversal is function Reverse_String (Item : String) return String is Result : String (Item'Range); begin for I in Item'range loop Result (Result'Last - I + Item'First) := Item (I); end loop; return Result; end Reverse_String; function Reverse_Words(S: String) return String is Cursor: Positive := S'First; Word: String := Simple_Parse.Next_Word(S, Cursor); begin if Cursor > S'Last then -- Word holds the last word return Reverse_String(Word); else return Reverse_String(Word) & " " & Reverse_Words(S(Cursor .. S'Last)); end if; end Reverse_Words; function Reverse_Order(S: String) return String is Cursor: Positive := S'First; Word: String := Simple_Parse.Next_Word(S, Cursor); begin if Cursor > S'Last then -- Word holds the last word return Word; else return Reverse_Order(S(Cursor .. S'Last)) & " " & Word; end if; end Reverse_Order; Phrase: String := "rosetta code phrase reversal"; use Ada.Text_IO; begin Put_Line("0. The original phrase: """ & Phrase & """"); Put_Line("1. Reverse the entire phrase: """ & Reverse_String(Phrase) & """"); Put_Line("2. Reverse words, same order: """ & Reverse_Words(Phrase) & """"); Put_Line("2. Reverse order, same words: """ & Reverse_Order(Phrase) & """"); end Phrase_Reversal;
--////////////////////////////////////////////////////////// -- SFML - Simple and Fast Multimedia Library -- Copyright (C) 2007-2015 Laurent Gomila (laurent@sfml-dev.org) -- This software is provided 'as-is', without any express or implied warranty. -- In no event will the authors be held liable for any damages arising from the use of this software. -- Permission is granted to anyone to use this software for any purpose, -- including commercial applications, and to alter it and redistribute it freely, -- subject to the following restrictions: -- 1. The origin of this software must not be misrepresented; -- you must not claim that you wrote the original software. -- If you use this software in a product, an acknowledgment -- in the product documentation would be appreciated but is not required. -- 2. Altered source versions must be plainly marked as such, -- and must not be misrepresented as being the original software. -- 3. This notice may not be removed or altered from any source distribution. --////////////////////////////////////////////////////////// with Sf.System.Time; package Sf.Audio.SoundRecorder is --/< Type of the callback used when starting a capture type sfSoundRecorderStartCallback is access function (userData : Standard.System.Address) return sfBool; --/< Type of the callback used to process audio data type sfSoundRecorderProcessCallback is access function (arg1 : access sfInt16; arg2 : sfSize_t; userData : Standard.System.Address) return sfBool; --/< Type of the callback used when stopping a capture type sfSoundRecorderStopCallback is access procedure (userData : Standard.System.Address); --////////////////////////////////////////////////////////// --/ @brief Construct a new sound recorder from callback functions --/ --/ @param onStart Callback function which will be called when a new capture starts (can be NULL) --/ @param onProcess Callback function which will be called each time there's audio data to process --/ @param onStop Callback function which will be called when the current capture stops (can be NULL) --/ @param userData Data to pass to the callback function (can be NULL) --/ --/ @return A new sfSoundRecorder object (NULL if failed) --/ --////////////////////////////////////////////////////////// function create (onStart : sfSoundRecorderStartCallback; onProcess : sfSoundRecorderProcessCallback; onStop : sfSoundRecorderStopCallback; userData : Standard.System.Address) return sfSoundRecorder_Ptr; --////////////////////////////////////////////////////////// --/ @brief Destroy a sound recorder --/ --/ @param soundRecorder Sound recorder to destroy --/ --////////////////////////////////////////////////////////// procedure destroy (soundRecorder : sfSoundRecorder_Ptr); --////////////////////////////////////////////////////////// --/ @brief Start the capture of a sound recorder --/ --/ The @a sampleRate parameter defines the number of audio samples --/ captured per second. The higher, the better the quality --/ (for example, 44100 samples/sec is CD quality). --/ This function uses its own thread so that it doesn't block --/ the rest of the program while the capture runs. --/ Please note that only one capture can happen at the same time. --/ --/ @param soundRecorder Sound recorder object --/ @param sampleRate Desired capture rate, in number of samples per second --/ --/ @return True, if start of capture was successful --/ --////////////////////////////////////////////////////////// function start (soundRecorder : sfSoundRecorder_Ptr; sampleRate : sfUint32) return sfBool; --////////////////////////////////////////////////////////// --/ @brief Stop the capture of a sound recorder --/ --/ @param soundRecorder Sound recorder object --/ --////////////////////////////////////////////////////////// procedure stop (soundRecorder : sfSoundRecorder_Ptr); --////////////////////////////////////////////////////////// --/ @brief Get the sample rate of a sound recorder --/ --/ The sample rate defines the number of audio samples --/ captured per second. The higher, the better the quality --/ (for example, 44100 samples/sec is CD quality). --/ --/ @param soundRecorder Sound recorder object --/ --/ @return Sample rate, in samples per second --/ --////////////////////////////////////////////////////////// function getSampleRate (soundRecorder : sfSoundRecorder_Ptr) return sfUint32; --////////////////////////////////////////////////////////// --/ @brief Check if the system supports audio capture --/ --/ This function should always be called before using --/ the audio capture features. If it returns false, then --/ any attempt to use sfSoundRecorder will fail. --/ --/ @return sfTrue if audio capture is supported, sfFalse otherwise --/ --////////////////////////////////////////////////////////// function isAvailable return sfBool; --////////////////////////////////////////////////////////// --/ @brief Set the processing interval --/ --/ The processing interval controls the period --/ between calls to the onProcessSamples function. You may --/ want to use a small interval if you want to process the --/ recorded data in real time, for example. --/ --/ Note: this is only a hint, the actual period may vary. --/ So don't rely on this parameter to implement precise timing. --/ --/ The default processing interval is 100 ms. --/ --/ @param soundRecorder Sound recorder object --/ @param interval Processing interval --/ --////////////////////////////////////////////////////////// procedure setProcessingInterval (soundRecorder : sfSoundRecorder_Ptr; interval : Sf.System.Time.sfTime); --////////////////////////////////////////////////////////// --/ @brief Get a list of the names of all availabe audio capture devices --/ --/ This function returns an array of strings --/ containing the names of all availabe audio capture devices. --/ If no devices are available then an empty array is returned. --/ --/ @return An array of strings containing the names --/ --////////////////////////////////////////////////////////// function getAvailableDevices return sfArrayOfStrings; --////////////////////////////////////////////////////////// --/ @brief Get the name of the default audio capture device --/ --/ This function returns the name of the default audio --/ capture device. If none is available, NULL is returned. --/ --/ @return The name of the default audio capture device (null terminated) --/ --////////////////////////////////////////////////////////// function getDefaultDevice return String; --////////////////////////////////////////////////////////// --/ @brief Set the audio capture device --/ --/ This function sets the audio capture device to the device --/ with the given name. It can be called on the fly (i.e: --/ while recording). If you do so while recording and --/ opening the device fails, it stops the recording. --/ --/ @param soundRecorder Sound recorder object --/ @param name The name of the audio capture device --/ --/ @return sfTrue, if it was able to set the requested device --/ --////////////////////////////////////////////////////////// function setDevice (soundRecorder : sfSoundRecorder_Ptr; name : String) return sfBool; --////////////////////////////////////////////////////////// --/ @brief Get the name of the current audio capture device --/ --/ @param soundRecorder Sound recorder object --/ --/ @return The name of the current audio capture device --/ --////////////////////////////////////////////////////////// function getDevice (soundRecorder : sfSoundRecorder_Ptr) return String; --////////////////////////////////////////////////////////// --/ @brief Set the channel count of the audio capture device --/ --/ This method allows you to specify the number of channels --/ used for recording. Currently only 16-bit mono and --/ 16-bit stereo are supported. --/ --/ @param soundRecorder Sound recorder object --/ @param channelCount Number of channels. Currently only --/ mono (1) and stereo (2) are supported. --/ --/ @see sfSoundRecorder_getChannelCount --/ --////////////////////////////////////////////////////////// procedure setChannelCount (soundRecorder : sfSoundRecorder_Ptr; channelCount : sfUint32); --////////////////////////////////////////////////////////// --/ @brief Get the number of channels used by this recorder --/ --/ Currently only mono and stereo are supported, so the --/ value is either 1 (for mono) or 2 (for stereo). --/ --/ @return Number of channels --/ --/ @see sfSoundRecorder_setChannelCount --/ --////////////////////////////////////////////////////////// function getChannelCount (soundRecorder : sfSoundRecorder_Ptr) return sfUint32; private pragma Convention (C, sfSoundRecorderStartCallback); pragma Convention (C, sfSoundRecorderProcessCallback); pragma Convention (C, sfSoundRecorderStopCallback); pragma Import (C, create, "sfSoundRecorder_create"); pragma Import (C, destroy, "sfSoundRecorder_destroy"); pragma Import (C, start, "sfSoundRecorder_start"); pragma Import (C, stop, "sfSoundRecorder_stop"); pragma Import (C, getSampleRate, "sfSoundRecorder_getSampleRate"); pragma Import (C, isAvailable, "sfSoundRecorder_isAvailable"); pragma Import (C, setProcessingInterval, "sfSoundRecorder_setProcessingInterval"); pragma Import (C, setChannelCount, "sfSoundRecorder_setChannelCount"); pragma Import (C, getChannelCount, "sfSoundRecorder_getChannelCount"); end Sf.Audio.SoundRecorder;
-- { dg-do run } with Text_IO; use Text_IO; with GNAT.SPITBOL.Patterns; use GNAT.SPITBOL.Patterns; procedure Spipaterr is X : String := "ABCDE"; Y : Pattern := Len (1) & X (2 .. 2); begin if Match ("XB", Y) then null; else raise Program_Error; end if; end;
with Util; use Util; with Device; package body BRAM is function Get_Count(width : Natural; depth : Natural) return Natural is bram_width : constant Natural := Device.Get_BRAM_Width; bram_depth : constant Natural := Device.Get_BRAM_Depth; result : Natural := 0; begin -- Handle the BRAM that is less than bram_width wide (if there is one). if (width mod bram_width) /= 0 then declare max_width : constant Natural := bram_width * bram_depth; small_width : constant Natural := width mod bram_width; rounded_width : constant Natural := Round_Power2(small_width); small_depth : constant Natural := max_width / rounded_width; begin result := (depth + small_depth - 1) / small_depth; end; end if; -- Handle BRAMs that are bram_width wide. declare big_count : constant Natural := width / bram_width; big_depth : constant Natural := (depth + bram_depth - 1) / bram_depth; begin result := result + big_depth * big_count; end; return result; end Get_Count; end BRAM;
with IRQ; with Ada.Interrupts.Names; use Ada.Interrupts.Names; package Peripherals is Handler : IRQ.Controller (USART1_Interrupt); end Peripherals;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- A D A . E X C E P T I O N S -- -- -- -- S p e c -- -- -- -- Copyright (C) 1992-2015, Free Software Foundation, Inc. -- -- -- -- This specification is derived from the Ada Reference Manual for use with -- -- GNAT. The copyright notice above, and the license provisions that follow -- -- apply solely to the contents of the part following the private keyword. -- -- -- -- 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 version of Ada.Exceptions is used only for building the compiler -- and certain basic tools. The "real" version of Ada.Exceptions is in -- a-except-2005.ads/adb, and is used for all other builds where full Ada -- functionality is required. In particular, it is used for building run -- times on all targets. -- This version is limited to Ada 95 features. It omits Ada 2005 features -- such as the additional definitions of Exception_Name returning -- Wide_[Wide_]String. It differs from the version specified in the Ada 95 RM -- only in that it is declared Preelaborate (see declaration below for why -- this is done). -- The reason for this splitting off of a separate version is to support -- older bootstrap compilers that do not support Ada 2005 features, and -- Ada.Exceptions is part of the compiler sources. pragma Compiler_Unit_Warning; pragma Polling (Off); -- We must turn polling off for this unit, because otherwise we get -- elaboration circularities with ourself. with System; with System.Parameters; with System.Standard_Library; with System.Traceback_Entries; package Ada.Exceptions is pragma Preelaborate; -- We make this preelaborable. If we did not do this, then run time units -- used by the compiler (e.g. s-soflin.ads) would run into trouble. -- Conformance with Ada 95 is not an issue, since this version is used -- only by the compiler. type Exception_Id is private; Null_Id : constant Exception_Id; type Exception_Occurrence is limited private; type Exception_Occurrence_Access is access all Exception_Occurrence; Null_Occurrence : constant Exception_Occurrence; function Exception_Name (X : Exception_Occurrence) return String; -- Same as Exception_Name (Exception_Identity (X)) function Exception_Name (Id : Exception_Id) return String; procedure Raise_Exception (E : Exception_Id; Message : String := ""); pragma No_Return (Raise_Exception); -- Note: In accordance with AI-466, CE is raised if E = Null_Id function Exception_Message (X : Exception_Occurrence) return String; procedure Reraise_Occurrence (X : Exception_Occurrence); -- Note: it would be really nice to give a pragma No_Return for this -- procedure, but it would be wrong, since Reraise_Occurrence does return -- if the argument is the null exception occurrence. See also procedure -- Reraise_Occurrence_Always in the private part of this package. function Exception_Identity (X : Exception_Occurrence) return Exception_Id; function Exception_Information (X : Exception_Occurrence) return String; -- The format of the exception information is as follows: -- -- exception name (as in Exception_Name) -- message (or a null line if no message) -- PID=nnnn -- 0xyyyyyyyy 0xyyyyyyyy ... -- -- The lines are separated by a ASCII.LF character -- The nnnn is the partition Id given as decimal digits. -- The 0x... line represents traceback program counter locations, -- in order with the first one being the exception location. -- Note on ordering: the compiler uses the Save_Occurrence procedure, but -- not the function from Rtsfind, so it is important that the procedure -- come first, since Rtsfind finds the first matching entity. procedure Save_Occurrence (Target : out Exception_Occurrence; Source : Exception_Occurrence); function Save_Occurrence (Source : Exception_Occurrence) return Exception_Occurrence_Access; private package SSL renames System.Standard_Library; package SP renames System.Parameters; subtype EOA is Exception_Occurrence_Access; Exception_Msg_Max_Length : constant := SP.Default_Exception_Msg_Max_Length; ------------------ -- Exception_Id -- ------------------ subtype Code_Loc is System.Address; -- Code location used in building exception tables and for call addresses -- when propagating an exception. Values of this type are created by using -- Label'Address or extracted from machine states using Get_Code_Loc. Null_Loc : constant Code_Loc := System.Null_Address; -- Null code location, used to flag outer level frame type Exception_Id is new SSL.Exception_Data_Ptr; function EId_To_String (X : Exception_Id) return String; function String_To_EId (S : String) return Exception_Id; pragma Stream_Convert (Exception_Id, String_To_EId, EId_To_String); -- Functions for implementing Exception_Id stream attributes Null_Id : constant Exception_Id := null; ------------------------- -- Private Subprograms -- ------------------------- function Exception_Name_Simple (X : Exception_Occurrence) return String; -- Like Exception_Name, but returns the simple non-qualified name of the -- exception. This is used to implement the Exception_Name function in -- Current_Exceptions (the DEC compatible unit). It is called from the -- compiler generated code (using Rtsfind, which does not respect the -- private barrier, so we can place this function in the private part -- where the compiler can find it, but the spec is unchanged.) procedure Raise_Exception_Always (E : Exception_Id; Message : String := ""); pragma No_Return (Raise_Exception_Always); pragma Export (Ada, Raise_Exception_Always, "__gnat_raise_exception"); -- This differs from Raise_Exception only in that the caller has determined -- that for sure the parameter E is not null, and that therefore no check -- for Null_Id is required. The expander converts Raise_Exception calls to -- Raise_Exception_Always if it can determine this is the case. The Export -- allows this routine to be accessed from Pure units. procedure Raise_From_Signal_Handler (E : Exception_Id; M : System.Address); pragma Export (Ada, Raise_From_Signal_Handler, "ada__exceptions__raise_from_signal_handler"); pragma No_Return (Raise_From_Signal_Handler); -- This routine is used to raise an exception from a signal handler. The -- signal handler has already stored the machine state (i.e. the state that -- corresponds to the location at which the signal was raised). E is the -- Exception_Id specifying what exception is being raised, and M is a -- pointer to a null-terminated string which is the message to be raised. -- Note that this routine never returns, so it is permissible to simply -- jump to this routine, rather than call it. This may be appropriate for -- systems where the right way to get out of signal handler is to alter the -- PC value in the machine state or in some other way ask the operating -- system to return here rather than to the original location. procedure Raise_From_Controlled_Operation (X : Ada.Exceptions.Exception_Occurrence); pragma No_Return (Raise_From_Controlled_Operation); pragma Export (Ada, Raise_From_Controlled_Operation, "__gnat_raise_from_controlled_operation"); -- Raise Program_Error, providing information about X (an exception raised -- during a controlled operation) in the exception message. procedure Reraise_Library_Exception_If_Any; pragma Export (Ada, Reraise_Library_Exception_If_Any, "__gnat_reraise_library_exception_if_any"); -- If there was an exception raised during library-level finalization, -- reraise the exception. procedure Reraise_Occurrence_Always (X : Exception_Occurrence); pragma No_Return (Reraise_Occurrence_Always); -- This differs from Raise_Occurrence only in that the caller guarantees -- that for sure the parameter X is not the null occurrence, and that -- therefore this procedure cannot return. The expander uses this routine -- in the translation of a raise statement with no parameter (reraise). procedure Reraise_Occurrence_No_Defer (X : Exception_Occurrence); pragma No_Return (Reraise_Occurrence_No_Defer); -- Exactly like Reraise_Occurrence, except that abort is not deferred -- before the call and the parameter X is known not to be the null -- occurrence. This is used in generated code when it is known that -- abort is already deferred. function Triggered_By_Abort return Boolean; -- Determine whether the current exception (if it exists) is an instance of -- Standard'Abort_Signal. ----------------------- -- Polling Interface -- ----------------------- -- The GNAT compiler has an option to generate polling calls to the Poll -- routine in this package. Specifying the -gnatP option for a compilation -- causes a call to Ada.Exceptions.Poll to be generated on every subprogram -- entry and on every iteration of a loop, thus avoiding the possibility of -- a case of unbounded time between calls. -- This polling interface may be used for instrumentation or debugging -- purposes (e.g. implementing watchpoints in software or in the debugger). -- In the GNAT technology itself, this interface is used to implement -- immediate asynchronous transfer of control and immediate abort on -- targets which do not provide for one thread interrupting another. -- Note: this used to be in a separate unit called System.Poll, but that -- caused horrible circular elaboration problems between System.Poll and -- Ada.Exceptions. procedure Poll; -- Check for asynchronous abort. Note that we do not inline the body. -- This makes the interface more useful for debugging purposes. -------------------------- -- Exception_Occurrence -- -------------------------- package TBE renames System.Traceback_Entries; Max_Tracebacks : constant := 50; -- Maximum number of trace backs stored in exception occurrence subtype Tracebacks_Array is TBE.Tracebacks_Array (1 .. Max_Tracebacks); -- Traceback array stored in exception occurrence type Exception_Occurrence is record Id : Exception_Id; -- Exception_Identity for this exception occurrence Msg_Length : Natural := 0; -- Length of message (zero = no message) Msg : String (1 .. Exception_Msg_Max_Length); -- Characters of message Exception_Raised : Boolean := False; -- Set to true to indicate that this exception occurrence has actually -- been raised. When an exception occurrence is first created, this is -- set to False, then when it is processed by Raise_Current_Exception, -- it is set to True. If Raise_Current_Exception is used to raise an -- exception for which this flag is already True, then it knows that -- it is dealing with the reraise case (which is useful to distinguish -- for exception tracing purposes). Pid : Natural := 0; -- Partition_Id for partition raising exception Num_Tracebacks : Natural range 0 .. Max_Tracebacks := 0; -- Number of traceback entries stored Tracebacks : Tracebacks_Array; -- Stored tracebacks (in Tracebacks (1 .. Num_Tracebacks)) end record; function "=" (Left, Right : Exception_Occurrence) return Boolean is abstract; -- Don't allow comparison on exception occurrences, we should not need -- this, and it would not work right, because of the Msg and Tracebacks -- fields which have unused entries not copied by Save_Occurrence. function EO_To_String (X : Exception_Occurrence) return String; function String_To_EO (S : String) return Exception_Occurrence; pragma Stream_Convert (Exception_Occurrence, String_To_EO, EO_To_String); -- Functions for implementing Exception_Occurrence stream attributes Null_Occurrence : constant Exception_Occurrence := ( Id => null, Msg_Length => 0, Msg => (others => ' '), Exception_Raised => False, Pid => 0, Num_Tracebacks => 0, Tracebacks => (others => TBE.Null_TB_Entry)); end Ada.Exceptions;
-- ----------------------------------------------------------------- -- -- -- -- This is free software; you can redistribute it and/or -- -- modify it under the terms of the GNU General Public -- -- License as published by the Free Software Foundation; either -- -- version 2 of the License, or (at your option) any later version. -- -- -- -- This software is distributed in the hope that it will be useful, -- -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- -- General Public License for more details. -- -- -- -- You should have received a copy of the GNU General Public -- -- License along with this library; if not, write to the -- -- Free Software Foundation, Inc., 59 Temple Place - Suite 330, -- -- Boston, MA 02111-1307, USA. -- -- -- -- ----------------------------------------------------------------- -- -- ----------------------------------------------------------------- -- -- This is a translation, to the Ada programming language, of the -- -- original C test files written by Sam Lantinga - www.libsdl.org -- -- translation made by Antonio F. Vargas - www.adapower.net/~avargas -- -- ----------------------------------------------------------------- -- with Interfaces.C; with Ada.Text_IO; use Ada.Text_IO; with Ada.Characters.Handling; with GNAT.OS_Lib; with SDL.Types; use SDL.Types; with TestGL_Sprogs; use TestGL_Sprogs; procedure TestGL is package C renames Interfaces.C; package CH renames Ada.Characters.Handling; use type Interfaces.C.int; use type V.Surface_Flags; package Int_IO is new Integer_IO (C.int); package CFloat_IO is new Float_IO (C.C_float); logo : Boolean := False; numtests : C.int := 1; bpp : C.int := 0; slowly : Boolean := False; gamma : C.C_float := 0.0; argc : Integer := CL.Argument_Count; video_flags : V.Surface_Flags := 0; begin while argc > 0 loop if (argc >= 2) and then (CL.Argument (argc - 1) = "-bpp") and then CH.Is_Digit (CL.Argument (argc) (1)) then declare last : Positive; begin Int_IO.Get (CL.Argument (argc), bpp, last); end; argc := argc - 2; elsif (argc >= 2) and then (CL.Argument (argc - 1) = "-gamma") and then CH.Is_Digit (CL.Argument (argc) (1)) then declare last : Positive; begin CFloat_IO.Get (CL.Argument (argc), gamma, last); end; argc := argc - 2; elsif CL.Argument (argc) = "-twice" then numtests := numtests + 1; argc := argc - 1; elsif CL.Argument (argc) = "-logo" then logo := True; argc := argc -1; elsif CL.Argument (argc) = "-slow" then slowly := True; argc := argc - 1; elsif CL.Argument (argc) = "-fullscreen" then video_flags := video_flags or V.FULLSCREEN; argc := argc - 1; elsif CL.Argument (argc) = "-h" then Put_Line ("Usage: " & CL.Command_Name & " " & "[-bpp N] [-gamma] [-twice] " & "[-logo] [-slow] [-fullscreen]"); argc := argc - 1; GNAT.OS_Lib.OS_Exit (0); else Put_Line ("Usage: " & CL.Command_Name & " " & "[-bpp N] [-gamma] [-twice] " & "[-logo] [-slow] [-fullscreen] [-h]"); argc := argc - 1; GNAT.OS_Lib.OS_Exit (0); end if; end loop; for i in 0 .. numtests - 1 loop RunGLTest (video_flags, logo, slowly, bpp, gamma); end loop; GNAT.OS_Lib.OS_Exit (0); end TestGL;
with Aof.Core.Properties; with Callbacks; -- In this example, we are going to create a simple integer property. -- As a refresher, a property is a class member field with a get and -- set method. A property is built upon the signals & slots concept -- in this implementation to realize the observer pattern. Below, -- the Connect method is used to subscribe a callback procedure to -- the property; when the property changes, all of the subscriber -- callbacks get invoked. procedure Property_Example is My_Integer_Property : Aof.Core.Properties.Integers.Property; begin -- Register the callback (On_Change) to be invoked when the -- property is modified. My_Integer_Property.Connect(Callbacks.On_Change'access); -- Now change the proerty... for I in 1 .. 5 loop My_Integer_Property.Set(I); end loop; end Property_Example;
private with NXP_SVD.GPIO; with HAL.GPIO; with NXP.Pint; use NXP.Pint; -- limited with NXP.IOCON; package NXP.GPIO is type GPIO_Port is limited private; type GPIO_Pin is (Pin_0, Pin_1, Pin_2, Pin_3, Pin_4, Pin_5, Pin_6, Pin_7, Pin_8, Pin_9, Pin_10, Pin_11, Pin_12, Pin_13, Pin_14, Pin_15, Pin_16, Pin_17, Pin_18, Pin_19, Pin_20, Pin_21, Pin_22, Pin_23, Pin_24, Pin_25, Pin_26, Pin_27, Pin_28, Pin_29, Pin_30, Pin_31 ); for GPIO_Pin use (Pin_0 => 16#0000_0001#, Pin_1 => 16#0000_0002#, Pin_2 => 16#0000_0004#, Pin_3 => 16#0000_0008#, Pin_4 => 16#0000_0010#, Pin_5 => 16#0000_0020#, Pin_6 => 16#0000_0040#, Pin_7 => 16#0000_0080#, Pin_8 => 16#0000_0100#, Pin_9 => 16#0000_0200#, Pin_10 => 16#0000_0400#, Pin_11 => 16#0000_0800#, Pin_12 => 16#0000_1000#, Pin_13 => 16#0000_2000#, Pin_14 => 16#0000_4000#, Pin_15 => 16#0000_8000#, Pin_16 => 16#0001_0000#, Pin_17 => 16#0002_0000#, Pin_18 => 16#0004_0000#, Pin_19 => 16#0008_0000#, Pin_20 => 16#0010_0000#, Pin_21 => 16#0020_0000#, Pin_22 => 16#0040_0000#, Pin_23 => 16#0080_0000#, Pin_24 => 16#0100_0000#, Pin_25 => 16#0200_0000#, Pin_26 => 16#0400_0000#, Pin_27 => 16#0800_0000#, Pin_28 => 16#1000_0000#, Pin_29 => 16#2000_0000#, Pin_30 => 16#4000_0000#, Pin_31 => 16#8000_0000#); for GPIO_Pin'Size use 32; -- for compatibility with hardware registers subtype GPIO_Pin_Index is Natural range 0 .. GPIO_Pin'Pos (GPIO_Pin'Last); type GPIO_Pins is array (Positive range <>) of GPIO_Pin; -- Note that, in addition to aggregates, the language-defined catenation -- operator "&" is available for types GPIO_Pin and GPIO_Pins, allowing one -- to construct GPIO_Pins values conveniently All_Pins : constant GPIO_Pins := (Pin_0, Pin_1, Pin_2, Pin_3, Pin_4, Pin_5, Pin_6, Pin_7, Pin_8, Pin_9, Pin_10, Pin_11, Pin_12, Pin_13, Pin_14, Pin_15, Pin_16, Pin_17, Pin_18, Pin_19, Pin_20, Pin_21, Pin_22, Pin_23, Pin_24, Pin_25, Pin_26, Pin_27, Pin_28, Pin_29, Pin_30, Pin_31 ); type Pin_IO_Modes is (Mode_In, Mode_Out, Mode_AF, Mode_Analog) with Size => 2; for Pin_IO_Modes use (Mode_In => 0, Mode_Out => 1, Mode_AF => 2, Mode_Analog => 3); type Pin_Output_Types is (Push_Pull, Open_Drain) with Size => 1; for Pin_Output_Types use (Push_Pull => 0, Open_Drain => 1); type Pin_Output_Speeds is (Speed_Low, Speed_High) with Size => 1; for Pin_Output_Speeds use (Speed_Low => 0, Speed_High => 1); type Internal_Pin_Resistors is (Floating, Pull_Down, Pull_Up, Repeater) with Size => 2; type GPIO_Port_Configuration is record Mode : Pin_IO_Modes; Output_Type : Pin_Output_Types; Speed : Pin_Output_Speeds; Resistors : Internal_Pin_Resistors; Invert : Boolean; end record; type Ports is (Port_0, Port_1); type GPIO_Point is new HAL.GPIO.GPIO_Point with record Periph : access GPIO_Port; -- Port should be a not null access, but this raises an exception -- during elaboration. Port : Ports; Pin : GPIO_Pin; end record; overriding function Mode (This : GPIO_Point) return HAL.GPIO.GPIO_Mode; overriding function Set_Mode (This : in out GPIO_Point; Mode : HAL.GPIO.GPIO_Config_Mode) return Boolean; overriding function Pull_Resistor (This : GPIO_Point) return HAL.GPIO.GPIO_Pull_Resistor; overriding function Set_Pull_Resistor (This : in out GPIO_Point; Pull : HAL.GPIO.GPIO_Pull_Resistor) return Boolean; overriding function Set (This : GPIO_Point) return Boolean with Inline; -- Returns True if the bit specified by This.Pin is set (not zero) in the -- input data register of This.Port.all; returns False otherwise. overriding procedure Set (This : in out GPIO_Point) with Inline; -- For This.Port.all, sets the output data register bit specified by -- This.Pin to one. Other pins are unaffected. overriding procedure Clear (This : in out GPIO_Point) with Inline; -- For This.Port.all, sets the output data register bit specified by -- This.Pin to zero. Other pins are unaffected. overriding procedure Toggle (This : in out GPIO_Point) with Inline; -- For This.Port.all, negates the output data register bit specified by -- This.Pin (one becomes zero and vice versa). Other pins are unaffected. procedure Configure_IO (This : GPIO_Point; Config : GPIO_Port_Configuration); -- For Point.Pin on the Point.Port.all, configures the -- characteristics specified by Config type GPIO_Points is array (Positive range <>) of GPIO_Point; function Any_Set (Pins : GPIO_Points) return Boolean with Inline; -- Returns True if any one of the bits specified by Pins is set (not zero) -- in the Port input data register; returns False otherwise. function Set (Pins : GPIO_Points) return Boolean renames Any_Set; -- Defined for readability when only one pin is specified in GPIO_Pins function All_Set (Pins : GPIO_Points) return Boolean with Inline; -- Returns True iff all of the bits specified by Pins are set (not zero) in -- the Port input data register; returns False otherwise. procedure Set (Pins : in out GPIO_Points) with Inline; -- For the given GPIO port, sets all of the output data register bits -- specified by Pins to one. Other pins are unaffected. procedure Clear (Pins : in out GPIO_Points) with Inline; -- For the given GPIO port, sets of all of the output data register bits -- specified by Pins to zero. Other pins are unaffected. procedure Toggle (Points : in out GPIO_Points) with Inline; -- For the given GPIO ports, negates all of the output data register bis -- specified by Pins (ones become zeros and vice versa). Other pins are -- unaffected. procedure Configure_IO (Points : GPIO_Points; Config : GPIO_Port_Configuration); -- For Point.Pin on the Point.Port.all, configures the -- characteristics specified by Config procedure Configure_Alternate_Function (This : GPIO_Point; AF : GPIO_Alternate_Function); procedure Configure_Alternate_Function (Points : GPIO_Points; AF : GPIO_Alternate_Function); procedure Enable_GPIO_Interrupt (Pin : GPIO_Point; Config : Pint_Configuration); private type GPIO_Port is new NXP_SVD.GPIO.GPIO_Peripheral; end NXP.GPIO;
with gtk.Widget; with Gtk.Button; with Gtk.Window; with Adam.exception_Handler, AdaM.Declaration.of_exception; with Gtk.Notebook; with Gtk.Table; package aIDE.Palette.of_exceptions is type Item is new Palette.item with private; type View is access all Item'Class; -- Forge -- function to_exceptions_Palette return View; -- Attributes -- function top_Widget (Self : in Item) return gtk.Widget.Gtk_Widget; -- Operations -- procedure show (Self : in out Item; Invoked_by : in Gtk.Button.gtk_Button; Target : in adam.exception_Handler.view; Slot : in Positive); procedure choice_is (Self : in out Item; --Now : in String; -- package_Name : in String; the_Exception : in AdaM.Declaration.of_exception.view); procedure freshen (Self : in out Item); private use gtk.Window, gtk.Button, gtk.Notebook, Gtk.Table; type Item is new Palette.item with record Invoked_by : gtk_Button; Target : adam.exception_Handler.view; Slot : Positive; recent_Table : gtk_Table; top_Notebook, all_Notebook : gtk_Notebook; Top : gtk_Window; delete_Button : gtk_Button; close_Button : gtk_Button; end record; procedure build_recent_List (Self : in out Item); end aIDE.Palette.of_exceptions;
with DDS.DataReader_Impl; with DDS.DataWriter_Impl; with DDS.DomainParticipant; with DDS.Publisher; with DDS.Subscriber; with DDS.Topic; with DDS.TopicDescription; with DDS.WaitSet; with DDS.ReadCondition; private package DDS.Request_Reply.Impl is type Ref is new Ada.Finalization.Limited_Controlled and Request_Reply.Ref with record Participant : DDS.DomainParticipant.Ref_Access; Publisher : DDS.Publisher.Ref_Access; Subscriber : DDS.Subscriber.Ref_Access; Reply_Topic : DDS.Topic.Ref_Access; Request_Topic : DDS.Topic.Ref_Access; Reader : DDS.DataReader_Impl.Ref_Access; Writer : DDS.DataWriter_Impl.Ref_Access; Waitset : DDS.WaitSet.Ref_Access; Not_Read_Sample_Cond : DDS.ReadCondition.Ref_Access; Any_Sample_Cond : DDS.ReadCondition.Ref_Access; Sample_Size : Natural; end record; type Ref_Access is access all Ref'Class; procedure Log_Exception (Log : Standard.String) is null; function Create_Request_Topic_Name_From_Service_Name (Service_Name : DDS.String) return DDS.String is (DDS.To_DDS_String (DDS.To_Standard_String (Service_Name) & "Request")); function Create_Reply_Topic_Name_From_Service_Name (Service_Name : DDS.String) return DDS.String is (DDS.To_DDS_String (DDS.To_Standard_String (Service_Name) & "Reply")); function Create_Request_Topic (Self : not null access Ref; Topic_Name : DDS.String; Type_Name : DDS.String; QoS : DDS.TopicQos := DDS.DomainParticipant.TOPIC_QOS_DEFAULT) return DDS.Topic.Ref_Access; function Create_Reply_Topic (Self : not null access Ref; Topic_Name : DDS.String; Type_Name : DDS.String; QoS : DDS.TopicQos := DDS.DomainParticipant.TOPIC_QOS_DEFAULT) return DDS.Topic.Ref_Access; function Create_Request_Topic_With_Profile (Self : not null access Ref; Topic_Name : DDS.String; Type_Name : DDS.String; Library_Name : DDS.String; Profile_Name : DDS.String) return DDS.Topic.Ref_Access; function Create_Reply_Topic_With_Profile (Self : not null access Ref; Topic_Name : DDS.String; Type_Name : DDS.String; Library_Name : DDS.String; Profile_Name : DDS.String) return DDS.Topic.Ref_Access; procedure Validate (Self : not null access Ref; Publisher : DDS.Publisher.Ref_Access; Subscriber : DDS.Subscriber.Ref_Access); CORRELATION_FIELD_NAME : constant DDS.String := To_DDS_String ("@related_sample_identity.writer_guid.value"); function CreateContentFilteredTopicName ( Self : not null access Ref; RelatedTopicName : DDS.String; Guid : Guid_T) return Standard.String; procedure Wait_For_Any_Sample (Self : not null access Ref; Max_Wait : DDS.Duration_T; Min_Sample_Count : DDS.Natural); procedure Wait_For_Samples (Self : not null access Ref; Max_Wait : DDS.Duration_T; Min_Sample_Count : DDS.Integer; WaitSet : not null DDS.WaitSet.Ref_Access; Initial_Condition : not null DDS.ReadCondition.Ref_Access; Condition : not null DDS.ReadCondition.Ref_Access); end DDS.Request_Reply.Impl;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- S Y S T E M . V A L U E _ R -- -- -- -- B o d y -- -- -- -- Copyright (C) 2020-2021, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- -- -- -- -- -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with System.Val_Util; use System.Val_Util; package body System.Value_R is subtype Char_As_Digit is Unsigned range 0 .. 17; subtype Valid_Digit is Char_As_Digit range 0 .. 15; E_Digit : constant Char_As_Digit := 14; Underscore : constant Char_As_Digit := 16; Not_A_Digit : constant Char_As_Digit := 17; function As_Digit (C : Character) return Char_As_Digit; -- Given a character return the digit it represents procedure Round_Extra (Digit : Char_As_Digit; Value : in out Uns; Scale : in out Integer; Extra : in out Char_As_Digit; Base : Unsigned); -- Round the triplet (Value, Scale, Extra) according to Digit in Base procedure Scan_Decimal_Digits (Str : String; Index : in out Integer; Max : Integer; Value : in out Uns; Scale : in out Integer; Extra : in out Char_As_Digit; Base_Violation : in out Boolean; Base : Unsigned; Base_Specified : Boolean); -- Scan the decimal part of a real (i.e. after decimal separator) -- -- The string parsed is Str (Index .. Max) and after the call Index will -- point to the first non-parsed character. -- -- For each digit parsed, Value = Value * Base + Digit and Scale is -- decremented by 1. If precision limit is reached, remaining digits are -- still parsed but ignored, except for the first which is stored in Extra. -- -- Base_Violation is set to True if a digit found is not part of the Base -- -- If Base_Specified is set, then the base was specified in the real procedure Scan_Integral_Digits (Str : String; Index : in out Integer; Max : Integer; Value : out Uns; Scale : out Integer; Extra : out Char_As_Digit; Base_Violation : in out Boolean; Base : Unsigned; Base_Specified : Boolean); -- Scan the integral part of a real (i.e. before decimal separator) -- -- The string parsed is Str (Index .. Max) and after the call Index will -- point to the first non-parsed character. -- -- For each digit parsed, either Value := Value * Base + Digit or Scale -- is incremented by 1 if precision limit is reached, in which case the -- remaining digits are still parsed but ignored, except for the first -- which is stored in Extra. -- -- Base_Violation is set to True if a digit found is not part of the Base -- -- If Base_Specified is set, then the base was specified in the real -------------- -- As_Digit -- -------------- function As_Digit (C : Character) return Char_As_Digit is begin case C is when '0' .. '9' => return Character'Pos (C) - Character'Pos ('0'); when 'a' .. 'f' => return Character'Pos (C) - (Character'Pos ('a') - 10); when 'A' .. 'F' => return Character'Pos (C) - (Character'Pos ('A') - 10); when '_' => return Underscore; when others => return Not_A_Digit; end case; end As_Digit; ----------------- -- Round_Extra -- ----------------- procedure Round_Extra (Digit : Char_As_Digit; Value : in out Uns; Scale : in out Integer; Extra : in out Char_As_Digit; Base : Unsigned) is pragma Assert (Base in 2 .. 16); B : constant Uns := Uns (Base); begin if Digit >= Base / 2 then -- If Extra is maximum, round Value if Extra = Base - 1 then -- If Value is maximum, scale it up if Value = Precision_Limit then Extra := Char_As_Digit (Value mod B); Value := Value / B; Scale := Scale + 1; Round_Extra (Digit, Value, Scale, Extra, Base); else Extra := 0; Value := Value + 1; end if; else Extra := Extra + 1; end if; end if; end Round_Extra; ------------------------- -- Scan_Decimal_Digits -- ------------------------- procedure Scan_Decimal_Digits (Str : String; Index : in out Integer; Max : Integer; Value : in out Uns; Scale : in out Integer; Extra : in out Char_As_Digit; Base_Violation : in out Boolean; Base : Unsigned; Base_Specified : Boolean) is pragma Assert (Base in 2 .. 16); pragma Assert (Index in Str'Range); pragma Assert (Max <= Str'Last); Umax : constant Uns := (Precision_Limit - Uns (Base) + 1) / Uns (Base); -- Max value which cannot overflow on accumulating next digit UmaxB : constant Uns := Precision_Limit / Uns (Base); -- Numbers bigger than UmaxB overflow if multiplied by base Precision_Limit_Reached : Boolean := False; -- Set to True if addition of a digit will cause Value to be superior -- to Precision_Limit. Precision_Limit_Just_Reached : Boolean; -- Set to True if Precision_Limit_Reached was just set to True, but only -- used when Round is True. Digit : Char_As_Digit; -- The current digit Temp : Uns; -- Temporary Trailing_Zeros : Natural := 0; -- Number of trailing zeros at a given point begin -- If initial Scale is not 0 then it means that Precision_Limit was -- reached during scanning of the integral part. if Scale > 0 then Precision_Limit_Reached := True; else Extra := 0; end if; if Round then Precision_Limit_Just_Reached := False; end if; -- The function precondition is that the first character is a valid -- digit. Digit := As_Digit (Str (Index)); loop -- Check if base is correct. If the base is not specified, the digit -- E or e cannot be considered as a base violation as it can be used -- for exponentiation. if Digit >= Base then if Base_Specified then Base_Violation := True; elsif Digit = E_Digit then return; else Base_Violation := True; end if; end if; -- If precision limit has been reached, just ignore any remaining -- digits for the computation of Value and Scale, but store the -- first in Extra and use the second to round Extra. The scanning -- should continue only to assess the validity of the string. if Precision_Limit_Reached then if Round and then Precision_Limit_Just_Reached then Round_Extra (Digit, Value, Scale, Extra, Base); Precision_Limit_Just_Reached := False; end if; else -- Trailing '0' digits are ignored until a non-zero digit is found if Digit = 0 then Trailing_Zeros := Trailing_Zeros + 1; else -- Handle accumulated zeros. for J in 1 .. Trailing_Zeros loop if Value <= UmaxB then Value := Value * Uns (Base); Scale := Scale - 1; else Extra := 0; Precision_Limit_Reached := True; if Round and then J = Trailing_Zeros then Round_Extra (Digit, Value, Scale, Extra, Base); end if; exit; end if; end loop; -- Reset trailing zero counter Trailing_Zeros := 0; -- Handle current non zero digit Temp := Value * Uns (Base) + Uns (Digit); -- Precision_Limit_Reached may have been set above if Precision_Limit_Reached then null; -- Check if Temp is larger than Precision_Limit, taking into -- account that Temp may wrap around when Precision_Limit is -- equal to the largest integer. elsif Value <= Umax or else (Value <= UmaxB and then ((Precision_Limit < Uns'Last and then Temp <= Precision_Limit) or else (Precision_Limit = Uns'Last and then Temp >= Uns (Base)))) then Value := Temp; Scale := Scale - 1; else Extra := Digit; Precision_Limit_Reached := True; if Round then Precision_Limit_Just_Reached := True; end if; end if; end if; end if; -- Check next character Index := Index + 1; if Index > Max then return; end if; Digit := As_Digit (Str (Index)); if Digit not in Valid_Digit then -- Underscore is only allowed if followed by a digit if Digit = Underscore and Index + 1 <= Max then Digit := As_Digit (Str (Index + 1)); if Digit in Valid_Digit then Index := Index + 1; else return; end if; -- Neither a valid underscore nor a digit else return; end if; end if; end loop; end Scan_Decimal_Digits; -------------------------- -- Scan_Integral_Digits -- -------------------------- procedure Scan_Integral_Digits (Str : String; Index : in out Integer; Max : Integer; Value : out Uns; Scale : out Integer; Extra : out Char_As_Digit; Base_Violation : in out Boolean; Base : Unsigned; Base_Specified : Boolean) is pragma Assert (Base in 2 .. 16); Umax : constant Uns := (Precision_Limit - Uns (Base) + 1) / Uns (Base); -- Max value which cannot overflow on accumulating next digit UmaxB : constant Uns := Precision_Limit / Uns (Base); -- Numbers bigger than UmaxB overflow if multiplied by base Precision_Limit_Reached : Boolean := False; -- Set to True if addition of a digit will cause Value to be superior -- to Precision_Limit. Precision_Limit_Just_Reached : Boolean; -- Set to True if Precision_Limit_Reached was just set to True, but only -- used when Round is True. Digit : Char_As_Digit; -- The current digit Temp : Uns; -- Temporary begin -- Initialize Value, Scale and Extra Value := 0; Scale := 0; Extra := 0; if Round then Precision_Limit_Just_Reached := False; end if; pragma Assert (Max <= Str'Last); -- The function precondition is that the first character is a valid -- digit. Digit := As_Digit (Str (Index)); loop -- Check if base is correct. If the base is not specified, the digit -- E or e cannot be considered as a base violation as it can be used -- for exponentiation. if Digit >= Base then if Base_Specified then Base_Violation := True; elsif Digit = E_Digit then return; else Base_Violation := True; end if; end if; -- If precision limit has been reached, just ignore any remaining -- digits for the computation of Value and Scale, but store the -- first in Extra and use the second to round Extra. The scanning -- should continue only to assess the validity of the string. if Precision_Limit_Reached then Scale := Scale + 1; if Round and then Precision_Limit_Just_Reached then Round_Extra (Digit, Value, Scale, Extra, Base); Precision_Limit_Just_Reached := False; end if; else Temp := Value * Uns (Base) + Uns (Digit); -- Check if Temp is larger than Precision_Limit, taking into -- account that Temp may wrap around when Precision_Limit is -- equal to the largest integer. if Value <= Umax or else (Value <= UmaxB and then ((Precision_Limit < Uns'Last and then Temp <= Precision_Limit) or else (Precision_Limit = Uns'Last and then Temp >= Uns (Base)))) then Value := Temp; else Extra := Digit; Precision_Limit_Reached := True; if Round then Precision_Limit_Just_Reached := True; end if; Scale := Scale + 1; end if; end if; -- Look for the next character Index := Index + 1; if Index > Max then return; end if; Digit := As_Digit (Str (Index)); if Digit not in Valid_Digit then -- Next character is not a digit. In that case stop scanning -- unless the next chracter is an underscore followed by a digit. if Digit = Underscore and Index + 1 <= Max then Digit := As_Digit (Str (Index + 1)); if Digit in Valid_Digit then Index := Index + 1; else return; end if; else return; end if; end if; end loop; end Scan_Integral_Digits; ------------------- -- Scan_Raw_Real -- ------------------- function Scan_Raw_Real (Str : String; Ptr : not null access Integer; Max : Integer; Base : out Unsigned; Scale : out Integer; Extra : out Unsigned; Minus : out Boolean) return Uns is pragma Assert (Max <= Str'Last); After_Point : Boolean; -- True if a decimal should be parsed Base_Char : Character := ASCII.NUL; -- Character used to set the base. If Nul this means that default -- base is used. Base_Violation : Boolean := False; -- If True some digits where not in the base. The real is still scanned -- till the end even if an error will be raised. Index : Integer; -- Local copy of string pointer Start : Positive; pragma Unreferenced (Start); Value : Uns; -- Mantissa as an Integer begin -- The default base is 10 Base := 10; -- We do not tolerate strings with Str'Last = Positive'Last if Str'Last = Positive'Last then raise Program_Error with "string upper bound is Positive'Last, not supported"; end if; -- Scan the optional sign Scan_Sign (Str, Ptr, Max, Minus, Start); Index := Ptr.all; pragma Assert (Index >= Str'First); pragma Annotate (CodePeer, Modified, Str (Index)); -- First character can be either a decimal digit or a dot and for some -- reason CodePeer incorrectly thinks it is always a digit. if Str (Index) in '0' .. '9' then After_Point := False; -- If this is a digit it can indicates either the float decimal -- part or the base to use. Scan_Integral_Digits (Str, Index, Max, Value, Scale, Char_As_Digit (Extra), Base_Violation, Base, Base_Specified => False); -- A dot is allowed only if followed by a digit (RM 3.5(47)) elsif Str (Index) = '.' and then Index < Max and then Str (Index + 1) in '0' .. '9' then After_Point := True; Index := Index + 1; Value := 0; Scale := 0; Extra := 0; else Bad_Value (Str); end if; -- Check if the first number encountered is a base pragma Assert (Index >= Str'First); if Index < Max and then (Str (Index) = '#' or else Str (Index) = ':') then Base_Char := Str (Index); if Value in 2 .. 16 then Base := Unsigned (Value); else Base_Violation := True; Base := 16; end if; Index := Index + 1; if Str (Index) = '.' and then Index < Max and then As_Digit (Str (Index + 1)) in Valid_Digit then After_Point := True; Index := Index + 1; Value := 0; end if; end if; -- Scan the integral part if still necessary if Base_Char /= ASCII.NUL and then not After_Point then if Index > Max or else As_Digit (Str (Index)) not in Valid_Digit then Bad_Value (Str); end if; Scan_Integral_Digits (Str, Index, Max, Value, Scale, Char_As_Digit (Extra), Base_Violation, Base, Base_Specified => Base_Char /= ASCII.NUL); end if; -- Do we have a dot? pragma Assert (Index >= Str'First); if not After_Point and then Index <= Max and then Str (Index) = '.' then -- At this stage if After_Point was not set, this means that an -- integral part has been found. Thus the dot is valid even if not -- followed by a digit. if Index < Max and then As_Digit (Str (Index + 1)) in Valid_Digit then After_Point := True; end if; Index := Index + 1; end if; -- Scan the decimal part if After_Point then pragma Assert (Index <= Max); Scan_Decimal_Digits (Str, Index, Max, Value, Scale, Char_As_Digit (Extra), Base_Violation, Base, Base_Specified => Base_Char /= ASCII.NUL); end if; -- If an explicit base was specified ensure that the delimiter is found if Base_Char /= ASCII.NUL then pragma Assert (Index > Max or else Index in Str'Range); if Index > Max or else Str (Index) /= Base_Char then Bad_Value (Str); else Index := Index + 1; end if; end if; -- Update pointer and scan exponent Ptr.all := Index; Scale := Scale + Scan_Exponent (Str, Ptr, Max, Real => True); -- Here is where we check for a bad based number if Base_Violation then Bad_Value (Str); else return Value; end if; end Scan_Raw_Real; -------------------- -- Value_Raw_Real -- -------------------- function Value_Raw_Real (Str : String; Base : out Unsigned; Scale : out Integer; Extra : out Unsigned; Minus : out Boolean) return Uns is begin -- We have to special case Str'Last = Positive'Last because the normal -- circuit ends up setting P to Str'Last + 1 which is out of bounds. We -- deal with this by converting to a subtype which fixes the bounds. if Str'Last = Positive'Last then declare subtype NT is String (1 .. Str'Length); begin return Value_Raw_Real (NT (Str), Base, Scale, Extra, Minus); end; -- Normal case where Str'Last < Positive'Last else declare V : Uns; P : aliased Integer := Str'First; begin V := Scan_Raw_Real (Str, P'Access, Str'Last, Base, Scale, Extra, Minus); Scan_Trailing_Blanks (Str, P); return V; end; end if; end Value_Raw_Real; end System.Value_R;
-- { dg-do compile } with System; with Ada.Unchecked_Conversion; procedure Test_Call is type F_ACC is access function (Str : String) return String; function Do_Something (V : F_Acc) return System.Address is begin return System.Null_Address; end Do_Something; function BUG_1 (This : access Integer) return F_Acc is begin return null; end BUG_1; function Unch is new Ada.Unchecked_Conversion (F_Acc, System.Address); Func : System.Address := Unch (BUG_1 (null)); V : System.Address := Do_Something (BUG_1 (null)); begin null; end Test_Call;
with Datos; use Datos; function Posicion ( L : Lista; Num : Integer ) return Natural is -- pre: -- post: el resultado es la posicion de la primera aparicion de Num, -- caso de que Num pertenezca a L, y cero en otro caso LCopia : Lista; Found : Boolean; Pos, PosDev : Integer; begin LCopia := L; Pos := 0; PosDev := 0; Found := False; while LCopia /= null and Found = False loop pos := pos+1; if LCopia.all.info = Num then PosDev := Pos; Found := True; end if; LCopia := LCopia.all.sig; end loop; return PosDev; end Posicion;
-------------------------------------------------------------------------------------------------------------------- -- Copyright (c) 2013-2020, Luke A. Guest -- -- This software is provided 'as-is', without any express or implied -- warranty. In no event will the authors be held liable for any damages -- arising from the use of this software. -- -- Permission is granted to anyone to use this software for any purpose, -- including commercial applications, and to alter it and redistribute it -- freely, subject to the following restrictions: -- -- 1. The origin of this software must not be misrepresented; you must not -- claim that you wrote the original software. If you use this software -- in a product, an acknowledgment in the product documentation would be -- appreciated but is not required. -- -- 2. Altered source versions must be plainly marked as such, and must not be -- misrepresented as being the original software. -- -- 3. This notice may not be removed or altered from any source -- distribution. -------------------------------------------------------------------------------------------------------------------- with SDL.Error; package body SDL.RWops.Streams is use type Interfaces.C.unsigned_long; function Open (Op : in RWops) return RWops_Stream is begin return (Ada.Streams.Root_Stream_Type with Context => Op); end Open; procedure Open (Op : in RWops; Stream : out RWops_Stream) is begin Stream.Context := Op; end Open; procedure Close (Stream : in RWops_Stream) is begin Close (Stream.Context); end Close; overriding procedure Read (Stream : in out RWops_Stream; Item : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Objects_Read : Interfaces.C.unsigned_long := 0; begin -- Re-implemented c-macro: -- #define SDL_RWread(ctx, ptr, size, n) (ctx)->read(ctx, ptr, size, n) -- Read : access function -- (context : RWops_Pointer; -- ptr : System.Address; -- size : Interfaces.C.unsigned_long; -- maxnum : Interfaces.C.unsigned_long) return Interfaces.C.unsigned_long; Objects_Read := Stream.Context.Read (Context => RWops_Pointer (Stream.Context), Ptr => Item'Address, Size => Item'Length, Max_Num => 1); if Objects_Read = 0 then raise RWops_Error with SDL.Error.Get; end if; Last := Item'Length; end Read; overriding procedure Write (Stream : in out RWops_Stream; Item : Ada.Streams.Stream_Element_Array) is Objects_Written : Interfaces.C.unsigned_long := 0; begin -- Re-implemented c-macro: -- #define SDL_RWwrite(ctx, ptr, size, n) (ctx)->write(ctx, ptr, size, n) -- Write : access function -- (Context : RWops_Pointer; -- Ptr : System.Address; -- Size : Interfaces.C.unsigned_long; -- Num : Interfaces.C.unsigned_long) return Interfaces.C.unsigned_long; Objects_Written := Stream.Context.Write (Context => RWops_Pointer (Stream.Context), Ptr => Item'Address, Size => Item'Length, Num => 1); if Objects_Written = 0 then raise RWops_Error with SDL.Error.Get; end if; end Write; end SDL.RWops.Streams;
function "-" (Left, Right : Luminance) return Count is begin if Left > Right then return Count (Left) - Count (Right); else return Count (Right) - Count (Left); end if; end "-";
-- Copyright (c) 2017 Maxim Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- with League.Strings; package body LSP.Servers.Handlers is function "+" (Text : Wide_Wide_String) return League.Strings.Universal_String renames League.Strings.To_Universal_String; ---------------------------- -- DidChangeConfiguration -- ---------------------------- procedure DidChangeConfiguration (Stream : access Ada.Streams.Root_Stream_Type'Class; Handler : not null LSP.Message_Handlers.Notification_Handler_Access) is Params : LSP.Messages.DidChangeConfigurationParams; begin LSP.Messages.DidChangeConfigurationParams'Read (Stream, Params); Handler.Workspace_Did_Change_Configuration (Params); end DidChangeConfiguration; --------------------------- -- DidChangeTextDocument -- --------------------------- procedure DidChangeTextDocument (Stream : access Ada.Streams.Root_Stream_Type'Class; Handler : not null LSP.Message_Handlers.Notification_Handler_Access) is Params : LSP.Messages.DidChangeTextDocumentParams; begin LSP.Messages.DidChangeTextDocumentParams'Read (Stream, Params); Handler.Text_Document_Did_Change (Params); end DidChangeTextDocument; -------------------------- -- DidCloseTextDocument -- -------------------------- procedure DidCloseTextDocument (Stream : access Ada.Streams.Root_Stream_Type'Class; Handler : not null LSP.Message_Handlers.Notification_Handler_Access) is Params : LSP.Messages.DidCloseTextDocumentParams; begin LSP.Messages.DidCloseTextDocumentParams'Read (Stream, Params); Handler.Text_Document_Did_Close (Params); end DidCloseTextDocument; ------------------------- -- DidSaveTextDocument -- ------------------------- procedure DidSaveTextDocument (Stream : access Ada.Streams.Root_Stream_Type'Class; Handler : not null LSP.Message_Handlers.Notification_Handler_Access) is Params : LSP.Messages.DidSaveTextDocumentParams; begin LSP.Messages.DidSaveTextDocumentParams'Read (Stream, Params); Handler.Text_Document_Did_Save (Params); end DidSaveTextDocument; ------------------------- -- DidOpenTextDocument -- ------------------------- procedure DidOpenTextDocument (Stream : access Ada.Streams.Root_Stream_Type'Class; Handler : not null LSP.Message_Handlers.Notification_Handler_Access) is Params : LSP.Messages.DidOpenTextDocumentParams; begin LSP.Messages.DidOpenTextDocumentParams'Read (Stream, Params); Handler.Text_Document_Did_Open (Params); end DidOpenTextDocument; -------------------- -- Do_Code_Action -- -------------------- function Do_Code_Action (Stream : access Ada.Streams.Root_Stream_Type'Class; Handler : not null LSP.Message_Handlers.Request_Handler_Access) return LSP.Messages.ResponseMessage'Class is Params : LSP.Messages.CodeActionParams; begin LSP.Messages.CodeActionParams'Read (Stream, Params); return Response : LSP.Messages.CodeAction_Response do Handler.Text_Document_Code_Action_Request (Response => Response, Value => Params); end return; end Do_Code_Action; ------------------- -- Do_Completion -- ------------------- function Do_Completion (Stream : access Ada.Streams.Root_Stream_Type'Class; Handler : not null LSP.Message_Handlers.Request_Handler_Access) return LSP.Messages.ResponseMessage'Class is Params : LSP.Messages.TextDocumentPositionParams; begin LSP.Messages.TextDocumentPositionParams'Read (Stream, Params); return Response : LSP.Messages.Completion_Response do Handler.Text_Document_Completion_Request (Response => Response, Value => Params); end return; end Do_Completion; ------------------- -- Do_Definition -- ------------------- function Do_Definition (Stream : access Ada.Streams.Root_Stream_Type'Class; Handler : not null LSP.Message_Handlers.Request_Handler_Access) return LSP.Messages.ResponseMessage'Class is Params : LSP.Messages.TextDocumentPositionParams; begin LSP.Messages.TextDocumentPositionParams'Read (Stream, Params); return Response : LSP.Messages.Location_Response do Handler.Text_Document_Definition_Request (Response => Response, Value => Params); end return; end Do_Definition; ------------------------ -- Do_Document_Symbol -- ------------------------ function Do_Document_Symbol (Stream : access Ada.Streams.Root_Stream_Type'Class; Handler : not null LSP.Message_Handlers.Request_Handler_Access) return LSP.Messages.ResponseMessage'Class is Params : LSP.Messages.DocumentSymbolParams; begin LSP.Messages.DocumentSymbolParams'Read (Stream, Params); return Response : LSP.Messages.Symbol_Response do Handler.Text_Document_Symbol_Request (Response => Response, Value => Params); end return; end Do_Document_Symbol; ------------------------ -- Do_Execute_Command -- ------------------------ function Do_Execute_Command (Stream : access Ada.Streams.Root_Stream_Type'Class; Handler : not null LSP.Message_Handlers.Request_Handler_Access) return LSP.Messages.ResponseMessage'Class is Params : LSP.Messages.ExecuteCommandParams; begin LSP.Messages.ExecuteCommandParams'Read (Stream, Params); return Response : LSP.Messages.ExecuteCommand_Response do Handler.Workspace_Execute_Command_Request (Response => Response, Value => Params); end return; end Do_Execute_Command; ------------- -- Do_Exit -- ------------- procedure Do_Exit (Stream : access Ada.Streams.Root_Stream_Type'Class; Handler : not null LSP.Message_Handlers.Notification_Handler_Access) is pragma Unreferenced (Stream); begin Handler.Exit_Notification; end Do_Exit; ------------------ -- Do_Highlight -- ------------------ function Do_Highlight (Stream : access Ada.Streams.Root_Stream_Type'Class; Handler : not null LSP.Message_Handlers.Request_Handler_Access) return LSP.Messages.ResponseMessage'Class is Params : LSP.Messages.TextDocumentPositionParams; begin LSP.Messages.TextDocumentPositionParams'Read (Stream, Params); return Response : LSP.Messages.Highlight_Response do Handler.Text_Document_Highlight_Request (Response => Response, Value => Params); end return; end Do_Highlight; -------------- -- Do_Hover -- -------------- function Do_Hover (Stream : access Ada.Streams.Root_Stream_Type'Class; Handler : not null LSP.Message_Handlers.Request_Handler_Access) return LSP.Messages.ResponseMessage'Class is Params : LSP.Messages.TextDocumentPositionParams; begin LSP.Messages.TextDocumentPositionParams'Read (Stream, Params); return Response : LSP.Messages.Hover_Response do Handler.Text_Document_Hover_Request (Response => Response, Value => Params); end return; end Do_Hover; ------------------- -- Do_Initialize -- ------------------- function Do_Initialize (Stream : access Ada.Streams.Root_Stream_Type'Class; Handler : not null LSP.Message_Handlers.Request_Handler_Access) return LSP.Messages.ResponseMessage'Class is Params : LSP.Messages.InitializeParams; begin LSP.Messages.InitializeParams'Read (Stream, Params); return Response : LSP.Messages.Initialize_Response do Handler.Initialize_Request (Response => Response, Value => Params); end return; end Do_Initialize; ------------------ -- Do_Not_Found -- ------------------ function Do_Not_Found (Stream : access Ada.Streams.Root_Stream_Type'Class; Handler : not null LSP.Message_Handlers.Request_Handler_Access) return LSP.Messages.ResponseMessage'Class is pragma Unreferenced (Stream, Handler); begin return Response : LSP.Messages.ResponseMessage do Response.error := (Is_Set => True, Value => (code => LSP.Messages.MethodNotFound, message => +"No such method", others => <>)); end return; end Do_Not_Found; ------------------- -- Do_References -- ------------------- function Do_References (Stream : access Ada.Streams.Root_Stream_Type'Class; Handler : not null LSP.Message_Handlers.Request_Handler_Access) return LSP.Messages.ResponseMessage'Class is Params : LSP.Messages.ReferenceParams; begin LSP.Messages.ReferenceParams'Read (Stream, Params); return Response : LSP.Messages.Location_Response do Handler.Text_Document_References_Request (Response => Response, Value => Params); end return; end Do_References; ----------------- -- Do_Shutdown -- ----------------- function Do_Shutdown (Stream : access Ada.Streams.Root_Stream_Type'Class; Handler : not null LSP.Message_Handlers.Request_Handler_Access) return LSP.Messages.ResponseMessage'Class is pragma Unreferenced (Stream); begin return Response : LSP.Messages.ResponseMessage do Handler.Shutdown_Request (Response); end return; end Do_Shutdown; ----------------------- -- Do_Signature_Help -- ----------------------- function Do_Signature_Help (Stream : access Ada.Streams.Root_Stream_Type'Class; Handler : not null LSP.Message_Handlers.Request_Handler_Access) return LSP.Messages.ResponseMessage'Class is Params : LSP.Messages.TextDocumentPositionParams; begin LSP.Messages.TextDocumentPositionParams'Read (Stream, Params); return Response : LSP.Messages.SignatureHelp_Response do Handler.Text_Document_Signature_Help_Request (Response => Response, Value => Params); end return; end Do_Signature_Help; ------------------------- -- Do_Workspace_Symbol -- ------------------------- function Do_Workspace_Symbol (Stream : access Ada.Streams.Root_Stream_Type'Class; Handler : not null LSP.Message_Handlers.Request_Handler_Access) return LSP.Messages.ResponseMessage'Class is Params : LSP.Messages.WorkspaceSymbolParams; begin LSP.Messages.WorkspaceSymbolParams'Read (Stream, Params); return Response : LSP.Messages.Symbol_Response do Handler.Workspace_Symbol_Request (Response => Response, Value => Params); end return; end Do_Workspace_Symbol; ------------------------- -- Ignore_Notification -- ------------------------- procedure Ignore_Notification (Stream : access Ada.Streams.Root_Stream_Type'Class; Handler : not null LSP.Message_Handlers.Notification_Handler_Access) is begin null; end Ignore_Notification; end LSP.Servers.Handlers;
-------------------------------------------- -- -- -- PACKAGE GAME - PARTIE ADA -- -- -- -- GAME-DISPLAY-DRAW.ADS -- -- -- -- Gestion du dessin sur surface -- -- -- -- Créateur : CAPELLE Mikaël -- -- Adresse : capelle.mikael@gmail.com -- -- -- -- Dernière modification : 14 / 06 / 2011 -- -- -- -------------------------------------------- with Game.Gtype, Game; use Game.Gtype, Game; package Game.Display.Draw is -- Pour utiliser Put_Pixel et Get_Pixel, la surface S doit être bloqué (lock) -- Transforme le Pixel contenue à la position (X,Y) de la surface S procedure Put_Pixel (Surf : in out Surface; X,Y : in Coord; Col : in Color); -- Récupère la couleur du Pixel se trouvant à la position (X,Y) de la -- surface S function Get_Pixel (Surf : in Surface; X,Y : in Coord) return Color; -- Une surface doit être bloqué avant tout dessin dessus -- Bloque (Lock) ou Debloque (Unlock) la surface S procedure Lock_Surface (Surf : in Surface); procedure Unlock_Surface (Surf : in Surface); -- Dessine un cercle procedure Cercle(Surf : in out Surface; -- Surface sur laquelle le cercle sera dessiné Centre : in Rect; -- Position du centre du cercle Col : in Color; -- Couleur du cercle Rayon : in Positive; -- Rayon du cercle Epaisseur : in Positive := 1; -- Epaisseur du cercle (bord) Lock : in Boolean := True); -- Surface à bloquer avant le dessin ? -- Dessine un disque procedure Disque(Surf : in out Surface; -- Surface sur laquelle le disque sera dessiné Centre : in Rect; -- Position du centre du disque Col : in Color; -- Couleur du disque Rayon : in Positive; -- Rayon du disque Lock : in Boolean := True); -- Surface à bloquer avant le dessin ? -- Trace un segmen procedure Segment(Surf : in out Surface; -- Surface sur laquelle le segment sera tracé X1,Y1 : in Integer; -- Position du point de départ X2,Y2 : in Integer; -- Position du point d'arrivée Col : in Color; -- Couleur du segment Lock : in Boolean := True); -- Surface à bloquer avant le tracé ? end Game.Display.Draw;
with Ada.Containers.Vectors; use Ada.Containers; with Ada.Text_IO; use Ada.Text_IO; procedure Day14 is package Natural_Vectors is new Vectors (Index_Type => Natural, Element_Type => Natural); Score_Board : Natural_Vectors.Vector; Part2_Goal : Natural_Vectors.Vector; Part2_Goal_Index : Natural := 0; Input : constant Natural := 165061; Elf1 : Natural := 0; Elf2 : Natural := 1; procedure Mix_Recipes is Sum : constant Natural := Score_Board (Elf1) + Score_Board (Elf2); Recipe1 : constant Natural := Sum / 10; Recipe2 : constant Natural := Sum mod 10; begin if Sum >= 10 then Score_Board.Append (Recipe1); end if; Score_Board.Append (Recipe2); Elf1 := (Elf1 + Score_Board (Elf1) + 1) mod Natural (Score_Board.Length); Elf2 := (Elf2 + Score_Board (Elf2) + 1) mod Natural (Score_Board.Length); end Mix_Recipes; begin -- Part 1 Score_Board.Append (3); Score_Board.Append (7); while Natural (Score_Board.Length) < (Input + 10) loop Mix_Recipes; end loop; Put ("Part 1 ="); for I in Input .. (Input + 9) loop Put (Natural'Image (Score_Board (I))); end loop; Put_Line (""); -- Part 2 Part2_Goal.Append (1); Part2_Goal.Append (6); Part2_Goal.Append (5); Part2_Goal.Append (0); Part2_Goal.Append (6); Part2_Goal.Append (1); Score_Board.Clear; Score_Board.Reserve_Capacity (2500000); Score_Board.Append (3); Score_Board.Append (7); Elf1 := 0; Elf2 := 1; Infinite_Loop : loop declare End_Index : constant Natural := Natural (Score_Board.Length); begin Mix_Recipes; for I in End_Index .. Natural (Score_Board.Length) - 1 loop if Score_Board (I) = Part2_Goal (Part2_Goal_Index) then Part2_Goal_Index := Part2_Goal_Index + 1; else Part2_Goal_Index := 0; end if; if Part2_Goal_Index = Natural (Part2_Goal.Length) then Put_Line ("Part 2 =" & Natural'Image (I - (Part2_Goal_Index - 1))); exit Infinite_Loop; end if; end loop; end; end loop Infinite_Loop; end Day14;
with Ada.Text_IO; use Ada.Text_IO; with Interfaces.C; use Interfaces.C; package Scheme_Test is procedure Adainit; pragma Import (C, AdaInit); procedure Adafinal; pragma Import (C, AdaFinal); function Hello_Ada(Num : Int) return Int with Export => True, Convention => C, External_Name => "hello_ada"; function Hello_Scheme (String : Char_Array) return Int with Import => True, Convention => C, External_Name => "hello_scheme"; end Scheme_Test;
------------------------------------------------------------------------------ -- Copyright (c) 2016-2017, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ package body Natools.Smaz_Implementations.Base_256 is use type Ada.Streams.Stream_Element; use type Ada.Streams.Stream_Element_Offset; procedure Read_Code (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Code : out Ada.Streams.Stream_Element; Verbatim_Length : out Natural; Last_Code : in Ada.Streams.Stream_Element; Variable_Length_Verbatim : in Boolean) is Input_Byte : constant Ada.Streams.Stream_Element := Input (Offset); begin if Input_Byte <= Last_Code then Code := Input_Byte; Verbatim_Length := 0; else Code := 0; if not Variable_Length_Verbatim then Verbatim_Length := Natural (Ada.Streams.Stream_Element'Last - Input_Byte) + 1; elsif Input_Byte < Ada.Streams.Stream_Element'Last then Verbatim_Length := Positive (Ada.Streams.Stream_Element'Last - Input_Byte); else Offset := Offset + 1; Verbatim_Length := Positive (Input (Offset)) + Natural (Ada.Streams.Stream_Element'Last - Last_Code) - 1; end if; end if; Offset := Offset + 1; end Read_Code; procedure Read_Verbatim (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Output : out String) is begin for I in Output'Range loop Output (I) := Character'Val (Input (Offset)); Offset := Offset + 1; end loop; end Read_Verbatim; procedure Skip_Verbatim (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Verbatim_Length : in Positive) is pragma Unreferenced (Input); begin Offset := Offset + Ada.Streams.Stream_Element_Offset (Verbatim_Length); end Skip_Verbatim; function Verbatim_Size (Input_Length : in Positive; Last_Code : in Ada.Streams.Stream_Element; Variable_Length_Verbatim : in Boolean) return Ada.Streams.Stream_Element_Count is Verbatim1_Max_Size : constant Ada.Streams.Stream_Element_Count := Ada.Streams.Stream_Element_Count (Ada.Streams.Stream_Element'Last - Last_Code) - Boolean'Pos (Variable_Length_Verbatim); Verbatim2_Max_Size : constant Ada.Streams.Stream_Element_Count := Ada.Streams.Stream_Element_Count (Ada.Streams.Stream_Element'Last) + Verbatim1_Max_Size; Remaining : Ada.Streams.Stream_Element_Count := Ada.Streams.Stream_Element_Count (Input_Length); Overhead : Ada.Streams.Stream_Element_Count := 0; begin if Variable_Length_Verbatim then if Remaining >= Verbatim2_Max_Size then declare Full_Blocks : constant Ada.Streams.Stream_Element_Count := Remaining / Verbatim2_Max_Size; begin Overhead := Overhead + 2 * Full_Blocks; Remaining := Remaining - Verbatim2_Max_Size * Full_Blocks; end; end if; if Remaining > Verbatim1_Max_Size then Overhead := Overhead + 2; Remaining := 0; end if; end if; declare Block_Count : constant Ada.Streams.Stream_Element_Count := (Remaining + Verbatim1_Max_Size - 1) / Verbatim1_Max_Size; begin Overhead := Overhead + Block_Count; end; return Overhead + Ada.Streams.Stream_Element_Count (Input_Length); end Verbatim_Size; procedure Write_Code (Output : in out Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Code : in Ada.Streams.Stream_Element) is begin Output (Offset) := Code; Offset := Offset + 1; end Write_Code; procedure Write_Verbatim (Output : in out Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Input : in String; Last_Code : in Ada.Streams.Stream_Element; Variable_Length_Verbatim : in Boolean) is Verbatim1_Max_Size : constant Natural := Natural (Ada.Streams.Stream_Element'Last - Last_Code) - Boolean'Pos (Variable_Length_Verbatim); Verbatim2_Max_Size : constant Natural := Natural (Ada.Streams.Stream_Element'Last) + Verbatim1_Max_Size; Input_Index : Positive := Input'First; Remaining_Length, Block_Length : Positive; begin while Input_Index in Input'Range loop Remaining_Length := Input'Last - Input_Index + 1; if Variable_Length_Verbatim and then Remaining_Length > Verbatim1_Max_Size then Block_Length := Positive'Min (Remaining_Length, Verbatim2_Max_Size); Output (Offset) := Ada.Streams.Stream_Element'Last; Output (Offset + 1) := Ada.Streams.Stream_Element (Block_Length - Verbatim1_Max_Size); Offset := Offset + 2; else Block_Length := Positive'Min (Remaining_Length, Verbatim1_Max_Size); Output (Offset) := Ada.Streams.Stream_Element'Last - Ada.Streams.Stream_Element (Block_Length - 1 + Boolean'Pos (Variable_Length_Verbatim)); Offset := Offset + 1; end if; Verbatim_Copy : for I in 1 .. Block_Length loop Output (Offset) := Character'Pos (Input (Input_Index)); Offset := Offset + 1; Input_Index := Input_Index + 1; end loop Verbatim_Copy; end loop; end Write_Verbatim; end Natools.Smaz_Implementations.Base_256;
with NXP.Device; use NXP.Device; with System; use System; with NXP_SVD; use NXP_SVD; with NXP_SVD.GPIO; use NXP_SVD.GPIO; with NXP_SVD.IOCON; use NXP_SVD.IOCON; with NXP_SVD.INPUTMUX; use NXP_SVD.INPUTMUX; with NXP_SVD.PINT; use NXP_SVD.PINT; package body NXP.GPIO is IOCON : aliased IOCON_Peripheral with Import, Address => S_NS_Periph (IOCON_Base); ------------- -- Any_Set -- ------------- function Any_Set (Pins : GPIO_Points) return Boolean is begin for Pin of Pins loop if Pin.Set then return True; end if; end loop; return False; end Any_Set; ---------- -- Mode -- ---------- overriding function Mode (This : GPIO_Point) return HAL.GPIO.GPIO_Mode is Index : constant GPIO_Pin_Index := GPIO_Pin'Pos (This.Pin); begin return HAL.GPIO.Output; end Mode; -------------- -- Set_Mode -- -------------- overriding function Set_Mode (This : in out GPIO_Point; Mode : HAL.GPIO.GPIO_Config_Mode) return Boolean is Index : constant GPIO_Pin_Index := GPIO_Pin'Pos (This.Pin); begin return True; end Set_Mode; ------------------- -- Pull_Resistor -- ------------------- overriding function Pull_Resistor (This : GPIO_Point) return HAL.GPIO.GPIO_Pull_Resistor is Index : constant GPIO_Pin_Index := GPIO_Pin'Pos (This.Pin); begin return HAL.GPIO.Floating; end Pull_Resistor; ----------------------- -- Set_Pull_Resistor -- ----------------------- overriding function Set_Pull_Resistor (This : in out GPIO_Point; Pull : HAL.GPIO.GPIO_Pull_Resistor) return Boolean is Index : constant GPIO_Pin_Index := GPIO_Pin'Pos (This.Pin); begin return True; end Set_Pull_Resistor; --------- -- Set -- --------- overriding function Set (This : GPIO_Point) return Boolean is Port_Idx : Integer := This.Port'Enum_Rep; Index : constant GPIO_Pin_Index := GPIO_Pin'Pos (This.Pin); begin return This.Periph.B (Port_Idx).B (Index).PBYTE; end Set; ------------- -- All_Set -- ------------- function All_Set (Pins : GPIO_Points) return Boolean is begin for Pin of Pins loop if not Pin.Set then return False; end if; end loop; return True; end All_Set; --------- -- Set -- --------- overriding procedure Set (This : in out GPIO_Point) is Port_Idx : Integer := This.Port'Enum_Rep; Index : constant GPIO_Pin_Index := GPIO_Pin'Pos (This.Pin); begin This.Periph.B (Port_Idx).B (Index).PBYTE := True; end Set; --------- -- Set -- --------- procedure Set (Pins : in out GPIO_Points) is begin for Pin of Pins loop Pin.Set; end loop; end Set; ----------- -- Clear -- ----------- overriding procedure Clear (This : in out GPIO_Point) is Port_Idx : Integer := This.Port'Enum_Rep; Index : constant GPIO_Pin_Index := GPIO_Pin'Pos (This.Pin); begin This.Periph.B (Port_Idx).B (Index).PBYTE := False; end Clear; ----------- -- Clear -- ----------- procedure Clear (Pins : in out GPIO_Points) is begin for Pin of Pins loop Pin.Clear; end loop; end Clear; ------------ -- Toggle -- ------------ overriding procedure Toggle (This : in out GPIO_Point) is Port_Idx : Integer := This.Port'Enum_Rep; Index : constant GPIO_Pin_Index := GPIO_Pin'Pos (This.Pin); Mask : UInt32 := 2 ** Index; begin This.Periph.NOT_k (Port_Idx) := Mask; end Toggle; ------------ -- Toggle -- ------------ procedure Toggle (Points : in out GPIO_Points) is begin for Point of Points loop Point.Toggle; end loop; end Toggle; ------------------ -- Configure_IO -- ------------------ procedure Configure_IO (This : GPIO_Point; Config : GPIO_Port_Configuration) is Port_Idx : Integer := This.Port'Enum_Rep; Index : constant GPIO_Pin_Index := GPIO_Pin'Pos (This.Pin); Mask : UInt32 := 2 ** Index; begin case Config.Mode is when Mode_Out => This.Periph.DIR (Port_Idx) := This.Periph.DIR (Port_Idx) or Mask; IOCON.P (Port_Idx).PIO (Index).CTL.SLEW := CTL_SLEW_Field'Enum_Val (Config.Speed'Enum_Rep); IOCON.P (Port_Idx).PIO (Index).CTL.OD := CTL_OD_Field'Enum_Val (Config.Output_Type'Enum_Rep); when Mode_In => This.Periph.DIR (Port_Idx) := This.Periph.DIR (Port_Idx) and not Mask; IOCON.P (Port_Idx).PIO (Index).CTL.MODE := CTL_MODE_Field'Enum_Val (Config.Resistors'Enum_Rep); IOCON.P (Port_Idx).PIO (Index).CTL.DIGIMODE := Digital; IOCON.P (Port_Idx).PIO (Index).CTL.INVERT := (if Config.Invert then Enabled else Disabled); when Mode_AF => IOCON.P (Port_Idx).PIO (Index).CTL.MODE := CTL_MODE_Field'Enum_Val (Config.Resistors'Enum_Rep); IOCON.P (Port_Idx).PIO (Index).CTL.DIGIMODE := Digital; IOCON.P (Port_Idx).PIO (Index).CTL.INVERT := (if Config.Invert then Enabled else Disabled); when others => null; end case; end Configure_IO; ------------------ -- Configure_IO -- ------------------ procedure Configure_IO (Points : GPIO_Points; Config : GPIO_Port_Configuration) is begin for Point of Points loop Point.Configure_IO (Config); end loop; end Configure_IO; ---------------------------------- -- Configure_Alternate_Function -- ---------------------------------- procedure Configure_Alternate_Function (This : GPIO_Point; AF : GPIO_Alternate_Function) is Port_Idx : Integer := This.Port'Enum_Rep; Index : constant GPIO_Pin_Index := GPIO_Pin'Pos (This.Pin); begin IOCON.P (Port_Idx).PIO (Index).CTL.FUNC := UInt4 (AF); end Configure_Alternate_Function; ---------------------------------- -- Configure_Alternate_Function -- ---------------------------------- procedure Configure_Alternate_Function (Points : GPIO_Points; AF : GPIO_Alternate_Function) is begin for Point of Points loop Point.Configure_Alternate_Function (AF); end loop; end Configure_Alternate_Function; procedure Enable_GPIO_Interrupt (Pin : GPIO_Point; Config : Pint_Configuration) is Port_Idx : Integer := Pin.Port'Enum_Rep; Index : constant GPIO_Pin_Index := GPIO_Pin'Pos (Pin.Pin); INPUTMUX : aliased INPUTMUX_Peripheral with Import, Address => S_NS_Periph (INPUTMUX_Base); PINT : aliased PINT_Peripheral with Import, Address => S_NS_Periph (PINT_Base); Slot : Integer := Config.Slot'Enum_Rep; Mask : UInt8 := (2 ** Slot); begin INPUTMUX.PINTSEL (Slot'Enum_Rep).INTPIN := UInt7 ((Port_Idx * 32) + Index); if Config.Mode = Pint_Edge then PINT.ISEL.PMODE := PINT.ISEL.PMODE and not Mask; if Config.Edge = Pint_Rising then PINT.SIENR.SETENRL := Mask; else PINT.SIENF.SETENAF := Mask; end if; else -- handle level PINT.ISEL.PMODE := PINT.ISEL.PMODE or Mask; if Config.Level = Pint_High then PINT.SIENR.SETENRL := Mask; else PINT.SIENF.SETENAF := Mask; end if; end if; end Enable_GPIO_Interrupt; end NXP.GPIO;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- S Y S T E M . I M G _ L L U -- -- -- -- S p e c -- -- -- -- Copyright (C) 1992-2005 Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, -- -- Boston, MA 02110-1301, USA. -- -- -- -- -- -- -- -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- This package contains the routines for supporting the Image attribute for -- unsigned (modular) integer types larger than Size Unsigned'Size, and also -- for conversion operations required in Text_IO.Modular_IO for such types. with System.Unsigned_Types; package System.Img_LLU is pragma Pure; function Image_Long_Long_Unsigned (V : System.Unsigned_Types.Long_Long_Unsigned) return String; -- Computes Long_Long_Unsigned'Image (V) and returns the result. procedure Set_Image_Long_Long_Unsigned (V : System.Unsigned_Types.Long_Long_Unsigned; S : out String; P : in out Natural); -- Sets the image of V starting at S (P + 1) with no leading spaces (i.e. -- Text_IO format where Width = 0), starting at S (P + 1), updating P -- to point to the last character stored. The caller promises that the -- buffer is large enough and no check is made for this (Constraint_Error -- will not be necessarily raised if this is violated since it is perfectly -- valid to compile this unit with checks off). end System.Img_LLU;
with System; with System.Storage_Elements; use System.Storage_Elements; with System.Machine_Code; use System.Machine_Code; with System.BB.MCU_Parameters; use System.BB.MCU_Parameters; package body STM32GD.Startup is procedure Stack_End with Import => True, Convention => Asm, External_Name => "__stack_end"; procedure Ada_Main with Import => True, Convention => C, External_Name => "main"; procedure SVCall_Handler with Export => True, External_Name => "__gnat_sv_call_trap"; pragma Weak_External (SVCall_Handler); procedure PendSV_Handler with Export => True, External_Name => "__gnat_pend_sv_trap"; pragma Weak_External (PendSV_Handler); procedure SysTick_Handler with Export => True, External_Name => "__gnat_sys_tick_trap"; pragma Weak_External (SysTick_Handler); procedure Default_Handler with Export => True, External_Name => "__gnat_irq_trap"; pragma Weak_External (Default_Handler); procedure Default_Handler is begin null; end Default_Handler; procedure Fault_Handler is begin loop null; end loop; end Fault_Handler; procedure SVCall_Handler is begin null; end SVCall_Handler; procedure PendSV_Handler is begin null; end PendSV_Handler; procedure SysTick_Handler is begin null; end SysTick_Handler; procedure Reset_Handler is Sdata : Storage_Element with Import, Convention => Asm, External_Name => "__data_start"; Edata : Storage_Element with Import, Convention => Asm, External_Name => "__data_end"; Sbss : Storage_Element with Import, Convention => Asm, External_Name => "__bss_start"; Ebss : Storage_Element with Import, Convention => Asm, External_Name => "__bss_end"; Data_Size : constant Storage_Offset := Edata'Address - Sdata'Address; -- Index from 1 so as to avoid subtracting 1 from the size Data_In_Flash : Storage_Array (1 .. Data_Size) with Import, Convention => Asm, External_Name => "__data_load"; Data_In_Sram : Storage_Array (1 .. Data_Size) with Import, Convention => Asm, External_Name => "__data_start"; Bss_Size : constant Storage_Offset := Ebss'Address - Sbss'Address; Bss : Storage_Array (1 .. Bss_Size) with Import, Convention => Ada, External_Name => "__bss_start"; begin Asm ("movs r0, #0; ldr r0, [r0]", Volatile => True); Asm ("movs r1, #0; sub r1, #1", Volatile => True); Asm ("cmp r0, r1; bne 1f", Volatile => True); Asm ("movs r0, #1; movs r2, #8; lsl r0, r2", Volatile => True); Asm ("movs r1, #1; movs r2, #29; lsl r1, r2", Volatile => True); Asm ("add r0, r1", Volatile => True); Asm ("1: mov sp, r0", Volatile => True); Data_In_Sram := Data_In_Flash; Bss := (others => 0); Ada_Main; end Reset_Handler; Vectors : array (1 .. Number_Of_Interrupts) of System.Address := ( Stack_End'Address, Reset_Handler'Address, Fault_Handler'Address, Fault_Handler'Address, Fault_Handler'Address, Fault_Handler'Address, Fault_Handler'Address, Fault_Handler'Address, Fault_Handler'Address, Fault_Handler'Address, Fault_Handler'Address, SVCall_Handler'Address, Fault_Handler'Address, Fault_Handler'Address, PendSV_Handler'Address, SysTick_Handler'Address, others => Default_Handler'Address) with Export; pragma Linker_Section (Vectors, ".vectors"); end STM32GD.Startup;
------------------------------------------------------------------------------ -- -- -- Hardware Abstraction Layer for STM32 Targets -- -- -- -- Copyright (C) 2014, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- This file provides register definitions for the STM32F4 (ARM Cortex M4F) -- microcontrollers from ST Microelectronics. pragma Restrictions (No_Elaboration_Code); with System; with STM32F4.GPIO; use STM32F4.GPIO; package STM32F4.SYSCFG is procedure Connect_External_Interrupt (Port : GPIO_Port; Pin : GPIO_Pin) with Inline; procedure Connect_External_Interrupt (Port : GPIO_Port; Pins : GPIO_Pins) with Inline; procedure Set_External_Trigger (Pin : GPIO_Pin; Trigger : External_Triggers) with Inline; procedure Set_External_Trigger (Pins : GPIO_Pins; Trigger : External_Triggers) with Inline; -- TODO: consider merging these two into those of Set_External_Trigger ??? procedure Select_Trigger_Edge (Pin : GPIO_Pin; Trigger : External_Triggers) with Inline; procedure Select_Trigger_Edge (Pins : GPIO_Pins; Trigger : External_Triggers) with Inline; procedure Clear_External_Interrupt (Pin : GPIO_Pin) with Inline; private type Boolean32 is array (0 .. 31) of Boolean; for Boolean32'Component_Size use 1; type EXTI_Registers is record IMR : Boolean32; -- Interrupt Mask Register EMR : Boolean32; -- Event Mask Register RTSR : Boolean32; -- Rising Trigger Selection Register FTSR : Boolean32; -- Falling Trigger Selection Register SWIER : Bits_32x1; -- Software Interrupt Event Register PR : Bits_32x1; -- Pending Register end record with Volatile; for EXTI_Registers use record IMR at 0 range 0 .. 31; EMR at 4 range 0 .. 31; RTSR at 8 range 0 .. 31; FTSR at 12 range 0 .. 31; SWIER at 16 range 0 .. 31; PR at 20 range 0 .. 31; end record; EXTI : EXTI_Registers with Volatile, Address => System'To_Address (EXTI_Base); pragma Import (Ada, EXTI); -- see pg 298 of "RM0090 Reference manual" in file named DM00031020.pdf -- There are four EXTICR registers in SYSCFG. Each register logically -- contains four EXTI_n values, each of which is 4 bits in length, for -- a total of 16 bits used in any one register. The other 16 bits are -- reserved per register. -- For a given EXTI_n, 'n' corresponds to a GPIO pin in the range -- zero through fifteen. Hence EXTI_0 corresponds to pin zero, EXTI_1 -- corresponds to pin one, and so on. Since there are 16 total pins, and -- each EXTRCR register holds four EXTI_n values, four EXTICR registers are -- required. -- So we have a way of handling 16 pins, one per EXTI_n value. But of -- course there are multiple ports, each with 16 distinct pins, yet there -- are only a total of 16 EXTI_n values. Therefore the 16 EXTI_n values are -- shared among all the ports. EXTI_3 corresponds to pin 3 for any one of -- GPIO_A, or GPIO_B, or GPIO_C, and so on. Combinations of ports are not -- allowed for any given EXTI_n value. Only one port can be associated with -- the same EXTI_n pin. Thus the value held within any EXTI_n indicates -- which single GPIO port is intended to be associated with that -- corresponding pin. -- Therefore, to map a given pin 'n' on a given port 'P' to an external -- interrupt or event, all we must do is find the EXTI_n corresponding -- to pin 'n' and write the port value 'P' into it. -- The hardware dictates the mapping of each EXTI_n within the four EXTICR -- registers. EXTICR(1) contains EXTI_0 through EXTI_3, EXTICR(2) holds -- EXTI_4 through EXTI_7, and so on. -- An EXTI_n value is just a GPIO port name. We need to have four of them -- per register, so we define an array of port names. These port names -- are numeric values, starting with zero for port A and increasing -- monotonically. These values are ensured by the aspect clause on the -- type GPIO_Port_Id. type GPIO_Port_Id is (GPIO_Port_A, GPIO_Port_B, GPIO_Port_C, GPIO_Port_D, GPIO_Port_E, GPIO_Port_F, GPIO_Port_G, GPIO_Port_H, GPIO_Port_I, GPIO_Port_J, GPIO_Port_K); -- TODO: rather ugly to have this board-specific range here, but if we -- put it in STM32F4.GPIO it will be just as bad, and if we put it in -- STM32F4[29].Discovery that will create a dependence on that package here, -- which is not the intent for GPIO_Port_Id'Size use 4; pragma Compile_Time_Error (not (GPIO_Port_Id'First = GPIO_Port_A and GPIO_Port_Id'Last = GPIO_Port_K and GPIO_Port_A'Enum_Rep = 0 and GPIO_Port_B'Enum_Rep = 1 and GPIO_Port_C'Enum_Rep = 2 and GPIO_Port_D'Enum_Rep = 3 and GPIO_Port_E'Enum_Rep = 4 and GPIO_Port_F'Enum_Rep = 5 and GPIO_Port_G'Enum_Rep = 6 and GPIO_Port_H'Enum_Rep = 7 and GPIO_Port_I'Enum_Rep = 8 and GPIO_Port_J'Enum_Rep = 9 and GPIO_Port_K'Enum_Rep = 10), "Invalid representation for type GPIO_Port_Id"); -- Confirming, but depended upon so we check it. function As_GPIO_Port_Id (Port : GPIO_Port) return GPIO_Port_Id with Inline; type EXTI_N_List is array (0 .. 3) of GPIO_Port_Id; -- NB: if you change the indexes you need to change the calculations in -- procedure Connect_External_Interrupt for EXTI_n_List'Component_Size use 4; -- Each control register has four EXTI_n values and a reserved 16-bit area. type EXTI_Control_Register is record EXTI : EXTI_n_List; Reserved : Half_Word; end record; for EXTI_Control_Register use record EXTI at 0 range 0 .. 15; Reserved at 2 range 0 .. 15; end record; type EXTI_Control_Registers is array (0 .. 3) of EXTI_Control_Register; -- NB: if you change the indexes you need to change the calculations in -- procedure Connect_External_Interrupt for EXTI_Control_Registers'Component_Size use 32; for EXTI_Control_Registers'Size use 4 * 32; type SYSCFG_Registers is record MEMRM : Word; PMC : Word; EXTICR : EXTI_Control_Registers; Reserved1 : Word; Reserved2 : Word; CMPCR : Word; end record with Volatile; for SYSCFG_Registers use record MEMRM at 0 range 0 .. 31; PMC at 4 range 0 .. 31; EXTICR at 8 range 0 .. 127; Reserved1 at 24 range 0 .. 31; Reserved2 at 28 range 0 .. 31; CMPCR at 32 range 0 .. 31; end record; SYSCFG : SYSCFG_Registers with Volatile, Address => System'To_Address (SYSCFG_Base); pragma Import (Ada, SYSCFG); end STM32F4.SYSCFG;
generic type Real is digits <>; type R_Index is range <>; type C_Index is range <>; type Matrix is array(R_Index, C_Index) of Real; package Rectangular_Test_Matrices is type Matrix_Id is (Zero_Diagonal, -- all 1's with 0 down the diagonal Upper_Ones, -- Lower_Ones, -- Zero_Cols_and_Rows, -- 1st 4 rows and cols all 0; else it's Upper_Ones Random, -- new seed each run. 16 bit elements (1 bit => 4x4 often singular) Frank, Ding_Dong, -- eigs clustered ~ pi; 99x99 matrix has lots of pi's to 18 sig. figs. Vandermonde, -- max allowed matrix size is 256 x 256 without over/under flow All_Zeros, All_Ones); procedure Init_Matrix (M : out Matrix; Desired_Matrix : in Matrix_Id := Random; Final_Row : in R_Index := R_Index'Last; Final_Col : in C_Index := C_Index'Last; Starting_Row : in R_Index := R_Index'First; Starting_Col : in C_Index := C_Index'First); end Rectangular_Test_Matrices;
package Inline2_Pkg is function Valid_Real (Number : Float) return Boolean; pragma Inline (Valid_Real); function Invalid_Real return Float; pragma Inline (Invalid_Real); end Inline2_Pkg;
-- part of AdaYaml, (c) 2017 Felix Krause -- released under the terms of the MIT license, see the file "copying.txt" with Yaml.Dom.Vectors; with Yaml.Events.Queue; with Yaml.Destination; package Yaml.Dom.Dumping is function To_Event_Queue (Document : Document_Reference) return Events.Queue.Reference; function To_Event_Queue (Documents : Vectors.Vector) return Events.Queue.Reference; procedure Dump (Document : Document_Reference; Output : not null Destination.Pointer); procedure Dump (Documents : Vectors.Vector; Output : not null Destination.Pointer); end Yaml.Dom.Dumping;
with Piles; with Ada.Text_IO; use Ada.Text_IO; with Ada.Unchecked_Deallocation; --// Pour libérer la mémoire allouée dynamiquement procedure Exemples_Memoire_Dynamique is type T_Pointeur_Integer is access Integer; procedure Free is new Ada.Unchecked_Deallocation (Integer, T_Pointeur_Integer); -- ou Ada.Unchecked_Deallocation (Object => Integer, Name => T_Pointeur_Integer); -- Allocation dynamique de mémoire et libération de cette mémoire. procedure Illustrer_Memoire_Dynamique is Ptr1 : T_Pointeur_Integer; begin Ptr1 := new Integer; -- Allocation dyamique de mémoire Ptr1.all := 5; -- Utilisation de cette mémoire Put_Line ("Ptr1.all = " & Integer'Image (Ptr1.all)); Free (Ptr1); -- Libération de la mémoire pragma Assert (Ptr1 = Null); -- Free met le pointeur à Null end Illustrer_Memoire_Dynamique; -- Mémoire allouée dynamiquement et non libérée. procedure Illustrer_Memoire_Dynamique_Sans_Free is Ptr1 : T_Pointeur_Integer; begin Ptr1 := new Integer; Ptr1.all := 5; Put_Line ("Ptr1.all = " & Integer'Image (Ptr1.all)); Free (Ptr1); end Illustrer_Memoire_Dynamique_Sans_Free; -- Illustrer la libération explicite de la mémoire et les précautions à -- prendre... procedure Illustrer_Memoire_Dynamique_Erreur is Ptr1, Ptr2 : T_Pointeur_Integer; begin Ptr1 := new Integer; Ptr2 := Ptr1; Ptr1.all := 5; pragma Assert (Ptr1.all = 5); pragma Assert (Ptr2.all = 5); Free (Ptr1); pragma Assert (Ptr1 = Null); -- le pointeur est bien mis à Null pragma Assert (Ptr2 /= Null); -- XXX Quelle est la valeur de Ptr2.all ? Null. --Put_Line ("Ptr2.all = " & Integer'Image (Ptr2.all)); --Ptr2.all := 7; --pragma Assert (Ptr2.all = 7); -- XXX A-t-on le droit de manipuler Ptr2.all ? Non. -- Si on éxucute le programme une exception est levée. -- XXX Que se passe-t-il si on exécute le programme avec valkyrie ? -- -- -- Le terme "Unchecked" dans Unchecked_Deallocation vient de là. Ada -- n'a pas de moyen de contrôler que quand on libère de la mémoire il -- n'y a plus aucun pointeur dans le programme qui la référence. C'est -- à la charge du programmeur ! Utiliser un ramasse-miettes (garbage -- collector) résoud ce problème car il ne libèrera la mémoire que s'il -- n'y a plus aucune référence dessus. end Illustrer_Memoire_Dynamique_Erreur; -- Illustrer les conséquence d'avoir un paramètre en in qui est un pointeur. procedure Illustrer_Pointeur_In is procedure SP (Ptr : in T_Pointeur_Integer) is begin Ptr.all := 123; end SP; Ptr : T_Pointeur_Integer; begin Ptr := new Integer; Ptr.all := 111; SP (Ptr); -- XXX Quelle est la valeur de Ptr.all ? 123 Put_Line ("valeur de Ptr.all ? " & Integer'Image (Ptr.all)); Free (Ptr); end Illustrer_Pointeur_In; -- Illustrer la question "Faut-il Detruire un pile chaînée si c'est -- une variable locale d'un sous-programme ?". procedure Illustrer_Pile_Locale is package Pile is new Piles (Integer); use Pile; P : T_Pile; begin Initialiser (P); Empiler (P, 4); Put_Line ("Sommet = " & Integer'Image (Sommet (P))); Empiler (P, 2); Put_Line ("Sommet = " & Integer'Image (Sommet (P))); Detruire (P); -- XXX P étant une variable locale du sous-programme, a-t-on besoin -- d'appeler Detruire dessus ? OUI end Illustrer_Pile_Locale; begin Illustrer_Memoire_Dynamique; Illustrer_Memoire_Dynamique_Sans_Free; Illustrer_Memoire_Dynamique_Erreur; Illustrer_Pointeur_In; Illustrer_Pile_Locale; end Exemples_Memoire_Dynamique;
with aIDE, AdaM.Factory; procedure launch_AIDE is begin AdaM.Factory.open; aIDE.start; aIDE.stop; AdaM.Factory.close; end launch_AIDE;
----------------------------------------------------------------------- -- el-expressions-nodes -- Expression Nodes -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2020, 2021 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- The 'ELNode' describes an expression that can later be evaluated -- on an expression context. Expressions are parsed and translated -- to a read-only tree. with EL.Functions; with Ada.Strings.Wide_Wide_Unbounded; private with Ada.Strings.Unbounded; with Util.Concurrent.Counters; private package EL.Expressions.Nodes is pragma Preelaborate; use EL.Functions; use Ada.Strings.Wide_Wide_Unbounded; use Ada.Strings.Unbounded; type Reduction; type ELNode is abstract tagged limited record Ref_Counter : Util.Concurrent.Counters.Counter; end record; type ELNode_Access is access all ELNode'Class; type Reduction is record Node : ELNode_Access; Value : EL.Objects.Object; end record; -- Evaluate a node on a given context. If function Get_Safe_Value (Expr : in ELNode; Context : in ELContext'Class) return Object; -- Evaluate a node on a given context. function Get_Value (Expr : in ELNode; Context : in ELContext'Class) return Object is abstract; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. function Reduce (Expr : access ELNode; Context : in ELContext'Class) return Reduction is abstract; -- Delete the expression tree (calls Delete (ELNode_Access) recursively). procedure Delete (Node : in out ELNode) is abstract; -- Delete the expression tree. Free the memory allocated by nodes -- of the expression tree. Clears the node pointer. procedure Delete (Node : in out ELNode_Access); -- ------------------------------ -- Unary expression node -- ------------------------------ type ELUnary is new ELNode with private; type Unary_Node is (EL_VOID, EL_NOT, EL_MINUS, EL_EMPTY); -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELUnary; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELUnary; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELUnary); -- ------------------------------ -- Binary expression node -- ------------------------------ type ELBinary is new ELNode with private; type Binary_Node is (EL_EQ, EL_NE, EL_LE, EL_LT, EL_GE, EL_GT, EL_ADD, EL_SUB, EL_MUL, EL_DIV, EL_MOD, EL_AND, EL_OR, EL_LAND, EL_LOR, EL_CONCAT); -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELBinary; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELBinary; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELBinary); -- ------------------------------ -- Ternary expression node -- ------------------------------ type ELTernary is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELTernary; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELTernary; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELTernary); -- ------------------------------ -- Variable to be looked at in the expression context -- ------------------------------ type ELVariable is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELVariable; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELVariable; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELVariable); -- ------------------------------ -- Value property referring to a variable -- ------------------------------ type ELValue (Len : Natural) is new ELNode with private; type ELValue_Access is access all ELValue'Class; -- Check if the target bean is a readonly bean. function Is_Readonly (Node : in ELValue; Context : in ELContext'Class) return Boolean; -- Get the variable name. function Get_Variable_Name (Node : in ELValue) return String; -- Evaluate the node and return a method info with -- the bean object and the method binding. function Get_Method_Info (Node : in ELValue; Context : in ELContext'Class) return Method_Info; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELValue; Context : ELContext'Class) return Object; -- Evaluate the node and set the value on the associated bean. -- Raises Invalid_Variable if the target object is not a bean. -- Raises Invalid_Expression if the target bean is not writeable. procedure Set_Value (Node : in ELValue; Context : in ELContext'Class; Value : in Objects.Object); -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELValue; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELValue); -- ------------------------------ -- Literal object (integer, boolean, float, string) -- ------------------------------ type ELObject is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELObject; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELObject; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELObject); -- ------------------------------ -- Function call with up to 4 arguments -- ------------------------------ type ELFunction is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELFunction; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELFunction; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELFunction); -- Create constant nodes function Create_Node (Value : Boolean) return ELNode_Access; function Create_Node (Value : Long_Long_Integer) return ELNode_Access; function Create_Node (Value : String) return ELNode_Access; function Create_Node (Value : Wide_Wide_String) return ELNode_Access; function Create_Node (Value : Long_Float) return ELNode_Access; function Create_Node (Value : Unbounded_Wide_Wide_String) return ELNode_Access; function Create_Variable (Name : in Wide_Wide_String) return ELNode_Access; function Create_Value (Variable : in ELNode_Access; Name : in Wide_Wide_String) return ELNode_Access; -- Create unary expressions function Create_Node (Of_Type : Unary_Node; Expr : ELNode_Access) return ELNode_Access; -- Create binary expressions function Create_Node (Of_Type : Binary_Node; Left : ELNode_Access; Right : ELNode_Access) return ELNode_Access; -- Create a ternary expression. function Create_Node (Cond : ELNode_Access; Left : ELNode_Access; Right : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access; Arg3 : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access; Arg3 : ELNode_Access; Arg4 : ELNode_Access) return ELNode_Access; private type ELUnary is new ELNode with record Kind : Unary_Node; Node : ELNode_Access; end record; -- ------------------------------ -- Binary nodes -- ------------------------------ type ELBinary is new ELNode with record Kind : Binary_Node; Left : ELNode_Access; Right : ELNode_Access; end record; -- ------------------------------ -- Ternary expression -- ------------------------------ type ELTernary is new ELNode with record Cond : ELNode_Access; Left : ELNode_Access; Right : ELNode_Access; end record; -- #{bean.name} - Bean name, Bean property -- #{bean[12]} - Bean name, -- Variable to be looked at in the expression context type ELVariable is new ELNode with record Name : Unbounded_String; end record; type ELVariable_Access is access all ELVariable; type ELValue (Len : Natural) is new ELNode with record Variable : ELNode_Access; Name : String (1 .. Len); end record; -- A literal object (integer, boolean, float, String) type ELObject is new ELNode with record Value : Object; end record; -- A function call with up to 4 arguments. type ELFunction is new ELNode with record Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access; Arg3 : ELNode_Access; Arg4 : ELNode_Access; end record; end EL.Expressions.Nodes;
package Bitmaps.RGB is type Pixel is record R, G, B : Luminance := Luminance'First; end record; type Raster is array (Natural range <>, Natural range <>) of Pixel; type Image (Width, Height : Positive) is record Pixels : Raster (0 .. Height, 0 .. Width); end record; Black : constant Pixel := (others => Luminance'First); White : constant Pixel := (others => Luminance'Last); function Max_X (Source : in Image) return Natural; function Max_Y (Source : in Image) return Natural; function Get_Pixel (Source : in Image; X, Y : Natural) return Pixel; procedure Set_Pixel (Target : in out Image; X, Y : Natural; Value : in Pixel); end Bitmaps.RGB;
package OpenGL.Check is GL_Error : exception; procedure State_OK (Message : in String := ""); procedure Raise_Exception (Message : in String); end OpenGL.Check;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2017-2020, 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. -- -- -- ------------------------------------------------------------------------------ with Ada.Text_IO; use Ada.Text_IO; with Cortex_M_SVD.SCB; use Cortex_M_SVD.SCB; with Cortex_M_SVD.NVIC; use Cortex_M_SVD.NVIC; with AGATE.Arch.ArmvX_m; with AGATE.Scheduler; package body AGATE.Traps is Handlers_Table : array (Trap_ID) of Trap_Handler := (others => null); Priorities_Table : array (Trap_ID) of Trap_Priority := (others => Trap_Priority'First); pragma Unreferenced (Priorities_Table); procedure IRQ_Handler; pragma Export (C, IRQ_Handler, "__unknown_interrupt_handler"); procedure Initialize; procedure Print_Fault; procedure Hard_Fault_Handler; pragma Export (C, Hard_Fault_Handler, "HardFault_Handler"); procedure Mem_Manage_Handler; pragma Export (C, Mem_Manage_Handler, "MemMang_Handler"); procedure Bus_Fault_Handler; pragma Export (C, Bus_Fault_Handler, "BusFault_Handler"); procedure Usage_Fault_Handler; pragma Export (C, Usage_Fault_Handler, "UsageFault_Handler"); ----------------- -- Print_Fault -- ----------------- procedure Print_Fault is type Stack_Array is array (1 .. 8) of Word with Pack, Size => 8 * 32; SP : constant System.Address := System.Address (Arch.ArmvX_m.PSP); SCB : SCB_Peripheral renames SCB_Periph; begin Put_Line ("Forced HardFault : " & SCB_Periph.HFSR.FORCED'Img); Put_Line ("Vector table read VECTTBL : " & SCB.HFSR.VECTTBL'Img); Put_Line ("MemManage:"); Put_Line (" - Instruction access : " & SCB.MMSR.IACCVIOL'Img); Put_Line (" - Data access : " & SCB.MMSR.DACCVIOL'Img); Put_Line (" - Unstacking from excp : " & SCB.MMSR.MUNSTKERR'Img); Put_Line (" - Stacking for excp : " & SCB.MMSR.MSTKERR'Img); Put_Line (" - FPU Lazy state preserv : " & SCB.MMSR.MLSPERR'Img); if SCB.MMSR.MMARVALID then Put_Line ("-> address : " & SCB.MMAR'Img); end if; Put_Line ("BusFault:"); Put_Line (" - Instruction bus error : " & SCB.BFSR.IBUSERR'Img); Put_Line (" - Precise data bus error : " & SCB.BFSR.PRECISERR'Img); Put_Line (" - Imprecise data bus err : " & SCB.BFSR.IMPRECISERR'Img); Put_Line (" - Unstacking from excp : " & SCB.BFSR.UNSTKERR'Img); Put_Line (" - Stacking for excp : " & SCB.BFSR.STKERR'Img); Put_Line (" - FPU Lazy state preserv : " & SCB.BFSR.LSPERR'Img); if SCB.BFSR.BFARVALID then Put_Line ("-> address : " & SCB.BFAR'Img); end if; Put_Line ("UsageFault:"); Put_Line (" - Undefined instruction : " & SCB.UFSR.UNDEFINSTR'Img); Put_Line (" - Invalid state : " & SCB.UFSR.INVSTATE'Img); Put_Line (" - Invalid PC load : " & SCB.UFSR.INVPC'Img); Put_Line (" - No co-processor : " & SCB.UFSR.NOCP'Img); Put_Line (" - Unaligned access : " & SCB.UFSR.UNALIGNED'Img); Put_Line (" - Division by zero : " & SCB.UFSR.DIVBYZERO'Img); Put_Line ("PSP: " & Hex (UInt32 (To_Integer (SP)))); if To_Integer (SP) = 0 or else SP mod Stack_Array'Alignment /= 0 then Put_Line ("Invalid PSP"); else declare Context : Stack_Array with Address => SP; begin Put_Line ("R0 : " & Hex (UInt32 (Context (1)))); Put_Line ("R1 : " & Hex (UInt32 (Context (2)))); Put_Line ("R2 : " & Hex (UInt32 (Context (3)))); Put_Line ("R3 : " & Hex (UInt32 (Context (4)))); Put_Line ("R12: " & Hex (UInt32 (Context (5)))); Put_Line ("LR : " & Hex (UInt32 (Context (6)))); Put_Line ("PC : " & Hex (UInt32 (Context (7)))); Put_Line ("PSR: " & Hex (UInt32 (Context (8)))); end; end if; end Print_Fault; ------------------------ -- Hard_Fault_Handler -- ------------------------ procedure Hard_Fault_Handler is begin Put_Line ("In HardFault"); Print_Fault; loop null; end loop; end Hard_Fault_Handler; ------------------------ -- Mem_Manage_Handler -- ------------------------ procedure Mem_Manage_Handler is begin Put_Line ("In mem manage fault"); Print_Fault; Scheduler.Fault; if Scheduler.Context_Switch_Needed then Scheduler.Do_Context_Switch; end if; end Mem_Manage_Handler; ----------------------- -- Bus_Fault_Handler -- ----------------------- procedure Bus_Fault_Handler is begin Put_Line ("In bus fault"); Print_Fault; Scheduler.Fault; if Scheduler.Context_Switch_Needed then Scheduler.Do_Context_Switch; end if; end Bus_Fault_Handler; ------------------------- -- Usage_Fault_Handler -- ------------------------- procedure Usage_Fault_Handler is begin Put_Line ("In usage fault"); Print_Fault; Scheduler.Fault; if Scheduler.Context_Switch_Needed then Scheduler.Do_Context_Switch; end if; end Usage_Fault_Handler; ---------------- -- Initialize -- ---------------- procedure Initialize is Vector : Word; pragma Import (C, Vector, "__vectors"); Vector_Address : constant Word := Word (To_Integer (Vector'Address)); begin SCB_Periph.VTOR := UInt32 (Vector_Address); -- Processor can enter Thread mode from any level under the control of -- an EXC_RETURN value. SCB_Periph.CCR.NONBASETHREADENA := On_Exc_Return; -- No unalign access traps. SCB_Periph.CCR.UNALIGNED_TRP := False; -- Enable Faults SCB_Periph.SHPRS.MEMFAULTENA := True; SCB_Periph.SHPRS.BUSFAULTENA := True; SCB_Periph.SHPRS.USGFAULTENA := True; AGATE.Arch.ArmvX_m.Enable_Faults; end Initialize; -------------- -- Register -- -------------- procedure Register (Handler : Trap_Handler; ID : Trap_ID; Priority : Trap_Priority) is begin Handlers_Table (ID) := Handler; Priorities_Table (ID) := Priority; end Register; ------------ -- Enable -- ------------ procedure Enable (ID : Trap_ID) is Reg_Index : constant Natural := Natural (ID) / 32; Bit : constant UInt32 := 2**(Natural (ID) mod 32); begin NVIC_Periph.NVIC_ISER (Reg_Index) := Bit; end Enable; ------------- -- Disable -- ------------- procedure Disable (ID : Trap_ID) is Reg_Index : constant Natural := Natural (ID) / 32; Bit : constant UInt32 := 2**(Natural (ID) mod 32); begin NVIC_Periph.NVIC_ICER (Reg_Index) := Bit; end Disable; ----------------- -- IRQ_Handler -- ----------------- procedure IRQ_Handler is ID : constant Trap_ID := Trap_ID (Integer (SCB_Periph.ICSR.VECTACTIVE) - 16); begin if Handlers_Table (ID) /= null then Handlers_Table (ID).all; else Ada.Text_IO.Put_Line ("No handler for: " & ID'Img); loop null; end loop; end if; if Scheduler.Context_Switch_Needed then Scheduler.Do_Context_Switch; end if; end IRQ_Handler; begin Initialize; end AGATE.Traps;
generic No_of_Stars : Natural := 400; far_side : GLOBE_3D.Real; package GLOBE_3D.Stars_sky is pragma Elaborate_Body; procedure Display (Rotation : Matrix_33); end GLOBE_3D.Stars_sky;
with Text_IO; with Ada.Text_IO; with Ada.Integer_Text_IO; with Ada.Sequential_IO; with Ada.Real_Time; with Interfaces; with Ray_Tracer; with Bitmap; with Scene; use Ada.Integer_Text_IO; use Ray_Tracer; use Interfaces; use Ada.Real_Time; use Ada.Text_IO; use Text_IO; procedure Test is t1,t2 : Ada.Real_Time.Time; temp : Ada.Real_Time.Time_Span; sec,sec2 : Ada.Real_Time.Seconds_Count; counter : integer := 0; spp : integer; image : Bitmap.Image; -- image for saving screen buffer to file begin Scene.Init(Ray_Tracer.g_scn, "/home/frol/PROG/HydraRepos/HydraCore/hydra_app/tests/test_42"); --Ray_Tracer.Init_Render(Ray_Tracer.RT_DEBUG); Ray_Tracer.Init_Render(Ray_Tracer.PT_MIS); Ray_Tracer.Resize_Viewport(Ray_Tracer.width, Ray_Tracer.height); Bitmap.Init(image, Ray_Tracer.width, Ray_Tracer.height); Put_Line("render start"); Put("threads_num = "); Put(integer'Image(Ray_Tracer.Threads_Num)); Put_Line(""); -- main rendering loop -- t1 := Ada.Real_Time.Clock; Split (t1, sec, temp); while not Ray_Tracer.Finished loop Ray_Tracer.Render_Pass; spp := Ray_Tracer.GetSPP; t2 := Ada.Real_Time.Clock; Split (t2, sec2, temp); Put("pass "); Put(integer'Image(counter)); Put(" -"); Put(Integer'Image(Integer(sec2-sec))); Put("s elasped. spp = "); Put_Line(integer'Image(spp)); -- copy frame to image and update file on disk -- for y in 0 .. Ray_Tracer.height-1 loop for x in 0 .. Ray_Tracer.width-1 loop image.data(y*Ray_Tracer.width + x) := Ray_Tracer.screen_buffer(x,y); end loop; end loop; Bitmap.SaveBMP(image, "ART_render.bmp"); counter := counter + 1; end loop; Bitmap.Delete(image); Put_Line("render finished"); end Test;
-- MIT License -- Copyright (c) 2021 Stephen Merrony -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- The above copyright notice and this permission notice shall be included in all -- copies or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -- SOFTWARE. with Ada.Real_Time; use Ada.Real_Time; with Ada.Strings.Fixed; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Ada.Text_IO; with Ada.Text_IO.Editing; with Interfaces; use Interfaces; with DG_Types; use DG_Types; with Memory; use Memory; -- Status_Monitor maintains a near real-time status screen available on STAT_PORT. -- -- The screen uses DG DASHER control codes for formatting, so a DASHER terminal emulator -- should be attached to it for good results. -- -- The Monitor task waits for status updates -- from known senders and upon receiving an update refreshes the display of that status -- on the monitor page. It is therefore the responsibility of the sender to update the -- status as often as it sees fit. package body Status_Monitor is type MIPS_T is delta 0.01 digits 5; package MIPS_IO is new Ada.Text_IO.Editing.Decimal_Output ( MIPS_T ); MIPS_Format : constant Ada.Text_IO.Editing.Picture := Ada.Text_IO.Editing.To_Picture ("ZZ9.99"); function To_Float(TS : Time_Span) return Float is SC1, SC2, SC3 : Seconds_Count; TS1, TS2, TS3 : Time_Span; begin -- Use Split(Time_Of()) to split time span into seconds and fraction -- Repeat twice to get microseconds and fraction thereof Split(Time_Of(0, TS), SC1, TS1); Split(Time_Of(0, TS1*1000), SC2, TS2); Split(Time_Of(0, TS2*1000), SC3, TS3); -- NOTE: it is safe to multiply by 1000 because RM95 D.8(31) -- guarantees that Time_Span'Last is >= 3600 seconds. -- Finally do the conversion of the remaining time-span to duration -- and add to other pieces. return (Float(SC1)*1.0E9 + Float(SC2)*1.0E6 + Float(SC3)*1.0E3 + Float(To_Duration(TS3*1000))) / 1.0E9; end To_Float; task body Monitor is Receiver : GNAT.Sockets.Socket_Type; Connection : GNAT.Sockets.Socket_Type; Client : GNAT.Sockets.Sock_Addr_Type; Channel : GNAT.Sockets.Stream_Access; Radix : Number_Base_T := Octal; CPU_Stats : Processor.CPU_Monitor_Rec; DPF_Stats : Devices.Disk6061.Status_Rec; MTB_Stats : Devices.Magtape6026.Status_Rec; Now, Last_CPU_Time, Last_DPF_Time : Time := Clock; CPU_Elapsed, DPF_Elapsed : Time_Span; I_Count, Last_I_Count : Unsigned_64 := 0; MIPS : Float; MIPS_Fixed : MIPS_T; DPF_IO_Count, Last_DPF_IO_Count : Unsigned_64 := 0; DPF_IOPS : Float; DPF_IOPS_I : Natural; begin loop select accept Start (Port : in GNAT.Sockets.Port_Type) do GNAT.Sockets.Create_Socket (Socket => Receiver); GNAT.Sockets.Set_Socket_Option (Socket => Receiver, Level => GNAT.Sockets.Socket_Level, Option => (Name => GNAT.Sockets.Reuse_Address, Enabled => True)); GNAT.Sockets.Bind_Socket (Socket => Receiver, Address => (Family => GNAT.Sockets.Family_Inet, Addr => GNAT.Sockets.Inet_Addr ("127.0.0.1"), Port => Port)); GNAT.Sockets.Listen_Socket (Socket => Receiver); end Start; GNAT.Sockets.Accept_Socket (Server => Receiver, Socket => Connection, Address => Client); Ada.Text_IO.Put_Line ("INFO: Status Monitor connected from " & GNAT.Sockets.Image (Client)); Channel := GNAT.Sockets.Stream (Connection); String'Write (Channel, Dasher_Erase_Page & " " & Dasher_Underline & "MV/Emua Status" & Dasher_Normal & Dasher_NL); or accept CPU_Update (Stats : in Processor.CPU_Monitor_Rec) do CPU_Stats := Stats; end CPU_Update; Now := Clock; I_Count := CPU_Stats.Instruction_Count - Last_I_Count; Last_I_Count := CPU_Stats.Instruction_Count; CPU_Elapsed := Now - Last_CPU_Time; MIPS := Float (I_Count) / To_Float(CPU_Elapsed); MIPS_Fixed := MIPS_T(MIPS / 1_000_000.0); Last_CPU_Time := Now; String'Write (Channel, Dasher_Write_Window_Addr & Character'Val (0) & Character'Val (CPU_Row_1) & Dasher_Erase_EOL); String'Write (Channel, "PC: " & Dword_To_String (Dword_T(CPU_Stats.PC), Radix, 11, true) & " Interrupts: " & Boolean_To_YN (CPU_Stats.ION) & " ATU: " & Boolean_To_YN (CPU_Stats.ATU) & " MIPS: " & MIPS_Fixed'Image ); String'Write (Channel, Dasher_Write_Window_Addr & Character'Val (0) & Character'Val (CPU_Row_2) & Dasher_Erase_EOL); String'Write (Channel, "AC0: " & Dword_To_String (CPU_Stats.AC(0), Radix, 11, true) & " AC1: " & Dword_To_String (CPU_Stats.AC(1), Radix, 11, true) & " AC2: " & Dword_To_String (CPU_Stats.AC(2), Radix, 11, true) & " AC3: " & Dword_To_String (CPU_Stats.AC(3), Radix, 11, true)); or accept DPF_Update (Stats : in Devices.Disk6061.Status_Rec) do DPF_Stats := Stats; end DPF_Update; Now := Clock; DPF_IO_Count := DPF_Stats.Reads + DPF_Stats.Writes - Last_DPF_IO_Count; Last_DPF_IO_Count := DPF_Stats.Reads + DPF_Stats.Writes; DPF_Elapsed := Now - Last_DPF_Time; DPF_IOPS := Float(DPF_IO_Count) / To_Float(DPF_Elapsed); DPF_IOPS_I := Natural(DPF_IOPS) / 1000; Last_DPF_Time := Now; String'Write (Channel, Dasher_Write_Window_Addr & Character'Val (0) & Character'Val (DPF_Row_1) & Dasher_Erase_EOL); String'Write (Channel, "DPF: (DPF0) - Attached: " & Boolean_To_YN (DPF_Stats.Image_Attached) & " Cyl: " & DPF_Stats.Cylinder'Image & " Surf: " & DPF_Stats.Surface'Image & " Sect: " & DPF_Stats.Sector'Image & " KIOPS: " & DPF_IOPS_I'Image); or accept MTB_Update (Stats : in Devices.Magtape6026.Status_Rec) do MTB_Stats := Stats; end MTB_Update; String'Write (Channel, Dasher_Write_Window_Addr & Character'Val (0) & Character'Val (MTB_Row_1) & Dasher_Erase_EOL); String'Write (Channel, "MTA: (MTC0) - Attached: " & Boolean_To_YN (MTB_Stats.Image_Attached(0)) & " Mem Addr: " & Dword_To_String (Dword_T(MTB_Stats.Mem_Addr_Reg), Radix, 12, true) & " Curr Cmd: " & MTB_Stats.Current_Cmd'Image); String'Write (Channel, Dasher_Write_Window_Addr & Character'Val (0) & Character'Val (MTB_Row_2) & Dasher_Erase_EOL); String'Write (Channel, " Image file: " & To_String(MTB_Stats.Image_Filename(0))); or accept Stop do GNAT.Sockets.Close_Socket (Connection); Ada.Text_IO.Put_Line ("INFO: Status Monitor stoppped"); end Stop; or terminate; end select; end loop; end Monitor; end Status_Monitor;
----------------------------------------------------------------------- -- asf.sessions -- ASF Sessions -- Copyright (C) 2010, 2011 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.Unchecked_Deallocation; -- The <b>ASF.Sessions</b> package is an Ada implementation of the -- Java servlet Specification (See JSR 315 at jcp.org). package body ASF.Sessions is use Ada.Strings.Unbounded; -- ------------------------------ -- Returns true if the session is valid. -- ------------------------------ function Is_Valid (Sess : in Session'Class) return Boolean is begin return Sess.Impl /= null and then Sess.Impl.Is_Active; end Is_Valid; -- ------------------------------ -- Returns a string containing the unique identifier assigned to this session. -- The identifier is assigned by the servlet container and is implementation dependent. -- ------------------------------ function Get_Id (Sess : in Session) return String is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; else return Sess.Impl.Id.all; end if; end Get_Id; -- ------------------------------ -- Returns the last time the client sent a request associated with this session, -- as the number of milliseconds since midnight January 1, 1970 GMT, and marked -- by the time the container recieved the request. -- -- Actions that your application takes, such as getting or setting a value associated -- with the session, do not affect the access time. -- ------------------------------ function Get_Last_Accessed_Time (Sess : in Session) return Ada.Calendar.Time is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; else return Sess.Impl.Access_Time; end if; end Get_Last_Accessed_Time; -- ------------------------------ -- Returns the maximum time interval, in seconds, that the servlet container will -- keep this session open between client accesses. After this interval, the servlet -- container will invalidate the session. The maximum time interval can be set with -- the Set_Max_Inactive_Interval method. -- A negative time indicates the session should never timeout. -- ------------------------------ function Get_Max_Inactive_Interval (Sess : in Session) return Duration is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; else return Sess.Impl.Max_Inactive; end if; end Get_Max_Inactive_Interval; -- ------------------------------ -- Specifies the time, in seconds, between client requests before the servlet -- container will invalidate this session. A negative time indicates the session -- should never timeout. -- ------------------------------ procedure Set_Max_Inactive_Interval (Sess : in Session; Interval : in Duration) is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; else Sess.Impl.Max_Inactive := Interval; end if; end Set_Max_Inactive_Interval; -- ------------------------------ -- Returns the object bound with the specified name in this session, -- or null if no object is bound under the name. -- ------------------------------ function Get_Attribute (Sess : in Session; Name : in String) return EL.Objects.Object is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; end if; Sess.Impl.Lock.Read; declare Pos : constant EL.Objects.Maps.Cursor := Sess.Impl.Attributes.Find (Name); begin if EL.Objects.Maps.Has_Element (Pos) then return Value : constant EL.Objects.Object := EL.Objects.Maps.Element (Pos) do Sess.Impl.Lock.Release_Read; end return; end if; exception when others => Sess.Impl.Lock.Release_Read; raise; end; Sess.Impl.Lock.Release_Read; return EL.Objects.Null_Object; end Get_Attribute; -- ------------------------------ -- Binds an object to this session, using the name specified. -- If an object of the same name is already bound to the session, -- the object is replaced. -- -- If the value passed in is null, this has the same effect as calling -- removeAttribute(). -- ------------------------------ procedure Set_Attribute (Sess : in out Session; Name : in String; Value : in EL.Objects.Object) is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; end if; begin Sess.Impl.Lock.Write; if EL.Objects.Is_Null (Value) then -- Do not complain if there is no attribute with the given name. if Sess.Impl.Attributes.Contains (Name) then Sess.Impl.Attributes.Delete (Name); end if; else Sess.Impl.Attributes.Include (Name, Value); end if; exception when others => Sess.Impl.Lock.Release_Write; raise; end; Sess.Impl.Lock.Release_Write; end Set_Attribute; -- ------------------------------ -- Removes the object bound with the specified name from this session. -- If the session does not have an object bound with the specified name, -- this method does nothing. -- ------------------------------ procedure Remove_Attribute (Sess : in out Session; Name : in String) is begin Set_Attribute (Sess, Name, EL.Objects.Null_Object); end Remove_Attribute; -- ------------------------------ -- Gets the principal that authenticated to the session. -- Returns null if there is no principal authenticated. -- ------------------------------ function Get_Principal (Sess : in Session) return ASF.Principals.Principal_Access is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; end if; return Sess.Impl.Principal; end Get_Principal; -- ------------------------------ -- Sets the principal associated with the session. -- ------------------------------ procedure Set_Principal (Sess : in out Session; Principal : in ASF.Principals.Principal_Access) is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; end if; Sess.Impl.Principal := Principal; end Set_Principal; -- ------------------------------ -- Invalidates this session then unbinds any objects bound to it. -- ------------------------------ procedure Invalidate (Sess : in out Session) is begin if Sess.Impl /= null then Sess.Impl.Is_Active := False; Finalize (Sess); end if; end Invalidate; -- ------------------------------ -- Adjust (increment) the session record reference counter. -- ------------------------------ overriding procedure Adjust (Object : in out Session) is begin if Object.Impl /= null then Util.Concurrent.Counters.Increment (Object.Impl.Ref_Counter); end if; end Adjust; procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record'Class, Name => Session_Record_Access); procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Principals.Principal'Class, Name => ASF.Principals.Principal_Access); -- ------------------------------ -- Decrement the session record reference counter and free the session record -- if this was the last session reference. -- ------------------------------ overriding procedure Finalize (Object : in out Session) is Release : Boolean; begin if Object.Impl /= null then Util.Concurrent.Counters.Decrement (Object.Impl.Ref_Counter, Release); if Release then Free (Object.Impl.Principal); Free (Object.Impl); else Object.Impl := null; end if; end if; end Finalize; overriding procedure Finalize (Object : in out Session_Record) is begin Free (Object.Id); end Finalize; end ASF.Sessions;
-- Storage_Array_To_Hex_String -- This is a simple conversion routine for test or example routines -- Copyright (c) 2015, James Humphry - see LICENSE file for details with System.Storage_Elements; function Storage_Array_To_Hex_String(X : System.Storage_Elements.Storage_Array) return String is use System.Storage_Elements; Hex_Digits : constant String := "0123456789ABCDEF"; Output : String(1 .. X'Length * 3); Byte : Storage_Element; begin -- This compile-time check is useful for GNAT, but in GNATprove it currently -- just generates a warning that it can not yet be proved correct. pragma Warnings (GNATprove, Off, "Compile_Time_Error"); pragma Compile_Time_Error ((Character'Size /= Storage_Element'Size), "Character and Storage_Element types are different sizes!"); pragma Warnings (GNATprove, On, "Compile_Time_Error"); for I in 1.. X'Length loop Byte := X(Storage_Offset(I) + X'First - 1); Output((I-1)*3 + 1 .. (I-1)*3 + 3) := (Hex_Digits(Integer(Byte / 16) + 1), Hex_Digits(Integer(Byte and 15) + 1), ','); end loop; return Output(Output'First..Output'Last - 1); end Storage_Array_To_Hex_String;
with Ada.Unchecked_Deallocation; package body Registre is procedure Initialiser (Registre : out T_Registre) is begin Registre := (others => null); end Initialiser; function Hash (Cle : Integer) return Integer is begin return Cle mod Modulo; end Hash; function Est_Vide (Registre : T_Registre) return Boolean is begin for I in Registre'Range loop if Registre (I) /= null then return False; end if; end loop; return True; end Est_Vide; -- Renvoie vrai si la clé est presente dans le registre. function Existe (Registre : T_Registre; Cle : Integer) return Boolean is Pointeur : T_Pointeur_Sur_Maillon; begin Pointeur := Registre (Hash (Cle)); while Pointeur /= null loop if Pointeur.all.Cle = Cle then return True; end if; Pointeur := Pointeur.all.Suivant; end loop; return False; end Existe; procedure Attribuer (Registre : in out T_Registre; Cle : in Integer; Element : in T_Element) is Pointeur : T_Pointeur_Sur_Maillon; begin if Registre (Hash (Cle)) = null then Pointeur := new T_Maillon; Pointeur.all := (Cle, Element, null); Registre (Hash (Cle)) := Pointeur; else Pointeur := Registre (Hash (Cle)); while Pointeur.all.Suivant /= null loop if Pointeur.all.Cle = Cle then Pointeur.all.Element := Element; return; end if; Pointeur := Pointeur.all.Suivant; end loop; if Pointeur.all.Cle = Cle then Pointeur.all.Element := Element; else Pointeur.all.Suivant := new T_Maillon; Pointeur.all.Suivant.all := (Cle, Element, null); end if; end if; end Attribuer; function Acceder (Registre : T_Registre; Cle : Integer) return T_Element is Pointeur : T_Pointeur_Sur_Maillon; begin Pointeur := Registre (Hash (Cle)); while Pointeur /= null loop if Pointeur.all.Cle = Cle then return Pointeur.all.Element; end if; Pointeur := Pointeur.all.Suivant; end loop; raise Cle_Absente_Exception; end Acceder; procedure Appliquer_Sur_Tous (Registre : in T_Registre) is procedure Appliquer_Sur_Maillon (Pointeur : in T_Pointeur_Sur_Maillon) is begin if Pointeur /= null then P (Pointeur.all.Cle, Pointeur.all.Element); Appliquer_Sur_Maillon (Pointeur.all.Suivant); end if; end Appliquer_Sur_Maillon; begin for I in Registre'Range loop Appliquer_Sur_Maillon (Registre (I)); end loop; end Appliquer_Sur_Tous; procedure Desallouer_Maillon is new Ada.Unchecked_Deallocation (T_Maillon, T_Pointeur_Sur_Maillon); procedure Supprimer (Registre : in out T_Registre; Cle : in Integer) is Pointeur : T_Pointeur_Sur_Maillon; Ancien : T_Pointeur_Sur_Maillon; begin if Registre (Hash (Cle)) /= null then Pointeur := Registre (Hash (Cle)); if Pointeur.all.Cle = Cle then Registre (Hash (Cle)) := Pointeur.all.Suivant; Desallouer_Maillon (Pointeur); return; end if; while Pointeur.all.Suivant /= null loop if Pointeur.all.Suivant.all.Cle = Cle then Ancien := Pointeur.all.Suivant; Pointeur.all.Suivant := Pointeur.all.Suivant.all.Suivant; Desallouer_Maillon (Ancien); return; end if; Pointeur := Pointeur.all.Suivant; end loop; end if; end Supprimer; procedure Supprimer_Maillons (Pointeur : in out T_Pointeur_Sur_Maillon) is begin if Pointeur /= null then Supprimer_Maillons (Pointeur.all.Suivant); end if; Desallouer_Maillon (Pointeur); end Supprimer_Maillons; procedure Detruire (Registre : in out T_Registre) is begin for I in Registre'Range loop Supprimer_Maillons (Registre (I)); end loop; end Detruire; end Registre;
pragma Task_Dispatching_Policy(FIFO_Within_Priorities); with Ada.Text_IO; use Ada.Text_IO; with Ada.Real_Time; use Ada.Real_Time; procedure overloaddetection is package Duration_IO is new Ada.Text_IO.Fixed_IO(Duration); package Int_IO is new Ada.Text_IO.Integer_IO(Integer); -------- function F(N : Integer) return Integer; function F(N : Integer) return Integer is X : Integer := 0; begin for Index in 1..N loop for I in 1..5000000 loop X := I; end loop; end loop; return X; end F; -------- Start : Time; Dummy : Integer; task type T(Period : Integer; ExecutionTime : Integer) is pragma Priority(20 - Period); -- priority corresponds to period length end; task body T is Next : Time; begin Next := Start; loop Next := Next + Milliseconds(22*Period); --loop takes about 23ms to finish --- Some dummy function Dummy := F(ExecutionTime); --- Duration_IO.Put(To_Duration(Clock - Start), 3, 3); -- print task execution duration Put(" : "); Int_IO.Put(Period, 2); -- print the priority Put_Line(""); delay until Next; end loop; end T; task type WDT(Period : Integer) is pragma Priority(25); entry tick(isok: in Integer); end; task body WDT is --watchdog timer task Next : Time; ok : Integer; begin Next := Clock; ok := 1; loop select accept tick(isok : in Integer) do --check for tick ok := 1; end tick; else Put_Line("OVERLOAD!!!!"); end select; Next := Next + Milliseconds(Period*22); delay until Next; end loop; end WDT; watchdog : WDT(36); --36 for 4th task Task type D(Period : Integer) is --overloaddetection task pragma Priority(1); end; task body D is Next : Time; begin Next := Start; loop Next := Next + Milliseconds(22*Period); -- period in multiple of 22ms watchdog.tick(1); --give task Duration_IO.Put(To_Duration(Clock - Start), 3, 3); -- print task execution duration Put(" : "); Int_IO.Put(12, 2); -- print ID=12 Put_Line(""); delay until Next; end loop; end D; Detector: D(36); --36 for 4th task -- Example Tasks Task_1 : T(3, 1); Task_2 : T(4, 1); Task_3 : T(6, 1); Task_4 : T(9, 2); begin Start := Clock; null; end overloaddetection;
-- C96005A.ADA -- Grant of Unlimited Rights -- -- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687, -- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained -- unlimited rights in the software and documentation contained herein. -- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making -- this public release, the Government intends to confer upon all -- recipients unlimited rights equal to those held by the Government. -- These rights include rights to use, duplicate, release or disclose the -- released technical data and computer software in whole or in part, in -- any manner and for any purpose whatsoever, and to have or permit others -- to do so. -- -- DISCLAIMER -- -- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR -- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED -- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE -- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE -- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A -- PARTICULAR PURPOSE OF SAID MATERIAL. --* -- CHECK THE CORRECTNESS OF THE ADDITION AND SUBTRACTION FUNCTIONS IN -- THE PREDEFINED PACKAGE CALENDAR, AND APPROPRIATE EXCEPTION HANDLING. -- SPECIFICALLY, -- (A) CHECK THAT ADDITION AND SUBTRACTION OPERATORS WORK CORRECTLY ON -- VALUES OF TYPE TIME. -- CPP 8/16/84 WITH CALENDAR; USE CALENDAR; WITH REPORT; USE REPORT; -- WITH TEXT_IO; USE TEXT_IO; PROCEDURE C96005A IS -- PACKAGE DURATION_IO IS NEW FIXED_IO (DURATION); -- USE DURATION_IO; BEGIN TEST ("C96005A", "CHECK THAT THE ADDITION AND SUBTRACTION " & "FUNCTIONS FOR VALUES OF TYPE TIME WORK CORRECTLY"); ----------------------------------------------- BEGIN -- (A) -- ADDITION TESTS FOLLOW. DECLARE NOW, NEW_TIME : TIME; INCREMENT : DURATION := 1.0; BEGIN NOW := TIME_OF (1984, 8, 13, 0.0); NEW_TIME := NOW + INCREMENT; IF NEW_TIME /= TIME_OF (1984, 8, 13, 1.0) THEN FAILED ("SUM OF TIMES IS INCORRECT - (A)1"); END IF; END; DECLARE NOW, NEW_TIME : TIME; INCREMENT : DURATION := 1.0; BEGIN NOW := TIME_OF (1984, 8, 13, 0.0); NEW_TIME := INCREMENT + NOW; IF NEW_TIME /= TIME_OF (1984, 8, 13, 1.0) THEN FAILED ("SUM OF TIMES IS INCORRECT - (A)2"); END IF; END; DECLARE NOW, NEW_TIME : TIME; INCREMENT : DURATION := 1.0; BEGIN NOW := TIME_OF (1984, 8, 13, 0.0); NEW_TIME := "+"(INCREMENT, NOW); IF NEW_TIME /= TIME_OF (1984, 8, 13, 1.0) THEN FAILED ("SUM OF TIMES IS INCORRECT - (A)3"); END IF; END; DECLARE NOW, NEW_TIME : TIME; INCREMENT : DURATION := 1.0; BEGIN NOW := TIME_OF (1984, 8, 13, 0.0); NEW_TIME := "+"(LEFT => NOW, RIGHT => INCREMENT); IF NEW_TIME /= TIME_OF (1984, 8, 13, 1.0) THEN FAILED ("SUM OF TIMES IS INCORRECT - (A)4"); END IF; END; -- SUBTRACTION TESTS FOLLOW. DECLARE NOW, ONCE : TIME; DIFFERENCE : DURATION; BEGIN NOW := TIME_OF (1984, 8, 13, 45_000.0); ONCE := TIME_OF (1984, 8, 12, 45_000.0); DIFFERENCE := NOW - ONCE; IF DIFFERENCE /= 86_400.0 THEN FAILED ("DIFFERENCE OF TIMES IS INCORRECT - (A)1"); -- COMMENT ("DIFFERENCE YIELDS: "); -- PUT (DIFFERENCE); END IF; END; DECLARE -- TIMES IN DIFFERENT MONTHS. NOW, ONCE : TIME; DIFFERENCE : DURATION; BEGIN NOW := TIME_OF (1984, 8, IDENT_INT(1), 60.0); ONCE := TIME_OF (1984, 7, 31, 86_399.0); DIFFERENCE := "-"(NOW, ONCE); IF DIFFERENCE /= 61.0 THEN FAILED ("DIFFERENCE OF TIMES IS INCORRECT - (A)2"); -- COMMENT ("DIFFERENCE YIELDS: "); -- PUT (DIFFERENCE); END IF; END; DECLARE -- TIMES IN DIFFERENT YEARS. NOW, AFTER : TIME; DIFFERENCE : DURATION; BEGIN NOW := TIME_OF (IDENT_INT(1999), 12, 31, 86_399.0); AFTER := TIME_OF (2000, 1, 1, 1.0); DIFFERENCE := "-"(LEFT => AFTER, RIGHT => NOW); IF DIFFERENCE /= 2.0 THEN FAILED ("DIFFERENCE OF TIMES IS INCORRECT - (A)3"); -- COMMENT ("DIFFERENCE YIELDS: "); -- PUT (DIFFERENCE); END IF; END; DECLARE -- TIMES IN A LEAP YEAR. NOW, LEAP : TIME; DIFFERENCE : DURATION; BEGIN NOW := TIME_OF (1984, 3, 1); LEAP := TIME_OF (1984, 2, 29, 86_399.0); DIFFERENCE := NOW - LEAP; IF DIFFERENCE /= 1.0 THEN FAILED ("DIFFERENCE OF TIMES IS INCORRECT - (A)4"); -- COMMENT ("DIFFERENCE YIELDS: "); -- PUT (DIFFERENCE); END IF; END; DECLARE -- TIMES IN A NON-LEAP YEAR. NOW, NON_LEAP : TIME; DIFFERENCE : DURATION; BEGIN NOW := TIME_OF (1983, 3, 1); NON_LEAP := TIME_OF (1983, 2, 28, 86_399.0); DIFFERENCE := NOW - NON_LEAP; IF DIFFERENCE /= 1.0 THEN FAILED ("DIFFERENCE OF TIMES IS INCORRECT - (A)5"); -- COMMENT ("DIFFERENCE YIELDS: "); -- PUT (DIFFERENCE); END IF; END; -- SUBTRACTION TESTS FOLLOW: TIME - DURATION. DECLARE NOW, NEW_TIME : TIME; INCREMENT : DURATION := 1.0; BEGIN NOW := TIME_OF (1984, 8, 13, 0.0); NEW_TIME := NOW - INCREMENT; IF NEW_TIME /= TIME_OF (1984, 8, 12, 86_399.0) THEN FAILED ("DIFFERENCE OF TIME AND DURATION IS " & "INCORRECT - (A)6"); END IF; END; DECLARE NOW, NEW_TIME : TIME; INCREMENT : DURATION := 1.0; BEGIN NOW := TIME_OF (1984, 8, 1, 0.0); NEW_TIME := NOW - INCREMENT; IF NEW_TIME /= TIME_OF (1984, 7, 31, 86_399.0) THEN FAILED ("DIFFERENCE OF TIME AND DURATION IS " & "INCORRECT - (A)7"); END IF; END; DECLARE NOW, NEW_TIME : TIME; INCREMENT : DURATION := 1.0; BEGIN NOW := TIME_OF (1984, 8, 1, 0.0); NEW_TIME := "-"(LEFT => NOW, RIGHT => INCREMENT); IF NEW_TIME /= TIME_OF (1984, 7, 31, 86_399.0) THEN FAILED ("DIFFERENCE OF TIME AND DURATION IS " & "INCORRECT - (A)8"); END IF; END; DECLARE NOW, NEW_TIME : TIME; INCREMENT : DURATION := 1.0; BEGIN NOW := TIME_OF (1984, 8, 1, 0.0); NEW_TIME := "-"(NOW, INCREMENT); IF NEW_TIME /= TIME_OF (1984, 7, 31, 86_399.0) THEN FAILED ("DIFFERENCE OF TIME AND DURATION IS " & "INCORRECT - (A)7"); END IF; END; END; -- (A) ----------------------------------------------- RESULT; END C96005A;
-- { dg-do compile } -- { dg-options "-gnatws" } with elab1; procedure elab2 is A : elab1.My_Rec; begin null; end;
with AUnit; use AUnit; with AUnit.Test_Cases; use AUnit.Test_Cases; package Test_String_Utils is type String_Utils_Test_Case is new Test_Case with null record; overriding procedure Register_Tests (T : in out String_Utils_Test_Case); -- Register routines to be run overriding function Name (T : String_Utils_Test_Case) return Message_String; -- Provide name identifying the test case end Test_String_Utils;
-- AOC 2020, Day 24 package Day is function count_tiles(filename : in String) return Natural; function evolve_tiles(filename : in String; steps : in Natural) return Natural; end Day;
package body Rejuvenation.Finder is -- Public: Find Node_Kind -------- function Find (Node : Ada_Node'Class; Predicate : not null access function (Node : Ada_Node'Class) return Boolean) return Node_List.Vector is (Find_Predicate (Node, Predicate, Into)); function Find_Non_Contained (Node : Ada_Node'Class; Predicate : not null access function (Node : Ada_Node'Class) return Boolean) return Node_List.Vector is (Find_Predicate (Node, Predicate, Over)); function Find (Node : Ada_Node'Class; Node_Kind : Ada_Node_Kind_Type) return Node_List.Vector is function Predicate (Node : Ada_Node'Class) return Boolean; function Predicate (Node : Ada_Node'Class) return Boolean is begin return Node.Kind = Node_Kind; end Predicate; begin return Find_Predicate (Node, Predicate'Access, Into); end Find; function Find_Non_Contained (Node : Ada_Node'Class; Node_Kind : Ada_Node_Kind_Type) return Node_List.Vector is function Predicate (Node : Ada_Node'Class) return Boolean; function Predicate (Node : Ada_Node'Class) return Boolean is begin return Node.Kind = Node_Kind; end Predicate; begin return Find_Predicate (Node, Predicate'Access, Over); end Find_Non_Contained; function Find_First (Node : Ada_Node'Class; Node_Kind : Ada_Node_Kind_Type) return Ada_Node is function Predicate (Node : Ada_Node'Class) return Boolean; function Predicate (Node : Ada_Node'Class) return Boolean is begin return Node.Kind = Node_Kind; end Predicate; use Node_List; Results : constant Node_List.Vector := Find_Predicate (Node, Predicate'Access, Stop); begin return (if Results.Is_Empty then No_Ada_Node else Element (Results.First)); end Find_First; function Find_Sub_List (Node : Ada_Node'Class; Node_Kinds : Node_Kind_Type_Array) return Node_List_List.Vector is begin return Find_NK_Sub_List (Node, Node_Kinds); end Find_Sub_List; -- Public: Find Match_Pattern -------- function Find_Full (Node : Ada_Node'Class; Find_Pattern : Pattern) return Match_Pattern_List.Vector is begin return Find_MP (Node, Find_Pattern.As_Ada_Node, Into); end Find_Full; function Find_Non_Contained_Full (Node : Ada_Node'Class; Find_Pattern : Pattern) return Match_Pattern_List.Vector is begin return Find_MP (Node, Find_Pattern.As_Ada_Node, Over); end Find_Non_Contained_Full; function Find_First_Full (Node : Ada_Node'Class; Find_Pattern : Pattern; Result : out Match_Pattern) return Boolean is use Match_Pattern_List; Results : constant Match_Pattern_List.Vector := Find_MP (Node, Find_Pattern.As_Ada_Node, Stop); begin if Results.Is_Empty then return False; else Result := Element (Results.First); return True; end if; end Find_First_Full; function Find_Sub_List (Node : Ada_Node'Class; Find_Pattern : Pattern; Next : Containment) return Match_Pattern_List.Vector; function Find_Sub_List (Node : Ada_Node'Class; Find_Pattern : Pattern; Next : Containment) return Match_Pattern_List.Vector is Find_Node : constant Ada_Node := Find_Pattern.As_Ada_Node; begin if Find_Node.Kind in Ada_Ada_List then return Find_MP_Sub_List (Node, Find_Node.Children, Next); else raise Pattern_Is_No_List_Exception; end if; end Find_Sub_List; function Find_Sub_List (Node : Ada_Node'Class; Find_Pattern : Pattern) return Match_Pattern_List.Vector is (Find_Sub_List (Node, Find_Pattern, Contained)); function Find_Non_Contained_Sub_List (Node : Ada_Node'Class; Find_Pattern : Pattern) return Match_Pattern_List.Vector is (Find_Sub_List (Node, Find_Pattern, Non_Contained)); function Find_Full (Node : Ada_Node'Class; Find_Patterns : Pattern_Array) return Match_Pattern_List.Vector is Result : Match_Pattern_List.Vector; begin for Find_Pattern of Find_Patterns loop Result.Append (Find_Full (Node, Find_Pattern)); end loop; return Result; end Find_Full; -- Private -------- function Find_Predicate (Node : Ada_Node'Class; Predicate : not null access function (Node : Ada_Node'Class) return Boolean; Next : Visit_Status) return Node_List.Vector is Result : Node_List.Vector; function Visit (Node : Ada_Node'Class) return Visit_Status; function Visit (Node : Ada_Node'Class) return Visit_Status is begin if Predicate (Node) then Result.Append (Ada_Node (Node)); -- TODO: look up which was prefer Node.As_Ada_Node or this return Next; else return Into; end if; end Visit; begin Node.Traverse (Visit'Access); return Result; end Find_Predicate; function Find_MP (Node : Ada_Node'Class; Pattern : Ada_Node; Next : Visit_Status) return Match_Pattern_List.Vector is Result : Match_Pattern_List.Vector; function Visit (Node : Ada_Node'Class) return Visit_Status; function Visit (Node : Ada_Node'Class) return Visit_Status is MP : Match_Pattern; Success : constant Boolean := MP.Match_Full (Pattern, Ada_Node (Node)); begin if Success then Result.Append (MP); return Next; else return Into; end if; end Visit; begin Node.Traverse (Visit'Access); return Result; end Find_MP; function Find_NK_Sub_List (Node : Ada_Node'Class; Node_Kinds : Node_Kind_Type_Array) return Node_List_List.Vector is Result : Node_List_List.Vector; function Visit (Node : Ada_Node'Class) return Visit_Status; function Visit (Node : Ada_Node'Class) return Visit_Status is begin if Node.Kind in Ada_Ada_List then for Node_Index in Node.Children'First .. (Node.Children'Last - Node_Kinds'Last) loop declare Success : Boolean; Nodes : Node_List.Vector; begin Success := True; for Kind_Index in Node_Kinds'Range loop -- array range starts at 0 if Node.Child (Node_Index + Kind_Index).Kind = Node_Kinds (Kind_Index) then Nodes.Append (Node.Child (Node_Index + Kind_Index)); else Success := False; end if; end loop; if Success then Result.Append (Nodes); end if; end; end loop; end if; return Into; end Visit; begin Node.Traverse (Visit'Access); return Result; end Find_NK_Sub_List; function Find_MP_Sub_List (Node : Ada_Node'Class; Pattern : Ada_Node_Array; Next : Containment) return Match_Pattern_List.Vector -- Special cases: -- We do not allow matches to contain overlapping nodes -- E.g. When the pattern $S_Stmt1; $S_Stmt2; -- is used to find a sublist in the list of nodes "A; B; C; D;" -- We find "A; B;" and "C; D;" -- Hence "B; C;" is NOT found -- -- Non-Contained: -- Don't go into matches, but when no match go into! is Result : Match_Pattern_List.Vector; function Visit (Node : Ada_Node'Class) return Visit_Status; function Visit (Node : Ada_Node'Class) return Visit_Status is begin if Node.Kind in Ada_Ada_List then declare Upperbound : constant Integer := Node.Last_Child_Index - Pattern'Length + 1; -- last possible index / start position to fit the whole pattern -- into remaining tail of the list Skip : Natural := Node.First_Child_Index - 1; -- skip counter to prevent overlapping matches begin for Node_Index in Node.Children'Range loop if Node_Index > Skip and then Node_Index <= Upperbound then declare MP : Match_Pattern; Success : constant Boolean := MP.Match_Prefix (Pattern, Node.Children, Node_Index); begin if Success then Result.Append (MP); Skip := Node_Index + Pattern'Length - 1; end if; end; end if; -- Do we need to vist this node? if Next = Contained or else Node_Index > Skip then Node.Child (Node_Index).Traverse (Visit'Access); end if; end loop; return Over; end; end if; return Into; end Visit; begin Node.Traverse (Visit'Access); return Result; end Find_MP_Sub_List; end Rejuvenation.Finder;
-- Copyright (c) 2017 Maxim Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- private package Ada_Pretty.Units is type Compilation_Unit is new Node with private; function New_Compilation_Unit (Root : not null Node_Access; Clauses : Node_Access := null; License : League.Strings.Universal_String) return Node'Class; function New_Subunit (Parent_Name : not null Node_Access; Proper_Body : not null Node_Access) return Node'Class; private type Compilation_Unit is new Node with record Root : not null Node_Access; Clauses : Node_Access; License : League.Strings.Universal_String; end record; overriding function Document (Self : Compilation_Unit; Printer : not null access League.Pretty_Printers.Printer'Class; Pad : Natural) return League.Pretty_Printers.Document; type Subunit is new Node with record Parent_Name : not null Node_Access; Proper_Body : not null Node_Access; end record; overriding function Document (Self : Subunit; Printer : not null access League.Pretty_Printers.Printer'Class; Pad : Natural) return League.Pretty_Printers.Document; end Ada_Pretty.Units;