content
stringlengths
23
1.05M
with Interfaces; use Interfaces; with STM32GD.Board; use STM32GD.Board; package Host_Message is type Packet_Type is array (Unsigned_8 range <>) of Unsigned_8; procedure Send_Hello; procedure Send_Packet (Packet: Packet_Type; Length: Unsigned_8); procedure Send_Heartbeat; procedure Send_Error_Message (M : String); end Host_Message;
with avtas.lmcp.types; use avtas.lmcp.types; package avtas.lmcp.object is type Object is tagged null record; type Object_Acc is access Object; type Object_Class_Acc is access Object'Class; function clone(this, that: Object_Acc) return Object_Acc is abstract; function "="(this, that: Object) return Boolean is (True); function getLmcpTypeName(this : Object) return String is ("Object"); function getFullLmcpTypeName(this : Object) return String is ("avtas.lmcp.object.Object"); function getLmcpType(this : Object'Class) return Int32_t is abstract; function getSeriesName(this : Object'Class) return String is abstract; function getSeriesNameAsLong(this : Object'Class) return Int64_t is abstract; function getSeriesVersion(this : Object'Class) return UInt16_t is abstract; end avtas.lmcp.object;
-- ----------------------------------------------------------------------------- -- smk, the smart make (http://lionel.draghi.free.fr/smk/) -- © 2018, 2019 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. -- ----------------------------------------------------------------------------- with Smk.Assertions; with Smk.Definitions; use Smk.Definitions; with Smk.IO; with Smk.Files; with Smk.Files.File_Lists; with Smk.Files.Find_Unused; with Smk.Smkfiles; with Smk.Runfiles; with Smk.Settings; use Smk.Settings; with Ada.Command_Line; with Ada.Directories; with Ada.Containers; with Ada.Strings.Unbounded; with Ada.Text_IO; procedure Smk.Main is -- -------------------------------------------------------------------------- -- Put_Line Utilities: procedure Put_Help is separate; procedure Put_Error (Msg : in String := ""; With_Help : in Boolean := False) is separate; -- -------------------------------------------------------------------------- procedure Analyze_Cmd_Line is separate; -- Cmd line options are then available in the Settings package. -- -------------------------------------------------------------------------- procedure Build is separate; begin -- -------------------------------------------------------------------------- Analyze_Cmd_Line; if IO.Some_Error then -- If some error occurs during command line analysis, stop here, -- even if Ignore_Errors or Keep_Going is set Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); return; end if; case Current_Command is when Read_Smkfile => Smkfiles.Dump; when Status => declare The_Runfile : Runfiles.Runfile; use Files; Updated_List : Assertions.Condition_Lists.List; begin if Runfiles.Runfiles_Found then The_Runfile := Runfiles.Get_Saved_Run (+To_Runfile_Name (Smkfile_Name)); Runfiles.Update_Files_Status (The_Runfile.Run_List, Updated_List); Runfiles.Put_Run (The_Runfile.Run_List); else Put_Error ("No previous run found."); end if; end; when List_Previous_Runs => Runfiles.Put_Run_List; when List_Targets => Runfiles.Put_Files (Runfiles.Load_Runfile, Print_Targets => True); when List_Sources => Runfiles.Put_Files (Runfiles.Load_Runfile, Print_Sources => True); when List_Unused => declare use Runfiles; use Files; use Files.File_Lists; The_Runfile : Runfile; Known_Files : File_Lists.Map; Known_Dirs : File_Lists.Map; Unknown_Files : File_Lists.Map; begin The_Runfile := Load_Runfile; Known_Files := Get_File_List (The_Runfile); Known_Dirs := Get_Dir_List (Known_Files); for F in Known_Dirs.Iterate loop Find_Unused (From => Key (F), Not_In => Known_Files, Put_In => Unknown_Files); end loop; if Settings.Long_Listing_Format then for F in Unknown_Files.Iterate loop IO.Put_Line (+Key (F)); end loop; else for F in Unknown_Files.Iterate loop IO.Put_Line (Shorten (+Key (F))); end loop; end if; end; when Whatsnew => declare use Runfiles; The_Runfile : Runfile; Updated_List : Assertions.Condition_Lists.List; begin The_Runfile := Load_Runfile; Update_Files_Status (The_Runfile.Run_List, Updated_List); Put_Updated (Updated_List); end; when Clean => Runfiles.Delete_Targets (Runfiles.Load_Runfile); when Reset => Runfiles.Clean_Run_Files; when Version => IO.Put_Line (Settings.Smk_Version); when Build => Build; when Add => Smkfiles.Add_To_Smkfile (Command_Line); when Dump => Runfiles.Dump (Runfiles.Load_Runfile); when Run => Smkfiles.Add_To_Smkfile (Command_Line); Build; when Help => Put_Help; when None => Put_Error ("Internal error : exiting Analyze_Cmd_Line without Command"); end case; if IO.Some_Error and not Ignore_Errors then Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); end if; end Smk.Main;
-- Copyright (c) 2020 Maxim Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- with Ada.Text_IO; package body Torrent.Logs is Output : Ada.Text_IO.File_Type; ---------------- -- Initialize -- ---------------- procedure Initialize (Output : League.Strings.Universal_String) is begin Ada.Text_IO.Create (Torrent.Logs.Output, Name => Output.To_UTF_8_String); Enabled := True; end Initialize; ----------- -- Print -- ----------- procedure Print (Text : String) is begin Ada.Text_IO.Put_Line (Output, Text); end Print; end Torrent.Logs;
------------------------------------------------------------------------------ -- Copyright (c) 2015-2017, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Ada.Calendar; with Natools.S_Expressions.Atom_Refs; with Natools.S_Expressions.Caches; with Natools.S_Expressions.Conditionals.Strings; with Natools.S_Expressions.Lockable; with Natools.S_Expressions.Templates.Dates; with Natools.Static_Maps.Web.Fallback_Render; with Natools.Web.ACL; with Natools.Web.Comment_Cookies; with Natools.Web.Escapes; with Natools.Web.Filters.Stores; with Natools.Web.Tags; with Natools.Web.String_Tables; procedure Natools.Web.Fallback_Render (Exchange : in out Natools.Web.Sites.Exchange; Name : in Natools.S_Expressions.Atom; Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class; Context : in String := ""; Re_Enter : access procedure (Exchange : in out Natools.Web.Sites.Exchange; Expression : in out Natools.S_Expressions.Lockable.Descriptor'Class) := null; Elements : in Natools.Web.Containers.Expression_Maps.Constant_Map := Natools.Web.Containers.Expression_Maps.Empty_Constant_Map; Severity : in Severities.Code := Severities.Error) is package Commands renames Natools.Static_Maps.Web.Fallback_Render; use type S_Expressions.Events.Event; procedure Render_Then_Else (Condition : in Boolean); procedure Render_Ref (Ref : in S_Expressions.Atom_Refs.Immutable_Reference); procedure Report_Unknown_Command; procedure Render_Then_Else (Condition : in Boolean) is Lock : S_Expressions.Lockable.Lock_State; Event : S_Expressions.Events.Event; begin Arguments.Next (Event); case Event is when S_Expressions.Events.Add_Atom => if Condition then Exchange.Append (Arguments.Current_Atom); end if; when S_Expressions.Events.Open_List => if Condition then Arguments.Lock (Lock); begin Arguments.Next; Re_Enter (Exchange, Arguments); Arguments.Unlock (Lock); exception when others => Arguments.Unlock (Lock, False); raise; end; else Arguments.Close_Current_List; end if; when S_Expressions.Events.Close_List | S_Expressions.Events.End_Of_Input | S_Expressions.Events.Error => return; end case; if Condition then return; end if; Arguments.Next (Event); case Event is when S_Expressions.Events.Add_Atom => Exchange.Append (Arguments.Current_Atom); when S_Expressions.Events.Open_List => Arguments.Lock (Lock); begin Arguments.Next; Re_Enter (Exchange, Arguments); Arguments.Unlock (Lock); exception when others => Arguments.Unlock (Lock, False); raise; end; when S_Expressions.Events.Close_List | S_Expressions.Events.End_Of_Input | S_Expressions.Events.Error => return; end case; end Render_Then_Else; procedure Render_Ref (Ref : in S_Expressions.Atom_Refs.Immutable_Reference) is begin if not Ref.Is_Empty then Escapes.Write (Exchange, S_Expressions.To_String (Ref.Query), Escapes.HTML_Attribute); elsif Re_Enter /= null then Re_Enter (Exchange, Arguments); end if; end Render_Ref; procedure Report_Unknown_Command is begin if Context /= "" then Log (Severity, "Unknown render command """ & S_Expressions.To_String (Name) & """ in " & Context); end if; end Report_Unknown_Command; begin case Commands.To_Command (S_Expressions.To_String (Name)) is when Commands.Unknown => Report_Unknown_Command; when Commands.Current_Time => S_Expressions.Templates.Dates.Render (Exchange, Arguments, Ada.Calendar.Clock); when Commands.Cookies => String_Tables.Render (Exchange, String_Tables.Create (Exchange.Cookie_Table), Arguments); when Commands.Comment_Cookie_Filter => Render_Ref (Comment_Cookies.Filter (Sites.Comment_Info (Exchange))); when Commands.Comment_Cookie_Link => Render_Ref (Comment_Cookies.Link (Sites.Comment_Info (Exchange))); when Commands.Comment_Cookie_Mail => Render_Ref (Comment_Cookies.Mail (Sites.Comment_Info (Exchange))); when Commands.Comment_Cookie_Name => Render_Ref (Comment_Cookies.Name (Sites.Comment_Info (Exchange))); when Commands.Element => if Re_Enter = null then Report_Unknown_Command; else declare Template : S_Expressions.Caches.Cursor := Exchange.Site.Get_Template (Elements, Arguments, Lookup_Template => False); begin Re_Enter (Exchange, Template); end; end if; when Commands.Element_Or_Template => if Re_Enter = null then Report_Unknown_Command; else declare Template : S_Expressions.Caches.Cursor := Exchange.Site.Get_Template (Elements, Arguments); begin Re_Enter (Exchange, Template); end; end if; when Commands.Filter => if Re_Enter = null then Report_Unknown_Command; elsif Arguments.Current_Event = S_Expressions.Events.Add_Atom then begin declare Filter : Filters.Filter'Class := Exchange.Site.Get_Filter (Arguments.Current_Atom); begin Arguments.Next; Exchange.Insert_Filter (Filter); Re_Enter (Exchange, Arguments); Exchange.Remove_Filter (Filter); end; exception when Filters.Stores.No_Filter => null; end; end if; when Commands.If_Comment_Cookie_Filter_Is => if Re_Enter = null then Report_Unknown_Command; elsif Arguments.Current_Event = S_Expressions.Events.Add_Atom then declare use type S_Expressions.Atom; Ref : constant S_Expressions.Atom_Refs.Immutable_Reference := Comment_Cookies.Filter (Sites.Comment_Info (Exchange)); begin if not Ref.Is_Empty and then Ref.Query = Arguments.Current_Atom then Arguments.Next; Re_Enter (Exchange, Arguments); end if; end; end if; when Commands.If_Has_Element => if Re_Enter = null then Report_Unknown_Command; elsif Arguments.Current_Event = S_Expressions.Events.Add_Atom and then Elements.Contains (Arguments.Current_Atom) then Arguments.Next; Re_Enter (Exchange, Arguments); end if; when Commands.If_Has_Not_Element => if Re_Enter = null then Report_Unknown_Command; elsif Arguments.Current_Event = S_Expressions.Events.Add_Atom and then not Elements.Contains (Arguments.Current_Atom) then Arguments.Next; Re_Enter (Exchange, Arguments); end if; when Commands.If_Has_Parameter_Else => if Re_Enter = null then Report_Unknown_Command; elsif Arguments.Current_Event = S_Expressions.Events.Add_Atom then Render_Then_Else (Exchange.Has_Parameter (S_Expressions.To_String (Arguments.Current_Atom))); end if; when Commands.If_Header_Else => if Re_Enter = null then Report_Unknown_Command; elsif Arguments.Current_Event = S_Expressions.Events.Open_List then declare Lock : S_Expressions.Lockable.Lock_State; Event : S_Expressions.Events.Event; Condition : Boolean; begin Arguments.Next (Event); if Event /= S_Expressions.Events.Add_Atom then return; end if; Arguments.Lock (Lock); Evaluate_Condition : declare Value : constant String := Exchange.Header (S_Expressions.To_String (Arguments.Current_Atom)); begin Arguments.Next; Condition := S_Expressions.Conditionals.Strings.Evaluate (Value, Arguments); Arguments.Unlock (Lock); exception when others => Arguments.Unlock (Lock, False); raise; end Evaluate_Condition; Render_Then_Else (Condition); end; end if; when Commands.If_Parameter_Is => if Re_Enter = null then Report_Unknown_Command; elsif Arguments.Current_Event = S_Expressions.Events.Add_Atom then declare Param_Value : constant String := Exchange.Parameter (S_Expressions.To_String (Arguments.Current_Atom)); Event : S_Expressions.Events.Event; begin Arguments.Next (Event); if Event = S_Expressions.Events.Add_Atom and then Param_Value = S_Expressions.To_String (Arguments.Current_Atom) then Arguments.Next; Re_Enter (Exchange, Arguments); end if; end; end if; when Commands.Load_Date => S_Expressions.Templates.Dates.Render (Exchange, Arguments, Exchange.Site.Load_Date); when Commands.Optional_Tags => Tags.Render (Exchange, Exchange.Site.Get_Tags, Arguments, Optional => True); when Commands.Parameter => if Arguments.Current_Event = S_Expressions.Events.Add_Atom then declare Parameter_Name : constant String := S_Expressions.To_String (Arguments.Current_Atom); begin if Exchange.Has_Parameter (Parameter_Name) then Escapes.Write (Exchange, Exchange.Parameter (Parameter_Name), Escapes.HTML_Attribute); elsif Re_Enter /= null then Arguments.Next; Re_Enter (Exchange, Arguments); end if; end; end if; when Commands.Set_MIME_Type => if Arguments.Current_Event = S_Expressions.Events.Add_Atom then Exchange.Set_MIME_Type (Arguments.Current_Atom); end if; when Commands.Tags => Tags.Render (Exchange, Exchange.Site.Get_Tags, Arguments); when Commands.Template => if Re_Enter = null then Report_Unknown_Command; else declare Template : S_Expressions.Caches.Cursor := Exchange.Site.Get_Template (Elements, Arguments, Lookup_Element => False); begin Re_Enter (Exchange, Template); end; end if; when Commands.User => if Re_Enter = null then Report_Unknown_Command; else declare Match : Boolean := False; begin ACL.Match (Sites.Identity (Exchange), Arguments, Match); if Match then Arguments.Next; Re_Enter (Exchange, Arguments); end if; end; end if; end case; end Natools.Web.Fallback_Render;
package body Benchmark.Matrix.LU is function Create_LU return Benchmark_Pointer is begin return new LU_Type; end Create_LU; procedure Run(benchmark : in LU_Type) is addr : constant Address_Type := 0; begin for k in 0 .. benchmark.size - 1 loop for j in k + 1 .. benchmark.size - 1 loop Read(benchmark, addr, k, j); Read(benchmark, addr, k, k); Write(benchmark, addr, k, j); end loop; for i in k + 1 .. benchmark.size - 1 loop for j in k + 1 .. benchmark.size - 1 loop Read(benchmark, addr, i, j); Read(benchmark, addr, i, k); Read(benchmark, addr, k, j); Write(benchmark, addr, i, j); end loop; end loop; end loop; end Run; end Benchmark.Matrix.LU;
with Ada.Containers; with Ada.Containers.Functional_Vectors; with TLSF.Block.Types; with TLSF.Config; use TLSF.Config; package TLSF.Proof.Model.Block with SPARK_Mode, Ghost is package BT renames TLSF.Block.Types; type Block is record Address : BT.Aligned_Address; Prev_Block_Address : BT.Aligned_Address := BT.Address_Null; Size : BT.Aligned_Size; end record with Predicate => Size >= BT.Quantum and Address >= BT.Quantum and (Prev_Block_Address = BT.Address_Null or (Prev_Block_Address >= BT.Quantum and Prev_Block_Address < Address)); use type BT.Aligned_Address; use type BT.Aligned_Size; use Ada.Containers; subtype Index_Type is Positive; package FV_Pkg is new Ada.Containers.Functional_Vectors (Index_Type => Index_Type, Element_Type => Block); use FV_Pkg; use type BT.Address_Space; subtype Address_Space is BT.Address_Space; -- Address space of model is First_Address .. Last_Address - 1, -- ie Last_Address is the first one that is out of address space type Formal_Model is record Blocks : FV_Pkg.Sequence; Mem_Region : Address_Space; end record; function Valid_Block (AS: Address_Space; B: Block) return Boolean is (B.Address in AS.First..AS.Last and then Integer(B.Address) + Integer(B.Size) in 0..Integer(BT.Address'Last) and then B.Address + B.Size in AS.First .. AS.Last and then (B.Prev_Block_Address = BT.Address_Null or else B.Prev_Block_Address in AS.First .. AS.Last)) with Post => (if Valid_Block'Result = True then B.Address in AS.First..AS.Last and B.Address + B.Size in AS.First .. AS.Last and (B.Prev_Block_Address = BT.Address_Null or B.Prev_Block_Address in AS.First .. AS.Last)); pragma Annotate (GNATprove, Inline_For_Proof, Valid_Block); function Next_Block_Address (B: Block) return BT.Aligned_Address is (B.Address + B.Size) with Pre => Integer(B.Address) + Integer(B.Size) in 0..Integer(BT.Address'Last); pragma Annotate (GNATprove, Inline_For_Proof, Next_Block_Address); function Neighbor_Blocks (B_Left, B_Right: Block) return Boolean is (Next_Block_Address (B_Left) = B_Right.Address and B_Right.Prev_Block_Address = B_Left.Address) with Pre => Integer (B_Left.Address) + Integer (B_Left.Size) in 0 .. Integer (BT.Address'Last); pragma Annotate (GNATprove, Inline_For_Proof, Neighbor_Blocks); -- excessive, but for clarity function Blocks_Addresses_Are_In_Ascending_Order(Bs : FV_Pkg.Sequence; From : Index_Type; To : Extended_Index) return Boolean is (if To >= 1 then (for all Idx in From..To-1 => Get(Bs,Idx).Address < Get(Bs, Idx+1).Address)) with Pre => To <= Last(Bs); pragma Annotate (GNATprove, Inline_For_Proof, Blocks_Addresses_Are_In_Ascending_Order); function All_Blocks_Are_Valid (AS : Address_Space; BS : FV_Pkg.Sequence; From : Index_Type; To : Extended_Index) return Boolean is (for all Idx in From..To => Valid_Block (AS, Get(BS, Idx))) with Pre => To <= Last(BS); pragma Annotate (GNATprove, Inline_For_Proof, All_Blocks_Are_Valid); function Boundary_Blocks_Coverage_Is_Correct(AS: Address_Space; BS : FV_Pkg.Sequence) return Boolean is (if Last(BS) >=1 then (Get (BS, 1).Address = AS.First and Get (BS, 1).Prev_Block_Address = BT.Address_Null and Next_Block_Address(Get(BS, Last(BS))) = AS.Last)) with Pre => All_Blocks_Are_Valid(AS, BS, 1, Last(BS)); function Coverage_Is_Continuous (AS : Address_Space; BS : FV_Pkg.Sequence; From : Index_Type; To : Extended_Index) return Boolean is (if To >= 1 then (for all Idx in From .. To-1 => Neighbor_Blocks(Get(BS, Idx), Get(BS, Idx+1)))) with Pre => To <= Last(BS) and then All_Blocks_Are_Valid(AS, BS, From, To); pragma Annotate (GNATprove, Inline_For_Proof, Coverage_Is_Continuous); function Blocks_Overlap (AS: Address_Space; B1, B2: Block) return Boolean is (B1.Address in B2.Address..(B2.Address + B2.Size - 1) or B1.Address + B1.Size -1 in B2.Address..(B2.Address + B2.Size - 1) or B2.Address in B1.Address..(B1.Address + B1.Size - 1) or B2.Address + B2.Size -1 in B1.Address..(B1.Address + B1.Size - 1)) with Pre => Valid_Block(AS, B1) and Valid_Block(AS, B2); pragma Annotate (GNATprove, Inline_For_Proof, Blocks_Overlap); function Blocks_Do_Not_Overlap (AS : Address_Space; BS : FV_Pkg.Sequence; From : Index_Type; To : Extended_Index) return Boolean is (for all Idx1 in From..To => (for all Idx2 in From..To => (if Idx1 /= Idx2 then not Blocks_Overlap(AS, Get(BS, Idx1), Get(BS, Idx2))))) with Pre => To <= Last(BS) and then All_Blocks_Are_Valid(AS, BS, From, To); pragma Annotate (GNATprove, Inline_For_Proof, Blocks_Do_Not_Overlap); function All_Block_Are_Uniq (AS : Address_Space; BS : FV_Pkg.Sequence; From : Index_Type; To : Extended_Index) return Boolean is (for all Idx1 in From..To => (for all Idx2 in From..To => (if Get (BS, Idx1) = Get (BS, Idx2) then Idx1 = Idx2))) with Pre => To <= Last(BS) and then All_Blocks_Are_Valid(AS, BS, From, To); pragma Annotate (GNATprove, Inline_For_Proof, All_Block_Are_Uniq); function All_Block_Addresses_Are_Uniq (AS : Address_Space; BS : FV_Pkg.Sequence; From : Index_Type; To : Extended_Index) return Boolean is (for all Idx1 in From..To => (for all Idx2 in From..To => (if Get (BS, Idx1).Address = Get (BS, Idx2).Address then Idx1 = Idx2))) with Pre => To <= Last(BS) and then All_Blocks_Are_Valid(AS, BS, From, To); pragma Annotate (GNATprove, Inline_For_Proof, All_Block_Addresses_Are_Uniq); function Partial_Valid(AS: Address_Space; BS: FV_Pkg.Sequence; From : Index_Type; To : Extended_Index) return Boolean is (All_Blocks_Are_Valid(AS, BS, From, To) and then Blocks_Addresses_Are_In_Ascending_Order(BS, From, To) and then Coverage_Is_Continuous(AS, BS, From, To) and then Blocks_Do_Not_Overlap(AS, BS, From, To) and then All_Block_Are_Uniq (AS, BS, From, To) and then All_Block_Addresses_Are_Uniq (AS, BS, From, To)) with Global => null, Depends => (Partial_Valid'Result => (AS, BS, From, To)), Pre => To <= Last(BS), Pure_Function; function Valid(M : Formal_Model) return Boolean is (Partial_Valid(M.Mem_Region, M.Blocks, 1, Last(M.Blocks)) and then Boundary_Blocks_Coverage_Is_Correct(M.Mem_Region, M.Blocks)) with Global => null, Depends => (Valid'Result => M), Pure_Function; procedure Equality_Preserves_Validity (Old_M, New_M : Formal_Model) with Global => null, Pre => Valid (Old_M) and Old_M = New_M, Post => Valid (New_M); function Address_In_Model (M : Formal_Model; Addr : BT.Aligned_Address) return Boolean is (for some Idx in 1 .. Last (M.Blocks) => Get (M.Blocks, Idx).Address = Addr) with Global => null, Pure_Function, Pre => Valid (M); function In_Model (M : Formal_Model; B : Block) return Boolean is (Contains (M.Blocks, 1, Last (M.Blocks), B)) with Global => null, Pure_Function, Pre => Valid (M), Post => (if In_Model'Result then Address_In_Model (M, B.Address)); procedure Addresses_Equality_Implies_Blocks_Equality (M : Formal_Model) with Global => null, Pre => Valid (M), Post => (for all I in 1 .. Last (M.Blocks) => In_Model (M, Get (M.Blocks, I))) and then (for all I in 1 .. Last (M.Blocks) => (for all J in 1 .. Last (M.Blocks) => (if Get (M.Blocks, I).Address = Get (M.Blocks, J).Address then I = J and then Get (M.Blocks, I) = Get (M.Blocks, J)))); procedure Addresses_Equality_Implies_Blocks_Equality (M : Formal_Model; Left, Right : Block) with Global => null, Pre => Valid (M) and then In_Model (M, Left) and then In_Model (M, Right), Post => (if Left.Address = Right.Address then Left = Right); function Is_First_Block(M: Formal_Model; B: Block) return Boolean with Global => null, Pure_Function, Pre => Valid (M) and then In_Model (M, B), Post => (if B.Address = M.Mem_Region.First then B = Get (M.Blocks, 1) and Is_First_Block'Result = True else Is_First_Block'Result = False); function Is_Last_Block(M: Formal_Model; B: Block) return Boolean with Global => null, Pure_Function, Pre => Valid (M) and then In_Model (M, B), Post => (if Next_Block_Address (B) = M.Mem_Region.Last then B = Get (M.Blocks, Last (M.Blocks)) and Is_Last_Block'Result = True else Is_Last_Block'Result = False); function Get_Prev(M: Formal_Model; B: Block) return Block with Global => null, Pure_Function, Pre => Valid (M) and then In_Model (M, B) and then not Is_First_Block (M, B), Post => Valid_Block (M.Mem_Region, Get_Prev'Result) and In_Model (M, Get_Prev'Result) and Neighbor_Blocks (Get_Prev'Result, B); function Get_Next(M: Formal_Model; B: Block) return Block with Global => null, Pure_Function, Pre => Valid (M) and then In_Model (M, B) and then not Is_Last_Block (M, B), Post => Valid_Block(M.Mem_Region, Get_Next'Result) and In_Model (M, Get_Next'Result) and Neighbor_Blocks(B, Get_Next'Result); procedure Equality_Preserves_Block_Relations (Left_M, Right_M : Formal_Model; B : Block) with Global => null, Pre => Valid (Left_M) and then Left_M = Right_M and then In_Model (Left_M, B), Post => Valid (Right_M) and then In_Model (Right_M, B) and then Is_Last_Block (Left_M, B) = Is_Last_Block (Right_M, B) and then Is_First_Block (Left_M, B) = Is_First_Block (Right_M, B) and then (if not Is_Last_Block (Left_M, B) then Get_Next (Left_M, B) = Get_Next (Right_M, B)) and then (if not Is_First_Block (Left_M, B) then Get_Prev (Left_M, B) = Get_Prev (Right_M, B)); function Initial_Block (Space : Address_Space) return Block with Post => Valid_Block (Space, Initial_Block'Result) and then Initial_Block'Result.Address = Space.First and then Next_Block_Address (Initial_Block'Result) = Space.Last and then Initial_Block'Result.Prev_Block_Address = BT.Address_Null; function Init_Model(Space : Address_Space) return Formal_Model with Post => Length(Init_Model'Result.Blocks) = 1 and then Init_Model'Result.Mem_Region = Space and then Get (Init_Model'Result.Blocks, 1).Address = Init_Model'Result.Mem_Region.First and then Next_Block_Address (Get (Init_Model'Result.Blocks, 1)) = Init_Model'Result.Mem_Region.Last and then Get (Init_Model'Result.Blocks, 1) = Initial_Block (Space) and then Valid (Init_Model'Result) and then In_Model (Init_Model'Result, Initial_Block (Space)) and then Is_Last_Block (Init_Model'Result, Initial_Block (Space)) and then Is_First_Block (Init_Model'Result, Initial_Block (Space)); procedure Split_Block (M : Formal_Model; B : Block; L_Size, R_Size : BT.Aligned_Size; B_Left, B_Right : out Block; New_M : out Formal_Model) with Global => null, Depends => (New_M => (M, B, L_Size, R_Size), B_Left => (B, L_Size), B_Right => (B, L_Size, R_Size)), Pre => (Valid (M) and then In_Model (M, B)) and L_Size >= Small_Block_Size and R_Size >= Small_Block_Size and B.SIze = L_Size + R_Size, Post => (Valid (New_M) and not In_Model (New_M, B) and In_Model (New_M, B_Left) and In_Model (New_M, B_Right) and B_Left.Address = B.Address and B_Left.Size = L_Size and B_Left.Prev_Block_Address = B.Prev_Block_Address and B_Right.Address = B.Address + L_Size and B_Right.Size = R_Size and Neighbor_Blocks (B_Left, B_Right) and Is_First_Block (M, B) = Is_First_Block (New_M, B_Left) and Is_Last_Block (M, B) = Is_Last_Block (New_M, B_Right)) and then (if not Is_First_Block (M, B) then Get_Prev (M, B) = Get_Prev (New_M, B_Left)) and then (if not Is_Last_Block (M, B) then Get_Next (M, B).Address = Get_Next (New_M, B_Right).Address and then Get_Next (M, B).Size = Get_Next (New_M, B_Right).Size and then Get_Next (New_M, B_Right).Prev_Block_Address = B_Right.Address and then In_Model (New_M, Get_Next (New_M, B_Right))); procedure Join (M : Formal_Model; Left, Right : Block; B : out Block; New_M : out Formal_Model) with Global => null, Depends => (New_M => (M, Left, Right), B => (Left, Right)), Pre => Valid (M) and then In_Model (M, Left) and then In_Model (M, Right) and then Neighbor_Blocks (Left, Right), Post => Valid (New_M) and then In_Model (New_M, B) and then not In_Model (New_M, Left) and then not In_Model (New_M, Right) and then B.Size = Left.Size + Right.Size and then B.Address = Left.Address and then Is_First_Block (M, Left) = Is_First_Block (New_M, B) and then Is_Last_Block (M, Right) = Is_Last_Block (New_M, B) and then B.Prev_Block_Address = Left.Prev_Block_Address and then (if not Is_First_Block (M, Left) then Get_Prev (M, Left) = Get_Prev (New_M, B)) and then (if not Is_Last_Block (M, Right) then Get_Next (M, Right).Address = Get_Next (New_M, B).Address and then Get_Next (M, Right).Size = Get_Next (New_M, B).Size and then Get_Next (New_M, B).Prev_Block_Address = B.Address); end TLSF.Proof.Model.Block;
-- CLI AURA Configuration Manifest package CLI.AURA is package Build is package Ada is package Compiler_Options is Ignore_Unknown_Pragmas: constant String := "-gnatwG"; -- Disable warnings from GNAT for the use of pragma External_With end Compiler_Options; end Ada; end Build; end CLI.AURA;
------------------------------------------------------------------------------ -- Copyright (c) 2006-2013, Maxim Reznik -- 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 Maxim Reznik, 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 OWNER OR CONTRIBUTORS BE -- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -- POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ package Asis.Gela.Elements.Defs is -------------------------- -- Type_Definition_Node -- -------------------------- type Type_Definition_Node is abstract new Definition_Node with private; type Type_Definition_Ptr is access all Type_Definition_Node; for Type_Definition_Ptr'Storage_Pool use Lists.Pool; function Corresponding_Type_Operators (Element : Type_Definition_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Add_To_Corresponding_Type_Operators (Element : in out Type_Definition_Node; Item : in Asis.Element); function Definition_Kind (Element : Type_Definition_Node) return Asis.Definition_Kinds; ----------------------------- -- Subtype_Indication_Node -- ----------------------------- type Subtype_Indication_Node is new Definition_Node with private; type Subtype_Indication_Ptr is access all Subtype_Indication_Node; for Subtype_Indication_Ptr'Storage_Pool use Lists.Pool; function New_Subtype_Indication_Node (The_Context : ASIS.Context) return Subtype_Indication_Ptr; function Get_Subtype_Mark (Element : Subtype_Indication_Node) return Asis.Expression; procedure Set_Subtype_Mark (Element : in out Subtype_Indication_Node; Value : in Asis.Expression); function Subtype_Constraint (Element : Subtype_Indication_Node) return Asis.Constraint; procedure Set_Subtype_Constraint (Element : in out Subtype_Indication_Node; Value : in Asis.Constraint); function Has_Null_Exclusion (Element : Subtype_Indication_Node) return Boolean; procedure Set_Has_Null_Exclusion (Element : in out Subtype_Indication_Node; Value : in Boolean); function Definition_Kind (Element : Subtype_Indication_Node) return Asis.Definition_Kinds; function Children (Element : access Subtype_Indication_Node) return Traverse_List; function Clone (Element : Subtype_Indication_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Subtype_Indication_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); --------------------- -- Constraint_Node -- --------------------- type Constraint_Node is abstract new Definition_Node with private; type Constraint_Ptr is access all Constraint_Node; for Constraint_Ptr'Storage_Pool use Lists.Pool; function Definition_Kind (Element : Constraint_Node) return Asis.Definition_Kinds; ------------------------------- -- Component_Definition_Node -- ------------------------------- type Component_Definition_Node is new Definition_Node with private; type Component_Definition_Ptr is access all Component_Definition_Node; for Component_Definition_Ptr'Storage_Pool use Lists.Pool; function New_Component_Definition_Node (The_Context : ASIS.Context) return Component_Definition_Ptr; function Component_Subtype_Indication (Element : Component_Definition_Node) return Asis.Subtype_Indication; procedure Set_Component_Subtype_Indication (Element : in out Component_Definition_Node; Value : in Asis.Subtype_Indication); function Trait_Kind (Element : Component_Definition_Node) return Asis.Trait_Kinds; procedure Set_Trait_Kind (Element : in out Component_Definition_Node; Value : in Asis.Trait_Kinds); function Definition_Kind (Element : Component_Definition_Node) return Asis.Definition_Kinds; function Children (Element : access Component_Definition_Node) return Traverse_List; function Clone (Element : Component_Definition_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Component_Definition_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); -------------------------------------- -- Discrete_Subtype_Definition_Node -- -------------------------------------- type Discrete_Subtype_Definition_Node is abstract new Definition_Node with private; type Discrete_Subtype_Definition_Ptr is access all Discrete_Subtype_Definition_Node; for Discrete_Subtype_Definition_Ptr'Storage_Pool use Lists.Pool; function Definition_Kind (Element : Discrete_Subtype_Definition_Node) return Asis.Definition_Kinds; ------------------------- -- Discrete_Range_Node -- ------------------------- type Discrete_Range_Node is abstract new Definition_Node with private; type Discrete_Range_Ptr is access all Discrete_Range_Node; for Discrete_Range_Ptr'Storage_Pool use Lists.Pool; function Definition_Kind (Element : Discrete_Range_Node) return Asis.Definition_Kinds; ------------------------------------ -- Unknown_Discriminant_Part_Node -- ------------------------------------ type Unknown_Discriminant_Part_Node is new Definition_Node with private; type Unknown_Discriminant_Part_Ptr is access all Unknown_Discriminant_Part_Node; for Unknown_Discriminant_Part_Ptr'Storage_Pool use Lists.Pool; function New_Unknown_Discriminant_Part_Node (The_Context : ASIS.Context) return Unknown_Discriminant_Part_Ptr; function Definition_Kind (Element : Unknown_Discriminant_Part_Node) return Asis.Definition_Kinds; function Clone (Element : Unknown_Discriminant_Part_Node; Parent : Asis.Element) return Asis.Element; ---------------------------------- -- Known_Discriminant_Part_Node -- ---------------------------------- type Known_Discriminant_Part_Node is new Definition_Node with private; type Known_Discriminant_Part_Ptr is access all Known_Discriminant_Part_Node; for Known_Discriminant_Part_Ptr'Storage_Pool use Lists.Pool; function New_Known_Discriminant_Part_Node (The_Context : ASIS.Context) return Known_Discriminant_Part_Ptr; function Discriminants (Element : Known_Discriminant_Part_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Set_Discriminants (Element : in out Known_Discriminant_Part_Node; Value : in Asis.Element); function Discriminants_List (Element : Known_Discriminant_Part_Node) return Asis.Element; function Definition_Kind (Element : Known_Discriminant_Part_Node) return Asis.Definition_Kinds; function Children (Element : access Known_Discriminant_Part_Node) return Traverse_List; function Clone (Element : Known_Discriminant_Part_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Known_Discriminant_Part_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); ---------------------------- -- Record_Definition_Node -- ---------------------------- type Record_Definition_Node is new Definition_Node with private; type Record_Definition_Ptr is access all Record_Definition_Node; for Record_Definition_Ptr'Storage_Pool use Lists.Pool; function New_Record_Definition_Node (The_Context : ASIS.Context) return Record_Definition_Ptr; function Record_Components (Element : Record_Definition_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Set_Record_Components (Element : in out Record_Definition_Node; Value : in Asis.Element); function Record_Components_List (Element : Record_Definition_Node) return Asis.Element; function Implicit_Components (Element : Record_Definition_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Add_To_Implicit_Components (Element : in out Record_Definition_Node; Item : in Asis.Element); function Definition_Kind (Element : Record_Definition_Node) return Asis.Definition_Kinds; function Children (Element : access Record_Definition_Node) return Traverse_List; function Clone (Element : Record_Definition_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Record_Definition_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); --------------------------------- -- Null_Record_Definition_Node -- --------------------------------- type Null_Record_Definition_Node is new Definition_Node with private; type Null_Record_Definition_Ptr is access all Null_Record_Definition_Node; for Null_Record_Definition_Ptr'Storage_Pool use Lists.Pool; function New_Null_Record_Definition_Node (The_Context : ASIS.Context) return Null_Record_Definition_Ptr; function Definition_Kind (Element : Null_Record_Definition_Node) return Asis.Definition_Kinds; function Clone (Element : Null_Record_Definition_Node; Parent : Asis.Element) return Asis.Element; ------------------------- -- Null_Component_Node -- ------------------------- type Null_Component_Node is new Definition_Node with private; type Null_Component_Ptr is access all Null_Component_Node; for Null_Component_Ptr'Storage_Pool use Lists.Pool; function New_Null_Component_Node (The_Context : ASIS.Context) return Null_Component_Ptr; function Pragmas (Element : Null_Component_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Set_Pragmas (Element : in out Null_Component_Node; Value : in Asis.Element); function Pragmas_List (Element : Null_Component_Node) return Asis.Element; function Definition_Kind (Element : Null_Component_Node) return Asis.Definition_Kinds; function Clone (Element : Null_Component_Node; Parent : Asis.Element) return Asis.Element; ----------------------- -- Variant_Part_Node -- ----------------------- type Variant_Part_Node is new Definition_Node with private; type Variant_Part_Ptr is access all Variant_Part_Node; for Variant_Part_Ptr'Storage_Pool use Lists.Pool; function New_Variant_Part_Node (The_Context : ASIS.Context) return Variant_Part_Ptr; function Discriminant_Direct_Name (Element : Variant_Part_Node) return Asis.Name; procedure Set_Discriminant_Direct_Name (Element : in out Variant_Part_Node; Value : in Asis.Name); function Variants (Element : Variant_Part_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Set_Variants (Element : in out Variant_Part_Node; Value : in Asis.Element); function Variants_List (Element : Variant_Part_Node) return Asis.Element; function Pragmas (Element : Variant_Part_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Set_Pragmas (Element : in out Variant_Part_Node; Value : in Asis.Element); function Pragmas_List (Element : Variant_Part_Node) return Asis.Element; function End_Pragmas (Element : Variant_Part_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Set_End_Pragmas (Element : in out Variant_Part_Node; Value : in Asis.Element); function End_Pragmas_List (Element : Variant_Part_Node) return Asis.Element; function Definition_Kind (Element : Variant_Part_Node) return Asis.Definition_Kinds; function Children (Element : access Variant_Part_Node) return Traverse_List; function Clone (Element : Variant_Part_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Variant_Part_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); ------------------ -- Variant_Node -- ------------------ type Variant_Node is new Definition_Node with private; type Variant_Ptr is access all Variant_Node; for Variant_Ptr'Storage_Pool use Lists.Pool; function New_Variant_Node (The_Context : ASIS.Context) return Variant_Ptr; function Record_Components (Element : Variant_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Set_Record_Components (Element : in out Variant_Node; Value : in Asis.Element); function Record_Components_List (Element : Variant_Node) return Asis.Element; function Implicit_Components (Element : Variant_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Add_To_Implicit_Components (Element : in out Variant_Node; Item : in Asis.Element); function Variant_Choices (Element : Variant_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Set_Variant_Choices (Element : in out Variant_Node; Value : in Asis.Element); function Variant_Choices_List (Element : Variant_Node) return Asis.Element; function Definition_Kind (Element : Variant_Node) return Asis.Definition_Kinds; function Children (Element : access Variant_Node) return Traverse_List; function Clone (Element : Variant_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Variant_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); ------------------------ -- Others_Choice_Node -- ------------------------ type Others_Choice_Node is new Definition_Node with private; type Others_Choice_Ptr is access all Others_Choice_Node; for Others_Choice_Ptr'Storage_Pool use Lists.Pool; function New_Others_Choice_Node (The_Context : ASIS.Context) return Others_Choice_Ptr; function Definition_Kind (Element : Others_Choice_Node) return Asis.Definition_Kinds; function Clone (Element : Others_Choice_Node; Parent : Asis.Element) return Asis.Element; ---------------------------- -- Access_Definition_Node -- ---------------------------- type Access_Definition_Node is abstract new Definition_Node with private; type Access_Definition_Ptr is access all Access_Definition_Node; for Access_Definition_Ptr'Storage_Pool use Lists.Pool; function Has_Null_Exclusion (Element : Access_Definition_Node) return Boolean; procedure Set_Has_Null_Exclusion (Element : in out Access_Definition_Node; Value : in Boolean); function Definition_Kind (Element : Access_Definition_Node) return Asis.Definition_Kinds; ------------------------------------- -- Incomplete_Type_Definition_Node -- ------------------------------------- type Incomplete_Type_Definition_Node is new Definition_Node with private; type Incomplete_Type_Definition_Ptr is access all Incomplete_Type_Definition_Node; for Incomplete_Type_Definition_Ptr'Storage_Pool use Lists.Pool; function New_Incomplete_Type_Definition_Node (The_Context : ASIS.Context) return Incomplete_Type_Definition_Ptr; function Definition_Kind (Element : Incomplete_Type_Definition_Node) return Asis.Definition_Kinds; function Clone (Element : Incomplete_Type_Definition_Node; Parent : Asis.Element) return Asis.Element; -------------------------------------------- -- Tagged_Incomplete_Type_Definition_Node -- -------------------------------------------- type Tagged_Incomplete_Type_Definition_Node is new Incomplete_Type_Definition_Node with private; type Tagged_Incomplete_Type_Definition_Ptr is access all Tagged_Incomplete_Type_Definition_Node; for Tagged_Incomplete_Type_Definition_Ptr'Storage_Pool use Lists.Pool; function New_Tagged_Incomplete_Type_Definition_Node (The_Context : ASIS.Context) return Tagged_Incomplete_Type_Definition_Ptr; function Has_Tagged (Element : Tagged_Incomplete_Type_Definition_Node) return Boolean; procedure Set_Has_Tagged (Element : in out Tagged_Incomplete_Type_Definition_Node; Value : in Boolean); function Definition_Kind (Element : Tagged_Incomplete_Type_Definition_Node) return Asis.Definition_Kinds; function Clone (Element : Tagged_Incomplete_Type_Definition_Node; Parent : Asis.Element) return Asis.Element; ---------------------------------- -- Private_Type_Definition_Node -- ---------------------------------- type Private_Type_Definition_Node is new Definition_Node with private; type Private_Type_Definition_Ptr is access all Private_Type_Definition_Node; for Private_Type_Definition_Ptr'Storage_Pool use Lists.Pool; function New_Private_Type_Definition_Node (The_Context : ASIS.Context) return Private_Type_Definition_Ptr; function Trait_Kind (Element : Private_Type_Definition_Node) return Asis.Trait_Kinds; procedure Set_Trait_Kind (Element : in out Private_Type_Definition_Node; Value : in Asis.Trait_Kinds); function Corresponding_Type_Operators (Element : Private_Type_Definition_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Add_To_Corresponding_Type_Operators (Element : in out Private_Type_Definition_Node; Item : in Asis.Element); function Has_Limited (Element : Private_Type_Definition_Node) return Boolean; procedure Set_Has_Limited (Element : in out Private_Type_Definition_Node; Value : in Boolean); function Has_Private (Element : Private_Type_Definition_Node) return Boolean; procedure Set_Has_Private (Element : in out Private_Type_Definition_Node; Value : in Boolean); function Definition_Kind (Element : Private_Type_Definition_Node) return Asis.Definition_Kinds; function Clone (Element : Private_Type_Definition_Node; Parent : Asis.Element) return Asis.Element; ----------------------------------------- -- Tagged_Private_Type_Definition_Node -- ----------------------------------------- type Tagged_Private_Type_Definition_Node is new Private_Type_Definition_Node with private; type Tagged_Private_Type_Definition_Ptr is access all Tagged_Private_Type_Definition_Node; for Tagged_Private_Type_Definition_Ptr'Storage_Pool use Lists.Pool; function New_Tagged_Private_Type_Definition_Node (The_Context : ASIS.Context) return Tagged_Private_Type_Definition_Ptr; function Has_Abstract (Element : Tagged_Private_Type_Definition_Node) return Boolean; procedure Set_Has_Abstract (Element : in out Tagged_Private_Type_Definition_Node; Value : in Boolean); function Has_Tagged (Element : Tagged_Private_Type_Definition_Node) return Boolean; procedure Set_Has_Tagged (Element : in out Tagged_Private_Type_Definition_Node; Value : in Boolean); function Definition_Kind (Element : Tagged_Private_Type_Definition_Node) return Asis.Definition_Kinds; function Clone (Element : Tagged_Private_Type_Definition_Node; Parent : Asis.Element) return Asis.Element; --------------------------------------- -- Private_Extension_Definition_Node -- --------------------------------------- type Private_Extension_Definition_Node is new Private_Type_Definition_Node with private; type Private_Extension_Definition_Ptr is access all Private_Extension_Definition_Node; for Private_Extension_Definition_Ptr'Storage_Pool use Lists.Pool; function New_Private_Extension_Definition_Node (The_Context : ASIS.Context) return Private_Extension_Definition_Ptr; function Ancestor_Subtype_Indication (Element : Private_Extension_Definition_Node) return Asis.Subtype_Indication; procedure Set_Ancestor_Subtype_Indication (Element : in out Private_Extension_Definition_Node; Value : in Asis.Subtype_Indication); function Implicit_Inherited_Declarations (Element : Private_Extension_Definition_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Add_To_Implicit_Inherited_Declarations (Element : in out Private_Extension_Definition_Node; Item : in Asis.Element); function Implicit_Inherited_Subprograms (Element : Private_Extension_Definition_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Add_To_Implicit_Inherited_Subprograms (Element : in out Private_Extension_Definition_Node; Item : in Asis.Element); function Has_Synchronized (Element : Private_Extension_Definition_Node) return Boolean; procedure Set_Has_Synchronized (Element : in out Private_Extension_Definition_Node; Value : in Boolean); function Has_Abstract (Element : Private_Extension_Definition_Node) return Boolean; procedure Set_Has_Abstract (Element : in out Private_Extension_Definition_Node; Value : in Boolean); function Definition_Kind (Element : Private_Extension_Definition_Node) return Asis.Definition_Kinds; function Children (Element : access Private_Extension_Definition_Node) return Traverse_List; function Clone (Element : Private_Extension_Definition_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Private_Extension_Definition_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); ------------------------------- -- Protected_Definition_Node -- ------------------------------- type Protected_Definition_Node is new Definition_Node with private; type Protected_Definition_Ptr is access all Protected_Definition_Node; for Protected_Definition_Ptr'Storage_Pool use Lists.Pool; function New_Protected_Definition_Node (The_Context : ASIS.Context) return Protected_Definition_Ptr; function Is_Private_Present (Element : Protected_Definition_Node) return Boolean; procedure Set_Is_Private_Present (Element : in out Protected_Definition_Node; Value : in Boolean); function Visible_Part_Items (Element : Protected_Definition_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Set_Visible_Part_Items (Element : in out Protected_Definition_Node; Value : in Asis.Element); function Visible_Part_Items_List (Element : Protected_Definition_Node) return Asis.Element; function Private_Part_Items (Element : Protected_Definition_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Set_Private_Part_Items (Element : in out Protected_Definition_Node; Value : in Asis.Element); function Private_Part_Items_List (Element : Protected_Definition_Node) return Asis.Element; function Get_Identifier (Element : Protected_Definition_Node) return Asis.Element; procedure Set_Identifier (Element : in out Protected_Definition_Node; Value : in Asis.Element); function Corresponding_Type_Operators (Element : Protected_Definition_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Add_To_Corresponding_Type_Operators (Element : in out Protected_Definition_Node; Item : in Asis.Element); function Definition_Kind (Element : Protected_Definition_Node) return Asis.Definition_Kinds; function Children (Element : access Protected_Definition_Node) return Traverse_List; function Clone (Element : Protected_Definition_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Protected_Definition_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); -------------------------- -- Task_Definition_Node -- -------------------------- type Task_Definition_Node is new Protected_Definition_Node with private; type Task_Definition_Ptr is access all Task_Definition_Node; for Task_Definition_Ptr'Storage_Pool use Lists.Pool; function New_Task_Definition_Node (The_Context : ASIS.Context) return Task_Definition_Ptr; function Is_Task_Definition_Present (Element : Task_Definition_Node) return Boolean; procedure Set_Is_Task_Definition_Present (Element : in out Task_Definition_Node; Value : in Boolean); function Definition_Kind (Element : Task_Definition_Node) return Asis.Definition_Kinds; function Clone (Element : Task_Definition_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Task_Definition_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); --------------------------------- -- Formal_Type_Definition_Node -- --------------------------------- type Formal_Type_Definition_Node is abstract new Definition_Node with private; type Formal_Type_Definition_Ptr is access all Formal_Type_Definition_Node; for Formal_Type_Definition_Ptr'Storage_Pool use Lists.Pool; function Corresponding_Type_Operators (Element : Formal_Type_Definition_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Add_To_Corresponding_Type_Operators (Element : in out Formal_Type_Definition_Node; Item : in Asis.Element); function Definition_Kind (Element : Formal_Type_Definition_Node) return Asis.Definition_Kinds; private type Type_Definition_Node is abstract new Definition_Node with record Corresponding_Type_Operators : aliased Secondary_Declaration_Lists.List_Node; end record; type Subtype_Indication_Node is new Definition_Node with record Subtype_Mark : aliased Asis.Expression; Subtype_Constraint : aliased Asis.Constraint; Has_Null_Exclusion : aliased Boolean := False; end record; type Constraint_Node is abstract new Definition_Node with record null; end record; type Component_Definition_Node is new Definition_Node with record Component_Subtype_Indication : aliased Asis.Subtype_Indication; Trait_Kind : aliased Asis.Trait_Kinds := An_Ordinary_Trait; end record; type Discrete_Subtype_Definition_Node is abstract new Definition_Node with record null; end record; type Discrete_Range_Node is abstract new Definition_Node with record null; end record; type Unknown_Discriminant_Part_Node is new Definition_Node with record null; end record; type Known_Discriminant_Part_Node is new Definition_Node with record Discriminants : aliased Primary_Declaration_Lists.List; end record; type Record_Definition_Node is new Definition_Node with record Record_Components : aliased Primary_Declaration_Lists.List; Implicit_Components : aliased Secondary_Declaration_Lists.List_Node; end record; type Null_Record_Definition_Node is new Definition_Node with record null; end record; type Null_Component_Node is new Definition_Node with record Pragmas : aliased Primary_Pragma_Lists.List; end record; type Variant_Part_Node is new Definition_Node with record Discriminant_Direct_Name : aliased Asis.Name; Variants : aliased Primary_Variant_Lists.List; Pragmas : aliased Primary_Pragma_Lists.List; End_Pragmas : aliased Primary_Pragma_Lists.List; end record; type Variant_Node is new Definition_Node with record Record_Components : aliased Primary_Declaration_Lists.List; Implicit_Components : aliased Secondary_Declaration_Lists.List_Node; Variant_Choices : aliased Primary_Choise_Lists.List; end record; type Others_Choice_Node is new Definition_Node with record null; end record; type Access_Definition_Node is abstract new Definition_Node with record Has_Null_Exclusion : aliased Boolean := False; end record; type Incomplete_Type_Definition_Node is new Definition_Node with record null; end record; type Tagged_Incomplete_Type_Definition_Node is new Incomplete_Type_Definition_Node with record Has_Tagged : aliased Boolean := False; end record; type Private_Type_Definition_Node is new Definition_Node with record Trait_Kind : aliased Asis.Trait_Kinds := An_Ordinary_Trait; Corresponding_Type_Operators : aliased Secondary_Declaration_Lists.List_Node; Has_Limited : aliased Boolean := False; Has_Private : aliased Boolean := False; end record; type Tagged_Private_Type_Definition_Node is new Private_Type_Definition_Node with record Has_Abstract : aliased Boolean := False; Has_Tagged : aliased Boolean := False; end record; type Private_Extension_Definition_Node is new Private_Type_Definition_Node with record Ancestor_Subtype_Indication : aliased Asis.Subtype_Indication; Implicit_Inherited_Declarations : aliased Secondary_Declaration_Lists.List_Node; Implicit_Inherited_Subprograms : aliased Secondary_Declaration_Lists.List_Node; Has_Synchronized : aliased Boolean := False; Has_Abstract : aliased Boolean := False; end record; type Protected_Definition_Node is new Definition_Node with record Is_Private_Present : aliased Boolean := False; Visible_Part_Items : aliased Primary_Declaration_Lists.List; Private_Part_Items : aliased Primary_Declaration_Lists.List; Identifier : aliased Asis.Element; Corresponding_Type_Operators : aliased Secondary_Declaration_Lists.List_Node; end record; type Task_Definition_Node is new Protected_Definition_Node with record Is_Task_Definition_Present : aliased Boolean := False; end record; type Formal_Type_Definition_Node is abstract new Definition_Node with record Corresponding_Type_Operators : aliased Secondary_Declaration_Lists.List_Node; end record; end Asis.Gela.Elements.Defs;
with Ada.Text_IO; use Ada.Text_IO; package body Memory.Stats is Max_Stride : constant := Integer'Last; function Create_Stats(mem : access Memory_Type'Class) return Stats_Pointer is result : constant Stats_Pointer := new Stats_Type; begin Set_Memory(result.all, mem); return result; end Create_Stats; function Clone(mem : Stats_Type) return Memory_Pointer is result : constant Stats_Pointer := new Stats_Type'(mem); begin return Memory_Pointer(result); end Clone; function Compute_Multiple(last, current : Integer) return Integer is begin if last /= 0 then return current / last; else return 0; end if; end Compute_Multiple; function Compute_Stride(last, current : Address_Type) return Integer is stride : Integer := 0; begin if last < current and current - last <= Max_Stride then stride := Integer(current - last); elsif last > current and last - current <= Max_Stride then stride := -Integer(last - current); end if; return stride; end Compute_Stride; procedure Process(mem : in out Stats_Type; address : in Address_Type; size : in Positive) is stride : constant Integer := Compute_Stride(mem.last_address, address); mult : constant Integer := Compute_Multiple(mem.last_stride, stride); begin mem.addresses.Increment(address); mem.strides.Increment(stride); mem.multipliers.Increment(mult); mem.last_address := address; mem.last_stride := stride; if address < mem.min_address then mem.min_address := address; end if; if address + Address_Type(size) > mem.max_address then mem.max_address := address + Address_Type(size); end if; end Process; procedure Reset(mem : in out Stats_Type; context : in Natural) is begin Reset(Container_Type(mem), context); mem.last_address := 0; mem.last_stride := 0; mem.reads := 0; mem.min_address := Address_Type'Last; mem.max_address := Address_Type'First; mem.addresses.Reset; mem.strides.Reset; mem.multipliers.Reset; end Reset; procedure Read(mem : in out Stats_Type; address : in Address_Type; size : in Positive) is begin Read(Container_Type(mem), address, size); mem.reads := mem.reads + 1; Process(mem, address, size); end Read; procedure Write(mem : in out Stats_Type; address : in Address_Type; size : in Positive) is begin Write(Container_Type(mem), address, size); Process(mem, address, size); end Write; procedure Show_Access_Stats(mem : in out Stats_Type) is begin Show_Access_Stats(Container_Type(mem)); Put_Line(" Reads: " & Long_Integer'Image(mem.reads)); Put_Line(" Writes: " & Long_Integer'Image(Get_Writes(mem))); Put_Line(" Min Address:" & Address_Type'Image(mem.min_address)); Put_Line(" Max Address:" & Address_Type'Image(mem.max_address)); mem.addresses.Show (" Addresses"); mem.strides.Show (" Strides"); mem.multipliers.Show(" Multipliers"); end Show_Access_Stats; end Memory.Stats;
with Interfaces; with Ada.Text_IO; with Ada.Unchecked_Deallocation; package body UnZip.Decompress.Huffman is -- Note from Pascal source: -- C code by info - zip group, translated to pascal by Christian Ghisler -- based on unz51g.zip -- Free huffman tables starting with table where t points to procedure HufT_free (tl : in out p_Table_list) is procedure Dispose is new Ada.Unchecked_Deallocation (HufT_table, p_HufT_table); procedure Dispose is new Ada.Unchecked_Deallocation (Table_list, p_Table_list); current : p_Table_list; tcount : Natural; -- just a stat. Idea : replace table_list with an array begin if full_trace then pragma Warnings (Off, "this code can never be executed and has been deleted"); Ada.Text_IO.Put ("[HufT_Free .. . "); tcount := 0; pragma Warnings (On, "this code can never be executed and has been deleted"); end if; while tl /= null loop Dispose (tl.all.table); -- destroy the Huffman table current := tl; tl := tl.all.next; Dispose (current); -- destroy the current node if full_trace then pragma Warnings (Off, "this code can never be executed and has been deleted"); tcount := tcount + 1; pragma Warnings (On, "this code can never be executed and has been deleted"); end if; end loop; if full_trace then pragma Warnings (Off, "this code can never be executed and has been deleted"); Ada.Text_IO.Put_Line (Integer'Image (tcount) & " tables]"); pragma Warnings (On, "this code can never be executed and has been deleted"); end if; end HufT_free; -- Build huffman table from code lengths given by array b procedure HufT_build (b : Length_array; s : Integer; d, e : Length_array; tl : out p_Table_list; m : in out Integer; huft_incomplete : out Boolean) is use Interfaces; b_max : constant := 16; b_maxp1 : constant := b_max + 1; -- bit length count table count : array (0 .. b_maxp1) of Integer := (others => 0); f : Integer; -- i repeats in table every f entries g : Integer; -- max. code length i, -- counter, current code j : Integer; -- counter kcc : Integer; -- number of bits in current code c_idx, v_idx : Natural; -- array indices current_table_ptr : p_HufT_table := null; current_node_ptr : p_Table_list := null; -- curr. node for the curr. table new_node_ptr : p_Table_list; -- new node for the new table new_entry : HufT; -- table entry for structure assignment u : array (0 .. b_max) of p_HufT_table; -- table stack n_max : constant := 288; -- values in order of bit length v : array (0 .. n_max) of Integer := (others => 0); el_v, el_v_m_s : Integer; w : Natural := 0; -- bits before this table offset, code_stack : array (0 .. b_maxp1) of Integer; table_level : Integer := -1; bits : array (Integer'(-1) .. b_maxp1) of Integer; -- ^bits (table_level) = # bits in table of level table_level y : Integer; -- number of dummy codes added z : Natural := 0; -- number of entries in current table el : Integer; -- length of eob code=code 256 no_copy_length_array : constant Boolean := d'Length = 0 or else e'Length = 0; begin if full_trace then pragma Warnings (Off, "this code can never be executed and has been deleted"); Ada.Text_IO.Put ("[HufT_Build .. ."); pragma Warnings (On, "this code can never be executed and has been deleted"); end if; tl := null; if b'Length > 256 then -- set length of EOB code, if any el := b (256); else el := b_max; end if; -- Generate counts for each bit length for k in b'Range loop if b (k) > b_max then -- m := 0; -- GNAT 2005 doesn't like it (warning). raise huft_error; end if; count (b (k)) := count (b (k)) + 1; end loop; if count (0) = b'Length then m := 0; huft_incomplete := False; -- spotted by Tucker Taft, 19 - Aug - 2004 return; -- complete end if; -- Find minimum and maximum length, bound m by those j := 1; while j <= b_max and then count (j) = 0 loop j := j + 1; end loop; kcc := j; if m < j then m := j; end if; i := b_max; while i > 0 and then count (i) = 0 loop i := i - 1; end loop; g := i; if m > i then m := i; end if; -- Adjust last length count to fill out codes, if needed y := Integer (Shift_Left (Unsigned_32'(1), j)); -- y := 2 ** j; while j < i loop y := y - count (j); if y < 0 then raise huft_error; end if; y := y * 2; j := j + 1; end loop; y := y - count (i); if y < 0 then raise huft_error; end if; count (i) := count (i) + y; -- Generate starting offsets into the value table for each length offset (1) := 0; j := 0; for idx in 2 .. i loop j := j + count (idx - 1); offset (idx) := j; end loop; -- Make table of values in order of bit length for idx in b'Range loop j := b (idx); if j /= 0 then v (offset (j)) := idx - b'First; offset (j) := offset (j) + 1; end if; end loop; -- Generate huffman codes and for each, make the table entries code_stack (0) := 0; i := 0; v_idx := v'First; bits (-1) := 0; -- go through the bit lengths (kcc already is bits in shortest code) for k in kcc .. g loop for am1 in reverse 0 .. count (k) - 1 loop -- a counts codes of length k -- here i is the huffman code of length k bits for value v (v_idx) while k > w + bits (table_level) loop w := w + bits (table_level); -- Length of tables to this position table_level := table_level + 1; z := g - w; -- Compute min size table <= m bits if z > m then z := m; end if; j := k - w; f := Integer (Shift_Left (Unsigned_32'(1), j)); -- f := 2 ** j; if f > am1 + 2 then -- Try a k - w bit table f := f - (am1 + 2); c_idx := k; loop -- Try smaller tables up to z bits j := j + 1; exit when j >= z; f := f * 2; c_idx := c_idx + 1; exit when f - count (c_idx) <= 0; f := f - count (c_idx); end loop; end if; if w + j > el and then w < el then j := el - w; -- Make EOB code end at table end if; if w = 0 then j := m; -- Fix : main table always m bits! end if; z := Integer (Shift_Left (Unsigned_32'(1), j)); -- z := 2 ** j; bits (table_level) := j; -- Allocate and link new table begin current_table_ptr := new HufT_table (0 .. z); new_node_ptr := new Table_list'(current_table_ptr, null); exception when Storage_Error => raise huft_out_of_memory; end; if current_node_ptr = null then -- first table tl := new_node_ptr; else current_node_ptr.all.next := new_node_ptr; -- not my first .. . end if; current_node_ptr := new_node_ptr; -- always non - Null from there u (table_level) := current_table_ptr; -- Connect to last table, if there is one if table_level > 0 then code_stack (table_level) := i; new_entry.bits := bits (table_level - 1); new_entry.extra_bits := 16 + j; new_entry.next_table := current_table_ptr; j := Integer ( Shift_Right (Unsigned_32 (i) and (Shift_Left (Unsigned_32'(1), w) - 1), w - bits (table_level - 1)) ); -- Test against bad input! if j > u (table_level - 1)'Last then raise huft_error; end if; u (table_level - 1).all (j) := new_entry; end if; end loop; -- Set up table entry in new_entry new_entry.bits := k - w; new_entry.next_table := null; -- Unused if v_idx >= b'Length then new_entry.extra_bits := invalid; else el_v := v (v_idx); el_v_m_s := el_v - s; if el_v_m_s < 0 then -- Simple code, raw value if el_v < 256 then new_entry.extra_bits := 16; else new_entry.extra_bits := 15; end if; new_entry.n := el_v; else -- Non - simple - > lookup in lists if no_copy_length_array then raise huft_error; end if; new_entry.extra_bits := e (el_v_m_s); new_entry.n := d (el_v_m_s); end if; v_idx := v_idx + 1; end if; -- fill code - like entries with new_entry f := Integer (Shift_Left (Unsigned_32'(1), k - w)); -- i.e. f := 2 ** (k - w); j := Integer (Shift_Right (Unsigned_32 (i), w)); while j < z loop current_table_ptr.all (j) := new_entry; j := j + f; end loop; -- backwards increment the k - bit code i j := Integer (Shift_Left (Unsigned_32'(1), k - 1)); -- i.e. : j := 2 ** (k - 1) while (Unsigned_32 (i) and Unsigned_32 (j)) /= 0 loop i := Integer (Unsigned_32 (i) xor Unsigned_32 (j)); j := j / 2; end loop; i := Integer (Unsigned_32 (i) xor Unsigned_32 (j)); -- backup over finished tables while Integer (Unsigned_32 (i) and (Shift_Left (1, w) - 1)) /= code_stack (table_level) loop table_level := table_level - 1; w := w - bits (table_level); -- Size of previous table! end loop; end loop; -- am1 end loop; -- k if full_trace then pragma Warnings (Off, "this code can never be executed and has been deleted"); Ada.Text_IO.Put_Line ("finished]"); pragma Warnings (On, "this code can never be executed and has been deleted"); end if; huft_incomplete := y /= 0 and then g /= 1; exception when others => HufT_free (tl); raise; end HufT_build; end UnZip.Decompress.Huffman;
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings; with Util.Strings; with Util.Log.Loggers; with EL.Contexts.Default; with EL.Utils; with EL.Variables.Default; with Gen.Model.Enums; package body Gen.Model.Tables is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Model.Tables"); -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : Column_Definition; Name : String) return Util.Beans.Objects.Object is use type Gen.Model.Mappings.Mapping_Definition_Access; begin if Name = "type" then declare T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; begin if T = null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (T.all'Access, Util.Beans.Objects.STATIC); end; elsif Name = "index" then return Util.Beans.Objects.To_Object (From.Number); elsif Name = "isUnique" then return Util.Beans.Objects.To_Object (From.Unique); elsif Name = "isNull" then return Util.Beans.Objects.To_Object (not From.Not_Null); elsif Name = "isInserted" then return Util.Beans.Objects.To_Object (From.Is_Inserted); elsif Name = "isUpdated" then return Util.Beans.Objects.To_Object (From.Is_Updated); elsif Name = "sqlType" then if Length (From.Sql_Type) > 0 then return Util.Beans.Objects.To_Object (From.Sql_Type); end if; declare T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; begin if T = null then return Util.Beans.Objects.Null_Object; -- If this is an association to another table, use the primary key of that table. elsif T.all in Table_Definition'Class and then Table_Definition'Class (T.all).Id_Column /= null then return Table_Definition'Class (T.all).Id_Column.Get_Value (Name); elsif T.all in Enums.Enum_Definition'Class then return T.Get_Value ("sqlType"); else declare Ctx : EL.Contexts.Default.Default_Context; Variables : aliased EL.Variables.Default.Default_Variable_Mapper; begin Variables.Bind ("column", From.Bean); Ctx.Set_Variable_Mapper (Variables'Unchecked_Access); return EL.Utils.Eval (To_String (T.Target), Ctx); end; end if; end; elsif Name = "sqlName" then if Length (From.Sql_Name) > 0 then return Util.Beans.Objects.To_Object (From.Sql_Name); end if; declare T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; Table : Table_Definition_Access; begin if T.all in Table_Definition'Class then Table := Table_Definition'Class (T.all)'Access; end if; if Table /= null and then Table.Id_Column /= null then return Util.Beans.Objects.To_Object (From.Name & "_" & Table.Id_Column.Name); else return Util.Beans.Objects.To_Object (From.Name); end if; end; elsif Name = "sqlLength" then return Util.Beans.Objects.To_Object (From.Sql_Length); elsif Name = "isVersion" then return Util.Beans.Objects.To_Object (From.Is_Version); elsif Name = "isReadable" then return Util.Beans.Objects.To_Object (From.Is_Readable); elsif Name = "isPrimaryKey" then return Util.Beans.Objects.To_Object (From.Is_Key); elsif Name = "isPrimitiveType" then return Util.Beans.Objects.To_Object (From.Is_Basic_Type); elsif Name = "generator" then return From.Generator; else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Returns true if the column type is a basic type. -- ------------------------------ function Is_Basic_Type (From : in Column_Definition) return Boolean is use type Gen.Model.Mappings.Mapping_Definition_Access; use type Gen.Model.Mappings.Basic_Type; T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; Name : constant String := To_String (From.Type_Name); begin if T /= null then return T.Kind /= Gen.Model.Mappings.T_BLOB and T.Kind /= Gen.Model.Mappings.T_TABLE and T.Kind /= Gen.Model.Mappings.T_BEAN; end if; return Name = "int" or Name = "String" or Name = "ADO.Identifier" or Name = "Timestamp" or Name = "Integer" or Name = "long" or Name = "Long" or Name = "Date" or Name = "Time"; end Is_Basic_Type; -- ------------------------------ -- Returns the column type. -- ------------------------------ function Get_Type (From : in Column_Definition) return String is use type Gen.Model.Mappings.Mapping_Definition_Access; T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; begin if T /= null then return To_String (T.Target); else return To_String (From.Type_Name); end if; end Get_Type; -- ------------------------------ -- Returns the column type mapping. -- ------------------------------ function Get_Type_Mapping (From : in Column_Definition) return Gen.Model.Mappings.Mapping_Definition_Access is use type Mappings.Mapping_Definition_Access; use type Gen.Model.Packages.Package_Definition_Access; Result : Gen.Model.Mappings.Mapping_Definition_Access := null; begin if From.Type_Mapping /= null then return From.Type_Mapping; end if; if From.Table /= null and then From.Table.Package_Def /= null then Result := From.Table.Package_Def.Find_Type (From.Type_Name); end if; if Result = null then Result := Gen.Model.Mappings.Find_Type (From.Type_Name); end if; if Result /= null and then From.Use_Foreign_Key_Type and then Result.all in Table_Definition'Class and then Table_Definition'Class (Result.all).Id_Column /= null then return Table_Definition'Class (Result.all).Id_Column.Get_Type_Mapping; end if; return Result; end Get_Type_Mapping; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Column_Definition) is use type Mappings.Mapping_Definition_Access; begin O.Bean := Util.Beans.Objects.To_Object (O'Unchecked_Access, Util.Beans.Objects.STATIC); end Prepare; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : Association_Definition; Name : String) return Util.Beans.Objects.Object is begin return Column_Definition (From).Get_Value (Name); end Get_Value; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Association_Definition) is use type Gen.Model.Mappings.Mapping_Definition_Access; T : constant Gen.Model.Mappings.Mapping_Definition_Access := O.Get_Type_Mapping; Table : Table_Definition_Access; begin if T = null then Table := Create_Table (O.Type_Name); O.Type_Mapping := Table.all'Access; end if; end Prepare; -- ------------------------------ -- Initialize the table definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Table_Definition) is begin O.Members_Bean := Util.Beans.Objects.To_Object (O.Members'Unchecked_Access, Util.Beans.Objects.STATIC); O.Operations_Bean := Util.Beans.Objects.To_Object (O.Operations'Unchecked_Access, Util.Beans.Objects.STATIC); end Initialize; -- ------------------------------ -- Create a table with the given name. -- ------------------------------ function Create_Table (Name : in Unbounded_String) return Table_Definition_Access is Table : constant Table_Definition_Access := new Table_Definition; begin Table.Name := Name; Table.Kind := Gen.Model.Mappings.T_TABLE; Table.Target := Name; declare Pos : constant Natural := Index (Table.Name, ".", Ada.Strings.Backward); begin if Pos > 0 then Table.Pkg_Name := Unbounded_Slice (Table.Name, 1, Pos - 1); Table.Type_Name := Unbounded_Slice (Table.Name, Pos + 1, Length (Table.Name)); else Table.Pkg_Name := To_Unbounded_String ("ADO"); Table.Type_Name := Table.Name; end if; Table.Table_Name := Table.Type_Name; end; return Table; end Create_Table; -- ------------------------------ -- Create a table column with the given name and add it to the table. -- ------------------------------ procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access) is begin Column := new Column_Definition; Column.Name := Name; Column.Sql_Name := Name; Column.Number := Table.Members.Get_Count; Column.Table := Table'Unchecked_Access; Table.Members.Append (Column); end Add_Column; -- ------------------------------ -- Create a table association with the given name and add it to the table. -- ------------------------------ procedure Add_Association (Table : in out Table_Definition; Name : in Unbounded_String; Assoc : out Association_Definition_Access) is begin Assoc := new Association_Definition; Assoc.Name := Name; Assoc.Number := Table.Members.Get_Count; Assoc.Table := Table'Unchecked_Access; Table.Members.Append (Assoc.all'Access); Table.Has_Associations := True; end Add_Association; -- ------------------------------ -- Create an operation with the given name and add it to the table. -- ------------------------------ procedure Add_Operation (Table : in out Table_Definition; Name : in Unbounded_String; Operation : out Model.Operations.Operation_Definition_Access) is begin Operation := new Model.Operations.Operation_Definition; Operation.Name := Name; Table.Operations.Append (Operation.all'Access); end Add_Operation; -- ------------------------------ -- Get the dependency between the two tables. -- Returns NONE if both table don't depend on each other. -- Returns FORWARD if the <tt>Left</tt> table depends on <tt>Right</tt>. -- Returns BACKWARD if the <tt>Right</tt> table depends on <tt>Left</tt>. -- ------------------------------ function Depends_On (Left, Right : in Table_Definition_Access) return Dependency_Type is begin if Left.Dependencies.Contains (Right) then Log.Info ("Table {0} depends on {1}", To_String (Left.Name), To_String (Right.Name)); return FORWARD; elsif Right.Dependencies.Contains (Left) then Log.Info ("Table {1} depends on {0}", To_String (Left.Name), To_String (Right.Name)); return BACKWARD; else return NONE; end if; end Depends_On; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Table_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "members" or Name = "columns" then return From.Members_Bean; elsif Name = "operations" then return From.Operations_Bean; elsif Name = "id" and From.Id_Column /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Id_Column.all'Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "version" and From.Version_Column /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Version_Column.all'Unchecked_Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "hasAssociations" then return Util.Beans.Objects.To_Object (From.Has_Associations); elsif Name = "hasList" then return Util.Beans.Objects.To_Object (From.Has_List); elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "table" then return Util.Beans.Objects.To_Object (From.Table_Name); elsif Name = "parent" then if From.Parent /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Parent.all'Unchecked_Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; else return Util.Beans.Objects.Null_Object; end if; elsif Name = "isVersion" or Name = "isPrimaryKey" or Name = "isBean" or Name = "isPrimitiveType" or Name = "isEnum" or Name = "isIdentifier" or Name = "isBoolean" or Name = "isBlob" or Name = "isDate" or Name = "isString" then return Util.Beans.Objects.To_Object (False); elsif Name = "isReadable" or Name = "isObject" then return Util.Beans.Objects.To_Object (True); elsif Name = "isLimited" then return Util.Beans.Objects.To_Object (From.Is_Limited); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Table_Definition) is use type Gen.Model.Mappings.Mapping_Definition_Access; Iter : Column_List.Cursor := O.Members.First; C : Column_Definition_Access; T : Gen.Model.Mappings.Mapping_Definition_Access; begin Log.Info ("Prepare table {0}", O.Name); while Column_List.Has_Element (Iter) loop C := Column_List.Element (Iter); C.Prepare; if C.Is_Key then Log.Info ("Found key {0}", C.Name); O.Id_Column := C; end if; if C.Is_Version then Log.Info ("Found version column {0}", C.Name); O.Version_Column := C; -- For the <<Version>> columns, do not allow users to modify them. C.Is_Updated := False; C.Is_Inserted := False; end if; -- Collect in the dependencies vectors the tables that we are using. if not C.Use_Foreign_Key_Type and then C.all in Association_Definition'Class then T := C.Get_Type_Mapping; if T /= null and then T.all in Table_Definition'Class then O.Dependencies.Append (Table_Definition'Class (T.all)'Access); end if; end if; Column_List.Next (Iter); end loop; if O.Id_Column = null and Length (O.Table_Name) > 0 then Log.Error ("Table {0} does not have any primary key", To_String (O.Name)); end if; if Length (O.Parent_Name) > 0 then declare Result : constant Mappings.Mapping_Definition_Access := O.Package_Def.Find_Type (O.Parent_Name); begin if Result /= null and then Result.all in Table_Definition'Class then O.Parent := Table_Definition'Class (Result.all)'Access; end if; end; end if; end Prepare; -- ------------------------------ -- Collect the dependencies to other tables. -- ------------------------------ procedure Collect_Dependencies (O : in out Table_Definition) is Iter : Table_Vectors.Cursor := O.Dependencies.First; List : Table_Vectors.Vector; D : Table_Definition_Access; begin Log.Info ("Collect dependencies of {0}", O.Name); if O.Has_Mark then return; end if; O.Has_Mark := True; while Table_Vectors.Has_Element (Iter) loop D := Table_Vectors.Element (Iter); D.Collect_Dependencies; List.Append (D.Dependencies); Table_Vectors.Next (Iter); end loop; O.Has_Mark := False; Iter := List.First; while Table_Vectors.Has_Element (Iter) loop D := Table_Vectors.Element (Iter); if not O.Dependencies.Contains (D) then Log.Info ("Adding dependency for {0} on {1}", To_String (O.Name), To_String (D.Name)); O.Dependencies.Append (D); end if; Table_Vectors.Next (Iter); end loop; end Collect_Dependencies; -- ------------------------------ -- Set the table name and determines the package name. -- ------------------------------ procedure Set_Table_Name (Table : in out Table_Definition; Name : in String) is Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin Table.Name := To_Unbounded_String (Name); if Pos > 0 then Table.Pkg_Name := To_Unbounded_String (Name (Name'First .. Pos - 1)); Table.Type_Name := To_Unbounded_String (Name (Pos + 1 .. Name'Last)); else Table.Pkg_Name := To_Unbounded_String ("ADO"); Table.Type_Name := Table.Name; end if; end Set_Table_Name; end Gen.Model.Tables;
-- -- Copyright (C) 2015-2016 secunet Security Networks AG -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- with HW.GFX.GMA.PLLs.LCPLL; with HW.GFX.GMA.PLLs.WRPLL; with HW.Debug; with GNAT.Source_Info; package body HW.GFX.GMA.PLLs with Refined_State => (State => PLLs) is type Count_Range is new Natural range 0 .. 2; type PLL_State is record Use_Count : Count_Range; Mode : Mode_Type; end record; type PLL_State_Array is array (WRPLLs) of PLL_State; PLLs : PLL_State_Array; procedure Initialize is begin PLLs := (WRPLLs => (Use_Count => 0, Mode => Invalid_Mode)); end Initialize; procedure Alloc_Configurable (Mode : in Mode_Type; PLL : out T; Success : out Boolean) with Pre => True is begin -- try to find shareable PLL for P in WRPLLs loop Success := PLLs (P).Use_Count /= 0 and PLLs (P).Use_Count /= Count_Range'Last and PLLs (P).Mode = Mode; if Success then PLL := P; PLLs (PLL).Use_Count := PLLs (PLL).Use_Count + 1; return; end if; end loop; -- try to find free PLL for P in WRPLLs loop if PLLs (P).Use_Count = 0 then PLL := P; WRPLL.On (PLL, Mode.Dotclock, Success); if Success then PLLs (PLL) := (Use_Count => 1, Mode => Mode); end if; return; end if; end loop; PLL := Invalid; end Alloc_Configurable; procedure Alloc (Port_Cfg : in Port_Config; PLL : out T; Success : out Boolean) is begin pragma Debug (Debug.Put_Line (GNAT.Source_Info.Enclosing_Entity)); if Port_Cfg.Port = DIGI_E then PLL := Invalid; Success := True; elsif Port_Cfg.Display = DP then PLL := LCPLL.Fixed_LCPLLs (Port_Cfg.DP.Bandwidth); Success := True; else Alloc_Configurable (Port_Cfg.Mode, PLL, Success); end if; end Alloc; procedure Free (PLL : T) is begin pragma Debug (Debug.Put_Line (GNAT.Source_Info.Enclosing_Entity)); if PLL in WRPLLs then if PLLs (PLL).Use_Count /= 0 then PLLs (PLL).Use_Count := PLLs (PLL).Use_Count - 1; if PLLs (PLL).Use_Count = 0 then WRPLL.Off (PLL); end if; end if; end if; end Free; procedure All_Off is begin pragma Debug (Debug.Put_Line (GNAT.Source_Info.Enclosing_Entity)); for PLL in WRPLLs loop WRPLL.Off (PLL); end loop; end All_Off; function Register_Value (PLL : T) return Word32 is begin return (if PLL in LCPLLs then LCPLL.Register_Value (PLL) elsif PLL in WRPLLs then WRPLL.Register_Value (PLL) else 0); end Register_Value; end HW.GFX.GMA.PLLs;
-- 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. with Ada.Strings.Bounded; with GL.Low_Level.Enums; with GL.Objects.Textures; with GL.Pixels; with Orka.Rendering.Framebuffers; with Orka.Resources.Locations; private with Ada.Containers.Indefinite_Holders; private with GL.Buffers; private with Orka.Containers.Bounded_Vectors; package Orka.Frame_Graphs is pragma Preelaborate; Maximum_Name_Length : constant := 16; package Name_Strings is new Ada.Strings.Bounded.Generic_Bounded_Length (Max => Maximum_Name_Length); type Resource_Version is private; type Extent_3D is record Width, Height, Depth : Positive := 1; end record; type Resource is record Name : Name_Strings.Bounded_String; Kind : GL.Low_Level.Enums.Texture_Kind; Format : GL.Pixels.Internal_Format; Extent : Extent_3D; Levels : Positive := 1; Samples : Natural := 0; Version : Resource_Version; end record; function "+" (Value : String) return Name_Strings.Bounded_String; function "+" (Value : Name_Strings.Bounded_String) return String; ---------------------------------------------------------------------- type Read_Mode is (Not_Used, Framebuffer_Attachment, Texture_Read, Image_Load); type Write_Mode is (Not_Used, Framebuffer_Attachment, Image_Store); type Input_Resource is record Mode : Read_Mode; Data : Resource; Implicit : Boolean; Written : Boolean; -- Written to by a previous render pass end record; type Output_Resource is record Mode : Write_Mode; Data : Resource; Implicit : Boolean; Read : Boolean; -- Read by a subsequent render pass end record; type Input_Resource_Array is array (Positive range <>) of Input_Resource; type Output_Resource_Array is array (Positive range <>) of Output_Resource; ---------------------------------------------------------------------- type Render_Pass (<>) is tagged limited private; function Name (Object : Render_Pass) return String; procedure Add_Input (Object : Render_Pass; Subject : Resource; Read : Read_Mode); -- Add the given resource as an input to the render pass, so that it -- can be read as a texture, an image texture, or attached to the -- framebuffer procedure Add_Output (Object : Render_Pass; Subject : Resource; Write : Write_Mode); -- Add the given resource as an output to the render pass, so that it -- can be written as an image texture or attached to the framebuffer function Add_Input_Output (Object : Render_Pass; Subject : Resource; Read : Read_Mode; Write : Write_Mode) return Resource with Pre => not (Read = Framebuffer_Attachment xor Write = Framebuffer_Attachment); -- Add the given resource as an input and an output to the render pass, -- indicating that the resource will be modified by the pass. The modified -- resource is returned and may be used as an input for other render passes. ---------------------------------------------------------------------- type Render_Pass_Data is private; function Name (Pass : Render_Pass_Data) return String; type Execute_Callback is access procedure (Pass : Render_Pass_Data); ---------------------------------------------------------------------- type Handle_Type is new Positive; type Builder (Maximum_Passes, Maximum_Handles : Positive; Maximum_Resources : Handle_Type) is tagged limited private; function Add_Pass (Object : in out Builder; Name : String; Execute : not null Execute_Callback; Side_Effect : Boolean := False) return Render_Pass'Class with Pre => Name'Length <= Maximum_Name_Length; type Graph (<>) is tagged limited private; function Cull (Object : Builder; Present : Resource) return Graph'Class; ---------------------------------------------------------------------- procedure Initialize (Object : in out Graph; Default : Rendering.Framebuffers.Framebuffer) with Pre => Default.Default; procedure Render (Object : in out Graph); function Input_Resources (Object : Graph; Pass : Render_Pass_Data) return Input_Resource_Array; function Output_Resources (Object : Graph; Pass : Render_Pass_Data) return Output_Resource_Array; procedure Write_Graph (Object : in out Graph; Location : Resources.Locations.Writable_Location_Ptr; Path : String); -- Write the frame graph as JSON to a file at the given path in the -- location -- -- To pretty print the JSON in the file, execute: -- -- python3 -m json.tool < graph.json function Get_Texture (Subject : Resource) return GL.Objects.Textures.Texture with Post => Get_Texture'Result.Allocated; private type Render_Pass (Frame_Graph : access Builder) is tagged limited record Index : Positive; end record; type Render_Pass_Data is record Name : Name_Strings.Bounded_String; Execute : Execute_Callback; Side_Effect : Boolean; Present : Boolean; References : Natural := 0; Read_Offset, Write_Offset : Positive := 1; Read_Count, Write_Count : Natural := 0; Has_Depth : Boolean := False; Has_Stencil : Boolean := False; end record; type Resource_Version is record Version : Natural := 1; -- Version will be 0 if added as implicit input end record; type Resource_Data is record Description : Resource; Modified : Boolean := False; -- True if there is a next version of this resource Implicit : Boolean := False; -- Internally added for framebuffer attachments Input_Mode : Read_Mode := Not_Used; Output_Mode : Write_Mode := Not_Used; Render_Pass : Natural := 0; -- The render pass that writes to this resource, 0 if none Read_Count : Natural := 0; References : Natural := 0; end record; package Pass_Vectors is new Containers.Bounded_Vectors (Positive, Render_Pass_Data); package Resource_Vectors is new Containers.Bounded_Vectors (Handle_Type, Resource_Data); package Handle_Vectors is new Containers.Bounded_Vectors (Positive, Handle_Type); type Builder (Maximum_Passes, Maximum_Handles : Positive; Maximum_Resources : Handle_Type) is tagged limited record Passes : Pass_Vectors.Vector (Maximum_Passes); Resources : Resource_Vectors.Vector (Maximum_Resources); -- Restriction 1: The method used by a render pass to read or write -- to a resource is stored in the resource itself. This means that -- a resource can only be read or written using one method. Read_Handles : Handle_Vectors.Vector (Maximum_Handles); Write_Handles : Handle_Vectors.Vector (Maximum_Handles); -- An array of slices of handles to resources read or written by -- render passes. These describe the links between render passes -- and resources in the frame graph. -- -- Each render pass has a slice of resources it reads and a slice of -- resources it writes. A slice is formed by a contiguous number of -- handles so that a render pass only needs to record the start -- offset and length of the slice. -- -- Restriction 2: Because a slice is a contiguous number of handles, -- the recording of inputs and outputs of different render passes -- cannot be interleaved. -- -- This restriction allows the graph to be implemented using just -- four simple arrays and the arrays should provide good data locality. Present_Pass : Natural := 0; end record; ----------------------------------------------------------------------------- package Framebuffer_Holders is new Ada.Containers.Indefinite_Holders (Element_Type => Rendering.Framebuffers.Framebuffer, "=" => Rendering.Framebuffers."="); type Framebuffer_Pass is record Index : Positive; Framebuffer : Framebuffer_Holders.Holder; Clear_Mask : GL.Buffers.Buffer_Bits; Invalidate_Mask : GL.Buffers.Buffer_Bits; Clear_Buffers : GL.Buffers.Color_Buffer_List (0 .. 7); Render_Buffers : GL.Buffers.Color_Buffer_List (0 .. 7); Buffers_Equal : Boolean; Invalidate_Points : Rendering.Framebuffers.Use_Point_Array; Depth_Writes : Boolean; Stencil_Writes : Boolean; end record; package Framebuffer_Pass_Vectors is new Containers.Bounded_Vectors (Positive, Framebuffer_Pass); type Graph (Maximum_Passes, Maximum_Handles : Positive; Maximum_Resources : Handle_Type) is tagged limited record Graph : Builder (Maximum_Passes, Maximum_Handles, Maximum_Resources); Framebuffers : Framebuffer_Pass_Vectors.Vector (Maximum_Passes); end record; end Orka.Frame_Graphs;
with Ada.Numerics; with PortAudioAda; use PortAudioAda; package Ctestc_Types is Pi : constant := Ada.Numerics.Pi; Two_Pi : constant := Pi * 2.0; Default_Buffer_Size : constant := 32; type Float_Array is array (Natural range <>) of aliased Float; pragma Convention (C, Float_Array); type paTestData is record left_phase : aliased Float; right_phase : aliased Float; end record; pragma Convention (C, paTestData); type paTestData_Ptr is access all paTestData; pragma Convention (C, paTestData_Ptr); pragma No_Strict_Aliasing (paTestData_Ptr); outputParameters : aliased PA_Stream_Parameters; data : aliased paTestData; pragma Convention (C, data); end Ctestc_Types;
package body Equilibrium is function Get_Indices (From : Array_Type) return Index_Vectors.Vector is Result : Index_Vectors.Vector; Right_Sum, Left_Sum : Element_Type := Zero; begin for Index in Index_Type'Range loop Right_Sum := Right_Sum + Element (From, Index); end loop; for Index in Index_Type'Range loop Right_Sum := Right_Sum - Element (From, Index); if Left_Sum = Right_Sum then Index_Vectors.Append (Result, Index); end if; Left_Sum := Left_Sum + Element (From, Index); end loop; return Result; end Get_Indices; end Equilibrium;
with Ada.Wide_Wide_Text_IO; with League.Strings; with XML.SAX.Attributes; with XML.SAX.Pretty_Writers; procedure Main is function "+" (Item : Wide_Wide_String) return League.Strings.Universal_String renames League.Strings.To_Universal_String; type Remarks is record Name : League.Strings.Universal_String; Remark : League.Strings.Universal_String; end record; type Remarks_Array is array (Positive range <>) of Remarks; ------------ -- Output -- ------------ procedure Output (Remarks : Remarks_Array) is Writer : XML.SAX.Pretty_Writers.SAX_Pretty_Writer; Attributes : XML.SAX.Attributes.SAX_Attributes; begin Writer.Set_Offset (2); Writer.Start_Document; Writer.Start_Element (Qualified_Name => +"CharacterRemarks"); for J in Remarks'Range loop Attributes.Clear; Attributes.Set_Value (+"name", Remarks (J).Name); Writer.Start_Element (Qualified_Name => +"Character", Attributes => Attributes); Writer.Characters (Remarks (J).Remark); Writer.End_Element (Qualified_Name => +"Character"); end loop; Writer.End_Element (Qualified_Name => +"CharacterRemarks"); Writer.End_Document; Ada.Wide_Wide_Text_IO.Put_Line (Writer.Text.To_Wide_Wide_String); end Output; begin Output (((+"April", +"Bubbly: I'm > Tam and <= Emily"), (+"Tam O'Shanter", +"Burns: ""When chapman billies leave the street ..."""), (+"Emily", +"Short & shrift"))); end Main;
package discriminant_specification is type Buffer(Size : Integer := 100) is record Pos : Integer := 0; Value : String(1 .. Size); end record; procedure append_ch(b : in out Buffer; ch : in character); procedure remove_ch(b : in out Buffer; ch : out character); function make_buf(size : in integer) return Buffer; mini : Buffer(10); end discriminant_specification;
-- Copyright (C) 2019 Thierry Rascle <thierr26@free.fr> -- MIT license. Please refer to the LICENSE file. -- with GNAT.Exception_Traces; -- For debugging. with Apsepp_Test_Harness; procedure Apsepp_Test is -- use GNAT.Exception_Traces; -- For debugging. begin -- Trace_On (Every_Raise); -- For debugging. Apsepp_Test_Harness.Apsepp_Test_Procedure; -- Trace_Off; -- For debugging. end Apsepp_Test;
with GID.Buffering; use GID.Buffering; with GID.Color_tables; package body GID.Decoding_TGA is ---------- -- Load -- ---------- procedure Load (image: in out Image_descriptor) is procedure Row_start(y: Natural) is begin if image.flag_1 then -- top first Set_X_Y(0, image.height-1-y); else Set_X_Y(0, y); end if; end Row_Start; -- Run Length Encoding -- RLE_pixels_remaining: Natural:= 0; is_run_packet: Boolean; type Pixel is record color: RGB_Color; alpha: U8; end record; pix, pix_mem: Pixel; generic bpp: Positive; pal: Boolean; procedure Get_pixel; pragma Inline(Get_Pixel); -- procedure Get_pixel is idx: Natural; p1, p2, c, d: U8; begin if pal then if image.palette'Length <= 256 then Get_Byte(image.buffer, p1); idx:= Natural(p1); else Get_Byte(image.buffer, p1); Get_Byte(image.buffer, p2); idx:= Natural(p1) + Natural(p2) * 256; end if; idx:= idx + image.palette'First; pix.color:= image.palette(idx); else case bpp is when 32 => -- BGRA Get_Byte(image.buffer, pix.color.blue); Get_Byte(image.buffer, pix.color.green); Get_Byte(image.buffer, pix.color.red); Get_Byte(image.buffer, pix.alpha); when 24 => -- BGR Get_Byte(image.buffer, pix.color.blue); Get_Byte(image.buffer, pix.color.green); Get_Byte(image.buffer, pix.color.red); when 16 | 15 => -- 5 bit per channel Get_Byte(image.buffer, c); Get_Byte(image.buffer, d); Color_tables.Convert(c, d, pix.color); if bpp=16 then pix.alpha:= U8((U16(c and 128) * 255)/128); end if; when 8 => -- Gray Get_Byte(image.buffer, pix.color.green); pix.color.red:= pix.color.green; pix.color.blue:= pix.color.green; when others => null; end case; end if; end Get_pixel; generic bpp: Positive; pal: Boolean; procedure RLE_Pixel; pragma Inline(RLE_Pixel); -- procedure RLE_Pixel is tmp: U8; procedure Get_pixel_for_RLE is new Get_pixel(bpp, pal); begin if RLE_pixels_remaining = 0 then -- load RLE code Get_Byte(image.buffer, tmp ); Get_pixel_for_RLE; RLE_pixels_remaining:= U8'Pos(tmp and 16#7F#); is_run_packet:= (tmp and 16#80#) /= 0; if is_run_packet then pix_mem:= pix; end if; else if is_run_packet then pix:= pix_mem; else Get_pixel_for_RLE; end if; RLE_pixels_remaining:= RLE_pixels_remaining - 1; end if; end RLE_Pixel; procedure RLE_pixel_32 is new RLE_pixel(32, False); procedure RLE_pixel_24 is new RLE_pixel(24, False); procedure RLE_pixel_16 is new RLE_pixel(16, False); procedure RLE_pixel_15 is new RLE_pixel(15, False); procedure RLE_pixel_8 is new RLE_pixel(8, False); procedure RLE_pixel_palette is new RLE_pixel(1, True); -- 1: dummy procedure Output_Pixel is pragma Inline(Output_Pixel); begin case Primary_color_range'Modulus is when 256 => Put_Pixel( Primary_color_range(pix.color.red), Primary_color_range(pix.color.green), Primary_color_range(pix.color.blue), Primary_color_range(pix.alpha) ); when 65_536 => Put_Pixel( 16#101# * Primary_color_range(pix.color.red), 16#101# * Primary_color_range(pix.color.green), 16#101# * Primary_color_range(pix.color.blue), 16#101# * Primary_color_range(pix.alpha) -- 16#101# because max intensity FF goes to FFFF ); when others => raise invalid_primary_color_range; end case; end Output_Pixel; procedure Get_RGBA is -- 32 bits procedure Get_pixel_32 is new Get_pixel(32, False); begin for y in 0..image.height-1 loop Row_start(y); for x in 0..image.width-1 loop Get_pixel_32; Output_Pixel; end loop; Feedback(((y+1)*100)/image.height); end loop; end Get_RGBA; procedure Get_RGB is -- 24 bits procedure Get_pixel_24 is new Get_pixel(24, False); begin for y in 0..image.height-1 loop Row_start(y); for x in 0..image.width-1 loop Get_pixel_24; Output_Pixel; end loop; Feedback(((y+1)*100)/image.height); end loop; end Get_RGB; procedure Get_16 is -- 16 bits procedure Get_pixel_16 is new Get_pixel(16, False); begin for y in 0..image.height-1 loop Row_start(y); for x in 0..image.width-1 loop Get_pixel_16; Output_Pixel; end loop; Feedback(((y+1)*100)/image.height); end loop; end Get_16; procedure Get_15 is -- 15 bits procedure Get_pixel_15 is new Get_pixel(15, False); begin for y in 0..image.height-1 loop Row_start(y); for x in 0..image.width-1 loop Get_pixel_15; Output_Pixel; end loop; Feedback(((y+1)*100)/image.height); end loop; end Get_15; procedure Get_Gray is procedure Get_pixel_8 is new Get_pixel(8, False); begin for y in 0..image.height-1 loop Row_start(y); for x in 0..image.width-1 loop Get_pixel_8; Output_Pixel; end loop; Feedback(((y+1)*100)/image.height); end loop; end Get_Gray; procedure Get_with_palette is procedure Get_pixel_palette is new Get_pixel(1, True); -- 1: dummy begin for y in 0..image.height-1 loop Row_start(y); for x in 0..image.width-1 loop Get_pixel_palette; Output_Pixel; end loop; Feedback(((y+1)*100)/image.height); end loop; end Get_with_palette; begin pix.alpha:= 255; -- opaque is default Attach_Stream(image.buffer, image.stream); -- if image.RLE_encoded then -- One format check per row RLE_pixels_remaining:= 0; for y in 0..image.height-1 loop Row_start(y); if image.palette /= null then for x in 0..image.width-1 loop RLE_pixel_palette; Output_Pixel; end loop; else case image.bits_per_pixel is when 32 => for x in 0..image.width-1 loop RLE_Pixel_32; Output_Pixel; end loop; when 24 => for x in 0..image.width-1 loop RLE_Pixel_24; Output_Pixel; end loop; when 16 => for x in 0..image.width-1 loop RLE_Pixel_16; Output_Pixel; end loop; when 15 => for x in 0..image.width-1 loop RLE_Pixel_15; Output_Pixel; end loop; when 8 => for x in 0..image.width-1 loop RLE_Pixel_8; Output_Pixel; end loop; when others => null; end case; end if; Feedback(((y+1)*100)/image.height); end loop; elsif image.palette /= null then Get_with_palette; else case image.bits_per_pixel is when 32 => Get_RGBA; when 24 => Get_RGB; when 16 => Get_16; when 15 => Get_15; when 8 => Get_Gray; when others => null; end case; end if; end Load; end GID.Decoding_TGA;
-- part of OpenGLAda, (c) 2017 Felix Krause -- released under the terms of the MIT license, see the file "COPYING" with GL.API; with GL.Enums.Getter; package body GL.Window is procedure Set_Viewport (X, Y : Int; Width, Height : Size) is begin GL.API.Viewport (X, Y, Width, Height); Raise_Exception_On_OpenGL_Error; end Set_Viewport; procedure Get_Viewport (X, Y : out Int; Width, Height : out Size) is Ret : Ints.Vector4; begin API.Get_Int_Vec4 (Enums.Getter.Viewport, Ret); Raise_Exception_On_OpenGL_Error; X := Ret (GL.X); Y := Ret (GL.Y); Width := Size (Ret (Z)); Height := Size (Ret (W)); end Get_Viewport; procedure Set_Depth_Range (Near, Far : Double) is begin API.Depth_Range (Near, Far); Raise_Exception_On_OpenGL_Error; end Set_Depth_Range; procedure Get_Depth_Range (Near, Far : out Double) is Ret : Doubles.Vector2; begin API.Get_Double_Vec2 (Enums.Getter.Depth_Range, Ret); Raise_Exception_On_OpenGL_Error; Near := Ret (X); Far := Ret (Y); end Get_Depth_Range; end GL.Window;
package body Options is SCCS_ID : constant String := "@(#) options.ada, Version 1.2"; Rcs_ID : constant String := "$Header: options.a,v 0.1 86/04/01 15:08:15 ada Exp $"; Verbose_Option : Boolean := False; Verbose_Conflict_Option : Boolean := False; Debug_Option : Boolean := False; Interface_to_C_Option : Boolean := False; Summary_Option : Boolean := False; Loud_Option : Boolean := False; -- UMASS CODES : Error_Recovery_Extension_Option : Boolean := False; -- END OF UMASS CODES. procedure Set_Options(S: in String) is begin for I in S'First..S'Last loop case S(I) is when 'v' | 'V' => Verbose_Option := True; when 'c' | 'C' => Verbose_Conflict_Option := True; when 'd' | 'D' => Debug_Option := True; when 'i' | 'I' => Interface_to_C_Option := True; when 's' | 'S' => Summary_Option := True; when 'l' | 'L' => Loud_Option := True; -- UMASS CODES : when 'e' | 'E' => Error_Recovery_Extension_Option := True; -- END OF UMASS CODES. when others => raise Illegal_Option; end case; end loop; end Set_Options; function Verbose return Boolean is begin return Verbose_Option; end; function Verbose_Conflict return Boolean is begin return Verbose_Conflict_Option; end; function Debug return Boolean is begin return Debug_Option; end; function Interface_to_C return Boolean is begin return Interface_to_C_Option; end; function Summary return Boolean is begin return Summary_Option; end; function Loud return Boolean is begin return Loud_Option; end; -- UMASS CODES : function Error_Recovery_Extension return Boolean is begin return Error_Recovery_Extension_Option; end; -- END OF UMASS CODES. end Options;
type Container is array (Positive range <>) of Element; for I in Container'Range loop declare Item : Element renames Container (I); begin Do_Something(Item); -- Here Item is a reference to Container (I) end; end loop;
------------------------------------------------------------------------------ -- G E L A A S I S -- -- ASIS implementation for Gela project, a portable Ada compiler -- -- http://gela.ada-ru.org -- -- - - - - - - - - - - - - - - - -- -- Read copyright and license at the end of this file -- ------------------------------------------------------------------------------ -- $Revision: 209 $ $Date: 2013-11-30 21:03:24 +0200 (Сб., 30 нояб. 2013) $ -- Purpose: with Gela.Embeded_Links.Lists; generic type Element_Type is private; with function "=" (Left, Right : Element_Type) return Boolean is <>; package Gela.Containers.Lists is pragma Preelaborate (Lists); type List is limited private; type Cursor is private; No_Element : constant Cursor; function Is_Empty (Container : List) return Boolean; procedure Clear (Container : in out List); function Element (Position : Cursor) return Element_Type; procedure Prepend (Container : in out List; New_Item : in Element_Type); procedure Append (Container : in out List; New_Item : in Element_Type); procedure Delete (Container : in out List; Position : in out Cursor); procedure Delete_First (Container : in out List); function First (Container : List) return Cursor; function First_Element (Container : List) return Element_Type; function Last_Element (Container : List) return Element_Type; function Next (Position : Cursor) return Cursor; function Find (Container : List; Item : Element_Type; Position : Cursor := No_Element) return Cursor; function Contains (Container : List; Item : Element_Type) return Boolean; function Has_Element (Position : Cursor) return Boolean; private type Node; type Node_Access is access all Node; type Node is record Next : Node_Access; Data : Element_Type; end record; function Get_Next (Item : Node_Access) return Node_Access; procedure Set_Next (Item, Next : Node_Access); pragma Inline (Get_Next, Set_Next); package E is new Gela.Embeded_Links.Lists (Node, Node_Access); type List is limited record X : aliased E.List; end record; type List_Access is access constant E.List; type Cursor is record Ptr : Node_Access; List : List_Access; end record; No_Element : constant Cursor := (null, null); end Gela.Containers.Lists; ------------------------------------------------------------------------------ -- Copyright (c) 2006-2013, Maxim Reznik -- 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 Maxim Reznik, 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 OWNER OR CONTRIBUTORS BE -- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -- POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------
with Ada.Text_IO; use Ada.Text_IO; package body Greetings is procedure Hello is begin Put_Line ("Hello WORLD!"); end Hello; procedure Goodbye is begin Put_Line ("Goodbye WORLD!"); end Goodbye; end Greetings;
----------------------------------------------------------------------- -- asf-beans-flash -- Bean giving access to the flash context -- Copyright (C) 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.Beans.Basic; with Util.Beans.Objects; package ASF.Beans.Flash is -- Context variable giving access to the request headers. FLASH_ATTRIBUTE_NAME : constant String := "flash"; KEEP_MESSAGES_ATTR_NAME : constant String := "keepMessages"; REDIRECT_ATTR_NAME : constant String := "redirect"; -- ------------------------------ -- Flash Bean -- ------------------------------ -- The <b>Flash_Bean</b> gives access to the flash context. type Flash_Bean is new Util.Beans.Basic.Readonly_Bean with private; -- Get the request header identified by the given name. -- Returns Null_Object if the request does not define such header. overriding function Get_Value (Bean : in Flash_Bean; Name : in String) return Util.Beans.Objects.Object; -- Return the Flash_Bean instance. function Instance return Util.Beans.Objects.Object; private type Flash_Bean is new Util.Beans.Basic.Readonly_Bean with null record; end ASF.Beans.Flash;
with Ada.Unchecked_Conversion; with C.winbase; with C.winnt; with C.winternl; package body System.Storage_Map is pragma Suppress (All_Checks); use type C.char_array; use type C.size_t; use type C.windef.ULONG; NTDLL_DLL : aliased constant C.winnt.WCHAR_array (0 .. 9) := ( C.winnt.WCHAR'Val (Wide_Character'Pos ('N')), C.winnt.WCHAR'Val (Wide_Character'Pos ('T')), C.winnt.WCHAR'Val (Wide_Character'Pos ('D')), C.winnt.WCHAR'Val (Wide_Character'Pos ('L')), C.winnt.WCHAR'Val (Wide_Character'Pos ('L')), C.winnt.WCHAR'Val (Wide_Character'Pos ('.')), C.winnt.WCHAR'Val (Wide_Character'Pos ('D')), C.winnt.WCHAR'Val (Wide_Character'Pos ('L')), C.winnt.WCHAR'Val (Wide_Character'Pos ('L')), C.winnt.WCHAR'Val (0)); type NtQueryInformationProcess_Type is access function ( ProcessHandle : C.winnt.HANDLE; ProcessInformationClass : C.winternl.PROCESSINFOCLASS; ProcessInformation : C.winnt.PVOID; ProcessInformationLength : C.windef.ULONG; ReturnLength : access C.windef.ULONG) return C.winternl.NTSTATUS with Convention => WINAPI; NtQueryInformationProcess_Name : constant C.char_array (0 .. 25) := "NtQueryInformationProcess" & C.char'Val (0); -- implementation function Load_Address return Address is function To_NtQueryInformationProcess_Type is new Ada.Unchecked_Conversion ( C.windef.FARPROC, NtQueryInformationProcess_Type); NtQueryInformationProcess : NtQueryInformationProcess_Type; begin NtQueryInformationProcess := To_NtQueryInformationProcess_Type ( C.winbase.GetProcAddress ( NTDLL, NtQueryInformationProcess_Name (0)'Access)); if NtQueryInformationProcess = null then return Null_Address; -- ??? else declare PBI : aliased C.winternl.PROCESS_BASIC_INFORMATION; ReturnLength : aliased C.windef.ULONG; Dummy_Status : C.winternl.NTSTATUS; PEB : C.winternl.PPEB; begin Dummy_Status := NtQueryInformationProcess ( C.winbase.GetCurrentProcess, C.winternl.ProcessBasicInformation, C.windef.LPVOID (PBI'Address), C.winternl.PROCESS_BASIC_INFORMATION'Size / Standard'Storage_Unit, ReturnLength'Access); PEB := PBI.PebBaseAddress; -- process environment block return Address (PEB.Reserved3 (1)); end; end if; end Load_Address; function NTDLL return C.windef.HMODULE is begin return C.winbase.GetModuleHandle (NTDLL_DLL (0)'Access); end NTDLL; end System.Storage_Map;
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 fibo is type stringptr is access all char_array; 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; -- --La suite de fibonaci -- function fibo0(a : in Integer; b : in Integer; i : in Integer) return Integer is tmp : Integer; out0 : Integer; b2 : Integer; a2 : Integer; begin out0 := 0; a2 := a; b2 := b; for j in integer range 0..i + 1 loop out0 := out0 + a2; tmp := b2; b2 := b2 + a2; a2 := tmp; end loop; return out0; end; i : Integer; b : Integer; a : Integer; begin Get(a); SkipSpaces; Get(b); SkipSpaces; Get(i); PInt(fibo0(a, b, i)); end;
pragma License (Unrestricted); with Ada.Containers; with Ada.Strings.Wide_Hash; function Ada.Strings.Wide_Fixed.Wide_Hash (Key : Wide_String) return Containers.Hash_Type renames Strings.Wide_Hash; pragma Pure (Ada.Strings.Wide_Fixed.Wide_Hash);
package Standard_Subtypes is subtype Double_Type is Standard.Long_Float; subtype Scalar is Double_Type; end Standard_Subtypes;
pragma Warnings (Off); pragma Ada_95; with System; package ada_main is gnat_argc : Integer; gnat_argv : System.Address; gnat_envp : System.Address; pragma Import (C, gnat_argc); pragma Import (C, gnat_argv); pragma Import (C, gnat_envp); gnat_exit_status : Integer; pragma Import (C, gnat_exit_status); GNAT_Version : constant String := "GNAT Version: GPL 2017 (20170515-63)" & ASCII.NUL; pragma Export (C, GNAT_Version, "__gnat_version"); Ada_Main_Program_Name : constant String := "_ada_main" & ASCII.NUL; pragma Export (C, Ada_Main_Program_Name, "__gnat_ada_main_program_name"); procedure adainit; pragma Export (C, adainit, "adainit"); procedure adafinal; pragma Export (C, adafinal, "adafinal"); function main (argc : Integer; argv : System.Address; envp : System.Address) return Integer; pragma Export (C, main, "main"); type Version_32 is mod 2 ** 32; u00001 : constant Version_32 := 16#d38f2cda#; pragma Export (C, u00001, "mainB"); u00002 : constant Version_32 := 16#b6df930e#; pragma Export (C, u00002, "system__standard_libraryB"); u00003 : constant Version_32 := 16#0a55feef#; pragma Export (C, u00003, "system__standard_libraryS"); u00004 : constant Version_32 := 16#76789da1#; pragma Export (C, u00004, "adaS"); u00005 : constant Version_32 := 16#0d7f1a43#; pragma Export (C, u00005, "ada__calendarB"); u00006 : constant Version_32 := 16#5b279c75#; pragma Export (C, u00006, "ada__calendarS"); u00007 : constant Version_32 := 16#85a06f66#; pragma Export (C, u00007, "ada__exceptionsB"); u00008 : constant Version_32 := 16#1a0dcc03#; pragma Export (C, u00008, "ada__exceptionsS"); u00009 : constant Version_32 := 16#e947e6a9#; pragma Export (C, u00009, "ada__exceptions__last_chance_handlerB"); u00010 : constant Version_32 := 16#41e5552e#; pragma Export (C, u00010, "ada__exceptions__last_chance_handlerS"); u00011 : constant Version_32 := 16#32a08138#; pragma Export (C, u00011, "systemS"); u00012 : constant Version_32 := 16#4e7785b8#; pragma Export (C, u00012, "system__soft_linksB"); u00013 : constant Version_32 := 16#ac24596d#; pragma Export (C, u00013, "system__soft_linksS"); u00014 : constant Version_32 := 16#b01dad17#; pragma Export (C, u00014, "system__parametersB"); u00015 : constant Version_32 := 16#4c8a8c47#; pragma Export (C, u00015, "system__parametersS"); u00016 : constant Version_32 := 16#30ad09e5#; pragma Export (C, u00016, "system__secondary_stackB"); u00017 : constant Version_32 := 16#88327e42#; pragma Export (C, u00017, "system__secondary_stackS"); u00018 : constant Version_32 := 16#f103f468#; pragma Export (C, u00018, "system__storage_elementsB"); u00019 : constant Version_32 := 16#1f63cb3c#; pragma Export (C, u00019, "system__storage_elementsS"); u00020 : constant Version_32 := 16#41837d1e#; pragma Export (C, u00020, "system__stack_checkingB"); u00021 : constant Version_32 := 16#bc1fead0#; pragma Export (C, u00021, "system__stack_checkingS"); u00022 : constant Version_32 := 16#87a448ff#; pragma Export (C, u00022, "system__exception_tableB"); u00023 : constant Version_32 := 16#6f0ee87a#; pragma Export (C, u00023, "system__exception_tableS"); u00024 : constant Version_32 := 16#ce4af020#; pragma Export (C, u00024, "system__exceptionsB"); u00025 : constant Version_32 := 16#5ac3ecce#; pragma Export (C, u00025, "system__exceptionsS"); u00026 : constant Version_32 := 16#80916427#; pragma Export (C, u00026, "system__exceptions__machineB"); u00027 : constant Version_32 := 16#047ef179#; pragma Export (C, u00027, "system__exceptions__machineS"); u00028 : constant Version_32 := 16#aa0563fc#; pragma Export (C, u00028, "system__exceptions_debugB"); u00029 : constant Version_32 := 16#4c2a78fc#; pragma Export (C, u00029, "system__exceptions_debugS"); u00030 : constant Version_32 := 16#6c2f8802#; pragma Export (C, u00030, "system__img_intB"); u00031 : constant Version_32 := 16#307b61fa#; pragma Export (C, u00031, "system__img_intS"); u00032 : constant Version_32 := 16#39df8c17#; pragma Export (C, u00032, "system__tracebackB"); u00033 : constant Version_32 := 16#6c825ffc#; pragma Export (C, u00033, "system__tracebackS"); u00034 : constant Version_32 := 16#9ed49525#; pragma Export (C, u00034, "system__traceback_entriesB"); u00035 : constant Version_32 := 16#32fb7748#; pragma Export (C, u00035, "system__traceback_entriesS"); u00036 : constant Version_32 := 16#18d5fcc5#; pragma Export (C, u00036, "system__traceback__symbolicB"); u00037 : constant Version_32 := 16#9df1ae6d#; pragma Export (C, u00037, "system__traceback__symbolicS"); u00038 : constant Version_32 := 16#179d7d28#; pragma Export (C, u00038, "ada__containersS"); u00039 : constant Version_32 := 16#701f9d88#; pragma Export (C, u00039, "ada__exceptions__tracebackB"); u00040 : constant Version_32 := 16#20245e75#; pragma Export (C, u00040, "ada__exceptions__tracebackS"); u00041 : constant Version_32 := 16#e865e681#; pragma Export (C, u00041, "system__bounded_stringsB"); u00042 : constant Version_32 := 16#455da021#; pragma Export (C, u00042, "system__bounded_stringsS"); u00043 : constant Version_32 := 16#42315736#; pragma Export (C, u00043, "system__crtlS"); u00044 : constant Version_32 := 16#08e0d717#; pragma Export (C, u00044, "system__dwarf_linesB"); u00045 : constant Version_32 := 16#b1bd2788#; pragma Export (C, u00045, "system__dwarf_linesS"); u00046 : constant Version_32 := 16#5b4659fa#; pragma Export (C, u00046, "ada__charactersS"); u00047 : constant Version_32 := 16#8f637df8#; pragma Export (C, u00047, "ada__characters__handlingB"); u00048 : constant Version_32 := 16#3b3f6154#; pragma Export (C, u00048, "ada__characters__handlingS"); u00049 : constant Version_32 := 16#4b7bb96a#; pragma Export (C, u00049, "ada__characters__latin_1S"); u00050 : constant Version_32 := 16#e6d4fa36#; pragma Export (C, u00050, "ada__stringsS"); u00051 : constant Version_32 := 16#e2ea8656#; pragma Export (C, u00051, "ada__strings__mapsB"); u00052 : constant Version_32 := 16#1e526bec#; pragma Export (C, u00052, "ada__strings__mapsS"); u00053 : constant Version_32 := 16#9dc9b435#; pragma Export (C, u00053, "system__bit_opsB"); u00054 : constant Version_32 := 16#0765e3a3#; pragma Export (C, u00054, "system__bit_opsS"); u00055 : constant Version_32 := 16#0626fdbb#; pragma Export (C, u00055, "system__unsigned_typesS"); u00056 : constant Version_32 := 16#92f05f13#; pragma Export (C, u00056, "ada__strings__maps__constantsS"); u00057 : constant Version_32 := 16#5ab55268#; pragma Export (C, u00057, "interfacesS"); u00058 : constant Version_32 := 16#9f00b3d3#; pragma Export (C, u00058, "system__address_imageB"); u00059 : constant Version_32 := 16#934c1c02#; pragma Export (C, u00059, "system__address_imageS"); u00060 : constant Version_32 := 16#ec78c2bf#; pragma Export (C, u00060, "system__img_unsB"); u00061 : constant Version_32 := 16#99d2c14c#; pragma Export (C, u00061, "system__img_unsS"); u00062 : constant Version_32 := 16#d7aac20c#; pragma Export (C, u00062, "system__ioB"); u00063 : constant Version_32 := 16#ace27677#; pragma Export (C, u00063, "system__ioS"); u00064 : constant Version_32 := 16#11faaec1#; pragma Export (C, u00064, "system__mmapB"); u00065 : constant Version_32 := 16#08d13e5f#; pragma Export (C, u00065, "system__mmapS"); u00066 : constant Version_32 := 16#92d882c5#; pragma Export (C, u00066, "ada__io_exceptionsS"); u00067 : constant Version_32 := 16#9d8ecedc#; pragma Export (C, u00067, "system__mmap__os_interfaceB"); u00068 : constant Version_32 := 16#8f4541b8#; pragma Export (C, u00068, "system__mmap__os_interfaceS"); u00069 : constant Version_32 := 16#54632e7c#; pragma Export (C, u00069, "system__os_libB"); u00070 : constant Version_32 := 16#ed466fde#; pragma Export (C, u00070, "system__os_libS"); u00071 : constant Version_32 := 16#d1060688#; pragma Export (C, u00071, "system__case_utilB"); u00072 : constant Version_32 := 16#16a9e8ef#; pragma Export (C, u00072, "system__case_utilS"); u00073 : constant Version_32 := 16#2a8e89ad#; pragma Export (C, u00073, "system__stringsB"); u00074 : constant Version_32 := 16#4c1f905e#; pragma Export (C, u00074, "system__stringsS"); u00075 : constant Version_32 := 16#769e25e6#; pragma Export (C, u00075, "interfaces__cB"); u00076 : constant Version_32 := 16#70be4e8c#; pragma Export (C, u00076, "interfaces__cS"); u00077 : constant Version_32 := 16#d0bc914c#; pragma Export (C, u00077, "system__object_readerB"); u00078 : constant Version_32 := 16#7f932442#; pragma Export (C, u00078, "system__object_readerS"); u00079 : constant Version_32 := 16#1a74a354#; pragma Export (C, u00079, "system__val_lliB"); u00080 : constant Version_32 := 16#a8846798#; pragma Export (C, u00080, "system__val_lliS"); u00081 : constant Version_32 := 16#afdbf393#; pragma Export (C, u00081, "system__val_lluB"); u00082 : constant Version_32 := 16#7cd4aac9#; pragma Export (C, u00082, "system__val_lluS"); u00083 : constant Version_32 := 16#27b600b2#; pragma Export (C, u00083, "system__val_utilB"); u00084 : constant Version_32 := 16#9e0037c6#; pragma Export (C, u00084, "system__val_utilS"); u00085 : constant Version_32 := 16#5bbc3f2f#; pragma Export (C, u00085, "system__exception_tracesB"); u00086 : constant Version_32 := 16#167fa1a2#; pragma Export (C, u00086, "system__exception_tracesS"); u00087 : constant Version_32 := 16#d178f226#; pragma Export (C, u00087, "system__win32S"); u00088 : constant Version_32 := 16#8c33a517#; pragma Export (C, u00088, "system__wch_conB"); u00089 : constant Version_32 := 16#29dda3ea#; pragma Export (C, u00089, "system__wch_conS"); u00090 : constant Version_32 := 16#9721e840#; pragma Export (C, u00090, "system__wch_stwB"); u00091 : constant Version_32 := 16#04cc8feb#; pragma Export (C, u00091, "system__wch_stwS"); u00092 : constant Version_32 := 16#a831679c#; pragma Export (C, u00092, "system__wch_cnvB"); u00093 : constant Version_32 := 16#266a1919#; pragma Export (C, u00093, "system__wch_cnvS"); u00094 : constant Version_32 := 16#ece6fdb6#; pragma Export (C, u00094, "system__wch_jisB"); u00095 : constant Version_32 := 16#a61a0038#; pragma Export (C, u00095, "system__wch_jisS"); u00096 : constant Version_32 := 16#a99e1d66#; pragma Export (C, u00096, "system__os_primitivesB"); u00097 : constant Version_32 := 16#b82f904e#; pragma Export (C, u00097, "system__os_primitivesS"); u00098 : constant Version_32 := 16#b6166bc6#; pragma Export (C, u00098, "system__task_lockB"); u00099 : constant Version_32 := 16#532ab656#; pragma Export (C, u00099, "system__task_lockS"); u00100 : constant Version_32 := 16#1a9147da#; pragma Export (C, u00100, "system__win32__extS"); u00101 : constant Version_32 := 16#f64b89a4#; pragma Export (C, u00101, "ada__integer_text_ioB"); u00102 : constant Version_32 := 16#b85ee1d1#; pragma Export (C, u00102, "ada__integer_text_ioS"); u00103 : constant Version_32 := 16#1d1c6062#; pragma Export (C, u00103, "ada__text_ioB"); u00104 : constant Version_32 := 16#95711eac#; pragma Export (C, u00104, "ada__text_ioS"); u00105 : constant Version_32 := 16#10558b11#; pragma Export (C, u00105, "ada__streamsB"); u00106 : constant Version_32 := 16#67e31212#; pragma Export (C, u00106, "ada__streamsS"); u00107 : constant Version_32 := 16#d85792d6#; pragma Export (C, u00107, "ada__tagsB"); u00108 : constant Version_32 := 16#8813468c#; pragma Export (C, u00108, "ada__tagsS"); u00109 : constant Version_32 := 16#c3335bfd#; pragma Export (C, u00109, "system__htableB"); u00110 : constant Version_32 := 16#b66232d2#; pragma Export (C, u00110, "system__htableS"); u00111 : constant Version_32 := 16#089f5cd0#; pragma Export (C, u00111, "system__string_hashB"); u00112 : constant Version_32 := 16#143c59ac#; pragma Export (C, u00112, "system__string_hashS"); u00113 : constant Version_32 := 16#1d9142a4#; pragma Export (C, u00113, "system__val_unsB"); u00114 : constant Version_32 := 16#168e1080#; pragma Export (C, u00114, "system__val_unsS"); u00115 : constant Version_32 := 16#4c01b69c#; pragma Export (C, u00115, "interfaces__c_streamsB"); u00116 : constant Version_32 := 16#b1330297#; pragma Export (C, u00116, "interfaces__c_streamsS"); u00117 : constant Version_32 := 16#6f0d52aa#; pragma Export (C, u00117, "system__file_ioB"); u00118 : constant Version_32 := 16#95d1605d#; pragma Export (C, u00118, "system__file_ioS"); u00119 : constant Version_32 := 16#86c56e5a#; pragma Export (C, u00119, "ada__finalizationS"); u00120 : constant Version_32 := 16#95817ed8#; pragma Export (C, u00120, "system__finalization_rootB"); u00121 : constant Version_32 := 16#7d52f2a8#; pragma Export (C, u00121, "system__finalization_rootS"); u00122 : constant Version_32 := 16#cf3f1b90#; pragma Export (C, u00122, "system__file_control_blockS"); u00123 : constant Version_32 := 16#f6fdca1c#; pragma Export (C, u00123, "ada__text_io__integer_auxB"); u00124 : constant Version_32 := 16#b9793d30#; pragma Export (C, u00124, "ada__text_io__integer_auxS"); u00125 : constant Version_32 := 16#181dc502#; pragma Export (C, u00125, "ada__text_io__generic_auxB"); u00126 : constant Version_32 := 16#a6c327d3#; pragma Export (C, u00126, "ada__text_io__generic_auxS"); u00127 : constant Version_32 := 16#b10ba0c7#; pragma Export (C, u00127, "system__img_biuB"); u00128 : constant Version_32 := 16#c00475f6#; pragma Export (C, u00128, "system__img_biuS"); u00129 : constant Version_32 := 16#4e06ab0c#; pragma Export (C, u00129, "system__img_llbB"); u00130 : constant Version_32 := 16#81c36508#; pragma Export (C, u00130, "system__img_llbS"); u00131 : constant Version_32 := 16#9dca6636#; pragma Export (C, u00131, "system__img_lliB"); u00132 : constant Version_32 := 16#23efd4e9#; pragma Export (C, u00132, "system__img_lliS"); u00133 : constant Version_32 := 16#a756d097#; pragma Export (C, u00133, "system__img_llwB"); u00134 : constant Version_32 := 16#28af469e#; pragma Export (C, u00134, "system__img_llwS"); u00135 : constant Version_32 := 16#eb55dfbb#; pragma Export (C, u00135, "system__img_wiuB"); u00136 : constant Version_32 := 16#ae45f264#; pragma Export (C, u00136, "system__img_wiuS"); u00137 : constant Version_32 := 16#d763507a#; pragma Export (C, u00137, "system__val_intB"); u00138 : constant Version_32 := 16#7a05ab07#; pragma Export (C, u00138, "system__val_intS"); u00139 : constant Version_32 := 16#03fc996e#; pragma Export (C, u00139, "ada__real_timeB"); u00140 : constant Version_32 := 16#c3d451b0#; pragma Export (C, u00140, "ada__real_timeS"); u00141 : constant Version_32 := 16#cb56a7b3#; pragma Export (C, u00141, "system__taskingB"); u00142 : constant Version_32 := 16#70384b95#; pragma Export (C, u00142, "system__taskingS"); u00143 : constant Version_32 := 16#c71f56c0#; pragma Export (C, u00143, "system__task_primitivesS"); u00144 : constant Version_32 := 16#fa769fc7#; pragma Export (C, u00144, "system__os_interfaceS"); u00145 : constant Version_32 := 16#22b0e2af#; pragma Export (C, u00145, "interfaces__c__stringsB"); u00146 : constant Version_32 := 16#603c1c44#; pragma Export (C, u00146, "interfaces__c__stringsS"); u00147 : constant Version_32 := 16#fc754292#; pragma Export (C, u00147, "system__task_primitives__operationsB"); u00148 : constant Version_32 := 16#24684c98#; pragma Export (C, u00148, "system__task_primitives__operationsS"); u00149 : constant Version_32 := 16#1b28662b#; pragma Export (C, u00149, "system__float_controlB"); u00150 : constant Version_32 := 16#d25cc204#; pragma Export (C, u00150, "system__float_controlS"); u00151 : constant Version_32 := 16#da8ccc08#; pragma Export (C, u00151, "system__interrupt_managementB"); u00152 : constant Version_32 := 16#0f60a80c#; pragma Export (C, u00152, "system__interrupt_managementS"); u00153 : constant Version_32 := 16#f65595cf#; pragma Export (C, u00153, "system__multiprocessorsB"); u00154 : constant Version_32 := 16#0a0c1e4b#; pragma Export (C, u00154, "system__multiprocessorsS"); u00155 : constant Version_32 := 16#77769007#; pragma Export (C, u00155, "system__task_infoB"); u00156 : constant Version_32 := 16#e54688cf#; pragma Export (C, u00156, "system__task_infoS"); u00157 : constant Version_32 := 16#9471a5c6#; pragma Export (C, u00157, "system__tasking__debugB"); u00158 : constant Version_32 := 16#f1f2435f#; pragma Export (C, u00158, "system__tasking__debugS"); u00159 : constant Version_32 := 16#fd83e873#; pragma Export (C, u00159, "system__concat_2B"); u00160 : constant Version_32 := 16#300056e8#; pragma Export (C, u00160, "system__concat_2S"); u00161 : constant Version_32 := 16#2b70b149#; pragma Export (C, u00161, "system__concat_3B"); u00162 : constant Version_32 := 16#39d0dd9d#; pragma Export (C, u00162, "system__concat_3S"); u00163 : constant Version_32 := 16#18e0e51c#; pragma Export (C, u00163, "system__img_enum_newB"); u00164 : constant Version_32 := 16#53ec87f8#; pragma Export (C, u00164, "system__img_enum_newS"); u00165 : constant Version_32 := 16#118e865d#; pragma Export (C, u00165, "system__stack_usageB"); u00166 : constant Version_32 := 16#3a3ac346#; pragma Export (C, u00166, "system__stack_usageS"); u00167 : constant Version_32 := 16#3791e504#; pragma Export (C, u00167, "ada__strings__unboundedB"); u00168 : constant Version_32 := 16#9fdb1809#; pragma Export (C, u00168, "ada__strings__unboundedS"); u00169 : constant Version_32 := 16#144f64ae#; pragma Export (C, u00169, "ada__strings__searchB"); u00170 : constant Version_32 := 16#c1ab8667#; pragma Export (C, u00170, "ada__strings__searchS"); u00171 : constant Version_32 := 16#933d1555#; pragma Export (C, u00171, "system__compare_array_unsigned_8B"); u00172 : constant Version_32 := 16#9ba3f0b5#; pragma Export (C, u00172, "system__compare_array_unsigned_8S"); u00173 : constant Version_32 := 16#97d13ec4#; pragma Export (C, u00173, "system__address_operationsB"); u00174 : constant Version_32 := 16#21ac3f0b#; pragma Export (C, u00174, "system__address_operationsS"); u00175 : constant Version_32 := 16#a2250034#; pragma Export (C, u00175, "system__storage_pools__subpoolsB"); u00176 : constant Version_32 := 16#cc5a1856#; pragma Export (C, u00176, "system__storage_pools__subpoolsS"); u00177 : constant Version_32 := 16#6abe5dbe#; pragma Export (C, u00177, "system__finalization_mastersB"); u00178 : constant Version_32 := 16#695cb8f2#; pragma Export (C, u00178, "system__finalization_mastersS"); u00179 : constant Version_32 := 16#7268f812#; pragma Export (C, u00179, "system__img_boolB"); u00180 : constant Version_32 := 16#c779f0d3#; pragma Export (C, u00180, "system__img_boolS"); u00181 : constant Version_32 := 16#6d4d969a#; pragma Export (C, u00181, "system__storage_poolsB"); u00182 : constant Version_32 := 16#114d1f95#; pragma Export (C, u00182, "system__storage_poolsS"); u00183 : constant Version_32 := 16#9aad1ff1#; pragma Export (C, u00183, "system__storage_pools__subpools__finalizationB"); u00184 : constant Version_32 := 16#fe2f4b3a#; pragma Export (C, u00184, "system__storage_pools__subpools__finalizationS"); u00185 : constant Version_32 := 16#70f25dad#; pragma Export (C, u00185, "system__atomic_countersB"); u00186 : constant Version_32 := 16#86fcacb5#; pragma Export (C, u00186, "system__atomic_countersS"); u00187 : constant Version_32 := 16#5fc82639#; pragma Export (C, u00187, "system__machine_codeS"); u00188 : constant Version_32 := 16#3c420900#; pragma Export (C, u00188, "system__stream_attributesB"); u00189 : constant Version_32 := 16#8bc30a4e#; pragma Export (C, u00189, "system__stream_attributesS"); u00190 : constant Version_32 := 16#97a2d3b4#; pragma Export (C, u00190, "ada__strings__unbounded__text_ioB"); u00191 : constant Version_32 := 16#f26abf4c#; pragma Export (C, u00191, "ada__strings__unbounded__text_ioS"); u00192 : constant Version_32 := 16#64b60562#; pragma Export (C, u00192, "p_stephandlerB"); u00193 : constant Version_32 := 16#c35ffe0a#; pragma Export (C, u00193, "p_stephandlerS"); u00194 : constant Version_32 := 16#a9261bbe#; pragma Export (C, u00194, "p_structuraltypesB"); u00195 : constant Version_32 := 16#386e2dac#; pragma Export (C, u00195, "p_structuraltypesS"); u00196 : constant Version_32 := 16#a347755d#; pragma Export (C, u00196, "ada__text_io__modular_auxB"); u00197 : constant Version_32 := 16#0d2bef47#; pragma Export (C, u00197, "ada__text_io__modular_auxS"); u00198 : constant Version_32 := 16#3e932977#; pragma Export (C, u00198, "system__img_lluB"); u00199 : constant Version_32 := 16#4feffd78#; pragma Export (C, u00199, "system__img_lluS"); u00200 : constant Version_32 := 16#23e4cea4#; pragma Export (C, u00200, "interfaces__cobolB"); u00201 : constant Version_32 := 16#394647ba#; pragma Export (C, u00201, "interfaces__cobolS"); u00202 : constant Version_32 := 16#5a895de2#; pragma Export (C, u00202, "system__pool_globalB"); u00203 : constant Version_32 := 16#7141203e#; pragma Export (C, u00203, "system__pool_globalS"); u00204 : constant Version_32 := 16#ee101ba4#; pragma Export (C, u00204, "system__memoryB"); u00205 : constant Version_32 := 16#6bdde70c#; pragma Export (C, u00205, "system__memoryS"); u00206 : constant Version_32 := 16#3adf5e61#; pragma Export (C, u00206, "p_stephandler__feistelhandlerB"); u00207 : constant Version_32 := 16#8e57995f#; pragma Export (C, u00207, "p_stephandler__feistelhandlerS"); u00208 : constant Version_32 := 16#e76fa629#; pragma Export (C, u00208, "p_stephandler__inputhandlerB"); u00209 : constant Version_32 := 16#abe41686#; pragma Export (C, u00209, "p_stephandler__inputhandlerS"); u00210 : constant Version_32 := 16#4b3cf578#; pragma Export (C, u00210, "system__byte_swappingS"); u00211 : constant Version_32 := 16#796b5f0d#; pragma Export (C, u00211, "system__sequential_ioB"); u00212 : constant Version_32 := 16#d8cc2bc8#; pragma Export (C, u00212, "system__sequential_ioS"); u00213 : constant Version_32 := 16#0806edc3#; pragma Export (C, u00213, "system__strings__stream_opsB"); u00214 : constant Version_32 := 16#55d4bd57#; pragma Export (C, u00214, "system__strings__stream_opsS"); u00215 : constant Version_32 := 16#17411e58#; pragma Export (C, u00215, "ada__streams__stream_ioB"); u00216 : constant Version_32 := 16#31fc8e02#; pragma Export (C, u00216, "ada__streams__stream_ioS"); u00217 : constant Version_32 := 16#5de653db#; pragma Export (C, u00217, "system__communicationB"); u00218 : constant Version_32 := 16#2bc0d4ea#; pragma Export (C, u00218, "system__communicationS"); u00219 : constant Version_32 := 16#8500a3df#; pragma Export (C, u00219, "p_stephandler__iphandlerB"); u00220 : constant Version_32 := 16#780e2d9b#; pragma Export (C, u00220, "p_stephandler__iphandlerS"); u00221 : constant Version_32 := 16#c0587cca#; pragma Export (C, u00221, "p_stephandler__keyhandlerB"); u00222 : constant Version_32 := 16#3666019b#; pragma Export (C, u00222, "p_stephandler__keyhandlerS"); u00223 : constant Version_32 := 16#13b3baa7#; pragma Export (C, u00223, "p_stephandler__outputhandlerB"); u00224 : constant Version_32 := 16#3db246c7#; pragma Export (C, u00224, "p_stephandler__outputhandlerS"); u00225 : constant Version_32 := 16#290d89e9#; pragma Export (C, u00225, "p_stephandler__reverseiphandlerB"); u00226 : constant Version_32 := 16#f3f8e71c#; pragma Export (C, u00226, "p_stephandler__reverseiphandlerS"); u00227 : constant Version_32 := 16#276453b7#; pragma Export (C, u00227, "system__img_lldB"); u00228 : constant Version_32 := 16#c1828851#; pragma Export (C, u00228, "system__img_lldS"); u00229 : constant Version_32 := 16#bd3715ff#; pragma Export (C, u00229, "system__img_decB"); u00230 : constant Version_32 := 16#9c8d88e3#; pragma Export (C, u00230, "system__img_decS"); u00231 : constant Version_32 := 16#96bbd7c2#; pragma Export (C, u00231, "system__tasking__rendezvousB"); u00232 : constant Version_32 := 16#ea18a31e#; pragma Export (C, u00232, "system__tasking__rendezvousS"); u00233 : constant Version_32 := 16#100eaf58#; pragma Export (C, u00233, "system__restrictionsB"); u00234 : constant Version_32 := 16#c1c3a556#; pragma Export (C, u00234, "system__restrictionsS"); u00235 : constant Version_32 := 16#6896b958#; pragma Export (C, u00235, "system__tasking__entry_callsB"); u00236 : constant Version_32 := 16#df420580#; pragma Export (C, u00236, "system__tasking__entry_callsS"); u00237 : constant Version_32 := 16#bc23950c#; pragma Export (C, u00237, "system__tasking__initializationB"); u00238 : constant Version_32 := 16#efd25374#; pragma Export (C, u00238, "system__tasking__initializationS"); u00239 : constant Version_32 := 16#72fc64c4#; pragma Export (C, u00239, "system__soft_links__taskingB"); u00240 : constant Version_32 := 16#5ae92880#; pragma Export (C, u00240, "system__soft_links__taskingS"); u00241 : constant Version_32 := 16#17d21067#; pragma Export (C, u00241, "ada__exceptions__is_null_occurrenceB"); u00242 : constant Version_32 := 16#e1d7566f#; pragma Export (C, u00242, "ada__exceptions__is_null_occurrenceS"); u00243 : constant Version_32 := 16#e774edef#; pragma Export (C, u00243, "system__tasking__task_attributesB"); u00244 : constant Version_32 := 16#6bc95a13#; pragma Export (C, u00244, "system__tasking__task_attributesS"); u00245 : constant Version_32 := 16#8bdfec1d#; pragma Export (C, u00245, "system__tasking__protected_objectsB"); u00246 : constant Version_32 := 16#a9001c61#; pragma Export (C, u00246, "system__tasking__protected_objectsS"); u00247 : constant Version_32 := 16#ee80728a#; pragma Export (C, u00247, "system__tracesB"); u00248 : constant Version_32 := 16#c0bde992#; pragma Export (C, u00248, "system__tracesS"); u00249 : constant Version_32 := 16#17aa7da7#; pragma Export (C, u00249, "system__tasking__protected_objects__entriesB"); u00250 : constant Version_32 := 16#427cf21f#; pragma Export (C, u00250, "system__tasking__protected_objects__entriesS"); u00251 : constant Version_32 := 16#1dc86ab7#; pragma Export (C, u00251, "system__tasking__protected_objects__operationsB"); u00252 : constant Version_32 := 16#ba36ad85#; pragma Export (C, u00252, "system__tasking__protected_objects__operationsS"); u00253 : constant Version_32 := 16#ab2f8f51#; pragma Export (C, u00253, "system__tasking__queuingB"); u00254 : constant Version_32 := 16#d1ba2fcb#; pragma Export (C, u00254, "system__tasking__queuingS"); u00255 : constant Version_32 := 16#f9053daa#; pragma Export (C, u00255, "system__tasking__utilitiesB"); u00256 : constant Version_32 := 16#14a33d48#; pragma Export (C, u00256, "system__tasking__utilitiesS"); u00257 : constant Version_32 := 16#bd6fc52e#; pragma Export (C, u00257, "system__traces__taskingB"); u00258 : constant Version_32 := 16#09f07b39#; pragma Export (C, u00258, "system__traces__taskingS"); u00259 : constant Version_32 := 16#d8fc9f88#; pragma Export (C, u00259, "system__tasking__stagesB"); u00260 : constant Version_32 := 16#e9cef940#; pragma Export (C, u00260, "system__tasking__stagesS"); -- BEGIN ELABORATION ORDER -- ada%s -- ada.characters%s -- ada.characters.latin_1%s -- interfaces%s -- system%s -- system.address_operations%s -- system.address_operations%b -- system.byte_swapping%s -- system.case_util%s -- system.case_util%b -- system.float_control%s -- system.float_control%b -- system.img_bool%s -- system.img_bool%b -- system.img_enum_new%s -- system.img_enum_new%b -- system.img_int%s -- system.img_int%b -- system.img_dec%s -- system.img_dec%b -- system.img_lli%s -- system.img_lli%b -- system.img_lld%s -- system.img_lld%b -- system.io%s -- system.io%b -- system.machine_code%s -- system.atomic_counters%s -- system.atomic_counters%b -- system.parameters%s -- system.parameters%b -- system.crtl%s -- interfaces.c_streams%s -- interfaces.c_streams%b -- system.restrictions%s -- system.restrictions%b -- system.storage_elements%s -- system.storage_elements%b -- system.stack_checking%s -- system.stack_checking%b -- system.stack_usage%s -- system.stack_usage%b -- system.string_hash%s -- system.string_hash%b -- system.htable%s -- system.htable%b -- system.strings%s -- system.strings%b -- system.traceback_entries%s -- system.traceback_entries%b -- system.traces%s -- system.traces%b -- system.unsigned_types%s -- system.img_biu%s -- system.img_biu%b -- system.img_llb%s -- system.img_llb%b -- system.img_llu%s -- system.img_llu%b -- system.img_llw%s -- system.img_llw%b -- system.img_uns%s -- system.img_uns%b -- system.img_wiu%s -- system.img_wiu%b -- system.wch_con%s -- system.wch_con%b -- system.wch_jis%s -- system.wch_jis%b -- system.wch_cnv%s -- system.wch_cnv%b -- system.compare_array_unsigned_8%s -- system.compare_array_unsigned_8%b -- system.concat_2%s -- system.concat_2%b -- system.concat_3%s -- system.concat_3%b -- system.traceback%s -- system.traceback%b -- system.val_util%s -- system.standard_library%s -- system.exception_traces%s -- ada.exceptions%s -- system.wch_stw%s -- system.val_util%b -- system.val_llu%s -- system.val_lli%s -- system.os_lib%s -- system.bit_ops%s -- ada.characters.handling%s -- ada.exceptions.traceback%s -- system.soft_links%s -- system.exception_table%s -- system.exception_table%b -- ada.io_exceptions%s -- ada.strings%s -- ada.containers%s -- system.exceptions%s -- system.exceptions%b -- system.secondary_stack%s -- system.address_image%s -- system.bounded_strings%s -- system.soft_links%b -- ada.exceptions.last_chance_handler%s -- system.exceptions_debug%s -- system.exceptions_debug%b -- system.exception_traces%b -- system.memory%s -- system.memory%b -- system.wch_stw%b -- system.val_llu%b -- system.val_lli%b -- interfaces.c%s -- system.win32%s -- system.mmap%s -- system.mmap.os_interface%s -- system.mmap.os_interface%b -- system.mmap%b -- system.os_lib%b -- system.bit_ops%b -- ada.strings.maps%s -- ada.strings.maps.constants%s -- ada.characters.handling%b -- ada.exceptions.traceback%b -- system.exceptions.machine%s -- system.exceptions.machine%b -- system.secondary_stack%b -- system.address_image%b -- system.bounded_strings%b -- ada.exceptions.last_chance_handler%b -- system.standard_library%b -- system.object_reader%s -- system.dwarf_lines%s -- system.dwarf_lines%b -- interfaces.c%b -- ada.strings.maps%b -- system.traceback.symbolic%s -- system.traceback.symbolic%b -- ada.exceptions%b -- system.object_reader%b -- ada.exceptions.is_null_occurrence%s -- ada.exceptions.is_null_occurrence%b -- ada.strings.search%s -- ada.strings.search%b -- interfaces.c.strings%s -- interfaces.c.strings%b -- interfaces.cobol%s -- interfaces.cobol%b -- system.multiprocessors%s -- system.multiprocessors%b -- system.os_interface%s -- system.interrupt_management%s -- system.interrupt_management%b -- system.task_info%s -- system.task_info%b -- system.task_lock%s -- system.task_lock%b -- system.task_primitives%s -- system.val_uns%s -- system.val_uns%b -- ada.tags%s -- ada.tags%b -- ada.streams%s -- ada.streams%b -- system.communication%s -- system.communication%b -- system.file_control_block%s -- system.finalization_root%s -- system.finalization_root%b -- ada.finalization%s -- system.file_io%s -- system.file_io%b -- ada.streams.stream_io%s -- ada.streams.stream_io%b -- system.storage_pools%s -- system.storage_pools%b -- system.finalization_masters%s -- system.finalization_masters%b -- system.storage_pools.subpools%s -- system.storage_pools.subpools.finalization%s -- system.storage_pools.subpools%b -- system.storage_pools.subpools.finalization%b -- system.stream_attributes%s -- system.stream_attributes%b -- ada.strings.unbounded%s -- ada.strings.unbounded%b -- system.val_int%s -- system.val_int%b -- system.win32.ext%s -- system.os_primitives%s -- system.os_primitives%b -- system.tasking%s -- system.task_primitives.operations%s -- system.tasking.debug%s -- system.tasking%b -- system.task_primitives.operations%b -- system.tasking.debug%b -- system.traces.tasking%s -- system.traces.tasking%b -- ada.calendar%s -- ada.calendar%b -- ada.real_time%s -- ada.real_time%b -- ada.text_io%s -- ada.text_io%b -- ada.strings.unbounded.text_io%s -- ada.strings.unbounded.text_io%b -- ada.text_io.generic_aux%s -- ada.text_io.generic_aux%b -- ada.text_io.integer_aux%s -- ada.text_io.integer_aux%b -- ada.integer_text_io%s -- ada.integer_text_io%b -- ada.text_io.modular_aux%s -- ada.text_io.modular_aux%b -- system.pool_global%s -- system.pool_global%b -- system.sequential_io%s -- system.sequential_io%b -- system.soft_links.tasking%s -- system.soft_links.tasking%b -- system.strings.stream_ops%s -- system.strings.stream_ops%b -- system.tasking.initialization%s -- system.tasking.task_attributes%s -- system.tasking.initialization%b -- system.tasking.task_attributes%b -- system.tasking.protected_objects%s -- system.tasking.protected_objects%b -- system.tasking.protected_objects.entries%s -- system.tasking.protected_objects.entries%b -- system.tasking.queuing%s -- system.tasking.queuing%b -- system.tasking.utilities%s -- system.tasking.utilities%b -- system.tasking.entry_calls%s -- system.tasking.rendezvous%s -- system.tasking.protected_objects.operations%s -- system.tasking.protected_objects.operations%b -- system.tasking.entry_calls%b -- system.tasking.rendezvous%b -- system.tasking.stages%s -- system.tasking.stages%b -- p_structuraltypes%s -- p_structuraltypes%b -- p_stephandler%s -- p_stephandler%b -- p_stephandler.feistelhandler%s -- p_stephandler.feistelhandler%b -- p_stephandler.inputhandler%s -- p_stephandler.inputhandler%b -- p_stephandler.iphandler%s -- p_stephandler.iphandler%b -- p_stephandler.keyhandler%s -- p_stephandler.keyhandler%b -- p_stephandler.outputhandler%s -- p_stephandler.outputhandler%b -- p_stephandler.reverseiphandler%s -- p_stephandler.reverseiphandler%b -- main%b -- END ELABORATION ORDER end ada_main;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- N A M E T -- -- -- -- S p e c -- -- -- -- Copyright (C) 1992-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 Alloc; with Table; with System; use System; with Types; use Types; package Namet is -- WARNING: There is a C version of this package. Any changes to this -- source file must be properly reflected in the C header file namet.h -- which is created manually from namet.ads and namet.adb. -- This package contains routines for handling the names table. The table -- is used to store character strings for identifiers and operator symbols, -- as well as other string values such as unit names and file names. -- The forms of the entries are as follows: -- Identifiers Stored with upper case letters folded to lower case. -- Upper half (16#80# bit set) and wide characters are -- stored in an encoded form (Uhh for upper half char, -- Whhhh for wide characters, WWhhhhhhhh as provided by -- the routine Append_Encoded, where hh are hex -- digits for the character code using lower case a-f). -- Normally the use of U or W in other internal names is -- avoided, but these letters may be used in internal -- names (without this special meaning), if they appear -- as the last character of the name, or they are -- followed by an upper case letter (other than the WW -- sequence), or an underscore. -- Operator symbols Stored with an initial letter O, and the remainder -- of the name is the lower case characters XXX where -- the name is Name_Op_XXX, see Snames spec for a full -- list of the operator names. Normally the use of O -- in other internal names is avoided, but it may be -- used in internal names (without this special meaning) -- if it is the last character of the name, or if it is -- followed by an upper case letter or an underscore. -- Character literals Character literals have names that are used only for -- debugging and error message purposes. The form is an -- upper case Q followed by a single lower case letter, -- or by a Uxx/Wxxxx/WWxxxxxxx encoding as described for -- identifiers. The Set_Character_Literal_Name procedure -- should be used to construct these encodings. Normally -- the use of O in other internal names is avoided, but -- it may be used in internal names (without this special -- meaning) if it is the last character of the name, or -- if it is followed by an upper case letter or an -- underscore. -- Unit names Stored with upper case letters folded to lower case, -- using Uhh/Whhhh/WWhhhhhhhh encoding as described for -- identifiers, and a %s or %b suffix for specs/bodies. -- See package Uname for further details. -- File names Are stored in the form provided by Osint. Typically -- they may include wide character escape sequences and -- upper case characters (in non-encoded form). Casing -- is also derived from the external environment. Note -- that file names provided by Osint must generally be -- consistent with the names from Fname.Get_File_Name. -- Other strings The names table is also used as a convenient storage -- location for other variable length strings such as -- error messages etc. There are no restrictions on what -- characters may appear for such entries. -- Note: the encodings Uhh (upper half characters), Whhhh (wide characters), -- WWhhhhhhhh (wide wide characters) and Qx (character literal names) are -- described in the spec, since they are visible throughout the system (e.g. -- in debugging output). However, no code should depend on these particular -- encodings, so it should be possible to change the encodings by making -- changes only to the Namet specification (to change these comments) and the -- body (which actually implements the encodings). -- The names are hashed so that a given name appears only once in the table, -- except that names entered with Name_Enter as opposed to Name_Find are -- omitted from the hash table. -- The first 26 entries in the names table (with Name_Id values in the range -- First_Name_Id .. First_Name_Id + 25) represent names which are the one -- character lower case letters in the range a-z, and these names are created -- and initialized by the Initialize procedure. -- Five values, one of type Int, one of type Byte, and three of type Boolean, -- are stored with each names table entry and subprograms are provided for -- setting and retrieving these associated values. The usage of these values -- is up to the client: -- In the compiler we have the following uses: -- The Int field is used to point to a chain of potentially visible -- entities (see Sem.Ch8 for details). -- The Byte field is used to hold the Token_Type value for reserved words -- (see Sem for details). -- The Boolean1 field is used to mark address clauses to optimize the -- performance of the Exp_Util.Following_Address_Clause function. -- The Boolean2 field is used to mark simple names that appear in -- Restriction[_Warning]s pragmas for No_Use_Of_Entity. This avoids most -- unnecessary searches of the No_Use_Of_Entity table. -- The Boolean3 field is set for names of pragmas that are to be ignored -- because of the occurrence of a corresponding pragma Ignore_Pragma. -- In the binder, we have the following uses: -- The Int field is used in various ways depending on the name involved, -- see binder documentation for details. -- The Byte and Boolean fields are unused. -- Note that the value of the Int and Byte fields are initialized to zero, -- and the Boolean field is initialized to False, when a new Name table entry -- is created. type Bounded_String (Max_Length : Natural := 2**12) is limited -- It's unlikely to have names longer than this. But we don't want to make -- it too big, because we declare these on the stack in recursive routines. record Length : Natural := 0; Chars : String (1 .. Max_Length); end record; -- To create a Name_Id, you can declare a Bounded_String as a local -- variable, and Append things onto it, and finally call Name_Find. -- You can also use a String, as in: -- X := Name_Find (Some_String & "_some_suffix"); -- For historical reasons, we also have the Global_Name_Buffer below, -- which is used by most of the code via the renamings. New code ought -- to avoid the global. Global_Name_Buffer : Bounded_String; Name_Buffer : String renames Global_Name_Buffer.Chars; Name_Len : Natural renames Global_Name_Buffer.Length; -- Note that there is some circuitry (e.g. Osint.Write_Program_Name) that -- does a save/restore on Name_Len and Name_Buffer (1 .. Name_Len). This -- works in part because Name_Len is default-initialized to 0. ----------------------------- -- Types for Namet Package -- ----------------------------- -- Name_Id values are used to identify entries in the names table. Except -- for the special values No_Name and Error_Name, they are subscript values -- for the Names table defined in this package. -- Note that with only a few exceptions, which are clearly documented, the -- type Name_Id should be regarded as a private type. In particular it is -- never appropriate to perform arithmetic operations using this type. type Name_Id is range Names_Low_Bound .. Names_High_Bound; for Name_Id'Size use 32; -- Type used to identify entries in the names table No_Name : constant Name_Id := Names_Low_Bound; -- The special Name_Id value No_Name is used in the parser to indicate -- a situation where no name is present (e.g. on a loop or block). Error_Name : constant Name_Id := Names_Low_Bound + 1; -- The special Name_Id value Error_Name is used in the parser to -- indicate that some kind of error was encountered in scanning out -- the relevant name, so it does not have a representable label. subtype Error_Name_Or_No_Name is Name_Id range No_Name .. Error_Name; -- Used to test for either error name or no name First_Name_Id : constant Name_Id := Names_Low_Bound + 2; -- Subscript of first entry in names table ------------------------------ -- Name_Id Membership Tests -- ------------------------------ -- The following functions allow a convenient notation for testing whether -- a Name_Id value matches any one of a list of possible values. In each -- case True is returned if the given T argument is equal to any of the V -- arguments. These essentially duplicate the Ada 2012 membership tests, -- but we cannot use the latter (yet) in the compiler front end, because -- of bootstrap considerations function Nam_In (T : Name_Id; V1 : Name_Id; V2 : Name_Id) return Boolean; function Nam_In (T : Name_Id; V1 : Name_Id; V2 : Name_Id; V3 : Name_Id) return Boolean; function Nam_In (T : Name_Id; V1 : Name_Id; V2 : Name_Id; V3 : Name_Id; V4 : Name_Id) return Boolean; function Nam_In (T : Name_Id; V1 : Name_Id; V2 : Name_Id; V3 : Name_Id; V4 : Name_Id; V5 : Name_Id) return Boolean; function Nam_In (T : Name_Id; V1 : Name_Id; V2 : Name_Id; V3 : Name_Id; V4 : Name_Id; V5 : Name_Id; V6 : Name_Id) return Boolean; function Nam_In (T : Name_Id; V1 : Name_Id; V2 : Name_Id; V3 : Name_Id; V4 : Name_Id; V5 : Name_Id; V6 : Name_Id; V7 : Name_Id) return Boolean; function Nam_In (T : Name_Id; V1 : Name_Id; V2 : Name_Id; V3 : Name_Id; V4 : Name_Id; V5 : Name_Id; V6 : Name_Id; V7 : Name_Id; V8 : Name_Id) return Boolean; function Nam_In (T : Name_Id; V1 : Name_Id; V2 : Name_Id; V3 : Name_Id; V4 : Name_Id; V5 : Name_Id; V6 : Name_Id; V7 : Name_Id; V8 : Name_Id; V9 : Name_Id) return Boolean; function Nam_In (T : Name_Id; V1 : Name_Id; V2 : Name_Id; V3 : Name_Id; V4 : Name_Id; V5 : Name_Id; V6 : Name_Id; V7 : Name_Id; V8 : Name_Id; V9 : Name_Id; V10 : Name_Id) return Boolean; function Nam_In (T : Name_Id; V1 : Name_Id; V2 : Name_Id; V3 : Name_Id; V4 : Name_Id; V5 : Name_Id; V6 : Name_Id; V7 : Name_Id; V8 : Name_Id; V9 : Name_Id; V10 : Name_Id; V11 : Name_Id) return Boolean; function Nam_In (T : Name_Id; V1 : Name_Id; V2 : Name_Id; V3 : Name_Id; V4 : Name_Id; V5 : Name_Id; V6 : Name_Id; V7 : Name_Id; V8 : Name_Id; V9 : Name_Id; V10 : Name_Id; V11 : Name_Id; V12 : Name_Id) return Boolean; pragma Inline (Nam_In); -- Inline all above functions ----------------- -- Subprograms -- ----------------- function To_String (Buf : Bounded_String) return String; pragma Inline (To_String); function "+" (Buf : Bounded_String) return String renames To_String; function Name_Find (Buf : Bounded_String := Global_Name_Buffer) return Name_Id; function Name_Find (S : String) return Name_Id; -- Name_Find searches the names table to see if the string has already been -- stored. If so, the Id of the existing entry is returned. Otherwise a new -- entry is created with its Name_Table_Int fields set to zero/false. Note -- that it is permissible for Buf.Length to be zero to lookup the empty -- name string. function Name_Enter (Buf : Bounded_String := Global_Name_Buffer) return Name_Id; -- Name_Enter is similar to Name_Find. The difference is that it does not -- search the table for an existing match, and also subsequent Name_Find -- calls using the same name will not locate the entry created by this -- call. Thus multiple calls to Name_Enter with the same name will create -- multiple entries in the name table with different Name_Id values. This -- is useful in the case of created names, which are never expected to be -- looked up. Note: Name_Enter should never be used for one character -- names, since these are efficiently located without hashing by Name_Find -- in any case. function Name_Equals (N1 : Name_Id; N2 : Name_Id) return Boolean; -- Return whether N1 and N2 denote the same character sequence function Get_Name_String (Id : Name_Id) return String; -- Returns the characters of Id as a String. The lower bound is 1. -- The following Append procedures ignore any characters that don't fit in -- Buf. procedure Append (Buf : in out Bounded_String; C : Character); -- Append C onto Buf pragma Inline (Append); procedure Append (Buf : in out Bounded_String; V : Nat); -- Append decimal representation of V onto Buf procedure Append (Buf : in out Bounded_String; S : String); -- Append S onto Buf procedure Append (Buf : in out Bounded_String; Buf2 : Bounded_String); -- Append Buf2 onto Buf procedure Append (Buf : in out Bounded_String; Id : Name_Id); -- Append the characters of Id onto Buf. It is an error to call this with -- one of the special name Id values (No_Name or Error_Name). procedure Append_Decoded (Buf : in out Bounded_String; Id : Name_Id); -- Same as Append, except that the result is decoded, so that upper half -- characters and wide characters appear as originally found in the source -- program text, operators have their source forms (special characters and -- enclosed in quotes), and character literals appear surrounded by -- apostrophes. procedure Append_Decoded_With_Brackets (Buf : in out Bounded_String; Id : Name_Id); -- Same as Append_Decoded, except that the brackets notation (Uhh -- replaced by ["hh"], Whhhh replaced by ["hhhh"], WWhhhhhhhh replaced by -- ["hhhhhhhh"]) is used for all non-lower half characters, regardless of -- how Opt.Wide_Character_Encoding_Method is set, and also in that -- characters in the range 16#80# .. 16#FF# are converted to brackets -- notation in all cases. This routine can be used when there is a -- requirement for a canonical representation not affected by the -- character set options (e.g. in the binder generation of symbols). procedure Append_Unqualified (Buf : in out Bounded_String; Id : Name_Id); -- Same as Append, except that qualification (as defined in unit -- Exp_Dbug) is removed (including both preceding __ delimited names, and -- also the suffixes used to indicate package body entities and to -- distinguish between overloaded entities). Note that names are not -- qualified until just before the call to gigi, so this routine is only -- needed by processing that occurs after gigi has been called. This -- includes all ASIS processing, since ASIS works on the tree written -- after gigi has been called. procedure Append_Unqualified_Decoded (Buf : in out Bounded_String; Id : Name_Id); -- Same as Append_Unqualified, but decoded as for Append_Decoded procedure Append_Encoded (Buf : in out Bounded_String; C : Char_Code); -- Appends given character code at the end of Buf. Lower case letters and -- digits are stored unchanged. Other 8-bit characters are stored using the -- Uhh encoding (hh = hex code), other 16-bit wide character values are -- stored using the Whhhh (hhhh = hex code) encoding, and other 32-bit wide -- wide character values are stored using the WWhhhhhhhh (hhhhhhhh = hex -- code). Note that this procedure does not fold upper case letters (they -- are stored using the Uhh encoding). procedure Set_Character_Literal_Name (Buf : in out Bounded_String; C : Char_Code); -- This procedure sets the proper encoded name for the character literal -- for the given character code. procedure Insert_Str (Buf : in out Bounded_String; S : String; Index : Positive); -- Inserts S in Buf, starting at Index. Any existing characters at or past -- this location get moved beyond the inserted string. function Is_Internal_Name (Buf : Bounded_String) return Boolean; procedure Get_Last_Two_Chars (N : Name_Id; C1 : out Character; C2 : out Character); -- Obtains last two characters of a name. C1 is last but one character and -- C2 is last character. If name is less than two characters long then both -- C1 and C2 are set to ASCII.NUL on return. function Get_Name_Table_Boolean1 (Id : Name_Id) return Boolean; function Get_Name_Table_Boolean2 (Id : Name_Id) return Boolean; function Get_Name_Table_Boolean3 (Id : Name_Id) return Boolean; -- Fetches the Boolean values associated with the given name function Get_Name_Table_Byte (Id : Name_Id) return Byte; pragma Inline (Get_Name_Table_Byte); -- Fetches the Byte value associated with the given name function Get_Name_Table_Int (Id : Name_Id) return Int; pragma Inline (Get_Name_Table_Int); -- Fetches the Int value associated with the given name procedure Set_Name_Table_Boolean1 (Id : Name_Id; Val : Boolean); procedure Set_Name_Table_Boolean2 (Id : Name_Id; Val : Boolean); procedure Set_Name_Table_Boolean3 (Id : Name_Id; Val : Boolean); -- Sets the Boolean value associated with the given name procedure Set_Name_Table_Byte (Id : Name_Id; Val : Byte); pragma Inline (Set_Name_Table_Byte); -- Sets the Byte value associated with the given name procedure Set_Name_Table_Int (Id : Name_Id; Val : Int); pragma Inline (Set_Name_Table_Int); -- Sets the Int value associated with the given name function Is_Internal_Name (Id : Name_Id) return Boolean; -- Returns True if the name is an internal name (i.e. contains a character -- for which Is_OK_Internal_Letter is true, or if the name starts or ends -- with an underscore. -- -- Note: if the name is qualified (has a double underscore), then only the -- final entity name is considered, not the qualifying names. Consider for -- example that the name: -- -- pkg__B_1__xyz -- -- is not an internal name, because the B comes from the internal name of -- a qualifying block, but the xyz means that this was indeed a declared -- identifier called "xyz" within this block and there is nothing internal -- about that name. function Is_OK_Internal_Letter (C : Character) return Boolean; pragma Inline (Is_OK_Internal_Letter); -- Returns true if C is a suitable character for using as a prefix or a -- suffix of an internally generated name, i.e. it is an upper case letter -- other than one of the ones used for encoding source names (currently the -- set of reserved letters is O, Q, U, W) and also returns False for the -- letter X, which is reserved for debug output (see Exp_Dbug). function Is_Operator_Name (Id : Name_Id) return Boolean; -- Returns True if name given is of the form of an operator (that is, it -- starts with an upper case O). function Is_Valid_Name (Id : Name_Id) return Boolean; -- True if Id is a valid name - points to a valid entry in the Name_Entries -- table. function Length_Of_Name (Id : Name_Id) return Nat; pragma Inline (Length_Of_Name); -- Returns length of given name in characters. This is the length of the -- encoded name, as stored in the names table. procedure Initialize; -- This is a dummy procedure. It is retained for easy compatibility with -- clients who used to call Initialize when this call was required. Now -- initialization is performed automatically during package elaboration. -- Note that this change fixes problems which existed prior to the change -- of Initialize being called more than once. See also Reinitialize which -- allows reinitialization of the tables. procedure Reinitialize; -- Clears the name tables and removes all existing entries from the table. procedure Reset_Name_Table; -- This procedure is used when there are multiple source files to reset the -- name table info entries associated with current entries in the names -- table. There is no harm in keeping the names entries themselves from one -- compilation to another, but we can't keep the entity info, since this -- refers to tree nodes, which are destroyed between each main source file. procedure Finalize; -- Called at the end of a use of the Namet package (before a subsequent -- call to Initialize). Currently this routine is only used to generate -- debugging output. procedure Lock; -- Lock name tables before calling back end. We reserve some extra space -- before locking to avoid unnecessary inefficiencies when we unlock. procedure Unlock; -- Unlocks the name table to allow use of the extra space reserved by the -- call to Lock. See gnat1drv for details of the need for this. procedure Tree_Read; -- Initializes internal tables from current tree file using the relevant -- Table.Tree_Read routines. Note that Initialize should not be called if -- Tree_Read is used. Tree_Read includes all necessary initialization. procedure Tree_Write; -- Writes out internal tables to current tree file using the relevant -- Table.Tree_Write routines. procedure Write_Name (Id : Name_Id); -- Write_Name writes the characters of the specified name using the -- standard output procedures in package Output. The name is written -- in encoded form (i.e. including Uhh, Whhh, Qx, _op as they appear in -- the name table). If Id is Error_Name, or No_Name, no text is output. procedure Write_Name_Decoded (Id : Name_Id); -- Like Write_Name, except that the name written is the decoded name, as -- described for Append_Decoded. function Name_Chars_Address return System.Address; -- Return starting address of name characters table (used in Back_End call -- to Gigi). function Name_Entries_Address return System.Address; -- Return starting address of Names table (used in Back_End call to Gigi) function Name_Entries_Count return Nat; -- Return current number of entries in the names table -------------------------- -- Obsolete Subprograms -- -------------------------- -- The following routines operate on Global_Name_Buffer. New code should -- use the routines above, and declare Bounded_Strings as local -- variables. Existing code can be improved incrementally by removing calls -- to the following. ???If we eliminate all of these, we can remove -- Global_Name_Buffer. But be sure to look at namet.h first. -- To see what these do, look at the bodies. They are all trivially defined -- in terms of routines above. procedure Add_Char_To_Name_Buffer (C : Character); pragma Inline (Add_Char_To_Name_Buffer); procedure Add_Nat_To_Name_Buffer (V : Nat); procedure Add_Str_To_Name_Buffer (S : String); procedure Get_Decoded_Name_String (Id : Name_Id); procedure Get_Decoded_Name_String_With_Brackets (Id : Name_Id); procedure Get_Name_String (Id : Name_Id); procedure Get_Name_String_And_Append (Id : Name_Id); procedure Get_Unqualified_Decoded_Name_String (Id : Name_Id); procedure Get_Unqualified_Name_String (Id : Name_Id); procedure Insert_Str_In_Name_Buffer (S : String; Index : Positive); function Is_Internal_Name return Boolean; procedure Set_Character_Literal_Name (C : Char_Code); procedure Store_Encoded_Character (C : Char_Code); ------------------------------ -- File and Unit Name Types -- ------------------------------ -- These are defined here in Namet rather than Fname and Uname to avoid -- problems with dependencies, and to avoid dragging in Fname and Uname -- into many more files, but it would be cleaner to move to Fname/Uname. type File_Name_Type is new Name_Id; -- File names are stored in the names table and this type is used to -- indicate that a Name_Id value is being used to hold a simple file name -- (which does not include any directory information). No_File : constant File_Name_Type := File_Name_Type (No_Name); -- Constant used to indicate no file is present (this is used for example -- when a search for a file indicates that no file of the name exists). Error_File_Name : constant File_Name_Type := File_Name_Type (Error_Name); -- The special File_Name_Type value Error_File_Name is used to indicate -- a unit name where some previous processing has found an error. subtype Error_File_Name_Or_No_File is File_Name_Type range No_File .. Error_File_Name; -- Used to test for either error file name or no file type Path_Name_Type is new Name_Id; -- Path names are stored in the names table and this type is used to -- indicate that a Name_Id value is being used to hold a path name (that -- may contain directory information). No_Path : constant Path_Name_Type := Path_Name_Type (No_Name); -- Constant used to indicate no path name is present type Unit_Name_Type is new Name_Id; -- Unit names are stored in the names table and this type is used to -- indicate that a Name_Id value is being used to hold a unit name, which -- terminates in %b for a body or %s for a spec. No_Unit_Name : constant Unit_Name_Type := Unit_Name_Type (No_Name); -- Constant used to indicate no file name present Error_Unit_Name : constant Unit_Name_Type := Unit_Name_Type (Error_Name); -- The special Unit_Name_Type value Error_Unit_Name is used to indicate -- a unit name where some previous processing has found an error. subtype Error_Unit_Name_Or_No_Unit_Name is Unit_Name_Type range No_Unit_Name .. Error_Unit_Name; ------------------------ -- Debugging Routines -- ------------------------ procedure wn (Id : Name_Id); pragma Export (Ada, wn); -- This routine is intended for debugging use only (i.e. it is intended to -- be called from the debugger). It writes the characters of the specified -- name using the standard output procedures in package Output, followed by -- a new line. The name is written in encoded form (i.e. including Uhh, -- Whhh, Qx, _op as they appear in the name table). If Id is Error_Name, -- No_Name, or invalid an appropriate string is written (<Error_Name>, -- <No_Name>, <invalid name>). Unlike Write_Name, this call does not affect -- the contents of Name_Buffer or Name_Len. private --------------------------- -- Table Data Structures -- --------------------------- -- The following declarations define the data structures used to store -- names. The definitions are in the private part of the package spec, -- rather than the body, since they are referenced directly by gigi. -- This table stores the actual string names. Although logically there is -- no need for a terminating character (since the length is stored in the -- name entry table), we still store a NUL character at the end of every -- name (for convenience in interfacing to the C world). package Name_Chars is new Table.Table ( Table_Component_Type => Character, Table_Index_Type => Int, Table_Low_Bound => 0, Table_Initial => Alloc.Name_Chars_Initial, Table_Increment => Alloc.Name_Chars_Increment, Table_Name => "Name_Chars"); type Name_Entry is record Name_Chars_Index : Int; -- Starting location of characters in the Name_Chars table minus one -- (i.e. pointer to character just before first character). The reason -- for the bias of one is that indexes in Name_Buffer are one's origin, -- so this avoids unnecessary adds and subtracts of 1. Name_Len : Short; -- Length of this name in characters Byte_Info : Byte; -- Byte value associated with this name Boolean1_Info : Boolean; Boolean2_Info : Boolean; Boolean3_Info : Boolean; -- Boolean values associated with the name Name_Has_No_Encodings : Boolean; -- This flag is set True if the name entry is known not to contain any -- special character encodings. This is used to speed up repeated calls -- to Append_Decoded. A value of False means that it is not known -- whether the name contains any such encodings. Hash_Link : Name_Id; -- Link to next entry in names table for same hash code Int_Info : Int; -- Int Value associated with this name end record; for Name_Entry use record Name_Chars_Index at 0 range 0 .. 31; Name_Len at 4 range 0 .. 15; Byte_Info at 6 range 0 .. 7; Boolean1_Info at 7 range 0 .. 0; Boolean2_Info at 7 range 1 .. 1; Boolean3_Info at 7 range 2 .. 2; Name_Has_No_Encodings at 7 range 3 .. 7; Hash_Link at 8 range 0 .. 31; Int_Info at 12 range 0 .. 31; end record; for Name_Entry'Size use 16 * 8; -- This ensures that we did not leave out any fields -- This is the table that is referenced by Name_Id entries. -- It contains one entry for each unique name in the table. package Name_Entries is new Table.Table ( Table_Component_Type => Name_Entry, Table_Index_Type => Name_Id'Base, Table_Low_Bound => First_Name_Id, Table_Initial => Alloc.Names_Initial, Table_Increment => Alloc.Names_Increment, Table_Name => "Name_Entries"); end Namet;
with System; with Utils; use Utils; package body Drivers.CC1101 is type Register_Type is ( IOCFG2, IOCFG1, IOCFG0, FIFOTHR, SYNC1, SYNC0, PKTLEN, PKTCTRL1, PKTCTRL0, ADDR, CHANNR, FSCTRL1, FSCTRL0, FREQ2, FREQ1, FREQ0, MDMCFG4, MDMCFG3, MDMCFG2, MDMCFG1, MDMCFG0, DEVIATN, MCSM2, MCSM1, MCSM0, FOCCFG, BSCFG, AGCCTRL2, AGCCTRL1, AGCCTRL0, WOREVT1, WOREVT0, WORCTRL, FREND1, FREND0, FSCAL3, FSCAL2, FSCAL1, FSCAL0, RCCTRL1, RCCTRL0, FSTEST, PTEST, AGCTEST, TEST2, TEST1, TEST0, PARTNUM, VERSION, FREQEST, LQI, RSSI, MARCSTATE, WORTIME1, WORTIME0, PKTSTATUS, VCO_VC_DAC, TXBYTES, RXBYTES, RCCTRL1_STATUS, RCCTRL0_STATUS); for Register_Type use ( IOCFG2 => 16#00#, IOCFG1 => 16#01#, IOCFG0 => 16#02#, FIFOTHR => 16#03#, SYNC1 => 16#04#, SYNC0 => 16#05#, PKTLEN => 16#06#, PKTCTRL1 => 16#07#, PKTCTRL0 => 16#08#, ADDR => 16#09#, CHANNR => 16#0A#, FSCTRL1 => 16#0B#, FSCTRL0 => 16#0C#, FREQ2 => 16#0D#, FREQ1 => 16#0E#, FREQ0 => 16#0F#, MDMCFG4 => 16#10#, MDMCFG3 => 16#11#, MDMCFG2 => 16#12#, MDMCFG1 => 16#13#, MDMCFG0 => 16#14#, DEVIATN => 16#15#, MCSM2 => 16#16#, MCSM1 => 16#17#, MCSM0 => 16#18#, FOCCFG => 16#19#, BSCFG => 16#1A#, AGCCTRL2 => 16#1B#, AGCCTRL1 => 16#1C#, AGCCTRL0 => 16#1D#, WOREVT1 => 16#1E#, WOREVT0 => 16#1F#, WORCTRL => 16#20#, FREND1 => 16#21#, FREND0 => 16#22#, FSCAL3 => 16#23#, FSCAL2 => 16#24#, FSCAL1 => 16#25#, FSCAL0 => 16#26#, RCCTRL1 => 16#27#, RCCTRL0 => 16#28#, FSTEST => 16#29#, PTEST => 16#2A#, AGCTEST => 16#2B#, TEST2 => 16#2C#, TEST1 => 16#2D#, TEST0 => 16#2E#, PARTNUM => 16#30#, VERSION => 16#31#, FREQEST => 16#32#, LQI => 16#33#, RSSI => 16#34#, MARCSTATE => 16#35#, WORTIME1 => 16#36#, WORTIME0 => 16#37#, PKTSTATUS => 16#38#, VCO_VC_DAC => 16#39#, TXBYTES => 16#3A#, RXBYTES => 16#3B#, RCCTRL1_STATUS => 16#3C#, RCCTRL0_STATUS => 16#3D#); type Commands is ( SRES, SFSTXON, SXOFF, SCAL, SRX, STX, SIDLE, SWOR, SPWD, SFRX, SFTX, SWORRST, SNOP); for Commands use ( SRES => 16#30#, SFSTXON => 16#31#, SXOFF => 16#32#, SCAL => 16#33#, SRX => 16#34#, STX => 16#35#, SIDLE => 16#36#, SWOR => 16#38#, SPWD => 16#39#, SFRX => 16#3A#, SFTX => 16#3B#, SWORRST => 16#3C#, SNOP => 16#3D#); type Init_Value is record Register : Register_Type; Value : Byte; end record; Init_Values : constant array (1 .. 29) of Init_Value := ( (IOCFG0, 16#41#), -- CHIP_RDYn (IOCFG2, 16#07#), -- RX with CRC ok (FIFOTHR, 16#47#), -- RX attenuation 6dB, 33/32 byte threshold (PKTLEN, 16#3D#), -- 62 bytes max packet length (PKTCTRL1, 16#0C#), -- CRC autoflush, status append (PKTCTRL0, 16#05#), -- TX/RX CRC enabled, variable packet length (FSCTRL1, 16#06#), -- 152kHz IF frequency (FREQ2, 16#10#), -- 434 MHz carrier frequency (FREQ1, 16#B1#), (FREQ0, 16#3B#), (MDMCFG4, 16#FA#), -- 135kHz channel bandwidth (MDMCFG3, 16#83#), -- 38.4kbps symbol rate (MDMCFG2, 16#31#), -- OOK, 16/16 sync word detection -- (MDMCFG2, 16#06#), -- 2-FSK, 16/16 sync word detection, carrier sense (MDMCFG1, 16#42#), -- 8 bytes preamble (DEVIATN, 16#27#), -- 11.9kHz FSK deviation (MCSM1, 16#3c#), (MCSM0, 16#18#), (FOCCFG, 16#16#), (WORCTRL, 16#FB#), (FSCAL3, 16#E9#), (FSCAL2, 16#2A#), (FSCAL1, 16#00#), (FSCAL0, 16#1F#), (AGCCTRL2, 16#04#), (AGCCTRL1, 16#00#), (AGCCTRL0, 16#91#), (TEST2, 16#81#), (TEST1, 16#35#), (TEST0, 16#09#)); procedure Write_Register (Register : Register_Type; Value : Byte); procedure Read_Register (Register : Register_Type; Value : out Byte); function Read_Register (Register : Register_Type) return Byte; procedure Write_Register (Register : Register_Type; Value : Byte) is begin Chip_Select.Clear; SPI.Send (Register'Enum_Rep); SPI.Send (Value); Chip_Select.Set; end Write_Register; procedure Read_Register (Register : Register_Type; Value : out Byte) is begin Chip_Select.Clear; SPI.Send (16#80# + Register'Enum_Rep); SPI.Receive (Value); Chip_Select.Set; end Read_Register; function Read_Register (Register : Register_Type) return Byte is Value : Byte; begin Chip_Select.Clear; SPI.Send (16#80# + Register'Enum_Rep); SPI.Receive (Value); Chip_Select.Set; return Value; end Read_Register; procedure Read_Status (Register : Register_Type; Value : out Byte) is begin Chip_Select.Clear; SPI.Send (16#C0# + Register'Enum_Rep); SPI.Receive (Value); Chip_Select.Set; end Read_Status; function Read_Status (Register : Register_Type) return Byte is Value : Byte; begin Chip_Select.Clear; SPI.Send (16#C0# + Register'Enum_Rep); SPI.Receive (Value); Chip_Select.Set; return Value; end Read_Status; procedure Read_Registers (Registers : out Raw_Register_Array) is begin for R in Register_Type loop if R'Enum_Rep < PARTNUM'Enum_Rep then Read_Register (R, Registers (R'Enum_Rep)); else Read_Status (R, Registers (R'Enum_Rep)); end if; end loop; end Read_Registers; procedure Init is begin for I of Init_Values loop Write_Register (I.Register, I.Value); end loop; end Init; procedure Print_Registers is begin Put_Line ( "PARTNUM:" & To_Hex_String (Unsigned_8 (Read_Status (PARTNUM))) & " VERSION:" & To_Hex_String (Unsigned_8 (Read_Status (VERSION))) & " SYNC0:" & To_Hex_String (Unsigned_8 (Read_Register (SYNC0))) & " SYNC1:" & To_Hex_String (Unsigned_8 (Read_Register (SYNC1))) & " FREQ:" & To_Hex_String (Unsigned_8 (Read_Register (FREQ0))) & To_Hex_String (Unsigned_8 (Read_Register (FREQ1))) & To_Hex_String (Unsigned_8 (Read_Register (FREQ2)))); end Print_Registers; procedure Set_Sync_Word (Word : Unsigned_16) is begin null; end Set_Sync_Word; function Get_Sync_Word return Unsigned_16 is begin return Unsigned_16 (Read_Register (SYNC1)) * 2 ** 8 + Unsigned_16 (Read_Register (SYNC0)); end Get_Sync_Word; procedure TX_Mode is begin null; end TX_Mode; procedure RX_Mode is begin Chip_Select.Clear; SPI.Send (SIDLE'Enum_Rep); SPI.Send (SFRX'Enum_Rep); SPI.Send (SRX'Enum_Rep); Chip_Select.Set; end RX_Mode; procedure TX (Packet: Packet_Type) is begin Chip_Select.Clear; SPI.Send (SFTX'Enum_Rep); Chip_Select.Clear; SPI.Send (16#3F# + 16#40#); for D of Packet loop SPI.Send (D); end loop; Chip_Select.Set; Chip_Select.Clear; SPI.Send (STX'Enum_Rep); Chip_Select.Set; end TX; function Wait_For_RX return Boolean is begin loop exit when RX_Available; end loop; return True; -- IRQ.Clear_Trigger; -- IRQ.Wait_For_Trigger; -- return IRQ.Triggered; end Wait_For_RX; function RX_Available return Boolean is begin return Read_Status (RXBYTES) > 0; end RX_Available; procedure Clear_IRQ is begin IRQ.Clear_Trigger; end Clear_IRQ; procedure RX (Packet : out Packet_Type; Length : out Natural) is N : Natural; begin N := Natural (Read_Status (RXBYTES)); Chip_Select.Clear; SPI.Send (16#3F# + 16#C0#); for I in 1 .. N loop SPI.Receive (Packet (I)); end loop; Chip_Select.Set; Length := N; end RX; procedure Power_Down is begin null; end Power_Down; procedure Cancel is begin null; end Cancel; end Drivers.CC1101;
package body agar.gui.widget.toolbar is package cbinds is function allocate (parent : widget_access_t; bar_type : type_t; num_rows : c.int; flags : flags_t) return toolbar_access_t; pragma import (c, allocate, "AG_ToolbarNew"); procedure row (toolbar : toolbar_access_t; row_name : c.int); pragma import (c, row, "AG_ToolbarRow"); end cbinds; function allocate (parent : widget_access_t; bar_type : type_t; num_rows : natural; flags : flags_t) return toolbar_access_t is begin return cbinds.allocate (parent => parent, bar_type => bar_type, num_rows => c.int (num_rows), flags => flags); end allocate; procedure row (toolbar : toolbar_access_t; row_name : natural) is begin cbinds.row (toolbar => toolbar, row_name => c.int (row_name)); end row; function widget (toolbar : toolbar_access_t) return widget_access_t is begin return agar.gui.widget.box.widget (toolbar.box'access); end widget; end agar.gui.widget.toolbar;
F1, F2 : File_Type; begin Open (F1, In_File, "city.ppm"); declare X : Image := Get_PPM (F1); begin Close (F1); Create (F2, Out_File, "city_sharpen.ppm"); Filter (X, ((-1.0, -1.0, -1.0), (-1.0, 9.0, -1.0), (-1.0, -1.0, -1.0))); Put_PPM (F2, X); end; Close (F2);
----------------------------------------------------------------------- -- security-random-tests - Tests for random package -- Copyright (C) 2017, 2018 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Test_Caller; package body Security.Random.Tests is package Caller is new Util.Test_Caller (Test, "Security.Random"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.Random.Generate", Test_Generate'Access); end Add_Tests; -- ------------------------------ -- Test Yadis discovery using static files -- ------------------------------ procedure Test_Generate (T : in out Test) is use Ada.Strings.Unbounded; G : Generator; Max : constant Ada.Streams.Stream_Element_Offset := 10; begin for I in 1 .. Max loop declare use type Ada.Streams.Stream_Element; S : Ada.Streams.Stream_Element_Array (1 .. I) := (others => 0); Rand : Ada.Strings.Unbounded.Unbounded_String; begin -- Try 5 times to fill the array with random patterns and make sure -- we don't get any 0. for Retry in 1 .. 5 loop G.Generate (S); exit when (for all R of S => R /= 0); end loop; T.Assert ((for all R of S => R /= 0), "Generator failed to initialize all bytes"); G.Generate (Positive (I), Rand); T.Assert (Length (Rand) > 0, "Generator failed to produce a base64url sequence"); end; end loop; end Test_Generate; end Security.Random.Tests;
with Ada.Unchecked_Deallocation, Interfaces.C.Strings, System; use type Interfaces.C.int, Interfaces.C.Strings.chars_ptr, System.Address; package body FLTK.Widgets.Groups.Input_Choices is procedure input_choice_set_draw_hook (W, D : in System.Address); pragma Import (C, input_choice_set_draw_hook, "input_choice_set_draw_hook"); pragma Inline (input_choice_set_draw_hook); procedure input_choice_set_handle_hook (W, H : in System.Address); pragma Import (C, input_choice_set_handle_hook, "input_choice_set_handle_hook"); pragma Inline (input_choice_set_handle_hook); function new_fl_input_choice (X, Y, W, H : in Interfaces.C.int; Text : in Interfaces.C.char_array) return System.Address; pragma Import (C, new_fl_input_choice, "new_fl_input_choice"); pragma Inline (new_fl_input_choice); procedure free_fl_input_choice (W : in System.Address); pragma Import (C, free_fl_input_choice, "free_fl_input_choice"); pragma Inline (free_fl_input_choice); function fl_input_choice_input (N : in System.Address) return System.Address; pragma Import (C, fl_input_choice_input, "fl_input_choice_input"); pragma Inline (fl_input_choice_input); function fl_input_choice_menubutton (N : in System.Address) return System.Address; pragma Import (C, fl_input_choice_menubutton, "fl_input_choice_menubutton"); pragma Inline (fl_input_choice_menubutton); procedure fl_input_choice_clear (N : in System.Address); pragma Import (C, fl_input_choice_clear, "fl_input_choice_clear"); pragma Inline (fl_input_choice_clear); function fl_input_choice_changed (N : in System.Address) return Interfaces.C.int; pragma Import (C, fl_input_choice_changed, "fl_input_choice_changed"); pragma Inline (fl_input_choice_changed); procedure fl_input_choice_clear_changed (N : in System.Address); pragma Import (C, fl_input_choice_clear_changed, "fl_input_choice_clear_changed"); pragma Inline (fl_input_choice_clear_changed); procedure fl_input_choice_set_changed (N : in System.Address); pragma Import (C, fl_input_choice_set_changed, "fl_input_choice_set_changed"); pragma Inline (fl_input_choice_set_changed); function fl_input_choice_get_down_box (N : in System.Address) return Interfaces.C.int; pragma Import (C, fl_input_choice_get_down_box, "fl_input_choice_get_down_box"); pragma Inline (fl_input_choice_get_down_box); procedure fl_input_choice_set_down_box (N : in System.Address; T : in Interfaces.C.int); pragma Import (C, fl_input_choice_set_down_box, "fl_input_choice_set_down_box"); pragma Inline (fl_input_choice_set_down_box); function fl_input_choice_get_textcolor (N : in System.Address) return Interfaces.C.unsigned; pragma Import (C, fl_input_choice_get_textcolor, "fl_input_choice_get_textcolor"); pragma Inline (fl_input_choice_get_textcolor); procedure fl_input_choice_set_textcolor (N : in System.Address; T : in Interfaces.C.unsigned); pragma Import (C, fl_input_choice_set_textcolor, "fl_input_choice_set_textcolor"); pragma Inline (fl_input_choice_set_textcolor); function fl_input_choice_get_textfont (N : in System.Address) return Interfaces.C.int; pragma Import (C, fl_input_choice_get_textfont, "fl_input_choice_get_textfont"); pragma Inline (fl_input_choice_get_textfont); procedure fl_input_choice_set_textfont (N : in System.Address; T : in Interfaces.C.int); pragma Import (C, fl_input_choice_set_textfont, "fl_input_choice_set_textfont"); pragma Inline (fl_input_choice_set_textfont); function fl_input_choice_get_textsize (N : in System.Address) return Interfaces.C.int; pragma Import (C, fl_input_choice_get_textsize, "fl_input_choice_get_textsize"); pragma Inline (fl_input_choice_get_textsize); procedure fl_input_choice_set_textsize (N : in System.Address; T : in Interfaces.C.int); pragma Import (C, fl_input_choice_set_textsize, "fl_input_choice_set_textsize"); pragma Inline (fl_input_choice_set_textsize); function fl_input_choice_get_value (N : in System.Address) return Interfaces.C.Strings.chars_ptr; pragma Import (C, fl_input_choice_get_value, "fl_input_choice_get_value"); pragma Inline (fl_input_choice_get_value); procedure fl_input_choice_set_value (N : in System.Address; T : in Interfaces.C.char_array); pragma Import (C, fl_input_choice_set_value, "fl_input_choice_set_value"); pragma Inline (fl_input_choice_set_value); procedure fl_input_choice_set_value2 (N : in System.Address; T : in Interfaces.C.int); pragma Import (C, fl_input_choice_set_value2, "fl_input_choice_set_value2"); pragma Inline (fl_input_choice_set_value2); procedure fl_input_choice_draw (W : in System.Address); pragma Import (C, fl_input_choice_draw, "fl_input_choice_draw"); pragma Inline (fl_input_choice_draw); function fl_input_choice_handle (W : in System.Address; E : in Interfaces.C.int) return Interfaces.C.int; pragma Import (C, fl_input_choice_handle, "fl_input_choice_handle"); pragma Inline (fl_input_choice_handle); procedure Free is new Ada.Unchecked_Deallocation (INP.Input, Input_Access); procedure Free is new Ada.Unchecked_Deallocation (MB.Menu_Button, Menu_Button_Access); procedure Finalize (This : in out Input_Choice) is begin if This.Void_Ptr /= System.Null_Address and then This in Input_Choice'Class then Group (This).Clear; free_fl_input_choice (This.Void_Ptr); Free (This.My_Input); Free (This.My_Menu_Button); This.Void_Ptr := System.Null_Address; end if; Finalize (Group (This)); end Finalize; package body Forge is function Create (X, Y, W, H : in Integer; Text : in String) return Input_Choice is begin return This : Input_Choice do This.Void_Ptr := new_fl_input_choice (Interfaces.C.int (X), Interfaces.C.int (Y), Interfaces.C.int (W), Interfaces.C.int (H), Interfaces.C.To_C (Text)); fl_group_end (This.Void_Ptr); fl_widget_set_user_data (This.Void_Ptr, Widget_Convert.To_Address (This'Unchecked_Access)); input_choice_set_draw_hook (This.Void_Ptr, Draw_Hook'Address); input_choice_set_handle_hook (This.Void_Ptr, Handle_Hook'Address); This.My_Input := new INP.Input; Wrapper (This.My_Input.all).Void_Ptr := fl_input_choice_input (This.Void_Ptr); Wrapper (This.My_Input.all).Needs_Dealloc := False; This.My_Menu_Button := new MB.Menu_Button; Wrapper (This.My_Menu_Button.all).Void_Ptr := fl_input_choice_menubutton (This.Void_Ptr); Wrapper (This.My_Menu_Button.all).Needs_Dealloc := False; end return; end Create; end Forge; function Input (This : in out Input_Choice) return INP.Input_Reference is begin return (Data => This.My_Input); end Input; function Menu_Button (This : in out Input_Choice) return MB.Menu_Button_Reference is begin return (Data => This.My_Menu_Button); end Menu_Button; procedure Clear (This : in out Input_Choice) is begin fl_input_choice_clear (This.Void_Ptr); end Clear; function Has_Changed (This : in Input_Choice) return Boolean is begin return fl_input_choice_changed (This.Void_Ptr) /= 0; end Has_Changed; procedure Clear_Changed (This : in out Input_Choice) is begin fl_input_choice_clear_changed (This.Void_Ptr); end Clear_Changed; procedure Set_Changed (This : in out Input_Choice; To : in Boolean) is begin if To then fl_input_choice_set_changed (This.Void_Ptr); end if; end Set_Changed; function Get_Down_Box (This : in Input_Choice) return Box_Kind is begin return Box_Kind'Val (fl_input_choice_get_down_box (This.Void_Ptr)); end Get_Down_Box; procedure Set_Down_Box (This : in out Input_Choice; To : in Box_Kind) is begin fl_input_choice_set_down_box (This.Void_Ptr, Box_Kind'Pos (To)); end Set_Down_Box; function Get_Text_Color (This : in Input_Choice) return Color is begin return Color (fl_input_choice_get_textcolor (This.Void_Ptr)); end Get_Text_Color; procedure Set_Text_Color (This : in out Input_Choice; To : in Color) is begin fl_input_choice_set_textcolor (This.Void_Ptr, Interfaces.C.unsigned (To)); end Set_Text_Color; function Get_Text_Font (This : in Input_Choice) return Font_Kind is begin return Font_Kind'Val (fl_input_choice_get_textfont (This.Void_Ptr)); end Get_Text_Font; procedure Set_Text_Font (This : in out Input_Choice; To : in Font_Kind) is begin fl_input_choice_set_textfont (This.Void_Ptr, Font_Kind'Pos (To)); end Set_Text_Font; function Get_Text_Size (This : in Input_Choice) return Font_Size is begin return Font_Size (fl_input_choice_get_textsize (This.Void_Ptr)); end Get_Text_Size; procedure Set_Text_Size (This : in out Input_Choice; To : in Font_Size) is begin fl_input_choice_set_textsize (This.Void_Ptr, Interfaces.C.int (To)); end Set_Text_Size; function Get_Input (This : in Input_Choice) return String is Ptr : Interfaces.C.Strings.chars_ptr := fl_input_choice_get_value (This.Void_Ptr); begin if Ptr = Interfaces.C.Strings.Null_Ptr then return ""; else -- pointer to internal buffer so no free necessary return Interfaces.C.Strings.Value (Ptr); end if; end Get_Input; procedure Set_Input (This : in out Input_Choice; To : in String) is begin fl_input_choice_set_value (This.Void_Ptr, Interfaces.C.To_C (To)); end Set_Input; procedure Set_Item (This : in out Input_Choice; Num : in Integer) is begin fl_input_choice_set_value2 (This.Void_Ptr, Interfaces.C.int (Num)); end Set_Item; procedure Draw (This : in out Input_Choice) is begin fl_input_choice_draw (This.Void_Ptr); end Draw; function Handle (This : in out Input_Choice; Event : in Event_Kind) return Event_Outcome is begin return Event_Outcome'Val (fl_input_choice_handle (This.Void_Ptr, Event_Kind'Pos (Event))); end Handle; end FLTK.Widgets.Groups.Input_Choices;
package YAML.Abstract_Object is type Instance is abstract tagged null record; subtype Class is Instance'Class; function Get (Item : in Instance; Name : in String) return Class is abstract; function Get (Item : in Instance; Index : in Positive) return Class is abstract; function Get (Item : in Instance; Name : in String) return String is abstract; function Get (Item : in Instance; Index : in Positive) return String is abstract; function Get (Item : in Instance; Name : in String; Default : in String) return String is abstract; function Get (Item : in Instance; Index : in Positive; Default : in String) return String is abstract; function Has (Item : in Instance; Name : in String) return Boolean is (False); function Has (Item : in Instance; Index : in Positive) return Boolean is (False); end YAML.Abstract_Object;
-- Copyright (C) 2019 Thierry Rascle <thierr26@free.fr> -- MIT license. Please refer to the LICENSE file. with Apsepp.Scope_Bound_Locks.Private_Handler; package body Apsepp.Scope_Bound_Locks is ---------------------------------------------------------------------------- procedure SB_Lock_CB_procedure is begin if SBLCB_Access /= null then SBLCB_Access.all; end if; end SB_Lock_CB_procedure; ---------------------------------------------------------------------------- overriding procedure Initialize (Obj : in out SB_L_Locker) is use Private_Handler; begin Protected_Handler.Do_Lock (Lock => Obj.Lock, Actually_Locked => Obj.Has_Locked); Obj.Is_Instantiated := True; end Initialize; ---------------------------------------------------------------------------- overriding procedure Finalize (Obj : in out SB_L_Locker) is use Private_Handler; begin if SB_L_Locker'Class (Obj).Has_Actually_Locked then Protected_Handler.Do_Unlock (Lock => Obj.Lock); end if; end Finalize; ---------------------------------------------------------------------------- function Locked (Lock : SB_Lock) return Boolean is (Lock.Is_Locked); ---------------------------------------------------------------------------- not overriding function Has_Actually_Locked (Obj : SB_L_Locker) return Boolean is (Obj.Has_Locked); ---------------------------------------------------------------------------- end Apsepp.Scope_Bound_Locks;
with gel.Joint, gel.Sprite, physics.Joint.hinge, physics.Space; package gel.hinge_Joint -- -- Allows sprites to be connected via a hinge joint. -- is type Item is new gel.Joint.item with private; type View is access all Item'Class; type Views is array (math.Index range <>) of View; -- Degrees of freedom. -- Revolve : constant joint.Degree_of_freedom := 1; package std_physics renames standard.Physics; use Math; --------- --- Forge -- procedure define (Self : access Item; in_Space : in std_physics.Space.view; Sprite_A, Sprite_B : access gel.Sprite.item'Class; pivot_Axis : in Vector_3; Anchor_in_A : in Vector_3; Anchor_in_B : in Vector_3; low_Limit, high_Limit : in math.Real; collide_Conected : in Boolean); procedure define (Self : access Item; in_Space : in std_physics.Space.view; Sprite_A, Sprite_B : access gel.Sprite.item'Class; pivot_Axis : in Vector_3; pivot_Anchor : in Vector_3); procedure define (Self : access Item; in_Space : in std_physics.Space.view; Sprite_A, Sprite_B : access gel.Sprite.item'Class; pivot_Axis : in Vector_3); -- -- Uses midpoint between sprite A and B for the pivot anchor. procedure define (Self : access Item; in_Space : in std_physics.Space.view; Sprite_A, Sprite_B : access gel.Sprite.item'Class; Frame_A, Frame_B : in Matrix_4x4; low_Limit : in Real := to_Radians (-180.0); high_Limit : in Real := to_Radians ( 180.0); collide_Conected : in Boolean); procedure define (Self : access Item; in_Space : in std_physics.Space.view; Sprite_A : access gel.Sprite.item'Class; Frame_A : in Matrix_4x4); overriding procedure destroy (Self : in out Item); -------------- --- Attributes -- function Angle (Self : in Item'Class) return Real; overriding function Physics (Self : in Item) return Joint.Physics_view; procedure Limits_are (Self : in out Item'Class; Low, High : in Real; Softness : in Real := 0.9; bias_Factor : in Real := 0.3; relaxation_Factor : in Real := 1.0); overriding function Frame_A (Self : in Item) return Matrix_4x4; overriding function Frame_B (Self : in Item) return Matrix_4x4; overriding procedure Frame_A_is (Self : in out Item; Now : in Matrix_4x4); overriding procedure Frame_B_is (Self : in out Item; Now : in Matrix_4x4); overriding function Degrees_of_freedom (Self : in Item) return joint.degree_of_Freedom; -- Bounds - limits the range of motion for a degree of freedom. -- overriding function low_Bound (Self : access Item; for_Degree : in joint.Degree_of_freedom) return Real; overriding procedure low_Bound_is (Self : access Item; for_Degree : in joint.Degree_of_freedom; Now : in Real); overriding function high_Bound (Self : access Item; for_Degree : in joint.Degree_of_freedom) return Real; overriding procedure high_Bound_is (Self : access Item; for_Degree : in joint.Degree_of_freedom; Now : in Real); overriding function is_Bound (Self : in Item; for_Degree : in joint.Degree_of_freedom) return Boolean; overriding function Extent (Self : in Item; for_Degree : in joint.Degree_of_freedom) return Real; overriding procedure Velocity_is (Self : in Item; for_Degree : in joint.Degree_of_freedom; Now : in Real); -------------- --- Operations -- -- Nil. private type Item is new gel.Joint.item with record Physics : access std_physics.Joint.hinge.item'Class; low_Bound, high_Bound : Real; Softness : Real; bias_Factor : Real; relaxation_Factor : Real; end record; procedure apply_Limits (Self : in out Item); end gel.hinge_Joint;
------------------------------------------------------------------------------ -- host.ads -- -- This package defines the task for the host. The host allows the philoso- -- phers to enter and leave the restaurant. It also keeps track of how many -- philosophers have died. The host is called Norman_Bates. -- -- Entries: -- -- Enter Allows you to enter the restaurant provided there are -- at least two empty seats. -- Leave Allows you to leave the restaurant. -- Death_Announcement Records the fact that a philosopher has died. -- -- Behavior: -- -- The host just sits around waiting for someone to ask him to escort her -- in to or out of the restaurant, or to inform him of a (philosopher's) -- death. He will take requests to be seated only if there are at least two -- free seats at the table. He will take requests to leave at any time. -- After all the philosophers have informed him of their deaths, he will -- fire all the cooks. -- -- Termination: -- -- The host keeps track of how many philosophers are alive. When this count -- reaches zero, he will fire all the cooks and then subsequently terminate -- himself. -- -- Note: -- -- The use of a host in the Dining Philosophers Problem is controversial be- -- cause the system relies on the "ethics" of our philosophers. The phil- -- osophers must be honest and always use the host to enter and leave, and -- always inform the host that they are dead (or terminally ill and unable -- to eat again!) One advantage, though, of having the philosophers inform- -- ing the host of their death is that the host does not need to poll to see -- how many philosophers are alive. ------------------------------------------------------------------------------ package Host is task Norman_Bates is entry Enter; entry Leave; entry Death_Announcement; end Norman_Bates; end Host;
generic type Element_Type is private; type List_Type is array (Integer range <>) of Element_Type; with function Compare (Left : Element_Type; Right : Element_Type) return Boolean; with function To_String (E : Element_Type) return String; package Sort_Generics is procedure Sort_Generic (List : in out List_Type); procedure Display_List (List : in List_Type); end Sort_Generics;
-- Copyright (C) 2019 Thierry Rascle <thierr26@free.fr> -- MIT license. Please refer to the LICENSE file. with Apsepp.Test_Node_Class.Generic_Assert; use Apsepp.Test_Node_Class; with Apsepp.Abstract_Test_Case; use Apsepp.Abstract_Test_Case; private with Apsepp_Scope_Debug_Test_Fixture; package Apsepp_Scope_Debug_Test_Case is type Apsepp_Scope_Debug_T_C is limited new Test_Case with null record; overriding procedure Setup_Routine (Obj : Apsepp_Scope_Debug_T_C); overriding function Routine_Array (Obj : Apsepp_Scope_Debug_T_C) return Test_Routine_Array; overriding procedure Run (Obj : in out Apsepp_Scope_Debug_T_C; Outcome : out Test_Outcome; Kind : Run_Kind := Assert_Cond_And_Run_Test); private use Apsepp_Scope_Debug_Test_Fixture; procedure Assert is new Apsepp.Test_Node_Class.Generic_Assert (Test_Node_Tag => Apsepp_Scope_Debug_T_C'Tag); SDFDT_Instance : aliased SDFDT; end Apsepp_Scope_Debug_Test_Case;
pragma No_Run_Time; with Interfaces.C; package Compute is procedure Compute; pragma Export (C, Compute, "compute"); end Compute;
-- Copyright (c) 2019 Maxim Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- with Ada.Unchecked_Conversion; package Torrent.Handshakes is use type Ada.Streams.Stream_Element_Count; Header : constant String := "BitTorrent protocol"; subtype Handshake_Image is Ada.Streams.Stream_Element_Array (1 .. 1 + Header'Length + 8 + 2 * SHA1'Length); type Handshake_Type is record Length : Ada.Streams.Stream_Element := Header'Length; Head : String (Header'Range) := Header; Zeros : Ada.Streams.Stream_Element_Array (1 .. 8) := (others => 0); Info_Hash : SHA1; Peer_Id : SHA1; end record with Pack, Size => 8 * (1 + Header'Length + 8 + 2 * SHA1'Length); function "+" is new Ada.Unchecked_Conversion (Handshake_Type, Handshake_Image); function "-" is new Ada.Unchecked_Conversion (Handshake_Image, Handshake_Type); end Torrent.Handshakes;
package Levels is type Level_Id is (Outside, Inside, Cave); procedure Update; procedure Enter (Id : Level_Id); procedure Leave (Id : Level_Id); end Levels;
package body Semantica is procedure Abuit (P : out Pnode) is begin P := null; end Abuit; procedure Creanode_Programa (P : out Atribut; A : in Atribut) is begin P := A; Arbre := P.A; end Creanode_Programa; procedure Creanode (P : out Atribut; Fe, Fd : in Atribut; Tn : in Tipusnode) is Paux : Pnode; begin Paux := new Node(Tn); Paux.Fe1 := Fe.A; Paux.Fd1 := Fd.A; P := (Nodearbre, 0, 0, Paux); end Creanode; procedure Creanode (P : out Atribut; Fe, Fc, Fd : in Atribut; Tn : in Tipusnode) is Paux : Pnode; begin Paux := new Node(Tn); Paux.Fe2 := Fe.A; Paux.Fd2 := Fd.A; Paux.Fc2 := Fc.A; P := (Nodearbre, 0, 0, Paux); end Creanode; procedure Creanode (P : out Atribut; Fe, Fd : in Atribut; Op : in Operacio; Tn : in Tipusnode) is Paux : Pnode; begin Paux := new Node(Tn); Paux.Fe3 := Fe.A; Paux.Fd3 := Fd.A; Paux.Op3 := Op; P := (Nodearbre, 0, 0, Paux); end Creanode; procedure Creanode (P : out Atribut; F : in Atribut; Op : in Operacio; Tn : in Tipusnode) is Paux : Pnode; begin Paux := new Node(Tn); Paux.F4 := F.A; Paux.Op4 := Op; P := (Nodearbre, 0, 0, Paux); end Creanode; procedure Creanode (P : out Atribut; Fe, Fce, Fc, Fd : in Atribut; Tn : in Tipusnode) is Paux : Pnode; begin Paux := new Node(Tn); Paux.Fe5 := Fe.A; Paux.Fc5 := Fce.A; Paux.Fd5 := Fc.A; Paux.Fid5 := Fd.A; P := (Nodearbre, 0, 0, Paux); end Creanode; procedure Creanode (P : out atribut; F : in atribut; Tn : in Tipusnode) is Paux : Pnode; begin Paux := new Node(Tn); Paux.F6 := F.A; P := (Nodearbre, 0, 0, Paux); end Creanode; -- Crea node per identificadors procedure Creanode_Id (P : out Atribut; Id : in Atribut; Tn : in Tipusnode) is Paux : Pnode; begin Paux := new Node(Tn); Paux.Id12 := Id.Idn; Paux.L1 := Id.Lin; Paux.C1 := Id.Col; P := (Nodearbre, 0, 0, Paux); end Creanode_Id; procedure Creanode_Val (P : out Atribut; A : in Atribut; Tn : in Tipusnode; S : in Valor) is Paux : Pnode; begin Paux := new Node(Tn); if S = 0 then Paux.Val := A.Val*(-1); else Paux.Val := A.Val; end if; Paux.Tconst := A.T; Paux.L2 := A.Lin; Paux.C2 := A.Col; P := (Nodearbre, 0, 0, Paux); end Creanode_Val; procedure Creanode_Mode (P : out Atribut; M : in mmode; Tn : in Tipusnode) is Paux : Pnode; begin Paux := new Node(Tn); Paux.M12 := M; P := (NodeArbre, 0, 0, Paux); end Creanode_Mode; procedure Creanode (P : out Atribut; Tn : in Tipusnode) is Paux : Pnode; begin Paux := new Node(tn); P := (NodeArbre, 0, 0, Paux); end Creanode; procedure Remunta (P : out Atribut; A : in Atribut) is begin P := A; end Remunta; procedure Cons_Tnode (P : in Pnode; Tn : out Tipusnode) is begin Tn := P.Tipus; end Cons_Tnode; -- Procediments per a les Taules procedure Noves_taules (Tp : out T_Procs; Tv : out T_Vars) is begin Tp.Np := 0; Tv.Nv := 0; end Noves_taules; -- Procediments per Taula de Procediments procedure Posa (Tp : in out T_Procs; Ip : in Info_Proc; Idp : out num_Proc) is begin Tp.Np := Tp.Np+1; Tp.Tp(Tp.Np) := Ip; Idp := Tp.Np; end Posa; procedure Modif_Descripcio (Tp : in out T_Procs; Idp : in Num_Proc; Ip : in Info_Proc) is begin Tp.Tp(Idp) := Ip; end Modif_Descripcio; -- Procediments per a la Taula de Variables procedure Posa (Tv : in out T_Vars; Iv : in Info_Var; Idv : out Num_Var) is begin Tv.Nv := Tv.Nv+1; Tv.Tv(Tv.Nv) := Iv; Idv := Tv.Nv; end Posa; function Nova_Etiq return Num_Etiq is begin Ne := Ne+1; return Ne; end Nova_Etiq; end Semantica;
-- WORDS, a Latin dictionary, by Colonel William Whitaker (USAF, Retired) -- -- Copyright William A. Whitaker (1936–2010) -- -- This is a free program, which means it is proper to copy it and pass -- it on to your friends. Consider it a developmental item for which -- there is no charge. However, just for form, it is Copyrighted -- (c). Permission is hereby freely given for any and all use of program -- and data. You can sell it as your own, but at least tell me. -- -- This version is distributed without obligation, but the developer -- would appreciate comments and suggestions. -- -- All parts of the WORDS system, source code and data files, are made freely -- available to anyone who wishes to use them, for whatever purpose. with Text_IO; with Direct_IO; with Latin_Utils.Strings_Package; use Latin_Utils.Strings_Package; with Latin_Utils.Dictionary_Package; use Latin_Utils.Dictionary_Package; procedure Sorter is -- This program sorts a file of lines (Strings) on 4 subStrings Mx .. Nx -- Sort by Stringwise (different cases), numeric, or POS enumeration package Boolean_Io is new Text_IO.Enumeration_IO (Boolean); use Boolean_Io; package Integer_IO is new Text_IO.Integer_IO (Integer); use Integer_IO; package Float_IO is new Text_IO.Float_IO (Float); use Float_IO; use Text_IO; Name_Length : constant := 80; Enter_Line : String (1 .. Name_Length) := (others => ' '); Ls, Last : Integer := 0; Input_Name : String (1 .. 80) := (others => ' '); Line_Length : constant := 300; -- ################################## -- Max line length on input file -- Shorter => less disk space to sort Current_Length : Integer := 0; subtype Text_Type is String (1 .. Line_Length); --type LINE_TYPE is -- record -- CURRENT_LENGTH : CURRENT_LINE_LENGTH_TYPE := 0; -- TEXT : TEXT_TYPE; -- end record; package Line_Io is new Direct_IO (Text_Type); use Line_Io; Blank_Text : constant Text_Type := (others => ' '); Line_Text : Text_Type := Blank_Text; Old_Line : Text_Type := Blank_Text; P_Line : Text_Type := Blank_Text; type Sort_Type is (A, C, G, U, N, F, P, S); package Sort_Type_Io is new Text_IO.Enumeration_IO (Sort_Type); use Sort_Type_Io; type Way_Type is (I, D); package Way_Type_Io is new Text_IO.Enumeration_IO (Way_Type); use Way_Type_Io; Input : Text_IO.File_Type; Output : Text_IO.File_Type; Work : Line_Io.File_Type; M1, M2, M3, M4 : Natural := 1; N1, N2, N3, N4 : Natural := Line_Length; S1, S2, S3, S4 : Sort_Type := A; W1, W2, W3, W4 : Way_Type := I; Entry_Finished : exception; -- For section numbering of large documents and standards type Section_Type is record First_Level : Integer := 0; Second_Level : Integer := 0; Third_Level : Integer := 0; Fourth_Level : Integer := 0; Fifth_Level : Integer := 0; end record; No_Section : constant Section_Type := (0, 0, 0, 0, 0); type Appendix_Type is (None, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z); package Appendix_Io is new Text_IO.Enumeration_IO (Appendix_Type); type Appendix_Section_Type is record Appendix : Appendix_Type := None; Section : Section_Type := No_Section; end record; No_Appendix_Section : constant Appendix_Section_Type := (None, (0, 0, 0, 0, 0)); -- procedure PUT (OUTPUT : TEXT_IO.FILE_TYPE; S : SECTION_TYPE); -- procedure PUT (S : SECTION_TYPE); -- procedure GET (FROM : in STRING; -- S : out SECTION_TYPE; LAST : out POSITIVE); -- function "<"(A, B : SECTION_TYPE) return BOOLEAN; -- -- procedure PUT (OUTPUT : TEXT_IO.FILE_TYPE; S : APPENDIX_SECTION_TYPE); -- procedure PUT (S : APPENDIX_SECTION_TYPE); -- procedure GET (FROM : in STRING; -- S : out APPENDIX_SECTION_TYPE; LAST : out POSITIVE); -- function "<"(A, B : APPENDIX_SECTION_TYPE) return BOOLEAN; -- procedure Get (From : in String; S : out Section_Type; Last : out Integer) is L : Integer := 0; Lt : constant Integer := From'Last; begin S := No_Section; if Trim (From)'Last < From'First then Last := From'First - 1; -- Nothing got processed return; -- Empty String, no data -- Return default end if; Get (From, S.First_Level, L); if L + 1 >= Lt then Last := L; return; end if; Get (From (L + 2 .. Lt), S.Second_Level, L); if L + 1 >= Lt then Last := L; return; end if; Get (From (L + 2 .. Lt), S.Third_Level, L); if L + 1 >= Lt then Last := L; return; end if; Get (From (L + 2 .. Lt), S.Fourth_Level, L); if L + 1 >= Lt then Last := L; return; end if; Get (From (L + 2 .. Lt), S.Fifth_Level, L); Last := L; return; exception when Text_IO.End_Error => Last := L; return; when Text_IO.Data_Error => Last := L; return; when others => Put (" Unexpected exception in GET (FROM; SECTION_TYPE)" & " with input =>"); Put (From); New_Line; Last := L; raise; end Get; procedure Get (From : in String; S : out Appendix_Section_Type; Last : out Integer) is use Appendix_Io; L : Integer := 0; Ft : constant Integer := From'First; Lt : constant Integer := From'Last; begin S := No_Appendix_Section; if (Ft = Lt) or else (Trim (From)'Length = 0) then -- Empty/blank String, no data Put ("@"); Last := From'First - 1; -- Nothing got processed return; -- Return default end if; --PUT_LINE ("In GET =>" & FROM & '|'); begin Get (From, S.Appendix, L); --PUT ("A"); if L + 1 >= Lt then Last := L; return; end if; exception when others => S.Appendix := None; L := Ft - 2; end; -- PUT ("B"); -- GET (FROM (L+2 .. LT), S.SECTION.FIRST_LEVEL, L); -- if L+1 >= LT then -- LAST := L; -- return; -- end if; --PUT ("C"); -- GET (FROM (L+2 .. LT), S.SECTION.SECOND_LEVEL, L); -- if L+1 >= LT then -- LAST := L; -- return; -- end if; --PUT ("D"); -- GET (FROM (L+2 .. LT), S.SECTION.THIRD_LEVEL, L); -- if L+1 >= LT then -- LAST := L; -- return; -- end if; --PUT ("E"); -- GET (FROM (L+2 .. LT), S.SECTION.FOURTH_LEVEL, L); -- if L+1 >= LT then -- LAST := L; -- return; -- end if; --PUT ("F"); -- GET (FROM (L+2 .. LT), S.SECTION.FIFTH_LEVEL, L); -- LAST := L; --PUT ("G"); Get (From (L + 2 .. Lt), S.Section, L); --PUT ("F"); return; exception when Text_IO.End_Error => Last := L; return; when Text_IO.Data_Error => Last := L; return; when others => Put (" Unexpected exception in GET (FROM; APPENDIX_SECTION_TYPE)" & " with input =>"); Put (From); New_Line; Last := L; return; end Get; function "<"(A, B : Appendix_Section_Type) return Boolean is begin if A.Appendix > B.Appendix then return False; elsif A.Appendix < B.Appendix then return True; else if A.Section.First_Level > B.Section.First_Level then return False; elsif A.Section.First_Level < B.Section.First_Level then return True; else if A.Section.Second_Level > B.Section.Second_Level then return False; elsif A.Section.Second_Level < B.Section.Second_Level then return True; else if A.Section.Third_Level > B.Section.Third_Level then return False; elsif A.Section.Third_Level < B.Section.Third_Level then return True; else if A.Section.Fourth_Level > B.Section.Fourth_Level then return False; elsif A.Section.Fourth_Level < B.Section.Fourth_Level then return True; else if A.Section.Fifth_Level > B.Section.Fifth_Level then return False; elsif A.Section.Fifth_Level < B.Section.Fifth_Level then return True; else return False; end if; end if; end if; end if; end if; end if; end "<"; procedure Prompt_For_Entry (Entry_Number : String) is begin Put ("Give starting column and size of "); Put (Entry_Number); Put_Line (" significant sort field "); Put (" with optional sort type and way => "); end Prompt_For_Entry; procedure Get_Entry (Mx, Nx : out Natural; Sx : out Sort_Type; Wx : out Way_Type) is M : Natural := 1; N : Natural := Line_Length; S : Sort_Type := A; W : Way_Type := I; Z : Natural := 0; procedure Echo_Entry is begin Put (" Sorting on LINE ("); Put (M, 3); Put (" .. "); Put (N, 3); Put (")"); Put (" with S = "); Put (S); Put (" and W = "); Put (W); New_Line (2); end Echo_Entry; begin M := 0; N := Line_Length; S := A; W := I; Get_Line (Enter_Line, Ls); if Ls = 0 then raise Entry_Finished; end if; Integer_IO.Get (Enter_Line (1 .. Ls), M, Last); begin Integer_IO.Get (Enter_Line (Last + 1 .. Ls), Z, Last); if M = 0 or Z = 0 then Put_Line ("Start or size of zero, you must be kidding, aborting"); raise Program_Error; elsif M + Z > Line_Length then Put_Line ("Size too large, going to end of line"); N := Line_Length; else N := M + Z - 1; end if; Sort_Type_Io.Get (Enter_Line (Last + 1 .. Ls), S, Last); Way_Type_Io.Get (Enter_Line (Last + 1 .. Ls), W, Last); Mx := M; Nx := N; Sx := S; Wx := W; Echo_Entry; return; exception when Program_Error => Put_Line ("PROGRAM_ERROR raised in GET_ENTRY"); raise; when others => Mx := M; Nx := N; Sx := S; Wx := W; Echo_Entry; return; end; end Get_Entry; function Ignore_Separators (S : String) return String is T : String (S'First .. S'Last) := Lower_Case (S); begin for I in S'First + 1 .. S'Last - 1 loop if (S (I - 1) /= '-' and then S (I - 1) /= '_') and then (S (I) = '-' or else S (I) = '_') and then (S (I + 1) /= '-' and then S (I + 1) /= '_') then T (I) := ' '; end if; end loop; return T; end Ignore_Separators; function Ltu (C, D : Character) return Boolean is begin if D = 'v' then if C < 'u' then return True; else return False; end if; elsif D = 'j' then if C < 'i' then return True; else return False; end if; elsif D = 'V' then if C < 'U' then return True; else return False; end if; elsif D = 'J' then if C < 'I' then return True; else return False; end if; else return C < D; end if; end Ltu; function Equ (C, D : Character) return Boolean is begin if (D = 'u') or (D = 'v') then if (C = 'u') or (C = 'v') then return True; else return False; end if; elsif (D = 'i') or (D = 'j') then if (C = 'i') or (C = 'j') then return True; else return False; end if; elsif (D = 'U') or (D = 'V') then if (C = 'U') or (C = 'V') then return True; else return False; end if; elsif (D = 'I') or (D = 'J') then if (C = 'I') or (C = 'J') then return True; else return False; end if; else return C = D; end if; end Equ; function Gtu (C, D : Character) return Boolean is begin if D = 'u' then if C > 'v' then return True; else return False; end if; elsif D = 'i' then if C > 'j' then return True; else return False; end if; elsif D = 'U' then if C > 'V' then return True; else return False; end if; elsif D = 'I' then if C > 'J' then return True; else return False; end if; else return C > D; end if; end Gtu; function Ltu (S, T : String) return Boolean is begin for I in 1 .. S'Length loop -- Not TRIMed, so same length if Equ (S (S'First + I - 1), T (T'First + I - 1)) then null; elsif Gtu (S (S'First + I - 1), T (T'First + I - 1)) then return False; elsif Ltu (S (S'First + I - 1), T (T'First + I - 1)) then return True; end if; end loop; return False; end Ltu; function Gtu (S, T : String) return Boolean is begin for I in 1 .. S'Length loop if Equ (S (S'First + I - 1), T (T'First + I - 1)) then null; elsif Ltu (S (S'First + I - 1), T (T'First + I - 1)) then return False; elsif Gtu (S (S'First + I - 1), T (T'First + I - 1)) then return True; end if; end loop; return False; end Gtu; function Equ (S, T : String) return Boolean is begin if S'Length /= T'Length then return False; end if; for I in 1 .. S'Length loop if not Equ (S (S'First + I - 1), T (T'First + I - 1)) then return False; end if; end loop; return True; end Equ; function Slt (X, Y : String; -- Make LEFT and RIGHT St : Sort_Type := A; Wt : Way_Type := I) return Boolean is As : String (X'Range) := X; Bs : String (Y'Range) := Y; Mn, Nn : Integer := 0; Fn, Gn : Float := 0.0; --FS, GS : SECTION_TYPE := NO_SECTION; Fs, Gs : Appendix_Section_Type := No_Appendix_Section; Px, Py : Part_Entry; -- So I can X here begin if St = A then As := Lower_Case (As); Bs := Lower_Case (Bs); if Wt = I then return As < Bs; else return As > Bs; end if; elsif St = C then if Wt = I then return As < Bs; else return As > Bs; end if; elsif St = G then As := Ignore_Separators (As); Bs := Ignore_Separators (Bs); if Wt = I then return As < Bs; else return As > Bs; end if; elsif St = U then As := Lower_Case (As); Bs := Lower_Case (Bs); if Wt = I then return Ltu (As, Bs); else return Gtu (As, Bs); end if; elsif St = N then Integer_IO.Get (As, Mn, Last); Integer_IO.Get (Bs, Nn, Last); if Wt = I then return Mn < Nn; else return Mn > Nn; end if; elsif St = F then Float_IO.Get (As, Fn, Last); Float_IO.Get (Bs, Gn, Last); if Wt = I then return Fn < Gn; else return Fn > Gn; end if; elsif St = P then Part_Entry_IO.Get (As, Px, Last); Part_Entry_IO.Get (Bs, Py, Last); if Wt = I then return Px < Py; else return (not (Px < Py)) and (not (Px = Py)); end if; elsif St = S then --PUT_LINE ("AS =>" & AS & '|'); Get (As, Fs, Last); --PUT_LINE ("BS =>" & BS & '|'); Get (Bs, Gs, Last); --PUT_LINE ("GOT AS & BS"); if Wt = I then return Fs < Gs; else return (not (Fs < Gs)) and (not (Fs = Gs)); end if; else return False; end if; exception when others => Text_IO.Put_Line ("exception in SLT showing LEFT and RIGHT"); Text_IO.Put_Line (X & "&"); Text_IO.Put_Line (Y & "|"); raise; end Slt; function Sort_Equal (X, Y : String; St : Sort_Type := A; Wt : Way_Type := I) return Boolean is pragma Unreferenced (Wt); As : String (X'Range) := X; Bs : String (Y'Range) := Y; Mn, Nn : Integer := 0; Fn, Gn : Float := 0.0; Fs, Gs : Appendix_Section_Type := No_Appendix_Section; Px, Py : Part_Entry; begin if St = A then As := Lower_Case (As); Bs := Lower_Case (Bs); return As = Bs; elsif St = C then return As = Bs; elsif St = G then As := Ignore_Separators (As); Bs := Ignore_Separators (Bs); return As = Bs; elsif St = U then As := Lower_Case (As); Bs := Lower_Case (Bs); return Equ (As, Bs); elsif St = N then Integer_IO.Get (As, Mn, Last); Integer_IO.Get (Bs, Nn, Last); return Mn = Nn; elsif St = F then Float_IO.Get (As, Fn, Last); Float_IO.Get (Bs, Gn, Last); return Fn = Gn; elsif St = P then Part_Entry_IO.Get (As, Px, Last); Part_Entry_IO.Get (Bs, Py, Last); return Px = Py; elsif St = S then Get (As, Fs, Last); Get (Bs, Gs, Last); return Fs = Gs; else return False; end if; exception when others => Text_IO.Put_Line ("exception in LT showing LEFT and RIGHT"); Text_IO.Put_Line (X & "|"); Text_IO.Put_Line (Y & "|"); raise; end Sort_Equal; function Lt (Left, Right : Text_Type) return Boolean is begin if Slt (Left (M1 .. N1), Right (M1 .. N1), S1, W1) then return True; elsif Sort_Equal (Left (M1 .. N1), Right (M1 .. N1), S1, W1) then if (N2 > 0) and then Slt (Left (M2 .. N2), Right (M2 .. N2), S2, W2) then return True; elsif (N2 > 0) and then Sort_Equal (Left (M2 .. N2), Right (M2 .. N2), S2, W2) then if (N3 > 0) and then Slt (Left (M3 .. N3), Right (M3 .. N3), S3, W3) then return True; elsif (N3 > 0) and then Sort_Equal (Left (M3 .. N3), Right (M3 .. N3), S3, W3) then if (N4 > 0) and then Slt (Left (M4 .. N4), Right (M4 .. N4), S4, W4) then return True; end if; end if; end if; end if; return False; exception when others => Text_IO.Put_Line ("exception in LT showing LEFT and RIGHT"); Text_IO.Put_Line (Left & "|"); Text_IO.Put_Line (Right & "|"); raise; end Lt; procedure Open_File_For_Input (Input : in out Text_IO.File_Type; Prompt : String := "File for input => ") is Last : Natural := 0; begin Get_Input_File : loop Check_Input : begin New_Line; Put (Prompt); Get_Line (Input_Name, Last); Open (Input, In_File, Input_Name (1 .. Last)); exit Get_Input_File; exception when others => Put_Line (" !!!!!!!!! Try Again !!!!!!!!"); end Check_Input; end loop Get_Input_File; end Open_File_For_Input; procedure Create_File_For_Output (Output : in out Text_IO.File_Type; Prompt : String := "File for output => ") is Name : String (1 .. 80) := (others => ' '); Last : Natural := 0; begin Get_Output_File : loop Check_Output : begin New_Line; Put (Prompt); Get_Line (Name, Last); if Trim (Name (1 .. Last))'Length /= 0 then Create (Output, Out_File, Name (1 .. Last)); else Create (Output, Out_File, Trim (Input_Name)); end if; exit Get_Output_File; exception when others => Put_Line (" !!!!!!!!! Try Again !!!!!!!!"); end Check_Output; end loop Get_Output_File; end Create_File_For_Output; function Graphic (S : String) return String is T : String (1 .. S'Length) := S; begin for I in S'Range loop if Character'Pos (S (I)) < 32 then T (I) := ' '; end if; end loop; return T; end Graphic; begin New_Line; Put_Line ("Sorts a text file of lines four times on subStrings M .. N"); Put_Line ( "A)lphabetic (all case) C)ase sensitive, iG)nore separators, U)i_is_vj,"); Put_Line (" iN)teger, F)loating point, S)ection, or P)art entry"); Put_Line (" I)ncreasing or D)ecreasing"); New_Line; Open_File_For_Input (Input, "What file to sort from => "); New_Line; Prompt_For_Entry ("first"); begin Get_Entry (M1, N1, S1, W1); exception when Program_Error => raise; when others => null; end; begin Prompt_For_Entry ("second"); Get_Entry (M2, N2, S2, W2); Prompt_For_Entry ("third"); Get_Entry (M3, N3, S3, W3); Prompt_For_Entry ("fourth"); Get_Entry (M4, N4, S4, W4); exception --when Program_Error => -- raise; when Entry_Finished => null; when Text_IO.Data_Error | Text_IO.End_Error => null; end; --PUT_LINE ("CREATING WORK FILE"); New_Line; Create (Work, Inout_File, "WORK."); Put_Line ("CREATED WORK FILE"); while not End_Of_File (Input) loop --begin Get_Line (Input, Line_Text, Current_Length); --exception when others => --TEXT_IO.PUT_LINE ("INPUT GET exception"); --TEXT_IO.PUT_LINE (LINE_TEXT (1 .. CURRENT_LENGTH) & "|"); --end; --PUT_LINE (LINE_TEXT (1 .. CURRENT_LENGTH)); if Trim (Line_Text (1 .. Current_Length)) /= "" then --begin Write (Work, Head (Line_Text (1 .. Current_Length), Line_Length)); --exception when others => --TEXT_IO.PUT_LINE ("WORK WRITE exception"); --TEXT_IO.PUT_LINE (LINE_TEXT (1 .. CURRENT_LENGTH) & "|"); --end; end if; end loop; Close (Input); Put_Line ("Begin sorting"); Line_Heapsort : declare L : Line_Io.Positive_Count := Size (Work) / 2 + 1; Ir : Line_Io.Positive_Count := Size (Work); I, J : Line_Io.Positive_Count; begin Text_IO.Put_Line ("SIZE OF WORK = " & Integer'Image (Integer (Size (Work)))); Main : loop if L > 1 then L := L - 1; Read (Work, Line_Text, L); Old_Line := Line_Text; else Read (Work, Line_Text, Ir); Old_Line := Line_Text; Read (Work, Line_Text, 1); Write (Work, Line_Text, Ir); Ir := Ir - 1; if Ir = 1 then Write (Work, Old_Line, 1); exit Main; end if; end if; I := L; J := L + L; while J <= Ir loop if J < Ir then Read (Work, Line_Text, J); Read (Work, P_Line, J + 1); --if LT (LINE.TEXT, P_LINE.TEXT) then if Lt (Line_Text, P_Line) then J := J + 1; end if; end if; Read (Work, Line_Text, J); --if OLD_LINE.TEXT < LINE.TEXT then if Lt (Old_Line, Line_Text) then Write (Work, Line_Text, I); I := J; J := J + J; else J := Ir + 1; end if; end loop; Write (Work, Old_Line, I); end loop Main; exception when Constraint_Error => Put_Line ("HEAP CONSTRAINT_ERROR"); when others => Put_Line ("HEAP other_ERROR"); end Line_Heapsort; Put_Line ("Finished sorting in WORK"); Create_File_For_Output (Output, "Where to put the output => "); --RESET (WORK); Set_Index (Work, 1); while not End_Of_File (Work) loop Read (Work, Line_Text); if Trim (Graphic (Line_Text))'Length > 0 then --PUT_LINE (TRIM (LINE_TEXT, RIGHT)); Put_Line (Output, Trim (Line_Text, Right)); end if; end loop; Close (Work); Close (Output); Put_Line ("Done!"); New_Line; exception when Program_Error => Put_Line ("SORT terminated on a PROGRAM_ERROR"); Close (Output); when Text_IO.Data_Error => --Terminate on primary start or size = 0 Put_Line ("SORT terminated on a DATA_ERROR"); Put_Line (Line_Text); Close (Output); when Constraint_Error => --Terminate on blank line for file name Put_Line ("SORT terminated on a CONSTRAINT_ERROR"); Close (Output); when Text_IO.Device_Error => --Ran out of space to write output file Put_Line ("SORT terminated on a DEVICE_ERROR"); Delete (Output); Create_File_For_Output (Output, "Wherelse to put the output => "); Reset (Work); while not End_Of_File (Work) loop Read (Work, Line_Text); Put_Line (Output, Line_Text); --(1 .. LINE.CURRENT_LENGTH)); end loop; Close (Output); end Sorter;
-- { dg-do compile } with System.Storage_Elements; use System.Storage_Elements; procedure Address_Conv is subtype My_Address is System.Address; type Rec is record A : My_Address; end record; Addr : constant My_Address := To_Address (16#FACEFACE#); R : constant Rec := (A => Addr); begin null; end;
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 euler34 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; type h is Array (Integer range <>) of Integer; type h_PTR is access h; sum : Integer; out0 : Integer; num : Integer; f : h_PTR; begin f := new h (0..9); for j in integer range 0..9 loop f(j) := 1; end loop; for i in integer range 1..9 loop f(i) := f(i) * i * f(i - 1); PInt(f(i)); PString(new char_array'( To_C(" "))); end loop; out0 := 0; PString(new char_array'( To_C("" & Character'Val(10)))); for a in integer range 0..9 loop for b in integer range 0..9 loop for c in integer range 0..9 loop for d in integer range 0..9 loop for e in integer range 0..9 loop for g in integer range 0..9 loop sum := f(a) + f(b) + f(c) + f(d) + f(e) + f(g); num := ((((a * 10 + b) * 10 + c) * 10 + d) * 10 + e) * 10 + g; if a = 0 then sum := sum - 1; if b = 0 then sum := sum - 1; if c = 0 then sum := sum - 1; if d = 0 then sum := sum - 1; end if; end if; end if; end if; if (sum = num and then sum /= 1) and then sum /= 2 then out0 := out0 + num; PInt(num); PString(new char_array'( To_C(" "))); end if; end loop; end loop; end loop; end loop; end loop; end loop; PString(new char_array'( To_C("" & Character'Val(10)))); PInt(out0); PString(new char_array'( To_C("" & Character'Val(10)))); end;
with hauntedhouse, tools; use hauntedhouse; procedure Demo is -- Princess task princess is entry scare(ghostPos: Position); end princess; task body princess is pos : Position := (1,3); hp : Natural := 3; begin while hp > 0 loop select when IsCorridor(pos) => accept scare(ghostPos: Position) do if ghostPos.x = pos.x and ghostPos.y = pos.y then hp := hp - 1; tools.Output.Puts("Princess scared - hp:" & Natural'Image(hp), 1); end if; end scare; end select; end loop; tools.Output.Puts("Princess dead", 1); end princess; -- Ghost task type Ghost; task body Ghost is pos : Position; begin while princess'Callable loop pos := GetRandPos; tools.Output.Puts("Ghost" & Natural'Image(pos.x) & "," & Natural'Image(pos.y), 1); princess.scare(pos); delay 0.2; end loop; end Ghost; ghosts : array (1 .. 3) of Ghost; begin null; end Demo;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2018, 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 System; with Interfaces; use Interfaces; with HAL; use HAL; with HAL.Time; package MPU60x0 is -- TODO: Definition of Configuration and Value record type MPU60x0_Sensor_Reading is record Accel_X : Integer_16; Accel_Y : Integer_16; Accel_Z : Integer_16; Temp : Integer_16; Gyro_X : Integer_16; Gyro_Y : Integer_16; Gyro_Z : Integer_16; end record with Size => 112; -- Since the Values are stored in big endian order in the sensor for MPU60x0_Sensor_Reading'Bit_Order use System.High_Order_First; for MPU60x0_Sensor_Reading'Scalar_Storage_Order use System.High_Order_First; pragma Pack (MPU60x0_Sensor_Reading); type MPU60x0_Sensor_Reading_Float is record Accel_X : Float; Accel_Y : Float; Accel_Z : Float; Temp : Float; Gyro_X : Float; Gyro_Y : Float; Gyro_Z : Float; end record with Size => 224; pragma Pack (MPU60x0_Sensor_Reading_Float); type MPU60x0_Gyro_Scale_Range is (deg_250_s, deg_500_s, deg_1000_s, deg_2500_s) with Size => 2; for MPU60x0_Gyro_Scale_Range use (deg_250_s => 0, deg_500_s => 1, deg_1000_s => 2, deg_2500_s => 3); type MPU60x0_Accel_Scale_Range is (g2, g4, g8, g16) with Size => 2; for MPU60x0_Accel_Scale_Range use (g2 => 0, g4 => 1, g8 => 2, g16 => 3); type MPU60x0_Configuration is record Time : HAL.Time.Any_Delays; Accel_Scale_Range : MPU60x0_Accel_Scale_Range; Gyro_Scale_Range : MPU60x0_Gyro_Scale_Range; -- TODO: Digital Filter setting -- TODO: Sample Speed setting -- TODO: Clock source settin end record; type MPU60x0_Self_Test_Response is record XA : Float; YA : Float; ZA : Float; XG : Float; YG : Float; ZG : Float; end record; type MPU60x0_Config_Access is access all MPU60x0_Configuration; type MPU60x0_Device is tagged limited private; procedure Configure (This : in out MPU60x0_Device; Conf : MPU60x0_Configuration); procedure Read_Values (This : MPU60x0_Device; Values : in out MPU60x0_Sensor_Reading); procedure Read_Values_Float (This : MPU60x0_Device; Values : in out MPU60x0_Sensor_Reading_Float); procedure Get_ST_Results (This : MPU60x0_Device; Values : out MPU60x0_Self_Test_Response); private type Self_Test_Registers is record XA_Test_H : UInt3; XG_Test : UInt5; YA_Test_H : UInt3; YG_Test : UInt5; ZA_Test_H : UInt3; ZG_Test : UInt5; Reserved_6_7 : UInt2; XA_Test_L : UInt2; YA_Test_L : UInt2; ZA_Test_L : UInt2; end record with Size => 32; for Self_Test_Registers use record XA_Test_H at 0 range 5 .. 7; XG_Test at 0 range 0 .. 4; YA_Test_H at 1 range 5 .. 7; YG_Test at 1 range 0 .. 4; ZA_Test_H at 2 range 5 .. 7; ZG_Test at 2 range 0 .. 4; Reserved_6_7 at 3 range 6 .. 7; XA_Test_L at 3 range 4 .. 5; YA_Test_L at 3 range 2 .. 3; ZA_Test_L at 3 range 0 .. 1; end record; SELF_TEST_REG_ADDRESS : constant UInt8 := 16#0D#; function Get_Deriv (Read1 : Float; Read2 : Float; FT : Float) return Float; function Get_G_FT (Input : UInt5) return Float; function Get_A_FT (Input_H : UInt3; Input_L : UInt2) return Float; type Sample_Rate_Divider is new UInt8; SR_DIV_ADDRESS : constant UInt8 := 16#19#; type MPU60x0_Filter_Setting is new UInt3; type Config is record Reserved_3_7 : UInt5; Filter_Setting : MPU60x0_Filter_Setting; end record with Size => 8; for Config use record Reserved_3_7 at 0 range 3 .. 7; Filter_Setting at 0 range 0 .. 2; end record; CONFIG_ADDRESS : constant UInt8 := 16#1A#; type Gyro_Config is record XG_Selftest : Boolean; YG_Selftest : Boolean; ZG_Selftest : Boolean; Scale_Range : MPU60x0_Gyro_Scale_Range; Reserved_0_2 : UInt3; end record with Size => 8; for Gyro_Config use record XG_Selftest at 0 range 7 .. 7; YG_Selftest at 0 range 6 .. 6; ZG_Selftest at 0 range 5 .. 5; Scale_Range at 0 range 3 .. 4; Reserved_0_2 at 0 range 0 .. 2; end record; GYRO_CONFIG_ADDRESS : constant UInt8 := 16#1B#; type Accel_Config is record XA_Selftest : Boolean; YA_Selftest : Boolean; ZA_Selftest : Boolean; Scale_range : MPU60x0_Accel_Scale_Range; Reserved_0_2 : UInt3; end record with Size => 8; for Accel_Config use record XA_Selftest at 0 range 7 .. 7; YA_Selftest at 0 range 6 .. 6; ZA_Selftest at 0 range 5 .. 5; Scale_Range at 0 range 3 .. 4; Reserved_0_2 at 0 range 0 .. 2; end record; ACCEL_CONFIG_ADDRESS : constant UInt8 := 16#1C#; -- TODO : FIFO enable register type Int_Pin_Config is record Int_Level : Boolean; Int_Open : Boolean; Latch_Int_Enable : Boolean; Int_Read_Clear : Boolean; FSync_Int_Level : Boolean; FSync_Int_Enable : Boolean; I2C_Bypass_Enable : Boolean; Reserved_0 : Boolean; end record with Size => 8; for Int_Pin_Config use record Int_Level at 0 range 7 .. 7; Int_Open at 0 range 6 .. 6; Latch_Int_Enable at 0 range 5 .. 5; Int_Read_Clear at 0 range 4 .. 4; FSync_Int_Level at 0 range 3 .. 3; FSync_Int_Enable at 0 range 2 .. 2; I2C_Bypass_Enable at 0 range 1 .. 1; Reserved_0 at 0 range 0 .. 0; end record; INT_PIN_CFG_ADDRESS : constant UInt8 := 16#37#; type Int_Enable is record Reserved_5_7 : UInt3; Fifo_Overflow_Enable : Boolean; I2C_Master_Int_Enable : Boolean; Reserved_1_2 : UInt2; Data_Ready_Enable : Boolean; end record with Size => 8; for Int_Enable use record Reserved_5_7 at 0 range 5 .. 7; Fifo_Overflow_Enable at 0 range 4 .. 4; I2C_Master_Int_Enable at 0 range 3 .. 3; Reserved_1_2 at 0 range 1 .. 2; Data_Ready_Enable at 0 range 0 .. 0; end record; INT_ENABLE_ADDRESS : constant UInt8 := 16#38#; type Int_Status is record Reserved_5_7 : UInt3; Fifo_Overflow : Boolean; I2C_Master_Int : Boolean; Reserved_1_2 : UInt2; Data_Ready : Boolean; end record with Size => 8; for Int_Status use record Reserved_5_7 at 0 range 5 .. 7; Fifo_Overflow at 0 range 4 .. 4; I2C_Master_Int at 0 range 3 .. 3; Reserved_1_2 at 0 range 1 .. 2; Data_Ready at 0 range 0 .. 0; end record; INT_STATUS_ADDRESS : constant UInt8 := 16#3A#; SENSOR_DATA_ADDRESS : constant UInt8 := 16#3B#; type Signal_Path_Reset is record Reserved_3_7 : UInt5; Gyro_Reset : Boolean; Accel_Reset : Boolean; Temp_Reset : Boolean; end record with Size => 8; for Signal_Path_Reset use record Reserved_3_7 at 0 range 3 .. 7; Gyro_Reset at 0 range 2 .. 2; Accel_Reset at 0 range 1 .. 1; Temp_Reset at 0 range 0 .. 0; end record; SIGNAL_PATH_RESET_ADDRESS : constant UInt8 := 16#68#; type User_Control is record Reserved_7 : Boolean; Fifo_Enable : Boolean; I2C_Master_Enable : Boolean; I2C_IF_Enable : Boolean; Reserved_3 : Boolean; Fifo_Reset : Boolean; I2C_Master_Reset : Boolean; Sensor_Reset : Boolean; end record with Size => 8; for User_Control use record Reserved_7 at 0 range 7 .. 7; Fifo_Enable at 0 range 6 .. 6; I2C_Master_Enable at 0 range 5 .. 5; I2C_IF_Enable at 0 range 4 .. 4; Reserved_3 at 0 range 3 .. 3; Fifo_Reset at 0 range 2 .. 2; I2C_Master_Reset at 0 range 1 .. 1; Sensor_Reset at 0 range 0 .. 0; end record; USER_CONTROL_ADDRESS : constant UInt8 := 16#6A#; type MPU60x0_Clock_Selection is (Internal, PLL_X, PLL_Y, PLL_Z, PLL_Ext_32kHz, PLL_Ext_19MHz, Stop) with Size => 3; for MPU60x0_Clock_Selection use (Internal => 0, PLL_X => 1, PLL_Y => 2, PLL_Z => 3, PLL_Ext_32kHz => 4, PLL_Ext_19MHz => 5, Stop => 7); type Power_Management1 is record Device_Reset : Boolean; Sleep : Boolean; Cycle : Boolean; Reserved_4 : Boolean; Temp_Disable : Boolean; Clock_Selection : MPU60x0_Clock_Selection; end record with Size => 8; for Power_Management1 use record Device_Reset at 0 range 7 .. 7; Sleep at 0 range 6 .. 6; Cycle at 0 range 5 .. 5; Reserved_4 at 0 range 4 .. 4; Temp_Disable at 0 range 3 .. 3; Clock_Selection at 0 range 0 .. 2; end record; POWER_MANAGEMENT1_ADDRESS : constant UInt8 := 16#6B#; type MPU60x0_WakeUp_Freq is (Hz1_25, Hz5, Hz20, Hz40) with Size => 2; for MPU60x0_WakeUp_Freq use (Hz1_25 => 0, Hz5 => 1, Hz20 => 2, Hz40 => 3); type Power_Management2 is record WakeUp_Freq : MPU60x0_WakeUp_Freq; XA_Standby : Boolean; YA_Standby : Boolean; ZA_Standby : Boolean; XG_Standby : Boolean; YG_Standby : Boolean; ZG_Standby : Boolean; end record with Size => 8; for Power_Management2 use record WakeUp_Freq at 0 range 6 .. 7; XA_Standby at 0 range 5 .. 5; YA_Standby at 0 range 4 .. 4; ZA_Standby at 0 range 3 .. 3; XG_Standby at 0 range 2 .. 2; YG_Standby at 0 range 1 .. 1; ZG_Standby at 0 range 0 .. 0; end record; POWER_MANAGEMENT2_ADDRESS : constant UInt8 := 16#6C#; -- TODO : FiFo count and Data WHOAMI_ADDRESS : constant UInt8 := 16#75#; WHOAMI_VALUE : constant UInt8 := 2#01101000#; type Byte_Array is array (Positive range <>) of UInt8 with Alignment => 2; type Byte_Array_Access is access Byte_Array; type MPU60x0_Device is tagged limited record Conf : MPU60x0_Configuration; end record; procedure Read_Port (This : MPU60x0_Device; Address : UInt8; Data : out Byte_Array); procedure Write_Port (This : MPU60x0_Device; Address : UInt8; Data : UInt8); end MPU60x0;
package body Math_2D.Points is use type Types.Real_Type; use type Types.Point_t; function Distance (Point_A : in Types.Point_t; Point_B : in Types.Point_t) return Types.Real_Type'Base is begin return Vectors.Magnitude (Types.Vector_t (Point_A - Point_B)); end Distance; end Math_2D.Points;
-- Note: This test does not yet work due to problems with -- declaring tasks. We can't abort without a task --with Ada.Text_IO; procedure Task_With_Abort is task AbortMe is entry Go; end AbortMe; task body AbortMe is begin accept Go; loop delay 1.0; --Ada.Text_IO.Put_Line("I'm not dead yet!"); end loop; end AbortMe; begin AbortMe.Go; delay 10.0; abort AbortMe; --Ada.Text_IO.Put_Line("Aborted AbortMe"); delay 2.0; end Task_With_Abort;
with Ada.Strings.Unbounded; with A_Nodes; with Dot; with Indented_Text; private with Ada.Exceptions; private with Ada.Text_IO; private with Ada.Wide_Text_IO; private with Asis; private with Asis.Set_Get; private with Interfaces.C.Extensions; private with Interfaces.C.Strings; private with Unchecked_Conversion; -- GNAT-specific: private with A4G.A_Types; private with Types; private with a_nodes_h.Support; -- Contains supporting declarations for child packages package Asis_Adapter is -- Controls behavior of Trace_ routines. Renamed here so clients have to -- with fewer packages: Trace_On : Boolean renames Indented_Text.Trace_On; Log_On : Boolean ; type Outputs_Record is record -- Initialized Output_Dir : Ada.Strings.Unbounded.Unbounded_String; -- Initialized A_Nodes : Standard.A_Nodes.Access_Class; -- Initialized Graph : Dot.Graphs.Access_Class; -- Initialized Text : Indented_Text.Access_Class; -- Initialized end record; -- Raised when a subprogram is called incorrectly: Usage_Error : Exception; -- Raised when an external routine fails and the subprogram cannot continue: External_Error : Exception; -- Raised when an external routine raises a usage-error-like exception or -- there is an internal logic error: Internal_Error : Exception; private Module_Name : constant String := "Asis_Adapter"; package AEX renames Ada.Exceptions; package ASU renames Ada.Strings.Unbounded; package ATI renames Ada.Text_IO; package AWTI renames Ada.Wide_Text_IO; package IC renames Interfaces.C; package ICE renames Interfaces.C.Extensions; package ICS renames Interfaces.C.Strings; package anhS renames a_nodes_h.Support; function To_String (Item : in Wide_String) return String; function To_Quoted_String (Item : in Wide_String) return String; function "+"(Item : in Wide_String) return String renames To_String; function To_Wide_String (Item : in String) return Wide_String; function "+"(Item : in String) return Wide_String renames To_Wide_String; function To_Chars_Ptr (Item : in Wide_String) return Interfaces.C.Strings.chars_ptr; function To_Chars_Ptr (Item : in String) return Interfaces.C.Strings.chars_ptr renames Interfaces.C.Strings.New_String; procedure Put (Item : in String) renames ATI.Put; procedure Put_Line (Item : in String) renames ATI.Put_Line; procedure Put_Wide (Item : in Wide_String) renames AWTI.Put; procedure Put_Line_Wide (Item : in Wide_String) renames AWTI.Put_Line; procedure Trace_Put (Message : in Wide_String) renames Indented_Text.Trace_Put; procedure Trace_Put_Line (Message : in Wide_String) renames Indented_Text.Trace_Put_Line; -- Provides routines that peofix the output with the name of the current -- module: generic Module_Name : in string; package Generic_Logging is procedure Log (Message : in String); procedure Log_Wide (Message : in Wide_String); procedure Log_Exception (X : in Aex.Exception_Occurrence); end Generic_Logging; -- Returns the image minus the leading space: function Spaceless_Image (Item : in Natural) return String; function NLB_Image (Item : in Natural) return String renames Spaceless_Image; type ID_Kind is (Unit_ID_Kind, Element_ID_Kind); function To_String (Id : in IC.int; Kind : in ID_Kind) return String; function To_Dot_ID_Type (Id : in IC.int; Kind : in ID_Kind) return Dot.ID_Type; -- String: -- Add <Name> => <Value> to the label, and print it if trace is on: procedure Add_To_Dot_Label (Dot_Label : in out Dot.HTML_Like_Labels.Class; Outputs : in out Outputs_Record; Name : in String; Value : in String); -- Boolean: -- Add <Name> => <Value> to the label, and print it if trace is on: -- ONLY acts if Value = True: procedure Add_To_Dot_Label (Dot_Label : in out Dot.HTML_Like_Labels.Class; Outputs : in out Outputs_Record; Name : in String; Value : in Boolean); -- String: -- Add <Value> to the label, and print it if trace is on: procedure Add_To_Dot_Label (Dot_Label : in out Dot.HTML_Like_Labels.Class; Outputs : in out Outputs_Record; Value : in String); -- Unit_ID or Element_ID: -- Add an edge node to the the dot graph: -- Use for both Unit_ID and Element_ID: procedure Add_Dot_Edge (Outputs : in out Outputs_Record; From : in IC.int; From_Kind : in ID_Kind; To : in IC.int; To_Kind : in ID_Kind; Label : in String); -- Order below is alphabetical: function To_Access_Definition_Kinds is new Unchecked_Conversion (Source => Asis.Access_Definition_Kinds, Target => a_nodes_h.Access_Definition_Kinds); function To_Access_Type_Kinds is new Unchecked_Conversion (Source => Asis.Access_Type_Kinds, Target => a_nodes_h.Access_Type_Kinds); function To_Association_Kinds is new Unchecked_Conversion (Source => Asis.Association_Kinds, Target => a_nodes_h.Association_Kinds); function To_Attribute_Kinds is new Unchecked_Conversion (Source => Asis.Attribute_Kinds, Target => a_nodes_h.Attribute_Kinds); function To_Clause_Kinds is new Unchecked_Conversion (Source => Asis.Clause_Kinds, Target => a_nodes_h.Clause_Kinds); function To_Representation_Clause_Kinds is new Unchecked_Conversion (Source => Asis.Representation_Clause_Kinds, Target => a_nodes_h.Representation_Clause_Kinds); function To_Constraint_Kinds is new Unchecked_Conversion (Source => Asis.Constraint_Kinds, Target => a_nodes_h.Constraint_Kinds); function To_Declaration_Kinds is new Unchecked_Conversion (Source => Asis.Declaration_Kinds, Target => a_nodes_h.Declaration_Kinds); function To_Declaration_Origins is new Unchecked_Conversion (Source => Asis.Declaration_Origins, Target => a_nodes_h.Declaration_Origins); function To_Defining_Name_Kinds is new Unchecked_Conversion (Source => Asis.Defining_Name_Kinds, Target => a_nodes_h.Defining_Name_Kinds); function To_Definition_Kinds is new Unchecked_Conversion (Source => Asis.Definition_Kinds, Target => a_nodes_h.Definition_Kinds); function To_Discrete_Range_Kinds is new Unchecked_Conversion (Source => Asis.Discrete_Range_Kinds, Target => a_nodes_h.Discrete_Range_Kinds); function To_Element_Kinds is new Unchecked_Conversion (Source => Asis.Element_Kinds, Target => a_nodes_h.Element_Kinds); function To_Expression_Kinds is new Unchecked_Conversion (Source => Asis.Expression_Kinds, Target => a_nodes_h.Expression_Kinds); function To_Formal_Type_Kinds is new Unchecked_Conversion (Source => Asis.Formal_Type_Kinds, Target => a_nodes_h.Formal_Type_Kinds); function To_Mode_Kinds is new Unchecked_Conversion (Source => Asis.Mode_Kinds, Target => a_nodes_h.Mode_Kinds); function To_Operator_Kinds is new Unchecked_Conversion (Source => Asis.Operator_Kinds, Target => a_nodes_h.Operator_Kinds); function To_Path_Kinds is new Unchecked_Conversion (Source => Asis.Path_Kinds, Target => a_nodes_h.Path_Kinds); function To_Pragma_Kinds is new Unchecked_Conversion (Source => Asis.Pragma_Kinds, Target => a_nodes_h.Pragma_Kinds); function To_Root_Type_Kinds is new Unchecked_Conversion (Source => Asis.Root_Type_Kinds, Target => a_nodes_h.Root_Type_Kinds); function To_Statement_Kinds is new Unchecked_Conversion (Source => Asis.Statement_Kinds, Target => a_nodes_h.Statement_Kinds); function To_Subprogram_Default_Kinds is new Unchecked_Conversion (Source => Asis.Subprogram_Default_Kinds, Target => a_nodes_h.Subprogram_Default_Kinds); function To_Type_Kinds is new Unchecked_Conversion (Source => Asis.Type_Kinds, Target => a_nodes_h.Type_Kinds); function To_Unit_Classes is new Unchecked_Conversion (Source => Asis.Unit_Classes, Target => a_nodes_h.Unit_Classes); function To_Unit_Kinds is new Unchecked_Conversion (Source => Asis.Unit_Kinds, Target => a_nodes_h.Unit_Kinds); function To_Unit_Origins is new Unchecked_Conversion (Source => Asis.Unit_Origins, Target => a_nodes_h.Unit_Origins); -- End alphabetical order end Asis_Adapter;
-- Lumen.Binary.IO -- Read and write streams of binary data from external -- files. -- -- Chip Richards, NiEstu, Phoenix AZ, Summer 2010 -- This code is covered by the ISC License: -- -- Copyright © 2010, 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. -- Environment with System.Address_To_Access_Conversions; package body Lumen.Binary.IO is --------------------------------------------------------------------------- -- Useful constant for our short I/O routines Bytes_Per_Short : constant := Short'Size / Ada.Streams.Stream_Element'Size; Bytes_Per_Word : constant := Word'Size / Ada.Streams.Stream_Element'Size; --------------------------------------------------------------------------- -- Open a file for reading procedure Open (File : in out File_Type; Pathname : in String) is begin -- Open -- Just regular stream open, for reading Ada.Streams.Stream_IO.Open (File => File, Mode => Ada.Streams.Stream_IO.In_File, Name => Pathname); exception when Ada.Streams.Stream_IO.Name_Error => raise Nonexistent_File; when Ada.Streams.Stream_IO.Use_Error => raise Unreadable_File; when Ada.Streams.Stream_IO.Device_Error => raise Access_Failed; when others => raise Unknown_Error; end Open; --------------------------------------------------------------------------- -- Create a file for writing procedure Create (File : in out File_Type; Pathname : in String) is begin -- Create -- Just regular stream create, for writing Ada.Streams.Stream_IO.Create (File => File, Mode => Ada.Streams.Stream_IO.Out_File, Name => Pathname); exception when Ada.Streams.Stream_IO.Name_Error => raise Malformed_Name; when Ada.Streams.Stream_IO.Use_Error => raise Unwriteable_File; when Ada.Streams.Stream_IO.Device_Error => raise Access_Failed; when others => raise Unknown_Error; end Create; --------------------------------------------------------------------------- -- Close open file procedure Close (File : in out File_Type) is begin -- Close Ada.Streams.Stream_IO.Close (File); end Close; --------------------------------------------------------------------------- -- Read and return a stream of bytes up to the given length function Read (File : File_Type; Length : Positive) return Byte_String is use Ada.Streams; -- Pointer-fumbling routines used to read data without copying it subtype SEA is Stream_Element_Array (1 .. Stream_Element_Offset (Length)); package SEA_Addr is new System.Address_To_Access_Conversions (SEA); Into : Byte_String (1 .. Length); Item : constant SEA_Addr.Object_Pointer := SEA_Addr.To_Pointer (Into'Address); Got : Stream_Element_Offset; begin -- Read Stream_IO.Read (File, Item.all, Got); return Into (Into'First .. Natural (Got)); exception when others => raise Read_Error; end Read; --------------------------------------------------------------------------- -- Read and return a stream of bytes up to the length of the given buffer procedure Read (File : in File_Type; Item : out Byte_String; Last : out Natural) is use Ada.Streams; -- Pointer-fumbling routines used to read data without copying it subtype SEA is Stream_Element_Array (Stream_Element_Offset (Item'First) .. Stream_Element_Offset (Item'Last)); package SEA_Addr is new System.Address_To_Access_Conversions (SEA); Into : constant SEA_Addr.Object_Pointer := SEA_Addr.To_Pointer (Item'Address); Got : Stream_Element_Offset; begin -- Read Stream_IO.Read (File, Into.all, Got); Last := Natural (Got); exception when others => raise Read_Error; end Read; --------------------------------------------------------------------------- -- Read and return a stream of shorts up to the given length function Read (File : File_Type; Length : Positive) return Short_String is use Ada.Streams; -- Pointer-fumbling routines used to read data without copying it subtype SEA is Stream_Element_Array (1 .. Stream_Element_Offset (Length * Bytes_Per_Short)); package SEA_Addr is new System.Address_To_Access_Conversions (SEA); Into : Short_String (1 .. Length); Item : constant SEA_Addr.Object_Pointer := SEA_Addr.To_Pointer (Into'Address); Got : Stream_Element_Offset; begin -- Read Stream_IO.Read (File, Item.all, Got); return Into (Into'First .. Natural (Got / Bytes_Per_Short)); exception when others => raise Read_Error; end Read; --------------------------------------------------------------------------- -- Read and return a stream of shorts up to the length of the given buffer procedure Read (File : in File_Type; Item : out Short_String; Last : out Natural) is use Ada.Streams; -- Pointer-fumbling routines used to read data without copying it subtype SEA is Stream_Element_Array (1 .. Stream_Element_Offset (Item'Length * Bytes_Per_Short)); package SEA_Addr is new System.Address_To_Access_Conversions (SEA); Into : constant SEA_Addr.Object_Pointer := SEA_Addr.To_Pointer (Item'Address); Got : Stream_Element_Offset; begin -- Read Stream_IO.Read (File, Into.all, Got); Last := Natural (Got); exception when others => raise Read_Error; end Read; --------------------------------------------------------------------------- -- Read and return a stream of words up to the given length function Read (File : File_Type; Length : Positive) return Word_String is use Ada.Streams; -- Pointer-fumbling routines used to read data without copying it subtype SEA is Stream_Element_Array (1 .. Stream_Element_Offset (Length * Bytes_Per_Word)); package SEA_Addr is new System.Address_To_Access_Conversions (SEA); Into : Word_String (1 .. Length); Item : constant SEA_Addr.Object_Pointer := SEA_Addr.To_Pointer (Into'Address); Got : Stream_Element_Offset; begin -- Read Stream_IO.Read (File, Item.all, Got); return Into (Into'First .. Natural (Got / Bytes_Per_Word)); exception when others => raise Read_Error; end Read; --------------------------------------------------------------------------- -- Read and return a stream of words up to the length of the given buffer procedure Read (File : in File_Type; Item : out Word_String; Last : out Natural) is use Ada.Streams; -- Pointer-fumbling routines used to read data without copying it subtype SEA is Stream_Element_Array (1 .. Stream_Element_Offset (Item'Length * Bytes_Per_Word)); package SEA_Addr is new System.Address_To_Access_Conversions (SEA); Into : constant SEA_Addr.Object_Pointer := SEA_Addr.To_Pointer (Item'Address); Got : Stream_Element_Offset; begin -- Read Stream_IO.Read (File, Into.all, Got); Last := Natural (Got); exception when others => raise Read_Error; end Read; --------------------------------------------------------------------------- -- Write a stream of bytes procedure Write (File : in File_Type; Item : in Byte_String) is use Ada.Streams; -- Pointer-fumbling routines used to write data without copying it subtype SEA is Stream_Element_Array (Stream_Element_Offset (Item'First) .. Stream_Element_Offset (Item'Last)); package SEA_Addr is new System.Address_To_Access_Conversions (SEA); From : constant SEA_Addr.Object_Pointer := SEA_Addr.To_Pointer (Item'Address); begin -- Write Stream_IO.Write (File, From.all); exception when others => raise Write_Error; end Write; --------------------------------------------------------------------------- end Lumen.Binary.IO;
-- Copyright (c) 2019 Maxim Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- with Program.Dummy_Subpools; package Program.Storage_Pools is pragma Preelaborate; subtype Storage_Pool is Program.Dummy_Subpools.Dummy_Storage_Pool; type Storage_Pool_Access is not null access all Storage_Pool; Pool_Access : constant Storage_Pool_Access with Import, External_Name => "pool_access"; Pool : Storage_Pool renames Pool_Access.all; end Program.Storage_Pools;
pragma Warnings (Off); pragma Style_Checks (Off); with GL; with GLOBE_3D.Math; with Ada.Numerics; use Ada.Numerics; package body Planet is procedure Create ( object : in out GLOBE_3D.p_Object_3D; scale : GLOBE_3D.Real; centre : GLOBE_3D.Point_3D; mercator : GLOBE_3D.Image_id; parts : Positive := 30 ) is use GLOBE_3D, GL, GLOBE_3D.REF, GLOBE_3D.Math; n : constant Positive := parts; step_i : constant Real := 1.0 / Real (n); step_j : constant Real := 1.0 / Real (n - 1); step_psi : constant Real := pi * step_j; step_theta : constant Real := 2.0 * pi * step_i; psi, theta, sin_psi : Real; k : Positive; face_0 : Face_type; -- takes defaults values procedure Map_texture (i, j : Natural) is ri, rj, ri1, rj1 : Real; begin ri := Real (i); ri1 := Real (i + 1); rj := Real (j); rj1 := Real (j + 1); face_0.texture_edge_map := ( (ri *step_i, rj *step_j), (ri1*step_i, rj *step_j), (ri1*step_i, rj1*step_j), (ri *step_i, rj1*step_j) ); end Map_texture; begin object := new Object_3D (Max_points => n*n, Max_faces => (n - 1)*n); object.centre := centre; -- Set points: k := 1; for j in 0 .. n - 1 loop for i in 0 .. n - 1 loop theta := Real (i) * step_theta; psi := Real (j) * step_psi; sin_psi := sin (psi); object.point (k) := scale * (sin_psi * cos (theta), sin_psi * sin (theta), - cos (psi)); -- phi [from North pole] = pi - psi; sin phi = sin psi; cos phi = - cos psi k := k + 1; end loop; end loop; -- Set faces: face_0.whole_texture := False; -- indeed all faces share the same texture face_0.skin := texture_only; face_0.texture := mercator; k := 1; for j in 0 .. n - 2 loop for i in 0 .. n - 2 loop if j=0 then face_0.P := (i + 1, 0, i + n + 2, i + n + 1); elsif j=n - 2 then face_0.P := (n*j + i + 1, n*j + i + 2, n*j + i + n + 2, 0); else face_0.P := (n*j + i + 1, n*j + i + 2, n*j + i + n + 2, n*j + i + n + 1); end if; Map_texture (i, j); object.face (k) := face_0; k := k + 1; end loop; if j=0 then face_0.P := (n, 0, n*j + n + 1, n*j + n + n); elsif j=n - 2 then face_0.P := (n*j + n, n*j + 1, n*j + n + 1, 0); else face_0.P := (n*j + n, n*j + 1, n*j + n + 1, n*j + n + n); end if; Map_texture (n - 1, j); object.face (k) := face_0; k := k + 1; end loop; end Create; end Planet;
package body Generic_Fifo is ---------- -- Push -- ---------- procedure Push (The_Fifo : in out Fifo_Type; Item : in Element_Type) is begin The_Fifo.Prepend(Item); end Push; --------- -- Pop -- --------- procedure Pop (The_Fifo : in out Fifo_Type; Item : out Element_Type) is begin if Is_Empty(The_Fifo) then raise Empty_Error; end if; Item := The_Fifo.Last_Element; The_Fifo.Delete_Last; end Pop; end Generic_Fifo;
-- Copyright (c) 2019 Maxim Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with League.Strings.Hash; with League.JSON.Objects; with Slim.Players; with Slim.Menu_Models.Play_Lists; package Slim.Menu_Models.JSON is type JSON_Menu_Model (Player : Slim.Players.Player_Access) is limited new Slim.Menu_Models.Menu_Model with private; procedure Initialize (Self : in out JSON_Menu_Model'Class; File : League.Strings.Universal_String); private type Play_List_Access is access all Slim.Menu_Models.Play_Lists.Play_List_Menu_Model; package Playlist_Maps is new Ada.Containers.Hashed_Maps (Key_Type => League.Strings.Universal_String, Element_Type => Play_List_Access, Hash => League.Strings.Hash, Equivalent_Keys => League.Strings."="); type JSON_Menu_Model (Player : Slim.Players.Player_Access) is limited new Slim.Menu_Models.Menu_Model with record Root : League.JSON.Objects.JSON_Object; Nested : League.Strings.Universal_String; Label : League.Strings.Universal_String; URL : League.Strings.Universal_String; Path : League.Strings.Universal_String; Playlist : League.Strings.Universal_String; Playlists : Playlist_Maps.Map; end record; overriding function Label (Self : JSON_Menu_Model; Path : Slim.Menu_Models.Menu_Path) return League.Strings.Universal_String; overriding function Item_Count (Self : JSON_Menu_Model; Path : Slim.Menu_Models.Menu_Path) return Natural; overriding function Enter_Command (Self : JSON_Menu_Model; Path : Menu_Path) return Slim.Menu_Commands.Menu_Command_Access; overriding function Play_Command (Self : JSON_Menu_Model; Path : Menu_Path) return Slim.Menu_Commands.Menu_Command_Access; end Slim.Menu_Models.JSON;
-- -- Jan & Uwe R. Zimmer, Australia, July 2011 -- with Real_Type; use Real_Type; with GLOBE_3D; with Graphics_Data; use Graphics_Data; with Graphics_Structures; use Graphics_Structures; with Rotations; use Rotations; with Vectors_3D; use Vectors_3D; package Graphics_OpenGL is pragma Elaborate_Body; procedure Position_Camera (C : Camera := Cam); procedure Draw (Draw_Object : GLOBE_3D.p_Object_3D; In_Object_Position : Vector_3D; In_Object_Rotation : Quaternion_Rotation); procedure Draw_Lines (Points : Points_3D); procedure Draw_Line (Line : Line_3D; Line_Radius : Real); procedure Draw_Laser (Line_Start, Line_End : Vector_3D; Beam_Radius, Aura_Radius : Real; Beam_Colour : RGBA_Colour); package Cursor_Management is function Cursor return Point_2D; procedure Home; procedure Line_Feed; procedure Paragraph_Feed; procedure Indend (Set_x : Natural); private Leading : constant Natural := 12; Paragraph_Spacing : constant Natural := Leading + 10; Home_Pos : constant Point_2D := (2, 10); Cursor_Pos : Point_2D := Home_Pos; end Cursor_Management; procedure Text_2D (S : String; C : Point_2D := Cursor_Management.Cursor); procedure Text_3D (S : String; P : Vector_3D); procedure Show_Drawing; package Full_Screen_Mode is procedure Change_Full_Screen; private Memoried_Viewer_Size : Size_2D; Memoried_Viewer_Position : Point_2D; end Full_Screen_Mode; procedure Set_Colour (Colour : RGB_Colour); procedure Set_Colour (Colour : RGBA_Colour); procedure Set_Material (Material : Materials); end Graphics_OpenGL;
package Debug7 is function Next (I : Integer) return Integer; function Renamed_Next (I : Integer) return Integer renames Next; end Debug7;
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Ada Modeling Framework -- -- -- -- Runtime Library 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$ ------------------------------------------------------------------------------ package AMF.UML is pragma Preelaborate; type UML_Aggregation_Kind is (None, Shared, Composite); type UML_Call_Concurrency_Kind is (Sequential, Guarded, Concurrent); type UML_Connector_Kind is (Assembly, Delegation); type UML_Expansion_Kind is (Parallel, Iterative, Stream); type UML_Interaction_Operator_Kind is (Alt_Operator, Opt_Operator, Break_Operator, Par_Operator, Loop_Operator, Critical_Operator, Neg_Operator, Assert_Operator, Strict_Operator, Seq_Operator, Ignore_Operator, Consider_Operator); type UML_Message_Kind is (Complete, Lost, Found, Unknown); type UML_Message_Sort is (Synch_Call, Asynch_Call, Asynch_Signal, Create_Message, Delete_Message, Reply); type UML_Object_Node_Ordering_Kind is (Unordered, Ordered, LIFO, FIFO); type UML_Parameter_Direction_Kind is (In_Parameter, In_Out_Parameter, Out_Parameter, Return_Parameter); type UML_Parameter_Effect_Kind is (Create, Read, Update, Delete); type UML_Pseudostate_Kind is (Initial_Pseudostate, Deep_History_Pseudostate, Shallow_History_Pseudostate, Join_Pseudostate, Fork_Pseudostate, Junction_Pseudostate, Choice_Pseudostate, Entry_Point_Pseudostate, Exit_Point_Pseudostate, Terminate_Pseudostate); type UML_Transition_Kind is (External, Internal, Local); type UML_Visibility_Kind is (Public_Visibility, Private_Visibility, Protected_Visibility, Package_Visibility); type Optional_UML_Aggregation_Kind (Is_Empty : Boolean := True) is record case Is_Empty is when True => null; when False => Value : UML_Aggregation_Kind; end case; end record; type Optional_UML_Call_Concurrency_Kind (Is_Empty : Boolean := True) is record case Is_Empty is when True => null; when False => Value : UML_Call_Concurrency_Kind; end case; end record; type Optional_UML_Connector_Kind (Is_Empty : Boolean := True) is record case Is_Empty is when True => null; when False => Value : UML_Connector_Kind; end case; end record; type Optional_UML_Expansion_Kind (Is_Empty : Boolean := True) is record case Is_Empty is when True => null; when False => Value : UML_Expansion_Kind; end case; end record; type Optional_UML_Interaction_Operator_Kind (Is_Empty : Boolean := True) is record case Is_Empty is when True => null; when False => Value : UML_Interaction_Operator_Kind; end case; end record; type Optional_UML_Message_Kind (Is_Empty : Boolean := True) is record case Is_Empty is when True => null; when False => Value : UML_Message_Kind; end case; end record; type Optional_UML_Message_Sort (Is_Empty : Boolean := True) is record case Is_Empty is when True => null; when False => Value : UML_Message_Sort; end case; end record; type Optional_UML_Object_Node_Ordering_Kind (Is_Empty : Boolean := True) is record case Is_Empty is when True => null; when False => Value : UML_Object_Node_Ordering_Kind; end case; end record; type Optional_UML_Parameter_Direction_Kind (Is_Empty : Boolean := True) is record case Is_Empty is when True => null; when False => Value : UML_Parameter_Direction_Kind; end case; end record; type Optional_UML_Parameter_Effect_Kind (Is_Empty : Boolean := True) is record case Is_Empty is when True => null; when False => Value : UML_Parameter_Effect_Kind; end case; end record; type Optional_UML_Pseudostate_Kind (Is_Empty : Boolean := True) is record case Is_Empty is when True => null; when False => Value : UML_Pseudostate_Kind; end case; end record; type Optional_UML_Transition_Kind (Is_Empty : Boolean := True) is record case Is_Empty is when True => null; when False => Value : UML_Transition_Kind; end case; end record; type Optional_UML_Visibility_Kind (Is_Empty : Boolean := True) is record case Is_Empty is when True => null; when False => Value : UML_Visibility_Kind; end case; end record; end AMF.UML;
pragma License (Unrestricted); -- implementation unit specialized for POSIX (Darwin, FreeBSD, or Linux) with Ada.Exception_Identification; with Ada.IO_Exceptions; with Ada.Streams; with System.Native_Calendar; with C.sys.stat; with C.sys.types; package System.Native_Directories is pragma Preelaborate; -- directory and file operations function Current_Directory return String; procedure Set_Directory (Directory : String); procedure Create_Directory (New_Directory : String); procedure Delete_Directory (Directory : String); procedure Delete_File (Name : String); procedure Rename ( Old_Name : String; New_Name : String; Overwrite : Boolean); procedure Copy_File ( Source_Name : String; Target_Name : String; Overwrite : Boolean); pragma Inline (Copy_File); -- renamed procedure Replace_File ( Source_Name : String; Target_Name : String); pragma Inline (Replace_File); -- renamed procedure Symbolic_Link ( Source_Name : String; Target_Name : String; Overwrite : Boolean); -- file and directory name operations function Full_Name (Name : String) return String; function Exists (Name : String) return Boolean; -- file and directory queries -- same as Ada.Directories.File_Kind type File_Kind is (Directory, Ordinary_File, Special_File); pragma Discard_Names (File_Kind); subtype Directory_Entry_Information_Type is C.sys.stat.struct_stat; procedure Get_Information ( Name : String; Information : aliased out Directory_Entry_Information_Type); function Kind (mode : C.sys.types.mode_t) return File_Kind; function Kind (Information : Directory_Entry_Information_Type) return File_Kind; function Size (Information : Directory_Entry_Information_Type) return Ada.Streams.Stream_Element_Count; function Modification_Time (Information : Directory_Entry_Information_Type) return Native_Calendar.Native_Time; pragma Inline (Modification_Time); procedure Set_Modification_Time ( Name : String; Time : Native_Calendar.Native_Time); -- exceptions function IO_Exception_Id (errno : C.signed_int) return Ada.Exception_Identification.Exception_Id; function Named_IO_Exception_Id (errno : C.signed_int) return Ada.Exception_Identification.Exception_Id; Name_Error : exception renames Ada.IO_Exceptions.Name_Error; Use_Error : exception renames Ada.IO_Exceptions.Use_Error; Device_Error : exception renames Ada.IO_Exceptions.Device_Error; end System.Native_Directories;
pragma Ada_2012; pragma Style_Checks (Off); with Interfaces.C; use Interfaces.C; package freetype_config_integer_types is -- unsupported macro: FT_SIZEOF_INT ( 32 / FT_CHAR_BIT ) -- unsupported macro: FT_SIZEOF_LONG ( 64 / FT_CHAR_BIT ) -- unsupported macro: FT_INT64 long -- unsupported macro: FT_UINT64 unsigned long --*************************************************************************** -- * -- * config/integer-types.h -- * -- * FreeType integer types definitions. -- * -- * Copyright (C) 1996-2020 by -- * David Turner, Robert Wilhelm, and Werner Lemberg. -- * -- * This file is part of the FreeType project, and may only be used, -- * modified, and distributed under the terms of the FreeType project -- * license, LICENSE.TXT. By continuing to use, modify, or distribute -- * this file you indicate that you have read the license and -- * understand and accept it fully. -- * -- -- There are systems (like the Texas Instruments 'C54x) where a `char` -- has 16~bits. ANSI~C says that `sizeof(char)` is always~1. Since an -- `int` has 16~bits also for this system, `sizeof(int)` gives~1 which -- is probably unexpected. -- -- `CHAR_BIT` (defined in `limits.h`) gives the number of bits in a -- `char` type. -- The size of an `int` type. -- The size of a `long` type. A five-byte `long` (as used e.g. on the -- DM642) is recognized but avoided. --************************************************************************* -- * -- * @section: -- * basic_types -- * -- --************************************************************************* -- * -- * @type: -- * FT_Int16 -- * -- * @description: -- * A typedef for a 16bit signed integer type. -- subtype FT_Int16 is short; -- /usr/include/freetype2/freetype/config/integer-types.h:79 --************************************************************************* -- * -- * @type: -- * FT_UInt16 -- * -- * @description: -- * A typedef for a 16bit unsigned integer type. -- subtype FT_UInt16 is unsigned_short; -- /usr/include/freetype2/freetype/config/integer-types.h:90 -- -- this #if 0 ... #endif clause is for documentation purposes --************************************************************************* -- * -- * @type: -- * FT_Int32 -- * -- * @description: -- * A typedef for a 32bit signed integer type. The size depends on the -- * configuration. -- --************************************************************************* -- * -- * @type: -- * FT_UInt32 -- * -- * A typedef for a 32bit unsigned integer type. The size depends on the -- * configuration. -- --************************************************************************* -- * -- * @type: -- * FT_Int64 -- * -- * A typedef for a 64bit signed integer type. The size depends on the -- * configuration. Only defined if there is real 64bit support; -- * otherwise, it gets emulated with a structure (if necessary). -- --************************************************************************* -- * -- * @type: -- * FT_UInt64 -- * -- * A typedef for a 64bit unsigned integer type. The size depends on the -- * configuration. Only defined if there is real 64bit support; -- * otherwise, it gets emulated with a structure (if necessary). -- -- subtype FT_Int32 is int; -- /usr/include/freetype2/freetype/config/integer-types.h:150 subtype FT_UInt32 is unsigned; -- /usr/include/freetype2/freetype/config/integer-types.h:151 -- look up an integer type that is at least 32~bits subtype FT_Fast is int; -- /usr/include/freetype2/freetype/config/integer-types.h:166 subtype FT_UFast is unsigned; -- /usr/include/freetype2/freetype/config/integer-types.h:167 -- determine whether we have a 64-bit `int` type for platforms without -- Autoconf -- `FT_LONG64` must be defined if a 64-bit type is available --************************************************************************* -- * -- * A 64-bit data type may create compilation problems if you compile in -- * strict ANSI mode. To avoid them, we disable other 64-bit data types if -- * `__STDC__` is defined. You can however ignore this rule by defining the -- * `FT_CONFIG_OPTION_FORCE_INT64` configuration macro. -- -- this compiler provides the `__int64` type -- XXXX: We should probably check the value of `__BORLANDC__` in order -- to test the compiler version. -- this compiler provides the `__int64` type -- Watcom doesn't provide 64-bit data types -- GCC provides the `long long` type subtype FT_Int64 is long; -- /usr/include/freetype2/freetype/config/integer-types.h:240 subtype FT_UInt64 is unsigned_long; -- /usr/include/freetype2/freetype/config/integer-types.h:241 end freetype_config_integer_types;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- E X P _ C H 1 1 -- -- -- -- B o d y -- -- -- -- $Revision$ -- -- -- Copyright (C) 1992-2001 Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, -- -- MA 02111-1307, USA. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Atree; use Atree; with Casing; use Casing; with Debug; use Debug; with Einfo; use Einfo; with Exp_Ch7; use Exp_Ch7; with Exp_Util; use Exp_Util; with Hostparm; use Hostparm; with Inline; use Inline; with Lib; use Lib; with Namet; use Namet; with Nlists; use Nlists; with Nmake; use Nmake; with Opt; use Opt; with Rtsfind; use Rtsfind; with Restrict; use Restrict; with Sem; use Sem; with Sem_Ch5; use Sem_Ch5; with Sem_Ch8; use Sem_Ch8; with Sem_Res; use Sem_Res; with Sem_Util; use Sem_Util; with Sinfo; use Sinfo; with Sinput; use Sinput; with Snames; use Snames; with Stand; use Stand; with Stringt; use Stringt; with Targparm; use Targparm; with Tbuild; use Tbuild; with Uintp; use Uintp; with Uname; use Uname; package body Exp_Ch11 is SD_List : List_Id; -- This list gathers the values SDn'Unrestricted_Access used to -- construct the unit exception table. It is set to Empty_List if -- there are no subprogram descriptors. ----------------------- -- Local Subprograms -- ----------------------- procedure Expand_Exception_Handler_Tables (HSS : Node_Id); -- Subsidiary procedure called by Expand_Exception_Handlers if zero -- cost exception handling is installed for this target. Replaces the -- exception handler structure with appropriate labeled code and tables -- that allow the zero cost exception handling circuits to find the -- correct handler (see unit Ada.Exceptions for details). procedure Generate_Subprogram_Descriptor (N : Node_Id; Loc : Source_Ptr; Spec : Entity_Id; Slist : List_Id); -- Procedure called to generate a subprogram descriptor. N is the -- subprogram body node or, in the case of an imported subprogram, is -- Empty, and Spec is the entity of the sunprogram. For details of the -- required structure, see package System.Exceptions. The generated -- subprogram descriptor is appended to Slist. Loc provides the -- source location to be used for the generated descriptor. --------------------------- -- Expand_At_End_Handler -- --------------------------- -- For a handled statement sequence that has a cleanup (At_End_Proc -- field set), an exception handler of the following form is required: -- exception -- when all others => -- cleanup call -- raise; -- Note: this exception handler is treated rather specially by -- subsequent expansion in two respects: -- The normal call to Undefer_Abort is omitted -- The raise call does not do Defer_Abort -- This is because the current tasking code seems to assume that -- the call to the cleanup routine that is made from an exception -- handler for the abort signal is called with aborts deferred. procedure Expand_At_End_Handler (HSS : Node_Id; Block : Node_Id) is Clean : constant Entity_Id := Entity (At_End_Proc (HSS)); Loc : constant Source_Ptr := Sloc (Clean); Ohandle : Node_Id; Stmnts : List_Id; begin pragma Assert (Present (Clean)); pragma Assert (No (Exception_Handlers (HSS))); if Restrictions (No_Exception_Handlers) then return; end if; if Present (Block) then New_Scope (Block); end if; Ohandle := Make_Others_Choice (Loc); Set_All_Others (Ohandle); Stmnts := New_List ( Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (Clean, Loc)), Make_Raise_Statement (Loc)); Set_Exception_Handlers (HSS, New_List ( Make_Exception_Handler (Loc, Exception_Choices => New_List (Ohandle), Statements => Stmnts))); Analyze_List (Stmnts, Suppress => All_Checks); Expand_Exception_Handlers (HSS); if Present (Block) then Pop_Scope; end if; end Expand_At_End_Handler; ------------------------------------- -- Expand_Exception_Handler_Tables -- ------------------------------------- -- See Ada.Exceptions specification for full details of the data -- structures that we need to construct here. As an example of the -- transformation that is required, given the structure: -- declare -- {declarations} -- .. -- begin -- {statements-1} -- ... -- exception -- when a | b => -- {statements-2} -- ... -- when others => -- {statements-3} -- ... -- end; -- We transform this into: -- declare -- {declarations} -- ... -- L1 : label; -- L2 : label; -- L3 : label; -- L4 : Label; -- L5 : label; -- begin -- <<L1>> -- {statements-1} -- <<L2>> -- exception -- when a | b => -- <<L3>> -- {statements-2} -- HR2 : constant Handler_Record := ( -- Lo => L1'Address, -- Hi => L2'Address, -- Id => a'Identity, -- Handler => L5'Address); -- HR3 : constant Handler_Record := ( -- Lo => L1'Address, -- Hi => L2'Address, -- Id => b'Identity, -- Handler => L4'Address); -- when others => -- <<L4>> -- {statements-3} -- HR1 : constant Handler_Record := ( -- Lo => L1'Address, -- Hi => L2'Address, -- Id => Others_Id, -- Handler => L4'Address); -- end; -- The exception handlers in the transformed version are marked with the -- Zero_Cost_Handling flag set, and all gigi does in this case is simply -- to put the handler code somewhere. It can optionally be put inline -- between the goto L3 and the label <<L3>> (which is why we generate -- that goto in the first place). procedure Expand_Exception_Handler_Tables (HSS : Node_Id) is Loc : constant Source_Ptr := Sloc (HSS); Handlrs : constant List_Id := Exception_Handlers (HSS); Stms : constant List_Id := Statements (HSS); Handler : Node_Id; Hlist : List_Id; -- This is the list to which handlers are to be appended. It is -- either the list for the enclosing subprogram, or the enclosing -- selective accept statement (which will turn into a subprogram -- during expansion later on). L1 : constant Entity_Id := Make_Defining_Identifier (Loc, Chars => New_Internal_Name ('L')); L2 : constant Entity_Id := Make_Defining_Identifier (Loc, Chars => New_Internal_Name ('L')); Lnn : Entity_Id; Choice : Node_Id; E_Id : Node_Id; HR_Ent : Node_Id; HL_Ref : Node_Id; Item : Node_Id; Subp_Entity : Entity_Id; -- This is the entity for the subprogram (or library level package) -- to which the handler record is to be attached for later reference -- in a subprogram descriptor for this entity. procedure Append_To_Stms (N : Node_Id); -- Append given statement to the end of the statements of the -- handled sequence of statements and analyze it in place. function Inside_Selective_Accept return Boolean; -- This function is called if we are inside the scope of an entry -- or task. It checks if the handler is appearing in the context -- of a selective accept statement. If so, Hlist is set to -- temporarily park the handlers in the N_Accept_Alternative. -- node. They will subsequently be moved to the procedure entity -- for the procedure built for this alternative. The statements that -- follow the Accept within the alternative are not inside the Accept -- for purposes of this test, and handlers that may appear within -- them belong in the enclosing task procedure. procedure Set_Hlist; -- Sets the handler list corresponding to Subp_Entity -------------------- -- Append_To_Stms -- -------------------- procedure Append_To_Stms (N : Node_Id) is begin Insert_After_And_Analyze (Last (Stms), N); Set_Exception_Junk (N); end Append_To_Stms; ----------------------------- -- Inside_Selective_Accept -- ----------------------------- function Inside_Selective_Accept return Boolean is Parnt : Node_Id; Curr : Node_Id := HSS; begin Parnt := Parent (HSS); while Nkind (Parnt) /= N_Compilation_Unit loop if Nkind (Parnt) = N_Accept_Alternative and then Curr = Accept_Statement (Parnt) then if Present (Accept_Handler_Records (Parnt)) then Hlist := Accept_Handler_Records (Parnt); else Hlist := New_List; Set_Accept_Handler_Records (Parnt, Hlist); end if; return True; else Curr := Parnt; Parnt := Parent (Parnt); end if; end loop; return False; end Inside_Selective_Accept; --------------- -- Set_Hlist -- --------------- procedure Set_Hlist is begin -- Never try to inline a subprogram with exception handlers Set_Is_Inlined (Subp_Entity, False); if Present (Subp_Entity) and then Present (Handler_Records (Subp_Entity)) then Hlist := Handler_Records (Subp_Entity); else Hlist := New_List; Set_Handler_Records (Subp_Entity, Hlist); end if; end Set_Hlist; -- Start of processing for Expand_Exception_Handler_Tables begin -- Nothing to do if this handler has already been processed if Zero_Cost_Handling (HSS) then return; end if; Set_Zero_Cost_Handling (HSS); -- Find the parent subprogram or package scope containing this -- exception frame. This should always find a real package or -- subprogram. If it does not it will stop at Standard, but -- this cannot legitimately occur. -- We only stop at library level packages, for inner packages -- we always attach handlers to the containing procedure. Subp_Entity := Current_Scope; Scope_Loop : loop -- Never need tables expanded inside a generic template if Is_Generic_Unit (Subp_Entity) then return; -- Stop if we reached containing subprogram. Go to protected -- subprogram if there is one defined. elsif Ekind (Subp_Entity) = E_Function or else Ekind (Subp_Entity) = E_Procedure then if Present (Protected_Body_Subprogram (Subp_Entity)) then Subp_Entity := Protected_Body_Subprogram (Subp_Entity); end if; Set_Hlist; exit Scope_Loop; -- Case of within an entry elsif Is_Entry (Subp_Entity) then -- Protected entry, use corresponding body subprogram if Present (Protected_Body_Subprogram (Subp_Entity)) then Subp_Entity := Protected_Body_Subprogram (Subp_Entity); Set_Hlist; exit Scope_Loop; -- Check if we are within a selective accept alternative elsif Inside_Selective_Accept then -- As a side effect, Inside_Selective_Accept set Hlist, -- in much the same manner as Set_Hlist, except that -- the list involved was the one for the selective accept. exit Scope_Loop; end if; -- Case of within library level package elsif Ekind (Subp_Entity) = E_Package and then Is_Compilation_Unit (Subp_Entity) then if Is_Body_Name (Unit_Name (Get_Code_Unit (HSS))) then Subp_Entity := Body_Entity (Subp_Entity); end if; Set_Hlist; exit Scope_Loop; -- Task type case elsif Ekind (Subp_Entity) = E_Task_Type then -- Check if we are within a selective accept alternative if Inside_Selective_Accept then -- As a side effect, Inside_Selective_Accept set Hlist, -- in much the same manner as Set_Hlist, except that the -- list involved was the one for the selective accept. exit Scope_Loop; -- Stop if we reached task type with task body procedure, -- use the task body procedure. elsif Present (Get_Task_Body_Procedure (Subp_Entity)) then Subp_Entity := Get_Task_Body_Procedure (Subp_Entity); Set_Hlist; exit Scope_Loop; end if; end if; -- If we fall through, keep looking Subp_Entity := Scope (Subp_Entity); end loop Scope_Loop; pragma Assert (Subp_Entity /= Standard_Standard); -- Analyze standard labels Analyze_Label_Entity (L1); Analyze_Label_Entity (L2); Insert_Before_And_Analyze (First (Stms), Make_Label (Loc, Identifier => New_Occurrence_Of (L1, Loc))); Set_Exception_Junk (First (Stms)); Append_To_Stms ( Make_Label (Loc, Identifier => New_Occurrence_Of (L2, Loc))); -- Loop through exception handlers Handler := First_Non_Pragma (Handlrs); while Present (Handler) loop Set_Zero_Cost_Handling (Handler); -- Add label at start of handler, and goto at the end Lnn := Make_Defining_Identifier (Loc, Chars => New_Internal_Name ('L')); Analyze_Label_Entity (Lnn); Item := Make_Label (Loc, Identifier => New_Occurrence_Of (Lnn, Loc)); Set_Exception_Junk (Item); Insert_Before_And_Analyze (First (Statements (Handler)), Item); -- Loop through choices Choice := First (Exception_Choices (Handler)); while Present (Choice) loop -- Others (or all others) choice if Nkind (Choice) = N_Others_Choice then if All_Others (Choice) then E_Id := New_Occurrence_Of (RTE (RE_All_Others_Id), Loc); else E_Id := New_Occurrence_Of (RTE (RE_Others_Id), Loc); end if; -- Special case of VMS_Exception. Not clear what we will do -- eventually here if and when we implement zero cost exceptions -- on VMS. But at least for now, don't blow up trying to take -- a garbage code address for such an exception. elsif Is_VMS_Exception (Entity (Choice)) then E_Id := New_Occurrence_Of (RTE (RE_Null_Id), Loc); -- Normal case of specific exception choice else E_Id := Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Entity (Choice), Loc), Attribute_Name => Name_Identity); end if; HR_Ent := Make_Defining_Identifier (Loc, Chars => New_Internal_Name ('H')); HL_Ref := Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (HR_Ent, Loc), Attribute_Name => Name_Unrestricted_Access); -- Now we need to add the entry for the new handler record to -- the list of handler records for the current subprogram. -- Normally we end up generating the handler records in exactly -- the right order. Here right order means innermost first, -- since the table will be searched sequentially. Since we -- generally expand from outside to inside, the order is just -- what we want, and we need to append the new entry to the -- end of the list. -- However, there are exceptions, notably in the case where -- a generic body is inserted later on. See for example the -- case of ACVC test C37213J, which has the following form: -- generic package x ... end x; -- package body x is -- begin -- ... -- exception (1) -- ... -- end x; -- ... -- declare -- package q is new x; -- begin -- ... -- exception (2) -- ... -- end; -- In this case, we will expand exception handler (2) first, -- since the expansion of (1) is delayed till later when the -- generic body is inserted. But (1) belongs before (2) in -- the chain. -- Note that scopes are not totally ordered, because two -- scopes can be in parallel blocks, so that it does not -- matter what order these entries appear in. An ordering -- relation exists if one scope is inside another, and what -- we really want is some partial ordering. -- A simple, not very efficient, but adequate algorithm to -- achieve this partial ordering is to search the list for -- the first entry containing the given scope, and put the -- new entry just before it. declare New_Scop : constant Entity_Id := Current_Scope; Ent : Node_Id; begin Ent := First (Hlist); loop -- If all searched, then we can just put the new -- entry at the end of the list (it actually does -- not matter where we put it in this case). if No (Ent) then Append_To (Hlist, HL_Ref); exit; -- If the current scope is within the scope of the -- entry then insert the entry before to retain the -- proper order as per above discussion. -- Note that for equal entries, we just keep going, -- which is fine, the entry will end up at the end -- of the list where it belongs. elsif Scope_Within (New_Scop, Scope (Entity (Prefix (Ent)))) then Insert_Before (Ent, HL_Ref); exit; -- Otherwise keep looking else Next (Ent); end if; end loop; end; Item := Make_Object_Declaration (Loc, Defining_Identifier => HR_Ent, Constant_Present => True, Aliased_Present => True, Object_Definition => New_Occurrence_Of (RTE (RE_Handler_Record), Loc), Expression => Make_Aggregate (Loc, Expressions => New_List ( Make_Attribute_Reference (Loc, -- Lo Prefix => New_Occurrence_Of (L1, Loc), Attribute_Name => Name_Address), Make_Attribute_Reference (Loc, -- Hi Prefix => New_Occurrence_Of (L2, Loc), Attribute_Name => Name_Address), E_Id, -- Id Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Lnn, Loc), -- Handler Attribute_Name => Name_Address)))); Set_Handler_List_Entry (Item, HL_Ref); Set_Exception_Junk (Item); Insert_After_And_Analyze (Last (Statements (Handler)), Item); Set_Is_Statically_Allocated (HR_Ent); -- If this is a late insertion (from body instance) it is being -- inserted in the component list of an already analyzed aggre- -- gate, and must be analyzed explicitly. Analyze_And_Resolve (HL_Ref, RTE (RE_Handler_Record_Ptr)); Next (Choice); end loop; Next_Non_Pragma (Handler); end loop; end Expand_Exception_Handler_Tables; ------------------------------- -- Expand_Exception_Handlers -- ------------------------------- procedure Expand_Exception_Handlers (HSS : Node_Id) is Handlrs : constant List_Id := Exception_Handlers (HSS); Loc : Source_Ptr; Handler : Node_Id; Others_Choice : Boolean; Obj_Decl : Node_Id; procedure Prepend_Call_To_Handler (Proc : RE_Id; Args : List_Id := No_List); -- Routine to prepend a call to the procedure referenced by Proc at -- the start of the handler code for the current Handler. procedure Prepend_Call_To_Handler (Proc : RE_Id; Args : List_Id := No_List) is Call : constant Node_Id := Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (Proc), Loc), Parameter_Associations => Args); begin Prepend_To (Statements (Handler), Call); Analyze (Call, Suppress => All_Checks); end Prepend_Call_To_Handler; -- Start of processing for Expand_Exception_Handlers begin -- Loop through handlers Handler := First_Non_Pragma (Handlrs); while Present (Handler) loop Loc := Sloc (Handler); -- If an exception occurrence is present, then we must declare it -- and initialize it from the value stored in the TSD -- declare -- name : Exception_Occurrence; -- -- begin -- Save_Occurrence (name, Get_Current_Excep.all) -- ... -- end; if Present (Choice_Parameter (Handler)) then declare Cparm : constant Entity_Id := Choice_Parameter (Handler); Clc : constant Source_Ptr := Sloc (Cparm); Save : Node_Id; begin Save := Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Save_Occurrence), Loc), Parameter_Associations => New_List ( New_Occurrence_Of (Cparm, Clc), Make_Explicit_Dereference (Loc, Make_Function_Call (Loc, Name => Make_Explicit_Dereference (Loc, New_Occurrence_Of (RTE (RE_Get_Current_Excep), Loc)))))); Mark_Rewrite_Insertion (Save); Prepend (Save, Statements (Handler)); Obj_Decl := Make_Object_Declaration (Clc, Defining_Identifier => Cparm, Object_Definition => New_Occurrence_Of (RTE (RE_Exception_Occurrence), Clc)); Set_No_Initialization (Obj_Decl, True); Rewrite (Handler, Make_Exception_Handler (Loc, Exception_Choices => Exception_Choices (Handler), Statements => New_List ( Make_Block_Statement (Loc, Declarations => New_List (Obj_Decl), Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => Statements (Handler)))))); Analyze_List (Statements (Handler), Suppress => All_Checks); end; end if; -- The processing at this point is rather different for the -- JVM case, so we completely separate the processing. -- For the JVM case, we unconditionally call Update_Exception, -- passing a call to the intrinsic function Current_Target_Exception -- (see JVM version of Ada.Exceptions in 4jexcept.adb for details). if Hostparm.Java_VM then declare Arg : Node_Id := Make_Function_Call (Loc, Name => New_Occurrence_Of (RTE (RE_Current_Target_Exception), Loc)); begin Prepend_Call_To_Handler (RE_Update_Exception, New_List (Arg)); end; -- For the normal case, we have to worry about the state of abort -- deferral. Generally, we defer abort during runtime handling of -- exceptions. When control is passed to the handler, then in the -- normal case we undefer aborts. In any case this entire handling -- is relevant only if aborts are allowed! elsif Abort_Allowed then -- There are some special cases in which we do not do the -- undefer. In particular a finalization (AT END) handler -- wants to operate with aborts still deferred. -- We also suppress the call if this is the special handler -- for Abort_Signal, since if we are aborting, we want to keep -- aborts deferred (one abort is enough thank you very much :-) -- If abort really needs to be deferred the expander must add -- this call explicitly, see Exp_Ch9.Expand_N_Asynchronous_Select. Others_Choice := Nkind (First (Exception_Choices (Handler))) = N_Others_Choice; if (Others_Choice or else Entity (First (Exception_Choices (Handler))) /= Stand.Abort_Signal) and then not (Others_Choice and then All_Others (First (Exception_Choices (Handler)))) and then Abort_Allowed then Prepend_Call_To_Handler (RE_Abort_Undefer); end if; end if; Next_Non_Pragma (Handler); end loop; -- The last step for expanding exception handlers is to expand the -- exception tables if zero cost exception handling is active. if Exception_Mechanism = Front_End_ZCX then Expand_Exception_Handler_Tables (HSS); end if; end Expand_Exception_Handlers; ------------------------------------ -- Expand_N_Exception_Declaration -- ------------------------------------ -- Generates: -- exceptE : constant String := "A.B.EXCEP"; -- static data -- except : exception_data := ( -- Handled_By_Other => False, -- Lang => 'A', -- Name_Length => exceptE'Length -- Full_Name => exceptE'Address -- HTable_Ptr => null); -- (protecting test only needed if not at library level) -- -- exceptF : Boolean := True -- static data -- if exceptF then -- exceptF := False; -- Register_Exception (except'Unchecked_Access); -- end if; procedure Expand_N_Exception_Declaration (N : Node_Id) is Loc : constant Source_Ptr := Sloc (N); Id : constant Entity_Id := Defining_Identifier (N); L : List_Id := New_List; Flag_Id : Entity_Id; Name_Exname : constant Name_Id := New_External_Name (Chars (Id), 'E'); Exname : constant Node_Id := Make_Defining_Identifier (Loc, Name_Exname); begin -- There is no expansion needed when compiling for the JVM since the -- JVM has a built-in exception mechanism. See 4jexcept.ads for details. if Hostparm.Java_VM then return; end if; -- Definition of the external name: nam : constant String := "A.B.NAME"; Insert_Action (N, Make_Object_Declaration (Loc, Defining_Identifier => Exname, Constant_Present => True, Object_Definition => New_Occurrence_Of (Standard_String, Loc), Expression => Make_String_Literal (Loc, Full_Qualified_Name (Id)))); Set_Is_Statically_Allocated (Exname); -- Create the aggregate list for type Standard.Exception_Type: -- Handled_By_Other component: False Append_To (L, New_Occurrence_Of (Standard_False, Loc)); -- Lang component: 'A' Append_To (L, Make_Character_Literal (Loc, Name_uA, Get_Char_Code ('A'))); -- Name_Length component: Nam'Length Append_To (L, Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Exname, Loc), Attribute_Name => Name_Length)); -- Full_Name component: Standard.A_Char!(Nam'Address) Append_To (L, Unchecked_Convert_To (Standard_A_Char, Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Exname, Loc), Attribute_Name => Name_Address))); -- HTable_Ptr component: null Append_To (L, Make_Null (Loc)); -- Import_Code component: 0 Append_To (L, Make_Integer_Literal (Loc, 0)); Set_Expression (N, Make_Aggregate (Loc, Expressions => L)); Analyze_And_Resolve (Expression (N), Etype (Id)); -- Register_Exception (except'Unchecked_Access); if not Restrictions (No_Exception_Handlers) then L := New_List ( Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Register_Exception), Loc), Parameter_Associations => New_List ( Unchecked_Convert_To (RTE (RE_Exception_Data_Ptr), Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Id, Loc), Attribute_Name => Name_Unrestricted_Access))))); Set_Register_Exception_Call (Id, First (L)); if not Is_Library_Level_Entity (Id) then Flag_Id := Make_Defining_Identifier (Loc, New_External_Name (Chars (Id), 'F')); Insert_Action (N, Make_Object_Declaration (Loc, Defining_Identifier => Flag_Id, Object_Definition => New_Occurrence_Of (Standard_Boolean, Loc), Expression => New_Occurrence_Of (Standard_True, Loc))); Set_Is_Statically_Allocated (Flag_Id); Append_To (L, Make_Assignment_Statement (Loc, Name => New_Occurrence_Of (Flag_Id, Loc), Expression => New_Occurrence_Of (Standard_False, Loc))); Insert_After_And_Analyze (N, Make_Implicit_If_Statement (N, Condition => New_Occurrence_Of (Flag_Id, Loc), Then_Statements => L)); else Insert_List_After_And_Analyze (N, L); end if; end if; end Expand_N_Exception_Declaration; --------------------------------------------- -- Expand_N_Handled_Sequence_Of_Statements -- --------------------------------------------- procedure Expand_N_Handled_Sequence_Of_Statements (N : Node_Id) is begin if Present (Exception_Handlers (N)) then Expand_Exception_Handlers (N); end if; -- The following code needs comments ??? if Nkind (Parent (N)) /= N_Package_Body and then Nkind (Parent (N)) /= N_Accept_Statement and then not Delay_Cleanups (Current_Scope) then Expand_Cleanup_Actions (Parent (N)); else Set_First_Real_Statement (N, First (Statements (N))); end if; end Expand_N_Handled_Sequence_Of_Statements; ------------------------------------- -- Expand_N_Raise_Constraint_Error -- ------------------------------------- -- The only processing required is to adjust the condition to deal -- with the C/Fortran boolean case. This may well not be necessary, -- as all such conditions are generated by the expander and probably -- are all standard boolean, but who knows what strange optimization -- in future may require this adjustment! procedure Expand_N_Raise_Constraint_Error (N : Node_Id) is begin Adjust_Condition (Condition (N)); end Expand_N_Raise_Constraint_Error; ---------------------------------- -- Expand_N_Raise_Program_Error -- ---------------------------------- -- The only processing required is to adjust the condition to deal -- with the C/Fortran boolean case. This may well not be necessary, -- as all such conditions are generated by the expander and probably -- are all standard boolean, but who knows what strange optimization -- in future may require this adjustment! procedure Expand_N_Raise_Program_Error (N : Node_Id) is begin Adjust_Condition (Condition (N)); end Expand_N_Raise_Program_Error; ------------------------------ -- Expand_N_Raise_Statement -- ------------------------------ procedure Expand_N_Raise_Statement (N : Node_Id) is Loc : constant Source_Ptr := Sloc (N); Ehand : Node_Id; E : Entity_Id; Str : String_Id; begin -- There is no expansion needed for statement "raise <exception>;" when -- compiling for the JVM since the JVM has a built-in exception -- mechanism. However we need the keep the expansion for "raise;" -- statements. See 4jexcept.ads for details. if Present (Name (N)) and then Hostparm.Java_VM then return; end if; -- Convert explicit raise of Program_Error, Constraint_Error, and -- Storage_Error into the corresponding raise node (in No_Run_Time -- mode all other raises will get normal expansion and be disallowed, -- but this is also faster in all modes). if Present (Name (N)) and then Nkind (Name (N)) = N_Identifier then if Entity (Name (N)) = Standard_Program_Error then Rewrite (N, Make_Raise_Program_Error (Loc)); Analyze (N); return; elsif Entity (Name (N)) = Standard_Constraint_Error then Rewrite (N, Make_Raise_Constraint_Error (Loc)); Analyze (N); return; elsif Entity (Name (N)) = Standard_Storage_Error then Rewrite (N, Make_Raise_Storage_Error (Loc)); Analyze (N); return; end if; end if; -- Case of name present, in this case we expand raise name to -- Raise_Exception (name'Identity, location_string); -- where location_string identifies the file/line of the raise if Present (Name (N)) then declare Id : Entity_Id := Entity (Name (N)); begin Build_Location_String (Loc); -- Build a C compatible string in case of no exception handlers, -- since this is what the last chance handler is expecting. if Restrictions (No_Exception_Handlers) then -- Generate a C null message when Global_Discard_Names is True -- or when Debug_Flag_NN is set. if Global_Discard_Names or else Debug_Flag_NN then Name_Buffer (1) := ASCII.NUL; Name_Len := 1; else Name_Len := Name_Len + 1; end if; -- Do not generate the message when Global_Discard_Names is True -- or when Debug_Flag_NN is set. elsif Global_Discard_Names or else Debug_Flag_NN then Name_Len := 0; end if; Str := String_From_Name_Buffer; -- For VMS exceptions, convert the raise into a call to -- lib$stop so it will be handled by __gnat_error_handler. if Is_VMS_Exception (Id) then declare Excep_Image : String_Id; Cond : Node_Id; begin if Present (Interface_Name (Id)) then Excep_Image := Strval (Interface_Name (Id)); else Get_Name_String (Chars (Id)); Set_All_Upper_Case; Excep_Image := String_From_Name_Buffer; end if; if Exception_Code (Id) /= No_Uint then Cond := Make_Integer_Literal (Loc, Exception_Code (Id)); else Cond := Unchecked_Convert_To (Standard_Integer, Make_Function_Call (Loc, Name => New_Occurrence_Of (RTE (RE_Import_Value), Loc), Parameter_Associations => New_List (Make_String_Literal (Loc, Strval => Excep_Image)))); end if; Rewrite (N, Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Lib_Stop), Loc), Parameter_Associations => New_List (Cond))); Analyze_And_Resolve (Cond, Standard_Integer); end; -- Not VMS exception case, convert raise to call to the -- Raise_Exception routine. else Rewrite (N, Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Raise_Exception), Loc), Parameter_Associations => New_List ( Make_Attribute_Reference (Loc, Prefix => Name (N), Attribute_Name => Name_Identity), Make_String_Literal (Loc, Strval => Str)))); end if; end; -- Case of no name present (reraise). We rewrite the raise to: -- Reraise_Occurrence_Always (EO); -- where EO is the current exception occurrence. If the current handler -- does not have a choice parameter specification, then we provide one. else -- Find innermost enclosing exception handler (there must be one, -- since the semantics has already verified that this raise statement -- is valid, and a raise with no arguments is only permitted in the -- context of an exception handler. Ehand := Parent (N); while Nkind (Ehand) /= N_Exception_Handler loop Ehand := Parent (Ehand); end loop; -- Make exception choice parameter if none present. Note that we do -- not need to put the entity on the entity chain, since no one will -- be referencing this entity by normal visibility methods. if No (Choice_Parameter (Ehand)) then E := Make_Defining_Identifier (Loc, New_Internal_Name ('E')); Set_Choice_Parameter (Ehand, E); Set_Ekind (E, E_Variable); Set_Etype (E, RTE (RE_Exception_Occurrence)); Set_Scope (E, Current_Scope); end if; -- Now rewrite the raise as a call to Reraise. A special case arises -- if this raise statement occurs in the context of a handler for -- all others (i.e. an at end handler). in this case we avoid -- the call to defer abort, cleanup routines are expected to be -- called in this case with aborts deferred. declare Ech : constant Node_Id := First (Exception_Choices (Ehand)); Ent : Entity_Id; begin if Nkind (Ech) = N_Others_Choice and then All_Others (Ech) then Ent := RTE (RE_Reraise_Occurrence_No_Defer); else Ent := RTE (RE_Reraise_Occurrence_Always); end if; Rewrite (N, Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (Ent, Loc), Parameter_Associations => New_List ( New_Occurrence_Of (Choice_Parameter (Ehand), Loc)))); end; end if; Analyze (N); end Expand_N_Raise_Statement; ---------------------------------- -- Expand_N_Raise_Storage_Error -- ---------------------------------- -- The only processing required is to adjust the condition to deal -- with the C/Fortran boolean case. This may well not be necessary, -- as all such conditions are generated by the expander and probably -- are all standard boolean, but who knows what strange optimization -- in future may require this adjustment! procedure Expand_N_Raise_Storage_Error (N : Node_Id) is begin Adjust_Condition (Condition (N)); end Expand_N_Raise_Storage_Error; ------------------------------ -- Expand_N_Subprogram_Info -- ------------------------------ procedure Expand_N_Subprogram_Info (N : Node_Id) is Loc : constant Source_Ptr := Sloc (N); begin -- For now, we replace an Expand_N_Subprogram_Info node with an -- attribute reference that gives the address of the procedure. -- This is because gigi does not yet recognize this node, and -- for the initial targets, this is the right value anyway. Rewrite (N, Make_Attribute_Reference (Loc, Prefix => Identifier (N), Attribute_Name => Name_Code_Address)); Analyze_And_Resolve (N, RTE (RE_Code_Loc)); end Expand_N_Subprogram_Info; ------------------------------------ -- Generate_Subprogram_Descriptor -- ------------------------------------ procedure Generate_Subprogram_Descriptor (N : Node_Id; Loc : Source_Ptr; Spec : Entity_Id; Slist : List_Id) is Code : Node_Id; Ent : Entity_Id; Decl : Node_Id; Dtyp : Entity_Id; Numh : Nat; Sdes : Node_Id; Hrc : List_Id; begin if Exception_Mechanism /= Front_End_ZCX then return; end if; -- Suppress descriptor if we are not generating code. This happens -- in the case of a -gnatc -gnatt compilation where we force generics -- to be generated, but we still don't want exception tables. if Operating_Mode /= Generate_Code then return; end if; -- Suppress descriptor if we are in No_Exceptions restrictions mode, -- since we can never propagate exceptions in any case in this mode. -- The same consideration applies for No_Exception_Handlers (which -- is also set in No_Run_Time mode). if Restrictions (No_Exceptions) or Restrictions (No_Exception_Handlers) then return; end if; -- Suppress descriptor if we are inside a generic. There are two -- ways that we can tell that, depending on what is going on. If -- we are actually inside the processing for a generic right now, -- then Expander_Active will be reset. If we are outside the -- generic, then we will see the generic entity. if not Expander_Active then return; end if; -- Suppress descriptor is subprogram is marked as eliminated, for -- example if this is a subprogram created to analyze a default -- expression with potential side effects. Ditto if it is nested -- within an eliminated subprogram, for example a cleanup action. declare Scop : Entity_Id; begin Scop := Spec; while Scop /= Standard_Standard loop if Ekind (Scop) = E_Generic_Procedure or else Ekind (Scop) = E_Generic_Function or else Ekind (Scop) = E_Generic_Package or else Is_Eliminated (Scop) then return; end if; Scop := Scope (Scop); end loop; end; -- Suppress descriptor for original protected subprogram (we will -- be called again later to generate the descriptor for the actual -- protected body subprogram.) This does not apply to barrier -- functions which are there own protected subprogram. if Is_Subprogram (Spec) and then Present (Protected_Body_Subprogram (Spec)) and then Protected_Body_Subprogram (Spec) /= Spec then return; end if; -- Suppress descriptors for packages unless they have at least one -- handler. The binder will generate the dummy (no handler) descriptors -- for elaboration procedures. We can't do it here, because we don't -- know if an elaboration routine does in fact exist. -- If there is at least one handler for the package spec or body -- then most certainly an elaboration routine must exist, so we -- can safely reference it. if (Nkind (N) = N_Package_Declaration or else Nkind (N) = N_Package_Body) and then No (Handler_Records (Spec)) then return; end if; -- Suppress all subprogram descriptors for the file System.Exceptions. -- We similarly suppress subprogram descriptors for Ada.Exceptions. -- These are all init_proc's for types which cannot raise exceptions. -- The reason this is done is that otherwise we get embarassing -- elaboration dependencies. Get_Name_String (Unit_File_Name (Current_Sem_Unit)); if Name_Buffer (1 .. 12) = "s-except.ads" or else Name_Buffer (1 .. 12) = "a-except.ads" then return; end if; -- Similarly, we need to suppress entries for System.Standard_Library, -- since otherwise we get elaboration circularities. Again, this would -- better be done with a Suppress_Initialization pragma :-) if Name_Buffer (1 .. 11) = "s-stalib.ad" then return; end if; -- For now, also suppress entries for s-stoele because we have -- some kind of unexplained error there ??? if Name_Buffer (1 .. 11) = "s-stoele.ad" then return; end if; -- And also for g-htable, because it cannot raise exceptions, -- and generates some kind of elaboration order problem. if Name_Buffer (1 .. 11) = "g-htable.ad" then return; end if; -- Suppress subprogram descriptor if already generated. This happens -- in the case of late generation from Delay_Subprogram_Descriptors -- beging set (where there is more than one instantiation in the list) if Has_Subprogram_Descriptor (Spec) then return; else Set_Has_Subprogram_Descriptor (Spec); end if; -- Never generate descriptors for inlined bodies if Analyzing_Inlined_Bodies then return; end if; -- Here we definitely are going to generate a subprogram descriptor declare Hnum : Nat := Homonym_Number (Spec); begin if Hnum = 1 then Hnum := 0; end if; Ent := Make_Defining_Identifier (Loc, Chars => New_External_Name (Chars (Spec), "SD", Hnum)); end; if No (Handler_Records (Spec)) then Hrc := Empty_List; Numh := 0; else Hrc := Handler_Records (Spec); Numh := List_Length (Hrc); end if; New_Scope (Spec); -- We need a static subtype for the declaration of the subprogram -- descriptor. For the case of 0-3 handlers we can use one of the -- predefined subtypes in System.Exceptions. For more handlers, -- we build our own subtype here. case Numh is when 0 => Dtyp := RTE (RE_Subprogram_Descriptor_0); when 1 => Dtyp := RTE (RE_Subprogram_Descriptor_1); when 2 => Dtyp := RTE (RE_Subprogram_Descriptor_2); when 3 => Dtyp := RTE (RE_Subprogram_Descriptor_3); when others => Dtyp := Make_Defining_Identifier (Loc, Chars => New_Internal_Name ('T')); -- Set the constructed type as global, since we will be -- referencing the object that is of this type globally Set_Is_Statically_Allocated (Dtyp); Decl := Make_Subtype_Declaration (Loc, Defining_Identifier => Dtyp, Subtype_Indication => Make_Subtype_Indication (Loc, Subtype_Mark => New_Occurrence_Of (RTE (RE_Subprogram_Descriptor), Loc), Constraint => Make_Index_Or_Discriminant_Constraint (Loc, Constraints => New_List ( Make_Integer_Literal (Loc, Numh))))); Append (Decl, Slist); -- We analyze the descriptor for the subprogram and package -- case, but not for the imported subprogram case (it will -- be analyzed when the freeze entity actions are analyzed. if Present (N) then Analyze (Decl); end if; Set_Exception_Junk (Decl); end case; -- Prepare the code address entry for the table entry. For the normal -- case of being within a procedure, this is simply: -- P'Code_Address -- where P is the procedure, but for the package case, it is -- P'Elab_Body'Code_Address -- P'Elab_Spec'Code_Address -- for the body and spec respectively. Note that we do our own -- analysis of these attribute references, because we know in this -- case that the prefix of ELab_Body/Spec is a visible package, -- which can be referenced directly instead of using the general -- case expansion for these attributes. if Ekind (Spec) = E_Package then Code := Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Spec, Loc), Attribute_Name => Name_Elab_Spec); Set_Etype (Code, Standard_Void_Type); Set_Analyzed (Code); elsif Ekind (Spec) = E_Package_Body then Code := Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Spec_Entity (Spec), Loc), Attribute_Name => Name_Elab_Body); Set_Etype (Code, Standard_Void_Type); Set_Analyzed (Code); else Code := New_Occurrence_Of (Spec, Loc); end if; Code := Make_Attribute_Reference (Loc, Prefix => Code, Attribute_Name => Name_Code_Address); Set_Etype (Code, RTE (RE_Address)); Set_Analyzed (Code); -- Now we can build the subprogram descriptor Sdes := Make_Object_Declaration (Loc, Defining_Identifier => Ent, Constant_Present => True, Aliased_Present => True, Object_Definition => New_Occurrence_Of (Dtyp, Loc), Expression => Make_Aggregate (Loc, Expressions => New_List ( Make_Integer_Literal (Loc, Numh), -- Num_Handlers Code, -- Code -- temp code ??? -- Make_Subprogram_Info (Loc, -- Subprogram_Info -- Identifier => -- New_Occurrence_Of (Spec, Loc)), New_Copy_Tree (Code), Make_Aggregate (Loc, -- Handler_Records Expressions => Hrc)))); Set_Exception_Junk (Sdes); Set_Is_Subprogram_Descriptor (Sdes); Append (Sdes, Slist); -- We analyze the descriptor for the subprogram and package case, -- but not for the imported subprogram case (it will be analyzed -- when the freeze entity actions are analyzed. if Present (N) then Analyze (Sdes); end if; -- We can now pop the scope used for analyzing the descriptor Pop_Scope; -- We need to set the descriptor as statically allocated, since -- it will be referenced from the unit exception table. Set_Is_Statically_Allocated (Ent); -- Append the resulting descriptor to the list. We do this only -- if we are in the main unit. You might think that we could -- simply skip generating the descriptors completely if we are -- not in the main unit, but in fact this is not the case, since -- we have problems with inconsistent serial numbers for internal -- names if we do this. if In_Extended_Main_Code_Unit (Spec) then Append_To (SD_List, Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Ent, Loc), Attribute_Name => Name_Unrestricted_Access)); Unit_Exception_Table_Present := True; end if; end Generate_Subprogram_Descriptor; ------------------------------------------------------------ -- Generate_Subprogram_Descriptor_For_Imported_Subprogram -- ------------------------------------------------------------ procedure Generate_Subprogram_Descriptor_For_Imported_Subprogram (Spec : Entity_Id; Slist : List_Id) is begin Generate_Subprogram_Descriptor (Empty, Sloc (Spec), Spec, Slist); end Generate_Subprogram_Descriptor_For_Imported_Subprogram; ------------------------------------------------ -- Generate_Subprogram_Descriptor_For_Package -- ------------------------------------------------ procedure Generate_Subprogram_Descriptor_For_Package (N : Node_Id; Spec : Entity_Id) is Adecl : Node_Id; begin Adecl := Aux_Decls_Node (Parent (N)); if No (Actions (Adecl)) then Set_Actions (Adecl, New_List); end if; Generate_Subprogram_Descriptor (N, Sloc (N), Spec, Actions (Adecl)); end Generate_Subprogram_Descriptor_For_Package; --------------------------------------------------- -- Generate_Subprogram_Descriptor_For_Subprogram -- --------------------------------------------------- procedure Generate_Subprogram_Descriptor_For_Subprogram (N : Node_Id; Spec : Entity_Id) is HSS : constant Node_Id := Handled_Statement_Sequence (N); begin if No (Exception_Handlers (HSS)) then Generate_Subprogram_Descriptor (N, Sloc (N), Spec, Statements (HSS)); else Generate_Subprogram_Descriptor (N, Sloc (N), Spec, Statements (Last (Exception_Handlers (HSS)))); end if; end Generate_Subprogram_Descriptor_For_Subprogram; ----------------------------------- -- Generate_Unit_Exception_Table -- ----------------------------------- -- The only remaining thing to generate here is to generate the -- reference to the subprogram descriptor chain. See Ada.Exceptions -- for details of required data structures. procedure Generate_Unit_Exception_Table is Loc : constant Source_Ptr := No_Location; Num : Nat; Decl : Node_Id; Ent : Entity_Id; Next_Ent : Entity_Id; Stent : Entity_Id; begin -- Nothing to be done if zero length exceptions not active if Exception_Mechanism /= Front_End_ZCX then return; end if; -- Remove any entries from SD_List that correspond to eliminated -- subprograms. Ent := First (SD_List); while Present (Ent) loop Next_Ent := Next (Ent); if Is_Eliminated (Scope (Entity (Prefix (Ent)))) then Remove (Ent); -- After this, there is no Next (Ent) anymore end if; Ent := Next_Ent; end loop; -- Nothing to do if no unit exception table present. -- An empty table can result from subprogram elimination, -- in such a case, eliminate the exception table itself. if Is_Empty_List (SD_List) then Unit_Exception_Table_Present := False; return; end if; -- Do not generate table in a generic if Inside_A_Generic then return; end if; -- Generate the unit exception table -- subtype Tnn is Subprogram_Descriptors_Record (Num); -- __gnat_unitname__SDP : aliased constant Tnn := -- Num, -- (sub1'unrestricted_access, -- sub2'unrestricted_access, -- ... -- subNum'unrestricted_access)); Num := List_Length (SD_List); Stent := Make_Defining_Identifier (Loc, Chars => New_Internal_Name ('T')); Insert_Library_Level_Action ( Make_Subtype_Declaration (Loc, Defining_Identifier => Stent, Subtype_Indication => Make_Subtype_Indication (Loc, Subtype_Mark => New_Occurrence_Of (RTE (RE_Subprogram_Descriptors_Record), Loc), Constraint => Make_Index_Or_Discriminant_Constraint (Loc, Constraints => New_List ( Make_Integer_Literal (Loc, Num)))))); Set_Is_Statically_Allocated (Stent); Get_External_Unit_Name_String (Unit_Name (Main_Unit)); Name_Buffer (1 + 7 .. Name_Len + 7) := Name_Buffer (1 .. Name_Len); Name_Buffer (1 .. 7) := "__gnat_"; Name_Len := Name_Len + 7; Add_Str_To_Name_Buffer ("__SDP"); Ent := Make_Defining_Identifier (Loc, Chars => Name_Find); Get_Name_String (Chars (Ent)); Set_Interface_Name (Ent, Make_String_Literal (Loc, Strval => String_From_Name_Buffer)); Decl := Make_Object_Declaration (Loc, Defining_Identifier => Ent, Object_Definition => New_Occurrence_Of (Stent, Loc), Constant_Present => True, Aliased_Present => True, Expression => Make_Aggregate (Loc, New_List ( Make_Integer_Literal (Loc, List_Length (SD_List)), Make_Aggregate (Loc, Expressions => SD_List)))); Insert_Library_Level_Action (Decl); Set_Is_Exported (Ent, True); Set_Is_Public (Ent, True); Set_Is_Statically_Allocated (Ent, True); Get_Name_String (Chars (Ent)); Set_Interface_Name (Ent, Make_String_Literal (Loc, Strval => String_From_Name_Buffer)); end Generate_Unit_Exception_Table; ---------------- -- Initialize -- ---------------- procedure Initialize is begin SD_List := Empty_List; end Initialize; ---------------------- -- Is_Non_Ada_Error -- ---------------------- function Is_Non_Ada_Error (E : Entity_Id) return Boolean is begin if not OpenVMS_On_Target then return False; end if; Get_Name_String (Chars (E)); -- Note: it is a little irregular for the body of exp_ch11 to know -- the details of the encoding scheme for names, but on the other -- hand, gigi knows them, and this is for gigi's benefit anyway! if Name_Buffer (1 .. 30) /= "system__aux_dec__non_ada_error" then return False; end if; return True; end Is_Non_Ada_Error; ---------------------------- -- Remove_Handler_Entries -- ---------------------------- procedure Remove_Handler_Entries (N : Node_Id) is function Check_Handler_Entry (N : Node_Id) return Traverse_Result; -- This function checks one node for a possible reference to a -- handler entry that must be deleted. it always returns OK. function Remove_All_Handler_Entries is new Traverse_Func (Check_Handler_Entry); -- This defines the traversal operation Discard : Traverse_Result; function Check_Handler_Entry (N : Node_Id) return Traverse_Result is begin if Nkind (N) = N_Object_Declaration then if Present (Handler_List_Entry (N)) then Remove (Handler_List_Entry (N)); Delete_Tree (Handler_List_Entry (N)); Set_Handler_List_Entry (N, Empty); elsif Is_Subprogram_Descriptor (N) then declare SDN : Node_Id; begin SDN := First (SD_List); while Present (SDN) loop if Defining_Identifier (N) = Entity (Prefix (SDN)) then Remove (SDN); Delete_Tree (SDN); exit; end if; Next (SDN); end loop; end; end if; end if; return OK; end Check_Handler_Entry; -- Start of processing for Remove_Handler_Entries begin if Exception_Mechanism = Front_End_ZCX then Discard := Remove_All_Handler_Entries (N); end if; end Remove_Handler_Entries; end Exp_Ch11;
-- -- Copyright 2018 The wookey project team <wookey@ssi.gouv.fr> -- - Ryad Benadjila -- - Arnauld Michelizza -- - Mathieu Renard -- - Philippe Thierry -- - Philippe Trebuchet -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- with m4.layout; package m4.systick with spark_mode => on is -- FIXME - Should be defined in arch/boards MAIN_CLOCK_FREQUENCY : constant := 168_000_000; TICKS_PER_SECOND : constant := 1000; subtype t_tick is unsigned_64; ---------------------------------------------------- -- SysTick control and status register (STK_CTRL) -- ---------------------------------------------------- type t_clock_type is (EXT_CLOCK, PROCESSOR_CLOCK) with size => 1; for t_clock_type use (EXT_CLOCK => 0, PROCESSOR_CLOCK => 1); type t_STK_CTRL is record ENABLE : boolean; -- Enables the counter TICKINT : boolean; -- Enables exception request CLKSOURCE : t_clock_type; COUNTFLAG : bit; end record with size => 32, volatile_full_access; for t_STK_CTRL use record ENABLE at 0 range 0 .. 0; TICKINT at 0 range 1 .. 1; CLKSOURCE at 0 range 2 .. 2; COUNTFLAG at 0 range 16 .. 16; end record; ---------------------------------------------- -- SysTick reload value register (STK_LOAD) -- ---------------------------------------------- -- Note: To generate a timer with a period of N processor clock -- cycles, use a RELOAD value of N-1. type t_STK_LOAD is record RELOAD : bits_24; end record with size => 32, volatile_full_access; ---------------------------------------------- -- SysTick current value register (STK_VAL) -- ---------------------------------------------- type t_STK_VAL is record CURRENT : bits_24; end record with size => 32, volatile_full_access; ---------------------------------------------------- -- SysTick calibration value register (STK_CALIB) -- ---------------------------------------------------- type t_STK_CALIB is record TENMS : bits_24; SKEW : bit; NOREF : bit; end record with size => 32, volatile_full_access; for t_STK_CALIB use record TENMS at 0 range 0 .. 23; SKEW at 0 range 30 .. 30; NOREF at 0 range 31 .. 31; end record; ---------------- -- Peripheral -- ---------------- type t_SYSTICK_peripheral is record CTRL : t_STK_CTRL; LOAD : t_STK_LOAD; VAL : t_STK_VAL; CALIB : t_STK_CALIB; end record with volatile; for t_SYSTICK_peripheral use record CTRL at 16#00# range 0 .. 31; LOAD at 16#04# range 0 .. 31; VAL at 16#08# range 0 .. 31; CALIB at 16#0C# range 0 .. 31; end record; SYSTICK : t_SYSTICK_peripheral with import, volatile, address => m4.layout.SYS_TIMER_base; --------------- -- Functions -- --------------- -- Initialize the systick module procedure init; -- Get the number of milliseconds elapsed since booting function get_ticks return unsigned_64 with volatile_function; function get_milliseconds return milliseconds with volatile_function; function get_microseconds return microseconds with volatile_function; function to_ticks (ms : milliseconds) return t_tick with inline_always; function to_milliseconds (t : t_tick) return milliseconds with inline_always; function to_microseconds (t : t_tick) return microseconds with inline_always; -- Note: default Systick IRQ handler is defined in package -- ewok.interrupts.handler and call 'increment' procedure procedure increment with inline_always; private ticks : t_tick := 0 with volatile, async_writers; end m4.systick;
-- { dg-do compile } with Pack1; package body limited_with is procedure Print_2 (Obj : access Pack1.Nested.Rec_Typ) is begin null; end; end limited_with;
with Ada.Integer_Text_IO; with Is_Palindrome; procedure Euler4 is function String_Palindrome is new Is_Palindrome(Character, Positive, String); Prod, Max: Integer := 0; begin for I in Integer range 100 .. 999 loop for J in Integer range I .. 999 loop Prod := I * J; if Prod > Max and String_Palindrome(Integer'Image(Prod) & ' ') then Max := Prod; end if; end loop; end loop; Ada.Integer_Text_IO.Put(Max); end Euler4;
procedure TEST is COLUMN_MAX : constant := 10; ROW_MAX : constant := COLUMN_MAX; type COLUMN_INDEX is range 1..COLUMN_MAX; type ROW_INDEX is range 1..ROW_MAX; type MATRIX is array(COLUMN_INDEX, ROW_INDEX) of INTEGER; A : MATRIX; I : INTEGER; procedure INIT_MATRIX(X : in INTEGER; Y : out MATRIX) is I, J : INTEGER; begin I := 1; while I <= COLUMN_MAX loop J := 1; while J <= ROW_MAX loop Y(I, J) := X; J := J + 1; end loop; I := I + 1; end loop; end INIT_MATRIX; begin I := 11; if I = 1 then print(1); elsif true then print("haha hoho"); elsif false then print(I > 10); else print(4+5); end if; INIT_MATRIX(I, A); print(I*3 / 4); end TEST;
-- IntCode Interpreter with Ada.Strings.Unbounded; with Ada.Strings.Maps; with Ada.Strings.Hash; with Ada.Strings.Fixed; with Ada.Text_IO; package body IntCode is package TIO renames Ada.Text_IO; procedure append_input(val : Integer) is begin input_vector.append(val); end append_input; function take_output return Integer is val : constant Integer := output_vector.First_Element; begin output_vector.Delete_First; return val; end take_output; function integer_hash(i: Integer) return Ada.Containers.Hash_Type is (Ada.Strings.Hash(Integer'Image(i))); type Program_Counter is new Natural; pc : Program_Counter; function to_pc(i : Integer) return Program_Counter is (Program_Counter(i)); function to_index(p : Program_Counter) return Natural is (Natural(p)); function val(offset : Integer) return Integer is (memory(memory(offset + to_index(pc)))); function val_a(offset : Integer := 1) return Integer renames val; function val_b(offset : Integer := 2) return Integer renames val; function loc_a return Integer is (memory(to_index(pc) + 1)); function loc_b return Integer is (memory(to_index(pc) + 2)); function loc_c return Integer is (memory(to_index(pc) + 3)); procedure increment_pc(s : Integer := 4) is begin pc := to_pc(to_index(pc) + s); end increment_pc; procedure load_file(path : String) is file : TIO.File_Type; begin TIO.open(File => file, Mode => TIO.In_File, Name => path); declare str : String := TIO.get_line(file); begin load(str); end; TIO.close(file); end load_file; procedure load(s : String) is start : Natural := s'First; finish : Natural; delimiters : constant Ada.Strings.Maps.Character_Set := Ada.Strings.Maps.to_set(Sequence => ","); begin memory.clear; while start <= s'Last loop Ada.Strings.Fixed.find_token(Source => s(start .. s'Last), Set => delimiters, Test => Ada.Strings.outside, First => start, Last => finish); if not(finish = 0 and then start = s'First) then memory.append(Integer'Value(s(start .. finish))); end if; start := finish + 1; end loop; pc := to_pc(memory.first_index); end load; procedure eval is should_halt : Boolean := False; val : Integer; begin pc := to_pc(memory.first_index); while not(should_halt) loop val := memory(to_index(pc)); case OpCode_Map(val) is when Add => memory(loc_c) := val_a + val_b; increment_pc; when Mult => memory(loc_c) := val_a * val_b; increment_pc; when Input => memory(loc_a) := input_vector.First_Element; input_vector.Delete_First; increment_pc(2); when Output => output_vector.Append(val_a); increment_pc(2); when Halt => should_halt := True; end case; end loop; end eval; procedure poke(addr : Natural; value : Integer) is begin memory(addr) := value; end poke; function peek(addr : Natural) return Integer is (memory(addr)); function dump return String is package Unbounded renames Ada.Strings.Unbounded; str : Ada.Strings.Unbounded.Unbounded_String; begin for m of memory loop Unbounded.append(str, (Integer'Image(m) & ", ")); end loop; return Unbounded.to_string(str); end dump; begin OpCode_Map.insert(1, Add); OpCode_Map.insert(2, Mult); OpCode_Map.insert(3, Input); OpCode_Map.insert(4, Output); OpCode_Map.insert(99, Halt); end IntCode;
------------------------------------------------------------------------------ -- -- -- ASIS-for-GNAT IMPLEMENTATION COMPONENTS -- -- -- -- A S I S . I M P L E M E N T A T I O N -- -- -- -- Copyright (C) 1995-2007, 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.adaccore.com). -- -- -- ------------------------------------------------------------------------------ with Ada.Characters.Handling; use Ada.Characters.Handling; with Ada.Strings; use Ada.Strings; with Ada.Strings.Fixed; use Ada.Strings.Fixed; with Asis.Errors; use Asis.Errors; with Asis.Exceptions; use Asis.Exceptions; with A4G.A_Debug; use A4G.A_Debug; with A4G.A_Opt; use A4G.A_Opt; with A4G.Contt; use A4G.Contt; with A4G.Defaults; with A4G.Vcheck; use A4G.Vcheck; with A4G.A_Osint; use A4G.A_Osint; with Gnatvsn; with Opt; package body Asis.Implementation is Package_Name : constant String := "Asis.Implementation."; ---------------------- -- Asis_Implementor -- ---------------------- function ASIS_Implementor return Wide_String is begin return "AdaCore (http://www.adacore.com)"; end ASIS_Implementor; ---------------------------------- -- ASIS_Implementor_Information -- ---------------------------------- function ASIS_Implementor_Information return Wide_String is begin return "Copyright (C) 1995-" & To_Wide_String (Gnatvsn.Current_Year) & ", Free Software Foundation"; end ASIS_Implementor_Information; ------------------------------ -- ASIS_Implementor_Version -- ------------------------------ function ASIS_Implementor_Version return Wide_String is GNAT_Version : constant String := Gnatvsn.Gnat_Version_String; First_Idx : constant Positive := GNAT_Version'First; Last_Idx : Positive := GNAT_Version'Last; Minus_Detected : Boolean := False; begin for J in reverse GNAT_Version'Range loop if GNAT_Version (J) = '-' then Last_Idx := J - 1; Minus_Detected := True; exit; end if; end loop; if Minus_Detected then return ASIS_Version & " for GNAT " & To_Wide_String (GNAT_Version (First_Idx .. Last_Idx)) & ")"; else return ASIS_Version & " for GNAT " & To_Wide_String (GNAT_Version (First_Idx .. Last_Idx)); end if; end ASIS_Implementor_Version; ------------------ -- ASIS_Version -- ------------------ function ASIS_Version return Wide_String is begin return "ASIS 2.0.R"; end ASIS_Version; --------------- -- Diagnosis -- --------------- function Diagnosis return Wide_String is begin -- The ASIS Diagnosis string uses only the first 256 values of -- Wide_Character type return To_Wide_String (Diagnosis_Buffer (1 .. Diagnosis_Len)); end Diagnosis; -------------- -- Finalize -- -------------- procedure Finalize (Parameters : Wide_String := "") is S_Parameters : constant String := Trim (To_String (Parameters), Both); -- all the valid actuals for Parametes should contain only -- characters from the first 256 values of Wide_Character type begin if not A4G.A_Opt.Is_Initialized then return; end if; if Debug_Flag_C or else Debug_Lib_Model or else Debug_Mode then Print_Context_Info; end if; if S_Parameters'Length > 0 then Process_Finalization_Parameters (S_Parameters); end if; A4G.Contt.Finalize; A4G.A_Opt.Set_Off; A4G.A_Debug.Set_Off; A4G.A_Opt.Is_Initialized := False; exception when ASIS_Failed => A4G.A_Opt.Set_Off; A4G.A_Debug.Set_Off; A4G.A_Opt.Is_Initialized := False; if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Outer_Call => Package_Name & "Finalize"); end if; raise; when Ex : others => A4G.A_Opt.Set_Off; A4G.A_Debug.Set_Off; A4G.A_Opt.Is_Initialized := False; Report_ASIS_Bug (Query_Name => Package_Name & "Finalize", Ex => Ex); end Finalize; ---------------- -- Initialize -- ---------------- procedure Initialize (Parameters : Wide_String := "") is S_Parameters : constant String := Trim (To_String (Parameters), Both); -- all the valid actuals for Parametes should contain only -- characters from the first 256 values of Wide_Character type begin if A4G.A_Opt.Is_Initialized then return; end if; if not A4G.A_Opt.Was_Initialized_At_Least_Once then Opt.Maximum_File_Name_Length := Get_Max_File_Name_Length; A4G.A_Opt.Was_Initialized_At_Least_Once := True; end if; if S_Parameters'Length > 0 then Process_Initialization_Parameters (S_Parameters); end if; A4G.Contt.Initialize; A4G.Defaults.Initialize; A4G.A_Opt.Is_Initialized := True; exception when ASIS_Failed => A4G.A_Opt.Set_Off; A4G.A_Debug.Set_Off; A4G.A_Opt.Is_Initialized := False; if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Outer_Call => Package_Name & "Initialize"); end if; raise; when Ex : others => A4G.A_Opt.Set_Off; A4G.A_Debug.Set_Off; A4G.A_Opt.Is_Initialized := False; Report_ASIS_Bug (Query_Name => Package_Name & "Initialize", Ex => Ex); end Initialize; ------------------ -- Is_Finalized -- ------------------ function Is_Finalized return Boolean is begin return not A4G.A_Opt.Is_Initialized; end Is_Finalized; -------------------- -- Is_Initialized -- -------------------- function Is_Initialized return Boolean is begin return A4G.A_Opt.Is_Initialized; end Is_Initialized; ---------------- -- Set_Status -- ---------------- procedure Set_Status (Status : Asis.Errors.Error_Kinds := Asis.Errors.Not_An_Error; Diagnosis : Wide_String := "") is begin A4G.Vcheck.Set_Error_Status (Status => Status, Diagnosis => To_String (Diagnosis)); end Set_Status; ------------ -- Status -- ------------ function Status return Asis.Errors.Error_Kinds is begin return Status_Indicator; end Status; end Asis.Implementation;
package Opt35_Pkg is pragma Pure; E : Exception; function F (I : Integer) return Integer; end Opt35_Pkg;
pragma License (Unrestricted); -- extended unit with Interfaces.C.Pointers; package Interfaces.C.Char_Pointers is new Pointers ( Index => size_t, Element => char, Element_Array => char_array, Default_Terminator => char'Val (0)); -- The instance of Interfaces.C.Pointers for char. pragma Pure (Interfaces.C.Char_Pointers);
--------------------------------------------------------------------------------- -- Copyright 2004-2005 © Luke A. Guest -- -- This code is to be used for tutorial purposes only. -- You may not redistribute this code in any form without my express permission. --------------------------------------------------------------------------------- package GLUtils is function GL_Vendor return String; function GL_Version return String; function GL_Renderer return String; function GL_Extensions return String; function GLU_Version return String; function GLU_Extensions return String; function IsExtensionAvailable(ExtensionToFind : in String) return Boolean; generic type ELEMENT is private; function GetProc(Name : in String) return ELEMENT; end GLUtils;
-- SPDX-FileCopyrightText: 2020 Max Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT ---------------------------------------------------------------- package Markdown is pragma Pure; subtype Can_Interrupt_Paragraph is Boolean; end Markdown;
-- part of AdaYaml, (c) 2017 Felix Krause -- released under the terms of the MIT license, see the file "copying.txt" private with Yaml.Events.Store; private with Yaml.Events.Queue; package Yaml.Transformator.Annotation.Vars is type Instance is limited new Transformator.Instance with private; overriding procedure Put (Object : in out Instance; E : Event); overriding function Has_Next (Object : Instance) return Boolean; overriding function Next (Object : in out Instance) return Event; function New_Vars (Pool : Text.Pool.Reference; Node_Context : Node_Context_Type; Processor_Context : Events.Context.Reference; Swallows_Previous : out Boolean) return not null Pointer; private type State_Type is not null access procedure (Object : in out Instance; E : Event); procedure Initial (Object : in out Instance; E : Event); procedure After_Annotation_Start (Object : in out Instance; E : Event); procedure After_Annotation_End (Object : in out Instance; E : Event); procedure At_Mapping_Level (Object : in out Instance; E : Event); procedure Inside_Value (Object : in out Instance; E : Event); procedure After_Mapping_End (Object : in out Instance; E : Event); type Instance is limited new Transformator.Instance with record Context : Events.Context.Reference; Depth : Natural := 0; State : State_Type := Initial'Access; Cur_Queue : Events.Queue.Instance; Cur_Name : Text.Reference; end record; end Yaml.Transformator.Annotation.Vars;
-- Standard Ada library specification -- Copyright (c) 2003-2018 Maxim Reznik <reznikmm@gmail.com> -- Copyright (c) 2004-2016 AXE Consultants -- Copyright (c) 2004, 2005, 2006 Ada-Europe -- Copyright (c) 2000 The MITRE Corporation, Inc. -- Copyright (c) 1992, 1993, 1994, 1995 Intermetrics, Inc. -- SPDX-License-Identifier: BSD-3-Clause and LicenseRef-AdaReferenceManual --------------------------------------------------------------------------- package Ada.Decimal is pragma Pure (Decimal); Max_Scale : constant := implementation_defined; Min_Scale : constant := implementation_defined; Min_Delta : constant := 10.0**(-Max_Scale); Max_Delta : constant := 10.0**(-Min_Scale); Max_Decimal_Digits : constant := implementation_defined; generic type Dividend_Type is delta <> digits <>; type Divisor_Type is delta <> digits <>; type Quotient_Type is delta <> digits <>; type Remainder_Type is delta <> digits <>; procedure Divide (Dividend : in Dividend_Type; Divisor : in Divisor_Type; Quotient : out Quotient_Type; Remainder : out Remainder_Type); pragma Convention (Intrinsic, Divide); end Ada.Decimal;
with System.Formatting; with System.Long_Long_Integer_Types; with System.Random_Initiators; with System.Storage_Elements; package body Ada.Numerics.MT19937 is use type Interfaces.Unsigned_32; use type System.Storage_Elements.Storage_Count; subtype Word_Unsigned is System.Long_Long_Integer_Types.Word_Unsigned; MATRIX_A : constant := 16#9908b0df#; UPPER_MASK : constant := 16#80000000#; -- 2 ** (32 - 1) LOWER_MASK : constant := 16#7fffffff#; -- not UPPER_MASK -- implementation function Random_32 (Gen : aliased in out Generator) return Unsigned_32 is pragma Suppress (Index_Check); pragma Suppress (Range_Check); mag01 : constant array (Unsigned_32 range 0 .. 1) of Unsigned_32 := (0, MATRIX_A); y : Unsigned_32; S : State renames Gen.State; begin if S.Condition >= N then for kk in 0 .. (N - M - 1) loop y := (S.Vector (kk) and UPPER_MASK) or (S.Vector (kk + 1) and LOWER_MASK); S.Vector (kk) := S.Vector (kk + M) xor Interfaces.Shift_Right (y, 1) xor mag01 (y and 1); end loop; for kk in (N - M) .. (N - 2) loop y := (S.Vector (kk) and UPPER_MASK) or (S.Vector (kk + 1) and LOWER_MASK); S.Vector (kk) := S.Vector (kk + (M - N)) xor Interfaces.Shift_Right (y, 1) xor mag01 (y and 1); end loop; y := (S.Vector (N - 1) and UPPER_MASK) or (S.Vector (0) and LOWER_MASK); S.Vector (N - 1) := S.Vector (M - 1) xor Interfaces.Shift_Right (y, 1) xor mag01 (y and 1); S.Condition := 0; end if; y := S.Vector (Integer (S.Condition)); S.Condition := S.Condition + 1; y := y xor Interfaces.Shift_Right (y, 11); y := y xor (Interfaces.Shift_Left (y, 7) and 16#9d2c5680#); y := y xor (Interfaces.Shift_Left (y, 15) and 16#efc60000#); y := y xor Interfaces.Shift_Right (y, 18); return y; end Random_32; function Initialize return Generator is begin return (State => Initialize); end Initialize; function Initialize (Initiator : Unsigned_32) return Generator is begin return (State => Initialize (Initiator)); end Initialize; function Initialize (Initiator : Unsigned_32_Array) return Generator is begin return (State => Initialize (Initiator)); end Initialize; procedure Reset (Gen : in out Generator) is begin Gen.State := Initialize; end Reset; procedure Reset (Gen : in out Generator; Initiator : Integer) is begin Gen.State := Initialize (Unsigned_32'Mod (Initiator)); end Reset; function Initialize return State is Init : aliased Unsigned_32_Array_N; begin System.Random_Initiators.Get ( Init'Address, Init'Size / Standard'Storage_Unit); return Initialize (Init); end Initialize; function Initialize (Initiator : Unsigned_32) return State is V : Unsigned_32 := Initiator; begin return Result : State do Result.Vector (0) := V; for I in 1 .. (N - 1) loop V := 1812433253 * (V xor Interfaces.Shift_Right (V, 30)) + Unsigned_32 (I); Result.Vector (I) := V; end loop; Result.Condition := N; end return; end Initialize; function Initialize (Initiator : Unsigned_32_Array) return State is Initiator_Length : constant Natural := Initiator'Length; i : Integer := 1; j : Integer := 0; begin return Result : State := Initialize (19650218) do if Initiator_Length > 0 then for K in reverse 1 .. Integer'Max (N, Initiator_Length) loop declare P : constant Unsigned_32 := Result.Vector (i - 1); begin Result.Vector (i) := (Result.Vector (i) xor ((P xor Interfaces.Shift_Right (P, 30)) * 1664525)) + Initiator (Initiator'First + j) + Unsigned_32 (j); end; i := i + 1; if i >= N then Result.Vector (0) := Result.Vector (N - 1); i := 1; end if; j := (j + 1) rem Positive'(Initiator_Length); end loop; for K in reverse 1 .. (N - 1) loop declare P : constant Unsigned_32 := Result.Vector (i - 1); begin Result.Vector (i) := (Result.Vector (i) xor ((P xor Interfaces.Shift_Right (P, 30)) * 1566083941)) - Unsigned_32 (i); end; i := i + 1; if i >= N then Result.Vector (0) := Result.Vector (N - 1); i := 1; end if; end loop; Result.Vector (0) := 16#80000000#; end if; end return; end Initialize; procedure Save (Gen : Generator; To_State : out State) is begin To_State := Gen.State; end Save; procedure Reset (Gen : in out Generator; From_State : State) is begin Gen.State := From_State; end Reset; function Reset (From_State : State) return Generator is begin return (State => From_State); end Reset; function Image (Of_State : State) return String is procedure Hex (Result : in out String; Value : Unsigned_32); procedure Hex (Result : in out String; Value : Unsigned_32) is Error : Boolean; Last : Natural; begin pragma Compile_Time_Error (Standard'Word_Size < 32, "word size < 32"); System.Formatting.Image ( Word_Unsigned (Value), Result, Last, Base => 16, Width => 32 / 4, Error => Error); pragma Assert (not Error and then Last = Result'Last); end Hex; Last : Natural := 0; begin return Result : String (1 .. Max_Image_Width) do for I in Unsigned_32_Array_N'Range loop declare Previous_Last : constant Natural := Last; begin Last := Last + 32 / 4; Hex (Result (Previous_Last + 1 .. Last), Of_State.Vector (I)); Last := Last + 1; Result (Last) := ':'; end; end loop; Hex (Result (Last + 1 .. Result'Last), Of_State.Condition); end return; end Image; function Value (Coded_State : String) return State is procedure Hex (Item : String; Value : out Unsigned_32); procedure Hex (Item : String; Value : out Unsigned_32) is Last : Positive; Error : Boolean; begin System.Formatting.Value ( Item, Last, Word_Unsigned (Value), Base => 16, Error => Error); if Error or else Last /= Item'Last then raise Constraint_Error; end if; end Hex; Last : Natural := Coded_State'First - 1; begin if Coded_State'Length /= Max_Image_Width then raise Constraint_Error; end if; return Result : State do for I in Unsigned_32_Array_N'Range loop declare Previous_Last : constant Natural := Last; begin Last := Last + 32 / 4; Hex ( Coded_State (Previous_Last + 1 .. Last), Result.Vector (I)); Last := Last + 1; if Coded_State (Last) /= ':' then raise Constraint_Error; end if; end; end loop; Hex (Coded_State (Last + 1 .. Coded_State'Last), Result.Condition); end return; end Value; function Random_0_To_1 (Gen : aliased in out Generator) return Uniformly_Distributed is begin return Uniformly_Distributed'Base (Random_32 (Gen)) * (1.0 / 4294967295.0); end Random_0_To_1; function Random_0_To_Less_Than_1 (Gen : aliased in out Generator) return Uniformly_Distributed is begin return Uniformly_Distributed'Base (Random_32 (Gen)) * (1.0 / 4294967296.0); end Random_0_To_Less_Than_1; function Random_Greater_Than_0_To_Less_Than_1 ( Gen : aliased in out Generator) return Uniformly_Distributed is begin return (Uniformly_Distributed'Base (Random_32 (Gen)) + 0.5) * (1.0 / 4294967296.0); end Random_Greater_Than_0_To_Less_Than_1; function Random_53_0_To_Less_Than_1 (Gen : aliased in out Generator) return Uniformly_Distributed is A : constant Unsigned_32 := Interfaces.Shift_Right (Random_32 (Gen), 5); B : constant Unsigned_32 := Interfaces.Shift_Right (Random_32 (Gen), 6); Float_A : constant Long_Long_Float := Uniformly_Distributed'Base (A); Float_B : constant Long_Long_Float := Uniformly_Distributed'Base (B); begin return (Float_A * 67108864.0 + Float_B) * (1.0 / 9007199254740992.0); end Random_53_0_To_Less_Than_1; end Ada.Numerics.MT19937;
----------------------------------------------------------------------- -- AWA.Audits.Models -- AWA.Audits.Models ----------------------------------------------------------------------- -- File generated by ada-gen DO NOT MODIFY -- Template used: templates/model/package-body.xhtml -- Ada Generator: https://ada-gen.googlecode.com/svn/trunk Revision 1095 ----------------------------------------------------------------------- -- Copyright (C) 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.Unchecked_Deallocation; with Util.Beans.Objects.Time; package body AWA.Audits.Models is use type ADO.Objects.Object_Record_Access; use type ADO.Objects.Object_Ref; pragma Warnings (Off, "formal parameter * is not referenced"); function Audit_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => AUDIT_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end Audit_Key; function Audit_Key (Id : in String) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => AUDIT_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end Audit_Key; function "=" (Left, Right : Audit_Ref'Class) return Boolean is begin return ADO.Objects.Object_Ref'Class (Left) = ADO.Objects.Object_Ref'Class (Right); end "="; procedure Set_Field (Object : in out Audit_Ref'Class; Impl : out Audit_Access) is Result : ADO.Objects.Object_Record_Access; begin Object.Prepare_Modify (Result); Impl := Audit_Impl (Result.all)'Access; end Set_Field; -- Internal method to allocate the Object_Record instance procedure Allocate (Object : in out Audit_Ref) is Impl : Audit_Access; begin Impl := new Audit_Impl; Impl.Date := ADO.DEFAULT_TIME; Impl.Old_Value.Is_Null := True; Impl.New_Value.Is_Null := True; Impl.Entity_Id := ADO.NO_IDENTIFIER; Impl.Field := 0; Impl.Entity_Type := 0; ADO.Objects.Set_Object (Object, Impl.all'Access); end Allocate; -- ---------------------------------------- -- Data object: Audit -- ---------------------------------------- procedure Set_Id (Object : in out Audit_Ref; Value : in ADO.Identifier) is Impl : Audit_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Key_Value (Impl.all, 1, Value); end Set_Id; function Get_Id (Object : in Audit_Ref) return ADO.Identifier is Impl : constant Audit_Access := Audit_Impl (Object.Get_Object.all)'Access; begin return Impl.Get_Key_Value; end Get_Id; procedure Set_Date (Object : in out Audit_Ref; Value : in Ada.Calendar.Time) is Impl : Audit_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Time (Impl.all, 2, Impl.Date, Value); end Set_Date; function Get_Date (Object : in Audit_Ref) return Ada.Calendar.Time is Impl : constant Audit_Access := Audit_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Date; end Get_Date; procedure Set_Old_Value (Object : in out Audit_Ref; Value : in String) is Impl : Audit_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_String (Impl.all, 3, Impl.Old_Value, Value); end Set_Old_Value; procedure Set_Old_Value (Object : in out Audit_Ref; Value : in ADO.Nullable_String) is Impl : Audit_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_String (Impl.all, 3, Impl.Old_Value, Value); end Set_Old_Value; function Get_Old_Value (Object : in Audit_Ref) return String is Value : constant ADO.Nullable_String := Object.Get_Old_Value; begin if Value.Is_Null then return ""; else return Ada.Strings.Unbounded.To_String (Value.Value); end if; end Get_Old_Value; function Get_Old_Value (Object : in Audit_Ref) return ADO.Nullable_String is Impl : constant Audit_Access := Audit_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Old_Value; end Get_Old_Value; procedure Set_New_Value (Object : in out Audit_Ref; Value : in String) is Impl : Audit_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_String (Impl.all, 4, Impl.New_Value, Value); end Set_New_Value; procedure Set_New_Value (Object : in out Audit_Ref; Value : in ADO.Nullable_String) is Impl : Audit_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_String (Impl.all, 4, Impl.New_Value, Value); end Set_New_Value; function Get_New_Value (Object : in Audit_Ref) return String is Value : constant ADO.Nullable_String := Object.Get_New_Value; begin if Value.Is_Null then return ""; else return Ada.Strings.Unbounded.To_String (Value.Value); end if; end Get_New_Value; function Get_New_Value (Object : in Audit_Ref) return ADO.Nullable_String is Impl : constant Audit_Access := Audit_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.New_Value; end Get_New_Value; procedure Set_Entity_Id (Object : in out Audit_Ref; Value : in ADO.Identifier) is Impl : Audit_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Identifier (Impl.all, 5, Impl.Entity_Id, Value); end Set_Entity_Id; function Get_Entity_Id (Object : in Audit_Ref) return ADO.Identifier is Impl : constant Audit_Access := Audit_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Entity_Id; end Get_Entity_Id; procedure Set_Field (Object : in out Audit_Ref; Value : in Integer) is Impl : Audit_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Integer (Impl.all, 6, Impl.Field, Value); end Set_Field; function Get_Field (Object : in Audit_Ref) return Integer is Impl : constant Audit_Access := Audit_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Field; end Get_Field; procedure Set_Session (Object : in out Audit_Ref; Value : in AWA.Users.Models.Session_Ref'Class) is Impl : Audit_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Object (Impl.all, 7, Impl.Session, Value); end Set_Session; function Get_Session (Object : in Audit_Ref) return AWA.Users.Models.Session_Ref'Class is Impl : constant Audit_Access := Audit_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Session; end Get_Session; procedure Set_Entity_Type (Object : in out Audit_Ref; Value : in ADO.Entity_Type) is Impl : Audit_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Entity_Type (Impl.all, 8, Impl.Entity_Type, Value); end Set_Entity_Type; function Get_Entity_Type (Object : in Audit_Ref) return ADO.Entity_Type is Impl : constant Audit_Access := Audit_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Entity_Type; end Get_Entity_Type; -- Copy of the object. procedure Copy (Object : in Audit_Ref; Into : in out Audit_Ref) is Result : Audit_Ref; begin if not Object.Is_Null then declare Impl : constant Audit_Access := Audit_Impl (Object.Get_Load_Object.all)'Access; Copy : constant Audit_Access := new Audit_Impl; begin ADO.Objects.Set_Object (Result, Copy.all'Access); Copy.Copy (Impl.all); Copy.Date := Impl.Date; Copy.Old_Value := Impl.Old_Value; Copy.New_Value := Impl.New_Value; Copy.Entity_Id := Impl.Entity_Id; Copy.Field := Impl.Field; Copy.Session := Impl.Session; Copy.Entity_Type := Impl.Entity_Type; end; end if; Into := Result; end Copy; procedure Find (Object : in out Audit_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Impl : constant Audit_Access := new Audit_Impl; begin Impl.Find (Session, Query, Found); if Found then ADO.Objects.Set_Object (Object, Impl.all'Access); else ADO.Objects.Set_Object (Object, null); Destroy (Impl); end if; end Find; procedure Load (Object : in out Audit_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier) is Impl : constant Audit_Access := new Audit_Impl; Found : Boolean; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter ("id = ?"); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); raise ADO.Objects.NOT_FOUND; end if; ADO.Objects.Set_Object (Object, Impl.all'Access); end Load; procedure Load (Object : in out Audit_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean) is Impl : constant Audit_Access := new Audit_Impl; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter ("id = ?"); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); else ADO.Objects.Set_Object (Object, Impl.all'Access); end if; end Load; procedure Save (Object : in out Audit_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl = null then Impl := new Audit_Impl; ADO.Objects.Set_Object (Object, Impl); end if; if not ADO.Objects.Is_Created (Impl.all) then Impl.Create (Session); else Impl.Save (Session); end if; end Save; procedure Delete (Object : in out Audit_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : constant ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl /= null then Impl.Delete (Session); end if; end Delete; -- -------------------- -- Free the object -- -------------------- procedure Destroy (Object : access Audit_Impl) is type Audit_Impl_Ptr is access all Audit_Impl; procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Audit_Impl, Audit_Impl_Ptr); pragma Warnings (Off, "*redundant conversion*"); Ptr : Audit_Impl_Ptr := Audit_Impl (Object.all)'Access; pragma Warnings (On, "*redundant conversion*"); begin Unchecked_Free (Ptr); end Destroy; procedure Find (Object : in out Audit_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query, AUDIT_DEF'Access); begin Stmt.Execute; if Stmt.Has_Elements then Object.Load (Stmt, Session); Stmt.Next; Found := not Stmt.Has_Elements; else Found := False; end if; end Find; overriding procedure Load (Object : in out Audit_Impl; Session : in out ADO.Sessions.Session'Class) is Found : Boolean; Query : ADO.SQL.Query; Id : constant ADO.Identifier := Object.Get_Key_Value; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter ("id = ?"); Object.Find (Session, Query, Found); if not Found then raise ADO.Objects.NOT_FOUND; end if; end Load; procedure Save (Object : in out Audit_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Update_Statement := Session.Create_Statement (AUDIT_DEF'Access); begin if Object.Is_Modified (6) then Stmt.Save_Field (Name => COL_5_1_NAME, -- field Value => Object.Field); Object.Clear_Modified (6); end if; if Object.Is_Modified (7) then Stmt.Save_Field (Name => COL_6_1_NAME, -- session_id Value => Object.Session); Object.Clear_Modified (7); end if; if Object.Is_Modified (8) then Stmt.Save_Field (Name => COL_7_1_NAME, -- entity_type Value => Object.Entity_Type); Object.Clear_Modified (8); end if; if Stmt.Has_Save_Fields then Stmt.Set_Filter (Filter => "id = ?"); Stmt.Add_Param (Value => Object.Get_Key); declare Result : Integer; begin Stmt.Execute (Result); if Result /= 1 then if Result /= 0 then raise ADO.Objects.UPDATE_ERROR; end if; end if; end; end if; end Save; procedure Create (Object : in out Audit_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Query : ADO.Statements.Insert_Statement := Session.Create_Statement (AUDIT_DEF'Access); Result : Integer; begin Session.Allocate (Id => Object); Query.Save_Field (Name => COL_0_1_NAME, -- id Value => Object.Get_Key); Query.Save_Field (Name => COL_1_1_NAME, -- date Value => Object.Date); Query.Save_Field (Name => COL_2_1_NAME, -- old_value Value => Object.Old_Value); Query.Save_Field (Name => COL_3_1_NAME, -- new_value Value => Object.New_Value); Query.Save_Field (Name => COL_4_1_NAME, -- entity_id Value => Object.Entity_Id); Query.Save_Field (Name => COL_5_1_NAME, -- field Value => Object.Field); Query.Save_Field (Name => COL_6_1_NAME, -- session_id Value => Object.Session); Query.Save_Field (Name => COL_7_1_NAME, -- entity_type Value => Object.Entity_Type); Query.Execute (Result); if Result /= 1 then raise ADO.Objects.INSERT_ERROR; end if; ADO.Objects.Set_Created (Object); end Create; procedure Delete (Object : in out Audit_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Delete_Statement := Session.Create_Statement (AUDIT_DEF'Access); begin Stmt.Set_Filter (Filter => "id = ?"); Stmt.Add_Param (Value => Object.Get_Key); Stmt.Execute; end Delete; -- ------------------------------ -- Get the bean attribute identified by the name. -- ------------------------------ overriding function Get_Value (From : in Audit_Ref; Name : in String) return Util.Beans.Objects.Object is Obj : ADO.Objects.Object_Record_Access; Impl : access Audit_Impl; begin if From.Is_Null then return Util.Beans.Objects.Null_Object; end if; Obj := From.Get_Load_Object; Impl := Audit_Impl (Obj.all)'Access; if Name = "id" then return ADO.Objects.To_Object (Impl.Get_Key); elsif Name = "date" then return Util.Beans.Objects.Time.To_Object (Impl.Date); elsif Name = "old_value" then if Impl.Old_Value.Is_Null then return Util.Beans.Objects.Null_Object; else return Util.Beans.Objects.To_Object (Impl.Old_Value.Value); end if; elsif Name = "new_value" then if Impl.New_Value.Is_Null then return Util.Beans.Objects.Null_Object; else return Util.Beans.Objects.To_Object (Impl.New_Value.Value); end if; elsif Name = "entity_id" then return Util.Beans.Objects.To_Object (Long_Long_Integer (Impl.Entity_Id)); elsif Name = "field" then return Util.Beans.Objects.To_Object (Long_Long_Integer (Impl.Field)); elsif Name = "entity_type" then return Util.Beans.Objects.To_Object (Long_Long_Integer (Impl.Entity_Type)); end if; return Util.Beans.Objects.Null_Object; end Get_Value; procedure List (Object : in out Audit_Vector; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class) is Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query, AUDIT_DEF'Access); begin Stmt.Execute; Audit_Vectors.Clear (Object); while Stmt.Has_Elements loop declare Item : Audit_Ref; Impl : constant Audit_Access := new Audit_Impl; begin Impl.Load (Stmt, Session); ADO.Objects.Set_Object (Item, Impl.all'Access); Object.Append (Item); end; Stmt.Next; end loop; end List; -- ------------------------------ -- Load the object from current iterator position -- ------------------------------ procedure Load (Object : in out Audit_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class) is begin Object.Set_Key_Value (Stmt.Get_Identifier (0)); Object.Date := Stmt.Get_Time (1); Object.Old_Value := Stmt.Get_Nullable_String (2); Object.New_Value := Stmt.Get_Nullable_String (3); Object.Entity_Id := Stmt.Get_Identifier (4); Object.Field := Stmt.Get_Integer (5); if not Stmt.Is_Null (6) then Object.Session.Set_Key_Value (Stmt.Get_Identifier (6), Session); end if; Object.Entity_Type := ADO.Entity_Type (Stmt.Get_Integer (7)); ADO.Objects.Set_Created (Object); end Load; function Audit_Field_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_STRING, Of_Class => AUDIT_FIELD_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end Audit_Field_Key; function Audit_Field_Key (Id : in String) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_STRING, Of_Class => AUDIT_FIELD_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end Audit_Field_Key; function "=" (Left, Right : Audit_Field_Ref'Class) return Boolean is begin return ADO.Objects.Object_Ref'Class (Left) = ADO.Objects.Object_Ref'Class (Right); end "="; procedure Set_Field (Object : in out Audit_Field_Ref'Class; Impl : out Audit_Field_Access) is Result : ADO.Objects.Object_Record_Access; begin Object.Prepare_Modify (Result); Impl := Audit_Field_Impl (Result.all)'Access; end Set_Field; -- Internal method to allocate the Object_Record instance procedure Allocate (Object : in out Audit_Field_Ref) is Impl : Audit_Field_Access; begin Impl := new Audit_Field_Impl; Impl.Entity_Type := 0; ADO.Objects.Set_Object (Object, Impl.all'Access); end Allocate; -- ---------------------------------------- -- Data object: Audit_Field -- ---------------------------------------- procedure Set_Id (Object : in out Audit_Field_Ref; Value : in Integer) is Impl : Audit_Field_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Key_Value (Impl.all, 1, ADO.Identifier (Value)); end Set_Id; function Get_Id (Object : in Audit_Field_Ref) return Integer is Impl : constant Audit_Field_Access := Audit_Field_Impl (Object.Get_Object.all)'Access; begin return Integer (ADO.Identifier '(Impl.Get_Key_Value)); end Get_Id; procedure Set_Name (Object : in out Audit_Field_Ref; Value : in String) is Impl : Audit_Field_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_String (Impl.all, 2, Impl.Name, Value); end Set_Name; procedure Set_Name (Object : in out Audit_Field_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String) is Impl : Audit_Field_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Unbounded_String (Impl.all, 2, Impl.Name, Value); end Set_Name; function Get_Name (Object : in Audit_Field_Ref) return String is begin return Ada.Strings.Unbounded.To_String (Object.Get_Name); end Get_Name; function Get_Name (Object : in Audit_Field_Ref) return Ada.Strings.Unbounded.Unbounded_String is Impl : constant Audit_Field_Access := Audit_Field_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Name; end Get_Name; procedure Set_Entity_Type (Object : in out Audit_Field_Ref; Value : in ADO.Entity_Type) is Impl : Audit_Field_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Entity_Type (Impl.all, 3, Impl.Entity_Type, Value); end Set_Entity_Type; function Get_Entity_Type (Object : in Audit_Field_Ref) return ADO.Entity_Type is Impl : constant Audit_Field_Access := Audit_Field_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Entity_Type; end Get_Entity_Type; -- Copy of the object. procedure Copy (Object : in Audit_Field_Ref; Into : in out Audit_Field_Ref) is Result : Audit_Field_Ref; begin if not Object.Is_Null then declare Impl : constant Audit_Field_Access := Audit_Field_Impl (Object.Get_Load_Object.all)'Access; Copy : constant Audit_Field_Access := new Audit_Field_Impl; begin ADO.Objects.Set_Object (Result, Copy.all'Access); Copy.Copy (Impl.all); Copy.Name := Impl.Name; Copy.Entity_Type := Impl.Entity_Type; end; end if; Into := Result; end Copy; procedure Find (Object : in out Audit_Field_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Impl : constant Audit_Field_Access := new Audit_Field_Impl; begin Impl.Find (Session, Query, Found); if Found then ADO.Objects.Set_Object (Object, Impl.all'Access); else ADO.Objects.Set_Object (Object, null); Destroy (Impl); end if; end Find; procedure Load (Object : in out Audit_Field_Ref; Session : in out ADO.Sessions.Session'Class; Id : in Integer) is Impl : constant Audit_Field_Access := new Audit_Field_Impl; Found : Boolean; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter ("id = ?"); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); raise ADO.Objects.NOT_FOUND; end if; ADO.Objects.Set_Object (Object, Impl.all'Access); end Load; procedure Load (Object : in out Audit_Field_Ref; Session : in out ADO.Sessions.Session'Class; Id : in Integer; Found : out Boolean) is Impl : constant Audit_Field_Access := new Audit_Field_Impl; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter ("id = ?"); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); else ADO.Objects.Set_Object (Object, Impl.all'Access); end if; end Load; procedure Save (Object : in out Audit_Field_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl = null then Impl := new Audit_Field_Impl; ADO.Objects.Set_Object (Object, Impl); end if; if not ADO.Objects.Is_Created (Impl.all) then Impl.Create (Session); else Impl.Save (Session); end if; end Save; procedure Delete (Object : in out Audit_Field_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : constant ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl /= null then Impl.Delete (Session); end if; end Delete; -- -------------------- -- Free the object -- -------------------- procedure Destroy (Object : access Audit_Field_Impl) is type Audit_Field_Impl_Ptr is access all Audit_Field_Impl; procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Audit_Field_Impl, Audit_Field_Impl_Ptr); pragma Warnings (Off, "*redundant conversion*"); Ptr : Audit_Field_Impl_Ptr := Audit_Field_Impl (Object.all)'Access; pragma Warnings (On, "*redundant conversion*"); begin Unchecked_Free (Ptr); end Destroy; procedure Find (Object : in out Audit_Field_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query, AUDIT_FIELD_DEF'Access); begin Stmt.Execute; if Stmt.Has_Elements then Object.Load (Stmt, Session); Stmt.Next; Found := not Stmt.Has_Elements; else Found := False; end if; end Find; overriding procedure Load (Object : in out Audit_Field_Impl; Session : in out ADO.Sessions.Session'Class) is Found : Boolean; Query : ADO.SQL.Query; Id : constant Integer := Integer (ADO.Identifier '(Object.Get_Key_Value)); begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter ("id = ?"); Object.Find (Session, Query, Found); if not Found then raise ADO.Objects.NOT_FOUND; end if; end Load; procedure Save (Object : in out Audit_Field_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Update_Statement := Session.Create_Statement (AUDIT_FIELD_DEF'Access); begin if Object.Is_Modified (1) then Stmt.Save_Field (Name => COL_0_2_NAME, -- id Value => Object.Get_Key); Object.Clear_Modified (1); end if; if Object.Is_Modified (2) then Stmt.Save_Field (Name => COL_1_2_NAME, -- name Value => Object.Name); Object.Clear_Modified (2); end if; if Object.Is_Modified (3) then Stmt.Save_Field (Name => COL_2_2_NAME, -- entity_type Value => Object.Entity_Type); Object.Clear_Modified (3); end if; if Stmt.Has_Save_Fields then Stmt.Set_Filter (Filter => "id = ?"); Stmt.Add_Param (Value => Object.Get_Key); declare Result : Integer; begin Stmt.Execute (Result); if Result /= 1 then if Result /= 0 then raise ADO.Objects.UPDATE_ERROR; end if; end if; end; end if; end Save; procedure Create (Object : in out Audit_Field_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Query : ADO.Statements.Insert_Statement := Session.Create_Statement (AUDIT_FIELD_DEF'Access); Result : Integer; begin Session.Allocate (Id => Object); Query.Save_Field (Name => COL_0_2_NAME, -- id Value => Object.Get_Key); Query.Save_Field (Name => COL_1_2_NAME, -- name Value => Object.Name); Query.Save_Field (Name => COL_2_2_NAME, -- entity_type Value => Object.Entity_Type); Query.Execute (Result); if Result /= 1 then raise ADO.Objects.INSERT_ERROR; end if; ADO.Objects.Set_Created (Object); end Create; procedure Delete (Object : in out Audit_Field_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Delete_Statement := Session.Create_Statement (AUDIT_FIELD_DEF'Access); begin Stmt.Set_Filter (Filter => "id = ?"); Stmt.Add_Param (Value => Object.Get_Key); Stmt.Execute; end Delete; -- ------------------------------ -- Get the bean attribute identified by the name. -- ------------------------------ overriding function Get_Value (From : in Audit_Field_Ref; Name : in String) return Util.Beans.Objects.Object is Obj : ADO.Objects.Object_Record_Access; Impl : access Audit_Field_Impl; begin if From.Is_Null then return Util.Beans.Objects.Null_Object; end if; Obj := From.Get_Load_Object; Impl := Audit_Field_Impl (Obj.all)'Access; if Name = "id" then return ADO.Objects.To_Object (Impl.Get_Key); elsif Name = "name" then return Util.Beans.Objects.To_Object (Impl.Name); elsif Name = "entity_type" then return Util.Beans.Objects.To_Object (Long_Long_Integer (Impl.Entity_Type)); end if; return Util.Beans.Objects.Null_Object; end Get_Value; -- ------------------------------ -- Load the object from current iterator position -- ------------------------------ procedure Load (Object : in out Audit_Field_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class) is begin Object.Set_Key_Value (Stmt.Get_Unbounded_String (0)); Object.Name := Stmt.Get_Unbounded_String (1); Object.Entity_Type := ADO.Entity_Type (Stmt.Get_Integer (2)); ADO.Objects.Set_Created (Object); end Load; end AWA.Audits.Models;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- P R J . N M S C -- -- -- -- B o d y -- -- -- -- $Revision$ -- -- -- Copyright (C) 2000-2001 Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, -- -- MA 02111-1307, USA. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Ada.Characters.Handling; use Ada.Characters.Handling; with Ada.Strings; use Ada.Strings; with Ada.Strings.Fixed; use Ada.Strings.Fixed; with Ada.Strings.Maps.Constants; use Ada.Strings.Maps.Constants; with Errout; use Errout; with GNAT.Case_Util; use GNAT.Case_Util; with GNAT.Directory_Operations; use GNAT.Directory_Operations; with GNAT.OS_Lib; use GNAT.OS_Lib; with MLib.Tgt; with Namet; use Namet; with Osint; use Osint; with Output; use Output; with Prj.Com; use Prj.Com; with Prj.Util; use Prj.Util; with Snames; use Snames; with Stringt; use Stringt; with Types; use Types; package body Prj.Nmsc is Dir_Sep : Character renames GNAT.OS_Lib.Directory_Separator; Error_Report : Put_Line_Access := null; procedure Check_Ada_Naming_Scheme (Naming : Naming_Data); -- Check that the package Naming is correct. procedure Check_Ada_Name (Name : Name_Id; Unit : out Name_Id); -- Check that a name is a valid Ada unit name. procedure Error_Msg (Msg : String; Flag_Location : Source_Ptr); -- Output an error message. If Error_Report is null, simply call -- Errout.Error_Msg. Otherwise, disregard Flag_Location and use -- Error_Report. function Get_Name_String (S : String_Id) return String; -- Get the string from a String_Id procedure Get_Unit (File_Name : Name_Id; Naming : Naming_Data; Unit_Name : out Name_Id; Unit_Kind : out Spec_Or_Body; Needs_Pragma : out Boolean); -- Find out, from a file name, the unit name, the unit kind and if a -- specific SFN pragma is needed. If the file name corresponds to no -- unit, then Unit_Name will be No_Name. function Is_Illegal_Append (This : String) return Boolean; -- Returns True if the string This cannot be used as -- a Specification_Append, a Body_Append or a Separate_Append. procedure Record_Source (File_Name : Name_Id; Path_Name : Name_Id; Project : Project_Id; Data : in out Project_Data; Location : Source_Ptr; Current_Source : in out String_List_Id); -- Put a unit in the list of units of a project, if the file name -- corresponds to a valid unit name. procedure Show_Source_Dirs (Project : Project_Id); -- List all the source directories of a project. function Locate_Directory (Name : Name_Id; Parent : Name_Id) return Name_Id; -- Locate a directory. -- Returns No_Name if directory does not exist. function Path_Name_Of (File_Name : String_Id; Directory : Name_Id) return String; -- Returns the path name of a (non project) file. -- Returns an empty string if file cannot be found. function Path_Name_Of (File_Name : String_Id; Directory : String_Id) return String; -- Same as above except that Directory is a String_Id instead -- of a Name_Id. --------------- -- Ada_Check -- --------------- procedure Ada_Check (Project : Project_Id; Report_Error : Put_Line_Access) is Data : Project_Data; Languages : Variable_Value := Nil_Variable_Value; procedure Check_Unit_Names (List : Array_Element_Id); -- Check that a list of unit names contains only valid names. procedure Find_Sources; -- Find all the sources in all of the source directories -- of a project. procedure Get_Path_Name_And_Record_Source (File_Name : String; Location : Source_Ptr; Current_Source : in out String_List_Id); -- Find the path name of a source in the source directories and -- record the source, if found. procedure Get_Sources_From_File (Path : String; Location : Source_Ptr); -- Get the sources of a project from a text file ---------------------- -- Check_Unit_Names -- ---------------------- procedure Check_Unit_Names (List : Array_Element_Id) is Current : Array_Element_Id := List; Element : Array_Element; Unit_Name : Name_Id; begin -- Loop through elements of the string list while Current /= No_Array_Element loop Element := Array_Elements.Table (Current); -- Check that it contains a valid unit name Check_Ada_Name (Element.Index, Unit_Name); if Unit_Name = No_Name then Error_Msg_Name_1 := Element.Index; Error_Msg ("{ is not a valid unit name.", Element.Value.Location); else if Current_Verbosity = High then Write_Str (" Body_Part ("""); Write_Str (Get_Name_String (Unit_Name)); Write_Line (""")"); end if; Element.Index := Unit_Name; Array_Elements.Table (Current) := Element; end if; Current := Element.Next; end loop; end Check_Unit_Names; ------------------ -- Find_Sources -- ------------------ procedure Find_Sources is Source_Dir : String_List_Id := Data.Source_Dirs; Element : String_Element; Dir : Dir_Type; Current_Source : String_List_Id := Nil_String; begin if Current_Verbosity = High then Write_Line ("Looking for sources:"); end if; -- For each subdirectory while Source_Dir /= Nil_String loop begin Element := String_Elements.Table (Source_Dir); if Element.Value /= No_String then declare Source_Directory : String (1 .. Integer (String_Length (Element.Value))); begin String_To_Name_Buffer (Element.Value); Source_Directory := Name_Buffer (1 .. Name_Len); if Current_Verbosity = High then Write_Str ("Source_Dir = "); Write_Line (Source_Directory); end if; -- We look to every entry in the source directory Open (Dir, Source_Directory); loop Read (Dir, Name_Buffer, Name_Len); if Current_Verbosity = High then Write_Str (" Checking "); Write_Line (Name_Buffer (1 .. Name_Len)); end if; exit when Name_Len = 0; declare Path_Access : constant GNAT.OS_Lib.String_Access := Locate_Regular_File (Name_Buffer (1 .. Name_Len), Source_Directory); File_Name : Name_Id; Path_Name : Name_Id; begin -- If it is a regular file if Path_Access /= null then File_Name := Name_Find; Name_Len := Path_Access'Length; Name_Buffer (1 .. Name_Len) := Path_Access.all; Path_Name := Name_Find; -- We attempt to register it as a source. -- However, there is no error if the file -- does not contain a valid source. -- But there is an error if we have a -- duplicate unit name. Record_Source (File_Name => File_Name, Path_Name => Path_Name, Project => Project, Data => Data, Location => No_Location, Current_Source => Current_Source); else if Current_Verbosity = High then Write_Line (" Not a regular file."); end if; end if; end; end loop; Close (Dir); end; end if; exception when Directory_Error => null; end; Source_Dir := Element.Next; end loop; if Current_Verbosity = High then Write_Line ("end Looking for sources."); end if; -- If we have looked for sources and found none, then -- it is an error. If a project is not supposed to contain -- any source, then we never call Find_Sources. if Current_Source = Nil_String then Error_Msg ("there are no sources in this project", Data.Location); end if; end Find_Sources; ------------------------------------- -- Get_Path_Name_And_Record_Source -- ------------------------------------- procedure Get_Path_Name_And_Record_Source (File_Name : String; Location : Source_Ptr; Current_Source : in out String_List_Id) is Source_Dir : String_List_Id := Data.Source_Dirs; Element : String_Element; Path_Name : GNAT.OS_Lib.String_Access; Found : Boolean := False; File : Name_Id; begin if Current_Verbosity = High then Write_Str (" Checking """); Write_Str (File_Name); Write_Line ("""."); end if; -- We look in all source directories for this file name while Source_Dir /= Nil_String loop Element := String_Elements.Table (Source_Dir); if Current_Verbosity = High then Write_Str (" """); Write_Str (Get_Name_String (Element.Value)); Write_Str (""": "); end if; Path_Name := Locate_Regular_File (File_Name, Get_Name_String (Element.Value)); if Path_Name /= null then if Current_Verbosity = High then Write_Line ("OK"); end if; Name_Len := File_Name'Length; Name_Buffer (1 .. Name_Len) := File_Name; File := Name_Find; Name_Len := Path_Name'Length; Name_Buffer (1 .. Name_Len) := Path_Name.all; -- Register the source. Report an error if the file does not -- correspond to a source. Record_Source (File_Name => File, Path_Name => Name_Find, Project => Project, Data => Data, Location => Location, Current_Source => Current_Source); Found := True; exit; else if Current_Verbosity = High then Write_Line ("No"); end if; Source_Dir := Element.Next; end if; end loop; end Get_Path_Name_And_Record_Source; --------------------------- -- Get_Sources_From_File -- --------------------------- procedure Get_Sources_From_File (Path : String; Location : Source_Ptr) is File : Prj.Util.Text_File; Line : String (1 .. 250); Last : Natural; Current_Source : String_List_Id := Nil_String; Nmb_Errors : constant Nat := Errors_Detected; begin if Current_Verbosity = High then Write_Str ("Opening """); Write_Str (Path); Write_Line ("""."); end if; -- We open the file Prj.Util.Open (File, Path); if not Prj.Util.Is_Valid (File) then Error_Msg ("file does not exist", Location); else while not Prj.Util.End_Of_File (File) loop Prj.Util.Get_Line (File, Line, Last); -- If the line is not empty and does not start with "--", -- then it must contains a file name. if Last /= 0 and then (Last = 1 or else Line (1 .. 2) /= "--") then Get_Path_Name_And_Record_Source (File_Name => Line (1 .. Last), Location => Location, Current_Source => Current_Source); exit when Nmb_Errors /= Errors_Detected; end if; end loop; Prj.Util.Close (File); end if; -- We should have found at least one source. -- If not, report an error. if Current_Source = Nil_String then Error_Msg ("this project has no source", Location); end if; end Get_Sources_From_File; -- Start of processing for Ada_Check begin Language_Independent_Check (Project, Report_Error); Error_Report := Report_Error; Data := Projects.Table (Project); Languages := Prj.Util.Value_Of (Name_Languages, Data.Decl.Attributes); Data.Naming.Current_Language := Name_Ada; Data.Sources_Present := Data.Source_Dirs /= Nil_String; if not Languages.Default then declare Current : String_List_Id := Languages.Values; Element : String_Element; Ada_Found : Boolean := False; begin Look_For_Ada : while Current /= Nil_String loop Element := String_Elements.Table (Current); String_To_Name_Buffer (Element.Value); To_Lower (Name_Buffer (1 .. Name_Len)); if Name_Buffer (1 .. Name_Len) = "ada" then Ada_Found := True; exit Look_For_Ada; end if; Current := Element.Next; end loop Look_For_Ada; if not Ada_Found then -- Mark the project file as having no sources for Ada Data.Sources_Present := False; end if; end; end if; declare Naming_Id : constant Package_Id := Util.Value_Of (Name_Naming, Data.Decl.Packages); Naming : Package_Element; begin -- If there is a package Naming, we will put in Data.Naming -- what is in this package Naming. if Naming_Id /= No_Package then Naming := Packages.Table (Naming_Id); if Current_Verbosity = High then Write_Line ("Checking ""Naming"" for Ada."); end if; declare Bodies : constant Array_Element_Id := Util.Value_Of (Name_Implementation, Naming.Decl.Arrays); Specifications : constant Array_Element_Id := Util.Value_Of (Name_Specification, Naming.Decl.Arrays); begin if Bodies /= No_Array_Element then -- We have elements in the array Body_Part if Current_Verbosity = High then Write_Line ("Found Bodies."); end if; Data.Naming.Bodies := Bodies; Check_Unit_Names (Bodies); else if Current_Verbosity = High then Write_Line ("No Bodies."); end if; end if; if Specifications /= No_Array_Element then -- We have elements in the array Specification if Current_Verbosity = High then Write_Line ("Found Specifications."); end if; Data.Naming.Specifications := Specifications; Check_Unit_Names (Specifications); else if Current_Verbosity = High then Write_Line ("No Specifications."); end if; end if; end; -- We are now checking if variables Dot_Replacement, Casing, -- Specification_Append, Body_Append and/or Separate_Append -- exist. -- For each variable, if it does not exist, we do nothing, -- because we already have the default. -- Check Dot_Replacement declare Dot_Replacement : constant Variable_Value := Util.Value_Of (Name_Dot_Replacement, Naming.Decl.Attributes); begin pragma Assert (Dot_Replacement.Kind = Single, "Dot_Replacement is not a single string"); if not Dot_Replacement.Default then String_To_Name_Buffer (Dot_Replacement.Value); if Name_Len = 0 then Error_Msg ("Dot_Replacement cannot be empty", Dot_Replacement.Location); else Canonical_Case_File_Name (Name_Buffer (1 .. Name_Len)); Data.Naming.Dot_Replacement := Name_Find; Data.Naming.Dot_Repl_Loc := Dot_Replacement.Location; end if; end if; end; if Current_Verbosity = High then Write_Str (" Dot_Replacement = """); Write_Str (Get_Name_String (Data.Naming.Dot_Replacement)); Write_Char ('"'); Write_Eol; end if; -- Check Casing declare Casing_String : constant Variable_Value := Util.Value_Of (Name_Casing, Naming.Decl.Attributes); begin pragma Assert (Casing_String.Kind = Single, "Casing is not a single string"); if not Casing_String.Default then declare Casing_Image : constant String := Get_Name_String (Casing_String.Value); begin declare Casing : constant Casing_Type := Value (Casing_Image); begin Data.Naming.Casing := Casing; end; exception when Constraint_Error => if Casing_Image'Length = 0 then Error_Msg ("Casing cannot be an empty string", Casing_String.Location); else Name_Len := Casing_Image'Length; Name_Buffer (1 .. Name_Len) := Casing_Image; Error_Msg_Name_1 := Name_Find; Error_Msg ("{ is not a correct Casing", Casing_String.Location); end if; end; end if; end; if Current_Verbosity = High then Write_Str (" Casing = "); Write_Str (Image (Data.Naming.Casing)); Write_Char ('.'); Write_Eol; end if; -- Check Specification_Suffix declare Ada_Spec_Suffix : constant Variable_Value := Prj.Util.Value_Of (Index => Name_Ada, In_Array => Data.Naming.Specification_Suffix); begin if Ada_Spec_Suffix.Kind = Single and then String_Length (Ada_Spec_Suffix.Value) /= 0 then String_To_Name_Buffer (Ada_Spec_Suffix.Value); Data.Naming.Current_Spec_Suffix := Name_Find; Data.Naming.Spec_Suffix_Loc := Ada_Spec_Suffix.Location; else Data.Naming.Current_Spec_Suffix := Default_Ada_Spec_Suffix; end if; end; if Current_Verbosity = High then Write_Str (" Specification_Suffix = """); Write_Str (Get_Name_String (Data.Naming.Current_Spec_Suffix)); Write_Char ('"'); Write_Eol; end if; -- Check Implementation_Suffix declare Ada_Impl_Suffix : constant Variable_Value := Prj.Util.Value_Of (Index => Name_Ada, In_Array => Data.Naming.Implementation_Suffix); begin if Ada_Impl_Suffix.Kind = Single and then String_Length (Ada_Impl_Suffix.Value) /= 0 then String_To_Name_Buffer (Ada_Impl_Suffix.Value); Data.Naming.Current_Impl_Suffix := Name_Find; Data.Naming.Impl_Suffix_Loc := Ada_Impl_Suffix.Location; else Data.Naming.Current_Impl_Suffix := Default_Ada_Impl_Suffix; end if; end; if Current_Verbosity = High then Write_Str (" Implementation_Suffix = """); Write_Str (Get_Name_String (Data.Naming.Current_Impl_Suffix)); Write_Char ('"'); Write_Eol; end if; -- Check Separate_Suffix declare Ada_Sep_Suffix : constant Variable_Value := Prj.Util.Value_Of (Variable_Name => Name_Separate_Suffix, In_Variables => Naming.Decl.Attributes); begin if Ada_Sep_Suffix.Default then Data.Naming.Separate_Suffix := Data.Naming.Current_Impl_Suffix; else String_To_Name_Buffer (Ada_Sep_Suffix.Value); if Name_Len = 0 then Error_Msg ("Separate_Suffix cannot be empty", Ada_Sep_Suffix.Location); else Data.Naming.Separate_Suffix := Name_Find; Data.Naming.Sep_Suffix_Loc := Ada_Sep_Suffix.Location; end if; end if; end; if Current_Verbosity = High then Write_Str (" Separate_Suffix = """); Write_Str (Get_Name_String (Data.Naming.Separate_Suffix)); Write_Char ('"'); Write_Eol; end if; -- Check if Data.Naming is valid Check_Ada_Naming_Scheme (Data.Naming); else Data.Naming.Current_Spec_Suffix := Default_Ada_Spec_Suffix; Data.Naming.Current_Impl_Suffix := Default_Ada_Impl_Suffix; Data.Naming.Separate_Suffix := Default_Ada_Impl_Suffix; end if; end; -- If we have source directories, then find the sources if Data.Sources_Present then if Data.Source_Dirs = Nil_String then Data.Sources_Present := False; else declare Sources : constant Variable_Value := Util.Value_Of (Name_Source_Files, Data.Decl.Attributes); Source_List_File : constant Variable_Value := Util.Value_Of (Name_Source_List_File, Data.Decl.Attributes); begin pragma Assert (Sources.Kind = List, "Source_Files is not a list"); pragma Assert (Source_List_File.Kind = Single, "Source_List_File is not a single string"); if not Sources.Default then if not Source_List_File.Default then Error_Msg ("?both variables source_files and " & "source_list_file are present", Source_List_File.Location); end if; -- Sources is a list of file names declare Current_Source : String_List_Id := Nil_String; Current : String_List_Id := Sources.Values; Element : String_Element; begin Data.Sources_Present := Current /= Nil_String; while Current /= Nil_String loop Element := String_Elements.Table (Current); String_To_Name_Buffer (Element.Value); declare File_Name : constant String := Name_Buffer (1 .. Name_Len); begin Get_Path_Name_And_Record_Source (File_Name => File_Name, Location => Element.Location, Current_Source => Current_Source); Current := Element.Next; end; end loop; end; -- No source_files specified. -- We check Source_List_File has been specified. elsif not Source_List_File.Default then -- Source_List_File is the name of the file -- that contains the source file names declare Source_File_Path_Name : constant String := Path_Name_Of (Source_List_File.Value, Data.Directory); begin if Source_File_Path_Name'Length = 0 then String_To_Name_Buffer (Source_List_File.Value); Error_Msg_Name_1 := Name_Find; Error_Msg ("file with sources { does not exist", Source_List_File.Location); else Get_Sources_From_File (Source_File_Path_Name, Source_List_File.Location); end if; end; else -- Neither Source_Files nor Source_List_File has been -- specified. -- Find all the files that satisfy -- the naming scheme in all the source directories. Find_Sources; end if; end; end if; end if; Projects.Table (Project) := Data; end Ada_Check; -------------------- -- Check_Ada_Name -- -------------------- procedure Check_Ada_Name (Name : Name_Id; Unit : out Name_Id) is The_Name : String := Get_Name_String (Name); Need_Letter : Boolean := True; Last_Underscore : Boolean := False; OK : Boolean := The_Name'Length > 0; begin for Index in The_Name'Range loop if Need_Letter then -- We need a letter (at the beginning, and following a dot), -- but we don't have one. if Is_Letter (The_Name (Index)) then Need_Letter := False; else OK := False; if Current_Verbosity = High then Write_Int (Types.Int (Index)); Write_Str (": '"); Write_Char (The_Name (Index)); Write_Line ("' is not a letter."); end if; exit; end if; elsif Last_Underscore and then (The_Name (Index) = '_' or else The_Name (Index) = '.') then -- Two underscores are illegal, and a dot cannot follow -- an underscore. OK := False; if Current_Verbosity = High then Write_Int (Types.Int (Index)); Write_Str (": '"); Write_Char (The_Name (Index)); Write_Line ("' is illegal here."); end if; exit; elsif The_Name (Index) = '.' then -- We need a letter after a dot Need_Letter := True; elsif The_Name (Index) = '_' then Last_Underscore := True; else -- We need an letter or a digit Last_Underscore := False; if not Is_Alphanumeric (The_Name (Index)) then OK := False; if Current_Verbosity = High then Write_Int (Types.Int (Index)); Write_Str (": '"); Write_Char (The_Name (Index)); Write_Line ("' is not alphanumeric."); end if; exit; end if; end if; end loop; -- Cannot end with an underscore or a dot OK := OK and then not Need_Letter and then not Last_Underscore; if OK then Unit := Name; else -- Signal a problem with No_Name Unit := No_Name; end if; end Check_Ada_Name; ----------------------------- -- Check_Ada_Naming_Scheme -- ----------------------------- procedure Check_Ada_Naming_Scheme (Naming : Naming_Data) is begin -- Only check if we are not using the standard naming scheme if Naming /= Standard_Naming_Data then declare Dot_Replacement : constant String := Get_Name_String (Naming.Dot_Replacement); Specification_Suffix : constant String := Get_Name_String (Naming.Current_Spec_Suffix); Implementation_Suffix : constant String := Get_Name_String (Naming.Current_Impl_Suffix); Separate_Suffix : constant String := Get_Name_String (Naming.Separate_Suffix); begin -- Dot_Replacement cannot -- - be empty -- - start or end with an alphanumeric -- - be a single '_' -- - start with an '_' followed by an alphanumeric -- - contain a '.' except if it is "." if Dot_Replacement'Length = 0 or else Is_Alphanumeric (Dot_Replacement (Dot_Replacement'First)) or else Is_Alphanumeric (Dot_Replacement (Dot_Replacement'Last)) or else (Dot_Replacement (Dot_Replacement'First) = '_' and then (Dot_Replacement'Length = 1 or else Is_Alphanumeric (Dot_Replacement (Dot_Replacement'First + 1)))) or else (Dot_Replacement'Length > 1 and then Index (Source => Dot_Replacement, Pattern => ".") /= 0) then Error_Msg ('"' & Dot_Replacement & """ is illegal for Dot_Replacement.", Naming.Dot_Repl_Loc); end if; -- Suffixes cannot -- - be empty -- - start with an alphanumeric -- - start with an '_' followed by an alphanumeric if Is_Illegal_Append (Specification_Suffix) then Error_Msg_Name_1 := Naming.Current_Spec_Suffix; Error_Msg ("{ is illegal for Specification_Suffix", Naming.Spec_Suffix_Loc); end if; if Is_Illegal_Append (Implementation_Suffix) then Error_Msg_Name_1 := Naming.Current_Impl_Suffix; Error_Msg ("% is illegal for Implementation_Suffix", Naming.Impl_Suffix_Loc); end if; if Implementation_Suffix /= Separate_Suffix then if Is_Illegal_Append (Separate_Suffix) then Error_Msg_Name_1 := Naming.Separate_Suffix; Error_Msg ("{ is illegal for Separate_Append", Naming.Sep_Suffix_Loc); end if; end if; -- Specification_Suffix cannot have the same termination as -- Implementation_Suffix or Separate_Suffix if Specification_Suffix'Length <= Implementation_Suffix'Length and then Implementation_Suffix (Implementation_Suffix'Last - Specification_Suffix'Length + 1 .. Implementation_Suffix'Last) = Specification_Suffix then Error_Msg ("Implementation_Suffix (""" & Implementation_Suffix & """) cannot end with" & "Specification_Suffix (""" & Specification_Suffix & """).", Naming.Impl_Suffix_Loc); end if; if Specification_Suffix'Length <= Separate_Suffix'Length and then Separate_Suffix (Separate_Suffix'Last - Specification_Suffix'Length + 1 .. Separate_Suffix'Last) = Specification_Suffix then Error_Msg ("Separate_Suffix (""" & Separate_Suffix & """) cannot end with" & " Specification_Suffix (""" & Specification_Suffix & """).", Naming.Sep_Suffix_Loc); end if; end; end if; end Check_Ada_Naming_Scheme; --------------- -- Error_Msg -- --------------- procedure Error_Msg (Msg : String; Flag_Location : Source_Ptr) is Error_Buffer : String (1 .. 5_000); Error_Last : Natural := 0; Msg_Name : Natural := 0; First : Positive := Msg'First; procedure Add (C : Character); -- Add a character to the buffer procedure Add (S : String); -- Add a string to the buffer procedure Add (Id : Name_Id); -- Add a name to the buffer --------- -- Add -- --------- procedure Add (C : Character) is begin Error_Last := Error_Last + 1; Error_Buffer (Error_Last) := C; end Add; procedure Add (S : String) is begin Error_Buffer (Error_Last + 1 .. Error_Last + S'Length) := S; Error_Last := Error_Last + S'Length; end Add; procedure Add (Id : Name_Id) is begin Get_Name_String (Id); Add (Name_Buffer (1 .. Name_Len)); end Add; -- Start of processing for Error_Msg begin if Error_Report = null then Errout.Error_Msg (Msg, Flag_Location); return; end if; if Msg (First) = '\' then -- Continuation character, ignore. First := First + 1; elsif Msg (First) = '?' then -- Warning character. It is always the first one, -- in this package. First := First + 1; Add ("Warning: "); end if; for Index in First .. Msg'Last loop if Msg (Index) = '{' or else Msg (Index) = '%' then -- Include a name between double quotes. Msg_Name := Msg_Name + 1; Add ('"'); case Msg_Name is when 1 => Add (Error_Msg_Name_1); when 2 => Add (Error_Msg_Name_2); when 3 => Add (Error_Msg_Name_3); when others => null; end case; Add ('"'); else Add (Msg (Index)); end if; end loop; Error_Report (Error_Buffer (1 .. Error_Last)); end Error_Msg; --------------------- -- Get_Name_String -- --------------------- function Get_Name_String (S : String_Id) return String is begin if S = No_String then return ""; else String_To_Name_Buffer (S); return Name_Buffer (1 .. Name_Len); end if; end Get_Name_String; -------------- -- Get_Unit -- -------------- procedure Get_Unit (File_Name : Name_Id; Naming : Naming_Data; Unit_Name : out Name_Id; Unit_Kind : out Spec_Or_Body; Needs_Pragma : out Boolean) is Canonical_Case_Name : Name_Id; begin Needs_Pragma := False; Get_Name_String (File_Name); Canonical_Case_File_Name (Name_Buffer (1 .. Name_Len)); Canonical_Case_Name := Name_Find; if Naming.Bodies /= No_Array_Element then -- There are some specified file names for some bodies -- of this project. Find out if File_Name is one of these bodies. declare Current : Array_Element_Id := Naming.Bodies; Element : Array_Element; begin while Current /= No_Array_Element loop Element := Array_Elements.Table (Current); if Element.Index /= No_Name then String_To_Name_Buffer (Element.Value.Value); Canonical_Case_File_Name (Name_Buffer (1 .. Name_Len)); if Canonical_Case_Name = Name_Find then -- File_Name corresponds to one body. -- So, we know it is a body, and we know the unit name. Unit_Kind := Body_Part; Unit_Name := Element.Index; Needs_Pragma := True; return; end if; end if; Current := Element.Next; end loop; end; end if; if Naming.Specifications /= No_Array_Element then -- There are some specified file names for some bodiesspecifications -- of this project. Find out if File_Name is one of these -- specifications. declare Current : Array_Element_Id := Naming.Specifications; Element : Array_Element; begin while Current /= No_Array_Element loop Element := Array_Elements.Table (Current); if Element.Index /= No_Name then String_To_Name_Buffer (Element.Value.Value); Canonical_Case_File_Name (Name_Buffer (1 .. Name_Len)); if Canonical_Case_Name = Name_Find then -- File_Name corresponds to one specification. -- So, we know it is a spec, and we know the unit name. Unit_Kind := Specification; Unit_Name := Element.Index; Needs_Pragma := True; return; end if; end if; Current := Element.Next; end loop; end; end if; declare File : String := Get_Name_String (Canonical_Case_Name); First : Positive := File'First; Last : Natural := File'Last; begin -- Check if the end of the file name is Specification_Append Get_Name_String (Naming.Current_Spec_Suffix); if File'Length > Name_Len and then File (Last - Name_Len + 1 .. Last) = Name_Buffer (1 .. Name_Len) then -- We have a spec Unit_Kind := Specification; Last := Last - Name_Len; if Current_Verbosity = High then Write_Str (" Specification: "); Write_Line (File (First .. Last)); end if; else Get_Name_String (Naming.Current_Impl_Suffix); -- Check if the end of the file name is Body_Append if File'Length > Name_Len and then File (Last - Name_Len + 1 .. Last) = Name_Buffer (1 .. Name_Len) then -- We have a body Unit_Kind := Body_Part; Last := Last - Name_Len; if Current_Verbosity = High then Write_Str (" Body: "); Write_Line (File (First .. Last)); end if; elsif Naming.Separate_Suffix /= Naming.Current_Spec_Suffix then Get_Name_String (Naming.Separate_Suffix); -- Check if the end of the file name is Separate_Append if File'Length > Name_Len and then File (Last - Name_Len + 1 .. Last) = Name_Buffer (1 .. Name_Len) then -- We have a separate (a body) Unit_Kind := Body_Part; Last := Last - Name_Len; if Current_Verbosity = High then Write_Str (" Separate: "); Write_Line (File (First .. Last)); end if; else Last := 0; end if; else Last := 0; end if; end if; if Last = 0 then -- This is not a source file Unit_Name := No_Name; Unit_Kind := Specification; if Current_Verbosity = High then Write_Line (" Not a valid file name."); end if; return; end if; Get_Name_String (Naming.Dot_Replacement); if Name_Buffer (1 .. Name_Len) /= "." then -- If Dot_Replacement is not a single dot, -- then there should not be any dot in the name. for Index in First .. Last loop if File (Index) = '.' then if Current_Verbosity = High then Write_Line (" Not a valid file name (some dot not replaced)."); end if; Unit_Name := No_Name; return; end if; end loop; -- Replace the substring Dot_Replacement with dots declare Index : Positive := First; begin while Index <= Last - Name_Len + 1 loop if File (Index .. Index + Name_Len - 1) = Name_Buffer (1 .. Name_Len) then File (Index) := '.'; if Name_Len > 1 and then Index < Last then File (Index + 1 .. Last - Name_Len + 1) := File (Index + Name_Len .. Last); end if; Last := Last - Name_Len + 1; end if; Index := Index + 1; end loop; end; end if; -- Check if the casing is right declare Src : String := File (First .. Last); begin case Naming.Casing is when All_Lower_Case => Fixed.Translate (Source => Src, Mapping => Lower_Case_Map); when All_Upper_Case => Fixed.Translate (Source => Src, Mapping => Upper_Case_Map); when Mixed_Case | Unknown => null; end case; if Src /= File (First .. Last) then if Current_Verbosity = High then Write_Line (" Not a valid file name (casing)."); end if; Unit_Name := No_Name; return; end if; -- We put the name in lower case Fixed.Translate (Source => Src, Mapping => Lower_Case_Map); if Current_Verbosity = High then Write_Str (" "); Write_Line (Src); end if; Name_Len := Src'Length; Name_Buffer (1 .. Name_Len) := Src; -- Now, we check if this name is a valid unit name Check_Ada_Name (Name => Name_Find, Unit => Unit_Name); end; end; end Get_Unit; ----------------------- -- Is_Illegal_Append -- ----------------------- function Is_Illegal_Append (This : String) return Boolean is begin return This'Length = 0 or else Is_Alphanumeric (This (This'First)) or else Index (This, ".") = 0 or else (This'Length >= 2 and then This (This'First) = '_' and then Is_Alphanumeric (This (This'First + 1))); end Is_Illegal_Append; -------------------------------- -- Language_Independent_Check -- -------------------------------- procedure Language_Independent_Check (Project : Project_Id; Report_Error : Put_Line_Access) is Last_Source_Dir : String_List_Id := Nil_String; Data : Project_Data := Projects.Table (Project); procedure Find_Source_Dirs (From : String_Id; Location : Source_Ptr); -- Find one or several source directories, and add them -- to the list of source directories of the project. ---------------------- -- Find_Source_Dirs -- ---------------------- procedure Find_Source_Dirs (From : String_Id; Location : Source_Ptr) is Directory : String (1 .. Integer (String_Length (From))); Directory_Id : Name_Id; Element : String_Element; procedure Recursive_Find_Dirs (Path : String_Id); -- Find all the subdirectories (recursively) of Path -- and add them to the list of source directories -- of the project. ------------------------- -- Recursive_Find_Dirs -- ------------------------- procedure Recursive_Find_Dirs (Path : String_Id) is Dir : Dir_Type; Name : String (1 .. 250); Last : Natural; The_Path : String := Get_Name_String (Path) & Dir_Sep; The_Path_Last : Positive := The_Path'Last; begin if The_Path'Length > 1 and then (The_Path (The_Path_Last - 1) = Dir_Sep or else The_Path (The_Path_Last - 1) = '/') then The_Path_Last := The_Path_Last - 1; end if; if Current_Verbosity = High then Write_Str (" "); Write_Line (The_Path (The_Path'First .. The_Path_Last)); end if; String_Elements.Increment_Last; Element := (Value => Path, Location => No_Location, Next => Nil_String); -- Case of first source directory if Last_Source_Dir = Nil_String then Data.Source_Dirs := String_Elements.Last; -- Here we already have source directories. else -- Link the previous last to the new one String_Elements.Table (Last_Source_Dir).Next := String_Elements.Last; end if; -- And register this source directory as the new last Last_Source_Dir := String_Elements.Last; String_Elements.Table (Last_Source_Dir) := Element; -- Now look for subdirectories Open (Dir, The_Path (The_Path'First .. The_Path_Last)); loop Read (Dir, Name, Last); exit when Last = 0; if Current_Verbosity = High then Write_Str (" Checking "); Write_Line (Name (1 .. Last)); end if; if Name (1 .. Last) /= "." and then Name (1 .. Last) /= ".." then -- Avoid . and .. declare Path_Name : constant String := The_Path (The_Path'First .. The_Path_Last) & Name (1 .. Last); begin if Is_Directory (Path_Name) then -- We have found a new subdirectory, -- register it and find its own subdirectories. Start_String; Store_String_Chars (Path_Name); Recursive_Find_Dirs (End_String); end if; end; end if; end loop; Close (Dir); exception when Directory_Error => null; end Recursive_Find_Dirs; -- Start of processing for Find_Source_Dirs begin if Current_Verbosity = High then Write_Str ("Find_Source_Dirs ("""); end if; String_To_Name_Buffer (From); Directory := Name_Buffer (1 .. Name_Len); Directory_Id := Name_Find; if Current_Verbosity = High then Write_Str (Directory); Write_Line (""")"); end if; -- First, check if we are looking for a directory tree, -- indicated by "/**" at the end. if Directory'Length >= 3 and then Directory (Directory'Last - 1 .. Directory'Last) = "**" and then (Directory (Directory'Last - 2) = '/' or else Directory (Directory'Last - 2) = Dir_Sep) then Name_Len := Directory'Length - 3; if Name_Len = 0 then -- This is the case of "/**": all directories -- in the file system. Name_Len := 1; Name_Buffer (1) := Directory (Directory'First); else Name_Buffer (1 .. Name_Len) := Directory (Directory'First .. Directory'Last - 3); end if; if Current_Verbosity = High then Write_Str ("Looking for all subdirectories of """); Write_Str (Name_Buffer (1 .. Name_Len)); Write_Line (""""); end if; declare Base_Dir : constant Name_Id := Name_Find; Root : constant Name_Id := Locate_Directory (Base_Dir, Data.Directory); begin if Root = No_Name then Error_Msg_Name_1 := Base_Dir; if Location = No_Location then Error_Msg ("{ is not a valid directory.", Data.Location); else Error_Msg ("{ is not a valid directory.", Location); end if; else -- We have an existing directory, -- we register it and all of its subdirectories. if Current_Verbosity = High then Write_Line ("Looking for source directories:"); end if; Start_String; Store_String_Chars (Get_Name_String (Root)); Recursive_Find_Dirs (End_String); if Current_Verbosity = High then Write_Line ("End of looking for source directories."); end if; end if; end; -- We have a single directory else declare Path_Name : constant Name_Id := Locate_Directory (Directory_Id, Data.Directory); begin if Path_Name = No_Name then Error_Msg_Name_1 := Directory_Id; if Location = No_Location then Error_Msg ("{ is not a valid directory", Data.Location); else Error_Msg ("{ is not a valid directory", Location); end if; else -- As it is an existing directory, we add it to -- the list of directories. String_Elements.Increment_Last; Start_String; Store_String_Chars (Get_Name_String (Path_Name)); Element.Value := End_String; if Last_Source_Dir = Nil_String then -- This is the first source directory Data.Source_Dirs := String_Elements.Last; else -- We already have source directories, -- link the previous last to the new one. String_Elements.Table (Last_Source_Dir).Next := String_Elements.Last; end if; -- And register this source directory as the new last Last_Source_Dir := String_Elements.Last; String_Elements.Table (Last_Source_Dir) := Element; end if; end; end if; end Find_Source_Dirs; -- Start of processing for Language_Independent_Check begin if Data.Language_Independent_Checked then return; end if; Data.Language_Independent_Checked := True; Error_Report := Report_Error; if Current_Verbosity = High then Write_Line ("Starting to look for directories"); end if; -- Check the object directory declare Object_Dir : Variable_Value := Util.Value_Of (Name_Object_Dir, Data.Decl.Attributes); begin pragma Assert (Object_Dir.Kind = Single, "Object_Dir is not a single string"); -- We set the object directory to its default Data.Object_Directory := Data.Directory; if not String_Equal (Object_Dir.Value, Empty_String) then String_To_Name_Buffer (Object_Dir.Value); if Name_Len = 0 then Error_Msg ("Object_Dir cannot be empty", Object_Dir.Location); else -- We check that the specified object directory -- does exist. Canonical_Case_File_Name (Name_Buffer (1 .. Name_Len)); declare Dir_Id : constant Name_Id := Name_Find; begin Data.Object_Directory := Locate_Directory (Dir_Id, Data.Directory); if Data.Object_Directory = No_Name then Error_Msg_Name_1 := Dir_Id; Error_Msg ("the object directory { cannot be found", Data.Location); end if; end; end if; end if; end; if Current_Verbosity = High then if Data.Object_Directory = No_Name then Write_Line ("No object directory"); else Write_Str ("Object directory: """); Write_Str (Get_Name_String (Data.Object_Directory)); Write_Line (""""); end if; end if; -- Check the exec directory declare Exec_Dir : Variable_Value := Util.Value_Of (Name_Exec_Dir, Data.Decl.Attributes); begin pragma Assert (Exec_Dir.Kind = Single, "Exec_Dir is not a single string"); -- We set the object directory to its default Data.Exec_Directory := Data.Object_Directory; if not String_Equal (Exec_Dir.Value, Empty_String) then String_To_Name_Buffer (Exec_Dir.Value); if Name_Len = 0 then Error_Msg ("Exec_Dir cannot be empty", Exec_Dir.Location); else -- We check that the specified object directory -- does exist. Canonical_Case_File_Name (Name_Buffer (1 .. Name_Len)); declare Dir_Id : constant Name_Id := Name_Find; begin Data.Exec_Directory := Locate_Directory (Dir_Id, Data.Directory); if Data.Exec_Directory = No_Name then Error_Msg_Name_1 := Dir_Id; Error_Msg ("the exec directory { cannot be found", Data.Location); end if; end; end if; end if; end; if Current_Verbosity = High then if Data.Exec_Directory = No_Name then Write_Line ("No exec directory"); else Write_Str ("Exec directory: """); Write_Str (Get_Name_String (Data.Exec_Directory)); Write_Line (""""); end if; end if; -- Look for the source directories declare Source_Dirs : Variable_Value := Util.Value_Of (Name_Source_Dirs, Data.Decl.Attributes); begin if Current_Verbosity = High then Write_Line ("Starting to look for source directories"); end if; pragma Assert (Source_Dirs.Kind = List, "Source_Dirs is not a list"); if Source_Dirs.Default then -- No Source_Dirs specified: the single source directory -- is the one containing the project file String_Elements.Increment_Last; Data.Source_Dirs := String_Elements.Last; Start_String; Store_String_Chars (Get_Name_String (Data.Directory)); String_Elements.Table (Data.Source_Dirs) := (Value => End_String, Location => No_Location, Next => Nil_String); if Current_Verbosity = High then Write_Line ("(Undefined) Single object directory:"); Write_Str (" """); Write_Str (Get_Name_String (Data.Directory)); Write_Line (""""); end if; elsif Source_Dirs.Values = Nil_String then -- If Source_Dirs is an empty string list, this means -- that this project contains no source. if Data.Object_Directory = Data.Directory then Data.Object_Directory := No_Name; end if; Data.Source_Dirs := Nil_String; Data.Sources_Present := False; else declare Source_Dir : String_List_Id := Source_Dirs.Values; Element : String_Element; begin -- We will find the source directories for each -- element of the list while Source_Dir /= Nil_String loop Element := String_Elements.Table (Source_Dir); Find_Source_Dirs (Element.Value, Element.Location); Source_Dir := Element.Next; end loop; end; end if; if Current_Verbosity = High then Write_Line ("Puting source directories in canonical cases"); end if; declare Current : String_List_Id := Data.Source_Dirs; Element : String_Element; begin while Current /= Nil_String loop Element := String_Elements.Table (Current); if Element.Value /= No_String then String_To_Name_Buffer (Element.Value); Canonical_Case_File_Name (Name_Buffer (1 .. Name_Len)); Start_String; Store_String_Chars (Name_Buffer (1 .. Name_Len)); Element.Value := End_String; String_Elements.Table (Current) := Element; end if; Current := Element.Next; end loop; end; end; -- Library Dir, Name, Version and Kind declare Attributes : constant Prj.Variable_Id := Data.Decl.Attributes; Lib_Dir : Prj.Variable_Value := Prj.Util.Value_Of (Snames.Name_Library_Dir, Attributes); Lib_Name : Prj.Variable_Value := Prj.Util.Value_Of (Snames.Name_Library_Name, Attributes); Lib_Version : Prj.Variable_Value := Prj.Util.Value_Of (Snames.Name_Library_Version, Attributes); The_Lib_Kind : Prj.Variable_Value := Prj.Util.Value_Of (Snames.Name_Library_Kind, Attributes); begin pragma Assert (Lib_Dir.Kind = Single); if Lib_Dir.Value = Empty_String then if Current_Verbosity = High then Write_Line ("No library directory"); end if; else -- Find path name, check that it is a directory Stringt.String_To_Name_Buffer (Lib_Dir.Value); declare Dir_Id : constant Name_Id := Name_Find; begin Data.Library_Dir := Locate_Directory (Dir_Id, Data.Directory); if Data.Library_Dir = No_Name then Error_Msg ("not an existing directory", Lib_Dir.Location); elsif Data.Library_Dir = Data.Object_Directory then Error_Msg ("library directory cannot be the same " & "as object directory", Lib_Dir.Location); Data.Library_Dir := No_Name; else if Current_Verbosity = High then Write_Str ("Library directory ="""); Write_Str (Get_Name_String (Data.Library_Dir)); Write_Line (""""); end if; end if; end; end if; pragma Assert (Lib_Name.Kind = Single); if Lib_Name.Value = Empty_String then if Current_Verbosity = High then Write_Line ("No library name"); end if; else Stringt.String_To_Name_Buffer (Lib_Name.Value); if not Is_Letter (Name_Buffer (1)) then Error_Msg ("must start with a letter", Lib_Name.Location); else Data.Library_Name := Name_Find; for Index in 2 .. Name_Len loop if not Is_Alphanumeric (Name_Buffer (Index)) then Data.Library_Name := No_Name; Error_Msg ("only letters and digits are allowed", Lib_Name.Location); exit; end if; end loop; if Data.Library_Name /= No_Name and then Current_Verbosity = High then Write_Str ("Library name = """); Write_Str (Get_Name_String (Data.Library_Name)); Write_Line (""""); end if; end if; end if; Data.Library := Data.Library_Dir /= No_Name and then Data.Library_Name /= No_Name; if Data.Library then if not MLib.Tgt.Libraries_Are_Supported then Error_Msg ("?libraries are not supported on this platform", Lib_Name.Location); Data.Library := False; else if Current_Verbosity = High then Write_Line ("This is a library project file"); end if; pragma Assert (Lib_Version.Kind = Single); if Lib_Version.Value = Empty_String then if Current_Verbosity = High then Write_Line ("No library version specified"); end if; else Stringt.String_To_Name_Buffer (Lib_Version.Value); Data.Lib_Internal_Name := Name_Find; end if; pragma Assert (The_Lib_Kind.Kind = Single); if The_Lib_Kind.Value = Empty_String then if Current_Verbosity = High then Write_Line ("No library kind specified"); end if; else Stringt.String_To_Name_Buffer (The_Lib_Kind.Value); declare Kind_Name : constant String := To_Lower (Name_Buffer (1 .. Name_Len)); OK : Boolean := True; begin if Kind_Name = "static" then Data.Library_Kind := Static; elsif Kind_Name = "dynamic" then Data.Library_Kind := Dynamic; elsif Kind_Name = "relocatable" then Data.Library_Kind := Relocatable; else Error_Msg ("illegal value for Library_Kind", The_Lib_Kind.Location); OK := False; end if; if Current_Verbosity = High and then OK then Write_Str ("Library kind = "); Write_Line (Kind_Name); end if; end; end if; end if; end if; end; if Current_Verbosity = High then Show_Source_Dirs (Project); end if; declare Naming_Id : constant Package_Id := Util.Value_Of (Name_Naming, Data.Decl.Packages); Naming : Package_Element; begin -- If there is a package Naming, we will put in Data.Naming -- what is in this package Naming. if Naming_Id /= No_Package then Naming := Packages.Table (Naming_Id); if Current_Verbosity = High then Write_Line ("Checking ""Naming""."); end if; -- Check Specification_Suffix Data.Naming.Specification_Suffix := Util.Value_Of (Name_Specification_Suffix, Naming.Decl.Arrays); declare Current : Array_Element_Id := Data.Naming.Specification_Suffix; Element : Array_Element; begin while Current /= No_Array_Element loop Element := Array_Elements.Table (Current); String_To_Name_Buffer (Element.Value.Value); if Name_Len = 0 then Error_Msg ("Specification_Suffix cannot be empty", Element.Value.Location); end if; Array_Elements.Table (Current) := Element; Current := Element.Next; end loop; end; -- Check Implementation_Suffix Data.Naming.Implementation_Suffix := Util.Value_Of (Name_Implementation_Suffix, Naming.Decl.Arrays); declare Current : Array_Element_Id := Data.Naming.Implementation_Suffix; Element : Array_Element; begin while Current /= No_Array_Element loop Element := Array_Elements.Table (Current); String_To_Name_Buffer (Element.Value.Value); if Name_Len = 0 then Error_Msg ("Implementation_Suffix cannot be empty", Element.Value.Location); end if; Array_Elements.Table (Current) := Element; Current := Element.Next; end loop; end; end if; end; Projects.Table (Project) := Data; end Language_Independent_Check; ---------------------- -- Locate_Directory -- ---------------------- function Locate_Directory (Name : Name_Id; Parent : Name_Id) return Name_Id is The_Name : constant String := Get_Name_String (Name); The_Parent : constant String := Get_Name_String (Parent) & Dir_Sep; The_Parent_Last : Positive := The_Parent'Last; begin if The_Parent'Length > 1 and then (The_Parent (The_Parent_Last - 1) = Dir_Sep or else The_Parent (The_Parent_Last - 1) = '/') then The_Parent_Last := The_Parent_Last - 1; end if; if Current_Verbosity = High then Write_Str ("Locate_Directory ("""); Write_Str (The_Name); Write_Str (""", """); Write_Str (The_Parent); Write_Line (""")"); end if; if Is_Absolute_Path (The_Name) then if Is_Directory (The_Name) then return Name; end if; else declare Full_Path : constant String := The_Parent (The_Parent'First .. The_Parent_Last) & The_Name; begin if Is_Directory (Full_Path) then Name_Len := Full_Path'Length; Name_Buffer (1 .. Name_Len) := Full_Path; return Name_Find; end if; end; end if; return No_Name; end Locate_Directory; ------------------ -- Path_Name_Of -- ------------------ function Path_Name_Of (File_Name : String_Id; Directory : String_Id) return String is Result : String_Access; begin String_To_Name_Buffer (File_Name); declare The_File_Name : constant String := Name_Buffer (1 .. Name_Len); begin String_To_Name_Buffer (Directory); Result := Locate_Regular_File (File_Name => The_File_Name, Path => Name_Buffer (1 .. Name_Len)); end; if Result = null then return ""; else Canonical_Case_File_Name (Result.all); return Result.all; end if; end Path_Name_Of; function Path_Name_Of (File_Name : String_Id; Directory : Name_Id) return String is Result : String_Access; The_Directory : constant String := Get_Name_String (Directory); begin String_To_Name_Buffer (File_Name); Result := Locate_Regular_File (File_Name => Name_Buffer (1 .. Name_Len), Path => The_Directory); if Result = null then return ""; else Canonical_Case_File_Name (Result.all); return Result.all; end if; end Path_Name_Of; ------------------- -- Record_Source -- ------------------- procedure Record_Source (File_Name : Name_Id; Path_Name : Name_Id; Project : Project_Id; Data : in out Project_Data; Location : Source_Ptr; Current_Source : in out String_List_Id) is Unit_Name : Name_Id; Unit_Kind : Spec_Or_Body; Needs_Pragma : Boolean; The_Location : Source_Ptr := Location; begin -- Find out the unit name, the unit kind and if it needs -- a specific SFN pragma. Get_Unit (File_Name => File_Name, Naming => Data.Naming, Unit_Name => Unit_Name, Unit_Kind => Unit_Kind, Needs_Pragma => Needs_Pragma); if Unit_Name = No_Name then if Current_Verbosity = High then Write_Str (" """); Write_Str (Get_Name_String (File_Name)); Write_Line (""" is not a valid source file name (ignored)."); end if; else -- Put the file name in the list of sources of the project String_Elements.Increment_Last; Get_Name_String (File_Name); Start_String; Store_String_Chars (Name_Buffer (1 .. Name_Len)); String_Elements.Table (String_Elements.Last) := (Value => End_String, Location => No_Location, Next => Nil_String); if Current_Source = Nil_String then Data.Sources := String_Elements.Last; else String_Elements.Table (Current_Source).Next := String_Elements.Last; end if; Current_Source := String_Elements.Last; -- Put the unit in unit list declare The_Unit : Unit_Id := Units_Htable.Get (Unit_Name); The_Unit_Data : Unit_Data; begin if Current_Verbosity = High then Write_Str ("Putting "); Write_Str (Get_Name_String (Unit_Name)); Write_Line (" in the unit list."); end if; -- The unit is already in the list, but may be it is -- only the other unit kind (spec or body), or what is -- in the unit list is a unit of a project we are extending. if The_Unit /= Prj.Com.No_Unit then The_Unit_Data := Units.Table (The_Unit); if The_Unit_Data.File_Names (Unit_Kind).Name = No_Name or else (Data.Modifies /= No_Project and then The_Unit_Data.File_Names (Unit_Kind).Project = Data.Modifies) then The_Unit_Data.File_Names (Unit_Kind) := (Name => File_Name, Path => Path_Name, Project => Project, Needs_Pragma => Needs_Pragma); Units.Table (The_Unit) := The_Unit_Data; else -- It is an error to have two units with the same name -- and the same kind (spec or body). if The_Location = No_Location then The_Location := Projects.Table (Project).Location; end if; Error_Msg_Name_1 := Unit_Name; Error_Msg ("duplicate source {", The_Location); Error_Msg_Name_1 := Projects.Table (The_Unit_Data.File_Names (Unit_Kind).Project).Name; Error_Msg_Name_2 := The_Unit_Data.File_Names (Unit_Kind).Path; Error_Msg ("\ project file {, {", The_Location); Error_Msg_Name_1 := Projects.Table (Project).Name; Error_Msg_Name_2 := Path_Name; Error_Msg ("\ project file {, {", The_Location); end if; -- It is a new unit, create a new record else Units.Increment_Last; The_Unit := Units.Last; Units_Htable.Set (Unit_Name, The_Unit); The_Unit_Data.Name := Unit_Name; The_Unit_Data.File_Names (Unit_Kind) := (Name => File_Name, Path => Path_Name, Project => Project, Needs_Pragma => Needs_Pragma); Units.Table (The_Unit) := The_Unit_Data; end if; end; end if; end Record_Source; ---------------------- -- Show_Source_Dirs -- ---------------------- procedure Show_Source_Dirs (Project : Project_Id) is Current : String_List_Id := Projects.Table (Project).Source_Dirs; Element : String_Element; begin Write_Line ("Source_Dirs:"); while Current /= Nil_String loop Element := String_Elements.Table (Current); Write_Str (" "); Write_Line (Get_Name_String (Element.Value)); Current := Element.Next; end loop; Write_Line ("end Source_Dirs."); end Show_Source_Dirs; end Prj.Nmsc;
---------------------------------------------------------------------- -- package body Peters_Eigen, eigendecomposition -- Copyright (C) 2008-2018 Jonathan S. Parker. -- -- Permission to use, copy, modify, and/or distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --------------------------------------------------------------------------- with Ada.numerics.Generic_Elementary_Functions; with Hessenberg; with Givens_QR_Method; with Hypot; package body Peters_Eigen is package Givens_Hess is new Hessenberg (Real, Index, Matrix); package Initial_QR is new Givens_QR_Method (Real, Index, Matrix); package Hypo is new Hypot (Real); Zero : constant Real := +0.0; One : constant Real := +1.0; Two : constant Real := +2.0; Half : constant Real := +0.5; Max_Exp : constant Integer := Real'Machine_Emax - Real'Machine_Emax/16; Sqrt_Max_Allowed_Real : constant Real := Two**(Max_Exp / 2); Min_Exp : constant Integer := Real'Machine_Emin - Real'Machine_Emin/16; Sqrt_Min_Allowed_Real : constant Real := Two**(Min_Exp / 2); package Math is new Ada.numerics.Generic_Elementary_Functions(Real); use Math; ---------- -- Div2 -- ---------- -- Complex division, C := A / B -- -- If B = 0, allow the usual real arithmetic to raise exceptions. -- -- Algorithm by Robert L. Smith. (Supposed to be better at avoiding -- unnecessary divisions by 0 (due to underflow) than Eispack version.) -- procedure Div2 (A_r, A_i : in Real; B_r, B_i : in Real; C_r, C_i : out Real) is e, f : Real; begin if Abs (B_i) < Abs (B_r) then e := B_i / B_r; f := B_r + B_i*e; C_r := (A_r + A_i*e) / f; C_i := (A_i - A_r*e) / f; else e := B_r / B_i; f := B_i + B_r*e; C_r := (A_i + A_r*e) / f; C_i :=(-A_r + A_i*e) / f; end if; end Div2; procedure Div (A_re, A_im : in Real; B_re, B_im : in Real; C_r, C_i : out Real) is A_max : constant Real := Real'Max (Abs A_re, Abs A_im); B_max : constant Real := Real'Max (Abs B_re, Abs B_im); A_Scale, B_Scale, Unscale, B_Squ : Real := One; A_Scale_exp, B_Scale_exp : Integer := 0; A_r, A_i, B_r, B_i : Real; begin C_r := Zero; C_i := Zero; if A_max = Zero then -- use default C_r, C_i return; end if; if B_max = Zero then raise Constraint_Error with "Division by 0 in Div"; end if; A_r := A_re; A_i := A_im; if A_max > Two**(Real'Machine_Emax/2 - 2) or else A_max < Two**(Real'Machine_Emin/2 + 2) then A_Scale_exp := -Real'Exponent (A_max); A_Scale := Two**A_Scale_exp; A_r := A_re * A_Scale; A_i := A_im * A_Scale; end if; B_r := B_re; B_i := B_im; if B_max > Two**(Real'Machine_Emax/2 - 2) or else B_max < Two**(Real'Machine_Emin/2 + 2) then B_Scale_exp := -Real'Exponent (B_max); B_Scale := Two**B_Scale_exp; B_r := B_re * B_Scale; B_i := B_im * B_Scale; end if; Unscale := Two**(B_Scale_exp - A_Scale_exp); -- over/under flow if A/B out of range. B_Squ := B_r**2 + B_i**2; C_r := ((A_r*B_r + A_i*B_i) / B_Squ) * Unscale; C_i := ((A_i*B_r - A_r*B_i) / B_Squ) * Unscale; end Div; -------------------- -- Balance_Matrix -- -------------------- -- procedure Balance_Matrix returns Vector D representing a -- diagonal matrix, and Matrix B, -- -- B := D^(-1) * A * D -- -- If we subsequently find the eigendecomposition of B -- -- B*v = lambda*v. -- -- Then -- -- D^(-1)*A*D*v = lambda*v -- -- implies that -- -- A*D*v = lambda*D*v, -- -- so that the eigenvectors of A are D*v, (D times the eigenvectors of B). -- The eigenvalues A and B are unchanged by the transformation. -- -- The eigenvectors v of matrix B are orthonormal, but not the -- eigenvectors D*v of matrix A. -- -- A is written over with B. procedure Balance_Matrix (A : in out Matrix; D : in out Col_Vector; Starting_Col : in Index; Final_Col : in Index; Balance_Policy : in Balance_Code := Partial) is Radix : constant Real := Two ** 1; -- Two**1 most accurate. Radix_Squared : constant Real := Radix ** 2; Reciprocal_Radix : constant Real := 1.0 / Radix; Reciprocal_Radix_Squared : constant Real := Reciprocal_Radix ** 2; Max_Allowed_Iterations : Integer := 16; Converged : Boolean := True; g, f, s : Real; Row_Norm, Col_Norm : Real; Min_Exp : constant Integer := Real'Machine_Emin + 16; Min_Allowed_Real : constant Real := Two ** Min_Exp; Max_Test : constant Real := Two**(Real'Machine_Emax / 2); Min_Test : constant Real := Two**(Real'Machine_Emin / 2); N : constant Integer := 1 + Integer (Real(Final_Col) - Real(Starting_Col)); begin case Balance_Policy is when Full => Max_Allowed_Iterations := 16; when Partial => Max_Allowed_Iterations := 2 + Integer (N / 500); when Disabled => Max_Allowed_Iterations := 0; end case; -- Balance a square block whose -- upper-left corner is (Starting_Col, Starting_Col). -- Lower-right corner is (Final_Col, Final_Col). D := (others => One); Until_Converged: for Interation_id in 1 .. Max_Allowed_Iterations loop Converged := True; for i in Starting_Col .. Final_Col loop Row_Norm := 0.0; Col_Norm := 0.0; for j in Starting_Col .. Final_Col loop if j /= i then Col_Norm := Col_Norm + Abs (A(j, i)); Row_Norm := Row_Norm + Abs (A(i, j)); end if; end loop; -- D(i) is already 1.0. If both norms are > 0.0 -- then calculate f for D(i) and g = 1/f for D(i)^(-1): if (Col_Norm > Min_Allowed_Real) and (Row_Norm > Min_Allowed_Real) then f := 1.0; g := Row_Norm * Reciprocal_Radix; s := Col_Norm + Row_Norm; while Col_Norm < g loop exit when f > Max_Test or else Col_Norm > Max_Test; f := f * Radix; Col_Norm := Col_Norm * Radix_Squared; end loop; g := Row_Norm * Radix; while Col_Norm > g loop exit when f < Min_Test or else Col_Norm < Min_Test; f := f * Reciprocal_Radix; Col_Norm := Col_Norm * Reciprocal_Radix_Squared; end loop; -- If we flunk the following test for all row/cols i, then -- Converged remains True, and we exit the loop and return. if ((Row_Norm + Col_Norm) / f < 0.93 * s) then -- .75 with 3 iters is like .95 with 2 iters Converged := False; D(i) := D(i) * f; -- D(i) initially 1.0 g := One / f; -- (multiplying by D on the right): Scale i_th col by f. for k in Starting_Col .. A'Last(1) loop -- k .. N A(k,i) := f * A(k,i); end loop; -- (multiplying by D^(-1) on the left)): Scale i_th row by g = 1/f for k in A'First(2) .. Final_Col loop -- 1 .. l A(i,k) := g * A(i,k); end loop; end if; end if; -- if both norms are non-zero end loop; -- in i_th row/col exit when Converged; end loop Until_Converged; end Balance_Matrix; ------------------ -- Balance_Undo -- ------------------ -- -- The eigenvectors of A are D*z, (multiply diagonal matrix -- D on the right times the eigenvectors Z of the balanced matrix B). -- procedure Balance_Undo (D : in Col_Vector; Z : in out Matrix; Starting_Col : in Index; Final_Col : in Index) is begin for r in Starting_Col .. Final_Col loop for c in Starting_Col .. Final_Col loop Z(r,c) := Z(r,c) * D(r); end loop; end loop; end Balance_Undo; ------------------------ -- Rotation_Factors_2 -- ------------------------ -- sn = a / sqrt(a**2 + b**2) -- cs = b / sqrt(a**2 + b**2) procedure Rotation_Factors_2 (a, b : in Real; sn_lo, sn_hi, cs_lo, cs_hi : out Real; hypot : out Real) is Abs_a : constant Real := Abs a; Abs_b : constant Real := Abs b; min_over_hypot, max_over_hypot_minus_1 : Real; Min_Allowed_Real : constant Real := Two**(Real'Machine_Emin + 16); begin -- default: cs_hi := One; cs_lo := Zero; sn_hi := Zero; sn_lo := Zero; hypot := One; if Abs_a >= Abs_b then if Abs_a > Min_Allowed_Real then Hypo.Get_Hypotenuse (a, b, hypot, min_over_hypot, max_over_hypot_minus_1); cs_hi := Zero; cs_lo := min_over_hypot; sn_hi := One; sn_lo := max_over_hypot_minus_1; if a < Zero then sn_hi := -sn_hi; sn_lo := -sn_lo; end if; if b < Zero then cs_lo := -cs_lo; end if; end if; else if Abs_b > Min_Allowed_Real then Hypo.Get_Hypotenuse (a, b, hypot, min_over_hypot, max_over_hypot_minus_1); sn_hi := Zero; sn_lo := min_over_hypot; cs_hi := One; cs_lo := max_over_hypot_minus_1; if a < Zero then sn_lo := -sn_lo; end if; if b < Zero then cs_hi := -cs_hi; cs_lo := -cs_lo; end if; end if; end if; end Rotation_Factors_2; --------------------------------------- -- Arg_1_is_Negligible_Respect_Arg_2 -- --------------------------------------- -- IF Abs_x is negligible in comparison to Abs_y then return True. function Arg_1_is_Negligible_Respect_Arg_2 (x, y : Real) return Boolean is Abs_x : constant Real := Abs x; Abs_y : constant Real := Abs y; Min_Allowed_Real : constant Real := Two ** Real'Machine_Emin; Added_Range : constant := 5; -- 2 to 8. 6,7 std. 7 helps with clustered eigs. Effective_Mantissa : constant Integer := Real'Machine_Mantissa + Added_Range; Eps_Factor : constant Real := Two**(-Effective_Mantissa); pragma Assert (Added_Range > 1); -- Stnd setting for Eps_Factor is: 2**(-Real'Machine_Mantissa-2) -- Usually Real'Machine_Mantissa = 53 if Real is 15 digits. begin if Abs_x < Min_Allowed_Real then -- eg, Abs_x = 0.0 return True; elsif Abs_x <= Abs_y*Eps_Factor then -- Abs_x is negligible in comparison to Abs_y return True; else return False; end if; end Arg_1_is_Negligible_Respect_Arg_2; ------------------------ -- Unpack_Eig_Vectors -- ------------------------ procedure Unpack_Eig_Vectors (W_i : in Col_Vector; Z : in out Matrix; -- will exit with Z_r, the real part of Z. Z_i : out Matrix; -- will exit with imaginary part. Starting_Col : in Index; Final_Col : in Index) is begin Z_i := (others => (others => Zero)); -- Im (W) > 0 at column c means that columns c and c+1 of Z are the -- Re and Im parts of the Eigenvector, with eig_val = (W_r(c), Abs(W_i(c))). for c in Starting_Col .. Final_Col-1 loop if W_i(c) > Zero then for j in Starting_Col .. Final_Col loop Z_i(j,c) := Z(j,c+1); Z_i(j,c+1) := -Z(j,c+1); end loop; for j in Starting_Col .. Final_Col loop Z(j,c+1):= Z(j,c); -- the real parts of the above 2 vecs are equal. end loop; if not (W_i(c+1) < Zero) then -- something went very wrong. raise Constraint_Error with "Fatal error in Unpack_Eig_Vectors"; end if; end if; end loop; end Unpack_Eig_Vectors; ---------- -- Norm -- ---------- function Norm (V_r, V_i : in Col_Vector; Starting_Col : in Index := Index'First; Final_Col : in Index := Index'Last) return Real is Max : Real := Zero; Sum, tst : Real := Zero; Scale : Real := One; Scaled : Boolean := False; Scale_Exp : Integer; X, Y : Real; begin for i in Starting_Col .. Final_Col loop tst := Abs (V_r(i)); if tst > Max then Max := tst; end if; tst := Abs (V_i(i)); if tst > Max then Max := tst; end if; end loop; if Max > Sqrt_Max_Allowed_Real then Scale_Exp := Integer'Min (Real'Exponent (Max), Real'Machine_Emax-4); Scale := Two**(-Scale_Exp); Scaled := True; end if; if Max < Sqrt_Min_Allowed_Real then Scale_Exp := Integer'Max (Real'Exponent (Max), Real'Machine_Emin+4); Scale := Two**(-Scale_Exp); Scaled := True; end if; if Scaled then for k in Starting_Col .. Final_Col loop X := Scale * V_r(k); Y := Scale * V_i(k); Sum := Sum + X**2 + Y**2; end loop; else for k in Starting_Col .. Final_Col loop Sum := Sum + V_r(k)**2 + V_i(k)**2; end loop; end if; if Scaled then return Sqrt (Abs Sum) * Two**Scale_Exp; else return Sqrt (Abs Sum); end if; end Norm; ------------------------------ -- Normalize_Column_Vectors -- ------------------------------ procedure Normalize_Column_Vectors (Z_r, Z_i : in out Matrix; Starting_Col : in Index; Final_Col : in Index) is Min_Exp : constant Integer := Real'Machine_Emin/2 + Real'Machine_Emin/4; Min_Allowed_Real : constant Real := Two**Min_Exp; V_r, V_i : Col_Vector; Norm_Factor : Real; begin for Col_id in Starting_Col .. Final_Col loop for j in Starting_Col .. Final_Col loop V_r(j) := Z_r(j, Col_id); end loop; for j in Starting_Col .. Final_Col loop V_i(j) := Z_i(j, Col_id); end loop; Norm_Factor := One / (Norm (V_r, V_i, Starting_Col, Final_Col) + Min_Allowed_Real); for j in Starting_Col .. Final_Col loop Z_r(j, Col_id) := Z_r(j, Col_id) * Norm_Factor; end loop; for j in Starting_Col .. Final_Col loop Z_i(j, Col_id) := Z_i(j, Col_id) * Norm_Factor; end loop; end loop; end Normalize_Column_Vectors; ---------------------------- -- Apply_QR_to_Hessenberg -- ---------------------------- -- Apply_QR_to_Hessenberg is a translation of the algol procedure -- hqr2, num. math. 16, 181-204(1970) by Peters and Wilkinson. -- handbook for auto. comp., vol.ii-linear algebra, 372-395(1971). -- -- Have Z' A Z = H where H and Z are input below. (H is upper Hessenberg.) -- The problem is to further elaborate Z so that A Z = w Z. The -- Col vectors of Z are eigvecs, and the diagonal elements of w are the -- eigvals. procedure Apply_QR_to_Hessenberg (H : in out Matrix; Z : in out Matrix; W_r, W_i : out Col_Vector; Norm : out Real; Unscale_Eigs : out Real; Starting_Col : in Index := Index'First; Final_Col : in Index := Index'Last; Eigenvectors_Desired : in Boolean := True; Id_of_Failed_Eig : out Integer) is N : constant Real := Real(Final_Col) - Real(Starting_Col) + One; Max_Allowed_Iterations : constant Integer := 128 * Integer (N); Remaining_Iterations : Integer := Max_Allowed_Iterations; Iteration_id : Integer := 1; Emin : constant Integer := Real'Machine_Emin; Min_Exp : constant Integer := Emin - Emin / 16; Min_Allowed_Real : constant Real := Two**(Min_Exp / 2 + 64); pragma Assert (Index'Base'First < Index'First - 1); pragma Assert (Final_Col > Starting_Col); Scale_Eigs : Real; begin W_r := (others => Zero); -- important init. W_i := (others => Zero); Id_of_Failed_Eig := Integer(Starting_Col) - 1; -- means none failed. -- compute matrix Norm Norm := Zero; for c in Starting_Col .. Final_Col loop for r in Starting_Col .. Final_Col loop Norm := Norm + Abs (H(r,c)); end loop; end loop; Unscale_Eigs := One; if Norm > Two ** (Real'Machine_Emax / 2 - 2) then Scale_Eigs := Two ** (- Real'Exponent (Norm)); UnScale_Eigs := One / Scale_Eigs; for c in Starting_Col .. Final_Col loop for r in Starting_Col .. Final_Col loop H(r,c) := H(r,c) * Scale_Eigs; end loop; end loop; end if; Find_All_Eigenvalues: declare Eig_id_0 : Index'Base := Final_Col; Eig_id_2, Eig_id_1 : Index'Base; l_memo, m_memo : Index; Final_k : Boolean; t : Real := Zero; -- essential init tst1, tst2 : Real := Zero; Hmm : Real; x, y : Real; p,q,r,w,zz,xx : Real; Exp_s : Integer; Scale, Scale_Inv : Real; r_div_s, q_div_s, p_div_s : Real; q_div_ps, r_div_ps : Real; s, ss, tmp0 : Real := Zero; begin Get_Next_Eigval: while Eig_id_0 >= Starting_Col loop -- iterate for eigenvalues: Iteration_id := 1; Eig_id_1 := Eig_id_0 - 1; Eig_id_2 := Eig_id_0 - 2; -- look for single small sub-diagonal element loop Find_Next_Root: loop for l in reverse Starting_Col .. Eig_id_0 loop l_memo := l; exit when l = Starting_Col; s := Abs (H(l-1,l-1)) + Abs (H(l,l)); if s < Min_Allowed_Real then s := Norm; end if; exit when Arg_1_is_Negligible_Respect_Arg_2 (H(l,l-1), s); end loop; -- form shift. x := H(Eig_id_0,Eig_id_0); if l_memo = Eig_id_0 then -- 1 root found H(Eig_id_0,Eig_id_0) := x + t; W_r(Eig_id_0) := H(Eig_id_0,Eig_id_0); W_i(Eig_id_0) := Zero; Eig_id_0 := Eig_id_1; goto End_of_Loop_Get_Next_Eigval; -- Notice we just decremented Eig_id_0. end if; y := H(Eig_id_1,Eig_id_1); w := H(Eig_id_0,Eig_id_1) * H(Eig_id_1,Eig_id_0); exit Find_Next_Root when l_memo = Eig_id_1; -- 2 roots found if Remaining_Iterations = 0 then -- didn't converge Id_of_Failed_Eig := Integer (Eig_id_0); return; end if; -- form exceptional shift if Iteration_id mod 14 = 0 then -- Forsythe_0 needs this. t := t + x; for i in Starting_Col .. Eig_id_0 loop H(i,i) := H(i,i) - x; end loop; s := Abs (H(Eig_id_0,Eig_id_1)) + Abs (H(Eig_id_1,Eig_id_2)); x := 0.75 * s; y := x; w := -0.4375 * s * s; end if; Iteration_id := Iteration_id + 1; Remaining_Iterations := Remaining_Iterations - 1; -- look for two consecutive small loop sub-diagonal elements. for m in reverse l_memo .. Eig_id_2 loop m_memo := m; Hmm := H(m,m); r := x - Hmm; s := y - Hmm; p := (r * s - w) / H(m+1,m) + H(m,m+1); q := H(m+1,m+1) - Hmm - r - s; r := H(m+2,m+1); Scale := One / (Abs (p) + Abs (q) + Abs (r) + Min_Allowed_Real); p := p * Scale; q := q * Scale; r := r * Scale; exit when m = l_memo; tst1 := Abs (H(m,m-1)) * (Abs (q) + Abs (r)); tst2 := Abs (p)*(Abs (H(m-1,m-1)) + Abs (Hmm) + Abs (H(m+1,m+1))); exit when Arg_1_is_Negligible_Respect_Arg_2 (tst1, tst2); end loop; for i in m_memo+2 .. Eig_id_0 loop H(i,i-2) := Zero; if (i /= m_memo+2) then H(i,i-3) := Zero; end if; end loop; -- double qr step w/ rows l_memo .. Eig_id_0, columns m_memo .. Eig_id_0 Double_QR: for k in m_memo .. Eig_id_1 loop Final_k := (k = Eig_id_1); if k /= m_memo then p := H(k,k-1); q := H(k+1,k-1); if Final_k then r := Zero; else r := H(k+2,k-1); end if; Scale := Abs (p) + Abs (q) + Abs (r); if Scale < Min_Allowed_Real then goto End_of_Loop_Double_QR; -- and then increment k. end if; if Scale < Two**(Emin / 2) or else Scale > Two**(Real'Emax / 4) then Exp_s := Real'Exponent (Scale); scale := Two ** (Exp_s); Scale_Inv := Two ** (-Exp_s); p := p * Scale_Inv; q := q * Scale_Inv; r := r * Scale_Inv; else scale := One; scale_inv := One; end if; end if; ss := p*p + q*q + r*r; s := Real'Copy_Sign (Sqrt (ss), p); if (k /= m_memo) then H(k,k-1) := -s * Scale; else if (l_memo /= m_memo) then H(k,k-1) := -H(k,k-1); end if; end if; p_div_s := p / s; q_div_s := q / s; r_div_s := r / s; q_div_ps := q / (p + s); r_div_ps := r / (p + s); if not Final_k then -- rows for j in k .. Final_Col loop tmp0 := H(k,j) + (q_div_ps * H(k+1,j) + r_div_ps * H(k+2,j)); H(k,j) := -p_div_s * H(k,j) - (q_div_s*H(k+1,j) + r_div_s*H(k+2,j)); H(k+1,j) := H(k+1,j) - tmp0 * q_div_s; H(k+2,j) := H(k+2,j) - tmp0 * r_div_s; end loop; -- columns for i in Starting_Col .. Index'Min (Eig_id_0,k+3) loop tmp0 := H(i,k) + (q_div_ps * H(i,k+1) + r_div_ps * H(i,k+2)); H(i,k) := -p_div_s * H(i,k) - (q_div_s*H(i,k+1) + r_div_s*H(i,k+2)); H(i,k+1) := H(i,k+1) - tmp0 * q_div_s; H(i,k+2) := H(i,k+2) - tmp0 * r_div_s; end loop; -- accumulate transformations if Eigenvectors_Desired then for i in Starting_Col .. Final_Col loop tmp0 := Z(i,k) + (q_div_ps * Z(i,k+1) + r_div_ps * Z(i,k+2)); Z(i,k) := -p_div_s * Z(i,k) - (q_div_s*Z(i,k+1) + r_div_s*Z(i,k+2)); Z(i,k+1) := Z(i,k+1) - tmp0 * q_div_s; Z(i,k+2) := Z(i,k+2) - tmp0 * r_div_s; end loop; end if; else for j in k .. Final_Col loop tmp0 := H(k,j) + q_div_ps * H(k+1,j); H(k,j) := -p_div_s * H(k,j) - q_div_s * H(k+1,j); H(k+1,j) := H(k+1,j) - q_div_s * tmp0; end loop; -- columns for i in Starting_Col .. Index'Min (Eig_id_0,k+3) loop tmp0 := H(i,k) + q_div_ps * H(i,k+1); H(i,k) := -p_div_s * H(i,k) - q_div_s * H(i,k+1); H(i,k+1) := H(i,k+1) - q_div_s * tmp0; end loop; -- accumulate transformations if Eigenvectors_Desired then for i in Starting_Col .. Final_Col loop tmp0 := Z(i,k) + q_div_ps * Z(i,k+1); Z(i,k) := -p_div_s * Z(i,k) - q_div_s * Z(i,k+1); Z(i,k+1) := Z(i,k+1) - q_div_s * tmp0; end loop; end if; end if; <<End_of_Loop_Double_QR>> null; end loop Double_QR; -- increment k end loop Find_Next_Root; -- two roots found. x, y, w were defined up top as: -- -- x := H(Eig_id_0,Eig_id_0); -- y := H(Eig_id_1,Eig_id_1); -- w := H(Eig_id_0,Eig_id_1) * H(Eig_id_1,Eig_id_0); p := Half * (y - x); q := p * p + w; zz := Sqrt (Abs (q)); H(Eig_id_0,Eig_id_0) := x + t; H(Eig_id_1,Eig_id_1) := y + t; x := x + t; if q >= Zero then -- real pair zz := p + Real'Copy_Sign (zz, p); W_r(Eig_id_1) := x + zz; W_r(Eig_id_0) := W_r(Eig_id_1); if (Abs zz > Min_Allowed_Real) then W_r(Eig_id_0) := x - w / zz; end if; W_i(Eig_id_1) := Zero; W_i(Eig_id_0) := Zero; xx := H(Eig_id_0,Eig_id_1); declare hypot, sn_lo, sn_hi, cs_lo, cs_hi : Real; tmp1, tmp0 : Real; begin Rotation_Factors_2 (xx, zz, sn_lo, sn_hi, cs_lo, cs_hi, hypot); -- sn = a / Sqrt(a*a + b*b), cs = b / Sqrt(a*a + b*b), (a=xx, b = zz) -- rows for j in Eig_id_1 .. Final_Col loop tmp1 := H(Eig_id_1,j); tmp0 := H(Eig_id_0,j); H(Eig_id_1,j) := sn_hi*tmp0 + cs_hi*tmp1 + (cs_lo*tmp1 + sn_lo*tmp0); H(Eig_id_0,j) :=-sn_hi*tmp1 + cs_hi*tmp0 + (cs_lo*tmp0 - sn_lo*tmp1); end loop; -- columns for i in Starting_Col .. Eig_id_0 loop tmp1 := H(i,Eig_id_1); tmp0 := H(i,Eig_id_0); H(i,Eig_id_1) := sn_hi*tmp0 + cs_hi*tmp1 + (cs_lo*tmp1 + sn_lo*tmp0); H(i,Eig_id_0) :=-sn_hi*tmp1 + cs_hi*tmp0 + (cs_lo*tmp0 - sn_lo*tmp1); end loop; -- columns for i in Starting_Col .. Final_Col loop tmp1 := Z(i,Eig_id_1); tmp0 := Z(i,Eig_id_0); Z(i,Eig_id_1) := sn_hi*tmp0 + cs_hi*tmp1 + (cs_lo*tmp1 + sn_lo*tmp0); Z(i,Eig_id_0) :=-sn_hi*tmp1 + cs_hi*tmp0 + (cs_lo*tmp0 - sn_lo*tmp1); end loop; end; else -- complex pair W_r(Eig_id_1) := p + x; W_r(Eig_id_0) := p + x; W_i(Eig_id_1) := zz; W_i(Eig_id_0) :=-zz; end if; Eig_id_0 := Eig_id_2; <<End_of_Loop_Get_Next_Eigval>> null; end loop Get_Next_Eigval; end Find_All_Eigenvalues; end Apply_QR_to_Hessenberg; --------------------------- -- Find_all_Eigenvectors -- --------------------------- -- Backsubstitute to find vectors of upper triangular form H. procedure Find_all_Eigenvectors (H : in out Matrix; Z : in out Matrix; Z_i : out Matrix; W_r, W_i : in Col_Vector; Norm : in Real; Starting_Col : in Index := Index'First; Final_Col : in Index := Index'Last) is Eig_Start, Eig_Memo : Index; Eig_2, Eig_1 : Index'Base; ra, sa : Real; p, q, r, s, w, zz : Real; Sum : Real; Min_Exp : constant Integer := Real'Machine_Emin; Min_Allowed_Real : constant Real := Two**(Min_Exp - Min_Exp/16); pragma Assert (Index'Base'First < Index'First - 1); pragma Assert (Final_Col > Starting_Col); begin if Norm = Zero then Z_i := (others => (others => Zero)); return; end if; Get_Next_Eigenvector: for Eig_0 in reverse Starting_Col .. Final_Col loop p := W_r(Eig_0); q := W_i(Eig_0); if Abs W_i(Eig_0) = Zero then -- Make real vector H(Eig_0,Eig_0) := One; Eig_Memo := Eig_0; if Eig_0 > Starting_Col then Get_Real_Vector: for i in reverse Starting_Col .. Eig_0-1 loop w := H(i,i) - p; r := Zero; for j in Eig_Memo .. Eig_0 loop r := r + H(i,j) * H(j,Eig_0); end loop; if W_i(i) < Zero then zz := w; s := r; else Eig_Memo := i; if (Abs W_i(i) < Min_Allowed_Real) then declare t : Real := w; Exp_t : Integer; begin if Abs t < Min_Allowed_Real then Exp_t := Real'Machine_Mantissa + 27; t := Norm * Two**(-Exp_t) + Min_Allowed_Real; end if; H(i,Eig_0) := -r / t; end; else -- solve real equations declare x, y, q, t : Real; begin x := H(i,i+1); y := H(i+1,i); q := (W_r(i) - p)**2 + W_i(i)**2; t := (x * s - zz * r) / q; H(i,Eig_0) := t; if (Abs (x) > Abs (zz)) then H(i+1,Eig_0) := (-r - w * t) / x; else H(i+1,Eig_0) := (-s - y * t) / zz; end if; end; end if; -- overflow control declare t, Scale : Real; Exp_t : Integer; begin t := Abs (H(i,Eig_0)); if t > Min_Allowed_Real then -- "t > Zero" fails Exp_t := Real'Exponent (t); if Exp_t > Real'Machine_Mantissa + 27 then Scale := Two**(-Exp_t); for j in i .. Eig_0 loop H(j,Eig_0) := H(j,Eig_0) * Scale; end loop; end if; end if; end; end if; end loop Get_Real_Vector; -- in i end if; -- if Eig_0 > Starting_Col -- Now go to end of loop Get_Next_Eigenvector, and increment Eig_0. elsif q < Zero then -- Complex vectors. Last vector component chosen imaginary -- so that eigenvector matrix is triangular. Eig_1 := Eig_0 - 1; Eig_2 := Eig_0 - 2; -- check if (Abs (H(Eig_0,Eig_1)) > Abs (H(Eig_1,Eig_0))) then H(Eig_1,Eig_1) := q / H(Eig_0,Eig_1); H(Eig_1,Eig_0) := -(H(Eig_0,Eig_0) - p) / H(Eig_0,Eig_1); else Div (Zero, -H(Eig_1,Eig_0), H(Eig_1,Eig_1)-p, q, H(Eig_1,Eig_1), H(Eig_1,Eig_0)); end if; H(Eig_0,Eig_1) := Zero; H(Eig_0,Eig_0) := One; Eig_Start := Eig_1; Get_Complex_Vector: for i in reverse Starting_Col .. Eig_2 loop w := H(i,i) - p; ra := Zero; sa := Zero; for j in Eig_Start .. Eig_0 loop ra := ra + H(i,j) * H(j,Eig_1); sa := sa + H(i,j) * H(j,Eig_0); end loop; if (W_i(i) < Zero) then zz := w; r := ra; s := sa; goto End_of_Loop_Get_Complex_Vector; end if; Eig_Start := i; -- decrement start of previous loop if (Abs W_i(i) < Min_Allowed_Real) then Div (-ra, -sa, w, q, H(i,Eig_1), H(i,Eig_0)); else -- solve complex equations declare x, y, vr, vi, tst1 : Real; begin x := H(i,i+1); y := H(i+1,i); vr := (W_r(i) - p) * (W_r(i) - p) + W_i(i) * W_i(i) - q * q; vi := (W_r(i) - p) * Two * q; if (Abs vr < Min_Allowed_Real and Abs vi < Min_Allowed_Real) then tst1 := Norm * (Abs(w)+Abs(q)+Abs(x)+Abs(y)+Abs(zz)); vr := tst1 * (Real'Epsilon * Two**(-10)); end if; Div(x*r-zz*ra+q*sa, x*s-zz*sa-q*ra, vr, vi, H(i,Eig_1), H(i,Eig_0)); if (Abs (x) > Abs (zz) + Abs (q)) then H(i+1,Eig_1) := (-ra - w * H(i,Eig_1) + q * H(i,Eig_0)) / x; H(i+1,Eig_0) := (-sa - w * H(i,Eig_0) - q * H(i,Eig_1)) / x; else Div(-r-y*H(i,Eig_1), -s-y*H(i,Eig_0), zz, q, H(i+1,Eig_1), H(i+1,Eig_0)); end if; end; end if; -- overflow control declare t, Scale : Real; Exp_t : Integer; begin t := Real'Max (Abs (H(i,Eig_1)), Abs (H(i,Eig_0))); if t > Min_Allowed_Real then Exp_t := Real'Exponent (t); if Exp_t > Real'Machine_Mantissa + 27 then Scale := Two**(-Exp_t); for j in i .. Eig_0 loop H(j,Eig_1) := H(j,Eig_1) * Scale; H(j,Eig_0) := H(j,Eig_0) * Scale; end loop; end if; end if; end; <<End_of_Loop_Get_Complex_Vector>> null; end loop Get_Complex_Vector; -- increment i end if; -- Abs W_i(Eig_0) < Min_Allowed_Real => do real vecs, else complex. end loop Get_Next_Eigenvector; -- increment Eig_0 -- multiply by transformation matrix to get the eigenvectors. -- Have H v = w v, where Z' A Z = H. Then Z H Z'(Zv) = w (Zv) -- implies that Z*v are the eigvecs of A = Z H Z'. (To save much -- space, the "v" eigenvectors were stored in H). --for j in reverse Starting_Col .. Final_Col loop -- for i in Starting_Col .. Final_Col loop -- Sum := Zero; -- for k in Starting_Col .. j loop -- Sum := Sum + Z(i,k) * H(k,j); -- end loop; -- Z(i,j) := Sum; -- end loop; --end loop; declare Z_row_vec, Z_new_row : array (Starting_Col .. Final_Col) of Real; begin for r in Starting_Col .. Final_Col loop for k in Starting_Col .. Final_Col loop -- reuse a row of Z below Z_row_vec(k) := Z(r, k); end loop; for c in Starting_Col .. Final_Col loop Sum := Zero; for k in Starting_Col .. c loop -- H is upper triangular --Sum := Sum + Z(r, k) * H(k, c); Sum := Sum + Z_row_vec(k) * H(k, c); -- H is Convention(Fortran). end loop; Z_new_row(c) := Sum; end loop; for c in Starting_Col .. Final_Col loop Z(r, c) := Z_new_row(c); end loop; end loop; end; Unpack_Eig_Vectors (W_i, Z, Z_i, Starting_Col, Final_Col); -- Gets (Z_r, Z_i) from Z. Destroys old Z. -- The out parameter Z_i is finally initialized here. end Find_all_Eigenvectors; ------------------------ -- Sort_Eigs_And_Vecs -- ------------------------ procedure Sort_Eigs_And_Vecs (Z_r, Z_i : in out Matrix; -- eigvecs are columns of Z W_r, W_i : in out Col_Vector; -- eigvals are vectors W Starting_Col : in Index := Index'First; Final_Col : in Index := Index'Last) is Max_Eig, tmp : Real; Eig_Size : Col_Vector := (others => Zero); i_Max : Index; begin if Starting_Col < Final_Col then for i in Starting_Col .. Final_Col loop Eig_Size(i) := Hypo.Hypotenuse (W_r(i), W_i(i)); end loop; for i in Starting_Col .. Final_Col-1 loop Max_Eig := Eig_Size(i); i_Max := i; for j in i+1 .. Final_Col loop if Eig_Size(j) > Max_Eig then Max_Eig := Eig_Size(j); i_Max := j; end if; end loop; if i_Max > i then tmp := W_r(i); W_r(i) := W_r(i_Max); W_r(i_Max) := tmp; tmp := W_i(i); W_i(i) := W_i(i_Max); W_i(i_Max) := tmp; tmp := Eig_Size(i); Eig_Size(i) := Eig_Size(i_Max); Eig_Size(i_Max) := tmp; -- swap cols of Z, the eigenvectors: for k in Starting_Col .. Final_Col loop tmp := Z_r(k, i); Z_r(k, i) := Z_r(k, i_Max); Z_r(k, i_Max) := tmp; end loop; for k in Starting_Col .. Final_Col loop tmp := Z_i(k, i); Z_i(k, i) := Z_i(k, i_Max); Z_i(k, i_Max) := tmp; end loop; end if; end loop; end if; end Sort_Eigs_And_Vecs; procedure Transpose (M : in out Matrix; Starting_Col : in Index := Index'First; Final_Col : in Index := Index'Last) is tmp : Real; begin for r in Starting_Col .. Final_Col loop for c in Starting_Col .. r loop tmp := M(c,r); M(c,r) := M(r,c); M(r,c) := tmp; end loop; end loop; end Transpose; --------------- -- Decompose -- --------------- procedure Decompose (A : in out Matrix; Z_r, Z_i : out Matrix; W_r, W_i : out Col_Vector; Id_of_Failed_Eig : out Integer; Starting_Col : in Index := Index'First; Final_Col : in Index := Index'Last; Eigenvectors_Desired : in Boolean := True; Balance_Policy : in Balance_Code := Disabled) is Norm : Real := One; Unscale_Eigs : Real := One; D : Col_Vector := (others => One); begin Id_of_Failed_Eig := Integer (Final_Col); -- init out parameter. Z_r := Givens_Hess.Identity; if Final_Col <= Starting_Col then raise Constraint_Error with "Can't have Final_Col <= Starting_Col"; end if; Balance_Matrix (A, D, Starting_Col, Final_Col, Balance_Policy); -- if matrix was balanced, then multiply D by I to get starting -- point for calculation of the Q matrix: Initial_Q => Z_r. -- -- ** The Q matrices won't be orthogonal if the matrix is balanced. ** for c in Index loop Z_r(c,c) := D(c); end loop; -- More generally, if Initial_Q is not I, but some Z_r: -- --for r in Starting_Col .. Final_Col loop --for c in Starting_Col .. Final_Col loop --Z_r(r,c) := Z_r(r,c) * D(c); --end loop; --end loop; Givens_Hess.Upper_Hessenberg (A => A, Q => Z_r, Starting_Col => Starting_Col, Final_Col => Final_Col, Initial_Q => Z_r); -- A is now in Upper_Hessenberg form, thanks to Z_r: A_true = Z_r' A Z_r. -- Procedure Upper_Hessenberg initializes "out" parameter Z_r. for i in 1 .. 8 loop Initial_QR.Lower_Diagonal_QR_Iteration (A => A, Q => Z_r, Shift => Zero, Starting_Col => Starting_Col, Final_Col => Final_Col); end loop; -- Helps eigvec calculation with several matrices, (eg. Pas_Fib, Vandermonde) -- Next, Z_r is input to Apply_QR_to_Hessenberg, where it is (optionally) -- transformed into the set of eigenvectors of A. -- -- A is now in Upper_Hessenberg form, thanks to Z_r: A_true = Z_r A Z_r'. Apply_QR_to_Hessenberg (A, Z_r, W_r, W_i, Norm, Unscale_Eigs, Starting_Col, Final_Col, Eigenvectors_Desired, -- if true then Z_i will be initialized Id_of_Failed_Eig); -- If Eigenvectors_Desired = False then Z_i remains uninitialized, -- (which may free up space with large matrices). if Eigenvectors_Desired then Find_all_Eigenvectors (A, Z_r, Z_i, W_r, W_i, Norm, Starting_Col, Final_Col); Normalize_Column_Vectors (Z_r, Z_i, Starting_Col, Final_Col); for c in Starting_Col .. Final_Col loop W_r(c) := Unscale_Eigs * W_r(c); W_i(c) := Unscale_Eigs * W_i(c); end loop; end if; end Decompose; end Peters_Eigen;
-- A PNG stream is made of several "chunks" (see type PNG_Chunk_tag). -- The image itself is contained in the IDAT chunk(s). -- -- Steps for decoding an image (step numbers are from the ISO standard): -- -- 10: Inflate deflated data; at each output buffer (slide), -- process with step 9. -- 9: Read filter code (row begin), or unfilter bytes, go with step 8 -- 8: Display pixels these bytes represent; -- eventually, locate the interlaced image current point -- -- Reference: Portable Network Graphics (PNG) Specification (Second Edition) -- ISO/IEC 15948:2003 (E) -- W3C Recommendation 10 November 2003 -- http://www.w3.org/TR/PNG/ -- with GID.Buffering, GID.Decoding_PNG.Huffman; with Ada.Text_IO, Ada.Exceptions; package body GID.Decoding_PNG is generic type Number is mod <>; procedure Big_endian_number( from : in out Input_buffer; n : out Number ); pragma Inline(Big_endian_number); procedure Big_endian_number( from : in out Input_buffer; n : out Number ) is b: U8; begin n:= 0; for i in 1..Number'Size/8 loop Buffering.Get_Byte(from, b); n:= n * 256 + Number(b); end loop; end Big_endian_number; procedure Big_endian is new Big_endian_number( U32 ); use Ada.Exceptions; ---------- -- Read -- ---------- procedure Read (image: in out Image_descriptor; ch: out Chunk_head) is str4: String(1..4); b: U8; begin Big_endian(image.buffer, ch.length); for i in str4'Range loop Buffering.Get_Byte(image.buffer, b); str4(i):= Character'Val(b); end loop; begin ch.kind:= PNG_Chunk_tag'Value(str4); if some_trace then Ada.Text_IO.Put_Line( "Chunk [" & str4 & "], length:" & U32'Image(ch.length) ); end if; exception when Constraint_Error => Raise_Exception( error_in_image_data'Identity, "PNG chunk unknown: " & Integer'Image(Character'Pos(str4(1))) & Integer'Image(Character'Pos(str4(2))) & Integer'Image(Character'Pos(str4(3))) & Integer'Image(Character'Pos(str4(4))) & " (" & str4 & ')' ); end; end Read; package CRC32 is procedure Init( CRC: out Unsigned_32 ); function Final( CRC: Unsigned_32 ) return Unsigned_32; procedure Update( CRC: in out Unsigned_32; InBuf: Byte_array ); pragma Inline( Update ); end CRC32; package body CRC32 is CRC32_Table : array( Unsigned_32'(0)..255 ) of Unsigned_32; procedure Prepare_table is -- CRC-32 algorithm, ISO-3309 Seed: constant:= 16#EDB88320#; l: Unsigned_32; begin for i in CRC32_Table'Range loop l:= i; for bit in 0..7 loop if (l and 1) = 0 then l:= Shift_Right(l,1); else l:= Shift_Right(l,1) xor Seed; end if; end loop; CRC32_Table(i):= l; end loop; end Prepare_table; procedure Update( CRC: in out Unsigned_32; InBuf: Byte_array ) is local_CRC: Unsigned_32; begin local_CRC:= CRC ; for i in InBuf'Range loop local_CRC := CRC32_Table( 16#FF# and ( local_CRC xor Unsigned_32( InBuf(i) ) ) ) xor Shift_Right( local_CRC , 8 ); end loop; CRC:= local_CRC; end Update; table_empty: Boolean:= True; procedure Init( CRC: out Unsigned_32 ) is begin if table_empty then Prepare_table; table_empty:= False; end if; CRC:= 16#FFFF_FFFF#; end Init; function Final( CRC: Unsigned_32 ) return Unsigned_32 is begin return not CRC; end Final; end CRC32; ---------- -- Load -- ---------- procedure Load (image: in out Image_descriptor) is ---------------------- -- Load_specialized -- ---------------------- generic -- These values are invariant through the whole picture, -- so we can make them generic parameters. As a result, all -- "if", "case", etc. using them at the center of the decoding -- are optimized out at compile-time. interlaced : Boolean; bits_per_pixel : Positive; bytes_to_unfilter : Positive; -- ^ amount of bytes to unfilter at a time -- = Integer'Max(1, bits_per_pixel / 8); subformat_id : Natural; procedure Load_specialized; -- procedure Load_specialized is use GID.Buffering; subtype Mem_row_bytes_array is Byte_array(0..image.width*8); -- mem_row_bytes: array(0..1) of Mem_row_bytes_array; -- We need to memorize two image rows, for un-filtering curr_row: Natural:= 1; -- either current is 1 and old is 0, or the reverse subtype X_range is Integer range -1..image.width-1; subtype Y_range is Integer range 0..image.height-1; -- X position -1 is for the row's filter methode code x: X_range:= X_range'First; y: Y_range:= Y_range'First; x_max: X_range; -- for non-interlaced images: = X_range'Last y_max: Y_range; -- for non-interlaced images: = Y_range'Last pass: Positive range 1..7:= 1; -------------------------- -- ** 9: Unfiltering ** -- -------------------------- -- http://www.w3.org/TR/PNG/#9Filters type Filter_method_0 is (None, Sub, Up, Average, Paeth); current_filter: Filter_method_0; procedure Unfilter_bytes( f: in Byte_array; -- filtered u: out Byte_array -- unfiltered ) is pragma Inline(Unfilter_bytes); -- Byte positions (f is the byte to be unfiltered): -- -- c b -- a f a,b,c, p,pa,pb,pc,pr: Integer; j: Integer:= 0; begin if full_trace and then x = 0 then if y = 0 then Ada.Text_IO.New_Line; end if; Ada.Text_IO.Put_Line( "row" & Integer'Image(y) & ": filter= " & Filter_method_0'Image(current_filter) ); end if; -- -- !! find a way to have f99n0g04.png decoded correctly... -- seems a filter issue. -- case current_filter is when None => -- Recon(x) = Filt(x) u:= f; when Sub => -- Recon(x) = Filt(x) + Recon(a) if x > 0 then for i in f'Range loop u(u'First+j):= f(i) + mem_row_bytes(curr_row)((x-1)*bytes_to_unfilter+j); j:= j + 1; end loop; else u:= f; end if; when Up => -- Recon(x) = Filt(x) + Recon(b) if y > 0 then for i in f'Range loop u(u'First+j):= f(i) + mem_row_bytes(1-curr_row)(x*bytes_to_unfilter+j); j:= j + 1; end loop; else u:= f; end if; when Average => -- Recon(x) = Filt(x) + floor((Recon(a) + Recon(b)) / 2) for i in f'Range loop if x > 0 then a:= Integer(mem_row_bytes(curr_row)((x-1)*bytes_to_unfilter+j)); else a:= 0; end if; if y > 0 then b:= Integer(mem_row_bytes(1-curr_row)(x*bytes_to_unfilter+j)); else b:= 0; end if; u(u'First+j):= U8((Integer(f(i)) + (a+b)/2) mod 256); j:= j + 1; end loop; when Paeth => -- Recon(x) = Filt(x) + PaethPredictor(Recon(a), Recon(b), Recon(c)) for i in f'Range loop if x > 0 then a:= Integer(mem_row_bytes(curr_row)((x-1)*bytes_to_unfilter+j)); else a:= 0; end if; if y > 0 then b:= Integer(mem_row_bytes(1-curr_row)(x*bytes_to_unfilter+j)); else b:= 0; end if; if x > 0 and y > 0 then c:= Integer(mem_row_bytes(1-curr_row)((x-1)*bytes_to_unfilter+j)); else c:= 0; end if; p := a + b - c; pa:= abs(p - a); pb:= abs(p - b); pc:= abs(p - c); if pa <= pb and then pa <= pc then pr:= a; elsif pb <= pc then pr:= b; else pr:= c; end if; u(u'First+j):= f(i) + U8(pr); j:= j + 1; end loop; end case; j:= 0; for i in u'Range loop mem_row_bytes(curr_row)(x*bytes_to_unfilter+j):= u(i); j:= j + 1; end loop; -- if u'Length /= bytes_to_unfilter then -- raise Constraint_Error; -- end if; end Unfilter_bytes; filter_stat: array(Filter_method_0) of Natural:= (others => 0); ---------------------------------------------- -- ** 8: Interlacing and pass extraction ** -- ---------------------------------------------- -- http://www.w3.org/TR/PNG/#8Interlace -- Output bytes from decompression -- procedure Output_uncompressed( data : in Byte_array; reject: out Natural -- amount of bytes to be resent here next time, -- in order to have a full multi-byte pixel ) is -- Display of pixels coded on 8 bits per channel in the PNG stream procedure Out_Pixel_8(br, bg, bb, ba: U8) is pragma Inline(Out_Pixel_8); function Times_257(x: Primary_color_range) return Primary_color_range is pragma Inline(Times_257); begin return 16 * (16 * x) + x; -- this is 257 * x, = 16#0101# * x -- Numbers 8-bit -> no OA warning at instanciation. Returns x if type Primary_color_range is mod 2**8. end Times_257; begin case Primary_color_range'Modulus is when 256 => Put_Pixel( Primary_color_range(br), Primary_color_range(bg), Primary_color_range(bb), Primary_color_range(ba) ); when 65_536 => Put_Pixel( Times_257(Primary_color_range(br)), Times_257(Primary_color_range(bg)), Times_257(Primary_color_range(bb)), Times_257(Primary_color_range(ba)) -- Times_257 makes max intensity FF go to FFFF ); when others => raise invalid_primary_color_range; end case; end Out_Pixel_8; procedure Out_Pixel_Palette(ix: U8) is pragma Inline(Out_Pixel_Palette); color_idx: constant Natural:= Integer(ix); begin Out_Pixel_8( image.palette(color_idx).red, image.palette(color_idx).green, image.palette(color_idx).blue, 255 ); end Out_Pixel_Palette; -- Display of pixels coded on 16 bits per channel in the PNG stream procedure Out_Pixel_16(br, bg, bb, ba: U16) is pragma Inline(Out_Pixel_16); begin case Primary_color_range'Modulus is when 256 => Put_Pixel( Primary_color_range(br / 256), Primary_color_range(bg / 256), Primary_color_range(bb / 256), Primary_color_range(ba / 256) ); when 65_536 => Put_Pixel( Primary_color_range(br), Primary_color_range(bg), Primary_color_range(bb), Primary_color_range(ba) ); when others => raise invalid_primary_color_range; end case; end Out_Pixel_16; procedure Inc_XY is pragma Inline(Inc_XY); xm, ym: Integer; begin if x < x_max then x:= x + 1; if interlaced then -- Position of pixels depending on pass: -- -- 1 6 4 6 2 6 4 6 -- 7 7 7 7 7 7 7 7 -- 5 6 5 6 5 6 5 6 -- 7 7 7 7 7 7 7 7 -- 3 6 4 6 3 6 4 6 -- 7 7 7 7 7 7 7 7 -- 5 6 5 6 5 6 5 6 -- 7 7 7 7 7 7 7 7 case pass is when 1 => Set_X_Y( x*8, Y_range'Last - y*8); when 2 => Set_X_Y(4 + x*8, Y_range'Last - y*8); when 3 => Set_X_Y( x*4, Y_range'Last - 4 - y*8); when 4 => Set_X_Y(2 + x*4, Y_range'Last - y*4); when 5 => Set_X_Y( x*2, Y_range'Last - 2 - y*4); when 6 => Set_X_Y(1 + x*2, Y_range'Last - y*2); when 7 => null; -- nothing to to, pixel are contiguous end case; end if; else x:= X_range'First; -- New row if y < y_max then y:= y + 1; curr_row:= 1-curr_row; -- swap row index for filtering if not interlaced then Feedback((y*100)/image.height); end if; elsif interlaced then -- last row has beed displayed while pass < 7 loop pass:= pass + 1; y:= 0; case pass is when 1 => null; when 2 => xm:= (image.width+3)/8 - 1; ym:= (image.height+7)/8 - 1; when 3 => xm:= (image.width+3)/4 - 1; ym:= (image.height+3)/8 - 1; when 4 => xm:= (image.width+1)/4 - 1; ym:= (image.height+3)/4 - 1; when 5 => xm:= (image.width+1)/2 - 1; ym:= (image.height+1)/4 - 1; when 6 => xm:= (image.width )/2 - 1; ym:= (image.height+1)/2 - 1; when 7 => xm:= image.width - 1; ym:= image.height/2 - 1; end case; if xm >=0 and xm <= X_range'Last and ym in Y_range then -- This pass is not empty (otherwise, we will continue -- to the next one, if any). x_max:= xm; y_max:= ym; exit; end if; end loop; end if; end if; end Inc_XY; uf: Byte_array(0..15); -- unfiltered bytes for a pixel w1, w2: U16; i: Integer; begin if some_trace then Ada.Text_IO.Put("[UO]"); end if; -- Depending on the row size, bpp, etc., we can have -- several rows, or less than one, being displayed -- with the present uncompressed data batch. -- i:= data'First; if i > data'Last then reject:= 0; return; -- data is empty, do nothing end if; -- -- Main loop over data -- loop if x = X_range'First then -- pseudo-column for filter method exit when i > data'Last; begin current_filter:= Filter_method_0'Val(data(i)); if some_trace then filter_stat(current_filter):= filter_stat(current_filter) + 1; end if; exception when Constraint_Error => Raise_Exception( error_in_image_data'Identity, "PNG: wrong filter code, row #" & Integer'Image(y) & " code:" & U8'Image(data(i)) ); end; if interlaced then case pass is when 1..6 => null; -- Set_X_Y for each pixel when 7 => Set_X_Y(0, Y_range'Last - 1 - y*2); end case; else Set_X_Y(0, Y_range'Last - y); end if; i:= i + 1; else -- normal pixel -- -- We quit the loop if all data has been used (except for an -- eventual incomplete pixel) exit when i > data'Last - (bytes_to_unfilter - 1); -- NB, for per-channel bpp < 8: -- 7.2 Scanlines - some low-order bits of the -- last byte of a scanline may go unused. case subformat_id is when 0 => ----------------------- -- Type 0: Greyscale -- ----------------------- case bits_per_pixel is when 1 | 2 | 4 => Unfilter_bytes(data(i..i), uf(0..0)); i:= i + 1; declare b: U8; shift: Integer:= 8 - bits_per_pixel; max: constant U8:= U8(Shift_Left(Unsigned_32'(1), bits_per_pixel)-1); -- Scaling factor to obtain the correct color value on a 0..255 range. -- The division is exact in all cases (bpp=8,4,2,1), -- since 255 = 3 * 5 * 17 and max = 255, 15, 3 or 1. -- This factor ensures: 0 -> 0, max -> 255 factor: constant U8:= 255 / max; begin -- loop through the number of pixels in this byte: for k in reverse 1..8/bits_per_pixel loop b:= (max and U8(Shift_Right(Unsigned_8(uf(0)), shift))) * factor; shift:= shift - bits_per_pixel; Out_Pixel_8(b, b, b, 255); exit when x >= x_max or k = 1; Inc_XY; end loop; end; when 8 => -- NB: with bpp as generic param, this case could be merged -- into the general 1,2,4[,8] case without loss of performance -- if the compiler is smart enough to simplify the code, given -- the value of bits_per_pixel. -- But we let it here for two reasons: -- 1) a compiler might be not smart enough -- 2) it is a very simple case, perhaps helpful for -- understanding the algorithm. Unfilter_bytes(data(i..i), uf(0..0)); i:= i + 1; Out_Pixel_8(uf(0), uf(0), uf(0), 255); when 16 => Unfilter_bytes(data(i..i+1), uf(0..1)); i:= i + 2; w1:= U16(uf(0)) * 256 + U16(uf(1)); Out_Pixel_16(w1, w1, w1, 65535); when others => null; -- undefined in PNG standard end case; when 2 => ----------------- -- Type 2: RGB -- ----------------- case bits_per_pixel is when 24 => Unfilter_bytes(data(i..i+2), uf(0..2)); i:= i + 3; Out_Pixel_8(uf(0), uf(1), uf(2), 255); when 48 => Unfilter_bytes(data(i..i+5), uf(0..5)); i:= i + 6; Out_Pixel_16( U16(uf(0)) * 256 + U16(uf(1)), U16(uf(2)) * 256 + U16(uf(3)), U16(uf(4)) * 256 + U16(uf(5)), 65_535 ); when others => null; end case; when 3 => ------------------------------ -- Type 3: RGB with palette -- ------------------------------ Unfilter_bytes(data(i..i), uf(0..0)); i:= i + 1; case bits_per_pixel is when 1 | 2 | 4 => declare shift: Integer:= 8 - bits_per_pixel; max: constant U8:= U8(Shift_Left(Unsigned_32'(1), bits_per_pixel)-1); begin -- loop through the number of pixels in this byte: for k in reverse 1..8/bits_per_pixel loop Out_Pixel_Palette(max and U8(Shift_Right(Unsigned_8(uf(0)), shift))); shift:= shift - bits_per_pixel; exit when x >= x_max or k = 1; Inc_XY; end loop; end; when 8 => -- Same remark for this case (8bpp) as -- within Image Type 0 / Greyscale above Out_Pixel_Palette(uf(0)); when others => null; end case; when 4 => ------------------------------- -- Type 4: Greyscale & Alpha -- ------------------------------- case bits_per_pixel is when 16 => Unfilter_bytes(data(i..i+1), uf(0..1)); i:= i + 2; Out_Pixel_8(uf(0), uf(0), uf(0), uf(1)); when 32 => Unfilter_bytes(data(i..i+3), uf(0..3)); i:= i + 4; w1:= U16(uf(0)) * 256 + U16(uf(1)); w2:= U16(uf(2)) * 256 + U16(uf(3)); Out_Pixel_16(w1, w1, w1, w2); when others => null; -- undefined in PNG standard end case; when 6 => ------------------ -- Type 6: RGBA -- ------------------ case bits_per_pixel is when 32 => Unfilter_bytes(data(i..i+3), uf(0..3)); i:= i + 4; Out_Pixel_8(uf(0), uf(1), uf(2), uf(3)); when 64 => Unfilter_bytes(data(i..i+7), uf(0..7)); i:= i + 8; Out_Pixel_16( U16(uf(0)) * 256 + U16(uf(1)), U16(uf(2)) * 256 + U16(uf(3)), U16(uf(4)) * 256 + U16(uf(5)), U16(uf(6)) * 256 + U16(uf(7)) ); when others => null; end case; when others => null; -- Unknown - exception already raised at header level end case; end if; Inc_XY; end loop; -- i is between data'Last-(bytes_to_unfilter-2) and data'Last+1 reject:= (data'Last + 1) - i; if reject > 0 then if some_trace then Ada.Text_IO.Put("[rj" & Integer'Image(reject) & ']'); end if; end if; end Output_uncompressed; ch: Chunk_head; -- Out of some intelligent design, there might be an IDAT chunk -- boundary anywhere inside the zlib compressed block... procedure Jump_IDAT is dummy: U32; begin Big_endian(image.buffer, dummy); -- ending chunk's CRC -- New chunk begins here. loop Read(image, ch); exit when ch.kind /= IDAT or ch.length > 0; end loop; if ch.kind /= IDAT then Raise_Exception( error_in_image_data'Identity, "PNG additional data chunk must be an IDAT" ); end if; end Jump_IDAT; --------------------------------------------------------------------- -- ** 10: Decompression ** -- -- Excerpt and simplification from UnZip.Decompress (Inflate only) -- --------------------------------------------------------------------- -- http://www.w3.org/TR/PNG/#10Compression -- Size of sliding dictionary and circular output buffer wsize: constant:= 16#10000#; -------------------------------------- -- Specifications of UnZ_* packages -- -------------------------------------- package UnZ_Glob is -- I/O Buffers -- > Sliding dictionary for unzipping, and output buffer as well slide: Byte_array( 0..wsize ); slide_index: Integer:= 0; -- Current Position in slide Zip_EOF : constant Boolean:= False; crc32val : Unsigned_32; -- crc calculated from data end UnZ_Glob; package UnZ_IO is procedure Init_Buffers; procedure Read_raw_byte ( bt : out U8 ); pragma Inline(Read_raw_byte); package Bit_buffer is procedure Init; -- Read at least n bits into the bit buffer, returns the n first bits function Read ( n: Natural ) return Integer; pragma Inline(Read); function Read_U32 ( n: Natural ) return Unsigned_32; pragma Inline(Read_U32); -- Dump n bits no longer needed from the bit buffer procedure Dump ( n: Natural ); pragma Inline(Dump); procedure Dump_to_byte_boundary; function Read_and_dump( n: Natural ) return Integer; pragma Inline(Read_and_dump); function Read_and_dump_U32( n: Natural ) return Unsigned_32; pragma Inline(Read_and_dump_U32); end Bit_buffer; procedure Flush ( x: Natural ); -- directly from slide to output stream procedure Flush_if_full(W: in out Integer); pragma Inline(Flush_if_full); procedure Copy( distance, length: Natural; index : in out Natural ); pragma Inline(Copy); end UnZ_IO; package UnZ_Meth is deflate_e_mode: constant Boolean:= False; procedure Inflate; end UnZ_Meth; ------------------------------ -- Bodies of UnZ_* packages -- ------------------------------ package body UnZ_IO is procedure Init_Buffers is begin UnZ_Glob.slide_index := 0; Bit_buffer.Init; CRC32.Init( UnZ_Glob.crc32val ); end Init_Buffers; procedure Read_raw_byte ( bt : out U8 ) is begin if ch.length = 0 then -- We hit the end of a PNG 'IDAT' chunk, so we go to the next one -- - in petto, it's strange design, but well... -- This "feature" has taken some time (and nerves) to be addressed. -- Incidentally, I have reprogrammed the whole Huffman -- decoding, and looked at many other wrong places to solve -- the mystery. Jump_IDAT; end if; Buffering.Get_Byte(image.buffer, bt); ch.length:= ch.length - 1; end Read_raw_byte; package body Bit_buffer is B : Unsigned_32; K : Integer; procedure Init is begin B := 0; K := 0; end Init; procedure Need( n : Natural ) is pragma Inline(Need); bt: U8; begin while K < n loop Read_raw_byte( bt ); B:= B or Shift_Left( Unsigned_32( bt ), K ); K:= K + 8; end loop; end Need; procedure Dump ( n : Natural ) is begin B := Shift_Right(B, n ); K := K - n; end Dump; procedure Dump_to_byte_boundary is begin Dump ( K mod 8 ); end Dump_to_byte_boundary; function Read_U32 ( n: Natural ) return Unsigned_32 is begin Need(n); return B and (Shift_Left(1,n) - 1); end Read_U32; function Read ( n: Natural ) return Integer is begin return Integer(Read_U32(n)); end Read; function Read_and_dump( n: Natural ) return Integer is res: Integer; begin res:= Read(n); Dump(n); return res; end Read_and_dump; function Read_and_dump_U32( n: Natural ) return Unsigned_32 is res: Unsigned_32; begin res:= Read_U32(n); Dump(n); return res; end Read_and_dump_U32; end Bit_buffer; old_bytes: Natural:= 0; -- how many bytes to be resent from last Inflate output byte_mem: Byte_array(1..8); procedure Flush ( x: Natural ) is begin if full_trace then Ada.Text_IO.Put("[Flush..." & Integer'Image(x)); end if; CRC32.Update( UnZ_Glob.crc32val, UnZ_Glob.slide( 0..x-1 ) ); if old_bytes > 0 then declare app: constant Byte_array:= byte_mem(1..old_bytes) & UnZ_Glob.slide(0..x-1); begin Output_uncompressed(app, old_bytes); -- In extreme cases (x very small), we might have some of -- the rejected bytes from byte_mem. if old_bytes > 0 then byte_mem(1..old_bytes):= app(app'Last-(old_bytes-1)..app'Last); end if; end; else Output_uncompressed(UnZ_Glob.slide(0..x-1), old_bytes); if old_bytes > 0 then byte_mem(1..old_bytes):= UnZ_Glob.slide(x-old_bytes..x-1); end if; end if; if full_trace then Ada.Text_IO.Put_Line("finished]"); end if; end Flush; procedure Flush_if_full(W: in out Integer) is begin if W = wsize then Flush(wsize); W:= 0; end if; end Flush_if_full; ---------------------------------------------------- -- Reproduction of sequences in the output slide. -- ---------------------------------------------------- -- Internal: procedure Adjust_to_Slide( source : in out Integer; remain : in out Natural; part : out Integer; index: Integer) is pragma Inline(Adjust_to_Slide); begin source:= source mod wsize; -- source and index are now in 0..WSize-1 if source > index then part:= wsize-source; else part:= wsize-index; end if; -- NB: part is in 1..WSize (part cannot be 0) if part > remain then part:= remain; end if; -- Now part <= remain remain:= remain - part; -- NB: remain cannot be < 0 end Adjust_to_Slide; procedure Copy_range(source, index: in out Natural; amount: Positive) is pragma Inline(Copy_range); begin if abs (index - source) < amount then -- if source >= index, the effect of copy is -- just like the non-overlapping case for count in reverse 1..amount loop UnZ_Glob.slide(index):= UnZ_Glob.slide(source); index := index + 1; source:= source + 1; end loop; else -- non-overlapping -> copy slice UnZ_Glob.slide( index .. index+amount-1 ):= UnZ_Glob.slide( source..source+amount-1 ); index := index + amount; source:= source + amount; end if; end Copy_range; -- The copying routines: procedure Copy( distance, length: Natural; index : in out Natural ) is source,part,remain: Integer; begin source:= index - distance; remain:= length; loop Adjust_to_Slide(source,remain,part, index); Copy_range(source, index, part); Flush_if_full(index); exit when remain = 0; end loop; end Copy; end UnZ_IO; package body UnZ_Meth is use GID.Decoding_PNG.Huffman; --------[ Method: Inflate ]-------- procedure Inflate_Codes ( Tl, Td: p_Table_list; Bl, Bd: Integer ) is CT : p_HufT_table; -- current table CT_idx : Integer; -- current table index length : Natural; E : Integer; -- table entry flag/number of extra bits W : Integer:= UnZ_Glob.slide_index; -- more local variable for slide index begin if full_trace then Ada.Text_IO.Put_Line("Begin Inflate_codes"); end if; -- inflate the coded data main_loop: while not UnZ_Glob.Zip_EOF loop CT:= Tl.table; CT_idx:= UnZ_IO.Bit_buffer.Read(Bl); loop E := CT(CT_idx).extra_bits; exit when E <= 16; if E = invalid then raise error_in_image_data; end if; -- then it's a literal UnZ_IO.Bit_buffer.Dump( CT(CT_idx).bits ); E:= E - 16; CT:= CT(CT_idx).next_table; CT_idx := UnZ_IO.Bit_buffer.Read(E); end loop; UnZ_IO.Bit_buffer.Dump ( CT(CT_idx).bits ); case E is when 16 => -- CTE.N is a Litteral UnZ_Glob.slide ( W ) := U8( CT(CT_idx).n ); W:= W + 1; UnZ_IO.Flush_if_full(W); when 15 => -- End of block (EOB) if full_trace then Ada.Text_IO.Put_Line("Exit Inflate_codes, e=15 EOB"); end if; exit main_loop; when others => -- We have a length/distance -- Get length of block to copy: length:= CT(CT_idx).n + UnZ_IO.Bit_buffer.Read_and_dump(E); -- Decode distance of block to copy: CT:= Td.table; CT_idx := UnZ_IO.Bit_buffer.Read(Bd); loop E := CT(CT_idx).extra_bits; exit when E <= 16; if E = invalid then raise error_in_image_data; end if; UnZ_IO.Bit_buffer.Dump( CT(CT_idx).bits ); E:= E - 16; CT:= CT(CT_idx).next_table; CT_idx := UnZ_IO.Bit_buffer.Read(E); end loop; UnZ_IO.Bit_buffer.Dump( CT(CT_idx).bits ); UnZ_IO.Copy( distance => CT(CT_idx).n + UnZ_IO.Bit_buffer.Read_and_dump(E), length => length, index => W ); end case; end loop main_loop; UnZ_Glob.slide_index:= W; if full_trace then Ada.Text_IO.Put_Line("End Inflate_codes"); end if; end Inflate_Codes; procedure Inflate_stored_block is -- Actually, nothing to inflate N : Integer; begin if full_trace then Ada.Text_IO.Put_Line("Begin Inflate_stored_block"); end if; UnZ_IO.Bit_buffer.Dump_to_byte_boundary; -- Get the block length and its complement N:= UnZ_IO.Bit_buffer.Read_and_dump( 16 ); if N /= Integer( (not UnZ_IO.Bit_buffer.Read_and_dump_U32(16)) and 16#ffff#) then raise error_in_image_data; end if; while N > 0 and then not UnZ_Glob.Zip_EOF loop -- Read and output the non-compressed data N:= N - 1; UnZ_Glob.slide ( UnZ_Glob.slide_index ) := U8( UnZ_IO.Bit_buffer.Read_and_dump(8) ); UnZ_Glob.slide_index:= UnZ_Glob.slide_index + 1; UnZ_IO.Flush_if_full(UnZ_Glob.slide_index); end loop; if full_trace then Ada.Text_IO.Put_Line("End Inflate_stored_block"); end if; end Inflate_stored_block; -- Copy lengths for literal codes 257..285 copy_lengths_literal : Length_array( 0..30 ) := ( 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 ); -- Extra bits for literal codes 257..285 extra_bits_literal : Length_array( 0..30 ) := ( 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, invalid, invalid ); -- Copy offsets for distance codes 0..29 (30..31: deflate_e) copy_offset_distance : constant Length_array( 0..31 ) := ( 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 32769, 49153 ); -- Extra bits for distance codes extra_bits_distance : constant Length_array( 0..31 ) := ( 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14 ); max_dist: Integer:= 29; -- changed to 31 for deflate_e procedure Inflate_fixed_block is Tl, -- literal/length code table Td : p_Table_list; -- distance code table Bl, Bd : Integer; -- lookup bits for tl/bd huft_incomplete : Boolean; -- length list for HufT_build (literal table) L: constant Length_array( 0..287 ):= ( 0..143=> 8, 144..255=> 9, 256..279=> 7, 280..287=> 8); begin if full_trace then Ada.Text_IO.Put_Line("Begin Inflate_fixed_block"); end if; -- make a complete, but wrong code set Bl := 7; HufT_build( L, 257, copy_lengths_literal, extra_bits_literal, Tl, Bl, huft_incomplete ); -- Make an incomplete code set Bd := 5; begin HufT_build( (0..max_dist => 5), 0, copy_offset_distance, extra_bits_distance, Td, Bd, huft_incomplete ); if huft_incomplete then if full_trace then Ada.Text_IO.Put_Line( "td is incomplete, pointer=null: " & Boolean'Image(Td=null) ); end if; end if; exception when huft_out_of_memory | huft_error => HufT_free( Tl ); raise error_in_image_data; end; Inflate_Codes ( Tl, Td, Bl, Bd ); HufT_free ( Tl ); HufT_free ( Td ); if full_trace then Ada.Text_IO.Put_Line("End Inflate_fixed_block"); end if; end Inflate_fixed_block; procedure Inflate_dynamic_block is bit_order : constant array ( 0..18 ) of Natural := ( 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ); Lbits : constant:= 9; Dbits : constant:= 6; current_length: Natural:= 0; defined, number_of_lengths: Natural; Tl, -- literal/length code tables Td : p_Table_list; -- distance code tables CT_dyn_idx : Integer; -- current table element Bl, Bd : Integer; -- lookup bits for tl/bd Nb : Natural; -- number of bit length codes Nl : Natural; -- number of literal length codes Nd : Natural; -- number of distance codes -- literal/length and distance code lengths Ll: Length_array( 0 .. 288+32-1 ):= (others=> 0); huft_incomplete : Boolean; procedure Repeat_length_code( amount: Natural ) is begin if defined + amount > number_of_lengths then raise error_in_image_data; end if; for c in reverse 1..amount loop Ll ( defined ) := Natural_M32(current_length); defined:= defined + 1; end loop; end Repeat_length_code; begin if full_trace then Ada.Text_IO.Put_Line("Begin Inflate_dynamic_block"); end if; -- Read in table lengths Nl := 257 + UnZ_IO.Bit_buffer.Read_and_dump(5); Nd := 1 + UnZ_IO.Bit_buffer.Read_and_dump(5); Nb := 4 + UnZ_IO.Bit_buffer.Read_and_dump(4); if Nl > 288 or else Nd > 32 then raise error_in_image_data; end if; -- Read in bit-length-code lengths. -- The rest, Ll( Bit_Order( Nb .. 18 ) ), is already = 0 for J in 0 .. Nb - 1 loop Ll ( bit_order( J ) ) := Natural_M32(UnZ_IO.Bit_buffer.Read_and_dump(3)); end loop; -- Build decoding table for trees--single level, 7 bit lookup Bl := 7; begin HufT_build ( Ll( 0..18 ), 19, empty, empty, Tl, Bl, huft_incomplete ); if huft_incomplete then HufT_free(Tl); raise error_in_image_data; end if; exception when others => raise error_in_image_data; end; -- Read in literal and distance code lengths number_of_lengths := Nl + Nd; defined := 0; current_length := 0; while defined < number_of_lengths loop CT_dyn_idx:= UnZ_IO.Bit_buffer.Read(Bl); UnZ_IO.Bit_buffer.Dump( Tl.table(CT_dyn_idx).bits ); case Tl.table(CT_dyn_idx).n is when 0..15 => -- length of code in bits (0..15) current_length:= Tl.table(CT_dyn_idx).n; Ll (defined) := Natural_M32(current_length); defined:= defined + 1; when 16 => -- repeat last length 3 to 6 times Repeat_length_code(3 + UnZ_IO.Bit_buffer.Read_and_dump(2)); when 17 => -- 3 to 10 zero length codes current_length:= 0; Repeat_length_code(3 + UnZ_IO.Bit_buffer.Read_and_dump(3)); when 18 => -- 11 to 138 zero length codes current_length:= 0; Repeat_length_code(11 + UnZ_IO.Bit_buffer.Read_and_dump(7)); when others => if full_trace then Ada.Text_IO.Put_Line( "Illegal length code: " & Integer'Image(Tl.table(CT_dyn_idx).n) ); end if; end case; end loop; HufT_free ( Tl ); -- free decoding table for trees -- Build the decoding tables for literal/length codes Bl := Lbits; begin HufT_build ( Ll( 0..Nl-1 ), 257, copy_lengths_literal, extra_bits_literal, Tl, Bl, huft_incomplete ); if huft_incomplete then HufT_free(Tl); raise error_in_image_data; end if; exception when others => raise error_in_image_data; end; -- Build the decoding tables for distance codes Bd := Dbits; begin HufT_build ( Ll( Nl..Nl+Nd-1 ), 0, copy_offset_distance, extra_bits_distance, Td, Bd, huft_incomplete ); if huft_incomplete then -- do nothing! if full_trace then Ada.Text_IO.Put_Line("PKZIP 1.93a bug workaround"); end if; end if; exception when huft_out_of_memory | huft_error => HufT_free(Tl); raise error_in_image_data; end; -- Decompress until an end-of-block code Inflate_Codes ( Tl, Td, Bl, Bd ); HufT_free ( Tl ); HufT_free ( Td ); if full_trace then Ada.Text_IO.Put_Line("End Inflate_dynamic_block"); end if; end Inflate_dynamic_block; procedure Inflate_Block( last_block: out Boolean ) is begin last_block:= Boolean'Val(UnZ_IO.Bit_buffer.Read_and_dump(1)); case UnZ_IO.Bit_buffer.Read_and_dump(2) is -- Block type = 0,1,2,3 when 0 => Inflate_stored_block; when 1 => Inflate_fixed_block; when 2 => Inflate_dynamic_block; when others => raise error_in_image_data; -- Bad block type (3) end case; end Inflate_Block; procedure Inflate is is_last_block: Boolean; blocks: Positive:= 1; begin if deflate_e_mode then copy_lengths_literal(28):= 3; -- instead of 258 extra_bits_literal(28):= 16; -- instead of 0 max_dist:= 31; end if; loop Inflate_Block ( is_last_block ); exit when is_last_block; blocks:= blocks+1; end loop; UnZ_IO.Flush( UnZ_Glob.slide_index ); UnZ_Glob.slide_index:= 0; if some_trace then Ada.Text_IO.Put("# blocks:" & Integer'Image(blocks)); end if; UnZ_Glob.crc32val := CRC32.Final( UnZ_Glob.crc32val ); end Inflate; end UnZ_Meth; -------------------------------------------------------------------- -- End of the Decompression part, and of UnZip.Decompress excerpt -- -------------------------------------------------------------------- b: U8; z_crc, dummy: U32; begin -- Load_specialized -- -- For optimization reasons, bytes_to_unfilter is passed as a -- generic parameter but should be always as below right to "/=" : -- if bytes_to_unfilter /= Integer'Max(1, bits_per_pixel / 8) then raise Program_Error; end if; if interlaced then x_max:= (image.width+7)/8 - 1; y_max:= (image.height+7)/8 - 1; else x_max:= X_range'Last; y_max:= Y_range'Last; end if; main_chunk_loop: loop loop Read(image, ch); exit when ch.kind = IEND or ch.length > 0; end loop; case ch.kind is when IEND => -- 11.2.5 IEND Image trailer exit main_chunk_loop; when IDAT => -- 11.2.4 IDAT Image data -- -- NB: the compressed data may hold on several IDAT chunks. -- It means that right in the middle of compressed data, you -- can have a chunk crc, and a new IDAT header!... -- UnZ_IO.Read_raw_byte(b); -- zlib compression method/flags code UnZ_IO.Read_raw_byte(b); -- Additional flags/check bits -- UnZ_IO.Init_Buffers; -- ^ we indicate that we have a byte reserve of chunk's length, -- minus both zlib header bytes. UnZ_Meth.Inflate; z_crc:= 0; for i in 1..4 loop begin UnZ_IO.Read_raw_byte(b); exception when error_in_image_data => -- vicious IEND at the wrong place -- basi4a08.png test image (corrupt imho) exit main_chunk_loop; end; z_crc:= z_crc * 256 + U32(b); end loop; -- z_crc : zlib Check value -- if z_crc /= U32(UnZ_Glob.crc32val) then -- ada.text_io.put(z_crc 'img & UnZ_Glob.crc32val'img); -- Raise_exception( -- error_in_image_data'Identity, -- "PNG: deflate stream corrupt" -- ); -- end if; -- ** Mystery: this check fail even with images which decompress perfectly -- ** Is CRC init value different between zip and zlib ? Is it Adler32 ? Big_endian(image.buffer, dummy); -- chunk's CRC -- last IDAT chunk's CRC (then, on compressed data) -- when tEXt => -- 11.3.4.3 tEXt Textual data for i in 1..ch.length loop Get_Byte(image.buffer, b); if some_trace then if b=0 then -- separates keyword from message Ada.Text_IO.New_Line; else Ada.Text_IO.Put(Character'Val(b)); end if; end if; end loop; Big_endian(image.buffer, dummy); -- chunk's CRC when others => -- Skip chunk data and CRC for i in 1..ch.length + 4 loop Get_Byte(image.buffer, b); end loop; end case; end loop main_chunk_loop; if some_trace then for f in Filter_method_0 loop Ada.Text_IO.Put_Line( "Filter: " & Filter_method_0'Image(f) & Integer'Image(filter_stat(f)) ); end loop; end if; Feedback(100); end Load_specialized; -- Instances of Load_specialized, with hard-coded parameters. -- They may take an insane amount of time to compile, and bloat the -- .o code , but are significantly faster since they make the -- compiler skip corresponding tests at pixel level. -- These instances are for most current PNG sub-formats. procedure Load_interlaced_1pal is new Load_specialized(True, 1, 1, 3); procedure Load_interlaced_2pal is new Load_specialized(True, 2, 1 ,3); procedure Load_interlaced_4pal is new Load_specialized(True, 4, 1, 3); procedure Load_interlaced_8pal is new Load_specialized(True, 8, 1, 3); procedure Load_interlaced_24 is new Load_specialized(True, 24, 3, 2); procedure Load_interlaced_32 is new Load_specialized(True, 32, 4, 6); -- procedure Load_straight_1pal is new Load_specialized(False, 1, 1, 3); procedure Load_straight_2pal is new Load_specialized(False, 2, 1, 3); procedure Load_straight_4pal is new Load_specialized(False, 4, 1, 3); procedure Load_straight_8pal is new Load_specialized(False, 8, 1, 3); procedure Load_straight_24 is new Load_specialized(False, 24, 3, 2); procedure Load_straight_32 is new Load_specialized(False, 32, 4, 6); -- -- For unusual sub-formats, we prefer to fall back to the -- slightly slower, general version, where parameters values -- are not known at compile-time: -- procedure Load_general is new Load_specialized( interlaced => image.interlaced, bits_per_pixel => image.bits_per_pixel, bytes_to_unfilter => Integer'Max(1, image.bits_per_pixel / 8), subformat_id => image.subformat_id ); begin -- Load -- -- All these case tests are better done at the picture -- level than at the pixel level. -- case image.subformat_id is when 2 => -- RGB case image.bits_per_pixel is when 24 => if image.interlaced then Load_interlaced_24; else Load_straight_24; end if; when others => Load_general; end case; when 3 => -- Palette case image.bits_per_pixel is when 1 => if image.interlaced then Load_interlaced_1pal; else Load_straight_1pal; end if; when 2 => if image.interlaced then Load_interlaced_2pal; else Load_straight_2pal; end if; when 4 => if image.interlaced then Load_interlaced_4pal; else Load_straight_4pal; end if; when 8 => if image.interlaced then Load_interlaced_8pal; else Load_straight_8pal; end if; when others => Load_general; end case; when 6 => -- RGBA case image.bits_per_pixel is when 32 => if image.interlaced then Load_interlaced_32; else Load_straight_32; end if; when others => Load_general; end case; when others => Load_general; end case; end Load; end GID.Decoding_PNG;
with gel.Sprite, gel.World; package gel.Terrain -- -- Provides a constructor for heightmap terrain. -- is function new_Terrain (World : in gel.World.view; heights_File : in String; texture_File : in String := ""; Scale : in math.Vector_3 := (1.0, 1.0, 1.0)) return access gel.Sprite.Grid; end gel.Terrain;
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Localization, Internationalization, Globalization for Ada -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2009-2017, 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$ ------------------------------------------------------------------------------ pragma Ada_2012; with Ada.Unchecked_Deallocation; with Matreshka.Atomics.Generic_Test_And_Set; with Matreshka.Internals.Strings.Configuration; package body Matreshka.Internals.Strings is use Matreshka.Internals.Strings.Configuration; use Matreshka.Internals.Utf16; use Matreshka.Internals.Unicode; Growth_Factor : constant := 32; -- The growth factor controls how much extra space is allocated when -- we have to increase the size of an allocated unbounded string. By -- allocating extra space, we avoid the need to reallocate on every -- append, particularly important when a string is built up by repeated -- append operations of small pieces. This is expressed as a factor so -- 32 means add 1/32 of the length of the string as growth space. Min_Mul_Alloc : constant := Standard'Maximum_Alignment * Standard'Storage_Unit / Code_Unit_16'Size; -- Allocation will be done by a multiple of Min_Mul_Alloc. This causes -- no memory loss as most (all?) malloc implementations are obliged to -- align the returned memory on the maximum alignment as malloc does not -- know the target alignment. procedure Free is new Ada.Unchecked_Deallocation (Index_Map, Index_Map_Access); procedure Free is new Ada.Unchecked_Deallocation (Shared_Sort_Key, Shared_Sort_Key_Access); procedure Free is new Ada.Unchecked_Deallocation (Shared_String, Shared_String_Access); function Test_And_Set is new Matreshka.Atomics.Generic_Test_And_Set (Index_Map, Index_Map_Access); function Aligned_Size (Size : Utf16_String_Index) return Utf16_String_Index; pragma Inline (Aligned_Size); -- Returns recommended size of the shared string which is greater or -- equal to specified. Calculation take in sense alignment of the allocated -- memory segments to use memory effectively by Append/Insert/etc -- operations. ------------------ -- Aligned_Size -- ------------------ function Aligned_Size (Size : Utf16_String_Index) return Utf16_String_Index is Static_Size : constant Utf16_String_Index := (Shared_Empty'Size - Code_Unit_16'Size * (Shared_Empty.Capacity + 1)) / Code_Unit_16'Size; -- Total size of all static components in Code_Unit_16 units. pragma Assert ((Shared_Empty'Size - Code_Unit_16'Size * (Shared_Empty.Capacity + 1)) mod Code_Unit_16'Size = 0); -- Reminder must be zero to compute value correctly. begin return (((Static_Size + Size + Size / Growth_Factor) / Min_Mul_Alloc + 1) * Min_Mul_Alloc - Static_Size); end Aligned_Size; -------------- -- Allocate -- -------------- function Allocate (Size : Matreshka.Internals.Utf16.Utf16_String_Index) return not null Shared_String_Access is pragma Assert (Size /= 0); begin return new Shared_String (Aligned_Size (Size) - 1); end Allocate; ------------------- -- Can_Be_Reused -- ------------------- function Can_Be_Reused (Self : not null Shared_String_Access; Size : Matreshka.Internals.Utf16.Utf16_String_Index) return Boolean is begin return Self /= Shared_Empty'Access and Self.Capacity > Size and Matreshka.Atomics.Counters.Is_One (Self.Counter); end Can_Be_Reused; ----------------------- -- Compute_Index_Map -- ----------------------- procedure Compute_Index_Map (Self : in out Shared_String) is pragma Assert (Self.Length /= 0); Map : Index_Map_Access := Self.Index_Map; Current : Utf16_String_Index := 0; begin -- Calculate index map if it is unavailable for now. if Map = null then Map := new Index_Map (Utf16_String_Index (Self.Length) - 1); for J in Map.Map'Range loop Map.Map (J) := Current; if Self.Value (Current) in High_Surrogate_Utf16_Code_Unit then Current := Current + 2; else Current := Current + 1; end if; end loop; if not Test_And_Set (Self.Index_Map, null, Map) then -- Operation can fail if mapping has been calculated by -- another thread. In this case computed result is -- dropped, memory freed and already calculated mapping -- is reused. Free (Map); end if; end if; end Compute_Index_Map; ----------------- -- Dereference -- ----------------- procedure Dereference (Self : in out Shared_Sort_Key_Access) is pragma Assert (Self /= null); pragma Suppress (Access_Check); begin if Self /= Shared_Empty_Key'Access and then Matreshka.Atomics.Counters.Decrement (Self.Counter) then Free (Self); end if; Self := null; end Dereference; ----------------- -- Dereference -- ----------------- procedure Dereference (Self : in out Shared_String_Access) is pragma Assert (Self /= null); pragma Suppress (Access_Check); begin if Self /= Shared_Empty'Access and then Matreshka.Atomics.Counters.Decrement (Self.Counter) then Free (Self.Index_Map); Free (Self); end if; Self := null; end Dereference; ---------- -- Hash -- ---------- function Hash (Self : not null Shared_String_Access) return League.Hash_Type is use type League.Hash_Type; M : constant League.Hash_Type := 16#5BD1E995#; H : League.Hash_Type := League.Hash_Type (Self.Length); K : league.Hash_Type; C : Code_Unit_32; Index : Utf16_String_Index := 0; begin while Index < Self.Unused loop Unchecked_Next (Self.Value, Index, C); K := League.Hash_Type (C) * M; K := K xor (K / 16#1000000#); K := K * M; H := H * M; H := H xor K; end loop; H := H xor (H / 16#2000#); H := H * M; H := H xor (H / 16#8000#); return H; end Hash; ------------ -- Mutate -- ------------ procedure Mutate (Self : in out not null Shared_String_Access; Size : Matreshka.Internals.Utf16.Utf16_String_Index) is pragma Assert (Size /= 0); -- Limitation of current implementation. begin if not Can_Be_Reused (Self, Size) then -- Shared string cann't be reused for some reason, new string is -- allocated and existing data is copied. declare Old : Shared_String_Access := Self; begin Self := Allocate (Size); Self.Value (0 .. Old.Unused) := Old.Value (0 .. Old.Unused); Self.Unused := Old.Unused; Self.Length := Old.Length; String_Handler.Fill_Null_Terminator (Self); Dereference (Old); end; else -- Shared string can be reused, but index map must be deallocated to -- prepare shared string for modification. Free (Self.Index_Map); end if; end Mutate; --------------- -- Reference -- --------------- procedure Reference (Self : not null Shared_Sort_Key_Access) is begin if Self /= Shared_Empty_Key'Access then Matreshka.Atomics.Counters.Increment (Self.Counter); end if; end Reference; --------------- -- Reference -- --------------- procedure Reference (Self : not null Shared_String_Access) is begin if Self /= Shared_Empty'Access then Matreshka.Atomics.Counters.Increment (Self.Counter); end if; end Reference; end Matreshka.Internals.Strings;
-- { dg-do compile } -- { dg-options "-gnatws" } procedure Discr22 is subtype Precision is Integer range 1 .. 5; type Rec(D1 : Precision; D2 : Integer) is record case D1 is when 1 => I : Integer; when others => null; end case; end record; for Rec use record D1 at 0 range 0 .. 7; end record; P : Precision; X : Rec(P, 0); begin null; end;
with Memory.DRAM; use type Memory.DRAM.DRAM_Pointer; with Util; use Util; separate (Parser) procedure Parse_DRAM(parser : in out Parser_Type; result : out Memory_Pointer) is ptr : DRAM.DRAM_Pointer := null; cas_cycles : Time_Type := 5; rcd_cycles : Time_Type := 5; rp_cycles : Time_Type := 5; wb_cycles : Time_Type := 0; word_size : Positive := 8; page_size : Positive := 1024; page_count : Positive := 16384; width : Positive := 2; burst_size : Positive := 1; multiplier : Time_Type := 1; open_page : Boolean := True; begin while Get_Type(parser) = Open loop Match(parser, Open); declare name : constant String := Get_Value(parser); begin Match(parser, Literal); declare value : constant String := Get_Value(parser); begin Match(parser, Literal); if name = "cas_cycles" then cas_cycles := Time_Type'Value(value); elsif name = "rcd_cycles" then rcd_cycles := Time_Type'Value(value); elsif name = "rp_cycles" then rp_cycles := Time_Type'Value(value); elsif name = "wb_cycles" then wb_cycles := Time_Type'Value(value); elsif name = "word_size" then word_size := Positive'Value(value); elsif name = "page_size" then page_size := Positive'Value(value); elsif name = "page_count" then page_count := Positive'Value(value); elsif name = "width" then width := Positive'Value(value); elsif name = "multiplier" then multiplier := Time_Type'Value(value); elsif name = "open_page" then open_page := Parse_Boolean(value); elsif name = "burst_size" then burst_size := Positive'Value(value); else Raise_Error(parser, "invalid dram attribute: " & name); end if; end; end; Match(parser, Close); end loop; ptr := DRAM.Create_DRAM(cas_cycles, rcd_cycles, rp_cycles, wb_cycles, multiplier, word_size, page_size, page_count, width, burst_size, open_page); if ptr = null then Raise_Error(parser, "invalid dram configuration"); end if; result := Memory_Pointer(ptr); exception when Data_Error | Constraint_Error => Raise_Error(parser, "invalid value in dram"); end Parse_DRAM;
-- ----------------------------------------------------------------------------- -- Copyright 2018 Lionel Draghi -- -- 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. -- ----------------------------------------------------------------------------- -- This file is part of the List_Image project -- available at https://github.com/LionelDraghi/List_Image -- ----------------------------------------------------------------------------- package List_Image is -- -------------------------------------------------------------------------- -- Style -- -------------------------------------------------------------------------- -- This signature package defines the style of the String returned by the -- Image function. -- -- Prefix, Postfix and Separator parameters are self explaining. -- If Prefix = '(', Postfix = ')', and Separator = ',', Image will be of -- this kind : (A,B,C,D) -- If all parameters are set to "", the image will be : ABCD -- -- Special Prefix and Postfix are possible for null list, and for list with -- a single element. -- This is usefull when you want to want "[A,B,C]" as an image, but you don't -- want "[]" when the list is empty. -- -- A usefull application of this feature is to have well written comments -- regarding singular and plural. -- If you want your image to be "A item found" but "A, B, C items found", -- just set Postfix to " items found", and Postfix_If_Single to -- " item found". -- And by the way, if you want the Image to be "No item found" when the -- list is emtpy, Prefix_If_Empty and Postfix_If_Empty are here for you. -- -- Last_Separator allows to have this kind of output : -- "A, B, C and D" -- -- Note that Separator may be whatever String. You may want to insert an End -- of Line sequence to split the list on several line, the EOL String and -- parameters are provided for that purpose. -- -------------------------------------------------------------------------- generic Prefix : String := ""; Postfix : String := ""; Separator : String := ""; Last_Separator : String := Separator; Prefix_If_Empty : String := Prefix; Postfix_If_Empty : String := Postfix; Prefix_If_Single : String := Prefix; Postfix_If_Single : String := Postfix; EOL : String := ""; package Image_Style is end Image_Style; -- -------------------------------------------------------------------------- -- Predefined single line styles -- -------------------------------------------------------------------------- -- -- Predefined **single line** styles (that are not relying on EOL -- definition), and are not plateform specific, are proposed here after. -- -- - Default_Style : -- > A, B, C -- -- - English_Style : -- > A, B and C -- -- - Bracketed_List_Style : -- > [A, B, C] -- -- - Markdown_Table_Style : -- > | A | B | C | -- Note : Markdown don't define tables, but it's a common extension, -- like in Github Flavored Markdown for example. -- -- -------------------------------------------------------------------------- package Default_Style is new Image_Style (Separator => ", "); package English_Style is new Image_Style (Separator => ", ", Last_Separator => " and "); package Bracketed_List_Style is new Image_Style (Prefix => "[", Postfix => "]", Separator => ", "); package Markdown_Table_Style is new List_Image.Image_Style (Prefix => "|", Separator => "|", Postfix => "|", Prefix_If_Empty => "", Postfix_If_Empty => ""); -- -------------------------------------------------------------------------- -- Predefined Multi-Lines styles -- -------------------------------------------------------------------------- -- -- Predefined (platform dependent) **multi lines** styles -- are proposed in the following child packages : -- - List_Image.Unix_Predefined_Styles -- - List_Image.Windows_Predefined_Styles -- -- Common line terminator definitions are provided here for convenience, -- as there is no easy and standard way in Ada to get the right EOL -- terminator on the current platform (supposing there is one on the -- targeted platform). -- -- -------------------------------------------------------------------------- -- Predefined EOL are (terminator explicit) : LF_EOL : constant String := (1 => ASCII.LF); CRLF_EOL : constant String := ASCII.CR & ASCII.LF; -- or (platform explicit) : Unix_EOL : constant String := LF_EOL; Windows_EOL : constant String := CRLF_EOL; -- -------------------------------------------------------------------------- -- Cursors -- -------------------------------------------------------------------------- generic type Container (<>) is limited private; type Cursor is private; with function First (Self : Container) return Cursor is <>; with function Has_Element (Pos : Cursor) return Boolean is <>; with function Next (Pos : Cursor) return Cursor is <>; package Cursors_Signature is end Cursors_Signature; -- -------------------------------------------------------------------------- -- The Image function -- -------------------------------------------------------------------------- generic with package Cursors is new Cursors_Signature (<>); with function Image (C : Cursors.Cursor) return String is <>; with package Style is new Image_Style (<>); function Image (Cont : in Cursors.Container) return String; end List_Image;
with Actors, Engines, Components.Destructibles, Libtcod.Color; package body Components.Attackers is use Destructibles; ------------ -- attack -- ------------ procedure attack(self : in out Attacker; owner : in out Actors.Actor; target : in out Actors.Actor; engine : in out Engines.Engine) is use Actors, Libtcod; real_damage : Health; target_destructible : access Destructible := target.destructible; msg_header : constant String := owner.get_name & " attacks " & target.get_name & " "; msg_color : constant RGB_Color := (if owner = engine.player then Color.red else Color.light_grey); begin if target.is_destructible and then not target_destructible.is_dead then real_damage := target_destructible.take_damage(target, self.power, engine); if real_damage = 0 then engine.gui.log(msg_header & "for no damage", msg_color); else engine.gui.log(msg_header & "for" & real_damage'Image & " damage", msg_color); end if; else engine.gui.log(msg_header & "in vain", msg_color); end if; end attack; end Components.Attackers;
-- Institution: Technische Universität München -- Department: Realtime Computer Systems (RCS) -- Project: StratoX -- Module: LED Driver -- -- Authors: Emanuel Regnath (emanuel.regnath@tum.de) -- -- Description: Control a single LED -- -- ToDo: Support several LEDs package LED with SPARK_Mode is procedure init with pre => True; procedure on; procedure off; end LED;
-- Copyright 2017-2021 Bartek thindil Jasicki -- -- This file is part of Steam Sky. -- -- Steam Sky is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- Steam Sky is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with Steam Sky. If not, see <http://www.gnu.org/licenses/>. -- ****h* Game/GSaveLoad -- FUNCTION -- Provide code to save and load the game data from file -- SOURCE package Game.SaveLoad is -- **** -- ****v* GSaveLoad/GSaveLoad.Save_Name -- FUNCTION -- Full path with file name for current savegame -- SOURCE Save_Name: Unbounded_String; -- **** -- ****e* GSaveLoad/GSaveLoad.Save_Game_Invalid_Data -- FUNCTION -- Raised when invalid data found in savegame -- SOURCE Save_Game_Invalid_Data: exception; -- **** -- ****f* GSaveLoad/GSaveLoad.Save_Game -- FUNCTION -- Save game to file -- PARAMETERS -- Pretty_Print - Did data stored in file should be pretty printed. Default -- false -- SOURCE procedure Save_Game(Pretty_Print: Boolean := False); -- **** -- ****f* GSaveLoad/GSaveLoad.Load_Game -- FUNCTION -- Load game from file -- SOURCE procedure Load_Game; -- **** -- ****f* GSaveLoad/GSaveLoad.Generate_Save_Name -- FUNCTION -- Generate unique name for save game file -- PARAMETERS -- Rename_Save - If true, rename existing save game file. Default false. -- SOURCE procedure Generate_Save_Name(Rename_Save: Boolean := False) with Post => Save_Name /= Save_Name'Old, Test_Case => (Name => "Test_GenerateSave_Name", Mode => Nominal); -- **** end Game.SaveLoad;
with Ada.Numerics.Generic_Complex_Arrays; with Ada.Numerics.Generic_Complex_Types; with Ada.Numerics.Generic_Real_Arrays; with GA_Maths; package SVD is type Real is digits 18; package Real_Arrays is new Ada.Numerics.Generic_Real_Arrays (Real); package Complex_Types is new Ada.Numerics.Generic_Complex_Types (Real); package Complex_Arrays is new Ada.Numerics.Generic_Complex_Arrays (Real_Arrays, Complex_Types); type SVD (Num_Rows, Num_Cols, Num_Singular : Natural) is private; SVD_Exception : Exception; function Condition_Number (aMatrix : GA_Maths.Float_Matrix) return Float; function Singular_Value_Decomposition (aMatrix : Complex_Arrays.Complex_Matrix) return SVD; function Singular_Value_Decomposition (aMatrix : GA_Maths.Float_Matrix) return SVD; private type SVD (Num_Rows, Num_Cols, Num_Singular : Natural) is record Matrix_U : Complex_Arrays.Complex_Matrix (1 .. Num_Rows, 1 .. Num_Cols) := (others => (others => (0.0, 0.0))); Matrix_V : Complex_Arrays.Complex_Matrix (1 .. Num_Rows, 1 .. Num_Cols) := (others => (others => (0.0, 0.0))); Matrix_W : Complex_Arrays.Complex_Vector (1 .. Num_Rows) :=(others => (0.0, 0.0)); Sorted_Singular_Values : Real_Arrays.Real_Vector (1 .. Num_Singular); end record; end SVD;
-- Institution: Technische Universität München -- Department: Realtime Computer Systems (RCS) -- Project: StratoX -- -- Authors: Emanuel Regnath (emanuel.regnath@tum.de) -- -- Description: Generic signal package -- -- ToDo: -- [ ] Implementation with Units; use Units; generic type Data_Type is private; -- with function "/" (X : Data_Type; Y : Float) return Data_Type is <>; -- with function "+" (X,Y : Data_Type) return Data_Type is <>; package Generic_Signal with SPARK_Mode is type Sample_Type is record data : Data_Type; timestamp : Time_Type; end record; type Signal_Type is array (Natural range <>) of Sample_Type; -- function Average( signal : Signal_Type ) return Data_Type; -- function Average( signal : Signal_Type ) return Data_Type is -- avg : Data_Type; -- begin -- avg := signal( signal'First ).data / signal'Length; -- if signal'Length > 1 then -- for index in Integer range signal'First+1 .. signal'Last loop -- avg := avg + signal( index ).data / signal'Length; -- end loop; -- end if; -- return avg; -- end Average; end Generic_Signal;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- S C N -- -- -- -- S p e c -- -- -- -- Copyright (C) 1992-2016, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING3. If not, go to -- -- http://www.gnu.org/licenses for a complete copy of the license. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- This package contains the lexical analyzer routines. This is used by the -- compiler for scanning Ada source files. with Casing; use Casing; with Errout; use Errout; with Scng; with Style; use Style; with Types; use Types; package Scn is procedure Initialize_Scanner (Unit : Unit_Number_Type; Index : Source_File_Index); -- Initialize lexical scanner for scanning a new file. The caller has -- completed the construction of the Units.Table entry for the specified -- Unit and Index references the corresponding source file. A special -- case is when Unit = No_Unit_Number, and Index corresponds to the -- source index for reading the configuration pragma file. function Determine_Token_Casing return Casing_Type; -- Determines the casing style of the current token, which is either a -- keyword or an identifier. See also package Casing. procedure Post_Scan; -- Create nodes for tokens: Char_Literal, Identifier, Real_Literal, -- Integer_Literal, String_Literal and Operator_Symbol. procedure Scan_Reserved_Identifier (Force_Msg : Boolean); -- This procedure is called to convert the current token, which the caller -- has checked is for a reserved word, to an equivalent identifier. This is -- of course only used in error situations where the parser can detect that -- a reserved word is being used as an identifier. An appropriate error -- message, pointing to the token, is also issued if either this is the -- first occurrence of misuse of this identifier, or if Force_Msg is True. ------------- -- Scanner -- ------------- -- The scanner used by the compiler is an instantiation of the -- generic package Scng with routines appropriate to the compiler package Scanner is new Scng (Post_Scan => Post_Scan, Error_Msg => Error_Msg, Error_Msg_S => Error_Msg_S, Error_Msg_SC => Error_Msg_SC, Error_Msg_SP => Error_Msg_SP, Style => Style.Style_Inst); procedure Scan renames Scanner.Scan; -- Scan scans out the next token, and advances the scan state accordingly -- (see package Scans for details). If the scan encounters an illegal -- token, then an error message is issued pointing to the bad character, -- and Scan returns a reasonable substitute token of some kind. end Scn;
with Ada.Strings.Fixed; with Ada.Integer_Text_IO; -- Copyright 2021 Melwyn Francis Carlo procedure A040 is use Ada.Strings.Fixed; use Ada.Integer_Text_IO; Max_E : constant Integer := 7; -- 1E+x N : constant array (Integer range 1 .. Max_E) of Integer := (1, 10, 100, 1000, 10000, 100000, 1000000); Indices : array (Integer range 1 .. Max_E) of Integer; Product_Val : Integer := 1; J, Num, Index_Val : Integer; begin Indices (1) := 1; for I in 2 .. Max_E loop Indices (I) := Indices (I - 1) + (9 * (I - 1) * Integer (10 ** (I - 2))); end loop; for I in 1 .. Max_E loop J := 1; while J <= Max_E loop if N (I) < Indices (J) then exit; end if; J := J + 1; end loop; J := J - 2; Num := Integer (10 ** J) + Integer ((N (I) - Indices (J + 1)) / (J + 1)); Index_Val := ((N (I) - Indices (J + 1)) mod (J + 1)) + 1; Product_Val := Product_Val * (Character'Pos ( Trim (Integer'Image (Num), Ada.Strings.Both) (Index_Val)) - Character'Pos ('0')); end loop; Put (Product_Val, Width => 0); end A040;
pragma Check_Policy (Trace => Ignore); with Ada.Unchecked_Conversion; with System.Address_To_Named_Access_Conversions; with System.Address_To_Constant_Access_Conversions; with System.Storage_Elements; with System.Unwind.Mapping; with System.Unwind.Representation; with C.basetsd; with C.unwind_pe; package body System.Unwind.Searching is pragma Suppress (All_Checks); use type Representation.Machine_Occurrence_Access; use type Storage_Elements.Storage_Offset; use type C.ptrdiff_t; use type C.signed_int; use type C.size_t; use type C.unsigned_char; use type C.unsigned_char_const_ptr; use type C.unsigned_int; -- _Unwind_Ptr is unsigned int or unsigned long use type C.unsigned_long; use type C.unsigned_long_long; use type C.unwind.sleb128_t; use type C.winnt.PRUNTIME_FUNCTION; Foreign_Exception : aliased Exception_Data with Import, Convention => Ada, External_Name => "system__exceptions__foreign_exception"; function builtin_eh_return_data_regno (A1 : C.signed_int) return C.signed_int with Import, Convention => Intrinsic, External_Name => "__builtin_eh_return_data_regno"; package unsigned_char_const_ptr_Conv is new Address_To_Constant_Access_Conversions ( C.unsigned_char, C.unsigned_char_const_ptr); function "+" (Left : C.unsigned_char_const_ptr; Right : C.ptrdiff_t) return C.unsigned_char_const_ptr with Convention => Intrinsic; pragma Inline_Always ("+"); function "+" (Left : C.unsigned_char_const_ptr; Right : C.ptrdiff_t) return C.unsigned_char_const_ptr is begin return unsigned_char_const_ptr_Conv.To_Pointer ( unsigned_char_const_ptr_Conv.To_Address (Left) + Storage_Elements.Storage_Offset (Right)); end "+"; function "<" (Left, Right : C.unsigned_char_const_ptr) return Boolean with Import, Convention => Intrinsic; package Unwind_Exception_ptr_Conv is new Address_To_Named_Access_Conversions ( C.unwind.struct_Unwind_Exception, C.unwind.struct_Unwind_Exception_ptr); package PUINT16_Conv is new Address_To_Named_Access_Conversions ( C.basetsd.UINT16, C.basetsd.PUINT16); package PDWORD64_Conv is new Address_To_Named_Access_Conversions ( C.basetsd.DWORD64, C.basetsd.PDWORD64); -- (unwind-seh.c) STATUS_USER_DEFINED : constant := 2 ** 29; GCC_MAGIC : constant := 16#474343#; -- "GCC" STATUS_GCC_THROW : constant := STATUS_USER_DEFINED + 0 * 2 ** 24 + GCC_MAGIC; -- UWOP_PUSH_NONVOL : constant := 0; UWOP_ALLOC_LARGE : constant := 1; -- UWOP_ALLOC_SMALL : constant := 2; -- UWOP_SET_FPREG : constant := 3; UWOP_SAVE_NONVOL : constant := 4; -- UWOP_SAVE_NONVOL_FAR : constant := 5; UWOP_SAVE_XMM128 : constant := 8; -- UWOP_SAVE_XMM128_FAR : constant := 9; UWOP_PUSH_MACHFRAME : constant := 10; -- equivalent to __gnat_adjust_context (raise-gcc.c) procedure Adjust_Context ( Unwind_Data : Address; Context_RSP : C.basetsd.ULONG64); procedure Adjust_Context ( Unwind_Data : Address; Context_RSP : C.basetsd.ULONG64) is unw : C.unsigned_char_const_ptr := unsigned_char_const_ptr_Conv.To_Pointer (Unwind_Data); rsp : C.basetsd.ULONG64 := Context_RSP; len : C.unsigned_char; begin -- Version = 1, no flags, no prolog. if unw.all /= 1 or else C.unsigned_char_const_ptr'(unw + 1).all /= 0 -- No frame pointer. or else C.unsigned_char_const_ptr'(unw + 3).all /= 0 then null; else len := C.unsigned_char_const_ptr'(unw + 2).all; unw := unw + 4; while len > 0 loop -- Offset in prolog = 0. exit when unw.all /= 0; case C.unsigned_char_const_ptr'(unw + 1).all and 16#0f# is when UWOP_ALLOC_LARGE => -- Expect < 512KB. exit when (C.unsigned_char_const_ptr'(unw + 1).all and 16#f0#) /= 0; rsp := rsp + 8 * C.basetsd.ULONG64 ( PUINT16_Conv.To_Pointer ( unsigned_char_const_ptr_Conv.To_Address ( unw + 2)) .all); len := len - 1; unw := unw + 2; when UWOP_SAVE_NONVOL | UWOP_SAVE_XMM128 => len := len - 1; unw := unw + 2; when UWOP_PUSH_MACHFRAME => declare rip : C.basetsd.ULONG64; begin rip := rsp; if (C.unsigned_char_const_ptr'(unw + 1).all and 16#f0#) = 16#10# then rip := rip + C.basetsd.ULONG64'Size / Standard'Storage_Unit; end if; -- Adjust rip. PDWORD64_Conv.To_Pointer (System'To_Address (rip)).all := PDWORD64_Conv.To_Pointer (System'To_Address (rip)).all + 1; end; exit; when others => -- Unexpected. exit; end case; unw := unw + 2; len := len - 1; end loop; end if; end Adjust_Context; -- implementation function Personality ( ABI_Version : C.signed_int; Phases : C.unwind.Unwind_Action; Exception_Class : C.unwind.Unwind_Exception_Class; Exception_Object : access C.unwind.struct_Unwind_Exception; Context : access C.unwind.struct_Unwind_Context) return C.unwind.Unwind_Reason_Code is function To_GNAT is new Ada.Unchecked_Conversion ( C.unwind.struct_Unwind_Exception_ptr, Representation.Machine_Occurrence_Access); function Cast is new Ada.Unchecked_Conversion ( C.unwind.struct_Unwind_Exception_ptr, C.unwind.Unwind_Word); function Cast is new Ada.Unchecked_Conversion ( Exception_Data_Access, C.unwind.Unwind_Ptr); function Cast is new Ada.Unchecked_Conversion (C.char_const_ptr, C.unwind.Unwind_Ptr); GCC_Exception : constant Representation.Machine_Occurrence_Access := To_GNAT (Exception_Object); landing_pad : C.unwind.Unwind_Ptr; ttype_filter : C.unwind.Unwind_Sword; -- 0 => finally, others => handler begin pragma Check (Trace, Ada.Debug.Put ("enter")); if ABI_Version /= 1 then pragma Check (Trace, Ada.Debug.Put ("leave, ABI_Version /= 1")); return C.unwind.URC_FATAL_PHASE1_ERROR; end if; if Exception_Class = Representation.GNAT_Exception_Class and then C.unsigned_int (Phases) = (C.unwind.UA_CLEANUP_PHASE or C.unwind.UA_HANDLER_FRAME) then landing_pad := GCC_Exception.landing_pad; ttype_filter := GCC_Exception.ttype_filter; pragma Check (Trace, Ada.Debug.Put ("shortcut!")); else declare -- about region lsda : C.void_ptr; base : C.unwind.Unwind_Ptr; call_site_encoding : C.unsigned_char; call_site_table : C.unsigned_char_const_ptr; lp_base : aliased C.unwind.Unwind_Ptr; action_table : C.unsigned_char_const_ptr; ttype_encoding : C.unsigned_char; ttype_table : C.unsigned_char_const_ptr; ttype_base : C.unwind.Unwind_Ptr; -- about action table_entry : C.unsigned_char_const_ptr; begin if Context = null then pragma Check (Trace, Ada.Debug.Put ("leave, Context = null")); return C.unwind.URC_CONTINUE_UNWIND; end if; lsda := C.unwind.Unwind_GetLanguageSpecificData (Context); if Address (lsda) = Null_Address then pragma Check (Trace, Ada.Debug.Put ("leave, lsda = null")); return C.unwind.URC_CONTINUE_UNWIND; end if; base := C.unwind.Unwind_GetRegionStart (Context); declare p : C.unsigned_char_const_ptr := unsigned_char_const_ptr_Conv.To_Pointer (Address (lsda)); tmp : aliased C.unwind.uleb128_t; lpbase_encoding : C.unsigned_char; begin lpbase_encoding := p.all; p := p + 1; if lpbase_encoding /= C.unwind_pe.DW_EH_PE_omit then p := C.unwind_pe.read_encoded_value ( Context, lpbase_encoding, p, lp_base'Access); else lp_base := base; end if; ttype_encoding := p.all; p := p + 1; if ttype_encoding /= C.unwind_pe.DW_EH_PE_omit then p := C.unwind_pe.read_uleb128 (p, tmp'Access); ttype_table := p + C.ptrdiff_t (tmp); else pragma Check (Trace, Check => Ada.Debug.Put ("ttype_encoding = DW_EH_PE_omit")); ttype_table := null; -- be access violation ? end if; ttype_base := C.unwind_pe.base_of_encoded_value (ttype_encoding, Context); call_site_encoding := p.all; p := p + 1; call_site_table := C.unwind_pe.read_uleb128 (p, tmp'Access); action_table := call_site_table + C.ptrdiff_t (tmp); end; declare p : C.unsigned_char_const_ptr := call_site_table; ip_before_insn : aliased C.signed_int := 0; ip : C.unwind.Unwind_Ptr := C.unwind.Unwind_GetIPInfo (Context, ip_before_insn'Access); begin if ip_before_insn = 0 then pragma Check (Trace, Ada.Debug.Put ("ip_before_insn = 0")); ip := ip - 1; end if; loop if not (p < action_table) then pragma Check (Trace, Check => Ada.Debug.Put ("leave, not (p < action_table)")); return C.unwind.URC_CONTINUE_UNWIND; end if; declare cs_start, cs_len, cs_lp : aliased C.unwind.Unwind_Ptr; cs_action : aliased C.unwind.uleb128_t; begin p := C.unwind_pe.read_encoded_value ( null, call_site_encoding, p, cs_start'Access); p := C.unwind_pe.read_encoded_value ( null, call_site_encoding, p, cs_len'Access); p := C.unwind_pe.read_encoded_value ( null, call_site_encoding, p, cs_lp'Access); p := C.unwind_pe.read_uleb128 (p, cs_action'Access); if ip < base + cs_start then pragma Check (Trace, Check => Ada.Debug.Put ("leave, ip < base + cs_start")); return C.unwind.URC_CONTINUE_UNWIND; elsif ip < base + cs_start + cs_len then if cs_lp /= 0 then landing_pad := lp_base + cs_lp; else pragma Check (Trace, Check => Ada.Debug.Put ("leave, cs_lp = 0")); return C.unwind.URC_CONTINUE_UNWIND; end if; if cs_action /= 0 then table_entry := action_table + C.ptrdiff_t (cs_action - 1); else table_entry := null; end if; exit; end if; end; end loop; end; -- landing_pad is found in here if table_entry = null then ttype_filter := 0; else declare ttype_size : constant C.ptrdiff_t := C.ptrdiff_t ( C.unwind_pe.size_of_encoded_value (ttype_encoding)); p : C.unsigned_char_const_ptr := table_entry; ar_filter, ar_disp : aliased C.unwind.sleb128_t; begin loop p := C.unwind_pe.read_sleb128 (p, ar_filter'Access); declare Dummy : C.unsigned_char_const_ptr; begin Dummy := C.unwind_pe.read_sleb128 (p, ar_disp'Access); end; if ar_filter = 0 then ttype_filter := 0; if ar_disp = 0 then pragma Check (Trace, Ada.Debug.Put ("finally")); exit; end if; elsif ar_filter > 0 and then (C.unsigned_int (Phases) and C.unwind.UA_FORCE_UNWIND) = 0 then declare filter : constant C.ptrdiff_t := C.ptrdiff_t (ar_filter) * ttype_size; choice : aliased C.unwind.Unwind_Ptr; is_handled : Boolean; Dummy : C.unsigned_char_const_ptr; begin Dummy := C.unwind_pe.read_encoded_value_with_base ( ttype_encoding, ttype_base, ttype_table + (-filter), choice'Access); if Exception_Class = Representation.GNAT_Exception_Class then if choice = Cast (Unhandled_Others_Value'Access) then pragma Check (Trace, Check => Ada.Debug.Put ("unhandled exception")); is_handled := True; else is_handled := choice = Cast (GCC_Exception.Occurrence.Id) or else ( not GCC_Exception.Occurrence.Id .Not_Handled_By_Others and then choice = Cast (Others_Value'Access)) or else choice = Cast (All_Others_Value'Access); end if; else pragma Check (Trace, Check => Ada.Debug.Put ("foreign exception")); is_handled := choice = Cast (Foreign_Exception'Access) or else choice = Cast (Others_Value'Access) or else choice = Cast (All_Others_Value'Access); end if; if is_handled then ttype_filter := C.unwind.Unwind_Sword (ar_filter); pragma Check (Trace, Check => Ada.Debug.Put ("handler is found")); exit; end if; end; else pragma Check (Trace, Ada.Debug.Put ("ar_filter < 0")); null; end if; if ar_disp = 0 then pragma Check (Trace, Check => Ada.Debug.Put ("leave, ar_disp = 0")); return C.unwind.URC_CONTINUE_UNWIND; end if; p := p + C.ptrdiff_t (ar_disp); end loop; end; end if; -- ttype_filter is found (or 0) in here if (C.unsigned_int (Phases) and C.unwind.UA_SEARCH_PHASE) /= 0 then if ttype_filter = 0 then -- cleanup pragma Check (Trace, Check => Ada.Debug.Put ("leave, UA_SEARCH_PHASE, cleanup")); return C.unwind.URC_CONTINUE_UNWIND; else -- Setup_Current_Excep (GCC_Exception); null; -- exception tracing (a-exextr.adb) is not implementd. -- shortcut for phase2 if Exception_Class = Representation.GNAT_Exception_Class then pragma Check (Trace, Ada.Debug.Put ("save for shortcut")); GCC_Exception.landing_pad := landing_pad; GCC_Exception.ttype_filter := ttype_filter; end if; pragma Check (Trace, Check => Ada.Debug.Put ( "leave, UA_SEARCH_PHASE, handler found")); return C.unwind.URC_HANDLER_FOUND; end if; elsif Phases = C.unwind.UA_CLEANUP_PHASE then if ttype_filter = 0 and then Exception_Class = Representation.GNAT_Exception_Class and then GCC_Exception.Stack_Guard /= Null_Address then declare Stack_Pointer : constant C.unwind.Unwind_Word := C.unwind.Unwind_GetCFA (Context); begin if Stack_Pointer < C.unwind.Unwind_Word (GCC_Exception.Stack_Guard) then pragma Check (Trace, Check => Ada.Debug.Put ("leave, skip cleanup")); return C.unwind.URC_CONTINUE_UNWIND; end if; end; end if; pragma Check (Trace, Check => Ada.Debug.Put ( "UA_CLEANUP_PHASE without UA_HANDLER_FRAME")); null; -- ??? elsif Phases = C.unwind.UA_END_OF_STACK then pragma Check (Trace, Ada.Debug.Put ("leave, end of stack")); return C.unwind.URC_HANDLER_FOUND; else pragma Check (Trace, Ada.Debug.Put ("miscellany phase")); null; -- ??? end if; end; end if; pragma Check (Trace, Ada.Debug.Put ("unwind!")); -- setup_to_install (raise-gcc.c) C.unwind.Unwind_SetGR ( Context, builtin_eh_return_data_regno (0), Cast (C.unwind.struct_Unwind_Exception_ptr (Exception_Object))); C.unwind.Unwind_SetGR ( Context, builtin_eh_return_data_regno (1), C.unwind.Unwind_Word'Mod (ttype_filter)); C.unwind.Unwind_SetIP (Context, landing_pad); -- Setup_Current_Excep (GCC_Exception); -- moved to Begin_Handler pragma Check (Trace, Ada.Debug.Put ("leave")); return C.unwind.URC_INSTALL_CONTEXT; end Personality; function Personality_SEH ( ms_exc : C.winnt.PEXCEPTION_RECORD; this_frame : C.void_ptr; ms_orig_context : C.winnt.PCONTEXT; ms_disp : C.winnt.PDISPATCHER_CONTEXT) return C.excpt.EXCEPTION_DISPOSITION is Result : C.excpt.EXCEPTION_DISPOSITION; begin pragma Check (Trace, Ada.Debug.Put ("enter")); if (ms_exc.ExceptionCode and STATUS_USER_DEFINED) = 0 then pragma Check (Trace, Ada.Debug.Put ("Windows exception")); declare the_exception : Representation.Machine_Occurrence_Access; excpip : constant C.basetsd.ULONG64 := C.basetsd.ULONG64 (Address (ms_exc.ExceptionAddress)); begin if excpip /= 0 and then excpip >= ms_disp.ImageBase + C.basetsd.ULONG64 (ms_disp.FunctionEntry.BeginAddress) and then excpip < ms_disp.ImageBase + C.basetsd.ULONG64 (ms_disp.FunctionEntry.EndAddress) then -- This is a fault in this function. -- We need to adjust the return address -- before raising the GCC exception. declare context : aliased C.winnt.CONTEXT; mf_func : C.winnt.PRUNTIME_FUNCTION := null; mf_imagebase : C.basetsd.ULONG64; mf_rsp : C.basetsd.ULONG64 := 0; begin -- Get the context. C.winnt.RtlCaptureContext (context'Access); loop declare RuntimeFunction : C.winnt.PRUNTIME_FUNCTION; ImageBase : aliased C.basetsd.ULONG64; HandlerData : aliased C.winnt.PVOID; EstablisherFrame : aliased C.basetsd.ULONG64; begin -- Get function metadata. RuntimeFunction := C.winnt.RtlLookupFunctionEntry ( context.Rip, ImageBase'Access, ms_disp.HistoryTable); exit when RuntimeFunction = ms_disp.FunctionEntry; mf_func := RuntimeFunction; mf_imagebase := ImageBase; mf_rsp := context.Rsp; if RuntimeFunction = null then -- In case of failure, -- assume this is a leaf function. context.Rip := PDWORD64_Conv.To_Pointer ( System'To_Address (context.Rsp)) .all; context.Rsp := context.Rsp + 8; else -- Unwind. declare Dummy : C.winnt.PEXCEPTION_ROUTINE; begin Dummy := C.winnt.RtlVirtualUnwind ( 0, ImageBase, context.Rip, RuntimeFunction, context'Access, HandlerData'Access, EstablisherFrame'Access, null); end; end if; -- 0 means bottom of the stack. if context.Rip = 0 then mf_func := null; exit; end if; end; end loop; if mf_func /= null then Adjust_Context ( System'To_Address ( mf_imagebase + C.basetsd.ULONG64 (mf_func.UnwindData)), mf_rsp); end if; end; end if; the_exception := Mapping.New_Machine_Occurrence_From_SEH (ms_exc); if the_exception /= null then declare exc : C.unwind.struct_Unwind_Exception_ptr; begin -- Directly convert the system exception to a GCC one. -- This is really breaking the API, but is necessary -- for stack size reasons: the normal way is to call -- Raise_From_Signal_Handler, which build the exception -- and calls _Unwind_RaiseException, which unwinds -- the stack and will call this personality routine. -- But the Windows unwinder needs about 2KB of stack. exc := the_exception.Header'Access; exc.F_private := (others => 0); ms_exc.ExceptionCode := STATUS_GCC_THROW; ms_exc.NumberParameters := 1; ms_exc.ExceptionInformation (0) := C.basetsd.ULONG_PTR ( Unwind_Exception_ptr_Conv.To_Address (exc)); end; end if; end; end if; pragma Check (Trace, Ada.Debug.Put ("GCC_specific_handler")); Result := C.unwind.GCC_specific_handler ( ms_exc, this_frame, ms_orig_context, ms_disp, Personality'Access); pragma Check (Trace, Ada.Debug.Put ("leave")); return Result; end Personality_SEH; end System.Unwind.Searching;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- S Y S T E M . M M A P . O S _ I N T E R F A C E -- -- -- -- B o d y -- -- -- -- Copyright (C) 2007-2020, AdaCore -- -- -- -- This library is free software; you can redistribute it and/or modify it -- -- under terms of the GNU General Public License as published by the Free -- -- Software Foundation; either version 3, or (at your option) any later -- -- version. This library is distributed in the hope that it will be useful, -- -- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN- -- -- TABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- 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.IO_Exceptions; with System; use System; with System.OS_Lib; use System.OS_Lib; with System.Mmap.Unix; use System.Mmap.Unix; package body System.Mmap.OS_Interface is function Align (Addr : File_Size) return File_Size; -- Align some offset/length to the lowest page boundary function Is_Mapping_Available return Boolean renames System.Mmap.Unix.Is_Mapping_Available; -- Wheter memory mapping is actually available on this system. It is an -- error to use Create_Mapping and Dispose_Mapping if this is False. --------------- -- Open_Read -- --------------- function Open_Read (Filename : String; Use_Mmap_If_Available : Boolean := True) return System_File is Fd : constant File_Descriptor := Open_Read (Filename, Binary); begin if Fd = Invalid_FD then return Invalid_System_File; end if; return (Fd => Fd, Mapped => Use_Mmap_If_Available and then Is_Mapping_Available, Write => False, Length => File_Size (File_Length (Fd))); end Open_Read; ---------------- -- Open_Write -- ---------------- function Open_Write (Filename : String; Use_Mmap_If_Available : Boolean := True) return System_File is Fd : constant File_Descriptor := Open_Read_Write (Filename, Binary); begin if Fd = Invalid_FD then return Invalid_System_File; end if; return (Fd => Fd, Mapped => Use_Mmap_If_Available and then Is_Mapping_Available, Write => True, Length => File_Size (File_Length (Fd))); end Open_Write; ----------- -- Close -- ----------- procedure Close (File : in out System_File) is begin Close (File.Fd); File.Fd := Invalid_FD; end Close; -------------------- -- Read_From_Disk -- -------------------- function Read_From_Disk (File : System_File; Offset, Length : File_Size) return System.Strings.String_Access is Buffer : String_Access := new String (1 .. Integer (Length)); begin -- ??? Lseek offset should be a size_t instead of a Long_Integer Lseek (File.Fd, Long_Integer (Offset), Seek_Set); if System.OS_Lib.Read (File.Fd, Buffer.all'Address, Integer (Length)) /= Integer (Length) then System.Strings.Free (Buffer); raise Ada.IO_Exceptions.Device_Error; end if; return Buffer; end Read_From_Disk; ------------------- -- Write_To_Disk -- ------------------- procedure Write_To_Disk (File : System_File; Offset, Length : File_Size; Buffer : System.Strings.String_Access) is begin pragma Assert (File.Write); Lseek (File.Fd, Long_Integer (Offset), Seek_Set); if System.OS_Lib.Write (File.Fd, Buffer.all'Address, Integer (Length)) /= Integer (Length) then raise Ada.IO_Exceptions.Device_Error; end if; end Write_To_Disk; -------------------- -- Create_Mapping -- -------------------- procedure Create_Mapping (File : System_File; Offset, Length : in out File_Size; Mutable : Boolean; Mapping : out System_Mapping) is Prot : Mmap_Prot; Flags : Mmap_Flags; begin if File.Write then Prot := PROT_READ + PROT_WRITE; Flags := MAP_SHARED; else Prot := PROT_READ; if Mutable then Prot := Prot + PROT_WRITE; end if; Flags := MAP_PRIVATE; end if; -- Adjust offset and mapping length to account for the required -- alignment of offset on page boundary. declare Queried_Offset : constant File_Size := Offset; begin Offset := Align (Offset); -- First extend the length to compensate the offset shift, then align -- it on the upper page boundary, so that the whole queried area is -- covered. Length := Length + Queried_Offset - Offset; Length := Align (Length + Get_Page_Size - 1); end; if Length > File_Size (Integer'Last) then raise Ada.IO_Exceptions.Device_Error; else Mapping := (Address => System.Mmap.Unix.Mmap (Offset => off_t (Offset), Length => Interfaces.C.size_t (Length), Prot => Prot, Flags => Flags, Fd => File.Fd), Length => Length); end if; end Create_Mapping; --------------------- -- Dispose_Mapping -- --------------------- procedure Dispose_Mapping (Mapping : in out System_Mapping) is Ignored : Integer; pragma Unreferenced (Ignored); begin Ignored := Munmap (Mapping.Address, Interfaces.C.size_t (Mapping.Length)); Mapping := Invalid_System_Mapping; end Dispose_Mapping; ------------------- -- Get_Page_Size -- ------------------- function Get_Page_Size return File_Size is function Internal return Integer; pragma Import (C, Internal, "getpagesize"); begin return File_Size (Internal); end Get_Page_Size; ----------- -- Align -- ----------- function Align (Addr : File_Size) return File_Size is begin return Addr - Addr mod Get_Page_Size; end Align; end System.Mmap.OS_Interface;
--with Ada.Text_IO; with Ada.Command_Line; use Ada.Command_Line; separate (Command_Line_Interface) procedure Read_Command_Line (Command_Args : out Command_Line_Type) is -- mytest --Maximum_Command_Length : constant := 1024; --subtype Command_Line_Type is String (1 .. Maximum_Command_Length); --Command_Args : Command_Line_Type; -- mytest last : integer := command_args'first - 1; procedure put ( s : string ) is begin command_args ( last+1.. last+s'length) := s; last := last + s'length; end; begin for i in 1 .. Ada.Command_Line.Argument_count -- - 1 loop if i/=1 then put(" "); end if; put ( Ada.Command_Line.argument(i) ); end loop; command_args (last+1..command_args'last) := ( others => ' ' ); -- Ada.Text_IO.Put_Line(Command_Args); end Read_Command_Line;
package defining_operator_symbol is function "*"(Left, Right : Integer) return Integer; end defining_operator_symbol;
with openGL.Primitive.indexed, openGL.IO; package body openGL.Model.billboard.colored_textured is type Geometry_view is access all Geometry.colored_textured.item'Class; --------- --- Forge -- function new_Billboard (Size : in Size_t := default_Size; Plane : in billboard.Plane; Color : in lucid_Color; Texture : in asset_Name) return View is Self : constant View := new Item; begin Self.define (Size); Self.Plane := Plane; Self.Color := Color; Self.Texture_Name := Texture; return Self; end new_Billboard; -------------- --- Attributes -- overriding function to_GL_Geometries (Self : access Item; Textures : access Texture.name_Map_of_texture'Class; Fonts : in Font.font_id_Map_of_font) return Geometry.views is pragma unreferenced (Textures, Fonts); use Geometry, Geometry.colored_textured, Texture; the_Indices : aliased constant Indices := (1, 2, 3, 4); the_Sites : constant billboard.Sites := vertex_Sites (Self.Plane, Self.Width, Self.Height); function new_Face (Vertices : access Geometry.colored_textured.Vertex_array) return Geometry_view is use openGL.Primitive; the_Geometry : constant Geometry_view := Geometry.colored_textured.new_Geometry; the_Primitive : constant Primitive.view := Primitive.indexed.new_Primitive (triangle_Fan, the_Indices).all'Access; begin the_Geometry.Vertices_are (Vertices.all); the_Geometry.add (the_Primitive); the_Geometry.is_Transparent; return the_Geometry; end new_Face; Color : constant rgba_Color := +Self.Color; the_Face : Geometry_view; begin declare the_Vertices : constant access Geometry.colored_textured.Vertex_array := Self.Vertices; begin the_Vertices.all := Geometry.colored_textured.Vertex_array' (1 => (site => the_Sites (1), color => Color, coords => (Self.texture_Coords (1))), 2 => (site => the_Sites (2), color => Color, coords => (Self.texture_Coords (2))), 3 => (site => the_Sites (3), color => Color, coords => (Self.texture_Coords (3))), 4 => (site => the_Sites (4), color => Color, coords => (Self.texture_Coords (4)))); the_Face := new_Face (Vertices => the_Vertices); if Self.texture_Name /= null_Asset then Self.Texture := IO.to_Texture (Self.texture_Name); end if; if Self.Texture /= null_Object then the_Face.Texture_is (Self.Texture); end if; end; Self.Geometry := the_Face; return (1 => Geometry.view (the_Face)); end to_GL_Geometries; procedure Color_is (Self : in out Item; Now : in lucid_Color) is begin Self.Color := Now; for i in Self.Vertices'Range loop Self.Vertices (i).Color := +Now; end loop; Self.is_Modified := True; end Color_is; procedure Texture_Coords_are (Self : in out Item; Now : in Coordinates) is begin Self.texture_Coords := Now; Self.needs_Rebuild := True; end Texture_Coords_are; overriding procedure modify (Self : in out Item) is begin Self.Geometry.Vertices_are (Self.Vertices.all); Self.is_Modified := False; end modify; overriding function is_Modified (Self : in Item) return Boolean is begin return Self.is_Modified; end is_Modified; end openGL.Model.billboard.colored_textured;