commit
stringlengths 40
40
| old_file
stringlengths 2
205
| new_file
stringlengths 2
205
| old_contents
stringlengths 0
32.9k
| new_contents
stringlengths 1
38.9k
| subject
stringlengths 3
9.4k
| message
stringlengths 6
9.84k
| lang
stringlengths 3
13
| license
stringclasses 13
values | repos
stringlengths 6
115k
|
---|---|---|---|---|---|---|---|---|---|
9d231f8c50a18be3ff39c21f9555f7733717ede4
|
src/asis/asis-data_decomposition-extensions.adb
|
src/asis/asis-data_decomposition-extensions.adb
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A S I S . D A T A _ D E C O M P O S I T I O N . E X T E N S I O N S --
-- --
-- B o d y --
-- --
-- Copyright (C) 1995-2010, 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, 59 Temple Place --
-- - Suite 330, Boston, MA 02111-1307, 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 Ada Core Technologies Inc --
-- (http://www.gnat.com). --
-- --
------------------------------------------------------------------------------
with Ada.Unchecked_Conversion;
with System; use System;
with Asis.Data_Decomposition.Vcheck; use Asis.Data_Decomposition.Vcheck;
with Asis.Data_Decomposition.Set_Get; use Asis.Data_Decomposition.Set_Get;
with Asis.Errors; use Asis.Errors;
with Asis.Exceptions; use Asis.Exceptions;
with Asis.Set_Get; use Asis.Set_Get;
with A4G.DDA_Aux; use A4G.DDA_Aux;
with A4G.Vcheck; use A4G.Vcheck;
with Einfo; use Einfo;
with Namet; use Namet;
with Uintp; use Uintp;
with Urealp; use Urealp;
package body Asis.Data_Decomposition.Extensions is
Package_Name : constant String := "Asis.Data_Decomposition.Extensions.";
-----------------------
-- Local subprograms --
-----------------------
procedure Write_Real_To_Buffer (U : Ureal);
-- Puts nnn/ddd to Name_Buffer, where nnn and ddd are integer values of
-- the normalized numerator and denominator of the given real value.
-- This procedure is supposed to be used to output images of positive
-- real values only, so it assumes, that nnn is always positive.
procedure Add_Uint_To_Buffer (U : Uint);
-- Add image of universal integer to Name_Buffer, updating Name_Len
-- (This procedure is the simplified version of the local procedure
-- Exp_Dbug.Add_Uint_To_Buffer - it always consider its argument
-- being positive)
------------------------
-- Add_Uint_To_Buffer --
------------------------
procedure Add_Uint_To_Buffer (U : Uint) is
begin
UI_Image (U, Decimal);
Add_Str_To_Name_Buffer (UI_Image_Buffer (1 .. UI_Image_Length));
end Add_Uint_To_Buffer;
-------------------------------
-- Component_Name_Definition --
-------------------------------
function Component_Name_Definition
(Component : Record_Component)
return Asis.Declaration
is
Result : Asis.Element;
begin
Check_Validity (Component, Package_Name & "Component_Name_Definition");
if Is_Nil (Component) then
Raise_ASIS_Inappropriate_Component
(Diagnosis => Package_Name & "Component_Name_Definition",
Component_Kind => Rec);
end if;
Result := Component_Name (Component);
return Result;
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Outer_Call => Package_Name & "Component_Name_Definition");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Component_Name_Definition",
Ex => Ex);
end Component_Name_Definition;
--------------------------
-- Delta_Value (String) --
--------------------------
function Delta_Value
(Fixed_Point_Subtype : Asis.Element)
return String
is
Arg_Node : Node_Id;
Res_Ureal : Ureal;
begin
Check_Validity
(Fixed_Point_Subtype, Package_Name & "Delta_Value (String)");
Arg_Node := R_Node (Fixed_Point_Subtype);
if not (Int_Kind (Fixed_Point_Subtype) = A_Defining_Identifier and then
Is_Fixed_Point_Type (Arg_Node))
then
Raise_ASIS_Inappropriate_Element
(Diagnosis => Package_Name & "Delta_Value (String)",
Wrong_Kind => Int_Kind (Fixed_Point_Subtype));
end if;
Res_Ureal := Einfo.Delta_Value (Arg_Node);
Write_Real_To_Buffer (Res_Ureal);
return Namet.Name_Buffer (1 .. Namet.Name_Len);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Outer_Call => Package_Name & "Delta_Value (String)",
Argument => Fixed_Point_Subtype);
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Delta_Value (String)",
Ex => Ex,
Arg_Element => Fixed_Point_Subtype);
end Delta_Value;
----------------------------
-- Delta_Value (Fraction) --
----------------------------
function Delta_Value
(Fixed_Point_Subtype : Asis.Element)
return Fraction
is
Arg_Node : Node_Id;
Res_Ureal : Ureal;
Result : Fraction;
begin
Check_Validity
(Fixed_Point_Subtype, Package_Name & "Delta_Value (Fraction)");
Arg_Node := R_Node (Fixed_Point_Subtype);
if not (Int_Kind (Fixed_Point_Subtype) = A_Defining_Identifier and then
Is_Fixed_Point_Type (Arg_Node))
then
Raise_ASIS_Inappropriate_Element
(Diagnosis => Package_Name & "Delta_Value (Fraction)",
Wrong_Kind => Int_Kind (Fixed_Point_Subtype));
end if;
Res_Ureal := Einfo.Delta_Value (Arg_Node);
Result.Num := UI_To_Aint (Norm_Num (Res_Ureal));
Result.Denum := UI_To_Aint (Norm_Den (Res_Ureal));
return Result;
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Outer_Call => Package_Name & "Delta_Value (Fraction)",
Argument => Fixed_Point_Subtype);
end if;
raise;
when Invalid_Data =>
Raise_ASIS_Inappropriate_Element
(Diagnosis => Package_Name & "Delta_Value (Fraction)",
Wrong_Kind => Int_Kind (Fixed_Point_Subtype),
Status => Data_Error);
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Delta_Value (Fraction)",
Ex => Ex,
Arg_Element => Fixed_Point_Subtype);
end Delta_Value;
------------------
-- Digits_Value --
------------------
function Digits_Value
(Floating_Point_Subtype : Asis.Element)
return ASIS_Natural
is
Arg_Node : Node_Id;
begin
Check_Validity (Floating_Point_Subtype, Package_Name & "Digits_Value");
Arg_Node := R_Node (Floating_Point_Subtype);
if not (Int_Kind (Floating_Point_Subtype) = A_Defining_Identifier
and then
(Is_Decimal_Fixed_Point_Type (Arg_Node) or else
Is_Floating_Point_Type (Arg_Node)))
then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Digits_Value",
Wrong_Kind => Int_Kind (Floating_Point_Subtype));
end if;
return ASIS_Natural (UI_To_Int (Einfo.Digits_Value (Arg_Node)));
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Outer_Call => Package_Name & "Digits_Value",
Argument => Floating_Point_Subtype);
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Digits_Value",
Ex => Ex,
Arg_Element => Floating_Point_Subtype);
end Digits_Value;
--------------------------
-- Portable_Data_Value --
--------------------------
function Portable_Data_Value
(Value : Constrained_Subtype)
return Portable_Data
is
Local_Value : aliased constant Constrained_Subtype := Value;
for Local_Value'Alignment use Standard'Maximum_Alignment;
-- We force the maximum alignment for Local_Value to make it
-- compatible with maximum alignment set for Portable_Data
-- in the spec of Asis.Data_Decomposition
subtype Result_Portable_Data is
Portable_Data (1 .. (Constrained_Subtype'Object_Size + 7) / 8);
type Result_Portable_Data_Access is access Result_Portable_Data;
function To_Result_Portable_Data_Access is new
Ada.Unchecked_Conversion (Address, Result_Portable_Data_Access);
Result : constant Result_Portable_Data_Access :=
To_Result_Portable_Data_Access (Local_Value'Address);
begin
return Result.all;
exception
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Outer_Call => Package_Name & "Portable_Data_Value");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Portable_Data_Value",
Ex => Ex);
end Portable_Data_Value;
-----------------
-- Scale_Value --
-----------------
function Scale_Value
(Desimal_Fixed_Point_Subtype : Asis.Element)
return ASIS_Natural
is
Arg_Node : Node_Id;
begin
Check_Validity
(Desimal_Fixed_Point_Subtype, Package_Name & "Scale_Value");
Arg_Node := R_Node (Desimal_Fixed_Point_Subtype);
if not (Int_Kind (Desimal_Fixed_Point_Subtype) = A_Defining_Identifier
and then
Is_Decimal_Fixed_Point_Type (Arg_Node))
then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Scale_Value",
Wrong_Kind => Int_Kind (Desimal_Fixed_Point_Subtype));
end if;
return ASIS_Natural (UI_To_Int (Einfo.Scale_Value (Arg_Node)));
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Outer_Call => Package_Name & "Scale_Value",
Argument => Desimal_Fixed_Point_Subtype);
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Scale_Value",
Ex => Ex,
Arg_Element => Desimal_Fixed_Point_Subtype);
end Scale_Value;
--------------------------
-- Small_Value (String) --
--------------------------
function Small_Value
(Fixed_Point_Subtype : Asis.Element)
return String
is
Arg_Node : Node_Id;
Res_Ureal : Ureal;
begin
Check_Validity
(Fixed_Point_Subtype, Package_Name & "Small_Value (String)");
Arg_Node := R_Node (Fixed_Point_Subtype);
if not (Int_Kind (Fixed_Point_Subtype) = A_Defining_Identifier and then
Is_Fixed_Point_Type (Arg_Node))
then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Small_Value (String)",
Wrong_Kind => Int_Kind (Fixed_Point_Subtype));
end if;
Res_Ureal := Einfo.Small_Value (Arg_Node);
Write_Real_To_Buffer (Res_Ureal);
return Namet.Name_Buffer (1 .. Namet.Name_Len);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Outer_Call => Package_Name & "Small_Value (String)",
Argument => Fixed_Point_Subtype);
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Small_Value (String)",
Ex => Ex,
Arg_Element => Fixed_Point_Subtype);
end Small_Value;
----------------------------
-- Small_Value (Fraction) --
----------------------------
function Small_Value
(Fixed_Point_Subtype : Asis.Element)
return Fraction
is
Arg_Node : Node_Id;
Res_Ureal : Ureal;
Result : Fraction;
begin
Check_Validity
(Fixed_Point_Subtype, Package_Name & "Small_Value (Fraction)");
Arg_Node := R_Node (Fixed_Point_Subtype);
if not (Int_Kind (Fixed_Point_Subtype) = A_Defining_Identifier and then
Is_Fixed_Point_Type (Arg_Node))
then
Raise_ASIS_Inappropriate_Element
(Package_Name & "Small_Value (Fraction)",
Wrong_Kind => Int_Kind (Fixed_Point_Subtype));
end if;
Res_Ureal := Einfo.Small_Value (Arg_Node);
Result.Num := UI_To_Aint (Norm_Num (Res_Ureal));
Result.Denum := UI_To_Aint (Norm_Den (Res_Ureal));
return Result;
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Outer_Call => Package_Name & "Small_Value (Fraction)",
Argument => Fixed_Point_Subtype);
end if;
raise;
when Invalid_Data =>
Raise_ASIS_Inappropriate_Element
(Diagnosis => Package_Name & "Small_Value (Fraction)",
Wrong_Kind => Int_Kind (Fixed_Point_Subtype),
Status => Data_Error);
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Small_Value (Fraction)",
Ex => Ex,
Arg_Element => Fixed_Point_Subtype);
end Small_Value;
--------------------------
-- Write_Real_To_Buffer --
--------------------------
procedure Write_Real_To_Buffer (U : Ureal) is
begin
Namet.Name_Len := 0;
Add_Uint_To_Buffer (Norm_Num (U));
Add_Str_To_Name_Buffer ("/");
Add_Uint_To_Buffer (Norm_Den (U));
end Write_Real_To_Buffer;
end Asis.Data_Decomposition.Extensions;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
3cbc1b35010e1d984365dedf2a4f5eeff592f29a
|
awa/src/awa-commands-list.adb
|
awa/src/awa-commands-list.adb
|
-----------------------------------------------------------------------
-- akt-commands-list -- List commands to report database information for admin tool
-- Copyright (C) 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
with ADO.Sessions;
with ADO.Statements;
with ADO.Schemas;
with ADO.Queries;
with AWA.Commands.Models;
package body AWA.Commands.List is
procedure List (Command : in out Command_Type;
Context : in out Context_Type;
Session : in out ADO.Sessions.Master_Session;
Query : in ADO.Queries.Context;
Prefix : in String);
procedure Database_Summary (Command : in out Command_Type;
Context : in out Context_Type;
Session : in out ADO.Sessions.Master_Session);
-- ------------------------------
-- List some database information.
-- ------------------------------
overriding
procedure Execute (Command : in out Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type) is
begin
Command_Drivers.Application_Command_Type (Command).Execute (Name, Args, Context);
end Execute;
overriding
procedure Execute (Command : in out Command_Type;
Application : in out AWA.Applications.Application'Class;
Args : in Argument_List'Class;
Context : in out Context_Type) is
pragma Unreferenced (Args);
Session : ADO.Sessions.Master_Session;
Query : ADO.Queries.Context;
begin
Application.Load_Bundle (Name => "commands",
Locale => "en",
Bundle => Command.Bundle);
Session := Application.Get_Master_Session;
if Command.List_Users then
Query.Set_Query (AWA.Commands.Models.Query_Command_User_List);
List (Command, Context, Session, Query, "command_user_list_");
end if;
if Command.List_Sessions then
Query.Set_Query (AWA.Commands.Models.Query_Command_Session_List);
List (Command, Context, Session, Query, "command_session_list_");
end if;
if Command.List_Jobs then
Query.Set_Query (AWA.Commands.Models.Query_Command_Job_List);
List (Command, Context, Session, Query, "command_job_list_");
end if;
if Command.List_Tables then
Database_Summary (Command, Context, Session);
end if;
end Execute;
procedure List (Command : in out Command_Type;
Context : in out Context_Type;
Session : in out ADO.Sessions.Master_Session;
Query : in ADO.Queries.Context;
Prefix : in String) is
function Get_Label (Name : in String) return String;
function Get_Label (Name : in String) return String is
Result : constant String := Command.Bundle.Get (Prefix & Name);
begin
if Util.Strings.Index (Result, ':') > 0 then
return Result;
else
return Result & ":10";
end if;
end Get_Label;
Statement : ADO.Statements.Query_Statement;
Print_Names : Boolean := True;
begin
Statement := Session.Create_Statement (Query);
Statement.Execute;
while Statement.Has_Elements loop
if Print_Names then
Context.Console.Start_Title;
for I in 1 .. Statement.Get_Column_Count loop
declare
Info : constant String := Get_Label (Statement.Get_Column_Name (I - 1));
Pos : constant Natural := Util.Strings.Index (Info, ':');
begin
Context.Console.Print_Title (Field_Number (I),
Info (Info'First .. Pos - 1),
Natural'Value (Info (Pos + 1 .. Info'Last)));
end;
end loop;
Context.Console.End_Title;
Print_Names := False;
end if;
Context.Console.Start_Row;
for I in 1 .. Statement.Get_Column_Count loop
if not Statement.Is_Null (I - 1) then
Context.Console.Print_Field (Field_Number (I),
Statement.Get_String (I - 1));
end if;
end loop;
Context.Console.End_Row;
Statement.Next;
end loop;
end List;
procedure Database_Summary (Command : in out Command_Type;
Context : in out Context_Type;
Session : in out ADO.Sessions.Master_Session) is
pragma Unreferenced (Command);
use ADO.Schemas;
Schema : ADO.Schemas.Schema_Definition;
Iter : Table_Cursor;
Col : Field_Number := 1;
begin
Session.Load_Schema (Schema);
Context.Console.Start_Title;
Context.Console.Print_Title (1, "Table", 30);
Context.Console.Print_Title (2, " Count", 8);
Context.Console.Print_Title (3, "", 3);
Context.Console.Print_Title (4, "Table", 30);
Context.Console.Print_Title (5, " Count", 8);
Context.Console.End_Title;
-- Dump the database schema using SQL create table forms.
Iter := Get_Tables (Schema);
while Has_Element (Iter) loop
declare
Table : constant Table_Definition := Element (Iter);
Count : Natural;
Statement : ADO.Statements.Query_Statement;
begin
if Col = 1 then
Context.Console.Start_Row;
end if;
Context.Console.Print_Field (Col, Get_Name (Table));
Statement := Session.Create_Statement ("SELECT COUNT(*) FROM " & Get_Name (Table));
Statement.Execute;
Count := Statement.Get_Integer (0);
Context.Console.Print_Field (Col + 1, Count, Consoles.J_RIGHT);
if Col >= 3 then
Context.Console.End_Row;
Col := 1;
else
Context.Console.Print_Field (Col + 2, "");
Col := Col + 3;
end if;
end;
Next (Iter);
end loop;
if Col /= 1 then
Context.Console.End_Row;
end if;
end Database_Summary;
-- ------------------------------
-- Setup the command before parsing the arguments and executing it.
-- ------------------------------
overriding
procedure Setup (Command : in out Command_Type;
Config : in out GNAT.Command_Line.Command_Line_Configuration;
Context : in out Context_Type) is
begin
GC.Set_Usage (Config => Config,
Usage => Command.Get_Name & " [arguments]",
Help => Command.Get_Description);
Command_Drivers.Application_Command_Type (Command).Setup (Config, Context);
GC.Define_Switch (Config => Config,
Output => Command.List_Users'Access,
Switch => "-u",
Long_Switch => "--users",
Help => -("List the users"));
GC.Define_Switch (Config => Config,
Output => Command.List_Jobs'Access,
Switch => "-j",
Long_Switch => "--jobs",
Help => -("List the jobs"));
GC.Define_Switch (Config => Config,
Output => Command.List_Sessions'Access,
Switch => "-s",
Long_Switch => "--sessions",
Help => -("List the sessions"));
GC.Define_Switch (Config => Config,
Output => Command.List_Tables'Access,
Switch => "-t",
Long_Switch => "--tables",
Help => -("List the database tables"));
end Setup;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Command : in out Command_Type;
Name : in String;
Context : in out Context_Type) is
pragma Unreferenced (Command, Context);
begin
null;
end Help;
begin
Command_Drivers.Driver.Add_Command ("list",
-("list information"),
Command'Access);
end AWA.Commands.List;
|
Implement operations to list database information for AWA applications
|
Implement operations to list database information for AWA applications
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
|
addb5fc5344e8b8c61ab8ef3a1808c24af97c205
|
src/util-streams-buffered-encoders.adb
|
src/util-streams-buffered-encoders.adb
|
-----------------------------------------------------------------------
-- util-streams-encoders -- Streams with encoding and decoding capabilities
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Encoders.Base64;
package body Util.Streams.Buffered.Encoders is
-- -----------------------
-- Initialize the stream to write on the given stream.
-- An internal buffer is allocated for writing the stream.
-- -----------------------
procedure Initialize (Stream : in out Encoding_Stream;
Output : in Output_Stream_Access;
Size : in Natural;
Format : in String) is
begin
Stream.Initialize (Output, Size);
Stream.Transform := new Util.Encoders.Base64.Encoder;
end Initialize;
-- -----------------------
-- Close the sink.
-- -----------------------
overriding
procedure Close (Stream : in out Encoding_Stream) is
begin
Stream.Flush;
Stream.Output.Close;
end Close;
-- -----------------------
-- Write the buffer array to the output stream.
-- -----------------------
overriding
procedure Write (Stream : in out Encoding_Stream;
Buffer : in Ada.Streams.Stream_Element_Array) is
First_Encoded : Ada.Streams.Stream_Element_Offset := Buffer'First;
Last_Encoded : Ada.Streams.Stream_Element_Offset;
Last_Pos : Ada.Streams.Stream_Element_Offset;
begin
while First_Encoded <= Buffer'Last loop
Stream.Transform.Transform
(Data => Buffer (First_Encoded .. Buffer'Last),
Into => Stream.Buffer (Stream.Write_Pos .. Stream.Buffer'Last),
Last => Last_Pos,
Encoded => Last_Encoded);
if Last_Encoded < Buffer'Last then
Stream.Output.Write (Stream.Buffer (Stream.Buffer'First .. Last_Pos));
Stream.Write_Pos := Stream.Buffer'First;
else
Stream.Write_Pos := Last_Pos + 1;
end if;
First_Encoded := Last_Encoded + 1;
end loop;
end Write;
-- -----------------------
-- Flush the buffer by writing on the output stream.
-- Raises Data_Error if there is no output stream.
-- -----------------------
overriding
procedure Flush (Stream : in out Encoding_Stream) is
Last_Pos : Ada.Streams.Stream_Element_Offset;
begin
Stream.Transform.Finish (Stream.Buffer (Stream.Write_Pos .. Stream.Buffer'Last),
Last_Pos);
Stream.Write_Pos := Last_Pos + 1;
Output_Buffer_Stream (Stream).Flush;
end Flush;
-- -----------------------
-- Flush the stream and release the buffer.
-- -----------------------
overriding
procedure Finalize (Object : in out Encoding_Stream) is
begin
null;
end Finalize;
end Util.Streams.Buffered.Encoders;
|
Implement the Encoding_Stream operations
|
Implement the Encoding_Stream operations
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
|
041ac8f097c1e1d5225aedc61584d00728abcdeb
|
src/asis/a4g-stand.adb
|
src/asis/a4g-stand.adb
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . S T A N D --
-- --
-- B o d y --
-- --
-- Copyright (c) 1999-2003, 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, 59 Temple Place --
-- - Suite 330, Boston, MA 02111-1307, 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 Ada Core Technologies Inc --
-- (http://www.gnat.com). --
-- --
------------------------------------------------------------------------------
with Asis.Set_Get; use Asis.Set_Get;
with A4G.A_Types; use A4G.A_Types;
with A4G.Contt; use A4G.Contt;
with Stand; use Stand;
with Atree; use Atree;
with Sinfo; use Sinfo;
package body A4G.Stand is
--------------------------------
-- Get_Numeric_Error_Renaming --
--------------------------------
function Get_Numeric_Error_Renaming return Asis.Element is
Result : Asis.Element := Numeric_Error_Template;
begin
Set_Encl_Tree (Result, Get_Current_Tree);
Set_Enclosing_Context (Result, Get_Current_Cont);
Set_Obtained (Result, A_OS_Time);
return Result;
end Get_Numeric_Error_Renaming;
---------------------------
-- Is_Standard_Char_Type --
---------------------------
function Is_Standard_Char_Type (N : Node_Id) return Boolean is
Result : Boolean := False;
Type_Ent : Entity_Id;
begin
if Sloc (N) = Standard_Location and then
Nkind (N) = N_Enumeration_Type_Definition
then
Type_Ent := Defining_Identifier (Parent (N));
if Type_Ent in Standard_Character .. Standard_Wide_Character then
Result := True;
end if;
end if;
return Result;
end Is_Standard_Char_Type;
-------------------------
-- Standard_Char_Decls --
-------------------------
function Standard_Char_Decls
(Type_Definition : Asis.Type_Definition;
Implicit : Boolean := False)
return Asis.Element_List
is
Arg_Node : constant Node_Id := Node (Type_Definition);
Rel_Len : Asis.ASIS_Positive;
Type_Ent : Entity_Id;
Tmp_Template : Element := Char_Literal_Spec_Template;
begin
-- Adjusting the template for the artificial character literal
-- specification:
Set_Encl_Unit_Id (Tmp_Template, Encl_Unit_Id (Type_Definition));
Set_Encl_Tree (Tmp_Template, Encl_Tree (Type_Definition));
Set_Node (Tmp_Template, Arg_Node);
Set_R_Node (Tmp_Template, Arg_Node);
Set_Enclosing_Context (Tmp_Template, Encl_Cont_Id (Type_Definition));
Set_Obtained (Tmp_Template, A_OS_Time);
Set_From_Instance (Tmp_Template, Is_From_Instance (Type_Definition));
Set_From_Implicit (Tmp_Template, Implicit);
Set_From_Inherited (Tmp_Template, Implicit);
if Implicit then
Set_Special_Case (Tmp_Template, Not_A_Special_Case);
Set_Node_Field_1 (Tmp_Template, Parent (Arg_Node));
end if;
Type_Ent := Defining_Identifier (Parent (Arg_Node));
while Type_Ent /= Etype (Type_Ent) loop
Type_Ent := Etype (Type_Ent);
end loop;
if Type_Ent = Standard_Character then
Rel_Len := 256;
else
Rel_Len := 65536;
end if;
declare
Result : Asis.Element_List (1 .. Rel_Len) := (others => Tmp_Template);
begin
for J in 1 .. Rel_Len loop
Set_Character_Code (Result (J), Char_Code (J - 1));
end loop;
return Result;
end;
end Standard_Char_Decls;
----------------------
-- Stand_Char_Image --
----------------------
function Stand_Char_Image (Code : Char_Code) return Wide_String is
function Hex_Digits (J : Natural) return Wide_String;
-- converts J into Hex digits string
function Hex_Digits (J : Natural) return Wide_String is
Hexd : constant Wide_String := "0123456789abcdef";
begin
if J > 16#FF# then
return Hex_Digits (J / 256) & Hex_Digits (J mod 256);
else
return Hexd (J / 16 + 1) & Hexd (J mod 16 + 1);
end if;
end Hex_Digits;
begin
if Code in 16#20# .. 16#7E# then
return ''' & Wide_Character'Val (Code) & ''';
else
return "'[""" & Hex_Digits (Natural (Code)) & """]'";
end if;
end Stand_Char_Image;
end A4G.Stand;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
|
1ab3dcf5e3d63d16fd4ada43368f9b329980abf0
|
regtests/util-mail-tests.adb
|
regtests/util-mail-tests.adb
|
-----------------------------------------------------------------------
-- util-mail-tests -- Unit tests for mail
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
package body Util.Mail.Tests is
package Caller is new Util.Test_Caller (Test, "Strings");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Mail.Parse_Address",
Test_Parse_Address'Access);
end Add_Tests;
procedure Test_Parse_Address (T : in out Test) is
use Ada.Strings.Unbounded;
procedure Check (Value : in String;
Name : in String;
Email : in String);
procedure Check (Value : in String;
Name : in String;
Email : in String) is
A : constant Email_Address := Parse_Address (Value);
begin
Util.Tests.Assert_Equals (T, Name, To_String (A.Name),
"Invalid name for: " & Value);
Util.Tests.Assert_Equals (T, Email, To_String (A.Address),
"Invalid email for: " & Value);
end Check;
begin
Check ("Luke Jedi <[email protected]> ", "Luke Jedi", "[email protected]");
Check (" <[email protected]> ", "Anakin", "[email protected]");
Check (" [email protected] ", "Vador", "[email protected]");
end Test_Parse_Address;
end Util.Mail.Tests;
|
Implement new unit test for Parse_Address
|
Implement new unit test for Parse_Address
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
|
59e56f2ddcd1c606100e97624faf60be9971cb07
|
awa/plugins/awa-comments/src/awa-comments-beans.ads
|
awa/plugins/awa-comments/src/awa-comments-beans.ads
|
-----------------------------------------------------------------------
-- awa-comments-beans -- Beans for the comments module
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects.Lists;
with ADO;
with ADO.Schemas;
with ADO.Sessions;
with AWA.Comments.Models;
with AWA.Comments.Modules;
-- == Comment Beans ==
-- Several bean types are provided to represent and manage a list of tags.
-- The tag module registers the bean constructors when it is initialized.
-- To use them, one must declare a bean definition in the application XML configuration.
--
-- === Comment_List_Bean ===
-- The <tt>Comment_List_Bean</tt> holds a list of comments and provides operations used by the
-- <tt>awa:tagList</tt> component to add or remove tags within a <tt>h:form</tt> component.
-- A bean can be declared and configured as follows in the XML application configuration file:
--
-- <managed-bean>
-- <managed-bean-name>postCommentList</managed-bean-name>
-- <managed-bean-class>AWA.Comments.Beans.Comment_List_Bean</managed-bean-class>
-- <managed-bean-scope>request</managed-bean-scope>
-- <managed-property>
-- <property-name>entity_type</property-name>
-- <property-class>String</property-class>
-- <value>awa_post</value>
-- </managed-property>
-- <managed-property>
-- <property-name>permission</property-name>
-- <property-class>String</property-class>
-- <value>blog-comment-post</value>
-- </managed-property>
-- </managed-bean>
--
-- The <tt>entity_type</tt> property defines the name of the database table to which the comments
-- are assigned. The <tt>permission</tt> property defines the permission name that must be used
-- to verify that the user has the permission do add or remove the comment.
--
package AWA.Comments.Beans is
type Comment_List_Bean is
new Util.Beans.Objects.Lists.List_Bean and Util.Beans.Basic.Bean with private;
type Comment_List_Bean_Access is access all Comment_List_Bean'Class;
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
overriding
procedure Set_Value (From : in out Comment_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Set the entity type (database table) with which the comments are associated.
procedure Set_Entity_Type (Into : in out Comment_List_Bean;
Table : in ADO.Schemas.Class_Mapping_Access);
-- Set the permission to check before removing or adding a comment on the entity.
procedure Set_Permission (Into : in out Comment_List_Bean;
Permission : in String);
-- Load the comments associated with the given database identifier.
procedure Load_Comments (Into : in out Comment_List_Bean;
Session : in ADO.Sessions.Session;
For_Entity_Id : in ADO.Identifier);
-- Create the comment list bean instance.
function Create_Comment_List_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
private
type Comment_List_Bean is
new Util.Beans.Objects.Lists.List_Bean and Util.Beans.Basic.Bean with record
Module : AWA.Comments.Modules.Comment_Module_Access;
Entity_Type : Ada.Strings.Unbounded.Unbounded_String;
Permission : Ada.Strings.Unbounded.Unbounded_String;
Current : Natural := 0;
end record;
end AWA.Comments.Beans;
|
Define the Comment_List_Bean type to represent a list of comments to be displayed
|
Define the Comment_List_Bean type to represent a list of comments to be displayed
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
|
4c80c06cd9dac5abf9735a16f041ab390ca6c803
|
src/util-commands-drivers.adb
|
src/util-commands-drivers.adb
|
-----------------------------------------------------------------------
-- util-commands-drivers -- Support to make command line tools
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
package body Util.Commands.Drivers is
-- The logger
Logs : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create (Driver_Name);
-- ------------------------------
-- Write the command usage.
-- ------------------------------
procedure Usage (Command : in Command_Type) is
begin
null;
end Usage;
-- ------------------------------
-- Print a message for the command. The level indicates whether the message is an error,
-- warning or informational. The command name can be used to known the originator.
-- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure.
-- ------------------------------
procedure Log (Command : in Command_Type;
Level : in Util.Log.Level_Type;
Name : in String;
Message : in String) is
begin
Command.Driver.Log (Level, Name, Message);
end Log;
-- ------------------------------
-- Register the command under the given name.
-- ------------------------------
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Command : in Command_Access) is
begin
Command.Driver := Driver'Unchecked_Access;
Driver.List.Include (Name, Command);
end Add_Command;
-- ------------------------------
-- Register the command under the given name.
-- ------------------------------
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Handler : in Command_Handler) is
begin
Driver.List.Include (Name, new Handler_Command_Type '(Driver => Driver'Unchecked_Access,
Handler => Handler));
end Add_Command;
-- ------------------------------
-- Find the command having the given name.
-- Returns null if the command was not found.
-- ------------------------------
function Find_Command (Driver : in Driver_Type;
Name : in String) return Command_Access is
Pos : constant Command_Maps.Cursor := Driver.List.Find (Name);
begin
if Command_Maps.Has_Element (Pos) then
return Command_Maps.Element (Pos);
else
return null;
end if;
end Find_Command;
-- ------------------------------
-- Execute the command registered under the given name.
-- ------------------------------
procedure Execute (Driver : in Driver_Type;
Name : in String;
Args : in out Argument_List;
Context : in out Context_Type) is
Command : constant Command_Access := Driver.Find_Command (Name);
begin
if Command /= null then
Command.Execute (Name, Args, Context);
end if;
end Execute;
-- ------------------------------
-- Print a message for the command. The level indicates whether the message is an error,
-- warning or informational. The command name can be used to known the originator.
-- ------------------------------
procedure Log (Driver : in Driver_Type;
Level : in Util.Log.Level_Type;
Name : in String;
Message : in String) is
begin
Logs.Print (Level, "{0}: {1}", Name, Message);
end Log;
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
overriding
procedure Execute (Command : in Handler_Command_Type;
Name : in String;
Args : in out Argument_List;
Context : in out Context_Type) is
begin
Command.Handler (Name, Args, Context);
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Command : in Handler_Command_Type;
Context : in out Context_Type) is
begin
null;
end Help;
end Util.Commands.Drivers;
|
Implement the generic package
|
Implement the generic package
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
|
188551eff2395b48951ac17b16b8aa1270a033f9
|
src/asis/asis-extensions-flat_kinds.adb
|
src/asis/asis-extensions-flat_kinds.adb
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . K N D _ C O N V --
-- --
-- B o d y --
-- --
-- $Revision: 15351 $
-- --
-- Copyright (c) 1995-2002, 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, 59 Temple Place --
-- - Suite 330, Boston, MA 02111-1307, 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 Ada Core Technologies Inc --
-- (http://www.gnat.com). --
-- --
------------------------------------------------------------------------------
with Asis.Set_Get;
with A4G.Knd_Conv; use A4G.Knd_Conv;
with A4G.Vcheck; use A4G.Vcheck;
package body Asis.Extensions.Flat_Kinds is
use Asis;
-----------------------
-- Flat_Element_Kind --
-----------------------
function Flat_Element_Kind
(Element : Asis.Element)
return Flat_Element_Kinds
is
begin
Check_Validity (Element, "Asis.Extensions.Flat_Kinds.Flat_Element_Kind");
return Flat_Element_Kinds (Asis.Set_Get.Int_Kind (Element));
end Flat_Element_Kind;
-------------------------------------------------
-- Flat Element Kinds Conversion Functions --
-------------------------------------------------
function Asis_From_Flat_Kind
(Flat_Kind : Flat_Element_Kinds)
return Asis.Element_Kinds
is
begin
return Asis_From_Internal_Kind (Internal_Element_Kinds (Flat_Kind));
end Asis_From_Flat_Kind;
function Pragma_Kind_From_Flat
(Flat_Kind : Flat_Element_Kinds)
return Asis.Pragma_Kinds
is
begin
return Pragma_Kind_From_Internal (Internal_Element_Kinds (Flat_Kind));
end Pragma_Kind_From_Flat;
function Defining_Name_Kind_From_Flat
(Flat_Kind : Flat_Element_Kinds)
return Asis.Defining_Name_Kinds
is
begin
return Defining_Name_Kind_From_Internal
(Internal_Element_Kinds (Flat_Kind));
end Defining_Name_Kind_From_Flat;
function Declaration_Kind_From_Flat
(Flat_Kind : Flat_Element_Kinds)
return Asis.Declaration_Kinds
is
begin
return Declaration_Kind_From_Internal
(Internal_Element_Kinds (Flat_Kind));
end Declaration_Kind_From_Flat;
function Definition_Kind_From_Flat
(Flat_Kind : Flat_Element_Kinds)
return Asis.Definition_Kinds
is
begin
return Definition_Kind_From_Internal
(Internal_Element_Kinds (Flat_Kind));
end Definition_Kind_From_Flat;
function Type_Kind_From_Flat
(Flat_Kind : Flat_Element_Kinds)
return Asis.Type_Kinds
is
begin
return Type_Kind_From_Internal (Internal_Element_Kinds (Flat_Kind));
end Type_Kind_From_Flat;
function Formal_Type_Kind_From_Flat
(Flat_Kind : Flat_Element_Kinds)
return Asis.Formal_Type_Kinds
is
begin
return Formal_Type_Kind_From_Internal
(Internal_Element_Kinds (Flat_Kind));
end Formal_Type_Kind_From_Flat;
function Access_Type_Kind_From_Flat
(Flat_Kind : Flat_Element_Kinds)
return Asis.Access_Type_Kinds
is
begin
return Access_Type_Kind_From_Internal
(Internal_Element_Kinds (Flat_Kind));
end Access_Type_Kind_From_Flat;
function Root_Type_Kind_From_Flat
(Flat_Kind : Flat_Element_Kinds)
return Asis.Root_Type_Kinds
is
begin
return Root_Type_Kind_From_Internal
(Internal_Element_Kinds (Flat_Kind));
end Root_Type_Kind_From_Flat;
function Constraint_Kind_From_Flat
(Flat_Kind : Flat_Element_Kinds)
return Asis.Constraint_Kinds
is
begin
return Constraint_Kind_From_Internal
(Internal_Element_Kinds (Flat_Kind));
end Constraint_Kind_From_Flat;
function Discrete_Range_Kind_From_Flat
(Flat_Kind : Flat_Element_Kinds)
return Asis.Discrete_Range_Kinds
is
begin
return Discrete_Range_Kind_From_Internal
(Internal_Element_Kinds (Flat_Kind));
end Discrete_Range_Kind_From_Flat;
function Expression_Kind_From_Flat
(Flat_Kind : Flat_Element_Kinds)
return Asis.Expression_Kinds
is
begin
return Expression_Kind_From_Internal
(Internal_Element_Kinds (Flat_Kind));
end Expression_Kind_From_Flat;
function Operator_Kind_From_Flat
(Flat_Kind : Flat_Element_Kinds)
return Asis.Operator_Kinds
is
begin
return Operator_Kind_From_Internal
(Internal_Element_Kinds (Flat_Kind));
end Operator_Kind_From_Flat;
function Attribute_Kind_From_Flat
(Flat_Kind : Flat_Element_Kinds)
return Asis.Attribute_Kinds
is
begin
return Attribute_Kind_From_Internal
(Internal_Element_Kinds (Flat_Kind));
end Attribute_Kind_From_Flat;
function Association_Kind_From_Flat
(Flat_Kind : Flat_Element_Kinds)
return Asis.Association_Kinds
is
begin
return Association_Kind_From_Internal
(Internal_Element_Kinds (Flat_Kind));
end Association_Kind_From_Flat;
function Statement_Kind_From_Flat
(Flat_Kind : Flat_Element_Kinds)
return Asis.Statement_Kinds
is
begin
return Statement_Kind_From_Internal (Internal_Element_Kinds (Flat_Kind));
end Statement_Kind_From_Flat;
function Path_Kind_From_Flat
(Flat_Kind : Flat_Element_Kinds)
return Asis.Path_Kinds
is
begin
return Path_Kind_From_Internal (Internal_Element_Kinds (Flat_Kind));
end Path_Kind_From_Flat;
function Clause_Kind_From_Flat
(Flat_Kind : Flat_Element_Kinds)
return Asis.Clause_Kinds
is
begin
return Clause_Kind_From_Internal (Internal_Element_Kinds (Flat_Kind));
end Clause_Kind_From_Flat;
function Representation_Clause_Kind_From_Flat
(Flat_Kind : Flat_Element_Kinds)
return Asis.Representation_Clause_Kinds
is
begin
return Representation_Clause_Kind_From_Internal
(Internal_Element_Kinds (Flat_Kind));
end Representation_Clause_Kind_From_Flat;
-------------------------------------
-- Additional Classification items --
-------------------------------------
-----------------------
-- Def_Operator_Kind --
-----------------------
function Def_Operator_Kind
(Op_Kind : Flat_Element_Kinds)
return Flat_Element_Kinds
is
begin
return Flat_Element_Kinds (Def_Operator_Kind
(Internal_Element_Kinds (Op_Kind)));
end Def_Operator_Kind;
end Asis.Extensions.Flat_Kinds;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
6fc616d2b2a06cbdbb14291f233472668026d168
|
regtests/security-oauth-clients-tests.ads
|
regtests/security-oauth-clients-tests.ads
|
-----------------------------------------------------------------------
-- Security-oauth-clients-tests - Unit tests for OAuth
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package Security.OAuth.Clients.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test Create_Nonce operation.
procedure Test_Create_Nonce (T : in out Test);
end Security.OAuth.Clients.Tests;
|
Add OAuth client unit tests
|
Add OAuth client unit tests
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
|
8642486eff375a6c2b875423157f09a78a311aa9
|
src/asf-parts-upload_method.ads
|
src/asf-parts-upload_method.ads
|
-----------------------------------------------------------------------
-- asf-parts -- ASF Parts
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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 EL.Methods.Proc_In;
package ASF.Parts.Upload_Method is
new EL.Methods.Proc_In (Param1_Type => ASF.Parts.Part'Class);
|
Define a method and binding for an Ada bean to receive an uploaded file
|
Define a method and binding for an Ada bean to receive an uploaded file
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
|
4a36287be0f9f2f833340b4eaa25de09b360e9a0
|
src/sys/http/util-http-mimes.adb
|
src/sys/http/util-http-mimes.adb
|
-----------------------------------------------------------------------
-- util-http-mimes -- HTTP Headers
-- Copyright (C) 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Characters.Handling;
with Ada.Strings.Equal_Case_Insensitive;
package body Util.Http.Mimes is
use Ada.Characters.Handling;
use Ada.Strings;
function Is_Mime (Header : in String;
Mime : in String) return Boolean is
Sep : Natural;
begin
Sep := Util.Strings.Index (Header, ';');
if Sep = 0 then
Sep := Header'Last;
else
Sep := Sep - 1;
while Sep > Header'First and then Is_Space (Header (Sep)) loop
Sep := Sep - 1;
end loop;
end if;
return Equal_Case_Insensitive (Header (Header'First .. Sep), Mime);
end Is_Mime;
end Util.Http.Mimes;
|
Implement Is_Mime function
|
Implement Is_Mime function
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
|
968024476c1d18dcb04b3a0d402ee0c89ef6cc9c
|
src/imago-ilu.ads
|
src/imago-ilu.ads
|
pragma License (Modified_GPL);
------------------------------------------------------------------------------
-- EMAIL: <[email protected]> --
-- License: Modified GNU GPLv3 or any later as published by Free Software --
-- Foundation (GMGPL). --
-- --
-- Copyright © 2014 darkestkhan --
------------------------------------------------------------------------------
-- This Program is Free Software: You can redistribute it and/or modify --
-- it under the terms of The GNU General Public License as published by --
-- the Free Software Foundation: either version 3 of the license, or --
-- (at your option) any later version. --
-- --
-- This Program is distributed in the hope that it will be useful, --
-- but WITHOUT ANY WARRANTY; without even the implied warranty of --
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the --
-- GNU General Public License for more details. --
-- --
-- You should have received a copy of the GNU General Public License --
-- along with this program. If not, see <http://www.gnu.org/licenses/>. --
-- --
-- As a special exception, if other files instantiate generics from this --
-- unit, or you link this unit with other files to produce an executable, --
-- this unit does not by itself cause the resulting executable to be --
-- covered by the GNU General Public License. This exception does not --
-- however invalidate any other reasons why the executable file might be --
-- covered by the GNU Public License. --
------------------------------------------------------------------------------
with Imago.IL;
use Imago;
package Imago.ILU is
--------------------------------------------------------------------------
---------------
-- T Y P E S --
---------------
--------------------------------------------------------------------------
-- TODO: Bind types (ILinfo, ILpointf, ILpointi).
--------------------------------------------------------------------------
-----------------------
-- C O N S T A N T S --
-----------------------
--------------------------------------------------------------------------
ILU_VERSION_1_7_8 : constant IL.Enum := 1;
ILU_VERSION : constant IL.Enum := 178;
ILU_FILTER : constant IL.Enum := 16#2600#;
ILU_NEAREST : constant IL.Enum := 16#2601#;
ILU_LINEAR : constant IL.Enum := 16#2602#;
ILU_BILINEAR : constant IL.Enum := 16#2603#;
ILU_SCALE_BOX : constant IL.Enum := 16#2604#;
ILU_SCALE_TRIANGLE : constant IL.Enum := 16#2605#;
ILU_SCALE_BELL : constant IL.Enum := 16#2606#;
ILU_SCALE_BSPLINE : constant IL.Enum := 16#2607#;
ILU_SCALE_LANCZOS3 : constant IL.Enum := 16#2608#;
ILU_SCALE_MITCHELL : constant IL.Enum := 16#2609#;
-- Error types.
ILU_INVALID_ENUM : constant IL.Enum := 16#0501#;
ILU_OUT_OF_MEMORY : constant IL.Enum := 16#0502#;
ILU_INTERNAL_ERROR : constant IL.Enum := 16#0504#;
ILU_INVALID_VALUE : constant IL.Enum := 16#0505#;
ILU_ILLEGAL_OPERATION : constant IL.Enum := 16#0506#;
ILU_INVALID_PARAM : constant IL.Enum := 16#0509#;
-- Values.
ILU_PLACEMENT : constant IL.Enum := 16#0700#;
ILU_LOWER_LEFT : constant IL.Enum := 16#0701#;
ILU_LOWER_RIGHT : constant IL.Enum := 16#0702#;
ILU_UPPER_LEFT : constant IL.Enum := 16#0703#;
ILU_UPPER_RIGHT : constant IL.Enum := 16#0704#;
ILU_CENTER : constant IL.Enum := 16#0705#;
ILU_CONVOLUTION_MATRIX : constant IL.Enum := 16#0710#;
ILU_VERSION_NUM : constant IL.Enum := IL.IL_VERSION_NUM;
ILU_VENDOR : constant IL.Enum := IL.IL_VENDOR;
-- Languages.
ILU_ENGLISH : constant IL.Enum := 16#0800#;
ILU_ARABIC : constant IL.Enum := 16#0801#;
ILU_DUTCH : constant IL.Enum := 16#0802#;
ILU_JAPANESE : constant IL.Enum := 16#0803#;
ILU_SPANISH : constant IL.Enum := 16#0804#;
ILU_GERMAN : constant IL.Enum := 16#0805#;
ILU_FRENCH : constant IL.Enum := 16#0806#;
--------------------------------------------------------------------------
---------------------------
-- S U B P R O G R A M S --
---------------------------
--------------------------------------------------------------------------
function Alienify return IL.Bool;
function Blur_Avg (Iter: in IL.UInt) return IL.Bool;
function Blur_Gaussian (Iter: in IL.UInt) return IL.Bool;
function Build_Mipmaps return IL.Bool;
function Colors_Used return IL.UInt;
function Colours_Used return IL.UInt;
function Compare_Image (Comp: in IL.UInt) return IL.Bool;
function Contrast (Contrats: in Float) return IL.Bool;
function Crop
( XOff: in IL.UInt; YOff: in IL.UInt; ZOff: in IL.UInt;
Width: in IL.UInt; Height: in IL.UInt; Depth: in IL.UInt
) return IL.Bool;
procedure Delete_Image (ID: in IL.UInt);
function Edge_Detect_E return IL.Bool;
function Edge_Detect_P return IL.Bool;
function Edge_Detect_S return IL.Bool;
function Emboss return IL.Bool;
function Enlarge_Canvas
( Width: in IL.UInt; Height: in IL.UInt; Depth: in IL.UInt
) return IL.Bool;
function Enlarge_Image
( XDim: in Float; YDim: in Float; ZDim: in Float
) return IL.Bool;
function Equalize return IL.Bool;
function Convolution
( Matrix: in IL.Pointer; Scale: in IL.Int; Bias: in IL.Int
) return IL.Bool;
function Flip_Image return IL.Bool;
function Gamma_Correct (Gamma: in Float) return IL.Bool;
function Gen_Image return IL.UInt;
procedure Image_Parameter (P_Name: in IL.Enum; Param: in IL.Enum);
procedure Init;
function Invert_Alpha return IL.Bool;
function Mirror return IL.Bool;
function Negative return IL.Bool;
function Noisify (Tolerance: in IL.ClampF) return IL.Bool;
function Pixelize (Pix_Size: in IL.UInt) return IL.Bool;
function Replace_Color
( Red: in IL.UByte; Green: in IL.UByte;
Blue: in IL.UByte; Tolerance: in Float
) return IL.Bool;
function Replace_Colour
( Red: in IL.UByte; Green: in IL.UByte;
Blue: in IL.UByte; Tolerance: in Float
) return IL.Bool;
function Scale
( Width: in IL.UInt; Height: in IL.UInt; Depth: in IL.UInt
) return IL.Bool;
function Scale_Alpha (Scale: in Float) return IL.Bool;
function Scale_Colors (R: in Float; G: in Float; B: in Float) return IL.Bool;
function Scale_Colours (R: in Float; G: in Float; B: in Float) return IL.Bool;
function Set_Language (Language: in IL.Enum) return IL.Bool;
function Sharpen (Factor: in Float; Iter: in IL.UInt) return IL.Bool;
function Swap_Colors return IL.Bool;
function Swap_Colours return IL.Bool;
function Wave (Angle: in Float) return IL.Bool;
-- ILconst_string iluErrorString(ILenum Error);
-- void iluGetImageInfo(ILinfo *Info);
-- ILint iluGetInteger(ILenum Mode);
-- void iluGetIntegerv(ILenum Mode, ILint *Param);
-- ILstring iluGetString(ILenum StringName);
-- ILuint iluLoadImage(ILconst_string FileName);
-- void iluRegionfv(ILpointf *Points, ILuint n);
-- void iluRegioniv(ILpointi *Points, ILuint n);
-- ILboolean iluRotate(ILfloat Angle);
-- ILboolean iluRotate3D(ILfloat x, ILfloat y, ILfloat z, ILfloat Angle);
-- ILboolean iluSaturate1f(ILfloat Saturation);
-- ILboolean iluSaturate4f(ILfloat r, ILfloat g, ILfloat b, ILfloat Saturation);
--------------------------------------------------------------------------
private
--------------------------------------------------------------------------
-------------------
-- I M P O R T S --
-------------------
--------------------------------------------------------------------------
Pragma Import (StdCall, Alienify, "iluAlienify");
Pragma Import (StdCall, Blur_Avg, "iluBlurAvg");
Pragma Import (StdCall, Blur_Gaussian, "iluBlurGaussian");
Pragma Import (StdCall, Build_Mipmaps, "iluBuildMipmaps");
Pragma Import (StdCall, Colors_Used, "iluColoursUsed");
Pragma Import (StdCall, Colours_Used, "iluColoursUsed");
Pragma Import (StdCall, Compare_Image, "iluCompareImage");
Pragma Import (StdCall, Contrast, "iluContrast");
Pragma Import (StdCall, Crop, "iluCrop");
Pragma Import (StdCall, Delete_Image, "iluDeleteImage");
Pragma Import (StdCall, Edge_Detect_E, "iluEdgeDetectE");
Pragma Import (StdCall, Edge_Detect_P, "iluEdgeDetectP");
Pragma Import (StdCall, Edge_Detect_S, "iluEdgeDetectS");
Pragma Import (StdCall, Emboss, "iluEmboss");
Pragma Import (StdCall, Enlarge_Canvas, "iluEnlargeCanvas");
Pragma Import (StdCall, Enlarge_Image, "iluEnlargeImage");
Pragma Import (StdCall, Equalize, "iluEqualize");
Pragma Import (StdCall, Convolution, "iluConvolution");
Pragma Import (StdCall, Flip_Image, "iluFlipImage");
Pragma Import (StdCall, Gamma_Correct, "iluGammaCorrect");
Pragma Import (StdCall, Gen_Image, "iluGenImage");
Pragma Import (StdCall, Image_Parameter, "iluImageParameter");
Pragma Import (StdCall, Init, "iluInit");
Pragma Import (StdCall, Invert_Alpha, "iluInvertAlpha");
Pragma Import (StdCall, Mirror, "iluMirror");
Pragma Import (StdCall, Negative, "iluNegative");
Pragma Import (StdCall, Noisify, "iluNoisify");
Pragma Import (StdCall, Pixelize, "iluPixelize");
Pragma Import (StdCall, Replace_Color, "iluReplaceColour");
Pragma Import (StdCall, Replace_Colour, "iluReplaceColour");
Pragma Import (StdCall, Scale, "iluScale");
Pragma Import (StdCall, Scale_Alpha, "iluScaleAlpha");
Pragma Import (StdCall, Scale_Colors, "iluScaleColours");
Pragma Import (StdCall, Scale_Colours, "iluScaleColours");
Pragma Import (StdCall, Set_Language, "iluSetLanguage");
Pragma Import (StdCall, Sharpen, "iluSharpen");
Pragma Import (StdCall, Swap_Colors, "iluSwapColours");
Pragma Import (StdCall, Swap_Colours, "iluSwapColours");
Pragma Import (StdCall, Wave, "iluWave");
--------------------------------------------------------------------------
end Imago.ILU;
|
Add initial bindings to ilu.h.
|
Add initial bindings to ilu.h.
Signed-off-by: darkestkhan <[email protected]>
|
Ada
|
isc
|
darkestkhan/imago
|
|
8f864690e394030569b41a34cd171f7654a6bbdc
|
awa/awaunit/awa-tests-helpers.adb
|
awa/awaunit/awa-tests-helpers.adb
|
-----------------------------------------------------------------------
-- awa-tests-helpers - Helpers for AWA unit tests
-- Copyright (C) 2011, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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.
-----------------------------------------------------------------------
package body AWA.Tests.Helpers is
-- ------------------------------
-- Extract from the Location header the part that is after the given base string.
-- If the Location header does not start with the base string, returns the empty
-- string.
-- ------------------------------
function Extract_Redirect (Reply : in ASF.Responses.Mockup.Response'Class;
Base : in String) return String is
R : constant String := Reply.Get_Header ("Location");
begin
if R'Length < Base'Length then
return "";
elsif R (R'First .. R'First + Base'Length - 1) /= Base then
return "";
else
return R (R'First + Base'Length .. R'Last);
end if;
end Extract_Redirect;
function Extract_Redirect (Reply : in ASF.Responses.Mockup.Response'Class;
Base : in String) return Ada.Strings.Unbounded.Unbounded_String is
begin
return Ada.Strings.Unbounded.To_Unbounded_String (Extract_Redirect (Reply, Base));
end Extract_Redirect;
end AWA.Tests.Helpers;
|
Implement the Extract_Redirect function
|
Implement the Extract_Redirect function
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
|
0695f2fa5f7d251eccbe17548afda71a24cb9114
|
awa/plugins/awa-votes/regtests/awa-votes-modules-tests.adb
|
awa/plugins/awa-votes/regtests/awa-votes-modules-tests.adb
|
-----------------------------------------------------------------------
-- awa-questions-services-tests -- Unit tests for storage service
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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 Ada.Strings.Unbounded;
with Util.Test_Caller;
with Util.Beans.Basic;
with Util.Beans.Objects;
with ADO;
with ADO.Objects;
with Security.Contexts;
with AWA.Users.Models;
with AWA.Services.Contexts;
with AWA.Votes.Modules;
with AWA.Tests.Helpers.Users;
package body AWA.Votes.Modules.Tests is
use Util.Tests;
use ADO;
package Caller is new Util.Test_Caller (Test, "Votes.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Votes.Services.Vote_Up",
Test_Vote_Up'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a question.
-- ------------------------------
procedure Test_Vote_Up (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
declare
Vote_Manager : Vote_Module_Access := Get_Vote_Module;
User : AWA.Users.Models.User_Ref := Context.Get_User;
begin
T.Assert (Vote_Manager /= null, "There is no vote module");
Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 1);
Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 2);
end;
end Test_Vote_Up;
end AWA.Votes.Modules.Tests;
|
Update the unit tests
|
Update the unit tests
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
|
f14964f32c204a32981e2f0fed86a0e2bba1fd70
|
src/util-beans-objects-pairs.adb
|
src/util-beans-objects-pairs.adb
|
-----------------------------------------------------------------------
-- Util.Beans.Objects.Pairs -- Pairs of objects
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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.
-----------------------------------------------------------------------
package body Util.Beans.Objects.Pairs is
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Pair;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "key" or Name = "first" then
return From.First;
elsif Name = "value" or Name = "second" then
return From.Second;
else
return Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out Pair;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "key" or Name = "first" then
From.First := Value;
elsif Name = "value" or Name = "second" then
From.Second := Value;
end if;
end Set_Value;
-- ------------------------------
-- Return an object represented by the pair of two values.
-- ------------------------------
function To_Object (First, Second : in Object) return Object is
Result : constant Pair_Access := new Pair;
begin
Result.First := First;
Result.Second := Second;
return To_Object (Result.all'Access);
end To_Object;
end Util.Beans.Objects.Pairs;
|
Implement pair of objects
|
Implement pair of objects
|
Ada
|
apache-2.0
|
flottokarotto/ada-util,flottokarotto/ada-util,Letractively/ada-util,Letractively/ada-util
|
|
2afc1c020a4d1beaacd4cf380fb6d0574509d80b
|
src/asf-components-utils.adb
|
src/asf-components-utils.adb
|
-----------------------------------------------------------------------
-- components-util -- ASF Util Components
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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.Views.Nodes;
package body ASF.Components.Utils is
-- ------------------------------
-- Get the line information where the component is defined.
-- ------------------------------
function Get_Line_Info (UI : in UIComponent'Class) return Views.Nodes.Line_Info is
begin
if UI.Tag /= null then
return UI.Tag.Get_Line_Info;
else
return UI.Tag.Get_Line_Info;
end if;
end Get_Line_Info;
-- ------------------------------
-- Get the line information where the component is defined.
-- ------------------------------
function Get_Line_Info (UI : in UIComponent'Class) return String is
begin
if UI.Tag /= null then
return UI.Tag.Get_Line_Info;
else
return UI.Tag.Get_Line_Info;
end if;
end Get_Line_Info;
end ASF.Components.Utils;
|
Implement the Get_Line_Info function
|
Implement the Get_Line_Info function
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
|
113511221a3435f3123652236330057a5937eb02
|
src/asis/a4g-contt-tt.adb
|
src/asis/a4g-contt-tt.adb
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . C O N T T . T T --
-- --
-- B o d y --
-- --
-- Copyright (C) 1995-2012, Free Software Foundation, Inc. --
-- --
-- ASIS-for-GNAT is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 2, or (at your option) any later --
-- version. ASIS-for-GNAT is distributed in the hope that it will be use- --
-- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- --
-- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General --
-- Public License for more details. You should have received a copy of the --
-- GNU General Public License distributed with ASIS-for-GNAT; see file --
-- COPYING. If not, write to the Free Software Foundation, 51 Franklin --
-- Street, Fifth Floor, Boston, MA 02110-1301, USA. --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the --
-- Software Engineering Laboratory of the Swiss Federal Institute of --
-- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the --
-- Scientific Research Computer Center of Moscow State University (SRCC --
-- MSU), Russia, with funding partially provided by grants from the Swiss --
-- National Science Foundation and the Swiss Academy of Engineering --
-- Sciences. ASIS-for-GNAT is now maintained by AdaCore --
-- (http://www.adacore.com). --
-- --
------------------------------------------------------------------------------
-- This package defines Tree Table, which contains the information
-- about the tree output files needed for swapping the ASTs accessed
-- by ASIS. This information includes such things as Asis Compilation
-- Units, and their top nodes in the tree.
with Asis; use Asis;
with Asis.Compilation_Units;
with Asis.Errors; use Asis.Errors;
with Asis.Set_Get; use Asis.Set_Get;
with A4G.A_Debug; use A4G.A_Debug;
with A4G.A_Output; use A4G.A_Output;
with A4G.Asis_Tables; use A4G.Asis_Tables;
with A4G.Contt.UT; use A4G.Contt.UT;
with A4G.Get_Unit; use A4G.Get_Unit;
with A4G.Vcheck; use A4G.Vcheck;
with Atree; use Atree;
with Lib; use Lib;
with Namet; use Namet;
with Nlists; use Nlists;
with Output; use Output;
with Sinfo; use Sinfo;
with Sinput; use Sinput;
with Tree_In;
package body A4G.Contt.TT is
procedure Set_Nil_Tree_Names (T : Tree_Id);
-- Sets all the fields related to Source File Name Table as indicating
-- empty strings
procedure Set_Nil_Tree_Attributes (T : Tree_Id);
-- Sets all the attributes of T as if T is an ASIS Nil_Tree
function Find_Enclosed_Decl
(Scope : Node_Id;
J : Int)
return Node_Id;
-- Starting from Scope, looks for the nested scope which is stored
-- in Node_Trace table as Node_Trase.Table (J). Node, that expanded
-- generic specs are considered as ordinary scopes.
-------------------------
-- Allocate_Tree_Entry --
-------------------------
function Allocate_Tree_Entry return Tree_Id is
New_Last : Tree_Id;
-- the Id of the new entry being allocated in the Unit Table
begin
Tree_Table.Increment_Last;
New_Last := Tree_Table.Last;
Set_Nil_Tree_Names (New_Last);
Set_Nil_Tree_Attributes (New_Last);
Tree_Table.Table (New_Last).Tree_Name_Chars_Index := A_Name_Chars.Last;
Tree_Table.Table (New_Last).Tree_Name_Len := Short (A_Name_Len);
-- Set corresponding string entry in the Name_Chars table
for I in 1 .. A_Name_Len loop
A_Name_Chars.Increment_Last;
A_Name_Chars.Table (A_Name_Chars.Last) := A_Name_Buffer (I);
end loop;
A_Name_Chars.Increment_Last;
A_Name_Chars.Table (A_Name_Chars.Last) := ASCII.NUL;
return New_Last;
end Allocate_Tree_Entry;
------------------------------------------
-- Current_Tree_Consistent_With_Sources --
------------------------------------------
function Current_Tree_Consistent_With_Sources return Boolean is
Result : Boolean := True;
Source_Stamp : Time_Stamp_Type;
Tree_Stamp : Time_Stamp_Type;
Source : File_Name_Type;
begin
for J in 2 .. Last_Source_File loop
-- We start from 2, because the entry 1 in the Source File Table
-- is always for system.ads (see Sinput, spec).
Tree_Stamp := Time_Stamp (J);
Source := Full_File_Name (J);
Get_Name_String (Source);
Name_Len := Name_Len + 1;
Name_Buffer (Name_Len) := ASCII.NUL;
if not Is_Regular_File (Name_Buffer) then
-- The source file was (re)moved
Result := False;
exit;
else
Source_Stamp := TS_From_OS_Time (File_Time_Stamp (Name_Buffer));
if Source_Stamp /= Tree_Stamp then
-- The source file has been changed
Result := False;
exit;
end if;
end if;
end loop;
return Result;
end Current_Tree_Consistent_With_Sources;
------------------------
-- Find_Enclosed_Decl --
------------------------
function Find_Enclosed_Decl
(Scope : Node_Id;
J : Int)
return Node_Id
is
Result : Node_Id := Empty;
List_To_Search : List_Id;
Kind_To_Search : constant Node_Kind := Node_Trace.Table (J).Kind;
Line_To_Search : constant Physical_Line_Number :=
Node_Trace.Table (J).Node_Line;
Col_To_Search : constant Column_Number :=
Node_Trace.Table (J).Node_Col;
function Check_Node (N : Node_Id) return Traverse_Result;
-- Check if N is the needed node. If it is, Sets Result equial to N and
-- returns Abandon. Othervise returns OK.
function Find_In_List (L : List_Id) return Node_Id;
-- Looks for the needed scope in a node list
procedure Traverse_Scope is new
Atree.Traverse_Proc (Process => Check_Node);
function Check_Node (N : Node_Id) return Traverse_Result is
N_Sloc : Source_Ptr;
Traverse_Res : Traverse_Result := OK;
begin
if Nkind (N) = Kind_To_Search then
N_Sloc := Sloc (N);
if Get_Physical_Line_Number (N_Sloc) = Line_To_Search
and then
Get_Column_Number (N_Sloc) = Col_To_Search
then
Result := N;
Traverse_Res := Abandon;
end if;
end if;
return Traverse_Res;
end Check_Node;
function Find_In_List (L : List_Id) return Node_Id is
Res : Node_Id := Empty;
Next_Node : Node_Id;
Next_Sloc : Source_Ptr;
begin
Next_Node := First_Non_Pragma (L);
while Present (Next_Node) loop
if Nkind (Next_Node) = Kind_To_Search then
Next_Sloc := Sloc (Next_Node);
if Get_Physical_Line_Number (Next_Sloc) = Line_To_Search
and then
Get_Column_Number (Next_Sloc) = Col_To_Search
then
Res := Next_Node;
exit;
end if;
end if;
Next_Node := Next_Non_Pragma (Next_Node);
end loop;
return Res;
end Find_In_List;
begin
if Nkind (Scope) = N_Package_Instantiation then
Result := Scope;
while Nkind (Result) /= N_Package_Declaration loop
Result := Prev_Non_Pragma (Result);
end loop;
return Result;
end if;
if Nkind (Scope) = N_Package_Body
or else
Nkind (Scope) = N_Subprogram_Body
or else
Nkind (Scope) = N_Block_Statement
then
List_To_Search := Sinfo.Declarations (Scope);
else
List_To_Search := Visible_Declarations (Scope);
end if;
Result := Find_In_List (List_To_Search);
if No (Result) then
if Nkind (Scope) = N_Package_Specification then
List_To_Search := Private_Declarations (Scope);
Result := Find_In_List (List_To_Search);
if No (Result)
and then
Nkind (Parent (Scope)) = N_Generic_Package_Declaration
then
List_To_Search := Generic_Formal_Declarations (Parent (Scope));
Result := Find_In_List (List_To_Search);
end if;
elsif Nkind (Scope) = N_Block_Statement
or else
Nkind (Scope) = N_Subprogram_Body
then
-- We can have an instantiation nested in some block statement in
-- tne library subprogram body. This should not happen too often,
-- so we can use this performance-expensive approach here.
Traverse_Scope (Scope);
end if;
end if;
pragma Assert (Present (Result));
return Result;
end Find_Enclosed_Decl;
-------------------
-- Get_Tree_Name --
-------------------
function Get_Tree_Name (C : Context_Id; Id : Tree_Id) return String is
begin
Get_Name_String (C, Id);
return A_Name_Buffer (1 .. A_Name_Len);
end Get_Tree_Name;
-----------------------------
-- Restore_Node_From_Trace --
-----------------------------
function Restore_Node_From_Trace
(In_Body : Boolean := False;
CU : Asis.Compilation_Unit := Asis.Nil_Compilation_Unit)
return Node_Id
is
Start_Node : Node_Id;
Result : Node_Id := Empty;
begin
if Asis.Compilation_Units.Is_Nil (CU) then
Start_Node := Unit (Cunit (Main_Unit));
if Nkind (Start_Node) = N_Package_Body and then
not In_Body
then
Start_Node := Corresponding_Spec (Start_Node);
while not (Nkind (Start_Node) = N_Package_Declaration
or else
Nkind (Start_Node) = N_Generic_Package_Declaration)
loop
Start_Node := Parent (Start_Node);
end loop;
end if;
else
Start_Node := Unit (Top (CU));
end if;
if Node_Trace.First = Node_Trace.Last then
-- One-element trace means, that we have a library-level package
-- instantiation
Result := Start_Node;
else
if Nkind (Start_Node) = N_Package_Declaration
or else
Nkind (Start_Node) = N_Generic_Package_Declaration
then
Start_Node := Specification (Start_Node);
end if;
for J in reverse Node_Trace.First + 1 .. Node_Trace.Last - 1 loop
Start_Node := Find_Enclosed_Decl (Start_Node, J);
if Nkind (Start_Node) = N_Package_Declaration
or else
Nkind (Start_Node) = N_Generic_Package_Declaration
then
Start_Node := Specification (Start_Node);
end if;
end loop;
Result := Find_Enclosed_Decl (Start_Node, Node_Trace.First);
end if;
pragma Assert (Present (Result));
return Result;
end Restore_Node_From_Trace;
---------------------
-- Get_Name_String --
---------------------
procedure Get_Name_String (C : Context_Id; Id : Tree_Id) is
S : Int;
L : Short;
begin
Reset_Context (C); -- ???
S := Tree_Table.Table (Id).Tree_Name_Chars_Index;
L := Tree_Table.Table (Id).Tree_Name_Len;
A_Name_Len := Natural (L);
for I in 1 .. A_Name_Len loop
A_Name_Buffer (I) := A_Name_Chars.Table (S + Int (I));
end loop;
end Get_Name_String;
-----------------
-- Print_Trees --
-----------------
procedure Print_Trees (C : Context_Id) is
begin
Write_Str ("Tree Table for Context number: ");
Write_Int (Int (C));
Write_Eol;
if C = Non_Associated then
Write_Str (" Nil Context, it can never be associated ");
Write_Str ("with any tree");
Write_Eol;
return;
end if;
if Is_Opened (C) then
for Tr in First_Tree_Id .. Last_Tree (C) loop
Output_Tree (C, Tr);
end loop;
Write_Eol;
else
Write_Str ("This Context is closed");
Write_Eol;
end if;
end Print_Trees;
-----------------------------
-- Set_Nil_Tree_Attributes --
-----------------------------
procedure Set_Nil_Tree_Attributes (T : Tree_Id) is
begin
Set_Main_Unit_Id (T, Nil_Unit);
Set_Main_Top (T, Empty);
Tree_Table.Table (T).Units := No_Elist;
end Set_Nil_Tree_Attributes;
------------------------
-- Set_Nil_Tree_Names --
------------------------
procedure Set_Nil_Tree_Names (T : Tree_Id) is
Tr : constant Tree_Id := T;
begin
Tree_Table.Table (Tr).Tree_Name_Chars_Index := 0;
Tree_Table.Table (Tr).Tree_Name_Len := 0;
end Set_Nil_Tree_Names;
---------------------------------------------------------------
-- Internal Tree Unit Attributes Access and Update Routines --
---------------------------------------------------------------
function Main_Unit_Id (T : Tree_Id) return Unit_Id is
begin
return Tree_Table.Table (T).Main_Unit;
end Main_Unit_Id;
function Main_Unit_Id return Unit_Id is
begin
return Tree_Table.Table (Current_Tree).Main_Unit;
end Main_Unit_Id;
procedure Set_Main_Unit_Id (T : Tree_Id; U : Unit_Id) is
begin
Tree_Table.Table (T).Main_Unit := U;
end Set_Main_Unit_Id;
procedure Set_Main_Top (T : Tree_Id; N : Node_Id) is
begin
Tree_Table.Table (T).Main_Top := N;
end Set_Main_Top;
procedure Set_Main_Unit_Id (U : Unit_Id) is
begin
Tree_Table.Table (Current_Tree).Main_Unit := U;
end Set_Main_Unit_Id;
procedure Set_Main_Top (N : Node_Id) is
begin
Tree_Table.Table (Current_Tree).Main_Top := N;
end Set_Main_Top;
-----------------------------------
-- Subprograms for Tree Swapping --
-----------------------------------
-----------------------------------
-- Append_Full_View_Tree_To_Unit --
-----------------------------------
procedure Append_Full_View_Tree_To_Unit (C : Context_Id; U : Unit_Id) is
begin
Reset_Context (C);
Add_To_Elmt_List (Unit_Id (Current_Tree),
Unit_Table.Table (U).Full_View_Trees);
end Append_Full_View_Tree_To_Unit;
--------------------------------------
-- Append_Limited_View_Tree_To_Unit --
--------------------------------------
procedure Append_Limited_View_Tree_To_Unit (C : Context_Id; U : Unit_Id) is
begin
Reset_Context (C);
Add_To_Elmt_List (Unit_Id (Current_Tree),
Unit_Table.Table (U).Limited_View_Trees);
end Append_Limited_View_Tree_To_Unit;
-------------------
-- Reorder_Trees --
-------------------
procedure Reorder_Trees (C : Context_Id) is
Main_Unit : Unit_Id;
-- The unit which main tree should be moved to the first position in
-- the list of trees for the unit being processed in a loop
First_Tree : Tree_Id;
Success : Boolean;
C_Mode : constant Context_Mode := Context_Processing_Mode (C);
begin
for U in First_Unit_Id + 1 .. Last_Unit loop
-- First_Unit_Id corresponds to Standard
Success := True;
Main_Unit := Nil_Unit;
case Kind (C, U) is
when A_Subunit =>
-- (1)
Main_Unit := Get_Subunit_Parent_Body (C, U);
while Kind (C, Main_Unit) in A_Subunit loop
Main_Unit := Get_Subunit_Parent_Body (C, Main_Unit);
end loop;
if No (Main_Tree (C, Main_Unit)) then
if C_Mode in Partition .. All_Trees then
Get_Name_String (U, Ada_Name);
ASIS_Warning
(Message =>
"Asis.Ada_Environments.Open: " &
"ancestor body is not compiled for subunit " &
A_Name_Buffer (1 .. A_Name_Len),
Error => Data_Error);
end if;
Success := False;
end if;
when A_Package |
A_Generic_Package |
A_Procedure |
A_Function |
A_Generic_Procedure |
A_Generic_Function =>
-- (2), (3) and (5)
if Is_Body_Required (C, U) or else
Kind (C, U) = A_Procedure or else
Kind (C, U) = A_Function or else
Kind (C, U) = A_Generic_Procedure or else
Kind (C, U) = A_Generic_Function
then
-- (2) and (5)
Main_Unit := Get_Body (C, U);
if No (Main_Unit) or else
No (Main_Tree (C, Main_Unit))
then
-- The second condition corresponds to the situation when
-- the tree is created for library-level generic spec
-- which requires the body
if C_Mode in Partition .. All_Trees and then
Origin (C, U) = An_Application_Unit
then
Get_Name_String (U, Ada_Name);
ASIS_Warning
(Message =>
"Asis.Ada_Environments.Open: "
& "body is not compiled for "
& A_Name_Buffer (1 .. A_Name_Len),
Error => Data_Error);
end if;
Success := False;
end if;
else
-- (3)
Main_Unit := U;
if No (Main_Tree (C, Main_Unit)) then
-- We do not generate any warning in this case, because
-- we do not know whether or not this package
-- declaration has to be compiled on its own. So we only
-- set Success OFF to prevent any change in the tree
-- list
Success := False;
end if;
end if;
when A_Generic_Unit_Instance =>
-- (4)
Main_Unit := U;
if No (Main_Tree (C, Main_Unit)) then
if C_Mode in Partition .. All_Trees and then
Origin (C, U) = An_Application_Unit
then
Get_Name_String (U, Ada_Name);
ASIS_Warning
(Message =>
"Asis.Ada_Environments.Open: "
& "library-level instance "
& A_Name_Buffer (1 .. A_Name_Len)
& " is not compiled",
Error => Data_Error);
end if;
Success := False;
end if;
when A_Library_Unit_Body =>
-- There are some situations when the body is compiled because
-- the corresponding spec is a supporter of the main unit of
-- the compilation. See Lib (spec), (h)
Main_Unit := U;
if No (Main_Tree (C, Main_Unit)) then
-- We do notr generate a warning here - if needed, the
-- warning is generated for the corresponding spec
Success := False;
end if;
when others =>
null;
end case;
if Success and then Present (Main_Unit) then
-- Here we have to reorder the trees for U. Currently the
-- simplest solution is used - we just prepend the right tree
-- to the tree list, if it is not already the first tree in
-- the list. So this tree may be duplicated in the list.
First_Tree := Main_Tree (C, Main_Unit);
if First_Tree /=
Tree_Id
(Unit (First_Elmt (Unit_Table.Table (U).Full_View_Trees)))
then
Prepend_Elmt
(Unit_Id (First_Tree), Unit_Table.Table (U).Full_View_Trees);
end if;
end if;
end loop;
end Reorder_Trees;
----------------
-- Reset_Tree --
----------------
procedure Reset_Tree (Context : Context_Id; Tree : Tree_Id) is
Tree_File_FD : File_Descriptor;
File_Closed : Boolean := False;
begin
-- Special processing for GNSA mode:
if Tree_Processing_Mode (Current_Context) = GNSA then
-- This is no more than a workaround for -GNSA C1 Context when we
-- have exactly one tree (and exactly one (GNSA) Context!
return;
end if;
if Context = Current_Context and then
Tree = Current_Tree
then
return;
end if;
if Debug_Flag_T then
Write_Str ("In Context ");
Write_Int (Int (Context));
Write_Str (" resetting the tree ");
Write_Int (Int (Tree));
Write_Eol;
end if;
-- the following call to Reset_Context is redundant, because the next
-- call to Get_Name_String also resets Context, but this is the right
-- place for Reset_Context
Reset_Context (Context);
Get_Name_String (Context, Tree);
-- should be always successful, because Tree may correspond only to
-- some tree file, which has been investigated by ASIS
A_Name_Buffer (A_Name_Len + 1) := ASCII.NUL;
if Debug_Flag_T then
Write_Str (" (");
Write_Str (A_Name_Buffer (1 .. A_Name_Len));
Write_Str (")");
Write_Eol;
end if;
Tree_File_FD := Open_Read (A_Name_Buffer'Address, Binary);
if Tree_File_FD = Invalid_FD then
Raise_ASIS_Failed
(Diagnosis => "A4G.Contt.TT.Reset_Tree: " &
"Cannot open tree file: " &
A_Name_Buffer (1 .. A_Name_Len) &
ASIS_Line_Terminator &
"ASIS external environment may have been changed",
Stat => Data_Error);
end if;
begin
Tree_In (Tree_File_FD);
exception
when others =>
Close (Tree_File_FD, File_Closed);
-- We did not chech File_Closed here, because the problem in
-- Tree_In seems to be more important for ASIS
Raise_ASIS_Failed
(Diagnosis => "A4G.Contt.TT.Reset_Tree: " &
"Can not read tree file: " &
A_Name_Buffer (1 .. A_Name_Len) &
ASIS_Line_Terminator &
"ASIS external environment may have been changed",
Stat => Data_Error);
end;
Close (Tree_File_FD, File_Closed);
if not File_Closed then
Raise_ASIS_Failed
(Diagnosis => "A4G.Contt.TT.Reset_Tree: " &
"Can not close tree file: " &
A_Name_Buffer (1 .. A_Name_Len) &
ASIS_Line_Terminator &
"disk is full or file may be used by other program",
Stat => Data_Error);
end if;
-- if we are here, then the required tree has been successfully
-- re-retrieved. So:
Current_Context := Context;
Current_Tree := Tree;
if Debug_Flag_T then
Write_Str ("In Context ");
Write_Int (Int (Context));
Write_Str (" the tree ");
Write_Int (Int (Tree));
Write_Str (" has been reset");
Write_Eol;
end if;
end Reset_Tree;
-----------------------------
-- Reset_Tree_For_Element --
-----------------------------
procedure Reset_Tree_For_Element (E : Asis.Element) is
begin
Reset_Tree (Encl_Cont_Id (E), Encl_Tree (E));
end Reset_Tree_For_Element;
-------------------------
-- Reset_Tree_For_Unit --
-------------------------
procedure Reset_Tree_For_Unit (C : Context_Id; U : Unit_Id) is
Tree_List : Elist_Id;
Tree_To_Set : Tree_Id;
begin
-- Special processing for GNSA mode:
if Tree_Processing_Mode (Get_Current_Cont) = GNSA then
-- This is no more than a workaround for -GNSA C1 Context when we
-- have exactly one tree (and exactly one (GNSA) Context!
return;
end if;
Tree_List := Unit_Table.Table (U).Full_View_Trees;
if No (Tree_List) or else No (First_Elmt (Tree_List)) then
Tree_List := Unit_Table.Table (U).Limited_View_Trees;
end if;
-- it cannot be No_List or Empty_List!
Tree_To_Set := Tree_Id (Unit (First_Elmt (Tree_List)));
if Debug_Flag_T then
Write_Str ("For unit ");
Write_Int (Int (U));
Write_Str (" ");
end if;
Reset_Tree (Context => C,
Tree => Tree_To_Set);
end Reset_Tree_For_Unit;
procedure Reset_Tree_For_Unit (Unit : Asis.Compilation_Unit) is
begin
Reset_Tree_For_Unit (Encl_Cont_Id (Unit), Get_Unit_Id (Unit));
end Reset_Tree_For_Unit;
-------------------------
-- Reset_Instance_Tree --
-------------------------
procedure Reset_Instance_Tree
(Lib_Level_Instance : Asis.Compilation_Unit;
Decl_Node : in out Node_Id)
is
U : Unit_Id := Get_Unit_Id (Lib_Level_Instance);
Tree_To_Set : Tree_Id;
Curr_Context : constant Context_Id := Get_Current_Cont;
Curr_Tree : constant Tree_Id := Get_Current_Tree;
In_Body : Boolean := False;
begin
-- Special processing for GNSA mode:
if Tree_Processing_Mode (Curr_Context) = GNSA then
-- This is no more than a workaround for -GNSA C1 Context when we
-- have exactly one tree (and exactly one (GNSA) Context!
return;
end if;
Tree_To_Set :=
Unit_Table.Table (U).Main_Tree;
if No (Tree_To_Set) then
if Kind (Lib_Level_Instance) in A_Package .. A_Generic_Package or else
Kind (Lib_Level_Instance) in A_Library_Unit_Body
then
U := Get_Body (Current_Context, U);
if Tree_Processing_Mode (Curr_Context) = Incremental and then
(No (U) or else
No (Unit_Table.Table (U).Main_Tree))
then
-- In this situation we try to compile the needed body on the
-- fly
if Is_Body_Required (Lib_Level_Instance) or else
Kind (Lib_Level_Instance) in A_Library_Unit_Body
then
U := Get_Main_Unit_Tree_On_The_Fly
(Start_Unit => Get_Unit_Id (Lib_Level_Instance),
Cont => Curr_Context,
Spec => False);
else
U := Get_Main_Unit_Tree_On_The_Fly
(Start_Unit => Get_Unit_Id (Lib_Level_Instance),
Cont => Curr_Context,
Spec => True);
end if;
end if;
elsif Kind (Lib_Level_Instance) in A_Generic_Unit_Instance and then
Tree_Processing_Mode (Encl_Cont_Id (Lib_Level_Instance)) =
Incremental
then
U := Get_Main_Unit_Tree_On_The_Fly
(Start_Unit => Get_Unit_Id (Lib_Level_Instance),
Cont => Curr_Context,
Spec => True);
end if;
if Present (U) then
Tree_To_Set := Unit_Table.Table (U).Main_Tree;
Reset_Tree (Context => Get_Current_Cont,
Tree => Curr_Tree);
end if;
end if;
if No (Tree_To_Set) or else Tree_To_Set = Current_Tree then
return;
end if;
Create_Node_Trace (Decl_Node);
Reset_Tree (Context => Get_Current_Cont,
Tree => Tree_To_Set);
if Kind (Lib_Level_Instance) in A_Library_Unit_Body then
In_Body := True;
end if;
Decl_Node := Restore_Node_From_Trace (In_Body);
end Reset_Instance_Tree;
----------------------------------
-- Tree_Consistent_With_Sources --
----------------------------------
function Tree_Consistent_With_Sources
(E : Asis.Element)
return Boolean
is
begin
Reset_Tree (Encl_Cont_Id (E), Encl_Tree (E));
return Current_Tree_Consistent_With_Sources;
end Tree_Consistent_With_Sources;
function Tree_Consistent_With_Sources
(CU : Asis.Compilation_Unit)
return Boolean
is
begin
Reset_Tree_For_Unit (CU);
return Current_Tree_Consistent_With_Sources;
end Tree_Consistent_With_Sources;
--------------------------
-- Unit_In_Current_Tree --
--------------------------
function Unit_In_Current_Tree (C : Context_Id; U : Unit_Id) return Boolean
is
begin
if U = Standard_Id then
return True;
end if;
if Current_Context /= C then
return False;
end if;
return
In_Elmt_List
(Unit_Id (Current_Tree), Unit_Table.Table (U).Full_View_Trees)
or else
(No (Unit_Table.Table (U).Full_View_Trees)
and then
In_Elmt_List
(Unit_Id (Current_Tree), Unit_Table.Table (U).Limited_View_Trees));
end Unit_In_Current_Tree;
--------------------------------------------------
-- General-Purpose Tree Table Subprograms --
--------------------------------------------------
---------------
-- Last_Tree --
---------------
function Last_Tree (C : Context_Id) return Tree_Id is
begin
Reset_Context (C);
return Tree_Table.Last;
end Last_Tree;
--------
-- No --
--------
function No (Tree : Tree_Id) return Boolean is
begin
return Tree = Nil_Tree;
end No;
-----------------
-- Output_Tree --
-----------------
procedure Output_Tree (C : Context_Id; Tree : Tree_Id) is
begin
-- ??? Check for Debug_Mode should be moved into the context(s) where
-- ??? Output_Tree is called
if Debug_Mode or else
Debug_Flag_C or else
Debug_Lib_Model
then
Write_Str ("Debug output for Tree Id " & Tree_Id'Image (Tree));
Write_Eol;
if Tree = Nil_Tree then
Write_Str ("This is a Nil Tree");
Write_Eol;
return;
end if;
Get_Name_String (C, Tree);
Write_Str ("Tree File Name is: " & A_Name_Buffer (1 .. A_Name_Len));
Write_Eol;
Write_Str ("Main Unit Id : ");
Write_Str (Main_Unit_Id (Tree)'Img);
Write_Eol;
Write_Str ("The list of the Units contained in the tree:");
Write_Eol;
Print_List (Tree_Table.Table (Tree).Units);
Write_Eol;
end if;
end Output_Tree;
-------------
-- Present --
-------------
function Present (Tree : Tree_Id) return Boolean is
begin
return Tree /= No_Tree_Name;
end Present;
end A4G.Contt.TT;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
48728bc1e63b1f291ba80a3afe544627be7abd72
|
src/asis/a4g-norm.ads
|
src/asis/a4g-norm.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . N O R M --
-- --
-- S p e c --
-- --
-- Copyright (c) 1995-2006, Free Software Foundation, Inc. --
-- --
-- ASIS-for-GNAT is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 2, or (at your option) any later --
-- version. ASIS-for-GNAT is distributed in the hope that it will be use- --
-- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- --
-- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General --
-- Public License for more details. You should have received a copy of the --
-- GNU General Public License distributed with ASIS-for-GNAT; see file --
-- COPYING. If not, write to the Free Software Foundation, 51 Franklin --
-- Street, Fifth Floor, Boston, MA 02110-1301, USA. --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the --
-- Software Engineering Laboratory of the Swiss Federal Institute of --
-- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the --
-- Scientific Research Computer Center of Moscow State University (SRCC --
-- MSU), Russia, with funding partially provided by grants from the Swiss --
-- National Science Foundation and the Swiss Academy of Engineering --
-- Sciences. ASIS-for-GNAT is now maintained by AdaCore --
-- (http://www.adacore.com). --
-- --
------------------------------------------------------------------------------
-- This package defines routines needed for yielding and processing
-- normalized associations and their components
with Asis;
with Types; use Types;
package A4G.Norm is
---------------------------------------
-- Obtaining normalized associations --
---------------------------------------
function Normalized_Param_Associations
(Call_Elem : Asis.Element)
return Asis.Association_List;
-- Creates the list of normalized associations for a given call to an
-- entry, a procedure or to a function (is intended to be used in the
-- implementation of Asis.Expressions.Function_Call_Parameters and
-- Asis.Statements.Call_Statement_Parameters). This function assumes that
-- the association list to be returned is not empty. It is an error to call
-- it when Sinfo.Parameter_Assoccciations function gives No_List for
-- the node representing the call in question
function Normalized_Discriminant_Associations
(Constr_Elem : Asis.Element;
Constr_Node : Node_Id)
return Asis.Association_List;
-- creates the list of normalized associations for a given discriminant
-- constraint; is intended to be used in the implementation of
-- Asis.Definitions.Discriminant_Associations. This function assumes,
-- that Constr_Node is of N_Index_Or_Discriminant_Constraint,
-- it is an error to call it for other nodes.
function Normalized_Generic_Associations
(Inst_Elem : Asis.Element;
Templ_Node : Node_Id)
return Asis.Association_List;
-- Creates the list of normalized associations for a given generic
-- instantiation (is intended to be used in the implementation of
-- Asis.Decalarations.Generic_Actual_Part. Templ_Node should be the
-- node representing the corresponding generic template declaration.
-- This function is supposed to be called if it is known that the list
-- of normalized associations is not empty
--
-- See the documentation of the body for the description of the
-- representation of the normalized generic associations.
function Normalized_Record_Component_Associations
(Aggregate : Asis.Element)
return Asis.Element_List;
-- Creates a list of normalized associations for a record aggregate
function Defining_Gen_Parameter (Gen_Form_Par : Node_Id) return Node_Id;
-- Assuming that Gen_Form_Par is a node representing a
-- generic_formal_parameter_SELECTOR_NAME (it is an error to call this
-- function for another actual!!!), this function finds the node
-- representing the defining occurrence of this generic formal
-- parameter.
--
-- ??? Is here a really good place for this function?
--
-- ??? And do we really need it???
--
-- For now this function is PARTIALLY IMPLEMENTED - it can work only
-- with a generic_formal_parameter_SELECTOR_NAME which is
-- operator_symbol "+" or "-"
----------------------------------------
-- Processing normalized associations --
----------------------------------------
function Discr_Def_Name
(Association : Asis.Discriminant_Association)
return Asis.Defining_Name;
-- from a normalized discriminant association this function creates
-- the ASIS Element representing the defining occurrence of the
-- discriminant. (Is intended to be used in
-- Asis.Expressions.Discriminant_Selector_Names).
--
-- !!!NOTE: for now the implementation is unstable and definitely
-- contains holes.
end A4G.Norm;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
8245b47867ab6c51f801c15340ce5351edca61b9
|
src/asm-intrinsic/util-concurrent-counters.ads
|
src/asm-intrinsic/util-concurrent-counters.ads
|
-----------------------------------------------------------------------
-- Util.Concurrent -- Concurrent Counters
-- Copyright (C) 2009, 2010, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- The <b>Counters</b> package defines the <b>Counter</b> type which provides
-- atomic increment and decrement operations. It is intended to be used to
-- implement reference counting in a multi-threaded environment.
--
-- type Ref is record
-- Cnt : Counter;
-- Data : ...;
-- end record;
--
-- Object : access Ref;
-- Is_Last : Boolean;
-- begin
-- Decrement (Object.Cnt, Is_Last); -- Multi-task safe operation
-- if Is_Last then
-- Free (Object);
-- end if;
--
-- Unlike the Ada portable implementation based on protected type, this implementation
-- does not require that <b>Counter</b> be a limited type.
private with Interfaces;
package Util.Concurrent.Counters is
pragma Preelaborate;
-- ------------------------------
-- Atomic Counter
-- ------------------------------
-- The atomic <b>Counter</b> implements a simple counter that can be
-- incremented or decremented atomically.
type Counter is private;
type Counter_Access is access all Counter;
-- Increment the counter atomically.
procedure Increment (C : in out Counter);
pragma Inline_Always (Increment);
-- Increment the counter atomically and return the value before increment.
procedure Increment (C : in out Counter;
Value : out Integer);
pragma Inline_Always (Increment);
-- Decrement the counter atomically.
procedure Decrement (C : in out Counter);
pragma Inline_Always (Decrement);
-- Decrement the counter atomically and return a status.
procedure Decrement (C : in out Counter;
Is_Zero : out Boolean);
pragma Inline_Always (Decrement);
-- Get the counter value
function Value (C : in Counter) return Integer;
pragma Inline_Always (Value);
ONE : constant Counter;
private
-- This implementation works without an Ada protected type:
-- o The size of the target object is 10 times smaller.
-- o Increment and Decrement operations are 5 times faster.
-- o It works by using special instructions
-- o The counter is Atomic to make sure the compiler will use atomic read/write instructions
-- and it prevents optimization (Atomic implies Volatile). The Atomic does not mean
-- that atomic instructions are used.
type Counter is record
Value : aliased Interfaces.Unsigned_32 := 0;
pragma Atomic (Value);
end record;
ONE : constant Counter := Counter '(Value => 1);
end Util.Concurrent.Counters;
|
Declare the Counters package for the gcc builtin implementation
|
Declare the Counters package for the gcc builtin implementation
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
|
7a540eb2585fc35138bc5801d3290772a605651c
|
src/asis/asis-ada_environments.ads
|
src/asis/asis-ada_environments.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT INTERFACE COMPONENTS --
-- --
-- A S I S . A D A _ E N V I R O N M E N T S --
-- --
-- S p e c --
-- --
-- --
-- Copyright (c) 2006, Free Software Foundation, Inc. --
-- --
-- This specification is adapted from the Ada Semantic Interface --
-- Specification Standard (ISO/IEC 15291) 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. The copyright notice --
-- above, and the license provisions that follow apply solely to the --
-- contents of the part following the private keyword. --
-- --
-- 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). --
-- --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- 8 package Asis.Ada_Environments
------------------------------------------------------------------------------
------------------------------------------------------------------------------
package Asis.Ada_Environments is
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Asis.Ada_Environments encapsulates a set of queries that map physical Ada
-- compilation and program execution environments to logical ASIS
-- environments.
--
------------------------------------------------------------------------------
-- 8.1 function Default_Name
------------------------------------------------------------------------------
function Default_Name return Wide_String;
------------------------------------------------------------------------------
-- Returns the default context name. If there is no default context name, a
-- null string is returned.
--
------------------------------------------------------------------------------
-- 8.2 function Default_Parameters
------------------------------------------------------------------------------
function Default_Parameters return Wide_String;
------------------------------------------------------------------------------
-- Returns the default context parameters. If there are no default context
-- parameters, a null string is returned.
--
------------------------------------------------------------------------------
-- 8.3 procedure Associate
------------------------------------------------------------------------------
procedure Associate
(The_Context : in out Asis.Context;
Name : Wide_String;
Parameters : Wide_String := Default_Parameters);
------------------------------------------------------------------------------
-- The_Context - Specifies the Context to associate
-- Name - Specifies the name for the Context association
-- Parameters - Specifies parameters to use when opening the Context
--
-- Used to give name and parameter associations to a Context. The
-- Has_Associations query is used to test whether or not a Context has
-- been given name and parameter associations. The Name and Parameters
-- queries are used to examine name and parameter associations.
--
-- A Context has at most one set of name/parameter values associated with
-- it at any time. Name and parameter associations cannot be modified while a
-- Context is open Previous name and parameters associations for this Context
-- are replaced by this call.
--
-- ASIS implementations are encouraged, but not required, to validate the
-- Parameters string immediately. It is recognized that some options cannot
-- be completely validated until the Open is performed. An invalid Parameters
-- value is reported by raising ASIS_Failed with a Status of Parameter_Error.
--
-- Raises ASIS_Inappropriate_Context if The_Context is open.
--
------------------------------------------------------------------------------
-- 8.4 procedure Open
------------------------------------------------------------------------------
procedure Open (The_Context : in out Asis.Context);
------------------------------------------------------------------------------
-- The_Context - Specifies the Context to open
--
-- Opens the ASIS Context using the Context's associated name and parameter
-- values.
--
-- Raises ASIS_Inappropriate_Context if The_Context is already open or if it
-- is uninitialized (does not have associated name and parameter values).
--
-- Raises ASIS_Failed if The_Context could not be opened for any reason. The
-- most likely Status values are Name_Error, Use_Error, Data_Error, and
-- Parameter_Error. Other possibilities include Storage_Error and
-- Capacity_Error.
--
------------------------------------------------------------------------------
-- 8.5 procedure Close
------------------------------------------------------------------------------
procedure Close (The_Context : in out Asis.Context);
------------------------------------------------------------------------------
-- The_Context - Specifies the Context to close
--
-- Closes the ASIS Context. Any previous Context name and parameter
-- associations are retained. This allows the same Context to be re-opened
-- later with the same associations.
--
-- All Compilation_Unit and Element values obtained from The_Context become
-- invalid when it is closed. Subsequent calls to ASIS services using such
-- invalid Compilation_Unit or Element values are erroneous. ASIS
-- implementations will attempt to detect such usage and raise ASIS_Failed in
-- response. Applications should be aware that the ability to detect the use
-- of such "dangling references" is implementation specific and not all
-- implementations are able to raise ASIS_Failed at the appropriate
-- points. Thus, applications that attempt to utilize invalid values may
-- exhibit unpredictable behavior.
--
-- Raises ASIS_Inappropriate_Context if The_Context is not open.
--
------------------------------------------------------------------------------
-- 8.6 procedure Dissociate
------------------------------------------------------------------------------
procedure Dissociate (The_Context : in out Asis.Context);
------------------------------------------------------------------------------
-- The_Context - Specifies the Context whose name and parameter associations
-- are to be cleared
--
-- Severs all previous associations for The_Context. A Context that does not
-- have associations (is uninitialized) is returned unchanged. The
-- variable The_Context is returned to its uninitialized state.
--
-- Contexts that have been given Names and Parameters should be Dissociated
-- when they are no longer necessary. Some amount of program storage can be
-- tied up by the stored Name and Parameter strings. This space is only
-- freed when a Context is Dissociated or when ASIS is Finalized.
--
-- This operation has no physical affect on any implementor's Ada environment.
--
-- Raises ASIS_Inappropriate_Context if The_Context is open.
--
------------------------------------------------------------------------------
-- 8.7 function Is_Equal
------------------------------------------------------------------------------
function Is_Equal
(Left : Asis.Context;
Right : Asis.Context)
return Boolean;
------------------------------------------------------------------------------
-- Left - Specifies the first Context
-- Right - Specifies the second Context
--
-- Returns True if Left and Right designate the same set of associated
-- compilation units. The Context variables may be open or closed.
--
-- Unless both Contexts are open, this operation is implemented as a pair of
-- simple string comparisons between the Name and Parameter associations for
-- the two Contexts. If both Contexts are open, this operation acts as a
-- set comparison and returns True if both sets contain the same units (all
-- unit versions are included in the comparison).
--
-- --|AN Application Note:
-- --|AN
-- --|AN With some implementations, Is_Equal may be True before the Contexts
-- --|AN are opened, but may be False after the Contexts are open.
-- --|AN One possible cause for this is a sequence of events such as:
-- --|AN
-- --|AN 1) ASIS program A opens the Left Context for READ,
-- --|AN 2) non-ASIS program B opens the Context for UPDATE, and creates
-- --|AN a new version of the implementor Context,
-- --|AN 3) ASIS program A opens the Right Context for READ, and gets the
-- --|AN new version.
--
------------------------------------------------------------------------------
-- 8.8 function Is_Identical
------------------------------------------------------------------------------
function Is_Identical
(Left : Asis.Context;
Right : Asis.Context)
return Boolean;
------------------------------------------------------------------------------
-- Left - Specifies the first Context
-- Right - Specifies the second Context
--
-- Returns True if Left and Right both designate the value associated with
-- one specific ASIS Context variable.
--
-- Returns False otherwise or if either Context is not open.
--
-- --|AN Application Note:
-- --|AN
-- --|AN No two physically separate open Context variables are ever
-- --|AN Is_Identical. The value associated with an open ASIS Context variable
-- --|AN is also directly associated with every Compilation_Unit or Element
-- --|AN derived from that Context. It is possible to obtain these Context
-- --|AN values by way of the Enclosing_Context and the
-- --|AN Enclosing_Compilation_Unit queries. These Context values can be
-- --|AN tested for identity with each other or with specific Context
-- --|AN variables. An open ASIS Context variable and an Enclosing_Context
-- --|AN value are only Is_Identical if the Compilation_Unit in question
-- --|AN was derived specifically from that open ASIS Context variable.
--
------------------------------------------------------------------------------
-- 8.9 function Exists
------------------------------------------------------------------------------
function Exists (The_Context : Asis.Context) return Boolean;
------------------------------------------------------------------------------
-- The_Context - Specifies a Context with associated name and parameter values
--
-- Returns True if The_Context is open or if The_Context designates an Ada
-- environment that can be determined to exist.
--
-- Returns False for any uninitialized The_Context variable.
--
-- --|IP Implementation Permissions:
-- --|IP
-- --|IP No guarantee is made that The_Context is readable or that an Open
-- --|IP operation on The_Context would succeed. The associated
-- --|IP parameter value for The_Context may not be fully validated by this
-- --|IP simple existence check. It may contain information that can only be
-- --|IP verified by an Open.
--
------------------------------------------------------------------------------
-- 8.10 function Is_Open
------------------------------------------------------------------------------
function Is_Open (The_Context : Asis.Context) return Boolean;
------------------------------------------------------------------------------
-- The_Context - Specifies the Context to check
--
-- Returns True if The_Context is currently open.
--
------------------------------------------------------------------------------
-- 8.11 function Has_Associations
------------------------------------------------------------------------------
function Has_Associations (The_Context : Asis.Context) return Boolean;
------------------------------------------------------------------------------
-- The_Context - Specifies the Context to check
--
-- Returns True if name and parameter values have been associated with
-- The_Context.
--
-- Returns False if The_Context is uninitialized.
--
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- 8.12 function Name
------------------------------------------------------------------------------
function Name (The_Context : Asis.Context) return Wide_String;
------------------------------------------------------------------------------
-- The_Context - Specifies the Context to check
--
-- Returns the Name value associated with The_Context.
--
-- Returns a null string if The_Context is uninitialized.
--
------------------------------------------------------------------------------
-- 8.13 function Parameter
------------------------------------------------------------------------------
function Parameters (The_Context : Asis.Context) return Wide_String;
------------------------------------------------------------------------------
-- The_Context - Specifies the Context to check
--
-- Returns the Parameters value associated with The_Context.
--
-- Returns a null string if The_Context is uninitialized.
--
------------------------------------------------------------------------------
-- 8.14 function Debug_Image
------------------------------------------------------------------------------
function Debug_Image (The_Context : Asis.Context) return Wide_String;
------------------------------------------------------------------------------
-- The_Context - Specifies the Context to represent
--
-- Returns a string value containing implementation-defined debugging
-- information associated with The_Context.
--
-- The return value uses Asis.Text.Delimiter_Image to separate lines in
-- multi-line results. The return value is not terminated with
-- Asis.Text.Delimiter_Image.
--
-- Returns a null string if The_Context is uninitialized.
--
-- These values are intended for two purposes. They are suitable for
-- inclusion in problem reports sent to the ASIS implementor. They can be
-- presumed to contain information useful when debugging the implementation
-- itself. They are also suitable for use by the ASIS application when
-- printing simple application debugging messages during application
-- development. They are intended to be, to some worthwhile degree,
-- intelligible to the user.
end Asis.Ada_Environments;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
6ed477a6dad7305fd23994d6a2bc45b7a963fa54
|
src/nanomsg-bus.ads
|
src/nanomsg-bus.ads
|
{header}
-- The MIT License (MIT)
-- Copyright (c) 2015 Pavel Zhukov <[email protected]>
-- 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.
package Nanomsg.Bus is
Nn_Proto_Bus : constant := 7;
Nn_Bus : constant Protocol_T := Nn_Proto_Bus * 16 + 0;и
end Nanomsg.Bus;
|
Add Readme
|
Add Readme
|
Ada
|
mit
|
landgraf/nanomsg-ada
|
|
0bd061ac9dc376407b2c1b29b3d93fbd018dbb03
|
src/os-linux/util-processes-os.adb
|
src/os-linux/util-processes-os.adb
|
-----------------------------------------------------------------------
-- util-processes-os -- System specific and low level operations
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Interfaces.C.Strings;
package body Util.Processes.Os is
use Util.Systems.Os;
use type Interfaces.C.size_t;
type Pipe_Type is array (0 .. 1) of File_Type;
procedure Close (Pipes : in out Pipe_Type);
-- ------------------------------
-- Create the output stream to read/write on the process input/output.
-- Setup the file to be closed on exec.
-- ------------------------------
function Create_Stream (File : in File_Type)
return Util.Streams.Raw.Raw_Stream_Access is
Stream : constant Util.Streams.Raw.Raw_Stream_Access := new Util.Streams.Raw.Raw_Stream;
Status : constant Integer := Sys_Fcntl (File, F_SETFL, FD_CLOEXEC);
pragma Unreferenced (Status);
begin
Stream.Initialize (File);
return Stream;
end Create_Stream;
-- ------------------------------
-- Wait for the process to exit.
-- ------------------------------
overriding
procedure Wait (Sys : in out System_Process;
Proc : in out Process'Class;
Timeout : in Duration) is
pragma Unreferenced (Sys, Timeout);
use type Util.Streams.Output_Stream_Access;
Result : Integer;
Wpid : Integer;
begin
-- Close the input stream pipe if there is one.
if Proc.Input /= null then
Util.Streams.Raw.Raw_Stream'Class (Proc.Input.all).Close;
end if;
Wpid := Sys_Waitpid (Integer (Proc.Pid), Result'Address, 0);
if Wpid = Integer (Proc.Pid) then
Proc.Exit_Value := Result / 256;
if Result mod 256 /= 0 then
Proc.Exit_Value := (Result mod 256) * 1000;
end if;
end if;
end Wait;
-- ------------------------------
-- Terminate the process by sending a signal on Unix and exiting the process on Windows.
-- This operation is not portable and has a different behavior between Unix and Windows.
-- Its intent is to stop the process.
-- ------------------------------
overriding
procedure Stop (Sys : in out System_Process;
Proc : in out Process'Class;
Signal : in Positive := 15) is
pragma Unreferenced (Sys);
Result : Integer;
begin
Result := Sys_Kill (Integer (Proc.Pid), Integer (Signal));
end Stop;
-- ------------------------------
-- Close both ends of the pipe (used to cleanup in case or error).
-- ------------------------------
procedure Close (Pipes : in out Pipe_Type) is
Result : Integer;
pragma Unreferenced (Result);
begin
if Pipes (0) /= NO_FILE then
Result := Sys_Close (Pipes (0));
Pipes (0) := NO_FILE;
end if;
if Pipes (1) /= NO_FILE then
Result := Sys_Close (Pipes (1));
Pipes (1) := NO_FILE;
end if;
end Close;
-- ------------------------------
-- Spawn a new process.
-- ------------------------------
overriding
procedure Spawn (Sys : in out System_Process;
Proc : in out Process'Class;
Mode : in Pipe_Mode := NONE) is
use Util.Streams.Raw;
use Interfaces.C.Strings;
use type Interfaces.C.int;
procedure Cleanup;
-- Suppress all checks to make sure the child process will not raise any exception.
pragma Suppress (All_Checks);
Result : Integer;
pragma Unreferenced (Result);
Stdin_Pipes : aliased Pipe_Type := (others => NO_FILE);
Stdout_Pipes : aliased Pipe_Type := (others => NO_FILE);
Stderr_Pipes : aliased Pipe_Type := (others => NO_FILE);
procedure Cleanup is
begin
Close (Stdin_Pipes);
Close (Stdout_Pipes);
Close (Stderr_Pipes);
end Cleanup;
begin
-- Since checks are disabled, verify by hand that the argv table is correct.
if Sys.Argv = null or else Sys.Argc < 1 or else Sys.Argv (0) = Null_Ptr then
raise Program_Error with "Invalid process argument list";
end if;
-- Setup the pipes.
if Mode = READ or Mode = READ_WRITE or Mode = READ_ALL then
if Sys_Pipe (Stdout_Pipes'Address) /= 0 then
raise Process_Error with "Cannot create stdout pipe";
end if;
end if;
if Mode = WRITE or Mode = READ_WRITE or Mode = READ_WRITE_ALL then
if Sys_Pipe (Stdin_Pipes'Address) /= 0 then
Cleanup;
raise Process_Error with "Cannot create stdin pipe";
end if;
end if;
if Mode = READ_ERROR then
if Sys_Pipe (Stderr_Pipes'Address) /= 0 then
Cleanup;
raise Process_Error with "Cannot create stderr pipe";
end if;
end if;
-- Create the new process by using vfork instead of fork. The parent process is blocked
-- until the child executes the exec or exits. The child process uses the same stack
-- as the parent.
Proc.Pid := Sys_VFork;
if Proc.Pid = 0 then
-- Do not use any Ada type while in the child process.
if Mode = READ_ALL or Mode = READ_WRITE_ALL then
Result := Sys_Dup2 (Stdout_Pipes (1), STDERR_FILENO);
end if;
if Stderr_Pipes (1) /= NO_FILE then
if Stderr_Pipes (1) /= STDERR_FILENO then
Result := Sys_Dup2 (Stderr_Pipes (1), STDERR_FILENO);
Result := Sys_Close (Stderr_Pipes (1));
end if;
Result := Sys_Close (Stderr_Pipes (0));
elsif Sys.Err_File /= Null_Ptr then
-- Redirect the process error to a file.
declare
Fd : File_Type;
begin
if Sys.Err_Append then
Fd := Sys_Open (Sys.Err_File, O_CREAT + O_WRONLY + O_APPEND, 8#644#);
else
Fd := Sys_Open (Sys.Err_File, O_CREAT + O_WRONLY + O_TRUNC, 8#644#);
end if;
if Fd < 0 then
Sys_Exit (254);
end if;
Result := Sys_Dup2 (Fd, STDOUT_FILENO);
Result := Sys_Close (Fd);
end;
end if;
if Stdout_Pipes (1) /= NO_FILE then
if Stdout_Pipes (1) /= STDOUT_FILENO then
Result := Sys_Dup2 (Stdout_Pipes (1), STDOUT_FILENO);
Result := Sys_Close (Stdout_Pipes (1));
end if;
Result := Sys_Close (Stdout_Pipes (0));
elsif Sys.Out_File /= Null_Ptr then
-- Redirect the process output to a file.
declare
Fd : File_Type;
begin
if Sys.Out_Append then
Fd := Sys_Open (Sys.Out_File, O_CREAT + O_WRONLY + O_APPEND, 8#644#);
else
Fd := Sys_Open (Sys.Out_File, O_CREAT + O_WRONLY + O_TRUNC, 8#644#);
end if;
if Fd < 0 then
Sys_Exit (254);
end if;
Result := Sys_Dup2 (Fd, STDOUT_FILENO);
Result := Sys_Close (Fd);
end;
end if;
if Stdin_Pipes (0) /= NO_FILE then
if Stdin_Pipes (0) /= STDIN_FILENO then
Result := Sys_Dup2 (Stdin_Pipes (0), STDIN_FILENO);
Result := Sys_Close (Stdin_Pipes (0));
end if;
Result := Sys_Close (Stdin_Pipes (1));
elsif Sys.In_File /= Null_Ptr then
-- Redirect the process input to a file.
declare
Fd : File_Type;
begin
Fd := Sys_Open (Sys.Out_File, O_RDONLY, 8#644#);
if Fd < 0 then
Sys_Exit (254);
end if;
Result := Sys_Dup2 (Fd, STDIN_FILENO);
Result := Sys_Close (Fd);
end;
end if;
Result := Sys_Execvp (Sys.Argv (0), Sys.Argv.all);
Sys_Exit (255);
end if;
-- Process creation failed, cleanup and raise an exception.
if Proc.Pid < 0 then
Cleanup;
raise Process_Error with "Cannot create process";
end if;
if Stdin_Pipes (1) /= NO_FILE then
Result := Sys_Close (Stdin_Pipes (0));
Proc.Input := Create_Stream (Stdin_Pipes (1)).all'Access;
end if;
if Stdout_Pipes (0) /= NO_FILE then
Result := Sys_Close (Stdout_Pipes (1));
Proc.Output := Create_Stream (Stdout_Pipes (0)).all'Access;
end if;
if Stderr_Pipes (0) /= NO_FILE then
Result := Sys_Close (Stderr_Pipes (1));
Proc.Error := Create_Stream (Stderr_Pipes (0)).all'Access;
end if;
end Spawn;
procedure Free is
new Ada.Unchecked_Deallocation (Name => Ptr_Ptr_Array, Object => Ptr_Array);
-- ------------------------------
-- Append the argument to the process argument list.
-- ------------------------------
overriding
procedure Append_Argument (Sys : in out System_Process;
Arg : in String) is
begin
if Sys.Argv = null then
Sys.Argv := new Ptr_Array (0 .. 10);
elsif Sys.Argc = Sys.Argv'Last - 1 then
declare
N : constant Ptr_Ptr_Array := new Ptr_Array (0 .. Sys.Argc + 32);
begin
N (0 .. Sys.Argc) := Sys.Argv (0 .. Sys.Argc);
Free (Sys.Argv);
Sys.Argv := N;
end;
end if;
Sys.Argv (Sys.Argc) := Interfaces.C.Strings.New_String (Arg);
Sys.Argc := Sys.Argc + 1;
Sys.Argv (Sys.Argc) := Interfaces.C.Strings.Null_Ptr;
end Append_Argument;
-- ------------------------------
-- Set the process input, output and error streams to redirect and use specified files.
-- ------------------------------
overriding
procedure Set_Streams (Sys : in out System_Process;
Input : in String;
Output : in String;
Error : in String;
Append_Output : in Boolean;
Append_Error : in Boolean) is
begin
if Input'Length > 0 then
Sys.In_File := Interfaces.C.Strings.New_String (Input);
end if;
if Output'Length > 0 then
Sys.Out_File := Interfaces.C.Strings.New_String (Output);
Sys.Out_Append := Append_Output;
end if;
if Error'Length > 0 then
Sys.Err_File := Interfaces.C.Strings.New_String (Error);
Sys.Err_Append := Append_Error;
end if;
end Set_Streams;
-- ------------------------------
-- Deletes the storage held by the system process.
-- ------------------------------
overriding
procedure Finalize (Sys : in out System_Process) is
begin
if Sys.Argv /= null then
for I in Sys.Argv'Range loop
Interfaces.C.Strings.Free (Sys.Argv (I));
end loop;
Free (Sys.Argv);
end if;
Interfaces.C.Strings.Free (Sys.In_File);
Interfaces.C.Strings.Free (Sys.Out_File);
Interfaces.C.Strings.Free (Sys.Err_File);
end Finalize;
end Util.Processes.Os;
|
-----------------------------------------------------------------------
-- util-processes-os -- System specific and low level operations
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Util.Processes.Os is
use Util.Systems.Os;
use type Interfaces.C.size_t;
type Pipe_Type is array (0 .. 1) of File_Type;
procedure Close (Pipes : in out Pipe_Type);
-- ------------------------------
-- Create the output stream to read/write on the process input/output.
-- Setup the file to be closed on exec.
-- ------------------------------
function Create_Stream (File : in File_Type)
return Util.Streams.Raw.Raw_Stream_Access is
Stream : constant Util.Streams.Raw.Raw_Stream_Access := new Util.Streams.Raw.Raw_Stream;
Status : constant Integer := Sys_Fcntl (File, F_SETFL, FD_CLOEXEC);
pragma Unreferenced (Status);
begin
Stream.Initialize (File);
return Stream;
end Create_Stream;
-- ------------------------------
-- Wait for the process to exit.
-- ------------------------------
overriding
procedure Wait (Sys : in out System_Process;
Proc : in out Process'Class;
Timeout : in Duration) is
pragma Unreferenced (Sys, Timeout);
use type Util.Streams.Output_Stream_Access;
Result : Integer;
Wpid : Integer;
begin
-- Close the input stream pipe if there is one.
if Proc.Input /= null then
Util.Streams.Raw.Raw_Stream'Class (Proc.Input.all).Close;
end if;
Wpid := Sys_Waitpid (Integer (Proc.Pid), Result'Address, 0);
if Wpid = Integer (Proc.Pid) then
Proc.Exit_Value := Result / 256;
if Result mod 256 /= 0 then
Proc.Exit_Value := (Result mod 256) * 1000;
end if;
end if;
end Wait;
-- ------------------------------
-- Terminate the process by sending a signal on Unix and exiting the process on Windows.
-- This operation is not portable and has a different behavior between Unix and Windows.
-- Its intent is to stop the process.
-- ------------------------------
overriding
procedure Stop (Sys : in out System_Process;
Proc : in out Process'Class;
Signal : in Positive := 15) is
pragma Unreferenced (Sys);
Result : Integer;
begin
Result := Sys_Kill (Integer (Proc.Pid), Integer (Signal));
end Stop;
-- ------------------------------
-- Close both ends of the pipe (used to cleanup in case or error).
-- ------------------------------
procedure Close (Pipes : in out Pipe_Type) is
Result : Integer;
pragma Unreferenced (Result);
begin
if Pipes (0) /= NO_FILE then
Result := Sys_Close (Pipes (0));
Pipes (0) := NO_FILE;
end if;
if Pipes (1) /= NO_FILE then
Result := Sys_Close (Pipes (1));
Pipes (1) := NO_FILE;
end if;
end Close;
-- ------------------------------
-- Spawn a new process.
-- ------------------------------
overriding
procedure Spawn (Sys : in out System_Process;
Proc : in out Process'Class;
Mode : in Pipe_Mode := NONE) is
use Util.Streams.Raw;
use Interfaces.C.Strings;
use type Interfaces.C.int;
procedure Cleanup;
-- Suppress all checks to make sure the child process will not raise any exception.
pragma Suppress (All_Checks);
Result : Integer;
pragma Unreferenced (Result);
Stdin_Pipes : aliased Pipe_Type := (others => NO_FILE);
Stdout_Pipes : aliased Pipe_Type := (others => NO_FILE);
Stderr_Pipes : aliased Pipe_Type := (others => NO_FILE);
procedure Cleanup is
begin
Close (Stdin_Pipes);
Close (Stdout_Pipes);
Close (Stderr_Pipes);
end Cleanup;
begin
-- Since checks are disabled, verify by hand that the argv table is correct.
if Sys.Argv = null or else Sys.Argc < 1 or else Sys.Argv (0) = Null_Ptr then
raise Program_Error with "Invalid process argument list";
end if;
-- Setup the pipes.
if Mode = READ or Mode = READ_WRITE or Mode = READ_ALL then
if Sys_Pipe (Stdout_Pipes'Address) /= 0 then
raise Process_Error with "Cannot create stdout pipe";
end if;
end if;
if Mode = WRITE or Mode = READ_WRITE or Mode = READ_WRITE_ALL then
if Sys_Pipe (Stdin_Pipes'Address) /= 0 then
Cleanup;
raise Process_Error with "Cannot create stdin pipe";
end if;
end if;
if Mode = READ_ERROR then
if Sys_Pipe (Stderr_Pipes'Address) /= 0 then
Cleanup;
raise Process_Error with "Cannot create stderr pipe";
end if;
end if;
-- Create the new process by using vfork instead of fork. The parent process is blocked
-- until the child executes the exec or exits. The child process uses the same stack
-- as the parent.
Proc.Pid := Sys_VFork;
if Proc.Pid = 0 then
-- Do not use any Ada type while in the child process.
if Mode = READ_ALL or Mode = READ_WRITE_ALL then
Result := Sys_Dup2 (Stdout_Pipes (1), STDERR_FILENO);
end if;
if Stderr_Pipes (1) /= NO_FILE then
if Stderr_Pipes (1) /= STDERR_FILENO then
Result := Sys_Dup2 (Stderr_Pipes (1), STDERR_FILENO);
Result := Sys_Close (Stderr_Pipes (1));
end if;
Result := Sys_Close (Stderr_Pipes (0));
elsif Sys.Err_File /= Null_Ptr then
-- Redirect the process error to a file.
declare
Fd : File_Type;
begin
if Sys.Err_Append then
Fd := Sys_Open (Sys.Err_File, O_CREAT + O_WRONLY + O_APPEND, 8#644#);
else
Fd := Sys_Open (Sys.Err_File, O_CREAT + O_WRONLY + O_TRUNC, 8#644#);
end if;
if Fd < 0 then
Sys_Exit (254);
end if;
Result := Sys_Dup2 (Fd, STDOUT_FILENO);
Result := Sys_Close (Fd);
end;
end if;
if Stdout_Pipes (1) /= NO_FILE then
if Stdout_Pipes (1) /= STDOUT_FILENO then
Result := Sys_Dup2 (Stdout_Pipes (1), STDOUT_FILENO);
Result := Sys_Close (Stdout_Pipes (1));
end if;
Result := Sys_Close (Stdout_Pipes (0));
elsif Sys.Out_File /= Null_Ptr then
-- Redirect the process output to a file.
declare
Fd : File_Type;
begin
if Sys.Out_Append then
Fd := Sys_Open (Sys.Out_File, O_CREAT + O_WRONLY + O_APPEND, 8#644#);
else
Fd := Sys_Open (Sys.Out_File, O_CREAT + O_WRONLY + O_TRUNC, 8#644#);
end if;
if Fd < 0 then
Sys_Exit (254);
end if;
Result := Sys_Dup2 (Fd, STDOUT_FILENO);
Result := Sys_Close (Fd);
end;
end if;
if Stdin_Pipes (0) /= NO_FILE then
if Stdin_Pipes (0) /= STDIN_FILENO then
Result := Sys_Dup2 (Stdin_Pipes (0), STDIN_FILENO);
Result := Sys_Close (Stdin_Pipes (0));
end if;
Result := Sys_Close (Stdin_Pipes (1));
elsif Sys.In_File /= Null_Ptr then
-- Redirect the process input to a file.
declare
Fd : File_Type;
begin
Fd := Sys_Open (Sys.Out_File, O_RDONLY, 8#644#);
if Fd < 0 then
Sys_Exit (254);
end if;
Result := Sys_Dup2 (Fd, STDIN_FILENO);
Result := Sys_Close (Fd);
end;
end if;
Result := Sys_Execvp (Sys.Argv (0), Sys.Argv.all);
Sys_Exit (255);
end if;
-- Process creation failed, cleanup and raise an exception.
if Proc.Pid < 0 then
Cleanup;
raise Process_Error with "Cannot create process";
end if;
if Stdin_Pipes (1) /= NO_FILE then
Result := Sys_Close (Stdin_Pipes (0));
Proc.Input := Create_Stream (Stdin_Pipes (1)).all'Access;
end if;
if Stdout_Pipes (0) /= NO_FILE then
Result := Sys_Close (Stdout_Pipes (1));
Proc.Output := Create_Stream (Stdout_Pipes (0)).all'Access;
end if;
if Stderr_Pipes (0) /= NO_FILE then
Result := Sys_Close (Stderr_Pipes (1));
Proc.Error := Create_Stream (Stderr_Pipes (0)).all'Access;
end if;
end Spawn;
procedure Free is
new Ada.Unchecked_Deallocation (Name => Ptr_Ptr_Array, Object => Ptr_Array);
-- ------------------------------
-- Append the argument to the process argument list.
-- ------------------------------
overriding
procedure Append_Argument (Sys : in out System_Process;
Arg : in String) is
begin
if Sys.Argv = null then
Sys.Argv := new Ptr_Array (0 .. 10);
elsif Sys.Argc = Sys.Argv'Last - 1 then
declare
N : constant Ptr_Ptr_Array := new Ptr_Array (0 .. Sys.Argc + 32);
begin
N (0 .. Sys.Argc) := Sys.Argv (0 .. Sys.Argc);
Free (Sys.Argv);
Sys.Argv := N;
end;
end if;
Sys.Argv (Sys.Argc) := Interfaces.C.Strings.New_String (Arg);
Sys.Argc := Sys.Argc + 1;
Sys.Argv (Sys.Argc) := Interfaces.C.Strings.Null_Ptr;
end Append_Argument;
-- ------------------------------
-- Set the process input, output and error streams to redirect and use specified files.
-- ------------------------------
overriding
procedure Set_Streams (Sys : in out System_Process;
Input : in String;
Output : in String;
Error : in String;
Append_Output : in Boolean;
Append_Error : in Boolean) is
begin
if Input'Length > 0 then
Sys.In_File := Interfaces.C.Strings.New_String (Input);
end if;
if Output'Length > 0 then
Sys.Out_File := Interfaces.C.Strings.New_String (Output);
Sys.Out_Append := Append_Output;
end if;
if Error'Length > 0 then
Sys.Err_File := Interfaces.C.Strings.New_String (Error);
Sys.Err_Append := Append_Error;
end if;
end Set_Streams;
-- ------------------------------
-- Deletes the storage held by the system process.
-- ------------------------------
overriding
procedure Finalize (Sys : in out System_Process) is
begin
if Sys.Argv /= null then
for I in Sys.Argv'Range loop
Interfaces.C.Strings.Free (Sys.Argv (I));
end loop;
Free (Sys.Argv);
end if;
Interfaces.C.Strings.Free (Sys.In_File);
Interfaces.C.Strings.Free (Sys.Out_File);
Interfaces.C.Strings.Free (Sys.Err_File);
end Finalize;
end Util.Processes.Os;
|
Remove unecessary with clause
|
Remove unecessary with clause
|
Ada
|
apache-2.0
|
flottokarotto/ada-util,Letractively/ada-util,flottokarotto/ada-util,Letractively/ada-util
|
6f68951d74d40cf878322a387f252a06a225fec8
|
src/ado-datasets.adb
|
src/ado-datasets.adb
|
-----------------------------------------------------------------------
-- ado-datasets -- Datasets
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Objects.Time;
with ADO.Schemas;
with ADO.Statements;
package body ADO.Datasets is
-- ------------------------------
-- Execute the SQL query on the database session and populate the dataset.
-- The column names are used to setup the dataset row bean definition.
-- ------------------------------
procedure List (Into : in out Dataset;
Session : in out ADO.Sessions.Session'Class;
Query : in ADO.Queries.Context'Class) is
procedure Fill (Data : in out Util.Beans.Objects.Datasets.Object_Array);
Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query);
procedure Fill (Data : in out Util.Beans.Objects.Datasets.Object_Array) is
use ADO.Schemas;
begin
for I in Data'Range loop
case Stmt.Get_Column_Type (I - 1) is
-- Boolean column
when T_BOOLEAN =>
Data (I) := Util.Beans.Objects.To_Object (Stmt.Get_Boolean (I - 1));
when T_TINYINT | T_SMALLINT | T_INTEGER | T_LONG_INTEGER | T_YEAR =>
Data (I) := Util.Beans.Objects.To_Object (Stmt.Get_Integer (I - 1));
when T_FLOAT | T_DOUBLE | T_DECIMAL =>
Data (I) := Util.Beans.Objects.Null_Object;
when T_ENUM =>
Data (I) := Util.Beans.Objects.To_Object (Stmt.Get_String (I - 1));
when T_TIME | T_DATE | T_DATE_TIME | T_TIMESTAMP =>
Data (I) := Util.Beans.Objects.Time.To_Object (Stmt.Get_Time (I - 1));
when T_CHAR | T_VARCHAR =>
Data (I) := Util.Beans.Objects.To_Object (Stmt.Get_String (I - 1));
when T_BLOB =>
Data (I) := Util.Beans.Objects.Null_Object;
when T_SET | T_UNKNOWN | T_NULL =>
Data (I) := Util.Beans.Objects.Null_Object;
end case;
end loop;
end Fill;
begin
Stmt.Execute;
Into.Clear;
if Stmt.Has_Elements then
for I in 1 .. Stmt.Get_Column_Count loop
Into.Add_Column (Stmt.Get_Column_Name (I - 1));
end loop;
while Stmt.Has_Elements loop
Into.Append (Fill'Access);
Stmt.Next;
end loop;
end if;
end List;
end ADO.Datasets;
|
Implement the List operation to setup the database with the SQL query result
|
Implement the List operation to setup the database with the SQL query result
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
|
d6dd8e44fb730f23f4cd58c33222664e2291960d
|
src/xml/util-serialize-io-xml.adb
|
src/xml/util-serialize-io-xml.adb
|
-----------------------------------------------------------------------
-- util-serialize-io-xml -- XML Serialization Driver
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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 Unicode;
with Unicode.CES.Utf8;
with Util.Log.Loggers;
package body Util.Serialize.IO.XML is
use Util.Log;
use Sax.Readers;
use Sax.Exceptions;
use Sax.Locators;
use Sax.Attributes;
use Unicode;
use Unicode.CES;
use Ada.Strings.Unbounded;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.XML");
-- ------------------------------
-- Warning
-- ------------------------------
overriding
procedure Warning (Handler : in out Xhtml_Reader;
Except : Sax.Exceptions.Sax_Parse_Exception'Class) is
pragma Warnings (Off, Handler);
begin
Log.Warn ("{0}: {1}", To_String (Get_Locator (Except)), Get_Message (Except));
end Warning;
-- ------------------------------
-- Error
-- ------------------------------
overriding
procedure Error (Handler : in out Xhtml_Reader;
Except : in Sax.Exceptions.Sax_Parse_Exception'Class) is
pragma Warnings (Off, Handler);
begin
Log.Error ("{0}: {1}", To_String (Get_Locator (Except)), Get_Message (Except));
end Error;
-- ------------------------------
-- Fatal_Error
-- ------------------------------
overriding
procedure Fatal_Error (Handler : in out Xhtml_Reader;
Except : in Sax.Exceptions.Sax_Parse_Exception'Class) is
pragma Unreferenced (Handler);
begin
Log.Error ("{0}: {1}", To_String (Get_Locator (Except)), Get_Message (Except));
end Fatal_Error;
-- ------------------------------
-- Set_Document_Locator
-- ------------------------------
overriding
procedure Set_Document_Locator (Handler : in out Xhtml_Reader;
Loc : in out Sax.Locators.Locator) is
begin
Handler.Locator := Loc;
end Set_Document_Locator;
-- ------------------------------
-- Start_Document
-- ------------------------------
overriding
procedure Start_Document (Handler : in out Xhtml_Reader) is
begin
null;
end Start_Document;
-- ------------------------------
-- End_Document
-- ------------------------------
overriding
procedure End_Document (Handler : in out Xhtml_Reader) is
begin
null;
end End_Document;
-- ------------------------------
-- Start_Prefix_Mapping
-- ------------------------------
overriding
procedure Start_Prefix_Mapping (Handler : in out Xhtml_Reader;
Prefix : in Unicode.CES.Byte_Sequence;
URI : in Unicode.CES.Byte_Sequence) is
begin
null;
end Start_Prefix_Mapping;
-- ------------------------------
-- End_Prefix_Mapping
-- ------------------------------
overriding
procedure End_Prefix_Mapping (Handler : in out Xhtml_Reader;
Prefix : in Unicode.CES.Byte_Sequence) is
begin
null;
end End_Prefix_Mapping;
-- ------------------------------
-- Start_Element
-- ------------------------------
overriding
procedure Start_Element (Handler : in out Xhtml_Reader;
Namespace_URI : in Unicode.CES.Byte_Sequence := "";
Local_Name : in Unicode.CES.Byte_Sequence := "";
Qname : in Unicode.CES.Byte_Sequence := "";
Atts : in Sax.Attributes.Attributes'Class) is
pragma Unreferenced (Namespace_URI, Qname);
Attr_Count : Natural;
begin
-- Handler.Line.Line := Sax.Locators.Get_Line_Number (Handler.Locator);
-- Handler.Line.Column := Sax.Locators.Get_Column_Number (Handler.Locator);
Log.Debug ("Start object {0}", Local_Name);
Handler.Handler.Start_Object (Local_Name);
Attr_Count := Get_Length (Atts);
for I in 0 .. Attr_Count - 1 loop
declare
Name : constant String := Get_Qname (Atts, I);
Value : constant String := Get_Value (Atts, I);
begin
Handler.Handler.Set_Member (Name => Name,
Value => Util.Beans.Objects.To_Object (Value),
Attribute => True);
end;
end loop;
end Start_Element;
-- ------------------------------
-- End_Element
-- ------------------------------
overriding
procedure End_Element (Handler : in out Xhtml_Reader;
Namespace_URI : in Unicode.CES.Byte_Sequence := "";
Local_Name : in Unicode.CES.Byte_Sequence := "";
Qname : in Unicode.CES.Byte_Sequence := "") is
pragma Unreferenced (Namespace_URI, Qname);
begin
Handler.Handler.Finish_Object (Local_Name);
if Length (Handler.Text) > 0 then
Log.Debug ("Close object {0} -> {1}", Local_Name, To_String (Handler.Text));
Handler.Handler.Set_Member (Local_Name, Util.Beans.Objects.To_Object (Handler.Text));
Set_Unbounded_String (Handler.Text, "");
else
Log.Debug ("Close object {0}", Local_Name);
end if;
end End_Element;
procedure Collect_Text (Handler : in out Xhtml_Reader;
Content : Unicode.CES.Byte_Sequence) is
begin
Append (Handler.Text, Content);
end Collect_Text;
-- ------------------------------
-- Characters
-- ------------------------------
overriding
procedure Characters (Handler : in out Xhtml_Reader;
Ch : in Unicode.CES.Byte_Sequence) is
begin
Collect_Text (Handler, Ch);
end Characters;
-- ------------------------------
-- Ignorable_Whitespace
-- ------------------------------
overriding
procedure Ignorable_Whitespace (Handler : in out Xhtml_Reader;
Ch : in Unicode.CES.Byte_Sequence) is
begin
if not Handler.Ignore_White_Spaces then
Collect_Text (Handler, Ch);
end if;
end Ignorable_Whitespace;
-- ------------------------------
-- Processing_Instruction
-- ------------------------------
overriding
procedure Processing_Instruction (Handler : in out Xhtml_Reader;
Target : in Unicode.CES.Byte_Sequence;
Data : in Unicode.CES.Byte_Sequence) is
pragma Unreferenced (Handler);
begin
Log.Error ("Processing instruction: {0}: {1}", Target, Data);
end Processing_Instruction;
-- ------------------------------
-- Skipped_Entity
-- ------------------------------
overriding
procedure Skipped_Entity (Handler : in out Xhtml_Reader;
Name : in Unicode.CES.Byte_Sequence) is
pragma Unmodified (Handler);
begin
null;
end Skipped_Entity;
-- ------------------------------
-- Start_Cdata
-- ------------------------------
overriding
procedure Start_Cdata (Handler : in out Xhtml_Reader) is
pragma Unmodified (Handler);
begin
Log.Info ("Start CDATA");
end Start_Cdata;
-- ------------------------------
-- End_Cdata
-- ------------------------------
overriding
procedure End_Cdata (Handler : in out Xhtml_Reader) is
pragma Unmodified (Handler);
begin
Log.Info ("End CDATA");
end End_Cdata;
-- ------------------------------
-- Resolve_Entity
-- ------------------------------
overriding
function Resolve_Entity (Handler : Xhtml_Reader;
Public_Id : Unicode.CES.Byte_Sequence;
System_Id : Unicode.CES.Byte_Sequence)
return Input_Sources.Input_Source_Access is
pragma Unreferenced (Handler);
begin
Log.Error ("Cannot resolve entity {0} - {1}", Public_Id, System_Id);
return null;
end Resolve_Entity;
overriding
procedure Start_DTD (Handler : in out Xhtml_Reader;
Name : Unicode.CES.Byte_Sequence;
Public_Id : Unicode.CES.Byte_Sequence := "";
System_Id : Unicode.CES.Byte_Sequence := "") is
begin
null;
end Start_DTD;
-- ------------------------------
-- Set the XHTML reader to ignore or not the white spaces.
-- When set to True, the ignorable white spaces will not be kept.
-- ------------------------------
procedure Set_Ignore_White_Spaces (Reader : in out Parser;
Value : in Boolean) is
begin
Reader.Ignore_White_Spaces := Value;
end Set_Ignore_White_Spaces;
-- ------------------------------
-- Set the XHTML reader to ignore empty lines.
-- ------------------------------
procedure Set_Ignore_Empty_Lines (Reader : in out Parser;
Value : in Boolean) is
begin
Reader.Ignore_Empty_Lines := Value;
end Set_Ignore_Empty_Lines;
-- ------------------------------
-- Parse an XML stream, and calls the appropriate SAX callbacks for each
-- event.
-- This is not re-entrant: you can not call Parse with the same Parser
-- argument in one of the SAX callbacks. This has undefined behavior.
-- ------------------------------
-- Parse the stream using the JSON parser.
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class) is
type String_Access is access all String (1 .. 32);
type Stream_Input is new Input_Sources.Input_Source with record
Index : Natural;
Last : Natural;
Encoding : Unicode.CES.Encoding_Scheme;
Buffer : String_Access;
end record;
-- Return the next character in the string.
procedure Next_Char (From : in out Stream_Input;
C : out Unicode.Unicode_Char);
-- True if From is past the last character in the string.
function Eof (From : in Stream_Input) return Boolean;
procedure Fill (From : in out Stream_Input'Class);
procedure Fill (From : in out Stream_Input'Class) is
begin
-- Move to the buffer start
if From.Last > From.Index and From.Index > From.Buffer'First then
From.Buffer (From.Buffer'First .. From.Last - 1 - From.Index + From.Buffer'First) :=
From.Buffer (From.Index .. From.Last - 1);
From.Last := From.Last - From.Index + From.Buffer'First;
From.Index := From.Buffer'First;
end if;
if From.Index > From.Last then
From.Index := From.Buffer'First;
end if;
begin
loop
Stream.Read (From.Buffer (From.Last));
From.Last := From.Last + 1;
exit when From.Last > From.Buffer'Last;
end loop;
exception
when others =>
null;
end;
end Fill;
-- Return the next character in the string.
procedure Next_Char (From : in out Stream_Input;
C : out Unicode.Unicode_Char) is
begin
if From.Index + 6 >= From.Last then
Fill (From);
end if;
From.Encoding.Read (From.Buffer.all, From.Index, C);
end Next_Char;
-- True if From is past the last character in the string.
function Eof (From : in Stream_Input) return Boolean is
begin
if From.Index < From.Last then
return False;
end if;
return Stream.Is_Eof;
end Eof;
Input : Stream_Input;
Xml_Parser : Xhtml_Reader;
Buf : aliased String (1 .. 32);
begin
Input.Buffer := Buf'Access;
Input.Index := 2;
Input.Last := 1;
Input.Set_Encoding (Unicode.CES.Utf8.Utf8_Encoding);
Input.Encoding := Unicode.CES.Utf8.Utf8_Encoding;
Xml_Parser.Handler := Handler'Unchecked_Access;
Xml_Parser.Ignore_White_Spaces := Handler.Ignore_White_Spaces;
Xml_Parser.Ignore_Empty_Lines := Handler.Ignore_Empty_Lines;
Sax.Readers.Reader (Xml_Parser).Parse (Input);
end Parse;
-- Close the current XML entity if an entity was started
procedure Close_Current (Stream : in out Output_Stream'Class);
-- ------------------------------
-- Close the current XML entity if an entity was started
-- ------------------------------
procedure Close_Current (Stream : in out Output_Stream'Class) is
begin
if Stream.Close_Start then
Stream.Write ('>');
Stream.Close_Start := False;
end if;
end Close_Current;
-- ------------------------------
-- Write the value as a XML string. Special characters are escaped using the XML
-- escape rules.
-- ------------------------------
procedure Write_String (Stream : in out Output_Stream;
Value : in String) is
begin
Close_Current (Stream);
Stream.Write (Value);
end Write_String;
-- ------------------------------
-- Start a new XML object.
-- ------------------------------
procedure Start_Entity (Stream : in out Output_Stream;
Name : in String) is
begin
Close_Current (Stream);
Stream.Close_Start := True;
Stream.Write ('<');
Stream.Write (Name);
end Start_Entity;
-- ------------------------------
-- Terminates the current XML object.
-- ------------------------------
procedure End_Entity (Stream : in out Output_Stream;
Name : in String) is
begin
Close_Current (Stream);
Stream.Write ("</");
Stream.Write (Name);
Stream.Write ('>');
end End_Entity;
-- ------------------------------
-- Write a XML name/value attribute.
-- ------------------------------
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
Stream.Write (' ');
Stream.Write (Name);
Stream.Write ("=""");
case Util.Beans.Objects.Get_Type (Value) is
when TYPE_NULL =>
null;
when TYPE_BOOLEAN =>
if Util.Beans.Objects.To_Boolean (Value) then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
when TYPE_INTEGER =>
Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value));
when others =>
Stream.Write_String (Util.Beans.Objects.To_String (Value));
end case;
Stream.Write ('"');
end Write_Attribute;
-- ------------------------------
-- Write a XML name/value entity (see Write_Attribute).
-- ------------------------------
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
Close_Current (Stream);
Stream.Write ('<');
Stream.Write (Name);
Stream.Write ('>');
case Util.Beans.Objects.Get_Type (Value) is
when TYPE_NULL =>
null;
when TYPE_BOOLEAN =>
if Util.Beans.Objects.To_Boolean (Value) then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
when TYPE_INTEGER =>
Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value));
when others =>
Stream.Write_String (Util.Beans.Objects.To_String (Value));
end case;
Stream.Write ("</");
Stream.Write (Name);
Stream.Write ('>');
end Write_Entity;
-- ------------------------------
-- Starts a XML array.
-- ------------------------------
procedure Start_Array (Stream : in out Output_Stream;
Length : in Ada.Containers.Count_Type) is
begin
null;
end Start_Array;
-- ------------------------------
-- Terminates a XML array.
-- ------------------------------
procedure End_Array (Stream : in out Output_Stream) is
begin
null;
end End_Array;
end Util.Serialize.IO.XML;
|
-----------------------------------------------------------------------
-- util-serialize-io-xml -- XML Serialization Driver
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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 Unicode;
with Unicode.CES.Utf8;
with Util.Log.Loggers;
package body Util.Serialize.IO.XML is
use Util.Log;
use Sax.Readers;
use Sax.Exceptions;
use Sax.Locators;
use Sax.Attributes;
use Unicode;
use Unicode.CES;
use Ada.Strings.Unbounded;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.XML");
-- ------------------------------
-- Warning
-- ------------------------------
overriding
procedure Warning (Handler : in out Xhtml_Reader;
Except : Sax.Exceptions.Sax_Parse_Exception'Class) is
pragma Warnings (Off, Handler);
begin
Log.Warn ("{0}: {1}", To_String (Get_Locator (Except)), Get_Message (Except));
end Warning;
-- ------------------------------
-- Error
-- ------------------------------
overriding
procedure Error (Handler : in out Xhtml_Reader;
Except : in Sax.Exceptions.Sax_Parse_Exception'Class) is
pragma Warnings (Off, Handler);
begin
Log.Error ("{0}: {1}", To_String (Get_Locator (Except)), Get_Message (Except));
end Error;
-- ------------------------------
-- Fatal_Error
-- ------------------------------
overriding
procedure Fatal_Error (Handler : in out Xhtml_Reader;
Except : in Sax.Exceptions.Sax_Parse_Exception'Class) is
pragma Unreferenced (Handler);
begin
Log.Error ("{0}: {1}", To_String (Get_Locator (Except)), Get_Message (Except));
end Fatal_Error;
-- ------------------------------
-- Set_Document_Locator
-- ------------------------------
overriding
procedure Set_Document_Locator (Handler : in out Xhtml_Reader;
Loc : in out Sax.Locators.Locator) is
begin
Handler.Locator := Loc;
end Set_Document_Locator;
-- ------------------------------
-- Start_Document
-- ------------------------------
overriding
procedure Start_Document (Handler : in out Xhtml_Reader) is
begin
null;
end Start_Document;
-- ------------------------------
-- End_Document
-- ------------------------------
overriding
procedure End_Document (Handler : in out Xhtml_Reader) is
begin
null;
end End_Document;
-- ------------------------------
-- Start_Prefix_Mapping
-- ------------------------------
overriding
procedure Start_Prefix_Mapping (Handler : in out Xhtml_Reader;
Prefix : in Unicode.CES.Byte_Sequence;
URI : in Unicode.CES.Byte_Sequence) is
begin
null;
end Start_Prefix_Mapping;
-- ------------------------------
-- End_Prefix_Mapping
-- ------------------------------
overriding
procedure End_Prefix_Mapping (Handler : in out Xhtml_Reader;
Prefix : in Unicode.CES.Byte_Sequence) is
begin
null;
end End_Prefix_Mapping;
-- ------------------------------
-- Start_Element
-- ------------------------------
overriding
procedure Start_Element (Handler : in out Xhtml_Reader;
Namespace_URI : in Unicode.CES.Byte_Sequence := "";
Local_Name : in Unicode.CES.Byte_Sequence := "";
Qname : in Unicode.CES.Byte_Sequence := "";
Atts : in Sax.Attributes.Attributes'Class) is
pragma Unreferenced (Namespace_URI, Qname);
Attr_Count : Natural;
begin
-- Handler.Line.Line := Sax.Locators.Get_Line_Number (Handler.Locator);
-- Handler.Line.Column := Sax.Locators.Get_Column_Number (Handler.Locator);
Log.Debug ("Start object {0}", Local_Name);
Handler.Handler.Start_Object (Local_Name);
Attr_Count := Get_Length (Atts);
for I in 0 .. Attr_Count - 1 loop
declare
Name : constant String := Get_Qname (Atts, I);
Value : constant String := Get_Value (Atts, I);
begin
Handler.Handler.Set_Member (Name => Name,
Value => Util.Beans.Objects.To_Object (Value),
Attribute => True);
end;
end loop;
end Start_Element;
-- ------------------------------
-- End_Element
-- ------------------------------
overriding
procedure End_Element (Handler : in out Xhtml_Reader;
Namespace_URI : in Unicode.CES.Byte_Sequence := "";
Local_Name : in Unicode.CES.Byte_Sequence := "";
Qname : in Unicode.CES.Byte_Sequence := "") is
pragma Unreferenced (Namespace_URI, Qname);
begin
Handler.Handler.Finish_Object (Local_Name);
if Length (Handler.Text) > 0 then
Log.Debug ("Close object {0} -> {1}", Local_Name, To_String (Handler.Text));
Handler.Handler.Set_Member (Local_Name, Util.Beans.Objects.To_Object (Handler.Text));
Set_Unbounded_String (Handler.Text, "");
else
Log.Debug ("Close object {0}", Local_Name);
end if;
end End_Element;
procedure Collect_Text (Handler : in out Xhtml_Reader;
Content : Unicode.CES.Byte_Sequence) is
begin
Append (Handler.Text, Content);
end Collect_Text;
-- ------------------------------
-- Characters
-- ------------------------------
overriding
procedure Characters (Handler : in out Xhtml_Reader;
Ch : in Unicode.CES.Byte_Sequence) is
begin
Collect_Text (Handler, Ch);
end Characters;
-- ------------------------------
-- Ignorable_Whitespace
-- ------------------------------
overriding
procedure Ignorable_Whitespace (Handler : in out Xhtml_Reader;
Ch : in Unicode.CES.Byte_Sequence) is
begin
if not Handler.Ignore_White_Spaces then
Collect_Text (Handler, Ch);
end if;
end Ignorable_Whitespace;
-- ------------------------------
-- Processing_Instruction
-- ------------------------------
overriding
procedure Processing_Instruction (Handler : in out Xhtml_Reader;
Target : in Unicode.CES.Byte_Sequence;
Data : in Unicode.CES.Byte_Sequence) is
pragma Unreferenced (Handler);
begin
Log.Error ("Processing instruction: {0}: {1}", Target, Data);
end Processing_Instruction;
-- ------------------------------
-- Skipped_Entity
-- ------------------------------
overriding
procedure Skipped_Entity (Handler : in out Xhtml_Reader;
Name : in Unicode.CES.Byte_Sequence) is
pragma Unmodified (Handler);
begin
null;
end Skipped_Entity;
-- ------------------------------
-- Start_Cdata
-- ------------------------------
overriding
procedure Start_Cdata (Handler : in out Xhtml_Reader) is
pragma Unmodified (Handler);
begin
Log.Info ("Start CDATA");
end Start_Cdata;
-- ------------------------------
-- End_Cdata
-- ------------------------------
overriding
procedure End_Cdata (Handler : in out Xhtml_Reader) is
pragma Unmodified (Handler);
begin
Log.Info ("End CDATA");
end End_Cdata;
-- ------------------------------
-- Resolve_Entity
-- ------------------------------
overriding
function Resolve_Entity (Handler : Xhtml_Reader;
Public_Id : Unicode.CES.Byte_Sequence;
System_Id : Unicode.CES.Byte_Sequence)
return Input_Sources.Input_Source_Access is
pragma Unreferenced (Handler);
begin
Log.Error ("Cannot resolve entity {0} - {1}", Public_Id, System_Id);
return null;
end Resolve_Entity;
overriding
procedure Start_DTD (Handler : in out Xhtml_Reader;
Name : Unicode.CES.Byte_Sequence;
Public_Id : Unicode.CES.Byte_Sequence := "";
System_Id : Unicode.CES.Byte_Sequence := "") is
begin
null;
end Start_DTD;
-- ------------------------------
-- Set the XHTML reader to ignore or not the white spaces.
-- When set to True, the ignorable white spaces will not be kept.
-- ------------------------------
procedure Set_Ignore_White_Spaces (Reader : in out Parser;
Value : in Boolean) is
begin
Reader.Ignore_White_Spaces := Value;
end Set_Ignore_White_Spaces;
-- ------------------------------
-- Set the XHTML reader to ignore empty lines.
-- ------------------------------
procedure Set_Ignore_Empty_Lines (Reader : in out Parser;
Value : in Boolean) is
begin
Reader.Ignore_Empty_Lines := Value;
end Set_Ignore_Empty_Lines;
-- ------------------------------
-- Parse an XML stream, and calls the appropriate SAX callbacks for each
-- event.
-- This is not re-entrant: you can not call Parse with the same Parser
-- argument in one of the SAX callbacks. This has undefined behavior.
-- ------------------------------
-- Parse the stream using the JSON parser.
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class) is
type String_Access is access all String (1 .. 32);
type Stream_Input is new Input_Sources.Input_Source with record
Index : Natural;
Last : Natural;
Encoding : Unicode.CES.Encoding_Scheme;
Buffer : String_Access;
end record;
-- Return the next character in the string.
procedure Next_Char (From : in out Stream_Input;
C : out Unicode.Unicode_Char);
-- True if From is past the last character in the string.
function Eof (From : in Stream_Input) return Boolean;
procedure Fill (From : in out Stream_Input'Class);
procedure Fill (From : in out Stream_Input'Class) is
begin
-- Move to the buffer start
if From.Last > From.Index and From.Index > From.Buffer'First then
From.Buffer (From.Buffer'First .. From.Last - 1 - From.Index + From.Buffer'First) :=
From.Buffer (From.Index .. From.Last - 1);
From.Last := From.Last - From.Index + From.Buffer'First;
From.Index := From.Buffer'First;
end if;
if From.Index > From.Last then
From.Index := From.Buffer'First;
end if;
begin
loop
Stream.Read (From.Buffer (From.Last));
From.Last := From.Last + 1;
exit when From.Last > From.Buffer'Last;
end loop;
exception
when others =>
null;
end;
end Fill;
-- Return the next character in the string.
procedure Next_Char (From : in out Stream_Input;
C : out Unicode.Unicode_Char) is
begin
if From.Index + 6 >= From.Last then
Fill (From);
end if;
From.Encoding.Read (From.Buffer.all, From.Index, C);
end Next_Char;
-- True if From is past the last character in the string.
function Eof (From : in Stream_Input) return Boolean is
begin
if From.Index < From.Last then
return False;
end if;
return Stream.Is_Eof;
end Eof;
Input : Stream_Input;
Xml_Parser : Xhtml_Reader;
Buf : aliased String (1 .. 32);
begin
Input.Buffer := Buf'Access;
Input.Index := 2;
Input.Last := 1;
Input.Set_Encoding (Unicode.CES.Utf8.Utf8_Encoding);
Input.Encoding := Unicode.CES.Utf8.Utf8_Encoding;
Xml_Parser.Handler := Handler'Unchecked_Access;
Xml_Parser.Ignore_White_Spaces := Handler.Ignore_White_Spaces;
Xml_Parser.Ignore_Empty_Lines := Handler.Ignore_Empty_Lines;
Sax.Readers.Reader (Xml_Parser).Parse (Input);
end Parse;
-- Close the current XML entity if an entity was started
procedure Close_Current (Stream : in out Output_Stream'Class);
-- ------------------------------
-- Close the current XML entity if an entity was started
-- ------------------------------
procedure Close_Current (Stream : in out Output_Stream'Class) is
begin
if Stream.Close_Start then
Stream.Write ('>');
Stream.Close_Start := False;
end if;
end Close_Current;
-- ------------------------------
-- Write the value as a XML string. Special characters are escaped using the XML
-- escape rules.
-- ------------------------------
procedure Write_String (Stream : in out Output_Stream;
Value : in String) is
begin
Close_Current (Stream);
Stream.Write (Value);
end Write_String;
-- ------------------------------
-- Start a new XML object.
-- ------------------------------
procedure Start_Entity (Stream : in out Output_Stream;
Name : in String) is
begin
Close_Current (Stream);
Stream.Close_Start := True;
Stream.Write ('<');
Stream.Write (Name);
end Start_Entity;
-- ------------------------------
-- Terminates the current XML object.
-- ------------------------------
procedure End_Entity (Stream : in out Output_Stream;
Name : in String) is
begin
Close_Current (Stream);
Stream.Write ("</");
Stream.Write (Name);
Stream.Write ('>');
end End_Entity;
-- ------------------------------
-- Write a XML name/value attribute.
-- ------------------------------
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
Stream.Write (' ');
Stream.Write (Name);
Stream.Write ("=""");
case Util.Beans.Objects.Get_Type (Value) is
when TYPE_NULL =>
null;
when TYPE_BOOLEAN =>
if Util.Beans.Objects.To_Boolean (Value) then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
when TYPE_INTEGER =>
Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value));
when others =>
Stream.Write (Util.Beans.Objects.To_String (Value));
end case;
Stream.Write ('"');
end Write_Attribute;
-- ------------------------------
-- Write a XML name/value entity (see Write_Attribute).
-- ------------------------------
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
Close_Current (Stream);
Stream.Write ('<');
Stream.Write (Name);
Stream.Write ('>');
case Util.Beans.Objects.Get_Type (Value) is
when TYPE_NULL =>
null;
when TYPE_BOOLEAN =>
if Util.Beans.Objects.To_Boolean (Value) then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
when TYPE_INTEGER =>
Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value));
when others =>
Stream.Write_String (Util.Beans.Objects.To_String (Value));
end case;
Stream.Write ("</");
Stream.Write (Name);
Stream.Write ('>');
end Write_Entity;
-- ------------------------------
-- Starts a XML array.
-- ------------------------------
procedure Start_Array (Stream : in out Output_Stream;
Length : in Ada.Containers.Count_Type) is
begin
null;
end Start_Array;
-- ------------------------------
-- Terminates a XML array.
-- ------------------------------
procedure End_Array (Stream : in out Output_Stream) is
begin
null;
end End_Array;
end Util.Serialize.IO.XML;
|
Use Stream.Write instead of Stream.Write_String to write the attribute value (otherwise we can close the current entity by writing the '>')
|
Use Stream.Write instead of Stream.Write_String to write the attribute value
(otherwise we can close the current entity by writing the '>')
|
Ada
|
apache-2.0
|
Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util
|
acb5908775e0ec0c3c897b1f0296d55c3db9f8ff
|
testutil/aunit/util-test_caller.adb
|
testutil/aunit/util-test_caller.adb
|
-----------------------------------------------------------------------
-- AUnit utils - Helper for writing unit tests
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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.
-----------------------------------------------------------------------
package body Util.Test_Caller is
procedure Add_Test (Suite : in Util.Tests.Access_Test_Suite;
Test_Name : in String;
Method : in Caller.Test_Method) is
begin
Suite.Add_Test (Caller.Create (Test_Name, Method));
end Add_Test;
end Util.Test_Caller;
|
-----------------------------------------------------------------------
-- AUnit utils - Helper for writing unit tests
-- Copyright (C) 2009, 2010, 2011, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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.
-----------------------------------------------------------------------
package body Util.Test_Caller is
procedure Add_Test (Suite : in Util.Tests.Access_Test_Suite;
Test_Name : in String;
Method : in Caller.Test_Method) is
begin
if Util.Tests.Is_Test_Enabled (Test_Name) then
Suite.Add_Test (Caller.Create (Test_Name, Method));
end if;
end Add_Test;
end Util.Test_Caller;
|
Use the Is_Test_Enabled function to ignore or take into account the test when it is added in the testsuite.
|
Use the Is_Test_Enabled function to ignore or take into account the
test when it is added in the testsuite.
|
Ada
|
apache-2.0
|
Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util
|
e073bb53b1f3e227034530d77aeafd10465981bd
|
src/asis/a4g-dda_aux.ads
|
src/asis/a4g-dda_aux.ads
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- A 4 G . D D A _ A U X --
-- --
-- S p e c --
-- --
-- $Revision: 14154 $
-- --
-- Copyright (C) 1999-2001 Ada Core Technologies, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, --
-- MA 02111-1307, USA. --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- It is now maintained by Ada Core Technologies Inc (http://www.gnat.com). --
-- --
------------------------------------------------------------------------------
-- This package contains auxiliary routines used to support the data
-- decomposition annex. At the level of this package, types and components
-- are represented by their normal Entity_Id values. The corresponding
-- entities have the necessary representation information stored in them.
-- DDA_Aux acts as an interface between the main ASIS routines and all
-- representation issues.
with Asis.Data_Decomposition;
with Repinfo; use Repinfo;
with Types; use Types;
with Uintp; use Uintp;
package A4G.DDA_Aux is
--------------------------------
-- Portable_Data Declarations --
--------------------------------
-- Asis.Data_Decomposition.Portable_Value;
-- Portable values are simply bytes, i.e. defined as mod 256. This is
-- fine for all the byte addressable architectures that GNAT runs on
-- now, and we will worry later about exotic cases (which may well
-- never arise).
-- Portable_Positive is Asis.Data_Decomposition.Portable_Positive;
-- This is simply a synonym for Asis.ASIS_Positive
-- Asis.Data_Decomposition.Portable_Data;
-- This is array (Portable_Positive range <>) of Portable_Data. Thus
-- it is simply an array of bytes. The representation of data in this
-- format is as follows:
--
-- For non-scalar values, the data value is stored at the start of
-- the value, occupying as many bits as needed. If there are padding
-- bits (on the right), they are stored as zero bits when a value is
-- retrieved, and ignored when a value is stored.
--
-- For scalar values, the data value is of length 1, 2, 4, or 8 bytes
-- in proper little-endian or big-endian format with sign or zero
-- bits filling the unused high order bits. For enumeration values,
-- this is the Enum_Rep value, i.e. the actual stored value, not the
-- Pos value. For biased types, the value is unsigned and biased.
---------------------------------
-- Basic Interface Definiitons --
---------------------------------
Variable_Rep_Info : exception;
-- This exception is raised if an attempt is made to access representation
-- information that depends on the value of a variable other than a
-- discriminant for the current record. For example, if the length of
-- a component of subtype String (1 .. N) is requested, and N is not a
-- discriminant or a static constant.
Invalid_Data : exception;
-- Exception raised if an invalid data value is detected. There is no
-- systematic checking for invalid values, but there are some situations
-- in which bad values are detected, and this exception is raised.
No_Component : exception;
-- Exception raised if a request is made to access a component in a
-- variant part of a record when the component does not exist for the
-- particular set of discriminant values present. Also raised if a
-- request is made to access an out of bounds subscript value for an
-- array element.
Null_Discrims : Repinfo.Discrim_List (1 .. 0) := (others => Uint_0);
-- Used as default if no discriminants given
----------------------
-- Utility Routines --
----------------------
function Build_Discrim_List
(Rec : Entity_Id;
Data : Asis.Data_Decomposition.Portable_Data)
return Repinfo.Discrim_List;
-- Given a record entity, and a value of this record type, builds a
-- list of discriminants from the given value and returns it. The
-- portable data value must include at least all the discriminants
-- if the type is for a discriminated record. If Rec is other than
-- a discriminated record type, then Data is ignored and Null_Discrims
-- is returned.
function Eval_Scalar_Node
(N : Node_Id;
Discs : Repinfo.Discrim_List := Null_Discrims)
return Uint;
-- This function is used to get the value of a node representing a value
-- of a scalar type. Evaluation is possible for static expressions and
-- for discriminant values (in the latter case, Discs must be provided
-- and must contain the appropriate list of discriminants). Note that
-- in the case of enumeration values, the result is the Pos value, not
-- the Enum_Rep value for the given enumeration literal.
--
-- Raises Variable_Rep_Info is raised if the expression is other than
-- a discriminant or a static expression, or if it is a discriminant
-- and no discriminant list is provided.
--
-- Note that this functionality is related to that provided by
-- Sem_Eval.Expr_Value, but this unit is not available in ASIS.
function Linear_Index
(Typ : Entity_Id;
Subs : Asis.Data_Decomposition.Dimension_Indexes;
Discs : Repinfo.Discrim_List := Null_Discrims)
return Asis.ASIS_Natural;
-- Given Typ, the entity for a definite array type or subtype, and Subs,
-- a list of 1's origin subscripts (that is, as usual Dimension_Indexes
-- has subscripts that are 1's origin with respect to the declared lower
-- bound), this routine computes the corresponding zero-origin linear
-- index from the start of the array data. The case of Fortran convention
-- (with row major order) is properly handled.
--
-- Raises No_Component if any of the subscripts is out of range (i.e.
-- exceeds the length of the corresponding subscript position).
function UI_From_Aint (A : Asis.ASIS_Integer) return Uint;
-- Converts ASIS_Integer value to Uint
function UI_Is_In_Aint_Range (U : Uint) return Boolean;
-- Determine if a universal integer value U is in range of ASIS_Integer.
-- Returns True iff in range (meaning that UI_To_Aint can be safely used).
function UI_To_Aint (U : Uint) return Asis.ASIS_Integer;
-- Converts Uint value to ASIS_Integer, the result must be in range
-- of ASIS_Integer, or otherwise the exception Invalid_Data is raised.
--------------------------------
-- Universal Integer Encoding --
--------------------------------
-- These routines deal with decoding and encoding scalar values from
-- Uint to portable data format.
function Encode_Scalar_Value
(Typ : Entity_Id;
Val : Uint)
return Asis.Data_Decomposition.Portable_Data;
-- Given Typ, the entity for a scalar type or subtype, this function
-- constructs a portable data valuethat represents a value of this
-- type given by Val. The value of the Uint may not exceed the largest
-- scalar value supported by the implementation. The result will be 1,
-- 2, 4 or 8 bytes long depending on the value of the input, positioned
-- to be intepreted as an integer, and sign or zero extended as needed.
-- For enumeration types, the value is the Enum_Rep value, not the Pos
-- value. For biased types, the bias is NOT present in the Uint value
-- (part of the job of Encode_Scalar_Value is to introduce the bias).
--
-- Raises Invalid_Data if value is out of range of the base type of Typ
function Encode_Scalar_Value
(Typ : Entity_Id;
Val : Asis.ASIS_Integer)
return Asis.Data_Decomposition.Portable_Data;
-- Similar to above function except input is ASIS_Integer instead of Uint
function Decode_Scalar_Value
(Typ : Entity_Id;
Data : Asis.Data_Decomposition.Portable_Data)
return Uint;
-- Given Typ, the entity for a scalar type or subtype, this function
-- takes the portable data value Data, that represents a value of
-- this type, and returns the equivalent Uint value. For enumeration
-- types the value is the Enum_Rep value, not the Pos value. For biased
-- types, the result is unbiased (part of the job of Decode_Scalar_Value
-- is to remove the bias).
--------------------------------
-- Record Discriminant Access --
--------------------------------
function Extract_Discriminant
(Data : Asis.Data_Decomposition.Portable_Data;
Disc : Entity_Id)
return Uint;
-- This function can be used to extract a discriminant value from a
-- record. Data is the portable data value representing the record
-- value, and Disc is the E_Discriminant entity for the discriminant.
function Set_Discriminant
(Data : Asis.Data_Decomposition.Portable_Data;
Disc : Entity_Id;
Val : Uint)
return Asis.Data_Decomposition.Portable_Data;
-- Given Data, a portable data value representing the prefix of a record
-- value which may already have some other discriminant values set, this
-- function creates a new Portable_Data value, increased in length
-- if necessary, in which the discriminant represented by E_Discriminant
-- entity Disc is set to the given value.
--
-- Raises Invalid_Data if the value does not fit in the field
procedure Set_Discriminant
(Data : in out Asis.Data_Decomposition.Portable_Data;
Disc : Entity_Id;
Val : Uint);
-- Similar to the function above, except that the modification is done
-- in place on the given portable data value. In this case, the Data
-- value must be long enough to contain the given discriminant field.
function Set_Discriminant
(Data : Asis.Data_Decomposition.Portable_Data;
Disc : Entity_Id;
Val : Asis.ASIS_Integer)
return Asis.Data_Decomposition.Portable_Data;
-- Similar to function above, but takes argument in ASIS_Integer form
procedure Set_Discriminant
(Data : in out Asis.Data_Decomposition.Portable_Data;
Disc : Entity_Id;
Val : Asis.ASIS_Integer);
-- Similar to function above, but takes argument in ASIS_Integer form
-----------------------------
-- Record Component Access --
-----------------------------
function Component_Present
(Comp : Entity_Id;
Discs : Repinfo.Discrim_List)
return Boolean;
-- Determines if the given component is present or not. For the case
-- where the component is part of a variant of a discriminated record,
-- Discs must contain the full list of discriminants for the record,
-- and the result is True or False depending on whether the variant
-- containing the field is present or not for the given discriminant
-- values. If the component is not part of a variant, including the
-- case where the record is non-discriminated, then Discs is ignored
-- and the result is always True.
function Extract_Record_Component
(Data : Asis.Data_Decomposition.Portable_Data;
Comp : Entity_Id;
Discs : Repinfo.Discrim_List := Null_Discrims)
return Asis.Data_Decomposition.Portable_Data;
-- Given Data, a portable data value representing a record value, this
-- routine extracts the component value corresponding to E_Component
-- entity Comp, and returns a new portable data value corresponding to
-- this component. The Discs parameter supplies the discriminants and
-- must be present in the discriminated record case if the component
-- may depend on discriminants. For scalar types, the result value
-- is 1,2,4, or 8 bytes, properly positioned to be interpreted as an
-- integer, and sign/zero extended as required. For all other types,
-- the value is extended if necessary to be an integral number of
-- bytes by adding zero bits.
--
-- Raises No_Component if an attempt is made to set a component in a
-- non-existent variant.
--
-- Raises No_Component if the specified component is part of a variant
-- that does not exist for the given discriminant values
--
-- Raises Variable_Rep_Info if the size or position of the component
-- depends on a variable other than a discriminant
function Set_Record_Component
(Data : Asis.Data_Decomposition.Portable_Data;
Comp : Entity_Id;
Val : Asis.Data_Decomposition.Portable_Data;
Discs : Repinfo.Discrim_List := Null_Discrims)
return Asis.Data_Decomposition.Portable_Data;
-- Given Data, a portable data value that represents a record value,
-- or a prefix of such a record, sets the component represented by the
-- E_Component entity Comp is set to the value represented by the portable
-- data value Val, and the result is returned as a portable data value,
-- extended in length if necessary to accomodate the newly added entry.
-- The Discs parameter supplies the discriminants and must be present
-- in the discriminated record case if the component may depend on
-- the values of discriminants.
--
-- Raises No_Component if an attempt is made to set a component in a
-- non-existent variant.
--
-- Raises No_Component if the specified component is part of a variant
-- that does not exist for the given discriminant values
--
-- Raises Variable_Rep_Info if the size or position of the component
-- depends on a variable other than a discriminant
--
-- Raises Invalid_Data if the data value is too large to fit.
procedure Set_Record_Component
(Data : in out Asis.Data_Decomposition.Portable_Data;
Comp : Entity_Id;
Val : Asis.Data_Decomposition.Portable_Data;
Discs : Repinfo.Discrim_List := Null_Discrims);
-- Same as the above, but operates in place on the given data value,
-- which must in this case be long enough to contain the component.
----------------------------
-- Array Component Access --
----------------------------
function Extract_Array_Component
(Typ : Entity_Id;
Data : Asis.Data_Decomposition.Portable_Data;
Subs : Asis.Data_Decomposition.Dimension_Indexes;
Discs : Repinfo.Discrim_List := Null_Discrims)
return Asis.Data_Decomposition.Portable_Data;
-- Given Typ, the entity for an array type, and Data, a portable data
-- value representing a value of this array type, this function extracts
-- the array element corresponding to the given list of subscript values.
-- The parameter Discs must be given if any of the bounds of the array
-- may depend on discriminant values, and supplies the corresponding
-- discriminants. For scalar component types, the value is 1,2,4, or 8,
-- properly positioned to be interpreted as an integer, and sign/zero
-- extended as required. For all other types, the value is extended if
-- necessary to be an integral number of bytes by adding zero bits.
--
-- Raises No_Component if any of the subscripts is out of bounds
-- (that is, exceeds the length of the corresponding index).
--
-- Raises Variable_Rep_Info if length of any index depends on a
-- variable other than a discriminant.
--
function Set_Array_Component
(Typ : Entity_Id;
Data : Asis.Data_Decomposition.Portable_Data;
Subs : Asis.Data_Decomposition.Dimension_Indexes;
Val : Asis.Data_Decomposition.Portable_Data;
Discs : Repinfo.Discrim_List := Null_Discrims)
return Asis.Data_Decomposition.Portable_Data;
-- Given a portable data value representing either a value of the array
-- type Typ, or a prefix of such a value, sets the element referenced by
-- the given subscript values in Subs, to the given value Val. The
-- parameter Discs must be given if any of the bounds of the array
-- may depend on discriminant values, and supplies the corresponding
-- discriminants. The returned result is the original portable data
-- value, extended if necessary to include the new element, with the
-- new element value in place.
--
-- Raises No_Component if any of the subscripts is out of bounds
-- (that is, exceeds the length of the corresponding index).
--
-- Raises Variable_Rep_Info if length of any index depends on a
-- variable other than a discriminant.
--
-- Raises Invalid_Data if the data value is too large to fit.
procedure Set_Array_Component
(Typ : Entity_Id;
Data : in out Asis.Data_Decomposition.Portable_Data;
Subs : Asis.Data_Decomposition.Dimension_Indexes;
Val : Asis.Data_Decomposition.Portable_Data;
Discs : Repinfo.Discrim_List := Null_Discrims);
-- Same as above, but operates in place on the given stream. The stream
-- must be long enough to contain the given element in this case.
-------------------------------
-- Representation Parameters --
-------------------------------
-- These routines give direct access to the values of the
-- representation fields stored in the tree, including the
-- proper interpretation of variable values that depend on
-- the values of discriminants.
function Get_Esize
(Comp : Entity_Id;
Discs : Repinfo.Discrim_List := Null_Discrims)
return Uint;
-- Obtains the size (actually the object size, Esize) of any subtype
-- or record component or discriminant. The function can be used for
-- components of discriminanted or non-discriminated records. In the
-- case of components of a discriminated record where the value depends
-- on discriminants, Discs provides the necessary discriminant values.
-- In all other cases, Discs is ignored and can be defaulted.
--
-- Raises Variable_Rep_Info if the size depends on a variable other
-- than a discriminant.
--
-- Raises No_Component if the component is in a variant that does not
-- exist for the given set of discriminant values.
function Get_Component_Bit_Offset
(Comp : Entity_Id;
Discs : Repinfo.Discrim_List := Null_Discrims)
return Uint;
-- Obtains the component first bit value for the specified component or
-- discriminant. This function can be used for discriminanted or non-
-- discriminanted records. In the case of components of a discriminated
-- record where the value depends on discriminants, Discs provides the
-- necessary discriminant values. Otherwise (and in particular in the case
-- of discriminants themselves), Discs is ignored and can be defaulted.
--
-- Raises Variable_Rep_Info if the size depends on a variable other
-- than a discriminant.
--
-- Raises No_Component if the component is in a variant that does not
-- exist for the given set of discriminant values.
function Get_Component_Size
(Typ : Entity_Id)
return Uint;
-- Given an array type or subtype, returns the component size value
function Get_Length
(Typ : Entity_Id;
Sub : Asis.ASIS_Positive;
Discs : Repinfo.Discrim_List := Null_Discrims)
return Asis.ASIS_Natural;
-- Given Typ, the entity for a definite array type or subtype, returns
-- the Length of the subscript designated by Sub (1 = first subscript
-- as in Length attribute). If the bounds of the array may depend on
-- discriminants, then Discs contains the list of discriminant values
-- (e.g. if we have an array field A.B, then the discriminants of A
-- may be needed).
--
-- Raises Variable_Rep_Info if the size depends on a variable other
-- than a discriminant.
-------------------------------
-- Computation of Attributes --
-------------------------------
-- The DDA_Aux package simply provides access to the representation
-- information stored in the tree, as described in Einfo, as refined
-- by the description in Repinfo with regard to the case where some
-- of the values depend on discriminants.
-- The ASIS spec requires that ASIS be able to compute the values of
-- the attributes Position, First_Bit, and Last_Bit.
-- This is done as follows. First compute the Size (with Get_Esize)
-- and the Component_Bit_Offset (with Get_Component_Bit_Offset). In the
-- case of a nested reference, e.g.
-- A.B.C
-- You need to extract the value A.B, and then ask for the
-- size of its component C, and also the component first bit
-- value of this component C.
-- This value gets added to the Component_Bit_Offset value for
-- the B field in A.
-- For arrays, the equivalent of Component_Bit_Offset is computed simply
-- as the zero origin linearized subscript multiplied by the value of
-- Component_Size for the array. As another example, consider:
-- A.B(15)
-- In this case you get the component first bit of the field B in A,
-- using the discriminants of A if there are any. Then you get the
-- component first bit of the 15th element of B, using the discriminants
-- of A (since the bounds of B may depend on them). You then add these
-- two component first bit values.
-- Once you have the aggregated value of the first bit offset (i.e. the
-- sum of the Component_Bit_Offset values and corresponding array offsets
-- for all levels of the access), then the formula is simply:
-- X'Position = First_Bit_Offset / Storage_Unit_Size
-- X'First = First_Bit_Offset mod Storage_Unit_Size
-- X'Last = X'First + component_size - 1
end A4G.DDA_Aux;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
a62f0454a139c01fe389fda6995905de7d89d840
|
testutil/aunit/util-tests-reporter.ads
|
testutil/aunit/util-tests-reporter.ads
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- A U N I T . R E P O R T E R . X M L --
-- --
-- S p e c --
-- --
-- --
-- Copyright (C) 2000-2008, AdaCore --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
-- Boston, MA 02110-1301, USA. --
-- --
-- GNAT is maintained by AdaCore (http://www.adacore.com) --
-- --
------------------------------------------------------------------------------
with AUnit.Reporter;
with AUnit.Test_Results;
with Ada.Text_IO;
with Ada.Strings.Unbounded;
-- XML reporter (fix AUnit issues and generate in a separate file instead of stdout).
package Util.Tests.Reporter is
type XML_Reporter is new AUnit.Reporter.Reporter with record
File : Ada.Strings.Unbounded.Unbounded_String;
end record;
procedure Report (Engine : XML_Reporter;
R : in out AUnit.Test_Results.Result'Class);
procedure Report (Engine : XML_Reporter;
File : in out Ada.Text_IO.File_Type;
R : in out AUnit.Test_Results.Result'Class);
end Util.Tests.Reporter;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- A U N I T . R E P O R T E R . X M L --
-- --
-- S p e c --
-- --
-- --
-- Copyright (C) 2000-2008, AdaCore --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
-- Boston, MA 02110-1301, USA. --
-- --
-- GNAT is maintained by AdaCore (http://www.adacore.com) --
-- --
------------------------------------------------------------------------------
with AUnit.Reporter;
with AUnit.Test_Results;
with AUnit.Options;
with Ada.Text_IO;
with Ada.Strings.Unbounded;
-- XML reporter (fix AUnit issues and generate in a separate file instead of stdout).
package Util.Tests.Reporter is
type XML_Reporter is new AUnit.Reporter.Reporter with record
File : Ada.Strings.Unbounded.Unbounded_String;
end record;
overriding
procedure Report (Engine : in XML_Reporter;
R : in out AUnit.Test_Results.Result'Class;
Options : in AUnit.Options.AUnit_Options := AUnit.Options.Default_Options);
procedure Report (Engine : XML_Reporter;
File : in out Ada.Text_IO.File_Type;
R : in out AUnit.Test_Results.Result'Class);
end Util.Tests.Reporter;
|
Fix compilation with AUnit 2014
|
Fix compilation with AUnit 2014
|
Ada
|
apache-2.0
|
Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util,Letractively/ada-util
|
39dda632d91e19b2f050dfe16b37f3e635035183
|
src/gnat/lib-list.adb
|
src/gnat/lib-list.adb
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- L I B . L I S T --
-- --
-- B o d y --
-- --
-- Copyright (C) 1992-2009, 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. --
-- --
------------------------------------------------------------------------------
separate (Lib)
procedure List (File_Names_Only : Boolean := False) is
Num_Units : constant Nat := Int (Units.Last) - Int (Units.First) + 1;
-- Number of units in file table
Sorted_Units : Unit_Ref_Table (1 .. Num_Units);
-- Table of unit numbers that we will sort
Unit_Hed : constant String := "Unit name ";
Unit_Und : constant String := "--------- ";
Unit_Bln : constant String := " ";
File_Hed : constant String := "File name ";
File_Und : constant String := "--------- ";
File_Bln : constant String := " ";
Time_Hed : constant String := "Time stamp";
Time_Und : constant String := "----------";
Unit_Length : constant Natural := Unit_Hed'Length;
File_Length : constant Natural := File_Hed'Length;
begin
-- First step is to make a sorted table of units
for J in 1 .. Num_Units loop
Sorted_Units (J) := Unit_Number_Type (Int (Units.First) + J - 1);
end loop;
Sort (Sorted_Units);
-- Now we can generate the unit table listing
Write_Eol;
if not File_Names_Only then
Write_Str (Unit_Hed);
Write_Str (File_Hed);
Write_Str (Time_Hed);
Write_Eol;
Write_Str (Unit_Und);
Write_Str (File_Und);
Write_Str (Time_Und);
Write_Eol;
Write_Eol;
end if;
for R in Sorted_Units'Range loop
if File_Names_Only then
if not Is_Internal_File_Name
(File_Name (Source_Index (Sorted_Units (R))))
then
Write_Name (Full_File_Name (Source_Index (Sorted_Units (R))));
Write_Eol;
end if;
else
Write_Unit_Name (Unit_Name (Sorted_Units (R)));
if Name_Len > (Unit_Length - 1) then
Write_Eol;
Write_Str (Unit_Bln);
else
for J in Name_Len + 1 .. Unit_Length loop
Write_Char (' ');
end loop;
end if;
Write_Name (Full_File_Name (Source_Index (Sorted_Units (R))));
if Name_Len > (File_Length - 1) then
Write_Eol;
Write_Str (Unit_Bln);
Write_Str (File_Bln);
else
for J in Name_Len + 1 .. File_Length loop
Write_Char (' ');
end loop;
end if;
Write_Str (String (Time_Stamp (Source_Index (Sorted_Units (R)))));
Write_Eol;
end if;
end loop;
Write_Eol;
end List;
|
Add GNAT files for ASIS
|
Add GNAT files for ASIS
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
|
bf4a56cf8ab8938f28d3fd822a4f59d84c8a2190
|
src/wiki-utils.adb
|
src/wiki-utils.adb
|
-----------------------------------------------------------------------
-- wiki-utils -- Wiki utility operations
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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 Wiki.Render.Text;
with Wiki.Render.Html;
with Wiki.Writers.Builders;
package body Wiki.Utils is
-- ------------------------------
-- Render the wiki text according to the wiki syntax in HTML into a string.
-- ------------------------------
function To_Html (Text : in Wide_Wide_String;
Syntax : in Wiki.Parsers.Wiki_Syntax_Type) return String is
Writer : aliased Wiki.Writers.Builders.Html_Writer_Type;
Renderer : aliased Wiki.Render.Html.Html_Writer;
begin
Renderer.Set_Writer (Writer'Unchecked_Access);
Wiki.Parsers.Parse (Renderer'Unchecked_Access, Text, Syntax);
return Writer.To_String;
end To_Html;
-- ------------------------------
-- Render the wiki text according to the wiki syntax in text into a string.
-- Wiki formatting and decoration are removed.
-- ------------------------------
function To_Text (Text : in Wide_Wide_String;
Syntax : in Wiki.Parsers.Wiki_Syntax_Type) return String is
Writer : aliased Wiki.Writers.Builders.Writer_Builder_Type;
Renderer : aliased Wiki.Render.Text.Text_Renderer;
begin
Renderer.Set_Writer (Writer'Unchecked_Access);
Wiki.Parsers.Parse (Renderer'Unchecked_Access, Text, Syntax);
return Writer.To_String;
end To_Text;
end Wiki.Utils;
|
Implement the To_Html and To_Text functions
|
Implement the To_Html and To_Text functions
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
|
c5e194f4173ce2772e59b125567e3cd00e5ee216
|
src/os-none/util-processes-os.ads
|
src/os-none/util-processes-os.ads
|
-----------------------------------------------------------------------
-- util-processes-os -- System specific and low level operations
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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 package Util.Processes.Os is
-- Wait for the process <b>Pid</b> to finish and return the process exit status.
procedure Waitpid (Pid : in Process_Identifier;
Status : out Integer);
-- Spawn a process
procedure Spawn (Proc : in out Process;
Mode : in Pipe_Mode := NONE);
end Util.Processes.Os;
|
-----------------------------------------------------------------------
-- util-processes-os -- Dummy system specific and low level operations
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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 package Util.Processes.Os is
-- Wait for the process <b>Pid</b> to finish and return the process exit status.
procedure Waitpid (Pid : in Process_Identifier;
Status : out Integer);
-- Spawn a process
procedure Spawn (Proc : in out Process;
Mode : in Pipe_Mode := NONE);
end Util.Processes.Os;
|
Update comment title
|
Update comment title
|
Ada
|
apache-2.0
|
flottokarotto/ada-util,Letractively/ada-util,flottokarotto/ada-util,Letractively/ada-util
|
706a072ee124b2438fb1d3d6b6be29e9da1c52c3
|
src/asf-components-widgets-factory.ads
|
src/asf-components-widgets-factory.ads
|
-----------------------------------------------------------------------
-- widgets-factory -- Factory for widget Components
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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.Factory;
package ASF.Components.Widgets.Factory is
-- Get the widget component factory.
function Definition return ASF.Factory.Factory_Bindings_Access;
end ASF.Components.Widgets.Factory;
|
Define the factory for the creation of widget components
|
Define the factory for the creation of widget components
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
|
ba81cf12b19410c8883501faf698f519205cf35e
|
src/wiki-nodes-lists.ads
|
src/wiki-nodes-lists.ads
|
-----------------------------------------------------------------------
-- wiki-nodes-lists -- Wiki Document Internal representation
-- Copyright (C) 2016, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Refs;
package Wiki.Nodes.Lists is
pragma Preelaborate;
package Node_List_Refs is new Util.Refs.General_References (Node_List, Finalize);
type Node_List_Ref is new Node_List_Refs.Ref with null record;
-- Append a node to the node list.
procedure Append (Into : in out Node_List_Ref;
Node : in Node_Type_Access);
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
procedure Iterate (List : in Node_List_Access;
Process : not null access procedure (Node : in Node_Type));
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
procedure Iterate (List : in Node_List_Ref;
Process : not null access procedure (Node : in Node_Type));
-- Returns True if the list reference is empty.
function Is_Empty (List : in Node_List_Ref) return Boolean;
-- Get the number of nodes in the list.
function Length (List : in Node_List_Ref) return Natural;
private
subtype Node_List_Accessor is Node_List_Refs.Element_Accessor;
procedure Iterate (List : in Node_List_Accessor;
Process : not null access procedure (Node : in Node_Type));
end Wiki.Nodes.Lists;
|
Refactor Node_List and references to use Ada Util general references
|
Refactor Node_List and references to use Ada Util general references
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
|
62895c53ba5c3a0fe6482efd1eda4cac07863c08
|
src/wiki-filters-toc.adb
|
src/wiki-filters-toc.adb
|
-----------------------------------------------------------------------
-- wiki-filters-toc -- Filter for the creation of Table Of Contents
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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 Wiki.Nodes;
package body Wiki.Filters.TOC is
-- ------------------------------
-- Add a section header with the given level in the document.
-- ------------------------------
overriding
procedure Add_Header (Filter : in out TOC_Filter;
Document : in out Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Natural) is
T : Wiki.Nodes.Node_List_Ref;
begin
Document.Get_TOC (T);
Wiki.Nodes.Append (T, new Wiki.Nodes.Node_Type '(Kind => Wiki.Nodes.N_TOC_ENTRY,
Len => Header'Length,
Header => Header,
Level => Level));
Filter_Type (Filter).Add_Header (Document, Header, Level);
end Add_Header;
end Wiki.Filters.TOC;
|
Implement the TOC filter to collect the table of content
|
Implement the TOC filter to collect the table of content
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
|
5e915c5561498a87832779decd879b462f90c306
|
src/http/util-mail.adb
|
src/http/util-mail.adb
|
-----------------------------------------------------------------------
-- util-mail -- Mail Utility Library
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Fixed;
package body Util.Mail is
-- ------------------------------
-- Parse the email address and separate the name from the address.
-- ------------------------------
function Parse_Address (E_Mail : in String) return Email_Address is
use Ada.Strings.Unbounded;
use Ada.Strings.Fixed;
use Ada.Strings;
Result : Email_Address;
First_Pos : constant Natural := Index (E_Mail, "<");
Last_Pos : constant Natural := Index (E_Mail, ">");
begin
if First_Pos > 0 and Last_Pos > 0 then
Result.Name := To_Unbounded_String (Trim (E_Mail (E_Mail'First .. First_Pos - 1),
Both));
Result.Address := To_Unbounded_String (Trim (E_Mail (First_Pos + 1 .. Last_Pos - 1),
Both));
else
Result.Address := To_Unbounded_String (Trim (E_Mail, Both));
end if;
return Result;
end Parse_Address;
end Util.Mail;
|
Implement the Parse_Address function
|
Implement the Parse_Address function
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
|
c1805eee3bf5cb522cea1001dbeaaab55099572c
|
regtests/security-oauth-clients-tests.adb
|
regtests/security-oauth-clients-tests.adb
|
-----------------------------------------------------------------------
-- Security-oauth-clients-tests - Unit tests for OAuth
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Measures;
with Util.Strings.Sets;
package body Security.OAuth.Clients.Tests is
package Caller is new Util.Test_Caller (Test, "Security.OAuth.Clients");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.OAuth.Clients.Create_Nonce",
Test_Create_Nonce'Access);
end Add_Tests;
-- ------------------------------
-- Test Create_Nonce operation.
-- ------------------------------
procedure Test_Create_Nonce (T : in out Test) is
Nonces : Util.Strings.Sets.Set;
begin
for I in 1 .. 1_000 loop
for I in 32 .. 734 loop
declare
S : constant String := Create_Nonce (I * 3);
begin
T.Assert (not Nonces.Contains (S), "Nonce was not unique: " & S);
Nonces.Include (S);
end;
end loop;
end loop;
declare
S : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
Nonce : constant String := Create_Nonce (128);
pragma Unreferenced (Nonce);
begin
null;
end;
end loop;
Util.Measures.Report (S, "128 bits nonce generation (1000 calls)");
end;
end Test_Create_Nonce;
end Security.OAuth.Clients.Tests;
|
Add unit tests for OAuth package and Create_Nonce operation
|
Add unit tests for OAuth package and Create_Nonce operation
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
|
648011620eda5659f2d9d05373b0ba8d302f9459
|
src/security-policies-roles.adb
|
src/security-policies-roles.adb
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with Util.Log.Loggers;
with Util.Serialize.Mappers.Record_Mapper;
with Security.Contexts;
with Security.Controllers;
with Security.Controllers.Roles;
-- The <b>Security.Permissions</b> package defines the different permissions that can be
-- checked by the access control manager.
package body Security.Policies.Roles is
use Util.Log;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Security.Permissions");
-- ------------------------------
-- Get the role name.
-- ------------------------------
function Get_Role_Name (Manager : in Role_Policy;
Role : in Role_Type) return String is
use type Ada.Strings.Unbounded.String_Access;
begin
if Manager.Names (Role) = null then
return "";
else
return Manager.Names (Role).all;
end if;
end Get_Role_Name;
-- ------------------------------
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
-- ------------------------------
function Find_Role (Manager : in Role_Policy;
Name : in String) return Role_Type is
use type Ada.Strings.Unbounded.String_Access;
begin
Log.Debug ("Searching role {0}", Name);
for I in Role_Type'First .. Manager.Next_Role loop
exit when Manager.Names (I) = null;
if Name = Manager.Names (I).all then
return I;
end if;
end loop;
Log.Debug ("Role {0} not found", Name);
raise Invalid_Name;
end Find_Role;
-- ------------------------------
-- Create a role
-- ------------------------------
procedure Create_Role (Manager : in out Role_Policy;
Name : in String;
Role : out Role_Type) is
begin
Role := Manager.Next_Role;
Log.Info ("Role {0} is {1}", Name, Role_Type'Image (Role));
if Manager.Next_Role = Role_Type'Last then
Log.Error ("Too many roles allocated. Number of roles is {0}",
Role_Type'Image (Role_Type'Last));
else
Manager.Next_Role := Manager.Next_Role + 1;
end if;
Manager.Names (Role) := new String '(Name);
end Create_Role;
-- ------------------------------
-- Get or build a permission type for the given name.
-- ------------------------------
procedure Add_Role_Type (Manager : in out Role_Policy;
Name : in String;
Result : out Role_Type) is
begin
Result := Manager.Find_Role (Name);
exception
when Invalid_Name =>
Manager.Create_Role (Name, Result);
end Add_Role_Type;
end Security.Policies.Roles;
|
Move the role based operation from Security.Permissions to the role based polcies
|
Move the role based operation from Security.Permissions to the role based polcies
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
|
91370e65651d452a193ab8d8533109a67ca5e345
|
src/asis/asis-compilation_units-times.adb
|
src/asis/asis-compilation_units-times.adb
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A S I S . C O M P I L A T I O N _ U N I T S . T I M E S --
-- --
-- B o d y --
-- --
-- Copyright (C) 1995-2008, 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, 59 Temple Place --
-- - Suite 330, Boston, MA 02111-1307, 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 Ada Core Technologies Inc --
-- (http://www.gnat.com). --
-- --
------------------------------------------------------------------------------
with Asis.Exceptions; use Asis.Exceptions;
with Asis.Errors; use Asis.Errors;
with Asis.Set_Get; use Asis.Set_Get;
with A4G.Vcheck; use A4G.Vcheck;
package body Asis.Compilation_Units.Times is
Package_Name : constant String := "Asis.Compilation_Units.Times.";
Standard_Time : constant Ada.Calendar.Time :=
Ada.Calendar.Time_Of (1994, 12, 21, 0.0);
-- used as Time_Of_Last_Update for the predefined Standard package
--------------------
-- Attribute_Time --
--------------------
function Attribute_Time
(Compilation_Unit : Asis.Compilation_Unit;
Attribute : Wide_String)
return Ada.Calendar.Time
is
begin
pragma Unreferenced (Attribute);
Check_Validity (Compilation_Unit, Package_Name & "Attribute_Time");
return Nil_ASIS_Time;
end Attribute_Time;
------------------------------
-- Compilation_CPU_Duration --
------------------------------
function Compilation_CPU_Duration
(Compilation_Unit : Asis.Compilation_Unit)
return Standard.Duration
is
begin
Check_Validity
(Compilation_Unit, Package_Name & "Compilation_CPU_Duration");
return 0.0;
end Compilation_CPU_Duration;
-------------------------
-- Time_Of_Last_Update --
-------------------------
function Time_Of_Last_Update
(Compilation_Unit : Asis.Compilation_Unit)
return Ada.Calendar.Time
is
begin
Check_Validity (Compilation_Unit, Package_Name & "Time_Of_Last_Update");
if Get_Unit_Id (Compilation_Unit) = Standard_Id then
return Standard_Time;
else
return Time_Stamp (Compilation_Unit);
end if;
exception
when ASIS_Inappropriate_Compilation_Unit =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Outer_Call => Package_Name & "Time_Of_Last_Update");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Time_Of_Last_Update",
Ex => Ex,
Arg_CU => Compilation_Unit);
end Time_Of_Last_Update;
end Asis.Compilation_Units.Times;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
9381d3e437f58ced6b4afebe4a4de7e44c6bd8c9
|
awa/plugins/awa-votes/regtests/awa-votes-modules-tests.ads
|
awa/plugins/awa-votes/regtests/awa-votes-modules-tests.ads
|
-----------------------------------------------------------------------
-- awa-votes-modules-tests -- Unit tests for vote service
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with AWA.Tests;
package AWA.Votes.Modules.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new AWA.Tests.Test with record
Manager : AWA.Votes.Modules.Vote_Module_Access;
end record;
-- Test vote.
procedure Test_Vote_Up (T : in out Test);
end AWA.Votes.Modules.Tests;
|
Update the unit tests
|
Update the unit tests
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
|
b263d9db337cff25d8cf919299041c565fb7ad5d
|
samples/wget.adb
|
samples/wget.adb
|
-----------------------------------------------------------------------
-- wget -- A simple wget command to fetch a page
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Command_Line;
with Util.Strings;
with Util.Strings.Tokenizers;
with Util.Http.Clients;
with Util.Http.Clients.Curl;
procedure Wget is
procedure Print_Token (Token : in String;
Done : out Boolean) is
begin
Ada.Text_IO.Put_Line (Token);
Done := False;
end Print_Token;
Count : constant Natural := Ada.Command_Line.Argument_Count;
begin
if Count = 0 then
Ada.Text_IO.Put_Line ("Usage: wget url ...");
Ada.Text_IO.Put_Line ("Example: wget http://www.adacore.com");
return;
end if;
Util.Http.Clients.Curl.Register;
for I in 1 .. Count loop
declare
Http : Util.Http.Clients.Client;
URI : constant String := Ada.Command_Line.Argument (1);
Response : Util.Http.Clients.Response;
begin
Http.Add_Header ("X-Requested-By", "wget");
Http.Get (URI, Response);
Ada.Text_IO.Put_Line ("Code: " & Natural'Image (Response.Get_Status));
Ada.Text_IO.Put_Line (Response.Get_Body);
end;
end loop;
end Wget;
|
-----------------------------------------------------------------------
-- wget -- A simple wget command to fetch a page
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Command_Line;
with Util.Http.Clients;
with Util.Http.Clients.Curl;
procedure Wget is
Count : constant Natural := Ada.Command_Line.Argument_Count;
begin
if Count = 0 then
Ada.Text_IO.Put_Line ("Usage: wget url ...");
Ada.Text_IO.Put_Line ("Example: wget http://www.adacore.com");
return;
end if;
Util.Http.Clients.Curl.Register;
for I in 1 .. Count loop
declare
Http : Util.Http.Clients.Client;
URI : constant String := Ada.Command_Line.Argument (1);
Response : Util.Http.Clients.Response;
begin
Http.Add_Header ("X-Requested-By", "wget");
Http.Get (URI, Response);
Ada.Text_IO.Put_Line ("Code: " & Natural'Image (Response.Get_Status));
Ada.Text_IO.Put_Line (Response.Get_Body);
end;
end loop;
end Wget;
|
Remove unused Print_Token operation
|
Remove unused Print_Token operation
|
Ada
|
apache-2.0
|
flottokarotto/ada-util,flottokarotto/ada-util,Letractively/ada-util,Letractively/ada-util
|
20a604402c8182239f05b133b5e8882d8270db4e
|
src/asis/a4g-span_beginning.ads
|
src/asis/a4g-span_beginning.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . S P A N _ B E G I N N I N G --
-- --
-- S p e c --
-- --
-- Copyright (C) 1995-2012, Free Software Foundation, Inc. --
-- --
-- ASIS-for-GNAT is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 2, or (at your option) any later --
-- version. ASIS-for-GNAT is distributed in the hope that it will be use- --
-- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- --
-- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General --
-- Public License for more details. You should have received a copy of the --
-- GNU General Public License distributed with ASIS-for-GNAT; see file --
-- COPYING. If not, write to the Free Software Foundation, 51 Franklin --
-- Street, Fifth Floor, Boston, MA 02110-1301, USA. --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the --
-- Software Engineering Laboratory of the Swiss Federal Institute of --
-- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the --
-- Scientific Research Computer Center of Moscow State University (SRCC --
-- MSU), Russia, with funding partially provided by grants from the Swiss --
-- National Science Foundation and the Swiss Academy of Engineering --
-- Sciences. ASIS-for-GNAT is now maintained by AdaCore --
-- (http://www.adacore.com). --
-- --
------------------------------------------------------------------------------
with Asis;
with A4G.Int_Knds; use A4G.Int_Knds;
with Types; use Types;
package A4G.Span_Beginning is
function Set_Image_Beginning (E : Asis.Element) return Source_Ptr;
-- The driver function for computing the beginning of the element image
-- in the GNAT source text buffer. In case if the argument is a labeled
-- statement returns the baginning of the first attachecd label. Otherwise
-- calls the element-kind-specific function for computing the image
-- beginning
-- The functions below compute the beginning of the text image for some
-- specific set of ELement kinds/
function Subunit_Beginning (E : Asis.Element) return Source_Ptr;
function Private_Unit_Beginning (E : Asis.Element) return Source_Ptr;
-- Assuming that E is an element representing the top Unit element of a
-- subunit or of a library item representing a private unit, returns the
-- source pointer to the beginning of the keyword SEPARATE or PRIVATE
-- accordingly.
function No_Search (E : Asis.Element) return Source_Ptr;
-- That is, we can just use Sloc from the node the Element is based upon.
function Search_Identifier_Beginning
(E : Asis.Element)
return Source_Ptr;
-- A special processing is needed for an identifier representing the
-- attribute designator in pseudo-attribute-reference in an attribute
-- definition clause and for 'Class attribute in aspect indication
function Search_Subtype_Indication_Beginning
(E : Asis.Element)
return Source_Ptr;
-- If the subtype mark is an expanded name, we have to look for its prefix
function Defining_Identifier_Beginning
(E : Asis.Element)
return Source_Ptr;
-- Returns the beginning of A_Defining_Identifier elements. In case of
-- labels we have to get rid of '<<'
function Short_Circuit_Beginning (E : Asis.Element) return Source_Ptr;
-- Returns the beginning of short circuit expression
function Membership_Test_Beginning (E : Asis.Element) return Source_Ptr;
-- Returns the beginning of membership test expression
function Null_Component_Beginning (E : Asis.Element) return Source_Ptr;
-- In case of A_Nil_Component element Sloc of its Node points to
-- "record" (it's easy) or to variant (it's a pain)
function Search_Prefix_Beginning (E : Asis.Element) return Source_Ptr;
-- Is needed when the Argument has a "prefix" in its structure, but Sloc
-- points somewhere inside the elemen structure
-- --|A2005 start
function Possible_Null_Exclusion_Beginning
(E : Asis.Element)
return Source_Ptr;
-- Should be used for constructs that can contain null_exclusion
function Possible_Overriding_Indicator_Beginning
(E : Asis.Element)
return Source_Ptr;
-- Is supposed to be used for some of the constructs that can contain
-- overriding_indicator
-- --|A2005 end
function Component_And_Parameter_Declaration_Beginning
(E : Asis.Element)
return Source_Ptr;
function Exception_Declaration_Beginning
(E : Asis.Element)
return Source_Ptr;
function Derived_Definition_Beginning (E : Asis.Element) return Source_Ptr;
function Type_Definition_Beginning (E : Asis.Element) return Source_Ptr;
function Interface_Definition_Beginning
(E : Asis.Element)
return Source_Ptr;
function Tagged_Type_Definition_Beginning
(E : Asis.Element)
return Source_Ptr;
function Simple_Expression_Range_Beginning
(E : Asis.Element)
return Source_Ptr;
function Component_Definition_Beginning
(E : Asis.Element)
return Source_Ptr;
function Search_Left_Parenthesis_After (E : Asis.Element) return Source_Ptr;
-- Is needed when the Element does not have its "own" node (in particular,
-- for A_Known_Discriminant_Part Element)
function Private_Extension_Definition_Beginning
(E : Asis.Element)
return Source_Ptr;
function Private_Type_Definition_Beginning
(E : Asis.Element)
return Source_Ptr;
function Explicit_Dereference_Beginning
(E : Asis.Element)
return Source_Ptr;
function Function_Call_Beginning (E : Asis.Element) return Source_Ptr;
function Indexed_Component_Beginning (E : Asis.Element) return Source_Ptr;
function Component_Association_Beginning
(E : Asis.Element)
return Source_Ptr;
function Association_Beginning
(E : Asis.Element)
return Source_Ptr;
function Parenthesized_Expression_Beginning
(E : Asis.Element)
return Source_Ptr;
function Assignment_Statement_Beginning
(E : Asis.Element)
return Source_Ptr;
function Named_Statement_Beginning
(E : Asis.Element)
return Source_Ptr;
-- Takes care of loop and block names
function Call_Statement_Beginning (E : Asis.Element) return Source_Ptr;
function While_Loop_Statement_Beginning
(E : Asis.Element)
return Source_Ptr;
function For_Loop_Statement_Beginning (E : Asis.Element) return Source_Ptr;
function Else_Path_Beginning (E : Asis.Element) return Source_Ptr;
function With_Clause_Beginning (E : Asis.Element) return Source_Ptr;
function Component_Clause_Beginning (E : Asis.Element) return Source_Ptr;
function Subprogram_Spec_Beginning (E : Asis.Element) return Source_Ptr;
function Formal_Object_Declaration_Beginning
(E : Asis.Element)
return Source_Ptr;
function A_Then_Abort_Path_Beginning (E : Asis.Element) return Source_Ptr;
function Select_Alternative_Beginning (E : Asis.Element) return Source_Ptr;
-- --|A2015 start
function Case_Expression_Path_Beginning
(E : Asis.Element)
return Source_Ptr;
function If_Expression_Beginning
(E : Asis.Element)
return Source_Ptr;
function Conditional_Expression_Path_Beginning
(E : Asis.Element)
return Source_Ptr;
function An_Else_Expression_Path_Beginning
(E : Asis.Element)
return Source_Ptr;
-- --|A2015 end
-- The look-up table below defines the mapping from Element kinds onto
-- specific routines for computing the Element image beginning
type Set_Source_Location_type is
access function (E : Asis.Element) return Source_Ptr;
Switch : array (Internal_Element_Kinds) of Set_Source_Location_type := (
An_All_Calls_Remote_Pragma ..
-- An_Asynchronous_Pragma
-- An_Atomic_Pragma
-- An_Atomic_Components_Pragma
-- An_Attach_Handler_Pragma
-- A_Controlled_Pragma
-- A_Convention_Pragma
-- An_Elaborate_All_Pragma
-- An_Elaborate_Body_Pragma
-- An_Export_Pragma
-- An_Import_Pragma
-- An_Inline_Pragma
-- An_Inspection_Point_Pragma
-- An_Interrupt_Handler_Pragma
-- An_Interrupt_Priority_Pragma
-- A_List_Pragma
-- A_Locking_Policy_Pragma
-- A_Normalize_Scalars_Pragma
-- An_Optimize_Pragma
-- A_Pack_Pragma
-- A_Page_Pragma
-- A_Preelaborate_Pragma
-- A_Priority_Pragma
-- A_Pure_Pragma
-- A_Queuing_Policy_Pragma
-- A_Remote_Call_Interface_Pragma
-- A_Remote_Types_Pragma
-- A_Restrictions_Pragma
-- A_Reviewable_Pragma
-- A_Shared_Passive_Pragma
-- A_Suppress_Pragma
-- A_Task_Dispatching_Policy_Pragma
-- A_Volatile_Pragma
-- A_Volatile_Components_Pragma
-- An_Implementation_Defined_Pragma
An_Unknown_Pragma => No_Search'Access,
A_Defining_Identifier => Defining_Identifier_Beginning'Access,
A_Defining_Character_Literal ..
-- A_Defining_Enumeration_Literal
-- A_Defining_Or_Operator
-- A_Defining_Xor_Operator
-- A_Defining_Equal_Operator
-- A_Defining_Not_Equal_Operator
-- A_Defining_Less_Than_Operator
-- A_Defining_Less_Than_Or_Equal_Operator
-- A_Defining_Greater_Than_Operator
-- A_Defining_Greater_Than_Or_Equal_Operator
-- A_Defining_Plus_Operator
-- A_Defining_Minus_Operator
-- A_Defining_Concatenate_Operator
-- A_Defining_Unary_Plus_Operator
-- A_Defining_Unary_Minus_Operator
-- A_Defining_Multiply_Operator
-- A_Defining_Divide_Operator
-- A_Defining_Mod_Operator
-- A_Defining_Rem_Operator
-- A_Defining_Exponentiate_Operator
-- A_Defining_Abs_Operator
A_Defining_Not_Operator => No_Search'Access,
A_Defining_Expanded_Name => Search_Prefix_Beginning'Access,
An_Ordinary_Type_Declaration ..
-- A_Task_Type_Declaration
-- A_Protected_Type_Declaration
-- An_Incomplete_Type_Declaration
-- A_Private_Type_Declaration
-- A_Private_Extension_Declaration
-- A_Subtype_Declaration
-- A_Variable_Declaration
-- A_Constant_Declaration
-- A_Deferred_Constant_Declaration
-- A_Single_Task_Declaration
-- A_Single_Protected_Declaration
-- An_Integer_Number_Decl
-- A_Real_Number_Declaration
-- An_Enumeration_Literal_Specification
A_Discriminant_Specification => No_Search'Access,
A_Component_Declaration =>
Component_And_Parameter_Declaration_Beginning'Access,
A_Loop_Parameter_Specification => No_Search'Access,
-- --|A2012 start
A_Generalized_Iterator_Specification => No_Search'Access, -- ???
An_Element_Iterator_Specification => No_Search'Access, -- ???
-- --|A2012 end
A_Procedure_Declaration ..
A_Function_Declaration => Subprogram_Spec_Beginning'Access,
-- --|A2005 start
A_Null_Procedure_Declaration => Subprogram_Spec_Beginning'Access,
-- --|A2005 end
-- --|A2012 start
An_Expression_Function_Declaration => Subprogram_Spec_Beginning'Access,
-- --|A2012 end
A_Parameter_Specification =>
Component_And_Parameter_Declaration_Beginning'Access,
A_Procedure_Body_Declaration ..
A_Function_Body_Declaration => Subprogram_Spec_Beginning'Access,
A_Package_Declaration ..
-- A_Package_Body_Declaration
-- An_Object_Renaming_Declaration
-- An_Exception_Renaming_Declaration
A_Package_Renaming_Declaration => No_Search'Access,
A_Procedure_Renaming_Declaration => Subprogram_Spec_Beginning'Access,
A_Function_Renaming_Declaration => Subprogram_Spec_Beginning'Access,
A_Generic_Package_Renaming_Declaration ..
-- A_Generic_Procedure_Renaming_Declaration
-- A_Generic_Function_Renaming_Declaration
-- A_Task_Body_Declaration
A_Protected_Body_Declaration => No_Search'Access,
An_Entry_Declaration => Possible_Overriding_Indicator_Beginning'Access,
An_Entry_Body_Declaration ..
An_Entry_Index_Specification => No_Search'Access,
A_Procedure_Body_Stub ..
A_Function_Body_Stub => Subprogram_Spec_Beginning'Access,
A_Package_Body_Stub ..
-- A_Task_Body_Stub
A_Protected_Body_Stub => No_Search'Access,
An_Exception_Declaration =>
Exception_Declaration_Beginning'Access,
A_Choice_Parameter_Specification ..
-- A_Generic_Procedure_Declaration
-- A_Generic_Function_Declaration
-- A_Generic_Package_Declaration
A_Package_Instantiation => No_Search'Access,
A_Procedure_Instantiation ..
A_Function_Instantiation =>
Possible_Overriding_Indicator_Beginning'Access,
A_Formal_Object_Declaration =>
Formal_Object_Declaration_Beginning'Access,
A_Formal_Type_Declaration ..
-- A_Formal_Procedure_Declaration
-- A_Formal_Function_Declaration
-- A_Formal_Package_Declaration
A_Formal_Package_Declaration_With_Box => No_Search'Access,
A_Derived_Type_Definition => Derived_Definition_Beginning'Access,
A_Derived_Record_Extension_Definition =>
Derived_Definition_Beginning'Access,
An_Enumeration_Type_Definition ..
-- A_Signed_Integer_Type_Definition
-- A_Modular_Type_Definition
---------------------------------------------------------
-- !!! They all are implicit and cannot have image
-- |
-- |-> A_Root_Integer_Definition
-- |-> A_Root_Real_Definition
-- |-> A_Root_Fixed_Definition
-- |-> A_Universal_Integer_Definition
-- |-> A_Universal_Real_Definition
-- +-> A_Universal_Fixed_Definition
---------------------------------------------------------
-- A_Floating_Point_Definition
-- An_Ordinary_Fixed_Point_Definition
-- A_Decimal_Fixed_Point_Definition
-- An_Unconstrained_Array_Definition
A_Constrained_Array_Definition => No_Search'Access,
A_Record_Type_Definition => Type_Definition_Beginning'Access,
A_Tagged_Record_Type_Definition =>
Tagged_Type_Definition_Beginning'Access,
-- --|A2005 start
An_Ordinary_Interface ..
-- A_Limited_Interface,
-- A_Task_Interface,
-- A_Protected_Interface,
A_Synchronized_Interface => Interface_Definition_Beginning'Access,
-- --|A2005 end
A_Pool_Specific_Access_To_Variable ..
-- An_Access_To_Variable
-- An_Access_To_Constant
-- An_Access_To_Procedure
-- An_Access_To_Protected_Procedure
-- An_Access_To_Function
An_Access_To_Protected_Function => No_Search'Access,
A_Subtype_Indication => Search_Subtype_Indication_Beginning'Access,
A_Range_Attribute_Reference => Search_Prefix_Beginning'Access,
A_Simple_Expression_Range => Simple_Expression_Range_Beginning'Access,
A_Digits_Constraint ..
-- A_Delta_Constraint
-- An_Index_Constraint
A_Discriminant_Constraint => No_Search'Access,
A_Component_Definition => Component_Definition_Beginning'Access,
A_Discrete_Subtype_Indication_As_Subtype_Definition =>
Search_Subtype_Indication_Beginning'Access,
A_Discrete_Range_Attribute_Reference_As_Subtype_Definition =>
Search_Prefix_Beginning'Access,
A_Discrete_Simple_Expression_Range_As_Subtype_Definition =>
Simple_Expression_Range_Beginning'Access,
A_Discrete_Subtype_Indication =>
Search_Subtype_Indication_Beginning'Access,
A_Discrete_Range_Attribute_Reference => Search_Prefix_Beginning'Access,
A_Discrete_Simple_Expression_Range =>
Simple_Expression_Range_Beginning'Access,
An_Unknown_Discriminant_Part ..
A_Known_Discriminant_Part => Search_Left_Parenthesis_After'Access,
A_Record_Definition ..
A_Null_Record_Definition => No_Search'Access,
A_Null_Component => Null_Component_Beginning'Access,
A_Variant_Part ..
-- A_Variant
An_Others_Choice => No_Search'Access,
-- --|A2005 start
An_Anonymous_Access_To_Variable ..
-- An_Anonymous_Access_To_Constant,
-- An_Anonymous_Access_To_Procedure,
-- An_Anonymous_Access_To_Protected_Procedure,
-- An_Anonymous_Access_To_Function,
An_Anonymous_Access_To_Protected_Function =>
Possible_Null_Exclusion_Beginning'Access,
-- --|A2005 end
A_Private_Type_Definition => Private_Type_Definition_Beginning'Access,
A_Tagged_Private_Type_Definition =>
Private_Type_Definition_Beginning'Access,
A_Private_Extension_Definition =>
Private_Extension_Definition_Beginning'Access,
A_Task_Definition => No_Search'Access,
A_Protected_Definition => No_Search'Access,
A_Formal_Private_Type_Definition =>
Private_Type_Definition_Beginning'Access,
A_Formal_Tagged_Private_Type_Definition =>
Private_Type_Definition_Beginning'Access,
A_Formal_Derived_Type_Definition => Derived_Definition_Beginning'Access,
A_Formal_Discrete_Type_Definition => No_Search'Access,
A_Formal_Signed_Integer_Type_Definition ..
-- A_Formal_Modular_Type_Definition
-- A_Formal_Floating_Point_Definition
-- A_Formal_Ordinary_Fixed_Point_Definition
A_Formal_Decimal_Fixed_Point_Definition => No_Search'Access,
A_Formal_Ordinary_Interface ..
-- A_Formal_Limited_Interface
-- A_Formal_Task_Interface
-- A_Formal_Protected_Interface
A_Formal_Synchronized_Interface => Interface_Definition_Beginning'Access,
A_Formal_Unconstrained_Array_Definition ..
-- A_Formal_Constrained_Array_Definition
-- A_Formal_Pool_Specific_Access_To_Variable
-- A_Formal_Access_To_Variable
-- A_Formal_Access_To_Constant
-- A_Formal_Access_To_Procedure
-- A_Formal_Access_To_Protected_Procedure
-- A_Formal_Access_To_Function
A_Formal_Access_To_Protected_Function => No_Search'Access,
An_Aspect_Specification => No_Search'Access,
An_Integer_Literal ..
-- A_Real_Literal
A_String_Literal => No_Search'Access,
An_Identifier => Search_Identifier_Beginning'Access,
An_And_Operator ..
-- An_Or_Operator
-- An_Xor_Operator
-- An_Equal_Operator
-- A_Not_Equal_Operator
-- A_Less_Than_Operator
-- A_Less_Than_Or_Equal_Operator
-- A_Greater_Than_Operator
-- A_Greater_Than_Or_Equal_Operator
-- A_Plus_Operator
-- A_Minus_Operator
-- A_Concatenate_Operator
-- A_Unary_Plus_Operator
-- A_Unary_Minus_Operator
-- A_Multiply_Operator
-- A_Divide_Operator
-- A_Mod_Operator
-- A_Rem_Operator
-- An_Exponentiate_Operator
-- An_Abs_Operator
-- A_Not_Operator
-- A_Character_Literal
An_Enumeration_Literal => No_Search'Access,
An_Explicit_Dereference => Explicit_Dereference_Beginning'Access,
A_Function_Call => Function_Call_Beginning'Access,
An_Indexed_Component => Indexed_Component_Beginning'Access,
A_Slice => Indexed_Component_Beginning'Access,
A_Selected_Component ..
-- An_Access_Attribute
-- An_Address_Attribute
-- An_Adjacent_Attribute
-- An_Aft_Attribute
-- An_Alignment_Attribute
-- A_Base_Attribute
-- A_Bit_Order_Attribute
-- A_Body_Version_Attribute
-- A_Callable_Attribute
-- A_Caller_Attribute
-- A_Ceiling_Attribute
-- A_Class_Attribute
-- A_Component_Size_Attribute
-- A_Compose_Attribute
-- A_Constrained_Attribute
-- A_Copy_Sign_Attribute
-- A_Count_Attribute
-- A_Definite_Attribute
-- A_Delta_Attribute
-- A_Denorm_Attribute
-- A_Digits_Attribute
-- An_Exponent_Attribute
-- An_External_Tag_Attribute
-- A_First_Attribute
-- A_First_Bit_Attribute
-- A_Floor_Attribute
-- A_Fore_Attribute
-- A_Fraction_Attribute
-- An_Identity_Attribute
-- An_Image_Attribute
-- An_Input_Attribute
-- A_Last_Attribute
-- A_Last_Bit_Attribute
-- A_Leading_Part_Attribute
-- A_Length_Attribute
-- A_Machine_Attribute
-- A_Machine_Emax_Attribute
-- A_Machine_Emin_Attribute
-- A_Machine_Mantissa_Attribute
-- A_Machine_Overflows_Attribute
-- A_Machine_Radix_Attribute
-- A_Machine_Rounds_Attribute
-- A_Max_Attribute
-- A_Max_Size_In_Storage_Elements_Attribute
-- A_Min_Attribute
-- A_Model_Attribute
-- A_Model_Emin_Attribute
-- A_Model_Epsilon_Attribute
-- A_Model_Mantissa_Attribute
-- A_Model_Small_Attribute
-- A_Modulus_Attribute
-- An_Output_Attribute
-- A_Partition_ID_Attribute
-- A_Pos_Attribute
-- A_Position_Attribute
-- A_Pred_Attribute
-- A_Range_Attribute
-- A_Read_Attribute
-- A_Remainder_Attribute
-- A_Round_Attribute
-- A_Rounding_Attribute
-- A_Safe_First_Attribute
-- A_Safe_Last_Attribute
-- A_Scale_Attribute
-- A_Scaling_Attribute
-- A_Signed_Zeros_Attribute
-- A_Size_Attribute
-- A_Small_Attribute
-- A_Storage_Pool_Attribute
-- A_Storage_Size_Attribute
-- A_Succ_Attribute
-- A_Tag_Attribute
-- A_Terminated_Attribute
-- A_Truncation_Attribute
-- An_Unbiased_Rounding_Attribute
-- An_Unchecked_Access_Attribute
-- A_Val_Attribute
-- A_Valid_Attribute
-- A_Value_Attribute
-- A_Version_Attribute
-- A_Wide_Image_Attribute
-- A_Wide_Value_Attribute
-- A_Wide_Width_Attribute
-- A_Width_Attribute
-- A_Write_Attribute
-- An_Implementation_Defined_Attribute
An_Unknown_Attribute => Search_Prefix_Beginning'Access,
A_Record_Aggregate ..
-- An_Extension_Aggregate
-- An_Positional_Array_Aggregate
A_Named_Array_Aggregate => No_Search'Access,
An_And_Then_Short_Circuit ..
An_Or_Else_Short_Circuit => Short_Circuit_Beginning'Access,
An_In_Membership_Test ..
A_Not_In_Membership_Test => Membership_Test_Beginning'Access,
A_Null_Literal => No_Search'Access,
A_Parenthesized_Expression =>
Parenthesized_Expression_Beginning'Access,
A_Type_Conversion => Search_Prefix_Beginning'Access,
A_Qualified_Expression => Search_Prefix_Beginning'Access,
An_Allocation_From_Subtype => No_Search'Access,
An_Allocation_From_Qualified_Expression => No_Search'Access,
-- --|A2012 start
A_Case_Expression => No_Search'Access,
An_If_Expression => If_Expression_Beginning'Access,
-- --|A2012 end
A_Pragma_Argument_Association => Association_Beginning'Access,
A_Discriminant_Association => Association_Beginning'Access,
A_Record_Component_Association => Component_Association_Beginning'Access,
An_Array_Component_Association => Component_Association_Beginning'Access,
A_Parameter_Association => Association_Beginning'Access,
A_Generic_Association => No_Search'Access,
A_Null_Statement => No_Search'Access,
An_Assignment_Statement => Assignment_Statement_Beginning'Access,
An_If_Statement => No_Search'Access,
A_Case_Statement => No_Search'Access,
A_Loop_Statement => Named_Statement_Beginning'Access,
A_While_Loop_Statement => While_Loop_Statement_Beginning'Access,
A_For_Loop_Statement => For_Loop_Statement_Beginning'Access,
A_Block_Statement => Named_Statement_Beginning'Access,
An_Exit_Statement => No_Search'Access,
A_Goto_Statement => No_Search'Access,
A_Procedure_Call_Statement => Call_Statement_Beginning'Access,
A_Return_Statement => No_Search'Access,
An_Accept_Statement => No_Search'Access,
An_Entry_Call_Statement => Call_Statement_Beginning'Access,
A_Requeue_Statement ..
-- A_Requeue_Statement_With_Abort
-- A_Delay_Until_Statement
-- A_Delay_Relative_Statement
-- A_Terminate_Alternative_Statement
-- A_Selective_Accept_Statement
-- A_Timed_Entry_Call_Statement
-- A_Conditional_Entry_Call_Statement
-- An_Asynchronous_Select_Statement
-- An_Abort_Statement
-- A_Raise_Statement
-- A_Code_Statement
-- An_If_Path
-- NOTE: There is no explicit node in GNAT AST tree corresponding to
-- this Internal_Element_Kind's. It's supposed that corresponding
-- Element's record field contains Source_Ptr type value that points to
-- word IF.
-- If it isn't so, we should change this part.
-- I believe it's more correct to have A_Then_Path in spite of
-- An_If_Path which should point to the word THEN.
An_Elsif_Path => No_Search'Access,
An_Else_Path => Else_Path_Beginning'Access,
A_Case_Path => No_Search'Access,
A_Select_Path ..
-- NOTE: There is no explicit node in GNAT AST tree corresponding to
-- this Internal_Element_Kind's. It's supposed that corresponding
-- Element's record field contains Source_Ptr type value that
-- points to word SELECT.
-- If it isn't so, we should change this part.
An_Or_Path => Select_Alternative_Beginning'Access,
-- NOTE: There is no explicit node in GNAT AST tree corresponding to
-- this Internal_Element_Kind's. It's supposed that corresponding
-- Element's record field contains Source_Ptr type value that points to
-- word OR. If it isn't so, we should change this part.
A_Then_Abort_Path => A_Then_Abort_Path_Beginning'Access,
-- --|A2015 start
A_Case_Expression_Path => Case_Expression_Path_Beginning'Access,
An_If_Expression_Path ..
An_Elsif_Expression_Path => Conditional_Expression_Path_Beginning'Access,
An_Else_Expression_Path => An_Else_Expression_Path_Beginning'Access,
-- --|A2015 end
A_Use_Package_Clause ..
-- A_Use_Type_Clause
A_Use_All_Type_Clause => No_Search'Access, -- Ada 2012
A_With_Clause => With_Clause_Beginning'Access,
An_Attribute_Definition_Clause ..
-- An_Enumeration_Representation_Clause
-- A_Record_Representation_Clause
An_At_Clause => No_Search'Access,
A_Component_Clause => Component_Clause_Beginning'Access,
An_Exception_Handler => No_Search'Access,
others => No_Search'Access);
end A4G.Span_Beginning;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
2af263ca9e9dae521cf0d5003802d33339e3808c
|
src/security-auth.adb
|
src/security-auth.adb
|
-----------------------------------------------------------------------
-- security-openid -- OpenID 2.0 Support
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Log.Loggers;
with Security.Auth.OpenID;
with Security.Auth.OAuth.Facebook;
with Security.Auth.OAuth.Googleplus;
package body Security.Auth is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth");
Def_Factory : Factory_Access := Default_Factory'Access;
-- ------------------------------
-- Get the provider.
-- ------------------------------
function Get_Provider (Assoc : in Association) return String is
begin
return To_String (Assoc.Provider);
end Get_Provider;
-- ------------------------------
-- Get the email address
-- ------------------------------
function Get_Email (Auth : in Authentication) return String is
begin
return To_String (Auth.Email);
end Get_Email;
-- ------------------------------
-- Get the user first name.
-- ------------------------------
function Get_First_Name (Auth : in Authentication) return String is
begin
return To_String (Auth.First_Name);
end Get_First_Name;
-- ------------------------------
-- Get the user last name.
-- ------------------------------
function Get_Last_Name (Auth : in Authentication) return String is
begin
return To_String (Auth.Last_Name);
end Get_Last_Name;
-- ------------------------------
-- Get the user full name.
-- ------------------------------
function Get_Full_Name (Auth : in Authentication) return String is
begin
return To_String (Auth.Full_Name);
end Get_Full_Name;
-- ------------------------------
-- Get the user identity.
-- ------------------------------
function Get_Identity (Auth : in Authentication) return String is
begin
return To_String (Auth.Identity);
end Get_Identity;
-- ------------------------------
-- Get the user claimed identity.
-- ------------------------------
function Get_Claimed_Id (Auth : in Authentication) return String is
begin
return To_String (Auth.Claimed_Id);
end Get_Claimed_Id;
-- ------------------------------
-- Get the user language.
-- ------------------------------
function Get_Language (Auth : in Authentication) return String is
begin
return To_String (Auth.Language);
end Get_Language;
-- ------------------------------
-- Get the user country.
-- ------------------------------
function Get_Country (Auth : in Authentication) return String is
begin
return To_String (Auth.Country);
end Get_Country;
-- ------------------------------
-- Get the result of the authentication.
-- ------------------------------
function Get_Status (Auth : in Authentication) return Auth_Result is
begin
return Auth.Status;
end Get_Status;
-- ------------------------------
-- Default principal
-- ------------------------------
-- ------------------------------
-- Get the principal name.
-- ------------------------------
function Get_Name (From : in Principal) return String is
begin
return Get_First_Name (From.Auth) & " " & Get_Last_Name (From.Auth);
end Get_Name;
-- ------------------------------
-- Get the user email address.
-- ------------------------------
function Get_Email (From : in Principal) return String is
begin
return Get_Email (From.Auth);
end Get_Email;
-- ------------------------------
-- Get the authentication data.
-- ------------------------------
function Get_Authentication (From : in Principal) return Authentication is
begin
return From.Auth;
end Get_Authentication;
-- ------------------------------
-- Create a principal with the given authentication results.
-- ------------------------------
function Create_Principal (Auth : in Authentication) return Principal_Access is
P : constant Principal_Access := new Principal;
begin
P.Auth := Auth;
return P;
end Create_Principal;
-- ------------------------------
-- Default factory used by `Initialize`. It supports OpenID, Google, Facebook.
-- ------------------------------
function Default_Factory (Provider : in String) return Manager_Access is
begin
if Provider = PROVIDER_OPENID then
return new Security.Auth.OpenID.Manager;
elsif Provider = PROVIDER_FACEBOOK then
return new Security.Auth.OAuth.Facebook.Manager;
elsif Provider = PROVIDER_GOOGLE_PLUS then
return new Security.Auth.OAuth.Googleplus.Manager;
else
Log.Error ("Authentication provider {0} not recognized", Provider);
raise Service_Error with "Authentication provider not supported";
end if;
end Default_Factory;
-- ------------------------------
-- Initialize the OpenID realm.
-- ------------------------------
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Name : in String := PROVIDER_OPENID) is
begin
Initialize (Realm, Params, Def_Factory, Name);
end Initialize;
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Factory : not null
access function (Name : in String) return Manager_Access;
Name : in String := PROVIDER_OPENID) is
Provider : constant String := Params.Get_Parameter ("auth.provider." & Name);
Impl : constant Manager_Access := Factory (Provider);
begin
if Impl = null then
Log.Error ("Authentication provider {0} not recognized", Provider);
raise Service_Error with "Authentication provider not supported";
end if;
Realm.Delegate := Impl;
Impl.Initialize (Params, Name);
Realm.Provider := To_Unbounded_String (Name);
end Initialize;
-- ------------------------------
-- Discover the OpenID provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned.
-- (See OpenID Section 7.3 Discovery)
-- ------------------------------
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point) is
begin
if Realm.Delegate /= null then
Realm.Delegate.Discover (Name, Result);
else
-- Result.URL := Realm.Realm;
Result.Alias := To_Unbounded_String ("");
end if;
end Discover;
-- ------------------------------
-- Associate the application (relying party) with the OpenID provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
-- ------------------------------
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association) is
begin
Result.Provider := Realm.Provider;
if Realm.Delegate /= null then
Realm.Delegate.Associate (OP, Result);
end if;
end Associate;
-- ------------------------------
-- Get the authentication URL to which the user must be redirected for authentication
-- by the authentication server.
-- ------------------------------
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String is
begin
if Realm.Delegate /= null then
return Realm.Delegate.Get_Authentication_URL (OP, Assoc);
else
return To_String (OP.URL);
end if;
end Get_Authentication_URL;
procedure Set_Result (Result : in out Authentication;
Status : in Auth_Result;
Message : in String) is
begin
if Status /= AUTHENTICATED then
Log.Error ("OpenID verification failed: {0}", Message);
else
Log.Info ("OpenID verification: {0}", Message);
end if;
Result.Status := Status;
end Set_Result;
-- ------------------------------
-- Verify the authentication result
-- ------------------------------
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication) is
begin
if Realm.Delegate /= null then
Realm.Delegate.Verify (Assoc, Request, Result);
else
Set_Result (Result, SETUP_NEEDED, "Setup is needed");
end if;
end Verify;
function To_String (OP : End_Point) return String is
begin
return "openid://" & To_String (OP.URL);
end To_String;
function To_String (Assoc : Association) return String is
begin
return "session_type=" & To_String (Assoc.Session_Type)
& "&assoc_type=" & To_String (Assoc.Assoc_Type)
& "&assoc_handle=" & To_String (Assoc.Assoc_Handle)
& "&mac_key=" & To_String (Assoc.Mac_Key);
end To_String;
-- ------------------------------
-- Set the default factory to use.
-- ------------------------------
procedure Set_Default_Factory (Factory : in Factory_Access) is
begin
Def_Factory := Factory;
end Set_Default_Factory;
overriding
procedure Finalize (Realm : in out Manager) is
procedure Free is
new Ada.Unchecked_Deallocation (Manager'Class, Manager_Access);
begin
Free (Realm.Delegate);
end Finalize;
end Security.Auth;
|
-----------------------------------------------------------------------
-- security-openid -- OpenID 2.0 Support
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Log.Loggers;
with Security.Auth.OpenID;
with Security.Auth.OAuth.Facebook;
with Security.Auth.OAuth.Googleplus;
with Security.Auth.OAuth.Yahoo;
with Security.Auth.OAuth.Github;
package body Security.Auth is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth");
Def_Factory : Factory_Access := Default_Factory'Access;
-- ------------------------------
-- Get the provider.
-- ------------------------------
function Get_Provider (Assoc : in Association) return String is
begin
return To_String (Assoc.Provider);
end Get_Provider;
-- ------------------------------
-- Get the email address
-- ------------------------------
function Get_Email (Auth : in Authentication) return String is
begin
return To_String (Auth.Email);
end Get_Email;
-- ------------------------------
-- Get the user first name.
-- ------------------------------
function Get_First_Name (Auth : in Authentication) return String is
begin
return To_String (Auth.First_Name);
end Get_First_Name;
-- ------------------------------
-- Get the user last name.
-- ------------------------------
function Get_Last_Name (Auth : in Authentication) return String is
begin
return To_String (Auth.Last_Name);
end Get_Last_Name;
-- ------------------------------
-- Get the user full name.
-- ------------------------------
function Get_Full_Name (Auth : in Authentication) return String is
begin
return To_String (Auth.Full_Name);
end Get_Full_Name;
-- ------------------------------
-- Get the user identity.
-- ------------------------------
function Get_Identity (Auth : in Authentication) return String is
begin
return To_String (Auth.Identity);
end Get_Identity;
-- ------------------------------
-- Get the user claimed identity.
-- ------------------------------
function Get_Claimed_Id (Auth : in Authentication) return String is
begin
return To_String (Auth.Claimed_Id);
end Get_Claimed_Id;
-- ------------------------------
-- Get the user language.
-- ------------------------------
function Get_Language (Auth : in Authentication) return String is
begin
return To_String (Auth.Language);
end Get_Language;
-- ------------------------------
-- Get the user country.
-- ------------------------------
function Get_Country (Auth : in Authentication) return String is
begin
return To_String (Auth.Country);
end Get_Country;
-- ------------------------------
-- Get the result of the authentication.
-- ------------------------------
function Get_Status (Auth : in Authentication) return Auth_Result is
begin
return Auth.Status;
end Get_Status;
-- ------------------------------
-- Default principal
-- ------------------------------
-- ------------------------------
-- Get the principal name.
-- ------------------------------
function Get_Name (From : in Principal) return String is
begin
return Get_First_Name (From.Auth) & " " & Get_Last_Name (From.Auth);
end Get_Name;
-- ------------------------------
-- Get the user email address.
-- ------------------------------
function Get_Email (From : in Principal) return String is
begin
return Get_Email (From.Auth);
end Get_Email;
-- ------------------------------
-- Get the authentication data.
-- ------------------------------
function Get_Authentication (From : in Principal) return Authentication is
begin
return From.Auth;
end Get_Authentication;
-- ------------------------------
-- Create a principal with the given authentication results.
-- ------------------------------
function Create_Principal (Auth : in Authentication) return Principal_Access is
P : constant Principal_Access := new Principal;
begin
P.Auth := Auth;
return P;
end Create_Principal;
-- ------------------------------
-- Default factory used by `Initialize`. It supports OpenID, Google, Facebook.
-- ------------------------------
function Default_Factory (Provider : in String) return Manager_Access is
begin
if Provider = PROVIDER_OPENID then
return new Security.Auth.OpenID.Manager;
elsif Provider = PROVIDER_FACEBOOK then
return new Security.Auth.OAuth.Facebook.Manager;
elsif Provider = PROVIDER_GOOGLE_PLUS then
return new Security.Auth.OAuth.Googleplus.Manager;
elsif Provider = PROVIDER_YAHOO then
return new Security.Auth.OAuth.Yahoo.Manager;
elsif Provider = PROVIDER_GITHUB then
return new Security.Auth.OAuth.Github.Manager;
else
Log.Error ("Authentication provider {0} not recognized", Provider);
raise Service_Error with "Authentication provider not supported";
end if;
end Default_Factory;
-- ------------------------------
-- Initialize the OpenID realm.
-- ------------------------------
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Name : in String := PROVIDER_OPENID) is
begin
Initialize (Realm, Params, Def_Factory, Name);
end Initialize;
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Factory : not null
access function (Name : in String) return Manager_Access;
Name : in String := PROVIDER_OPENID) is
Provider : constant String := Params.Get_Parameter ("auth.provider." & Name);
Impl : constant Manager_Access := Factory (Provider);
begin
if Impl = null then
Log.Error ("Authentication provider {0} not recognized", Provider);
raise Service_Error with "Authentication provider not supported";
end if;
Realm.Delegate := Impl;
Impl.Initialize (Params, Name);
Realm.Provider := To_Unbounded_String (Name);
end Initialize;
-- ------------------------------
-- Discover the OpenID provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned.
-- (See OpenID Section 7.3 Discovery)
-- ------------------------------
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point) is
begin
if Realm.Delegate /= null then
Realm.Delegate.Discover (Name, Result);
else
-- Result.URL := Realm.Realm;
Result.Alias := To_Unbounded_String ("");
end if;
end Discover;
-- ------------------------------
-- Associate the application (relying party) with the OpenID provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
-- ------------------------------
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association) is
begin
Result.Provider := Realm.Provider;
if Realm.Delegate /= null then
Realm.Delegate.Associate (OP, Result);
end if;
end Associate;
-- ------------------------------
-- Get the authentication URL to which the user must be redirected for authentication
-- by the authentication server.
-- ------------------------------
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String is
begin
if Realm.Delegate /= null then
return Realm.Delegate.Get_Authentication_URL (OP, Assoc);
else
return To_String (OP.URL);
end if;
end Get_Authentication_URL;
procedure Set_Result (Result : in out Authentication;
Status : in Auth_Result;
Message : in String) is
begin
if Status /= AUTHENTICATED then
Log.Error ("OpenID verification failed: {0}", Message);
else
Log.Info ("OpenID verification: {0}", Message);
end if;
Result.Status := Status;
end Set_Result;
-- ------------------------------
-- Verify the authentication result
-- ------------------------------
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication) is
begin
if Realm.Delegate /= null then
Realm.Delegate.Verify (Assoc, Request, Result);
else
Set_Result (Result, SETUP_NEEDED, "Setup is needed");
end if;
end Verify;
function To_String (OP : End_Point) return String is
begin
return "openid://" & To_String (OP.URL);
end To_String;
function To_String (Assoc : Association) return String is
begin
return "session_type=" & To_String (Assoc.Session_Type)
& "&assoc_type=" & To_String (Assoc.Assoc_Type)
& "&assoc_handle=" & To_String (Assoc.Assoc_Handle)
& "&mac_key=" & To_String (Assoc.Mac_Key);
end To_String;
-- ------------------------------
-- Set the default factory to use.
-- ------------------------------
procedure Set_Default_Factory (Factory : in Factory_Access) is
begin
Def_Factory := Factory;
end Set_Default_Factory;
overriding
procedure Finalize (Realm : in out Manager) is
procedure Free is
new Ada.Unchecked_Deallocation (Manager'Class, Manager_Access);
begin
Free (Realm.Delegate);
end Finalize;
end Security.Auth;
|
Update to recognize the Yahoo and Github providers
|
Update to recognize the Yahoo and Github providers
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
9081edd0457c8050db4156c0bd58c67c0f5e1125
|
src/gen-model-projects.ads
|
src/gen-model-projects.ads
|
-----------------------------------------------------------------------
-- gen-model-projects -- Projects meta data
-- Copyright (C) 2011, 2012, 2013, 2014, 2017, 2018, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Vectors;
with Util.Beans.Objects;
with Util.Properties;
with Gen.Utils;
with Gen.Utils.GNAT;
package Gen.Model.Projects is
use Ada.Strings.Unbounded;
type Project_Definition is tagged;
type Project_Definition_Access is access all Project_Definition'Class;
type Dependency_Type is (NONE, DIRECT, INDIRECT, BOTH);
type Project_Reference is record
Project : Project_Definition_Access := null;
Name : Unbounded_String;
Kind : Dependency_Type := NONE;
end record;
package Project_Vectors is
new Ada.Containers.Vectors (Element_Type => Project_Reference,
Index_Type => Natural);
-- ------------------------------
-- Project Definition
-- ------------------------------
type Project_Definition is new Definition with record
Path : Unbounded_String;
Props : Util.Properties.Manager;
Modules : Project_Vectors.Vector;
-- The root project definition.
Root : Project_Definition_Access := null;
-- The list of plugin names that this plugin or project depends on.
Dependencies : Project_Vectors.Vector;
-- The list of GNAT project files used by the project.
Project_Files : Gen.Utils.GNAT.Project_Info_Vectors.Vector;
-- The list of 'dynamo.xml' files used by the project (gathered from GNAT files
-- and by scanning the 'plugins' directory).
Dynamo_Files : Gen.Utils.String_List.Vector;
-- Whether we did a recursive scan of GNAT project files.
Recursive_Scan : Boolean := False;
-- Whether we are doing a recursive operation on the project (prevent from cycles).
Recursing : Boolean := False;
-- Whether we did a recursive scan of Dynamo dependencies.
Depend_Scan : Boolean := False;
-- Whether this project is a plugin.
Is_Plugin : Boolean := False;
end record;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : Project_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Get the project name.
function Get_Project_Name (Project : in Project_Definition) return String;
-- Get the GNAT project file name. The default is to use the Dynamo project
-- name and add the <b>.gpr</b> extension. The <b>gnat_project</b> configuration
-- property allows to override this default.
function Get_GNAT_Project_Name (Project : in Project_Definition) return String;
-- Get the directory path which holds application modules.
-- This is controlled by the <b>modules_dir</b> configuration property.
-- The default is <tt>plugins</tt>.
-- ------------------------------
function Get_Module_Dir (Project : in Project_Definition) return String;
-- Find the dependency for the <b>Name</b> plugin.
-- Returns a null dependency if the project does not depend on that plugin.
function Find_Dependency (From : in Project_Definition;
Name : in String) return Project_Reference;
-- Add a dependency to the plugin identified by <b>Name</b>.
procedure Add_Dependency (Into : in out Project_Definition;
Name : in String;
Kind : in Dependency_Type);
-- Add a dependency to the plugin identified by <b>Project</b>.
procedure Add_Dependency (Into : in out Project_Definition;
Project : in Project_Definition_Access;
Kind : in Dependency_Type);
-- Create a project definition instance to record a project with the dynamo XML file path.
procedure Create_Project (Into : in out Project_Definition;
Name : in String;
Path : in String;
Project : out Project_Definition_Access);
-- Add the project in the global project list on the root project instance.
procedure Add_Project (Into : in out Project_Definition;
Project : in Project_Definition_Access);
-- Add the project <b>Name</b> as a module.
procedure Add_Module (Into : in out Project_Definition;
Name : in String);
-- Add the project represented by <b>Project</b> if it is not already part of the modules.
procedure Add_Module (Into : in out Project_Definition;
Project : in Project_Definition_Access);
-- Find the project definition associated with the dynamo XML file <b>Path</b>.
-- Returns null if there is no such project
function Find_Project (From : in Project_Definition;
Path : in String) return Project_Definition_Access;
-- Find the project definition having the name <b>Name</b>.
-- Returns null if there is no such project
function Find_Project_By_Name (From : in Project_Definition;
Name : in String) return Project_Definition_Access;
-- Save the project description and parameters.
procedure Save (Project : in out Project_Definition;
Path : in String);
-- Read the XML project description into the project description.
procedure Read_Project (Project : in out Project_Definition);
-- Scan and read the possible modules used by the application. Modules are stored in the
-- <b>modules</b> directory. Each module is stored in its own directory and has its own
-- <b>dynamo.xml</b> file.
procedure Read_Modules (Project : in out Project_Definition);
-- Update the project definition from the properties.
procedure Update_From_Properties (Project : in out Project_Definition);
-- ------------------------------
-- Root Project Definition
-- ------------------------------
-- The root project is the project that is actually read by Dynamo.
-- It contains the lists of all projects that are necessary and which are found either
-- by scanning GNAT projects or by looking at plugin dependencies.
type Root_Project_Definition is new Project_Definition with record
Projects : Project_Vectors.Vector;
Install_Dir : Unbounded_String;
end record;
-- Add the project in the global project list on the root project instance.
overriding
procedure Add_Project (Into : in out Root_Project_Definition;
Project : in Project_Definition_Access);
-- Find the project definition having the name <b>Name</b>.
-- Returns null if there is no such project
overriding
function Find_Project_By_Name (From : in Root_Project_Definition;
Name : in String) return Project_Definition_Access;
-- Find the project definition associated with the dynamo XML file <b>Path</b>.
-- Returns null if there is no such project
overriding
function Find_Project (From : in Root_Project_Definition;
Path : in String) return Project_Definition_Access;
-- Read the XML project file. When <b>Recursive</b> is set, read the GNAT project
-- files used by the main project and load all the <b>dynamo.xml</b> files defined
-- by these project.
procedure Read_Project (Project : in out Root_Project_Definition;
File : in String;
Config : in Util.Properties.Manager'Class;
Recursive : in Boolean := False);
private
-- Update the project references after a project is found and initialized.
procedure Update_References (Root : in out Root_Project_Definition;
Project : in Project_Definition_Access);
-- Iterate over the project referenced in the list and execute the <b>Process</b> procedure.
procedure Iterate (List : in out Project_Vectors.Vector;
Process : access procedure (Item : in out Project_Reference));
-- Find a project from the list
function Find_Project (List : in Project_Vectors.Vector;
Name : in String) return Project_Reference;
end Gen.Model.Projects;
|
-----------------------------------------------------------------------
-- gen-model-projects -- Projects meta data
-- Copyright (C) 2011, 2012, 2013, 2014, 2017, 2018, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Vectors;
with Util.Beans.Objects;
with Util.Properties;
with Gen.Utils;
with Gen.Utils.GNAT;
package Gen.Model.Projects is
use Ada.Strings.Unbounded;
type Project_Definition is tagged;
type Project_Definition_Access is access all Project_Definition'Class;
type Dependency_Type is (NONE, DIRECT, INDIRECT, BOTH);
type Project_Reference is record
Project : Project_Definition_Access := null;
Name : Unbounded_String;
Kind : Dependency_Type := NONE;
end record;
package Project_Vectors is
new Ada.Containers.Vectors (Element_Type => Project_Reference,
Index_Type => Natural);
-- ------------------------------
-- Project Definition
-- ------------------------------
type Project_Definition is new Definition with record
Path : Unbounded_String;
Props : Util.Properties.Manager;
Modules : Project_Vectors.Vector;
-- The root project definition.
Root : Project_Definition_Access := null;
-- The list of plugin names that this plugin or project depends on.
Dependencies : Project_Vectors.Vector;
-- The list of GNAT project files used by the project.
Project_Files : Gen.Utils.GNAT.Project_Info_Vectors.Vector;
-- The list of 'dynamo.xml' files used by the project (gathered from GNAT files
-- and by scanning the 'plugins' directory).
Dynamo_Files : Gen.Utils.String_List.Vector;
-- Whether we did a recursive scan of GNAT project files.
Recursive_Scan : Boolean := False;
-- Whether we are doing a recursive operation on the project (prevent from cycles).
Recursing : Boolean := False;
-- Whether we did a recursive scan of Dynamo dependencies.
Depend_Scan : Boolean := False;
-- Whether this project is a plugin.
Is_Plugin : Boolean := False;
-- Whether the project needs the generation for the different databases
Use_Mysql : Boolean := True;
Use_Sqlite : Boolean := True;
Use_Postgresql : Boolean := True;
end record;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : Project_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Get the project name.
function Get_Project_Name (Project : in Project_Definition) return String;
-- Get the GNAT project file name. The default is to use the Dynamo project
-- name and add the <b>.gpr</b> extension. The <b>gnat_project</b> configuration
-- property allows to override this default.
function Get_GNAT_Project_Name (Project : in Project_Definition) return String;
-- Get the directory path which holds application modules.
-- This is controlled by the <b>modules_dir</b> configuration property.
-- The default is <tt>plugins</tt>.
-- ------------------------------
function Get_Module_Dir (Project : in Project_Definition) return String;
-- Find the dependency for the <b>Name</b> plugin.
-- Returns a null dependency if the project does not depend on that plugin.
function Find_Dependency (From : in Project_Definition;
Name : in String) return Project_Reference;
-- Add a dependency to the plugin identified by <b>Name</b>.
procedure Add_Dependency (Into : in out Project_Definition;
Name : in String;
Kind : in Dependency_Type);
-- Add a dependency to the plugin identified by <b>Project</b>.
procedure Add_Dependency (Into : in out Project_Definition;
Project : in Project_Definition_Access;
Kind : in Dependency_Type);
-- Create a project definition instance to record a project with the dynamo XML file path.
procedure Create_Project (Into : in out Project_Definition;
Name : in String;
Path : in String;
Project : out Project_Definition_Access);
-- Add the project in the global project list on the root project instance.
procedure Add_Project (Into : in out Project_Definition;
Project : in Project_Definition_Access);
-- Add the project <b>Name</b> as a module.
procedure Add_Module (Into : in out Project_Definition;
Name : in String);
-- Add the project represented by <b>Project</b> if it is not already part of the modules.
procedure Add_Module (Into : in out Project_Definition;
Project : in Project_Definition_Access);
-- Find the project definition associated with the dynamo XML file <b>Path</b>.
-- Returns null if there is no such project
function Find_Project (From : in Project_Definition;
Path : in String) return Project_Definition_Access;
-- Find the project definition having the name <b>Name</b>.
-- Returns null if there is no such project
function Find_Project_By_Name (From : in Project_Definition;
Name : in String) return Project_Definition_Access;
-- Save the project description and parameters.
procedure Save (Project : in out Project_Definition;
Path : in String);
-- Read the XML project description into the project description.
procedure Read_Project (Project : in out Project_Definition);
-- Scan and read the possible modules used by the application. Modules are stored in the
-- <b>modules</b> directory. Each module is stored in its own directory and has its own
-- <b>dynamo.xml</b> file.
procedure Read_Modules (Project : in out Project_Definition);
-- Update the project definition from the properties.
procedure Update_From_Properties (Project : in out Project_Definition);
-- ------------------------------
-- Root Project Definition
-- ------------------------------
-- The root project is the project that is actually read by Dynamo.
-- It contains the lists of all projects that are necessary and which are found either
-- by scanning GNAT projects or by looking at plugin dependencies.
type Root_Project_Definition is new Project_Definition with record
Projects : Project_Vectors.Vector;
Install_Dir : Unbounded_String;
end record;
-- Add the project in the global project list on the root project instance.
overriding
procedure Add_Project (Into : in out Root_Project_Definition;
Project : in Project_Definition_Access);
-- Find the project definition having the name <b>Name</b>.
-- Returns null if there is no such project
overriding
function Find_Project_By_Name (From : in Root_Project_Definition;
Name : in String) return Project_Definition_Access;
-- Find the project definition associated with the dynamo XML file <b>Path</b>.
-- Returns null if there is no such project
overriding
function Find_Project (From : in Root_Project_Definition;
Path : in String) return Project_Definition_Access;
-- Read the XML project file. When <b>Recursive</b> is set, read the GNAT project
-- files used by the main project and load all the <b>dynamo.xml</b> files defined
-- by these project.
procedure Read_Project (Project : in out Root_Project_Definition;
File : in String;
Config : in Util.Properties.Manager'Class;
Recursive : in Boolean := False);
private
-- Update the project references after a project is found and initialized.
procedure Update_References (Root : in out Root_Project_Definition;
Project : in Project_Definition_Access);
-- Iterate over the project referenced in the list and execute the <b>Process</b> procedure.
procedure Iterate (List : in out Project_Vectors.Vector;
Process : access procedure (Item : in out Project_Reference));
-- Find a project from the list
function Find_Project (List : in Project_Vectors.Vector;
Name : in String) return Project_Reference;
end Gen.Model.Projects;
|
Fix #9: add Use_Mysql, Use_Sqlite and Use_Postresql to control the SQL generation on the project
|
Fix #9: add Use_Mysql, Use_Sqlite and Use_Postresql to control the SQL generation on the project
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
82ca030bd272c83e2f883eef5a3b493f63f485ed
|
src/asis/a4g-encl_el.ads
|
src/asis/a4g-encl_el.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . E N C L _ E L --
-- --
-- S p e c --
-- --
-- Copyright (C) 1995-2010, Free Software Foundation, Inc. --
-- --
-- ASIS-for-GNAT is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 2, or (at your option) any later --
-- version. ASIS-for-GNAT is distributed in the hope that it will be use- --
-- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- --
-- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General --
-- Public License for more details. You should have received a copy of the --
-- GNU General Public License distributed with ASIS-for-GNAT; see file --
-- COPYING. If not, write to the Free Software Foundation, 51 Franklin --
-- Street, Fifth Floor, Boston, MA 02110-1301, USA. --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the --
-- Software Engineering Laboratory of the Swiss Federal Institute of --
-- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the --
-- Scientific Research Computer Center of Moscow State University (SRCC --
-- MSU), Russia, with funding partially provided by grants from the Swiss --
-- National Science Foundation and the Swiss Academy of Engineering --
-- Sciences. ASIS-for-GNAT is now maintained by AdaCore --
-- (http://www.adacore.com). --
-- --
------------------------------------------------------------------------------
-- This package contains routines for computing the enclosing element
-- for the Asis.Elements.Enclosing_Element function
with Asis;
package A4G.Encl_El is
function Corresponding_Instantiation
(Element : Asis.Element)
return Asis.Element;
-- This function accepts an Element representing an expanded generic
-- declaration as an argument and returns the generic instantiation
-- which was expanded in the argument declaration. According to subclause
-- 15.26, this instantiation should be returned as the Enclosing_Element
-- for the expanded generic declaration.
--
-- Should we move this function in Asis.Extensions?
function Enclosing_For_Explicit_Instance_Component
(Element : Asis.Element)
return Asis.Element;
-- Computes the Enclosing Element for an explicit component of an
-- expanded generic declaration. The problem in this case is, that if
-- the result represents the whole expanded declaration, the
-- Special_Case field of the result should be properly set
function Enclosing_Element_For_Explicit
(Element : Asis.Element)
return Asis.Element;
-- This is the general constructor of enclosing element for explicit
-- elements
function Enclosing_Element_For_Implicit
(Element : Asis.Element)
return Asis.Element;
-- This is the general constructor of enclosing element for implicit
-- elements. It's only partially implemented for now.
function Enclosing_Element_For_Limited_View
(Element : Asis.Element)
return Asis.Element;
-- This is the general constructor of enclosing element for elements from
-- limited view.
end A4G.Encl_El;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
|
2f342af96d307e83d6c8532714e59e50edf36588
|
src/asm-intrinsic/util-concurrent-counters.adb
|
src/asm-intrinsic/util-concurrent-counters.adb
|
-----------------------------------------------------------------------
-- Util.Concurrent -- Concurrent Counters
-- Copyright (C) 2009, 2010, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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.
-----------------------------------------------------------------------
package body Util.Concurrent.Counters is
use Interfaces;
function Sync_Add_And_Fetch
(Ptr : access Interfaces.Unsigned_32;
Value : Interfaces.Integer_32) return Interfaces.Unsigned_32;
pragma Import (Intrinsic, Sync_Add_And_Fetch,
External_Name => "__sync_add_and_fetch_4");
function Sync_Fetch_And_Add
(Ptr : access Interfaces.Unsigned_32;
Value : Interfaces.Integer_32) return Interfaces.Unsigned_32;
pragma Import (Intrinsic, Sync_Fetch_And_Add,
External_Name => "__sync_fetch_and_add_4");
procedure Sync_Add
(Ptr : access Interfaces.Unsigned_32;
Value : Interfaces.Unsigned_32);
pragma Import (Intrinsic, Sync_Add,
External_Name => "__sync_add_and_fetch_4");
-- ------------------------------
-- Increment the counter atomically.
-- ------------------------------
procedure Increment (C : in out Counter) is
begin
Sync_Add (C.Value'Unrestricted_Access, 1);
end Increment;
-- ------------------------------
-- Increment the counter atomically and return the value before increment.
-- ------------------------------
procedure Increment (C : in out Counter;
Value : out Integer) is
begin
Value := Integer (Sync_Fetch_And_Add (C.Value'Unrestricted_Access, 1));
end Increment;
-- ------------------------------
-- Decrement the counter atomically.
-- ------------------------------
procedure Decrement (C : in out Counter) is
begin
Sync_Add (C.Value'Unrestricted_Access, -1);
end Decrement;
-- ------------------------------
-- Decrement the counter atomically and return a status.
-- ------------------------------
procedure Decrement (C : in out Counter;
Is_Zero : out Boolean) is
Value : Unsigned_32;
begin
Value := Sync_Add_And_Fetch (C.Value'Unrestricted_Access, -1);
Is_Zero := Value /= 0;
end Decrement;
-- ------------------------------
-- Get the counter value
-- ------------------------------
function Value (C : in Counter) return Integer is
begin
return Integer (C.Value);
end Value;
end Util.Concurrent.Counters;
|
Implement the atomic counters using the gcc builtins __sync_add_and_fetch_4 and __sync_fetch_and_add_4
|
Implement the atomic counters using the gcc builtins __sync_add_and_fetch_4 and __sync_fetch_and_add_4
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
|
8372758e1241f36cb682eba508761a23b435d083
|
src/wiki-nodes-lists.adb
|
src/wiki-nodes-lists.adb
|
-----------------------------------------------------------------------
-- wiki-nodes-lists -- Wiki Document Internal representation
-- Copyright (C) 2016, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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.
-----------------------------------------------------------------------
package body Wiki.Nodes.Lists is
-- ------------------------------
-- Append a node to the node list.
-- ------------------------------
procedure Append (Into : in out Node_List_Ref;
Node : in Node_Type_Access) is
begin
if Into.Is_Null then
Node_List_Refs.Ref (Into) := Node_List_Refs.Create;
Into.Value.Current := Into.Value.First'Access;
end if;
Append (Into.Value, Node);
end Append;
-- ------------------------------
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
-- ------------------------------
procedure Iterate (List : in Node_List_Accessor;
Process : not null access procedure (Node : in Node_Type)) is
Block : Node_List_Block_Access := List.First'Access;
begin
loop
for I in 1 .. Block.Last loop
Process (Block.List (I).all);
end loop;
Block := Block.Next;
exit when Block = null;
end loop;
end Iterate;
procedure Iterate (List : in Node_List_Access;
Process : not null access procedure (Node : in Node_Type)) is
Block : Node_List_Block_Access := List.First'Access;
begin
loop
for I in 1 .. Block.Last loop
Process (Block.List (I).all);
end loop;
Block := Block.Next;
exit when Block = null;
end loop;
end Iterate;
-- ------------------------------
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
-- ------------------------------
procedure Iterate (List : in Node_List_Ref;
Process : not null access procedure (Node : in Node_Type)) is
begin
if not List.Is_Null then
Iterate (List.Value, Process);
end if;
end Iterate;
-- ------------------------------
-- Returns True if the list reference is empty.
-- ------------------------------
function Is_Empty (List : in Node_List_Ref) return Boolean is
begin
return List.Is_Null;
end Is_Empty;
-- ------------------------------
-- Get the number of nodes in the list.
-- ------------------------------
function Length (List : in Node_List_Ref) return Natural is
begin
if List.Is_Null then
return 0;
else
return List.Value.Length;
end if;
end Length;
end Wiki.Nodes.Lists;
|
Refactor Node_List and references to use Ada Util general references
|
Refactor Node_List and references to use Ada Util general references
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
|
a2f47ceed907187c7f88c64410aaa66f836ab96b
|
src/gen-artifacts-yaml.adb
|
src/gen-artifacts-yaml.adb
|
-----------------------------------------------------------------------
-- gen-artifacts-yaml -- Query artifact for Code Generator
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Exceptions;
with Util.Strings;
with Text;
with Yaml.Source.File;
with Yaml.Parser;
with Gen.Configs;
with Gen.Model.Tables;
with Gen.Model.Queries;
with Gen.Model.Mappings;
with Gen.Model.Operations;
with Util.Log.Loggers;
with Util.Encoders.HMAC.SHA1;
with Util.Stacks;
use Yaml;
package body Gen.Artifacts.Yaml is
use Ada.Strings.Unbounded;
use Gen.Model;
use Gen.Model.Tables;
use Gen.Model.Queries;
use Gen.Configs;
use Util.Log;
use type Text.Reference;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Yaml");
type State_Type is (IN_ROOT,
IN_TABLE,
IN_COLUMNS,
IN_COLUMN,
IN_UNKOWN);
type Node_Info is record
State : State_Type;
Name : Text.Reference;
Has_Name : Boolean := False;
Table : Gen.Model.Tables.Table_Definition_Access;
Col : Gen.Model.Tables.Column_Definition_Access;
end record;
type Node_Info_Access is access all Node_Info;
package Node_Stack is new Util.Stacks (Element_Type => Node_Info,
Element_Type_Access => Node_Info_Access);
procedure Read_Scalar (Node : in Node_Info_Access;
Name : in String;
Value : in String) is
begin
case Node.State is
when IN_TABLE =>
if Node.Table = null then
return;
end if;
Log.Debug ("Set table {0} attribute {1}={2}", Node.Table.Name, Name, Value);
if Name = "table" then
Node.Table.Table_Name := To_Unbounded_String (Value);
end if;
when IN_COLUMN =>
if Node.Col = null then
return;
end if;
Log.Debug ("Set table column {0} attribute {1}={2}", Node.Col.Name, Name, Value);
if Name = "type" then
Node.Col.Set_Type (Value);
elsif Name = "length" then
Node.Col.Sql_Length := Natural'Value (Value);
elsif Name = "column" then
Node.Col.Sql_Name := To_Unbounded_String (Value);
elsif Name = "unique" then
Node.Col.Unique := Value = "true" or Value = "yes";
elsif Name = "nullable" then
null;
end if;
when others =>
Log.Error ("Scalar {0}: {1} not handled", Name, Value);
end case;
end Read_Scalar;
procedure Process_Mapping (Model : in out Gen.Model.Packages.Model_Definition;
Stack : in out Node_Stack.Stack) is
Node : Node_Info_Access;
New_Node : Node_Info_Access;
begin
Node := Node_Stack.Current (Stack);
if Node.Has_Name then
Node.Has_Name := False;
case Node.State is
when IN_ROOT =>
Node_Stack.Push (Stack);
New_Node := Node_Stack.Current (Stack);
New_Node.Table := Gen.Model.Tables.Create_Table (To_Unbounded_String (Node.Name & ""));
New_Node.State := IN_TABLE;
Model.Register_Table (New_Node.Table);
when IN_TABLE =>
if Node.Name = "fields" or Node.Name = "properties" then
Node_Stack.Push (Stack);
New_Node := Node_Stack.Current (Stack);
New_Node.Table := Node.Table;
New_Node.State := IN_COLUMNS;
end if;
when IN_COLUMNS =>
Node.Table.Add_Column (To_Unbounded_String (Node.Name & ""), Node.Col);
Node_Stack.Push (Stack);
New_Node := Node_Stack.Current (Stack);
New_Node.Table := Node.Table;
New_Node.State := IN_COLUMN;
when others =>
Node_Stack.Push (Stack);
New_Node := Node_Stack.Current (Stack);
New_Node.State := IN_UNKOWN;
end case;
end if;
end Process_Mapping;
-- Read the UML/XMI model file.
procedure Read_Model (Handler : in out Artifact;
File : in String;
Model : in out Gen.Model.Packages.Model_Definition;
Context : in out Generator'Class;
Is_Predefined : in Boolean := False) is
Input : Source.Pointer;
P : Parser.Instance;
Cur : Event;
Stack : Node_Stack.Stack;
Node : Node_Info_Access;
Loc : Mark;
begin
Log.Info ("Reading YAML file {0}", File);
Input := Source.File.As_Source (File);
P.Set_Input (Input);
loop
Cur := P.Next;
exit when Cur.Kind = Stream_End;
case Cur.Kind is
when Stream_Start | Document_Start =>
Node_Stack.Push (Stack);
when Stream_End | Document_End =>
Node_Stack.Pop (Stack);
when Alias =>
null;
when Scalar =>
Node := Node_Stack.Current (Stack);
if Node.Has_Name then
Read_Scalar (Node, Node.Name & "", Cur.Content & "");
Node.Has_Name := False;
else
Node.Name := Cur.Content;
Node.Has_Name := True;
end if;
when Sequence_Start =>
Node_Stack.Push (Stack);
when Sequence_End =>
Node_Stack.Pop (Stack);
when Mapping_Start =>
Process_Mapping (Model, Stack);
when Mapping_End =>
Node_Stack.Pop (Stack);
when Annotation_Start =>
null;
when Annotation_End =>
null;
end case;
end loop;
exception
when E : others =>
Loc := P.Current_Lexer_Token_Start;
Context.Error ("{0}: {1}", Util.Strings.Image (Loc.Line) & ":"
& Util.Strings.Image (Loc.Column) & ": ",
Ada.Exceptions.Exception_Message (E));
end Read_Model;
-- ------------------------------
-- Prepare the generation of the package:
-- o identify the column types which are used
-- o build a list of package for the with clauses.
-- ------------------------------
overriding
procedure Prepare (Handler : in out Artifact;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class) is
pragma Unreferenced (Handler);
begin
Log.Debug ("Preparing the model for query");
if Model.Has_Packages then
Context.Add_Generation (Name => GEN_PACKAGE_SPEC, Mode => ITERATION_PACKAGE,
Mapping => Gen.Model.Mappings.ADA_MAPPING);
Context.Add_Generation (Name => GEN_PACKAGE_BODY, Mode => ITERATION_PACKAGE,
Mapping => Gen.Model.Mappings.ADA_MAPPING);
end if;
end Prepare;
end Gen.Artifacts.Yaml;
|
Read a YAML model files and configure the model tables with it
|
Read a YAML model files and configure the model tables with it
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
11eb2788ad603777a21f701fd326282dde800c20
|
src/wiki-render-wiki.ads
|
src/wiki-render-wiki.ads
|
-----------------------------------------------------------------------
-- wiki-render-wiki -- Wiki to Wiki renderer
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
with Util.Strings;
with Wiki.Documents;
with Wiki.Attributes;
with Wiki.Writers;
with Wiki.Parsers;
-- == Wiki Renderer ==
-- The <tt>Wiki_Renderer</tt> allows to render a wiki document into another wiki content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Wiki is
use Standard.Wiki.Attributes;
use Ada.Strings.Wide_Wide_Unbounded;
-- ------------------------------
-- Wiki to HTML writer
-- ------------------------------
type Wiki_Renderer is new Standard.Wiki.Documents.Document_Reader with private;
-- Set the output writer.
procedure Set_Writer (Document : in out Wiki_Renderer;
Writer : in Writers.Writer_Type_Access;
Format : in Parsers.Wiki_Syntax_Type);
-- Add a section header in the document.
overriding
procedure Add_Header (Document : in out Wiki_Renderer;
Header : in Unbounded_Wide_Wide_String;
Level : in Positive);
-- Add a line break (<br>).
overriding
procedure Add_Line_Break (Document : in out Wiki_Renderer);
-- Add a paragraph (<p>). Close the previous paragraph if any.
-- The paragraph must be closed at the next paragraph or next header.
overriding
procedure Add_Paragraph (Document : in out Wiki_Renderer);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
overriding
procedure Add_Blockquote (Document : in out Wiki_Renderer;
Level : in Natural);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
overriding
procedure Add_List_Item (Document : in out Wiki_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Add an horizontal rule (<hr>).
overriding
procedure Add_Horizontal_Rule (Document : in out Wiki_Renderer);
-- Add a link.
overriding
procedure Add_Link (Document : in out Wiki_Renderer;
Name : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String;
Title : in Unbounded_Wide_Wide_String);
-- Add an image.
overriding
procedure Add_Image (Document : in out Wiki_Renderer;
Link : in Unbounded_Wide_Wide_String;
Alt : in Unbounded_Wide_Wide_String;
Position : in Unbounded_Wide_Wide_String;
Description : in Unbounded_Wide_Wide_String);
-- Add a quote.
overriding
procedure Add_Quote (Document : in out Wiki_Renderer;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String);
-- Add a text block with the given format.
overriding
procedure Add_Text (Document : in out Wiki_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Documents.Format_Map);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Document : in out Wiki_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String);
overriding
procedure Start_Element (Document : in out Wiki_Renderer;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Attribute_List_Type);
overriding
procedure End_Element (Document : in out Wiki_Renderer;
Name : in Unbounded_Wide_Wide_String);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Document : in out Wiki_Renderer);
private
type Wide_String_Access is access constant Wide_Wide_String;
type Wiki_Tag_Type is (Bold_Start, Bold_End, Italic_Start, Italic_End,
Underline_Start, Underline_End,
Header_Start, Header_End,
Line_Break,
Blockquote_Start, Blockquote_End);
type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access;
-- Emit a new line.
procedure New_Line (Document : in out Wiki_Renderer);
procedure Close_Paragraph (Document : in out Wiki_Renderer);
procedure Open_Paragraph (Document : in out Wiki_Renderer);
type List_Style_Array is array (1 .. 32) of Boolean;
EMPTY_TAG : aliased constant Wide_Wide_String := "";
type Wiki_Renderer is new Documents.Document_Reader with record
Writer : Writers.Writer_Type_Access := null;
Syntax : Parsers.Wiki_Syntax_Type := Parsers.SYNTAX_CREOLE;
Format : Documents.Format_Map := (others => False);
Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access);
Has_Paragraph : Boolean := False;
Has_Item : Boolean := False;
Need_Paragraph : Boolean := False;
Empty_Line : Boolean := True;
Current_Level : Natural := 0;
Quote_Level : Natural := 0;
end record;
end Wiki.Render.Wiki;
|
Define the Wiki renderer type to render the result in Wiki text
|
Define the Wiki renderer type to render the result in Wiki text
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
|
a566480ba1f88506ce1981c8fb924113243f4642
|
src/asis/asis-data_decomposition-extensions.ads
|
src/asis/asis-data_decomposition-extensions.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A S I S . D A T A _ D E C O M P O S I T I O N . E X T E N S I O N S --
-- --
-- S p e c --
-- --
-- Copyright (c) 1995-2008, 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, 59 Temple Place --
-- - Suite 330, Boston, MA 02111-1307, 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 Ada Core Technologies Inc --
-- (http://www.gnat.com). --
-- --
------------------------------------------------------------------------------
-- This package contains queries yielding various representation information
-- which may be useful for ASIS applications, and which can not be obtained
-- through the Asis.Data_Decomposition package as defined by the ASIS
-- Standard.
package Asis.Data_Decomposition.Extensions is
generic
type Constrained_Subtype is private;
function Portable_Data_Value
(Value : Constrained_Subtype)
return Portable_Data;
-- This is the inverse function for
-- Asis.Data_Decomposition.Portable_Constrained_Subtype. Instantiated with
-- an appropriate scalar type, (e.g., System.Integer, can be used to
-- convert value to a data stream that can be used by ASIS Data
-- Decomposition queries, in particular, for passing as an actual for the
-- Value parameter of
-- Asis.Data_Decomposition.Construct_Artificial_Data_Stream.
--
-- Instantiated with a record type, can be used to convert a value to a
-- data stream that can be analyzed by ASIS Data Decomposition queries.
function Component_Name_Definition
(Component : Record_Component)
return Asis.Declaration;
-- For the argument Compononent, returns the corresponding
-- A_Defining_Identified Element.
-- Asis.Data_Decomposition.Component_Declaration query can not be used to
-- determine the name of the component in case if two or more record
-- components are defined by the same component declaration or discriminant
-- specification, that's why this query may be needed.
--
-- All non-Nil component values are appropriate.
--
-- Returns Defining_Name_Kinds:
-- A_Defining_Identifier
----------------------------
-- Static type attributes --
----------------------------
-- Queries defined in this section returns static representation
-- attributes of types and subtypes. Some, but not all of the attributes
-- defined in RM 95 which return representation information about types
-- and subtypes and which are not functions are mapped onto
-- Asis.Data_Decomposition.Extensions queries.
-- --|AN Application Note:
--
-- In contrast to Asis.Data_Decomposition queries which operates on type
-- definitions, these queries operates on type and subtype defining names.
-- The reason is that type and its subtypes may have different values of
-- the same representation attribute, and this difference may be
-- important for application.
--------------------------------------------------------
-- Floating Point Types and Decimal Fixed Point Types --
--------------------------------------------------------
function Digits_Value
(Floating_Point_Subtype : Asis.Element)
return ASIS_Natural;
-- Provided that Floating_Point_Subtype is the defining name of some
-- floating point or decimal fixed point type or subtype (including types
-- derived from floating point or decimal fixed point types), this
-- function returns the requested decimal precision for this type or
-- subtype, as defined in RM 95, 3.5.8(2), 3.5.10(7)
--
-- Appropriate Defining_Name_Kinds
-- A_Defining_Identifier, provided that it defines some floating
-- point or decimal fixed point type
-- or subtype
-----------------------------------------------------
-- Fixed Point Types and Decimal Fixed Point Types --
-----------------------------------------------------
-- --|AN Application Note:
--
-- For fixed point types, it is important to return the precise values of
-- 'small' and 'delta'. The corresponding Ada attributes 'Small and 'Delta
-- are defined in RM95 as being of universal_real type. But in this unit,
-- we can not use universal_real as a return type of a query, and using
-- any explicitly defined real type can not guarantee that the exact
-- values of 'small' and 'delta' will be returned by the corresponding
-- queries, since these values have arbitrary exact precision.
--
-- To represent the value of universal_real type, the Small_Value
-- and Delta_Value functions return a pair of integers representing
-- the normalized fraction with integer numerator and denominator
-- ("normalized means that the fraction is reduced to lowest terms),
-- or alternatively a string is returned that contains the fraction
-- represented in this manner. The latter form is the only one that
-- can be used if the numerator or denominator is outside the range
-- of ASIS_Integer.
type Fraction is record
Num : ASIS_Integer;
Denum : ASIS_Positive;
end record;
function Small_Value
(Fixed_Point_Subtype : Asis.Element)
return String;
-- Provided that Fixed_Point_Subtype is the defining name of some
-- fixed point type or subtype (including types derived from fixed
-- point types), this function returns the string image of 'small' of
-- this type or subtype, as defined in RM 95, 3.5.10(2) as a string
-- value representing a fraction (numerator / denominator), with no
-- spaces, and both numerator and denominator represented in decimal.
--
-- Appropriate Defining_Name_Kinds
-- A_Defining_Identifier, provided that it defines some fixed point
-- or decimal fixed point type or subtype
function Small_Value
(Fixed_Point_Subtype : Asis.Element)
return Fraction;
-- Provided that Fixed_Point_Subtype is the defining name of some
-- fixed point type or subtype (including types derived from fixed
-- point types), this function returns the fraction representation of
-- 'small' of this type or subtype, as defined in RM 95, 3.5.10(2)
-- ASIS_Failed is raised and the corresponding Diagnosis tring is set
-- if the numerator or denominator is outside the representable range.
--
-- Appropriate Defining_Name_Kinds
-- A_Defining_Identifier, provided that it defines some fixed point
-- or decimal fixed point type or subtype
function Delta_Value
(Fixed_Point_Subtype : Asis.Element)
return String;
-- Provided that Fixed_Point_Subtype is the defining name of some
-- fixed point type or subtype (including types derived from fixed
-- point types), this function returns the string image of 'delta' of
-- this type or subtype, as defined in RM 95, 3.5.10(2) as a string
-- value representing a fraction (numerator / denominator), with no
-- spaces, and both numerator and denominator represented in decimal.
--
-- Appropriate Defining_Name_Kinds
-- A_Defining_Identifier, provided that it defines some fixed point
-- or decimal fixed point type or subtype
function Delta_Value
(Fixed_Point_Subtype : Asis.Element)
return Fraction;
-- Provided that Fixed_Point_Subtype is the defining name of some
-- fixed point type or subtype (including types derived from fixed
-- point types), this function returns the fraction representation of
-- 'delta' of this type or subtype, as defined in RM 95, 3.5.10(3)
-- ASIS_Failed is raised and the corresponding Diagnosis tring is set
-- if the numerator or denominator is outside the representable range.
--
-- Appropriate Defining_Name_Kinds
-- A_Defining_Identifier, provided that it defines some fixed point
-- or decimal fixed point type or subtype
----------------------
-- Other Attributes --
----------------------
-- The current version of Asis.Data_Decomposition.Extensions does not
-- provide queries for the 'Fore or 'Aft attributes of fixed point types.
-------------------------------
-- Decimal Fixed Point Types --
-------------------------------
function Scale_Value
(Desimal_Fixed_Point_Subtype : Asis.Element)
return ASIS_Natural;
-- Provided that Desimal_Fixed_Point_Subtype is the defining name of some
-- decimal fixed point type or subtype (including types derived from
-- decimal fixed point types), this function returns the scale of
-- this type or subtype, as defined in RM 95 3.5.10(11).
--
-- Appropriate Defining_Name_Kinds
-- A_Defining_Identifier, provided that it defines some decimal fixed
-- point type or subtype
end Asis.Data_Decomposition.Extensions;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
|
decb8467b350bcb932e8d324a37ffa627de6b094
|
src/base/beans/util-beans-objects-iterators.adb
|
src/base/beans/util-beans-objects-iterators.adb
|
-----------------------------------------------------------------------
-- util-beans-objects-iterators -- Iterators for objects
-- Copyright (C) 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Beans.Basic;
package body Util.Beans.Objects.Iterators is
-- ------------------------------
-- Returns True if the iterator provides a key for each element.
-- ------------------------------
function Has_Key (Iter : in Iterator) return Boolean is
begin
return Iter.Iter /= null and then Iter.Iter.all in Proxy_Map_Iterator'Class;
end Has_Key;
-- ------------------------------
-- Returns True if the iterator has an element.
-- ------------------------------
function Has_Element (Iter : in Iterator) return Boolean is
begin
return Iter.Iter /= null and then Iter.Iter.Has_Element;
end Has_Element;
-- ------------------------------
-- Returns the current iterator element or Null_Object if it is empty.
-- ------------------------------
function Element (Iter : in Iterator) return Object is
begin
if Iter.Iter = null then
return Null_Object;
else
return Object (Iter.Iter.Element);
end if;
end Element;
-- ------------------------------
-- Returns the key associated with the current element.
-- ------------------------------
function Key (Iter : in Iterator) return String is
begin
if Iter.Iter = null then
return "";
elsif not (Iter.Iter.all in Proxy_Map_Iterator'Class) then
return "";
else
return Proxy_Map_Iterator'Class (Iter.Iter.all).Key;
end if;
end Key;
-- ------------------------------
-- Move the iterator to the next element.
-- ------------------------------
procedure Next (Iter : in out Iterator) is
begin
if Iter.Iter /= null then
Iter.Iter.Next;
end if;
end Next;
-- ------------------------------
-- Move the iterator to the previous element.
-- ------------------------------
procedure Previous (Iter : in out Iterator) is
begin
if Iter.Iter /= null then
Iter.Iter.Previous;
end if;
end Previous;
overriding
procedure Adjust (Iter : in out Iterator) is
begin
if Iter.Iter /= null then
Util.Concurrent.Counters.Increment (Iter.Iter.Ref_Counter);
end if;
end Adjust;
procedure Free is
new Ada.Unchecked_Deallocation (Object => Proxy_Iterator'Class,
Name => Proxy_Iterator_Access);
overriding
procedure Finalize (Iter : in out Iterator) is
Release : Boolean;
begin
if Iter.Iter /= null then
Util.Concurrent.Counters.Decrement (Iter.Iter.Ref_Counter, Release);
if Release then
Free (Iter.Iter);
else
Iter.Iter := null;
end if;
end if;
end Finalize;
-- ------------------------------
-- Create an iterator to iterate from the first element.
-- ------------------------------
function First (Item : in Object) return Iterator is
Iter : Iterator;
begin
if Item.V.Of_Type /= TYPE_BEAN then
return Iter;
end if;
if Item.V.Proxy = null then
return Iter;
end if;
declare
Proxy : constant Bean_Proxy_Access := Item.V.Proxy;
List : Iterator_Bean_Access;
begin
if not (Bean_Proxy (Proxy.all).Bean.all in Iterator_Bean'Class) then
return Iter;
end if;
List := Iterator_Bean'Class (Bean_Proxy (Proxy.all).Bean.all)'Unchecked_Access;
Iter.Iter := List.First;
if Iter.Iter /= null then
Util.Concurrent.Counters.Increment (Iter.Iter.Ref_Counter);
Iter.Iter.Proxy := Proxy;
Util.Concurrent.Counters.Increment (Proxy.Ref_Counter);
end if;
end;
return Iter;
end First;
-- ------------------------------
-- Create an iterator to iterate from the last element.
-- ------------------------------
function Last (Item : in Object) return Iterator is
Iter : Iterator;
begin
if Item.V.Of_Type /= TYPE_BEAN then
return Iter;
end if;
if Item.V.Proxy = null then
return Iter;
end if;
declare
Proxy : constant Bean_Proxy_Access := Item.V.Proxy;
List : Iterator_Bean_Access;
begin
if not (Bean_Proxy (Proxy.all).Bean.all in Iterator_Bean'Class) then
return Iter;
end if;
List := Iterator_Bean'Class (Bean_Proxy (Proxy.all).Bean.all)'Unchecked_Access;
Iter.Iter := List.Last;
if Iter.Iter /= null then
Util.Concurrent.Counters.Increment (Iter.Iter.Ref_Counter);
Iter.Iter.Proxy := Proxy;
Util.Concurrent.Counters.Increment (Proxy.Ref_Counter);
end if;
end;
return Iter;
end Last;
package body Iter is
overriding
function First (Object : in Forward_Iterator) return Iterator is
begin
return Object.Iter;
end First;
overriding
function Next (Object : in Forward_Iterator;
Pos : in Iterator) return Iterator is
Result : Iterator := Pos;
begin
Next (Result);
return Result;
end Next;
end Iter;
function Iterate (Item : in Object) return
Object_Iterator_Interfaces.Forward_Iterator'Class is
begin
return Result : Iter.Forward_Iterator do
Result.Iter := First (Item);
end return;
end Iterate;
overriding
procedure Finalize (Proxy : in out Proxy_Iterator) is
Release : Boolean;
begin
if Proxy.Proxy /= null then
Util.Concurrent.Counters.Decrement (Proxy.Proxy.Ref_Counter, Release);
if Release then
Free (Proxy.Proxy);
else
Proxy.Proxy := null;
end if;
end if;
end Finalize;
function Get_Bean (Iter : in Proxy_Iterator'Class) return T_Access is
begin
if Iter.Proxy = null then
return null;
end if;
if not (Bean_Proxy (Iter.Proxy.all).Bean.all in T'Class) then
return null;
end if;
return T'Class (Bean_Proxy (Iter.Proxy.all).Bean.all)'Unchecked_Access;
end Get_Bean;
end Util.Beans.Objects.Iterators;
|
Implement the Iterators operations
|
Implement the Iterators operations
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
|
f9490a804be74485a790bea5cee9206a8bdeeca4
|
src/asis/a4g-a_elists.adb
|
src/asis/a4g-a_elists.adb
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . A _ E L I S T S --
-- --
-- B o d y --
-- --
-- Copyright (C) 1995-2007, Free Software Foundation, Inc. --
-- --
-- ASIS-for-GNAT is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 2, or (at your option) any later --
-- version. ASIS-for-GNAT is distributed in the hope that it will be use- --
-- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- --
-- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General --
-- Public License for more details. You should have received a copy of the --
-- GNU General Public License distributed with ASIS-for-GNAT; see file --
-- COPYING. If not, write to the Free Software Foundation, 51 Franklin --
-- Street, Fifth Floor, Boston, MA 02110-1301, USA. --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the --
-- Software Engineering Laboratory of the Swiss Federal Institute of --
-- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the --
-- Scientific Research Computer Center of Moscow State University (SRCC --
-- MSU), Russia, with funding partially provided by grants from the Swiss --
-- National Science Foundation and the Swiss Academy of Engineering --
-- Sciences. ASIS-for-GNAT is now maintained by AdaCore --
-- (http://www.adaccore.com). --
-- --
------------------------------------------------------------------------------
-- This is the modification of the GNAT Elists package. See spec for the
-- description of the modifications.
with A4G.A_Debug; use A4G.A_Debug;
with Output; use Output;
package body A4G.A_Elists is
----------------------
-- Add_To_Elmt_List --
----------------------
procedure Add_To_Elmt_List (Unit : Unit_Id; List : in out Elist_Id) is
begin
if No (List) then
List := New_Elmt_List;
Append_Elmt (Unit, List);
elsif not In_Elmt_List (Unit, List) then
Append_Elmt (Unit, List);
end if;
end Add_To_Elmt_List;
-----------------
-- Append_Elmt --
-----------------
procedure Append_Elmt (Unit : Unit_Id; To : Elist_Id) is
L : constant Elmt_Id := Elists.Table (To).Last;
begin
Elmts.Increment_Last;
Elmts.Table (Elmts.Last).Unit := Unit;
Elmts.Table (Elmts.Last).Next := Union_Id (To);
if L = No_Elmt then
Elists.Table (To).First := Elmts.Last;
else
Elmts.Table (L).Next := Union_Id (Elmts.Last);
end if;
Elists.Table (To).Last := Elmts.Last;
if Debug_Flag_N then
Write_Str ("Append new element Elmt_Id = ");
Write_Int (Int (Elmts.Last));
Write_Str (" to list Elist_Id = ");
Write_Int (Int (To));
Write_Str (" referencing Unit_Id = ");
Write_Int (Int (Unit));
Write_Eol;
end if;
end Append_Elmt;
------------------
-- Prepend_Elmt --
------------------
procedure Prepend_Elmt (Unit : Unit_Id; To : Elist_Id) is
F : constant Elmt_Id := Elists.Table (To).First;
begin
Elmts.Increment_Last;
Elmts.Table (Elmts.Last).Unit := Unit;
if F = No_Elmt then
Elists.Table (To).Last := Elmts.Last;
Elmts.Table (Elmts.Last).Next := Union_Id (To);
else
Elmts.Table (Elmts.Last).Next := Union_Id (F);
end if;
Elists.Table (To).First := Elmts.Last;
end Prepend_Elmt;
-----------------------
-- Insert_Elmt_After --
-----------------------
procedure Insert_Elmt_After (Unit : Unit_Id; Elmt : Elmt_Id) is
N : constant Union_Id := Elmts.Table (Elmt).Next;
begin
pragma Assert (Elmt /= No_Elmt);
Elmts.Increment_Last;
Elmts.Table (Elmts.Last).Unit := Unit;
Elmts.Table (Elmts.Last).Next := N;
Elmts.Table (Elmt).Next := Union_Id (Elmts.Last);
if N in Elist_Range then
Elists.Table (Elist_Id (N)).Last := Elmts.Last;
end if;
end Insert_Elmt_After;
-------------
-- Belongs --
-------------
function Belongs (List1 : Elist_Id; List2 : Elist_Id) return Boolean is
Curr_Elmt : Elmt_Id;
begin
if No (List1) or else Is_Empty_Elmt_List (List1) then
return True;
end if;
Curr_Elmt := First_Elmt (List1);
while Present (Curr_Elmt) loop
if not In_Elmt_List (Unit (Curr_Elmt), List2) then
return False;
end if;
Curr_Elmt := Next_Elmt (Curr_Elmt);
end loop;
return True;
end Belongs;
----------------
-- First_Elmt --
----------------
function First_Elmt (List : Elist_Id) return Elmt_Id is
begin
pragma Assert (List > Elist_Low_Bound);
return Elists.Table (List).First;
end First_Elmt;
----------------
-- Initialize --
----------------
procedure Initialize is
begin
Elists.Init;
Elmts.Init;
end Initialize;
------------------
-- In_Elmt_List --
------------------
function In_Elmt_List (U : Unit_Id; List : Elist_Id) return Boolean is
Curr_Elmt : Elmt_Id;
begin
if No (List) or else Is_Empty_Elmt_List (List) then
return False;
end if;
Curr_Elmt := First_Elmt (List);
while Present (Curr_Elmt) loop
if U = Unit (Curr_Elmt) then
return True;
end if;
Curr_Elmt := Next_Elmt (Curr_Elmt);
end loop;
return False;
end In_Elmt_List;
---------------
-- Intersect --
---------------
function Intersect (List1 : Elist_Id; List2 : Elist_Id) return Boolean is
Curr_Elmt : Elmt_Id;
begin
if No (List1) or else No (List2) or else
Is_Empty_Elmt_List (List1) or else
Is_Empty_Elmt_List (List2)
then
return False;
else
Curr_Elmt := First_Elmt (List1);
while Present (Curr_Elmt) loop
if In_Elmt_List (Unit (Curr_Elmt), List2) then
return True;
end if;
Curr_Elmt := Next_Elmt (Curr_Elmt);
end loop;
return False;
end if;
end Intersect;
------------------------
-- Is_Empty_Elmt_List --
------------------------
function Is_Empty_Elmt_List (List : Elist_Id) return Boolean is
begin
return Elists.Table (List).First = No_Elmt;
end Is_Empty_Elmt_List;
-------------------
-- Last_Elist_Id --
-------------------
function Last_Elist_Id return Elist_Id is
begin
return Elists.Last;
end Last_Elist_Id;
---------------
-- Last_Elmt --
---------------
function Last_Elmt (List : Elist_Id) return Elmt_Id is
begin
return Elists.Table (List).Last;
end Last_Elmt;
------------------
-- Last_Elmt_Id --
------------------
function Last_Elmt_Id return Elmt_Id is
begin
return Elmts.Last;
end Last_Elmt_Id;
-----------------
-- List_Length --
-----------------
function List_Length (List : Elist_Id) return Natural is
Result : Natural := 0;
Elem : Elmt_Id;
begin
Elem := First_Elmt (List);
while Present (Elem) loop
Result := Result + 1;
Elem := Next_Elmt (Elem);
end loop;
return Result;
end List_Length;
---------------
-- Move_List --
---------------
procedure Move_List
(List_From : Elist_Id;
List_To : in out Elist_Id)
is
begin
if No (List_To) then
List_To := New_Elmt_List;
end if;
if No (List_From) or else Is_Empty_Elmt_List (List_From) then
return;
end if;
-- if we are here, we have to move elements...
if Is_Empty_Elmt_List (List_To) then
Elists.Table (List_To).Last := Elists.Table (List_From).Last;
Elmts.Table (Elists.Table (List_From).Last).Next :=
Union_Id (List_To);
else
Elmts.Table (Elists.Table (List_From).Last).Next :=
Elmts.Table (Elists.Table (List_To).First).Next;
end if;
Elists.Table (List_To).First := Elists.Table (List_From).First;
Elists.Table (List_From).First := No_Elmt;
Elists.Table (List_From).Last := No_Elmt;
end Move_List;
-------------------
-- New_Elmt_List --
-------------------
function New_Elmt_List return Elist_Id is
begin
Elists.Increment_Last;
Elists.Table (Elists.Last).First := No_Elmt;
Elists.Table (Elists.Last).Last := No_Elmt;
if Debug_Flag_N then
Write_Str ("Allocate new element list, returned ID = ");
Write_Int (Int (Elists.Last));
Write_Eol;
end if;
return Elists.Last;
end New_Elmt_List;
---------------
-- Next_Elmt --
---------------
function Next_Elmt (Elmt : Elmt_Id) return Elmt_Id is
N : constant Union_Id := Elmts.Table (Elmt).Next;
begin
if N in Elist_Range then
return No_Elmt;
else
return Elmt_Id (N);
end if;
end Next_Elmt;
--------
-- No --
--------
function No (List : Elist_Id) return Boolean is
begin
return List = No_Elist;
end No;
function No (Elmt : Elmt_Id) return Boolean is
begin
return Elmt = No_Elmt;
end No;
-----------
-- Unit --
-----------
function Unit (Elmt : Elmt_Id) return Unit_Id is
begin
if Elmt = No_Elmt then
return Nil_Unit;
else
return Elmts.Table (Elmt).Unit;
end if;
end Unit;
----------------
-- Num_Elists --
----------------
function Num_Elists return Nat is
begin
return Int (Elmts.Last) - Int (Elmts.First) + 1;
end Num_Elists;
-------------
-- Present --
-------------
function Present (List : Elist_Id) return Boolean is
begin
return List /= No_Elist;
end Present;
function Present (Elmt : Elmt_Id) return Boolean is
begin
return Elmt /= No_Elmt;
end Present;
----------------
-- Print_List --
----------------
procedure Print_List (List : Elist_Id) is
Curr_Elmt : Elmt_Id;
Counter : Int := 1;
begin
if No (List) then
if Debug_Flag_N then
Write_Str (" There is no list here");
Write_Eol;
end if;
return;
end if;
if Is_Empty_Elmt_List (List) then
if Debug_Flag_N then
Write_Str (" The list is empty");
Write_Eol;
end if;
return;
end if;
if Debug_Flag_N then
Write_Str ("List contains the following Ids:");
Write_Eol;
end if;
Curr_Elmt := First_Elmt (List);
while Present (Curr_Elmt) loop
if Debug_Flag_N then
Write_Str (" Element number ");
Write_Int (Counter);
Write_Str (" is ");
Write_Int (Int (Unit (Curr_Elmt)));
Write_Eol;
end if;
Curr_Elmt := Next_Elmt (Curr_Elmt);
Counter := Counter + 1;
end loop;
end Print_List;
-----------------
-- Remove_Elmt --
-----------------
procedure Remove_Elmt (List : Elist_Id; Elmt : Elmt_Id) is
Nxt : Elmt_Id;
Prv : Elmt_Id;
begin
Nxt := Elists.Table (List).First;
-- Case of removing only element in the list
if Elmts.Table (Nxt).Next in Elist_Range then
pragma Assert (Nxt = Elmt);
Elists.Table (List).First := No_Elmt;
Elists.Table (List).Last := No_Elmt;
-- Case of removing the first element in the list
elsif Nxt = Elmt then
Elists.Table (List).First := Elmt_Id (Elmts.Table (Nxt).Next);
-- Case of removing second or later element in the list
else
loop
Prv := Nxt;
Nxt := Elmt_Id (Elmts.Table (Prv).Next);
exit when Nxt = Elmt
or else Elmts.Table (Nxt).Next in Elist_Range;
end loop;
pragma Assert (Nxt = Elmt);
Elmts.Table (Prv).Next := Elmts.Table (Nxt).Next;
if Elmts.Table (Prv).Next in Elist_Range then
Elists.Table (List).Last := Prv;
end if;
end if;
end Remove_Elmt;
----------------------
-- Remove_Last_Elmt --
----------------------
procedure Remove_Last_Elmt (List : Elist_Id) is
Nxt : Elmt_Id;
Prv : Elmt_Id;
begin
Nxt := Elists.Table (List).First;
-- Case of removing only element in the list
if Elmts.Table (Nxt).Next in Elist_Range then
Elists.Table (List).First := No_Elmt;
Elists.Table (List).Last := No_Elmt;
-- Case of at least two elements in list
else
loop
Prv := Nxt;
Nxt := Elmt_Id (Elmts.Table (Prv).Next);
exit when Elmts.Table (Nxt).Next in Elist_Range;
end loop;
Elmts.Table (Prv).Next := Elmts.Table (Nxt).Next;
Elists.Table (List).Last := Prv;
end if;
end Remove_Last_Elmt;
------------------
-- Replace_Elmt --
------------------
procedure Replace_Elmt (Elmt : Elmt_Id; New_Unit : Unit_Id) is
begin
Elmts.Table (Elmt).Unit := New_Unit;
end Replace_Elmt;
end A4G.A_Elists;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
|
c9f14e6e0efee9b1ed0af2f5b487948cb5dd8557
|
src/asis/a4g-span_end.ads
|
src/asis/a4g-span_end.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . S P A N _ E N D --
-- --
-- S p e c --
-- --
-- Copyright (c) 1995-1999, 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, 59 Temple Place --
-- - Suite 330, Boston, MA 02111-1307, 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 Ada Core Technologies Inc --
-- (http://www.gnat.com). --
-- --
------------------------------------------------------------------------------
with Asis; use Asis;
with Types; use Types;
package A4G.Span_End is
-- This package encapsulates queries needed to find the end of Element's
-- Span (as the pointer to the Source Buffer).
function Set_Image_End (E : Asis.Element) return Source_Ptr;
-- This is the main function in this package. It returns the pointer
-- to the last character of the given element in the Source Buffer
end A4G.Span_End;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
|
0abbfb46276065c039af969bf26d573f46f6db83
|
src/asis/a4g-a_output.adb
|
src/asis/a4g-a_output.adb
|
------------------------------------------------------------------------------
-- --
-- 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;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
9d08ea139d2c4ea3357963cfdadf9daa5876f8f0
|
src/util-beans-objects-datasets.adb
|
src/util-beans-objects-datasets.adb
|
-----------------------------------------------------------------------
-- Util.Beans.Objects.Datasets -- Datasets
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Util.Beans.Objects.Datasets is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Object_Array,
Name => Object_Array_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Object => Dataset_Array,
Name => Dataset_Array_Access);
-- ------------------------------
-- Get the number of elements in the list.
-- ------------------------------
overriding
function Get_Count (From : in Dataset) return Natural is
begin
return From.Count;
end Get_Count;
-- ------------------------------
-- Set the current row index. Valid row indexes start at 1.
-- ------------------------------
overriding
procedure Set_Row_Index (From : in out Dataset;
Index : in Natural) is
begin
From.Current_Pos := Index;
From.Current.Data := From.Data (Index);
end Set_Row_Index;
-- ------------------------------
-- Get the element at the current row index.
-- ------------------------------
overriding
function Get_Row (From : in Dataset) return Util.Beans.Objects.Object is
begin
return From.Row;
end Get_Row;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Dataset;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "count" then
return Util.Beans.Objects.To_Object (From.Count);
elsif Name = "rowIndex" then
return Util.Beans.Objects.To_Object (From.Current_Pos);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Append a row in the dataset and call the fill procedure to populate
-- the row content.
-- ------------------------------
procedure Append (Into : in out Dataset;
Fill : not null access procedure (Data : in out Object_Array)) is
Data : constant Object_Array_Access := new Object_Array (1 .. Into.Columns);
begin
if Into.Data = null then
Into.Data := new Dataset_Array (1 .. 10);
elsif Into.Count >= Into.Data'Last then
declare
-- Sun's Java ArrayList use a 2/3 grow factor.
-- Python's array use 8/9.
Grow : constant Positive := (Into.Count * 2) / 3;
Set : constant Dataset_Array_Access := new Dataset_Array (1 .. Grow);
begin
Set (Into.Data'Range) := Into.Data.all;
Free (Into.Data);
Into.Data := Set;
end;
end if;
Into.Count := Into.Count + 1;
Into.Data (Into.Count) := Data;
Fill (Data.all);
end Append;
-- ------------------------------
-- Add a column to the dataset. If the position is not specified,
-- the column count is incremented and the name associated with the last column.
-- Raises Invalid_State exception if the dataset contains some rows,
-- ------------------------------
procedure Add_Column (Into : in out Dataset;
Name : in String;
Pos : in Natural := 0) is
Col : Positive;
begin
if Into.Count /= 0 then
raise Invalid_State with "The dataset contains some rows.";
end if;
if Pos = 0 then
Col := Into.Columns + 1;
else
Col := Pos;
end if;
Into.Map.Insert (Name, Col);
if Into.Columns < Col then
Into.Columns := Col;
end if;
end Add_Column;
-- ------------------------------
-- Clear the content of the dataset.
-- ------------------------------
procedure Clear (Set : in out Dataset) is
begin
for I in 1 .. Set.Count loop
Free (Set.Data (I));
end loop;
Set.Count := 0;
Set.Current_Pos := 0;
Set.Current.Data := null;
end Clear;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Row;
Name : in String) return Util.Beans.Objects.Object is
Pos : constant Dataset_Map.Cursor := From.Map.Find (Name);
begin
if From.Data /= null and then Dataset_Map.Has_Element (Pos) then
return From.Data (Dataset_Map.Element (Pos));
else
return Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out Row;
Name : in String;
Value : in Util.Beans.Objects.Object) is
Pos : constant Dataset_Map.Cursor := From.Map.Find (Name);
begin
if From.Data /= null and then Dataset_Map.Has_Element (Pos) then
From.Data (Dataset_Map.Element (Pos)) := Value;
end if;
end Set_Value;
-- ------------------------------
-- Initialize the dataset and the row bean instance.
-- ------------------------------
overriding
procedure Initialize (Set : in out Dataset) is
begin
Set.Row := To_Object (Value => Set.Current'Unchecked_Access,
Storage => STATIC);
Set.Current.Map := Set.Map'Unchecked_Access;
end Initialize;
-- ------------------------------
-- Release the dataset storage.
-- ------------------------------
overriding
procedure Finalize (Set : in out Dataset) is
begin
Set.Clear;
Free (Set.Data);
end Finalize;
end Util.Beans.Objects.Datasets;
|
Implement the Datasets package
|
Implement the Datasets package
|
Ada
|
apache-2.0
|
flottokarotto/ada-util,Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util
|
|
989a543bff624ffd95e9e475a6edeed9b8226915
|
regtests/util-strings-tests.adb
|
regtests/util-strings-tests.adb
|
-----------------------------------------------------------------------
-- strings.tests -- Unit tests for strings
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings;
with Ada.Strings.Unbounded;
with Ada.Strings.Fixed;
with Ada.Strings.Unbounded.Hash;
with Util.Test_Caller;
with Util.Strings.Transforms;
with Util.Strings.Maps;
with Util.Perfect_Hash;
with Ada.Streams;
with Util.Measures;
package body Util.Strings.Tests is
use Ada.Strings.Unbounded;
use Util.Tests;
use Util.Strings.Transforms;
package Caller is new Util.Test_Caller (Test, "Strings");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Strings.Transforms.Escape_Javascript",
Test_Escape_Javascript'Access);
Caller.Add_Test (Suite, "Test Util.Strings.Transforms.Escape_Xml",
Test_Escape_Xml'Access);
Caller.Add_Test (Suite, "Test Util.Strings.Transforms.Capitalize",
Test_Capitalize'Access);
Caller.Add_Test (Suite, "Test Util.Strings.Transforms.To_Upper_Case",
Test_To_Upper_Case'Access);
Caller.Add_Test (Suite, "Test Util.Strings.Transforms.To_Lower_Case",
Test_To_Lower_Case'Access);
Caller.Add_Test (Suite, "Test Util.Strings.Transforms.To_Hex",
Test_To_Hex'Access);
Caller.Add_Test (Suite, "Test Measure",
Test_Measure_Copy'Access);
Caller.Add_Test (Suite, "Test Util.Strings.Index",
Test_Index'Access);
Caller.Add_Test (Suite, "Test Util.Strings.Rindex",
Test_Rindex'Access);
Caller.Add_Test (Suite, "Test Util.Strings.Benchmark",
Test_Measure_Hash'Access);
Caller.Add_Test (Suite, "Test Util.Strings.String_Ref",
Test_String_Ref'Access);
Caller.Add_Test (Suite, "Test perfect hash",
Test_Perfect_Hash'Access);
end Add_Tests;
procedure Test_Escape_Javascript (T : in out Test) is
Result : Unbounded_String;
begin
Escape_Javascript (Content => ASCII.LF & " ""a string"" a 'single quote'",
Into => Result);
Assert_Equals (T, "\n \""a string\"" a \'single quote\'", Result);
Result := To_Unbounded_String ("");
Escape_Javascript (Content => ASCII.ESC & "[m " & Character'Val (255),
Into => Result);
Assert_Equals (T, "\u001B[m \u00FF", Result);
end Test_Escape_Javascript;
procedure Test_Escape_Xml (T : in out Test) is
Result : Unbounded_String;
begin
Escape_Xml (Content => ASCII.LF & " < ""a string"" a 'single quote' >& ",
Into => Result);
Assert_Equals (T, ASCII.LF & " < ""a string"" a 'single quote' >& ",
Result);
Result := To_Unbounded_String ("");
Escape_Xml (Content => ASCII.ESC & "[m " & Character'Val (255),
Into => Result);
Assert_Equals (T, ASCII.ESC & "[m ÿ", Result);
end Test_Escape_Xml;
procedure Test_Capitalize (T : in out Test) is
Result : Unbounded_String;
begin
Assert_Equals (T, "Capitalize_A_String", Capitalize ("capITalIZe_a_strING"));
Capitalize ("CapAS_String", Result);
Assert_Equals (T, "Capas_String", Result);
end Test_Capitalize;
procedure Test_To_Upper_Case (T : in out Test) is
begin
Assert_Equals (T, "UPPERCASE_0123_STR", To_Upper_Case ("upperCase_0123_str"));
end Test_To_Upper_Case;
procedure Test_To_Lower_Case (T : in out Test) is
begin
Assert_Equals (T, "lowercase_0123_str", To_Lower_Case ("LowERCase_0123_STR"));
end Test_To_Lower_Case;
procedure Test_To_Hex (T : in out Test) is
Result : Unbounded_String;
begin
To_Hex (Result, Character'Val (23));
Assert_Equals (T, "\u0017", Result);
To_Hex (Result, Character'Val (31));
Assert_Equals (T, "\u0017\u001F", Result);
To_Hex (Result, Character'Val (255));
Assert_Equals (T, "\u0017\u001F\u00FF", Result);
end Test_To_Hex;
procedure Test_Measure_Copy (T : in out Test) is
pragma Unreferenced (T);
Buf : constant Ada.Streams.Stream_Element_Array (1 .. 10_024) := (others => 23);
pragma Suppress (All_Checks, Buf);
begin
declare
T : Util.Measures.Stamp;
R : Ada.Strings.Unbounded.Unbounded_String;
begin
for I in Buf'Range loop
Append (R, Character'Val (Buf (I)));
end loop;
Util.Measures.Report (T, "Stream transform using Append (1024 bytes)");
end;
declare
T : Util.Measures.Stamp;
R : Ada.Strings.Unbounded.Unbounded_String;
S : String (1 .. 10_024);
pragma Suppress (All_Checks, S);
begin
for I in Buf'Range loop
S (Natural (I)) := Character'Val (Buf (I));
end loop;
Append (R, S);
Util.Measures.Report (T, "Stream transform using temporary string (1024 bytes)");
end;
-- declare
-- T : Util.Measures.Stamp;
-- R : Ada.Strings.Unbounded.Unbounded_String;
-- P : constant Ptr := new String (1 .. Buf'Length);
--
-- pragma Suppress (All_Checks, P);
-- begin
-- for I in P'Range loop
-- P (I) := Character'Val (Buf (Ada.Streams.Stream_Element_Offset (I)));
-- end loop;
-- Ada.Strings.Unbounded.Aux.Set_String (R, P.all'Access);
-- Util.Measures.Report (T, "Stream transform using Aux string (1024 bytes)");
-- end;
end Test_Measure_Copy;
-- Test the Index operation
procedure Test_Index (T : in out Test) is
Str : constant String := "0123456789abcdefghijklmnopq";
begin
declare
St : Util.Measures.Stamp;
Pos : Integer;
begin
for I in 1 .. 10 loop
Pos := Index (Str, 'q');
end loop;
Util.Measures.Report (St, "Util.Strings.Index");
Assert_Equals (T, 27, Pos, "Invalid index position");
end;
declare
St : Util.Measures.Stamp;
Pos : Integer;
begin
for I in 1 .. 10 loop
Pos := Ada.Strings.Fixed.Index (Str, "q");
end loop;
Util.Measures.Report (St, "Ada.Strings.Fixed.Index");
Assert_Equals (T, 27, Pos, "Invalid index position");
end;
end Test_Index;
-- Test the Rindex operation
procedure Test_Rindex (T : in out Test) is
Str : constant String := "0123456789abcdefghijklmnopq";
begin
declare
St : Util.Measures.Stamp;
Pos : Natural;
begin
for I in 1 .. 10 loop
Pos := Rindex (Str, '0');
end loop;
Util.Measures.Report (St, "Util.Strings.Rindex");
Assert_Equals (T, 1, Pos, "Invalid rindex position");
end;
declare
St : Util.Measures.Stamp;
Pos : Natural;
begin
for I in 1 .. 10 loop
Pos := Ada.Strings.Fixed.Index (Str, "0", Ada.Strings.Backward);
end loop;
Util.Measures.Report (St, "Ada.Strings.Fixed.Rindex");
Assert_Equals (T, 1, Pos, "Invalid rindex position");
end;
end Test_Rindex;
package String_Map is new Ada.Containers.Hashed_Maps
(Key_Type => Unbounded_String,
Element_Type => Unbounded_String,
Hash => Hash,
Equivalent_Keys => "=");
package String_Ref_Map is new Ada.Containers.Hashed_Maps
(Key_Type => String_Ref,
Element_Type => String_Ref,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys);
-- Do some benchmark on String -> X hash mapped.
procedure Test_Measure_Hash (T : in out Test) is
KEY : aliased constant String := "testing";
Str_Map : Util.Strings.Maps.Map;
Ptr_Map : Util.Strings.String_Access_Map.Map;
Ref_Map : String_Ref_Map.Map;
Unb_Map : String_Map.Map;
Name : String_Access := new String '(KEY);
Ref : constant String_Ref := To_String_Ref (KEY);
begin
Str_Map.Insert (Name.all, Name.all);
Ptr_Map.Insert (Name.all'Access, Name.all'Access);
Unb_Map.Insert (To_Unbounded_String (KEY), To_Unbounded_String (KEY));
Ref_Map.Insert (Ref, Ref);
-- Performance of Hashed_Map Name_Access -> Name_Access
-- (the fastest hash)
declare
St : Util.Measures.Stamp;
Pos : constant Strings.String_Access_Map.Cursor := Ptr_Map.Find (KEY'Unchecked_Access);
Val : constant Name_Access := Util.Strings.String_Access_Map.Element (Pos);
begin
Util.Measures.Report (St, "Util.Strings.String_Access_Maps.Find+Element");
Assert_Equals (T, "testing", Val.all, "Invalid value returned");
end;
-- Performance of Hashed_Map String_Ref -> String_Ref
-- (almost same performance as Hashed_Map Name_Access -> Name_Access)
declare
St : Util.Measures.Stamp;
Pos : constant String_Ref_Map.Cursor := Ref_Map.Find (Ref);
Val : constant String_Ref := String_Ref_Map.Element (Pos);
begin
Util.Measures.Report (St, "Util.Strings.String_Ref_Maps.Find+Element");
Assert_Equals (T, "testing", String '(To_String (Val)), "Invalid value returned");
end;
-- Performance of Hashed_Map Unbounded_String -> Unbounded_String
-- (little overhead due to String copy made by Unbounded_String)
declare
St : Util.Measures.Stamp;
Pos : constant String_Map.Cursor := Unb_Map.Find (To_Unbounded_String (KEY));
Val : constant Unbounded_String := String_Map.Element (Pos);
begin
Util.Measures.Report (St, "Hashed_Maps<Unbounded,Unbounded..Find+Element");
Assert_Equals (T, "testing", Val, "Invalid value returned");
end;
-- Performance for Indefinite_Hashed_Map String -> String
-- (the slowest hash, string copy to get the result, pointer to key and element
-- in the hash map implementation)
declare
St : Util.Measures.Stamp;
Pos : constant Util.Strings.Maps.Cursor := Str_Map.Find (KEY);
Val : constant String := Util.Strings.Maps.Element (Pos);
begin
Util.Measures.Report (St, "Util.Strings.Maps.Find+Element");
Assert_Equals (T, "testing", Val, "Invalid value returned");
end;
Free (Name);
end Test_Measure_Hash;
-- ------------------------------
-- Test String_Ref creation
-- ------------------------------
procedure Test_String_Ref (T : in out Test) is
R1 : String_Ref := To_String_Ref ("testing a string");
begin
for I in 1 .. 1_000 loop
declare
S : constant String (1 .. I) := (others => 'x');
R2 : constant String_Ref := To_String_Ref (S);
begin
Assert_Equals (T, S, To_String (R2), "Invalid String_Ref");
T.Assert (R2 = S, "Invalid comparison");
Assert_Equals (T, I, Length (R2), "Invalid length");
R1 := R2;
T.Assert (R1 = R2, "Invalid String_Ref copy");
end;
end loop;
end Test_String_Ref;
-- Test perfect hash (samples/gperfhash)
procedure Test_Perfect_Hash (T : in out Test) is
begin
for I in Util.Perfect_Hash.Keywords'Range loop
declare
K : constant String := Util.Perfect_Hash.Keywords (I).all;
begin
Assert_Equals (T, I, Util.Perfect_Hash.Hash (K),
"Invalid hash");
Assert_Equals (T, I, Util.Perfect_Hash.Hash (To_Lower_Case (K)),
"Invalid hash");
Assert (T, Util.Perfect_Hash.Is_Keyword (K), "Keyword " & K & " is not a keyword");
Assert (T, Util.Perfect_Hash.Is_Keyword (To_Lower_Case (K)),
"Keyword " & K & " is not a keyword");
end;
end loop;
end Test_Perfect_Hash;
end Util.Strings.Tests;
|
-----------------------------------------------------------------------
-- strings.tests -- Unit tests for strings
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings;
with Ada.Strings.Unbounded;
with Ada.Strings.Fixed;
with Ada.Strings.Unbounded.Hash;
with Util.Test_Caller;
with Util.Strings.Transforms;
with Util.Strings.Maps;
with Util.Perfect_Hash;
with Ada.Streams;
with Util.Measures;
package body Util.Strings.Tests is
use Ada.Strings.Unbounded;
use Util.Tests;
use Util.Strings.Transforms;
package Caller is new Util.Test_Caller (Test, "Strings");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Strings.Transforms.Escape_Javascript",
Test_Escape_Javascript'Access);
Caller.Add_Test (Suite, "Test Util.Strings.Transforms.Escape_Xml",
Test_Escape_Xml'Access);
Caller.Add_Test (Suite, "Test Util.Strings.Transforms.Capitalize",
Test_Capitalize'Access);
Caller.Add_Test (Suite, "Test Util.Strings.Transforms.To_Upper_Case",
Test_To_Upper_Case'Access);
Caller.Add_Test (Suite, "Test Util.Strings.Transforms.To_Lower_Case",
Test_To_Lower_Case'Access);
Caller.Add_Test (Suite, "Test Util.Strings.Transforms.To_Hex",
Test_To_Hex'Access);
Caller.Add_Test (Suite, "Test Measure",
Test_Measure_Copy'Access);
Caller.Add_Test (Suite, "Test Util.Strings.Index",
Test_Index'Access);
Caller.Add_Test (Suite, "Test Util.Strings.Rindex",
Test_Rindex'Access);
Caller.Add_Test (Suite, "Test Util.Strings.Benchmark",
Test_Measure_Hash'Access);
Caller.Add_Test (Suite, "Test Util.Strings.String_Ref",
Test_String_Ref'Access);
Caller.Add_Test (Suite, "Test perfect hash",
Test_Perfect_Hash'Access);
end Add_Tests;
procedure Test_Escape_Javascript (T : in out Test) is
Result : Unbounded_String;
begin
Escape_Javascript (Content => ASCII.LF & " ""a string"" a 'single quote'",
Into => Result);
Assert_Equals (T, "\n \""a string\"" a \'single quote\'", Result);
Result := To_Unbounded_String ("");
Escape_Javascript (Content => ASCII.ESC & "[m " & Character'Val (255),
Into => Result);
Assert_Equals (T, "\u001B[m " & Character'Val (255), Result);
end Test_Escape_Javascript;
procedure Test_Escape_Xml (T : in out Test) is
Result : Unbounded_String;
begin
Escape_Xml (Content => ASCII.LF & " < ""a string"" a 'single quote' >& ",
Into => Result);
Assert_Equals (T, ASCII.LF & " < ""a string"" a 'single quote' >& ",
Result);
Result := To_Unbounded_String ("");
Escape_Xml (Content => ASCII.ESC & "[m " & Character'Val (255),
Into => Result);
Assert_Equals (T, ASCII.ESC & "[m ÿ", Result);
end Test_Escape_Xml;
procedure Test_Capitalize (T : in out Test) is
Result : Unbounded_String;
begin
Assert_Equals (T, "Capitalize_A_String", Capitalize ("capITalIZe_a_strING"));
Capitalize ("CapAS_String", Result);
Assert_Equals (T, "Capas_String", Result);
end Test_Capitalize;
procedure Test_To_Upper_Case (T : in out Test) is
begin
Assert_Equals (T, "UPPERCASE_0123_STR", To_Upper_Case ("upperCase_0123_str"));
end Test_To_Upper_Case;
procedure Test_To_Lower_Case (T : in out Test) is
begin
Assert_Equals (T, "lowercase_0123_str", To_Lower_Case ("LowERCase_0123_STR"));
end Test_To_Lower_Case;
procedure Test_To_Hex (T : in out Test) is
Result : Unbounded_String;
begin
To_Hex (Result, Character'Val (23));
Assert_Equals (T, "\u0017", Result);
To_Hex (Result, Character'Val (31));
Assert_Equals (T, "\u0017\u001F", Result);
To_Hex (Result, Character'Val (255));
Assert_Equals (T, "\u0017\u001F\u00FF", Result);
end Test_To_Hex;
procedure Test_Measure_Copy (T : in out Test) is
pragma Unreferenced (T);
Buf : constant Ada.Streams.Stream_Element_Array (1 .. 10_024) := (others => 23);
pragma Suppress (All_Checks, Buf);
begin
declare
T : Util.Measures.Stamp;
R : Ada.Strings.Unbounded.Unbounded_String;
begin
for I in Buf'Range loop
Append (R, Character'Val (Buf (I)));
end loop;
Util.Measures.Report (T, "Stream transform using Append (1024 bytes)");
end;
declare
T : Util.Measures.Stamp;
R : Ada.Strings.Unbounded.Unbounded_String;
S : String (1 .. 10_024);
pragma Suppress (All_Checks, S);
begin
for I in Buf'Range loop
S (Natural (I)) := Character'Val (Buf (I));
end loop;
Append (R, S);
Util.Measures.Report (T, "Stream transform using temporary string (1024 bytes)");
end;
-- declare
-- T : Util.Measures.Stamp;
-- R : Ada.Strings.Unbounded.Unbounded_String;
-- P : constant Ptr := new String (1 .. Buf'Length);
--
-- pragma Suppress (All_Checks, P);
-- begin
-- for I in P'Range loop
-- P (I) := Character'Val (Buf (Ada.Streams.Stream_Element_Offset (I)));
-- end loop;
-- Ada.Strings.Unbounded.Aux.Set_String (R, P.all'Access);
-- Util.Measures.Report (T, "Stream transform using Aux string (1024 bytes)");
-- end;
end Test_Measure_Copy;
-- Test the Index operation
procedure Test_Index (T : in out Test) is
Str : constant String := "0123456789abcdefghijklmnopq";
begin
declare
St : Util.Measures.Stamp;
Pos : Integer;
begin
for I in 1 .. 10 loop
Pos := Index (Str, 'q');
end loop;
Util.Measures.Report (St, "Util.Strings.Index");
Assert_Equals (T, 27, Pos, "Invalid index position");
end;
declare
St : Util.Measures.Stamp;
Pos : Integer;
begin
for I in 1 .. 10 loop
Pos := Ada.Strings.Fixed.Index (Str, "q");
end loop;
Util.Measures.Report (St, "Ada.Strings.Fixed.Index");
Assert_Equals (T, 27, Pos, "Invalid index position");
end;
end Test_Index;
-- Test the Rindex operation
procedure Test_Rindex (T : in out Test) is
Str : constant String := "0123456789abcdefghijklmnopq";
begin
declare
St : Util.Measures.Stamp;
Pos : Natural;
begin
for I in 1 .. 10 loop
Pos := Rindex (Str, '0');
end loop;
Util.Measures.Report (St, "Util.Strings.Rindex");
Assert_Equals (T, 1, Pos, "Invalid rindex position");
end;
declare
St : Util.Measures.Stamp;
Pos : Natural;
begin
for I in 1 .. 10 loop
Pos := Ada.Strings.Fixed.Index (Str, "0", Ada.Strings.Backward);
end loop;
Util.Measures.Report (St, "Ada.Strings.Fixed.Rindex");
Assert_Equals (T, 1, Pos, "Invalid rindex position");
end;
end Test_Rindex;
package String_Map is new Ada.Containers.Hashed_Maps
(Key_Type => Unbounded_String,
Element_Type => Unbounded_String,
Hash => Hash,
Equivalent_Keys => "=");
package String_Ref_Map is new Ada.Containers.Hashed_Maps
(Key_Type => String_Ref,
Element_Type => String_Ref,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys);
-- Do some benchmark on String -> X hash mapped.
procedure Test_Measure_Hash (T : in out Test) is
KEY : aliased constant String := "testing";
Str_Map : Util.Strings.Maps.Map;
Ptr_Map : Util.Strings.String_Access_Map.Map;
Ref_Map : String_Ref_Map.Map;
Unb_Map : String_Map.Map;
Name : String_Access := new String '(KEY);
Ref : constant String_Ref := To_String_Ref (KEY);
begin
Str_Map.Insert (Name.all, Name.all);
Ptr_Map.Insert (Name.all'Access, Name.all'Access);
Unb_Map.Insert (To_Unbounded_String (KEY), To_Unbounded_String (KEY));
Ref_Map.Insert (Ref, Ref);
-- Performance of Hashed_Map Name_Access -> Name_Access
-- (the fastest hash)
declare
St : Util.Measures.Stamp;
Pos : constant Strings.String_Access_Map.Cursor := Ptr_Map.Find (KEY'Unchecked_Access);
Val : constant Name_Access := Util.Strings.String_Access_Map.Element (Pos);
begin
Util.Measures.Report (St, "Util.Strings.String_Access_Maps.Find+Element");
Assert_Equals (T, "testing", Val.all, "Invalid value returned");
end;
-- Performance of Hashed_Map String_Ref -> String_Ref
-- (almost same performance as Hashed_Map Name_Access -> Name_Access)
declare
St : Util.Measures.Stamp;
Pos : constant String_Ref_Map.Cursor := Ref_Map.Find (Ref);
Val : constant String_Ref := String_Ref_Map.Element (Pos);
begin
Util.Measures.Report (St, "Util.Strings.String_Ref_Maps.Find+Element");
Assert_Equals (T, "testing", String '(To_String (Val)), "Invalid value returned");
end;
-- Performance of Hashed_Map Unbounded_String -> Unbounded_String
-- (little overhead due to String copy made by Unbounded_String)
declare
St : Util.Measures.Stamp;
Pos : constant String_Map.Cursor := Unb_Map.Find (To_Unbounded_String (KEY));
Val : constant Unbounded_String := String_Map.Element (Pos);
begin
Util.Measures.Report (St, "Hashed_Maps<Unbounded,Unbounded..Find+Element");
Assert_Equals (T, "testing", Val, "Invalid value returned");
end;
-- Performance for Indefinite_Hashed_Map String -> String
-- (the slowest hash, string copy to get the result, pointer to key and element
-- in the hash map implementation)
declare
St : Util.Measures.Stamp;
Pos : constant Util.Strings.Maps.Cursor := Str_Map.Find (KEY);
Val : constant String := Util.Strings.Maps.Element (Pos);
begin
Util.Measures.Report (St, "Util.Strings.Maps.Find+Element");
Assert_Equals (T, "testing", Val, "Invalid value returned");
end;
Free (Name);
end Test_Measure_Hash;
-- ------------------------------
-- Test String_Ref creation
-- ------------------------------
procedure Test_String_Ref (T : in out Test) is
R1 : String_Ref := To_String_Ref ("testing a string");
begin
for I in 1 .. 1_000 loop
declare
S : constant String (1 .. I) := (others => 'x');
R2 : constant String_Ref := To_String_Ref (S);
begin
Assert_Equals (T, S, To_String (R2), "Invalid String_Ref");
T.Assert (R2 = S, "Invalid comparison");
Assert_Equals (T, I, Length (R2), "Invalid length");
R1 := R2;
T.Assert (R1 = R2, "Invalid String_Ref copy");
end;
end loop;
end Test_String_Ref;
-- Test perfect hash (samples/gperfhash)
procedure Test_Perfect_Hash (T : in out Test) is
begin
for I in Util.Perfect_Hash.Keywords'Range loop
declare
K : constant String := Util.Perfect_Hash.Keywords (I).all;
begin
Assert_Equals (T, I, Util.Perfect_Hash.Hash (K),
"Invalid hash");
Assert_Equals (T, I, Util.Perfect_Hash.Hash (To_Lower_Case (K)),
"Invalid hash");
Assert (T, Util.Perfect_Hash.Is_Keyword (K), "Keyword " & K & " is not a keyword");
Assert (T, Util.Perfect_Hash.Is_Keyword (To_Lower_Case (K)),
"Keyword " & K & " is not a keyword");
end;
end loop;
end Test_Perfect_Hash;
end Util.Strings.Tests;
|
Update the unit test
|
Update the unit test
|
Ada
|
apache-2.0
|
Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util,Letractively/ada-util
|
2377ad4f92c4f08346af1fbb34146ca8f44a3598
|
src/asis/a4g-a_sinput.adb
|
src/asis/a4g-a_sinput.adb
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . A _ S I N P U T --
-- --
-- B o d y --
-- --
-- Copyright (C) 1995-2010, 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.Characters.Handling; use Ada.Characters.Handling;
with System.WCh_Con; use System.WCh_Con;
with Asis.Set_Get; use Asis.Set_Get;
with Atree; use Atree;
with Opt; use Opt;
with Sinfo; use Sinfo;
with Sinput; use Sinput;
with Widechar; use Widechar;
package body A4G.A_Sinput is
use ASCII;
-- Make control characters visible
-----------------------
-- Local subprograms --
-----------------------
procedure Skip_Comment (P : in out Source_Ptr);
-- When P is set on the first '-' of a comment, this procedure resets
-- the value of P to the first character of the group of control
-- characters signifying the end of line containing the comment
-- initially indicated by P.
--
-- This procedure should not be used for the last comment in the
-- group of comments following a compilation unit in a compilation.
procedure Skip_String (P : in out Source_Ptr);
-- When P set on the first quoter of a string literal (it may be '"' or
-- '%', this procedure resets the value of P to the first character
-- after the literal.
-------------------------
-- A_Get_Column_Number --
-------------------------
function A_Get_Column_Number (P : Source_Ptr) return Source_Ptr is
Sindex : constant Source_File_Index := Get_Source_File_Index (P);
Src : constant Source_Buffer_Ptr := Source_Text (Sindex);
S : Source_Ptr;
Result : Source_Ptr := 0;
begin
S := Line_Start (P);
while S <= P loop
if Is_Start_Of_Wide_Char_For_ASIS (Src, S) then
Skip_Wide_For_ASIS (Src, S);
else
S := S + 1;
end if;
Result := Result + 1;
end loop;
return Result;
end A_Get_Column_Number;
-----------------------
-- Comment_Beginning --
-----------------------
function Comment_Beginning (Line_Image : Text_Buffer) return Source_Ptr is
Line_Image_Start : constant Source_Ptr := Line_Image'First;
Line_Image_End : constant Source_Ptr := Line_Image'Last;
Scanner_Pos : Source_Ptr;
String_Delimiter : Standard.Character;
begin
Scanner_Pos := Line_Image_Start - 1;
Scan_The_Line : while Scanner_Pos < Line_Image_End loop
Scanner_Pos := Scanner_Pos + 1;
case Line_Image (Scanner_Pos) is
when '"' | '%' =>
if not ((Scanner_Pos - 1) >= Line_Image_Start and then
Line_Image (Scanner_Pos - 1) = '''
and then
(Scanner_Pos + 1) <= Line_Image_End and then
Line_Image (Scanner_Pos + 1) = ''')
then
-- We have to awoid considering character literals '"'
-- '%' as string brackets
String_Delimiter := Line_Image (Scanner_Pos);
Skip_String_Literal : loop
Scanner_Pos := Scanner_Pos + 1;
if Line_Image (Scanner_Pos) = String_Delimiter then
-- we are in a legal Ada source, therefore:
if Scanner_Pos < Line_Image'Last and then
Line_Image (Scanner_Pos + 1) = String_Delimiter
then
-- Delimiter as character inside the literal.
Scanner_Pos := Scanner_Pos + 1;
else
-- End of the literal.
exit Skip_String_Literal;
end if;
end if;
end loop Skip_String_Literal;
end if;
when '-' =>
if (Scanner_Pos < Line_Image'Last) and then
(Line_Image (Scanner_Pos + 1) = '-')
then
return Scanner_Pos;
end if;
when others =>
null;
end case;
end loop Scan_The_Line;
-- There wasn't any comment if we reach this point.
return No_Location;
end Comment_Beginning;
--------------------
-- Exp_Name_Image --
--------------------
function Exp_Name_Image (Name : Node_Id) return String is
Prefix_Node : Node_Id;
Selector_Node : Node_Id;
begin
if Nkind (Name) = N_Identifier or else
Nkind (Name) = N_Defining_Identifier
then
-- ????? See E729-A04!
return Identifier_Image (Name);
end if;
if Nkind (Name) = N_Defining_Program_Unit_Name then
Prefix_Node := Sinfo.Name (Name);
Selector_Node := Defining_Identifier (Name);
else
-- Nkind (Name) = N_Expanded_Name
Prefix_Node := Prefix (Name);
Selector_Node := Selector_Name (Name);
end if;
return Exp_Name_Image (Prefix_Node)
& '.'
& Identifier_Image (Selector_Node); -- ???
end Exp_Name_Image;
-------------------
-- Get_Character --
-------------------
function Get_Character (P : Source_Ptr) return Character is
Sindex : constant Source_File_Index := Get_Source_File_Index (P);
Src : constant Source_Buffer_Ptr := Source_Text (Sindex);
begin
return Src (P);
end Get_Character;
------------------
-- Get_Location --
------------------
function Get_Location (E : Asis.Element) return Source_Ptr is
begin
return Sloc (Node (E));
end Get_Location;
-------------------------
-- Get_Num_Literal_End --
-------------------------
function Get_Num_Literal_End (P : Source_Ptr) return Source_Ptr is
Sindex : constant Source_File_Index := Get_Source_File_Index (P);
Src : constant Source_Buffer_Ptr := Source_Text (Sindex);
S : Source_Ptr;
B_Char : Character;
begin
-- Src (P) is the leading digit of a numeric literal
S := P + 1;
loop
if Is_Hexadecimal_Digit (Src (S)) or else Src (S) = '_' then
S := S + 1;
elsif Src (S) = '#' or else Src (S) = ':' then
-- based literal: 16#E#E1 or 016#offf#
-- J.2 (3): "The number sign characters (#) of a based_literal
-- can be replaced by colons (:) provided that the replacement
-- is done for both occurrences. But in case of a colon, we
-- have to make sure that we indeed have a based literal, but not
-- a decimal literal immediatelly followed by an assignment sign,
-- see G119-012:
--
-- SPLIT_INDEX:INTEGER RANGE 1..80:=1;
if Src (S) = ':' and then Src (S + 1) = '=' then
S := S - 1;
exit;
end if;
B_Char := Src (S);
-- and now - looking for trailing '#' or ':':
S := S + 1;
while Src (S) /= B_Char loop
S := S + 1;
end loop;
if Src (S + 1) = 'E' or else
Src (S + 1) = 'e'
then
-- this means something like 5#1234.1234#E2
S := S + 2;
else
exit;
end if;
elsif Src (S) = '+'
or else
Src (S) = '-'
then -- 12E+34 or 12+34?
if Src (S - 1) = 'E'
or else
Src (S - 1) = 'e'
then
-- it is the sign of the exponent
S := S + 1;
else
S := S - 1; -- to go back in the literal
exit;
end if;
elsif Src (S) = '.' then -- 3.14 or 3..14?
if Is_Hexadecimal_Digit (Src (S + 1)) then
S := S + 1;
else
S := S - 1; -- to go back in the literal
exit;
end if;
else -- for sure, we already are outside the literal
S := S - 1; -- to go back in the literal
exit;
end if;
end loop;
return S;
end Get_Num_Literal_End;
--------------------
-- Get_String_End --
--------------------
function Get_String_End (P : Source_Ptr) return Source_Ptr is
Sindex : constant Source_File_Index := Get_Source_File_Index (P);
Src : constant Source_Buffer_Ptr := Source_Text (Sindex);
S : Source_Ptr;
Quote : Character;
begin
-- Src (P) is the leading quotation of the non-nul string constant
-- which can be either '"' OR '%' (J.2 (2)).
Quote := Src (P);
S := P + 1;
loop
if Src (S) = Quote and then Src (S + 1) = Quote then
S := S + 2;
elsif Src (S) /= Quote then
if Is_Start_Of_Wide_Char_For_ASIS (Src, S) then
Skip_Wide_For_ASIS (Src, S);
else
S := S + 1;
end if;
else
-- S points to the trailing quotation of the constant
exit;
end if;
end loop;
return S;
end Get_String_End;
-------------------
-- Get_Wide_Word --
-------------------
function Get_Wide_Word
(P_Start : Source_Ptr;
P_End : Source_Ptr)
return Wide_String
is
Sindex : constant Source_File_Index := Get_Source_File_Index (P_Start);
Src : constant Source_Buffer_Ptr := Source_Text (Sindex);
Result : Wide_String (1 .. Positive (P_End - P_Start + 1));
Last_Idx : Natural := 0;
Next_Ch : Char_Code;
S : Source_Ptr;
Success : Boolean;
pragma Unreferenced (Success);
begin
S := P_Start;
while S <= P_End loop
Last_Idx := Last_Idx + 1;
if Is_Start_Of_Wide_Char_For_ASIS (Src, S) then
Scan_Wide (Src, S, Next_Ch, Success);
Result (Last_Idx) := Wide_Character'Val (Next_Ch);
else
Result (Last_Idx) := To_Wide_Character (Src (S));
S := S + 1;
end if;
end loop;
return Result (1 .. Last_Idx);
end Get_Wide_Word;
-----------------
-- Get_Wide_Ch --
-----------------
function Get_Wide_Ch (S : Source_Ptr) return Wide_Character is
Sindex : constant Source_File_Index := Get_Source_File_Index (S);
Src : constant Source_Buffer_Ptr := Source_Text (Sindex);
S1 : Source_Ptr := S;
Ch : Char_Code;
Result : Wide_Character;
Success : Boolean;
pragma Unreferenced (Success);
begin
if Is_Start_Of_Wide_Char_For_ASIS (Src, S1) then
Scan_Wide (Src, S1, Ch, Success);
Result := Wide_Character'Val (Ch);
else
Result := To_Wide_Character (Src (S1));
end if;
return Result;
end Get_Wide_Ch;
------------------
-- Get_Word_End --
------------------
function Get_Word_End
(P : Source_Ptr;
In_Word : In_Word_Condition)
return Source_Ptr
is
S : Source_Ptr;
begin
S := P;
while In_Word (S + 1) loop
S := S + 1;
end loop;
return S;
end Get_Word_End;
----------------------
-- Identifier_Image --
----------------------
function Identifier_Image (Ident : Node_Id) return String is
Image_Start : Source_Ptr;
Image_End : Source_Ptr;
begin
Image_Start := Sloc (Ident);
Image_End := Get_Word_End (P => Image_Start,
In_Word => In_Identifier'Access);
-- See E729-A04!!!
return To_String (Get_Wide_Word (Image_Start, Image_End));
end Identifier_Image;
-------------------
-- In_Identifier --
-------------------
function In_Identifier (P : Source_Ptr) return Boolean is
Sindex : constant Source_File_Index := Get_Source_File_Index (P);
Src : constant Source_Buffer_Ptr := Source_Text (Sindex);
Char : Character;
Result : Boolean := True;
begin
Char := Src (P);
if Char = ' ' or else
Char = '&' or else
Char = ''' or else
Char = '(' or else
Char = ')' or else
Char = '*' or else
Char = '+' or else
Char = ',' or else
Char = '-' or else
Char = '.' or else
Char = '/' or else
Char = ':' or else
Char = ';' or else
Char = '<' or else
Char = '=' or else
Char = '>' or else
Char = '|' or else
Char = '!' or else
Char = ASCII.LF or else
Char = ASCII.FF or else
Char = ASCII.HT or else
Char = ASCII.VT or else
Char = ASCII.CR
then
Result := False;
end if;
return Result;
end In_Identifier;
-----------------
-- Is_EOL_Char --
-----------------
function Is_EOL_Char (Ch : Character) return Boolean is
Result : Boolean := False;
begin
Result :=
Ch = ASCII.CR
or else
Ch = ASCII.LF
or else
Ch = ASCII.FF
or else
Ch = ASCII.VT;
return Result;
end Is_EOL_Char;
------------------------------------
-- Is_Start_Of_Wide_Char_For_ASIS --
------------------------------------
function Is_Start_Of_Wide_Char_For_ASIS
(S : Source_Buffer_Ptr;
P : Source_Ptr;
C : Source_Ptr := No_Location)
return Boolean
is
Result : Boolean := False;
begin
if C /= No_Location and then P > C then
-- We are in comment, so we can not have bracket encoding
if Wide_Character_Encoding_Method /= WCEM_Brackets then
Result := Is_Start_Of_Wide_Char (S, P);
end if;
else
Result := Is_Start_Of_Wide_Char (S, P);
if not Result then
Result := P <= S'Last - 2
and then S (P) = '['
and then S (P + 1) = '"'
and then (S (P + 2) in '0' .. '9'
or else
S (P + 2) in 'a' .. 'f'
or else
S (P + 2) in 'A' .. 'F');
end if;
end if;
return Result;
end Is_Start_Of_Wide_Char_For_ASIS;
---------------------
-- Next_Identifier --
---------------------
function Next_Identifier (P : Source_Ptr) return Source_Ptr is
Sindex : constant Source_File_Index := Get_Source_File_Index (P);
Src : constant Source_Buffer_Ptr := Source_Text (Sindex);
S : Source_Ptr;
begin
S := P + 1;
while not Is_Letter (Src (S)) loop
if Src (S) = '-' and then Src (S + 1) = '-' then
Skip_Comment (S);
else
S := S + 1;
end if;
end loop;
return S;
end Next_Identifier;
---------------------
-- Number_Of_Lines --
---------------------
function Number_Of_Lines (E : Asis.Element) return Integer is
SFI : constant Source_File_Index :=
Get_Source_File_Index (Get_Location (E));
begin
-- return Integer (Num_Source_Lines (SFI) + Line_Offset (SFI));
return Integer (Num_Source_Lines (SFI));
end Number_Of_Lines;
--------------------
-- Operator_Image --
--------------------
function Operator_Image (Node : Node_Id) return String is
S_Start : constant Source_Ptr := Sloc (Node);
-- S_Start points to the leading character of a given operator symbol.
Sindex : constant Source_File_Index :=
Get_Source_File_Index (S_Start);
Src : constant Source_Buffer_Ptr := Source_Text (Sindex);
S_End : Source_Ptr := S_Start;
-- should be set as pointing to the last character of a given
-- operator symbol.
Ch : Character;
begin
Ch := Src (S_Start);
if Ch = 'A' or else Ch = 'a' -- "abs" or "and"
or else Ch = 'M' or else Ch = 'm' -- "mod"
or else Ch = 'N' or else Ch = 'n' -- "not"
or else Ch = 'R' or else Ch = 'r' -- "rem"
or else Ch = 'X' or else Ch = 'x' -- "xor"
then
S_End := S_Start + 2;
elsif Ch = 'O' or else Ch = 'o' then -- "or"
S_End := S_Start + 1;
elsif Ch = '=' -- "="
or else Ch = '+' -- "+"
or else Ch = '-' -- "-"
or else Ch = '&' -- "&"
then
S_End := S_Start;
elsif Ch = '/' -- "/=" or "/"?
or else Ch = '<' -- "<=" or "<"?
or else Ch = '>' -- ">=" or ">"?
or else Ch = '*' -- "**" or "*"?
then
Ch := Src (S_Start + 1);
if Ch = '=' or else -- "/=", "<=" or ">="
Ch = '*' -- "**"
then
S_End := S_Start + 1;
else
S_End := S_Start;
-- "<", ">", "*" or "/"
end if;
end if;
return (1 => '"') & String (Src (S_Start .. S_End)) & (1 => '"');
end Operator_Image;
-------------------------
-- Rightmost_Non_Blank --
-------------------------
function Rightmost_Non_Blank (P : Source_Ptr) return Source_Ptr is
S : Source_Ptr := P;
Sindex : constant Source_File_Index := Get_Source_File_Index (P);
Src : constant Source_Buffer_Ptr := Source_Text (Sindex);
begin
loop
if Src (S) = '-' and then Src (S + 1) = '-' then
Skip_Comment (S);
elsif Is_Graphic (Src (S)) and then Src (S) /= ' ' then
exit;
else
S := S + 1;
end if;
end loop;
return S;
end Rightmost_Non_Blank;
------------------------------
-- Search_Beginning_Of_Word --
------------------------------
function Search_Beginning_Of_Word (S : Source_Ptr) return Source_Ptr is
SFI : constant Source_File_Index := Get_Source_File_Index (S);
Src : constant Source_Buffer_Ptr := Source_Text (SFI);
S_P : Source_Ptr;
begin
S_P := S;
while S_P >= Source_First (SFI)
and then (Src (S_P) in 'A' .. 'Z' or else
Src (S_P) in 'a' .. 'z' or else
Src (S_P) in '0' .. '9' or else
Src (S_P) = '_')
loop
S_P := S_P - 1;
end loop;
return S_P + 1;
end Search_Beginning_Of_Word;
------------------------
-- Search_End_Of_Word --
------------------------
function Search_End_Of_Word (S : Source_Ptr) return Source_Ptr is
S_P : Source_Ptr := S;
SFI : constant Source_File_Index := Get_Source_File_Index (S);
Src : constant Source_Buffer_Ptr := Source_Text (SFI);
Char : Character;
begin
Char := Src (S_P);
while not (Char = ' ' or else
Char = '&' or else
Char = ''' or else
Char = '(' or else
Char = ')' or else
Char = '*' or else
Char = '+' or else
Char = ',' or else
Char = '-' or else
Char = '.' or else
Char = '/' or else
Char = ':' or else
Char = ';' or else
Char = '<' or else
Char = '=' or else
Char = '>' or else
Char = '|' or else
Char = '!' or else
Char = ASCII.LF or else
Char = ASCII.FF or else
Char = ASCII.HT or else
Char = ASCII.VT or else
Char = ASCII.CR)
loop
S_P := S_P + 1;
Char := Src (S_P);
end loop;
S_P := S_P - 1;
return S_P;
end Search_End_Of_Word;
-----------------------------
-- Search_Left_Parenthesis --
-----------------------------
function Search_Left_Parenthesis (S : Source_Ptr) return Source_Ptr is
S_P : Source_Ptr := S - 1;
SFI : constant Source_File_Index := Get_Source_File_Index (S);
Src : constant Source_Buffer_Ptr := Source_Text (SFI);
begin
loop
case Src (S_P) is
when '(' =>
return S_P;
when CR | LF =>
declare
TempS : Source_Ptr := Line_Start (S_P);
begin
while (Src (TempS) /= '-' or else
Src (TempS + 1) /= '-')
and then
TempS < S_P
loop
TempS := TempS + 1;
end loop;
S_P := TempS - 1;
end;
when others =>
S_P := S_P - 1;
end case;
end loop;
end Search_Left_Parenthesis;
----------------------
-- Search_Next_Word --
----------------------
function Search_Next_Word (S : Source_Ptr) return Source_Ptr is
S_P : Source_Ptr := S + 1;
SFI : constant Source_File_Index := Get_Source_File_Index (S);
Src : constant Source_Buffer_Ptr := Source_Text (SFI);
begin
loop
case Src (S_P) is
when ' ' | HT | CR | LF =>
S_P := S_P + 1;
when '-' =>
if Src (S_P + 1) = '-' then
Skip_Comment (S_P);
else
return S_P;
end if;
when others =>
return S_P;
end case;
end loop;
end Search_Next_Word;
----------------------
-- Search_Prev_Word --
----------------------
function Search_Prev_Word (S : Source_Ptr) return Source_Ptr is
S_P : Source_Ptr := S - 1;
SFI : constant Source_File_Index := Get_Source_File_Index (S);
Src : constant Source_Buffer_Ptr := Source_Text (SFI);
begin
loop
case Src (S_P) is
when ' ' | HT =>
S_P := S_P - 1;
when CR | LF =>
declare
TempS : Source_Ptr := Line_Start (S_P);
begin
while (Src (TempS) /= '-' or else
Src (TempS + 1) /= '-')
and then
TempS < S_P
loop
TempS := TempS + 1;
end loop;
S_P := TempS - 1;
end;
when others =>
return S_P;
end case;
end loop;
end Search_Prev_Word;
----------------------------
-- Search_Prev_Word_Start --
----------------------------
function Search_Prev_Word_Start (S : Source_Ptr) return Source_Ptr is
begin
return Search_Beginning_Of_Word (Search_Prev_Word (S));
end Search_Prev_Word_Start;
-----------------------------
-- Search_Rightmost_Symbol --
-----------------------------
function Search_Rightmost_Symbol
(P : Source_Ptr;
Char : Character := ';')
return Source_Ptr
is
S : Source_Ptr := P;
-- the location to be returned, the search is started from P
Sindex : constant Source_File_Index := Get_Source_File_Index (P);
Src : constant Source_Buffer_Ptr := Source_Text (Sindex);
begin
while Src (S) /= Char loop
if Src (S) = '-' and then Src (S + 1) = '-' then
Skip_Comment (S);
elsif (Src (S) = '"' or else Src (S) = '%')
and then
not (Src (S - 1) = ''' and then Src (S + 1) = ''')
then
Skip_String (S);
else
S := S + 1;
end if;
end loop;
return S;
end Search_Rightmost_Symbol;
-----------------
-- Skip_String --
-----------------
procedure Skip_String (P : in out Source_Ptr) is
Sindex : constant Source_File_Index := Get_Source_File_Index (P);
Src : constant Source_Buffer_Ptr := Source_Text (Sindex);
Quoter : constant Character := Src (P);
begin
-- we are in the beginning of a legal string literal in a legal
-- Ada program. So we do not have to be careful with all
-- the checks:
while not (Src (P) = Quoter and then Src (P + 1) /= Quoter) loop
P := P + 1;
end loop;
P := P + 1;
end Skip_String;
------------------
-- Skip_Comment --
------------------
procedure Skip_Comment (P : in out Source_Ptr) is
Sindex : constant Source_File_Index := Get_Source_File_Index (P);
Src : constant Source_Buffer_Ptr := Source_Text (Sindex);
begin
if Src (P) = '-' and then Src (P + 1) = '-' then
P := P + 2;
while not (Src (P) = VT or else
Src (P) = CR or else
Src (P) = LF or else
Src (P) = FF)
loop
P := P + 1;
end loop;
end if;
end Skip_Comment;
------------------------
-- Skip_Wide_For_ASIS --
------------------------
procedure Skip_Wide_For_ASIS
(S : Source_Buffer_Ptr;
P : in out Source_Ptr)
is
Old_P : constant Source_Ptr := P;
Old_Wide_Character_Encoding_Method : WC_Encoding_Method;
begin
Skip_Wide (S, P);
if P = Old_P + 1 then
-- We have a bracket encoding, but the encoding method is different
-- from WCEM_Brackets
P := P - 1;
Old_Wide_Character_Encoding_Method := Wide_Character_Encoding_Method;
Wide_Character_Encoding_Method := WCEM_Brackets;
Skip_Wide (S, P);
Wide_Character_Encoding_Method := Old_Wide_Character_Encoding_Method;
end if;
end Skip_Wide_For_ASIS;
------------------------------
-- Source_Locations_To_Span --
------------------------------
function Source_Locations_To_Span
(Span_Beg : Source_Ptr;
Span_End : Source_Ptr)
return Span
is
Sp : Span;
begin
Sp.First_Line := Line_Number (Get_Physical_Line_Number (Span_Beg));
Sp.First_Column := Character_Position (A_Get_Column_Number (Span_Beg));
Sp.Last_Line := Line_Number (Get_Physical_Line_Number (Span_End));
Sp.Last_Column := Character_Position (A_Get_Column_Number (Span_End));
return Sp;
end Source_Locations_To_Span;
-----------------------
-- Wide_String_Image --
-----------------------
function Wide_String_Image (Node : Node_Id) return Wide_String is
S_Start : constant Source_Ptr := Sloc (Node);
-- S_Start points to the leading quote of a given string literal.
Sindex : constant Source_File_Index :=
Get_Source_File_Index (S_Start);
Src : constant Source_Buffer_Ptr := Source_Text (Sindex);
S_End : Source_Ptr := S_Start + 1;
-- should be set as pointing to the last character of a
-- string literal; empty and non-empty literals are processed
-- in the same way - we simply take a literal as it is from the
-- Source Buffer
Quote : constant Character := Src (S_Start);
-- Quoter may be '"' or '%'!
begin
loop
if Src (S_End) = Quote and then
Src (S_End + 1) = Quote
then
-- doubled string quote as an element of a given string
S_End := S_End + 2;
elsif Src (S_End) /= Quote then
-- "usial" string element
S_End := S_End + 1;
else
-- S_End points to the trailing quote of a given string
exit;
end if;
end loop;
declare
Result : Wide_String (1 .. Positive (S_End - S_Start + 1));
Last_Idx : Natural := 0;
Next_Ch : Char_Code;
S : Source_Ptr;
Success : Boolean;
pragma Unreferenced (Success);
begin
S := S_Start;
while S <= S_End loop
Last_Idx := Last_Idx + 1;
if Is_Start_Of_Wide_Char_For_ASIS (Src, S) then
Scan_Wide (Src, S, Next_Ch, Success);
Result (Last_Idx) := Wide_Character'Val (Next_Ch);
else
Result (Last_Idx) := To_Wide_Character (Src (S));
S := S + 1;
end if;
end loop;
return Result (1 .. Last_Idx);
end;
end Wide_String_Image;
end A4G.A_Sinput;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
|
981b90adea9ffcadeea580fd5f2a40b97dab5373
|
src/asis/a4g-cu_info2.ads
|
src/asis/a4g-cu_info2.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . C U _ I N F O 2 --
-- --
-- S p e c --
-- --
-- Copyright (c) 1995-1999, 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, 59 Temple Place --
-- - Suite 330, Boston, MA 02111-1307, 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 Ada Core Technologies Inc --
-- (http://www.gnat.com). --
-- --
------------------------------------------------------------------------------
with Asis; use Asis;
with A4G.A_Types; use A4G.A_Types;
with Types; use Types;
-- This package contains the routines used to compute the unit attributes
-- during the second pass through the tree files, when ASIS operates in
-- Use_Pre_Created_Trees mode. There is some duplication of the
-- functionalities provided by this package and by A4G.C_U_Info and
-- A4G.S_U_Info; the last two packages were coded before for
-- Compile_On_The_Fly ASIS operation mode. The intent is to get rid of
-- A4G.C_U_Info and A4G.S_U_Info in the final ASIS version, so we do not
-- bother about these duplications for now.
-- ???THIS COMMENT HEADER SHOULD BE REVISED!!!???
package A4G.CU_Info2 is
procedure Set_Kind_and_Class
(C : Context_Id;
U : Unit_Id;
Top : Node_Id);
-- Taking the unit's subtree top node, this procedure computes and sets
-- the Unit Kind and the Unit Class for U. Because of some technical ,
-- reasons, it is more easy to define the Unit Kind and the Unit Class
-- in the same routine
procedure Get_Ada_Name (Top : Node_Id);
-- Computes (by traversing the tree) the fully expanded Ada name
-- of a compilation unit whose subtree contained as having Top as
-- its top node in the full tree currently being accessed. This name
-- then is set in A_Name_Buffer, and A_Name_Len is set as its length
procedure Set_S_F_Name_and_Origin
(Context : Context_Id;
Unit : Unit_Id;
Top : Node_Id);
-- This procedure obtains the source file name from the GNAT tree and
-- stores it in the Unit_Table. By analyzing the file name (this analysis
-- is based on the Fname.Is_Predefined_File_Name GNAt function, the
-- Unit_Origin for the Unit is defined and stored in the Unit table.
function Is_Main (Top : Node_Id; Kind : Unit_Kinds) return Boolean;
-- Defines if the Unit having Top as its N_Compilation_Unit node
-- can be a main subprogram for a partition. Asis Unit Kind is
-- used to optimize this computation
procedure Set_Dependencies
(C : Context_Id;
U : Unit_Id;
Top : Node_Id);
-- Taking the unit's subtree top node, this procedure computes and sets
-- all the dependency information needed for semantic queries from the
-- Asis.Compilation_Units package. This information is stored as unit
-- lists (see A4G.Unit_Rec). For now, we do not compute the lists of
-- *direct* supporters and *direct* dependents, because we think, that
-- these ASIS notions are ill-defined and cannot be mapped onto RM95
-- in a natural way.
end A4G.CU_Info2;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
|
7a70fd1cb3d1209414eb379f2c96a11230489105
|
src/asis/a4g-get_unit.adb
|
src/asis/a4g-get_unit.adb
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . G E T _ U N I 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.Characters.Handling; use Ada.Characters.Handling;
with GNAT.Directory_Operations; use GNAT.Directory_Operations;
with GNAT.OS_Lib; use GNAT.OS_Lib;
with Asis.Errors;
with Asis.Exceptions; use Asis.Exceptions;
with Asis.Set_Get; use Asis.Set_Get;
with A4G.A_Debug; use A4G.A_Debug;
with A4G.A_Opt; use A4G.A_Opt;
with A4G.U_Conv; use A4G.U_Conv;
with A4G.Contt.Dp; use A4G.Contt.Dp;
with A4G.Contt.SD; use A4G.Contt.SD;
with A4G.Contt.TT; use A4G.Contt.TT;
with A4G.Contt.UT; use A4G.Contt.UT; use A4G.Contt;
with A4G.Defaults; use A4G.Defaults;
with A4G.GNAT_Int; use A4G.GNAT_Int;
with A4G.Vcheck; use A4G.Vcheck;
with Output; use Output;
package body A4G.Get_Unit is
-----------------------
-- Local subprograms --
-----------------------
function Convert_To_String (Wide_Name : Wide_String) return String;
-- Takes the name (of a compilation unit) and converts it into String
-- following the GNAT encoding rules as described in Namet.
-----------------------
-- Convert_To_String --
-----------------------
function Convert_To_String (Wide_Name : Wide_String) return String is
begin
if Is_String (Wide_Name) then
return To_String (Wide_Name);
else
Not_Implemented_Yet ("Wide_Character in Unit name");
end if;
end Convert_To_String;
----------------------------
-- Fetch_Unit_By_Ada_Name --
----------------------------
function Fetch_Unit_By_Ada_Name
(Name : String;
Norm_Name : String;
Context : Context_Id;
Spec : Boolean)
return Unit_Id
is
Result_Unit_Id : Unit_Id;
Result_Tree : Tree_Id;
File_Name : String_Access;
-- We use File_Name to obtain the source file name according to
-- the GNAT file name rules (including the krunching rules)
Predefined : Boolean := False;
Success : Boolean := False;
Source_File : String_Access;
-- source to compile, contains all the path information
Tree_File_N : String_Access;
-- tree output file to be retrieved (name)
Tree_File_D : File_Descriptor;
-- tree output file to be retrieved (file descriptor)
Cont_Tree_Mode : constant Tree_Mode := Tree_Processing_Mode (Context);
procedure Get_Source_File;
-- This procedure creates the value of Source_File using the values
-- of Name and Spec. The procedure first tries to get the file
-- containing the body regardless of the value of the Spec parameter.
-- The idea is to get for Spec => True the tree file containing both
-- the spec and the body of the compilation unit. If we get the tree
-- file for the spec only, then latter on we may get into
-- the following problem - the attempt to get the body of the
-- compilation unit will create the tree file for the body, and
-- this tree file will have the same name. As a result, all the
-- references into the tree for spec will become erroneous, and
-- we will have the problem similar to what was reported as 7504-002.
--
-- ??? All this "compile-on-the-fly" Context mode becomes a real
-- mess. May be, we have to get rid of it???
procedure Get_Source_File is
begin
-- The code is really awfull, but probably it would be better to
-- get rid of the "compila-on-the-fly" mode, then to polish
-- the code.
File_Name := Source_From_Unit_Name (Name, False);
-- if needed, the name is krunched here (??? may be, we can already
-- forget about systems with the limitations on the file name
-- length???)
-- Note also, that ASIS cannot work with files which names override
-- the standard GNAT file name convention as a result of
-- Source_File_Name pragma.
Source_File := Locate_In_Search_Path
(C => Context,
File_Name => To_String (File_Name),
Dir_Kind => Source);
if Source_File = null then
Source_File := Locate_Default_File
(File_Name => File_Name,
Dir_Kind => Source);
end if;
if Source_File /= null then
return;
elsif Spec then
File_Name := Source_From_Unit_Name (Name, True);
Source_File := Locate_In_Search_Path
(C => Context,
File_Name => To_String (File_Name),
Dir_Kind => Source);
if Source_File = null then
Source_File := Locate_Default_File
(File_Name => File_Name,
Dir_Kind => Source);
end if;
end if;
if Source_File = null and then
Is_Predefined_File_Name (File_Name)
-- not GNAT, but ASIS Is_Predefined_File_Name function is called
-- here!
then
-- if File_Name is the name of a predefined unit, we shall try
-- the default source search path. See also
-- A4G.Contt.Set_Predefined_Units
File_Name := Source_From_Unit_Name (Name, False);
Predefined := True;
Source_File := Locate_Default_File (File_Name, Source);
if Source_File = null then
File_Name := Source_From_Unit_Name (Name, True);
Source_File := Locate_Default_File (File_Name, Source);
end if;
end if;
end Get_Source_File;
begin
-- we start from looking for a unit in the Unit Name Table
Set_Name_String (Norm_Name);
Result_Unit_Id := Name_Find (Context);
if Result_Unit_Id /= Nil_Unit then
return Result_Unit_Id;
elsif Cont_Tree_Mode = Pre_Created then
if Norm_Name = "standard%s" then
-- For Standard, we have to search twice - first for possible
-- redefinition of Standard, then - for predefined Standard
return Standard_Id;
else
return Nil_Unit;
end if;
end if;
if Spec then
-- The idea is to avoid non-needed recompilations in case if we
-- already have the (tree for the) corresponding body, see F823-027.
A_Name_Buffer (A_Name_Len) := 'b';
Result_Unit_Id := Name_Find (Context);
if Result_Unit_Id /= Nil_Unit then
return Nil_Unit;
end if;
end if;
-- We can be here only if Context was associated in On_The_Fly or Mixed
-- tree processing mode mode, and we have failed to find the required
-- unit among units which are already known to ASIS. Therefore, we
-- have to (try to) create the tree by compiling the source:
Get_Source_File;
if Source_File = null then
if Debug_Mode then
Write_Str ("Fetch_Unit_By_Ada_Name: cannot locate a source file ");
Write_Str ("for " & Name);
Write_Eol;
end if;
return Nil_Unit;
end if;
-- And trying to compile - Source_File contains the reference
-- to the existing source file which has been already successfully
-- located in the Context:
if Debug_Mode then
Write_Str ("Fetch_Unit_By_Ada_Name: "
& "Trying to create a tree on the fly:");
Write_Eol;
Write_Str ("Source file is " & To_String (Source_File));
Write_Eol;
end if;
Create_Tree (Source_File => Source_File,
Context => Context,
Is_Predefined => Predefined,
Success => Success);
if not Success then
if Debug_Mode then
Write_Str ("Failure...");
Write_Eol;
end if;
return Nil_Unit;
end if;
if Debug_Mode then
Write_Str ("Success...");
Write_Eol;
end if;
-- here we have a new tree, successfully created just here. We will
-- read it in, then we will investigate it just in the same way as
-- during opening a Context and then we look into the unit table for
-- the needed unit again
Tree_File_N := Tree_From_Source_Name (File_Name);
-- ??? IT WOULD BE BETTER TO USE STRIP_DIRECTORY (SOURCE_FILE)
-- INSTEAD OF FILE_NAME HERE!!!!!
Tree_File_D := Open_Read (Tree_File_N.all'Address, Binary);
begin
if Debug_Mode then
Write_Str ("Fetch_Unit_By_Ada_Name: trying to read in a tree...");
Write_Eol;
end if;
Tree_In_With_Version_Check (Tree_File_D, Context, Success);
if Success then
if Debug_Mode then
Write_Str ("Fetch_Unit_By_Ada_Name: a tree is read in...");
Write_Eol;
end if;
else
-- This should never happen!
Set_Error_Status
(Status => Asis.Errors.Use_Error,
Diagnosis => "A4G.Get_Unit.Fetch_Unit_By_Ada_Name:"
& ASIS_Line_Terminator
& "problems reading tree file "
& To_String (Tree_File_N));
raise ASIS_Failed;
end if;
exception
when Program_Error |
ASIS_Failed =>
raise;
when Ex : others =>
-- If we are here, we are definitely having a serious problem:
-- we have a tree file which is version-compartible with ASIS,
-- and we can not read it because of some unknown reason.
Set_Current_Cont (Nil_Context_Id);
Set_Current_Tree (Nil_Tree);
-- debug stuff...
if Debug_Flag_O or else
Debug_Lib_Model or else
Debug_Mode
then
Write_Str ("A4G.Get_Unit.Fetch_Unit_By_Ada_Name:");
Write_Eol;
Write_Str ("Cannot read the tree file ");
Write_Str (To_String (Tree_File_N));
Write_Str (" newly created for a source file ");
Write_Str (To_String (Source_File));
Write_Eol;
end if;
Report_ASIS_Bug
(Query_Name => "A4G.Get_Unit.Fetch_Unit_By_Ada_Name" &
" (tree file " & To_String (Tree_File_N) & ")",
Ex => Ex);
end;
Set_Name_String (To_String (Tree_File_N));
Set_Current_Cont (Context);
Result_Tree := Allocate_Tree_Entry;
Set_Current_Tree (Result_Tree);
-- here we have to investigate the newly created tree:
if Tree_Processing_Mode (Context) = Incremental then
begin
NB_Save;
Register_Units (Set_First_New_Unit => True);
Scan_Units_New;
Set_All_Dependencies (Use_First_New_Unit => True);
Reorder_Trees (Context);
exception
when Inconsistent_Incremental_Context =>
-- Erase the old Context information
Increase_ASIS_OS_Time;
Pre_Initialize (Context);
A4G.Contt.Initialize (Context);
-- We still have one good tree
Result_Tree := Allocate_Tree_Entry;
NB_Restore;
Set_Current_Tree (Result_Tree);
-- And we have to extract the information from this tree
Register_Units;
Scan_Units_New;
Set_All_Dependencies;
end;
else
-- For old "on the fly" and mixed mode no enhansment
Register_Units;
Scan_Units_New;
end if;
-- and now - the final attempt to get the needed unit. We have to reset
-- the name buffer - it may be changed by Scan_Units_New:
Set_Name_String (Norm_Name);
Result_Unit_Id := Name_Find (Context);
if Result_Unit_Id = Nil_Unit
and then
Norm_Name = "standard%s"
then
-- For Standard, we have to search twice - first for possible
-- redefinition of Standard, then - for predefined Standard
Result_Unit_Id := Standard_Id;
end if;
return Result_Unit_Id;
end Fetch_Unit_By_Ada_Name;
-----------------------------------
-- Get_Main_Unit_Tree_On_The_Fly --
-----------------------------------
function Get_Main_Unit_Tree_On_The_Fly
(Start_Unit : Unit_Id;
Cont : Context_Id;
Spec : Boolean)
return Unit_Id
is
Start_CU : constant Asis.Compilation_Unit :=
Get_Comp_Unit (Start_Unit, Cont);
Result_Unit_Id : Unit_Id;
Result_Tree : Tree_Id;
File_Name : String_Access;
-- We use File_Name to obtain the source file name according to
-- the GNAT file name rules (including the krunching rules)
Predefined : Boolean := False;
Success : Boolean := False;
S_File_To_Compile : String_Access;
-- source to compile, contains all the path information
Tmp_S_File, Tmp_S_File1 : String_Access;
Tree_File_N : String_Access;
-- tree output file to be retrieved (name)
Tree_File_D : File_Descriptor;
-- tree output file to be retrieved (file descriptor)
procedure Get_Source_File_To_Compile;
-- This procedure creates the value of Source_File using the values
-- of Start_Unit and Spec. If Spec is ON, the full source name of
-- Start_Unit is used. If Spec is OFF, we try to create the source
-- file name from the unit name by applying the standard GNAT file
-- naming rules. This is the weak point of the implementation, because
-- this does not wor for non-standard names
procedure Get_Source_File_To_Compile is
begin
if Spec then
S_File_To_Compile :=
new String'(Source_File (Start_CU) & ASCII.NUL);
else
-- The first thing to do is to try to locate the file with the
-- name computed on the base of the standard GNAT name rules
File_Name := Source_From_Unit_Name (Unit_Name (Start_CU), False);
S_File_To_Compile := Locate_In_Search_Path
(C => Cont,
File_Name => To_String (File_Name),
Dir_Kind => Source);
if S_File_To_Compile = null then
-- Two possibilities:
-- - Start_Unit is a predefined unit
-- - Try to convert spec name into unit body name and to
-- locate it
Tmp_S_File := new String'(Source_File (Start_CU));
Tmp_S_File (Tmp_S_File'Last) := 'b';
Tmp_S_File1 := new String'(Base_Name (Tmp_S_File.all));
if not Is_Predefined_File_Name (Tmp_S_File1) then
S_File_To_Compile := Locate_In_Search_Path
(C => Cont,
File_Name => Tmp_S_File.all,
Dir_Kind => Source);
else
Predefined := True;
S_File_To_Compile :=
Locate_Default_File (Tmp_S_File, Source);
end if;
end if;
end if;
end Get_Source_File_To_Compile;
begin
Get_Source_File_To_Compile;
if S_File_To_Compile = null then
if Debug_Mode then
Write_Str ("Get_Main_Unit_Tree_On_The_Fly: cannot create a main ");
Write_Str ("tree for " & Unit_Name (Start_CU));
Write_Eol;
end if;
return Nil_Unit;
end if;
-- Now we try to compile - Source_File contains the reference
-- to the existing source file which has been already successfully
-- located in the Context:
if Debug_Mode then
Write_Str ("Get_Main_Unit_Tree_On_The_Fly: "
& "Trying to create a main tree on the fly:");
Write_Eol;
Write_Str ("Source file is " & S_File_To_Compile.all);
Write_Eol;
end if;
Create_Tree (Source_File => S_File_To_Compile,
Context => Cont,
Is_Predefined => Predefined,
Success => Success);
if not Success then
if Debug_Mode then
Write_Str ("Failure...");
Write_Eol;
end if;
return Nil_Unit;
end if;
if Debug_Mode then
Write_Str ("Success...");
Write_Eol;
end if;
-- Now we have a new tree, successfully created just here. We have to
-- add it to the incremental Context
Tree_File_N := new String'(Base_Name (S_File_To_Compile.all));
Tree_File_N (Tree_File_N'Last - 1) := 't';
-- ??? What about non-standart file names????
Tree_File_D := Open_Read (Tree_File_N.all'Address, Binary);
begin
if Debug_Mode then
Write_Str ("Get_Main_Unit_Tree_On_The_Fly: read in a tree...");
Write_Eol;
end if;
Tree_In_With_Version_Check (Tree_File_D, Cont, Success);
if Success then
if Debug_Mode then
Write_Str ("Get_Main_Unit_Tree_On_The_Fly: done...");
Write_Eol;
end if;
else
-- This should never happen!
Set_Error_Status
(Status => Asis.Errors.Use_Error,
Diagnosis => "A4G.Get_Unit.Get_Main_Unit_Tree_On_The_Fly:"
& ASIS_Line_Terminator
& "problems reading tree file "
& To_String (Tree_File_N));
raise ASIS_Failed;
end if;
exception
when Program_Error |
ASIS_Failed =>
raise;
when Ex : others =>
-- If we are here, we are definitely having a serious problem:
-- we have a tree file which is version-compartible with ASIS,
-- and we can not read it because of some unknown reason.
Set_Current_Cont (Nil_Context_Id);
Set_Current_Tree (Nil_Tree);
-- debug stuff...
if Debug_Flag_O or else
Debug_Lib_Model or else
Debug_Mode
then
Write_Str ("A4G.Get_Unit.Get_Main_Unit_Tree_On_The_Fly:");
Write_Eol;
Write_Str ("Cannot read the tree file ");
Write_Str (To_String (Tree_File_N));
Write_Str (" newly created for a source file ");
Write_Str (S_File_To_Compile.all);
Write_Eol;
end if;
Report_ASIS_Bug
(Query_Name => "A4G.Get_Unit.Get_Main_Unit_Tree_On_The_Fly" &
" (tree file " & To_String (Tree_File_N) & ")",
Ex => Ex);
end;
Set_Name_String (To_String (Tree_File_N));
Set_Current_Cont (Cont);
Result_Tree := Allocate_Tree_Entry;
Set_Current_Tree (Result_Tree);
-- here we have to investigate the newly created tree:
begin
NB_Save;
Register_Units (Set_First_New_Unit => True);
Scan_Units_New;
Set_All_Dependencies (Use_First_New_Unit => True);
Reorder_Trees (Cont);
exception
when Inconsistent_Incremental_Context =>
-- Erase the old Context information
Increase_ASIS_OS_Time;
Pre_Initialize (Cont);
A4G.Contt.Initialize (Cont);
-- We still have one good tree
Result_Tree := Allocate_Tree_Entry;
NB_Restore;
Set_Current_Tree (Result_Tree);
-- And we have to extract the information from this tree
Register_Units;
Scan_Units_New;
Set_All_Dependencies;
end;
-- and now - forming the result Unit_Id
if Spec then
Result_Unit_Id := Start_Unit;
else
Result_Unit_Id := Get_Body (Cont, Start_Unit);
end if;
return Result_Unit_Id;
end Get_Main_Unit_Tree_On_The_Fly;
------------------
-- Get_One_Unit --
------------------
function Get_One_Unit
(Name : Wide_String;
Context : Context_Id;
Spec : Boolean)
return Unit_Id
is
Unit_Name : constant String := Convert_To_String (Name);
Name_Length : constant Natural := Unit_Name'Length;
Norm_Unit_Name : String (1 .. Name_Length + 2); -- "+ 2" for %(s|b)
Result_Id : Unit_Id;
Is_Unit_Name : Boolean := False;
begin
-- first of all, we have to check if Name can really be
-- treated as Ada unit name:
if Name_Length = 0 then
return Nil_Unit;
end if;
Get_Norm_Unit_Name (U_Name => Unit_Name,
N_U_Name => Norm_Unit_Name,
Spec => Spec,
May_Be_Unit_Name => Is_Unit_Name);
if not Is_Unit_Name then
return Nil_Unit;
end if;
-- Now we are sure that Name has the syntax structure of the Ada
-- unit name, and we have to check whether ASIS has already got
-- to know about this unit in its Unit Table, Norm_Unit_Name has
-- already been prepared for the corresponding search in the
-- Unit Table. If this check fails, we will
-- have to try to compile the Unit from its source:
Result_Id := Fetch_Unit_By_Ada_Name
(Name => Unit_Name,
Norm_Name => Norm_Unit_Name,
Context => Context,
Spec => Spec);
return Result_Id;
end Get_One_Unit;
end A4G.Get_Unit;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
b2c57aba5284f6e2b7be1a716414a8b059fd1649
|
awa/plugins/awa-storages/regtests/awa-storages-tests.adb
|
awa/plugins/awa-storages/regtests/awa-storages-tests.adb
|
-----------------------------------------------------------------------
-- awa-storages-tests -- Unit tests for storages module
-- Copyright (C) 2018, 2019, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Strings;
with ADO;
with Servlet.Streams;
with ASF.Tests;
with AWA.Tests.Helpers.Users;
with AWA.Storages.Beans;
with AWA.Storages.Models;
with AWA.Storages.Services;
with AWA.Storages.Modules;
with AWA.Services.Contexts;
with Security.Contexts;
package body AWA.Storages.Tests is
use Ada.Strings.Unbounded;
use AWA.Tests;
use type AWA.Storages.Services.Storage_Service_Access;
package Caller is new Util.Test_Caller (Test, "Storages.Beans");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Storages.Beans.Create",
Test_Create_Document'Access);
Caller.Add_Test (Suite, "Test AWA.Storages.Servlets (missing)",
Test_Missing_Document'Access);
end Add_Tests;
-- ------------------------------
-- Get some access on the wiki as anonymous users.
-- ------------------------------
procedure Verify_Anonymous (T : in out Test;
Page : in String;
Title : in String) is
pragma Unreferenced (Title);
Request : Servlet.Requests.Mockup.Request;
Reply : Servlet.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/storages/documents.html",
"storage-anonymous-list.html");
ASF.Tests.Assert_Contains (T, "List of pages", Reply,
"Wiki list recent page is invalid");
end Verify_Anonymous;
-- ------------------------------
-- Verify that the wiki lists contain the given page.
-- ------------------------------
procedure Verify_List_Contains (T : in out Test;
Page : in String) is
Request : Servlet.Requests.Mockup.Request;
Reply : Servlet.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/storages/documents.html",
"storage-list.html");
ASF.Tests.Assert_Contains (T, "Documents of the workspace", Reply,
"List of documents is invalid");
end Verify_List_Contains;
-- ------------------------------
-- Test access to the blog as anonymous user.
-- ------------------------------
procedure Test_Anonymous_Access (T : in out Test) is
begin
T.Verify_Anonymous ("", "");
end Test_Anonymous_Access;
-- ------------------------------
-- Test creation of document by simulating web requests.
-- ------------------------------
procedure Test_Create_Document (T : in out Test) is
Request : Servlet.Requests.Mockup.Request;
Reply : Servlet.Responses.Mockup.Response;
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
Request.Set_Parameter ("folder-name", "Test Folder Name");
Request.Set_Parameter ("storage-folder-create-form", "1");
Request.Set_Parameter ("storage-folder-create-button", "1");
ASF.Tests.Do_Post (Request, Reply, "/storages/forms/folder-create.html", "folder-create-form.html");
T.Assert (Reply.Get_Status = Servlet.Responses.SC_OK,
"Invalid response after folder creation");
ASF.Tests.Do_Get (Request, Reply, "/storages/documents.html",
"storage-list.html");
ASF.Tests.Assert_Contains (T, "Documents of the workspace", Reply,
"List of documents is invalid (title)");
ASF.Tests.Assert_Contains (T, "Test Folder Name", Reply,
"List of documents is invalid (content)");
end Test_Create_Document;
-- ------------------------------
-- Test getting a document which does not exist.
-- ------------------------------
procedure Test_Missing_Document (T : in out Test) is
Request : Servlet.Requests.Mockup.Request;
Reply : Servlet.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/storages/files/12345345/view/missing.pdf",
"storage-file-missing.html");
ASF.Tests.Assert_Matches (T, ".title.Page not found./title.", Reply,
"Page for a missing document is invalid",
Servlet.Responses.SC_NOT_FOUND);
end Test_Missing_Document;
end AWA.Storages.Tests;
|
Implement the new test for storage module to simulate web requests
|
Implement the new test for storage module to simulate web requests
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
|
b25e86269443a89a2a23faf0e9d22e883567fa99
|
src/util-serialize-mappers-record_mapper.ads
|
src/util-serialize-mappers-record_mapper.ads
|
-----------------------------------------------------------------------
-- Util.Serialize.Mappers.Record_Mapper -- Mapper for record types
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Objects;
with Util.Serialize.IO;
generic
type Element_Type is limited private;
type Element_Type_Access is access all Element_Type;
type Fields is (<>);
-- The <b>Set_Member</b> procedure will be called by the mapper when a mapping associated
-- with <b>Field</b> is recognized. The <b>Value</b> holds the value that was extracted
-- according to the mapping. The <b>Set_Member</b> procedure should save in the target
-- object <b>Into</b> the value. If an error is detected, the procedure can raise the
-- <b>Util.Serialize.Mappers.Field_Error</b> exception. The exception message will be
-- reported by the IO reader as an error.
with procedure Set_Member (Into : in out Element_Type;
Field : in Fields;
Value : in Util.Beans.Objects.Object);
-- Adding a second function/procedure as generic parameter makes the
-- Vector_Mapper generic package fail to instantiate a valid package.
-- The failure occurs in Vector_Mapper in the 'with package Element_Mapper' instantiation.
--
-- with function Get_Member (From : in Element_Type;
-- Field : in Fields) return Util.Beans.Objects.Object;
package Util.Serialize.Mappers.Record_Mapper is
type Get_Member_Access is
access function (From : in Element_Type;
Field : in Fields) return Util.Beans.Objects.Object;
-- Procedure to give access to the <b>Element_Type</b> object from the context.
type Process_Object is not null
access procedure (Ctx : in out Util.Serialize.Contexts.Context'Class;
Attr : in Mapping'Class;
Value : in Util.Beans.Objects.Object;
Process : not null
access procedure (Attr : in Mapping'Class;
Item : in out Element_Type;
Value : in Util.Beans.Objects.Object));
type Proxy_Object is not null
access procedure (Attr : in Mapping'Class;
Element : in out Element_Type;
Value : in Util.Beans.Objects.Object);
-- Set the attribute member described by the <b>Attr</b> mapping
-- into the value passed in <b>Element</b>. This operation will call
-- the package parameter function of the same name.
procedure Set_Member (Attr : in Mapping'Class;
Element : in out Element_Type;
Value : in Util.Beans.Objects.Object);
-- -----------------------
-- Data context
-- -----------------------
-- Data context to get access to the target element.
type Element_Data is new Util.Serialize.Contexts.Data with private;
type Element_Data_Access is access all Element_Data'Class;
-- Get the element object.
function Get_Element (Data : in Element_Data) return Element_Type_Access;
-- Set the element object. When <b>Release</b> is set, the element <b>Element</b>
-- will be freed when the reader context is deleted (by <b>Finalize</b>).
procedure Set_Element (Data : in out Element_Data;
Element : in Element_Type_Access;
Release : in Boolean := False);
-- Finalize the object when it is removed from the reader context.
-- If the <b>Release</b> parameter was set, the target element will be freed.
overriding
procedure Finalize (Data : in out Element_Data);
-- -----------------------
-- Record mapper
-- -----------------------
type Mapper is new Util.Serialize.Mappers.Mapper with private;
type Mapper_Access is access all Mapper'Class;
-- Execute the mapping operation on the object associated with the current context.
-- The object is extracted from the context and the <b>Execute</b> operation is called.
procedure Execute (Handler : in Mapper;
Map : in Mapping'Class;
Ctx : in out Util.Serialize.Contexts.Context'Class;
Value : in Util.Beans.Objects.Object);
-- Add a mapping for setting a member. When the attribute rule defined by <b>Path</b>
-- is matched, the <b>Set_Member</b> procedure will be called with the value and the
-- <b>Field</b> identification.
procedure Add_Mapping (Into : in out Mapper;
Path : in String;
Field : in Fields);
-- Add a mapping associated with the path and described by a mapper object.
-- The <b>Proxy</b> procedure is in charge of giving access to the target
-- object used by the <b>Map</b> mapper.
procedure Add_Mapping (Into : in out Mapper;
Path : in String;
Map : in Util.Serialize.Mappers.Mapper_Access;
Proxy : in Proxy_Object);
-- Clone the <b>Handler</b> instance and get a copy of that single object.
overriding
function Clone (Handler : in Mapper) return Util.Serialize.Mappers.Mapper_Access;
--
procedure Bind (Into : in out Mapper;
Getter : in Get_Member_Access);
procedure Bind (Into : in out Mapper;
From : in Mapper_Access);
function Get_Getter (From : in Mapper) return Get_Member_Access;
-- Set the element in the context. When <b>Release</b> is set, the element <b>Element</b>
-- will be freed when the reader context is deleted (by <b>Finalize</b>).
procedure Set_Context (Ctx : in out Util.Serialize.Contexts.Context'Class;
Element : in Element_Type_Access;
Release : in Boolean := False);
-- Build a default mapping based on the <b>Fields</b> enumeration.
-- The enumeration name is used for the mapping name with the optional <b>FIELD_</b>
-- prefix stripped.
procedure Add_Default_Mapping (Into : in out Mapper);
-- Write the element on the stream using the mapper description.
procedure Write (Handler : in Mapper;
Stream : in out Util.Serialize.IO.Output_Stream'Class;
Element : in Element_Type);
-- Write the element on the stream using the mapper description.
procedure Write (Handler : in Util.Serialize.Mappers.Mapper'Class;
Getter : in Get_Member_Access;
Stream : in out Util.Serialize.IO.Output_Stream'Class;
Element : in Element_Type);
private
type Element_Data is new Util.Serialize.Contexts.Data with record
Element : Element_Type_Access;
Release : Boolean;
end record;
type Mapper is new Util.Serialize.Mappers.Mapper with record
Execute : Proxy_Object := Set_Member'Access;
Get_Member : Get_Member_Access;
end record;
type Attribute_Mapping is new Mapping with record
Index : Fields;
end record;
type Attribute_Mapping_Access is access all Attribute_Mapping'Class;
procedure Set_Member (Attr : in Attribute_Mapping;
Element : in out Element_Type;
Value : in Util.Beans.Objects.Object);
type Proxy_Mapper is new Mapper with null record;
type Proxy_Mapper_Access is access all Proxy_Mapper'Class;
-- Find the mapper associated with the given name.
-- Returns null if there is no mapper.
overriding
function Find_Mapper (Controller : in Proxy_Mapper;
Name : in String;
Attribute : in Boolean := False)
return Util.Serialize.Mappers.Mapper_Access;
end Util.Serialize.Mappers.Record_Mapper;
|
-----------------------------------------------------------------------
-- Util.Serialize.Mappers.Record_Mapper -- Mapper for record types
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Objects;
with Util.Serialize.IO;
generic
type Element_Type (<>) is limited private;
type Element_Type_Access is access all Element_Type;
type Fields is (<>);
-- The <b>Set_Member</b> procedure will be called by the mapper when a mapping associated
-- with <b>Field</b> is recognized. The <b>Value</b> holds the value that was extracted
-- according to the mapping. The <b>Set_Member</b> procedure should save in the target
-- object <b>Into</b> the value. If an error is detected, the procedure can raise the
-- <b>Util.Serialize.Mappers.Field_Error</b> exception. The exception message will be
-- reported by the IO reader as an error.
with procedure Set_Member (Into : in out Element_Type;
Field : in Fields;
Value : in Util.Beans.Objects.Object);
-- Adding a second function/procedure as generic parameter makes the
-- Vector_Mapper generic package fail to instantiate a valid package.
-- The failure occurs in Vector_Mapper in the 'with package Element_Mapper' instantiation.
--
-- with function Get_Member (From : in Element_Type;
-- Field : in Fields) return Util.Beans.Objects.Object;
package Util.Serialize.Mappers.Record_Mapper is
type Get_Member_Access is
access function (From : in Element_Type;
Field : in Fields) return Util.Beans.Objects.Object;
-- Procedure to give access to the <b>Element_Type</b> object from the context.
type Process_Object is not null
access procedure (Ctx : in out Util.Serialize.Contexts.Context'Class;
Attr : in Mapping'Class;
Value : in Util.Beans.Objects.Object;
Process : not null
access procedure (Attr : in Mapping'Class;
Item : in out Element_Type;
Value : in Util.Beans.Objects.Object));
type Proxy_Object is not null
access procedure (Attr : in Mapping'Class;
Element : in out Element_Type;
Value : in Util.Beans.Objects.Object);
-- Set the attribute member described by the <b>Attr</b> mapping
-- into the value passed in <b>Element</b>. This operation will call
-- the package parameter function of the same name.
procedure Set_Member (Attr : in Mapping'Class;
Element : in out Element_Type;
Value : in Util.Beans.Objects.Object);
-- -----------------------
-- Data context
-- -----------------------
-- Data context to get access to the target element.
type Element_Data is new Util.Serialize.Contexts.Data with private;
type Element_Data_Access is access all Element_Data'Class;
-- Get the element object.
function Get_Element (Data : in Element_Data) return Element_Type_Access;
-- Set the element object. When <b>Release</b> is set, the element <b>Element</b>
-- will be freed when the reader context is deleted (by <b>Finalize</b>).
procedure Set_Element (Data : in out Element_Data;
Element : in Element_Type_Access;
Release : in Boolean := False);
-- Finalize the object when it is removed from the reader context.
-- If the <b>Release</b> parameter was set, the target element will be freed.
overriding
procedure Finalize (Data : in out Element_Data);
-- -----------------------
-- Record mapper
-- -----------------------
type Mapper is new Util.Serialize.Mappers.Mapper with private;
type Mapper_Access is access all Mapper'Class;
-- Execute the mapping operation on the object associated with the current context.
-- The object is extracted from the context and the <b>Execute</b> operation is called.
procedure Execute (Handler : in Mapper;
Map : in Mapping'Class;
Ctx : in out Util.Serialize.Contexts.Context'Class;
Value : in Util.Beans.Objects.Object);
-- Add a mapping for setting a member. When the attribute rule defined by <b>Path</b>
-- is matched, the <b>Set_Member</b> procedure will be called with the value and the
-- <b>Field</b> identification.
procedure Add_Mapping (Into : in out Mapper;
Path : in String;
Field : in Fields);
-- Add a mapping associated with the path and described by a mapper object.
-- The <b>Proxy</b> procedure is in charge of giving access to the target
-- object used by the <b>Map</b> mapper.
procedure Add_Mapping (Into : in out Mapper;
Path : in String;
Map : in Util.Serialize.Mappers.Mapper_Access;
Proxy : in Proxy_Object);
-- Clone the <b>Handler</b> instance and get a copy of that single object.
overriding
function Clone (Handler : in Mapper) return Util.Serialize.Mappers.Mapper_Access;
--
procedure Bind (Into : in out Mapper;
Getter : in Get_Member_Access);
procedure Bind (Into : in out Mapper;
From : in Mapper_Access);
function Get_Getter (From : in Mapper) return Get_Member_Access;
-- Set the element in the context. When <b>Release</b> is set, the element <b>Element</b>
-- will be freed when the reader context is deleted (by <b>Finalize</b>).
procedure Set_Context (Ctx : in out Util.Serialize.Contexts.Context'Class;
Element : in Element_Type_Access;
Release : in Boolean := False);
-- Build a default mapping based on the <b>Fields</b> enumeration.
-- The enumeration name is used for the mapping name with the optional <b>FIELD_</b>
-- prefix stripped.
procedure Add_Default_Mapping (Into : in out Mapper);
-- Write the element on the stream using the mapper description.
procedure Write (Handler : in Mapper;
Stream : in out Util.Serialize.IO.Output_Stream'Class;
Element : in Element_Type);
-- Write the element on the stream using the mapper description.
procedure Write (Handler : in Util.Serialize.Mappers.Mapper'Class;
Getter : in Get_Member_Access;
Stream : in out Util.Serialize.IO.Output_Stream'Class;
Element : in Element_Type);
private
type Element_Data is new Util.Serialize.Contexts.Data with record
Element : Element_Type_Access;
Release : Boolean;
end record;
type Mapper is new Util.Serialize.Mappers.Mapper with record
Execute : Proxy_Object := Set_Member'Access;
Get_Member : Get_Member_Access;
end record;
type Attribute_Mapping is new Mapping with record
Index : Fields;
end record;
type Attribute_Mapping_Access is access all Attribute_Mapping'Class;
procedure Set_Member (Attr : in Attribute_Mapping;
Element : in out Element_Type;
Value : in Util.Beans.Objects.Object);
type Proxy_Mapper is new Mapper with null record;
type Proxy_Mapper_Access is access all Proxy_Mapper'Class;
-- Find the mapper associated with the given name.
-- Returns null if there is no mapper.
overriding
function Find_Mapper (Controller : in Proxy_Mapper;
Name : in String;
Attribute : in Boolean := False)
return Util.Serialize.Mappers.Mapper_Access;
end Util.Serialize.Mappers.Record_Mapper;
|
Allow an indefinite type as Element_Type for the generic package
|
Allow an indefinite type as Element_Type for the generic package
|
Ada
|
apache-2.0
|
flottokarotto/ada-util,Letractively/ada-util,flottokarotto/ada-util,Letractively/ada-util
|
9793de1bac2738e3f7b070cd678657e1230f6008
|
regtests/security-oauth-jwt-tests.ads
|
regtests/security-oauth-jwt-tests.ads
|
-----------------------------------------------------------------------
-- Security-oayth-jwt-tests - Unit tests for JSON Web Token
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package Security.OAuth.JWT.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test Decode operation with errors.
procedure Test_Decode_Error (T : in out Test);
generic
with function Get (From : in Token) return String;
Value : String;
procedure Test_Operation (T : in out Test);
generic
with function Get (From : in Token) return Ada.Calendar.Time;
Value : String;
procedure Test_Time_Operation (T : in out Test);
end Security.OAuth.JWT.Tests;
|
Add unit tests for JWT
|
Add unit tests for JWT
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
|
18fef9c52c1e969262093144960360d2cb31f79d
|
awa/plugins/awa-images/regtests/awa-images-tests.adb
|
awa/plugins/awa-images/regtests/awa-images-tests.adb
|
-----------------------------------------------------------------------
-- awa-images-tests -- Unit tests for images module
-- Copyright (C) 2018, 2019, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Strings;
with ADO;
with Servlet.Streams;
with ASF.Tests;
with AWA.Tests.Helpers.Users;
with AWA.Images.Beans;
with AWA.Images.Models;
with AWA.Images.Modules;
with AWA.Services.Contexts;
with Security.Contexts;
package body AWA.Images.Tests is
use Ada.Strings.Unbounded;
use AWA.Tests;
package Caller is new Util.Test_Caller (Test, "Images.Beans");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Images.Beans.Create",
Test_Create_Image'Access);
Caller.Add_Test (Suite, "Test AWA.Images.Servlets (missing)",
Test_Missing_Image'Access);
end Add_Tests;
-- ------------------------------
-- Get some access on the wiki as anonymous users.
-- ------------------------------
procedure Verify_Anonymous (T : in out Test;
Page : in String;
Title : in String) is
pragma Unreferenced (Title);
Request : Servlet.Requests.Mockup.Request;
Reply : Servlet.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/storages/images.html",
"images-anonymous-list.html");
ASF.Tests.Assert_Contains (T, "List of pages", Reply,
"Wiki list recent page is invalid");
end Verify_Anonymous;
-- ------------------------------
-- Verify that the wiki lists contain the given page.
-- ------------------------------
procedure Verify_List_Contains (T : in out Test;
Name : in String) is
Request : Servlet.Requests.Mockup.Request;
Reply : Servlet.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/storages/documents.html",
"storage-list.html");
ASF.Tests.Assert_Contains (T, "Documents of the workspace", Reply,
"List of documents is invalid");
end Verify_List_Contains;
-- ------------------------------
-- Test access to the blog as anonymous user.
-- ------------------------------
procedure Test_Anonymous_Access (T : in out Test) is
begin
T.Verify_Anonymous ("", "");
end Test_Anonymous_Access;
-- ------------------------------
-- Test creation of image by simulating web requests.
-- ------------------------------
procedure Test_Create_Image (T : in out Test) is
Request : Servlet.Requests.Mockup.Request;
Reply : Servlet.Responses.Mockup.Response;
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
Request.Set_Parameter ("folder-name", "Image Folder Name");
Request.Set_Parameter ("storage-folder-create-form", "1");
Request.Set_Parameter ("storage-folder-create-button", "1");
ASF.Tests.Do_Post (Request, Reply, "/storages/forms/folder-create.html", "folder-create-form.html");
T.Assert (Reply.Get_Status = Servlet.Responses.SC_OK,
"Invalid response after folder creation");
ASF.Tests.Do_Get (Request, Reply, "/storages/images.html",
"image-list.html");
ASF.Tests.Assert_Contains (T, "Documents of the workspace", Reply,
"List of documents is invalid (title)");
ASF.Tests.Assert_Contains (T, "Test Folder Name", Reply,
"List of documents is invalid (content)");
end Test_Create_Image;
-- ------------------------------
-- Test getting an image which does not exist.
-- ------------------------------
procedure Test_Missing_Image (T : in out Test) is
Request : Servlet.Requests.Mockup.Request;
Reply : Servlet.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/storages/images/12345345/view/missing.jpg",
"image-file-missing.html");
ASF.Tests.Assert_Matches (T, ".title.Page not found./title.", Reply,
"Page for a missing document is invalid",
Servlet.Responses.SC_NOT_FOUND);
end Test_Missing_Image;
end AWA.Images.Tests;
|
Implement the tests for the image service by simulating web requests
|
Implement the tests for the image service by simulating web requests
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
|
f901323dd98ebdde72eb63fa8de8af2140e3164d
|
src/asis/a4g-gnat_int.ads
|
src/asis/a4g-gnat_int.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . G N A T _ I N T --
-- --
-- S p e c --
-- --
-- Copyright (C) 1995-2008, Free Software Foundation, Inc. --
-- --
-- ASIS-for-GNAT is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 2, or (at your option) any later --
-- version. ASIS-for-GNAT is distributed in the hope that it will be use- --
-- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- --
-- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General --
-- Public License for more details. You should have received a copy of the --
-- GNU General Public License distributed with ASIS-for-GNAT; see file --
-- COPYING. If not, write to the Free Software Foundation, 51 Franklin --
-- Street, Fifth Floor, Boston, MA 02110-1301, USA. --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the --
-- Software Engineering Laboratory of the Swiss Federal Institute of --
-- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the --
-- Scientific Research Computer Center of Moscow State University (SRCC --
-- MSU), Russia, with funding partially provided by grants from the Swiss --
-- National Science Foundation and the Swiss Academy of Engineering --
-- Sciences. ASIS-for-GNAT is now maintained by AdaCore --
-- (http://www.adacore.com). --
-- --
------------------------------------------------------------------------------
-- This package contains the utility routines used for calling the GNAT
-- compiler from inside the ASIS implementation routines to create a tree
-- file. These routines may be used by ASIS-based tools as well. The idea is
-- to call GNAT in a black-box manner. The current version of this package
-- borrows most of the ideas and the code patterns from the body of the
-- GNAT Make package (which defines the gnatmake-related routines).
-- Unfortunately, GNAT do not provide the public interface to these
-- routines, so we simply have copied the code from make.adb with some
-- modifications.
--
-- This package also contains the routine which reads the tree file with
-- checking the GNAT-ASIS versions compartibility.
with Ada.Calendar; use Ada.Calendar;
with A4G.A_Types; use A4G.A_Types;
with A4G.A_Debug;
with GNAT.OS_Lib; use GNAT.OS_Lib;
with Types; use Types;
package A4G.GNAT_Int is
-----------------------------------
-- Compiler Variables & Routines --
-----------------------------------
Nul_Argument_List : constant Argument_List (1 .. 0) := (others => null);
-- The flags listed below are used to form the appropriate GNAT or
-- gnatmake call to create the tree file
Comp_Flag : constant String_Access := new String'("-c");
GNAT_Flag : constant String_Access := new String'("-gnatg");
GNAT_Flag_ct : constant String_Access := new String'("-gnatct");
GNAT_Flag_t : constant String_Access := new String'("-gnatt");
GNAT_Flag_ws : constant String_Access := new String'("-gnatws");
GNAT_Flag_yN : constant String_Access := new String'("-gnatyN");
GNAT_Flag_05 : constant String_Access := new String'("-gnat05");
GCC_Flag_X : constant String_Access := new String'("-x");
GCC_Par_Ada : constant String_Access := new String'("ada");
GCC_Flag_o : constant String_Access := new String'("-o");
GNATMAKE_Flag_q : constant String_Access := new String'("-q");
GNATMAKE_Flag_u : constant String_Access := new String'("-u");
GNATMAKE_Flag_f : constant String_Access := new String'("-f");
GNATMAKE_Flag_cargs : constant String_Access := new String'("-cargs");
-- Display_Executed_Programs : Boolean renames A4G.A_Debug.Debug_Mode;
-- Set to True if name of commands should be output on stderr.
-- Now this flag is toughtly binded with the flag setting the
-- ASIS Debug Mode. Is it a good decision?
function Execute
(Program : String_Access;
Args : Argument_List;
Compiler_Out : String := "";
Display_Call : Boolean := A4G.A_Debug.Debug_Mode)
return Boolean;
-- Executes Program. If the program is not set (the actual for Program is
-- null), executes the gcc command Args contains the arguments to be passed
-- to Program. If the program is executed successfully True is returned.
--
-- If Compiler_Out is a non-empty string, this string is treated as the
-- name of a text file to redirect the compiler output into (if the file
-- does not exist, it is created). Othervise the compiler output is
-- sent to Stderr.
--
-- If Display_Call is ON, outputs into Stderr the command used to execure
-- Program.
procedure Create_Tree (Source_File : String_Access;
Context : Context_Id;
Is_Predefined : Boolean;
Success : out Boolean);
-- Tries to create the tree output file for the given source file
-- in the context of a given Context. Uses the "standard" GNAT
-- installation to do this
procedure Tree_In_With_Version_Check
(Desc : File_Descriptor;
Cont : Context_Id;
Success : out Boolean);
-- Desc is the file descriptor for the file containing the tree file
-- created by the compiler, Cont is the Id of the Context this tree is
-- supposed to belong to. This routine reads in the content of the tree
-- file and makes the GNAT-ASIS version check as a part of tree reading.
-- If the version check fails or if any error corresponding to the problems
-- with the expected tree format is detected, Program_Error is raised with
-- the exception message "Inconsistent versions of GNAT and ASIS". If
-- the tree can not be read in because of any other reason (for example,
-- it is not compile-only), the Success parameter is set OFF and the
-- continuation depends on the Context parameters. If the tree has been
-- read in successfully and if it is compile-only, Success is set ON.
--
-- Before calling this procedure, a caller should put the name of the tree
-- file to read into A_Name_Buffer.
--
-- NOTE: the procedure always closes Desc before returning. Closing it
-- the second time is erroneous.
function A_Time (T : Time_Stamp_Type)
return Time;
-- Converts GNAT file time stamp into the corresponding value
-- of Asis_Time.
end A4G.GNAT_Int;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
|
f2145816fcef15d943cf6ee651d54f5b63fec0c6
|
regtests/util-streams-buffered-lzma-tests.ads
|
regtests/util-streams-buffered-lzma-tests.ads
|
-----------------------------------------------------------------------
-- util-streams-buffered-lzma-tests -- Unit tests for LZMA buffered streams
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package Util.Streams.Buffered.Lzma.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
procedure Test_Compress_Stream (T : in out Test);
end Util.Streams.Buffered.Lzma.Tests;
|
Add a new test for Compress_Stream using LZMA
|
Add a new test for Compress_Stream using LZMA
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
|
cb79b4859cc53f34b08e6469f293a38c1a3177c4
|
src/util-beans-objects-datasets.adb
|
src/util-beans-objects-datasets.adb
|
-----------------------------------------------------------------------
-- Util.Beans.Objects.Datasets -- Datasets
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Util.Beans.Objects.Datasets is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Object_Array,
Name => Object_Array_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Object => Dataset_Array,
Name => Dataset_Array_Access);
-- ------------------------------
-- Get the number of elements in the list.
-- ------------------------------
overriding
function Get_Count (From : in Dataset) return Natural is
begin
return From.Count;
end Get_Count;
-- ------------------------------
-- Set the current row index. Valid row indexes start at 1.
-- ------------------------------
overriding
procedure Set_Row_Index (From : in out Dataset;
Index : in Natural) is
begin
From.Current_Pos := Index;
From.Current.Data := From.Data (Index);
end Set_Row_Index;
-- ------------------------------
-- Get the element at the current row index.
-- ------------------------------
overriding
function Get_Row (From : in Dataset) return Util.Beans.Objects.Object is
begin
return From.Row;
end Get_Row;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Dataset;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "count" then
return Util.Beans.Objects.To_Object (From.Count);
elsif Name = "rowIndex" then
return Util.Beans.Objects.To_Object (From.Current_Pos);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Append a row in the dataset and call the fill procedure to populate
-- the row content.
-- ------------------------------
procedure Append (Into : in out Dataset;
Fill : not null access procedure (Data : in out Object_Array)) is
Data : constant Object_Array_Access := new Object_Array (1 .. Into.Columns);
begin
if Into.Data = null then
Into.Data := new Dataset_Array (1 .. 10);
elsif Into.Count >= Into.Data'Last then
declare
-- Sun's Java ArrayList use a 2/3 grow factor.
-- Python's array use 8/9.
Grow : constant Positive := (Into.Count * 2) / 3;
Set : constant Dataset_Array_Access := new Dataset_Array (1 .. Grow);
begin
Set (Into.Data'Range) := Into.Data.all;
Free (Into.Data);
Into.Data := Set;
end;
end if;
Into.Count := Into.Count + 1;
Into.Data (Into.Count) := Data;
Fill (Data.all);
end Append;
-- ------------------------------
-- Add a column to the dataset. If the position is not specified,
-- the column count is incremented and the name associated with the last column.
-- Raises Invalid_State exception if the dataset contains some rows,
-- ------------------------------
procedure Add_Column (Into : in out Dataset;
Name : in String;
Pos : in Natural := 0) is
Col : Positive;
begin
if Into.Count /= 0 then
raise Invalid_State with "The dataset contains some rows.";
end if;
if Pos = 0 then
Col := Into.Columns + 1;
else
Col := Pos;
end if;
Into.Map.Insert (Name, Col);
if Into.Columns < Col then
Into.Columns := Col;
end if;
end Add_Column;
-- ------------------------------
-- Clear the content of the dataset.
-- ------------------------------
procedure Clear (Set : in out Dataset) is
begin
for I in 1 .. Set.Count loop
Free (Set.Data (I));
end loop;
Set.Count := 0;
Set.Current_Pos := 0;
Set.Current.Data := null;
end Clear;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Row;
Name : in String) return Util.Beans.Objects.Object is
Pos : constant Dataset_Map.Cursor := From.Map.Find (Name);
begin
if From.Data /= null and then Dataset_Map.Has_Element (Pos) then
return From.Data (Dataset_Map.Element (Pos));
else
return Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out Row;
Name : in String;
Value : in Util.Beans.Objects.Object) is
Pos : constant Dataset_Map.Cursor := From.Map.Find (Name);
begin
if From.Data /= null and then Dataset_Map.Has_Element (Pos) then
From.Data (Dataset_Map.Element (Pos)) := Value;
end if;
end Set_Value;
-- ------------------------------
-- Initialize the dataset and the row bean instance.
-- ------------------------------
overriding
procedure Initialize (Set : in out Dataset) is
begin
Set.Row := To_Object (Value => Set.Current'Unchecked_Access,
Storage => STATIC);
Set.Current.Map := Set.Map'Unchecked_Access;
end Initialize;
-- ------------------------------
-- Release the dataset storage.
-- ------------------------------
overriding
procedure Finalize (Set : in out Dataset) is
begin
Set.Clear;
Free (Set.Data);
end Finalize;
end Util.Beans.Objects.Datasets;
|
Implement the Datasets package
|
Implement the Datasets package
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
|
ad1da3bc5ed08bebdb430e8764ac07f4481450af
|
src/util-events-timers.adb
|
src/util-events-timers.adb
|
-----------------------------------------------------------------------
-- util-events-timers -- Timer list management
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Util.Events.Timers is
use type Ada.Real_Time.Time;
procedure Free is
new Ada.Unchecked_Deallocation (Object => Timer_Node,
Name => Timer_Node_Access);
-- Repeat the timer.
procedure Repeat (Event : in out Timer_Ref;
In_Time : in Ada.Real_Time.Time_Span) is
begin
null;
end Repeat;
-- -----------------------
-- Cancel the timer.
-- -----------------------
procedure Cancel (Event : in out Timer_Ref) is
begin
if Event.Value /= null and then Event.Value.List /= null then
Event.Value.List.all.Cancel (Event.Value);
Event.Value.List := null;
end if;
end Cancel;
-- -----------------------
-- Check if the timer is ready to be executed.
-- -----------------------
function Is_Scheduled (Event : in Timer_Ref) return Boolean is
begin
return Event.Value /= null and then Event.Value.List /= null;
end Is_Scheduled;
-- -----------------------
-- Returns the deadline time for the timer execution.
-- Returns Time'Last if the timer is not scheduled.
-- -----------------------
function Time_Of_Event (Event : in Timer_Ref) return Ada.Real_Time.Time is
begin
return (if Event.Value /= null then Event.Value.Deadline else Ada.Real_Time.Time_Last);
end Time_Of_Event;
-- -----------------------
-- Set a timer to be called at the given time.
-- -----------------------
procedure Set_Timer (List : in out Timer_List;
Handler : in Timer_Access;
Event : in out Timer_Ref'Class;
At_Time : in Ada.Real_Time.Time) is
begin
if Event.Value = null then
Event.Value := new Timer_Node;
end if;
Event.Value.Handler := Handler;
-- Cancel the timer if it is part of another timer manager.
if Event.Value.List /= null and Event.Value.List /= List.Manager'Unchecked_Access then
Event.Value.List.all.Cancel (Event.Value);
end if;
-- Update the timer.
Event.Value.List := List.Manager'Unchecked_Access;
List.Manager.Add (Event.Value, At_Time);
end Set_Timer;
-- -----------------------
-- Process the timer handlers that have passed the deadline and return the next
-- deadline. The <tt>Max_Count</tt> parameter allows to limit the number of timer handlers
-- that are called by operation. The default is not limited.
-- -----------------------
procedure Process (List : in out Timer_List;
Timeout : out Ada.Real_Time.Time;
Max_Count : in Natural := Natural'Last) is
Timer : Timer_Ref;
begin
loop
List.Manager.Find_Next (Timeout, Timer);
exit when not Timer.Is_Scheduled;
Timer.Value.Handler.Time_Handler (Timer);
end loop;
end Process;
overriding
procedure Adjust (Object : in out Timer_Ref) is
begin
if Object.Value /= null then
Util.Concurrent.Counters.Increment (Object.Value.Counter);
end if;
end Adjust;
overriding
procedure Finalize (Object : in out Timer_Ref) is
Is_Zero : Boolean;
begin
if Object.Value /= null then
Util.Concurrent.Counters.Decrement (Object.Value.Counter, Is_Zero);
if Is_Zero then
Free (Object.Value);
else
Object.Value := null;
end if;
end if;
end Finalize;
protected body Timer_Manager is
-- -----------------------
-- Add a timer.
-- -----------------------
procedure Add (Timer : in out Timer_Node_Access;
Deadline : in Ada.Real_Time.Time) is
Current : Timer_Node_Access := List;
Prev : Timer_Node_Access;
begin
Util.Concurrent.Counters.Increment (Timer.Counter);
if Timer.List /= null then
Cancel (Timer);
end if;
Timer.Deadline := Deadline;
while Current /= null loop
if Current.Deadline < Deadline then
if Prev = null then
List := Timer;
else
Prev.Next := Timer;
end if;
Timer.Next := Current;
Current.Prev := Timer;
return;
end if;
Prev := Current;
Current := Current.Next;
end loop;
if Prev = null then
List := Timer;
Timer.Prev := null;
else
Prev.Next := Timer;
Timer.Prev := Prev;
end if;
Timer.Next := null;
end Add;
-- -----------------------
-- Cancel a timer.
-- -----------------------
procedure Cancel (Timer : in out Timer_Node_Access) is
Is_Zero : Boolean;
begin
if Timer.List = null then
return;
end if;
if List = Timer then
List := Timer.Next;
Timer.Prev := null;
if List /= null then
List.Prev := null;
end if;
elsif Timer.Prev /= null then
Timer.Prev.Next := Timer.Next;
Timer.Next.Prev := Timer.Prev;
else
return;
end if;
Timer.Next := null;
Timer.Prev := null;
Timer.List := null;
Util.Concurrent.Counters.Decrement (Timer.Counter, Is_Zero);
if Is_Zero then
Free (Timer);
end if;
end Cancel;
-- -----------------------
-- Find the next timer to be executed or return the next deadline.
-- -----------------------
procedure Find_Next (Deadline : out Ada.Real_Time.Time;
Timer : in out Timer_Ref) is
Now : constant Ada.Real_Time.Time := Ada.Real_Time.Clock;
begin
if List = null then
Timer.Finalize;
Deadline := Ada.Real_Time.Time_Last;
elsif List.Deadline < Now then
Timer.Value := List;
Util.Concurrent.Counters.Increment (Timer.Value.Counter);
List := List.Next;
if List /= null then
List.Prev := null;
Deadline := List.Deadline;
else
Deadline := Ada.Real_Time.Time_Last;
end if;
else
Deadline := List.Deadline;
Timer.Finalize;
end if;
end Find_Next;
end Timer_Manager;
overriding
procedure Finalize (Object : in out Timer_List) is
begin
null;
end Finalize;
end Util.Events.Timers;
|
Implement the timer management operations
|
Implement the timer management operations
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
|
fb36f928e9706247c1dff891fe6417281c8c90c0
|
regtests/asf-converters-tests.ads
|
regtests/asf-converters-tests.ads
|
-----------------------------------------------------------------------
-- asf-converters-tests - Unit tests for ASF.Converters
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with ASF.Contexts.Faces.Tests;
package ASF.Converters.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new ASF.Contexts.Faces.Tests.Test with null record;
-- Test the date short converter.
procedure Test_Date_Short_Converter (T : in out Test);
-- Test the date medium converter.
procedure Test_Date_Medium_Converter (T : in out Test);
-- Test the date long converter.
procedure Test_Date_Long_Converter (T : in out Test);
-- Test the date full converter.
procedure Test_Date_Full_Converter (T : in out Test);
-- Test the time short converter.
procedure Test_Time_Short_Converter (T : in out Test);
-- Test the time short converter.
procedure Test_Time_Medium_Converter (T : in out Test);
-- Test the time long converter.
procedure Test_Time_Long_Converter (T : in out Test);
end ASF.Converters.Tests;
|
Add a new set of unit tests for the date converter
|
Add a new set of unit tests for the date converter
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
|
145f5678da2e21364ea5589944d79d20974038cc
|
hal/src/hal-block_drivers.ads
|
hal/src/hal-block_drivers.ads
|
with Interfaces; use Interfaces;
package HAL.Block_Drivers is
type Block_Driver is limited interface;
type Block_Driver_Ref is access all Block_Driver'Class;
subtype Block is Byte_Array;
function Read
(This : in out Block_Driver;
Block_Number : Unsigned_32;
Data : out Block)
return Boolean is abstract;
function Write
(This : in out Block_Driver;
Block_Number : Unsigned_32;
Data : Block)
return Boolean is abstract;
end HAL.Block_Drivers;
|
Add block driver interface
|
HAL: Add block driver interface
|
Ada
|
bsd-3-clause
|
simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,ellamosi/Ada_BMP_Library
|
|
c7ce62dcd188b73f85ffef4c669ca85c79b71cc2
|
src/util-serialize-io-json.adb
|
src/util-serialize-io-json.adb
|
-----------------------------------------------------------------------
-- util-serialize-io-json -- JSON Serialization Driver
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Characters.Latin_1;
with Ada.IO_Exceptions;
with Util.Strings;
with Util.Streams;
with Util.Streams.Buffered;
package body Util.Serialize.IO.JSON is
use Ada.Strings.Unbounded;
-- -----------------------
-- Write the string as a quoted JSON string
-- -----------------------
procedure Write_String (Stream : in out Output_Stream;
Value : in String) is
begin
Stream.Write ('"');
for I in Value'Range loop
declare
C : constant Character := Value (I);
begin
if C = '"' then
Stream.Write ("\""");
elsif C = '\' then
Stream.Write ("\\");
elsif Character'Pos (C) >= 16#20# then
Stream.Write (C);
else
case C is
when Ada.Characters.Latin_1.BS =>
Stream.Write ("\b");
when Ada.Characters.Latin_1.VT =>
Stream.Write ("\f");
when Ada.Characters.Latin_1.LF =>
Stream.Write ("\n");
when Ada.Characters.Latin_1.CR =>
Stream.Write ("\r");
when Ada.Characters.Latin_1.HT =>
Stream.Write ("\t");
when others =>
Util.Streams.Texts.TR.To_Hex (Streams.Buffered.Buffered_Stream (Stream), C);
end case;
end if;
end;
end loop;
Stream.Write ('"');
end Write_String;
-- -----------------------
-- Start writing an object identified by the given name
-- -----------------------
procedure Start_Entity (Stream : in out Output_Stream;
Name : in String) is
Current : access Node_Info := Node_Info_Stack.Current (Stream.Stack);
begin
if Current /= null then
if Current.Has_Fields then
Stream.Write (',');
else
Current.Has_Fields := True;
end if;
end if;
Node_Info_Stack.Push (Stream.Stack);
Current := Node_Info_Stack.Current (Stream.Stack);
Current.Has_Fields := False;
if Name'Length > 0 then
Stream.Write_String (Name);
Stream.Write (':');
end if;
Stream.Write ('{');
end Start_Entity;
-- -----------------------
-- Finish writing an object identified by the given name
-- -----------------------
procedure End_Entity (Stream : in out Output_Stream;
Name : in String) is
pragma Unreferenced (Name);
begin
Node_Info_Stack.Pop (Stream.Stack);
Stream.Write ('}');
end End_Entity;
-- -----------------------
-- Write an attribute member from the current object
-- -----------------------
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
Current : constant access Node_Info := Node_Info_Stack.Current (Stream.Stack);
begin
if Current /= null then
if Current.Has_Fields then
Stream.Write (",");
else
Current.Has_Fields := True;
end if;
end if;
Stream.Write_String (Name);
Stream.Write (':');
case Util.Beans.Objects.Get_Type (Value) is
when TYPE_NULL =>
Stream.Write ("null");
when TYPE_BOOLEAN =>
if Util.Beans.Objects.To_Boolean (Value) then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
when TYPE_INTEGER =>
Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value));
when others =>
Stream.Write_String (Util.Beans.Objects.To_String (Value));
end case;
end Write_Attribute;
-- -----------------------
-- Write an object value as an entity
-- -----------------------
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
Stream.Write_Attribute (Name, Value);
end Write_Entity;
-- -----------------------
-- Start an array that will contain the specified number of elements
-- -----------------------
procedure Start_Array (Stream : in out Output_Stream;
Length : in Ada.Containers.Count_Type) is
pragma Unreferenced (Length);
begin
Node_Info_Stack.Push (Stream.Stack);
Stream.Write ('[');
end Start_Array;
-- -----------------------
-- Finishes an array
-- -----------------------
procedure End_Array (Stream : in out Output_Stream) is
begin
Node_Info_Stack.Pop (Stream.Stack);
Stream.Write (']');
end End_Array;
-- -----------------------
-- Get the current location (file and line) to report an error message.
-- -----------------------
function Get_Location (Handler : in Parser) return String is
begin
return Util.Strings.Image (Handler.Line_Number);
end Get_Location;
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class) is
-- Put back a token in the buffer.
procedure Put_Back (P : in out Parser'Class;
Token : in Token_Type);
-- Parse the expression buffer to find the next token.
procedure Peek (P : in out Parser'Class;
Token : out Token_Type);
-- Parse a list of members
-- members ::= pair | pair ',' members
-- pair ::= string ':' value
-- value ::= string | number | object | array | true | false | null
procedure Parse_Pairs (P : in out Parser'Class);
-- Parse a value
-- value ::= string | number | object | array | true | false | null
procedure Parse_Value (P : in out Parser'Class;
Name : in String);
procedure Parse (P : in out Parser'Class);
procedure Parse (P : in out Parser'Class) is
Token : Token_Type;
begin
Peek (P, Token);
if Token /= T_LEFT_BRACE then
P.Error ("Missing '{'");
end if;
Parse_Pairs (P);
Peek (P, Token);
if Token /= T_RIGHT_BRACE then
P.Error ("Missing '}'");
end if;
end Parse;
-- ------------------------------
-- Parse a list of members
-- members ::= pair | pair ',' members
-- pair ::= string ':' value
-- value ::= string | number | object | array | true | false | null
-- ------------------------------
procedure Parse_Pairs (P : in out Parser'Class) is
Current_Name : Unbounded_String;
Token : Token_Type;
begin
loop
Peek (P, Token);
if Token /= T_STRING then
Put_Back (P, Token);
return;
end if;
Current_Name := P.Token;
Peek (P, Token);
if Token /= T_COLON then
P.Error ("Missing ':'");
end if;
Parse_Value (P, To_String (Current_Name));
Peek (P, Token);
if Token /= T_COMMA then
Put_Back (P, Token);
return;
end if;
end loop;
end Parse_Pairs;
-- ------------------------------
-- Parse a value
-- value ::= string | number | object | array | true | false | null
-- ------------------------------
procedure Parse_Value (P : in out Parser'Class;
Name : in String) is
Token : Token_Type;
begin
Peek (P, Token);
case Token is
when T_LEFT_BRACE =>
P.Start_Object (Name);
Parse_Pairs (P);
Peek (P, Token);
if Token /= T_RIGHT_BRACE then
P.Error ("Missing '}'");
end if;
P.Finish_Object (Name);
--
when T_LEFT_BRACKET =>
P.Start_Array (Name);
Peek (P, Token);
if Token /= T_RIGHT_BRACKET then
Put_Back (P, Token);
loop
Parse_Value (P, Name);
Peek (P, Token);
exit when Token = T_RIGHT_BRACKET;
if Token /= T_COMMA then
P.Error ("Missing ']'");
end if;
end loop;
end if;
P.Finish_Array (Name);
when T_NULL =>
P.Set_Member (Name, Util.Beans.Objects.Null_Object);
when T_NUMBER =>
P.Set_Member (Name, Util.Beans.Objects.To_Object (P.Token));
when T_STRING =>
P.Set_Member (Name, Util.Beans.Objects.To_Object (P.Token));
when T_TRUE =>
P.Set_Member (Name, Util.Beans.Objects.To_Object (True));
when T_FALSE =>
P.Set_Member (Name, Util.Beans.Objects.To_Object (False));
when T_EOF =>
P.Error ("End of stream reached");
return;
when others =>
P.Error ("Invalid token");
end case;
end Parse_Value;
-- ------------------------------
-- Put back a token in the buffer.
-- ------------------------------
procedure Put_Back (P : in out Parser'Class;
Token : in Token_Type) is
begin
P.Pending_Token := Token;
end Put_Back;
-- ------------------------------
-- Parse the expression buffer to find the next token.
-- ------------------------------
procedure Peek (P : in out Parser'Class;
Token : out Token_Type) is
C, C1 : Character;
begin
-- If a token was put back, return it.
if P.Pending_Token /= T_EOF then
Token := P.Pending_Token;
P.Pending_Token := T_EOF;
return;
end if;
if P.Has_Pending_Char then
C := P.Pending_Char;
else
-- Skip white spaces
loop
Stream.Read (Char => C);
if C = Ada.Characters.Latin_1.LF then
P.Line_Number := P.Line_Number + 1;
else
exit when C /= ' '
and C /= Ada.Characters.Latin_1.CR and C /= Ada.Characters.Latin_1.HT;
end if;
end loop;
end if;
P.Has_Pending_Char := False;
-- See what we have and continue parsing.
case C is
-- Literal string using double quotes
-- Collect up to the end of the string and put
-- the result in the parser token result.
when '"' =>
Delete (P.Token, 1, Length (P.Token));
loop
Stream.Read (Char => C1);
if C1 = '\' then
Stream.Read (Char => C1);
case C1 is
when '"' | '\' | '/' =>
C := C1;
when 'b' =>
C1 := Ada.Characters.Latin_1.BS;
when 'f' =>
C1 := Ada.Characters.Latin_1.VT;
when 'n' =>
C1 := Ada.Characters.Latin_1.LF;
when 'r' =>
C1 := Ada.Characters.Latin_1.CR;
when 't' =>
C1 := Ada.Characters.Latin_1.HT;
when 'u' =>
null;
when others =>
P.Error ("Invalid character '" & C1 & "' in \x sequence");
end case;
elsif C1 = C then
Token := T_STRING;
return;
end if;
Append (P.Token, C1);
end loop;
-- Number
when '-' | '0' .. '9' =>
Delete (P.Token, 1, Length (P.Token));
Append (P.Token, C);
loop
Stream.Read (Char => C);
exit when C not in '0' .. '9';
Append (P.Token, C);
end loop;
if C = '.' then
Append (P.Token, C);
loop
Stream.Read (Char => C);
exit when C not in '0' .. '9';
Append (P.Token, C);
end loop;
end if;
if C = 'e' or C = 'E' then
Append (P.Token, C);
Stream.Read (Char => C);
if C = '+' or C = '-' then
Append (P.Token, C);
Stream.Read (Char => C);
end if;
loop
Stream.Read (Char => C);
exit when C not in '0' .. '9';
Append (P.Token, C);
end loop;
end if;
if C /= ' ' and C /= Ada.Characters.Latin_1.HT then
P.Has_Pending_Char := True;
P.Pending_Char := C;
end if;
Token := T_NUMBER;
return;
-- Parse a name composed of letters or digits.
when 'a' .. 'z' | 'A' .. 'Z' =>
Delete (P.Token, 1, Length (P.Token));
Append (P.Token, C);
loop
Stream.Read (Char => C);
exit when not (C in 'a' .. 'z' or C in 'A' .. 'Z'
or C in '0' .. '9' or C = '_');
Append (P.Token, C);
end loop;
-- Putback the last character unless we can ignore it.
if C /= ' ' and C /= Ada.Characters.Latin_1.HT then
P.Has_Pending_Char := True;
P.Pending_Char := C;
end if;
-- and empty eq false ge gt le lt ne not null true
case Element (P.Token, 1) is
when 'n' | 'N' =>
if P.Token = "null" then
Token := T_NULL;
return;
end if;
when 'f' | 'F' =>
if P.Token = "false" then
Token := T_FALSE;
return;
end if;
when 't' | 'T' =>
if P.Token = "true" then
Token := T_TRUE;
return;
end if;
when others =>
null;
end case;
Token := T_UNKNOWN;
return;
when '{' =>
Token := T_LEFT_BRACE;
return;
when '}' =>
Token := T_RIGHT_BRACE;
return;
when '[' =>
Token := T_LEFT_BRACKET;
return;
when ']' =>
Token := T_RIGHT_BRACKET;
return;
when ':' =>
Token := T_COLON;
return;
when ',' =>
Token := T_COMMA;
return;
when others =>
Token := T_UNKNOWN;
return;
end case;
exception
when Ada.IO_Exceptions.Data_Error =>
Token := T_EOF;
return;
end Peek;
begin
Parse (Handler);
end Parse;
end Util.Serialize.IO.JSON;
|
-----------------------------------------------------------------------
-- util-serialize-io-json -- JSON Serialization Driver
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Characters.Latin_1;
with Ada.IO_Exceptions;
with Util.Strings;
with Util.Streams;
with Util.Streams.Buffered;
package body Util.Serialize.IO.JSON is
use Ada.Strings.Unbounded;
-- -----------------------
-- Write the string as a quoted JSON string
-- -----------------------
procedure Write_String (Stream : in out Output_Stream;
Value : in String) is
begin
Stream.Write ('"');
for I in Value'Range loop
declare
C : constant Character := Value (I);
begin
if C = '"' then
Stream.Write ("\""");
elsif C = '\' then
Stream.Write ("\\");
elsif Character'Pos (C) >= 16#20# then
Stream.Write (C);
else
case C is
when Ada.Characters.Latin_1.BS =>
Stream.Write ("\b");
when Ada.Characters.Latin_1.VT =>
Stream.Write ("\f");
when Ada.Characters.Latin_1.LF =>
Stream.Write ("\n");
when Ada.Characters.Latin_1.CR =>
Stream.Write ("\r");
when Ada.Characters.Latin_1.HT =>
Stream.Write ("\t");
when others =>
Util.Streams.Texts.TR.To_Hex (Streams.Buffered.Buffered_Stream (Stream), C);
end case;
end if;
end;
end loop;
Stream.Write ('"');
end Write_String;
-- -----------------------
-- Start writing an object identified by the given name
-- -----------------------
procedure Start_Entity (Stream : in out Output_Stream;
Name : in String) is
Current : access Node_Info := Node_Info_Stack.Current (Stream.Stack);
begin
if Current /= null then
if Current.Has_Fields then
Stream.Write (',');
else
Current.Has_Fields := True;
end if;
end if;
Node_Info_Stack.Push (Stream.Stack);
Current := Node_Info_Stack.Current (Stream.Stack);
Current.Has_Fields := False;
if Name'Length > 0 then
Stream.Write_String (Name);
Stream.Write (':');
end if;
Stream.Write ('{');
end Start_Entity;
-- -----------------------
-- Finish writing an object identified by the given name
-- -----------------------
procedure End_Entity (Stream : in out Output_Stream;
Name : in String) is
pragma Unreferenced (Name);
begin
Node_Info_Stack.Pop (Stream.Stack);
Stream.Write ('}');
end End_Entity;
-- -----------------------
-- Write an attribute member from the current object
-- -----------------------
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
Current : constant access Node_Info := Node_Info_Stack.Current (Stream.Stack);
begin
if Current /= null then
if Current.Has_Fields then
Stream.Write (",");
else
Current.Has_Fields := True;
end if;
end if;
Stream.Write_String (Name);
Stream.Write (':');
case Util.Beans.Objects.Get_Type (Value) is
when TYPE_NULL =>
Stream.Write ("null");
when TYPE_BOOLEAN =>
if Util.Beans.Objects.To_Boolean (Value) then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
when TYPE_INTEGER =>
Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value));
when others =>
Stream.Write_String (Util.Beans.Objects.To_String (Value));
end case;
end Write_Attribute;
-- -----------------------
-- Write an object value as an entity
-- -----------------------
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
Stream.Write_Attribute (Name, Value);
end Write_Entity;
-- -----------------------
-- Start an array that will contain the specified number of elements
-- -----------------------
procedure Start_Array (Stream : in out Output_Stream;
Length : in Ada.Containers.Count_Type) is
pragma Unreferenced (Length);
begin
Node_Info_Stack.Push (Stream.Stack);
Stream.Write ('[');
end Start_Array;
-- -----------------------
-- Finishes an array
-- -----------------------
procedure End_Array (Stream : in out Output_Stream) is
begin
Node_Info_Stack.Pop (Stream.Stack);
Stream.Write (']');
end End_Array;
-- -----------------------
-- Get the current location (file and line) to report an error message.
-- -----------------------
function Get_Location (Handler : in Parser) return String is
begin
return Util.Strings.Image (Handler.Line_Number);
end Get_Location;
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class) is
-- Put back a token in the buffer.
procedure Put_Back (P : in out Parser'Class;
Token : in Token_Type);
-- Parse the expression buffer to find the next token.
procedure Peek (P : in out Parser'Class;
Token : out Token_Type);
-- Parse a list of members
-- members ::= pair | pair ',' members
-- pair ::= string ':' value
-- value ::= string | number | object | array | true | false | null
procedure Parse_Pairs (P : in out Parser'Class);
-- Parse a value
-- value ::= string | number | object | array | true | false | null
procedure Parse_Value (P : in out Parser'Class;
Name : in String);
procedure Parse (P : in out Parser'Class);
procedure Parse (P : in out Parser'Class) is
Token : Token_Type;
begin
Peek (P, Token);
if Token /= T_LEFT_BRACE then
P.Error ("Missing '{'");
end if;
Parse_Pairs (P);
Peek (P, Token);
if Token /= T_RIGHT_BRACE then
P.Error ("Missing '}'");
end if;
end Parse;
-- ------------------------------
-- Parse a list of members
-- members ::= pair | pair ',' members
-- pair ::= string ':' value
-- value ::= string | number | object | array | true | false | null
-- ------------------------------
procedure Parse_Pairs (P : in out Parser'Class) is
Current_Name : Unbounded_String;
Token : Token_Type;
begin
loop
Peek (P, Token);
if Token /= T_STRING then
Put_Back (P, Token);
return;
end if;
Current_Name := P.Token;
Peek (P, Token);
if Token /= T_COLON then
P.Error ("Missing ':'");
end if;
Parse_Value (P, To_String (Current_Name));
Peek (P, Token);
if Token /= T_COMMA then
Put_Back (P, Token);
return;
end if;
end loop;
end Parse_Pairs;
-- ------------------------------
-- Parse a value
-- value ::= string | number | object | array | true | false | null
-- ------------------------------
procedure Parse_Value (P : in out Parser'Class;
Name : in String) is
Token : Token_Type;
begin
Peek (P, Token);
case Token is
when T_LEFT_BRACE =>
P.Start_Object (Name);
Parse_Pairs (P);
Peek (P, Token);
if Token /= T_RIGHT_BRACE then
P.Error ("Missing '}'");
end if;
P.Finish_Object (Name);
--
when T_LEFT_BRACKET =>
P.Start_Array (Name);
Peek (P, Token);
if Token /= T_RIGHT_BRACKET then
Put_Back (P, Token);
loop
Parse_Value (P, Name);
Peek (P, Token);
exit when Token = T_RIGHT_BRACKET;
if Token /= T_COMMA then
P.Error ("Missing ']'");
end if;
end loop;
end if;
P.Finish_Array (Name);
when T_NULL =>
P.Set_Member (Name, Util.Beans.Objects.Null_Object);
when T_NUMBER =>
P.Set_Member (Name, Util.Beans.Objects.To_Object (P.Token));
when T_STRING =>
P.Set_Member (Name, Util.Beans.Objects.To_Object (P.Token));
when T_TRUE =>
P.Set_Member (Name, Util.Beans.Objects.To_Object (True));
when T_FALSE =>
P.Set_Member (Name, Util.Beans.Objects.To_Object (False));
when T_EOF =>
P.Error ("End of stream reached");
return;
when others =>
P.Error ("Invalid token");
end case;
end Parse_Value;
-- ------------------------------
-- Put back a token in the buffer.
-- ------------------------------
procedure Put_Back (P : in out Parser'Class;
Token : in Token_Type) is
begin
P.Pending_Token := Token;
end Put_Back;
-- ------------------------------
-- Parse the expression buffer to find the next token.
-- ------------------------------
procedure Peek (P : in out Parser'Class;
Token : out Token_Type) is
C, C1 : Character;
begin
-- If a token was put back, return it.
if P.Pending_Token /= T_EOF then
Token := P.Pending_Token;
P.Pending_Token := T_EOF;
return;
end if;
if P.Has_Pending_Char then
C := P.Pending_Char;
else
-- Skip white spaces
loop
Stream.Read (Char => C);
if C = Ada.Characters.Latin_1.LF then
P.Line_Number := P.Line_Number + 1;
else
exit when C /= ' '
and C /= Ada.Characters.Latin_1.CR and C /= Ada.Characters.Latin_1.HT;
end if;
end loop;
end if;
P.Has_Pending_Char := False;
-- See what we have and continue parsing.
case C is
-- Literal string using double quotes
-- Collect up to the end of the string and put
-- the result in the parser token result.
when '"' =>
Delete (P.Token, 1, Length (P.Token));
loop
Stream.Read (Char => C1);
if C1 = '\' then
Stream.Read (Char => C1);
case C1 is
when '"' | '\' | '/' =>
null;
when 'b' =>
C1 := Ada.Characters.Latin_1.BS;
when 'f' =>
C1 := Ada.Characters.Latin_1.VT;
when 'n' =>
C1 := Ada.Characters.Latin_1.LF;
when 'r' =>
C1 := Ada.Characters.Latin_1.CR;
when 't' =>
C1 := Ada.Characters.Latin_1.HT;
when 'u' =>
null;
when others =>
P.Error ("Invalid character '" & C1 & "' in \x sequence");
end case;
elsif C1 = C then
Token := T_STRING;
return;
end if;
Append (P.Token, C1);
end loop;
-- Number
when '-' | '0' .. '9' =>
Delete (P.Token, 1, Length (P.Token));
Append (P.Token, C);
loop
Stream.Read (Char => C);
exit when C not in '0' .. '9';
Append (P.Token, C);
end loop;
if C = '.' then
Append (P.Token, C);
loop
Stream.Read (Char => C);
exit when C not in '0' .. '9';
Append (P.Token, C);
end loop;
end if;
if C = 'e' or C = 'E' then
Append (P.Token, C);
Stream.Read (Char => C);
if C = '+' or C = '-' then
Append (P.Token, C);
Stream.Read (Char => C);
end if;
loop
Stream.Read (Char => C);
exit when C not in '0' .. '9';
Append (P.Token, C);
end loop;
end if;
if C /= ' ' and C /= Ada.Characters.Latin_1.HT then
P.Has_Pending_Char := True;
P.Pending_Char := C;
end if;
Token := T_NUMBER;
return;
-- Parse a name composed of letters or digits.
when 'a' .. 'z' | 'A' .. 'Z' =>
Delete (P.Token, 1, Length (P.Token));
Append (P.Token, C);
loop
Stream.Read (Char => C);
exit when not (C in 'a' .. 'z' or C in 'A' .. 'Z'
or C in '0' .. '9' or C = '_');
Append (P.Token, C);
end loop;
-- Putback the last character unless we can ignore it.
if C /= ' ' and C /= Ada.Characters.Latin_1.HT then
P.Has_Pending_Char := True;
P.Pending_Char := C;
end if;
-- and empty eq false ge gt le lt ne not null true
case Element (P.Token, 1) is
when 'n' | 'N' =>
if P.Token = "null" then
Token := T_NULL;
return;
end if;
when 'f' | 'F' =>
if P.Token = "false" then
Token := T_FALSE;
return;
end if;
when 't' | 'T' =>
if P.Token = "true" then
Token := T_TRUE;
return;
end if;
when others =>
null;
end case;
Token := T_UNKNOWN;
return;
when '{' =>
Token := T_LEFT_BRACE;
return;
when '}' =>
Token := T_RIGHT_BRACE;
return;
when '[' =>
Token := T_LEFT_BRACKET;
return;
when ']' =>
Token := T_RIGHT_BRACKET;
return;
when ':' =>
Token := T_COLON;
return;
when ',' =>
Token := T_COMMA;
return;
when others =>
Token := T_UNKNOWN;
return;
end case;
exception
when Ada.IO_Exceptions.Data_Error =>
Token := T_EOF;
return;
end Peek;
begin
Parser'Class (Handler).Start_Object ("");
Parse (Handler);
Parser'Class (Handler).Finish_Object ("");
end Parse;
end Util.Serialize.IO.JSON;
|
Fix parsing and mapping of JSON
|
Fix parsing and mapping of JSON
|
Ada
|
apache-2.0
|
Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util
|
52c7c02304231ebf7f276fec23422017e144755a
|
matp/src/events/mat-events-tools.ads
|
matp/src/events/mat-events-tools.ads
|
-----------------------------------------------------------------------
-- mat-events-tools - Profiler Events Description
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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.Vectors;
package MAT.Events.Tools is
Not_Found : exception;
package Target_Event_Vectors is
new Ada.Containers.Vectors (Positive, Target_Event_Type);
subtype Target_Event_Vector is Target_Event_Vectors.Vector;
subtype Target_Event_Cursor is Target_Event_Vectors.Cursor;
-- Find in the list the first event with the given type.
-- Raise <tt>Not_Found</tt> if the list does not contain such event.
function Find (List : in Target_Event_Vector;
Kind : in Probe_Index_Type) return Target_Event_Type;
end MAT.Events.Tools;
|
Declare the MAT.Events.Tools package and move the Target_Event_Vectors definition in it
|
Declare the MAT.Events.Tools package and move the Target_Event_Vectors definition in it
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
|
77e43d97c7285605a7902f818a0ab64896af35eb
|
ADA/src/main.adb
|
ADA/src/main.adb
|
with Ada.Text_IO;
use Ada.Text_IO;
procedure main is
begin -- Bonjour
Put("Hello Master Falindir");
end main;
|
Add ai with ADA
|
Add ai with ADA
|
Ada
|
mit
|
Falindir/AI,Falindir/AI,Falindir/AI,Falindir/AI,Falindir/AI,Falindir/AI,Falindir/AI,Falindir/AI,Falindir/AI,Falindir/AI,Falindir/AI,Falindir/AI,Falindir/AI
|
|
2245a25ab7ebf2636ceb61596418d84f48927312
|
src/asis/a4g-vcheck.ads
|
src/asis/a4g-vcheck.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . V C H E C K --
-- --
-- S p e c --
-- --
-- Copyright (C) 1995-2010, 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 Asis; use Asis;
with Asis.Text; use Asis.Text;
with Asis.Errors; use Asis.Errors;
with A4G.A_Types; use A4G.A_Types;
with A4G.Int_Knds; use A4G.Int_Knds;
-- This package contains the routines for checking the validity of the
-- arguments of the ASIS queries and for generating the diagnostic info.
-- This package in its current state originated from the very beginning of
-- the ASIS project and it definitely needs revising.
package A4G.Vcheck is
-- GNAT-style reformatting required!! Only formal compatibility with -gnatg
-- is achieved by now.
-- This package contains procedures for checking the validity of the
-- Context, Compilation_Unit and Element values, raising the
-- Asis-defined exceptions (with previous setting of the status
-- value and forming the Diagnosis string) in some standard
-- situations and utility subprograms to be used in the keeping to
-- the "catch-all" policy defined in the subsection 3.6 of the
-- ASIS: Detailed Semantics and Implementation Document (v. 1.1.1)
--
-- The first prototype implementation uses rather roof approach
-- to keep to the "catch-all" policy in respect to the
-- non-Asis-defined exceptions and to handle the status and Diagnosis
-- information. The main principles of this approach are:
--
-- (a) all non-Asis exceptions are caught by
--
-- when others =>
-- Raise_ASIS_Failed (Diagnosis => "Name of the routine in which"
-- &" this handler is" );
--
-- exception handler, and as a rule no attempt is undertaken
-- to recover from the error situation (Status is set as
-- "Value_Error" and ASIS_Failed is raised);
--
-- (b) Diagnosis string contains only general description of the failure
-- and the indication of the Asis query or low-level implementation
-- utility subprogram in which the Asis-defined exception was initially
-- raised;
--
-- (c) if Asis-defined exception propagates through the Asis implementation,
-- then the information related to the dynamic context of the exception
-- propagation is added to the Diagnosis (and separated by the
-- Asis_Types_And_Limits.ASIS_Line_Terminator constant).
--
-- (d) most of the routines in the Asis implementation should contain the
-- exception handler with the "others" choice (as described in the
-- paragraph (a) above. If it is known that the Asis_defined exception
-- could be raised in the procedure or function body, then the body
-- should contain two following exception handlers in the order given:
--
-- when Asis_ASIS_Inappropriate_Context |
-- ASIS_Inappropriate_Compilation_Unit |
-- ASIS_Inappropriate_Element =>
--
-- raise; -- nothing should be done additionally;
-- -- exception has been raised in the argument(s)
-- -- validity/appropriation checks in the same
-- -- frame
--
-- when ASIS_Failed -- | other possible Asis-defined exceptions
-- =>
-- Add_Call_Information (Outer_Call => "Name of the routine in which"
-- &" this handler is" );
-- raise; ---????????
--
-- when others =>
-- Raise_ASIS_Failed (Diagnosis => "Name of the routine in which"
-- &" this handler is" );
--
procedure Add (Phrase : String);
-- Adds Phrase to Diagnosis_Buffer and resets Diagnosis_Len. Exits with no
-- (further) change in Diagnosis_Buffer as soon as Diagnosis_Len attains
-- Max_Diagnosis_Length.
------------------------------------------------------------
-- Checking the validity of Context, Compilation_Unit and
-- Element
------------------------------------------------------------
------------------------------------------------------------
procedure Check_Validity
(Compilation_Unit : Asis.Compilation_Unit;
Query : String);
------------------------------------------------------------
-- Compilation_Unit - Specifies the unit to check
-- Query - Specifies the name of query in which the check
-- is performed. The parameter value is used to
-- form the Diagnosis string
--
-- Performs the check if the unit does not belong to the closed library
-- Sets the corresponding Status and forms the corresponding Diagnosis
-- if the check fails
--
-- BETTER DOCS NEEDED!!
---------------------------------------------------------------
procedure Check_Validity
(Element : Asis.Element;
Query : String);
------------------------------------------------------------
-- Element - Specifies the element to check
-- Query - Specifies the name of query in which the check is performed.
-- The parameter value is used to form the Diagnosis string
--
-- Performs the check if the element does not belong to the invalid
-- element
-- Sets the corresponding Status and forms the corresponding Diagnosis
-- if the check fails
--
-- BETTER DOCS NEEDED!!
---------------------------------------------------------------
procedure Check_Validity (Line : Asis.Text.Line;
Query : String);
------------------------------------------------------------
-- Line - Specifies the Line to check
-- Query - Specifies the name of query in which the check is performed.
-- The parameter value is used to form the Diagnosis string
--
-- Performs the check if the line does not belong to the invalid
-- Context
-- Sets the corresponding Status and forms the corresponding Diagnosis
-- if the check fails
--
-- BETTER DOCS NEEDED!!
------------------------------------------------------------
procedure Check_Validity (Context : Asis.Context;
Query : String);
------------------------------------------------------------
-- Context - Specifies the ASIS Context to check
-- Query - Specifies the name of query in which the check is performed.
-- The parameter value is used to form the Diagnosis string
--
-- Performs the check if the Context is not in inassosiated or inopened
-- state
-- Sets the corresponding Status and forms the corresponding Diagnosis
-- if the check fails
--
-- BETTER DOCS NEEDED!!
-------------------------------------
-- Raising Asis-defined exceptions --
-------------------------------------
procedure Raise_ASIS_Failed
(Diagnosis : String;
Argument : Asis.Element := Nil_Element;
Stat : Asis.Errors.Error_Kinds := Internal_Error;
Bool_Par : Boolean := False;
Internal_Bug : Boolean := True);
-- Raises ASIS_Failed with Stat as the value of ASIS Error Status.
-- Usually expects the query name as Diagnosis. If the corresponding ASIS
-- standard query has an optional boolean parameter, and if this parameter
-- is set on for the given call to this query, then Bool_Par is expected to
-- be set True. Internal_Bug specifies if the procedure is called for an
-- internal implementation bug.
-- This routine may be used to raise ASIS_Failed not only for the cases of
-- internal implementation errors. In this case Internal_Bug should be set
-- OFF, and Stat should specify the error kind.
-- If Argument is not IS_Nil, adds the debug image of the argument to the
-- diagnosis string.
procedure Raise_ASIS_Failed_In_Traversing
(Start_Element : Asis.Element;
Failure_At : Asis.Element;
Pre_Op : Boolean;
Exception_Info : String);
-- Raises ASIS_Failed with Stat as Unhandled_Exception_Error for the
-- situation when some non-ASIS exception is raised in actual Pre-
-- (Pre-Op is set ON) or Post-Operation (Pre_Op is set False). If forms the
-- diagnostic message indicating the starting Element of the traversal
-- (should be provided as the actual for Start_Element), the Element for
-- which the failure took place (actual for Failure_At) and the information
-- about the exception raised (passed as Exception_Info)
--------------------------------------------------------------------
procedure Raise_ASIS_Inappropriate_Compilation_Unit
(Diagnosis : String);
--------------------------------------------------------------------
-- Diagnosis - Specifies the query to which the Compilation Unit
-- with inappropriate kind was passed
--
-- Raises ASIS_Inappropriate_Compilation_Unit with Value_Error status
--
-- BETTER DOCS NEEDED!!
--------------------------------------------------------------------
procedure Raise_ASIS_Inappropriate_Element
(Diagnosis : String;
Wrong_Kind : Internal_Element_Kinds;
Status : Error_Kinds := Value_Error);
--------------------------------------------------------------------
-- Diagnosis - Specifies the query to which the Element with
-- inappropriate kind was passed
--
-- Raises ASIS_Inappropriate_Element with Status error status
--
-- BETTER DOCS NEEDED!!
--
--------------------------------------------------------------------
procedure Raise_ASIS_Inappropriate_Line_Number
(Diagnosis : String;
Status : Error_Kinds := Value_Error);
--------------------------------------------------------------------
procedure Not_Implemented_Yet (Diagnosis : String);
--------------------------------------------------------------------
-- Diagnosis - Specifies the query which has not been implemented
-- properly yet and has a placeholder as its body
--
-- Raises ASIS_Failed with Not_Implemented_Error status
--
-- This procedure is used in the placeholder bodies of the non-implemented
-- queries
--
-- BETTER DOCS NEEDED!!
--------------------------------------------------------------------
----------------------------------------------
-- Setting the Status and Diagnosis values --
----------------------------------------------
--------------------------------------------------------------------
procedure Set_Error_Status
(Status : Error_Kinds := Not_An_Error;
Diagnosis : String := Nil_Asis_String);
--------------------------------------------------------------------
--
-- This procedure is the full analog of the A4G.Set_Status
-- procedure, it is intended to be used as the implementation of the
-- A4G.Set_Status (by means of the renaming_as_a_body
-- in the body of Asis_Environment)
--------------------------------------------------------------------
-----------------------------
-- Adding Call Information --
-----------------------------
procedure Add_Call_Information
(Outer_Call : String;
Argument : Asis.Element := Nil_Element;
Bool_Par : Boolean := False);
-- Adds in the ASIS diagnosis the information about dynamically enclosing
-- calls when an ASIS exception is propagated from some dynamically
-- enclosed routine. If Argument is not Nil, adds its debug image in the
-- Diagnosis, if needed (that is, if Argument_Postponed flag is set on,
-- and resets this flag OFF after that)
pragma No_Return (Raise_ASIS_Failed);
pragma No_Return (Raise_ASIS_Inappropriate_Compilation_Unit);
pragma No_Return (Raise_ASIS_Inappropriate_Element);
pragma No_Return (Not_Implemented_Yet);
-------------------------------------------
-- The revised code is below this header --
-------------------------------------------
---------------------------------------------------------------------
-- Data Objects for Handling the Diagnosis string and Error Status --
---------------------------------------------------------------------
Status_Indicator : Error_Kinds := Not_An_Error;
Diagnosis_Buffer : String (1 .. Max_Diagnosis_Length);
Diagnosis_Len : Natural range 0 .. Max_Diagnosis_Length := 0;
-- The string buffer to form ASIS Diagnosis
---------------------------
-- ASIS Error handling --
---------------------------
-- The following documentation item should be revised when the revising of
-- the ASIS exception handling is completed (BB14-010)
-- According to the ASIS Standard, only ASIS-defined exceptions are allowed
-- to be raised by ASIS queries.
--
-- The semantics of ASIS_Inappropriate_*** expectations well-defined and is
-- supposed to be implemented in full conformance with ASIS Standard
-- requirements.
--
-- According to Asis.Exceptions, ASIS_Failed is "is a catch-all exception
-- that may be raised for different reasons in different ASIS
-- implementations".
--
-- We are using the following approach to handing and reporting the
-- internal implementation errors and to raising ASIS_Failed.
--
-- 1. According to the (rather ill-defined) requirement of the ASIS
-- Standard and other documents generated during the ASIS
-- standardization process (in particular, "ASIS: Detailed Semantics and
-- Implementation. Ada Semantic Interface Specification. ASIS version
-- 1.1.1. April 26, 1994 by Gary E. Barnes), the body of every ASIS
-- query contains 'when OTHERS' exception handler which does not allow
-- any non-ASIS exception to propagate out of any ASIS query. (The
-- exception is a set of rather trivial bodies of ASIS queries for which
-- raising of non-ASIS exceptions is practically impossible).
--
-- 2. By default any unexpected exception raise (that is, raising of any
-- non-ASIS exception because of any reason) is treated as ASIS
-- implementation error which should be immediately reported and which
-- does not allow to continue the execution of any ASIS application.
-- That is, detection of such an error should result in immediate exit
-- to OS. This is implemented as the default behavior of all the ASIS
-- and ASIS extensions queries.
--
-- 3. An application may want to continue its execution even in case when
-- an internal ASIS implementation error is detected. (The reason could
-- be to try to use some workarounds for known ASIS implementation
-- problems and to get the required information by some other ways).
-- For this the application may set the Keep_Going flag ON by setting
-- '-k' parameter of Asis.Implementation.Initialize. As a result,
-- instead of generating the exit to OS, ASIS_Failed is raised with
-- Unhandled_Exception_Error status.
--
-- 4. We have some other reasons for raising ASIS_Failed. It can be raised
-- in case when ASIS is initialized with "treat ASIS warnings as errors"
-- mode as a part of generating of the ASIS warning. We have to use
-- ASIS_Failed here, because the ASIS Standard does not give us any
-- other choice. ASIS_Failed may also be raised by queries from
-- Asis.Compilation_Units which are not supposed to be used for a
-- dynamic Context. The important thing is that when ASIS_Failed is
-- raised as a result of ASIS warning, the Error Status can never be
-- Unhandled_Exception_Error
--
-- 5. The general approach to exception handling in our ASIS implementation
-- is:
--
-- - For every standard ASIS query and for every ASIS Extensions query
-- which is not trivial enough to conclude that raising of any
-- non-ASIS exception is practically impossible, the body of this
-- query should contain "when EX : OTHERS' handler, and the only
-- statement in this handler should be the call to Report_ASIS_Bug
-- procedure (see the documentation of this procedure below)
--
-- - For every standard ASIS query and for every ASIS Extensions query
-- which is not trivial enough to conclude that generating of the ASIS
-- failure is practically impossible or for which we can not be sure
-- that its implementation does not use any other ASIS queries, the
-- body of this query should contain the handler for ASIS_Failed with
-- the following code
--
-- when ASIS_Failed =>
-- is Status_Indicator = Unhandled_Exception_Error then
-- Add_Call_Information (...)
-- end if;
--
-- raise;
--
-- The idea in behind is: if ASIS_Failed is the result of the internal
-- ASIS implementation bug (that is, unexpected exception suppressed),
-- we are collecting the information of enclosing calls, this may be
-- useful if the call to one ASIS query is used in the implementation
-- of some other ASIS query, the full "trace" of calls of the ASIS
-- queries may be useful for an ASIS application programmer if (s)he
-- would like to provide protections for ASIS bugs and to use some
-- workarounds. And if ASIS_Failed is a result of ASIS warning, it
-- should just propagated out of ASIS with the Diagnosis string formed
-- as a part of error generation. ASIS_Failed raised when calling
-- Asis.Compilation_Units queries which can not be used for a dynamic
-- context could never be raised inside the call to an ASIS query
-- enclosed into a call to some other ASIS query.
procedure Report_ASIS_Bug
(Query_Name : String;
Ex : Exception_Occurrence;
Arg_Element : Asis.Element := Nil_Element;
Arg_Element_2 : Asis.Element := Nil_Element;
Arg_CU : Asis.Compilation_Unit := Nil_Compilation_Unit;
Arg_CU_2 : Asis.Compilation_Unit := Nil_Compilation_Unit;
Arg_Line : Asis.Text.Line := Nil_Line;
Arg_Span : Asis.Text.Span := Nil_Span;
Bool_Par_ON : Boolean := False;
Context_Par : Boolean := False
-- What else???
);
pragma No_Return (Report_ASIS_Bug);
-- This procedure is supposed to be called in "when OTHERS" exception
-- handlers of an ASIS queries only. If we are in such an exception
-- handler, then for sure we have detected some ASIS implementation bug.
-- Depending on the ASIS initialization options, this procedure may
-- perform the following options:
--
-- - generates the ASIS bug box similar to the GNAT bug box generated by
-- the GNAT Comperr.Compiler_Abort procedure.
--
-- - raises ASIS_Failed with the summary of the information which should
-- go into the ASIS bug box as the ASIS Diagnosis string
--
-- - causes the exit to OS.
--
-- Either exit to OS or raising ASIS_Failed should take place in any case.
-- In case of exit to OS, the ASIS bug box should be generated.
--
-- The call to this procedure should never result in exception raise (other
-- then raising ASIS_Failed by purpose), the worst case is that the
-- diagnostic information formed by this procedure is incomplete.
--
-- Query_Name should be set to the full expanded Ada name of the query
-- where this procedure is called
--
-- Ex should be the exception name form enclosing "when Ex : others"
-- handlers.
--
-- All the other parameters are used to compose some debug information
-- about the parameters of the call which fails. Some ASIS queries have
-- two Element or Compilation Unit parameters, that's why we need
-- Arg_Element_2 and Arg_CU_2. For queries having only one Element or CU
-- parameter, Arg_Element or Arg_CU should be used to pass the argument of
-- the call to form the diagnostic info.
end A4G.Vcheck;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
81c13386680f784d80d6988889af60877067cd97
|
src/asis/asis-extensions-iterator.ads
|
src/asis/asis-extensions-iterator.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT COMPONENTS --
-- --
-- A S I S . E X T E N S I O N S . I T E R A T O R --
-- --
-- S p e c --
-- --
-- Copyright (c) 2003-2006, Free Software Foundation, Inc. --
-- --
-- ASIS-for-GNAT is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 2, or (at your option) any later --
-- version. ASIS-for-GNAT is distributed in the hope that it will be use- --
-- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- --
-- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General --
-- Public License for more details. You should have received a copy of the --
-- GNU General Public License distributed with ASIS-for-GNAT; see file --
-- COPYING. If not, write to the Free Software Foundation, 51 Franklin --
-- Street, Fifth Floor, Boston, MA 02110-1301, USA. --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the --
-- Software Engineering Laboratory of the Swiss Federal Institute of --
-- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the --
-- Scientific Research Computer Center of Moscow State University (SRCC --
-- MSU), Russia, with funding partially provided by grants from the Swiss --
-- National Science Foundation and the Swiss Academy of Engineering --
-- Sciences. ASIS-for-GNAT is now maintained by AdaCore --
-- (http://www.adacore.com). --
-- --
------------------------------------------------------------------------------
-- This package encapsulates the generic procedure Traverse_Unit which
-- is a generalization of the standard ASIS Asis.Iterator.Traverse_Element
-- procedure. Traverse_Unit traverses all the syntactical components of the
-- argument ASIS Compilation Unit.
package Asis.Extensions.Iterator is
generic
type State_Information is limited private;
with procedure Pre_Operation
(Element : Asis.Element;
Control : in out Traverse_Control;
State : in out State_Information) is <>;
with procedure Post_Operation
(Element : Asis.Element;
Control : in out Traverse_Control;
State : in out State_Information) is <>;
procedure Traverse_Unit
(Unit : Asis.Compilation_Unit;
Control : in out Traverse_Control;
State : in out State_Information);
-- Traverses all the syntactical structure of the argument Compilation
-- Unit. In ASIS, a Compilation Unit consists of context clause Elements
-- and of the Element representing the program unit, and these syntax
-- elements does not have a common root. Traverse_Unit instantiates
-- Asis.Iterator.Traverse_Element passing its own formal parameters as
-- actuals for Traverse_Element. Then it goes into all the
-- first-depth-level structural components of the argument Compilation
-- Unit by applying this instance of Traverse_Element to it.
--
-- If the value of traverse Control becomes Terminate_Immediately,
-- traversing of all the unit components is terminated (that is, if it
-- happens in some context clause Element, the Unit declaration Element
-- will not be traversed.
--
-- Appropriate Unit_Kinds:
-- A_Procedure
-- A_Function
-- A_Package
--
-- A_Generic_Procedure
-- A_Generic_Function
-- A_Generic_Package
--
-- A_Procedure_Instance
-- A_Function_Instance
-- A_Package_Instance
--
-- A_Procedure_Renaming
-- A_Function_Renaming
-- A_Package_Renaming
--
-- A_Generic_Procedure_Renaming
-- A_Generic_Function_Renaming
-- A_Generic_Package_Renaming
--
-- A_Procedure_Body
-- A_Procedure_Body
-- A_Function_Body
-- A_Package_Body
--
-- A_Procedure_Body_Subunit
-- A_Function_Body_Subunit
-- A_Package_Body_Subunit
-- A_Task_Body_Subunit
-- A_Protected_Body_Subunit
end Asis.Extensions.Iterator;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
|
1ac70d2cdac21bed230ff3f7fdbbf0086b65eee4
|
src/asis/asis-text-set_get.adb
|
src/asis/asis-text-set_get.adb
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A S I S . T E X T . S E T _ G E T --
-- --
-- B o d y --
-- --
-- Copyright (C) 1995-2008, 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, 59 Temple Place --
-- - Suite 330, Boston, MA 02111-1307, 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 Ada Core Technologies Inc --
-- (http://www.gnat.com). --
-- --
------------------------------------------------------------------------------
with Ada.Characters.Handling; use Ada.Characters.Handling;
with Asis.Set_Get; use Asis.Set_Get;
with A4G.A_Sinput; use A4G.A_Sinput;
with A4G.Contt; use A4G.Contt;
with A4G.Contt.TT; use A4G.Contt.TT;
with Sinput; use Sinput;
with Widechar; use Widechar;
package body Asis.Text.Set_Get is
---------
-- Get --
---------
function Line_Length (L : Line) return Character_Position is
begin
return L.Length;
end Line_Length;
function Line_Location (L : Line) return Source_Ptr is
begin
if not (L.Enclosing_Context = Get_Current_Cont and then
L.Enclosing_Tree = Get_Current_Tree)
then
Reset_Tree (L.Enclosing_Context, L.Enclosing_Tree);
end if;
return L.Sloc;
end Line_Location;
function Valid (L : Line) return Boolean is
begin
return Is_Opened (L.Enclosing_Context) and then
Later (Opened_At (L.Enclosing_Context), L.Obtained);
end Valid;
------------------------
-- Debug_Image (Span) --
------------------------
function Debug_Image (The_Span : Span) return String is
LT : String renames ASIS_Line_Terminator;
begin
return LT
& "Debug image for Asis.Text.Span:"
& LT
& "First Line : "
& Int'Image (Int (The_Span.First_Line))
& LT
& "First Column : "
& Int'Image (Int (The_Span.First_Column))
& LT
& "Last Line : "
& Int'Image (Int (The_Span.Last_Line))
& LT
& "Last Column : "
& Int'Image (Int (The_Span.Last_Column))
& LT
& LT;
end Debug_Image;
---------------------
-- Line_Wide_Image --
---------------------
function Line_Wide_Image (L : Line) return Wide_String is
begin
if Line_Length (L) = 0 then
return "";
end if;
declare
Result : Wide_String (1 .. Line_Length (L));
S : Source_Ptr := L.Sloc;
SFI : constant Source_File_Index := Get_Source_File_Index (S);
Src : constant Source_Buffer_Ptr := Source_Text (SFI);
Next_Ch : Char_Code;
Success : Boolean;
pragma Unreferenced (Success);
begin
for J in Result'Range loop
if Is_Start_Of_Wide_Char_For_ASIS (Src, S, L.Comment_Sloc) then
Scan_Wide (Src, S, Next_Ch, Success);
Result (J) := Wide_Character'Val (Next_Ch);
else
Result (J) := To_Wide_Character (Src (S));
S := S + 1;
end if;
end loop;
return Result;
end;
end Line_Wide_Image;
---------
-- Set --
---------
procedure Set_Line_Length (L : in out Line; N : Character_Position) is
begin
L.Length := N;
end Set_Line_Length;
procedure Set_Line_Location (L : in out Line; S : Source_Ptr) is
begin
L.Rel_Sloc := L.Rel_Sloc + (S - L.Sloc);
L.Sloc := S;
end Set_Line_Location;
---------------
-- Set_Lines --
---------------
procedure Set_Lines (LList : in out Line_List; El : Element) is
First_Line : constant Line_Number := LList'First;
Last_Line : constant Line_Number := LList'Last;
El_Sloc : constant Source_Ptr := Location (El);
-- This call to Location resets the tree for El, if needed;
-- and this makes all the routine "tree-swapping-safe"
Sloc_Move : constant Source_Ptr := Rel_Sloc (El) - El_Sloc;
-- Sloc_Move in fact is equal to - Sloc (Top (Enclosing_CU)),
-- so by adding Sloc_Move we can get relative Sloc for lines:
-- We define local variables for Element characteristics in order
-- not to compute this in the loop:
El_Encl_Unit : constant Unit_Id := Encl_Unit_Id (El);
El_Encl_Cont : constant Context_Id := Encl_Cont_Id (El);
El_Encl_Tree : constant Tree_Id := Encl_Tree (El);
El_Obtained : constant ASIS_OS_Time := Obtained (El);
SFI : constant Source_File_Index := Get_Source_File_Index (El_Sloc);
Src_First : constant Source_Ptr := Source_First (SFI);
Src : constant Source_Buffer_Ptr := Source_Text (SFI);
S : Source_Ptr;
Wide_Length : Character_Position;
-- Line length counted in wide characters
Comment_Pos : Source_Ptr;
-- Start of the comment in the next line image. Zero if there is no
-- comment as a part of the line image
begin
-- the only thing which requires special processing is
-- setting of the length of the last Line in LList if
-- this Line corresponds to the last line in the compilation
-- containing El.
-- We start from settings which do not require any
-- special processing. We take from Element all which can
-- be safely "transferred" into Lines. Note, that we know,
-- that El is valid, that is, the Context from which it had been
-- obtained was not closed after obtaining this Element. So we
-- simply copy the time when El was obtained in all the Lines
-- in Line list
for LN in First_Line .. Last_Line loop
LList (LN).Enclosing_Unit := El_Encl_Unit;
LList (LN).Enclosing_Context := El_Encl_Cont;
LList (LN).Enclosing_Tree := El_Encl_Tree;
LList (LN).Obtained := El_Obtained;
LList (LN).Sloc := Line_Start (Physical_Line_Number (LN), SFI);
LList (LN).Rel_Sloc := LList (LN).Sloc + Sloc_Move;
end loop;
-- Counting Line lengths. Firtst we count length in the internal
-- representation:
for LN in First_Line .. Last_Line - 1 loop
S := LList (LN + 1).Sloc - 1;
while S > Src_First
and then
Is_EOL_Char (Src (S))
and then
S >= LList (LN).Sloc
loop
S := S - 1;
end loop;
if S = Src_First then
-- Empty lines in the beginning of a source file
LList (LN).Length := 0;
else
LList (LN).Length :=
Character_Position (S - LList (LN).Sloc + 1);
end if;
end loop;
-- The special case of the last Line in the list:
S := LList (Last_Line).Sloc;
while S < Source_Last (SFI)
and then
not Is_EOL_Char (Src (S))
loop
S := S + 1;
end loop;
LList (Last_Line).Length :=
Character_Position (S - LList (Last_Line).Sloc);
-- Recompute line lengths, taking into account possible encodings of
-- upper half characters. The result should be the lengths of the lines
-- in the original source
for LN in First_Line .. Last_Line loop
if LList (LN).Length /= 0 then
Wide_Length := 0;
S := LList (LN).Sloc;
Comment_Pos := Comment_Beginning
(Src (S .. S + Source_Ptr (LList (LN).Length) - 1));
LList (LN).Comment_Sloc := Comment_Pos;
while S < LList (LN).Sloc + Source_Ptr (LList (LN).Length) loop
if Is_Start_Of_Wide_Char_For_ASIS (Src, S, Comment_Pos) then
Skip_Wide_For_ASIS (Src, S);
else
S := S + 1;
end if;
Wide_Length := Wide_Length + 1;
end loop;
LList (LN).Length := Wide_Length;
end if;
end loop;
end Set_Lines;
end Asis.Text.Set_Get;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
|
615dada69b3b3c9450345ff82221100f98113ded
|
orka_numerics/src/x86/generic/avx2/orka-numerics-doubles-tensors-cpu.ads
|
orka_numerics/src/x86/generic/avx2/orka-numerics-doubles-tensors-cpu.ads
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2021 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Orka.Numerics.Tensors.SIMD_CPU;
with Orka.SIMD.AVX.Doubles.Arithmetic;
with Orka.SIMD.AVX.Doubles.Compare;
with Orka.SIMD.AVX.Doubles.Logical;
with Orka.SIMD.AVX.Doubles.Math;
with Orka.SIMD.AVX.Longs.Logical;
with Orka.SIMD.AVX2.Longs.Arithmetic;
with Orka.SIMD.AVX2.Longs.Logical;
with Orka.SIMD.AVX2.Longs.Shift;
with Orka.SIMD.AVX2.Longs.Random;
package Orka.Numerics.Doubles.Tensors.CPU is new Orka.Numerics.Doubles.Tensors.SIMD_CPU
(Index_4D,
Integer_64,
SIMD.AVX.Longs.m256l,
SIMD.AVX2.Longs.Arithmetic."+",
SIMD.AVX2.Longs.Logical."and",
SIMD.AVX2.Longs.Shift.Shift_Elements_Left_Zeros,
SIMD.AVX2.Longs.Shift.Shift_Elements_Right_Zeros,
SIMD.AVX.Longs.Logical.Test_All_Ones,
SIMD.AVX.Longs.Logical.Test_All_Zero,
SIMD.AVX.Doubles.m256d,
SIMD.AVX.Doubles.Arithmetic."*",
SIMD.AVX.Doubles.Arithmetic."/",
SIMD.AVX.Doubles.Arithmetic."+",
SIMD.AVX.Doubles.Arithmetic."-",
SIMD.AVX.Doubles.Arithmetic."-",
SIMD.AVX.Doubles.Arithmetic."abs",
SIMD.AVX.Doubles.Arithmetic.Sum,
SIMD.AVX.Doubles.Arithmetic.Divide_Or_Zero,
SIMD.AVX.Doubles.Math.Sqrt,
SIMD.AVX.Doubles.Math.Min,
SIMD.AVX.Doubles.Math.Max,
SIMD.AVX.Doubles.Math.Ceil,
SIMD.AVX.Doubles.Math.Floor,
SIMD.AVX.Doubles.Math.Round_Nearest_Integer,
SIMD.AVX.Doubles.Math.Round_Truncate,
SIMD.AVX.Doubles.Logical.And_Not,
SIMD.AVX.Doubles.Logical."and",
SIMD.AVX.Doubles.Logical."or",
SIMD.AVX.Doubles.Logical."xor",
SIMD.AVX.Doubles.Compare."=",
SIMD.AVX.Doubles.Compare."/=",
SIMD.AVX.Doubles.Compare.">",
SIMD.AVX.Doubles.Compare."<",
SIMD.AVX.Doubles.Compare.">=",
SIMD.AVX.Doubles.Compare."<=",
SIMD.AVX2.Longs.Random.State,
SIMD.AVX2.Longs.Random.Next,
SIMD.AVX2.Longs.Random.Reset);
pragma Preelaborate (Orka.Numerics.Doubles.Tensors.CPU);
|
Add instantiation of SIMD_CPU for Float_64 using AVX2
|
numerics: Add instantiation of SIMD_CPU for Float_64 using AVX2
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
|
e73b9f77a1b3a1291bb5d88b67a73301a03f4fcb
|
mat/src/gtk/mat-callbacks.adb
|
mat/src/gtk/mat-callbacks.adb
|
-----------------------------------------------------------------------
-- mat-callbacks - Callbacks for Gtk
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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 Gtk.Main;
package body MAT.Callbacks is
-- ------------------------------
-- Callback executed when the "quit" action is executed from the menu.
-- ------------------------------
procedure On_Menu_Quit (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is
begin
Gtk.Main.Main_Quit;
end On_Menu_Quit;
end MAT.Callbacks;
|
Implement the On_Menu_Quit procedure
|
Implement the On_Menu_Quit procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
|
05aeadad4f0beb6f969af9578099badf66165c8f
|
src/asis/a4g-a_types.ads
|
src/asis/a4g-a_types.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . A _ T Y P E S --
-- --
-- S p e c --
-- --
-- Copyright (C) 1995-2012, 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.Characters.Latin_1; use Ada.Characters.Latin_1;
with Ada.Characters.Handling; use Ada.Characters.Handling;
with GNAT.OS_Lib; use GNAT.OS_Lib;
package A4G.A_Types is
pragma Elaborate_Body (A4G.A_Types);
-- This package is the ASIS implementation's analog of the GNAT Types
-- package (except the part related to the ASIS_OS_Time type).
-- It contains host independent type and constant definitions
-- which is supposed to be used in more than one unit in the ASIS
-- implementation.
------------------
-- ASIS_OS_Time --
------------------
-- To check, that a given abstraction is valid in the sense defined by the
-- ASIS standard (that is, that the enclosing Context of the given
-- abstraction has not been closed after creating this abstraction), ASIS
-- needs some kind of logical time (or logical time stamp). This logical
-- time is increased each time when any ASIS Context is opened. It is not
-- reset when ASIS is initialized, because it may lead to collisions in
-- validity checks
-- An ASIS abstraction is valid if its logical time stamp is equal or
-- greater than the time stamp of its enclosing Context.
type ASIS_OS_Time is private;
Nil_ASIS_OS_Time : constant ASIS_OS_Time;
Last_ASIS_OS_Time : constant ASIS_OS_Time;
procedure Increase_ASIS_OS_Time;
-- Increases the ASIS logical "clock"
function A_OS_Time return ASIS_OS_Time;
-- Gets the current value of the ASIS logical "clock"
function Later (L, R : ASIS_OS_Time) return Boolean;
-- Compares time stamps.
-----------------------------------------
-- Types for Context and Context Table --
-----------------------------------------
Inconsistent_Incremental_Context : exception;
-- raised when any inconsistency found for Incremental Tree processing
-- mode
Context_Low_Bound : constant := 0;
Context_High_Bound : constant := 1_000_000;
type Context_Id is range Context_Low_Bound .. Context_High_Bound;
-- Type used to identify entries in ASIS Context table
Non_Associated : constant Context_Id := Context_Low_Bound;
Nil_Context_Id : constant Context_Id := Context_Low_Bound;
First_Context_Id : constant Context_Id := Context_Low_Bound + 1;
---------------------------------------------
-- Types for Container and Container Table --
---------------------------------------------
Container_Low_Bound : constant := 0;
Container_High_Bound : constant := 100;
type Container_Id is range Container_Low_Bound .. Container_High_Bound;
-- Type used to identify entries in ASIS Container table
Nil_Container_Id : constant Container_Id := Container_Low_Bound;
First_Container_Id : constant Container_Id := Container_Low_Bound + 1;
-----------------------------------------------
-- Types for Compilation_Unit and Unit Table --
-----------------------------------------------
Unit_Low_Bound : constant := 0;
Unit_High_Bound : constant := 100_000;
type Unit_Id is range Unit_Low_Bound .. Unit_High_Bound;
-- Type used to identify entries in the ASIS Unit table
Nil_Unit : constant Unit_Id := Unit_Low_Bound;
No_Unit_Id : Unit_Id renames Nil_Unit;
First_Unit_Id : constant Unit_Id := Unit_Low_Bound + 1;
Standard_Id : constant Unit_Id := First_Unit_Id;
-- The entry in the Unit table corresponding to the package Standard
-- Standard goes first in any Unit table
Config_Comp_Id : constant Unit_Id := Standard_Id + 1;
-- The entry in the Unit table corresponding to the artificial
-- A_Configuration_Compilation unit. We may have at most one such unit.
-- If there is no configuration pragmas in the Context, there is no harm
-- to allocate such a unit, because the only way for an ASIS client to get
-- it is to get the enclosing unit for a configuration pragma.
type Unit_Id_List is array (Natural range <>) of Unit_Id;
Nil_Unit_Id_List : constant Unit_Id_List (1 .. 0) := (others => Nil_Unit);
--------------------------
-- Types for Tree Table --
--------------------------
Tree_Low_Bound : constant := 0;
Tree_High_Bound : constant := 100_000;
type Tree_Id is range Tree_Low_Bound .. Tree_High_Bound;
-- Type used to identify entries in ASIS Tree table
Nil_Tree : constant Tree_Id := Tree_Low_Bound;
No_Tree_Name : Tree_Id renames Nil_Tree; -- ???
First_Tree_Id : constant Tree_Id := Tree_Low_Bound + 1;
-----------------------------------------------
-- Types for Search Directories Paths Tables --
-----------------------------------------------
No_Dir : constant := 0;
First_Dir_Id : constant := 1;
Last_Dir_Id : constant := 1_000;
type Dir_Id is range No_Dir .. Last_Dir_Id;
type Search_Dir_Kinds is (
Source, -- for source search path
Object, -- for object search path
Tree); -- for tree search path
-- this type may be further expanded
--------------------------------------------
-- Types for Internal Element Structure --
--------------------------------------------
type Special_Cases is (
-- this enumeration type is needed to distinguish some special
-- cases in Element constructing and handling
Not_A_Special_Case,
A_Dummy_Block_Statement,
-- the result of an obsolescent function
-- Declarations.Body_Block_Statement
Predefined_Operation,
-- indicates the predefined operation for a user-defined type
-- (or component thereof???). Note, that such an operation is
-- defined not in the Standard package.
Explicit_From_Standard,
-- indicates the explicit Element obtained from the package
-- Standard. "Explicit" means here any construct which is
-- contained in the "source" text of Standard included in RM95
-- plus explicit constants substituting "implementation-defined"
-- italic strings in this "source"
Numeric_Error_Renaming,
-- Indicates the artificial ASIS Element created to represent the
-- obsolete renaming of Numeric_Error in the package Standard
-- (see B712-005)
Implicit_From_Standard,
-- indicates the implicit Element obtained from the package
-- Standard, that is, implicitly declared predefined operations
-- and their components, and root and universal numeric type
-- definitions and declarations
Stand_Char_Literal,
-- indicates the defining character literal declared in the
-- definition of the predefined type Standard.Character
-- or Standard.Wide_Character. An ASIS Element representing such
-- a literal has no corresponding node in the tree, and it is
-- based on the N_Defining_Identifier node for the corresponding
-- type
Expanded_Package_Instantiation,
-- indicates A_Package_Declaration element which represents the
-- package declaration which is the result of an instantiation
-- of a generic package
Expanded_Subprogram_Instantiation,
-- indicates A_Procedure_Declaration or A_Function_Declaration
-- element which represents the package declaration which is the
-- result of an instantiation of a generic package
Configuration_File_Pragma,
-- Indicates a configuration pragma belonging not to the source of some
-- Ada compilation unit, but to the configuration file (an components
-- thereof)
Rewritten_Named_Number,
-- Indicates An_Identifier Element representing a named number in the
-- situation when the corresponding tree structure is rewritten into
-- N_Integer/Real_Literal node and no original tree structure is
-- available (see BB10-002)
Is_From_Gen_Association,
-- See D722-012.
-- The problem here is that in case of a formal object, the front-end
-- creates the renaming declaration as a means to pass an actual
-- parameter, and the parameter itself (the corresponding tree node)
-- is used as a part of this renaming declaration. So we have a problem
-- with Enclosing_Element. The Parent pointer from this actual points
-- to the renaming declaration structure. In case if we are not in the
-- expanded code, we may compare levels of instantiation and it helps,
-- but in general case it is too complicated. So the solution is to
-- mark the corresponding node if it comes from the generic association
-- (and we can gen into this node only by means of a structural query!)
-- and to use this mark in the Enclosing_Element processing.
Is_From_Imp_Neq_Declaration,
-- Indicates if the given element is an implicit declaration of the
-- "/=" operation corresponding to the explicit redefinition of "=" or
-- a subcomponent thereof
-- Implicit_Inherited_Subprogram
-- indicates the declaration of an implicit inherited user-defined
-- subprogram or a component thereof.
-- may be continued...
Dummy_Base_Attribute_Designator,
Dummy_Class_Attribute_Designator,
Dummy_Base_Attribute_Prefix,
Dummy_Class_Attribute_Prefix,
-- These four values are used to mark components of the artificial
-- 'Base and 'Class attribute reference that ASIS has to simulate when
-- processing references to a formal type in the instantiation in case
-- when a formal type is an unconstrained type, and the actual type is a
-- 'Class attribute, or when an actual is a 'Base attribute and the
-- front-end creates too much of artificial data structures in the tree.
From_Limited_View
-- The corresponding Element is (a part of) a package or type limited
-- view, see RM 05 10.1.1 (12.1/2 .. 12.5.2)
-- may be continued...
);
type Normalization_Cases is (
-- This enumeration type represents the different possible states of
-- An_Association Elements in respect to normalization of associations
Is_Not_Normalized,
Is_Normalized,
-- normalized association created for an actual parameter which itself
-- is presented at the place of the call/instantiation
Is_Normalized_Defaulted,
-- normalized association created for an actual parameter which itself
-- is NOT presented at the place of the call/instantiation, so the
-- default value should be used
Is_Normalized_Defaulted_For_Box);
-- normalized association created for an actual parameter which itself
-- is NOT presented at the place of the instantiation and the definition
-- of the formal parameter includes box as the default value, so the
-- actual parameter should be found at the place of the instantiation
subtype Expanded_Spec is Special_Cases
range Expanded_Package_Instantiation .. Expanded_Subprogram_Instantiation;
subtype Normalized_Association is Normalization_Cases
range Is_Normalized .. Is_Normalized_Defaulted_For_Box;
subtype Defaulted_Association is Normalization_Cases
range Is_Normalized_Defaulted .. Is_Normalized_Defaulted_For_Box;
subtype Predefined is Special_Cases
range Predefined_Operation .. Stand_Char_Literal;
-- COMMENTS
--
-- *1* Handling the Parenthesized Expressions and
-- One_Pair_Of_Parentheses_Away and Two_Pairs_Of_Parentheses_Away
-- Special Cases.
--
-- An Asis Element of A_Parenthesized_Expression could be built
-- on the base of any tree node which could be used for building the
-- elements of all other An_Expresion subordinate kinds.
-- A_Parenthesized_Expression kind is determined by comparing (during
-- the automatic Internal_Element_Kinds determination only!!!) the
-- Paren_Count field of the node with zero - see Sinfo.ads, the
-- documentation item for "4.4 (Primary)" RM subsection, and
-- Atree.ads the documentation item related to the Paren_Count field.
--
-- When a subexpression is to be selected from the element of
-- A_Parenthesized_Expression kind by the
-- Asis_Definition.Expression_Parenthesized function, the result will
-- be built on the base of just the same node as the argument having,
-- just the same value of the Paren_Count field. If the argument has
-- more than one pair of parentheses, the result will also be of
-- A_Parenthesized_Expression kind, and the Special_Cases values
-- One_Pair_Of_Parentheses_Away and Two_Pairs_Of_Parentheses_Away
-- are intended to be used to count the pairs of parentheses remained
-- in the result element. All the corresponding element kind
-- determination and element construction should be performed in
-- "by-hand" mode, except the case when the argument parenthesized
-- expression has only one pair of parentheses.
--
-- GNAT cannot distinguish more than three levels of the enclosing
-- pairs of parentheses for a non-parenthesized enclosed expression.
-- (Paren_Count = 3 stands for any number of the enclosing parentheses
-- equal or greater than 3.) So ASIS-for-GNAT implementation cannot
-- do more than GNAT itself (of course, we could do some search in the
-- source buffer, but we prefer to agree with GNAT team that even
-- Paren_Count = 3 already is a pathological case :).
--
-- See also Asis_Definition.Expression_Parenthesized (body) and
-- A4G.Mapping.Node_To_Element (body)
--
-- *2* Root/Universal types definitions - we do not need any special
-- value for representing elements of Root_Type_Kinds, because for
-- each value there may be only one Element of the corresponding kind
-- in a given opened Context.
--
-------------------------
-- Nil String constants--
-------------------------
Nil_Asis_String : constant String := "";
Nil_Asis_Wide_String : constant Wide_String := "";
-------------------------------------------------
-- Constants for the Diagnosis string buffer --
-------------------------------------------------
ASIS_Line_Terminator : constant String := (1 => LF);
-- what about DOS-like end-of-line?
Diagnosis_String_Length : constant Positive :=
76 + ASIS_Line_Terminator'Length;
-- We are trying to set ASIS_Line_Terminator in the Diagnosis string to
-- keep text strings at most 76 characters long
Max_Diagnosis_Length : constant Positive := 32 * Diagnosis_String_Length;
-- The length of the buffer in which the Diagnosis string is formed,
-- now it is at most 32 lines 76 character each. Should be enough for
-- any practically meaningful diagnosis
Asis_Wide_Line_Terminator : constant Wide_String :=
(1 => To_Wide_Character (LF));
--
-- the physical line terminator, is used in the Diagnosis string
-- to separate the parts of the diagnosis message
-- See also documentation of the Skip_Line_Terminators procedure
-- in the (GNAT.)sinput.adb
ASIS_Line_Terminator_Len : constant Positive
:= ASIS_Line_Terminator'Length;
Incorrect_Setting : constant String := "Attempt to set Not_An_Error "
& "status with non-nil diagnosis string";
Incorrect_Setting_Len : constant Positive := Incorrect_Setting'Length;
-------------------
-- Miscellaneous --
-------------------
ASIS_Path_Separator : Character;
-- Is initialized in the package body. Takes into account that in VMS
-- ',' should be used instead of GNAT.OS_Lib.Path_Separator.
ASIS_Current_Directory : String_Access;
-- Is initialized in the package body. "[]" in VMS, "." otherwise
function Asis_Normalize_Pathname
(Name : String;
Directory : String := "";
Resolve_Links : Boolean := True;
Case_Sensitive : Boolean := True) return String;
-- ASIS version of GNAT.OS_Lib.Normalize_Pathname. It applies
-- To_Host_Dir_Spec to the result of GNAT.OS_Lib.Normalize_Pathname.
-- Should be applied to directory names only! For file names
-- GNAT.OS_Lib.Normalize_Pathname should be used.
-- ??? Is this the right place for this subprogram???
Internal_Implementation_Error : exception;
-- Means exactly this. Is supposed to be raised in control statement
-- paths which should never be reached. We need this exception mostly
-- because some parts of old ASIS code (developed at the research stage of
-- the ASIS project) sometimes are not structured properly.
function Parameter_String_To_List
(Par_String : String)
return Argument_List_Access;
-- Take a string that is a converted to the String type Parameters string
-- of the ASIS query Initialize, Associate or Finalize (??? Should we
-- process the original Wide_String Parameters string without converting
-- it to String?) and parse it into an Argument_List.
--
-- This function is similar to GNAT.OS_Int.Argument_String_To_List, but
-- it does not treat '\' as a backquoting character.
private
type ASIS_OS_Time is new Long_Integer range 0 .. Long_Integer'Last;
ASIS_Clock : ASIS_OS_Time := 1;
-- This is the ASIS logical "clock" used to ret ASIS logical time.
Nil_ASIS_OS_Time : constant ASIS_OS_Time := 0;
Last_ASIS_OS_Time : constant ASIS_OS_Time := ASIS_OS_Time'Last;
end A4G.A_Types;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
bcb79194b1c7571c516248204cc9e09a8b5115f2
|
src/asis/asis-text-set_get.ads
|
src/asis/asis-text-set_get.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A S I S . T E X T . S E T _ G E T --
-- --
-- S p e c --
-- --
-- Copyright (c) 1995-2006, 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). --
-- --
------------------------------------------------------------------------------
package Asis.Text.Set_Get is
---------
-- Get --
---------
function Line_Length (L : Line) return Character_Position;
-- Returns line length. Note, that this is the length in the original
-- source, counted in wide characters, but not the length in the internal
-- representation counted in one-byte characters
function Line_Location (L : Line) return Source_Ptr;
-- when Line Location is obtained, the tree is resetted if needed
function Valid (L : Line) return Boolean;
-- chechs, if the argument is valid, that is, if the Context
-- from which this line was obtained is still opened
function Line_Wide_Image (L : Line) return Wide_String;
-- Returns the line image as the line is represented in the original
-- source text
function Debug_Image (The_Span : Span) return String;
-- Produces the debug output for its argument
---------
-- Set --
---------
procedure Set_Line_Length (L : in out Line; N : Character_Position);
procedure Set_Line_Location (L : in out Line; S : Source_Ptr);
-- this procedure is intended to correct the Sloc field in
-- the first line from a line list covering a given Span.
-- This means, that all the fields of the Line to be corrected
-- have been already set as pointing to the beginning of
-- a given line. Together with setting the Sloc field, this
-- procedure adjust the Rel_Sloc field.
procedure Set_Lines (LList : in out Line_List; El : Element);
-- This procedure creates LList as a list of lines
-- accessable through El. It gets LList as a list
-- of Nil_Lines and makes the proper settings for
-- the components of each line, making them non-nil
-- It takes all the characteristics of these lines from El,
-- that is, from the tree on which El is based. This is
-- "tree-swapping-safe" procedure.
-- The only call to this procedure is in the third
-- Asis.Text.Lines function, which explicitly specifies
-- the bounds of the Line_List to be returned (that is, LList).
-- The caller makes all the checks needed to make sure, that
-- the compilation enclosing El really contains lines with numbers
-- LList'First and LList'Last
end Asis.Text.Set_Get;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
3c4d2524f21d19c44fedbab44c450ef402b62d9e
|
src/asf-security.ads
|
src/asf-security.ads
|
-----------------------------------------------------------------------
-- asf-security -- ASF Security
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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.
-----------------------------------------------------------------------
package ASF.Security is
end ASF.Security;
|
Define an ASF Security package
|
Define an ASF Security package
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
|
30c937b73f55f3f31d3e0ba3410ee42d9c9ee4d7
|
src/babel-stores.ads
|
src/babel-stores.ads
|
-----------------------------------------------------------------------
-- babel-stores -- Storage management
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- 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 Babel.Files;
with Babel.Files.Buffers;
with Babel.Filters;
package Babel.Stores is
type Store_Type is limited interface;
type Store_Type_Access is access all Store_Type'Class;
procedure Read (Store : in out Store_Type;
Path : in String;
Into : in out Babel.Files.Buffers.Buffer) is abstract;
procedure Write (Store : in out Store_Type;
Path : in String;
Into : in Babel.Files.Buffers.Buffer) is abstract;
procedure Scan (Store : in out Store_Type;
Path : in String;
Into : in out Babel.Files.File_Container'Class;
Filter : in Babel.Filters.Filter_Type'Class) is abstract;
end Babel.Stores;
|
Backup store to access files (local, remote, ...)
|
Backup store to access files (local, remote, ...)
|
Ada
|
apache-2.0
|
stcarrez/babel
|
|
a71abb25b07fe19e6b9b8583bec474d23035a0f4
|
src/gen-artifacts-docs-googlecode.adb
|
src/gen-artifacts-docs-googlecode.adb
|
-----------------------------------------------------------------------
-- gen-artifacts-docs-googlecode -- Artifact for Googlecode documentation format
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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.
-----------------------------------------------------------------------
package body Gen.Artifacts.Docs.Googlecode is
-- ------------------------------
-- Get the document name from the file document (ex: <name>.wiki or <name>.md).
-- ------------------------------
overriding
function Get_Document_Name (Formatter : in Document_Formatter;
Document : in File_Document) return String is
begin
return Ada.Strings.Unbounded.To_String (Document.Name) & ".wiki";
end Get_Document_Name;
end Gen.Artifacts.Docs.Googlecode;
|
Implement the Get_Document_Name function for the Google Code wiki syntax
|
Implement the Get_Document_Name function for the Google Code wiki syntax
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
cd53626e183d9a112bfbd76654f358a8eaa27b8d
|
src/security-policies-roles.adb
|
src/security-policies-roles.adb
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with Util.Log.Loggers;
with Util.Serialize.Mappers.Record_Mapper;
with Security.Contexts;
with Security.Controllers;
with Security.Controllers.Roles;
-- The <b>Security.Permissions</b> package defines the different permissions that can be
-- checked by the access control manager.
package body Security.Policies.Roles is
use Util.Log;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Security.Permissions");
-- ------------------------------
-- Get the role name.
-- ------------------------------
function Get_Role_Name (Manager : in Role_Policy;
Role : in Role_Type) return String is
use type Ada.Strings.Unbounded.String_Access;
begin
if Manager.Names (Role) = null then
return "";
else
return Manager.Names (Role).all;
end if;
end Get_Role_Name;
-- ------------------------------
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
-- ------------------------------
function Find_Role (Manager : in Role_Policy;
Name : in String) return Role_Type is
use type Ada.Strings.Unbounded.String_Access;
begin
Log.Debug ("Searching role {0}", Name);
for I in Role_Type'First .. Manager.Next_Role loop
exit when Manager.Names (I) = null;
if Name = Manager.Names (I).all then
return I;
end if;
end loop;
Log.Debug ("Role {0} not found", Name);
raise Invalid_Name;
end Find_Role;
-- ------------------------------
-- Create a role
-- ------------------------------
procedure Create_Role (Manager : in out Role_Policy;
Name : in String;
Role : out Role_Type) is
begin
Role := Manager.Next_Role;
Log.Info ("Role {0} is {1}", Name, Role_Type'Image (Role));
if Manager.Next_Role = Role_Type'Last then
Log.Error ("Too many roles allocated. Number of roles is {0}",
Role_Type'Image (Role_Type'Last));
else
Manager.Next_Role := Manager.Next_Role + 1;
end if;
Manager.Names (Role) := new String '(Name);
end Create_Role;
-- ------------------------------
-- Get or build a permission type for the given name.
-- ------------------------------
procedure Add_Role_Type (Manager : in out Role_Policy;
Name : in String;
Result : out Role_Type) is
begin
Result := Manager.Find_Role (Name);
exception
when Invalid_Name =>
Manager.Create_Role (Name, Result);
end Add_Role_Type;
end Security.Policies.Roles;
|
Move the role based operation from Security.Permissions to the role based polcies
|
Move the role based operation from Security.Permissions to the role based polcies
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
|
c04c809196c2770c439c09ecee3deccbedc10f6f
|
src/ado-utils-streams.adb
|
src/ado-utils-streams.adb
|
-----------------------------------------------------------------------
-- ado-utils-streams -- IO stream utilities
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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.
-----------------------------------------------------------------------
package body ADO.Utils.Streams is
use type Ada.Streams.Stream_Element_Offset;
subtype Offset is Ada.Streams.Stream_Element_Offset;
-- ------------------------------
-- Initialize the blob stream to read the content of the blob.
-- ------------------------------
procedure Initialize (Stream : in out Blob_Stream;
Blob : in ADO.Blob_Ref) is
begin
Stream.Data := Blob;
Stream.Pos := 1;
end Initialize;
-- ------------------------------
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
-- ------------------------------
overriding
procedure Read (Stream : in out Blob_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset) is
Blob : constant Blob_Access := Stream.Data.Value;
Avail : Offset;
begin
if Blob = null then
Last := Into'First - 1;
else
Avail := Blob.Data'Last - Stream.Pos + 1;
if Avail > Into'Length then
Avail := Into'Length;
end if;
Last := Into'First + Avail - 1;
if Avail > 0 then
Into (Into'First .. Last) := Blob.Data (Stream.Pos .. Stream.Pos + Avail - 1);
Stream.Pos := Stream.Pos + Avail;
end if;
end if;
end Read;
function Get_Blob (Stream : in Blob_Output_Stream) return Blob_Ref is
Size : constant Offset := Offset (Stream.Get_Size);
Buffer : constant Util.Streams.Buffered.Buffer_Access := Stream.Get_Buffer;
begin
return Create_Blob (Data => Buffer (Buffer'First .. Buffer'First + Size - 1));
end Get_Blob;
end ADO.Utils.Streams;
|
Implement operations for blob streams
|
Implement operations for blob streams
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
|
c2345ce04ff1c297f96561699698f024d3a144bc
|
src/security-auth.adb
|
src/security-auth.adb
|
-----------------------------------------------------------------------
-- security-openid -- OpenID 2.0 Support
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Security.Auth.OpenID;
with Security.Auth.OAuth.Facebook;
package body Security.Auth is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth");
-- ------------------------------
-- Get the provider.
-- ------------------------------
function Get_Provider (Assoc : in Association) return String is
begin
return To_String (Assoc.Provider);
end Get_Provider;
-- ------------------------------
-- Get the email address
-- ------------------------------
function Get_Email (Auth : in Authentication) return String is
begin
return To_String (Auth.Email);
end Get_Email;
-- ------------------------------
-- Get the user first name.
-- ------------------------------
function Get_First_Name (Auth : in Authentication) return String is
begin
return To_String (Auth.First_Name);
end Get_First_Name;
-- ------------------------------
-- Get the user last name.
-- ------------------------------
function Get_Last_Name (Auth : in Authentication) return String is
begin
return To_String (Auth.Last_Name);
end Get_Last_Name;
-- ------------------------------
-- Get the user full name.
-- ------------------------------
function Get_Full_Name (Auth : in Authentication) return String is
begin
return To_String (Auth.Full_Name);
end Get_Full_Name;
-- ------------------------------
-- Get the user identity.
-- ------------------------------
function Get_Identity (Auth : in Authentication) return String is
begin
return To_String (Auth.Identity);
end Get_Identity;
-- ------------------------------
-- Get the user claimed identity.
-- ------------------------------
function Get_Claimed_Id (Auth : in Authentication) return String is
begin
return To_String (Auth.Claimed_Id);
end Get_Claimed_Id;
-- ------------------------------
-- Get the user language.
-- ------------------------------
function Get_Language (Auth : in Authentication) return String is
begin
return To_String (Auth.Language);
end Get_Language;
-- ------------------------------
-- Get the user country.
-- ------------------------------
function Get_Country (Auth : in Authentication) return String is
begin
return To_String (Auth.Country);
end Get_Country;
-- ------------------------------
-- Get the result of the authentication.
-- ------------------------------
function Get_Status (Auth : in Authentication) return Auth_Result is
begin
return Auth.Status;
end Get_Status;
-- ------------------------------
-- Default principal
-- ------------------------------
-- ------------------------------
-- Get the principal name.
-- ------------------------------
function Get_Name (From : in Principal) return String is
begin
return Get_First_Name (From.Auth) & " " & Get_Last_Name (From.Auth);
end Get_Name;
-- ------------------------------
-- Get the user email address.
-- ------------------------------
function Get_Email (From : in Principal) return String is
begin
return Get_Email (From.Auth);
end Get_Email;
-- ------------------------------
-- Get the authentication data.
-- ------------------------------
function Get_Authentication (From : in Principal) return Authentication is
begin
return From.Auth;
end Get_Authentication;
-- ------------------------------
-- Create a principal with the given authentication results.
-- ------------------------------
function Create_Principal (Auth : in Authentication) return Principal_Access is
P : constant Principal_Access := new Principal;
begin
P.Auth := Auth;
return P;
end Create_Principal;
-- ------------------------------
-- Initialize the OpenID realm.
-- ------------------------------
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Provider : in String := PROVIDER_OPENID) is
Impl : Manager_Access;
begin
if Provider = PROVIDER_OPENID then
Impl := new Security.Auth.OpenID.Manager;
elsif Provider = PROVIDER_FACEBOOK then
Impl := new Security.Auth.OAuth.Facebook.Manager;
else
Log.Error ("Authentication provider {0} not recognized", Provider);
raise Service_Error with "Authentication provider not supported";
end if;
Impl.Initialize (Params, Provider);
Realm.Delegate := Impl;
Realm.Provider := To_Unbounded_String (Provider);
end Initialize;
-- ------------------------------
-- Discover the OpenID provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned.
-- (See OpenID Section 7.3 Discovery)
-- ------------------------------
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point) is
begin
if Realm.Delegate /= null then
Realm.Delegate.Discover (Name, Result);
else
-- Result.URL := Realm.Realm;
Result.Alias := To_Unbounded_String ("");
end if;
end Discover;
-- ------------------------------
-- Associate the application (relying party) with the OpenID provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
-- ------------------------------
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association) is
begin
Result.Provider := Realm.Provider;
if Realm.Delegate /= null then
Realm.Delegate.Associate (OP, Result);
end if;
end Associate;
-- ------------------------------
-- Get the authentication URL to which the user must be redirected for authentication
-- by the authentication server.
-- ------------------------------
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String is
begin
if Realm.Delegate /= null then
return Realm.Delegate.Get_Authentication_URL (OP, Assoc);
else
return To_String (OP.URL);
end if;
end Get_Authentication_URL;
procedure Set_Result (Result : in out Authentication;
Status : in Auth_Result;
Message : in String) is
begin
if Status /= AUTHENTICATED then
Log.Error ("OpenID verification failed: {0}", Message);
else
Log.Info ("OpenID verification: {0}", Message);
end if;
Result.Status := Status;
end Set_Result;
-- ------------------------------
-- Verify the authentication result
-- ------------------------------
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication) is
begin
if Realm.Delegate /= null then
Realm.Delegate.Verify (Assoc, Request, Result);
else
Set_Result (Result, SETUP_NEEDED, "Setup is needed");
end if;
end Verify;
function To_String (OP : End_Point) return String is
begin
return "openid://" & To_String (OP.URL);
end To_String;
function To_String (Assoc : Association) return String is
begin
return "session_type=" & To_String (Assoc.Session_Type)
& "&assoc_type=" & To_String (Assoc.Assoc_Type)
& "&assoc_handle=" & To_String (Assoc.Assoc_Handle)
& "&mac_key=" & To_String (Assoc.Mac_Key);
end To_String;
end Security.Auth;
|
Implement the new authentication framework based on the OpenID implementation
|
Implement the new authentication framework based on the OpenID implementation
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
|
007d900617973d4a97292bf894e9914720cab667
|
src/util-serialize-io.adb
|
src/util-serialize-io.adb
|
-----------------------------------------------------------------------
-- util-serialize-io -- IO Drivers for serialization
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Streams.Files;
with Ada.Streams;
with Ada.Streams.Stream_IO;
with Ada.Exceptions;
package body Util.Serialize.IO is
-- use Util.Log;
use type Util.Log.Loggers.Logger_Access;
-- The logger
Log : aliased constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Serialize.IO",
Util.Log.WARN_LEVEL);
-- ------------------------------
-- Read the file and parse it using the JSON parser.
-- ------------------------------
procedure Parse (Handler : in out Parser;
File : in String) is
Stream : aliased Util.Streams.Files.File_Stream;
Buffer : Util.Streams.Buffered.Buffered_Stream;
begin
if Handler.Error_Logger = null then
Handler.Error_Logger := Log'Access;
end if;
Buffer.Initialize (Output => null,
Input => Stream'Unchecked_Access,
Size => 1024);
Stream.Open (Mode => Ada.Streams.Stream_IO.In_File, Name => File);
Context_Stack.Clear (Handler.Stack);
Parser'Class (Handler).Parse (Buffer);
exception
when Util.Serialize.Mappers.Field_Fatal_Error =>
null;
when E : others =>
Parser'Class (Handler).Error ("Exception " & Ada.Exceptions.Exception_Name (E));
end Parse;
-- ------------------------------
-- Parse the content string.
-- ------------------------------
procedure Parse_String (Handler : in out Parser;
Content : in String) is
Stream : aliased Util.Streams.Buffered.Buffered_Stream;
begin
if Handler.Error_Logger = null then
Handler.Error_Logger := Log'Access;
end if;
Stream.Initialize (Content => Content);
Context_Stack.Clear (Handler.Stack);
Parser'Class (Handler).Parse (Stream);
exception
when Util.Serialize.Mappers.Field_Fatal_Error =>
null;
when E : others =>
Handler.Error_Logger.Error ("Exception " & Ada.Exceptions.Exception_Name (E), E);
end Parse_String;
-- ------------------------------
-- Returns true if the <b>Parse</b> operation detected at least one error.
-- ------------------------------
function Has_Error (Handler : in Parser) return Boolean is
begin
return Handler.Error_Flag;
end Has_Error;
-- ------------------------------
-- Set the error logger to report messages while parsing and reading the input file.
-- ------------------------------
procedure Set_Logger (Handler : in out Parser;
Logger : in Util.Log.Loggers.Logger_Access) is
begin
Handler.Error_Logger := Logger;
end Set_Logger;
-- ------------------------------
-- Push the current context when entering in an element.
-- ------------------------------
procedure Push (Handler : in out Parser) is
use type Util.Serialize.Mappers.Mapper_Access;
begin
Context_Stack.Push (Handler.Stack);
end Push;
-- ------------------------------
-- Pop the context and restore the previous context when leaving an element
-- ------------------------------
procedure Pop (Handler : in out Parser) is
begin
Context_Stack.Pop (Handler.Stack);
end Pop;
function Find_Mapper (Handler : in Parser;
Name : in String) return Util.Serialize.Mappers.Mapper_Access is
pragma Unreferenced (Handler, Name);
begin
return null;
end Find_Mapper;
-- ------------------------------
-- Start a new object associated with the given name. This is called when
-- the '{' is reached. The reader must be updated so that the next
-- <b>Set_Member</b> procedure will associate the name/value pair on the
-- new object.
-- ------------------------------
procedure Start_Object (Handler : in out Parser;
Name : in String) is
use type Util.Serialize.Mappers.Mapper_Access;
Current : constant Element_Context_Access := Context_Stack.Current (Handler.Stack);
Next : Element_Context_Access;
Pos : Positive;
begin
Context_Stack.Push (Handler.Stack);
Next := Context_Stack.Current (Handler.Stack);
if Current /= null then
Pos := 1;
-- Notify we are entering in the given node for each active mapping.
for I in Current.Active_Nodes'Range loop
declare
Node : constant Mappers.Mapper_Access := Current.Active_Nodes (I);
Child : Mappers.Mapper_Access;
begin
exit when Node = null;
Child := Node.Find_Mapper (Name => Name);
if Child /= null then
Child.Start_Object (Handler, Name);
Next.Active_Nodes (Pos) := Child;
Pos := Pos + 1;
end if;
end;
end loop;
while Pos <= Next.Active_Nodes'Last loop
Next.Active_Nodes (Pos) := null;
Pos := Pos + 1;
end loop;
else
Next.Active_Nodes (1) := Handler.Mapping_Tree.Find_Mapper (Name);
end if;
end Start_Object;
-- ------------------------------
-- Finish an object associated with the given name. The reader must be
-- updated to be associated with the previous object.
-- ------------------------------
procedure Finish_Object (Handler : in out Parser;
Name : in String) is
use type Util.Serialize.Mappers.Mapper_Access;
begin
declare
Current : constant Element_Context_Access := Context_Stack.Current (Handler.Stack);
begin
if Current /= null then
-- Notify we are leaving the given node for each active mapping.
for I in Current.Active_Nodes'Range loop
declare
Node : constant Mappers.Mapper_Access := Current.Active_Nodes (I);
begin
exit when Node = null;
Node.Finish_Object (Handler, Name);
end;
end loop;
end if;
end;
Handler.Pop;
end Finish_Object;
procedure Start_Array (Handler : in out Parser;
Name : in String) is
pragma Unreferenced (Name);
begin
Handler.Push;
end Start_Array;
procedure Finish_Array (Handler : in out Parser;
Name : in String) is
pragma Unreferenced (Name);
begin
Handler.Pop;
end Finish_Array;
-- -----------------------
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
-- -----------------------
procedure Set_Member (Handler : in out Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False) is
use Util.Serialize.Mappers;
Current : constant Element_Context_Access := Context_Stack.Current (Handler.Stack);
begin
if Current /= null then
-- Look each active mapping node.
for I in Current.Active_Nodes'Range loop
declare
Node : constant Mapper_Access := Current.Active_Nodes (I);
begin
exit when Node = null;
Node.Set_Member (Name => Name,
Value => Value,
Attribute => Attribute,
Context => Handler);
exception
when E : Util.Serialize.Mappers.Field_Error =>
Handler.Error (Message => Ada.Exceptions.Exception_Message (E));
when E : Util.Serialize.Mappers.Field_Fatal_Error =>
Handler.Error (Message => Ada.Exceptions.Exception_Message (E));
raise;
-- For other exception, report an error with the field name and value.
when E : others =>
Handler.Error (Message => "Cannot set field '" & Name & "' to '"
& Util.Beans.Objects.To_String (Value) & "': "
& Ada.Exceptions.Exception_Message (E));
raise;
end;
end loop;
end if;
end Set_Member;
-- ------------------------------
-- Get the current location (file and line) to report an error message.
-- ------------------------------
function Get_Location (Handler : in Parser) return String is
pragma Unreferenced (Handler);
begin
return "";
end Get_Location;
-- ------------------------------
-- Report an error while parsing the input stream. The error message will be reported
-- on the logger associated with the parser. The parser will be set as in error so that
-- the <b>Has_Error</b> function will return True after parsing the whole file.
-- ------------------------------
procedure Error (Handler : in out Parser;
Message : in String) is
begin
Handler.Error_Logger.Error ("{0}: {1}",
Parser'Class (Handler).Get_Location,
Message);
Handler.Error_Flag := True;
end Error;
procedure Add_Mapping (Handler : in out Parser;
Path : in String;
Mapper : in Util.Serialize.Mappers.Mapper_Access) is
begin
Handler.Mapping_Tree.Add_Mapping (Path, Mapper);
end Add_Mapping;
-- ------------------------------
-- Dump the mapping tree on the logger using the INFO log level.
-- ------------------------------
procedure Dump (Handler : in Parser'Class;
Logger : in Util.Log.Loggers.Logger'Class) is
begin
Util.Serialize.Mappers.Dump (Handler.Mapping_Tree, Logger, "Mapping ");
end Dump;
end Util.Serialize.IO;
|
-----------------------------------------------------------------------
-- util-serialize-io -- IO Drivers for serialization
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Streams.Files;
with Ada.Streams;
with Ada.Streams.Stream_IO;
with Ada.Exceptions;
package body Util.Serialize.IO is
-- use Util.Log;
use type Util.Log.Loggers.Logger_Access;
-- The logger
Log : aliased constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Serialize.IO",
Util.Log.WARN_LEVEL);
-- ------------------------------
-- Read the file and parse it using the JSON parser.
-- ------------------------------
procedure Parse (Handler : in out Parser;
File : in String) is
Stream : aliased Util.Streams.Files.File_Stream;
Buffer : Util.Streams.Buffered.Buffered_Stream;
begin
if Handler.Error_Logger = null then
Handler.Error_Logger := Log'Access;
end if;
Handler.Error_Logger.Info ("Reading file {0}", File);
Buffer.Initialize (Output => null,
Input => Stream'Unchecked_Access,
Size => 1024);
Stream.Open (Mode => Ada.Streams.Stream_IO.In_File, Name => File);
Context_Stack.Clear (Handler.Stack);
Parser'Class (Handler).Parse (Buffer);
exception
when Util.Serialize.Mappers.Field_Fatal_Error =>
null;
when E : others =>
Parser'Class (Handler).Error ("Exception " & Ada.Exceptions.Exception_Name (E));
end Parse;
-- ------------------------------
-- Parse the content string.
-- ------------------------------
procedure Parse_String (Handler : in out Parser;
Content : in String) is
Stream : aliased Util.Streams.Buffered.Buffered_Stream;
begin
if Handler.Error_Logger = null then
Handler.Error_Logger := Log'Access;
end if;
Stream.Initialize (Content => Content);
Context_Stack.Clear (Handler.Stack);
Parser'Class (Handler).Parse (Stream);
exception
when Util.Serialize.Mappers.Field_Fatal_Error =>
null;
when E : others =>
Handler.Error_Logger.Error ("Exception " & Ada.Exceptions.Exception_Name (E), E);
end Parse_String;
-- ------------------------------
-- Returns true if the <b>Parse</b> operation detected at least one error.
-- ------------------------------
function Has_Error (Handler : in Parser) return Boolean is
begin
return Handler.Error_Flag;
end Has_Error;
-- ------------------------------
-- Set the error logger to report messages while parsing and reading the input file.
-- ------------------------------
procedure Set_Logger (Handler : in out Parser;
Logger : in Util.Log.Loggers.Logger_Access) is
begin
Handler.Error_Logger := Logger;
end Set_Logger;
-- ------------------------------
-- Push the current context when entering in an element.
-- ------------------------------
procedure Push (Handler : in out Parser) is
use type Util.Serialize.Mappers.Mapper_Access;
begin
Context_Stack.Push (Handler.Stack);
end Push;
-- ------------------------------
-- Pop the context and restore the previous context when leaving an element
-- ------------------------------
procedure Pop (Handler : in out Parser) is
begin
Context_Stack.Pop (Handler.Stack);
end Pop;
function Find_Mapper (Handler : in Parser;
Name : in String) return Util.Serialize.Mappers.Mapper_Access is
pragma Unreferenced (Handler, Name);
begin
return null;
end Find_Mapper;
-- ------------------------------
-- Start a new object associated with the given name. This is called when
-- the '{' is reached. The reader must be updated so that the next
-- <b>Set_Member</b> procedure will associate the name/value pair on the
-- new object.
-- ------------------------------
procedure Start_Object (Handler : in out Parser;
Name : in String) is
use type Util.Serialize.Mappers.Mapper_Access;
Current : constant Element_Context_Access := Context_Stack.Current (Handler.Stack);
Next : Element_Context_Access;
Pos : Positive;
begin
Context_Stack.Push (Handler.Stack);
Next := Context_Stack.Current (Handler.Stack);
if Current /= null then
Pos := 1;
-- Notify we are entering in the given node for each active mapping.
for I in Current.Active_Nodes'Range loop
declare
Node : constant Mappers.Mapper_Access := Current.Active_Nodes (I);
Child : Mappers.Mapper_Access;
begin
exit when Node = null;
Child := Node.Find_Mapper (Name => Name);
if Child /= null then
Child.Start_Object (Handler, Name);
Next.Active_Nodes (Pos) := Child;
Pos := Pos + 1;
end if;
end;
end loop;
while Pos <= Next.Active_Nodes'Last loop
Next.Active_Nodes (Pos) := null;
Pos := Pos + 1;
end loop;
else
Next.Active_Nodes (1) := Handler.Mapping_Tree.Find_Mapper (Name);
end if;
end Start_Object;
-- ------------------------------
-- Finish an object associated with the given name. The reader must be
-- updated to be associated with the previous object.
-- ------------------------------
procedure Finish_Object (Handler : in out Parser;
Name : in String) is
use type Util.Serialize.Mappers.Mapper_Access;
begin
declare
Current : constant Element_Context_Access := Context_Stack.Current (Handler.Stack);
begin
if Current /= null then
-- Notify we are leaving the given node for each active mapping.
for I in Current.Active_Nodes'Range loop
declare
Node : constant Mappers.Mapper_Access := Current.Active_Nodes (I);
begin
exit when Node = null;
Node.Finish_Object (Handler, Name);
end;
end loop;
end if;
end;
Handler.Pop;
end Finish_Object;
procedure Start_Array (Handler : in out Parser;
Name : in String) is
pragma Unreferenced (Name);
begin
Handler.Push;
end Start_Array;
procedure Finish_Array (Handler : in out Parser;
Name : in String) is
pragma Unreferenced (Name);
begin
Handler.Pop;
end Finish_Array;
-- -----------------------
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
-- -----------------------
procedure Set_Member (Handler : in out Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False) is
use Util.Serialize.Mappers;
Current : constant Element_Context_Access := Context_Stack.Current (Handler.Stack);
begin
if Current /= null then
-- Look each active mapping node.
for I in Current.Active_Nodes'Range loop
declare
Node : constant Mapper_Access := Current.Active_Nodes (I);
begin
exit when Node = null;
Node.Set_Member (Name => Name,
Value => Value,
Attribute => Attribute,
Context => Handler);
exception
when E : Util.Serialize.Mappers.Field_Error =>
Handler.Error (Message => Ada.Exceptions.Exception_Message (E));
when E : Util.Serialize.Mappers.Field_Fatal_Error =>
Handler.Error (Message => Ada.Exceptions.Exception_Message (E));
raise;
-- For other exception, report an error with the field name and value.
when E : others =>
Handler.Error (Message => "Cannot set field '" & Name & "' to '"
& Util.Beans.Objects.To_String (Value) & "': "
& Ada.Exceptions.Exception_Message (E));
raise;
end;
end loop;
end if;
end Set_Member;
-- ------------------------------
-- Get the current location (file and line) to report an error message.
-- ------------------------------
function Get_Location (Handler : in Parser) return String is
pragma Unreferenced (Handler);
begin
return "";
end Get_Location;
-- ------------------------------
-- Report an error while parsing the input stream. The error message will be reported
-- on the logger associated with the parser. The parser will be set as in error so that
-- the <b>Has_Error</b> function will return True after parsing the whole file.
-- ------------------------------
procedure Error (Handler : in out Parser;
Message : in String) is
begin
Handler.Error_Logger.Error ("{0}: {1}",
Parser'Class (Handler).Get_Location,
Message);
Handler.Error_Flag := True;
end Error;
procedure Add_Mapping (Handler : in out Parser;
Path : in String;
Mapper : in Util.Serialize.Mappers.Mapper_Access) is
begin
Handler.Mapping_Tree.Add_Mapping (Path, Mapper);
end Add_Mapping;
-- ------------------------------
-- Dump the mapping tree on the logger using the INFO log level.
-- ------------------------------
procedure Dump (Handler : in Parser'Class;
Logger : in Util.Log.Loggers.Logger'Class) is
begin
Util.Serialize.Mappers.Dump (Handler.Mapping_Tree, Logger, "Mapping ");
end Dump;
end Util.Serialize.IO;
|
Add an info log when reading a file
|
Add an info log when reading a file
|
Ada
|
apache-2.0
|
Letractively/ada-util,flottokarotto/ada-util,Letractively/ada-util,flottokarotto/ada-util
|
db12244a6aabf7132cea04f66bb9fe2b97c46f40
|
regtests/util-commands-tests.adb
|
regtests/util-commands-tests.adb
|
-----------------------------------------------------------------------
-- util-commands-tests - Test for commands
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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 GNAT.Command_Line;
with Util.Test_Caller;
with Util.Commands.Parsers.GNAT_Parser;
with Util.Commands.Drivers;
package body Util.Commands.Tests is
package Caller is new Util.Test_Caller (Test, "Commands");
type Test_Context_Type is record
Number : Integer;
Success : Boolean := False;
end record;
package Test_Command is new
Util.Commands.Drivers (Context_Type => Test_Context_Type,
Config_Parser => Util.Commands.Parsers.GNAT_Parser.Config_Parser,
Driver_Name => "test");
type Test_Command_Type is new Test_Command.Command_Type with record
Opt_Count : aliased Integer := 0;
Opt_V : aliased Boolean := False;
Opt_N : aliased Boolean := False;
Expect_V : Boolean := False;
Expect_N : Boolean := False;
Expect_C : Integer := 0;
Expect_A : Integer := 0;
Expect_Help : Boolean := False;
end record;
overriding
procedure Execute (Command : in out Test_Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Test_Context_Type);
-- Setup the command before parsing the arguments and executing it.
procedure Setup (Command : in out Test_Command_Type;
Config : in out GNAT.Command_Line.Command_Line_Configuration;
Context : in out Test_Context_Type);
-- Write the help associated with the command.
procedure Help (Command : in out Test_Command_Type;
Context : in out Test_Context_Type);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Commands.Driver.Execute",
Test_Execute'Access);
Caller.Add_Test (Suite, "Test Util.Commands.Driver.Help",
Test_Help'Access);
Caller.Add_Test (Suite, "Test Util.Commands.Driver.Usage",
Test_Usage'Access);
end Add_Tests;
overriding
procedure Execute (Command : in out Test_Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Test_Context_Type) is
pragma Unreferenced (Name);
begin
Context.Success := Command.Opt_Count = Command.Expect_C and
Command.Opt_V = Command.Expect_V and
Command.Opt_N = Command.Expect_N and
Args.Get_Count = Command.Expect_A and
not Command.Expect_Help;
end Execute;
-- ------------------------------
-- Setup the command before parsing the arguments and executing it.
-- ------------------------------
procedure Setup (Command : in out Test_Command_Type;
Config : in out GNAT.Command_Line.Command_Line_Configuration;
Context : in out Test_Context_Type) is
pragma Unreferenced (Context);
begin
GNAT.Command_Line.Define_Switch (Config => Config,
Switch => "-c:",
Long_Switch => "--count=",
Help => "Number option",
Section => "",
Initial => Integer (0),
Default => Integer (10),
Output => Command.Opt_Count'Access);
GNAT.Command_Line.Define_Switch (Config => Config,
Switch => "-v",
Long_Switch => "--verbose",
Help => "Verbose option",
Section => "",
Output => Command.Opt_V'Access);
GNAT.Command_Line.Define_Switch (Config => Config,
Switch => "-n",
Long_Switch => "--not",
Help => "Not option",
Section => "",
Output => Command.Opt_N'Access);
end Setup;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Command : in out Test_Command_Type;
Context : in out Test_Context_Type) is
begin
Context.Success := Command.Expect_Help;
end Help;
-- ------------------------------
-- Tests when the execution of commands.
-- ------------------------------
procedure Test_Execute (T : in out Test) is
C1 : aliased Test_Command_Type;
C2 : aliased Test_Command_Type;
D : Test_Command.Driver_Type;
Args : String_Argument_List (500, 30);
begin
D.Set_Description ("Test command");
D.Add_Command ("list", C1'Unchecked_Access);
D.Add_Command ("print", C2'Unchecked_Access);
declare
Ctx : Test_Context_Type;
begin
C1.Expect_V := True;
C1.Expect_N := True;
C1.Expect_C := 4;
C1.Expect_A := 2;
Initialize (Args, "list --count=4 -v -n test titi");
D.Execute ("list", Args, Ctx);
T.Assert (Ctx.Success, "Some arguments not parsed correctly");
end;
declare
Ctx : Test_Context_Type;
begin
C1.Expect_V := False;
C1.Expect_N := True;
C1.Expect_C := 8;
C1.Expect_A := 3;
Initialize (Args, "list -c 8 -n test titi last");
D.Execute ("list", Args, Ctx);
T.Assert (Ctx.Success, "Some arguments not parsed correctly");
end;
end Test_Execute;
-- ------------------------------
-- Test execution of help.
-- ------------------------------
procedure Test_Help (T : in out Test) is
C1 : aliased Test_Command_Type;
C2 : aliased Test_Command_Type;
H : aliased Test_Command.Help_Command_Type;
D : Test_Command.Driver_Type;
Args : String_Argument_List (500, 30);
begin
D.Set_Description ("Test command");
D.Add_Command ("list", C1'Unchecked_Access);
D.Add_Command ("print", C2'Unchecked_Access);
D.Add_Command ("help", H'Unchecked_Access);
declare
Ctx : Test_Context_Type;
begin
C1.Expect_Help := True;
Initialize (Args, "help list");
D.Execute ("help", Args, Ctx);
T.Assert (Ctx.Success, "Some arguments not parsed correctly");
end;
declare
Ctx : Test_Context_Type;
begin
C2.Expect_Help := True;
Initialize (Args, "help print");
D.Execute ("help", Args, Ctx);
T.Assert (Ctx.Success, "Some arguments not parsed correctly");
end;
end Test_Help;
-- ------------------------------
-- Test usage operation.
-- ------------------------------
procedure Test_Usage (T : in out Test) is
C1 : aliased Test_Command_Type;
C2 : aliased Test_Command_Type;
H : aliased Test_Command.Help_Command_Type;
D : Test_Command.Driver_Type;
Args : String_Argument_List (500, 30);
begin
D.Set_Description ("Test command");
D.Add_Command ("list", C1'Unchecked_Access);
D.Add_Command ("print", C2'Unchecked_Access);
D.Add_Command ("help", H'Unchecked_Access);
Args.Initialize (Line => "cmd list");
declare
Ctx : Test_Context_Type;
begin
D.Usage (Args, Ctx);
C1.Expect_Help := True;
Initialize (Args, "help list");
D.Execute ("help", Args, Ctx);
T.Assert (Ctx.Success, "Some arguments not parsed correctly");
end;
end Test_Usage;
end Util.Commands.Tests;
|
-----------------------------------------------------------------------
-- util-commands-tests - Test for commands
-- Copyright (C) 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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 GNAT.Command_Line;
with Util.Test_Caller;
with Util.Commands.Parsers.GNAT_Parser;
with Util.Commands.Drivers;
package body Util.Commands.Tests is
package Caller is new Util.Test_Caller (Test, "Commands");
type Test_Context_Type is record
Number : Integer;
Success : Boolean := False;
end record;
package Test_Command is new
Util.Commands.Drivers (Context_Type => Test_Context_Type,
Config_Parser => Util.Commands.Parsers.GNAT_Parser.Config_Parser,
Driver_Name => "test");
type Test_Command_Type is new Test_Command.Command_Type with record
Opt_Count : aliased Integer := 0;
Opt_V : aliased Boolean := False;
Opt_N : aliased Boolean := False;
Expect_V : Boolean := False;
Expect_N : Boolean := False;
Expect_C : Integer := 0;
Expect_A : Integer := 0;
Expect_Help : Boolean := False;
end record;
overriding
procedure Execute (Command : in out Test_Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Test_Context_Type);
-- Setup the command before parsing the arguments and executing it.
procedure Setup (Command : in out Test_Command_Type;
Config : in out GNAT.Command_Line.Command_Line_Configuration;
Context : in out Test_Context_Type);
-- Write the help associated with the command.
procedure Help (Command : in out Test_Command_Type;
Name : in String;
Context : in out Test_Context_Type);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Commands.Driver.Execute",
Test_Execute'Access);
Caller.Add_Test (Suite, "Test Util.Commands.Driver.Help",
Test_Help'Access);
Caller.Add_Test (Suite, "Test Util.Commands.Driver.Usage",
Test_Usage'Access);
end Add_Tests;
overriding
procedure Execute (Command : in out Test_Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Test_Context_Type) is
pragma Unreferenced (Name);
begin
Context.Success := Command.Opt_Count = Command.Expect_C and
Command.Opt_V = Command.Expect_V and
Command.Opt_N = Command.Expect_N and
Args.Get_Count = Command.Expect_A and
not Command.Expect_Help;
end Execute;
-- ------------------------------
-- Setup the command before parsing the arguments and executing it.
-- ------------------------------
procedure Setup (Command : in out Test_Command_Type;
Config : in out GNAT.Command_Line.Command_Line_Configuration;
Context : in out Test_Context_Type) is
pragma Unreferenced (Context);
begin
GNAT.Command_Line.Define_Switch (Config => Config,
Switch => "-c:",
Long_Switch => "--count=",
Help => "Number option",
Section => "",
Initial => Integer (0),
Default => Integer (10),
Output => Command.Opt_Count'Access);
GNAT.Command_Line.Define_Switch (Config => Config,
Switch => "-v",
Long_Switch => "--verbose",
Help => "Verbose option",
Section => "",
Output => Command.Opt_V'Access);
GNAT.Command_Line.Define_Switch (Config => Config,
Switch => "-n",
Long_Switch => "--not",
Help => "Not option",
Section => "",
Output => Command.Opt_N'Access);
end Setup;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Command : in out Test_Command_Type;
Name : in String;
Context : in out Test_Context_Type) is
pragma Unreferenced (Name);
begin
Context.Success := Command.Expect_Help;
end Help;
-- ------------------------------
-- Tests when the execution of commands.
-- ------------------------------
procedure Test_Execute (T : in out Test) is
C1 : aliased Test_Command_Type;
C2 : aliased Test_Command_Type;
D : Test_Command.Driver_Type;
Args : String_Argument_List (500, 30);
begin
D.Set_Description ("Test command");
D.Add_Command ("list", C1'Unchecked_Access);
D.Add_Command ("print", C2'Unchecked_Access);
declare
Ctx : Test_Context_Type;
begin
C1.Expect_V := True;
C1.Expect_N := True;
C1.Expect_C := 4;
C1.Expect_A := 2;
Initialize (Args, "list --count=4 -v -n test titi");
D.Execute ("list", Args, Ctx);
T.Assert (Ctx.Success, "Some arguments not parsed correctly");
end;
declare
Ctx : Test_Context_Type;
begin
C1.Expect_V := False;
C1.Expect_N := True;
C1.Expect_C := 8;
C1.Expect_A := 3;
Initialize (Args, "list -c 8 -n test titi last");
D.Execute ("list", Args, Ctx);
T.Assert (Ctx.Success, "Some arguments not parsed correctly");
end;
end Test_Execute;
-- ------------------------------
-- Test execution of help.
-- ------------------------------
procedure Test_Help (T : in out Test) is
C1 : aliased Test_Command_Type;
C2 : aliased Test_Command_Type;
H : aliased Test_Command.Help_Command_Type;
D : Test_Command.Driver_Type;
Args : String_Argument_List (500, 30);
begin
D.Set_Description ("Test command");
D.Add_Command ("list", C1'Unchecked_Access);
D.Add_Command ("print", C2'Unchecked_Access);
D.Add_Command ("help", H'Unchecked_Access);
declare
Ctx : Test_Context_Type;
begin
C1.Expect_Help := True;
Initialize (Args, "help list");
D.Execute ("help", Args, Ctx);
T.Assert (Ctx.Success, "Some arguments not parsed correctly");
end;
declare
Ctx : Test_Context_Type;
begin
C2.Expect_Help := True;
Initialize (Args, "help print");
D.Execute ("help", Args, Ctx);
T.Assert (Ctx.Success, "Some arguments not parsed correctly");
end;
end Test_Help;
-- ------------------------------
-- Test usage operation.
-- ------------------------------
procedure Test_Usage (T : in out Test) is
C1 : aliased Test_Command_Type;
C2 : aliased Test_Command_Type;
H : aliased Test_Command.Help_Command_Type;
D : Test_Command.Driver_Type;
Args : String_Argument_List (500, 30);
begin
D.Set_Description ("Test command");
D.Add_Command ("list", C1'Unchecked_Access);
D.Add_Command ("print", C2'Unchecked_Access);
D.Add_Command ("help", H'Unchecked_Access);
Args.Initialize (Line => "cmd list");
declare
Ctx : Test_Context_Type;
begin
D.Usage (Args, Ctx);
C1.Expect_Help := True;
Initialize (Args, "help list");
D.Execute ("help", Args, Ctx);
T.Assert (Ctx.Success, "Some arguments not parsed correctly");
end;
end Test_Usage;
end Util.Commands.Tests;
|
Add Name parameter to the Help procedure
|
Add Name parameter to the Help procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
448a76e17f454690cde06faa2b0de19ee9e03f4b
|
regtests/util-serialize-io-form-tests.adb
|
regtests/util-serialize-io-form-tests.adb
|
-----------------------------------------------------------------------
-- util-serialize-io-form-tests -- Unit tests for form parser
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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.Stream_IO;
with Ada.Characters.Wide_Wide_Latin_1;
with Ada.Calendar.Formatting;
with Util.Test_Caller;
with Util.Log.Loggers;
with Util.Streams.Files;
with Util.Beans.Objects.Readers;
package body Util.Serialize.IO.Form.Tests is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.Form");
package Caller is new Util.Test_Caller (Test, "Serialize.IO.Form");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Parse (parse errors)",
Test_Parse_Error'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Parse (parse Ok)",
Test_Parser'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Write",
Test_Output'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Read",
Test_Read'Access);
end Add_Tests;
-- ------------------------------
-- Check various form parsing errors.
-- ------------------------------
procedure Test_Parse_Error (T : in out Test) is
procedure Check_Parse_Error (Content : in String);
procedure Check_Parse_Error (Content : in String) is
P : Parser;
R : Util.Beans.Objects.Readers.Reader;
begin
P.Parse_String (Content, R);
Log.Error ("No exception raised for: {0}", Content);
-- T.Fail ("No exception for " & Content);
exception
when Parse_Error =>
null;
end Check_Parse_Error;
begin
Check_Parse_Error ("bad");
Check_Parse_Error ("bad=%rw%ad");
end Test_Parse_Error;
-- ------------------------------
-- Check various (basic) JSformON valid strings (no mapper).
-- ------------------------------
procedure Test_Parser (T : in out Test) is
procedure Check_Parse (Content : in String);
procedure Check_Parse (Content : in String) is
P : Parser;
R : Util.Beans.Objects.Readers.Reader;
begin
P.Parse_String (Content, R);
exception
when Parse_Error =>
Log.Error ("Parse error for: " & Content);
T.Fail ("Parse error for: " & Content);
end Check_Parse;
begin
Check_Parse ("name=value");
Check_Parse ("name=value¶m=value");
Check_Parse ("name+name=value+value");
Check_Parse ("name%20%30=value%23%ce");
end Test_Parser;
-- ------------------------------
-- Generate some output stream for the test.
-- ------------------------------
procedure Write_Stream (Stream : in out Util.Serialize.IO.Output_Stream'Class) is
Name : Ada.Strings.Unbounded.Unbounded_String;
Wide : constant Wide_Wide_String :=
Ada.Characters.Wide_Wide_Latin_1.CR &
Ada.Characters.Wide_Wide_Latin_1.LF &
Ada.Characters.Wide_Wide_Latin_1.HT &
Wide_Wide_Character'Val (16#080#) &
Wide_Wide_Character'Val (16#1fC#) &
Wide_Wide_Character'Val (16#20AC#) & -- Euro sign
Wide_Wide_Character'Val (16#2acbf#);
T : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (2011, 11, 19, 23, 0, 0);
begin
Ada.Strings.Unbounded.Append (Name, "Katniss Everdeen");
Stream.Start_Document;
Stream.Start_Entity ("root");
Stream.Start_Entity ("person");
Stream.Write_Attribute ("id", 1);
Stream.Write_Attribute ("name", Name);
Stream.Write_Entity ("name", Name);
Stream.Write_Entity ("gender", "female");
Stream.Write_Entity ("volunteer", True);
Stream.Write_Entity ("age", 17);
Stream.Write_Entity ("date", T);
Stream.Write_Wide_Entity ("skin", "olive skin");
Stream.Start_Array ("badges");
Stream.Start_Entity ("badge");
Stream.Write_Entity ("level", "gold");
Stream.Write_Entity ("name", "hunter");
Stream.End_Entity ("badge");
Stream.Start_Entity ("badge");
Stream.Write_Entity ("level", "gold");
Stream.Write_Entity ("name", "archery");
Stream.End_Entity ("badge");
Stream.End_Array ("badges");
Stream.Start_Entity ("district");
Stream.Write_Attribute ("id", 12);
Stream.Write_Wide_Attribute ("industry", "Coal mining");
Stream.Write_Attribute ("state", "<destroyed>");
Stream.Write_Long_Entity ("members", 10_000);
Stream.Write_Entity ("description", "<TBW>&""");
Stream.Write_Wide_Entity ("wescape", "'""<>&;,@!`~[]{}^%*()-+=");
Stream.Write_Entity ("escape", "'""<>&;,@!`~\[]{}^%*()-+=");
Stream.Write_Wide_Entity ("wide", Wide);
Stream.End_Entity ("district");
Stream.End_Entity ("person");
Stream.End_Entity ("root");
Stream.End_Document;
end Write_Stream;
-- ------------------------------
-- Test the JSON output stream generation.
-- ------------------------------
procedure Test_Output (T : in out Test) is
File : aliased Util.Streams.Files.File_Stream;
Buffer : aliased Util.Streams.Texts.Print_Stream;
Stream : Util.Serialize.IO.Form.Output_Stream;
Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.form");
Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.form");
begin
File.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Path);
Buffer.Initialize (Output => File'Unchecked_Access, Size => 10000);
Stream.Initialize (Output => Buffer'Unchecked_Access);
Write_Stream (Stream);
Stream.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => Expect,
Test => Path,
Message => "Form output serialization");
end Test_Output;
-- ------------------------------
-- Test reading a form content into an Object tree.
-- ------------------------------
procedure Test_Read (T : in out Test) is
use Util.Beans.Objects;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/files/pass-01.form");
Root : Util.Beans.Objects.Object;
Value : Util.Beans.Objects.Object;
begin
Root := Read (Path);
T.Assert (not Util.Beans.Objects.Is_Null (Root), "Read should not return null object");
T.Assert (not Util.Beans.Objects.Is_Array (Root), "Root object is not an array");
Value := Util.Beans.Objects.Get_Value (Root, "home");
Util.Tests.Assert_Equals (T, "Cosby",
Util.Beans.Objects.To_String (Value),
"Invalid first parameter");
Value := Util.Beans.Objects.Get_Value (Root, "favorite flavor");
Util.Tests.Assert_Equals (T, "flies",
Util.Beans.Objects.To_String (Value),
"Invalid second parameter");
end Test_Read;
end Util.Serialize.IO.Form.Tests;
|
Implement new tests for form serialization and deserialization
|
Implement new tests for form serialization and deserialization
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
|
f0e8392273d08f6316ee2db14b4438b29da919a7
|
src/asf-components-utils.adb
|
src/asf-components-utils.adb
|
-----------------------------------------------------------------------
-- components-util -- ASF Util Components
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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.Views.Nodes;
package body ASF.Components.Utils is
-- ------------------------------
-- Get the line information where the component is defined.
-- ------------------------------
function Get_Line_Info (UI : in UIComponent'Class) return Views.Nodes.Line_Info is
begin
if UI.Tag /= null then
return UI.Tag.Get_Line_Info;
else
return UI.Tag.Get_Line_Info;
end if;
end Get_Line_Info;
-- ------------------------------
-- Get the line information where the component is defined.
-- ------------------------------
function Get_Line_Info (UI : in UIComponent'Class) return String is
begin
if UI.Tag /= null then
return UI.Tag.Get_Line_Info;
else
return UI.Tag.Get_Line_Info;
end if;
end Get_Line_Info;
end ASF.Components.Utils;
|
Implement the Get_Line_Info function
|
Implement the Get_Line_Info function
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
|
95e4c6bf2d8ed371b3d4c7d0c10c323373f9fe75
|
regtests/wiki-filters-html-tests.adb
|
regtests/wiki-filters-html-tests.adb
|
-----------------------------------------------------------------------
-- wiki-filters-html-tests -- Unit tests for wiki HTML filters
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Assertions;
with Util.Strings;
with Util.Log.Loggers;
package body Wiki.Filters.Html.Tests is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Wiki.Filters");
package Caller is new Util.Test_Caller (Test, "Wikis.Filters.Html");
procedure Assert_Equals is
new Util.Assertions.Assert_Equals_T (Html_Tag_Type);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Wiki.Filters.Html.Find_Tag",
Test_Find_Tag'Access);
end Add_Tests;
-- Test Find_Tag operation.
procedure Test_Find_Tag (T : in out Test) is
begin
for I in Html_Tag_Type'Range loop
declare
Name : constant String := Html_Tag_Type'Image (I);
Wname : constant Wide_Wide_String := Html_Tag_Type'Wide_Wide_Image (I);
Pos : constant Natural := Util.Strings.Index (Name, '_');
Tag : constant Html_Tag_Type := Find_Tag (WName (WName'First .. Pos - 1));
begin
Log.Info ("Checking tag {0}", Name);
Assert_Equals (T, I, Tag, "Find_Tag failed");
end;
end loop;
end Test_Find_Tag;
end Wiki.Filters.Html.Tests;
|
Implement a new test for the HTML filters internal operations
|
Implement a new test for the HTML filters internal operations
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
|
f8fb79133291c1fe993dea1190f5c8fb37462ca4
|
src/wiki-utils.ads
|
src/wiki-utils.ads
|
-----------------------------------------------------------------------
-- wiki-utils -- Wiki utility operations
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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 Wiki.Parsers;
package Wiki.Utils is
-- Render the wiki text according to the wiki syntax in HTML into a string.
function To_Html (Text : in Wide_Wide_String;
Syntax : in Wiki.Parsers.Wiki_Syntax_Type) return String;
-- Render the wiki text according to the wiki syntax in text into a string.
-- Wiki formatting and decoration are removed.
function To_Text (Text : in Wide_Wide_String;
Syntax : in Wiki.Parsers.Wiki_Syntax_Type) return String;
end Wiki.Utils;
|
Define the Wiki.Utils package with To_Html and To_Text functions
|
Define the Wiki.Utils package with To_Html and To_Text functions
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
|
2512f8fcd8093724d36f1674488e4e49de1776c8
|
src/asis/a4g-a_debug.ads
|
src/asis/a4g-a_debug.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . A _ D E B U G --
-- --
-- S p e c --
-- --
-- Copyright (C) 1995-2012, 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, 59 Temple Place --
-- - Suite 330, Boston, MA 02111-1307, 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 Ada Core Technologies Inc --
-- (http://www.gnat.com). --
-- --
------------------------------------------------------------------------------
package A4G.A_Debug is
-- This package contains global flags used to control the inclusion
-- of debugging code in various phases of the ASIS-for-GNAT. It is
-- an almost complete analog of the GNAT Debug package
-------------------------
-- Dynamic Debug Flags --
-------------------------
-- Thirty six flags that can be used to activate various specialized
-- debugging output information. The flags are preset to False, which
-- corresponds to the given output being suppressed. The individual
-- flags can be turned on using the undocumented switch /dxxx where
-- xxx is a string of letters for flags to be turned on. Documentation
-- on the current usage of these flags is contained in the body of Debug
-- rather than the spec, so that we don't have to recompile the world
-- when a new debug flag is added
Debug_Flag_A : Boolean := False;
Debug_Flag_B : Boolean := False;
Debug_Flag_C : Boolean := False;
Debug_Flag_D : Boolean := False;
Debug_Flag_E : Boolean := False;
Debug_Flag_F : Boolean := False;
Debug_Flag_G : Boolean := False;
Debug_Flag_H : Boolean := False;
Debug_Flag_I : Boolean := False;
Debug_Flag_J : Boolean := False;
Debug_Flag_K : Boolean := False;
Debug_Flag_L : Boolean := False;
Debug_Flag_M : Boolean := False;
Debug_Flag_N : Boolean := False;
Debug_Flag_O : Boolean := False;
Debug_Flag_P : Boolean := False;
Debug_Flag_Q : Boolean := False;
Debug_Flag_R : Boolean := False;
Debug_Flag_S : Boolean := False;
Debug_Flag_T : Boolean := False;
Debug_Flag_U : Boolean := False;
Debug_Flag_V : Boolean := False;
Debug_Flag_W : Boolean := False;
Debug_Flag_X : Boolean := False;
Debug_Flag_Y : Boolean := False;
Debug_Flag_Z : Boolean := False;
Debug_Flag_1 : Boolean := False;
Debug_Flag_2 : Boolean := False;
Debug_Flag_3 : Boolean := False;
Debug_Flag_4 : Boolean := False;
Debug_Flag_5 : Boolean := False;
Debug_Flag_6 : Boolean := False;
Debug_Flag_7 : Boolean := False;
Debug_Flag_8 : Boolean := False;
Debug_Flag_9 : Boolean := False;
procedure Set_Debug_Flag (C : Character; Val : Boolean := True);
-- Where C is 0-9 or a-z, sets the corresponding debug flag to the
-- given value. In the checks off version of debug, the call to
-- Set_Debug_Flag is always a null operation.
procedure Set_Off;
-- Sets all the debug flags OFF (except Debug_Lib_Model for now),
-- is to be called by Asis_Environment.Finalize
procedure Set_On; -- TEMPORARY SOLUTION!!!
-- Sets all the debug flags ON.
------------------------
-- TEMPORARY SOLUTION --
------------------------
Debug_Mode : Boolean := False;
-- Flag indicating if the debugging information should be output by the
-- routines from the A4G.A_Output package
Debug_Lib_Model : Boolean := False;
-- Flag forcing the debug output of the tables implementing the ASIS
-- Context Model to be performed when finalizing the ASIS Environment.
-- Currently should be set by hand. The debug output is produced only if
-- Debug_Mode is set ON.
end A4G.A_Debug;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
ee53abf2390868489cf59ca2d9db8a1cd6542fb7
|
src/natools-static_maps-s_expressions-conditionals.ads
|
src/natools-static_maps-s_expressions-conditionals.ads
|
------------------------------------------------------------------------------
-- Copyright (c) 2015, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Natools.Static_Maps.S_Expressions.Conditionals is a common parent to --
-- generated static hash maps related to S-expression conditionals system. --
------------------------------------------------------------------------------
package Natools.Static_Maps.S_Expressions.Conditionals is
pragma Pure;
end Natools.Static_Maps.S_Expressions.Conditionals;
|
add missing package in previous commits
|
static_maps-s_expressions-conditionals: add missing package in previous commits
|
Ada
|
isc
|
faelys/natools
|
|
5aed4e74edbad0dd6ddeaa9a25ffa901e3930c83
|
samples/gperfhash.adb
|
samples/gperfhash.adb
|
-----------------------------------------------------------------------
-- gperfhash -- Perfect hash Ada generator
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Strings.Unbounded;
with Ada.Strings.Fixed;
with Ada.Command_Line;
with GNAT.Command_Line;
with GNAT.Perfect_Hash_Generators;
with Util.Log.Loggers;
with Util.Files;
with Util.Strings.Vectors;
with Util.Strings.Transforms;
-- This simple utility is an Ada perfect hash generator. Given a fixed set of keywords,
-- it generates an Ada package (spec and body) which provides a perfect hash function.
-- The perfect hash algorithm is in fact provided by GNAT Perfect_Hash_Generators package.
procedure Gperfhash is
use Util.Log.Loggers;
use Ada.Strings.Unbounded;
use GNAT.Command_Line;
use Ada.Text_IO;
-- Read a keyword and add it in the keyword list.
procedure Read_Keyword (Line : in String);
-- Given a package name, return the file name that correspond.
function To_File_Name (Name : in String) return String;
procedure Generate_Keyword_Table (Into : in out Ada.Text_IO.File_Type);
-- Generate the package specification.
procedure Generate_Specs (Name : in String);
-- Generate the package body.
procedure Generate_Body (Name : in String);
Log : constant Logger := Create ("log", "samples/log4j.properties");
Pkg_Name : Unbounded_String := To_Unbounded_String ("gphash");
Names : Util.Strings.Vectors.Vector;
-- When true, generate a perfect hash which ignores the case.
Ignore_Case : Boolean := False;
-- ------------------------------
-- Generate the keyword table.
-- ------------------------------
procedure Generate_Keyword_Table (Into : in out Ada.Text_IO.File_Type) is
Index : Integer := 0;
procedure Print_Keyword (Pos : in Util.Strings.Vectors.Cursor);
procedure Print_Table (Pos : in Util.Strings.Vectors.Cursor);
-- ------------------------------
-- Print a keyword as an Ada constant string.
-- ------------------------------
procedure Print_Keyword (Pos : in Util.Strings.Vectors.Cursor) is
Name : constant String := Util.Strings.Vectors.Element (Pos);
begin
Put (Into, " K_");
Put (Into, Util.Strings.Image (Index));
Set_Col (Into, 20);
Put (Into, ": aliased constant String := """);
Put (Into, Name);
Put_Line (Into, """;");
Index := Index + 1;
end Print_Keyword;
-- ------------------------------
-- Build the keyword table.
-- ------------------------------
procedure Print_Table (Pos : in Util.Strings.Vectors.Cursor) is
pragma Unreferenced (Pos);
begin
if Index > 0 then
if Index mod 4 = 0 then
Put_Line (Into, ",");
Put (Into, " ");
else
Put (Into, ", ");
end if;
end if;
Put (Into, "K_");
Put (Into, Util.Strings.Image (Index));
Put (Into, "'Access");
Index := Index + 1;
end Print_Table;
begin
New_Line (Into);
Put_Line (Into, " type Name_Access is access constant String;");
Put_Line (Into, " type Keyword_Array is array (Natural range <>) of Name_Access;");
Put_Line (Into, " Keywords : constant Keyword_Array;");
Put_Line (Into, "private");
New_Line (Into);
Names.Iterate (Print_Keyword'Access);
New_Line (Into);
Index := 0;
Put_Line (Into, " Keywords : constant Keyword_Array := (");
Put (Into, " ");
Names.Iterate (Print_Table'Access);
Put_Line (Into, ");");
end Generate_Keyword_Table;
-- ------------------------------
-- Generate the package specification.
-- ------------------------------
procedure Generate_Specs (Name : in String) is
File : Ada.Text_IO.File_Type;
Path : constant String := To_File_Name (Name) & ".ads";
begin
Ada.Text_IO.Open (File => File,
Mode => Ada.Text_IO.Out_File,
Name => Path);
Put_Line (File, "-- Generated by gperfhash");
Put (File, "package ");
Put (File, To_String (Pkg_Name));
Put_Line (File, " is");
New_Line (File);
Put_Line (File, " function Hash (S : String) return Natural;");
New_Line (File);
Put_Line (File, " -- Returns true if the string <b>S</b> is a keyword.");
Put_Line (File, " function Is_Keyword (S : in String) return Boolean;");
Generate_Keyword_Table (File);
Put (File, "end ");
Put (File, To_String (Pkg_Name));
Put (File, ";");
New_Line (File);
Close (File);
end Generate_Specs;
-- ------------------------------
-- Generate the package body.
-- ------------------------------
procedure Generate_Body (Name : in String) is
-- Read the generated body file.
procedure Read_Body (Line : in String);
Path : constant String := To_File_Name (Name) & ".adb";
File : Ada.Text_IO.File_Type;
Count : Natural;
Lines : Util.Strings.Vectors.Vector;
-- ------------------------------
-- Read the generated body file.
-- ------------------------------
procedure Read_Body (Line : in String) is
begin
Lines.Append (Line);
end Read_Body;
procedure Generate_Char_Position is
use GNAT.Perfect_Hash_Generators;
V : Natural;
begin
Put (File, " (");
for I in 0 .. 255 loop
if I >= Character'Pos ('a') and I <= Character'Pos ('z') then
V := Value (Used_Character_Set, I - Character'Pos ('a') + Character'Pos ('A'));
else
V := GNAT.Perfect_Hash_Generators.Value (Used_Character_Set, I);
end if;
if I > 0 then
if I mod 16 = 0 then
Put_Line (File, ",");
Put (File, " ");
else
Put (File, ", ");
end if;
end if;
Put (File, Util.Strings.Image (V));
end loop;
Put_Line (File, ");");
end Generate_Char_Position;
begin
Util.Files.Read_File (Path => Path, Process => Read_Body'Access);
Count := Natural (Lines.Length);
Ada.Text_IO.Open (File => File,
Mode => Ada.Text_IO.Out_File,
Name => Path);
Put_Line (File, "-- Generated by gperfhash");
if Ignore_Case then
Put_Line (File, "with Util.Strings.Transforms;");
end if;
for I in 1 .. Count loop
declare
L : constant String := Lines.Element (I);
begin
if Ignore_Case and I >= 6 and I <= 16 then
if I = 6 then
Generate_Char_Position;
end if;
else
Put_Line (File, L);
end if;
-- Generate the Is_Keyword function before the package end.
if I = Count - 1 then
Put_Line (File, " -- Returns true if the string <b>S</b> is a keyword.");
Put_Line (File, " function Is_Keyword (S : in String) return Boolean is");
Put_Line (File, " H : constant Natural := Hash (S);");
Put_Line (File, " begin");
if Ignore_Case then
Put_Line (File, " return Keywords (H).all = "
& "Util.Strings.Transforms.To_Upper_Case (S);");
else
Put_Line (File, " return Keywords (H).all = S;");
end if;
Put_Line (File, " end Is_Keyword;");
end if;
end;
end loop;
Close (File);
end Generate_Body;
-- ------------------------------
-- Read a keyword and add it in the keyword list.
-- ------------------------------
procedure Read_Keyword (Line : in String) is
use Ada.Strings;
Word : String := Fixed.Trim (Line, Both);
begin
if Word'Length > 0 then
if Ignore_Case then
Word := Util.Strings.Transforms.To_Upper_Case (Word);
end if;
Names.Append (Word);
GNAT.Perfect_Hash_Generators.Insert (Word);
end if;
end Read_Keyword;
-- ------------------------------
-- Given a package name, return the file name that correspond.
-- ------------------------------
function To_File_Name (Name : in String) return String is
Result : String (Name'Range);
begin
for J in Name'Range loop
if Name (J) in 'A' .. 'Z' then
Result (J) := Character'Val (Character'Pos (Name (J))
- Character'Pos ('A')
+ Character'Pos ('a'));
elsif Name (J) = '.' then
Result (J) := '-';
else
Result (J) := Name (J);
end if;
end loop;
return Result;
end To_File_Name;
begin
-- Initialization is optional. Get the log configuration by reading the property
-- file 'samples/log4j.properties'. The 'log.util' logger will use a DEBUG level
-- and write the message in 'result.log'.
Util.Log.Loggers.Initialize ("samples/log4j.properties");
loop
case Getopt ("h i p: package: help") is
when ASCII.NUL =>
exit;
when 'i' =>
Ignore_Case := True;
when 'p' =>
Pkg_Name := To_Unbounded_String (Parameter);
when others =>
raise GNAT.Command_Line.Invalid_Switch;
end case;
end loop;
declare
Keywords : constant String := Get_Argument;
Pkg : constant String := To_String (Pkg_Name);
Count : Natural := 0;
K_2_V : Float;
V : Natural;
Seed : constant Natural := 4321; -- Needed by the hash algorithm
begin
-- Read the keywords.
Util.Files.Read_File (Path => Keywords, Process => Read_Keyword'Access);
Count := Natural (Names.Length);
if Count = 0 then
Log.Error ("There is no keyword.");
Ada.Command_Line.Set_Exit_Status (1);
return;
end if;
-- Generate the perfect hash package.
V := 2 * Count + 1;
loop
K_2_V := Float (V) / Float (Count);
GNAT.Perfect_Hash_Generators.Initialize (Seed, K_2_V);
begin
GNAT.Perfect_Hash_Generators.Compute;
exit;
exception
when GNAT.Perfect_Hash_Generators.Too_Many_Tries =>
V := V + 1;
end;
end loop;
GNAT.Perfect_Hash_Generators.Produce (Pkg);
-- Override what GNAT generates to have a list of keywords and other operations.
Generate_Specs (Pkg);
Generate_Body (Pkg);
end;
exception
when GNAT.Command_Line.Invalid_Switch =>
Log.Error ("Usage: gperfhash -i -p package keyword-file");
end Gperfhash;
|
-----------------------------------------------------------------------
-- gperfhash -- Perfect hash Ada generator
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Strings.Unbounded;
with Ada.Strings.Fixed;
with Ada.IO_Exceptions;
with Ada.Command_Line;
with GNAT.Command_Line;
with GNAT.Perfect_Hash_Generators;
with Util.Log.Loggers;
with Util.Files;
with Util.Strings.Vectors;
with Util.Strings.Transforms;
-- This simple utility is an Ada perfect hash generator. Given a fixed set of keywords,
-- it generates an Ada package (spec and body) which provides a perfect hash function.
-- The perfect hash algorithm is in fact provided by GNAT Perfect_Hash_Generators package.
--
-- Usage: gperfhash [-i] [-p package] keyword-file
--
-- -i Generate a perfect hash which ignores the case
-- -p package Use <b>package</b> as the name of package (default is <b>gphash</b>)
-- keyword-file The file which contains the keywords, one keyword on each line
procedure Gperfhash is
use Util.Log.Loggers;
use Ada.Strings.Unbounded;
use GNAT.Command_Line;
use Ada.Text_IO;
-- Read a keyword and add it in the keyword list.
procedure Read_Keyword (Line : in String);
-- Given a package name, return the file name that correspond.
function To_File_Name (Name : in String) return String;
procedure Generate_Keyword_Table (Into : in out Ada.Text_IO.File_Type);
-- Generate the package specification.
procedure Generate_Specs (Name : in String);
-- Generate the package body.
procedure Generate_Body (Name : in String);
Log : constant Logger := Create ("log", "samples/log4j.properties");
Pkg_Name : Unbounded_String := To_Unbounded_String ("gphash");
Names : Util.Strings.Vectors.Vector;
-- When true, generate a perfect hash which ignores the case.
Ignore_Case : Boolean := False;
-- ------------------------------
-- Generate the keyword table.
-- ------------------------------
procedure Generate_Keyword_Table (Into : in out Ada.Text_IO.File_Type) is
Index : Integer := 0;
procedure Print_Keyword (Pos : in Util.Strings.Vectors.Cursor);
procedure Print_Table (Pos : in Util.Strings.Vectors.Cursor);
-- ------------------------------
-- Print a keyword as an Ada constant string.
-- ------------------------------
procedure Print_Keyword (Pos : in Util.Strings.Vectors.Cursor) is
Name : constant String := Util.Strings.Vectors.Element (Pos);
begin
Put (Into, " K_");
Put (Into, Util.Strings.Image (Index));
Set_Col (Into, 20);
Put (Into, ": aliased constant String := """);
Put (Into, Name);
Put_Line (Into, """;");
Index := Index + 1;
end Print_Keyword;
-- ------------------------------
-- Build the keyword table.
-- ------------------------------
procedure Print_Table (Pos : in Util.Strings.Vectors.Cursor) is
pragma Unreferenced (Pos);
begin
if Index > 0 then
if Index mod 4 = 0 then
Put_Line (Into, ",");
Put (Into, " ");
else
Put (Into, ", ");
end if;
end if;
Put (Into, "K_");
Put (Into, Util.Strings.Image (Index));
Put (Into, "'Access");
Index := Index + 1;
end Print_Table;
begin
New_Line (Into);
Put_Line (Into, " type Name_Access is access constant String;");
Put_Line (Into, " type Keyword_Array is array (Natural range <>) of Name_Access;");
Put_Line (Into, " Keywords : constant Keyword_Array;");
Put_Line (Into, "private");
New_Line (Into);
Names.Iterate (Print_Keyword'Access);
New_Line (Into);
Index := 0;
Put_Line (Into, " Keywords : constant Keyword_Array := (");
Put (Into, " ");
Names.Iterate (Print_Table'Access);
Put_Line (Into, ");");
end Generate_Keyword_Table;
-- ------------------------------
-- Generate the package specification.
-- ------------------------------
procedure Generate_Specs (Name : in String) is
File : Ada.Text_IO.File_Type;
Path : constant String := To_File_Name (Name) & ".ads";
begin
Ada.Text_IO.Open (File => File,
Mode => Ada.Text_IO.Out_File,
Name => Path);
Put_Line (File, "-- Generated by gperfhash");
Put (File, "package ");
Put (File, To_String (Pkg_Name));
Put_Line (File, " is");
New_Line (File);
Put_Line (File, " function Hash (S : String) return Natural;");
New_Line (File);
Put_Line (File, " -- Returns true if the string <b>S</b> is a keyword.");
Put_Line (File, " function Is_Keyword (S : in String) return Boolean;");
Generate_Keyword_Table (File);
Put (File, "end ");
Put (File, To_String (Pkg_Name));
Put (File, ";");
New_Line (File);
Close (File);
end Generate_Specs;
-- ------------------------------
-- Generate the package body.
-- ------------------------------
procedure Generate_Body (Name : in String) is
-- Read the generated body file.
procedure Read_Body (Line : in String);
-- Re-generate the char position table to ignore the case.
procedure Generate_Char_Position;
Path : constant String := To_File_Name (Name) & ".adb";
File : Ada.Text_IO.File_Type;
Count : Natural;
Lines : Util.Strings.Vectors.Vector;
-- ------------------------------
-- Read the generated body file.
-- ------------------------------
procedure Read_Body (Line : in String) is
begin
Lines.Append (Line);
end Read_Body;
-- ------------------------------
-- Re-generate the char position table to ignore the case.
-- ------------------------------
procedure Generate_Char_Position is
use GNAT.Perfect_Hash_Generators;
V : Natural;
begin
Put (File, " (");
for I in 0 .. 255 loop
if I >= Character'Pos ('a') and I <= Character'Pos ('z') then
V := Value (Used_Character_Set, I - Character'Pos ('a') + Character'Pos ('A'));
else
V := GNAT.Perfect_Hash_Generators.Value (Used_Character_Set, I);
end if;
if I > 0 then
if I mod 16 = 0 then
Put_Line (File, ",");
Put (File, " ");
else
Put (File, ", ");
end if;
end if;
Put (File, Util.Strings.Image (V));
end loop;
Put_Line (File, ");");
end Generate_Char_Position;
begin
Util.Files.Read_File (Path => Path, Process => Read_Body'Access);
Count := Natural (Lines.Length);
Ada.Text_IO.Open (File => File,
Mode => Ada.Text_IO.Out_File,
Name => Path);
Put_Line (File, "-- Generated by gperfhash");
if Ignore_Case then
Put_Line (File, "with Util.Strings.Transforms;");
end if;
for I in 1 .. Count loop
declare
L : constant String := Lines.Element (I);
begin
-- Replace the char position table by ours. The lower case letter are just
-- mapped to the corresponding upper case letter.
if Ignore_Case and I >= 6 and I <= 16 then
if I = 6 then
Generate_Char_Position;
end if;
else
Put_Line (File, L);
end if;
-- Generate the Is_Keyword function before the package end.
if I = Count - 1 then
Put_Line (File, " -- Returns true if the string <b>S</b> is a keyword.");
Put_Line (File, " function Is_Keyword (S : in String) return Boolean is");
Put_Line (File, " H : constant Natural := Hash (S);");
Put_Line (File, " begin");
if Ignore_Case then
Put_Line (File, " return Keywords (H).all = "
& "Util.Strings.Transforms.To_Upper_Case (S);");
else
Put_Line (File, " return Keywords (H).all = S;");
end if;
Put_Line (File, " end Is_Keyword;");
end if;
end;
end loop;
Close (File);
end Generate_Body;
-- ------------------------------
-- Read a keyword and add it in the keyword list.
-- ------------------------------
procedure Read_Keyword (Line : in String) is
use Ada.Strings;
Word : String := Fixed.Trim (Line, Both);
begin
if Word'Length > 0 then
if Ignore_Case then
Word := Util.Strings.Transforms.To_Upper_Case (Word);
end if;
Names.Append (Word);
GNAT.Perfect_Hash_Generators.Insert (Word);
end if;
end Read_Keyword;
-- ------------------------------
-- Given a package name, return the file name that correspond.
-- ------------------------------
function To_File_Name (Name : in String) return String is
Result : String (Name'Range);
begin
for J in Name'Range loop
if Name (J) in 'A' .. 'Z' then
Result (J) := Character'Val (Character'Pos (Name (J))
- Character'Pos ('A')
+ Character'Pos ('a'));
elsif Name (J) = '.' then
Result (J) := '-';
else
Result (J) := Name (J);
end if;
end loop;
return Result;
end To_File_Name;
begin
-- Initialization is optional. Get the log configuration by reading the property
-- file 'samples/log4j.properties'. The 'log.util' logger will use a DEBUG level
-- and write the message in 'result.log'.
Util.Log.Loggers.Initialize ("samples/log4j.properties");
loop
case Getopt ("h i p: package: help") is
when ASCII.NUL =>
exit;
when 'i' =>
Ignore_Case := True;
when 'p' =>
Pkg_Name := To_Unbounded_String (Parameter);
when others =>
raise GNAT.Command_Line.Invalid_Switch;
end case;
end loop;
declare
Keywords : constant String := Get_Argument;
Pkg : constant String := To_String (Pkg_Name);
Count : Natural := 0;
K_2_V : Float;
V : Natural;
Seed : constant Natural := 4321; -- Needed by the hash algorithm
begin
-- Read the keywords.
Util.Files.Read_File (Path => Keywords, Process => Read_Keyword'Access);
Count := Natural (Names.Length);
if Count = 0 then
Log.Error ("There is no keyword.");
raise GNAT.Command_Line.Invalid_Switch;
end if;
-- Generate the perfect hash package.
V := 2 * Count + 1;
loop
K_2_V := Float (V) / Float (Count);
GNAT.Perfect_Hash_Generators.Initialize (Seed, K_2_V);
begin
GNAT.Perfect_Hash_Generators.Compute;
exit;
exception
when GNAT.Perfect_Hash_Generators.Too_Many_Tries =>
V := V + 1;
end;
end loop;
GNAT.Perfect_Hash_Generators.Produce (Pkg);
-- Override what GNAT generates to have a list of keywords and other operations.
Generate_Specs (Pkg);
Generate_Body (Pkg);
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot read the keyword file.");
Ada.Command_Line.Set_Exit_Status (1);
end;
exception
when GNAT.Command_Line.Invalid_Switch =>
Log.Error ("Usage: gperfhash -i -p package keyword-file");
Log.Error ("-i Generate a perfect hash which ignores the case");
Log.Error ("-p package Use 'package' as the name of package (default is 'gphash')");
Log.Error ("keyword-file The file which contains the keywords, one keyword on each line");
Ada.Command_Line.Set_Exit_Status (1);
end Gperfhash;
|
Add some error messages
|
Add some error messages
|
Ada
|
apache-2.0
|
Letractively/ada-util,flottokarotto/ada-util,Letractively/ada-util,flottokarotto/ada-util
|
5047bbc561be5862180b1931978295d2e85dfad0
|
src/asis/a4g-a_elists.adb
|
src/asis/a4g-a_elists.adb
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . A _ E L I S T S --
-- --
-- B o d y --
-- --
-- Copyright (C) 1995-2007, Free Software Foundation, Inc. --
-- --
-- ASIS-for-GNAT is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 2, or (at your option) any later --
-- version. ASIS-for-GNAT is distributed in the hope that it will be use- --
-- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- --
-- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General --
-- Public License for more details. You should have received a copy of the --
-- GNU General Public License distributed with ASIS-for-GNAT; see file --
-- COPYING. If not, write to the Free Software Foundation, 51 Franklin --
-- Street, Fifth Floor, Boston, MA 02110-1301, USA. --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the --
-- Software Engineering Laboratory of the Swiss Federal Institute of --
-- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the --
-- Scientific Research Computer Center of Moscow State University (SRCC --
-- MSU), Russia, with funding partially provided by grants from the Swiss --
-- National Science Foundation and the Swiss Academy of Engineering --
-- Sciences. ASIS-for-GNAT is now maintained by AdaCore --
-- (http://www.adaccore.com). --
-- --
------------------------------------------------------------------------------
-- This is the modification of the GNAT Elists package. See spec for the
-- description of the modifications.
with A4G.A_Debug; use A4G.A_Debug;
with Output; use Output;
package body A4G.A_Elists is
----------------------
-- Add_To_Elmt_List --
----------------------
procedure Add_To_Elmt_List (Unit : Unit_Id; List : in out Elist_Id) is
begin
if No (List) then
List := New_Elmt_List;
Append_Elmt (Unit, List);
elsif not In_Elmt_List (Unit, List) then
Append_Elmt (Unit, List);
end if;
end Add_To_Elmt_List;
-----------------
-- Append_Elmt --
-----------------
procedure Append_Elmt (Unit : Unit_Id; To : Elist_Id) is
L : constant Elmt_Id := Elists.Table (To).Last;
begin
Elmts.Increment_Last;
Elmts.Table (Elmts.Last).Unit := Unit;
Elmts.Table (Elmts.Last).Next := Union_Id (To);
if L = No_Elmt then
Elists.Table (To).First := Elmts.Last;
else
Elmts.Table (L).Next := Union_Id (Elmts.Last);
end if;
Elists.Table (To).Last := Elmts.Last;
if Debug_Flag_N then
Write_Str ("Append new element Elmt_Id = ");
Write_Int (Int (Elmts.Last));
Write_Str (" to list Elist_Id = ");
Write_Int (Int (To));
Write_Str (" referencing Unit_Id = ");
Write_Int (Int (Unit));
Write_Eol;
end if;
end Append_Elmt;
------------------
-- Prepend_Elmt --
------------------
procedure Prepend_Elmt (Unit : Unit_Id; To : Elist_Id) is
F : constant Elmt_Id := Elists.Table (To).First;
begin
Elmts.Increment_Last;
Elmts.Table (Elmts.Last).Unit := Unit;
if F = No_Elmt then
Elists.Table (To).Last := Elmts.Last;
Elmts.Table (Elmts.Last).Next := Union_Id (To);
else
Elmts.Table (Elmts.Last).Next := Union_Id (F);
end if;
Elists.Table (To).First := Elmts.Last;
end Prepend_Elmt;
-----------------------
-- Insert_Elmt_After --
-----------------------
procedure Insert_Elmt_After (Unit : Unit_Id; Elmt : Elmt_Id) is
N : constant Union_Id := Elmts.Table (Elmt).Next;
begin
pragma Assert (Elmt /= No_Elmt);
Elmts.Increment_Last;
Elmts.Table (Elmts.Last).Unit := Unit;
Elmts.Table (Elmts.Last).Next := N;
Elmts.Table (Elmt).Next := Union_Id (Elmts.Last);
if N in Elist_Range then
Elists.Table (Elist_Id (N)).Last := Elmts.Last;
end if;
end Insert_Elmt_After;
-------------
-- Belongs --
-------------
function Belongs (List1 : Elist_Id; List2 : Elist_Id) return Boolean is
Curr_Elmt : Elmt_Id;
begin
if No (List1) or else Is_Empty_Elmt_List (List1) then
return True;
end if;
Curr_Elmt := First_Elmt (List1);
while Present (Curr_Elmt) loop
if not In_Elmt_List (Unit (Curr_Elmt), List2) then
return False;
end if;
Curr_Elmt := Next_Elmt (Curr_Elmt);
end loop;
return True;
end Belongs;
----------------
-- First_Elmt --
----------------
function First_Elmt (List : Elist_Id) return Elmt_Id is
begin
pragma Assert (List > Elist_Low_Bound);
return Elists.Table (List).First;
end First_Elmt;
----------------
-- Initialize --
----------------
procedure Initialize is
begin
Elists.Init;
Elmts.Init;
end Initialize;
------------------
-- In_Elmt_List --
------------------
function In_Elmt_List (U : Unit_Id; List : Elist_Id) return Boolean is
Curr_Elmt : Elmt_Id;
begin
if No (List) or else Is_Empty_Elmt_List (List) then
return False;
end if;
Curr_Elmt := First_Elmt (List);
while Present (Curr_Elmt) loop
if U = Unit (Curr_Elmt) then
return True;
end if;
Curr_Elmt := Next_Elmt (Curr_Elmt);
end loop;
return False;
end In_Elmt_List;
---------------
-- Intersect --
---------------
function Intersect (List1 : Elist_Id; List2 : Elist_Id) return Boolean is
Curr_Elmt : Elmt_Id;
begin
if No (List1) or else No (List2) or else
Is_Empty_Elmt_List (List1) or else
Is_Empty_Elmt_List (List2)
then
return False;
else
Curr_Elmt := First_Elmt (List1);
while Present (Curr_Elmt) loop
if In_Elmt_List (Unit (Curr_Elmt), List2) then
return True;
end if;
Curr_Elmt := Next_Elmt (Curr_Elmt);
end loop;
return False;
end if;
end Intersect;
------------------------
-- Is_Empty_Elmt_List --
------------------------
function Is_Empty_Elmt_List (List : Elist_Id) return Boolean is
begin
return Elists.Table (List).First = No_Elmt;
end Is_Empty_Elmt_List;
-------------------
-- Last_Elist_Id --
-------------------
function Last_Elist_Id return Elist_Id is
begin
return Elists.Last;
end Last_Elist_Id;
---------------
-- Last_Elmt --
---------------
function Last_Elmt (List : Elist_Id) return Elmt_Id is
begin
return Elists.Table (List).Last;
end Last_Elmt;
------------------
-- Last_Elmt_Id --
------------------
function Last_Elmt_Id return Elmt_Id is
begin
return Elmts.Last;
end Last_Elmt_Id;
-----------------
-- List_Length --
-----------------
function List_Length (List : Elist_Id) return Natural is
Result : Natural := 0;
Elem : Elmt_Id;
begin
Elem := First_Elmt (List);
while Present (Elem) loop
Result := Result + 1;
Elem := Next_Elmt (Elem);
end loop;
return Result;
end List_Length;
---------------
-- Move_List --
---------------
procedure Move_List
(List_From : Elist_Id;
List_To : in out Elist_Id)
is
begin
if No (List_To) then
List_To := New_Elmt_List;
end if;
if No (List_From) or else Is_Empty_Elmt_List (List_From) then
return;
end if;
-- if we are here, we have to move elements...
if Is_Empty_Elmt_List (List_To) then
Elists.Table (List_To).Last := Elists.Table (List_From).Last;
Elmts.Table (Elists.Table (List_From).Last).Next :=
Union_Id (List_To);
else
Elmts.Table (Elists.Table (List_From).Last).Next :=
Elmts.Table (Elists.Table (List_To).First).Next;
end if;
Elists.Table (List_To).First := Elists.Table (List_From).First;
Elists.Table (List_From).First := No_Elmt;
Elists.Table (List_From).Last := No_Elmt;
end Move_List;
-------------------
-- New_Elmt_List --
-------------------
function New_Elmt_List return Elist_Id is
begin
Elists.Increment_Last;
Elists.Table (Elists.Last).First := No_Elmt;
Elists.Table (Elists.Last).Last := No_Elmt;
if Debug_Flag_N then
Write_Str ("Allocate new element list, returned ID = ");
Write_Int (Int (Elists.Last));
Write_Eol;
end if;
return Elists.Last;
end New_Elmt_List;
---------------
-- Next_Elmt --
---------------
function Next_Elmt (Elmt : Elmt_Id) return Elmt_Id is
N : constant Union_Id := Elmts.Table (Elmt).Next;
begin
if N in Elist_Range then
return No_Elmt;
else
return Elmt_Id (N);
end if;
end Next_Elmt;
--------
-- No --
--------
function No (List : Elist_Id) return Boolean is
begin
return List = No_Elist;
end No;
function No (Elmt : Elmt_Id) return Boolean is
begin
return Elmt = No_Elmt;
end No;
-----------
-- Unit --
-----------
function Unit (Elmt : Elmt_Id) return Unit_Id is
begin
if Elmt = No_Elmt then
return Nil_Unit;
else
return Elmts.Table (Elmt).Unit;
end if;
end Unit;
----------------
-- Num_Elists --
----------------
function Num_Elists return Nat is
begin
return Int (Elmts.Last) - Int (Elmts.First) + 1;
end Num_Elists;
-------------
-- Present --
-------------
function Present (List : Elist_Id) return Boolean is
begin
return List /= No_Elist;
end Present;
function Present (Elmt : Elmt_Id) return Boolean is
begin
return Elmt /= No_Elmt;
end Present;
----------------
-- Print_List --
----------------
procedure Print_List (List : Elist_Id) is
Curr_Elmt : Elmt_Id;
Counter : Int := 1;
begin
if No (List) then
if Debug_Flag_N then
Write_Str (" There is no list here");
Write_Eol;
end if;
return;
end if;
if Is_Empty_Elmt_List (List) then
if Debug_Flag_N then
Write_Str (" The list is empty");
Write_Eol;
end if;
return;
end if;
if Debug_Flag_N then
Write_Str ("List contains the following Ids:");
Write_Eol;
end if;
Curr_Elmt := First_Elmt (List);
while Present (Curr_Elmt) loop
if Debug_Flag_N then
Write_Str (" Element number ");
Write_Int (Counter);
Write_Str (" is ");
Write_Int (Int (Unit (Curr_Elmt)));
Write_Eol;
end if;
Curr_Elmt := Next_Elmt (Curr_Elmt);
Counter := Counter + 1;
end loop;
end Print_List;
-----------------
-- Remove_Elmt --
-----------------
procedure Remove_Elmt (List : Elist_Id; Elmt : Elmt_Id) is
Nxt : Elmt_Id;
Prv : Elmt_Id;
begin
Nxt := Elists.Table (List).First;
-- Case of removing only element in the list
if Elmts.Table (Nxt).Next in Elist_Range then
pragma Assert (Nxt = Elmt);
Elists.Table (List).First := No_Elmt;
Elists.Table (List).Last := No_Elmt;
-- Case of removing the first element in the list
elsif Nxt = Elmt then
Elists.Table (List).First := Elmt_Id (Elmts.Table (Nxt).Next);
-- Case of removing second or later element in the list
else
loop
Prv := Nxt;
Nxt := Elmt_Id (Elmts.Table (Prv).Next);
exit when Nxt = Elmt
or else Elmts.Table (Nxt).Next in Elist_Range;
end loop;
pragma Assert (Nxt = Elmt);
Elmts.Table (Prv).Next := Elmts.Table (Nxt).Next;
if Elmts.Table (Prv).Next in Elist_Range then
Elists.Table (List).Last := Prv;
end if;
end if;
end Remove_Elmt;
----------------------
-- Remove_Last_Elmt --
----------------------
procedure Remove_Last_Elmt (List : Elist_Id) is
Nxt : Elmt_Id;
Prv : Elmt_Id;
begin
Nxt := Elists.Table (List).First;
-- Case of removing only element in the list
if Elmts.Table (Nxt).Next in Elist_Range then
Elists.Table (List).First := No_Elmt;
Elists.Table (List).Last := No_Elmt;
-- Case of at least two elements in list
else
loop
Prv := Nxt;
Nxt := Elmt_Id (Elmts.Table (Prv).Next);
exit when Elmts.Table (Nxt).Next in Elist_Range;
end loop;
Elmts.Table (Prv).Next := Elmts.Table (Nxt).Next;
Elists.Table (List).Last := Prv;
end if;
end Remove_Last_Elmt;
------------------
-- Replace_Elmt --
------------------
procedure Replace_Elmt (Elmt : Elmt_Id; New_Unit : Unit_Id) is
begin
Elmts.Table (Elmt).Unit := New_Unit;
end Replace_Elmt;
end A4G.A_Elists;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
50de5a614a152589b457a88224bf42ff84339061
|
mat/src/mat-readers-streams.adb
|
mat/src/mat-readers-streams.adb
|
-----------------------------------------------------------------------
-- mat-readers-streams -- Reader for streams
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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.Stream_IO;
with Util.Log.Loggers;
with MAT.Readers.Marshaller;
package body MAT.Readers.Streams is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Files");
BUFFER_SIZE : constant Natural := 100 * 1024;
MAX_MSG_SIZE : constant Ada.Streams.Stream_Element_Offset := 2048;
-- ------------------------------
-- Read the events from the stream and stop when the end of the stream is reached.
-- ------------------------------
procedure Read_All (Reader : in out Stream_Reader_Type) is
use Ada.Streams;
use type MAT.Types.Uint8;
Data : aliased Ada.Streams.Stream_Element_Array (0 .. MAX_MSG_SIZE);
Buffer : aliased Buffer_Type;
Msg : Message;
Last : Ada.Streams.Stream_Element_Offset;
Format : MAT.Types.Uint8;
begin
Msg.Buffer := Buffer'Unchecked_Access;
Msg.Buffer.Start := Data (0)'Address;
Msg.Buffer.Current := Msg.Buffer.Start;
Msg.Buffer.Last := Data (MAX_MSG_SIZE)'Address;
Msg.Buffer.Size := 3;
Reader.Stream.Read (Data (0 .. 2), Last);
Format := MAT.Readers.Marshaller.Get_Uint8 (Msg.Buffer);
if Format = 0 then
Msg.Buffer.Endian := LITTLE_ENDIAN;
Log.Debug ("Data stream is little endian");
else
Msg.Buffer.Endian := BIG_ENDIAN;
Log.Debug ("Data stream is big endian");
end if;
Msg.Size := Natural (MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer));
if Msg.Size < 2 then
Log.Error ("Invalid message size {0}", Natural'Image (Msg.Size));
end if;
Reader.Stream.Read (Data (0 .. Ada.Streams.Stream_Element_Offset (Msg.Size - 1)), Last);
Msg.Buffer.Current := Msg.Buffer.Start;
Msg.Buffer.Last := Data (Last)'Address;
Msg.Buffer.Size := Msg.Size;
Reader.Read_Headers (Msg);
while not Reader.Stream.Is_Eof loop
Reader.Stream.Read (Data (0 .. 1), Last);
exit when Last /= 2;
Msg.Buffer.Size := 2;
Msg.Buffer.Current := Msg.Buffer.Start;
Msg.Size := Natural (MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer));
if Msg.Size < 2 then
Log.Error ("Invalid message size {0}", Natural'Image (Msg.Size));
end if;
if Ada.Streams.Stream_Element_Offset (Msg.Size) >= Data'Last then
Log.Error ("Message size {0} is too big", Natural'Image (Msg.Size));
exit;
end if;
Reader.Stream.Read (Data (0 .. Ada.Streams.Stream_Element_Offset (Msg.Size - 1)), Last);
Msg.Buffer.Current := Msg.Buffer.Start;
Msg.Buffer.Last := Data (Last)'Address;
Msg.Buffer.Size := Msg.Size;
Reader.Dispatch_Message (Msg);
end loop;
end Read_All;
end MAT.Readers.Streams;
|
Implement the Read_All operation
|
Implement the Read_All operation
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
|
e03cfa779b2b0ae32ee0ba3a04a0bd0d9001970e
|
src/asis/a4g-asis_tables.adb
|
src/asis/a4g-asis_tables.adb
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . A S I S _ T A B L E S --
-- --
-- B o d y --
-- --
-- Copyright (C) 1995-2009, Free Software Foundation, Inc. --
-- --
-- ASIS-for-GNAT is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 2, or (at your option) any later --
-- version. ASIS-for-GNAT is distributed in the hope that it will be use- --
-- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- --
-- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General --
-- Public License for more details. You should have received a copy of the --
-- GNU General Public License distributed with ASIS-for-GNAT; see file --
-- COPYING. If not, write to the Free Software Foundation, 51 Franklin --
-- Street, Fifth Floor, Boston, MA 02110-1301, USA. --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the --
-- Software Engineering Laboratory of the Swiss Federal Institute of --
-- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the --
-- Scientific Research Computer Center of Moscow State University (SRCC --
-- MSU), Russia, with funding partially provided by grants from the Swiss --
-- National Science Foundation and the Swiss Academy of Engineering --
-- Sciences. ASIS-for-GNAT is now maintained by AdaCore --
-- (http://www.adacore.com). --
-- --
------------------------------------------------------------------------------
with Asis.Elements; use Asis.Elements;
with Atree; use Atree;
with Sinput; use Sinput;
with Einfo; use Einfo;
with Nlists; use Nlists;
package body A4G.Asis_Tables is
---------------------
-- Add_New_Element --
---------------------
procedure Add_New_Element (Element : Asis.Element) is
Found : Boolean := False;
begin
for J in 1 .. Asis_Element_Table.Last loop
if Is_Equal (Element, Asis_Element_Table.Table (J)) then
Found := True;
exit;
end if;
end loop;
if not Found then
Asis_Element_Table.Append (Element);
end if;
end Add_New_Element;
-----------------------
-- Create_Node_Trace --
-----------------------
procedure Create_Node_Trace (N : Node_Id) is
Next_Node : Node_Id;
Next_Sloc : Source_Ptr;
Next_Node_Rec : Node_Trace_Rec;
begin
Node_Trace.Init;
Next_Node := N;
while Present (Next_Node) loop
Next_Sloc := Sloc (Next_Node);
Next_Node_Rec.Kind := Nkind (Next_Node);
Next_Node_Rec.Node_Line := Get_Physical_Line_Number (Next_Sloc);
Next_Node_Rec.Node_Col := Get_Column_Number (Next_Sloc);
Node_Trace.Append (Next_Node_Rec);
Next_Node := Enclosing_Scope (Next_Node);
end loop;
end Create_Node_Trace;
---------------------
-- Enclosing_Scope --
---------------------
function Enclosing_Scope (N : Node_Id) return Node_Id is
Result : Node_Id := N;
Entity_Node : Entity_Id := Empty;
begin
if Nkind (Result) = N_Package_Declaration then
Entity_Node := Defining_Unit_Name (Sinfo.Specification (Result));
elsif Nkind (Result) = N_Package_Body then
Entity_Node := Defining_Unit_Name (Result);
end if;
if Nkind (Entity_Node) = N_Defining_Program_Unit_Name then
Entity_Node := Sinfo.Defining_Identifier (Entity_Node);
end if;
if Present (Entity_Node) and then
Is_Generic_Instance (Entity_Node)
then
-- going to the corresponding instantiation
if Nkind (Parent (Result)) = N_Compilation_Unit then
-- We are at the top/ and we do not need a library-level
-- instantiation - it is always unique in the compilation
-- unit
Result := Empty;
else
-- "local" instantiation, therefore - one or two steps down the
-- declaration list to get in the instantiation node:
Result := Next_Non_Pragma (Result);
if Nkind (Result) = N_Package_Body then
-- This is an expanded generic body
Result := Next_Non_Pragma (Result);
end if;
end if;
else
-- One step up to the enclosing scope
Result := Parent (Result);
while not (Nkind (Result) = N_Package_Specification or else
Nkind (Result) = N_Package_Body or else
Nkind (Result) = N_Compilation_Unit or else
Nkind (Result) = N_Subprogram_Body or else
Nkind (Result) = N_Block_Statement)
loop
Result := Parent (Result);
end loop;
if Nkind (Result) = N_Package_Specification then
Result := Parent (Result);
elsif Nkind (Result) = N_Compilation_Unit then
Result := Empty;
end if;
end if;
return Result;
end Enclosing_Scope;
--------------
-- Is_Equal --
--------------
function Is_Equal
(N : Node_Id;
Trace_Rec : Node_Trace_Rec)
return Boolean
is
begin
return Nkind (N) = Trace_Rec.Kind and then
Get_Physical_Line_Number (Sloc (N)) = Trace_Rec.Node_Line and then
Get_Column_Number (Sloc (N)) = Trace_Rec.Node_Col;
end Is_Equal;
end A4G.Asis_Tables;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
|
8701f675c1689a385f8b3d49f0609dc5a61959c2
|
awa/plugins/awa-wikis/src/awa-wikis-modules.adb
|
awa/plugins/awa-wikis/src/awa-wikis-modules.adb
|
-----------------------------------------------------------------------
-- awa-wikis-modules -- Module wikis
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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 AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with AWA.Modules.Get;
with AWA.Permissions;
with AWA.Permissions.Services;
with AWA.Wikis.Beans;
with AWA.Modules.Beans;
with ADO.Sessions;
with Util.Log.Loggers;
package body AWA.Wikis.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Wikis.Module");
package Register is new AWA.Modules.Beans (Module => Wiki_Module,
Module_Access => Wiki_Module_Access);
-- ------------------------------
-- Initialize the wikis module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Wiki_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the wikis module");
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_Space_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_Space_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the wikis module.
-- ------------------------------
function Get_Wiki_Module return Wiki_Module_Access is
function Get is new AWA.Modules.Get (Wiki_Module, Wiki_Module_Access, NAME);
begin
return Get;
end Get_Wiki_Module;
-- ------------------------------
-- Create the wiki space.
-- ------------------------------
procedure Create_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class) is
pragma Unreferenced (Module);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
Log.Info ("Creating new wiki space {0}", String '(Wiki.Get_Name));
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS);
-- Check that the user has the create permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Wiki_Space.Permission,
Entity => WS);
Wiki.Set_Workspace (WS);
Wiki.Save (DB);
-- Add the permission for the user to use the new wiki space.
AWA.Permissions.Services.Add_Permission (Session => DB,
User => User,
Entity => Wiki);
Ctx.Commit;
Log.Info ("Wiki {0} created for user {1}",
ADO.Identifier'Image (Wiki.Get_Id), ADO.Identifier'Image (User));
end Create_Wiki_Space;
-- ------------------------------
-- Save the wiki space.
-- ------------------------------
procedure Save_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Log.Info ("Updating wiki space {0}", String '(Wiki.Get_Name));
Ctx.Start;
-- Check that the user has the update permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Update_Wiki_Space.Permission,
Entity => Wiki);
Wiki.Save (DB);
Ctx.Commit;
end Save_Wiki_Space;
-- ------------------------------
-- Load the wiki space.
-- ------------------------------
procedure Load_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class;
Id : in ADO.Identifier) is
pragma Unreferenced (Module);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
begin
Wiki.Load (DB, Id, Found);
end Load_Wiki_Space;
-- ------------------------------
-- Create the wiki page into the wiki space.
-- ------------------------------
procedure Create_Wiki_Page (Model : in Wiki_Module;
Into : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page : in out Awa.Wikis.Models.Wiki_Page_Ref'Class) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Log.Info ("Create wiki page {0}", String '(Page.Get_Name));
-- Check that the user has the create wiki page permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Create_Wiki_Pages.Permission,
Entity => Into);
Ctx.Start;
Page.Set_Is_Public (Into.Get_Is_Public);
Page.Set_Wiki (Into);
Page.Save (DB);
Ctx.Commit;
end Create_Wiki_Page;
-- ------------------------------
-- Save the wiki page.
-- ------------------------------
procedure Save (Model : in Wiki_Module;
Page : in out Awa.Wikis.Models.Wiki_Page_Ref'Class) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
-- Check that the user has the create wiki page permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Update_Wiki_Pages.Permission,
Entity => Page);
Ctx.Start;
Page.Save (DB);
Ctx.Commit;
end Save;
end AWA.Wikis.Modules;
|
-----------------------------------------------------------------------
-- awa-wikis-modules -- Module wikis
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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 AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with AWA.Modules.Get;
with AWA.Permissions;
with AWA.Permissions.Services;
with AWA.Users.Models;
with AWA.Wikis.Beans;
with AWA.Modules.Beans;
with Ada.Calendar;
with ADO.Sessions;
with Util.Log.Loggers;
package body AWA.Wikis.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Wikis.Module");
package Register is new AWA.Modules.Beans (Module => Wiki_Module,
Module_Access => Wiki_Module_Access);
-- ------------------------------
-- Initialize the wikis module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Wiki_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the wikis module");
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_Space_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_Space_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the wikis module.
-- ------------------------------
function Get_Wiki_Module return Wiki_Module_Access is
function Get is new AWA.Modules.Get (Wiki_Module, Wiki_Module_Access, NAME);
begin
return Get;
end Get_Wiki_Module;
-- ------------------------------
-- Create the wiki space.
-- ------------------------------
procedure Create_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class) is
pragma Unreferenced (Module);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
Log.Info ("Creating new wiki space {0}", String '(Wiki.Get_Name));
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS);
-- Check that the user has the create permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Wiki_Space.Permission,
Entity => WS);
Wiki.Set_Workspace (WS);
Wiki.Save (DB);
-- Add the permission for the user to use the new wiki space.
AWA.Permissions.Services.Add_Permission (Session => DB,
User => User,
Entity => Wiki);
Ctx.Commit;
Log.Info ("Wiki {0} created for user {1}",
ADO.Identifier'Image (Wiki.Get_Id), ADO.Identifier'Image (User));
end Create_Wiki_Space;
-- ------------------------------
-- Save the wiki space.
-- ------------------------------
procedure Save_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Log.Info ("Updating wiki space {0}", String '(Wiki.Get_Name));
Ctx.Start;
-- Check that the user has the update permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Update_Wiki_Space.Permission,
Entity => Wiki);
Wiki.Save (DB);
Ctx.Commit;
end Save_Wiki_Space;
-- ------------------------------
-- Load the wiki space.
-- ------------------------------
procedure Load_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class;
Id : in ADO.Identifier) is
pragma Unreferenced (Module);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
begin
Wiki.Load (DB, Id, Found);
end Load_Wiki_Space;
-- ------------------------------
-- Create the wiki page into the wiki space.
-- ------------------------------
procedure Create_Wiki_Page (Model : in Wiki_Module;
Into : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page : in out Awa.Wikis.Models.Wiki_Page_Ref'Class) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Log.Info ("Create wiki page {0}", String '(Page.Get_Name));
-- Check that the user has the create wiki page permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Create_Wiki_Pages.Permission,
Entity => Into);
Ctx.Start;
Page.Set_Is_Public (Into.Get_Is_Public);
Page.Set_Wiki (Into);
Page.Save (DB);
Ctx.Commit;
end Create_Wiki_Page;
-- ------------------------------
-- Save the wiki page.
-- ------------------------------
procedure Save (Model : in Wiki_Module;
Page : in out Awa.Wikis.Models.Wiki_Page_Ref'Class) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
-- Check that the user has the create wiki page permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Update_Wiki_Pages.Permission,
Entity => Page);
Ctx.Start;
Page.Save (DB);
Ctx.Commit;
end Save;
-- ------------------------------
-- Create a new wiki content for the wiki page.
-- ------------------------------
procedure Create_Wiki_Content (Model : in Wiki_Module;
Page : in out Awa.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
User : AWA.Users.Models.User_Ref := Ctx.Get_User;
begin
-- Check that the user has the create wiki content permission on the given wiki page.
AWA.Permissions.Check (Permission => ACL_Update_Wiki_Pages.Permission,
Entity => Page);
Ctx.Start;
Content.Set_Page (Page);
Content.Set_Create_Date (Ada.Calendar.Clock);
Content.Set_Author (User);
Content.Save (DB);
Page.Set_Content (Content);
Page.Set_Last_Version (Page.Get_Last_Version + 1);
Page.Save (DB);
Ctx.Commit;
end Create_Wiki_Content;
end AWA.Wikis.Modules;
|
Implement the Create_Wiki_Content procedure
|
Implement the Create_Wiki_Content procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
eac7d5eaa87343c9ad3e64ad323b34f9ca44a519
|
src/asis/asis-compilation_units-relations.ads
|
src/asis/asis-compilation_units-relations.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT INTERFACE COMPONENTS --
-- --
-- A S I S . C O M P I L A T I O N _ U N I T S . R E L A T I O N S --
-- --
-- S p e c --
-- --
-- Copyright (c) 2006, Free Software Foundation, Inc. --
-- --
-- This specification is adapted from the Ada Semantic Interface --
-- Specification Standard (ISO/IEC 15291) 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. The copyright notice --
-- above, and the license provisions that follow apply solely to the --
-- contents of the part following the private keyword. --
-- --
-- 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). --
-- --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- 12 package Asis.Compilation_Units.Relations
------------------------------------------------------------------------------
------------------------------------------------------------------------------
package Asis.Compilation_Units.Relations is
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Asis.Compilation_Units.Relations encapsulates semantic relationship
-- concepts used in ASIS.
------------------------------------------------------------------------------
-- 12.1 type Relationship
------------------------------------------------------------------------------
-- Relationship queries provide references to compilation units that are
-- related, in some specific fashion, to one or more given compilation units.
-- Compilation units located by these queries are returned as a set of
-- ordered lists.
type Relationship
(Consistent_Length : Asis.ASIS_Natural;
Inconsistent_Length : Asis.ASIS_Natural;
Missing_Length : Asis.ASIS_Natural;
Circular_Length : Asis.ASIS_Natural)
is
record
Consistent : Asis.Compilation_Unit_List (1 .. Consistent_Length);
Inconsistent : Asis.Compilation_Unit_List (1 .. Inconsistent_Length);
Missing : Asis.Compilation_Unit_List (1 .. Missing_Length);
Circular : Asis.Compilation_Unit_List (1 .. Circular_Length);
end record;
-- The following describes the semantics of the unit lists returned by the
-- queries Semantic_Dependence_Order and Elaboration_Order:
--
-- Each query returns a set of four lists. Every unit returned will have the
-- same Enclosing_Context. The lists are:
--
-- a) (Consistent) A list of consistent ordered units.
-- b) (Inconsistent) A list of units that are inconsistent with one or
-- more units on which they semantically depend.
-- c) (Missing) A list of units that have missing (nonexistent) related
-- units.
-- d) (Circular) A list of circular semantic dependencies between units.
--
--
-- a) The consistent units list:
--
-- The semantics for the ordering of units in the first list are defined by
-- the individual queries.
--
-- Every unit in this list is unique. No duplicates are returned; no
-- two units in the list are Is_Equal or Is_Identical.
--
-- b) The inconsistent units list:
--
-- The second list is made up of unit pairs.
--
-- Each pairing defines an inconsistent semantic dependence relationship.
-- The right unit of each pair semantically depends on the preceding left
-- unit. All rightmost units of each pair are always inconsistent, and will
-- not appear in the consistent units list. The leftmost unit can be either
-- consistent or inconsistent. If a leftmost units is consistent, then it
-- also appears in the consistent units list; otherwise the unit is part of
-- an inconsistent transitive relationship.
--
-- The unit pairs are ordered such that there are no forward semantic
-- dependencies between the inconsistent units. Each inconsistent unit's
-- supporters always precede it in the list.
--
-- As an example, given four units, A withs B, B withs C, and C withs D;
-- if D is replaced, the inconsistent list contains six units with the
-- three pairs:
--
-- DC CB BA
--
-- The list indicates that units C, B, and A are inconsistent (the
-- rightmost units of each pair). Semantic dependencies such as B depends
-- on C also are indicated. The units C, B, and A are in an order that
-- could be submitted to the compiler (a possible recompilation order).
--
-- If a unit is inconsistent because the source for the unit has been
-- edited (or otherwise been made inconsistent by some action of the user
-- or implementation) then the unit references Nil_Compilation_Unit as the
-- cause of the inconsistency (e.g., (Nil A Nil B) is a list of two
-- inconsistent units, neither of which can point to a third unit as the
-- cause for their being inconsistent).
--
-- --|IP An implementation is allowed to use Nil_Compilation_Unit value for
-- --|IP the first unit of each pair if it cannot determine the supporting
-- --|IP unit causing the inconsistent semantic dependence.
--
-- For the above example, the list returned is:
--
-- DC DB DA CB CA BA
--
-- This list reports all dependencies:
--
-- D withed by C withed by B withed by A => DC DB DA
-- C withed by B withed by A => CB CA
-- B withed by A => BA
--
-- c) The missing dependence list:
--
-- The third list is made up of unit pairs. Each pairing consists of a
-- unit followed by a missing related unit needed by the first unit.
-- A missing unit is a required Compilation_Unit, with a known name, with a
-- Unit_Kind that is either A_Nonexistent_Declaration or
-- A_Nonexistent_Body.
--
-- For example:
--
-- Given a list containing the units: AB AC
--
-- If Unit_Kind(B) = A_Nonexistent_Declaration and
-- Unit_Kind(C) = A_Nonexistent_Body then
--
-- It can be deduced that:
-- A is missing a needed supporter B (A depends semantically on B).
-- A is missing a needed related unit body C
-- (depending on the kind for A, C can be A's required body or some
-- subunit of A)
--
-- A unit is reported as missing only if the Post-Compilation Rules of Ada
-- determine it to be needed. Reference Manual 10.2.
--
-- d) The circular dependence list:
--
-- Circular dependencies between compilation units are provided in the
-- fourth list. There may be more than one set of circular dependencies.
-- The ordering of distinct sets in the list is implementation-defined.
-- This list will never contain nonexistent units.
--
-- The list is made up of unit pairs. The second unit of each pair depends
-- semantically on the first unit. A circularity is established when the
-- first unit of a pair also appears as the second unit of a later pair.
-- (See the unit A in the example below; it is the first unit of the first
-- pair and is the second unit of the third pair). The next set of circular
-- dependent units, if any, starts with the next unit in the list (the unit
-- D in the example below).
--
-- For example:
--
-- Given a list containing the units: AC CB BA DG GF FE ED
--
-- It can be determined that there are two sets of circularly dependent
-- units:
-- {A, B, C} and {D, E, F, G}
--
-- The dependencies are: A depends on B, B depends on C, C depends on A.
-- D depends on E, E depends on F, F depends on G, G depends on D.
--
-- Each circle of dependence is reported exactly once. It is not reported
-- once for each unit in the circle.
--
------------------------------------------------------------------------------
-- 12.2 constant Nil_Relationship
------------------------------------------------------------------------------
Nil_Relationship : constant Relationship :=
(Consistent_Length => 0,
Inconsistent_Length => 0,
Missing_Length => 0,
Circular_Length => 0,
Consistent => Asis.Nil_Compilation_Unit_List,
Inconsistent => Asis.Nil_Compilation_Unit_List,
Missing => Asis.Nil_Compilation_Unit_List,
Circular => Asis.Nil_Compilation_Unit_List);
------------------------------------------------------------------------------
-- 12.3 function Semantic_Dependence_Order
------------------------------------------------------------------------------
-- Semantic Dependence Relationships - Reference Manual 10.1.1(24).
-- Elaboration Dependence Relationships - Reference Manual 10.1.1(25).
--
-- --|AN Application Note:
-- --|AN
-- --|AN To properly determine unit consistency, use one of the two semantic
-- --|AN dependence queries: Elaboration_Order or Semantic_Dependence_Order.
-- --|AN These queries return a value of the type Relationship, which contains
-- --|AN lists of consistent, inconsistent, missing and circular units.
-- --|AN
-- --|AN For these two queries, the existence of units in one or more of the
-- --|AN inconsistent, missing, or circular units list means that the
-- --|AN consistent unit list may not be complete.
-- --|AN
-- --|AN Applications that do not check for inconsistent, missing, or circular
-- --|AN units before using the consistent list might not operate as expected.
-- --|AN
------------------------------------------------------------------------------
function Semantic_Dependence_Order
(Compilation_Units : Asis.Compilation_Unit_List;
Dependent_Units : Asis.Compilation_Unit_List;
The_Context : Asis.Context;
Relation : Asis.Relation_Kinds)
return Relationship;
------------------------------------------------------------------------------
-- Compilation_Units - Specifies a list of pertinent units
-- Dependent_Units - Specifies dependents used to limit the query
-- The_Context - Specifies a program Context for context
-- Relation - Specifies the relationship to query
--
-- Produces a Relationship value containing compilation_unit elements related
-- to the given Compilation_Units by the specified relation.
--
-- The compilation_unit elements in the consistent units list are ordered such
-- that there are no forward semantic dependencies.
--
-- Dependent_Units are ignored unless the Relation is Descendants or
-- Dependents. The union of units in the needed units of the Dependent_Units
-- list provide a limiting context for the query. Only members of these
-- needed units are present in the result.
--
-- If the Dependent_Units list is Is_Nil, the context for the search is the
-- entire Context. The result of such a query is the full (unlimited)
-- list of Dependents for the Compilation_Units.
--
-- All units in the result will have an Enclosing_Context value that
-- Is_Identical to The_Context.
--
-- Appropriate Unit_Kinds:
-- A_Procedure
-- A_Function
-- A_Package
-- A_Generic_Procedure
-- A_Generic_Function
-- A_Generic_Package
-- A_Procedure_Instance
-- A_Function_Instance
-- A_Package_Instance
-- A_Procedure_Renaming
-- A_Function_Renaming
-- A_Package_Renaming
-- A_Generic_Procedure_Renaming
-- A_Generic_Function_Renaming
-- A_Generic_Package_Renaming
-- A_Procedure_Body
-- A_Function_Body
-- A_Package_Body
-- A_Procedure_Body_Subunit
-- A_Function_Body_Subunit
-- A_Package_Body_Subunit
-- A_Task_Body_Subunit
-- A_Protected_Body_Subunit
-- An_Unknown_Unit -- See Implementation Permissions
--
-- The Semantic_Dependence_Order query should never raise an exception
-- when processing inconsistent unit (sub)sets. This query is the only
-- means for an application to know if a given unit is consistent with
-- (some of) its supporters (dependents), and therefore the related
-- semantic processing can give valuable results for this unit.
--
-- --|IP Implementation Permissions:
-- --|IP
-- --|IP The handling of An_Unknown_Unit is implementation specific. It can be
-- --|IP possible to obtain Semantic Dependence Relationships when starting
-- --|IP with a list containing one or more units that are An_Unknown_Unit.
-- --|IP However, results may vary across ASIS implementations.
-- --|AN----------------------------------------------------------------------
-- --|AN Semantic_Dependence_Order defines consistent units to be ordered such
-- --|AN that there are no forward semantic dependencies.
--
------------------------------------------------------------------------------
-- 12.4 function Elaboration_Order
------------------------------------------------------------------------------
function Elaboration_Order
(Compilation_Units : Asis.Compilation_Unit_List;
The_Context : Asis.Context)
return Relationship;
------------------------------------------------------------------------------
-- Compilation_Units - Specifies a list of units to elaborate
-- The_Context - Specifies a program Context for context
--
-- Produces, in elaboration order, a Relationship value containing compilation
-- units required to elaborate the given compilation units.
--
-- The return value contains the set of ordered lists described above for the
-- queries on Semantic Dependence Relationships. If the inconsistent,
-- missing, and circular lists are empty, the consistent list will contain
-- all units required to elaborate the arguments.
-- --|IP
-- --|IP The Relationship value may include any number of
-- --|IP implementation-specific runtime support packages.
--
-- The first unit in the Consistent units list will always be the
-- specification for package Standard. The list will contain all units
-- required to elaborate the arguments.
--
-- Use the Context_Clause_Elements query to get pragma Elaborate elements
-- for a compilation unit.
--
-- Appropriate Unit_Kinds:
-- A_Procedure
-- A_Function
-- A_Package
-- A_Generic_Procedure
-- A_Generic_Function
-- A_Generic_Package
-- A_Procedure_Instance
-- A_Function_Instance
-- A_Package_Instance
-- A_Procedure_Renaming
-- A_Function_Renaming
-- A_Package_Renaming
-- A_Generic_Procedure_Renaming
-- A_Generic_Function_Renaming
-- A_Generic_Package_Renaming
-- A_Procedure_Body
-- A_Function_Body
-- A_Package_Body
-- A_Procedure_Body_Subunit
-- A_Function_Body_Subunit
-- A_Package_Body_Subunit
-- A_Task_Body_Subunit
-- A_Protected_Body_Subunit
-- An_Unknown_Unit -- See Implementation Permissions
--
-- --|IP Implementation Permissions:
-- --|IP
-- --|IP The handling of An_Unknown_Unit is implementation specific. It can
-- --|IP be possible to obtain Semantic Dependence Relationships when starting
-- --|IP with a list containing one or more units that are An_Unknown_Unit.
-- --|IP However, results may vary across ASIS implementations.
--
------------------------------------------------------------------------------
end Asis.Compilation_Units.Relations;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
073bbb095e0c288f4f0b583b4169926cdf5f1c58
|
orka_numerics/src/x86/generic/avx/orka-numerics-doubles-tensors-cpu.ads
|
orka_numerics/src/x86/generic/avx/orka-numerics-doubles-tensors-cpu.ads
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2022 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Orka.Numerics.Tensors.SIMD_CPU;
with Orka.SIMD.AVX.Doubles.Arithmetic;
with Orka.SIMD.AVX.Doubles.Compare;
with Orka.SIMD.AVX.Doubles.Logical;
with Orka.SIMD.AVX.Doubles.Math;
with Orka.SIMD.AVX.Longs.Logical;
with Orka.SIMD.AVX.Longs.Random.Emulation;
with Orka.SIMD.AVX.Longs.Arithmetic.Emulation;
with Orka.SIMD.AVX.Longs.Logical.Emulation;
with Orka.SIMD.AVX.Longs.Shift.Emulation;
package Orka.Numerics.Doubles.Tensors.CPU is new Orka.Numerics.Doubles.Tensors.SIMD_CPU
(Index_4D,
Integer_64,
SIMD.AVX.Longs.m256l,
SIMD.AVX.Longs.Arithmetic.Emulation."+",
SIMD.AVX.Longs.Logical.Emulation."and",
SIMD.AVX.Longs.Shift.Emulation.Shift_Elements_Left_Zeros,
SIMD.AVX.Longs.Shift.Emulation.Shift_Elements_Right_Zeros,
SIMD.AVX.Longs.Logical.Test_All_Ones,
SIMD.AVX.Longs.Logical.Test_All_Zero,
SIMD.AVX.Doubles.m256d,
SIMD.AVX.Doubles.Arithmetic."*",
SIMD.AVX.Doubles.Arithmetic."/",
SIMD.AVX.Doubles.Arithmetic."+",
SIMD.AVX.Doubles.Arithmetic."-",
SIMD.AVX.Doubles.Arithmetic."-",
SIMD.AVX.Doubles.Arithmetic."abs",
SIMD.AVX.Doubles.Arithmetic.Sum,
SIMD.AVX.Doubles.Arithmetic.Divide_Or_Zero,
SIMD.AVX.Doubles.Math.Sqrt,
SIMD.AVX.Doubles.Math.Min,
SIMD.AVX.Doubles.Math.Max,
SIMD.AVX.Doubles.Math.Ceil,
SIMD.AVX.Doubles.Math.Floor,
SIMD.AVX.Doubles.Math.Round_Nearest_Integer,
SIMD.AVX.Doubles.Math.Round_Truncate,
SIMD.AVX.Doubles.Logical.And_Not,
SIMD.AVX.Doubles.Logical."and",
SIMD.AVX.Doubles.Logical."or",
SIMD.AVX.Doubles.Logical."xor",
SIMD.AVX.Doubles.Compare."=",
SIMD.AVX.Doubles.Compare."/=",
SIMD.AVX.Doubles.Compare.">",
SIMD.AVX.Doubles.Compare."<",
SIMD.AVX.Doubles.Compare.">=",
SIMD.AVX.Doubles.Compare."<=",
SIMD.AVX.Longs.Random.Emulation.State,
SIMD.AVX.Longs.Random.Emulation.Next,
SIMD.AVX.Longs.Random.Emulation.Reset);
pragma Preelaborate (Orka.Numerics.Doubles.Tensors.CPU);
|
Add instantiation of SIMD_CPU for Float_64 using AVX
|
numerics: Add instantiation of SIMD_CPU for Float_64 using AVX
Some functions operate on vectors of Integer_64 and would normally
require AVX2 intrinsics. These are emulated with functions that use AVX
and SSE2 intrinsics.
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
|
c65ed3aea8ce0c6b77827cd2d1fdb49542177cf9
|
src/asis/asis-iterator.ads
|
src/asis/asis-iterator.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT INTERFACE COMPONENTS --
-- --
-- A S I S . I T E R A T O R --
-- --
-- S p e c --
-- --
-- Copyright (c) 2006, Free Software Foundation, Inc. --
-- --
-- This specification is adapted from the Ada Semantic Interface --
-- Specification Standard (ISO/IEC 15291) 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. The copyright notice --
-- above, and the license provisions that follow apply solely to the --
-- contents of the part following the private keyword. --
-- --
-- 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). --
-- --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- 14 package Asis.Iterator
------------------------------------------------------------------------------
------------------------------------------------------------------------------
package Asis.Iterator is
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Asis.Iterator encapsulates the generic procedure Traverse_Element which
-- allows an ASIS application to perform an iterative traversal of a
-- logical syntax tree. It requires the use of two generic procedures,
-- Pre_Operation, which identifies processing for the traversal, and
-- Post_Operation, which identifies processing after the traversal.
-- The State_Information allows processing state to be passed during the
-- iteration of Traverse_Element.
--
-- Package Asis.Iterator is established as a child package to highlight the
-- iteration capability and to facilitate the translation of ASIS to IDL.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- 14.1 procedure Traverse_Element
------------------------------------------------------------------------------
generic
type State_Information is limited private;
with procedure Pre_Operation
(Element : Asis.Element;
Control : in out Traverse_Control;
State : in out State_Information) is <>;
with procedure Post_Operation
(Element : Asis.Element;
Control : in out Traverse_Control;
State : in out State_Information) is <>;
procedure Traverse_Element
(Element : Asis.Element;
Control : in out Traverse_Control;
State : in out State_Information);
------------------------------------------------------------------------------
-- Element - Specifies the initial element in the traversal
-- Control - Specifies what next to do with the traversal
-- State_Information - Specifies other information for the traversal
--
-- Traverses the element and all its component elements, if any.
-- Component elements are all elements that can be obtained by a combination
-- of the ASIS structural queries appropriate for the given element.
--
-- If an element has one or more component elements, each is called a child
-- element. An element's parent element is its Enclosing_Element. Children
-- with the same parent are sibling elements. The type Traverse_Control uses
-- the terms children and siblings to control the traverse.
--
-- For each element, the formal procedure Pre_Operation is called when first
-- visiting the element. Each of that element's children are then visited
-- and finally the formal procedure Post_Operation is called for the element.
--
-- The order of Element traversal is in terms of the textual representation of
-- the Elements. Elements are traversed in left-to-right and top-to-bottom
-- order.
--
-- Traversal of Implicit Elements:
--
-- Implicit elements are not traversed by default. However, they may be
-- explicitly queried and then passed to the traversal instance. Implicit
-- elements include implicit predefined operator declarations, implicit
-- inherited subprogram declarations, implicit expanded generic specifications
-- and bodies, default expressions supplied to procedure, function, and entry
-- calls, etc.
--
-- Applications that wish to traverse these implicit Elements shall query for
-- them at the appropriate places in a traversal and then recursively call
-- their instantiation of the traversal generic. (Implicit elements provided
-- by ASIS do not cover all possible Ada implicit constructs. For example,
-- implicit initializations for variables of an access type are not provided
-- by ASIS.)
--
-- Traversal of Association lists:
--
-- Argument and association lists for procedure calls, function calls, entry
-- calls, generic instantiations, and aggregates are traversed in their
-- unnormalized forms, as if the Normalized parameter was False for those
-- queries. Implementations that always normalize certain associations may
-- return Is_Normalized associations. See the Implementation Permissions
-- for the queries Discriminant_Associations, Generic_Actual_Part,
-- Call_Statement_Parameters, Record_Component_Associations, or
-- Function_Call_Parameters.
--
-- Applications that wish to explicitly traverse normalized associations can
-- do so by querying the appropriate locations in order to obtain the
-- normalized list. The list can then be traversed by recursively calling
-- the traverse instance. Once that sub-traversal is finished, the Control
-- parameter can be set to Abandon_Children to skip processing of the
-- unnormalized argument list.
--
-- Traversal can be controlled with the Control parameter.
--
-- A call to an instance of Traverse_Element will not result in calls to
-- Pre_Operation or Post_Operation unless Control is set to Continue.
--
-- The subprograms matching Pre_Operation and Post_Operation can set
-- their Control parameter to affect the traverse:
--
-- Continue -- Continues the normal depth-first traversal.
--
-- Abandon_Children -- Prevents traversal of the current element's
-- -- children.
-- -- If set in a Pre_Operation, traversal picks up
-- -- with the next sibling element of the current
-- -- element.
-- -- If set in a Post_Operation, this is the
-- -- same as Continue, all children will already
-- -- have been traversed. Traversal picks up with
-- -- the Post_Operation of the parent.
--
-- Abandon_Siblings -- Prevents traversal of the current element's
-- -- children and remaining siblings.
-- -- If set in a Pre_Operation, this abandons the
-- -- associated Post_Operation for the current
-- -- element. Traversal picks up with the
-- -- Post_Operation of the parent.
-- -- If set in a Post_Operation, traversal picks
-- -- up with the Post_Operation of the parent.
--
-- Terminate_Immediately -- Does exactly that.
--
-- Raises ASIS_Inappropriate_Element if the element is a Nil_Element
------------------------------------------------------------------------------
end Asis.Iterator;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
|
51ae88f6706d4c9bc4d700143c12f3eb507d14c8
|
src/asis/a4g-a_opt.adb
|
src/asis/a4g-a_opt.adb
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- --
-- A 4 G . A _ O P T --
-- --
-- B o d y --
-- --
-- Copyright (C) 1995-2012, Free Software Foundation, Inc. --
-- --
-- ASIS-for-GNAT is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 2, or (at your option) any later --
-- version. ASIS-for-GNAT is distributed in the hope that it will be use- --
-- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- --
-- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General --
-- Public License for more details. You should have received a copy of the --
-- GNU General Public License distributed with ASIS-for-GNAT; see file --
-- COPYING. If not, write to the Free Software Foundation, 51 Franklin --
-- Street, Fifth Floor, Boston, MA 02110-1301, USA. --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the --
-- Software Engineering Laboratory of the Swiss Federal Institute of --
-- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the --
-- Scientific Research Computer Center of Moscow State University (SRCC --
-- MSU), Russia, with funding partially provided by grants from the Swiss --
-- National Science Foundation and the Swiss Academy of Engineering --
-- Sciences. ASIS-for-GNAT is now maintained by AdaCore --
-- (http://www.adacore.com). --
-- --
------------------------------------------------------------------------------
with Asis.Errors; use Asis.Errors;
with A4G.A_Types; use A4G.A_Types;
with A4G.A_Osint; use A4G.A_Osint;
with A4G.A_Output; use A4G.A_Output;
with A4G.A_Debug; use A4G.A_Debug;
with A4G.Vcheck; use A4G.Vcheck;
with GNAT.OS_Lib; use GNAT.OS_Lib;
package body A4G.A_Opt is
-------------------------------------
-- Process_Finalization_Parameters --
-------------------------------------
procedure Process_Finalization_Parameters (Parameters : String) is
Final_Parameters : Argument_List_Access;
procedure Process_One_Parameter (Param : String);
-- incapsulates processing of a separate parameter
---------------------------
-- Process_One_Parameter --
---------------------------
procedure Process_One_Parameter (Param : String) is
Parameter : constant String (1 .. Param'Length) := Param;
begin
ASIS_Warning
(Message => "Asis.Implementation.Finalize: "
& "unknown parameter - "
& Parameter,
Error => Parameter_Error);
end Process_One_Parameter;
begin -- Process_Finalization_Parameters
Final_Parameters := Parameter_String_To_List (Parameters);
for I in Final_Parameters'Range loop
Process_One_Parameter (Final_Parameters (I).all);
end loop;
Free_Argument_List (Final_Parameters);
end Process_Finalization_Parameters;
---------------------------------------
-- Process_Initialization_Parameters --
---------------------------------------
procedure Process_Initialization_Parameters (Parameters : String) is
Init_Parameters : Argument_List_Access;
procedure Process_One_Parameter (Param : String);
-- incapsulates processing of a separate parameter
---------------------------
-- Process_One_Parameter --
---------------------------
procedure Process_One_Parameter (Param : String) is
Parameter : constant String (1 .. Param'Length) := Param;
Unknown_Parameter : Boolean := False;
subtype Dig is Character range '1' .. '9';
subtype Let is Character range 'a' .. 'z';
procedure Process_Parameter;
procedure Process_Option;
-- Process_Option works if Param starts from '-', and
-- Process_Parameter works otherwise
procedure Process_Parameter is
begin
-- no parameter is currently available as an ASIS initialization
-- parameter
Raise_ASIS_Failed
(Diagnosis => "Asis.Implementation.Initialize: "
& "unknown parameter - "
& Parameter,
Stat => Parameter_Error,
Internal_Bug => False);
end Process_Parameter;
procedure Process_Option is
begin
case Parameter (2) is
when 'a' =>
if Parameter = "-asis05"
or else
Parameter = "-asis12"
or else
Parameter = "-asis95"
then
-- We have to accept these parameters because of
-- compatibility reasons
null;
else
Unknown_Parameter := True;
end if;
when 'd' =>
if Parameter'Length = 3
and then
(Parameter (3) in Dig or else
Parameter (3) in Let)
then
Set_Debug_Flag (Parameter (3));
elsif Parameter = "-dall" then
A4G.A_Debug.Set_On;
else
Unknown_Parameter := True;
end if;
when 'k' =>
if Parameter = "-k" then
Keep_Going := True;
else
Unknown_Parameter := True;
end if;
when 'n' =>
if Parameter = "-nbb" then
Generate_Bug_Box := False;
Keep_Going := True;
else
Unknown_Parameter := True;
end if;
when 's' =>
if Parameter = "-sv" then
Strong_Version_Check := True;
else
Unknown_Parameter := True;
end if;
when 'w' =>
if Parameter = "-ws" then
ASIS_Warning_Mode := Suppress;
elsif Parameter = "-we" then
ASIS_Warning_Mode := Treat_As_Error;
elsif Parameter = "-wv" then
Strong_Version_Check := False;
else
Unknown_Parameter := True;
end if;
when others =>
Unknown_Parameter := True;
end case;
if Unknown_Parameter then
Raise_ASIS_Failed
(Diagnosis => "Asis.Implementation.Initialize: "
& "unknown option - "
& Parameter,
Stat => Parameter_Error,
Internal_Bug => False);
end if;
end Process_Option;
begin -- Process_One_Parameter
if Parameter (1) = '-' then
if Parameter'Length >= 2 then
Process_Option;
else
Raise_ASIS_Failed
(Diagnosis => "Asis.Implementation.Initialize: "
& "Option is missing after ""-""",
Stat => Parameter_Error,
Internal_Bug => False);
end if;
else
Process_Parameter;
end if;
end Process_One_Parameter;
begin -- Process_Initialization_Parameters
Init_Parameters := Parameter_String_To_List (Parameters);
for I in Init_Parameters'Range loop
Process_One_Parameter (Init_Parameters (I).all);
end loop;
Free_Argument_List (Init_Parameters);
end Process_Initialization_Parameters;
-------------
-- Set_Off --
-------------
procedure Set_Off is
begin
Is_Initialized := False;
ASIS_Warning_Mode := Normal;
Strong_Version_Check := True;
Generate_Bug_Box := True;
Keep_Going := False;
end Set_Off;
end A4G.A_Opt;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.