content
stringlengths
23
1.05M
-- nymph.ada - Main package file for the NymphRPC package. -- -- Revision 0 -- -- 2018/09/24, Maya Posch package nymph is -- public private -- end nymph;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- P R J . C O N F -- -- -- -- B o d y -- -- -- -- Copyright (C) 2006-2010, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING3. If not, go to -- -- http://www.gnu.org/licenses for a complete copy of the license. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Hostparm; with Makeutl; use Makeutl; with MLib.Tgt; with Opt; use Opt; with Output; use Output; with Prj.Env; with Prj.Err; with Prj.Part; with Prj.PP; with Prj.Proc; use Prj.Proc; with Prj.Tree; use Prj.Tree; with Prj.Util; use Prj.Util; with Prj; use Prj; with Snames; use Snames; with Ada.Directories; use Ada.Directories; with Ada.Exceptions; use Ada.Exceptions; with GNAT.Case_Util; use GNAT.Case_Util; with GNAT.HTable; use GNAT.HTable; package body Prj.Conf is Auto_Cgpr : constant String := "auto.cgpr"; Default_Name : constant String := "default.cgpr"; -- Default configuration file that will be used if found Config_Project_Env_Var : constant String := "GPR_CONFIG"; -- Name of the environment variable that provides the name of the -- configuration file to use. Gprconfig_Name : constant String := "gprconfig"; package RTS_Languages is new GNAT.HTable.Simple_HTable (Header_Num => Prj.Header_Num, Element => Name_Id, No_Element => No_Name, Key => Name_Id, Hash => Prj.Hash, Equal => "="); -- Stores the runtime names for the various languages. This is in general -- set from a --RTS command line option. ----------------------- -- Local_Subprograms -- ----------------------- procedure Add_Attributes (Project_Tree : Project_Tree_Ref; Conf_Decl : Declarations; User_Decl : in out Declarations); -- Process the attributes in the config declarations. -- For single string values, if the attribute is not declared in the user -- declarations, declare it with the value in the config declarations. -- For string list values, prepend the value in the user declarations with -- the value in the config declarations. function Check_Target (Config_File : Prj.Project_Id; Autoconf_Specified : Boolean; Project_Tree : Prj.Project_Tree_Ref; Target : String := "") return Boolean; -- Check that the config file's target matches Target. -- Target should be set to the empty string when the user did not specify -- a target. If the target in the configuration file is invalid, this -- function will raise Invalid_Config with an appropriate message. -- Autoconf_Specified should be set to True if the user has used -- autoconf. function Locate_Config_File (Name : String) return String_Access; -- Search for Name in the config files directory. Return full path if -- found, or null otherwise. procedure Raise_Invalid_Config (Msg : String); pragma No_Return (Raise_Invalid_Config); -- Raises exception Invalid_Config with given message -------------------- -- Add_Attributes -- -------------------- procedure Add_Attributes (Project_Tree : Project_Tree_Ref; Conf_Decl : Declarations; User_Decl : in out Declarations) is Conf_Attr_Id : Variable_Id; Conf_Attr : Variable; Conf_Array_Id : Array_Id; Conf_Array : Array_Data; Conf_Array_Elem_Id : Array_Element_Id; Conf_Array_Elem : Array_Element; Conf_List : String_List_Id; Conf_List_Elem : String_Element; User_Attr_Id : Variable_Id; User_Attr : Variable; User_Array_Id : Array_Id; User_Array : Array_Data; User_Array_Elem_Id : Array_Element_Id; User_Array_Elem : Array_Element; begin Conf_Attr_Id := Conf_Decl.Attributes; User_Attr_Id := User_Decl.Attributes; while Conf_Attr_Id /= No_Variable loop Conf_Attr := Project_Tree.Variable_Elements.Table (Conf_Attr_Id); User_Attr := Project_Tree.Variable_Elements.Table (User_Attr_Id); if not Conf_Attr.Value.Default then if User_Attr.Value.Default then -- No attribute declared in user project file: just copy the -- value of the configuration attribute. User_Attr.Value := Conf_Attr.Value; Project_Tree.Variable_Elements.Table (User_Attr_Id) := User_Attr; elsif User_Attr.Value.Kind = List and then Conf_Attr.Value.Values /= Nil_String then -- List attribute declared in both the user project and the -- configuration project: prepend the user list with the -- configuration list. declare Conf_List : String_List_Id := Conf_Attr.Value.Values; Conf_Elem : String_Element; User_List : constant String_List_Id := User_Attr.Value.Values; New_List : String_List_Id; New_Elem : String_Element; begin -- Create new list String_Element_Table.Increment_Last (Project_Tree.String_Elements); New_List := String_Element_Table.Last (Project_Tree.String_Elements); -- Value of attribute is new list User_Attr.Value.Values := New_List; Project_Tree.Variable_Elements.Table (User_Attr_Id) := User_Attr; loop -- Get each element of configuration list Conf_Elem := Project_Tree.String_Elements.Table (Conf_List); New_Elem := Conf_Elem; Conf_List := Conf_Elem.Next; if Conf_List = Nil_String then -- If it is the last element in the list, connect to -- first element of user list, and we are done. New_Elem.Next := User_List; Project_Tree.String_Elements.Table (New_List) := New_Elem; exit; else -- If it is not the last element in the list, add to -- new list. String_Element_Table.Increment_Last (Project_Tree.String_Elements); New_Elem.Next := String_Element_Table.Last (Project_Tree.String_Elements); Project_Tree.String_Elements.Table (New_List) := New_Elem; New_List := New_Elem.Next; end if; end loop; end; end if; end if; Conf_Attr_Id := Conf_Attr.Next; User_Attr_Id := User_Attr.Next; end loop; Conf_Array_Id := Conf_Decl.Arrays; while Conf_Array_Id /= No_Array loop Conf_Array := Project_Tree.Arrays.Table (Conf_Array_Id); User_Array_Id := User_Decl.Arrays; while User_Array_Id /= No_Array loop User_Array := Project_Tree.Arrays.Table (User_Array_Id); exit when User_Array.Name = Conf_Array.Name; User_Array_Id := User_Array.Next; end loop; -- If this associative array does not exist in the user project file, -- do a shallow copy of the full associative array. if User_Array_Id = No_Array then Array_Table.Increment_Last (Project_Tree.Arrays); User_Array := Conf_Array; User_Array.Next := User_Decl.Arrays; User_Decl.Arrays := Array_Table.Last (Project_Tree.Arrays); Project_Tree.Arrays.Table (User_Decl.Arrays) := User_Array; else -- Otherwise, check each array element Conf_Array_Elem_Id := Conf_Array.Value; while Conf_Array_Elem_Id /= No_Array_Element loop Conf_Array_Elem := Project_Tree.Array_Elements.Table (Conf_Array_Elem_Id); User_Array_Elem_Id := User_Array.Value; while User_Array_Elem_Id /= No_Array_Element loop User_Array_Elem := Project_Tree.Array_Elements.Table (User_Array_Elem_Id); exit when User_Array_Elem.Index = Conf_Array_Elem.Index; User_Array_Elem_Id := User_Array_Elem.Next; end loop; -- If the array element does not exist in the user array, -- insert a shallow copy of the conf array element in the -- user array. if User_Array_Elem_Id = No_Array_Element then Array_Element_Table.Increment_Last (Project_Tree.Array_Elements); User_Array_Elem := Conf_Array_Elem; User_Array_Elem.Next := User_Array.Value; User_Array.Value := Array_Element_Table.Last (Project_Tree.Array_Elements); Project_Tree.Array_Elements.Table (User_Array.Value) := User_Array_Elem; Project_Tree.Arrays.Table (User_Array_Id) := User_Array; -- Otherwise, if the value is a string list, prepend the -- user array element with the conf array element value. elsif Conf_Array_Elem.Value.Kind = List then Conf_List := Conf_Array_Elem.Value.Values; if Conf_List /= Nil_String then declare Link : constant String_List_Id := User_Array_Elem.Value.Values; Previous : String_List_Id := Nil_String; Next : String_List_Id; begin loop Conf_List_Elem := Project_Tree.String_Elements.Table (Conf_List); String_Element_Table.Increment_Last (Project_Tree.String_Elements); Next := String_Element_Table.Last (Project_Tree.String_Elements); Project_Tree.String_Elements.Table (Next) := Conf_List_Elem; if Previous = Nil_String then User_Array_Elem.Value.Values := Next; Project_Tree.Array_Elements.Table (User_Array_Elem_Id) := User_Array_Elem; else Project_Tree.String_Elements.Table (Previous).Next := Next; end if; Previous := Next; Conf_List := Conf_List_Elem.Next; if Conf_List = Nil_String then Project_Tree.String_Elements.Table (Previous).Next := Link; exit; end if; end loop; end; end if; end if; Conf_Array_Elem_Id := Conf_Array_Elem.Next; end loop; end if; Conf_Array_Id := Conf_Array.Next; end loop; end Add_Attributes; ------------------------------------ -- Add_Default_GNAT_Naming_Scheme -- ------------------------------------ procedure Add_Default_GNAT_Naming_Scheme (Config_File : in out Project_Node_Id; Project_Tree : Project_Node_Tree_Ref) is procedure Create_Attribute (Name : Name_Id; Value : String; Index : String := ""; Pkg : Project_Node_Id := Empty_Node); ---------------------- -- Create_Attribute -- ---------------------- procedure Create_Attribute (Name : Name_Id; Value : String; Index : String := ""; Pkg : Project_Node_Id := Empty_Node) is Attr : Project_Node_Id; pragma Unreferenced (Attr); Expr : Name_Id := No_Name; Val : Name_Id := No_Name; Parent : Project_Node_Id := Config_File; begin if Index /= "" then Name_Len := Index'Length; Name_Buffer (1 .. Name_Len) := Index; Val := Name_Find; end if; if Pkg /= Empty_Node then Parent := Pkg; end if; Name_Len := Value'Length; Name_Buffer (1 .. Name_Len) := Value; Expr := Name_Find; Attr := Create_Attribute (Tree => Project_Tree, Prj_Or_Pkg => Parent, Name => Name, Index_Name => Val, Kind => Prj.Single, Value => Create_Literal_String (Expr, Project_Tree)); end Create_Attribute; -- Local variables Name : Name_Id; Naming : Project_Node_Id; -- Start of processing for Add_Default_GNAT_Naming_Scheme begin if Config_File = Empty_Node then -- Create a dummy config file is none was found Name_Len := Auto_Cgpr'Length; Name_Buffer (1 .. Name_Len) := Auto_Cgpr; Name := Name_Find; -- An invalid project name to avoid conflicts with user-created ones Name_Len := 5; Name_Buffer (1 .. Name_Len) := "_auto"; Config_File := Create_Project (In_Tree => Project_Tree, Name => Name_Find, Full_Path => Path_Name_Type (Name), Is_Config_File => True); -- Setup library support case MLib.Tgt.Support_For_Libraries is when None => null; when Static_Only => Create_Attribute (Name_Library_Support, "static_only"); when Full => Create_Attribute (Name_Library_Support, "full"); end case; if MLib.Tgt.Standalone_Library_Auto_Init_Is_Supported then Create_Attribute (Name_Library_Auto_Init_Supported, "true"); else Create_Attribute (Name_Library_Auto_Init_Supported, "false"); end if; -- Setup Ada support (Ada is the default language here, since this -- is only called when no config file existed initially, ie for -- gnatmake). Create_Attribute (Name_Default_Language, "ada"); Naming := Create_Package (Project_Tree, Config_File, "naming"); Create_Attribute (Name_Spec_Suffix, ".ads", "ada", Pkg => Naming); Create_Attribute (Name_Separate_Suffix, ".adb", "ada", Pkg => Naming); Create_Attribute (Name_Body_Suffix, ".adb", "ada", Pkg => Naming); Create_Attribute (Name_Dot_Replacement, "-", Pkg => Naming); Create_Attribute (Name_Casing, "lowercase", Pkg => Naming); if Current_Verbosity = High then Write_Line ("Automatically generated (in-memory) config file"); Prj.PP.Pretty_Print (Project => Config_File, In_Tree => Project_Tree, Backward_Compatibility => False); end if; end if; end Add_Default_GNAT_Naming_Scheme; ----------------------- -- Apply_Config_File -- ----------------------- procedure Apply_Config_File (Config_File : Prj.Project_Id; Project_Tree : Prj.Project_Tree_Ref) is Conf_Decl : constant Declarations := Config_File.Decl; Conf_Pack_Id : Package_Id; Conf_Pack : Package_Element; User_Decl : Declarations; User_Pack_Id : Package_Id; User_Pack : Package_Element; Proj : Project_List; begin Proj := Project_Tree.Projects; while Proj /= null loop if Proj.Project /= Config_File then User_Decl := Proj.Project.Decl; Add_Attributes (Project_Tree => Project_Tree, Conf_Decl => Conf_Decl, User_Decl => User_Decl); Conf_Pack_Id := Conf_Decl.Packages; while Conf_Pack_Id /= No_Package loop Conf_Pack := Project_Tree.Packages.Table (Conf_Pack_Id); User_Pack_Id := User_Decl.Packages; while User_Pack_Id /= No_Package loop User_Pack := Project_Tree.Packages.Table (User_Pack_Id); exit when User_Pack.Name = Conf_Pack.Name; User_Pack_Id := User_Pack.Next; end loop; if User_Pack_Id = No_Package then Package_Table.Increment_Last (Project_Tree.Packages); User_Pack := Conf_Pack; User_Pack.Next := User_Decl.Packages; User_Decl.Packages := Package_Table.Last (Project_Tree.Packages); Project_Tree.Packages.Table (User_Decl.Packages) := User_Pack; else Add_Attributes (Project_Tree => Project_Tree, Conf_Decl => Conf_Pack.Decl, User_Decl => Project_Tree.Packages.Table (User_Pack_Id).Decl); end if; Conf_Pack_Id := Conf_Pack.Next; end loop; Proj.Project.Decl := User_Decl; end if; Proj := Proj.Next; end loop; end Apply_Config_File; ------------------ -- Check_Target -- ------------------ function Check_Target (Config_File : Project_Id; Autoconf_Specified : Boolean; Project_Tree : Prj.Project_Tree_Ref; Target : String := "") return Boolean is Variable : constant Variable_Value := Value_Of (Name_Target, Config_File.Decl.Attributes, Project_Tree); Tgt_Name : Name_Id := No_Name; OK : Boolean; begin if Variable /= Nil_Variable_Value and then not Variable.Default then Tgt_Name := Variable.Value; end if; if Target = "" then OK := not Autoconf_Specified or else Tgt_Name = No_Name; else OK := Tgt_Name /= No_Name and then Target = Get_Name_String (Tgt_Name); end if; if not OK then if Autoconf_Specified then if Verbose_Mode then Write_Line ("inconsistent targets, performing autoconf"); end if; return False; else if Tgt_Name /= No_Name then Raise_Invalid_Config ("invalid target name """ & Get_Name_String (Tgt_Name) & """ in configuration"); else Raise_Invalid_Config ("no target specified in configuration file"); end if; end if; end if; return True; end Check_Target; -------------------------------------- -- Get_Or_Create_Configuration_File -- -------------------------------------- procedure Get_Or_Create_Configuration_File (Project : Project_Id; Project_Tree : Project_Tree_Ref; Project_Node_Tree : Prj.Tree.Project_Node_Tree_Ref; Allow_Automatic_Generation : Boolean; Config_File_Name : String := ""; Autoconf_Specified : Boolean; Target_Name : String := ""; Normalized_Hostname : String; Packages_To_Check : String_List_Access := null; Config : out Prj.Project_Id; Config_File_Path : out String_Access; Automatically_Generated : out Boolean; Flags : Processing_Flags; On_Load_Config : Config_File_Hook := null) is At_Least_One_Compiler_Command : Boolean := False; -- Set to True if at least one attribute Ide'Compiler_Command is -- specified for one language of the system. function Default_File_Name return String; -- Return the name of the default config file that should be tested procedure Do_Autoconf; -- Generate a new config file through gprconfig. In case of error, this -- raises the Invalid_Config exception with an appropriate message function Get_Config_Switches return Argument_List_Access; -- Return the --config switches to use for gprconfig function Might_Have_Sources (Project : Project_Id) return Boolean; -- True if the specified project might have sources (ie the user has not -- explicitly specified it. We haven't checked the file system, nor do -- we need to at this stage. ----------------------- -- Default_File_Name -- ----------------------- function Default_File_Name return String is Ada_RTS : constant String := Runtime_Name_For (Name_Ada); Tmp : String_Access; begin if Target_Name /= "" then if Ada_RTS /= "" then return Target_Name & '-' & Ada_RTS & Config_Project_File_Extension; else return Target_Name & Config_Project_File_Extension; end if; elsif Ada_RTS /= "" then return Ada_RTS & Config_Project_File_Extension; else Tmp := Getenv (Config_Project_Env_Var); declare T : constant String := Tmp.all; begin Free (Tmp); if T'Length = 0 then return Default_Name; else return T; end if; end; end if; end Default_File_Name; ------------------------ -- Might_Have_Sources -- ------------------------ function Might_Have_Sources (Project : Project_Id) return Boolean is Variable : Variable_Value; begin Variable := Value_Of (Name_Source_Dirs, Project.Decl.Attributes, Project_Tree); if Variable = Nil_Variable_Value or else Variable.Default or else Variable.Values /= Nil_String then Variable := Value_Of (Name_Source_Files, Project.Decl.Attributes, Project_Tree); return Variable = Nil_Variable_Value or else Variable.Default or else Variable.Values /= Nil_String; else return False; end if; end Might_Have_Sources; ------------------------- -- Get_Config_Switches -- ------------------------- function Get_Config_Switches return Argument_List_Access is package Language_Htable is new GNAT.HTable.Simple_HTable (Header_Num => Prj.Header_Num, Element => Name_Id, No_Element => No_Name, Key => Name_Id, Hash => Prj.Hash, Equal => "="); -- Hash table to keep the languages used in the project tree IDE : constant Package_Id := Value_Of (Name_Ide, Project.Decl.Packages, Project_Tree); Prj_Iter : Project_List; List : String_List_Id; Elem : String_Element; Lang : Name_Id; Variable : Variable_Value; Name : Name_Id; Count : Natural; Result : Argument_List_Access; Check_Default : Boolean; begin Prj_Iter := Project_Tree.Projects; while Prj_Iter /= null loop if Might_Have_Sources (Prj_Iter.Project) then Variable := Value_Of (Name_Languages, Prj_Iter.Project.Decl.Attributes, Project_Tree); if Variable = Nil_Variable_Value or else Variable.Default then -- Languages is not declared. If it is not an extending -- project, or if it extends a project with no Languages, -- check for Default_Language. Check_Default := Prj_Iter.Project.Extends = No_Project; if not Check_Default then Variable := Value_Of (Name_Languages, Prj_Iter.Project.Extends.Decl.Attributes, Project_Tree); Check_Default := Variable /= Nil_Variable_Value and then Variable.Values = Nil_String; end if; if Check_Default then Variable := Value_Of (Name_Default_Language, Prj_Iter.Project.Decl.Attributes, Project_Tree); if Variable /= Nil_Variable_Value and then not Variable.Default then Get_Name_String (Variable.Value); To_Lower (Name_Buffer (1 .. Name_Len)); Lang := Name_Find; Language_Htable.Set (Lang, Lang); else -- If no default language is declared, default to Ada Language_Htable.Set (Name_Ada, Name_Ada); end if; end if; elsif Variable.Values /= Nil_String then -- Attribute Languages is declared with a non empty -- list: put all the languages in Language_HTable. List := Variable.Values; while List /= Nil_String loop Elem := Project_Tree.String_Elements.Table (List); Get_Name_String (Elem.Value); To_Lower (Name_Buffer (1 .. Name_Len)); Lang := Name_Find; Language_Htable.Set (Lang, Lang); List := Elem.Next; end loop; end if; end if; Prj_Iter := Prj_Iter.Next; end loop; Name := Language_Htable.Get_First; Count := 0; while Name /= No_Name loop Count := Count + 1; Name := Language_Htable.Get_Next; end loop; Result := new String_List (1 .. Count); Count := 1; Name := Language_Htable.Get_First; while Name /= No_Name loop -- Check if IDE'Compiler_Command is declared for the language. -- If it is, use its value to invoke gprconfig. Variable := Value_Of (Name, Attribute_Or_Array_Name => Name_Compiler_Command, In_Package => IDE, In_Tree => Project_Tree, Force_Lower_Case_Index => True); declare Config_Command : constant String := "--config=" & Get_Name_String (Name); Runtime_Name : constant String := Runtime_Name_For (Name); begin if Variable = Nil_Variable_Value or else Length_Of_Name (Variable.Value) = 0 then Result (Count) := new String'(Config_Command & ",," & Runtime_Name); else At_Least_One_Compiler_Command := True; declare Compiler_Command : constant String := Get_Name_String (Variable.Value); begin if Is_Absolute_Path (Compiler_Command) then Result (Count) := new String' (Config_Command & ",," & Runtime_Name & "," & Containing_Directory (Compiler_Command) & "," & Simple_Name (Compiler_Command)); else Result (Count) := new String' (Config_Command & ",," & Runtime_Name & ",," & Compiler_Command); end if; end; end if; end; Count := Count + 1; Name := Language_Htable.Get_Next; end loop; return Result; end Get_Config_Switches; ----------------- -- Do_Autoconf -- ----------------- procedure Do_Autoconf is Obj_Dir : constant Variable_Value := Value_Of (Name_Object_Dir, Project.Decl.Attributes, Project_Tree); Gprconfig_Path : String_Access; Success : Boolean; begin Gprconfig_Path := Locate_Exec_On_Path (Gprconfig_Name); if Gprconfig_Path = null then Raise_Invalid_Config ("could not locate gprconfig for auto-configuration"); end if; -- First, find the object directory of the user's project if Obj_Dir = Nil_Variable_Value or else Obj_Dir.Default then Get_Name_String (Project.Directory.Display_Name); else if Is_Absolute_Path (Get_Name_String (Obj_Dir.Value)) then Get_Name_String (Obj_Dir.Value); else Name_Len := 0; Add_Str_To_Name_Buffer (Get_Name_String (Project.Directory.Display_Name)); Add_Str_To_Name_Buffer (Get_Name_String (Obj_Dir.Value)); end if; end if; if Subdirs /= null then Add_Char_To_Name_Buffer (Directory_Separator); Add_Str_To_Name_Buffer (Subdirs.all); end if; for J in 1 .. Name_Len loop if Name_Buffer (J) = '/' then Name_Buffer (J) := Directory_Separator; end if; end loop; declare Obj_Dir : constant String := Name_Buffer (1 .. Name_Len); Switches : Argument_List_Access := Get_Config_Switches; Args : Argument_List (1 .. 5); Arg_Last : Positive; Obj_Dir_Exists : Boolean := True; begin -- Check if the object directory exists. If Setup_Projects is True -- (-p) and directory does not exist, attempt to create it. -- Otherwise, if directory does not exist, fail without calling -- gprconfig. if not Is_Directory (Obj_Dir) and then (Setup_Projects or else Subdirs /= null) then begin Create_Path (Obj_Dir); if not Quiet_Output then Write_Str ("object directory """); Write_Str (Obj_Dir); Write_Line (""" created"); end if; exception when others => Raise_Invalid_Config ("could not create object directory " & Obj_Dir); end; end if; if not Is_Directory (Obj_Dir) then case Flags.Require_Obj_Dirs is when Error => Raise_Invalid_Config ("object directory " & Obj_Dir & " does not exist"); when Warning => Prj.Err.Error_Msg (Flags, "?object directory " & Obj_Dir & " does not exist"); Obj_Dir_Exists := False; when Silent => null; end case; end if; -- Invoke gprconfig Args (1) := new String'("--batch"); Args (2) := new String'("-o"); -- If no config file was specified, set the auto.cgpr one if Config_File_Name = "" then if Obj_Dir_Exists then Args (3) := new String'(Obj_Dir & Directory_Separator & Auto_Cgpr); else declare Path_FD : File_Descriptor; Path_Name : Path_Name_Type; begin Prj.Env.Create_Temp_File (In_Tree => Project_Tree, Path_FD => Path_FD, Path_Name => Path_Name, File_Use => "configuration file"); if Path_FD /= Invalid_FD then Args (3) := new String'(Get_Name_String (Path_Name)); GNAT.OS_Lib.Close (Path_FD); else -- We'll have an error message later on Args (3) := new String' (Obj_Dir & Directory_Separator & Auto_Cgpr); end if; end; end if; else Args (3) := new String'(Config_File_Name); end if; if Normalized_Hostname = "" then Arg_Last := 3; else if Target_Name = "" then if At_Least_One_Compiler_Command then Args (4) := new String'("--target=all"); else Args (4) := new String'("--target=" & Normalized_Hostname); end if; else Args (4) := new String'("--target=" & Target_Name); end if; Arg_Last := 4; end if; if not Verbose_Mode then Arg_Last := Arg_Last + 1; Args (Arg_Last) := new String'("-q"); end if; if Verbose_Mode then Write_Str (Gprconfig_Name); for J in 1 .. Arg_Last loop Write_Char (' '); Write_Str (Args (J).all); end loop; for J in Switches'Range loop Write_Char (' '); Write_Str (Switches (J).all); end loop; Write_Eol; elsif not Quiet_Output then -- Display no message if we are creating auto.cgpr, unless in -- verbose mode if Config_File_Name /= "" or else Verbose_Mode then Write_Str ("creating "); Write_Str (Simple_Name (Args (3).all)); Write_Eol; end if; end if; Spawn (Gprconfig_Path.all, Args (1 .. Arg_Last) & Switches.all, Success); Free (Switches); Config_File_Path := Locate_Config_File (Args (3).all); if Config_File_Path = null then Raise_Invalid_Config ("could not create " & Args (3).all); end if; for F in Args'Range loop Free (Args (F)); end loop; end; end Do_Autoconf; Success : Boolean; Config_Project_Node : Project_Node_Id := Empty_Node; begin Free (Config_File_Path); Config := No_Project; if Config_File_Name /= "" then Config_File_Path := Locate_Config_File (Config_File_Name); else Config_File_Path := Locate_Config_File (Default_File_Name); end if; if Config_File_Path = null then if (not Allow_Automatic_Generation) and then Config_File_Name /= "" then Raise_Invalid_Config ("could not locate main configuration project " & Config_File_Name); end if; end if; Automatically_Generated := Allow_Automatic_Generation and then Config_File_Path = null; <<Process_Config_File>> if Automatically_Generated then if Hostparm.OpenVMS then -- There is no gprconfig on VMS Raise_Invalid_Config ("could not locate any configuration project file"); else -- This might raise an Invalid_Config exception Do_Autoconf; end if; end if; -- Parse the configuration file if Verbose_Mode and then Config_File_Path /= null then Write_Str ("Checking configuration "); Write_Line (Config_File_Path.all); end if; if Config_File_Path /= null then Prj.Part.Parse (In_Tree => Project_Node_Tree, Project => Config_Project_Node, Project_File_Name => Config_File_Path.all, Always_Errout_Finalize => False, Packages_To_Check => Packages_To_Check, Current_Directory => Current_Directory, Is_Config_File => True, Flags => Flags); else -- Maybe the user will want to create his own configuration file Config_Project_Node := Empty_Node; end if; if On_Load_Config /= null then On_Load_Config (Config_File => Config_Project_Node, Project_Node_Tree => Project_Node_Tree); end if; if Config_Project_Node /= Empty_Node then Prj.Proc.Process_Project_Tree_Phase_1 (In_Tree => Project_Tree, Project => Config, Success => Success, From_Project_Node => Config_Project_Node, From_Project_Node_Tree => Project_Node_Tree, Flags => Flags, Reset_Tree => False); end if; if Config_Project_Node = Empty_Node or else Config = No_Project then Raise_Invalid_Config ("processing of configuration project """ & Config_File_Path.all & """ failed"); end if; -- Check that the target of the configuration file is the one the user -- specified on the command line. We do not need to check that when in -- auto-conf mode, since the appropriate target was passed to gprconfig. if not Automatically_Generated and then not Check_Target (Config, Autoconf_Specified, Project_Tree, Target_Name) then Automatically_Generated := True; goto Process_Config_File; end if; end Get_Or_Create_Configuration_File; ------------------------ -- Locate_Config_File -- ------------------------ function Locate_Config_File (Name : String) return String_Access is Prefix_Path : constant String := Executable_Prefix_Path; begin if Prefix_Path'Length /= 0 then return Locate_Regular_File (Name, "." & Path_Separator & Prefix_Path & "share" & Directory_Separator & "gpr"); else return Locate_Regular_File (Name, "."); end if; end Locate_Config_File; ------------------------------------ -- Parse_Project_And_Apply_Config -- ------------------------------------ procedure Parse_Project_And_Apply_Config (Main_Project : out Prj.Project_Id; User_Project_Node : out Prj.Tree.Project_Node_Id; Config_File_Name : String := ""; Autoconf_Specified : Boolean; Project_File_Name : String; Project_Tree : Prj.Project_Tree_Ref; Project_Node_Tree : Prj.Tree.Project_Node_Tree_Ref; Packages_To_Check : String_List_Access; Allow_Automatic_Generation : Boolean := True; Automatically_Generated : out Boolean; Config_File_Path : out String_Access; Target_Name : String := ""; Normalized_Hostname : String; Flags : Processing_Flags; On_Load_Config : Config_File_Hook := null) is begin -- Parse the user project tree Prj.Initialize (Project_Tree); Main_Project := No_Project; Automatically_Generated := False; Prj.Part.Parse (In_Tree => Project_Node_Tree, Project => User_Project_Node, Project_File_Name => Project_File_Name, Always_Errout_Finalize => False, Packages_To_Check => Packages_To_Check, Current_Directory => Current_Directory, Is_Config_File => False, Flags => Flags); if User_Project_Node = Empty_Node then User_Project_Node := Empty_Node; return; end if; Process_Project_And_Apply_Config (Main_Project => Main_Project, User_Project_Node => User_Project_Node, Config_File_Name => Config_File_Name, Autoconf_Specified => Autoconf_Specified, Project_Tree => Project_Tree, Project_Node_Tree => Project_Node_Tree, Packages_To_Check => Packages_To_Check, Allow_Automatic_Generation => Allow_Automatic_Generation, Automatically_Generated => Automatically_Generated, Config_File_Path => Config_File_Path, Target_Name => Target_Name, Normalized_Hostname => Normalized_Hostname, Flags => Flags, On_Load_Config => On_Load_Config); end Parse_Project_And_Apply_Config; -------------------------------------- -- Process_Project_And_Apply_Config -- -------------------------------------- procedure Process_Project_And_Apply_Config (Main_Project : out Prj.Project_Id; User_Project_Node : Prj.Tree.Project_Node_Id; Config_File_Name : String := ""; Autoconf_Specified : Boolean; Project_Tree : Prj.Project_Tree_Ref; Project_Node_Tree : Prj.Tree.Project_Node_Tree_Ref; Packages_To_Check : String_List_Access; Allow_Automatic_Generation : Boolean := True; Automatically_Generated : out Boolean; Config_File_Path : out String_Access; Target_Name : String := ""; Normalized_Hostname : String; Flags : Processing_Flags; On_Load_Config : Config_File_Hook := null; Reset_Tree : Boolean := True) is Main_Config_Project : Project_Id; Success : Boolean; begin Main_Project := No_Project; Automatically_Generated := False; Process_Project_Tree_Phase_1 (In_Tree => Project_Tree, Project => Main_Project, Success => Success, From_Project_Node => User_Project_Node, From_Project_Node_Tree => Project_Node_Tree, Flags => Flags, Reset_Tree => Reset_Tree); if not Success then Main_Project := No_Project; return; end if; if Project_Tree.Source_Info_File_Name /= null then if not Is_Absolute_Path (Project_Tree.Source_Info_File_Name.all) then declare Obj_Dir : constant Variable_Value := Value_Of (Name_Object_Dir, Main_Project.Decl.Attributes, Project_Tree); begin if Obj_Dir = Nil_Variable_Value or else Obj_Dir.Default then Get_Name_String (Main_Project.Directory.Display_Name); else if Is_Absolute_Path (Get_Name_String (Obj_Dir.Value)) then Get_Name_String (Obj_Dir.Value); else Name_Len := 0; Add_Str_To_Name_Buffer (Get_Name_String (Main_Project.Directory.Display_Name)); Add_Str_To_Name_Buffer (Get_Name_String (Obj_Dir.Value)); end if; end if; Add_Char_To_Name_Buffer (Directory_Separator); Add_Str_To_Name_Buffer (Project_Tree.Source_Info_File_Name.all); Free (Project_Tree.Source_Info_File_Name); Project_Tree.Source_Info_File_Name := new String'(Name_Buffer (1 .. Name_Len)); end; end if; Read_Source_Info_File (Project_Tree); end if; -- Find configuration file Get_Or_Create_Configuration_File (Config => Main_Config_Project, Project => Main_Project, Project_Tree => Project_Tree, Project_Node_Tree => Project_Node_Tree, Allow_Automatic_Generation => Allow_Automatic_Generation, Config_File_Name => Config_File_Name, Autoconf_Specified => Autoconf_Specified, Target_Name => Target_Name, Normalized_Hostname => Normalized_Hostname, Packages_To_Check => Packages_To_Check, Config_File_Path => Config_File_Path, Automatically_Generated => Automatically_Generated, Flags => Flags, On_Load_Config => On_Load_Config); Apply_Config_File (Main_Config_Project, Project_Tree); -- Finish processing the user's project Prj.Proc.Process_Project_Tree_Phase_2 (In_Tree => Project_Tree, Project => Main_Project, Success => Success, From_Project_Node => User_Project_Node, From_Project_Node_Tree => Project_Node_Tree, Flags => Flags); if Success then if Project_Tree.Source_Info_File_Name /= null and then not Project_Tree.Source_Info_File_Exists then Write_Source_Info_File (Project_Tree); end if; else Main_Project := No_Project; end if; end Process_Project_And_Apply_Config; -------------------------- -- Raise_Invalid_Config -- -------------------------- procedure Raise_Invalid_Config (Msg : String) is begin Raise_Exception (Invalid_Config'Identity, Msg); end Raise_Invalid_Config; ---------------------- -- Runtime_Name_For -- ---------------------- function Runtime_Name_For (Language : Name_Id) return String is begin if RTS_Languages.Get (Language) /= No_Name then return Get_Name_String (RTS_Languages.Get (Language)); else return ""; end if; end Runtime_Name_For; --------------------- -- Set_Runtime_For -- --------------------- procedure Set_Runtime_For (Language : Name_Id; RTS_Name : String) is begin Name_Len := RTS_Name'Length; Name_Buffer (1 .. Name_Len) := RTS_Name; RTS_Languages.Set (Language, Name_Find); end Set_Runtime_For; end Prj.Conf;
-- -- ABench2020 Benchmark Suite -- -- Linear Search Program -- -- Licensed under the MIT License. See LICENSE file in the ABench root -- directory for license information. -- -- Uncomment the line below to print the result. -- with Ada.Text_IO; use Ada.Text_IO; procedure Linear_Search is type Vector is array (Natural range<>) of Integer; procedure Search (Search_Array : Vector; Search_Value : Integer) is Count : Integer := 0; Index : Integer := 0; begin for I in 1 .. Search_Array'Last loop if Search_Array (I) = Search_Value then Count := Count + 1; end if; end loop; if Count = 0 then return; end if; declare Index_Array : Vector (1 .. Count); begin for I in 1 .. Search_Array'Last loop if Search_Array (I) = Search_Value then Index := Index + 1; Index_Array (Index) := I; end if; end loop; -- Uncomment the line below to print the result. -- for I in 1 .. Index_Array'Last loop -- Put (Integer'Image (Index_Array (I))); -- end loop; end; end; Search_Value : Integer; Search_Array : Vector := (3, 4, 7, 8, 9, 10, 11, 24, 25, 55, 56, 78, 90, 98, 120, 134, 152, 155, 165, 167, 168, 198, 250, 287, 298, 300, 310, 333, 338, 350, 399, 442, 475, 567); begin loop Search_Value := 250; Search (Search_Array, Search_Value); end loop; end;
------------------------------------------------------------------------------- -- Copyright (c) 2019, Daniel King -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- * Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- * The name of the copyright holder may not be used to endorse or promote -- Products derived from this software without specific prior written -- permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -- DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------- with Keccak.Types; -- @summary -- Implements an optimized Keccak-f permutation based on SIMD instruction sets -- such as SSE, NEON, and AVX. -- -- @description -- This package provides a basis for parallel implementations of Keccak -- for processing N separate permutations in parallel, where N is the number -- of vector components in the SIMD instruction set used. -- -- When instantiating this package, subprograms and types are provided as -- formal generic parameters which implement each of the required operations -- for the target instruction set. -- -- @group Parallel Keccak-f generic Lane_Size_Log : in Positive; -- The binary logarithm of the lane size. -- -- This determines the Keccak-f state size. Allowed values are: -- * Lane_Size_Log = 3 => 8-bit lanes, Keccak-f[200] -- * Lane_Size_Log = 4 => 16-bit lanes, Keccak-f[400] -- * Lane_Size_Log = 5 => 32-bit lanes, Keccak-f[800] -- * Lane_Size_Log = 6 => 64-bit lanes, Keccak-f[1600] type Lane_Type is mod <>; -- Lane type e.g. Unsigned_64. type VXXI_Index is range <>; -- Index type into the vector component. type VXXI is private; -- Vector type. type VXXI_View is array (VXXI_Index) of Lane_Type; -- A view of the vector type, permitting individual access to each vector -- component. Vector_Width : Positive; -- Number of vector to components to actually use. -- -- Usually, this would be set to the actual number of vector components -- (e.g. 4 for a 4x 32-bit vector). However, you may use a smaller number -- if you don't want to use the full vector width. For example, you could -- set Vector_Width to 2 with a 4x 32-bit vector type, to obtain 2x -- parallelism (the upper 2 vector components would not be used). with function Load (X : in VXXI_View) return VXXI; with function Store (X : in VXXI) return VXXI_View; with function "xor" (A, State_Size_Bits : in VXXI) return VXXI; -- Calculates A xor State_Size_Bits per vector component. with function Rotate_Left (A : in VXXI; Amount : in Natural) return VXXI; -- Calculates Rotate_Left(A) per vector component. with function And_Not (A, State_Size_Bits : in VXXI) return VXXI; -- Calculates State_Size_Bits and (not A) per vector component. with function Shift_Left (A : in Lane_Type; Amount : in Natural) return Lane_Type; with function Shift_Right (A : in Lane_Type; Amount : in Natural) return Lane_Type; package Keccak.Generic_Parallel_KeccakF is Lane_Size_Bits : constant Positive := 2**Lane_Size_Log; -- Lane size (in bits, i.e. 8, 16, 32, or 64) State_Size_Bits : constant Positive := Lane_Size_Bits * 25; -- Keccak-f state size (in bits). Num_Parallel_Instances : constant Positive := Vector_Width; pragma Assert (Lane_Size_Bits mod 8 = 0, "Generic_Parallel_KeccakF only supports Lane_Size_Log in 3 .. 6"); pragma Assert (Vector_Width in 1 .. VXXI_View'Length, "Vector_Width exceeds vector type's width"); type Parallel_State is private; Initialized_State : constant Parallel_State; type Round_Index is range 0 .. 23; subtype Round_Count is Positive range 1 .. 24; procedure Init (S : out Parallel_State) with Global => null; -- Initialise the Keccak state to all zeroes. generic First_Round : Round_Index := 0; Num_Rounds : Round_Count := 24; procedure Permute_All (S : in out Parallel_State) with Global => null; -- Applies the Keccak-f permutation function to all N parallel states. -- -- This generic function is a Keccak-p permutation which is -- instantiated, with the number rounds, into a Keccak-f instance. procedure XOR_Bits_Into_State_Separate (S : in out Parallel_State; Data : in Types.Byte_Array; Data_Offset : in Natural; Bit_Len : in Natural) with Global => null, Pre => (Data'Length / Vector_Width <= Natural'Last / 8 and then Data'Length mod Vector_Width = 0 and then Data_Offset <= (Data'Length / Vector_Width) and then Bit_Len <= ((Data'Length / Vector_Width) - Data_Offset) * 8 and then Bit_Len <= State_Size_Bits); -- XOR separate data into each parallel Keccak instance. -- -- The @Data@ array contains the data to be XORed into all parallel -- instances. The bytes in @Data@ are split into equal chunks depending on -- the number of parallel instances. For example, for Keccak-f[1600]�2 the -- @Data@ array is split into 2 chunks as shown below: -- -- . DO BL DO BL -- |--->|<---->| |--->|<---->| -- +-----------------------------------------+ -- | | | Data -- +-----------------------------------------+ -- . | | | | -- . | XOR | | XOR | -- . | v | | v | -- . +-----------+ +-----------+ -- . | state 0 | | state 1 | -- . +-----------+ +-----------+ -- -- Where DO = Data_Offset and BL = Bit_Len -- -- The @Data_Offset@ determines the offset within each chunk to start -- reading data. @Bit_Len@ determines the number of bits to read from each -- chunk. -- -- The data is always XORed starting at the beginning of the Keccak state. -- -- @param S The parallel Keccak state to where the bits are XORed. -- -- @param Data The array containing the data to XOR into the parallel state. -- The size of this array must be a multiple of the number of parallel -- instances. For Example, for Keccak-f[1600]�4 then Data'Length -- must be a multiple of 4. -- -- @param Data_Offset Offset of the first byte(s) to read from the @Data@ -- array. -- -- @param Bit_Len The number of bits to XOR into each state. procedure XOR_Bits_Into_State_All (S : in out Parallel_State; Data : in Types.Byte_Array; Bit_Len : in Natural) with Global => null, Depends => (S =>+ (Data, Bit_Len)), Pre => (Data'Length <= Natural'Last / 8 and then Bit_Len <= Data'Length * 8 and then Bit_Len <= State_Size_Bits); -- XOR the same data into all parallel Keccak instances. -- -- The @Data@ array contains the data to be XORed into all parallel -- instances. For example, for Keccak-f[1600]�2 this would be as follows: -- -- . BL -- . |<--------->| -- . +----------------+ -- . | | Data -- . +----------------+ -- . /\ -- . XOR / \ XOR -- . v / \ v -- +-----------+-----------+ -- | state 0 | state 1 | -- +-----------+-----------+ -- -- Where BL = Bit_Len -- -- The data is always XORed starting at the beginning of the Keccak state. -- -- @param S The parallel Keccak state to where the bits are XORed. -- -- @param Data The array containing the data to XOR into each parallel state. -- -- @param Bit_Len The length of the data, in bits. procedure Extract_Bytes (S : in Parallel_State; Data : in out Types.Byte_Array; Data_Offset : in Natural; Byte_Len : in Natural) with Global => null, Pre => (Data'Length mod Vector_Width = 0 and then Data_Offset <= Data'Length / Vector_Width and then Byte_Len <= (Data'Length / Vector_Width) - Data_Offset and then Byte_Len <= State_Size_Bits / 8); -- Extract bytes from the Keccak state. -- -- The @Data@ array is split into N equal sized chunks, where N is the -- number of parallel instances. The bytes extracted from each Keccak -- state is then copied into the each chunk, offset by @Data_Offset@. -- An example is shown below for Keccak-f[1600]�2 (i.e. 2 parallel -- instances): -- -- . DO BL DO BL -- |--->|<---->| |--->|<---->| -- +-----------------------------------------+ -- | | | Data -- +-----------------------------------------+ -- . | ^ | | ^ | -- . | Read | | Read | -- . | | | | -- . +-----------+ +-----------+ -- . | state 0 | | state 1 | -- . +-----------+ +-----------+ -- -- The bytes are always read from the beginning of the Keccak state. -- -- @param S The Keccak state to read bytes from. -- -- @param Data Bytes extracted from the Keccak state are copied to this -- array, offset according to @Data_Offset@. -- -- @param Data_Offset The offset in the @Data@ array to mark the position -- of the first byte in each chunk. -- -- @param Byte_Len The number of bytes to read from each chunk. private type X_Coord is mod 5; type Y_Coord is mod 5; type Parallel_State is array (X_Coord, Y_Coord) of VXXI_View; Initialized_State : constant Parallel_State := (others => (others => (others => 0))); end Keccak.Generic_Parallel_KeccakF;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- S E M _ M E C H -- -- -- -- B o d y -- -- -- -- Copyright (C) 1996-2020, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING3. If not, go to -- -- http://www.gnu.org/licenses for a complete copy of the license. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Atree; use Atree; with Einfo; use Einfo; with Errout; use Errout; with Namet; use Namet; with Sem; use Sem; with Sem_Aux; use Sem_Aux; with Sinfo; use Sinfo; with Snames; use Snames; package body Sem_Mech is ------------------------- -- Set_Mechanism_Value -- ------------------------- procedure Set_Mechanism_Value (Ent : Entity_Id; Mech_Name : Node_Id) is procedure Bad_Mechanism; -- Signal bad mechanism name ------------------- -- Bad_Mechanism -- ------------------- procedure Bad_Mechanism is begin Error_Msg_N ("unrecognized mechanism name", Mech_Name); end Bad_Mechanism; -- Start of processing for Set_Mechanism_Value begin if Mechanism (Ent) /= Default_Mechanism then Error_Msg_NE ("mechanism for & has already been set", Mech_Name, Ent); end if; -- MECHANISM_NAME ::= value | reference if Nkind (Mech_Name) = N_Identifier then if Chars (Mech_Name) = Name_Value then Set_Mechanism_With_Checks (Ent, By_Copy, Mech_Name); elsif Chars (Mech_Name) = Name_Reference then Set_Mechanism_With_Checks (Ent, By_Reference, Mech_Name); elsif Chars (Mech_Name) = Name_Copy then Error_Msg_N ("bad mechanism name, Value assumed", Mech_Name); Set_Mechanism (Ent, By_Copy); else Bad_Mechanism; end if; else Bad_Mechanism; end if; end Set_Mechanism_Value; ------------------------------- -- Set_Mechanism_With_Checks -- ------------------------------- procedure Set_Mechanism_With_Checks (Ent : Entity_Id; Mech : Mechanism_Type; Enod : Node_Id) is pragma Unreferenced (Enod); begin -- Right now we don't do any checks, should we do more ??? Set_Mechanism (Ent, Mech); end Set_Mechanism_With_Checks; -------------------- -- Set_Mechanisms -- -------------------- procedure Set_Mechanisms (E : Entity_Id) is Formal : Entity_Id; Typ : Entity_Id; begin -- Skip this processing if inside a generic template. Not only is -- it unnecessary (since neither extra formals nor mechanisms are -- relevant for the template itself), but at least at the moment, -- procedures get frozen early inside a template so attempting to -- look at the formal types does not work too well if they are -- private types that have not been frozen yet. if Inside_A_Generic then return; end if; -- Loop through formals Formal := First_Formal (E); while Present (Formal) loop if Mechanism (Formal) = Default_Mechanism then Typ := Underlying_Type (Etype (Formal)); -- If there is no underlying type, then skip this processing and -- leave the convention set to Default_Mechanism. It seems odd -- that there should ever be such cases but there are (see -- comments for filed regression tests 1418-001 and 1912-009) ??? if No (Typ) then goto Skip_Formal; end if; case Convention (E) is --------- -- Ada -- --------- -- Note: all RM defined conventions are treated the same from -- the point of view of parameter passing mechanism. Convention -- Ghost has the same dynamic semantics as convention Ada. when Convention_Ada | Convention_Entry | Convention_Intrinsic | Convention_Protected | Convention_Stubbed => -- By reference types are passed by reference (RM 6.2(4)) if Is_By_Reference_Type (Typ) then Set_Mechanism (Formal, By_Reference); -- By copy types are passed by copy (RM 6.2(3)) elsif Is_By_Copy_Type (Typ) then Set_Mechanism (Formal, By_Copy); -- All other types we leave the Default_Mechanism set, so -- that the backend can choose the appropriate method. else null; end if; -- Special Ada conventions specifying passing mechanism when Convention_Ada_Pass_By_Copy => Set_Mechanism (Formal, By_Copy); when Convention_Ada_Pass_By_Reference => Set_Mechanism (Formal, By_Reference); ------- -- C -- ------- -- Note: Assembler and Stdcall also use C conventions when Convention_Assembler | Convention_C_Family | Convention_Stdcall => -- The following values are passed by copy -- IN Scalar parameters (RM B.3(66)) -- IN parameters of access types (RM B.3(67)) -- Access parameters (RM B.3(68)) -- Access to subprogram types (RM B.3(71)) -- Note: in the case of access parameters, it is the pointer -- that is passed by value. In GNAT access parameters are -- treated as IN parameters of an anonymous access type, so -- this falls out free. -- The bottom line is that all IN elementary types are -- passed by copy in GNAT. if Is_Elementary_Type (Typ) then if Ekind (Formal) = E_In_Parameter then Set_Mechanism (Formal, By_Copy); -- OUT and IN OUT parameters of elementary types are -- passed by reference (RM B.3(68)). Note that we are -- not following the advice to pass the address of a -- copy to preserve by copy semantics. else Set_Mechanism (Formal, By_Reference); end if; -- Records are normally passed by reference (RM B.3(69)). -- However, this can be overridden by the use of the -- C_Pass_By_Copy pragma or C_Pass_By_Copy convention. elsif Is_Record_Type (Typ) then -- If the record is not convention C, then we always -- pass by reference, C_Pass_By_Copy does not apply. if Convention (Typ) /= Convention_C then Set_Mechanism (Formal, By_Reference); -- OUT and IN OUT parameters of record types are passed -- by reference regardless of pragmas (RM B.3 (69/2)). elsif Ekind (Formal) in E_Out_Parameter | E_In_Out_Parameter then Set_Mechanism (Formal, By_Reference); -- IN parameters of record types are passed by copy only -- when the related type has convention C_Pass_By_Copy -- (RM B.3 (68.1/2)). elsif Ekind (Formal) = E_In_Parameter and then C_Pass_By_Copy (Typ) then Set_Mechanism (Formal, By_Copy); -- Otherwise, for a C convention record, we set the -- convention in accordance with a possible use of -- the C_Pass_By_Copy pragma. Note that the value of -- Default_C_Record_Mechanism in the absence of such -- a pragma is By_Reference. else Set_Mechanism (Formal, Default_C_Record_Mechanism); end if; -- Array types are passed by reference (B.3 (71)) elsif Is_Array_Type (Typ) then Set_Mechanism (Formal, By_Reference); -- For all other types, use Default_Mechanism mechanism else null; end if; ----------- -- COBOL -- ----------- when Convention_COBOL => -- Access parameters (which in GNAT look like IN parameters -- of an access type) are passed by copy (RM B.4(96)) as -- are all other IN parameters of scalar type (RM B.4(97)). -- For now we pass these parameters by reference as well. -- The RM specifies the intent BY_CONTENT, but gigi does -- not currently transform By_Copy properly. If we pass by -- reference, it will be imperative to introduce copies ??? if Is_Elementary_Type (Typ) and then Ekind (Formal) = E_In_Parameter then Set_Mechanism (Formal, By_Reference); -- All other parameters (i.e. all non-scalar types, and -- all OUT or IN OUT parameters) are passed by reference. -- Note that at the moment we are not bothering to make -- copies of scalar types as recommended in the RM. else Set_Mechanism (Formal, By_Reference); end if; ------------- -- Fortran -- ------------- when Convention_Fortran => -- Access types are passed by default (presumably this -- will mean they are passed by copy) if Is_Access_Type (Typ) then null; -- For now, we pass all other parameters by reference. -- It is not clear that this is right in the long run, -- but it seems to correspond to what gnu f77 wants. else Set_Mechanism (Formal, By_Reference); end if; end case; end if; <<Skip_Formal>> -- remove this when problem above is fixed ??? Next_Formal (Formal); end loop; -- Note: there is nothing we need to do for the return type here. -- We deal with returning by reference in the Ada sense, by use of -- the flag By_Ref, rather than by messing with mechanisms. -- A mechanism of Reference for the return means that an extra -- parameter must be provided for the return value (that is the -- DEC meaning of the pragma), and is unrelated to the Ada notion -- of return by reference. -- Note: there was originally code here to set the mechanism to -- By_Reference for types that are "by reference" in the Ada sense, -- but, in accordance with the discussion above, this is wrong, and -- the code was removed. end Set_Mechanisms; end Sem_Mech;
package Opt42 is type Index_Type is range 1 .. 7; type Row_Type is array (Index_Type) of Float; type Array_Type is array (Index_Type) of Row_Type; function "*" (Left, Right : in Array_Type) return Array_Type; end Opt42;
----------------------------------------------------------------------- -- secret-services -- Ada wrapper for Secret Service -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Secret.Attributes; with Secret.Values; -- === Secret Service === -- The <tt>Secret.Services</tt> package defines the <tt>Service_Type</tt> that gives -- access to the secret service provided by the desktop keyring manager. The service -- instance is declared as follows: -- -- Service : Secret.Services.Service_Type; -- -- The initialization is optional since the libsecret API will do the initialization itself -- if necessary. However, the initialization could be useful to indicate to open a session -- and/or to load the collections. In that case, the <tt>Initialize</tt> procedure is called: -- -- Service.Initialize (Open_Session => True); -- -- The list of attributes that allows to retrieve the secret value must be declared and -- initialized with the key/value pairs: -- -- Attr : Secret.Attributes.Map; -- -- and the key/value pairs are inserted as follows: -- -- Attr.Insert ("my-key", "my-value"); -- -- The secret value is represented by the <tt>Secret_Type</tt> and it is initialized as -- follows: -- -- Value : Secret.Values.Secret_Type := Secret.Values.Create ("my-password-to-protect"); -- -- Then, storing the secret value is done by the <tt>Store</tt> procedure and the label -- is given to help identifying the value from the keyring manager: -- -- Service.Store (Attr, "Application password", Value); -- package Secret.Services is Service_Error : exception; type Service_Type is new Object_Type with null record; -- Initialize the secret service instance by getting a secret service proxy and -- making sure the service has the service flags initialized. procedure Initialize (Service : out Service_Type; Open_Session : in Boolean := False; Load_Collections : in Boolean := False); -- Store the value in the secret service identified by the attributes and associate -- the value with the given label. procedure Store (Service : in Service_Type; Attr : in Secret.Attributes.Map; Label : in String; Value : in Secret.Values.Secret_Type) with Pre => not Attr.Is_Null and not Value.Is_Null; -- Lookup in the secret service the value identified by the attributes. function Lookup (Service : in Service_Type; Attr : in Secret.Attributes.Map) return Secret.Values.Secret_Type with Pre => not Attr.Is_Null; -- Remove from the secret service the value associated with the given attributes. procedure Remove (Service : in Service_Type; Attr : in Secret.Attributes.Map) with Pre => not Attr.Is_Null; end Secret.Services;
pragma Check_Policy (Trace => Ignore); package body System.Shared_Storage is procedure Shared_Var_Lock (Var : String) is begin pragma Check (Trace, Ada.Debug.Put (Var)); Lock_Hook (Var); end Shared_Var_Lock; procedure Shared_Var_Unlock (Var : String) is begin pragma Check (Trace, Ada.Debug.Put (Var)); Unlock_Hook (Var); end Shared_Var_Unlock; package body Shared_Var_Procs is procedure Read is pragma Check (Trace, Ada.Debug.Put (Full_Name)); Stream : constant access Ada.Streams.Root_Stream_Type'Class := Read_Hook (Full_Name); begin if Stream /= null then Typ'Read (Stream, V); end if; end Read; procedure Write is pragma Check (Trace, Ada.Debug.Put (Full_Name)); Stream : constant access Ada.Streams.Root_Stream_Type'Class := Write_Hook (Full_Name); begin if Stream /= null then Typ'Write (Stream, V); end if; end Write; end Shared_Var_Procs; end System.Shared_Storage;
-- LED-Library by Emanuel Regnath (emanuel.regnath@tum.de) Date:2_015-05-20 -- -- Description: -- Portable LED Library that features switching, blinking and morse (non-blocking) -- -- Setup: -- To port the lib to your system, simply overwrite the 2 functions LED_HAL_init -- and LED_HAL_set in the .cpp file and adjust the HAL part in the .hpp file -- -- Usage: -- 1. call LED_init which will configure the LED port and pin -- 2. call LED_switch or LED_blink or LED_morse to select the operation mode -- 3. frequently call LED_tick and LED_sync to manage LED timings. -- with HIL.Devices; package LED_Manager is -- HAL: adjust these types to your system -- ---------------------------------------------------------------------------- type Time_Type is new Natural; -- max. value: 7 * BLINK_TIME BLINK_TIME : constant Time_Type := 250; -- arbitrary time basis (dot time in morse mode) type LED_State_Type is (ON, OFF); type LED_Blink_Type is (FLASH, FAST, SLOW); type LED_Blink_Speed_Type is array (LED_Blink_Type) of Time_Type; --type Color_Type is Array (Positive range <> ) of HIL.Devices.Device_Type_GPIO; type Color_Type is array (HIL.Devices.Device_Type_LED) of Boolean; procedure Set_Color (col : Color_Type); -- for all of the subsequent methods, select color to use -- increases the internal timing counter -- elapsed_time should be a divider of BLINK_TIME. procedure LED_tick (elapsed_time : Time_Type); -- perform LED switching in blink or morse mode procedure LED_sync; -- switch LED on or off (will stop blink or morse mode) procedure LED_switchOn; procedure LED_switchOff; -- select blink mode procedure LED_blink (speed : LED_Blink_Type); procedure LED_blinkPulse (on_time : Time_Type; off_time : Time_Type); end LED_Manager;
------------------------------------------------------------------------------ -- -- -- AUDIO / RIFF / WAV -- -- -- -- Reporting of RIFF format information for wavefiles -- -- -- -- The MIT License (MIT) -- -- -- -- Copyright (c) 2015 -- 2020 Gustavo A. Hoffmann -- -- -- -- Permission is hereby granted, free of charge, to any person obtaining -- -- a copy of this software and associated documentation files (the -- -- "Software"), to deal in the Software without restriction, including -- -- without limitation the rights to use, copy, modify, merge, publish, -- -- distribute, sublicense, and / or sell copies of the Software, and to -- -- permit persons to whom the Software is furnished to do so, subject to -- -- the following conditions: -- -- -- -- The above copyright notice and this permission notice shall be -- -- included in all copies or substantial portions of the Software. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -- -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -- -- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -- -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -- -- CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -- -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -- -- SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -- ------------------------------------------------------------------------------ with Ada.Text_IO; use Ada.Text_IO; with Audio.RIFF.Wav.GUIDs; use Audio.RIFF.Wav.GUIDs; package body Audio.RIFF.Wav.Formats.Report is ----------- -- Print -- ----------- procedure Print (W : Wave_Format_Extensible) is begin Put_Line ("------------ WAVEFORMAT header ------------"); Put_Line ("Format: " & Wav_Format_Tag'Image (W.Format_Tag)); Put_Line ("BitsPerSample: " & Image (W.Bits_Per_Sample)); Put_Line ("Channels: " & Unsigned_16'Image (W.Channels)); Put_Line ("SamplesPerSec: " & Positive'Image (To_Positive (W.Samples_Per_Sec))); Put_Line ("BlockAlign: " & Unsigned_16'Image (W.Block_Align)); Put_Line ("AvgBytesPerSec: " & Unsigned_32'Image (W.Avg_Bytes_Per_Sec)); Put_Line ("Ext. Size: " & Unsigned_16'Image (W.Size)); if W.Size > 0 then Put_Line ("ValidBitsPerSample: " & Unsigned_16'Image (W.Valid_Bits_Per_Sample)); Put ("Channel Mask: "); if W.Channel_Config (Speaker_Front_Left) then Put (" Front_Left"); end if; if W.Channel_Config (Speaker_Front_Right) then Put (" Front_Right"); end if; if W.Channel_Config (Speaker_Front_Center) then Put (" Front_Center"); end if; if W.Channel_Config (Speaker_Low_Frequency) then Put (" Low_Frequency"); end if; if W.Channel_Config (Speaker_Back_Left) then Put (" Back_Left"); end if; if W.Channel_Config (Speaker_Back_Right) then Put (" Back_Right"); end if; if W.Channel_Config (Speaker_Front_Left_Of_Center) then Put (" Front_Left_Of_Center"); end if; if W.Channel_Config (Speaker_Front_Right_Of_Center) then Put (" Front_Right_Of_Center"); end if; if W.Channel_Config (Speaker_Back_Center) then Put (" Back_Center"); end if; if W.Channel_Config (Speaker_Side_Left) then Put (" Side_Left"); end if; if W.Channel_Config (Speaker_Side_Right) then Put (" Side_Right"); end if; if W.Channel_Config (Speaker_Top_Center) then Put (" Top_Center"); end if; if W.Channel_Config (Speaker_Top_Front_Left) then Put (" Top_Front_Left"); end if; if W.Channel_Config (Speaker_Top_Front_Center) then Put (" Top_Front_Center"); end if; if W.Channel_Config (Speaker_Top_Front_Right) then Put (" Top_Front_Right"); end if; if W.Channel_Config (Speaker_Top_Back_Left) then Put (" Top_Back_Left"); end if; if W.Channel_Config (Speaker_Top_Back_Center) then Put (" Top_Back_Center"); end if; if W.Channel_Config (Speaker_Top_Back_Right) then Put (" Top_Back_Right"); end if; New_Line; Put ("SubFormat: "); if W.Sub_Format = GUID_Undefined then Put_Line ("undefined"); elsif W.Sub_Format = GUID_PCM then Put_Line ("KSDATAFORMAT_SUBTYPE_PCM (IEC 60958 PCM)"); elsif W.Sub_Format = GUID_IEEE_Float then Put_Line ("KSDATAFORMAT_SUBTYPE_IEEE_FLOAT " & "(IEEE Floating-Point PCM)"); else Put_Line ("unknown"); end if; end if; Put_Line ("-------------------------------------------"); end Print; end Audio.RIFF.Wav.Formats.Report;
with STM32GD.USART; use STM32GD.USART; with STM32_SVD; with Ada.Synchronous_Task_Control; use Ada.Synchronous_Task_Control; package Serial is subtype Line_Length is Integer range 1 .. 64; type Serial_Data is record Data : USART_Data (Line_Length); Length : Natural; end record; protected Input is entry Read (Data : out Serial_Data); function Is_Ready return Boolean; procedure Set_Ready (Line : Serial_Data); private Buffer : Serial_Data; Ready : Boolean := False; end Input; package Output is procedure Write (Data : in USART_Data; Length : in Natural); procedure Write (Character : in STM32_SVD.Byte); end Output; end Serial;
with MSP430_SVD; use MSP430_SVD; with MSPGD.Clock.Source; generic Module : SPI_Module_Type; Speed: UInt32; Mode : SPI_Mode := Mode_0; with package Clock is new MSPGD.Clock.Source (<>); package MSPGD.SPI.Peripheral is pragma Preelaborate; procedure Init; procedure Send (Data : in Unsigned_8); procedure Send (Data : in Buffer_Type); procedure Receive (Data : out Unsigned_8); procedure Receive (Data : out Buffer_Type); procedure Transfer (Data : in out Unsigned_8); procedure Transfer (Data : in out Buffer_Type); end MSPGD.SPI.Peripheral;
with Tkmrpc.Types; with Tkmrpc.Operations.Ike; package Tkmrpc.Request.Ike.Isa_Auth is Data_Size : constant := 1908; type Data_Type is record Isa_Id : Types.Isa_Id_Type; Cc_Id : Types.Cc_Id_Type; Init_Message : Types.Init_Message_Type; Signature : Types.Signature_Type; end record; for Data_Type use record Isa_Id at 0 range 0 .. (8 * 8) - 1; Cc_Id at 8 range 0 .. (8 * 8) - 1; Init_Message at 16 range 0 .. (1504 * 8) - 1; Signature at 1520 range 0 .. (388 * 8) - 1; end record; for Data_Type'Size use Data_Size * 8; Padding_Size : constant := Request.Body_Size - Data_Size; subtype Padding_Range is Natural range 1 .. Padding_Size; subtype Padding_Type is Types.Byte_Sequence (Padding_Range); type Request_Type is record Header : Request.Header_Type; Data : Data_Type; Padding : Padding_Type; end record; for Request_Type use record Header at 0 range 0 .. (Request.Header_Size * 8) - 1; Data at Request.Header_Size range 0 .. (Data_Size * 8) - 1; Padding at Request.Header_Size + Data_Size range 0 .. (Padding_Size * 8) - 1; end record; for Request_Type'Size use Request.Request_Size * 8; Null_Request : constant Request_Type := Request_Type' (Header => Request.Header_Type'(Operation => Operations.Ike.Isa_Auth, Request_Id => 0), Data => Data_Type'(Isa_Id => Types.Isa_Id_Type'First, Cc_Id => Types.Cc_Id_Type'First, Init_Message => Types.Null_Init_Message_Type, Signature => Types.Null_Signature_Type), Padding => Padding_Type'(others => 0)); end Tkmrpc.Request.Ike.Isa_Auth;
-- Generated at 2015-10-25 22:37:42 +0000 by Natools.Static_Hash_Maps -- from src/natools-web-tags-maps.sx package Natools.Static_Maps.Web.Tags is pragma Pure; type List_Command is (Unknown_List_Command, All_Children, All_Descendants, All_Elements, All_Leaves, Current_Element, Current_Tag_List, Element_Count, Greater_Children, Greater_Descendants, Greater_Elements, Greater_Leaves, If_Current, If_Current_Leaf, If_Current_Parent, If_Not_Current, If_Not_Current_Leaf, If_Not_Current_Parent, Full_Name, Last_Name, Lesser_Children, Lesser_Descendants, Lesser_Elements, Lesser_Leaves, Name, Parent, Tags); function To_List_Command (Key : String) return List_Command; private Map_1_Key_0 : aliased constant String := "all-children"; Map_1_Key_1 : aliased constant String := "all-descendants"; Map_1_Key_2 : aliased constant String := "all-elements"; Map_1_Key_3 : aliased constant String := "all-leaves"; Map_1_Key_4 : aliased constant String := "current-element"; Map_1_Key_5 : aliased constant String := "current-tag-list"; Map_1_Key_6 : aliased constant String := "element-count"; Map_1_Key_7 : aliased constant String := "greater-children"; Map_1_Key_8 : aliased constant String := "greater-descendants"; Map_1_Key_9 : aliased constant String := "greater-elements"; Map_1_Key_10 : aliased constant String := "greater-leaves"; Map_1_Key_11 : aliased constant String := "if-current"; Map_1_Key_12 : aliased constant String := "if-current-leaf"; Map_1_Key_13 : aliased constant String := "if-current-parent"; Map_1_Key_14 : aliased constant String := "if-not-current"; Map_1_Key_15 : aliased constant String := "if-not-current-leaf"; Map_1_Key_16 : aliased constant String := "if-not-current-parent"; Map_1_Key_17 : aliased constant String := "full-name"; Map_1_Key_18 : aliased constant String := "last-name"; Map_1_Key_19 : aliased constant String := "lesser-children"; Map_1_Key_20 : aliased constant String := "lesser-descendants"; Map_1_Key_21 : aliased constant String := "lesser-elements"; Map_1_Key_22 : aliased constant String := "lesser-leaves"; Map_1_Key_23 : aliased constant String := "name"; Map_1_Key_24 : aliased constant String := "parent"; Map_1_Key_25 : aliased constant String := "tags"; Map_1_Keys : constant array (0 .. 25) of access constant String := (Map_1_Key_0'Access, Map_1_Key_1'Access, Map_1_Key_2'Access, Map_1_Key_3'Access, Map_1_Key_4'Access, Map_1_Key_5'Access, Map_1_Key_6'Access, Map_1_Key_7'Access, Map_1_Key_8'Access, Map_1_Key_9'Access, Map_1_Key_10'Access, Map_1_Key_11'Access, Map_1_Key_12'Access, Map_1_Key_13'Access, Map_1_Key_14'Access, Map_1_Key_15'Access, Map_1_Key_16'Access, Map_1_Key_17'Access, Map_1_Key_18'Access, Map_1_Key_19'Access, Map_1_Key_20'Access, Map_1_Key_21'Access, Map_1_Key_22'Access, Map_1_Key_23'Access, Map_1_Key_24'Access, Map_1_Key_25'Access); Map_1_Elements : constant array (0 .. 25) of List_Command := (All_Children, All_Descendants, All_Elements, All_Leaves, Current_Element, Current_Tag_List, Element_Count, Greater_Children, Greater_Descendants, Greater_Elements, Greater_Leaves, If_Current, If_Current_Leaf, If_Current_Parent, If_Not_Current, If_Not_Current_Leaf, If_Not_Current_Parent, Full_Name, Last_Name, Lesser_Children, Lesser_Descendants, Lesser_Elements, Lesser_Leaves, Name, Parent, Tags); end Natools.Static_Maps.Web.Tags;
-- MIT License -- Copyright (c) 2021 Stephen Merrony -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- The above copyright notice and this permission notice shall be included in all -- copies or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -- SOFTWARE. with Ada.Calendar; with Ada.Characters.Handling; with GNAT.Calendar; with Interfaces; use Interfaces; with AOSVS.Agent; with Debug_Logs; use Debug_Logs; with Memory; use Memory; with PARU_32; use PARU_32; package body AOSVS.System is function Sys_ERMSG (CPU : in out CPU_T) return Boolean is Supplied_Buf_Len : Unsigned_8 := Unsigned_8(Get_DW_Bits(CPU.AC(1), 16, 8)); ERMES_Chan : Unsigned_8 := Unsigned_8(Get_DW_Bits(CPU.AC(1), 24, 8)); Default_Response : String := "UNKNOWN ERROR CODE " & CPU.AC(0)'Image; begin Loggers.Debug_Print (Sc_Log, "?ERMSG - Octal code: " & Dword_To_String (CPU.AC(0), Octal, 8)); if ERMES_Chan /= 255 then raise Not_Yet_Implemented with "Custom ERMES files"; end if; -- TODO - actually look it up! RAM.Write_String_BA (CPU.AC(2), Default_Response); CPU.AC(0) := Dword_T(Default_Response'Last); return true; end Sys_ERMSG; function Sys_EXEC (CPU : in out CPU_T; PID : in Word_T; TID : in Word_T) return Boolean is Pkt_Addr : Phys_Addr_T := Phys_Addr_T(CPU.AC(2)); XRFNC : Word_T := RAM.Read_Word (Pkt_Addr); BP : DWord_T; begin Loggers.Debug_Print (Sc_Log, "?EXEC"); case XRFNC is when XFSTS => RAM.Write_Word (Pkt_Addr + XFP1, PID); BP := RAM.Read_Dword(Pkt_Addr + XFP2); if BP /= 0 then RAM.Write_String_BA (BP, "CON10"); -- TODO always claims to be @CON10 end if; when others => raise AOSVS.Agent.Not_Yet_Implemented with "Function code:" & XRFNC'Image; end case; return true; end Sys_EXEC; function Sys_GDAY (CPU : in out CPU_T) return Boolean is Now : Ada.Calendar.Time := Ada.Calendar.Clock; begin Loggers.Debug_Print (Sc_Log, "?GDAY"); CPU.AC(0) := Dword_T(Ada.Calendar.Day(Now)); CPU.AC(1) := Dword_T(Ada.Calendar.Month(Now)); CPU.AC(2) := Dword_T(Ada.Calendar.Year(Now) - 1900); -- Should be -1900, but Y2K! return true; end Sys_GDAY; function Sys_GTMES (CPU : in out CPU_T; PID : in Word_T; TID : in Word_T) return Boolean is Pkt_Addr : Phys_Addr_T := Phys_Addr_T(CPU.AC(2)); P_Greq : Word_T := RAM.Read_Word (Pkt_Addr + GREQ); P_Gnum : Word_T := RAM.Read_Word (Pkt_Addr + GNUM); P_Gres : Dword_T; Err : Word_T; Res_US : Unbounded_String; Num_Args : Word_T; begin Loggers.Debug_Print (Sc_Log, "?GTMES"); Err := 0; case P_Greq is when GMES => Loggers.Debug_Print (Sc_Log, "------ Req. Type: ?GMES"); Res_US := AOSVS.Agent.Actions.Get_PR_Name (PID); Num_Args := Word_T(AOSVS.Agent.Actions.Get_Num_Args (PID)); if Num_Args > 0 then for A in 1 .. Num_Args loop Res_US := Res_US & " " & AOSVS.Agent.Actions.Get_Nth_Arg(PID, A); end loop; end if; Res_US := Res_US & ASCII.NUL; CPU.AC(0) := Dword_T((Length(Res_US)+1)/2); -- word length CPU.AC(1) := Dword_T(GFCF); P_Gres := RAM.Read_Dword (Pkt_Addr + PARU_32.GRES); if P_Gres /= 16#ffff_ffff# then RAM.Write_String_BA (P_Gres, To_String(Res_US)); end if; Loggers.Debug_Print (Sc_Log, "----- Returning: " & To_String(Res_US)); when GCMD => Loggers.Debug_Print (Sc_Log, "------ Req. Type: ?GCMD"); -- Procs launched interactively do not return the program name part of the command... -- Res_US := AOSVS.Agent.Actions.Get_PR_Name (PID); Num_Args := Word_T(AOSVS.Agent.Actions.Get_Num_Args (PID)); if Num_Args > 0 then for A in 1 .. Num_Args loop if A > 1 then Res_US := Res_US & " "; end if; Res_US := Res_US & AOSVS.Agent.Actions.Get_Nth_Arg(PID, A); end loop; end if; -- Res_US := Res_US & ASCII.NUL; CPU.AC(1) := Dword_T((Length(Res_US))); -- byte length P_Gres := RAM.Read_Dword (Pkt_Addr + PARU_32.GRES); if P_Gres /= 16#ffff_ffff# then RAM.Write_String_BA (P_Gres, To_String(Res_US)); end if; Loggers.Debug_Print (Sc_Log, "----- Returning: " & To_String(Res_US)); when GCNT => Loggers.Debug_Print (Sc_Log, "------ Req. Type: ?GCNT"); Num_Args := Word_T(AOSVS.Agent.Actions.Get_Num_Args (PID)) - 1; CPU.AC(0) := Dword_T(Num_Args); Loggers.Debug_Print (Sc_Log, "----- Returning Arg Count:" & Num_Args'Image); when GARG => declare Arg_US : Unbounded_String := AOSVS.Agent.Actions.Get_Nth_Arg(PID, P_Gnum); Arg_Int : Integer; begin Loggers.Debug_Print (Sc_Log, "------ Req. Type: ?GARG"); Arg_Int := Integer'Value(To_String(Arg_US)); -- no exception - it's a simple integer argument CPU.AC(1) := Dword_T(Arg_Int); CPU.AC(0) := Dword_T(Length (Arg_US)); exception when others => -- not an integer... CPU.AC(1) := 16#FFFF_FFFF#; CPU.AC(0) := Dword_T(Length (Arg_US)); RAM.Write_String_BA (RAM.Read_Dword(Pkt_Addr + GRES), To_String (Arg_US)); end; when others => raise AOSVS.Agent.Not_Yet_Implemented with "?GTMES request type " & P_Greq'Image; end case; if Err /= 0 then CPU.AC(0) := Dword_T(Err); return false; end if; return true; end Sys_GTMES; function Sys_GTOD (CPU : in out CPU_T) return Boolean is Now : Ada.Calendar.Time := Ada.Calendar.Clock; begin Loggers.Debug_Print (Sc_Log, "?GTOD"); CPU.AC(0) := Dword_T(GNAT.Calendar.Second(Now)); CPU.AC(1) := Dword_T(GNAT.Calendar.Minute(Now)); CPU.AC(2) := Dword_T(GNAT.Calendar.Hour(Now)); return true; end Sys_GTOD; function Sys_SINFO (CPU : in out CPU_T) return Boolean is Pkt_Addr : Phys_Addr_T := Phys_Addr_T(CPU.AC(2)); P_SIRS : Word_T := RAM.Read_Word (Pkt_Addr + SIRS); begin Loggers.Debug_Print (Sc_Log, "?SINFO"); RAM.Write_Word (Pkt_Addr + SIRN, 16#07_49#); -- AOS/VS Version faked to 7.73 RAM.Write_Dword (Pkt_Addr + SIMM, 255); -- max mem page - check this if RAM.Read_Dword (Pkt_Addr + SILN) /= 0 then RAM.Write_String_BA (RAM.Read_Dword (Pkt_Addr + SILN), "MASTERLDU"); end if; if RAM.Read_Dword (Pkt_Addr + SIID) /= 0 then RAM.Write_String_BA (RAM.Read_Dword (Pkt_Addr + SIID), "VSEMUA"); end if; if RAM.Read_Dword (Pkt_Addr + SIOS) /= 0 then RAM.Write_String_BA (RAM.Read_Dword (Pkt_Addr + SIOS), ":VSEMUA"); end if; RAM.Write_Word(Pkt_Addr + SSIN, SAVS); return true; end Sys_SINFO; end AOSVS.System;
with AUnit.Test_Suites; with AUnit.Test_Fixtures; with AUnit.Test_Caller; with Testsuite.Encode; with Testsuite.Decode; private with Test_Utils.Abstract_Decoder; private with Test_Utils.Abstract_Encoder; package Testsuite.Encode_Decode is procedure Set_Kinds (E : Testsuite.Encode.Encoder_Kind; D : Testsuite.Decode.Decoder_Kind); procedure Add_Tests (Suite : in out AUnit.Test_Suites.Test_Suite'Class); private type Encoder_Decoder_Fixture is new AUnit.Test_Fixtures.Test_Fixture with record Encoder : Test_Utils.Abstract_Encoder.Any_Acc; E_Kind : Testsuite.Encode.Encoder_Kind; Decoder : Test_Utils.Abstract_Decoder.Any_Acc; D_Kind : Testsuite.Decode.Decoder_Kind; end record; overriding procedure Set_Up (Test : in out Encoder_Decoder_Fixture); overriding procedure Tear_Down (Test : in out Encoder_Decoder_Fixture); package Encoder_Decoder_Caller is new AUnit.Test_Caller (Encoder_Decoder_Fixture); end Testsuite.Encode_Decode;
package body Kafka.Topic.Partition is procedure List_Add(List : Partition_List_Type; Topic : String; Partition : Integer_32) is C_Topic : chars_ptr := New_String(Topic); Unused : System.Address; begin Unused := rd_kafka_topic_partition_list_add(List, C_Topic, Partition); Free(C_Topic); end List_Add; procedure List_Add_Range(List : Partition_List_Type; Topic : String; Start : Integer_32; Stop : Integer_32) is C_Topic : chars_ptr := New_String(Topic); begin rd_kafka_topic_partition_list_add_range(List, C_Topic, Start, Stop); Free(C_Topic); end List_Add_Range; function List_Delete(List : Partition_List_Type; Topic : String; Partition : Integer_32) return Boolean is C_Topic : chars_ptr := New_String(Topic); Result : int; begin Result := rd_kafka_topic_partition_list_del(List, C_Topic, Partition); Free(C_Topic); return Result = 1; end List_Delete; end Kafka.Topic.Partition;
-- This package has been generated automatically by GNATtest. -- Do not edit any part of it, see GNATtest documentation for more details. -- begin read only with GNATtest_Generated; package Tk.Image.Photo.Photo_Options_Test_Data.Photo_Options_Tests is type Test_Photo_Options is new GNATtest_Generated.GNATtest_Standard.Tk.Image .Photo .Photo_Options_Test_Data .Test_Photo_Options with null record; procedure Test_Create_22037c_8377bb(Gnattest_T: in out Test_Photo_Options); -- tk-image-photo.ads:224:4:Create:Tests_Create_Photo procedure Test_Create_fa334a_6f3d65(Gnattest_T: in out Test_Photo_Options); -- tk-image-photo.ads:250:4:Create:Tests_Create2_Photo procedure Test_Configure_6e2ac0_462460 (Gnattest_T: in out Test_Photo_Options); -- tk-image-photo.ads:297:4:Configure:Tests_Configure_Photo procedure Test_Get_Options_5c7a9c_d39689 (Gnattest_T: in out Test_Photo_Options); -- tk-image-photo.ads:356:4:Get_Options:Tests_Get_Options_Photo end Tk.Image.Photo.Photo_Options_Test_Data.Photo_Options_Tests; -- end read only
with Ada.Text_IO; with Ada.Characters.Latin_1; -- There's also 'with ASCII;', but that's obsolete with Ada.Strings.Fixed; procedure Gol is use Ada.Text_IO; Width : constant Positive := 5; Height : constant Positive := 5; type Cell is (Dead, Alive); type Rows is mod Height; type Cols is mod Width; type Board is array (Rows, Cols) of Cell; type Neighbors is range 0 .. 8; procedure Render_Board(B: Board) is begin for Row in Rows loop for Col in Cols loop case B(Row, Col) is when Alive => Put('#'); when Dead => Put('.'); end case; end loop; New_Line; end loop; end; function Count_Neighbors(B: Board; Row0: Rows; Col0: Cols) return Neighbors is begin return Result : Neighbors := 0 do for Delta_Row in Rows range 0 .. 2 loop for Delta_Col in Cols range 0 .. 2 loop if Delta_Row /= 1 or Delta_Col /= 1 then declare Row : constant Rows := Row0 + Delta_Row - 1; Col : constant Cols := Col0 + Delta_Col - 1; begin if B(Row, Col) = Alive then Result := Result + 1; end if; end; end if; end loop; end loop; end return; end; function Next(Current : Board) return Board is begin return Result : Board do for Row in Rows loop for Col in Cols loop declare N : constant Neighbors := Count_Neighbors(Current, Row, Col); begin case Current(Row, Col) is when Dead => Result(Row, Col) := (if N = 3 then Alive else Dead); when Alive => Result(Row, Col) := (if N in 2 .. 3 then Alive else Dead); end case; end; end loop; end loop; end return; end; Current : Board := ( ( Dead, Alive, Dead, others => Dead), ( Dead, Dead, Alive, others => Dead), (Alive, Alive, Alive, others => Dead), others => (others => Dead) ); begin --for I in 1 .. 2 loop Render_Board(Current); Current := Next(Current); delay Duration(0.25); Put(Ada.Characters.Latin_1.ESC & "[" & Ada.Strings.Fixed.Trim(Height'Image, Ada.Strings.Left) & "A"); Put(Ada.Characters.Latin_1.ESC & "[" & Ada.Strings.Fixed.Trim(Width'Image, Ada.Strings.Left) & "D"); end loop; end;
with AUnit.Assertions; use AUnit.Assertions; with Brackelib; package body Queues_Tests is Container : State_Queues.Queue; procedure Set_Up (T : in out Test) is begin null; end Set_Up; procedure Test_Enqueue (T : in out Test) is begin Assert (Size (Container) = 0, "Incorrect size before push"); Enqueue (Container, 314); Assert (Size (Container) = 1, "Incorrect size after push"); end Test_Enqueue; procedure Test_Dequeue (T : in out Test) is begin Assert (Size (Container) = 1, "Incorrect size before push"); declare Item : Integer := Dequeue (Container); begin Assert (Size (Container) = 0, "Incorrect size after push"); end; Assert (Dequeue (Container) = 1234, "Exception Stack_Empty not raised"); exception when Queue_Empty => null; end Test_Dequeue; procedure Test_Clear (T : in out Test) is begin Assert (Size (Container) = 0, "Incorrect size before push"); Enqueue (Container, 314); Assert (Size (Container) = 1, "Incorrect size after push"); Clear (Container); Assert (Is_Empty (Container), "Incorrect Is_Empty response after clear"); end Test_Clear; procedure Test_Empty (T : in out Test) is begin Assert (Size (Container) = 0, "Incorrect size before Is_Empty"); Assert (Is_Empty (Container), "Incorrect Is_Empty response"); Enqueue (Container, 314); Assert (not Is_Empty (Container), "Incorrect Is_Empty response"); end Test_Empty; end Queues_Tests;
------------------------------------------------------------------------------ -- -- -- ASIS-for-GNAT IMPLEMENTATION COMPONENTS -- -- -- -- A 4 G . A _ O U T P U T -- -- -- -- B o d y -- -- -- -- Copyright (C) 1995-2011, Free Software Foundation, Inc. -- -- -- -- ASIS-for-GNAT is free software; you can redistribute it and/or modify it -- -- under terms of the GNU General Public License as published by the Free -- -- Software Foundation; either version 2, or (at your option) any later -- -- version. ASIS-for-GNAT is distributed in the hope that it will be use- -- -- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- -- -- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General -- -- Public License for more details. You should have received a copy of the -- -- GNU General Public License distributed with ASIS-for-GNAT; see file -- -- COPYING. If not, write to the Free Software Foundation, 51 Franklin -- -- Street, Fifth Floor, Boston, MA 02110-1301, USA. -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the -- -- Software Engineering Laboratory of the Swiss Federal Institute of -- -- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the -- -- Scientific Research Computer Center of Moscow State University (SRCC -- -- MSU), Russia, with funding partially provided by grants from the Swiss -- -- National Science Foundation and the Swiss Academy of Engineering -- -- Sciences. ASIS-for-GNAT is now maintained by AdaCore -- -- (http://www.adacore.com). -- -- -- ------------------------------------------------------------------------------ with Ada.Exceptions; use Ada.Exceptions; with Ada.Strings.Fixed; use Ada.Strings.Fixed; -- with Asis.Text; use Asis.Text; with Asis.Elements; use Asis.Elements; with A4G.A_Debug; use A4G.A_Debug; with A4G.A_Types; use A4G.A_Types; with A4G.Int_Knds; use A4G.Int_Knds; with A4G.Contt; use A4G.Contt; with A4G.Contt.UT; use A4G.Contt.UT; with A4G.Contt.TT; use A4G.Contt.TT; with A4G.A_Opt; use A4G.A_Opt; with A4G.Vcheck; use A4G.Vcheck; with Asis.Set_Get; use Asis.Set_Get; with Atree; use Atree; with Namet; use Namet; with Output; use Output; with Sinfo; use Sinfo; with Sinput; use Sinput; package body A4G.A_Output is LT : String renames A4G.A_Types.ASIS_Line_Terminator; --------- -- Add -- --------- procedure Add (Phrase : String) is begin if Debug_Buffer_Len = Max_Debug_Buffer_Len then return; end if; for I in Phrase'Range loop Debug_Buffer_Len := Debug_Buffer_Len + 1; Debug_Buffer (Debug_Buffer_Len) := Phrase (I); if Debug_Buffer_Len = Max_Debug_Buffer_Len then exit; end if; end loop; end Add; ------------------ -- ASIS_Warning -- ------------------ procedure ASIS_Warning (Message : String; Error : Asis.Errors.Error_Kinds := Not_An_Error) is begin case ASIS_Warning_Mode is when Suppress => null; when Normal => Set_Standard_Error; Write_Str ("ASIS warning: "); Write_Eol; Write_Str (Message); Write_Eol; Set_Standard_Output; when Treat_As_Error => -- ??? Raise_ASIS_Failed should be revised to use like that Raise_ASIS_Failed ( Argument => Nil_Element, Diagnosis => Message, Stat => Error); end case; end ASIS_Warning; -------------------------------------- -- Debug_String (Compilation Unit) -- -------------------------------------- -- SHOULD BE REVISED USING Debug_Buffer!!! function Debug_String (CUnit : Compilation_Unit) return String is LT : String renames A4G.A_Types.ASIS_Line_Terminator; U : Unit_Id; C : Context_Id; begin U := Get_Unit_Id (CUnit); C := Encl_Cont_Id (CUnit); if No (U) then return "This is a Nil Compilation Unit"; else Reset_Context (C); return LT & "Unit Id: " & Unit_Id'Image (U) & LT & " Unit name: " & Unit_Name (CUnit) & LT & " Kind: " & Asis.Unit_Kinds'Image (Kind (C, U)) & LT & " Class: " & Asis.Unit_Classes'Image (Class (C, U)) & LT & " Origin: " & Asis.Unit_Origins'Image (Origin (C, U)) & LT & " Enclosing Context Id: " & Context_Id'Image (C) & LT & " Is consistent: " & Boolean'Image (Is_Consistent (C, U)) & LT & "-------------------------------------------------"; end if; end Debug_String; procedure Debug_String (CUnit : Compilation_Unit; No_Abort : Boolean := False) is LT : String renames A4G.A_Types.ASIS_Line_Terminator; U : Unit_Id; C : Context_Id; begin Debug_Buffer_Len := 0; U := Get_Unit_Id (CUnit); C := Encl_Cont_Id (CUnit); if No (U) then Add ("This is a Nil Compilation Unit"); else Reset_Context (C); Add (LT); Add ("Unit Id: " & Unit_Id'Image (U) & LT); Add (" Unit name: " & Unit_Name (CUnit) & LT); Add (" Kind: " & Asis.Unit_Kinds'Image (Kind (C, U)) & LT); Add (" Class: " & Asis.Unit_Classes'Image (Class (C, U)) & LT); Add (" Origin: " & Asis.Unit_Origins'Image (Origin (C, U)) & LT); Add (" Enclosing Context Id: " & Context_Id'Image (C) & LT); Add (" Is consistent: " & Boolean'Image (Is_Consistent (C, U)) & LT); Add ("-------------------------------------------------"); end if; exception when Ex : others => if No_Abort then Add (LT & "Can not complete the unit debug image because of" & LT); Add (Exception_Information (Ex)); else raise; end if; end Debug_String; ----------------------------- -- Debug_String (Context) -- ----------------------------- -- SHOULD BE REVISED USING Debug_Buffer!!! function Debug_String (Cont : Context) return String is LT : String renames A4G.A_Types.ASIS_Line_Terminator; C : constant Context_Id := Get_Cont_Id (Cont); Debug_String_Prefix : constant String := "Context Id: " & Context_Id'Image (C) & LT; begin if C = Non_Associated then return Debug_String_Prefix & " This Context has never been associated"; elsif not Is_Associated (C) and then not Is_Opened (C) then return Debug_String_Prefix & " This Context is dissociated at the moment"; elsif not Is_Opened (C) then -- here Is_Associated (C) return Debug_String_Prefix & " This Context has associations," & LT & " but it is closed at the moment"; else -- here Is_Associated (C) and Is_Opened (C) return Debug_String_Prefix & " This Context is opened at the moment" & LT & " All tree files: " & Tree_Id'Image (Last_Tree (C) - First_Tree_Id + 1) & LT & " All units: " & Unit_Id'Image (Last_Unit - First_Unit_Id + 1) & LT & " Existing specs : " & Natural'Image (Lib_Unit_Decls (C)) & LT & " Existing bodies: " & Natural'Image (Comp_Unit_Bodies (C)) & LT & " Nonexistent units:" & Natural'Image (Natural (Last_Unit - First_Unit_Id + 1) - (Lib_Unit_Decls (C) + Comp_Unit_Bodies (C))) & LT & "================="; end if; end Debug_String; ----------------------------- -- Debug_String (Element) -- ----------------------------- procedure Debug_String (E : Element; No_Abort : Boolean := False) is E_Kind : constant Internal_Element_Kinds := Int_Kind (E); E_Kind_Image : constant String := Internal_Element_Kinds'Image (E_Kind); E_Unit : constant Asis.Compilation_Unit := Encl_Unit (E); E_Unit_Class : constant Unit_Classes := Class (E_Unit); N : constant Node_Id := Node (E); R_N : constant Node_Id := R_Node (E); N_F_1 : constant Node_Id := Node_Field_1 (E); N_F_2 : constant Node_Id := Node_Field_2 (E); C : constant Context_Id := Encl_Cont_Id (E); T : constant Tree_Id := Encl_Tree (E); begin Debug_Buffer_Len := 0; if Is_Nil (E) then Add ("This is a Nil Element"); else Add (E_Kind_Image); Add (LT & "located in "); Add (Unit_Name (E_Unit)); if E_Unit_Class = A_Separate_Body then Add (" (subunit, Unit_Id ="); elsif E_Unit_Class = A_Public_Declaration or else E_Unit_Class = A_Private_Declaration then Add (" (spec, Unit_Id ="); else Add (" (body, Unit_Id ="); end if; Add (Unit_Id'Image (Encl_Unit_Id (E))); Add (", Context_Id ="); Add (Context_Id'Image (C)); Add (")" & LT); if not (Debug_Flag_I) then Add ("text position :"); -- if not Is_Text_Available (E) then -- Creating the source location from the element node. We -- cannot safely use Element_Span here because in case of a -- bug in a structural query this may result in curcling of -- query blow-ups. if Sloc (N) <= No_Location then Add (" not available"); Add (LT); else Add (" "); declare use Ada.Strings; P : Source_Ptr; Sindex : Source_File_Index; Instance_Depth : Natural := 0; procedure Enter_Sloc; -- For the current value of P, adds to the debug string -- the string of the form file_name:line_number. Also -- computes Sindex as the Id of the sourse file of P. procedure Enter_Sloc is F_Name : File_Name_Type; begin Sindex := Get_Source_File_Index (P); F_Name := File_Name (Sindex); Get_Name_String (F_Name); Add (Name_Buffer (1 .. Name_Len) & ":"); Add (Trim (Get_Physical_Line_Number (P)'Img, Both)); Add (":"); Add (Trim (Get_Column_Number (P)'Img, Both)); end Enter_Sloc; begin P := Sloc (N); Enter_Sloc; P := Instantiation (Sindex); while P /= No_Location loop Add ("["); Instance_Depth := Instance_Depth + 1; Enter_Sloc; P := Instantiation (Sindex); end loop; for J in 1 .. Instance_Depth loop Add ("]"); end loop; Add (LT); end; end if; -- else -- declare -- Arg_Span : Span; -- FL : String_Ptr; -- LL : String_Ptr; -- FC : String_Ptr; -- LC : String_Ptr; -- begin -- -- this operation is potentially dangerous - it may -- -- change the tree (In fact, it should not, if we -- -- take into account the typical conditions when -- -- this routine is called -- Arg_Span := Element_Span (E); -- FL := new String'(Line_Number'Image (Arg_Span.First_Line)); -- LL := new String'(Line_Number'Image (Arg_Span.Last_Line)); -- FC := new String'(Character_Position'Image -- (Arg_Span.First_Column)); -- LC := new String'(Character_Position'Image -- (Arg_Span.Last_Column)); -- Add (FL.all); -- Add (" :"); -- Add (FC.all); -- Add (" -"); -- Add (LL.all); -- Add (" :"); -- Add (LC.all); -- Add (LT); -- end; -- end if; end if; Add (" Nodes:" & LT); Add (" Node :" & Node_Id'Image (N)); Add (" - " & Node_Kind'Image (Nkind (N)) & LT); Add (" R_Node :" & Node_Id'Image (R_N)); Add (" - " & Node_Kind'Image (Nkind (R_N)) & LT); Add (" Node_Field_1 :" & Node_Id'Image (N_F_1)); Add (" - " & Node_Kind'Image (Nkind (N_F_1)) & LT); Add (" Node_Field_2 :" & Node_Id'Image (N_F_2)); Add (" - " & Node_Kind'Image (Nkind (N_F_2)) & LT); Add (" Rel_Sloc :"); Add (Source_Ptr'Image (Rel_Sloc (E)) & LT); if Special_Case (E) /= Not_A_Special_Case then Add (" Special Case : "); Add (Special_Cases'Image (Special_Case (E)) & LT); end if; if Special_Case (E) = Stand_Char_Literal or else Character_Code (E) /= 0 then Add (" Character_Code :"); Add (Char_Code'Image (Character_Code (E)) & LT); end if; case Normalization_Case (E) is when Is_Normalized => Add (" Normalized" & LT); when Is_Normalized_Defaulted => Add (" Normalized (with default value)" & LT); when Is_Normalized_Defaulted_For_Box => Add (" Normalized (with default value computed for box)" & LT); when Is_Not_Normalized => null; end case; if Parenth_Count (E) > 0 then Add (" Parenth_Count :"); Add (Nat'Image (Parenth_Count (E)) & LT); end if; if Is_From_Implicit (E) then Add (" Is implicit" & LT); end if; if Is_From_Inherited (E) then Add (" Is inherited" & LT); end if; if Is_From_Instance (E) then Add (" Is from instance" & LT); end if; Add (" obtained from the tree "); if Present (T) then Get_Name_String (C, T); Add (A_Name_Buffer (1 .. A_Name_Len)); Add (" (Tree_Id =" & Tree_Id'Image (T) & ")"); else Add (" <nil tree>"); end if; end if; exception when Ex : others => if No_Abort then Add (LT & "Can not complete the unit debug image because of" & LT); Add (Exception_Information (Ex)); else raise; end if; end Debug_String; ---------------- -- Write_Node -- ---------------- procedure Write_Node (N : Node_Id; Prefix : String := "") is begin Write_Str (Prefix); Write_Str ("Node_Id = "); Write_Int (Int (N)); Write_Eol; Write_Str (Prefix); Write_Str ("Nkind = "); Write_Str (Node_Kind'Image (Nkind (N))); Write_Eol; Write_Str (Prefix); Write_Str ("Rewrite_Sub value : "); Write_Str (Boolean'Image (Is_Rewrite_Substitution (N))); Write_Eol; Write_Str (Prefix); Write_Str ("Rewrite_Ins value : "); Write_Str (Boolean'Image (Is_Rewrite_Insertion (N))); Write_Eol; Write_Str (Prefix); Write_Str ("Comes_From_Source value : "); Write_Str (Boolean'Image (Comes_From_Source (N))); Write_Eol; if Original_Node (N) = N then Write_Str (Prefix); Write_Str (" Node is unchanged"); Write_Eol; elsif Original_Node (N) = Empty then Write_Str (Prefix); Write_Str (" Node has been inserted"); Write_Eol; else Write_Str (Prefix); Write_Str (" Node has been rewritten"); Write_Eol; Write_Node (N => Original_Node (N), Prefix => Write_Node.Prefix & " Original node -> "); end if; Write_Eol; end Write_Node; end A4G.A_Output;
with Ada.Unchecked_Conversion; with Cortex_M.Cache; use Cortex_M.Cache; with STM32.DMA2D; use STM32.DMA2D; package body STM32.DMA2D_Bitmap is function To_DMA2D_Buffer (Buffer : HAL.Bitmap.Bitmap_Buffer'Class) return DMA2D_Buffer with Inline; function To_DMA2D_CM is new Ada.Unchecked_Conversion (HAL.Bitmap.Bitmap_Color_Mode, STM32.DMA2D.DMA2D_Color_Mode); function To_DMA2D_Color is new Ada.Unchecked_Conversion (HAL.Bitmap.Bitmap_Color, STM32.DMA2D.DMA2D_Color); --------------------- -- To_DMA2D_Buffer -- --------------------- function To_DMA2D_Buffer (Buffer : HAL.Bitmap.Bitmap_Buffer'Class) return DMA2D_Buffer is begin return (Addr => Buffer.Addr, Width => (if Buffer.Swapped then Buffer.Height else Buffer.Width), Height => (if Buffer.Swapped then Buffer.Width else Buffer.Height), Color_Mode => To_DMA2D_CM (Buffer.Color_Mode)); end To_DMA2D_Buffer; --------------- -- Set_Pixel -- --------------- overriding procedure Set_Pixel (Buffer : DMA2D_Bitmap_Buffer; X : Natural; Y : Natural; Value : Word) is begin DMA2D_Wait_Transfer; HAL.Bitmap.Bitmap_Buffer (Buffer).Set_Pixel (X, Y, Value); end Set_Pixel; --------------------- -- Set_Pixel_Blend -- --------------------- overriding procedure Set_Pixel_Blend (Buffer : DMA2D_Bitmap_Buffer; X : Natural; Y : Natural; Value : HAL.Bitmap.Bitmap_Color) is DMA_Buf : constant DMA2D_Buffer := To_DMA2D_Buffer (Buffer); begin if To_DMA2D_CM (Buffer.Color_Mode) in DMA2D_Dst_Color_Mode then if not Buffer.Swapped then DMA2D_Set_Pixel_Blend (Buffer => DMA_Buf, X => X, Y => Y, Color => To_DMA2D_Color (Value)); else DMA2D_Set_Pixel_Blend (Buffer => DMA_Buf, X => Y, Y => Buffer.Width - X - 1, Color => To_DMA2D_Color (Value)); end if; else HAL.Bitmap.Bitmap_Buffer (Buffer).Set_Pixel_Blend (X, Y, Value); end if; end Set_Pixel_Blend; --------------- -- Get_Pixel -- --------------- overriding function Get_Pixel (Buffer : DMA2D_Bitmap_Buffer; X : Natural; Y : Natural) return Word is begin DMA2D_Wait_Transfer; return HAL.Bitmap.Bitmap_Buffer (Buffer).Get_Pixel (X, Y); end Get_Pixel; ---------- -- Fill -- ---------- overriding procedure Fill (Buffer : DMA2D_Bitmap_Buffer; Color : Word) is begin if To_DMA2D_CM (Buffer.Color_Mode) in DMA2D_Dst_Color_Mode then DMA2D_Fill (To_DMA2D_Buffer (Buffer), Color); else HAL.Bitmap.Bitmap_Buffer (Buffer).Fill (Color); end if; end Fill; --------------- -- Fill_Rect -- --------------- overriding procedure Fill_Rect (Buffer : DMA2D_Bitmap_Buffer; Color : Word; X : Integer; Y : Integer; Width : Integer; Height : Integer) is DMA_Buf : constant DMA2D_Buffer := To_DMA2D_Buffer (Buffer); begin if To_DMA2D_CM (Buffer.Color_Mode) in DMA2D_Dst_Color_Mode then if not Buffer.Swapped then DMA2D_Fill_Rect (DMA_Buf, Color => Color, X => X, Y => Y, Width => Width, Height => Height); else DMA2D_Fill_Rect (DMA_Buf, Color => Color, X => Y, Y => Buffer.Width - X - Width, Width => Height, Height => Width); end if; else HAL.Bitmap.Bitmap_Buffer (Buffer).Fill_Rect (Color, X, Y, Width, Height); end if; end Fill_Rect; --------------- -- Copy_Rect -- --------------- overriding procedure Copy_Rect (Src_Buffer : HAL.Bitmap.Bitmap_Buffer'Class; X_Src : Natural; Y_Src : Natural; Dst_Buffer : DMA2D_Bitmap_Buffer; X_Dst : Natural; Y_Dst : Natural; Bg_Buffer : HAL.Bitmap.Bitmap_Buffer'Class; X_Bg : Natural; Y_Bg : Natural; Width : Natural; Height : Natural) is use type System.Address; DMA_Buf_Src : constant DMA2D_Buffer := To_DMA2D_Buffer (Src_Buffer); DMA_Buf_Dst : constant DMA2D_Buffer := To_DMA2D_Buffer (Dst_Buffer); DMA_Buf_Bg : DMA2D_Buffer := To_DMA2D_Buffer (Bg_Buffer); X0_Src : Natural := X_Src; Y0_Src : Natural := Y_Src; X0_Dst : Natural := X_Dst; Y0_Dst : Natural := Y_Dst; X0_Bg : Natural := X_Bg; Y0_Bg : Natural := Y_Bg; W : Natural := Width; H : Natural := Height; begin if Src_Buffer.Swapped then X0_Src := Y_Src; Y0_Src := Src_Buffer.Width - X_Src - Width; end if; if Dst_Buffer.Swapped then X0_Dst := Y_Dst; Y0_Dst := Dst_Buffer.Width - X_Dst - Width; W := Height; H := Width; end if; if Bg_Buffer.Addr = System.Null_Address then DMA_Buf_Bg := STM32.DMA2D.Null_Buffer; X0_Bg := 0; Y0_Bg := 0; elsif Bg_Buffer.Swapped then X0_Bg := Y_Bg; Y0_Bg := Bg_Buffer.Width - X_Bg - Width; end if; DMA2D_Copy_Rect (DMA_Buf_Src, X0_Src, Y0_Src, DMA_Buf_Dst, X0_Dst, Y0_Dst, DMA_Buf_Bg, X0_Bg, Y0_Bg, W, H); end Copy_Rect; ------------------- -- Wait_Transfer -- ------------------- overriding procedure Wait_Transfer (Buffer : DMA2D_Bitmap_Buffer) is begin DMA2D_Wait_Transfer; Cortex_M.Cache.Clean_Invalidate_DCache (Start => Buffer.Addr, Len => Buffer.Buffer_Size); end Wait_Transfer; end STM32.DMA2D_Bitmap;
with Algorithm; use Algorithm; with Communication; use Communication; with Types; use Types; package Botstate is type Bot is tagged record Algo : Algorithm_Ptr; Port : Serial_Port; end record; procedure Init (Self : in out Bot; TTY_Name : in String; Algo_Type : in Algorithm_Type); procedure Start (Self : in Bot); procedure Kill (Self : in out Bot); end Botstate;
-- -- Convert any image or animation file to BMP file(s). -- -- Middle-size test/demo for the GID (Generic Image Decoder) package. -- -- Supports: -- - Transparency (blends transparent or partially opaque areas with a -- background image, gid.gif, or a fixed, predefined colour) -- - Display orientation (JPEG EXIF informations from digital cameras) -- -- For a smaller and simpler example, look for mini.adb . -- with GID; with Ada.Calendar; with Ada.Characters.Handling; use Ada.Characters.Handling; with Ada.Command_Line; use Ada.Command_Line; with Ada.Streams.Stream_IO; use Ada.Streams.Stream_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Text_IO; use Ada.Text_IO; with Ada.Unchecked_Deallocation; with Interfaces; procedure To_BMP is default_bkg_name: constant String:= "gid.gif"; procedure Blurb is begin Put_Line(Standard_Error, "To_BMP * Converts any image file to a BMP file"); Put_Line(Standard_Error, "Simple test for the GID (Generic Image Decoder) package"); Put_Line(Standard_Error, "Package version " & GID.version & " dated " & GID.reference); Put_Line(Standard_Error, "URL: " & GID.web); New_Line(Standard_Error); Put_Line(Standard_Error, "Syntax:"); Put_Line(Standard_Error, "to_bmp [-] [-<background_image_name>] <image_1> [<image_2>...]"); New_Line(Standard_Error); Put_Line(Standard_Error, "Options:"); Put_Line(Standard_Error, " '-': don't output image (testing only)"); Put_Line(Standard_Error, " '-<background_image_name>':"); Put_Line(Standard_Error, " use specifed background to mix with transparent images"); Put_Line(Standard_Error, " (otherwise, trying with '"& default_bkg_name &"' or single color)"); New_Line(Standard_Error); Put_Line(Standard_Error, "Output: "".dib"" is added the full input name(s)"); Put_Line(Standard_Error, " Reason of "".dib"": unknown synonym of "".bmp"";"); Put_Line(Standard_Error, " just do ""del *.dib"" for cleanup"); New_Line(Standard_Error); end Blurb; -- Image used as background for displaying images having transparency background_image_name: Unbounded_String:= Null_Unbounded_String; use Interfaces; type Byte_Array is array(Integer range <>) of Unsigned_8; type p_Byte_Array is access Byte_Array; procedure Dispose is new Ada.Unchecked_Deallocation(Byte_Array, p_Byte_Array); forgive_errors: constant Boolean:= False; error: Boolean; img_buf, bkg_buf: p_Byte_Array:= null; bkg: GID.Image_descriptor; generic correct_orientation: GID.Orientation; -- Load image into a 24-bit truecolor BGR raw bitmap (for a BMP output) procedure Load_raw_image( image : in out GID.Image_descriptor; buffer: in out p_Byte_Array; next_frame: out Ada.Calendar.Day_Duration ); -- procedure Load_raw_image( image : in out GID.Image_descriptor; buffer: in out p_Byte_Array; next_frame: out Ada.Calendar.Day_Duration ) is subtype Primary_color_range is Unsigned_8; subtype U16 is Unsigned_16; image_width: constant Positive:= GID.Pixel_width(image); image_height: constant Positive:= GID.Pixel_height(image); padded_line_size_x: constant Positive:= 4 * Integer(Float'Ceiling(Float(image_width) * 3.0 / 4.0)); padded_line_size_y: constant Positive:= 4 * Integer(Float'Ceiling(Float(image_height) * 3.0 / 4.0)); -- (in bytes) idx: Integer; mem_x, mem_y: Natural; bkg_padded_line_size: Positive; bkg_width, bkg_height: Natural; -- procedure Set_X_Y (x, y: Natural) is pragma Inline(Set_X_Y); use GID; rev_x: constant Natural:= image_width - (x+1); rev_y: constant Natural:= image_height - (y+1); begin case correct_orientation is when Unchanged => idx:= 3 * x + padded_line_size_x * y; when Rotation_90 => idx:= 3 * rev_y + padded_line_size_y * x; when Rotation_180 => idx:= 3 * rev_x + padded_line_size_x * rev_y; when Rotation_270 => idx:= 3 * y + padded_line_size_y * rev_x; end case; mem_x:= x; mem_y:= y; end Set_X_Y; -- -- No background version of Put_Pixel -- procedure Put_Pixel_without_bkg ( red, green, blue : Primary_color_range; alpha : Primary_color_range ) is pragma Inline(Put_Pixel_without_bkg); pragma Warnings(off, alpha); -- alpha is just ignored use GID; begin buffer(idx..idx+2):= (blue, green, red); -- GID requires us to look to next pixel for next time: case correct_orientation is when Unchanged => idx:= idx + 3; when Rotation_90 => idx:= idx + padded_line_size_y; when Rotation_180 => idx:= idx - 3; when Rotation_270 => idx:= idx - padded_line_size_y; end case; end Put_Pixel_without_bkg; -- -- Unicolor background version of Put_Pixel -- procedure Put_Pixel_with_unicolor_bkg ( red, green, blue : Primary_color_range; alpha : Primary_color_range ) is pragma Inline(Put_Pixel_with_unicolor_bkg); u_red : constant:= 200; u_green: constant:= 133; u_blue : constant:= 32; begin if alpha = 255 then buffer(idx..idx+2):= (blue, green, red); else -- blend with bckground color buffer(idx) := Primary_color_range((U16(alpha) * U16(blue) + U16(255-alpha) * u_blue )/255); buffer(idx+1):= Primary_color_range((U16(alpha) * U16(green) + U16(255-alpha) * u_green)/255); buffer(idx+2):= Primary_color_range((U16(alpha) * U16(red) + U16(255-alpha) * u_red )/255); end if; idx:= idx + 3; -- ^ GID requires us to look to next pixel on the right for next time. end Put_Pixel_with_unicolor_bkg; -- -- Background image version of Put_Pixel -- procedure Put_Pixel_with_image_bkg ( red, green, blue : Primary_color_range; alpha : Primary_color_range ) is pragma Inline(Put_Pixel_with_image_bkg); b_red, b_green, b_blue : Primary_color_range; bkg_idx: Natural; begin if alpha = 255 then buffer(idx..idx+2):= (blue, green, red); else -- blend with background image bkg_idx:= 3 * (mem_x mod bkg_width) + bkg_padded_line_size * (mem_y mod bkg_height); b_blue := bkg_buf(bkg_idx); b_green:= bkg_buf(bkg_idx+1); b_red := bkg_buf(bkg_idx+2); buffer(idx) := Primary_color_range((U16(alpha) * U16(blue) + U16(255-alpha) * U16(b_blue) )/255); buffer(idx+1):= Primary_color_range((U16(alpha) * U16(green) + U16(255-alpha) * U16(b_green))/255); buffer(idx+2):= Primary_color_range((U16(alpha) * U16(red) + U16(255-alpha) * U16(b_red) )/255); end if; idx:= idx + 3; -- ^ GID requires us to look to next pixel on the right for next time. mem_x:= mem_x + 1; end Put_Pixel_with_image_bkg; stars: Natural:= 0; procedure Feedback(percents: Natural) is so_far: constant Natural:= percents / 5; begin for i in stars+1..so_far loop Put( Standard_Error, '*'); end loop; stars:= so_far; end Feedback; -- Here, the exciting thing: the instanciation of -- GID.Load_image_contents. In our case, we load the image -- into a 24-bit bitmap (because we provide a Put_Pixel -- that does that with the pixels), but we could do plenty -- of other things instead, like display the image live on a GUI. -- More exciting: for tuning performance, we have 3 different -- instances of GID.Load_image_contents (each of them with the full -- decoders for all formats, own specialized generic instances, inlines, -- etc.) depending on the transparency features. procedure BMP24_Load_without_bkg is new GID.Load_image_contents( Primary_color_range, Set_X_Y, Put_Pixel_without_bkg, Feedback, GID.fast ); procedure BMP24_Load_with_unicolor_bkg is new GID.Load_image_contents( Primary_color_range, Set_X_Y, Put_Pixel_with_unicolor_bkg, Feedback, GID.fast ); procedure BMP24_Load_with_image_bkg is new GID.Load_image_contents( Primary_color_range, Set_X_Y, Put_Pixel_with_image_bkg, Feedback, GID.fast ); begin error:= False; Dispose(buffer); case correct_orientation is when GID.Unchanged | GID.Rotation_180 => buffer:= new Byte_Array(0..padded_line_size_x * GID.Pixel_height(image) - 1); when GID.Rotation_90 | GID.Rotation_270 => buffer:= new Byte_Array(0..padded_line_size_y * GID.Pixel_width(image) - 1); end case; if GID.Expect_transparency(image) then if background_image_name = Null_Unbounded_String then BMP24_Load_with_unicolor_bkg(image, next_frame); else bkg_width:= GID.Pixel_width(bkg); bkg_height:= GID.Pixel_height(bkg); bkg_padded_line_size:= 4 * Integer(Float'Ceiling(Float(bkg_width) * 3.0 / 4.0)); BMP24_Load_with_image_bkg(image, next_frame); end if; else BMP24_Load_without_bkg(image, next_frame); end if; -- -- For testing: white rectangle with a red half-frame. -- buffer.all:= (others => 255); -- for x in 0..GID.Pixel_width(image)-1 loop -- Put_Pixel_with_unicolor_bkg(x,0,255,0,0,255); -- end loop; -- for y in 0..GID.Pixel_height(image)-1 loop -- Put_Pixel_with_unicolor_bkg(0,y,255,0,0,255); -- end loop; exception when others => if forgive_errors then error:= True; next_frame:= 0.0; else raise; end if; end Load_raw_image; procedure Load_raw_image_0 is new Load_raw_image(GID.Unchanged); procedure Load_raw_image_90 is new Load_raw_image(GID.Rotation_90); procedure Load_raw_image_180 is new Load_raw_image(GID.Rotation_180); procedure Load_raw_image_270 is new Load_raw_image(GID.Rotation_270); procedure Dump_BMP_24(name: String; i: GID.Image_descriptor) is f: Ada.Streams.Stream_IO.File_Type; type BITMAPFILEHEADER is record bfType : Unsigned_16; bfSize : Unsigned_32; bfReserved1: Unsigned_16:= 0; bfReserved2: Unsigned_16:= 0; bfOffBits : Unsigned_32; end record; -- ^ No packing needed BITMAPFILEHEADER_Bytes: constant:= 14; type BITMAPINFOHEADER is record biSize : Unsigned_32; biWidth : Unsigned_32; biHeight : Unsigned_32; biPlanes : Unsigned_16:= 1; biBitCount : Unsigned_16; biCompression : Unsigned_32:= 0; biSizeImage : Unsigned_32; biXPelsPerMeter: Unsigned_32:= 0; biYPelsPerMeter: Unsigned_32:= 0; biClrUsed : Unsigned_32:= 0; biClrImportant : Unsigned_32:= 0; end record; -- ^ No packing needed BITMAPINFOHEADER_Bytes: constant:= 40; FileInfo : BITMAPINFOHEADER; FileHeader: BITMAPFILEHEADER; -- generic type Number is mod <>; procedure Write_Intel_x86_number(n: in Number); procedure Write_Intel_x86_number(n: in Number) is m: Number:= n; bytes: constant Integer:= Number'Size/8; begin for i in 1..bytes loop Unsigned_8'Write(Stream(f), Unsigned_8(m and 255)); m:= m / 256; end loop; end Write_Intel_x86_number; procedure Write_Intel is new Write_Intel_x86_number( Unsigned_16 ); procedure Write_Intel is new Write_Intel_x86_number( Unsigned_32 ); begin FileHeader.bfType := 16#4D42#; -- 'BM' FileHeader.bfOffBits := BITMAPINFOHEADER_Bytes + BITMAPFILEHEADER_Bytes; FileInfo.biSize := BITMAPINFOHEADER_Bytes; case GID.Display_orientation(i) is when GID.Unchanged | GID.Rotation_180 => FileInfo.biWidth := Unsigned_32(GID.Pixel_width(i)); FileInfo.biHeight := Unsigned_32(GID.Pixel_height(i)); when GID.Rotation_90 | GID.Rotation_270 => FileInfo.biWidth := Unsigned_32(GID.Pixel_height(i)); FileInfo.biHeight := Unsigned_32(GID.Pixel_width(i)); end case; FileInfo.biBitCount := 24; FileInfo.biSizeImage := Unsigned_32(img_buf.all'Length); FileHeader.bfSize := FileHeader.bfOffBits + FileInfo.biSizeImage; Create(f, Out_File, name & ".dib"); -- BMP Header, endian-safe: Write_Intel(FileHeader.bfType); Write_Intel(FileHeader.bfSize); Write_Intel(FileHeader.bfReserved1); Write_Intel(FileHeader.bfReserved2); Write_Intel(FileHeader.bfOffBits); -- Write_Intel(FileInfo.biSize); Write_Intel(FileInfo.biWidth); Write_Intel(FileInfo.biHeight); Write_Intel(FileInfo.biPlanes); Write_Intel(FileInfo.biBitCount); Write_Intel(FileInfo.biCompression); Write_Intel(FileInfo.biSizeImage); Write_Intel(FileInfo.biXPelsPerMeter); Write_Intel(FileInfo.biYPelsPerMeter); Write_Intel(FileInfo.biClrUsed); Write_Intel(FileInfo.biClrImportant); -- BMP raw BGR image: declare -- Workaround for the severe xxx'Read xxx'Write performance -- problems in the GNAT and ObjectAda compilers (as in 2009) -- This is possible if and only if Byte = Stream_Element and -- arrays types are both packed the same way. -- subtype Size_test_a is Byte_Array(1..19); subtype Size_test_b is Ada.Streams.Stream_Element_Array(1..19); workaround_possible: constant Boolean:= Size_test_a'Size = Size_test_b'Size and then Size_test_a'Alignment = Size_test_b'Alignment; -- begin if workaround_possible then declare use Ada.Streams; SE_Buffer : Stream_Element_Array (0..Stream_Element_Offset(img_buf'Length-1)); for SE_Buffer'Address use img_buf.all'Address; pragma Import (Ada, SE_Buffer); begin Ada.Streams.Write(Stream(f).all, SE_Buffer(0..Stream_Element_Offset(img_buf'Length-1))); end; else Byte_Array'Write(Stream(f), img_buf.all); -- the workaround is about this line... end if; end; Close(f); end Dump_BMP_24; procedure Process(name: String; as_background, test_only: Boolean) is f: Ada.Streams.Stream_IO.File_Type; i: GID.Image_descriptor; up_name: constant String:= To_Upper(name); -- next_frame, current_frame: Ada.Calendar.Day_Duration:= 0.0; begin -- -- Load the image in its original format -- Open(f, In_File, name); Put_Line(Standard_Error, "Processing " & name & "..."); -- GID.Load_image_header( i, Stream(f).all, try_tga => name'Length >= 4 and then up_name(up_name'Last-3..up_name'Last) = ".TGA" ); Put_Line(Standard_Error, " Image format: " & GID.Image_format_type'Image(GID.Format(i)) ); Put_Line(Standard_Error, " Image detailed format: " & GID.Detailed_format(i) ); Put_Line(Standard_Error, " Image sub-format ID (if any): " & Integer'Image(GID.Subformat(i)) ); Put_Line(Standard_Error, " Dimensions in pixels: " & Integer'Image(GID.Pixel_width(i)) & " x" & Integer'Image(GID.Pixel_height(i)) ); Put_Line(Standard_Error, " Display orientation: " & GID.Orientation'Image(GID.Display_orientation(i)) ); Put(Standard_Error, " Color depth: " & Integer'Image(GID.Bits_per_pixel(i)) & " bits" ); if GID.Bits_per_pixel(i) <= 24 then Put_Line(Standard_Error, ',' & Integer'Image(2**GID.Bits_per_pixel(i)) & " colors" ); else New_Line(Standard_Error); end if; Put_Line(Standard_Error, " Palette: " & Boolean'Image(GID.Has_palette(i)) ); Put_Line(Standard_Error, " Greyscale: " & Boolean'Image(GID.Greyscale(i)) ); Put_Line(Standard_Error, " RLE encoding (if any): " & Boolean'Image(GID.RLE_encoded(i)) ); Put_Line(Standard_Error, " Interlaced (GIF: each frame's choice): " & Boolean'Image(GID.Interlaced(i)) ); Put_Line(Standard_Error, " Expect transparency: " & Boolean'Image(GID.Expect_transparency(i)) ); Put_Line(Standard_Error, "1........10........20"); Put_Line(Standard_Error, " | | "); -- if as_background then case GID.Display_orientation(i) is when GID.Unchanged => Load_raw_image_0(i, bkg_buf, next_frame); when GID.Rotation_90 => Load_raw_image_90(i, bkg_buf, next_frame); when GID.Rotation_180 => Load_raw_image_180(i, bkg_buf, next_frame); when GID.Rotation_270 => Load_raw_image_270(i, bkg_buf, next_frame); end case; bkg:= i; New_Line(Standard_Error); Close(f); return; end if; loop case GID.Display_orientation(i) is when GID.Unchanged => Load_raw_image_0(i, img_buf, next_frame); when GID.Rotation_90 => Load_raw_image_90(i, img_buf, next_frame); when GID.Rotation_180 => Load_raw_image_180(i, img_buf, next_frame); when GID.Rotation_270 => Load_raw_image_270(i, img_buf, next_frame); end case; if not test_only then Dump_BMP_24(name & Duration'Image(current_frame), i); end if; New_Line(Standard_Error); if error then Put_Line(Standard_Error, "Error!"); end if; exit when next_frame = 0.0; current_frame:= next_frame; end loop; Close(f); exception when GID.unknown_image_format => Put_Line(Standard_Error, " Image format is unknown!"); if Is_Open(f) then Close(f); end if; end Process; test_only: Boolean:= False; begin if Argument_Count=0 then Blurb; return; end if; Put_Line(Standard_Error, "To_BMP, using GID version " & GID.version & " dated " & GID.reference); begin Process(default_bkg_name, True, False); -- if success: background_image_name:= To_Unbounded_String(default_bkg_name); exception when Ada.Text_IO.Name_Error => null; -- nothing bad, just couldn't find default background end; for i in 1..Argument_Count loop declare arg: constant String:= Argument(i); begin if arg /= "" and then arg(arg'First)='-' then declare opt: constant String:= arg(arg'First+1..arg'Last); begin if opt = "" then test_only:= True; else Put_Line(Standard_Error, "Background image is " & opt); Process(opt, True, False); -- define this only after processing, otherwise -- a transparent background will try to use -- an undefined background background_image_name:= To_Unbounded_String(opt); end if; end; else Process(arg, False, test_only); end if; end; end loop; end To_BMP;
with Digital; use Digital; with Analog; use Analog; with Pins_STM32F446; use Pins_STM32F446; package AdaCar.Entrada_Salida is procedure Init_System; function Lectura_Digital(Canal: Canal_DI) return Estado_Digital; procedure Salida_Digital(Canal: Canal_DO; Valor: Estado_Digital); procedure Comienza_Analogico(Canal: Canal_AI); function Lectura_Analogico(Canal: Canal_AI) return Unidades_AI; end AdaCar.Entrada_Salida;
------------------------------------------------------------------------------- -- Copyright (c) 2016, Daniel King -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- * Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- * The name of the copyright holder may not be used to endorse or promote -- Products derived from this software without specific prior written -- permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -- DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------- with Ketje_Tests; with Ketje; with AUnit.Test_Caller; package body Ketje_Suite is package Ketje_Jr_Tests is new Ketje_Tests (Ketje.Jr); package Ketje_Sr_Tests is new Ketje_Tests (Ketje.Jr); package Ketje_Minor_Tests is new Ketje_Tests (Ketje.Minor); package Ketje_Major_Tests is new Ketje_Tests (Ketje.Major); package Caller_Jr is new AUnit.Test_Caller (Ketje_Jr_Tests.Test); package Caller_Sr is new AUnit.Test_Caller (Ketje_Sr_Tests.Test); package Caller_Minor is new AUnit.Test_Caller (Ketje_Minor_Tests.Test); package Caller_Major is new AUnit.Test_Caller (Ketje_Major_Tests.Test); function Suite return Access_Test_Suite is Ret : constant Access_Test_Suite := new Test_Suite; begin -- KetjeJr Ret.Add_Test (Caller_Jr.Create ("KetjeJr: Test encrypt -> decrypt loopback", Ketje_Jr_Tests.Test_Encrypt_Decrypt'Access)); Ret.Add_Test (Caller_Jr.Create ("KetjeJr: Test streaming AAD", Ketje_Jr_Tests.Test_Streaming_AAD'Access)); Ret.Add_Test (Caller_Jr.Create ("KetjeJr: Test streaming encryption", Ketje_Jr_Tests.Test_Streaming_Encryption'Access)); Ret.Add_Test (Caller_Jr.Create ("KetjeJr: Test streaming decryption", Ketje_Jr_Tests.Test_Streaming_Decryption'Access)); Ret.Add_Test (Caller_Jr.Create ("KetjeJr: Test streaming tag", Ketje_Jr_Tests.Test_Streaming_Tag'Access)); Ret.Add_Test (Caller_Jr.Create ("KetjeJr: Test Verify_Tag", Ketje_Jr_Tests.Test_Verify_Tag'Access)); Ret.Add_Test (Caller_Jr.Create ("KetjeJr: Test streaming Verify_Tag", Ketje_Jr_Tests.Test_Streaming_Verify_Tag'Access)); -- KetjeSr Ret.Add_Test (Caller_Sr.Create ("KetjeSr: Test encrypt -> decrypt loopback", Ketje_Sr_Tests.Test_Encrypt_Decrypt'Access)); Ret.Add_Test (Caller_Sr.Create ("KetjeSr: Test streaming AAD", Ketje_Sr_Tests.Test_Streaming_AAD'Access)); Ret.Add_Test (Caller_Sr.Create ("KetjeSr: Test streaming encryption", Ketje_Sr_Tests.Test_Streaming_Encryption'Access)); Ret.Add_Test (Caller_Sr.Create ("KetjeSr: Test streaming decryption", Ketje_Sr_Tests.Test_Streaming_Decryption'Access)); Ret.Add_Test (Caller_Sr.Create ("KetjeSr: Test streaming tag", Ketje_Sr_Tests.Test_Streaming_Tag'Access)); Ret.Add_Test (Caller_Sr.Create ("KetjeSr: Test Verify_Tag", Ketje_Sr_Tests.Test_Verify_Tag'Access)); Ret.Add_Test (Caller_Sr.Create ("KetjeSr: Test streaming Verify_Tag", Ketje_Sr_Tests.Test_Streaming_Verify_Tag'Access)); -- KetjeMinor Ret.Add_Test (Caller_Minor.Create ("KetjeMinor: Test encrypt -> decrypt loopback", Ketje_Minor_Tests.Test_Encrypt_Decrypt'Access)); Ret.Add_Test (Caller_Minor.Create ("KetjeMinor: Test streaming AAD", Ketje_Minor_Tests.Test_Streaming_AAD'Access)); Ret.Add_Test (Caller_Minor.Create ("KetjeMinor: Test streaming encryption", Ketje_Minor_Tests.Test_Streaming_Encryption'Access)); Ret.Add_Test (Caller_Minor.Create ("KetjeMinor: Test streaming decryption", Ketje_Minor_Tests.Test_Streaming_Decryption'Access)); Ret.Add_Test (Caller_Minor.Create ("KetjeMinor: Test streaming tag", Ketje_Minor_Tests.Test_Streaming_Tag'Access)); Ret.Add_Test (Caller_Minor.Create ("KetjeMinor: Test Verify_Tag", Ketje_Minor_Tests.Test_Verify_Tag'Access)); Ret.Add_Test (Caller_Minor.Create ("KetjeMinor: Test streaming Verify_Tag", Ketje_Minor_Tests.Test_Streaming_Verify_Tag'Access)); -- KetjeMajor Ret.Add_Test (Caller_Major.Create ("KetjeMajor: Test encrypt -> decrypt loopback", Ketje_Major_Tests.Test_Encrypt_Decrypt'Access)); Ret.Add_Test (Caller_Major.Create ("KetjeMajor: Test streaming AAD", Ketje_Major_Tests.Test_Streaming_AAD'Access)); Ret.Add_Test (Caller_Major.Create ("KetjeMajor: Test streaming encryption", Ketje_Major_Tests.Test_Streaming_Encryption'Access)); Ret.Add_Test (Caller_Major.Create ("KetjeMajor: Test streaming decryption", Ketje_Major_Tests.Test_Streaming_Decryption'Access)); Ret.Add_Test (Caller_Major.Create ("KetjeMajor: Test streaming tag", Ketje_Major_Tests.Test_Streaming_Tag'Access)); Ret.Add_Test (Caller_Major.Create ("KetjeMajor: Test Verify_Tag", Ketje_Major_Tests.Test_Verify_Tag'Access)); Ret.Add_Test (Caller_Major.Create ("KetjeMajor: Test streaming Verify_Tag", Ketje_Major_Tests.Test_Streaming_Verify_Tag'Access)); return Ret; end Suite; end Ketje_Suite;
with GL; use GL; with GLU; use GLU; with Glut; use Glut; with GNAT.OS_Lib; package body ada_sphere_procs is procedure display is begin glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); glutSolidSphere(1.0, 10, 10); glutSwapBuffers; end display; procedure reshape(w : Integer; h : Integer) is begin glViewport(0, 0, GLsizei(w), GLsizei(h)); end reshape; procedure menu (value : Integer) is begin if (value = 666) then GNAT.OS_Lib.OS_Exit (0); end if; end menu; procedure init is light_diffuse : array(0 .. 3) of aliased GLfloat := (1.0, 0.0, 0.0, 1.0); light_position : array(0 .. 3) of aliased GLfloat := (1.0, 1.0, 1.0, 0.0); begin glClearColor(0.1, 0.1, 0.1, 0.0); glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse(0)'access); glLightfv(GL_LIGHT0, GL_POSITION, light_position(0)'access); glFrontFace(GL_CW); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glMatrixMode(GL_PROJECTION); gluPerspective(40.0, 1.0, 1.0, 10.0); glMatrixMode(GL_MODELVIEW); gluLookAt( 0.0, 0.0, -5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); end init; end ada_sphere_procs;
with Ada.Command_Line; with Ada.Text_IO; use Ada.Text_IO; with GNATCOLL.Projects; with GNATCOLL.VFS; with Langkit_Support.Slocs; with Libadalang.Analysis; with Libadalang.Common; with Libadalang.Project_Provider; procedure Main is package LAL renames Libadalang.Analysis; package LALCO renames Libadalang.Common; package Slocs renames Langkit_Support.Slocs; -- Context : constant LAL.Analysis_Context := LAL.Create_Context; Context : LAL.Analysis_Context; Provider : LAL.Unit_Provider_Reference; -- If Node is an object declaration, print its text. Always continue the -- traversal. function Process_Node (Node : LAL.Ada_Node'Class) return LALCO.Visit_Status is use type LALCO.Ada_Node_Kind_Type; begin -- if Node.Kind = LALCO.Ada_Object_Decl then Put_Line ("Line" & Slocs.Line_Number'Image (Node.Sloc_Range.Start_Line) & ": " & LALCO.Ada_Node_Kind_Type'Image (Node.kind) & ": " & Node.Debug_Text); -- end if; return LALCO.Into; end Process_Node; -- Load the project file designated by the first command-line argument function Load_Project return LAL.Unit_Provider_Reference is package GPR renames GNATCOLL.Projects; package LAL_GPR renames Libadalang.Project_Provider; use type GNATCOLL.VFS.Filesystem_String; Project_Filename : constant String := Ada.Command_Line.Argument (1); Project_File : constant GNATCOLL.VFS.Virtual_File := GNATCOLL.VFS.Create (+Project_Filename); Env : GPR.Project_Environment_Access; Project : constant GPR.Project_Tree_Access := new GPR.Project_Tree; begin GPR.Initialize (Env); -- Use procedures in GNATCOLL.Projects to set scenario -- variables (Change_Environment), to set the target -- and the runtime (Set_Target_And_Runtime), etc. Project.Load (Project_File, Env); return LAL_GPR.Create_Project_Unit_Provider (Tree => Project, Project => GPR.No_Project, Env => Env); end Load_Project; begin Context := LAL.Create_Context (Unit_Provider => Load_Project); -- Try to parse all source file given as arguments for I in 2 .. Ada.Command_Line.Argument_Count loop declare Filename : constant String := Ada.Command_Line.Argument (I); Unit : constant LAL.Analysis_Unit := Context.Get_From_File (Filename); begin Put_Line ("== " & Filename & " =="); -- Report parsing errors, if any if Unit.Has_Diagnostics then for D of Unit.Diagnostics loop Put_Line (Unit.Format_GNU_Diagnostic (D)); end loop; -- Otherwise, look for object declarations else Unit.Root.Traverse (Process_Node'Access); end if; New_Line; end; end loop; end Main;
with Interfaces.C; with System.Address_To_Access_Conversions; with System.Storage_Elements; with Ada.Strings.Unbounded; package body OpenAL.List is package C renames Interfaces.C; package UB_Strings renames Ada.Strings.Unbounded; package Bytes is new System.Address_To_Access_Conversions (Object => C.char); use System.Storage_Elements; use type C.char; use type UB_Strings.Unbounded_String; procedure Address_To_Vector (Address : in System.Address; List : out String_Vector_t) is Current_Address : System.Address := Address; Char_Pointer : Bytes.Object_Pointer; Next_Pointer : Bytes.Object_Pointer; Buffer : UB_Strings.Unbounded_String; begin Main_Loop : loop Char_Pointer := Bytes.To_Pointer (Current_Address); if Char_Pointer.all /= C.nul then UB_Strings.Append (Buffer, C.To_Ada (Char_Pointer.all)); else if Buffer /= UB_Strings.Null_Unbounded_String then String_Vectors.Append (List, UB_Strings.To_String (Buffer)); Buffer := UB_Strings.Null_Unbounded_String; end if; Next_Pointer := Bytes.To_Pointer (Current_Address + 1); if Next_Pointer.all = C.nul then exit Main_Loop; end if; end if; Current_Address := Current_Address + 1; end loop Main_Loop; end Address_To_Vector; end OpenAL.List;
-- { dg-do run } -- { dg-options "-gnatp" } procedure Misaligned_Nest is type Int is record V : Integer; end record; type Block is record B : Boolean; I : Int; end record; pragma Pack (Block); for Block'Alignment use 1; type Pair is array (1 .. 2) of Block; P : Pair; begin for K in P'Range loop P(K).I.V := 1; end loop; end;
with RP.Device; with Tiny; procedure LEDs is Delay_In_Between : constant Integer := 1000; begin Tiny.Initialize; loop -- LED Red RP.Device.Timer.Delay_Milliseconds (Delay_In_Between); Tiny.Switch_On (Tiny.LED_Red); RP.Device.Timer.Delay_Milliseconds (Delay_In_Between); Tiny.Switch_Off (Tiny.LED_Red); -- LED Green RP.Device.Timer.Delay_Milliseconds (Delay_In_Between); Tiny.Switch_On (Tiny.LED_Green); RP.Device.Timer.Delay_Milliseconds (Delay_In_Between); Tiny.Switch_Off (Tiny.LED_Green); -- LED Blue RP.Device.Timer.Delay_Milliseconds (Delay_In_Between); Tiny.Switch_On (Tiny.LED_Blue); RP.Device.Timer.Delay_Milliseconds (Delay_In_Between); Tiny.Switch_Off (Tiny.LED_Blue); end loop; end LEDs;
with Version; with CLIC.Subcommand; private with CLIC.Subcommand.Instance; private with Ada.Text_IO; private with CLIC.TTY; private with GNAT.OS_Lib; with Templates_Parser; package Commands is Translations : Templates_Parser.Translate_Set; Wrong_Command_Arguments : exception; Child_Failed : exception; -- Used to notify that a subprocess completed with non-zero error Command_Failed : exception; -- Signals "normal" command completion with failure -- (i.e., no need to print stack trace). ------------- -- Execute -- ------------- procedure Execute; -- Entry point into WebsiteGenerator, -- will parse the command line and proceed as needed. ------------- -- Command -- ------------- type Command is abstract limited new CLIC.Subcommand.Command with private; -- This type encapsulates configuration and execution of a specific -- command. private type Command is abstract limited new CLIC.Subcommand.Command with null record; procedure Set_Global_Switches (Config : in out CLIC.Subcommand.Switches_Configuration); package Sub_Cmd is new CLIC.Subcommand.Instance (Main_Command_Name => "websitegenerator", Version => Version.Current, Put => Ada.Text_IO.Put, Put_Line => Ada.Text_IO.Put_Line, Put_Error => Ada.Text_IO.Put_Line, Error_Exit => GNAT.OS_Lib.OS_Exit, Set_Global_Switches => Set_Global_Switches, TTY_Chapter => CLIC.TTY.Bold, TTY_Description => CLIC.TTY.Description, TTY_Version => CLIC.TTY.Version, TTY_Underline => CLIC.TTY.Underline, TTY_Emph => CLIC.TTY.Emph); end Commands;
-- SPDX-FileCopyrightText: 2019 Max Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT ------------------------------------------------------------- with Program.Elements.Constraints; with Program.Lexical_Elements; with Program.Elements.Expressions; package Program.Elements.Digits_Constraints is pragma Pure (Program.Elements.Digits_Constraints); type Digits_Constraint is limited interface and Program.Elements.Constraints.Constraint; type Digits_Constraint_Access is access all Digits_Constraint'Class with Storage_Size => 0; not overriding function Digits_Expression (Self : Digits_Constraint) return not null Program.Elements.Expressions.Expression_Access is abstract; not overriding function Real_Range_Constraint (Self : Digits_Constraint) return Program.Elements.Constraints.Constraint_Access is abstract; type Digits_Constraint_Text is limited interface; type Digits_Constraint_Text_Access is access all Digits_Constraint_Text'Class with Storage_Size => 0; not overriding function To_Digits_Constraint_Text (Self : in out Digits_Constraint) return Digits_Constraint_Text_Access is abstract; not overriding function Digits_Token (Self : Digits_Constraint_Text) return not null Program.Lexical_Elements.Lexical_Element_Access is abstract; not overriding function Range_Token (Self : Digits_Constraint_Text) return Program.Lexical_Elements.Lexical_Element_Access is abstract; end Program.Elements.Digits_Constraints;
with datos; use datos; procedure Desplazar_Una_Posicion_A_La_Derecha (L : in out Lista_Enteros; PosActual, Pos : in Integer) is --Pre: Pos indica una posicion de L (entre 1 y L.Cont + 1) --Post: se han desplazado una posicion a la derecha todos los -- elementos de L, empezando por Pos hasta L.Cont Cont, Num : Integer; begin Cont := PosActual; Num := L.Numeros(PosActual); loop exit when Cont = Pos; L.Numeros(Cont):= L.Numeros(Cont-1); Cont := Cont-1; end loop; L.Numeros(Cont) := Num; end Desplazar_Una_Posicion_A_La_Derecha;
package body System.Storage_Elements is pragma Suppress (All_Checks); function "+" (Left : Address; Right : Storage_Offset) return Address is begin return System'To_Address ( Integer_Address (Left) + Integer_Address'Mod (Right)); end "+"; function "+" (Left : Storage_Offset; Right : Address) return Address is begin return System'To_Address ( Integer_Address'Mod (Left) + Integer_Address (Right)); end "+"; function "-" (Left : Address; Right : Storage_Offset) return Address is begin return System'To_Address ( Integer_Address (Left) - Integer_Address'Mod (Right)); end "-"; function "-" (Left, Right : Address) return Storage_Offset is begin return Storage_Offset (Left) - Storage_Offset (Right); end "-"; function "mod" (Left : Address; Right : Storage_Offset) return Storage_Offset is begin return Storage_Offset (Left mod Address (Right)); -- unsigned mod end "mod"; function To_Address (Value : Integer_Address) return Address is begin return Address (Value); end To_Address; function To_Integer (Value : Address) return Integer_Address is begin return Integer_Address (Value); end To_Integer; end System.Storage_Elements;
with Trendy_Terminal.Completions; with Trendy_Terminal.Maps; with Trendy_Terminal.Lines; use Trendy_Terminal.Lines; with Trendy_Terminal.Lines.Line_Vectors; package body Trendy_Terminal.IO.Line_Editors is function Should_Terminate_Input (Input_Line : ASU.Unbounded_String) return Boolean is Key_CR : constant := 10; Key_FF : constant := 13; Input : constant Integer := Character'Pos(ASU.Element(Input_Line, 1)); begin return Input = Key_CR or else Input = Key_FF; end Should_Terminate_Input; -- Processes the next line of input in according to completion, formatting, -- and hinting callbacks. -- -- TODO: Support full utf-8. Only ASCII is supported for now. -- -- Helper to implicitly use a Stateless_Line_Editor function Get_Line(Format_Fn : Format_Function := null; Completion_Fn : Completion_Function := null; Line_History : Histories.History_Access := null) return String is Editor : Stateless_Line_Editor := (Format_Fn => Format_Fn, Completion_Fn => Completion_Fn, Line_History => Line_History); begin return Get_Line (Editor); end Get_Line; function Get_Line (Editor : in out Line_Editor'Class) return String is use Trendy_Terminal.Maps; use all type ASU.Unbounded_String; use all type Ada.Containers.Count_Type; use Trendy_Terminal.Histories; Input_Line : ASU.Unbounded_String; L : Lines.Line; Line_Pos : constant VT100.Cursor_Position := VT100.Get_Cursor_Position; Edit_Pos : VT100.Cursor_Position := Line_Pos; Tab_Pos : Integer := 1; Tab_Completions : Trendy_Terminal.Completions.Completion_Set; History_Completions : Trendy_Terminal.Completions.Completion_Set; Reset_Keys : constant array(Positive range <>) of Key := (Key_Left, Key_Right, Key_Backspace, Key_Delete, Key_Home, Key_End ); begin Edit_Pos.Row := Line_Pos.Row; Trendy_Terminal.Completions.Clear (Tab_Completions); Trendy_Terminal.Completions.Clear (History_Completions); loop Rewrite_Line (Line_Pos, Lines.Current (Editor.Format (L))); Edit_Pos.Col := Lines.Get_Cursor_Index(L) + Line_Pos.Col - 1; VT100.Set_Cursor_Position (Edit_Pos); -- Get and process the new input. Input_Line := ASU.To_Unbounded_String(Platform.Get_Input); if Maps.Sequence_For(Key_Left) = Input_Line then Lines.Move_Cursor(L, Lines.Left); elsif Maps.Sequence_For (Key_Right) = Input_Line then Lines.Move_Cursor(L, Lines.Right); elsif Maps.Sequence_For (Key_Backspace) = Input_Line then Lines.Backspace (L); elsif Maps.Sequence_For (Key_Delete) = Input_Line then Lines.Delete (L); elsif Maps.Sequence_For (Key_Home) = Input_Line then Lines.Set_Cursor_Index (L, 1); elsif Maps.Sequence_For (Key_End) = Input_Line then Lines.Set_Cursor_Index (L, Lines.Length (L) + 1); elsif Maps.Sequence_For (Key_Up) = Input_Line then -- Roll to the previous element in history Trendy_Terminal.Completions.Clear (Tab_Completions); if not Trendy_Terminal.Completions.Is_Empty (History_Completions) then Trendy_Terminal.Completions.Move_Forward (History_Completions); elsif Editor.Line_History /= null then Trendy_Terminal.Completions.Fill ( History_Completions, Trendy_Terminal.Histories.Completions_Matching ( Editor.Line_History.all, Lines.Current (L))); end if; if not Trendy_Terminal.Completions.Is_Empty (History_Completions) then L := Lines.Make (Trendy_Terminal.Completions.Get_Current (History_Completions)); end if; elsif Maps.Sequence_For (Key_Down) = Input_Line then Trendy_Terminal.Completions.Clear (Tab_Completions); if not Trendy_Terminal.Completions.Is_Empty (History_Completions) then Trendy_Terminal.Completions.Move_Backward (History_Completions); else if Editor.Line_History /= null then Trendy_Terminal.Completions.Fill ( History_Completions, Trendy_Terminal.Histories.Completions_Matching ( Editor.Line_History.all, Lines.Current (L))); end if; end if; if not Trendy_Terminal.Completions.Is_Empty (History_Completions) then L := Lines.Make (Trendy_Terminal.Completions.Get_Current (History_Completions)); end if; elsif Maps.Sequence_For (Key_Shift_Tab) = Input_Line then Trendy_Terminal.Completions.Clear (History_Completions); if not Trendy_Terminal.Completions.Is_Empty (Tab_Completions) then Trendy_Terminal.Completions.Move_Backward (Tab_Completions); else Trendy_Terminal.Completions.Fill (Tab_Completions, Editor.Complete (L)); end if; if not Trendy_Terminal.Completions.Is_Empty (Tab_Completions) then L := Lines.Make (Trendy_Terminal.Completions.Get_Current (Tab_Completions)); end if; elsif Maps.Sequence_For (Key_Tab) = Input_Line then Trendy_Terminal.Completions.Clear (History_Completions); if not Trendy_Terminal.Completions.Is_Empty (Tab_Completions) then Trendy_Terminal.Completions.Move_Forward (Tab_Completions); else Trendy_Terminal.Completions.Fill (Tab_Completions, Editor.Complete (L)); end if; if not Trendy_Terminal.Completions.Is_Empty (Tab_Completions) then L := Lines.Make (Trendy_Terminal.Completions.Get_Current (Tab_Completions)); end if; elsif Maps.Sequence_For (Key_Ctrl_C) = Input_Line then return ""; elsif ASU.Length (Input_Line) = 1 and then Should_Terminate_Input (Input_Line) then -- TODO: this should only add the commadn if it was successful. Submit (Editor, L); return Lines.Current (L); elsif not Maps.Is_Key (ASU.To_String (Input_Line)) then -- Actual text was inserted, so restart completions. -- TODO: Maybe add a "replace" mode? Trendy_Terminal.Completions.Clear (Tab_Completions); Trendy_Terminal.Completions.Clear (History_Completions); Lines.Insert (L, ASU.To_String (Input_Line)); end if; if Maps.Is_Key (ASU.To_String (Input_Line)) and then (for some Key of Reset_Keys => Maps.Key_For (ASU.To_String (Input_Line)) = Key) then Trendy_Terminal.Completions.Clear (Tab_Completions); Trendy_Terminal.Completions.Clear (History_Completions); end if; end loop; end Get_Line; overriding function Format (E : in out Stateless_Line_Editor; L : Lines.Line) return Lines.Line is (if E.Format_Fn /= null then E.Format_Fn (L) else L); overriding function Complete (E : in out Stateless_Line_Editor; L : Lines.Line) return Lines.Line_Vectors.Vector is (if E.Completion_Fn /= null then E.Completion_Fn (L) else Lines.Line_Vectors.Empty_Vector); overriding procedure Submit (E: in out Stateless_Line_Editor; L : Lines.Line) is begin null; end Submit; end Trendy_Terminal.IO.Line_Editors;
package Integrators.RK4 is pragma Preelaborate; -- Runge Kutta order 4 integrator type RK4_Integrator is new Integrator with private; overriding procedure Integrate (Object : in out RK4_Integrator; Subject : in out Physics_Object'Class; T, DT : GL.Types.Double); overriding function State (Object : RK4_Integrator) return Integrator_State; function Create_Integrator (Subject : Physics_Object'Class; Position : Vectors.Vector4; Velocity : Vectors.Vector4; Orientation : Quaternions.Quaternion := Quaternions.Identity_Value) return RK4_Integrator; private type Linear_State is record Position, Momentum, Velocity : Vectors.Vector4 := Vectors.Zero_Point; Inverse_Mass : GL.Types.Double; end record; type Angular_State is record Orientation : Quaternions.Quaternion := Quaternions.Identity_Value; Angular_Momentum, Angular_Velocity : Vectors.Vector4 := Vectors.Zero_Point; Inverse_Inertia : GL.Types.Double; end record; type RK4_Integrator is new Integrator with record Linear : Linear_State; Angular : Angular_State; end record; end Integrators.RK4;
with HAL.Bitmap; use HAL.Bitmap; package Utils is BG : constant Bitmap_Color := (Alpha => 255, others => 0); procedure Clear(Update : Boolean; Color : Bitmap_Color := BG); function GetRandomFloat return Float; end Utils;
------------------------------------------------------------------------------ -- 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) $: with Asis.Errors; with Asis.Elements; with Asis.Exceptions; with Asis.Declarations; use Asis.Declarations; with Asis.Implementation; with Asis.Compilation_Units; use Asis.Compilation_Units; with Asis.Gela.Units; with XASIS.Utils; with Asis.Gela.Contexts.Utils; with Ada.Wide_Text_IO; package body Asis.Gela.Contexts is procedure Check_Same_Context (Unit : Asis.Compilation_Unit; The_Context : Concrete_Context_Node; Raiser : Wide_String); procedure Check_Same_Context (Decl : Asis.Declaration; The_Context : Concrete_Context_Node; Raiser : Wide_String); --------------- -- Associate -- --------------- procedure Associate (The_Context : access Concrete_Context_Node; Name : in Wide_String; Parameters : in Wide_String) is begin The_Context.This := Asis.Context (The_Context); The_Context.Context_Name := U.To_Unbounded_Wide_String (Name); The_Context.Parameters := U.To_Unbounded_Wide_String (Parameters); The_Context.Has_Associations := True; The_Context.Error := Success; The_Context.User_Encoding := Encodings.UTF_8; -- The_Context.Current_File := The_Context.Parameters; Compilations.Initialize (The_Context.Compilation_List); end Associate; ----------------------- -- Check_Appropriate -- ----------------------- function Check_Appropriate (The_Context : in Concrete_Context_Node) return Boolean is begin return The_Context.Check_Appropriate; end Check_Appropriate; ------------------------ -- Check_Same_Context -- ------------------------ procedure Check_Same_Context (Unit : Asis.Compilation_Unit; The_Context : Concrete_Context_Node; Raiser : Wide_String) is Decl : constant Asis.Declaration := Asis.Elements.Unit_Declaration (Unit); begin Check_Same_Context (Decl, The_Context, Raiser); end Check_Same_Context; ------------------------ -- Check_Same_Context -- ------------------------ procedure Check_Same_Context (Decl : Asis.Declaration; The_Context : Concrete_Context_Node; Raiser : Wide_String) is use Asis.Elements; Unit : constant Asis.Compilation_Unit := Asis.Elements.Enclosing_Compilation_Unit (Decl); Unit_Context : constant Asis.Context := Enclosing_Context (Unit); begin if not Assigned (Unit_Context) or else Unit_Context.all not in Concrete_Context_Node'Class or else not Is_Equal (The_Context, Concrete_Context_Node (Unit_Context.all)) then Implementation.Set_Status (Asis.Errors.Not_Implemented_Error, "Multiple context in : " & Raiser); raise Asis.Exceptions.ASIS_Failed; end if; end Check_Same_Context; ----------- -- Close -- ----------- procedure Close (The_Context : in out Concrete_Context_Node) is begin The_Context.Is_Open := False; end Close; ----------------------------- -- Compilation_Unit_Bodies -- ----------------------------- function Compilation_Unit_Bodies (The_Context : in Concrete_Context_Node) return Asis.Compilation_Unit_List is begin return Secondary_Unit_Lists.To_Compilation_Unit_List (The_Context.Compilation_Unit_Bodies); end Compilation_Unit_Bodies; --------------------------- -- Compilation_Unit_Body -- --------------------------- function Compilation_Unit_Body (Name : in Wide_String; The_Context : in Concrete_Context_Node) return Asis.Compilation_Unit is -- use Asis.Gela.Elements.Utils; use Secondary_Unit_Lists; use type U.Unbounded_Wide_String; Bodies : List_Node renames The_Context.Compilation_Unit_Bodies; Unit : Compilation_Unit; begin for I in 1 .. Length (Bodies) loop Unit := Compilation_Unit (Get (Bodies, I)); if XASIS.Utils.Are_Equal_Identifiers (Unit_Full_Name (Unit), Name) then return Unit; end if; end loop; return Nil_Compilation_Unit; end Compilation_Unit_Body; --------------------------- -- Configuration_Pragmas -- --------------------------- function Configuration_Pragmas (The_Context : in Concrete_Context_Node) return Asis.Pragma_Element_List is begin return Secondary_Pragma_Lists.To_Pragma_List (The_Context.Configuration_Pragmas); end Configuration_Pragmas; ----------------------------- -- Make_Configuration_Unit -- ----------------------------- procedure Make_Configuration_Unit (The_Context : in out Concrete_Context_Node) is use Asis.Gela.Units; New_Unit : Any_Compilation_Unit_Ptr; begin if not Assigned (The_Context.Configuration_Unit) then New_Unit := new Any_Compilation_Unit_Node; Set_Enclosing_Context (New_Unit.all, The_Context.This); Set_Unit_Kind (New_Unit.all, A_Configuration_Compilation); Set_Unit_Class (New_Unit.all, Not_A_Class); Set_Unit_Origin (New_Unit.all, An_Application_Unit); The_Context.Configuration_Unit := Asis.Compilation_Unit (New_Unit); end if; end Make_Configuration_Unit; ------------------------------- -- Context_Compilation_Units -- ------------------------------- function Context_Compilation_Units (The_Context : in Concrete_Context_Node) return Asis.Compilation_Unit_List is begin return Compilation_Unit_Bodies (The_Context) & Library_Unit_Declarations (The_Context); end Context_Compilation_Units; ------------------ -- Context_Name -- ------------------ function Context_Name (The_Context : Concrete_Context_Node) return Wide_String is begin return U.To_Wide_String (The_Context.Context_Name); end Context_Name; ------------------------ -- Corresponding_Body -- ------------------------ function Corresponding_Body (Library_Item : in Asis.Compilation_Unit; The_Context : in Concrete_Context_Node) return Asis.Compilation_Unit is begin Check_Same_Context (Library_Item, The_Context, "Corresponding_Body"); return Corresponding_Body (Library_Item); end Corresponding_Body; ------------------------ -- Corresponding_Body -- ------------------------ function Corresponding_Body (Declaration : in Asis.Declaration; The_Context : in Concrete_Context_Node) return Asis.Declaration is begin Check_Same_Context (Declaration, The_Context, "Corresponding_Body"); return Corresponding_Body (Declaration); end Corresponding_Body; ----------------------------- -- Corresponding_Body_Stub -- ----------------------------- function Corresponding_Body_Stub (Subunit : in Asis.Declaration; The_Context : in Concrete_Context_Node) return Asis.Declaration is begin Check_Same_Context (Subunit, The_Context, "Corresponding_Body_Stub"); return Corresponding_Body_Stub (Subunit); end Corresponding_Body_Stub; ---------------------------- -- Corresponding_Children -- ---------------------------- function Corresponding_Children (Library_Unit : in Asis.Compilation_Unit; The_Context : in Concrete_Context_Node) return Asis.Compilation_Unit_List is begin Check_Same_Context (Library_Unit, The_Context, "Corresponding_Children"); return Corresponding_Children (Library_Unit); end Corresponding_Children; ------------------------------- -- Corresponding_Declaration -- ------------------------------- function Corresponding_Declaration (Library_Item : in Asis.Compilation_Unit; The_Context : in Concrete_Context_Node) return Asis.Compilation_Unit is begin Check_Same_Context (Library_Item, The_Context, "Corresponding_Declaration"); return Corresponding_Declaration (Library_Item); end Corresponding_Declaration; ------------------------------- -- Corresponding_Declaration -- ------------------------------- function Corresponding_Declaration (Declaration : in Asis.Declaration; The_Context : in Concrete_Context_Node) return Asis.Declaration is begin Check_Same_Context (Declaration, The_Context, "Corresponding_Declaration"); return Corresponding_Declaration (Declaration); end Corresponding_Declaration; -------------------------------------- -- Corresponding_Parent_Declaration -- -------------------------------------- function Corresponding_Parent_Declaration (Library_Unit : in Asis.Compilation_Unit; The_Context : in Concrete_Context_Node) return Asis.Compilation_Unit is begin Check_Same_Context (Library_Unit, The_Context, "Corresponding_Parent_Declaration"); return Corresponding_Parent_Declaration (Library_Unit); end Corresponding_Parent_Declaration; --------------------------- -- Corresponding_Subunit -- --------------------------- function Corresponding_Subunit (Body_Stub : in Asis.Declaration; The_Context : in Concrete_Context_Node) return Asis.Declaration is begin Check_Same_Context (Body_Stub, The_Context, "Corresponding_Subunit"); return Corresponding_Subunit (Body_Stub); end Corresponding_Subunit; --------------------------------------- -- Corresponding_Subunit_Parent_Body -- --------------------------------------- function Corresponding_Subunit_Parent_Body (Subunit : in Asis.Compilation_Unit; The_Context : in Concrete_Context_Node) return Asis.Compilation_Unit is begin Check_Same_Context (Subunit, The_Context, "Corresponding_Subunit_Parent_Body"); return Corresponding_Subunit_Parent_Body (Subunit); end Corresponding_Subunit_Parent_Body; ------------------------------------ -- Corresponding_Type_Declaration -- ------------------------------------ function Corresponding_Type_Declaration (Declaration : in Asis.Declaration; The_Context : in Concrete_Context_Node) return Asis.Declaration is begin Check_Same_Context (Declaration, The_Context, "Corresponding_Type_Declaration"); return Corresponding_Type_Declaration (Declaration); end Corresponding_Type_Declaration; ------------------ -- Current_File -- ------------------ function Current_File (The_Context : Concrete_Context_Node) return Wide_String is begin return U.To_Wide_String (The_Context.Current_File); end Current_File; ------------------ -- Current_Unit -- ------------------ function Current_Unit (The_Context : in Concrete_Context_Node) return Asis.Compilation_Unit is begin return The_Context.Current_Unit; end Current_Unit; ----------------- -- Debug_Image -- ----------------- function Debug_Image (The_Context : Concrete_Context_Node) return Wide_String is begin return "Debug_Image"; end Debug_Image; ---------------- -- Dissociate -- ---------------- procedure Dissociate (The_Context : in out Concrete_Context_Node) is begin The_Context.Has_Associations := False; -- Compilations.Finalize (The_Context.Compilation_List); end Dissociate; ---------------------- -- Has_Associations -- ---------------------- function Has_Associations (The_Context : Concrete_Context_Node) return Boolean is begin return The_Context.Has_Associations; end Has_Associations; -------------- -- Is_Equal -- -------------- function Is_Equal (Left : in Concrete_Context_Node; Right : in Concrete_Context_Node) return Boolean is use type U.Unbounded_Wide_String; begin return Left.Context_Name = Right.Context_Name; end Is_Equal; ------------- -- Is_Open -- ------------- function Is_Open (The_Context : Concrete_Context_Node) return Boolean is begin return The_Context.Is_Open; end Is_Open; -------------------------- -- New_Compilation_Unit -- -------------------------- function New_Compilation_Unit (The_Context : access Concrete_Context_Node) return Asis.Compilation_Unit is use Asis.Gela.Units; Result : constant Asis.Compilation_Unit := The_Context.Current_Unit; New_Unit : constant Any_Compilation_Unit_Ptr := new Any_Compilation_Unit_Node; begin Set_Enclosing_Context (New_Unit.all, The_Context.This); Set_Text_Name (New_Unit.all, Current_File (The_Context.all)); The_Context.Current_Unit := Compilation_Unit (New_Unit); return Result; end New_Compilation_Unit; ------------------------------ -- Library_Unit_Declaration -- ------------------------------ function Library_Unit_Declaration (Name : in Wide_String; The_Context : in Concrete_Context_Node) return Asis.Compilation_Unit is use Secondary_Unit_Lists; use type U.Unbounded_Wide_String; Decls : List_Node renames The_Context.Library_Unit_Declarations; Unit : Compilation_Unit; begin for I in 1 .. Length (Decls) loop Unit := Compilation_Unit (Get (Decls, I)); if XASIS.Utils.Are_Equal_Identifiers (Unit_Full_Name (Unit), Name) then return Unit; end if; end loop; return Nil_Compilation_Unit; end Library_Unit_Declaration; ------------------------------- -- Library_Unit_Declarations -- ------------------------------- function Library_Unit_Declarations (The_Context : in Concrete_Context_Node) return Asis.Compilation_Unit_List is begin return Secondary_Unit_Lists.To_Compilation_Unit_List (The_Context.Library_Unit_Declarations); end Library_Unit_Declarations; ------------------ -- Limited_View -- ------------------ function Limited_View (Name : in Wide_String; The_Context : in Concrete_Context_Node) return Asis.Compilation_Unit is use Secondary_Unit_Lists; use type U.Unbounded_Wide_String; Decls : List_Node renames The_Context.Limited_Views; Unit : Compilation_Unit; begin for I in 1 .. Length (Decls) loop Unit := Compilation_Unit (Get (Decls, I)); if XASIS.Utils.Are_Equal_Identifiers (Unit_Full_Name (Unit), Name) then return Unit; end if; end loop; return Nil_Compilation_Unit; end Limited_View; ------------------- -- Limited_Views -- ------------------- function Limited_Views (The_Context : in Concrete_Context_Node) return Asis.Compilation_Unit_List is begin return Secondary_Unit_Lists.To_Compilation_Unit_List (The_Context.Limited_Views); end Limited_Views; ---------- -- Open -- ---------- procedure Open (The_Context : in out Concrete_Context_Node) is begin Utils.Parse_Parameters (The_Context); Utils.Read_File_And_Supporters (The_Context); if The_Context.Error > Warning then Implementation.Set_Status (Asis.Errors.Environment_Error, "There are compilation errors"); raise Asis.Exceptions.ASIS_Failed; end if; The_Context.Is_Open := True; end Open; ---------------- -- Parameters -- ---------------- function Parameters (The_Context : Concrete_Context_Node) return Wide_String is begin return U.To_Wide_String (The_Context.Parameters); end Parameters; ------------------ -- Report_Error -- ------------------ procedure Report_Error (The_Context : in out Concrete_Context_Node; The_Unit : in Compilation_Unit := Asis.Nil_Compilation_Unit; Where : in Text_Position := Asis.Nil_Text_Position; Text : in Wide_String; Level : in Error_Level := Fatal) is function Get_File_Name return Wide_String is begin if Is_Nil (The_Unit) then return Current_File (The_Context); else return Text_Name (The_Unit.all); end if; end Get_File_Name; File_Name : constant Wide_String := Get_File_Name; Where_Img : constant Wide_String := To_Wide_String (Where); Message : constant Wide_String := File_Name & ":" & Where_Img & ": " & Text; begin Ada.Wide_Text_IO.Put_Line (Message); if The_Context.Error < Level then The_Context.Error := Level; if Level = Fatal then Implementation.Set_Status (Asis.Errors.Environment_Error, Message); raise Asis.Exceptions.ASIS_Failed; end if; end if; end Report_Error; --------------------------- -- Set_Check_Appropriate -- --------------------------- procedure Set_Check_Appropriate (The_Context : in out Concrete_Context_Node; Value : in Boolean) is begin The_Context.Check_Appropriate := Value; end Set_Check_Appropriate; -------------- -- Subunits -- -------------- function Subunits (Parent_Body : in Asis.Compilation_Unit; The_Context : in Concrete_Context_Node) return Asis.Compilation_Unit_List is begin Check_Same_Context (Parent_Body, The_Context, "Subunits"); return Subunits (Parent_Body); end Subunits; end Asis.Gela.Contexts; ------------------------------------------------------------------------------ -- 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 Prefix_Notation is type My_Type is tagged private; procedure Operator_Zero (X : My_Type); procedure Operator_One (X : My_Type; A : Integer); private type My_Type is tagged null record; procedure Operator_Zero (X : My_Type) is null; procedure Operator_One (X : My_Type; A : Integer) is null; end Prefix_Notation;
-- Lumen.Image.PPM -- Load and save netpbm's PPM image data -- -- Chip Richards, NiEstu, Phoenix AZ, Spring 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 Ada.Characters.Handling; with Ada.Characters.Latin_1; with Ada.Streams.Stream_IO; with Lumen.Binary.Endian.Shorts; package body Lumen.Image.PPM is --------------------------------------------------------------------------- function From_File (File : in Binary.IO.File_Type; PPM_Format : in Character) return Descriptor is ------------------------------------------------------------------------ Next : Character; Result : Descriptor; ------------------------------------------------------------------------ -- Return the next character from the input stream; used only when -- reading the header/metadata function Next_Char return Character is BS : constant Binary.Byte_String := Binary.IO.Read (File, 1); begin -- Next_Char return Character'Val (BS (1)); end Next_Char; ------------------------------------------------------------------------ -- Skip intervening whitespace and comments, and return the next -- character; used only when reading the header/metadata function Skip return Character is C : Character; begin -- Skip loop C := Next_Char; if C = '#' then -- works for DOS-style lines, too while C /= Ada.Characters.Latin_1.LF loop C := Next_Char; end loop ; -- only thing we're looking for elsif Ada.Characters.Handling.Is_Decimal_Digit (C) then return C ; end if ; end loop ; end Skip ; ------------------------------------------------------------------------ -- Read a nonnegative decimal integer from the stream, represented as -- Latin_1 digits; used when reading the header/metadata in all formats -- and the RGB values in the ASCII version of the format. function Read_Num (First : in Character) return Natural is Number : Natural := 0; C : Character; begin -- Read_Num C := First; loop Number := Number * 10 + (Character'Pos (C) - Character'Pos ('0')); C := Next_Char; if not Ada.Characters.Handling.Is_Decimal_Digit (C) then return Number; -- always discards trailing non-digit end if ; end loop; end Read_Num; ------------------------------------------------------------------------ -- Read a PBM ASCII (portable bitmap) file procedure Read_APBM is Col : Natural; Pix : Pixel; Value : Natural; begin -- Read_APBM -- Read the data a row at a time and unpack it into our internal format for Row in Result.Values'Range (1) loop Col := Result.Values'First (2); for Pixel in 1 .. Result.Width loop Next := Skip; Value := Read_Num (Next); if Value = 1 then Pix := Black_Pixel; else Pix := White_Pixel; end if; Result.Values (Row, Col) := Pix; Col := Col + 1; end loop; end loop; end Read_APBM; ------------------------------------------------------------------------ -- Read a PGM ASCII (portable greymap) file procedure Read_APGM is Col : Natural; Value : Natural; begin -- Read_APGM -- Read the data a row at a time and unpack it into our internal format for Row in Result.Values'Range (1) loop Col := Result.Values'First (2); for Pixel in 1 .. Result.Width loop Next := Skip; Value := Read_Num (Next); Result.Values (Row, Col).R := Binary.Byte (Value); Result.Values (Row, Col).G := Binary.Byte (Value); Result.Values (Row, Col).B := Binary.Byte (Value); -- PGMs don't have alpha, so use max Result.Values (Row, Col).A := Binary.Byte'Last; Col := Col + 1; end loop; end loop; end Read_APGM; ------------------------------------------------------------------------ -- Read a PPM ASCII (portable pixmap) file procedure Read_APPM is Col : Natural; function Read_Color return Binary.Byte is begin return Binary.Byte (Read_Num (Skip)); end Read_Color; begin -- Read_APPM -- Read the data a row at a time and unpack it into our internal format for Row in Result.Values'Range (1) loop Col := Result.Values'First (2); for Pixel in 1 .. Result.Width loop Result.Values (Row, Col).R := Read_Color; Result.Values (Row, Col).G := Read_Color; Result.Values (Row, Col).B := Read_Color; -- PPMs don't have alpha, so use max Result.Values (Row, Col).A := Binary.Byte'Last; Col := Col + 1; end loop; end loop; end Read_APPM; ------------------------------------------------------------------------ -- Read a PBM (portable bitmap) file procedure Read_PBM is use Binary; Row_Size : constant Natural := (Result.Width + Byte_LB) / Byte_Bits; Row_Buf : Byte_String (0 .. Row_Size - 1); Last : Natural; Col : Natural; Pix : Pixel; begin -- Read_PBM -- Read the data a row at a time and unpack it into our internal format for Row in Result.Values'Range (1) loop Binary.IO.Read (File, Row_Buf, Last); -- Move the image data into our output buffer a pixel at a time, -- expanding bitmap data to RGB and adding an alpha value to each Col := Result.Values'First (2); Buffer : for Row_Byte in Row_Buf'Range loop for Bits in 1 .. Byte_Bits loop -- Test top bit; 1 = black, 0 = white (yeah, that's right) if Row_Buf (Row_Byte) > Byte'Last / 2 then Pix := Black_Pixel; else Pix := White_Pixel; end if; Row_Buf (Row_Byte) := Row_Buf (Row_Byte) * 2; Result.Values (Row, Col) := Pix; Col := Col + 1; -- rest of buffer is don't-care bits exit Buffer when Col > Result.Values'Last (2); end loop; end loop Buffer; -- Check for early EOF if Last < Row_Size - 1 then Col := (Last + 1) * Byte_Bits; for Fill in Col .. Result.Values'Last (2) loop -- disappear missing columns in current row Result.Values (Row, Col) := Transparent_Pixel; end loop; -- Disappear missing rows, if any if Row < Result.Height - 1 then for Fill in Row + 1 .. Result.Values'Last (1) loop for Col in Result.Values'Range (2) loop Result.Values (Fill, Col) := Transparent_Pixel; end loop; end loop; end if; -- Signal truncated image, if the caller cares Result.Complete := False; exit; -- EOF ends the input process end if; end loop ; end Read_PBM; ------------------------------------------------------------------------ -- Read a PGM (portable greymap) file procedure Read_PGM is Maxval : Natural; begin -- Read_PGM -- Read the maxval Maxval := Read_Num (Skip); if Maxval > 65535 then raise Invalid_Format; elsif Maxval > 255 then -- Wide greymap pixels, 2 bytes each. Calculate the row size and -- create an environment in which that type exists. declare use Binary; package BS is new Endian.Shorts (Short); -- multiplier to maximize pixel value retention Mult : constant Short := Short'Last / Short (Maxval); -- divisor to convert shorts to bytes Div : constant := Short (Byte'Last) + 1; Row_Buf : Short_String (0 .. Result.Width - 1); Last : Natural; Grey : Byte; begin -- block to read 16-bit PGM data -- Read the data a row at a time and unpack it into our internal -- format for Row in Result.Values'Range (1) loop IO.Read (File, Row_Buf, Last); -- Move the image data into our output buffer a pixel at a -- time, trying to retain as much grey data as possible, -- expanding greymap data to RGB and adding an alpha value -- to each for Col in Result.Values'Range (2) loop Grey := Byte ((BS.To_Big (Row_Buf (Col)) * Mult) / Div); Result.Values (Row, Col).R := Grey; Result.Values (Row, Col).G := Grey; Result.Values (Row, Col).B := Grey; -- PGMs don't have alpha, so use max Result.Values (Row, Col).A := Byte'Last; end loop ; -- Check for early EOF if Last < Result.Width - 1 then for Col in Last + 1 .. Result.Values'Last (2) loop -- disappear missing columns in current row Result.Values (Row, Col) := Transparent_Pixel; end loop; -- Disappear missing rows, if any if Row < Result.Height - 1 then for Fill in Row + 1 .. Result.Values'Last (1) loop for Col in Result.Values'Range (2) loop Result.Values (Fill, Col) := Transparent_Pixel; end loop; end loop; end if; -- Signal truncated image, if the caller cares Result.Complete := False; exit; -- EOF ends the input process end if; end loop; end; else -- Regular greymap pixels, 1 byte each. Create the byte string to -- use as an input buffer. declare use type Binary.Byte; Row_Buf : Binary.Byte_String (0 .. Result.Width - 1); Last : Natural; Grey : Binary.Byte; begin -- block to read 8-bit PGM data -- Read the data a row at a time and unpack it into our internal -- format for Row in Result.Values'Range (1) loop Binary.IO.Read (File, Row_Buf, Last); -- Move the image data into our output buffer a pixel at a -- time, expanding greymap data to RGB and adding an alpha -- value to each for Col in Result.Values'Range (2) loop Grey := Row_Buf (Col); Result.Values (Row, Col).R := Grey; Result.Values (Row, Col).G := Grey; Result.Values (Row, Col).B := Grey; -- PGMs don't have alpha, so use max Result.Values (Row, Col).A := Binary.Byte'Last; end loop ; -- Check for early EOF if Last < Result.Width - 1 then for Col in Last + 1 .. Result.Values'Last (2) loop -- disappear missing columns in current row Result.Values (Row, Col) := Transparent_Pixel; end loop; -- Disappear missing rows, if any if Row < Result.Height - 1 then for Fill in Row + 1 .. Result.Values'Last (1) loop for Col in Result.Values'Range (2) loop Result.Values (Fill, Col) := Transparent_Pixel; end loop; end loop; end if; -- Signal truncated image, if the caller cares Result.Complete := False; exit; -- EOF ends the input process end if; end loop; end; end if; end Read_PGM; ------------------------------------------------------------------------ -- Read a PPM (portable pixmap) file procedure Read_PPM is Maxval : Natural; begin -- Read_PPM -- Read the maxval Maxval := Read_Num (Skip); if Maxval > 65535 then raise Invalid_Format; elsif Maxval > 255 then -- Wide pixels, 2 bytes per color value. Calculate the row size -- and create an environment in which that type exists. declare use Binary; package BS is new Endian.Shorts (Short); -- multiplier to maximize pixel value retention Mult : constant Short := Short'Last / Short (Maxval); -- divisor to convert shorts to bytes Div : constant := Short (Byte'Last) + 1; -- 3 color values per pixel Row_Size : constant Natural := Result.Width * 3; Row_Buf : Short_String (0 .. Row_Size - 1); Last : Natural; begin -- block to read 16-bit PPM data -- Read the data a row at a time and unpack it into our internal -- format for Row in Result.Values'Range (1) loop IO.Read (File, Row_Buf, Last); -- Move the image data into our output buffer a pixel at a -- time, trying to retain as much color data as possible, -- and adding an alpha value to each for Col in Result.Values'Range (2) loop Result.Values (Row, Col).R := Byte ((BS.To_Big (Row_Buf ((Col * 3) + 0)) * Mult) / Div); Result.Values (Row, Col).G := Byte ((BS.To_Big (Row_Buf ((Col * 3) + 1)) * Mult) / Div); Result.Values (Row, Col).B := Byte ((BS.To_Big (Row_Buf ((Col * 3) + 2)) * Mult) / Div); -- PPMs don't have alpha, so use max Result.Values (Row, Col).A := Byte'Last; end loop ; -- Check for early EOF if Last < Row_Size - 1 then for Col in (Last / 3) + 1 .. Result.Values'Last (2) loop -- disappear missing columns in current row Result.Values (Row, Col) := Transparent_Pixel; end loop; -- Disappear missing rows, if any if Row < Result.Height - 1 then for Fill in Row + 1 .. Result.Values'Last (1) loop for Col in Result.Values'Range (2) loop Result.Values (Fill, Col) := Transparent_Pixel; end loop; end loop; end if; -- Signal truncated image, if the caller cares Result.Complete := False; exit; -- EOF ends the input process end if; end loop; end; else -- Regular pixels, 1 byte per color value. Calculate the row size -- and create an environment in which that type exists. declare use type Binary.Byte; -- 3 color values per pixel Row_Size : constant Natural := Result.Width * 3; Row_Buf : Binary.Byte_String (0 .. Row_Size - 1); Last : Natural; begin -- block to read 8-bit PPM data -- Read the data a row at a time and unpack it into our internal -- format for Row in Result.Values'Range (1) loop Binary.IO.Read (File, Row_Buf, Last); -- Move the image data into our output buffer a pixel at a -- time, adding an alpha value to each for Col in Result.Values'Range (2) loop Result.Values (Row, Col).R := Row_Buf ((Col * 3) + 0); Result.Values (Row, Col).G := Row_Buf ((Col * 3) + 1); Result.Values (Row, Col).B := Row_Buf ((Col * 3) + 2); -- PPMs don't have alpha, so use max Result.Values (Row, Col).A := Binary.Byte'Last; end loop ; -- Check for early EOF if Last < Row_Size - 1 then for Col in (Last / 3) + 1 .. Result.Values'Last (2) loop -- disappear missing columns in current row Result.Values (Row, Col) := Transparent_Pixel; end loop; -- Disappear missing rows, if any if Row < Result.Height - 1 then for Fill in Row + 1 .. Result.Values'Last (1) loop for Col in Result.Values'Range (2) loop Result.Values (Fill, Col) := Transparent_Pixel; end loop; end loop; end if; -- Signal truncated image, if the caller cares Result.Complete := False; exit; -- EOF ends the input process end if; end loop; end; end if; end Read_PPM; ------------------------------------------------------------------------ begin -- From_File -- Reposition to actual start of metadata, after signature check Ada.Streams.Stream_IO.Set_Index (File, 3); -- Get image dimensions and allocate the image buffer Next := Skip; Result.Width := Read_Num (Next); Next := Skip; Result.Height := Read_Num (Next); Result.Values := new Pixel_Matrix (0 .. Result.Height - 1, 0 .. Result.Width - 1); Result.Complete := True; -- assume complete image unless we hit early EOF -- Based on format, read the rest of the data case PPM_Format is when '1' => Read_APBM; return Result; when '2' => Read_APGM; return Result; when '3' => Read_APPM; return Result; when '4' => Read_PBM; return Result; when '5' => Read_PGM; return Result; when '6' => Read_PPM; return Result; when others => raise Program_Error; -- shouldn't happen end case; end From_File; --------------------------------------------------------------------------- end Lumen.Image.PPM;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015, 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 STMicroelectronics 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. -- -- -- -- -- -- This file is based on: -- -- -- -- @file stm32f4xx_hal_i2c.c -- -- @author MCD Application Team -- -- @version V1.1.0 -- -- @date 19-June-2014 -- -- @brief I2C HAL module driver. -- -- -- -- COPYRIGHT(c) 2014 STMicroelectronics -- ------------------------------------------------------------------------------ with Ada.Real_Time; use Ada.Real_Time; with STM32_SVD.I2C; use STM32_SVD.I2C; with STM32.Device; use STM32.Device; package body STM32.I2C is use type HAL.I2C.I2C_Status; type I2C_Status_Flag is (Start_Bit, Address_Sent, Byte_Transfer_Finished, Address_Sent_10bit, Stop_Detection, Rx_Data_Register_Not_Empty, Tx_Data_Register_Empty, Bus_Error, Arbitration_Lost, Ack_Failure, UnderOverrun, Packet_Error, Timeout, SMB_Alert, Master_Slave_Mode, Busy, Transmitter_Receiver_Mode, General_Call, SMB_Default, SMB_Host, Dual_Flag); -- Low level flag handling function Flag_Status (This : I2C_Port; Flag : I2C_Status_Flag) return Boolean; procedure Clear_Address_Sent_Status (This : I2C_Port); -- Higher level flag handling procedure Wait_Flag (This : in out I2C_Port; Flag : I2C_Status_Flag; F_State : Boolean; Timeout : Natural; Status : out HAL.I2C.I2C_Status); procedure Wait_Master_Flag (This : in out I2C_Port; Flag : I2C_Status_Flag; Timeout : Natural; Status : out HAL.I2C.I2C_Status); procedure Master_Request_Write (This : in out I2C_Port; Addr : HAL.I2C.I2C_Address; Timeout : Natural; Status : out HAL.I2C.I2C_Status); procedure Master_Request_Read (This : in out I2C_Port; Addr : HAL.I2C.I2C_Address; Timeout : Natural; Status : out HAL.I2C.I2C_Status); procedure Mem_Request_Write (This : in out I2C_Port; Addr : HAL.I2C.I2C_Address; Mem_Addr : UInt16; Mem_Addr_Size : HAL.I2C.I2C_Memory_Address_Size; Timeout : Natural; Status : out HAL.I2C.I2C_Status); procedure Mem_Request_Read (This : in out I2C_Port; Addr : HAL.I2C.I2C_Address; Mem_Addr : UInt16; Mem_Addr_Size : HAL.I2C.I2C_Memory_Address_Size; Timeout : Natural; Status : out HAL.I2C.I2C_Status); --------------- -- Configure -- --------------- procedure Configure (This : in out I2C_Port; Conf : I2C_Configuration) is CR1 : CR1_Register; CCR : CCR_Register; OAR1 : OAR1_Register; PCLK1 : constant UInt32 := System_Clock_Frequencies.PCLK1; Freq_Range : constant UInt16 := UInt16 (PCLK1 / 1_000_000); begin if This.State /= Reset then return; end if; This.Config := Conf; -- Disable the I2C port if Freq_Range < 2 or else Freq_Range > 45 then raise Program_Error with "PCLK1 too high or too low: expected 2-45 MHz, current" & Freq_Range'Img & " MHz"; end if; Set_State (This, False); -- Load CR2 and clear FREQ This.Periph.CR2 := (LAST => False, DMAEN => False, ITBUFEN => False, ITEVTEN => False, ITERREN => False, FREQ => UInt6 (Freq_Range), others => <>); -- Set the port timing if Conf.Clock_Speed <= 100_000 then -- Mode selection to Standard Mode CCR.F_S := False; CCR.CCR := UInt12 (PCLK1 / (Conf.Clock_Speed * 2)); if CCR.CCR < 4 then CCR.CCR := 4; end if; This.Periph.TRISE.TRISE := UInt6 (Freq_Range + 1); else -- Fast mode CCR.F_S := True; if Conf.Duty_Cycle = DutyCycle_2 then CCR.CCR := UInt12 (PCLK1 / (Conf.Clock_Speed * 3)); else CCR.CCR := UInt12 (PCLK1 / (Conf.Clock_Speed * 25)); CCR.DUTY := True; end if; if CCR.CCR = 0 then CCR.CCR := 1; end if; This.Periph.TRISE.TRISE := UInt6 ((UInt32 (Freq_Range) * 300) / 1000 + 1); end if; This.Periph.CCR := CCR; -- CR1 configuration case Conf.Mode is when I2C_Mode => CR1.SMBUS := False; CR1.SMBTYPE := False; when SMBusDevice_Mode => CR1.SMBUS := True; CR1.SMBTYPE := False; when SMBusHost_Mode => CR1.SMBUS := True; CR1.SMBTYPE := True; end case; CR1.ENGC := Conf.General_Call_Enabled; CR1.NOSTRETCH := not Conf.Clock_Stretching_Enabled; This.Periph.CR1 := CR1; -- Address mode (slave mode) configuration OAR1.ADDMODE := Conf.Addressing_Mode = Addressing_Mode_10bit; case Conf.Addressing_Mode is when Addressing_Mode_7bit => OAR1.ADD0 := False; OAR1.ADD7 := UInt7 (Conf.Own_Address / 2); OAR1.ADD10 := 0; when Addressing_Mode_10bit => OAR1.ADD0 := (Conf.Own_Address and 2#1#) /= 0; OAR1.ADD7 := UInt7 ((Conf.Own_Address / 2) and 2#1111111#); OAR1.ADD10 := UInt2 (Conf.Own_Address / 2 ** 8); end case; This.Periph.OAR1 := OAR1; Set_State (This, True); This.State := Ready; end Configure; ----------------- -- Flag_Status -- ----------------- function Flag_Status (This : I2C_Port; Flag : I2C_Status_Flag) return Boolean is begin case Flag is when Start_Bit => return This.Periph.SR1.SB; when Address_Sent => return This.Periph.SR1.ADDR; when Byte_Transfer_Finished => return This.Periph.SR1.BTF; when Address_Sent_10bit => return This.Periph.SR1.ADD10; when Stop_Detection => return This.Periph.SR1.STOPF; when Rx_Data_Register_Not_Empty => return This.Periph.SR1.RxNE; when Tx_Data_Register_Empty => return This.Periph.SR1.TxE; when Bus_Error => return This.Periph.SR1.BERR; when Arbitration_Lost => return This.Periph.SR1.ARLO; when Ack_Failure => return This.Periph.SR1.AF; when UnderOverrun => return This.Periph.SR1.OVR; when Packet_Error => return This.Periph.SR1.PECERR; when Timeout => return This.Periph.SR1.TIMEOUT; when SMB_Alert => return This.Periph.SR1.SMBALERT; when Master_Slave_Mode => return This.Periph.SR2.MSL; when Busy => return This.Periph.SR2.BUSY; when Transmitter_Receiver_Mode => return This.Periph.SR2.TRA; when General_Call => return This.Periph.SR2.GENCALL; when SMB_Default => return This.Periph.SR2.SMBDEFAULT; when SMB_Host => return This.Periph.SR2.SMBHOST; when Dual_Flag => return This.Periph.SR2.DUALF; end case; end Flag_Status; -- ---------------- -- -- Clear_Flag -- -- ---------------- -- -- procedure Clear_Flag -- (Port : in out I2C_Port; -- Target : Clearable_I2C_Status_Flag) -- is -- Unref : Bit with Unreferenced; -- begin -- case Target is -- when Bus_Error => -- Port.SR1.BERR := 0; -- when Arbitration_Lost => -- Port.SR1.ARLO := 0; -- when Ack_Failure => -- Port.SR1.AF := 0; -- when UnderOverrun => -- Port.SR1.OVR := 0; -- when Packet_Error => -- Port.SR1.PECERR := 0; -- when Timeout => -- Port.SR1.TIMEOUT := 0; -- when SMB_Alert => -- Port.SR1.SMBALERT := 0; -- end case; -- end Clear_Flag; ------------------------------- -- Clear_Address_Sent_Status -- ------------------------------- procedure Clear_Address_Sent_Status (This : I2C_Port) is Unref : Boolean with Volatile, Unreferenced; begin -- ADDR is cleared after reading both SR1 and SR2 Unref := This.Periph.SR1.ADDR; Unref := This.Periph.SR2.MSL; end Clear_Address_Sent_Status; -- --------------------------------- -- -- Clear_Stop_Detection_Status -- -- --------------------------------- -- -- procedure Clear_Stop_Detection_Status (Port : in out I2C_Port) is -- Unref : Bit with Volatile, Unreferenced; -- begin -- Unref := Port.SR1.STOPF; -- Port.CR1.PE := True; -- end Clear_Stop_Detection_Status; --------------- -- Wait_Flag -- --------------- procedure Wait_Flag (This : in out I2C_Port; Flag : I2C_Status_Flag; F_State : Boolean; Timeout : Natural; Status : out HAL.I2C.I2C_Status) is Start : constant Time := Clock; begin while Flag_Status (This, Flag) = F_State loop if Clock - Start > Milliseconds (Timeout) then This.State := Ready; Status := HAL.I2C.Err_Timeout; return; end if; end loop; Status := HAL.I2C.Ok; end Wait_Flag; ---------------------- -- Wait_Master_Flag -- ---------------------- procedure Wait_Master_Flag (This : in out I2C_Port; Flag : I2C_Status_Flag; Timeout : Natural; Status : out HAL.I2C.I2C_Status) is Start : constant Time := Clock; begin while not Flag_Status (This, Flag) loop if This.Periph.SR1.AF then -- Generate STOP This.Periph.CR1.STOP := True; -- Clear the AF flag This.Periph.SR1.AF := False; This.State := Ready; Status := HAL.I2C.Err_Error; return; end if; if Clock - Start > Milliseconds (Timeout) then This.State := Ready; Status := HAL.I2C.Err_Timeout; return; end if; end loop; Status := HAL.I2C.Ok; end Wait_Master_Flag; -------------------------- -- Master_Request_Write -- -------------------------- procedure Master_Request_Write (This : in out I2C_Port; Addr : HAL.I2C.I2C_Address; Timeout : Natural; Status : out HAL.I2C.I2C_Status) is begin This.Periph.CR1.START := True; Wait_Flag (This, Start_Bit, False, Timeout, Status); if Status /= HAL.I2C.Ok then return; end if; if This.Config.Addressing_Mode = Addressing_Mode_7bit then This.Periph.DR.DR := UInt8 (Addr) and not 2#1#; else declare MSB : constant UInt8 := UInt8 (Shift_Right (UInt16 (Addr) and 16#300#, 7)); LSB : constant UInt8 := UInt8 (Addr and 16#FF#); begin -- We need to send 2#1111_MSB0# when MSB are the 3 most -- significant bits of the address This.Periph.DR.DR := MSB or 16#F0#; Wait_Master_Flag (This, Address_Sent_10bit, Timeout, Status); if Status /= HAL.I2C.Ok then return; end if; This.Periph.DR.DR := LSB; end; end if; Wait_Master_Flag (This, Address_Sent, Timeout, Status); end Master_Request_Write; -------------------------- -- Master_Request_Write -- -------------------------- procedure Master_Request_Read (This : in out I2C_Port; Addr : HAL.I2C.I2C_Address; Timeout : Natural; Status : out HAL.I2C.I2C_Status) is begin This.Periph.CR1.ACK := True; This.Periph.CR1.START := True; Wait_Flag (This, Start_Bit, False, Timeout, Status); if Status /= HAL.I2C.Ok then return; end if; if This.Config.Addressing_Mode = Addressing_Mode_7bit then This.Periph.DR.DR := UInt8 (Addr) or 2#1#; else declare MSB : constant UInt8 := UInt8 (Shift_Right (UInt16 (Addr) and 16#300#, 7)); LSB : constant UInt8 := UInt8 (Addr and 16#FF#); begin -- We need to write the address bit. So let's start with a -- write header -- We need to send 2#1111_MSB0# when MSB are the 3 most -- significant bits of the address This.Periph.DR.DR := MSB or 16#F0#; Wait_Master_Flag (This, Address_Sent_10bit, Timeout, Status); if Status /= HAL.I2C.Ok then return; end if; This.Periph.DR.DR := LSB; Wait_Master_Flag (This, Address_Sent, Timeout, Status); if Status /= HAL.I2C.Ok then return; end if; Clear_Address_Sent_Status (This); -- Generate a re-start This.Periph.CR1.START := True; Wait_Flag (This, Start_Bit, False, Timeout, Status); if Status /= HAL.I2C.Ok then return; end if; -- resend the MSB with the read bit set. This.Periph.DR.DR := MSB or 16#F1#; end; end if; Wait_Master_Flag (This, Address_Sent, Timeout, Status); end Master_Request_Read; ----------------------- -- Mem_Request_Write -- ----------------------- procedure Mem_Request_Write (This : in out I2C_Port; Addr : HAL.I2C.I2C_Address; Mem_Addr : UInt16; Mem_Addr_Size : HAL.I2C.I2C_Memory_Address_Size; Timeout : Natural; Status : out HAL.I2C.I2C_Status) is begin This.Periph.CR1.START := True; Wait_Flag (This, Start_Bit, False, Timeout, Status); if Status /= HAL.I2C.Ok then return; end if; -- Send slave address This.Periph.DR.DR := UInt8 (Addr) and not 2#1#; Wait_Master_Flag (This, Address_Sent, Timeout, Status); if Status /= HAL.I2C.Ok then return; end if; Clear_Address_Sent_Status (This); -- Wait until TXE flag is set Wait_Flag (This, Tx_Data_Register_Empty, False, Timeout, Status); if Status /= HAL.I2C.Ok then return; end if; case Mem_Addr_Size is when HAL.I2C.Memory_Size_8b => This.Periph.DR.DR := UInt8 (Mem_Addr); when HAL.I2C.Memory_Size_16b => This.Periph.DR.DR := UInt8 (Shift_Right (Mem_Addr, 8)); Wait_Flag (This, Tx_Data_Register_Empty, False, Timeout, Status); if Status /= HAL.I2C.Ok then return; end if; This.Periph.DR.DR := UInt8 (Mem_Addr and 16#FF#); end case; -- Wait until TXE flag is set Wait_Flag (This, Tx_Data_Register_Empty, False, Timeout, Status); end Mem_Request_Write; ---------------------- -- Mem_Request_Read -- ---------------------- procedure Mem_Request_Read (This : in out I2C_Port; Addr : HAL.I2C.I2C_Address; Mem_Addr : UInt16; Mem_Addr_Size : HAL.I2C.I2C_Memory_Address_Size; Timeout : Natural; Status : out HAL.I2C.I2C_Status) is begin This.Periph.CR1.ACK := True; This.Periph.CR1.START := True; Wait_Flag (This, Start_Bit, False, Timeout, Status); if Status /= HAL.I2C.Ok then return; end if; -- Send slave address in write mode This.Periph.DR.DR := UInt8 (Addr) and not 16#1#; Wait_Master_Flag (This, Address_Sent, Timeout, Status); if Status /= HAL.I2C.Ok then return; end if; Clear_Address_Sent_Status (This); -- Wait until TXE flag is set Wait_Flag (This, Tx_Data_Register_Empty, False, Timeout, Status); if Status /= HAL.I2C.Ok then return; end if; case Mem_Addr_Size is when HAL.I2C.Memory_Size_8b => This.Periph.DR.DR := UInt8 (Mem_Addr); when HAL.I2C.Memory_Size_16b => This.Periph.DR.DR := UInt8 (Shift_Right (Mem_Addr, 8)); Wait_Flag (This, Tx_Data_Register_Empty, False, Timeout, Status); if Status /= HAL.I2C.Ok then return; end if; This.Periph.DR.DR := UInt8 (Mem_Addr and 16#FF#); end case; -- Wait until TXE flag is set Wait_Flag (This, Tx_Data_Register_Empty, False, Timeout, Status); if Status /= HAL.I2C.Ok then return; end if; -- We now need to reset and send the slave address in read mode This.Periph.CR1.START := True; Wait_Flag (This, Start_Bit, False, Timeout, Status); if Status /= HAL.I2C.Ok then return; end if; -- Send slave address in read mode This.Periph.DR.DR := UInt8 (Addr) or 16#1#; Wait_Master_Flag (This, Address_Sent, Timeout, Status); end Mem_Request_Read; --------------------- -- Master_Transmit -- --------------------- overriding procedure Master_Transmit (This : in out I2C_Port; Addr : HAL.I2C.I2C_Address; Data : HAL.I2C.I2C_Data; Status : out HAL.I2C.I2C_Status; Timeout : Natural := 1000) is Idx : Natural := Data'First; begin if This.State = Reset then Status := HAL.I2C.Err_Error; return; elsif Data'Length = 0 then Status := HAL.I2C.Err_Error; return; end if; Wait_Flag (This, Busy, True, Timeout, Status); if Status /= HAL.I2C.Ok then Status := HAL.I2C.Busy; return; end if; if This.State /= Ready then Status := HAL.I2C.Busy; return; end if; This.State := Master_Busy_Tx; This.Periph.CR1.POS := False; Master_Request_Write (This, Addr, Timeout, Status); if Status /= HAL.I2C.Ok then return; end if; Clear_Address_Sent_Status (This); while Idx <= Data'Last loop Wait_Flag (This, Tx_Data_Register_Empty, False, Timeout, Status); if Status /= HAL.I2C.Ok then return; end if; This.Periph.DR.DR := Data (Idx); Idx := Idx + 1; if Flag_Status (This, Byte_Transfer_Finished) and then Idx <= Data'Last and then Status = HAL.I2C.Ok then This.Periph.DR.DR := Data (Idx); Idx := Idx + 1; end if; end loop; Wait_Flag (This, Tx_Data_Register_Empty, False, Timeout, Status); if Status /= HAL.I2C.Ok then return; end if; -- Generate STOP This.Periph.CR1.STOP := True; This.State := Ready; end Master_Transmit; -------------------- -- Master_Receive -- -------------------- overriding procedure Master_Receive (This : in out I2C_Port; Addr : HAL.I2C.I2C_Address; Data : out HAL.I2C.I2C_Data; Status : out HAL.I2C.I2C_Status; Timeout : Natural := 1000) is Idx : Natural := Data'First; begin if This.State = Reset then Status := HAL.I2C.Err_Error; return; elsif Data'Length = 0 then Status := HAL.I2C.Err_Error; return; end if; Wait_Flag (This, Busy, True, Timeout, Status); if Status /= HAL.I2C.Ok then Status := HAL.I2C.Busy; return; end if; if This.State /= Ready then Status := HAL.I2C.Busy; return; end if; This.State := Master_Busy_Rx; This.Periph.CR1.POS := False; Master_Request_Read (This, Addr, Timeout, Status); if Status /= HAL.I2C.Ok then return; end if; if Data'Length = 1 then -- Disable acknowledge This.Periph.CR1.ACK := False; Clear_Address_Sent_Status (This); This.Periph.CR1.STOP := True; elsif Data'Length = 2 then -- Disable acknowledge This.Periph.CR1.ACK := False; This.Periph.CR1.POS := True; Clear_Address_Sent_Status (This); else -- Automatic acknowledge This.Periph.CR1.ACK := True; Clear_Address_Sent_Status (This); end if; while Idx <= Data'Last loop if Idx = Data'Last then -- One UInt8 to read Wait_Flag (This, Rx_Data_Register_Not_Empty, False, Timeout, Status); if Status /= HAL.I2C.Ok then return; end if; Data (Idx) := This.Periph.DR.DR; Idx := Idx + 1; elsif Idx + 1 = Data'Last then -- Two bytes to read This.Periph.CR1.ACK := False; Wait_Flag (This, Byte_Transfer_Finished, False, Timeout, Status); if Status /= HAL.I2C.Ok then return; end if; This.Periph.CR1.STOP := True; -- read the data from DR Data (Idx) := This.Periph.DR.DR; Idx := Idx + 1; Data (Idx) := This.Periph.DR.DR; Idx := Idx + 1; elsif Idx + 2 = Data'Last then -- Three bytes to read Wait_Flag (This, Byte_Transfer_Finished, False, Timeout, Status); if Status /= HAL.I2C.Ok then return; end if; This.Periph.CR1.ACK := False; -- read the data from DR Data (Idx) := This.Periph.DR.DR; Idx := Idx + 1; Wait_Flag (This, Byte_Transfer_Finished, False, Timeout, Status); if Status /= HAL.I2C.Ok then return; end if; This.Periph.CR1.STOP := True; -- read the data from DR Data (Idx) := This.Periph.DR.DR; Idx := Idx + 1; Data (Idx) := This.Periph.DR.DR; Idx := Idx + 1; else -- One byte to read Wait_Flag (This, Rx_Data_Register_Not_Empty, False, Timeout, Status); if Status /= HAL.I2C.Ok then return; end if; Data (Idx) := This.Periph.DR.DR; Idx := Idx + 1; Wait_Flag (This, Byte_Transfer_Finished, False, Timeout, Status); if Status = HAL.I2C.Ok then Data (Idx) := This.Periph.DR.DR; Idx := Idx + 1; end if; end if; end loop; This.State := Ready; end Master_Receive; --------------- -- Mem_Write -- --------------- overriding procedure Mem_Write (This : in out I2C_Port; Addr : HAL.I2C.I2C_Address; Mem_Addr : UInt16; Mem_Addr_Size : HAL.I2C.I2C_Memory_Address_Size; Data : HAL.I2C.I2C_Data; Status : out HAL.I2C.I2C_Status; Timeout : Natural := 1000) is Idx : Natural := Data'First; begin if This.State = Reset then Status := HAL.I2C.Err_Error; return; elsif Data'Length = 0 then Status := HAL.I2C.Err_Error; return; end if; Wait_Flag (This, Busy, True, Timeout, Status); if Status /= HAL.I2C.Ok then Status := HAL.I2C.Busy; return; end if; if This.State /= Ready then Status := HAL.I2C.Busy; return; end if; This.State := Mem_Busy_Tx; This.Periph.CR1.POS := False; Mem_Request_Write (This, Addr, Mem_Addr, Mem_Addr_Size, Timeout, Status); if Status /= HAL.I2C.Ok then return; end if; while Idx <= Data'Last loop Wait_Flag (This, Tx_Data_Register_Empty, False, Timeout, Status); if Status /= HAL.I2C.Ok then return; end if; This.Periph.DR.DR := Data (Idx); Idx := Idx + 1; if Flag_Status (This, Byte_Transfer_Finished) and then Idx <= Data'Last and then Status = HAL.I2C.Ok then This.Periph.DR.DR := Data (Idx); Idx := Idx + 1; end if; end loop; Wait_Flag (This, Tx_Data_Register_Empty, False, Timeout, Status); if Status /= HAL.I2C.Ok then return; end if; -- Generate STOP This.Periph.CR1.STOP := True; This.State := Ready; end Mem_Write; -------------- -- Mem_Read -- -------------- overriding procedure Mem_Read (This : in out I2C_Port; Addr : HAL.I2C.I2C_Address; Mem_Addr : UInt16; Mem_Addr_Size : HAL.I2C.I2C_Memory_Address_Size; Data : out HAL.I2C.I2C_Data; Status : out HAL.I2C.I2C_Status; Timeout : Natural := 1000) is Idx : Natural := Data'First; begin if This.State = Reset then Status := HAL.I2C.Err_Error; return; elsif Data'Length = 0 then Status := HAL.I2C.Err_Error; return; end if; Wait_Flag (This, Busy, True, Timeout, Status); if Status /= HAL.I2C.Ok then Status := HAL.I2C.Busy; return; end if; if This.State /= Ready then Status := HAL.I2C.Busy; return; end if; This.State := Mem_Busy_Rx; This.Periph.CR1.POS := False; Mem_Request_Read (This, Addr, Mem_Addr, Mem_Addr_Size, Timeout, Status); if Status /= HAL.I2C.Ok then return; end if; if Data'Length = 1 then This.Periph.CR1.ACK := False; Clear_Address_Sent_Status (This); This.Periph.CR1.STOP := True; elsif Data'Length = 2 then This.Periph.CR1.ACK := False; This.Periph.CR1.POS := True; Clear_Address_Sent_Status (This); else -- Automatic acknowledge This.Periph.CR1.ACK := True; Clear_Address_Sent_Status (This); end if; while Idx <= Data'Last loop if Idx = Data'Last then -- One byte to read Wait_Flag (This, Rx_Data_Register_Not_Empty, False, Timeout, Status); if Status /= HAL.I2C.Ok then return; end if; Data (Idx) := This.Periph.DR.DR; Idx := Idx + 1; elsif Idx + 1 = Data'Last then -- Two bytes to read This.Periph.CR1.ACK := False; Wait_Flag (This, Byte_Transfer_Finished, False, Timeout, Status); if Status /= HAL.I2C.Ok then return; end if; This.Periph.CR1.STOP := True; -- read the data from DR Data (Idx) := This.Periph.DR.DR; Idx := Idx + 1; Data (Idx) := This.Periph.DR.DR; Idx := Idx + 1; elsif Idx + 2 = Data'Last then -- Three bytes to read Wait_Flag (This, Byte_Transfer_Finished, False, Timeout, Status); if Status /= HAL.I2C.Ok then return; end if; This.Periph.CR1.ACK := False; -- read the data from DR Data (Idx) := This.Periph.DR.DR; Idx := Idx + 1; Wait_Flag (This, Byte_Transfer_Finished, False, Timeout, Status); if Status /= HAL.I2C.Ok then return; end if; This.Periph.CR1.STOP := True; -- read the data from DR Data (Idx) := This.Periph.DR.DR; Idx := Idx + 1; Data (Idx) := This.Periph.DR.DR; Idx := Idx + 1; else -- One byte to read Wait_Flag (This, Rx_Data_Register_Not_Empty, False, Timeout, Status); if Status /= HAL.I2C.Ok then return; end if; Data (Idx) := This.Periph.DR.DR; Idx := Idx + 1; Wait_Flag (This, Byte_Transfer_Finished, False, Timeout, Status); if Status = HAL.I2C.Ok then Data (Idx) := This.Periph.DR.DR; Idx := Idx + 1; end if; end if; end loop; This.State := Ready; end Mem_Read; --------------- -- Set_State -- --------------- procedure Set_State (This : in out I2C_Port; Enabled : Boolean) is begin This.Periph.CR1.PE := Enabled; end Set_State; ------------------ -- Port_Enabled -- ------------------ function Port_Enabled (This : I2C_Port) return Boolean is begin return This.Periph.CR1.PE; end Port_Enabled; ---------------------- -- Enable_Interrupt -- ---------------------- procedure Enable_Interrupt (This : in out I2C_Port; Source : I2C_Interrupt) is begin case Source is when Error_Interrupt => This.Periph.CR2.ITERREN := True; when Event_Interrupt => This.Periph.CR2.ITEVTEN := True; when Buffer_Interrupt => This.Periph.CR2.ITBUFEN := True; end case; end Enable_Interrupt; ----------------------- -- Disable_Interrupt -- ----------------------- procedure Disable_Interrupt (This : in out I2C_Port; Source : I2C_Interrupt) is begin case Source is when Error_Interrupt => This.Periph.CR2.ITERREN := False; when Event_Interrupt => This.Periph.CR2.ITEVTEN := False; when Buffer_Interrupt => This.Periph.CR2.ITBUFEN := False; end case; end Disable_Interrupt; ------------- -- Enabled -- ------------- function Enabled (This : I2C_Port; Source : I2C_Interrupt) return Boolean is begin case Source is when Error_Interrupt => return This.Periph.CR2.ITERREN; when Event_Interrupt => return This.Periph.CR2.ITEVTEN; when Buffer_Interrupt => return This.Periph.CR2.ITBUFEN; end case; end Enabled; end STM32.I2C;
with GMP.Random; with Ada.Text_IO; procedure random is Gen : aliased GMP.Random.Generator; begin Ada.Text_IO.Put_Line (Long_Integer'Image (GMP.Random.Random (Gen))); Ada.Text_IO.Put_Line (Long_Integer'Image (GMP.Random.Random (Gen))); Ada.Text_IO.Put_Line (Long_Integer'Image (GMP.Random.Random (Gen))); end random;
-- with EU_Projects.Nodes.Action_Nodes.WPs; -- with EU_Projects.Nodes.Action_Nodes.Tasks; -- with EU_Projects.Nodes.Timed_Nodes.Deliverables; -- with EU_Projects.Nodes.Timed_Nodes.Milestones; -- with Ada.Tags; -- with EU_Projects.Nodes.Partners; package body EU_Projects.Nodes is ----------- -- After -- ----------- function After (Labels : Node_Label_Lists.Vector; Done_Var : String) return String is Tmp : Unbounded_String := Null_Unbounded_String; --To_Unbounded_String ("max("); begin if Labels.Is_Empty then if Tmp = Null_Unbounded_String then raise Bad_Input with "End time '*' with no parent"; end if; end if; for El of Labels loop if Tmp /= Null_Unbounded_String then Tmp := Tmp & ","; end if; Tmp := Tmp & To_String (El) & "." & Done_Var; end loop; return To_String ("max(" & Tmp & ")"); end After; function Join (List : Node_Label_Lists.Vector; Separator : String) return String is Result : Unbounded_String; begin for idx in List.Iterate loop Result := Result & Image (List (Idx)); if Node_Label_Lists.To_Index (Idx) < List.Last_Index then Result := Result & Separator; end if; end loop; return To_String (Result); end Join; -------------- -- Is_Fixed -- -------------- function Is_Fixed (Item : Node_Type; Var : Simple_Identifier) return Boolean is begin raise Unknown_Instant_Var; return False; end Is_Fixed; ----------------- -- Fix_Instant -- ----------------- procedure Fix_Instant (Item : in out Node_Type; Var : Simple_Identifier; Value : Times.Instant) is begin raise Unknown_Instant_Var with "Bad call to Fix_Instant"; end Fix_Instant; -- ------------------ -- -- Fix_Duration -- -- ------------------ -- -- procedure Fix_Duration -- (Item : in out Node_Type; -- Var : Simple_Identifier; -- Value : Times.Duration) -- is -- begin -- raise Unknown_Duration_Var with "Bad call to Fix_Duration"; -- end Fix_Duration; -- function Create (Label : Identifiers.Identifier; -- Name : String; -- Short_Name : String; -- Description : String; -- Index : Node_Index := No_Index) -- return Node_Type -- is -- use Ada.Finalization; -- begin -- return Node_Type'(Controlled with -- Label => Label, -- Name => To_Unbounded_String (Name), -- Short_Name => To_Unbounded_String (Short_Name), -- Index => Index, -- Description => To_Unbounded_String (Description), -- Attributes => Attribute_Maps.Empty_Map); -- end Create; ------------------- -- Add_Attribute -- ------------------- procedure Add_Attribute (Item : in out Node_Type; Name : in String; Value : in String) is begin Item.Attributes.Include (Key => Name, New_Item => Value); end Add_Attribute; ---------------------- -- Parse_Label_List -- ---------------------- function Parse_Label_List (Input : String) return Node_Label_Lists.Vector is Result : Node_Label_Lists.Vector; begin for ID of To_ID_List (Input) loop Result.Append (Node_Label (ID)); end loop; return Result; end Parse_Label_List; end EU_Projects.Nodes; -- -- --------------- -- -- Set_Index -- -- --------------- -- -- procedure Set_Index (Item : in out Node_Type; -- Idx : Node_Index) -- is -- begin -- if Item.Index /= No_Index then -- raise Constraint_Error; -- end if; -- -- Item.Index := Idx; -- end Set_Index; -- -- ---------- -- -- Is_A -- -- ---------- -- -- function Is_A (Item : Node_Type'Class; -- Class : Node_Class) -- return Boolean -- is -- use type Ada.Tags.Tag; -- Tags : constant array (Node_Class) of Ada.Tags.Tag := -- ( -- A_WP => Action_Nodes.WPs.Project_WP'Tag, -- A_Task => Action_Nodes.Tasks.Project_Task'Tag, -- A_Deliverable => Timed_Nodes.Deliverables.Deliverable'Tag, -- A_Milestone => Timed_Nodes.Milestones.Milestone'Tag, -- A_Partner => Nodes.Partners.Partner'Tag -- ); -- begin -- return Item'Tag = Tags (Class); -- end Is_A;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- Copyright (C) 2012-2016, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Ada.Unchecked_Conversion; with System.BB.Parameters; with Interfaces; use Interfaces; with Interfaces.STM32; use Interfaces.STM32; with Interfaces.STM32.RCC; use Interfaces.STM32.RCC; package body System.STM32 is package Param renames System.BB.Parameters; HPRE_Presc_Table : constant array (AHB_Prescaler_Enum) of UInt32 := (2, 4, 8, 16, 64, 128, 256, 512); PPRE_Presc_Table : constant array (APB_Prescaler_Enum) of UInt32 := (2, 4, 8, 16); ------------------- -- System_Clocks -- ------------------- function System_Clocks return RCC_System_Clocks is Source : constant SYSCLK_Source := SYSCLK_Source'Val (RCC_Periph.CFGR.SWS); Result : RCC_System_Clocks; begin -- System clock Mux case Source is -- HSE as source when SYSCLK_SRC_HSE => Result.SYSCLK := Param.HSE_Clock; -- HSI as source when SYSCLK_SRC_HSI => Result.SYSCLK := Param.HSI_Clock / (2 ** Natural (RCC_Periph.CR.HSIDIV)); -- HSE as source when SYSCLK_SRC_CSI => Result.SYSCLK := Param.CSI_Clock; -- PLL1 as source when SYSCLK_SRC_PLL => declare Pllm : constant UInt32 := UInt32 (RCC_Periph.PLLCKSELR.DIVM1); -- Get the correct value of Pll M divisor Plln : constant UInt32 := UInt32 (RCC_Periph.PLL1DIVR.DIVN1 + 1); -- Get the correct value of Pll N multiplier Pllp : constant UInt32 := UInt32 (RCC_Periph.PLL1DIVR.DIVR1 + 1); -- Get the correct value of Pll R divisor PLLSRC : constant PLL_Source := PLL_Source'Val (RCC_Periph.PLLCKSELR.PLLSRC); -- Get PLL Source Mux PLLCLK : UInt32; begin case PLLSRC is when PLL_SRC_HSE => -- HSE as source PLLCLK := ((Param.HSE_Clock / Pllm) * Plln) / Pllp; when PLL_SRC_HSI => -- HSI as source PLLCLK := ((Param.HSI_Clock / Pllm) * Plln) / Pllp; when PLL_SRC_CSI => -- CSI as source PLLCLK := ((Param.CSI_Clock / Pllm) * Plln) / Pllp; end case; Result.SYSCLK := PLLCLK; end; end case; declare function To_AHBP is new Ada.Unchecked_Conversion (UInt4, AHB_Prescaler); function To_APBP is new Ada.Unchecked_Conversion (UInt3, APB_Prescaler); -- Get value of AHB1_PRE (D1CPRE prescaler) HPRE1 : constant AHB_Prescaler := To_AHBP (RCC_Periph.D1CFGR.D1CPRE); HPRE1_Div : constant UInt32 := (if HPRE1.Enabled then HPRE_Presc_Table (HPRE1.Value) else 1); -- Get the value of AHB2_PRE (HPRE prescaler) HPRE2 : constant AHB_Prescaler := To_AHBP (RCC_Periph.D1CFGR.HPRE); HPRE2_Div : constant UInt32 := (if HPRE2.Enabled then HPRE_Presc_Table (HPRE2.Value) else 1); -- Get the value of APB1_PRE (D2PPRE1 prescaler) PPRE1 : constant APB_Prescaler := To_APBP (RCC_Periph.D2CFGR.D2PPRE1); PPRE1_Div : constant UInt32 := (if PPRE1.Enabled then PPRE_Presc_Table (PPRE1.Value) else 1); -- Get the value of APB2_PRE (D2PPRE2 prescaler) PPRE2 : constant APB_Prescaler := To_APBP (RCC_Periph.D2CFGR.D2PPRE2); PPRE2_Div : constant UInt32 := (if PPRE2.Enabled then PPRE_Presc_Table (PPRE2.Value) else 1); -- Get the value of APB3_PRE (D1PPRE prescaler) PPRE3 : constant APB_Prescaler := To_APBP (RCC_Periph.D1CFGR.D1PPRE); PPRE3_Div : constant UInt32 := (if PPRE3.Enabled then PPRE_Presc_Table (PPRE3.Value) else 1); -- Get the value of APB4_PRE (D3PPRE prescaler) PPRE4 : constant APB_Prescaler := To_APBP (RCC_Periph.D3CFGR.D3PPRE); PPRE4_Div : constant UInt32 := (if PPRE4.Enabled then PPRE_Presc_Table (PPRE4.Value) else 1); begin Result.HCLK1 := Result.SYSCLK / HPRE1_Div; Result.HCLK2 := Result.HCLK1 / HPRE2_Div; Result.PCLK1 := Result.HCLK2 / PPRE1_Div; Result.PCLK2 := Result.HCLK2 / PPRE2_Div; Result.PCLK3 := Result.HCLK2 / PPRE3_Div; Result.PCLK4 := Result.HCLK2 / PPRE4_Div; -- Timer clocks -- If APB1 (D2PPRE1) and APB2 (D2PPRE2) prescaler (D2PPRE1, D2PPRE2 -- in the RCC_D2CFGR register) are configured to a division factor of -- 1 or 2 with RCC_CFGR.TIMPRE = 0 (or also 4 with RCC_CFGR.TIMPRE -- = 1), then TIMxCLK = PCLKx. -- Otherwise, the timer clock frequencies are set to twice to the -- frequency of the APB domain to which the timers are connected with -- RCC_CFGR.TIMPRE = 0, so TIMxCLK = 2 x PCLKx (or TIMxCLK = -- 4 x PCLKx with RCC_CFGR.TIMPRE = 1). case RCC_Periph.CFGR.TIMPRE is when 0 => -- TIMs 2 .. 7, 12 .. 14 if PPRE1_Div <= 2 then Result.TIMCLK1 := Result.PCLK1; else Result.TIMCLK1 := Result.PCLK1 * 2; end if; -- TIMs TIMs 1, 8, 15 .. 17 if PPRE2_Div <= 2 then Result.TIMCLK2 := Result.PCLK2; else Result.TIMCLK2 := Result.PCLK2 * 2; end if; when 1 => -- TIMs 2 .. 7, 12 .. 14 if PPRE1_Div <= 4 then Result.TIMCLK1 := Result.PCLK1; else Result.TIMCLK1 := Result.PCLK1 * 4; end if; -- TIMs 1, 8, 15 .. 17 if PPRE2_Div <= 4 then Result.TIMCLK2 := Result.PCLK2; else Result.TIMCLK2 := Result.PCLK2 * 4; end if; end case; -- HRTIM clock -- If RCC_CFGR.HRTIMSEL = 0, HRTIM prescaler clock cource is the same -- as timer 2 (TIMCLK1), otherwise it is the CPU clock (HCLK2). case RCC_Periph.CFGR.HRTIMSEL is when 0 => Result.TIMCLK3 := Result.TIMCLK1; when 1 => Result.TIMCLK3 := Result.HCLK1; end case; end; return Result; end System_Clocks; end System.STM32;
-- C46024A.ADA -- Grant of Unlimited Rights -- -- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687, -- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained -- unlimited rights in the software and documentation contained herein. -- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making -- this public release, the Government intends to confer upon all -- recipients unlimited rights equal to those held by the Government. -- These rights include rights to use, duplicate, release or disclose the -- released technical data and computer software in whole or in part, in -- any manner and for any purpose whatsoever, and to have or permit others -- to do so. -- -- DISCLAIMER -- -- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR -- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED -- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE -- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE -- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A -- PARTICULAR PURPOSE OF SAID MATERIAL. --* -- OBJECTIVE: -- CHECK FLOATING POINT CONVERSIONS WHEN THE TARGET TYPE IS A -- FIXED POINT TYPE, FOR DIGITS 5. -- HISTORY: -- JET 02/19/88 CREATED ORIGINAL TEST. WITH REPORT; USE REPORT; PROCEDURE C46024A IS TYPE FLOAT5 IS DIGITS 5; TYPE FIX1 IS DELTA 2#0.01# RANGE -16#20.0# .. 16#20.0#; TYPE FIX2 IS DELTA 2#0.0001# RANGE -16#80.0# .. 16#80.0#; TYPE FIX3 IS DELTA 2#0.000001# RANGE -16#200.0# .. 16#200.0#; F5, F5A, F5B : FLOAT5; GENERIC TYPE F IS DELTA <>; FUNCTION IDENTG (A : F) RETURN F; FUNCTION IDENTG (A : F) RETURN F IS BEGIN RETURN A + F(IDENT_INT(0)); END IDENTG; FUNCTION IDENT1 IS NEW IDENTG(FIX1); FUNCTION IDENT2 IS NEW IDENTG(FIX2); FUNCTION IDENT3 IS NEW IDENTG(FIX3); BEGIN TEST ("C46024A", "CHECK FLOATING POINT CONVERSIONS WHEN THE " & "TARGET TYPE IS A FIXED POINT TYPE, FOR " & "5-DIGIT PRECISION"); IF FIX1(FLOAT5'(2#0.1000_0000_0000_0000_00#E-1)) /= IDENT1(2#0.01#) THEN FAILED ("INCORRECT RESULT FROM CONVERSION (1)"); END IF; IF FIX1(FLOAT5'(-2#0.1111_1110_0000_0000_00#E5)) /= IDENT1(-2#1_1111.11#) THEN FAILED ("INCORRECT RESULT FROM CONVERSION (2)"); END IF; IF FIX1(FLOAT5'(-2#0.1010_0111_1111_1111_11#E4)) < IDENT1(-2#1010.10#) OR FIX1(FLOAT5'(-2#0.1010_0111_1111_1111_11#E4)) > IDENT1(-2#1010.01#) THEN FAILED ("INCORRECT RESULT FROM CONVERSION (3)"); END IF; IF FIX2(FLOAT5'(-2#0.1000_0000_0000_0000_00#E-3)) /= IDENT2(-2#0.0001#) THEN FAILED ("INCORRECT RESULT FROM CONVERSION (4)"); END IF; IF FIX2(FLOAT5'(2#0.1111_1111_1110_0000_00#E7)) /= IDENT2(2#111_1111.1111#) THEN FAILED ("INCORRECT RESULT FROM CONVERSION (5)"); END IF; F5 := 2#0.1010_1010_1010_1010_10#E5; IF FIX2(F5) < IDENT2(2#1_0101.0101#) OR FIX2(F5) > IDENT2(2#1_0101.0110#) THEN FAILED ("INCORRECT RESULT FROM CONVERSION (6)"); END IF; IF FIX3(FLOAT5'(2#0.1000_0000_0000_0000_00#E-5)) /= IDENT3(2#0.000001#) THEN FAILED ("INCORRECT RESULT FROM CONVERSION (7)"); END IF; IF FIX3(FLOAT5'(-2#0.1111_1111_1111_1110_00#E9)) /= IDENT3(-2#1_1111_1111.1111_11#) THEN FAILED ("INCORRECT RESULT FROM CONVERSION (8)"); END IF; F5 := -2#0.1010_1010_1010_1010_10#E8; IF FIX3(F5) < IDENT3(-2#1010_1010.1010_11#) OR FIX3(F5) > IDENT3(-2#1010_1010.1010_10#) THEN FAILED ("INCORRECT RESULT FROM CONVERSION (9)"); END IF; F5A := 2#0.1010_1010_1010_1010_10#E4; F5B := 2#0.1010_1010_1010_1010_10#E5; IF FIX1(F5A) = IDENT1(2#1010.11#) AND FIX1(-F5A) = IDENT1(-2#1010.11#) AND FIX1(F5B) = IDENT1(2#1_0101.01#) AND FIX1(-F5B) = IDENT1(-2#1_0101.01#) THEN COMMENT ("CONVERSION ROUNDS TO NEAREST"); ELSIF FIX1(F5A) = IDENT1(2#1010.10#) AND FIX1(-F5B) = IDENT1(-2#1_0101.10#) THEN COMMENT ("CONVERSION ROUNDS TO LEAST FIXED-POINT VALUE"); ELSIF FIX1(F5B) = IDENT1(2#1_0101.10#) AND FIX1(-F5A) = IDENT1(-2#1010.10#) THEN COMMENT ("CONVERSION ROUNDS TO GREATEST FIXED-POINT VALUE"); ELSIF FIX1(F5A) = IDENT1(2#1010.10#) AND FIX1(-F5A) = IDENT1(-2#1010.10#) THEN COMMENT ("CONVERSION ROUNDS TOWARD ZERO"); ELSIF FIX1(F5B) = IDENT1(2#1_0101.10#) AND FIX1(-F5B) = IDENT1(-2#1_0101.10#) THEN COMMENT ("CONVERSION ROUNDS AWAY FROM ZERO"); ELSE COMMENT ("UNABLE TO DETERMINE CONVERSION PATTERN"); END IF; RESULT; END C46024A;
with Ada.Text_IO; use Ada.Text_IO; procedure Barnes18 is subtype Digit is Character range '0' .. '9'; type Counters is array (Digit) of Natural range 0 .. 2; function Val (C : Character) return Natural is (Natural'Value ("" & C)); -------------------- -- Print_Solution -- -------------------- procedure Print_Solution (I, J : Positive) is Spaces : Natural := 0; begin Put_Line (" " & I'Img); Put_Line (" " & J'Img); Put_Line ("------"); for C of J'Img loop if C in Digit then for W in 1 .. Spaces loop Put (" "); end loop; Put_Line (Natural'Image (I * Val (C))); Spaces := Spaces + 1; end if; end loop; Put_Line ("------"); Put_Line (Natural'Image (I * J)); end Print_Solution; ----------- -- Check -- ----------- procedure Check (I, J : Positive) is Counter : Counters := (others => 0); -------------- -- Register -- -------------- procedure Register (Num : Positive) is begin for C of Num'Img loop if C in Digit then Counter (C) := Counter (C) + 1; -- Will raise on >2, discarding candidates end if; end loop; end Register; begin Register (I); Register (J); Register (I * J); for C of J'Img loop if C in Digit then Register (I * Val (C)); end if; end loop; -- Verify each digit appears exactly two times: for V of Counter loop if V /= 2 then raise Constraint_Error; end if; end loop; Print_Solution (I, J); exception when Constraint_Error => -- Put ("."); null; end Check; begin for I in 100 .. 999 loop for J in 100 .. 999 loop Check (I, J); end loop; end loop; -- Indeed there's only one solution, although we continue checking after found end Barnes18;
----------------------------------------------------------------------- -- babel-base-users-- User's database for file owership identification -- Copyright (C) 2014, 2015 Stephane.Carrez -- Written by Stephane.Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- private with Ada.Finalization; private with Ada.Containers.Hashed_Maps; with Util.Strings; -- == User database == -- The <tt>Babel.Base.Users</tt> package defines a small database that maintains the -- mapping between a user or group name and the user <tt>uid_t</tt> or group <tt>gid_t</tt>. -- The mapping is obtained by using the Posix.1-2001 operations getpwnam_r (3) and -- getgrnam_r (3). The Posix operations are called once for a given name/id and they are -- stored in several hash map. A protected type is used to maintain the user and group -- mapping cache so that concurrent accesses are possible. package Babel.Base.Users is subtype Name_Access is Util.Strings.Name_Access; -- Information about a user and its group. type User_Type is record Name : Name_Access; Group : Name_Access; Uid : Uid_Type; Gid : Gid_Type; end record; NO_USER : constant User_Type; type Database is tagged limited private; type Database_Access is access all Database'Class; -- Find the UID and GID for the user that corresponds to the given name and group. function Find (From : in Database; User : in String; Group : in String) return User_Type; -- Find the UID and GID for the user that corresponds to the given name and group. function Find (From : in Database; User : in Uid_Type; Group : in Gid_Type) return User_Type; -- Get the user name associated with the given UID. -- Returns null if the UID was not found. function Get_Name (From : in Database; Id : in Uid_Type) return Name_Access; -- Get the UID associated with the given user name. function Get_Uid (From : in Database; Name : in String) return Uid_Type; -- Get the group name associated with the given GID. -- Returns null if the GID was not found. function Get_Group (From : in Database; Id : in Gid_Type) return Name_Access; -- Get the GID associated with the given group name. function Get_Gid (From : in Database; Name : in String) return Gid_Type; private INVALID_ID : constant Natural := Natural'Last; NO_USER : constant User_Type := User_Type'(Name => null, Group => null, Uid => Uid_Type'Last, Gid => Gid_Type'Last); function Hash (Key : in Natural) return Ada.Containers.Hash_Type; package Id_Map is new Ada.Containers.Hashed_Maps (Key_Type => Natural, Element_Type => Name_Access, Hash => Hash, Equivalent_Keys => "=", "=" => Util.Strings."="); package Name_Map is new Ada.Containers.Hashed_Maps (Key_Type => Name_Access, Element_Type => Natural, Hash => Util.Strings.Hash, Equivalent_Keys => Util.Strings.Equivalent_Keys, "=" => "="); -- To keep the implementation simple, the same protected type and same hash maps -- is used for the users and groups database. protected type Local_Base is -- Find in the ID map for the associated user/group name. -- If the item is not found in the map, call the <tt>Search</tt> function to resolve it. -- If the ID was not found, return a null name. procedure Find_Name (Id : in Natural; Search : not null access function (Id : in Natural) return String; Name : out Name_Access); -- Find in the name map for the corresponding ID. -- If the name was not found in the map, call the <tt>Search</tt> function to resolve it. procedure Find_Id (Name : in String; Search : not null access function (Name : in String) return Natural; Id : out Natural; Result : out Name_Access); procedure Clear; private Names : Name_Map.Map; Ids : Id_Map.Map; end Local_Base; type Database is limited new Ada.Finalization.Limited_Controlled with record User_Base : aliased Local_Base; Group_Base : aliased Local_Base; Users : access Local_Base; Groups : access Local_Base; end record; overriding procedure Initialize (Db : in out Database); overriding procedure Finalize (Db : in out Database); end Babel.Base.Users;
-- Institution: Technische Universität München -- Department: Realtime Computer Systems (RCS) -- Project: StratoX -- -- Authors: Emanuel Regnath (emanuel.regnath@tum.de) with HIL.Devices; -- @summary -- Target-independent specification for HIL of GPIO package HIL.GPIO with SPARK_Mode is type GPIO_Signal_Type is( HIGH, LOW); type GPIO_Point_Type is new HIL.Devices.Device_Type_GPIO; subtype Point_Out_Type is GPIO_Point_Type; --subtype Ponit_In_Type is GPIO_Point_Type; --function init return Boolean; procedure configure; -- precondition that Point is Output procedure write (Point : in GPIO_Point_Type; Signal : in GPIO_Signal_Type); procedure read (Point : in GPIO_Point_Type; Signal : out GPIO_Signal_Type); procedure All_LEDs_Off; procedure All_LEDs_On; end HIL.GPIO;
-- Mail Baby API -- This is an API defintion for accesssing the Mail.Baby mail service. -- -- The version of the OpenAPI document: 1.0.0 -- Contact: detain@interserver.net -- -- NOTE: This package is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. -- https://openapi-generator.tech -- Do not edit the class manually. with Swagger.Streams; with Ada.Containers.Vectors; package .Models is pragma Style_Checks ("-mr"); type SendMailAdvFrom_Type is record Email : Swagger.UString; Name : Swagger.Nullable_UString; end record; package SendMailAdvFrom_Type_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => SendMailAdvFrom_Type); procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in SendMailAdvFrom_Type); procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in SendMailAdvFrom_Type_Vectors.Vector); procedure Deserialize (From : in Swagger.Value_Type; Name : in String; Value : out SendMailAdvFrom_Type); procedure Deserialize (From : in Swagger.Value_Type; Name : in String; Value : out SendMailAdvFrom_Type_Vectors.Vector); type MailLog_Type is record Id : Swagger.Nullable_Long; end record; package MailLog_Type_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => MailLog_Type); procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in MailLog_Type); procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in MailLog_Type_Vectors.Vector); procedure Deserialize (From : in Swagger.Value_Type; Name : in String; Value : out MailLog_Type); procedure Deserialize (From : in Swagger.Value_Type; Name : in String; Value : out MailLog_Type_Vectors.Vector); type GenericResponse_Type is record Status : Swagger.Nullable_UString; Text : Swagger.Nullable_UString; end record; package GenericResponse_Type_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => GenericResponse_Type); procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in GenericResponse_Type); procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in GenericResponse_Type_Vectors.Vector); procedure Deserialize (From : in Swagger.Value_Type; Name : in String; Value : out GenericResponse_Type); procedure Deserialize (From : in Swagger.Value_Type; Name : in String; Value : out GenericResponse_Type_Vectors.Vector); type ErrorResponse_Type is record Code : Swagger.UString; Message : Swagger.UString; end record; package ErrorResponse_Type_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => ErrorResponse_Type); procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in ErrorResponse_Type); procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in ErrorResponse_Type_Vectors.Vector); procedure Deserialize (From : in Swagger.Value_Type; Name : in String; Value : out ErrorResponse_Type); procedure Deserialize (From : in Swagger.Value_Type; Name : in String; Value : out ErrorResponse_Type_Vectors.Vector); type MailOrder_Type is record Id : Integer; Status : Swagger.UString; Username : Swagger.UString; Password : Swagger.Nullable_UString; Comment : Swagger.Nullable_UString; end record; package MailOrder_Type_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => MailOrder_Type); procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in MailOrder_Type); procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in MailOrder_Type_Vectors.Vector); procedure Deserialize (From : in Swagger.Value_Type; Name : in String; Value : out MailOrder_Type); procedure Deserialize (From : in Swagger.Value_Type; Name : in String; Value : out MailOrder_Type_Vectors.Vector); type MailContact_Type is record Email : Swagger.UString; Name : Swagger.Nullable_UString; end record; package MailContact_Type_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => MailContact_Type); procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in MailContact_Type); procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in MailContact_Type_Vectors.Vector); procedure Deserialize (From : in Swagger.Value_Type; Name : in String; Value : out MailContact_Type); procedure Deserialize (From : in Swagger.Value_Type; Name : in String; Value : out MailContact_Type_Vectors.Vector); type SendMail_Type is record To : Swagger.UString; From : Swagger.UString; Subject : Swagger.UString; P_Body : Swagger.UString; end record; package SendMail_Type_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => SendMail_Type); procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in SendMail_Type); procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in SendMail_Type_Vectors.Vector); procedure Deserialize (From : in Swagger.Value_Type; Name : in String; Value : out SendMail_Type); procedure Deserialize (From : in Swagger.Value_Type; Name : in String; Value : out SendMail_Type_Vectors.Vector); type InlineResponse401_Type is record Code : Swagger.UString; Message : Swagger.UString; end record; package InlineResponse401_Type_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => InlineResponse401_Type); procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in InlineResponse401_Type); procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in InlineResponse401_Type_Vectors.Vector); procedure Deserialize (From : in Swagger.Value_Type; Name : in String; Value : out InlineResponse401_Type); procedure Deserialize (From : in Swagger.Value_Type; Name : in String; Value : out InlineResponse401_Type_Vectors.Vector); type MailAttachment_Type is record Data : Swagger.Http_Content_Type; Filename : Swagger.Nullable_UString; end record; package MailAttachment_Type_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => MailAttachment_Type); procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in MailAttachment_Type); procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in MailAttachment_Type_Vectors.Vector); procedure Deserialize (From : in Swagger.Value_Type; Name : in String; Value : out MailAttachment_Type); procedure Deserialize (From : in Swagger.Value_Type; Name : in String; Value : out MailAttachment_Type_Vectors.Vector); -- ------------------------------ -- Email details -- Details for an Email -- ------------------------------ type SendMailAdv_Type is record Subject : Swagger.UString; P_Body : Swagger.UString; From : .Models.SendMailAdvFrom_Type_Vectors.Vector; To : .Models.MailContact_Type_Vectors.Vector; Id : Swagger.Long; Replyto : .Models.MailContact_Type_Vectors.Vector; Cc : .Models.MailContact_Type_Vectors.Vector; Bcc : .Models.MailContact_Type_Vectors.Vector; Attachments : .Models.MailAttachment_Type_Vectors.Vector; end record; package SendMailAdv_Type_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => SendMailAdv_Type); procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in SendMailAdv_Type); procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in SendMailAdv_Type_Vectors.Vector); procedure Deserialize (From : in Swagger.Value_Type; Name : in String; Value : out SendMailAdv_Type); procedure Deserialize (From : in Swagger.Value_Type; Name : in String; Value : out SendMailAdv_Type_Vectors.Vector); end .Models;
package body Misaligned_Param_Pkg is type IP is access all Integer; function Channel_Eth (Kind : IP) return Integer; pragma Export (Ada, Channel_Eth, "channel_eth"); function Channel_Eth (Kind : IP) return Integer is begin Kind.all := 111; return 0; end; end Misaligned_Param_Pkg;
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Web Framework -- -- -- -- Tools Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2015-2018, Vadim Godunko <vgodunko@gmail.com> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with Ada.Directories; with Ada.Wide_Text_IO; with Ada.Wide_Wide_Text_IO; with Ada.Command_Line; with GNAT.Directory_Operations; with GNAT.OS_Lib; with GNAT.Strings; with Asis; with Asis.Ada_Environments; with Asis.Compilation_Units; with Asis.Elements; with Asis.Errors; with Asis.Exceptions; with Asis.Extensions; with Asis.Implementation; with League.Application; with League.Strings; with League.String_Vectors; with Engines.Contexts; with Engines.Registry_All_Actions; procedure Asis2JS is use type League.Strings.Universal_String; procedure Compile_Unit (Unit : Asis.Compilation_Unit; Output_File : League.Strings.Universal_String); procedure Compile_File (Source_File : League.Strings.Universal_String; Output_File : League.Strings.Universal_String); procedure Create_ADT_File (Source_File : League.Strings.Universal_String); -- Runs GNAT compiler to generate ADT file. procedure Print_Runtime_Directory (Arg : League.Strings.Universal_String); -- Print adalib directory in format expected by gprconfig. -- Escape '..' to work with regexp. Avoid windows style pathes -- because gprconfig doesn't understand it well enought. function Relative_Path (From : League.Strings.Universal_String; To : League.Strings.Universal_String; Escape : Wide_Wide_String) return League.Strings.Universal_String; Engine : aliased Engines.Contexts.Context; Context : Asis.Context; Source_File : League.Strings.Universal_String; Options : League.String_Vectors.Universal_String_Vector; ADT_File : League.Strings.Universal_String; Output_File : League.Strings.Universal_String; ------------------ -- Compile_File -- ------------------ procedure Compile_File (Source_File : League.Strings.Universal_String; Output_File : League.Strings.Universal_String) is File_Name : constant Wide_String := Source_File.To_UTF_16_Wide_String; Units : constant Asis.Compilation_Unit_List := Asis.Compilation_Units.Compilation_Units (Context); Success : Boolean := False; begin for J in Units'Range loop if Asis.Compilation_Units.Text_Name (Units (J)) = File_Name then case Asis.Compilation_Units.Unit_Kind (Units (J)) is when Asis.A_Package_Body => Success := True; Compile_Unit (Asis.Compilation_Units.Corresponding_Declaration (Units (J)), Output_File); exit; when Asis.A_Package | Asis.A_Generic_Unit_Instance | Asis.A_Renaming | Asis.A_Generic_Unit_Declaration => Success := True; Compile_Unit (Units (J), Output_File); exit; when Asis.A_Procedure | Asis.A_Function => -- Specification for subprogram body is optional, process it -- when available or process body directly. if not Asis.Compilation_Units.Is_Nil (Asis.Compilation_Units.Corresponding_Body (Units (J))) then Success := True; Compile_Unit (Asis.Compilation_Units.Corresponding_Body (Units (J)), Output_File); end if; when Asis.A_Procedure_Body | Asis.A_Function_Body => Success := True; Compile_Unit (Units (J), Output_File); when others => Ada.Wide_Text_IO.Put (Asis.Compilation_Units.Debug_Image (Units (J))); raise Program_Error; end case; end if; end loop; if not Success then raise Program_Error; end if; end Compile_File; ------------------ -- Compile_Unit -- ------------------ procedure Compile_Unit (Unit : Asis.Compilation_Unit; Output_File : League.Strings.Universal_String) is List : constant Asis.Context_Clause_List := Asis.Elements.Context_Clause_Elements (Unit); Result : League.Strings.Universal_String; Code : League.Strings.Universal_String; File : Ada.Wide_Wide_Text_IO.File_Type; begin for J in List'Range loop Result := Engine.Text.Get_Property (List (J), Engines.Code); Code.Append (Result); end loop; Result := Engine.Text.Get_Property (Element => Asis.Elements.Unit_Declaration (Unit), Name => Engines.Code); Code.Append (Result); Ada.Wide_Wide_Text_IO.Create (File, Ada.Wide_Wide_Text_IO.Out_File, Output_File.To_UTF_8_String, "wcem=8"); Ada.Wide_Wide_Text_IO.Put_Line (File, Code.To_Wide_Wide_String); Ada.Wide_Wide_Text_IO.Close (File); end Compile_Unit; --------------------- -- Create_ADT_File -- --------------------- procedure Create_ADT_File (Source_File : League.Strings.Universal_String) is Success : Boolean; Source : GNAT.Strings.String_Access := new String'(Source_File.To_UTF_8_String); Arguments : GNAT.Strings.String_List (1 .. Options.Length); begin for J in 1 .. Options.Length loop Arguments (J) := new String'(Options (J).To_UTF_8_String); end loop; Asis.Extensions.Compile (Source, Arguments, Success); GNAT.Strings.Free (Source); for J in Arguments'Range loop GNAT.Strings.Free (Arguments (J)); end loop; if not Success then raise Program_Error; end if; end Create_ADT_File; ----------------------------- -- Print_Runtime_Directory -- ----------------------------- procedure Print_Runtime_Directory (Arg : League.Strings.Universal_String) is procedure Launch_GCC (GCC : League.Strings.Universal_String; Output : out League.Strings.Universal_String); -- gcc -print-file-name=adalib procedure Launch_GCC (GCC : League.Strings.Universal_String; Output : out League.Strings.Universal_String) is Code : Integer; Name : constant String := GCC.To_UTF_8_String; Full : GNAT.OS_Lib.String_Access; Temp : GNAT.OS_Lib.String_Access; FD : GNAT.OS_Lib.File_Descriptor; Args : GNAT.OS_Lib.Argument_List := (1 => new String'("-print-file-name=adalib")); begin if Ada.Directories.Simple_Name (Name) = Name then Full := GNAT.OS_Lib.Locate_Exec_On_Path (Name); else Full := new String'(GCC.To_UTF_8_String); end if; GNAT.OS_Lib.Create_Temp_Output_File (FD, Temp); GNAT.OS_Lib.Spawn (Program_Name => Full.all, Args => Args, Output_File_Descriptor => FD, Return_Code => Code); declare Input : Ada.Wide_Wide_Text_IO.File_Type; begin Ada.Wide_Wide_Text_IO.Open (Input, Ada.Wide_Wide_Text_IO.In_File, Temp.all); while not Ada.Wide_Wide_Text_IO.End_Of_File (Input) loop Output.Append (Ada.Wide_Wide_Text_IO.Get_Line (Input)); end loop; Ada.Wide_Wide_Text_IO.Close (Input); GNAT.OS_Lib.Close (FD); Ada.Directories.Delete_File (Temp.all); GNAT.Strings.Free (Args (1)); GNAT.Strings.Free (Full); GNAT.Strings.Free (Temp); if Code = 0 then declare Cmd : constant String := Ada.Directories.Full_Name (Ada.Command_Line.Command_Name); Real : constant String := Ada.Directories.Full_Name (Output.To_UTF_8_String); begin Output := Relative_Path (League.Strings.From_UTF_8_String (Cmd), League.Strings.From_UTF_8_String (Real), Escape => "\.\."); end; else Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); end if; end; end Launch_GCC; GCC : League.Strings.Universal_String := League.Strings.To_Universal_String ("gcc"); Output : League.Strings.Universal_String; begin if Arg.Index ("=") > 0 then GCC := Arg.Tail_From (Arg.Index ("=") + 1); end if; Launch_GCC (GCC, Output); Ada.Wide_Wide_Text_IO.Put_Line (Output.To_Wide_Wide_String); end Print_Runtime_Directory; ------------------- -- Relative_Path -- ------------------- function Relative_Path (From : League.Strings.Universal_String; To : League.Strings.Universal_String; Escape : Wide_Wide_String) return League.Strings.Universal_String is Sep : constant Character := GNAT.Directory_Operations.Dir_Separator; W_Sep : constant Wide_Wide_Character := Wide_Wide_Character'Val (Character'Pos (Sep)); F : constant League.String_Vectors.Universal_String_Vector := From.Split (W_Sep); T : constant League.String_Vectors.Universal_String_Vector := To.Split (W_Sep); Common : Natural := Natural'Min (F.Length, T.Length); Result : League.Strings.Universal_String; begin for J in 1 .. Common loop if F (J) /= T (J) then Common := J - 1; exit; end if; end loop; for J in Common + 1 .. F.Length - 1 loop Result.Append (Escape); Result.Append ("/"); end loop; for J in Common + 1 .. T.Length loop Result.Append (T (J)); Result.Append ("/"); end loop; return Result; end Relative_Path; begin -- Process command line parameters. declare Arguments : constant League.String_Vectors.Universal_String_Vector := League.Application.Arguments; begin for J in 1 .. Arguments.Length loop if Arguments (J).Starts_With ("-I") or Arguments (J).Starts_With ("-g") then Options.Append (Arguments (J)); elsif Arguments (J) = League.Strings.To_Universal_String ("-g") then Ada.Wide_Text_IO.Put_Line (Ada.Wide_Text_IO.Standard_Error, "warning: -g switch is not supported yet"); elsif Arguments (J).Starts_With ("--print-runtime-dir") then Print_Runtime_Directory (Arguments (J)); return; elsif Source_File.Is_Empty then Source_File := Arguments (J); else raise Program_Error; end if; end loop; end; ADT_File := Source_File.Head (Source_File.Length - 1) & 't'; ADT_File := League.Strings.From_UTF_8_String (Ada.Directories.Simple_Name (ADT_File.To_UTF_8_String)); Output_File := ADT_File.Head (ADT_File.Length - 4) & ".js"; -- Enable use of UTF-8 as source code encoding. Options.Append (League.Strings.From_UTF_8_String ("-gnatW8")); -- Execute GNAT to generate ADT files. Create_ADT_File (Source_File); -- Initialize ASIS-for-GNAT and load ADT file. Asis.Implementation.Initialize ("-ws"); Asis.Ada_Environments.Associate (The_Context => Context, Name => Asis.Ada_Environments.Default_Name, Parameters => "-C1 " & ADT_File.To_UTF_16_Wide_String); Asis.Ada_Environments.Open (Context); -- Register processing actions. Engines.Registry_All_Actions (Engine); -- Process file. Compile_File (Source_File, Output_File); -- Finalize ASIS. Asis.Ada_Environments.Close (Context); Asis.Ada_Environments.Dissociate (Context); Asis.Implementation.Finalize; exception when Asis.Exceptions.ASIS_Inappropriate_Context | Asis.Exceptions.ASIS_Inappropriate_Container | Asis.Exceptions.ASIS_Inappropriate_Compilation_Unit | Asis.Exceptions.ASIS_Inappropriate_Element | Asis.Exceptions.ASIS_Inappropriate_Line | Asis.Exceptions.ASIS_Inappropriate_Line_Number | Asis.Exceptions.ASIS_Failed => Ada.Wide_Text_IO.Put ("ASIS Error Status is "); Ada.Wide_Text_IO.Put (Asis.Errors.Error_Kinds'Wide_Image (Asis.Implementation.Status)); Ada.Wide_Text_IO.New_Line; Ada.Wide_Text_IO.Put ("ASIS Diagnosis is "); Ada.Wide_Text_IO.New_Line; Ada.Wide_Text_IO.Put (Asis.Implementation.Diagnosis); Ada.Wide_Text_IO.New_Line; Asis.Implementation.Set_Status; Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); end Asis2JS;
-- smart_c_resources.adb -- A reference counting package to wrap a C type that requires initialization -- and finalization. -- Copyright (c) 2016, James Humphry -- -- Permission to use, copy, modify, and/or distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE -- OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -- PERFORMANCE OF THIS SOFTWARE. package body Smart_C_Resources is ------------- -- Smart_T -- ------------- function Make_Smart_T (X : in T) return Smart_T is (Ada.Finalization.Controlled with Element => X, Counter => Make_New_Counter); function Element (S : Smart_T) return T is (S.Element); function Use_Count (S : in Smart_T) return Natural is (Use_Count(S.Counter.all)); overriding procedure Initialize (Object : in out Smart_T) is begin Object.Element := Initialize; Object.Counter := Make_New_Counter; end Initialize; overriding procedure Adjust (Object : in out Smart_T) is begin pragma Assert (Check => Object.Counter /= null, Message => "Corruption during Smart_T assignment."); Check_Increment_Use_Count(Object.Counter.all); end Adjust; overriding procedure Finalize (Object : in out Smart_T) is begin if Object.Counter /= null then -- Finalize is required to be idempotent to cope with rare -- situations when it may be called multiple times. By setting -- Object.Counter to null, I ensure that there can be no -- double-decrementing of counters or double-deallocations. Decrement_Use_Count(Object.Counter.all); if Use_Count(Object.Counter.all) = 0 then Finalize(Object.Element); Deallocate_If_Unused(Object.Counter); end if; Object.Counter := null; end if; end Finalize; end Smart_C_Resources;
with Sodium.Functions; use Sodium.Functions; with Ada.Text_IO; use Ada.Text_IO; procedure Demo_Ada is upper_bound : Natural32 := 16#FFF#; Custom_Size : Key_Size_Range := 48; begin if not initialize_sodium_library then Put_Line ("Initialization failed"); return; end if; Put_Line (" Full random: " & Random_Word'Img); Put_Line ("Limited to $FFF: " & Random_Limited_Word (upper_bound)'Img); Put_Line (" Random salt: " & As_Hexidecimal (Random_Salt)); Put_Line (" Random short: " & As_Hexidecimal (Random_Short_Key)); Put_Line (" Random Std key: " & As_Hexidecimal (Random_Standard_Hash_Key)); Put_LIne ("Rand 48-bit Key: " & As_Hexidecimal (Random_Hash_Key (Custom_Size))); end Demo_Ada;
-- -- 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 ada.unchecked_conversion; with ewok.devices_shared; use ewok.devices_shared; with ewok.tasks; use type ewok.tasks.t_task_type; with ewok.devices; with ewok.layout; with ewok.mpu; with ewok.mpu.allocator; with ewok.debug; with config; with config.memlayout; use config.memlayout; package body ewok.memory with spark_mode => off is procedure init (success : out boolean) is begin ewok.mpu.init (success); end init; -- zerofiy BSS section of given task in RAM. procedure zeroify_bss (id : in t_real_task_id) is begin ewok.mpu.zeroify_bss(id); end zeroify_bss; -- map .data section from flash memory to RAM for target application -- mapping .data section depend on the memory backend, i.e. in MPU based -- system, this is a recopy from a given region to another as in MMU -- based system, this is a virtual memory mapping procedure copy_data_to_ram (id : in t_real_task_id) is begin ewok.mpu.copy_data_to_ram(id); end copy_data_to_ram; procedure map_code_and_data (id : in t_real_task_id) is flash_mask : t_mask := (others => 1); ram_mask : t_mask := (others => 1); begin for i in 0 .. config.memlayout.list(id).flash_slot_number - 1 loop flash_mask(config.memlayout.list(id).flash_slot_start + i) := 0; end loop; for i in 0 .. config.memlayout.list(id).ram_slot_number - 1 loop ram_mask(config.memlayout.list(id).ram_slot_start + i) := 0; end loop; ewok.mpu.update_subregions (region_number => ewok.mpu.USER_CODE_REGION, subregion_mask => to_unsigned_8 (flash_mask)); ewok.mpu.update_subregions (region_number => ewok.mpu.USER_DATA_REGION, subregion_mask => to_unsigned_8 (ram_mask)); end map_code_and_data; procedure unmap_user_code_and_data is begin ewok.mpu.update_subregions (region_number => ewok.mpu.USER_CODE_REGION, subregion_mask => 2#1111_1111#); ewok.mpu.update_subregions (region_number => ewok.mpu.USER_DATA_REGION, subregion_mask => 2#1111_1111#); end unmap_user_code_and_data; procedure map_device (dev_id : in ewok.devices_shared.t_registered_device_id; success : out boolean) is region_type : ewok.mpu.t_region_type; begin if ewok.devices.is_device_region_ro (dev_id) then region_type := ewok.mpu.REGION_TYPE_USER_DEV_RO; else region_type := ewok.mpu.REGION_TYPE_USER_DEV; end if; ewok.mpu.allocator.map_in_pool (addr => ewok.devices.get_device_addr (dev_id), size => ewok.devices.get_device_size (dev_id), region_type => region_type, subregion_mask => ewok.devices.get_device_subregions_mask (dev_id), success => success); if not success then pragma DEBUG (debug.log ("mpu_mapping_device(): can not be mapped")); end if; end map_device; procedure unmap_device (dev_id : in ewok.devices_shared.t_registered_device_id) is begin ewok.mpu.allocator.unmap_from_pool (ewok.devices.get_device_addr (dev_id)); end unmap_device; procedure unmap_all_devices is begin ewok.mpu.allocator.unmap_all_from_pool; end unmap_all_devices; function device_can_be_mapped return boolean is begin return ewok.mpu.allocator.free_region_exist; end device_can_be_mapped; procedure map_task (id : in t_task_id) is new_task : ewok.tasks.t_task renames ewok.tasks.tasks_list(id); dev_id : t_device_id; ok : boolean; begin -- Release previously dynamically allocated regions (used for mapping -- devices and ISR stack) unmap_all_devices; -- Kernel tasks have no access to user regions if new_task.ttype = ewok.tasks.TASK_TYPE_KERNEL then unmap_user_code_and_data; return; end if; -- Mapping ISR device and ISR stack if new_task.mode = TASK_MODE_ISRTHREAD then -- Mapping the ISR stack ewok.mpu.allocator.map_in_pool (addr => ewok.layout.STACK_BOTTOM_TASK_ISR, size => 4096, region_type => ewok.mpu.REGION_TYPE_ISR_STACK, subregion_mask => 0, success => ok); if not ok then debug.panic ("mpu_isr(): mapping ISR stack failed!"); end if; -- Mapping the ISR device dev_id := new_task.isr_ctx.device_id; if dev_id /= ID_DEV_UNUSED then map_device (dev_id, ok); if not ok then debug.panic ("mpu_switching(): mapping device failed!"); end if; end if; -- Mapping main thread devices else -- Note: -- - EXTIs are a special case where an interrupt can trigger a -- user ISR without any device_id associated -- - DMAs are not registered in devices for i in new_task.devices'range loop if new_task.devices(i).device_id /= ID_DEV_UNUSED and then new_task.devices(i).mounted = true then map_device (new_task.devices(i).device_id, ok); if not ok then debug.panic ("mpu_switching(): mapping device failed!"); end if; end if; end loop; end if; -- ISR or MAIN thread map_code_and_data (id); end map_task; end ewok.memory;
package GLOBE_3D.Math is ------------- -- Vectors -- ------------- function "*" (l : Real; v : Vector_3D) return Vector_3D; pragma Inline ("*"); function "*" (v : Vector_3D; l : Real) return Vector_3D; pragma Inline ("*"); function "+" (a, b : Vector_3D) return Vector_3D; pragma Inline ("+"); function "-" (a : Vector_3D) return Vector_3D; pragma Inline ("-"); function "-" (a, b : Vector_3D) return Vector_3D; pragma Inline ("-"); function "*" (a, b : Vector_3D) return Real; -- dot product pragma Inline ("*"); function "*" (a, b : Vector_3D) return Vector_3D; -- cross product pragma Inline ("*"); function Norm (a : Vector_3D) return Real; pragma Inline (Norm); function Norm2 (a : Vector_3D) return Real; pragma Inline (Norm2); function Normalized (a : Vector_3D) return Vector_3D; -- Angles -- function Angle (Point_1, Point_2, Point_3 : Vector_3D) return Real; -- -- returns the angle between the vector Point_1 to Point_2 and the vector Point_3 to Point_2. function to_Degrees (Radians : Real) return Real; function to_Radians (Degrees : Real) return Real; -------------- -- Matrices -- -------------- function "*" (A, B : Matrix_33) return Matrix_33; function "*" (A : Matrix_33; x : Vector_3D) return Vector_3D; function "*" (A : Matrix_44; x : Vector_3D) return Vector_3D; function "*" (A : Matrix_44; x : Vector_3D) return Vector_4D; function Transpose (A : Matrix_33) return Matrix_33; function Transpose (A : Matrix_44) return Matrix_44; function Det (A : Matrix_33) return Real; function XYZ_rotation (ax, ay, az : Real) return Matrix_33; function XYZ_rotation (v : Vector_3D) return Matrix_33; -- Gives a rotation matrix that corresponds to look into a certain -- direction. Camera swing rotation is arbitrary. -- Left - multiply by XYZ_Rotation (0.0, 0.0, az) to correct it. function Look_at (direction : Vector_3D) return Matrix_33; function Look_at (eye, center, up : Vector_3D) return Matrix_33; -- This is for correcting cumulation of small computational -- errors, making the rotation matrix no more orthogonal procedure Re_Orthonormalize (M : in out Matrix_33); -- Right - multiply current matrix by A procedure Multiply_GL_Matrix (A : Matrix_33); -- Impose A as current matrix procedure Set_GL_Matrix (A : Matrix_33); -- For replacing the " = 0.0" test which is a Bad Thing function Almost_zero (x : Real) return Boolean; pragma Inline (Almost_zero); function Almost_zero (x : GL.C_Float) return Boolean; pragma Inline (Almost_zero); function sub_Matrix (Self : Matrix; start_Row, end_Row, start_Col, end_Col : Positive) return Matrix; end GLOBE_3D.Math;
-- SPDX-License-Identifier: MIT -- -- Copyright (c) 1999 .. 2018 Gautier de Montmollin -- SWITZERLAND -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. with DCF.Zip.Headers; with Ada.Characters.Handling; with Ada.IO_Exceptions; with Ada.Unchecked_Deallocation; package body DCF.Zip is function Name (Object : Archived_File) return String is (Object.Node.File_Name); function Name_Encoding (Object : Archived_File) return Zip_Name_Encoding is (Object.Node.Name_Encoding); function Compressed_Size (Object : Archived_File) return File_Size_Type is (Object.Node.Comp_Size); function Uncompressed_Size (Object : Archived_File) return File_Size_Type is (Object.Node.Uncomp_Size); function Date_Time (Object : Archived_File) return Time is (Object.Node.Date_Time); function Compressed (Object : Archived_File) return Boolean is (Object.Node.Method = Deflate); function Encrypted (Object : Archived_File) return Boolean is (Object.Node.Encrypted_2_X); function File_Index (Object : Archived_File) return DCF.Streams.Zs_Index_Type is (Object.Node.File_Index); function CRC_32 (Object : Archived_File) return Unsigned_32 is (Object.Node.Crc_32); procedure Dispose is new Ada.Unchecked_Deallocation (Dir_Node, P_Dir_Node); procedure Dispose is new Ada.Unchecked_Deallocation (String, P_String); package Binary_Tree_Rebalancing is procedure Rebalance (Root : in out P_Dir_Node); end Binary_Tree_Rebalancing; package body Binary_Tree_Rebalancing is ------------------------------------------------------------------- -- Tree Rebalancing in Optimal Time and Space -- -- QUENTIN F. STOUT and BETTE L. WARREN -- -- Communications of the ACM September 1986 Volume 29 Number 9 -- ------------------------------------------------------------------- -- http://www.eecs.umich.edu/~qstout/pap/CACM86.pdf -- -- Translated by (New) P2Ada v. 15-Nov-2006 procedure Tree_To_Vine (Root : P_Dir_Node; Size : out Integer) is -- Transform the tree with pseudo-root "root^" into a vine with -- pseudo-root node "root^", and store the number of nodes in "size" Vine_Tail, Remainder, Temp : P_Dir_Node; begin Vine_Tail := Root; Remainder := Vine_Tail.Right; Size := 0; while Remainder /= null loop if Remainder.Left = null then -- Move vine-tail down one: Vine_Tail := Remainder; Remainder := Remainder.Right; Size := Size + 1; else -- Rotate: Temp := Remainder.Left; Remainder.Left := Temp.Right; Temp.Right := Remainder; Remainder := Temp; Vine_Tail.Right := Temp; end if; end loop; end Tree_To_Vine; procedure Vine_To_Tree (Root : P_Dir_Node; Size_Given : Integer) is -- Convert the vine with "size" nodes and pseudo-root -- node "root^" into a balanced tree Leaf_Count : Integer; Size : Integer := Size_Given; procedure Compression (Root_Compress : P_Dir_Node; Count : Integer) is -- Compress "count" spine nodes in the tree with pseudo-root "root_compress^" Scanner, Child : P_Dir_Node; begin Scanner := Root_Compress; for Counter in reverse 1 .. Count loop Child := Scanner.Right; Scanner.Right := Child.Right; Scanner := Scanner.Right; Child.Right := Scanner.Left; Scanner.Left := Child; end loop; end Compression; -- Returns n - 2 ** Integer( Float'Floor( log( Float(n) ) / log(2.0) ) ) -- without Float-Point calculation and rounding errors with too short floats function Remove_Leading_Binary_1 (N : Integer) return Integer is X : Integer := 2**16; -- supposed maximum begin if N < 1 then return N; end if; while N mod X = N loop X := X / 2; end loop; return N mod X; end Remove_Leading_Binary_1; begin -- Vine_to_tree Leaf_Count := Remove_Leading_Binary_1 (Size + 1); Compression (Root, Leaf_Count); -- create deepest leaves -- Use Perfect_leaves instead for a perfectly balanced tree Size := Size - Leaf_Count; while Size > 1 loop Compression (Root, Size / 2); Size := Size / 2; end loop; end Vine_To_Tree; procedure Rebalance (Root : in out P_Dir_Node) is -- Rebalance the binary search tree with root "root.all", -- with the result also rooted at "root.all". -- Uses the Tree_to_vine and Vine_to_tree procedures Pseudo_Root : P_Dir_Node; Size : Integer; begin Pseudo_Root := new Dir_Node (Name_Len => 0); Pseudo_Root.Right := Root; Tree_To_Vine (Pseudo_Root, Size); Vine_To_Tree (Pseudo_Root, Size); Root := Pseudo_Root.Right; Dispose (Pseudo_Root); end Rebalance; end Binary_Tree_Rebalancing; -- 19-Jun-2001: Enhanced file name identification -- a) when case insensitive -> all UPPER (current) -- b) '\' and '/' identified -> all '/' (new) function Normalize (S : String; Case_Sensitive : Boolean) return String is Sn : String := (if Case_Sensitive then S else Ada.Characters.Handling.To_Upper (S)); begin for I in Sn'Range loop if Sn (I) = '\' then Sn (I) := '/'; end if; end loop; return Sn; end Normalize; function Get_Node (Info : in Zip_Info; Name : in String) return P_Dir_Node is Aux : P_Dir_Node := Info.Dir_Binary_Tree; Up_Name : constant String := Normalize (Name, Info.Case_Sensitive); begin while Aux /= null loop if Up_Name > Aux.Dico_Name then Aux := Aux.Right; elsif Up_Name < Aux.Dico_Name then Aux := Aux.Left; else -- entry found ! return Aux; end if; end loop; return null; end Get_Node; Boolean_To_Encoding : constant array (Boolean) of Zip_Name_Encoding := (False => IBM_437, True => UTF_8); ------------------------------------------------------------- -- Load Zip_info from a stream containing the .zip archive -- ------------------------------------------------------------- procedure Load (Info : out Zip_Info; From : in out DCF.Streams.Root_Zipstream_Type'Class; Case_Sensitive : in Boolean := False) is procedure Insert (Dico_Name : String; -- UPPER if case-insensitive search File_Name : String; File_Index : DCF.Streams.Zs_Index_Type; Comp_Size, Uncomp_Size : File_Size_Type; Crc_32 : Unsigned_32; Date_Time : Time; Method : Pkzip_Method; Name_Encoding : Zip_Name_Encoding; Read_Only : Boolean; Encrypted_2_X : Boolean; Root_Node : in out P_Dir_Node) is procedure Insert_Into_Tree (Node : in out P_Dir_Node) is begin if Node = null then Node := new Dir_Node' ((Name_Len => File_Name'Length, Left => null, Right => null, Dico_Name => Dico_Name, File_Name => File_Name, File_Index => File_Index, Comp_Size => Comp_Size, Uncomp_Size => Uncomp_Size, Crc_32 => Crc_32, Date_Time => Date_Time, Method => Method, Name_Encoding => Name_Encoding, Read_Only => Read_Only, Encrypted_2_X => Encrypted_2_X)); elsif Dico_Name > Node.Dico_Name then Insert_Into_Tree (Node.Right); elsif Dico_Name < Node.Dico_Name then Insert_Into_Tree (Node.Left); else -- Here we have a case where the entry name already exists -- in the dictionary raise Duplicate_Name with "Entry name '" & Dico_Name & "' appears twice in archive"; end if; end Insert_Into_Tree; begin Insert_Into_Tree (Root_Node); end Insert; The_End : Zip.Headers.End_Of_Central_Dir; Header : Zip.Headers.Central_File_Header; P : P_Dir_Node := null; Main_Comment : P_String; begin if Info.Loaded then raise Program_Error; end if; Zip.Headers.Load (From, The_End); -- We take the opportunity to read the main comment, which is right -- after the end-of-central-directory block Main_Comment := new String (1 .. Integer (The_End.Main_Comment_Length)); String'Read (From'Access, Main_Comment.all); -- Process central directory From.Set_Index (DCF.Streams.Zs_Index_Type (1 + The_End.Central_Dir_Offset) + The_End.Offset_Shifting); for I in 1 .. The_End.Total_Entries loop Zip.Headers.Read_And_Check (From, Header); declare This_Name : String (1 .. Natural (Header.Short_Info.Filename_Length)); begin String'Read (From'Access, This_Name); -- Skip extra field and entry comment From.Set_Index (From.Index + DCF.Streams.Zs_Size_Type (Header.Short_Info.Extra_Field_Length + Header.Comment_Length)); -- Now the whole i_th central directory entry is behind Insert (Dico_Name => Normalize (This_Name, Case_Sensitive), File_Name => Normalize (This_Name, True), File_Index => DCF.Streams.Zs_Index_Type (1 + Header.Local_Header_Offset) + The_End.Offset_Shifting, Comp_Size => Header.Short_Info.Dd.Compressed_Size, Uncomp_Size => Header.Short_Info.Dd.Uncompressed_Size, Crc_32 => Header.Short_Info.Dd.Crc_32, Date_Time => Header.Short_Info.File_Timedate, Method => Method_From_Code (Header.Short_Info.Zip_Type), Name_Encoding => Boolean_To_Encoding ((Header.Short_Info.Bit_Flag and Zip.Headers.Language_Encoding_Flag_Bit) /= 0), Read_Only => Header.Made_By_Version / 256 = 0 and -- DOS-like (Header.External_Attributes and 1) = 1, Encrypted_2_X => (Header.Short_Info.Bit_Flag and Zip.Headers.Encryption_Flag_Bit) /= 0, Root_Node => P); -- Since the files are usually well ordered, the tree as inserted -- is very unbalanced; we need to rebalance it from time to time -- during loading, otherwise the insertion slows down dramatically -- for zip files with plenty of files - converges to -- O(total_entries ** 2)... if I mod 256 = 0 then Binary_Tree_Rebalancing.Rebalance (P); end if; end; end loop; Binary_Tree_Rebalancing.Rebalance (P); Info.Loaded := True; Info.Case_Sensitive := Case_Sensitive; Info.Zip_Input_Stream := From'Unchecked_Access; Info.Dir_Binary_Tree := P; Info.Total_Entries := Integer (The_End.Total_Entries); Info.Zip_File_Comment := Main_Comment; Info.Zip_Archive_Format := Zip_32; exception when Zip.Headers.Bad_End => raise Zip.Archive_Corrupted with "Bad (or no) end-of-central-directory"; when Zip.Headers.Bad_Central_Header => raise Zip.Archive_Corrupted with "Bad central directory entry header"; end Load; function Is_Loaded (Info : in Zip_Info) return Boolean is (Info.Loaded); function Name (Info : in Zip_Info) return String is (Info.Zip_Input_Stream.Get_Name); function Comment (Info : in Zip_Info) return String is (Info.Zip_File_Comment.all); function Stream (Info : in Zip_Info) return not null DCF.Streams.Zipstream_Class_Access is (Info.Zip_Input_Stream); function Entries (Info : in Zip_Info) return Natural is (Info.Total_Entries); ------------ -- Delete -- ------------ procedure Delete (Info : in out Zip_Info) is procedure Delete (P : in out P_Dir_Node) is begin if P /= null then Delete (P.Left); Delete (P.Right); Dispose (P); P := null; end if; end Delete; begin Delete (Info.Dir_Binary_Tree); Dispose (Info.Zip_File_Comment); Info.Loaded := False; -- <-- added 14-Jan-2002 end Delete; procedure Traverse (Z : Zip_Info) is procedure Traverse_Tree (P : P_Dir_Node) is begin if P /= null then Traverse_Tree (P.Left); Action ((Node => P)); Traverse_Tree (P.Right); end if; end Traverse_Tree; begin Traverse_Tree (Z.Dir_Binary_Tree); end Traverse; procedure Traverse_One_File (Z : Zip_Info; Name : String) is Dn : constant P_Dir_Node := Get_Node (Z, Name); begin if Dn = null then raise File_Name_Not_Found with "Entry " & Name & " not found in " & Z.Name; end if; Action ((Node => Dn)); end Traverse_One_File; function Exists (Info : in Zip_Info; Name : in String) return Boolean is (Get_Node (Info, Name) /= null); procedure Blockread (Stream : in out DCF.Streams.Root_Zipstream_Type'Class; Buffer : out Byte_Buffer; Actually_Read : out Natural) is use Ada.Streams; use DCF.Streams; Se_Buffer : Stream_Element_Array (1 .. Buffer'Length); for Se_Buffer'Address use Buffer'Address; pragma Import (Ada, Se_Buffer); Last_Read : Stream_Element_Offset; begin Read (Stream, Se_Buffer, Last_Read); Actually_Read := Natural (Last_Read); end Blockread; procedure Blockread (Stream : in out DCF.Streams.Root_Zipstream_Type'Class; Buffer : out Byte_Buffer) is Actually_Read : Natural; begin Blockread (Stream, Buffer, Actually_Read); if Actually_Read < Buffer'Last then raise Ada.IO_Exceptions.End_Error; end if; end Blockread; procedure Blockwrite (Stream : in out Ada.Streams.Root_Stream_Type'Class; Buffer : in Byte_Buffer) is use Ada.Streams; Se_Buffer : Stream_Element_Array (1 .. Buffer'Length); for Se_Buffer'Address use Buffer'Address; pragma Import (Ada, Se_Buffer); begin Stream.Write (Se_Buffer); end Blockwrite; procedure Blockread (Stream : in out DCF.Streams.Root_Zipstream_Type'Class; Buffer : out Ada.Streams.Stream_Element_Array) is Last_Read : Ada.Streams.Stream_Element_Offset; use type Ada.Streams.Stream_Element_Offset; begin Stream.Read (Buffer, Last_Read); if Last_Read < Buffer'Last then raise Ada.IO_Exceptions.End_Error; end if; end Blockread; function Method_From_Code (Code : Unsigned_16) return Pkzip_Method is -- An enumeration clause might be more elegant, but needs -- curiously an Unchecked_Conversion... (RM 13.4) begin case Code is when Compression_Format_Code.Store => return Store; when Compression_Format_Code.Deflate => return Deflate; when others => raise Constraint_Error with "Unknown compression method " & Code'Image; end case; end Method_From_Code; procedure Copy_Chunk (From : in out DCF.Streams.Root_Zipstream_Type'Class; Into : in out Ada.Streams.Root_Stream_Type'Class; Bytes : Ada.Streams.Stream_Element_Count; Feedback : Feedback_Proc := null) is use type Ada.Streams.Stream_Element_Offset; function Percentage (Left, Right : Ada.Streams.Stream_Element_Count) return Natural is (Natural ((100.0 * Float (Left)) / Float (Right))); Buffer : Ada.Streams.Stream_Element_Array (1 .. Default_Buffer_Size); Last_Read : Ada.Streams.Stream_Element_Offset; Counted : Ada.Streams.Stream_Element_Count := 0; User_Aborting : Boolean := False; begin while Counted < Bytes loop if Feedback /= null then Feedback (Percentage (Counted, Bytes), User_Aborting); if User_Aborting then raise User_Abort; end if; end if; From.Read (Buffer, Last_Read); if Last_Read < Bytes - Counted then -- Premature end, unexpected raise Zip.Archive_Corrupted; end if; Counted := Counted + Last_Read; Into.Write (Buffer (1 .. Last_Read)); end loop; end Copy_Chunk; overriding procedure Adjust (Info : in out Zip_Info) is function Tree_Clone (P : in P_Dir_Node) return P_Dir_Node is Q : P_Dir_Node; begin if P = null then return null; else Q := new Dir_Node'(P.all); Q.Left := Tree_Clone (P.Left); Q.Right := Tree_Clone (P.Right); return Q; end if; end Tree_Clone; begin Info.Dir_Binary_Tree := Tree_Clone (Info.Dir_Binary_Tree); Info.Zip_File_Comment := new String'(Info.Zip_File_Comment.all); end Adjust; overriding procedure Finalize (Info : in out Zip_Info) is begin Delete (Info); end Finalize; end DCF.Zip;
With Ada.Text_IO.Text_Streams; Function INI.Read_INI(File_Name : String) return INI.Instance is Function Open_File(File_Name : String) return Ada.Text_IO.File_Type is use Ada.Text_IO; Begin Return Result : File_Type do Ada.Text_IO.Open( File => Result, Mode => In_File, Name => File_Name ); end return; End Open_File; INI_File : Ada.Text_IO.File_Type := Open_File(File_Name); INI_Stream : Ada.Text_IO.Text_Streams.Stream_Access renames Ada.Text_IO.Text_Streams.Stream( File => INI_File ); Use INI; Begin Return Result : Constant Instance:= Instance'Input( INI_Stream ) do Ada.Text_IO.Close( INI_File ); End return; End INI.Read_INI;
------------------------------------------------------------------------------ -- C O D E P E E R / S P A R K -- -- -- -- Copyright (C) 2015-2020, AdaCore -- -- -- -- This is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. This software is distributed in the hope that it will be useful, -- -- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN- -- -- TABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -- -- License for more details. You should have received a copy of the GNU -- -- General Public License distributed with this software; see file -- -- COPYING3. If not, go to http://www.gnu.org/licenses for a complete copy -- -- of the license. -- -- -- ------------------------------------------------------------------------------ pragma Ada_2012; with Ada.Directories; use Ada.Directories; with Ada.Strings.Unbounded.Hash; with Ada.Text_IO; use Ada.Text_IO; with GNATCOLL.JSON; use GNATCOLL.JSON; package body SA_Messages is ----------------------- -- Local subprograms -- ----------------------- function "<" (Left, Right : SA_Message) return Boolean is (if Left.Kind /= Right.Kind then Left.Kind < Right.Kind else Left.Kind in Check_Kind and then Left.Check_Result < Right.Check_Result); function "<" (Left, Right : Simple_Source_Location) return Boolean is (if Left.File_Name /= Right.File_Name then Left.File_Name < Right.File_Name elsif Left.Line /= Right.Line then Left.Line < Right.Line else Left.Column < Right.Column); function "<" (Left, Right : Source_Locations) return Boolean is (if Left'Length /= Right'Length then Left'Length < Right'Length elsif Left'Length = 0 then False elsif Left (Left'Last) /= Right (Right'Last) then Left (Left'Last) < Right (Right'Last) else Left (Left'First .. Left'Last - 1) < Right (Right'First .. Right'Last - 1)); function "<" (Left, Right : Source_Location) return Boolean is (Left.Locations < Right.Locations); function Base_Location (Location : Source_Location) return Simple_Source_Location is (Location.Locations (1)); function Hash (Key : SA_Message) return Hash_Type; function Hash (Key : Source_Location) return Hash_Type; --------- -- "<" -- --------- function "<" (Left, Right : Message_And_Location) return Boolean is (if Left.Message = Right.Message then Left.Location < Right.Location else Left.Message < Right.Message); ------------ -- Column -- ------------ function Column (Location : Source_Location) return Column_Number is (Base_Location (Location).Column); --------------- -- File_Name -- --------------- function File_Name (Location : Source_Location) return String is (To_String (Base_Location (Location).File_Name)); function File_Name (Location : Source_Location) return Unbounded_String is (Base_Location (Location).File_Name); ------------------------ -- Enclosing_Instance -- ------------------------ function Enclosing_Instance (Location : Source_Location) return Source_Location_Or_Null is (Count => Location.Count - 1, Locations => Location.Locations (2 .. Location.Count)); ---------- -- Hash -- ---------- function Hash (Key : Message_And_Location) return Hash_Type is (Hash (Key.Message) + Hash (Key.Location)); function Hash (Key : SA_Message) return Hash_Type is begin return Result : Hash_Type := Hash_Type'Mod (Message_Kind'Pos (Key.Kind)) do if Key.Kind in Check_Kind then Result := Result + Hash_Type'Mod (SA_Check_Result'Pos (Key.Check_Result)); end if; end return; end Hash; function Hash (Key : Source_Location) return Hash_Type is begin return Result : Hash_Type := Hash_Type'Mod (Key.Count) do for Loc of Key.Locations loop Result := Result + Hash (Loc.File_Name); Result := Result + Hash_Type'Mod (Loc.Line); Result := Result + Hash_Type'Mod (Loc.Column); end loop; end return; end Hash; --------------- -- Iteration -- --------------- function Iteration (Location : Source_Location) return Iteration_Id is (Base_Location (Location).Iteration); ---------- -- Line -- ---------- function Line (Location : Source_Location) return Line_Number is (Base_Location (Location).Line); -------------- -- Location -- -------------- function Location (Item : Message_And_Location) return Source_Location is (Item.Location); ---------- -- Make -- ---------- function Make (File_Name : String; Line : Line_Number; Column : Column_Number; Iteration : Iteration_Id; Enclosing_Instance : Source_Location_Or_Null) return Source_Location is begin return Result : Source_Location (Count => Enclosing_Instance.Count + 1) do Result.Locations (1) := (File_Name => To_Unbounded_String (File_Name), Line => Line, Column => Column, Iteration => Iteration); Result.Locations (2 .. Result.Count) := Enclosing_Instance.Locations; end return; end Make; ------------------ -- Make_Msg_Loc -- ------------------ function Make_Msg_Loc (Msg : SA_Message; Loc : Source_Location) return Message_And_Location is begin return Message_And_Location'(Count => Loc.Count, Message => Msg, Location => Loc); end Make_Msg_Loc; ------------- -- Message -- ------------- function Message (Item : Message_And_Location) return SA_Message is (Item.Message); package Field_Names is -- A Source_Location value is represented in JSON as a two or three -- field value having fields Message_Kind (a string) and Locations (an -- array); if the Message_Kind indicates a check kind, then a third -- field is present: Check_Result (a string). The element type of the -- Locations array is a value having at least 4 fields: -- File_Name (a string), Line (an integer), Column (an integer), -- and Iteration_Kind (an integer); if the Iteration_Kind field -- has the value corresponding to the enumeration literal Numbered, -- then two additional integer fields are present, Iteration_Number -- and Iteration_Of_Total. Check_Result : constant String := "Check_Result"; Column : constant String := "Column"; File_Name : constant String := "File_Name"; Iteration_Kind : constant String := "Iteration_Kind"; Iteration_Number : constant String := "Iteration_Number"; Iteration_Of_Total : constant String := "Iteration_Total"; Line : constant String := "Line"; Locations : constant String := "Locations"; Message_Kind : constant String := "Message_Kind"; Messages : constant String := "Messages"; end Field_Names; package body Writing is File : File_Type; -- The file to which output will be written (in Close, not in Write) Messages : JSON_Array; -- Successive calls to Write append messages to this list ----------------------- -- Local subprograms -- ----------------------- function To_JSON_Array (Locations : Source_Locations) return JSON_Array; -- Represent a Source_Locations array as a JSON_Array function To_JSON_Value (Location : Simple_Source_Location) return JSON_Value; -- Represent a Simple_Source_Location as a JSON_Value ----------- -- Close -- ----------- procedure Close is Value : constant JSON_Value := Create_Object; begin -- only one field for now Set_Field (Value, Field_Names.Messages, Messages); Put_Line (File, Write (Item => Value, Compact => False)); Clear (Messages); Close (File => File); end Close; ------------- -- Is_Open -- ------------- function Is_Open return Boolean is (Is_Open (File)); ---------- -- Open -- ---------- procedure Open (File_Name : String) is begin Create (File => File, Mode => Out_File, Name => File_Name); Clear (Messages); end Open; ------------------- -- To_JSON_Array -- ------------------- function To_JSON_Array (Locations : Source_Locations) return JSON_Array is begin return Result : JSON_Array := Empty_Array do for Location of Locations loop Append (Result, To_JSON_Value (Location)); end loop; end return; end To_JSON_Array; ------------------- -- To_JSON_Value -- ------------------- function To_JSON_Value (Location : Simple_Source_Location) return JSON_Value is begin return Result : constant JSON_Value := Create_Object do Set_Field (Result, Field_Names.File_Name, Location.File_Name); Set_Field (Result, Field_Names.Line, Integer (Location.Line)); Set_Field (Result, Field_Names.Column, Integer (Location.Column)); Set_Field (Result, Field_Names.Iteration_Kind, Integer'( Iteration_Kind'Pos (Location.Iteration.Kind))); if Location.Iteration.Kind = Numbered then Set_Field (Result, Field_Names.Iteration_Number, Location.Iteration.Number); Set_Field (Result, Field_Names.Iteration_Of_Total, Location.Iteration.Of_Total); end if; end return; end To_JSON_Value; ----------- -- Write -- ----------- procedure Write (Message : SA_Message; Location : Source_Location) is Value : constant JSON_Value := Create_Object; begin Set_Field (Value, Field_Names.Message_Kind, Message.Kind'Img); if Message.Kind in Check_Kind then Set_Field (Value, Field_Names.Check_Result, Message.Check_Result'Img); end if; Set_Field (Value, Field_Names.Locations, To_JSON_Array (Location.Locations)); Append (Messages, Value); end Write; end Writing; package body Reading is File : File_Type; -- The file from which messages are read (in Open, not in Read) Messages : JSON_Array; -- The list of messages that were read in from File Next_Index : Positive; -- The index of the message in Messages which will be returned by the -- next call to Get. Parse_Full_Path : Boolean := True; -- if the full path or only the base name of the file should be parsed ----------- -- Close -- ----------- procedure Close is begin Clear (Messages); Close (File); end Close; ---------- -- Done -- ---------- function Done return Boolean is (Next_Index > Length (Messages)); --------- -- Get -- --------- function Get return Message_And_Location is Value : constant JSON_Value := Get (Messages, Next_Index); function Get_Message (Kind : Message_Kind) return SA_Message; -- Return SA_Message of given kind, filling in any non-discriminant -- by reading from Value. function Make (Location : Source_Location; Message : SA_Message) return Message_And_Location; -- Constructor function To_Location (Encoded : JSON_Array; Full_Path : Boolean) return Source_Location; -- Decode a Source_Location from JSON_Array representation function To_Simple_Location (Encoded : JSON_Value; Full_Path : Boolean) return Simple_Source_Location; -- Decode a Simple_Source_Location from JSON_Value representation ----------------- -- Get_Message -- ----------------- function Get_Message (Kind : Message_Kind) return SA_Message is begin -- If we had AI12-0086, then we could use aggregates here (which -- would be better than field-by-field assignment for the usual -- maintainability reasons). But we don't, so we won't. return Result : SA_Message (Kind => Kind) do if Kind in Check_Kind then Result.Check_Result := SA_Check_Result'Value (Get (Value, Field_Names.Check_Result)); end if; end return; end Get_Message; ---------- -- Make -- ---------- function Make (Location : Source_Location; Message : SA_Message) return Message_And_Location is (Count => Location.Count, Message => Message, Location => Location); ----------------- -- To_Location -- ----------------- function To_Location (Encoded : JSON_Array; Full_Path : Boolean) return Source_Location is begin return Result : Source_Location (Count => Length (Encoded)) do for I in Result.Locations'Range loop Result.Locations (I) := To_Simple_Location (Get (Encoded, I), Full_Path); end loop; end return; end To_Location; ------------------------ -- To_Simple_Location -- ------------------------ function To_Simple_Location (Encoded : JSON_Value; Full_Path : Boolean) return Simple_Source_Location is function Get_Iteration_Id (Kind : Iteration_Kind) return Iteration_Id; -- Given the discriminant for an Iteration_Id value, return the -- entire value. ---------------------- -- Get_Iteration_Id -- ---------------------- function Get_Iteration_Id (Kind : Iteration_Kind) return Iteration_Id is begin -- Initialize non-discriminant fields, if any return Result : Iteration_Id (Kind => Kind) do if Kind = Numbered then Result := (Kind => Numbered, Number => Get (Encoded, Field_Names.Iteration_Number), Of_Total => Get (Encoded, Field_Names.Iteration_Of_Total)); end if; end return; end Get_Iteration_Id; -- Local variables FN : constant Unbounded_String := Get (Encoded, Field_Names.File_Name); -- Start of processing for To_Simple_Location begin return (File_Name => (if Full_Path then FN else To_Unbounded_String (Simple_Name (To_String (FN)))), Line => Line_Number (Integer'(Get (Encoded, Field_Names.Line))), Column => Column_Number (Integer'(Get (Encoded, Field_Names.Column))), Iteration => Get_Iteration_Id (Kind => Iteration_Kind'Val (Integer'(Get (Encoded, Field_Names.Iteration_Kind))))); end To_Simple_Location; -- Start of processing for Get begin Next_Index := Next_Index + 1; return Make (Message => Get_Message (Message_Kind'Value (Get (Value, Field_Names.Message_Kind))), Location => To_Location (Get (Value, Field_Names.Locations), Parse_Full_Path)); end Get; ------------- -- Is_Open -- ------------- function Is_Open return Boolean is (Is_Open (File)); ---------- -- Open -- ---------- procedure Open (File_Name : String; Full_Path : Boolean := True) is File_Text : Unbounded_String := Null_Unbounded_String; begin Parse_Full_Path := Full_Path; Open (File => File, Mode => In_File, Name => File_Name); -- File read here, not in Get, but that's an implementation detail while not End_Of_File (File) loop Append (File_Text, Get_Line (File)); end loop; Messages := Get (Read (File_Text), Field_Names.Messages); Next_Index := 1; end Open; end Reading; end SA_Messages;
package Shapes is pragma Elaborate_Body; type Float_T is digits 6; type Vertex_T is record X : Float_T; Y : Float_T; end record; type Vertices_T is array (Positive range <>) of Vertex_T; -- Create abstract Shape_T with some information -- Create primitive subprograms to get/set object description, -- number of sides, and perimeter -- Create concrete Quadrilateral type which is a shape with 4 sides -- Implement primitive subprograms as needed -- Create concrete Square type which is a Quadrilateral with all 4 sides -- of the same length. -- Implement primitive subprograms as needed -- Create concrete Triangle type which is a shape with 3 sides -- Implement primitive subprograms as needed end Shapes;
package collada.Library.visual_scenes -- -- Models a collada 'visual_scenes' library, which contains node/joint hierachy info. -- is ------------ -- Transform -- type transform_Kind is (Translate, Rotate, Scale, full_Transform); type Transform (Kind : transform_Kind := transform_Kind'First) is record Sid : Text; case Kind is when Translate => Vector : Vector_3; when Rotate => Axis : Vector_3; Angle : math.Real; when Scale => Scale : Vector_3; when full_Transform => Matrix : Matrix_4x4; end case; end record; type Transform_array is array (Positive range <>) of aliased Transform; function to_Matrix (Self : in Transform) return collada.Matrix_4x4; -------- --- Node -- type Node is tagged private; type Node_view is access all Node; type Nodes is array (Positive range <>) of Node_view; function Sid (Self : in Node) return Text; function Id (Self : in Node) return Text; function Name (Self : in Node) return Text; procedure Sid_is (Self : in out Node; Now : in Text); procedure Id_is (Self : in out Node; Now : in Text); procedure Name_is (Self : in out Node; Now : in Text); procedure add (Self : in out Node; the_Transform : in Transform); function Transforms (Self : in Node) return Transform_array; function fetch_Transform (Self : access Node; transform_Sid : in String) return access Transform; function local_Transform (Self : in Node) return Matrix_4x4; -- -- Returns the result of combining all 'Transforms'. function global_Transform (Self : in Node) return Matrix_4x4; -- -- Returns the result of combining 'local_Transform' with each ancestors 'local_Transform'. function full_Transform (Self : in Node) return Matrix_4x4; function Translation (Self : in Node) return Vector_3; function Rotate_Z (Self : in Node) return Vector_4; function Rotate_Y (Self : in Node) return Vector_4; function Rotate_X (Self : in Node) return Vector_4; function Scale (Self : in Node) return Vector_3; procedure set_x_rotation_Angle (Self : in out Node; To : in math.Real); procedure set_y_rotation_Angle (Self : in out Node; To : in math.Real); procedure set_z_rotation_Angle (Self : in out Node; To : in math.Real); procedure set_Location (Self : in out Node; To : in math.Vector_3); procedure set_Location_x (Self : in out Node; To : in math.Real); procedure set_Location_y (Self : in out Node; To : in math.Real); procedure set_Location_z (Self : in out Node; To : in math.Real); procedure set_Transform (Self : in out Node; To : in math.Matrix_4x4); function Parent (Self : in Node) return Node_view; procedure Parent_is (Self : in out Node; Now : Node_view); function Children (Self : in Node) return Nodes; function Child (Self : in Node; Which : in Positive) return Node_view; function Child (Self : in Node; Named : in String ) return Node_view; procedure add (Self : in out Node; the_Child : in Node_view); Transform_not_found : exception; ---------------- --- visual_Scene -- type visual_Scene is record Id : Text; Name : Text; root_Node : Node_view; end record; type visual_Scene_array is array (Positive range <>) of visual_Scene; ---------------- --- Library Item -- type Item is record Contents : access visual_Scene_array; skeletal_Root : Text; end record; private type Transform_array_view is access all Transform_array; type Nodes_view is access all Nodes; type Node is tagged record Sid : Text; Id : Text; Name : Text; Transforms : Transform_array_view; Parent : Node_view; Children : Nodes_view; end record; end collada.Library.visual_scenes;
pragma Style_Checks (Off); -- This spec has been automatically generated from STM32H743x.svd pragma Restrictions (No_Elaboration_Code); with HAL; with System; package STM32_SVD.SPI is pragma Preelaborate; --------------- -- Registers -- --------------- -- control register 1 type CR1_Register is record -- Serial Peripheral Enable SPE : Boolean := False; -- unspecified Reserved_1_7 : HAL.UInt7 := 16#0#; -- Master automatic SUSP in Receive mode MASRX : Boolean := False; -- Read-only. Master transfer start CSTART : Boolean := False; -- Write-only. Master SUSPend request CSUSP : Boolean := False; -- Rx/Tx direction at Half-duplex mode HDDIR : Boolean := False; -- Internal SS signal input level SSI : Boolean := False; -- 32-bit CRC polynomial configuration CRC33_17 : Boolean := False; -- CRC calculation initialization pattern control for receiver RCRCI : Boolean := False; -- CRC calculation initialization pattern control for transmitter TCRCI : Boolean := False; -- Read-only. Locking the AF configuration of associated IOs IOLOCK : Boolean := False; -- unspecified Reserved_17_31 : HAL.UInt15 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CR1_Register use record SPE at 0 range 0 .. 0; Reserved_1_7 at 0 range 1 .. 7; MASRX at 0 range 8 .. 8; CSTART at 0 range 9 .. 9; CSUSP at 0 range 10 .. 10; HDDIR at 0 range 11 .. 11; SSI at 0 range 12 .. 12; CRC33_17 at 0 range 13 .. 13; RCRCI at 0 range 14 .. 14; TCRCI at 0 range 15 .. 15; IOLOCK at 0 range 16 .. 16; Reserved_17_31 at 0 range 17 .. 31; end record; subtype CR2_TSIZE_Field is HAL.UInt16; subtype CR2_TSER_Field is HAL.UInt16; -- control register 2 type CR2_Register is record -- Number of data at current transfer TSIZE : CR2_TSIZE_Field := 16#0#; -- Read-only. Number of data transfer extension to be reload into TSIZE -- just when a previous TSER : CR2_TSER_Field := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CR2_Register use record TSIZE at 0 range 0 .. 15; TSER at 0 range 16 .. 31; end record; subtype CFG1_DSIZE_Field is HAL.UInt5; subtype CFG1_FTHVL_Field is HAL.UInt4; subtype CFG1_UDRCFG_Field is HAL.UInt2; subtype CFG1_UDRDET_Field is HAL.UInt2; subtype CFG1_CRCSIZE_Field is HAL.UInt5; subtype CFG1_MBR_Field is HAL.UInt3; -- configuration register 1 type CFG1_Register is record -- Number of bits in at single SPI data frame DSIZE : CFG1_DSIZE_Field := 16#7#; -- threshold level FTHVL : CFG1_FTHVL_Field := 16#0#; -- Behavior of slave transmitter at underrun condition UDRCFG : CFG1_UDRCFG_Field := 16#0#; -- Detection of underrun condition at slave transmitter UDRDET : CFG1_UDRDET_Field := 16#0#; -- unspecified Reserved_13_13 : HAL.Bit := 16#0#; -- Rx DMA stream enable RXDMAEN : Boolean := False; -- Tx DMA stream enable TXDMAEN : Boolean := False; -- Length of CRC frame to be transacted and compared CRCSIZE : CFG1_CRCSIZE_Field := 16#7#; -- unspecified Reserved_21_21 : HAL.Bit := 16#0#; -- Hardware CRC computation enable CRCEN : Boolean := False; -- unspecified Reserved_23_27 : HAL.UInt5 := 16#0#; -- Master baud rate MBR : CFG1_MBR_Field := 16#0#; -- unspecified Reserved_31_31 : HAL.Bit := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CFG1_Register use record DSIZE at 0 range 0 .. 4; FTHVL at 0 range 5 .. 8; UDRCFG at 0 range 9 .. 10; UDRDET at 0 range 11 .. 12; Reserved_13_13 at 0 range 13 .. 13; RXDMAEN at 0 range 14 .. 14; TXDMAEN at 0 range 15 .. 15; CRCSIZE at 0 range 16 .. 20; Reserved_21_21 at 0 range 21 .. 21; CRCEN at 0 range 22 .. 22; Reserved_23_27 at 0 range 23 .. 27; MBR at 0 range 28 .. 30; Reserved_31_31 at 0 range 31 .. 31; end record; subtype CFG2_MSSI_Field is HAL.UInt4; subtype CFG2_MIDI_Field is HAL.UInt4; subtype CFG2_COMM_Field is HAL.UInt2; subtype CFG2_SP_Field is HAL.UInt3; -- configuration register 2 type CFG2_Register is record -- Master SS Idleness MSSI : CFG2_MSSI_Field := 16#0#; -- Master Inter-Data Idleness MIDI : CFG2_MIDI_Field := 16#0#; -- unspecified Reserved_8_14 : HAL.UInt7 := 16#0#; -- Swap functionality of MISO and MOSI pins IOSWP : Boolean := False; -- unspecified Reserved_16_16 : HAL.Bit := 16#0#; -- SPI Communication Mode COMM : CFG2_COMM_Field := 16#0#; -- Serial Protocol SP : CFG2_SP_Field := 16#0#; -- SPI Master MASTER : Boolean := False; -- Data frame format LSBFRST : Boolean := False; -- Clock phase CPHA : Boolean := False; -- Clock polarity CPOL : Boolean := False; -- Software management of SS signal input SSM : Boolean := False; -- unspecified Reserved_27_27 : HAL.Bit := 16#0#; -- SS input/output polarity SSIOP : Boolean := False; -- SS output enable SSOE : Boolean := False; -- SS output management in master mode SSOM : Boolean := False; -- Alternate function GPIOs control AFCNTR : Boolean := False; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CFG2_Register use record MSSI at 0 range 0 .. 3; MIDI at 0 range 4 .. 7; Reserved_8_14 at 0 range 8 .. 14; IOSWP at 0 range 15 .. 15; Reserved_16_16 at 0 range 16 .. 16; COMM at 0 range 17 .. 18; SP at 0 range 19 .. 21; MASTER at 0 range 22 .. 22; LSBFRST at 0 range 23 .. 23; CPHA at 0 range 24 .. 24; CPOL at 0 range 25 .. 25; SSM at 0 range 26 .. 26; Reserved_27_27 at 0 range 27 .. 27; SSIOP at 0 range 28 .. 28; SSOE at 0 range 29 .. 29; SSOM at 0 range 30 .. 30; AFCNTR at 0 range 31 .. 31; end record; -- Interrupt Enable Register type IER_Register is record -- RXP Interrupt Enable RXPIE : Boolean := False; -- Read-only. TXP interrupt enable TXPIE : Boolean := False; -- Read-only. DXP interrupt enabled DPXPIE : Boolean := False; -- EOT, SUSP and TXC interrupt enable EOTIE : Boolean := False; -- TXTFIE interrupt enable TXTFIE : Boolean := False; -- UDR interrupt enable UDRIE : Boolean := False; -- OVR interrupt enable OVRIE : Boolean := False; -- CRC Interrupt enable CRCEIE : Boolean := False; -- TIFRE interrupt enable TIFREIE : Boolean := False; -- Mode Fault interrupt enable MODFIE : Boolean := False; -- Additional number of transactions reload interrupt enable TSERFIE : Boolean := False; -- unspecified Reserved_11_31 : HAL.UInt21 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for IER_Register use record RXPIE at 0 range 0 .. 0; TXPIE at 0 range 1 .. 1; DPXPIE at 0 range 2 .. 2; EOTIE at 0 range 3 .. 3; TXTFIE at 0 range 4 .. 4; UDRIE at 0 range 5 .. 5; OVRIE at 0 range 6 .. 6; CRCEIE at 0 range 7 .. 7; TIFREIE at 0 range 8 .. 8; MODFIE at 0 range 9 .. 9; TSERFIE at 0 range 10 .. 10; Reserved_11_31 at 0 range 11 .. 31; end record; subtype SR_RXPLVL_Field is HAL.UInt2; subtype SR_CTSIZE_Field is HAL.UInt16; -- Status Register type SR_Register is record -- Read-only. Rx-Packet available RXP : Boolean; -- Read-only. Tx-Packet space available TXP : Boolean; -- Read-only. Duplex Packet DXP : Boolean; -- Read-only. End Of Transfer EOT : Boolean; -- Read-only. Transmission Transfer Filled TXTF : Boolean; -- Read-only. Underrun at slave transmission mode UDR : Boolean; -- Read-only. Overrun OVR : Boolean; -- Read-only. CRC Error CRCE : Boolean; -- Read-only. TI frame format error TIFRE : Boolean; -- Read-only. Mode Fault MODF : Boolean; -- Read-only. Additional number of SPI data to be transacted was reload TSERF : Boolean; -- Read-only. SUSPend SUSP : Boolean; -- Read-only. TxFIFO transmission complete TXC : Boolean; -- Read-only. RxFIFO Packing LeVeL RXPLVL : SR_RXPLVL_Field; -- Read-only. RxFIFO Word Not Empty RXWNE : Boolean; -- Read-only. Number of data frames remaining in current TSIZE session CTSIZE : SR_CTSIZE_Field; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for SR_Register use record RXP at 0 range 0 .. 0; TXP at 0 range 1 .. 1; DXP at 0 range 2 .. 2; EOT at 0 range 3 .. 3; TXTF at 0 range 4 .. 4; UDR at 0 range 5 .. 5; OVR at 0 range 6 .. 6; CRCE at 0 range 7 .. 7; TIFRE at 0 range 8 .. 8; MODF at 0 range 9 .. 9; TSERF at 0 range 10 .. 10; SUSP at 0 range 11 .. 11; TXC at 0 range 12 .. 12; RXPLVL at 0 range 13 .. 14; RXWNE at 0 range 15 .. 15; CTSIZE at 0 range 16 .. 31; end record; -- Interrupt/Status Flags Clear Register type IFCR_Register is record -- unspecified Reserved_0_2 : HAL.UInt3 := 16#0#; -- Write-only. End Of Transfer flag clear EOTC : Boolean := False; -- Write-only. Transmission Transfer Filled flag clear TXTFC : Boolean := False; -- Write-only. Underrun flag clear UDRC : Boolean := False; -- Write-only. Overrun flag clear OVRC : Boolean := False; -- Write-only. CRC Error flag clear CRCEC : Boolean := False; -- Write-only. TI frame format error flag clear TIFREC : Boolean := False; -- Write-only. Mode Fault flag clear MODFC : Boolean := False; -- Write-only. TSERFC flag clear TSERFC : Boolean := False; -- Write-only. SUSPend flag clear SUSPC : Boolean := False; -- unspecified Reserved_12_31 : HAL.UInt20 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for IFCR_Register use record Reserved_0_2 at 0 range 0 .. 2; EOTC at 0 range 3 .. 3; TXTFC at 0 range 4 .. 4; UDRC at 0 range 5 .. 5; OVRC at 0 range 6 .. 6; CRCEC at 0 range 7 .. 7; TIFREC at 0 range 8 .. 8; MODFC at 0 range 9 .. 9; TSERFC at 0 range 10 .. 10; SUSPC at 0 range 11 .. 11; Reserved_12_31 at 0 range 12 .. 31; end record; subtype I2SCFGR_I2SCFG_Field is HAL.UInt3; subtype I2SCFGR_I2SSTD_Field is HAL.UInt2; subtype I2SCFGR_DATLEN_Field is HAL.UInt2; subtype I2SCFGR_I2SDIV_Field is HAL.UInt8; -- SPI/I2S configuration register type I2SCFGR_Register is record -- I2S mode selection I2SMOD : Boolean := False; -- I2S configuration mode I2SCFG : I2SCFGR_I2SCFG_Field := 16#0#; -- I2S standard selection I2SSTD : I2SCFGR_I2SSTD_Field := 16#0#; -- unspecified Reserved_6_6 : HAL.Bit := 16#0#; -- PCM frame synchronization PCMSYNC : Boolean := False; -- Data length to be transferred DATLEN : I2SCFGR_DATLEN_Field := 16#0#; -- Channel length (number of bits per audio channel) CHLEN : Boolean := False; -- Serial audio clock polarity CKPOL : Boolean := False; -- Word select inversion FIXCH : Boolean := False; -- Fixed channel length in SLAVE WSINV : Boolean := False; -- Data format DATFMT : Boolean := False; -- unspecified Reserved_15_15 : HAL.Bit := 16#0#; -- I2S linear prescaler I2SDIV : I2SCFGR_I2SDIV_Field := 16#0#; -- Odd factor for the prescaler ODD : Boolean := False; -- Master clock output enable MCKOE : Boolean := False; -- unspecified Reserved_26_31 : HAL.UInt6 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for I2SCFGR_Register use record I2SMOD at 0 range 0 .. 0; I2SCFG at 0 range 1 .. 3; I2SSTD at 0 range 4 .. 5; Reserved_6_6 at 0 range 6 .. 6; PCMSYNC at 0 range 7 .. 7; DATLEN at 0 range 8 .. 9; CHLEN at 0 range 10 .. 10; CKPOL at 0 range 11 .. 11; FIXCH at 0 range 12 .. 12; WSINV at 0 range 13 .. 13; DATFMT at 0 range 14 .. 14; Reserved_15_15 at 0 range 15 .. 15; I2SDIV at 0 range 16 .. 23; ODD at 0 range 24 .. 24; MCKOE at 0 range 25 .. 25; Reserved_26_31 at 0 range 26 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- Serial peripheral interface type SPI_Peripheral is record -- control register 1 CR1 : aliased CR1_Register; -- control register 2 CR2 : aliased CR2_Register; -- configuration register 1 CFG1 : aliased CFG1_Register; -- configuration register 2 CFG2 : aliased CFG2_Register; -- Interrupt Enable Register IER : aliased IER_Register; -- Status Register SR : aliased SR_Register; -- Interrupt/Status Flags Clear Register IFCR : aliased IFCR_Register; -- Transmit Data Register TXDR : aliased HAL.UInt32; -- Receive Data Register RXDR : aliased HAL.UInt32; -- Polynomial Register CRCPOLY : aliased HAL.UInt32; -- Transmitter CRC Register TXCRC : aliased HAL.UInt32; -- Receiver CRC Register RXCRC : aliased HAL.UInt32; -- Underrun Data Register UDRDR : aliased HAL.UInt32; -- SPI/I2S configuration register I2SCFGR : aliased I2SCFGR_Register; end record with Volatile; for SPI_Peripheral use record CR1 at 16#0# range 0 .. 31; CR2 at 16#4# range 0 .. 31; CFG1 at 16#8# range 0 .. 31; CFG2 at 16#C# range 0 .. 31; IER at 16#10# range 0 .. 31; SR at 16#14# range 0 .. 31; IFCR at 16#18# range 0 .. 31; TXDR at 16#20# range 0 .. 31; RXDR at 16#30# range 0 .. 31; CRCPOLY at 16#40# range 0 .. 31; TXCRC at 16#44# range 0 .. 31; RXCRC at 16#48# range 0 .. 31; UDRDR at 16#4C# range 0 .. 31; I2SCFGR at 16#50# range 0 .. 31; end record; -- Serial peripheral interface SPI1_Periph : aliased SPI_Peripheral with Import, Address => SPI1_Base; -- Serial peripheral interface SPI2_Periph : aliased SPI_Peripheral with Import, Address => SPI2_Base; -- Serial peripheral interface SPI3_Periph : aliased SPI_Peripheral with Import, Address => SPI3_Base; -- Serial peripheral interface SPI4_Periph : aliased SPI_Peripheral with Import, Address => SPI4_Base; -- Serial peripheral interface SPI5_Periph : aliased SPI_Peripheral with Import, Address => SPI5_Base; -- Serial peripheral interface SPI6_Periph : aliased SPI_Peripheral with Import, Address => SPI6_Base; end STM32_SVD.SPI;
with Es_Par; with Listas_Enteros; procedure Crear_Sublista_Pares is new Listas_Enteros.Crear_Sublista(Cuantos => 4, Filtro => Es_Par);
------------------------------------------------------------------------------ -- -- -- GNAT RUNTIME COMPONENTS -- -- -- -- A D A . N U M E R I C S -- -- -- -- S p e c -- -- -- -- $Revision: 2 $ -- -- -- -- This specification is adapted from the Ada Reference Manual for use with -- -- GNAT. In accordance with the copyright of that document, you can freely -- -- copy and modify this specification, provided that if you redistribute a -- -- modified version, any changes that you have made are clearly indicated. -- -- -- ------------------------------------------------------------------------------ with Ada.Numerics.Generic_Complex_Types; generic with package Complex_Types is new Ada.Numerics.Generic_Complex_Types (<>); use Complex_Types; package Ada.Numerics.Generic_Complex_Elementary_Functions is function Sqrt (X : Complex) return Complex; function Log (X : Complex) return Complex; function Exp (X : Complex) return Complex; function Exp (X : Imaginary) return Complex; function "**" (Left : Complex; Right : Complex) return Complex; function "**" (Left : Complex; Right : Float'Base) return Complex; function "**" (Left : Float'Base; Right : Complex) return Complex; function Sin (X : Complex) return Complex; function Cos (X : Complex) return Complex; function Tan (X : Complex) return Complex; function Cot (X : Complex) return Complex; function Arcsin (X : Complex) return Complex; function Arccos (X : Complex) return Complex; function Arctan (X : Complex) return Complex; function Arccot (X : Complex) return Complex; function Sinh (X : Complex) return Complex; function Cosh (X : Complex) return Complex; function Tanh (X : Complex) return Complex; function Coth (X : Complex) return Complex; function Arcsinh (X : Complex) return Complex; function Arccosh (X : Complex) return Complex; function Arctanh (X : Complex) return Complex; function Arccoth (X : Complex) return Complex; end Ada.Numerics.Generic_Complex_Elementary_Functions;
----------------------------------------------------------------------- -- util-streams-buffered-lzma -- LZMA streams -- Copyright (C) 2018, 2019 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Lzma.Base; use Lzma; package Util.Streams.Buffered.Lzma is -- ----------------------- -- Compress stream -- ----------------------- -- The <b>Compress_Stream</b> is an output stream which uses the LZMA encoder to -- compress the data before writing it to the output. type Compress_Stream is limited new Util.Streams.Buffered.Output_Buffer_Stream with private; -- Initialize the stream to write on the given stream. -- An internal buffer is allocated for writing the stream. overriding procedure Initialize (Stream : in out Compress_Stream; Output : access Output_Stream'Class; Size : in Positive); -- Close the sink. overriding procedure Close (Stream : in out Compress_Stream); -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Compress_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Flush the buffer by writing on the output stream. -- Raises Data_Error if there is no output stream. overriding procedure Flush (Stream : in out Compress_Stream); -- ----------------------- -- Compress stream -- ----------------------- -- The <b>Compress_Stream</b> is an output stream which uses the LZMA encoder to -- compress the data before writing it to the output. type Decompress_Stream is limited new Util.Streams.Buffered.Input_Buffer_Stream with private; -- Initialize the stream to write on the given stream. -- An internal buffer is allocated for writing the stream. overriding procedure Initialize (Stream : in out Decompress_Stream; Input : access Input_Stream'Class; Size : in Positive); -- Write the buffer array to the output stream. overriding procedure Read (Stream : in out Decompress_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); private type Compress_Stream is limited new Util.Streams.Buffered.Output_Buffer_Stream with record Stream : aliased Base.lzma_stream := Base.LZMA_STREAM_INIT; end record; -- Flush the stream and release the buffer. overriding procedure Finalize (Object : in out Compress_Stream); type Decompress_Stream is limited new Util.Streams.Buffered.Input_Buffer_Stream with record Stream : aliased Base.lzma_stream := Base.LZMA_STREAM_INIT; Action : Base.lzma_action := Base.LZMA_RUN; end record; -- Flush the stream and release the buffer. overriding procedure Finalize (Object : in out Decompress_Stream); end Util.Streams.Buffered.Lzma;
package FLTK.Widgets.Charts is type Chart is new Widget with private; type Chart_Reference (Data : not null access Chart'Class) is limited null record with Implicit_Dereference => Data; package Forge is function Create (X, Y, W, H : in Integer; Text : in String) return Chart; end Forge; procedure Add (This : in out Chart; Data_Value : in Long_Float; Data_Label : in String := ""; Data_Color : in Color := No_Color); procedure Insert (This : in out Chart; Position : in Natural; Data_Value : in Long_Float; Data_Label : in String := ""; Data_Color : in Color := No_Color); procedure Replace (This : in out Chart; Position : in Natural; Data_Value : in Long_Float; Data_Label : in String := ""; Data_Color : in Color := No_Color); procedure Clear (This : in out Chart); function Will_Autosize (This : in Chart) return Boolean; procedure Set_Autosize (This : in out Chart; To : in Boolean); procedure Get_Bounds (This : in Chart; Lower, Upper : out Long_Float); procedure Set_Bounds (This : in out Chart; Lower, Upper : in Long_Float); function Get_Maximum_Size (This : in Chart) return Natural; procedure Set_Maximum_Size (This : in out Chart; To : in Natural); function Get_Size (This : in Chart) return Natural; function Get_Text_Color (This : in Chart) return Color; procedure Set_Text_Color (This : in out Chart; To : in Color); function Get_Text_Font (This : in Chart) return Font_Kind; procedure Set_Text_Font (This : in out Chart; To : in Font_Kind); function Get_Text_Size (This : in Chart) return Font_Size; procedure Set_Text_Size (This : in out Chart; To : in Font_Size); procedure Resize (This : in out Chart; W, H : in Integer); procedure Draw (This : in out Chart); function Handle (This : in out Chart; Event : in Event_Kind) return Event_Outcome; private type Chart is new Widget with null record; overriding procedure Finalize (This : in out Chart); pragma Inline (Add); pragma Inline (Insert); pragma Inline (Replace); pragma Inline (Clear); pragma Inline (Will_Autosize); pragma Inline (Set_Autosize); pragma Inline (Get_Bounds); pragma Inline (Set_Bounds); pragma Inline (Get_Maximum_Size); pragma Inline (Set_Maximum_Size); pragma Inline (Get_Size); pragma Inline (Get_Text_Color); pragma Inline (Set_Text_Color); pragma Inline (Get_Text_Font); pragma Inline (Set_Text_Font); pragma Inline (Get_Text_Size); pragma Inline (Set_Text_Size); pragma Inline (Resize); pragma Inline (Draw); pragma Inline (Handle); end FLTK.Widgets.Charts;
with Ada.Characters.Handling; with Ada.Numerics.Discrete_Random; use Ada; use Ada.Characters; package body Solitaire_Operations is function Value (Card : Card_Value) return Card_Value is begin -- Value if Card >= Card_Value'Last then return Card_Value'Last - 1; else return Card; end if; end Value; package Random is new Numerics.Discrete_Random (Card_Value); procedure Swap (Left : in out Card_Value; Right : in out Card_Value) is Temp : constant Card_Value := Left; begin -- Swap Left := Right; Right := Temp; end Swap; pragma Inline (Swap); Gen : Random.Generator; procedure Shuffle (Deck : in out Deck_List) is begin -- Shuffle All_Cards : for I in Deck'range loop Swap (Deck (I), Deck (Random.Random (Gen) ) ); end loop All_Cards; end Shuffle; function Find (Value : Card_Value; Deck : Deck_List) return Card_Value is -- Returns the index in Deck of Value -- Note: raises Program_Error if Value not in Deck begin -- Find -- pragma Warnings (Off, "*statement missing following this statement"); -- GNAT-specific. Search : for I in Deck'range loop if Deck (I) = Value then return I; end if; end loop Search; -- pragma Warnings (On, "*statement missing following this statement"); -- GNAT-specific. end Find; procedure End_Joker_To_Front (Index : in out Card_Value; Deck : in out Deck_List) is -- If Index points to the last card of Deck, moves the last card of Deck to the front of Deck and adjusts Index begin -- End_Joker_To_Front if Index >= Deck'Last then Deck := Deck (Deck'Last) & Deck (Deck'First .. Deck'Last - 1); Index := Deck'First; end if; end End_Joker_To_Front; A_Joker : constant Card_Value := Card_Value'Last - 1; B_Joker : constant Card_Value := Card_Value'Last; procedure Move_A_Joker (Deck : in out Deck_List) is -- Moves the A Joker 1 card down Index : Card_Value := Find (A_Joker, Deck); begin -- Move_A_Joker End_Joker_To_Front (Index => Index, Deck => Deck); -- Make sure A Joker not last card of Deck Swap (Deck (Index), Deck (Index + 1) ); end Move_A_Joker; procedure Move_B_Joker (Deck : in out Deck_List) is -- Moves the B Joker 2 cards down Index : Card_Value := Find (B_Joker, Deck); begin -- Move_B_Joker End_Joker_To_Front (Index => Index, Deck => Deck); -- Make sure B Joker not last card of Deck Swap (Deck (Index), Deck (Index + 1) ); Index := Index + 1; End_Joker_To_Front (Index => Index, Deck => Deck); -- Make sure B Joker not last card of Deck Swap (Deck (Index), Deck (Index + 1) ); end Move_B_Joker; procedure Triple_Cut (Deck : in out Deck_List) is -- Perform a triple cut on Deck A_Index : constant Card_Value := Find (A_Joker, Deck); B_Index : constant Card_Value := Find (B_Joker, Deck); T_Index : constant Card_Value := Card_Value'Min (A_Index, B_Index); -- Index of top Joker L_Index : constant Card_Value := Card_Value'Max (A_Index, B_Index); -- Index of lower (bottom) Joker begin -- Triple_Cut Deck := Deck (L_Index + 1 .. Deck'Last) & Deck (T_Index .. L_Index) & Deck (Deck'First .. T_Index - 1); end Triple_Cut; pragma Inline (Triple_Cut); procedure Counted_Cut (Deck : in out Deck_List; Count : in Card_Value) is -- Perform a counted cut on Deck moving Count cards from the top to before the last card begin -- Counted_Cut Deck := Deck (Count + 1 .. Deck'Last - 1) & Deck (Deck'First .. Count) & Deck (Deck'Last); end Counted_Cut; pragma Inline (Counted_Cut); function To_Value (Char : Character) return Character_Value is begin -- To_Value return Character'Pos (Handling.To_Upper (Char) ) - Character'Pos ('A') + 1; end To_Value; pragma Inline (To_Value); procedure Key (Deck : out Deck_List; Passphrase : in String) is begin -- Key Deck := Standard_Deck; All_Characters : for I in Passphrase'range loop if Handling.Is_Letter (Passphrase (I) ) then Move_A_Joker (Deck => Deck); Move_B_Joker (Deck => Deck); Triple_Cut (Deck => Deck); Counted_Cut (Deck => Deck, Count => Value (Deck (Deck'Last) ) ); Counted_Cut (Deck => Deck, Count => Value (To_Value (Passphrase (I) ) ) ); end if; end loop All_Characters; end Key; procedure Generate (Deck : in out Deck_List; Key : out Character_Value) is Count : Card_Value; Result : Card_Value; begin -- Generate Move_A_Joker (Deck => Deck); Move_B_Joker (Deck => Deck); Triple_Cut (Deck => Deck); Counted_Cut (Deck => Deck, Count => Value (Deck (Deck'Last) ) ); -- Output card Count := Value (Deck (Deck'First) ) + 1; Result := Deck (Count); if Result in A_Joker .. B_Joker then -- Found a Joker; repeat Generate (Deck => Deck, Key => Key); else if Result > Character_Value'Last then Result := Result - Character_Value'Last; end if; Key := Result; end if; end Generate; function Add (Left : Character_Value; Right : Character_Value) return Character_Value is Result : Positive := Left + Right; begin -- Add Reduce : loop exit Reduce when Result in Character_Value; Result := Result - Character_Value'Last; end loop Reduce; return Result; end Add; function Sub (Left : Character_Value; Right : Character_Value) return Character_Value is Result : Integer := Left - Right; begin -- Sub Increase : loop exit Increase when Result in Character_Value; Result := Result + Character_Value'Last; end loop Increase; return Result; end Sub; function To_Character (Value : Character_Value) return Character is begin -- To_Character return Character'Val (Character'Pos ('A') + Value - 1); end To_Character; pragma Inline (To_Character); procedure Encrypt (Deck : in out Deck_List; Plain : in String; Crypto : out String) is Key : Character_Value; begin -- Encrypt if Plain'Length /= Crypto'Length then raise Constraint_Error; end if; All_Chars : for I in Plain'range loop Generate (Deck => Deck, Key => Key); Crypto (I - Plain'First + Crypto'First) := To_Character (Add (To_Value (Plain (I) ), Key) ); end loop All_Chars; end Encrypt; procedure Decrypt (Deck : in out Deck_List; Crypto : in String; Plain : out String) is Key : Character_Value; begin -- Decrypt if Plain'Length /= Crypto'Length then raise Constraint_Error; end if; All_Chars : for I in Crypto'range loop Generate (Deck => Deck, Key => Key); Plain (I - Crypto'First + Plain'First) := To_Character (Sub (To_Value (Crypto (I) ), Key) ); end loop All_Chars; end Decrypt; begin -- Solitaire_Operations Random.Reset (Gen); end Solitaire_Operations;
package body any_Math.any_Geometry.any_d3 is -------- -- Plane -- procedure normalise (the_Plane : in out Plane) is use Functions; inverse_Magnitude : constant Real := 1.0 / SqRt ( the_Plane (1) * the_Plane (1) + the_Plane (2) * the_Plane (2) + the_Plane (3) * the_Plane (3)); begin the_Plane (1) := the_Plane (1) * inverse_Magnitude; the_Plane (2) := the_Plane (2) * inverse_Magnitude; the_Plane (3) := the_Plane (3) * inverse_Magnitude; the_Plane (4) := the_Plane (4) * inverse_Magnitude; end normalise; function Image (the_Model : in a_Model) return String is begin return "(Site_Count =>" & Integer'Image (the_Model.Site_Count) & "," & " Tri_Count =>" & Integer'Image (the_Model. Tri_Count) & ")"; exception when others => return "<TODO>"; end Image; ---------- -- Bounds -- function to_bounding_Box (Self : Sites) return bounding_Box is Bounds : bounding_Box := null_Bounds; begin for Each in Self'Range loop Bounds.Lower (1) := Real'Min (Bounds.Lower (1), Self (Each)(1)); Bounds.Lower (2) := Real'Min (Bounds.Lower (2), Self (Each)(2)); Bounds.Lower (3) := Real'Min (Bounds.Lower (3), Self (Each)(3)); Bounds.Upper (1) := Real'Max (Bounds.Upper (1), Self (Each)(1)); Bounds.Upper (2) := Real'Max (Bounds.Upper (2), Self (Each)(2)); Bounds.Upper (3) := Real'Max (Bounds.Upper (3), Self (Each)(3)); end loop; return Bounds; end to_bounding_Box; function Extent (Self : in bounding_Box; Dimension : in Index) return Real is begin return Self.Upper (Dimension) - Self.Lower (Dimension); end Extent; function "or" (Left : in bounding_Box; Right : in Site) return bounding_Box is Result : bounding_Box; begin for i in Right'Range loop if Right (i) < Left.Lower (i) then Result.Lower (i) := Right (i); else Result.Lower (i) := Left.Lower (i); end if; if Right (i) > Left.Upper (i) then Result.Upper (i) := Right (i); else Result.Upper (i) := Left.Upper (i); end if; end loop; return Result; end "or"; function "or" (Left : in bounding_Box; Right : in bounding_Box) return bounding_Box is Result : bounding_Box := Left or Right.Lower; begin Result := Result or Right.Upper; return Result; end "or"; function "+" (Left : in bounding_Box; Right : in Vector_3) return bounding_Box is begin return (Left.Lower + Right, Left.Upper + Right); end "+"; function Image (Self : bounding_Box) return String is begin return "(lower => " & Image (Self.Lower) & ", upper => " & Image (Self.Upper) & ")"; end Image; end any_Math.any_Geometry.any_d3;
package body afrl.cmasi.OperatingRegion.SPARK_Boundary with SPARK_Mode => Off is --------------- -- Get_Areas -- --------------- function Get_Areas (Region : OperatingRegion) return OperatingRegionAreas is InAreas : constant afrl.cmasi.OperatingRegion.Vect_Int64_Acc := Region.getKeepInAreas; OutAreas : constant afrl.cmasi.OperatingRegion.Vect_Int64_Acc := Region.getKeepInAreas; begin return R : OperatingRegionAreas do for E of InAreas.all loop Int64_Vects.Append (R.KeepInAreas, E); end loop; for E of OutAreas.all loop Int64_Vects.Append (R.KeepOutAreas, E); end loop; end return; end Get_Areas; end afrl.cmasi.OperatingRegion.SPARK_Boundary;
-- This file is generated by SWIG. Please do *not* modify by hand. -- with Interfaces.C; package osmesa_c.Pointers is -- GLenum_Pointer -- type GLenum_Pointer is access all osmesa_c.GLenum; -- GLenum_Pointers -- type GLenum_Pointers is array (Interfaces.C .size_t range <>) of aliased osmesa_c.Pointers.GLenum_Pointer; -- GLint_Pointer -- type GLint_Pointer is access all osmesa_c.GLint; -- GLint_Pointers -- type GLint_Pointers is array (Interfaces.C .size_t range <>) of aliased osmesa_c.Pointers.GLint_Pointer; -- GLsizei_Pointer -- type GLsizei_Pointer is access all osmesa_c.GLsizei; -- GLsizei_Pointers -- type GLsizei_Pointers is array (Interfaces.C .size_t range <>) of aliased osmesa_c.Pointers.GLsizei_Pointer; -- GLboolean_Pointer -- type GLboolean_Pointer is access all osmesa_c.GLboolean; -- GLboolean_Pointers -- type GLboolean_Pointers is array (Interfaces.C .size_t range <>) of aliased osmesa_c.Pointers.GLboolean_Pointer; -- OSMesaContext_Pointer -- type OSMesaContext_Pointer is access all osmesa_c.OSMesaContext; -- OSMesaContext_Pointers -- type OSMesaContext_Pointers is array (Interfaces.C .size_t range <>) of aliased osmesa_c.Pointers.OSMesaContext_Pointer; -- OSMESAproc_Pointer -- type OSMESAproc_Pointer is access all osmesa_c.OSMESAproc; -- OSMESAproc_Pointers -- type OSMESAproc_Pointers is array (Interfaces.C .size_t range <>) of aliased osmesa_c.Pointers.OSMESAproc_Pointer; end osmesa_c.Pointers;
-------------------------------------------------------------------------------- -- -- -- Copyright (C) 2004, RISC OS Ada Library (RASCAL) developers. -- -- -- -- This library is free software; you can redistribute it and/or -- -- modify it under the terms of the GNU Lesser General Public -- -- License as published by the Free Software Foundation; either -- -- version 2.1 of the License, or (at your option) any later version. -- -- -- -- This library is distributed in the hope that it will be useful, -- -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- -- Lesser General Public License for more details. -- -- -- -- You should have received a copy of the GNU Lesser General Public -- -- License along with this library; if not, write to the Free Software -- -- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -- -- -- -------------------------------------------------------------------------------- -- @brief Toolbox related types and methods. -- $Author$ -- $Date$ -- $Revision$ with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with System.Unsigned_Types; use System.Unsigned_Types; with System; use System; with Interfaces.C; use Interfaces.C; with Ada.Unchecked_Conversion; with System.Address_To_Access_Conversions; with RASCAL.Memory; use RASCAL.Memory; with RASCAL.OS; use RASCAL.OS; package RASCAL.Toolbox is type Object_Class is new Integer; Max_Object_Name : Integer := 12; type Descriptor_Block_Type is new Address; type Object_State is (Hidden, Showing); type Toolbox_SysInfo_Type is (Task_Name, Messages_File_Descriptor, Ressource_Directory, Wimp_Task_Handle, Sprite_Area); type Object_ShowType is (Default, FullSpec, TopLeft, Centre, AtPointer); type Creation_Type is (From_Template, From_Memory); type Top_Left_Type is record X : Integer; Y : Integer; end record; pragma Convention (C, Top_Left_Type); type Template_Header is record Class : Object_Class; Flags : Integer; Version : Integer; Name : Char_Array (1..12); Total_Size : Integer; Body_Ptr : System.Address; Body_Size : Integer; end record; pragma Convention (C, Template_Header); -- -- Type used by Window class for window sizing. -- type Toolbox_BBox_Type is record xmin : Integer; ymin : Integer; xmax : Integer; ymax : Integer; end record; pragma Convention (C, Toolbox_BBox_Type); type Toolbox_EventObject_Type is record Header : Toolbox_Event_Header; end record; pragma Convention (C, Toolbox_EventObject_Type); type Toolbox_MessageEvent_Type is record Self : Object_ID; Component : Component_ID; Event : Toolbox_EventObject_Type; end record; pragma Convention (C, Toolbox_MessageEvent_Type); type ResourceFile_Header_Type is record File_ID : Integer; Version_Number : Integer; Object_Offset : Integer; end record; pragma Convention (C, ResourceFile_Header_Type); type RelocationTable_Type is record Num_Relocations : Integer; Relocations : Integer; end record; pragma Convention (C, RelocationTable_Type); type Relocation_Type is record Word_To_Relocate : Integer; Directive : Integer; end record; pragma Convention (C, Relocation_Type); type Event_Interest_Type is record Code : Integer; Class : Object_Class; end record; pragma Convention (C, Event_Interest_Type); type ResourceFileObject_TemplateHeader_Type is record String_Table_Offset : Integer; Message_Table_Offset : Integer; Relocation_Table_Offset : Integer; Header : Template_Header; end record; pragma Convention (C, ResourceFileObject_TemplateHeader_Type); -- -- A Toolbox Event. -- type Reason_ToolboxEvent is null record; pragma Convention (C, Reason_ToolboxEvent); type Reason_ToolboxEvent_Pointer is access Reason_ToolboxEvent; type AWEL_Reason_ToolboxEvent is abstract new Wimp_EventListener(Reason_Event_ToolboxEvent,-1,-1) with record Event : Reason_ToolboxEvent_Pointer; end record; -- -- Raised if the Toolbox detects an error when it is not processing a Toolbox SWI. -- type Toolbox_Error is record Header : Toolbox_Event_Header; Number : Integer; Message : Char_Array (1 .. 256 - 20 - (Toolbox_Event_Header'Size/CHAR_BIT) - (Object_ID'Size/CHAR_BIT) - (Component_ID'Size/CHAR_BIT) - (Integer'Size/CHAR_BIT)); end record; pragma Convention (C, Toolbox_Error); type Toolbox_Error_Pointer is access Toolbox_Error; type ATEL_Toolbox_Error is abstract new Toolbox_EventListener(Toolbox_Event_Error,-1,-1) with record Event : Toolbox_Error_Pointer; end record; -- -- Raised after the Toolbox creates objects that have their auto-created attribute set. -- type Toolbox_ObjectAutoCreated is record Header : Toolbox_Event_Header; Template_Name : Char_Array (1 .. 256 - 20 - (Toolbox_Event_Header'Size/CHAR_BIT) - (Object_ID'Size/CHAR_BIT) - (Component_ID'Size/CHAR_BIT)); end record; pragma Convention (C, Toolbox_ObjectAutoCreated); type Toolbox_ObjectAutoCreated_Pointer is access Toolbox_ObjectAutoCreated; type ATEL_Toolbox_ObjectAutoCreated is abstract new Toolbox_EventListener(Toolbox_Event_ObjectAutoCreated,-1,-1) with record Event : Toolbox_ObjectAutoCreated_Pointer; end record; -- -- Raised after the Toolbox deletes an object. -- type Toolbox_ObjectDeleted is record Header : Toolbox_Event_Header; end record; pragma Convention (C, Toolbox_ObjectDeleted); type Toolbox_ObjectDeleted_Pointer is access Toolbox_ObjectDeleted; type ATEL_Toolbox_ObjectDeleted is abstract new Toolbox_EventListener(Toolbox_Event_ObjectDeleted,-1,-1) with record Event : Toolbox_ObjectDeleted_Pointer; end record; -- -- Creates an object, either from a named template in a res file, or from a template description block in memory. -- function Create_Object (Template : in string; Flags : in Creation_Type := From_Template) return Object_ID; -- -- Deletes a given object. By default objects attached to this object are also deleted. -- procedure Delete_Object (Object : in Object_ID; Flags : in System.Unsigned_Types.Unsigned := 0); -- -- Returns the id of the Ancestor of the given object. -- procedure Get_Ancestor (Object : in Object_ID; Ancestor : out Object_ID; Component : out Component_ID; Flags : in System.Unsigned_Types.Unsigned := 0); -- -- Returns the value of the client handle for this object. -- function Get_Client (Object : in Object_ID; Flags : in System.Unsigned_Types.Unsigned := 0) return Object_ID; -- -- Returns the class of the object. -- function Get_Class (Object : in Object_ID; Flags : in System.Unsigned_Types.Unsigned := 0) return Object_Class; -- -- Returns information regarding the state of an object. -- function Get_State (Object : in Object_ID; Flags : in System.Unsigned_Types.Unsigned := 0) return Object_State; -- -- Returns the parent of the object. -- procedure Get_Parent (Object : in Object_ID; Parent : out Object_ID; Component : out Component_ID; Flags : in System.Unsigned_Types.Unsigned := 0); -- -- Returns the name of the template used to create the object. -- function Get_Template_Name (Object : in Object_ID; Flags : in System.Unsigned_Types.Unsigned := 0) return string; -- -- Hides the object. -- procedure Hide_Object (Object : in Object_ID; Flags : in System.Unsigned_Types.Unsigned := 0); -- -- Loads the given resource file, and creates any objects which have the auto-create flag set. -- procedure Load_Resources (Filename : in string; Flags : in System.Unsigned_Types.Unsigned := 0); -- -- Sets the value of the client handle for this object. -- procedure Set_Client_Handle (Object : in Object_ID; Client : in Object_ID; Flags : in System.Unsigned_Types.Unsigned := 0); -- -- Shows the given object on screen at specific coordinates. -- procedure Show_Object_At (Object : in Object_ID; X : Integer; Y : Integer; Parent_Object : in Object_ID; Parent_Component : in Component_ID; Flags : in System.Unsigned_Types.Unsigned := 0); -- -- Shows the given object on screen. -- procedure Show_Object (Object : in Object_ID; Parent_Object : in Object_ID := 0; Parent_Component : in Component_ID := 0; Show : in Object_ShowType := Default; Flags : in System.Unsigned_Types.Unsigned := 0); -- -- Returns a pointer to a block suitable to pass to Create_Object. -- function Template_Lookup (Template_Name : in string; Flags : in System.Unsigned_Types.Unsigned := 0) return Address; -- -- Raises toolbox event. -- procedure Raise_Event (Object : in Object_ID; Component : in Component_ID; Event : in Address; Flags : in System.Unsigned_Types.Unsigned := 0); -- -- Abstract event handler for AWEL_Reason_ToolboxEvent event. -- procedure Handle (The : in AWEL_Reason_ToolboxEvent) is abstract; -- -- Abstract event handler for the ATEL_Toolbox_Error event. -- procedure Handle (The : in ATEL_Toolbox_Error) is abstract; -- -- Abstract event handler for the ATEL_Toolbox_ObjectAutoCreated event. -- procedure Handle (The : in ATEL_Toolbox_ObjectAutoCreated) is abstract; -- -- Abstract event handler for the ATEL_Toolbox_ObjectDeleted event. -- procedure Handle (The : in ATEL_Toolbox_ObjectDeleted) is abstract; end RASCAL.Toolbox;
with Device; use Device; with Memory.Container; use Memory.Container; with Memory.Join; use Memory.Join; package body Memory.Transform is procedure Process(mem : in out Transform_Type; address : in Address_Type; size : in Address_Type; dir : in Boolean; is_read : in Boolean) is abits : constant Positive := Get_Address_Bits; mask : constant Address_Type := Address_Type(2) ** abits - 1; start : Address_Type := address; trans : Address_Type := Apply(Transform_Type'Class(mem), start, dir); total : Address_Type := 0; incr : Address_Type; nsize : Address_Type; last : Address_Type; temp : Address_Type; begin trans := trans and mask; incr := Address_Type(Get_Alignment(Transform_Type'Class(mem))); while (address mod incr) /= 0 loop incr := incr / 2; end loop; while total < size loop -- Determine how big we can make the current access. last := trans; nsize := Address_Type'Min(size - total, incr); while total + nsize < size loop temp := Apply(Transform_Type'Class(mem), start + nsize, dir); temp := temp and mask; exit when ((last + nsize) and mask) /= temp; nsize := Address_Type'Min(size - total, nsize + incr); end loop; -- Perform the access. if dir and mem.bank /= null then if is_read then Read(mem.bank.all, trans, Natural(nsize)); else Write(mem.bank.all, trans, Natural(nsize)); end if; else if is_read then Read(Container_Type(mem), trans, Natural(nsize)); else Write(Container_Type(mem), trans, Natural(nsize)); end if; end if; total := total + nsize; start := start + nsize; trans := temp; end loop; end Process; procedure Set_Value(mem : in out Transform_Type; value : in Long_Integer) is begin mem.value := value; end Set_Value; function Get_Value(mem : Transform_Type) return Long_Integer is begin return mem.value; end Get_Value; function Get_Bank(mem : Transform_Type) return Memory_Pointer is begin return Memory_Pointer(mem.bank); end Get_Bank; procedure Set_Bank(mem : in out Transform_Type; bank : access Memory_Type'Class) is begin mem.bank := bank; end Set_Bank; procedure Reset(mem : in out Transform_Type; context : in Natural) is begin Reset(Container_Type(mem), context); if mem.bank /= null then Reset(mem.bank.all, context); end if; end Reset; procedure Read(mem : in out Transform_Type; address : in Address_Type; size : in Positive) is start : Time_Type; begin if mem.bank /= null then start := Get_Time(mem.bank.all); Process(mem, address, Address_Type(size), True, True); Advance(mem, Get_Time(mem.bank.all) - start); else Process(mem, address, Address_Type(size), True, True); end if; end Read; procedure Write(mem : in out Transform_Type; address : in Address_Type; size : in Positive) is start : Time_Type; begin if mem.bank /= null then start := Get_Time(mem.bank.all); Process(mem, address, Address_Type(size), True, False); Advance(mem, Get_Time(mem.bank.all) - start); else Process(mem, address, Address_Type(size), True, False); end if; end Write; procedure Forward_Read(mem : in out Transform_Type; source : in Natural; address : in Address_Type; size : in Positive) is begin Process(mem, address, Address_Type(size), False, True); end Forward_Read; procedure Forward_Write(mem : in out Transform_Type; source : in Natural; address : in Address_Type; size : in Positive) is begin Process(mem, address, Address_Type(size), False, False); end Forward_Write; procedure Forward_Idle(mem : in out Transform_Type; source : in Natural; cycles : in Time_Type) is begin Idle(Container_Type(mem), cycles); end Forward_Idle; function Forward_Get_Time(mem : Transform_Type) return Time_Type is begin return Get_Time(Container_Type(mem)); end Forward_Get_Time; function Get_Join_Length(mem : Transform_Type) return Natural is begin return Get_Transform_Length(Transform_Type'Class(mem)); end Get_Join_Length; function Get_Cost(mem : Transform_Type) return Cost_Type is result : Cost_Type := Get_Cost(Container_Type(mem)); begin if mem.bank /= null then result := result + Get_Cost(mem.bank.all); end if; return result; end Get_Cost; function Is_Empty(mem : Transform_Type) return Boolean is begin return False; end Is_Empty; function Get_Alignment(mem : Transform_Type) return Positive is begin return 1; end Get_Alignment; function To_String(mem : Transform_Type) return Unbounded_String is result : Unbounded_String; begin Append(result, "(" & Get_Name(Transform_Type'Class(mem)) & " "); if mem.value /= 0 then Append(result, "(value " & To_String(mem.value) & ")"); end if; if mem.bank /= null then Append(result, "(bank "); Append(result, To_String(To_String(mem.bank.all))); Append(result, ")"); end if; Append(result, "(memory "); Append(result, To_String(Container_Type(mem))); Append(result, ")"); Append(result, ")"); return result; end To_String; procedure Generate_Simple(mem : in Transform_Type; sigs : in out Unbounded_String; code : in out Unbounded_String) is word_bits : constant Natural := 8 * Get_Word_Size(mem); other : constant Memory_Pointer := Get_Memory(mem); name : constant String := "m" & To_String(Get_ID(mem)); oname : constant String := "m" & To_String(Get_ID(other.all)); tname : constant String := Get_Name(Transform_Type'Class(mem)); value : constant Long_Integer := mem.value; begin Generate(other.all, sigs, code); Declare_Signals(sigs, name, word_bits); -- Transform into the bank. Line(code, name & "_inst : entity work." & tname); Line(code, " generic map ("); Line(code, " ADDR_WIDTH => ADDR_WIDTH,"); Line(code, " WORD_WIDTH => " & To_String(word_bits) & ","); Line(code, " VALUE => " & To_String(value)); Line(code, " )"); Line(code, " port map ("); Line(code, " clk => clk,"); Line(code, " rst => rst,"); Line(code, " addr => " & name & "_addr,"); Line(code, " din => " & name & "_din,"); Line(code, " dout => " & name & "_dout,"); Line(code, " re => " & name & "_re,"); Line(code, " we => " & name & "_we,"); Line(code, " mask => " & name & "_mask,"); Line(code, " ready => " & name & "_ready,"); Line(code, " maddr => " & oname & "_addr,"); Line(code, " min => " & oname & "_dout,"); Line(code, " mout => " & oname & "_din,"); Line(code, " mre => " & oname & "_re,"); Line(code, " mwe => " & oname & "_we,"); Line(code, " mmask => " & oname & "_mask,"); Line(code, " mready => " & oname & "_ready"); Line(code, " );"); end Generate_Simple; procedure Generate_Banked(mem : in Transform_Type; sigs : in out Unbounded_String; code : in out Unbounded_String) is word_bits : constant Natural := 8 * Get_Word_Size(mem); bank : constant Memory_Pointer := Get_Bank(mem); join : constant Join_Pointer := Find_Join(bank); other : constant Memory_Pointer := Get_Memory(mem); name : constant String := "m" & To_String(Get_ID(mem)); bname : constant String := "m" & To_String(Get_ID(bank.all)); oname : constant String := "m" & To_String(Get_ID(other.all)); jname : constant String := "m" & To_String(Get_ID(join.all)); tname : constant String := Get_Name(Transform_Type'Class(mem)); value : constant Long_Integer := mem.value; begin Generate(other.all, sigs, code); Generate(bank.all, sigs, code); Declare_Signals(sigs, name, word_bits); -- Transform into the bank. Line(code, name & "_inst : entity work." & tname); Line(code, " generic map ("); Line(code, " ADDR_WIDTH => ADDR_WIDTH,"); Line(code, " WORD_WIDTH => " & To_String(word_bits) & ","); Line(code, " VALUE => " & To_String(value)); Line(code, " )"); Line(code, " port map ("); Line(code, " clk => clk,"); Line(code, " rst => rst,"); Line(code, " addr => " & name & "_addr,"); Line(code, " din => " & name & "_din,"); Line(code, " dout => " & name & "_dout,"); Line(code, " re => " & name & "_re,"); Line(code, " we => " & name & "_we,"); Line(code, " mask => " & name & "_mask,"); Line(code, " ready => " & name & "_ready,"); Line(code, " maddr => " & bname & "_addr,"); Line(code, " min => " & bname & "_dout,"); Line(code, " mout => " & bname & "_din,"); Line(code, " mre => " & bname & "_re,"); Line(code, " mwe => " & bname & "_we,"); Line(code, " mmask => " & bname & "_mask,"); Line(code, " mready => " & bname & "_ready"); Line(code, " );"); -- Transform out of the bank. Line(code, jname & "_inst : entity work." & tname); Line(code, " generic map ("); Line(code, " ADDR_WIDTH => ADDR_WIDTH,"); Line(code, " WORD_WIDTH => " & To_String(word_bits) & ","); Line(code, " VALUE => " & To_String(-value)); Line(code, " )"); Line(code, " port map ("); Line(code, " clk => clk,"); Line(code, " rst => rst,"); Line(code, " addr => " & jname & "_addr,"); Line(code, " din => " & jname & "_din,"); Line(code, " dout => " & jname & "_dout,"); Line(code, " re => " & jname & "_re,"); Line(code, " we => " & jname & "_we,"); Line(code, " mask => " & jname & "_mask,"); Line(code, " ready => " & jname & "_ready,"); Line(code, " maddr => " & oname & "_addr,"); Line(code, " min => " & oname & "_dout,"); Line(code, " mout => " & oname & "_din,"); Line(code, " mre => " & oname & "_re,"); Line(code, " mwe => " & oname & "_we,"); Line(code, " mmask => " & oname & "_mask,"); Line(code, " mready => " & oname & "_ready"); Line(code, " );"); end Generate_Banked; procedure Generate(mem : in Transform_Type; sigs : in out Unbounded_String; code : in out Unbounded_String) is begin if mem.bank /= null then Generate_Banked(mem, sigs, code); else Generate_Simple(mem, sigs, code); end if; end Generate; function Get_Path_Length(mem : Transform_Type) return Natural is len : Natural := Get_Transform_Length(Transform_Type'Class(mem)); begin if mem.bank /= null then len := len + Get_Path_Length(mem.bank.all); else len := len + Get_Path_Length(Container_Type(mem)); end if; return len; end Get_Path_Length; procedure Adjust(mem : in out Transform_Type) is jp : Join_Pointer; cp : Container_Pointer; ptr : Memory_Pointer; begin Adjust(Container_Type(mem)); if mem.bank /= null then mem.bank := Clone(mem.bank.all); ptr := Memory_Pointer(mem.bank); loop if ptr.all in Join_Type'Class then jp := Join_Pointer(ptr); Set_Parent(jp.all, mem'Unchecked_Access); exit; else cp := Container_Pointer(ptr); ptr := Get_Memory(cp.all); end if; end loop; end if; end Adjust; procedure Finalize(mem : in out Transform_Type) is begin Destroy(Memory_Pointer(mem.bank)); Finalize(Container_Type(mem)); end Finalize; end Memory.Transform;
with Alumnos; package Clases is Max_Alumnos : constant Integer := 100; subtype Num_Alumno is Integer range 1..Max_Alumnos; type Clase is private; procedure Inserta_Alumno (Alu : in Alumnos.Alumno; La_Clase : in out Clase); function Dame_Alumno (Num : in Num_Alumno; La_Clase : in Clase) return Alumnos.Alumno; function Numero_Alumnos (La_Clase : in Clase) return Natural; function Llena (La_Clase : in Clase) return Boolean; Private type Tipo_Alumnos is array (1..Max_Alumnos) of Alumnos.Alumno; type Clase is record Alumnos : Tipo_Alumnos; Num : Integer:=0; end record; end Clases;
-- -- The author disclaims copyright to this source code. In place of -- a legal notice, here is a blessing: -- -- May you do good and not evil. -- May you find forgiveness for yourself and forgive others. -- May you share freely, not taking more than you give. -- package Setup is Default_Template_Ada : constant String := "lempar.adb"; Default_Template_C : constant String := "lempar.c"; function Get_Program_Name return String; function Get_Program_Version return String; function Get_Build_ISO8601_UTC return String; function Get_Uname_M return String; function Get_Uname_N return String; function Get_Uname_P return String; function Get_Uname_R return String; function Get_Uname_S return String; end Setup;
-- Copyright (C) 2019 Thierry Rascle <thierr26@free.fr> -- MIT license. Please refer to the LICENSE file. with Ada.Command_Line, Apsepp.Test_Node_Class.Runner_Sequential.Create; package body Apsepp_Test_Harness is ---------------------------------------------------------------------------- procedure Apsepp_Test_Procedure is use Ada.Command_Line, Apsepp.Test_Node_Class, Apsepp.Test_Node_Class.Runner_Sequential; Test_Runner : Test_Runner_Sequential := Create (Test_Suite'Access, Reporter'Access); Outcome : Test_Outcome; begin Test_Runner.Early_Run; Test_Runner.Run (Outcome); Set_Exit_Status (if Outcome = Passed then Success else Failure); end Apsepp_Test_Procedure; ---------------------------------------------------------------------------- end Apsepp_Test_Harness;
-- Institution: Technische Universität München -- Department: Realtime Computer Systems (RCS) -- Project: StratoX -- Module: LSM303D Driver -- -- Authors: Emanuel Regnath (emanuel.regnath@tum.de) -- -- Description: Register definitions for the LSM303D -- -- ToDo: -- [ ] Implementation package LSM303D is ADDR_WHO_AM_I : constant := 0x0F WHO_I_AM : constant := 0x49 ADDR_OUT_TEMP_L : constant := 0x05; ADDR_OUT_TEMP_H : constant := 0x06; ADDR_STATUS_M : constant := 0x07; ADDR_OUT_X_L_M : constant := 0x08; ADDR_OUT_X_H_M : constant := 0x09; ADDR_OUT_Y_L_M : constant := 0x0A; ADDR_OUT_Y_H_M : constant := 0x0B; ADDR_OUT_Z_L_M : constant := 0x0C; ADDR_OUT_Z_H_M : constant := 0x0D; ADDR_INT_CTRL_M : constant := 0x12; ADDR_INT_SRC_M : constant := 0x13; ADDR_REFERENCE_X : constant := 0x1c; ADDR_REFERENCE_Y : constant := 0x1d; ADDR_REFERENCE_Z : constant := 0x1e; ADDR_STATUS_A : constant := 0x27; ADDR_OUT_X_L_A : constant := 0x28; ADDR_OUT_X_H_A : constant := 0x29; ADDR_OUT_Y_L_A : constant := 0x2A; ADDR_OUT_Y_H_A : constant := 0x2B; ADDR_OUT_Z_L_A : constant := 0x2C; ADDR_OUT_Z_H_A : constant := 0x2D; ADDR_CTRL_REG0 : constant := 0x1F; ADDR_CTRL_REG1 : constant := 0x20; ADDR_CTRL_REG2 : constant := 0x21; ADDR_CTRL_REG3 : constant := 0x22; ADDR_CTRL_REG4 : constant := 0x23; ADDR_CTRL_REG5 : constant := 0x24; ADDR_CTRL_REG6 : constant := 0x25; ADDR_CTRL_REG7 : constant := 0x26; ADDR_FIFO_CTRL : constant := 0x2e; ADDR_FIFO_SRC : constant := 0x2f; ADDR_IG_CFG1 : constant := 0x30; ADDR_IG_SRC1 : constant := 0x31; ADDR_IG_THS1 : constant := 0x32; ADDR_IG_DUR1 : constant := 0x33; ADDR_IG_CFG2 : constant := 0x34; ADDR_IG_SRC2 : constant := 0x35; ADDR_IG_THS2 : constant := 0x36; ADDR_IG_DUR2 : constant := 0x37; ADDR_CLICK_CFG : constant := 0x38; ADDR_CLICK_SRC : constant := 0x39; ADDR_CLICK_THS : constant := 0x3a; ADDR_TIME_LIMIT : constant := 0x3b; ADDR_TIME_LATENCY : constant := 0x3c; ADDR_TIME_WINDOW : constant := 0x3d; ADDR_ACT_THS : constant := 0x3e; ADDR_ACT_DUR : constant := 0x3f; end LSM303D;
-- Copyright (c) 2020 Maxim Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- package body Torrent.Shutdown is protected body Signal is entry Wait_SIGINT when SIGINT_Triggered is begin SIGINT_Triggered := False; end Wait_SIGINT; procedure Handle is begin SIGINT_Triggered := True; end Handle; end Signal; end Torrent.Shutdown;
with Irc.Bot; with Irc.Commands; with Irc.Message; with Ada.Strings.Unbounded; -- This bot simply connects to an IRC server and sticks -- around without doing much of anything. Most simplistic -- example. procedure Pong_Bot is Bot : Irc.Bot.Connection; begin -- Specify the server, port, and nick of our bot Bot := Irc.Bot.Create ("irc.tenthbit.net", 6667, Nick => "pongbot"); -- Normally, you would use Irc.Commands.Install (Bot) to add -- the standard command set. Bot.On_Message ("PING", Irc.Commands.Ping_Server'Access); -- Connect the socket and identify the bot (send NICK and USER) Bot.Connect; Bot.Identify; -- Loop until program is killed or an error occurs loop declare Line : Ada.Strings.Unbounded.Unbounded_String; Msg : Irc.Message.Message; begin Bot.Read_Line (Line); Msg := Irc.Message.Parse_Line (Line); Bot.Do_Message (Msg); -- Print out the message so we can get some feedback Msg.Print; exception when Irc.Message.Parse_Error => exit; end; end loop; -- Close the socket Bot.Disconnect; end Pong_Bot;
package My_Package is type My_Type is tagged private; procedure Some_Procedure(Item : out My_Type); function Set(Value : in Integer) return My_Type; private type My_Type is tagged record Variable : Integer := -12; end record; end My_Package;
-- Copyright 2016-2019 NXP -- All rights reserved.SPDX-License-Identifier: BSD-3-Clause -- This spec has been automatically generated from LPC55S6x.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with HAL; with System; package NXP_SVD.PLU is pragma Preelaborate; --------------- -- Registers -- --------------- ----------------------------- -- LUT cluster's Registers -- ----------------------------- -- Selects the input source to be connected to LUT0 input0. For each LUT, -- the slot associated with the output from LUTn itself is tied low. type LUT_INP_MUX_LUTn_INPx_Field is ( -- The PLU primary inputs 0. PLU_INPUTS0, -- The PLU primary inputs 1. PLU_INPUTS1, -- The PLU primary inputs 2. PLU_INPUTS2, -- The PLU primary inputs 3. PLU_INPUTS3, -- The PLU primary inputs 4. PLU_INPUTS4, -- The PLU primary inputs 5. PLU_INPUTS5, -- The output of LUT0. LUT_OUTPUTS0, -- The output of LUT1. LUT_OUTPUTS1, -- The output of LUT2. LUT_OUTPUTS2, -- The output of LUT3. LUT_OUTPUTS3, -- The output of LUT4. LUT_OUTPUTS4, -- The output of LUT5. LUT_OUTPUTS5, -- The output of LUT6. LUT_OUTPUTS6, -- The output of LUT7. LUT_OUTPUTS7, -- The output of LUT8. LUT_OUTPUTS8, -- The output of LUT9. LUT_OUTPUTS9, -- The output of LUT10. LUT_OUTPUTS10, -- The output of LUT11. LUT_OUTPUTS11, -- The output of LUT12. LUT_OUTPUTS12, -- The output of LUT13. LUT_OUTPUTS13, -- The output of LUT14. LUT_OUTPUTS14, -- The output of LUT15. LUT_OUTPUTS15, -- The output of LUT16. LUT_OUTPUTS16, -- The output of LUT17. LUT_OUTPUTS17, -- The output of LUT18. LUT_OUTPUTS18, -- The output of LUT19. LUT_OUTPUTS19, -- The output of LUT20. LUT_OUTPUTS20, -- The output of LUT21. LUT_OUTPUTS21, -- The output of LUT22. LUT_OUTPUTS22, -- The output of LUT23. LUT_OUTPUTS23, -- The output of LUT24. LUT_OUTPUTS24, -- The output of LUT25. LUT_OUTPUTS25, -- state(0). STATE0, -- state(1). STATE1, -- state(2). STATE2, -- state(3). STATE3) with Size => 6; for LUT_INP_MUX_LUTn_INPx_Field use (PLU_INPUTS0 => 0, PLU_INPUTS1 => 1, PLU_INPUTS2 => 2, PLU_INPUTS3 => 3, PLU_INPUTS4 => 4, PLU_INPUTS5 => 5, LUT_OUTPUTS0 => 6, LUT_OUTPUTS1 => 7, LUT_OUTPUTS2 => 8, LUT_OUTPUTS3 => 9, LUT_OUTPUTS4 => 10, LUT_OUTPUTS5 => 11, LUT_OUTPUTS6 => 12, LUT_OUTPUTS7 => 13, LUT_OUTPUTS8 => 14, LUT_OUTPUTS9 => 15, LUT_OUTPUTS10 => 16, LUT_OUTPUTS11 => 17, LUT_OUTPUTS12 => 18, LUT_OUTPUTS13 => 19, LUT_OUTPUTS14 => 20, LUT_OUTPUTS15 => 21, LUT_OUTPUTS16 => 22, LUT_OUTPUTS17 => 23, LUT_OUTPUTS18 => 24, LUT_OUTPUTS19 => 25, LUT_OUTPUTS20 => 26, LUT_OUTPUTS21 => 27, LUT_OUTPUTS22 => 28, LUT_OUTPUTS23 => 29, LUT_OUTPUTS24 => 30, LUT_OUTPUTS25 => 31, STATE0 => 32, STATE1 => 33, STATE2 => 34, STATE3 => 35); -- LUTn input x MUX type LUT_INP_MUX_LUT_Register is record -- Selects the input source to be connected to LUT0 input0. For each -- LUT, the slot associated with the output from LUTn itself is tied -- low. LUTn_INPx : LUT_INP_MUX_LUTn_INPx_Field := NXP_SVD.PLU.PLU_INPUTS0; -- unspecified Reserved_6_31 : HAL.UInt26 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for LUT_INP_MUX_LUT_Register use record LUTn_INPx at 0 range 0 .. 5; Reserved_6_31 at 0 range 6 .. 31; end record; -- LUTn input x MUX type LUT_INP_MUX_LUT_Registers is array (0 .. 4) of LUT_INP_MUX_LUT_Register with Volatile; -- no description available type LUT_Cluster is record -- LUTn input x MUX LUT_INP_MUX : aliased LUT_INP_MUX_LUT_Registers; end record with Volatile, Size => 256; for LUT_Cluster use record LUT_INP_MUX at 0 range 0 .. 159; end record; -- no description available type LUT_Clusters is array (0 .. 25) of LUT_Cluster; -- Specifies the Truth Table contents for LUT0 -- Specifies the Truth Table contents for LUT0 type LUT_TRUTH_Registers is array (0 .. 25) of HAL.UInt32 with Volatile; subtype OUTPUTS_OUTPUT_STATE_Field is HAL.UInt8; -- Provides the current state of the 8 designated PLU Outputs. type OUTPUTS_Register is record -- Read-only. Provides the current state of the 8 designated PLU -- Outputs.. OUTPUT_STATE : OUTPUTS_OUTPUT_STATE_Field; -- unspecified Reserved_8_31 : HAL.UInt24; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for OUTPUTS_Register use record OUTPUT_STATE at 0 range 0 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; subtype WAKEINT_CTRL_MASK_Field is HAL.UInt8; -- control input of the PLU, add filtering for glitch. type WAKEINT_CTRL_FILTER_MODE_Field is ( -- Bypass mode. Bypass, -- Filter 1 clock period. Filter1Clk, -- Filter 2 clock period. Filter2Clk, -- Filter 3 clock period. Filter3Clk) with Size => 2; for WAKEINT_CTRL_FILTER_MODE_Field use (Bypass => 0, Filter1Clk => 1, Filter2Clk => 2, Filter3Clk => 3); -- hclk is divided by 2**filter_clksel. type WAKEINT_CTRL_FILTER_CLKSEL_Field is ( -- Selects the 1 MHz low-power oscillator as the filter clock. Fro1Mhz, -- Selects the 12 Mhz FRO as the filter clock. Fro12Mhz, -- Selects a third filter clock source, if provided. Other_Clock) with Size => 2; for WAKEINT_CTRL_FILTER_CLKSEL_Field use (Fro1Mhz => 0, Fro12Mhz => 1, Other_Clock => 2); -- Wakeup interrupt control for PLU type WAKEINT_CTRL_Register is record -- Interrupt mask (which of the 8 PLU Outputs contribute to interrupt) MASK : WAKEINT_CTRL_MASK_Field := 16#0#; -- control input of the PLU, add filtering for glitch. FILTER_MODE : WAKEINT_CTRL_FILTER_MODE_Field := NXP_SVD.PLU.Bypass; -- hclk is divided by 2**filter_clksel. FILTER_CLKSEL : WAKEINT_CTRL_FILTER_CLKSEL_Field := NXP_SVD.PLU.Fro1Mhz; -- latch the interrupt , then can be cleared with next bit INTR_CLEAR LATCH_ENABLE : Boolean := False; -- Write data bit of one shall clear (set to zero) the corresponding bit -- in the field. Write to clear wakeint_latched INTR_CLEAR : Boolean := False; -- unspecified Reserved_14_31 : HAL.UInt18 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for WAKEINT_CTRL_Register use record MASK at 0 range 0 .. 7; FILTER_MODE at 0 range 8 .. 9; FILTER_CLKSEL at 0 range 10 .. 11; LATCH_ENABLE at 0 range 12 .. 12; INTR_CLEAR at 0 range 13 .. 13; Reserved_14_31 at 0 range 14 .. 31; end record; -- Selects the source to be connected to PLU Output 0. type OUTPUT_MUX_OUTPUTn_Field is ( -- The PLU output 0. PLU_OUTPUT0, -- The PLU output 1. PLU_OUTPUT1, -- The PLU output 2. PLU_OUTPUT2, -- The PLU output 3. PLU_OUTPUT3, -- The PLU output 4. PLU_OUTPUT4, -- The PLU output 5. PLU_OUTPUT5, -- The PLU output 6. PLU_OUTPUT6, -- The PLU output 7. PLU_OUTPUT7, -- The PLU output 8. PLU_OUTPUT8, -- The PLU output 9. PLU_OUTPUT9, -- The PLU output 10. PLU_OUTPUT10, -- The PLU output 11. PLU_OUTPUT11, -- The PLU output 12. PLU_OUTPUT12, -- The PLU output 13. PLU_OUTPUT13, -- The PLU output 14. PLU_OUTPUT14, -- The PLU output 15. PLU_OUTPUT15, -- The PLU output 16. PLU_OUTPUT16, -- The PLU output 17. PLU_OUTPUT17, -- The PLU output 18. PLU_OUTPUT18, -- The PLU output 19. PLU_OUTPUT19, -- The PLU output 20. PLU_OUTPUT20, -- The PLU output 21. PLU_OUTPUT21, -- The PLU output 22. PLU_OUTPUT22, -- The PLU output 23. PLU_OUTPUT23, -- The PLU output 24. PLU_OUTPUT24, -- The PLU output 25. PLU_OUTPUT25, -- state(0). STATE0, -- state(1). STATE1, -- state(2). STATE2, -- state(3). STATE3) with Size => 5; for OUTPUT_MUX_OUTPUTn_Field use (PLU_OUTPUT0 => 0, PLU_OUTPUT1 => 1, PLU_OUTPUT2 => 2, PLU_OUTPUT3 => 3, PLU_OUTPUT4 => 4, PLU_OUTPUT5 => 5, PLU_OUTPUT6 => 6, PLU_OUTPUT7 => 7, PLU_OUTPUT8 => 8, PLU_OUTPUT9 => 9, PLU_OUTPUT10 => 10, PLU_OUTPUT11 => 11, PLU_OUTPUT12 => 12, PLU_OUTPUT13 => 13, PLU_OUTPUT14 => 14, PLU_OUTPUT15 => 15, PLU_OUTPUT16 => 16, PLU_OUTPUT17 => 17, PLU_OUTPUT18 => 18, PLU_OUTPUT19 => 19, PLU_OUTPUT20 => 20, PLU_OUTPUT21 => 21, PLU_OUTPUT22 => 22, PLU_OUTPUT23 => 23, PLU_OUTPUT24 => 24, PLU_OUTPUT25 => 25, STATE0 => 26, STATE1 => 27, STATE2 => 28, STATE3 => 29); -- Selects the source to be connected to PLU Output 0 type OUTPUT_MUX_Register is record -- Selects the source to be connected to PLU Output 0. OUTPUTn : OUTPUT_MUX_OUTPUTn_Field := NXP_SVD.PLU.PLU_OUTPUT0; -- unspecified Reserved_5_31 : HAL.UInt27 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for OUTPUT_MUX_Register use record OUTPUTn at 0 range 0 .. 4; Reserved_5_31 at 0 range 5 .. 31; end record; -- Selects the source to be connected to PLU Output 0 type OUTPUT_MUX_Registers is array (0 .. 7) of OUTPUT_MUX_Register with Volatile; ----------------- -- Peripherals -- ----------------- -- LPC80X Programmable Logic Unit (PLU) type PLU_Peripheral is record -- no description available LUT : aliased LUT_Clusters; -- Specifies the Truth Table contents for LUT0 LUT_TRUTH : aliased LUT_TRUTH_Registers; -- Provides the current state of the 8 designated PLU Outputs. OUTPUTS : aliased OUTPUTS_Register; -- Wakeup interrupt control for PLU WAKEINT_CTRL : aliased WAKEINT_CTRL_Register; -- Selects the source to be connected to PLU Output 0 OUTPUT_MUX : aliased OUTPUT_MUX_Registers; end record with Volatile; for PLU_Peripheral use record LUT at 16#0# range 0 .. 6655; LUT_TRUTH at 16#800# range 0 .. 831; OUTPUTS at 16#900# range 0 .. 31; WAKEINT_CTRL at 16#904# range 0 .. 31; OUTPUT_MUX at 16#C00# range 0 .. 255; end record; -- LPC80X Programmable Logic Unit (PLU) PLU_Periph : aliased PLU_Peripheral with Import, Address => System'To_Address (16#4003D000#); end NXP_SVD.PLU;
-- SPDX-FileCopyrightText: 2019 Max Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT ------------------------------------------------------------- with Program.Elements.Type_Definitions; with Program.Lexical_Elements; with Program.Elements.Expressions; package Program.Elements.Modular_Types is pragma Pure (Program.Elements.Modular_Types); type Modular_Type is limited interface and Program.Elements.Type_Definitions.Type_Definition; type Modular_Type_Access is access all Modular_Type'Class with Storage_Size => 0; not overriding function Modulus (Self : Modular_Type) return not null Program.Elements.Expressions.Expression_Access is abstract; type Modular_Type_Text is limited interface; type Modular_Type_Text_Access is access all Modular_Type_Text'Class with Storage_Size => 0; not overriding function To_Modular_Type_Text (Self : in out Modular_Type) return Modular_Type_Text_Access is abstract; not overriding function Mod_Token (Self : Modular_Type_Text) return not null Program.Lexical_Elements.Lexical_Element_Access is abstract; end Program.Elements.Modular_Types;
-- Euler1 in Ada with Ada.Integer_Text_IO; procedure Euler1_2 is function mySum(n : in Integer; size : in Integer) return Integer is begin return n * (((size/n) **2 + (size/n)) / 2); end mySum; function Euler(size : in Integer) return Integer is begin return mySum(3,size) + mySum(5,size) - mySum(15,size); end Euler; begin Ada.Integer_Text_IO.Put (Integer( Euler(999) )); end Euler1_2;
pragma License (Unrestricted); -- implementation unit specialized for Darwin (or FreeBSD) with C.dirent; with C.sys.dirent; package System.Native_Directories.Searching is pragma Preelaborate; subtype Directory_Entry_Access is C.sys.dirent.struct_dirent_ptr; function New_Directory_Entry (Source : not null Directory_Entry_Access) return not null Directory_Entry_Access; procedure Free (X : in out Directory_Entry_Access); type Directory_Entry_Additional_Type is record Filled : Boolean; Information : aliased C.sys.stat.struct_stat; end record; pragma Suppress_Initialization (Directory_Entry_Additional_Type); -- same as Ada.Directories.Filter_Type type Filter_Type is array (File_Kind) of Boolean; pragma Pack (Filter_Type); pragma Suppress_Initialization (Filter_Type); subtype Handle_Type is C.dirent.DIR_ptr; Null_Handle : constant Handle_Type := null; type Search_Type is record Handle : C.dirent.DIR_ptr; Pattern : C.char_ptr; Filter : Filter_Type; end record; pragma Suppress_Initialization (Search_Type); procedure Start_Search ( Search : aliased in out Search_Type; Directory : String; Pattern : String; Filter : Filter_Type; Directory_Entry : out Directory_Entry_Access; Has_Next_Entry : out Boolean); procedure End_Search ( Search : aliased in out Search_Type; Raise_On_Error : Boolean); procedure Get_Next_Entry ( Search : aliased in out Search_Type; Directory_Entry : out Directory_Entry_Access; Has_Next_Entry : out Boolean); procedure Get_Entry ( Directory : String; Name : String; Directory_Entry : aliased out Directory_Entry_Access; -- allocated Additional : aliased in out Directory_Entry_Additional_Type); function Simple_Name (Directory_Entry : not null Directory_Entry_Access) return String; function Kind (Directory_Entry : not null Directory_Entry_Access) return File_Kind; function Size ( Directory : String; Directory_Entry : not null Directory_Entry_Access; Additional : aliased in out Directory_Entry_Additional_Type) return Ada.Streams.Stream_Element_Count; function Modification_Time ( Directory : String; Directory_Entry : not null Directory_Entry_Access; Additional : aliased in out Directory_Entry_Additional_Type) return Native_Calendar.Native_Time; procedure Get_Information ( Directory : String; Directory_Entry : not null Directory_Entry_Access; Information : aliased out C.sys.stat.struct_stat); end System.Native_Directories.Searching;
with Last_Chance_Handler; pragma Unreferenced (Last_Chance_Handler); with STM32GD.GPIO; with STM32GD.GPIO.Pin; with STM32_SVD.RCC; with Peripherals; procedure Main is package GPIO renames STM32GD.GPIO; package LED is new GPIO.Pin (Pin => GPIO.Pin_5, Port => GPIO.Port_A, Mode => GPIO.Mode_Out); package Button is new GPIO.Pin (Pin => GPIO.Pin_2, Port => GPIO.Port_A); begin STM32_SVD.RCC.RCC_Periph.AHBENR.IOPAEN := True; Button.Init; LED.Init; Peripherals.Handler.Run; end Main;
with System.Long_Long_Integer_Types; package body System.Boolean_Array_Operations is pragma Suppress (All_Checks); use type Long_Long_Integer_Types.Word_Unsigned; use type Storage_Elements.Storage_Element; use type Storage_Elements.Storage_Offset; subtype Word_Unsigned is Long_Long_Integer_Types.Word_Unsigned; Word_Unit : constant := Standard'Word_Size / Standard'Storage_Unit; Word_Mask : constant := Word_Unit - 1; pragma Compile_Time_Error (Word_Unit > 8, "should fix Vector_Not"); -- implementation procedure Vector_Not ( R, X : Address; Length : Storage_Elements.Storage_Count) is Dest_Addr : Address := R; Right_Addr : Address := X; Dest_End : constant Address := Dest_Addr + Length; begin if ((Dest_Addr or Right_Addr) and Word_Mask) = 0 then declare Dest_End_Word : constant Address := Dest_End and not Word_Mask; begin while Dest_Addr < Dest_End_Word loop declare Dest : Word_Unsigned; for Dest'Address use Dest_Addr; Right : Word_Unsigned; for Right'Address use Right_Addr; begin Dest := (2 ** 0 or 2 ** Standard'Storage_Unit or 2 ** (Standard'Storage_Unit * 2) or 2 ** (Standard'Storage_Unit * 3) or 2 ** (Standard'Storage_Unit * 4) or 2 ** (Standard'Storage_Unit * 5) or 2 ** (Standard'Storage_Unit * 6) or 2 ** (Standard'Storage_Unit * 7)) xor Right; end; Dest_Addr := Dest_Addr + Address'(Word_Unit); Right_Addr := Right_Addr + Address'(Word_Unit); end loop; end; end if; while Dest_Addr < Dest_End loop declare Dest : Storage_Elements.Storage_Element; for Dest'Address use Dest_Addr; Right : Storage_Elements.Storage_Element; for Right'Address use Right_Addr; begin Dest := 1 xor Right; end; Dest_Addr := Dest_Addr + Address'(1); Right_Addr := Right_Addr + Address'(1); end loop; end Vector_Not; procedure Vector_And ( R, X, Y : Address; Length : Storage_Elements.Storage_Count) is Dest_Addr : Address := R; Left_Addr : Address := X; Right_Addr : Address := Y; Dest_End : constant Address := Dest_Addr + Length; begin if ((Dest_Addr or Left_Addr or Right_Addr) and Word_Mask) = 0 then declare Dest_End_Word : constant Address := Dest_End and not Word_Mask; begin while Dest_Addr < Dest_End_Word loop declare Dest : Word_Unsigned; for Dest'Address use Dest_Addr; Left : Word_Unsigned; for Left'Address use Left_Addr; Right : Word_Unsigned; for Right'Address use Right_Addr; begin Dest := Left and Right; end; Dest_Addr := Dest_Addr + Address'(Word_Unit); Left_Addr := Left_Addr + Address'(Word_Unit); Right_Addr := Right_Addr + Address'(Word_Unit); end loop; end; end if; while Dest_Addr < Dest_End loop declare Dest : Storage_Elements.Storage_Element; for Dest'Address use Dest_Addr; Left : Storage_Elements.Storage_Element; for Left'Address use Left_Addr; Right : Storage_Elements.Storage_Element; for Right'Address use Right_Addr; begin Dest := Left and Right; end; Dest_Addr := Dest_Addr + Address'(1); Left_Addr := Left_Addr + Address'(1); Right_Addr := Right_Addr + Address'(1); end loop; end Vector_And; procedure Vector_Or ( R, X, Y : Address; Length : Storage_Elements.Storage_Count) is Dest_Addr : Address := R; Left_Addr : Address := X; Right_Addr : Address := Y; Dest_End : constant Address := Dest_Addr + Length; begin if ((Dest_Addr or Left_Addr or Right_Addr) and Word_Mask) = 0 then declare Dest_End_Word : constant Address := Dest_End and not Word_Mask; begin while Dest_Addr < Dest_End_Word loop declare Dest : Word_Unsigned; for Dest'Address use Dest_Addr; Left : Word_Unsigned; for Left'Address use Left_Addr; Right : Word_Unsigned; for Right'Address use Right_Addr; begin Dest := Left or Right; end; Dest_Addr := Dest_Addr + Address'(Word_Unit); Left_Addr := Left_Addr + Address'(Word_Unit); Right_Addr := Right_Addr + Address'(Word_Unit); end loop; end; end if; while Dest_Addr < Dest_End loop declare Dest : Storage_Elements.Storage_Element; for Dest'Address use Dest_Addr; Left : Storage_Elements.Storage_Element; for Left'Address use Left_Addr; Right : Storage_Elements.Storage_Element; for Right'Address use Right_Addr; begin Dest := Left or Right; end; Dest_Addr := Dest_Addr + Address'(1); Left_Addr := Left_Addr + Address'(1); Right_Addr := Right_Addr + Address'(1); end loop; end Vector_Or; procedure Vector_Xor ( R, X, Y : Address; Length : Storage_Elements.Storage_Count) is Dest_Addr : Address := R; Left_Addr : Address := X; Right_Addr : Address := Y; Dest_End : constant Address := Dest_Addr + Length; begin if ((Dest_Addr or Left_Addr or Right_Addr) and Word_Mask) = 0 then declare Dest_End_Word : constant Address := Dest_End and not Word_Mask; begin while Dest_Addr < Dest_End_Word loop declare Dest : Word_Unsigned; for Dest'Address use Dest_Addr; Left : Word_Unsigned; for Left'Address use Left_Addr; Right : Word_Unsigned; for Right'Address use Right_Addr; begin Dest := Left xor Right; end; Dest_Addr := Dest_Addr + Address'(Word_Unit); Left_Addr := Left_Addr + Address'(Word_Unit); Right_Addr := Right_Addr + Address'(Word_Unit); end loop; end; end if; while Dest_Addr < Dest_End loop declare Dest : Storage_Elements.Storage_Element; for Dest'Address use Dest_Addr; Left : Storage_Elements.Storage_Element; for Left'Address use Left_Addr; Right : Storage_Elements.Storage_Element; for Right'Address use Right_Addr; begin Dest := Left xor Right; end; Dest_Addr := Dest_Addr + Address'(1); Left_Addr := Left_Addr + Address'(1); Right_Addr := Right_Addr + Address'(1); end loop; end Vector_Xor; end System.Boolean_Array_Operations;
-- { dg-do compile } package Pack7 is type R (D : Natural) is record S : String (1 .. D); N : Natural; B : Boolean; end record; for R'Alignment use 4; pragma Pack (R); end Pack7;
-- This file is generated by SWIG. Please do *not* modify by hand. -- with Swig; with Interfaces.C; package bullet_c is -- Shape -- subtype Shape is Swig.opaque_structure; type Shape_array is array (Interfaces.C.size_t range <>) of aliased bullet_c.Shape; -- Object -- subtype Object is Swig.opaque_structure; type Object_array is array (Interfaces.C.size_t range <>) of aliased bullet_c.Object; -- Joint -- subtype Joint is Swig.opaque_structure; type Joint_array is array (Interfaces.C.size_t range <>) of aliased bullet_c.Joint; -- Space -- subtype Space is Swig.opaque_structure; type Space_array is array (Interfaces.C.size_t range <>) of aliased bullet_c.Space; end bullet_c;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2018, AdaCore and other contributors -- -- -- -- See github.com/AdaCore/Ada_Drivers_Library/graphs/contributors -- -- for more information -- -- -- -- 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 NRF51_SVD.UART; use NRF51_SVD.UART; package body nRF51.UART is ------------ -- Enable -- ------------ procedure Enable (This : in out UART) is begin This.Periph.ENABLE.ENABLE := Enabled; end Enable; ------------- -- Disable -- ------------- procedure Disable (This : in out UART) is begin This.Periph.ENABLE.ENABLE := Disabled; end Disable; ------------- -- Enabled -- ------------- function Enabled (This : UART) return Boolean is begin return This.Periph.ENABLE.ENABLE = Enabled; end Enabled; --------------- -- Configure -- --------------- procedure Configure (This : in out UART; RX_Pin : GPIO_Pin_Index; TX_Pin : GPIO_Pin_Index; Speed : UART_Speed) is begin This.Periph.PSELRXD := UInt32 (RX_Pin); This.Periph.PSELTXD := UInt32 (TX_Pin); This.Periph.BAUDRATE := (case Speed is when UART_1200_Baud => 16#0004_F000#, when UART_2400_Baud => 16#0009_D000#, when UART_4800_Baud => 16#0013_B000#, when UART_9600_Baud => 16#0027_5000#, when UART_14400_Baud => 16#003B_0000#, when UART_19200_Baud => 16#004E_A000#, when UART_28800_Baud => 16#0075_F000#, when UART_38400_Baud => 16#009D_5000#, when UART_57600_Baud => 16#00EB_F000#, when UART_76800_Baud => 16#013A_9000#, when UART_115200_Baud => 16#01D7_E000#, when UART_230400_Baud => 16#03AF_B000#, when UART_250000_Baud => 16#0400_0000#, when UART_460800_Baud => 16#075F_7000#, when UART_921600_Baud => 16#0EBE_DFA4#, when UART_1M_Baud => 16#1000_0000#); end Configure; ---------------- -- Disconnect -- ---------------- procedure Disconnect (This : in out UART) is begin This.Periph.PSELRXD := 16#FFFF_FFFF#; This.Periph.PSELTXD := 16#FFFF_FFFF#; end Disconnect; --------------- -- Data_Size -- --------------- overriding function Data_Size (Port : UART) return UART_Data_Size is pragma Unreferenced (Port); begin return Data_Size_8b; end Data_Size; -------------- -- Transmit -- -------------- overriding procedure Transmit (This : in out UART; Data : UART_Data_8b; Status : out UART_Status; Timeout : Natural := 1000) is pragma Unreferenced (Timeout); Index : Integer := Data'First + 1; Err_Src : ERRORSRC_Register with Unreferenced; begin if Data'Length = 0 then Status := Ok; return; end if; -- Clear errors This.Periph.ERRORSRC.OVERRUN := Errorsrc_Overrun_Field_Reset; This.Periph.ERRORSRC.PARITY := Errorsrc_Parity_Field_Reset; This.Periph.ERRORSRC.FRAMING := Errorsrc_Framing_Field_Reset; This.Periph.ERRORSRC.BREAK := Errorsrc_Break_Field_Reset; -- Prepare first byte This.Periph.TXD.TXD := Data (Data'First); -- Start TX sequence This.Periph.TASKS_STARTTX := 1; loop loop if This.Periph.EVENTS_ERROR /= 0 then Err_Src := This.Periph.ERRORSRC; Status := Err_Error; -- Clear the error This.Periph.EVENTS_ERROR := 0; -- Stop sequence This.Periph.TASKS_STOPTX := 1; return; end if; exit when This.Periph.EVENTS_TXDRDY /= 0; end loop; -- Clear the event This.Periph.EVENTS_TXDRDY := 0; exit when Index > Data'Last; This.Periph.TXD.TXD := Data (Index); Index := Index + 1; end loop; Status := Ok; end Transmit; ------------- -- Receive -- ------------- overriding procedure Receive (This : in out UART; Data : out UART_Data_8b; Status : out UART_Status; Timeout : Natural := 1000) is pragma Unreferenced (Timeout); Err_Src : ERRORSRC_Register with Unreferenced; begin if Data'Length = 0 then Status := Ok; return; end if; -- Clear errors This.Periph.ERRORSRC.OVERRUN := Errorsrc_Overrun_Field_Reset; This.Periph.ERRORSRC.PARITY := Errorsrc_Parity_Field_Reset; This.Periph.ERRORSRC.FRAMING := Errorsrc_Framing_Field_Reset; This.Periph.ERRORSRC.BREAK := Errorsrc_Break_Field_Reset; -- Start RX sequence This.Periph.TASKS_STARTRX := 1; for Index in Data'Range loop loop if This.Periph.EVENTS_ERROR /= 0 then Err_Src := This.Periph.ERRORSRC; Status := Err_Error; -- Clear the error This.Periph.EVENTS_ERROR := 0; return; end if; exit when This.Periph.EVENTS_RXDRDY /= 0; end loop; -- Clear the event This.Periph.EVENTS_RXDRDY := 0; Data (Index) := This.Periph.RXD.RXD; end loop; Status := Ok; end Receive; -------------- -- Transmit -- -------------- overriding procedure Transmit (This : in out UART; Data : UART_Data_9b; Status : out UART_Status; Timeout : Natural := 1000) is pragma Unreferenced (Data, Timeout); begin Status := Err_Error; end Transmit; ------------- -- Receive -- ------------- overriding procedure Receive (This : in out UART; Data : out UART_Data_9b; Status : out UART_Status; Timeout : Natural := 1000) is pragma Unreferenced (Data, Timeout); begin Status := Err_Error; end Receive; end nRF51.UART;
with Units; use Units; --with Altunits; use Altunits; with Ada.Text_IO; use Ada.Text_IO; procedure main is a : Length_Type := 5.0; b : Time_Type := 2.0; v : Linear_Velocity_Type := 3.0; --v : Linear_Velocity_Type := 3.0; function calc_my_velocity( l : Length_Type; t : Time_Type ) return Linear_Velocity_Type is begin return l / t; end calc_my_velocity; begin v := calc_my_velocity( a, a ); Put_Line("Test"); end main; -- with Dim_Sys: 522383 -- without Dim_Sys: 523132
----------------------------------------------------------------------- -- babel-Streams-xz -- XZ/LZMA stream management -- Copyright (C) 2014, 2015 Stephane.Carrez -- Written by Stephane.Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Interfaces.C; with Lzma.Container; with Lzma.Check; package body Babel.Streams.XZ is use type Interfaces.C.size_t; use type Ada.Streams.Stream_Element_Offset; use type Lzma.Base.lzma_action; use type Lzma.Base.lzma_ret; -- ------------------------------ -- Set the input stream to decompress. -- ------------------------------ procedure Set_Input (Stream : in out Stream_Type; Input : in Babel.Streams.Stream_Access) is Result : Lzma.Base.lzma_ret; begin Stream.Input := Input; Stream.Action := Lzma.Base.LZMA_RUN; Result := Lzma.Container.lzma_stream_decoder (Stream.Context'Unchecked_Access, Long_Long_Integer'Last, Lzma.Container.LZMA_CONCATENATED); end Set_Input; -- ------------------------------ -- Set the output stream to write the compressed stream. -- ------------------------------ procedure Set_Output (Stream : in out Stream_Type; Output : in Babel.Streams.Stream_Access) is Result : Lzma.Base.lzma_ret; begin Stream.Output := Output; Stream.Action := Lzma.Base.LZMA_RUN; Result := Lzma.Container.lzma_easy_encoder (Stream.Context'Unchecked_Access, 6, Lzma.Check.LZMA_CHECK_CRC64); Stream.Context.next_out := Stream.Buffer.Data (Stream.Buffer.Data'First)'Unchecked_Access; Stream.Context.avail_out := Stream.Buffer.Data'Length; end Set_Output; -- ------------------------------ -- Read the data stream as much as possible and return the result in a buffer. -- The buffer is owned by the stream and need not be released. The same buffer may -- or may not be returned by the next <tt>Read</tt> operation. -- A null buffer is returned when the end of the data stream is reached. -- ------------------------------ overriding procedure Read (Stream : in out Stream_Type; Buffer : out Babel.Files.Buffers.Buffer_Access) is use type Babel.Files.Buffers.Buffer_Access; Inbuf : Babel.Files.Buffers.Buffer_Access; Result : Lzma.Base.lzma_ret; begin Buffer := Stream.Buffer; Stream.Context.next_out := Buffer.Data (Buffer.Data'First)'Unchecked_Access; Stream.Context.avail_out := Buffer.Data'Length; loop -- Read a block of data from the source file. if Stream.Context.avail_in = 0 and Stream.Action = Lzma.Base.LZMA_RUN then Stream.Input.Read (Inbuf); if Inbuf = null then Stream.Action := Lzma.Base.LZMA_FINISH; else Stream.Context.next_in := Inbuf.Data (Inbuf.Data'First)'Unchecked_Access; Stream.Context.avail_in := Interfaces.C.size_t (Inbuf.Last - Inbuf.Data'First + 1); end if; end if; Result := Lzma.Base.lzma_code (Stream.Context'Unchecked_Access, Stream.Action); -- Write the output data when the buffer is full or we reached the end of stream. exit when Stream.Context.avail_out = 0 or Result = Lzma.Base.LZMA_STREAM_END; if Result /= Lzma.Base.LZMA_OK then Buffer := null; return; end if; end loop; if Buffer.Data'Length = Stream.Context.avail_out then Buffer := null; else Buffer.Last := Buffer.Data'Last - Ada.Streams.Stream_Element_Offset (Stream.Context.avail_out); end if; end Read; -- ------------------------------ -- Write the buffer in the data stream. -- ------------------------------ overriding procedure Write (Stream : in out Stream_Type; Buffer : in Babel.Files.Buffers.Buffer_Access) is Result : Lzma.Base.lzma_ret; begin Stream.Context.next_in := Buffer.Data (Buffer.Data'First)'Unchecked_Access; Stream.Context.avail_in := Interfaces.C.size_t (Buffer.Last - Buffer.Data'First + 1); loop -- Read a block of data from the source file. exit when Stream.Context.avail_in = 0; Result := Lzma.Base.lzma_code (Stream.Context'Unchecked_Access, Stream.Action); -- Write the output data when the buffer is full or we reached the end of stream. if Stream.Context.avail_out = 0 or Result = Lzma.Base.LZMA_STREAM_END then Stream.Buffer.Last := Stream.Buffer.Data'Last - Ada.Streams.Stream_Element_Offset (Stream.Context.avail_out); Stream.Output.Write (Stream.Buffer); Stream.Context.avail_out := Stream.Buffer.Data'Length; Stream.Context.next_out := Stream.Buffer.Data (Stream.Buffer.Data'First)'Unchecked_Access; end if; exit when Result /= Lzma.Base.LZMA_OK; end loop; end Write; -- ------------------------------ -- Flush the data stream. -- ------------------------------ overriding procedure Flush (Stream : in out Stream_Type) is Result : Lzma.Base.lzma_ret; begin Stream.Action := Lzma.Base.LZMA_FINISH; Stream.Context.avail_in := 0; loop -- Read a block of data from the source file. Result := Lzma.Base.lzma_code (Stream.Context'Unchecked_Access, Stream.Action); -- Write the output data when the buffer is full or we reached the end of stream. if Stream.Context.avail_out = 0 or Result = Lzma.Base.LZMA_STREAM_END then Stream.Buffer.Last := Stream.Buffer.Data'Last - Ada.Streams.Stream_Element_Offset (Stream.Context.avail_out); Stream.Output.Write (Stream.Buffer); Stream.Context.avail_out := Stream.Buffer.Data'Length; Stream.Context.next_out := Stream.Buffer.Data (Stream.Buffer.Data'First)'Unchecked_Access; end if; exit when Result /= Lzma.Base.LZMA_OK; end loop; Stream.Output.Flush; end Flush; -- ------------------------------ -- Close the data stream. -- ------------------------------ overriding procedure Close (Stream : in out Stream_Type) is begin if Stream.Output /= null then Stream.Flush; Stream.Output.Close; end if; end Close; -- ------------------------------ -- Prepare to read again the data stream from the beginning. -- ------------------------------ overriding procedure Rewind (Stream : in out Stream_Type) is begin Stream.Action := Lzma.Base.LZMA_RUN; Stream.Input.Rewind; end Rewind; -- ------------------------------ -- Release the stream buffer and the LZMA stream. -- ------------------------------ overriding procedure Finalize (Stream : in out Stream_Type) is begin Lzma.Base.lzma_end (Stream.Context'Unchecked_Access); Babel.Streams.Stream_Type (Stream).Finalize; end Finalize; end Babel.Streams.XZ;
-- This package has been generated automatically by GNATtest. -- Do not edit any part of it, see GNATtest documentation for more details. -- begin read only with Gnattest_Generated; package Events.Test_Data.Tests is type Test is new GNATtest_Generated.GNATtest_Standard.Events.Test_Data .Test with null record; procedure Test_CheckForEvent_1c4562_e01b25(Gnattest_T: in out Test); -- events.ads:99:4:CheckForEvent:Test_CheckForEvent procedure Test_UpdateEvents_96e988_646fe5(Gnattest_T: in out Test); -- events.ads:109:4:UpdateEvents:Test_UpdateEvents procedure Test_DeleteEvent_0ca9ce_33228f(Gnattest_T: in out Test); -- events.ads:119:4:DeleteEvent:Test_DeleteEvent procedure Test_GenerateTraders_8d2b65_5d00a3(Gnattest_T: in out Test); -- events.ads:128:4:GenerateTraders:Test_GenerateTraders procedure Test_RecoverBase_904011_a032fd(Gnattest_T: in out Test); -- events.ads:138:4:RecoverBase:Test_RecoverBase procedure Test_GenerateEnemies_7f8f2c_3cff13(Gnattest_T: in out Test); -- events.ads:151:4:GenerateEnemies:Test_GenerateEnemies end Events.Test_Data.Tests; -- end read only
-- ---------------------------------------------------------------------------- -- -- The intent of this unit is to provide a simple main program that runs -- one Test_Case. -- The procedure is intended to be instansiated as a childern to -- the package containing the test_case. -- -- with AUnit.Test_Cases.Simple_Main_Generic; -- procedure component.children.tests.testcase1.main is -- new AUnit.Test_Cases.Simple_Main_Generic(Test_Case); -- -- Thus providing a simple main for One_Testcase to be used during development. -- -- ---------------------------------------------------------------------------- with AUnit.Test_Cases; generic type Test_Case is new AUnit.Test_Cases.Test_Case with private; procedure AUnit.Test_Cases.Simple_Main_Generic;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- P A R _ S C O -- -- -- -- B o d y -- -- -- -- Copyright (C) 2009-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. -- -- -- ------------------------------------------------------------------------------ with Aspects; use Aspects; with Atree; use Atree; with Debug; use Debug; with Errout; use Errout; with Lib; use Lib; with Lib.Util; use Lib.Util; with Namet; use Namet; with Nlists; use Nlists; with Opt; use Opt; with Output; use Output; with Put_SCOs; with SCOs; use SCOs; with Sem; use Sem; with Sem_Util; use Sem_Util; with Sinfo; use Sinfo; with Sinput; use Sinput; with Snames; use Snames; with Table; with GNAT.HTable; use GNAT.HTable; with GNAT.Heap_Sort_G; with GNAT.Table; package body Par_SCO is -------------------------- -- First-pass SCO table -- -------------------------- -- The Short_Circuit_And_Or pragma enables one to use AND and OR operators -- in source code while the ones used with booleans will be interpreted as -- their short circuit alternatives (AND THEN and OR ELSE). Thus, the true -- meaning of these operators is known only after the semantic analysis. -- However, decision SCOs include short circuit operators only. The SCO -- information generation pass must be done before expansion, hence before -- the semantic analysis. Because of this, the SCO information generation -- is done in two passes. -- The first one (SCO_Record_Raw, before semantic analysis) completes the -- SCO_Raw_Table assuming all AND/OR operators are short circuit ones. -- Then, the semantic analysis determines which operators are promoted to -- short circuit ones. Finally, the second pass (SCO_Record_Filtered) -- translates the SCO_Raw_Table to SCO_Table, taking care of removing the -- remaining AND/OR operators and of adjusting decisions accordingly -- (splitting decisions, removing empty ones, etc.). type SCO_Generation_State_Type is (None, Raw, Filtered); SCO_Generation_State : SCO_Generation_State_Type := None; -- Keep track of the SCO generation state: this will prevent us from -- running some steps multiple times (the second pass has to be started -- from multiple places). package SCO_Raw_Table is new GNAT.Table (Table_Component_Type => SCO_Table_Entry, Table_Index_Type => Nat, Table_Low_Bound => 1, Table_Initial => 500, Table_Increment => 300); ----------------------- -- Unit Number Table -- ----------------------- -- This table parallels the SCO_Unit_Table, keeping track of the unit -- numbers corresponding to the entries made in this table, so that before -- writing out the SCO information to the ALI file, we can fill in the -- proper dependency numbers and file names. -- Note that the zero'th entry is here for convenience in sorting the -- table, the real lower bound is 1. package SCO_Unit_Number_Table is new Table.Table (Table_Component_Type => Unit_Number_Type, Table_Index_Type => SCO_Unit_Index, Table_Low_Bound => 0, -- see note above on sort Table_Initial => 20, Table_Increment => 200, Table_Name => "SCO_Unit_Number_Entry"); ------------------------------------------ -- Condition/Operator/Pragma Hash Table -- ------------------------------------------ -- We need to be able to get to conditions quickly for handling the calls -- to Set_SCO_Condition efficiently, and similarly to get to pragmas to -- handle calls to Set_SCO_Pragma_Enabled (the same holds for operators and -- Set_SCO_Logical_Operator). For this purpose we identify the conditions, -- operators and pragmas in the table by their starting sloc, and use this -- hash table to map from these sloc values to SCO_Table indexes. type Header_Num is new Integer range 0 .. 996; -- Type for hash table headers function Hash (F : Source_Ptr) return Header_Num; -- Function to Hash source pointer value function Equal (F1 : Source_Ptr; F2 : Source_Ptr) return Boolean; -- Function to test two keys for equality function "<" (S1 : Source_Location; S2 : Source_Location) return Boolean; -- Function to test for source locations order package SCO_Raw_Hash_Table is new Simple_HTable (Header_Num, Int, 0, Source_Ptr, Hash, Equal); -- The actual hash table -------------------------- -- Internal Subprograms -- -------------------------- function Has_Decision (N : Node_Id) return Boolean; -- N is the node for a subexpression. Returns True if the subexpression -- contains a nested decision (i.e. either is a logical operator, or -- contains a logical operator in its subtree). -- -- This must be used in the first pass (SCO_Record_Raw) only: here AND/OR -- operators are considered as short circuit, just in case the -- Short_Circuit_And_Or pragma is used: only real short circuit operations -- will be kept in the secord pass. type Tristate is (False, True, Unknown); function Is_Logical_Operator (N : Node_Id) return Tristate; -- N is the node for a subexpression. This procedure determines whether N -- is a logical operator: True for short circuit conditions, Unknown for OR -- and AND (the Short_Circuit_And_Or pragma may be used) and False -- otherwise. Note that in cases where True is returned, callers assume -- Nkind (N) in N_Op. function To_Source_Location (S : Source_Ptr) return Source_Location; -- Converts Source_Ptr value to Source_Location (line/col) format procedure Process_Decisions (N : Node_Id; T : Character; Pragma_Sloc : Source_Ptr); -- If N is Empty, has no effect. Otherwise scans the tree for the node N, -- to output any decisions it contains. T is one of IEGPWX (for context of -- expression: if/exit when/entry guard/pragma/while/expression). If T is -- other than X, the node N is the if expression involved, and a decision -- is always present (at the very least a simple decision is present at the -- top level). procedure Process_Decisions (L : List_Id; T : Character; Pragma_Sloc : Source_Ptr); -- Calls above procedure for each element of the list L procedure Set_Raw_Table_Entry (C1 : Character; C2 : Character; From : Source_Ptr; To : Source_Ptr; Last : Boolean; Pragma_Sloc : Source_Ptr := No_Location; Pragma_Aspect_Name : Name_Id := No_Name); -- Append an entry to SCO_Raw_Table with fields set as per arguments type Dominant_Info is record K : Character; -- F/T/S/E for a valid dominance marker, or ' ' for no dominant N : Node_Id; -- Node providing the Sloc(s) for the dominance marker end record; No_Dominant : constant Dominant_Info := (' ', Empty); procedure Record_Instance (Id : Instance_Id; Inst_Sloc : Source_Ptr); -- Add one entry from the instance table to the corresponding SCO table procedure Traverse_Declarations_Or_Statements (L : List_Id; D : Dominant_Info := No_Dominant; P : Node_Id := Empty); -- Process L, a list of statements or declarations dominated by D. If P is -- present, it is processed as though it had been prepended to L. function Traverse_Declarations_Or_Statements (L : List_Id; D : Dominant_Info := No_Dominant; P : Node_Id := Empty) return Dominant_Info; -- Same as above, and returns dominant information corresponding to the -- last node with SCO in L. -- The following Traverse_* routines perform appropriate calls to -- Traverse_Declarations_Or_Statements to traverse specific node kinds. -- Parameter D, when present, indicates the dominant of the first -- declaration or statement within N. -- Why is Traverse_Sync_Definition commented specificaly and -- the others are not??? procedure Traverse_Generic_Package_Declaration (N : Node_Id); procedure Traverse_Handled_Statement_Sequence (N : Node_Id; D : Dominant_Info := No_Dominant); procedure Traverse_Package_Body (N : Node_Id); procedure Traverse_Package_Declaration (N : Node_Id; D : Dominant_Info := No_Dominant); procedure Traverse_Subprogram_Or_Task_Body (N : Node_Id; D : Dominant_Info := No_Dominant); procedure Traverse_Sync_Definition (N : Node_Id); -- Traverse a protected definition or task definition -- Note regarding traversals: In a few cases where an Alternatives list is -- involved, pragmas such as "pragma Page" may show up before the first -- alternative. We skip them because we're out of statement or declaration -- context, so these can't be pragmas of interest for SCO purposes, and -- the regular alternative processing typically involves attribute queries -- which aren't valid for a pragma. procedure Write_SCOs_To_ALI_File is new Put_SCOs; -- Write SCO information to the ALI file using routines in Lib.Util ---------- -- dsco -- ---------- procedure dsco is procedure Dump_Entry (Index : Nat; T : SCO_Table_Entry); -- Dump a SCO table entry ---------------- -- Dump_Entry -- ---------------- procedure Dump_Entry (Index : Nat; T : SCO_Table_Entry) is begin Write_Str (" "); Write_Int (Index); Write_Char ('.'); if T.C1 /= ' ' then Write_Str (" C1 = '"); Write_Char (T.C1); Write_Char ('''); end if; if T.C2 /= ' ' then Write_Str (" C2 = '"); Write_Char (T.C2); Write_Char ('''); end if; if T.From /= No_Source_Location then Write_Str (" From = "); Write_Int (Int (T.From.Line)); Write_Char (':'); Write_Int (Int (T.From.Col)); end if; if T.To /= No_Source_Location then Write_Str (" To = "); Write_Int (Int (T.To.Line)); Write_Char (':'); Write_Int (Int (T.To.Col)); end if; if T.Last then Write_Str (" True"); else Write_Str (" False"); end if; Write_Eol; end Dump_Entry; -- Start of processing for dsco begin -- Dump SCO unit table Write_Line ("SCO Unit Table"); Write_Line ("--------------"); for Index in 1 .. SCO_Unit_Table.Last loop declare UTE : SCO_Unit_Table_Entry renames SCO_Unit_Table.Table (Index); begin Write_Str (" "); Write_Int (Int (Index)); Write_Str (" Dep_Num = "); Write_Int (Int (UTE.Dep_Num)); Write_Str (" From = "); Write_Int (Int (UTE.From)); Write_Str (" To = "); Write_Int (Int (UTE.To)); Write_Str (" File_Name = """); if UTE.File_Name /= null then Write_Str (UTE.File_Name.all); end if; Write_Char ('"'); Write_Eol; end; end loop; -- Dump SCO Unit number table if it contains any entries if SCO_Unit_Number_Table.Last >= 1 then Write_Eol; Write_Line ("SCO Unit Number Table"); Write_Line ("---------------------"); for Index in 1 .. SCO_Unit_Number_Table.Last loop Write_Str (" "); Write_Int (Int (Index)); Write_Str (". Unit_Number = "); Write_Int (Int (SCO_Unit_Number_Table.Table (Index))); Write_Eol; end loop; end if; -- Dump SCO raw-table Write_Eol; Write_Line ("SCO Raw Table"); Write_Line ("---------"); if SCO_Generation_State = Filtered then Write_Line ("Empty (free'd after second pass)"); else for Index in 1 .. SCO_Raw_Table.Last loop Dump_Entry (Index, SCO_Raw_Table.Table (Index)); end loop; end if; -- Dump SCO table itself Write_Eol; Write_Line ("SCO Filtered Table"); Write_Line ("---------"); for Index in 1 .. SCO_Table.Last loop Dump_Entry (Index, SCO_Table.Table (Index)); end loop; end dsco; ----------- -- Equal -- ----------- function Equal (F1 : Source_Ptr; F2 : Source_Ptr) return Boolean is begin return F1 = F2; end Equal; ------- -- < -- ------- function "<" (S1 : Source_Location; S2 : Source_Location) return Boolean is begin return S1.Line < S2.Line or else (S1.Line = S2.Line and then S1.Col < S2.Col); end "<"; ------------------ -- Has_Decision -- ------------------ function Has_Decision (N : Node_Id) return Boolean is function Check_Node (N : Node_Id) return Traverse_Result; -- Determine if Nkind (N) indicates the presence of a decision (i.e. N -- is a logical operator, which is a decision in itself, or an -- IF-expression whose Condition attribute is a decision). ---------------- -- Check_Node -- ---------------- function Check_Node (N : Node_Id) return Traverse_Result is begin -- If we are not sure this is a logical operator (AND and OR may be -- turned into logical operators with the Short_Circuit_And_Or -- pragma), assume it is. Putative decisions will be discarded if -- needed in the secord pass. if Is_Logical_Operator (N) /= False or else Nkind (N) = N_If_Expression then return Abandon; else return OK; end if; end Check_Node; function Traverse is new Traverse_Func (Check_Node); -- Start of processing for Has_Decision begin return Traverse (N) = Abandon; end Has_Decision; ---------- -- Hash -- ---------- function Hash (F : Source_Ptr) return Header_Num is begin return Header_Num (Nat (F) mod 997); end Hash; ---------------- -- Initialize -- ---------------- procedure Initialize is begin SCO_Unit_Number_Table.Init; -- The SCO_Unit_Number_Table entry with index 0 is intentionally set -- aside to be used as temporary for sorting. SCO_Unit_Number_Table.Increment_Last; end Initialize; ------------------------- -- Is_Logical_Operator -- ------------------------- function Is_Logical_Operator (N : Node_Id) return Tristate is begin if Nkind_In (N, N_And_Then, N_Op_Not, N_Or_Else) then return True; elsif Nkind_In (N, N_Op_And, N_Op_Or) then return Unknown; else return False; end if; end Is_Logical_Operator; ----------------------- -- Process_Decisions -- ----------------------- -- Version taking a list procedure Process_Decisions (L : List_Id; T : Character; Pragma_Sloc : Source_Ptr) is N : Node_Id; begin if L /= No_List then N := First (L); while Present (N) loop Process_Decisions (N, T, Pragma_Sloc); Next (N); end loop; end if; end Process_Decisions; -- Version taking a node Current_Pragma_Sloc : Source_Ptr := No_Location; -- While processing a pragma, this is set to the sloc of the N_Pragma node procedure Process_Decisions (N : Node_Id; T : Character; Pragma_Sloc : Source_Ptr) is Mark : Nat; -- This is used to mark the location of a decision sequence in the SCO -- table. We use it for backing out a simple decision in an expression -- context that contains only NOT operators. Mark_Hash : Nat; -- Likewise for the putative SCO_Raw_Hash_Table entries: see below type Hash_Entry is record Sloc : Source_Ptr; SCO_Index : Nat; end record; -- We must register all conditions/pragmas in SCO_Raw_Hash_Table. -- However we cannot register them in the same time we are adding the -- corresponding SCO entries to the raw table since we may discard them -- later on. So instead we put all putative conditions into Hash_Entries -- (see below) and register them once we are sure we keep them. -- -- This data structure holds the conditions/pragmas to register in -- SCO_Raw_Hash_Table. package Hash_Entries is new Table.Table (Table_Component_Type => Hash_Entry, Table_Index_Type => Nat, Table_Low_Bound => 1, Table_Initial => 10, Table_Increment => 10, Table_Name => "Hash_Entries"); -- Hold temporarily (i.e. free'd before returning) the Hash_Entry before -- they are registered in SCO_Raw_Hash_Table. X_Not_Decision : Boolean; -- This flag keeps track of whether a decision sequence in the SCO table -- contains only NOT operators, and is for an expression context (T=X). -- The flag will be set False if T is other than X, or if an operator -- other than NOT is in the sequence. procedure Output_Decision_Operand (N : Node_Id); -- The node N is the top level logical operator of a decision, or it is -- one of the operands of a logical operator belonging to a single -- complex decision. This routine outputs the sequence of table entries -- corresponding to the node. Note that we do not process the sub- -- operands to look for further decisions, that processing is done in -- Process_Decision_Operand, because we can't get decisions mixed up in -- the global table. Call has no effect if N is Empty. procedure Output_Element (N : Node_Id); -- Node N is an operand of a logical operator that is not itself a -- logical operator, or it is a simple decision. This routine outputs -- the table entry for the element, with C1 set to ' '. Last is set -- False, and an entry is made in the condition hash table. procedure Output_Header (T : Character); -- Outputs a decision header node. T is I/W/E/P for IF/WHILE/EXIT WHEN/ -- PRAGMA, and 'X' for the expression case. procedure Process_Decision_Operand (N : Node_Id); -- This is called on node N, the top level node of a decision, or on one -- of its operands or suboperands after generating the full output for -- the complex decision. It process the suboperands of the decision -- looking for nested decisions. function Process_Node (N : Node_Id) return Traverse_Result; -- Processes one node in the traversal, looking for logical operators, -- and if one is found, outputs the appropriate table entries. ----------------------------- -- Output_Decision_Operand -- ----------------------------- procedure Output_Decision_Operand (N : Node_Id) is C1 : Character; C2 : Character; -- C1 holds a character that identifies the operation while C2 -- indicates whether we are sure (' ') or not ('?') this operation -- belongs to the decision. '?' entries will be filtered out in the -- second (SCO_Record_Filtered) pass. L : Node_Id; T : Tristate; begin if No (N) then return; end if; T := Is_Logical_Operator (N); -- Logical operator if T /= False then if Nkind (N) = N_Op_Not then C1 := '!'; L := Empty; else L := Left_Opnd (N); if Nkind_In (N, N_Op_Or, N_Or_Else) then C1 := '|'; else pragma Assert (Nkind_In (N, N_Op_And, N_And_Then)); C1 := '&'; end if; end if; if T = True then C2 := ' '; else C2 := '?'; end if; Set_Raw_Table_Entry (C1 => C1, C2 => C2, From => Sloc (N), To => No_Location, Last => False); Hash_Entries.Append ((Sloc (N), SCO_Raw_Table.Last)); Output_Decision_Operand (L); Output_Decision_Operand (Right_Opnd (N)); -- Not a logical operator else Output_Element (N); end if; end Output_Decision_Operand; -------------------- -- Output_Element -- -------------------- procedure Output_Element (N : Node_Id) is FSloc : Source_Ptr; LSloc : Source_Ptr; begin Sloc_Range (N, FSloc, LSloc); Set_Raw_Table_Entry (C1 => ' ', C2 => 'c', From => FSloc, To => LSloc, Last => False); Hash_Entries.Append ((FSloc, SCO_Raw_Table.Last)); end Output_Element; ------------------- -- Output_Header -- ------------------- procedure Output_Header (T : Character) is Loc : Source_Ptr := No_Location; -- Node whose Sloc is used for the decision Nam : Name_Id := No_Name; -- For the case of an aspect, aspect name begin case T is when 'I' | 'E' | 'W' | 'a' | 'A' => -- For IF, EXIT, WHILE, or aspects, the token SLOC is that of -- the parent of the expression. Loc := Sloc (Parent (N)); if T = 'a' or else T = 'A' then Nam := Chars (Identifier (Parent (N))); end if; when 'G' | 'P' => -- For entry guard, the token sloc is from the N_Entry_Body. -- For PRAGMA, we must get the location from the pragma node. -- Argument N is the pragma argument, and we have to go up -- two levels (through the pragma argument association) to -- get to the pragma node itself. For the guard on a select -- alternative, we do not have access to the token location for -- the WHEN, so we use the first sloc of the condition itself -- (note: we use First_Sloc, not Sloc, because this is what is -- referenced by dominance markers). -- Doesn't this requirement of using First_Sloc need to be -- documented in the spec ??? if Nkind_In (Parent (N), N_Accept_Alternative, N_Delay_Alternative, N_Terminate_Alternative) then Loc := First_Sloc (N); else Loc := Sloc (Parent (Parent (N))); end if; when 'X' => -- For an expression, no Sloc null; -- No other possibilities when others => raise Program_Error; end case; Set_Raw_Table_Entry (C1 => T, C2 => ' ', From => Loc, To => No_Location, Last => False, Pragma_Sloc => Pragma_Sloc, Pragma_Aspect_Name => Nam); -- For an aspect specification, which will be rewritten into a -- pragma, enter a hash table entry now. if T = 'a' then Hash_Entries.Append ((Loc, SCO_Raw_Table.Last)); end if; end Output_Header; ------------------------------ -- Process_Decision_Operand -- ------------------------------ procedure Process_Decision_Operand (N : Node_Id) is begin if Is_Logical_Operator (N) /= False then if Nkind (N) /= N_Op_Not then Process_Decision_Operand (Left_Opnd (N)); X_Not_Decision := False; end if; Process_Decision_Operand (Right_Opnd (N)); else Process_Decisions (N, 'X', Pragma_Sloc); end if; end Process_Decision_Operand; ------------------ -- Process_Node -- ------------------ function Process_Node (N : Node_Id) return Traverse_Result is begin case Nkind (N) is -- Logical operators, output table entries and then process -- operands recursively to deal with nested conditions. when N_And_Then | N_Op_And | N_Op_Not | N_Op_Or | N_Or_Else => declare T : Character; begin -- If outer level, then type comes from call, otherwise it -- is more deeply nested and counts as X for expression. if N = Process_Decisions.N then T := Process_Decisions.T; else T := 'X'; end if; -- Output header for sequence X_Not_Decision := T = 'X' and then Nkind (N) = N_Op_Not; Mark := SCO_Raw_Table.Last; Mark_Hash := Hash_Entries.Last; Output_Header (T); -- Output the decision Output_Decision_Operand (N); -- If the decision was in an expression context (T = 'X') -- and contained only NOT operators, then we don't output -- it, so delete it. if X_Not_Decision then SCO_Raw_Table.Set_Last (Mark); Hash_Entries.Set_Last (Mark_Hash); -- Otherwise, set Last in last table entry to mark end else SCO_Raw_Table.Table (SCO_Raw_Table.Last).Last := True; end if; -- Process any embedded decisions Process_Decision_Operand (N); return Skip; end; -- Case expression -- Really hard to believe this is correct given the special -- handling for if expressions below ??? when N_Case_Expression => return OK; -- ??? -- If expression, processed like an if statement when N_If_Expression => declare Cond : constant Node_Id := First (Expressions (N)); Thnx : constant Node_Id := Next (Cond); Elsx : constant Node_Id := Next (Thnx); begin Process_Decisions (Cond, 'I', Pragma_Sloc); Process_Decisions (Thnx, 'X', Pragma_Sloc); Process_Decisions (Elsx, 'X', Pragma_Sloc); return Skip; end; -- All other cases, continue scan when others => return OK; end case; end Process_Node; procedure Traverse is new Traverse_Proc (Process_Node); -- Start of processing for Process_Decisions begin if No (N) then return; end if; Hash_Entries.Init; -- See if we have simple decision at outer level and if so then -- generate the decision entry for this simple decision. A simple -- decision is a boolean expression (which is not a logical operator -- or short circuit form) appearing as the operand of an IF, WHILE, -- EXIT WHEN, or special PRAGMA construct. if T /= 'X' and then Is_Logical_Operator (N) = False then Output_Header (T); Output_Element (N); -- Change Last in last table entry to True to mark end of -- sequence, which is this case is only one element long. SCO_Raw_Table.Table (SCO_Raw_Table.Last).Last := True; end if; Traverse (N); -- Now we have the definitive set of SCO entries, register them in the -- corresponding hash table. for J in 1 .. Hash_Entries.Last loop SCO_Raw_Hash_Table.Set (Hash_Entries.Table (J).Sloc, Hash_Entries.Table (J).SCO_Index); end loop; Hash_Entries.Free; end Process_Decisions; ----------- -- pscos -- ----------- procedure pscos is procedure Write_Info_Char (C : Character) renames Write_Char; -- Write one character; procedure Write_Info_Initiate (Key : Character) renames Write_Char; -- Start new one and write one character; procedure Write_Info_Nat (N : Nat); -- Write value of N procedure Write_Info_Terminate renames Write_Eol; -- Terminate current line -------------------- -- Write_Info_Nat -- -------------------- procedure Write_Info_Nat (N : Nat) is begin Write_Int (N); end Write_Info_Nat; procedure Debug_Put_SCOs is new Put_SCOs; -- Start of processing for pscos begin Debug_Put_SCOs; end pscos; --------------------- -- Record_Instance -- --------------------- procedure Record_Instance (Id : Instance_Id; Inst_Sloc : Source_Ptr) is Inst_Src : constant Source_File_Index := Get_Source_File_Index (Inst_Sloc); begin SCO_Instance_Table.Append ((Inst_Dep_Num => Dependency_Num (Unit (Inst_Src)), Inst_Loc => To_Source_Location (Inst_Sloc), Enclosing_Instance => SCO_Instance_Index (Instance (Inst_Src)))); pragma Assert (SCO_Instance_Table.Last = SCO_Instance_Index (Id)); end Record_Instance; ---------------- -- SCO_Output -- ---------------- procedure SCO_Output is procedure Populate_SCO_Instance_Table is new Sinput.Iterate_On_Instances (Record_Instance); begin pragma Assert (SCO_Generation_State = Filtered); if Debug_Flag_Dot_OO then dsco; end if; Populate_SCO_Instance_Table; -- Sort the unit tables based on dependency numbers Unit_Table_Sort : declare function Lt (Op1 : Natural; Op2 : Natural) return Boolean; -- Comparison routine for sort call procedure Move (From : Natural; To : Natural); -- Move routine for sort call -------- -- Lt -- -------- function Lt (Op1 : Natural; Op2 : Natural) return Boolean is begin return Dependency_Num (SCO_Unit_Number_Table.Table (SCO_Unit_Index (Op1))) < Dependency_Num (SCO_Unit_Number_Table.Table (SCO_Unit_Index (Op2))); end Lt; ---------- -- Move -- ---------- procedure Move (From : Natural; To : Natural) is begin SCO_Unit_Table.Table (SCO_Unit_Index (To)) := SCO_Unit_Table.Table (SCO_Unit_Index (From)); SCO_Unit_Number_Table.Table (SCO_Unit_Index (To)) := SCO_Unit_Number_Table.Table (SCO_Unit_Index (From)); end Move; package Sorting is new GNAT.Heap_Sort_G (Move, Lt); -- Start of processing for Unit_Table_Sort begin Sorting.Sort (Integer (SCO_Unit_Table.Last)); end Unit_Table_Sort; -- Loop through entries in the unit table to set file name and -- dependency number entries. for J in 1 .. SCO_Unit_Table.Last loop declare U : constant Unit_Number_Type := SCO_Unit_Number_Table.Table (J); UTE : SCO_Unit_Table_Entry renames SCO_Unit_Table.Table (J); begin Get_Name_String (Reference_Name (Source_Index (U))); UTE.File_Name := new String'(Name_Buffer (1 .. Name_Len)); UTE.Dep_Num := Dependency_Num (U); end; end loop; -- Now the tables are all setup for output to the ALI file Write_SCOs_To_ALI_File; end SCO_Output; ------------------------- -- SCO_Pragma_Disabled -- ------------------------- function SCO_Pragma_Disabled (Loc : Source_Ptr) return Boolean is Index : Nat; begin if Loc = No_Location then return False; end if; Index := SCO_Raw_Hash_Table.Get (Loc); -- The test here for zero is to deal with possible previous errors, and -- for the case of pragma statement SCOs, for which we always set the -- Pragma_Sloc even if the particular pragma cannot be specifically -- disabled. if Index /= 0 then declare T : SCO_Table_Entry renames SCO_Raw_Table.Table (Index); begin case T.C1 is when 'S' => -- Pragma statement return T.C2 = 'p'; when 'A' => -- Aspect decision (enabled) return False; when 'a' => -- Aspect decision (not enabled) return True; when ASCII.NUL => -- Nullified disabled SCO return True; when others => raise Program_Error; end case; end; else return False; end if; end SCO_Pragma_Disabled; -------------------- -- SCO_Record_Raw -- -------------------- procedure SCO_Record_Raw (U : Unit_Number_Type) is procedure Traverse_Aux_Decls (N : Node_Id); -- Traverse the Aux_Decls_Node of compilation unit N ------------------------ -- Traverse_Aux_Decls -- ------------------------ procedure Traverse_Aux_Decls (N : Node_Id) is ADN : constant Node_Id := Aux_Decls_Node (N); begin Traverse_Declarations_Or_Statements (Config_Pragmas (ADN)); Traverse_Declarations_Or_Statements (Pragmas_After (ADN)); -- Declarations and Actions do not correspond to source constructs, -- they contain only nodes from expansion, so at this point they -- should still be empty: pragma Assert (No (Declarations (ADN))); pragma Assert (No (Actions (ADN))); end Traverse_Aux_Decls; -- Local variables From : Nat; Lu : Node_Id; -- Start of processing for SCO_Record_Raw begin -- It is legitimate to run this pass multiple times (once per unit) so -- run it even if it was already run before. pragma Assert (SCO_Generation_State in None .. Raw); SCO_Generation_State := Raw; -- Ignore call if not generating code and generating SCO's if not (Generate_SCO and then Operating_Mode = Generate_Code) then return; end if; -- Ignore call if this unit already recorded for J in 1 .. SCO_Unit_Number_Table.Last loop if U = SCO_Unit_Number_Table.Table (J) then return; end if; end loop; -- Otherwise record starting entry From := SCO_Raw_Table.Last + 1; -- Get Unit (checking case of subunit) Lu := Unit (Cunit (U)); if Nkind (Lu) = N_Subunit then Lu := Proper_Body (Lu); end if; -- Traverse the unit Traverse_Aux_Decls (Cunit (U)); case Nkind (Lu) is when N_Generic_Instantiation | N_Generic_Package_Declaration | N_Package_Body | N_Package_Declaration | N_Protected_Body | N_Subprogram_Body | N_Subprogram_Declaration | N_Task_Body => Traverse_Declarations_Or_Statements (L => No_List, P => Lu); -- All other cases of compilation units (e.g. renamings), generate no -- SCO information. when others => null; end case; -- Make entry for new unit in unit tables, we will fill in the file -- name and dependency numbers later. SCO_Unit_Table.Append ( (Dep_Num => 0, File_Name => null, File_Index => Get_Source_File_Index (Sloc (Lu)), From => From, To => SCO_Raw_Table.Last)); SCO_Unit_Number_Table.Append (U); end SCO_Record_Raw; ----------------------- -- Set_SCO_Condition -- ----------------------- procedure Set_SCO_Condition (Cond : Node_Id; Val : Boolean) is -- SCO annotations are not processed after the filtering pass pragma Assert (not Generate_SCO or else SCO_Generation_State = Raw); Constant_Condition_Code : constant array (Boolean) of Character := (False => 'f', True => 't'); Orig : constant Node_Id := Original_Node (Cond); Dummy : Source_Ptr; Index : Nat; Start : Source_Ptr; begin Sloc_Range (Orig, Start, Dummy); Index := SCO_Raw_Hash_Table.Get (Start); -- Index can be zero for boolean expressions that do not have SCOs -- (simple decisions outside of a control flow structure), or in case -- of a previous error. if Index = 0 then return; else pragma Assert (SCO_Raw_Table.Table (Index).C1 = ' '); SCO_Raw_Table.Table (Index).C2 := Constant_Condition_Code (Val); end if; end Set_SCO_Condition; ------------------------------ -- Set_SCO_Logical_Operator -- ------------------------------ procedure Set_SCO_Logical_Operator (Op : Node_Id) is -- SCO annotations are not processed after the filtering pass pragma Assert (not Generate_SCO or else SCO_Generation_State = Raw); Orig : constant Node_Id := Original_Node (Op); Orig_Sloc : constant Source_Ptr := Sloc (Orig); Index : constant Nat := SCO_Raw_Hash_Table.Get (Orig_Sloc); begin -- All (putative) logical operators are supposed to have their own entry -- in the SCOs table. However, the semantic analysis may invoke this -- subprogram with nodes that are out of the SCO generation scope. if Index /= 0 then SCO_Raw_Table.Table (Index).C2 := ' '; end if; end Set_SCO_Logical_Operator; ---------------------------- -- Set_SCO_Pragma_Enabled -- ---------------------------- procedure Set_SCO_Pragma_Enabled (Loc : Source_Ptr) is -- SCO annotations are not processed after the filtering pass pragma Assert (not Generate_SCO or else SCO_Generation_State = Raw); Index : Nat; begin -- Nothing to do if not generating SCO, or if we're not processing the -- original source occurrence of the pragma. if not (Generate_SCO and then In_Extended_Main_Source_Unit (Loc) and then not (In_Instance or In_Inlined_Body)) then return; end if; -- Note: the reason we use the Sloc value as the key is that in the -- generic case, the call to this procedure is made on a copy of the -- original node, so we can't use the Node_Id value. Index := SCO_Raw_Hash_Table.Get (Loc); -- A zero index here indicates that semantic analysis found an -- activated pragma at Loc which does not have a corresponding pragma -- or aspect at the syntax level. This may occur in legitimate cases -- because of expanded code (such are Pre/Post conditions generated for -- formal parameter validity checks), or as a consequence of a previous -- error. if Index = 0 then return; else declare T : SCO_Table_Entry renames SCO_Raw_Table.Table (Index); begin -- Note: may be called multiple times for the same sloc, so -- account for the fact that the entry may already have been -- marked enabled. case T.C1 is -- Aspect (decision SCO) when 'a' => T.C1 := 'A'; when 'A' => null; -- Pragma (statement SCO) when 'S' => pragma Assert (T.C2 = 'p' or else T.C2 = 'P'); T.C2 := 'P'; when others => raise Program_Error; end case; end; end if; end Set_SCO_Pragma_Enabled; ------------------------- -- Set_Raw_Table_Entry -- ------------------------- procedure Set_Raw_Table_Entry (C1 : Character; C2 : Character; From : Source_Ptr; To : Source_Ptr; Last : Boolean; Pragma_Sloc : Source_Ptr := No_Location; Pragma_Aspect_Name : Name_Id := No_Name) is pragma Assert (SCO_Generation_State = Raw); begin SCO_Raw_Table.Append ((C1 => C1, C2 => C2, From => To_Source_Location (From), To => To_Source_Location (To), Last => Last, Pragma_Sloc => Pragma_Sloc, Pragma_Aspect_Name => Pragma_Aspect_Name)); end Set_Raw_Table_Entry; ------------------------ -- To_Source_Location -- ------------------------ function To_Source_Location (S : Source_Ptr) return Source_Location is begin if S = No_Location then return No_Source_Location; else return (Line => Get_Logical_Line_Number (S), Col => Get_Column_Number (S)); end if; end To_Source_Location; ----------------------------------------- -- Traverse_Declarations_Or_Statements -- ----------------------------------------- -- Tables used by Traverse_Declarations_Or_Statements for temporarily -- holding statement and decision entries. These are declared globally -- since they are shared by recursive calls to this procedure. type SC_Entry is record N : Node_Id; From : Source_Ptr; To : Source_Ptr; Typ : Character; end record; -- Used to store a single entry in the following table, From:To represents -- the range of entries in the CS line entry, and typ is the type, with -- space meaning that no type letter will accompany the entry. package SC is new Table.Table (Table_Component_Type => SC_Entry, Table_Index_Type => Nat, Table_Low_Bound => 1, Table_Initial => 1000, Table_Increment => 200, Table_Name => "SCO_SC"); -- Used to store statement components for a CS entry to be output as a -- result of the call to this procedure. SC.Last is the last entry stored, -- so the current statement sequence is represented by SC_Array (SC_First -- .. SC.Last), where SC_First is saved on entry to each recursive call to -- the routine. -- -- Extend_Statement_Sequence adds an entry to this array, and then -- Set_Statement_Entry clears the entries starting with SC_First, copying -- these entries to the main SCO output table. The reason that we do the -- temporary caching of results in this array is that we want the SCO table -- entries for a given CS line to be contiguous, and the processing may -- output intermediate entries such as decision entries. type SD_Entry is record Nod : Node_Id; Lst : List_Id; Typ : Character; Plo : Source_Ptr; end record; -- Used to store a single entry in the following table. Nod is the node to -- be searched for decisions for the case of Process_Decisions_Defer with a -- node argument (with Lst set to No_List. Lst is the list to be searched -- for decisions for the case of Process_Decisions_Defer with a List -- argument (in which case Nod is set to Empty). Plo is the sloc of the -- enclosing pragma, if any. package SD is new Table.Table (Table_Component_Type => SD_Entry, Table_Index_Type => Nat, Table_Low_Bound => 1, Table_Initial => 1000, Table_Increment => 200, Table_Name => "SCO_SD"); -- Used to store possible decision information. Instead of calling the -- Process_Decisions procedures directly, we call Process_Decisions_Defer, -- which simply stores the arguments in this table. Then when we clear -- out a statement sequence using Set_Statement_Entry, after generating -- the CS lines for the statements, the entries in this table result in -- calls to Process_Decision. The reason for doing things this way is to -- ensure that decisions are output after the CS line for the statements -- in which the decisions occur. procedure Traverse_Declarations_Or_Statements (L : List_Id; D : Dominant_Info := No_Dominant; P : Node_Id := Empty) is Discard_Dom : Dominant_Info; pragma Warnings (Off, Discard_Dom); begin Discard_Dom := Traverse_Declarations_Or_Statements (L, D, P); end Traverse_Declarations_Or_Statements; function Traverse_Declarations_Or_Statements (L : List_Id; D : Dominant_Info := No_Dominant; P : Node_Id := Empty) return Dominant_Info is Current_Dominant : Dominant_Info := D; -- Dominance information for the current basic block Current_Test : Node_Id; -- Conditional node (N_If_Statement or N_Elsiif being processed N : Node_Id; SC_First : constant Nat := SC.Last + 1; SD_First : constant Nat := SD.Last + 1; -- Record first entries used in SC/SD at this recursive level procedure Extend_Statement_Sequence (N : Node_Id; Typ : Character); -- Extend the current statement sequence to encompass the node N. Typ is -- the letter that identifies the type of statement/declaration that is -- being added to the sequence. procedure Process_Decisions_Defer (N : Node_Id; T : Character); pragma Inline (Process_Decisions_Defer); -- This routine is logically the same as Process_Decisions, except that -- the arguments are saved in the SD table for later processing when -- Set_Statement_Entry is called, which goes through the saved entries -- making the corresponding calls to Process_Decision. Note: the -- enclosing statement must have already been added to the current -- statement sequence, so that nested decisions are properly -- identified as such. procedure Process_Decisions_Defer (L : List_Id; T : Character); pragma Inline (Process_Decisions_Defer); -- Same case for list arguments, deferred call to Process_Decisions procedure Set_Statement_Entry; -- Output CS entries for all statements saved in table SC, and end the -- current CS sequence. Then output entries for all decisions nested in -- these statements, which have been deferred so far. procedure Traverse_One (N : Node_Id); -- Traverse one declaration or statement procedure Traverse_Aspects (N : Node_Id); -- Helper for Traverse_One: traverse N's aspect specifications procedure Traverse_Degenerate_Subprogram (N : Node_Id); -- Common code to handle null procedures and expression functions. Emit -- a SCO of the given Kind and N outside of the dominance flow. ------------------------------- -- Extend_Statement_Sequence -- ------------------------------- procedure Extend_Statement_Sequence (N : Node_Id; Typ : Character) is Dummy : Source_Ptr; F : Source_Ptr; T : Source_Ptr; To_Node : Node_Id := Empty; begin Sloc_Range (N, F, T); case Nkind (N) is when N_Accept_Statement => if Present (Parameter_Specifications (N)) then To_Node := Last (Parameter_Specifications (N)); elsif Present (Entry_Index (N)) then To_Node := Entry_Index (N); end if; when N_Case_Statement => To_Node := Expression (N); when N_Elsif_Part | N_If_Statement => To_Node := Condition (N); when N_Extended_Return_Statement => To_Node := Last (Return_Object_Declarations (N)); when N_Loop_Statement => To_Node := Iteration_Scheme (N); when N_Asynchronous_Select | N_Conditional_Entry_Call | N_Selective_Accept | N_Single_Protected_Declaration | N_Single_Task_Declaration | N_Timed_Entry_Call => T := F; when N_Protected_Type_Declaration | N_Task_Type_Declaration => if Has_Aspects (N) then To_Node := Last (Aspect_Specifications (N)); elsif Present (Discriminant_Specifications (N)) then To_Node := Last (Discriminant_Specifications (N)); else To_Node := Defining_Identifier (N); end if; when N_Subexpr => To_Node := N; when others => null; end case; if Present (To_Node) then Sloc_Range (To_Node, Dummy, T); end if; SC.Append ((N, F, T, Typ)); end Extend_Statement_Sequence; ----------------------------- -- Process_Decisions_Defer -- ----------------------------- procedure Process_Decisions_Defer (N : Node_Id; T : Character) is begin SD.Append ((N, No_List, T, Current_Pragma_Sloc)); end Process_Decisions_Defer; procedure Process_Decisions_Defer (L : List_Id; T : Character) is begin SD.Append ((Empty, L, T, Current_Pragma_Sloc)); end Process_Decisions_Defer; ------------------------- -- Set_Statement_Entry -- ------------------------- procedure Set_Statement_Entry is SC_Last : constant Int := SC.Last; SD_Last : constant Int := SD.Last; begin -- Output statement entries from saved entries in SC table for J in SC_First .. SC_Last loop if J = SC_First then if Current_Dominant /= No_Dominant then declare From : Source_Ptr; To : Source_Ptr; begin Sloc_Range (Current_Dominant.N, From, To); if Current_Dominant.K /= 'E' then To := No_Location; end if; Set_Raw_Table_Entry (C1 => '>', C2 => Current_Dominant.K, From => From, To => To, Last => False, Pragma_Sloc => No_Location, Pragma_Aspect_Name => No_Name); end; end if; end if; declare SCE : SC_Entry renames SC.Table (J); Pragma_Sloc : Source_Ptr := No_Location; Pragma_Aspect_Name : Name_Id := No_Name; begin -- For the case of a statement SCO for a pragma controlled by -- Set_SCO_Pragma_Enabled, set Pragma_Sloc so that the SCO (and -- those of any nested decision) is emitted only if the pragma -- is enabled. if SCE.Typ = 'p' then Pragma_Sloc := SCE.From; SCO_Raw_Hash_Table.Set (Pragma_Sloc, SCO_Raw_Table.Last + 1); Pragma_Aspect_Name := Pragma_Name_Unmapped (SCE.N); pragma Assert (Pragma_Aspect_Name /= No_Name); elsif SCE.Typ = 'P' then Pragma_Aspect_Name := Pragma_Name_Unmapped (SCE.N); pragma Assert (Pragma_Aspect_Name /= No_Name); end if; Set_Raw_Table_Entry (C1 => 'S', C2 => SCE.Typ, From => SCE.From, To => SCE.To, Last => (J = SC_Last), Pragma_Sloc => Pragma_Sloc, Pragma_Aspect_Name => Pragma_Aspect_Name); end; end loop; -- Last statement of basic block, if present, becomes new current -- dominant. if SC_Last >= SC_First then Current_Dominant := ('S', SC.Table (SC_Last).N); end if; -- Clear out used section of SC table SC.Set_Last (SC_First - 1); -- Output any embedded decisions for J in SD_First .. SD_Last loop declare SDE : SD_Entry renames SD.Table (J); begin if Present (SDE.Nod) then Process_Decisions (SDE.Nod, SDE.Typ, SDE.Plo); else Process_Decisions (SDE.Lst, SDE.Typ, SDE.Plo); end if; end; end loop; -- Clear out used section of SD table SD.Set_Last (SD_First - 1); end Set_Statement_Entry; ---------------------- -- Traverse_Aspects -- ---------------------- procedure Traverse_Aspects (N : Node_Id) is AE : Node_Id; AN : Node_Id; C1 : Character; begin AN := First (Aspect_Specifications (N)); while Present (AN) loop AE := Expression (AN); -- SCOs are generated before semantic analysis/expansion: -- PPCs are not split yet. pragma Assert (not Split_PPC (AN)); C1 := ASCII.NUL; case Get_Aspect_Id (AN) is -- Aspects rewritten into pragmas controlled by a Check_Policy: -- Current_Pragma_Sloc must be set to the sloc of the aspect -- specification. The corresponding pragma will have the same -- sloc. when Aspect_Invariant | Aspect_Post | Aspect_Postcondition | Aspect_Pre | Aspect_Precondition | Aspect_Type_Invariant => C1 := 'a'; -- Aspects whose checks are generated in client units, -- regardless of whether or not the check is activated in the -- unit which contains the declaration: create decision as -- unconditionally enabled aspect (but still make a pragma -- entry since Set_SCO_Pragma_Enabled will be called when -- analyzing actual checks, possibly in other units). -- Pre/post can have checks in client units too because of -- inheritance, so should they be moved here??? when Aspect_Dynamic_Predicate | Aspect_Predicate | Aspect_Static_Predicate => C1 := 'A'; -- Other aspects: just process any decision nested in the -- aspect expression. when others => if Has_Decision (AE) then C1 := 'X'; end if; end case; if C1 /= ASCII.NUL then pragma Assert (Current_Pragma_Sloc = No_Location); if C1 = 'a' or else C1 = 'A' then Current_Pragma_Sloc := Sloc (AN); end if; Process_Decisions_Defer (AE, C1); Current_Pragma_Sloc := No_Location; end if; Next (AN); end loop; end Traverse_Aspects; ------------------------------------ -- Traverse_Degenerate_Subprogram -- ------------------------------------ procedure Traverse_Degenerate_Subprogram (N : Node_Id) is begin -- Complete current sequence of statements Set_Statement_Entry; declare Saved_Dominant : constant Dominant_Info := Current_Dominant; -- Save last statement in current sequence as dominant begin -- Output statement SCO for degenerate subprogram body (null -- statement or freestanding expression) outside of the dominance -- chain. Current_Dominant := No_Dominant; Extend_Statement_Sequence (N, Typ => ' '); -- For the case of an expression-function, collect decisions -- embedded in the expression now. if Nkind (N) in N_Subexpr then Process_Decisions_Defer (N, 'X'); end if; Set_Statement_Entry; -- Restore current dominant information designating last statement -- in previous sequence (i.e. make the dominance chain skip over -- the degenerate body). Current_Dominant := Saved_Dominant; end; end Traverse_Degenerate_Subprogram; ------------------ -- Traverse_One -- ------------------ procedure Traverse_One (N : Node_Id) is begin -- Initialize or extend current statement sequence. Note that for -- special cases such as IF and Case statements we will modify -- the range to exclude internal statements that should not be -- counted as part of the current statement sequence. case Nkind (N) is -- Package declaration when N_Package_Declaration => Set_Statement_Entry; Traverse_Package_Declaration (N, Current_Dominant); -- Generic package declaration when N_Generic_Package_Declaration => Set_Statement_Entry; Traverse_Generic_Package_Declaration (N); -- Package body when N_Package_Body => Set_Statement_Entry; Traverse_Package_Body (N); -- Subprogram declaration or subprogram body stub when N_Expression_Function | N_Subprogram_Body_Stub | N_Subprogram_Declaration => declare Spec : constant Node_Id := Specification (N); begin Process_Decisions_Defer (Parameter_Specifications (Spec), 'X'); -- Case of a null procedure: generate a NULL statement SCO if Nkind (N) = N_Subprogram_Declaration and then Nkind (Spec) = N_Procedure_Specification and then Null_Present (Spec) then Traverse_Degenerate_Subprogram (N); -- Case of an expression function: generate a statement SCO -- for the expression (and then decision SCOs for any nested -- decisions). elsif Nkind (N) = N_Expression_Function then Traverse_Degenerate_Subprogram (Expression (N)); end if; end; -- Entry declaration when N_Entry_Declaration => Process_Decisions_Defer (Parameter_Specifications (N), 'X'); -- Generic subprogram declaration when N_Generic_Subprogram_Declaration => Process_Decisions_Defer (Generic_Formal_Declarations (N), 'X'); Process_Decisions_Defer (Parameter_Specifications (Specification (N)), 'X'); -- Task or subprogram body when N_Subprogram_Body | N_Task_Body => Set_Statement_Entry; Traverse_Subprogram_Or_Task_Body (N); -- Entry body when N_Entry_Body => declare Cond : constant Node_Id := Condition (Entry_Body_Formal_Part (N)); Inner_Dominant : Dominant_Info := No_Dominant; begin Set_Statement_Entry; if Present (Cond) then Process_Decisions_Defer (Cond, 'G'); -- For an entry body with a barrier, the entry body -- is dominanted by a True evaluation of the barrier. Inner_Dominant := ('T', N); end if; Traverse_Subprogram_Or_Task_Body (N, Inner_Dominant); end; -- Protected body when N_Protected_Body => Set_Statement_Entry; Traverse_Declarations_Or_Statements (Declarations (N)); -- Exit statement, which is an exit statement in the SCO sense, -- so it is included in the current statement sequence, but -- then it terminates this sequence. We also have to process -- any decisions in the exit statement expression. when N_Exit_Statement => Extend_Statement_Sequence (N, 'E'); Process_Decisions_Defer (Condition (N), 'E'); Set_Statement_Entry; -- If condition is present, then following statement is -- only executed if the condition evaluates to False. if Present (Condition (N)) then Current_Dominant := ('F', N); else Current_Dominant := No_Dominant; end if; -- Label, which breaks the current statement sequence, but the -- label itself is not included in the next statement sequence, -- since it generates no code. when N_Label => Set_Statement_Entry; Current_Dominant := No_Dominant; -- Block statement, which breaks the current statement sequence when N_Block_Statement => Set_Statement_Entry; -- The first statement in the handled sequence of statements -- is dominated by the elaboration of the last declaration. Current_Dominant := Traverse_Declarations_Or_Statements (L => Declarations (N), D => Current_Dominant); Traverse_Handled_Statement_Sequence (N => Handled_Statement_Sequence (N), D => Current_Dominant); -- If statement, which breaks the current statement sequence, -- but we include the condition in the current sequence. when N_If_Statement => Current_Test := N; Extend_Statement_Sequence (N, 'I'); Process_Decisions_Defer (Condition (N), 'I'); Set_Statement_Entry; -- Now we traverse the statements in the THEN part Traverse_Declarations_Or_Statements (L => Then_Statements (N), D => ('T', N)); -- Loop through ELSIF parts if present if Present (Elsif_Parts (N)) then declare Saved_Dominant : constant Dominant_Info := Current_Dominant; Elif : Node_Id := First (Elsif_Parts (N)); begin while Present (Elif) loop -- An Elsif is executed only if the previous test -- got a FALSE outcome. Current_Dominant := ('F', Current_Test); -- Now update current test information Current_Test := Elif; -- We generate a statement sequence for the -- construct "ELSIF condition", so that we have -- a statement for the resulting decisions. Extend_Statement_Sequence (Elif, 'I'); Process_Decisions_Defer (Condition (Elif), 'I'); Set_Statement_Entry; -- An ELSIF part is never guaranteed to have -- been executed, following statements are only -- dominated by the initial IF statement. Current_Dominant := Saved_Dominant; -- Traverse the statements in the ELSIF Traverse_Declarations_Or_Statements (L => Then_Statements (Elif), D => ('T', Elif)); Next (Elif); end loop; end; end if; -- Finally traverse the ELSE statements if present Traverse_Declarations_Or_Statements (L => Else_Statements (N), D => ('F', Current_Test)); -- CASE statement, which breaks the current statement sequence, -- but we include the expression in the current sequence. when N_Case_Statement => Extend_Statement_Sequence (N, 'C'); Process_Decisions_Defer (Expression (N), 'X'); Set_Statement_Entry; -- Process case branches, all of which are dominated by the -- CASE statement. declare Alt : Node_Id; begin Alt := First_Non_Pragma (Alternatives (N)); while Present (Alt) loop Traverse_Declarations_Or_Statements (L => Statements (Alt), D => Current_Dominant); Next (Alt); end loop; end; -- ACCEPT statement when N_Accept_Statement => Extend_Statement_Sequence (N, 'A'); Set_Statement_Entry; -- Process sequence of statements, dominant is the ACCEPT -- statement. Traverse_Handled_Statement_Sequence (N => Handled_Statement_Sequence (N), D => Current_Dominant); -- SELECT when N_Selective_Accept => Extend_Statement_Sequence (N, 'S'); Set_Statement_Entry; -- Process alternatives declare Alt : Node_Id; Guard : Node_Id; S_Dom : Dominant_Info; begin Alt := First (Select_Alternatives (N)); while Present (Alt) loop S_Dom := Current_Dominant; Guard := Condition (Alt); if Present (Guard) then Process_Decisions (Guard, 'G', Pragma_Sloc => No_Location); Current_Dominant := ('T', Guard); end if; Traverse_One (Alt); Current_Dominant := S_Dom; Next (Alt); end loop; end; Traverse_Declarations_Or_Statements (L => Else_Statements (N), D => Current_Dominant); when N_Conditional_Entry_Call | N_Timed_Entry_Call => Extend_Statement_Sequence (N, 'S'); Set_Statement_Entry; -- Process alternatives Traverse_One (Entry_Call_Alternative (N)); if Nkind (N) = N_Timed_Entry_Call then Traverse_One (Delay_Alternative (N)); else Traverse_Declarations_Or_Statements (L => Else_Statements (N), D => Current_Dominant); end if; when N_Asynchronous_Select => Extend_Statement_Sequence (N, 'S'); Set_Statement_Entry; Traverse_One (Triggering_Alternative (N)); Traverse_Declarations_Or_Statements (L => Statements (Abortable_Part (N)), D => Current_Dominant); when N_Accept_Alternative => Traverse_Declarations_Or_Statements (L => Statements (N), D => Current_Dominant, P => Accept_Statement (N)); when N_Entry_Call_Alternative => Traverse_Declarations_Or_Statements (L => Statements (N), D => Current_Dominant, P => Entry_Call_Statement (N)); when N_Delay_Alternative => Traverse_Declarations_Or_Statements (L => Statements (N), D => Current_Dominant, P => Delay_Statement (N)); when N_Triggering_Alternative => Traverse_Declarations_Or_Statements (L => Statements (N), D => Current_Dominant, P => Triggering_Statement (N)); when N_Terminate_Alternative => -- It is dubious to emit a statement SCO for a TERMINATE -- alternative, since no code is actually executed if the -- alternative is selected -- the tasking runtime call just -- never returns??? Extend_Statement_Sequence (N, ' '); Set_Statement_Entry; -- Unconditional exit points, which are included in the current -- statement sequence, but then terminate it when N_Goto_Statement | N_Raise_Statement | N_Requeue_Statement => Extend_Statement_Sequence (N, ' '); Set_Statement_Entry; Current_Dominant := No_Dominant; -- Simple return statement. which is an exit point, but we -- have to process the return expression for decisions. when N_Simple_Return_Statement => Extend_Statement_Sequence (N, ' '); Process_Decisions_Defer (Expression (N), 'X'); Set_Statement_Entry; Current_Dominant := No_Dominant; -- Extended return statement when N_Extended_Return_Statement => Extend_Statement_Sequence (N, 'R'); Process_Decisions_Defer (Return_Object_Declarations (N), 'X'); Set_Statement_Entry; Traverse_Handled_Statement_Sequence (N => Handled_Statement_Sequence (N), D => Current_Dominant); Current_Dominant := No_Dominant; -- Loop ends the current statement sequence, but we include -- the iteration scheme if present in the current sequence. -- But the body of the loop starts a new sequence, since it -- may not be executed as part of the current sequence. when N_Loop_Statement => declare ISC : constant Node_Id := Iteration_Scheme (N); Inner_Dominant : Dominant_Info := No_Dominant; begin if Present (ISC) then -- If iteration scheme present, extend the current -- statement sequence to include the iteration scheme -- and process any decisions it contains. -- While loop if Present (Condition (ISC)) then Extend_Statement_Sequence (N, 'W'); Process_Decisions_Defer (Condition (ISC), 'W'); -- Set more specific dominant for inner statements -- (the control sloc for the decision is that of -- the WHILE token). Inner_Dominant := ('T', ISC); -- For loop else Extend_Statement_Sequence (N, 'F'); Process_Decisions_Defer (Loop_Parameter_Specification (ISC), 'X'); end if; end if; Set_Statement_Entry; if Inner_Dominant = No_Dominant then Inner_Dominant := Current_Dominant; end if; Traverse_Declarations_Or_Statements (L => Statements (N), D => Inner_Dominant); end; -- Pragma when N_Pragma => -- Record sloc of pragma (pragmas don't nest) pragma Assert (Current_Pragma_Sloc = No_Location); Current_Pragma_Sloc := Sloc (N); -- Processing depends on the kind of pragma declare Nam : constant Name_Id := Pragma_Name_Unmapped (N); Arg : Node_Id := First (Pragma_Argument_Associations (N)); Typ : Character; begin case Nam is when Name_Assert | Name_Assert_And_Cut | Name_Assume | Name_Check | Name_Loop_Invariant | Name_Postcondition | Name_Precondition => -- For Assert/Check/Precondition/Postcondition, we -- must generate a P entry for the decision. Note -- that this is done unconditionally at this stage. -- Output for disabled pragmas is suppressed later -- on when we output the decision line in Put_SCOs, -- depending on setting by Set_SCO_Pragma_Enabled. if Nam = Name_Check then Next (Arg); end if; Process_Decisions_Defer (Expression (Arg), 'P'); Typ := 'p'; -- Pre/postconditions can be inherited so SCO should -- never be deactivated??? when Name_Debug => if Present (Arg) and then Present (Next (Arg)) then -- Case of a dyadic pragma Debug: first argument -- is a P decision, any nested decision in the -- second argument is an X decision. Process_Decisions_Defer (Expression (Arg), 'P'); Next (Arg); end if; Process_Decisions_Defer (Expression (Arg), 'X'); Typ := 'p'; -- For all other pragmas, we generate decision entries -- for any embedded expressions, and the pragma is -- never disabled. -- Should generate P decisions (not X) for assertion -- related pragmas: [Type_]Invariant, -- [{Static,Dynamic}_]Predicate??? when others => Process_Decisions_Defer (N, 'X'); Typ := 'P'; end case; -- Add statement SCO Extend_Statement_Sequence (N, Typ); Current_Pragma_Sloc := No_Location; end; -- Object declaration. Ignored if Prev_Ids is set, since the -- parser generates multiple instances of the whole declaration -- if there is more than one identifier declared, and we only -- want one entry in the SCOs, so we take the first, for which -- Prev_Ids is False. when N_Number_Declaration | N_Object_Declaration => if not Prev_Ids (N) then Extend_Statement_Sequence (N, 'o'); if Has_Decision (N) then Process_Decisions_Defer (N, 'X'); end if; end if; -- All other cases, which extend the current statement sequence -- but do not terminate it, even if they have nested decisions. when N_Protected_Type_Declaration | N_Task_Type_Declaration => Extend_Statement_Sequence (N, 't'); Process_Decisions_Defer (Discriminant_Specifications (N), 'X'); Set_Statement_Entry; Traverse_Sync_Definition (N); when N_Single_Protected_Declaration | N_Single_Task_Declaration => Extend_Statement_Sequence (N, 'o'); Set_Statement_Entry; Traverse_Sync_Definition (N); when others => -- Determine required type character code, or ASCII.NUL if -- no SCO should be generated for this node. declare NK : constant Node_Kind := Nkind (N); Typ : Character; begin case NK is when N_Full_Type_Declaration | N_Incomplete_Type_Declaration | N_Private_Extension_Declaration | N_Private_Type_Declaration => Typ := 't'; when N_Subtype_Declaration => Typ := 's'; when N_Renaming_Declaration => Typ := 'r'; when N_Generic_Instantiation => Typ := 'i'; when N_Package_Body_Stub | N_Protected_Body_Stub | N_Representation_Clause | N_Task_Body_Stub | N_Use_Package_Clause | N_Use_Type_Clause => Typ := ASCII.NUL; when N_Procedure_Call_Statement => Typ := ' '; when others => if NK in N_Statement_Other_Than_Procedure_Call then Typ := ' '; else Typ := 'd'; end if; end case; if Typ /= ASCII.NUL then Extend_Statement_Sequence (N, Typ); end if; end; -- Process any embedded decisions if Has_Decision (N) then Process_Decisions_Defer (N, 'X'); end if; end case; -- Process aspects if present Traverse_Aspects (N); end Traverse_One; -- Start of processing for Traverse_Declarations_Or_Statements begin -- Process single prefixed node if Present (P) then Traverse_One (P); end if; -- Loop through statements or declarations if Is_Non_Empty_List (L) then N := First (L); while Present (N) loop -- Note: For separate bodies, we see the tree after Par.Labl has -- introduced implicit labels, so we need to ignore those nodes. if Nkind (N) /= N_Implicit_Label_Declaration then Traverse_One (N); end if; Next (N); end loop; end if; -- End sequence of statements and flush deferred decisions if Present (P) or else Is_Non_Empty_List (L) then Set_Statement_Entry; end if; return Current_Dominant; end Traverse_Declarations_Or_Statements; ------------------------------------------ -- Traverse_Generic_Package_Declaration -- ------------------------------------------ procedure Traverse_Generic_Package_Declaration (N : Node_Id) is begin Process_Decisions (Generic_Formal_Declarations (N), 'X', No_Location); Traverse_Package_Declaration (N); end Traverse_Generic_Package_Declaration; ----------------------------------------- -- Traverse_Handled_Statement_Sequence -- ----------------------------------------- procedure Traverse_Handled_Statement_Sequence (N : Node_Id; D : Dominant_Info := No_Dominant) is Handler : Node_Id; begin -- For package bodies without a statement part, the parser adds an empty -- one, to normalize the representation. The null statement therein, -- which does not come from source, does not get a SCO. if Present (N) and then Comes_From_Source (N) then Traverse_Declarations_Or_Statements (Statements (N), D); if Present (Exception_Handlers (N)) then Handler := First_Non_Pragma (Exception_Handlers (N)); while Present (Handler) loop Traverse_Declarations_Or_Statements (L => Statements (Handler), D => ('E', Handler)); Next (Handler); end loop; end if; end if; end Traverse_Handled_Statement_Sequence; --------------------------- -- Traverse_Package_Body -- --------------------------- procedure Traverse_Package_Body (N : Node_Id) is Dom : Dominant_Info; begin -- The first statement in the handled sequence of statements is -- dominated by the elaboration of the last declaration. Dom := Traverse_Declarations_Or_Statements (Declarations (N)); Traverse_Handled_Statement_Sequence (Handled_Statement_Sequence (N), Dom); end Traverse_Package_Body; ---------------------------------- -- Traverse_Package_Declaration -- ---------------------------------- procedure Traverse_Package_Declaration (N : Node_Id; D : Dominant_Info := No_Dominant) is Spec : constant Node_Id := Specification (N); Dom : Dominant_Info; begin Dom := Traverse_Declarations_Or_Statements (Visible_Declarations (Spec), D); -- First private declaration is dominated by last visible declaration Traverse_Declarations_Or_Statements (Private_Declarations (Spec), Dom); end Traverse_Package_Declaration; ------------------------------ -- Traverse_Sync_Definition -- ------------------------------ procedure Traverse_Sync_Definition (N : Node_Id) is Dom_Info : Dominant_Info := ('S', N); -- The first declaration is dominated by the protected or task [type] -- declaration. Sync_Def : Node_Id; -- N's protected or task definition Priv_Decl : List_Id; Vis_Decl : List_Id; -- Sync_Def's Visible_Declarations and Private_Declarations begin case Nkind (N) is when N_Protected_Type_Declaration | N_Single_Protected_Declaration => Sync_Def := Protected_Definition (N); when N_Single_Task_Declaration | N_Task_Type_Declaration => Sync_Def := Task_Definition (N); when others => raise Program_Error; end case; -- Sync_Def may be Empty at least for empty Task_Type_Declarations. -- Querying Visible or Private_Declarations is invalid in this case. if Present (Sync_Def) then Vis_Decl := Visible_Declarations (Sync_Def); Priv_Decl := Private_Declarations (Sync_Def); else Vis_Decl := No_List; Priv_Decl := No_List; end if; Dom_Info := Traverse_Declarations_Or_Statements (L => Vis_Decl, D => Dom_Info); -- If visible declarations are present, the first private declaration -- is dominated by the last visible declaration. Traverse_Declarations_Or_Statements (L => Priv_Decl, D => Dom_Info); end Traverse_Sync_Definition; -------------------------------------- -- Traverse_Subprogram_Or_Task_Body -- -------------------------------------- procedure Traverse_Subprogram_Or_Task_Body (N : Node_Id; D : Dominant_Info := No_Dominant) is Decls : constant List_Id := Declarations (N); Dom_Info : Dominant_Info := D; begin -- If declarations are present, the first statement is dominated by the -- last declaration. Dom_Info := Traverse_Declarations_Or_Statements (L => Decls, D => Dom_Info); Traverse_Handled_Statement_Sequence (N => Handled_Statement_Sequence (N), D => Dom_Info); end Traverse_Subprogram_Or_Task_Body; ------------------------- -- SCO_Record_Filtered -- ------------------------- procedure SCO_Record_Filtered is type Decision is record Kind : Character; -- Type of the SCO decision (see comments for SCO_Table_Entry.C1) Sloc : Source_Location; Top : Nat; -- Index in the SCO_Raw_Table for the root operator/condition for the -- expression that controls the decision. end record; -- Decision descriptor: used to gather information about a candidate -- SCO decision. package Pending_Decisions is new Table.Table (Table_Component_Type => Decision, Table_Index_Type => Nat, Table_Low_Bound => 1, Table_Initial => 1000, Table_Increment => 200, Table_Name => "Filter_Pending_Decisions"); -- Table used to hold decisions to process during the collection pass procedure Add_Expression_Tree (Idx : in out Nat); -- Add SCO raw table entries for the decision controlling expression -- tree starting at Idx to the filtered SCO table. procedure Collect_Decisions (D : Decision; Next : out Nat); -- Collect decisions to add to the filtered SCO table starting at the -- D decision (including it and its nested operators/conditions). Set -- Next to the first node index passed the whole decision. procedure Compute_Range (Idx : in out Nat; From : out Source_Location; To : out Source_Location); -- Compute the source location range for the expression tree starting at -- Idx in the SCO raw table. Store its bounds in From and To. function Is_Decision (Idx : Nat) return Boolean; -- Return if the expression tree starting at Idx has adjacent nested -- nodes that make a decision. procedure Process_Pending_Decisions (Original_Decision : SCO_Table_Entry); -- Complete the filtered SCO table using collected decisions. Output -- decisions inherit the pragma information from the original decision. procedure Search_Nested_Decisions (Idx : in out Nat); -- Collect decisions to add to the filtered SCO table starting at the -- node at Idx in the SCO raw table. This node must not be part of an -- already-processed decision. Set Idx to the first node index passed -- the whole expression tree. procedure Skip_Decision (Idx : in out Nat; Process_Nested_Decisions : Boolean); -- Skip all the nodes that belong to the decision starting at Idx. If -- Process_Nested_Decision, call Search_Nested_Decisions on the first -- nested nodes that do not belong to the decision. Set Idx to the first -- node index passed the whole expression tree. ------------------------- -- Add_Expression_Tree -- ------------------------- procedure Add_Expression_Tree (Idx : in out Nat) is Node_Idx : constant Nat := Idx; T : SCO_Table_Entry renames SCO_Raw_Table.Table (Node_Idx); From : Source_Location; To : Source_Location; begin case T.C1 is when ' ' => -- This is a single condition. Add an entry for it and move on SCO_Table.Append (T); Idx := Idx + 1; when '!' => -- This is a NOT operator: add an entry for it and browse its -- only child. SCO_Table.Append (T); Idx := Idx + 1; Add_Expression_Tree (Idx); when others => -- This must be an AND/OR/AND THEN/OR ELSE operator if T.C2 = '?' then -- This is not a short circuit operator: consider this one -- and all its children as a single condition. Compute_Range (Idx, From, To); SCO_Table.Append ((From => From, To => To, C1 => ' ', C2 => 'c', Last => False, Pragma_Sloc => No_Location, Pragma_Aspect_Name => No_Name)); else -- This is a real short circuit operator: add an entry for -- it and browse its children. SCO_Table.Append (T); Idx := Idx + 1; Add_Expression_Tree (Idx); Add_Expression_Tree (Idx); end if; end case; end Add_Expression_Tree; ----------------------- -- Collect_Decisions -- ----------------------- procedure Collect_Decisions (D : Decision; Next : out Nat) is Idx : Nat := D.Top; begin if D.Kind /= 'X' or else Is_Decision (D.Top) then Pending_Decisions.Append (D); end if; Skip_Decision (Idx, True); Next := Idx; end Collect_Decisions; ------------------- -- Compute_Range -- ------------------- procedure Compute_Range (Idx : in out Nat; From : out Source_Location; To : out Source_Location) is Sloc_F : Source_Location := No_Source_Location; Sloc_T : Source_Location := No_Source_Location; procedure Process_One; -- Process one node of the tree, and recurse over children. Update -- Idx during the traversal. ----------------- -- Process_One -- ----------------- procedure Process_One is begin if Sloc_F = No_Source_Location or else SCO_Raw_Table.Table (Idx).From < Sloc_F then Sloc_F := SCO_Raw_Table.Table (Idx).From; end if; if Sloc_T = No_Source_Location or else Sloc_T < SCO_Raw_Table.Table (Idx).To then Sloc_T := SCO_Raw_Table.Table (Idx).To; end if; if SCO_Raw_Table.Table (Idx).C1 = ' ' then -- This is a condition: nothing special to do Idx := Idx + 1; elsif SCO_Raw_Table.Table (Idx).C1 = '!' then -- The "not" operator has only one operand Idx := Idx + 1; Process_One; else -- This is an AND THEN or OR ELSE logical operator: follow the -- left, then the right operands. Idx := Idx + 1; Process_One; Process_One; end if; end Process_One; -- Start of processing for Compute_Range begin Process_One; From := Sloc_F; To := Sloc_T; end Compute_Range; ----------------- -- Is_Decision -- ----------------- function Is_Decision (Idx : Nat) return Boolean is Index : Nat := Idx; begin loop declare T : SCO_Table_Entry renames SCO_Raw_Table.Table (Index); begin case T.C1 is when ' ' => return False; when '!' => -- This is a decision iff the only operand of the NOT -- operator could be a standalone decision. Index := Idx + 1; when others => -- This node is a logical operator (and thus could be a -- standalone decision) iff it is a short circuit -- operator. return T.C2 /= '?'; end case; end; end loop; end Is_Decision; ------------------------------- -- Process_Pending_Decisions -- ------------------------------- procedure Process_Pending_Decisions (Original_Decision : SCO_Table_Entry) is begin for Index in 1 .. Pending_Decisions.Last loop declare D : Decision renames Pending_Decisions.Table (Index); Idx : Nat := D.Top; begin -- Add a SCO table entry for the decision itself pragma Assert (D.Kind /= ' '); SCO_Table.Append ((To => No_Source_Location, From => D.Sloc, C1 => D.Kind, C2 => ' ', Last => False, Pragma_Sloc => Original_Decision.Pragma_Sloc, Pragma_Aspect_Name => Original_Decision.Pragma_Aspect_Name)); -- Then add ones for its nested operators/operands. Do not -- forget to tag its *last* entry as such. Add_Expression_Tree (Idx); SCO_Table.Table (SCO_Table.Last).Last := True; end; end loop; -- Clear the pending decisions list Pending_Decisions.Set_Last (0); end Process_Pending_Decisions; ----------------------------- -- Search_Nested_Decisions -- ----------------------------- procedure Search_Nested_Decisions (Idx : in out Nat) is begin loop declare T : SCO_Table_Entry renames SCO_Raw_Table.Table (Idx); begin case T.C1 is when ' ' => Idx := Idx + 1; exit; when '!' => Collect_Decisions ((Kind => 'X', Sloc => T.From, Top => Idx), Idx); exit; when others => if T.C2 = '?' then -- This is not a logical operator: start looking for -- nested decisions from here. Recurse over the left -- child and let the loop take care of the right one. Idx := Idx + 1; Search_Nested_Decisions (Idx); else -- We found a nested decision Collect_Decisions ((Kind => 'X', Sloc => T.From, Top => Idx), Idx); exit; end if; end case; end; end loop; end Search_Nested_Decisions; ------------------- -- Skip_Decision -- ------------------- procedure Skip_Decision (Idx : in out Nat; Process_Nested_Decisions : Boolean) is begin loop declare T : SCO_Table_Entry renames SCO_Raw_Table.Table (Idx); begin Idx := Idx + 1; case T.C1 is when ' ' => exit; when '!' => -- This NOT operator belongs to the outside decision: -- just skip it. null; when others => if T.C2 = '?' and then Process_Nested_Decisions then -- This is not a logical operator: start looking for -- nested decisions from here. Recurse over the left -- child and let the loop take care of the right one. Search_Nested_Decisions (Idx); else -- This is a logical operator, so it belongs to the -- outside decision: skip its left child, then let the -- loop take care of the right one. Skip_Decision (Idx, Process_Nested_Decisions); end if; end case; end; end loop; end Skip_Decision; -- Start of processing for SCO_Record_Filtered begin -- Filtering must happen only once: do nothing if it this pass was -- already run. if SCO_Generation_State = Filtered then return; else pragma Assert (SCO_Generation_State = Raw); SCO_Generation_State := Filtered; end if; -- Loop through all SCO entries under SCO units for Unit_Idx in 1 .. SCO_Unit_Table.Last loop declare Unit : SCO_Unit_Table_Entry renames SCO_Unit_Table.Table (Unit_Idx); Idx : Nat := Unit.From; -- Index of the current SCO raw table entry New_From : constant Nat := SCO_Table.Last + 1; -- After copying SCO enties of interest to the final table, we -- will have to change the From/To indexes this unit targets. -- This constant keeps track of the new From index. begin while Idx <= Unit.To loop declare T : SCO_Table_Entry renames SCO_Raw_Table.Table (Idx); begin case T.C1 is -- Decision (of any kind, including pragmas and aspects) when 'E' | 'G' | 'I' | 'W' | 'X' | 'P' | 'a' | 'A' => if SCO_Pragma_Disabled (T.Pragma_Sloc) then -- Skip SCO entries for decisions in disabled -- constructs (pragmas or aspects). Idx := Idx + 1; Skip_Decision (Idx, False); else Collect_Decisions ((Kind => T.C1, Sloc => T.From, Top => Idx + 1), Idx); Process_Pending_Decisions (T); end if; -- There is no translation/filtering to do for other kind -- of SCO items (statements, dominance markers, etc.). when '|' | '&' | '!' | ' ' => -- SCO logical operators and conditions cannot exist -- on their own: they must be inside a decision (such -- entries must have been skipped by -- Collect_Decisions). raise Program_Error; when others => SCO_Table.Append (T); Idx := Idx + 1; end case; end; end loop; -- Now, update the SCO entry indexes in the unit entry Unit.From := New_From; Unit.To := SCO_Table.Last; end; end loop; -- Then clear the raw table to free bytes SCO_Raw_Table.Free; end SCO_Record_Filtered; end Par_SCO;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 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.Containers.Ordered_Sets; with Ada.Real_Time; with Orka.Behaviors; with Orka.Cameras; with Orka.Jobs.System; use Ada.Real_Time; generic Time_Step, Frame_Limit : Time_Span; Camera : Cameras.Camera_Ptr; with package Job_Manager is new Orka.Jobs.System (<>); Maximum_Frame_Time : Time_Span := Milliseconds (1000); -- Maximum allowed duration of a frame. The simulation loop will -- exit by raising an exception if this time is exceeded package Orka.Loops is protected Handler is procedure Stop; procedure Set_Frame_Limit (Value : Time_Span); function Frame_Limit return Time_Span; procedure Enable_Limit (Enable : Boolean); function Limit_Enabled return Boolean; function Should_Stop return Boolean; private Limit : Time_Span := Orka.Loops.Frame_Limit; Stop_Flag : Boolean := False; Limit_Flag : Boolean := False; end Handler; use type Behaviors.Behavior_Ptr; use type Behaviors.Behavior_Array_Access; function "<" (Left, Right : Behaviors.Behavior_Ptr) return Boolean; package Behavior_Sets is new Ada.Containers.Ordered_Sets (Behaviors.Behavior_Ptr, "<", "="); protected Scene is procedure Add (Object : Behaviors.Behavior_Ptr) with Post => Modified; procedure Remove (Object : Behaviors.Behavior_Ptr) with Post => Modified; procedure Replace_Array (Target : in out Behaviors.Behavior_Array_Access) with Pre => Target /= null, Post => Target /= null and not Modified; function Modified return Boolean; procedure Set_Camera (Camera : Cameras.Camera_Ptr); function Camera return Cameras.Camera_Ptr; private Modified_Flag : Boolean := False; Behaviors_Set : Behavior_Sets.Set; Scene_Camera : Cameras.Camera_Ptr := Orka.Loops.Camera; end Scene; procedure Stop_Loop; procedure Run_Loop (Render : not null access procedure (Scene : not null Behaviors.Behavior_Array_Access; Camera : Cameras.Camera_Ptr)); end Orka.Loops;
with Ada.Text_IO; with Ada.Command_Line; with SDL.Video.Windows.Makers; with SDL.Video.Renderers.Makers; with SDL.Video.Surfaces.Makers; with SDL.Video.Textures.Makers; with SDL.Images.IO; with SDL.Events.Events; with SDL.Error; procedure Main is Window_Title : constant String := "Hello World!"; Image_Name : constant String := "../img/grumpy-cat.png"; use SDL.Video; use type Windows.Window_Flags; use type Renderers.Renderer_flags; use type SDL.Events.Event_Types; Win : Windows.Window; Ren : Renderers.Renderer; Bmp : Surfaces.Surface; Tex : Textures.Texture; Event : SDL.Events.Events.Events; Dummy : Boolean; begin -- Initialise SDL if not SDL.Initialise or not SDL.Images.Initialise then Ada.Text_IO.Put_Line (Ada.Text_IO.Standard_Error, "SDL.Initialise error: " & SDL.Error.Get); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); return; end if; -- Create window Windows.Makers.Create (Win, Title => Window_Title, Position => (100, 100), Size => (620, 387), Flags => Windows.Shown); -- Create renderer Renderers.Makers.Create (Rend => Ren, Window => Win, Flags => (Renderers.Accelerated or Renderers.Present_V_Sync)); -- Create image SDL.Images.IO.Create (Surface => Bmp, File_Name => Image_Name); -- Create texture Textures.Makers.Create (Tex => Tex, Renderer => Ren, Surface => Bmp); -- Present texture Ren.Clear; Ren.Copy (Copy_From => Tex); Ren.Present; -- Event loop -- Exit after 2 seconds for I in 1 .. 200 loop Dummy := SDL.Events.Events.Poll (Event); exit when Event.Common.Event_Type = SDL.Events.Quit; delay 0.010; end loop; -- Cleanup -- Not needed really when soon out of scope Tex.Finalize; Ren.Finalize; Win.Finalize; SDL.Finalise; end Main;
----------------------------------------------------------------------- -- asf-navigations -- Navigations -- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Contexts.Faces; with EL.Expressions; with EL.Contexts; with Ada.Finalization; with ASF.Applications.Views; with Ada.Strings.Unbounded; limited with ASF.Applications.Main; private with Ada.Containers.Vectors; private with Ada.Containers.Hashed_Maps; private with Ada.Strings.Unbounded.Hash; -- The <b>ASF.Navigations</b> package is responsible for calculating the view to be -- rendered after an action is processed. The navigation handler contains some rules -- (defined in XML files) and it uses the current view id, the action outcome and -- the faces context to decide which view must be rendered. -- -- See JSR 314 - JavaServer Faces Specification 7.4 NavigationHandler package ASF.Navigations is -- ------------------------------ -- Navigation Handler -- ------------------------------ type Navigation_Handler is new Ada.Finalization.Limited_Controlled with private; type Navigation_Handler_Access is access all Navigation_Handler'Class; -- After executing an action and getting the action outcome, proceed to the navigation -- to the next page. procedure Handle_Navigation (Handler : in Navigation_Handler; Action : in String; Outcome : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Provide a default navigation rules for the view and the outcome when no application -- navigation was found. The default looks for an XHTML file in the same directory as -- the view and which has the base name defined by <b>Outcome</b>. procedure Handle_Default_Navigation (Handler : in Navigation_Handler; View : in String; Outcome : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Initialize the the lifecycle handler. procedure Initialize (Handler : in out Navigation_Handler; App : access ASF.Applications.Main.Application'Class); -- Free the storage used by the navigation handler. overriding procedure Finalize (Handler : in out Navigation_Handler); -- Add a navigation case to navigate from the view identifier by <b>From</b> -- to the result view identified by <b>To</b>. Some optional conditions are evaluated -- The <b>Outcome</b> must match unless it is empty. -- The <b>Action</b> must match unless it is empty. -- The <b>Condition</b> expression must evaluate to True. procedure Add_Navigation_Case (Handler : in out Navigation_Handler; From : in String; To : in String; Outcome : in String := ""; Action : in String := ""; Condition : in String := ""; Context : in EL.Contexts.ELContext'Class); -- ------------------------------ -- Navigation Case -- ------------------------------ -- The <b>Navigation_Case</b> contains a condition and a navigation action. -- The condition must be matched to execute the navigation action. type Navigation_Case is abstract tagged limited private; type Navigation_Access is access all Navigation_Case'Class; -- Check if the navigator specific condition matches the current execution context. function Matches (Navigator : in Navigation_Case; Action : in String; Outcome : in String; Context : in ASF.Contexts.Faces.Faces_Context'Class) return Boolean; -- Navigate to the next page or action according to the controller's navigator. -- A navigator controller could redirect the user to another page, render a specific -- view or return some raw content. procedure Navigate (Navigator : in Navigation_Case; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is abstract; -- Add a navigation case to navigate from the view identifier by <b>From</b> -- by using the navigation rule defined by <b>Navigator</b>. -- Some optional conditions are evaluated: -- The <b>Outcome</b> must match unless it is empty. -- The <b>Action</b> must match unless it is empty. -- The <b>Condition</b> expression must evaluate to True. procedure Add_Navigation_Case (Handler : in out Navigation_Handler'Class; Navigator : in Navigation_Access; From : in String; Outcome : in String := ""; Action : in String := ""; Condition : in String := ""; Context : in EL.Contexts.ELContext'Class); private use Ada.Strings.Unbounded; type Navigation_Case is abstract tagged limited record -- When not empty, the condition that must be verified to follow this navigator. Condition : EL.Expressions.Expression; View_Handler : access ASF.Applications.Views.View_Handler'Class; Outcome : String_Access; Action : String_Access; end record; package Navigator_Vector is new Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Navigation_Access); -- ------------------------------ -- Navigation Rule -- ------------------------------ type Rule is tagged limited record Navigators : Navigator_Vector.Vector; end record; -- Clear the navigation rules. procedure Clear (Controller : in out Rule); -- Search for the navigator that matches the current action, outcome and context. -- Returns the navigator or null if there was no match. function Find_Navigation (Controller : in Rule; Action : in String; Outcome : in String; Context : in Contexts.Faces.Faces_Context'Class) return Navigation_Access; type Rule_Access is access all Rule'Class; package Rule_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Rule_Access, Hash => Hash, Equivalent_Keys => "="); type Navigation_Rules is limited record -- Exact match rules Rules : Rule_Map.Map; end record; -- Clear the navigation rules. procedure Clear (Controller : in out Navigation_Rules); type Navigation_Rules_Access is access all Navigation_Rules; type Navigation_Handler is new Ada.Finalization.Limited_Controlled with record Rules : Navigation_Rules_Access; Application : access ASF.Applications.Main.Application'Class; View_Handler : access ASF.Applications.Views.View_Handler'Class; end record; end ASF.Navigations;
with Generic_Bounded_Image; with Interfaces; use Interfaces; pragma Elaborate_All (Generic_Bounded_Image); -- @summary functions to provide a string image of numbers -- overapproximating the length, otherwise we would need a -- separate body for each data type. This is tight enough -- in most cases. -- Also note that the intrinsic Image functions return with a leading -- space, which is why package Bounded_Image with SPARK_Mode is function Integer_Img is new Generic_Bounded_Image.Image_32 (Integer) with Inline; function Unsigned_Img is new Generic_Bounded_Image.Image_32 (Unsigned_32) with Inline; function Natural_Img is new Generic_Bounded_Image.Image_32 (Natural) with Inline; function Unsigned8_Img is new Generic_Bounded_Image.Image_4 (Unsigned_8) with Inline; function Integer8_Img is new Generic_Bounded_Image.Image_4 (Integer_8) with Inline; end Bounded_Image;
with impact.d2.Math; package body impact.d2.orbs.Shape is function to_Circle (Radius : in float_math.Real) return Shape.item is begin return (m_radius => Radius); end to_Circle; function Clone (Self : in Item) return Shape.item is begin return Self; end Clone; function test_Point (Self : in Item; xf : in impact.d2.Math.b2Transform; p : in impact.d2.Math.b2Vec2 ) return Boolean is use impact.d2.Math; center : constant impact.d2.Math.b2Vec2 := xf.position; d : constant impact.d2.Math.b2Vec2 := p - center; begin return impact.d2.Math.b2Dot (d, d) <= Self.m_radius * Self.m_radius; end test_Point; -- Collision Detection in Interactive 3D Environments by Gino van den Bergen -- From Section 3.1.2 -- x = s + a * r -- norm(x) = radius -- function ray_Cast (Self : in Item; output : access collision.b2RayCastOutput; input : in collision.b2RayCastInput; transform : in impact.d2.Math.b2Transform ) return Boolean is use float_math.Functions, impact.d2.Math; position : constant impact.d2.Math.b2Vec2 := transform.position; s : constant impact.d2.Math.b2Vec2 := input.p1 - position; b : constant float32 := impact.d2.Math.b2Dot (s, s) - Self.m_radius * Self.m_radius; -- Solve quadratic equation. r : constant b2Vec2 := input.p2 - input.p1; c : constant float32 := impact.d2.Math.b2Dot (s, r); rr : float32 := b2Dot (r, r); sigma : constant float32 := c * c - rr * b; a : float32; begin if sigma < 0.0 or else rr < b2_epsilon then -- Check for negative discriminant and short segment. return False; end if; a := -(c + SqRt (sigma)); -- Find the point of intersection of the line with the circle. if 0.0 <= a and then a <= input.maxFraction * rr then -- Is the intersection point on the segment? a := a / rr; output.fraction := a; output.normal := s + a * r; impact.d2.Math.Normalize (output.normal); return True; end if; return False; end ray_Cast; procedure compute_AABB (Self : in Item; aabb : access collision.b2AABB; xf : in impact.d2.Math.b2Transform) is use impact.d2.Math; p : b2Vec2 := xf.position; begin aabb.lowerBound := (p.x - Self.m_radius, p.y - Self.m_radius); aabb.upperBound := (p.x + Self.m_radius, p.y + Self.m_radius); end compute_AABB; procedure compute_Mass (Self : in Item; massData : access mass_Data; density : in float32) is Radius_squared : constant float32 := Self.m_radius * Self.m_radius; begin massData.mass := density * b2_pi * Radius_squared; massData.center := (0.0, 0.0); -- inertia about the local origin massData.I := massData.mass * (0.5 * Radius_squared); end compute_Mass; function get_Support (Self : in Item; d : in impact.d2.Math.b2Vec2) return int32 is pragma Unreferenced (d, Self); begin return 0; end get_Support; function get_support_Vertex (Self : in Item; d : in impact.d2.Math.b2Vec2) return impact.d2.Math.b2Vec2 is pragma Unreferenced (d, Self); begin return (0.0, 0.0); end get_support_Vertex; function get_vertex_Count (Self : in Item ) return int32 is pragma Unreferenced (Self); begin return 1; end get_vertex_Count; function get_Vertex (Self : in Item; index : in int32) return impact.d2.Math.b2Vec2 is pragma Unreferenced (Self); use type int32; begin pragma Assert (index = 0); return (0.0, 0.0); -- Self.m_p; end get_Vertex; end impact.d2.orbs.Shape;
-- This package has been generated automatically by GNATtest. -- You are allowed to add your code to the bodies of test routines. -- Such changes will be kept during further regeneration of this file. -- All code placed outside of test routine bodies will be lost. The -- code intended to set up and tear down the test environment should be -- placed into Log.Test_Data. with AUnit.Assertions; use AUnit.Assertions; with System.Assertions; -- begin read only -- id:2.2/00/ -- -- This section can be used to add with clauses if necessary. -- -- end read only -- begin read only -- end read only package body Log.Test_Data.Tests is -- begin read only -- id:2.2/01/ -- -- This section can be used to add global variables and other elements. -- -- end read only -- begin read only -- end read only -- begin read only procedure Wrap_Test_Log_Message_6a7537_caf43b (Message: String; Message_Type: Debug_Types; New_Line, Time_Stamp: Boolean := True) is begin begin pragma Assert(Message'Length > 0); null; exception when System.Assertions.Assert_Failure => AUnit.Assertions.Assert (False, "req_sloc(log.ads:0):Test_LogMessage test requirement violated"); end; GNATtest_Generated.GNATtest_Standard.Log.Log_Message (Message, Message_Type, New_Line, Time_Stamp); begin pragma Assert(True); null; exception when System.Assertions.Assert_Failure => AUnit.Assertions.Assert (False, "ens_sloc(log.ads:0:):Test_LogMessage test commitment violated"); end; end Wrap_Test_Log_Message_6a7537_caf43b; -- end read only -- begin read only procedure Test_Log_Message_test_logmessage(Gnattest_T: in out Test); procedure Test_Log_Message_6a7537_caf43b(Gnattest_T: in out Test) renames Test_Log_Message_test_logmessage; -- id:2.2/6a7537630b1363a5/Log_Message/1/0/test_logmessage/ procedure Test_Log_Message_test_logmessage(Gnattest_T: in out Test) is procedure Log_Message (Message: String; Message_Type: Debug_Types; New_Line, Time_Stamp: Boolean := True) renames Wrap_Test_Log_Message_6a7537_caf43b; -- end read only pragma Unreferenced(Gnattest_T); begin Log_Message("Test message", EVERYTHING); End_Logging; Assert(True, "This test can only crash."); -- begin read only end Test_Log_Message_test_logmessage; -- end read only -- begin read only -- id:2.2/02/ -- -- This section can be used to add elaboration code for the global state. -- begin -- end read only null; -- begin read only -- end read only end Log.Test_Data.Tests;
with ada.text_io; use ada.text_io; with ada.integer_text_io; use ada.integer_text_io; with tools; use tools; procedure main is drawDeck: deck; -- Deck cards are drawn fromt discardDeck: deck; -- Deck removed cards are placed to playerHand: deck; -- Player's current hand dealerHand: deck; -- Dealers's current hand Player,Dealer : Boolean := False; temp:integer := 1; response : integer; counter : Integer := 0; chipTotal : Integer := 500; wager : integer := 500; -- =================================================== -- PLAY GAME -- =================================================== procedure displayAll(hand:in deck) is begin new_page; ada.text_io.put("~~~~~~~~~~~~~~~~~~~Playing for :$"); ada.integer_text_io.put(item =>wager, width =>6); ada.text_io.put(" ~~~~~~~~~~~~~~~~~~~~"); new_line; ada.text_io.put("============DEALER============="); new_line; display(dealerHand); ada.text_io.put("Current total ~"); ada.integer_text_io.put(getScore(dealerHand)); new_line; ada.text_io.put("============PLAYER============="); new_line; display(playerHand); ada.text_io.put("Current total ~"); ada.integer_text_io.put(getScore(playerHand)); new_line; ada.text_io.put("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); new_line; end displayAll; Procedure playGame(chips: in integer) is begin loop ada.text_io.put("How much do you want to bet? Current total ~$"); ada.integer_text_io.put(item=>chipTotal, width => 6); new_line; ada.integer_text_io.get(wager); new_line; if wager > chipTotal or wager <= 0 then ada.text_io.put("Invalid entry, try again"); new_line; else chipTotal := chipTotal - wager; exit; end if; end loop; -- Draw starting hands drawToHand(dealerHand,drawDeck,discardDeck); drawToHand(dealerHand,drawDeck,discardDeck); drawToHand(playerHand,drawDeck,discardDeck); drawToHand(playerHand,drawDeck,discardDeck); displayAll(playerHand); -- Player Turn Loop ada.text_io.put("1 to hit 2 to stay"); ada.integer_text_io.get(response); new_line; if response = 1 then drawToHand(playerHand,drawDeck,discardDeck); elsif response = 2 then exit; -- elsif response = 3 then -- showdeck(drawDeck); -- new_line; -- showdeck(playerHand); -- new_line; -- showdeck(dealerHand); end if; displayAll(playerHand); if checkBust(getScore(playerHand)) then exit; end if; end loop; -- Dealer Turn Loop -- Dealer stays on >17, if player busts or is currently winning if getScore(PlayerHand) > 21 or getScore(dealerHand)> getScore(playerHand) then exit; elsif getScore(dealerHand) > 17 and (getScore(playerHand)< getScore(dealerHand)) then exit; else drawToHand(dealerHand,drawDeck,discardDeck); end if; end loop; displayAll(dealerHand); -- Pick winner, reward wager if (checkBust(getScore(playerHand))) then -- player lose new_line; ada.text_io.put("Dealer Wins, you lost $"); ada.integer_text_io.put(wager); elsif (checkBust(getScore(dealerHand))) then -- player win new_line; ada.text_io.put("Player Wins, you won $"); ada.integer_text_io.put(wager); chipTotal := chipTotal + (2*wager); elsif getScore(dealerHand) >= getScore(playerHand) then -- player loses ties new_line; ada.text_io.put("Dealer Wins, you lost $"); ada.integer_text_io.put(wager); elsif getScore(playerHand) > getScore(dealerHand) then -- player win new_line; ada.text_io.put("Player Wins, you won $"); ada.integer_text_io.put(wager); chipTotal := chipTotal + (2*wager); end if; new_line; -- Discard both hands at the end discardHand(dealerHand,discardDeck); discardHand(playerHand,discardDeck); end playGame; -- =========================================== begin-- Set up defaults for decks drawDeck := makeDeck(drawDeck); -- Makes a new deck, puts it in drawDeck discardDeck := makeEmptyDeck(discardDeck); -- Makes a new, empty deck playerHand := makeEmptyDeck(playerHand); -- '' dealerHand := makeEmptyDeck(dealerHand);-- '' loop exit when counter = 50; -- why repeat so much? shuffle(discardDeck, drawDeck); shuffle(drawDeck, discardDeck); counter := counter+1; end loop; -- ================================================== --MAIN LOOP -- ================================================= new_page; loop -- ======================================= -- Main Menu -- ======================================= ada.text_io.put("MAIN MENU "); new_line; ada.text_io.put("Current Money ~ $"); ada.integer_text_io.put(chipTotal); new_line; ada.text_io.put("1) Play New Game"); new_line; ada.text_io.put("2) Quit)"); new_line; ada.integer_text_io.get(response); case response is when 1 => -- play game playGame(chipTotal); when 2 => -- quit exit; when others => -- bad input ada.text_io.put("Invalid input, try again"); new_line; end case; if chipTotal = 0 then new_line; ada.text_io.put("You are out of money. You are being escorted out of the building."); new_line; ada.text_io.put("GAME OVER"); exit; end if; end loop; end main;