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
|
---|---|---|---|---|---|---|---|---|---|
28c3e414883091ed098b807b11600ca16715bd86
|
src/wiki-writers-builders.adb
|
src/wiki-writers-builders.adb
|
-----------------------------------------------------------------------
-- wiki-writers-builders -- Wiki writer to a string builder
-- Copyright (C) 2011, 2012, 2013, 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.Characters.Conversions;
package body Wiki.Writers.Builders is
-- ------------------------------
-- Write the content to the string builder.
-- ------------------------------
overriding
procedure Write (Writer : in out Writer_Builder_Type;
Content : in Wide_Wide_String) is
begin
Wide_Wide_Builders.Append (Writer.Content, Content);
end Write;
-- ------------------------------
-- Write the content to the string builder.
-- ------------------------------
overriding
procedure Write (Writer : in out Writer_Builder_Type;
Content : in Unbounded_Wide_Wide_String) is
begin
Wide_Wide_Builders.Append (Writer.Content, To_Wide_Wide_String (Content));
end Write;
-- ------------------------------
-- Iterate over the buffer content calling the <tt>Process</tt> procedure with each
-- chunk.
-- ------------------------------
procedure Iterate (Source : in Writer_Builder_Type;
Process : not null access procedure (Chunk : in Wide_Wide_String)) is
begin
Wide_Wide_Builders.Iterate (Source.Content, Process);
end Iterate;
-- ------------------------------
-- Convert what was collected in the writer builder to a string and return it.
-- ------------------------------
function To_String (Source : in Writer_Builder_Type) return String is
Pos : Natural := 0;
Result : String (1 .. Wide_Wide_Builders.Length (Source.Content));
procedure Convert (Chunk : in Wide_Wide_String) is
begin
for I in Chunk'Range loop
Pos := Pos + 1;
Result (Pos) := Ada.Characters.Conversions.To_Character (Chunk (I));
end loop;
end Convert;
begin
Wide_Wide_Builders.Iterate (Source.Content, Convert'Access);
return Result;
end To_String;
-- ------------------------------
-- Write a single character to the string builder.
-- ------------------------------
procedure Write (Writer : in out Writer_Builder_Type;
Char : in Wide_Wide_Character) is
begin
Wide_Wide_Builders.Append (Writer.Content, Char);
end Write;
-- ------------------------------
-- Write a single character to the string builder.
-- ------------------------------
procedure Write_Char (Writer : in out Writer_Builder_Type;
Char : in Character) is
begin
Wide_Wide_Builders.Append (Writer.Content,
Ada.Characters.Conversions.To_Wide_Wide_Character (Char));
end Write_Char;
-- ------------------------------
-- Write the string to the string builder.
-- ------------------------------
procedure Write_String (Writer : in out Writer_Builder_Type;
Content : in String) is
begin
for I in Content'Range loop
Writer.Write_Char (Content (I));
end loop;
end Write_String;
type Unicode_Char is mod 2**31;
-- ------------------------------
-- Internal method to write a character on the response stream
-- and escape that character as necessary. Unlike 'Write_Char',
-- this operation does not closes the current XML entity.
-- ------------------------------
procedure Write_Escape (Stream : in out Html_Writer_Type'Class;
Char : in Wide_Wide_Character) is
Code : constant Unicode_Char := Wide_Wide_Character'Pos (Char);
begin
-- If "?" or over, no escaping is needed (this covers
-- most of the Latin alphabet)
if Code > 16#3F# or Code <= 16#20# then
Stream.Write (Char);
elsif Char = '<' then
Stream.Write ("<");
elsif Char = '>' then
Stream.Write (">");
elsif Char = '&' then
Stream.Write ("&");
else
Stream.Write (Char);
end if;
end Write_Escape;
-- ------------------------------
-- Close the current XML entity if an entity was started
-- ------------------------------
procedure Close_Current (Stream : in out Html_writer_Type'Class) is
begin
if Stream.Close_Start then
Stream.Write_Char ('>');
Stream.Close_Start := False;
end if;
end Close_Current;
procedure Write_Wide_Element (Writer : in out Html_writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String) is
begin
Writer.Start_Element (Name);
Writer.Write_Wide_Text (Content);
Writer.End_Element (Name);
end Write_Wide_Element;
procedure Write_Wide_Attribute (Writer : in out Html_writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String) is
Count : constant Natural := Length (Content);
begin
if Writer.Close_Start then
Writer.Write_Char (' ');
Writer.Write_String (Name);
Writer.Write_Char ('=');
Writer.Write_Char ('"');
for I in 1 .. Count loop
declare
C : constant Wide_Wide_Character := Element (Content, I);
begin
if C = '"' then
Writer.Write_String (""");
else
Writer.Write_Escape (C);
end if;
end;
end loop;
Writer.Write_Char ('"');
end if;
end Write_Wide_Attribute;
procedure Start_Element (Writer : in out Html_Writer_Type;
Name : in String) is
begin
Close_Current (Writer);
Writer.Write_Char ('<');
Writer.Write_String (Name);
Writer.Close_Start := True;
end Start_Element;
procedure End_Element (Writer : in out Html_Writer_Type;
Name : in String) is
begin
Close_Current (Writer);
Writer.Write_String ("</");
Writer.Write_String (Name);
Writer.Write_Char ('>');
end End_Element;
procedure Write_Wide_Text (Writer : in out Html_Writer_Type;
Content : in Unbounded_Wide_Wide_String) is
Count : constant Natural := Length (Content);
begin
Close_Current (Writer);
if Count > 0 then
for I in 1 .. Count loop
Html_Writer_Type'Class (Writer).Write (Element (Content, I));
end loop;
end if;
end Write_Wide_Text;
end Wiki.Writers.Builders;
|
Implement the operations for the text and html writers
|
Implement the operations for the text and html writers
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
|
3977c8482e727be71bb44b74b1413db70d14bc9d
|
src/sqlite/ado-schemas-sqlite.adb
|
src/sqlite/ado-schemas-sqlite.adb
|
-----------------------------------------------------------------------
-- ado.schemas -- Database Schemas
-- 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 ADO.Statements;
with ADO.Statements.Create;
with Ada.Strings.Fixed;
with Util.Strings.Transforms;
package body ADO.Schemas.Sqlite is
use ADO.Statements;
procedure Load_Table_Schema (C : in ADO.Drivers.Connections.Database_Connection'Class;
Table : in Table_Definition);
function String_To_Type (Value : in String) return Column_Type;
function String_To_Type (Value : in String) return Column_Type is
Pos : Natural;
begin
if Value = "date" then
return T_DATE;
elsif Value = "datetime" then
return T_DATE_TIME;
elsif Value = "int" or Value = "integer" then
return T_INTEGER;
elsif Value = "bigint" then
return T_LONG_INTEGER;
elsif Value = "tinyint" then
return T_TINYINT;
elsif Value = "smallint" then
return T_SMALLINT;
elsif Value = "blob" then
return T_BLOB;
end if;
Pos := Ada.Strings.Fixed.Index (Value, "(");
if Pos > 0 then
declare
Name : constant String := Value (Value'First .. Pos - 1);
begin
if Name = "varchar" then
return T_VARCHAR;
elsif Name = "real" or Name = "float" or Name = "double" then
return T_FLOAT;
elsif Name = "int" then
return T_INTEGER;
elsif Name = "bigint" then
return T_LONG_INTEGER;
else
return T_UNKNOWN;
end if;
end;
end if;
return T_UNKNOWN;
end String_To_Type;
-- ------------------------------
-- Load the table definition
-- ------------------------------
procedure Load_Table_Schema (C : in ADO.Drivers.Connections.Database_Connection'Class;
Table : in Table_Definition) is
Name : constant String := Get_Name (Table);
Stmt : Query_Statement
:= Create.Create_Statement (C.Create_Statement ("pragma table_info('" & Name & "')"));
Last : Column_Definition := null;
Col : Column_Definition;
Value : Unbounded_String;
begin
Stmt.Execute;
while Stmt.Has_Elements loop
Col := new Column;
Col.Name := Stmt.Get_Unbounded_String (1);
Col.Collation := Stmt.Get_Unbounded_String (2);
Col.Default := Stmt.Get_Unbounded_String (5);
if Last /= null then
Last.Next_Column := Col;
else
Table.First_Column := Col;
end if;
Value := Stmt.Get_Unbounded_String (2);
Col.Col_Type
:= String_To_Type (Util.Strings.Transforms.To_Lower_Case (To_String (Value)));
Value := Stmt.Get_Unbounded_String (3);
Col.Is_Null := Value = "0";
Last := Col;
Stmt.Next;
end loop;
end Load_Table_Schema;
-- ------------------------------
-- Load the database schema
-- ------------------------------
procedure Load_Schema (C : in ADO.Drivers.Connections.Database_Connection'Class;
Schema : out Schema_Definition) is
Stmt : Query_Statement
:= Create.Create_Statement (C.Create_Statement ("SELECT NAME FROM sqlite_master"));
Table : Table_Definition;
Last : Table_Definition := null;
begin
Schema.Schema := new ADO.Schemas.Schema;
Stmt.Execute;
while Stmt.Has_Elements loop
Table := new ADO.Schemas.Table;
Table.Name := Stmt.Get_Unbounded_String (0);
if Last /= null then
Last.Next_Table := Table;
else
Schema.Schema.First_Table := Table;
end if;
Load_Table_Schema (C, Table);
Last := Table;
Stmt.Next;
end loop;
end Load_Schema;
end ADO.Schemas.Sqlite;
|
Implement the Load_Schema procedure for SQLite
|
Implement the Load_Schema procedure for SQLite
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
|
dd1dc9faeaeeaf276b1c505589f7b84de8d89b45
|
src/util-properties.ads
|
src/util-properties.ads
|
-----------------------------------------------------------------------
-- properties -- Generic name/value property management
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 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 Ada.Strings.Unbounded;
with Ada.Finalization;
with Ada.Text_IO;
package Util.Properties is
NO_PROPERTY : exception;
use Ada.Strings.Unbounded;
subtype Value is Ada.Strings.Unbounded.Unbounded_String;
function "+" (S : String) return Value renames To_Unbounded_String;
function "-" (S : Value) return String renames To_String;
-- The manager holding the name/value pairs and providing the operations
-- to get and set the properties.
type Manager is new Ada.Finalization.Controlled with private;
type Manager_Access is access all Manager'Class;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in Value) return Boolean;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in String) return Boolean;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return Value;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Value) return Value;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Value) return String;
-- Returns the property value or Default if it does not exist.
function Get (Self : in Manager'Class;
Name : in String;
Default : in String) return String;
-- Insert the specified property in the list.
procedure Insert (Self : in out Manager'Class;
Name : in String;
Item : in String);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in String);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in Value);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in Unbounded_String;
Item : in Value);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in String);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in Value);
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager'Class;
Process : access procedure (Name, Item : Value));
type Name_Array is array (Natural range <>) of Value;
-- Return the name of the properties defined in the manager.
-- When a prefix is specified, only the properties starting with
-- the prefix are returned.
function Get_Names (Self : in Manager;
Prefix : in String := "") return Name_Array;
-- Load the properties from the file input stream. The file must follow
-- the definition of Java property files. When a prefix is specified, keep
-- only the properties that starts with the prefix. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
procedure Load_Properties (Self : in out Manager'Class;
File : in Ada.Text_IO.File_Type;
Prefix : in String := "";
Strip : in Boolean := False);
-- Load the properties from the file. The file must follow the
-- definition of Java property files. When a prefix is specified, keep
-- only the properties that starts with the prefix. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
-- Raises NAME_ERROR if the file does not exist.
procedure Load_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "";
Strip : in Boolean := False);
-- Copy the properties from FROM which start with a given prefix.
-- If the prefix is empty, all properties are copied. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
procedure Copy (Self : in out Manager'Class;
From : in Manager'Class;
Prefix : in String := "";
Strip : in Boolean := False);
private
-- Abstract interface for the implementation of Properties
-- (this allows to decouples the implementation from the API)
package Interface_P is
type Manager is abstract tagged limited record
Count : Natural := 0;
end record;
type Manager_Access is access all Manager'Class;
type Manager_Factory is access function return Manager_Access;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager; Name : in Value)
return Boolean is abstract;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager; Name : in Value)
return Value is abstract;
procedure Insert (Self : in out Manager; Name : in Value;
Item : in Value) is abstract;
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager; Name : in Value;
Item : in Value) is abstract;
-- Remove the property given its name.
procedure Remove (Self : in out Manager; Name : in Value) is abstract;
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager;
Process : access procedure (Name, Item : Value)) is abstract;
-- Deep copy of properties stored in 'From' to 'To'.
function Create_Copy (Self : in Manager)
return Manager_Access is abstract;
procedure Delete (Self : in Manager; Obj : in out Manager_Access)
is abstract;
function Get_Names (Self : in Manager;
Prefix : in String) return Name_Array is abstract;
end Interface_P;
procedure Set_Property_Implementation (Self : in out Manager;
Impl : in Interface_P.Manager_Access);
-- Create a property implementation if there is none yet.
procedure Check_And_Create_Impl (Self : in out Manager);
type Manager is new Ada.Finalization.Controlled with record
Impl : Interface_P.Manager_Access := null;
end record;
overriding
procedure Adjust (Object : in out Manager);
overriding
procedure Finalize (Object : in out Manager);
end Util.Properties;
|
-----------------------------------------------------------------------
-- properties -- Generic name/value property management
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 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 Ada.Finalization;
with Ada.Text_IO;
with Util.Concurrent.Counters;
package Util.Properties is
NO_PROPERTY : exception;
use Ada.Strings.Unbounded;
subtype Value is Ada.Strings.Unbounded.Unbounded_String;
function "+" (S : String) return Value renames To_Unbounded_String;
function "-" (S : Value) return String renames To_String;
-- The manager holding the name/value pairs and providing the operations
-- to get and set the properties.
type Manager is new Ada.Finalization.Controlled with private;
type Manager_Access is access all Manager'Class;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in Value) return Boolean;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in String) return Boolean;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return Value;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Value) return Value;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Value) return String;
-- Returns the property value or Default if it does not exist.
function Get (Self : in Manager'Class;
Name : in String;
Default : in String) return String;
-- Insert the specified property in the list.
procedure Insert (Self : in out Manager'Class;
Name : in String;
Item : in String);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in String);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in Value);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in Unbounded_String;
Item : in Value);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in String);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in Value);
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager'Class;
Process : access procedure (Name, Item : Value));
type Name_Array is array (Natural range <>) of Value;
-- Return the name of the properties defined in the manager.
-- When a prefix is specified, only the properties starting with
-- the prefix are returned.
function Get_Names (Self : in Manager;
Prefix : in String := "") return Name_Array;
-- Load the properties from the file input stream. The file must follow
-- the definition of Java property files. When a prefix is specified, keep
-- only the properties that starts with the prefix. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
procedure Load_Properties (Self : in out Manager'Class;
File : in Ada.Text_IO.File_Type;
Prefix : in String := "";
Strip : in Boolean := False);
-- Load the properties from the file. The file must follow the
-- definition of Java property files. When a prefix is specified, keep
-- only the properties that starts with the prefix. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
-- Raises NAME_ERROR if the file does not exist.
procedure Load_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "";
Strip : in Boolean := False);
-- Copy the properties from FROM which start with a given prefix.
-- If the prefix is empty, all properties are copied. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
procedure Copy (Self : in out Manager'Class;
From : in Manager'Class;
Prefix : in String := "";
Strip : in Boolean := False);
private
-- Abstract interface for the implementation of Properties
-- (this allows to decouples the implementation from the API)
package Interface_P is
type Manager is abstract tagged limited record
Count : Util.Concurrent.Counters.Counter;
end record;
type Manager_Access is access all Manager'Class;
type Manager_Factory is access function return Manager_Access;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager; Name : in Value)
return Boolean is abstract;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager; Name : in Value)
return Value is abstract;
procedure Insert (Self : in out Manager; Name : in Value;
Item : in Value) is abstract;
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager; Name : in Value;
Item : in Value) is abstract;
-- Remove the property given its name.
procedure Remove (Self : in out Manager; Name : in Value) is abstract;
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager;
Process : access procedure (Name, Item : Value)) is abstract;
-- Deep copy of properties stored in 'From' to 'To'.
function Create_Copy (Self : in Manager)
return Manager_Access is abstract;
procedure Delete (Self : in Manager; Obj : in out Manager_Access)
is abstract;
function Get_Names (Self : in Manager;
Prefix : in String) return Name_Array is abstract;
end Interface_P;
procedure Set_Property_Implementation (Self : in out Manager;
Impl : in Interface_P.Manager_Access);
-- Create a property implementation if there is none yet.
procedure Check_And_Create_Impl (Self : in out Manager);
type Manager is new Ada.Finalization.Controlled with record
Impl : Interface_P.Manager_Access := null;
end record;
overriding
procedure Adjust (Object : in out Manager);
overriding
procedure Finalize (Object : in out Manager);
end Util.Properties;
|
Use a concurrent conter for property managers
|
Use a concurrent conter for property managers
|
Ada
|
apache-2.0
|
Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util
|
20455fd53b1b3a80afb7f31937c31b4618cbcdea
|
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
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
2026df8bec7e0468de8afcde7b119d84e369b255
|
src/asf-filters-cache_control.ads
|
src/asf-filters-cache_control.ads
|
-----------------------------------------------------------------------
-- asf-filters-cache_control -- HTTP response Cache-Control settings
-- 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.Unbounded;
with ASF.Requests;
with ASF.Responses;
with ASF.Servlets;
-- The <b>ASF.Filters.Cache_Control</b> package implements a servlet filter to add
-- cache control headers in a response.
--
package ASF.Filters.Cache_Control is
-- Filter configuration parameter, when not empty, add a Vary header in the response.
VARY_HEADER_PARAM : constant String := "header.vary";
-- Filter configuration parameter, defines the expiration date in seconds relative
-- to the current date. When 0, disable browser caching.
CACHE_CONTROL_PARAM : constant String := "header.cache-control";
type Cache_Control_Filter is new ASF.Filters.Filter with record
Vary : Ada.Strings.Unbounded.Unbounded_String;
Cache_Control_Header : Ada.Strings.Unbounded.Unbounded_String;
end record;
-- The Do_Filter method of the Filter is called by the container each time
-- a request/response pair is passed through the chain due to a client request
-- for a resource at the end of the chain. The <b>Cache_Control</b> filter adds
-- a <tt>Cache-Control</tt>, <tt>Expires</tt>, <tt>Pragma</tt> and optionally a
-- <tt>Vary</tt> header in the HTTP response.
overriding
procedure Do_Filter (F : in Cache_Control_Filter;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain);
-- Called by the servlet container to indicate to a filter that the filter
-- instance is being placed into service.
procedure Initialize (Server : in out Cache_Control_Filter;
Config : in ASF.Servlets.Filter_Config);
end ASF.Filters.Cache_Control;
|
Define the Cache_Control package with Cache_Control_Filter type to add a Cache-Control, Vary headers in the HTTP response
|
Define the Cache_Control package with Cache_Control_Filter type to add
a Cache-Control, Vary headers in the HTTP response
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
|
486f1d3590d6c2ce5f248126f5a9d58e59e65660
|
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
|
stcarrez/ada-util,stcarrez/ada-util
|
|
e3e5c90ba726d8d051ea00d80e7c71cfa58f1bad
|
awa/plugins/awa-counters/src/awa-counters-beans.adb
|
awa/plugins/awa-counters/src/awa-counters-beans.adb
|
-----------------------------------------------------------------------
-- awa-counters-beans -- Counter bean definition
-- 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 AWA.Counters.Beans is
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Counter_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
return Util.Beans.Objects.To_Object (From.Value);
end Get_Value;
end AWA.Counters.Beans;
|
Implement the Get_Value procedure for the Counter_Bean
|
Implement the Get_Value procedure for the Counter_Bean
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
|
36829f1e1d4adbdfe2e54b81d6c9168ee73bf736
|
regtests/asf-rest-tests.ads
|
regtests/asf-rest-tests.ads
|
-----------------------------------------------------------------------
-- asf-rest-tests - Unit tests for ASF.Rest and ASF.Servlets.Rest
-- 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 Ada.Strings.Unbounded;
with Util.Tests;
with Util.Beans.Objects;
with ASF.Tests;
package ASF.Rest.Tests is
type Test_API is record
N : Natural := 0;
end record;
procedure Create (Data : in out Test_API;
Req : in out ASF.Rest.Request'Class;
Reply : in out ASF.Rest.Response'Class;
Stream : in out ASF.Rest.Output_Stream'Class);
procedure Update (Data : in out Test_API;
Req : in out ASF.Rest.Request'Class;
Reply : in out ASF.Rest.Response'Class;
Stream : in out ASF.Rest.Output_Stream'Class);
procedure Delete (Data : in out Test_API;
Req : in out ASF.Rest.Request'Class;
Reply : in out ASF.Rest.Response'Class;
Stream : in out ASF.Rest.Output_Stream'Class);
procedure List (Data : in out Test_API;
Req : in out ASF.Rest.Request'Class;
Reply : in out ASF.Rest.Response'Class;
Stream : in out ASF.Rest.Output_Stream'Class);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test REST POST create operation
procedure Test_Create (T : in out Test);
-- Test REST GET operation
procedure Test_Get (T : in out Test);
-- Test REST PUT update operation
procedure Test_Update (T : in out Test);
-- Test REST DELETE delete operation
procedure Test_Delete (T : in out Test);
-- Test REST operation on invalid operation.
procedure Test_Invalid (T : in out Test);
procedure Test_Operation (T : in out Test;
Method : in String;
URI : in String;
Status : in Natural);
end ASF.Rest.Tests;
|
Add REST unit tests
|
Add REST unit tests
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
|
f1bf7d2f673d7ae956fd9bfe21f1cc70a65c8c20
|
awa/plugins/awa-mail/src/aws/awa-mail-clients-aws_smtp-initialize_nossl.adb
|
awa/plugins/awa-mail/src/aws/awa-mail-clients-aws_smtp-initialize_nossl.adb
|
-----------------------------------------------------------------------
-- awa-mail-clients-aws_smtp-initialize -- Initialize SMTP client without SSL support
-- 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.
-----------------------------------------------------------------------
separate (AWA.Mail.Clients.AWS_SMTP)
procedure Initialize (Client : in out AWS_Mail_Manager'Class;
Props : in Util.Properties.Manager'Class) is
Server : constant String := Props.Get (Name => "smtp.host", Default => "localhost");
User : constant String := Props.Get (Name => "smtp.user", Default => "");
Passwd : constant String := Props.Get (Name => "smtp.password", Default => "");
begin
if User'Length > 0 then
Client.Creds := AWS.SMTP.Authentication.Plain.Initialize (User, Passwd);
Client.Server := AWS.SMTP.Client.Initialize (Server_Name => Server,
Port => Client.Port,
Credential => Client.Creds'Access);
else
Client.Server := AWS.SMTP.Client.Initialize (Server_Name => Server,
Port => Client.Port);
end if;
end Initialize;
|
Implement the Initialize procedure for AWS version before gnat-2015 (aws 3.1)
|
Implement the Initialize procedure for AWS version before gnat-2015 (aws 3.1)
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
|
53d8446e039e408d2703f3d62ed3935fba45fa0f
|
src/asis/a4g.ads
|
src/asis/a4g.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . A _ S E M --
-- --
-- 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). --
-- --
------------------------------------------------------------------------------
-- This package is the root of the ASIS-for-GNAT implementation hierarchy.
-- All the implementation components, except Asis.Set_Get and
-- Asis.Text.Set_Get (which need access to the private parts of the
-- corresponding ASIS interface packages), are children or grandchildren of
-- A4G. (A4G stands for Asis For GNAT).
--
-- The primary aim of this package is to constrain the pollution of the user
-- namespace when using the ASIS library to create ASIS applications, by
-- children of A4G.
package A4G is
pragma Pure (A4G);
end A4G;
|
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
|
|
fc1a7af1206102cf3e1c96df153d0fe831b06d33
|
atest.adb
|
atest.adb
|
with Posix;
use Posix;
procedure ATest is
Error : errno_t;
begin
Close(5,Error);
end ATest;
|
Test Ada main program
|
Test Ada main program
|
Ada
|
lgpl-2.1
|
ve3wwg/adafpx,ve3wwg/adafpx
|
|
c9c39c839b25f3822d0efe419052f0690d9eb7ea
|
awa/plugins/awa-blogs/regtests/awa-blogs-tests.adb
|
awa/plugins/awa-blogs/regtests/awa-blogs-tests.adb
|
-----------------------------------------------------------------------
-- awa-blogs-tests -- Unit tests for blogs module
-- 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.Test_Caller;
with Util.Strings;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Principals;
with ASF.Tests;
with AWA.Users.Models;
with AWA.Services.Contexts;
with AWA.Tests.Helpers.Users;
with Security.Contexts;
package body AWA.Blogs.Tests is
package Caller is new Util.Test_Caller (Test, "Blogs.Beans");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Create_Blog",
Test_Create_Blog'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of blog by simulating web requests.
-- ------------------------------
procedure Test_Create_Blog (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
Request.Set_Parameter ("title", "The Blog Title");
Request.Set_Parameter ("create-blog", "1");
Request.Set_Parameter ("create", "1");
ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create-blog.html", "create-blog.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response");
declare
R : constant String := Reply.Get_Header ("Location");
Pos : constant Natural := Util.Strings.Rindex (R, '=');
begin
T.Assert (Pos > 0, "Invalid redirect response");
ASF.Tests.Assert_Redirect (T, "/asfunit/blogs/admin/create.html?id="
& R (Pos + 1 .. R'Last),
Reply, "Invalid redirect after blog creation");
Request.Set_Parameter ("post-blog-id", R (Pos + 1 .. R'Last));
Request.Set_Parameter ("post", "1");
Request.Set_Parameter ("post-title", "Post title");
Request.Set_Parameter ("text", "The blog post content.");
Request.Set_Parameter ("uri", "the-blog-url");
Request.Set_Parameter ("save", "1");
Request.Set_Parameter ("post-status", "1");
Request.Set_Parameter ("allow-comment", "0");
ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create.html", "create-post.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response");
ASF.Tests.Assert_Redirect (T, "/asfunit/blogs/admin/list.html?blog_id="
& R (Pos + 1 .. R'Last),
Reply, "Invalid redirect after blog post creation");
end;
end Test_Create_Blog;
end AWA.Blogs.Tests;
|
Implement a new test to simulate a blog creation and blog post creation using HTTP requests
|
Implement a new test to simulate a blog creation and blog post creation using HTTP requests
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
|
54d9999913c0380c7b754917efbe2902d266f20d
|
src/security-auth-oauth-facebook.ads
|
src/security-auth-oauth-facebook.ads
|
-----------------------------------------------------------------------
-- security-auth-oauth-facebook -- Facebook OAuth based authentication
-- 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 Security.OAuth.Clients;
package Security.Auth.OAuth.Facebook is
-- ------------------------------
-- OAuth Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the OAuth authorization process.
type Manager is new Security.Auth.OAuth.Manager with private;
-- Verify the OAuth access token and retrieve information about the user.
overriding
procedure Verify_Access_Token (Realm : in Manager;
Assoc : in Association;
Request : in Parameters'Class;
Token : in Security.OAuth.Clients.Access_Token_Access;
Result : in out Authentication);
private
type Manager is new Security.Auth.OAuth.Manager with null record;
end Security.Auth.OAuth.Facebook;
|
Define the Facebook authentication by using OAuth and Facebook Graph API
|
Define the Facebook authentication by using OAuth and Facebook Graph API
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
|
a7f0d4fb2b3a23dc79ec0b89ff85ef2263cd54bc
|
awa/regtests/awa-commands-tests.adb
|
awa/regtests/awa-commands-tests.adb
|
-----------------------------------------------------------------------
-- awa-commands-tests -- Test the AWA.Commands
-- 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 Ada.Text_IO;
with Util.Processes;
with Util.Streams.Pipes;
with Util.Streams.Buffered;
with Util.Test_Caller;
with Util.Log.Loggers;
package body AWA.Commands.Tests is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Commands.Tests");
package Caller is new Util.Test_Caller (Test, "Commands");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Commands.Start_Stop",
Test_Start_Stop'Access);
end Add_Tests;
-- ------------------------------
-- Execute the command and get the output in a string.
-- ------------------------------
procedure Execute (T : in out Test;
Command : in String;
Input : in String;
Output : in String;
Result : out Ada.Strings.Unbounded.Unbounded_String;
Status : in Natural := 0) is
P : aliased Util.Streams.Pipes.Pipe_Stream;
Buffer : Util.Streams.Buffered.Input_Buffer_Stream;
begin
if Input'Length > 0 then
Log.Info ("Execute: {0} < {1}", Command, Input);
elsif Output'Length > 0 then
Log.Info ("Execute: {0} > {1}", Command, Output);
else
Log.Info ("Execute: {0}", Command);
end if;
P.Set_Input_Stream (Input);
P.Set_Output_Stream (Output);
P.Open (Command, Util.Processes.READ_ALL);
-- Write on the process input stream.
Result := Ada.Strings.Unbounded.Null_Unbounded_String;
Buffer.Initialize (P'Unchecked_Access, 8192);
Buffer.Read (Result);
P.Close;
Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Result));
Log.Info ("Command result: {0}", Result);
Util.Tests.Assert_Equals (T, Status, P.Get_Exit_Status, "Command '" & Command & "' failed");
end Execute;
-- ------------------------------
-- Test start and stop command.
-- ------------------------------
procedure Test_Start_Stop (T : in out Test) is
task Start_Server is
entry Start;
entry Wait (Result : out Ada.Strings.Unbounded.Unbounded_String);
end Start_Server;
task body Start_Server is
Output : Ada.Strings.Unbounded.Unbounded_String;
begin
accept Start do
null;
end Start;
begin
T.Execute ("bin/awa_command -c test-sqlite.properties start -m 26123",
"", "", Output, 0);
exception
when others =>
Output := Ada.Strings.Unbounded.To_Unbounded_String ("* exception *");
end;
accept Wait (Result : out Ada.Strings.Unbounded.Unbounded_String) do
Result := Output;
end Wait;
end Start_Server;
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
-- Launch the 'start' command in a separate task because the command will hang.
Start_Server.Start;
delay 5.0;
-- Launch the 'stop' command, this should terminate the 'start' command.
T.Execute ("bin/awa_command -c test-sqlite.properties stop -m 26123",
"", "", Result, 0);
-- Wait for the task result.
Start_Server.Wait (Result);
Util.Tests.Assert_Equals (T, "", Result, "AWA start command output");
end Test_Start_Stop;
end AWA.Commands.Tests;
|
Implement the Test_Start_Stop procedure to test the 'start' and 'stop' commands
|
Implement the Test_Start_Stop procedure to test the 'start' and 'stop' commands
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
|
212dc64f2572ebaf8163ddc09656429cc52c0223
|
src/oto-al.ads
|
src/oto-al.ads
|
pragma License (Modified_GPL);
------------------------------------------------------------------------------
-- EMAIL: <[email protected]> --
-- License: Modified GNU GPLv3 or any later as published by Free Software --
-- Foundation (GMGPL, see COPYING file). --
-- --
-- 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 System;
with Oto.Binary;
use Oto;
package Oto.AL is
---------------------------------------------------------------------------
---------------
-- T Y P E S --
---------------
---------------------------------------------------------------------------
subtype Bool is Binary.Byte;
subtype Byte is Binary.S_Byte;
subtype Chat is Binary.Byte;
subtype Enum is Binary.S_Word;
subtype Int is Integer;
subtype Short is Binary.S_Short;
subtype SizeI is Integer;
subtype UByte is Binary.Byte;
subtype UInt is Binary.Word;
subtype UShort is Binary.Short;
subtype Pointer is System.Address;
---------------------------------------------------------------------------
-----------------------
-- C O N S T A N T S --
-----------------------
---------------------------------------------------------------------------
-- "no distance model" or "no buffer"
AL_NONE : constant Enum := 0;
AL_FALSE : constant Bool := 0;
AL_TRUE : constant Bool := 1;
-- Indicate Source has relative coordinates.
AL_SOURCE_RELATIVE : constant Enum := 16#202#;
-- Directional source, inner cone angle, in degrees.
-- Range: [0-360]
-- Default: 360
AL_CONE_INNER_ANGLE : constant Enum := 16#1001#;
-- Directional source, outer cone angle, in degrees.
-- Range: [0-360]
-- Default: 360
AL_CONE_OUTER_ANGLE : constant Enum := 16#1002#;
-- Specify the pitch to be applied at source.
-- Range: [0.5-2.0]
-- Default: 1.0
AL_PITCH : constant Enum := 16#1003#;
-- Specify the current location in three dimensional space.
-- OpenAL, like OpenGL, uses a right handed coordinate system,
-- where in a frontal default view X (thumb) points right,
-- Y points up (index finger), and Z points towards the
-- viewer/camera (middle finger).
-- To switch from a left handed coordinate system, flip the
-- sign on the Z coordinate.
-- Listener position is always in the world coordinate system.
AL_POSITION : constant Enum := 16#1004#;
-- Specify the current direction.
AL_DIRECTION : constant Enum := 16#1005#;
-- Specify the current velocity in three dimensional space.
AL_VELOCITY : constant Enum := 16#1006#;
-- Indicate whether source is looping.
-- Type: ALboolean
-- Range: [AL_TRUE, AL_FALSE]
-- Default: FALSE.
AL_LOOPING : constant Enum := 16#1007#;
-- Indicate the buffer to provide sound samples.
-- Type: ALuint.
-- Range: any valid Buffer id.
AL_BUFFER : constant Enum := 16#1009#;
-- Indicate the gain (volume amplification) applied.
-- Type: Float.
-- Range: ]0.0- ]
-- A value of 1.0 means un-attenuated/unchanged.
-- Each division by 2 equals an attenuation of -6dB.
-- Each multiplicaton with 2 equals an amplification of +6dB.
-- A value of 0.0 is meaningless with respect to a logarithmic
-- scale; it is interpreted as zero volume - the channel
-- is effectively disabled.
AL_GAIN : constant Enum := 16#100A#;
-- Indicate minimum source attenuation
-- Type: Float
-- Range: [0.0 - 1.0]
--
-- Logarthmic
AL_MIN_GAIN : constant Enum := 16#100D#;
-- Indicate maximum source attenuation
-- Type: Float
-- Range: [0.0 - 1.0]
--
-- Logarthmic
AL_MAX_GAIN : constant Enum := 16#100E#;
-- Indicate listener orientation.
--
-- at/up
AL_ORIENTATION : constant Enum := 16#100F#;
-- Source state information.
AL_SOURCE_STATE : constant Enum := 16#1010#;
AL_INITIAL : constant Enum := 16#1011#;
AL_PLAYING : constant Enum := 16#1012#;
AL_PAUSED : constant Enum := 16#1013#;
AL_STOPPED : constant Enum := 16#1014#;
-- Buffer Queue params
AL_BUFFERS_QUEUED : constant Enum := 16#1015#;
AL_BUFFERS_PROCESSED : constant Enum := 16#1016#;
-- Source buffer position information
AL_SEC_OFFSET : constant Enum := 16#1024#;
AL_SAMPLE_OFFSET : constant Enum := 16#1025#;
AL_BYTE_OFFSET : constant Enum := 16#1026#;
-- Source type (Static, Streaming or undetermined)
-- Source is Static if a Buffer has been attached using AL_BUFFER
-- Source is Streaming if one or more Buffers have been attached using alSourceQueueBuffers
-- Source is undetermined when it has the NULL buffer attached
AL_SOURCE_TYPE : constant Enum := 16#1027#;
AL_STATIC : constant Enum := 16#1028#;
AL_STREAMING : constant Enum := 16#1029#;
AL_UNDETERMINED : constant Enum := 16#1030#;
-- Sound samples: format specifier.
AL_FORMAT_MONO8 : constant Enum := 16#1100#;
AL_FORMAT_MONO16 : constant Enum := 16#1101#;
AL_FORMAT_STEREO8 : constant Enum := 16#1102#;
AL_FORMAT_STEREO16 : constant Enum := 16#1103#;
-- source specific reference distance
-- Type: Float
-- Range: 0.0 - +inf
--
-- At 0.0, no distance attenuation occurs. Default is 1.0.
AL_REFERENCE_DISTANCE : constant Enum := 16#1020#;
-- source specific rolloff factor
-- Type: Float
-- Range: 0.0 - +inf
AL_ROLLOFF_FACTOR : constant Enum := 16#1021#;
-- Directional source, outer cone gain.
--
-- Default: 0.0
-- Range: [0.0 - 1.0]
-- Logarithmic
AL_CONE_OUTER_GAIN : constant Enum := 16#1022#;
-- Indicate distance above which sources are not
-- attenuated using the inverse clamped distance model.
--
-- Default: +inf
-- Type: Float
-- Range: 0.0 - +inf
AL_MAX_DISTANCE : constant Enum := 16#1023#;
-- Sound samples: frequency, in units of Hertz [Hz].
-- This is the number of samples per second. Half of the
-- sample frequency marks the maximum significant
-- frequency component.
AL_FREQUENCY : constant Enum := 16#2001#;
AL_BITS : constant Enum := 16#2002#;
AL_CHANNELS : constant Enum := 16#2003#;
AL_SIZE : constant Enum := 16#2004#;
-- Buffer state.
--
-- Not supported for public use (yet).
AL_UNUSED : constant Enum := 16#2010#;
AL_PENDING : constant Enum := 16#2011#;
AL_PROCESSED : constant Enum := 16#2012#;
-- Errors: No Error.
AL_NO_ERROR : constant Enum := 0;
-- Invalid Name paramater passed to AL call.
AL_INVALID_NAME : constant Enum := 16#A001#;
-- Invalid parameter passed to AL call.
AL_INVALID_ENUM : constant Enum := 16#A002#;
-- Invalid enum parameter value.
AL_INVALID_VALUE : constant Enum := 16#A003#;
-- Illegal call.
AL_INVALID_OPERATION : constant Enum := 16#A004#;
-- No mojo.
AL_OUT_OF_MEMORY : constant Enum := 16#A005#;
-- Context strings: Vendor Name.
AL_VENDOR : constant Enum := 16#B001#;
AL_VERSION : constant Enum := 16#B002#;
AL_RENDERER : constant Enum := 16#B003#;
AL_EXTENSIONS : constant Enum := 16#B004#;
-- Doppler scale. Default 1.0
AL_DOPPLER_FACTOR : constant Enum := 16#C000#;
-- Tweaks speed of propagation.
AL_DOPPLER_VELOCITY : constant Enum := 16#C001#;
-- Speed of Sound in units per second
AL_SPEED_OF_SOUND : constant Enum := 16#C003#;
-- Distance models
--
-- used in conjunction with DistanceModel
--
-- implicit: NONE, which disances distance attenuation.
AL_DISTANCE_MODEL : constant Enum := 16#D000#;
AL_INVERSE_DISTANCE : constant Enum := 16#D001#;
AL_INVERSE_DISTANCE_CLAMPED : constant Enum := 16#D002#;
AL_LINEAR_DISTANCE : constant Enum := 16#D003#;
AL_LINEAR_DISTANCE_CLAMPED : constant Enum := 16#D004#;
AL_EXPONENT_DISTANCE : constant Enum := 16#D005#;
AL_EXPONENT_DISTANCE_CLAMPED : constant Enum := 16#D006#;
---------------------------------------------------------------------------
end Oto.AL;
|
Define constants.
|
AL: Define constants.
Signed-off-by: darkestkhan <[email protected]>
|
Ada
|
isc
|
darkestkhan/oto
|
|
01ab96168aa12c90566a25cef81408cebd78f9ee
|
mat/src/gtk/mat-consoles-gtkmat.ads
|
mat/src/gtk/mat-consoles-gtkmat.ads
|
-----------------------------------------------------------------------
-- mat-consoles-text - Text console interface
-- 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.Text_IO;
with Glib;
with Gtk.Frame;
with Gtk.List_Store;
with Gtk.Tree_Model;
with Gtk.Cell_Renderer_Text;
with Gtk.Tree_View;
package MAT.Consoles.Gtkmat is
type Console_Type is new MAT.Consoles.Console_Type with private;
type Console_Type_Access is access all Console_Type'Class;
-- Initialize the console to display the result in the Gtk frame.
procedure Initialize (Console : in out Console_Type;
Frame : in Gtk.Frame.Gtk_Frame);
-- Report a notice message.
overriding
procedure Notice (Console : in out Console_Type;
Kind : in Notice_Type;
Message : in String);
-- Report an error message.
overriding
procedure Error (Console : in out Console_Type;
Message : in String);
-- Print the field value for the given field.
overriding
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in String);
-- Print the title for the given field.
overriding
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String);
-- Start a new title in a report.
overriding
procedure Start_Title (Console : in out Console_Type);
-- Finish a new title in a report.
procedure End_Title (Console : in out Console_Type);
-- Start a new row in a report.
overriding
procedure Start_Row (Console : in out Console_Type);
-- Finish a new row in a report.
overriding
procedure End_Row (Console : in out Console_Type);
private
type Column_Type is record
Field : Field_Type;
Title : Ada.Strings.Unbounded.Unbounded_String;
end record;
type Column_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Column_Type;
type Field_Index_Array is array (Field_Type) of Glib.Gint;
type Console_Type is new MAT.Consoles.Console_Type with record
Frame : Gtk.Frame.Gtk_Frame;
-- Model : Gtk.Tree_Model.Gtk_Tree_Model;
List : Gtk.List_Store.Gtk_List_Store;
Current_Row : Gtk.Tree_Model.Gtk_Tree_Iter;
File : Ada.Text_IO.File_Type;
Indexes : Field_Index_Array;
Columns : Column_Array;
Tree : Gtk.Tree_View.Gtk_Tree_View;
Col_Text : Gtk.Cell_Renderer_Text.Gtk_Cell_renderer_Text;
end record;
end MAT.Consoles.Gtkmat;
|
Define the MAT.Consoles.Gtkmat package with support for a console output in Gtk
|
Define the MAT.Consoles.Gtkmat package with support for a console output in Gtk
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
|
e3e7db4e570d0c643ce2d9a5867ee7e65f466822
|
src/util-properties-bundles.adb
|
src/util-properties-bundles.adb
|
-----------------------------------------------------------------------
-- properties -- Generic name/value property management
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 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 Ada.Unchecked_Deallocation;
with Ada.Unchecked_Conversion;
with Ada.Directories;
with Ada.Containers.Vectors;
with Ada.Strings.Fixed;
with Util.Log.Loggers;
package body Util.Properties.Bundles is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Util.Properties.Bundles");
procedure Free is
new Ada.Unchecked_Deallocation (Manager'Class,
Bundle_Manager_Access);
procedure Free is
new Ada.Unchecked_Deallocation (String,
Util.Strings.String_Access);
-- Implementation of the Bundle
-- (this allows to decouples the implementation from the API)
package Interface_P is
type Manager is new Util.Properties.Interface_P.Manager with private;
type Manager_Object_Access is access all Manager;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager; Name : in Value)
return Boolean;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager; Name : in Value)
return Value;
procedure Insert (Self : in out Manager; Name : in Value;
Item : in Value);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager; Name : in Value;
Item : in Value);
-- Remove the property given its name.
procedure Remove (Self : in out Manager; Name : in Value);
procedure Load_Properties (Self : in out Manager;
File : in String);
-- Deep copy of properties stored in 'From' to 'To'.
function Create_Copy (Self : in Manager)
return Util.Properties.Interface_P.Manager_Access;
procedure Delete (Self : in Manager;
Obj : in out Util.Properties.Interface_P.Manager_Access);
function Get_Names (Self : in Manager;
Prefix : in String) return Name_Array;
procedure Add_Bundle (Self : in out Manager;
Props : in Util.Properties.Manager_Access);
private
use type Util.Properties.Manager_Access;
package PropertyList is new Ada.Containers.Vectors
(Element_Type => Util.Properties.Manager_Access,
Index_Type => Natural,
"=" => "=");
type Manager is new Util.Properties.Interface_P.Manager with record
List : PropertyList.Vector;
Props : aliased Util.Properties.Manager;
end record;
procedure Free is
new Ada.Unchecked_Deallocation (Manager,
Manager_Object_Access);
end Interface_P;
procedure Add_Bundle (Self : in out Manager;
Props : in Manager_Access) is
use type Util.Properties.Interface_P.Manager_Access;
begin
Interface_P.Manager'Class (Self.Impl.all).Add_Bundle (Props);
end Add_Bundle;
procedure Initialize (Object : in out Manager) is
use Util.Properties.Interface_P;
begin
Object.Impl := new Util.Properties.Bundles.Interface_P.Manager;
Object.Impl.Count := 1;
end Initialize;
procedure Adjust (Object : in out Manager) is
use Util.Properties.Interface_P;
begin
if Object.Impl /= null then
Object.Impl.Count := Object.Impl.Count + 1;
else
Object.Impl := new Util.Properties.Bundles.Interface_P.Manager;
Object.Impl.Count := 1;
end if;
end Adjust;
-- ------------------------------
-- Initialize the bundle factory and specify where the property files are stored.
-- ------------------------------
procedure Initialize (Factory : in out Loader;
Path : in String) is
begin
Log.Info ("Initialize bundle factory to load from {0}", Path);
Factory.Path := To_Unbounded_String (Path);
end Initialize;
-- ------------------------------
-- Load the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Load_Bundle (Factory : in out Loader;
Name : in String;
Locale : in String;
Bundle : out Manager'Class) is
Found : Boolean := False;
begin
Log.Info ("Load bundle {0} for language {1}", Name, Locale);
Find_Bundle (Factory, Name, Locale, Bundle, Found);
if not Found then
Load_Bundle (Factory, Name, Found);
if not Found then
Log.Error ("Bundle {0} not found", Name);
raise NO_BUNDLE with "No bundle '" & Name & "'";
end if;
Find_Bundle (Factory, Name, Locale, Bundle, Found);
if not Found then
Log.Error ("Bundle {0} not found", Name);
raise NO_BUNDLE with "No bundle '" & Name & "'";
end if;
end if;
end Load_Bundle;
-- ------------------------------
-- Find the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Find_Bundle (Factory : in out Loader;
Name : in String;
Locale : in String;
Bundle : out Manager'Class;
Found : out Boolean) is
use Ada.Strings;
use type Util.Properties.Manager_Access;
Loc_Name : constant String := '_' & Locale;
Last_Pos : Natural := Loc_Name'Last;
begin
Log.Info ("Looking for bundle {0} and language {1}", Name, Locale);
Found := False;
Factory.Lock.Read;
declare
Pos : Bundle_Map.Cursor;
begin
while Last_Pos >= Loc_Name'First loop
declare
Bundle_Name : aliased constant String
:= Name & Loc_Name (Loc_Name'First .. Last_Pos);
begin
Pos := Factory.Bundles.Find (Bundle_Name'Unrestricted_Access);
if Bundle_Map.Has_Element (Pos) then
Bundle.Finalize;
Bundle.Impl := Bundle_Map.Element (Pos).Impl;
Bundle.Impl.Count := Bundle.Impl.Count + 1;
Found := True;
exit;
end if;
end;
if Last_Pos > Loc_Name'First then
Last_Pos := Fixed.Index (Loc_Name, "_", Last_Pos - 1, Backward);
else
Last_Pos := Last_Pos - 1;
end if;
end loop;
exception
when others =>
Factory.Lock.Release_Read;
raise;
end;
Factory.Lock.Release_Read;
end Find_Bundle;
-- ------------------------------
-- Load the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Load_Bundle (Factory : in out Loader;
Name : in String;
Found : out Boolean) is
use Ada.Directories;
use Ada.Strings;
use Util.Strings;
use Ada.Containers;
use Util.Strings.String_Set;
use Bundle_Map;
Path : constant String := To_String (Factory.Path);
Filter : constant Filter_Type := (Ordinary_File => True, others => False);
Pattern : constant String := Name & "*.properties";
Ent : Directory_Entry_Type;
Names : Util.Strings.String_Set.Set;
Search : Search_Type;
begin
Log.Info ("Reading bundle {1} in directory {0}", Path, Name);
Found := False;
Start_Search (Search, Directory => Path,
Pattern => Pattern, Filter => Filter);
Factory.Lock.Write;
begin
-- Scan the directory and load all the property files.
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Simple : constant String := Simple_Name (Ent);
File_Path : constant String := Full_Name (Ent);
Bundle : constant Bundle_Manager_Access := new Manager;
Bundle_Name : constant Name_Access
:= new String '(Simple (Simple'First .. Simple'Last - 11));
begin
Log.Debug ("Loading file {0}", File_Path);
Interface_P.Manager'Class (Bundle.Impl.all).Load_Properties (File_Path);
Factory.Bundles.Include (Key => Bundle_Name, New_Item => Bundle);
Found := True;
Names.Insert (Bundle_Name);
end;
end loop;
-- Link the property files to implement the localization default rules.
while Names.Length > 0 loop
declare
Name_Pos : String_Set.Cursor := Names.First;
Bundle_Name : constant Name_Access := String_Set.Element (Name_Pos);
Idx : Natural := Fixed.Index (Bundle_Name.all, "_", Backward);
Bundle_Pos : constant Bundle_Map.Cursor := Factory.Bundles.Find (Bundle_Name);
Bundle : constant Bundle_Manager_Access := Element (Bundle_Pos);
begin
Names.Delete (Name_Pos);
-- Associate the property bundle to the first existing parent
-- Ex: message_fr_CA -> message_fr
-- message_fr_CA -> message
while Idx > 0 loop
declare
Name : aliased constant String
:= Bundle_Name (Bundle_Name'First .. Idx - 1);
Pos : constant Bundle_Map.Cursor
:= Factory.Bundles.Find (Name'Unchecked_Access);
begin
if Bundle_Map.Has_Element (Pos) then
Bundle.Add_Bundle (Bundle_Map.Element (Pos).all'Access);
Idx := 0;
else
Idx := Fixed.Index (Bundle_Name.all, "_", Idx - 1, Backward);
end if;
end;
end loop;
end;
end loop;
exception
when others =>
Factory.Lock.Release_Write;
raise;
end;
Factory.Lock.Release_Write;
exception
when Name_Error =>
Log.Error ("Cannot read directory: {0}", Path);
end Load_Bundle;
-- Implementation of the Bundle
-- (this allows to decouples the implementation from the API)
package body Interface_P is
use PropertyList;
-- ------------------------------
-- Returns TRUE if the property exists.
-- ------------------------------
function Exists (Self : in Manager; Name : in Value)
return Boolean is
Iter : Cursor := Self.List.First;
begin
if Self.Props.Exists (Name) then
return True;
end if;
while Has_Element (Iter) loop
if Element (Iter).Exists (Name) then
return True;
end if;
Iter := Next (Iter);
end loop;
return False;
end Exists;
-- ------------------------------
-- Returns the property value. Raises an exception if not found.
-- ------------------------------
function Get (Self : in Manager; Name : in Value)
return Value is
begin
return Self.Props.Get (Name);
exception
when NO_PROPERTY =>
declare
Iter : Cursor := Self.List.First;
begin
while Has_Element (Iter) loop
begin
return Element (Iter).all.Get (Name);
exception
when NO_PROPERTY =>
Iter := Next (Iter);
end;
end loop;
end;
raise;
end Get;
procedure Load_Properties (Self : in out Manager;
File : in String) is
begin
Self.Props.Load_Properties (File);
end Load_Properties;
procedure Insert (Self : in out Manager;
Name : in Value;
Item : in Value) is
pragma Unreferenced (Self);
pragma Unreferenced (Name);
pragma Unreferenced (Item);
begin
raise NOT_WRITEABLE with "Bundle is readonly";
end Insert;
-- ------------------------------
-- Set the value of the property. The property is created if it
-- does not exists.
-- ------------------------------
procedure Set (Self : in out Manager;
Name : in Value;
Item : in Value) is
begin
raise NOT_WRITEABLE with "Bundle is readonly";
end Set;
-- ------------------------------
-- Remove the property given its name.
-- ------------------------------
procedure Remove (Self : in out Manager; Name : in Value) is
begin
raise NOT_WRITEABLE with "Bundle is readonly";
end Remove;
-- ------------------------------
-- Deep copy of properties stored in 'From' to 'To'.
-- ------------------------------
function Create_Copy (Self : in Manager)
return Util.Properties.Interface_P.Manager_Access is
pragma Unreferenced (Self);
begin
return null;
end Create_Copy;
procedure Delete (Self : in Manager;
Obj : in out Util.Properties.Interface_P.Manager_Access) is
pragma Unreferenced (Self);
Item : Manager_Object_Access := Manager (Obj.all)'Access;
begin
Free (Item);
end Delete;
function Get_Names (Self : in Manager;
Prefix : in String) return Name_Array is
Result : Name_Array (1 .. 2);
Iter : Cursor := Self.List.First;
begin
while Has_Element (Iter) loop
declare
N : constant Name_Array := Element (Iter).Get_Names (Prefix);
begin
return N;
end;
Iter := Next (Iter);
end loop;
return Result;
end Get_Names;
procedure Add_Bundle (Self : in out Manager;
Props : in Util.Properties.Manager_Access) is
begin
Self.List.Append (Props);
end Add_Bundle;
end Interface_P;
-- ------------------------------
-- Clear the bundle cache
-- ------------------------------
procedure Clear_Cache (Factory : in out Loader) is
use Util.Strings;
use Bundle_Map;
function To_String_Access is
new Ada.Unchecked_Conversion (Source => Util.Strings.Name_Access,
Target => Util.Strings.String_Access);
begin
Log.Info ("Clearing bundle cache");
Factory.Lock.Write;
loop
declare
Pos : Bundle_Map.Cursor := Factory.Bundles.First;
Name : Util.Strings.String_Access;
Node : Bundle_Manager_Access;
begin
exit when not Has_Element (Pos);
Node := Element (Pos);
Name := To_String_Access (Key (Pos));
Factory.Bundles.Delete (Pos);
Free (Node);
Free (Name);
end;
end loop;
Factory.Lock.Release_Write;
end Clear_Cache;
-- ------------------------------
-- Finalize the bundle loader and clear the cache
-- ------------------------------
procedure Finalize (Factory : in out Loader) is
begin
Clear_Cache (Factory);
end Finalize;
end Util.Properties.Bundles;
|
-----------------------------------------------------------------------
-- properties -- Generic name/value property management
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 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 Ada.Unchecked_Deallocation;
with Ada.Unchecked_Conversion;
with Ada.Directories;
with Ada.Containers.Vectors;
with Ada.Strings.Fixed;
with Util.Log.Loggers;
package body Util.Properties.Bundles is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Util.Properties.Bundles");
procedure Free is
new Ada.Unchecked_Deallocation (Manager'Class,
Bundle_Manager_Access);
procedure Free is
new Ada.Unchecked_Deallocation (String,
Util.Strings.String_Access);
-- Implementation of the Bundle
-- (this allows to decouples the implementation from the API)
package Interface_P is
type Manager is new Util.Properties.Interface_P.Manager with private;
type Manager_Object_Access is access all Manager;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager; Name : in Value)
return Boolean;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager; Name : in Value)
return Value;
procedure Insert (Self : in out Manager; Name : in Value;
Item : in Value);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager; Name : in Value;
Item : in Value);
-- Remove the property given its name.
procedure Remove (Self : in out Manager; Name : in Value);
procedure Load_Properties (Self : in out Manager;
File : in String);
-- Deep copy of properties stored in 'From' to 'To'.
function Create_Copy (Self : in Manager)
return Util.Properties.Interface_P.Manager_Access;
procedure Delete (Self : in Manager;
Obj : in out Util.Properties.Interface_P.Manager_Access);
function Get_Names (Self : in Manager;
Prefix : in String) return Name_Array;
procedure Add_Bundle (Self : in out Manager;
Props : in Util.Properties.Manager_Access);
private
use type Util.Properties.Manager_Access;
package PropertyList is new Ada.Containers.Vectors
(Element_Type => Util.Properties.Manager_Access,
Index_Type => Natural,
"=" => "=");
type Manager is new Util.Properties.Interface_P.Manager with record
List : PropertyList.Vector;
Props : aliased Util.Properties.Manager;
end record;
procedure Free is
new Ada.Unchecked_Deallocation (Manager,
Manager_Object_Access);
end Interface_P;
procedure Add_Bundle (Self : in out Manager;
Props : in Manager_Access) is
use type Util.Properties.Interface_P.Manager_Access;
begin
Interface_P.Manager'Class (Self.Impl.all).Add_Bundle (Props);
end Add_Bundle;
procedure Initialize (Object : in out Manager) is
use Util.Properties.Interface_P;
begin
Object.Impl := new Util.Properties.Bundles.Interface_P.Manager;
Object.Impl.Count := 1;
end Initialize;
procedure Adjust (Object : in out Manager) is
use Util.Properties.Interface_P;
begin
if Object.Impl /= null then
Object.Impl.Count := Object.Impl.Count + 1;
else
Object.Impl := new Util.Properties.Bundles.Interface_P.Manager;
Object.Impl.Count := 1;
end if;
end Adjust;
-- ------------------------------
-- Initialize the bundle factory and specify where the property files are stored.
-- ------------------------------
procedure Initialize (Factory : in out Loader;
Path : in String) is
begin
Log.Info ("Initialize bundle factory to load from {0}", Path);
Factory.Path := To_Unbounded_String (Path);
end Initialize;
-- ------------------------------
-- Load the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Load_Bundle (Factory : in out Loader;
Name : in String;
Locale : in String;
Bundle : out Manager'Class) is
Found : Boolean := False;
begin
Log.Info ("Load bundle {0} for language {1}", Name, Locale);
Find_Bundle (Factory, Name, Locale, Bundle, Found);
if not Found then
Load_Bundle (Factory, Name, Found);
if not Found then
Log.Error ("Bundle {0} not found", Name);
raise NO_BUNDLE with "No bundle '" & Name & "'";
end if;
Find_Bundle (Factory, Name, Locale, Bundle, Found);
if not Found then
Log.Error ("Bundle {0} not found", Name);
raise NO_BUNDLE with "No bundle '" & Name & "'";
end if;
end if;
end Load_Bundle;
-- ------------------------------
-- Find the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Find_Bundle (Factory : in out Loader;
Name : in String;
Locale : in String;
Bundle : out Manager'Class;
Found : out Boolean) is
use Ada.Strings;
use type Util.Properties.Manager_Access;
Loc_Name : constant String := '_' & Locale;
Last_Pos : Natural := Loc_Name'Last;
begin
Log.Info ("Looking for bundle {0} and language {1}", Name, Locale);
Found := False;
Factory.Lock.Read;
declare
Pos : Bundle_Map.Cursor;
begin
while Last_Pos >= Loc_Name'First loop
declare
Bundle_Name : aliased constant String
:= Name & Loc_Name (Loc_Name'First .. Last_Pos);
begin
Pos := Factory.Bundles.Find (Bundle_Name'Unrestricted_Access);
if Bundle_Map.Has_Element (Pos) then
Bundle.Finalize;
Bundle.Impl := Bundle_Map.Element (Pos).Impl;
Bundle.Impl.Count := Bundle.Impl.Count + 1;
Found := True;
exit;
end if;
end;
if Last_Pos > Loc_Name'First then
Last_Pos := Fixed.Index (Loc_Name, "_", Last_Pos - 1, Backward);
else
Last_Pos := Last_Pos - 1;
end if;
end loop;
exception
when others =>
Factory.Lock.Release_Read;
raise;
end;
Factory.Lock.Release_Read;
end Find_Bundle;
-- ------------------------------
-- Load the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Load_Bundle (Factory : in out Loader;
Name : in String;
Found : out Boolean) is
use Ada.Directories;
use Ada.Strings;
use Util.Strings;
use Ada.Containers;
use Util.Strings.String_Set;
use Bundle_Map;
Path : constant String := To_String (Factory.Path);
Filter : constant Filter_Type := (Ordinary_File => True, others => False);
Pattern : constant String := Name & "*.properties";
Ent : Directory_Entry_Type;
Names : Util.Strings.String_Set.Set;
Search : Search_Type;
begin
Log.Info ("Reading bundle {1} in directory {0}", Path, Name);
Found := False;
Start_Search (Search, Directory => Path,
Pattern => Pattern, Filter => Filter);
Factory.Lock.Write;
begin
-- Scan the directory and load all the property files.
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Simple : constant String := Simple_Name (Ent);
File_Path : constant String := Full_Name (Ent);
Bundle : constant Bundle_Manager_Access := new Manager;
Bundle_Name : constant Name_Access
:= new String '(Simple (Simple'First .. Simple'Last - 11));
begin
Log.Debug ("Loading file {0}", File_Path);
Interface_P.Manager'Class (Bundle.Impl.all).Load_Properties (File_Path);
Factory.Bundles.Include (Key => Bundle_Name, New_Item => Bundle);
Found := True;
Names.Insert (Bundle_Name);
end;
end loop;
-- Link the property files to implement the localization default rules.
while Names.Length > 0 loop
declare
Name_Pos : String_Set.Cursor := Names.First;
Bundle_Name : constant Name_Access := String_Set.Element (Name_Pos);
Idx : Natural := Fixed.Index (Bundle_Name.all, "_", Backward);
Bundle_Pos : constant Bundle_Map.Cursor := Factory.Bundles.Find (Bundle_Name);
Bundle : constant Bundle_Manager_Access := Element (Bundle_Pos);
begin
Names.Delete (Name_Pos);
-- Associate the property bundle to the first existing parent
-- Ex: message_fr_CA -> message_fr
-- message_fr_CA -> message
while Idx > 0 loop
declare
Name : aliased constant String
:= Bundle_Name (Bundle_Name'First .. Idx - 1);
Pos : constant Bundle_Map.Cursor
:= Factory.Bundles.Find (Name'Unchecked_Access);
begin
if Bundle_Map.Has_Element (Pos) then
Bundle.Add_Bundle (Bundle_Map.Element (Pos).all'Access);
Idx := 0;
else
Idx := Fixed.Index (Bundle_Name.all, "_", Idx - 1, Backward);
end if;
end;
end loop;
end;
end loop;
exception
when others =>
Factory.Lock.Release_Write;
raise;
end;
Factory.Lock.Release_Write;
exception
when Name_Error =>
Log.Error ("Cannot read directory: {0}", Path);
end Load_Bundle;
-- Implementation of the Bundle
-- (this allows to decouples the implementation from the API)
package body Interface_P is
use PropertyList;
-- ------------------------------
-- Returns TRUE if the property exists.
-- ------------------------------
function Exists (Self : in Manager; Name : in Value)
return Boolean is
Iter : Cursor := Self.List.First;
begin
if Self.Props.Exists (Name) then
return True;
end if;
while Has_Element (Iter) loop
if Element (Iter).Exists (Name) then
return True;
end if;
Iter := Next (Iter);
end loop;
return False;
end Exists;
-- ------------------------------
-- Returns the property value. Raises an exception if not found.
-- ------------------------------
function Get (Self : in Manager; Name : in Value)
return Value is
begin
return Self.Props.Get (Name);
exception
when NO_PROPERTY =>
declare
Iter : Cursor := Self.List.First;
begin
while Has_Element (Iter) loop
begin
return Element (Iter).all.Get (Name);
exception
when NO_PROPERTY =>
Iter := Next (Iter);
end;
end loop;
end;
raise;
end Get;
procedure Load_Properties (Self : in out Manager;
File : in String) is
begin
Self.Props.Load_Properties (File);
end Load_Properties;
procedure Insert (Self : in out Manager;
Name : in Value;
Item : in Value) is
pragma Unreferenced (Self);
pragma Unreferenced (Name);
pragma Unreferenced (Item);
begin
raise NOT_WRITEABLE with "Bundle is readonly";
end Insert;
-- ------------------------------
-- Set the value of the property. The property is created if it
-- does not exists.
-- ------------------------------
procedure Set (Self : in out Manager;
Name : in Value;
Item : in Value) is
begin
raise NOT_WRITEABLE with "Bundle is readonly";
end Set;
-- ------------------------------
-- Remove the property given its name.
-- ------------------------------
procedure Remove (Self : in out Manager; Name : in Value) is
begin
raise NOT_WRITEABLE with "Bundle is readonly";
end Remove;
-- ------------------------------
-- Deep copy of properties stored in 'From' to 'To'.
-- ------------------------------
function Create_Copy (Self : in Manager)
return Util.Properties.Interface_P.Manager_Access is
pragma Unreferenced (Self);
begin
return null;
end Create_Copy;
procedure Delete (Self : in Manager;
Obj : in out Util.Properties.Interface_P.Manager_Access) is
pragma Unreferenced (Self);
Item : Manager_Object_Access := Manager (Obj.all)'Access;
begin
Free (Item);
end Delete;
function Get_Names (Self : in Manager;
Prefix : in String) return Name_Array is
Result : Name_Array (1 .. 2);
Iter : Cursor := Self.List.First;
begin
while Has_Element (Iter) loop
declare
M : constant Util.Properties.Manager_Access := Element (Iter);
N : constant Name_Array := M.Get_Names (Prefix);
begin
return N;
end;
Iter := Next (Iter);
end loop;
return Result;
end Get_Names;
procedure Add_Bundle (Self : in out Manager;
Props : in Util.Properties.Manager_Access) is
begin
Self.List.Append (Props);
end Add_Bundle;
end Interface_P;
-- ------------------------------
-- Clear the bundle cache
-- ------------------------------
procedure Clear_Cache (Factory : in out Loader) is
use Util.Strings;
use Bundle_Map;
function To_String_Access is
new Ada.Unchecked_Conversion (Source => Util.Strings.Name_Access,
Target => Util.Strings.String_Access);
begin
Log.Info ("Clearing bundle cache");
Factory.Lock.Write;
loop
declare
Pos : Bundle_Map.Cursor := Factory.Bundles.First;
Name : Util.Strings.String_Access;
Node : Bundle_Manager_Access;
begin
exit when not Has_Element (Pos);
Node := Element (Pos);
Name := To_String_Access (Key (Pos));
Factory.Bundles.Delete (Pos);
Free (Node);
Free (Name);
end;
end loop;
Factory.Lock.Release_Write;
end Clear_Cache;
-- ------------------------------
-- Finalize the bundle loader and clear the cache
-- ------------------------------
procedure Finalize (Factory : in out Loader) is
begin
Clear_Cache (Factory);
end Finalize;
end Util.Properties.Bundles;
|
Fix compilation with gcc 4.4.1
|
Fix compilation with gcc 4.4.1
|
Ada
|
apache-2.0
|
flottokarotto/ada-util,Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util
|
e0d2a6721eb09f35a1a70c2761e02805c5807b92
|
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
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
|
851dd878c9fe4890784be9c96e81000711429de6
|
regtests/asf-navigations-tests.adb
|
regtests/asf-navigations-tests.adb
|
-----------------------------------------------------------------------
-- asf-navigations-tests - Tests for ASF navigation
-- 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.Beans.Objects;
with ASF.Tests;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Applications.Main;
with ASF.Applications.Main.Configs;
with ASF.Applications.Tests;
package body ASF.Navigations.Tests is
use Util.Beans.Objects;
use ASF.Tests;
package Caller is new Util.Test_Caller (Test, "Navigations");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test navigation exact match (view, outcome, action)",
Test_Exact_Navigation'Access);
Caller.Add_Test (Suite, "Test navigation partial match (view, outcome)",
Test_Partial_Navigation'Access);
Caller.Add_Test (Suite, "Test navigation exception match (view, outcome)",
Test_Exception_Navigation'Access);
end Add_Tests;
-- ------------------------------
-- Initialize the test application
-- ------------------------------
overriding
procedure Set_Up (T : in out Test) is
pragma Unreferenced (T);
use type ASF.Applications.Main.Application_Access;
Fact : ASF.Applications.Main.Application_Factory;
begin
if ASF.Tests.Get_Application = null then
ASF.Tests.Initialize (Util.Tests.Get_Properties, Factory => Fact);
end if;
end Set_Up;
-- ------------------------------
-- Check the navigation for an URI and expect the result to match the regular expression.
-- ------------------------------
procedure Check_Navigation (T : in out Test;
Name : in String;
Match : in String;
Raise_Flag : in Boolean := False) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Form : aliased ASF.Applications.Tests.Form_Bean;
File : constant String := Util.Tests.Get_Path ("regtests/config/test-navigations.xml");
begin
Form.Perm_Error := Raise_Flag;
ASF.Applications.Main.Configs.Read_Configuration (ASF.Tests.Get_Application.all, File);
Request.Set_Attribute ("form", To_Object (Value => Form'Unchecked_Access,
Storage => STATIC));
Do_Get (Request, Reply, "/tests/" & Name & ".html", Name & ".txt");
Request.Set_Parameter ("formText", "1");
Request.Set_Parameter ("name", "John");
Request.Set_Parameter ("password", "12345");
Request.Set_Parameter ("email", "[email protected]");
Request.Set_Parameter ("ok", "1");
Do_Post (Request, Reply, "/tests/" & Name & ".html", Name & "form-navigation-exact.txt");
Assert_Matches (T, Match,
Reply, "Wrong generated content");
end Check_Navigation;
-- ------------------------------
-- Test a form navigation with an exact match (view, outcome, action).
-- ------------------------------
procedure Test_Exact_Navigation (T : in out Test) is
begin
T.Check_Navigation ("form-nav", ".*success.*");
end Test_Exact_Navigation;
-- ------------------------------
-- Test a form navigation with a partial match (view, outcome).
-- ------------------------------
procedure Test_Partial_Navigation (T : in out Test) is
begin
T.Check_Navigation ("form-nav-partial", ".*success partial.*");
end Test_Partial_Navigation;
-- ------------------------------
-- Test a form navigation with a exception match (view, outcome).
-- ------------------------------
procedure Test_Exception_Navigation (T : in out Test) is
begin
T.Check_Navigation ("form-nav-exception", ".*success exception.*", True);
end Test_Exception_Navigation;
end ASF.Navigations.Tests;
|
Add navigation rule unit test
|
Add navigation rule unit test
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
|
866ec1da9f3f29a17d5e31b46d459700266f2bb0
|
src/wiki-parsers-google.ads
|
src/wiki-parsers-google.ads
|
-----------------------------------------------------------------------
-- wiki-parsers-google -- Google Code parser operations
-- Copyright (C) 2011 - 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 Wiki.Parsers.Common;
private package Wiki.Parsers.Google is
pragma Preelaborate;
Wiki_Table : aliased constant Parser_Table
:= (
16#0A# => Parse_End_Line'Access,
16#0D# => Parse_End_Line'Access,
Character'Pos (' ') => Parse_Space'Access,
Character'Pos ('=') => Common.Parse_Header'Access,
Character'Pos ('*') => Common.Parse_Single_Bold'Access,
Character'Pos ('_') => Common.Parse_Single_Italic'Access,
Character'Pos ('`') => Common.Parse_Single_Code'Access,
Character'Pos ('^') => Common.Parse_Single_Superscript'Access,
Character'Pos ('~') => Common.Parse_Double_Strikeout'Access,
Character'Pos (',') => Common.Parse_Double_Subscript'Access,
Character'Pos ('[') => Common.Parse_Link'Access,
Character'Pos ('\') => Common.Parse_Line_Break'Access,
Character'Pos ('#') => Common.Parse_List'Access,
Character'Pos ('{') => Common.Parse_Preformatted'Access,
Character'Pos ('}') => Common.Parse_Preformatted'Access,
Character'Pos ('<') => Parse_Maybe_Html'Access,
others => Parse_Text'Access
);
end Wiki.Parsers.Google;
|
move the Google code wiki parser definition in a separate child package
|
Refactor: move the Google code wiki parser definition in a separate child package
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
|
1305b95588f176f6b38e99b9d31d94178fbd8cd6
|
src/asis/a4g-a_alloc.ads
|
src/asis/a4g-a_alloc.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . A _ A L L O C --
-- --
-- S p e c --
-- --
-- Version : 1.00 --
-- --
-- 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). --
-- --
------------------------------------------------------------------------------
package A4G.A_Alloc is
-- This package contains definitions for initial sizes and growth increments
-- for the various dynamic arrays used for principle ASIS Context
-- Model data strcutures. The indicated initial size is allocated for the
-- start of each file, and the increment factor is a percentage used
-- to increase the table size when it needs expanding
-- (e.g. a value of 100 = 100% increase = double)
-- This package is the ASIS implementation's analog of the GNAT Alloc package
Alloc_ASIS_Units_Initial : constant := 1_000;
-- Initial allocation for unit tables
Alloc_ASIS_Units_Increment : constant := 150;
-- Incremental allocation factor for unit tables
Alloc_Contexts_Initial : constant := 20;
-- Initial allocation for Context table (A4G.Contt)
Alloc_Contexts_Increment : constant := 150;
-- Incremental allocation factor for Context table (Contt)
Alloc_ASIS_Trees_Initial : constant := 1_000;
-- Initial allocation for tree tables
Alloc_ASIS_Trees_Increment : constant := 150;
-- Incremental allocation factor for tree tables
end A4G.A_Alloc;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
b31e0d7d25dd36baceef7ce199d9b7f9d0719dae
|
src/ado-caches-discrete.adb
|
src/ado-caches-discrete.adb
|
-----------------------------------------------------------------------
-- ado-cache-discrete -- Simple cache management for discrete types
-- 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.
-----------------------------------------------------------------------
package body ADO.Caches.Discrete is
-- ------------------------------
-- Expand the name into a target parameter value to be used in the SQL query.
-- The Expander can return a T_NULL when a value is not found or
-- it may also raise some exception.
-- ------------------------------
overriding
function Expand (Instance : in out Cache_Type;
Name : in String) return ADO.Parameters.Parameter is
Value : Element_Type;
begin
Value := Instance.Find (Name);
return ADO.Parameters.Parameter '(T => ADO.Parameters.T_LONG_INTEGER,
Len => 0, Value_Len => 0, Position => 0,
Name => "",
Long_Num => Element_Type'Pos (Value));
end Expand;
-- ------------------------------
-- Find the value associated with the given name.
-- Raises the No_Value exception if no such mapping exist.
-- ------------------------------
function Find (Cache : in out Cache_Type;
Name : in String) return Element_Type is
begin
return Cache.Controller.Find (Name);
end Find;
-- ------------------------------
-- Insert the value associated with the given name in the cache.
-- When <tt>Override</tt> is set, override existing values otherwise raise an exception.
-- ------------------------------
procedure Insert (Cache : in out Cache_Type;
Name : in String;
Value : in Element_Type;
Override : in Boolean := False) is
begin
Cache.Controller.Insert (Name, Value, Override);
end Insert;
-- ------------------------------
-- Delete the value associated with the given name in the cache.
-- Raise the No_Value exception if the value is not found and <tt>Ignore</tt> is not set.
-- ------------------------------
procedure Delete (Cache : in out Cache_Type;
Name : in String;
Ignore : in Boolean := False) is
begin
Cache.Controller.Delete (Name, Ignore);
end Delete;
-- ------------------------------
-- Initialize the entity cache by reading the database entity table.
-- ------------------------------
procedure Initialize (Cache : in out Cache_Type;
Session : in out ADO.Sessions.Session'Class) is
begin
null;
end Initialize;
protected body Cache_Controller is
-- ------------------------------
-- Find the value associated with the given name.
-- Raises the No_Value exception if no such mapping exist.
-- ------------------------------
function Find (Name : in String) return Element_Type is
Pos : constant Cache_Map.Cursor := Values.Find (Name);
begin
if Cache_Map.Has_Element (Pos) then
return Cache_Map.Element (Pos);
else
Log.Info ("Unknown cached value {0}", Name);
raise No_Value with "Value '" & Name & "' not found";
end if;
end Find;
-- ------------------------------
-- Insert the value associated with the given name in the cache.
-- When <tt>Override</tt> is set, override existing values otherwise raise an exception.
-- ------------------------------
procedure Insert (Name : in String;
Value : in Element_Type;
Override : in Boolean := False) is
Pos : constant Cache_Map.Cursor := Values.Find (Name);
begin
if Cache_Map.Has_Element (Pos) then
if not Override then
raise No_Value;
end if;
Values.Replace_Element (Pos, Value);
else
Values.Insert (Name, Value);
end if;
end Insert;
-- ------------------------------
-- Delete the value associated with the given name in the cache.
-- Raise the No_Value exception if the value is not found and <tt>Ignore</tt> is not set.
-- ------------------------------
procedure Delete (Name : in String;
Ignore : in Boolean := False) is
Pos : Cache_Map.Cursor := Values.Find (Name);
begin
if Cache_Map.Has_Element (Pos) then
Values.Delete (Pos);
elsif not Ignore then
raise No_Value;
end if;
end Delete;
end Cache_Controller;
end ADO.Caches.Discrete;
|
Implement cache for discrete types
|
Implement cache for discrete types
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
|
abd047edea15c670ae91c4565ea16a57210b55b5
|
bsp-examples/evb1000/stm32-nvic.ads
|
bsp-examples/evb1000/stm32-nvic.ads
|
-- This spec has been automatically generated from STM32F105xx.svd
pragma Restrictions (No_Elaboration_Code);
pragma Ada_2012;
with System;
package STM32.NVIC is
pragma Preelaborate;
---------------
-- Registers --
---------------
-------------------
-- ICTR_Register --
-------------------
subtype ICTR_INTLINESNUM_Field is STM32.UInt4;
-- Interrupt Controller Type Register
type ICTR_Register is record
-- Read-only. Total number of interrupt lines in groups
INTLINESNUM : ICTR_INTLINESNUM_Field;
-- unspecified
Reserved_4_31 : STM32.UInt28;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for ICTR_Register use record
INTLINESNUM at 0 range 0 .. 3;
Reserved_4_31 at 0 range 4 .. 31;
end record;
------------------
-- IPR_Register --
------------------
-- IPR0_IPR_N array element
subtype IPR0_IPR_N_Element is STM32.Byte;
-- IPR0_IPR_N array
type IPR0_IPR_N_Field_Array is array (0 .. 3) of IPR0_IPR_N_Element
with Component_Size => 8, Size => 32;
-- Interrupt Priority Register
type IPR_Register
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- IPR_N as a value
Val : STM32.Word;
when True =>
-- IPR_N as an array
Arr : IPR0_IPR_N_Field_Array;
end case;
end record
with Unchecked_Union, Size => 32, Volatile_Full_Access,
Bit_Order => System.Low_Order_First;
for IPR_Register use record
Val at 0 range 0 .. 31;
Arr at 0 range 0 .. 31;
end record;
-------------------
-- STIR_Register --
-------------------
subtype STIR_INTID_Field is STM32.UInt9;
-- Software Triggered Interrupt Register
type STIR_Register is record
-- Write-only. interrupt to be triggered
INTID : STIR_INTID_Field := 16#0#;
-- unspecified
Reserved_9_31 : STM32.UInt23 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for STIR_Register use record
INTID at 0 range 0 .. 8;
Reserved_9_31 at 0 range 9 .. 31;
end record;
-----------------
-- Peripherals --
-----------------
-- Nested Vectored Interrupt Controller
type NVIC_Peripheral is record
-- Interrupt Controller Type Register
ICTR : ICTR_Register;
-- Interrupt Set-Enable Register
ISER0 : STM32.Word;
-- Interrupt Set-Enable Register
ISER1 : STM32.Word;
-- Interrupt Set-Enable Register
ISER2 : STM32.Word;
-- Interrupt Clear-Enable Register
ICER0 : STM32.Word;
-- Interrupt Clear-Enable Register
ICER1 : STM32.Word;
-- Interrupt Clear-Enable Register
ICER2 : STM32.Word;
-- Interrupt Set-Pending Register
ISPR0 : STM32.Word;
-- Interrupt Set-Pending Register
ISPR1 : STM32.Word;
-- Interrupt Set-Pending Register
ISPR2 : STM32.Word;
-- Interrupt Clear-Pending Register
ICPR0 : STM32.Word;
-- Interrupt Clear-Pending Register
ICPR1 : STM32.Word;
-- Interrupt Clear-Pending Register
ICPR2 : STM32.Word;
-- Interrupt Active Bit Register
IABR0 : STM32.Word;
-- Interrupt Active Bit Register
IABR1 : STM32.Word;
-- Interrupt Active Bit Register
IABR2 : STM32.Word;
-- Interrupt Priority Register
IPR0 : IPR_Register;
-- Interrupt Priority Register
IPR1 : IPR_Register;
-- Interrupt Priority Register
IPR2 : IPR_Register;
-- Interrupt Priority Register
IPR3 : IPR_Register;
-- Interrupt Priority Register
IPR4 : IPR_Register;
-- Interrupt Priority Register
IPR5 : IPR_Register;
-- Interrupt Priority Register
IPR6 : IPR_Register;
-- Interrupt Priority Register
IPR7 : IPR_Register;
-- Interrupt Priority Register
IPR8 : IPR_Register;
-- Interrupt Priority Register
IPR9 : IPR_Register;
-- Interrupt Priority Register
IPR10 : IPR_Register;
-- Interrupt Priority Register
IPR11 : IPR_Register;
-- Interrupt Priority Register
IPR12 : IPR_Register;
-- Interrupt Priority Register
IPR13 : IPR_Register;
-- Interrupt Priority Register
IPR14 : IPR_Register;
-- Interrupt Priority Register
IPR15 : IPR_Register;
-- Interrupt Priority Register
IPR16 : IPR_Register;
-- Software Triggered Interrupt Register
STIR : STIR_Register;
end record
with Volatile;
for NVIC_Peripheral use record
ICTR at 4 range 0 .. 31;
ISER0 at 256 range 0 .. 31;
ISER1 at 260 range 0 .. 31;
ISER2 at 264 range 0 .. 31;
ICER0 at 384 range 0 .. 31;
ICER1 at 388 range 0 .. 31;
ICER2 at 392 range 0 .. 31;
ISPR0 at 512 range 0 .. 31;
ISPR1 at 516 range 0 .. 31;
ISPR2 at 520 range 0 .. 31;
ICPR0 at 640 range 0 .. 31;
ICPR1 at 644 range 0 .. 31;
ICPR2 at 648 range 0 .. 31;
IABR0 at 768 range 0 .. 31;
IABR1 at 772 range 0 .. 31;
IABR2 at 776 range 0 .. 31;
IPR0 at 1024 range 0 .. 31;
IPR1 at 1028 range 0 .. 31;
IPR2 at 1032 range 0 .. 31;
IPR3 at 1036 range 0 .. 31;
IPR4 at 1040 range 0 .. 31;
IPR5 at 1044 range 0 .. 31;
IPR6 at 1048 range 0 .. 31;
IPR7 at 1052 range 0 .. 31;
IPR8 at 1056 range 0 .. 31;
IPR9 at 1060 range 0 .. 31;
IPR10 at 1064 range 0 .. 31;
IPR11 at 1068 range 0 .. 31;
IPR12 at 1072 range 0 .. 31;
IPR13 at 1076 range 0 .. 31;
IPR14 at 1080 range 0 .. 31;
IPR15 at 1084 range 0 .. 31;
IPR16 at 1088 range 0 .. 31;
STIR at 3840 range 0 .. 31;
end record;
-- Nested Vectored Interrupt Controller
NVIC_Periph : aliased NVIC_Peripheral
with Import, Address => NVIC_Base;
end STM32.NVIC;
|
Add a missing file for the EVB1000 BSP example
|
Add a missing file for the EVB1000 BSP example
|
Ada
|
mit
|
damaki/DW1000
|
|
7011aa50850a6708ead7f9be87d1ceb410d4d0f2
|
src/asis/asis-implementation.ads
|
src/asis/asis-implementation.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT INTERFACE COMPONENTS --
-- --
-- A S I S . I M P L E M E N T A T I O N --
-- --
-- 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). --
-- --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- 6 package Asis.Implementation
------------------------------------------------------------------------------
------------------------------------------------------------------------------
with Asis.Errors;
package Asis.Implementation is
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Asis.Implementation provides queries to initialize, finalize, and query the
-- error status of the ASIS Implementation.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- 6.1 function ASIS_Version
------------------------------------------------------------------------------
function ASIS_Version return Wide_String;
------------------------------------------------------------------------------
-- 6.2 function ASIS_Implementor
------------------------------------------------------------------------------
function ASIS_Implementor return Wide_String;
------------------------------------------------------------------------------
-- 6.3 function ASIS_Implementor_Version
------------------------------------------------------------------------------
function ASIS_Implementor_Version return Wide_String;
------------------------------------------------------------------------------
-- 6.4 function ASIS_Implementor_Information
------------------------------------------------------------------------------
function ASIS_Implementor_Information return Wide_String;
------------------------------------------------------------------------------
-- Returns values which identify:
--
-- ASIS_Version - the version of the ASIS interface,
-- e.g., "2.1"
-- ASIS_Implementor - the name of the implementor,
-- e.g., "Ada Inc."
-- ASIS_Implementor_Version - the implementation's version,
-- e.g., "5.2a"
-- ASIS_Implementor_Information - implementation information,
-- e.g., "Copyright ..."
--
------------------------------------------------------------------------------
-- 6.5 function Is_Initialized
------------------------------------------------------------------------------
function Is_Initialized return Boolean;
------------------------------------------------------------------------------
-- Returns True if ASIS is currently initialized.
--
------------------------------------------------------------------------------
-- 6.6 procedure Initialize
------------------------------------------------------------------------------
procedure Initialize (Parameters : Wide_String := "");
------------------------------------------------------------------------------
-- Parameters - Specifies implementation specific parameters.
--
-- Performs any necessary initialization activities. This shall be invoked
-- at least once before any other ASIS services are used. Parameter values
-- are implementation dependent. The call is ignored if ASIS is already
-- initialized. All ASIS queries and services are ready for use once this
-- call completes.
--
-- Raises ASIS_Failed if ASIS failed to initialize or if the Parameters
-- argument is invalid. Status is Environment_Error or Parameter_Error.
--
-- --|AN Application Note:
-- --|AN
-- --|AN The ASIS implementation may be Initialized and Finalized any number
-- --|AN of times during the operation of an ASIS program. However, all
-- --|AN existing Context, Compilation_Unit and Element values become invalid
-- --|AN when ASIS Is_Finalized. Subsequent calls to ASIS queries or services
-- --|AN using such invalid Compilation_Unit or Element values will cause
-- --|AN ASIS_Inappropriate_Context to be raised.
--
------------------------------------------------------------------------------
-- 6.7 function Is_Finalized
------------------------------------------------------------------------------
function Is_Finalized return Boolean;
------------------------------------------------------------------------------
-- Returns True if ASIS is currently finalized or if ASIS has never been
-- initialized.
--
------------------------------------------------------------------------------
-- 6.8 procedure Finalize
------------------------------------------------------------------------------
procedure Finalize (Parameters : Wide_String := "");
------------------------------------------------------------------------------
-- Parameters - Specifies any implementation required parameter values.
--
-- Performs any necessary ASIS termination activities. This should be invoked
-- once following the last use of other ASIS queries. Parameter values are
-- implementation dependent. The call is ignored if ASIS is already finalized.
-- Subsequent calls to ASIS Environment, Compilation_Unit, and Element
-- queries, are erroneous while the environment Is_Finalized.
--
-- Raises ASIS_Failed if the ASIS implementation failed to finalize. Status
-- is likely to be Internal_Error and will not be Not_An_Error.
--
-------------------------------------------------------------------------------
-- Whenever an error condition is detected, and any ASIS exception is raised,
-- an Asis.Errors.Error_Kinds value and a Diagnosis string is stored. These
-- values can be retrieved by the Status and Diagnosis functions. The
-- Diagnosis function will retrieve the diagnostic message describing the
-- error.
--
-- Error information always refers to the most recently recorded error.
--
-- Note that Diagnosis values are implementation dependent and may vary
-- greatly among ASIS implementations.
--
------------------------------------------------------------------------------
-- 6.9 function Status
------------------------------------------------------------------------------
function Status return Asis.Errors.Error_Kinds;
------------------------------------------------------------------------------
-- Returns the Error_Kinds value for the most recent error.
--
------------------------------------------------------------------------------
-- 6.10 function Diagnosis
------------------------------------------------------------------------------
function Diagnosis return Wide_String;
------------------------------------------------------------------------------
-- Returns a string value describing the most recent error.
--
-- Will typically return a null string if Status = Not_An_Error.
--
------------------------------------------------------------------------------
-- 6.11 procedure Set_Status
------------------------------------------------------------------------------
procedure Set_Status
(Status : Asis.Errors.Error_Kinds := Asis.Errors.Not_An_Error;
Diagnosis : Wide_String := "");
------------------------------------------------------------------------------
-- Status - Specifies the new status to be recorded
-- Diagnosis - Specifies the new diagnosis to be recorded
--
-- Sets (clears, if the defaults are used) the Status and Diagnosis
-- information. Future calls to Status will return this Status (Not_An_Error)
-- and this Diagnosis (a null string).
--
-- Raises ASIS_Failed, with a Status of Internal_Error and a Diagnosis of
-- a null string, if the Status parameter is Not_An_Error and the Diagnosis
-- parameter is not a null string.
--
------------------------------------------------------------------------------
--
end Asis.Implementation;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
5c106d6d731043c44152c504e1b4e4228a9a23e4
|
regtests/util-events-timers-tests.adb
|
regtests/util-events-timers-tests.adb
|
-----------------------------------------------------------------------
-- util-events-timers-tests -- Unit tests for timers
-- 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.Tests;
with Util.Test_Caller;
package body Util.Events.Timers.Tests is
use Util.Tests;
use type Ada.Real_Time.Time;
package Caller is new Util.Test_Caller (Test, "Events.Timers");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Events.Channels.Post_Event",
Test_Timer_Event'Access);
end Add_Tests;
overriding
procedure Time_Handler (Sub : in out Test;
Event : in out Timer_Ref'Class) is
begin
Sub.Count := Sub.Count + 1;
end Time_Handler;
procedure Test_Timer_Event (T : in out Test) is
M : Timer_List;
R : Timer_Ref;
Start : Ada.Real_Time.Time := Ada.Real_Time.Clock;
Deadline : Ada.Real_Time.Time;
Now : Ada.Real_Time.Time;
begin
T.Assert (not R.Is_Scheduled, "Empty timer should not be scheduled");
for Retry in 1 .. 10 loop
M.Set_Timer (T'Unchecked_Access, R, Start + Ada.Real_Time.Milliseconds (10));
M.Process (Deadline);
Now := Ada.Real_Time.Clock;
exit when Now < Deadline;
end loop;
T.Assert (Now < Deadline, "The timer deadline is not correct");
delay until Deadline;
M.Process (Deadline);
Assert_Equals (T, 1, T.Count, "The timer handler was not called");
end Test_Timer_Event;
end Util.Events.Timers.Tests;
|
Implement the new unit tests for the timer management
|
Implement the new unit tests for the timer management
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
|
519b008331ed483e40a09d1030b38ca0efca9ed3
|
src/http/util-http-clients.adb
|
src/http/util-http-clients.adb
|
-----------------------------------------------------------------------
-- util-http-clients -- HTTP Clients
-- 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.Http.Clients is
-- ------------------------------
-- Returns a boolean indicating whether the named response header has already
-- been set.
-- ------------------------------
overriding
function Contains_Header (Reply : in Response;
Name : in String) return Boolean is
begin
if Reply.Delegate = null then
return False;
else
return Reply.Delegate.Contains_Header (Name);
end if;
end Contains_Header;
-- ------------------------------
-- Returns the value of the specified response header as a String. If the response
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
-- ------------------------------
overriding
function Get_Header (Reply : in Response;
Name : in String) return String is
begin
if Reply.Delegate = null then
return "";
else
return Reply.Delegate.Get_Header (Name);
end if;
end Get_Header;
-- ------------------------------
-- Sets a message header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
-- ------------------------------
overriding
procedure Set_Header (Reply : in out Response;
Name : in String;
Value : in String) is
begin
Reply.Delegate.Set_Header (Name, Value);
end Set_Header;
-- ------------------------------
-- Adds a request header with the given name and value.
-- This method allows request headers to have multiple values.
-- ------------------------------
overriding
procedure Add_Header (Reply : in out Response;
Name : in String;
Value : in String) is
begin
Reply.Delegate.Add_Header (Name, Value);
end Add_Header;
-- ------------------------------
-- Iterate over the response headers and executes the <b>Process</b> procedure.
-- ------------------------------
overriding
procedure Iterate_Headers (Reply : in Response;
Process : not null access
procedure (Name : in String;
Value : in String)) is
begin
if Reply.Delegate /= null then
Reply.Delegate.Iterate_Headers (Process);
end if;
end Iterate_Headers;
-- ------------------------------
-- Get the response body as a string.
-- ------------------------------
overriding
function Get_Body (Reply : in Response) return String is
begin
if Reply.Delegate = null then
return "";
else
return Reply.Delegate.Get_Body;
end if;
end Get_Body;
-- ------------------------------
-- Get the response status code.
-- ------------------------------
function Get_Status (Reply : in Response) return Natural is
begin
return Reply.Delegate.Get_Status;
end Get_Status;
-- ------------------------------
-- Returns a boolean indicating whether the named response header has already
-- been set.
-- ------------------------------
overriding
function Contains_Header (Request : in Client;
Name : in String) return Boolean is
begin
if Request.Delegate = null then
return False;
else
return Request.Delegate.Contains_Header (Name);
end if;
end Contains_Header;
-- ------------------------------
-- Returns the value of the specified request header as a String. If the request
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
-- ------------------------------
overriding
function Get_Header (Request : in Client;
Name : in String) return String is
begin
if Request.Delegate = null then
return "";
else
return Request.Delegate.Get_Header (Name);
end if;
end Get_Header;
-- ------------------------------
-- Sets a header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
-- ------------------------------
overriding
procedure Set_Header (Request : in out Client;
Name : in String;
Value : in String) is
begin
Request.Delegate.Set_Header (Name, Value);
end Set_Header;
-- ------------------------------
-- Adds a header with the given name and value.
-- This method allows headers to have multiple values.
-- ------------------------------
overriding
procedure Add_Header (Request : in out Client;
Name : in String;
Value : in String) is
begin
Request.Delegate.Add_Header (Name, Value);
end Add_Header;
-- ------------------------------
-- Iterate over the request headers and executes the <b>Process</b> procedure.
-- ------------------------------
overriding
procedure Iterate_Headers (Request : in Client;
Process : not null access
procedure (Name : in String;
Value : in String)) is
begin
Request.Delegate.Iterate_Headers (Process);
end Iterate_Headers;
-- ------------------------------
-- Removes all headers with the given name.
-- ------------------------------
procedure Remove_Header (Request : in out Client;
Name : in String) is
begin
null;
end Remove_Header;
-- ------------------------------
-- Initialize the client
-- ------------------------------
overriding
procedure Initialize (Http : in out Client) is
begin
Http.Delegate := null;
Http.Manager := Default_Http_Manager;
Http.Manager.Create (Http);
end Initialize;
overriding
procedure Finalize (Http : in out Client) is
procedure Free is new Ada.Unchecked_Deallocation (Http_Request'Class,
Http_Request_Access);
begin
Free (Http.Delegate);
end Finalize;
-- ------------------------------
-- Execute an http GET request on the given URL. Additional request parameters,
-- cookies and headers should have been set on the client object.
-- ------------------------------
procedure Get (Request : in out Client;
URL : in String;
Reply : out Response'Class) is
begin
Request.Manager.Do_Get (Request, URL, Reply);
end Get;
-- ------------------------------
-- Execute an http POST request on the given URL. The post data is passed in <b>Data</b>.
-- Additional request cookies and headers should have been set on the client object.
-- ------------------------------
procedure Post (Request : in out Client;
URL : in String;
Data : in String;
Reply : out Response'Class) is
begin
Request.Manager.Do_Post (Request, URL, Data, Reply);
end Post;
-- ------------------------------
-- Adds the specified cookie to the request. This method can be called multiple
-- times to set more than one cookie.
-- ------------------------------
procedure Add_Cookie (Http : in out Client;
Cookie : in Util.Http.Cookies.Cookie) is
begin
null;
end Add_Cookie;
-- ------------------------------
-- Free the resource used by the response.
-- ------------------------------
overriding
procedure Finalize (Reply : in out Response) is
procedure Free is new Ada.Unchecked_Deallocation (Http_Response'Class,
Http_Response_Access);
begin
Free (Reply.Delegate);
end Finalize;
end Util.Http.Clients;
|
-----------------------------------------------------------------------
-- util-http-clients -- HTTP Clients
-- Copyright (C) 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 Ada.Unchecked_Deallocation;
with Util.Log.Loggers;
package body Util.Http.Clients is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients");
-- ------------------------------
-- Returns a boolean indicating whether the named response header has already
-- been set.
-- ------------------------------
overriding
function Contains_Header (Reply : in Response;
Name : in String) return Boolean is
begin
if Reply.Delegate = null then
return False;
else
return Reply.Delegate.Contains_Header (Name);
end if;
end Contains_Header;
-- ------------------------------
-- Returns the value of the specified response header as a String. If the response
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
-- ------------------------------
overriding
function Get_Header (Reply : in Response;
Name : in String) return String is
begin
if Reply.Delegate = null then
return "";
else
return Reply.Delegate.Get_Header (Name);
end if;
end Get_Header;
-- ------------------------------
-- Sets a message header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
-- ------------------------------
overriding
procedure Set_Header (Reply : in out Response;
Name : in String;
Value : in String) is
begin
Reply.Delegate.Set_Header (Name, Value);
end Set_Header;
-- ------------------------------
-- Adds a request header with the given name and value.
-- This method allows request headers to have multiple values.
-- ------------------------------
overriding
procedure Add_Header (Reply : in out Response;
Name : in String;
Value : in String) is
begin
Reply.Delegate.Add_Header (Name, Value);
end Add_Header;
-- ------------------------------
-- Iterate over the response headers and executes the <b>Process</b> procedure.
-- ------------------------------
overriding
procedure Iterate_Headers (Reply : in Response;
Process : not null access
procedure (Name : in String;
Value : in String)) is
begin
if Reply.Delegate /= null then
Reply.Delegate.Iterate_Headers (Process);
end if;
end Iterate_Headers;
-- ------------------------------
-- Get the response body as a string.
-- ------------------------------
overriding
function Get_Body (Reply : in Response) return String is
begin
if Reply.Delegate = null then
return "";
else
return Reply.Delegate.Get_Body;
end if;
end Get_Body;
-- ------------------------------
-- Get the response status code.
-- ------------------------------
function Get_Status (Reply : in Response) return Natural is
begin
return Reply.Delegate.Get_Status;
end Get_Status;
-- ------------------------------
-- Returns a boolean indicating whether the named response header has already
-- been set.
-- ------------------------------
overriding
function Contains_Header (Request : in Client;
Name : in String) return Boolean is
begin
if Request.Delegate = null then
return False;
else
return Request.Delegate.Contains_Header (Name);
end if;
end Contains_Header;
-- ------------------------------
-- Returns the value of the specified request header as a String. If the request
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
-- ------------------------------
overriding
function Get_Header (Request : in Client;
Name : in String) return String is
begin
if Request.Delegate = null then
return "";
else
return Request.Delegate.Get_Header (Name);
end if;
end Get_Header;
-- ------------------------------
-- Sets a header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
-- ------------------------------
overriding
procedure Set_Header (Request : in out Client;
Name : in String;
Value : in String) is
begin
Request.Delegate.Set_Header (Name, Value);
end Set_Header;
-- ------------------------------
-- Adds a header with the given name and value.
-- This method allows headers to have multiple values.
-- ------------------------------
overriding
procedure Add_Header (Request : in out Client;
Name : in String;
Value : in String) is
begin
Request.Delegate.Add_Header (Name, Value);
end Add_Header;
-- ------------------------------
-- Iterate over the request headers and executes the <b>Process</b> procedure.
-- ------------------------------
overriding
procedure Iterate_Headers (Request : in Client;
Process : not null access
procedure (Name : in String;
Value : in String)) is
begin
Request.Delegate.Iterate_Headers (Process);
end Iterate_Headers;
-- ------------------------------
-- Removes all headers with the given name.
-- ------------------------------
procedure Remove_Header (Request : in out Client;
Name : in String) is
begin
null;
end Remove_Header;
-- ------------------------------
-- Initialize the client
-- ------------------------------
overriding
procedure Initialize (Http : in out Client) is
begin
Http.Delegate := null;
Http.Manager := Default_Http_Manager;
if Http.Manager = null then
Log.Error ("No HTTP manager was defined");
raise Program_Error with "No HTTP manager was defined.";
end if;
Http.Manager.Create (Http);
end Initialize;
overriding
procedure Finalize (Http : in out Client) is
procedure Free is new Ada.Unchecked_Deallocation (Http_Request'Class,
Http_Request_Access);
begin
Free (Http.Delegate);
end Finalize;
-- ------------------------------
-- Execute an http GET request on the given URL. Additional request parameters,
-- cookies and headers should have been set on the client object.
-- ------------------------------
procedure Get (Request : in out Client;
URL : in String;
Reply : out Response'Class) is
begin
Request.Manager.Do_Get (Request, URL, Reply);
end Get;
-- ------------------------------
-- Execute an http POST request on the given URL. The post data is passed in <b>Data</b>.
-- Additional request cookies and headers should have been set on the client object.
-- ------------------------------
procedure Post (Request : in out Client;
URL : in String;
Data : in String;
Reply : out Response'Class) is
begin
Request.Manager.Do_Post (Request, URL, Data, Reply);
end Post;
-- ------------------------------
-- Adds the specified cookie to the request. This method can be called multiple
-- times to set more than one cookie.
-- ------------------------------
procedure Add_Cookie (Http : in out Client;
Cookie : in Util.Http.Cookies.Cookie) is
begin
null;
end Add_Cookie;
-- ------------------------------
-- Free the resource used by the response.
-- ------------------------------
overriding
procedure Finalize (Reply : in out Response) is
procedure Free is new Ada.Unchecked_Deallocation (Http_Response'Class,
Http_Response_Access);
begin
Free (Reply.Delegate);
end Finalize;
end Util.Http.Clients;
|
Add a log error and raise an exception if there is no http implementation selected
|
Add a log error and raise an exception if there is no http implementation selected
|
Ada
|
apache-2.0
|
Letractively/ada-util,flottokarotto/ada-util,Letractively/ada-util,flottokarotto/ada-util
|
16548a22e8a25630abad8aab3c7e66ed9d19b512
|
src/asis/asis-ids.adb
|
src/asis/asis-ids.adb
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A S I S . I D 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.Characters.Handling; use Ada.Characters.Handling;
with A4G.Vcheck; use A4G.Vcheck;
package body Asis.Ids is
------------------------------------------------------------------------------
-- NOT IMPLEMENTED
function Hash (The_Id : Id) return Asis.ASIS_Integer is
begin
pragma Unreferenced (The_Id);
Raise_ASIS_Failed (Diagnosis => "Asis.Ids.Hash");
return 0;
end Hash;
-----------------------------------------------------------------------------
-- NOT IMPLEMENTED
function "<" (Left : Id;
Right : Id) return Boolean is
begin
pragma Unreferenced (Left);
pragma Unreferenced (Right);
Raise_ASIS_Failed (Diagnosis => "Asis.Ids.""<""");
return True;
end "<";
-----------------------------------------------------------------------------
-- NOT IMPLEMENTED
function ">" (Left : Id;
Right : Id) return Boolean is
begin
pragma Unreferenced (Left);
pragma Unreferenced (Right);
Raise_ASIS_Failed (Diagnosis => "Asis.Ids."">""");
return False;
end ">";
-----------------------------------------------------------------------------
-- NOT IMPLEMENTED
function Is_Nil (Right : Id) return Boolean is
begin
pragma Unreferenced (Right);
Raise_ASIS_Failed (Diagnosis => "Asis.Ids.Is_Nil");
return True;
end Is_Nil;
-----------------------------------------------------------------------------
-- NOT IMPLEMENTED
function Is_Equal
(Left : Id;
Right : Id)
return Boolean
is
begin
pragma Unreferenced (Left);
pragma Unreferenced (Right);
Raise_ASIS_Failed (Diagnosis => "Asis.Ids.Is_Equal");
return True;
end Is_Equal;
-----------------------------------------------------------------------------
-- NOT IMPLEMENTED
function Create_Id (Element : Asis.Element) return Id is
begin
pragma Unreferenced (Element);
Raise_ASIS_Failed (Diagnosis => "Asis.Ids.Create_Id");
return Nil_Id;
end Create_Id;
-----------------------------------------------------------------------------
-- NOT IMPLEMENTED
function Create_Element
(The_Id : Id;
The_Context : Asis.Context)
return Asis.Element
is
begin
pragma Unreferenced (The_Id);
pragma Unreferenced (The_Context);
Raise_ASIS_Failed (Diagnosis => "Asis.Ids.Create_Element");
return Nil_Element;
end Create_Element;
-----------------------------------------------------------------------------
-- NOT IMPLEMENTED
function Debug_Image (The_Id : Id) return Wide_String is
begin
if Is_Nil (The_Id) then
return Nil_Asis_Wide_String;
else
return To_Wide_String (The_Id.all);
end if;
end Debug_Image;
-----------------------------------------------------------------------------
end Asis.Ids;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
be9fb4641e4a537fc4d0572ef82fc06205b188a7
|
src/wiki-filters.ads
|
src/wiki-filters.ads
|
-----------------------------------------------------------------------
-- wiki-filters -- Wiki 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 Ada.Strings.Wide_Wide_Unbounded;
with Ada.Finalization;
with Wiki.Attributes;
with Wiki.Documents;
-- == Filters ==
-- The <b>Wiki.Filters</b> package provides a simple filter framework that allows to plug
-- specific filters when a wiki document is parsed and processed. The <tt>Filter_Type</tt>
-- implements the <tt>Document_Reader</tt> interface to catch all the wiki document operations
-- and it forwards the different calls to a next wiki document instance. A filter can do some
-- operations while calls are made so that it can:
--
-- * Get the text content and filter it by looking at forbidden words in some dictionary,
-- * Ignore some formatting construct (for example to forbid the use of links),
-- * Verify and do some corrections on HTML content embedded in wiki text,
-- * Expand some plugins, specific links to complex content.
--
-- To implement a new filter, the <tt>Filter_Type</tt> type must be used as a base type
-- and some of the operations have to be overriden. The default <tt>Filter_Type</tt> operations
-- just propagate the call to the attached wiki document instance (ie, a kind of pass
-- through filter).
--
package Wiki.Filters is
pragma Preelaborate;
use Ada.Strings.Wide_Wide_Unbounded;
-- ------------------------------
-- Filter type
-- ------------------------------
type Filter_Type is new Ada.Finalization.Limited_Controlled
and Wiki.Documents.Document_Reader with private;
type Filter_Type_Access is access all Filter_Type'Class;
-- Add a section header in the document.
overriding
procedure Add_Header (Document : in out Filter_Type;
Header : in Unbounded_Wide_Wide_String;
Level : in Positive);
-- Add a line break (<br>).
overriding
procedure Add_Line_Break (Document : in out Filter_Type);
-- 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 Filter_Type);
-- 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 Filter_Type;
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 Filter_Type;
Level : in Positive;
Ordered : in Boolean);
-- Add an horizontal rule (<hr>).
overriding
procedure Add_Horizontal_Rule (Document : in out Filter_Type);
-- Add a link.
overriding
procedure Add_Link (Document : in out Filter_Type;
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 Filter_Type;
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 Filter_Type;
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 Filter_Type;
Text : in Unbounded_Wide_Wide_String;
Format : in Wiki.Documents.Format_Map);
-- Add a text block that is pre-formatted.
overriding
procedure Add_Preformatted (Document : in out Filter_Type;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String);
overriding
procedure Start_Element (Document : in out Filter_Type;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Wiki.Attributes.Attribute_List_Type);
overriding
procedure End_Element (Document : in out Filter_Type;
Name : in Unbounded_Wide_Wide_String);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Document : in out Filter_Type);
-- Set the document reader.
procedure Set_Document (Filter : in out Filter_Type;
Document : in Wiki.Documents.Document_Reader_Access);
private
type Filter_Type is new Ada.Finalization.Limited_Controlled
and Wiki.Documents.Document_Reader with record
Document : Wiki.Documents.Document_Reader_Access;
end record;
end Wiki.Filters;
|
Add some documentation
|
Add some documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
|
1a693428d2729913570a5daa668c9d869edb1d68
|
src/wiki-plugins-conditions.ads
|
src/wiki-plugins-conditions.ads
|
-----------------------------------------------------------------------
-- wiki-plugins-conditions -- Condition Plugin
-- 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.Strings;
-- === Conditions Plugins ===
-- The <b>Wiki.Plugins.Conditions</b> package defines a set of conditional plugins
-- to show or hide wiki content according to some conditions evaluated during the parsing phase.
--
package Wiki.Plugins.Conditions is
MAX_CONDITION_DEPTH : constant Natural := 31;
type Condition_Depth is new Natural range 0 .. MAX_CONDITION_DEPTH;
type Condition_Type is (CONDITION_IF, CONDITION_ELSIF, CONDITION_ELSE, CONDITION_END);
type Condition_Plugin is new Wiki_Plugin with private;
-- Evaluate the condition and return it as a boolean status.
function Evaluate (Plugin : in Condition_Plugin;
Params : in Wiki.Attributes.Attribute_List) return Boolean;
-- Get the type of condition (IF, ELSE, ELSIF, END) represented by the plugin.
function Get_Condition_Kind (Plugin : in Condition_Plugin;
Params : in Wiki.Attributes.Attribute_List)
return Condition_Type;
-- Evaluate the condition described by the parameters and hide or show the wiki
-- content.
overriding
procedure Expand (Plugin : in out Condition_Plugin;
Document : in out Wiki.Documents.Document;
Params : in out Wiki.Attributes.Attribute_List;
Context : in Plugin_Context);
-- Append the attribute name/value to the condition plugin parameter list.
procedure Append (Plugin : in out Condition_Plugin;
Name : in Wiki.Strings.WString;
Value : in Wiki.Strings.WString);
private
type Boolean_Array is array (Condition_Depth) of Boolean;
pragma Pack (Boolean_Array);
type Condition_Plugin is new Wiki_Plugin with record
Depth : Condition_Depth := 1;
Values : Boolean_Array := (others => False);
Params : Wiki.Attributes.Attribute_List;
end record;
end Wiki.Plugins.Conditions;
|
Declare the Conditions package with the Condition_Plugin type for the support of conditional inclusion in wiki text
|
Declare the Conditions package with the Condition_Plugin type for the
support of conditional inclusion in wiki text
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
|
30b09fbd4848b5d3b7dd163f6efbe0761a5f73db
|
src/wiki-streams-html-builders.adb
|
src/wiki-streams-html-builders.adb
|
-----------------------------------------------------------------------
-- wiki-writers-builders -- Wiki writer to a string builder
-- Copyright (C) 2011, 2012, 2013, 2015, 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.
-----------------------------------------------------------------------
package body Wiki.Streams.Html.Builders is
-- Close the current XML entity if an entity was started
procedure Close_Current (Stream : in out Html_Output_Builder_Stream'Class);
-- Internal method to write a character on the response stream
-- and escape that character as necessary. Unlike 'Write_Char',
-- this operation does not closes the current XML entity.
procedure Write_Escape (Stream : in out Html_Output_Builder_Stream'Class;
Char : in Wide_Wide_Character);
type Unicode_Char is mod 2**31;
-- ------------------------------
-- Internal method to write a character on the response stream
-- and escape that character as necessary. Unlike 'Write_Char',
-- this operation does not closes the current XML entity.
-- ------------------------------
procedure Write_Escape (Stream : in out Html_Output_Builder_Stream'Class;
Char : in Wide_Wide_Character) is
Code : constant Unicode_Char := Wide_Wide_Character'Pos (Char);
begin
-- If "?" or over, no escaping is needed (this covers
-- most of the Latin alphabet)
if Code > 16#3F# or Code <= 16#20# then
Stream.Write (Char);
elsif Char = '<' then
Stream.Write ("<");
elsif Char = '>' then
Stream.Write (">");
elsif Char = '&' then
Stream.Write ("&");
else
Stream.Write (Char);
end if;
end Write_Escape;
-- ------------------------------
-- Close the current XML entity if an entity was started
-- ------------------------------
procedure Close_Current (Stream : in out Html_Output_Builder_Stream'Class) is
begin
if Stream.Close_Start then
Stream.Write ('>');
Stream.Close_Start := False;
end if;
end Close_Current;
procedure Write_Wide_Element (Stream : in out Html_Output_Builder_Stream;
Name : in String;
Content : in Wiki.Strings.WString) is
begin
Stream.Start_Element (Name);
Stream.Write_Wide_Text (Content);
Stream.End_Element (Name);
end Write_Wide_Element;
-- ------------------------------
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
-- ------------------------------
procedure Write_Wide_Attribute (Stream : in out Html_Output_Builder_Stream;
Name : in String;
Content : in Wiki.Strings.WString) is
begin
if Stream.Close_Start then
Stream.Write (' ');
Stream.Write_String (Name);
Stream.Write ('=');
Stream.Write ('"');
for I in Content'Range loop
declare
C : constant Wide_Wide_Character := Content (I);
begin
if C = '"' then
Stream.Write (""");
else
Stream.Write_Escape (C);
end if;
end;
end loop;
Stream.Write ('"');
end if;
end Write_Wide_Attribute;
procedure Write_Wide_Attribute (Stream : in out Html_Output_Builder_Stream;
Name : in String;
Content : in Unbounded_Wide_Wide_String) is
Count : constant Natural := Length (Content);
begin
if Stream.Close_Start then
Stream.Write (' ');
Stream.Write_String (Name);
Stream.Write ('=');
Stream.Write ('"');
for I in 1 .. Count loop
declare
C : constant Wide_Wide_Character := Element (Content, I);
begin
if C = '"' then
Stream.Write (""");
else
Stream.Write_Escape (C);
end if;
end;
end loop;
Stream.Write ('"');
end if;
end Write_Wide_Attribute;
procedure Start_Element (Stream : in out Html_Output_Builder_Stream;
Name : in String) is
begin
Close_Current (Stream);
Stream.Write ('<');
Stream.Write_String (Name);
Stream.Close_Start := True;
end Start_Element;
procedure End_Element (Stream : in out Html_Output_Builder_Stream;
Name : in String) is
begin
if Stream.Close_Start then
Stream.Write (" />");
Stream.Close_Start := False;
else
Close_Current (Stream);
Stream.Write ("</");
Stream.Write_String (Name);
Stream.Write ('>');
end if;
end End_Element;
procedure Write_Wide_Text (Stream : in out Html_Output_Builder_Stream;
Content : in Wiki.Strings.WString) is
begin
Close_Current (Stream);
for I in Content'Range loop
Html_Output_Builder_Stream'Class (Stream).Write_Escape (Content (I));
end loop;
end Write_Wide_Text;
end Wiki.Streams.Html.Builders;
|
Implement the Wiki.Streams.Html.Builders package
|
Implement the Wiki.Streams.Html.Builders package
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
|
0a218952eaf96cb0031e33cb23e62404d11e73e1
|
src/asf-rest.adb
|
src/asf-rest.adb
|
-----------------------------------------------------------------------
-- asf-rest -- REST Support
-- 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.
-----------------------------------------------------------------------
package body ASF.Rest is
-- ------------------------------
-- Get the permission index associated with the REST operation.
-- ------------------------------
function Get_Permission (Handler : in Descriptor)
return Security.Permissions.Permission_Index is
begin
return Handler.Permission;
end Get_Permission;
-- ------------------------------
-- Register the API descriptor in a list.
-- ------------------------------
procedure Register (List : in out Descriptor_Access;
Item : in Descriptor_Access) is
begin
Item.Next := Item;
List := Item;
end Register;
end ASF.Rest;
|
Implement the Get_Permission and Register operations
|
Implement the Get_Permission and Register operations
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
|
66a18261401a53c850b0cc65380712800d255517
|
regtests/babel-base-text-tests.adb
|
regtests/babel-base-text-tests.adb
|
-----------------------------------------------------------------------
-- babel-base-text-tests - Unit tests for babel text database
-- 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 Util.Test_Caller;
package body Babel.Base.Text.Tests is
package Caller is new Util.Test_Caller (Test, "Base.Users");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Babel.Base.Text.Load",
Test_Load'Access);
end Add_Tests;
-- Test the loading a text database.
procedure Test_Load (T : in out Test) is
DB : Text_Database;
begin
DB.Load (Util.Tests.Get_Path ("regtests/files/db/database.txt"));
end Test_Load;
end Babel.Base.Text.Tests;
|
Add Test_Load operation
|
Add Test_Load operation
|
Ada
|
apache-2.0
|
stcarrez/babel
|
|
e66a060952db57f1bd9021af21fee4b295d3b1b6
|
regtests/util-serialize-io-xml-tests.ads
|
regtests/util-serialize-io-xml-tests.ads
|
-----------------------------------------------------------------------
-- serialize-io-xml-tests -- Unit tests for XML serialization
-- 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 AUnit.Test_Suites;
with AUnit.Test_Fixtures;
package Util.Serialize.IO.XML.Tests is
procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite);
type Test is new AUnit.Test_Fixtures.Test_Fixture with null record;
procedure Test_Parser (T : in out Test);
procedure Test_Writer (T : in out Test);
end Util.Serialize.IO.XML.Tests;
|
-----------------------------------------------------------------------
-- serialize-io-xml-tests -- Unit tests for XML serialization
-- 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 AUnit.Test_Suites;
with AUnit.Test_Fixtures;
package Util.Serialize.IO.XML.Tests is
procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite);
type Test is new AUnit.Test_Fixtures.Test_Fixture with null record;
-- Test XML de-serialization
procedure Test_Parser (T : in out Test);
-- Test XML serialization
procedure Test_Writer (T : in out Test);
end Util.Serialize.IO.XML.Tests;
|
Add comment
|
Add comment
|
Ada
|
apache-2.0
|
Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util,Letractively/ada-util
|
752bf742c903771675043ab532f7af8829238c29
|
regtests/ado-drivers-tests.ads
|
regtests/ado-drivers-tests.ads
|
-----------------------------------------------------------------------
-- ado-drivers-tests -- Unit tests for database drivers
-- 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;
package ADO.Drivers.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test the Get_Config operation.
procedure Test_Get_Config (T : in out Test);
-- Test the Get_Driver operation.
procedure Test_Get_Driver (T : in out Test);
-- Test loading some invalid database driver.
procedure Test_Load_Invalid_Driver (T : in out Test);
-- Test the Get_Driver_Index operation.
procedure Test_Get_Driver_Index (T : in out Test);
end ADO.Drivers.Tests;
|
Define some new tests for the database drivers support
|
Define some new tests for the database drivers support
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
|
6f2201b1eabfc286f0cf0dd585c54d1eb92a0a44
|
src/asis/a4g-a_osint.adb
|
src/asis/a4g-a_osint.adb
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . A _ O S I N T --
-- --
-- B o d y --
-- --
-- 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 Unchecked_Deallocation;
package body A4G.A_Osint is
-----------------------
-- Local subprograms --
-----------------------
procedure Free_String is new Unchecked_Deallocation (String, String_Access);
procedure Free_List is new Unchecked_Deallocation
(Argument_List, Argument_List_Access);
------------------------
-- Free_Argument_List --
------------------------
procedure Free_Argument_List (List : in out Argument_List_Access) is
begin
if List = null then
return;
end if;
for J in List'Range loop
Free_String (List (J));
end loop;
Free_List (List);
end Free_Argument_List;
------------------------------
-- Get_Max_File_Name_Length --
------------------------------
function Get_Max_File_Name_Length return Int is
function Get_Maximum_File_Name_Length return Int;
pragma Import (C, Get_Maximum_File_Name_Length,
"__gnat_get_maximum_file_name_length");
-- This function does what we want, but it returns -1 when there
-- is no restriction on the file name length
--
-- The implementation has been "stolen" from the body of GNAT
-- Osint.Initialize
begin
if Get_Maximum_File_Name_Length = -1 then
return Int'Last;
else
return Get_Maximum_File_Name_Length;
end if;
end Get_Max_File_Name_Length;
------------------------------
-- Normalize_Directory_Name --
------------------------------
function Normalize_Directory_Name
(Directory : String)
return String
is
begin
-- For now this just insures that the string is terminated with
-- the directory separator character. Add more later?
if Directory (Directory'Last) = Directory_Separator then
return Directory;
elsif Directory'Length = 0 then
-- now we do not need this, but it is no harm to keep it
return '.' & Directory_Separator;
else
return Directory & Directory_Separator;
end if;
end Normalize_Directory_Name;
end A4G.A_Osint;
|
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
|
|
484f22c643bb59fe6c5f5080feaee5e64e41fe7a
|
src/asis/asis-data_decomposition-vcheck.ads
|
src/asis/asis-data_decomposition-vcheck.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 . V C H E C K --
-- --
-- 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 contains validity checks for abstractions declared in
-- Asis.Data_Decomposition (see 22.1, 22.3)
private package Asis.Data_Decomposition.Vcheck is
type Component_Kinds is (Not_A_Component, Arr, Rec);
procedure Check_Validity
(Comp : Record_Component;
Query : String);
-- Checks if Comp is valid in a sense as defined in 22.1. Raises
-- Asis_Failed and sets the corresponding error status and diagnosis in
-- case if the check fails. The Query parameter is supposed to be the name
-- of the query where the check is performad.
procedure Check_Validity
(Comp : Array_Component;
Query : String);
-- Checks if Comp is valid in a sense as defined in 22.3. Raises
-- Asis_Failed and sets the corresponding error status and diagnosis in
-- case if the check fails. The Query parameter is supposed to be the name
-- of the query where the check is performad.
procedure Raise_ASIS_Inappropriate_Component
(Diagnosis : String;
Component_Kind : Component_Kinds);
-- Raises ASIS_Inappropriate_Element with Value_Error Error Status.
-- Diagnosis usially is the name of the query where the exception is
-- raised. Component_Kind, if not equal to Not_A_Component, is used to put
-- in the ASIS diagnosis string some information to distinguish the
-- queries with the same name which are defined for both Record_Component
-- and Array_Component.
end Asis.Data_Decomposition.Vcheck;
|
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
|
|
fa1aa326fa90df0fd0cf92e11b43c3a6a2e55b8f
|
src/asis/a4g-a_sem.ads
|
src/asis/a4g-a_sem.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . A _ S E M --
-- --
-- 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). --
-- --
------------------------------------------------------------------------------
-- This package contains routines needed for semantic queries from
-- more than one Asis package
with Asis; use Asis;
with A4G.Int_Knds; use A4G.Int_Knds;
with Einfo; use Einfo;
with Types; use Types;
package A4G.A_Sem is
-- All the routines defined in this package do not check their
-- arguments - a caller is responsible for the proper use of these
-- routines
---------------------------------------
-- Routines working on ASIS Elements --
---------------------------------------
function Belongs_To_Limited_View (Decl : Asis.Element) return Boolean;
-- Checks if the argument (declaration) Element may belong to a limited
-- view of some package, see RM 05 10.1.1 (12.1/2 ..12.5/2))
function Limited_View_Kind
(Decl : Asis.Element)
return Internal_Element_Kinds;
-- Provided that Belongs_To_Limited_View (Decl), returns the rind that
-- Decl should have in limited view (actually, the result is the kind of
-- the argument except in case of type declarations, when the type is
-- converted to An_Incomplete_Type_Declaration or
-- A_Tagged_Incomplete_Type_Declaration
function Get_Corr_Called_Entity
(Call : Asis.Element)
return Asis.Declaration;
-- This function incapsulates the common code from
-- Asis.Expressions.Corresponding_Called_Function and
-- Asis.Statements.Corresponding_Called_Entity.
-- It gets the Ada construction which is either a procedure (entry)
-- or a function call and returns the declaration of the called
-- entity. This function does not check this argument to be an
-- appropriate Element for any of these ASIS queries.
function Is_Range_Memberchip_Test (E : Asis.Element) return Boolean;
function Is_Type_Memberchip_Test (E : Asis.Element) return Boolean;
-- These two functions are used as a check for appropriate Element in two
-- obsolescent queries from Asis.Expressions - Membership_Test_Range and
-- Membership_Test_Subtype_Mark respectively. They assume that an argument
-- Element represents a membreship check Element. They check if the
-- argument represents the membership test that in old ASIS was classified
-- as An_In_Range_Membership_Test .. A_Not_In_Range_Membership_Test or
-- An_In_Type_Membership_Test .. A_Not_In_Type_Membership_Test
-- respectively.
procedure Reset_For_Body
(El : in out Asis.Element;
Body_Unit : Asis.Compilation_Unit);
-- Provided that El is a declaration from the spec of a library package
-- or a library generic package, this procedure resets El to Is_Identical
-- Element, but obtained from the tree contained the body for this package.
-- This body is represented by the Body_Unit parameter, we use it to avoid
-- call to Asis.Compilation_Units.Corresponding_Body in the implementation
-- of this function.
------------------------------------
-- Routines working on tree nodes --
------------------------------------
function Entity_Present (N : Node_Id) return Boolean;
-- Differs from 'Present (Entity (N))' that in case if the check
-- 'Present (Entity (N))' does not point to an expression node as it
-- happens for identifiers that identify aspects in aspect specifications.
function Defined_In_Standard (N : Node_Id) return Boolean;
-- checks if its argument is an identifier or an enumeration literal
-- defined in the predefined Standard package
function Char_Defined_In_Standard (N : Node_Id) return Boolean;
-- Checks if its argument is a character literal defined in the
-- predefined Standard package. Can be applied to reference nodes and
-- entity nodes.
function Unwind_Renaming (Def_Name : Node_Id) return Node_Id;
-- Supposing that Def_Name is the node representing some defining
-- occurrence of some name, this function unwinds all the renamings
-- (if any) and returns the node representing the defining
-- name of the entity referenced by this name. If there is no
-- declaration for a given entity (this is the case, when a name
-- renames a subprogram-attribute) an Empty node is returned.
--
-- Note, that the node for renaming declaration may be rewritten,
-- in particular, renaming of a subprogram-attribute is rewritten
-- into a subprogram body
procedure Set_Stub_For_Subunit_If_Any (Def_Name : in out Node_Id);
-- If Def_Name is N_Defining_Identifier node which represents the
-- subprogram defining identifier from the proper body of a subunit,
-- it is reset to point to the corresponding N_Defining_Identifier
-- node from the corresponding body stub, if this stub acts as spec,
-- or to the N_Defining_Identifier node from the corresponding
-- subprogram declaration. Otherwise the argument remains unchanged.
function Corr_Decl_For_Stub (Stub_Node : Node_Id) return Node_Id;
-- This function should be called only for N_Subprogram_Body_Stub
-- nodes. If the corresponding subprogram body stub is a completion
-- of some subprogram declaration, the functions returns the node
-- representing this subprogram declaration, otherwise it returns
-- the Empty node.
function Is_Anonymous (E : Entity_Kind) return Boolean;
-- Check if E corresponds to an anonymous access type or subtype.
function Is_Predefined (Def_Op : Node_Id) return Boolean;
-- Returns True if Def_Op is N_Defining_Operator_Symbol representing
-- a predefined operation. Returns False otherwise.
-- ??? May be, there is something like this in GNAT???
function Is_Impl_Neq (Def_Op : Entity_Id) return Boolean;
-- Checks if the argument if the entity of implicit "/=" that is defined
-- for explicit user-defined "="
function Is_From_Instance (Node : Node_Id) return Boolean;
-- Checks if Node is from expanded generic template
function Is_From_Rewritten_Aggregate (Node : Node_Id) return Boolean;
-- Checks if Node is an N_Component_Association node belonging to a
-- rewritten tree structure corresponding to some aggregate. Returns False
-- if Node is not of N_Component_Association kind.
function Is_Name_Of_Expanded_Subprogram (Node : Node_Id) return Boolean;
-- Detects if the argument is a defining name from an expanded subprogram
-- instantiation, In this case the front-end creates an artificial
-- defining identifier node that is not Comes_From_Source, but that also
-- does not have an instantiation chain in Sloc, so ASIS can get confused
-- with this node and treat is as an implicit node if apply the usual
-- tests to it. (See G312-006).
function Is_From_Unknown_Pragma (Node : Node_Id) return Boolean;
-- Checks if Node belongs to a subtree rooted by unknown pragma. The tree
-- structures for unknown pragmas are very poorly decorated, so semantic
-- queries may just blow up when applied to elements representing
-- components of such pragmas.
function Get_Actual_Type_Name (Type_Mark_Node : Node_Id) return Node_Id;
-- This function supposes, that its argument is of N_Identifier kind.
-- When applied to a reference to an implicit subtype created in
-- expanded generic instantiation as a way to pass the actual type,
-- this function "unwinds" this implicit subtyping and returns the
-- reference to the actual type. Otherwise it returns its argument
-- unchanged.
-- The case when the actual type is a derived type is treated specially -
-- in this case "unwinding" could bring the internal type created by the
-- front-end, so we break this unwinding and return the entity (!!!) node
-- of the corresponding actual type.
function Get_Instance_Name (Int_Name : Node_Id) return Node_Id;
-- For Int_Node which should be Is_Generic_Instance (otherwise it is an
-- error to use this function) and which denotes the entity declared in
-- an artificial package created by the compiler for a generic
-- instantiation, it finds an entity defined in a generic instantiation
function Get_Derived_Type
(Type_Entity : Entity_Id;
Inherited_Subpr : Entity_Id)
return Entity_Id;
-- This function supposes that Type_Entity is a type entity,
-- and Inherited_Subpr is the defining name of implicit inherited
-- subprogram. It checks if Type_Entity is an ancestor type for the
-- derived type which inherits Inherited_Subpr, and if it is, returns
-- the entity of the derived type, otherwise returns Type_Entity
function Is_Derived_Rep_Item
(Type_Entity : Entity_Id;
Rep_Item : Node_Id)
return Boolean;
-- Supposing that Type_Entity is an entity of some type, and Rep_Item
-- represents some representation item from the chain of representation
-- items associated with this type, this function checks it Type_Entity
-- derives this Rep_Item from some of its parent types.
function Is_Artificial_Protected_Op_Item_Spec
(E : Entity_Id)
return Boolean;
-- Checks if E represents the entity from the artificial subprogram spec
-- created by the compiler for some protected_operation_item which does not
-- have a separate spec in the source code.
-- Note that this function check protected operation entity and entities of
-- its formal parameters (At some point we should rename it as
-- Is_FROM_Artificial_Protected_Op_Item_Spec)
function Represents_Class_Wide_Type_In_Instance
(N : Node_Id)
return Boolean;
-- Test function used to check if from the ASIS viewpoint the argument may
-- represent the 'Class attribute reference corresponding to the actual
-- class-wide type in the instantiation (see F410-011 for full details)
function Represents_Base_Type_In_Instance (N : Node_Id) return Boolean;
-- Test function used to check if from the ASIS viewpoint the argument may
-- represent the 'Base attribute reference corresponding to the actual
-- type in the instantiation.
function Pass_Generic_Actual (N : Node_Id) return Boolean;
-- Checks if N represents an artificial (created by the front-end)
-- declaration used to pass the actual in the instantiation. The problem
-- here is that for such declarations the Sloc field not always (and not
-- for all of their subcomponents) points to the instantiation chain.
function Part_Of_Pass_Generic_Actual (N : Node_Id) return Boolean;
-- This function checks if its argument is a subcomponent of the construct
-- for that Pass_Generic_Actual returns True. The only reason to have these
-- two function instead of just this one is performance.
function Explicit_Parent_Subprogram (E : Entity_Id) return Entity_Id;
-- Provided that E points to an inherited subprogram, this function
-- computes the entity of the corresponding explicitly defined parent
-- subprogram.
function Get_Importing_Pragma (E : Entity_Id) return Node_Id;
-- Supposing that E is an Is_Imported Entity node, compute the
-- corresponding Import or Interface pragma.
function Is_Applied_To
(Pragma_Node : Node_Id;
Entity_Node : Entity_Id)
return Boolean;
-- Supposing that Pragma_Node denotes a pragma, and Entity_Node is an
-- entity node (the caller is responsible for this), checks if the pragma
-- is applied to the entity.
end A4G.A_Sem;
|
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
|
|
1163a52abf7bcfe2e665ee36382558dc8b004075
|
src/asis/a4g-a_types.adb
|
src/asis/a4g-a_types.adb
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . A _ T Y P E 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, 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.Unchecked_Conversion;
with System; use System;
with Hostparm;
package body A4G.A_Types is
---------------
-- A_OS_Time --
---------------
function A_OS_Time return ASIS_OS_Time is
begin
return ASIS_Clock;
end A_OS_Time;
-----------------------------
-- Asis_Normalize_Pathname --
-----------------------------
Asis_Normalize_Pathname_Result : String_Access;
function Asis_Normalize_Pathname
(Name : String;
Directory : String := "";
Resolve_Links : Boolean := True;
Case_Sensitive : Boolean := True) return String
is
-- ???
-- All the stuff in the declarative part is copied from Osint...
function C_String_Length (S : Address) return Integer;
-- Returns length of a C string (zero for a null address)
function To_Path_String_Access
(Path_Addr : Address;
Path_Len : Integer) return String_Access;
-- Converts a C String to an Ada String. Are we doing this to avoid
-- withing Interfaces.C.Strings ???
-- Caller must free result.
function To_Host_Dir_Spec
(Canonical_Dir : String;
Prefix_Style : Boolean) return String_Access;
-- Convert a canonical syntax directory specification to host syntax.
-- The Prefix_Style flag is currently ignored but should be set to
-- False. Note that the caller must free result.
-- ???
-- Copied from Osint...
function C_String_Length (S : Address) return Integer is
function Strlen (S : Address) return Integer;
pragma Import (C, Strlen, "strlen");
begin
if S = Null_Address then
return 0;
else
return Strlen (S);
end if;
end C_String_Length;
function To_Path_String_Access
(Path_Addr : Address;
Path_Len : Integer) return String_Access
is
subtype Path_String is String (1 .. Path_Len);
type Path_String_Access is access Path_String;
function Address_To_Access is new
Ada.Unchecked_Conversion (Source => Address,
Target => Path_String_Access);
Path_Access : constant Path_String_Access :=
Address_To_Access (Path_Addr);
Return_Val : String_Access;
begin
Return_Val := new String (1 .. Path_Len);
for J in 1 .. Path_Len loop
Return_Val (J) := Path_Access (J);
end loop;
return Return_Val;
end To_Path_String_Access;
function To_Host_Dir_Spec
(Canonical_Dir : String;
Prefix_Style : Boolean) return String_Access
is
function To_Host_Dir_Spec
(Canonical_Dir : Address;
Prefix_Flag : Integer) return Address;
pragma Import (C, To_Host_Dir_Spec, "__gnat_to_host_dir_spec");
C_Canonical_Dir : String (1 .. Canonical_Dir'Length + 1);
Host_Dir_Addr : Address;
Host_Dir_Len : Integer;
begin
C_Canonical_Dir (1 .. Canonical_Dir'Length) := Canonical_Dir;
C_Canonical_Dir (C_Canonical_Dir'Last) := ASCII.NUL;
if Prefix_Style then
Host_Dir_Addr := To_Host_Dir_Spec (C_Canonical_Dir'Address, 1);
else
Host_Dir_Addr := To_Host_Dir_Spec (C_Canonical_Dir'Address, 0);
end if;
Host_Dir_Len := C_String_Length (Host_Dir_Addr);
if Host_Dir_Len = 0 then
return null;
else
return To_Path_String_Access (Host_Dir_Addr, Host_Dir_Len);
end if;
end To_Host_Dir_Spec;
begin
if Name = "" then
return "";
else
Free (Asis_Normalize_Pathname_Result);
Asis_Normalize_Pathname_Result := To_Host_Dir_Spec (
Canonical_Dir =>
Normalize_Pathname (
Name => Name,
Directory => Directory,
Resolve_Links => Resolve_Links,
Case_Sensitive => Case_Sensitive),
Prefix_Style => False);
return Asis_Normalize_Pathname_Result.all;
end if;
end Asis_Normalize_Pathname;
---------------------------
-- Increase_ASIS_OS_Time --
---------------------------
procedure Increase_ASIS_OS_Time is
begin
ASIS_Clock := ASIS_Clock + 1;
end Increase_ASIS_OS_Time;
-----------
-- Later --
-----------
function Later (L, R : ASIS_OS_Time) return Boolean is
begin
return L <= R;
end Later;
------------------------------
-- Parameter_String_To_List --
------------------------------
function Parameter_String_To_List
(Par_String : String)
return Argument_List_Access
is
Max_Pars : constant Integer := Par_String'Length;
New_Parv : Argument_List (1 .. Max_Pars);
New_Parc : Natural := 0;
Idx : Integer;
Old_Idx : Integer;
function Move_To_Next_Par (Ind : Integer) return Integer;
-- Provided that Ind points somewhere inside Par_String, moves
-- it ahead to point to the beginning of the next parameter if
-- Ind points to the character considering as a parameter separator,
-- otherwise returns Ind unchanged. If Ind points to a separator and
-- there is no more parameters ahead, Par_String'Last + 1 is returned.
-- (See the definition of the syntax of the Parameters string in the
-- ASIS Reference Manual)
function Move_To_Par_End (Ind : Integer) return Integer;
-- Provided that Ind points to some character of a separate parameters
-- being a part of Par_String, returns the index of the last character
-- of this parameter
function Move_To_Next_Par (Ind : Integer) return Integer is
Result : Integer := Ind;
begin
while Result <= Par_String'Last and then
(Par_String (Result) = ' ' or else
Par_String (Result) = ASCII.HT or else
Par_String (Result) = ASCII.LF or else
Par_String (Result) = ASCII.CR)
loop
Result := Result + 1;
end loop;
return Result;
end Move_To_Next_Par;
function Move_To_Par_End (Ind : Integer) return Integer is
Result : Integer := Ind;
Quoted : Boolean := False;
begin
loop
-- Am unquoted white space or EOL is the end of an argument
if not Quoted
and then
(Par_String (Result) = ' ' or else
Par_String (Result) = ASCII.HT or else
Par_String (Result) = ASCII.LF or else
Par_String (Result) = ASCII.CR)
then
exit;
-- Start of quoted string
elsif not Quoted
and then Par_String (Result) = '"'
then
Quoted := True;
-- End of a quoted string and end of an argument
elsif Quoted
and then Par_String (Result) = '"'
then
Result := Result + 1;
exit;
end if;
Result := Result + 1;
exit when Result > Par_String'Last;
end loop;
Result := Result - 1;
return Result;
end Move_To_Par_End;
begin
Idx := Move_To_Next_Par (Par_String'First);
while Idx <= Par_String'Last loop
Old_Idx := Idx;
Idx := Move_To_Par_End (Idx);
New_Parc := New_Parc + 1;
New_Parv (New_Parc) :=
new String'(Par_String (Old_Idx .. Idx));
Idx := Move_To_Next_Par (Idx + 1);
end loop;
return new Argument_List'(New_Parv (1 .. New_Parc));
end Parameter_String_To_List;
begin
if Hostparm.OpenVMS then
ASIS_Path_Separator := ',';
ASIS_Current_Directory := new String'("[]");
else
ASIS_Path_Separator := GNAT.OS_Lib.Path_Separator;
ASIS_Current_Directory := new String'(".");
end if;
end A4G.A_Types;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
22145ff8a9ce9f3081e1feb5aa4f031aca2ef276
|
src/asf-servlets-faces-mappers.adb
|
src/asf-servlets-faces-mappers.adb
|
-----------------------------------------------------------------------
-- asf-servlets-faces-mappers -- Read faces specific configuration files
-- 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.Unchecked_Deallocation;
with ASF.Routes.Servlets.Faces;
package body ASF.Servlets.Faces.Mappers is
use type ASF.Routes.Route_Type_Access;
procedure Free is
new Ada.Unchecked_Deallocation (Object => ASF.Routes.Servlets.Faces.Faces_Route_Type'Class,
Name => ASF.Routes.Servlets.Faces.Faces_Route_Type_Access);
function Find_Servlet (Container : in Servlet_Registry_Access;
View : in String)
return ASF.Servlets.Servlet_Access is
Disp : constant Request_Dispatcher := Container.Get_Request_Dispatcher (View);
Route : constant ASF.Routes.Route_Type_Access := Disp.Context.Get_Route;
begin
if Route = null then
raise Util.Serialize.Mappers.Field_Error with "No servlet mapped to view " & View;
end if;
if not (Route.all in ASF.Routes.Servlets.Servlet_Route_Type'Class) then
raise Util.Serialize.Mappers.Field_Error with "View " & View & " not mapped to a servlet";
end if;
return ASF.Routes.Servlets.Servlet_Route_Type'Class (Route.all).Servlet;
end Find_Servlet;
-- ------------------------------
-- Save in the servlet config object the value associated with the given field.
-- When the URL_MAPPING, URL_PATTERN, VIEW_ID field
-- is reached, insert the new configuration rule in the servlet registry.
-- ------------------------------
procedure Set_Member (N : in out Servlet_Config;
Field : in Servlet_Fields;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
Route : ASF.Routes.Servlets.Faces.Faces_Route_Type_Access;
begin
case Field is
when URL_PATTERN =>
N.URL_Pattern := Value;
when VIEW_ID =>
N.View_Id := Value;
when URL_MAPPING =>
declare
View : constant String := To_String (N.View_Id);
Servlet : constant ASF.Servlets.Servlet_Access := Find_Servlet (N.Handler, View);
begin
Route := new ASF.Routes.Servlets.Faces.Faces_Route_Type;
Route.View := To_Unbounded_String (View);
Route.Servlet := Servlet;
N.Handler.Add_Route (Pattern => To_String (N.URL_Pattern),
To => Route.all'Access,
ELContext => N.Context.all);
exception
when others =>
Free (Route);
raise;
end;
end case;
end Set_Member;
SMapper : aliased Servlet_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the servlet and mapping rules <b>url-mapping</b>.
-- ------------------------------
package body Reader_Config is
begin
Reader.Add_Mapping ("faces-config", SMapper'Access);
Reader.Add_Mapping ("module", SMapper'Access);
Reader.Add_Mapping ("web-app", SMapper'Access);
Config.Handler := Handler;
Config.Context := Context;
Servlet_Mapper.Set_Context (Reader, Config'Unchecked_Access);
end Reader_Config;
begin
SMapper.Add_Mapping ("url-mapping", URL_MAPPING);
SMapper.Add_Mapping ("url-mapping/pattern", URL_PATTERN);
SMapper.Add_Mapping ("url-mapping/view-id", VIEW_ID);
end ASF.Servlets.Faces.Mappers;
|
Read the faces extension configuration to add support for pretty URL with URL parameter injection
|
Read the faces extension configuration to add support for pretty URL
with URL parameter injection
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
|
c0ae7de8dea2a3b5749d8af26f18c9f40278a717
|
regtests/util-files-tests.adb
|
regtests/util-files-tests.adb
|
-----------------------------------------------------------------------
-- files.tests -- Unit tests for files
-- 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.Directories;
with Util.Test_Caller;
package body Util.Files.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Files");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Files.Read_File",
Test_Read_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Read_File (missing)",
Test_Read_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Read_File (truncate)",
Test_Read_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Write_File",
Test_Write_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Iterate_Path",
Test_Iterate_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Find_File_Path",
Test_Find_File_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Compose_Path",
Test_Compose_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Get_Relative_Path",
Test_Get_Relative_Path'Access);
end Add_Tests;
-- ------------------------------
-- Test reading a file into a string
-- Reads this ada source file and checks we have read it correctly
-- ------------------------------
procedure Test_Read_File (T : in out Test) is
Result : Unbounded_String;
begin
Read_File (Path => "regtests/util-files-tests.adb", Into => Result);
T.Assert (Index (Result, "Util.Files.Tests") > 0,
"Content returned by Read_File is not correct");
T.Assert (Index (Result, "end Util.Files.Tests;") > 0,
"Content returned by Read_File is not correct");
end Test_Read_File;
procedure Test_Read_File_Missing (T : in out Test) is
Result : Unbounded_String;
pragma Unreferenced (Result);
begin
Read_File (Path => "regtests/files-test--util.adb", Into => Result);
T.Assert (False, "No exception raised");
exception
when others =>
null;
end Test_Read_File_Missing;
procedure Test_Read_File_Truncate (T : in out Test) is
Result : Unbounded_String;
begin
Read_File (Path => "regtests/util-files-tests.adb", Into => Result,
Max_Size => 50);
Assert_Equals (T, Length (Result), 50,
"Read_File did not truncate correctly");
T.Assert (Index (Result, "Apache License") > 0,
"Content returned by Read_File is not correct");
end Test_Read_File_Truncate;
-- ------------------------------
-- Check writing a file
-- ------------------------------
procedure Test_Write_File (T : in out Test) is
Path : constant String := Util.Tests.Get_Test_Path ("test-write.txt");
Content : constant String := "Testing Util.Files.Write_File" & ASCII.LF;
Result : Unbounded_String;
begin
Write_File (Path => Path, Content => Content);
Read_File (Path => Path, Into => Result);
Assert_Equals (T, To_String (Result), Content,
"Invalid content written or read");
end Test_Write_File;
-- ------------------------------
-- Check Find_File_Path
-- ------------------------------
procedure Test_Find_File_Path (T : in out Test) is
Dir : constant String := Util.Tests.Get_Path ("regtests");
Paths : constant String := ".;" & Dir;
begin
declare
P : constant String := Util.Files.Find_File_Path ("test.properties", Paths);
begin
Assert_Equals (T, Dir & "/test.properties", P,
"Invalid path returned");
end;
Assert_Equals (T, "blablabla.properties",
Util.Files.Find_File_Path ("blablabla.properties", Paths));
end Test_Find_File_Path;
-- ------------------------------
-- Check Iterate_Path
-- ------------------------------
procedure Test_Iterate_Path (T : in out Test) is
procedure Check_Path (Dir : in String;
Done : out Boolean);
Last : Unbounded_String;
procedure Check_Path (Dir : in String;
Done : out Boolean) is
begin
if Dir = "a" or Dir = "bc" or Dir = "de" then
Done := False;
else
Done := True;
Last := To_Unbounded_String (Dir);
end if;
end Check_Path;
begin
Iterate_Path ("a;bc;de;f", Check_Path'Access);
Assert_Equals (T, "f", Last, "Invalid last path");
Iterate_Path ("de;bc;de;b", Check_Path'Access);
Assert_Equals (T, "b", Last, "Invalid last path");
end Test_Iterate_Path;
-- ------------------------------
-- Test the Compose_Path operation
-- ------------------------------
procedure Test_Compose_Path (T : in out Test) is
begin
Assert_Equals (T, "src/os-none",
Compose_Path ("src;regtests", "os-none"),
"Invalid path composition");
Assert_Equals (T, "regtests/bundles",
Compose_Path ("src;regtests", "bundles"),
"Invalid path composition");
if Ada.Directories.Exists ("/usr/bin") then
Assert_Equals (T, "/usr/bin;/usr/local/bin;/usr/bin",
Compose_Path ("/usr;/usr/local;/usr", "bin"),
"Invalid path composition");
end if;
end Test_Compose_Path;
-- ------------------------------
-- Test the Get_Relative_Path operation.
-- ------------------------------
procedure Test_Get_Relative_Path (T : in out Test) is
begin
Assert_Equals (T, "../util",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util"),
"Invalid relative path");
Assert_Equals (T, "../util",
Get_Relative_Path ("/home/john/src/asf/", "/home/john/src/util"),
"Invalid relative path");
Assert_Equals (T, "../util/b",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util/b"),
"Invalid relative path");
Assert_Equals (T, "../as",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/as"),
"Invalid relative path");
Assert_Equals (T, "../../",
Get_Relative_Path ("/home/john/src/asf", "/home/john"),
"Invalid relative path");
Assert_Equals (T, "/usr/share/admin",
Get_Relative_Path ("/home/john/src/asf", "/usr/share/admin"),
"Invalid absolute path");
Assert_Equals (T, "/home/john",
Get_Relative_Path ("home/john/src/asf", "/home/john"),
"Invalid relative path");
Assert_Equals (T, "e",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/e"),
"Invalid relative path");
Assert_Equals (T, ".",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/"),
"Invalid relative path");
end Test_Get_Relative_Path;
end Util.Files.Tests;
|
-----------------------------------------------------------------------
-- files.tests -- Unit tests for files
-- 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.Directories;
with Util.Test_Caller;
package body Util.Files.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Files");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Files.Read_File",
Test_Read_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Read_File (missing)",
Test_Read_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Read_File (truncate)",
Test_Read_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Write_File",
Test_Write_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Iterate_Path",
Test_Iterate_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Find_File_Path",
Test_Find_File_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Compose_Path",
Test_Compose_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Get_Relative_Path",
Test_Get_Relative_Path'Access);
end Add_Tests;
-- ------------------------------
-- Test reading a file into a string
-- Reads this ada source file and checks we have read it correctly
-- ------------------------------
procedure Test_Read_File (T : in out Test) is
Result : Unbounded_String;
begin
Read_File (Path => "regtests/util-files-tests.adb", Into => Result);
T.Assert (Index (Result, "Util.Files.Tests") > 0,
"Content returned by Read_File is not correct");
T.Assert (Index (Result, "end Util.Files.Tests;") > 0,
"Content returned by Read_File is not correct");
end Test_Read_File;
procedure Test_Read_File_Missing (T : in out Test) is
Result : Unbounded_String;
pragma Unreferenced (Result);
begin
Read_File (Path => "regtests/files-test--util.adb", Into => Result);
T.Assert (False, "No exception raised");
exception
when others =>
null;
end Test_Read_File_Missing;
procedure Test_Read_File_Truncate (T : in out Test) is
Result : Unbounded_String;
begin
Read_File (Path => "regtests/util-files-tests.adb", Into => Result,
Max_Size => 50);
Assert_Equals (T, Length (Result), 50,
"Read_File did not truncate correctly");
T.Assert (Index (Result, "Apache License") > 0,
"Content returned by Read_File is not correct");
end Test_Read_File_Truncate;
-- ------------------------------
-- Check writing a file
-- ------------------------------
procedure Test_Write_File (T : in out Test) is
Path : constant String := Util.Tests.Get_Test_Path ("test-write.txt");
Content : constant String := "Testing Util.Files.Write_File" & ASCII.LF;
Result : Unbounded_String;
begin
Write_File (Path => Path, Content => Content);
Read_File (Path => Path, Into => Result);
Assert_Equals (T, To_String (Result), Content,
"Invalid content written or read");
end Test_Write_File;
-- ------------------------------
-- Check Find_File_Path
-- ------------------------------
procedure Test_Find_File_Path (T : in out Test) is
Dir : constant String := Util.Tests.Get_Path ("regtests");
Paths : constant String := ".;" & Dir;
begin
declare
P : constant String := Util.Files.Find_File_Path ("test.properties", Paths);
begin
Assert_Equals (T, Dir & "/test.properties", P,
"Invalid path returned");
end;
Assert_Equals (T, "blablabla.properties",
Util.Files.Find_File_Path ("blablabla.properties", Paths));
end Test_Find_File_Path;
-- ------------------------------
-- Check Iterate_Path
-- ------------------------------
procedure Test_Iterate_Path (T : in out Test) is
procedure Check_Path (Dir : in String;
Done : out Boolean);
Last : Unbounded_String;
procedure Check_Path (Dir : in String;
Done : out Boolean) is
begin
if Dir = "a" or Dir = "bc" or Dir = "de" then
Done := False;
else
Done := True;
end if;
Last := To_Unbounded_String (Dir);
end Check_Path;
begin
Iterate_Path ("a;bc;de;f", Check_Path'Access);
Assert_Equals (T, "f", Last, "Invalid last path");
Iterate_Path ("de;bc;de;b", Check_Path'Access);
Assert_Equals (T, "b", Last, "Invalid last path");
Iterate_Path ("de;bc;de;a", Check_Path'Access, Ada.Strings.Backward);
Assert_Equals (T, "de", Last, "Invalid last path");
end Test_Iterate_Path;
-- ------------------------------
-- Test the Compose_Path operation
-- ------------------------------
procedure Test_Compose_Path (T : in out Test) is
begin
Assert_Equals (T, "src/os-none",
Compose_Path ("src;regtests", "os-none"),
"Invalid path composition");
Assert_Equals (T, "regtests/bundles",
Compose_Path ("src;regtests", "bundles"),
"Invalid path composition");
if Ada.Directories.Exists ("/usr/bin") then
Assert_Equals (T, "/usr/bin;/usr/local/bin;/usr/bin",
Compose_Path ("/usr;/usr/local;/usr", "bin"),
"Invalid path composition");
end if;
end Test_Compose_Path;
-- ------------------------------
-- Test the Get_Relative_Path operation.
-- ------------------------------
procedure Test_Get_Relative_Path (T : in out Test) is
begin
Assert_Equals (T, "../util",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util"),
"Invalid relative path");
Assert_Equals (T, "../util",
Get_Relative_Path ("/home/john/src/asf/", "/home/john/src/util"),
"Invalid relative path");
Assert_Equals (T, "../util/b",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util/b"),
"Invalid relative path");
Assert_Equals (T, "../as",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/as"),
"Invalid relative path");
Assert_Equals (T, "../../",
Get_Relative_Path ("/home/john/src/asf", "/home/john"),
"Invalid relative path");
Assert_Equals (T, "/usr/share/admin",
Get_Relative_Path ("/home/john/src/asf", "/usr/share/admin"),
"Invalid absolute path");
Assert_Equals (T, "/home/john",
Get_Relative_Path ("home/john/src/asf", "/home/john"),
"Invalid relative path");
Assert_Equals (T, "e",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/e"),
"Invalid relative path");
Assert_Equals (T, ".",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/"),
"Invalid relative path");
end Test_Get_Relative_Path;
end Util.Files.Tests;
|
Add test to check iterating over the search paths in reverse order
|
Add test to check iterating over the search paths in reverse order
|
Ada
|
apache-2.0
|
Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util,Letractively/ada-util
|
89f3c619fe1b1ac44f4d5c7cf22cdf32cb935963
|
src/util-concurrent-fifos.adb
|
src/util-concurrent-fifos.adb
|
-----------------------------------------------------------------------
-- Util.Concurrent.Fifos -- Concurrent Fifo Queues
-- 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.Unchecked_Deallocation;
package body Util.Concurrent.Fifos is
-- ------------------------------
-- Put the element in the queue.
-- ------------------------------
procedure Enqueue (Into : in out Fifo;
Item : in Element_Type;
Wait : in Duration := FOREVER) is
begin
if Wait < 0.0 then
Into.Buffer.Enqueue (Item);
else
select
Into.Buffer.Enqueue (Item);
or
delay Wait;
raise Timeout;
end select;
end if;
end Enqueue;
-- ------------------------------
-- Get an element from the queue.
-- Wait until one element gets available.
-- ------------------------------
procedure Dequeue (From : in out Fifo;
Item : out Element_Type;
Wait : in Duration := FOREVER) is
begin
if Wait < 0.0 then
From.Buffer.Dequeue (Item);
else
select
From.Buffer.Dequeue (Item);
or
delay Wait;
raise Timeout;
end select;
end if;
end Dequeue;
-- ------------------------------
-- Get the number of elements in the queue.
-- ------------------------------
function Get_Count (From : in Fifo) return Natural is
begin
return From.Buffer.Get_Count;
end Get_Count;
-- ------------------------------
-- Set the queue size.
-- ------------------------------
procedure Set_Size (Into : in out Fifo;
Capacity : in Positive) is
begin
Into.Buffer.Set_Size (Capacity);
end Set_Size;
-- ------------------------------
-- Initializes the queue.
-- ------------------------------
overriding
procedure Initialize (Object : in out Fifo) is
begin
Object.Buffer.Set_Size (Default_Size);
end Initialize;
-- ------------------------------
-- Release the queue elements.
-- ------------------------------
overriding
procedure Finalize (Object : in out Fifo) is
begin
if Clear_On_Dequeue then
while Object.Get_Count > 0 loop
declare
Unused : Element_Type;
begin
Object.Dequeue (Unused);
end;
end loop;
end if;
Object.Buffer.Set_Size (0);
end Finalize;
-- Queue of objects.
protected body Protected_Fifo is
-- ------------------------------
-- Put the element in the queue.
-- If the queue is full, wait until some room is available.
-- ------------------------------
entry Enqueue (Item : in Element_Type) when Count < Elements'Length is
begin
Elements (Last) := Item;
Last := Last + 1;
if Last > Elements'Last then
Last := Elements'First;
end if;
Count := Count + 1;
end Enqueue;
-- ------------------------------
-- Get an element from the queue.
-- Wait until one element gets available.
-- ------------------------------
entry Dequeue (Item : out Element_Type) when Count > 0 is
begin
Count := Count - 1;
Item := Elements (First);
-- For the clear on dequeue mode, erase the queue element.
-- If the element holds some storage or a reference, this gets cleared here.
-- The element used to clear is at index 0 (which does not exist if Clear_On_Dequeue
-- is false). There is no overhead when this is not used
-- (ie, instantiation/compile time flag).
if Clear_On_Dequeue then
Elements (First) := Elements (0);
end if;
First := First + 1;
if First > Elements'Last then
First := Elements'First;
end if;
end Dequeue;
-- ------------------------------
-- Get the number of elements in the queue.
-- ------------------------------
function Get_Count return Natural is
begin
return Count;
end Get_Count;
-- ------------------------------
-- Set the queue size.
-- ------------------------------
procedure Set_Size (Capacity : in Natural) is
procedure Free is new Ada.Unchecked_Deallocation (Element_Array, Element_Array_Access);
First_Pos : Natural := 1;
begin
if Clear_On_Dequeue then
First_Pos := 0;
end if;
if Capacity = 0 then
Free (Elements);
elsif Elements = null then
Elements := new Element_Array (First_Pos .. Capacity);
else
declare
New_Array : Element_Array_Access := new Element_Array (First_Pos .. Capacity);
begin
if Capacity > Elements'Length then
New_Array (First_Pos .. Elements'Last) := Elements (First_Pos .. Elements'Last);
else
New_Array (First_Pos .. Capacity) := Elements (First_Pos .. Capacity);
end if;
Free (Elements);
Elements := New_Array;
end;
end if;
end Set_Size;
end Protected_Fifo;
end Util.Concurrent.Fifos;
|
-----------------------------------------------------------------------
-- Util.Concurrent.Fifos -- Concurrent Fifo Queues
-- 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.Unchecked_Deallocation;
package body Util.Concurrent.Fifos is
-- ------------------------------
-- Put the element in the queue.
-- ------------------------------
procedure Enqueue (Into : in out Fifo;
Item : in Element_Type;
Wait : in Duration := FOREVER) is
begin
if Wait < 0.0 then
Into.Buffer.Enqueue (Item);
else
select
Into.Buffer.Enqueue (Item);
or
delay Wait;
raise Timeout;
end select;
end if;
end Enqueue;
-- ------------------------------
-- Get an element from the queue.
-- Wait until one element gets available.
-- ------------------------------
procedure Dequeue (From : in out Fifo;
Item : out Element_Type;
Wait : in Duration := FOREVER) is
begin
if Wait < 0.0 then
From.Buffer.Dequeue (Item);
else
select
From.Buffer.Dequeue (Item);
or
delay Wait;
raise Timeout;
end select;
end if;
end Dequeue;
-- ------------------------------
-- Get the number of elements in the queue.
-- ------------------------------
function Get_Count (From : in Fifo) return Natural is
begin
return From.Buffer.Get_Count;
end Get_Count;
-- ------------------------------
-- Set the queue size.
-- ------------------------------
procedure Set_Size (Into : in out Fifo;
Capacity : in Positive) is
begin
Into.Buffer.Set_Size (Capacity);
end Set_Size;
-- ------------------------------
-- Initializes the queue.
-- ------------------------------
overriding
procedure Initialize (Object : in out Fifo) is
begin
Object.Buffer.Set_Size (Default_Size);
end Initialize;
-- ------------------------------
-- Release the queue elements.
-- ------------------------------
overriding
procedure Finalize (Object : in out Fifo) is
begin
if Clear_On_Dequeue then
while Object.Get_Count > 0 loop
declare
Unused : Element_Type;
begin
Object.Dequeue (Unused);
end;
end loop;
end if;
Object.Buffer.Set_Size (0);
end Finalize;
-- Queue of objects.
protected body Protected_Fifo is
-- ------------------------------
-- Put the element in the queue.
-- If the queue is full, wait until some room is available.
-- ------------------------------
entry Enqueue (Item : in Element_Type) when Count < Elements'Length is
begin
Elements (Last) := Item;
Last := Last + 1;
if Last > Elements'Last then
if Clear_On_Dequeue then
Last := Elements'First + 1;
else
Last := Elements'First;
end if;
end if;
Count := Count + 1;
end Enqueue;
-- ------------------------------
-- Get an element from the queue.
-- Wait until one element gets available.
-- ------------------------------
entry Dequeue (Item : out Element_Type) when Count > 0 is
begin
Count := Count - 1;
Item := Elements (First);
-- For the clear on dequeue mode, erase the queue element.
-- If the element holds some storage or a reference, this gets cleared here.
-- The element used to clear is at index 0 (which does not exist if Clear_On_Dequeue
-- is false). There is no overhead when this is not used
-- (ie, instantiation/compile time flag).
if Clear_On_Dequeue then
Elements (First) := Elements (0);
end if;
First := First + 1;
if First > Elements'Last then
First := Elements'First;
end if;
end Dequeue;
-- ------------------------------
-- Get the number of elements in the queue.
-- ------------------------------
function Get_Count return Natural is
begin
return Count;
end Get_Count;
-- ------------------------------
-- Set the queue size.
-- ------------------------------
procedure Set_Size (Capacity : in Natural) is
procedure Free is new Ada.Unchecked_Deallocation (Element_Array, Element_Array_Access);
First_Pos : Natural := 1;
begin
if Clear_On_Dequeue then
First_Pos := 0;
end if;
if Capacity = 0 then
Free (Elements);
elsif Elements = null then
Elements := new Element_Array (First_Pos .. Capacity);
else
declare
New_Array : Element_Array_Access := new Element_Array (First_Pos .. Capacity);
begin
if Capacity > Elements'Length then
New_Array (First_Pos .. Elements'Last) := Elements (First_Pos .. Elements'Last);
else
New_Array (First_Pos .. Capacity) := Elements (First_Pos .. Capacity);
end if;
Free (Elements);
Elements := New_Array;
end;
end if;
end Set_Size;
end Protected_Fifo;
end Util.Concurrent.Fifos;
|
Fix queue wrapping in the Clear_On_Dequeue instantiation mode
|
Fix queue wrapping in the Clear_On_Dequeue instantiation mode
|
Ada
|
apache-2.0
|
Letractively/ada-util,flottokarotto/ada-util,Letractively/ada-util,flottokarotto/ada-util
|
6f3f1e8053acf5119360b736de468e15695119f0
|
src/asf-components-widgets-likes.adb
|
src/asf-components-widgets-likes.adb
|
-----------------------------------------------------------------------
-- components-widgets-likes -- Social Likes 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 Util.Locales;
with Util.Beans.Objects;
with Util.Strings.Tokenizers;
with ASF.Requests;
with ASF.Contexts.Writer;
package body ASF.Components.Widgets.Likes is
FB_LAYOUT_ATTR : aliased constant String := "data-layout";
FB_SHOW_FACES_ATTR : aliased constant String := "data-show-faces";
FB_WIDTH_ATTR : aliased constant String := "data-width";
FB_ACTION_ATTR : aliased constant String := "data-action";
FB_FONT_ATTR : aliased constant String := "data-font";
FB_COlORSCHEME_ATTR : aliased constant String := "data-colorscheme";
FB_REF_ATTR : aliased constant String := "data-ref";
FB_KIDS_ATTR : aliased constant String := "data-kid_directed_site";
FACEBOOK_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
FACEBOOK_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.facebook.script";
type Like_Generator_Binding is record
Name : Util.Strings.Name_Access;
Generator : Like_Generator_Access;
end record;
type Like_Generator_Array is array (1 .. MAX_LIKE_GENERATOR) of Like_Generator_Binding;
FB_NAME : aliased constant String := "facebook";
FB_GENERATOR : aliased Facebook_Like_Generator;
Generators : Like_Generator_Array := (1 => (FB_NAME'Access, FB_GENERATOR'Access),
others => (null, null));
-- ------------------------------
-- Render the facebook like button according to the component attributes.
-- ------------------------------
overriding
procedure Render_Like (Generator : in Facebook_Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
Request : constant ASF.Requests.Request_Access := Context.Get_Request;
begin
if not Context.Is_Ajax_Request and then
Util.Beans.Objects.Is_Null (Request.Get_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE)) then
Request.Set_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True));
Writer.Queue_Script ("(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0];"
& "if (d.getElementById(id)) return;"
& "js = d.createElement(s); js.id = id;"
& "js.src = ""//connect.facebook.net/");
Writer.Queue_Script (Util.Locales.To_String (Context.Get_Locale));
Writer.Queue_Script ("/all.js#xfbml=1&;appId=116337738505130");
Writer.Queue_Script (Generator.App_Id);
Writer.Queue_Script (""";fjs.parentNode.insertBefore(js, fjs);"
& "}(document, 'script', 'facebook-jssdk'));");
Writer.Start_Element ("div");
Writer.Write_Attribute ("id", "fb-root");
Writer.End_Element ("div");
end if;
Writer.Start_Element ("div");
Writer.Write_Attribute ("class", "fb-like");
Writer.Write_Attribute ("data-href", Href);
Writer.Write_Attribute ("data-send", "true");
UI.Render_Attributes (Context, FACEBOOK_ATTRIBUTE_NAMES, Writer);
Writer.End_Element ("div");
end Render_Like;
-- ------------------------------
-- Get the link to submit in the like action.
-- ------------------------------
function Get_Link (UI : in UILike;
Context : in ASF.Contexts.Faces.Faces_Context'Class) return String is
Href : constant String := UI.Get_Attribute ("href", Context, "");
begin
if Href'Length > 0 then
return Href;
else
return Context.Get_Request.Get_Request_URI;
end if;
end Get_Link;
-- ------------------------------
-- Render an image with the source link created from an email address to the Gravatars service.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UILike;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
begin
if UI.Is_Rendered (Context) then
declare
Kind : constant String := UI.Get_Attribute ("type", Context, "");
Href : constant String := UILike'Class (UI).Get_Link (Context);
procedure Render (Name : in String; Done : out Boolean);
procedure Render (Name : in String;
Done : out Boolean) is
use type Util.Strings.Name_Access;
begin
Done := False;
for I in Generators'Range loop
exit when Generators (I).Name = null;
if Generators (I).Name.all = Name then
Generators (I).Generator.Render_Like (UI, Href, Context);
return;
end if;
end loop;
UI.Log_Error ("Like type {0} is not recognized", Name);
end Render;
begin
if Kind'Length = 0 then
UI.Log_Error ("The like type is empty.");
else
Util.Strings.Tokenizers.Iterate_Tokens (Content => Kind, Pattern => ",",
Process => Render'Access);
end if;
end;
end if;
end Encode_Begin;
-- ------------------------------
-- Register the like generator under the given name.
-- ------------------------------
procedure Register_Like (Name : in Util.Strings.Name_Access;
Generator : in Like_Generator_Access) is
use type Util.Strings.Name_Access;
begin
for I in Generators'Range loop
if Generators (I).Name = null then
Generators (I).Name := Name;
Generators (I).Generator := Generator;
return;
end if;
end loop;
end Register_Like;
begin
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_LAYOUT_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SHOW_FACES_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_WIDTH_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_ACTION_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_FONT_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_COlORSCHEME_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_REF_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_KIDS_ATTR'Access);
end ASF.Components.Widgets.Likes;
|
Implement the <w:like> button with Facebook like support
|
Implement the <w:like> button with Facebook like support
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
|
261612ce9af416be1eb10f5909c5d667a1f9e642
|
src/asis/asis-implementation-permissions.ads
|
src/asis/asis-implementation-permissions.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT INTERFACE COMPONENTS --
-- --
-- A S I S . I M P L E M E N T A T I O N . P E R M I S S I O N S --
-- --
-- S p e c --
-- --
-- $Revision: 14416 $
-- --
-- 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. --
-- --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- 7 package Asis.Implementation.Permissions
------------------------------------------------------------------------------
package Asis.Implementation.Permissions is
------------------------------------------------------------------------------
-- 7.1 function Is_Formal_Parameter_Named_Notation_Supported
------------------------------------------------------------------------------
function Is_Formal_Parameter_Named_Notation_Supported return Boolean;
------------------------------------------------------------------------------
-- Returns True if it is possible to detect usage of named notation.
--
-- Returns False if this implementation will always change parameter lists
-- using named notation to positional lists in function, subprogram, and
-- entry calls. In that case, the Formal_Parameter query will always return
-- a Nil_Element unless the parameter list is obtained with Normalized = True.
--
-- This function affects association lists for aggregates, instantiations,
-- discriminant lists, entry calls, and subprogram calls.
--
------------------------------------------------------------------------------
-- 7.2 function Default_In_Mode_Supported
------------------------------------------------------------------------------
function Default_In_Mode_Supported return Boolean;
------------------------------------------------------------------------------
-- Returns True if the A_Default_In_Mode kind is supported by this
-- implementation.
--
------------------------------------------------------------------------------
-- 7.3 function Generic_Actual_Part_Normalized
------------------------------------------------------------------------------
function Generic_Actual_Part_Normalized return Boolean;
------------------------------------------------------------------------------
-- Returns True if the query Generic_Actual_Part will always return artificial
-- Is_Normalized associations using the defining_identifier instead of the
-- generic_formal_parameter_selector_name, and using default_expression or
-- default_name.
--
-- if Generic_Actual_Part_Normalized then the query Generic_Actual_Part will
-- always behave as if called with Normalized => True.
--
------------------------------------------------------------------------------
-- 7.4 function Record_Component_Associations_Normalized
------------------------------------------------------------------------------
function Record_Component_Associations_Normalized return Boolean;
------------------------------------------------------------------------------
-- Returns True if the query Record_Component_Associations will always return
-- artificial Is_Normalized associations using the defining_identifier instead
-- of the component_selector_name.
--
-- if Record_Component_Associations_Normalized then the query
-- Record_Component_Associations will always behave as if called with
-- Normalized => True.
--
------------------------------------------------------------------------------
-- 7.5 function Is_Prefix_Call_Supported
------------------------------------------------------------------------------
function Is_Prefix_Call_Supported return Boolean;
------------------------------------------------------------------------------
-- Returns True if the ASIS implementation has the ability to determine
-- whether calls are in prefix form.
--
------------------------------------------------------------------------------
-- 7.6 function Function_Call_Parameters_Normalized
------------------------------------------------------------------------------
function Function_Call_Parameters_Normalized return Boolean;
------------------------------------------------------------------------------
-- Returns True if the query Function_Call_Parameters will always return
-- artificial Is_Normalized associations using the defining_identifier instead
-- of the formal_parameter_selector_name, and using the default_expression.
--
-- if Function_Call_Parameters_Normalized then the query
-- Function_Call_Parameters will always behave as if called with
-- Normalized => True.
--
------------------------------------------------------------------------------
-- 7.7 function Call_Statement_Parameters_Normalized
------------------------------------------------------------------------------
function Call_Statement_Parameters_Normalized return Boolean;
------------------------------------------------------------------------------
-- Returns True if the query Call_Statement_Parameters will always return
-- artificial Is_Normalized associations using the defining_identifier instead
-- of the formal_parameter_selector_name, and using the default_expression.
--
-- if Call_Statement_Parameters_Normalized then the query
-- Call_Statement_Parameters will always behave as if called with
-- Normalized => True.
--
------------------------------------------------------------------------------
-- It is not possible to obtain either a normalized or
-- unnormalized Discriminant_Association list for an unconstrained record
-- or derived subtype_indication where the discriminant_association is
-- supplied by default; there is no constraint to query, and a Nil_Element
-- is returned from the query Subtype_Constraint.
--
------------------------------------------------------------------------------
-- 7.8 function Discriminant_Associations_Normalized
------------------------------------------------------------------------------
function Discriminant_Associations_Normalized return Boolean;
------------------------------------------------------------------------------
-- Returns True if the query Discriminant_Associations will always return
-- artificial Is_Normalized associations using the defining_identifier instead
-- of the discriminant_selector_name.
--
-- if Discriminant_Associations_Normalized then the query
-- Discriminant_Associations will always behave as if called with
-- Normalized => True.
--
------------------------------------------------------------------------------
-- 7.9 function Is_Line_Number_Supported
------------------------------------------------------------------------------
function Is_Line_Number_Supported return Boolean;
------------------------------------------------------------------------------
-- Returns True if the implementation can return valid line numbers for
-- Elements.
--
-- An implementation may choose to ignore line number values in which case
-- this function returns False.
--
------------------------------------------------------------------------------
-- 7.10 function Is_Span_Column_Position_Supported
------------------------------------------------------------------------------
function Is_Span_Column_Position_Supported return Boolean;
------------------------------------------------------------------------------
-- Returns True if the implementation can return valid character positions for
-- elements.
--
-- An implementation may choose to ignore column character position values
-- within spans in which case this function returns False. This function will
-- be False if Is_Line_Number_Supported = False.
--
------------------------------------------------------------------------------
-- 7.11 function Is_Commentary_Supported
------------------------------------------------------------------------------
function Is_Commentary_Supported return Boolean;
------------------------------------------------------------------------------
-- Returns True if the implementation can return comments.
--
-- An implementation may choose to ignore comments in the text in which case
-- the function Is_Commentary_Supported returns False.
--
------------------------------------------------------------------------------
-- 7.12 function Attributes_Are_Supported
------------------------------------------------------------------------------
function Attributes_Are_Supported return Boolean;
------------------------------------------------------------------------------
-- Returns True if an implementation supports compilation unit attributes.
-- Returns False if all attributes will return Has_Attribute() = False.
--
------------------------------------------------------------------------------
-- 7.13 function Implicit_Components_Supported
------------------------------------------------------------------------------
function Implicit_Components_Supported return Boolean;
------------------------------------------------------------------------------
-- Returns True if the implementation provides elements representing
-- implicit implementation-defined record components.
--
------------------------------------------------------------------------------
-- 7.14 function Object_Declarations_Normalized
------------------------------------------------------------------------------
function Object_Declarations_Normalized return Boolean;
------------------------------------------------------------------------------
-- Returns True if the implementation normalizes multiple object declarations
-- to an equivalent sequence of single declarations.
--
------------------------------------------------------------------------------
-- 7.15 function Predefined_Operations_Supported
------------------------------------------------------------------------------
function Predefined_Operations_Supported return Boolean;
------------------------------------------------------------------------------
-- Returns True if the implementation supports queries of predefined
-- operations.
--
------------------------------------------------------------------------------
-- 7.16 function Inherited_Declarations_Supported
------------------------------------------------------------------------------
function Inherited_Declarations_Supported return Boolean;
------------------------------------------------------------------------------
-- Returns True if the implementation supports queries of inherited
-- declarations.
--
------------------------------------------------------------------------------
-- 7.17 function Inherited_Subprograms_Supported
------------------------------------------------------------------------------
function Inherited_Subprograms_Supported return Boolean;
------------------------------------------------------------------------------
-- Returns True if the implementation supports queries of inherited
-- subprograms.
--
------------------------------------------------------------------------------
-- 7.18 function Generic_Macro_Expansion_Supported
------------------------------------------------------------------------------
function Generic_Macro_Expansion_Supported return Boolean;
------------------------------------------------------------------------------
-- Returns True if the implementation expands generics using macros to
-- supports queries.
------------------------------------------------------------------------------
end Asis.Implementation.Permissions;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
49c20de4e99746bcd66a3c6011756b6539e9b355
|
src/security-policies-urls.adb
|
src/security-policies-urls.adb
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- Copyright (C) 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.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Ada.Unchecked_Deallocation;
with Ada.Strings.Unbounded;
with Util.Refs;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.IO.XML;
with Util.Serialize.Mappers;
with Util.Serialize.Mappers.Record_Mapper;
with GNAT.Regexp;
with Security.Controllers;
package body Security.Policies.Urls is
-- ------------------------------
-- URL policy
-- ------------------------------
-- Get the policy name.
overriding
function Get_Name (From : in URL_Policy) return String is
begin
return NAME;
end Get_Name;
-- Returns True if the user has the permission to access the given URI permission.
function Has_Permission (Manager : in URL_Policy;
Context : in Security_Context_Access;
Permission : in URI_Permission'Class) return Boolean is
Name : constant String_Ref := To_String_Ref (Permission.URI);
Ref : constant Rules_Ref.Ref := Manager.Cache.Get;
Rules : constant Rules_Access := Ref.Value;
Pos : constant Rules_Maps.Cursor := Rules.Map.Find (Name);
Rule : Access_Rule_Ref;
begin
-- If the rule is not in the cache, search for the access rule that
-- matches our URI. Update the cache. This cache update is thread-safe
-- as the cache map is never modified: a new cache map is installed.
if not Rules_Maps.Has_Element (Pos) then
declare
New_Ref : constant Rules_Ref.Ref := Rules_Ref.Create;
begin
Rule := Manager.Find_Access_Rule (Permission.URI);
New_Ref.Value.all.Map := Rules.Map;
New_Ref.Value.all.Map.Insert (Name, Rule);
Manager.Cache.Set (New_Ref);
end;
else
Rule := Rules_Maps.Element (Pos);
end if;
-- Check if the user has one of the required permission.
declare
P : constant Access_Rule_Access := Rule.Value;
Granted : Boolean;
begin
if P /= null then
for I in P.Permissions'Range loop
-- Context.Has_Permission (P.Permissions (I), Granted);
if Granted then
return True;
end if;
end loop;
end if;
end;
return False;
end Has_Permission;
-- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b>
-- permissions.
procedure Grant_URI_Permission (Manager : in out URL_Policy;
URI : in String;
To : in String) is
begin
null;
end Grant_URI_Permission;
-- ------------------------------
-- Policy Configuration
-- ------------------------------
type Policy_Config is record
Id : Natural := 0;
Permissions : Util.Beans.Objects.Vectors.Vector;
Patterns : Util.Beans.Objects.Vectors.Vector;
Manager : URL_Policy_Access;
end record;
type Policy_Config_Access is access all Policy_Config;
-- Setup the XML parser to read the <b>policy</b> description. For example:
-- Find the access rule of the policy that matches the given URI.
-- Returns the No_Rule value (disable access) if no rule is found.
function Find_Access_Rule (Manager : in URL_Policy;
URI : in String) return Access_Rule_Ref is
Matched : Boolean := False;
Result : Access_Rule_Ref;
procedure Match (P : in Policy);
procedure Match (P : in Policy) is
begin
if GNAT.Regexp.Match (URI, P.Pattern) then
Matched := True;
Result := P.Rule;
end if;
end Match;
Last : constant Natural := Manager.Policies.Last_Index;
begin
for I in 1 .. Last loop
Manager.Policies.Query_Element (I, Match'Access);
if Matched then
return Result;
end if;
end loop;
return Result;
end Find_Access_Rule;
-- ------------------------------
-- Initialize the permission manager.
-- ------------------------------
overriding
procedure Initialize (Manager : in out URL_Policy) is
begin
Manager.Cache := new Rules_Ref.Atomic_Ref;
Manager.Cache.Set (Rules_Ref.Create);
end Initialize;
-- ------------------------------
-- Finalize the permission manager.
-- ------------------------------
overriding
procedure Finalize (Manager : in out URL_Policy) is
use Ada.Strings.Unbounded;
use Security.Controllers;
procedure Free is
new Ada.Unchecked_Deallocation (Rules_Ref.Atomic_Ref,
Rules_Ref_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class,
Security.Controllers.Controller_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Controller_Access_Array,
Controller_Access_Array_Access);
begin
Free (Manager.Cache);
-- for I in Manager.Names'Range loop
-- exit when Manager.Names (I) = null;
-- Ada.Strings.Unbounded.Free (Manager.Names (I));
-- end loop;
end Finalize;
type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY);
procedure Set_Member (P : in out Policy_Config;
Field : in Policy_Fields;
Value : in Util.Beans.Objects.Object);
procedure Process (Policy : in Policy_Config);
procedure Set_Member (P : in out Policy_Config;
Field : in Policy_Fields;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_ID =>
P.Id := Util.Beans.Objects.To_Integer (Value);
when FIELD_PERMISSION =>
P.Permissions.Append (Value);
when FIELD_URL_PATTERN =>
P.Patterns.Append (Value);
when FIELD_POLICY =>
Process (P);
P.Id := 0;
P.Permissions.Clear;
P.Patterns.Clear;
end case;
end Set_Member;
procedure Process (Policy : in Policy_Config) is
Pol : Security.Policies.URLs.Policy;
Count : constant Natural := Natural (Policy.Permissions.Length);
Rule : constant Access_Rule_Ref := Access_Rule_Refs.Create (new Access_Rule (Count));
Iter : Util.Beans.Objects.Vectors.Cursor := Policy.Permissions.First;
Pos : Positive := 1;
begin
Pol.Rule := Rule;
-- Step 1: Initialize the list of permission index in Access_Rule from the permission names.
while Util.Beans.Objects.Vectors.Has_Element (Iter) loop
declare
Perm : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter);
Name : constant String := Util.Beans.Objects.To_String (Perm);
begin
Rule.Value.all.Permissions (Pos) := Permissions.Get_Permission_Index (Name);
Pos := Pos + 1;
exception
when Invalid_Name =>
raise Util.Serialize.Mappers.Field_Error with "Invalid permission: " & Name;
end;
Util.Beans.Objects.Vectors.Next (Iter);
end loop;
-- Step 2: Create one policy for each URL pattern
Iter := Policy.Patterns.First;
while Util.Beans.Objects.Vectors.Has_Element (Iter) loop
declare
Pattern : constant Util.Beans.Objects.Object
:= Util.Beans.Objects.Vectors.Element (Iter);
begin
Pol.Id := Policy.Id;
Pol.Pattern := GNAT.Regexp.Compile (Util.Beans.Objects.To_String (Pattern));
Policy.Manager.Policies.Append (Pol);
end;
Util.Beans.Objects.Vectors.Next (Iter);
end loop;
end Process;
package Policy_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Policy_Config,
Element_Type_Access => Policy_Config_Access,
Fields => Policy_Fields,
Set_Member => Set_Member);
Policy_Mapping : aliased Policy_Mapper.Mapper;
-- Setup the XML parser to read the <b>policy</b> description.
overriding
procedure Set_Reader_Config (Policy : in out URL_Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is
-- Policy_Mapping : aliased Policy_Mapper.Mapper;
Config : Policy_Config_Access := new Policy_Config;
begin
Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access);
Reader.Add_Mapping ("module", Policy_Mapping'Access);
Config.Manager := Policy'Unchecked_Access;
Policy_Mapper.Set_Context (Reader, Config);
end Set_Reader_Config;
begin
Policy_Mapping.Add_Mapping ("policy", FIELD_POLICY);
Policy_Mapping.Add_Mapping ("policy/@id", FIELD_ID);
Policy_Mapping.Add_Mapping ("policy/permission", FIELD_PERMISSION);
Policy_Mapping.Add_Mapping ("policy/url-pattern", FIELD_URL_PATTERN);
end Security.Policies.Urls;
|
Implement the URL security policy from the old Security.Permissions package
|
Implement the URL security policy from the old Security.Permissions package
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
|
42ef168f4785ea2ae235595127974b66fd3effae
|
regtests/util-http-headers-tests.adb
|
regtests/util-http-headers-tests.adb
|
-----------------------------------------------------------------------
-- util-http-headers-tests - Unit tests for 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 Util.Test_Caller;
package body Util.Http.Headers.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Headers");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Http.Headers.Get_Accepted",
Test_Get_Accepted'Access);
end Add_Tests;
-- ------------------------------
-- Test the Get_Accepted function.
-- ------------------------------
procedure Test_Get_Accepted (T : in out Test) is
use type Mimes.Mime_Access;
M : Mimes.Mime_Access;
begin
M := Get_Accepted ("image/gif", Mimes.Images);
T.Assert (M /= null, "Null mime returned");
T.Assert_Equals (M.all, Mimes.Gif, "Bad accept");
M := Get_Accepted ("image/*", Mimes.Images);
T.Assert (M /= null, "Null mime returned");
T.Assert_Equals (M.all, Mimes.Jpg, "Bad accept");
M := Get_Accepted ("image/* q=0.2, image/svg+xml", Mimes.Images);
T.Assert (M /= null, "Null mime returned");
T.Assert_Equals (M.all, Mimes.Svg, "Bad accept");
M := Get_Accepted ("image/* q=0.2, image/svg+xml", Mimes.Api);
T.Assert (M = null, "Should not match");
end Test_Get_Accepted;
end Util.Http.Headers.Tests;
|
Add the new tests for Headers package
|
Add the new tests for Headers package
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
|
7512864f63963e1afc2aa53fe42094f3f30da841
|
awa/plugins/awa-storages/src/awa-storages-stores.ads
|
awa/plugins/awa-storages/src/awa-storages-stores.ads
|
-----------------------------------------------------------------------
-- awa-storages-stores -- The storage interface
-- 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 ADO.Sessions;
with AWA.Storages.Models;
package AWA.Storages.Stores is
-- ------------------------------
-- Store Service
-- ------------------------------
type Store is limited interface;
type Store_Access is access all Store'Class;
procedure Save (Storage : in Store;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Path : in String) is abstract;
procedure Load (Storage : in Store;
From : in AWA.Storages.Models.Storage_Ref'Class;
Into : in String) is abstract;
end AWA.Storages.Stores;
|
Define the store interface to support several storage services (file, database, Amazon)
|
Define the store interface to support several storage services (file, database, Amazon)
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
|
5a14821e30c87c344eb8c5cc24b779f2b013c78a
|
src/asis/asis-data_decomposition-aux.ads
|
src/asis/asis-data_decomposition-aux.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 . A U X --
-- --
-- S p e c --
-- --
-- Copyright (c) 1995-2005, 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 auxiliary routines needed by queries from
-- Asis.Data_Decomposition.
with Snames; use Snames;
private package Asis.Data_Decomposition.Aux is
-- If the documentation of a function which works on ASIS Element does
-- not contain an explicit list of appropriate Element Kinds, this means,
-- that the functon does not check the kind of its actual, and a caller
-- is responsible for proving the correct argument.
function Subtype_Model_Kind (S : Element) return Type_Model_Kinds;
-- Defines Type_Model_Kind for A_Subtype_Indication Element.
-- The current approach is:
--
-- - if the model kind of the type mark of S is A_Complex_Dynamic_Model
-- or Not_A_Type_Model the result is also A_Complex_Dynamic_Model or
-- Not_A_Type_Model respectively, regardless of the constraint imposed
-- by S (if any); ???
-- - if S does not contain an explicit constraint, its model kind is the
-- same as of its type mark;
--
-- - if S contains an explicit constraint, then:
-- o if the constraint is static, the result is A_Simple_Static_Model;
--
-- o if the constraint is dynamic, but the only dynamic components
-- in this constraint are discriminants from the enclosing record
-- type definition, then the result is A_Simple_Dynamic_Model;
--
-- o otherwise the result is A_Complex_Dynamic_Model;
type Constraint_Model_Kinds is (
Not_A_Constraint_Model,
-- non-defined
Static_Constraint,
-- constraint is defined by static expressions
Discriminated,
-- all the dynamic expressions in the constrain are discriminants of
-- the enclosing record type definition
External);
-- the constraint contains external dynamic expressions
function Constraint_Model_Kind (C : Element) return Constraint_Model_Kinds;
-- Supposing that C is either index or discriminant constraint element,
-- this function checks the model kind of this constraint.
function Record_Model_Kind (R : Element) return Type_Model_Kinds;
-- Provided that R is of A_Record_Type_Definition kind, defines
-- the type model kind for it.
function Type_Definition_From_Subtype_Mark (S : Element) return Element;
-- Taking an Element which is a subtype mark defining a given component,
-- this query computes the type definition for the (base) type denoted
-- by this type mark.
function Discriminant_Part_From_Type_Definition
(T : Element)
return Element;
-- Provided that T is A_Type_Definition Element, it returns its
-- known_discriminant_part (Nil_Element if there is no
-- known_discriminant_part). In case of a derived type,
-- known_discriminant_part of the parent type is returned in case if
-- the declaration of this derived type does not have its own
-- known_discriminant_part
function Is_Derived_From_Record (TD : Element) return Boolean;
function Is_Derived_From_Array (TD : Element) return Boolean;
-- Check if TD is A_Derived_Type_Definition element defining a type which
-- is (directly or undirectly) derived from a record/array type.
function Root_Record_Definition (Type_Def : Element) return Element;
function Root_Array_Definition (Type_Def : Element) return Element;
-- If Is_Derived_From_Record/Is_Derived_From_Array (Type_Def), then this
-- function returns the definition of a record type/array from which this
-- type is derived (directly or indirectly). Otherwise it returns its
-- argument unchanged.
function Component_Type_Definition (E : Element) return Element;
-- Provided that E is of A_Component_Declaration (Record_Component
-- case) or A_Subtype_Indication (Array_Component case) kind (the function
-- does not check this, a caller is responsible for providing the right
-- argument), this function returns the type definition for this component
-- (it unwinds all the subtypings, but not derivations)
function Subtype_Entity (E : Element) return Entity_Id;
-- Given E as A_Subtype_Indication element, this function computes the
-- Entity Id of the corresponding type or subtype (which may be an
-- implicit type created by the compiler as well)
function Linear_Index
(Inds : Dimension_Indexes;
Ind_Lengths : Dimention_Length;
Conv : Convention_Id := Convention_Ada)
return Asis.ASIS_Natural;
function De_Linear_Index
(Index : Asis.ASIS_Natural;
D : ASIS_Natural;
Ind_Lengths : Dimention_Length;
Conv : Convention_Id := Convention_Ada)
return Dimension_Indexes;
-- These two functions perform index linearizetion-delinearization
-- for DDA queries working with array componnets and indexes
-- D is the number of dimention of an array componnet, Ind_Lengths is a
-- list of lengths for each dimention, both these parameters should come
-- from the caller, they should be extracted from the corresponding array
-- component. The length of Dimension_Indexes returned by De_Linear_Index
-- is D.
--
-- ??? What about checks that indexes and length are in right ranges???
-- ??? Or should it be done in the calling context???
function Max_Len (Component : Array_Component) return Asis.ASIS_Natural;
-- Computes linearized length of array componnet
function Wrong_Indexes
(Component : Array_Component;
Indexes : Dimension_Indexes)
return Boolean;
-- Supposing that Componnet is not-null, this function checks if Indexes
-- are in the expected ranges for this component (this check starts from
-- checking that the dimentions are the same). Returns True if Indexes
-- are NOT the appropriate indexes for the component, because this
-- function is supposed to use as a check to detect an inappropriate
-- argument of a query
function Build_Discrim_List_If_Data_Presented
(Rec : Entity_Id;
Data : Asis.Data_Decomposition.Portable_Data;
Ignore_Discs : Boolean := False)
return Discrim_List;
-- This is a wrapper function for A4G.DDA_Aux.Build_Discrim_List.
-- In case is Data is not Nil_Portable_Data, it behaves as
-- A4G.DDA_Aux.Build_Discrim_List, otherwise if Ignore_Discs is not set
-- ON, it tries to get the discriminant data from the discriminant
-- constraint or default discriminant values, otherwise it returns
-- Null_Discrims,
end Asis.Data_Decomposition.Aux;
|
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
|
|
8a3a2e4d450f4e6c8961518ae01ef32ecc26fd7b
|
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
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
|
d0a93819ac94cf89df060d6a9dbbe7556b17615c
|
hello_world.adb
|
hello_world.adb
|
with Ada.Text_IO;
procedure HelloWorld is
begin
Ada.Text_IO.Put_Line("Hello, world!");
end HelloWorld;
|
Create hello_world.adb
|
Create hello_world.adb
|
Ada
|
mit
|
sanchittechnogeek/hello-world,sanchittechnogeek/hello-world,sanchittechnogeek/hello-world,sanchittechnogeek/hello-world,berviantoleo/hello-world,berviantoleo/hello-world,berviantoleo/hello-world,berviantoleo/hello-world,sanchittechnogeek/hello-world,berviantoleo/hello-world,sanchittechnogeek/hello-world,berviantoleo/hello-world,sanchittechnogeek/hello-world,berviantoleo/hello-world,berviantoleo/hello-world,sanchittechnogeek/hello-world,sanchittechnogeek/hello-world,sanchittechnogeek/hello-world,berviantoleo/hello-world,berviantoleo/hello-world,sanchittechnogeek/hello-world,berviantoleo/hello-world,sanchittechnogeek/hello-world,sanchittechnogeek/hello-world,sanchittechnogeek/hello-world,sanchittechnogeek/hello-world,berviantoleo/hello-world,sanchittechnogeek/hello-world,berviantoleo/hello-world,berviantoleo/hello-world,sanchittechnogeek/hello-world,berviantoleo/hello-world,berviantoleo/hello-world,berviantoleo/hello-world,sanchittechnogeek/hello-world,berviantoleo/hello-world
|
|
b4d8e258cfc8f793649d827c42b1aa12b9c06094
|
src/asis/a4g-defaults.ads
|
src/asis/a4g-defaults.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . D E F A U L T S --
-- --
-- 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). --
-- --
------------------------------------------------------------------------------
-- This package defines the default directory source paths which are the same
-- for any ASIS context.
--
-- In many aspects this package loks like the corresponding part of the
-- GNAT Osint package (see, in particular the code of Osint.Initialize
-- and Osint routines for locating files. But we cannot use Osint directly.
with A4G.A_Types; use A4G.A_Types;
with GNAT.OS_Lib; use GNAT.OS_Lib;
with Table;
package A4G.Defaults is
----------------------------------------------
-- Data Structures for Default Search Paths --
----------------------------------------------
package ASIS_Src_Search_Directories is new Table.Table (
Table_Component_Type => String_Access,
Table_Index_Type => Dir_Id,
Table_Low_Bound => First_Dir_Id,
Table_Initial => 12,
Table_Increment => 100,
Table_Name => "A4G.Defaults.Src_Search_Directories");
-- Table of the names of the directories listed as the value of the
-- ADA_INCLUDE_PATH environment variable
package ASIS_Lib_Search_Directories is new Table.Table (
Table_Component_Type => String_Access,
Table_Index_Type => Dir_Id,
Table_Low_Bound => First_Dir_Id,
Table_Initial => 12,
Table_Increment => 100,
Table_Name => "A4G.Defaults.Lib_Search_Directories");
-- Table of the names of the directories listed as the value of the
-- ADA_OBJECT_PATH environment variable. We are considering object
-- and ALI files coming together, so we call them both as library
-- files.
package ASIS_Tree_Search_Directories is new Table.Table (
Table_Component_Type => String_Access,
Table_Index_Type => Dir_Id,
Table_Low_Bound => First_Dir_Id,
Table_Initial => 12,
Table_Increment => 100,
Table_Name => "A4G.Defaults.Lib_Search_Directories");
-- Table of the names of the directories for dfault trees. Currently
-- contains exactly the same information as the table defined by
-- ASIS_Lib_Search_Directories, because we consider, that
-- the ADA_INCLUDE_PATH environment variable also defines the
-- "default" location for tree files. This may be changed if we decide
-- to use a separate environment variable for trees
procedure Initialize;
-- Initialises the tables containing the default search paths by
-- examining the environment variables. This procedure should
-- be called when ASIS is initialized, and ontly in this situation.
procedure Finalize;
-- reclames all the storage used by strings which store the default
-- source paths.
-- This procedure should be called when ASIS is finalized, and only
-- in this situation.
function Locate_Default_File
(File_Name : String_Access;
Dir_Kind : Search_Dir_Kinds)
return String_Access;
-- Tries to locate the given file in the default directories, following
-- the order in which these directories are listed in the values of
-- the corresponding environment variables. Returns the full file name,
-- if the fle has been located, or returns a null access value otherwise.
procedure Print_Source_Defaults;
procedure Print_Lib_Defaults;
procedure Print_Tree_Defaults;
-- these procedures produce the debug output for the tables storing the
-- default source paths.
end A4G.Defaults;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
1aa454e87a39af72582305c5b9f5d9f50a18bc46
|
src/asis/a4g.ads
|
src/asis/a4g.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . A _ S E M --
-- --
-- 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). --
-- --
------------------------------------------------------------------------------
-- This package is the root of the ASIS-for-GNAT implementation hierarchy.
-- All the implementation components, except Asis.Set_Get and
-- Asis.Text.Set_Get (which need access to the private parts of the
-- corresponding ASIS interface packages), are children or grandchildren of
-- A4G. (A4G stands for Asis For GNAT).
--
-- The primary aim of this package is to constrain the pollution of the user
-- namespace when using the ASIS library to create ASIS applications, by
-- children of A4G.
package A4G is
pragma Pure (A4G);
end A4G;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
e93c1cf9a0516f13a385f89d0e0600a4fc36122c
|
src/util-beans-objects-readers.adb
|
src/util-beans-objects-readers.adb
|
-----------------------------------------------------------------------
-- util-beans-objects-readers -- 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.Serialize.IO;
package body Util.Beans.Objects.Readers is
-- -----------------------
-- 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.
-- -----------------------
overriding
procedure Start_Object (Handler : in out Parser;
Name : in String) is
begin
if Name'Length > 0 then
Ada.Strings.Unbounded.Append (Handler.Base_Name, Name);
Ada.Strings.Unbounded.Append (Handler.Base_Name, Handler.Separator);
Length_Stack.Push (Handler.Lengths);
Length_Stack.Current (Handler.Lengths).all := Name'Length + Handler.Separator_Length;
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.
-- -----------------------
overriding
procedure Finish_Object (Handler : in out Parser;
Name : in String) is
Len : constant Natural := Ada.Strings.Unbounded.Length (Handler.Base_Name);
begin
if Name'Length > 0 then
Ada.Strings.Unbounded.Delete (Handler.Base_Name,
Len - Name'Length - Handler.Separator_Length + 1, Len);
end if;
end Finish_Object;
overriding
procedure Start_Array (Handler : in out Parser;
Name : in String) is
begin
Handler.Start_Object (Name);
-- Util.Serialize.IO.JSON.Parser (Handler).Start_Array (Name);
end Start_Array;
overriding
procedure Finish_Array (Handler : in out Parser;
Name : in String;
Count : in Natural) is
begin
Parser'Class (Handler).Set_Member ("length", Util.Beans.Objects.To_Object (Count));
Handler.Finish_Object (Name);
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.
-- -----------------------
overriding
procedure Set_Member (Handler : in out Reader;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False) is
pragma Unreferenced (Attribute);
begin
Handler.Current.Set_Value (Name, Value);
end Set_Member;
-- 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
null;
end Error;
end Util.Beans.Objects.Readers;
|
Implement operations for the object reader type
|
Implement operations for the object reader type
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
|
fb6ff18299cf4de2e8345d4071f746a7f0d4e86b
|
src/asis/a4g-contt-sd.adb
|
src/asis/a4g-contt-sd.adb
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . C O N T T . S D --
-- --
-- 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 Ada.Exceptions;
with GNAT.Directory_Operations; use GNAT.Directory_Operations;
with Asis.Errors; use Asis.Errors;
with Asis.Exceptions; use Asis.Exceptions;
with A4G.A_Debug; use A4G.A_Debug;
with A4G.GNAT_Int;
with A4G.A_Output; use A4G.A_Output;
with A4G.Contt.TT; use A4G.Contt.TT;
with A4G.Contt.UT; use A4G.Contt.UT;
with A4G.CU_Info2; use A4G.CU_Info2;
with A4G.Defaults; use A4G.Defaults;
with A4G.Vcheck; use A4G.Vcheck;
with Atree;
with Lib;
with Output; use Output;
with Sinfo; use Sinfo;
package body A4G.Contt.SD is
------------------------------------
-- Local Subprograms (new stuff) --
------------------------------------
-- Do we need some of these local subprograms as the interface
-- subprograms of this package?
-- Is this package the right location for these subprograms?
procedure Scan_Search_Path (C : Context_Id);
-- Scans the tree search path and stores the names of the tree file
-- candidates in the context tree table.
procedure Scan_Tree_List (C : Context_Id);
-- This procedure is supposed to be called for One_tree and N_Trees
-- Context processing modes, therefore the Parameters string associated
-- with C should contain at least one tree name. It scans the list of tree
-- file names which have been extracted from the Parameters string when
-- making the association for C. For each tree file name checks if the
-- file exists and stores existing files in the context tree table. In case
-- if this check fails, raises ASIS_Failed if C was defined as "-C1"
-- ("one tree") context, or generates Asis Warning for "-CN" Context.
-- This procedure does not reset a context.
procedure Read_and_Check_New
(C : Context_Id;
Tree : Tree_Id;
Success : out Boolean);
-- Tries to read in Tree and to check if this tree is compile-only.
-- if both of these attempts are successful, sets Success ON and
-- sets Current_Tree as Tree. If either of these actions fails, then
-- depending on the Context operation mode, either raises ASIS_Failed
-- and forms the Diagnosis string on behalf on Asis.Ada_Environments.Open,
-- or only sets Success OFF, in both cases Current_Context and Current_Tree
-- are set to nil values.
procedure Process_Unit_New (U : Unit_Number_Type);
-- Does the general unit processing in one-pass Context opening. If this
-- unit is "new", it creates the new entry in the unit table and checks,
-- if the unit in the tree is consistent with the unit source (if needed).
-- If U corresponds to a "known" unit, it makes the consistency check.
-- If this procedure raises ASIS_Failed, it forms the Diagnosis string
-- on behalf on Asis.Ada_Environments.Open
-- ????????
procedure Investigate_Unit_New
(C : Context_Id;
U : Unit_Id;
U_N : Unit_Number_Type);
-- Computes the basic unit attributes for U_N and stores them for the
-- ASIS unit U in the ASIS Context C.
procedure Store_Tree (Path : String);
-- Stores the full name of the tree file in the Context Tree table for
-- the current Context. It supposes, that when it is called,
-- Namet.Name_Table contains the name of the tree file to be stored,
-- but without any directory information, and Path contains the path to
-- the tree search directory (followed by directory separator) where this
-- file was found.
---------------------------
-- Investigate_Trees_New --
---------------------------
procedure Investigate_Trees_New (C : Context_Id) is
Success : Boolean := False;
-- flag indicating if the next tree file has been successfully read in
Current_Dir : constant Dir_Name_Str := Get_Current_Dir;
begin
-- here we have all the names of tree files stored in the tree table
-- for C
for T in First_Tree_Id .. Last_Tree (C) loop
Read_and_Check_New (C, T, Success);
if Success then
Get_Name_String (C, T);
Change_Dir (Dir_Name (A_Name_Buffer (1 .. A_Name_Len)));
Register_Units;
Scan_Units_New;
Change_Dir (Current_Dir);
end if;
end loop;
end Investigate_Trees_New;
--------------------------
-- Investigate_Unit_New --
--------------------------
procedure Investigate_Unit_New
(C : Context_Id;
U : Unit_Id;
U_N : Unit_Number_Type)
is
Top : constant Node_Id := Lib.Cunit (U_N);
-- pointer to the N_Compilation_Unit node for U in the currently
-- accessed tree
begin
Set_S_F_Name_and_Origin (C, U, Top);
Check_Source_Consistency (C, U);
Set_Kind_and_Class (C, U, Top);
Get_Ada_Name (Top);
Set_Ada_Name (U);
Set_Is_Main_Unit (C, U, Is_Main (Top, Kind (C, U)));
Set_Is_Body_Required (C, U, Sinfo.Body_Required (Top));
Set_Dependencies (C, U, Top);
end Investigate_Unit_New;
----------------------
-- Process_Unit_New --
----------------------
procedure Process_Unit_New (U : Unit_Number_Type) is
Cont : constant Context_Id := Get_Current_Cont;
Include_Unit : Boolean := False;
Current_Unit : Unit_Id;
begin
Namet.Get_Decoded_Name_String (Lib.Unit_Name (U));
Set_Norm_Ada_Name_String_With_Check (U, Include_Unit);
if not Include_Unit then
return;
end if;
Current_Unit := Name_Find (Cont);
-- all the units in the current tree are already registered, therefore
-- Current_Unit should not be Nil_Unit
if Already_Processed (Cont, Current_Unit) then
Check_Consistency (Cont, Current_Unit, U);
-- Append_Tree_To_Unit (Cont, Current_Unit);
else
Investigate_Unit_New (Cont, Current_Unit, U);
end if;
end Process_Unit_New;
------------------------
-- Read_and_Check_New --
------------------------
procedure Read_and_Check_New
(C : Context_Id;
Tree : Tree_Id;
Success : out Boolean)
is
Tree_File_D : File_Descriptor;
begin
-- Special processing for GNSA mode:
if Tree_Processing_Mode (C) = GNSA then
if Context_Processing_Mode (C) = One_Tree then
Set_Current_Cont (C);
Set_Current_Tree (Tree);
Success := True;
return;
else
-- Other possibilites are not implemented now, so
pragma Assert (False);
null;
end if;
end if;
Get_Name_String (C, Tree);
A_Name_Buffer (A_Name_Len + 1) := ASCII.NUL;
Tree_File_D := Open_Read (A_Name_Buffer'Address, Binary);
A4G.GNAT_Int.Tree_In_With_Version_Check (Tree_File_D, C, Success);
Set_Current_Cont (C);
Set_Current_Tree (Tree);
exception
when Program_Error |
ASIS_Failed =>
Set_Current_Cont (Nil_Context_Id);
Set_Current_Tree (Nil_Tree);
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 ("The tree file ");
Write_Str (A_Name_Buffer (1 .. A_Name_Len));
Write_Str (" was not read in and checked successfully");
Write_Eol;
Write_Str (Ada.Exceptions.Exception_Name (Ex));
Write_Str (" was raised");
Write_Eol;
Write_Str ("Exception message: ");
Write_Str (Ada.Exceptions.Exception_Message (Ex));
Write_Eol;
end if;
Report_ASIS_Bug
(Query_Name => "A4G.Contt.SD.Read_and_Check_New" &
" (tree file " &
A_Name_Buffer (1 .. A_Name_Len) & ")",
Ex => Ex);
end Read_and_Check_New;
--------------------
-- Scan_Tree_List --
--------------------
procedure Scan_Tree_List (C : Context_Id) is
Cont_Mode : constant Context_Mode := Context_Processing_Mode (C);
Tree_List : Tree_File_List_Ptr renames
Contexts.Table (C).Context_Tree_Files;
GNSA_Tree_Name : constant String := "GNSA-created tree";
-- Can be used for -C1 COntext only.
-- Success : Boolean;
begin
-- Special processing for GNSA mode:
if Tree_Processing_Mode (C) = GNSA then
if Context_Processing_Mode (C) = One_Tree then
Name_Len := GNSA_Tree_Name'Length;
Name_Buffer (1 .. Name_Len) := GNSA_Tree_Name;
Store_Tree ("");
return;
else
-- Other possibilites are not implemented now, so
pragma Assert (False);
null;
end if;
end if;
for I in Tree_List'Range loop
exit when Tree_List (I) = null;
if not Is_Regular_File (Tree_List (I).all) then
-- -- A loop needed to deal with possible raise conditions
-- Success := False;
-- for J in 1 .. 100 loop
-- if Is_Regular_File (Tree_List (I).all) then
-- Success := True;
-- exit;
-- end if;
-- delay 0.05;
-- end loop;
-- if not Success then
if Cont_Mode = One_Tree then
Set_Error_Status
(Status => Asis.Errors.Use_Error,
Diagnosis => "Asis.Ada_Environments.Open:"
& ASIS_Line_Terminator
& "tree file "
& Tree_List (I).all
& " does not exist");
raise ASIS_Failed;
elsif Cont_Mode = N_Trees then
ASIS_Warning
(Message => "Asis.Ada_Environments.Open: "
& ASIS_Line_Terminator
& "tree file "
& Tree_List (I).all
& " does not exist",
Error => Use_Error);
end if;
-- end if;
else
Name_Len := Tree_List (I)'Length;
Name_Buffer (1 .. Name_Len) := Tree_List (I).all;
Store_Tree ("");
end if;
end loop;
end Scan_Tree_List;
----------------------
-- Scan_Search_Path --
----------------------
procedure Scan_Search_Path (C : Context_Id) is
Curr_Dir : GNAT.Directory_Operations.Dir_Type;
Search_Path : constant Directory_List_Ptr :=
Contexts.Table (C).Tree_Path;
procedure Scan_Dir (Path : String);
-- scans tree files in Curr_Dir. Puts in the Name Table all
-- the files having names of the form *.at?, which have not been
-- scanned before. Sets the global variable Last_Tree_File equal to
-- the Name_Id of the last scanned tree file. The names of the tree
-- files stores in the Name Table are also stored in the ASIS tree
-- table with the directory information passed as the actual for Path
-- parameter
procedure Read_Tree_File
(Dir : in out GNAT.Directory_Operations.Dir_Type;
Str : out String;
Last : out Natural);
-- This procedure is the modification of GNAT.Directory_Operations.Read
-- which reads only tree file entries from the directory. A Tree file
-- is any file having the extension '.[aA][dD][tT]' (We are
-- considering upper case letters because of "semi-case-sensitiveness"
-- of Windows 95/98/NT.)
procedure Read_Tree_File
(Dir : in out GNAT.Directory_Operations.Dir_Type;
Str : out String;
Last : out Natural)
is
function Is_Tree_File return Boolean;
-- Checks if the file name stored in Str is the name of some tree
-- file. This function assumes that Str'First is 1, and that
-- Last > 0
function Is_Tree_File return Boolean is
Result : Boolean := False;
begin
if Last >= 5 and then
Str (Last - 3) = '.' and then
(Str (Last) = 't' or else
Str (Last) = 'T') and then
(Str (Last - 1) = 'd' or else
Str (Last - 1) = 'D') and then
(Str (Last - 2) = 'a' or else
Str (Last - 2) = 'A')
then
Result := True;
end if;
return Result;
end Is_Tree_File;
begin
GNAT.Directory_Operations.Read (Dir, Str, Last);
while Last > 0 loop
exit when Is_Tree_File;
GNAT.Directory_Operations.Read (Dir, Str, Last);
end loop;
end Read_Tree_File;
procedure Scan_Dir (Path : String) is
T_File : Name_Id;
Is_First_Tree : Boolean := True;
begin
-- looking for the first tree file in this directory
Read_Tree_File
(Dir => Curr_Dir,
Str => Namet.Name_Buffer,
Last => Namet.Name_Len);
while Namet.Name_Len > 0 loop
T_File := Name_Find;
if Is_First_Tree then
Is_First_Tree := False;
First_Tree_File := T_File;
end if;
if T_File > Last_Tree_File then
Last_Tree_File := T_File;
Store_Tree (Path);
end if;
Read_Tree_File
(Dir => Curr_Dir,
Str => Namet.Name_Buffer,
Last => Namet.Name_Len);
end loop;
end Scan_Dir;
begin -- Scan_Search_Path
if Search_Path = null then
GNAT.Directory_Operations.Open (Curr_Dir, "." & Directory_Separator);
Scan_Dir ("");
GNAT.Directory_Operations.Close (Curr_Dir);
else
for I in 1 .. Search_Path'Last loop
GNAT.Directory_Operations.Open (Curr_Dir, Search_Path (I).all);
Scan_Dir (Search_Path (I).all);
GNAT.Directory_Operations.Close (Curr_Dir);
end loop;
end if;
if Use_Default_Trees (C) then
for J in First_Dir_Id .. ASIS_Tree_Search_Directories.Last loop
GNAT.Directory_Operations.Open
(Curr_Dir,
ASIS_Tree_Search_Directories.Table (J).all);
Scan_Dir (ASIS_Tree_Search_Directories.Table (J).all);
GNAT.Directory_Operations.Close (Curr_Dir);
end loop;
end if;
end Scan_Search_Path;
-------------------------
-- Scan_Tree_Files_New --
-------------------------
procedure Scan_Tree_Files_New (C : Context_Id) is
C_Mode : constant Context_Mode := Context_Processing_Mode (C);
GNSA_Tree_Name : constant String := "GNSA-created tree";
-- Can be used for -C1 Context only
begin
-- Special processing for GNSA mode:
if Tree_Processing_Mode (C) = GNSA then
if Context_Processing_Mode (C) = One_Tree then
Name_Len := GNSA_Tree_Name'Length;
Name_Buffer (1 .. Name_Len) := GNSA_Tree_Name;
Store_Tree ("");
return;
-- to avoid GNAT Name Table corruption
else
-- Other possibilites are not implemented now, so
pragma Assert (False);
null;
end if;
end if;
-- first, initialization which is (may be?) common for all context
-- modes:
First_Tree_File := First_Name_Id;
Last_Tree_File := First_Name_Id - 1;
Namet.Initialize;
-- now for different context modes we call individual scan procedures.
-- all of them first put names of tree files into the GNAT Name table
-- and then transfer them into Context tree table, but we cannot
-- factor this out because of the differences in processing a search
-- path (if any) and forming the full names of the tree files
case C_Mode is
when All_Trees =>
Scan_Search_Path (C);
when One_Tree | N_Trees =>
Scan_Tree_List (C);
-- all the tree file names have already been stored in the
-- context tree table when association parameters were processed
null;
when Partition =>
Not_Implemented_Yet ("Scan_Tree_Files_New (Partition)");
end case;
-- debug output:...
if Debug_Flag_O or else
Debug_Lib_Model or else
Debug_Mode
then
Write_Str ("Scanning tree files for Context ");
Write_Int (Int (C));
Write_Eol;
if Context_Processing_Mode (C) = All_Trees then
if Last_Tree_File < First_Tree_File then
Write_Str (" no tree file has been found");
Write_Eol;
else
Write_Str (" the content of the Name Table is:");
Write_Eol;
for I in First_Tree_File .. Last_Tree_File loop
Get_Name_String (I);
Write_Str (" ");
Write_Str (Name_Buffer (1 .. Name_Len));
Write_Eol;
end loop;
end if;
else
Write_Str ("Trees already stored in the tree table:");
Write_Eol;
for Tr in First_Tree_Id .. Last_Tree (C) loop
Get_Name_String (C, Tr);
Write_Str (" " & A_Name_Buffer (1 .. A_Name_Len));
Write_Eol;
end loop;
end if;
end if;
end Scan_Tree_Files_New;
--------------------
-- Scan_Units_New --
--------------------
procedure Scan_Units_New is
Main_Unit_Id : Unit_Id;
Next_Unit_Id : Unit_Id;
Include_Unit : Boolean := False;
begin
for N_Unit in Main_Unit .. Lib.Last_Unit loop
if Atree.Present (Lib.Cunit (N_Unit)) then
Process_Unit_New (N_Unit);
end if;
end loop;
-- And here we collect compilation dependencies for the main unit in
-- the tree:
Namet.Get_Decoded_Name_String (Lib.Unit_Name (Main_Unit));
Set_Norm_Ada_Name_String_With_Check (Main_Unit, Include_Unit);
if not Include_Unit then
return;
end if;
Main_Unit_Id := Name_Find (Current_Context);
for N_Unit in Main_Unit .. Lib.Last_Unit loop
if Atree.Present (Lib.Cunit (N_Unit)) then
Namet.Get_Decoded_Name_String (Lib.Unit_Name (N_Unit));
Set_Norm_Ada_Name_String_With_Check (N_Unit, Include_Unit);
if Include_Unit then
Next_Unit_Id := Name_Find (Current_Context);
Add_To_Elmt_List
(Unit => Next_Unit_Id,
List =>
Unit_Table.Table (Main_Unit_Id).Compilation_Dependencies);
end if;
end if;
end loop;
Unit_Table.Table (Main_Unit_Id).Main_Tree := Current_Tree;
Set_Main_Unit_Id (Main_Unit_Id);
end Scan_Units_New;
----------------
-- Store_Tree --
----------------
procedure Store_Tree (Path : String) is
New_Tree : Tree_Id;
-- we do not need it, but Allocate_Tree_Entry is a function...
pragma Warnings (Off, New_Tree);
begin
if Path = "" then
Set_Name_String (Normalize_Pathname (Name_Buffer (1 .. Name_Len)));
else
Set_Name_String
(Normalize_Pathname
(Path & Directory_Separator & Name_Buffer (1 .. Name_Len)));
end if;
New_Tree := Allocate_Tree_Entry;
end Store_Tree;
end A4G.Contt.SD;
|
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
|
|
6bfbfef68526507e1f89e25e5e55a516d8c77d54
|
src/gnat/lib-sort.adb
|
src/gnat/lib-sort.adb
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- L I B . S O R 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. --
-- --
------------------------------------------------------------------------------
with GNAT.Heap_Sort_G;
separate (Lib)
procedure Sort (Tbl : in out Unit_Ref_Table) is
T : array (0 .. Integer (Tbl'Last - Tbl'First + 1)) of Unit_Number_Type;
-- Actual sort is done on this copy of the array with 0's origin
-- subscripts. Location 0 is used as a temporary by the sorting algorithm.
-- Also the addressing of the table is more efficient with 0's origin,
-- even though we have to copy Tbl back and forth.
function Lt_Uname (C1, C2 : Natural) return Boolean;
-- Comparison routine for comparing Unames. Needed by the sorting routine
procedure Move_Uname (From : Natural; To : Natural);
-- Move routine needed by the sorting routine below
package Sorting is new GNAT.Heap_Sort_G (Move_Uname, Lt_Uname);
--------------
-- Lt_Uname --
--------------
function Lt_Uname (C1, C2 : Natural) return Boolean is
begin
-- Preprocessing data and definition files are not sorted, they are
-- at the bottom of the list. They are recognized because they are
-- the only ones without a Unit_Name.
if Units.Table (T (C1)).Unit_Name = No_Unit_Name then
return False;
elsif Units.Table (T (C2)).Unit_Name = No_Unit_Name then
return True;
else
return
Uname_Lt
(Units.Table (T (C1)).Unit_Name, Units.Table (T (C2)).Unit_Name);
end if;
end Lt_Uname;
----------------
-- Move_Uname --
----------------
procedure Move_Uname (From : Natural; To : Natural) is
begin
T (To) := T (From);
end Move_Uname;
-- Start of processing for Sort
begin
if T'Last > 0 then
for I in 1 .. T'Last loop
T (I) := Tbl (Int (I) - 1 + Tbl'First);
end loop;
Sorting.Sort (T'Last);
-- Sort is complete, copy result back into place
for I in 1 .. T'Last loop
Tbl (Int (I) - 1 + Tbl'First) := T (I);
end loop;
end if;
end Sort;
|
Add GNAT file for ASIS
|
Add GNAT file for ASIS
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
ce89b61f503806b4ea588d29d54ddfb87a74b752
|
src/ado-caches.adb
|
src/ado-caches.adb
|
-----------------------------------------------------------------------
-- ado-cache -- Simple cache 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 ADO.Caches is
-- --------------------
-- Expand the name from the given group into a target parameter value to be used in
-- the SQL query. The expander can look in a cache or in some configuration to find
-- the value associated with the name and return it. The Expander can return a
-- T_NULL when a value is not found or it may also raise some exception.
-- --------------------
overriding
function Expand (Instance : in Cache_Manager;
Group : in String;
Name : in String) return ADO.Parameters.Parameter is
use type Ada.Strings.Unbounded.Unbounded_String;
C : Cache_Type_Access := Instance.First;
begin
while C /= null loop
if C.Name = Group then
return C.Expand (Name);
end if;
C := C.Next;
end loop;
raise No_Value;
end Expand;
-- --------------------
-- Insert a new cache in the manager. The cache is identified by the given name.
-- --------------------
procedure Add_Cache (Manager : in out Cache_Manager;
Name : in String;
Cache : in Cache_Type_Access) is
begin
Cache.Next := Manager.First;
Cache.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name);
Manager.First := Cache;
end Add_Cache;
-- --------------------
-- Finalize the cache manager releasing every cache group.
-- --------------------
overriding
procedure Finalize (Manager : in out Cache_Manager) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Cache_Type'Class,
Name => Cache_Type_Access);
Cache : Cache_Type_Access;
begin
loop
Cache := Manager.First;
exit when Cache = null;
Manager.First := Cache.Next;
Free (Cache);
end loop;
end Finalize;
end ADO.Caches;
|
Implement the cache manager operation
|
Implement the cache manager operation
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
|
342f736daf481f0e1212d864d48af3bc61e99d12
|
regtests/asf-filters-tests.adb
|
regtests/asf-filters-tests.adb
|
-----------------------------------------------------------------------
-- Filters Tests - Unit tests for ASF.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.
-----------------------------------------------------------------------
package body ASF.Filters.Tests is
-- ------------------------------
-- Increment the counter each time Do_Filter is called.
-- ------------------------------
procedure Do_Filter (F : in Test_Filter;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain) is
begin
F.Count.all := F.Count.all + 1;
ASF.Servlets.Do_Filter (Chain => Chain, Request => Request, Response => Response);
end Do_Filter;
-- ------------------------------
-- Initialize the test filter.
-- ------------------------------
overriding
procedure Initialize (Server : in out Test_Filter;
Context : in ASF.Servlets.Servlet_Registry'Class) is
pragma Unreferenced (Context);
begin
Server.Count := Server.Counter'Unchecked_Access;
end Initialize;
end ASF.Filters.Tests;
|
Implement a test filter that counts the number of times it is traversed
|
Implement a test filter that counts the number of times it is traversed
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
|
66bcf2dee79da01d8ccf835f7f0f8a1f746b136e
|
src/asf-security-filters-oauth.ads
|
src/asf-security-filters-oauth.ads
|
-----------------------------------------------------------------------
-- security-filters-oauth -- OAuth Security filter
-- 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.Unbounded;
with ASF.Filters;
with ASF.Requests;
with ASF.Responses;
with ASF.Servlets;
with Security.OAuth.Servers; use Security.OAuth;
with Security.Policies; use Security;
-- The <b>ASF.Security.Filters.OAuth</b> package provides a servlet filter that
-- implements the RFC 6749 "Accessing Protected Resources" part: it extracts the OAuth
-- access token, verifies the grant and the permission. The servlet filter implements
-- the RFC 6750 "OAuth 2.0 Bearer Token Usage".
--
package ASF.Security.Filters.OAuth is
-- RFC 2617 HTTP header for authorization.
AUTHORIZATION_HEADER_NAME : constant String := "Authorization";
-- RFC 2617 HTTP header for failed authorization.
WWW_AUTHENTICATE_HEADER_NAME : constant String := "WWW-Authenticate";
type Auth_Filter is new ASF.Filters.Filter with private;
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
overriding
procedure Initialize (Server : in out Auth_Filter;
Config : in ASF.Servlets.Filter_Config);
-- Set the permission manager that must be used to verify the permission.
procedure Set_Permission_Manager (Filter : in out Auth_Filter;
Manager : in Policies.Policy_Manager_Access);
-- Filter the request to make sure the user is authenticated.
-- Invokes the <b>Do_Login</b> procedure if there is no user.
-- If a permission manager is defined, check that the user has the permission
-- to view the page. Invokes the <b>Do_Deny</b> procedure if the permission
-- is denied.
procedure Do_Filter (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain);
-- Display or redirects the user to the login page. This procedure is called when
-- the user is not authenticated.
procedure Do_Login (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class);
-- Display the forbidden access page. This procedure is called when the user is not
-- authorized to see the page. The default implementation returns the SC_FORBIDDEN error.
procedure Do_Deny (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class);
private
type Auth_Filter is new ASF.Filters.Filter with record
Manager : Policies.Policy_Manager_Access;
Realm : Servers.Auth_Manager_Access;
Realm_URL : Ada.Strings.Unbounded.Unbounded_String;
end record;
end ASF.Security.Filters.OAuth;
|
Declare the OAuth child package with the Auth_Filter for the definition and representation of the OAuth server side filter to verify the access token when an API call is made
|
Declare the OAuth child package with the Auth_Filter for the definition and representation
of the OAuth server side filter to verify the access token when an API call is made
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
|
2e4601ae35d8979b4c5686d34888084ec83d6d90
|
src/util-measures.adb
|
src/util-measures.adb
|
-----------------------------------------------------------------------
-- measure -- Benchmark tools
-- Copyright (C) 2008, 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 Ada.Task_Attributes;
with Ada.Strings.Hash;
with Ada.Unchecked_Deallocation;
with GNAT.Calendar.Time_IO;
with Util.Streams.Buffered;
package body Util.Measures is
ISO_DATE_TIME : constant GNAT.Calendar.Time_IO.Picture_String := "%Y-%m-%d %H:%M:%S";
procedure Free is
new Ada.Unchecked_Deallocation (Buckets_Type, Buckets_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Measure, Measure_Access);
procedure Free is
new Ada.Unchecked_Deallocation (String, String_Access);
package Task_Context is new Ada.Task_Attributes
(Measure_Set_Access, null);
function Format (D : in Duration) return String;
-- Format the duration in a time in 'ns', 'us', 'ms' or seconds.
function Format (D : in Duration;
Unit : in Unit_Type) return String;
-- ------------------------------
-- Disable collecting measures on the measure set.
-- ------------------------------
procedure Disable (Measures : in out Measure_Set) is
begin
Measures.Enabled := False;
end Disable;
-- ------------------------------
-- Enable collecting measures on the measure set.
-- ------------------------------
procedure Enable (Measures : in out Measure_Set) is
begin
Measures.Enabled := True;
end Enable;
-- ------------------------------
-- Set the per-thread measure set.
-- ------------------------------
procedure Set_Current (Measures : in Measure_Set_Access) is
begin
Task_Context.Set_Value (Measures);
end Set_Current;
-- ------------------------------
-- Get the per-thread measure set.
-- ------------------------------
function Get_Current return Measure_Set_Access is
begin
return Task_Context.Value;
end Get_Current;
-- ------------------------------
-- Dump an XML result with the measures collected by the measure set.
-- When writing the measures, the measure set is cleared. It is safe
-- to write measures while other measures are being collected.
-- ------------------------------
procedure Write (Measures : in out Measure_Set;
Title : in String;
Stream : in out Util.Streams.Texts.Print_Stream'Class) is
use Util.Streams.Buffered;
procedure Dump_XML (Item : in Measure_Access);
procedure Dump_XML (Item : in Measure_Access) is
Time : constant String := Format (Item.Time);
begin
Stream.Write ("<time count=""");
Stream.Write (Item.Count);
Stream.Write (""" time=""");
Stream.Write (Time (Time'First + 1 .. Time'Last));
Stream.Write (""" title=""");
Util.Streams.Texts.TR.Escape_Java_Script (Into => Buffered_Stream (Stream),
Content => Item.Name.all);
Stream.Write ("""/>");
Stream.Write (ASCII.LF);
end Dump_XML;
Buckets : Buckets_Access;
TS, TE : Ada.Calendar.Time;
begin
Measures.Data.Steal_Map (Buckets, TS, TE);
Stream.Write ("<measures title=""");
Util.Streams.Texts.TR.Escape_Java_Script (Into => Buffered_Stream (Stream),
Content => Title);
Stream.Write (""" start=""");
Stream.Write (TS, ISO_DATE_TIME);
Stream.Write (""" end=""");
Stream.Write (TE, ISO_DATE_TIME);
Stream.Write (""">");
if Buckets /= null then
begin
for I in Buckets'Range loop
declare
Next : Measure_Access;
Node : Measure_Access := Buckets (I);
begin
while Node /= null loop
Dump_XML (Node);
Free (Node.Name);
Next := Node.Next;
Free (Node);
Node := Next;
end loop;
end;
end loop;
exception
when others =>
Free (Buckets);
raise;
end;
Free (Buckets);
end if;
Stream.Write ("</measures>");
end Write;
-- ------------------------------
-- Dump an XML result with the measures collected by the measure set.
-- ------------------------------
procedure Write (Measures : in out Measure_Set;
Title : in String;
Stream : in Ada.Text_IO.File_Type) is
Buffer : aliased Util.Streams.Buffered.Buffered_Stream;
Output : Util.Streams.Texts.Print_Stream;
begin
Buffer.Initialize (Size => 128 * 1024);
Output.Initialize (To => Buffer'Unchecked_Access);
Write (Measures, Title, Output);
Output.Flush;
Ada.Text_IO.Put_Line (Stream, Util.Streams.Texts.To_String (Buffer));
end Write;
-- ------------------------------
-- Dump an XML result with the measures in a file.
-- ------------------------------
procedure Write (Measures : in out Measure_Set;
Title : in String;
Path : in String) is
File : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Create (File => File, Name => Path);
Write (Measures, Title, File);
Ada.Text_IO.Close (File);
exception
when others =>
if Ada.Text_IO.Is_Open (File) then
Ada.Text_IO.Close (File);
end if;
raise;
end Write;
-- ------------------------------
-- Report the time spent between the stamp creation and this method call.
-- Collect the result in the per-thread measure set under the given measure
-- title.
-- ------------------------------
procedure Report (S : in out Stamp;
Title : in String;
Count : in Positive := 1) is
Measures : constant Measure_Set_Access := Task_Context.Value;
begin
if Measures /= null and then Measures.Enabled then
Report (Measures.all, S, Title, Count);
end if;
end Report;
-- ------------------------------
-- Report the time spent between the stamp creation and this method call.
-- Collect the result in the measure set under the given measure title.
-- ------------------------------
procedure Report (Measures : in out Measure_Set;
S : in out Stamp;
Title : in String;
Count : in Positive := 1) is
use Ada.Calendar;
begin
if Measures.Enabled then
declare
D : constant Duration := Ada.Calendar.Clock - S.Start;
begin
Measures.Data.Add (Title, D, Count);
end;
S.Start := Ada.Calendar.Clock;
end if;
end Report;
-- ------------------------------
-- Report the time spent between the stamp creation and this method call.
-- The report is written in the file with the given title. The duration is
-- expressed in the unit defined in <tt>Unit</tt>.
-- ------------------------------
procedure Report (S : in out Stamp;
File : in out Ada.Text_IO.File_Type;
Title : in String;
Unit : in Unit_Type := Microseconds) is
use Ada.Calendar;
D : constant Duration := Ada.Calendar.Clock - S.Start;
begin
Ada.Text_IO.Put (File, Title);
Ada.Text_IO.Put (File, Format (D, Unit));
S.Start := Ada.Calendar.Clock;
end Report;
protected body Measure_Data is
-- ------------------------------
-- Get the measures and clear to start a new set of measures.
-- Return in <b>Time_Start</b> and <b>Time_End</b> the period of time.
-- ------------------------------
procedure Steal_Map (Result : out Buckets_Access;
Time_Start : out Ada.Calendar.Time;
Time_End : out Ada.Calendar.Time) is
begin
Result := Buckets;
Time_Start := Start;
Start := Ada.Calendar.Clock;
Time_End := Start;
Buckets := null;
end Steal_Map;
-- ------------------------------
-- Add the measure
-- ------------------------------
procedure Add (Title : in String;
D : in Duration;
Count : in Positive := 1) is
use Ada.Containers;
use Ada.Calendar;
Pos : Hash_Type;
Node : Measure_Access;
begin
if Buckets = null then
Buckets := new Buckets_Type (0 .. 256);
end if;
Pos := Ada.Strings.Hash (Title) mod Buckets'Length;
Node := Buckets (Pos);
while Node /= null loop
if Node.Name'Length = Title'Length
and then Node.Name.all = Title then
Node.Count := Node.Count + Count;
Node.Time := Node.Time + D;
return;
end if;
Node := Node.Next;
end loop;
Buckets (Pos) := new Measure '(Name => new String '(Title),
Time => D,
Count => Count,
Next => Buckets (Pos));
end Add;
end Measure_Data;
-- ------------------------------
-- Format the duration in a time in 'ns', 'us', 'ms' or seconds.
-- ------------------------------
function Format (D : Duration) return String is
begin
if D < 0.000_001 then
return Duration'Image (D * 1_000_000_000) & "ns";
elsif D < 0.001 then
return Duration'Image (D * 1_000_000) & "us";
elsif D < 1.0 then
return Duration'Image (D * 1_000) & "ms";
else
return Duration'Image (D) & "s";
end if;
end Format;
-- ------------------------------
-- Format the duration in a time in 'ns', 'us', 'ms' or seconds.
-- ------------------------------
function Format (D : in Duration;
Unit : in Unit_Type) return String is
begin
case Unit is
when Seconds =>
return Duration'Image (D);
when Milliseconds =>
return Duration'Image (D * 1_000);
when Microseconds =>
return Duration'Image (D * 1_000_000);
when Nanoseconds =>
return Duration'Image (D * 1_000_000_000);
end case;
end Format;
-- ------------------------------
-- Finalize the measures and release the storage.
-- ------------------------------
overriding
procedure Finalize (Measures : in out Measure_Set) is
Buckets : Buckets_Access;
TS, TE : Ada.Calendar.Time;
begin
-- When deleting the measure set, we have to release the buckets and measures
-- that were allocated. We could call <b>Write</b> but we don't know where
-- the measures have to be written.
Measures.Data.Steal_Map (Buckets, TS, TE);
if Buckets /= null then
for I in Buckets'Range loop
declare
Next : Measure_Access;
Node : Measure_Access := Buckets (I);
begin
while Node /= null loop
Free (Node.Name);
Next := Node.Next;
Free (Node);
Node := Next;
end loop;
end;
end loop;
Free (Buckets);
end if;
end Finalize;
end Util.Measures;
|
-----------------------------------------------------------------------
-- measure -- Benchmark tools
-- Copyright (C) 2008, 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 Ada.Task_Attributes;
with Ada.Strings.Hash;
with Ada.Unchecked_Deallocation;
with GNAT.Calendar.Time_IO;
with Util.Streams.Buffered;
package body Util.Measures is
ISO_DATE_TIME : constant GNAT.Calendar.Time_IO.Picture_String := "%Y-%m-%d %H:%M:%S";
procedure Free is
new Ada.Unchecked_Deallocation (Buckets_Type, Buckets_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Measure, Measure_Access);
procedure Free is
new Ada.Unchecked_Deallocation (String, String_Access);
package Task_Context is new Ada.Task_Attributes
(Measure_Set_Access, null);
function Format (D : in Duration) return String;
-- Format the duration in a time in 'ns', 'us', 'ms' or seconds.
function Format (D : in Duration;
Unit : in Unit_Type) return String;
-- ------------------------------
-- Disable collecting measures on the measure set.
-- ------------------------------
procedure Disable (Measures : in out Measure_Set) is
begin
Measures.Enabled := False;
end Disable;
-- ------------------------------
-- Enable collecting measures on the measure set.
-- ------------------------------
procedure Enable (Measures : in out Measure_Set) is
begin
Measures.Enabled := True;
end Enable;
-- ------------------------------
-- Set the per-thread measure set.
-- ------------------------------
procedure Set_Current (Measures : in Measure_Set_Access) is
begin
Task_Context.Set_Value (Measures);
end Set_Current;
-- ------------------------------
-- Get the per-thread measure set.
-- ------------------------------
function Get_Current return Measure_Set_Access is
begin
return Task_Context.Value;
end Get_Current;
-- ------------------------------
-- Dump an XML result with the measures collected by the measure set.
-- When writing the measures, the measure set is cleared. It is safe
-- to write measures while other measures are being collected.
-- ------------------------------
procedure Write (Measures : in out Measure_Set;
Title : in String;
Stream : in out Util.Streams.Texts.Print_Stream'Class) is
use Util.Streams.Buffered;
procedure Dump_XML (Item : in Measure_Access);
procedure Dump_XML (Item : in Measure_Access) is
Total : constant String := Format (Item.Time);
Time : constant String := Format (Item.Time / Item.Count);
begin
Stream.Write ("<time count=""");
Stream.Write (Item.Count);
Stream.Write (""" time=""");
Stream.Write (Time (Time'First + 1 .. Time'Last));
if Item.Count > 1 then
Stream.Write (""" total=""");
Stream.Write (Total (Total'First + 1 .. Total'Last));
end if;
Stream.Write (""" title=""");
Util.Streams.Texts.TR.Escape_Java_Script (Into => Buffered_Stream (Stream),
Content => Item.Name.all);
Stream.Write ("""/>");
Stream.Write (ASCII.LF);
end Dump_XML;
Buckets : Buckets_Access;
TS, TE : Ada.Calendar.Time;
begin
Measures.Data.Steal_Map (Buckets, TS, TE);
Stream.Write ("<measures title=""");
Util.Streams.Texts.TR.Escape_Java_Script (Into => Buffered_Stream (Stream),
Content => Title);
Stream.Write (""" start=""");
Stream.Write (TS, ISO_DATE_TIME);
Stream.Write (""" end=""");
Stream.Write (TE, ISO_DATE_TIME);
Stream.Write (""">");
if Buckets /= null then
begin
for I in Buckets'Range loop
declare
Next : Measure_Access;
Node : Measure_Access := Buckets (I);
begin
while Node /= null loop
Dump_XML (Node);
Free (Node.Name);
Next := Node.Next;
Free (Node);
Node := Next;
end loop;
end;
end loop;
exception
when others =>
Free (Buckets);
raise;
end;
Free (Buckets);
end if;
Stream.Write ("</measures>");
end Write;
-- ------------------------------
-- Dump an XML result with the measures collected by the measure set.
-- ------------------------------
procedure Write (Measures : in out Measure_Set;
Title : in String;
Stream : in Ada.Text_IO.File_Type) is
Buffer : aliased Util.Streams.Buffered.Buffered_Stream;
Output : Util.Streams.Texts.Print_Stream;
begin
Buffer.Initialize (Size => 128 * 1024);
Output.Initialize (To => Buffer'Unchecked_Access);
Write (Measures, Title, Output);
Output.Flush;
Ada.Text_IO.Put_Line (Stream, Util.Streams.Texts.To_String (Buffer));
end Write;
-- ------------------------------
-- Dump an XML result with the measures in a file.
-- ------------------------------
procedure Write (Measures : in out Measure_Set;
Title : in String;
Path : in String) is
File : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Create (File => File, Name => Path);
Write (Measures, Title, File);
Ada.Text_IO.Close (File);
exception
when others =>
if Ada.Text_IO.Is_Open (File) then
Ada.Text_IO.Close (File);
end if;
raise;
end Write;
-- ------------------------------
-- Report the time spent between the stamp creation and this method call.
-- Collect the result in the per-thread measure set under the given measure
-- title.
-- ------------------------------
procedure Report (S : in out Stamp;
Title : in String;
Count : in Positive := 1) is
Measures : constant Measure_Set_Access := Task_Context.Value;
begin
if Measures /= null and then Measures.Enabled then
Report (Measures.all, S, Title, Count);
end if;
end Report;
-- ------------------------------
-- Report the time spent between the stamp creation and this method call.
-- Collect the result in the measure set under the given measure title.
-- ------------------------------
procedure Report (Measures : in out Measure_Set;
S : in out Stamp;
Title : in String;
Count : in Positive := 1) is
use Ada.Calendar;
begin
if Measures.Enabled then
declare
D : constant Duration := Ada.Calendar.Clock - S.Start;
begin
Measures.Data.Add (Title, D, Count);
end;
S.Start := Ada.Calendar.Clock;
end if;
end Report;
-- ------------------------------
-- Report the time spent between the stamp creation and this method call.
-- The report is written in the file with the given title. The duration is
-- expressed in the unit defined in <tt>Unit</tt>.
-- ------------------------------
procedure Report (S : in out Stamp;
File : in out Ada.Text_IO.File_Type;
Title : in String;
Unit : in Unit_Type := Microseconds) is
use Ada.Calendar;
D : constant Duration := Ada.Calendar.Clock - S.Start;
begin
Ada.Text_IO.Put (File, Title);
Ada.Text_IO.Put (File, Format (D, Unit));
S.Start := Ada.Calendar.Clock;
end Report;
protected body Measure_Data is
-- ------------------------------
-- Get the measures and clear to start a new set of measures.
-- Return in <b>Time_Start</b> and <b>Time_End</b> the period of time.
-- ------------------------------
procedure Steal_Map (Result : out Buckets_Access;
Time_Start : out Ada.Calendar.Time;
Time_End : out Ada.Calendar.Time) is
begin
Result := Buckets;
Time_Start := Start;
Start := Ada.Calendar.Clock;
Time_End := Start;
Buckets := null;
end Steal_Map;
-- ------------------------------
-- Add the measure
-- ------------------------------
procedure Add (Title : in String;
D : in Duration;
Count : in Positive := 1) is
use Ada.Containers;
use Ada.Calendar;
Pos : Hash_Type;
Node : Measure_Access;
begin
if Buckets = null then
Buckets := new Buckets_Type (0 .. 256);
end if;
Pos := Ada.Strings.Hash (Title) mod Buckets'Length;
Node := Buckets (Pos);
while Node /= null loop
if Node.Name'Length = Title'Length
and then Node.Name.all = Title then
Node.Count := Node.Count + Count;
Node.Time := Node.Time + D;
return;
end if;
Node := Node.Next;
end loop;
Buckets (Pos) := new Measure '(Name => new String '(Title),
Time => D,
Count => Count,
Next => Buckets (Pos));
end Add;
end Measure_Data;
-- ------------------------------
-- Format the duration in a time in 'ns', 'us', 'ms' or seconds.
-- ------------------------------
function Format (D : in Duration) return String is
begin
if D < 0.000_001 then
return Duration'Image (D * 1_000_000_000) (1 .. 6) & " ns";
elsif D < 0.001 then
return Duration'Image (D * 1_000_000) (1 .. 6) & " us";
elsif D < 1.0 then
return Duration'Image (D * 1_000) (1 .. 6) & " ms";
else
return Duration'Image (D) (1 .. 6) & " s";
end if;
end Format;
-- ------------------------------
-- Format the duration in a time in 'ns', 'us', 'ms' or seconds.
-- ------------------------------
function Format (D : in Duration;
Unit : in Unit_Type) return String is
begin
case Unit is
when Seconds =>
return Duration'Image (D);
when Milliseconds =>
return Duration'Image (D * 1_000);
when Microseconds =>
return Duration'Image (D * 1_000_000);
when Nanoseconds =>
return Duration'Image (D * 1_000_000_000);
end case;
end Format;
-- ------------------------------
-- Finalize the measures and release the storage.
-- ------------------------------
overriding
procedure Finalize (Measures : in out Measure_Set) is
Buckets : Buckets_Access;
TS, TE : Ada.Calendar.Time;
begin
-- When deleting the measure set, we have to release the buckets and measures
-- that were allocated. We could call <b>Write</b> but we don't know where
-- the measures have to be written.
Measures.Data.Steal_Map (Buckets, TS, TE);
if Buckets /= null then
for I in Buckets'Range loop
declare
Next : Measure_Access;
Node : Measure_Access := Buckets (I);
begin
while Node /= null loop
Free (Node.Name);
Next := Node.Next;
Free (Node);
Node := Next;
end loop;
end;
end loop;
Free (Buckets);
end if;
end Finalize;
end Util.Measures;
|
Improve the format of duration in performance reports Report the total time and the single call time
|
Improve the format of duration in performance reports
Report the total time and the single call time
|
Ada
|
apache-2.0
|
flottokarotto/ada-util,Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util
|
87bcf89024c3a6b503c8f2381172462872c717a8
|
src/asf-components-widgets-inputs.adb
|
src/asf-components-widgets-inputs.adb
|
-----------------------------------------------------------------------
-- asf-components-widgets-inputs -- Input 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 Ada.Strings.Unbounded;
with ASF.Components.Html.Messages;
with ASF.Applications.Messages.Vectors;
with Util.Beans.Objects;
package body ASF.Components.Widgets.Inputs is
use Ada.Strings.Unbounded;
-- ------------------------------
-- Render the input field title.
-- ------------------------------
procedure Render_Title (UI : in UIInput;
Writer : in Response_Writer_Access;
Context : in out Faces_Context'Class) is
Title : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "title");
begin
Writer.Start_Element ("dt");
Writer.Write (Title);
Writer.End_Element ("dt");
end Render_Title;
-- ------------------------------
-- Render the input component. Starts the DL/DD list and write the input
-- component with the possible associated error message.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIInput;
Context : in out Faces_Context'Class) is
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Id : constant String := To_String (UI.Get_Client_Id);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Messages : constant ASF.Applications.Messages.Vectors.Cursor := Context.Get_Messages (Id);
Style : constant String := UI.Get_Attribute ("styleClass", Context);
begin
Writer.Start_Element ("dl");
if ASF.Applications.Messages.Vectors.Has_Element (Messages) then
Writer.Write_Attribute ("class", Style & " awa-error");
elsif Style'Length > 0 then
Writer.Write_Attribute ("class", Style);
end if;
UI.Render_Title (Writer, Context);
Writer.Start_Element ("dd");
UI.Render_Input (Context);
end;
end Encode_Begin;
-- ------------------------------
-- Render the end of the input component. Closes the DL/DD list.
-- ------------------------------
overriding
procedure Encode_End (UI : in UIInput;
Context : in out Faces_Context'Class) is
use ASF.Components.Html.Messages;
begin
if not UI.Is_Rendered (Context) then
return;
end if;
-- Render the error message associated with the input field.
declare
Id : constant String := To_String (UI.Get_Client_Id);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Messages : constant ASF.Applications.Messages.Vectors.Cursor := Context.Get_Messages (Id);
begin
if ASF.Applications.Messages.Vectors.Has_Element (Messages) then
Write_Message (UI, ASF.Applications.Messages.Vectors.Element (Messages),
SPAN_NO_STYLE, False, True, Context);
end if;
Writer.End_Element ("dd");
Writer.End_Element ("dl");
end;
end Encode_End;
end ASF.Components.Widgets.Inputs;
|
Implement the input text field widget
|
Implement the input text field widget
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
|
dd767325665721c58a53695b7bfc0af691ea3577
|
src/babel-files-maps.adb
|
src/babel-files-maps.adb
|
-----------------------------------------------------------------------
-- babel-files-maps -- Hash maps for files and directories
-- 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.
-----------------------------------------------------------------------
package body Babel.Files.Maps is
-- ------------------------------
-- Find the file with the given name in the file map.
-- ------------------------------
function Find (From : in File_Map;
Name : in String) return File_Cursor is
begin
return From.Find (Key => Name'Unrestricted_Access);
end Find;
end Babel.Files.Maps;
|
Implement the Find operation
|
Implement the Find operation
|
Ada
|
apache-2.0
|
stcarrez/babel
|
|
ec855f10061f888423fd59d429cf26b0349f4ae6
|
src/security-auth-oauth.ads
|
src/security-auth-oauth.ads
|
-----------------------------------------------------------------------
-- security-auth-oauth -- OAuth based authentication
-- 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 Security.OAuth.Clients;
private package Security.Auth.OAuth is
-- ------------------------------
-- OAuth Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the OAuth authorization process.
type Manager is abstract new Security.Auth.Manager with private;
-- Initialize the authentication realm.
overriding
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Provider : in String := PROVIDER_OPENID);
-- 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.
-- Read the XRDS document from the URI and initialize the OpenID provider end point.
-- (See OpenID Section 7.3 Discovery)
overriding
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point);
-- Associate the application (relying party) with the OpenID provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
overriding
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association);
overriding
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String;
-- Verify the authentication result
overriding
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
-- Verify the OAuth access token and retrieve information about the user.
procedure Verify_Access_Token (Realm : in Manager;
Assoc : in Association;
Request : in Parameters'Class;
Token : in Security.OAuth.Clients.Access_Token_Access;
Result : in out Authentication) is abstract;
private
type Manager is abstract new Security.Auth.Manager with record
Return_To : Unbounded_String;
Realm : Unbounded_String;
Scope : Unbounded_String;
App : Security.OAuth.Clients.Application;
end record;
end Security.Auth.OAuth;
|
Define the OAuth based authorization
|
Define the OAuth based authorization
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
|
e8004e3c6907487bd7180bbb326536a0872e56b7
|
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
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
|
0822601ab5f0e98e1d1fa590d1e1dcfd1dbd8e76
|
src/wiki-streams-html-builders.ads
|
src/wiki-streams-html-builders.ads
|
-----------------------------------------------------------------------
-- wiki-streams-html-builders -- Wiki writer to a string builder
-- Copyright (C) 2011, 2012, 2013, 2015, 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.Streams.Builders;
-- == Writer interfaces ==
-- The <tt>Wiki.Writers</tt> package defines the interfaces used by the renderer to write
-- their outputs.
--
package Wiki.Streams.Html.Builders is
type Html_Output_Builder_Stream is limited new Wiki.Streams.Builders.Output_Builder_Stream
and Wiki.Streams.Html.Html_Output_Stream with private;
type Html_Output_Builder_Stream_Access is access all Html_Output_Builder_Stream'Class;
overriding
procedure Write_Wide_Element (Stream : in out Html_Output_Builder_Stream;
Name : in String;
Content : in Wiki.Strings.WString);
overriding
procedure Write_Wide_Attribute (Stream : in out Html_Output_Builder_Stream;
Name : in String;
Content : in Unbounded_Wide_Wide_String);
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
overriding
procedure Write_Wide_Attribute (Stream : in out Html_Output_Builder_Stream;
Name : in String;
Content : in Wiki.Strings.WString);
overriding
procedure Start_Element (Stream : in out Html_Output_Builder_Stream;
Name : in String);
overriding
procedure End_Element (Stream : in out Html_Output_Builder_Stream;
Name : in String);
overriding
procedure Write_Wide_Text (Stream : in out Html_Output_Builder_Stream;
Content : in Wiki.Strings.WString);
private
type Html_Output_Builder_Stream is limited new Wiki.Streams.Builders.Output_Builder_Stream
and Wiki.Streams.Html.Html_Output_Stream with record
-- Whether an XML element must be closed (that is a '>' is necessary)
Close_Start : Boolean := False;
end record;
end Wiki.Streams.Html.Builders;
|
Declare the Wiki.Streams.Html.Builders package for the HTML output stream
|
Declare the Wiki.Streams.Html.Builders package for the HTML output stream
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
|
7838272e51c95195ce6e37c5b05d12dfac61ac23
|
src/util-concurrent-arrays.ads
|
src/util-concurrent-arrays.ads
|
-----------------------------------------------------------------------
-- Util.Concurrent.Arrays -- Concurrent Arrays
-- 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.Finalization;
with Util.Concurrent.Counters;
-- == Introduction ==
-- The <b>Util.Concurrent.Arrays</b> generic package defines an array which provides a
-- concurrent read only access and a protected exclusive write access. This implementation
-- is intended to be used in applications that have to frequently iterate over the array
-- content. Adding or removing elements in the array is assumed to be a not so frequent
-- operation. Based on these assumptions, updating the array is implemented by
-- using the <tt>copy on write</tt> design pattern. Read access is provided through a
-- reference object that can be shared by multiple readers.
--
-- == Declaration ==
-- The package must be instantiated using the element type representing the array element.
--
-- package My_Array is new Util.Concurrent.Arrays (Element_Type => Integer);
--
-- == Adding Elements ==
-- The vector instance is declared and elements are added as follows:
--
-- C : My_Array.Vector;
--
-- C.Append (E1);
--
-- == Iterating over the array ==
-- To read and iterate over the vector, a task will get a reference to the vector array
-- and it will iterate over it. The reference will be held until the reference object is
-- finalized. While doing so, if another task updates the vector, a new vector array will
-- be associated with the vector instance (but this will not change the reader's references).
--
-- R : My_Array.Ref := C.Get;
--
-- R.Iterate (Process'Access);
-- ...
-- R.Iterate (Process'Access);
--
-- In the above example, the two `Iterate` operations will iterate over the same list of
-- elements, even if another task appends an element in the middle.
--
-- Notes:
-- * This package is close to the Java class `java.util.concurrent.CopyOnWriteArrayList`.
-- * The package implements voluntarily a very small subset of `Ada.Containers.Vectors`.
-- * The implementation does not use the Ada container for performance and size reasons.
-- * The `Iterate` and `Reverse_Iterate` operation give a direct access to the element.
generic
type Element_Type is private;
with function "=" (Left, Right : in Element_Type) return Boolean is <>;
package Util.Concurrent.Arrays is
-- The reference to the read-only vector elements.
type Ref is tagged private;
-- Returns True if the container is empty.
function Is_Empty (Container : in Ref) return Boolean;
-- Iterate over the vector elements and execute the <b>Process</b> procedure
-- with the element as parameter.
procedure Iterate (Container : in Ref;
Process : not null access procedure (Item : in Element_Type));
-- Iterate over the vector elements in reverse order and execute the <b>Process</b> procedure
-- with the element as parameter.
procedure Reverse_Iterate (Container : in Ref;
Process : not null access procedure (Item : in Element_Type));
-- Vector of elements.
type Vector is new Ada.Finalization.Limited_Controlled with private;
-- Get a read-only reference to the vector elements. The referenced vector will never
-- be modified.
function Get (Container : in Vector'Class) return Ref;
-- Append the element to the vector. The modification will not be visible to readers
-- until they call the <b>Get</b> function.
procedure Append (Container : in out Vector;
Item : in Element_Type);
-- Remove the element represented by <b>Item</b> from the vector. The modification will
-- not be visible to readers until they call the <b>Get</b> function.
procedure Remove (Container : in out Vector;
Item : in Element_Type);
-- Release the vector elements.
overriding
procedure Finalize (Object : in out Vector);
private
-- To store the vector elements, we use an array which is allocated dynamically.
-- The generated code is smaller compared to the use of Ada vectors container.
type Element_Array is array (Positive range <>) of Element_Type;
type Element_Array_Access is access all Element_Array;
Null_Element_Array : constant Element_Array_Access := null;
type Vector_Record (Len : Positive) is record
Ref_Counter : Util.Concurrent.Counters.Counter;
List : Element_Array (1 .. Len);
end record;
type Vector_Record_Access is access all Vector_Record;
type Ref is new Ada.Finalization.Controlled with record
Target : Vector_Record_Access := null;
end record;
-- Release the reference. Invoke <b>Finalize</b> and free the storage if it was
-- the last reference.
overriding
procedure Finalize (Obj : in out Ref);
-- Update the reference counter after an assignment.
overriding
procedure Adjust (Obj : in out Ref);
-- Vector of objects
protected type Protected_Vector is
-- Get a readonly reference to the vector.
function Get return Ref;
-- Append the element to the vector.
procedure Append (Item : in Element_Type);
-- Remove the element from the vector.
procedure Remove (Item : in Element_Type);
private
Elements : Ref;
end Protected_Vector;
type Vector is new Ada.Finalization.Limited_Controlled with record
List : Protected_Vector;
end record;
end Util.Concurrent.Arrays;
|
-----------------------------------------------------------------------
-- Util.Concurrent.Arrays -- Concurrent Arrays
-- 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.Finalization;
with Util.Concurrent.Counters;
-- == Introduction ==
-- The <b>Util.Concurrent.Arrays</b> generic package defines an array which provides a
-- concurrent read only access and a protected exclusive write access. This implementation
-- is intended to be used in applications that have to frequently iterate over the array
-- content. Adding or removing elements in the array is assumed to be a not so frequent
-- operation. Based on these assumptions, updating the array is implemented by
-- using the <tt>copy on write</tt> design pattern. Read access is provided through a
-- reference object that can be shared by multiple readers.
--
-- == Declaration ==
-- The package must be instantiated using the element type representing the array element.
--
-- package My_Array is new Util.Concurrent.Arrays (Element_Type => Integer);
--
-- == Adding Elements ==
-- The vector instance is declared and elements are added as follows:
--
-- C : My_Array.Vector;
--
-- C.Append (E1);
--
-- == Iterating over the array ==
-- To read and iterate over the vector, a task will get a reference to the vector array
-- and it will iterate over it. The reference will be held until the reference object is
-- finalized. While doing so, if another task updates the vector, a new vector array will
-- be associated with the vector instance (but this will not change the reader's references).
--
-- R : My_Array.Ref := C.Get;
--
-- R.Iterate (Process'Access);
-- ...
-- R.Iterate (Process'Access);
--
-- In the above example, the two `Iterate` operations will iterate over the same list of
-- elements, even if another task appends an element in the middle.
--
-- Notes:
-- * This package is close to the Java class `java.util.concurrent.CopyOnWriteArrayList`.
--
-- * The package implements voluntarily a very small subset of `Ada.Containers.Vectors`.
--
-- * The implementation does not use the Ada container for performance and size reasons.
--
-- * The `Iterate` and `Reverse_Iterate` operation give a direct access to the element.
generic
type Element_Type is private;
with function "=" (Left, Right : in Element_Type) return Boolean is <>;
package Util.Concurrent.Arrays is
-- The reference to the read-only vector elements.
type Ref is tagged private;
-- Returns True if the container is empty.
function Is_Empty (Container : in Ref) return Boolean;
-- Iterate over the vector elements and execute the <b>Process</b> procedure
-- with the element as parameter.
procedure Iterate (Container : in Ref;
Process : not null access procedure (Item : in Element_Type));
-- Iterate over the vector elements in reverse order and execute the <b>Process</b> procedure
-- with the element as parameter.
procedure Reverse_Iterate (Container : in Ref;
Process : not null access procedure (Item : in Element_Type));
-- Vector of elements.
type Vector is new Ada.Finalization.Limited_Controlled with private;
-- Get a read-only reference to the vector elements. The referenced vector will never
-- be modified.
function Get (Container : in Vector'Class) return Ref;
-- Append the element to the vector. The modification will not be visible to readers
-- until they call the <b>Get</b> function.
procedure Append (Container : in out Vector;
Item : in Element_Type);
-- Remove the element represented by <b>Item</b> from the vector. The modification will
-- not be visible to readers until they call the <b>Get</b> function.
procedure Remove (Container : in out Vector;
Item : in Element_Type);
-- Release the vector elements.
overriding
procedure Finalize (Object : in out Vector);
private
-- To store the vector elements, we use an array which is allocated dynamically.
-- The generated code is smaller compared to the use of Ada vectors container.
type Element_Array is array (Positive range <>) of Element_Type;
type Element_Array_Access is access all Element_Array;
Null_Element_Array : constant Element_Array_Access := null;
type Vector_Record (Len : Positive) is record
Ref_Counter : Util.Concurrent.Counters.Counter;
List : Element_Array (1 .. Len);
end record;
type Vector_Record_Access is access all Vector_Record;
type Ref is new Ada.Finalization.Controlled with record
Target : Vector_Record_Access := null;
end record;
-- Release the reference. Invoke <b>Finalize</b> and free the storage if it was
-- the last reference.
overriding
procedure Finalize (Obj : in out Ref);
-- Update the reference counter after an assignment.
overriding
procedure Adjust (Obj : in out Ref);
-- Vector of objects
protected type Protected_Vector is
-- Get a readonly reference to the vector.
function Get return Ref;
-- Append the element to the vector.
procedure Append (Item : in Element_Type);
-- Remove the element from the vector.
procedure Remove (Item : in Element_Type);
private
Elements : Ref;
end Protected_Vector;
type Vector is new Ada.Finalization.Limited_Controlled with record
List : Protected_Vector;
end record;
end Util.Concurrent.Arrays;
|
Update the documentation for dynamo
|
Update the documentation for dynamo
|
Ada
|
apache-2.0
|
Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util
|
a266272133d8a91550e96ff8ea97dd8302a4be20
|
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 '"' | '\' | '/' =>
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;
|
-----------------------------------------------------------------------
-- util-serialize-io-json -- JSON Serialization Driver
-- Copyright (C) 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 Interfaces;
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);
function Hexdigit (C : in Character) return Interfaces.Unsigned_32;
-- 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;
function Hexdigit (C : in Character) return Interfaces.Unsigned_32 is
use type Interfaces.Unsigned_32;
begin
if C >= '0' and C <= '9' then
return Character'Pos (C) - Character'Pos ('0');
elsif C >= 'a' and C <= 'f' then
return Character'Pos (C) - Character'Pos ('a') + 10;
elsif C >= 'A' and C <= 'F' then
return Character'Pos (C) - Character'Pos ('A') + 10;
else
raise Constraint_Error with "Invalid hexdigit: " & C;
end if;
end Hexdigit;
-- ------------------------------
-- 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' =>
declare
use Interfaces;
C2, C3, C4 : Character;
Val : Interfaces.Unsigned_32;
begin
Stream.Read (Char => C1);
Stream.Read (Char => C2);
Stream.Read (Char => C3);
Stream.Read (Char => C4);
Val := Interfaces.Shift_Left (Hexdigit (C1), 12);
Val := Val + Interfaces.Shift_Left (Hexdigit (C2), 8);
Val := Val + Interfaces.Shift_Left (Hexdigit (C3), 4);
Val := Val + Hexdigit (C4);
-- Encode the value as an UTF-8 string.
if Val >= 16#1000# then
Append (P.Token, Character'Val (16#E0# or Shift_Right (Val, 12)));
Val := Val and 16#0fff#;
Append (P.Token, Character'Val (16#80# or Shift_Right (Val, 6)));
Val := Val and 16#03f#;
C1 := Character'Val (16#80# or Val);
elsif Val >= 16#80# then
Append (P.Token, Character'Val (16#C0# or Shift_Right (Val, 6)));
Val := Val and 16#03f#;
C1 := Character'Val (16#80# or Val);
else
C1 := Character'Val (Val);
end if;
end;
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;
|
Handle the JSON \u sequences and emit UTF-8 strings
|
Handle the JSON \u sequences and emit UTF-8 strings
|
Ada
|
apache-2.0
|
flottokarotto/ada-util,Letractively/ada-util,flottokarotto/ada-util,Letractively/ada-util
|
ac32c851f5f425d690d97d8f5a6c4d09782ab73f
|
src/sys/encoders/util-encoders-uri.ads
|
src/sys/encoders/util-encoders-uri.ads
|
-----------------------------------------------------------------------
-- util-encoders-uri -- Encode and decode URI using percent encoding
-- 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.
-----------------------------------------------------------------------
-- == URI Encoder and Decoder ==
-- The `Util.Encoders.URI` package provides operations to encode and decode
-- using the URI percent encoding and decoding scheme.
-- A string encoded using percent encoding as described in RFC 3986 is
-- simply decoded as follows:
--
-- Decoded : constant String := Util.Encoders.URI.Decode ("%20%2F%3A");
--
-- To encode a string, one must choose the character set that must be encoded
-- and then call the `Encode` function. The character set indicates those
-- characters that must be percent encoded. Two character sets are provided,
--
-- * `HREF_STRICT` defines a strict character set to encode all reserved
-- characters as defined by RFC 3986. This is the default.
-- * `HREF_LOOSE` defines a character set that does not encode the
-- reserved characters such as `-_.+!*'(),%#@?=;:/&$`.
--
-- Encoded : constant String := Util.Encoders.URI.Encode (" /:");
--
package Util.Encoders.URI is
pragma Preelaborate;
type Encoding_Array is array (Character) of Boolean;
-- Strict encoding of reserved characters RFC3986
HREF_STRICT : constant Encoding_Array
:= ('0' .. '9' => False,
'a' .. 'z' => False,
'A' .. 'Z' => False,
'-' => False, '.' => False, '_' => False, '~' => False,
others => True);
-- Loose encoding where punctuation reserved characters are not encoded.
HREF_LOOSE : constant Encoding_Array
:= ('0' .. '9' => False,
'a' .. 'z' => False,
'A' .. 'Z' => False,
'-' => False, '.' => False, '_' => False, '~' => False, '+' => False,
''' => False, '*' => False, '(' => False, '&' => False, '$' => False,
')' => False, ',' => False, '%' => False, '#' => False, '@' => False,
'?' => False, '=' => False, ';' => False, ':' => False, '/' => False,
others => True);
-- Compute the length of the encoded URI string with percent encoding
-- and with the given encoding array. Characters for which the `Encoding` array
-- returns True are encoded using %HEXDIGIT HEXDIGIT.
-- Returns the length of encoded string.
function Encoded_Length (URI : in String;
Encoding : in Encoding_Array := HREF_STRICT) return Natural;
-- Encode the string using URI percent encoding.
-- Characters for which the `Encoding` array returns True are encoded
-- using %HEXDIGIT HEXDIGIT. Returns the percent encoded string.
function Encode (URI : in String;
Encoding : in Encoding_Array := HREF_STRICT) return String;
-- Decode the percent encoded URI string.
function Decode (URI : in String) return String;
end Util.Encoders.URI;
|
Add the Util.Encoders.URI package with functions to encode/decode percent encoding
|
Add the Util.Encoders.URI package with functions to encode/decode percent encoding
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
|
d0c70ad30d82ad1685a47254bd057165d71e0629
|
src/el-beans-methods.ads
|
src/el-beans-methods.ads
|
-----------------------------------------------------------------------
-- EL.Beans.Methods -- Bean methods
-- Copyright (C) 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 Util.Strings;
package EL.Beans.Methods is
pragma Preelaborate;
type Method_Binding is tagged limited record
Name : Util.Strings.Name_Access;
end record;
type Method_Binding_Access is access constant Method_Binding'Class;
type Method_Binding_Array is array (Natural range <>) of Method_Binding_Access;
type Method_Binding_Array_Access is access constant Method_Binding_Array;
type Method_Bean is limited Interface;
type Method_Bean_Access is access all Method_Bean'Class;
function Get_Method_Bindings (From : in Method_Bean)
return Method_Binding_Array_Access is abstract;
end EL.Beans.Methods;
|
Declare the method binding types
|
Declare the method binding types
|
Ada
|
apache-2.0
|
Letractively/ada-el
|
|
dde6442dce8fe8773eab4c5f07494c864753ebce
|
src/security-policies.adb
|
src/security-policies.adb
|
-----------------------------------------------------------------------
-- security-policies -- Security Policies
-- Copyright (C) 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.Unchecked_Deallocation;
with Util.Log.Loggers;
with Security.Controllers;
package body Security.Policies is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies");
-- Get the policy name.
function Get_Name (From : in Policy) return String is
begin
return "";
end Get_Name;
-- ------------------------------
-- Get the policy index.
-- ------------------------------
function Get_Policy_Index (From : in Policy'Class) return Policy_Index is
begin
return From.Index;
end Get_Policy_Index;
-- ------------------------------
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
-- ------------------------------
procedure Add_Permission (Manager : in out Policy;
Name : in String;
Permission : in Controller_Access) is
begin
Manager.Manager.Add_Permission (Name, Permission);
end Add_Permission;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- ------------------------------
-- Get the policy with the name <b>Name</b> registered in the policy manager.
-- Returns null if there is no such policy.
-- ------------------------------
function Get_Policy (Manager : in Policy_Manager;
Name : in String) return Policy_Access is
begin
for I in Manager.Policies'Range loop
if Manager.Policies (I) = null then
return null;
elsif Manager.Policies (I).Get_Name = Name then
return Manager.Policies (I);
end if;
end loop;
return null;
end Get_Policy;
-- ------------------------------
-- Add the policy to the policy manager. After a policy is added in the manager,
-- it can participate in the security policy.
-- Raises Policy_Error if the policy table is full.
-- ------------------------------
procedure Add_Policy (Manager : in out Policy_Manager;
Policy : in Policy_Access) is
Name : constant String := Policy.Get_Name;
begin
Log.Info ("Adding policy {0}", Name);
for I in Manager.Policies'Range loop
if Manager.Policies (I) = null then
Manager.Policies (I) := Policy;
Policy.Manager := Manager'Unchecked_Access;
Policy.Index := I;
return;
end if;
end loop;
Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}",
Policy_Index'Image (Manager.Max_Policies + 1), Name);
raise Policy_Error;
end Add_Policy;
-- ------------------------------
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
-- ------------------------------
procedure Add_Permission (Manager : in out Policy_Manager;
Name : in String;
Permission : in Controller_Access) is
use type Permissions.Permission_Index;
Index : Permission_Index;
begin
Log.Info ("Adding permission {0}", Name);
Permissions.Add_Permission (Name, Index);
if Index >= Manager.Last_Index then
declare
Count : constant Permission_Index := Index + 32;
Perms : constant Controller_Access_Array_Access
:= new Controller_Access_Array (0 .. Count);
begin
if Manager.Permissions /= null then
Perms (Manager.Permissions'Range) := Manager.Permissions.all;
end if;
Manager.Permissions := Perms;
Manager.Last_Index := Count;
end;
end if;
Manager.Permissions (Index) := Permission;
end Add_Permission;
-- ------------------------------
-- Get the security controller associated with the permission index <b>Index</b>.
-- Returns null if there is no such controller.
-- ------------------------------
function Get_Controller (Manager : in Policy_Manager'Class;
Index : in Permissions.Permission_Index) return Controller_Access is
use type Permissions.Permission_Index;
begin
if Index >= Manager.Last_Index then
return null;
else
return Manager.Permissions (Index);
end if;
end Get_Controller;
-- Read the policy file
procedure Read_Policy (Manager : in out Policy_Manager;
File : in String) is
use Util;
Reader : Util.Serialize.IO.XML.Parser;
package Policy_Config is
new Reader_Config (Reader, Manager'Unchecked_Access);
pragma Warnings (Off, Policy_Config);
begin
Log.Info ("Reading policy file {0}", File);
-- Prepare the reader to parse the policy configuration.
for I in Manager.Policies'Range loop
exit when Manager.Policies (I) = null;
Manager.Policies (I).Prepare_Config (Reader);
end loop;
-- Read the configuration file.
Reader.Parse (File);
-- Finish the policy configuration.
for I in Manager.Policies'Range loop
exit when Manager.Policies (I) = null;
Manager.Policies (I).Finish_Config (Reader);
end loop;
end Read_Policy;
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Policy_Manager) is
begin
null;
end Initialize;
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Policy_Manager) is
procedure Free is
new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class,
Controller_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Controller_Access_Array,
Controller_Access_Array_Access);
begin
if Manager.Permissions /= null then
for I in Manager.Permissions.all'Range loop
exit when Manager.Permissions (I) = null;
-- SCz 2011-12-03: GNAT 2011 reports a compilation error:
-- 'missing "with" clause on package "Security.Controllers"'
-- if we use the 'Security.Controller_Access' type, even if this "with" clause exist.
-- gcc 4.4.3 under Ubuntu does not have this issue.
-- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler bug
-- but we have to use a temporary variable and do some type conversion...
declare
P : Controller_Access := Manager.Permissions (I).all'Access;
begin
Free (P);
Manager.Permissions (I) := null;
end;
end loop;
Free (Manager.Permissions);
end if;
end Finalize;
end Security.Policies;
|
-----------------------------------------------------------------------
-- security-policies -- Security Policies
-- Copyright (C) 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.Unchecked_Deallocation;
with Util.Log.Loggers;
with Security.Controllers;
package body Security.Policies is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies");
-- Get the policy name.
function Get_Name (From : in Policy) return String is
begin
return "";
end Get_Name;
-- ------------------------------
-- Get the policy index.
-- ------------------------------
function Get_Policy_Index (From : in Policy'Class) return Policy_Index is
begin
return From.Index;
end Get_Policy_Index;
-- ------------------------------
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
-- ------------------------------
procedure Add_Permission (Manager : in out Policy;
Name : in String;
Permission : in Controller_Access) is
begin
Manager.Manager.Add_Permission (Name, Permission);
end Add_Permission;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- ------------------------------
-- Get the policy with the name <b>Name</b> registered in the policy manager.
-- Returns null if there is no such policy.
-- ------------------------------
function Get_Policy (Manager : in Policy_Manager;
Name : in String) return Policy_Access is
begin
for I in Manager.Policies'Range loop
if Manager.Policies (I) = null then
return null;
elsif Manager.Policies (I).Get_Name = Name then
return Manager.Policies (I);
end if;
end loop;
return null;
end Get_Policy;
-- ------------------------------
-- Add the policy to the policy manager. After a policy is added in the manager,
-- it can participate in the security policy.
-- Raises Policy_Error if the policy table is full.
-- ------------------------------
procedure Add_Policy (Manager : in out Policy_Manager;
Policy : in Policy_Access) is
Name : constant String := Policy.Get_Name;
begin
Log.Info ("Adding policy {0}", Name);
for I in Manager.Policies'Range loop
if Manager.Policies (I) = null then
Manager.Policies (I) := Policy;
Policy.Manager := Manager'Unchecked_Access;
Policy.Index := I;
return;
end if;
end loop;
Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}",
Policy_Index'Image (Manager.Max_Policies + 1), Name);
raise Policy_Error;
end Add_Policy;
-- ------------------------------
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
-- ------------------------------
procedure Add_Permission (Manager : in out Policy_Manager;
Name : in String;
Permission : in Controller_Access) is
use type Permissions.Permission_Index;
Index : Permission_Index;
begin
Log.Info ("Adding permission {0}", Name);
Permissions.Add_Permission (Name, Index);
if Index >= Manager.Last_Index then
declare
Count : constant Permission_Index := Index + 32;
Perms : constant Controller_Access_Array_Access
:= new Controller_Access_Array (0 .. Count);
begin
if Manager.Permissions /= null then
Perms (Manager.Permissions'Range) := Manager.Permissions.all;
end if;
Manager.Permissions := Perms;
Manager.Last_Index := Count;
end;
end if;
Manager.Permissions (Index) := Permission;
end Add_Permission;
-- ------------------------------
-- Get the security controller associated with the permission index <b>Index</b>.
-- Returns null if there is no such controller.
-- ------------------------------
function Get_Controller (Manager : in Policy_Manager'Class;
Index : in Permissions.Permission_Index) return Controller_Access is
use type Permissions.Permission_Index;
begin
if Index >= Manager.Last_Index then
return null;
else
return Manager.Permissions (Index);
end if;
end Get_Controller;
-- ------------------------------
-- Create the policy contexts to be associated with the security context.
-- ------------------------------
function Create_Policy_Contexts (Manager : in Policy_Manager)
return Policy_Context_Array_Access is
begin
return new Policy_Context_Array (1 .. Manager.Max_Policies);
end Create_Policy_Contexts;
-- Read the policy file
procedure Read_Policy (Manager : in out Policy_Manager;
File : in String) is
use Util;
Reader : Util.Serialize.IO.XML.Parser;
package Policy_Config is
new Reader_Config (Reader, Manager'Unchecked_Access);
pragma Warnings (Off, Policy_Config);
begin
Log.Info ("Reading policy file {0}", File);
-- Prepare the reader to parse the policy configuration.
for I in Manager.Policies'Range loop
exit when Manager.Policies (I) = null;
Manager.Policies (I).Prepare_Config (Reader);
end loop;
-- Read the configuration file.
Reader.Parse (File);
-- Finish the policy configuration.
for I in Manager.Policies'Range loop
exit when Manager.Policies (I) = null;
Manager.Policies (I).Finish_Config (Reader);
end loop;
end Read_Policy;
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Policy_Manager) is
begin
null;
end Initialize;
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Policy_Manager) is
procedure Free is
new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class,
Controller_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Controller_Access_Array,
Controller_Access_Array_Access);
begin
if Manager.Permissions /= null then
for I in Manager.Permissions.all'Range loop
exit when Manager.Permissions (I) = null;
-- SCz 2011-12-03: GNAT 2011 reports a compilation error:
-- 'missing "with" clause on package "Security.Controllers"'
-- if we use the 'Security.Controller_Access' type, even if this "with" clause exist.
-- gcc 4.4.3 under Ubuntu does not have this issue.
-- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler bug
-- but we have to use a temporary variable and do some type conversion...
declare
P : Controller_Access := Manager.Permissions (I).all'Access;
begin
Free (P);
Manager.Permissions (I) := null;
end;
end loop;
Free (Manager.Permissions);
end if;
end Finalize;
end Security.Policies;
|
Implement the Create_Policy_Contexts operation
|
Implement the Create_Policy_Contexts operation
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
eced66b50edf5a0764f622e66439007c690e9742
|
src/http/util-http-clients.ads
|
src/http/util-http-clients.ads
|
-----------------------------------------------------------------------
-- util-http-clients -- HTTP Clients
-- 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.Finalization;
with Util.Http.Cookies;
-- == Client ==
-- The <tt>Util.Http.Clients</tt> package defines a set of API for an HTTP client to send
-- requests to an HTTP server.
--
-- === GET request ===
-- To retrieve a content using the HTTP GET operation, a client instance must be created.
-- The response is returned in a specific object that must therefore be declared:
--
-- Http : Util.Http.Clients.Client;
-- Response : Util.Http.Clients.Response;
--
-- Before invoking the GET operation, the client can setup a number of HTTP headers.
--
-- Http.Add_Header ("X-Requested-By", "wget");
--
-- The GET operation is performed when the <tt>Get</tt> procedure is called:
--
-- Http.Get ("http://www.google.com", Response);
--
-- Once the response is received, the <tt>Response</tt> object contains the status of the
-- HTTP response, the HTTP reply headers and the body.
package Util.Http.Clients is
Connection_Error : exception;
-- ------------------------------
-- Http response
-- ------------------------------
-- The <b>Response</b> type represents a response returned by an HTTP request.
type Response is limited new Abstract_Response with private;
-- Returns a boolean indicating whether the named response header has already
-- been set.
overriding
function Contains_Header (Reply : in Response;
Name : in String) return Boolean;
-- Returns the value of the specified response header as a String. If the response
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
overriding
function Get_Header (Reply : in Response;
Name : in String) return String;
-- Sets a message header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
overriding
procedure Set_Header (Reply : in out Response;
Name : in String;
Value : in String);
-- Adds a request header with the given name and value.
-- This method allows request headers to have multiple values.
overriding
procedure Add_Header (Reply : in out Response;
Name : in String;
Value : in String);
-- Iterate over the response headers and executes the <b>Process</b> procedure.
overriding
procedure Iterate_Headers (Reply : in Response;
Process : not null access
procedure (Name : in String;
Value : in String));
-- Get the response body as a string.
overriding
function Get_Body (Reply : in Response) return String;
-- Get the response status code.
overriding
function Get_Status (Reply : in Response) return Natural;
-- ------------------------------
-- Http client
-- ------------------------------
-- The <b>Client</b> type allows to execute HTTP GET/POST requests.
type Client is limited new Abstract_Request with private;
type Client_Access is access all Client;
-- Returns a boolean indicating whether the named response header has already
-- been set.
overriding
function Contains_Header (Request : in Client;
Name : in String) return Boolean;
-- Returns the value of the specified request header as a String. If the request
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
overriding
function Get_Header (Request : in Client;
Name : in String) return String;
-- Sets a header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
overriding
procedure Set_Header (Request : in out Client;
Name : in String;
Value : in String);
-- Adds a header with the given name and value.
-- This method allows headers to have multiple values.
overriding
procedure Add_Header (Request : in out Client;
Name : in String;
Value : in String);
-- Iterate over the request headers and executes the <b>Process</b> procedure.
overriding
procedure Iterate_Headers (Request : in Client;
Process : not null access
procedure (Name : in String;
Value : in String));
-- Removes all headers with the given name.
procedure Remove_Header (Request : in out Client;
Name : in String);
-- Adds the specified cookie to the request. This method can be called multiple
-- times to set more than one cookie.
procedure Add_Cookie (Http : in out Client;
Cookie : in Util.Http.Cookies.Cookie);
-- Execute an http GET request on the given URL. Additional request parameters,
-- cookies and headers should have been set on the client object.
procedure Get (Request : in out Client;
URL : in String;
Reply : out Response'Class);
-- Execute an http POST request on the given URL. The post data is passed in <b>Data</b>.
-- Additional request cookies and headers should have been set on the client object.
procedure Post (Request : in out Client;
URL : in String;
Data : in String;
Reply : out Response'Class);
private
subtype Http_Request is Abstract_Request;
subtype Http_Request_Access is Abstract_Request_Access;
subtype Http_Response is Abstract_Response;
subtype Http_Response_Access is Abstract_Response_Access;
type Http_Manager is interface;
type Http_Manager_Access is access all Http_Manager'Class;
procedure Create (Manager : in Http_Manager;
Http : in out Client'Class) is abstract;
procedure Do_Get (Manager : in Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class) is abstract;
procedure Do_Post (Manager : in Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class) is abstract;
Default_Http_Manager : Http_Manager_Access;
type Response is new Ada.Finalization.Limited_Controlled and Abstract_Response with record
Delegate : Abstract_Response_Access;
end record;
-- Free the resource used by the response.
overriding
procedure Finalize (Reply : in out Response);
type Client is new Ada.Finalization.Limited_Controlled and Abstract_Request with record
Manager : Http_Manager_Access;
Delegate : Http_Request_Access;
end record;
-- Initialize the client
overriding
procedure Initialize (Http : in out Client);
overriding
procedure Finalize (Http : in out Client);
end Util.Http.Clients;
|
-----------------------------------------------------------------------
-- util-http-clients -- HTTP Clients
-- 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.Finalization;
with Util.Http.Cookies;
-- == Client ==
-- The <tt>Util.Http.Clients</tt> package defines a set of API for an HTTP client to send
-- requests to an HTTP server.
--
-- === GET request ===
-- To retrieve a content using the HTTP GET operation, a client instance must be created.
-- The response is returned in a specific object that must therefore be declared:
--
-- Http : Util.Http.Clients.Client;
-- Response : Util.Http.Clients.Response;
--
-- Before invoking the GET operation, the client can setup a number of HTTP headers.
--
-- Http.Add_Header ("X-Requested-By", "wget");
--
-- The GET operation is performed when the <tt>Get</tt> procedure is called:
--
-- Http.Get ("http://www.google.com", Response);
--
-- Once the response is received, the <tt>Response</tt> object contains the status of the
-- HTTP response, the HTTP reply headers and the body. A response header can be obtained
-- by using the <tt>Get_Header</tt> function and the body using <tt>Get_Body</tt>:
--
-- Body : constant String := Response.Get_Body;
--
package Util.Http.Clients is
Connection_Error : exception;
-- ------------------------------
-- Http response
-- ------------------------------
-- The <b>Response</b> type represents a response returned by an HTTP request.
type Response is limited new Abstract_Response with private;
-- Returns a boolean indicating whether the named response header has already
-- been set.
overriding
function Contains_Header (Reply : in Response;
Name : in String) return Boolean;
-- Returns the value of the specified response header as a String. If the response
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
overriding
function Get_Header (Reply : in Response;
Name : in String) return String;
-- Sets a message header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
overriding
procedure Set_Header (Reply : in out Response;
Name : in String;
Value : in String);
-- Adds a request header with the given name and value.
-- This method allows request headers to have multiple values.
overriding
procedure Add_Header (Reply : in out Response;
Name : in String;
Value : in String);
-- Iterate over the response headers and executes the <b>Process</b> procedure.
overriding
procedure Iterate_Headers (Reply : in Response;
Process : not null access
procedure (Name : in String;
Value : in String));
-- Get the response body as a string.
overriding
function Get_Body (Reply : in Response) return String;
-- Get the response status code.
overriding
function Get_Status (Reply : in Response) return Natural;
-- ------------------------------
-- Http client
-- ------------------------------
-- The <b>Client</b> type allows to execute HTTP GET/POST requests.
type Client is limited new Abstract_Request with private;
type Client_Access is access all Client;
-- Returns a boolean indicating whether the named response header has already
-- been set.
overriding
function Contains_Header (Request : in Client;
Name : in String) return Boolean;
-- Returns the value of the specified request header as a String. If the request
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
overriding
function Get_Header (Request : in Client;
Name : in String) return String;
-- Sets a header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
overriding
procedure Set_Header (Request : in out Client;
Name : in String;
Value : in String);
-- Adds a header with the given name and value.
-- This method allows headers to have multiple values.
overriding
procedure Add_Header (Request : in out Client;
Name : in String;
Value : in String);
-- Iterate over the request headers and executes the <b>Process</b> procedure.
overriding
procedure Iterate_Headers (Request : in Client;
Process : not null access
procedure (Name : in String;
Value : in String));
-- Removes all headers with the given name.
procedure Remove_Header (Request : in out Client;
Name : in String);
-- Adds the specified cookie to the request. This method can be called multiple
-- times to set more than one cookie.
procedure Add_Cookie (Http : in out Client;
Cookie : in Util.Http.Cookies.Cookie);
-- Execute an http GET request on the given URL. Additional request parameters,
-- cookies and headers should have been set on the client object.
procedure Get (Request : in out Client;
URL : in String;
Reply : out Response'Class);
-- Execute an http POST request on the given URL. The post data is passed in <b>Data</b>.
-- Additional request cookies and headers should have been set on the client object.
procedure Post (Request : in out Client;
URL : in String;
Data : in String;
Reply : out Response'Class);
private
subtype Http_Request is Abstract_Request;
subtype Http_Request_Access is Abstract_Request_Access;
subtype Http_Response is Abstract_Response;
subtype Http_Response_Access is Abstract_Response_Access;
type Http_Manager is interface;
type Http_Manager_Access is access all Http_Manager'Class;
procedure Create (Manager : in Http_Manager;
Http : in out Client'Class) is abstract;
procedure Do_Get (Manager : in Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class) is abstract;
procedure Do_Post (Manager : in Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class) is abstract;
Default_Http_Manager : Http_Manager_Access;
type Response is new Ada.Finalization.Limited_Controlled and Abstract_Response with record
Delegate : Abstract_Response_Access;
end record;
-- Free the resource used by the response.
overriding
procedure Finalize (Reply : in out Response);
type Client is new Ada.Finalization.Limited_Controlled and Abstract_Request with record
Manager : Http_Manager_Access;
Delegate : Http_Request_Access;
end record;
-- Initialize the client
overriding
procedure Initialize (Http : in out Client);
overriding
procedure Finalize (Http : in out Client);
end Util.Http.Clients;
|
Update the documentation
|
Update the documentation
|
Ada
|
apache-2.0
|
Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util
|
c6ece4d4f43f0124c8c7c2ff24ede06860c0b80e
|
src/ado-utils.adb
|
src/ado-utils.adb
|
-----------------------------------------------------------------------
-- ado-utils -- Utility operations for ADO
-- 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 ADO.Utils is
-- ------------------------------
-- Build a bean object from the identifier.
-- ------------------------------
function To_Object (Id : in ADO.Identifier) return Util.Beans.Objects.Object is
begin
if Id = ADO.NO_IDENTIFIER then
return Util.Beans.Objects.Null_Object;
else
return Util.Beans.Objects.To_Object (Long_Long_Integer (Id));
end if;
end To_Object;
-- ------------------------------
-- Build the identifier from the bean object.
-- ------------------------------
function To_Identifier (Value : in Util.Beans.Objects.Object) return ADO.Identifier is
begin
if Util.Beans.Objects.Is_Null (Value) then
return ADO.NO_IDENTIFIER;
else
return ADO.Identifier (Util.Beans.Objects.To_Long_Long_Integer (Value));
end if;
end To_Identifier;
end ADO.Utils;
|
Implement To_Identifier and To_Object operations
|
Implement To_Identifier and To_Object operations
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
|
d08319bd88bee12849710c4f1f0aeb3ea606e6ac
|
src/util-properties-bundles.ads
|
src/util-properties-bundles.ads
|
-----------------------------------------------------------------------
-- properties-bundles -- Generic name/value property management
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 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.Containers;
with Ada.Finalization;
with Ada.Containers.Hashed_Maps;
with Util.Strings;
with Util.Concurrent.Locks;
package Util.Properties.Bundles is
NO_BUNDLE : exception;
NOT_WRITEABLE : exception;
type Manager is new Util.Properties.Manager with private;
-- ------------------------------
-- Bundle loader
-- ------------------------------
-- The <b>Loader</b> provides facilities for loading property bundles
-- and maintains a cache of bundles. The cache is thread-safe but the returned
-- bundles are not thread-safe.
type Loader is limited private;
type Loader_Access is access all Loader;
-- Initialize the bundle factory and specify where the property files are stored.
procedure Initialize (Factory : in out Loader;
Path : in String);
-- Load the bundle with the given name and for the given locale name.
procedure Load_Bundle (Factory : in out Loader;
Name : in String;
Locale : in String;
Bundle : out Manager'Class);
private
procedure Add_Bundle (Self : in out Manager; Props : in Manager_Access);
-- Add a bundle
type Bundle_Manager_Access is access all Manager'Class;
type Manager is new Util.Properties.Manager with null record;
procedure Initialize (Object : in out Manager);
procedure Adjust (Object : in out Manager);
package Bundle_Map is
new Ada.Containers.Hashed_Maps
(Element_Type => Bundle_Manager_Access,
Key_Type => Util.Strings.Name_Access,
Hash => Util.Strings.Hash,
Equivalent_Keys => Util.Strings.Equivalent_Keys);
type Loader is new Ada.Finalization.Limited_Controlled with record
Lock : Util.Concurrent.Locks.RW_Lock;
Bundles : Bundle_Map.Map;
Path : Unbounded_String;
end record;
-- Finalize the bundle loader and clear the cache
procedure Finalize (Factory : in out Loader);
-- Clear the cache bundle
procedure Clear_Cache (Factory : in out Loader);
-- Find the bundle with the given name and for the given locale name.
procedure Find_Bundle (Factory : in out Loader;
Name : in String;
Locale : in String;
Bundle : out Manager'Class;
Found : out Boolean);
-- Load the bundle with the given name and for the given locale name.
procedure Load_Bundle (Factory : in out Loader;
Name : in String;
Found : out Boolean);
end Util.Properties.Bundles;
|
-----------------------------------------------------------------------
-- properties-bundles -- Generic name/value property management
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 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.Containers;
with Ada.Finalization;
with Ada.Containers.Hashed_Maps;
with Util.Strings;
with Util.Concurrent.Locks;
package Util.Properties.Bundles is
NO_BUNDLE : exception;
NOT_WRITEABLE : exception;
type Manager is new Util.Properties.Manager with private;
-- ------------------------------
-- Bundle loader
-- ------------------------------
-- The <b>Loader</b> provides facilities for loading property bundles
-- and maintains a cache of bundles. The cache is thread-safe but the returned
-- bundles are not thread-safe.
type Loader is limited private;
type Loader_Access is access all Loader;
-- Initialize the bundle factory and specify where the property files are stored.
procedure Initialize (Factory : in out Loader;
Path : in String);
-- Load the bundle with the given name and for the given locale name.
procedure Load_Bundle (Factory : in out Loader;
Name : in String;
Locale : in String;
Bundle : out Manager'Class);
private
procedure Add_Bundle (Self : in out Manager; Props : in Manager_Access);
-- Add a bundle
type Bundle_Manager_Access is access all Manager'Class;
type Manager is new Util.Properties.Manager with null record;
overriding
procedure Initialize (Object : in out Manager);
overriding
procedure Adjust (Object : in out Manager);
package Bundle_Map is
new Ada.Containers.Hashed_Maps
(Element_Type => Bundle_Manager_Access,
Key_Type => Util.Strings.Name_Access,
Hash => Util.Strings.Hash,
Equivalent_Keys => Util.Strings.Equivalent_Keys);
type Loader is new Ada.Finalization.Limited_Controlled with record
Lock : Util.Concurrent.Locks.RW_Lock;
Bundles : Bundle_Map.Map;
Path : Unbounded_String;
end record;
-- Finalize the bundle loader and clear the cache
overriding
procedure Finalize (Factory : in out Loader);
-- Clear the cache bundle
procedure Clear_Cache (Factory : in out Loader);
-- Find the bundle with the given name and for the given locale name.
procedure Find_Bundle (Factory : in out Loader;
Name : in String;
Locale : in String;
Bundle : out Manager'Class;
Found : out Boolean);
-- Load the bundle with the given name and for the given locale name.
procedure Load_Bundle (Factory : in out Loader;
Name : in String;
Found : out Boolean);
end Util.Properties.Bundles;
|
Add overriding keyword to several operations
|
Add overriding keyword to several operations
|
Ada
|
apache-2.0
|
Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util,Letractively/ada-util
|
fce2738c69d5ccb8f4ec6ee5f32a1de2042aaea1
|
src/util-properties-bundles.adb
|
src/util-properties-bundles.adb
|
-----------------------------------------------------------------------
-- properties -- Generic name/value property management
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 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.Unchecked_Deallocation;
with Ada.Unchecked_Conversion;
with Ada.Directories;
with Ada.Containers.Vectors;
with Ada.Strings.Fixed;
with Util.Log.Loggers;
with Util.Files;
with Util.Strings.Maps;
package body Util.Properties.Bundles is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Util.Properties.Bundles");
procedure Free is
new Ada.Unchecked_Deallocation (Manager'Class,
Bundle_Manager_Access);
-- Implementation of the Bundle
-- (this allows to decouples the implementation from the API)
package Interface_P is
type Manager is new Util.Properties.Interface_P.Manager with private;
type Manager_Object_Access is access all Manager;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager; Name : in Value)
return Boolean;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager; Name : in Value)
return Value;
procedure Insert (Self : in out Manager; Name : in Value;
Item : in Value);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager; Name : in Value;
Item : in Value);
-- Remove the property given its name.
procedure Remove (Self : in out Manager; Name : in Value);
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager;
Process : access procedure (Name, Item : Value));
procedure Load_Properties (Self : in out Manager;
File : in String);
-- Deep copy of properties stored in 'From' to 'To'.
function Create_Copy (Self : in Manager)
return Util.Properties.Interface_P.Manager_Access;
procedure Delete (Self : in Manager;
Obj : in out Util.Properties.Interface_P.Manager_Access);
function Get_Names (Self : in Manager;
Prefix : in String) return Name_Array;
procedure Add_Bundle (Self : in out Manager;
Props : in Util.Properties.Manager_Access);
private
use type Util.Properties.Manager_Access;
package PropertyList is new Ada.Containers.Vectors
(Element_Type => Util.Properties.Manager_Access,
Index_Type => Natural,
"=" => "=");
type Manager is new Util.Properties.Interface_P.Manager with record
List : PropertyList.Vector;
Props : aliased Util.Properties.Manager;
end record;
procedure Free is
new Ada.Unchecked_Deallocation (Manager,
Manager_Object_Access);
end Interface_P;
procedure Add_Bundle (Self : in out Manager;
Props : in Manager_Access) is
use type Util.Properties.Interface_P.Manager_Access;
begin
Interface_P.Manager'Class (Self.Impl.all).Add_Bundle (Props);
end Add_Bundle;
procedure Initialize (Object : in out Manager) is
use Util.Properties.Interface_P;
begin
Object.Impl := new Util.Properties.Bundles.Interface_P.Manager;
Object.Impl.Count := 1;
end Initialize;
procedure Adjust (Object : in out Manager) is
use Util.Properties.Interface_P;
begin
if Object.Impl /= null then
Object.Impl.Count := Object.Impl.Count + 1;
else
Object.Impl := new Util.Properties.Bundles.Interface_P.Manager;
Object.Impl.Count := 1;
end if;
end Adjust;
-- ------------------------------
-- Initialize the bundle factory and specify where the property files are stored.
-- ------------------------------
procedure Initialize (Factory : in out Loader;
Path : in String) is
begin
Log.Info ("Initialize bundle factory to load from {0}", Path);
Factory.Path := To_Unbounded_String (Path);
end Initialize;
-- ------------------------------
-- Load the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Load_Bundle (Factory : in out Loader;
Name : in String;
Locale : in String;
Bundle : out Manager'Class) is
Found : Boolean := False;
begin
Log.Info ("Load bundle {0} for language {1}", Name, Locale);
Find_Bundle (Factory, Name, Locale, Bundle, Found);
if not Found then
Load_Bundle (Factory, Name, Found);
if not Found then
Log.Error ("Bundle {0} not found", Name);
raise NO_BUNDLE with "No bundle '" & Name & "'";
end if;
Find_Bundle (Factory, Name, Locale, Bundle, Found);
if not Found then
Log.Error ("Bundle {0} not found", Name);
raise NO_BUNDLE with "No bundle '" & Name & "'";
end if;
end if;
end Load_Bundle;
-- ------------------------------
-- Find the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Find_Bundle (Factory : in out Loader;
Name : in String;
Locale : in String;
Bundle : out Manager'Class;
Found : out Boolean) is
use Ada.Strings;
use type Util.Properties.Manager_Access;
Loc_Name : constant String := '_' & Locale;
Last_Pos : Integer := Loc_Name'Last;
begin
Log.Info ("Looking for bundle {0} and language {1}", Name, Locale);
Found := False;
Factory.Lock.Read;
declare
Pos : Bundle_Map.Cursor;
begin
while Last_Pos + 1 >= Loc_Name'First loop
declare
Bundle_Name : aliased constant String
:= Name & Loc_Name (Loc_Name'First .. Last_Pos);
begin
Log.Debug ("Searching for {0}", Bundle_Name);
Pos := Factory.Bundles.Find (Bundle_Name'Unrestricted_Access);
if Bundle_Map.Has_Element (Pos) then
Bundle.Finalize;
Bundle.Impl := Bundle_Map.Element (Pos).Impl;
Bundle.Impl.Count := Bundle.Impl.Count + 1;
Found := True;
exit;
end if;
end;
if Last_Pos > Loc_Name'First then
Last_Pos := Fixed.Index (Loc_Name, "_", Last_Pos - 1, Backward) - 1;
else
Last_Pos := Last_Pos - 1;
end if;
end loop;
exception
when others =>
Factory.Lock.Release_Read;
raise;
end;
Factory.Lock.Release_Read;
end Find_Bundle;
-- ------------------------------
-- Load the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Load_Bundle (Factory : in out Loader;
Name : in String;
Found : out Boolean) is
use Ada.Directories;
use Ada.Strings;
use Util.Strings;
use Ada.Containers;
use Util.Strings.String_Set;
use Bundle_Map;
procedure Process_File (Name : in String;
File_Path : in String;
Done : out Boolean);
Path : constant String := To_String (Factory.Path);
Pattern : constant String := Name & "*.properties";
Names : Util.Strings.String_Set.Set;
procedure Process_File (Name : in String;
File_Path : in String;
Done : out Boolean) is
subtype Cursor is Bundle_Map.Cursor;
Base_Name : aliased constant String := Name (Name'First .. Name'Last - 11);
Pos : constant Cursor := Factory.Bundles.Find (Base_Name'Unchecked_Access);
Bundle_Name : Name_Access;
Bundle : Bundle_Manager_Access;
begin
Log.Debug ("Loading file {0}", File_Path);
if Bundle_Map.Has_Element (Pos) then
Bundle := Bundle_Map.Element (Pos);
else
Bundle := new Manager;
Bundle_Name := new String '(Base_Name);
Factory.Bundles.Include (Key => Bundle_Name, New_Item => Bundle);
Names.Insert (Bundle_Name);
end if;
Interface_P.Manager'Class (Bundle.Impl.all).Load_Properties (File_Path);
Found := True;
Done := False;
end Process_File;
begin
Log.Info ("Reading bundle {1} in directory {0}", Path, Name);
Found := False;
Factory.Lock.Write;
begin
Util.Files.Iterate_Files_Path (Pattern => Pattern,
Path => Path,
Process => Process_File'Access,
Going => Ada.Strings.Backward);
-- Link the property files to implement the localization default rules.
while Names.Length > 0 loop
declare
Name_Pos : String_Set.Cursor := Names.First;
Bundle_Name : constant Name_Access := String_Set.Element (Name_Pos);
Idx : Natural := Fixed.Index (Bundle_Name.all, "_", Backward);
Bundle_Pos : constant Bundle_Map.Cursor := Factory.Bundles.Find (Bundle_Name);
Bundle : constant Bundle_Manager_Access := Element (Bundle_Pos);
begin
Names.Delete (Name_Pos);
-- Associate the property bundle to the first existing parent
-- Ex: message_fr_CA -> message_fr
-- message_fr_CA -> message
while Idx > 0 loop
declare
Name : aliased constant String
:= Bundle_Name (Bundle_Name'First .. Idx - 1);
Pos : constant Bundle_Map.Cursor
:= Factory.Bundles.Find (Name'Unchecked_Access);
begin
if Bundle_Map.Has_Element (Pos) then
Bundle.Add_Bundle (Bundle_Map.Element (Pos).all'Access);
Idx := 0;
else
Idx := Fixed.Index (Bundle_Name.all, "_", Idx - 1, Backward);
end if;
end;
end loop;
end;
end loop;
exception
when others =>
Factory.Lock.Release_Write;
raise;
end;
Factory.Lock.Release_Write;
exception
when Name_Error =>
Log.Error ("Cannot read directory: {0}", Path);
end Load_Bundle;
-- Implementation of the Bundle
-- (this allows to decouples the implementation from the API)
package body Interface_P is
use PropertyList;
-- ------------------------------
-- Returns TRUE if the property exists.
-- ------------------------------
function Exists (Self : in Manager; Name : in Value)
return Boolean is
Iter : Cursor := Self.List.First;
begin
if Self.Props.Exists (Name) then
return True;
end if;
while Has_Element (Iter) loop
if Element (Iter).Exists (Name) then
return True;
end if;
Iter := Next (Iter);
end loop;
return False;
end Exists;
-- ------------------------------
-- Returns the property value. Raises an exception if not found.
-- ------------------------------
function Get (Self : in Manager; Name : in Value)
return Value is
begin
return Self.Props.Get (Name);
exception
when NO_PROPERTY =>
declare
Iter : Cursor := Self.List.First;
begin
while Has_Element (Iter) loop
begin
return Element (Iter).all.Get (Name);
exception
when NO_PROPERTY =>
Iter := Next (Iter);
end;
end loop;
end;
raise;
end Get;
procedure Load_Properties (Self : in out Manager;
File : in String) is
begin
Self.Props.Load_Properties (File);
end Load_Properties;
procedure Insert (Self : in out Manager;
Name : in Value;
Item : in Value) is
pragma Unreferenced (Self);
pragma Unreferenced (Name);
pragma Unreferenced (Item);
begin
raise NOT_WRITEABLE with "Bundle is readonly";
end Insert;
-- ------------------------------
-- Set the value of the property. The property is created if it
-- does not exists.
-- ------------------------------
procedure Set (Self : in out Manager;
Name : in Value;
Item : in Value) is
begin
raise NOT_WRITEABLE with "Bundle is readonly";
end Set;
-- ------------------------------
-- Remove the property given its name.
-- ------------------------------
procedure Remove (Self : in out Manager; Name : in Value) is
begin
raise NOT_WRITEABLE with "Bundle is readonly";
end Remove;
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager;
Process : access procedure (Name, Item : Value)) is
begin
raise Program_Error with "Iterate is not implemented on Bundle";
end Iterate;
-- ------------------------------
-- Deep copy of properties stored in 'From' to 'To'.
-- ------------------------------
function Create_Copy (Self : in Manager)
return Util.Properties.Interface_P.Manager_Access is
pragma Unreferenced (Self);
begin
return null;
end Create_Copy;
procedure Delete (Self : in Manager;
Obj : in out Util.Properties.Interface_P.Manager_Access) is
pragma Unreferenced (Self);
Item : Manager_Object_Access := Manager (Obj.all)'Access;
begin
Free (Item);
end Delete;
function Get_Names (Self : in Manager;
Prefix : in String) return Name_Array is
Result : Name_Array (1 .. 2);
Iter : constant Cursor := Self.List.First;
begin
while Has_Element (Iter) loop
declare
M : constant Util.Properties.Manager_Access := Element (Iter);
N : constant Name_Array := M.Get_Names (Prefix);
begin
return N;
end;
end loop;
return Result;
end Get_Names;
procedure Add_Bundle (Self : in out Manager;
Props : in Util.Properties.Manager_Access) is
begin
Self.List.Append (Props);
end Add_Bundle;
end Interface_P;
-- ------------------------------
-- Clear the bundle cache
-- ------------------------------
procedure Clear_Cache (Factory : in out Loader) is
use Util.Strings;
use Bundle_Map;
function To_String_Access is
new Ada.Unchecked_Conversion (Source => Util.Strings.Name_Access,
Target => Ada.Strings.Unbounded.String_Access);
begin
Log.Info ("Clearing bundle cache");
Factory.Lock.Write;
loop
declare
Pos : Bundle_Map.Cursor := Factory.Bundles.First;
Name : Ada.Strings.Unbounded.String_Access;
Node : Bundle_Manager_Access;
begin
exit when not Has_Element (Pos);
Node := Element (Pos);
Name := To_String_Access (Key (Pos));
Factory.Bundles.Delete (Pos);
Free (Node);
Free (Name);
end;
end loop;
Factory.Lock.Release_Write;
end Clear_Cache;
-- ------------------------------
-- Finalize the bundle loader and clear the cache
-- ------------------------------
procedure Finalize (Factory : in out Loader) is
begin
Clear_Cache (Factory);
end Finalize;
end Util.Properties.Bundles;
|
-----------------------------------------------------------------------
-- properties -- Generic name/value property management
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2011, 2012, 2013, 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.Unchecked_Deallocation;
with Ada.Unchecked_Conversion;
with Ada.Directories;
with Ada.Containers.Vectors;
with Ada.Strings.Fixed;
with Util.Log.Loggers;
with Util.Files;
package body Util.Properties.Bundles is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Properties.Bundles");
procedure Free is
new Ada.Unchecked_Deallocation (Manager'Class,
Bundle_Manager_Access);
-- Implementation of the Bundle
-- (this allows to decouples the implementation from the API)
package Interface_P is
type Manager is new Util.Properties.Interface_P.Manager with private;
type Manager_Object_Access is access all Manager;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager; Name : in Value)
return Boolean;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager; Name : in Value)
return Value;
procedure Insert (Self : in out Manager; Name : in Value;
Item : in Value);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager; Name : in Value;
Item : in Value);
-- Remove the property given its name.
procedure Remove (Self : in out Manager; Name : in Value);
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager;
Process : access procedure (Name, Item : Value));
procedure Load_Properties (Self : in out Manager;
File : in String);
-- Deep copy of properties stored in 'From' to 'To'.
function Create_Copy (Self : in Manager)
return Util.Properties.Interface_P.Manager_Access;
procedure Delete (Self : in Manager;
Obj : in out Util.Properties.Interface_P.Manager_Access);
function Get_Names (Self : in Manager;
Prefix : in String) return Name_Array;
procedure Add_Bundle (Self : in out Manager;
Props : in Util.Properties.Manager_Access);
private
use type Util.Properties.Manager_Access;
package PropertyList is new Ada.Containers.Vectors
(Element_Type => Util.Properties.Manager_Access,
Index_Type => Natural,
"=" => "=");
type Manager is new Util.Properties.Interface_P.Manager with record
List : PropertyList.Vector;
Props : aliased Util.Properties.Manager;
end record;
procedure Free is
new Ada.Unchecked_Deallocation (Manager,
Manager_Object_Access);
end Interface_P;
procedure Add_Bundle (Self : in out Manager;
Props : in Manager_Access) is
use type Util.Properties.Interface_P.Manager_Access;
begin
Interface_P.Manager'Class (Self.Impl.all).Add_Bundle (Props);
end Add_Bundle;
procedure Initialize (Object : in out Manager) is
use Util.Properties.Interface_P;
begin
Object.Impl := new Util.Properties.Bundles.Interface_P.Manager;
Object.Impl.Count := 1;
end Initialize;
procedure Adjust (Object : in out Manager) is
use Util.Properties.Interface_P;
begin
if Object.Impl /= null then
Object.Impl.Count := Object.Impl.Count + 1;
else
Object.Impl := new Util.Properties.Bundles.Interface_P.Manager;
Object.Impl.Count := 1;
end if;
end Adjust;
-- ------------------------------
-- Initialize the bundle factory and specify where the property files are stored.
-- ------------------------------
procedure Initialize (Factory : in out Loader;
Path : in String) is
begin
Log.Info ("Initialize bundle factory to load from {0}", Path);
Factory.Path := To_Unbounded_String (Path);
end Initialize;
-- ------------------------------
-- Load the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Load_Bundle (Factory : in out Loader;
Name : in String;
Locale : in String;
Bundle : out Manager'Class) is
Found : Boolean := False;
begin
Log.Info ("Load bundle {0} for language {1}", Name, Locale);
Find_Bundle (Factory, Name, Locale, Bundle, Found);
if not Found then
Load_Bundle (Factory, Name, Found);
if not Found then
Log.Error ("Bundle {0} not found", Name);
raise NO_BUNDLE with "No bundle '" & Name & "'";
end if;
Find_Bundle (Factory, Name, Locale, Bundle, Found);
if not Found then
Log.Error ("Bundle {0} not found", Name);
raise NO_BUNDLE with "No bundle '" & Name & "'";
end if;
end if;
end Load_Bundle;
-- ------------------------------
-- Find the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Find_Bundle (Factory : in out Loader;
Name : in String;
Locale : in String;
Bundle : out Manager'Class;
Found : out Boolean) is
use Ada.Strings;
use type Util.Properties.Manager_Access;
Loc_Name : constant String := '_' & Locale;
Last_Pos : Integer := Loc_Name'Last;
begin
Log.Info ("Looking for bundle {0} and language {1}", Name, Locale);
Found := False;
Factory.Lock.Read;
declare
Pos : Bundle_Map.Cursor;
begin
while Last_Pos + 1 >= Loc_Name'First loop
declare
Bundle_Name : aliased constant String
:= Name & Loc_Name (Loc_Name'First .. Last_Pos);
begin
Log.Debug ("Searching for {0}", Bundle_Name);
Pos := Factory.Bundles.Find (Bundle_Name'Unrestricted_Access);
if Bundle_Map.Has_Element (Pos) then
Bundle.Finalize;
Bundle.Impl := Bundle_Map.Element (Pos).Impl;
Bundle.Impl.Count := Bundle.Impl.Count + 1;
Found := True;
exit;
end if;
end;
if Last_Pos > Loc_Name'First then
Last_Pos := Fixed.Index (Loc_Name, "_", Last_Pos - 1, Backward) - 1;
else
Last_Pos := Last_Pos - 1;
end if;
end loop;
exception
when others =>
Factory.Lock.Release_Read;
raise;
end;
Factory.Lock.Release_Read;
end Find_Bundle;
-- ------------------------------
-- Load the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Load_Bundle (Factory : in out Loader;
Name : in String;
Found : out Boolean) is
use Ada.Directories;
use Ada.Strings;
use Util.Strings;
use Ada.Containers;
use Util.Strings.String_Set;
use Bundle_Map;
procedure Process_File (Name : in String;
File_Path : in String;
Done : out Boolean);
Path : constant String := To_String (Factory.Path);
Pattern : constant String := Name & "*.properties";
Names : Util.Strings.String_Set.Set;
procedure Process_File (Name : in String;
File_Path : in String;
Done : out Boolean) is
subtype Cursor is Bundle_Map.Cursor;
Base_Name : aliased constant String := Name (Name'First .. Name'Last - 11);
Pos : constant Cursor := Factory.Bundles.Find (Base_Name'Unchecked_Access);
Bundle_Name : Name_Access;
Bundle : Bundle_Manager_Access;
begin
Log.Debug ("Loading file {0}", File_Path);
if Bundle_Map.Has_Element (Pos) then
Bundle := Bundle_Map.Element (Pos);
else
Bundle := new Manager;
Bundle_Name := new String '(Base_Name);
Factory.Bundles.Include (Key => Bundle_Name, New_Item => Bundle);
Names.Insert (Bundle_Name);
end if;
Interface_P.Manager'Class (Bundle.Impl.all).Load_Properties (File_Path);
Found := True;
Done := False;
end Process_File;
begin
Log.Info ("Reading bundle {1} in directory {0}", Path, Name);
Found := False;
Factory.Lock.Write;
begin
Util.Files.Iterate_Files_Path (Pattern => Pattern,
Path => Path,
Process => Process_File'Access,
Going => Ada.Strings.Backward);
-- Link the property files to implement the localization default rules.
while Names.Length > 0 loop
declare
Name_Pos : String_Set.Cursor := Names.First;
Bundle_Name : constant Name_Access := String_Set.Element (Name_Pos);
Idx : Natural := Fixed.Index (Bundle_Name.all, "_", Backward);
Bundle_Pos : constant Bundle_Map.Cursor := Factory.Bundles.Find (Bundle_Name);
Bundle : constant Bundle_Manager_Access := Element (Bundle_Pos);
begin
Names.Delete (Name_Pos);
-- Associate the property bundle to the first existing parent
-- Ex: message_fr_CA -> message_fr
-- message_fr_CA -> message
while Idx > 0 loop
declare
Name : aliased constant String
:= Bundle_Name (Bundle_Name'First .. Idx - 1);
Pos : constant Bundle_Map.Cursor
:= Factory.Bundles.Find (Name'Unchecked_Access);
begin
if Bundle_Map.Has_Element (Pos) then
Bundle.Add_Bundle (Bundle_Map.Element (Pos).all'Access);
Idx := 0;
else
Idx := Fixed.Index (Bundle_Name.all, "_", Idx - 1, Backward);
end if;
end;
end loop;
end;
end loop;
exception
when others =>
Factory.Lock.Release_Write;
raise;
end;
Factory.Lock.Release_Write;
exception
when Name_Error =>
Log.Error ("Cannot read directory: {0}", Path);
end Load_Bundle;
-- Implementation of the Bundle
-- (this allows to decouples the implementation from the API)
package body Interface_P is
use PropertyList;
-- ------------------------------
-- Returns TRUE if the property exists.
-- ------------------------------
function Exists (Self : in Manager; Name : in Value)
return Boolean is
Iter : Cursor := Self.List.First;
begin
if Self.Props.Exists (Name) then
return True;
end if;
while Has_Element (Iter) loop
if Element (Iter).Exists (Name) then
return True;
end if;
Iter := Next (Iter);
end loop;
return False;
end Exists;
-- ------------------------------
-- Returns the property value. Raises an exception if not found.
-- ------------------------------
function Get (Self : in Manager; Name : in Value)
return Value is
begin
return Self.Props.Get (Name);
exception
when NO_PROPERTY =>
declare
Iter : Cursor := Self.List.First;
begin
while Has_Element (Iter) loop
begin
return Element (Iter).all.Get (Name);
exception
when NO_PROPERTY =>
Iter := Next (Iter);
end;
end loop;
end;
raise;
end Get;
procedure Load_Properties (Self : in out Manager;
File : in String) is
begin
Self.Props.Load_Properties (File);
end Load_Properties;
procedure Insert (Self : in out Manager;
Name : in Value;
Item : in Value) is
pragma Unreferenced (Self);
pragma Unreferenced (Name);
pragma Unreferenced (Item);
begin
raise NOT_WRITEABLE with "Bundle is readonly";
end Insert;
-- ------------------------------
-- Set the value of the property. The property is created if it
-- does not exists.
-- ------------------------------
procedure Set (Self : in out Manager;
Name : in Value;
Item : in Value) is
begin
raise NOT_WRITEABLE with "Bundle is readonly";
end Set;
-- ------------------------------
-- Remove the property given its name.
-- ------------------------------
procedure Remove (Self : in out Manager; Name : in Value) is
begin
raise NOT_WRITEABLE with "Bundle is readonly";
end Remove;
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager;
Process : access procedure (Name, Item : Value)) is
begin
raise Program_Error with "Iterate is not implemented on Bundle";
end Iterate;
-- ------------------------------
-- Deep copy of properties stored in 'From' to 'To'.
-- ------------------------------
function Create_Copy (Self : in Manager)
return Util.Properties.Interface_P.Manager_Access is
pragma Unreferenced (Self);
begin
return null;
end Create_Copy;
procedure Delete (Self : in Manager;
Obj : in out Util.Properties.Interface_P.Manager_Access) is
pragma Unreferenced (Self);
Item : Manager_Object_Access := Manager (Obj.all)'Access;
begin
Free (Item);
end Delete;
function Get_Names (Self : in Manager;
Prefix : in String) return Name_Array is
Result : Name_Array (1 .. 2);
Iter : constant Cursor := Self.List.First;
begin
while Has_Element (Iter) loop
declare
M : constant Util.Properties.Manager_Access := Element (Iter);
N : constant Name_Array := M.Get_Names (Prefix);
begin
return N;
end;
end loop;
return Result;
end Get_Names;
procedure Add_Bundle (Self : in out Manager;
Props : in Util.Properties.Manager_Access) is
begin
Self.List.Append (Props);
end Add_Bundle;
end Interface_P;
-- ------------------------------
-- Clear the bundle cache
-- ------------------------------
procedure Clear_Cache (Factory : in out Loader) is
use Util.Strings;
use Bundle_Map;
function To_String_Access is
new Ada.Unchecked_Conversion (Source => Util.Strings.Name_Access,
Target => Ada.Strings.Unbounded.String_Access);
begin
Log.Info ("Clearing bundle cache");
Factory.Lock.Write;
loop
declare
Pos : Bundle_Map.Cursor := Factory.Bundles.First;
Name : Ada.Strings.Unbounded.String_Access;
Node : Bundle_Manager_Access;
begin
exit when not Has_Element (Pos);
Node := Element (Pos);
Name := To_String_Access (Key (Pos));
Factory.Bundles.Delete (Pos);
Free (Node);
Free (Name);
end;
end loop;
Factory.Lock.Release_Write;
end Clear_Cache;
-- ------------------------------
-- Finalize the bundle loader and clear the cache
-- ------------------------------
procedure Finalize (Factory : in out Loader) is
begin
Clear_Cache (Factory);
end Finalize;
end Util.Properties.Bundles;
|
Remove unused with package
|
Remove unused with package
|
Ada
|
apache-2.0
|
Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util
|
7fab750eecd0897e0a55bcedf03b94d62a192e7c
|
src/asf-components-widgets-selects.adb
|
src/asf-components-widgets-selects.adb
|
-----------------------------------------------------------------------
-- components-widgets-selects -- Select component with jQuery Chosen
-- 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 ASF.Contexts.Writer;
with ASF.Components.Base;
package body ASF.Components.Widgets.Selects is
-- ------------------------------
-- Render the chosen configuration script.
-- ------------------------------
overriding
procedure Encode_End (UI : in UIChosen;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
use type ASF.Components.Base.UIComponent_Access;
procedure Process (Content : in String);
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
Facets : ASF.Components.Base.UIComponent_Access;
procedure Process (Content : in String) is
begin
Writer.Queue_Script (Content);
end Process;
begin
if not UI.Is_Rendered (Context) then
return;
end if;
Writer.Queue_Script ("$('#");
Writer.Queue_Script (UI.Get_Client_Id);
Writer.Queue_Script ("').chosen({");
-- If there is an options facet, render it now.
Facets := UI.Get_Facet (OPTIONS_FACET_NAME);
if Facets /= null then
Facets.Wrap_Encode_Children (Context, Process'Access);
end if;
Writer.Queue_Script ("})");
Facets := UI.Get_Facet (EVENTS_FACET_NAME);
if Facets /= null then
Facets.Wrap_Encode_Children (Context, Process'Access);
end if;
Writer.Queue_Script (";");
end Encode_End;
end ASF.Components.Widgets.Selects;
|
Implement the UIChosen support to generate the jQuery chosen activation script
|
Implement the UIChosen support to generate the jQuery chosen activation script
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
|
07cee2180a9d28f73a7ade9f55090772edab22f5
|
src/util-refs.ads
|
src/util-refs.ads
|
-----------------------------------------------------------------------
-- util-refs -- Reference Counting
-- 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.Finalization;
with Util.Concurrent.Counters;
-- The <b>Util.Refs</b> package provides support to implement object reference counting.
--
-- The data type to share through reference counting has to inherit from <b>Ref_Entity</b>
-- and the generic package <b>References</b> has to be instantiated.
-- <pre>
-- type Data is new Util.Refs.Ref_Entity with record ... end record;
-- type Data_Access is access all Data;
--
-- package Data_Ref is new Utils.Refs.References (Data, Data_Access);
-- </pre>
--
-- The reference is used as follows:
--
-- <pre>
-- D : Data_Ref.Ref := Data_Ref.Create; -- Allocate and get a reference
-- D2 : Data_Ref.Ref := D; -- Share reference
-- D.Value.all.XXXX := 0; -- Set data member XXXX
-- </pre>
--
-- When a reference is shared in a multi-threaded environment, the reference has to
-- be protected by using the <b>References.Atomic_Ref</b> type.
--
-- R : Data_Ref.Atomic_Ref;
--
-- The reference is then obtained by the protected operation <b>Get</b>.
--
-- D : Data_Ref.Ref := R.Get;
--
package Util.Refs is
-- Root of referenced objects.
type Ref_Entity is abstract tagged limited private;
-- Finalize the referenced object. This is called before the object is freed.
procedure Finalize (Object : in out Ref_Entity) is null;
generic
type Element_Type (<>) is new Ref_Entity with private;
type Element_Access is access all Element_Type;
package Indefinite_References is
type Ref is new Ada.Finalization.Controlled with private;
-- Create an element and return a reference to that element.
function Create (Value : in Element_Access) return Ref;
-- Get the element access value.
function Value (Object : in Ref'Class) return Element_Access;
pragma Inline_Always (Value);
-- Returns true if the reference does not contain any element.
function Is_Null (Object : in Ref'Class) return Boolean;
pragma Inline_Always (Is_Null);
-- The <b>Atomic_Ref</b> protected type defines a reference to an
-- element which can be obtained and changed atomically. The default
-- Ada construct:
--
-- Ref1 := Ref2;
--
-- does not guarantee atomicity of the copy (assignment) and the increment
-- of the reference counter (Adjust operation). To replace shared reference
-- by another one, the whole assignment and Adjust have to be protected.
-- This is achieved by this protected type through the <b>Get</b> and <b>Set</b>
protected type Atomic_Ref is
-- Get the reference
function Get return Ref;
-- Change the reference
procedure Set (Object : in Ref);
private
Value : Ref;
end Atomic_Ref;
private
type Ref is new Ada.Finalization.Controlled with record
Target : Element_Access := null;
end record;
-- Release the reference. Invoke <b>Finalize</b> and free the storage if it was
-- the last reference.
overriding
procedure Finalize (Obj : in out Ref);
-- Update the reference counter after an assignment.
overriding
procedure Adjust (Obj : in out Ref);
end Indefinite_References;
generic
type Element_Type is new Ref_Entity with private;
type Element_Access is access all Element_Type;
package References is
package IR is new Indefinite_References (Element_Type, Element_Access);
subtype Ref is IR.Ref;
-- Create an element and return a reference to that element.
function Create return Ref;
-- Get the element access value.
function Value (Object : in Ref'Class) return Element_Access
renames IR.Value;
-- Returns true if the reference does not contain any element.
function Is_Null (Object : in Ref'Class) return Boolean
renames IR.Is_Null;
-- The <b>Atomic_Ref</b> protected type defines a reference to an
-- element which can be obtained and changed atomically. The default
-- Ada construct:
--
-- Ref1 := Ref2;
--
-- does not guarantee atomicity of the copy (assignment) and the increment
-- of the reference counter (Adjust operation). To replace shared reference
-- by another one, the whole assignment and Adjust have to be protected.
-- This is achieved by this protected type through the <b>Get</b> and <b>Set</b>
subtype Atomic_Ref is IR.Atomic_Ref;
end References;
private
type Ref_Entity is abstract tagged limited record
Ref_Counter : Util.Concurrent.Counters.Counter;
end record;
end Util.Refs;
|
-----------------------------------------------------------------------
-- util-refs -- Reference Counting
-- 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.Finalization;
with Util.Concurrent.Counters;
-- The <b>Util.Refs</b> package provides support to implement object reference counting.
--
-- The data type to share through reference counting has to inherit from <b>Ref_Entity</b>
-- and the generic package <b>References</b> has to be instantiated.
-- <pre>
-- type Data is new Util.Refs.Ref_Entity with record ... end record;
-- type Data_Access is access all Data;
--
-- package Data_Ref is new Utils.Refs.References (Data, Data_Access);
-- </pre>
--
-- The reference is used as follows:
--
-- <pre>
-- D : Data_Ref.Ref := Data_Ref.Create; -- Allocate and get a reference
-- D2 : Data_Ref.Ref := D; -- Share reference
-- D.Value.all.XXXX := 0; -- Set data member XXXX
-- </pre>
--
-- When a reference is shared in a multi-threaded environment, the reference has to
-- be protected by using the <b>References.Atomic_Ref</b> type.
--
-- R : Data_Ref.Atomic_Ref;
--
-- The reference is then obtained by the protected operation <b>Get</b>.
--
-- D : Data_Ref.Ref := R.Get;
--
package Util.Refs is
-- Root of referenced objects.
type Ref_Entity is abstract tagged limited private;
-- Finalize the referenced object. This is called before the object is freed.
procedure Finalize (Object : in out Ref_Entity) is null;
generic
type Element_Type (<>) is new Ref_Entity with private;
type Element_Access is access all Element_Type;
package Indefinite_References is
type Ref is new Ada.Finalization.Controlled with private;
-- Create an element and return a reference to that element.
function Create (Value : in Element_Access) return Ref;
-- Get the element access value.
function Value (Object : in Ref'Class) return Element_Access;
pragma Inline_Always (Value);
-- Returns true if the reference does not contain any element.
function Is_Null (Object : in Ref'Class) return Boolean;
pragma Inline_Always (Is_Null);
-- The <b>Atomic_Ref</b> protected type defines a reference to an
-- element which can be obtained and changed atomically. The default
-- Ada construct:
--
-- Ref1 := Ref2;
--
-- does not guarantee atomicity of the copy (assignment) and the increment
-- of the reference counter (Adjust operation). To replace shared reference
-- by another one, the whole assignment and Adjust have to be protected.
-- This is achieved by this protected type through the <b>Get</b> and <b>Set</b>
protected type Atomic_Ref is
-- Get the reference
function Get return Ref;
-- Change the reference
procedure Set (Object : in Ref);
private
Value : Ref;
end Atomic_Ref;
private
type Ref is new Ada.Finalization.Controlled with record
Target : Element_Access := null;
end record;
-- Release the reference. Invoke <b>Finalize</b> and free the storage if it was
-- the last reference.
overriding
procedure Finalize (Obj : in out Ref);
-- Update the reference counter after an assignment.
overriding
procedure Adjust (Obj : in out Ref);
end Indefinite_References;
generic
type Element_Type is new Ref_Entity with private;
type Element_Access is access all Element_Type;
package References is
package IR is new Indefinite_References (Element_Type, Element_Access);
subtype Ref is IR.Ref;
-- Create an element and return a reference to that element.
function Create return Ref;
-- The <b>Atomic_Ref</b> protected type defines a reference to an
-- element which can be obtained and changed atomically. The default
-- Ada construct:
--
-- Ref1 := Ref2;
--
-- does not guarantee atomicity of the copy (assignment) and the increment
-- of the reference counter (Adjust operation). To replace shared reference
-- by another one, the whole assignment and Adjust have to be protected.
-- This is achieved by this protected type through the <b>Get</b> and <b>Set</b>
subtype Atomic_Ref is IR.Atomic_Ref;
end References;
private
type Ref_Entity is abstract tagged limited record
Ref_Counter : Util.Concurrent.Counters.Counter;
end record;
end Util.Refs;
|
Remove some renames which are not necessary
|
Remove some renames which are not necessary
|
Ada
|
apache-2.0
|
Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util
|
4cafc3f342818a08578e3c1348067c3e882ebf76
|
awa/plugins/awa-images/src/awa-images-beans.adb
|
awa/plugins/awa-images/src/awa-images-beans.adb
|
-----------------------------------------------------------------------
-- awa-images-beans -- Image Ada Beans
-- 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 ADO.Queries;
with ADO.Sessions;
with ADO.Objects;
with ADO.Sessions.Entities;
with AWA.Workspaces.Models;
with AWA.Services.Contexts;
with AWA.Storages.Modules;
package body AWA.Images.Beans is
-- ------------------------------
-- Load the list of images associated with the current folder.
-- ------------------------------
overriding
procedure Load_Files (Storage : in Image_List_Bean) is
use AWA.Services;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := Storage.Module.Get_Session;
Query : ADO.Queries.Context;
begin
if not Storage.Init_Flags (AWA.Storages.Beans.INIT_FOLDER) then
Load_Folder (Storage);
end if;
Query.Set_Query (AWA.Images.Models.Query_Image_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, Session);
if Storage.Folder_Bean.Is_Null then
Query.Bind_Null_Param ("folder_id");
else
Query.Bind_Param ("folder_id", Storage.Folder_Bean.Get_Id);
end if;
AWA.Images.Models.List (Storage.Image_List_Bean.all, Session, Query);
Storage.Flags (AWA.Storages.Beans.INIT_FILE_LIST) := True;
end Load_Files;
overriding
function Get_Value (List : in Image_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "images" then
return Util.Beans.Objects.To_Object (Value => List.Image_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "folders" then
return Util.Beans.Objects.To_Object (Value => List.Folder_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "folder" then
-- if not List.Init_Flags (INIT_FOLDER) then
-- Load_Folder (List);
-- end if;
if List.Folder_Bean.Is_Null then
return Util.Beans.Objects.Null_Object;
end if;
return Util.Beans.Objects.To_Object (Value => List.Folder_Bean,
Storage => Util.Beans.Objects.STATIC);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Create the Image_List_Bean bean instance.
-- ------------------------------
function Create_Image_List_Bean (Module : in AWA.Images.Modules.Image_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
pragma Unreferenced (Module);
Object : constant Image_List_Bean_Access := new Image_List_Bean;
begin
Object.Module := AWA.Storages.Modules.Get_Storage_Module;
Object.Folder_Bean := Object.Folder'Access;
Object.Folder_List_Bean := Object.Folder_List'Access;
Object.Files_List_Bean := Object.Files_List'Access;
Object.Image_List_Bean := Object.Image_List'Access;
Object.Flags := Object.Init_Flags'Access;
return Object.all'Access;
end Create_Image_List_Bean;
end AWA.Images.Beans;
|
Implement the AWA.Images.Beans package with the Load_Files procedure
|
Implement the AWA.Images.Beans package with the Load_Files procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
|
7bf39aa32ee428ed6636ec8a1ac25b0aa6bb4fa8
|
awa/src/awa-oauth-services.ads
|
awa/src/awa-oauth-services.ads
|
-----------------------------------------------------------------------
-- awa-oauth-services -- OAuth Server Side
-- 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 Security.OAuth.Servers;
package AWA.OAuth.Services is
type Auth_Manager is new Security.OAuth.Servers.Auth_Manager with private;
type Auth_Manager_Access is access all Auth_Manager'Class;
private
type Auth_Manager is new Security.OAuth.Servers.Auth_Manager with record
N : Natural;
end record;
end AWA.OAuth.Services;
|
Declare the AWA.OAuth.Services package with the Auth_Manager
|
Declare the AWA.OAuth.Services package with the Auth_Manager
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
|
ddac499fa7a2792cac94b61520f5bca537781236
|
src/asis/a4g-queries.ads
|
src/asis/a4g-queries.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . Q U E R I E S --
-- --
-- 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.adaccore.com). --
-- --
-- The original version of this component has been developed by Jean-Charles--
-- Marteau ([email protected]) and Serge Reboul --
-- ([email protected]), ENSIMAG High School Graduates (Computer --
-- sciences) Grenoble, France in Sema Group Grenoble, France. Now this --
-- component is maintained by the ASIS team --
-- --
------------------------------------------------------------------------------
with Asis; use Asis;
----------------------------------------------------------
-- The goal of this package is, when we have an element --
-- to let us have ALL the possible queries for that --
-- element that return its children. --
----------------------------------------------------------
package A4G.Queries is
-- There is 3 kinds of queries in Asis :
type Query_Kinds is
(Bug,
-- just for the discriminant default expression
Single_Element_Query,
-- Queries taking an element and returning an element.
Element_List_Query,
-- Queries taking an element and returning a list of elements.
Element_List_Query_With_Boolean
-- Queries taking an element and a boolean and returning a list
-- of elements.
);
type A_Single_Element_Query is access
function (Elem : Asis.Element) return Asis.Element;
type A_Element_List_Query is access
function (Elem : Asis.Element) return Asis.Element_List;
type A_Element_List_Query_With_Boolean is access
function
(Elem : Asis.Element;
Bool : Boolean)
return Asis.Element_List;
-- Discriminant record that can access any type of query.
type Func_Elem (Query_Kind : Query_Kinds := Bug) is record
case Query_Kind is
when Bug =>
null;
when Single_Element_Query =>
Func_Simple : A_Single_Element_Query;
when Element_List_Query =>
Func_List : A_Element_List_Query;
when Element_List_Query_With_Boolean =>
Func_List_Boolean : A_Element_List_Query_With_Boolean;
Bool : Boolean;
end case;
end record;
type Query_Array is array (Positive range <>) of Func_Elem;
-- an empty array, when the element is a terminal
No_Query : Query_Array (1 .. 0);
----------------------------------------------------
-- This function returns a Query_Array containing --
-- all the existing queries for that element. --
-- If an element has no children, No_Query is --
-- returned. --
----------------------------------------------------
function Appropriate_Queries (Element : Asis.Element) return Query_Array;
end A4G.Queries;
|
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
|
|
e91ebec06bf858ee75cac5ccd264f2a9369d502c
|
rts/boards/i386/adainclude/last_chance_handler.ads
|
rts/boards/i386/adainclude/last_chance_handler.ads
|
-- -*- Mode: Ada -*-
-- Filename : last_chance_handler.ads
-- Description : Definition of the exception handler for the kernel.
-- Author : Luke A. Guest
-- Created On : Thu Jun 14 12:06:21 2012
-- Licence : See LICENCE in the root directory.
with System;
procedure Last_Chance_Handler
(Source_Location : System.Address; Line : Integer);
pragma Export (C, Last_Chance_Handler, "__gnat_last_chance_handler");
|
-- -*- Mode: Ada -*-
-- Filename : last_chance_handler.ads
-- Description : Definition of the exception handler for the kernel.
-- Author : Luke A. Guest
-- Created On : Thu Jun 14 12:06:21 2012
-- Licence : See LICENCE in the root directory.
with System;
procedure Last_Chance_Handler
(Source_Location : System.Address; Line : Integer);
pragma Export (C, Last_Chance_Handler, "__gnat_last_chance_handler");
pragma Preelaborate (Last_Chance_Handler);
|
Make this package Preelaborate so a-except can depend on it.
|
Make this package Preelaborate so a-except can depend on it.
|
Ada
|
bsd-2-clause
|
Lucretia/tamp2,Lucretia/bare_bones,robdaemon/bare_bones
|
0016f157639026a64feda2aa716041301d3c6f94
|
tools/druss-config.adb
|
tools/druss-config.adb
|
-----------------------------------------------------------------------
-- druss-config -- Configuration management for Druss
-- 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.Environment_Variables;
with Ada.Directories;
with Util.Files;
package body Druss.Config is
Cfg : Util.Properties.Manager;
-- ------------------------------
-- Initialize the configuration.
-- ------------------------------
procedure Initialize is
Home : constant String := Ada.Environment_Variables.Value ("HOME");
Path : constant String := Util.Files.Compose (Home, ".config/druss/druss.properties");
begin
if Ada.Directories.Exists (Path) then
Cfg.Load_Properties (Path);
end if;
end Initialize;
-- ------------------------------
-- Get the configuration parameter.
-- ------------------------------
function Get (Name : in String) return String is
begin
return Cfg.Get (Name);
end Get;
-- ------------------------------
-- Initalize the list of gateways from the configuration file.
-- ------------------------------
procedure Get_Gateways (List : in out Druss.Gateways.Gateway_Vector) is
begin
Druss.Gateways.Initialize (Cfg, List);
end Get_Gateways;
end Druss.Config;
|
Implement the Initialize, Get and Get_Gateways operations
|
Implement the Initialize, Get and Get_Gateways operations
|
Ada
|
apache-2.0
|
stcarrez/bbox-ada-api
|
|
15753f779663723b08dfe49e8b0d91c954f5aa77
|
src/util-strings.ads
|
src/util-strings.ads
|
-----------------------------------------------------------------------
-- Util-strings -- Various String Utility
-- Copyright (C) 2001, 2002, 2003, 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.Containers;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Hashed_Sets;
with Util.Concurrent.Counters;
package Util.Strings is
pragma Preelaborate;
-- Constant string access
type Name_Access is access constant String;
-- Compute the hash value of the string.
function Hash (Key : Name_Access) return Ada.Containers.Hash_Type;
-- Returns true if left and right strings are equivalent.
function Equivalent_Keys (Left, Right : Name_Access) return Boolean;
-- Search for the first occurrence of the character in the string
-- after the from index. This implementation is 3-times faster than
-- the Ada.Strings.Fixed version.
-- Returns the index of the first occurrence or 0.
function Index (Source : in String;
Char : in Character;
From : in Natural := 0) return Natural;
-- Search for the first occurrence of the character in the string
-- before the from index and going backward.
-- This implementation is 3-times faster than the Ada.Strings.Fixed version.
-- Returns the index of the first occurrence or 0.
function Rindex (Source : in String;
Ch : in Character;
From : in Natural := 0) return Natural;
-- Search for the first occurrence of the pattern in the string.
function Index (Source : in String;
Pattern : in String;
From : in Positive;
Going : in Ada.Strings.Direction := Ada.Strings.Forward) return Natural;
-- Returns Integer'Image (Value) with the possible space stripped.
function Image (Value : in Integer) return String;
-- Returns Integer'Image (Value) with the possible space stripped.
function Image (Value : in Long_Long_Integer) return String;
package String_Access_Map is new Ada.Containers.Hashed_Maps
(Key_Type => Name_Access,
Element_Type => Name_Access,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys);
package String_Set is new Ada.Containers.Hashed_Sets
(Element_Type => Name_Access,
Hash => Hash,
Equivalent_Elements => Equivalent_Keys);
-- String reference
type String_Ref is private;
-- Create a string reference from a string.
function To_String_Ref (S : in String) return String_Ref;
-- Create a string reference from an unbounded string.
function To_String_Ref (S : in Ada.Strings.Unbounded.Unbounded_String) return String_Ref;
-- Get the string
function To_String (S : in String_Ref) return String;
-- Get the string as an unbounded string
function To_Unbounded_String (S : in String_Ref) return Ada.Strings.Unbounded.Unbounded_String;
-- Compute the hash value of the string reference.
function Hash (Key : in String_Ref) return Ada.Containers.Hash_Type;
-- Returns true if left and right string references are equivalent.
function Equivalent_Keys (Left, Right : in String_Ref) return Boolean;
function "=" (Left, Right : in String_Ref) return Boolean renames Equivalent_Keys;
function "=" (Left : in String_Ref;
Right : in String) return Boolean;
function "=" (Left : in String_Ref;
Right : in Ada.Strings.Unbounded.Unbounded_String) return Boolean;
-- Returns the string length.
function Length (S : in String_Ref) return Natural;
private
pragma Inline (To_String_Ref);
pragma Inline (To_String);
type String_Record (Len : Natural) is limited record
Counter : Util.Concurrent.Counters.Counter;
Str : String (1 .. Len);
end record;
type String_Record_Access is access all String_Record;
type String_Ref is new Ada.Finalization.Controlled with record
Str : String_Record_Access := null;
end record;
-- Increment the reference counter.
overriding
procedure Adjust (Object : in out String_Ref);
-- Decrement the reference counter and free the allocated string.
overriding
procedure Finalize (Object : in out String_Ref);
end Util.Strings;
|
-----------------------------------------------------------------------
-- Util-strings -- Various String Utility
-- Copyright (C) 2001, 2002, 2003, 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.Containers;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Hashed_Sets;
with Util.Concurrent.Counters;
package Util.Strings is
pragma Preelaborate;
-- Constant string access
type Name_Access is access constant String;
-- Compute the hash value of the string.
function Hash (Key : Name_Access) return Ada.Containers.Hash_Type;
-- Returns true if left and right strings are equivalent.
function Equivalent_Keys (Left, Right : Name_Access) return Boolean;
-- Search for the first occurrence of the character in the string
-- after the from index. This implementation is 3-times faster than
-- the Ada.Strings.Fixed version.
-- Returns the index of the first occurrence or 0.
function Index (Source : in String;
Char : in Character;
From : in Natural := 0) return Natural;
-- Search for the first occurrence of the character in the string
-- before the from index and going backward.
-- This implementation is 3-times faster than the Ada.Strings.Fixed version.
-- Returns the index of the first occurrence or 0.
function Rindex (Source : in String;
Ch : in Character;
From : in Natural := 0) return Natural;
-- Search for the first occurrence of the pattern in the string.
function Index (Source : in String;
Pattern : in String;
From : in Positive;
Going : in Ada.Strings.Direction := Ada.Strings.Forward) return Natural;
-- Returns Integer'Image (Value) with the possible space stripped.
function Image (Value : in Integer) return String;
-- Returns Integer'Image (Value) with the possible space stripped.
function Image (Value : in Long_Long_Integer) return String;
package String_Access_Map is new Ada.Containers.Hashed_Maps
(Key_Type => Name_Access,
Element_Type => Name_Access,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys);
package String_Set is new Ada.Containers.Hashed_Sets
(Element_Type => Name_Access,
Hash => Hash,
Equivalent_Elements => Equivalent_Keys);
-- String reference
type String_Ref is private;
-- Create a string reference from a string.
function To_String_Ref (S : in String) return String_Ref;
-- Create a string reference from an unbounded string.
function To_String_Ref (S : in Ada.Strings.Unbounded.Unbounded_String) return String_Ref;
-- Get the string
function To_String (S : in String_Ref) return String;
-- Get the string as an unbounded string
function To_Unbounded_String (S : in String_Ref) return Ada.Strings.Unbounded.Unbounded_String;
-- Compute the hash value of the string reference.
function Hash (Key : in String_Ref) return Ada.Containers.Hash_Type;
-- Returns true if left and right string references are equivalent.
function Equivalent_Keys (Left, Right : in String_Ref) return Boolean;
function "=" (Left, Right : in String_Ref) return Boolean renames Equivalent_Keys;
function "=" (Left : in String_Ref;
Right : in String) return Boolean;
function "=" (Left : in String_Ref;
Right : in Ada.Strings.Unbounded.Unbounded_String) return Boolean;
-- Returns the string length.
function Length (S : in String_Ref) return Natural;
private
pragma Inline (To_String_Ref);
pragma Inline (To_String);
type String_Record (Len : Natural) is limited record
Counter : Util.Concurrent.Counters.Counter;
Str : String (1 .. Len);
end record;
type String_Record_Access is access all String_Record;
type String_Ref is new Ada.Finalization.Controlled with record
Str : String_Record_Access := null;
end record;
pragma Finalize_Storage_Only (String_Ref);
-- Increment the reference counter.
overriding
procedure Adjust (Object : in out String_Ref);
-- Decrement the reference counter and free the allocated string.
overriding
procedure Finalize (Object : in out String_Ref);
end Util.Strings;
|
Add Finalize_Storage_Only on String_Ref
|
Add Finalize_Storage_Only on String_Ref
|
Ada
|
apache-2.0
|
flottokarotto/ada-util,Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util
|
25b6498a8b13fc1d987ec90fbd533f813c278497
|
src/wiki-filters.adb
|
src/wiki-filters.adb
|
-----------------------------------------------------------------------
-- wiki-filters -- Wiki 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.
-----------------------------------------------------------------------
package body Wiki.Filters is
-- ------------------------------
-- Add a section header in the document.
-- ------------------------------
overriding
procedure Add_Header (Document : in out Filter_Type;
Header : in Unbounded_Wide_Wide_String;
Level : in Positive) is
begin
Document.Document.Add_Header (Header, Level);
end Add_Header;
-- ------------------------------
-- Add a line break (<br>).
-- ------------------------------
overriding
procedure Add_Line_Break (Document : in out Filter_Type) is
begin
Document.Document.Add_Line_Break;
end Add_Line_Break;
-- ------------------------------
-- 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 Filter_Type) is
begin
Document.Document.Add_Paragraph;
end Add_Paragraph;
-- ------------------------------
-- 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 Filter_Type;
Level : in Natural) is
begin
Document.Document.Add_Blockquote (Level);
end Add_Blockquote;
-- ------------------------------
-- 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 Filter_Type;
Level : in Positive;
Ordered : in Boolean) is
begin
Document.Document.Add_List_Item (Level, Ordered);
end Add_List_Item;
-- ------------------------------
-- Add an horizontal rule (<hr>).
-- ------------------------------
overriding
procedure Add_Horizontal_Rule (Document : in out Filter_Type) is
begin
Document.Document.Add_Horizontal_Rule;
end Add_Horizontal_Rule;
-- ------------------------------
-- Add a link.
-- ------------------------------
overriding
procedure Add_Link (Document : in out Filter_Type;
Name : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String;
Title : in Unbounded_Wide_Wide_String) is
begin
Document.Document.Add_Link (Name, Link, Language, Title);
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
overriding
procedure Add_Image (Document : in out Filter_Type;
Link : in Unbounded_Wide_Wide_String;
Alt : in Unbounded_Wide_Wide_String;
Position : in Unbounded_Wide_Wide_String;
Description : in Unbounded_Wide_Wide_String) is
begin
Document.Document.Add_Image (Link, Alt, Position, Description);
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
overriding
procedure Add_Quote (Document : in out Filter_Type;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String) is
begin
Document.Document.Add_Quote (Quote, Link, Language);
end Add_Quote;
-- ------------------------------
-- Add a text block with the given format.
-- ------------------------------
overriding
procedure Add_Text (Document : in out Filter_Type;
Text : in Unbounded_Wide_Wide_String;
Format : in Wiki.Documents.Format_Map) is
begin
Document.Document.Add_Text (Text, Format);
end Add_Text;
-- ------------------------------
-- Add a text block that is pre-formatted.
-- ------------------------------
overriding
procedure Add_Preformatted (Document : in out Filter_Type;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String) is
begin
Document.Document.Add_Preformatted (Text, Format);
end Add_Preformatted;
overriding
procedure Start_Element (Document : in out Filter_Type;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Wiki.Attributes.Attribute_List_Type) is
begin
Document.Document.Start_Element (Name, Attributes);
end Start_Element;
overriding
procedure End_Element (Document : in out Filter_Type;
Name : in Unbounded_Wide_Wide_String) is
begin
Document.Document.End_Element (Name);
end End_Element;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Document : in out Filter_Type) is
begin
Document.Document.Finish;
end Finish;
-- ------------------------------
-- Set the document reader.
-- ------------------------------
procedure Set_Document (Filter : in out Filter_Type;
Document : in Wiki.Documents.Document_Reader_Access) is
begin
Filter.Document := Document;
end Set_Document;
end Wiki.Filters;
|
Implement the Wiki.Filters package with the Filter_Type type and its operations
|
Implement the Wiki.Filters package with the Filter_Type type and its operations
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
|
998ae2ce2a2cd0494d5b8a056fbd72bfa0843da9
|
src/asis/a4g-contt-dp.ads
|
src/asis/a4g-contt-dp.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . C O N T T . D P --
-- --
-- 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 for computing and setting semantic
-- dependencies between ASIS Compilation Units
with Asis; use Asis;
with Asis.Extensions; use Asis.Extensions;
package A4G.Contt.Dp is -- Context_Table.DePendencies
-- All the subprograms defined in this package are supposed, that
-- (1) they are called at most once (depending on the unit kind) for any
-- unit stored in the Context Unit table
-- (2) the caller is responsible, that these subprograms are called for
-- the actuals of appropriate kinds
-- OPEN PROBLEMS:
--
-- 1. DOCUMENTATION!!!
--
-- 2. The idea is to *compute from the tree* only direct dependencies,
-- and for all the indirect dependencies, to compute them from
-- the direct dependencies using their transitive nature.
procedure Set_Supporters (C : Context_Id; U : Unit_Id; Top : Node_Id);
-- This procedure sets the **direct** supporters for U. For now,
-- the idea is to set *from the tree* only the direct dependencies,
-- as being the function of the source text of a Unit (???). All
-- the indirect dependencies should be set from direct ones using
-- the transitive nature of the dependencies.
--
-- So, for now, only Direct_Supporters, Direct_Dependants and
-- Implicit_Supporters (representing only direct implicit dependencies
-- imposed by implicit with clauses) are set by this procedure.
--
-- OPEN PROBLEM: If we set only **direct* dependencies, may be,
-- we need only ONE function to do this? do we really need
-- Set_Ancestors, Set_Childs, ???? ?
procedure Set_Subunits (C : Context_Id; U : Unit_Id; Top : Node_Id);
-- Sets the full list of the subunit for a given body (that is, adds
-- nonexistent units for missed subunits)
procedure Process_Stub (C : Context_Id; U : Unit_Id; Stub : Node_Id);
-- Taking the node for a body stub, this function checks if the
-- corresponding subunit exists in the Context C. If it does not exist,
-- a unit of A_Nonexistent_Body kind is allocated in the Context Unit
-- table and appended to the list of subunits of U.
--
-- This procedure supposes, that before it is called, the normalized
-- name of U has been already set in A_Name_Buffer. When returning from
-- this procedure, A_Name_Buffer and A_Name_Len are remained in the
-- same state as before the call.
procedure Append_Subunit_Name (Def_S_Name : Node_Id);
-- Supposing that A_Name_Buf contains the name of the parent body, and
-- Def_S_Name points to the defining identifier obtained from the body
-- stub, this procedure forms in A_Name_Buffer the name of the subunit
procedure Set_Withed_Units (C : Context_Id; U : Unit_Id; Top : Node_Id);
-- This procedure sets the Direct_Supporters and Implicit_Supporters
-- dependency lists on the base of with clauses explicicitly presented
-- in unit's source and generated by the compiler respectively.
procedure Set_Direct_Dependents (U : Unit_Id);
-- This procedure is supposed to be called for U just after
-- Set_Withed_Units has done its work. For any unit U1 included
-- in the list of direct supporters for U, U is included in the list
-- of direct dependers of U1.
procedure Add_To_Parent (C : Context_Id; U : Unit_Id);
-- Adds U to the list of children for its parent unit declaration.
-- U is added to the list only it is consistent with the parent
procedure Set_All_Dependencies (Use_First_New_Unit : Boolean := False);
-- Sets all supportiers and all dependants for units contained in the
-- argument Context. Should be called when all the units are already set.
-- If Use_First_New_Unit is set ON (this may happen for Incremental
-- Context only), completes the dependencies only for new units from the
-- new tree (see the body of A4G.Get_Unit.Fetch_Unit_By_Ada_Name)
procedure Set_All_Ancestors
(Compilation_Units : Asis.Compilation_Unit_List;
Result : in out Compilation_Unit_List_Access);
-- This procedure takes the arguments of
-- Asis.Compilation_Units.Relations.Semantic_Dependence_Order query in
-- case when Relation parameter is set to Ancestors and computes the
-- consistent part of the result.(???)
procedure Set_All_Descendants
(Compilation_Units : Asis.Compilation_Unit_List;
Result : in out Compilation_Unit_List_Access);
-- This procedure takes the arguments of
-- Asis.Compilation_Units.Relations.Semantic_Dependence_Order query in
-- case when Relation parameter is set to Descendants and computes the
-- consistent part of the result.(???)
procedure Set_All_Supporters
(Compilation_Units : Asis.Compilation_Unit_List;
Result : in out Compilation_Unit_List_Access);
-- This procedure takes the arguments of
-- Asis.Compilation_Units.Relations.Semantic_Dependence_Order query in
-- case when Relation parameter is set to Supporters and
-- computes the consistent part of the result.(???)
procedure Set_All_Dependents
(Compilation_Units : Asis.Compilation_Unit_List;
Dependent_Units : Asis.Compilation_Unit_List;
Result : in out Compilation_Unit_List_Access);
-- This procedure takes the arguments of
-- Asis.Compilation_Units.Relations.Semantic_Dependence_Order query in
-- case when Relation parameter is set to Dependents and computes the
-- consistent part of the result.(???)
procedure Set_All_Families
(Compilation_Units : Asis.Compilation_Unit_List;
Result : in out Compilation_Unit_List_Access);
-- This procedure takes the arguments of
-- Asis.Compilation_Units.Relations.Semantic_Dependence_Order query in
-- case when Relation parameter is set to Family and
-- computes the consistent part of the result.(???)
procedure Set_All_Needed_Units
(Compilation_Units : Asis.Compilation_Unit_List;
Result : in out Compilation_Unit_List_Access;
Missed : in out Compilation_Unit_List_Access);
-- This procedure takes the arguments of
-- Asis.Compilation_Units.Relations.Semantic_Dependence_Order query in
-- case when Relation parameter is set to Needed_Units and
-- computes the consistent part of the result and missed units.(???)
end A4G.Contt.Dp;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
cbd3c55a6d3774330604f0b890f9f12e605ffa23
|
src/asis/a4g-knd_conv.ads
|
src/asis/a4g-knd_conv.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . K N D _ C O N V --
-- --
-- S p e c --
-- --
-- Copyright (C) 1995-2011, Free Software Foundation, Inc. --
-- --
-- ASIS-for-GNAT is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 2, or (at your option) any later --
-- version. ASIS-for-GNAT is distributed in the hope that it will be use- --
-- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- --
-- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General --
-- Public License for more details. You should have received a copy of the --
-- GNU General Public License distributed with ASIS-for-GNAT; see file --
-- COPYING. If not, write to the Free Software Foundation, 51 Franklin --
-- Street, Fifth Floor, Boston, MA 02110-1301, USA. --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the --
-- Software Engineering Laboratory of the Swiss Federal Institute of --
-- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the --
-- Scientific Research Computer Center of Moscow State University (SRCC --
-- MSU), Russia, with funding partially provided by grants from the Swiss --
-- National Science Foundation and the Swiss Academy of Engineering --
-- Sciences. ASIS-for-GNAT is now maintained by AdaCore --
-- (http://www.adacore.com). --
-- --
------------------------------------------------------------------------------
with Asis;
with A4G.Int_Knds; use A4G.Int_Knds;
package A4G.Knd_Conv is
--------------------------------------
-- Element Classification Functions --
--------------------------------------
-- The following functions convert the Internal Element Kind value
-- given as their argument into the corresponding value of the
-- corresponding Asis Element Classification subordinate kind.
-- Not_A_XXX is returned if the argument does not belong to the
-- corresponding internal classification subtype.
function Asis_From_Internal_Kind
(Internal_Kind : Internal_Element_Kinds)
return Asis.Element_Kinds;
function Pragma_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Pragma_Kinds;
function Defining_Name_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Defining_Name_Kinds;
function Declaration_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Declaration_Kinds;
function Definition_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Definition_Kinds;
function Type_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Type_Kinds;
function Formal_Type_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Formal_Type_Kinds;
function Access_Type_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Access_Type_Kinds;
function Root_Type_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Root_Type_Kinds;
-- --|A2005 start
function Access_Definition_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Access_Definition_Kinds;
function Interface_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Interface_Kinds;
-- --|A2005 end
function Constraint_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Constraint_Kinds;
function Discrete_Range_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Discrete_Range_Kinds;
function Expression_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Expression_Kinds;
function Operator_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Operator_Kinds;
function Attribute_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Attribute_Kinds;
function Association_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Association_Kinds;
function Statement_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Statement_Kinds;
function Path_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Path_Kinds;
function Clause_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Clause_Kinds;
function Representation_Clause_Kind_From_Internal
(Internal_Kind : Internal_Element_Kinds)
return Asis.Representation_Clause_Kinds;
-------------------------------------
-- Additional Classification items --
-------------------------------------
function Def_Operator_Kind
(Op_Kind : Internal_Element_Kinds)
return Internal_Element_Kinds;
-- this function "converts" the value of Internal_Operator_Symbol_Kinds
-- into the corresponding value of Internal_Defining_Operator_Kinds
-- It is an error to call it to an Internal_Element_Kinds value which
-- does not belong to Internal_Operator_Symbol_Kinds
end A4G.Knd_Conv;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
d12033fad8d74fc6e03fc88c07a075ecc1e0fbc4
|
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
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
|
8f6f77847f06a64e091921382f66bbe7936d32d5
|
src/babel-filters.adb
|
src/babel-filters.adb
|
-----------------------------------------------------------------------
-- babel-filters -- File filters
-- 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.
-----------------------------------------------------------------------
package body Babel.Filters is
use type Ada.Directories.File_Kind;
-- ------------------------------
-- Return True if the file or directory is accepted by the filter.
-- ------------------------------
overriding
function Is_Accepted (Filter : in Exclude_Directory_Filter_Type;
Kind : in Ada.Directories.File_Kind;
Path : in String;
Name : in String) return Boolean is
begin
if Kind /= Ada.Directories.Directory then
return True;
end if;
if Filter.Excluded.Contains (Name) then
return False;
end if;
return True;
end Is_Accepted;
-- ------------------------------
-- Add the given path to the list of excluded directories.
-- ------------------------------
procedure Add_Exclude (Filter : in out Exclude_Directory_Filter_Type;
Path : in String) is
begin
Filter.Excluded.Include (Path);
end Add_Exclude;
end Babel.Filters;
|
Backup filter implementation
|
Backup filter implementation
|
Ada
|
apache-2.0
|
stcarrez/babel
|
|
21411d4f0ce56763f7b5444f84d11482b0d793b0
|
src/util-texts-builders.adb
|
src/util-texts-builders.adb
|
-----------------------------------------------------------------------
-- util-texts-builders -- Text builder
-- 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.Texts.Builders is
-- ------------------------------
-- Get the length of the item builder.
-- ------------------------------
function Length (Source : in Builder) return Natural is
begin
return Source.Length;
end Length;
-- ------------------------------
-- Get the capacity of the builder.
-- ------------------------------
function Capacity (Source : in Builder) return Natural is
B : constant Block_Access := Source.Current;
begin
return Source.Length + B.Len - B.Last;
end Capacity;
-- ------------------------------
-- Get the builder block size.
-- ------------------------------
function Block_Size (Source : in Builder) return Positive is
begin
return Source.Block_Size;
end Block_Size;
-- ------------------------------
-- Set the block size for the allocation of next chunks.
-- ------------------------------
procedure Set_Block_Size (Source : in out Builder;
Size : in Positive) is
begin
Source.Block_Size := Size;
end Set_Block_Size;
-- ------------------------------
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
-- ------------------------------
procedure Append (Source : in out Builder;
New_Item : in Input) is
B : Block_Access := Source.Current;
Start : Natural := New_Item'First;
Last : constant Natural := New_Item'Last;
begin
while Start <= Last loop
declare
Space : Natural := B.Len - B.Last;
Size : constant Natural := Last - Start + 1;
begin
if Space > Size then
Space := Size;
elsif Space = 0 then
if Size > Source.Block_Size then
B.Next_Block := new Block (Size);
else
B.Next_Block := new Block (Source.Block_Size);
end if;
B := B.Next_Block;
Source.Current := B;
if B.Len > Size then
Space := Size;
else
Space := B.Len;
end if;
end if;
B.Content (B.Last + 1 .. B.Last + Space) := New_Item (Start .. Start + Space - 1);
Source.Length := Source.Length + Space;
B.Last := B.Last + Space;
Start := Start + Space;
end;
end loop;
end Append;
-- ------------------------------
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
-- ------------------------------
procedure Append (Source : in out Builder;
New_Item : in Element_Type) is
B : Block_Access := Source.Current;
begin
if B.Len = B.Last then
B.Next_Block := new Block (Source.Block_Size);
B := B.Next_Block;
Source.Current := B;
end if;
Source.Length := Source.Length + 1;
B.Last := B.Last + 1;
B.Content (B.Last) := New_Item;
end Append;
-- ------------------------------
-- Clear the source freeing any storage allocated for the buffer.
-- ------------------------------
procedure Clear (Source : in out Builder) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Block, Name => Block_Access);
Current, Next : Block_Access;
begin
Next := Source.First.Next_Block;
while Next /= null loop
Current := Next;
Next := Current.Next_Block;
Free (Current);
end loop;
Source.First.Next_Block := null;
Source.First.Last := 0;
Source.Current := Source.First'Unchecked_Access;
Source.Length := 0;
end Clear;
-- ------------------------------
-- Iterate over the buffer content calling the <tt>Process</tt> procedure with each
-- chunk.
-- ------------------------------
procedure Iterate (Source : in Builder;
Process : not null access procedure (Chunk : in Input)) is
begin
if Source.First.Last > 0 then
Process (Source.First.Content (1 .. Source.First.Last));
declare
B : Block_Access := Source.First.Next_Block;
begin
while B /= null loop
Process (B.Content (1 .. B.Last));
B := B.Next_Block;
end loop;
end;
end if;
end Iterate;
-- ------------------------------
-- Get the buffer content as an array.
-- ------------------------------
function To_Array (Source : in Builder) return Input is
Result : Input (1 .. Source.Length);
begin
if Source.First.Last > 0 then
declare
Pos : Positive := Source.First.Last;
B : Block_Access := Source.First.Next_Block;
begin
Result (1 .. Pos) := Source.First.Content (1 .. Pos);
while B /= null loop
Result (Pos + 1 .. Pos + B.Last) := B.Content (1 .. B.Last);
Pos := Pos + B.Last;
B := B.Next_Block;
end loop;
end;
end if;
return Result;
end To_Array;
-- ------------------------------
-- Setup the builder.
-- ------------------------------
overriding
procedure Initialize (Source : in out Builder) is
begin
Source.Current := Source.First'Unchecked_Access;
end Initialize;
-- ------------------------------
-- Finalize the builder releasing the storage.
-- ------------------------------
overriding
procedure Finalize (Source : in out Builder) is
begin
Clear (Source);
end Finalize;
end Util.Texts.Builders;
|
Implement the new package
|
Implement the new package
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
|
3c4c54278b470ec940fdeae55e8578c62a0502d2
|
src/security-oauth-jwt.adb
|
src/security-oauth-jwt.adb
|
-----------------------------------------------------------------------
-- security-oauth-jwt -- OAuth Java 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 Ada.Calendar.Conversions;
with Interfaces.C;
with Util.Encoders;
with Util.Strings;
with Util.Properties.JSON;
with Util.Log.Loggers;
package body Security.OAuth.JWT is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.OAuth.JWT");
function Get_Time (From : in Util.Properties.Manager;
Name : in String) return Ada.Calendar.Time;
-- Decode the part using base64url and parse the JSON content into the property manager.
procedure Decode_Part (Into : in out Util.Properties.Manager;
Name : in String;
Data : in String);
function Get_Time (From : in Util.Properties.Manager;
Name : in String) return Ada.Calendar.Time is
Value : constant String := From.Get (Name);
begin
return Ada.Calendar.Conversions.To_Ada_Time (Interfaces.C.long'Value (Value));
end Get_Time;
-- ------------------------------
-- Get the issuer claim from the token (the "iss" claim).
-- ------------------------------
function Get_Issuer (From : in Token) return String is
begin
return From.Claims.Get ("iss");
end Get_Issuer;
-- ------------------------------
-- Get the subject claim from the token (the "sub" claim).
-- ------------------------------
function Get_Subject (From : in Token) return String is
begin
return From.Claims.Get ("sub");
end Get_Subject;
-- ------------------------------
-- Get the audience claim from the token (the "aud" claim).
-- ------------------------------
function Get_Audience (From : in Token) return String is
begin
return From.Claims.Get ("aud");
end Get_Audience;
-- ------------------------------
-- Get the expiration claim from the token (the "exp" claim).
-- ------------------------------
function Get_Expiration (From : in Token) return Ada.Calendar.Time is
begin
return Get_Time (From.Claims, "exp");
end Get_Expiration;
-- ------------------------------
-- Get the not before claim from the token (the "nbf" claim).
-- ------------------------------
function Get_Not_Before (From : in Token) return Ada.Calendar.Time is
begin
return Get_Time (From.Claims, "nbf");
end Get_Not_Before;
-- ------------------------------
-- Get the issued at claim from the token (the "iat" claim).
-- ------------------------------
function Get_Issued_At (From : in Token) return Ada.Calendar.Time is
begin
return Get_Time (From.Claims, "iat");
end Get_Issued_At;
-- ------------------------------
-- Get the authentication time claim from the token (the "auth_time" claim).
-- ------------------------------
function Get_Authentication_Time (From : in Token) return Ada.Calendar.Time is
begin
return Get_Time (From.Claims, "auth_time");
end Get_Authentication_Time;
-- ------------------------------
-- Get the JWT ID claim from the token (the "jti" claim).
-- ------------------------------
function Get_JWT_ID (From : in Token) return String is
begin
return From.Claims.Get ("jti");
end Get_JWT_ID;
-- ------------------------------
-- Get the authorized clients claim from the token (the "azp" claim).
-- ------------------------------
function Get_Authorized_Presenters (From : in Token) return String is
begin
return From.Claims.Get ("azp");
end Get_Authorized_Presenters;
-- ------------------------------
-- Get the claim with the given name from the token.
-- ------------------------------
function Get_Claim (From : in Token;
Name : in String) return String is
begin
return From.Claims.Get (Name);
end Get_Claim;
-- ------------------------------
-- Decode the part using base64url and parse the JSON content into the property manager.
-- ------------------------------
procedure Decode_Part (Into : in out Util.Properties.Manager;
Name : in String;
Data : in String) is
Decoder : constant Util.Encoders.Encoder := Util.Encoders.Create (Util.Encoders.BASE_64_URL);
Content : constant String := Decoder.Decode (Data);
begin
Log.Debug ("Decoding {0}: {1}", Name, Content);
Util.Properties.JSON.Parse_JSON (Into, Content);
end Decode_Part;
-- ------------------------------
-- Decode a string representing an encoded JWT token according to the JWT specification:
--
-- Section 7. Rules for Creating and Validating a JWT
--
-- The JWT token is composed of 3 parts encoded in Base64url and separated by '.' .
-- The first part represents the header, the second part the claims and the last part
-- the signature. The <tt>Decode</tt> operation splits the parts, decodes them,
-- parses the JSON content represented by the header and the claims.
-- The <tt>Decode</tt> operation does not verify the signature (yet!).
--
-- Return the decoded token or raise an exception.
-- ------------------------------
function Decode (Content : in String) return Token is
Pos1 : constant Natural := Util.Strings.Index (Content, '.');
Pos2 : Natural;
Result : Token;
begin
if Pos1 = 0 then
Log.Error ("Invalid JWT token: missing '.' separator. JWT: {0}", Content);
raise Invalid_Token with "Missing header separator";
end if;
Pos2 := Util.Strings.Index (Content, '.', Pos1 + 1);
if Pos2 = 0 then
Log.Error ("Invalid JWT token: missing second '.' separator. JWT: {0}", Content);
raise Invalid_Token with "Missing signature separator";
end if;
Decode_Part (Result.Header, "header", Content (Content'First .. Pos1 - 1));
Decode_Part (Result.Claims, "claims", Content (Pos1 + 1 .. Pos2 - 1));
return Result;
end Decode;
end Security.OAuth.JWT;
|
Implement the JWT decoding and extraction
|
Implement the JWT decoding and extraction
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
|
fd92a514b7287781cc2299a43fa95cc094654640
|
awa/regtests/awa-wikis-writers-tests.adb
|
awa/regtests/awa-wikis-writers-tests.adb
|
-----------------------------------------------------------------------
-- Render Tests - Unit tests for AWA Wiki rendering
-- 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.Text_IO;
with Ada.Directories;
with Ada.Characters.Conversions;
with Util.Files;
with Util.Measures;
package body AWA.Wikis.Writers.Tests is
use Ada.Strings.Unbounded;
-- ------------------------------
-- Test rendering a wiki text in HTML or text.
-- ------------------------------
procedure Test_Render (T : in out Test) is
function To_Wide (Item : in String) return Wide_Wide_String
renames Ada.Characters.Conversions.To_Wide_Wide_String;
Result_File : constant String := To_String (T.Result);
Content : Unbounded_String;
begin
Util.Files.Read_File (Path => To_String (T.File),
Into => Content,
Max_Size => 10000);
declare
Time : Util.Measures.Stamp;
begin
if T.Is_Html then
Content := To_Unbounded_String
(Writers.To_Html (To_Wide (To_String (Content)), T.Format));
else
Content := To_Unbounded_String
(Writers.To_Text (To_Wide (To_String (Content)), T.Format));
end if;
Util.Measures.Report (Time, "Render " & To_String (T.Name));
end;
Util.Files.Write_File (Result_File, Content);
Util.Tests.Assert_Equal_Files (T => T,
Expect => To_String (T.Expect),
Test => Result_File,
Message => "Render");
end Test_Render;
-- ------------------------------
-- Test case name
-- ------------------------------
overriding
function Name (T : in Test) return Util.Tests.Message_String is
begin
if T.Is_Html then
return Util.Tests.Format ("Test HTML " & To_String (T.Name));
else
return Util.Tests.Format ("Test TEXT " & To_String (T.Name));
end if;
end Name;
-- ------------------------------
-- Perform the test.
-- ------------------------------
overriding
procedure Run_Test (T : in out Test) is
begin
T.Test_Render;
end Run_Test;
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
use Ada.Directories;
function Create_Test (Name : in String; Is_Html : in Boolean) return Test_Case_Access;
Result_Dir : constant String := "regtests/result";
Dir : constant String := "regtests/files/wiki";
Expect_Dir : constant String := "regtests/expect";
Path : constant String := Util.Tests.Get_Path (Dir);
Expect_Path : constant String := Util.Tests.Get_Path (Expect_Dir);
Result_Path : constant String := Util.Tests.Get_Test_Path (Result_Dir);
Search : Search_Type;
Filter : constant Filter_Type := (others => True);
Ent : Directory_Entry_Type;
function Create_Test (Name : in String; Is_Html : in Boolean) return Test_Case_Access is
Ext : constant String := Ada.Directories.Extension (Name);
Tst : Test_Case_Access;
begin
Tst := new Test;
Tst.Is_Html := Is_Html;
Tst.Name := To_Unbounded_String (Name);
Tst.File := To_Unbounded_String (Path & "/" & Name);
if Is_Html then
Tst.Expect := To_Unbounded_String (Expect_Path & "/wiki-html/" & Name);
Tst.Result := To_Unbounded_String (Result_Path & "/wiki-html/" & Name);
else
Tst.Expect := To_Unbounded_String (Expect_Path & "/wiki-txt/" & Name);
Tst.Result := To_Unbounded_String (Result_Path & "/wiki-txt/" & Name);
end if;
if Ext = "wiki" then
Tst.Format := AWA.Wikis.Parsers.SYNTAX_GOOGLE;
elsif Ext = "dotclear" then
Tst.Format := AWA.Wikis.Parsers.SYNTAX_DOTCLEAR;
elsif Ext = "creole" then
Tst.Format := AWA.Wikis.Parsers.SYNTAX_CREOLE;
elsif Ext = "phpbb" then
Tst.Format := AWA.Wikis.Parsers.SYNTAX_PHPBB;
elsif Ext = "mediawiki" then
Tst.Format := AWA.Wikis.Parsers.SYNTAX_MEDIA_WIKI;
else
Tst.Format := AWA.Wikis.Parsers.SYNTAX_MIX;
end if;
return Tst;
end Create_Test;
begin
if Kind (Path) /= Directory then
Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path);
end if;
Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Simple : constant String := Simple_Name (Ent);
Tst : Test_Case_Access;
begin
if Simple /= "." and then Simple /= ".."
and then Simple /= ".svn" then
Tst := Create_Test (Simple, True);
Suite.Add_Test (Tst.all'Access);
Tst := Create_Test (Simple, False);
Suite.Add_Test (Tst.all'Access);
end if;
end;
end loop;
end Add_Tests;
end AWA.Wikis.Writers.Tests;
|
Implement the new wiki unit tests
|
Implement the new wiki unit tests
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
|
857dbafc196ce88378e654468c1c508b4c72f709
|
src/asis/asis-ada_environments.adb
|
src/asis/asis-ada_environments.adb
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A S I S . A D A _ E N V I R O N M E N T 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, 51 Franklin --
-- Street, Fifth Floor, Boston, MA 02110-1301, USA. --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the --
-- Software Engineering Laboratory of the Swiss Federal Institute of --
-- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the --
-- Scientific Research Computer Center of Moscow State University (SRCC --
-- MSU), Russia, with funding partially provided by grants from the Swiss --
-- National Science Foundation and the Swiss Academy of Engineering --
-- Sciences. ASIS-for-GNAT is now maintained by AdaCore --
-- (http://www.adaccore.com). --
-- --
------------------------------------------------------------------------------
with Ada.Characters.Handling; use Ada.Characters.Handling;
with Ada.Strings; use Ada.Strings;
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
with Asis.Errors; use Asis.Errors;
with Asis.Exceptions; use Asis.Exceptions;
with 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.A_Output; use A4G.A_Output;
with A4G.Contt; use A4G.Contt;
with A4G.Contt.TT; use A4G.Contt.TT;
with A4G.Contt.UT; use A4G.Contt.UT;
with A4G.Vcheck; use A4G.Vcheck;
with Output; use Output;
package body Asis.Ada_Environments is
Package_Name : constant String := "Asis.Ada_Environments.";
---------------
-- Associate --
---------------
procedure Associate
(The_Context : in out Asis.Context;
Name : Wide_String;
Parameters : Wide_String := Default_Parameters)
is
S_Parameters : constant String := Trim (To_String (Parameters), Both);
Cont : Context_Id;
begin
Cont := Get_Cont_Id (The_Context);
if not A4G.A_Opt.Is_Initialized then
Set_Error_Status
(Status => Initialization_Error,
Diagnosis => Package_Name & "Associate: "
& "called for non-initialized ASIS");
raise ASIS_Failed;
end if;
if Is_Opened (Cont) then
Set_Error_Status
(Status => Value_Error,
Diagnosis => Package_Name & "Associate: "
& "the Context has already been opened");
raise ASIS_Inappropriate_Context;
end if;
if Cont = Non_Associated then
-- this is the first association for a given Context
Cont := Allocate_New_Context;
Set_Cont (The_Context, Cont);
else
Erase_Old (Cont);
end if;
Verify_Context_Name (To_String (Name), Cont);
Process_Context_Parameters (S_Parameters, Cont);
Set_Is_Associated (Cont, True);
Save_Context (Cont);
Set_Current_Cont (Nil_Context_Id);
exception
when ASIS_Inappropriate_Context =>
Set_Is_Associated (Cont, False);
raise;
when ASIS_Failed =>
Set_Is_Associated (Cont, False);
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information (Outer_Call => Package_Name & "Associate");
end if;
raise;
when Ex : others =>
Set_Is_Associated (Cont, False);
Report_ASIS_Bug
(Query_Name => Package_Name & "Associate",
Ex => Ex);
end Associate;
-----------
-- Close --
-----------
procedure Close (The_Context : in out Asis.Context) is
Cont : Context_Id;
begin
Cont := Get_Cont_Id (The_Context);
Reset_Context (Cont);
if not Is_Opened (Cont) then
Set_Error_Status (Status => Value_Error,
Diagnosis => Package_Name & "Close: " &
"the Context is not open");
raise ASIS_Inappropriate_Context;
end if;
if Debug_Flag_C or else
Debug_Lib_Model or else
Debug_Mode
then
Write_Str ("Closing Context ");
Write_Int (Int (Cont));
Write_Eol;
Print_Units (Cont);
Print_Trees (Cont);
end if;
Set_Is_Opened (Cont, False);
Set_Current_Cont (Nil_Context_Id);
Reset_Cache;
exception
when ASIS_Inappropriate_Context =>
raise;
when ASIS_Failed =>
Set_Current_Cont (Nil_Context_Id);
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information (Outer_Call => Package_Name & "Close");
end if;
raise;
when Ex : others =>
Set_Current_Cont (Nil_Context_Id);
Report_ASIS_Bug
(Query_Name => Package_Name & "Associate",
Ex => Ex);
end Close;
-----------------
-- Debug_Image --
-----------------
function Debug_Image
(The_Context : Asis.Context)
return Wide_String
is
Arg_Cont : Context_Id;
LT : Wide_String renames A4G.A_Types.Asis_Wide_Line_Terminator;
begin
Arg_Cont := Get_Cont_Id (The_Context);
Reset_Context (Arg_Cont);
return LT & "Context Debug_Image: " &
LT & "Context Id is" &
Context_Id'Wide_Image (Arg_Cont) &
LT & To_Wide_String (Debug_String (The_Context));
exception
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Debug_Image",
Ex => Ex);
end Debug_Image;
------------------
-- Default_Name --
------------------
function Default_Name return Wide_String is
begin
return Nil_Asis_Wide_String;
end Default_Name;
------------------------
-- Default_Parameters --
------------------------
function Default_Parameters return Wide_String is
begin
return Nil_Asis_Wide_String;
end Default_Parameters;
----------------
-- Dissociate --
----------------
procedure Dissociate (The_Context : in out Asis.Context) is
Cont : Context_Id;
begin
Cont := Get_Cont_Id (The_Context);
if Is_Opened (Cont) then
Set_Error_Status (Status => Value_Error,
Diagnosis => Package_Name & "Dissociate: "
& "the Context is open");
raise ASIS_Inappropriate_Context;
end if;
if Debug_Flag_C or else
Debug_Lib_Model or else
Debug_Mode
then
Write_Str ("Dissociating Context ");
Write_Int (Int (Cont));
Write_Eol;
Print_Context_Parameters (Cont);
end if;
if Is_Associated (Cont) then
Erase_Old (Cont);
Set_Is_Associated (Cont, False);
end if;
exception
when ASIS_Inappropriate_Context =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information (Outer_Call => Package_Name & "Dissociate");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Dissociate",
Ex => Ex);
end Dissociate;
------------
-- Exists --
------------
function Exists (The_Context : Asis.Context) return Boolean is
Cont : Context_Id;
begin
Cont := Get_Cont_Id (The_Context);
return Is_Associated (Cont);
end Exists;
----------------------
-- Has_Associations --
----------------------
function Has_Associations
(The_Context : Asis.Context)
return Boolean
is
Cont : Context_Id;
begin
Cont := Get_Cont_Id (The_Context);
return Is_Associated (Cont);
end Has_Associations;
--------------
-- Is_Equal --
--------------
function Is_Equal
(Left : Asis.Context;
Right : Asis.Context)
return Boolean
is
begin
return Get_Cont_Id (Left) = Get_Cont_Id (Right);
-- Should be revised
end Is_Equal;
------------------
-- Is_Identical --
------------------
function Is_Identical
(Left : Asis.Context;
Right : Asis.Context)
return Boolean
is
begin
return Get_Cont_Id (Left) = Get_Cont_Id (Right);
end Is_Identical;
-------------
-- Is_Open --
-------------
function Is_Open (The_Context : Asis.Context) return Boolean is
Cont : Context_Id;
begin
Cont := Get_Cont_Id (The_Context);
return Is_Opened (Cont);
end Is_Open;
----------
-- Name --
----------
function Name (The_Context : Asis.Context) return Wide_String is
Cont : Context_Id;
begin
Cont := Get_Cont_Id (The_Context);
return To_Wide_String (Get_Context_Name (Cont));
end Name;
----------
-- Open --
----------
procedure Open (The_Context : in out Asis.Context) is
Cont : Context_Id;
Context_Tree_Mode : Tree_Mode;
begin
Cont := Get_Cont_Id (The_Context);
if not Is_Associated (Cont) then
Set_Error_Status (Status => Value_Error,
Diagnosis => Package_Name & "Open: " &
"the Context does not have association");
raise ASIS_Inappropriate_Context;
elsif Is_Opened (Cont) then
Set_Error_Status (Status => Value_Error,
Diagnosis => Package_Name & "Open: " &
"the Context has already been opened");
raise ASIS_Inappropriate_Context;
end if;
Reset_Context (Cont);
Context_Tree_Mode := Tree_Processing_Mode (Cont);
if Tree_Processing_Mode (Cont) = GNSA then
Set_Error_Status (Status => Use_Error,
Diagnosis => Package_Name & "Open: " &
"GNSA Context mode is not allowed");
raise ASIS_Inappropriate_Context;
end if;
Increase_ASIS_OS_Time;
Pre_Initialize (Cont);
A4G.Contt.Initialize (Cont);
-- Having these two Pre_Initialize and A4G.Contt.Initialize calling
-- one after another is a kind of junk, but there are some problems
-- with multi-context processing which have not been completely
-- detected and which does not allow to get rid of this definitely
-- redundunt "initialization"
case Context_Tree_Mode is
when Pre_Created | Mixed =>
Scan_Trees_New (Cont);
when Incremental =>
-- Not the best approach, unfortunately
begin
Scan_Trees_New (Cont);
exception
when Inconsistent_Incremental_Context =>
-- Setting empty incremental context:
Pre_Initialize (Cont);
A4G.Contt.Initialize (Cont);
end;
when others =>
null;
end case;
Set_Is_Opened (Cont, True);
Save_Context (Cont);
Set_Current_Cont (Nil_Context_Id);
exception
when Program_Error =>
raise;
when ASIS_Inappropriate_Context =>
raise;
when ASIS_Failed =>
Set_Is_Opened (Cont, False);
Set_Current_Cont (Nil_Context_Id);
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information (Outer_Call => Package_Name & "Open");
end if;
raise;
when Ex : others =>
Set_Is_Opened (Cont, False);
Set_Current_Cont (Nil_Context_Id);
Report_ASIS_Bug
(Query_Name => Package_Name & "Open",
Ex => Ex);
end Open;
----------------
-- Parameters --
----------------
function Parameters (The_Context : Asis.Context) return Wide_String is
Cont : Context_Id;
begin
Cont := Get_Cont_Id (The_Context);
return To_Wide_String (Get_Context_Parameters (Cont));
end Parameters;
end Asis.Ada_Environments;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
eb133822dece2e693f8b239e076610daa504a913
|
src/util-processes-tools.adb
|
src/util-processes-tools.adb
|
-----------------------------------------------------------------------
-- util-processes-tools -- System specific and low level operations
-- 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.Systems.Os;
with Util.Streams.Texts;
with Util.Streams.Pipes;
package body Util.Processes.Tools is
-- ------------------------------
-- Execute the command and append the output in the vector array.
-- The program output is read line by line and the standard input is closed.
-- Return the program exit status.
-- ------------------------------
procedure Execute (Command : in String;
Output : in out Util.Strings.Vectors.Vector;
Status : out Integer) is
Proc : aliased Util.Streams.Pipes.Pipe_Stream;
Text : Util.Streams.Texts.Reader_Stream;
begin
Proc.Add_Close (Util.Systems.Os.STDIN_FILENO);
Text.Initialize (Proc'Unchecked_Access);
Proc.Open (Command, Util.Processes.READ);
while not Text.Is_Eof loop
declare
Line : Ada.Strings.Unbounded.Unbounded_String;
begin
Text.Read_Line (Line, Strip => True);
exit when Ada.Strings.Unbounded.Length (Line) = 0;
Output.Append (Ada.Strings.Unbounded.To_String (Line));
end;
end loop;
Proc.Close;
Status := Proc.Get_Exit_Status;
end Execute;
end Util.Processes.Tools;
|
Implement the Execute procedure
|
Implement the Execute procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
|
09e37a10da19c42b92e823ea50871e2e82c9ed21
|
src/asis/asis-data_decomposition-set_get.adb
|
src/asis/asis-data_decomposition-set_get.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 . S E T _ G E T --
-- --
-- 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 System; use System;
with Asis.Declarations; use Asis.Declarations;
with Asis.Definitions; use Asis.Definitions;
with Asis.Elements; use Asis.Elements;
with Asis.Extensions; use Asis.Extensions;
with Asis.Iterator; use Asis.Iterator;
with Asis.Set_Get; use Asis.Set_Get;
with Asis.Data_Decomposition.Aux; use Asis.Data_Decomposition.Aux;
with A4G.Contt; use A4G.Contt;
with Atree; use Atree;
with Sinfo; use Sinfo;
with Einfo; use Einfo;
with Nlists; use Nlists;
with Uintp; use Uintp;
package body Asis.Data_Decomposition.Set_Get is
-----------------------
-- Local subprograms --
-----------------------
procedure Set_Derived_Type_Components (E : Asis.Element);
-- Provided that E is a derived type definition, this procedure sets in
-- Asis_Element_Table the defining identifiers of the components of the
-- corresponding type. (For inherited components it sets the corresponding
-- implicit names)
--------------------
-- Component_Name --
--------------------
function Component_Name (Comp : RC) return Asis.Defining_Name is
begin
return Comp.Component_Name;
end Component_Name;
---------------
-- Dimension --
---------------
function Dimension (Comp : AC) return ASIS_Natural
is
begin
return Comp.Dimension;
end Dimension;
---------------------------
-- Get_Array_Type_Entity --
---------------------------
function Get_Array_Type_Entity (Comp : AC) return Entity_Id is
Result : Entity_Id;
pragma Warnings (Off, Result);
begin
-- ???!!! This is a trick needed to reset the right tree!
-- ???!!! Should be replaced by a proper tree handling for
-- ???!!! array components
Result := Node (Comp.Parent_Array_Type);
Result := Comp.Array_Type_Entity;
return Result;
end Get_Array_Type_Entity;
---------------------
-- Get_Comp_Entity --
---------------------
function Get_Comp_Entity (Comp : RC) return Entity_Id is
begin
return R_Node (Component_Name (Comp));
end Get_Comp_Entity;
-----------------------
-- Get_Record_Entity --
-----------------------
function Get_Record_Entity (Comp : RC) return Entity_Id is
Result : Entity_Id;
begin
Result := R_Node (Parent_Record_Type (Comp));
while Nkind (Result) /= N_Full_Type_Declaration loop
Result := Parent (Result);
end loop;
Result := Defining_Identifier (Result);
return Result;
end Get_Record_Entity;
---------------------
-- Get_Type_Entity --
---------------------
function Get_Type_Entity (Comp : RC) return Node_Id is
Result : Node_Id;
begin
Result := Etype (R_Node (Component_Name (Comp)));
if Ekind (Result) = E_Private_Type then
Result := Full_View (Result);
end if;
return Result;
end Get_Type_Entity;
-------------------
-- Is_Array_Comp --
-------------------
function Is_Array_Comp (Comp : AC) return Boolean is
begin
return Comp.Is_Array_Comp;
end Is_Array_Comp;
function Is_Array_Comp (Comp : RC) return Boolean is
begin
return Comp.Is_Array_Comp;
end Is_Array_Comp;
--------------------
-- Is_Record_Comp --
--------------------
function Is_Record_Comp (Comp : AC) return Boolean is
begin
return Comp.Is_Record_Comp;
end Is_Record_Comp;
function Is_Record_Comp (Comp : RC) return Boolean is
begin
return Comp.Is_Record_Comp;
end Is_Record_Comp;
-----------------------
-- Parent_Array_Type --
-----------------------
function Parent_Array_Type (Comp : AC) return Asis.Declaration is
begin
return Comp.Parent_Array_Type;
end Parent_Array_Type;
---------------------
-- Parent_Discrims --
---------------------
function Parent_Discrims (Comp : AC) return Discrim_List is
begin
if Comp.Parent_Discrims = null then
return Null_Discrims;
else
return Comp.Parent_Discrims.all;
end if;
end Parent_Discrims;
function Parent_Discrims (Comp : RC) return Discrim_List is
begin
if Comp.Parent_Discrims = null then
return Null_Discrims;
else
return Comp.Parent_Discrims.all;
end if;
end Parent_Discrims;
------------------------
-- Parent_Record_Type --
------------------------
function Parent_Record_Type (Comp : RC) return Asis.Declaration is
begin
return Comp.Parent_Record_Type;
end Parent_Record_Type;
-------------------------
-- Set_Array_Componnet --
-------------------------
function Set_Array_Componnet
(Array_Type_Definition : Element;
Enclosing_Record_Component : Record_Component := Nil_Record_Component;
Parent_Indication : Element := Nil_Element;
Parent_Discriminants : Discrim_List := Null_Discrims;
Parent_First_Bit_Offset : ASIS_Natural := 0;
Dynamic_Array : Boolean := False)
return Array_Component
is
Comp_Node : Node_Id;
Comp_Type_Entity : Node_Id;
Result : Array_Component := Nil_Array_Component;
Enclosing_Array_Type : Element;
Array_Entity : Entity_Id := Empty;
-- This should be a type entity defining the enclosed
-- array type. This may be an implicit type created by the compiler,
-- but the point is that in should contain real ranges for
-- this component
Dim : Asis.ASIS_Positive;
Tmp_Node : Node_Id;
Comp_Size : ASIS_Natural;
begin
Result.Parent_Array_Type := Array_Type_Definition;
Result.Parent_Component_Name :=
Component_Name (Enclosing_Record_Component);
Comp_Node := Node (Array_Type_Definition);
Comp_Type_Entity := Defining_Identifier (Parent (Comp_Node));
if Ekind (Comp_Type_Entity) in Object_Kind then
-- Array definition as a part of an object definition, here we have
-- an anonymous array type
Comp_Type_Entity := Etype (Etype (Comp_Type_Entity));
Array_Entity := Comp_Type_Entity;
end if;
Comp_Type_Entity := Component_Type (Comp_Type_Entity);
if Ekind (Comp_Type_Entity) = E_Private_Type then
Comp_Type_Entity := Full_View (Comp_Type_Entity);
end if;
Result.Is_Record_Comp := Is_Record_Type (Comp_Type_Entity);
Result.Is_Array_Comp := Is_Array_Type (Comp_Type_Entity);
if not Is_Nil (Enclosing_Record_Component) then
Array_Entity := R_Node (Enclosing_Record_Component.Component_Name);
Array_Entity := Etype (Array_Entity);
elsif not Is_Nil (Parent_Indication) then
Enclosing_Array_Type := Enclosing_Element (Parent_Indication);
Enclosing_Array_Type := Enclosing_Element (Enclosing_Array_Type);
Enclosing_Array_Type := Enclosing_Element (Enclosing_Array_Type);
Array_Entity := Defining_Identifier (R_Node (Enclosing_Array_Type));
Array_Entity := Component_Type (Array_Entity);
elsif No (Array_Entity) then
Enclosing_Array_Type := Enclosing_Element (Array_Type_Definition);
Array_Entity := Defining_Identifier (R_Node (Enclosing_Array_Type));
end if;
if Ekind (Array_Entity) = E_Private_Type then
Array_Entity := Full_View (Array_Entity);
end if;
Result.Array_Type_Entity := Array_Entity;
-- Computing dimentions and lengths:
Tmp_Node := First_Index (Array_Entity);
Dim := ASIS_Positive (List_Length (List_Containing (Tmp_Node)));
Result.Dimension := Dim;
Result.Length := (others => 0);
for I in 1 .. Dim loop
if Dynamic_Array then
Result.Length (I) := 0;
else
Result.Length (I) := Get_Length (Typ => Array_Entity,
Sub => I,
Discs => Parent_Discriminants);
end if;
end loop;
Comp_Size := ASIS_Natural (UI_To_Int (
Get_Component_Size (Array_Entity)));
Result.Position := Parent_First_Bit_Offset / Storage_Unit;
Result.First_Bit := Parent_First_Bit_Offset mod Storage_Unit;
Result.Last_Bit := Result.First_Bit + Comp_Size - 1;
Result.Size := Comp_Size;
Set_Parent_Discrims (Result, Parent_Discriminants);
Result.Parent_Context := Get_Current_Cont;
Result.Obtained := A_OS_Time;
return Result;
end Set_Array_Componnet;
------------------------------
-- Set_All_Named_Components --
------------------------------
procedure Set_All_Named_Components (E : Element) is
Discr_Part : Element;
begin
if Asis.Elements.Type_Kind (E) = A_Derived_Type_Definition then
Set_Derived_Type_Components (E);
else
Discr_Part := Discriminant_Part (Enclosing_Element (E));
Set_Named_Components (Discr_Part, New_List);
Set_Named_Components (E, Append);
end if;
end Set_All_Named_Components;
---------------------------------
-- Set_Derived_Type_Components --
---------------------------------
procedure Set_Derived_Type_Components (E : Asis.Element) is
Discr_Part : constant Asis.Element :=
Discriminant_Part (Enclosing_Element (E));
Impl_Comps : constant Asis.Element_List :=
Implicit_Inherited_Declarations (E);
begin
Set_Named_Components (Discr_Part, New_List);
for J in Impl_Comps'Range loop
Asis_Element_Table.Append (Names (Impl_Comps (J)) (1));
end loop;
end Set_Derived_Type_Components;
--------------------------
-- Set_Named_Components --
--------------------------
procedure Set_Named_Components (E : Element; List_Kind : List_Kinds) is
Control : Traverse_Control := Continue;
State : No_State := Not_Used;
procedure Set_Def_Name
(Element : Asis.Element;
Control : in out Traverse_Control;
State : in out No_State);
-- If Element is of A_Defining_Identifier kind, this procedure stores
-- it in the Asis Element Table. Used as Pre-Operation
procedure Set_Def_Name
(Element : Asis.Element;
Control : in out Traverse_Control;
State : in out No_State)
is
begin
pragma Unreferenced (Control);
pragma Unreferenced (State);
if Int_Kind (Element) /= A_Defining_Identifier then
return;
end if;
Asis_Element_Table.Append (Element);
end Set_Def_Name;
procedure Create_Name_List is new Traverse_Element (
State_Information => No_State,
Pre_Operation => Set_Def_Name,
Post_Operation => No_Op);
begin
if List_Kind = New_List then
Asis_Element_Table.Init;
end if;
if Is_Nil (E) then
return;
end if;
Create_Name_List
(Element => E,
Control => Control,
State => State);
end Set_Named_Components;
-------------------------
-- Set_Parent_Discrims --
-------------------------
procedure Set_Parent_Discrims (Comp : in out AC; Discs : Discrim_List) is
begin
if Discs = Null_Discrims then
Comp.Parent_Discrims := null;
else
Comp.Parent_Discrims := new Discrim_List'(Discs);
end if;
end Set_Parent_Discrims;
----------------------------
-- Set_Record_Type_Entity --
----------------------------
procedure Set_Record_Type_Entity (AC : Array_Component) is
begin
Record_Type_Entity := Get_Array_Type_Entity (AC);
Record_Type_Entity := Component_Type (Record_Type_Entity);
end Set_Record_Type_Entity;
procedure Set_Record_Type_Entity (RC : Record_Component) is
begin
Record_Type_Entity := R_Node (Component_Name (RC));
Record_Type_Entity := Etype (Record_Type_Entity);
end Set_Record_Type_Entity;
procedure Set_Record_Type_Entity is
begin
Record_Type_Entity :=
Defining_Identifier (Parent (R_Node (Parent_Type_Definition)));
end Set_Record_Type_Entity;
--------------------------------
-- Set_Parent_Type_Definition --
--------------------------------
procedure Set_Parent_Type_Definition (E : Element) is
begin
Parent_Type_Definition := E;
end Set_Parent_Type_Definition;
--------------------------------------
-- Set_Record_Components_From_Names --
--------------------------------------
procedure Set_Record_Components_From_Names
(Parent_First_Bit : ASIS_Natural := 0;
Data_Stream : Portable_Data := Nil_Portable_Data;
Discriminants : Boolean := False)
is
New_Comp : Asis.List_Index;
Component_Name : Element;
Comp_Entity : Node_Id;
Discs : constant Discrim_List :=
Build_Discrim_List_If_Data_Presented
(Rec => Record_Type_Entity,
Data => Data_Stream,
Ignore_Discs => Discriminants);
Comp_Type_Entity : Node_Id;
Comp_First_Bit_Offset : ASIS_Natural;
Comp_Position : ASIS_Natural;
Comp_Size : ASIS_Natural;
begin
Record_Component_Table.Init;
for I in 1 .. Asis_Element_Table.Last loop
Component_Name := Def_N_Table (I);
Comp_Entity := Node (Component_Name);
if Discs = Null_Discrims or else
Component_Present (Comp_Entity, Discs)
then
Record_Component_Table.Increment_Last;
New_Comp := Record_Component_Table.Last;
RC_Table (New_Comp).Parent_Record_Type := Parent_Type_Definition;
RC_Table (New_Comp).Component_Name := Component_Name;
Comp_Type_Entity := Etype (Comp_Entity);
if Ekind (Comp_Type_Entity) = E_Private_Type then
Comp_Type_Entity := Full_View (Comp_Type_Entity);
end if;
RC_Table (New_Comp).Is_Record_Comp :=
Is_Record_Type (Comp_Type_Entity);
RC_Table (New_Comp).Is_Array_Comp :=
Is_Array_Type (Comp_Type_Entity);
if Discs = Null_Discrims then
RC_Table (New_Comp).Parent_Discrims := null;
else
RC_Table (New_Comp).Parent_Discrims :=
new Discrim_List'(Discs);
end if;
Comp_First_Bit_Offset := Parent_First_Bit +
ASIS_Natural (UI_To_Int (
Get_Component_Bit_Offset (Comp_Entity, Discs)));
Comp_Position := Comp_First_Bit_Offset / Storage_Unit;
Comp_Size := ASIS_Natural (UI_To_Int
(Get_Esize (Comp_Entity, Discs)));
RC_Table (New_Comp).Position := Comp_Position;
RC_Table (New_Comp).First_Bit :=
Comp_First_Bit_Offset mod Storage_Unit;
RC_Table (New_Comp).Last_Bit :=
RC_Table (New_Comp).First_Bit + Comp_Size - 1;
RC_Table (New_Comp).Size := Comp_Size;
RC_Table (New_Comp).Parent_Context := Get_Current_Cont;
RC_Table (New_Comp).Obtained := A_OS_Time;
end if;
end loop;
end Set_Record_Components_From_Names;
end Asis.Data_Decomposition.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
|
|
2c7068102650cf005a7ae89db3452db403b4c3d3
|
awa/src/awa-commands-info.ads
|
awa/src/awa-commands-info.ads
|
-----------------------------------------------------------------------
-- akt-commands-info -- Info command to describe the current configuration
-- 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 GNAT.Command_Line;
with AWA.Commands.Drivers;
with AWA.Applications;
with AWA.Modules;
with ASF.Locales;
generic
with package Command_Drivers is new AWA.Commands.Drivers (<>);
package AWA.Commands.Info is
type Command_Type is new Command_Drivers.Application_Command_Type with record
Bundle : ASF.Locales.Bundle;
Long_List : aliased Boolean := False;
Value_Length : Positive := 50;
end record;
-- Print the configuration about the application.
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);
-- 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);
-- Write the help associated with the command.
overriding
procedure Help (Command : in out Command_Type;
Name : in String;
Context : in out Context_Type);
-- Print the configuration identified by the given name.
procedure Print (Command : in out Command_Type;
Name : in String;
Value : in String;
Default : in String;
Context : in out Context_Type);
procedure Print (Command : in out Command_Type;
Application : in out AWA.Applications.Application'Class;
Name : in String;
Default : in String;
Context : in out Context_Type);
procedure Print (Command : in out Command_Type;
Module : in AWA.Modules.Module'Class;
Name : in String;
Default : in String;
Context : in out Context_Type);
Command : aliased Command_Type;
end AWA.Commands.Info;
|
Add package AWA.Commands.Info to report configuration information
|
Add package AWA.Commands.Info to report configuration information
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
|
00640dac872e5ea7b8b9fdc14383f610197e858f
|
src/util-concurrent-pools.adb
|
src/util-concurrent-pools.adb
|
-----------------------------------------------------------------------
-- Util.Concurrent.Pools -- Concurrent Pools
-- 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;
package body Util.Concurrent.Pools is
-- ------------------------------
-- Get an element instance from the pool.
-- Wait until one instance gets available.
-- ------------------------------
procedure Get_Instance (From : in out Pool;
Item : out Element_Type) is
begin
From.List.Get_Instance (Item);
end Get_Instance;
-- ------------------------------
-- Put the element back to the pool.
-- ------------------------------
procedure Release (Into : in out Pool;
Item : in Element_Type) is
begin
Into.List.Release (Item);
end Release;
-- ------------------------------
-- Set the pool size.
-- ------------------------------
procedure Set_Size (Into : in out Pool;
Capacity : in Positive) is
begin
Into.List.Set_Size (Capacity);
end Set_Size;
-- ------------------------------
-- Release the pool elements.
-- ------------------------------
overriding
procedure Finalize (Object : in out Pool) is
begin
Object.List.Set_Size (0);
end Finalize;
-- Pool of objects
protected body Protected_Pool is
-- ------------------------------
-- Get an element instance from the pool.
-- Wait until one instance gets available.
-- ------------------------------
entry Get_Instance (Item : out Element_Type) when Available > 0 is
begin
Item := Elements (Available);
Available := Available - 1;
end Get_Instance;
-- ------------------------------
-- Put the element back to the pool.
-- ------------------------------
procedure Release (Item : in Element_Type) is
begin
Available := Available + 1;
Elements (Available) := Item;
end Release;
-- ------------------------------
-- Set the pool size.
-- ------------------------------
procedure Set_Size (Capacity : in Natural) is
procedure Free is new Ada.Unchecked_Deallocation (Element_Array, Element_Array_Access);
begin
if Capacity = 0 then
Free (Elements);
elsif Elements = null then
Elements := new Element_Array (1 .. Capacity);
else
declare
New_Array : Element_Array_Access := new Element_Array (1 .. Capacity);
begin
if Capacity > Elements'Size then
New_Array (1 .. Elements'Last) := Elements (1 .. Elements'Last);
else
New_Array (1 .. Capacity) := Elements (1 .. Capacity);
end if;
Free (Elements);
Elements := New_Array;
end;
end if;
end Set_Size;
end Protected_Pool;
end Util.Concurrent.Pools;
|
-----------------------------------------------------------------------
-- Util.Concurrent.Pools -- Concurrent Pools
-- Copyright (C) 2011, 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.Unchecked_Deallocation;
package body Util.Concurrent.Pools is
-- ------------------------------
-- Get an element instance from the pool.
-- Wait until one instance gets available.
-- ------------------------------
procedure Get_Instance (From : in out Pool;
Item : out Element_Type) is
begin
From.List.Get_Instance (Item);
end Get_Instance;
-- ------------------------------
-- Put the element back to the pool.
-- ------------------------------
procedure Release (Into : in out Pool;
Item : in Element_Type) is
begin
Into.List.Release (Item);
end Release;
-- ------------------------------
-- Set the pool size.
-- ------------------------------
procedure Set_Size (Into : in out Pool;
Capacity : in Positive) is
begin
Into.List.Set_Size (Capacity);
end Set_Size;
-- ------------------------------
-- Release the pool elements.
-- ------------------------------
overriding
procedure Finalize (Object : in out Pool) is
begin
Object.List.Set_Size (0);
end Finalize;
-- Pool of objects
protected body Protected_Pool is
-- ------------------------------
-- Get an element instance from the pool.
-- Wait until one instance gets available.
-- ------------------------------
entry Get_Instance (Item : out Element_Type) when Available > 0 is
begin
Item := Elements (Available);
Available := Available - 1;
end Get_Instance;
-- ------------------------------
-- Put the element back to the pool.
-- ------------------------------
procedure Release (Item : in Element_Type) is
begin
Available := Available + 1;
Elements (Available) := Item;
end Release;
-- ------------------------------
-- Set the pool size.
-- ------------------------------
procedure Set_Size (Capacity : in Natural) is
procedure Free is new Ada.Unchecked_Deallocation (Element_Array, Element_Array_Access);
begin
if Capacity = 0 then
Free (Elements);
elsif Elements = null then
Elements := new Element_Array (1 .. Capacity);
else
declare
New_Array : constant Element_Array_Access := new Element_Array (1 .. Capacity);
begin
if Capacity > Elements'Size then
New_Array (1 .. Elements'Last) := Elements (1 .. Elements'Last);
else
New_Array (1 .. Capacity) := Elements (1 .. Capacity);
end if;
Free (Elements);
Elements := New_Array;
end;
end if;
end Set_Size;
end Protected_Pool;
end Util.Concurrent.Pools;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util,Letractively/ada-util
|
ff94781516a3ba224341ee0902f7ed56911da2de
|
regtests/util-http-clients-tests.adb
|
regtests/util-http-clients-tests.adb
|
-----------------------------------------------------------------------
-- util-http-clients-tests -- Unit tests for HTTP client
-- 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 Util.Test_Caller;
with Util.Strings.Transforms;
with Util.Http.Tools;
with Util.Strings;
with Util.Log.Loggers;
package body Util.Http.Clients.Tests is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Tests");
package body Http_Tests is
package Caller is new Util.Test_Caller (Http_Test, "Http-" & NAME);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Get",
Test_Http_Get'Access);
Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Post",
Test_Http_Post'Access);
end Add_Tests;
overriding
procedure Set_Up (T : in out Http_Test) is
begin
Test (T).Set_Up;
Register;
end Set_Up;
end Http_Tests;
overriding
procedure Set_Up (T : in out Test) is
begin
Log.Info ("Starting test server");
T.Server := new Test_Server;
T.Server.Start;
end Set_Up;
overriding
procedure Tear_Down (T : in out Test) is
begin
if T.Server /= null then
Log.Info ("Stopping test server");
T.Server.Stop;
T.Server := null;
end if;
end Tear_Down;
-- ------------------------------
-- Process the line received by the server.
-- ------------------------------
overriding
procedure Process_Line (Into : in out Test_Server;
Line : in Ada.Strings.Unbounded.Unbounded_String;
Stream : in out Util.Streams.Texts.Reader_Stream'Class;
Client : in out Util.Streams.Sockets.Socket_Stream'Class) is
L : constant String := Ada.Strings.Unbounded.To_String (Line);
Pos : Natural := Util.Strings.Index (L, ' ');
begin
if Pos > 0 and Into.Method = UNKNOWN then
if L (L'First .. Pos - 1) = "GET" then
Into.Method := GET;
elsif L (L'First .. Pos - 1) = "POST" then
Into.Method := POST;
else
Into.Method := UNKNOWN;
end if;
end if;
Pos := Util.Strings.Index (L, ':');
if Pos > 0 then
if L (L'First .. Pos) = "Content-Type:" then
Into.Content_Type
:= Ada.Strings.Unbounded.To_Unbounded_String (L (Pos + 2 .. L'Last - 2));
elsif L (L'First .. Pos) = "Content-Length:" then
Into.Length := Natural'Value (L (Pos + 1 .. L'Last - 2));
end if;
end if;
if L'Length = 2 and then Into.Length > 0 then
for I in 1 .. Into.Length loop
declare
C : Character;
begin
Stream.Read (C);
Ada.Strings.Unbounded.Append (Into.Result, C);
end;
end loop;
declare
Output : Util.Streams.Texts.Print_Stream;
begin
Output.Initialize (Client'Unchecked_Access);
Output.Write ("HTTP/1.1 200 Found" & ASCII.CR & ASCII.LF);
Output.Write ("Content-Length: 4" & ASCII.CR & ASCII.LF);
Output.Write (ASCII.CR & ASCII.LF);
Output.Write ("OK" & ASCII.CR & ASCII.LF);
Output.Flush;
end;
end if;
Log.Info ("Received: {0}", L);
end Process_Line;
-- ------------------------------
-- Get the test server base URI.
-- ------------------------------
function Get_Uri (T : in Test) return String is
begin
return "http://" & T.Server.Get_Host & ":" & Util.Strings.Image (T.Server.Get_Port);
end Get_Uri;
-- ------------------------------
-- Test the http Get operation.
-- ------------------------------
procedure Test_Http_Get (T : in out Test) is
Request : Client;
Reply : Response;
begin
Request.Get ("http://www.google.com", Reply);
T.Assert (Reply.Get_Status = 200 or Reply.Get_Status = 302, "Get status is invalid");
Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_get.txt"), Reply, True);
-- Check the content.
declare
Content : constant String := Util.Strings.Transforms.To_Lower_Case (Reply.Get_Body);
begin
Util.Tests.Assert_Matches (T, ".*html.*", Content, "Invalid GET content");
end;
-- Check one header.
declare
Content : constant String := Reply.Get_Header ("Content-Type");
begin
T.Assert (Content'Length > 0, "Empty Content-Type header");
Util.Tests.Assert_Matches (T, ".*text/html.*", Content, "Invalid content type");
end;
end Test_Http_Get;
-- ------------------------------
-- Test the http POST operation.
-- ------------------------------
procedure Test_Http_Post (T : in out Test) is
Request : Client;
Reply : Response;
Uri : constant String := T.Get_Uri;
begin
Log.Info ("Post on " & Uri);
T.Server.Method := UNKNOWN;
Request.Post (Uri & "/post",
"p1=1", Reply);
T.Assert (T.Server.Method = POST, "Invalid method received by server");
Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type,
"Invalid content type received by server");
Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response");
Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_post.txt"), Reply, True);
end Test_Http_Post;
end Util.Http.Clients.Tests;
|
-----------------------------------------------------------------------
-- util-http-clients-tests -- Unit tests for HTTP client
-- 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.Unchecked_Deallocation;
with Util.Test_Caller;
with Util.Strings.Transforms;
with Util.Http.Tools;
with Util.Strings;
with Util.Log.Loggers;
package body Util.Http.Clients.Tests is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Tests");
package body Http_Tests is
package Caller is new Util.Test_Caller (Http_Test, "Http-" & NAME);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Get",
Test_Http_Get'Access);
Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Post",
Test_Http_Post'Access);
end Add_Tests;
overriding
procedure Set_Up (T : in out Http_Test) is
begin
Test (T).Set_Up;
Register;
end Set_Up;
end Http_Tests;
overriding
procedure Set_Up (T : in out Test) is
begin
Log.Info ("Starting test server");
T.Server := new Test_Server;
T.Server.Start;
end Set_Up;
overriding
procedure Tear_Down (T : in out Test) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Test_Server'Class,
Name => Test_Server_Access);
begin
if T.Server /= null then
Log.Info ("Stopping test server");
T.Server.Stop;
Free (T.Server);
T.Server := null;
end if;
end Tear_Down;
-- ------------------------------
-- Process the line received by the server.
-- ------------------------------
overriding
procedure Process_Line (Into : in out Test_Server;
Line : in Ada.Strings.Unbounded.Unbounded_String;
Stream : in out Util.Streams.Texts.Reader_Stream'Class;
Client : in out Util.Streams.Sockets.Socket_Stream'Class) is
L : constant String := Ada.Strings.Unbounded.To_String (Line);
Pos : Natural := Util.Strings.Index (L, ' ');
begin
if Pos > 0 and Into.Method = UNKNOWN then
if L (L'First .. Pos - 1) = "GET" then
Into.Method := GET;
elsif L (L'First .. Pos - 1) = "POST" then
Into.Method := POST;
else
Into.Method := UNKNOWN;
end if;
end if;
Pos := Util.Strings.Index (L, ':');
if Pos > 0 then
if L (L'First .. Pos) = "Content-Type:" then
Into.Content_Type
:= Ada.Strings.Unbounded.To_Unbounded_String (L (Pos + 2 .. L'Last - 2));
elsif L (L'First .. Pos) = "Content-Length:" then
Into.Length := Natural'Value (L (Pos + 1 .. L'Last - 2));
end if;
end if;
if L'Length = 2 and then Into.Length > 0 then
for I in 1 .. Into.Length loop
declare
C : Character;
begin
Stream.Read (C);
Ada.Strings.Unbounded.Append (Into.Result, C);
end;
end loop;
declare
Output : Util.Streams.Texts.Print_Stream;
begin
Output.Initialize (Client'Unchecked_Access);
Output.Write ("HTTP/1.1 200 Found" & ASCII.CR & ASCII.LF);
Output.Write ("Content-Length: 4" & ASCII.CR & ASCII.LF);
Output.Write (ASCII.CR & ASCII.LF);
Output.Write ("OK" & ASCII.CR & ASCII.LF);
Output.Flush;
end;
end if;
Log.Info ("Received: {0}", L);
end Process_Line;
-- ------------------------------
-- Get the test server base URI.
-- ------------------------------
function Get_Uri (T : in Test) return String is
begin
return "http://" & T.Server.Get_Host & ":" & Util.Strings.Image (T.Server.Get_Port);
end Get_Uri;
-- ------------------------------
-- Test the http Get operation.
-- ------------------------------
procedure Test_Http_Get (T : in out Test) is
Request : Client;
Reply : Response;
begin
Request.Get ("http://www.google.com", Reply);
T.Assert (Reply.Get_Status = 200 or Reply.Get_Status = 302, "Get status is invalid");
Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_get.txt"), Reply, True);
-- Check the content.
declare
Content : constant String := Util.Strings.Transforms.To_Lower_Case (Reply.Get_Body);
begin
Util.Tests.Assert_Matches (T, ".*html.*", Content, "Invalid GET content");
end;
-- Check one header.
declare
Content : constant String := Reply.Get_Header ("Content-Type");
begin
T.Assert (Content'Length > 0, "Empty Content-Type header");
Util.Tests.Assert_Matches (T, ".*text/html.*", Content, "Invalid content type");
end;
end Test_Http_Get;
-- ------------------------------
-- Test the http POST operation.
-- ------------------------------
procedure Test_Http_Post (T : in out Test) is
Request : Client;
Reply : Response;
Uri : constant String := T.Get_Uri;
begin
Log.Info ("Post on " & Uri);
T.Server.Method := UNKNOWN;
Request.Post (Uri & "/post",
"p1=1", Reply);
T.Assert (T.Server.Method = POST, "Invalid method received by server");
Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type,
"Invalid content type received by server");
Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response");
Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_post.txt"), Reply, True);
end Test_Http_Post;
end Util.Http.Clients.Tests;
|
Fix a memory leak in the unit test
|
Fix a memory leak in the unit test
|
Ada
|
apache-2.0
|
flottokarotto/ada-util,Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util
|
d43b9723f93d5e528538628784068fbd5d24435e
|
src/security-controllers-urls.adb
|
src/security-controllers-urls.adb
|
-----------------------------------------------------------------------
-- security-controllers-urls -- URL permission controller
-- 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 body Security.Controllers.URLs is
-- ------------------------------
-- Returns true if the user associated with the security context <b>Context</b> has
-- the permission to access the URL defined in <b>Permission</b>.
-- ------------------------------
overriding
function Has_Permission (Handler : in URL_Controller;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean is
begin
if Permission in Security.Policies.URLs.URL_Permission'Class then
return Handler.Manager.Has_Permission (Context,
Policies.URLs.URL_Permission'Class (Permission));
else
return False;
end if;
end Has_Permission;
end Security.Controllers.URLs;
|
Implement the URL controller
|
Implement the URL controller
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
|
c2dc74c94cd61718a6488d2a3310815a52317ee3
|
src/sys/http/aws/util-http-clients-aws__1.adb
|
src/sys/http/aws/util-http-clients-aws__1.adb
|
-----------------------------------------------------------------------
-- util-http-clients-web -- HTTP Clients with AWS implementation
-- Copyright (C) 2011, 2012, 2017, 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 Ada.Strings.Unbounded;
with Util.Http.Clients.AWS_I.Messages;
with Util.Http.Clients.AWS_I.Headers.Set;
with Util.Log.Loggers;
package body Util.Http.Clients.AWS is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Web");
Manager : aliased AWS_Http_Manager;
-- ------------------------------
-- Register the Http manager.
-- ------------------------------
procedure Register is
begin
Default_Http_Manager := Manager'Access;
end Register;
function To_Status (Code : in AWS_I.Messages.Status_Code) return Natural;
function To_Status (Code : in AWS_I.Messages.Status_Code) return Natural is
use AWS_I.Messages;
begin
case Code is
when S100 =>
return 100;
when S101 =>
return 101;
when S102 =>
return 102;
when S200 =>
return 200;
when S201 =>
return 201;
when S203 =>
return 203;
when S204 =>
return 204;
when S205 =>
return 205;
when S206 =>
return 206;
when S207 =>
return 207;
when S300 =>
return 300;
when S301 =>
return 301;
when S302 =>
return 302;
when S303 =>
return 303;
when S304 =>
return 304;
when S305 =>
return 305;
when S307 =>
return 307;
when S400 =>
return 400;
when S401 =>
return 401;
when S402 =>
return 402;
when S403 =>
return 403;
when S404 =>
return 404;
when S405 =>
return 405;
when S406 =>
return 406;
when S407 =>
return 407;
when S408 =>
return 408;
when S409 =>
return 409;
when S410 =>
return 410;
when S411 =>
return 411;
when S412 =>
return 412;
when S413 =>
return 413;
when S414 =>
return 414;
when S415 =>
return 415;
when S416 =>
return 416;
when S417 =>
return 417;
when S422 =>
return 422;
when S423 =>
return 423;
when S424 =>
return 424;
when S500 =>
return 500;
when S501 =>
return 501;
when S502 =>
return 502;
when S503 =>
return 503;
when S504 =>
return 504;
when S505 =>
return 505;
when S507 =>
return 507;
when others =>
return 500;
end case;
end To_Status;
procedure Create (Manager : in AWS_Http_Manager;
Http : in out Client'Class) is
pragma Unreferenced (Manager);
begin
Http.Delegate := new AWS_Http_Request;
end Create;
overriding
procedure Do_Get (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class) is
pragma Unreferenced (Manager);
Req : constant AWS_Http_Request_Access
:= AWS_Http_Request'Class (Http.Delegate.all)'Access;
Rep : constant AWS_Http_Response_Access := new AWS_Http_Response;
begin
Log.Info ("Get {0}", URI);
Reply.Delegate := Rep.all'Access;
Rep.Data := AWS_I.Client.Get (URL => URI, Headers => Req.Headers,
Timeouts => Req.Timeouts);
end Do_Get;
overriding
procedure Do_Post (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class) is
pragma Unreferenced (Manager);
Req : constant AWS_Http_Request_Access
:= AWS_Http_Request'Class (Http.Delegate.all)'Access;
Rep : constant AWS_Http_Response_Access := new AWS_Http_Response;
begin
Log.Info ("Post {0}", URI);
Reply.Delegate := Rep.all'Access;
Rep.Data := AWS_I.Client.Post (URL => URI, Data => Data,
Headers => Req.Headers,
Timeouts => Req.Timeouts);
end Do_Post;
overriding
procedure Do_Put (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class) is
pragma Unreferenced (Manager);
Req : constant AWS_Http_Request_Access
:= AWS_Http_Request'Class (Http.Delegate.all)'Access;
Rep : constant AWS_Http_Response_Access := new AWS_Http_Response;
begin
Log.Info ("Put {0}", URI);
Reply.Delegate := Rep.all'Access;
Rep.Data := AWS_I.Client.Put (URL => URI, Data => Data, Headers => Req.Headers,
Timeouts => Req.Timeouts);
end Do_Put;
overriding
procedure Do_Delete (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class) is
pragma Unreferenced (Manager, Http, Reply);
begin
Log.Info ("Delete {0}", URI);
raise Program_Error with "Delete is not supported by AWS and there is no easy conditional"
& " compilation in Ada to enable Delete support for the latest AWS version. "
& "For now, you have to use curl, or install the latest AWS version and then "
& "uncomment the AWS.Client.Delete call and remove this exception.";
end Do_Delete;
-- ------------------------------
-- Set the timeout for the connection.
-- ------------------------------
overriding
procedure Set_Timeout (Manager : in AWS_Http_Manager;
Http : in Client'Class;
Timeout : in Duration) is
pragma Unreferenced (Manager);
begin
AWS_Http_Request'Class (Http.Delegate.all).Timeouts
:= AWS_I.Client.Timeouts (Connect => Timeout,
Send => Timeout,
Receive => Timeout,
Response => Timeout);
end Set_Timeout;
-- ------------------------------
-- Returns a boolean indicating whether the named request header has already
-- been set.
-- ------------------------------
function Contains_Header (Http : in AWS_Http_Request;
Name : in String) return Boolean is
Values : constant AWS_I.Headers.VString_Array
:= AWS_I.Headers.Get_Values (Http.Headers, Name);
begin
return Values'Length > 0;
end Contains_Header;
-- ------------------------------
-- Returns the value of the specified request header as a String. If the request
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
-- ------------------------------
overriding
function Get_Header (Request : in AWS_Http_Request;
Name : in String) return String is
Values : constant AWS_I.Headers.VString_Array
:= AWS_I.Headers.Get_Values (Request.Headers, Name);
begin
if Values'Length > 0 then
return Ada.Strings.Unbounded.To_String (Values (Values'First));
else
return "";
end if;
end Get_Header;
-- ------------------------------
-- Sets a request header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
-- ------------------------------
overriding
procedure Set_Header (Http : in out AWS_Http_Request;
Name : in String;
Value : in String) is
begin
AWS_I.Headers.Set.Add (Http.Headers, Name, Value);
end Set_Header;
-- ------------------------------
-- Adds a request header with the given name and value.
-- This method allows request headers to have multiple values.
-- ------------------------------
overriding
procedure Add_Header (Http : in out AWS_Http_Request;
Name : in String;
Value : in String) is
begin
AWS_I.Headers.Set.Add (Http.Headers, Name, Value);
end Add_Header;
-- Iterate over the request headers and executes the <b>Process</b> procedure.
overriding
procedure Iterate_Headers (Request : in AWS_Http_Request;
Process : not null access
procedure (Name : in String;
Value : in String)) is
begin
null;
end Iterate_Headers;
-- ------------------------------
-- Returns a boolean indicating whether the named response header has already
-- been set.
-- ------------------------------
function Contains_Header (Reply : in AWS_Http_Response;
Name : in String) return Boolean is
begin
return AWS_I.Response.Header (Reply.Data, Name) /= "";
end Contains_Header;
-- ------------------------------
-- Returns the value of the specified response header as a String. If the response
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
-- ------------------------------
function Get_Header (Reply : in AWS_Http_Response;
Name : in String) return String is
begin
return AWS_I.Response.Header (Reply.Data, Name);
end Get_Header;
-- Sets a message header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
overriding
procedure Set_Header (Reply : in out AWS_Http_Response;
Name : in String;
Value : in String) is
begin
null;
end Set_Header;
-- Adds a request header with the given name and value.
-- This method allows request headers to have multiple values.
overriding
procedure Add_Header (Reply : in out AWS_Http_Response;
Name : in String;
Value : in String) is
begin
null;
end Add_Header;
-- Iterate over the response headers and executes the <b>Process</b> procedure.
overriding
procedure Iterate_Headers (Reply : in AWS_Http_Response;
Process : not null access
procedure (Name : in String;
Value : in String)) is
begin
null;
end Iterate_Headers;
-- ------------------------------
-- Get the response body as a string.
-- ------------------------------
function Get_Body (Reply : in AWS_Http_Response) return String is
begin
return AWS_I.Response.Message_Body (Reply.Data);
end Get_Body;
-- Get the response status code.
overriding
function Get_Status (Reply : in AWS_Http_Response) return Natural is
begin
return To_Status (AWS_I.Response.Status_Code (Reply.Data));
end Get_Status;
end Util.Http.Clients.AWS;
|
Add support for old AWS versions (Delete not available)
|
Add support for old AWS versions (Delete not available)
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
|
4188ab5450c3ffdc4b83075b357813998bfc2363
|
regtests/ado-drivers-tests.adb
|
regtests/ado-drivers-tests.adb
|
-----------------------------------------------------------------------
-- ado-drivers-tests -- Unit tests for database drivers
-- 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.Test_Caller;
with ADO.Drivers.Connections;
package body ADO.Drivers.Tests is
use ADO.Drivers.Connections;
package Caller is new Util.Test_Caller (Test, "ADO.Drivers");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Config",
Test_Get_Config'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver",
Test_Get_Driver'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver_Index",
Test_Get_Driver_Index'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver",
Test_Load_Invalid_Driver'Access);
end Add_Tests;
-- ------------------------------
-- Test the Get_Config operation.
-- ------------------------------
procedure Test_Get_Config (T : in out Test) is
begin
T.Assert (ADO.Drivers.Get_Config ("test.database")'Length > 0,
"The Get_Config operation returned no value for the test database");
end Test_Get_Config;
-- ------------------------------
-- Test the Get_Driver operation.
-- ------------------------------
procedure Test_Get_Driver (T : in out Test) is
Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql");
Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite");
begin
T.Assert (Mysql_Driver /= null or Sqlite_Driver /= null,
"No database driver was found!");
end Test_Get_Driver;
-- ------------------------------
-- Test loading some invalid database driver.
-- ------------------------------
procedure Test_Load_Invalid_Driver (T : in out Test) is
Invalid_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("invalid");
begin
T.Assert (Invalid_Driver = null,
"The Get_Driver operation must return null for invalid drivers");
end Test_Load_Invalid_Driver;
-- ------------------------------
-- Test the Get_Driver_Index operation.
-- ------------------------------
procedure Test_Get_Driver_Index (T : in out Test) is
Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql");
Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite");
begin
if Mysql_Driver /= null then
T.Assert (Mysql_Driver.Get_Driver_Index > 0, "The driver index must be positive");
end if;
if Sqlite_Driver /= null then
T.Assert (Sqlite_Driver.Get_Driver_Index > 0, "The driver index must be positive");
end if;
if Mysql_Driver /= null and Sqlite_Driver /= null then
T.Assert (Mysql_Driver.Get_Driver_Index /= Sqlite_Driver.Get_Driver_Index,
"Two drivers must have different driver indexes");
end if;
end Test_Get_Driver_Index;
end ADO.Drivers.Tests;
|
Implement the new tests for database drivers support
|
Implement the new tests for database drivers support
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
|
989c910941d5294609adc832c2de48017502c983
|
src/asis/asis-limited_views.adb
|
src/asis/asis-limited_views.adb
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT INTERFACE COMPONENTS --
-- --
-- A S I S . L I M I T E D _ V I E W S --
-- --
-- B o d y --
-- --
-- Copyright (C) 2010-2011, Free Software Foundation, Inc. --
-- --
-- This specification is added to be used together with the Ada Semantic --
-- Interface Specification Standard (ISO/IEC 15291) for use with GNAT. -- --
-- --
-- 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.Compilation_Units; use Asis.Compilation_Units;
with Asis.Elements; use Asis.Elements;
with Asis.Errors; use Asis.Errors;
with Asis.Exceptions; use Asis.Exceptions;
with Asis.Set_Get; use Asis.Set_Get;
with A4G.Asis_Tables;
with A4G.Contt.TT;
with A4G.Contt.UT;
with A4G.Mapping; use A4G.Mapping;
with A4G.Vcheck; use A4G.Vcheck;
with Atree; use Atree;
with Nlists; use Nlists;
with Sinfo; use Sinfo;
package body Asis.Limited_Views is
Package_Name : constant String := "Asis.Limited_Views.";
-------------------------
-- Get_Nonlimited_View --
-------------------------
function Get_Nonlimited_View (D : Asis.Element) return Asis.Element is
Encl_Unit : Asis.Compilation_Unit;
Arg_Node : Node_Id;
Res_Node : Node_Id;
Def_Name_Case : constant Boolean := Element_Kind (D) = A_Defining_Name;
begin
if not Is_From_Limited_View (D) then
Raise_ASIS_Inappropriate_Element
(Package_Name &
"Is_From_Limited_View (non-limited view as actual)",
Wrong_Kind => Int_Kind (D));
end if;
Encl_Unit := Enclosing_Compilation_Unit (D);
if Has_Limited_View_Only (Encl_Unit) then
return Nil_Element;
end if;
Arg_Node := Node (D);
if Def_Name_Case then
while not (Is_List_Member (Arg_Node)
or else
Nkind (Arg_Node) = N_Package_Declaration)
loop
Arg_Node := Parent (Arg_Node);
end loop;
end if;
A4G.Asis_Tables.Create_Node_Trace (Arg_Node);
A4G.Contt.TT.Reset_Tree_For_Unit (Encl_Unit);
Res_Node := A4G.Contt.TT.Restore_Node_From_Trace (CU => Encl_Unit);
if Def_Name_Case then
if Nkind (Res_Node) = N_Package_Declaration then
if Is_List_Member (Res_Node) then
Res_Node := Defining_Unit_Name (Sinfo.Specification (Res_Node));
else
Res_Node := Defining_Identifier (Res_Node);
end if;
end if;
end if;
return Node_To_Element_New
(Node => Res_Node,
In_Unit => Encl_Unit);
exception
when ASIS_Inappropriate_Element =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => D,
Outer_Call => Package_Name & "Get_Nonlimited_View");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Get_Nonlimited_View",
Ex => Ex,
Arg_Element => D);
end Get_Nonlimited_View;
---------------------------
-- Has_Limited_View_Only --
---------------------------
function Has_Limited_View_Only
(Right : Asis.Compilation_Unit)
return Boolean
is
Result : Boolean := False;
begin
if Unit_Kind (Right) = A_Package
and then
not Is_Standard (Right)
then
Result := A4G.Contt.UT.Has_Limited_View_Only
(Encl_Cont_Id (Right),
Get_Unit_Id (Right));
end if;
return Result;
exception
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Outer_Call => Package_Name & "Has_Limited_View_Only");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Has_Limited_View_Only",
Ex => Ex,
Arg_CU => Right);
end Has_Limited_View_Only;
--------------------------
-- Is_From_Limited_View --
--------------------------
function Is_From_Limited_View (D : Asis.Element) return Boolean is
begin
return Special_Case (D) = From_Limited_View;
end Is_From_Limited_View;
end Asis.Limited_Views;
|
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
|
|
78a114cf9bef01e1d03e0642d37d8edd4e6866f2
|
src/util-commands-parsers-gnat_parser.adb
|
src/util-commands-parsers-gnat_parser.adb
|
-----------------------------------------------------------------------
-- util-commands-parsers.gnat_parser -- GNAT command line parser for command drivers
-- 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.OS_Lib;
package body Util.Commands.Parsers.GNAT_Parser is
function To_OS_Lib_Argument_List (Args : in Argument_List'Class)
return GNAT.OS_Lib.Argument_List_Access;
function To_OS_Lib_Argument_List (Args : in Argument_List'Class)
return GNAT.OS_Lib.Argument_List_Access is
Count : constant Natural := Args.Get_Count;
New_Arg : GNAT.OS_Lib.Argument_List (1 .. Count);
begin
for I in 1 .. Count loop
New_Arg (I) := new String '(Args.Get_Argument (I));
end loop;
return new GNAT.OS_Lib.Argument_List '(New_Arg);
end To_OS_Lib_Argument_List;
procedure Execute (Config : in out Config_Type;
Args : in Util.Commands.Argument_List'Class;
Process : access procedure (Cmd_Args : in Commands.Argument_List'Class)) is
Parser : GNAT.Command_Line.Opt_Parser;
Cmd_Args : Dynamic_Argument_List;
Params : GNAT.OS_Lib.Argument_List_Access
:= To_OS_Lib_Argument_List (Args);
begin
GNAT.Command_Line.Initialize_Option_Scan (Parser, Params);
GNAT.Command_Line.Getopt (Config => Config, Parser => Parser);
loop
declare
S : constant String := GNAT.Command_Line.Get_Argument (Parser => Parser);
begin
exit when S'Length = 0;
Cmd_Args.List.Append (S);
end;
end loop;
Process (Cmd_Args);
GNAT.OS_Lib.Free (Params);
exception
when others =>
GNAT.OS_Lib.Free (Params);
raise;
end Execute;
end Util.Commands.Parsers.GNAT_Parser;
|
Implement the GNAT_Parser package to parse arguments using GNAT Getopt
|
Implement the GNAT_Parser package to parse arguments using GNAT Getopt
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
|
6fd84de489e5079cb66d96a5142ec816ac7b1148
|
regtests/babel-stores-local-tests.adb
|
regtests/babel-stores-local-tests.adb
|
-----------------------------------------------------------------------
-- babel-stores-local-tests - Unit tests for babel streams
-- 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 Util.Tests;
with Util.Test_Caller;
with Util.Encoders.SHA1;
with Util.Encoders.Base16;
with Babel.Files.Signatures;
package body Babel.Stores.Local.Tests is
package Caller is new Util.Test_Caller (Test, "Stores.Local");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Babel.Streams.Read",
Test_Read_File'Access);
end Add_Tests;
-- ------------------------------
-- Test the Read_File and Write_File operations.
-- ------------------------------
procedure Test_Read_File (T : in out Test) is
Buffers : aliased Babel.Files.Buffers.Buffer_Pool;
Local : aliased Babel.Stores.Local.Local_Store_Type;
Stream : Babel.Streams.Refs.Stream_Ref;
Sign : Util.Encoders.SHA1.Hash_Array;
Sign_Copy : Util.Encoders.SHA1.Hash_Array;
Hex : Util.Encoders.Base16.Encoder;
begin
Buffers.Create_Pool (Size => 16 * 1024,
Count => 10_000);
Local.Set_Buffers (Buffers'Unchecked_Access);
Local.Set_Root_Directory (Util.Tests.Get_Path (""));
Local.Read_File ("bin/babel_harness", Stream);
Local.Write_File ("regtests/result/babel_harness.copy", Stream, 8#755#);
Babel.Files.Signatures.Sha1 (Stream, Sign);
Local.Read_File ("regtests/result/babel_harness.copy", Stream);
Babel.Files.Signatures.Sha1 (Stream, Sign_Copy);
declare
S1 : constant String := Util.Encoders.Transform (Hex, Sign);
S2 : constant String := Util.Encoders.Transform (Hex, Sign_Copy);
begin
Util.Tests.Assert_Equals (T, S1, S2, "SHA1 comparison");
end;
end Test_Read_File;
end Babel.Stores.Local.Tests;
|
Implement the Test_Read_File procedure
|
Implement the Test_Read_File procedure
|
Ada
|
apache-2.0
|
stcarrez/babel
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.