content
stringlengths
23
1.05M
-- ----------------------------------------------------------------------------- -- smk, the smart make -- © 2018 Lionel Draghi <lionel.draghi@free.fr> -- SPDX-License-Identifier: APSL-2.0 -- ----------------------------------------------------------------------------- -- 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. -- ----------------------------------------------------------------------------- -- ----------------------------------------------------------------------------- -- Procedure: Smk.Main body -- -- Implementation Notes: -- -- Portability Issues: -- -- Anticipated Changes: -- ----------------------------------------------------------------------------- with Smk.IO; with Smk.Makefiles; with Smk.Run_Files; with Smk.Settings; use Smk.Settings; with Ada.Calendar; with Ada.Command_Line; with Ada.Directories; procedure Smk.Main is -- Debug : constant Boolean := True; -- -------------------------------------------------------------------------- procedure Put_Help is separate; procedure Put_Error (Msg : in String := ""; With_Help : in Boolean := False) is separate; -- Put_Line Utilities -- -------------------------------------------------------------------------- procedure Analyze_Cmd_Line is separate; -- Cmd line options are then available in the Settings package. -- -------------------------------------------------------------------------- procedure Analyze_Run (-- Previous_Run_Time : in Ada.Calendar.Time; Source_Files : out Run_Files.File_Lists.Map; Target_Files : out Run_Files.File_Lists.Map) is separate; -- Based on the run log file (that is the strace output), and the run time, -- it identifies Source and Target files. -- Thanks to strace -y option, file names appears clearly between <> -- in the strace output. -- This output is filtered to keep only those file names, and pushed to -- Source_Files list output parameter if the file's time tag is older than -- the execution time, and to Target_Files list otherwise. -- -------------------------------------------------------------------------- function Must_Be_Run (Command : Run_Files.Command_Lines; Previous_Run : in out Run_Files.Run_Lists.Map) return Boolean is separate; -- This function return True if one of the following condition is met: -- 1. the --always-make option is set; -- 2. the provided Command is not found in the previous run; -- 3. one the files identified as Target during the previous run -- is missing; -- 4. one the files identified as Source during the previous run -- has been updated after the previous run. -- -------------------------------------------------------------------------- procedure Run_Command (E : in out Makefiles.Makefile_Entry; The_Run_List : in out Run_Files.Run_Lists.Map) -- Was_Run : out Boolean) is separate; -- Run_Command is in charge of spawning the Cmd (using strace), -- and analysing the strace log file. -- The_Run_List is updated with this run results -- -------------------------------------------------------------------------- procedure Clean_Files is use Ada.Directories; Search : Search_Type; File : Directory_Entry_Type; begin Start_Search (Search, Directory => ".", Pattern => Smk_File_Prefix & "*", Filter => (Ordinary_File => True, others => False)); while More_Entries (Search) loop Get_Next_Entry (Search, File); IO.Put_Line ("Deleting " & Simple_Name (File)); Delete_File (Simple_Name (File)); end loop; end Clean_Files; The_Makefile : Makefiles.Makefile; The_Run_List : Run_Files.Run_Lists.Map; begin -- -------------------------------------------------------------------------- Analyze_Cmd_Line; if IO.Some_Error then -- If some error occurs during command line analysis, stop here. Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); return; end if; if Clean_Smk_Files then Clean_Files; end if; if Makefile_Name = "" then return; end if; -- Nothing to do : useful for, e.g. -h or -v options -- Fixme: do we want -ls or -lm option without Makefile given that just -- apply to.smk.* files found in the directory? -- 1. Current Makefile analysis -- ---------------------------- Makefiles.Analyze (Makefile_Name, The_Makefile); if List_Makefile then -- -lm option Makefiles.Dump (The_Makefile); return; end if; -- 2. Load previous run -- -------------------- if Run_Files.Saved_Run_Found then The_Run_List := Run_Files.Get_Saved_Run; else The_Run_List := Run_Files.Run_Lists.Empty_Map; end if; if List_Saved_Run then -- -ls Option Run_Files.Dump (The_Run_List, Filter_Sytem_Files => True); return; end if; -- 3. Run commands found in the Makefile -- ------------------------------------- declare A_Cmd_Was_Run : Boolean := False; -- use Run_Files; begin Outer : for I in 1 .. The_Makefile.Entries.Length loop -- This double loop is a pragmatic way to avoid a more complex -- dependies analysis. -- -- Why: build command may appears not ordered in the Makefile. -- What should we do if a command invalidate another one that was -- before in The_Makefile.Entries? -- Exemple : -- 1. gcc -o hello hello.o main.o -- 2. gcc -o hello.o -c hello.c -- 3. gcc -o main.o -c main.c -- If main.c is changed, a single loop approach will re-run 3. and -- exit. -- The double loop will re-loop, and run 1. -- If during the inner loop, nothing is run, then OK, -- we exit the outer loop. -- -- The the worst order will cause as many loop as -- The_Makefile.Entries. Otherwise, it means that there is a circular -- dependency. -- To avoid infinite recursion in that case, the outer loop is -- limited to the worst case, that is The_Makefile.Entries.Length. A_Cmd_Was_Run := False; Inner : for E of The_Makefile.Entries loop -- IO.Put_Line (Positive'Image (Positive (I)) & " " & (+E.Command) -- & " Already_Run = " -- & Boolean'Image (E.Already_Run)); if not E.Already_Run then Run_Command (E, The_Run_List); if IO.Some_Error and not Ignore_Errors then exit Outer; end if; A_Cmd_Was_Run := E.Already_Run; end if; end loop Inner; -- IO.Put_Line (""); -- Naive loop aproach : each time a cmd is run, and potentialy -- invalidate another cmd, we restart the whole cmd list, until -- no command is re-run. exit Outer when not A_Cmd_Was_Run; end loop Outer; end; -- 4. Save the updated run -- ----------------------- Run_Files.Save_Run (The_Run_List); if IO.Some_Error then Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); return; end if; end Smk.Main;
package Private2_Pkg is type Rec2 (D : Natural) is private; private type Rec1 (D : Natural) is null record; type Rec2 (D : Natural) is new Rec1 (D); end Private2_Pkg;
----------------------------------------------------------------------- -- are-generator-c -- Generator for C/C++ -- Copyright (C) 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.Text_IO; with Ada.Calendar.Conversions; with Interfaces.C; with Util.Log.Loggers; package body Are.Generator.C is use Ada.Text_IO; use Ada.Strings.Unbounded; function Get_Content_Type (Resource : in Are.Resource_Type; Context : in Are.Context_Type'Class) return String; function Get_Type_Name (Prefix : in String; Resource : in Are.Resource_Type; Context : in Are.Context_Type'Class) return String; function To_File_Name (Name : in String) return String; function To_C_Name (Prefix : in String; Name : in String) return String; function To_Define_Name (Name : in String; Postfix : in String := "_H_") return String; function To_Prefix_Name (Name : in String) return String; -- Generate the resource declaration list. procedure Generate_Resource_Declarations (Resource : in Are.Resource_Type; Into : in out Ada.Text_IO.File_Type; Content_Name : in String; Content_Type : in String; Var_Prefix : in String); -- Generate the resource content definition. procedure Generate_Resource_Contents (Resource : in out Are.Resource_Type; Into : in out Ada.Text_IO.File_Type); Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Are.Generator.C"); -- ------------------------------ -- Generate the C/C++ code for the resources that have been collected. -- ------------------------------ overriding procedure Generate (Generator : in out Generator_Type; Resources : in Resource_List; Context : in out Are.Context_Type'Class) is Resource : Resource_Access := Resources.Head; begin while Resource /= null loop if Context.Name_Index then Resource.Collect_Names (Context.Ignore_Case, Generator.Names); end if; Generator.Generate_Header (Resource.all, Context); Generator.Generate_Source (Resource.all, Context); Generator.Names.Clear; Resource := Resource.Next; end loop; end Generate; function Get_Content_Type (Resource : in Are.Resource_Type; Context : in Are.Context_Type'Class) return String is begin if Resource.Format = R_LINES then return Resource.Get_Content_Type_Name (Context, "const char* const*"); end if; if Resource.Format = R_STRING then return Resource.Get_Content_Type_Name (Context, "const char*"); end if; return Resource.Get_Content_Type_Name (Context, "const unsigned char *"); end Get_Content_Type; function Get_Type_Name (Prefix : in String; Resource : in Are.Resource_Type; Context : in Are.Context_Type'Class) return String is Type_Name : constant String := Resource.Get_Type_Name (Context, Prefix & "_content"); begin if Util.Strings.Index (Type_Name, ' ') > 0 then return Type_Name; else return "struct " & Type_Name; end if; end Get_Type_Name; -- ------------------------------ -- Given a package name, return the file name that correspond. -- ------------------------------ function To_File_Name (Name : in String) return String is Result : String (Name'Range); begin for J in Name'Range loop if Name (J) in 'A' .. 'Z' then Result (J) := Character'Val (Character'Pos (Name (J)) - Character'Pos ('A') + Character'Pos ('a')); elsif Name (J) = '.' then Result (J) := '-'; else Result (J) := Name (J); end if; end loop; return Result; end To_File_Name; -- ------------------------------ -- Given a package name, return the file name that correspond. -- ------------------------------ function To_Define_Name (Name : in String; Postfix : in String := "_H_") return String is Result : String (Name'Range); begin for J in Name'Range loop if Name (J) in 'a' .. 'z' then Result (J) := Character'Val (Character'Pos (Name (J)) - Character'Pos ('a') + Character'Pos ('A')); elsif Name (J) = '.' or Name (J) = ' ' then Result (J) := '_'; else Result (J) := Name (J); end if; end loop; return "_" & Result & Postfix; end To_Define_Name; -- ------------------------------ -- Given a package name, return a prefix to use for global variables. -- ------------------------------ function To_Prefix_Name (Name : in String) return String is Result : String (Name'Range); begin for J in Name'Range loop if Name (J) in 'A' .. 'Z' then Result (J) := Character'Val (Character'Pos (Name (J)) - Character'Pos ('A') + Character'Pos ('a')); elsif Name (J) = '.' or Name (J) = ' ' then Result (J) := '_'; else Result (J) := Name (J); end if; end loop; return Result; end To_Prefix_Name; function To_C_Name (Prefix : in String; Name : in String) return String is Result : Unbounded_String; begin Append (Result, Prefix); for C of Name loop if C = '-' or C = '.' then Append (Result, '_'); elsif C >= 'a' and C <= 'z' then Append (Result, C); elsif C >= 'A' and C <= 'Z' then Append (Result, C); elsif C >= '0' and C <= '9' then Append (Result, C); end if; end loop; return To_String (Result); end To_C_Name; -- ------------------------------ -- Generate the resource declaration list. -- ------------------------------ procedure Generate_Resource_Declarations (Resource : in Are.Resource_Type; Into : in out Ada.Text_IO.File_Type; Content_Name : in String; Content_Type : in String; Var_Prefix : in String) is Remain : Natural := Natural (Resource.Files.Length); begin Put (Into, "enum"); Put_Line (Into, " {"); for File in Resource.Files.Iterate loop Put (Into, " "); Put (Into, To_C_Name (Var_Prefix, File_Maps.Key (File))); Remain := Remain - 1; if Remain /= 0 then Put_Line (Into, ","); else New_Line (Into); end if; end loop; Put_Line (Into, "};"); New_Line (Into); Put (Into, "extern const "); Put (Into, Content_Type); Put (Into, " "); Put (Into, Content_Name); Put_Line (Into, "[];"); New_Line (Into); end Generate_Resource_Declarations; -- ------------------------------ -- Generate the resource content definition. -- ------------------------------ procedure Generate_Resource_Contents (Resource : in out Are.Resource_Type; Into : in out Ada.Text_IO.File_Type) is procedure Write_Binary (Name : in String; Content : in Are.File_Info); procedure Write_String (Content : in String); procedure Write_String (Name : in String; Content : in Are.File_Info); procedure Write_Lines (Name : in String; Content : in out Are.File_Info); procedure Write (File_Name : in String; Content : in out Are.File_Info); procedure Write_Binary (Name : in String; Content : in Are.File_Info) is Need_Sep : Boolean := False; Column : Natural := 0; begin Put (Into, "static const unsigned char "); Put (Into, Name); Put (Into, "[] = {"); if Content.Content = null or else Content.Content'Length = 0 then Put_Line (Into, "};"); elsif Content.Content'Length = 1 then Put (Into, Util.Strings.Image (Natural (Content.Content (Content.Content'First)))); Put_Line (Into, "};"); else New_Line (Into); Put (Into, " "); for C of Content.Content.all loop if Need_Sep then Put (Into, ","); Need_Sep := False; end if; if Column > 20 then New_Line (Into); Put (Into, " "); Column := 1; elsif Column > 0 then Put (Into, " "); end if; Put (Into, Util.Strings.Image (Natural (C))); Column := Column + 1; Need_Sep := True; end loop; New_Line (Into); Put_Line (Into, "};"); end if; New_Line (Into); end Write_Binary; procedure Write_String (Content : in String) is Need_Sep : Boolean := False; Column : Natural := 0; begin Column := 40; Put (Into, """"); for C of Content loop if Column > 80 then if not Need_Sep then Put (Into, """"); end if; New_Line (Into); Put (Into, " "); Column := 3; Need_Sep := True; end if; case C is when ASCII.CR => Put (Into, "\r"); Column := Column + 2; when ASCII.LF => Put (Into, "\n"); Column := Column + 2; when ASCII.HT => Put (Into, "\t"); Column := Column + 2; when '"' => Put (Into, "\"""); Column := Column + 2; when others => if Need_Sep then Put (Into, " """); Need_Sep := False; end if; Put (Into, C); end case; Column := Column + 1; end loop; if not Need_Sep then Put (Into, """"); end if; end Write_String; procedure Write_String (Name : in String; Content : in Are.File_Info) is begin Put (Into, "static const char "); Put (Into, Name); Put (Into, "[] = "); if Content.Content /= null and then Content.Content'Length > 0 then declare First : constant Natural := Natural (Content.Content'First); Last : constant Natural := Natural (Content.Content'Last); File_Content : String (First .. Last); for File_Content'Address use Content.Content.all'Address; begin Write_String (File_Content); end; else Put (Into, """"""); end if; Put_Line (Into, ";"); end Write_String; procedure Write_Lines (Name : in String; Content : in out Are.File_Info) is Lines : Util.Strings.Vectors.Vector; Count : Natural := 0; begin Are.Convert_To_Lines (Resource, Content, Lines); Put (Into, "static const char *const "); Put (Into, Name); Put (Into, "[] = {"); if Lines.Is_Empty then Put_Line (Into, "};"); else New_Line (Into); for Line of Lines loop if Count >= 1 then Put_Line (Into, ","); end if; Set_Col (Into, 3); Write_String (Line); Count := Count + 1; end loop; New_Line (Into); Put_Line (Into, "};"); end if; Content.Line_Count := Count; end Write_Lines; Index : Natural := 0; procedure Write (File_Name : in String; Content : in out Are.File_Info) is pragma Unreferenced (File_Name); Name : constant String := "C_" & Util.Strings.Image (Index); begin if Resource.Format = R_LINES then Write_Lines (Name, Content); elsif Resource.Format = R_STRING then Write_String (Name, Content); else Write_Binary (Name, Content); end if; end Write; begin for File in Resource.Files.Iterate loop Index := Index + 1; Resource.Files.Update_Element (File, Write'Access); New_Line (Into); end loop; end Generate_Resource_Contents; -- ------------------------------ -- Generate the package specification. -- ------------------------------ procedure Generate_Header (Generator : in out Generator_Type; Resource : in out Are.Resource_Type; Context : in out Are.Context_Type'Class) is pragma Unreferenced (Generator); Name : constant String := To_String (Resource.Name); Define : constant String := To_Define_Name (Name); Filename : constant String := To_File_Name (Name) & ".h"; Path : constant String := Context.Get_Output_Path (Filename); Prefix : constant String := To_Prefix_Name (Name); Def_Func : constant String := To_Prefix_Name (Name) & "_get_content"; Content_Name : constant String := Prefix & "_contents"; List_Names : constant String := Prefix & "_names"; Type_Name : constant String := Get_Type_Name (Prefix, Resource, Context); Content_Type : constant String := Get_Content_Type (Resource, Context); Func_Name : constant String := Resource.Get_Function_Name (Context, Def_Func); Type_Define : constant String := To_Define_Name (Type_Name, "_TYPE_"); File : Ada.Text_IO.File_Type; begin Log.Info ("Writing resource {0} in {1}", Name, Path); Ada.Text_IO.Create (File => File, Mode => Ada.Text_IO.Out_File, Name => Path); Put (File, "// "); Put_Line (File, Get_Title); Put (File, "#ifndef "); Put_Line (File, Define); Put (File, "#define "); Put_Line (File, Define); New_Line (File); Put_Line (File, "#include <time.h>"); New_Line (File); Put_Line (File, "#ifdef __cplusplus"); Put_Line (File, "extern ""C"" {"); Put_Line (File, "#endif"); New_Line (File); -- Declare the struct holding the data. if not Context.No_Type_Declaration then Log.Debug ("Writing struct {0} declaration", Type_Name); Put (File, "#ifndef "); Put_Line (File, Type_Define); Put (File, "#define "); Put_Line (File, Type_Define); New_Line (File); Put (File, Type_Name); Put_Line (File, " {"); Put (File, " "); Put (File, Content_Type); Put (File, " "); Put (File, Resource.Get_Member_Content_Name (Context, "content")); Put_Line (File, ";"); if Resource.Format = R_LINES then Put (File, " size_t "); Put (File, Resource.Get_Member_Length_Name (Context, "length")); Put_Line (File, ";"); else Put (File, " size_t "); Put (File, Resource.Get_Member_Length_Name (Context, "size")); Put_Line (File, ";"); Put (File, " time_t "); Put (File, Resource.Get_Member_Modtime_Name (Context, "modtime")); Put_Line (File, ";"); Put (File, " int "); Put (File, Resource.Get_Member_Format_Name (Context, "format")); Put_Line (File, ";"); end if; Put_Line (File, "};"); New_Line (File); Put_Line (File, "#endif"); New_Line (File); end if; if Context.List_Content then Put_Line (File, "// Sorted array of names composing the resource."); Put (File, "extern const char* const "); Put (File, List_Names); Put_Line (File, "[];"); Put (File, "static const int "); Put (File, List_Names); Put (File, "_length = "); Put (File, Util.Strings.Image (Natural (Resource.Files.Length))); Put_Line (File, ";"); New_Line (File); end if; if Context.Declare_Var then Generate_Resource_Declarations (Resource, File, Content_Name, Type_Name, Context.Var_Prefix.all); end if; if Context.Name_Index then Log.Debug ("Writing {0} declaration", Func_Name); Put_Line (File, "// Returns the data stream with the given name or null."); Put (File, "extern const "); Put (File, Type_Name); Put (File, "* "); Put (File, Func_Name); Put (File, "(const char* name);"); New_Line (File); New_Line (File); end if; Put_Line (File, "#ifdef __cplusplus"); Put_Line (File, "}"); Put_Line (File, "#endif"); New_Line (File); Put (File, "#endif /* "); Put (File, Define); Put_Line (File, " */"); Close (File); end Generate_Header; -- ------------------------------ -- Generate the package body. -- ------------------------------ procedure Generate_Source (Generator : in out Generator_Type; Resource : in out Are.Resource_Type; Context : in out Are.Context_Type'Class) is procedure Generate_Keyword_Table (Into : in out Ada.Text_IO.File_Type; Names : in Util.Strings.Vectors.Vector); Name : constant String := To_String (Resource.Name); Filename : constant String := To_File_Name (Name) & ".c"; Path : constant String := Context.Get_Output_Path (Filename); Prefix : constant String := To_Prefix_Name (Name); List_Names : constant String := Prefix & "_names"; Def_Func : constant String := Prefix & "_get_content"; Content_Name : constant String := Prefix & "_contents"; Type_Name : constant String := Get_Type_Name (Prefix, Resource, Context); Func_Name : constant String := Resource.Get_Function_Name (Context, Def_Func); Count : constant Natural := Natural (Resource.Files.Length); File : Ada.Text_IO.File_Type; -- ------------------------------ -- Generate the keyword table. -- ------------------------------ procedure Generate_Keyword_Table (Into : in out Ada.Text_IO.File_Type; Names : in Util.Strings.Vectors.Vector) is Index : Integer := 0; begin New_Line (Into); if not Context.List_Content then Put (Into, "static "); end if; Put (Into, "const char* const "); Put (Into, List_Names); Put_Line (Into, "[] = {"); for Name of Names loop if Index > 0 then Put_Line (Into, ","); end if; Put (Into, " """); Put (Into, Name); Put (Into, """"); Index := Index + 1; end loop; New_Line (Into); Put_Line (Into, "};"); New_Line (Into); end Generate_Keyword_Table; begin Log.Info ("Writing resource {0} in {1}", Name, Path); Ada.Text_IO.Create (File => File, Mode => Ada.Text_IO.Out_File, Name => Path); Put (File, "// "); Put_Line (File, Get_Title); Put_Line (File, "#include <string.h>"); Put (File, "#include """); Put (File, Filename (Filename'First .. Filename'Last - 1)); Put_Line (File, "h"""); New_Line (File); Generate_Resource_Contents (Resource, File); if Context.Name_Index then Generate_Keyword_Table (File, Generator.Names); end if; if Count >= 1 then Log.Debug ("Writing struct {0} contents[] with {1} entries", Type_Name, Util.Strings.Image (Count)); New_Line (File); if not Context.Declare_Var then Put (File, "static "); end if; Put (File, "const "); Put (File, Type_Name); Put (File, " "); Put (File, Content_Name); Put_Line (File, "[] = {"); declare Need_Sep : Boolean := False; Col : Natural := 0; Index : Natural := 1; begin for Content in Resource.Files.Iterate loop if Need_Sep then Put (File, ","); New_Line (File); end if; Put (File, " { "); Put (File, "C_"); Put (File, Util.Strings.Image (Index)); Index := Index + 1; Put (File, ","); declare use Ada.Calendar.Conversions; Data : constant File_Info := File_Maps.Element (Content); begin if Resource.Format = R_LINES then Put (File, Natural'Image (Data.Line_Count)); else Put (File, Ada.Directories.File_Size'Image (Data.Length)); Put (File, ","); Put (File, Interfaces.C.long'Image (To_Unix_Time (Data.Modtime))); end if; end; Put (File, " }"); Col := Col + 1; Need_Sep := True; end loop; end; New_Line (File); Put_Line (File, "};"); end if; if Context.Name_Index then Log.Debug ("Writing {0} implementation", Func_Name); Put_Line (File, "// Returns the data stream with the given name or null."); Put (File, "const "); Put (File, Type_Name); Put (File, "* "); Put (File, Func_Name); Put (File, "(const char* name)"); New_Line (File); Put_Line (File, "{"); if Count > 1 then Put_Line (File, " int low = 0;"); Put (File, " int high = "); Put (File, Util.Strings.Image (Count - 1)); Put_Line (File, ";"); Put_Line (File, " while (low <= high)"); Put_Line (File, " {"); Put_Line (File, " int mid = (low + high) / 2;"); Put_Line (File, " int cmp = strcmp(" & List_Names & "[mid], name);"); Put_Line (File, " if (cmp == 0)"); Put (File, " return &"); Put (File, Content_Name); Put_Line (File, "[mid];"); Put_Line (File, " else if (cmp < 0)"); Put_Line (File, " low = mid + 1;"); Put_Line (File, " else"); Put_Line (File, " high = mid - 1;"); Put_Line (File, " }"); Put_Line (File, " return 0;"); else Put (File, " return (strcmp("); Put (File, List_Names); Put (File, "[0], name) == 0 ? &"); Put (File, Content_Name); Put_Line (File, "[0] : 0);"); end if; Put_Line (File, "}"); New_Line (File); end if; Close (File); end Generate_Source; end Are.Generator.C;
----------------------------------------------------------------------- -- monitor - A simple monitor API -- Copyright (C) 2016, 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 Servlet.Responses; package body Monitor is type Monitor_Array is array (1 .. MAX_MONITOR) of Monitor_Data; Monitors : Monitor_Array; -- Get values of the monitor. procedure Get_Values (Req : in out Servlet.Rest.Request'Class; Reply : in out Servlet.Rest.Response'Class; Stream : in out Servlet.Rest.Output_Stream'Class) is Id : constant String := Req.Get_Path_Parameter (1); Pos : Positive; begin Pos := Positive'Value (Id); -- Monitors (Pos).Put (0); -- Get the monitor values. declare Values : constant Value_Array := Monitors (Pos).Get_Values; begin -- Write the JSON/XML document. Stream.Start_Document; Stream.Start_Array ("values"); for V of Values loop Stream.Write_Long_Entity ("value", Long_Long_Integer (V)); end loop; Stream.End_Array ("values"); Stream.End_Document; end; exception when others => Reply.Set_Status (Servlet.Responses.SC_NOT_FOUND); end Get_Values; -- PUT /mon/:id procedure Put_Value (Req : in out Servlet.Rest.Request'Class; Reply : in out Servlet.Rest.Response'Class; Stream : in out Servlet.Rest.Output_Stream'Class) is pragma Unreferenced (Stream); Id : constant String := Req.Get_Path_Parameter (1); Pos : Positive; Val : Natural; begin Pos := Positive'Value (Id); begin Val := Natural'Value (Req.Get_Parameter ("value")); Monitors (Pos).Put (Val); exception when others => Reply.Set_Status (Servlet.Responses.SC_BAD_REQUEST); end; exception when others => Reply.Set_Status (Servlet.Responses.SC_NOT_FOUND); end Put_Value; protected body Monitor_Data is procedure Put (Value : in Natural) is use type Ada.Calendar.Time; Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; Dt : constant Duration := Now - Slot_Start; Cnt : Natural := Natural (Dt / Slot_Size); begin if Cnt > 0 then while Cnt > 0 loop Cnt := Cnt - 1; Pos := Pos + 1; if Pos > Values'Last then Pos := Values'First; Value_Count := Values'Length; elsif Value_Count < Values'Length then Value_Count := Value_Count + 1; end if; Slot_Start := Slot_Start + Slot_Size; end loop; end if; Values (Pos) := Value; end Put; procedure Put (Value : in Natural; Slot : in Natural) is begin null; end Put; function Get_Values return Value_Array is Result : Value_Array (1 .. Value_Count); Cnt : Natural; N : Natural; begin if Value_Count = Values'Length then Cnt := Values'Last - Pos; else Cnt := 0; end if; if Cnt > 0 then Result (1 .. Cnt) := Values (Pos + 1 .. Pos + 1 + Cnt - 1); N := Cnt + 1; else N := 1; end if; if Value_Count = Values'Length then Cnt := Pos; else Cnt := Pos - 1; end if; if Cnt > 0 then Result (N .. N + Cnt - 1) := Values (1 .. Cnt); end if; return Result; end Get_Values; end Monitor_Data; end Monitor;
------------------------------------------------------------------------------ -- -- -- GNAT ncurses Binding -- -- -- -- Terminal_Interface.Curses.Forms -- -- -- -- B O D Y -- -- -- ------------------------------------------------------------------------------ -- Copyright (c) 1998-2009,2011 Free Software Foundation, Inc. -- -- -- -- Permission is hereby granted, free of charge, to any person obtaining a -- -- copy of this software and associated documentation files (the -- -- "Software"), to deal in the Software without restriction, including -- -- without limitation the rights to use, copy, modify, merge, publish, -- -- distribute, distribute with modifications, sublicense, and/or sell -- -- copies of the Software, and to permit persons to whom the Software is -- -- furnished to do so, subject to the following conditions: -- -- -- -- The above copyright notice and this permission notice shall be included -- -- in all copies or substantial portions of the Software. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -- -- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -- -- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -- -- IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -- -- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -- -- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR -- -- THE USE OR OTHER DEALINGS IN THE SOFTWARE. -- -- -- -- Except as contained in this notice, the name(s) of the above copyright -- -- holders shall not be used in advertising or otherwise to promote the -- -- sale, use or other dealings in this Software without prior written -- -- authorization. -- ------------------------------------------------------------------------------ -- Author: Juergen Pfeifer, 1996 -- Version Control: -- $Revision: 1.28 $ -- $Date: 2011/03/22 23:37:32 $ -- Binding Version 01.00 ------------------------------------------------------------------------------ with Ada.Unchecked_Deallocation; with Ada.Unchecked_Conversion; with Interfaces.C; use Interfaces.C; with Interfaces.C.Strings; use Interfaces.C.Strings; with Interfaces.C.Pointers; with Terminal_Interface.Curses.Aux; package body Terminal_Interface.Curses.Forms is use Terminal_Interface.Curses.Aux; type C_Field_Array is array (Natural range <>) of aliased Field; package F_Array is new Interfaces.C.Pointers (Natural, Field, C_Field_Array, Null_Field); ------------------------------------------------------------------------------ -- | -- | -- | -- subtype chars_ptr is Interfaces.C.Strings.chars_ptr; function FOS_2_CInt is new Ada.Unchecked_Conversion (Field_Option_Set, C_Int); function CInt_2_FOS is new Ada.Unchecked_Conversion (C_Int, Field_Option_Set); function FrmOS_2_CInt is new Ada.Unchecked_Conversion (Form_Option_Set, C_Int); function CInt_2_FrmOS is new Ada.Unchecked_Conversion (C_Int, Form_Option_Set); procedure Request_Name (Key : Form_Request_Code; Name : out String) is function Form_Request_Name (Key : C_Int) return chars_ptr; pragma Import (C, Form_Request_Name, "form_request_name"); begin Fill_String (Form_Request_Name (C_Int (Key)), Name); end Request_Name; function Request_Name (Key : Form_Request_Code) return String is function Form_Request_Name (Key : C_Int) return chars_ptr; pragma Import (C, Form_Request_Name, "form_request_name"); begin return Fill_String (Form_Request_Name (C_Int (Key))); end Request_Name; ------------------------------------------------------------------------------ -- | -- | -- | -- | -- |===================================================================== -- | man page form_field_new.3x -- |===================================================================== -- | -- | -- | function Create (Height : Line_Count; Width : Column_Count; Top : Line_Position; Left : Column_Position; Off_Screen : Natural := 0; More_Buffers : Buffer_Number := Buffer_Number'First) return Field is function Newfield (H, W, T, L, O, M : C_Int) return Field; pragma Import (C, Newfield, "new_field"); Fld : constant Field := Newfield (C_Int (Height), C_Int (Width), C_Int (Top), C_Int (Left), C_Int (Off_Screen), C_Int (More_Buffers)); begin if Fld = Null_Field then raise Form_Exception; end if; return Fld; end Create; -- | -- | -- | procedure Delete (Fld : in out Field) is function Free_Field (Fld : Field) return C_Int; pragma Import (C, Free_Field, "free_field"); Res : Eti_Error; begin Res := Free_Field (Fld); if Res /= E_Ok then Eti_Exception (Res); end if; Fld := Null_Field; end Delete; -- | -- | -- | function Duplicate (Fld : Field; Top : Line_Position; Left : Column_Position) return Field is function Dup_Field (Fld : Field; Top : C_Int; Left : C_Int) return Field; pragma Import (C, Dup_Field, "dup_field"); F : constant Field := Dup_Field (Fld, C_Int (Top), C_Int (Left)); begin if F = Null_Field then raise Form_Exception; end if; return F; end Duplicate; -- | -- | -- | function Link (Fld : Field; Top : Line_Position; Left : Column_Position) return Field is function Lnk_Field (Fld : Field; Top : C_Int; Left : C_Int) return Field; pragma Import (C, Lnk_Field, "link_field"); F : constant Field := Lnk_Field (Fld, C_Int (Top), C_Int (Left)); begin if F = Null_Field then raise Form_Exception; end if; return F; end Link; -- | -- |===================================================================== -- | man page form_field_just.3x -- |===================================================================== -- | -- | -- | procedure Set_Justification (Fld : Field; Just : Field_Justification := None) is function Set_Field_Just (Fld : Field; Just : C_Int) return C_Int; pragma Import (C, Set_Field_Just, "set_field_just"); Res : constant Eti_Error := Set_Field_Just (Fld, C_Int (Field_Justification'Pos (Just))); begin if Res /= E_Ok then Eti_Exception (Res); end if; end Set_Justification; -- | -- | -- | function Get_Justification (Fld : Field) return Field_Justification is function Field_Just (Fld : Field) return C_Int; pragma Import (C, Field_Just, "field_just"); begin return Field_Justification'Val (Field_Just (Fld)); end Get_Justification; -- | -- |===================================================================== -- | man page form_field_buffer.3x -- |===================================================================== -- | -- | -- | procedure Set_Buffer (Fld : Field; Buffer : Buffer_Number := Buffer_Number'First; Str : String) is type Char_Ptr is access all Interfaces.C.char; function Set_Fld_Buffer (Fld : Field; Bufnum : C_Int; S : Char_Ptr) return C_Int; pragma Import (C, Set_Fld_Buffer, "set_field_buffer"); Txt : char_array (0 .. Str'Length); Len : size_t; Res : Eti_Error; begin To_C (Str, Txt, Len); Res := Set_Fld_Buffer (Fld, C_Int (Buffer), Txt (Txt'First)'Access); if Res /= E_Ok then Eti_Exception (Res); end if; end Set_Buffer; -- | -- | -- | procedure Get_Buffer (Fld : Field; Buffer : Buffer_Number := Buffer_Number'First; Str : out String) is function Field_Buffer (Fld : Field; B : C_Int) return chars_ptr; pragma Import (C, Field_Buffer, "field_buffer"); begin Fill_String (Field_Buffer (Fld, C_Int (Buffer)), Str); end Get_Buffer; function Get_Buffer (Fld : Field; Buffer : Buffer_Number := Buffer_Number'First) return String is function Field_Buffer (Fld : Field; B : C_Int) return chars_ptr; pragma Import (C, Field_Buffer, "field_buffer"); begin return Fill_String (Field_Buffer (Fld, C_Int (Buffer))); end Get_Buffer; -- | -- | -- | procedure Set_Status (Fld : Field; Status : Boolean := True) is function Set_Fld_Status (Fld : Field; St : C_Int) return C_Int; pragma Import (C, Set_Fld_Status, "set_field_status"); Res : constant Eti_Error := Set_Fld_Status (Fld, Boolean'Pos (Status)); begin if Res /= E_Ok then raise Form_Exception; end if; end Set_Status; -- | -- | -- | function Changed (Fld : Field) return Boolean is function Field_Status (Fld : Field) return C_Int; pragma Import (C, Field_Status, "field_status"); Res : constant C_Int := Field_Status (Fld); begin if Res = Curses_False then return False; else return True; end if; end Changed; -- | -- | -- | procedure Set_Maximum_Size (Fld : Field; Max : Natural := 0) is function Set_Field_Max (Fld : Field; M : C_Int) return C_Int; pragma Import (C, Set_Field_Max, "set_max_field"); Res : constant Eti_Error := Set_Field_Max (Fld, C_Int (Max)); begin if Res /= E_Ok then Eti_Exception (Res); end if; end Set_Maximum_Size; -- | -- |===================================================================== -- | man page form_field_opts.3x -- |===================================================================== -- | -- | -- | procedure Set_Options (Fld : Field; Options : Field_Option_Set) is function Set_Field_Opts (Fld : Field; Opt : C_Int) return C_Int; pragma Import (C, Set_Field_Opts, "set_field_opts"); Opt : constant C_Int := FOS_2_CInt (Options); Res : Eti_Error; begin Res := Set_Field_Opts (Fld, Opt); if Res /= E_Ok then Eti_Exception (Res); end if; end Set_Options; -- | -- | -- | procedure Switch_Options (Fld : Field; Options : Field_Option_Set; On : Boolean := True) is function Field_Opts_On (Fld : Field; Opt : C_Int) return C_Int; pragma Import (C, Field_Opts_On, "field_opts_on"); function Field_Opts_Off (Fld : Field; Opt : C_Int) return C_Int; pragma Import (C, Field_Opts_Off, "field_opts_off"); Err : Eti_Error; Opt : constant C_Int := FOS_2_CInt (Options); begin if On then Err := Field_Opts_On (Fld, Opt); else Err := Field_Opts_Off (Fld, Opt); end if; if Err /= E_Ok then Eti_Exception (Err); end if; end Switch_Options; -- | -- | -- | procedure Get_Options (Fld : Field; Options : out Field_Option_Set) is function Field_Opts (Fld : Field) return C_Int; pragma Import (C, Field_Opts, "field_opts"); Res : constant C_Int := Field_Opts (Fld); begin Options := CInt_2_FOS (Res); end Get_Options; -- | -- | -- | function Get_Options (Fld : Field := Null_Field) return Field_Option_Set is Fos : Field_Option_Set; begin Get_Options (Fld, Fos); return Fos; end Get_Options; -- | -- |===================================================================== -- | man page form_field_attributes.3x -- |===================================================================== -- | -- | -- | procedure Set_Foreground (Fld : Field; Fore : Character_Attribute_Set := Normal_Video; Color : Color_Pair := Color_Pair'First) is function Set_Field_Fore (Fld : Field; Attr : C_Chtype) return C_Int; pragma Import (C, Set_Field_Fore, "set_field_fore"); Ch : constant Attributed_Character := (Ch => Character'First, Color => Color, Attr => Fore); Res : constant Eti_Error := Set_Field_Fore (Fld, AttrChar_To_Chtype (Ch)); begin if Res /= E_Ok then Eti_Exception (Res); end if; end Set_Foreground; -- | -- | -- | procedure Foreground (Fld : Field; Fore : out Character_Attribute_Set) is function Field_Fore (Fld : Field) return C_Chtype; pragma Import (C, Field_Fore, "field_fore"); begin Fore := Chtype_To_AttrChar (Field_Fore (Fld)).Attr; end Foreground; procedure Foreground (Fld : Field; Fore : out Character_Attribute_Set; Color : out Color_Pair) is function Field_Fore (Fld : Field) return C_Chtype; pragma Import (C, Field_Fore, "field_fore"); begin Fore := Chtype_To_AttrChar (Field_Fore (Fld)).Attr; Color := Chtype_To_AttrChar (Field_Fore (Fld)).Color; end Foreground; -- | -- | -- | procedure Set_Background (Fld : Field; Back : Character_Attribute_Set := Normal_Video; Color : Color_Pair := Color_Pair'First) is function Set_Field_Back (Fld : Field; Attr : C_Chtype) return C_Int; pragma Import (C, Set_Field_Back, "set_field_back"); Ch : constant Attributed_Character := (Ch => Character'First, Color => Color, Attr => Back); Res : constant Eti_Error := Set_Field_Back (Fld, AttrChar_To_Chtype (Ch)); begin if Res /= E_Ok then Eti_Exception (Res); end if; end Set_Background; -- | -- | -- | procedure Background (Fld : Field; Back : out Character_Attribute_Set) is function Field_Back (Fld : Field) return C_Chtype; pragma Import (C, Field_Back, "field_back"); begin Back := Chtype_To_AttrChar (Field_Back (Fld)).Attr; end Background; procedure Background (Fld : Field; Back : out Character_Attribute_Set; Color : out Color_Pair) is function Field_Back (Fld : Field) return C_Chtype; pragma Import (C, Field_Back, "field_back"); begin Back := Chtype_To_AttrChar (Field_Back (Fld)).Attr; Color := Chtype_To_AttrChar (Field_Back (Fld)).Color; end Background; -- | -- | -- | procedure Set_Pad_Character (Fld : Field; Pad : Character := Space) is function Set_Field_Pad (Fld : Field; Ch : C_Int) return C_Int; pragma Import (C, Set_Field_Pad, "set_field_pad"); Res : constant Eti_Error := Set_Field_Pad (Fld, C_Int (Character'Pos (Pad))); begin if Res /= E_Ok then Eti_Exception (Res); end if; end Set_Pad_Character; -- | -- | -- | procedure Pad_Character (Fld : Field; Pad : out Character) is function Field_Pad (Fld : Field) return C_Int; pragma Import (C, Field_Pad, "field_pad"); begin Pad := Character'Val (Field_Pad (Fld)); end Pad_Character; -- | -- |===================================================================== -- | man page form_field_info.3x -- |===================================================================== -- | -- | -- | procedure Info (Fld : Field; Lines : out Line_Count; Columns : out Column_Count; First_Row : out Line_Position; First_Column : out Column_Position; Off_Screen : out Natural; Additional_Buffers : out Buffer_Number) is type C_Int_Access is access all C_Int; function Fld_Info (Fld : Field; L, C, Fr, Fc, Os, Ab : C_Int_Access) return C_Int; pragma Import (C, Fld_Info, "field_info"); L, C, Fr, Fc, Os, Ab : aliased C_Int; Res : constant Eti_Error := Fld_Info (Fld, L'Access, C'Access, Fr'Access, Fc'Access, Os'Access, Ab'Access); begin if Res /= E_Ok then Eti_Exception (Res); else Lines := Line_Count (L); Columns := Column_Count (C); First_Row := Line_Position (Fr); First_Column := Column_Position (Fc); Off_Screen := Natural (Os); Additional_Buffers := Buffer_Number (Ab); end if; end Info; -- | -- | -- | procedure Dynamic_Info (Fld : Field; Lines : out Line_Count; Columns : out Column_Count; Max : out Natural) is type C_Int_Access is access all C_Int; function Dyn_Info (Fld : Field; L, C, M : C_Int_Access) return C_Int; pragma Import (C, Dyn_Info, "dynamic_field_info"); L, C, M : aliased C_Int; Res : constant Eti_Error := Dyn_Info (Fld, L'Access, C'Access, M'Access); begin if Res /= E_Ok then Eti_Exception (Res); else Lines := Line_Count (L); Columns := Column_Count (C); Max := Natural (M); end if; end Dynamic_Info; -- | -- |===================================================================== -- | man page form_win.3x -- |===================================================================== -- | -- | -- | procedure Set_Window (Frm : Form; Win : Window) is function Set_Form_Win (Frm : Form; Win : Window) return C_Int; pragma Import (C, Set_Form_Win, "set_form_win"); Res : constant Eti_Error := Set_Form_Win (Frm, Win); begin if Res /= E_Ok then Eti_Exception (Res); end if; end Set_Window; -- | -- | -- | function Get_Window (Frm : Form) return Window is function Form_Win (Frm : Form) return Window; pragma Import (C, Form_Win, "form_win"); W : constant Window := Form_Win (Frm); begin return W; end Get_Window; -- | -- | -- | procedure Set_Sub_Window (Frm : Form; Win : Window) is function Set_Form_Sub (Frm : Form; Win : Window) return C_Int; pragma Import (C, Set_Form_Sub, "set_form_sub"); Res : constant Eti_Error := Set_Form_Sub (Frm, Win); begin if Res /= E_Ok then Eti_Exception (Res); end if; end Set_Sub_Window; -- | -- | -- | function Get_Sub_Window (Frm : Form) return Window is function Form_Sub (Frm : Form) return Window; pragma Import (C, Form_Sub, "form_sub"); W : constant Window := Form_Sub (Frm); begin return W; end Get_Sub_Window; -- | -- | -- | procedure Scale (Frm : Form; Lines : out Line_Count; Columns : out Column_Count) is type C_Int_Access is access all C_Int; function M_Scale (Frm : Form; Yp, Xp : C_Int_Access) return C_Int; pragma Import (C, M_Scale, "scale_form"); X, Y : aliased C_Int; Res : constant Eti_Error := M_Scale (Frm, Y'Access, X'Access); begin if Res /= E_Ok then Eti_Exception (Res); end if; Lines := Line_Count (Y); Columns := Column_Count (X); end Scale; -- | -- |===================================================================== -- | man page menu_hook.3x -- |===================================================================== -- | -- | -- | procedure Set_Field_Init_Hook (Frm : Form; Proc : Form_Hook_Function) is function Set_Field_Init (Frm : Form; Proc : Form_Hook_Function) return C_Int; pragma Import (C, Set_Field_Init, "set_field_init"); Res : constant Eti_Error := Set_Field_Init (Frm, Proc); begin if Res /= E_Ok then Eti_Exception (Res); end if; end Set_Field_Init_Hook; -- | -- | -- | procedure Set_Field_Term_Hook (Frm : Form; Proc : Form_Hook_Function) is function Set_Field_Term (Frm : Form; Proc : Form_Hook_Function) return C_Int; pragma Import (C, Set_Field_Term, "set_field_term"); Res : constant Eti_Error := Set_Field_Term (Frm, Proc); begin if Res /= E_Ok then Eti_Exception (Res); end if; end Set_Field_Term_Hook; -- | -- | -- | procedure Set_Form_Init_Hook (Frm : Form; Proc : Form_Hook_Function) is function Set_Form_Init (Frm : Form; Proc : Form_Hook_Function) return C_Int; pragma Import (C, Set_Form_Init, "set_form_init"); Res : constant Eti_Error := Set_Form_Init (Frm, Proc); begin if Res /= E_Ok then Eti_Exception (Res); end if; end Set_Form_Init_Hook; -- | -- | -- | procedure Set_Form_Term_Hook (Frm : Form; Proc : Form_Hook_Function) is function Set_Form_Term (Frm : Form; Proc : Form_Hook_Function) return C_Int; pragma Import (C, Set_Form_Term, "set_form_term"); Res : constant Eti_Error := Set_Form_Term (Frm, Proc); begin if Res /= E_Ok then Eti_Exception (Res); end if; end Set_Form_Term_Hook; -- | -- |===================================================================== -- | man page form_fields.3x -- |===================================================================== -- | -- | -- | procedure Redefine (Frm : Form; Flds : Field_Array_Access) is function Set_Frm_Fields (Frm : Form; Items : System.Address) return C_Int; pragma Import (C, Set_Frm_Fields, "set_form_fields"); Res : Eti_Error; begin pragma Assert (Flds.all (Flds'Last) = Null_Field); if Flds.all (Flds'Last) /= Null_Field then raise Form_Exception; else Res := Set_Frm_Fields (Frm, Flds.all (Flds'First)'Address); if Res /= E_Ok then Eti_Exception (Res); end if; end if; end Redefine; -- | -- | -- | function Fields (Frm : Form; Index : Positive) return Field is use F_Array; function C_Fields (Frm : Form) return Pointer; pragma Import (C, C_Fields, "form_fields"); P : Pointer := C_Fields (Frm); begin if P = null or else Index > Field_Count (Frm) then raise Form_Exception; else P := P + ptrdiff_t (C_Int (Index) - 1); return P.all; end if; end Fields; -- | -- | -- | function Field_Count (Frm : Form) return Natural is function Count (Frm : Form) return C_Int; pragma Import (C, Count, "field_count"); begin return Natural (Count (Frm)); end Field_Count; -- | -- | -- | procedure Move (Fld : Field; Line : Line_Position; Column : Column_Position) is function Move (Fld : Field; L, C : C_Int) return C_Int; pragma Import (C, Move, "move_field"); Res : constant Eti_Error := Move (Fld, C_Int (Line), C_Int (Column)); begin if Res /= E_Ok then Eti_Exception (Res); end if; end Move; -- | -- |===================================================================== -- | man page form_new.3x -- |===================================================================== -- | -- | -- | function Create (Fields : Field_Array_Access) return Form is function NewForm (Fields : System.Address) return Form; pragma Import (C, NewForm, "new_form"); M : Form; begin pragma Assert (Fields.all (Fields'Last) = Null_Field); if Fields.all (Fields'Last) /= Null_Field then raise Form_Exception; else M := NewForm (Fields.all (Fields'First)'Address); if M = Null_Form then raise Form_Exception; end if; return M; end if; end Create; -- | -- | -- | procedure Delete (Frm : in out Form) is function Free (Frm : Form) return C_Int; pragma Import (C, Free, "free_form"); Res : constant Eti_Error := Free (Frm); begin if Res /= E_Ok then Eti_Exception (Res); end if; Frm := Null_Form; end Delete; -- | -- |===================================================================== -- | man page form_opts.3x -- |===================================================================== -- | -- | -- | procedure Set_Options (Frm : Form; Options : Form_Option_Set) is function Set_Form_Opts (Frm : Form; Opt : C_Int) return C_Int; pragma Import (C, Set_Form_Opts, "set_form_opts"); Opt : constant C_Int := FrmOS_2_CInt (Options); Res : Eti_Error; begin Res := Set_Form_Opts (Frm, Opt); if Res /= E_Ok then Eti_Exception (Res); end if; end Set_Options; -- | -- | -- | procedure Switch_Options (Frm : Form; Options : Form_Option_Set; On : Boolean := True) is function Form_Opts_On (Frm : Form; Opt : C_Int) return C_Int; pragma Import (C, Form_Opts_On, "form_opts_on"); function Form_Opts_Off (Frm : Form; Opt : C_Int) return C_Int; pragma Import (C, Form_Opts_Off, "form_opts_off"); Err : Eti_Error; Opt : constant C_Int := FrmOS_2_CInt (Options); begin if On then Err := Form_Opts_On (Frm, Opt); else Err := Form_Opts_Off (Frm, Opt); end if; if Err /= E_Ok then Eti_Exception (Err); end if; end Switch_Options; -- | -- | -- | procedure Get_Options (Frm : Form; Options : out Form_Option_Set) is function Form_Opts (Frm : Form) return C_Int; pragma Import (C, Form_Opts, "form_opts"); Res : constant C_Int := Form_Opts (Frm); begin Options := CInt_2_FrmOS (Res); end Get_Options; -- | -- | -- | function Get_Options (Frm : Form := Null_Form) return Form_Option_Set is Fos : Form_Option_Set; begin Get_Options (Frm, Fos); return Fos; end Get_Options; -- | -- |===================================================================== -- | man page form_post.3x -- |===================================================================== -- | -- | -- | procedure Post (Frm : Form; Post : Boolean := True) is function M_Post (Frm : Form) return C_Int; pragma Import (C, M_Post, "post_form"); function M_Unpost (Frm : Form) return C_Int; pragma Import (C, M_Unpost, "unpost_form"); Res : Eti_Error; begin if Post then Res := M_Post (Frm); else Res := M_Unpost (Frm); end if; if Res /= E_Ok then Eti_Exception (Res); end if; end Post; -- | -- |===================================================================== -- | man page form_cursor.3x -- |===================================================================== -- | -- | -- | procedure Position_Cursor (Frm : Form) is function Pos_Form_Cursor (Frm : Form) return C_Int; pragma Import (C, Pos_Form_Cursor, "pos_form_cursor"); Res : constant Eti_Error := Pos_Form_Cursor (Frm); begin if Res /= E_Ok then Eti_Exception (Res); end if; end Position_Cursor; -- | -- |===================================================================== -- | man page form_data.3x -- |===================================================================== -- | -- | -- | function Data_Ahead (Frm : Form) return Boolean is function Ahead (Frm : Form) return C_Int; pragma Import (C, Ahead, "data_ahead"); Res : constant C_Int := Ahead (Frm); begin if Res = Curses_False then return False; else return True; end if; end Data_Ahead; -- | -- | -- | function Data_Behind (Frm : Form) return Boolean is function Behind (Frm : Form) return C_Int; pragma Import (C, Behind, "data_behind"); Res : constant C_Int := Behind (Frm); begin if Res = Curses_False then return False; else return True; end if; end Data_Behind; -- | -- |===================================================================== -- | man page form_driver.3x -- |===================================================================== -- | -- | -- | function Driver (Frm : Form; Key : Key_Code) return Driver_Result is function Frm_Driver (Frm : Form; Key : C_Int) return C_Int; pragma Import (C, Frm_Driver, "form_driver"); R : constant Eti_Error := Frm_Driver (Frm, C_Int (Key)); begin if R /= E_Ok then if R = E_Unknown_Command then return Unknown_Request; elsif R = E_Invalid_Field then return Invalid_Field; elsif R = E_Request_Denied then return Request_Denied; else Eti_Exception (R); return Form_Ok; end if; else return Form_Ok; end if; end Driver; -- | -- |===================================================================== -- | man page form_page.3x -- |===================================================================== -- | -- | -- | procedure Set_Current (Frm : Form; Fld : Field) is function Set_Current_Fld (Frm : Form; Fld : Field) return C_Int; pragma Import (C, Set_Current_Fld, "set_current_field"); Res : constant Eti_Error := Set_Current_Fld (Frm, Fld); begin if Res /= E_Ok then Eti_Exception (Res); end if; end Set_Current; -- | -- | -- | function Current (Frm : Form) return Field is function Current_Fld (Frm : Form) return Field; pragma Import (C, Current_Fld, "current_field"); Fld : constant Field := Current_Fld (Frm); begin if Fld = Null_Field then raise Form_Exception; end if; return Fld; end Current; -- | -- | -- | procedure Set_Page (Frm : Form; Page : Page_Number := Page_Number'First) is function Set_Frm_Page (Frm : Form; Pg : C_Int) return C_Int; pragma Import (C, Set_Frm_Page, "set_form_page"); Res : constant Eti_Error := Set_Frm_Page (Frm, C_Int (Page)); begin if Res /= E_Ok then Eti_Exception (Res); end if; end Set_Page; -- | -- | -- | function Page (Frm : Form) return Page_Number is function Get_Page (Frm : Form) return C_Int; pragma Import (C, Get_Page, "form_page"); P : constant C_Int := Get_Page (Frm); begin if P < 0 then raise Form_Exception; else return Page_Number (P); end if; end Page; function Get_Index (Fld : Field) return Positive is function Get_Fieldindex (Fld : Field) return C_Int; pragma Import (C, Get_Fieldindex, "field_index"); Res : constant C_Int := Get_Fieldindex (Fld); begin if Res = Curses_Err then raise Form_Exception; end if; return Positive (Natural (Res) + Positive'First); end Get_Index; -- | -- |===================================================================== -- | man page form_new_page.3x -- |===================================================================== -- | -- | -- | procedure Set_New_Page (Fld : Field; New_Page : Boolean := True) is function Set_Page (Fld : Field; Flg : C_Int) return C_Int; pragma Import (C, Set_Page, "set_new_page"); Res : constant Eti_Error := Set_Page (Fld, Boolean'Pos (New_Page)); begin if Res /= E_Ok then Eti_Exception (Res); end if; end Set_New_Page; -- | -- | -- | function Is_New_Page (Fld : Field) return Boolean is function Is_New (Fld : Field) return C_Int; pragma Import (C, Is_New, "new_page"); Res : constant C_Int := Is_New (Fld); begin if Res = Curses_False then return False; else return True; end if; end Is_New_Page; procedure Free (FA : in out Field_Array_Access; Free_Fields : Boolean := False) is procedure Release is new Ada.Unchecked_Deallocation (Field_Array, Field_Array_Access); begin if FA /= null and then Free_Fields then for I in FA'First .. (FA'Last - 1) loop if FA.all (I) /= Null_Field then Delete (FA.all (I)); end if; end loop; end if; Release (FA); end Free; -- |===================================================================== function Default_Field_Options return Field_Option_Set is begin return Get_Options (Null_Field); end Default_Field_Options; function Default_Form_Options return Form_Option_Set is begin return Get_Options (Null_Form); end Default_Form_Options; end Terminal_Interface.Curses.Forms;
----------------------------------------------------------------------- -- util-concurrent-tests -- Unit tests for concurrency package -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2019 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Strings.Unbounded; with Ada.Finalization; with Util.Concurrent.Counters; with Util.Test_Caller; with Util.Measures; with Util.Log.Loggers; with Util.Concurrent.Copies; with Util.Concurrent.Pools; with Util.Concurrent.Fifos; with Util.Concurrent.Arrays; with Util.Concurrent.Sequence_Queues; package body Util.Concurrent.Tests is use Util.Tests; use Util.Concurrent.Counters; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Concurrent.Tests"); type Connection is new Ada.Finalization.Controlled with record Name : Ada.Strings.Unbounded.Unbounded_String; Value : Natural := 0; end record; function "=" (Left, Right : in Connection) return Boolean; overriding procedure Finalize (C : in out Connection); function "=" (Left, Right : in Connection) return Boolean is begin return Left.Value = Right.Value; end "="; package Connection_Pool is new Util.Concurrent.Pools (Connection); package Connection_Fifo is new Util.Concurrent.Fifos (Connection, 7); package Connection_Arrays is new Util.Concurrent.Arrays (Connection); package Connection_Sequences is new Util.Concurrent.Sequence_Queues (Connection, Natural, 13); package Caller is new Util.Test_Caller (Test, "Concurrent"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Concurrent.Counter.Increment", Test_Increment'Access); Caller.Add_Test (Suite, "Test Util.Concurrent.Counter.Decrement", Test_Decrement'Access); Caller.Add_Test (Suite, "Test Util.Concurrent.Counter.Decrement + Test", Test_Decrement_And_Test'Access); Caller.Add_Test (Suite, "Test Util.Concurrent.Copies.Get + Set", Test_Copy'Access); Caller.Add_Test (Suite, "Test Util.Concurrent.Pools.Get_Instance", Test_Pool'Access); Caller.Add_Test (Suite, "Test Util.Concurrent.Pools (concurrent test)", Test_Concurrent_Pool'Access); Caller.Add_Test (Suite, "Test Util.Concurrent.Fifos", Test_Fifo'Access); Caller.Add_Test (Suite, "Test Util.Concurrent.Fifos (concurrent test)", Test_Concurrent_Fifo'Access); Caller.Add_Test (Suite, "Test Util.Concurrent.Arrays", Test_Array'Access); Caller.Add_Test (Suite, "Test Util.Concurrent.Sequence_Queues", Test_Concurrent_Sequences'Access); end Add_Tests; overriding procedure Finalize (C : in out Connection) is begin null; end Finalize; -- ------------------------------ -- Test concurrent pool -- ------------------------------ procedure Test_Pool (T : in out Test) is use Ada.Strings.Unbounded; P : Connection_Pool.Pool; C : Connection; begin -- Set the pool capacity. P.Set_Size (Capacity => 10); -- Insert the objects. for I in 1 .. 10 loop C.Name := To_Unbounded_String (Integer'Image (I)); P.Release (C); end loop; -- Use the pool and verify the objects. declare C : array (1 .. 10) of Connection; begin for J in 1 .. 3 loop -- Get each object and verify that it matches our instance. for I in reverse 1 .. 10 loop P.Get_Instance (C (I)); Assert_Equals (T, Integer'Image (I), To_String (C (I).Name), "Invalid pool object"); end loop; -- Put the object back in the pool. for I in 1 .. 10 loop P.Release (C (I)); end loop; end loop; end; declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop P.Get_Instance (C); P.Release (C); end loop; Util.Measures.Report (S, "Pool Get_Instance+Release", 1000); end; end Test_Pool; -- ------------------------------ -- Test concurrent pool -- ------------------------------ procedure Test_Concurrent_Pool (T : in out Test) is use Ada.Strings.Unbounded; Count_By_Task : constant Natural := 10_001; Task_Count : constant Natural := 17; Capacity : constant Natural := 5; P : Connection_Pool.Pool; C : Connection; S : Util.Measures.Stamp; begin -- Set the pool capacity. P.Set_Size (Capacity => Capacity); -- Insert the objects. for I in 1 .. Capacity loop C.Name := To_Unbounded_String (Integer'Image (I)); P.Release (C); end loop; declare -- A task that picks an object from the pool, increment the value and puts -- back the object in the pool. task type Worker is entry Start (Count : in Natural); end Worker; task body Worker is Cnt : Natural; begin accept Start (Count : in Natural) do Cnt := Count; end Start; -- Get an object from the pool, increment the value and put it back in the pool. for I in 1 .. Cnt loop declare C : Connection; begin P.Get_Instance (C); C.Value := C.Value + 1; P.Release (C); end; end loop; exception when E : others => Log.Error ("Exception raised", E); Ada.Text_IO.Put_Line ("Exception raised."); end Worker; type Worker_Array is array (1 .. Task_Count) of Worker; Tasks : Worker_Array; begin for I in Tasks'Range loop Tasks (I).Start (Count_By_Task); end loop; -- Leaving the Worker task scope means we are waiting for our tasks to finish. end; Util.Measures.Report (S, "Executed Get+Release " & Natural'Image (Count_By_Task * Task_Count)); declare Total : Natural := 0; begin for I in 1 .. Capacity loop P.Get_Instance (C); Total := Total + C.Value; end loop; Assert_Equals (T, Count_By_Task * Task_Count, Total, "Invalid computation"); end; end Test_Concurrent_Pool; procedure Test_Increment (T : in out Test) is C : Counter; begin Increment (C); Assert_Equals (T, Value (C), 1, "Increment failed"); end Test_Increment; procedure Test_Decrement (T : in out Test) is C : Counter; begin Increment (C); Decrement (C); Assert_Equals (T, Value (C), 0, "Increment + Decrement failed"); end Test_Decrement; procedure Test_Decrement_And_Test (T : in out Test) is C : Counter; Is_Zero : Boolean; begin Increment (C); Assert_Equals (T, Value (C), 1, "Increment failed"); Decrement (C, Is_Zero); Assert_Equals (T, Value (C), 0, "Decrement failed"); T.Assert (Is_Zero, "Counter should be zero"); Increment (C); Increment (C); Decrement (C, Is_Zero); T.Assert (not Is_Zero, "Counter should not be zero"); end Test_Decrement_And_Test; procedure Test_Copy (T : in out Test) is type Data is record C : Natural := 0; L : Long_Long_Integer := 1; B : Boolean := False; F : Float := 1.0; S : String (1 .. 10) := (others => ' '); end record; package Data_Atomic is new Util.Concurrent.Copies (Data); D : Data_Atomic.Atomic; V : Data; V2 : Data; begin V.C := 1; V.B := True; V.S := "0123456789"; D.Set (V); V2 := D.Get; Assert_Equals (T, 1, V2.C, "Invalid Data.C"); Assert_Equals (T, "0123456789", V2.S, "Invalid Data.S"); -- Concurrent test: -- o increment the long long integer -- o rotate the string by 1 position declare Count_By_Task : constant Natural := 100_001; Task_Count : constant Natural := 17; -- A task that increments the shared counter <b>Unsafe</b> and <b>Counter</b> by -- the specified amount. task type Worker is entry Start (Count : in Natural); end Worker; task body Worker is Cnt : Natural; Val : Data; C : Character; begin accept Start (Count : in Natural) do Cnt := Count; end Start; -- Increment the two counters as many times as necessary. for I in 1 .. Cnt loop Val := D.Get; -- Val := V; Val.L := Val.L + 1; C := Val.S (1); Val.S (1 .. 9) := Val.S (2 .. 10); Val.S (10) := C; D.Set (Val); -- V := Val; Val.S (1 .. 9) := Val.S (2 .. 10); Val.S (10) := C; end loop; exception when others => Ada.Text_IO.Put_Line ("Exception raised."); end Worker; type Worker_Array is array (1 .. Task_Count) of Worker; Tasks : Worker_Array; begin for I in Tasks'Range loop Tasks (I).Start (Count_By_Task); end loop; -- Leaving the Worker task scope means we are waiting for our tasks to finish. end; -- We can't predict the exact value for string after the rotation passes. -- At least, we must have one of the following values (when using an unprotected -- copy, the string value contains garbage). T.Assert (D.Get.S = "0123456789" or D.Get.S = "1234567890" or D.Get.S = "2345678901" or D.Get.S = "3456789012" or D.Get.S = "4567890123" or D.Get.S = "5678901234" or D.Get.S = "6789012345" or D.Get.S = "7890123456" or D.Get.S = "8901234567" or D.Get.S = "9012345678", "Invalid result: " & D.Get.S); end Test_Copy; -- ------------------------------ -- Test fifo -- ------------------------------ procedure Test_Fifo (T : in out Test) is Q : Connection_Fifo.Fifo; Val : Connection; Res : Connection; Cnt : Natural; begin for I in 1 .. 100 loop Cnt := I mod 8; for J in 1 .. Cnt loop Val.Name := Ada.Strings.Unbounded.To_Unbounded_String (Natural'Image (I)); Val.Value := I * J; Q.Enqueue (Val); Util.Tests.Assert_Equals (T, J, Q.Get_Count, "Invalid queue size"); end loop; for J in 1 .. Cnt loop Q.Dequeue (Res); Util.Tests.Assert_Equals (T, I * J, Res.Value, "Invalid dequeue at " & Natural'Image (I) & " - " & Natural'Image (J)); Util.Tests.Assert_Equals (T, Natural'Image (I), Val.Name, "Invalid dequeue at " & Natural'Image (I) & " - " & Natural'Image (J)); end loop; declare S : Util.Measures.Stamp; begin for J in 1 .. 7 loop Q.Enqueue (Val); end loop; Util.Measures.Report (S, "Enqueue 7 elements "); end; declare S : Util.Measures.Stamp; begin for J in 1 .. 7 loop Q.Dequeue (Val); end loop; Util.Measures.Report (S, "Dequeue 7 elements "); end; end loop; for I in 1 .. 100 loop Q.Set_Size (I); end loop; end Test_Fifo; -- Test concurrent aspects of fifo. procedure Test_Concurrent_Fifo (T : in out Test) is Count_By_Task : constant Natural := 60_001; Task_Count : constant Natural := 17; Q : Connection_Fifo.Fifo; S : Util.Measures.Stamp; begin Q.Set_Size (23); declare -- A task that adds elements in the shared queue. task type Producer is entry Start (Count : in Natural); end Producer; -- A task that consumes the elements. task type Consumer is entry Start (Count : in Natural); entry Get (Result : out Long_Long_Integer); end Consumer; task body Producer is Cnt : Natural; begin accept Start (Count : in Natural) do Cnt := Count; end Start; -- Send Cnt values in the queue. for I in 1 .. Cnt loop declare C : Connection; begin C.Value := I; Q.Enqueue (C); end; end loop; exception when E : others => Log.Error ("Exception raised", E); Ada.Text_IO.Put_Line ("Exception raised."); end Producer; task body Consumer is Cnt : Natural; Tot : Long_Long_Integer := 0; begin accept Start (Count : in Natural) do Cnt := Count; end Start; -- Get an object from the pool, increment the value and put it back in the pool. for I in 1 .. Cnt loop declare C : Connection; begin Q.Dequeue (C); -- if C.Value /= I then -- Ada.Text_IO.Put_Line ("Value: " & Natural'Image (C.Value) -- & " instead of " & Natural'Image (I)); -- end if; Tot := Tot + Long_Long_Integer (C.Value); end; end loop; -- Ada.Text_IO.Put_Line ("Total: " & Natural'Image (Tot)); accept Get (Result : out Long_Long_Integer) do Result := Tot; end Get; exception when E : others => Log.Error ("Exception raised", E); Ada.Text_IO.Put_Line ("Exception raised."); end Consumer; type Worker_Array is array (1 .. Task_Count) of Producer; type Consummer_Array is array (1 .. Task_Count) of Consumer; Producers : Worker_Array; Consumers : Consummer_Array; Value : Long_Long_Integer; Total : Long_Long_Integer := 0; Expect : Long_Long_Integer; begin for I in Producers'Range loop Producers (I).Start (Count_By_Task); end loop; for I in Consumers'Range loop Consumers (I).Start (Count_By_Task); end loop; for I in Consumers'Range loop Consumers (I).Get (Value); Total := Total + Value; end loop; Expect := Long_Long_Integer ((Count_By_Task * (Count_By_Task + 1)) / 2); Expect := Expect * Long_Long_Integer (Task_Count); Assert_Equals (T, Expect, Total, "Invalid computation"); end; Util.Measures.Report (S, "Executed Queue+Dequeue " & Natural'Image (Count_By_Task * Task_Count) & " task count: " & Natural'Image (Task_Count)); end Test_Concurrent_Fifo; -- ------------------------------ -- Test concurrent arrays. -- ------------------------------ procedure Test_Array (T : in out Test) is procedure Sum_All (C : in Connection); List : Connection_Arrays.Vector; L : Connection_Arrays.Ref; Val : Connection; Sum : Natural; procedure Sum_All (C : in Connection) is begin Sum := Sum + C.Value; end Sum_All; begin L := List.Get; T.Assert (L.Is_Empty, "List should be empty"); Val.Value := 1; List.Append (Val); T.Assert (L.Is_Empty, "List should be empty"); L := List.Get; T.Assert (not L.Is_Empty, "List should not be empty"); Sum := 0; L.Iterate (Sum_All'Access); Util.Tests.Assert_Equals (T, 1, Sum, "List iterate failed"); for I in 1 .. 100 loop Val.Value := I; List.Append (Val); end loop; -- The list refered to by 'L' should not change. Sum := 0; L.Iterate (Sum_All'Access); Util.Tests.Assert_Equals (T, 1, Sum, "List iterate failed"); -- After getting the list again, we should see the new elements. L := List.Get; Sum := 0; L.Iterate (Sum_All'Access); Util.Tests.Assert_Equals (T, 5051, Sum, "List iterate failed"); Sum := 0; L.Reverse_Iterate (Sum_All'Access); Util.Tests.Assert_Equals (T, 5051, Sum, "List reverse iterate failed"); -- Remove last value. Val.Value := 100; List.Remove (Val); L := List.Get; Sum := 0; L.Iterate (Sum_All'Access); Util.Tests.Assert_Equals (T, 5051 - 100, Sum, "List iterate failed"); -- Remove first value. Val.Value := 1; List.Remove (Val); L := List.Get; Sum := 0; L.Iterate (Sum_All'Access); Util.Tests.Assert_Equals (T, 5051 - 100 - 1, Sum, "List iterate failed"); -- Remove middle value. Val.Value := 50; List.Remove (Val); L := List.Get; Sum := 0; L.Iterate (Sum_All'Access); Util.Tests.Assert_Equals (T, 5051 - 100 - 1 - 50, Sum, "List iterate failed"); end Test_Array; -- ------------------------------ -- Test concurrent aspects of sequences. -- ------------------------------ procedure Test_Concurrent_Sequences (T : in out Test) is Count_By_Task : constant Natural := 60_001; Task_Count : constant Natural := 8; Pool_Count : constant Natural := 23; Last_Sequence : constant Natural := 1_000; Q : Connection_Sequences.Queue; F : Connection_Pool.Pool; S : Util.Measures.Stamp; Seq_Error : Boolean := True; First_Error : Natural := 0; Expect_Seq : Natural := 0; begin Q.Set_Size (Pool_Count * 2); F.Set_Size (Pool_Count); declare -- A task that picks elements and work on them. task type Worker is entry Start; end Worker; task body Worker is begin accept Start do null; end Start; -- Send Cnt values in the queue. loop declare C : Connection; begin F.Get_Instance (C, 3.0); Q.Enqueue (C, C.Value); exit when C.Value = Last_Sequence; end; end loop; exception when Connection_Pool.Timeout => null; when E : others => Log.Error ("Exception raised", E); Ada.Text_IO.Put_Line ("Exception raised."); end Worker; type Worker_Array is array (1 .. Task_Count) of Worker; Producers : Worker_Array; C : Connection; Seq : Natural; Avail : Natural; Next : Natural := 0; begin for I in Producers'Range loop Producers (I).Start; end loop; Seq_Error := False; while Next < Last_Sequence loop F.Get_Available (Avail); if Avail /= Pool_Count and Next - Expect_Seq <= Pool_Count then C.Value := Next; F.Release (C); Next := Next + 1; else Q.Dequeue (C, Seq, 3.0); if Seq /= Expect_Seq then if First_Error = 0 then Ada.Text_IO.Put_Line ("Got" & Natural'Image (Seq) & " expecting" & Natural'Image (Expect_Seq)); First_Error := Seq; end if; Seq_Error := True; end if; Expect_Seq := Seq + 1; end if; end loop; loop Q.Dequeue (C, Seq); if Seq /= Expect_Seq then if First_Error = 0 then First_Error := Seq; end if; Seq_Error := True; end if; Expect_Seq := Seq + 1; exit when Expect_Seq = Last_Sequence - 1; end loop; exception when Connection_Sequences.Timeout => Seq_Error := True; First_Error := Expect_Seq + 1_000_000; end; Util.Measures.Report (S, "Executed Queue+Dequeue " & Natural'Image (Count_By_Task * Task_Count) & " task count: " & Natural'Image (Task_Count)); T.Assert (not Seq_Error, "Incorrect sequences " & Natural'Image (First_Error) & " Expect_Seq=" & Natural'Image (Expect_Seq)); end Test_Concurrent_Sequences; end Util.Concurrent.Tests;
with Disorderly.Random; use Disorderly.Random; with Disorderly.Random.Clock_Entropy; with Chi_Gaussian_CDF; with text_io; use text_io; -- translated from Marsaglia, Tsang diehard suite. procedure gcd_8bytes_1 is Bits_per_Random_Word : constant := 61; -- Must set this correctly here. There's no way to check this. Stream_1 : Disorderly.Random.State; -- Create a stream of Random numbers -- by initializing this after the begin, w/ a call to Reset_with_Calendar type Real is digits 15; package Chi_Analysis is new Chi_Gaussian_CDF (Real); use Chi_Analysis; type Unsigned_64 is mod 2**64; type Statistical_Data is array (Unsigned_64 range <>) of Real; -- Greatest Common Divisor Count test. -- -- 1st test counts No of occurances of GCD's calculated for pairs of Rands: Span_of_GCD_Count_Test : constant := 100; subtype GCD_Count_Test_Range is Unsigned_64 range 1 .. Span_of_GCD_Count_Test; subtype GCD_Counts is Statistical_Data (GCD_Count_Test_Range); True_DOF_for_GCD_Count_Test : constant := Span_of_GCD_Count_Test - 1; -- Greatest Common Divisor Iterations test. -- -- 2nd test counts No of Iterations required to find GCD of a pair of Rands: subtype GCD_Iterations_Test_Range is Unsigned_64 range 7..57; subtype GCD_Iterations_Stats is Statistical_Data (GCD_Iterations_Test_Range); True_DOF_for_Iterations_Test : constant := 50; type Permissable_Range_of_Bits_per_Word is range 61..64; Probability_of_GCD_Iterations : constant array(Permissable_Range_of_Bits_per_Word) of GCD_Iterations_Stats := --61bit, 1.5 * 2^40 sample_size (( 3.60634420876918E-11, 1.84113362237163E-10, 9.27526422816774E-10, 4.18462466610514E-09, 1.79804729945634E-08, 7.02996697762738E-08, 2.50987637707073E-07, 8.29602156401328E-07, 2.54719381463592E-06, 7.29226651500263E-06, 1.95308024083953E-05, 4.90890664008001E-05, 1.16038067220791E-04, 2.58472948031419E-04, 5.43582520786794E-04, 1.08110812383846E-03, 2.03641299373450E-03, 3.63780116996445E-03, 6.16967723370813E-03, 9.94544514548540E-03, 1.52515013444075E-02, 2.22684802100285E-02, 3.09799653111006E-02, 4.10936488194199E-02, 5.20026693911464E-02, 6.28131812491515E-02, 7.24521456393869E-02, 7.98344028653051E-02, 8.40652918002730E-02, 8.46145726650518E-02, 8.14282151139038E-02, 7.49344837759449E-02, 6.59512901418012E-02, 5.55169851045914E-02, 4.47006642858943E-02, 3.44248149624985E-02, 2.53562087328527E-02, 1.78608364057373E-02, 1.20299972414100E-02, 7.74637900821804E-03, 4.76738610228969E-03, 2.80356488466445E-03, 1.57480260911499E-03, 8.44672639884622E-04, 4.32374513247455E-04, 2.11148911267114E-04, 9.83079048835308E-05, 4.36203933887831E-05, 1.84285277298287E-05, 7.40598087482478E-06, 4.38173035787338E-06 ), --62bit, 1.25 * 2^40 sample_size ( 1.0e-11, 1.0e-10, 1.0e-09, 3.12356860376894E-09, 1.07153027784079E-08, 4.23540768679231E-08, 1.53834844240919E-07, 5.18621527589858E-07, 1.62184005603194E-06, 4.72031460958533E-06, 1.28798790683504E-05, 3.29731628880836E-05, 7.93799634266179E-05, 1.80152335087769E-04, 3.86169017292559E-04, 7.83033167681424E-04, 1.50444347600569E-03, 2.74219085113145E-03, 4.74746785839670E-03, 7.81447832123376E-03, 1.22424124856480E-02, 1.82686513180670E-02, 2.59868027780612E-02, 3.52614222552802E-02, 4.56673437729478E-02, 5.64818627550267E-02, 6.67421547936101E-02, 7.53817606542725E-02, 8.14047969237436E-02, 8.40791420108871E-02, 8.30774562251463E-02, 7.85453180062177E-02, 7.10665999366029E-02, 6.15405520489730E-02, 5.10077870050736E-02, 4.04669900148292E-02, 3.07284356771561E-02, 2.23318681637466E-02, 1.55313623552502E-02, 1.03353681937733E-02, 6.57944859049166E-03, 4.00580784917111E-03, 2.33198539935984E-03, 1.29759441624628E-03, 6.89835629600566E-04, 3.50286864704685E-04, 1.69781225849874E-04, 7.85187381552532E-05, 3.46313805493992E-05, 1.45411046105437E-05, 9.24259074963629E-06 ), --63bit ( 1.0e-11, 1.0e-10, 1.0e-09, 1.84718373930082E-09, 6.40193320577964E-09, 2.55613485933282E-08, 9.43073246162385E-08, 3.22844243783039E-07, 1.02684680314269E-06, 3.04464447253850E-06, 8.45538488647435E-06, 2.20202909986256E-05, 5.39864840902737E-05, 1.24805929772265E-04, 2.72558390861377E-04, 5.63293603590864E-04, 1.10343044616456E-03, 2.05119602287595E-03, 3.62303316342150E-03, 6.08702397312300E-03, 9.73696121127432E-03, 1.48417563932526E-02, 2.15752666608751E-02, 2.99300470460366E-02, 3.96473091677763E-02, 5.01783137979146E-02, 6.07052047053003E-02, 7.02302970366873E-02, 7.77271460929115E-02, 8.23192137850128E-02, 8.34508585840013E-02, 8.09940879425994E-02, 7.52742528147792E-02, 6.69985561098656E-02, 5.71142716544273E-02, 4.66340440261774E-02, 3.64706130903869E-02, 2.73180850017525E-02, 1.95966771325402E-02, 1.34618205693187E-02, 8.85359909625550E-03, 5.57415191451582E-03, 3.35856920628430E-03, 1.93597860015871E-03, 1.06730554853129E-03, 5.62642482691444E-04, 2.83431539173762E-04, 1.36380568619643E-04, 6.26575392743689E-05, 2.74562980848714E-05, 1.87182404260966E-05 ), --64bit ( 1.0e-11, 1.0e-10, 1.0e-09, 1.04345316584739E-09, 3.79978802003380E-09, 1.54057084324045E-08, 5.78617295508997E-08, 2.00539862918150E-07, 6.48949814300674E-07, 1.95518324390933E-06, 5.52275103271111E-06, 1.46452957172490E-05, 3.65230218449142E-05, 8.59657468633183E-05, 1.91198751215577E-04, 4.02582168842653E-04, 8.03587449586808E-04, 1.52299020523464E-03, 2.74339848013672E-03, 4.70193459930467E-03, 7.67594423026215E-03, 1.19457277723591E-02, 1.77364065986088E-02, 2.51409167733881E-02, 3.40445156152176E-02, 4.40656369518870E-02, 5.45457989380035E-02, 6.45975542736172E-02, 7.32208271168525E-02, 7.94619972674910E-02, 8.25876607805387E-02, 8.22245617538202E-02, 7.84341962288130E-02, 7.16953611735031E-02, 6.28069448083503E-02, 5.27326066778591E-02, 4.24344945974250E-02, 3.27284291460981E-02, 2.41922337119225E-02, 1.71370716094518E-02, 1.16315170244181E-02, 7.56359276545279E-03, 4.71090568017745E-03, 2.80972215655816E-03, 1.60432155716990E-03, 8.76614772803603E-04, 4.58251069641038E-04, 2.29045271690766E-04, 1.09453786394119E-04, 4.99610013018052E-05, 3.64976355437345E-05) ); -- 2^64 distr based on 1.25 * 2^40 sample size --------------------------------- -- Get_Chi_Statistic_and_P_val -- --------------------------------- procedure Get_Chi_Statistic_and_P_val (Probability_Distribution : in Statistical_Data; Observed_Count : in Statistical_Data; True_Degrees_of_Freedom : in Positive; Sample_Size : in Unsigned_64; Chi_squared : out Real; P_val, P_val_Variance : out Real) is Expected_Count, Sum : Real; begin Sum := 0.0; for i in Probability_Distribution'Range loop Expected_Count := Probability_Distribution(i) * Real (Sample_Size); Sum := Sum + (Observed_Count(i) - Expected_Count)**2 / Expected_Count; end loop; Chi_squared := Sum; P_val := Chi_Squared_CDF (Real (True_Degrees_of_Freedom), Chi_squared); P_val_Variance := (P_val-0.5)**2; end Get_Chi_Statistic_and_P_val; ------------------------------ -- Greatest_Common_Divisors -- ------------------------------ -- from diehard. -- GCD Test, uses pairs of Rand's: u and v -- where pairs = Sample_Size. -- ***Requires uniform rands on 0..2**No_of_Bits_in_Test-1.*** procedure Greatest_Common_Divisors (Sample_Size : in Unsigned_64; Count_of_GCD_Iterations : out GCD_Iterations_Stats) is Observed_Count_of_GCDs : GCD_Counts; s, e : Real; p99, chi99,variance_p99 : Real; ave_chi99, ave_p99, ave_variance_p99 : Real := 0.0; p, chi, variance_p : Real; ave_p, ave_chi, ave_variance_p : Real := 0.0; k : Unsigned_64; u, v, w : Unsigned_64; u0, v0 : Random_Int; No_of_Samples : constant Integer := 2**20; begin Observed_Count_of_GCDs := (others => 0.0); Count_of_GCD_Iterations := (others => 0.0); Outer: for j in 1..No_of_Samples loop Observed_Count_of_GCDs := (others => 0.0); Count_of_GCD_Iterations := (others => 0.0); for i in Unsigned_64 range 1 .. Sample_Size loop Get_Pair: loop Get_Random (u0, Stream_1); Get_Random (v0, Stream_1); u := Unsigned_64 (u0); v := Unsigned_64 (v0); exit Get_Pair when (u > 0 and then v > 0); end loop Get_Pair; k := 0; Euclid: loop w := u mod v; u := v; v := w; k := k + 1; exit Euclid when v = 0; end loop Euclid; -- k is Observed number of Iterations to obtain greatest common divisor (GCD). -- u is the greatest common divisor (GCD). if k < Count_of_GCD_Iterations'First then k := Count_of_GCD_Iterations'First; end if; if k > Count_of_GCD_Iterations'Last then k := Count_of_GCD_Iterations'Last; end if; Count_of_GCD_Iterations(k) := Count_of_GCD_Iterations(k)+1.0; if u > Observed_Count_of_GCDs'Last then u := Observed_Count_of_GCDs'Last; end if; if u < Observed_Count_of_GCDs'First then u := Observed_Count_of_GCDs'First; end if; Observed_Count_of_GCDs(u) := Observed_Count_of_GCDs(u) + 1.0; end loop; Get_Chi_Statistic_and_P_val (Probability_Distribution => Probability_of_GCD_Iterations (Bits_per_Random_Word), Observed_Count => Count_of_GCD_Iterations, True_Degrees_of_Freedom => True_DOF_for_Iterations_Test, Sample_Size => Sample_Size, Chi_squared => chi, P_val => p, P_val_Variance => variance_p); ave_chi := ave_chi + chi; ave_p := ave_p + p; ave_variance_p := ave_variance_p + variance_p; -- on range 1..99 distribution seems to be: (0.607926 + 6.0e-8 * i) / i^2 -- theoretical value, with inf number of bits: 0.60792710 / i^2 -- -- e := Real (Sample_Size) * 0.6081842 / Real (i)**2;--asymptotically, i = 5410 p99 := 0.0; variance_p99 := 0.0; --e := Real (Sample_Size) * 0.61097691e-2; -- in theory, p >> 2**32 e := Real (Sample_Size) * 0.61097e-2; -- I get 0.61097e-2 chi99 := (Observed_Count_of_GCDs(GCD_Count_Test_Range'Last) - e)**2 / e; for i in GCD_Count_Test_Range'First .. GCD_Count_Test_Range'Last-1 loop e := Real (Sample_Size) * (0.607926 + 6.0E-8 * Real (i)) / Real (i)**2; s := (Observed_Count_of_GCDs(i) - e)**2 / e; chi99 := chi99 + s; end loop; p99 := Chi_Squared_CDF (Real(True_DOF_for_GCD_Count_Test), chi99); variance_p99 := (p99-0.5)**2; ave_chi99 := ave_chi99 + chi99; ave_p99 := ave_p99 + p99; ave_variance_p99 := ave_variance_p99 + variance_p99; new_line(1); put("Test"); put (Integer'Image(j)); put(". Chi^2 (47 dof), ave p-val, and ave normalized variance of GCD iterations:"); new_line; put(" "); put (Real'Image (chi)); put (Real'Image (ave_p / Real(j))); put (Real'Image (ave_variance_p / (Real(j)*(0.25/3.0)))); -- should -> 1.0 new_line(1); put(" Chi^2 (99 dof), ave p-val, and ave normalized variance of GCD's:"); new_line; put(" "); put (Real'Image (chi99)); put (Real'Image (ave_p99 / Real(j))); put (Real'Image (ave_variance_p99 / (Real(j)*(0.25/3.0)))); end loop Outer; end Greatest_Common_Divisors; begin Disorderly.Random.Clock_Entropy.Reset (Stream_1); -- The state of the generator is Stream_1. (Starts up a random stream.) test: declare Sample_Size : constant Unsigned_64 := 2**35; -- turn way up to best see failure -- 2**35 Sample_Size is OK, chi squared wise. -- 2**36 Sample_Size is unimpeachable. -- 2**37 Sample_Size is gd stnd tst. Tks mny hrs! Full_Sample_Size : Real; Sample_Iteration_Stats : GCD_Iterations_Stats; Full_Iteration_Stats : GCD_Iterations_Stats := (others => 0.0); begin for i in 1..2**16 loop Greatest_Common_Divisors (Sample_Size, Sample_Iteration_Stats); Full_Sample_Size := Real(i)*Real(Sample_Size); for k in Full_Iteration_Stats'Range loop Full_Iteration_Stats(k) := Full_Iteration_Stats(k) + Sample_Iteration_Stats(k); end loop; new_line; for k in Full_Iteration_Stats'Range loop if (Integer(k)-Integer(Full_Iteration_Stats'First)) mod 3 = 0 then new_line; end if; put (Real'Image (Full_Iteration_Stats(k) / Full_Sample_Size)); put (","); end loop; new_line; end loop; end test; end;
package body Peak is function Max (X,Y : Float) return Float is R : Float; begin if X >= Y then R := X; else R := Y; end if; return R; end Max; procedure Coeffs (Y1,Y2,Y3 : in Float; A,B,C : out Float) is begin A := -- 0.5*(Y1-2*Y2+Y3) PolyPaver.Floats.Multiply( 0.5, PolyPaver.Floats.Add( Y1, PolyPaver.Floats.Add( PolyPaver.Floats.Multiply(-2.0,Y2), Y3))); B := -- 0.5*(Y3-Y1) PolyPaver.Floats.Multiply(0.5,PolyPaver.Floats.Add(y3,-y1)); C := Y2; end Coeffs; function PeakQ (A,B,C,X : in Float) return Float is Ghost : Float; begin Ghost := PolyPaver.Floats.Add( A, PolyPaver.Floats.Add(X,-X)); return PolyPaver.Floats.Add( C, -PolyPaver.Floats.Divide( PolyPaver.Floats.Multiply(B,B), PolyPaver.Floats.Multiply(4.0,Ghost))); end PeakQ; function PeakUnit (Y1,Y2,Y3 : Float) return Float is A,B,C,M1,M2,R : Float; begin M1 := Max(Y1,Y3); Coeffs(Y1,Y2,Y3,A,B,C); if A < -0.05 and PolyPaver.Floats.Multiply(2.0,A) <= B and B <= PolyPaver.Floats.Multiply(-2.0,A) then -- poly has peak within [-1,1] R := Max(M1,PeakQ(A,B,C,0.0)); else R := M1; end if; return R; end PeakUnit; end Peak;
package body Intcode.Op is use type Memory.Value; function Instruction_Size(Instruction: Code) return Natural is (case Instruction is when Add|Mul => 3, when Get|Put|Mrb => 1, when Jnz|Jz => 2, when Lt|Eq => 3, when Halt => 1); function Get_Code(V: Memory.Value) return Code is begin case V is when 1 => return Add; when 2 => return Mul; when 3 => return Get; when 4 => return Put; when 5 => return Jnz; when 6 => return Jz; when 7 => return Lt; when 8 => return Eq; when 9 => return Mrb; when 99 => return Halt; when others => raise Constraint_Error with "unknown op code" & V'Image; end case; end Get_Code; function Decode(V: Memory.Value) return Schema is I: constant Code := Get_Code(V mod 100); Size: constant Natural := Instruction_Size(I); Result: Schema := (Num_Params => Size, Instruction => I, Params => (others => Position)); W: Memory.Value := V / 100; begin for I in Result.Params'Range loop Result.Params(I) := (case W mod 10 is when 0 => Position, when 1 => Immediate, when 2 => Relative, when others => raise Constraint_Error with "unknown mode"); W := W / 10; end loop; return Result; end Decode; end Intcode.Op;
with Interfaces; use Interfaces; package STM32.F4.GPIO is pragma Pure; subtype Port_Bit_Number is Natural range 0 .. 15; -- MODER type Port_Mode is ( Input_Mode, Output_Mode, Alternate_Mode, Analog_mode ) with Size => 2; for Port_Mode use ( Input_Mode => 2#00#, Output_Mode => 2#01#, Alternate_Mode => 2#10#, Analog_Mode => 2#11# ); type Port_Mode_Register is array(Port_Bit_Number) of Port_Mode with Pack, Size => 32; -- OTYPER type Output_Type is ( Push_Pull_Type, Open_Low_Type ) with Size => 1; for Output_Type use ( Push_Pull_Type => 2#0#, Open_Low_Type => 2#1# ); pragma Warnings(Off, "16 bits of ""Output_Type_Register"" unused"); type Output_Type_Register is array(Port_Bit_Number) of Output_Type with Pack, Size => 32; pragma Warnings(On, "16 bits of ""Output_Type_Register"" unused"); -- OSPEEDR type Output_Speed is ( Low_Speed, -- 50pF ---100--- ns Medium_Speed, -- 50pF 20 10 6 ns High_Speed, -- 40pF 10 6 4 ns Very_High_Speed -- 30pF 6 4 2.5ns ) with Size => 2; for Output_Speed use ( Low_Speed => 2#00#, Medium_Speed => 2#01#, High_Speed => 2#10#, Very_High_Speed => 2#11# ); type Output_Speed_Register is array(Port_Bit_Number) of Output_Speed with Pack, Size => 32; -- PUPDR type Port_Pull is ( No_Pull, Pull_Up, Pull_Down ) with Size => 2; for Port_Pull use ( No_Pull => 2#00#, Pull_Up => 2#01#, Pull_Down => 2#10# ); type Port_Pull_Register is array(Port_Bit_Number) of Port_Pull with Pack, Size => 32; -- BSRR type Bit_Set_Reset_Register is record BS: Unsigned_16; BR: Unsigned_16; end record with Size => 32; for Bit_Set_Reset_Register use record BS at 0 range 0 .. 15; BR at 0 range 16 .. 31; end record; -- LCKR type Lock_Bit_Array is array (Port_Bit_Number) of Boolean with Pack, Size => 16; type Configuration_Lock_Register is record LCK: Lock_Bit_Array; LCKK: Boolean; end record with Size => 32; for Configuration_Lock_Register use record LCK at 0 range 0 .. 15; LCKK at 0 range 16 .. 16; end record; -- AFRL/AFRH type Alternate_Function is mod 16; package Alternate_Functions is -- AFL constants SYS : constant Alternate_Function := 0; TIM1 : constant Alternate_Function := 1; TIM2 : constant Alternate_Function := 1; TIM3 : constant Alternate_Function := 2; TIM4 : constant Alternate_Function := 2; TIM5 : constant Alternate_Function := 2; TIM8 : constant Alternate_Function := 3; TIM9 : constant Alternate_Function := 3; TIM10 : constant Alternate_Function := 3; TIM11 : constant Alternate_Function := 3; I2C1 : constant Alternate_Function := 4; I2C2 : constant Alternate_Function := 4; I2C3 : constant Alternate_Function := 4; SPI1 : constant Alternate_Function := 5; SPI2 : constant Alternate_Function := 5; I2S2 : constant Alternate_Function := 5; I2S2Ext : constant Alternate_Function := 5; SPI3 : constant Alternate_Function := 6; I2SExt : constant Alternate_Function := 6; I2S3 : constant Alternate_Function := 6; USART1 : constant Alternate_Function := 7; USART2 : constant Alternate_Function := 7; USART3 : constant Alternate_Function := 7; I2S3Ext : constant Alternate_Function := 7; UART4 : constant Alternate_Function := 8; UART5 : constant Alternate_Function := 8; USART6 : constant Alternate_Function := 8; CAN1 : constant Alternate_Function := 9; CAN2 : constant Alternate_Function := 9; TIM12 : constant Alternate_Function := 9; TIM13 : constant Alternate_Function := 9; TIM14 : constant Alternate_Function := 9; OTG_FS : constant Alternate_Function := 10; OTG_HS : constant Alternate_Function := 10; ETH : constant Alternate_Function := 11; FSMC : constant Alternate_Function := 12; SDIO : constant Alternate_Function := 12; OTG_FS_B : constant Alternate_Function := 12; DCMI : constant Alternate_Function := 13; EVENTOUT : constant Alternate_Function := 15; end Alternate_Functions; type Alternate_Function_Register is array (0 .. 15) of Alternate_Function with Pack, Size => 64; type GPIO_Registers is record MODER: Port_Mode_Register; OTYPER: Output_Type_Register; OSPEEDR: Output_Speed_Register; PUPDR: Port_Pull_Register; IDR: Interfaces.Unsigned_32; ODR: Interfaces.Unsigned_32; BSRR: Bit_Set_Reset_Register; LCKR: Configuration_Lock_Register; AFR: Alternate_Function_Register; end record with Volatile; for GPIO_Registers use record MODER at 16#00# range 0 .. 31; OTYPER at 16#04# range 0 .. 31; OSPEEDR at 16#08# range 0 .. 31; PUPDR at 16#0C# range 0 .. 31; IDR at 16#10# range 0 .. 31; ODR at 16#14# range 0 .. 31; BSRR at 16#18# range 0 .. 31; LCKR at 16#1C# range 0 .. 31; AFR at 16#20# range 0 .. 63; end record; end STM32.F4.GPIO;
with AWS.Response; with AWS.Server; with AWS.Services.Dispatchers.Linker; with AWS.Services.Dispatchers.URI; with AWS.Status; with AWS.Config; with AWS.Resources.Streams; with Ada.Streams; with AWS.Resources.Streams.Memory; package Download_Manager is use AWS; use Ada.Streams; function CB (Request : Status.Data) return Response.Data; procedure Create_Filename; Filename : constant String := "dm_file.data"; URI : Services.Dispatchers.URI.Handler; Handler : Services.Dispatchers.Linker.Handler; Conf : Config.Object := Config.Get_Current; WS : Server.HTTP; type Pump_Stream is limited new AWS.Resources.Streams.Memory.Stream_Type with private; procedure Open (S : in out Pump_Stream); overriding function End_Of_File (Resource : Pump_Stream) return Boolean; overriding procedure Read (Resource : in out Pump_Stream; Buffer : out Stream_Element_Array; Last : out Stream_Element_Offset); overriding procedure Close (Resource : in out Pump_Stream); overriding procedure Reset (Resource : in out Pump_Stream) is null; overriding procedure Set_Index (Resource : in out Pump_Stream; To : Stream_Element_Offset) is null; private not overriding procedure Real_Read (Resource : in out Pump_Stream; Buffer : out Stream_Element_Array; Last : out Stream_Element_Offset); type Pump_Stream is limited new AWS.Resources.Streams.Memory.Stream_Type with record Is_Open : Boolean := False; end record; end;
with -- AdaM.Source, AdaM.Entity, gtk.Widget; package aIDE.Editor is type Item is abstract tagged private; type View is access all Item'Class; -- function to_Editor (Target : in AdaM.Source.Entity_view) return Editor.view; function to_Editor (Target : in AdaM.Entity.view) return Editor.view; function top_Widget (Self : in Item) return gtk.Widget.Gtk_Widget; procedure freshen (Self : in out Item) is null; private type Item is abstract tagged record null; end record; end aIDE.Editor;
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Web Framework -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014-2021, Vadim Godunko <vgodunko@gmail.com> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with Ada.Unchecked_Deallocation; package body Matreshka.Servlet_Dispatchers is use type Matreshka.Servlet_Registrations.Servlet_Registration_Access; Solidus : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("/"); Asterisk_Full_Stop : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("*."); Solidus_Asterisk : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("/*"); procedure Free is new Ada.Unchecked_Deallocation (Abstract_Dispatcher'Class, Dispatcher_Access); ----------------- -- Add_Mapping -- ----------------- procedure Add_Mapping (Self : not null access Context_Dispatcher'Class; Servlet : not null Matreshka.Servlet_Registrations.Servlet_Registration_Access; URL_Pattern : League.Strings.Universal_String; Success : out Boolean) is use type League.Strings.Universal_String; begin Success := False; if URL_Pattern.Is_Empty then -- Exact map to application's context root. if Self.Root_Servlet = null then Self.Root_Servlet := Servlet; Success := True; end if; elsif URL_Pattern = Solidus then -- "Default" servlet of the application. if Self.Default_Servlet = null then Self.Default_Servlet := Servlet; Success := True; end if; elsif URL_Pattern.Starts_With (Asterisk_Full_Stop) then -- Extension mapping. declare Extension : constant League.Strings.Universal_String := URL_Pattern.Tail_From (3); begin if not Extension.Is_Empty and then Extension.Index ('.') = 0 and then not Self.Extension_Servlets.Contains (Extension) then -- Extension should not be empty string, extension should not -- contains '.' character and should not be mapped already. Self.Extension_Servlets.Insert (Extension, Servlet); Success := True; end if; end; elsif URL_Pattern.Starts_With (Solidus) then -- Path mapping. declare Is_Pattern : constant Boolean := URL_Pattern.Ends_With (Solidus_Asterisk); URL : constant League.Strings.Universal_String := (if Is_Pattern then URL_Pattern.Head (URL_Pattern.Length - 2) else URL_Pattern); Path : League.String_Vectors.Universal_String_Vector := URL.Split ('/', League.Strings.Skip_Empty); Index : Positive := 1; Current : Dispatcher_Access; Parent : Dispatcher_Access := Self.all'Unchecked_Access; Aux : Dispatcher_Access; Position : Dispatcher_Maps.Cursor; begin if URL_Pattern.Ends_With (Solidus) then Path.Append (League.Strings.Empty_Universal_String); end if; loop Position := Segment_Dispatcher'Class (Parent.all).Children.Find (Path (Index)); if Dispatcher_Maps.Has_Element (Position) then Current := Dispatcher_Maps.Element (Position); else -- Current segment of path is not mapped to dispatcher, -- allocate new dispatcher. if Index = Path.Length then Current := new Servlet_Dispatcher; else Current := new Segment_Dispatcher; end if; Segment_Dispatcher'Class (Parent.all).Children.Insert (Path (Index), Current); end if; if Index = Path.Length then if Current.all not in Servlet_Dispatcher'Class then -- Change type of current dispatcher to servant -- dispatcher. Aux := Current; Current := new Servlet_Dispatcher' (Children => Segment_Dispatcher'Class (Aux.all).Children, others => <>); Segment_Dispatcher'Class (Parent.all).Children.Replace_Element (Position, Current); Free (Aux); end if; if Is_Pattern then if Servlet_Dispatcher'Class (Current.all).Mapping_Servlet = null then Servlet_Dispatcher'Class (Current.all).Mapping_Servlet := Servlet; Success := True; end if; else if Servlet_Dispatcher'Class (Current.all).Exact_Servlet = null then Servlet_Dispatcher'Class (Current.all).Exact_Servlet := Servlet; Success := True; end if; end if; exit; end if; -- Go to next segment. Parent := Current; Current := null; Index := Index + 1; Position := Dispatcher_Maps.No_Element; end loop; end; end if; end Add_Mapping; -------------- -- Dispatch -- -------------- overriding procedure Dispatch (Self : not null access constant Context_Dispatcher; Request : in out Matreshka.Servlet_HTTP_Requests.Abstract_HTTP_Servlet_Request'Class; Path : League.String_Vectors.Universal_String_Vector; Index : Positive; Servlet : in out Matreshka.Servlet_Registrations.Servlet_Registration_Access) is Servlet_Found : Boolean := False; -- Sets to True when servlet is found by this subprogram, but not by -- call to inherited one. begin if Path.Length < Index or (Path.Length = Index and Path (Index).Is_Empty) then -- Exact match of root, use root servlet when available; otherwise -- use default servlet. if Self.Root_Servlet /= null then Servlet := Self.Root_Servlet; Servlet_Found := True; elsif Self.Default_Servlet /= null then Servlet := Self.Default_Servlet; Servlet_Found := True; end if; else -- Call inherited subprogram to lookup exact servlet or longest -- path-prefix. Segment_Dispatcher (Self.all).Dispatch (Request, Path, Index, Servlet); if Servlet = null then -- Lookup servlet using extension mapping. declare Last_Segment : constant League.Strings.Universal_String := Path (Path.Length); Full_Stop_Position : constant Natural := Last_Segment.Last_Index ('.'); Position : constant Extension_Maps.Cursor := (if Full_Stop_Position /= 0 then Self.Extension_Servlets.Find (Last_Segment.Tail_From (Full_Stop_Position + 1)) else Extension_Maps.No_Element); begin if Extension_Maps.Has_Element (Position) then Servlet := Extension_Maps.Element (Position); Servlet_Found := True; end if; end; end if; if Servlet = null then -- Use application's default servlet. Servlet := Self.Default_Servlet; Servlet_Found := True; end if; end if; -- Set indices of last segment of context and servlet paths. if Servlet /= null then Request.Set_Context_Last_Segment (Index - 1); if Servlet_Found then Request.Set_Servlet_Last_Segment (Index - 1); end if; end if; end Dispatch; -------------- -- Dispatch -- -------------- overriding procedure Dispatch (Self : not null access constant Segment_Dispatcher; Request : in out Matreshka.Servlet_HTTP_Requests.Abstract_HTTP_Servlet_Request'Class; Path : League.String_Vectors.Universal_String_Vector; Index : Positive; Servlet : in out Matreshka.Servlet_Registrations.Servlet_Registration_Access) is begin if Path.Length < Index then -- Looked path is exactly what this (simple) dispatcher handles. -- Request for this path should be processed in another way by one of -- parent dispatchers. null; else declare Position : constant Dispatcher_Maps.Cursor := Self.Children.Find (Path (Index)); begin if Dispatcher_Maps.Has_Element (Position) then Dispatcher_Maps.Element (Position).Dispatch (Request, Path, Index + 1, Servlet); end if; end; end if; end Dispatch; -------------- -- Dispatch -- -------------- overriding procedure Dispatch (Self : not null access constant Servlet_Dispatcher; Request : in out Matreshka.Servlet_HTTP_Requests.Abstract_HTTP_Servlet_Request'Class; Path : League.String_Vectors.Universal_String_Vector; Index : Positive; Servlet : in out Matreshka.Servlet_Registrations.Servlet_Registration_Access) is begin if Path.Length < Index then -- Exact match, use exact match servlet when available. if Self.Exact_Servlet /= null then Servlet := Self.Exact_Servlet; Request.Set_Servlet_Last_Segment (Index - 1); end if; else -- Call inherited subprogram to lookup exact servlet or longest -- path-prefix. Segment_Dispatcher (Self.all).Dispatch (Request, Path, Index, Servlet); end if; if Servlet = null then -- Exact or longest path-prefix servlet was not found; use path -- mapping servlet when available for current path-prefix. if Self.Mapping_Servlet /= null then Servlet := Self.Mapping_Servlet; Request.Set_Servlet_Last_Segment (Index - 1); end if; end if; end Dispatch; end Matreshka.Servlet_Dispatchers;
package Generator is type Generator is tagged private; procedure Reset (Gen : in out Generator); function Get_Next (Gen : access Generator) return Natural; type Generator_Function is access function (X : Natural) return Natural; procedure Set_Generator_Function (Gen : in out Generator; Func : Generator_Function); procedure Skip (Gen : access Generator'Class; Count : Positive := 1); private function Identity (X : Natural) return Natural; type Generator is tagged record Last_Source : Natural := 0; Last_Value : Natural := 0; Gen_Func : Generator_Function := Identity'Access; end record; end Generator;
with Ada.Strings.Bounded; package Randomise is package R_String is new Ada.Strings.Bounded.Generic_Bounded_Length(80); procedure Randomise_String(S : in out R_String.Bounded_String); end Randomise;
-------------------------------------------------------------------------------- -- MIT License -- -- Copyright (c) 2020 Zane Myers -- -- 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 Vulkan.Math.Vec2; with Vulkan.Math.Vec4; with Vulkan.Math.Uvec2; use Vulkan.Math.Vec2; use Vulkan.Math.Vec4; use Vulkan.Math.Uvec2; -------------------------------------------------------------------------------- --< @group Vulkan Math Functions -------------------------------------------------------------------------------- --< @summary --< This package provides GLSL Floating Point Packing and Unpacking functions. --< --< @description --< All floating point pack and unpack functions op -------------------------------------------------------------------------------- package Vulkan.Math.Packing is pragma Preelaborate; pragma Pure; ---------------------------------------------------------------------------- -- Normalized Vector Packing and Unpacking Functions ---------------------------------------------------------------------------- --< @summary --< This operation packs a normalized Vkm_Vec2 with unsigned components into --< a 32-bit unsigned integer. --< --< @description --< Each component of the unsigned normalized input Vkm_Vec2 is packed into --< an 16-bit bitfield of an unsigned integer. --< --< The following conversion function is used to transform each floating --< point component into an 16-bit bitfield, where c is a component of the vector: --< --< uint16_c := round( clamp ( c, 0, 1) * 65535.0) --< --< The packed vector is formatted as follows in the unsigned integer: --< bits | 31 30 ... 17 16 | 15 14 ... 1 0 | --< component | y | x | --< --< @param vector --< The normalized Vkm_Vec2 value to pack into an unsigned integer. --< --< @return --< The unsigned integer value. ---------------------------------------------------------------------------- function Pack_Unsigned_Normalized_2x16( vector : in Vkm_Vec2) return Vkm_Uint; ---------------------------------------------------------------------------- --< @summary --< This operation packs a normalized Vkm_Vec2 with signed components into --< a 32-bit unsigned integer. --< --< @description --< Each component of the signed normalized input Vkm_Vec2 is packed into --< an 16-bit bitfield of an unsigned integer. --< --< The following conversion function is used to transform each floating --< point component into an 16-bit bitfield, where c is a component of the vector: --< --< int16_c := round( clamp ( c, -1, 1) * 32767.0) --< --< The packed vector is formatted as follows in the unsigned integer: --< bits | 31 30 ... 17 16 | 15 14 ... 1 0 | --< component | y | x | --< --< @param vector --< The normalized Vkm_Vec2 value to pack into an unsigned integer. --< --< @return --< The unsigned integer value. ---------------------------------------------------------------------------- function Pack_Signed_Normalized_2x16( vector : in Vkm_Vec2) return Vkm_Uint; ---------------------------------------------------------------------------- --< @summary --< This operation packs a normalized Vkm_Vec4 with unsigned components into --< a 32-bit unsigned integer. --< --< @description --< Each component of the unsigned normalized input Vkm_Vec4 is packed into --< an 8-bit bitfield of an unsigned integer. --< --< The following conversion function is used to transform each floating --< point component into an 8-bit bitfield, where c is a component of the vector: --< --< uint8_c := round( clamp ( c, 0, 1) * 255.0) --< --< The packed vector is formatted as follows in the unsigned integer: --< bits | 31 ... 24 | 23 ... 16 | 15 ... 8 | 7 ... 0 | --< component | w | z | y | x | --< --< @param vector --< The normalized Vkm_Vec4 value to pack into an unsigned integer. --< --< @return --< The unsigned integer value. ---------------------------------------------------------------------------- function Pack_Unsigned_Normalized_4x8( vector : in Vkm_Vec4) return Vkm_Uint; ---------------------------------------------------------------------------- --< @summary --< This operation packs a normalized Vkm_Vec4 with signed components into --< a 32-bit unsigned integer. --< --< @description --< Each component of the signed normalized input Vkm_Vec4 is packed into --< an 8-bit bitfield of an unsigned integer. --< --< The following conversion function is used to transform each floating --< point component into an 8-bit bitfield, where c is a component of the vector: --< --< int8_c := round( clamp ( c, -1, 1) * 127.0) --< --< The packed vector is formatted as follows in the unsigned integer: --< bits | 31 ... 24 | 23 ... 16 | 15 ... 8 | 7 ... 0 | --< component | w | z | y | x | --< --< @param vector --< The normalized Vkm_Vec4 value to pack into an unsigned integer. --< --< @return --< The unsigned integer value. ---------------------------------------------------------------------------- function Pack_Signed_Normalized_4x8( vector : in Vkm_Vec4) return Vkm_Uint; ---------------------------------------------------------------------------- --< @summary --< This operation unpacks a normalized Vkm_Vec2 with unsigned components from --< a 32-bit unsigned integer. --< --< @description --< Each component of the unsigned normalized output Vkm_Vec2 is unpacked from --< a 16-bit bitfield of an unsigned integer. --< --< The unpacked vector is extracted as follows from the unsigned integer: --< bits | 31 30 ... 17 16 | 15 14 ... 1 0 | --< component | y | x | --< --< The following conversion function is used to transform each 16-bit --< bitfield into a floating point value, where c is a component of the vector, --< and uint16_c is the 16-bit packed component: --< --< c := uint16_c / 65535.0 --< --< @param packed --< The unsigned integer that contains the packed Vkm_Vec2. --< --< @return --< The unpacked signed normalized Vkm_Vec2 value. ---------------------------------------------------------------------------- function Unpack_Unsigned_Normalized_2x16( packed : in Vkm_Uint) return Vkm_Vec2; ---------------------------------------------------------------------------- --< @summary --< This operation unpacks a normalized Vkm_Vec2 with signed components from --< a 32-bit unsigned integer. --< --< @description --< Each component of the signed normalized output Vkm_Vec2 is unpacked from --< a 16-bit bitfield of an unsigned integer. --< --< The unpacked vector is extracted as follows from the unsigned integer: --< bits | 31 30 ... 17 16 | 15 14 ... 1 0 | --< component | y | x | --< --< The following conversion function is used to transform each 16-bit --< bitfield into a floating point value, where c is a component of the vector, --< and uint16_c is the 16-bit packed component: --< --< c := clamp(uint16_c / 32767.0, -1, 1) --< --< @param packed --< The unsigned integer that contains the packed Vkm_Vec2. --< --< @return --< The unpacked signed normalized Vkm_Vec2 value. ---------------------------------------------------------------------------- function Unpack_Signed_Normalized_2x16( packed : in Vkm_Uint) return Vkm_Vec2; ---------------------------------------------------------------------------- --< @summary --< This operation unpacks a normalized Vkm_Vec4 with unsigned components from --< a 32-bit unsigned integer. --< --< @description --< Each component of the unsigned normalized output Vkm_Vec4 is unpacked from --< an 8-bit bitfield of an unsigned integer. --< --< The unpacked vector is extracted as follows from the unsigned integer: --< bits | 31 ... 24 | 23 ... 16 | 15 ... 8 | 7 ... 0 | --< component | w | z | y | x | --< --< The following conversion function is used to transform each 8-bit --< bitfield into a floating point value, where c is a component of the vector, --< and uint8_c is the 8-bit packed component: --< --< c := uint8_c / 256.0 --< --< @param packed --< The unsigned integer that contains the packed Vkm_Vec4. --< --< @return --< The unpacked unsigned normalized Vkm_Vec4 value. ---------------------------------------------------------------------------- function Unpack_Unsigned_Normalized_4x8( packed : in Vkm_Uint) return Vkm_Vec4; ---------------------------------------------------------------------------- --< @summary --< This operation unpacks a normalized Vkm_Vec4 with signed components from --< a 32-bit unsigned integer. --< --< @description --< Each component of the signed normalized output Vkm_Vec4 is unpacked from --< an 8-bit bitfield of an unsigned integer. --< --< The unpacked vector is extracted as follows from the unsigned integer: --< bits | 31 ... 24 | 23 ... 16 | 15 ... 8 | 7 ... 0 | --< component | w | z | y | x | --< --< The following conversion function is used to transform each 8-bit --< bitfield into a floating point value, where c is a component of the vector, --< and uint8_c is the 8-bit packed component: --< --< c := clamp(uint8_c / 127.0, -1, 1) --< --< @param packed --< The unsigned integer that contains the packed Vkm_Vec4. --< --< @return --< The unpacked signed normalized Vkm_Vec4 value. ---------------------------------------------------------------------------- function Unpack_Signed_Normalized_4x8( packed : in Vkm_Uint) return Vkm_Vec4; ---------------------------------------------------------------------------- -- Half-Float packing and unpacking functions ---------------------------------------------------------------------------- --< @summary --< This operation packs components of a Vkm_Vec2 as half-floats into --< a 32-bit unsigned integer. --< --< @description --< Each component of the Vkm_Vec2 is converted to a half-precision floating --< point number and then packed into a 16-bit field of an unsigned integer. --< --< The floating point representations are shown below for reference: --< --< bits | Sign | Exponent | Significand | --< Half-Float | 15 | 14 .. 10 | 9 .. 0 | --< Single-Float | 31 | 30 .. 23 | 22 .. 0 | --< --< Conversion is performed by copying the least significant bits of the fields --< of the single-precision floating point number to the corresponding fields --< of the half-precision floating point number. --< --< The vector is packed as follows into the unsigned integer: --< bits | 31 30 ... 17 16 | 15 14 ... 1 0 | --< component | y | x | --< --< @param vector --< The Vkm_Vec2 vector that is packed into the Vkm_Uint. --< --< @return --< The Vkm_Uint that contains the packed vector. ---------------------------------------------------------------------------- function Pack_Half_2x16( vector : in Vkm_Vec2) return Vkm_Uint; ---------------------------------------------------------------------------- --< @summary --< This operation upacks a Vkm_Vec2 vector from an unsigned integer. --< --< @description --< Each component of the Vkm_Vec2 is converted from a half-precision floating --< point number after being unpacked from a 16-bit field of an unsigned integer. --< --< The packed vector is extracted as follows from the unsigned integer: --< bits | 31 30 ... 17 16 | 15 14 ... 1 0 | --< component | y | x | --< --< The floating point representations are shown below for reference: --< --< Fields | Sign | Exponent | Significand | --< Half-Float | 15 | 14 .. 10 | 9 .. 0 | --< Single-Float | 31 | 30 .. 23 | 22 .. 0 | --< --< Conversion is performed by copying the fields of the half-precision --< floating point number to the least significant bits of the corresponding --< fields of the single-precision floating point number. --< --< @param packed --< The Vkm_Uint that contains the packed vector. --< --< @return --< The unpacked Vkm_Vec2. ---------------------------------------------------------------------------- function Unpack_Half_2x16( packed : in Vkm_Uint) return Vkm_Vec2; ---------------------------------------------------------------------------- -- Douple packing and unpacking functions ---------------------------------------------------------------------------- --< @summary --< This operation packs a Vkm_Uvec2 into a 64-bit Vkm_Double value. --< --< @description --< Each component of the Vkm_Uvec2 input is packed into a 32-bit bitfield --< of a Vkm_Double. --< --< The Vkm_Uvec2 is packed into the Vkm_Double as follows: --< bits | 63 62 ... 33 32 | 31 30 ... 1 0 | --< component | y | x | --< --< @param vector --< The Vkm_Uvec2 vector that is packed into the double. --< --< @return --< The Vkm_Double that contains the packed Vkm_Uvec2 value. ---------------------------------------------------------------------------- function Pack_Double_2x32( vector : in Vkm_Uvec2) return Vkm_Double; ---------------------------------------------------------------------------- --< @summary --< This operation unpacks a Vkm_Uvec2 from a 64-bit Vkm_Double value. --< --< @description --< Each component of the Vkm_Uvec2 output is unpacked from a 32-bit bitfield --< of a Vkm_Double. --< --< The Vkm_Uvec2 is unpacked from the Vkm_Double as follows: --< bits | 63 62 ... 33 32 | 31 30 ... 1 0 | --< component | y | x | --< --< @param packed --< The Vkm_Double that contains the packed Vkm_Uvec2. --< --< @return --< The Vkm_Uvec2 unpacked from the Vkm_Double. ---------------------------------------------------------------------------- function Unpack_Double_2x32( packed : in Vkm_Double) return Vkm_Uvec2; end Vulkan.Math.Packing;
-- This spec has been automatically generated from STM32L0x3.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with HAL; with System; package STM32_SVD.DMA is pragma Preelaborate; --------------- -- Registers -- --------------- -- interrupt status register type ISR_Register is record -- Read-only. Channel x global interrupt flag (x = 1 ..7) GIF1 : Boolean; -- Read-only. Channel x transfer complete flag (x = 1 ..7) TCIF1 : Boolean; -- Read-only. Channel x half transfer flag (x = 1 ..7) HTIF1 : Boolean; -- Read-only. Channel x transfer error flag (x = 1 ..7) TEIF1 : Boolean; -- Read-only. Channel x global interrupt flag (x = 1 ..7) GIF2 : Boolean; -- Read-only. Channel x transfer complete flag (x = 1 ..7) TCIF2 : Boolean; -- Read-only. Channel x half transfer flag (x = 1 ..7) HTIF2 : Boolean; -- Read-only. Channel x transfer error flag (x = 1 ..7) TEIF2 : Boolean; -- Read-only. Channel x global interrupt flag (x = 1 ..7) GIF3 : Boolean; -- Read-only. Channel x transfer complete flag (x = 1 ..7) TCIF3 : Boolean; -- Read-only. Channel x half transfer flag (x = 1 ..7) HTIF3 : Boolean; -- Read-only. Channel x transfer error flag (x = 1 ..7) TEIF3 : Boolean; -- Read-only. Channel x global interrupt flag (x = 1 ..7) GIF4 : Boolean; -- Read-only. Channel x transfer complete flag (x = 1 ..7) TCIF4 : Boolean; -- Read-only. Channel x half transfer flag (x = 1 ..7) HTIF4 : Boolean; -- Read-only. Channel x transfer error flag (x = 1 ..7) TEIF4 : Boolean; -- Read-only. Channel x global interrupt flag (x = 1 ..7) GIF5 : Boolean; -- Read-only. Channel x transfer complete flag (x = 1 ..7) TCIF5 : Boolean; -- Read-only. Channel x half transfer flag (x = 1 ..7) HTIF5 : Boolean; -- Read-only. Channel x transfer error flag (x = 1 ..7) TEIF5 : Boolean; -- Read-only. Channel x global interrupt flag (x = 1 ..7) GIF6 : Boolean; -- Read-only. Channel x transfer complete flag (x = 1 ..7) TCIF6 : Boolean; -- Read-only. Channel x half transfer flag (x = 1 ..7) HTIF6 : Boolean; -- Read-only. Channel x transfer error flag (x = 1 ..7) TEIF6 : Boolean; -- Read-only. Channel x global interrupt flag (x = 1 ..7) GIF7 : Boolean; -- Read-only. Channel x transfer complete flag (x = 1 ..7) TCIF7 : Boolean; -- Read-only. Channel x half transfer flag (x = 1 ..7) HTIF7 : Boolean; -- Read-only. Channel x transfer error flag (x = 1 ..7) TEIF7 : Boolean; -- unspecified Reserved_28_31 : HAL.UInt4; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for ISR_Register use record GIF1 at 0 range 0 .. 0; TCIF1 at 0 range 1 .. 1; HTIF1 at 0 range 2 .. 2; TEIF1 at 0 range 3 .. 3; GIF2 at 0 range 4 .. 4; TCIF2 at 0 range 5 .. 5; HTIF2 at 0 range 6 .. 6; TEIF2 at 0 range 7 .. 7; GIF3 at 0 range 8 .. 8; TCIF3 at 0 range 9 .. 9; HTIF3 at 0 range 10 .. 10; TEIF3 at 0 range 11 .. 11; GIF4 at 0 range 12 .. 12; TCIF4 at 0 range 13 .. 13; HTIF4 at 0 range 14 .. 14; TEIF4 at 0 range 15 .. 15; GIF5 at 0 range 16 .. 16; TCIF5 at 0 range 17 .. 17; HTIF5 at 0 range 18 .. 18; TEIF5 at 0 range 19 .. 19; GIF6 at 0 range 20 .. 20; TCIF6 at 0 range 21 .. 21; HTIF6 at 0 range 22 .. 22; TEIF6 at 0 range 23 .. 23; GIF7 at 0 range 24 .. 24; TCIF7 at 0 range 25 .. 25; HTIF7 at 0 range 26 .. 26; TEIF7 at 0 range 27 .. 27; Reserved_28_31 at 0 range 28 .. 31; end record; -- interrupt flag clear register type IFCR_Register is record -- Write-only. Channel x global interrupt clear (x = 1 ..7) CGIF1 : Boolean := False; -- Write-only. Channel x transfer complete clear (x = 1 ..7) CTCIF1 : Boolean := False; -- Write-only. Channel x half transfer clear (x = 1 ..7) CHTIF1 : Boolean := False; -- Write-only. Channel x transfer error clear (x = 1 ..7) CTEIF1 : Boolean := False; -- Write-only. Channel x global interrupt clear (x = 1 ..7) CGIF2 : Boolean := False; -- Write-only. Channel x transfer complete clear (x = 1 ..7) CTCIF2 : Boolean := False; -- Write-only. Channel x half transfer clear (x = 1 ..7) CHTIF2 : Boolean := False; -- Write-only. Channel x transfer error clear (x = 1 ..7) CTEIF2 : Boolean := False; -- Write-only. Channel x global interrupt clear (x = 1 ..7) CGIF3 : Boolean := False; -- Write-only. Channel x transfer complete clear (x = 1 ..7) CTCIF3 : Boolean := False; -- Write-only. Channel x half transfer clear (x = 1 ..7) CHTIF3 : Boolean := False; -- Write-only. Channel x transfer error clear (x = 1 ..7) CTEIF3 : Boolean := False; -- Write-only. Channel x global interrupt clear (x = 1 ..7) CGIF4 : Boolean := False; -- Write-only. Channel x transfer complete clear (x = 1 ..7) CTCIF4 : Boolean := False; -- Write-only. Channel x half transfer clear (x = 1 ..7) CHTIF4 : Boolean := False; -- Write-only. Channel x transfer error clear (x = 1 ..7) CTEIF4 : Boolean := False; -- Write-only. Channel x global interrupt clear (x = 1 ..7) CGIF5 : Boolean := False; -- Write-only. Channel x transfer complete clear (x = 1 ..7) CTCIF5 : Boolean := False; -- Write-only. Channel x half transfer clear (x = 1 ..7) CHTIF5 : Boolean := False; -- Write-only. Channel x transfer error clear (x = 1 ..7) CTEIF5 : Boolean := False; -- Write-only. Channel x global interrupt clear (x = 1 ..7) CGIF6 : Boolean := False; -- Write-only. Channel x transfer complete clear (x = 1 ..7) CTCIF6 : Boolean := False; -- Write-only. Channel x half transfer clear (x = 1 ..7) CHTIF6 : Boolean := False; -- Write-only. Channel x transfer error clear (x = 1 ..7) CTEIF6 : Boolean := False; -- Write-only. Channel x global interrupt clear (x = 1 ..7) CGIF7 : Boolean := False; -- Write-only. Channel x transfer complete clear (x = 1 ..7) CTCIF7 : Boolean := False; -- Write-only. Channel x half transfer clear (x = 1 ..7) CHTIF7 : Boolean := False; -- Write-only. Channel x transfer error clear (x = 1 ..7) CTEIF7 : Boolean := False; -- unspecified Reserved_28_31 : HAL.UInt4 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for IFCR_Register use record CGIF1 at 0 range 0 .. 0; CTCIF1 at 0 range 1 .. 1; CHTIF1 at 0 range 2 .. 2; CTEIF1 at 0 range 3 .. 3; CGIF2 at 0 range 4 .. 4; CTCIF2 at 0 range 5 .. 5; CHTIF2 at 0 range 6 .. 6; CTEIF2 at 0 range 7 .. 7; CGIF3 at 0 range 8 .. 8; CTCIF3 at 0 range 9 .. 9; CHTIF3 at 0 range 10 .. 10; CTEIF3 at 0 range 11 .. 11; CGIF4 at 0 range 12 .. 12; CTCIF4 at 0 range 13 .. 13; CHTIF4 at 0 range 14 .. 14; CTEIF4 at 0 range 15 .. 15; CGIF5 at 0 range 16 .. 16; CTCIF5 at 0 range 17 .. 17; CHTIF5 at 0 range 18 .. 18; CTEIF5 at 0 range 19 .. 19; CGIF6 at 0 range 20 .. 20; CTCIF6 at 0 range 21 .. 21; CHTIF6 at 0 range 22 .. 22; CTEIF6 at 0 range 23 .. 23; CGIF7 at 0 range 24 .. 24; CTCIF7 at 0 range 25 .. 25; CHTIF7 at 0 range 26 .. 26; CTEIF7 at 0 range 27 .. 27; Reserved_28_31 at 0 range 28 .. 31; end record; subtype CCR_PSIZE_Field is HAL.UInt2; subtype CCR_MSIZE_Field is HAL.UInt2; subtype CCR_PL_Field is HAL.UInt2; -- channel x configuration register type CCR_Register is record -- Channel enable EN : Boolean := False; -- Transfer complete interrupt enable TCIE : Boolean := False; -- Half transfer interrupt enable HTIE : Boolean := False; -- Transfer error interrupt enable TEIE : Boolean := False; -- Data transfer direction DIR : Boolean := False; -- Circular mode CIRC : Boolean := False; -- Peripheral increment mode PINC : Boolean := False; -- Memory increment mode MINC : Boolean := False; -- Peripheral size PSIZE : CCR_PSIZE_Field := 16#0#; -- Memory size MSIZE : CCR_MSIZE_Field := 16#0#; -- Channel priority level PL : CCR_PL_Field := 16#0#; -- Memory to memory mode MEM2MEM : Boolean := False; -- unspecified Reserved_15_31 : HAL.UInt17 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CCR_Register use record EN at 0 range 0 .. 0; TCIE at 0 range 1 .. 1; HTIE at 0 range 2 .. 2; TEIE at 0 range 3 .. 3; DIR at 0 range 4 .. 4; CIRC at 0 range 5 .. 5; PINC at 0 range 6 .. 6; MINC at 0 range 7 .. 7; PSIZE at 0 range 8 .. 9; MSIZE at 0 range 10 .. 11; PL at 0 range 12 .. 13; MEM2MEM at 0 range 14 .. 14; Reserved_15_31 at 0 range 15 .. 31; end record; subtype CNDTR_NDT_Field is HAL.UInt16; -- channel x number of data register type CNDTR_Register is record -- Number of data to transfer NDT : CNDTR_NDT_Field := 16#0#; -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CNDTR_Register use record NDT at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; subtype CSELR_C1S_Field is HAL.UInt4; subtype CSELR_C2S_Field is HAL.UInt4; subtype CSELR_C3S_Field is HAL.UInt4; subtype CSELR_C4S_Field is HAL.UInt4; subtype CSELR_C5S_Field is HAL.UInt4; subtype CSELR_C6S_Field is HAL.UInt4; subtype CSELR_C7S_Field is HAL.UInt4; -- channel selection register type CSELR_Register is record -- DMA channel 1 selection C1S : CSELR_C1S_Field := 16#0#; -- DMA channel 2 selection C2S : CSELR_C2S_Field := 16#0#; -- DMA channel 3 selection C3S : CSELR_C3S_Field := 16#0#; -- DMA channel 4 selection C4S : CSELR_C4S_Field := 16#0#; -- DMA channel 5 selection C5S : CSELR_C5S_Field := 16#0#; -- DMA channel 6 selection C6S : CSELR_C6S_Field := 16#0#; -- DMA channel 7 selection C7S : CSELR_C7S_Field := 16#0#; -- unspecified Reserved_28_31 : HAL.UInt4 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CSELR_Register use record C1S at 0 range 0 .. 3; C2S at 0 range 4 .. 7; C3S at 0 range 8 .. 11; C4S at 0 range 12 .. 15; C5S at 0 range 16 .. 19; C6S at 0 range 20 .. 23; C7S at 0 range 24 .. 27; Reserved_28_31 at 0 range 28 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- Direct memory access controller type DMA1_Peripheral is record -- interrupt status register ISR : aliased ISR_Register; -- interrupt flag clear register IFCR : aliased IFCR_Register; -- channel x configuration register CCR1 : aliased CCR_Register; -- channel x number of data register CNDTR1 : aliased CNDTR_Register; -- channel x peripheral address register CPAR1 : aliased HAL.UInt32; -- channel x memory address register CMAR1 : aliased HAL.UInt32; -- channel x configuration register CCR2 : aliased CCR_Register; -- channel x number of data register CNDTR2 : aliased CNDTR_Register; -- channel x peripheral address register CPAR2 : aliased HAL.UInt32; -- channel x memory address register CMAR2 : aliased HAL.UInt32; -- channel x configuration register CCR3 : aliased CCR_Register; -- channel x number of data register CNDTR3 : aliased CNDTR_Register; -- channel x peripheral address register CPAR3 : aliased HAL.UInt32; -- channel x memory address register CMAR3 : aliased HAL.UInt32; -- channel x configuration register CCR4 : aliased CCR_Register; -- channel x number of data register CNDTR4 : aliased CNDTR_Register; -- channel x peripheral address register CPAR4 : aliased HAL.UInt32; -- channel x memory address register CMAR4 : aliased HAL.UInt32; -- channel x configuration register CCR5 : aliased CCR_Register; -- channel x number of data register CNDTR5 : aliased CNDTR_Register; -- channel x peripheral address register CPAR5 : aliased HAL.UInt32; -- channel x memory address register CMAR5 : aliased HAL.UInt32; -- channel x configuration register CCR6 : aliased CCR_Register; -- channel x number of data register CNDTR6 : aliased CNDTR_Register; -- channel x peripheral address register CPAR6 : aliased HAL.UInt32; -- channel x memory address register CMAR6 : aliased HAL.UInt32; -- channel x configuration register CCR7 : aliased CCR_Register; -- channel x number of data register CNDTR7 : aliased CNDTR_Register; -- channel x peripheral address register CPAR7 : aliased HAL.UInt32; -- channel x memory address register CMAR7 : aliased HAL.UInt32; -- channel selection register CSELR : aliased CSELR_Register; end record with Volatile; for DMA1_Peripheral use record ISR at 16#0# range 0 .. 31; IFCR at 16#4# range 0 .. 31; CCR1 at 16#8# range 0 .. 31; CNDTR1 at 16#C# range 0 .. 31; CPAR1 at 16#10# range 0 .. 31; CMAR1 at 16#14# range 0 .. 31; CCR2 at 16#1C# range 0 .. 31; CNDTR2 at 16#20# range 0 .. 31; CPAR2 at 16#24# range 0 .. 31; CMAR2 at 16#28# range 0 .. 31; CCR3 at 16#30# range 0 .. 31; CNDTR3 at 16#34# range 0 .. 31; CPAR3 at 16#38# range 0 .. 31; CMAR3 at 16#3C# range 0 .. 31; CCR4 at 16#44# range 0 .. 31; CNDTR4 at 16#48# range 0 .. 31; CPAR4 at 16#4C# range 0 .. 31; CMAR4 at 16#50# range 0 .. 31; CCR5 at 16#58# range 0 .. 31; CNDTR5 at 16#5C# range 0 .. 31; CPAR5 at 16#60# range 0 .. 31; CMAR5 at 16#64# range 0 .. 31; CCR6 at 16#6C# range 0 .. 31; CNDTR6 at 16#70# range 0 .. 31; CPAR6 at 16#74# range 0 .. 31; CMAR6 at 16#78# range 0 .. 31; CCR7 at 16#80# range 0 .. 31; CNDTR7 at 16#84# range 0 .. 31; CPAR7 at 16#88# range 0 .. 31; CMAR7 at 16#8C# range 0 .. 31; CSELR at 16#A8# range 0 .. 31; end record; -- Direct memory access controller DMA1_Periph : aliased DMA1_Peripheral with Import, Address => System'To_Address (16#40020000#); end STM32_SVD.DMA;
with Ada.Text_IO; procedure Ada_Main is procedure C_Func; pragma Import (C, C_Func); package ATI renames Ada.Text_Io; begin ATI.Put_Line ("Ada_Main: Calling C_Func"); C_Func; ATI.Put_Line ("Ada_Main: Returned from C_Func"); end Ada_Main;
with Interfaces.C.Strings, System; use type System.Address; package body FLTK.Widgets.Valuators is procedure valuator_set_draw_hook (W, D : in System.Address); pragma Import (C, valuator_set_draw_hook, "valuator_set_draw_hook"); pragma Inline (valuator_set_draw_hook); procedure valuator_set_handle_hook (W, H : in System.Address); pragma Import (C, valuator_set_handle_hook, "valuator_set_handle_hook"); pragma Inline (valuator_set_handle_hook); function new_fl_valuator (X, Y, W, H : in Interfaces.C.int; Text : in Interfaces.C.char_array) return System.Address; pragma Import (C, new_fl_valuator, "new_fl_valuator"); pragma Inline (new_fl_valuator); procedure free_fl_valuator (V : in System.Address); pragma Import (C, free_fl_valuator, "free_fl_valuator"); pragma Inline (free_fl_valuator); function fl_valuator_clamp (V : in System.Address; D : in Interfaces.C.double) return Interfaces.C.double; pragma Import (C, fl_valuator_clamp, "fl_valuator_clamp"); pragma Inline (fl_valuator_clamp); function fl_valuator_round (V : in System.Address; D : in Interfaces.C.double) return Interfaces.C.double; pragma Import (C, fl_valuator_round, "fl_valuator_round"); pragma Inline (fl_valuator_round); function fl_valuator_increment (V : in System.Address; D : in Interfaces.C.double; S : in Interfaces.C.int) return Interfaces.C.double; pragma Import (C, fl_valuator_increment, "fl_valuator_increment"); pragma Inline (fl_valuator_increment); function fl_valuator_get_minimum (V : in System.Address) return Interfaces.C.double; pragma Import (C, fl_valuator_get_minimum, "fl_valuator_get_minimum"); pragma Inline (fl_valuator_get_minimum); procedure fl_valuator_set_minimum (V : in System.Address; D : in Interfaces.C.double); pragma Import (C, fl_valuator_set_minimum, "fl_valuator_set_minimum"); pragma Inline (fl_valuator_set_minimum); function fl_valuator_get_maximum (V : in System.Address) return Interfaces.C.double; pragma Import (C, fl_valuator_get_maximum, "fl_valuator_get_maximum"); pragma Inline (fl_valuator_get_maximum); procedure fl_valuator_set_maximum (V : in System.Address; D : in Interfaces.C.double); pragma Import (C, fl_valuator_set_maximum, "fl_valuator_set_maximum"); pragma Inline (fl_valuator_set_maximum); function fl_valuator_get_step (V : in System.Address) return Interfaces.C.double; pragma Import (C, fl_valuator_get_step, "fl_valuator_get_step"); pragma Inline (fl_valuator_get_step); procedure fl_valuator_set_step (V : in System.Address; T : in Interfaces.C.double); pragma Import (C, fl_valuator_set_step, "fl_valuator_set_step"); pragma Inline (fl_valuator_set_step); function fl_valuator_get_value (V : in System.Address) return Interfaces.C.double; pragma Import (C, fl_valuator_get_value, "fl_valuator_get_value"); pragma Inline (fl_valuator_get_value); procedure fl_valuator_set_value (V : in System.Address; D : in Interfaces.C.double); pragma Import (C, fl_valuator_set_value, "fl_valuator_set_value"); pragma Inline (fl_valuator_set_value); procedure fl_valuator_bounds (V : in System.Address; A, B : in Interfaces.C.double); pragma Import (C, fl_valuator_bounds, "fl_valuator_bounds"); pragma Inline (fl_valuator_bounds); procedure fl_valuator_precision (V : in System.Address; D : in Interfaces.C.int); pragma Import (C, fl_valuator_precision, "fl_valuator_precision"); pragma Inline (fl_valuator_precision); procedure fl_valuator_range (V : in System.Address; A, B : in Interfaces.C.double); pragma Import (C, fl_valuator_range, "fl_valuator_range"); pragma Inline (fl_valuator_range); function fl_valuator_handle (V : in System.Address; E : in Interfaces.C.int) return Interfaces.C.int; pragma Import (C, fl_valuator_handle, "fl_valuator_handle"); pragma Inline (fl_valuator_handle); procedure Finalize (This : in out Valuator) is begin if This.Void_Ptr /= System.Null_Address and then This in Valuator'Class then free_fl_valuator (This.Void_Ptr); This.Void_Ptr := System.Null_Address; end if; Finalize (Widget (This)); end Finalize; package body Forge is function Create (X, Y, W, H : in Integer; Text : in String) return Valuator is begin return This : Valuator do This.Void_Ptr := new_fl_valuator (Interfaces.C.int (X), Interfaces.C.int (Y), Interfaces.C.int (W), Interfaces.C.int (H), Interfaces.C.To_C (Text)); fl_widget_set_user_data (This.Void_Ptr, Widget_Convert.To_Address (This'Unchecked_Access)); valuator_set_draw_hook (This.Void_Ptr, Draw_Hook'Address); valuator_set_handle_hook (This.Void_Ptr, Handle_Hook'Address); end return; end Create; end Forge; function Clamp (This : in Valuator; Input : in Long_Float) return Long_Float is begin return Long_Float (fl_valuator_clamp (This.Void_Ptr, Interfaces.C.double (Input))); end Clamp; function Round (This : in Valuator; Input : in Long_Float) return Long_Float is begin return Long_Float (fl_valuator_round (This.Void_Ptr, Interfaces.C.double (Input))); end Round; function Increment (This : in Valuator; Input : in Long_Float; Step : in Integer) return Long_Float is begin return Long_Float (fl_valuator_increment (This.Void_Ptr, Interfaces.C.double (Input), Interfaces.C.int (Step))); end Increment; function Get_Minimum (This : in Valuator) return Long_Float is begin return Long_Float (fl_valuator_get_minimum (This.Void_Ptr)); end Get_Minimum; procedure Set_Minimum (This : in out Valuator; To : in Long_Float) is begin fl_valuator_set_minimum (This.Void_Ptr, Interfaces.C.double (To)); end Set_Minimum; function Get_Maximum (This : in Valuator) return Long_Float is begin return Long_Float (fl_valuator_get_maximum (This.Void_Ptr)); end Get_Maximum; procedure Set_Maximum (This : in out Valuator; To : in Long_Float) is begin fl_valuator_set_maximum (This.Void_Ptr, Interfaces.C.double (To)); end Set_Maximum; function Get_Step (This : in Valuator) return Long_Float is begin return Long_Float (fl_valuator_get_step (This.Void_Ptr)); end Get_Step; procedure Set_Step (This : in out Valuator; To : in Long_Float) is begin fl_valuator_set_step (This.Void_Ptr, Interfaces.C.double (To)); end Set_Step; function Get_Value (This : in Valuator) return Long_Float is begin return Long_Float (fl_valuator_get_value (This.Void_Ptr)); end Get_Value; procedure Set_Value (This : in out Valuator; To : in Long_Float) is begin fl_valuator_set_value (This.Void_Ptr, Interfaces.C.double (To)); end Set_Value; procedure Set_Bounds (This : in out Valuator; Min, Max : in Long_Float) is begin fl_valuator_bounds (This.Void_Ptr, Interfaces.C.double (Min), Interfaces.C.double (Max)); end Set_Bounds; procedure Set_Precision (This : in out Valuator; To : in Integer) is begin fl_valuator_precision (This.Void_Ptr, Interfaces.C.int (To)); end Set_Precision; procedure Set_Range (This : in out Valuator; Min, Max : in Long_Float) is begin fl_valuator_range (This.Void_Ptr, Interfaces.C.double (Min), Interfaces.C.double (Max)); end Set_Range; function Handle (This : in out Valuator; Event : in Event_Kind) return Event_Outcome is begin return Event_Outcome'Val (fl_valuator_handle (This.Void_Ptr, Event_Kind'Pos (Event))); end Handle; end FLTK.Widgets.Valuators;
with Ada.Strings.Unbounded; with Ada.Text_IO; use Ada.Text_IO; with Blade; with Blade_Types; with GA_Maths; with GA_Utilities; with Multivectors; use Multivectors; with Multivector_Type; procedure Test_MV is no_bv : Multivector := Basis_Vector (Blade_Types.C3_no); e1_bv : Multivector := Basis_Vector (Blade_Types.C3_e1); e2_bv : Multivector := Basis_Vector (Blade_Types.C3_e2); e3_bv : Multivector := Basis_Vector (Blade_Types.C3_e3); ni_bv : Multivector := Basis_Vector (Blade_Types.C3_ni); BV_Names : Blade.Basis_Vector_Names; MV : Multivector; MV1 : Multivector; MV12 : Multivector; MV1p2 : Multivector; MV13 : Multivector; Op23 : Multivector; Op23_1 : Multivector; Add_1_Op23_1 : Multivector; Inv_Add_1_Op23_1 : Multivector; MV_Info : Multivector_Type.MV_Type_Record; begin BV_Names.Append (Ada.Strings.Unbounded.To_Unbounded_String ("no")); BV_Names.Append (Ada.Strings.Unbounded.To_Unbounded_String ("e1")); BV_Names.Append (Ada.Strings.Unbounded.To_Unbounded_String ("e2")); BV_Names.Append (Ada.Strings.Unbounded.To_Unbounded_String ("e3")); BV_Names.Append (Ada.Strings.Unbounded.To_Unbounded_String ("ni")); -- MV_Info := Multivector_Type.Init (MV); -- C3GA_Utilities.Print_Multivector ("New", MV); -- Multivector_Type.Print_Multivector_Info ("Null MV", MV_Info); -- New_Line; -- -- C3GA_Utilities.Print_Multivector ("no", no_bv); -- MV_Info := Multivector_Type.Init (no_bv); -- Put_Line ("Bit count: " & GA_Maths.Unsigned_Integer -- 'Image (1) & -- Natural'Image (GA_Maths.Bit_Count (1))); -- Multivector_Type.Print_Multivector_Info ("no", MV_Info); -- -- MV_Info := Multivector_Type.Init (e1_bv); -- C3GA_Utilities.Print_Multivector ("e1", e1_bv); -- Multivector_Type.Print_Multivector_Info ("e1", MV_Info); -- -- C3GA_Utilities.Print_Multivector ("e2", e2_bv); -- MV_Info := Multivector_Type.Init (e2_bv); -- Multivector_Type.Print_Multivector_Info ("e2", MV_Info); -- -- MV_Info := Multivector_Type.Init (e3_bv); -- C3GA_Utilities.Print_Multivector ("e3", e3_bv); -- Multivector_Type.Print_Multivector_Info ("e3", MV_Info); -- -- C3GA_Utilities.Print_Multivector ("ni", ni_bv); -- MV_Info := Multivector_Type.Init (ni_bv); -- Multivector_Type.Print_Multivector_Info ("ni", MV_Info); -- MV1 := e1_bv; GA_Utilities.Print_Multivector ("MV = e1", MV1); MV_Info := Multivector_Type.Init (MV1); Multivector_Type.Print_Multivector_Info ("MV = e1", MV_Info); New_Line; Put_Line ("Multivector_String:"); Put_Line (Ada.Strings.Unbounded.To_String (Multivector_String (MV1, BV_Names))); MV1p2 := e1_bv + e2_bv; GA_Utilities.Print_Multivector ("e1 + e2", MV1p2); MV_Info := Multivector_Type.Init (MV1p2); Multivector_Type.Print_Multivector_Info ("e1 + e2", MV_Info); New_Line; Put_Line ("Multivector_String:"); Put_Line (Ada.Strings.Unbounded.To_String (Multivector_String (MV1p2, BV_Names))); MV12 := Outer_Product (e1_bv, e2_bv); GA_Utilities.Print_Multivector ("e1 ^ e2", MV12); MV_Info := Multivector_Type.Init (MV12); Multivector_Type.Print_Multivector_Info ("e1 ^ e2", MV_Info); New_Line; Put_Line ("Multivector_String:"); Put_Line (Ada.Strings.Unbounded.To_String (Multivector_String (MV12, BV_Names))); MV13 := Outer_Product (e1_bv, e3_bv); GA_Utilities.Print_Multivector ("e1 ^ e3", MV13); MV_Info := Multivector_Type.Init (MV12); Multivector_Type.Print_Multivector_Info ("e1 ^ e3", MV_Info); New_Line; Put_Line ("Multivector_String:"); Put_Line (Ada.Strings.Unbounded.To_String (Multivector_String (MV13, BV_Names))); -- Multivector A = e1.add(e2.op(e3).op(e1)); -- = e1 + (e2^e3)^e1) Op23 := Outer_Product (e2_bv, e3_bv); Op23_1 := Outer_Product (Op23, e1_bv); Add_1_Op23_1 := e1_bv + Op23_1; GA_Utilities.Print_Multivector ("Op23: e2 ^ e3", Op23); GA_Utilities.Print_Multivector ("Op23_1: (e2 ^ e3) ^ e1", Op23_1); GA_Utilities.Print_Multivector ("Op23 G Inverse", General_Inverse (Op23)); GA_Utilities.Print_Multivector ("Op23 V Inverse", Versor_Inverse (Op23)); GA_Utilities.Print_Multivector ("Op23_1: (e2 ^ e3) ^ e1", Op23_1); GA_Utilities.Print_Multivector ("Add_1_Op23_1: e1 + ((e2 ^ e3) ^ e1", Add_1_Op23_1); GA_Utilities.Print_Multivector ("Add_1_Op23_1 G Inverse", General_Inverse (Add_1_Op23_1)); GA_Utilities.Print_Multivector ("Add_1_Op23_1 V Inverse", Versor_Inverse (Add_1_Op23_1)); Inv_Add_1_Op23_1 := General_Inverse (Add_1_Op23_1); exception when anError : others => Put_Line ("An exception occurred in Test_MV."); raise; end Test_MV;
------------------------------------------------------------------------------ -- -- -- GNAT RUNTIME COMPONENTS -- -- -- -- S Y S T E M . A S S E R T I O N S -- -- -- -- S p e c -- -- -- -- $Revision: 2 $ -- -- -- -- Copyright (c) 1992,1993,1994 NYU, All Rights Reserved -- -- -- -- The GNAT library is free software; you can redistribute it and/or modify -- -- it under terms of the GNU Library General Public License as published by -- -- the Free Software Foundation; either version 2, or (at your option) any -- -- later version. The GNAT library is distributed in the hope that it will -- -- be useful, but WITHOUT ANY WARRANTY; without even the implied warranty -- -- of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- -- Library General Public License for more details. You should have -- -- received a copy of the GNU Library General Public License along with -- -- the GNAT library; see the file COPYING.LIB. If not, write to the Free -- -- Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. -- -- -- ------------------------------------------------------------------------------ -- This module contains the definition of the exception that is raised -- when an assertion made using pragma Assert fails (i.e. the given -- expression evaluates to False. It also contains the routines used -- to raise this assertion with an associated message. with System.Parameters; package System.Assertions is Assert_Msg : String (1 .. System.Parameters.Exception_Msg_Max); Assert_Msg_Length : Natural := 0; -- Characters and length of message passed to Raise_Assert_Failure -- The initial length of zero indicates that no message has been set -- yet (and Assert_Message will return the null string in such cases) Assert_Failure : exception; -- Exception raised when assertion fails procedure Raise_Assert_Failure (Msg : String); -- Called to raise Assert_Failure with given message end System.Assertions;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- G N A T . C O M M A N D _ L I N E -- -- -- -- B o d y -- -- -- -- Copyright (C) 1999-2016, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Ada.Characters.Handling; use Ada.Characters.Handling; with Ada.Strings.Unbounded; with Ada.Text_IO; use Ada.Text_IO; with Ada.Unchecked_Deallocation; with GNAT.Directory_Operations; use GNAT.Directory_Operations; with GNAT.OS_Lib; use GNAT.OS_Lib; package body GNAT.Command_Line is -- General note: this entire body could use much more commenting. There -- are large sections of uncommented code throughout, and many formal -- parameters of local subprograms are not documented at all ??? package CL renames Ada.Command_Line; type Switch_Parameter_Type is (Parameter_None, Parameter_With_Optional_Space, -- ':' in getopt Parameter_With_Space_Or_Equal, -- '=' in getopt Parameter_No_Space, -- '!' in getopt Parameter_Optional); -- '?' in getopt procedure Set_Parameter (Variable : out Parameter_Type; Arg_Num : Positive; First : Positive; Last : Natural; Extra : Character := ASCII.NUL); pragma Inline (Set_Parameter); -- Set the parameter that will be returned by Parameter below -- -- Extra is a character that needs to be added when reporting Full_Switch. -- (it will in general be the switch character, for instance '-'). -- Otherwise, Full_Switch will report 'f' instead of '-f'. In particular, -- it needs to be set when reporting an invalid switch or handling '*'. -- -- Parameters need to be defined ??? function Goto_Next_Argument_In_Section (Parser : Opt_Parser) return Boolean; -- Go to the next argument on the command line. If we are at the end of -- the current section, we want to make sure there is no other identical -- section on the command line (there might be multiple instances of -- -largs). Returns True iff there is another argument. function Get_File_Names_Case_Sensitive return Integer; pragma Import (C, Get_File_Names_Case_Sensitive, "__gnat_get_file_names_case_sensitive"); File_Names_Case_Sensitive : constant Boolean := Get_File_Names_Case_Sensitive /= 0; procedure Canonical_Case_File_Name (S : in out String); -- Given a file name, converts it to canonical case form. For systems where -- file names are case sensitive, this procedure has no effect. If file -- names are not case sensitive (i.e. for example if you have the file -- "xyz.adb", you can refer to it as XYZ.adb or XyZ.AdB), then this call -- converts the given string to canonical all lower case form, so that two -- file names compare equal if they refer to the same file. procedure Internal_Initialize_Option_Scan (Parser : Opt_Parser; Switch_Char : Character; Stop_At_First_Non_Switch : Boolean; Section_Delimiters : String); -- Initialize Parser, which must have been allocated already function Argument (Parser : Opt_Parser; Index : Integer) return String; -- Return the index-th command line argument procedure Find_Longest_Matching_Switch (Switches : String; Arg : String; Index_In_Switches : out Integer; Switch_Length : out Integer; Param : out Switch_Parameter_Type); -- Return the Longest switch from Switches that at least partially matches -- Arg. Index_In_Switches is set to 0 if none matches. What are other -- parameters??? in particular Param is not always set??? procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Argument_List, Argument_List_Access); procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Command_Line_Configuration_Record, Command_Line_Configuration); procedure Remove (Line : in out Argument_List_Access; Index : Integer); -- Remove a specific element from Line procedure Add (Line : in out Argument_List_Access; Str : String_Access; Before : Boolean := False); -- Add a new element to Line. If Before is True, the item is inserted at -- the beginning, else it is appended. procedure Add (Config : in out Command_Line_Configuration; Switch : Switch_Definition); procedure Add (Def : in out Alias_Definitions_List; Alias : Alias_Definition); -- Add a new element to Def procedure Initialize_Switch_Def (Def : out Switch_Definition; Switch : String := ""; Long_Switch : String := ""; Help : String := ""; Section : String := ""; Argument : String := "ARG"); -- Initialize [Def] with the contents of the other parameters. -- This also checks consistency of the switch parameters, and will raise -- Invalid_Switch if they do not match. procedure Decompose_Switch (Switch : String; Parameter_Type : out Switch_Parameter_Type; Switch_Last : out Integer); -- Given a switch definition ("name:" for instance), extracts the type of -- parameter that is expected, and the name of the switch function Can_Have_Parameter (S : String) return Boolean; -- True if S can have a parameter function Require_Parameter (S : String) return Boolean; -- True if S requires a parameter function Actual_Switch (S : String) return String; -- Remove any possible trailing '!', ':', '?' and '=' generic with procedure Callback (Simple_Switch : String; Separator : String; Parameter : String; Index : Integer); -- Index in Config.Switches, or -1 procedure For_Each_Simple_Switch (Config : Command_Line_Configuration; Section : String; Switch : String; Parameter : String := ""; Unalias : Boolean := True); -- Breaks Switch into as simple switches as possible (expanding aliases and -- ungrouping common prefixes when possible), and call Callback for each of -- these. procedure Sort_Sections (Line : GNAT.OS_Lib.Argument_List_Access; Sections : GNAT.OS_Lib.Argument_List_Access; Params : GNAT.OS_Lib.Argument_List_Access); -- Reorder the command line switches so that the switches belonging to a -- section are grouped together. procedure Group_Switches (Cmd : Command_Line; Result : Argument_List_Access; Sections : Argument_List_Access; Params : Argument_List_Access); -- Group switches with common prefixes whenever possible. Once they have -- been grouped, we also check items for possible aliasing. procedure Alias_Switches (Cmd : Command_Line; Result : Argument_List_Access; Params : Argument_List_Access); -- When possible, replace one or more switches by an alias, i.e. a shorter -- version. function Looking_At (Type_Str : String; Index : Natural; Substring : String) return Boolean; -- Return True if the characters starting at Index in Type_Str are -- equivalent to Substring. generic with function Callback (S : String; Index : Integer) return Boolean; procedure Foreach_Switch (Config : Command_Line_Configuration; Section : String); -- Iterate over all switches defined in Config, for a specific section. -- Index is set to the index in Config.Switches. Stop iterating when -- Callback returns False. -------------- -- Argument -- -------------- function Argument (Parser : Opt_Parser; Index : Integer) return String is begin if Parser.Arguments /= null then return Parser.Arguments (Index + Parser.Arguments'First - 1).all; else return CL.Argument (Index); end if; end Argument; ------------------------------ -- Canonical_Case_File_Name -- ------------------------------ procedure Canonical_Case_File_Name (S : in out String) is begin if not File_Names_Case_Sensitive then for J in S'Range loop if S (J) in 'A' .. 'Z' then S (J) := Character'Val (Character'Pos (S (J)) + (Character'Pos ('a') - Character'Pos ('A'))); end if; end loop; end if; end Canonical_Case_File_Name; --------------- -- Expansion -- --------------- function Expansion (Iterator : Expansion_Iterator) return String is type Pointer is access all Expansion_Iterator; It : constant Pointer := Iterator'Unrestricted_Access; S : String (1 .. 1024); Last : Natural; Current : Depth := It.Current_Depth; NL : Positive; begin -- It is assumed that a directory is opened at the current level. -- Otherwise GNAT.Directory_Operations.Directory_Error will be raised -- at the first call to Read. loop Read (It.Levels (Current).Dir, S, Last); -- If we have exhausted the directory, close it and go back one level if Last = 0 then Close (It.Levels (Current).Dir); -- If we are at level 1, we are finished; return an empty string if Current = 1 then return String'(1 .. 0 => ' '); -- Otherwise continue with the directory at the previous level else Current := Current - 1; It.Current_Depth := Current; end if; -- If this is a directory, that is neither "." or "..", attempt to -- go to the next level. elsif Is_Directory (It.Dir_Name (1 .. It.Levels (Current).Name_Last) & S (1 .. Last)) and then S (1 .. Last) /= "." and then S (1 .. Last) /= ".." then -- We can go to the next level only if we have not reached the -- maximum depth, if Current < It.Maximum_Depth then NL := It.Levels (Current).Name_Last; -- And if relative path of this new directory is not too long if NL + Last + 1 < Max_Path_Length then Current := Current + 1; It.Current_Depth := Current; It.Dir_Name (NL + 1 .. NL + Last) := S (1 .. Last); NL := NL + Last + 1; It.Dir_Name (NL) := Directory_Separator; It.Levels (Current).Name_Last := NL; Canonical_Case_File_Name (It.Dir_Name (1 .. NL)); -- Open the new directory, and read from it GNAT.Directory_Operations.Open (It.Levels (Current).Dir, It.Dir_Name (1 .. NL)); end if; end if; end if; -- Check the relative path against the pattern -- Note that we try to match also against directory names, since -- clients of this function may expect to retrieve directories. declare Name : String := It.Dir_Name (It.Start .. It.Levels (Current).Name_Last) & S (1 .. Last); begin Canonical_Case_File_Name (Name); -- If it matches return the relative path if GNAT.Regexp.Match (Name, Iterator.Regexp) then return Name; end if; end; end loop; end Expansion; --------------------- -- Current_Section -- --------------------- function Current_Section (Parser : Opt_Parser := Command_Line_Parser) return String is begin if Parser.Current_Section = 1 then return ""; end if; for Index in reverse 1 .. Integer'Min (Parser.Current_Argument - 1, Parser.Section'Last) loop if Parser.Section (Index) = 0 then return Argument (Parser, Index); end if; end loop; return ""; end Current_Section; ----------------- -- Full_Switch -- ----------------- function Full_Switch (Parser : Opt_Parser := Command_Line_Parser) return String is begin if Parser.The_Switch.Extra = ASCII.NUL then return Argument (Parser, Parser.The_Switch.Arg_Num) (Parser.The_Switch.First .. Parser.The_Switch.Last); else return Parser.The_Switch.Extra & Argument (Parser, Parser.The_Switch.Arg_Num) (Parser.The_Switch.First .. Parser.The_Switch.Last); end if; end Full_Switch; ------------------ -- Get_Argument -- ------------------ function Get_Argument (Do_Expansion : Boolean := False; Parser : Opt_Parser := Command_Line_Parser) return String is begin if Parser.In_Expansion then declare S : constant String := Expansion (Parser.Expansion_It); begin if S'Length /= 0 then return S; else Parser.In_Expansion := False; end if; end; end if; if Parser.Current_Argument > Parser.Arg_Count then -- If this is the first time this function is called if Parser.Current_Index = 1 then Parser.Current_Argument := 1; while Parser.Current_Argument <= Parser.Arg_Count and then Parser.Section (Parser.Current_Argument) /= Parser.Current_Section loop Parser.Current_Argument := Parser.Current_Argument + 1; end loop; else return String'(1 .. 0 => ' '); end if; elsif Parser.Section (Parser.Current_Argument) = 0 then while Parser.Current_Argument <= Parser.Arg_Count and then Parser.Section (Parser.Current_Argument) /= Parser.Current_Section loop Parser.Current_Argument := Parser.Current_Argument + 1; end loop; end if; Parser.Current_Index := Integer'Last; while Parser.Current_Argument <= Parser.Arg_Count and then Parser.Is_Switch (Parser.Current_Argument) loop Parser.Current_Argument := Parser.Current_Argument + 1; end loop; if Parser.Current_Argument > Parser.Arg_Count then return String'(1 .. 0 => ' '); elsif Parser.Section (Parser.Current_Argument) = 0 then return Get_Argument (Do_Expansion); end if; Parser.Current_Argument := Parser.Current_Argument + 1; -- Could it be a file name with wild cards to expand? if Do_Expansion then declare Arg : constant String := Argument (Parser, Parser.Current_Argument - 1); begin for Index in Arg'Range loop if Arg (Index) = '*' or else Arg (Index) = '?' or else Arg (Index) = '[' then Parser.In_Expansion := True; Start_Expansion (Parser.Expansion_It, Arg); return Get_Argument (Do_Expansion, Parser); end if; end loop; end; end if; return Argument (Parser, Parser.Current_Argument - 1); end Get_Argument; ---------------------- -- Decompose_Switch -- ---------------------- procedure Decompose_Switch (Switch : String; Parameter_Type : out Switch_Parameter_Type; Switch_Last : out Integer) is begin if Switch = "" then Parameter_Type := Parameter_None; Switch_Last := Switch'Last; return; end if; case Switch (Switch'Last) is when ':' => Parameter_Type := Parameter_With_Optional_Space; Switch_Last := Switch'Last - 1; when '=' => Parameter_Type := Parameter_With_Space_Or_Equal; Switch_Last := Switch'Last - 1; when '!' => Parameter_Type := Parameter_No_Space; Switch_Last := Switch'Last - 1; when '?' => Parameter_Type := Parameter_Optional; Switch_Last := Switch'Last - 1; when others => Parameter_Type := Parameter_None; Switch_Last := Switch'Last; end case; end Decompose_Switch; ---------------------------------- -- Find_Longest_Matching_Switch -- ---------------------------------- procedure Find_Longest_Matching_Switch (Switches : String; Arg : String; Index_In_Switches : out Integer; Switch_Length : out Integer; Param : out Switch_Parameter_Type) is Index : Natural; Length : Natural := 1; Last : Natural; P : Switch_Parameter_Type; begin Index_In_Switches := 0; Switch_Length := 0; -- Remove all leading spaces first to make sure that Index points -- at the start of the first switch. Index := Switches'First; while Index <= Switches'Last and then Switches (Index) = ' ' loop Index := Index + 1; end loop; while Index <= Switches'Last loop -- Search the length of the parameter at this position in Switches Length := Index; while Length <= Switches'Last and then Switches (Length) /= ' ' loop Length := Length + 1; end loop; -- Length now marks the separator after the current switch. Last will -- mark the last character of the name of the switch. if Length = Index + 1 then P := Parameter_None; Last := Index; else Decompose_Switch (Switches (Index .. Length - 1), P, Last); end if; -- If it is the one we searched, it may be a candidate if Arg'First + Last - Index <= Arg'Last and then Switches (Index .. Last) = Arg (Arg'First .. Arg'First + Last - Index) and then Last - Index + 1 > Switch_Length and then (P /= Parameter_With_Space_Or_Equal or else Arg'Last = Arg'First + Last - Index or else Arg (Arg'First + Last - Index + 1) = '=') then Param := P; Index_In_Switches := Index; Switch_Length := Last - Index + 1; end if; -- Look for the next switch in Switches while Index <= Switches'Last and then Switches (Index) /= ' ' loop Index := Index + 1; end loop; Index := Index + 1; end loop; end Find_Longest_Matching_Switch; ------------ -- Getopt -- ------------ function Getopt (Switches : String; Concatenate : Boolean := True; Parser : Opt_Parser := Command_Line_Parser) return Character is Dummy : Boolean; begin <<Restart>> -- If we have finished parsing the current command line item (there -- might be multiple switches in a single item), then go to the next -- element. if Parser.Current_Argument > Parser.Arg_Count or else (Parser.Current_Index > Argument (Parser, Parser.Current_Argument)'Last and then not Goto_Next_Argument_In_Section (Parser)) then return ASCII.NUL; end if; -- By default, the switch will not have a parameter Parser.The_Parameter := (Integer'Last, Integer'Last, Integer'Last - 1, ASCII.NUL); Parser.The_Separator := ASCII.NUL; declare Arg : constant String := Argument (Parser, Parser.Current_Argument); Index_Switches : Natural := 0; Max_Length : Natural := 0; End_Index : Natural; Param : Switch_Parameter_Type; begin -- If we are on a new item, test if this might be a switch if Parser.Current_Index = Arg'First then if Arg = "" or else Arg (Arg'First) /= Parser.Switch_Character then -- If it isn't a switch, return it immediately. We also know it -- isn't the parameter to a previous switch, since that has -- already been handled. if Switches (Switches'First) = '*' then Set_Parameter (Parser.The_Switch, Arg_Num => Parser.Current_Argument, First => Arg'First, Last => Arg'Last); Parser.Is_Switch (Parser.Current_Argument) := True; Dummy := Goto_Next_Argument_In_Section (Parser); return '*'; end if; if Parser.Stop_At_First then Parser.Current_Argument := Positive'Last; return ASCII.NUL; elsif not Goto_Next_Argument_In_Section (Parser) then return ASCII.NUL; else -- Recurse to get the next switch on the command line goto Restart; end if; end if; -- We are on the first character of a new command line argument, -- which starts with Switch_Character. Further analysis is needed. Parser.Current_Index := Parser.Current_Index + 1; Parser.Is_Switch (Parser.Current_Argument) := True; end if; Find_Longest_Matching_Switch (Switches => Switches, Arg => Arg (Parser.Current_Index .. Arg'Last), Index_In_Switches => Index_Switches, Switch_Length => Max_Length, Param => Param); -- If switch is not accepted, it is either invalid or is returned -- in the context of '*'. if Index_Switches = 0 then -- Find the current switch that we did not recognize. This is in -- fact difficult because Getopt does not know explicitly about -- short and long switches. Ideally, we would want the following -- behavior: -- * for short switches, with Concatenate: -- if -a is not recognized, and the command line has -daf -- we should report the invalid switch as "-a". -- * for short switches, wihtout Concatenate: -- we should report the invalid switch as "-daf". -- * for long switches: -- if the commadn line is "--long" we should report --long -- as unrecongized. -- Unfortunately, the fact that long switches start with a -- duplicate switch character is just a convention (so we could -- have a long switch "-long" for instance). We'll still rely on -- this convention here to try and get as helpful an error message -- as possible. -- Long switch case (starting with double switch character) if Arg (Arg'First + 1) = Parser.Switch_Character then End_Index := Arg'Last; -- Short switch case else End_Index := (if Concatenate then Parser.Current_Index else Arg'Last); end if; if Switches /= "" and then Switches (Switches'First) = '*' then -- Always prepend the switch character, so that users know -- that this comes from a switch on the command line. This -- is especially important when Concatenate is False, since -- otherwise the current argument first character is lost. if Parser.Section (Parser.Current_Argument) = 0 then -- A section transition should not be returned to the user Dummy := Goto_Next_Argument_In_Section (Parser); goto Restart; else Set_Parameter (Parser.The_Switch, Arg_Num => Parser.Current_Argument, First => Parser.Current_Index, Last => Arg'Last, Extra => Parser.Switch_Character); Parser.Is_Switch (Parser.Current_Argument) := True; Dummy := Goto_Next_Argument_In_Section (Parser); return '*'; end if; end if; if Parser.Current_Index = Arg'First then Set_Parameter (Parser.The_Switch, Arg_Num => Parser.Current_Argument, First => Parser.Current_Index, Last => End_Index); else Set_Parameter (Parser.The_Switch, Arg_Num => Parser.Current_Argument, First => Parser.Current_Index, Last => End_Index, Extra => Parser.Switch_Character); end if; Parser.Current_Index := End_Index + 1; raise Invalid_Switch; end if; End_Index := Parser.Current_Index + Max_Length - 1; Set_Parameter (Parser.The_Switch, Arg_Num => Parser.Current_Argument, First => Parser.Current_Index, Last => End_Index); case Param is when Parameter_With_Optional_Space => if End_Index < Arg'Last then Set_Parameter (Parser.The_Parameter, Arg_Num => Parser.Current_Argument, First => End_Index + 1, Last => Arg'Last); Dummy := Goto_Next_Argument_In_Section (Parser); elsif Parser.Current_Argument < Parser.Arg_Count and then Parser.Section (Parser.Current_Argument + 1) /= 0 then Parser.Current_Argument := Parser.Current_Argument + 1; Parser.The_Separator := ' '; Set_Parameter (Parser.The_Parameter, Arg_Num => Parser.Current_Argument, First => Argument (Parser, Parser.Current_Argument)'First, Last => Argument (Parser, Parser.Current_Argument)'Last); Parser.Is_Switch (Parser.Current_Argument) := True; Dummy := Goto_Next_Argument_In_Section (Parser); else Parser.Current_Index := End_Index + 1; raise Invalid_Parameter; end if; when Parameter_With_Space_Or_Equal => -- If the switch is of the form <switch>=xxx if End_Index < Arg'Last then if Arg (End_Index + 1) = '=' and then End_Index + 1 < Arg'Last then Parser.The_Separator := '='; Set_Parameter (Parser.The_Parameter, Arg_Num => Parser.Current_Argument, First => End_Index + 2, Last => Arg'Last); Dummy := Goto_Next_Argument_In_Section (Parser); else Parser.Current_Index := End_Index + 1; raise Invalid_Parameter; end if; -- Case of switch of the form <switch> xxx elsif Parser.Current_Argument < Parser.Arg_Count and then Parser.Section (Parser.Current_Argument + 1) /= 0 then Parser.Current_Argument := Parser.Current_Argument + 1; Parser.The_Separator := ' '; Set_Parameter (Parser.The_Parameter, Arg_Num => Parser.Current_Argument, First => Argument (Parser, Parser.Current_Argument)'First, Last => Argument (Parser, Parser.Current_Argument)'Last); Parser.Is_Switch (Parser.Current_Argument) := True; Dummy := Goto_Next_Argument_In_Section (Parser); else Parser.Current_Index := End_Index + 1; raise Invalid_Parameter; end if; when Parameter_No_Space => if End_Index < Arg'Last then Set_Parameter (Parser.The_Parameter, Arg_Num => Parser.Current_Argument, First => End_Index + 1, Last => Arg'Last); Dummy := Goto_Next_Argument_In_Section (Parser); else Parser.Current_Index := End_Index + 1; raise Invalid_Parameter; end if; when Parameter_Optional => if End_Index < Arg'Last then Set_Parameter (Parser.The_Parameter, Arg_Num => Parser.Current_Argument, First => End_Index + 1, Last => Arg'Last); end if; Dummy := Goto_Next_Argument_In_Section (Parser); when Parameter_None => if Concatenate or else End_Index = Arg'Last then Parser.Current_Index := End_Index + 1; else -- If Concatenate is False and the full argument is not -- recognized as a switch, this is an invalid switch. if Switches (Switches'First) = '*' then Set_Parameter (Parser.The_Switch, Arg_Num => Parser.Current_Argument, First => Arg'First, Last => Arg'Last); Parser.Is_Switch (Parser.Current_Argument) := True; Dummy := Goto_Next_Argument_In_Section (Parser); return '*'; end if; Set_Parameter (Parser.The_Switch, Arg_Num => Parser.Current_Argument, First => Parser.Current_Index, Last => Arg'Last, Extra => Parser.Switch_Character); Parser.Current_Index := Arg'Last + 1; raise Invalid_Switch; end if; end case; return Switches (Index_Switches); end; end Getopt; ----------------------------------- -- Goto_Next_Argument_In_Section -- ----------------------------------- function Goto_Next_Argument_In_Section (Parser : Opt_Parser) return Boolean is begin Parser.Current_Argument := Parser.Current_Argument + 1; if Parser.Current_Argument > Parser.Arg_Count or else Parser.Section (Parser.Current_Argument) = 0 then loop Parser.Current_Argument := Parser.Current_Argument + 1; if Parser.Current_Argument > Parser.Arg_Count then Parser.Current_Index := 1; return False; end if; exit when Parser.Section (Parser.Current_Argument) = Parser.Current_Section; end loop; end if; Parser.Current_Index := Argument (Parser, Parser.Current_Argument)'First; return True; end Goto_Next_Argument_In_Section; ------------------ -- Goto_Section -- ------------------ procedure Goto_Section (Name : String := ""; Parser : Opt_Parser := Command_Line_Parser) is Index : Integer; begin Parser.In_Expansion := False; if Name = "" then Parser.Current_Argument := 1; Parser.Current_Index := 1; Parser.Current_Section := 1; return; end if; Index := 1; while Index <= Parser.Arg_Count loop if Parser.Section (Index) = 0 and then Argument (Parser, Index) = Parser.Switch_Character & Name then Parser.Current_Argument := Index + 1; Parser.Current_Index := 1; if Parser.Current_Argument <= Parser.Arg_Count then Parser.Current_Section := Parser.Section (Parser.Current_Argument); end if; -- Exit from loop if we have the start of another section if Index = Parser.Section'Last or else Parser.Section (Index + 1) /= 0 then return; end if; end if; Index := Index + 1; end loop; Parser.Current_Argument := Positive'Last; Parser.Current_Index := 2; -- so that Get_Argument returns nothing end Goto_Section; ---------------------------- -- Initialize_Option_Scan -- ---------------------------- procedure Initialize_Option_Scan (Switch_Char : Character := '-'; Stop_At_First_Non_Switch : Boolean := False; Section_Delimiters : String := "") is begin Internal_Initialize_Option_Scan (Parser => Command_Line_Parser, Switch_Char => Switch_Char, Stop_At_First_Non_Switch => Stop_At_First_Non_Switch, Section_Delimiters => Section_Delimiters); end Initialize_Option_Scan; ---------------------------- -- Initialize_Option_Scan -- ---------------------------- procedure Initialize_Option_Scan (Parser : out Opt_Parser; Command_Line : GNAT.OS_Lib.Argument_List_Access; Switch_Char : Character := '-'; Stop_At_First_Non_Switch : Boolean := False; Section_Delimiters : String := "") is begin Free (Parser); if Command_Line = null then Parser := new Opt_Parser_Data (CL.Argument_Count); Internal_Initialize_Option_Scan (Parser => Parser, Switch_Char => Switch_Char, Stop_At_First_Non_Switch => Stop_At_First_Non_Switch, Section_Delimiters => Section_Delimiters); else Parser := new Opt_Parser_Data (Command_Line'Length); Parser.Arguments := Command_Line; Internal_Initialize_Option_Scan (Parser => Parser, Switch_Char => Switch_Char, Stop_At_First_Non_Switch => Stop_At_First_Non_Switch, Section_Delimiters => Section_Delimiters); end if; end Initialize_Option_Scan; ------------------------------------- -- Internal_Initialize_Option_Scan -- ------------------------------------- procedure Internal_Initialize_Option_Scan (Parser : Opt_Parser; Switch_Char : Character; Stop_At_First_Non_Switch : Boolean; Section_Delimiters : String) is Section_Num : Section_Number; Section_Index : Integer; Last : Integer; Delimiter_Found : Boolean; Discard : Boolean; pragma Warnings (Off, Discard); begin Parser.Current_Argument := 0; Parser.Current_Index := 0; Parser.In_Expansion := False; Parser.Switch_Character := Switch_Char; Parser.Stop_At_First := Stop_At_First_Non_Switch; Parser.Section := (others => 1); -- If we are using sections, we have to preprocess the command line to -- delimit them. A section can be repeated, so we just give each item -- on the command line a section number Section_Num := 1; Section_Index := Section_Delimiters'First; while Section_Index <= Section_Delimiters'Last loop Last := Section_Index; while Last <= Section_Delimiters'Last and then Section_Delimiters (Last) /= ' ' loop Last := Last + 1; end loop; Delimiter_Found := False; Section_Num := Section_Num + 1; for Index in 1 .. Parser.Arg_Count loop pragma Assert (Argument (Parser, Index)'First = 1); if Argument (Parser, Index) /= "" and then Argument (Parser, Index)(1) = Parser.Switch_Character and then Argument (Parser, Index) = Parser.Switch_Character & Section_Delimiters (Section_Index .. Last - 1) then Parser.Section (Index) := 0; Delimiter_Found := True; elsif Parser.Section (Index) = 0 then -- A previous section delimiter Delimiter_Found := False; elsif Delimiter_Found then Parser.Section (Index) := Section_Num; end if; end loop; Section_Index := Last + 1; while Section_Index <= Section_Delimiters'Last and then Section_Delimiters (Section_Index) = ' ' loop Section_Index := Section_Index + 1; end loop; end loop; Discard := Goto_Next_Argument_In_Section (Parser); end Internal_Initialize_Option_Scan; --------------- -- Parameter -- --------------- function Parameter (Parser : Opt_Parser := Command_Line_Parser) return String is begin if Parser.The_Parameter.First > Parser.The_Parameter.Last then return String'(1 .. 0 => ' '); else return Argument (Parser, Parser.The_Parameter.Arg_Num) (Parser.The_Parameter.First .. Parser.The_Parameter.Last); end if; end Parameter; --------------- -- Separator -- --------------- function Separator (Parser : Opt_Parser := Command_Line_Parser) return Character is begin return Parser.The_Separator; end Separator; ------------------- -- Set_Parameter -- ------------------- procedure Set_Parameter (Variable : out Parameter_Type; Arg_Num : Positive; First : Positive; Last : Natural; Extra : Character := ASCII.NUL) is begin Variable.Arg_Num := Arg_Num; Variable.First := First; Variable.Last := Last; Variable.Extra := Extra; end Set_Parameter; --------------------- -- Start_Expansion -- --------------------- procedure Start_Expansion (Iterator : out Expansion_Iterator; Pattern : String; Directory : String := ""; Basic_Regexp : Boolean := True) is Directory_Separator : Character; pragma Import (C, Directory_Separator, "__gnat_dir_separator"); First : Positive := Pattern'First; Pat : String := Pattern; begin Canonical_Case_File_Name (Pat); Iterator.Current_Depth := 1; -- If Directory is unspecified, use the current directory ("./" or ".\") if Directory = "" then Iterator.Dir_Name (1 .. 2) := "." & Directory_Separator; Iterator.Start := 3; else Iterator.Dir_Name (1 .. Directory'Length) := Directory; Iterator.Start := Directory'Length + 1; Canonical_Case_File_Name (Iterator.Dir_Name (1 .. Directory'Length)); -- Make sure that the last character is a directory separator if Directory (Directory'Last) /= Directory_Separator then Iterator.Dir_Name (Iterator.Start) := Directory_Separator; Iterator.Start := Iterator.Start + 1; end if; end if; Iterator.Levels (1).Name_Last := Iterator.Start - 1; -- Open the initial Directory, at depth 1 GNAT.Directory_Operations.Open (Iterator.Levels (1).Dir, Iterator.Dir_Name (1 .. Iterator.Start - 1)); -- If in the current directory and the pattern starts with "./" or ".\", -- drop the "./" or ".\" from the pattern. if Directory = "" and then Pat'Length > 2 and then Pat (Pat'First) = '.' and then Pat (Pat'First + 1) = Directory_Separator then First := Pat'First + 2; end if; Iterator.Regexp := GNAT.Regexp.Compile (Pat (First .. Pat'Last), Basic_Regexp, True); Iterator.Maximum_Depth := 1; -- Maximum_Depth is equal to 1 plus the number of directory separators -- in the pattern. for Index in First .. Pat'Last loop if Pat (Index) = Directory_Separator then Iterator.Maximum_Depth := Iterator.Maximum_Depth + 1; exit when Iterator.Maximum_Depth = Max_Depth; end if; end loop; end Start_Expansion; ---------- -- Free -- ---------- procedure Free (Parser : in out Opt_Parser) is procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Opt_Parser_Data, Opt_Parser); begin if Parser /= null and then Parser /= Command_Line_Parser then Free (Parser.Arguments); Unchecked_Free (Parser); end if; end Free; ------------------ -- Define_Alias -- ------------------ procedure Define_Alias (Config : in out Command_Line_Configuration; Switch : String; Expanded : String; Section : String := "") is Def : Alias_Definition; begin if Config = null then Config := new Command_Line_Configuration_Record; end if; Def.Alias := new String'(Switch); Def.Expansion := new String'(Expanded); Def.Section := new String'(Section); Add (Config.Aliases, Def); end Define_Alias; ------------------- -- Define_Prefix -- ------------------- procedure Define_Prefix (Config : in out Command_Line_Configuration; Prefix : String) is begin if Config = null then Config := new Command_Line_Configuration_Record; end if; Add (Config.Prefixes, new String'(Prefix)); end Define_Prefix; --------- -- Add -- --------- procedure Add (Config : in out Command_Line_Configuration; Switch : Switch_Definition) is procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Switch_Definitions, Switch_Definitions_List); Tmp : Switch_Definitions_List; begin if Config = null then Config := new Command_Line_Configuration_Record; end if; Tmp := Config.Switches; if Tmp = null then Config.Switches := new Switch_Definitions (1 .. 1); else Config.Switches := new Switch_Definitions (1 .. Tmp'Length + 1); Config.Switches (1 .. Tmp'Length) := Tmp.all; Unchecked_Free (Tmp); end if; if Switch.Switch /= null and then Switch.Switch.all = "*" then Config.Star_Switch := True; end if; Config.Switches (Config.Switches'Last) := Switch; end Add; --------- -- Add -- --------- procedure Add (Def : in out Alias_Definitions_List; Alias : Alias_Definition) is procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Alias_Definitions, Alias_Definitions_List); Tmp : Alias_Definitions_List := Def; begin if Tmp = null then Def := new Alias_Definitions (1 .. 1); else Def := new Alias_Definitions (1 .. Tmp'Length + 1); Def (1 .. Tmp'Length) := Tmp.all; Unchecked_Free (Tmp); end if; Def (Def'Last) := Alias; end Add; --------------------------- -- Initialize_Switch_Def -- --------------------------- procedure Initialize_Switch_Def (Def : out Switch_Definition; Switch : String := ""; Long_Switch : String := ""; Help : String := ""; Section : String := ""; Argument : String := "ARG") is P1, P2 : Switch_Parameter_Type := Parameter_None; Last1, Last2 : Integer; begin if Switch /= "" then Def.Switch := new String'(Switch); Decompose_Switch (Switch, P1, Last1); end if; if Long_Switch /= "" then Def.Long_Switch := new String'(Long_Switch); Decompose_Switch (Long_Switch, P2, Last2); end if; if Switch /= "" and then Long_Switch /= "" then if (P1 = Parameter_None and then P2 /= P1) or else (P2 = Parameter_None and then P1 /= P2) or else (P1 = Parameter_Optional and then P2 /= P1) or else (P2 = Parameter_Optional and then P2 /= P1) then raise Invalid_Switch with "Inconsistent parameter types for " & Switch & " and " & Long_Switch; end if; end if; if Section /= "" then Def.Section := new String'(Section); end if; if Argument /= "ARG" then Def.Argument := new String'(Argument); end if; if Help /= "" then Def.Help := new String'(Help); end if; end Initialize_Switch_Def; ------------------- -- Define_Switch -- ------------------- procedure Define_Switch (Config : in out Command_Line_Configuration; Switch : String := ""; Long_Switch : String := ""; Help : String := ""; Section : String := ""; Argument : String := "ARG") is Def : Switch_Definition; begin if Switch /= "" or else Long_Switch /= "" then Initialize_Switch_Def (Def, Switch, Long_Switch, Help, Section, Argument); Add (Config, Def); end if; end Define_Switch; ------------------- -- Define_Switch -- ------------------- procedure Define_Switch (Config : in out Command_Line_Configuration; Output : access Boolean; Switch : String := ""; Long_Switch : String := ""; Help : String := ""; Section : String := ""; Value : Boolean := True) is Def : Switch_Definition (Switch_Boolean); begin if Switch /= "" or else Long_Switch /= "" then Initialize_Switch_Def (Def, Switch, Long_Switch, Help, Section); Def.Boolean_Output := Output.all'Unchecked_Access; Def.Boolean_Value := Value; Add (Config, Def); end if; end Define_Switch; ------------------- -- Define_Switch -- ------------------- procedure Define_Switch (Config : in out Command_Line_Configuration; Output : access Integer; Switch : String := ""; Long_Switch : String := ""; Help : String := ""; Section : String := ""; Initial : Integer := 0; Default : Integer := 1; Argument : String := "ARG") is Def : Switch_Definition (Switch_Integer); begin if Switch /= "" or else Long_Switch /= "" then Initialize_Switch_Def (Def, Switch, Long_Switch, Help, Section, Argument); Def.Integer_Output := Output.all'Unchecked_Access; Def.Integer_Default := Default; Def.Integer_Initial := Initial; Add (Config, Def); end if; end Define_Switch; ------------------- -- Define_Switch -- ------------------- procedure Define_Switch (Config : in out Command_Line_Configuration; Output : access GNAT.Strings.String_Access; Switch : String := ""; Long_Switch : String := ""; Help : String := ""; Section : String := ""; Argument : String := "ARG") is Def : Switch_Definition (Switch_String); begin if Switch /= "" or else Long_Switch /= "" then Initialize_Switch_Def (Def, Switch, Long_Switch, Help, Section, Argument); Def.String_Output := Output.all'Unchecked_Access; Add (Config, Def); end if; end Define_Switch; -------------------- -- Define_Section -- -------------------- procedure Define_Section (Config : in out Command_Line_Configuration; Section : String) is begin if Config = null then Config := new Command_Line_Configuration_Record; end if; Add (Config.Sections, new String'(Section)); end Define_Section; -------------------- -- Foreach_Switch -- -------------------- procedure Foreach_Switch (Config : Command_Line_Configuration; Section : String) is begin if Config /= null and then Config.Switches /= null then for J in Config.Switches'Range loop if (Section = "" and then Config.Switches (J).Section = null) or else (Config.Switches (J).Section /= null and then Config.Switches (J).Section.all = Section) then exit when Config.Switches (J).Switch /= null and then not Callback (Config.Switches (J).Switch.all, J); exit when Config.Switches (J).Long_Switch /= null and then not Callback (Config.Switches (J).Long_Switch.all, J); end if; end loop; end if; end Foreach_Switch; ------------------ -- Get_Switches -- ------------------ function Get_Switches (Config : Command_Line_Configuration; Switch_Char : Character := '-'; Section : String := "") return String is Ret : Ada.Strings.Unbounded.Unbounded_String; use Ada.Strings.Unbounded; function Add_Switch (S : String; Index : Integer) return Boolean; -- Add a switch to Ret ---------------- -- Add_Switch -- ---------------- function Add_Switch (S : String; Index : Integer) return Boolean is pragma Unreferenced (Index); begin if S = "*" then Ret := "*" & Ret; -- Always first elsif S (S'First) = Switch_Char then Append (Ret, " " & S (S'First + 1 .. S'Last)); else Append (Ret, " " & S); end if; return True; end Add_Switch; Tmp : Boolean; pragma Unreferenced (Tmp); procedure Foreach is new Foreach_Switch (Add_Switch); -- Start of processing for Get_Switches begin if Config = null then return ""; end if; Foreach (Config, Section => Section); -- Add relevant aliases if Config.Aliases /= null then for A in Config.Aliases'Range loop if Config.Aliases (A).Section.all = Section then Tmp := Add_Switch (Config.Aliases (A).Alias.all, -1); end if; end loop; end if; return To_String (Ret); end Get_Switches; ------------------------ -- Section_Delimiters -- ------------------------ function Section_Delimiters (Config : Command_Line_Configuration) return String is use Ada.Strings.Unbounded; Result : Unbounded_String; begin if Config /= null and then Config.Sections /= null then for S in Config.Sections'Range loop Append (Result, " " & Config.Sections (S).all); end loop; end if; return To_String (Result); end Section_Delimiters; ----------------------- -- Set_Configuration -- ----------------------- procedure Set_Configuration (Cmd : in out Command_Line; Config : Command_Line_Configuration) is begin Cmd.Config := Config; end Set_Configuration; ----------------------- -- Get_Configuration -- ----------------------- function Get_Configuration (Cmd : Command_Line) return Command_Line_Configuration is begin return Cmd.Config; end Get_Configuration; ---------------------- -- Set_Command_Line -- ---------------------- procedure Set_Command_Line (Cmd : in out Command_Line; Switches : String; Getopt_Description : String := ""; Switch_Char : Character := '-') is Tmp : Argument_List_Access; Parser : Opt_Parser; S : Character; Section : String_Access := null; function Real_Full_Switch (S : Character; Parser : Opt_Parser) return String; -- Ensure that the returned switch value contains the Switch_Char prefix -- if needed. ---------------------- -- Real_Full_Switch -- ---------------------- function Real_Full_Switch (S : Character; Parser : Opt_Parser) return String is begin if S = '*' then return Full_Switch (Parser); else return Switch_Char & Full_Switch (Parser); end if; end Real_Full_Switch; -- Start of processing for Set_Command_Line begin Free (Cmd.Expanded); Free (Cmd.Params); if Switches /= "" then Tmp := Argument_String_To_List (Switches); Initialize_Option_Scan (Parser, Tmp, Switch_Char); loop begin if Cmd.Config /= null then -- Do not use Getopt_Description in this case. Otherwise, -- if we have defined a prefix -gnaty, and two switches -- -gnatya and -gnatyL!, we would have a different behavior -- depending on the order of switches: -- -gnatyL1a => -gnatyL with argument "1a" -- -gnatyaL1 => -gnatya and -gnatyL with argument "1" -- This is because the call to Getopt below knows nothing -- about prefixes, and in the first case finds a valid -- switch with arguments, so returns it without analyzing -- the argument. In the second case, the switch matches "*", -- and is then decomposed below. -- Note: When a Command_Line object is associated with a -- Command_Line_Config (which is mostly the case for tools -- that let users choose the command line before spawning -- other tools, for instance IDEs), the configuration of -- the switches must be taken from the Command_Line_Config. S := Getopt (Switches => "* " & Get_Switches (Cmd.Config), Concatenate => False, Parser => Parser); else S := Getopt (Switches => "* " & Getopt_Description, Concatenate => False, Parser => Parser); end if; exit when S = ASCII.NUL; declare Sw : constant String := Real_Full_Switch (S, Parser); Is_Section : Boolean := False; begin if Cmd.Config /= null and then Cmd.Config.Sections /= null then Section_Search : for S in Cmd.Config.Sections'Range loop if Sw = Cmd.Config.Sections (S).all then Section := Cmd.Config.Sections (S); Is_Section := True; exit Section_Search; end if; end loop Section_Search; end if; if not Is_Section then if Section = null then Add_Switch (Cmd, Sw, Parameter (Parser)); else Add_Switch (Cmd, Sw, Parameter (Parser), Section => Section.all); end if; end if; end; exception when Invalid_Parameter => -- Add it with no parameter, if that's the way the user -- wants it. -- Specify the separator in all cases, as the switch might -- need to be unaliased, and the alias might contain -- switches with parameters. if Section = null then Add_Switch (Cmd, Switch_Char & Full_Switch (Parser)); else Add_Switch (Cmd, Switch_Char & Full_Switch (Parser), Section => Section.all); end if; end; end loop; Free (Parser); end if; end Set_Command_Line; ---------------- -- Looking_At -- ---------------- function Looking_At (Type_Str : String; Index : Natural; Substring : String) return Boolean is begin return Index + Substring'Length - 1 <= Type_Str'Last and then Type_Str (Index .. Index + Substring'Length - 1) = Substring; end Looking_At; ------------------------ -- Can_Have_Parameter -- ------------------------ function Can_Have_Parameter (S : String) return Boolean is begin if S'Length <= 1 then return False; end if; case S (S'Last) is when '!' | ':' | '?' | '=' => return True; when others => return False; end case; end Can_Have_Parameter; ----------------------- -- Require_Parameter -- ----------------------- function Require_Parameter (S : String) return Boolean is begin if S'Length <= 1 then return False; end if; case S (S'Last) is when '!' | ':' | '=' => return True; when others => return False; end case; end Require_Parameter; ------------------- -- Actual_Switch -- ------------------- function Actual_Switch (S : String) return String is begin if S'Length <= 1 then return S; end if; case S (S'Last) is when '!' | ':' | '?' | '=' => return S (S'First .. S'Last - 1); when others => return S; end case; end Actual_Switch; ---------------------------- -- For_Each_Simple_Switch -- ---------------------------- procedure For_Each_Simple_Switch (Config : Command_Line_Configuration; Section : String; Switch : String; Parameter : String := ""; Unalias : Boolean := True) is function Group_Analysis (Prefix : String; Group : String) return Boolean; -- Perform the analysis of a group of switches Found_In_Config : Boolean := False; function Is_In_Config (Config_Switch : String; Index : Integer) return Boolean; -- If Switch is the same as Config_Switch, run the callback and sets -- Found_In_Config to True. function Starts_With (Config_Switch : String; Index : Integer) return Boolean; -- if Switch starts with Config_Switch, sets Found_In_Config to True. -- The return value is for the Foreach_Switch iterator. -------------------- -- Group_Analysis -- -------------------- function Group_Analysis (Prefix : String; Group : String) return Boolean is Idx : Natural; Found : Boolean; function Analyze_Simple_Switch (Switch : String; Index : Integer) return Boolean; -- "Switches" is one of the switch definitions passed to the -- configuration, not one of the switches found on the command line. --------------------------- -- Analyze_Simple_Switch -- --------------------------- function Analyze_Simple_Switch (Switch : String; Index : Integer) return Boolean is pragma Unreferenced (Index); Full : constant String := Prefix & Group (Idx .. Group'Last); Sw : constant String := Actual_Switch (Switch); -- Switches definition minus argument definition Last : Natural; Param : Natural; begin -- Verify that sw starts with Prefix if Looking_At (Sw, Sw'First, Prefix) -- Verify that the group starts with sw and then Looking_At (Full, Full'First, Sw) then Last := Idx + Sw'Length - Prefix'Length - 1; Param := Last + 1; if Can_Have_Parameter (Switch) then -- Include potential parameter to the recursive call. Only -- numbers are allowed. while Last < Group'Last and then Group (Last + 1) in '0' .. '9' loop Last := Last + 1; end loop; end if; if not Require_Parameter (Switch) or else Last >= Param then if Idx = Group'First and then Last = Group'Last and then Last < Param then -- The group only concerns a single switch. Do not -- perform recursive call. -- Note that we still perform a recursive call if -- a parameter is detected in the switch, as this -- is a way to correctly identify such a parameter -- in aliases. return False; end if; Found := True; -- Recursive call, using the detected parameter if any if Last >= Param then For_Each_Simple_Switch (Config, Section, Prefix & Group (Idx .. Param - 1), Group (Param .. Last)); else For_Each_Simple_Switch (Config, Section, Prefix & Group (Idx .. Last), ""); end if; Idx := Last + 1; return False; end if; end if; return True; end Analyze_Simple_Switch; procedure Foreach is new Foreach_Switch (Analyze_Simple_Switch); -- Start of processing for Group_Analysis begin Idx := Group'First; while Idx <= Group'Last loop Found := False; Foreach (Config, Section); if not Found then For_Each_Simple_Switch (Config, Section, Prefix & Group (Idx), ""); Idx := Idx + 1; end if; end loop; return True; end Group_Analysis; ------------------ -- Is_In_Config -- ------------------ function Is_In_Config (Config_Switch : String; Index : Integer) return Boolean is Last : Natural; P : Switch_Parameter_Type; begin Decompose_Switch (Config_Switch, P, Last); if Config_Switch (Config_Switch'First .. Last) = Switch then case P is when Parameter_None => if Parameter = "" then Callback (Switch, "", "", Index => Index); Found_In_Config := True; return False; end if; when Parameter_With_Optional_Space => Callback (Switch, " ", Parameter, Index => Index); Found_In_Config := True; return False; when Parameter_With_Space_Or_Equal => Callback (Switch, "=", Parameter, Index => Index); Found_In_Config := True; return False; when Parameter_No_Space => Callback (Switch, "", Parameter, Index); Found_In_Config := True; return False; when Parameter_Optional => Callback (Switch, "", Parameter, Index); Found_In_Config := True; return False; end case; end if; return True; end Is_In_Config; ----------------- -- Starts_With -- ----------------- function Starts_With (Config_Switch : String; Index : Integer) return Boolean is Last : Natural; Param : Natural; P : Switch_Parameter_Type; begin -- This function is called when we believe the parameter was -- specified as part of the switch, instead of separately. Thus we -- look in the config to find all possible switches. Decompose_Switch (Config_Switch, P, Last); if Looking_At (Switch, Switch'First, Config_Switch (Config_Switch'First .. Last)) then -- Set first char of Param, and last char of Switch Param := Switch'First + Last; Last := Switch'First + Last - Config_Switch'First; case P is -- None is already handled in Is_In_Config when Parameter_None => null; when Parameter_With_Space_Or_Equal => if Param <= Switch'Last and then (Switch (Param) = ' ' or else Switch (Param) = '=') then Callback (Switch (Switch'First .. Last), "=", Switch (Param + 1 .. Switch'Last), Index); Found_In_Config := True; return False; end if; when Parameter_With_Optional_Space => if Param <= Switch'Last and then Switch (Param) = ' ' then Param := Param + 1; end if; Callback (Switch (Switch'First .. Last), " ", Switch (Param .. Switch'Last), Index); Found_In_Config := True; return False; when Parameter_No_Space | Parameter_Optional => Callback (Switch (Switch'First .. Last), "", Switch (Param .. Switch'Last), Index); Found_In_Config := True; return False; end case; end if; return True; end Starts_With; procedure Foreach_In_Config is new Foreach_Switch (Is_In_Config); procedure Foreach_Starts_With is new Foreach_Switch (Starts_With); -- Start of processing for For_Each_Simple_Switch begin -- First determine if the switch corresponds to one belonging to the -- configuration. If so, run callback and exit. -- ??? Is this necessary. On simple tests, we seem to have the same -- results with or without this call. Foreach_In_Config (Config, Section); if Found_In_Config then return; end if; -- If adding a switch that can in fact be expanded through aliases, -- add separately each of its expansions. -- This takes care of expansions like "-T" -> "-gnatwrs", where the -- alias and its expansion do not have the same prefix. Given the order -- in which we do things here, the expansion of the alias will itself -- be checked for a common prefix and split into simple switches. if Unalias and then Config /= null and then Config.Aliases /= null then for A in Config.Aliases'Range loop if Config.Aliases (A).Section.all = Section and then Config.Aliases (A).Alias.all = Switch and then Parameter = "" then For_Each_Simple_Switch (Config, Section, Config.Aliases (A).Expansion.all, ""); return; end if; end loop; end if; -- If adding a switch grouping several switches, add each of the simple -- switches instead. if Config /= null and then Config.Prefixes /= null then for P in Config.Prefixes'Range loop if Switch'Length > Config.Prefixes (P)'Length + 1 and then Looking_At (Switch, Switch'First, Config.Prefixes (P).all) then -- Alias expansion will be done recursively if Config.Switches = null then for S in Switch'First + Config.Prefixes (P)'Length .. Switch'Last loop For_Each_Simple_Switch (Config, Section, Config.Prefixes (P).all & Switch (S), ""); end loop; return; elsif Group_Analysis (Config.Prefixes (P).all, Switch (Switch'First + Config.Prefixes (P)'Length .. Switch'Last)) then -- Recursive calls already done on each switch of the group: -- Return without executing Callback. return; end if; end if; end loop; end if; -- Test if added switch is a known switch with parameter attached -- instead of being specified separately if Parameter = "" and then Config /= null and then Config.Switches /= null then Found_In_Config := False; Foreach_Starts_With (Config, Section); if Found_In_Config then return; end if; end if; -- The switch is invalid in the config, but we still want to report it. -- The config could, for instance, include "*" to specify it accepts -- all switches. Callback (Switch, " ", Parameter, Index => -1); end For_Each_Simple_Switch; ---------------- -- Add_Switch -- ---------------- procedure Add_Switch (Cmd : in out Command_Line; Switch : String; Parameter : String := ""; Separator : Character := ASCII.NUL; Section : String := ""; Add_Before : Boolean := False) is Success : Boolean; pragma Unreferenced (Success); begin Add_Switch (Cmd, Switch, Parameter, Separator, Section, Add_Before, Success); end Add_Switch; ---------------- -- Add_Switch -- ---------------- procedure Add_Switch (Cmd : in out Command_Line; Switch : String; Parameter : String := ""; Separator : Character := ASCII.NUL; Section : String := ""; Add_Before : Boolean := False; Success : out Boolean) is procedure Add_Simple_Switch (Simple : String; Sepa : String; Param : String; Index : Integer); -- Add a new switch that has had all its aliases expanded, and switches -- ungrouped. We know there are no more aliases in Switches. ----------------------- -- Add_Simple_Switch -- ----------------------- procedure Add_Simple_Switch (Simple : String; Sepa : String; Param : String; Index : Integer) is Sep : Character; begin if Index = -1 and then Cmd.Config /= null and then not Cmd.Config.Star_Switch then raise Invalid_Switch with "Invalid switch " & Simple; end if; if Separator /= ASCII.NUL then Sep := Separator; elsif Sepa = "" then Sep := ASCII.NUL; else Sep := Sepa (Sepa'First); end if; if Cmd.Expanded = null then Cmd.Expanded := new Argument_List'(1 .. 1 => new String'(Simple)); if Param /= "" then Cmd.Params := new Argument_List'(1 .. 1 => new String'(Sep & Param)); else Cmd.Params := new Argument_List'(1 .. 1 => null); end if; if Section = "" then Cmd.Sections := new Argument_List'(1 .. 1 => null); else Cmd.Sections := new Argument_List'(1 .. 1 => new String'(Section)); end if; else -- Do we already have this switch? for C in Cmd.Expanded'Range loop if Cmd.Expanded (C).all = Simple and then ((Cmd.Params (C) = null and then Param = "") or else (Cmd.Params (C) /= null and then Cmd.Params (C).all = Sep & Param)) and then ((Cmd.Sections (C) = null and then Section = "") or else (Cmd.Sections (C) /= null and then Cmd.Sections (C).all = Section)) then return; end if; end loop; -- Inserting at least one switch Success := True; Add (Cmd.Expanded, new String'(Simple), Add_Before); if Param /= "" then Add (Cmd.Params, new String'(Sep & Param), Add_Before); else Add (Cmd.Params, null, Add_Before); end if; if Section = "" then Add (Cmd.Sections, null, Add_Before); else Add (Cmd.Sections, new String'(Section), Add_Before); end if; end if; end Add_Simple_Switch; procedure Add_Simple_Switches is new For_Each_Simple_Switch (Add_Simple_Switch); -- Local Variables Section_Valid : Boolean := False; -- Start of processing for Add_Switch begin if Section /= "" and then Cmd.Config /= null then for S in Cmd.Config.Sections'Range loop if Section = Cmd.Config.Sections (S).all then Section_Valid := True; exit; end if; end loop; if not Section_Valid then raise Invalid_Section; end if; end if; Success := False; Add_Simple_Switches (Cmd.Config, Section, Switch, Parameter); Free (Cmd.Coalesce); end Add_Switch; ------------ -- Remove -- ------------ procedure Remove (Line : in out Argument_List_Access; Index : Integer) is Tmp : Argument_List_Access := Line; begin Line := new Argument_List (Tmp'First .. Tmp'Last - 1); if Index /= Tmp'First then Line (Tmp'First .. Index - 1) := Tmp (Tmp'First .. Index - 1); end if; Free (Tmp (Index)); if Index /= Tmp'Last then Line (Index .. Tmp'Last - 1) := Tmp (Index + 1 .. Tmp'Last); end if; Unchecked_Free (Tmp); end Remove; --------- -- Add -- --------- procedure Add (Line : in out Argument_List_Access; Str : String_Access; Before : Boolean := False) is Tmp : Argument_List_Access := Line; begin if Tmp /= null then Line := new Argument_List (Tmp'First .. Tmp'Last + 1); if Before then Line (Tmp'First) := Str; Line (Tmp'First + 1 .. Tmp'Last + 1) := Tmp.all; else Line (Tmp'Range) := Tmp.all; Line (Tmp'Last + 1) := Str; end if; Unchecked_Free (Tmp); else Line := new Argument_List'(1 .. 1 => Str); end if; end Add; ------------------- -- Remove_Switch -- ------------------- procedure Remove_Switch (Cmd : in out Command_Line; Switch : String; Remove_All : Boolean := False; Has_Parameter : Boolean := False; Section : String := "") is Success : Boolean; pragma Unreferenced (Success); begin Remove_Switch (Cmd, Switch, Remove_All, Has_Parameter, Section, Success); end Remove_Switch; ------------------- -- Remove_Switch -- ------------------- procedure Remove_Switch (Cmd : in out Command_Line; Switch : String; Remove_All : Boolean := False; Has_Parameter : Boolean := False; Section : String := ""; Success : out Boolean) is procedure Remove_Simple_Switch (Simple, Separator, Param : String; Index : Integer); -- Removes a simple switch, with no aliasing or grouping -------------------------- -- Remove_Simple_Switch -- -------------------------- procedure Remove_Simple_Switch (Simple, Separator, Param : String; Index : Integer) is C : Integer; pragma Unreferenced (Param, Separator, Index); begin if Cmd.Expanded /= null then C := Cmd.Expanded'First; while C <= Cmd.Expanded'Last loop if Cmd.Expanded (C).all = Simple and then (Remove_All or else (Cmd.Sections (C) = null and then Section = "") or else (Cmd.Sections (C) /= null and then Section = Cmd.Sections (C).all)) and then (not Has_Parameter or else Cmd.Params (C) /= null) then Remove (Cmd.Expanded, C); Remove (Cmd.Params, C); Remove (Cmd.Sections, C); Success := True; if not Remove_All then return; end if; else C := C + 1; end if; end loop; end if; end Remove_Simple_Switch; procedure Remove_Simple_Switches is new For_Each_Simple_Switch (Remove_Simple_Switch); -- Start of processing for Remove_Switch begin Success := False; Remove_Simple_Switches (Cmd.Config, Section, Switch, "", Unalias => not Has_Parameter); Free (Cmd.Coalesce); end Remove_Switch; ------------------- -- Remove_Switch -- ------------------- procedure Remove_Switch (Cmd : in out Command_Line; Switch : String; Parameter : String; Section : String := "") is procedure Remove_Simple_Switch (Simple, Separator, Param : String; Index : Integer); -- Removes a simple switch, with no aliasing or grouping -------------------------- -- Remove_Simple_Switch -- -------------------------- procedure Remove_Simple_Switch (Simple, Separator, Param : String; Index : Integer) is pragma Unreferenced (Separator, Index); C : Integer; begin if Cmd.Expanded /= null then C := Cmd.Expanded'First; while C <= Cmd.Expanded'Last loop if Cmd.Expanded (C).all = Simple and then ((Cmd.Sections (C) = null and then Section = "") or else (Cmd.Sections (C) /= null and then Section = Cmd.Sections (C).all)) and then ((Cmd.Params (C) = null and then Param = "") or else (Cmd.Params (C) /= null -- Ignore the separator stored in Parameter and then Cmd.Params (C) (Cmd.Params (C)'First + 1 .. Cmd.Params (C)'Last) = Param)) then Remove (Cmd.Expanded, C); Remove (Cmd.Params, C); Remove (Cmd.Sections, C); -- The switch is necessarily unique by construction of -- Add_Switch. return; else C := C + 1; end if; end loop; end if; end Remove_Simple_Switch; procedure Remove_Simple_Switches is new For_Each_Simple_Switch (Remove_Simple_Switch); -- Start of processing for Remove_Switch begin Remove_Simple_Switches (Cmd.Config, Section, Switch, Parameter); Free (Cmd.Coalesce); end Remove_Switch; -------------------- -- Group_Switches -- -------------------- procedure Group_Switches (Cmd : Command_Line; Result : Argument_List_Access; Sections : Argument_List_Access; Params : Argument_List_Access) is function Compatible_Parameter (Param : String_Access) return Boolean; -- True when the parameter can be part of a group -------------------------- -- Compatible_Parameter -- -------------------------- function Compatible_Parameter (Param : String_Access) return Boolean is begin -- No parameter OK if Param = null then return True; -- We need parameters without separators elsif Param (Param'First) /= ASCII.NUL then return False; -- Parameters must be all digits else for J in Param'First + 1 .. Param'Last loop if Param (J) not in '0' .. '9' then return False; end if; end loop; return True; end if; end Compatible_Parameter; -- Local declarations Group : Ada.Strings.Unbounded.Unbounded_String; First : Natural; use type Ada.Strings.Unbounded.Unbounded_String; -- Start of processing for Group_Switches begin if Cmd.Config = null or else Cmd.Config.Prefixes = null then return; end if; for P in Cmd.Config.Prefixes'Range loop Group := Ada.Strings.Unbounded.Null_Unbounded_String; First := 0; for C in Result'Range loop if Result (C) /= null and then Compatible_Parameter (Params (C)) and then Looking_At (Result (C).all, Result (C)'First, Cmd.Config.Prefixes (P).all) then -- If we are still in the same section, group the switches if First = 0 or else (Sections (C) = null and then Sections (First) = null) or else (Sections (C) /= null and then Sections (First) /= null and then Sections (C).all = Sections (First).all) then Group := Group & Result (C) (Result (C)'First + Cmd.Config.Prefixes (P)'Length .. Result (C)'Last); if Params (C) /= null then Group := Group & Params (C) (Params (C)'First + 1 .. Params (C)'Last); Free (Params (C)); end if; if First = 0 then First := C; end if; Free (Result (C)); -- We changed section: we put the grouped switches to the first -- place, on continue with the new section. else Result (First) := new String' (Cmd.Config.Prefixes (P).all & Ada.Strings.Unbounded.To_String (Group)); Group := Ada.Strings.Unbounded.To_Unbounded_String (Result (C) (Result (C)'First + Cmd.Config.Prefixes (P)'Length .. Result (C)'Last)); First := C; end if; end if; end loop; if First > 0 then Result (First) := new String' (Cmd.Config.Prefixes (P).all & Ada.Strings.Unbounded.To_String (Group)); end if; end loop; end Group_Switches; -------------------- -- Alias_Switches -- -------------------- procedure Alias_Switches (Cmd : Command_Line; Result : Argument_List_Access; Params : Argument_List_Access) is Found : Boolean; First : Natural; procedure Check_Cb (Switch, Separator, Param : String; Index : Integer); -- Checks whether the command line contains [Switch]. Sets the global -- variable [Found] appropriately. This is called for each simple switch -- that make up an alias, to know whether the alias should be applied. procedure Remove_Cb (Switch, Separator, Param : String; Index : Integer); -- Remove the simple switch [Switch] from the command line, since it is -- part of a simpler alias -------------- -- Check_Cb -- -------------- procedure Check_Cb (Switch, Separator, Param : String; Index : Integer) is pragma Unreferenced (Separator, Index); begin if Found then for E in Result'Range loop if Result (E) /= null and then (Params (E) = null or else Params (E) (Params (E)'First + 1 .. Params (E)'Last) = Param) and then Result (E).all = Switch then return; end if; end loop; Found := False; end if; end Check_Cb; --------------- -- Remove_Cb -- --------------- procedure Remove_Cb (Switch, Separator, Param : String; Index : Integer) is pragma Unreferenced (Separator, Index); begin for E in Result'Range loop if Result (E) /= null and then (Params (E) = null or else Params (E) (Params (E)'First + 1 .. Params (E)'Last) = Param) and then Result (E).all = Switch then if First > E then First := E; end if; Free (Result (E)); Free (Params (E)); return; end if; end loop; end Remove_Cb; procedure Check_All is new For_Each_Simple_Switch (Check_Cb); procedure Remove_All is new For_Each_Simple_Switch (Remove_Cb); -- Start of processing for Alias_Switches begin if Cmd.Config = null or else Cmd.Config.Aliases = null then return; end if; for A in Cmd.Config.Aliases'Range loop -- Compute the various simple switches that make up the alias. We -- split the expansion into as many simple switches as possible, and -- then check whether the expanded command line has all of them. Found := True; Check_All (Cmd.Config, Switch => Cmd.Config.Aliases (A).Expansion.all, Section => Cmd.Config.Aliases (A).Section.all); if Found then First := Integer'Last; Remove_All (Cmd.Config, Switch => Cmd.Config.Aliases (A).Expansion.all, Section => Cmd.Config.Aliases (A).Section.all); Result (First) := new String'(Cmd.Config.Aliases (A).Alias.all); end if; end loop; end Alias_Switches; ------------------- -- Sort_Sections -- ------------------- procedure Sort_Sections (Line : GNAT.OS_Lib.Argument_List_Access; Sections : GNAT.OS_Lib.Argument_List_Access; Params : GNAT.OS_Lib.Argument_List_Access) is Sections_List : Argument_List_Access := new Argument_List'(1 .. 1 => null); Found : Boolean; Old_Line : constant Argument_List := Line.all; Old_Sections : constant Argument_List := Sections.all; Old_Params : constant Argument_List := Params.all; Index : Natural; begin if Line = null then return; end if; -- First construct a list of all sections for E in Line'Range loop if Sections (E) /= null then Found := False; for S in Sections_List'Range loop if (Sections_List (S) = null and then Sections (E) = null) or else (Sections_List (S) /= null and then Sections (E) /= null and then Sections_List (S).all = Sections (E).all) then Found := True; exit; end if; end loop; if not Found then Add (Sections_List, Sections (E)); end if; end if; end loop; Index := Line'First; for S in Sections_List'Range loop for E in Old_Line'Range loop if (Sections_List (S) = null and then Old_Sections (E) = null) or else (Sections_List (S) /= null and then Old_Sections (E) /= null and then Sections_List (S).all = Old_Sections (E).all) then Line (Index) := Old_Line (E); Sections (Index) := Old_Sections (E); Params (Index) := Old_Params (E); Index := Index + 1; end if; end loop; end loop; Unchecked_Free (Sections_List); end Sort_Sections; ----------- -- Start -- ----------- procedure Start (Cmd : in out Command_Line; Iter : in out Command_Line_Iterator; Expanded : Boolean := False) is begin if Cmd.Expanded = null then Iter.List := null; return; end if; -- Reorder the expanded line so that sections are grouped Sort_Sections (Cmd.Expanded, Cmd.Sections, Cmd.Params); -- Coalesce the switches as much as possible if not Expanded and then Cmd.Coalesce = null then Cmd.Coalesce := new Argument_List (Cmd.Expanded'Range); for E in Cmd.Expanded'Range loop Cmd.Coalesce (E) := new String'(Cmd.Expanded (E).all); end loop; Free (Cmd.Coalesce_Sections); Cmd.Coalesce_Sections := new Argument_List (Cmd.Sections'Range); for E in Cmd.Sections'Range loop Cmd.Coalesce_Sections (E) := (if Cmd.Sections (E) = null then null else new String'(Cmd.Sections (E).all)); end loop; Free (Cmd.Coalesce_Params); Cmd.Coalesce_Params := new Argument_List (Cmd.Params'Range); for E in Cmd.Params'Range loop Cmd.Coalesce_Params (E) := (if Cmd.Params (E) = null then null else new String'(Cmd.Params (E).all)); end loop; -- Not a clone, since we will not modify the parameters anyway Alias_Switches (Cmd, Cmd.Coalesce, Cmd.Coalesce_Params); Group_Switches (Cmd, Cmd.Coalesce, Cmd.Coalesce_Sections, Cmd.Coalesce_Params); end if; if Expanded then Iter.List := Cmd.Expanded; Iter.Params := Cmd.Params; Iter.Sections := Cmd.Sections; else Iter.List := Cmd.Coalesce; Iter.Params := Cmd.Coalesce_Params; Iter.Sections := Cmd.Coalesce_Sections; end if; if Iter.List = null then Iter.Current := Integer'Last; else Iter.Current := Iter.List'First - 1; Next (Iter); end if; end Start; -------------------- -- Current_Switch -- -------------------- function Current_Switch (Iter : Command_Line_Iterator) return String is begin return Iter.List (Iter.Current).all; end Current_Switch; -------------------- -- Is_New_Section -- -------------------- function Is_New_Section (Iter : Command_Line_Iterator) return Boolean is Section : constant String := Current_Section (Iter); begin if Iter.Sections = null then return False; elsif Iter.Current = Iter.Sections'First or else Iter.Sections (Iter.Current - 1) = null then return Section /= ""; else return Section /= Iter.Sections (Iter.Current - 1).all; end if; end Is_New_Section; --------------------- -- Current_Section -- --------------------- function Current_Section (Iter : Command_Line_Iterator) return String is begin if Iter.Sections = null or else Iter.Current > Iter.Sections'Last or else Iter.Sections (Iter.Current) = null then return ""; end if; return Iter.Sections (Iter.Current).all; end Current_Section; ----------------------- -- Current_Separator -- ----------------------- function Current_Separator (Iter : Command_Line_Iterator) return String is begin if Iter.Params = null or else Iter.Current > Iter.Params'Last or else Iter.Params (Iter.Current) = null then return ""; else declare Sep : constant Character := Iter.Params (Iter.Current) (Iter.Params (Iter.Current)'First); begin if Sep = ASCII.NUL then return ""; else return "" & Sep; end if; end; end if; end Current_Separator; ----------------------- -- Current_Parameter -- ----------------------- function Current_Parameter (Iter : Command_Line_Iterator) return String is begin if Iter.Params = null or else Iter.Current > Iter.Params'Last or else Iter.Params (Iter.Current) = null then return ""; else -- Return result, skipping separator declare P : constant String := Iter.Params (Iter.Current).all; begin return P (P'First + 1 .. P'Last); end; end if; end Current_Parameter; -------------- -- Has_More -- -------------- function Has_More (Iter : Command_Line_Iterator) return Boolean is begin return Iter.List /= null and then Iter.Current <= Iter.List'Last; end Has_More; ---------- -- Next -- ---------- procedure Next (Iter : in out Command_Line_Iterator) is begin Iter.Current := Iter.Current + 1; while Iter.Current <= Iter.List'Last and then Iter.List (Iter.Current) = null loop Iter.Current := Iter.Current + 1; end loop; end Next; ---------- -- Free -- ---------- procedure Free (Config : in out Command_Line_Configuration) is procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Switch_Definitions, Switch_Definitions_List); procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Alias_Definitions, Alias_Definitions_List); begin if Config /= null then Free (Config.Prefixes); Free (Config.Sections); Free (Config.Usage); Free (Config.Help); Free (Config.Help_Msg); if Config.Aliases /= null then for A in Config.Aliases'Range loop Free (Config.Aliases (A).Alias); Free (Config.Aliases (A).Expansion); Free (Config.Aliases (A).Section); end loop; Unchecked_Free (Config.Aliases); end if; if Config.Switches /= null then for S in Config.Switches'Range loop Free (Config.Switches (S).Switch); Free (Config.Switches (S).Long_Switch); Free (Config.Switches (S).Help); Free (Config.Switches (S).Section); Free (Config.Switches (S).Argument); end loop; Unchecked_Free (Config.Switches); end if; Unchecked_Free (Config); end if; end Free; ---------- -- Free -- ---------- procedure Free (Cmd : in out Command_Line) is begin Free (Cmd.Expanded); Free (Cmd.Coalesce); Free (Cmd.Coalesce_Sections); Free (Cmd.Coalesce_Params); Free (Cmd.Params); Free (Cmd.Sections); end Free; --------------- -- Set_Usage -- --------------- procedure Set_Usage (Config : in out Command_Line_Configuration; Usage : String := "[switches] [arguments]"; Help : String := ""; Help_Msg : String := "") is begin if Config = null then Config := new Command_Line_Configuration_Record; end if; Free (Config.Usage); Free (Config.Help); Free (Config.Help_Msg); Config.Usage := new String'(Usage); Config.Help := new String'(Help); Config.Help_Msg := new String'(Help_Msg); end Set_Usage; ------------------ -- Display_Help -- ------------------ procedure Display_Help (Config : Command_Line_Configuration) is function Switch_Name (Def : Switch_Definition; Section : String) return String; -- Return the "-short, --long=ARG" string for Def. -- Returns "" if the switch is not in the section. function Param_Name (P : Switch_Parameter_Type; Name : String := "ARG") return String; -- Return the display for a switch parameter procedure Display_Section_Help (Section : String); -- Display the help for a specific section ("" is the default section) -------------------------- -- Display_Section_Help -- -------------------------- procedure Display_Section_Help (Section : String) is Max_Len : Natural := 0; begin -- ??? Special display for "*" New_Line; if Section /= "" and then Config.Switches /= null then Put_Line ("Switches after " & Section); end if; -- Compute size of the switches column if Config.Switches /= null then for S in Config.Switches'Range loop Max_Len := Natural'Max (Max_Len, Switch_Name (Config.Switches (S), Section)'Length); end loop; end if; if Config.Aliases /= null then for A in Config.Aliases'Range loop if Config.Aliases (A).Section.all = Section then Max_Len := Natural'Max (Max_Len, Config.Aliases (A).Alias'Length); end if; end loop; end if; -- Display the switches if Config.Switches /= null then for S in Config.Switches'Range loop declare N : constant String := Switch_Name (Config.Switches (S), Section); begin if N /= "" then Put (" "); Put (N); Put ((1 .. Max_Len - N'Length + 1 => ' ')); if Config.Switches (S).Help /= null then Put (Config.Switches (S).Help.all); end if; New_Line; end if; end; end loop; end if; -- Display the aliases if Config.Aliases /= null then for A in Config.Aliases'Range loop if Config.Aliases (A).Section.all = Section then Put (" "); Put (Config.Aliases (A).Alias.all); Put ((1 .. Max_Len - Config.Aliases (A).Alias'Length + 1 => ' ')); Put ("Equivalent to " & Config.Aliases (A).Expansion.all); New_Line; end if; end loop; end if; end Display_Section_Help; ---------------- -- Param_Name -- ---------------- function Param_Name (P : Switch_Parameter_Type; Name : String := "ARG") return String is begin case P is when Parameter_None => return ""; when Parameter_With_Optional_Space => return " " & To_Upper (Name); when Parameter_With_Space_Or_Equal => return "=" & To_Upper (Name); when Parameter_No_Space => return To_Upper (Name); when Parameter_Optional => return '[' & To_Upper (Name) & ']'; end case; end Param_Name; ----------------- -- Switch_Name -- ----------------- function Switch_Name (Def : Switch_Definition; Section : String) return String is use Ada.Strings.Unbounded; Result : Unbounded_String; P1, P2 : Switch_Parameter_Type; Last1, Last2 : Integer := 0; begin if (Section = "" and then Def.Section = null) or else (Def.Section /= null and then Def.Section.all = Section) then if Def.Switch /= null and then Def.Switch.all = "*" then return "[any switch]"; end if; if Def.Switch /= null then Decompose_Switch (Def.Switch.all, P1, Last1); Append (Result, Def.Switch (Def.Switch'First .. Last1)); if Def.Long_Switch /= null then Decompose_Switch (Def.Long_Switch.all, P2, Last2); Append (Result, ", " & Def.Long_Switch (Def.Long_Switch'First .. Last2)); if Def.Argument = null then Append (Result, Param_Name (P2, "ARG")); else Append (Result, Param_Name (P2, Def.Argument.all)); end if; else if Def.Argument = null then Append (Result, Param_Name (P1, "ARG")); else Append (Result, Param_Name (P1, Def.Argument.all)); end if; end if; -- Def.Switch is null (Long_Switch must be non-null) else Decompose_Switch (Def.Long_Switch.all, P2, Last2); Append (Result, Def.Long_Switch (Def.Long_Switch'First .. Last2)); if Def.Argument = null then Append (Result, Param_Name (P2, "ARG")); else Append (Result, Param_Name (P2, Def.Argument.all)); end if; end if; end if; return To_String (Result); end Switch_Name; -- Start of processing for Display_Help begin if Config = null then return; end if; if Config.Help /= null and then Config.Help.all /= "" then Put_Line (Config.Help.all); end if; if Config.Usage /= null then Put_Line ("Usage: " & Base_Name (Ada.Command_Line.Command_Name) & " " & Config.Usage.all); else Put_Line ("Usage: " & Base_Name (Ada.Command_Line.Command_Name) & " [switches] [arguments]"); end if; if Config.Help_Msg /= null and then Config.Help_Msg.all /= "" then Put_Line (Config.Help_Msg.all); else Display_Section_Help (""); if Config.Sections /= null and then Config.Switches /= null then for S in Config.Sections'Range loop Display_Section_Help (Config.Sections (S).all); end loop; end if; end if; end Display_Help; ------------ -- Getopt -- ------------ procedure Getopt (Config : Command_Line_Configuration; Callback : Switch_Handler := null; Parser : Opt_Parser := Command_Line_Parser; Concatenate : Boolean := True) is Getopt_Switches : String_Access; C : Character := ASCII.NUL; Empty_Name : aliased constant String := ""; Current_Section : Integer := -1; Section_Name : not null access constant String := Empty_Name'Access; procedure Simple_Callback (Simple_Switch : String; Separator : String; Parameter : String; Index : Integer); -- Needs comments ??? procedure Do_Callback (Switch, Parameter : String; Index : Integer); ----------------- -- Do_Callback -- ----------------- procedure Do_Callback (Switch, Parameter : String; Index : Integer) is begin -- Do automatic handling when possible if Index /= -1 then case Config.Switches (Index).Typ is when Switch_Untyped => null; -- no automatic handling when Switch_Boolean => Config.Switches (Index).Boolean_Output.all := Config.Switches (Index).Boolean_Value; return; when Switch_Integer => begin if Parameter = "" then Config.Switches (Index).Integer_Output.all := Config.Switches (Index).Integer_Default; else Config.Switches (Index).Integer_Output.all := Integer'Value (Parameter); end if; exception when Constraint_Error => raise Invalid_Parameter with "Expected integer parameter for '" & Switch & "'"; end; return; when Switch_String => Free (Config.Switches (Index).String_Output.all); Config.Switches (Index).String_Output.all := new String'(Parameter); return; end case; end if; -- Otherwise calls the user callback if one was defined if Callback /= null then Callback (Switch => Switch, Parameter => Parameter, Section => Section_Name.all); end if; end Do_Callback; procedure For_Each_Simple is new For_Each_Simple_Switch (Simple_Callback); --------------------- -- Simple_Callback -- --------------------- procedure Simple_Callback (Simple_Switch : String; Separator : String; Parameter : String; Index : Integer) is pragma Unreferenced (Separator); begin Do_Callback (Switch => Simple_Switch, Parameter => Parameter, Index => Index); end Simple_Callback; -- Start of processing for Getopt begin -- Initialize sections if Config.Sections = null then Config.Sections := new Argument_List'(1 .. 0 => null); end if; Internal_Initialize_Option_Scan (Parser => Parser, Switch_Char => Parser.Switch_Character, Stop_At_First_Non_Switch => Parser.Stop_At_First, Section_Delimiters => Section_Delimiters (Config)); Getopt_Switches := new String' (Get_Switches (Config, Parser.Switch_Character, Section_Name.all) & " h -help"); -- Initialize output values for automatically handled switches if Config.Switches /= null then for S in Config.Switches'Range loop case Config.Switches (S).Typ is when Switch_Untyped => null; -- Nothing to do when Switch_Boolean => Config.Switches (S).Boolean_Output.all := not Config.Switches (S).Boolean_Value; when Switch_Integer => Config.Switches (S).Integer_Output.all := Config.Switches (S).Integer_Initial; when Switch_String => if Config.Switches (S).String_Output.all = null then Config.Switches (S).String_Output.all := new String'(""); end if; end case; end loop; end if; -- For all sections, and all switches within those sections loop C := Getopt (Switches => Getopt_Switches.all, Concatenate => Concatenate, Parser => Parser); if C = '*' then -- Full_Switch already includes the leading '-' Do_Callback (Switch => Full_Switch (Parser), Parameter => Parameter (Parser), Index => -1); elsif C /= ASCII.NUL then if Full_Switch (Parser) = "h" or else Full_Switch (Parser) = "-help" then Display_Help (Config); raise Exit_From_Command_Line; end if; -- Do switch expansion if needed For_Each_Simple (Config, Section => Section_Name.all, Switch => Parser.Switch_Character & Full_Switch (Parser), Parameter => Parameter (Parser)); else if Current_Section = -1 then Current_Section := Config.Sections'First; else Current_Section := Current_Section + 1; end if; exit when Current_Section > Config.Sections'Last; Section_Name := Config.Sections (Current_Section); Goto_Section (Section_Name.all, Parser); Free (Getopt_Switches); Getopt_Switches := new String' (Get_Switches (Config, Parser.Switch_Character, Section_Name.all)); end if; end loop; Free (Getopt_Switches); exception when Invalid_Switch => Free (Getopt_Switches); -- Message inspired by "ls" on Unix Put_Line (Standard_Error, Base_Name (Ada.Command_Line.Command_Name) & ": unrecognized option '" & Full_Switch (Parser) & "'"); Try_Help; raise; when others => Free (Getopt_Switches); raise; end Getopt; ----------- -- Build -- ----------- procedure Build (Line : in out Command_Line; Args : out GNAT.OS_Lib.Argument_List_Access; Expanded : Boolean := False; Switch_Char : Character := '-') is Iter : Command_Line_Iterator; Count : Natural := 0; begin Start (Line, Iter, Expanded => Expanded); while Has_More (Iter) loop if Is_New_Section (Iter) then Count := Count + 1; end if; Count := Count + 1; Next (Iter); end loop; Args := new Argument_List (1 .. Count); Count := Args'First; Start (Line, Iter, Expanded => Expanded); while Has_More (Iter) loop if Is_New_Section (Iter) then Args (Count) := new String'(Switch_Char & Current_Section (Iter)); Count := Count + 1; end if; Args (Count) := new String'(Current_Switch (Iter) & Current_Separator (Iter) & Current_Parameter (Iter)); Count := Count + 1; Next (Iter); end loop; end Build; -------------- -- Try_Help -- -------------- -- Note: Any change to the message displayed should also be done in -- gnatbind.adb that does not use this interface. procedure Try_Help is begin Put_Line (Standard_Error, "try """ & Base_Name (Ada.Command_Line.Command_Name) & " --help"" for more information."); end Try_Help; end GNAT.Command_Line;
pragma License (Unrestricted); -- extended unit with Ada.Directories.Volumes; function Ada.Directories.Equal_File_Names ( FS : Volumes.File_System; Left, Right : String) return Boolean; -- This function compare two file names by the method of the file system. -- For example, it uses NFD and case-insensitive on HFS+. pragma Inline (Ada.Directories.Equal_File_Names);
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Localization, Internationalization, Globalization for Ada -- -- -- -- Testsuite Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2010-2013, Vadim Godunko <vgodunko@gmail.com> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ -- This test incorporates tests for known problems of Universal_String -- manipulation subprograms. ------------------------------------------------------------------------------ with League.Application; with League.String_Vectors; with League.Strings; procedure String_Operations_Test is use League.String_Vectors; use League.Strings; procedure Test_TN_219; procedure Test_TN_319; -------------- -- Test_219 -- -------------- procedure Test_TN_219 is -- Initial implementation of prepend character operation crash with -- internal exception when source string is empty. S : Universal_String; E : Universal_String := To_Universal_String (" "); begin S.Prepend (' '); if S /= E then raise Program_Error; end if; end Test_TN_219; ----------------- -- Test_TN_319 -- ----------------- procedure Test_TN_319 is S : constant Universal_String := To_Universal_String ("file:///test_226_0.xmi#test"); begin if S.Index ('#') /= 23 then raise Program_Error; end if; end Test_TN_319; begin -- Initial implementation of concatenation of character with empty string -- raises exception and incorrectly compute size of the internal data -- representation. declare S : Universal_String; E : Universal_String := To_Universal_String ("A"); begin S := 'A' & S; if S /= E then raise Program_Error; end if; end; -- Initial implementation of concatenation of character with empty string -- raises exception and incorrectly compute size of the internal data -- representation. declare S : Universal_String; E : Universal_String := To_Universal_String ("A"); begin S := S & 'A'; if S /= E then raise Program_Error; end if; end; -- Initial implementation of slice replace operation uses incorrect length -- to allocate new shared string. declare S : Universal_String := To_Universal_String ("A0Z"); R : Universal_String := To_Universal_String ("abcdefghigklmnopqrstuvwxyz"); E : Universal_String := To_Universal_String ("AabcdefghigklmnopqrstuvwxyzZ"); begin S.Replace (2, 2, R); if S /= E then raise Program_Error; end if; end; -- Initial implementation of slice replace operation unable to insert -- string into the first position. declare S : Universal_String := To_Universal_String ("Z"); R : Universal_String := To_Universal_String ("abcdefghigklmnopqrstuvwxyz"); E : Universal_String := To_Universal_String ("abcdefghigklmnopqrstuvwxyzZ"); begin S.Replace (1, 0, R); if S /= E then raise Program_Error; end if; end; -- Initial implementation of replace operation computed indices incorrectly -- when string has mixed one/two code unit character. declare S : Universal_String := To_Universal_String ("_20- _D7FF-퟿_6c0f-氏_E000-" & Wide_Wide_Character'Val (16#E000#) & "_FFFD-�_effe-" & Wide_Wide_Character'Val (16#EFFE#) & "_010000-𐀀_10FFFF-" & Wide_Wide_Character'Val (16#10FFFD#) & "_08ffff-" & Wide_Wide_Character'Val (16#8FFFD#) & " This is a PI target "); R : Universal_String := To_Universal_String ("&#x20;"); E : Universal_String := To_Universal_String ("_20- _D7FF-퟿_6c0f-氏_E000-" & Wide_Wide_Character'Val (16#E000#) & "_FFFD-�_effe-" & Wide_Wide_Character'Val (16#EFFE#) & "_010000-𐀀_10FFFF-" & Wide_Wide_Character'Val (16#10FFFD#) & "_08ffff-" & Wide_Wide_Character'Val (16#8FFFD#) & " This is a PI target&#x20;"); begin S.Replace (S.Length, S.Length, R); if S /= E then raise Program_Error; end if; end; -- Initial implementation of Split operation doesn't create last element -- when it is empty. declare S : Universal_String := To_Universal_String ("a,,c,"); V : Universal_String_Vector := S.Split (','); begin if V.Element (1) /= To_Universal_String ("a") then raise Program_Error; end if; if V.Element (2) /= Empty_Universal_String then raise Program_Error; end if; if V.Element (3) /= To_Universal_String ("c") then raise Program_Error; end if; if V.Element (4) /= Empty_Universal_String then raise Program_Error; end if; end; Test_TN_219; Test_TN_319; end String_Operations_Test;
-- This file is generated by SWIG. Please do *not* modify by hand. -- with swig; with interfaces.C; package speech_tools_c is -- EST_Wave -- subtype EST_Wave is swig.incomplete_class; type EST_Wave_array is array (interfaces.C.Size_t range <>) of aliased speech_tools_c.EST_Wave; -- EST_String -- subtype EST_String is swig.incomplete_class; type EST_String_array is array (interfaces.C.Size_t range <>) of aliased speech_tools_c.EST_String; -- EST_Item_featfunc -- subtype EST_Item_featfunc is swig.incomplete_class; type EST_Item_featfunc_array is array (interfaces.C.Size_t range <>) of aliased speech_tools_c.EST_Item_featfunc; -- EST_Item -- subtype EST_Item is swig.incomplete_class; type EST_Item_array is array (interfaces.C.Size_t range <>) of aliased speech_tools_c.EST_Item; -- EST_Val -- subtype EST_Val is swig.incomplete_class; type EST_Val_array is array (interfaces.C.Size_t range <>) of aliased speech_tools_c.EST_Val; -- LISP -- subtype LISP is swig.incomplete_class; type LISP_array is array (interfaces.C.Size_t range <>) of aliased speech_tools_c.LISP; -- EST_Ngrammar -- subtype EST_Ngrammar is swig.incomplete_class; type EST_Ngrammar_array is array (interfaces.C.Size_t range <>) of aliased speech_tools_c.EST_Ngrammar; -- EST_WFST -- subtype EST_WFST is swig.incomplete_class; type EST_WFST_array is array (interfaces.C.Size_t range <>) of aliased speech_tools_c.EST_WFST; -- EST_Utterance -- subtype EST_Utterance is swig.incomplete_class; type EST_Utterance_array is array (interfaces.C.Size_t range <>) of aliased speech_tools_c.EST_Utterance; -- UnitDatabase -- subtype UnitDatabase is swig.incomplete_class; type UnitDatabase_array is array (interfaces.C.Size_t range <>) of aliased speech_tools_c.UnitDatabase; end speech_tools_c;
-- SPDX-FileCopyrightText: 2020 Max Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT ---------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with League.JSON.Objects; with League.Strings; with Jupyter.Kernels; package Hello_World is type Kernel is limited new Jupyter.Kernels.Kernel with private; private type Session is limited new Jupyter.Kernels.Session with null record; overriding procedure Execute (Self : aliased in out Session; IO_Pub : not null Jupyter.Kernels.IO_Pub_Access; Execution_Counter : Positive; Code : League.Strings.Universal_String; Silent : Boolean; User_Expressions : League.JSON.Objects.JSON_Object; Allow_Stdin : Boolean; Stop_On_Error : Boolean; Expression_Values : out League.JSON.Objects.JSON_Object; Error : in out Jupyter.Kernels.Execution_Error); type Session_Access is access all Session; function Hash (Value : Positive) return Ada.Containers.Hash_Type is (Ada.Containers.Hash_Type'Mod (Value)); package Session_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Positive, Element_Type => Session_Access, Hash => Hash, Equivalent_Keys => "="); type Kernel is limited new Jupyter.Kernels.Kernel with record Map : Session_Maps.Map; Last_Id : Natural := 0; end record; overriding procedure Kernel_Info (Self : aliased in out Kernel; Result : out League.JSON.Objects.JSON_Object); overriding procedure Create_Session (Self : aliased in out Kernel; Session_Id : Positive; Result : out Jupyter.Kernels.Session_Access); overriding function Get_Session (Self : aliased in out Kernel; Session_Id : Positive) return Jupyter.Kernels.Session_Access; end Hello_World;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2018 onox <denkpadje@gmail.com> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Orka.Windows; package Orka.Contexts is pragma Preelaborate; type Context_Version is record Major, Minor : Natural; end record with Dynamic_Predicate => Context_Version.Major >= 4 or else (Context_Version.Major = 3 and Context_Version.Minor >= 2); type Context_Flags is record Debug : Boolean := False; Robust : Boolean := False; No_Error : Boolean := False; end record with Dynamic_Predicate => (if Context_Flags.No_Error then not (Context_Flags.Debug or Context_Flags.Robust)); function Image (Version : Context_Version) return String; function Image (Flags : Context_Flags) return String; type Context is limited interface; function Create_Context (Version : Context_Version; Flags : Context_Flags := (others => False)) return Context is abstract; function Version (Object : Context) return Context_Version is abstract; function Flags (Object : Context) return Context_Flags is abstract; type Task_Kind is (Current_Task, Any_Task); function Is_Current (Object : Context; Kind : Task_Kind) return Boolean is abstract; procedure Make_Current (Object : Context) is abstract with Pre'Class => not Object.Is_Current (Any_Task), Post'Class => Object.Is_Current (Current_Task); procedure Make_Not_Current (Object : Context) is abstract with Pre'Class => Object.Is_Current (Current_Task), Post'Class => not Object.Is_Current (Any_Task); ----------------------------------------------------------------------------- type Feature is (Reversed_Z, Multisample, Sample_Shading); procedure Enable (Object : in out Context; Subject : Feature) is abstract; -- Note: If enabling Reversed_Z, the depth must be cleared with the -- value 0.0 function Enabled (Object : Context; Subject : Feature) return Boolean is abstract; ----------------------------------------------------------------------------- -- Helper utilities -- ----------------------------------------------------------------------------- type Feature_Array is array (Feature) of Boolean; procedure Enable (Features : in out Feature_Array; Subject : Feature); function Enabled (Features : Feature_Array; Subject : Feature) return Boolean; ----------------------------------------------------------------------------- -- Contexts with a surface -- ----------------------------------------------------------------------------- type Surface_Context is limited interface and Context; procedure Make_Current (Object : Surface_Context; Window : in out Orka.Windows.Window'Class) is abstract with Pre'Class => Object.Is_Current (Current_Task) or not Object.Is_Current (Any_Task), Post'Class => Object.Is_Current (Current_Task); end Orka.Contexts;
with Ada.Unchecked_Deallocation, Ada.Strings.Fixed; package body ARM_Syntax is -- -- Ada reference manual formatter (ARM_Form). -- -- This package contains the database to collect the syntax summary and -- cross-reference. -- -- --------------------------------------- -- Copyright 2000, 2004, 2006, 2011 -- AXE Consultants. All rights reserved. -- P.O. Box 1512, Madison WI 53701 -- E-Mail: randy@rrsoftware.com -- -- ARM_Form is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License version 3 -- as published by the Free Software Foundation. -- -- AXE CONSULTANTS MAKES THIS TOOL AND SOURCE CODE AVAILABLE ON AN "AS IS" -- BASIS AND MAKES NO WARRANTY, EXPRESS OR IMPLIED, AS TO THE ACCURACY, -- CAPABILITY, EFFICIENCY, MERCHANTABILITY, OR FUNCTIONING OF THIS TOOL. -- IN NO EVENT WILL AXE CONSULTANTS BE LIABLE FOR ANY GENERAL, -- CONSEQUENTIAL, INDIRECT, INCIDENTAL, EXEMPLARY, OR SPECIAL DAMAGES, -- EVEN IF AXE CONSULTANTS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -- DAMAGES. -- -- A copy of the GNU General Public License is available in the file -- gpl-3-0.txt in the standard distribution of the ARM_Form tool. -- Otherwise, see <http://www.gnu.org/licenses/>. -- -- If the GPLv3 license is not satisfactory for your needs, a commercial -- use license is available for this tool. Contact Randy at AXE Consultants -- for more information. -- -- --------------------------------------- -- -- Edit History: -- -- 5/17/00 - RLB - Created package. -- 5/24/00 - RLB - Updated to use revised Tabset. -- 5/26/00 - RLB - Added a Tabset parameter. -- 8/ 4/00 - RLB - Changed style to make font smaller (per Duff). -- 8/16/00 - RLB - Added NoParaNum; removed junk space (which caused -- blank lines and paragraph numbers). -- 9/26/00 - RLB - Revised to use SyntaxDisplay format to get more -- control over the formating of this section. -- 9/27/00 - RLB - Revised XRef to decrease white space. -- 9/28/00 - RLB - Added code to make links in HTML version. -- 9/09/04 - RLB - Removed unused junk noted by Stephen Leake. -- 6/22/06 - RLB - Added additional information to improve the links. -- Changed the cross-reference table to use the Ada 83 -- format (which adds missing section references). -- 10/13/06 - RLB - Added Defined flag to cross-references to eliminate -- junk errors from not-quite-non-terminals. -- 10/18/11 - RLB - Changed to GPLv3 license. type String_Ptr is access String; type Rule_Type; type Rule_Ptr is access Rule_Type; type Rule_Type is record Clause : String (1..10); Clause_Len : Natural; Rule : String_Ptr; Tabset : String (1..40); Next : Rule_Ptr; end record; Rule_List : Rule_Ptr := null; Rule_List_Tail : Rule_Ptr := null; type XRef_Type; type XRef_Ptr is access XRef_Type; type XRef_Type is record Clause : String (1..10); Clause_Len : Natural; Name : String (1..40); Name_Len : Natural; Used_In : String (1..40); Used_In_Len : Natural; Defined : Boolean; Next : XRef_Ptr; end record; XRef_List : XRef_Ptr := null; XRef_Count : Natural := 0; type NT_Type; type NT_Ptr is access NT_Type; type NT_Type is record Name : String (1..40); Name_Len : Natural; Clause : String (1..10); Clause_Len : Natural; Link_Target : Target_Type; Next : NT_Ptr; end record; NT_List : NT_Ptr := null; NT_Count : Natural := 0; procedure Free is new Ada.Unchecked_Deallocation (Rule_Type, Rule_Ptr); -- procedure Free is new Ada.Unchecked_Deallocation (XRef_Type, XRef_Ptr); not referenced -- procedure Free is new Ada.Unchecked_Deallocation (NT_Type, NT_Ptr); procedure Free is new Ada.Unchecked_Deallocation (String, String_Ptr); procedure Create is -- Initialize the syntax database. begin Rule_List := null; Rule_List_Tail := null; end Create; procedure Destroy is -- Destroy the syntax database. RTemp : Rule_Ptr; begin while Rule_List /= null loop RTemp := Rule_List; Rule_List := RTemp.Next; Free (RTemp.Rule); Free (RTemp); end loop; end Destroy; procedure Insert_Rule ( For_Clause : in String; Rule : in String; Tabset : in String := "") is -- Add a rule for the syntax summary. The rule appears in For_Clause. -- Tabset provides any needed tab settings. Temp_Rule : Rule_Type; begin Ada.Strings.Fixed.Move (Target => Temp_Rule.Clause, Source => For_Clause, Drop => Ada.Strings.Error, Pad => ' '); Temp_Rule.Clause_Len := For_Clause'Length; Temp_Rule.Rule := new String'(Rule); Ada.Strings.Fixed.Move (Target => Temp_Rule.Tabset, Source => Tabset, Drop => Ada.Strings.Error, Pad => ' '); Temp_Rule.Next := null; if Rule_List_Tail = null then Rule_List := new Rule_Type'(Temp_Rule); Rule_List_Tail := Rule_List; else Rule_List_Tail.Next := new Rule_Type'(Temp_Rule); Rule_List_Tail := Rule_List_Tail.Next; end if; end Insert_Rule; procedure Add_Non_Terminal ( NT_Name : in String; For_Clause : in String; Link_Target : out ARM_Syntax.Target_Type) is -- Add a non-terminal to the syntax list. Returns a new Link_Target -- for the Non-Terminal. Temp_NT : NT_Type; begin Ada.Strings.Fixed.Move (Target => Temp_NT.Clause, Source => For_Clause, Drop => Ada.Strings.Error, Pad => ' '); Temp_NT.Clause_Len := For_Clause'Length; Ada.Strings.Fixed.Move (Target => Temp_NT.Name, Source => NT_Name, Drop => Ada.Strings.Error, Pad => ' '); Temp_NT.Name_Len := NT_Name'Length; declare Val : constant String := Natural'Image(NT_Count); begin Temp_NT.Link_Target := "S0000"; if Val'Length <= 5 then Temp_NT.Link_Target (5-(Val'Length-2)..5) := Val(2..Val'Last); else raise Program_Error; -- Too many. end if; Link_Target := Temp_NT.Link_Target; end; if NT_List = null then Temp_NT.Next := null; NT_List := new NT_Type'(Temp_NT); else Temp_NT.Next := NT_List; NT_List := new NT_Type'(Temp_NT); end if; NT_Count := NT_Count + 1; end Add_Non_Terminal; function Non_Terminal_Clause (NT_Name : in String) return String is -- Return the clause where NT_Name is declared. -- Returns "" if NT_Name is not a declared Non_Terminal. Loc : NT_Ptr; begin Loc := NT_List; while Loc /= null loop if NT_Name = Loc.Name(1..Loc.Name_Len) then return Loc.Clause(1..Loc.Clause_Len); end if; Loc := Loc.Next; end loop; return ""; -- Not found. end Non_Terminal_Clause; function Non_Terminal_Link_Target (NT_Name : in String) return Target_Type is -- Return the link target for NT_Name. -- Returns " " if NT_Name is not a declared Non_Terminal. Loc : NT_Ptr; begin Loc := NT_List; while Loc /= null loop if NT_Name = Loc.Name(1..Loc.Name_Len) then return Loc.Link_Target; end if; Loc := Loc.Next; end loop; return Target_Type'(others => ' '); -- Not found. end Non_Terminal_Link_Target; procedure Add_Xref ( Name : in String; Used_In : in String; Clause : in String; Defined : in Boolean) is -- Add a cross-reference entry. -- The item referenced is Name, and it is referenced in the production -- for Used_In, in Clause. It is a defined non-terminal if Defined -- is True (thus it can be linked). Temp_XRef : XRef_Type; begin Ada.Strings.Fixed.Move (Target => Temp_XRef.Clause, Source => Clause, Drop => Ada.Strings.Error, Pad => ' '); Temp_XRef.Clause_Len := Clause'Length; Ada.Strings.Fixed.Move (Target => Temp_XRef.Name, Source => Name, Drop => Ada.Strings.Error, Pad => ' '); Temp_XRef.Name_Len := Name'Length; Ada.Strings.Fixed.Move (Target => Temp_XRef.Used_In, Source => Used_In, Drop => Ada.Strings.Error, Pad => ' '); Temp_XRef.Used_In_Len := Used_In'Length; Temp_XRef.Defined := Defined; -- Check for an identical record already loaded: declare Temp : XRef_Ptr := XRef_List; begin -- We assume that all of the items from the current clause -- are together at the top of the list. If the list is inserted -- in reverse order (the default), that will be true. while Temp /= null and then (Temp.Clause_Len = Temp_XRef.Clause_Len) and then (Temp.Clause = Temp_XRef.Clause) loop if (Temp.Name_Len = Temp_XRef.Name_Len) and then (Temp.Used_In_Len = Temp_XRef.Used_In_Len) and then (Temp.Name = Temp_XRef.Name) and then (Temp.Used_In = Temp_XRef.Used_In) then -- Identical to an existing item, forget it. -- (We do this to eliminate multiple items from one production. return; end if; Temp := Temp.Next; end loop; end; if XRef_List = null then Temp_XRef.Next := null; XRef_List := new XRef_Type'(Temp_XRef); else Temp_XRef.Next := XRef_List; XRef_List := new XRef_Type'(Temp_XRef); end if; XRef_Count := XRef_Count + 1; end Add_Xref; --generic -- with procedure Format_Text (Text : in String; -- Text_Name : in String); procedure Report is -- Output the fully formatted syntax summary to the -- "Format_Text" routine. "Format_Text" allows all commands -- for the full formatter. (Text_Name is an identifying name -- for error messages). Temp : Rule_Ptr; begin Format_Text ("@begin(syntaxdisplay)" & Ascii.LF, "Prefix"); Temp := Rule_List; while Temp /= null loop if Ada.Strings.Fixed.Trim (Temp.Tabset, Ada.Strings.Right) = "" then Format_Text ("@noparanum@RefSecbyNum{" & Temp.Clause(1..Temp.Clause_Len) & "}:" & Ascii.LF & Temp.Rule.all & Ascii.LF & Ascii.LF, Temp.Clause(1..Temp.Clause_Len)); else Format_Text ("@noparanum@tabclear{}@tabset{" & Ada.Strings.Fixed.Trim (Temp.Tabset, Ada.Strings.Right) & "}@RefSecbyNum{" & Temp.Clause(1..Temp.Clause_Len) & "}:" & Ascii.LF & Temp.Rule.all & Ascii.LF & Ascii.LF, Temp.Clause(1..Temp.Clause_Len)); end if; Temp := Temp.Next; end loop; Format_Text ("@end(syntaxdisplay)" & Ascii.LF, "Suffix"); end Report; --generic -- with procedure Format_Text (Text : in String; -- Text_Name : in String); procedure XRef is -- Output the fully formatted syntax cross-reference to the -- "Format_Text" routine. "Format_Text" allows all commands -- for the full formatter. (Text_Name is an identifying name -- for error messages). Temp : XRef_Ptr; Last : XRef_Ptr := null; Items : array (1..XRef_Count) of XRef_Ptr; begin -- Sort the items: -- Load the items: Temp := XRef_List; for I in Items'range loop Items(I) := Temp; Temp := Temp.Next; end loop; -- Sort the items array (use an insertion sort): declare Left : Natural; -- Left sorting stop function "<" (Left, Right : XRef_Ptr) return Boolean is begin -- We sort first on "Name", then on "Used_In". if Left.Name (1..Left.Name_Len) < Right.Name (1..Right.Name_Len) then return True; elsif Left.Name (1..Left.Name_Len) > Right.Name (1..Right.Name_Len) then return False; else return Left.Used_In (1..Left.Used_In_Len) < Right.Used_In (1..Right.Used_In_Len); end if; end "<"; begin for Right In Items'First+1 .. Items'Last loop -- Right sorting stop Temp := Items(Right); Left := Right - 1; while Temp < Items(Left) loop -- Switch items Items(Left + 1) := Items(Left); Left := Left - 1; exit when Left = 0; end loop; Items(Left + 1) := Temp; end loop; end; -- Relink the items in the sorted order: for I in Items'First .. Items'Last - 1 loop Items(I).Next := Items(I+1); end loop; if Items'Length > 0 then Items(Items'Last).Next := null; XRef_List := Items(1); else XRef_List := null; end if; Format_Text ("@begin(syntaxdisplay)" & Ascii.LF, "Prefix"); Format_Text ("@tabclear()@tabset(P4, P38)" & Ascii.LF, "Prefix"); Format_Text ("@begin(twocol)" & Ascii.LF, "Prefix"); Temp := XRef_List; while Temp /= null loop if Last = null or else Last.Name (1..Last.Name_Len) /= Temp.Name (1..Temp.Name_Len) then -- New header: declare Clause : constant String := Non_Terminal_Clause (Temp.Name (1..Temp.Name_Len)); begin if Temp.Defined then if Clause /= "" then Format_Text ("@noparanum@trailing@nt{" & Temp.Name (1..Temp.Name_Len) & "}@\@RefSecbyNum{" & Clause & "}" & Ascii.LF, Temp.Name (1..Temp.Name_Len) & " header"); else -- Undefined? Weird, but don't break, just use the -- Ada 83 ellipsis. Format_Text ("@noparanum@trailing@nt{" & Temp.Name (1..Temp.Name_Len) & "}@\..." & Ascii.LF, Temp.Name (1..Temp.Name_Len) & " header"); end if; else if Clause /= "" then Format_Text ("@noparanum@trailing@ntf{" & Temp.Name (1..Temp.Name_Len) & "}@\@RefSecbyNum{" & Clause & "}" & Ascii.LF, Temp.Name (1..Temp.Name_Len) & " header"); else -- Undefined? Weird, but don't break, just use the -- Ada 83 ellipsis. Format_Text ("@noparanum@trailing@ntf{" & Temp.Name (1..Temp.Name_Len) & "}@\..." & Ascii.LF, Temp.Name (1..Temp.Name_Len) & " header"); end if; end if; end; -- Original: --Format_Text ("@noparanum@trailing@nt{" & Temp.Name (1..Temp.Name_Len) & -- "}" & Ascii.LF, -- Temp.Name (1..Temp.Name_Len) & " header"); Last := Temp; end if; if Temp.Next = null or else Temp.Name (1..Temp.Name_Len) /= Temp.Next.Name (1..Temp.Next.Name_Len) then -- Last item of a set. Format_Text ("@\@nt{" & Temp.Used_In(1..Temp.Used_In_Len) & "}@\" & "@RefSecbyNum{" & Temp.Clause(1..Temp.Clause_Len) & '}' & Ascii.LF & Ascii.LF, Temp.Name (1..Temp.Name_Len) & " ref " & Temp.Clause(1..Temp.Clause_Len)); else -- Not an end item. Format_Text ("@\@nt{" & Temp.Used_In(1..Temp.Used_In_Len) & "}@\" & "@RefSecbyNum{" & Temp.Clause(1..Temp.Clause_Len) & '}' & Ascii.LF, Temp.Name (1..Temp.Name_Len) & " ref " & Temp.Clause(1..Temp.Clause_Len)); end if; Temp := Temp.Next; end loop; Format_Text ("@end(twocol)" & Ascii.LF, "Suffix"); Format_Text ("@end(syntaxdisplay)" & Ascii.LF, "Suffix"); -- Should free the XRef list here, but we won't do anything -- afterwards, so doing so doesn't matter. end XRef; end ARM_Syntax;
-- Copyright 2021 Jeff Foley. All rights reserved. -- Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file. local json = require("json") name = "CommonCrawl" type = "api" local urls = {} function start() setratelimit(2) end function vertical(ctx, domain) -- Check that the index URLs have been obtained if (urls == nil or #urls == 0) then urls = indexurls(ctx) if (urls == nil or #urls == 0) then return end checkratelimit() end for i, url in pairs(urls) do scrape(ctx, { ['url']=buildurl(url, domain), headers={['Content-Type']="application/json"}, }) checkratelimit() end end function buildurl(url, domain) return url .. "?url=*." .. domain .. "&output=json&fl=url" end function indexurls(ctx) local resp local cfg = datasrc_config() local iurl = "https://index.commoncrawl.org/collinfo.json" -- Check if the response data is in the graph database if (cfg.ttl ~= nil and cfg.ttl > 0) then resp = obtain_response(iurl, cfg.ttl) end if (resp == nil or resp == "") then local err resp, err = request(ctx, { url=iurl, headers={['Content-Type']="application/json"}, }) if (err ~= nil and err ~= "") then log(ctx, err .. ": " .. resp) return nil end if (cfg.ttl ~= nil and cfg.ttl > 0) then cache_response(iurl, resp) end end local data = json.decode(resp) if (data == nil or #data == 0) then return nil end local urls = {} for i, u in pairs(data) do local url = u["cdx-api"] if (url ~= nil and url ~= "") then table.insert(urls, url) end end return urls end
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2020 onox <denkpadje@gmail.com> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Numerics.Generic_Elementary_Functions; with GL.Types; with Orka.Transforms.Singles.Matrices; package body Orka.Features.Terrain.Spheres is function Plane_To_Sphere (Vertex : Orka.Transforms.Singles.Vectors.Vector4; Parameters : Orka.Features.Terrain.Spheroid_Parameters) return Orka.Transforms.Singles.Vectors.Vector4 is package EF is new Ada.Numerics.Generic_Elementary_Functions (GL.Types.Single); use Orka.Transforms.Singles.Vectors; Axis : GL.Types.Single renames Parameters (1); E2 : GL.Types.Single renames Parameters (2); Y_Mask : GL.Types.Single renames Parameters (3); Z_Mask : GL.Types.Single renames Parameters (4); Unit : Vector4 := Vertex * (2.0, 2.0, 1.0, 1.0) - (1.0, 1.0, 0.0, 0.0); -- Centers the plane begin -- World matrix assumes ECEF, meaning: -- -- z -- | -- o--y -- / -- x -- -- So the 3rd element (1.0) must be moved to the 'x' position, -- and the first two elements (H and V) must be moved to 'y' and 'z'. Unit := Normalize ((Unit (Z), Unit (X), Unit (Y), 0.0)); Unit (W) := 1.0; declare Height : constant GL.Types.Single := Length ((Unit (Y), Unit (Z), 0.0, 0.0) * (Y_Mask, Z_Mask, 0.0, 0.0)); N : constant GL.Types.Single := Axis / EF.Sqrt (1.0 - E2 * Height * Height); Scale : Vector4 := ((1.0, 1.0, 1.0, 1.0) - E2 * (0.0, Y_Mask, Z_Mask, 0.0)) * N; begin Scale (W) := 1.0; return Scale * Unit; end; end Plane_To_Sphere; function Get_Sphere_Visibilities (Parameters : Spheroid_Parameters; Front, Back, World, View : Orka.Types.Singles.Matrix4) return GL.Types.Single_Array is use Orka.Transforms.Singles.Matrices; World_View : constant Orka.Types.Singles.Matrix4 := View * World; Vertices : constant array (GL.Types.Size range 0 .. 3) of Orka.Types.Singles.Vector4 := (Plane_To_Sphere ((0.0, 0.0, 1.0, 1.0), Parameters), Plane_To_Sphere ((1.0, 0.0, 1.0, 1.0), Parameters), Plane_To_Sphere ((0.0, 1.0, 1.0, 1.0), Parameters), Plane_To_Sphere ((1.0, 1.0, 1.0, 1.0), Parameters)); Faces : constant array (GL.Types.Size range 0 .. 1) of Orka.Types.Singles.Matrix4 := (Front, Back); Result : GL.Types.Single_Array (0 .. 7); use Orka.Transforms.Singles.Vectors; use all type GL.Types.Int; begin for Index in Result'Range loop declare V : Orka.Types.Singles.Vector4 renames Vertices (Index mod 4); F : Orka.Types.Singles.Matrix4 renames Faces (Index / 4); -- Vector pointing to vertex from camera or sphere V_From_C : constant Orka.Types.Singles.Vector4 := World_View * (F * V); V_From_S : constant Orka.Types.Singles.Vector4 := View * (F * V); begin Result (Index) := Dot (Normalize (V_From_C), Normalize (V_From_S)); end; end loop; return Result; end Get_Sphere_Visibilities; ----------------------------------------------------------------------------- subtype Tile_Index is Positive range 1 .. 6; subtype Vertex_Index is GL.Types.Size range 0 .. 7; type Edge_Index is range 1 .. 12; type Edge_Index_Array is array (Positive range 1 .. 4) of Edge_Index; type Vertex_Index_Array is array (Positive range 1 .. 2) of Vertex_Index; type Tile_Index_Array is array (Positive range <>) of Tile_Index; type Tile_3_Array is array (Vertex_Index) of Tile_Index_Array (1 .. 3); type Tile_2_Array is array (Edge_Index) of Tile_Index_Array (1 .. 2); type Edges_Array is array (Tile_Index) of Edge_Index_Array; type Vertices_Array is array (Edge_Index) of Vertex_Index_Array; -- The three tiles that are visible when a particular -- vertex is visible Vertex_Buffer_Indices : constant Tile_3_Array := (0 => (1, 4, 6), 1 => (1, 2, 6), 2 => (1, 4, 5), 3 => (1, 2, 5), 4 => (2, 3, 6), 5 => (3, 4, 6), 6 => (2, 3, 5), 7 => (3, 4, 5)); -- The vertices that form each edge Edge_Vertex_Indices : constant Vertices_Array := (1 => (0, 2), 2 => (1, 3), 3 => (2, 3), 4 => (0, 1), 5 => (4, 6), 6 => (5, 7), 7 => (6, 7), 8 => (4, 5), 9 => (2, 7), 10 => (3, 6), 11 => (0, 5), 12 => (1, 4)); -- The two tiles to which each edge belongs Edge_Tiles_Indices : constant Tile_2_Array := (1 => (1, 4), 2 => (1, 2), 3 => (1, 5), 4 => (1, 6), 5 => (3, 2), 6 => (3, 4), 7 => (3, 5), 8 => (3, 6), 9 => (4, 5), 10 => (2, 5), 11 => (4, 6), 12 => (2, 6)); -- The four edges of each tile Tile_Edge_Indices : constant Edges_Array := (1 => (1, 2, 3, 4), 2 => (2, 5, 10, 12), 3 => (5, 6, 7, 8), 4 => (1, 6, 9, 11), 5 => (3, 7, 9, 10), 6 => (4, 8, 11, 12)); Threshold_A : constant := 0.55; Threshold_B : constant := 0.25; function Get_Visible_Tiles (Visibilities : GL.Types.Single_Array) return Visible_Tile_Array is Visible_Tile_Count : array (Tile_Index) of Natural := (others => 0); Vertex_Visible : Boolean := False; Result : Visible_Tile_Array := (Tile_Index => False); begin -- Heuristic 1: a tile is visible if it surrounds a vertex that is -- pointing towards the camera for Vertex in Vertex_Buffer_Indices'Range loop if Visibilities (Vertex) < 0.0 then for Tile of Vertex_Buffer_Indices (Vertex) loop Result (Tile) := True; end loop; Vertex_Visible := True; end if; end loop; -- If all vertices point away from the camera, the camera is usually -- close to some of the tiles if not Vertex_Visible then -- Heuristic 2: an edge is visible if the maximum vertex visibility -- is less than some threshold for Edge in Edge_Vertex_Indices'Range loop if (for all Vertex of Edge_Vertex_Indices (Edge) => Visibilities (Vertex) < Threshold_A) then for Tile of Edge_Tiles_Indices (Edge) loop Visible_Tile_Count (Tile) := Visible_Tile_Count (Tile) + 1; end loop; end if; end loop; declare Max_Count : Natural := 0; function Average_Visibility (Vertices : Vertex_Index_Array) return GL.Types.Single is Sum : GL.Types.Single := 0.0; begin for Vertex of Vertices loop Sum := Sum + Visibilities (Vertex); end loop; return Sum / GL.Types.Single (Vertices'Length); end Average_Visibility; begin for Tile in Visible_Tile_Count'Range loop Max_Count := Natural'Max (Max_Count, Visible_Tile_Count (Tile)); end loop; -- A tile is visible if it has the highest number (1, 2, or 4) -- of visible edges -- -- For example, tile 1 might have a count of 4, while its surrounding -- tiles (2, 4, 5, and 6) have a count of 1. In that case choose to -- display tile 1. for Tile in Visible_Tile_Count'Range loop if Visible_Tile_Count (Tile) = Max_Count then Result (Tile) := True; end if; end loop; -- Sometimes the camera might be positioned above a tile with count 4 -- and looking at some of its edges. In that case we should render the -- adjacent tiles as well if those tiles are 'likely' to be visible. if Max_Count in 2 | 4 then for Tile in Tile_Edge_Indices'Range loop if Result (Tile) then -- Heuristic 3: all tiles that surround an edge of a visible tile -- with an average vertex visibility less than some threshold -- are visible as well for Edge of Tile_Edge_Indices (Tile) loop if Average_Visibility (Edge_Vertex_Indices (Edge)) < Threshold_B then for Tile of Edge_Tiles_Indices (Edge) loop Result (Tile) := True; end loop; end if; end loop; end if; end loop; end if; end; end if; return Result; end Get_Visible_Tiles; end Orka.Features.Terrain.Spheres;
-- The Village of Vampire by YT, このソースコードはNYSLです with Ada.Numerics.MT19937; procedure Vampire.Villages.Advance ( Village : in out Village_Type; Now : in Ada.Calendar.Time; Generator : aliased in out Ada.Numerics.MT19937.Generator; Changed : out Boolean; List_Changed : out Boolean);
-- part of OpenGLAda, (c) 2017 Felix Krause -- released under the terms of the MIT license, see the file "COPYING" with GL.Low_Level.Enums; package GL.Objects.Queries is pragma Preelaborate; type Query_Object is new GL_Object with private; Default_Query : constant Query_Object; procedure Begin_Query (Target : GL.Low_Level.Enums.Query_Param; Object : Query_Object); procedure End_Query (Target : GL.Low_Level.Enums.Query_Param); procedure Begin_Query_Indexed (Target : GL.Low_Level.Enums.Query_Param; Index : UInt; Object : Query_Object); procedure End_Query_Indexed (Target : GL.Low_Level.Enums.Query_Param; Index : UInt); procedure Get_Query_Object (Object : Query_Object; Pname : GL.Low_Level.Enums.Query_Results; Params : out UInt); function Is_Query (Query : Query_Object) return Boolean; procedure Query_Counter (Object : Query_Object; Target : Low_Level.Enums.Query_Param); private type Query_Object is new GL_Object with null record; overriding procedure Internal_Create_Id (Object : Query_Object; Id : out UInt); overriding procedure Internal_Release_Id (Object : Query_Object; Id : UInt); Default_Query : constant Query_Object := Query_Object'( Ada.Finalization.Controlled with Reference => Reference_To_Null_Object'Access); end GL.Objects.Queries;
-------------------------------------------------------------------------------------------------------------------- -- 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. -------------------------------------------------------------------------------------------------------------------- -- Pixel_Format_Test_Cases -------------------------------------------------------------------------------------------------------------------- with Ada.Unchecked_Conversion; with Ada.Strings.Fixed; use Ada.Strings.Fixed; use Ada.Strings; with Interfaces.C; with SDL.Video.Pixel_Formats; use SDL.Video.Pixel_Formats; with AUnit.Assertions; use AUnit.Assertions; with Ada.Text_Io; -- use Ada.Text_Io; package body Pixel_Format_Test_Cases is overriding function Name (Test : Pixel_Format_Test_Case) return Message_String is begin return Format ("Pixel format test"); end Name; use type C.int; function To_int is new Ada.Unchecked_Conversion (Source => Pixel_Format_Names, Target => C.int); package int_IO is new Ada.Text_IO.Integer_Io (C.int); use int_IO; function To_Binary (Num : in C.int) return String is Result : String (1 .. 100); begin Put (Result, Num, 2); return Trim (Result, Left); end To_Binary; overriding procedure Run_Test (Test : in out Pixel_Format_Test_Case) is begin declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_Unknown)); C_Value : constant String := To_Binary (C_Unknown); Error : constant String := "Pixel_Format_Unknown (" & Ada_Value & ") /= C_Index_Unknown (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_Unknown) = C_Unknown, Error); end; declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_Index_1_LSB)); C_Value : constant String := To_Binary (C_Index_1_LSB); Error : constant String := "Pixel_Format_Index_1_LSB (" & Ada_Value & ") /= C_Index_1_LSB (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_Index_1_LSB) = C_Index_1_LSB, Error); end; declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_Index_1_MSB)); C_Value : constant String := To_Binary (C_Index_1_MSB); Error : constant String := "Pixel_Format_Index_1_MSB (" & Ada_Value & ") /= C_Index_1_MSB (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_Index_1_MSB) = C_Index_1_MSB, Error); end; declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_Index_4_LSB)); C_Value : constant String := To_Binary (C_Index_4_LSB); Error : constant String := "Pixel_Format_Index_4_LSB (" & Ada_Value & ") /= C_Index_4_LSB (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_Index_4_LSB) = C_Index_4_LSB, Error); end; -- Put (To => Ada_Value, Item => To_int (Pixel_Format_Index_4_MSB), Base => 16); -- Put (To => C_Value, Item => C_Index_4_MSB, Base => 16); declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_Index_4_MSB)); C_Value : constant String := To_Binary (C_Index_4_MSB); Error : constant String := "Pixel_Format_Index_4_MSB (" & Ada_Value & ") /= C_Index_4_MSB (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_Index_4_MSB) = C_Index_4_MSB, Error); end; declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_Index_8)); C_Value : constant String := To_Binary (C_Index_8); Error : constant String := "Pixel_Format_Index_8 (" & Ada_Value & ") /= C_Index_8 (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_Index_8) = C_Index_8, Error); end; declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_RGB_332)); C_Value : constant String := To_Binary (C_RGB_332); Error : constant String := "Pixel_Format_RGB_332 (" & Ada_Value & ") /= C_RGB_332 (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_RGB_332) = C_RGB_332, Error); end; declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_RGB_444)); C_Value : constant String := To_Binary (C_RGB_444); Error : constant String := "Pixel_Format_RGB_444 (" & Ada_Value & ") /= C_RGB_444 (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_RGB_444) = C_RGB_444, Error); end; declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_RGB_555)); C_Value : constant String := To_Binary (C_RGB_555); Error : constant String := "Pixel_Format_RGB_555 (" & Ada_Value & ") /= C_RGB_555 (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_RGB_555) = C_RGB_555, Error); end; declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_BGR_555)); C_Value : constant String := To_Binary (C_BGR_555); Error : constant String := "Pixel_Format_BGR_555 (" & Ada_Value & ") /= C_BGR_555 (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_BGR_555) = C_BGR_555, Error); end; declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_ARGB_4444)); C_Value : constant String := To_Binary (C_ARGB_4444); Error : constant String := "Pixel_Format_ARGB_4444 (" & Ada_Value & ") /= C_ARGB_4444 (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_ARGB_4444) = C_ARGB_4444, Error); end; declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_RGBA_4444)); C_Value : constant String := To_Binary (C_RGBA_4444); Error : constant String := "Pixel_Format_RGBA_4444 (" & Ada_Value & ") /= C_RGBA_4444 (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_RGBA_4444) = C_RGBA_4444, Error); end; declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_ABGR_4444)); C_Value : constant String := To_Binary (C_ABGR_4444); Error : constant String := "Pixel_Format_ABGR_4444 (" & Ada_Value & ") /= C_ABGR_4444 (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_ABGR_4444) = C_ABGR_4444, Error); end; declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_BGRA_4444)); C_Value : constant String := To_Binary (C_BGRA_4444); Error : constant String := "Pixel_Format_BGRA_4444 (" & Ada_Value & ") /= C_BGRA_4444 (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_BGRA_4444) = C_BGRA_4444, Error); end; declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_ARGB_1555)); C_Value : constant String := To_Binary (C_ARGB_1555); Error : constant String := "Pixel_Format_ARGB_1555 (" & Ada_Value & ") /= C_ARGB_1555 (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_ARGB_1555) = C_ARGB_1555, Error); end; declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_RGBA_5551)); C_Value : constant String := To_Binary (C_RGBA_5551); Error : constant String := "Pixel_Format_RGBA_5551 (" & Ada_Value & ") /= C_RGBA_5551 (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_RGBA_5551) = C_RGBA_5551, Error); end; declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_ABGR_1555)); C_Value : constant String := To_Binary (C_ABGR_1555); Error : constant String := "Pixel_Format_ABGR_1555 (" & Ada_Value & ") /= C_ABGR_1555 (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_ABGR_1555) = C_ABGR_1555, Error); end; declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_BGRA_5551)); C_Value : constant String := To_Binary (C_BGRA_5551); Error : constant String := "Pixel_Format_BGRA_5551 (" & Ada_Value & ") /= C_BGRA_5551 (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_BGRA_5551) = C_BGRA_5551, Error); end; declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_RGB_565)); C_Value : constant String := To_Binary (C_RGB_565); Error : constant String := "Pixel_Format_RGB_565 (" & Ada_Value & ") /= C_RGB_565 (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_RGB_565) = C_RGB_565, Error); end; declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_BGR_565)); C_Value : constant String := To_Binary (C_BGR_565); Error : constant String := "Pixel_Format_BGR_565 (" & Ada_Value & ") /= C_BGR_565 (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_BGR_565) = C_BGR_565, Error); end; declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_RGB_24)); C_Value : constant String := To_Binary (C_RGB_24); Error : constant String := "Pixel_Format_RGB_24 (" & Ada_Value & ") /= C_RGB_24 (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_RGB_24) = C_RGB_24, Error); end; declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_BGR_24)); C_Value : constant String := To_Binary (C_BGR_24); Error : constant String := "Pixel_Format_BGR_24 (" & Ada_Value & ") /= C_BGR_24 (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_BGR_24) = C_BGR_24, Error); end; declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_RGB_888)); C_Value : constant String := To_Binary (C_RGB_888); Error : constant String := "Pixel_Format_RGB_888 (" & Ada_Value & ") /= C_RGB_888 (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_RGB_888) = C_RGB_888, Error); end; declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_RGBX_8888)); C_Value : constant String := To_Binary (C_RGBX_8888); Error : constant String := "Pixel_Format_RGBX_8888 (" & Ada_Value & ") /= C_RGBX_8888 (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_RGBX_8888) = C_RGBX_8888, Error); end; declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_BGR_888)); C_Value : constant String := To_Binary (C_BGR_888); Error : constant String := "Pixel_Format_BGR_888 (" & Ada_Value & ") /= C_BGR_888 (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_BGR_888) = C_BGR_888, Error); end; declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_BGRX_8888)); C_Value : constant String := To_Binary (C_BGRX_8888); Error : constant String := "Pixel_Format_BGRX_8888 (" & Ada_Value & ") /= C_BGRX_8888 (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_BGRX_8888) = C_BGRX_8888, Error); end; declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_ARGB_8888)); C_Value : constant String := To_Binary (C_ARGB_8888); Error : constant String := "Pixel_Format_ARGB_8888 (" & Ada_Value & ") /= C_ARGB_8888 (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_ARGB_8888) /= C_ARGB_8888, Error); end; declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_RGBA_8888)); C_Value : constant String := To_Binary (C_RGBA_8888); Error : constant String := "Pixel_Format_RGBA_8888 (" & Ada_Value & ") /= C_RGBA_8888 (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_RGBA_8888) = C_RGBA_8888, Error); end; declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_ABGR_8888)); C_Value : constant String := To_Binary (C_ABGR_8888); Error : constant String := "Pixel_Format_ABGR_8888 (" & Ada_Value & ") /= C_ABGR_8888 (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_ABGR_8888) = C_ABGR_8888, Error); end; declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_BGRA_8888)); C_Value : constant String := To_Binary (C_BGRA_8888); Error : constant String := "Pixel_Format_BGRA_8888 (" & Ada_Value & ") /= C_BGRA_8888 (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_BGRA_8888) = C_BGRA_8888, Error); end; declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_ARGB_2101010)); C_Value : constant String := To_Binary (C_ARGB_2101010); Error : constant String := "Pixel_Format_ARGB_2101010 (" & Ada_Value & ") /= C_ARGB_2101010 (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_ARGB_2101010) = C_ARGB_2101010, Error); end; declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_YV_12)); C_Value : constant String := To_Binary (C_YV_12); Error : constant String := "Pixel_Format_YV_12 (" & Ada_Value & ") /= C_YV_12 (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_YV_12) = C_YV_12, Error); end; declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_IYUV)); C_Value : constant String := To_Binary (C_IYUV); Error : constant String := "Pixel_Format_IYUV (" & Ada_Value & ") /= C_IYUV (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_IYUV) = C_IYUV, Error); end; declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_YUY_2)); C_Value : constant String := To_Binary (C_YUY_2); Error : constant String := "Pixel_Format_YUY_2 (" & Ada_Value & ") /= C_YUY_2 (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_YUY_2) = C_YUY_2, Error); end; declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_UYVY)); C_Value : constant String := To_Binary (C_UYVY); Error : constant String := "Pixel_Format_UYVY (" & Ada_Value & ") /= C_UYVY (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_UYVY) = C_UYVY, Error); end; declare Ada_Value : constant String := To_Binary (To_int (Pixel_Format_YVYU)); C_Value : constant String := To_Binary (C_YVYU); Error : constant String := "Pixel_Format_YVYU (" & Ada_Value & ") /= C_YVYU (" & C_Value & ")"; begin -- Put_Line (Error); Assert (To_int (Pixel_Format_YVYU) = C_YVYU, Error); end; end Run_Test; end Pixel_Format_Test_Cases;
with swap, ada.text_io; use ada.text_io; procedure demo is a:integer:=3; b:integer:=5; begin put_line("A:"&integer'image(a)&", B:"&integer'image(b)); swap(a,b); put_line("A:"&integer'image(a)&", B:"&integer'image(b)); end demo;
with Support; use Support; package body BSSNBase.Runge is -- increments in data delta_gBar_ptr : MetricGridArray_ptr := new MetricGridArray (1..max_num_x, 1..max_num_y, 1..max_num_z); delta_ABar_ptr : ExtcurvGridArray_ptr := new ExtcurvGridArray (1..max_num_x, 1..max_num_y, 1..max_num_z); delta_N_ptr : LapseGridArray_ptr := new LapseGridArray (1..max_num_x, 1..max_num_y, 1..max_num_z); delta_phi_ptr : ConFactGridArray_ptr := new ConFactGridArray (1..max_num_x, 1..max_num_y, 1..max_num_z); delta_trK_ptr : TraceKGridArray_ptr := new TraceKGridArray (1..max_num_x, 1..max_num_y, 1..max_num_z); delta_Gi_ptr : GammaGridArray_ptr := new GammaGridArray (1..max_num_x, 1..max_num_y, 1..max_num_z); delta_gBar : MetricGridArray renames delta_gBar_ptr.all; delta_ABar : ExtcurvGridArray renames delta_ABar_ptr.all; delta_N : LapseGridArray renames delta_N_ptr.all; delta_phi : ConFactGridArray renames delta_phi_ptr.all; delta_trK : TraceKGridArray renames delta_trK_ptr.all; delta_Gi : GammaGridArray renames delta_Gi_ptr.all; -- data at start of time step old_gBar_ptr : MetricGridArray_ptr := new MetricGridArray (1..max_num_x, 1..max_num_y, 1..max_num_z); old_ABar_ptr : ExtcurvGridArray_ptr := new ExtcurvGridArray (1..max_num_x, 1..max_num_y, 1..max_num_z); old_N_ptr : LapseGridArray_ptr := new LapseGridArray (1..max_num_x, 1..max_num_y, 1..max_num_z); old_phi_ptr : ConFactGridArray_ptr := new ConFactGridArray (1..max_num_x, 1..max_num_y, 1..max_num_z); old_trK_ptr : TraceKGridArray_ptr := new TraceKGridArray (1..max_num_x, 1..max_num_y, 1..max_num_z); old_Gi_ptr : GammaGridArray_ptr := new GammaGridArray (1..max_num_x, 1..max_num_y, 1..max_num_z); old_gBar : MetricGridArray renames old_gBar_ptr.all; old_ABar : ExtcurvGridArray renames old_ABar_ptr.all; old_N : LapseGridArray renames old_N_ptr.all; old_phi : ConFactGridArray renames old_phi_ptr.all; old_trK : TraceKGridArray renames old_trK_ptr.all; old_Gi : GammaGridArray renames old_Gi_ptr.all; -- the_time at start of time step old_time : Real; procedure set_time_step is courant_time_step : Real; begin courant_time_step := courant * min ( dx, min (dy,dz) ); time_step := min (courant_time_step, constant_time_step); end set_time_step; procedure set_time_step_min is courant_time_step : Real; begin courant_time_step := courant_min * min ( dx, min (dy,dz) ); time_step_min := min (courant_time_step, constant_time_step); end set_time_step_min; procedure rk_step (ct : Real; cw : Real; params : SlaveParams) is i, j, k : Integer; the_task : Integer := params (1); beg_point : Integer := params (2); end_point : Integer := params (3); begin for b in beg_point .. end_point loop i := grid_point_list (b).i; j := grid_point_list (b).j; k := grid_point_list (b).k; gBar (i,j,k) := old_gBar (i,j,k) + time_step * ct * dot_gBar (i,j,k); ABar (i,j,k) := old_ABar (i,j,k) + time_step * ct * dot_ABar (i,j,k); N (i,j,k) := old_N (i,j,k) + time_step * ct * dot_N (i,j,k); phi (i,j,k) := old_phi (i,j,k) + time_step * ct * dot_phi (i,j,k); trK (i,j,k) := old_trK (i,j,k) + time_step * ct * dot_trK (i,j,k); Gi (i,j,k) := old_Gi (i,j,k) + time_step * ct * dot_Gi (i,j,k); delta_gBar (i,j,k) := delta_gBar (i,j,k) + time_step * cw * dot_gBar (i,j,k); delta_ABar (i,j,k) := delta_ABar (i,j,k) + time_step * cw * dot_ABar (i,j,k); delta_N (i,j,k) := delta_N (i,j,k) + time_step * cw * dot_N (i,j,k); delta_phi (i,j,k) := delta_phi (i,j,k) + time_step * cw * dot_phi (i,j,k); delta_trK (i,j,k) := delta_trK (i,j,k) + time_step * cw * dot_trK (i,j,k); delta_Gi (i,j,k) := delta_Gi (i,j,k) + time_step * cw * dot_Gi (i,j,k); end loop; if the_task = 1 then the_time := old_time + time_step * ct; end if; end rk_step; procedure beg_runge_kutta (params : SlaveParams) is i, j, k : Integer; the_task : Integer := params (1); beg_point : Integer := params (2); end_point : Integer := params (3); begin for b in beg_point .. end_point loop i := grid_point_list (b).i; j := grid_point_list (b).j; k := grid_point_list (b).k; old_gBar (i,j,k) := gBar (i,j,k); old_ABar (i,j,k) := ABar (i,j,k); old_N (i,j,k) := N (i,j,k); old_phi (i,j,k) := phi (i,j,k); old_trK (i,j,k) := trK (i,j,k); old_Gi (i,j,k) := Gi (i,j,k); dot_gBar (i,j,k) := (others => 0.0); dot_ABar (i,j,k) := (others => 0.0); dot_N (i,j,k) := 0.0; dot_phi (i,j,k) := 0.0; dot_trK (i,j,k) := 0.0; dot_Gi (i,j,k) := (others => 0.0); delta_gBar (i,j,k) := (others => 0.0); delta_ABar (i,j,k) := (others => 0.0); delta_N (i,j,k) := 0.0; delta_phi (i,j,k) := 0.0; delta_trK (i,j,k) := 0.0; delta_Gi (i,j,k) := (others => 0.0); end loop; if the_task = 1 then old_time := the_time; end if; end beg_runge_kutta; procedure end_runge_kutta (params : SlaveParams) is i, j, k : Integer; the_task : Integer := params (1); beg_point : Integer := params (2); end_point : Integer := params (3); begin for b in beg_point .. end_point loop i := grid_point_list (b).i; j := grid_point_list (b).j; k := grid_point_list (b).k; gBar (i,j,k) := old_gBar (i,j,k) + delta_gBar (i,j,k); ABar (i,j,k) := old_ABar (i,j,k) + delta_ABar (i,j,k); N (i,j,k) := old_N (i,j,k) + delta_N (i,j,k); phi (i,j,k) := old_phi (i,j,k) + delta_phi (i,j,k); trK (i,j,k) := old_trK (i,j,k) + delta_trK (i,j,k); Gi (i,j,k) := old_Gi (i,j,k) + delta_Gi (i,j,k); end loop; if the_task = 1 then the_time := the_time + time_step; end if; end end_runge_kutta; end BSSNBase.Runge;
-------------------------------------------------------------------------------- -- -- -- B A L L _ O N _ B E A M _ A D C -- -- -- -- Body -- -- -- -- This package implements an A/D converter interface with a position sensor -- -- sensor of package Ball_On_Beam_Simulator, instead of the "ideal" results -- -- produced by function Ball_Position of that BB.Ideal. -- -- The ADC converter transforms the result of Ball_Position into a 12-bit -- -- conversion. The conversion has some random noise added, with gaussian -- -- distribution to better emulate reality and to motivate the need for using -- -- some form of filtering. -- -- -- -- -- Author: Jorge Real -- -- Universitat Politecnica de Valencia -- -- December, 2020 - Version 1 -- -- February, 2021 - Version 2 -- -- -- -- -- -- This package implements an A/D converter interface with the position -- -- sensor of package Ball_On_Beam_Simulator, instead of the "ideal" results -- -- produced by function Ball_Position of that package. -- -- The ADC converter transforms the result of Ball_Position into a 12-bit -- -- conversion. The conversion has some random noise added, with gaussian -- -- distribution to better emulate reality and to motivate the need for using -- -- some form of filtering. -- -- -- -- This is free software in the ample sense: -- -- you can use it freely, provided you preserve -- -- this comment at the header of source files -- -- and you clearly indicate the changes made to -- -- the original file, if any. -- -- -- -------------------------------------------------------------------------------- with Ada.Real_Time; use Ada.Real_Time; with Ada.Real_Time.Timing_Events; use Ada.Real_Time.Timing_Events; with Ada.Numerics; use Ada.Numerics; with Ada.Numerics.Float_Random; use Ada.Numerics.Float_Random; with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; package body BB.ADC is -- The following procedures just call the implementation in package -- Ball_On_Beam_Simulator. Ball_On_Beam_ADC only modifies the interface -- with the position sensor, emulating an A/D converter procedure Set_Beam_Angle (Inclination : Angle) renames BB.Set_Beam_Angle; procedure Set_Simulation_Mode (Mode : Simulation_Mode) renames BB.Set_Simulation_Mode; -- Move system to a solar system object procedure Move_BB_To (Where : in Solar_System_Object) renames BB.Move_BB_To; -- ADC implementation -- Latency of conversion Conversion_Delay : Time_Span := Milliseconds (2); -- To simulate gaussian noise in the ADC Noise : Generator; -- Standard deviation of noise Sigma : constant := 4.0; -- Protected object for ADC interrupt simulation protected ADC is pragma Interrupt_Priority; procedure Set_User_Handler (UH : ADC_Handler_Access); function Conversion_Result return ADC_Register; procedure Write_CR (Value : ADC_Register); private ADC_Interrupt : Timing_Event; procedure ADC_Int_Handler (TE : in out Timing_Event); Interrupt_Enabled : Boolean := False; User_Handler : ADC_Handler_Access; User_Handler_Is_Set : Boolean := False; Conversion : ADC_Register := 0; end ADC; protected body ADC is function Conversion_Result return ADC_Register is (Conversion); procedure Set_User_Handler (UH : ADC_Handler_Access) is begin User_Handler := UH; User_Handler_Is_Set := True; end Set_User_Handler; procedure Write_CR (Value : ADC_Register) is IE : constant Boolean := ((Value / 4) mod 2) /= 0; -- bit 2 TRG : constant Boolean := (Value mod 2) /= 0; -- bit 0 begin if IE then Interrupt_Enabled := True; else Interrupt_Enabled := False; end if; if TRG then -- Set TE for end-of-conversion interrupt Set_Handler (Event => ADC_Interrupt, At_Time => Clock + Conversion_Delay, Handler => ADC_Int_Handler'Access); -- Clear EOC bit Conversion := Conversion and 16#7FFF#; end if; end Write_CR; procedure ADC_Int_Handler (TE : in out Timing_Event) is -- Simulated ball position, with gaussian random noise added -- Gaussian random obtained using the Box-Muller method Simulated_Position : constant Float := Ball_Position + (Sigma * Sqrt (-2.0 * Log (Random (Noise), Ada.Numerics.e)) * Cos (2.0 * Pi * Random (Noise))); -- Aux is assigned the Simulated_Position scaled to an ADC value. The -- Simulated_Position could over/underflow the range of Position, -- due to the addition of noise. Hence the convenience of this Aux -- variable before we saturate the conversion to fall within the -- range (0..4095), first thing we do in the body of this handler. Aux : Integer := Integer (( (Simulated_Position - Position'First) * 4096.0) / (Position'Last - Position'First)); begin -- Saturate Aux to a range representable with 12 bits in NBC. Needed -- because the addition of noise may over/underflow that range Aux := Integer'Max (0, Aux); Aux := Integer'Min (Aux, 4095); -- Set the EOC bit in the Data register Conversion := ADC_Register (Aux) or 16#8000#; -- Execute user handler if interrupts are enabled and a handler is set if Interrupt_Enabled and then User_Handler_Is_Set then User_Handler.all; end if; end ADC_Int_Handler; end ADC; ------------------------ -- Attach_ADC_Handler -- ------------------------ procedure Attach_ADC_Handler (Handler : ADC_Handler_Access) is begin ADC.Set_User_Handler (Handler); end Attach_ADC_Handler; -------------- -- Write_CR -- -------------- procedure Write_CR (Value : ADC_Register) is begin ADC.Write_CR (Value); end Write_CR; ------------- -- Read_DR -- ------------- function Read_DR return ADC_Register is (ADC.Conversion_Result); begin Reset (Noise); end BB.ADC;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../../License.txt with CommonText; with AdaBase.Interfaces.Connection; package AdaBase.Connection.Base is package CT renames CommonText; package AIC renames AdaBase.Interfaces.Connection; type Base_Connection is abstract new Base_Pure and AIC.iConnection with private; type Base_Connection_Access is access all Base_Connection'Class; overriding function autoCommit (conn : Base_Connection) return Boolean; overriding procedure setCaseMode (conn : out Base_Connection; mode : Case_Modes); overriding function getCaseMode (conn : Base_Connection) return Case_Modes; overriding procedure setMaxBlobSize (conn : out Base_Connection; maxsize : BLOB_Maximum); overriding function maxBlobSize (conn : Base_Connection) return BLOB_Maximum; overriding function transactionIsolation (conn : Base_Connection) return Trax_Isolation; overriding function serverVersion (conn : Base_Connection) return String; overriding function serverInfo (conn : Base_Connection) return String; overriding function clientVersion (conn : Base_Connection) return String; overriding function clientInfo (conn : Base_Connection) return String; overriding function connected (conn : Base_Connection) return Boolean; function utf8_encoding (conn : Base_Connection) return Boolean; private type Base_Connection is abstract new Base_Pure and AIC.iConnection with record prop_auto_commit : Boolean := False; prop_active : Boolean := False; prop_trax_isolation : Trax_Isolation := repeatable_read; prop_case_mode : Case_Modes := natural_case; prop_max_blob : BLOB_Maximum := 2 ** 12; -- 4kb encoding_is_utf8 : Boolean := True; character_set : CT.Text := CT.SUS ("UTF8"); info_server : CT.Text := CT.blank; info_server_version : CT.Text := CT.blank; info_client : CT.Text := CT.blank; info_client_version : CT.Text := CT.blank; end record; overriding procedure finalize (conn : in out Base_Connection) is null; end AdaBase.Connection.Base;
----------------------------------------------------------------------- -- mat-expressions -- Expressions for event and memory slot selection -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with MAT.Frames; with MAT.Expressions.Parser; package body MAT.Expressions is procedure Free is new Ada.Unchecked_Deallocation (Object => Node_Type, Name => Node_Type_Access); -- Destroy recursively the node, releasing the storage. procedure Destroy (Node : in out Node_Type_Access); Resolver : Resolver_Type_Access; -- ------------------------------ -- Create a NOT expression node. -- ------------------------------ function Create_Not (Expr : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NOT, Expr => Expr.Node); Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter); return Result; end Create_Not; -- ------------------------------ -- Create a AND expression node. -- ------------------------------ function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_AND, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_And; -- ------------------------------ -- Create a OR expression node. -- ------------------------------ function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_OR, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_Or; -- ------------------------------ -- Create an INSIDE expression node. -- ------------------------------ function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String; Kind : in Inside_Type) return Expression_Type is Result : Expression_Type; Region : MAT.Memory.Region_Info; begin if Resolver /= null then case Kind is when INSIDE_REGION | INSIDE_DIRECT_REGION => Region := Resolver.Find_Region (Ada.Strings.Unbounded.To_String (Name)); when others => Region := Resolver.Find_Symbol (Ada.Strings.Unbounded.To_String (Name)); end case; end if; if Kind = INSIDE_DIRECT_REGION or Kind = INSIDE_DIRECT_FUNCTION then Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_IN_FUNC_DIRECT, Min_Addr => Region.Start_Addr, Max_Addr => Region.End_Addr); else Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_IN_FUNC, Min_Addr => Region.Start_Addr, Max_Addr => Region.End_Addr); end if; return Result; end Create_Inside; function Create_Inside (Addr : in MAT.Types.Uint64; Kind : in Inside_Type) return Expression_Type is Result : Expression_Type; Region : MAT.Memory.Region_Info; begin if Resolver /= null then Region := Resolver.Find_Symbol (Addr); end if; if Kind = INSIDE_DIRECT_REGION or Kind = INSIDE_DIRECT_FUNCTION then Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_IN_FUNC_DIRECT, Min_Addr => Region.Start_Addr, Max_Addr => Region.End_Addr); else Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_IN_FUNC, Min_Addr => Region.Start_Addr, Max_Addr => Region.End_Addr); end if; return Result; end Create_Inside; -- ------------------------------ -- Create an size range expression node. -- ------------------------------ function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_SIZE, Min_Size => Min, Max_Size => Max); return Result; end Create_Size; -- ------------------------------ -- Create an addr range expression node. -- ------------------------------ function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_HAS_ADDR, Min_Addr => Min, Max_Addr => Max); return Result; end Create_Addr; -- ------------------------------ -- Create an time range expression node. -- ------------------------------ function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type is use type MAT.Types.Target_Tick_Ref; Result : Expression_Type; Start : MAT.Types.Target_Tick_Ref; begin if Resolver /= null then Start := Resolver.Get_Start_Time; else Start := 0; end if; if Max = MAT.Types.Target_Tick_Ref'Last then Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_TIME, Min_Time => Min + Start, Max_Time => Max); else Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_TIME, Min_Time => Min + Start, Max_Time => Max + Start); end if; return Result; end Create_Time; -- ------------------------------ -- Create a thread ID range expression node. -- ------------------------------ function Create_Thread (Min : in MAT.Types.Target_Thread_Ref; Max : in MAT.Types.Target_Thread_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_THREAD, Min_Thread => Min, Max_Thread => Max); return Result; end Create_Thread; -- ------------------------------ -- Create a event type expression check. -- ------------------------------ function Create_Event_Type (Event_Kind : in MAT.Events.Probe_Index_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_TYPE, Event_Kind => Event_Kind); return Result; end Create_Event_Type; -- ------------------------------ -- Create an event ID range expression node. -- ------------------------------ function Create_Event (Min : in MAT.Events.Event_Id_Type; Max : in MAT.Events.Event_Id_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_EVENT, Min_Event => Min, Max_Event => Max); return Result; end Create_Event; -- ------------------------------ -- Create an expression node to keep allocation events which don't have any associated free. -- ------------------------------ function Create_No_Free return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NO_FREE); return Result; end Create_No_Free; -- ------------------------------ -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is begin if Node.Node = null then return True; else return Is_Selected (Node.Node.all, Addr, Allocation); end if; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Event : in MAT.Events.Target_Event_Type) return Boolean is begin if Node.Node = null then return True; else return Is_Selected (Node.Node.all, Event); end if; end Is_Selected; -- ------------------------------ -- Evaluate the node against the context. Returns True if the node expression -- selects the memory slot defined by the context. -- ------------------------------ function Is_Selected (Node : in Node_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; use type MAT.Types.Target_Thread_Ref; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Addr, Allocation); when N_AND => return Is_Selected (Node.Left.all, Addr, Allocation) and then Is_Selected (Node.Right.all, Addr, Allocation); when N_OR => return Is_Selected (Node.Left.all, Addr, Allocation) or else Is_Selected (Node.Right.all, Addr, Allocation); when N_RANGE_SIZE => return Allocation.Size >= Node.Min_Size and Allocation.Size <= Node.Max_Size; when N_RANGE_ADDR => return Addr >= Node.Min_Addr and Addr <= Node.Max_Addr; when N_RANGE_TIME => return Allocation.Time >= Node.Min_Time and Allocation.Time <= Node.Max_Time; when N_HAS_ADDR => return Addr <= Node.Min_Addr and Addr + Allocation.Size >= Node.Max_Addr; when N_IN_FUNC => return MAT.Frames.In_Function (Allocation.Frame, Node.Min_Addr, Node.Max_Addr); when N_IN_FUNC_DIRECT => return MAT.Frames.By_Function (Allocation.Frame, Node.Min_Addr, Node.Max_Addr); when N_THREAD => return Allocation.Thread >= Node.Min_Thread and Allocation.Thread <= Node.Max_Thread; when others => return False; end case; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Node_Type; Event : in MAT.Events.Target_Event_Type) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; use type MAT.Types.Target_Thread_Ref; use type MAT.Events.Event_Id_Type; use type MAT.Events.Probe_Index_Type; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Event); when N_AND => return Is_Selected (Node.Left.all, Event) and then Is_Selected (Node.Right.all, Event); when N_OR => return Is_Selected (Node.Left.all, Event) or else Is_Selected (Node.Right.all, Event); when N_RANGE_SIZE => return Event.Size >= Node.Min_Size and Event.Size <= Node.Max_Size; when N_RANGE_ADDR => return Event.Addr >= Node.Min_Addr and Event.Addr <= Node.Max_Addr; when N_RANGE_TIME => return Event.Time >= Node.Min_Time and Event.Time <= Node.Max_Time; when N_EVENT => return Event.Id >= Node.Min_Event and Event.Id <= Node.Max_Event; when N_THREAD => return Event.Thread >= Node.Min_Thread and Event.Thread <= Node.Max_Thread; when N_TYPE => return Event.Index = Node.Event_Kind; when N_HAS_ADDR => if Event.Index = MAT.Events.MSG_MALLOC or Event.Index = MAT.Events.MSG_REALLOC then return Event.Addr <= Node.Min_Addr and Event.Addr + Event.Size >= Node.Max_Addr; end if; return False; when N_NO_FREE => if Event.Index = MAT.Events.MSG_MALLOC or Event.Index = MAT.Events.MSG_REALLOC then return Event.Next_Id = 0; else return False; end if; when N_IN_FUNC => return MAT.Frames.In_Function (Event.Frame, Node.Min_Addr, Node.Max_Addr); when N_IN_FUNC_DIRECT => return MAT.Frames.By_Function (Event.Frame, Node.Min_Addr, Node.Max_Addr); when others => return False; end case; end Is_Selected; -- ------------------------------ -- Parse the string and return the expression tree. -- ------------------------------ function Parse (Expr : in String; Resolver : in Resolver_Type_Access) return Expression_Type is begin MAT.Expressions.Resolver := Resolver; return MAT.Expressions.Parser.Parse (Expr); end Parse; -- ------------------------------ -- Destroy recursively the node, releasing the storage. -- ------------------------------ procedure Destroy (Node : in out Node_Type_Access) is Release : Boolean; begin if Node /= null then Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Release); if Release then case Node.Kind is when N_NOT => Destroy (Node.Expr); when N_AND | N_OR => Destroy (Node.Left); Destroy (Node.Right); when others => null; end case; Free (Node); else Node := null; end if; end if; end Destroy; -- ------------------------------ -- Release the reference and destroy the expression tree if it was the last reference. -- ------------------------------ overriding procedure Finalize (Obj : in out Expression_Type) is begin if Obj.Node /= null then Destroy (Obj.Node); end if; end Finalize; -- ------------------------------ -- Update the reference after an assignment. -- ------------------------------ overriding procedure Adjust (Obj : in out Expression_Type) is begin if Obj.Node /= null then Util.Concurrent.Counters.Increment (Obj.Node.Ref_Counter); end if; end Adjust; end MAT.Expressions;
-- { dg-do compile } -- { dg-options "-fdump-tree-original" } package body Renaming6 is function Get_I return Integer is begin return I; end; procedure Set_I (Val : Integer) is begin I := Val; end; function Get_J return Integer is begin return J; end; procedure Set_J (Val : Integer) is begin J := Val; end; end Renaming6; -- { dg-final { scan-tree-dump-times "atomic_load" 2 "original" } } -- { dg-final { scan-tree-dump-times "atomic_store" 2 "original" } } -- { dg-final { scan-tree-dump-not "j" "original" } }
pragma SPARK_Mode; package body Geo_Filter is procedure FilterState (State : in out LineState; Thresh : out Boolean) is Current_Point : constant Point_Type := State2PointLookup (State); X_Sum, Y_Sum : Integer := 0; X_Avg, Y_Avg : Integer; begin case State is when Unknown => Thresh := True; when others => Window (Window_Index) := Current_Point; if Window_Index = Window_Type'Last then Window_Index := Window_Type'First; else Window_Index := Window_Index + 1; end if; for Item of Window loop X_Sum := X_Sum + Item.X; Y_Sum := Y_Sum + Item.Y; end loop; X_Avg := X_Sum / Window'Length; Y_Avg := Y_Sum / Window'Length; State := AvgPoint2StateLookup (X_Avg, Y_Avg); Thresh := (Radii_Length (X => X_Avg, Y => Y_Avg) > Radii_Threshold); end case; end FilterState; function Radii_Length (X : Integer; Y : Integer) return Integer is N : constant Integer := (X * X) + (Y * Y); A : Integer := N; B : Integer := (A + 1) / 2; begin while B < A loop A := B; B := (A + N / A) / 2; end loop; return A; end Radii_Length; end Geo_Filter;
with Constants; use constants; with Interfaces; use Interfaces; with Ada.Real_Time; use Ada.Real_Time; procedure main with SPARK_Mode is begin Do_Something; end main;
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- XML Processor -- -- -- -- Testsuite Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2011-2012, Vadim Godunko <vgodunko@gmail.com> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with Ada.Wide_Wide_Text_IO; with League.IRIs; with Matreshka.XML_Catalogs.Entry_Files; with Matreshka.XML_Catalogs.Loader; with Matreshka.XML_Catalogs.Resolver; package body XMLCatConf.Testsuite_Handlers is use type League.Strings.Universal_String; type Test_Type is (Error, Match, No_Match); -- Tags Test_Suite_Tag : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("TestSuite"); Test_Cases_Tag : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("TestCases"); Entity_Test_Tag : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("EntityTest"); URI_Test_Tag : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("UriTest"); -- Attributes Catalog_Attribute : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("catalog"); Expected_File_Attribute : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("expectedFile"); Expected_URI_Attribute : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("expectedUri"); Id_Attribute : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("id"); Prefer_Attribute : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("prefer"); Public_Id_Attribute : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("publicId"); System_Id_Attribute : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("systemId"); Type_Attribute : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("type"); URI_Attribute : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("uri"); -- Literals Error_Literal : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("error"); Match_Literal : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("match"); No_Match_Literal : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("nomatch"); Public_Literal : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("public"); System_Literal : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("system"); procedure Process_Entity_Test_Start_Tag (Self : in out Testsuite_Handler; Attributes : XML.SAX.Attributes.SAX_Attributes; Success : in out Boolean); procedure Process_Uri_Test_Start_Tag (Self : in out Testsuite_Handler; Attributes : XML.SAX.Attributes.SAX_Attributes; Success : in out Boolean); function Value (Image : League.Strings.Universal_String) return Test_Type; -- Converts string representation of test type into internal -- representation. function Value (Image : League.Strings.Universal_String) return Matreshka.XML_Catalogs.Entry_Files.Prefer_Mode; -- Converts string representation of test type into internal -- representation. ----------- -- Error -- ----------- overriding procedure Error (Self : in out Testsuite_Handler; Occurrence : XML.SAX.Parse_Exceptions.SAX_Parse_Exception; Success : in out Boolean) is begin Ada.Wide_Wide_Text_IO.Put_Line (Ada.Wide_Wide_Text_IO.Standard_Error, "(error) " & Occurrence.Message.To_Wide_Wide_String); end Error; ------------------ -- Error_String -- ------------------ overriding function Error_String (Self : Testsuite_Handler) return League.Strings.Universal_String is begin return League.Strings.Empty_Universal_String; end Error_String; ----------------- -- Fatal_Error -- ----------------- overriding procedure Fatal_Error (Self : in out Testsuite_Handler; Occurrence : XML.SAX.Parse_Exceptions.SAX_Parse_Exception) is begin Ada.Wide_Wide_Text_IO.Put_Line (Ada.Wide_Wide_Text_IO.Standard_Error, "(fatal) " & Occurrence.Message.To_Wide_Wide_String); end Fatal_Error; ----------------------------------- -- Process_Entity_Test_Start_Tag -- ----------------------------------- procedure Process_Entity_Test_Start_Tag (Self : in out Testsuite_Handler; Attributes : XML.SAX.Attributes.SAX_Attributes; Success : in out Boolean) is Id : constant League.Strings.Universal_String := Attributes.Value (Id_Attribute); Catalog : constant League.Strings.Universal_String := Self.Locator.Base_URI.Resolve (League.IRIs.From_Universal_String (Attributes.Value (Catalog_Attribute))).To_Universal_String; Expected_File : constant League.Strings.Universal_String := Attributes.Value (Expected_File_Attribute); Expected_URI : constant League.Strings.Universal_String := Attributes.Value (Expected_URI_Attribute); Kind : constant Test_Type := Value (Attributes.Value (Type_Attribute)); Public_Id : constant League.Strings.Universal_String := Attributes.Value (Public_Id_Attribute); System_Id : constant League.Strings.Universal_String := Attributes.Value (System_Id_Attribute); Prefer : constant Matreshka.XML_Catalogs.Entry_Files.Prefer_Mode := Value (Attributes.Value (Prefer_Attribute)); Expected : League.Strings.Universal_String; Resolved_URI : League.Strings.Universal_String; Resolved : Boolean; File : Matreshka.XML_Catalogs.Entry_Files.Catalog_Entry_File_Access := Matreshka.XML_Catalogs.Loader.Load (Catalog, Prefer); List : aliased Matreshka.XML_Catalogs.Entry_Files.Catalog_Entry_File_List; begin List.Catalog_Entry_Files.Append (File); if Expected_File.Is_Empty and not Expected_URI.Is_Empty then Expected := Expected_URI; elsif not Expected_File.Is_Empty and Expected_URI.Is_Empty then Expected := Expected_File; else Expected.Clear; end if; -- Resolve document. Matreshka.XML_Catalogs.Resolver.Resolve_External_Identifier (List'Unchecked_Access, Public_Id, System_Id, Resolved_URI, Resolved); case Kind is when Error => if Resolved then raise Program_Error; end if; when Match => if not Resolved then Ada.Wide_Wide_Text_IO.Put_Line ("FAIL " & Id.To_Wide_Wide_String); Ada.Wide_Wide_Text_IO.Put_Line ("Expected: '" & Expected.To_Wide_Wide_String & '''); raise Program_Error; end if; -- Construct expected absolute URI. Expected := Self.Locator.Base_URI.Resolve (League.IRIs.From_Universal_String (Expected)).To_Universal_String; if Resolved_URI /= Expected then Ada.Wide_Wide_Text_IO.Put_Line ("FAIL " & Id.To_Wide_Wide_String); Ada.Wide_Wide_Text_IO.Put_Line (" Expected: '" & Expected.To_Wide_Wide_String & '''); Ada.Wide_Wide_Text_IO.Put_Line (" Resolved: '" & Resolved_URI.To_Wide_Wide_String & '''); raise Program_Error; end if; when No_Match => if Resolved then raise Program_Error; end if; if Resolved_URI /= Expected then Ada.Wide_Wide_Text_IO.Put_Line ("FAIL " & Id.To_Wide_Wide_String); Ada.Wide_Wide_Text_IO.Put_Line (" Expected: '" & Expected.To_Wide_Wide_String & '''); Ada.Wide_Wide_Text_IO.Put_Line (" Resolved: '" & Resolved_URI.To_Wide_Wide_String & '''); raise Program_Error; end if; end case; end Process_Entity_Test_Start_Tag; -------------------------------- -- Process_Uri_Test_Start_Tag -- -------------------------------- procedure Process_Uri_Test_Start_Tag (Self : in out Testsuite_Handler; Attributes : XML.SAX.Attributes.SAX_Attributes; Success : in out Boolean) is Id : constant League.Strings.Universal_String := Attributes.Value (Id_Attribute); Catalog : constant League.Strings.Universal_String := Self.Locator.Base_URI.Resolve (League.IRIs.From_Universal_String (Attributes.Value (Catalog_Attribute))).To_Universal_String; Expected_File : constant League.Strings.Universal_String := Attributes.Value (Expected_File_Attribute); Expected_URI : constant League.Strings.Universal_String := Attributes.Value (Expected_URI_Attribute); Kind : constant Test_Type := Value (Attributes.Value (Type_Attribute)); URI : constant League.Strings.Universal_String := Attributes.Value (URI_Attribute); Expected : League.Strings.Universal_String; Resolved_URI : League.Strings.Universal_String; Resolved : Boolean; File : Matreshka.XML_Catalogs.Entry_Files.Catalog_Entry_File_Access := Matreshka.XML_Catalogs.Loader.Load (Catalog, Matreshka.XML_Catalogs.Entry_Files.System); List : aliased Matreshka.XML_Catalogs.Entry_Files.Catalog_Entry_File_List; begin List.Catalog_Entry_Files.Append (File); if Expected_File.Is_Empty and not Expected_URI.Is_Empty then Expected := Expected_URI; elsif not Expected_File.Is_Empty and Expected_URI.Is_Empty then Expected := Expected_File; else Expected.Clear; end if; -- Resolve URI. Matreshka.XML_Catalogs.Resolver.Resolve_URI (List'Unchecked_Access, URI, Resolved_URI, Resolved); case Kind is when Error => if Resolved then raise Program_Error; end if; when Match => if not Resolved then Ada.Wide_Wide_Text_IO.Put_Line ("FAIL " & Id.To_Wide_Wide_String); Ada.Wide_Wide_Text_IO.Put_Line (" Expected: '" & Expected.To_Wide_Wide_String & '''); raise Program_Error; end if; -- Construct expected absolute URI. Expected := Self.Locator.Base_URI.Resolve (League.IRIs.From_Universal_String (Expected)).To_Universal_String; if Resolved_URI /= Expected then Ada.Wide_Wide_Text_IO.Put_Line ("FAIL " & Id.To_Wide_Wide_String); Ada.Wide_Wide_Text_IO.Put_Line (" Expected: '" & Expected.To_Wide_Wide_String & '''); Ada.Wide_Wide_Text_IO.Put_Line (" Resolved: '" & Resolved_URI.To_Wide_Wide_String & '''); raise Program_Error; end if; when No_Match => if Resolved then raise Program_Error; end if; if Resolved_URI /= Expected then Ada.Wide_Wide_Text_IO.Put_Line ("FAIL " & Id.To_Wide_Wide_String); Ada.Wide_Wide_Text_IO.Put_Line (" Expected: '" & Expected.To_Wide_Wide_String & '''); Ada.Wide_Wide_Text_IO.Put_Line (" Resolved: '" & Resolved_URI.To_Wide_Wide_String & '''); raise Program_Error; end if; end case; end Process_Uri_Test_Start_Tag; -------------------------- -- Set_Document_Locator -- -------------------------- overriding procedure Set_Document_Locator (Self : in out Testsuite_Handler; Locator : XML.SAX.Locators.SAX_Locator) is begin Self.Locator := Locator; end Set_Document_Locator; ------------------- -- Start_Element -- ------------------- overriding procedure Start_Element (Self : in out Testsuite_Handler; Namespace_URI : League.Strings.Universal_String; Local_Name : League.Strings.Universal_String; Qualified_Name : League.Strings.Universal_String; Attributes : XML.SAX.Attributes.SAX_Attributes; Success : in out Boolean) is begin if Qualified_Name = Test_Suite_Tag then null; elsif Qualified_Name = Test_Cases_Tag then null; elsif Qualified_Name = Entity_Test_Tag then Process_Entity_Test_Start_Tag (Self, Attributes, Success); elsif Qualified_Name = Uri_Test_Tag then Process_Uri_Test_Start_Tag (Self, Attributes, Success); else raise Program_Error; end if; end Start_Element; ----------- -- Value -- ----------- function Value (Image : League.Strings.Universal_String) return Matreshka.XML_Catalogs.Entry_Files.Prefer_Mode is begin if Image = Public_Literal then return Matreshka.XML_Catalogs.Entry_Files.Public; elsif Image = System_Literal then return Matreshka.XML_Catalogs.Entry_Files.System; else raise Constraint_Error; end if; end Value; ----------- -- Value -- ----------- function Value (Image : League.Strings.Universal_String) return Test_Type is begin if Image = Error_Literal then return Error; elsif Image = Match_Literal then return Match; elsif Image = No_Match_Literal then return No_Match; else raise Constraint_Error; end if; end Value; ------------- -- Warning -- ------------- overriding procedure Warning (Self : in out Testsuite_Handler; Occurrence : XML.SAX.Parse_Exceptions.SAX_Parse_Exception; Success : in out Boolean) is begin Ada.Wide_Wide_Text_IO.Put_Line (Ada.Wide_Wide_Text_IO.Standard_Error, "(warning) " & Occurrence.Message.To_Wide_Wide_String); end Warning; end XMLCatConf.Testsuite_Handlers;
-- C52104Y.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 LENGTHS MUST MATCH IN ARRAY AND SLICE ASSIGNMENTS. -- MORE SPECIFICALLY, TEST THAT ATTEMPTED ASSIGNMENTS BETWEEN -- ARRAYS WITH NON-MATCHING LENGTHS LEAVE THE DESTINATION ARRAY -- INTACT AND CAUSE CONSTRAINT_ERROR TO BE RAISED. -- (OVERLAPS BETWEEN THE OPERANDS OF THE ASSIGNMENT STATEMENT -- ARE TREATED ELSEWHERE.) -- THIS IS A SPECIAL CASE IN -- DIVISION D : NULL ARRAYS WHOSE LENGTHS ARE NOT DETERMINABLE -- STATICALLY -- WHICH (THE SPECIAL CASE) TREATS TWO-DIMENSIONAL ARRAYS WHOSE LENGTH -- ALONG ONE DIMENSION IS GREATER THAN INTEGER'LAST AND WHOSE -- LENGTH ALONG THE OTHER DIMENSION IS 0 . -- AN ADDITIONAL OBJECTIVE OF THIS TEST IS TO CHECK WHETHER LENGTH -- COMPARISONS (AND LENGTH COMPUTATIONS) CAUSE CONSTRAINT_ERROR -- TO BE RAISED. -- *** NOTE: This test has been modified since ACVC version 1.11 to -- 9X -- *** remove incompatibilities associated with the transition -- 9X -- *** to Ada 9X. -- 9X -- *** -- 9X -- RM 07/31/81 -- SPS 03/22/83 -- JBG 06/16/83 -- EG 10/28/85 FIX NUMERIC_ERROR/CONSTRAINT_ERROR ACCORDING TO -- AI-00387. -- MRM 03/30/93 REMOVE NUMERIC_ERROR FOR 9X COMPATIBILITY WITH REPORT; PROCEDURE C52104Y IS USE REPORT ; BEGIN TEST( "C52104Y" , "CHECK THAT IN ARRAY ASSIGNMENTS AND IN SLICE" & " ASSIGNMENTS, THE LENGTHS MUST MATCH" ); -- IN THIS TEST WE CAN'T USE AGGREGATE ASSIGNMENT (EXCEPT WHEN -- THE AGGREGATES ARE STRING LITERALS); THEREFORE: -- -- (1) ARRAYS WILL BE INITIALIZED BY INDIVIDUAL ASSIGNMENTS; -- (2) CAN'T USE NON-NULL CONSTANT ARRAYS. -- WE ASSUME THAT IN AN ARRAY_TYPE_DEFINITION THE INDEX PORTION -- AND THE COMPONENT_TYPE PORTION ARE FUNCTIONALLY ORTHOGONAL -- ALSO AT THE IMPLEMENTATION LEVEL, I.E. THAT THE CORRECTNESS -- OF THE ACCESSING MECHANISM FOR ARRAYS DOES NOT DEPEND ON -- COMPONENT_TYPE. ACCORDINGLY WE ARE TESTING FOR SOME BUT -- NOT ALL KINDS OF COMPONENT_TYPE. (COMPONENT_TYPES INCLUDED: -- INTEGER , CHARACTER , BOOLEAN .) ------------------------------------------------------------------- -- (10) MULTIDIMENSIONAL ARRAY OBJECTS WHOSE TYPEMARKS WERE -- DEFINED USING THE "BOX" COMPOUND SYMBOL. -- (TWO-DIMENSIONAL ARRAYS OF BOOLEANS.) CONSTR_ERR: BEGIN -- THIS BLOCK CATCHES CONSTRAINT_ERROR IF IT IS -- RAISED BY THE SUBTYPE DECLARATION. DCL_ARR: DECLARE TYPE TABOX5 IS ARRAY( INTEGER RANGE <> , INTEGER RANGE <> ) OF BOOLEAN ; PRAGMA PACK (TABOX5); SUBTYPE TABOX52 IS TABOX5( IDENT_INT(13)..IDENT_INT( 13 ) , IDENT_INT(-6)..IDENT_INT( INTEGER'LAST-4 ) ); BEGIN COMMENT ("NO CONSTRAINT_ERROR FOR NON-NULL ARRAY SUBTYPE " & "WHEN ONE DIMENSION HAS INTEGER'LAST + 3 " & "COMPONENTS"); OBJ_DCL: DECLARE -- THIS BLOCK DECLARES ONE NULL ARRAY AND ONE -- PACKED BOOLEAN ARRAY WITH INTEGER'LAST + 3 -- COMPONENTS; STORAGE ERROR MAY BE RAISED. ARRX51 : TABOX5( IDENT_INT(13)..IDENT_INT( 12 ) , IDENT_INT(-6)..IDENT_INT( INTEGER'LAST-4 ) ); ARRX52 : TABOX52 ; -- BIG ARRAY HERE. BEGIN COMMENT ("NO CONSTRAINT OR STORAGE ERROR WHEN ARRAY "& "WITH INTEGER'LAST+3 COMPONENTS ALLOCATED"); -- NULL ARRAY ASSIGNMENT: ARRX52 := ARRX51 ; FAILED( "EXCEPTION NOT RAISED (10)" ); EXCEPTION WHEN CONSTRAINT_ERROR => COMMENT ("CONSTRAINT_ERROR RAISED WHEN " & "CHECKING LENGTHS FOR ARRAY HAVING " & "> INTEGER'LAST COMPONENTS ON ONE " & "DIMENSION"); WHEN OTHERS => FAILED( "OTHER EXCEPTION RAISED - SUBTEST 10"); END OBJ_DCL; EXCEPTION WHEN STORAGE_ERROR => COMMENT ("STORAGE_ERROR RAISED WHEN DECLARING ONE "& "PACKED BOOLEAN ARRAY WITH INTEGER'LAST "& "+ 3 COMPONENTS"); WHEN CONSTRAINT_ERROR => COMMENT ("CONSTRAINT_ERROR RAISED WHEN DECLARING "& "ONE PACKED BOOLEAN ARRAY WITH "& "INTEGER'LAST + 3 COMPONENTS"); WHEN OTHERS => FAILED ("SOME EXCEPTION RAISED - 3"); END DCL_ARR; EXCEPTION WHEN CONSTRAINT_ERROR => COMMENT ("CONSTRAINT_ERROR RAISED WHEN DECLARING AN " & "ARRAY SUBTYPE WITH INTEGER'LAST + 3 " & "COMPONENTS"); WHEN STORAGE_ERROR => FAILED ("STORAGE_ERROR RAISED FOR TYPE DECLARATION"); WHEN OTHERS => FAILED( "OTHER EXCEPTION RAISED - 4"); END CONSTR_ERR; RESULT ; END C52104Y;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- S Y S T E M . S T O R A G E _ P O O L S . S U B P O O L S -- -- -- -- S p e c -- -- -- -- Copyright (C) 2011-2012, 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. -- -- -- -- -- -- -- -- -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Ada.Finalization; with System.Finalization_Masters; with System.Storage_Elements; package System.Storage_Pools.Subpools is pragma Preelaborate; type Root_Storage_Pool_With_Subpools is abstract new Root_Storage_Pool with private; -- The base for all implementations of Storage_Pool_With_Subpools. This -- type is Limited_Controlled by derivation. To use subpools, an access -- type must be associated with an implementation descending from type -- Root_Storage_Pool_With_Subpools. type Root_Subpool is abstract tagged limited private; -- The base for all implementations of Subpool. Objects of this type are -- managed by the pool_with_subpools. type Subpool_Handle is access all Root_Subpool'Class; for Subpool_Handle'Storage_Size use 0; -- Since subpools are limited types by definition, a handle is instead used -- to manage subpool abstractions. overriding procedure Allocate (Pool : in out Root_Storage_Pool_With_Subpools; Storage_Address : out System.Address; Size_In_Storage_Elements : System.Storage_Elements.Storage_Count; Alignment : System.Storage_Elements.Storage_Count); -- Allocate an object described by Size_In_Storage_Elements and Alignment -- on the default subpool of Pool. Controlled types allocated through this -- routine will NOT be handled properly. procedure Allocate_From_Subpool (Pool : in out Root_Storage_Pool_With_Subpools; Storage_Address : out System.Address; Size_In_Storage_Elements : System.Storage_Elements.Storage_Count; Alignment : System.Storage_Elements.Storage_Count; Subpool : not null Subpool_Handle) is abstract; -- ??? This precondition causes errors in simple tests, disabled for now -- with Pre'Class => Pool_Of_Subpool (Subpool) = Pool'Access; -- This routine requires implementation. Allocate an object described by -- Size_In_Storage_Elements and Alignment on a subpool. function Create_Subpool (Pool : in out Root_Storage_Pool_With_Subpools) return not null Subpool_Handle is abstract; -- This routine requires implementation. Create a subpool within the given -- pool_with_subpools. overriding procedure Deallocate (Pool : in out Root_Storage_Pool_With_Subpools; Storage_Address : System.Address; Size_In_Storage_Elements : System.Storage_Elements.Storage_Count; Alignment : System.Storage_Elements.Storage_Count) is null; procedure Deallocate_Subpool (Pool : in out Root_Storage_Pool_With_Subpools; Subpool : in out Subpool_Handle) is abstract; -- ??? This precondition causes errors in simple tests, disabled for now -- with Pre'Class => Pool_Of_Subpool (Subpool) = Pool'Access; -- This routine requires implementation. Reclaim the storage a particular -- subpool occupies in a pool_with_subpools. This routine is called by -- Ada.Unchecked_Deallocate_Subpool. function Default_Subpool_For_Pool (Pool : Root_Storage_Pool_With_Subpools) return not null Subpool_Handle; -- Return a common subpool which is used for object allocations without a -- Subpool_Handle_name in the allocator. The default implementation of this -- routine raises Program_Error. function Pool_Of_Subpool (Subpool : not null Subpool_Handle) return access Root_Storage_Pool_With_Subpools'Class; -- Return the owner of the subpool procedure Set_Pool_Of_Subpool (Subpool : not null Subpool_Handle; To : in out Root_Storage_Pool_With_Subpools'Class); -- Set the owner of the subpool. This is intended to be called from -- Create_Subpool or similar subpool constructors. Raises Program_Error -- if the subpool already belongs to a pool. overriding function Storage_Size (Pool : Root_Storage_Pool_With_Subpools) return System.Storage_Elements.Storage_Count is (System.Storage_Elements.Storage_Count'Last); private -- Model -- Pool_With_Subpools SP_Node SP_Node SP_Node -- +-->+--------------------+ +-----+ +-----+ +-----+ -- | | Subpools -------->| ------->| ------->| -------> -- | +--------------------+ +-----+ +-----+ +-----+ -- | |Finalization_Started|<------ |<------- |<------- |<--- -- | +--------------------+ +-----+ +-----+ +-----+ -- +--- Controller.Encl_Pool| | nul | | + | | + | -- | +--------------------+ +-----+ +--|--+ +--:--+ -- | : : Dummy | ^ : -- | : : | | : -- | Root_Subpool V | -- | +-------------+ | -- +-------------------------------- Owner | | -- FM_Node FM_Node +-------------+ | -- +-----+ +-----+<-- Master.Objects| | -- <------ |<------ | +-------------+ | -- +-----+ +-----+ | Node -------+ -- | ------>| -----> +-------------+ -- +-----+ +-----+ : : -- |ctrl | Dummy : : -- | obj | -- +-----+ -- -- SP_Nodes are created on the heap. FM_Nodes and associated objects are -- created on the pool_with_subpools. type Any_Storage_Pool_With_Subpools_Ptr is access all Root_Storage_Pool_With_Subpools'Class; for Any_Storage_Pool_With_Subpools_Ptr'Storage_Size use 0; -- A pool controller is a special controlled object which ensures the -- proper initialization and finalization of the enclosing pool. type Pool_Controller (Enclosing_Pool : Any_Storage_Pool_With_Subpools_Ptr) is new Ada.Finalization.Limited_Controlled with null record; -- Subpool list types. Each pool_with_subpools contains a list of subpools. -- This is an indirect doubly linked list since subpools are not supposed -- to be allocatable by language design. type SP_Node; type SP_Node_Ptr is access all SP_Node; type SP_Node is record Prev : SP_Node_Ptr := null; Next : SP_Node_Ptr := null; Subpool : Subpool_Handle := null; end record; -- Root_Storage_Pool_With_Subpools internal structure. The type uses a -- special controller to perform initialization and finalization actions -- on itself. This is necessary because the end user of this package may -- decide to override Initialize and Finalize, thus disabling the desired -- behavior. -- Pool_With_Subpools SP_Node SP_Node SP_Node -- +-->+--------------------+ +-----+ +-----+ +-----+ -- | | Subpools -------->| ------->| ------->| -------> -- | +--------------------+ +-----+ +-----+ +-----+ -- | |Finalization_Started| : : : : : : -- | +--------------------+ -- +--- Controller.Encl_Pool| -- +--------------------+ -- : End-user : -- : components : type Root_Storage_Pool_With_Subpools is abstract new Root_Storage_Pool with record Subpools : aliased SP_Node; -- A doubly linked list of subpools Finalization_Started : Boolean := False; pragma Atomic (Finalization_Started); -- A flag which prevents the creation of new subpools while the master -- pool is being finalized. The flag needs to be atomic because it is -- accessed without Lock_Task / Unlock_Task. Controller : Pool_Controller (Root_Storage_Pool_With_Subpools'Unchecked_Access); -- A component which ensures that the enclosing pool is initialized and -- finalized at the appropriate places. end record; -- A subpool is an abstraction layer which sits on top of a pool. It -- contains links to all controlled objects allocated on a particular -- subpool. -- Pool_With_Subpools SP_Node SP_Node SP_Node -- +-->+----------------+ +-----+ +-----+ +-----+ -- | | Subpools ------>| ------->| ------->| -------> -- | +----------------+ +-----+ +-----+ +-----+ -- | : :<------ |<------- |<------- | -- | : : +-----+ +-----+ +-----+ -- | |null | | + | | + | -- | +-----+ +--|--+ +--:--+ -- | | ^ : -- | Root_Subpool V | -- | +-------------+ | -- +---------------------------- Owner | | -- +-------------+ | -- .......... Master | | -- +-------------+ | -- | Node -------+ -- +-------------+ -- : End-user : -- : components : type Root_Subpool is abstract tagged limited record Owner : Any_Storage_Pool_With_Subpools_Ptr := null; -- A reference to the master pool_with_subpools Master : aliased System.Finalization_Masters.Finalization_Master; -- A heterogeneous collection of controlled objects Node : SP_Node_Ptr := null; -- A link to the doubly linked list node which contains the subpool. -- This back pointer is used in subpool deallocation. end record; procedure Adjust_Controlled_Dereference (Addr : in out System.Address; Storage_Size : in out System.Storage_Elements.Storage_Count; Alignment : System.Storage_Elements.Storage_Count); -- Given the memory attributes of a heap-allocated object that is known to -- be controlled, adjust the address and size of the object to include the -- two hidden pointers inserted by the finalization machinery. -- ??? Once Storage_Pools.Allocate_Any is removed, this should be renamed -- to Allocate_Any. procedure Allocate_Any_Controlled (Pool : in out Root_Storage_Pool'Class; Context_Subpool : Subpool_Handle; Context_Master : Finalization_Masters.Finalization_Master_Ptr; Fin_Address : Finalization_Masters.Finalize_Address_Ptr; Addr : out System.Address; Storage_Size : System.Storage_Elements.Storage_Count; Alignment : System.Storage_Elements.Storage_Count; Is_Controlled : Boolean; On_Subpool : Boolean); -- Compiler interface. This version of Allocate handles all possible cases, -- either on a pool or a pool_with_subpools, regardless of the controlled -- status of the allocated object. Parameter usage: -- -- * Pool - The pool associated with the access type. Pool can be any -- derivation from Root_Storage_Pool, including a pool_with_subpools. -- -- * Context_Subpool - The subpool handle name of an allocator. If no -- subpool handle is present at the point of allocation, the actual -- would be null. -- -- * Context_Master - The finalization master associated with the access -- type. If the access type's designated type is not controlled, the -- actual would be null. -- -- * Fin_Address - TSS routine Finalize_Address of the designated type. -- If the designated type is not controlled, the actual would be null. -- -- * Addr - The address of the allocated object. -- -- * Storage_Size - The size of the allocated object. -- -- * Alignment - The alignment of the allocated object. -- -- * Is_Controlled - A flag which determines whether the allocated object -- is controlled. When set to True, the machinery generates additional -- data. -- -- * On_Subpool - A flag which determines whether the a subpool handle -- name is present at the point of allocation. This is used for error -- diagnostics. procedure Deallocate_Any_Controlled (Pool : in out Root_Storage_Pool'Class; Addr : System.Address; Storage_Size : System.Storage_Elements.Storage_Count; Alignment : System.Storage_Elements.Storage_Count; Is_Controlled : Boolean); -- Compiler interface. This version of Deallocate handles all possible -- cases, either from a pool or a pool_with_subpools, regardless of the -- controlled status of the deallocated object. Parameter usage: -- -- * Pool - The pool associated with the access type. Pool can be any -- derivation from Root_Storage_Pool, including a pool_with_subpools. -- -- * Addr - The address of the allocated object. -- -- * Storage_Size - The size of the allocated object. -- -- * Alignment - The alignment of the allocated object. -- -- * Is_Controlled - A flag which determines whether the allocated object -- is controlled. When set to True, the machinery generates additional -- data. overriding procedure Finalize (Controller : in out Pool_Controller); -- Buffer routine, calls Finalize_Pool procedure Finalize_Pool (Pool : in out Root_Storage_Pool_With_Subpools); -- Iterate over all subpools of Pool, detach them one by one and finalize -- their masters. This action first detaches a controlled object from a -- particular master, then invokes its Finalize_Address primitive. procedure Finalize_Subpool (Subpool : not null Subpool_Handle); -- Finalize all controlled objects chained on Subpool's master. Remove the -- subpool from its owner's list. Deallocate the associated doubly linked -- list node. function Header_Size_With_Padding (Alignment : System.Storage_Elements.Storage_Count) return System.Storage_Elements.Storage_Count; -- Given an arbitrary alignment, calculate the size of the header which -- precedes a controlled object as the nearest multiple rounded up of the -- alignment. overriding procedure Initialize (Controller : in out Pool_Controller); -- Buffer routine, calls Initialize_Pool procedure Initialize_Pool (Pool : in out Root_Storage_Pool_With_Subpools); -- Setup the doubly linked list of subpools procedure Print_Pool (Pool : Root_Storage_Pool_With_Subpools); -- Debug routine, output the contents of a pool_with_subpools procedure Print_Subpool (Subpool : Subpool_Handle); -- Debug routine, output the contents of a subpool end System.Storage_Pools.Subpools;
pragma License (Unrestricted); -- implementation unit specialized for POSIX (Darwin, FreeBSD, or Linux) package System.Native_Command_Line is pragma Preelaborate; function Argument_Count return Natural; pragma Pure_Function (Argument_Count); pragma Inline (Argument_Count); function Argument (Number : Natural) return String; -- Returns Command_Name if Number = 0. end System.Native_Command_Line;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- S E M _ C H 1 1 -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2020, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING3. If not, go to -- -- http://www.gnu.org/licenses for a complete copy of the license. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Atree; use Atree; with Checks; use Checks; with Einfo; use Einfo; with Errout; use Errout; with Lib; use Lib; with Lib.Xref; use Lib.Xref; with Namet; use Namet; with Nlists; use Nlists; with Nmake; use Nmake; with Opt; use Opt; with Restrict; use Restrict; with Rident; use Rident; with Rtsfind; use Rtsfind; with Sem; use Sem; with Sem_Aux; use Sem_Aux; with Sem_Ch5; use Sem_Ch5; with Sem_Ch8; use Sem_Ch8; with Sem_Ch13; use Sem_Ch13; with Sem_Res; use Sem_Res; with Sem_Util; use Sem_Util; with Sem_Warn; use Sem_Warn; with Sinfo; use Sinfo; with Snames; use Snames; with Stand; use Stand; package body Sem_Ch11 is ----------------------------------- -- Analyze_Exception_Declaration -- ----------------------------------- procedure Analyze_Exception_Declaration (N : Node_Id) is Id : constant Entity_Id := Defining_Identifier (N); PF : constant Boolean := Is_Pure (Current_Scope); begin Generate_Definition (Id); Enter_Name (Id); Set_Ekind (Id, E_Exception); Set_Etype (Id, Standard_Exception_Type); Set_Is_Statically_Allocated (Id); Set_Is_Pure (Id, PF); if Has_Aspects (N) then Analyze_Aspect_Specifications (N, Id); end if; end Analyze_Exception_Declaration; -------------------------------- -- Analyze_Exception_Handlers -- -------------------------------- procedure Analyze_Exception_Handlers (L : List_Id) is Handler : Node_Id; Choice : Entity_Id; Id : Node_Id; H_Scope : Entity_Id := Empty; procedure Check_Duplication (Id : Node_Id); -- Iterate through the identifiers in each handler to find duplicates function Others_Present return Boolean; -- Returns True if others handler is present ----------------------- -- Check_Duplication -- ----------------------- procedure Check_Duplication (Id : Node_Id) is Handler : Node_Id; Id1 : Node_Id; Id_Entity : Entity_Id := Entity (Id); begin if Present (Renamed_Entity (Id_Entity)) then Id_Entity := Renamed_Entity (Id_Entity); end if; Handler := First_Non_Pragma (L); while Present (Handler) loop Id1 := First (Exception_Choices (Handler)); while Present (Id1) loop -- Only check against the exception choices which precede -- Id in the handler, since the ones that follow Id have not -- been analyzed yet and will be checked in a subsequent call. if Id = Id1 then return; elsif Nkind (Id1) /= N_Others_Choice and then (Id_Entity = Entity (Id1) or else (Id_Entity = Renamed_Entity (Entity (Id1)))) then if Handler /= Parent (Id) then Error_Msg_Sloc := Sloc (Id1); Error_Msg_NE ("exception choice duplicates &#", Id, Id1); else if Ada_Version = Ada_83 and then Comes_From_Source (Id) then Error_Msg_N ("(Ada 83): duplicate exception choice&", Id); end if; end if; end if; Next_Non_Pragma (Id1); end loop; Next (Handler); end loop; end Check_Duplication; -------------------- -- Others_Present -- -------------------- function Others_Present return Boolean is H : Node_Id; begin H := First (L); while Present (H) loop if Nkind (H) /= N_Pragma and then Nkind (First (Exception_Choices (H))) = N_Others_Choice then return True; end if; Next (H); end loop; return False; end Others_Present; -- Start of processing for Analyze_Exception_Handlers begin Handler := First (L); -- Pragma Restriction_Warnings has more related semantics than pragma -- Restrictions in that it flags exception handlers as violators. Note -- that the compiler must still generate handlers for certain critical -- scenarios such as finalization. As a result, these handlers should -- not be subjected to the restriction check when in warnings mode. if not Comes_From_Source (Handler) and then (Restriction_Warnings (No_Exception_Handlers) or else Restriction_Warnings (No_Exception_Propagation) or else Restriction_Warnings (No_Exceptions)) then null; else Check_Restriction (No_Exceptions, Handler); Check_Restriction (No_Exception_Handlers, Handler); end if; -- Kill current remembered values, since we don't know where we were -- when the exception was raised. Kill_Current_Values; -- Loop through handlers (which can include pragmas) while Present (Handler) loop -- If pragma just analyze it if Nkind (Handler) = N_Pragma then Analyze (Handler); -- Otherwise we have a real exception handler else -- Deal with choice parameter. The exception handler is a -- declarative part for the choice parameter, so it constitutes a -- scope for visibility purposes. We create an entity to denote -- the whole exception part, and use it as the scope of all the -- choices, which may even have the same name without conflict. -- This scope plays no other role in expansion or code generation. Choice := Choice_Parameter (Handler); if Present (Choice) then Set_Local_Raise_Not_OK (Handler); if Comes_From_Source (Choice) then Check_Restriction (No_Exception_Propagation, Choice); Set_Debug_Info_Needed (Choice); end if; if No (H_Scope) then H_Scope := New_Internal_Entity (E_Block, Current_Scope, Sloc (Choice), 'E'); Set_Is_Exception_Handler (H_Scope); end if; Push_Scope (H_Scope); Set_Etype (H_Scope, Standard_Void_Type); Enter_Name (Choice); Set_Ekind (Choice, E_Variable); if RTE_Available (RE_Exception_Occurrence) then Set_Etype (Choice, RTE (RE_Exception_Occurrence)); end if; Generate_Definition (Choice); -- Indicate that choice has an initial value, since in effect -- this field is assigned an initial value by the exception. -- We also consider that it is modified in the source. Set_Has_Initial_Value (Choice, True); Set_Never_Set_In_Source (Choice, False); end if; Id := First (Exception_Choices (Handler)); while Present (Id) loop if Nkind (Id) = N_Others_Choice then if Present (Next (Id)) or else Present (Next (Handler)) or else Present (Prev (Id)) then Error_Msg_N ("OTHERS must appear alone and last", Id); end if; else Analyze (Id); -- In most cases the choice has already been analyzed in -- Analyze_Handled_Statement_Sequence, in order to expand -- local handlers. This advance analysis does not take into -- account the case in which a choice has the same name as -- the choice parameter of the handler, which may hide an -- outer exception. This pathological case appears in ACATS -- B80001_3.adb, and requires an explicit check to verify -- that the id is not hidden. if not Is_Entity_Name (Id) or else Ekind (Entity (Id)) /= E_Exception or else (Nkind (Id) = N_Identifier and then Chars (Id) = Chars (Choice)) then Error_Msg_N ("exception name expected", Id); else -- Emit a warning at the declaration level when a local -- exception is never raised explicitly. if Warn_On_Redundant_Constructs and then not Is_Raised (Entity (Id)) and then Scope (Entity (Id)) = Current_Scope then Error_Msg_NE ("exception & is never raised?r?", Entity (Id), Id); end if; if Present (Renamed_Entity (Entity (Id))) then if Entity (Id) = Standard_Numeric_Error then Check_Restriction (No_Obsolescent_Features, Id); if Warn_On_Obsolescent_Feature then Error_Msg_N ("Numeric_Error is an " & "obsolescent feature (RM J.6(1))?j?", Id); Error_Msg_N ("\use Constraint_Error instead?j?", Id); end if; end if; end if; Check_Duplication (Id); -- Check for exception declared within generic formal -- package (which is illegal, see RM 11.2(8)) declare Ent : Entity_Id := Entity (Id); Scop : Entity_Id; begin if Present (Renamed_Entity (Ent)) then Ent := Renamed_Entity (Ent); end if; Scop := Scope (Ent); while Scop /= Standard_Standard and then Ekind (Scop) = E_Package loop if Nkind (Declaration_Node (Scop)) = N_Package_Specification and then Nkind (Original_Node (Parent (Declaration_Node (Scop)))) = N_Formal_Package_Declaration then Error_Msg_NE ("exception& is declared in generic formal " & "package", Id, Ent); Error_Msg_N ("\and therefore cannot appear in handler " & "(RM 11.2(8))", Id); exit; -- If the exception is declared in an inner -- instance, nothing else to check. elsif Is_Generic_Instance (Scop) then exit; end if; Scop := Scope (Scop); end loop; end; end if; end if; Next (Id); end loop; -- Check for redundant handler (has only raise statement) and is -- either an others handler, or is a specific handler when no -- others handler is present. if Warn_On_Redundant_Constructs and then List_Length (Statements (Handler)) = 1 and then Nkind (First (Statements (Handler))) = N_Raise_Statement and then No (Name (First (Statements (Handler)))) and then (not Others_Present or else Nkind (First (Exception_Choices (Handler))) = N_Others_Choice) then Error_Msg_N ("useless handler contains only a reraise statement?r?", Handler); end if; -- Now analyze the statements of this handler Analyze_Statements (Statements (Handler)); -- If a choice was present, we created a special scope for it, so -- this is where we pop that special scope to get rid of it. if Present (Choice) then End_Scope; end if; end if; Next (Handler); end loop; end Analyze_Exception_Handlers; -------------------------------- -- Analyze_Handled_Statements -- -------------------------------- procedure Analyze_Handled_Statements (N : Node_Id) is Handlers : constant List_Id := Exception_Handlers (N); Handler : Node_Id; Choice : Node_Id; begin if Present (Handlers) then Kill_All_Checks; end if; -- We are now going to analyze the statements and then the exception -- handlers. We certainly need to do things in this order to get the -- proper sequential semantics for various warnings. -- However, there is a glitch. When we process raise statements, an -- optimization is to look for local handlers and specialize the code -- in this case. -- In order to detect if a handler is matching, we must have at least -- analyzed the choices in the proper scope so that proper visibility -- analysis is performed. Hence we analyze just the choices first, -- before we analyze the statement sequence. Handler := First_Non_Pragma (Handlers); while Present (Handler) loop Choice := First_Non_Pragma (Exception_Choices (Handler)); while Present (Choice) loop Analyze (Choice); Next_Non_Pragma (Choice); end loop; Next_Non_Pragma (Handler); end loop; -- Analyze statements in sequence Analyze_Statements (Statements (N)); -- If the current scope is a subprogram, entry or task body or declare -- block then this is the right place to check for hanging useless -- assignments from the statement sequence. Skip this in the body of a -- postcondition, since in that case there are no source references, and -- we need to preserve deferred references from the enclosing scope. if ((Is_Subprogram (Current_Scope) or else Is_Entry (Current_Scope)) and then Chars (Current_Scope) /= Name_uPostconditions) or else Ekind (Current_Scope) in E_Block | E_Task_Type then Warn_On_Useless_Assignments (Current_Scope); end if; -- Deal with handlers or AT END proc if Present (Handlers) then Analyze_Exception_Handlers (Handlers); elsif Present (At_End_Proc (N)) then Analyze (At_End_Proc (N)); end if; end Analyze_Handled_Statements; ------------------------------ -- Analyze_Raise_Expression -- ------------------------------ procedure Analyze_Raise_Expression (N : Node_Id) is Exception_Id : constant Node_Id := Name (N); Exception_Name : Entity_Id := Empty; begin if Comes_From_Source (N) then Check_Compiler_Unit ("raise expression", N); end if; -- Check exception restrictions on the original source if Comes_From_Source (N) then Check_Restriction (No_Exceptions, N); end if; Analyze (Exception_Id); if Is_Entity_Name (Exception_Id) then Exception_Name := Entity (Exception_Id); end if; if No (Exception_Name) or else Ekind (Exception_Name) /= E_Exception then Error_Msg_N ("exception name expected in raise statement", Exception_Id); else Set_Is_Raised (Exception_Name); end if; -- Deal with RAISE WITH case if Present (Expression (N)) then Analyze_And_Resolve (Expression (N), Standard_String); end if; -- Check obsolescent use of Numeric_Error if Exception_Name = Standard_Numeric_Error then Check_Restriction (No_Obsolescent_Features, Exception_Id); end if; -- Kill last assignment indication Kill_Current_Values (Last_Assignment_Only => True); -- Raise_Type is compatible with all other types so that the raise -- expression is legal in any expression context. It will be eventually -- replaced by the concrete type imposed by the context. Set_Etype (N, Raise_Type); end Analyze_Raise_Expression; ----------------------------- -- Analyze_Raise_Statement -- ----------------------------- procedure Analyze_Raise_Statement (N : Node_Id) is Exception_Id : constant Node_Id := Name (N); Exception_Name : Entity_Id := Empty; P : Node_Id; Par : Node_Id; begin Check_Unreachable_Code (N); -- Check exception restrictions on the original source if Comes_From_Source (N) then Check_Restriction (No_Exceptions, N); end if; -- Check for useless assignment to OUT or IN OUT scalar preceding the -- raise. Right now only look at assignment statements, could do more??? if Is_List_Member (N) then declare P : Node_Id; L : Node_Id; begin P := Prev (N); -- Skip past null statements and pragmas while Present (P) and then Nkind (P) in N_Null_Statement | N_Pragma loop P := Prev (P); end loop; -- See if preceding statement is an assignment if Present (P) and then Nkind (P) = N_Assignment_Statement then L := Name (P); -- Give warning for assignment to scalar formal if Is_Scalar_Type (Etype (L)) and then Is_Entity_Name (L) and then Is_Formal (Entity (L)) -- Do this only for parameters to the current subprogram. -- This avoids some false positives for the nested case. and then Nearest_Dynamic_Scope (Current_Scope) = Scope (Entity (L)) then -- Don't give warning if we are covered by an exception -- handler, since this may result in false positives, since -- the handler may handle the exception and return normally. -- First find the enclosing handled sequence of statements -- (note, we could also look for a handler in an outer block -- but currently we don't, and in that case we'll emit the -- warning). Par := N; loop Par := Parent (Par); exit when Nkind (Par) = N_Handled_Sequence_Of_Statements; end loop; -- See if there is a handler, give message if not if No (Exception_Handlers (Par)) then Error_Msg_N ("assignment to pass-by-copy formal " & "may have no effect??", P); Error_Msg_N ("\RAISE statement may result in abnormal return " & "(RM 6.4.1(17))??", P); end if; end if; end if; end; end if; -- Reraise statement if No (Exception_Id) then P := Parent (N); while Nkind (P) not in N_Exception_Handler | N_Subprogram_Body | N_Package_Body | N_Task_Body | N_Entry_Body loop P := Parent (P); end loop; if Nkind (P) /= N_Exception_Handler then Error_Msg_N ("reraise statement must appear directly in a handler", N); -- If a handler has a reraise, it cannot be the target of a local -- raise (goto optimization is impossible), and if the no exception -- propagation restriction is set, this is a violation. else Set_Local_Raise_Not_OK (P); -- Do not check the restriction if the reraise statement is part -- of the code generated for an AT-END handler. That's because -- if the restriction is actually active, we never generate this -- raise anyway, so the apparent violation is bogus. if not From_At_End (N) then Check_Restriction (No_Exception_Propagation, N); end if; end if; -- Normal case with exception id present else Analyze (Exception_Id); if Is_Entity_Name (Exception_Id) then Exception_Name := Entity (Exception_Id); end if; if No (Exception_Name) or else Ekind (Exception_Name) /= E_Exception then Error_Msg_N ("exception name expected in raise statement", Exception_Id); else Set_Is_Raised (Exception_Name); end if; -- Deal with RAISE WITH case if Present (Expression (N)) then Analyze_And_Resolve (Expression (N), Standard_String); end if; end if; -- Check obsolescent use of Numeric_Error if Exception_Name = Standard_Numeric_Error then Check_Restriction (No_Obsolescent_Features, Exception_Id); end if; -- Kill last assignment indication Kill_Current_Values (Last_Assignment_Only => True); end Analyze_Raise_Statement; ----------------------------- -- Analyze_Raise_xxx_Error -- ----------------------------- -- Normally, the Etype is already set (when this node is used within -- an expression, since it is copied from the node which it rewrites). -- If this node is used in a statement context, then we set the type -- Standard_Void_Type. This is used both by Gigi and by the front end -- to distinguish the statement use and the subexpression use. -- The only other required processing is to take care of the Condition -- field if one is present. procedure Analyze_Raise_xxx_Error (N : Node_Id) is function Same_Expression (C1, C2 : Node_Id) return Boolean; -- It often occurs that two identical raise statements are generated in -- succession (for example when dynamic elaboration checks take place on -- separate expressions in a call). If the two statements are identical -- according to the simple criterion that follows, the raise is -- converted into a null statement. --------------------- -- Same_Expression -- --------------------- function Same_Expression (C1, C2 : Node_Id) return Boolean is begin if No (C1) and then No (C2) then return True; elsif Is_Entity_Name (C1) and then Is_Entity_Name (C2) then return Entity (C1) = Entity (C2); elsif Nkind (C1) /= Nkind (C2) then return False; elsif Nkind (C1) in N_Unary_Op then return Same_Expression (Right_Opnd (C1), Right_Opnd (C2)); elsif Nkind (C1) in N_Binary_Op then return Same_Expression (Left_Opnd (C1), Left_Opnd (C2)) and then Same_Expression (Right_Opnd (C1), Right_Opnd (C2)); elsif Nkind (C1) = N_Null then return True; else return False; end if; end Same_Expression; -- Start of processing for Analyze_Raise_xxx_Error begin if No (Etype (N)) then Set_Etype (N, Standard_Void_Type); end if; if Present (Condition (N)) then Analyze_And_Resolve (Condition (N), Standard_Boolean); end if; -- Deal with static cases in obvious manner if Nkind (Condition (N)) = N_Identifier then if Entity (Condition (N)) = Standard_True then Set_Condition (N, Empty); elsif Entity (Condition (N)) = Standard_False then Rewrite (N, Make_Null_Statement (Sloc (N))); end if; end if; -- Remove duplicate raise statements. Note that the previous one may -- already have been removed as well. if not Comes_From_Source (N) and then Nkind (N) /= N_Null_Statement and then Is_List_Member (N) and then Present (Prev (N)) and then Nkind (N) = Nkind (Original_Node (Prev (N))) and then Same_Expression (Condition (N), Condition (Original_Node (Prev (N)))) then Rewrite (N, Make_Null_Statement (Sloc (N))); end if; end Analyze_Raise_xxx_Error; end Sem_Ch11;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- A U N I T . T E S T _ R E S U L T S -- -- -- -- S p e c -- -- -- -- -- -- Copyright (C) 2000-2011, AdaCore -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- -- -- -- -- -- -- -- -- 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 is maintained by AdaCore (http://www.adacore.com) -- -- -- ------------------------------------------------------------------------------ with Ada_Containers.AUnit_Lists; with AUnit.Time_Measure; use AUnit.Time_Measure; -- Test reporting. -- package AUnit.Test_Results is type Result is tagged limited private; -- Record result. A result object is associated with the execution of a -- top-level test suite. type Test_Failure is record Message : Message_String; Source_Name : Message_String; Line : Natural; end record; type Test_Failure_Access is access all Test_Failure; pragma No_Strict_Aliasing (Test_Failure_Access); -- Description of a test routine failure type Test_Error is record Exception_Name : Message_String; Exception_Message : Message_String; Traceback : Message_String; end record; type Test_Error_Access is access all Test_Error; pragma No_Strict_Aliasing (Test_Error_Access); -- Description of unexpected exceptions type Test_Result is record Test_Name : Message_String; Routine_Name : Message_String; Failure : Test_Failure_Access; Error : Test_Error_Access; Elapsed : Time := Null_Time; end record; -- Decription of a test routine result use Ada_Containers; package Result_Lists is new Ada_Containers.AUnit_Lists (Test_Result); -- Containers for all test results procedure Add_Error (R : in out Result; Test_Name : Message_String; Routine_Name : Message_String; Error : Test_Error; Elapsed : Time); -- Record an unexpected exception procedure Add_Failure (R : in out Result; Test_Name : Message_String; Routine_Name : Message_String; Failure : Test_Failure; Elapsed : Time); -- Record a test routine failure procedure Add_Success (R : in out Result; Test_Name : Message_String; Routine_Name : Message_String; Elapsed : Time); -- Record a test routine success procedure Set_Elapsed (R : in out Result; T : Time); -- Set Elapsed time for reporter function Error_Count (R : Result) return Count_Type; -- Number of routines with unexpected exceptions procedure Errors (R : in out Result; E : in out Result_Lists.List); -- List of routines with unexpected exceptions. This resets the list. function Failure_Count (R : Result) return Count_Type; -- Number of failed routines procedure Failures (R : in out Result; F : in out Result_Lists.List); -- List of failed routines. This resets the list. function Elapsed (R : Result) return Time; -- Elapsed time for test execution procedure Start_Test (R : in out Result; Subtest_Count : Count_Type); -- Set count for a test run function Success_Count (R : Result) return Count_Type; -- Number of successful routines procedure Successes (R : in out Result; S : in out Result_Lists.List); -- List of successful routines. This resets the list. function Successful (R : Result) return Boolean; -- All routines successful? function Test_Count (R : Result) return Ada_Containers.Count_Type; -- Number of routines run procedure Clear (R : in out Result); -- Clear the results private pragma Inline (Errors, Failures, Successes); type Result is tagged limited record Tests_Run : Count_Type := 0; Result_List : Result_Lists.List; Elapsed_Time : Time := Null_Time; end record; end AUnit.Test_Results;
------------------------------------------------------------------------------ -- -- -- GNAT RUNTIME COMPONENTS -- -- -- -- S Y S T E M . S T R E A M _ A T T R I B U T E S -- -- -- -- B o d y -- -- -- -- $Revision$ -- -- -- Copyright (C) 1992-1998, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, -- -- MA 02111-1307, USA. -- -- -- -- As a special exception, if other files instantiate generics from this -- -- unit, or you link this unit with other files to produce an executable, -- -- this unit does not by itself cause the resulting executable to be -- -- covered by the GNU General Public License. This exception does not -- -- however invalidate any other reasons why the executable file might be -- -- covered by the GNU Public License. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Ada.IO_Exceptions; with Ada.Streams; use Ada.Streams; with Unchecked_Conversion; package body System.Stream_Attributes is Err : exception renames Ada.IO_Exceptions.End_Error; -- Exception raised if insufficient data read (note that the RM implies -- that Data_Error might be the appropriate choice, but AI195-00132 -- decides with a binding interpretation that End_Error is preferred). SU : constant := System.Storage_Unit; subtype SEA is Ada.Streams.Stream_Element_Array; subtype SEO is Ada.Streams.Stream_Element_Offset; generic function UC renames Unchecked_Conversion; -- Subtypes used to define Stream_Element_Array values that map -- into the elementary types, using unchecked conversion. Thin_Pointer_Size : constant := System.Address'Size; Fat_Pointer_Size : constant := System.Address'Size * 2; subtype S_AD is SEA (1 .. (Fat_Pointer_Size + SU - 1) / SU); subtype S_AS is SEA (1 .. (Thin_Pointer_Size + SU - 1) / SU); subtype S_B is SEA (1 .. (Boolean'Size + SU - 1) / SU); subtype S_C is SEA (1 .. (Character'Size + SU - 1) / SU); subtype S_F is SEA (1 .. (Float'Size + SU - 1) / SU); subtype S_I is SEA (1 .. (Integer'Size + SU - 1) / SU); subtype S_LF is SEA (1 .. (Long_Float'Size + SU - 1) / SU); subtype S_LI is SEA (1 .. (Long_Integer'Size + SU - 1) / SU); subtype S_LLF is SEA (1 .. (Long_Long_Float'Size + SU - 1) / SU); subtype S_LLI is SEA (1 .. (Long_Long_Integer'Size + SU - 1) / SU); subtype S_LLU is SEA (1 .. (UST.Long_Long_Unsigned'Size + SU - 1) / SU); subtype S_LU is SEA (1 .. (UST.Long_Unsigned'Size + SU - 1) / SU); subtype S_SF is SEA (1 .. (Short_Float'Size + SU - 1) / SU); subtype S_SI is SEA (1 .. (Short_Integer'Size + SU - 1) / SU); subtype S_SSI is SEA (1 .. (Short_Short_Integer'Size + SU - 1) / SU); subtype S_SSU is SEA (1 .. (UST.Short_Short_Unsigned'Size + SU - 1) / SU); subtype S_SU is SEA (1 .. (UST.Short_Unsigned'Size + SU - 1) / SU); subtype S_U is SEA (1 .. (UST.Unsigned'Size + SU - 1) / SU); subtype S_WC is SEA (1 .. (Wide_Character'Size + SU - 1) / SU); -- Unchecked conversions from the elementary type to the stream type function From_AD is new UC (Fat_Pointer, S_AD); function From_AS is new UC (Thin_Pointer, S_AS); function From_C is new UC (Character, S_C); function From_F is new UC (Float, S_F); function From_I is new UC (Integer, S_I); function From_LF is new UC (Long_Float, S_LF); function From_LI is new UC (Long_Integer, S_LI); function From_LLF is new UC (Long_Long_Float, S_LLF); function From_LLI is new UC (Long_Long_Integer, S_LLI); function From_LLU is new UC (UST.Long_Long_Unsigned, S_LLU); function From_LU is new UC (UST.Long_Unsigned, S_LU); function From_SF is new UC (Short_Float, S_SF); function From_SI is new UC (Short_Integer, S_SI); function From_SSI is new UC (Short_Short_Integer, S_SSI); function From_SSU is new UC (UST.Short_Short_Unsigned, S_SSU); function From_SU is new UC (UST.Short_Unsigned, S_SU); function From_U is new UC (UST.Unsigned, S_U); function From_WC is new UC (Wide_Character, S_WC); -- Unchecked conversions from the stream type to elementary type function To_AD is new UC (S_AD, Fat_Pointer); function To_AS is new UC (S_AS, Thin_Pointer); function To_C is new UC (S_C, Character); function To_F is new UC (S_F, Float); function To_I is new UC (S_I, Integer); function To_LF is new UC (S_LF, Long_Float); function To_LI is new UC (S_LI, Long_Integer); function To_LLF is new UC (S_LLF, Long_Long_Float); function To_LLI is new UC (S_LLI, Long_Long_Integer); function To_LLU is new UC (S_LLU, UST.Long_Long_Unsigned); function To_LU is new UC (S_LU, UST.Long_Unsigned); function To_SF is new UC (S_SF, Short_Float); function To_SI is new UC (S_SI, Short_Integer); function To_SSI is new UC (S_SSI, Short_Short_Integer); function To_SSU is new UC (S_SSU, UST.Short_Short_Unsigned); function To_SU is new UC (S_SU, UST.Short_Unsigned); function To_U is new UC (S_U, UST.Unsigned); function To_WC is new UC (S_WC, Wide_Character); ---------- -- I_AD -- ---------- function I_AD (Stream : access RST) return Fat_Pointer is T : S_AD; L : SEO; begin Ada.Streams.Read (Stream.all, T, L); if L < T'Last then raise Err; else return To_AD (T); end if; end I_AD; ---------- -- I_AS -- ---------- function I_AS (Stream : access RST) return Thin_Pointer is T : S_AS; L : SEO; begin Ada.Streams.Read (Stream.all, T, L); if L < T'Last then raise Err; else return To_AS (T); end if; end I_AS; --------- -- I_B -- --------- function I_B (Stream : access RST) return Boolean is T : S_B; L : SEO; begin Ada.Streams.Read (Stream.all, T, L); if L < T'Last then raise Err; else return Boolean'Val (T (1)); end if; end I_B; --------- -- I_C -- --------- function I_C (Stream : access RST) return Character is T : S_C; L : SEO; begin Ada.Streams.Read (Stream.all, T, L); if L < T'Last then raise Err; else return To_C (T); end if; end I_C; --------- -- I_F -- --------- function I_F (Stream : access RST) return Float is T : S_F; L : SEO; begin Ada.Streams.Read (Stream.all, T, L); if L < T'Last then raise Err; else return To_F (T); end if; end I_F; --------- -- I_I -- --------- function I_I (Stream : access RST) return Integer is T : S_I; L : SEO; begin Ada.Streams.Read (Stream.all, T, L); if L < T'Last then raise Err; else return To_I (T); end if; end I_I; ---------- -- I_LF -- ---------- function I_LF (Stream : access RST) return Long_Float is T : S_LF; L : SEO; begin Ada.Streams.Read (Stream.all, T, L); if L < T'Last then raise Err; else return To_LF (T); end if; end I_LF; ---------- -- I_LI -- ---------- function I_LI (Stream : access RST) return Long_Integer is T : S_LI; L : SEO; begin Ada.Streams.Read (Stream.all, T, L); if L < T'Last then raise Err; else return To_LI (T); end if; end I_LI; ----------- -- I_LLF -- ----------- function I_LLF (Stream : access RST) return Long_Long_Float is T : S_LLF; L : SEO; begin Ada.Streams.Read (Stream.all, T, L); if L < T'Last then raise Err; else return To_LLF (T); end if; end I_LLF; ----------- -- I_LLI -- ----------- function I_LLI (Stream : access RST) return Long_Long_Integer is T : S_LLI; L : SEO; begin Ada.Streams.Read (Stream.all, T, L); if L < T'Last then raise Err; else return To_LLI (T); end if; end I_LLI; ----------- -- I_LLU -- ----------- function I_LLU (Stream : access RST) return UST.Long_Long_Unsigned is T : S_LLU; L : SEO; begin Ada.Streams.Read (Stream.all, T, L); if L < T'Last then raise Err; else return To_LLU (T); end if; end I_LLU; ---------- -- I_LU -- ---------- function I_LU (Stream : access RST) return UST.Long_Unsigned is T : S_LU; L : SEO; begin Ada.Streams.Read (Stream.all, T, L); if L < T'Last then raise Err; else return To_LU (T); end if; end I_LU; ---------- -- I_SF -- ---------- function I_SF (Stream : access RST) return Short_Float is T : S_SF; L : SEO; begin Ada.Streams.Read (Stream.all, T, L); if L < T'Last then raise Err; else return To_SF (T); end if; end I_SF; ---------- -- I_SI -- ---------- function I_SI (Stream : access RST) return Short_Integer is T : S_SI; L : SEO; begin Ada.Streams.Read (Stream.all, T, L); if L < T'Last then raise Err; else return To_SI (T); end if; end I_SI; ----------- -- I_SSI -- ----------- function I_SSI (Stream : access RST) return Short_Short_Integer is T : S_SSI; L : SEO; begin Ada.Streams.Read (Stream.all, T, L); if L < T'Last then raise Err; else return To_SSI (T); end if; end I_SSI; ----------- -- I_SSU -- ----------- function I_SSU (Stream : access RST) return UST.Short_Short_Unsigned is T : S_SSU; L : SEO; begin Ada.Streams.Read (Stream.all, T, L); if L < T'Last then raise Err; else return To_SSU (T); end if; end I_SSU; ---------- -- I_SU -- ---------- function I_SU (Stream : access RST) return UST.Short_Unsigned is T : S_SU; L : SEO; begin Ada.Streams.Read (Stream.all, T, L); if L < T'Last then raise Err; else return To_SU (T); end if; end I_SU; --------- -- I_U -- --------- function I_U (Stream : access RST) return UST.Unsigned is T : S_U; L : SEO; begin Ada.Streams.Read (Stream.all, T, L); if L < T'Last then raise Err; else return To_U (T); end if; end I_U; ---------- -- I_WC -- ---------- function I_WC (Stream : access RST) return Wide_Character is T : S_WC; L : SEO; begin Ada.Streams.Read (Stream.all, T, L); if L < T'Last then raise Err; else return To_WC (T); end if; end I_WC; ---------- -- W_AD -- ---------- procedure W_AD (Stream : access RST; Item : in Fat_Pointer) is T : constant S_AD := From_AD (Item); begin Ada.Streams.Write (Stream.all, T); end W_AD; ---------- -- W_AS -- ---------- procedure W_AS (Stream : access RST; Item : in Thin_Pointer) is T : constant S_AS := From_AS (Item); begin Ada.Streams.Write (Stream.all, T); end W_AS; --------- -- W_B -- --------- procedure W_B (Stream : access RST; Item : in Boolean) is T : S_B; begin T (1) := Boolean'Pos (Item); Ada.Streams.Write (Stream.all, T); end W_B; --------- -- W_C -- --------- procedure W_C (Stream : access RST; Item : in Character) is T : constant S_C := From_C (Item); begin Ada.Streams.Write (Stream.all, T); end W_C; --------- -- W_F -- --------- procedure W_F (Stream : access RST; Item : in Float) is T : constant S_F := From_F (Item); begin Ada.Streams.Write (Stream.all, T); end W_F; --------- -- W_I -- --------- procedure W_I (Stream : access RST; Item : in Integer) is T : constant S_I := From_I (Item); begin Ada.Streams.Write (Stream.all, T); end W_I; ---------- -- W_LF -- ---------- procedure W_LF (Stream : access RST; Item : in Long_Float) is T : constant S_LF := From_LF (Item); begin Ada.Streams.Write (Stream.all, T); end W_LF; ---------- -- W_LI -- ---------- procedure W_LI (Stream : access RST; Item : in Long_Integer) is T : constant S_LI := From_LI (Item); begin Ada.Streams.Write (Stream.all, T); end W_LI; ----------- -- W_LLF -- ----------- procedure W_LLF (Stream : access RST; Item : in Long_Long_Float) is T : constant S_LLF := From_LLF (Item); begin Ada.Streams.Write (Stream.all, T); end W_LLF; ----------- -- W_LLI -- ----------- procedure W_LLI (Stream : access RST; Item : in Long_Long_Integer) is T : constant S_LLI := From_LLI (Item); begin Ada.Streams.Write (Stream.all, T); end W_LLI; ----------- -- W_LLU -- ----------- procedure W_LLU (Stream : access RST; Item : in UST.Long_Long_Unsigned) is T : constant S_LLU := From_LLU (Item); begin Ada.Streams.Write (Stream.all, T); end W_LLU; ---------- -- W_LU -- ---------- procedure W_LU (Stream : access RST; Item : in UST.Long_Unsigned) is T : constant S_LU := From_LU (Item); begin Ada.Streams.Write (Stream.all, T); end W_LU; ---------- -- W_SF -- ---------- procedure W_SF (Stream : access RST; Item : in Short_Float) is T : constant S_SF := From_SF (Item); begin Ada.Streams.Write (Stream.all, T); end W_SF; ---------- -- W_SI -- ---------- procedure W_SI (Stream : access RST; Item : in Short_Integer) is T : constant S_SI := From_SI (Item); begin Ada.Streams.Write (Stream.all, T); end W_SI; ----------- -- W_SSI -- ----------- procedure W_SSI (Stream : access RST; Item : in Short_Short_Integer) is T : constant S_SSI := From_SSI (Item); begin Ada.Streams.Write (Stream.all, T); end W_SSI; ----------- -- W_SSU -- ----------- procedure W_SSU (Stream : access RST; Item : in UST.Short_Short_Unsigned) is T : constant S_SSU := From_SSU (Item); begin Ada.Streams.Write (Stream.all, T); end W_SSU; ---------- -- W_SU -- ---------- procedure W_SU (Stream : access RST; Item : in UST.Short_Unsigned) is T : constant S_SU := From_SU (Item); begin Ada.Streams.Write (Stream.all, T); end W_SU; --------- -- W_U -- --------- procedure W_U (Stream : access RST; Item : in UST.Unsigned) is T : constant S_U := From_U (Item); begin Ada.Streams.Write (Stream.all, T); end W_U; ---------- -- W_WC -- ---------- procedure W_WC (Stream : access RST; Item : in Wide_Character) is T : constant S_WC := From_WC (Item); begin Ada.Streams.Write (Stream.all, T); end W_WC; end System.Stream_Attributes;
with GNATCOLL.Mmap; generic Separator_Sequence : in String; package Linereader is use GNATCOLL.Mmap; End_Of_Input_Exception : Exception; type Reader (Str : Str_Access; Len : Natural) is tagged private; -- Read a line of text function Get_Line (Self : in out Reader) return String; -- Has the last call to Get_Line or Get_Ramainder reached the end? function End_Of_Input (Self : Reader) return Boolean; -- Backup current position procedure Backup (Self : in out Reader); -- Restore backed up position procedure Restore (Self : in out Reader); -- Get remainder: position .. last function Get_Remainder (Self : in out Reader) return String; private type Reader( Str : Str_Access; Len : Natural) is tagged record Source : Str_Access := Str; Backup : Positive := 1; Position : Positive := 1; Last : Natural := Len; End_Of_Input : Boolean := false; end record; end Linereader;
-- part of OpenGLAda, (c) 2017 Felix Krause -- released under the terms of the MIT license, see the file "COPYING" with Ada.Command_Line; with Ada.Containers.Indefinite_Vectors; with Ada.Directories; use Ada.Directories; with Ada.Exceptions; use Ada.Exceptions; with Ada.Text_IO; with Specs; procedure Generate is Proc : Specs.Processor; package Spec_Vectors is new Ada.Containers.Indefinite_Vectors (Positive, String); Spec_Paths : Spec_Vectors.Vector; package Path_Sorting is new Spec_Vectors.Generic_Sorting; Source_Folder : constant String := "src/specs"; Target_Folder : constant String := "src/generated"; Interface_Folder : constant String := "src/interface"; procedure Process_File (Directory_Entry : in Directory_Entry_Type) is Path : constant String := Full_Name (Directory_Entry); begin Ada.Text_IO.Put_Line ("Processing " & Path & " ..."); Spec_Paths.Append (Path); Ada.Text_IO.Put_Line ("Done processing " & Path & " ."); end Process_File; begin Search (Source_Folder, "*.spec", (Ordinary_File => True, others => False), Process_File'Access); Path_Sorting.Sort (Spec_Paths); for Path of Spec_Paths loop Specs.Parse_File (Proc, Path); end loop; Create_Path (Target_Folder); declare use type Specs.Spec; Cur : Specs.Spec := Specs.First (Proc); begin while Cur /= Specs.No_Spec loop Specs.Write_API (Proc, Cur, Target_Folder); Cur := Specs.Next (Proc, Cur); end loop; end; Specs.Write_Init (Proc, Target_Folder); Specs.Write_Wrapper_Table (Proc, Target_Folder, Interface_Folder); exception when Error : Specs.Parsing_Error => Ada.Text_IO.Put_Line (Exception_Message (Error)); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); end Generate;
package body afrl.impact.AngledAreaSearchTask.SPARK_Boundary with SPARK_Mode => Off is function Get_SearchAreaID (X : AngledAreaSearchTask) return Int64 renames getSearchAreaID; end afrl.impact.AngledAreaSearchTask.SPARK_Boundary;
-- { dg-do run } -- { dg-options "-gnatN" } with Text_IO; use Text_IO; with system; use system; procedure inline_tagged is package Pkg is type T_Inner is tagged record Value : Integer; end record; type T_Inner_access is access all T_Inner; procedure P2 (This : in T_Inner; Ptr : address); pragma inline (P2); type T_Outer is record Inner : T_Inner_Access; end record; procedure P1 (This : access T_Outer); end Pkg; package body Pkg is procedure P2 (This : in T_Inner; Ptr : address) is begin if this'address /= Ptr then raise Program_Error; end if; end; procedure P1 (This : access T_Outer) is begin P2 (This.Inner.all, This.Inner.all'Address); end P1; end Pkg; use Pkg; Thing : aliased T_Outer := (inner => new T_Inner); begin P1 (Thing'access); end;
with lace.Event.Logger, lace.Event.utility, system.RPC, ada.unchecked_Deallocation; package body lace.make_Subject is procedure destroy (Self : in out Item) is begin Self.safe_Observers.destruct; end destroy; -- Attributes -- overriding function Observers (Self : in Item; of_Kind : in event.Kind) return subject.Observer_views is begin return Self.safe_Observers.fetch_Observers (of_Kind); end Observers; overriding function observer_Count (Self : in Item) return Natural is begin return Self.safe_Observers.observer_Count; end observer_Count; -- Operations -- overriding procedure register (Self : access Item; the_Observer : in Observer.view; of_Kind : in event.Kind) is begin Self.safe_Observers.add (the_Observer, of_Kind); if subject.Logger /= null then subject.Logger.log_Connection (the_Observer, Subject.view (Self), of_Kind); end if; end register; overriding procedure deregister (Self : in out Item; the_Observer : in Observer.view; of_Kind : in event.Kind) is begin Self.safe_Observers.rid (the_Observer, of_Kind); if subject.Logger /= null then subject.Logger.log_disconnection (the_Observer, Self'unchecked_Access, of_Kind); end if; end deregister; overriding procedure emit (Self : access Item; the_Event : in Event.item'Class := event.null_Event) is use lace.Event.utility; my_Observers : constant subject.Observer_views := Self.Observers (to_Kind (the_Event'Tag)); begin for Each in my_Observers'Range loop begin my_Observers (Each).receive (the_Event, from_subject => Subject.item'Class (Self.all).Name); if subject.Logger /= null then subject.Logger.log_Emit (Subject.view (Self), my_Observers (Each), the_Event); end if; exception when system.RPC.communication_Error | storage_Error => if subject.Logger /= null then subject.Logger.log_Emit (Subject.view (Self), my_Observers (Each), the_Event); end if; end; end loop; end emit; overriding function emit (Self : access Item; the_Event : in Event.item'Class := event.null_Event) return subject.Observer_views is use lace.Event.utility; my_Observers : constant subject.Observer_views := Self.Observers (to_Kind (the_Event'Tag)); bad_Observers : subject.Observer_views (my_Observers'Range); bad_Count : Natural := 0; begin for Each in my_Observers'Range loop begin my_Observers (Each).receive (the_Event, from_subject => Subject.item'Class (Self.all).Name); if subject.Logger /= null then subject.Logger.log_Emit (Subject.view (Self), my_Observers (Each), the_Event); end if; exception when system.RPC.communication_Error | storage_Error => bad_Count := bad_Count + 1; bad_Observers (bad_Count) := my_Observers (Each); end; end loop; return bad_Observers (1 .. bad_Count); end emit; -- Safe Observers -- protected body safe_Observers is procedure destruct is use event_kind_Maps_of_event_observers; procedure free is new ada.unchecked_Deallocation (event_Observer_Vector, event_Observer_Vector_view); Cursor : event_kind_Maps_of_event_observers.Cursor := the_Observers.First; the_event_Observer_Vector : event_Observer_Vector_view; begin while has_Element (Cursor) loop the_event_Observer_Vector := Element (Cursor); free (the_event_Observer_Vector); next (Cursor); end loop; end destruct; procedure add (the_Observer : in Observer.view; of_Kind : in event.Kind) is use event_Observer_Vectors, event_kind_Maps_of_event_observers; Cursor : constant event_kind_Maps_of_event_observers.Cursor := the_Observers.find (of_Kind); the_event_Observers : event_Observer_Vector_view; begin if has_Element (Cursor) then the_event_Observers := Element (Cursor); else the_event_Observers := new event_Observer_Vector; the_Observers.insert (of_Kind, the_event_Observers); end if; the_event_Observers.append (the_Observer); end add; procedure rid (the_Observer : in Observer.view; of_Kind : in event.Kind) is the_event_Observers : event_Observer_Vector renames the_Observers.Element (of_Kind).all; begin the_event_Observers.delete (the_event_Observers.find_Index (the_Observer)); end rid; function fetch_Observers (of_Kind : in event.Kind) return subject.Observer_views is begin if the_Observers.Contains (of_Kind) then declare the_event_Observers : constant event_Observer_Vector_view := the_Observers.Element (of_Kind); my_Observers : subject.Observer_views (1 .. Natural (the_event_Observers.Length)); begin for Each in my_Observers'Range loop my_Observers (Each) := the_event_Observers.Element (Each); end loop; return my_Observers; end; else return (1 .. 0 => <>); end if; end fetch_Observers; function observer_Count return Natural is use event_kind_Maps_of_event_observers; Cursor : event_kind_Maps_of_event_observers.Cursor := the_Observers.First; Count : Natural := 0; begin while has_Element (Cursor) loop Count := Count + Natural (Element (Cursor).Length); next (Cursor); end loop; return Count; end observer_Count; end safe_Observers; end lace.make_Subject;
with STM32_SVD.GPIO; use STM32_SVD.GPIO; with STM32_SVD.SYSCFG; use STM32_SVD.SYSCFG; with STM32GD.EXTI; with STM32GD.EXTI.IRQ; with STM32GD.GPIO.Port; package body STM32GD.GPIO.IRQ is Index : constant Natural := GPIO_Pin'Pos (Pin.Pin); Pin_Mask : constant UInt16 := GPIO_Pin'Enum_Rep (Pin.Pin); procedure Connect_External_Interrupt is Port_Id : constant UInt4 := GPIO_Port'Enum_Rep (Pin.Port); begin case Index is when 0 .. 3 => SYSCFG_Periph.EXTICR1.EXTI.Arr (Index) := Port_Id; when 4 .. 7 => SYSCFG_Periph.EXTICR2.EXTI.Arr (Index) := Port_Id; when 8 .. 11 => SYSCFG_Periph.EXTICR3.EXTI.Arr (Index) := Port_Id; when 12 .. 15 => SYSCFG_Periph.EXTICR4.EXTI.Arr (Index) := Port_Id; when others => raise Program_Error; end case; end Connect_External_Interrupt; function Interrupt_Line_Number return STM32GD.EXTI.External_Line_Number is begin return STM32GD.EXTI.External_Line_Number'Val (Index); end Interrupt_Line_Number; procedure Wait_For_Trigger is begin STM32GD.EXTI.IRQ.IRQ_Handler.Wait; end Wait_For_Trigger; procedure Clear_Trigger is begin STM32GD.EXTI.IRQ.IRQ_Handler.Reset_Status (Interrupt_Line_Number); end Clear_Trigger; function Triggered return Boolean is begin return STM32GD.EXTI.IRQ.IRQ_Handler.Status (Interrupt_Line_Number); end Triggered; procedure Cancel_Wait is begin STM32GD.EXTI.IRQ.IRQ_Handler.Cancel; end Cancel_Wait; procedure Configure_Trigger (Event : Boolean := False; Rising : Boolean := False; Falling : Boolean := False) is use STM32GD.EXTI; Line : constant External_Line_Number := External_Line_Number'Val (Index); T : External_Triggers; begin Connect_External_Interrupt; if Event then if Rising and Falling then T := Event_Rising_Falling_Edge; elsif Rising then T := Event_Rising_Edge; else T := Event_Falling_Edge; Enable_External_Event (Line, T); end if; else if Rising and Falling then T := Interrupt_Rising_Falling_Edge; elsif Rising then T := Interrupt_Rising_Edge; else T := Interrupt_Falling_Edge; end if; Enable_External_Interrupt (Line, T); end if; end Configure_Trigger; end STM32GD.GPIO.IRQ;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2016 onox <denkpadje@gmail.com> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Characters.Latin_1; with Ada.Strings.Fixed; with Orka.Logging; with Orka.Strings; with Orka.Terminals; package body Orka.Rendering.Programs.Modules is use all type Orka.Logging.Source; use all type Orka.Logging.Severity; package Messages is new Orka.Logging.Messages (Shader_Compiler); function Trim_Image (Value : Integer) return String is (Orka.Strings.Trim (Integer'Image (Value))); package L1 renames Ada.Characters.Latin_1; use Orka.Strings; procedure Log_Error_With_Source (Text, Info_Log, Message : String) is package SF renames Ada.Strings.Fixed; Extra_Rows : constant := 1; Line_Number_Padding : constant := 2; Separator : constant String := " | "; use SF; use all type Orka.Terminals.Color; use all type Orka.Terminals.Style; begin declare Log_Parts : constant Orka.Strings.String_List := Split (Info_Log, ":", 3); Message_Parts : constant String_List := Split (Trim (+Log_Parts (3)), ": ", 2); Message_Kind_Color : constant Orka.Terminals.Color := (if +Message_Parts (1) = "error" then Red elsif +Message_Parts (1) = "warning" then Yellow elsif +Message_Parts (1) = "note" then Cyan else Default); Message_Kind : constant String := Orka.Terminals.Colorize (+Message_Parts (1) & ":", Foreground => Message_Kind_Color); Message_Value : constant String := Orka.Terminals.Colorize (+Message_Parts (2), Attribute => Bold); ------------------------------------------------------------------------- Lines : constant Orka.Strings.String_List := Orka.Strings.Split (Text, "" & L1.LF); Error_Row : constant Positive := Positive'Value (+Orka.Strings.Split (+Log_Parts (2), "(", 2) (1)); First_Row : constant Positive := Positive'Max (Lines'First, Error_Row - Extra_Rows); Last_Row : constant Positive := Positive'Min (Lines'Last, Error_Row + Extra_Rows); Line_Digits : constant Positive := Trim (Last_Row'Image)'Length + Line_Number_Padding; begin Messages.Log (Error, Message); for Row_Index in First_Row .. Last_Row loop declare Row_Image : constant String := SF.Tail (Trim (Row_Index'Image), Line_Digits); Row_Image_Colorized : constant String := Orka.Terminals.Colorize (Row_Image, Attribute => Dark); Line_Image : constant String := +Lines (Row_Index); First_Index_Line : constant Natural := SF.Index_Non_Blank (Line_Image, Going => Ada.Strings.Forward); Last_Index_Line : constant Natural := SF.Index_Non_Blank (Line_Image, Going => Ada.Strings.Backward); Error_Indicator : constant String := Orka.Terminals.Colorize (Natural'Max (0, First_Index_Line - 1) * " " & (Last_Index_Line - First_Index_Line + 1) * "^", Foreground => Green, Attribute => Bold); Prefix_Image : constant String := (Row_Image'Length + Separator'Length) * " "; begin Messages.Log (Error, Row_Image_Colorized & Separator & Line_Image); if Row_Index = Error_Row then Messages.Log (Error, Prefix_Image & Error_Indicator); Messages.Log (Error, Prefix_Image & ">>> " & Message_Kind & " " & Message_Value); end if; end; end loop; end; exception when others => -- Continue if parsing Info_Log fails null; end Log_Error_With_Source; procedure Load_And_Compile (Object : in out Module; Shader_Kind : GL.Objects.Shaders.Shader_Type; Location : Resources.Locations.Location_Ptr; Path : String) is begin if Path /= "" then pragma Assert (Object.Shaders (Shader_Kind).Is_Empty); declare Shader : GL.Objects.Shaders.Shader (Kind => Shader_Kind); Source : constant Resources.Byte_Array_Pointers.Pointer := Location.Read_Data (Path); Text : String renames Resources.Convert (Source.Get); begin Shader.Set_Source (Text); Shader.Compile; if not Shader.Compile_Status then declare Log : constant String := Shader.Info_Log; Log_Parts : constant Orka.Strings.String_List := Split (Log, "" & L1.LF); begin for Part of Log_Parts loop Log_Error_With_Source (Text, +Part, "Compiling shader " & Path & " failed:"); end loop; raise Shader_Compile_Error with Path & ":" & Log; end; end if; Messages.Log (Debug, "Compiled shader " & Path); Messages.Log (Debug, " size: " & Trim_Image (Orka.Strings.Lines (Text)) & " lines (" & Trim_Image (Source.Get.Value'Length) & " bytes)"); Messages.Log (Debug, " kind: " & Shader_Kind'Image); Object.Shaders (Shader_Kind).Replace_Element (Shader); end; end if; end Load_And_Compile; procedure Set_And_Compile (Object : in out Module; Shader_Kind : GL.Objects.Shaders.Shader_Type; Source : String) is begin if Source /= "" then pragma Assert (Object.Shaders (Shader_Kind).Is_Empty); declare Shader : GL.Objects.Shaders.Shader (Kind => Shader_Kind); begin Shader.Set_Source (Source); Shader.Compile; if not Shader.Compile_Status then declare Log : constant String := Shader.Info_Log; Log_Parts : constant Orka.Strings.String_List := Split (Log, "" & L1.LF); begin for Part of Log_Parts loop Log_Error_With_Source (Source, +Part, "Compiling " & Shader_Kind'Image & " shader failed:"); end loop; raise Shader_Compile_Error with Shader_Kind'Image & ":" & Log; end; end if; Messages.Log (Debug, "Compiled string with " & Trim_Image (Source'Length) & " characters"); Messages.Log (Debug, " size: " & Trim_Image (Orka.Strings.Lines (Source)) & " lines"); Messages.Log (Debug, " kind: " & Shader_Kind'Image); Object.Shaders (Shader_Kind).Replace_Element (Shader); end; end if; end Set_And_Compile; function Create_Module_From_Sources (VS, TCS, TES, GS, FS, CS : String := "") return Module is use GL.Objects.Shaders; begin return Result : Module do Set_And_Compile (Result, Vertex_Shader, VS); Set_And_Compile (Result, Tess_Control_Shader, TCS); Set_And_Compile (Result, Tess_Evaluation_Shader, TES); Set_And_Compile (Result, Geometry_Shader, GS); Set_And_Compile (Result, Fragment_Shader, FS); Set_And_Compile (Result, Compute_Shader, CS); end return; end Create_Module_From_Sources; function Create_Module (Location : Resources.Locations.Location_Ptr; VS, TCS, TES, GS, FS, CS : String := "") return Module is use GL.Objects.Shaders; begin return Result : Module do Load_And_Compile (Result, Vertex_Shader, Location, VS); Load_And_Compile (Result, Tess_Control_Shader, Location, TCS); Load_And_Compile (Result, Tess_Evaluation_Shader, Location, TES); Load_And_Compile (Result, Geometry_Shader, Location, GS); Load_And_Compile (Result, Fragment_Shader, Location, FS); Load_And_Compile (Result, Compute_Shader, Location, CS); end return; end Create_Module; procedure Attach_Shaders (Modules : Module_Array; Program : in out Programs.Program) is use GL.Objects.Shaders; procedure Attach (Subject : Module; Stage : GL.Objects.Shaders.Shader_Type) is Holder : Shader_Holder.Holder renames Subject.Shaders (Stage); begin if not Holder.Is_Empty then Program.GL_Program.Attach (Holder.Element); end if; end Attach; begin for Module of Modules loop Attach (Module, Vertex_Shader); Attach (Module, Tess_Control_Shader); Attach (Module, Tess_Evaluation_Shader); Attach (Module, Geometry_Shader); Attach (Module, Fragment_Shader); Attach (Module, Compute_Shader); end loop; end Attach_Shaders; procedure Detach_Shaders (Modules : Module_Array; Program : Programs.Program) is use GL.Objects.Shaders; procedure Detach (Holder : Shader_Holder.Holder) is begin if not Holder.Is_Empty then Program.GL_Program.Detach (Holder.Element); end if; end Detach; begin for Module of Modules loop Detach (Module.Shaders (Vertex_Shader)); Detach (Module.Shaders (Tess_Control_Shader)); Detach (Module.Shaders (Tess_Evaluation_Shader)); Detach (Module.Shaders (Geometry_Shader)); Detach (Module.Shaders (Fragment_Shader)); Detach (Module.Shaders (Compute_Shader)); end loop; end Detach_Shaders; end Orka.Rendering.Programs.Modules;
-- SPDX-FileCopyrightText: 2019 Max Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT ------------------------------------------------------------- package body Program.Plain_Lexical_Elements is type Lexical_Element_Access is access Lexical_Element; ------------ -- Append -- ------------ not overriding procedure Append (Self : aliased in out Lexical_Element_Vector; Span : Program.Source_Buffers.Span; Kind : Program.Lexical_Elements.Lexical_Element_Kind; Symbol : Program.Symbols.Symbol) is Item : constant Lexical_Element_Access := new Lexical_Element' (Vector => Self'Unchecked_Access, Span => Span, Kind => Kind, Symbol => Symbol); begin Self.Vector.Append (Program.Lexical_Elements.Lexical_Element_Access (Item)); end Append; ------------- -- Element -- ------------- overriding function Element (Self : Lexical_Element_Vector; Index : Positive) return not null Program.Lexical_Elements.Lexical_Element_Access is begin return Self.Vector.Element (Index); end Element; ---------- -- From -- ---------- overriding function From (Self : Lexical_Element) return Program.Lexical_Elements.Location is From_Line : Positive; To_Line : Positive; From_Column : Positive; To_Column : Positive; begin Self.Vector.Buffer.Get_Span (Self.Span, From_Line, To_Line, From_Column, To_Column); return (From_Line, From_Column); end From; ----------- -- Image -- ----------- overriding function Image (Self : Lexical_Element) return Program.Text is begin return Self.Vector.Buffer.Text (Self.Span); end Image; ---------- -- Kind -- ---------- overriding function Kind (Self : Lexical_Element) return Program.Lexical_Elements.Lexical_Element_Kind is begin return Self.Kind; end Kind; ---------------- -- Last_Index -- ---------------- overriding function Last_Index (Self : Lexical_Element_Vector) return Positive is begin return Self.Vector.Last_Index; end Last_Index; ------------ -- Symbol -- ------------ function Symbol (Self : Lexical_Element'Class) return Program.Symbols.Symbol is begin return Self.Symbol; end Symbol; end Program.Plain_Lexical_Elements;
-- SaxonSOC GPIO mapping -- The structure is mostly based on https://github.com/AdaCore/bb-runtimes/ -- blob/community-2020/riscv/sifive/fe310/svd/i-fe310-gpio.ads with System; -- TODO do more than just the LEDS package Interfaces.SaxonSOC.GPIO is pragma Preelaborate; pragma No_Elaboration_Code_All; -- Auxiliary types type GPIO_Control_Reg is new Unsigned_32; type Mask_T is new Unsigned_32; -- Addresses GPIO_A_Base_Address : constant := 16#1000_0000#; GPIO_A_Input : GPIO_Control_Reg with Volatile_Full_Access, Address => System'To_Address (GPIO_A_Base_Address); GPIO_A_Output : GPIO_Control_Reg with Address => System'To_Address (GPIO_A_Base_Address + 16#04#); GPIO_A_Output_Enable : GPIO_Control_Reg with Address => System'To_Address (GPIO_A_Base_Address + 16#08#); end Interfaces.SaxonSOC.GPIO;
with AUnit; with AUnit.Test_Fixtures; with Brackelib.Stacks; package Stacks_Tests is package State_Stacks is new Brackelib.Stacks (Integer); use State_Stacks; type Test is new AUnit.Test_Fixtures.Test_Fixture with null record; procedure Set_Up (T : in out Test); procedure Test_Push (T : in out Test); procedure Test_Pop (T : in out Test); procedure Test_Top (T : in out Test); procedure Test_Clear (T : in out Test); end Stacks_Tests;
-- -- Copyright (C) 2021, AdaCore -- pragma Style_Checks (Off); -- This spec has been automatically generated from STM32L562.svd with System; package Interfaces.STM32.SYSCFG is pragma Preelaborate; pragma No_Elaboration_Code_All; --------------- -- Registers -- --------------- -- SYSCFG secure configuration register type SECCFGR_Register is record -- SYSCFG clock control security SYSCFGSEC : Boolean := False; -- ClassB security CLASSBSEC : Boolean := False; -- SRAM2 security SRAM2SEC : Boolean := False; -- FPUSEC FPUSEC : Boolean := False; -- unspecified Reserved_4_31 : Interfaces.STM32.UInt28 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for SECCFGR_Register use record SYSCFGSEC at 0 range 0 .. 0; CLASSBSEC at 0 range 1 .. 1; SRAM2SEC at 0 range 2 .. 2; FPUSEC at 0 range 3 .. 3; Reserved_4_31 at 0 range 4 .. 31; end record; -- configuration register 1 type CFGR1_Register is record -- unspecified Reserved_0_7 : Interfaces.STM32.Byte := 16#0#; -- I/O analog switch voltage booster enable BOOSTEN : Boolean := False; -- GPIO analog switch control voltage selection ANASWVDD : Boolean := False; -- unspecified Reserved_10_15 : Interfaces.STM32.UInt6 := 16#0#; -- Fast-mode Plus (Fm+) driving capability activation on PB6 I2C_PB6_FMP : Boolean := False; -- Fast-mode Plus (Fm+) driving capability activation on PB7 I2C_PB7_FMP : Boolean := False; -- Fast-mode Plus (Fm+) driving capability activation on PB8 I2C_PB8_FMP : Boolean := False; -- Fast-mode Plus (Fm+) driving capability activation on PB9 I2C_PB9_FMP : Boolean := False; -- I2C1 Fast-mode Plus driving capability activation I2C1_FMP : Boolean := False; -- I2C2 Fast-mode Plus driving capability activation I2C2_FMP : Boolean := False; -- I2C3 Fast-mode Plus driving capability activation I2C3_FMP : Boolean := False; -- I2C4_FMP I2C4_FMP : Boolean := False; -- unspecified Reserved_24_31 : Interfaces.STM32.Byte := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CFGR1_Register use record Reserved_0_7 at 0 range 0 .. 7; BOOSTEN at 0 range 8 .. 8; ANASWVDD at 0 range 9 .. 9; Reserved_10_15 at 0 range 10 .. 15; I2C_PB6_FMP at 0 range 16 .. 16; I2C_PB7_FMP at 0 range 17 .. 17; I2C_PB8_FMP at 0 range 18 .. 18; I2C_PB9_FMP at 0 range 19 .. 19; I2C1_FMP at 0 range 20 .. 20; I2C2_FMP at 0 range 21 .. 21; I2C3_FMP at 0 range 22 .. 22; I2C4_FMP at 0 range 23 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; -- FPU interrupt mask register type FPUIMR_Register is record -- Floating point unit interrupts enable bits FPU_IE : Interfaces.STM32.UInt6 := 16#1F#; -- unspecified Reserved_6_31 : Interfaces.STM32.UInt26 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for FPUIMR_Register use record FPU_IE at 0 range 0 .. 5; Reserved_6_31 at 0 range 6 .. 31; end record; -- SYSCFG CPU non-secure lock register type CNSLCKR_Register is record -- VTOR_NS register lock LOCKNSVTOR : Boolean := False; -- Non-secure MPU registers lock LOCKNSMPU : Boolean := False; -- unspecified Reserved_2_31 : Interfaces.STM32.UInt30 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CNSLCKR_Register use record LOCKNSVTOR at 0 range 0 .. 0; LOCKNSMPU at 0 range 1 .. 1; Reserved_2_31 at 0 range 2 .. 31; end record; -- SYSCFG CPU secure lock register type CSLOCKR_Register is record -- LOCKSVTAIRCR LOCKSVTAIRCR : Boolean := False; -- LOCKSMPU LOCKSMPU : Boolean := False; -- LOCKSAU LOCKSAU : Boolean := False; -- unspecified Reserved_3_31 : Interfaces.STM32.UInt29 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CSLOCKR_Register use record LOCKSVTAIRCR at 0 range 0 .. 0; LOCKSMPU at 0 range 1 .. 1; LOCKSAU at 0 range 2 .. 2; Reserved_3_31 at 0 range 3 .. 31; end record; -- CFGR2 type CFGR2_Register is record -- Write-only. LOCKUP (hardfault) output enable bit CLL : Boolean := False; -- Write-only. SRAM2 parity lock bit SPL : Boolean := False; -- Write-only. PVD lock enable bit PVDL : Boolean := False; -- Write-only. ECC Lock ECCL : Boolean := False; -- unspecified Reserved_4_7 : Interfaces.STM32.UInt4 := 16#0#; -- SRAM2 parity error flag SPF : Boolean := False; -- unspecified Reserved_9_31 : Interfaces.STM32.UInt23 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CFGR2_Register use record CLL at 0 range 0 .. 0; SPL at 0 range 1 .. 1; PVDL at 0 range 2 .. 2; ECCL at 0 range 3 .. 3; Reserved_4_7 at 0 range 4 .. 7; SPF at 0 range 8 .. 8; Reserved_9_31 at 0 range 9 .. 31; end record; -- SCSR type SCSR_Register is record -- SRAM2 Erase SRAM2ER : Boolean := False; -- Read-only. SRAM2 busy by erase operation SRAM2BSY : Boolean := False; -- unspecified Reserved_2_31 : Interfaces.STM32.UInt30 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for SCSR_Register use record SRAM2ER at 0 range 0 .. 0; SRAM2BSY at 0 range 1 .. 1; Reserved_2_31 at 0 range 2 .. 31; end record; -- SKR type SKR_Register is record -- Write-only. SRAM2 write protection key for software erase KEY : Interfaces.STM32.Byte := 16#0#; -- unspecified Reserved_8_31 : Interfaces.STM32.UInt24 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for SKR_Register use record KEY at 0 range 0 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; -- SWPR type SWPR_Register is record -- Write-only. P0WP P0WP : Boolean := False; -- Write-only. P1WP P1WP : Boolean := False; -- Write-only. P2WP P2WP : Boolean := False; -- Write-only. P3WP P3WP : Boolean := False; -- Write-only. P4WP P4WP : Boolean := False; -- Write-only. P5WP P5WP : Boolean := False; -- Write-only. P6WP P6WP : Boolean := False; -- Write-only. P7WP P7WP : Boolean := False; -- Write-only. P8WP P8WP : Boolean := False; -- Write-only. P9WP P9WP : Boolean := False; -- Write-only. P10WP P10WP : Boolean := False; -- Write-only. P11WP P11WP : Boolean := False; -- Write-only. P12WP P12WP : Boolean := False; -- Write-only. P13WP P13WP : Boolean := False; -- Write-only. P14WP P14WP : Boolean := False; -- Write-only. P15WP P15WP : Boolean := False; -- Write-only. P16WP P16WP : Boolean := False; -- Write-only. P17WP P17WP : Boolean := False; -- Write-only. P18WP P18WP : Boolean := False; -- Write-only. P19WP P19WP : Boolean := False; -- Write-only. P20WP P20WP : Boolean := False; -- Write-only. P21WP P21WP : Boolean := False; -- Write-only. P22WP P22WP : Boolean := False; -- Write-only. P23WP P23WP : Boolean := False; -- Write-only. P24WP P24WP : Boolean := False; -- Write-only. P25WP P25WP : Boolean := False; -- Write-only. P26WP P26WP : Boolean := False; -- Write-only. P27WP P27WP : Boolean := False; -- Write-only. P28WP P28WP : Boolean := False; -- Write-only. P29WP P29WP : Boolean := False; -- Write-only. P30WP P30WP : Boolean := False; -- Write-only. SRAM2 page 31 write protection P31WP : Boolean := False; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for SWPR_Register use record P0WP at 0 range 0 .. 0; P1WP at 0 range 1 .. 1; P2WP at 0 range 2 .. 2; P3WP at 0 range 3 .. 3; P4WP at 0 range 4 .. 4; P5WP at 0 range 5 .. 5; P6WP at 0 range 6 .. 6; P7WP at 0 range 7 .. 7; P8WP at 0 range 8 .. 8; P9WP at 0 range 9 .. 9; P10WP at 0 range 10 .. 10; P11WP at 0 range 11 .. 11; P12WP at 0 range 12 .. 12; P13WP at 0 range 13 .. 13; P14WP at 0 range 14 .. 14; P15WP at 0 range 15 .. 15; P16WP at 0 range 16 .. 16; P17WP at 0 range 17 .. 17; P18WP at 0 range 18 .. 18; P19WP at 0 range 19 .. 19; P20WP at 0 range 20 .. 20; P21WP at 0 range 21 .. 21; P22WP at 0 range 22 .. 22; P23WP at 0 range 23 .. 23; P24WP at 0 range 24 .. 24; P25WP at 0 range 25 .. 25; P26WP at 0 range 26 .. 26; P27WP at 0 range 27 .. 27; P28WP at 0 range 28 .. 28; P29WP at 0 range 29 .. 29; P30WP at 0 range 30 .. 30; P31WP at 0 range 31 .. 31; end record; -- SWPR2 type SWPR2_Register is record -- Write-only. P32WP P32WP : Boolean := False; -- Write-only. P33WP P33WP : Boolean := False; -- Write-only. P34WP P34WP : Boolean := False; -- Write-only. P35WP P35WP : Boolean := False; -- Write-only. P36WP P36WP : Boolean := False; -- Write-only. P37WP P37WP : Boolean := False; -- Write-only. P38WP P38WP : Boolean := False; -- Write-only. P39WP P39WP : Boolean := False; -- Write-only. P40WP P40WP : Boolean := False; -- Write-only. P41WP P41WP : Boolean := False; -- Write-only. P42WP P42WP : Boolean := False; -- Write-only. P43WP P43WP : Boolean := False; -- Write-only. P44WP P44WP : Boolean := False; -- Write-only. P45WP P45WP : Boolean := False; -- Write-only. P46WP P46WP : Boolean := False; -- Write-only. P47WP P47WP : Boolean := False; -- Write-only. P48WP P48WP : Boolean := False; -- Write-only. P49WP P49WP : Boolean := False; -- Write-only. P50WP P50WP : Boolean := False; -- Write-only. P51WP P51WP : Boolean := False; -- Write-only. P52WP P52WP : Boolean := False; -- Write-only. P53WP P53WP : Boolean := False; -- Write-only. P54WP P54WP : Boolean := False; -- Write-only. P55WP P55WP : Boolean := False; -- Write-only. P56WP P56WP : Boolean := False; -- Write-only. P57WP P57WP : Boolean := False; -- Write-only. P58WP P58WP : Boolean := False; -- Write-only. P59WP P59WP : Boolean := False; -- Write-only. P60WP P60WP : Boolean := False; -- Write-only. P61WP P61WP : Boolean := False; -- Write-only. P62WP P62WP : Boolean := False; -- Write-only. P63WP P63WP : Boolean := False; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for SWPR2_Register use record P32WP at 0 range 0 .. 0; P33WP at 0 range 1 .. 1; P34WP at 0 range 2 .. 2; P35WP at 0 range 3 .. 3; P36WP at 0 range 4 .. 4; P37WP at 0 range 5 .. 5; P38WP at 0 range 6 .. 6; P39WP at 0 range 7 .. 7; P40WP at 0 range 8 .. 8; P41WP at 0 range 9 .. 9; P42WP at 0 range 10 .. 10; P43WP at 0 range 11 .. 11; P44WP at 0 range 12 .. 12; P45WP at 0 range 13 .. 13; P46WP at 0 range 14 .. 14; P47WP at 0 range 15 .. 15; P48WP at 0 range 16 .. 16; P49WP at 0 range 17 .. 17; P50WP at 0 range 18 .. 18; P51WP at 0 range 19 .. 19; P52WP at 0 range 20 .. 20; P53WP at 0 range 21 .. 21; P54WP at 0 range 22 .. 22; P55WP at 0 range 23 .. 23; P56WP at 0 range 24 .. 24; P57WP at 0 range 25 .. 25; P58WP at 0 range 26 .. 26; P59WP at 0 range 27 .. 27; P60WP at 0 range 28 .. 28; P61WP at 0 range 29 .. 29; P62WP at 0 range 30 .. 30; P63WP at 0 range 31 .. 31; end record; -- RSSCMDR type RSSCMDR_Register is record -- RSS commands RSSCMD : Interfaces.STM32.Byte := 16#0#; -- unspecified Reserved_8_31 : Interfaces.STM32.UInt24 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for RSSCMDR_Register use record RSSCMD at 0 range 0 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- System configuration controller type SYSCFG_Peripheral is record -- SYSCFG secure configuration register SECCFGR : aliased SECCFGR_Register; -- configuration register 1 CFGR1 : aliased CFGR1_Register; -- FPU interrupt mask register FPUIMR : aliased FPUIMR_Register; -- SYSCFG CPU non-secure lock register CNSLCKR : aliased CNSLCKR_Register; -- SYSCFG CPU secure lock register CSLOCKR : aliased CSLOCKR_Register; -- CFGR2 CFGR2 : aliased CFGR2_Register; -- SCSR SCSR : aliased SCSR_Register; -- SKR SKR : aliased SKR_Register; -- SWPR SWPR : aliased SWPR_Register; -- SWPR2 SWPR2 : aliased SWPR2_Register; -- RSSCMDR RSSCMDR : aliased RSSCMDR_Register; end record with Volatile; for SYSCFG_Peripheral use record SECCFGR at 16#0# range 0 .. 31; CFGR1 at 16#4# range 0 .. 31; FPUIMR at 16#8# range 0 .. 31; CNSLCKR at 16#C# range 0 .. 31; CSLOCKR at 16#10# range 0 .. 31; CFGR2 at 16#14# range 0 .. 31; SCSR at 16#18# range 0 .. 31; SKR at 16#1C# range 0 .. 31; SWPR at 16#20# range 0 .. 31; SWPR2 at 16#24# range 0 .. 31; RSSCMDR at 16#2C# range 0 .. 31; end record; -- System configuration controller SEC_SYSCFG_Periph : aliased SYSCFG_Peripheral with Import, Address => SEC_SYSCFG_Base; -- System configuration controller SYSCFG_Periph : aliased SYSCFG_Peripheral with Import, Address => SYSCFG_Base; end Interfaces.STM32.SYSCFG;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Ada.Text_IO; use Ada.Text_IO; with Mat; -- use Mat; procedure factorial is N : Natural; begin Get( N ); Put( Mat.factorial(N) ); end factorial;
with Interfaces.C; use Interfaces.C; with Interfaces.C.Strings; with System; package body gnatcoll.dl is package dlfcn_h is function dlopen (arg1 : System.Address; arg2 : Flag) return System.Address; -- dlfcn.h:57:14 pragma Import (C, dlopen, "dlopen"); function dlclose (arg1 : System.Address) return int; -- dlfcn.h:61:12 pragma Import (C, dlclose, "dlclose"); function dlsym (arg1 : System.Address; arg2 : System.Address) return System.Address; -- dlfcn.h:65:14 pragma Import (C, dlsym, "dlsym"); function dlerror return Interfaces.C.Strings.chars_ptr; -- dlfcn.h:83:14 pragma Import (C, dlerror, "dlerror"); end dlfcn_h; use dlfcn_h; use type system.Address; procedure Open (This : in out Dynamic_Library; File_Name : String; Flags : Flag := RTLD_LAZY) is L_name : aliased constant string := File_Name & ASCII.NUL; begin this.handle := dlopen (L_name'Address, Flags); if this.handle = System.Null_Address then raise Dynamic_Library_Error with error; end if; end; function Open (File_Name : String; Flags : Flag := RTLD_LAZY) return Dynamic_Library is begin return ret : Dynamic_Library do open(ret,File_Name,Flags); end return; end; procedure close (this : dynamic_Library) is ret : int; begin ret := dlclose (this.handle); if ret /= 0 then raise Dynamic_Library_Error with error; end if; end; function sym (this : dynamic_Library; Symbol_name : String) return System.Address is L_name : aliased constant string := Symbol_name & ASCII.NUL; begin return ret : System.Address do ret := dlsym (this.handle, L_name'Address); if ret = System.Null_Address then raise Dynamic_Library_Error with error; end if; end return; end; function error return String is begin return Interfaces.C.Strings.Value (dlerror); end; end gnatcoll.dl;
-------------------------------------------------------------------------- -- Maze 19991109 <> 20020509 by Joe Wingbermuehle -- This is a random maze generator -------------------------------------------------------------------------- with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Ada.Numerics.Discrete_Random; with Ada.Calendar; use Ada.Calendar; with Ada.Command_Line; procedure Maze is Block : constant String := "[]"; -- Block for maze Space : constant String := " "; -- Blank space for maze Release : constant String := "20020509"; -- Release date subtype Random_Range is Integer range 0 .. 3; package Random4 is new Ada.Numerics.Discrete_Random(Random_Range); type Array_Type is array(Positive range <>, Positive range <>) of Integer range 0 .. 1; type Array_Pointer is access Array_Type; maze : Array_Pointer; -- The maze array seed : Random4.Generator; -- Random number seed width : Integer range 1 .. Integer'last; -- Maze width height : Integer range 1 .. Integer'last; -- Maze height ------------------------------------------------------------------ -- Display the maze ------------------------------------------------------------------ procedure Display_Maze is begin for y in 1 .. height loop for x in 1 .. width loop if maze(x, y) = 1 then Put(Block); else Put(Space); end if; end loop; New_Line; end loop; end Display_Maze; ------------------------------------------------------------------ -- Initialize the maze array ------------------------------------------------------------------ procedure Initialize_Board is begin for y in 1 .. height loop for x in 1 .. width loop maze(x, y) := 1; end loop; end loop; end Initialize_Board; ------------------------------------------------------------------ -- Carve out a section of the maze ------------------------------------------------------------------ procedure Carve_Maze(x : in Integer; y : in Integer) is d : Integer range 0 .. 3; -- Direction c : Integer range 0 .. 4; -- Number of directions tried dx, dy : Integer; x1, y1 : Integer; x2, y2 : Integer; begin d := Random4.Random(seed); c := 0; while c < 4 loop dx := 0; dy := 0; case d is when 0 => dx := 1; when 1 => dy := 1; when 2 => dx := -1; when 3 => dy := -1; end case; x1 := x + dx; y1 := y + dy; x2 := x1 + dx; y2 := y1 + dy; if x2 > 1 and x2 < width and y2 > 1 and y2 < height then if maze(x1, y1) = 1 and maze(x2, y2) = 1 then maze(x1, y1) := 0; maze(x2, y2) := 0; Carve_Maze(x2, y2); end if; end if; c := c + 1; d := (d + 1) mod 4; end loop; end Carve_Maze; ------------------------------------------------------------------ -- Generate the maze ------------------------------------------------------------------ procedure Generate_Maze is begin Initialize_Board; maze(2, 2) := 0; Carve_Maze(2, 2); maze(2, 1) := 0; maze(width - 1, height) := 0; end Generate_Maze; begin -- Display the header Put("Maze " & Release & " by Joe Wingbermuehle"); New_Line; if Ada.Command_Line.Argument_Count /= 2 then Put_Line("usage: " & Ada.Command_Line.Command_Name & " <width> <height>"); return; end if; -- Read the size from the command line begin width := Integer'value(Ada.Command_Line.Argument(1)); height := Integer'value(Ada.Command_Line.Argument(2)); exception when others => Put_Line("Invalid size"); return; end; -- Create the maze array height := height * 2 + 3; width := width * 2 + 3; maze := new Array_Type(1 .. width, 1 .. height); -- Generate the maze Random4.Reset(seed, Integer(Seconds(Clock))); Generate_Maze; Display_Maze; end Maze;
package body Tkmrpc.Contexts.cc is pragma Warnings (Off, "* already use-visible through previous use type clause"); use type Types.cc_id_type; use type Types.certificate_type; use type Types.certificate_type; use type Types.ca_id_type; use type Types.ri_id_type; use type Types.authag_id_type; use type Types.abs_time_type; use type Types.abs_time_type; pragma Warnings (On, "* already use-visible through previous use type clause"); type cc_FSM_Type is record State : cc_State_Type; certificate : Types.certificate_type; last_cert : Types.certificate_type; ca_id : Types.ca_id_type; ri_id : Types.ri_id_type; authag_id : Types.authag_id_type; not_before : Types.abs_time_type; not_after : Types.abs_time_type; end record; -- Certificate Chain Context Null_cc_FSM : constant cc_FSM_Type := cc_FSM_Type' (State => clean, certificate => Types.Null_certificate_type, last_cert => Types.Null_certificate_type, ca_id => Types.ca_id_type'First, ri_id => Types.ri_id_type'First, authag_id => Types.authag_id_type'First, not_before => Types.abs_time_type'First, not_after => Types.abs_time_type'First); type Context_Array_Type is array (Types.cc_id_type) of cc_FSM_Type; Context_Array : Context_Array_Type := Context_Array_Type' (others => (Null_cc_FSM)); ------------------------------------------------------------------------- function Get_State (Id : Types.cc_id_type) return cc_State_Type is begin return Context_Array (Id).State; end Get_State; ------------------------------------------------------------------------- function Has_authag_id (Id : Types.cc_id_type; authag_id : Types.authag_id_type) return Boolean is (Context_Array (Id).authag_id = authag_id); ------------------------------------------------------------------------- function Has_ca_id (Id : Types.cc_id_type; ca_id : Types.ca_id_type) return Boolean is (Context_Array (Id).ca_id = ca_id); ------------------------------------------------------------------------- function Has_certificate (Id : Types.cc_id_type; certificate : Types.certificate_type) return Boolean is (Context_Array (Id).certificate = certificate); ------------------------------------------------------------------------- function Has_last_cert (Id : Types.cc_id_type; last_cert : Types.certificate_type) return Boolean is (Context_Array (Id).last_cert = last_cert); ------------------------------------------------------------------------- function Has_not_after (Id : Types.cc_id_type; not_after : Types.abs_time_type) return Boolean is (Context_Array (Id).not_after = not_after); ------------------------------------------------------------------------- function Has_not_before (Id : Types.cc_id_type; not_before : Types.abs_time_type) return Boolean is (Context_Array (Id).not_before = not_before); ------------------------------------------------------------------------- function Has_ri_id (Id : Types.cc_id_type; ri_id : Types.ri_id_type) return Boolean is (Context_Array (Id).ri_id = ri_id); ------------------------------------------------------------------------- function Has_State (Id : Types.cc_id_type; State : cc_State_Type) return Boolean is (Context_Array (Id).State = State); ------------------------------------------------------------------------- pragma Warnings (Off, "condition can only be False if invalid values present"); function Is_Valid (Id : Types.cc_id_type) return Boolean is (Context_Array'First <= Id and Id <= Context_Array'Last); pragma Warnings (On, "condition can only be False if invalid values present"); ------------------------------------------------------------------------- procedure add_certificate (Id : Types.cc_id_type; certificate : Types.certificate_type; not_before : Types.abs_time_type; not_after : Types.abs_time_type) is begin Context_Array (Id).last_cert := certificate; Context_Array (Id).not_before := not_before; Context_Array (Id).not_after := not_after; end add_certificate; ------------------------------------------------------------------------- procedure check (Id : Types.cc_id_type; ca_id : Types.ca_id_type) is begin Context_Array (Id).ca_id := ca_id; Context_Array (Id).State := checked; end check; ------------------------------------------------------------------------- procedure create (Id : Types.cc_id_type; authag_id : Types.authag_id_type; ri_id : Types.ri_id_type; certificate : Types.certificate_type; last_cert : Types.certificate_type; not_before : Types.abs_time_type; not_after : Types.abs_time_type) is begin Context_Array (Id).authag_id := authag_id; Context_Array (Id).ri_id := ri_id; Context_Array (Id).certificate := certificate; Context_Array (Id).last_cert := last_cert; Context_Array (Id).not_before := not_before; Context_Array (Id).not_after := not_after; Context_Array (Id).State := linked; end create; ------------------------------------------------------------------------- function get_certificate (Id : Types.cc_id_type) return Types.certificate_type is begin return Context_Array (Id).certificate; end get_certificate; ------------------------------------------------------------------------- function get_last_cert (Id : Types.cc_id_type) return Types.certificate_type is begin return Context_Array (Id).last_cert; end get_last_cert; ------------------------------------------------------------------------- function get_not_after (Id : Types.cc_id_type) return Types.abs_time_type is begin return Context_Array (Id).not_after; end get_not_after; ------------------------------------------------------------------------- function get_not_before (Id : Types.cc_id_type) return Types.abs_time_type is begin return Context_Array (Id).not_before; end get_not_before; ------------------------------------------------------------------------- function get_remote_id (Id : Types.cc_id_type) return Types.ri_id_type is begin return Context_Array (Id).ri_id; end get_remote_id; ------------------------------------------------------------------------- procedure invalidate (Id : Types.cc_id_type) is begin Context_Array (Id).State := invalid; end invalidate; ------------------------------------------------------------------------- procedure reset (Id : Types.cc_id_type) is begin Context_Array (Id).ca_id := Types.ca_id_type'First; Context_Array (Id).authag_id := Types.authag_id_type'First; Context_Array (Id).ri_id := Types.ri_id_type'First; Context_Array (Id).certificate := Types.Null_certificate_type; Context_Array (Id).not_before := Types.abs_time_type'First; Context_Array (Id).not_after := Types.abs_time_type'First; Context_Array (Id).State := clean; end reset; end Tkmrpc.Contexts.cc;
------------------------------------------------------------------------------ -- -- -- ASIS-for-GNAT IMPLEMENTATION COMPONENTS -- -- -- -- A S I S . D E F I N I T I O N S -- -- -- -- B o d y -- -- -- -- Copyright (C) 1995-2011, Free Software Foundation, Inc. -- -- -- -- ASIS-for-GNAT is free software; you can redistribute it and/or modify it -- -- under terms of the GNU General Public License as published by the Free -- -- Software Foundation; either version 2, or (at your option) any later -- -- version. ASIS-for-GNAT is distributed in the hope that it will be use- -- -- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- -- -- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General -- -- Public License for more details. You should have received a copy of the -- -- GNU General Public License distributed with ASIS-for-GNAT; see file -- -- COPYING. If not, write to the Free Software Foundation, 51 Franklin -- -- Street, Fifth Floor, Boston, MA 02110-1301, USA. -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the -- -- Software Engineering Laboratory of the Swiss Federal Institute of -- -- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the -- -- Scientific Research Computer Center of Moscow State University (SRCC -- -- MSU), Russia, with funding partially provided by grants from the Swiss -- -- National Science Foundation and the Swiss Academy of Engineering -- -- Sciences. ASIS-for-GNAT is now maintained by AdaCore -- -- (http://www.adacore.com). -- -- -- ------------------------------------------------------------------------------ with Asis.Declarations; use Asis.Declarations; with Asis.Elements; use Asis.Elements; with Asis.Errors; use Asis.Errors; with Asis.Exceptions; use Asis.Exceptions; with Asis.Extensions; use Asis.Extensions; with Asis.Set_Get; use Asis.Set_Get; with A4G.A_Sem; use A4G.A_Sem; with A4G.Asis_Tables; use A4G.Asis_Tables; with A4G.Contt.UT; use A4G.Contt.UT; with A4G.Mapping; use A4G.Mapping; with A4G.Norm; use A4G.Norm; with A4G.Stand; use A4G.Stand; with A4G.Vcheck; use A4G.Vcheck; with Atree; use Atree; with Einfo; use Einfo; with Namet; use Namet; with Nlists; use Nlists; with Sinfo; use Sinfo; package body Asis.Definitions is Package_Name : constant String := "Asis.Definitions."; ------------------------------------------------------------------------------ --------------------------- -- ASIS 2005 Draft stuff -- --------------------------- --------------------------------------------- -- Anonymous_Access_To_Object_Subtype_Mark -- --------------------------------------------- function Anonymous_Access_To_Object_Subtype_Mark (Definition : Asis.Definition) return Asis.Expression is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Definition); Arg_Node : Node_Id; begin Check_Validity (Definition, Package_Name & "Anonymous_Access_To_Object_Subtype_Mark"); if not (Arg_Kind = An_Anonymous_Access_To_Variable or else Arg_Kind = An_Anonymous_Access_To_Constant) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Anonymous_Access_To_Object_Subtype_Mark", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Definition); return Node_To_Element_New (Node => Subtype_Mark (Arg_Node), Starting_Element => Definition); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Definition, Outer_Call => Package_Name & "Anonymous_Access_To_Object_Subtype_Mark"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Anonymous_Access_To_Object_Subtype_Mark", Ex => Ex, Arg_Element => Definition); end Anonymous_Access_To_Object_Subtype_Mark; ------------------------------- -- Component_Definition_View -- ------------------------------- function Component_Definition_View (Component_Definition : Asis.Component_Definition) return Asis.Definition is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Component_Definition); Res_Node : Node_Id; Result_Kind : Internal_Element_Kinds := Not_An_Element; begin Check_Validity (Component_Definition, Package_Name & "Component_Definition_View"); if not (Arg_Kind = A_Component_Definition) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Component_Definition_View", Wrong_Kind => Arg_Kind); end if; Res_Node := R_Node (Component_Definition); if Is_Rewrite_Substitution (Res_Node) or else Present (Access_Definition (Res_Node)) then Res_Node := Access_Definition (Original_Node (Res_Node)); else Result_Kind := A_Subtype_Indication; Res_Node := Sinfo.Subtype_Indication (Res_Node); end if; return Node_To_Element_New (Node => Res_Node, Starting_Element => Component_Definition, Internal_Kind => Result_Kind); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Component_Definition, Outer_Call => Package_Name & "Component_Definition_View"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Component_Definition_View", Ex => Ex, Arg_Element => Component_Definition); end Component_Definition_View; ------------------------------- -- Definition_Interface_List -- ------------------------------- function Definition_Interface_List (Type_Definition : Asis.Definition) return Asis.Expression_List is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Type_Definition); Arg_Node : Node_Id; First_I : Node_Id; I_Kind : Internal_Element_Kinds; begin Check_Validity (Type_Definition, Package_Name & "Definition_Interface_List"); if not (Arg_Kind = A_Derived_Record_Extension_Definition or else Arg_Kind = A_Private_Extension_Definition or else Arg_Kind in Internal_Interface_Kinds or else Arg_Kind = A_Formal_Derived_Type_Definition or else Arg_Kind in Internal_Formal_Interface_Kinds) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Definition_Interface_List", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Type_Definition); if Nkind (Arg_Node) = N_Record_Definition and then not Interface_Present (Arg_Node) then return Nil_Element_List; elsif Nkind (Arg_Node) = N_Derived_Type_Definition and then Interface_Present (Arg_Node) then -- The first interface name in the list is represented as -- Subtype_Indication field in N_Derived_Type_Definition node First_I := Sinfo.Subtype_Indication (Arg_Node); if Nkind (First_I) = N_Identifier then I_Kind := An_Identifier; else I_Kind := A_Selected_Component; end if; return Node_To_Element_New (Node => First_I, Starting_Element => Type_Definition, Internal_Kind => I_Kind) & N_To_E_List_New (List => Interface_List (Arg_Node), Starting_Element => Type_Definition); else return N_To_E_List_New (List => Interface_List (Arg_Node), Starting_Element => Type_Definition); end if; exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Type_Definition, Outer_Call => Package_Name & "Definition_Interface_List"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Definition_Interface_List", Ex => Ex, Arg_Element => Type_Definition); end Definition_Interface_List; --------------------------- -- ASIS 2012 Draft stuff -- --------------------------- ----------------------- -- Aspect_Definition -- ----------------------- function Aspect_Definition (Aspect_Specification : Asis.Element) return Asis.Element is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Aspect_Specification); begin Check_Validity (Aspect_Specification, Package_Name & "Aspect_Definition"); if Arg_Kind /= An_Aspect_Specification then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Aspect_Definition", Wrong_Kind => Arg_Kind); end if; return Node_To_Element_New (Node => Sinfo.Expression (Node (Aspect_Specification)), Starting_Element => Aspect_Specification); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Aspect_Specification, Outer_Call => Package_Name & "Aspect_Definition"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Aspect_Definition", Ex => Ex, Arg_Element => Aspect_Specification); end Aspect_Definition; ----------------- -- Aspect_Mark -- ----------------- function Aspect_Mark (Aspect_Specification : Asis.Element) return Asis.Element is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Aspect_Specification); Res_Node : Node_Id; Res_Kind : Internal_Element_Kinds := An_Identifier; begin Check_Validity (Aspect_Specification, Package_Name & "Aspect_Mark"); if Arg_Kind /= An_Aspect_Specification then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Aspect_Mark", Wrong_Kind => Arg_Kind); end if; Res_Node := Node (Aspect_Specification); if Class_Present (Res_Node) then Res_Kind := A_Class_Attribute; end if; Res_Node := Sinfo.Identifier (Res_Node); return Node_To_Element_New (Node => Res_Node, Starting_Element => Aspect_Specification, Internal_Kind => Res_Kind); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Aspect_Specification, Outer_Call => Package_Name & "Aspect_Mark"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Aspect_Mark", Ex => Ex, Arg_Element => Aspect_Specification); end Aspect_Mark; ------------------------------------------------------------------------------ -- NOT IMPLEMENTED -- The query is implemented with the following ramification of its -- definition: -- -- 1. The list of appropriate kinds is: -- -- Appropriate Definition_Kinds: -- A_Type_Definition -- A_Formal_Type_Declaration -- A_Private_Type_Definition -- A_Tagged_Private_Type_Definition -- A_Private_Extension_Definition -- A_Task_Definition -- A_Protected_Definition -- -- 2. The query returns only primitive operators of the type, except if the -- argument is A_Formal_Type_Declaration. In the latter case the result -- contains inherited user-defined operators and all the formal -- operators defined for this type -- -- 3. Any operator that satisfy conditions given in (2) and that has a -- parameter or returns the result of the argument type is returned. -- -- 4. In case of a private type and private extension, the query returns -- the same results when applied to the private and to the full view. -- -- 5. Implicit declarations of predefined operators are not supported. So -- they are not included in the result of the query function Corresponding_Type_Operators (Type_Definition : Asis.Type_Definition) return Asis.Declaration_List is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Type_Definition); begin Check_Validity (Type_Definition, Package_Name & "Corresponding_Type_Operators"); if not (Arg_Kind in Internal_Type_Kinds or else Arg_Kind in Internal_Formal_Type_Kinds or else Arg_Kind in A_Private_Type_Definition .. A_Protected_Definition) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Corresponding_Type_Operators", Wrong_Kind => Arg_Kind); end if; return Inherited_Type_Operators (Type_Definition) & Explicit_Type_Operators (Type_Definition); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Type_Definition, Outer_Call => Package_Name & "Corresponding_Type_Operators"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Corresponding_Type_Operators", Ex => Ex, Arg_Element => Type_Definition); end Corresponding_Type_Operators; ----------------------------------------------------------------------------- function Parent_Subtype_Indication (Type_Definition : Asis.Type_Definition) return Asis.Subtype_Indication is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Type_Definition); Arg_Node : Node_Id; begin Check_Validity (Type_Definition, Package_Name & "Parent_Subtype_Indication"); if not (Arg_Kind = A_Derived_Type_Definition or else Arg_Kind = A_Derived_Record_Extension_Definition) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Parent_Subtype_Indication", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Type_Definition); return Node_To_Element_New (Node => Sinfo.Subtype_Indication (Arg_Node), Starting_Element => Type_Definition, Internal_Kind => A_Subtype_Indication); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Type_Definition, Outer_Call => Package_Name & "Parent_Subtype_Indication"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Parent_Subtype_Indication", Ex => Ex, Arg_Element => Type_Definition); end Parent_Subtype_Indication; ----------------------------------------------------------------------------- function Record_Definition (Type_Definition : Asis.Type_Definition) return Asis.Record_Definition is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Type_Definition); Arg_Node : Node_Id; Result_Kind : Internal_Element_Kinds; Result_Node : Node_Id; begin Check_Validity (Type_Definition, Package_Name & "Record_Definition"); if not (Arg_Kind = A_Derived_Record_Extension_Definition or else Arg_Kind = A_Record_Type_Definition or else Arg_Kind = A_Tagged_Record_Type_Definition) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Record_Definition", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Type_Definition); if Arg_Kind = A_Derived_Record_Extension_Definition then Result_Node := Record_Extension_Part (Arg_Node); else Result_Node := Arg_Node; end if; if Null_Present (Result_Node) then Result_Kind := A_Null_Record_Definition; else Result_Kind := A_Record_Definition; end if; return Node_To_Element_New (Node => Result_Node, Starting_Element => Type_Definition, Internal_Kind => Result_Kind); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Type_Definition, Outer_Call => Package_Name & "Record_Definition"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Record_Definition", Ex => Ex, Arg_Element => Type_Definition); end Record_Definition; ------------------------------------------------------------------------------ -- NOT IMPLEMENTED??? function Implicit_Inherited_Declarations (Definition : Asis.Definition) return Asis.Declaration_List is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Definition); Type_Entity_Node : Node_Id; Type_Decl_Node : Node_Id; Inherit_Discrims : Boolean := True; begin Check_Validity (Definition, Package_Name & "Implicit_Inherited_Declarations"); if not (Arg_Kind = A_Private_Extension_Definition or else Arg_Kind = A_Derived_Type_Definition or else Arg_Kind = A_Derived_Record_Extension_Definition or else Arg_Kind = A_Formal_Derived_Type_Definition) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Implicit_Inherited_Declarations", Wrong_Kind => Arg_Kind); end if; Type_Entity_Node := Defining_Identifier (Parent (R_Node (Definition))); if not (Is_Record_Type (Type_Entity_Node) or else Is_Enumeration_Type (Type_Entity_Node) or else Is_Task_Type (Type_Entity_Node) or else Is_Protected_Type (Type_Entity_Node)) then return Nil_Element_List; end if; Type_Decl_Node := Parent (R_Node (Definition)); if Present (Discriminant_Specifications (Original_Node (Type_Decl_Node))) then Inherit_Discrims := False; end if; if Is_Record_Type (Type_Entity_Node) then Set_Inherited_Components (Definition, Inherit_Discrims); elsif Is_Concurrent_Type (Type_Entity_Node) then Set_Concurrent_Inherited_Components (Definition, Inherit_Discrims); elsif Is_Enumeration_Type (Type_Entity_Node) then if Present (First_Literal (Type_Entity_Node)) then Set_Inherited_Literals (Definition); else -- Type derived (directly or indirectly) from Standard.Character -- or Standard.Wide_Character return Standard_Char_Decls (Type_Definition => Definition, Implicit => True); end if; else Not_Implemented_Yet (Diagnosis => Package_Name & "Implicit_Inherited_Declarations"); end if; for J in 1 .. Asis_Element_Table.Last loop Set_From_Implicit (Asis_Element_Table.Table (J), True); Set_From_Inherited (Asis_Element_Table.Table (J), True); Set_Node_Field_1 (Asis_Element_Table.Table (J), Type_Decl_Node); end loop; return Asis.Declaration_List (Asis_Element_Table.Table (1 .. Asis_Element_Table.Last)); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Definition, Outer_Call => Package_Name & "Implicit_Inherited_Declarations"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Implicit_Inherited_Declarations", Ex => Ex, Arg_Element => Definition); end Implicit_Inherited_Declarations; ------------------------------------------------------------------------------ function Implicit_Inherited_Subprograms (Definition : Asis.Definition) return Asis.Declaration_List is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Definition); Type_Entity_Node : Node_Id; Next_Subpr_Node : Node_Id; Next_Expl_Subpr : Node_Id; Expl_Subpr_Name : Node_Id; Next_Subpr_Kind : Internal_Element_Kinds; Next_Subpr_Element : Element; Result_Unit : Compilation_Unit; begin Check_Validity (Definition, Package_Name & "Implicit_Inherited_Subprograms"); if not (Arg_Kind = A_Private_Extension_Definition or else Arg_Kind = A_Derived_Type_Definition or else Arg_Kind = A_Derived_Record_Extension_Definition or else Arg_Kind = A_Formal_Derived_Type_Definition or else Arg_Kind in Internal_Interface_Kinds or else Arg_Kind in Internal_Formal_Interface_Kinds) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Implicit_Inherited_Subprograms", Wrong_Kind => Arg_Kind); end if; Type_Entity_Node := R_Node (Definition); if Nkind (Type_Entity_Node) /= N_Private_Extension_Declaration then Type_Entity_Node := Parent (Type_Entity_Node); end if; Type_Entity_Node := Defining_Identifier (Type_Entity_Node); Result_Unit := Encl_Unit (Definition); Asis_Element_Table.Init; Next_Subpr_Node := Next_Entity (Type_Entity_Node); -- All the inherited subprograms can be *after* the type entity only Type_Entity_Node := Parent (Type_Entity_Node); -- now Type_Entity_Node points to the type declaration of the type -- which inherits the result subprograms while Present (Next_Subpr_Node) loop if (Ekind (Next_Subpr_Node) = E_Procedure or else Ekind (Next_Subpr_Node) = E_Function) and then Parent (Next_Subpr_Node) = Type_Entity_Node and then not (Is_Hidden (Next_Subpr_Node) and then Present (Interface_Alias (Next_Subpr_Node))) then -- This entity node represents the user-defined inherited -- subprogram for Type_Entity_Node Next_Expl_Subpr := Explicit_Parent_Subprogram (Next_Subpr_Node); Expl_Subpr_Name := Next_Expl_Subpr; if Is_Generic_Instance (Expl_Subpr_Name) then -- Go to the instantiation entity node, because for the -- expanded subprogram the front-end creates an artificial -- name: while Nkind (Expl_Subpr_Name) /= N_Package_Declaration loop Expl_Subpr_Name := Parent (Expl_Subpr_Name); end loop; while Nkind (Expl_Subpr_Name) not in N_Generic_Instantiation loop Expl_Subpr_Name := Next (Expl_Subpr_Name); end loop; Expl_Subpr_Name := Defining_Unit_Name (Expl_Subpr_Name); end if; if Chars (Next_Subpr_Node) = Chars (Expl_Subpr_Name) then -- For this condition, see the discussion in 8215-007 Next_Expl_Subpr := Parent (Next_Expl_Subpr); if Ekind (Next_Subpr_Node) = E_Function then Next_Subpr_Kind := A_Function_Declaration; elsif Null_Present (Next_Expl_Subpr) then Next_Subpr_Kind := A_Null_Procedure_Declaration; else Next_Subpr_Kind := A_Procedure_Declaration; end if; Next_Expl_Subpr := Parent (Next_Expl_Subpr); Next_Subpr_Element := Node_To_Element_New (Node => Next_Expl_Subpr, Node_Field_1 => Next_Subpr_Node, Internal_Kind => Next_Subpr_Kind, Inherited => True, In_Unit => Result_Unit); -- See the comment in the body of -- A4G.A_Sem.Get_Corr_Called_Entity if Is_From_Instance (Next_Subpr_Node) then Set_From_Instance (Next_Subpr_Element, True); else Set_From_Instance (Next_Subpr_Element, False); end if; Asis_Element_Table.Append (Next_Subpr_Element); end if; end if; Next_Subpr_Node := Next_Entity (Next_Subpr_Node); end loop; return Asis.Declaration_List (Asis_Element_Table.Table (1 .. Asis_Element_Table.Last)); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Definition, Outer_Call => Package_Name & "Implicit_Inherited_Subprograms"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Implicit_Inherited_Subprograms", Ex => Ex, Arg_Element => Definition); end Implicit_Inherited_Subprograms; ----------------------------------------------------------------------------- function Corresponding_Parent_Subtype (Type_Definition : Asis.Type_Definition) return Asis.Declaration is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Type_Definition); Type_Mark_Node : Node_Id; Result_Node : Node_Id; Result_Unit : Asis.Compilation_Unit; Result : Asis.Element := Nil_Element; begin Check_Validity (Type_Definition, Package_Name & "Corresponding_Parent_Subtype"); if not (Arg_Kind = A_Derived_Type_Definition or else Arg_Kind = A_Derived_Record_Extension_Definition) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Corresponding_Parent_Subtype", Wrong_Kind => Arg_Kind); end if; Type_Mark_Node := Sinfo.Subtype_Indication (Node (Type_Definition)); if Nkind (Type_Mark_Node) = N_Subtype_Indication then Type_Mark_Node := Sinfo.Subtype_Mark (Type_Mark_Node); end if; if Nkind (Original_Node (Type_Mark_Node)) /= N_Attribute_Reference then Result_Node := Entity (Type_Mark_Node); Result_Node := Parent (Result_Node); Result_Unit := Enclosing_Unit (Encl_Cont_Id (Type_Definition), Result_Node); Result := Node_To_Element_New (Node => Result_Node, In_Unit => Result_Unit); end if; return Result; exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Type_Definition, Outer_Call => Package_Name & "Corresponding_Parent_Subtype"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Corresponding_Parent_Subtype", Ex => Ex, Arg_Element => Type_Definition); end Corresponding_Parent_Subtype; ----------------------------------------------------------------------------- function Corresponding_Root_Type (Type_Definition : Asis.Type_Definition) return Asis.Declaration is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Type_Definition); Result_El : Asis.Declaration; Result_Kind : Internal_Element_Kinds; Def_El : Asis.Type_Definition; Def_Kind : Internal_Element_Kinds; begin Check_Validity (Type_Definition, Package_Name & "Corresponding_Root_Type"); if not (Arg_Kind = A_Derived_Type_Definition or else Arg_Kind = A_Derived_Record_Extension_Definition) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Corresponding_Root_Type", Wrong_Kind => Arg_Kind); end if; Result_El := Corresponding_Parent_Subtype_Unwind_Base (Type_Definition); loop Result_Kind := Int_Kind (Result_El); if Result_Kind = A_Subtype_Declaration then Result_El := Corresponding_First_Subtype (Result_El); else -- Result_El can be of An_Ordinary_Type_Declaration, -- A_Task_Type_Declaration, A_Protected_Type_Declaration, -- A_Private_Type_Declaration, A_Private_Extension_Declaration -- or A_Formal_Type_Declaration only if Result_Kind = An_Ordinary_Type_Declaration or else Result_Kind = A_Formal_Type_Declaration then Def_El := Type_Declaration_View (Result_El); Def_Kind := Int_Kind (Def_El); if Def_Kind = A_Derived_Type_Definition or else Def_Kind = A_Derived_Record_Extension_Definition then Result_El := Corresponding_Parent_Subtype_Unwind_Base (Def_El); else exit; end if; else exit; end if; end if; end loop; return Result_El; exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Type_Definition, Outer_Call => Package_Name & "Corresponding_Root_Type"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Corresponding_Root_Type", Ex => Ex, Arg_Element => Type_Definition); end Corresponding_Root_Type; ------------------------------------------------------------------------------ function Corresponding_Type_Structure (Type_Definition : Asis.Type_Definition) return Asis.Declaration is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Type_Definition); Result_El : Asis.Element; Type_Def_El : Asis.Element; Res_Entity_Node : Node_Id; Tmp_Node : Node_Id; begin Check_Validity (Type_Definition, Package_Name & "Corresponding_Type_Structure"); if not (Arg_Kind = A_Derived_Type_Definition or else Arg_Kind = A_Derived_Record_Extension_Definition) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Corresponding_Type_Structure", Wrong_Kind => Arg_Kind); end if; -- The implementation approach: -- 1. We are considering, that the following things change the -- type structure (type representation): -- (1) adding the new component to a tagged record type; -- (2) applying any representation pragma or representation -- clause to a type in the derivation chain -- ??? What about adding a new primitive operation in case of a -- ??? tagged type? It changes the representation of the tag. -- -- 2. The implementation is based on other semantic queries from -- this package. The idea is to make the implementation more -- stable and to isolate the code which depends on processing of -- implicit types in the tree Result_El := Enclosing_Element (Type_Definition); Res_Entity_Node := Defining_Identifier (Node (Result_El)); Derivation_Chain : loop -- In this loop we are iterating through the derivation chain. -- There are three reasons to exit the loop: -- 1. Result_El has representation items; -- 2. Result_El is not a derived type -- 3. Result_El defines a new component Tmp_Node := First_Rep_Item (Res_Entity_Node); while Present (Tmp_Node) loop if not Is_Derived_Rep_Item (Res_Entity_Node, Tmp_Node) then exit Derivation_Chain; end if; Tmp_Node := Next_Rep_Item (Tmp_Node); end loop; Type_Def_El := Type_Declaration_View (Result_El); case Int_Kind (Type_Def_El) is when A_Derived_Type_Definition | A_Formal_Derived_Type_Definition => null; when A_Derived_Record_Extension_Definition => -- Here we are iterating through the list of the components -- checking if there is a new, non-inherited component: Tmp_Node := First_Entity (Res_Entity_Node); while Present (Tmp_Node) loop if (Ekind (Tmp_Node) = E_Component or else Ekind (Tmp_Node) = E_Discriminant) and then Original_Record_Component (Tmp_Node) = Tmp_Node then -- Note that we can have implicit (sub)types in the chain exit Derivation_Chain; end if; Tmp_Node := Next_Entity (Tmp_Node); end loop; when others => exit Derivation_Chain; end case; Result_El := Type_Declaration_View (Result_El); Result_El := Corresponding_Parent_Subtype (Result_El); if Int_Kind (Result_El) = A_Subtype_Declaration then Result_El := Corresponding_First_Subtype (Result_El); end if; Res_Entity_Node := Defining_Identifier (Node (Result_El)); end loop Derivation_Chain; return Result_El; exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Type_Definition, Outer_Call => Package_Name & "Corresponding_Type_Structure"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Corresponding_Type_Structure", Ex => Ex, Arg_Element => Type_Definition); end Corresponding_Type_Structure; ------------------------------------------------------------------------------ function Enumeration_Literal_Declarations (Type_Definition : Asis.Type_Definition) return Asis.Declaration_List is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Type_Definition); Arg_Node : Node_Id; begin Check_Validity (Type_Definition, Package_Name & "Enumeration_Literal_Declarations"); if not (Arg_Kind = An_Enumeration_Type_Definition) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Enumeration_Literal_Declarations", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Type_Definition); if Is_Standard_Char_Type (Arg_Node) then -- There is no Literals list for standard char types, so a special -- processing is needed return Standard_Char_Decls (Type_Definition); else return N_To_E_List_New (List => Literals (Arg_Node), Starting_Element => Type_Definition, Internal_Kind => An_Enumeration_Literal_Specification); end if; exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Type_Definition, Outer_Call => Package_Name & "Enumeration_Literal_Declarations"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Enumeration_Literal_Declarations", Ex => Ex, Arg_Element => Type_Definition); end Enumeration_Literal_Declarations; ------------------------------------------------------------------------------ -- OPEN PROBLEMS: -- -- 1. Standard.Character and Standard.Whide_Character types have -- to be processed specifically (See Sinfo.ads item for -- N_Enumeration_Type_Definition Node. This is not implemented yet. ------------------------------------------------------------------------------ function Integer_Constraint (Type_Definition : Asis.Type_Definition) return Asis.Range_Constraint is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Type_Definition); Arg_Node : Node_Id; begin Check_Validity (Type_Definition, Package_Name & "Integer_Constraint"); if not (Arg_Kind = A_Signed_Integer_Type_Definition) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Integer_Constraint", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Type_Definition); return Node_To_Element_New (Node => Arg_Node, Starting_Element => Type_Definition, Internal_Kind => A_Simple_Expression_Range); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Type_Definition, Outer_Call => Package_Name & "Integer_Constraint"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Integer_Constraint", Ex => Ex, Arg_Element => Type_Definition); end Integer_Constraint; ----------------------------------------------------------------------------- function Mod_Static_Expression (Type_Definition : Asis.Type_Definition) return Asis.Expression is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Type_Definition); Arg_Node : Node_Id; begin Check_Validity (Type_Definition, Package_Name & "Mod_Static_Expression"); if not (Arg_Kind = A_Modular_Type_Definition) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Mod_Static_Expression", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Type_Definition); return Node_To_Element_New (Node => Sinfo.Expression (Arg_Node), Starting_Element => Type_Definition); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Type_Definition, Outer_Call => Package_Name & "Mod_Static_Expression"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Mod_Static_Expression", Ex => Ex, Arg_Element => Type_Definition); end Mod_Static_Expression; ----------------------------------------------------------------------------- function Digits_Expression (Definition : Asis.Definition) return Asis.Expression is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Definition); Arg_Node : Node_Id; begin Check_Validity (Definition, Package_Name & "Digits_Expression"); if not (Arg_Kind = A_Floating_Point_Definition or else Arg_Kind = A_Decimal_Fixed_Point_Definition or else Arg_Kind = A_Digits_Constraint) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Digits_Expression", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Definition); return Node_To_Element_New (Node => Digits_Expression (Arg_Node), Starting_Element => Definition); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Definition, Outer_Call => Package_Name & "Digits_Expression"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Digits_Expression", Ex => Ex, Arg_Element => Definition); end Digits_Expression; ----------------------------------------------------------------------------- function Delta_Expression (Definition : Asis.Definition) return Asis.Expression is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Definition); Arg_Node : Node_Id; begin Check_Validity (Definition, Package_Name & "Delta_Expression"); if not (Arg_Kind = An_Ordinary_Fixed_Point_Definition or else Arg_Kind = A_Decimal_Fixed_Point_Definition or else Arg_Kind = A_Delta_Constraint) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Delta_Expression", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Definition); return Node_To_Element_New (Node => Delta_Expression (Arg_Node), Starting_Element => Definition); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Definition, Outer_Call => Package_Name & "Delta_Expression"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Delta_Expression", Ex => Ex, Arg_Element => Definition); end Delta_Expression; ----------------------------------------------------------------------------- function Real_Range_Constraint (Definition : Asis.Definition) return Asis.Range_Constraint is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Definition); Arg_Node : Node_Id; Result_Node : Node_Id; begin Check_Validity (Definition, Package_Name & "Real_Range_Constraint"); if not (Arg_Kind = A_Floating_Point_Definition or else Arg_Kind = An_Ordinary_Fixed_Point_Definition or else Arg_Kind = A_Decimal_Fixed_Point_Definition or else Arg_Kind = A_Digits_Constraint or else Arg_Kind = A_Delta_Constraint) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Real_Range_Constraint", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Definition); if Arg_Kind = A_Floating_Point_Definition or else Arg_Kind = An_Ordinary_Fixed_Point_Definition or else Arg_Kind = A_Decimal_Fixed_Point_Definition then Result_Node := Real_Range_Specification (Arg_Node); else -- Arg_Kind = A_Digits_Constraint or Arg_Kind = A_Delta_Constraint Result_Node := Sinfo.Range_Constraint (Arg_Node); end if; if No (Result_Node) then return Nil_Element; else return Node_To_Element_New (Node => Result_Node, Starting_Element => Definition, Internal_Kind => A_Simple_Expression_Range); end if; exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information ( Argument => Definition, Outer_Call => Package_Name & "Real_Range_Constraint"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Real_Range_Constraint", Ex => Ex, Arg_Element => Definition); end Real_Range_Constraint; ----------------------------------------------------------------------------- function Index_Subtype_Definitions (Type_Definition : Asis.Type_Definition) return Asis.Expression_List is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Type_Definition); Arg_Node : Node_Id; begin Check_Validity (Type_Definition, Package_Name & "Index_Subtype_Definitions"); if not (Arg_Kind = An_Unconstrained_Array_Definition or else Arg_Kind = A_Formal_Unconstrained_Array_Definition) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Index_Subtype_Definitions", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Type_Definition); return N_To_E_List_New (List => Subtype_Marks (Arg_Node), Starting_Element => Type_Definition); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information ( Argument => Type_Definition, Outer_Call => Package_Name & "Index_Subtype_Definitions"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Index_Subtype_Definitions", Ex => Ex, Arg_Element => Type_Definition); end Index_Subtype_Definitions; ----------------------------------------------------------------------------- function Discrete_Subtype_Definitions (Type_Definition : Asis.Type_Definition) return Asis.Definition_List is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Type_Definition); Arg_Node : Node_Id; begin Check_Validity (Type_Definition, Package_Name & "Discrete_Subtype_Definitions"); if not (Arg_Kind = A_Constrained_Array_Definition or else Arg_Kind = A_Formal_Constrained_Array_Definition) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Discrete_Subtype_Definitions", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Type_Definition); return N_To_E_List_New ( List => Discrete_Subtype_Definitions (Arg_Node), Starting_Element => Type_Definition); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Type_Definition, Outer_Call => Package_Name & "Discrete_Subtype_Definitions"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Discrete_Subtype_Definitions", Ex => Ex, Arg_Element => Type_Definition); end Discrete_Subtype_Definitions; -------------------------------- -- Array_Component_Definition -- -------------------------------- function Array_Component_Definition (Type_Definition : Asis.Type_Definition) return Asis.Component_Definition is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Type_Definition); Arg_Node : Node_Id; begin Check_Validity (Type_Definition, Package_Name & "Array_Component_Definition"); if not (Arg_Kind = An_Unconstrained_Array_Definition or else Arg_Kind = A_Constrained_Array_Definition or else Arg_Kind = A_Formal_Unconstrained_Array_Definition or else Arg_Kind = A_Formal_Constrained_Array_Definition) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Array_Component_Definition", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Type_Definition); return Node_To_Element_New (Node => Sinfo.Component_Definition (Arg_Node), Starting_Element => Type_Definition, Internal_Kind => A_Component_Definition); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Type_Definition, Outer_Call => Package_Name & "Array_Component_Definition"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Array_Component_Definition", Ex => Ex, Arg_Element => Type_Definition); end Array_Component_Definition; ----------------------------------------------------------------------------- function Access_To_Object_Definition (Type_Definition : Asis.Type_Definition) return Asis.Subtype_Indication is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Type_Definition); Arg_Node : Node_Id; begin Check_Validity (Type_Definition, Package_Name & "Access_To_Object_Definition"); if not (Arg_Kind = A_Pool_Specific_Access_To_Variable or else Arg_Kind = An_Access_To_Variable or else Arg_Kind = An_Access_To_Constant or else Arg_Kind = A_Formal_Pool_Specific_Access_To_Variable or else Arg_Kind = A_Formal_Access_To_Variable or else Arg_Kind = A_Formal_Access_To_Constant) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Access_To_Object_Definition", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Type_Definition); return Node_To_Element_New (Node => Sinfo.Subtype_Indication (Arg_Node), Starting_Element => Type_Definition, Internal_Kind => A_Subtype_Indication); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Type_Definition, Outer_Call => Package_Name & "Access_To_Object_Definition"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Access_To_Object_Definition", Ex => Ex, Arg_Element => Type_Definition); end Access_To_Object_Definition; ----------------------------------------------------------------------------- function Access_To_Subprogram_Parameter_Profile (Type_Definition : Asis.Type_Definition) return Asis.Parameter_Specification_List is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Type_Definition); Arg_Node : Node_Id; Result_List : List_Id; begin Check_Validity (Type_Definition, Package_Name & "Access_To_Subprogram_Parameter_Profile"); if not (Arg_Kind = An_Access_To_Procedure or else Arg_Kind = An_Access_To_Protected_Procedure or else Arg_Kind = An_Access_To_Function or else Arg_Kind = An_Access_To_Protected_Function or else Arg_Kind = A_Formal_Access_To_Procedure or else Arg_Kind = A_Formal_Access_To_Protected_Procedure or else Arg_Kind = A_Formal_Access_To_Function or else Arg_Kind = A_Formal_Access_To_Protected_Function or else -- --|A2005 start Arg_Kind = An_Anonymous_Access_To_Procedure or else Arg_Kind = An_Anonymous_Access_To_Protected_Procedure or else Arg_Kind = An_Anonymous_Access_To_Function or else Arg_Kind = An_Anonymous_Access_To_Protected_Function) -- --|A2005 end then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Access_To_Subprogram_Parameter_Profile", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Type_Definition); -- --|A2005 start if Nkind (Arg_Node) = N_Access_Definition then Arg_Node := Sinfo.Access_To_Subprogram_Definition (Arg_Node); end if; -- --|A2005 end Result_List := Parameter_Specifications (Arg_Node); if No (Result_List) then return Nil_Element_List; else return N_To_E_List_New (List => Result_List, Starting_Element => Type_Definition, Internal_Kind => A_Parameter_Specification); end if; exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Type_Definition, Outer_Call => Package_Name & "Access_To_Subprogram_Parameter_Profile"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Access_To_Subprogram_Parameter_Profile", Ex => Ex, Arg_Element => Type_Definition); end Access_To_Subprogram_Parameter_Profile; ----------------------------------------------------------------------------- function Access_To_Function_Result_Profile (Type_Definition : Asis.Type_Definition) return Asis.Expression is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Type_Definition); Arg_Node : Node_Id; begin Check_Validity (Type_Definition, Package_Name & "Access_To_Function_Result_Profile"); if not (Arg_Kind = An_Access_To_Function or else Arg_Kind = An_Access_To_Protected_Function or else Arg_Kind = A_Formal_Access_To_Function or else Arg_Kind = A_Formal_Access_To_Protected_Function or else -- --|A2005 start Arg_Kind = An_Anonymous_Access_To_Function or else Arg_Kind = An_Anonymous_Access_To_Protected_Function) -- --|A2005 end then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Access_To_Function_Result_Profile", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Type_Definition); -- --|A2005 start if Nkind (Arg_Node) = N_Access_Definition then Arg_Node := Sinfo.Access_To_Subprogram_Definition (Arg_Node); end if; -- --|A2005 end return Node_To_Element_New (Node => Sinfo.Result_Definition (Arg_Node), Starting_Element => Type_Definition); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Type_Definition, Outer_Call => Package_Name & "Access_To_Function_Result_Profile"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Access_To_Function_Result_Profile", Ex => Ex, Arg_Element => Type_Definition); end Access_To_Function_Result_Profile; ----------------------------------------------------------------------------- function Subtype_Mark (Definition : Asis.Definition) return Asis.Expression is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Definition); Arg_Node : Node_Id; Result_Node : Node_Id; Result_Kind : Internal_Element_Kinds := Not_An_Element; begin Check_Validity (Definition, Package_Name & "Subtype_Mark"); if not (Arg_Kind = A_Subtype_Indication or else Arg_Kind = A_Discrete_Subtype_Indication or else Arg_Kind = A_Formal_Derived_Type_Definition or else Arg_Kind = A_Discrete_Subtype_Indication_As_Subtype_Definition) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Subtype_Mark", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Definition); if Nkind (Arg_Node) = N_Subtype_Indication or else Nkind (Arg_Node) = N_Formal_Derived_Type_Definition then Result_Node := Sinfo.Subtype_Mark (Arg_Node); else Result_Node := R_Node (Definition); end if; if Nkind (Original_Node (Result_Node)) = N_Identifier and then not Is_Rewrite_Substitution (Result_Node) then if Is_Part_Of_Instance (Definition) then if Represents_Class_Wide_Type_In_Instance (Result_Node) then Result_Kind := A_Class_Attribute; elsif Represents_Base_Type_In_Instance (Result_Node) then Result_Kind := A_Base_Attribute; else Result_Kind := An_Identifier; end if; else Result_Kind := An_Identifier; end if; elsif Nkind (Original_Node (Result_Node)) = N_Expanded_Name then Result_Kind := A_Selected_Component; end if; return Node_To_Element_New (Node => Result_Node, Starting_Element => Definition, Internal_Kind => Result_Kind); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Definition, Outer_Call => Package_Name & "Subtype_Mark"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Subtype_Mark", Ex => Ex, Arg_Element => Definition); end Subtype_Mark; ----------------------------------------------------------------------------- function Subtype_Constraint (Definition : Asis.Definition) return Asis.Constraint is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Definition); Arg_Node : Node_Id; Result_Node : Node_Id := Empty; Result_Kind : Internal_Element_Kinds := Not_An_Element; begin Check_Validity (Definition, Package_Name & "Subtype_Constraint"); if not (Arg_Kind = A_Subtype_Indication or else Arg_Kind = A_Discrete_Subtype_Indication or else Arg_Kind = A_Discrete_Subtype_Indication_As_Subtype_Definition) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Subtype_Constraint", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Definition); if Nkind (Arg_Node) = N_Subtype_Indication then Result_Node := Sinfo.Constraint (Arg_Node); elsif Sloc (Arg_Node) <= Standard_Location and then Nkind (Parent (Arg_Node)) = N_Subtype_Declaration then -- This is either Standard.Positive or Standard.Natural, -- they have the constraint information not in -- N_Subtype_Declaration node, but in N_Defining_Identifier node Result_Node := Scalar_Range (Defining_Identifier (Parent (Arg_Node))); Result_Kind := A_Simple_Expression_Range; end if; return Node_To_Element_New (Node => Result_Node, Starting_Element => Definition, Internal_Kind => Result_Kind); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Definition, Outer_Call => Package_Name & "Subtype_Constraint"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Subtype_Constraint", Ex => Ex, Arg_Element => Definition); end Subtype_Constraint; ----------------------------------------------------------------------------- function Lower_Bound (Constraint : Asis.Range_Constraint) return Asis.Expression is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Constraint); Arg_Node : Node_Id; Result_Node : Node_Id; begin Check_Validity (Constraint, Package_Name & "Lower_Bound"); if not (Arg_Kind = A_Simple_Expression_Range or else Arg_Kind = A_Discrete_Simple_Expression_Range or else Arg_Kind = A_Discrete_Simple_Expression_Range_As_Subtype_Definition) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Lower_Bound", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Constraint); if Nkind (Arg_Node) = N_Range_Constraint then Result_Node := Low_Bound (Range_Expression (Arg_Node)); elsif Nkind (Arg_Node) = N_Component_Clause then Result_Node := First_Bit (Arg_Node); else -- Nkind (Arg_Node) = N_Range or else -- Nkind (Arg_Node) = N_Real_Range_Specification Result_Node := Low_Bound (Arg_Node); end if; return Node_To_Element_New (Node => Result_Node, Starting_Element => Constraint); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Constraint, Outer_Call => Package_Name & "Lower_Bound"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Lower_Bound", Ex => Ex, Arg_Element => Constraint); end Lower_Bound; ----------------------------------------------------------------------------- function Upper_Bound (Constraint : Asis.Range_Constraint) return Asis.Expression is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Constraint); Arg_Node : Node_Id; Result_Node : Node_Id; begin Check_Validity (Constraint, Package_Name & "Upper_Bound"); if not (Arg_Kind = A_Simple_Expression_Range or else Arg_Kind = A_Discrete_Simple_Expression_Range or else Arg_Kind = A_Discrete_Simple_Expression_Range_As_Subtype_Definition) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Upper_Bound", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Constraint); if Nkind (Arg_Node) = N_Range_Constraint then Result_Node := High_Bound (Range_Expression (Arg_Node)); elsif Nkind (Arg_Node) = N_Component_Clause then Result_Node := Last_Bit (Arg_Node); else Result_Node := High_Bound (Arg_Node); end if; return Node_To_Element_New (Node => Result_Node, Starting_Element => Constraint); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Constraint, Outer_Call => Package_Name & "Upper_Bound"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Upper_Bound", Ex => Ex, Arg_Element => Constraint); end Upper_Bound; ----------------------------------------------------------------------------- function Range_Attribute (Constraint : Asis.Range_Constraint) return Asis.Expression is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Constraint); Arg_Node : constant Node_Id := Node (Constraint); Result_Node : Node_Id; begin Check_Validity (Constraint, Package_Name & "Range_Attribute"); if not (Arg_Kind = A_Range_Attribute_Reference or else Arg_Kind = A_Discrete_Range_Attribute_Reference or else Arg_Kind = A_Discrete_Range_Attribute_Reference_As_Subtype_Definition) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Range_Attribute", Wrong_Kind => Arg_Kind); end if; if Nkind (Arg_Node) = N_Range_Constraint then -- one step down to N_Attruibute_Reference node Result_Node := Range_Expression (Arg_Node); else Result_Node := R_Node (Constraint); end if; return Node_To_Element_New (Starting_Element => Constraint, Node => Result_Node, Internal_Kind => A_Range_Attribute); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Constraint, Outer_Call => Package_Name & "Range_Attribute"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Range_Attribute", Ex => Ex, Arg_Element => Constraint); end Range_Attribute; ------------------------------------------------------------------------- function Discrete_Ranges (Constraint : Asis.Constraint) return Asis.Discrete_Range_List is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Constraint); Arg_Node : Node_Id; begin Check_Validity (Constraint, Package_Name & "Discrete_Ranges"); if not (Arg_Kind = An_Index_Constraint) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Discrete_Ranges", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Constraint); return N_To_E_List_New (List => Constraints (Arg_Node), Starting_Element => Constraint); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Constraint, Outer_Call => Package_Name & "Discrete_Ranges"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Discrete_Ranges", Ex => Ex, Arg_Element => Constraint); end Discrete_Ranges; ------------------------------------------------------------------------------ -- ??? PARTIALLY IMPLEMENTED, CANNOT PROCESS THE CASE WHEN -- ??? NORMALIZED = TRUE function Discriminant_Associations (Constraint : Asis.Constraint; Normalized : Boolean := False) return Asis.Discriminant_Association_List is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Constraint); Arg_Node : Node_Id; begin Check_Validity (Constraint, Package_Name & "Discriminant_Associations"); if not (Arg_Kind = A_Discriminant_Constraint) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Discriminant_Associations", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Constraint); if Normalized then return Normalized_Discriminant_Associations ( Constr_Elem => Constraint, Constr_Node => Arg_Node); else return N_To_E_List_New (List => Constraints (Arg_Node), Internal_Kind => A_Discriminant_Association, Starting_Element => Constraint); end if; exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Constraint, Bool_Par => Normalized, Outer_Call => Package_Name & "Discriminant_Associations"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Discriminant_Associations", Ex => Ex, Arg_Element => Constraint, Bool_Par_ON => Normalized); end Discriminant_Associations; ----------------------------------------------------------------------------- function Component_Subtype_Indication (Component_Definition : Asis.Definition) return Asis.Definition is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Component_Definition); Arg_Node : Node_Id; begin Check_Validity (Component_Definition, Package_Name & "Component_Subtype_Indication"); if not (Arg_Kind = A_Component_Definition) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Component_Subtype_Indication", Wrong_Kind => Arg_Kind); end if; Arg_Node := Sinfo.Subtype_Indication (R_Node (Component_Definition)); return Node_To_Element_New (Node => Arg_Node, Starting_Element => Component_Definition, Internal_Kind => A_Subtype_Indication); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Component_Definition, Outer_Call => Package_Name & "Component_Subtype_Indication"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Component_Subtype_Indication", Ex => Ex, Arg_Element => Component_Definition); end Component_Subtype_Indication; ----------------------------------------------------------------------------- function Discriminants (Definition : Asis.Definition) return Asis.Discriminant_Specification_List is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Definition); Arg_Node : Node_Id; begin Check_Validity (Definition, Package_Name & "Discriminations"); if not (Arg_Kind = A_Known_Discriminant_Part) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Discriminations", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Definition); return N_To_E_List_New (List => Discriminant_Specifications (Arg_Node), Starting_Element => Definition, Internal_Kind => A_Discriminant_Specification); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Definition, Outer_Call => Package_Name & "Discriminations"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Discriminations", Ex => Ex, Arg_Element => Definition); end Discriminants; ----------------------------------------------------------------------------- function Record_Components (Definition : Asis.Record_Definition; Include_Pragmas : Boolean := False) return Asis.Record_Component_List is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Definition); Arg_Node : Node_Id; Component_List_Node : Node_Id; Result_List : List_Id; -- All nodes except the Variant Node Variant_Part_Node : Node_Id; begin Check_Validity (Definition, Package_Name & "Record_Components"); if not (Arg_Kind = A_Record_Definition or else Arg_Kind = A_Variant) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Record_Components", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Definition); Component_List_Node := Component_List (Arg_Node); -- first, we should check the null record case: if Null_Present (Component_List_Node) then return Element_List'(1 => Node_To_Element_New (Node => Arg_Node, Starting_Element => Definition, Internal_Kind => A_Null_Component)); end if; Result_List := Component_Items (Component_List_Node); Variant_Part_Node := Variant_Part (Component_List_Node); if No (Variant_Part_Node) then return N_To_E_List_New (List => Result_List, Include_Pragmas => Include_Pragmas, Starting_Element => Definition); else return ( N_To_E_List_New (List => Result_List, Include_Pragmas => Include_Pragmas, Starting_Element => Definition) & Element_List'(1 => Node_To_Element_New (Node => Variant_Part_Node, Starting_Element => Definition, Internal_Kind => A_Variant_Part)) ); end if; exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Definition, Bool_Par => Include_Pragmas, Outer_Call => Package_Name & "Record_Components"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Record_Components", Ex => Ex, Arg_Element => Definition, Bool_Par_ON => Include_Pragmas); end Record_Components; ------------------------------------------------------------------------------ -- NOT IMPLEMENTED function Implicit_Components (Definition : Asis.Record_Definition) return Asis.Record_Component_List is begin Check_Validity (Definition, Package_Name & "Implicit_Components"); Not_Implemented_Yet (Diagnosis => Package_Name & "Implicit_Components"); -- ASIS_Failed is raised, Not_Implemented_Error status is set return Nil_Element_List; -- to make the code syntactically correct exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Definition, Outer_Call => Package_Name & "Implicit_Components"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Implicit_Components", Ex => Ex, Arg_Element => Definition); end Implicit_Components; ----------------------------------------------------------------------------- function Discriminant_Direct_Name (Variant_Part : Asis.Record_Component) return Asis.Name is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Variant_Part); Arg_Node : Node_Id; begin Check_Validity (Variant_Part, Package_Name & "Discriminant_Direct_Name"); if not (Arg_Kind = A_Variant_Part) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Discriminant_Direct_Name", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Variant_Part); return Node_To_Element_New (Node => Sinfo.Name (Arg_Node), Starting_Element => Variant_Part, Internal_Kind => An_Identifier); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Variant_Part, Outer_Call => Package_Name & "Discriminant_Direct_Name"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Discriminant_Direct_Name", Ex => Ex, Arg_Element => Variant_Part); end Discriminant_Direct_Name; ----------------------------------------------------------------------------- function Variants (Variant_Part : Asis.Record_Component; Include_Pragmas : Boolean := False) return Asis.Variant_List is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Variant_Part); Arg_Node : Node_Id; begin Check_Validity (Variant_Part, Package_Name & "Variants"); if not (Arg_Kind = A_Variant_Part) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Variants", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Variant_Part); return N_To_E_List_New (List => Variants (Arg_Node), Include_Pragmas => Include_Pragmas, Starting_Element => Variant_Part); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Variant_Part, Bool_Par => Include_Pragmas, Outer_Call => Package_Name & "Variants"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Variants", Ex => Ex, Arg_Element => Variant_Part, Bool_Par_ON => Include_Pragmas); end Variants; ----------------------------------------------------------------------------- function Variant_Choices (Variant : Asis.Variant) return Asis.Element_List is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Variant); Arg_Node : Node_Id; begin Check_Validity (Variant, Package_Name & "Variant_Choices"); if not (Arg_Kind = A_Variant) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Variant_Choices", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Variant); return Discrete_Choice_Node_To_Element_List (Choice_List => Discrete_Choices (Arg_Node), Starting_Element => Variant); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Variant, Outer_Call => Package_Name & "Variant_Choices"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Variant_Choices", Ex => Ex, Arg_Element => Variant); end Variant_Choices; ------------------------------------------------------------------------------ -- OPEN PROBLEMS: -- -- 1. Is using of the special list construction function -- Discrete_Choice_Node_To_Element_List really necessary here? We should -- try to replace it by non-special (trivial) constructor (all -- necessary local mapping items for Nodes in the Node List have -- already been defined - ???). -- -- IT SEEMS TO BE NOT ONLY OK, BUT REALLY NECESSARY HERE (03.11.95) ------------------------------------------------------------------------------ function Ancestor_Subtype_Indication (Definition : Asis.Definition) return Asis.Definition is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Definition); Arg_Node : Node_Id; begin Check_Validity (Definition, Package_Name & "Ancestor_Subtype_Indication"); if not (Arg_Kind = A_Private_Extension_Definition) then Raise_ASIS_Inappropriate_Element (Diagnosis => Package_Name & "Ancestor_Subtype_Indication", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Definition); return Node_To_Element_New (Node => Sinfo.Subtype_Indication (Arg_Node), Starting_Element => Definition, Internal_Kind => A_Subtype_Indication); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Definition, Outer_Call => Package_Name & "Ancestor_Subtype_Indication"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Ancestor_Subtype_Indication", Ex => Ex, Arg_Element => Definition); end Ancestor_Subtype_Indication; ----------------------------------------------------------------------------- function Visible_Part_Items (Definition : Asis.Definition; Include_Pragmas : Boolean := False) return Asis.Definition_List is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Definition); Arg_Node : Node_Id; begin Check_Validity (Definition, Package_Name & "Visible_Part_Items"); if not (Arg_Kind = A_Task_Definition or else Arg_Kind = A_Protected_Definition) then Raise_ASIS_Inappropriate_Element (Package_Name & "Visible_Part_Items", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Definition); return N_To_E_List_New (List => Visible_Declarations (Arg_Node), Include_Pragmas => Include_Pragmas, Starting_Element => Definition); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Definition, Bool_Par => Include_Pragmas, Outer_Call => Package_Name & "Visible_Part_Items"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Visible_Part_Items", Ex => Ex, Arg_Element => Definition, Bool_Par_ON => Include_Pragmas); end Visible_Part_Items; ----------------------------------------------------------------------------- function Private_Part_Items (Definition : Asis.Definition; Include_Pragmas : Boolean := False) return Asis.Definition_List is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Definition); Arg_Node : Node_Id; begin Check_Validity (Definition, Package_Name & "Private_Part_Items"); if not (Arg_Kind = A_Task_Definition or else Arg_Kind = A_Protected_Definition) then Raise_ASIS_Inappropriate_Element (Package_Name & "Private_Part_Items", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Definition); return N_To_E_List_New (List => Private_Declarations (Arg_Node), Include_Pragmas => Include_Pragmas, Starting_Element => Definition); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Definition, Bool_Par => Include_Pragmas, Outer_Call => Package_Name & "Private_Part_Items"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Private_Part_Items", Ex => Ex, Arg_Element => Definition, Bool_Par_ON => Include_Pragmas); end Private_Part_Items; ----------------------------------------------------------------------------- function Is_Private_Present (Definition : Asis.Definition) return Boolean is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Definition); Arg_Node : Node_Id; begin Check_Validity (Definition, Package_Name & "Is_Private_Present"); if not (Arg_Kind = A_Task_Definition or else Arg_Kind = A_Protected_Definition) then -- unexpected element return False; end if; Arg_Node := Node (Definition); return Present (Private_Declarations (Arg_Node)); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Argument => Definition, Outer_Call => Package_Name & "Is_Private_Present"); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Is_Private_Present", Ex => Ex, Arg_Element => Definition); end Is_Private_Present; ----------------------------------------------------------------------------- end Asis.Definitions;
with Orka; package body Integrators.RK4 is use Vectors; use GL.Types; use type Orka.Float_64; package Linear_Integrator is procedure Integrate (Current : in out Linear_State; Force : not null access function (State : Linear_State; Time : Double) return Vectors.Vector4; T, DT : Double); end Linear_Integrator; package Angular_Integrator is procedure Integrate (Current : in out Angular_State; Torque : not null access function (State : Angular_State; Time : Double) return Vectors.Vector4; T, DT : Double); end Angular_Integrator; package body Linear_Integrator is type Derivative is record DX, DP : Vectors.Vector4 := Vectors.Zero_Point; end record; procedure Update (State : in out Linear_State; Motion : Derivative; DT : Double) is begin State.Position := State.Position + Motion.DX * DT; State.Momentum := State.Momentum + Motion.DP * DT; -- Recompute velocity after updating momentum State.Velocity := State.Momentum * State.Inverse_Mass; end Update; function Evaluate (Initial : Linear_State; Force : not null access function (State : Linear_State; Time : Double) return Vectors.Vector4; T, DT : Double; Motion : Derivative) return Derivative is Next : Linear_State := Initial; begin Update (Next, Motion, DT); return Result : Derivative do Result.DX := Next.Velocity; Result.DP := Force (Next, T + DT); end return; end Evaluate; procedure Integrate (Current : in out Linear_State; Force : not null access function (State : Linear_State; Time : Double) return Vectors.Vector4; T, DT : Double) is Initial, A, B, C, D : Derivative; DX_DT, DP_DT : Vectors.Vector4; begin A := Evaluate (Current, Force, T, 0.0, Initial); B := Evaluate (Current, Force, T, DT * 0.5, A); C := Evaluate (Current, Force, T, DT * 0.5, B); D := Evaluate (Current, Force, T, DT, C); DX_DT := 1.0 / 6.0 * (A.DX + 2.0 * (B.DX + C.DX) + D.DX); DP_DT := 1.0 / 6.0 * (A.DP + 2.0 * (B.DP + C.DP) + D.DP); Update (Current, (DX => DX_DT, DP => DP_DT), DT); end Integrate; end Linear_Integrator; package body Angular_Integrator is use Quaternions; type Derivative is record Spin : Quaternions.Quaternion := Quaternions.Identity_Value; Torque : Vectors.Vector4 := Vectors.Zero_Point; end record; function Quaternion (Value : Vectors.Vector4) return Quaternions.Quaternion is use Orka; begin return Result : Quaternions.Quaternion := Quaternions.Quaternion (Value) do Result (W) := 0.0; end return; end Quaternion; function Q (Value : Vectors.Vector4) return Quaternions.Quaternion is (Quaternions.Quaternion (Value)) with Inline; function V (Value : Quaternions.Quaternion) return Vectors.Vector4 is (Vectors.Vector4 (Value)) with Inline; procedure Update (State : in out Angular_State; Motion : Derivative; DT : Double) is begin State.Orientation := Q (V (State.Orientation) + V (Motion.Spin) * DT); State.Angular_Momentum := State.Angular_Momentum + Motion.Torque * DT; -- Recompute angular velocity after updating angular momentum State.Angular_Velocity := State.Angular_Momentum * State.Inverse_Inertia; State.Orientation := Quaternions.Normalize (State.Orientation); pragma Assert (Quaternions.Normalized (State.Orientation)); end Update; function Evaluate (Initial : Angular_State; Torque : not null access function (State : Angular_State; Time : Double) return Vectors.Vector4; T, DT : Double; Motion : Derivative) return Derivative is Next : Angular_State := Initial; begin Update (Next, Motion, DT); return Result : Derivative do Result.Spin := Q (0.5 * V (Quaternion (Next.Angular_Velocity) * Next.Orientation)); Result.Torque := Torque (Next, T + DT); end return; end Evaluate; procedure Integrate (Current : in out Angular_State; Torque : not null access function (State : Angular_State; Time : Double) return Vectors.Vector4; T, DT : Double) is Initial, A, B, C, D : Derivative; D_Spin : Quaternions.Quaternion; D_Torque : Vectors.Vector4; begin A := Evaluate (Current, Torque, T, 0.0, Initial); B := Evaluate (Current, Torque, T, DT * 0.5, A); C := Evaluate (Current, Torque, T, DT * 0.5, B); D := Evaluate (Current, Torque, T, DT, C); D_Spin := Q (1.0 / 6.0 * (V (A.Spin) + 2.0 * (V (B.Spin) + V (C.Spin)) + V (D.Spin))); D_Torque := 1.0 / 6.0 * (A.Torque + 2.0 * (B.Torque + C.Torque) + D.Torque); Update (Current, (Spin => D_Spin, Torque => D_Torque), DT); end Integrate; end Angular_Integrator; function Create_Integrator (Subject : Physics_Object'Class; Position : Vectors.Vector4; Velocity : Vectors.Vector4; Orientation : Quaternions.Quaternion := Quaternions.Identity_Value) return RK4_Integrator is begin return Result : RK4_Integrator do Result.Linear.Position := Position; Result.Linear.Momentum := Velocity * (1.0 / Subject.Inverse_Mass); Result.Angular.Orientation := Quaternions.Normalize (Orientation); end return; end Create_Integrator; overriding procedure Integrate (Object : in out RK4_Integrator; Subject : in out Physics_Object'Class; T, DT : GL.Types.Double) is Total_Force : Vectors.Vector4 := Vectors.Zero_Direction; Total_Torque : Vectors.Vector4 := Vectors.Zero_Direction; -- FIXME Just provide 2 vectors instead of 2 functions? (only allow time-invariant systems) function Force (State : Linear_State; Time : Double) return Vectors.Vector4 is (Total_Force); function Torque (State : Angular_State; Time : Double) return Vectors.Vector4 is (Total_Torque); begin Subject.Update (Object.State, Duration (DT)); declare Center_Of_Mass : constant Vectors.Vector4 := Subject.Center_Of_Mass; Forces : Force_Array_Access := Subject.Forces; begin for Force_Point of Forces.all loop declare Force : Vectors.Vector4 := Force_Point.Force; Offset : Vectors.Vector4 := Force_Point.Point - Center_Of_Mass; begin Quaternions.Rotate_At_Origin (Force, Object.Angular.Orientation); Quaternions.Rotate_At_Origin (Offset, Object.Angular.Orientation); Total_Force := Total_Force + Force; Total_Torque := Total_Torque - Vectors.Cross (Force, Offset); end; end loop; Free (Forces); exception when others => Free (Forces); raise; end; declare Moments : Moment_Array_Access := Subject.Moments; begin for Moment of Moments.all loop declare Torque : Vectors.Vector4 := Moment; begin Quaternions.Rotate_At_Origin (Torque, Object.Angular.Orientation); Total_Torque := Total_Torque + Torque; end; end loop; Free (Moments); exception when others => Free (Moments); raise; end; Object.Linear.Inverse_Mass := Subject.Inverse_Mass; Object.Angular.Inverse_Inertia := Subject.Inverse_Inertia; Linear_Integrator.Integrate (Object.Linear, Force'Access, T, DT); Angular_Integrator.Integrate (Object.Angular, Torque'Access, T, DT); end Integrate; overriding function State (Object : RK4_Integrator) return Integrator_State is (Position => Object.Linear.Position, Momentum => Object.Linear.Momentum, Velocity => Object.Linear.Velocity, Orientation => Object.Angular.Orientation, Angular_Momentum => Object.Angular.Angular_Momentum, Angular_Velocity => Object.Angular.Angular_Velocity); end Integrators.RK4;
------------------------------------------------------------------------------ -- Copyright (c) 2014, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Natools.S_Expressions.Templates.Generic_Integers provides a template -- -- interpreter for integer rendering. -- -- The following commands are recognized: -- -- (align "left|right|center") -- -- (base "symbol 0" "symbol 1" "symbol 2" ...) -- -- (left-padding "symbol") -- -- (image (0 "symbol 0") (2 "symbol 2") ...) -- -- (max-width "max width" ["overflow text"]) -- -- (min-width "min width") -- -- (padding "left-symbol" "right-symbol") -- -- (padding "symbol") -- -- (prefix ("prefix" 0 (10 20) ...) (("prefix" width) 2) ...) -- -- (right-padding "symbol") -- -- (sign "plus sign" ["minus sign"]) -- -- (suffix ("suffix" 0 (10 20) ...) (("suffix" width) 2) ...) -- -- (width "fixed width") -- -- (width "min width" "max width" ["overflow text"]) -- -- Top-level atoms are taken as the image for the next number. -- ------------------------------------------------------------------------------ with Ada.Containers.Ordered_Maps; with Ada.Streams; with Natools.References; with Natools.S_Expressions.Atom_Buffers; with Natools.S_Expressions.Atom_Refs; with Natools.S_Expressions.Lockable; with Natools.Storage_Pools; generic type T is range <>; with function "<" (Left, Right : T) return Boolean is <>; package Natools.S_Expressions.Templates.Generic_Integers is pragma Preelaborate; -------------------------- -- High-Level Interface -- -------------------------- type Format is tagged private; function Render (Value : T; Template : Format) return Atom; -- Render Value according to Template procedure Parse (Template : in out Format; Expression : in out Lockable.Descriptor'Class); -- Read Expression to fill Template procedure Render (Output : in out Ada.Streams.Root_Stream_Type'Class; Template : in out Lockable.Descriptor'Class; Value : in T); -- Read a rendering format from Template and use it on Value procedure Render (Output : in out Ada.Streams.Root_Stream_Type'Class; Default_Format : in Format; Template : in out Lockable.Descriptor'Class; Value : in T); -- Read a rendering format from Template, using defaults -- from Default_Format, and use it on Value. --------------------- -- Auxiliary Types -- --------------------- type Alignment is (Left_Aligned, Centered, Right_Aligned); type Width is range 0 .. 10000; subtype Base_T is T'Base; subtype Natural_T is Base_T range 0 .. Base_T'Last; type Atom_Array is array (Natural_T range <>) of Atom_Refs.Immutable_Reference; function Create (Atom_List : in out S_Expressions.Descriptor'Class) return Atom_Array; -- Build an array consisting of consecutive atoms found in Atom_List package Atom_Arrays is new References (Atom_Array, Storage_Pools.Access_In_Default_Pool'Storage_Pool, Storage_Pools.Access_In_Default_Pool'Storage_Pool); function Create (Atom_List : in out S_Expressions.Descriptor'Class) return Atom_Arrays.Immutable_Reference; -- Build an array reference consisting of -- consecutive atoms found in Atom_List. function Decimal return Atom_Arrays.Immutable_Reference with Post => not Decimal'Result.Is_Empty; -- Return a reference to usual decimal representation type Interval is record First, Last : T; end record with Dynamic_Predicate => not (Interval.Last < Interval.First); function "<" (Left, Right : Interval) return Boolean is (Left.Last < Right.First); -- Strict non-overlap comparison type Displayed_Atom is record Image : Atom_Refs.Immutable_Reference; Width : Generic_Integers.Width; end record; package Atom_Maps is new Ada.Containers.Ordered_Maps (Interval, Displayed_Atom, "<"); function Next_Index (Map : Atom_Maps.Map) return T is (if Map.Is_Empty then T'First else Map.Last_Key.Last + 1); -- Index of the next element to insert in sequential lists procedure Exclude (Map : in out Atom_Maps.Map; Values : in Interval); -- Remove the given interval from the map procedure Include (Map : in out Atom_Maps.Map; Values : in Interval; Image : in Atom_Refs.Immutable_Reference; Width : in Generic_Integers.Width); -- Add Image to the given interval, overwriting any existing values. -- If Image is empty, behave like Exclude. procedure Parse_Single_Affix (Map : in out Atom_Maps.Map; Expression : in out Lockable.Descriptor'Class); -- Parse Expression as an affix atom, followed by single numbers (atoms) -- or ranges (lists of two atoms). procedure Parse (Map : in out Atom_Maps.Map; Expression : in out Lockable.Descriptor'Class); -- Parse Expression as a list of single image expressions (see above) --------------------- -- Format Mutators -- --------------------- procedure Set_Align (Object : in out Format; Value : in Alignment); procedure Append_Image (Object : in out Format; Image : in Atom_Refs.Immutable_Reference); procedure Append_Image (Object : in out Format; Image : in Atom); procedure Remove_Image (Object : in out Format; Value : in T); procedure Set_Image (Object : in out Format; Value : in T; Image : in Atom_Refs.Immutable_Reference); procedure Set_Image (Object : in out Format; Value : in T; Image : in Atom); procedure Set_Left_Padding (Object : in out Format; Symbol : in Atom_Refs.Immutable_Reference); procedure Set_Left_Padding (Object : in out Format; Symbol : in Atom); procedure Set_Maximum_Width (Object : in out Format; Value : in Width); procedure Set_Minimum_Width (Object : in out Format; Value : in Width); procedure Set_Negative_Sign (Object : in out Format; Sign : in Atom_Refs.Immutable_Reference); procedure Set_Negative_Sign (Object : in out Format; Sign : in Atom); procedure Set_Overflow_Message (Object : in out Format; Message : in Atom_Refs.Immutable_Reference); procedure Set_Overflow_Message (Object : in out Format; Message : in Atom); procedure Set_Positive_Sign (Object : in out Format; Sign : in Atom_Refs.Immutable_Reference); procedure Set_Positive_Sign (Object : in out Format; Sign : in Atom); procedure Remove_Prefix (Object : in out Format; Value : in T); procedure Set_Prefix (Object : in out Format; Value : in T; Prefix : in Atom_Refs.Immutable_Reference; Width : in Generic_Integers.Width); procedure Set_Prefix (Object : in out Format; Value : in T; Prefix : in Atom); procedure Set_Prefix (Object : in out Format; Value : in T; Prefix : in Atom; Width : in Generic_Integers.Width); procedure Remove_Prefix (Object : in out Format; Values : in Interval); procedure Set_Prefix (Object : in out Format; Values : in Interval; Prefix : in Atom_Refs.Immutable_Reference; Width : in Generic_Integers.Width); procedure Set_Prefix (Object : in out Format; Values : in Interval; Prefix : in Atom); procedure Set_Prefix (Object : in out Format; Values : in Interval; Prefix : in Atom; Width : in Generic_Integers.Width); procedure Set_Right_Padding (Object : in out Format; Symbol : in Atom_Refs.Immutable_Reference); procedure Set_Right_Padding (Object : in out Format; Symbol : in Atom); procedure Remove_Suffix (Object : in out Format; Value : in T); procedure Set_Suffix (Object : in out Format; Value : in T; Suffix : in Atom_Refs.Immutable_Reference; Width : in Generic_Integers.Width); procedure Set_Suffix (Object : in out Format; Value : in T; Suffix : in Atom); procedure Set_Suffix (Object : in out Format; Value : in T; Suffix : in Atom; Width : in Generic_Integers.Width); procedure Remove_Suffix (Object : in out Format; Values : in Interval); procedure Set_Suffix (Object : in out Format; Values : in Interval; Suffix : in Atom_Refs.Immutable_Reference; Width : in Generic_Integers.Width); procedure Set_Suffix (Object : in out Format; Values : in Interval; Suffix : in Atom); procedure Set_Suffix (Object : in out Format; Values : in Interval; Suffix : in Atom; Width : in Generic_Integers.Width); procedure Set_Symbols (Object : in out Format; Symbols : in Atom_Arrays.Immutable_Reference); procedure Set_Symbols (Object : in out Format; Expression : in out S_Expressions.Descriptor'Class); private Base_10 : Atom_Arrays.Immutable_Reference; -- Cache for the often-used decimal representation procedure Reverse_Render (Value : in Natural_T; Symbols : in Atom_Array; Output : in out Atom_Buffers.Atom_Buffer; Length : out Width) with Pre => Symbols'Length >= 2 and Symbols'First = 0; -- Create a little-endian image of Value using the given symbol table type Format is tagged record Symbols : Atom_Arrays.Immutable_Reference; Positive_Sign : Atom_Refs.Immutable_Reference; Negative_Sign : Atom_Refs.Immutable_Reference; Minimum_Width : Width := 0; Align : Alignment := Right_Aligned; Left_Padding : Atom_Refs.Immutable_Reference; Right_Padding : Atom_Refs.Immutable_Reference; Maximum_Width : Width := Width'Last; Overflow_Message : Atom_Refs.Immutable_Reference; Images : Atom_Maps.Map; Prefix : Atom_Maps.Map; Suffix : Atom_Maps.Map; end record; end Natools.S_Expressions.Templates.Generic_Integers;
-- The Beer-Ware License (revision 42) -- -- Jacob Sparre Andersen <jacob@jacob-sparre.dk> wrote this. As long as you -- retain this notice you can do whatever you want with this stuff. If we meet -- some day, and you think this stuff is worth it, you can buy me a beer in -- return. -- -- Jacob Sparre Andersen with Interfaces.C.Strings; package body Sound.Mono is procedure Close (Line : in out Line_Type) is use type Interfaces.C.int; Error : Interfaces.C.int; begin Error := snd_pcm_close (Line); if Error /= 0 then raise Program_Error with "snd_pcm_close failed: " & Error'Img; end if; end Close; function Is_Open (Line : in Line_Type) return Boolean is use Sound.ALSA; begin case snd_pcm_state (Line) is when Prepared | Running => return True; when Open | Setup | XRun | Draining | Paused | Suspended | Disconnected => return False; end case; end Is_Open; procedure Open (Line : in out Line_Type; Mode : in Line_Mode; Resolution : in out Sample_Frequency; Buffer_Size : in out Duration; Period : in out Duration) is use Interfaces.C, Interfaces.C.Strings, Sound.ALSA; Name : aliased char_array := To_C ("plughw:0,0"); Error : Interfaces.C.int; Local_Line : aliased Line_Type := Line; Settings : aliased Sound.ALSA.snd_pcm_hw_params_t; begin Error := snd_pcm_open (pcmp => Local_Line'Access, name => To_Chars_Ptr (Name'Unchecked_Access), stream => Sound.ALSA.Value (Mode), mode => 0); if Error /= 0 then raise Program_Error with "Error code (snd_pcm_open): " & Error'Img; end if; Clear_Settings : begin Error := snd_pcm_hw_params_any (pcm => Local_Line, params => Settings'Access); if Error /= 0 then raise Program_Error with "Error code (snd_pcm_hw_params_any): " & Error'Img; end if; end Clear_Settings; Set_Resampling_Rate : begin Error := snd_pcm_hw_params_set_rate_resample (pcm => Local_Line, params => Settings'Access, val => False); if Error /= 0 then raise Program_Error with "Error code (snd_pcm_hw_params_set_rate_resample): " & Error'Img; end if; end Set_Resampling_Rate; Set_Sampling_Layout : begin Error := snd_pcm_hw_params_set_access (pcm => Local_Line, params => Settings'Access, val => Read_Write_Interleaved); if Error /= 0 then raise Program_Error with "Error code (snd_pcm_hw_params_set_access): " & Error'Img; end if; end Set_Sampling_Layout; Set_Recording_Format : begin Error := snd_pcm_hw_params_set_format (pcm => Local_Line, params => Settings'Access, format => Sound.ALSA.Signed_16_Bit); if Error /= 0 then raise Program_Error with "Error code (snd_pcm_hw_params_set_format): " & Error'Img; end if; end Set_Recording_Format; Set_Channel_Count : begin Error := snd_pcm_hw_params_set_channels (pcm => Local_Line, params => Settings'Access, val => 1); if Error /= 0 then raise Program_Error with "Error code (snd_pcm_hw_params_set_channels): " & Error'Img; end if; end Set_Channel_Count; Set_Sample_Frequency : declare Sample_Rate : aliased Interfaces.C.unsigned := Interfaces.C.unsigned (Resolution); Approximation : aliased Sound.ALSA.Approximation_Direction := 0; begin Error := snd_pcm_hw_params_set_rate_near (pcm => Local_Line, params => Settings'Access, val => Sample_Rate'Access, dir => Approximation'Access); if Error /= 0 then raise Program_Error with "Error code (snd_pcm_hw_params_set_rate_near): " & Error'Img; end if; Resolution := Sample_Frequency (Sample_Rate); end Set_Sample_Frequency; Set_Buffer_Time : declare Buffer_Time : aliased Interfaces.C.unsigned := Interfaces.C.unsigned (1_000_000 * Buffer_Size); Approximation : aliased Sound.ALSA.Approximation_Direction := 0; begin Error := snd_pcm_hw_params_set_buffer_time_near (pcm => Local_Line, params => Settings'Access, val => Buffer_Time'Access, dir => Approximation'Access); if Error /= 0 then raise Program_Error with "Error code (snd_pcm_hw_params_set_buffer_time_near): " & Error'Img; end if; Buffer_Size := Duration (Buffer_Time) / 1_000_000.0; end Set_Buffer_Time; Set_Period : declare Period_Time : aliased Interfaces.C.unsigned := Interfaces.C.unsigned (1_000_000 * Period); Approximation : aliased Sound.ALSA.Approximation_Direction := 0; begin Error := snd_pcm_hw_params_set_period_time_near (pcm => Local_Line, params => Settings'Access, val => Period_Time'Access, dir => Approximation'Access); if Error /= 0 then raise Program_Error with "Error code (snd_pcm_hw_params_set_period_time_near): " & Error'Img; end if; Period := Duration (Period_Time) / 1_000_000.0; end Set_Period; Register_Settings : begin Error := snd_pcm_hw_params (pcm => Local_Line, params => Settings'Access); if Error /= 0 then raise Program_Error with "Error code (snd_pcm_hw_params): " & Error'Img; end if; end Register_Settings; Line := Local_Line; end Open; procedure Read (Line : in Line_Type; Item : out Frame_Array; Last : out Natural) is pragma Unmodified (Item); -- As we cheat with "function snd_pcm_readi". function snd_pcm_readi (pcm : in Line_Type; buffer : in Frame_Array; -- actually "out" size : in ALSA.snd_pcm_uframes_t) return ALSA.snd_pcm_sframes_t; pragma Import (C, snd_pcm_readi); use type Sound.ALSA.snd_pcm_sframes_t; Received_Frame_Count : Sound.ALSA.snd_pcm_sframes_t; begin Received_Frame_Count := snd_pcm_readi (pcm => Line, buffer => Item, size => Item'Length); if Received_Frame_Count < 0 then raise Program_Error with "snd_pcm_readi failed: " & Received_Frame_Count'Img; else Last := Item'First - 1 + Natural (Received_Frame_Count); end if; end Read; procedure Write (Line : in Line_Type; Item : in Frame_Array; Last : out Natural) is function snd_pcm_writei (pcm : in Line_Type; buffer : in Frame_Array; size : in ALSA.snd_pcm_uframes_t) return ALSA.snd_pcm_sframes_t; pragma Import (C, snd_pcm_writei); use type Sound.ALSA.snd_pcm_sframes_t; Written_Frame_Count : Sound.ALSA.snd_pcm_sframes_t; begin Written_Frame_Count := snd_pcm_writei (pcm => Line, buffer => Item, size => Item'Length); if Written_Frame_Count < 0 then raise Program_Error with "snd_pcm_writei failed: " & Written_Frame_Count'Img; else Last := Item'First - 1 + Natural (Written_Frame_Count); end if; end Write; end Sound.Mono;
with Ada.Integer_Text_IO; procedure Sum_Digits is -- sums the digits of an integer (in whatever base) -- outputs the sum (in base 10) function Sum_Of_Digits(N: Natural; Base: Natural := 10) return Natural is Sum: Natural := 0; Val: Natural := N; begin while Val > 0 loop Sum := Sum + (Val mod Base); Val := Val / Base; end loop; return Sum; end Sum_Of_Digits; use Ada.Integer_Text_IO; begin -- main procedure Sum_Digits Put(Sum_OF_Digits(1)); -- 1 Put(Sum_OF_Digits(12345)); -- 15 Put(Sum_OF_Digits(123045)); -- 15 Put(Sum_OF_Digits(123045, 50)); -- 104 Put(Sum_OF_Digits(16#fe#, 10)); -- 11 Put(Sum_OF_Digits(16#fe#, 16)); -- 29 Put(Sum_OF_Digits(16#f0e#, 16)); -- 29 end Sum_Digits;
with Test_Solution; use Test_Solution; package problem_15 is type Int128 is range -2**127 .. 2**127 - 1; function Solution_1 return Int128; procedure Test_Solution_1; function Get_Solutions return Solution_Case; end problem_15;
package FRUnaligned1 is type r is array (1 .. 72) of Boolean; pragma Pack (r); type s is record x : Boolean; y : r; end record; for s use record x at 0 range 0 .. 0; y at 0 range 1 .. 72; end record; end FRUnaligned1;
-- convert UCD/CaseFolding.txt -- bin/ucd_casefolding $UCD/CaseFolding.txt > ../source/strings/a-uccafo.ads with Ada.Command_Line; use Ada.Command_Line; with Ada.Containers.Ordered_Maps; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Ada.Strings; use Ada.Strings; with Ada.Strings.Fixed; use Ada.Strings.Fixed; with Ada.Strings.Maps; use Ada.Strings.Maps; with Ada.Strings.Wide_Wide_Unbounded; use Ada.Strings.Wide_Wide_Unbounded; with Ada.Text_IO; use Ada.Text_IO; procedure ucd_casefolding is Hexadecimal_Digit_Set : constant Character_Set := To_Set ("0123456789ABCDEF"); function Value (S : String) return Wide_Wide_Character is Img : constant String := "Hex_" & (1 .. 8 - S'Length => '0') & S; begin return Wide_Wide_Character'Value (Img); end Value; procedure Put_16 (Item : Integer) is S : String (1 .. 8); -- "16#XXXX#" begin Put (S, Item, Base => 16); S (1) := '1'; S (2) := '6'; S (3) := '#'; for I in reverse 4 .. 6 loop if S (I) = '#' then S (4 .. I) := (others => '0'); exit; end if; end loop; Put (S); end Put_16; package CF_Maps is new Ada.Containers.Ordered_Maps ( Wide_Wide_Character, Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); use CF_Maps; function Compressible (I : CF_Maps.Cursor) return Boolean is begin return Length (Element (I)) = 1 and then Wide_Wide_Character'Pos (Element (Element (I), 1)) - Wide_Wide_Character'Pos (Key (I)) in -128 .. 127; end Compressible; type Kind_Type is (C, F, S, T); -- common, full, simple, special Table : array (Kind_Type) of aliased CF_Maps.Map; type Bit is (In_16, In_32); function Get_Bit (C : Wide_Wide_Character) return Bit is begin if C > Wide_Wide_Character'Val (16#FFFF#) then return In_32; else return In_16; end if; end Get_Bit; subtype Len is Integer range 1 .. 3; Num : array (Kind_Type, Bit, Len, Boolean) of Natural; begin declare File : Ada.Text_IO.File_Type; begin Open (File, In_File, Argument (1)); while not End_Of_File (File) loop declare Line : constant String := Get_Line (File); P : Positive := Line'First; N : Natural; Token_First : Positive; Token_Last : Natural; Source : Wide_Wide_Character; Dest : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Kind : Kind_Type; begin if Line'Length = 0 or else Line (P) = '#' then null; -- comment else Find_Token ( Line (P .. Line'Last), Hexadecimal_Digit_Set, Inside, Token_First, Token_Last); if Token_First /= P then raise Data_Error with Line & " -- A"; end if; Source := Value (Line (Token_First .. Token_Last)); P := Token_Last + 1; if Line (P) /= ';' then raise Data_Error with Line & " -- B"; end if; P := P + 1; -- skip ';' N := Index_Non_Blank (Line (P .. Line'Last)); if N = 0 then raise Data_Error with Line & " -- C"; end if; P := N; case Line (P) is when 'C' => Kind := C; when 'F' => Kind := F; when 'S' => Kind := S; when 'T' => Kind := T; when others => raise Data_Error with Line & " -- D"; end case; P := P + 1; -- skip kind if Line (P) /= ';' then raise Data_Error with Line & " -- E"; end if; P := P + 1; -- skip ';' Dest := Null_Unbounded_Wide_Wide_String; loop N := Index_Non_Blank (Line (P .. Line'Last)); if N = 0 then raise Data_Error with Line & " -- F"; end if; P := N; exit when Line (P) = ';'; Find_Token ( Line (P .. Line'Last), Hexadecimal_Digit_Set, Inside, Token_First, Token_Last); if Token_First /= P then raise Data_Error with Line & " -- G"; end if; Append (Dest, Value (Line (Token_First .. Token_Last))); P := Token_Last + 1; end loop; Insert (Table (Kind), Source, Dest); end if; end; end loop; Close (File); end; for Kind in Kind_Type loop for B in Bit loop for L in Len loop for Compressed in Boolean loop Num (Kind, B, L, Compressed) := 0; end loop; end loop; end loop; declare I : CF_Maps.Cursor := First (Table (Kind)); begin while Has_Element (I) loop declare B : Bit := Get_Bit (Key (I)); L : Len; begin if Compressible (I) then declare K : Wide_Wide_Character := Key (I); E : Wide_Wide_Character := Element (Element (I), 1); N : CF_Maps.Cursor := Next (I); RLE : Positive := 1; Compressed : Boolean; begin while Has_Element (N) and then RLE < 255 and then Compressible (N) and then Key (N) = Wide_Wide_Character'Succ (K) and then Element (Element (N), 1) = Wide_Wide_Character'Succ (E) loop K := Key (N); E := Element (Element (N), 1); N := Next (N); RLE := RLE + 1; end loop; I := N; Compressed := RLE > 1; Num (Kind, B, 1, Compressed) := Num (Kind, B, 1, Compressed) + 1; end; else L := Length (Element (I)); Num (Kind, B, L, False) := Num (Kind, B, L, False) + 1; I := Next (I); end if; end; end loop; end; end loop; Put_Line ("pragma License (Unrestricted);"); Put_Line ("-- implementation unit, translated from CaseFolding.txt"); Put_Line ("package Ada.UCD.Case_Folding is"); Put_Line (" pragma Pure;"); New_Line; for Kind in Kind_Type loop Put (" "); Put (Kind_Type'Image (Kind)); Put ("_Total : constant := "); Put (Integer (Length (Table (Kind))), Width => 1); Put (";"); New_Line; end loop; New_Line; Put_Line (" type Run_Length_8 is mod 2 ** 8;"); New_Line; Put_Line (" type Compressed_Item_Type is record"); Put_Line (" Start : UCS_2;"); Put_Line (" Length : Run_Length_8;"); Put_Line (" Diff : Difference_8;"); Put_Line (" end record;"); Put_Line (" pragma Suppress_Initialization (Compressed_Item_Type);"); Put_Line (" for Compressed_Item_Type'Size use 32; -- 16 + 8 + 8"); Put_Line (" for Compressed_Item_Type use record"); Put_Line (" Start at 0 range 0 .. 15;"); Put_Line (" Length at 0 range 16 .. 23;"); Put_Line (" Diff at 0 range 24 .. 31;"); Put_Line (" end record;"); New_Line; Put_Line (" type Compressed_Type is array (Positive range <>) of Compressed_Item_Type;"); Put_Line (" pragma Suppress_Initialization (Compressed_Type);"); Put_Line (" for Compressed_Type'Component_Size use 32;"); New_Line; Put (" subtype C_Table_XXXXx1_Type is Map_16x1_Type (1 .. "); Put (Num (C, In_16, 1, False), Width => 1); Put (");"); New_Line; Put (" subtype C_Table_XXXXx1_Compressed_Type is Compressed_Type (1 .. "); Put (Num (C, In_16, 1, True), Width => 1); Put (");"); New_Line; Put (" subtype C_Table_1XXXXx1_Compressed_Type is Compressed_Type (1 .. "); Put (Num (C, In_32, 1, True), Width => 1); Put (");"); New_Line; if Num (C, In_16, 2, False) /= 0 or else Num (C, In_16, 3, False) /= 0 or else Num (C, In_32, 1, False) /= 0 or else Num (C, In_32, 2, False) /= 0 or else Num (C, In_32, 3, False) /= 0 then raise Data_Error with "num of C"; end if; Put (" subtype F_Table_XXXXx2_Type is Map_16x2_Type (1 .. "); Put (Num (F, In_16, 2, False), Width => 1); Put (");"); New_Line; Put (" subtype F_Table_XXXXx3_Type is Map_16x3_Type (1 .. "); Put (Num (F, In_16, 3, False), Width => 1); Put (");"); New_Line; if Num (F, In_16, 1, False) /= 0 or else Num (F, In_16, 1, True) /= 0 or else Num (F, In_32, 1, False) /= 0 or else Num (F, In_32, 1, True) /= 0 or else Num (F, In_32, 2, False) /= 0 or else Num (F, In_32, 3, False) /= 0 then raise Data_Error with "num of S"; end if; Put (" subtype S_Table_XXXXx1_Type is Map_16x1_Type (1 .. "); Put (Num (S, In_16, 1, False), Width => 1); Put (");"); New_Line; Put (" subtype S_Table_XXXXx1_Compressed_Type is Compressed_Type (1 .. "); Put (Num (S, In_16, 1, True), Width => 1); Put (");"); New_Line; if Num (S, In_16, 2, False) /= 0 or else Num (S, In_16, 3, False) /= 0 or else Num (S, In_32, 1, False) /= 0 or else Num (S, In_32, 1, True) /= 0 or else Num (S, In_32, 2, False) /= 0 or else Num (S, In_32, 3, False) /= 0 then raise Data_Error with "num of S"; end if; Put (" subtype T_Table_XXXXx1_Type is Map_16x1_Type (1 .. "); Put (Num (T, In_16, 1, False), Width => 1); Put (");"); New_Line; if Num (T, In_16, 1, True) /= 0 or else Num (T, In_16, 2, False) /= 0 or else Num (T, In_16, 3, False) /= 0 or else Num (T, In_32, 1, False) /= 0 or else Num (T, In_32, 1, True) /= 0 or else Num (T, In_32, 2, False) /= 0 or else Num (T, In_32, 3, False) /= 0 then raise Data_Error with "num of S"; end if; New_Line; for Kind in Kind_Type loop for B in Bit loop for L in Len loop for Compressed in Boolean loop if Num (Kind, B, L, Compressed) /= 0 then Put (" "); Put (Kind_Type'Image (Kind)); Put ("_Table_"); if B = In_32 then Put ("1"); end if; Put ("XXXXx"); Put (L, Width => 1); if Compressed then Put ("_Compressed"); end if; Put (" : constant "); Put (Kind_Type'Image (Kind)); Put ("_Table_"); if B = In_32 then Put ("1"); end if; Put ("XXXXx"); Put (L, Width => 1); if Compressed then Put ("_Compressed"); end if; Put ("_Type := ("); New_Line; declare Offset : Integer := 0; I : CF_Maps.Cursor := First (Table (Kind)); Second : Boolean := False; begin if B = In_32 then Offset := 16#10000#; end if; while Has_Element (I) loop declare Item_B : Bit := Get_Bit (Key (I)); Item_L : Len := Length (Element (I)); Item_RLE : Positive := 1; N : CF_Maps.Cursor := Next (I); begin if Compressible (I) then declare K : Wide_Wide_Character := Key (I); E : Wide_Wide_Character := Element (Element (I), 1); begin while Has_Element (N) and then Item_RLE < 255 and then Compressible (N) and then Key (N) = Wide_Wide_Character'Succ (K) and then Element (Element (N), 1) = Wide_Wide_Character'Succ (E) loop K := Key (N); E := Element (Element (N), 1); N := Next (N); Item_RLE := Item_RLE + 1; end loop; end; end if; if Item_B = B and then Item_L = L and then (Item_RLE > 1) = Compressed then if Second then Put (","); New_Line; end if; Put (" "); if Num (Kind, B, L, Compressed) = 1 then Put ("1 => "); end if; Put ("("); Put_16 ( Wide_Wide_Character'Pos (Key (I)) - Offset); Put (", "); if Compressed then Put (Item_RLE, Width => 1); Put (", "); Put ( Wide_Wide_Character'Pos (Element (Element (I), 1)) - Wide_Wide_Character'Pos (Key (I)), Width => 1); else if L > 1 then Put ("("); end if; for J in 1 .. Item_L loop if J > 1 then Put (", "); end if; Put_16 ( Wide_Wide_Character'Pos ( Element (Element (I), J)) - Offset); end loop; if L > 1 then Put (")"); end if; end if; Put (")"); Second := True; end if; I := N; end; end loop; Put (");"); New_Line; end; New_Line; end if; end loop; end loop; end loop; end loop; Put_Line ("end Ada.UCD.Case_Folding;"); end ucd_casefolding;
----------------------------------------------------------------------- -- servlet-servlets-rest -- REST servlet -- Copyright (C) 2016, 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Servlet.Rest; with Servlet.Routes.Servlets.Rest; use Servlet.Rest; package Servlet.Core.Rest is -- The <b>Servlet</b> represents the component that will handle -- an HTTP request received by the server. type Rest_Servlet is new Servlet with private; -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. overriding procedure Initialize (Server : in out Rest_Servlet; Context : in Servlet_Registry'Class); -- Receives standard HTTP requests from the public service method and dispatches -- them to the Do_XXX methods defined in this class. This method is an HTTP-specific -- version of the Servlet.service(Request, Response) method. There's no need -- to override this method. overriding procedure Service (Server : in Rest_Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); -- Create a route for the REST API. function Create_Route (Registry : in Servlet_Registry; Name : in String) return Routes.Servlets.Rest.API_Route_Type_Access; function Create_Route (Servlet : in Servlet_Access) return Routes.Servlets.Rest.API_Route_Type_Access; procedure Dispatch (Server : in Rest_Servlet; Method : in Method_Type; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); private type Rest_Servlet is new Servlet with null record; end Servlet.Core.Rest;
-- SPDX-FileCopyrightText: 2021 Max Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT ------------------------------------------------------------- with Program.Cross_Reference_Updaters; with Program.Elements.Call_Statements; with Program.Interpretations; package Program.Complete_Contexts.Call_Statements is pragma Preelaborate; procedure Call_Statement (Sets : not null Program.Interpretations.Context_Access; Setter : not null Program.Cross_Reference_Updaters .Cross_Reference_Updater_Access; Element : Program.Elements.Call_Statements.Call_Statement_Access); end Program.Complete_Contexts.Call_Statements;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015-2016, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with STM32.Board; use STM32.Board; with Bitmapped_Drawing; with Bitmap_Color_Conversion; use Bitmap_Color_Conversion; package body LCD_Std_Out is -- We don't make the current font visible to clients because changing it -- requires recomputation of the screen layout (eg the char height) and -- issuance of commands to the LCD component driver (eg to refill). Current_Font : BMP_Font := Default_Font; Char_Width : Natural := BMP_Fonts.Char_Width (Current_Font); Char_Height : Natural := BMP_Fonts.Char_Height (Current_Font); Max_Width : Natural := LCD_Natural_Width - Char_Width; -- The last place on the current "line" on the LCD where a char of the -- current font size can be printed Max_Height : Natural := LCD_Natural_Height - Char_Height; -- The last "line" on the LCD where a char of this current font size can be -- printed Current_Y : Natural := 0; -- The current "line" that the text will appear upon. Note this wraps -- around to the top of the screen. Char_Count : Natural := 0; -- The number of characters currently printed on the current line Initialized : Boolean := False; procedure Draw_Char (X, Y : Natural; Msg : Character); -- Convenience routine for call Drawing.Draw_Char procedure Recompute_Screen_Dimensions (Font : BMP_Font); -- Determins the max height and width for the specified font, given the -- current LCD orientation procedure Check_Initialized with Inline; -- Ensures that the LCD display is initialized and DMA2D -- is up and running procedure Internal_Put (Msg : String); -- Puts a new String in the frame buffer procedure Internal_Put (Msg : Character); -- Puts a new character in the frame buffer. ----------------------- -- Check_Initialized -- ----------------------- procedure Check_Initialized is begin if Initialized then return; end if; Initialized := True; if Display.Initialized then -- Ensure we use polling here: LCD_Std_Out may be called from the -- Last chance handler, and we don't want unexpected tasks or -- protected objects calling an entry not meant for that Display.Set_Mode (HAL.Framebuffer.Polling); else Display.Initialize (Mode => HAL.Framebuffer.Polling); Display.Initialize_Layer (1, HAL.Bitmap.RGB_565); Clear_Screen; end if; end Check_Initialized; --------------------------------- -- Recompute_Screen_Dimensions -- --------------------------------- procedure Recompute_Screen_Dimensions (Font : BMP_Font) is begin Check_Initialized; Char_Width := BMP_Fonts.Char_Width (Font); Char_Height := BMP_Fonts.Char_Height (Font); Max_Width := Display.Width - Char_Width - 1; Max_Height := Display.Height - Char_Height - 1; end Recompute_Screen_Dimensions; -------------- -- Set_Font -- -------------- procedure Set_Font (To : in BMP_Font) is begin Current_Font := To; Recompute_Screen_Dimensions (Current_Font); end Set_Font; --------------------- -- Set_Orientation -- --------------------- procedure Set_Orientation (To : in HAL.Framebuffer.Display_Orientation) is begin Display.Set_Orientation (To); Recompute_Screen_Dimensions (Current_Font); Clear_Screen; end Set_Orientation; ------------------ -- Clear_Screen -- ------------------ procedure Clear_Screen is begin Check_Initialized; Display.Hidden_Buffer (1).Set_Source (Current_Background_Color); Display.Hidden_Buffer (1).Fill; Current_Y := 0; Char_Count := 0; Display.Update_Layer (1, True); end Clear_Screen; ------------------ -- Internal_Put -- ------------------ procedure Internal_Put (Msg : String) is begin for C of Msg loop if C = ASCII.LF then New_Line; else Internal_Put (C); end if; end loop; end Internal_Put; --------- -- Put -- --------- procedure Put (Msg : String) is begin Internal_Put (Msg); Display.Update_Layer (1, True); end Put; --------------- -- Draw_Char -- --------------- procedure Draw_Char (X, Y : Natural; Msg : Character) is begin Check_Initialized; Bitmapped_Drawing.Draw_Char (Display.Hidden_Buffer (1).all, Start => (X, Y), Char => Msg, Font => Current_Font, Foreground => Bitmap_Color_To_Word (Display.Color_Mode (1), Current_Text_Color), Background => Bitmap_Color_To_Word (Display.Color_Mode (1), Current_Background_Color)); end Draw_Char; --------- -- Put -- --------- procedure Internal_Put (Msg : Character) is begin if Char_Count * Char_Width > Max_Width then New_Line; end if; Draw_Char (Char_Count * Char_Width, Current_Y, Msg); Char_Count := Char_Count + 1; end Internal_Put; --------- -- Put -- --------- procedure Put (Msg : Character) is begin Internal_Put (Msg); Display.Update_Layer (1, True); end Put; -------------- -- New_Line -- -------------- procedure New_Line is begin Char_Count := 0; -- next char printed will be at the start of a new line if Current_Y + Char_Height > Max_Height then Current_Y := 0; else Current_Y := Current_Y + Char_Height; end if; end New_Line; -------------- -- Put_Line -- -------------- procedure Put_Line (Msg : String) is begin Put (Msg); New_Line; end Put_Line; --------- -- Put -- --------- procedure Put (X, Y : Natural; Msg : Character) is begin Draw_Char (X, Y, Msg); Display.Update_Layer (1, True); end Put; --------- -- Put -- --------- procedure Put (X, Y : Natural; Msg : String) is Count : Natural := 0; Next_X : Natural; begin for C of Msg loop Next_X := X + Count * Char_Width; Draw_Char (Next_X, Y, C); Count := Count + 1; end loop; Display.Update_Layer (1, True); end Put; end LCD_Std_Out;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2019 onox <denkpadje@gmail.com> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. private with Ada.Finalization; private with GL.Objects.Vertex_Arrays; private with GL.Types; private with SDL.Video.GL; private with SDL.Video.Windows; with Orka.Contexts; package Orka.Windows.SDL is pragma Preelaborate; type SDL_Context is limited new Contexts.Surface_Context with private; overriding function Create_Context (Version : Contexts.Context_Version; Flags : Contexts.Context_Flags := (others => False)) return SDL_Context; type SDL_Window is limited new Window with private; overriding function Create_Window (Context : Contexts.Surface_Context'Class; Width, Height : Positive; Title : String := ""; Samples : Natural := 0; Visible, Resizable : Boolean := True; Transparent : Boolean := False) return SDL_Window with Pre => Context in SDL_Context'Class; overriding function Pointer_Input (Object : SDL_Window) return Inputs.Pointers.Pointer_Input_Ptr; overriding function Width (Object : SDL_Window) return Positive; overriding function Height (Object : SDL_Window) return Positive; overriding procedure Set_Title (Object : in out SDL_Window; Value : String); overriding procedure Close (Object : in out SDL_Window); overriding function Should_Close (Object : SDL_Window) return Boolean; overriding procedure Process_Input (Object : in out SDL_Window); overriding procedure Swap_Buffers (Object : in out SDL_Window); overriding procedure Set_Vertical_Sync (Object : in out SDL_Window; Enable : Boolean); private type SDL_Context is limited new Ada.Finalization.Limited_Controlled and Contexts.Surface_Context with record Version : Contexts.Context_Version; Flags : Contexts.Context_Flags; Features : Contexts.Feature_Array := (others => False); end record; overriding procedure Finalize (Object : in out SDL_Context); overriding procedure Enable (Object : in out SDL_Context; Subject : Contexts.Feature); overriding function Enabled (Object : SDL_Context; Subject : Contexts.Feature) return Boolean; overriding function Version (Object : SDL_Context) return Contexts.Context_Version; overriding function Flags (Object : SDL_Context) return Contexts.Context_Flags; overriding function Is_Current (Object : SDL_Context; Kind : Orka.Contexts.Task_Kind) return Boolean; overriding procedure Make_Current (Object : SDL_Context); overriding procedure Make_Current (Object : SDL_Context; Window : in out Orka.Windows.Window'Class); overriding procedure Make_Not_Current (Object : SDL_Context); type SDL_Window is limited new Ada.Finalization.Limited_Controlled and Window with record Input : Inputs.Pointers.Pointer_Input_Ptr; Finalized : Boolean; Vertex_Array : GL.Objects.Vertex_Arrays.Vertex_Array_Object; Context : Standard.SDL.Video.GL.Contexts; Window : Standard.SDL.Video.Windows.Window; Close_Window : Boolean := False; Position_X : GL.Types.Double := 0.0; Position_Y : GL.Types.Double := 0.0; Scroll_X : GL.Types.Double := 0.0; Scroll_Y : GL.Types.Double := 0.0; Width, Height : Positive; end record; overriding procedure Finalize (Object : in out SDL_Window); end Orka.Windows.SDL;
----------------------------------------------------------------------- -- mat-readers-sockets -- Reader for TCP/IP sockets -- Copyright (C) 2014, 2019 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; package body MAT.Readers.Streams.Sockets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Sockets"); BUFFER_SIZE : constant Natural := 100 * 1024; -- ------------------------------ -- Initialize the socket listener. -- ------------------------------ overriding procedure Initialize (Listener : in out Socket_Listener_Type) is begin GNAT.Sockets.Create_Selector (Listener.Accept_Selector); end Initialize; -- ------------------------------ -- Destroy the socket listener. -- ------------------------------ overriding procedure Finalize (Listener : in out Socket_Listener_Type) is begin GNAT.Sockets.Close_Selector (Listener.Accept_Selector); end Finalize; -- ------------------------------ -- Open the socket to accept connections and start the listener task. -- ------------------------------ procedure Start (Listener : in out Socket_Listener_Type; List : in MAT.Events.Probes.Reader_List_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type) is begin Log.Info ("Starting the listener socket task"); Listener.List := List; Listener.Listener.Start (Listener'Unchecked_Access, Address); end Start; -- ------------------------------ -- Stop the listener socket. -- ------------------------------ procedure Stop (Listener : in out Socket_Listener_Type) is begin GNAT.Sockets.Abort_Selector (Listener.Accept_Selector); end Stop; -- ------------------------------ -- Create a target instance for the new client. -- ------------------------------ procedure Create_Target (Listener : in out Socket_Listener_Type; Client : in GNAT.Sockets.Socket_Type; Address : in GNAT.Sockets.Sock_Addr_Type) is Reader : constant Socket_Reader_Type_Access := new Socket_Reader_Type; Stream : constant access Util.Streams.Input_Stream'Class := Reader.Socket'Access; begin Reader.Client := Client; Reader.Stream.Initialize (Input => Stream, Size => BUFFER_SIZE); Reader.Server.Start (Reader, Client); Listener.List.Initialize (Reader.all); Listener.Clients.Append (Reader); end Create_Target; task body Socket_Listener_Task is use type GNAT.Sockets.Selector_Status; Peer : GNAT.Sockets.Sock_Addr_Type; Server : GNAT.Sockets.Socket_Type; Instance : Socket_Listener_Type_Access; Client : GNAT.Sockets.Socket_Type; Selector_Status : GNAT.Sockets.Selector_Status; begin select accept Start (Listener : in Socket_Listener_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type) do Instance := Listener; GNAT.Sockets.Create_Socket (Server); GNAT.Sockets.Set_Socket_Option (Server, GNAT.Sockets.Socket_Level, (GNAT.Sockets.Reuse_Address, True)); GNAT.Sockets.Bind_Socket (Server, Address); GNAT.Sockets.Listen_Socket (Server); end Start; or terminate; end select; loop GNAT.Sockets.Accept_Socket (Server => Server, Socket => Client, Address => Peer, Timeout => GNAT.Sockets.Forever, Selector => Instance.Accept_Selector'Access, Status => Selector_Status); exit when Selector_Status = GNAT.Sockets.Aborted; if Selector_Status = GNAT.Sockets.Completed then Instance.Create_Target (Client => Client, Address => Peer); end if; end loop; GNAT.Sockets.Close_Socket (Server); declare Iter : Socket_Client_Lists.Cursor := Instance.Clients.First; begin while Socket_Client_Lists.Has_Element (Iter) loop GNAT.Sockets.Close_Socket (Socket_Client_Lists.Element (Iter).Client); Iter := Socket_Client_Lists.Next (Iter); end loop; end; end Socket_Listener_Task; task body Socket_Reader_Task is Instance : Socket_Reader_Type_Access; Socket : GNAT.Sockets.Socket_Type; begin select accept Start (Reader : in Socket_Reader_Type_Access; Client : in GNAT.Sockets.Socket_Type) do Instance := Reader; Socket := Client; end Start; or terminate; end select; Instance.Socket.Open (Socket); Instance.Read_All; GNAT.Sockets.Close_Socket (Socket); exception when E : others => Log.Error ("Exception", E, True); GNAT.Sockets.Close_Socket (Socket); end Socket_Reader_Task; procedure Close (Reader : in out Socket_Reader_Type) is begin Reader.Stop := True; end Close; end MAT.Readers.Streams.Sockets;
-- { dg-do run } with Init7; use Init7; with Text_IO; use Text_IO; with Dump; procedure R7 is function Get_Elem (R : R1) return Integer is Tmp : R1 := R; begin return Tmp.N.C1; end; procedure Set_Elem (R : access R1; I : Integer) is Tmp : R1 := R.all; begin Tmp.N.C1 := I; R.all := Tmp; end; function Get_Elem (R : R2) return Integer is Tmp : R2 := R; begin return Tmp.N.C1; end; procedure Set_Elem (R : access R2; I : Integer) is Tmp : R2 := R.all; begin Tmp.N.C1 := I; R.all := Tmp; end; A1 : aliased R1 := My_R1; A2 : aliased R2 := My_R2; begin Put ("A1 :"); Dump (A1'Address, R1'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "A1 : 78 56 34 12 12 00 ab 00 34 00 cd 00 56 00 ef 00.*\n" } Put ("A2 :"); Dump (A2'Address, R1'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "A2 : 12 34 56 78 00 ab 00 12 00 cd 00 34 00 ef 00 56.*\n" } if Get_Elem (A1) /= 16#AB0012# then raise Program_Error; end if; Set_Elem (A1'Access, 16#CD0034#); if Get_Elem (A1) /= 16#CD0034# then raise Program_Error; end if; if Get_Elem (A2) /= 16#AB0012# then raise Program_Error; end if; Set_Elem (A2'Access, 16#CD0034#); if Get_Elem (A2) /= 16#CD0034# then raise Program_Error; end if; end;
with Ada.Unchecked_Deallocation; with PB_Support.IO; with PB_Support.Internal; package body Google.Protobuf.Descriptor is package Descriptor_Proto_IO is new PB_Support.IO.Message_IO (Google.Protobuf.Descriptor.Descriptor_Proto, Google.Protobuf.Descriptor.Descriptor_Proto_Vector, Google.Protobuf.Descriptor.Append); package Extension_Range_IO is new PB_Support.IO.Message_IO (Google.Protobuf.Descriptor.Extension_Range, Google.Protobuf.Descriptor.Extension_Range_Vector, Google.Protobuf.Descriptor.Append); package Reserved_Range_IO is new PB_Support.IO.Message_IO (Google.Protobuf.Descriptor.Reserved_Range, Google.Protobuf.Descriptor.Reserved_Range_Vector, Google.Protobuf.Descriptor.Append); package Enum_Descriptor_Proto_IO is new PB_Support.IO.Message_IO (Google.Protobuf.Descriptor.Enum_Descriptor_Proto, Google.Protobuf.Descriptor.Enum_Descriptor_Proto_Vector, Google.Protobuf.Descriptor.Append); package Enum_Options_IO is new PB_Support.IO.Message_IO (Google.Protobuf.Descriptor.Enum_Options, Google.Protobuf.Descriptor.Enum_Options_Vector, Google.Protobuf.Descriptor.Append); package Enum_Value_Descriptor_Proto_IO is new PB_Support.IO.Message_IO (Google.Protobuf.Descriptor.Enum_Value_Descriptor_Proto, Google.Protobuf.Descriptor.Enum_Value_Descriptor_Proto_Vector, Google.Protobuf.Descriptor.Append); package Enum_Value_Options_IO is new PB_Support.IO.Message_IO (Google.Protobuf.Descriptor.Enum_Value_Options, Google.Protobuf.Descriptor.Enum_Value_Options_Vector, Google.Protobuf.Descriptor.Append); package Field_Descriptor_Proto_IO is new PB_Support.IO.Message_IO (Google.Protobuf.Descriptor.Field_Descriptor_Proto, Google.Protobuf.Descriptor.Field_Descriptor_Proto_Vector, Google.Protobuf.Descriptor.Append); type Integer_Label is range 1 .. 3 with Size => Google.Protobuf.Descriptor.Label'Size; package Label_IO is new PB_Support.IO.Enum_IO (Google.Protobuf.Descriptor.Label, Integer_Label, Google.Protobuf.Descriptor.Label_Vectors); type Integer_PB_Type is range 1 .. 18 with Size => Google.Protobuf.Descriptor.PB_Type'Size; package PB_Type_IO is new PB_Support.IO.Enum_IO (Google.Protobuf.Descriptor.PB_Type, Integer_PB_Type, Google.Protobuf.Descriptor.PB_Type_Vectors); package Field_Options_IO is new PB_Support.IO.Message_IO (Google.Protobuf.Descriptor.Field_Options, Google.Protobuf.Descriptor.Field_Options_Vector, Google.Protobuf.Descriptor.Append); type Integer_CType is range 0 .. 2 with Size => Google.Protobuf.Descriptor.CType'Size; package CType_IO is new PB_Support.IO.Enum_IO (Google.Protobuf.Descriptor.CType, Integer_CType, Google.Protobuf.Descriptor.CType_Vectors); type Integer_JSType is range 0 .. 2 with Size => Google.Protobuf.Descriptor.JSType'Size; package JSType_IO is new PB_Support.IO.Enum_IO (Google.Protobuf.Descriptor.JSType, Integer_JSType, Google.Protobuf.Descriptor.JSType_Vectors); package File_Descriptor_Proto_IO is new PB_Support.IO.Message_IO (Google.Protobuf.Descriptor.File_Descriptor_Proto, Google.Protobuf.Descriptor.File_Descriptor_Proto_Vector, Google.Protobuf.Descriptor.Append); package File_Options_IO is new PB_Support.IO.Message_IO (Google.Protobuf.Descriptor.File_Options, Google.Protobuf.Descriptor.File_Options_Vector, Google.Protobuf.Descriptor.Append); type Integer_Optimize_Mode is range 1 .. 3 with Size => Google.Protobuf.Descriptor.Optimize_Mode'Size; package Optimize_Mode_IO is new PB_Support.IO.Enum_IO (Google.Protobuf.Descriptor.Optimize_Mode, Integer_Optimize_Mode, Google.Protobuf.Descriptor.Optimize_Mode_Vectors); package Annotation_IO is new PB_Support.IO.Message_IO (Google.Protobuf.Descriptor.Annotation, Google.Protobuf.Descriptor.Annotation_Vector, Google.Protobuf.Descriptor.Append); package Message_Options_IO is new PB_Support.IO.Message_IO (Google.Protobuf.Descriptor.Message_Options, Google.Protobuf.Descriptor.Message_Options_Vector, Google.Protobuf.Descriptor.Append); package Method_Descriptor_Proto_IO is new PB_Support.IO.Message_IO (Google.Protobuf.Descriptor.Method_Descriptor_Proto, Google.Protobuf.Descriptor.Method_Descriptor_Proto_Vector, Google.Protobuf.Descriptor.Append); package Method_Options_IO is new PB_Support.IO.Message_IO (Google.Protobuf.Descriptor.Method_Options, Google.Protobuf.Descriptor.Method_Options_Vector, Google.Protobuf.Descriptor.Append); package Oneof_Descriptor_Proto_IO is new PB_Support.IO.Message_IO (Google.Protobuf.Descriptor.Oneof_Descriptor_Proto, Google.Protobuf.Descriptor.Oneof_Descriptor_Proto_Vector, Google.Protobuf.Descriptor.Append); package Oneof_Options_IO is new PB_Support.IO.Message_IO (Google.Protobuf.Descriptor.Oneof_Options, Google.Protobuf.Descriptor.Oneof_Options_Vector, Google.Protobuf.Descriptor.Append); package Service_Descriptor_Proto_IO is new PB_Support.IO.Message_IO (Google.Protobuf.Descriptor.Service_Descriptor_Proto, Google.Protobuf.Descriptor.Service_Descriptor_Proto_Vector, Google.Protobuf.Descriptor.Append); package Service_Options_IO is new PB_Support.IO.Message_IO (Google.Protobuf.Descriptor.Service_Options, Google.Protobuf.Descriptor.Service_Options_Vector, Google.Protobuf.Descriptor.Append); package Source_Code_Info_IO is new PB_Support.IO.Message_IO (Google.Protobuf.Descriptor.Source_Code_Info, Google.Protobuf.Descriptor.Source_Code_Info_Vector, Google.Protobuf.Descriptor.Append); package Location_IO is new PB_Support.IO.Message_IO (Google.Protobuf.Descriptor.Location, Google.Protobuf.Descriptor.Location_Vector, Google.Protobuf.Descriptor.Append); package Uninterpreted_Option_IO is new PB_Support.IO.Message_IO (Google.Protobuf.Descriptor.Uninterpreted_Option, Google.Protobuf.Descriptor.Uninterpreted_Option_Vector, Google.Protobuf.Descriptor.Append); package Name_Part_IO is new PB_Support.IO.Message_IO (Google.Protobuf.Descriptor.Name_Part, Google.Protobuf.Descriptor.Name_Part_Vector, Google.Protobuf.Descriptor.Append); function Length (Self : File_Descriptor_Set_Vector) return Natural is begin return Self.Length; end Length; procedure Clear (Self : in out File_Descriptor_Set_Vector) is begin Self.Length := 0; end Clear; procedure Free is new Ada.Unchecked_Deallocation (File_Descriptor_Set_Array, File_Descriptor_Set_Array_Access); procedure Append (Self : in out File_Descriptor_Set_Vector; V : File_Descriptor_Set) is Init_Length : constant Positive := Positive'Max (1, 256 / File_Descriptor_Set'Size); begin if Self.Length = 0 then Self.Data := new File_Descriptor_Set_Array (1 .. Init_Length); elsif Self.Length = Self.Data'Last then Self.Data := new File_Descriptor_Set_Array' (Self.Data.all & File_Descriptor_Set_Array'(1 .. Self.Length => <>)); end if; Self.Length := Self.Length + 1; Self.Data (Self.Length) := V; end Append; overriding procedure Adjust (Self : in out File_Descriptor_Set_Vector) is begin if Self.Length > 0 then Self.Data := new File_Descriptor_Set_Array'(Self.Data (1 .. Self.Length)); end if; end Adjust; overriding procedure Finalize (Self : in out File_Descriptor_Set_Vector) is begin if Self.Data /= null then Free (Self.Data); end if; end Finalize; not overriding function Get_File_Descriptor_Set_Variable_Reference (Self : aliased in out File_Descriptor_Set_Vector; Index : Positive) return File_Descriptor_Set_Variable_Reference is begin return (Element => Self.Data (Index)'Access); end Get_File_Descriptor_Set_Variable_Reference; not overriding function Get_File_Descriptor_Set_Constant_Reference (Self : aliased File_Descriptor_Set_Vector; Index : Positive) return File_Descriptor_Set_Constant_Reference is begin return (Element => Self.Data (Index)'Access); end Get_File_Descriptor_Set_Constant_Reference; procedure Read_File_Descriptor_Set (Stream : access Ada.Streams.Root_Stream_Type'Class; V : out File_Descriptor_Set) is Key : aliased PB_Support.IO.Key; begin while PB_Support.IO.Read_Key (Stream, Key'Access) loop case Key.Field is when 1 => File_Descriptor_Proto_IO.Read_Vector (Stream, Key.Encoding, V.File); when others => PB_Support.IO.Unknown_Field (Stream, Key.Encoding); end case; end loop; end Read_File_Descriptor_Set; procedure Write_File_Descriptor_Set (Stream : access Ada.Streams.Root_Stream_Type'Class; V : File_Descriptor_Set) is begin if Stream.all not in PB_Support.Internal.Stream then declare WS : aliased PB_Support.Internal.Stream (Stream); begin Write_File_Descriptor_Set (WS'Access, V); return; end; end if; declare WS : PB_Support.Internal.Stream renames PB_Support.Internal.Stream (Stream.all); begin WS.Start_Message; for J in 1 .. V.File.Length loop WS.Write_Key ((1, PB_Support.Length_Delimited)); Google.Protobuf.Descriptor.File_Descriptor_Proto'Write (Stream, V.File (J)); end loop; if WS.End_Message then Write_File_Descriptor_Set (WS'Access, V); end if; end; end Write_File_Descriptor_Set; function Length (Self : File_Descriptor_Proto_Vector) return Natural is begin return Self.Length; end Length; procedure Clear (Self : in out File_Descriptor_Proto_Vector) is begin Self.Length := 0; end Clear; procedure Free is new Ada.Unchecked_Deallocation (File_Descriptor_Proto_Array, File_Descriptor_Proto_Array_Access); procedure Append (Self : in out File_Descriptor_Proto_Vector; V : File_Descriptor_Proto) is Init_Length : constant Positive := Positive'Max (1, 256 / File_Descriptor_Proto'Size); begin if Self.Length = 0 then Self.Data := new File_Descriptor_Proto_Array (1 .. Init_Length); elsif Self.Length = Self.Data'Last then Self.Data := new File_Descriptor_Proto_Array' (Self.Data.all & File_Descriptor_Proto_Array'(1 .. Self.Length => <>)); end if; Self.Length := Self.Length + 1; Self.Data (Self.Length) := V; end Append; overriding procedure Adjust (Self : in out File_Descriptor_Proto_Vector) is begin if Self.Length > 0 then Self.Data := new File_Descriptor_Proto_Array'(Self.Data (1 .. Self.Length)); end if; end Adjust; overriding procedure Finalize (Self : in out File_Descriptor_Proto_Vector) is begin if Self.Data /= null then Free (Self.Data); end if; end Finalize; not overriding function Get_File_Descriptor_Proto_Variable_Reference (Self : aliased in out File_Descriptor_Proto_Vector; Index : Positive) return File_Descriptor_Proto_Variable_Reference is begin return (Element => Self.Data (Index)'Access); end Get_File_Descriptor_Proto_Variable_Reference; not overriding function Get_File_Descriptor_Proto_Constant_Reference (Self : aliased File_Descriptor_Proto_Vector; Index : Positive) return File_Descriptor_Proto_Constant_Reference is begin return (Element => Self.Data (Index)'Access); end Get_File_Descriptor_Proto_Constant_Reference; procedure Read_File_Descriptor_Proto (Stream : access Ada.Streams.Root_Stream_Type'Class; V : out File_Descriptor_Proto) is Key : aliased PB_Support.IO.Key; begin while PB_Support.IO.Read_Key (Stream, Key'Access) loop case Key.Field is when 1 => if not V.Name.Is_Set then V.Name := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Name.Value); when 2 => if not V.PB_Package.Is_Set then V.PB_Package := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.PB_Package.Value); when 3 => PB_Support.IO.Read_Vector (Stream, Key.Encoding, V.Dependency); when 10 => PB_Support.IO.Read_Varint_Vector (Stream, Key.Encoding, V.Public_Dependency); when 11 => PB_Support.IO.Read_Varint_Vector (Stream, Key.Encoding, V.Weak_Dependency); when 4 => Descriptor_Proto_IO.Read_Vector (Stream, Key.Encoding, V.Message_Type); when 5 => Enum_Descriptor_Proto_IO.Read_Vector (Stream, Key.Encoding, V.Enum_Type); when 6 => Service_Descriptor_Proto_IO.Read_Vector (Stream, Key.Encoding, V.Service); when 7 => Field_Descriptor_Proto_IO.Read_Vector (Stream, Key.Encoding, V.Extension); when 8 => if not V.Options.Is_Set then V.Options := (True, others => <>); end if; File_Options_IO.Read (Stream, Key.Encoding, V.Options.Value); when 9 => if not V.Source_Code_Info.Is_Set then V.Source_Code_Info := (True, others => <>); end if; Source_Code_Info_IO.Read (Stream, Key.Encoding, V.Source_Code_Info.Value); when 12 => if not V.Syntax.Is_Set then V.Syntax := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Syntax.Value); when others => PB_Support.IO.Unknown_Field (Stream, Key.Encoding); end case; end loop; end Read_File_Descriptor_Proto; procedure Write_File_Descriptor_Proto (Stream : access Ada.Streams.Root_Stream_Type'Class; V : File_Descriptor_Proto) is begin if Stream.all not in PB_Support.Internal.Stream then declare WS : aliased PB_Support.Internal.Stream (Stream); begin Write_File_Descriptor_Proto (WS'Access, V); return; end; end if; declare WS : PB_Support.Internal.Stream renames PB_Support.Internal.Stream (Stream.all); begin WS.Start_Message; if V.Name.Is_Set then WS.Write (1, V.Name.Value); end if; if V.PB_Package.Is_Set then WS.Write (2, V.PB_Package.Value); end if; WS.Write (3, V.Dependency); WS.Write_Varint (10, V.Public_Dependency); WS.Write_Varint (11, V.Weak_Dependency); for J in 1 .. V.Message_Type.Length loop WS.Write_Key ((4, PB_Support.Length_Delimited)); Google.Protobuf.Descriptor.Descriptor_Proto'Write (Stream, V.Message_Type (J)); end loop; for J in 1 .. V.Enum_Type.Length loop WS.Write_Key ((5, PB_Support.Length_Delimited)); Google.Protobuf.Descriptor.Enum_Descriptor_Proto'Write (Stream, V.Enum_Type (J)); end loop; for J in 1 .. V.Service.Length loop WS.Write_Key ((6, PB_Support.Length_Delimited)); Google.Protobuf.Descriptor.Service_Descriptor_Proto'Write (Stream, V.Service (J)); end loop; for J in 1 .. V.Extension.Length loop WS.Write_Key ((7, PB_Support.Length_Delimited)); Google.Protobuf.Descriptor.Field_Descriptor_Proto'Write (Stream, V.Extension (J)); end loop; if V.Options.Is_Set then WS.Write_Key ((8, PB_Support.Length_Delimited)); Google.Protobuf.Descriptor.File_Options'Write (Stream, V.Options.Value); end if; if V.Source_Code_Info.Is_Set then WS.Write_Key ((9, PB_Support.Length_Delimited)); Google.Protobuf.Descriptor.Source_Code_Info'Write (Stream, V.Source_Code_Info.Value); end if; if V.Syntax.Is_Set then WS.Write (12, V.Syntax.Value); end if; if WS.End_Message then Write_File_Descriptor_Proto (WS'Access, V); end if; end; end Write_File_Descriptor_Proto; function Length (Self : Descriptor_Proto_Vector) return Natural is begin return Self.Length; end Length; procedure Clear (Self : in out Descriptor_Proto_Vector) is begin Self.Length := 0; end Clear; procedure Free is new Ada.Unchecked_Deallocation (Descriptor_Proto_Array, Descriptor_Proto_Array_Access); procedure Append (Self : in out Descriptor_Proto_Vector; V : Descriptor_Proto) is Init_Length : constant Positive := Positive'Max (1, 256 / Descriptor_Proto'Size); begin if Self.Length = 0 then Self.Data := new Descriptor_Proto_Array (1 .. Init_Length); elsif Self.Length = Self.Data'Last then Self.Data := new Descriptor_Proto_Array' (Self.Data.all & Descriptor_Proto_Array'(1 .. Self.Length => <>)); end if; Self.Length := Self.Length + 1; Self.Data (Self.Length) := V; end Append; overriding procedure Adjust (Self : in out Descriptor_Proto_Vector) is begin if Self.Length > 0 then Self.Data := new Descriptor_Proto_Array'(Self.Data (1 .. Self.Length)); end if; end Adjust; overriding procedure Finalize (Self : in out Descriptor_Proto_Vector) is begin if Self.Data /= null then Free (Self.Data); end if; end Finalize; not overriding function Get_Descriptor_Proto_Variable_Reference (Self : aliased in out Descriptor_Proto_Vector; Index : Positive) return Descriptor_Proto_Variable_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Descriptor_Proto_Variable_Reference; not overriding function Get_Descriptor_Proto_Constant_Reference (Self : aliased Descriptor_Proto_Vector; Index : Positive) return Descriptor_Proto_Constant_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Descriptor_Proto_Constant_Reference; procedure Read_Descriptor_Proto (Stream : access Ada.Streams.Root_Stream_Type'Class; V : out Descriptor_Proto) is Key : aliased PB_Support.IO.Key; begin while PB_Support.IO.Read_Key (Stream, Key'Access) loop case Key.Field is when 1 => if not V.Name.Is_Set then V.Name := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Name.Value); when 2 => Field_Descriptor_Proto_IO.Read_Vector (Stream, Key.Encoding, V.Field); when 6 => Field_Descriptor_Proto_IO.Read_Vector (Stream, Key.Encoding, V.Extension); when 3 => Descriptor_Proto_IO.Read_Vector (Stream, Key.Encoding, V.Nested_Type); when 4 => Enum_Descriptor_Proto_IO.Read_Vector (Stream, Key.Encoding, V.Enum_Type); when 5 => Extension_Range_IO.Read_Vector (Stream, Key.Encoding, V.Extension_Range); when 8 => Oneof_Descriptor_Proto_IO.Read_Vector (Stream, Key.Encoding, V.Oneof_Decl); when 7 => if not V.Options.Is_Set then V.Options := (True, others => <>); end if; Message_Options_IO.Read (Stream, Key.Encoding, V.Options.Value); when 9 => Reserved_Range_IO.Read_Vector (Stream, Key.Encoding, V.Reserved_Range); when 10 => PB_Support.IO.Read_Vector (Stream, Key.Encoding, V.Reserved_Name); when others => PB_Support.IO.Unknown_Field (Stream, Key.Encoding); end case; end loop; end Read_Descriptor_Proto; procedure Write_Descriptor_Proto (Stream : access Ada.Streams.Root_Stream_Type'Class; V : Descriptor_Proto) is begin if Stream.all not in PB_Support.Internal.Stream then declare WS : aliased PB_Support.Internal.Stream (Stream); begin Write_Descriptor_Proto (WS'Access, V); return; end; end if; declare WS : PB_Support.Internal.Stream renames PB_Support.Internal.Stream (Stream.all); begin WS.Start_Message; if V.Name.Is_Set then WS.Write (1, V.Name.Value); end if; for J in 1 .. V.Field.Length loop WS.Write_Key ((2, PB_Support.Length_Delimited)); Google.Protobuf.Descriptor.Field_Descriptor_Proto'Write (Stream, V.Field (J)); end loop; for J in 1 .. V.Extension.Length loop WS.Write_Key ((6, PB_Support.Length_Delimited)); Google.Protobuf.Descriptor.Field_Descriptor_Proto'Write (Stream, V.Extension (J)); end loop; for J in 1 .. V.Nested_Type.Length loop WS.Write_Key ((3, PB_Support.Length_Delimited)); Google.Protobuf.Descriptor.Descriptor_Proto'Write (Stream, V.Nested_Type (J)); end loop; for J in 1 .. V.Enum_Type.Length loop WS.Write_Key ((4, PB_Support.Length_Delimited)); Google.Protobuf.Descriptor.Enum_Descriptor_Proto'Write (Stream, V.Enum_Type (J)); end loop; for J in 1 .. V.Extension_Range.Length loop WS.Write_Key ((5, PB_Support.Length_Delimited)); Google.Protobuf.Descriptor.Extension_Range'Write (Stream, V.Extension_Range (J)); end loop; for J in 1 .. V.Oneof_Decl.Length loop WS.Write_Key ((8, PB_Support.Length_Delimited)); Google.Protobuf.Descriptor.Oneof_Descriptor_Proto'Write (Stream, V.Oneof_Decl (J)); end loop; if V.Options.Is_Set then WS.Write_Key ((7, PB_Support.Length_Delimited)); Google.Protobuf.Descriptor.Message_Options'Write (Stream, V.Options.Value); end if; for J in 1 .. V.Reserved_Range.Length loop WS.Write_Key ((9, PB_Support.Length_Delimited)); Google.Protobuf.Descriptor.Reserved_Range'Write (Stream, V.Reserved_Range (J)); end loop; WS.Write (10, V.Reserved_Name); if WS.End_Message then Write_Descriptor_Proto (WS'Access, V); end if; end; end Write_Descriptor_Proto; function Length (Self : Extension_Range_Vector) return Natural is begin return Self.Length; end Length; procedure Clear (Self : in out Extension_Range_Vector) is begin Self.Length := 0; end Clear; procedure Free is new Ada.Unchecked_Deallocation (Extension_Range_Array, Extension_Range_Array_Access); procedure Append (Self : in out Extension_Range_Vector; V : Extension_Range) is Init_Length : constant Positive := Positive'Max (1, 256 / Extension_Range'Size); begin if Self.Length = 0 then Self.Data := new Extension_Range_Array (1 .. Init_Length); elsif Self.Length = Self.Data'Last then Self.Data := new Extension_Range_Array' (Self.Data.all & Extension_Range_Array'(1 .. Self.Length => <>)); end if; Self.Length := Self.Length + 1; Self.Data (Self.Length) := V; end Append; overriding procedure Adjust (Self : in out Extension_Range_Vector) is begin if Self.Length > 0 then Self.Data := new Extension_Range_Array'(Self.Data (1 .. Self.Length)); end if; end Adjust; overriding procedure Finalize (Self : in out Extension_Range_Vector) is begin if Self.Data /= null then Free (Self.Data); end if; end Finalize; not overriding function Get_Extension_Range_Variable_Reference (Self : aliased in out Extension_Range_Vector; Index : Positive) return Extension_Range_Variable_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Extension_Range_Variable_Reference; not overriding function Get_Extension_Range_Constant_Reference (Self : aliased Extension_Range_Vector; Index : Positive) return Extension_Range_Constant_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Extension_Range_Constant_Reference; procedure Read_Extension_Range (Stream : access Ada.Streams.Root_Stream_Type'Class; V : out Extension_Range) is Key : aliased PB_Support.IO.Key; begin while PB_Support.IO.Read_Key (Stream, Key'Access) loop case Key.Field is when 1 => if not V.Start.Is_Set then V.Start := (True, others => <>); end if; PB_Support.IO.Read_Varint (Stream, Key.Encoding, V.Start.Value); when 2 => if not V.PB_End.Is_Set then V.PB_End := (True, others => <>); end if; PB_Support.IO.Read_Varint (Stream, Key.Encoding, V.PB_End.Value); when others => PB_Support.IO.Unknown_Field (Stream, Key.Encoding); end case; end loop; end Read_Extension_Range; procedure Write_Extension_Range (Stream : access Ada.Streams.Root_Stream_Type'Class; V : Extension_Range) is begin if Stream.all not in PB_Support.Internal.Stream then declare WS : aliased PB_Support.Internal.Stream (Stream); begin Write_Extension_Range (WS'Access, V); return; end; end if; declare WS : PB_Support.Internal.Stream renames PB_Support.Internal.Stream (Stream.all); begin WS.Start_Message; if V.Start.Is_Set then WS.Write_Varint (1, V.Start.Value); end if; if V.PB_End.Is_Set then WS.Write_Varint (2, V.PB_End.Value); end if; if WS.End_Message then Write_Extension_Range (WS'Access, V); end if; end; end Write_Extension_Range; function Length (Self : Reserved_Range_Vector) return Natural is begin return Self.Length; end Length; procedure Clear (Self : in out Reserved_Range_Vector) is begin Self.Length := 0; end Clear; procedure Free is new Ada.Unchecked_Deallocation (Reserved_Range_Array, Reserved_Range_Array_Access); procedure Append (Self : in out Reserved_Range_Vector; V : Reserved_Range) is Init_Length : constant Positive := Positive'Max (1, 256 / Reserved_Range'Size); begin if Self.Length = 0 then Self.Data := new Reserved_Range_Array (1 .. Init_Length); elsif Self.Length = Self.Data'Last then Self.Data := new Reserved_Range_Array' (Self.Data.all & Reserved_Range_Array'(1 .. Self.Length => <>)); end if; Self.Length := Self.Length + 1; Self.Data (Self.Length) := V; end Append; overriding procedure Adjust (Self : in out Reserved_Range_Vector) is begin if Self.Length > 0 then Self.Data := new Reserved_Range_Array'(Self.Data (1 .. Self.Length)); end if; end Adjust; overriding procedure Finalize (Self : in out Reserved_Range_Vector) is begin if Self.Data /= null then Free (Self.Data); end if; end Finalize; not overriding function Get_Reserved_Range_Variable_Reference (Self : aliased in out Reserved_Range_Vector; Index : Positive) return Reserved_Range_Variable_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Reserved_Range_Variable_Reference; not overriding function Get_Reserved_Range_Constant_Reference (Self : aliased Reserved_Range_Vector; Index : Positive) return Reserved_Range_Constant_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Reserved_Range_Constant_Reference; procedure Read_Reserved_Range (Stream : access Ada.Streams.Root_Stream_Type'Class; V : out Reserved_Range) is Key : aliased PB_Support.IO.Key; begin while PB_Support.IO.Read_Key (Stream, Key'Access) loop case Key.Field is when 1 => if not V.Start.Is_Set then V.Start := (True, others => <>); end if; PB_Support.IO.Read_Varint (Stream, Key.Encoding, V.Start.Value); when 2 => if not V.PB_End.Is_Set then V.PB_End := (True, others => <>); end if; PB_Support.IO.Read_Varint (Stream, Key.Encoding, V.PB_End.Value); when others => PB_Support.IO.Unknown_Field (Stream, Key.Encoding); end case; end loop; end Read_Reserved_Range; procedure Write_Reserved_Range (Stream : access Ada.Streams.Root_Stream_Type'Class; V : Reserved_Range) is begin if Stream.all not in PB_Support.Internal.Stream then declare WS : aliased PB_Support.Internal.Stream (Stream); begin Write_Reserved_Range (WS'Access, V); return; end; end if; declare WS : PB_Support.Internal.Stream renames PB_Support.Internal.Stream (Stream.all); begin WS.Start_Message; if V.Start.Is_Set then WS.Write_Varint (1, V.Start.Value); end if; if V.PB_End.Is_Set then WS.Write_Varint (2, V.PB_End.Value); end if; if WS.End_Message then Write_Reserved_Range (WS'Access, V); end if; end; end Write_Reserved_Range; function Length (Self : Field_Descriptor_Proto_Vector) return Natural is begin return Self.Length; end Length; procedure Clear (Self : in out Field_Descriptor_Proto_Vector) is begin Self.Length := 0; end Clear; procedure Free is new Ada.Unchecked_Deallocation (Field_Descriptor_Proto_Array, Field_Descriptor_Proto_Array_Access); procedure Append (Self : in out Field_Descriptor_Proto_Vector; V : Field_Descriptor_Proto) is Init_Length : constant Positive := Positive'Max (1, 256 / Field_Descriptor_Proto'Size); begin if Self.Length = 0 then Self.Data := new Field_Descriptor_Proto_Array (1 .. Init_Length); elsif Self.Length = Self.Data'Last then Self.Data := new Field_Descriptor_Proto_Array' (Self.Data.all & Field_Descriptor_Proto_Array'(1 .. Self.Length => <>)); end if; Self.Length := Self.Length + 1; Self.Data (Self.Length) := V; end Append; overriding procedure Adjust (Self : in out Field_Descriptor_Proto_Vector) is begin if Self.Length > 0 then Self.Data := new Field_Descriptor_Proto_Array'(Self.Data (1 .. Self.Length)); end if; end Adjust; overriding procedure Finalize (Self : in out Field_Descriptor_Proto_Vector) is begin if Self.Data /= null then Free (Self.Data); end if; end Finalize; not overriding function Get_Field_Descriptor_Proto_Variable_Reference (Self : aliased in out Field_Descriptor_Proto_Vector; Index : Positive) return Field_Descriptor_Proto_Variable_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Field_Descriptor_Proto_Variable_Reference; not overriding function Get_Field_Descriptor_Proto_Constant_Reference (Self : aliased Field_Descriptor_Proto_Vector; Index : Positive) return Field_Descriptor_Proto_Constant_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Field_Descriptor_Proto_Constant_Reference; procedure Read_Field_Descriptor_Proto (Stream : access Ada.Streams.Root_Stream_Type'Class; V : out Field_Descriptor_Proto) is Key : aliased PB_Support.IO.Key; begin while PB_Support.IO.Read_Key (Stream, Key'Access) loop case Key.Field is when 1 => if not V.Name.Is_Set then V.Name := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Name.Value); when 3 => if not V.Number.Is_Set then V.Number := (True, others => <>); end if; PB_Support.IO.Read_Varint (Stream, Key.Encoding, V.Number.Value); when 4 => if not V.Label.Is_Set then V.Label := (True, others => <>); end if; Label_IO.Read (Stream, Key.Encoding, V.Label.Value); when 5 => if not V.PB_Type.Is_Set then V.PB_Type := (True, others => <>); end if; PB_Type_IO.Read (Stream, Key.Encoding, V.PB_Type.Value); when 6 => if not V.Type_Name.Is_Set then V.Type_Name := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Type_Name.Value); when 2 => if not V.Extendee.Is_Set then V.Extendee := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Extendee.Value); when 7 => if not V.Default_Value.Is_Set then V.Default_Value := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Default_Value.Value); when 9 => if not V.Oneof_Index.Is_Set then V.Oneof_Index := (True, others => <>); end if; PB_Support.IO.Read_Varint (Stream, Key.Encoding, V.Oneof_Index.Value); when 10 => if not V.Json_Name.Is_Set then V.Json_Name := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Json_Name.Value); when 8 => if not V.Options.Is_Set then V.Options := (True, others => <>); end if; Field_Options_IO.Read (Stream, Key.Encoding, V.Options.Value); when others => PB_Support.IO.Unknown_Field (Stream, Key.Encoding); end case; end loop; end Read_Field_Descriptor_Proto; procedure Write_Field_Descriptor_Proto (Stream : access Ada.Streams.Root_Stream_Type'Class; V : Field_Descriptor_Proto) is begin if Stream.all not in PB_Support.Internal.Stream then declare WS : aliased PB_Support.Internal.Stream (Stream); begin Write_Field_Descriptor_Proto (WS'Access, V); return; end; end if; declare WS : PB_Support.Internal.Stream renames PB_Support.Internal.Stream (Stream.all); begin WS.Start_Message; if V.Name.Is_Set then WS.Write (1, V.Name.Value); end if; if V.Number.Is_Set then WS.Write_Varint (3, V.Number.Value); end if; if V.Label.Is_Set then Label_IO.Write (WS, 4, V.Label.Value); end if; if V.PB_Type.Is_Set then PB_Type_IO.Write (WS, 5, V.PB_Type.Value); end if; if V.Type_Name.Is_Set then WS.Write (6, V.Type_Name.Value); end if; if V.Extendee.Is_Set then WS.Write (2, V.Extendee.Value); end if; if V.Default_Value.Is_Set then WS.Write (7, V.Default_Value.Value); end if; if V.Oneof_Index.Is_Set then WS.Write_Varint (9, V.Oneof_Index.Value); end if; if V.Json_Name.Is_Set then WS.Write (10, V.Json_Name.Value); end if; if V.Options.Is_Set then WS.Write_Key ((8, PB_Support.Length_Delimited)); Google.Protobuf.Descriptor.Field_Options'Write (Stream, V.Options.Value); end if; if WS.End_Message then Write_Field_Descriptor_Proto (WS'Access, V); end if; end; end Write_Field_Descriptor_Proto; function Length (Self : Oneof_Descriptor_Proto_Vector) return Natural is begin return Self.Length; end Length; procedure Clear (Self : in out Oneof_Descriptor_Proto_Vector) is begin Self.Length := 0; end Clear; procedure Free is new Ada.Unchecked_Deallocation (Oneof_Descriptor_Proto_Array, Oneof_Descriptor_Proto_Array_Access); procedure Append (Self : in out Oneof_Descriptor_Proto_Vector; V : Oneof_Descriptor_Proto) is Init_Length : constant Positive := Positive'Max (1, 256 / Oneof_Descriptor_Proto'Size); begin if Self.Length = 0 then Self.Data := new Oneof_Descriptor_Proto_Array (1 .. Init_Length); elsif Self.Length = Self.Data'Last then Self.Data := new Oneof_Descriptor_Proto_Array' (Self.Data.all & Oneof_Descriptor_Proto_Array'(1 .. Self.Length => <>)); end if; Self.Length := Self.Length + 1; Self.Data (Self.Length) := V; end Append; overriding procedure Adjust (Self : in out Oneof_Descriptor_Proto_Vector) is begin if Self.Length > 0 then Self.Data := new Oneof_Descriptor_Proto_Array'(Self.Data (1 .. Self.Length)); end if; end Adjust; overriding procedure Finalize (Self : in out Oneof_Descriptor_Proto_Vector) is begin if Self.Data /= null then Free (Self.Data); end if; end Finalize; not overriding function Get_Oneof_Descriptor_Proto_Variable_Reference (Self : aliased in out Oneof_Descriptor_Proto_Vector; Index : Positive) return Oneof_Descriptor_Proto_Variable_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Oneof_Descriptor_Proto_Variable_Reference; not overriding function Get_Oneof_Descriptor_Proto_Constant_Reference (Self : aliased Oneof_Descriptor_Proto_Vector; Index : Positive) return Oneof_Descriptor_Proto_Constant_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Oneof_Descriptor_Proto_Constant_Reference; procedure Read_Oneof_Descriptor_Proto (Stream : access Ada.Streams.Root_Stream_Type'Class; V : out Oneof_Descriptor_Proto) is Key : aliased PB_Support.IO.Key; begin while PB_Support.IO.Read_Key (Stream, Key'Access) loop case Key.Field is when 1 => if not V.Name.Is_Set then V.Name := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Name.Value); when 2 => if not V.Options.Is_Set then V.Options := (True, others => <>); end if; Oneof_Options_IO.Read (Stream, Key.Encoding, V.Options.Value); when others => PB_Support.IO.Unknown_Field (Stream, Key.Encoding); end case; end loop; end Read_Oneof_Descriptor_Proto; procedure Write_Oneof_Descriptor_Proto (Stream : access Ada.Streams.Root_Stream_Type'Class; V : Oneof_Descriptor_Proto) is begin if Stream.all not in PB_Support.Internal.Stream then declare WS : aliased PB_Support.Internal.Stream (Stream); begin Write_Oneof_Descriptor_Proto (WS'Access, V); return; end; end if; declare WS : PB_Support.Internal.Stream renames PB_Support.Internal.Stream (Stream.all); begin WS.Start_Message; if V.Name.Is_Set then WS.Write (1, V.Name.Value); end if; if V.Options.Is_Set then WS.Write_Key ((2, PB_Support.Length_Delimited)); Google.Protobuf.Descriptor.Oneof_Options'Write (Stream, V.Options.Value); end if; if WS.End_Message then Write_Oneof_Descriptor_Proto (WS'Access, V); end if; end; end Write_Oneof_Descriptor_Proto; function Length (Self : Enum_Descriptor_Proto_Vector) return Natural is begin return Self.Length; end Length; procedure Clear (Self : in out Enum_Descriptor_Proto_Vector) is begin Self.Length := 0; end Clear; procedure Free is new Ada.Unchecked_Deallocation (Enum_Descriptor_Proto_Array, Enum_Descriptor_Proto_Array_Access); procedure Append (Self : in out Enum_Descriptor_Proto_Vector; V : Enum_Descriptor_Proto) is Init_Length : constant Positive := Positive'Max (1, 256 / Enum_Descriptor_Proto'Size); begin if Self.Length = 0 then Self.Data := new Enum_Descriptor_Proto_Array (1 .. Init_Length); elsif Self.Length = Self.Data'Last then Self.Data := new Enum_Descriptor_Proto_Array' (Self.Data.all & Enum_Descriptor_Proto_Array'(1 .. Self.Length => <>)); end if; Self.Length := Self.Length + 1; Self.Data (Self.Length) := V; end Append; overriding procedure Adjust (Self : in out Enum_Descriptor_Proto_Vector) is begin if Self.Length > 0 then Self.Data := new Enum_Descriptor_Proto_Array'(Self.Data (1 .. Self.Length)); end if; end Adjust; overriding procedure Finalize (Self : in out Enum_Descriptor_Proto_Vector) is begin if Self.Data /= null then Free (Self.Data); end if; end Finalize; not overriding function Get_Enum_Descriptor_Proto_Variable_Reference (Self : aliased in out Enum_Descriptor_Proto_Vector; Index : Positive) return Enum_Descriptor_Proto_Variable_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Enum_Descriptor_Proto_Variable_Reference; not overriding function Get_Enum_Descriptor_Proto_Constant_Reference (Self : aliased Enum_Descriptor_Proto_Vector; Index : Positive) return Enum_Descriptor_Proto_Constant_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Enum_Descriptor_Proto_Constant_Reference; procedure Read_Enum_Descriptor_Proto (Stream : access Ada.Streams.Root_Stream_Type'Class; V : out Enum_Descriptor_Proto) is Key : aliased PB_Support.IO.Key; begin while PB_Support.IO.Read_Key (Stream, Key'Access) loop case Key.Field is when 1 => if not V.Name.Is_Set then V.Name := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Name.Value); when 2 => Enum_Value_Descriptor_Proto_IO.Read_Vector (Stream, Key.Encoding, V.Value); when 3 => if not V.Options.Is_Set then V.Options := (True, others => <>); end if; Enum_Options_IO.Read (Stream, Key.Encoding, V.Options.Value); when others => PB_Support.IO.Unknown_Field (Stream, Key.Encoding); end case; end loop; end Read_Enum_Descriptor_Proto; procedure Write_Enum_Descriptor_Proto (Stream : access Ada.Streams.Root_Stream_Type'Class; V : Enum_Descriptor_Proto) is begin if Stream.all not in PB_Support.Internal.Stream then declare WS : aliased PB_Support.Internal.Stream (Stream); begin Write_Enum_Descriptor_Proto (WS'Access, V); return; end; end if; declare WS : PB_Support.Internal.Stream renames PB_Support.Internal.Stream (Stream.all); begin WS.Start_Message; if V.Name.Is_Set then WS.Write (1, V.Name.Value); end if; for J in 1 .. V.Value.Length loop WS.Write_Key ((2, PB_Support.Length_Delimited)); Google.Protobuf.Descriptor.Enum_Value_Descriptor_Proto'Write (Stream, V.Value (J)); end loop; if V.Options.Is_Set then WS.Write_Key ((3, PB_Support.Length_Delimited)); Google.Protobuf.Descriptor.Enum_Options'Write (Stream, V.Options.Value); end if; if WS.End_Message then Write_Enum_Descriptor_Proto (WS'Access, V); end if; end; end Write_Enum_Descriptor_Proto; function Length (Self : Enum_Value_Descriptor_Proto_Vector) return Natural is begin return Self.Length; end Length; procedure Clear (Self : in out Enum_Value_Descriptor_Proto_Vector) is begin Self.Length := 0; end Clear; procedure Free is new Ada.Unchecked_Deallocation (Enum_Value_Descriptor_Proto_Array, Enum_Value_Descriptor_Proto_Array_Access); procedure Append (Self : in out Enum_Value_Descriptor_Proto_Vector; V : Enum_Value_Descriptor_Proto) is Init_Length : constant Positive := Positive'Max (1, 256 / Enum_Value_Descriptor_Proto'Size); begin if Self.Length = 0 then Self.Data := new Enum_Value_Descriptor_Proto_Array (1 .. Init_Length); elsif Self.Length = Self.Data'Last then Self.Data := new Enum_Value_Descriptor_Proto_Array' (Self.Data.all & Enum_Value_Descriptor_Proto_Array'(1 .. Self.Length => <>)); end if; Self.Length := Self.Length + 1; Self.Data (Self.Length) := V; end Append; overriding procedure Adjust (Self : in out Enum_Value_Descriptor_Proto_Vector) is begin if Self.Length > 0 then Self.Data := new Enum_Value_Descriptor_Proto_Array' (Self.Data (1 .. Self.Length)); end if; end Adjust; overriding procedure Finalize (Self : in out Enum_Value_Descriptor_Proto_Vector) is begin if Self.Data /= null then Free (Self.Data); end if; end Finalize; not overriding function Get_Enum_Value_Descriptor_Proto_Variable_Reference (Self : aliased in out Enum_Value_Descriptor_Proto_Vector; Index : Positive) return Enum_Value_Descriptor_Proto_Variable_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Enum_Value_Descriptor_Proto_Variable_Reference; not overriding function Get_Enum_Value_Descriptor_Proto_Constant_Reference (Self : aliased Enum_Value_Descriptor_Proto_Vector; Index : Positive) return Enum_Value_Descriptor_Proto_Constant_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Enum_Value_Descriptor_Proto_Constant_Reference; procedure Read_Enum_Value_Descriptor_Proto (Stream : access Ada.Streams.Root_Stream_Type'Class; V : out Enum_Value_Descriptor_Proto) is Key : aliased PB_Support.IO.Key; begin while PB_Support.IO.Read_Key (Stream, Key'Access) loop case Key.Field is when 1 => if not V.Name.Is_Set then V.Name := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Name.Value); when 2 => if not V.Number.Is_Set then V.Number := (True, others => <>); end if; PB_Support.IO.Read_Varint (Stream, Key.Encoding, V.Number.Value); when 3 => if not V.Options.Is_Set then V.Options := (True, others => <>); end if; Enum_Value_Options_IO.Read (Stream, Key.Encoding, V.Options.Value); when others => PB_Support.IO.Unknown_Field (Stream, Key.Encoding); end case; end loop; end Read_Enum_Value_Descriptor_Proto; procedure Write_Enum_Value_Descriptor_Proto (Stream : access Ada.Streams.Root_Stream_Type'Class; V : Enum_Value_Descriptor_Proto) is begin if Stream.all not in PB_Support.Internal.Stream then declare WS : aliased PB_Support.Internal.Stream (Stream); begin Write_Enum_Value_Descriptor_Proto (WS'Access, V); return; end; end if; declare WS : PB_Support.Internal.Stream renames PB_Support.Internal.Stream (Stream.all); begin WS.Start_Message; if V.Name.Is_Set then WS.Write (1, V.Name.Value); end if; if V.Number.Is_Set then WS.Write_Varint (2, V.Number.Value); end if; if V.Options.Is_Set then WS.Write_Key ((3, PB_Support.Length_Delimited)); Google.Protobuf.Descriptor.Enum_Value_Options'Write (Stream, V.Options.Value); end if; if WS.End_Message then Write_Enum_Value_Descriptor_Proto (WS'Access, V); end if; end; end Write_Enum_Value_Descriptor_Proto; function Length (Self : Service_Descriptor_Proto_Vector) return Natural is begin return Self.Length; end Length; procedure Clear (Self : in out Service_Descriptor_Proto_Vector) is begin Self.Length := 0; end Clear; procedure Free is new Ada.Unchecked_Deallocation (Service_Descriptor_Proto_Array, Service_Descriptor_Proto_Array_Access); procedure Append (Self : in out Service_Descriptor_Proto_Vector; V : Service_Descriptor_Proto) is Init_Length : constant Positive := Positive'Max (1, 256 / Service_Descriptor_Proto'Size); begin if Self.Length = 0 then Self.Data := new Service_Descriptor_Proto_Array (1 .. Init_Length); elsif Self.Length = Self.Data'Last then Self.Data := new Service_Descriptor_Proto_Array' (Self.Data.all & Service_Descriptor_Proto_Array'(1 .. Self.Length => <>)); end if; Self.Length := Self.Length + 1; Self.Data (Self.Length) := V; end Append; overriding procedure Adjust (Self : in out Service_Descriptor_Proto_Vector) is begin if Self.Length > 0 then Self.Data := new Service_Descriptor_Proto_Array'(Self.Data (1 .. Self.Length)); end if; end Adjust; overriding procedure Finalize (Self : in out Service_Descriptor_Proto_Vector) is begin if Self.Data /= null then Free (Self.Data); end if; end Finalize; not overriding function Get_Service_Descriptor_Proto_Variable_Reference (Self : aliased in out Service_Descriptor_Proto_Vector; Index : Positive) return Service_Descriptor_Proto_Variable_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Service_Descriptor_Proto_Variable_Reference; not overriding function Get_Service_Descriptor_Proto_Constant_Reference (Self : aliased Service_Descriptor_Proto_Vector; Index : Positive) return Service_Descriptor_Proto_Constant_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Service_Descriptor_Proto_Constant_Reference; procedure Read_Service_Descriptor_Proto (Stream : access Ada.Streams.Root_Stream_Type'Class; V : out Service_Descriptor_Proto) is Key : aliased PB_Support.IO.Key; begin while PB_Support.IO.Read_Key (Stream, Key'Access) loop case Key.Field is when 1 => if not V.Name.Is_Set then V.Name := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Name.Value); when 2 => Method_Descriptor_Proto_IO.Read_Vector (Stream, Key.Encoding, V.Method); when 3 => if not V.Options.Is_Set then V.Options := (True, others => <>); end if; Service_Options_IO.Read (Stream, Key.Encoding, V.Options.Value); when others => PB_Support.IO.Unknown_Field (Stream, Key.Encoding); end case; end loop; end Read_Service_Descriptor_Proto; procedure Write_Service_Descriptor_Proto (Stream : access Ada.Streams.Root_Stream_Type'Class; V : Service_Descriptor_Proto) is begin if Stream.all not in PB_Support.Internal.Stream then declare WS : aliased PB_Support.Internal.Stream (Stream); begin Write_Service_Descriptor_Proto (WS'Access, V); return; end; end if; declare WS : PB_Support.Internal.Stream renames PB_Support.Internal.Stream (Stream.all); begin WS.Start_Message; if V.Name.Is_Set then WS.Write (1, V.Name.Value); end if; for J in 1 .. V.Method.Length loop WS.Write_Key ((2, PB_Support.Length_Delimited)); Google.Protobuf.Descriptor.Method_Descriptor_Proto'Write (Stream, V.Method (J)); end loop; if V.Options.Is_Set then WS.Write_Key ((3, PB_Support.Length_Delimited)); Google.Protobuf.Descriptor.Service_Options'Write (Stream, V.Options.Value); end if; if WS.End_Message then Write_Service_Descriptor_Proto (WS'Access, V); end if; end; end Write_Service_Descriptor_Proto; function Length (Self : Method_Descriptor_Proto_Vector) return Natural is begin return Self.Length; end Length; procedure Clear (Self : in out Method_Descriptor_Proto_Vector) is begin Self.Length := 0; end Clear; procedure Free is new Ada.Unchecked_Deallocation (Method_Descriptor_Proto_Array, Method_Descriptor_Proto_Array_Access); procedure Append (Self : in out Method_Descriptor_Proto_Vector; V : Method_Descriptor_Proto) is Init_Length : constant Positive := Positive'Max (1, 256 / Method_Descriptor_Proto'Size); begin if Self.Length = 0 then Self.Data := new Method_Descriptor_Proto_Array (1 .. Init_Length); elsif Self.Length = Self.Data'Last then Self.Data := new Method_Descriptor_Proto_Array' (Self.Data.all & Method_Descriptor_Proto_Array'(1 .. Self.Length => <>)); end if; Self.Length := Self.Length + 1; Self.Data (Self.Length) := V; end Append; overriding procedure Adjust (Self : in out Method_Descriptor_Proto_Vector) is begin if Self.Length > 0 then Self.Data := new Method_Descriptor_Proto_Array'(Self.Data (1 .. Self.Length)); end if; end Adjust; overriding procedure Finalize (Self : in out Method_Descriptor_Proto_Vector) is begin if Self.Data /= null then Free (Self.Data); end if; end Finalize; not overriding function Get_Method_Descriptor_Proto_Variable_Reference (Self : aliased in out Method_Descriptor_Proto_Vector; Index : Positive) return Method_Descriptor_Proto_Variable_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Method_Descriptor_Proto_Variable_Reference; not overriding function Get_Method_Descriptor_Proto_Constant_Reference (Self : aliased Method_Descriptor_Proto_Vector; Index : Positive) return Method_Descriptor_Proto_Constant_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Method_Descriptor_Proto_Constant_Reference; procedure Read_Method_Descriptor_Proto (Stream : access Ada.Streams.Root_Stream_Type'Class; V : out Method_Descriptor_Proto) is Key : aliased PB_Support.IO.Key; begin while PB_Support.IO.Read_Key (Stream, Key'Access) loop case Key.Field is when 1 => if not V.Name.Is_Set then V.Name := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Name.Value); when 2 => if not V.Input_Type.Is_Set then V.Input_Type := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Input_Type.Value); when 3 => if not V.Output_Type.Is_Set then V.Output_Type := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Output_Type.Value); when 4 => if not V.Options.Is_Set then V.Options := (True, others => <>); end if; Method_Options_IO.Read (Stream, Key.Encoding, V.Options.Value); when 5 => if not V.Client_Streaming.Is_Set then V.Client_Streaming := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Client_Streaming.Value); when 6 => if not V.Server_Streaming.Is_Set then V.Server_Streaming := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Server_Streaming.Value); when others => PB_Support.IO.Unknown_Field (Stream, Key.Encoding); end case; end loop; end Read_Method_Descriptor_Proto; procedure Write_Method_Descriptor_Proto (Stream : access Ada.Streams.Root_Stream_Type'Class; V : Method_Descriptor_Proto) is begin if Stream.all not in PB_Support.Internal.Stream then declare WS : aliased PB_Support.Internal.Stream (Stream); begin Write_Method_Descriptor_Proto (WS'Access, V); return; end; end if; declare WS : PB_Support.Internal.Stream renames PB_Support.Internal.Stream (Stream.all); begin WS.Start_Message; if V.Name.Is_Set then WS.Write (1, V.Name.Value); end if; if V.Input_Type.Is_Set then WS.Write (2, V.Input_Type.Value); end if; if V.Output_Type.Is_Set then WS.Write (3, V.Output_Type.Value); end if; if V.Options.Is_Set then WS.Write_Key ((4, PB_Support.Length_Delimited)); Google.Protobuf.Descriptor.Method_Options'Write (Stream, V.Options.Value); end if; if V.Client_Streaming.Is_Set then WS.Write (5, V.Client_Streaming.Value); end if; if V.Server_Streaming.Is_Set then WS.Write (6, V.Server_Streaming.Value); end if; if WS.End_Message then Write_Method_Descriptor_Proto (WS'Access, V); end if; end; end Write_Method_Descriptor_Proto; function Length (Self : File_Options_Vector) return Natural is begin return Self.Length; end Length; procedure Clear (Self : in out File_Options_Vector) is begin Self.Length := 0; end Clear; procedure Free is new Ada.Unchecked_Deallocation (File_Options_Array, File_Options_Array_Access); procedure Append (Self : in out File_Options_Vector; V : File_Options) is Init_Length : constant Positive := Positive'Max (1, 256 / File_Options'Size); begin if Self.Length = 0 then Self.Data := new File_Options_Array (1 .. Init_Length); elsif Self.Length = Self.Data'Last then Self.Data := new File_Options_Array' (Self.Data.all & File_Options_Array'(1 .. Self.Length => <>)); end if; Self.Length := Self.Length + 1; Self.Data (Self.Length) := V; end Append; overriding procedure Adjust (Self : in out File_Options_Vector) is begin if Self.Length > 0 then Self.Data := new File_Options_Array'(Self.Data (1 .. Self.Length)); end if; end Adjust; overriding procedure Finalize (Self : in out File_Options_Vector) is begin if Self.Data /= null then Free (Self.Data); end if; end Finalize; not overriding function Get_File_Options_Variable_Reference (Self : aliased in out File_Options_Vector; Index : Positive) return File_Options_Variable_Reference is begin return (Element => Self.Data (Index)'Access); end Get_File_Options_Variable_Reference; not overriding function Get_File_Options_Constant_Reference (Self : aliased File_Options_Vector; Index : Positive) return File_Options_Constant_Reference is begin return (Element => Self.Data (Index)'Access); end Get_File_Options_Constant_Reference; procedure Read_File_Options (Stream : access Ada.Streams.Root_Stream_Type'Class; V : out File_Options) is Key : aliased PB_Support.IO.Key; begin while PB_Support.IO.Read_Key (Stream, Key'Access) loop case Key.Field is when 1 => if not V.Java_Package.Is_Set then V.Java_Package := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Java_Package.Value); when 8 => if not V.Java_Outer_Classname.Is_Set then V.Java_Outer_Classname := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Java_Outer_Classname.Value); when 10 => if not V.Java_Multiple_Files.Is_Set then V.Java_Multiple_Files := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Java_Multiple_Files.Value); when 20 => if not V.Java_Generate_Equals_And_Hash.Is_Set then V.Java_Generate_Equals_And_Hash := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Java_Generate_Equals_And_Hash.Value); when 27 => if not V.Java_String_Check_Utf_8.Is_Set then V.Java_String_Check_Utf_8 := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Java_String_Check_Utf_8.Value); when 9 => if not V.Optimize_For.Is_Set then V.Optimize_For := (True, others => <>); end if; Optimize_Mode_IO.Read (Stream, Key.Encoding, V.Optimize_For.Value); when 11 => if not V.Go_Package.Is_Set then V.Go_Package := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Go_Package.Value); when 16 => if not V.Cc_Generic_Services.Is_Set then V.Cc_Generic_Services := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Cc_Generic_Services.Value); when 17 => if not V.Java_Generic_Services.Is_Set then V.Java_Generic_Services := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Java_Generic_Services.Value); when 18 => if not V.Py_Generic_Services.Is_Set then V.Py_Generic_Services := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Py_Generic_Services.Value); when 23 => if not V.Deprecated.Is_Set then V.Deprecated := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Deprecated.Value); when 31 => if not V.Cc_Enable_Arenas.Is_Set then V.Cc_Enable_Arenas := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Cc_Enable_Arenas.Value); when 36 => if not V.Objc_Class_Prefix.Is_Set then V.Objc_Class_Prefix := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Objc_Class_Prefix.Value); when 37 => if not V.Csharp_Namespace.Is_Set then V.Csharp_Namespace := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Csharp_Namespace.Value); when 999 => Uninterpreted_Option_IO.Read_Vector (Stream, Key.Encoding, V.Uninterpreted_Option); when others => PB_Support.IO.Unknown_Field (Stream, Key.Encoding); end case; end loop; end Read_File_Options; procedure Write_File_Options (Stream : access Ada.Streams.Root_Stream_Type'Class; V : File_Options) is begin if Stream.all not in PB_Support.Internal.Stream then declare WS : aliased PB_Support.Internal.Stream (Stream); begin Write_File_Options (WS'Access, V); return; end; end if; declare WS : PB_Support.Internal.Stream renames PB_Support.Internal.Stream (Stream.all); begin WS.Start_Message; if V.Java_Package.Is_Set then WS.Write (1, V.Java_Package.Value); end if; if V.Java_Outer_Classname.Is_Set then WS.Write (8, V.Java_Outer_Classname.Value); end if; if V.Java_Multiple_Files.Is_Set then WS.Write (10, V.Java_Multiple_Files.Value); end if; if V.Java_Generate_Equals_And_Hash.Is_Set then WS.Write (20, V.Java_Generate_Equals_And_Hash.Value); end if; if V.Java_String_Check_Utf_8.Is_Set then WS.Write (27, V.Java_String_Check_Utf_8.Value); end if; if V.Optimize_For.Is_Set then Optimize_Mode_IO.Write (WS, 9, V.Optimize_For.Value); end if; if V.Go_Package.Is_Set then WS.Write (11, V.Go_Package.Value); end if; if V.Cc_Generic_Services.Is_Set then WS.Write (16, V.Cc_Generic_Services.Value); end if; if V.Java_Generic_Services.Is_Set then WS.Write (17, V.Java_Generic_Services.Value); end if; if V.Py_Generic_Services.Is_Set then WS.Write (18, V.Py_Generic_Services.Value); end if; if V.Deprecated.Is_Set then WS.Write (23, V.Deprecated.Value); end if; if V.Cc_Enable_Arenas.Is_Set then WS.Write (31, V.Cc_Enable_Arenas.Value); end if; if V.Objc_Class_Prefix.Is_Set then WS.Write (36, V.Objc_Class_Prefix.Value); end if; if V.Csharp_Namespace.Is_Set then WS.Write (37, V.Csharp_Namespace.Value); end if; for J in 1 .. V.Uninterpreted_Option.Length loop WS.Write_Key ((999, PB_Support.Length_Delimited)); Google.Protobuf.Descriptor.Uninterpreted_Option'Write (Stream, V.Uninterpreted_Option (J)); end loop; if WS.End_Message then Write_File_Options (WS'Access, V); end if; end; end Write_File_Options; function Length (Self : Message_Options_Vector) return Natural is begin return Self.Length; end Length; procedure Clear (Self : in out Message_Options_Vector) is begin Self.Length := 0; end Clear; procedure Free is new Ada.Unchecked_Deallocation (Message_Options_Array, Message_Options_Array_Access); procedure Append (Self : in out Message_Options_Vector; V : Message_Options) is Init_Length : constant Positive := Positive'Max (1, 256 / Message_Options'Size); begin if Self.Length = 0 then Self.Data := new Message_Options_Array (1 .. Init_Length); elsif Self.Length = Self.Data'Last then Self.Data := new Message_Options_Array' (Self.Data.all & Message_Options_Array'(1 .. Self.Length => <>)); end if; Self.Length := Self.Length + 1; Self.Data (Self.Length) := V; end Append; overriding procedure Adjust (Self : in out Message_Options_Vector) is begin if Self.Length > 0 then Self.Data := new Message_Options_Array'(Self.Data (1 .. Self.Length)); end if; end Adjust; overriding procedure Finalize (Self : in out Message_Options_Vector) is begin if Self.Data /= null then Free (Self.Data); end if; end Finalize; not overriding function Get_Message_Options_Variable_Reference (Self : aliased in out Message_Options_Vector; Index : Positive) return Message_Options_Variable_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Message_Options_Variable_Reference; not overriding function Get_Message_Options_Constant_Reference (Self : aliased Message_Options_Vector; Index : Positive) return Message_Options_Constant_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Message_Options_Constant_Reference; procedure Read_Message_Options (Stream : access Ada.Streams.Root_Stream_Type'Class; V : out Message_Options) is Key : aliased PB_Support.IO.Key; begin while PB_Support.IO.Read_Key (Stream, Key'Access) loop case Key.Field is when 1 => if not V.Message_Set_Wire_Format.Is_Set then V.Message_Set_Wire_Format := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Message_Set_Wire_Format.Value); when 2 => if not V.No_Standard_Descriptor_Accessor.Is_Set then V.No_Standard_Descriptor_Accessor := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.No_Standard_Descriptor_Accessor.Value); when 3 => if not V.Deprecated.Is_Set then V.Deprecated := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Deprecated.Value); when 7 => if not V.Map_Entry.Is_Set then V.Map_Entry := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Map_Entry.Value); when 999 => Uninterpreted_Option_IO.Read_Vector (Stream, Key.Encoding, V.Uninterpreted_Option); when others => PB_Support.IO.Unknown_Field (Stream, Key.Encoding); end case; end loop; end Read_Message_Options; procedure Write_Message_Options (Stream : access Ada.Streams.Root_Stream_Type'Class; V : Message_Options) is begin if Stream.all not in PB_Support.Internal.Stream then declare WS : aliased PB_Support.Internal.Stream (Stream); begin Write_Message_Options (WS'Access, V); return; end; end if; declare WS : PB_Support.Internal.Stream renames PB_Support.Internal.Stream (Stream.all); begin WS.Start_Message; if V.Message_Set_Wire_Format.Is_Set then WS.Write (1, V.Message_Set_Wire_Format.Value); end if; if V.No_Standard_Descriptor_Accessor.Is_Set then WS.Write (2, V.No_Standard_Descriptor_Accessor.Value); end if; if V.Deprecated.Is_Set then WS.Write (3, V.Deprecated.Value); end if; if V.Map_Entry.Is_Set then WS.Write (7, V.Map_Entry.Value); end if; for J in 1 .. V.Uninterpreted_Option.Length loop WS.Write_Key ((999, PB_Support.Length_Delimited)); Google.Protobuf.Descriptor.Uninterpreted_Option'Write (Stream, V.Uninterpreted_Option (J)); end loop; if WS.End_Message then Write_Message_Options (WS'Access, V); end if; end; end Write_Message_Options; function Length (Self : Field_Options_Vector) return Natural is begin return Self.Length; end Length; procedure Clear (Self : in out Field_Options_Vector) is begin Self.Length := 0; end Clear; procedure Free is new Ada.Unchecked_Deallocation (Field_Options_Array, Field_Options_Array_Access); procedure Append (Self : in out Field_Options_Vector; V : Field_Options) is Init_Length : constant Positive := Positive'Max (1, 256 / Field_Options'Size); begin if Self.Length = 0 then Self.Data := new Field_Options_Array (1 .. Init_Length); elsif Self.Length = Self.Data'Last then Self.Data := new Field_Options_Array' (Self.Data.all & Field_Options_Array'(1 .. Self.Length => <>)); end if; Self.Length := Self.Length + 1; Self.Data (Self.Length) := V; end Append; overriding procedure Adjust (Self : in out Field_Options_Vector) is begin if Self.Length > 0 then Self.Data := new Field_Options_Array'(Self.Data (1 .. Self.Length)); end if; end Adjust; overriding procedure Finalize (Self : in out Field_Options_Vector) is begin if Self.Data /= null then Free (Self.Data); end if; end Finalize; not overriding function Get_Field_Options_Variable_Reference (Self : aliased in out Field_Options_Vector; Index : Positive) return Field_Options_Variable_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Field_Options_Variable_Reference; not overriding function Get_Field_Options_Constant_Reference (Self : aliased Field_Options_Vector; Index : Positive) return Field_Options_Constant_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Field_Options_Constant_Reference; procedure Read_Field_Options (Stream : access Ada.Streams.Root_Stream_Type'Class; V : out Field_Options) is Key : aliased PB_Support.IO.Key; begin while PB_Support.IO.Read_Key (Stream, Key'Access) loop case Key.Field is when 1 => if not V.Ctype.Is_Set then V.Ctype := (True, others => <>); end if; CType_IO.Read (Stream, Key.Encoding, V.Ctype.Value); when 2 => if not V.Packed.Is_Set then V.Packed := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Packed.Value); when 6 => if not V.Jstype.Is_Set then V.Jstype := (True, others => <>); end if; JSType_IO.Read (Stream, Key.Encoding, V.Jstype.Value); when 5 => if not V.Lazy.Is_Set then V.Lazy := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Lazy.Value); when 3 => if not V.Deprecated.Is_Set then V.Deprecated := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Deprecated.Value); when 10 => if not V.Weak.Is_Set then V.Weak := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Weak.Value); when 999 => Uninterpreted_Option_IO.Read_Vector (Stream, Key.Encoding, V.Uninterpreted_Option); when others => PB_Support.IO.Unknown_Field (Stream, Key.Encoding); end case; end loop; end Read_Field_Options; procedure Write_Field_Options (Stream : access Ada.Streams.Root_Stream_Type'Class; V : Field_Options) is begin if Stream.all not in PB_Support.Internal.Stream then declare WS : aliased PB_Support.Internal.Stream (Stream); begin Write_Field_Options (WS'Access, V); return; end; end if; declare WS : PB_Support.Internal.Stream renames PB_Support.Internal.Stream (Stream.all); begin WS.Start_Message; if V.Ctype.Is_Set then CType_IO.Write (WS, 1, V.Ctype.Value); end if; if V.Packed.Is_Set then WS.Write (2, V.Packed.Value); end if; if V.Jstype.Is_Set then JSType_IO.Write (WS, 6, V.Jstype.Value); end if; if V.Lazy.Is_Set then WS.Write (5, V.Lazy.Value); end if; if V.Deprecated.Is_Set then WS.Write (3, V.Deprecated.Value); end if; if V.Weak.Is_Set then WS.Write (10, V.Weak.Value); end if; for J in 1 .. V.Uninterpreted_Option.Length loop WS.Write_Key ((999, PB_Support.Length_Delimited)); Google.Protobuf.Descriptor.Uninterpreted_Option'Write (Stream, V.Uninterpreted_Option (J)); end loop; if WS.End_Message then Write_Field_Options (WS'Access, V); end if; end; end Write_Field_Options; function Length (Self : Oneof_Options_Vector) return Natural is begin return Self.Length; end Length; procedure Clear (Self : in out Oneof_Options_Vector) is begin Self.Length := 0; end Clear; procedure Free is new Ada.Unchecked_Deallocation (Oneof_Options_Array, Oneof_Options_Array_Access); procedure Append (Self : in out Oneof_Options_Vector; V : Oneof_Options) is Init_Length : constant Positive := Positive'Max (1, 256 / Oneof_Options'Size); begin if Self.Length = 0 then Self.Data := new Oneof_Options_Array (1 .. Init_Length); elsif Self.Length = Self.Data'Last then Self.Data := new Oneof_Options_Array' (Self.Data.all & Oneof_Options_Array'(1 .. Self.Length => <>)); end if; Self.Length := Self.Length + 1; Self.Data (Self.Length) := V; end Append; overriding procedure Adjust (Self : in out Oneof_Options_Vector) is begin if Self.Length > 0 then Self.Data := new Oneof_Options_Array'(Self.Data (1 .. Self.Length)); end if; end Adjust; overriding procedure Finalize (Self : in out Oneof_Options_Vector) is begin if Self.Data /= null then Free (Self.Data); end if; end Finalize; not overriding function Get_Oneof_Options_Variable_Reference (Self : aliased in out Oneof_Options_Vector; Index : Positive) return Oneof_Options_Variable_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Oneof_Options_Variable_Reference; not overriding function Get_Oneof_Options_Constant_Reference (Self : aliased Oneof_Options_Vector; Index : Positive) return Oneof_Options_Constant_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Oneof_Options_Constant_Reference; procedure Read_Oneof_Options (Stream : access Ada.Streams.Root_Stream_Type'Class; V : out Oneof_Options) is Key : aliased PB_Support.IO.Key; begin while PB_Support.IO.Read_Key (Stream, Key'Access) loop case Key.Field is when 999 => Uninterpreted_Option_IO.Read_Vector (Stream, Key.Encoding, V.Uninterpreted_Option); when others => PB_Support.IO.Unknown_Field (Stream, Key.Encoding); end case; end loop; end Read_Oneof_Options; procedure Write_Oneof_Options (Stream : access Ada.Streams.Root_Stream_Type'Class; V : Oneof_Options) is begin if Stream.all not in PB_Support.Internal.Stream then declare WS : aliased PB_Support.Internal.Stream (Stream); begin Write_Oneof_Options (WS'Access, V); return; end; end if; declare WS : PB_Support.Internal.Stream renames PB_Support.Internal.Stream (Stream.all); begin WS.Start_Message; for J in 1 .. V.Uninterpreted_Option.Length loop WS.Write_Key ((999, PB_Support.Length_Delimited)); Google.Protobuf.Descriptor.Uninterpreted_Option'Write (Stream, V.Uninterpreted_Option (J)); end loop; if WS.End_Message then Write_Oneof_Options (WS'Access, V); end if; end; end Write_Oneof_Options; function Length (Self : Enum_Options_Vector) return Natural is begin return Self.Length; end Length; procedure Clear (Self : in out Enum_Options_Vector) is begin Self.Length := 0; end Clear; procedure Free is new Ada.Unchecked_Deallocation (Enum_Options_Array, Enum_Options_Array_Access); procedure Append (Self : in out Enum_Options_Vector; V : Enum_Options) is Init_Length : constant Positive := Positive'Max (1, 256 / Enum_Options'Size); begin if Self.Length = 0 then Self.Data := new Enum_Options_Array (1 .. Init_Length); elsif Self.Length = Self.Data'Last then Self.Data := new Enum_Options_Array' (Self.Data.all & Enum_Options_Array'(1 .. Self.Length => <>)); end if; Self.Length := Self.Length + 1; Self.Data (Self.Length) := V; end Append; overriding procedure Adjust (Self : in out Enum_Options_Vector) is begin if Self.Length > 0 then Self.Data := new Enum_Options_Array'(Self.Data (1 .. Self.Length)); end if; end Adjust; overriding procedure Finalize (Self : in out Enum_Options_Vector) is begin if Self.Data /= null then Free (Self.Data); end if; end Finalize; not overriding function Get_Enum_Options_Variable_Reference (Self : aliased in out Enum_Options_Vector; Index : Positive) return Enum_Options_Variable_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Enum_Options_Variable_Reference; not overriding function Get_Enum_Options_Constant_Reference (Self : aliased Enum_Options_Vector; Index : Positive) return Enum_Options_Constant_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Enum_Options_Constant_Reference; procedure Read_Enum_Options (Stream : access Ada.Streams.Root_Stream_Type'Class; V : out Enum_Options) is Key : aliased PB_Support.IO.Key; begin while PB_Support.IO.Read_Key (Stream, Key'Access) loop case Key.Field is when 2 => if not V.Allow_Alias.Is_Set then V.Allow_Alias := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Allow_Alias.Value); when 3 => if not V.Deprecated.Is_Set then V.Deprecated := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Deprecated.Value); when 999 => Uninterpreted_Option_IO.Read_Vector (Stream, Key.Encoding, V.Uninterpreted_Option); when others => PB_Support.IO.Unknown_Field (Stream, Key.Encoding); end case; end loop; end Read_Enum_Options; procedure Write_Enum_Options (Stream : access Ada.Streams.Root_Stream_Type'Class; V : Enum_Options) is begin if Stream.all not in PB_Support.Internal.Stream then declare WS : aliased PB_Support.Internal.Stream (Stream); begin Write_Enum_Options (WS'Access, V); return; end; end if; declare WS : PB_Support.Internal.Stream renames PB_Support.Internal.Stream (Stream.all); begin WS.Start_Message; if V.Allow_Alias.Is_Set then WS.Write (2, V.Allow_Alias.Value); end if; if V.Deprecated.Is_Set then WS.Write (3, V.Deprecated.Value); end if; for J in 1 .. V.Uninterpreted_Option.Length loop WS.Write_Key ((999, PB_Support.Length_Delimited)); Google.Protobuf.Descriptor.Uninterpreted_Option'Write (Stream, V.Uninterpreted_Option (J)); end loop; if WS.End_Message then Write_Enum_Options (WS'Access, V); end if; end; end Write_Enum_Options; function Length (Self : Enum_Value_Options_Vector) return Natural is begin return Self.Length; end Length; procedure Clear (Self : in out Enum_Value_Options_Vector) is begin Self.Length := 0; end Clear; procedure Free is new Ada.Unchecked_Deallocation (Enum_Value_Options_Array, Enum_Value_Options_Array_Access); procedure Append (Self : in out Enum_Value_Options_Vector; V : Enum_Value_Options) is Init_Length : constant Positive := Positive'Max (1, 256 / Enum_Value_Options'Size); begin if Self.Length = 0 then Self.Data := new Enum_Value_Options_Array (1 .. Init_Length); elsif Self.Length = Self.Data'Last then Self.Data := new Enum_Value_Options_Array' (Self.Data.all & Enum_Value_Options_Array'(1 .. Self.Length => <>)); end if; Self.Length := Self.Length + 1; Self.Data (Self.Length) := V; end Append; overriding procedure Adjust (Self : in out Enum_Value_Options_Vector) is begin if Self.Length > 0 then Self.Data := new Enum_Value_Options_Array'(Self.Data (1 .. Self.Length)); end if; end Adjust; overriding procedure Finalize (Self : in out Enum_Value_Options_Vector) is begin if Self.Data /= null then Free (Self.Data); end if; end Finalize; not overriding function Get_Enum_Value_Options_Variable_Reference (Self : aliased in out Enum_Value_Options_Vector; Index : Positive) return Enum_Value_Options_Variable_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Enum_Value_Options_Variable_Reference; not overriding function Get_Enum_Value_Options_Constant_Reference (Self : aliased Enum_Value_Options_Vector; Index : Positive) return Enum_Value_Options_Constant_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Enum_Value_Options_Constant_Reference; procedure Read_Enum_Value_Options (Stream : access Ada.Streams.Root_Stream_Type'Class; V : out Enum_Value_Options) is Key : aliased PB_Support.IO.Key; begin while PB_Support.IO.Read_Key (Stream, Key'Access) loop case Key.Field is when 1 => if not V.Deprecated.Is_Set then V.Deprecated := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Deprecated.Value); when 999 => Uninterpreted_Option_IO.Read_Vector (Stream, Key.Encoding, V.Uninterpreted_Option); when others => PB_Support.IO.Unknown_Field (Stream, Key.Encoding); end case; end loop; end Read_Enum_Value_Options; procedure Write_Enum_Value_Options (Stream : access Ada.Streams.Root_Stream_Type'Class; V : Enum_Value_Options) is begin if Stream.all not in PB_Support.Internal.Stream then declare WS : aliased PB_Support.Internal.Stream (Stream); begin Write_Enum_Value_Options (WS'Access, V); return; end; end if; declare WS : PB_Support.Internal.Stream renames PB_Support.Internal.Stream (Stream.all); begin WS.Start_Message; if V.Deprecated.Is_Set then WS.Write (1, V.Deprecated.Value); end if; for J in 1 .. V.Uninterpreted_Option.Length loop WS.Write_Key ((999, PB_Support.Length_Delimited)); Google.Protobuf.Descriptor.Uninterpreted_Option'Write (Stream, V.Uninterpreted_Option (J)); end loop; if WS.End_Message then Write_Enum_Value_Options (WS'Access, V); end if; end; end Write_Enum_Value_Options; function Length (Self : Service_Options_Vector) return Natural is begin return Self.Length; end Length; procedure Clear (Self : in out Service_Options_Vector) is begin Self.Length := 0; end Clear; procedure Free is new Ada.Unchecked_Deallocation (Service_Options_Array, Service_Options_Array_Access); procedure Append (Self : in out Service_Options_Vector; V : Service_Options) is Init_Length : constant Positive := Positive'Max (1, 256 / Service_Options'Size); begin if Self.Length = 0 then Self.Data := new Service_Options_Array (1 .. Init_Length); elsif Self.Length = Self.Data'Last then Self.Data := new Service_Options_Array' (Self.Data.all & Service_Options_Array'(1 .. Self.Length => <>)); end if; Self.Length := Self.Length + 1; Self.Data (Self.Length) := V; end Append; overriding procedure Adjust (Self : in out Service_Options_Vector) is begin if Self.Length > 0 then Self.Data := new Service_Options_Array'(Self.Data (1 .. Self.Length)); end if; end Adjust; overriding procedure Finalize (Self : in out Service_Options_Vector) is begin if Self.Data /= null then Free (Self.Data); end if; end Finalize; not overriding function Get_Service_Options_Variable_Reference (Self : aliased in out Service_Options_Vector; Index : Positive) return Service_Options_Variable_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Service_Options_Variable_Reference; not overriding function Get_Service_Options_Constant_Reference (Self : aliased Service_Options_Vector; Index : Positive) return Service_Options_Constant_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Service_Options_Constant_Reference; procedure Read_Service_Options (Stream : access Ada.Streams.Root_Stream_Type'Class; V : out Service_Options) is Key : aliased PB_Support.IO.Key; begin while PB_Support.IO.Read_Key (Stream, Key'Access) loop case Key.Field is when 33 => if not V.Deprecated.Is_Set then V.Deprecated := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Deprecated.Value); when 999 => Uninterpreted_Option_IO.Read_Vector (Stream, Key.Encoding, V.Uninterpreted_Option); when others => PB_Support.IO.Unknown_Field (Stream, Key.Encoding); end case; end loop; end Read_Service_Options; procedure Write_Service_Options (Stream : access Ada.Streams.Root_Stream_Type'Class; V : Service_Options) is begin if Stream.all not in PB_Support.Internal.Stream then declare WS : aliased PB_Support.Internal.Stream (Stream); begin Write_Service_Options (WS'Access, V); return; end; end if; declare WS : PB_Support.Internal.Stream renames PB_Support.Internal.Stream (Stream.all); begin WS.Start_Message; if V.Deprecated.Is_Set then WS.Write (33, V.Deprecated.Value); end if; for J in 1 .. V.Uninterpreted_Option.Length loop WS.Write_Key ((999, PB_Support.Length_Delimited)); Google.Protobuf.Descriptor.Uninterpreted_Option'Write (Stream, V.Uninterpreted_Option (J)); end loop; if WS.End_Message then Write_Service_Options (WS'Access, V); end if; end; end Write_Service_Options; function Length (Self : Method_Options_Vector) return Natural is begin return Self.Length; end Length; procedure Clear (Self : in out Method_Options_Vector) is begin Self.Length := 0; end Clear; procedure Free is new Ada.Unchecked_Deallocation (Method_Options_Array, Method_Options_Array_Access); procedure Append (Self : in out Method_Options_Vector; V : Method_Options) is Init_Length : constant Positive := Positive'Max (1, 256 / Method_Options'Size); begin if Self.Length = 0 then Self.Data := new Method_Options_Array (1 .. Init_Length); elsif Self.Length = Self.Data'Last then Self.Data := new Method_Options_Array' (Self.Data.all & Method_Options_Array'(1 .. Self.Length => <>)); end if; Self.Length := Self.Length + 1; Self.Data (Self.Length) := V; end Append; overriding procedure Adjust (Self : in out Method_Options_Vector) is begin if Self.Length > 0 then Self.Data := new Method_Options_Array'(Self.Data (1 .. Self.Length)); end if; end Adjust; overriding procedure Finalize (Self : in out Method_Options_Vector) is begin if Self.Data /= null then Free (Self.Data); end if; end Finalize; not overriding function Get_Method_Options_Variable_Reference (Self : aliased in out Method_Options_Vector; Index : Positive) return Method_Options_Variable_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Method_Options_Variable_Reference; not overriding function Get_Method_Options_Constant_Reference (Self : aliased Method_Options_Vector; Index : Positive) return Method_Options_Constant_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Method_Options_Constant_Reference; procedure Read_Method_Options (Stream : access Ada.Streams.Root_Stream_Type'Class; V : out Method_Options) is Key : aliased PB_Support.IO.Key; begin while PB_Support.IO.Read_Key (Stream, Key'Access) loop case Key.Field is when 33 => if not V.Deprecated.Is_Set then V.Deprecated := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Deprecated.Value); when 999 => Uninterpreted_Option_IO.Read_Vector (Stream, Key.Encoding, V.Uninterpreted_Option); when others => PB_Support.IO.Unknown_Field (Stream, Key.Encoding); end case; end loop; end Read_Method_Options; procedure Write_Method_Options (Stream : access Ada.Streams.Root_Stream_Type'Class; V : Method_Options) is begin if Stream.all not in PB_Support.Internal.Stream then declare WS : aliased PB_Support.Internal.Stream (Stream); begin Write_Method_Options (WS'Access, V); return; end; end if; declare WS : PB_Support.Internal.Stream renames PB_Support.Internal.Stream (Stream.all); begin WS.Start_Message; if V.Deprecated.Is_Set then WS.Write (33, V.Deprecated.Value); end if; for J in 1 .. V.Uninterpreted_Option.Length loop WS.Write_Key ((999, PB_Support.Length_Delimited)); Google.Protobuf.Descriptor.Uninterpreted_Option'Write (Stream, V.Uninterpreted_Option (J)); end loop; if WS.End_Message then Write_Method_Options (WS'Access, V); end if; end; end Write_Method_Options; function Length (Self : Uninterpreted_Option_Vector) return Natural is begin return Self.Length; end Length; procedure Clear (Self : in out Uninterpreted_Option_Vector) is begin Self.Length := 0; end Clear; procedure Free is new Ada.Unchecked_Deallocation (Uninterpreted_Option_Array, Uninterpreted_Option_Array_Access); procedure Append (Self : in out Uninterpreted_Option_Vector; V : Uninterpreted_Option) is Init_Length : constant Positive := Positive'Max (1, 256 / Uninterpreted_Option'Size); begin if Self.Length = 0 then Self.Data := new Uninterpreted_Option_Array (1 .. Init_Length); elsif Self.Length = Self.Data'Last then Self.Data := new Uninterpreted_Option_Array' (Self.Data.all & Uninterpreted_Option_Array'(1 .. Self.Length => <>)); end if; Self.Length := Self.Length + 1; Self.Data (Self.Length) := V; end Append; overriding procedure Adjust (Self : in out Uninterpreted_Option_Vector) is begin if Self.Length > 0 then Self.Data := new Uninterpreted_Option_Array'(Self.Data (1 .. Self.Length)); end if; end Adjust; overriding procedure Finalize (Self : in out Uninterpreted_Option_Vector) is begin if Self.Data /= null then Free (Self.Data); end if; end Finalize; not overriding function Get_Uninterpreted_Option_Variable_Reference (Self : aliased in out Uninterpreted_Option_Vector; Index : Positive) return Uninterpreted_Option_Variable_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Uninterpreted_Option_Variable_Reference; not overriding function Get_Uninterpreted_Option_Constant_Reference (Self : aliased Uninterpreted_Option_Vector; Index : Positive) return Uninterpreted_Option_Constant_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Uninterpreted_Option_Constant_Reference; procedure Read_Uninterpreted_Option (Stream : access Ada.Streams.Root_Stream_Type'Class; V : out Uninterpreted_Option) is Key : aliased PB_Support.IO.Key; begin while PB_Support.IO.Read_Key (Stream, Key'Access) loop case Key.Field is when 2 => Name_Part_IO.Read_Vector (Stream, Key.Encoding, V.Name); when 3 => if not V.Identifier_Value.Is_Set then V.Identifier_Value := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Identifier_Value.Value); when 4 => if not V.Positive_Int_Value.Is_Set then V.Positive_Int_Value := (True, others => <>); end if; PB_Support.IO.Read_Varint (Stream, Key.Encoding, V.Positive_Int_Value.Value); when 5 => if not V.Negative_Int_Value.Is_Set then V.Negative_Int_Value := (True, others => <>); end if; PB_Support.IO.Read_Varint (Stream, Key.Encoding, V.Negative_Int_Value.Value); when 6 => if not V.Double_Value.Is_Set then V.Double_Value := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Double_Value.Value); when 7 => if not V.String_Value.Is_Set then V.String_Value := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.String_Value.Value); when 8 => if not V.Aggregate_Value.Is_Set then V.Aggregate_Value := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Aggregate_Value.Value); when others => PB_Support.IO.Unknown_Field (Stream, Key.Encoding); end case; end loop; end Read_Uninterpreted_Option; procedure Write_Uninterpreted_Option (Stream : access Ada.Streams.Root_Stream_Type'Class; V : Uninterpreted_Option) is begin if Stream.all not in PB_Support.Internal.Stream then declare WS : aliased PB_Support.Internal.Stream (Stream); begin Write_Uninterpreted_Option (WS'Access, V); return; end; end if; declare WS : PB_Support.Internal.Stream renames PB_Support.Internal.Stream (Stream.all); begin WS.Start_Message; for J in 1 .. V.Name.Length loop WS.Write_Key ((2, PB_Support.Length_Delimited)); Google.Protobuf.Descriptor.Name_Part'Write (Stream, V.Name (J)); end loop; if V.Identifier_Value.Is_Set then WS.Write (3, V.Identifier_Value.Value); end if; if V.Positive_Int_Value.Is_Set then WS.Write_Varint (4, V.Positive_Int_Value.Value); end if; if V.Negative_Int_Value.Is_Set then WS.Write_Varint (5, V.Negative_Int_Value.Value); end if; if V.Double_Value.Is_Set then WS.Write (6, V.Double_Value.Value); end if; if V.String_Value.Is_Set then WS.Write (7, V.String_Value.Value); end if; if V.Aggregate_Value.Is_Set then WS.Write (8, V.Aggregate_Value.Value); end if; if WS.End_Message then Write_Uninterpreted_Option (WS'Access, V); end if; end; end Write_Uninterpreted_Option; function Length (Self : Name_Part_Vector) return Natural is begin return Self.Length; end Length; procedure Clear (Self : in out Name_Part_Vector) is begin Self.Length := 0; end Clear; procedure Free is new Ada.Unchecked_Deallocation (Name_Part_Array, Name_Part_Array_Access); procedure Append (Self : in out Name_Part_Vector; V : Name_Part) is Init_Length : constant Positive := Positive'Max (1, 256 / Name_Part'Size); begin if Self.Length = 0 then Self.Data := new Name_Part_Array (1 .. Init_Length); elsif Self.Length = Self.Data'Last then Self.Data := new Name_Part_Array' (Self.Data.all & Name_Part_Array'(1 .. Self.Length => <>)); end if; Self.Length := Self.Length + 1; Self.Data (Self.Length) := V; end Append; overriding procedure Adjust (Self : in out Name_Part_Vector) is begin if Self.Length > 0 then Self.Data := new Name_Part_Array'(Self.Data (1 .. Self.Length)); end if; end Adjust; overriding procedure Finalize (Self : in out Name_Part_Vector) is begin if Self.Data /= null then Free (Self.Data); end if; end Finalize; not overriding function Get_Name_Part_Variable_Reference (Self : aliased in out Name_Part_Vector; Index : Positive) return Name_Part_Variable_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Name_Part_Variable_Reference; not overriding function Get_Name_Part_Constant_Reference (Self : aliased Name_Part_Vector; Index : Positive) return Name_Part_Constant_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Name_Part_Constant_Reference; procedure Read_Name_Part (Stream : access Ada.Streams.Root_Stream_Type'Class; V : out Name_Part) is Key : aliased PB_Support.IO.Key; begin while PB_Support.IO.Read_Key (Stream, Key'Access) loop case Key.Field is when 1 => PB_Support.IO.Read (Stream, Key.Encoding, V.Name_Part); when 2 => PB_Support.IO.Read (Stream, Key.Encoding, V.Is_Extension); when others => PB_Support.IO.Unknown_Field (Stream, Key.Encoding); end case; end loop; end Read_Name_Part; procedure Write_Name_Part (Stream : access Ada.Streams.Root_Stream_Type'Class; V : Name_Part) is begin if Stream.all not in PB_Support.Internal.Stream then declare WS : aliased PB_Support.Internal.Stream (Stream); begin Write_Name_Part (WS'Access, V); return; end; end if; declare WS : PB_Support.Internal.Stream renames PB_Support.Internal.Stream (Stream.all); begin WS.Start_Message; WS.Write (1, V.Name_Part); WS.Write (2, V.Is_Extension); if WS.End_Message then Write_Name_Part (WS'Access, V); end if; end; end Write_Name_Part; function Length (Self : Source_Code_Info_Vector) return Natural is begin return Self.Length; end Length; procedure Clear (Self : in out Source_Code_Info_Vector) is begin Self.Length := 0; end Clear; procedure Free is new Ada.Unchecked_Deallocation (Source_Code_Info_Array, Source_Code_Info_Array_Access); procedure Append (Self : in out Source_Code_Info_Vector; V : Source_Code_Info) is Init_Length : constant Positive := Positive'Max (1, 256 / Source_Code_Info'Size); begin if Self.Length = 0 then Self.Data := new Source_Code_Info_Array (1 .. Init_Length); elsif Self.Length = Self.Data'Last then Self.Data := new Source_Code_Info_Array' (Self.Data.all & Source_Code_Info_Array'(1 .. Self.Length => <>)); end if; Self.Length := Self.Length + 1; Self.Data (Self.Length) := V; end Append; overriding procedure Adjust (Self : in out Source_Code_Info_Vector) is begin if Self.Length > 0 then Self.Data := new Source_Code_Info_Array'(Self.Data (1 .. Self.Length)); end if; end Adjust; overriding procedure Finalize (Self : in out Source_Code_Info_Vector) is begin if Self.Data /= null then Free (Self.Data); end if; end Finalize; not overriding function Get_Source_Code_Info_Variable_Reference (Self : aliased in out Source_Code_Info_Vector; Index : Positive) return Source_Code_Info_Variable_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Source_Code_Info_Variable_Reference; not overriding function Get_Source_Code_Info_Constant_Reference (Self : aliased Source_Code_Info_Vector; Index : Positive) return Source_Code_Info_Constant_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Source_Code_Info_Constant_Reference; procedure Read_Source_Code_Info (Stream : access Ada.Streams.Root_Stream_Type'Class; V : out Source_Code_Info) is Key : aliased PB_Support.IO.Key; begin while PB_Support.IO.Read_Key (Stream, Key'Access) loop case Key.Field is when 1 => Location_IO.Read_Vector (Stream, Key.Encoding, V.Location); when others => PB_Support.IO.Unknown_Field (Stream, Key.Encoding); end case; end loop; end Read_Source_Code_Info; procedure Write_Source_Code_Info (Stream : access Ada.Streams.Root_Stream_Type'Class; V : Source_Code_Info) is begin if Stream.all not in PB_Support.Internal.Stream then declare WS : aliased PB_Support.Internal.Stream (Stream); begin Write_Source_Code_Info (WS'Access, V); return; end; end if; declare WS : PB_Support.Internal.Stream renames PB_Support.Internal.Stream (Stream.all); begin WS.Start_Message; for J in 1 .. V.Location.Length loop WS.Write_Key ((1, PB_Support.Length_Delimited)); Google.Protobuf.Descriptor.Location'Write (Stream, V.Location (J)); end loop; if WS.End_Message then Write_Source_Code_Info (WS'Access, V); end if; end; end Write_Source_Code_Info; function Length (Self : Location_Vector) return Natural is begin return Self.Length; end Length; procedure Clear (Self : in out Location_Vector) is begin Self.Length := 0; end Clear; procedure Free is new Ada.Unchecked_Deallocation (Location_Array, Location_Array_Access); procedure Append (Self : in out Location_Vector; V : Location) is Init_Length : constant Positive := Positive'Max (1, 256 / Location'Size); begin if Self.Length = 0 then Self.Data := new Location_Array (1 .. Init_Length); elsif Self.Length = Self.Data'Last then Self.Data := new Location_Array' (Self.Data.all & Location_Array'(1 .. Self.Length => <>)); end if; Self.Length := Self.Length + 1; Self.Data (Self.Length) := V; end Append; overriding procedure Adjust (Self : in out Location_Vector) is begin if Self.Length > 0 then Self.Data := new Location_Array'(Self.Data (1 .. Self.Length)); end if; end Adjust; overriding procedure Finalize (Self : in out Location_Vector) is begin if Self.Data /= null then Free (Self.Data); end if; end Finalize; not overriding function Get_Location_Variable_Reference (Self : aliased in out Location_Vector; Index : Positive) return Location_Variable_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Location_Variable_Reference; not overriding function Get_Location_Constant_Reference (Self : aliased Location_Vector; Index : Positive) return Location_Constant_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Location_Constant_Reference; procedure Read_Location (Stream : access Ada.Streams.Root_Stream_Type'Class; V : out Location) is Key : aliased PB_Support.IO.Key; begin while PB_Support.IO.Read_Key (Stream, Key'Access) loop case Key.Field is when 1 => PB_Support.IO.Read_Varint_Vector (Stream, Key.Encoding, V.Path); when 2 => PB_Support.IO.Read_Varint_Vector (Stream, Key.Encoding, V.Span); when 3 => if not V.Leading_Comments.Is_Set then V.Leading_Comments := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Leading_Comments.Value); when 4 => if not V.Trailing_Comments.Is_Set then V.Trailing_Comments := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Trailing_Comments.Value); when 6 => PB_Support.IO.Read_Vector (Stream, Key.Encoding, V.Leading_Detached_Comments); when others => PB_Support.IO.Unknown_Field (Stream, Key.Encoding); end case; end loop; end Read_Location; procedure Write_Location (Stream : access Ada.Streams.Root_Stream_Type'Class; V : Location) is begin if Stream.all not in PB_Support.Internal.Stream then declare WS : aliased PB_Support.Internal.Stream (Stream); begin Write_Location (WS'Access, V); return; end; end if; declare WS : PB_Support.Internal.Stream renames PB_Support.Internal.Stream (Stream.all); begin WS.Start_Message; WS.Write_Varint_Packed (1, V.Path); WS.Write_Varint_Packed (2, V.Span); if V.Leading_Comments.Is_Set then WS.Write (3, V.Leading_Comments.Value); end if; if V.Trailing_Comments.Is_Set then WS.Write (4, V.Trailing_Comments.Value); end if; WS.Write (6, V.Leading_Detached_Comments); if WS.End_Message then Write_Location (WS'Access, V); end if; end; end Write_Location; function Length (Self : Generated_Code_Info_Vector) return Natural is begin return Self.Length; end Length; procedure Clear (Self : in out Generated_Code_Info_Vector) is begin Self.Length := 0; end Clear; procedure Free is new Ada.Unchecked_Deallocation (Generated_Code_Info_Array, Generated_Code_Info_Array_Access); procedure Append (Self : in out Generated_Code_Info_Vector; V : Generated_Code_Info) is Init_Length : constant Positive := Positive'Max (1, 256 / Generated_Code_Info'Size); begin if Self.Length = 0 then Self.Data := new Generated_Code_Info_Array (1 .. Init_Length); elsif Self.Length = Self.Data'Last then Self.Data := new Generated_Code_Info_Array' (Self.Data.all & Generated_Code_Info_Array'(1 .. Self.Length => <>)); end if; Self.Length := Self.Length + 1; Self.Data (Self.Length) := V; end Append; overriding procedure Adjust (Self : in out Generated_Code_Info_Vector) is begin if Self.Length > 0 then Self.Data := new Generated_Code_Info_Array'(Self.Data (1 .. Self.Length)); end if; end Adjust; overriding procedure Finalize (Self : in out Generated_Code_Info_Vector) is begin if Self.Data /= null then Free (Self.Data); end if; end Finalize; not overriding function Get_Generated_Code_Info_Variable_Reference (Self : aliased in out Generated_Code_Info_Vector; Index : Positive) return Generated_Code_Info_Variable_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Generated_Code_Info_Variable_Reference; not overriding function Get_Generated_Code_Info_Constant_Reference (Self : aliased Generated_Code_Info_Vector; Index : Positive) return Generated_Code_Info_Constant_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Generated_Code_Info_Constant_Reference; procedure Read_Generated_Code_Info (Stream : access Ada.Streams.Root_Stream_Type'Class; V : out Generated_Code_Info) is Key : aliased PB_Support.IO.Key; begin while PB_Support.IO.Read_Key (Stream, Key'Access) loop case Key.Field is when 1 => Annotation_IO.Read_Vector (Stream, Key.Encoding, V.Annotation); when others => PB_Support.IO.Unknown_Field (Stream, Key.Encoding); end case; end loop; end Read_Generated_Code_Info; procedure Write_Generated_Code_Info (Stream : access Ada.Streams.Root_Stream_Type'Class; V : Generated_Code_Info) is begin if Stream.all not in PB_Support.Internal.Stream then declare WS : aliased PB_Support.Internal.Stream (Stream); begin Write_Generated_Code_Info (WS'Access, V); return; end; end if; declare WS : PB_Support.Internal.Stream renames PB_Support.Internal.Stream (Stream.all); begin WS.Start_Message; for J in 1 .. V.Annotation.Length loop WS.Write_Key ((1, PB_Support.Length_Delimited)); Google.Protobuf.Descriptor.Annotation'Write (Stream, V.Annotation (J)); end loop; if WS.End_Message then Write_Generated_Code_Info (WS'Access, V); end if; end; end Write_Generated_Code_Info; function Length (Self : Annotation_Vector) return Natural is begin return Self.Length; end Length; procedure Clear (Self : in out Annotation_Vector) is begin Self.Length := 0; end Clear; procedure Free is new Ada.Unchecked_Deallocation (Annotation_Array, Annotation_Array_Access); procedure Append (Self : in out Annotation_Vector; V : Annotation) is Init_Length : constant Positive := Positive'Max (1, 256 / Annotation'Size); begin if Self.Length = 0 then Self.Data := new Annotation_Array (1 .. Init_Length); elsif Self.Length = Self.Data'Last then Self.Data := new Annotation_Array' (Self.Data.all & Annotation_Array'(1 .. Self.Length => <>)); end if; Self.Length := Self.Length + 1; Self.Data (Self.Length) := V; end Append; overriding procedure Adjust (Self : in out Annotation_Vector) is begin if Self.Length > 0 then Self.Data := new Annotation_Array'(Self.Data (1 .. Self.Length)); end if; end Adjust; overriding procedure Finalize (Self : in out Annotation_Vector) is begin if Self.Data /= null then Free (Self.Data); end if; end Finalize; not overriding function Get_Annotation_Variable_Reference (Self : aliased in out Annotation_Vector; Index : Positive) return Annotation_Variable_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Annotation_Variable_Reference; not overriding function Get_Annotation_Constant_Reference (Self : aliased Annotation_Vector; Index : Positive) return Annotation_Constant_Reference is begin return (Element => Self.Data (Index)'Access); end Get_Annotation_Constant_Reference; procedure Read_Annotation (Stream : access Ada.Streams.Root_Stream_Type'Class; V : out Annotation) is Key : aliased PB_Support.IO.Key; begin while PB_Support.IO.Read_Key (Stream, Key'Access) loop case Key.Field is when 1 => PB_Support.IO.Read_Varint_Vector (Stream, Key.Encoding, V.Path); when 2 => if not V.Source_File.Is_Set then V.Source_File := (True, others => <>); end if; PB_Support.IO.Read (Stream, Key.Encoding, V.Source_File.Value); when 3 => if not V.PB_Begin.Is_Set then V.PB_Begin := (True, others => <>); end if; PB_Support.IO.Read_Varint (Stream, Key.Encoding, V.PB_Begin.Value); when 4 => if not V.PB_End.Is_Set then V.PB_End := (True, others => <>); end if; PB_Support.IO.Read_Varint (Stream, Key.Encoding, V.PB_End.Value); when others => PB_Support.IO.Unknown_Field (Stream, Key.Encoding); end case; end loop; end Read_Annotation; procedure Write_Annotation (Stream : access Ada.Streams.Root_Stream_Type'Class; V : Annotation) is begin if Stream.all not in PB_Support.Internal.Stream then declare WS : aliased PB_Support.Internal.Stream (Stream); begin Write_Annotation (WS'Access, V); return; end; end if; declare WS : PB_Support.Internal.Stream renames PB_Support.Internal.Stream (Stream.all); begin WS.Start_Message; WS.Write_Varint_Packed (1, V.Path); if V.Source_File.Is_Set then WS.Write (2, V.Source_File.Value); end if; if V.PB_Begin.Is_Set then WS.Write_Varint (3, V.PB_Begin.Value); end if; if V.PB_End.Is_Set then WS.Write_Varint (4, V.PB_End.Value); end if; if WS.End_Message then Write_Annotation (WS'Access, V); end if; end; end Write_Annotation; end Google.Protobuf.Descriptor;
package Loop_Optimization5_Pkg is type String_Access is access all String; function Init return String; function Locate (S : String) return String_Access; end Loop_Optimization5_Pkg;
----------------------------------------------------------------------- -- util-encoders-sha1 -- Compute SHA-1 hash -- Copyright (C) 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.Encoders.Base16; with Util.Encoders.Base64; -- The <b>Util.Encodes.SHA1</b> package generates SHA-1 hash according to -- RFC3174 or [FIPS-180-1]. package body Util.Encoders.SHA1 is use Ada.Streams; -- ------------------------------ -- Encodes the binary input stream represented by <b>Data</b> into -- an SHA-1 hash 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) is pragma Unreferenced (E); Hex_Encoder : Util.Encoders.Base16.Encoder; Sha_Encoder : Context; Hash : Ada.Streams.Stream_Element_Array (0 .. 19); begin Update (Sha_Encoder, Data); Finish (Sha_Encoder, Hash); Hex_Encoder.Transform (Data => Hash, Into => Into, Last => Last, Encoded => Encoded); Encoded := Data'Last; end Transform; Padding : constant String (1 .. 64) := (1 => Character'Val (16#80#), 2 .. 64 => ASCII.NUL); -- ------------------------------ -- Computes the SHA1 hash and returns the raw binary hash in <b>Hash</b>. -- ------------------------------ procedure Finish (E : in out Context; Hash : out Hash_Array) is N : constant Natural := E.Pos * 4 + E.Pending_Pos + 1 + 8; C : constant Unsigned_64 := E.Count * 8; begin -- Pad to 512-bit block with 0x80 and 64-bit bit count at the end. if N <= 64 then Update (E, Padding (1 .. 64 - N + 1)); else Update (E, Padding (1 .. 128 - N + 1)); end if; pragma Assert (E.Pending_Pos = 0); pragma Assert (E.Pos = 14); E.W (14) := Unsigned_32 (Shift_Right (C, 32)); E.W (15) := Unsigned_32 (C and 16#0ffffffff#); Compute (E); Hash (Hash'First) := Stream_Element (Shift_Right (E.H (0), 24) and 16#0FF#); Hash (Hash'First + 1) := Stream_Element (Shift_Right (E.H (0), 16) and 16#0FF#); Hash (Hash'First + 2) := Stream_Element (Shift_Right (E.H (0), 8) and 16#0FF#); Hash (Hash'First + 3) := Stream_Element (E.H (0) and 16#0FF#); Hash (Hash'First + 4) := Stream_Element (Shift_Right (E.H (1), 24) and 16#0FF#); Hash (Hash'First + 5) := Stream_Element (Shift_Right (E.H (1), 16) and 16#0FF#); Hash (Hash'First + 6) := Stream_Element (Shift_Right (E.H (1), 8) and 16#0FF#); Hash (Hash'First + 7) := Stream_Element (E.H (1) and 16#0FF#); Hash (Hash'First + 8) := Stream_Element (Shift_Right (E.H (2), 24) and 16#0FF#); Hash (Hash'First + 9) := Stream_Element (Shift_Right (E.H (2), 16) and 16#0FF#); Hash (Hash'First + 10) := Stream_Element (Shift_Right (E.H (2), 8) and 16#0FF#); Hash (Hash'First + 11) := Stream_Element (E.H (2) and 16#0FF#); Hash (Hash'First + 12) := Stream_Element (Shift_Right (E.H (3), 24) and 16#0FF#); Hash (Hash'First + 13) := Stream_Element (Shift_Right (E.H (3), 16) and 16#0FF#); Hash (Hash'First + 14) := Stream_Element (Shift_Right (E.H (3), 8) and 16#0FF#); Hash (Hash'First + 15) := Stream_Element (E.H (3) and 16#0FF#); Hash (Hash'First + 16) := Stream_Element (Shift_Right (E.H (4), 24) and 16#0FF#); Hash (Hash'First + 17) := Stream_Element (Shift_Right (E.H (4), 16) and 16#0FF#); Hash (Hash'First + 18) := Stream_Element (Shift_Right (E.H (4), 8) and 16#0FF#); Hash (Hash'First + 19) := Stream_Element (E.H (4) and 16#0FF#); -- Re-initialize for the next hash. E.Initialize; end Finish; -- ------------------------------ -- Computes the SHA1 hash and returns the hexadecimal hash in <b>Hash</b>. -- ------------------------------ procedure Finish (E : in out Context; Hash : out Digest) is Buf : Ada.Streams.Stream_Element_Array (1 .. Hash'Length); for Buf'Address use Hash'Address; pragma Import (Ada, Buf); H : Hash_Array; B : Util.Encoders.Base16.Encoder; Last : Ada.Streams.Stream_Element_Offset; Encoded : Ada.Streams.Stream_Element_Offset; begin Finish (E, H); B.Transform (Data => H, Into => Buf, Last => Last, Encoded => Encoded); end Finish; -- ------------------------------ -- Computes the SHA1 hash and returns the base64 hash in <b>Hash</b>. -- ------------------------------ procedure Finish_Base64 (E : in out Context; Hash : out Base64_Digest) is Buf : Ada.Streams.Stream_Element_Array (1 .. Hash'Length); for Buf'Address use Hash'Address; pragma Import (Ada, Buf); H : Hash_Array; B : Util.Encoders.Base64.Encoder; Last : Ada.Streams.Stream_Element_Offset; Encoded : Ada.Streams.Stream_Element_Offset; begin Finish (E, H); B.Transform (Data => H, Into => Buf, Last => Last, Encoded => Encoded); end Finish_Base64; function To_Unsigned_32 (C3, C2, C1, C0 : in Character) return Unsigned_32; pragma Inline_Always (To_Unsigned_32); function To_Unsigned_32 (C3, C2, C1, C0 : in Character) return Unsigned_32 is begin return Character'Pos (C3) or Shift_Left (Unsigned_32 (Character'Pos (C2)), 8) or Shift_Left (Unsigned_32 (Character'Pos (C1)), 16) or Shift_Left (Unsigned_32 (Character'Pos (C0)), 24); end To_Unsigned_32; -- ------------------------------ -- Update the hash with the string. -- ------------------------------ procedure Update (E : in out Context; S : in Ada.Streams.Stream_Element_Array) is Buf : String (1 .. S'Length); for Buf'Address use S'Address; pragma Import (Ada, Buf); begin E.Update (Buf); end Update; -- ------------------------------ -- Update the hash with the string. -- ------------------------------ procedure Update (E : in out Context; S : in String) is I : Natural := S'First; N : Natural := E.Pos; begin if S'Length = 0 then return; end if; E.Count := E.Count + S'Length; -- If we have pending characters, try to make a current word with the string. -- If the string is not wide enough, save it in the pending context array. -- We can save at most 3 bytes. case E.Pending_Pos is when 1 => if S'Length >= 3 then E.W (N) := To_Unsigned_32 (S (I + 2), S (I + 1), S (I + 0), E.Pending (1)); E.Pending_Pos := 0; N := N + 1; if N = 16 then Compute (E); N := 0; end if; I := S'First + 3; else E.Pending (2) := S (I + 0); if I + 1 >= S'Last then E.Pending (3) := S (I + 1); E.Pending_Pos := 3; else E.Pending_Pos := 2; end if; return; end if; when 2 => if S'Length >= 2 then E.W (N) := To_Unsigned_32 (S (I + 1), S (I + 0), E.Pending (2), E.Pending (1)); E.Pending_Pos := 0; N := N + 1; if N = 16 then Compute (E); N := 0; end if; I := S'First + 2; else E.Pending (3) := S (I + 0); E.Pending_Pos := 3; return; end if; when 3 => E.W (N) := To_Unsigned_32 (S (I + 0), E.Pending (3), E.Pending (2), E.Pending (1)); E.Pending_Pos := 0; N := N + 1; if N = 16 then Compute (E); N := 0; end if; I := S'First + 1; when others => I := S'First; end case; -- Fill the 32-bit word block array. When we have a full 512-bit block, -- compute the hash pass. while I + 3 <= S'Last loop E.W (N) := To_Unsigned_32 (S (I + 3), S (I + 2), S (I + 1), S (I + 0)); I := I + 4; N := N + 1; if N = 16 then Compute (E); N := 0; end if; end loop; E.Pos := N; -- Save what remains in the pending buffer. N := S'Last + 1 - I; if N > 0 then E.Pending (1 .. N) := S (I .. S'Last); E.Pending_Pos := N; end if; end Update; function F1 (B, C, D : in Unsigned_32) return Unsigned_32; pragma Inline_Always (F1); function F2 (B, C, D : in Unsigned_32) return Unsigned_32; pragma Inline_Always (F2); function F3 (B, C, D : in Unsigned_32) return Unsigned_32; pragma Inline_Always (F3); function F4 (B, C, D : in Unsigned_32) return Unsigned_32; pragma Inline_Always (F4); function F1 (B, C, D : in Unsigned_32) return Unsigned_32 is begin return (B and C) or ((not B) and D); end F1; function F2 (B, C, D : in Unsigned_32) return Unsigned_32 is begin return B xor C xor D; end F2; function F3 (B, C, D : in Unsigned_32) return Unsigned_32 is begin return (B and C) or (B and D) or (C and D); end F3; function F4 (B, C, D : in Unsigned_32) return Unsigned_32 is begin return B xor C xor D; end F4; -- ------------------------------ -- Process the message block collected in the context. -- ------------------------------ procedure Compute (Ctx : in out Context) is W : W_Array renames Ctx.W; H : H_Array renames Ctx.H; V, A, B, C, D, E : Unsigned_32; begin -- Step b: For t = 16 to 79 let -- W(t) = S^1(W(t-3) XOR W(t-8) XOR W(t-14) XOR W(t-16)). for I in 16 .. 79 loop W (I) := Rotate_Left (W (I - 3) xor W (I - 8) xor W (I - 14) xor W (I - 16), 1); end loop; -- Step c: Let A = H0, B = H1, C = H2, D = H3, E = H4. A := H (0); B := H (1); C := H (2); D := H (3); E := H (4); -- Step d: For t = 0 to 79 do -- TEMP = S^5(A) + f(t;B,C,D) + E + W(t) + K(t); -- E = D; D = C; C = S^30(B); B = A; A = TEMP; for I in 0 .. 19 loop V := Rotate_Left (A, 5) + F1 (B, C, D) + E + W (I) + 16#5A82_7999#; E := D; D := C; C := Rotate_Left (B, 30); B := A; A := V; end loop; for I in 20 .. 39 loop V := Rotate_Left (A, 5) + F2 (B, C, D) + E + W (I) + 16#6ED9_EBA1#; E := D; D := C; C := Rotate_Left (B, 30); B := A; A := V; end loop; for I in 40 .. 59 loop V := Rotate_Left (A, 5) + F3 (B, C, D) + E + W (I) + 16#8F1B_BCDC#; E := D; D := C; C := Rotate_Left (B, 30); B := A; A := V; end loop; for I in 60 .. 79 loop V := Rotate_Left (A, 5) + F4 (B, C, D) + E + W (I) + 16#CA62_C1D6#; E := D; D := C; C := Rotate_Left (B, 30); B := A; A := V; end loop; -- Step e: Let H0 = H0 + A, H1 = H1 + B, H2 = H2 + C, H3 = H3 + D, H4 = H4 + E. H (0) := H (0) + A; H (1) := H (1) + B; H (2) := H (2) + C; H (3) := H (3) + D; H (4) := H (4) + E; end Compute; -- ------------------------------ -- Initialize the SHA-1 context. -- ------------------------------ overriding procedure Initialize (E : in out Context) is begin E.Count := 0; E.Pending_Pos := 0; E.Pos := 0; E.H (0) := 16#67452301#; E.H (1) := 16#EFCDAB89#; E.H (2) := 16#98BADCFE#; E.H (3) := 16#10325476#; E.H (4) := 16#C3D2E1F0#; end Initialize; end Util.Encoders.SHA1;
with openGL.Light, openGL.Visual, openGL.Model.Box.lit_textured, openGL.Palette, openGL.Demo; procedure launch_diffuse_Light -- -- Exercise the rendering of models with a diffuse light. -- is use openGL, openGL.Model, openGL.Math, openGL.linear_Algebra_3d; the_Texture : constant asset_Name := to_Asset ("assets/opengl/texture/Face1.bmp"); begin Demo.print_Usage; Demo.define ("openGL 'diffuse Light' Demo"); Demo.Camera.Position_is ((0.0, 0.0, 10.0), y_Rotation_from (to_Radians (0.0))); declare use openGL.Model.box, openGL.Visual.Forge, openGL.Light, openGL.Palette; -- The Model. -- the_Box : constant Model.Box.lit_textured.view := openGL.Model.Box.lit_textured.new_Box (Size => (4.0, 4.0, 4.0), Faces => (Front => (texture_Name => the_Texture), Rear => (texture_Name => the_Texture), Upper => (texture_Name => the_Texture), Lower => (texture_Name => the_Texture), Left => (texture_Name => the_Texture), Right => (texture_Name => the_Texture))); -- The Visual. -- the_Visuals : constant openGL.Visual.views := (1 => new_Visual (the_Box.all'Access)); -- The Light. -- the_Light : openGL.Light.item := Demo.Renderer.new_Light; initial_Site : constant openGL.Vector_3 := (0.0, 0.0, 15.0); site_Delta : openGL.Vector_3 := (1.0, 0.0, 0.0); cone_Direction : constant openGL.Vector_3 := (0.0, 0.0, -1.0); begin -- Setup the visual. -- the_Visuals (1).Site_is (Origin_3D); the_Visuals (1).Spin_is (y_Rotation_from (to_Radians (20.0))); -- Setup the light. -- the_Light. Kind_is (Diffuse); the_Light. Site_is (initial_Site); the_Light.Color_is (White); the_Light. cone_Angle_is (5.0); the_Light. cone_Direction_is (cone_Direction); the_Light.ambient_Coefficient_is (0.015); Demo.Renderer.set (the_Light); -- Main loop. -- while not Demo.Done loop -- Handle user commands. -- Demo.Dolly.evolve; Demo.Done := Demo.Dolly.quit_Requested; -- Move the light. -- if the_Light.Site (1) > 2.0 then site_Delta (1) := -0.01; elsif the_Light.Site (1) < -2.0 then site_Delta (1) := 0.01; end if; the_Light.Site_is (the_Light.Site + site_Delta); Demo.Renderer.set (the_Light); -- Render the sprites. -- Demo.Camera.render (the_Visuals); while not Demo.Camera.cull_Completed loop delay Duration'Small; end loop; Demo.Renderer.render; Demo.FPS_Counter.increment; -- Frames per second display. delay 1.0 / 60.0; end loop; end; Demo.destroy; end launch_diffuse_Light;
with interfaces; use interfaces; with types; use types; with config.memlayout; with ewok.debug; package body config.tasks with spark_mode => off is package CFGAPP renames config.applications; package CFGMEM renames config.memlayout; procedure zeroify_bss (id : in config.applications.t_real_task_id) is begin if CFGAPP.list(id).bss_size > 0 then declare bss_address : constant system_address := CFGMEM.apps_region.ram_memory_addr + CFGAPP.list(id).data_offset + to_unsigned_32 (CFGAPP.list(id).data_size) + to_unsigned_32 (CFGAPP.list(id).stack_size); bss_region : byte_array (1 .. to_unsigned_32 (CFGAPP.list(id).bss_size)) with address => to_address (bss_address); begin ewok.debug.log (ewok.debug.INFO, "zeroify bss: task " & id'image & ", at " & system_address'image (bss_address) & ", " & unsigned_16'image (CFGAPP.list(id).bss_size) & " bytes"); bss_region := (others => 0); end; end if; end zeroify_bss; procedure copy_data_to_ram (id : in config.applications.t_real_task_id) is begin if CFGAPP.list(id).data_size > 0 then declare data_in_flash_address : constant system_address := CFGMEM.apps_region.flash_memory_addr + CFGAPP.list(id).data_flash_offset; data_in_flash : byte_array (1 .. to_unsigned_32 (CFGAPP.list(id).data_size)) with address => to_address (data_in_flash_address); data_in_ram_address : constant system_address := CFGMEM.apps_region.ram_memory_addr + CFGAPP.list(id).data_offset + to_unsigned_32 (CFGAPP.list(id).stack_size); data_in_ram : byte_array (1 .. to_unsigned_32 (CFGAPP.list(id).data_size)) with address => to_address (data_in_ram_address); begin ewok.debug.log (ewok.debug.INFO, "task " & id'image & ": copy data from " & system_address'image (data_in_flash_address) & " to " & system_address'image (data_in_ram_address) & ", size " & CFGAPP.list(id).data_size'image); data_in_ram := data_in_flash; end; end if; end copy_data_to_ram; end config.tasks;
package GLOBE_3D.Textures is -- The textures are stored by GL in that way: -- -- an image < - > a number (Image_ID) -- -- To complete this, and facilitate things, GLOBE_3D adds the -- following associations: -- -- a number (Image_ID) - > -- a record (Texture_info) with an image name -- and whether the image was already stored into GL -- (images can be loaded on first use, or preloaded) -- and other infos -- -- an image name - > a number (Image_ID) -- -- Names are case insensitive! ------------------------------------------------------------------------ -- Here are three ways of registering the texture names that GLOBE_3D -- -- will find in the resource files. You can use any mix of these -- -- methods at your convenience. -- ------------------------------------------------------------------------ -------------------------------------------- -- a) Texture - by - texture name association -- -------------------------------------------- -- -- Free way of associating names. E.g., the texture name list could be -- simply stored on a text file, or obtained by a "dir"- like operation. -- The system associates a name to a texture id that it finds itself. procedure Add_texture_name (name : String; id : out Image_ID); ------------------------------------------------------------ -- b) Texture name association by searching the .zip data -- -- resource files for images -- ------------------------------------------------------------ -- -- For "real life" programs which don't know of the data. -- Allows subdirectories in resource ('/' or '\' in names) -- and a flexible management. -- -- The texture name list is obtained by traversing the directory of -- both .zip data resource files, searching for images (anyway, the -- textures are read from there!). -- -- The zip name (s) must be set first with -- GLOBE_3D.Set_level_data_name, GLOBE_3D.Set_global_data_name procedure Register_textures_from_resources; ------------------------------------------------------------ -- c) Texture name association through an enumarated type -- ------------------------------------------------------------ -- -- For test or demo programs. -- Easy, reliable, but : static, hard - coded and disallowing a -- directory structure. generic type Texture_enum is (<>); procedure Associate_textures; --------------------------------------------------------------------- -- When texture names are registered, you have the following tools -- --------------------------------------------------------------------- -- - Recall a texture's ID - you need it to define objects' faces. function Texture_ID (name : String) return Image_ID; Texture_name_not_found : exception; -- - Recall a texture's name function Texture_name (id : Image_ID; Trim_Flag : Boolean) return Ident; -- Check if the texture image has been loaded and load it if needed. -- This is done automatically, but you may want to force the loading -- of the images before beginning to display. procedure Check_2D_texture (id : Image_ID; blending_hint : out Boolean); -- variant for situations where the blending information doesn't matter: procedure Check_2D_texture (id : Image_ID); -- same, but for all textures. procedure Check_all_textures; function Valid_texture_ID (id : Image_ID) return Boolean; -- >= 16 - apr - 2008 : no more need to reserve anything; unbounded collection -- -- Textures_not_reserved : exception; -- Texture_out_of_range : exception; Undefined_texture_ID : exception; Undefined_texture_name : exception; -- - Erase the present texture collection -- (names, GL ID's, evenutally loaded images) procedure Reset_textures; end GLOBE_3D.Textures;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- G N A T . C G I -- -- -- -- B o d y -- -- -- -- Copyright (C) 2001-2005, AdaCore -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, -- -- Boston, MA 02110-1301, USA. -- -- -- -- As a special exception, if other files instantiate generics from this -- -- unit, or you link this unit with other files to produce an executable, -- -- this unit does not by itself cause the resulting executable to be -- -- covered by the GNU General Public License. This exception does not -- -- however invalidate any other reasons why the executable file might be -- -- covered by the GNU Public License. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Ada.Text_IO; with Ada.Strings.Fixed; with Ada.Characters.Handling; with Ada.Strings.Maps; with GNAT.OS_Lib; with GNAT.Table; package body GNAT.CGI is use Ada; Valid_Environment : Boolean := True; -- This boolean will be set to False if the initialization was not -- completed correctly. It must be set to true there because the -- Initialize routine (called during elaboration) will use some of the -- services exported by this unit. Current_Method : Method_Type; -- This is the current method used to pass CGI parameters Header_Sent : Boolean := False; -- Will be set to True when the header will be sent -- Key/Value table declaration type String_Access is access String; type Key_Value is record Key : String_Access; Value : String_Access; end record; package Key_Value_Table is new Table (Key_Value, Positive, 1, 1, 50); ----------------------- -- Local subprograms -- ----------------------- procedure Check_Environment; pragma Inline (Check_Environment); -- This procedure will raise Data_Error if Valid_Environment is False procedure Initialize; -- Initialize CGI package by reading the runtime environment. This -- procedure is called during elaboration. All exceptions raised during -- this procedure are deferred. -------------------- -- Argument_Count -- -------------------- function Argument_Count return Natural is begin Check_Environment; return Key_Value_Table.Last; end Argument_Count; ----------------------- -- Check_Environment -- ----------------------- procedure Check_Environment is begin if not Valid_Environment then raise Data_Error; end if; end Check_Environment; ------------ -- Decode -- ------------ function Decode (S : String) return String is Result : String (S'Range); K : Positive := S'First; J : Positive := Result'First; begin while K <= S'Last loop if K + 2 <= S'Last and then S (K) = '%' and then Characters.Handling.Is_Hexadecimal_Digit (S (K + 1)) and then Characters.Handling.Is_Hexadecimal_Digit (S (K + 2)) then -- Here we have '%HH' which is an encoded character where 'HH' is -- the character number in hexadecimal. Result (J) := Character'Val (Natural'Value ("16#" & S (K + 1 .. K + 2) & '#')); K := K + 3; else Result (J) := S (K); K := K + 1; end if; J := J + 1; end loop; return Result (Result'First .. J - 1); end Decode; ------------------------- -- For_Every_Parameter -- ------------------------- procedure For_Every_Parameter is Quit : Boolean; begin Check_Environment; for K in 1 .. Key_Value_Table.Last loop Quit := False; Action (Key_Value_Table.Table (K).Key.all, Key_Value_Table.Table (K).Value.all, K, Quit); exit when Quit; end loop; end For_Every_Parameter; ---------------- -- Initialize -- ---------------- procedure Initialize is Request_Method : constant String := Characters.Handling.To_Upper (Metavariable (CGI.Request_Method)); procedure Initialize_GET; -- Read CGI parameters for a GET method. In this case the parameters -- are passed into QUERY_STRING environment variable. procedure Initialize_POST; -- Read CGI parameters for a POST method. In this case the parameters -- are passed with the standard input. The total number of characters -- for the data is passed in CONTENT_LENGTH environment variable. procedure Set_Parameter_Table (Data : String); -- Parse the parameter data and set the parameter table -------------------- -- Initialize_GET -- -------------------- procedure Initialize_GET is Data : constant String := Metavariable (Query_String); begin Current_Method := Get; if Data /= "" then Set_Parameter_Table (Data); end if; end Initialize_GET; --------------------- -- Initialize_POST -- --------------------- procedure Initialize_POST is Content_Length : constant Natural := Natural'Value (Metavariable (CGI.Content_Length)); Data : String (1 .. Content_Length); begin Current_Method := Post; if Content_Length /= 0 then Text_IO.Get (Data); Set_Parameter_Table (Data); end if; end Initialize_POST; ------------------------- -- Set_Parameter_Table -- ------------------------- procedure Set_Parameter_Table (Data : String) is procedure Add_Parameter (K : Positive; P : String); -- Add a single parameter into the table at index K. The parameter -- format is "key=value". Count : constant Positive := 1 + Strings.Fixed.Count (Data, Strings.Maps.To_Set ("&")); -- Count is the number of parameters in the string. Parameters are -- separated by ampersand character. Index : Positive := Data'First; Amp : Natural; ------------------- -- Add_Parameter -- ------------------- procedure Add_Parameter (K : Positive; P : String) is Equal : constant Natural := Strings.Fixed.Index (P, "="); begin if Equal = 0 then raise Data_Error; else Key_Value_Table.Table (K) := Key_Value'(new String'(Decode (P (P'First .. Equal - 1))), new String'(Decode (P (Equal + 1 .. P'Last)))); end if; end Add_Parameter; -- Start of processing for Set_Parameter_Table begin Key_Value_Table.Set_Last (Count); for K in 1 .. Count - 1 loop Amp := Strings.Fixed.Index (Data (Index .. Data'Last), "&"); Add_Parameter (K, Data (Index .. Amp - 1)); Index := Amp + 1; end loop; -- add last parameter Add_Parameter (Count, Data (Index .. Data'Last)); end Set_Parameter_Table; -- Start of processing for Initialize begin if Request_Method = "GET" then Initialize_GET; elsif Request_Method = "POST" then Initialize_POST; else Valid_Environment := False; end if; exception when others => -- If we have an exception during initialization of this unit we -- just declare it invalid. Valid_Environment := False; end Initialize; --------- -- Key -- --------- function Key (Position : Positive) return String is begin Check_Environment; if Position <= Key_Value_Table.Last then return Key_Value_Table.Table (Position).Key.all; else raise Parameter_Not_Found; end if; end Key; ---------------- -- Key_Exists -- ---------------- function Key_Exists (Key : String) return Boolean is begin Check_Environment; for K in 1 .. Key_Value_Table.Last loop if Key_Value_Table.Table (K).Key.all = Key then return True; end if; end loop; return False; end Key_Exists; ------------------ -- Metavariable -- ------------------ function Metavariable (Name : Metavariable_Name; Required : Boolean := False) return String is function Get_Environment (Variable_Name : String) return String; -- Returns the environment variable content --------------------- -- Get_Environment -- --------------------- function Get_Environment (Variable_Name : String) return String is Value : OS_Lib.String_Access := OS_Lib.Getenv (Variable_Name); Result : constant String := Value.all; begin OS_Lib.Free (Value); return Result; end Get_Environment; Result : constant String := Get_Environment (Metavariable_Name'Image (Name)); -- Start of processing for Metavariable begin Check_Environment; if Result = "" and then Required then raise Parameter_Not_Found; else return Result; end if; end Metavariable; ------------------------- -- Metavariable_Exists -- ------------------------- function Metavariable_Exists (Name : Metavariable_Name) return Boolean is begin Check_Environment; if Metavariable (Name) = "" then return False; else return True; end if; end Metavariable_Exists; ------------ -- Method -- ------------ function Method return Method_Type is begin Check_Environment; return Current_Method; end Method; -------- -- Ok -- -------- function Ok return Boolean is begin return Valid_Environment; end Ok; ---------------- -- Put_Header -- ---------------- procedure Put_Header (Header : String := Default_Header; Force : Boolean := False) is begin if Header_Sent = False or else Force then Check_Environment; Text_IO.Put_Line (Header); Text_IO.New_Line; Header_Sent := True; end if; end Put_Header; --------- -- URL -- --------- function URL return String is function Exists_And_Not_80 (Server_Port : String) return String; -- Returns ':' & Server_Port if Server_Port is not "80" and the empty -- string otherwise (80 is the default sever port). ----------------------- -- Exists_And_Not_80 -- ----------------------- function Exists_And_Not_80 (Server_Port : String) return String is begin if Server_Port = "80" then return ""; else return ':' & Server_Port; end if; end Exists_And_Not_80; -- Start of processing for URL begin Check_Environment; return "http://" & Metavariable (Server_Name) & Exists_And_Not_80 (Metavariable (Server_Port)) & Metavariable (Script_Name); end URL; ----------- -- Value -- ----------- function Value (Key : String; Required : Boolean := False) return String is begin Check_Environment; for K in 1 .. Key_Value_Table.Last loop if Key_Value_Table.Table (K).Key.all = Key then return Key_Value_Table.Table (K).Value.all; end if; end loop; if Required then raise Parameter_Not_Found; else return ""; end if; end Value; ----------- -- Value -- ----------- function Value (Position : Positive) return String is begin Check_Environment; if Position <= Key_Value_Table.Last then return Key_Value_Table.Table (Position).Value.all; else raise Parameter_Not_Found; end if; end Value; begin Initialize; end GNAT.CGI;
------------------------------------------------------------------------------- -- This file is part of libsparkcrypto. -- -- @author Alexander Senier -- @date 2019-02-21 -- -- Copyright (C) 2018 Componolit GmbH -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- -- * Neither the name of the 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. ------------------------------------------------------------------------------- private with LSC.Internal.AES; package LSC.AES_Generic is pragma Pure; type Keylen_Type is (L128, L192, L256); -- Available AES modes function Key_Bytes (Keylen : Keylen_Type) return Natural; -- AES key lengths for @Keylen in bytes -- FIXME: This crashes GCC 6.3. Re-add as soon as it's not used anymore. -- with Ghost; type Dec_Key_Type is private; type Enc_Key_Type is private; generic type Index_Type is (<>); type Elem_Type is (<>); type Key_Type is array (Index_Type range <>) of Elem_Type; function Dec_Key (K : Key_Type; Keylen : Keylen_Type) return Dec_Key_Type with Pre => K'Length = Key_Bytes (Keylen); -- Return decryption key of length @Keylen from byte array generic type Index_Type is (<>); type Elem_Type is (<>); type Key_Type is array (Index_Type range <>) of Elem_Type; function Enc_Key (K : Key_Type; Keylen : Keylen_Type) return Enc_Key_Type with Pre => K'Length = Key_Bytes (Keylen); -- Return encryption key of length @Keylen from byte array generic type Plaintext_Index_Type is (<>); type Plaintext_Elem_Type is (<>); type Plaintext_Type is array (Plaintext_Index_Type range <>) of Plaintext_Elem_Type; type Ciphertext_Index_Type is (<>); type Ciphertext_Elem_Type is (<>); type Ciphertext_Type is array (Ciphertext_Index_Type range <>) of Ciphertext_Elem_Type; function Decrypt (Ciphertext : Ciphertext_Type; Key : Dec_Key_Type) return Plaintext_Type with Pre => Ciphertext'Length = 16, Post => Decrypt'Result'Length = 16; -- Decrypt @Ciphertext using @Key, @Keylen determines the AES key -- length (AES-128, AES-192, AES-256) generic type Plaintext_Index_Type is (<>); type Plaintext_Elem_Type is (<>); type Plaintext_Type is array (Plaintext_Index_Type range <>) of Plaintext_Elem_Type; type Ciphertext_Index_Type is (<>); type Ciphertext_Elem_Type is (<>); type Ciphertext_Type is array (Ciphertext_Index_Type range <>) of Ciphertext_Elem_Type; function Encrypt (Plaintext : Plaintext_Type; Key : Enc_Key_Type) return Ciphertext_Type with Pre => Plaintext'Length = 16, Post => Encrypt'Result'Length = 16; -- Decrypt @Plaintext using @Key, @Keylen determines the AES key -- length (AES-128, AES-192, AES-256) private function Key_Bytes (Keylen : Keylen_Type) return Natural is (case Keylen is when L128 => 16, when L192 => 24, when L256 => 32); type Dec_Key_Type is record Context : Internal.AES.AES_Dec_Context; end record; type Enc_Key_Type is record Context : Internal.AES.AES_Enc_Context; end record; end LSC.AES_Generic;
with Interfaces; use Interfaces; with STM32GD.Board; procedure Main is begin STM32GD.Board.Init; STM32GD.Board.Text_IO.Put_Line ("Hello, World!"); STM32GD.Board.Text_IO.Put_Integer (Integer'Last); STM32GD.Board.Text_IO.New_Line; STM32GD.Board.Text_IO.Put_Integer (Integer'First + 1); STM32GD.Board.Text_IO.New_Line; STM32GD.Board.Text_IO.Put_Hex (Unsigned_32'Last); STM32GD.Board.Text_IO.New_Line; STM32GD.Board.Text_IO.Put_Hex (16#1234_5678#, 4); STM32GD.Board.Text_IO.New_Line; STM32GD.Board.Text_IO.Put_Hex (16#1234#, 8); STM32GD.Board.Text_IO.New_Line; STM32GD.Board.Text_IO.Hex_Dump ("Short string"); STM32GD.Board.Text_IO.Hex_Dump ("Hex dump of a longer string 1234"); end Main;
-- //////////////////////////////////////////////////////////// -- // -- // SFML - Simple and Fast Multimedia Library -- // Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com) -- // -- // 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. -- // -- //////////////////////////////////////////////////////////// -- //////////////////////////////////////////////////////////// -- // Headers -- //////////////////////////////////////////////////////////// with Sf.Config; with Sf.Window.Types; with Sf.Window.Event; with Sf.Window.VideoMode; with Sf.Window.WindowHandle; package Sf.Window.Window is use Sf.Config; use Sf.Window.Types; use Sf.Window.Event; use Sf.Window.VideoMode; use Sf.Window.WindowHandle; -- //////////////////////////////////////////////////////////// -- /// Enumeration of window creation styles -- /// -- //////////////////////////////////////////////////////////// sfNone : constant sfUint32 := 0; -- ///< No border / title bar --(this --flag and all others are --mutually --exclusive) sfTitlebar : constant sfUint32 := 1; -- ///< Title bar + --fixed border sfResize : constant sfUint32 := 2; -- ///< Titlebar + --resizable --border + maximize --button sfClose : constant sfUint32 := 4; -- ///< Titlebar + close --button sfFullscreen : constant sfUint32 := 8; -- ///< Fullscreen --mode (this --flag and all others --are --mutually exclusive) -- //////////////////////////////////////////////////////////// -- /// Structure defining the window's creation settings -- //////////////////////////////////////////////////////////// type sfWindowSettings is record DepthBits : aliased sfUint32; -- ///< Bits of the --depth buffer StencilBits : aliased sfUint32; -- ///< Bits of the --stencil buffer AntialiasingLevel : aliased sfUint32; -- ///< Level of --antialiasing end record; -- //////////////////////////////////////////////////////////// -- /// Construct a new window -- /// -- /// \param Mode : Video mode to use -- /// \param Title : Title of the window -- /// \param Style : Window style -- /// \param Params : Creation settings -- /// -- //////////////////////////////////////////////////////////// function sfWindow_Create (Mode : sfVideoMode; Title : String; Style : sfUint32 := sfResize or sfClose; Params : sfWindowSettings := (24, 8, 0)) return sfWindow_Ptr; -- //////////////////////////////////////////////////////////// -- /// Construct a window from an existing control -- /// -- /// \param Handle : Platform-specific handle of the control -- /// \param Params : Creation settings -- /// -- //////////////////////////////////////////////////////////// function sfWindow_CreateFromHandle (Handle : sfWindowHandle; Params : sfWindowSettings) return sfWindow_Ptr; -- //////////////////////////////////////////////////////////// -- /// Destroy an existing window -- /// -- /// \param Window : Window to destroy -- /// -- //////////////////////////////////////////////////////////// procedure sfWindow_Destroy (Window : sfWindow_Ptr); -- //////////////////////////////////////////////////////////// -- /// Close a window (but doesn't destroy the internal data) -- /// -- /// \param Window : Window to close -- /// -- //////////////////////////////////////////////////////////// procedure sfWindow_Close (Window : sfWindow_Ptr); -- //////////////////////////////////////////////////////////// -- /// Tell whether or not a window is opened -- /// -- /// \param Window : Window object -- /// -- //////////////////////////////////////////////////////////// function sfWindow_IsOpened (Window : sfWindow_Ptr) return sfBool; -- //////////////////////////////////////////////////////////// -- /// Get the width of the rendering region of a window -- /// -- /// \param Window : Window object -- /// -- /// \return Width in pixels -- /// -- //////////////////////////////////////////////////////////// function sfWindow_GetWidth (Window : sfWindow_Ptr) return sfUint32; -- //////////////////////////////////////////////////////////// -- /// Get the height of the rendering region of a window -- /// -- /// \param Window : Window object -- /// -- /// \return Height in pixels -- /// -- //////////////////////////////////////////////////////////// function sfWindow_GetHeight (Window : sfWindow_Ptr) return sfUint32; -- //////////////////////////////////////////////////////////// -- /// Get the creation settings of a window -- /// -- /// \param Window : Window object -- /// -- /// \return Settings used to create the window -- /// -- //////////////////////////////////////////////////////////// function sfWindow_GetSettings (Window : sfWindow_Ptr) return sfWindowSettings; -- //////////////////////////////////////////////////////////// -- /// Get the event on top of events stack of a window, if --any, and pop it -- /// -- /// \param Window : Window object -- /// \param Event : Event to fill, if any -- /// -- /// \return sfTrue if an event was returned, sfFalse if --events stack was --empty -- /// -- //////////////////////////////////////////////////////////// function sfWindow_GetEvent (Window : sfWindow_Ptr; Event : access sfEvent) return sfBool; -- //////////////////////////////////////////////////////////// -- /// Enable / disable vertical synchronization on a window -- /// -- /// \param Window : Window object -- /// \param Enabled : sfTrue to enable v-sync, sfFalse to --deactivate -- /// -- //////////////////////////////////////////////////////////// procedure sfWindow_UseVerticalSync (Window : sfWindow_Ptr; Enabled : sfBool); -- //////////////////////////////////////////////////////////// -- /// Show or hide the mouse cursor on a window -- /// -- /// \param Window : Window object -- /// \param Show : sfTrue to show, sfFalse to hide -- /// -- //////////////////////////////////////////////////////////// procedure sfWindow_ShowMouseCursor (Window : sfWindow_Ptr; Show : sfBool); -- //////////////////////////////////////////////////////////// -- /// Change the position of the mouse cursor on a window -- /// -- /// \param Window : Window object -- /// \param Left : Left coordinate of the cursor, relative --to the window -- /// \param Top : Top coordinate of the cursor, relative --to the window -- /// -- //////////////////////////////////////////////////////////// procedure sfWindow_SetCursorPosition (Window : sfWindow_Ptr; Left : sfUint32; Top : sfUint32); -- //////////////////////////////////////////////////////////// -- /// Change the position of a window on screen. -- /// Only works for top-level windows -- /// -- /// \param Window : Window object -- /// \param Left : Left position -- /// \param Top : Top position -- /// -- //////////////////////////////////////////////////////////// procedure sfWindow_SetPosition (Window : sfWindow_Ptr; Left : Integer; Top : Integer); -- //////////////////////////////////////////////////////////// -- /// Change the size of the rendering region of a window -- /// -- /// \param Window : Window object -- /// \param Width : New Width -- /// \param Height : New Height -- /// -- //////////////////////////////////////////////////////////// procedure sfWindow_SetSize (Window : sfWindow_Ptr; Width : sfUint32; Height : sfUint32); -- //////////////////////////////////////////////////////////// -- /// Show or hide a window -- /// -- /// \param Window : Window object -- /// \param State : sfTrue to show, sfFalse to hide -- /// -- //////////////////////////////////////////////////////////// procedure sfWindow_Show (Window : sfWindow_Ptr; State : sfBool); -- //////////////////////////////////////////////////////////// -- /// Enable or disable automatic key-repeat for keydown --events. -- /// Automatic key-repeat is enabled by default -- /// -- /// \param Window : Window object -- /// \param Enabled : sfTrue to enable, sfFalse to disable -- /// -- //////////////////////////////////////////////////////////// procedure sfWindow_EnableKeyRepeat (Window : sfWindow_Ptr; Enabled : sfBool); -- //////////////////////////////////////////////////////////// -- /// Change the window's icon -- /// -- /// \param Window : Window object -- /// \param Width : Icon's width, in pixels -- /// \param Height : Icon's height, in pixels -- /// \param Pixels : Pointer to the pixels in memory, format --must be RGBA --32 bits -- /// -- //////////////////////////////////////////////////////////// procedure sfWindow_SetIcon (Window : sfWindow_Ptr; Width : sfUint32; Height : sfUint32; Pixels : sfUint8_Ptr); -- //////////////////////////////////////////////////////////// -- /// Activate or deactivate a window as the current target --for rendering -- /// -- /// \param Window : Window object -- /// \param Active : sfTrue to activate, sfFalse to deactivate -- /// -- /// \return True if operation was successful, false otherwise -- /// -- //////////////////////////////////////////////////////////// function sfWindow_SetActive (Window : sfWindow_Ptr; Active : sfBool) return sfBool; -- //////////////////////////////////////////////////////////// -- /// Display a window on screen -- /// -- /// \param Window : Window object -- /// -- //////////////////////////////////////////////////////////// procedure sfWindow_Display (Window : sfWindow_Ptr); -- //////////////////////////////////////////////////////////// -- /// Get the input manager of a window -- /// -- /// \param Window : Window object -- /// -- /// \return Reference to the input -- /// -- //////////////////////////////////////////////////////////// function sfWindow_GetInput (Window : sfWindow_Ptr) return sfInput_Ptr; -- //////////////////////////////////////////////////////////// -- /// Limit the framerate to a maximum fixed frequency for a --window -- /// -- /// \param Window : Window object -- /// -- /// \param Limit : Framerate limit, in frames per seconds --(use 0 to --disable limit) -- /// -- //////////////////////////////////////////////////////////// procedure sfWindow_SetFramerateLimit (Window : sfWindow_Ptr; Limit : sfUint32); -- //////////////////////////////////////////////////////////// -- /// Get time elapsed since last frame of a window -- /// -- /// \param Window : Window object -- /// -- /// \return Time elapsed, in seconds -- /// -- //////////////////////////////////////////////////////////// function sfWindow_GetFrameTime (Window : sfWindow_Ptr) return Float; -- //////////////////////////////////////////////////////////// -- /// Change the joystick threshold, ie. the value below which -- /// no move event will be generated -- /// -- /// \param Window : Window object -- /// \param Threshold : New threshold, in range [0, 100] -- /// -- //////////////////////////////////////////////////////////// procedure sfWindow_SetJoystickThreshold (Window : sfWindow_Ptr; Threshold : Float); private pragma Convention (C_Pass_By_Copy, sfWindowSettings); pragma Import (C, sfWindow_CreateFromHandle, "sfWindow_CreateFromHandle"); pragma Import (C, sfWindow_Destroy, "sfWindow_Destroy"); pragma Import (C, sfWindow_Close, "sfWindow_Close"); pragma Import (C, sfWindow_IsOpened, "sfWindow_IsOpened"); pragma Import (C, sfWindow_GetWidth, "sfWindow_GetWidth"); pragma Import (C, sfWindow_GetHeight, "sfWindow_GetHeight"); pragma Import (C, sfWindow_GetSettings, "sfWindow_GetSettings"); pragma Import (C, sfWindow_GetEvent, "sfWindow_GetEvent"); pragma Import (C, sfWindow_UseVerticalSync, "sfWindow_UseVerticalSync"); pragma Import (C, sfWindow_ShowMouseCursor, "sfWindow_ShowMouseCursor"); pragma Import (C, sfWindow_SetCursorPosition, "sfWindow_SetCursorPosition"); pragma Import (C, sfWindow_SetPosition, "sfWindow_SetPosition"); pragma Import (C, sfWindow_SetSize, "sfWindow_SetSize"); pragma Import (C, sfWindow_Show, "sfWindow_Show"); pragma Import (C, sfWindow_EnableKeyRepeat, "sfWindow_EnableKeyRepeat"); pragma Import (C, sfWindow_SetIcon, "sfWindow_SetIcon"); pragma Import (C, sfWindow_SetActive, "sfWindow_SetActive"); pragma Import (C, sfWindow_Display, "sfWindow_Display"); pragma Import (C, sfWindow_GetInput, "sfWindow_GetInput"); pragma Import (C, sfWindow_SetFramerateLimit, "sfWindow_SetFramerateLimit"); pragma Import (C, sfWindow_GetFrameTime, "sfWindow_GetFrameTime"); pragma Import (C, sfWindow_SetJoystickThreshold, "sfWindow_SetJoystickThreshold"); end Sf.Window.Window;
-- Generated at 2014-07-02 17:53:59 +0000 by Natools.Static_Hash_Maps -- from src/simple_webapps-upload_servers-commands.sx package Simple_Webapps.Commands.Upload_Servers is pragma Pure; type Config_Command is (Config_Error, Set_Storage_File, Set_Directory, Set_Error_Template, Set_HMAC_Key, Set_Index_Template, Set_Input_Dir, Set_Max_Expiration, Set_Report_Template, Set_Static_Dir); type File_Command is (File_Error, Set_Name, Set_Comment, Set_Download, Set_Expiration, Set_MIME_Type, Set_Upload); function To_Config_Command (Key : String) return Config_Command; function To_File_Command (Key : String) return File_Command; private Map_1_Key_0 : aliased constant String := "backend"; Map_1_Key_1 : aliased constant String := "directory"; Map_1_Key_2 : aliased constant String := "error-template"; Map_1_Key_3 : aliased constant String := "hmac-key"; Map_1_Key_4 : aliased constant String := "index-template"; Map_1_Key_5 : aliased constant String := "input-directory"; Map_1_Key_6 : aliased constant String := "max-expiration"; Map_1_Key_7 : aliased constant String := "report-template"; Map_1_Key_8 : aliased constant String := "static"; Map_1_Key_9 : aliased constant String := "static-dir"; Map_1_Key_10 : aliased constant String := "static-resources"; Map_1_Keys : constant array (0 .. 10) of access constant String := (Map_1_Key_0'Access, Map_1_Key_1'Access, Map_1_Key_2'Access, Map_1_Key_3'Access, Map_1_Key_4'Access, Map_1_Key_5'Access, Map_1_Key_6'Access, Map_1_Key_7'Access, Map_1_Key_8'Access, Map_1_Key_9'Access, Map_1_Key_10'Access); Map_1_Elements : constant array (0 .. 10) of Config_Command := (Set_Storage_File, Set_Directory, Set_Error_Template, Set_HMAC_Key, Set_Index_Template, Set_Input_Dir, Set_Max_Expiration, Set_Report_Template, Set_Static_Dir, Set_Static_Dir, Set_Static_Dir); Map_2_Key_0 : aliased constant String := "name"; Map_2_Key_1 : aliased constant String := "comment"; Map_2_Key_2 : aliased constant String := "download-key"; Map_2_Key_3 : aliased constant String := "expire"; Map_2_Key_4 : aliased constant String := "mime-type"; Map_2_Key_5 : aliased constant String := "upload"; Map_2_Keys : constant array (0 .. 5) of access constant String := (Map_2_Key_0'Access, Map_2_Key_1'Access, Map_2_Key_2'Access, Map_2_Key_3'Access, Map_2_Key_4'Access, Map_2_Key_5'Access); Map_2_Elements : constant array (0 .. 5) of File_Command := (Set_Name, Set_Comment, Set_Download, Set_Expiration, Set_MIME_Type, Set_Upload); end Simple_Webapps.Commands.Upload_Servers;
with ada.text_io, ada.Integer_text_IO, Ada.Text_IO.Text_Streams, Ada.Strings.Fixed, Interfaces.C; use ada.text_io, ada.Integer_text_IO, Ada.Strings, Ada.Strings.Fixed, Interfaces.C; procedure aaa_08tuple is type stringptr is access all char_array; procedure PString(s : stringptr) is begin String'Write (Text_Streams.Stream (Current_Output), To_Ada(s.all)); end; procedure PInt(i : in Integer) is begin String'Write (Text_Streams.Stream (Current_Output), Trim(Integer'Image(i), Left)); end; procedure SkipSpaces is C : Character; Eol : Boolean; begin loop Look_Ahead(C, Eol); exit when Eol or C /= ' '; Get(C); end loop; end; type tuple_int_int; type tuple_int_int_PTR is access tuple_int_int; type tuple_int_int is record tuple_int_int_field_0 : Integer; tuple_int_int_field_1 : Integer; end record; type toto; type toto_PTR is access toto; type toto is record foo : tuple_int_int_PTR; bar : Integer; end record; t : toto_PTR; f : tuple_int_int_PTR; e : tuple_int_int_PTR; d : Integer; c : Integer; bar_0 : Integer; b : Integer; a : Integer; begin Get(bar_0); SkipSpaces; Get(c); SkipSpaces; Get(d); SkipSpaces; e := new tuple_int_int; e.tuple_int_int_field_0 := c; e.tuple_int_int_field_1 := d; t := new toto; t.foo := e; t.bar := bar_0; f := t.foo; a := f.tuple_int_int_field_0; b := f.tuple_int_int_field_1; PInt(a); PString(new char_array'( To_C(" "))); PInt(b); PString(new char_array'( To_C(" "))); PInt(t.bar); PString(new char_array'( To_C("" & Character'Val(10)))); end;
with C.signal; package body System.Native_Interrupts is use type C.signed_int; procedure Mask (How : C.signed_int; Interrupt : Interrupt_Id); procedure Mask (How : C.signed_int; Interrupt : Interrupt_Id) is Mask : aliased C.signal.sigset_t; Dummy : C.signed_int; R : C.signed_int; begin Dummy := C.signal.sigemptyset (Mask'Access); Dummy := C.signal.sigaddset (Mask'Access, Interrupt); R := C.signal.sigprocmask (How, Mask'Access, null); if R < 0 then raise Program_Error; end if; end Mask; -- implementation function Is_Blocked (Interrupt : Interrupt_Id) return Boolean is Current_Mask : aliased C.signal.sigset_t; R : C.signed_int; begin R := C.signal.sigprocmask ( C.signal.SIG_SETMASK, null, Current_Mask'Access); if R < 0 then raise Program_Error; end if; return C.signal.sigismember (Current_Mask'Access, Interrupt) /= 0; end Is_Blocked; procedure Block (Interrupt : Interrupt_Id) is begin Mask (C.signal.SIG_BLOCK, Interrupt); end Block; procedure Unblock (Interrupt : Interrupt_Id) is begin Mask (C.signal.SIG_UNBLOCK, Interrupt); end Unblock; procedure Raise_Interrupt (Interrupt : Interrupt_Id) is begin if C.signal.C_raise (Interrupt) < 0 then raise Program_Error; end if; end Raise_Interrupt; end System.Native_Interrupts;
-- Copyright (c) 2020 Raspberry Pi (Trading) Ltd. -- -- SPDX-License-Identifier: BSD-3-Clause -- This spec has been automatically generated from rp2040.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with HAL; with System; package RP_SVD.WATCHDOG is pragma Preelaborate; --------------- -- Registers -- --------------- subtype CTRL_TIME_Field is HAL.UInt24; -- CTRL_PAUSE_DBG array type CTRL_PAUSE_DBG_Field_Array is array (0 .. 1) of Boolean with Component_Size => 1, Size => 2; -- Type definition for CTRL_PAUSE_DBG type CTRL_PAUSE_DBG_Field (As_Array : Boolean := False) is record case As_Array is when False => -- PAUSE_DBG as a value Val : HAL.UInt2; when True => -- PAUSE_DBG as an array Arr : CTRL_PAUSE_DBG_Field_Array; end case; end record with Unchecked_Union, Size => 2; for CTRL_PAUSE_DBG_Field use record Val at 0 range 0 .. 1; Arr at 0 range 0 .. 1; end record; -- Watchdog control\n The rst_wdsel register determines which subsystems -- are reset when the watchdog is triggered.\n The watchdog can be -- triggered in software. type CTRL_Register is record -- Read-only. Indicates the number of ticks / 2 (see errata RP2040-E1) -- before a watchdog reset will be triggered TIME : CTRL_TIME_Field := 16#0#; -- Pause the watchdog timer when JTAG is accessing the bus fabric PAUSE_JTAG : Boolean := True; -- Pause the watchdog timer when processor 0 is in debug mode PAUSE_DBG : CTRL_PAUSE_DBG_Field := (As_Array => False, Val => 16#1#); -- unspecified Reserved_27_29 : HAL.UInt3 := 16#0#; -- When not enabled the watchdog timer is paused ENABLE : Boolean := False; -- After a write operation all bits in the field are cleared (set to -- zero). Trigger a watchdog reset TRIGGER : Boolean := False; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CTRL_Register use record TIME at 0 range 0 .. 23; PAUSE_JTAG at 0 range 24 .. 24; PAUSE_DBG at 0 range 25 .. 26; Reserved_27_29 at 0 range 27 .. 29; ENABLE at 0 range 30 .. 30; TRIGGER at 0 range 31 .. 31; end record; subtype LOAD_LOAD_Field is HAL.UInt24; -- Load the watchdog timer. The maximum setting is 0xffffff which -- corresponds to 0xffffff / 2 ticks before triggering a watchdog reset -- (see errata RP2040-E1). type LOAD_Register is record -- Write-only. LOAD : LOAD_LOAD_Field := 16#0#; -- unspecified Reserved_24_31 : HAL.UInt8 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for LOAD_Register use record LOAD at 0 range 0 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; -- Logs the reason for the last reset. Both bits are zero for the case of a -- hardware reset. type REASON_Register is record -- Read-only. TIMER : Boolean; -- Read-only. FORCE : Boolean; -- unspecified Reserved_2_31 : HAL.UInt30; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for REASON_Register use record TIMER at 0 range 0 .. 0; FORCE at 0 range 1 .. 1; Reserved_2_31 at 0 range 2 .. 31; end record; subtype TICK_CYCLES_Field is HAL.UInt9; subtype TICK_COUNT_Field is HAL.UInt9; -- Controls the tick generator type TICK_Register is record -- Total number of clk_tick cycles before the next tick. CYCLES : TICK_CYCLES_Field := 16#0#; -- start / stop tick generation ENABLE : Boolean := True; -- Read-only. Is the tick generator running? RUNNING : Boolean := False; -- Read-only. Count down timer: the remaining number clk_tick cycles -- before the next tick is generated. COUNT : TICK_COUNT_Field := 16#0#; -- unspecified Reserved_20_31 : HAL.UInt12 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for TICK_Register use record CYCLES at 0 range 0 .. 8; ENABLE at 0 range 9 .. 9; RUNNING at 0 range 10 .. 10; COUNT at 0 range 11 .. 19; Reserved_20_31 at 0 range 20 .. 31; end record; ----------------- -- Peripherals -- ----------------- type WATCHDOG_Peripheral is record -- Watchdog control\n The rst_wdsel register determines which subsystems -- are reset when the watchdog is triggered.\n The watchdog can be -- triggered in software. CTRL : aliased CTRL_Register; -- Load the watchdog timer. The maximum setting is 0xffffff which -- corresponds to 0xffffff / 2 ticks before triggering a watchdog reset -- (see errata RP2040-E1). LOAD : aliased LOAD_Register; -- Logs the reason for the last reset. Both bits are zero for the case -- of a hardware reset. REASON : aliased REASON_Register; -- Scratch register. Information persists through soft reset of the -- chip. SCRATCH0 : aliased HAL.UInt32; -- Scratch register. Information persists through soft reset of the -- chip. SCRATCH1 : aliased HAL.UInt32; -- Scratch register. Information persists through soft reset of the -- chip. SCRATCH2 : aliased HAL.UInt32; -- Scratch register. Information persists through soft reset of the -- chip. SCRATCH3 : aliased HAL.UInt32; -- Scratch register. Information persists through soft reset of the -- chip. SCRATCH4 : aliased HAL.UInt32; -- Scratch register. Information persists through soft reset of the -- chip. SCRATCH5 : aliased HAL.UInt32; -- Scratch register. Information persists through soft reset of the -- chip. SCRATCH6 : aliased HAL.UInt32; -- Scratch register. Information persists through soft reset of the -- chip. SCRATCH7 : aliased HAL.UInt32; -- Controls the tick generator TICK : aliased TICK_Register; end record with Volatile; for WATCHDOG_Peripheral use record CTRL at 16#0# range 0 .. 31; LOAD at 16#4# range 0 .. 31; REASON at 16#8# range 0 .. 31; SCRATCH0 at 16#C# range 0 .. 31; SCRATCH1 at 16#10# range 0 .. 31; SCRATCH2 at 16#14# range 0 .. 31; SCRATCH3 at 16#18# range 0 .. 31; SCRATCH4 at 16#1C# range 0 .. 31; SCRATCH5 at 16#20# range 0 .. 31; SCRATCH6 at 16#24# range 0 .. 31; SCRATCH7 at 16#28# range 0 .. 31; TICK at 16#2C# range 0 .. 31; end record; WATCHDOG_Periph : aliased WATCHDOG_Peripheral with Import, Address => WATCHDOG_Base; end RP_SVD.WATCHDOG;
pragma Ada_2012; package body GStreamer.rtsp.message is -------------- -- Get_Type -- -------------- function Get_Type (Msg : access GstRTSPMessage_Record) return GstRTSPMsgType is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "Get_Type unimplemented"); return raise Program_Error with "Unimplemented function Get_Type"; end Get_Type; ----------------- -- new_request -- ----------------- procedure new_request (msg : System.Address; method : GstRTSPMethod; uri : access GLIB.gchar) is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "new_request unimplemented"); raise Program_Error with "Unimplemented procedure new_request"; end new_request; ------------------ -- init_request -- ------------------ procedure init_request (msg : access GstRTSPMessage; method : GstRTSPMethod; uri : access GLIB.gchar) is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "init_request unimplemented"); raise Program_Error with "Unimplemented procedure init_request"; end init_request; ------------------- -- parse_request -- ------------------- procedure parse_request (msg : access GstRTSPMessage; method : access GstRTSPMethod; uri : System.Address; version : access GstRTSPVersion) is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "parse_request unimplemented"); raise Program_Error with "Unimplemented procedure parse_request"; end parse_request; ------------------ -- new_response -- ------------------ procedure new_response (msg : System.Address; code : GstRTSPStatusCode; reason : access GLIB.gchar; request : access constant GstRTSPMessage) is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "new_response unimplemented"); raise Program_Error with "Unimplemented procedure new_response"; end new_response; ------------------- -- init_response -- ------------------- procedure init_response (msg : access GstRTSPMessage_Record; code : GstRTSPStatusCode; reason : access GLIB.gchar; request : access constant GstRTSPMessage) is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "init_response unimplemented"); raise Program_Error with "Unimplemented procedure init_response"; end init_response; -------------------- -- parse_response -- -------------------- procedure parse_response (msg : access GstRTSPMessage_Record; code : access GstRTSPStatusCode; reason : System.Address; version : access GstRTSPVersion) is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "parse_response unimplemented"); raise Program_Error with "Unimplemented procedure parse_response"; end parse_response; -------------- -- new_data -- -------------- procedure new_data (msg : System.Address; channel : GLIB.guint8) is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "new_data unimplemented"); raise Program_Error with "Unimplemented procedure new_data"; end new_data; --------------- -- init_data -- --------------- procedure init_data (msg : access GstRTSPMessage_Record; channel : GLIB.guint8) is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "init_data unimplemented"); raise Program_Error with "Unimplemented procedure init_data"; end init_data; ---------------- -- parse_data -- ---------------- procedure parse_data (msg : access GstRTSPMessage_Record; channel : access GLIB.guint8) is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "parse_data unimplemented"); raise Program_Error with "Unimplemented procedure parse_data"; end parse_data; ---------------- -- add_header -- ---------------- procedure add_header (msg : access GstRTSPMessage_Record; field : GstRTSPHeaderField; value : access GLIB.gchar) is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "add_header unimplemented"); raise Program_Error with "Unimplemented procedure add_header"; end add_header; ----------------- -- take_header -- ----------------- procedure take_header (msg : access GstRTSPMessage_Record; field : GstRTSPHeaderField; value : access GLIB.gchar) is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "take_header unimplemented"); raise Program_Error with "Unimplemented procedure take_header"; end take_header; ------------------- -- remove_header -- ------------------- procedure remove_header (msg : access GstRTSPMessage_Record; field : GstRTSPHeaderField; indx : GLIB.gint) is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "remove_header unimplemented"); raise Program_Error with "Unimplemented procedure remove_header"; end remove_header; ---------------- -- get_header -- ---------------- procedure get_header (msg : access constant GstRTSPMessage_Record; field : GstRTSPHeaderField; value : System.Address; indx : GLIB.gint) is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "get_header unimplemented"); raise Program_Error with "Unimplemented procedure get_header"; end get_header; -------------------- -- append_headers -- -------------------- procedure append_headers (msg : access constant GstRTSPMessage; str : access Glib.String.GString) is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "append_headers unimplemented"); raise Program_Error with "Unimplemented procedure append_headers"; end append_headers; -------------- -- set_body -- -------------- procedure set_body (msg : access GstRTSPMessage_Record; data : access GLIB.guint8; size : GLIB.guint) is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "set_body unimplemented"); raise Program_Error with "Unimplemented procedure set_body"; end set_body; --------------- -- take_body -- --------------- procedure take_body (msg : access GstRTSPMessage_Record; data : access GLIB.guint8; size : GLIB.guint) is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "take_body unimplemented"); raise Program_Error with "Unimplemented procedure take_body"; end take_body; -------------- -- get_body -- -------------- procedure get_body (msg : access constant GstRTSPMessage_Record; data : System.Address; size : access GLIB.guint) is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "get_body unimplemented"); raise Program_Error with "Unimplemented procedure get_body"; end get_body; ---------------- -- steal_body -- ---------------- procedure steal_body (msg : access GstRTSPMessage_Record; data : System.Address; size : access GLIB.guint) is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "steal_body unimplemented"); raise Program_Error with "Unimplemented procedure steal_body"; end steal_body; ---------- -- dump -- ---------- procedure dump (msg : access GstRTSPMessage_Record) is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "dump unimplemented"); raise Program_Error with "Unimplemented procedure dump"; end dump; ------------- -- gst_new -- ------------- procedure gst_new (msg : in out GstRTSPMessage) is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "gst_new unimplemented"); raise Program_Error with "Unimplemented procedure gst_new"; end gst_new; ---------- -- init -- ---------- procedure init (msg : access GstRTSPMessage_Record) is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "init unimplemented"); raise Program_Error with "Unimplemented procedure init"; end init; ----------- -- unset -- ----------- procedure unset (msg : access GstRTSPMessage_Record) is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "unset unimplemented"); raise Program_Error with "Unimplemented procedure unset"; end unset; ---------- -- free -- ---------- procedure free (msg : access GstRTSPMessage_Record) is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "free unimplemented"); raise Program_Error with "Unimplemented procedure free"; end free; end GStreamer.rtsp.message;
pragma License (Unrestricted); with Ada.Wide_Characters.Handling; package Ada.Wide_Characters.Unicode is pragma Preelaborate; -- Ada.Wide_Characters.Handling is not Pure. function To_Lower_Case (U : Wide_Character) return Wide_Character renames Handling.To_Lower; end Ada.Wide_Characters.Unicode;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- E X P _ P A K D -- -- -- -- S p e c -- -- -- -- Copyright (C) 1992-2020, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING3. If not, go to -- -- http://www.gnu.org/licenses for a complete copy of the license. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- Expand routines for manipulation of packed arrays with Rtsfind; use Rtsfind; with Types; use Types; package Exp_Pakd is ------------------------------------- -- Implementation of Packed Arrays -- ------------------------------------- -- When a packed array (sub)type is frozen, we create a corresponding -- type that will be used to hold the bits of the packed value, and store -- the entity for this type in the Packed_Array_Impl_Type field of the -- E_Array_Type or E_Array_Subtype entity for the packed array. -- This packed array type has the name xxxPn, where xxx is the name -- of the packed type, and n is the component size. The expanded -- declaration declares a type that is one of the following: -- For an unconstrained array with component size 1,2,4 or any other -- odd component size. These are the cases in which we do not need -- to align the underlying array. -- type xxxPn is new Packed_Bytes1; -- For an unconstrained array with component size that is divisible -- by 2, but not divisible by 4 (other than 2 itself). These are the -- cases in which we can generate better code if the underlying array -- is 2-byte aligned (see System.Pack_14 in file s-pack14 for example). -- type xxxPn is new Packed_Bytes2; -- For an unconstrained array with component size that is divisible -- by 4, other than powers of 2 (which either come under the 1,2,4 -- exception above, or are not packed at all). These are cases where -- we can generate better code if the underlying array is 4-byte -- aligned (see System.Pack_20 in file s-pack20 for example). -- type xxxPn is new Packed_Bytes4; -- For a constrained array with a static index type where the number -- of bits does not exceed the size of Unsigned: -- type xxxPn is new Unsigned range 0 .. 2 ** nbits - 1; -- For a constrained array with a static index type where the number -- of bits is greater than the size of Unsigned, but does not exceed -- the size of Long_Long_Unsigned: -- type xxxPn is new Long_Long_Unsigned range 0 .. 2 ** nbits - 1; -- For all other constrained arrays, we use one of -- type xxxPn is new Packed_Bytes1 (0 .. m); -- type xxxPn is new Packed_Bytes2 (0 .. m); -- type xxxPn is new Packed_Bytes4 (0 .. m); -- where m is calculated (from the length of the original packed array) -- to hold the required number of bits, and the choice of the particular -- Packed_Bytes{1,2,4} type is made on the basis of alignment needs as -- described above for the unconstrained case. -- When the packed array (sub)type is specified to have the reverse scalar -- storage order, the Packed_Bytes{1,2,4} references above are replaced -- with Rev_Packed_Bytes{1,2,4}. This is necessary because, although the -- component type is Packed_Byte and therefore endian neutral, the scalar -- storage order of the new type must be compatible with that of an outer -- composite type, if this composite type contains a component whose type -- is the packed array (sub)type and which does not start or does not end -- on a storage unit boundary. -- When a variable of packed array type is allocated, gigi will allocate -- the amount of space indicated by the corresponding packed array type. -- However, we do NOT attempt to rewrite the types of any references or -- to retype the variable itself, since this would cause all kinds of -- semantic problems in the front end (remember that expansion proceeds -- at the same time as analysis). -- For an indexed reference to a packed array, we simply convert the -- reference to the appropriate equivalent reference to the object -- of the packed array type (using unchecked conversion). -- In some cases (for internally generated types, and for the subtypes -- for record fields that depend on a discriminant), the corresponding -- packed type cannot be easily generated in advance. In these cases, -- we generate the required subtype on the fly at the reference point. -- For the modular case, any unused bits are initialized to zero, and -- all operations maintain these bits as zero (where necessary all -- unchecked conversions from corresponding array values require -- these bits to be clear, which is done automatically by gigi). -- For the array cases, there can be unused bits in the last byte, and -- these are neither initialized, nor treated specially in operations -- (i.e. it is allowable for these bits to be clobbered, e.g. by not). --------------------------- -- Endian Considerations -- --------------------------- -- The standard does not specify the way in which bits are numbered in -- a packed array. There are two reasonable rules for deciding this: -- Store the first bit at right end (low order) word. This means -- that the scaled subscript can be used directly as a left shift -- count (if we put bit 0 at the left end, then we need an extra -- subtract to compute the shift count). -- Layout the bits so that if the packed boolean array is overlaid on -- a record, using unchecked conversion, then bit 0 of the array is -- the same as the bit numbered bit 0 in a record representation -- clause applying to the record. For example: -- type Rec is record -- C : Bits4; -- D : Bits7; -- E : Bits5; -- end record; -- for Rec use record -- C at 0 range 0 .. 3; -- D at 0 range 4 .. 10; -- E at 0 range 11 .. 15; -- end record; -- type P16 is array (0 .. 15) of Boolean; -- pragma Pack (P16); -- Now if we use unchecked conversion to convert a value of the record -- type to the packed array type, according to this second criterion, -- we would expect field D to occupy bits 4..10 of the Boolean array. -- Although not required, this correspondence seems a highly desirable -- property, and is one that GNAT decides to guarantee. For a little -- endian machine, we can also meet the first requirement, but for a -- big endian machine, it will be necessary to store the first bit of -- a Boolean array in the left end (most significant) bit of the word. -- This may cost an extra instruction on some machines, but we consider -- that a worthwhile price to pay for the consistency. -- One more important point arises in the case where we have a constrained -- subtype of an unconstrained array. Take the case of 20 bits. For the -- unconstrained representation, we would use an array of bytes: -- Little-endian case -- 8-7-6-5-4-3-2-1 16-15-14-13-12-11-10-9 x-x-x-x-20-19-18-17 -- Big-endian case -- 1-2-3-4-5-6-7-8 9-10-11-12-13-14-15-16 17-18-19-20-x-x-x-x -- For the constrained case, we use a 20-bit modular value, but in -- general this value may well be stored in 32 bits. Let's look at -- what it looks like: -- Little-endian case -- x-x-x-x-x-x-x-x-x-x-x-x-20-19-18-17-...-10-9-8-7-6-5-4-3-2-1 -- which stored in memory looks like -- 8-7-...-2-1 16-15-...-10-9 x-x-x-x-20-19-18-17 x-x-x-x-x-x-x -- An important rule is that the constrained and unconstrained cases -- must have the same bit representation in memory, since we will often -- convert from one to the other (e.g. when calling a procedure whose -- formal is unconstrained). As we see, that criterion is met for the -- little-endian case above. Now let's look at the big-endian case: -- Big-endian case -- x-x-x-x-x-x-x-x-x-x-x-x-1-2-3-4-5-6-7-8-9-10-...-17-18-19-20 -- which stored in memory looks like -- x-x-x-x-x-x-x-x x-x-x-x-1-2-3-4 5-6-...11-12 13-14-...-19-20 -- That won't do, the representation value in memory is NOT the same in -- the constrained and unconstrained case. The solution is to store the -- modular value left-justified: -- 1-2-3-4-5-6-7-8-9-10-...-17-18-19-20-x-x-x-x-x-x-x-x-x-x-x -- which stored in memory looks like -- 1-2-...-7-8 9-10-...15-16 17-18-19-20-x-x-x-x x-x-x-x-x-x-x-x -- and now, we do indeed have the same representation for the memory -- version in the constrained and unconstrained cases. ---------------------------------------------- -- Entity Tables for Packed Access Routines -- ---------------------------------------------- -- For the cases of component size = 3,5-7,9-15,17-31,33-63 we call library -- routines. These tables provide the entity for the proper routine. They -- are exposed in the spec to allow checking for the presence of the needed -- routine when an array is subject to pragma Pack. type E_Array is array (Int range 01 .. 63) of RE_Id; -- Array of Bits_nn entities. Note that we do not use library routines -- for the 8-bit and 16-bit cases, but we still fill in the table, using -- entries from System.Unsigned, because we also use this table for -- certain special unchecked conversions in the big-endian case. Bits_Id : constant E_Array := (01 => RE_Bits_1, 02 => RE_Bits_2, 03 => RE_Bits_03, 04 => RE_Bits_4, 05 => RE_Bits_05, 06 => RE_Bits_06, 07 => RE_Bits_07, 08 => RE_Unsigned_8, 09 => RE_Bits_09, 10 => RE_Bits_10, 11 => RE_Bits_11, 12 => RE_Bits_12, 13 => RE_Bits_13, 14 => RE_Bits_14, 15 => RE_Bits_15, 16 => RE_Unsigned_16, 17 => RE_Bits_17, 18 => RE_Bits_18, 19 => RE_Bits_19, 20 => RE_Bits_20, 21 => RE_Bits_21, 22 => RE_Bits_22, 23 => RE_Bits_23, 24 => RE_Bits_24, 25 => RE_Bits_25, 26 => RE_Bits_26, 27 => RE_Bits_27, 28 => RE_Bits_28, 29 => RE_Bits_29, 30 => RE_Bits_30, 31 => RE_Bits_31, 32 => RE_Unsigned_32, 33 => RE_Bits_33, 34 => RE_Bits_34, 35 => RE_Bits_35, 36 => RE_Bits_36, 37 => RE_Bits_37, 38 => RE_Bits_38, 39 => RE_Bits_39, 40 => RE_Bits_40, 41 => RE_Bits_41, 42 => RE_Bits_42, 43 => RE_Bits_43, 44 => RE_Bits_44, 45 => RE_Bits_45, 46 => RE_Bits_46, 47 => RE_Bits_47, 48 => RE_Bits_48, 49 => RE_Bits_49, 50 => RE_Bits_50, 51 => RE_Bits_51, 52 => RE_Bits_52, 53 => RE_Bits_53, 54 => RE_Bits_54, 55 => RE_Bits_55, 56 => RE_Bits_56, 57 => RE_Bits_57, 58 => RE_Bits_58, 59 => RE_Bits_59, 60 => RE_Bits_60, 61 => RE_Bits_61, 62 => RE_Bits_62, 63 => RE_Bits_63); -- Array of Get routine entities. These are used to obtain an element from -- a packed array. The N'th entry is used to obtain elements from a packed -- array whose component size is N. RE_Null is used as a null entry, for -- the cases where a library routine is not used. Get_Id : constant E_Array := (01 => RE_Null, 02 => RE_Null, 03 => RE_Get_03, 04 => RE_Null, 05 => RE_Get_05, 06 => RE_Get_06, 07 => RE_Get_07, 08 => RE_Null, 09 => RE_Get_09, 10 => RE_Get_10, 11 => RE_Get_11, 12 => RE_Get_12, 13 => RE_Get_13, 14 => RE_Get_14, 15 => RE_Get_15, 16 => RE_Null, 17 => RE_Get_17, 18 => RE_Get_18, 19 => RE_Get_19, 20 => RE_Get_20, 21 => RE_Get_21, 22 => RE_Get_22, 23 => RE_Get_23, 24 => RE_Get_24, 25 => RE_Get_25, 26 => RE_Get_26, 27 => RE_Get_27, 28 => RE_Get_28, 29 => RE_Get_29, 30 => RE_Get_30, 31 => RE_Get_31, 32 => RE_Null, 33 => RE_Get_33, 34 => RE_Get_34, 35 => RE_Get_35, 36 => RE_Get_36, 37 => RE_Get_37, 38 => RE_Get_38, 39 => RE_Get_39, 40 => RE_Get_40, 41 => RE_Get_41, 42 => RE_Get_42, 43 => RE_Get_43, 44 => RE_Get_44, 45 => RE_Get_45, 46 => RE_Get_46, 47 => RE_Get_47, 48 => RE_Get_48, 49 => RE_Get_49, 50 => RE_Get_50, 51 => RE_Get_51, 52 => RE_Get_52, 53 => RE_Get_53, 54 => RE_Get_54, 55 => RE_Get_55, 56 => RE_Get_56, 57 => RE_Get_57, 58 => RE_Get_58, 59 => RE_Get_59, 60 => RE_Get_60, 61 => RE_Get_61, 62 => RE_Get_62, 63 => RE_Get_63); -- Array of Get routine entities to be used in the case where the packed -- array is itself a component of a packed structure, and therefore may not -- be fully aligned. This only affects the even sizes, since for the odd -- sizes, we do not get any fixed alignment in any case. GetU_Id : constant E_Array := (01 => RE_Null, 02 => RE_Null, 03 => RE_Get_03, 04 => RE_Null, 05 => RE_Get_05, 06 => RE_GetU_06, 07 => RE_Get_07, 08 => RE_Null, 09 => RE_Get_09, 10 => RE_GetU_10, 11 => RE_Get_11, 12 => RE_GetU_12, 13 => RE_Get_13, 14 => RE_GetU_14, 15 => RE_Get_15, 16 => RE_Null, 17 => RE_Get_17, 18 => RE_GetU_18, 19 => RE_Get_19, 20 => RE_GetU_20, 21 => RE_Get_21, 22 => RE_GetU_22, 23 => RE_Get_23, 24 => RE_GetU_24, 25 => RE_Get_25, 26 => RE_GetU_26, 27 => RE_Get_27, 28 => RE_GetU_28, 29 => RE_Get_29, 30 => RE_GetU_30, 31 => RE_Get_31, 32 => RE_Null, 33 => RE_Get_33, 34 => RE_GetU_34, 35 => RE_Get_35, 36 => RE_GetU_36, 37 => RE_Get_37, 38 => RE_GetU_38, 39 => RE_Get_39, 40 => RE_GetU_40, 41 => RE_Get_41, 42 => RE_GetU_42, 43 => RE_Get_43, 44 => RE_GetU_44, 45 => RE_Get_45, 46 => RE_GetU_46, 47 => RE_Get_47, 48 => RE_GetU_48, 49 => RE_Get_49, 50 => RE_GetU_50, 51 => RE_Get_51, 52 => RE_GetU_52, 53 => RE_Get_53, 54 => RE_GetU_54, 55 => RE_Get_55, 56 => RE_GetU_56, 57 => RE_Get_57, 58 => RE_GetU_58, 59 => RE_Get_59, 60 => RE_GetU_60, 61 => RE_Get_61, 62 => RE_GetU_62, 63 => RE_Get_63); -- Array of Set routine entities. These are used to assign an element of a -- packed array. The N'th entry is used to assign elements for a packed -- array whose component size is N. RE_Null is used as a null entry, for -- the cases where a library routine is not used. Set_Id : constant E_Array := (01 => RE_Null, 02 => RE_Null, 03 => RE_Set_03, 04 => RE_Null, 05 => RE_Set_05, 06 => RE_Set_06, 07 => RE_Set_07, 08 => RE_Null, 09 => RE_Set_09, 10 => RE_Set_10, 11 => RE_Set_11, 12 => RE_Set_12, 13 => RE_Set_13, 14 => RE_Set_14, 15 => RE_Set_15, 16 => RE_Null, 17 => RE_Set_17, 18 => RE_Set_18, 19 => RE_Set_19, 20 => RE_Set_20, 21 => RE_Set_21, 22 => RE_Set_22, 23 => RE_Set_23, 24 => RE_Set_24, 25 => RE_Set_25, 26 => RE_Set_26, 27 => RE_Set_27, 28 => RE_Set_28, 29 => RE_Set_29, 30 => RE_Set_30, 31 => RE_Set_31, 32 => RE_Null, 33 => RE_Set_33, 34 => RE_Set_34, 35 => RE_Set_35, 36 => RE_Set_36, 37 => RE_Set_37, 38 => RE_Set_38, 39 => RE_Set_39, 40 => RE_Set_40, 41 => RE_Set_41, 42 => RE_Set_42, 43 => RE_Set_43, 44 => RE_Set_44, 45 => RE_Set_45, 46 => RE_Set_46, 47 => RE_Set_47, 48 => RE_Set_48, 49 => RE_Set_49, 50 => RE_Set_50, 51 => RE_Set_51, 52 => RE_Set_52, 53 => RE_Set_53, 54 => RE_Set_54, 55 => RE_Set_55, 56 => RE_Set_56, 57 => RE_Set_57, 58 => RE_Set_58, 59 => RE_Set_59, 60 => RE_Set_60, 61 => RE_Set_61, 62 => RE_Set_62, 63 => RE_Set_63); -- Array of Set routine entities to be used in the case where the packed -- array is itself a component of a packed structure, and therefore may not -- be fully aligned. This only affects the even sizes, since for the odd -- sizes, we do not get any fixed alignment in any case. SetU_Id : constant E_Array := (01 => RE_Null, 02 => RE_Null, 03 => RE_Set_03, 04 => RE_Null, 05 => RE_Set_05, 06 => RE_SetU_06, 07 => RE_Set_07, 08 => RE_Null, 09 => RE_Set_09, 10 => RE_SetU_10, 11 => RE_Set_11, 12 => RE_SetU_12, 13 => RE_Set_13, 14 => RE_SetU_14, 15 => RE_Set_15, 16 => RE_Null, 17 => RE_Set_17, 18 => RE_SetU_18, 19 => RE_Set_19, 20 => RE_SetU_20, 21 => RE_Set_21, 22 => RE_SetU_22, 23 => RE_Set_23, 24 => RE_SetU_24, 25 => RE_Set_25, 26 => RE_SetU_26, 27 => RE_Set_27, 28 => RE_SetU_28, 29 => RE_Set_29, 30 => RE_SetU_30, 31 => RE_Set_31, 32 => RE_Null, 33 => RE_Set_33, 34 => RE_SetU_34, 35 => RE_Set_35, 36 => RE_SetU_36, 37 => RE_Set_37, 38 => RE_SetU_38, 39 => RE_Set_39, 40 => RE_SetU_40, 41 => RE_Set_41, 42 => RE_SetU_42, 43 => RE_Set_43, 44 => RE_SetU_44, 45 => RE_Set_45, 46 => RE_SetU_46, 47 => RE_Set_47, 48 => RE_SetU_48, 49 => RE_Set_49, 50 => RE_SetU_50, 51 => RE_Set_51, 52 => RE_SetU_52, 53 => RE_Set_53, 54 => RE_SetU_54, 55 => RE_Set_55, 56 => RE_SetU_56, 57 => RE_Set_57, 58 => RE_SetU_58, 59 => RE_Set_59, 60 => RE_SetU_60, 61 => RE_Set_61, 62 => RE_SetU_62, 63 => RE_Set_63); ----------------- -- Subprograms -- ----------------- procedure Create_Packed_Array_Impl_Type (Typ : Entity_Id); -- Typ is a array type or subtype to which pragma Pack applies. If the -- Packed_Array_Impl_Type field of Typ is already set, then the call has -- no effect, otherwise a suitable type or subtype is created and stored in -- the Packed_Array_Impl_Type field of Typ. This created type is an Itype -- so that Gigi will simply elaborate and freeze the type on first use -- (which is typically the definition of the corresponding array type). -- -- Note: although this routine is included in the expander package for -- packed types, it is actually called unconditionally from Freeze, -- whether or not expansion (and code generation) is enabled. We do this -- since we want gigi to be able to properly compute type characteristics -- (for the Data Decomposition Annex of ASIS, and possible other future -- uses) even if code generation is not active. Strictly this means that -- this procedure is not part of the expander, but it seems appropriate -- to keep it together with the other expansion routines that have to do -- with packed array types. procedure Expand_Packed_Boolean_Operator (N : Node_Id); -- N is an N_Op_And, N_Op_Or or N_Op_Xor node whose operand type is a -- packed boolean array. This routine expands the appropriate operations -- to carry out the logical operation on the packed arrays. It handles -- both the modular and array representation cases. procedure Expand_Packed_Element_Reference (N : Node_Id); -- N is an N_Indexed_Component node whose prefix is a packed array. In -- the bit packed case, this routine can only be used for the expression -- evaluation case, not the assignment case, since the result is not a -- variable. See Expand_Bit_Packed_Element_Set for how the assignment case -- is handled in the bit packed case. For the enumeration case, the result -- of this call is always a variable, so the call can be used for both the -- expression evaluation and assignment cases. procedure Expand_Bit_Packed_Element_Set (N : Node_Id); -- N is an N_Assignment_Statement node whose name is an indexed -- component of a bit-packed array. This procedure rewrites the entire -- assignment statement with appropriate code to set the referenced -- bits of the packed array type object. Note that this procedure is -- used only for the bit-packed case, not for the enumeration case. procedure Expand_Packed_Eq (N : Node_Id); -- N is an N_Op_Eq node where the operands are packed arrays whose -- representation is an array-of-bytes type (the case where a modular -- type is used for the representation does not require any special -- handling, because in the modular case, unused bits are zeroes. procedure Expand_Packed_Not (N : Node_Id); -- N is an N_Op_Not node where the operand is packed array of Boolean -- in standard representation (i.e. component size is one bit). This -- procedure expands the corresponding not operation. Note that the -- non-standard representation case is handled by using a loop through -- elements generated by the normal non-packed circuitry. function Involves_Packed_Array_Reference (N : Node_Id) return Boolean; -- N is the node for a name. This function returns true if the name -- involves a packed array reference. A node involves a packed array -- reference if it is itself an indexed component referring to a bit- -- packed array, or it is a selected component whose prefix involves -- a packed array reference. procedure Expand_Packed_Address_Reference (N : Node_Id); -- The node N is an attribute reference for the 'Address reference, where -- the prefix involves a packed array reference. This routine expands the -- necessary code for performing the address reference in this case. procedure Expand_Packed_Bit_Reference (N : Node_Id); -- The node N is an attribute reference for the 'Bit reference, where the -- prefix involves a packed array reference. This routine expands the -- necessary code for performing the bit reference in this case. end Exp_Pakd;
generic type T is private; with function Image (Item : T) return String; with function "=" (First_Item, Second_Item : T) return Boolean; with function "+" (First_Item, Second_Item : T) return T; with function "-" (First_Item, Second_Item : T) return T; with function "*" (First_Item, Second_Item : T) return T; with function "/" (First_Item, Second_Item : T) return T; package Eval is type Expr; type Expr_Access is access Expr; type Expr_Type is (Add, Sub, Mul, Div, Val); type Expr (Kind : Expr_Type) is record case Kind is when Val => Val : T; when others => Left, Right : Expr_Access; end case; end record; procedure Show (E : in Expr); function Eval (E : in Expr) return T; end Eval;
with Ada.Strings; use Ada.Strings; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Strings.Equal_Case_Insensitive; with Langkit_Support.Text; use Langkit_Support.Text; package body Rejuvenation.Utils is -- Raw signature -------- function Raw_Signature (Node : Ada_Node'Class; Before, After : Node_Location := No_Trivia) return String is begin if Node.Is_Null then return ""; else declare First : constant Positive := Start_Offset (Node, Before); Last : constant Natural := End_Offset (Node, After); Unit : constant Analysis_Unit := Node.Unit; Node_Str : constant String := Encode (Unit.Text (First .. Last), Unit.Get_Charset); begin return Node_Str; end; end if; end Raw_Signature; function Raw_Signature (Token : Token_Reference; Charset : String) return String is (if Token = No_Token then "" else Encode (Text (Token), Charset)); function Raw_Signature (First_Node, Last_Node : Ada_Node'Class; Before, After : Node_Location := No_Trivia) return String is First : constant Positive := Start_Offset (First_Node, Before); Last : constant Natural := End_Offset (Last_Node, After); Unit : constant Analysis_Unit := First_Node.Unit; Str : constant String := Encode (Unit.Text (First .. Last), Unit.Get_Charset); begin return Str; end Raw_Signature; function Are_Equal_As_Raw_Signature (Node1, Node2 : Ada_Node'Class) return Boolean is begin return Raw_Signature (Node1) = Raw_Signature (Node2); end Are_Equal_As_Raw_Signature; function Are_Equal_Case_Insensitive_As_Raw_Signature (Node1, Node2 : Ada_Node'Class) return Boolean is begin return Equal_Case_Insensitive (Raw_Signature (Node1), Raw_Signature (Node2)); end Are_Equal_Case_Insensitive_As_Raw_Signature; -- Package (Distributed over files) functionality function In_Same_Package (Unit1, Unit2 : Analysis_Unit) return Boolean is Unit1_Filename : constant String := Unit1.Get_Filename; Unit2_Filename : constant String := Unit2.Get_Filename; begin -- TODO: should the comparison be case insensitive? return Unit1_Filename (Unit1_Filename'First .. Unit1_Filename'Last - 1) = Unit2_Filename (Unit2_Filename'First .. Unit2_Filename'Last - 1); end In_Same_Package; -- Image -------- function Image (Node_List_Vector : Node_List.Vector) return String is begin if Node_List_Vector.Length = 0 then return "[]"; else declare Str : Unbounded_String := To_Unbounded_String (Node_List_Vector.First_Element.Image); begin for Index in Node_List_Vector.First_Index + 1 .. Node_List_Vector.Last_Index loop Str := Str & ", " & Node_List_Vector.Element (Positive (Index)).Image; end loop; return "[" & To_String (Str) & "]"; end; end if; end Image; -- Get trivia tokens -------- function Get_Trivia_Before (Node : Ada_Node'Class) return Token_List.Vector is begin return Get_Trivia_Before (Node.Token_Start); end Get_Trivia_Before; function Get_Trivia_Before (Token : Token_Reference) return Token_List.Vector is Results : Token_List.Vector; Running_Token : Token_Reference := Previous (Token); begin while Is_Trivia (Running_Token) loop Token_List.Prepend (Results, Running_Token); Running_Token := Previous (Running_Token); end loop; return Results; end Get_Trivia_Before; function Get_Trivia_After (Node : Ada_Node'Class) return Token_List.Vector is begin return Get_Trivia_After (Node.Token_End); end Get_Trivia_After; function Get_Trivia_After (Token : Token_Reference) return Token_List.Vector is Results : Token_List.Vector; Running_Token : Token_Reference := Next (Token); begin while Is_Trivia (Running_Token) loop Token_List.Append (Results, Running_Token); Running_Token := Next (Running_Token); end loop; return Results; end Get_Trivia_After; function Get_Tokens (Node : Ada_Node'Class) return Token_List.Vector is Results : Token_List.Vector; Running_Token : Token_Reference := Node.Token_Start; begin while Running_Token /= Node.Token_End loop Token_List.Append (Results, Running_Token); Running_Token := Next (Running_Token); end loop; Token_List.Append (Results, Running_Token); return Results; end Get_Tokens; end Rejuvenation.Utils;
with Ada.Text_IO; use Ada.Text_IO; procedure Euler11 is type Int_Mat is array(Positive range <>, Positive range <>) of Integer; N : constant Int_Mat := ((08,02,22,97,38,15,00,40,00,75,04,05,07,78,52,12,50,77,91,08), (49,49,99,40,17,81,18,57,60,87,17,40,98,43,69,48,04,56,62,00), (81,49,31,73,55,79,14,29,93,71,40,67,53,88,30,03,49,13,36,65), (52,70,95,23,04,60,11,42,69,24,68,56,01,32,56,71,37,02,36,91), (22,31,16,71,51,67,63,89,41,92,36,54,22,40,40,28,66,33,13,80), (24,47,32,60,99,03,45,02,44,75,33,53,78,36,84,20,35,17,12,50), (32,98,81,28,64,23,67,10,26,38,40,67,59,54,70,66,18,38,64,70), (67,26,20,68,02,62,12,20,95,63,94,39,63,08,40,91,66,49,94,21), (24,55,58,05,66,73,99,26,97,17,78,78,96,83,14,88,34,89,63,72), (21,36,23,09,75,00,76,44,20,45,35,14,00,61,33,97,34,31,33,95), (78,17,53,28,22,75,31,67,15,94,03,80,04,62,16,14,09,53,56,92), (16,39,05,42,96,35,31,47,55,58,88,24,00,17,54,24,36,29,85,57), (86,56,00,48,35,71,89,07,05,44,44,37,44,60,21,58,51,54,17,58), (19,80,81,68,05,94,47,69,28,73,92,13,86,52,17,77,04,89,55,40), (04,52,08,83,97,35,99,16,07,97,57,32,16,26,26,79,33,27,98,66), (88,36,68,87,57,62,20,72,03,46,33,67,46,55,12,32,63,93,53,69), (04,42,16,73,38,25,39,11,24,94,72,18,08,46,29,32,40,62,76,36), (20,69,36,41,72,30,23,88,34,62,99,69,82,67,59,85,74,04,36,16), (20,73,35,29,78,31,90,01,74,31,49,71,48,86,81,16,23,57,05,54), (01,70,54,71,83,51,54,69,16,92,33,48,61,43,52,01,89,19,67,48)); function Get(Y, X : Integer) return Integer is begin if X in N'Range(2) and Y in N'Range(1) then return N(Y, X); else return 0; end if; end; Max : Integer := 0; begin for Y in N'Range(1) loop for X in N'Range(2) loop -- direction - Max := Integer'Max(Max, Get(Y, X) * Get(Y, X + 1) * Get(Y, X + 2) * Get(Y, X + 3)); -- direction | Max := Integer'Max(Max, Get(Y, X) * Get(Y + 1, X) * Get(Y + 2, X) * Get(Y + 3, X)); -- direction / Max := Integer'Max(Max, Get(Y, X) * Get(Y - 1, X + 1) * Get(Y - 2, X + 2) * Get(Y - 3, X + 3)); -- direction \ Max := Integer'Max(Max, Get(Y, X) * Get(Y + 1, X + 1) * Get(Y + 2, X + 2) * Get(Y + 3, X + 3)); end loop; end loop; Put_Line(Integer'Image(Max)); end Euler11;
-- Teapot -- Produces a Newell teapot, also known as a Utah teapot, an iconic -- object in computer graphics history -- -- Chip Richards, NiEstu, Phoenix AZ, Spring 2012 -- This code is covered by the ISC License: -- -- Copyright © 2012, NiEstu -- -- Permission to use, copy, modify, and/or distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- -- The software is provided "as is" and the author disclaims all warranties -- with regard to this software including all implied warranties of -- merchantability and fitness. In no event shall the author be liable for any -- special, direct, indirect, or consequential damages or any damages -- whatsoever resulting from loss of use, data or profits, whether in an -- action of contract, negligence or other tortious action, arising out of or -- in connection with the use or performance of this software. package Teapot is -- Type of teapot to draw: wireframe or solid type Drawing_Type is ( Wire, Solid ); -- The procedure that draws a teapot procedure Draw (Size : in Float; Form : in Drawing_Type := Solid); end Teapot;
-- DAT2TXT.ADA Ver. 4.01 2001-SEP-10 Copyright 1988-2001 John J. Herro -- -- SOFTWARE INNOVATIONS TECHNOLOGY www.adatutor.com -- 1083 MANDARIN DR NE -- PALM BAY FL 32905-4706 john@adatutor.com -- -- (321) 951-0233 -- -- Run this program on a PC before installing AdaTutor on another computer. -- It translates ADATUTOR.DAT to TUTOR.TXT, a text file that can be easily -- transferred to other computers. Then compile and run TXT2DAT.ADA on the -- other machine to create ADATUTOR.DAT from TUTOR.TXT. -- -- This code is written in Ada 83 and will compile on Ada 83 and Ada 95 -- compilers. -- with Direct_IO, Text_IO; procedure DAT2TXT is subtype Block_Subtype is String(1 .. 64); package Random_IO is new Direct_IO(Block_Subtype); Data_File : Random_IO.File_Type; -- The input file. Text_File : Text_IO.File_Type; -- The output file. Block : Block_Subtype; -- A block of 64 bytes being copied. OK : Boolean := True; -- True when both files open successfully. Legal_Note : constant String := " Copyright 1988-2001 John J. Herro "; -- Legal_Note isn't used by the program, but it causes most -- compilers to place this string in the executable file. begin begin Random_IO.Open(Data_File, Random_IO.In_File, Name => "ADATUTOR.DAT"); exception when Random_IO.Name_Error => Text_IO.Put_Line( "I'm sorry. The file ADATUTOR.DAT seems to be missing."); OK := False; end; begin Text_IO.Create(Text_File, Name => "TUTOR.TXT"); exception when others => Text_IO.Put_Line("I'm sorry. I can't seem to create TUTOR.TXT."); Text_IO.Put_Line("Perhaps that file already exists?"); OK := False; end; if OK then while not Random_IO.End_Of_File(Data_File) loop Random_IO.Read(Data_File, Item => Block); Text_IO.Put_Line(File => Text_File, Item => Block); end loop; Random_IO.Close(Data_File); Text_IO.Close(Text_File); Text_IO.Put_Line("TUTOR.TXT created."); end if; end DAT2TXT;
with Ada.Text_IO; use Ada.Text_IO; with GNATCOLL.GMP; use GNATCOLL.GMP; with GNATCOLL.GMP.Integers; use GNATCOLL.GMP.Integers; procedure ArbitraryInt is type stracc is access String; BigInt : Big_Integer; len : Natural; str : stracc; begin Set (BigInt, 5); Raise_To_N (BigInt, Unsigned_Long (4**(3**2))); str := new String'(Image (BigInt)); len := str'Length; Put_Line ("Size is:"& Natural'Image (len)); Put_Line (str (1 .. 20) & "....." & str (len - 19 .. len)); end ArbitraryInt;