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
|
---|---|---|---|---|---|---|---|---|---|
e5ab42737cfef659dfa5db2076b7b78bf630d876
|
src/wiki-streams-text_io.adb
|
src/wiki-streams-text_io.adb
|
-----------------------------------------------------------------------
-- wiki-streams-text_io -- Text_IO input output streams
-- Copyright (C) 2016, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
with Wiki.Helpers;
package body Wiki.Streams.Text_IO is
-- ------------------------------
-- Open the file and prepare to read the input stream.
-- ------------------------------
procedure Open (Stream : in out File_Input_Stream;
Path : in String;
Form : in String := "") is
begin
Ada.Wide_Wide_Text_IO.Open (Stream.File, Ada.Wide_Wide_Text_IO.In_File, Path, Form);
Stream.Stdin := False;
end Open;
-- ------------------------------
-- Close the file.
-- ------------------------------
procedure Close (Stream : in out File_Input_Stream) is
begin
if Ada.Wide_Wide_Text_IO.Is_Open (Stream.File) then
Ada.Wide_Wide_Text_IO.Close (Stream.File);
end if;
end Close;
-- ------------------------------
-- Close the stream.
-- ------------------------------
overriding
procedure Finalize (Stream : in out File_Input_Stream) is
begin
Stream.Close;
end Finalize;
-- ------------------------------
-- Read the input stream and fill the `Into` buffer until either it is full or
-- we reach the end of line. Returns in `Last` the last valid position in the
-- `Into` buffer. When there is no character to read, return True in
-- the `Eof` indicator.
-- ------------------------------
overriding
procedure Read (Input : in out File_Input_Stream;
Into : in out Wiki.Strings.WString;
Last : out Natural;
Eof : out Boolean) is
Available : Boolean;
Pos : Natural := Into'First;
Char : Wiki.Strings.WChar;
begin
if Input.Stdin then
if not Ada.Wide_Wide_Text_Io.End_Of_File then
Ada.Wide_Wide_Text_IO.Get_Line (Into, Last);
if Last < Into'Last then
Into (Last + 1) := Helpers.Lf;
Last := Last + 1;
end if;
Eof := False;
else
Last := Into'First - 1;
Eof := True;
end if;
else
if not Ada.Wide_Wide_Text_Io.End_Of_File (Input.File) then
Ada.Wide_Wide_Text_IO.Get_Line (Input.File, Into, Last);
if Last < Into'Last then
Into (Last + 1) := Helpers.Lf;
Last := Last + 1;
end if;
Eof := False;
else
Last := Into'First - 1;
Eof := True;
end if;
end if;
-- Eof := False;
-- while Pos <= Into'Last loop
-- if Input.Stdin then
-- Ada.Wide_Wide_Text_IO.Get_Immediate (Char, Available);
-- else
-- Ada.Wide_Wide_Text_IO.Get_Immediate (Input.File, Char, Available);
-- end if;
-- Into (Pos) := Char;
-- Pos := Pos + 1;
-- exit when Char = Helpers.LF or Char = Helpers.CR;
-- end loop;
-- Last := Pos - 1;
exception
when Ada.IO_Exceptions.End_Error =>
Last := Pos - 1;
Eof := True;
end Read;
-- ------------------------------
-- Open the file and prepare to write the output stream.
-- ------------------------------
procedure Open (Stream : in out File_Output_Stream;
Path : in String;
Form : in String := "") is
begin
if Ada.Wide_Wide_Text_IO.Is_Open (Stream.File) then
Ada.Wide_Wide_Text_IO.Close (Stream.File);
end if;
Ada.Wide_Wide_Text_IO.Open (Stream.File, Ada.Wide_Wide_Text_IO.Out_File, Path, Form);
Ada.Wide_Wide_Text_IO.Set_Line_Length (Ada.Wide_Wide_Text_IO.Count'Last);
Stream.Stdout := False;
end Open;
-- ------------------------------
-- Create the file and prepare to write the output stream.
-- ------------------------------
procedure Create (Stream : in out File_Output_Stream;
Path : in String;
Form : in String := "") is
begin
Ada.Wide_Wide_Text_IO.Create (Stream.File, Ada.Wide_Wide_Text_IO.Out_File, Path, Form);
Ada.Wide_Wide_Text_IO.Set_Line_Length (Ada.Wide_Wide_Text_IO.Count'Last);
Stream.Stdout := False;
end Create;
-- ------------------------------
-- Close the file.
-- ------------------------------
procedure Close (Stream : in out File_Output_Stream) is
begin
if Ada.Wide_Wide_Text_IO.Is_Open (Stream.File) then
Ada.Wide_Wide_Text_IO.Close (Stream.File);
end if;
end Close;
-- ------------------------------
-- Write the string to the output stream.
-- ------------------------------
overriding
procedure Write (Stream : in out File_Output_Stream;
Content : in Wiki.Strings.WString) is
begin
if not Stream.Stdout then
Ada.Wide_Wide_Text_IO.Put (Stream.File, Content);
else
Ada.Wide_Wide_Text_IO.Put (Content);
end if;
end Write;
-- ------------------------------
-- Write a single character to the output stream.
-- ------------------------------
overriding
procedure Write (Stream : in out File_Output_Stream;
Char : in Wiki.Strings.WChar) is
begin
if not Stream.Stdout then
Ada.Wide_Wide_Text_IO.Put (Stream.File, Char);
else
Ada.Wide_Wide_Text_IO.Put (Char);
end if;
end Write;
-- ------------------------------
-- Close the stream.
-- ------------------------------
overriding
procedure Finalize (Stream : in out File_Output_Stream) is
begin
Stream.Close;
end Finalize;
end Wiki.Streams.Text_IO;
|
-----------------------------------------------------------------------
-- wiki-streams-text_io -- Text_IO input output streams
-- Copyright (C) 2016, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
with Wiki.Helpers;
package body Wiki.Streams.Text_IO is
-- ------------------------------
-- Open the file and prepare to read the input stream.
-- ------------------------------
procedure Open (Stream : in out File_Input_Stream;
Path : in String;
Form : in String := "") is
begin
Ada.Wide_Wide_Text_IO.Open (Stream.File, Ada.Wide_Wide_Text_IO.In_File, Path, Form);
Stream.Stdin := False;
end Open;
-- ------------------------------
-- Close the file.
-- ------------------------------
procedure Close (Stream : in out File_Input_Stream) is
begin
if Ada.Wide_Wide_Text_IO.Is_Open (Stream.File) then
Ada.Wide_Wide_Text_IO.Close (Stream.File);
end if;
end Close;
-- ------------------------------
-- Close the stream.
-- ------------------------------
overriding
procedure Finalize (Stream : in out File_Input_Stream) is
begin
Stream.Close;
end Finalize;
-- ------------------------------
-- Read the input stream and fill the `Into` buffer until either it is full or
-- we reach the end of line. Returns in `Last` the last valid position in the
-- `Into` buffer. When there is no character to read, return True in
-- the `Eof` indicator.
-- ------------------------------
overriding
procedure Read (Input : in out File_Input_Stream;
Into : in out Wiki.Strings.WString;
Last : out Natural;
Eof : out Boolean) is
begin
if Input.Stdin then
if not Ada.Wide_Wide_Text_IO.End_Of_File then
Ada.Wide_Wide_Text_IO.Get_Line (Into, Last);
if Last < Into'Last then
Into (Last + 1) := Helpers.LF;
Last := Last + 1;
end if;
Eof := False;
else
Last := Into'First - 1;
Eof := True;
end if;
else
if not Ada.Wide_Wide_Text_IO.End_Of_File (Input.File) then
Ada.Wide_Wide_Text_IO.Get_Line (Input.File, Into, Last);
if Last < Into'Last then
Into (Last + 1) := Helpers.LF;
Last := Last + 1;
end if;
Eof := False;
else
Last := Into'First - 1;
Eof := True;
end if;
end if;
exception
when Ada.IO_Exceptions.End_Error =>
Last := Into'First - 1;
Eof := True;
end Read;
-- ------------------------------
-- Open the file and prepare to write the output stream.
-- ------------------------------
procedure Open (Stream : in out File_Output_Stream;
Path : in String;
Form : in String := "") is
begin
if Ada.Wide_Wide_Text_IO.Is_Open (Stream.File) then
Ada.Wide_Wide_Text_IO.Close (Stream.File);
end if;
Ada.Wide_Wide_Text_IO.Open (Stream.File, Ada.Wide_Wide_Text_IO.Out_File, Path, Form);
Ada.Wide_Wide_Text_IO.Set_Line_Length (Ada.Wide_Wide_Text_IO.Count'Last);
Stream.Stdout := False;
end Open;
-- ------------------------------
-- Create the file and prepare to write the output stream.
-- ------------------------------
procedure Create (Stream : in out File_Output_Stream;
Path : in String;
Form : in String := "") is
begin
Ada.Wide_Wide_Text_IO.Create (Stream.File, Ada.Wide_Wide_Text_IO.Out_File, Path, Form);
Ada.Wide_Wide_Text_IO.Set_Line_Length (Ada.Wide_Wide_Text_IO.Count'Last);
Stream.Stdout := False;
end Create;
-- ------------------------------
-- Close the file.
-- ------------------------------
procedure Close (Stream : in out File_Output_Stream) is
begin
if Ada.Wide_Wide_Text_IO.Is_Open (Stream.File) then
Ada.Wide_Wide_Text_IO.Close (Stream.File);
end if;
end Close;
-- ------------------------------
-- Write the string to the output stream.
-- ------------------------------
overriding
procedure Write (Stream : in out File_Output_Stream;
Content : in Wiki.Strings.WString) is
begin
if not Stream.Stdout then
Ada.Wide_Wide_Text_IO.Put (Stream.File, Content);
else
Ada.Wide_Wide_Text_IO.Put (Content);
end if;
end Write;
-- ------------------------------
-- Write a single character to the output stream.
-- ------------------------------
overriding
procedure Write (Stream : in out File_Output_Stream;
Char : in Wiki.Strings.WChar) is
begin
if not Stream.Stdout then
Ada.Wide_Wide_Text_IO.Put (Stream.File, Char);
else
Ada.Wide_Wide_Text_IO.Put (Char);
end if;
end Write;
-- ------------------------------
-- Close the stream.
-- ------------------------------
overriding
procedure Finalize (Stream : in out File_Output_Stream) is
begin
Stream.Close;
end Finalize;
end Wiki.Streams.Text_IO;
|
Fix compilation warnings: remove unused local variables
|
Fix compilation warnings: remove unused local variables
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
c5df7c0f6320048afcdef2920039addc8b7b155c
|
matp/regtests/mat-expressions-tests.adb
|
matp/regtests/mat-expressions-tests.adb
|
-----------------------------------------------------------------------
-- mat-expressions-tests -- Unit tests for MAT expressions
-- 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.Directories;
with Util.Test_Caller;
with Util.Assertions;
package body MAT.Expressions.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Expressions");
procedure Assert_Equals_Kind is
new Util.Assertions.Assert_Equals_T (Value_Type => Kind_Type);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test MAT.Expressions.Parse",
Test_Parse_Expression'Access);
end Add_Tests;
-- ------------------------------
-- Test parsing simple expressions
-- ------------------------------
procedure Test_Parse_Expression (T : in out Test) is
Result : MAT.Expressions.Expression_Type;
begin
Result := MAT.Expressions.Parse ("by foo", null);
T.Assert (Result.Node /= null, "Parse 'by foo' must return a expression");
Assert_Equals_Kind (T, N_INSIDE, Result.Node.Kind, "Invalid node kind");
Result := MAT.Expressions.Parse ("by direct foo", null);
T.Assert (Result.Node /= null, "Parse 'by direct foo' must return a expression");
Assert_Equals_Kind (T, N_INSIDE, Result.Node.Kind, "Invalid node kind");
Result := MAT.Expressions.Parse ("after foo", null);
T.Assert (Result.Node /= null, "Parse 'after foo' must return a expression");
-- Assert_Equals_Kind (T, N_INSIDE, Result.Node.Kind, "Invalid node kind");
Result := MAT.Expressions.Parse ("before foo", null);
T.Assert (Result.Node /= null, "Parse 'before foo' must return a expression");
-- Assert_Equals_Kind (T, N_INSIDE, Result.Node.Kind, "Invalid node kind");
Result := MAT.Expressions.Parse ("with size in [10,100]", null);
T.Assert (Result.Node /= null, "Parse 'by direct foo' must return a expression");
Assert_Equals_Kind (T, N_RANGE_SIZE, Result.Node.Kind, "Invalid node kind");
Result := MAT.Expressions.Parse ("with size in [10..100]", null);
T.Assert (Result.Node /= null, "Parse 'by direct foo' must return a expression");
Assert_Equals_Kind (T, N_RANGE_SIZE, Result.Node.Kind, "Invalid node kind");
end Test_Parse_Expression;
end MAT.Expressions.Tests;
|
-----------------------------------------------------------------------
-- mat-expressions-tests -- Unit tests for MAT expressions
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Util.Test_Caller;
with Util.Assertions;
package body MAT.Expressions.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Expressions");
procedure Assert_Equals_Kind is
new Util.Assertions.Assert_Equals_T (Value_Type => Kind_Type);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test MAT.Expressions.Parse",
Test_Parse_Expression'Access);
end Add_Tests;
-- ------------------------------
-- Test parsing simple expressions
-- ------------------------------
procedure Test_Parse_Expression (T : in out Test) is
Result : MAT.Expressions.Expression_Type;
begin
Result := MAT.Expressions.Parse ("by foo", null);
T.Assert (Result.Node /= null, "Parse 'by foo' must return a expression");
Assert_Equals_Kind (T, N_IN_FUNC, Result.Node.Kind, "Invalid node kind");
Result := MAT.Expressions.Parse ("by direct foo", null);
T.Assert (Result.Node /= null, "Parse 'by direct foo' must return a expression");
Assert_Equals_Kind (T, N_IN_FUNC_DIRECT, Result.Node.Kind, "Invalid node kind");
Result := MAT.Expressions.Parse ("after foo", null);
T.Assert (Result.Node /= null, "Parse 'after foo' must return a expression");
-- Assert_Equals_Kind (T, N_INSIDE, Result.Node.Kind, "Invalid node kind");
Result := MAT.Expressions.Parse ("before foo", null);
T.Assert (Result.Node /= null, "Parse 'before foo' must return a expression");
-- Assert_Equals_Kind (T, N_INSIDE, Result.Node.Kind, "Invalid node kind");
Result := MAT.Expressions.Parse ("size = 10", null);
T.Assert (Result.Node /= null, "Parse 'size = 10' must return a expression");
Assert_Equals_Kind (T, N_RANGE_SIZE, Result.Node.Kind, "Invalid node kind");
Result := MAT.Expressions.Parse ("size > 10", null);
T.Assert (Result.Node /= null, "Parse 'size > 10' must return a expression");
Assert_Equals_Kind (T, N_RANGE_SIZE, Result.Node.Kind, "Invalid node kind");
Result := MAT.Expressions.Parse ("size < 10", null);
T.Assert (Result.Node /= null, "Parse 'size < 10' must return a expression");
Assert_Equals_Kind (T, N_RANGE_SIZE, Result.Node.Kind, "Invalid node kind");
Result := MAT.Expressions.Parse ("event = 23", null);
T.Assert (Result.Node /= null, "Parse 'event = 23' must return a expression");
Assert_Equals_Kind (T, N_EVENT, Result.Node.Kind, "Invalid node kind");
Result := MAT.Expressions.Parse ("event = 1..100", null);
T.Assert (Result.Node /= null, "Parse 'event = 1..100' must return a expression");
Assert_Equals_Kind (T, N_EVENT, Result.Node.Kind, "Invalid node kind");
end Test_Parse_Expression;
end MAT.Expressions.Tests;
|
Add some unit tests for expressions
|
Add some unit tests for expressions
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
f7cec8d22f4f13c44cc6a71da43fc7d7de821140
|
testutil/ahven/ahven-text_runner.adb
|
testutil/ahven/ahven-text_runner.adb
|
--
-- Copyright (c) 2007-2009 Tero Koskinen <[email protected]>
--
-- Permission to use, copy, modify, and distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
--
with Ada.Text_IO;
with Ada.Strings.Fixed;
with Ada.Characters.Latin_1;
with Ahven.Runner;
with Ahven.XML_Runner;
with Ahven.AStrings;
use Ada.Text_IO;
use Ada.Strings.Fixed;
package body Ahven.Text_Runner is
use Ahven.Results;
use Ahven.Framework;
use Ahven.AStrings;
-- Local procedures
procedure Pad (Level : Natural);
procedure Print_Test (Info : Result_Info;
Level : Natural;
Result : String);
procedure Print_Passes (Result : Result_Collection;
Level : Natural);
procedure Report_Results (Result : Result_Collection;
Verbose : Boolean := False);
procedure Print_Log_File (Filename : String);
procedure Pad (Level : Natural) is
begin
for A in Integer range 1 .. Level loop
Put (" ");
end loop;
end Pad;
procedure Pad (Amount : in Natural;
Total : in out Natural) is
begin
for A in Natural range 1 .. Amount loop
Put (" ");
end loop;
Total := Total + Amount;
end Pad;
procedure Multiline_Pad (Input : String;
Level : Natural) is
begin
Pad (Level);
for A in Input'Range loop
Put (Input (A));
if (Input (A) = Ada.Characters.Latin_1.LF) and (A /= Input'Last) then
Pad (Level);
end if;
end loop;
end Multiline_Pad;
procedure Print_Test (Info : Result_Info;
Level : Natural;
Result : String) is
use Ada.Strings;
Max_Output_Width : constant := 50;
Max_Result_Width : constant := 7;
Max_Time_Out_Width : constant := 12;
subtype Result_Size is Integer range 1 .. Max_Result_Width;
subtype Time_Out_Size is Integer range 1 .. Max_Time_Out_Width;
procedure Print_Text (Str : String; Total : in out Natural) is
begin
Put (Str);
Total := Total + Str'Length;
end Print_Text;
Msg : constant String := Get_Message (Info);
Result_Out : String (Result_Size) := (others => ' ');
Time_Out : String (Time_Out_Size) := (others => ' ');
Total_Text : Natural := 0;
begin
Pad (Level + 1, Total_Text);
Print_Text (Get_Routine_Name (Info), Total_Text);
if Msg'Length > 0 then
Print_Text (" - ", Total_Text);
Print_Text (Msg, Total_Text);
end if;
if Total_Text < Max_Output_Width then
Pad (Max_Output_Width - Total_Text, Total_Text);
end if;
-- If we know the name of the routine, we print it,
-- the result, and the execution time.
if Get_Routine_Name (Info)'Length > 0 then
Move (Source => Result,
Target => Result_Out,
Drop => Right,
Justify => Left,
Pad => ' ');
Move (Source => Duration'Image (Get_Execution_Time (Info)),
Target => Time_Out,
Drop => Right,
Justify => Right,
Pad => ' ');
Put (" " & Result_Out);
Put (" " & Time_Out & "s");
end if;
if Get_Long_Message (Info)'Length > 0 then
New_Line;
Multiline_Pad (Get_Long_Message (Info), Level + 2);
end if;
New_Line;
end Print_Test;
type Print_Child_Proc is access
procedure (Result : Result_Collection; Level : Natural);
type Child_Count_Proc is access
function (Result : Result_Collection) return Natural;
procedure Print_Children (Result : Result_Collection;
Level : Natural;
Action : Print_Child_Proc;
Count : Child_Count_Proc)
is
Child_Iter : Result_Collection_Cursor := First_Child (Result);
begin
loop
exit when not Is_Valid (Child_Iter);
if Count.all (Data (Child_Iter).all) > 0 then
Action.all (Data (Child_Iter).all, Level + 1);
end if;
Child_Iter := Next (Child_Iter);
end loop;
end Print_Children;
procedure Print_Statuses (Result : Result_Collection;
Level : Natural;
Start : Result_Info_Cursor;
Action : Print_Child_Proc;
Status : String;
Count : Child_Count_Proc;
Print_Log : Boolean) is
Position : Result_Info_Cursor := Start;
begin
if Length (Get_Test_Name (Result)) > 0 then
Pad (Level);
Put_Line (To_String (Get_Test_Name (Result)) & ":");
end if;
Test_Loop :
loop
exit Test_Loop when not Is_Valid (Position);
Print_Test (Data (Position), Level, Status);
if Print_Log and
(Length (Get_Output_File (Data (Position))) > 0) then
Print_Log_File (To_String (Get_Output_File (Data (Position))));
end if;
Position := Next (Position);
end loop Test_Loop;
Print_Children (Result => Result,
Level => Level,
Action => Action,
Count => Count);
end Print_Statuses;
--
-- Print all failures from the result collection
-- and then recurse into child collections.
--
procedure Print_Failures (Result : Result_Collection;
Level : Natural) is
begin
Print_Statuses
(Result => Result,
Level => Level,
Start => First_Failure (Result),
Action => Print_Failures'Access,
Status => "FAIL",
Count => Failure_Count'Access,
Print_Log => True);
end Print_Failures;
--
-- Print all skips from the result collection
-- and then recurse into child collections.
--
procedure Print_Skips (Result : Result_Collection;
Level : Natural) is
begin
Print_Statuses
(Result => Result,
Level => Level,
Start => First_Skipped (Result),
Action => Print_Skips'Access,
Status => "SKIPPED",
Count => Skipped_Count'Access,
Print_Log => True);
end Print_Skips;
--
-- Print all errors from the result collection
-- and then recurse into child collections.
--
procedure Print_Errors (Result : Result_Collection;
Level : Natural) is
begin
Print_Statuses
(Result => Result,
Level => Level,
Start => First_Error (Result),
Action => Print_Errors'Access,
Status => "ERROR",
Count => Error_Count'Access,
Print_Log => True);
end Print_Errors;
--
-- Print all passes from the result collection
-- and then recurse into child collections.
--
procedure Print_Passes (Result : Result_Collection;
Level : Natural) is
begin
Print_Statuses
(Result => Result,
Level => Level,
Start => First_Pass (Result),
Action => Print_Passes'Access,
Status => "PASS",
Count => Pass_Count'Access,
Print_Log => False);
end Print_Passes;
--
-- Report passes, skips, failures, and errors from the result collection.
procedure Report_Results (Result : Result_Collection;
Verbose : Boolean := False) is
begin
Put_Line ("Passed : " & Integer'Image (Pass_Count (Result)));
if Verbose then
Print_Passes (Result, 0);
end if;
New_Line;
if Skipped_Count (Result) > 0 then
Put_Line ("Skipped : " & Integer'Image (Skipped_Count (Result)));
Print_Skips (Result, 0);
New_Line;
end if;
if Failure_Count (Result) > 0 then
Put_Line ("Failed : " & Integer'Image (Failure_Count (Result)));
Print_Failures (Result, 0);
New_Line;
end if;
if Error_Count (Result) > 0 then
Put_Line ("Errors : " & Integer'Image (Error_Count (Result)));
Print_Errors (Result, 0);
end if;
end Report_Results;
procedure Print_Log_File (Filename : String) is
Handle : File_Type;
Char : Character := ' ';
First : Boolean := True;
begin
Open (Handle, In_File, Filename);
loop
exit when End_Of_File (Handle);
Get (Handle, Char);
if First then
Put_Line ("===== Output =======");
First := False;
end if;
Put (Char);
if End_Of_Line (Handle) then
New_Line;
end if;
end loop;
Close (Handle);
if not First then
Put_Line ("====================");
end if;
end Print_Log_File;
procedure Do_Report (Test_Results : Results.Result_Collection;
Args : Parameters.Parameter_Info) is
begin
if Parameters.XML_Results (Args) then
XML_Runner.Report_Results
(Test_Results, Parameters.Result_Dir (Args));
else
Report_Results (Test_Results, Parameters.Verbose (Args));
end if;
end Do_Report;
procedure Run (Suite : in out Framework.Test'Class) is
begin
Runner.Run_Suite (Suite, Do_Report'Access);
end Run;
procedure Run (Suite : Framework.Test_Suite_Access) is
begin
Run (Suite.all);
end Run;
end Ahven.Text_Runner;
|
--
-- Copyright (c) 2007-2009 Tero Koskinen <[email protected]>
--
-- Permission to use, copy, modify, and distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
--
with Ada.Text_IO;
with Ada.Strings.Fixed;
with Ada.Characters.Latin_1;
with Ada.IO_Exceptions;
with Ahven.Runner;
with Ahven.XML_Runner;
with Ahven.AStrings;
use Ada.Text_IO;
use Ada.Strings.Fixed;
package body Ahven.Text_Runner is
use Ahven.Results;
use Ahven.Framework;
use Ahven.AStrings;
-- Local procedures
procedure Pad (Level : Natural);
procedure Print_Test (Info : Result_Info;
Level : Natural;
Result : String);
procedure Print_Passes (Result : Result_Collection;
Level : Natural);
procedure Report_Results (Result : Result_Collection;
Verbose : Boolean := False);
procedure Print_Log_File (Filename : String);
procedure Pad (Level : Natural) is
begin
for A in Integer range 1 .. Level loop
Put (" ");
end loop;
end Pad;
procedure Pad (Amount : in Natural;
Total : in out Natural) is
begin
for A in Natural range 1 .. Amount loop
Put (" ");
end loop;
Total := Total + Amount;
end Pad;
procedure Multiline_Pad (Input : String;
Level : Natural) is
begin
Pad (Level);
for A in Input'Range loop
Put (Input (A));
if (Input (A) = Ada.Characters.Latin_1.LF) and (A /= Input'Last) then
Pad (Level);
end if;
end loop;
end Multiline_Pad;
procedure Print_Test (Info : Result_Info;
Level : Natural;
Result : String) is
use Ada.Strings;
Max_Output_Width : constant := 50;
Max_Result_Width : constant := 7;
Max_Time_Out_Width : constant := 12;
subtype Result_Size is Integer range 1 .. Max_Result_Width;
subtype Time_Out_Size is Integer range 1 .. Max_Time_Out_Width;
procedure Print_Text (Str : String; Total : in out Natural) is
begin
Put (Str);
Total := Total + Str'Length;
end Print_Text;
Msg : constant String := Get_Message (Info);
Result_Out : String (Result_Size) := (others => ' ');
Time_Out : String (Time_Out_Size) := (others => ' ');
Total_Text : Natural := 0;
begin
Pad (Level + 1, Total_Text);
Print_Text (Get_Routine_Name (Info), Total_Text);
if Msg'Length > 0 then
Print_Text (" - ", Total_Text);
Print_Text (Msg, Total_Text);
end if;
if Total_Text < Max_Output_Width then
Pad (Max_Output_Width - Total_Text, Total_Text);
end if;
-- If we know the name of the routine, we print it,
-- the result, and the execution time.
if Get_Routine_Name (Info)'Length > 0 then
Move (Source => Result,
Target => Result_Out,
Drop => Right,
Justify => Left,
Pad => ' ');
Move (Source => Duration'Image (Get_Execution_Time (Info)),
Target => Time_Out,
Drop => Right,
Justify => Right,
Pad => ' ');
Put (" " & Result_Out);
Put (" " & Time_Out & "s");
end if;
if Get_Long_Message (Info)'Length > 0 then
New_Line;
Multiline_Pad (Get_Long_Message (Info), Level + 2);
end if;
New_Line;
end Print_Test;
type Print_Child_Proc is access
procedure (Result : Result_Collection; Level : Natural);
type Child_Count_Proc is access
function (Result : Result_Collection) return Natural;
procedure Print_Children (Result : Result_Collection;
Level : Natural;
Action : Print_Child_Proc;
Count : Child_Count_Proc)
is
Child_Iter : Result_Collection_Cursor := First_Child (Result);
begin
loop
exit when not Is_Valid (Child_Iter);
if Count.all (Data (Child_Iter).all) > 0 then
Action.all (Data (Child_Iter).all, Level + 1);
end if;
Child_Iter := Next (Child_Iter);
end loop;
end Print_Children;
procedure Print_Statuses (Result : Result_Collection;
Level : Natural;
Start : Result_Info_Cursor;
Action : Print_Child_Proc;
Status : String;
Count : Child_Count_Proc;
Print_Log : Boolean) is
Position : Result_Info_Cursor := Start;
begin
if Length (Get_Test_Name (Result)) > 0 then
Pad (Level);
Put_Line (To_String (Get_Test_Name (Result)) & ":");
end if;
Test_Loop :
loop
exit Test_Loop when not Is_Valid (Position);
Print_Test (Data (Position), Level, Status);
if Print_Log and
(Length (Get_Output_File (Data (Position))) > 0) then
Print_Log_File (To_String (Get_Output_File (Data (Position))));
end if;
Position := Next (Position);
end loop Test_Loop;
Print_Children (Result => Result,
Level => Level,
Action => Action,
Count => Count);
end Print_Statuses;
--
-- Print all failures from the result collection
-- and then recurse into child collections.
--
procedure Print_Failures (Result : Result_Collection;
Level : Natural) is
begin
Print_Statuses
(Result => Result,
Level => Level,
Start => First_Failure (Result),
Action => Print_Failures'Access,
Status => "FAIL",
Count => Failure_Count'Access,
Print_Log => True);
end Print_Failures;
--
-- Print all skips from the result collection
-- and then recurse into child collections.
--
procedure Print_Skips (Result : Result_Collection;
Level : Natural) is
begin
Print_Statuses
(Result => Result,
Level => Level,
Start => First_Skipped (Result),
Action => Print_Skips'Access,
Status => "SKIPPED",
Count => Skipped_Count'Access,
Print_Log => True);
end Print_Skips;
--
-- Print all errors from the result collection
-- and then recurse into child collections.
--
procedure Print_Errors (Result : Result_Collection;
Level : Natural) is
begin
Print_Statuses
(Result => Result,
Level => Level,
Start => First_Error (Result),
Action => Print_Errors'Access,
Status => "ERROR",
Count => Error_Count'Access,
Print_Log => True);
end Print_Errors;
--
-- Print all passes from the result collection
-- and then recurse into child collections.
--
procedure Print_Passes (Result : Result_Collection;
Level : Natural) is
begin
Print_Statuses
(Result => Result,
Level => Level,
Start => First_Pass (Result),
Action => Print_Passes'Access,
Status => "PASS",
Count => Pass_Count'Access,
Print_Log => False);
end Print_Passes;
--
-- Report passes, skips, failures, and errors from the result collection.
procedure Report_Results (Result : Result_Collection;
Verbose : Boolean := False) is
begin
Put_Line ("Passed : " & Integer'Image (Pass_Count (Result)));
if Verbose then
Print_Passes (Result, 0);
end if;
New_Line;
if Skipped_Count (Result) > 0 then
Put_Line ("Skipped : " & Integer'Image (Skipped_Count (Result)));
Print_Skips (Result, 0);
New_Line;
end if;
if Failure_Count (Result) > 0 then
Put_Line ("Failed : " & Integer'Image (Failure_Count (Result)));
Print_Failures (Result, 0);
New_Line;
end if;
if Error_Count (Result) > 0 then
Put_Line ("Errors : " & Integer'Image (Error_Count (Result)));
Print_Errors (Result, 0);
end if;
end Report_Results;
procedure Print_Log_File (Filename : String) is
Handle : File_Type;
Char : Character := ' ';
First : Boolean := True;
begin
Open (Handle, In_File, Filename);
begin
loop
exit when End_Of_File (Handle);
Get (Handle, Char);
if First then
Put_Line ("===== Output =======");
First := False;
end if;
Put (Char);
if End_Of_Line (Handle) then
New_Line;
end if;
end loop;
-- The End_Error exception is sometimes raised.
exception
when Ada.IO_Exceptions.End_Error =>
null;
end;
Close (Handle);
if not First then
Put_Line ("====================");
end if;
end Print_Log_File;
procedure Do_Report (Test_Results : Results.Result_Collection;
Args : Parameters.Parameter_Info) is
begin
if Parameters.XML_Results (Args) then
XML_Runner.Report_Results
(Test_Results, Parameters.Result_Dir (Args));
else
Report_Results (Test_Results, Parameters.Verbose (Args));
end if;
end Do_Report;
procedure Run (Suite : in out Framework.Test'Class) is
begin
Runner.Run_Suite (Suite, Do_Report'Access);
end Run;
procedure Run (Suite : Framework.Test_Suite_Access) is
begin
Run (Suite.all);
end Run;
end Ahven.Text_Runner;
|
Fix the Ahven text runner: the END_ERROR exception can be raised when reading the test output file
|
Fix the Ahven text runner: the END_ERROR exception can be raised when reading the test output file
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
aa879bad58b8259b199cf1b7f75f60de0a79438b
|
src/gen-commands-templates.ads
|
src/gen-commands-templates.ads
|
-----------------------------------------------------------------------
-- gen-commands-templates -- Template based command
-- 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.Containers.Vectors;
with Util.Strings.Sets;
package Gen.Commands.Templates is
-- ------------------------------
-- Template Generic Command
-- ------------------------------
-- This command adds a XHTML page to the web application.
type Command is new Gen.Commands.Command with private;
type Command_Access is access all Command'Class;
-- Execute the command with the arguments.
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler);
-- Write the help associated with the command.
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler);
-- Read the template commands defined in dynamo configuration directory.
procedure Read_Commands (Generator : in out Gen.Generator.Handler);
private
type Param is record
Name : Ada.Strings.Unbounded.Unbounded_String;
Argument : Ada.Strings.Unbounded.Unbounded_String;
Value : Ada.Strings.Unbounded.Unbounded_String;
Is_Optional : Boolean := False;
end record;
package Param_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Param);
type Command is new Gen.Commands.Command with record
Name : Ada.Strings.Unbounded.Unbounded_String;
Title : Ada.Strings.Unbounded.Unbounded_String;
Usage : Ada.Strings.Unbounded.Unbounded_String;
Help_Msg : Ada.Strings.Unbounded.Unbounded_String;
Base_Dir : Ada.Strings.Unbounded.Unbounded_String;
Templates : Util.Strings.Sets.Set;
Params : Param_Vectors.Vector;
end record;
end Gen.Commands.Templates;
|
-----------------------------------------------------------------------
-- gen-commands-templates -- Template based command
-- Copyright (C) 2011, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Vectors;
with Util.Strings.Sets;
with Util.Strings.Vectors;
package Gen.Commands.Templates is
-- ------------------------------
-- Template Generic Command
-- ------------------------------
-- This command adds a XHTML page to the web application.
type Command is new Gen.Commands.Command with private;
type Command_Access is access all Command'Class;
-- Execute the command with the arguments.
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler);
-- Write the help associated with the command.
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler);
-- Read the template commands defined in dynamo configuration directory.
procedure Read_Commands (Generator : in out Gen.Generator.Handler);
private
type Param is record
Name : Ada.Strings.Unbounded.Unbounded_String;
Argument : Ada.Strings.Unbounded.Unbounded_String;
Value : Ada.Strings.Unbounded.Unbounded_String;
Is_Optional : Boolean := False;
end record;
package Param_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Param);
type Patch is record
Template : Ada.Strings.Unbounded.Unbounded_String;
After : Util.Strings.Vectors.Vector;
Before : Ada.Strings.Unbounded.Unbounded_String;
end record;
package Patch_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Patch);
type Command is new Gen.Commands.Command with record
Name : Ada.Strings.Unbounded.Unbounded_String;
Title : Ada.Strings.Unbounded.Unbounded_String;
Usage : Ada.Strings.Unbounded.Unbounded_String;
Help_Msg : Ada.Strings.Unbounded.Unbounded_String;
Base_Dir : Ada.Strings.Unbounded.Unbounded_String;
Templates : Util.Strings.Sets.Set;
Patches : Patch_Vectors.Vector;
Params : Param_Vectors.Vector;
end record;
end Gen.Commands.Templates;
|
Add support to patch files when executing some template command
|
Add support to patch files when executing some template command
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
419ad16a5c88b11691a9df6941bccff5cf279ff8
|
src/gl/interface/gl-toggles.ads
|
src/gl/interface/gl-toggles.ads
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2012 Felix Krause <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
private with GL.Low_Level;
with GL.Types;
package GL.Toggles is
pragma Preelaborate;
type Toggle_State is (Disabled, Enabled);
type Toggle is (Line_Smooth, Polygon_Smooth, Cull_Face, Depth_Test,
Stencil_Test, Dither, Blend, Color_Logic_Op, Scissor_Test,
Polygon_Offset_Point, Polygon_Offset_Line,
Clip_Distance_0, Clip_Distance_1, Clip_Distance_2, Clip_Distance_3,
Clip_Distance_4, Clip_Distance_5, Clip_Distance_6, Clip_Distance_7,
Polygon_Offset_Fill, Multisample,
Sample_Alpha_To_Coverage, Sample_Alpha_To_One, Sample_Coverage,
Debug_Output_Synchronous,
Program_Point_Size, Depth_Clamp,
Texture_Cube_Map_Seamless, Sample_Shading,
Rasterizer_Discard, Primitive_Restart_Fixed_Index,
Framebuffer_SRGB, Sample_Mask, Primitive_Restart,
Debug_Output);
procedure Enable (Subject : Toggle);
procedure Disable (Subject : Toggle);
procedure Set (Subject : Toggle; Value : Toggle_State);
function State (Subject : Toggle) return Toggle_State;
subtype Toggle_Indexed is Toggle
with Static_Predicate => Toggle_Indexed in Scissor_Test | Blend;
procedure Enable (Subject : Toggle_Indexed; Index : Types.UInt);
procedure Disable (Subject : Toggle_Indexed; Index : Types.UInt);
procedure Set (Subject : Toggle_Indexed; Index : Types.UInt; Value : Toggle_State);
function State (Subject : Toggle_Indexed; Index : Types.UInt) return Toggle_State;
private
for Toggle use (Line_Smooth => 16#0B20#,
Polygon_Smooth => 16#0B41#,
Cull_Face => 16#0B44#,
Depth_Test => 16#0B71#,
Stencil_Test => 16#0B90#,
Dither => 16#0BD0#,
Blend => 16#0BE2#,
Color_Logic_Op => 16#0BF2#,
Scissor_Test => 16#0C11#,
Polygon_Offset_Point => 16#2A01#,
Polygon_Offset_Line => 16#2A02#,
Clip_Distance_0 => 16#3000#,
Clip_Distance_1 => 16#3001#,
Clip_Distance_2 => 16#3002#,
Clip_Distance_3 => 16#3003#,
Clip_Distance_4 => 16#3004#,
Clip_Distance_5 => 16#3005#,
Clip_Distance_6 => 16#3006#,
Clip_Distance_7 => 16#3007#,
Polygon_Offset_Fill => 16#8037#,
Multisample => 16#809D#,
Sample_Alpha_To_Coverage => 16#809E#,
Sample_Alpha_To_One => 16#809F#,
Sample_Coverage => 16#80A0#,
Debug_Output_Synchronous => 16#8242#,
Program_Point_Size => 16#8642#,
Depth_Clamp => 16#864F#,
Texture_Cube_Map_Seamless => 16#884F#,
Sample_Shading => 16#8C36#,
Rasterizer_Discard => 16#8C89#,
Primitive_Restart_Fixed_Index => 16#8D69#,
Framebuffer_SRGB => 16#8DB9#,
Sample_Mask => 16#8E51#,
Primitive_Restart => 16#8F9D#,
Debug_Output => 16#92E0#);
for Toggle'Size use Low_Level.Enum'Size;
end GL.Toggles;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2012 Felix Krause <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
private with GL.Low_Level;
with GL.Types;
package GL.Toggles is
pragma Preelaborate;
type Toggle_State is (Disabled, Enabled);
type Toggle is (Line_Smooth, Polygon_Smooth, Cull_Face, Depth_Test,
Stencil_Test, Dither, Blend, Color_Logic_Op, Scissor_Test,
Polygon_Offset_Point, Polygon_Offset_Line,
Clip_Distance_0, Clip_Distance_1, Clip_Distance_2, Clip_Distance_3,
Clip_Distance_4, Clip_Distance_5, Clip_Distance_6, Clip_Distance_7,
Polygon_Offset_Fill, Multisample,
Sample_Alpha_To_Coverage, Sample_Alpha_To_One, Sample_Coverage,
Debug_Output_Synchronous,
Program_Point_Size, Depth_Clamp,
Texture_Cube_Map_Seamless, Sample_Shading,
Rasterizer_Discard, Primitive_Restart_Fixed_Index,
Framebuffer_SRGB, Sample_Mask, Primitive_Restart,
Debug_Output);
procedure Enable (Subject : Toggle);
procedure Disable (Subject : Toggle);
procedure Set (Subject : Toggle; Value : Toggle_State);
function State (Subject : Toggle) return Toggle_State;
type Toggle_Indexed is (Blend, Scissor_Test);
procedure Enable (Subject : Toggle_Indexed; Index : Types.UInt);
procedure Disable (Subject : Toggle_Indexed; Index : Types.UInt);
procedure Set (Subject : Toggle_Indexed; Index : Types.UInt; Value : Toggle_State);
function State (Subject : Toggle_Indexed; Index : Types.UInt) return Toggle_State;
private
for Toggle use (Line_Smooth => 16#0B20#,
Polygon_Smooth => 16#0B41#,
Cull_Face => 16#0B44#,
Depth_Test => 16#0B71#,
Stencil_Test => 16#0B90#,
Dither => 16#0BD0#,
Blend => 16#0BE2#,
Color_Logic_Op => 16#0BF2#,
Scissor_Test => 16#0C11#,
Polygon_Offset_Point => 16#2A01#,
Polygon_Offset_Line => 16#2A02#,
Clip_Distance_0 => 16#3000#,
Clip_Distance_1 => 16#3001#,
Clip_Distance_2 => 16#3002#,
Clip_Distance_3 => 16#3003#,
Clip_Distance_4 => 16#3004#,
Clip_Distance_5 => 16#3005#,
Clip_Distance_6 => 16#3006#,
Clip_Distance_7 => 16#3007#,
Polygon_Offset_Fill => 16#8037#,
Multisample => 16#809D#,
Sample_Alpha_To_Coverage => 16#809E#,
Sample_Alpha_To_One => 16#809F#,
Sample_Coverage => 16#80A0#,
Debug_Output_Synchronous => 16#8242#,
Program_Point_Size => 16#8642#,
Depth_Clamp => 16#864F#,
Texture_Cube_Map_Seamless => 16#884F#,
Sample_Shading => 16#8C36#,
Rasterizer_Discard => 16#8C89#,
Primitive_Restart_Fixed_Index => 16#8D69#,
Framebuffer_SRGB => 16#8DB9#,
Sample_Mask => 16#8E51#,
Primitive_Restart => 16#8F9D#,
Debug_Output => 16#92E0#);
for Toggle'Size use Low_Level.Enum'Size;
for Toggle_Indexed use
(Blend => 16#0BE2#,
Scissor_Test => 16#0C11#);
for Toggle_Indexed'Size use Low_Level.Enum'Size;
end GL.Toggles;
|
Make subtype Toggle_Indexed a type to workaround compiler bug
|
gl: Make subtype Toggle_Indexed a type to workaround compiler bug
Static_Predicate would fail for value GL.Toggles.Blend. Changing
Toggle_Indexed from a subtype with a predicate to a separate type avoids
raising the Assert_Failure exception when compiled with GNAT FSF.
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
9f14058017b1a8f543acc8c1f7aa058acf27ca82
|
src/wiki-documents.adb
|
src/wiki-documents.adb
|
-----------------------------------------------------------------------
-- wiki-nodes -- Wiki Document Internal representation
-- Copyright (C) 2016, 2019, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Wiki.Documents is
use Wiki.Nodes;
use Wiki.Nodes.Lists;
-- ------------------------------
-- Append a HTML tag start node to the document.
-- ------------------------------
procedure Push_Node (Into : in out Document;
Tag : in Html_Tag;
Attributes : in Wiki.Attributes.Attribute_List) is
Node : constant Node_Type_Access := new Node_Type '(Kind => N_TAG_START,
Len => 0,
Tag_Start => Tag,
Attributes => Attributes,
Children => null,
Parent => Into.Current);
begin
Append (Into, Node);
Into.Current := Node;
end Push_Node;
-- ------------------------------
-- Pop the HTML tag.
-- ------------------------------
procedure Pop_Node (From : in out Document;
Tag : in Html_Tag) is
pragma Unreferenced (Tag);
begin
if From.Current /= null then
From.Current := From.Current.Parent;
end if;
end Pop_Node;
-- ------------------------------
-- Returns True if the current node is the root document node.
-- ------------------------------
function Is_Root_Node (Doc : in Document) return Boolean is
begin
return Doc.Current = null;
end Is_Root_Node;
-- ------------------------------
-- Append a section header at end of the document.
-- ------------------------------
procedure Append (Into : in out Document;
Header : in Wiki.Strings.WString;
Level : in Positive) is
begin
Append (Into, new Node_Type '(Kind => N_HEADER,
Len => Header'Length,
Parent => Into.Current,
Header => Header,
Level => Level));
end Append;
-- ------------------------------
-- Append a node to the document.
-- ------------------------------
procedure Append (Into : in out Document;
Node : in Wiki.Nodes.Node_Type_Access) is
begin
if Into.Current = null then
Append (Into.Nodes, Node);
else
Append (Into.Current, Node);
end if;
end Append;
-- ------------------------------
-- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH.
-- ------------------------------
procedure Append (Into : in out Document;
Kind : in Simple_Node_Kind) is
begin
case Kind is
when N_LINE_BREAK =>
Append (Into, new Node_Type '(Kind => N_LINE_BREAK, Len => 0,
Parent => Into.Current));
when N_HORIZONTAL_RULE =>
Append (Into, new Node_Type '(Kind => N_HORIZONTAL_RULE, Len => 0,
Parent => Into.Current));
when N_PARAGRAPH =>
Append (Into, new Node_Type '(Kind => N_PARAGRAPH, Len => 0,
Parent => Into.Current));
when N_NEWLINE =>
Append (Into, new Node_Type '(Kind => N_NEWLINE, Len => 0,
Parent => Into.Current));
when N_TOC_DISPLAY =>
Append (Into, new Node_Type '(Kind => N_TOC_DISPLAY, Len => 0,
Parent => Into.Current));
Into.Using_TOC := True;
end case;
end Append;
-- ------------------------------
-- Append the text with the given format at end of the document.
-- ------------------------------
procedure Append (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Format_Map) is
begin
Append (Into, new Node_Type '(Kind => N_TEXT, Len => Text'Length,
Parent => Into.Current,
Text => Text, Format => Format));
end Append;
-- ------------------------------
-- Add a link.
-- ------------------------------
procedure Add_Link (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_LINK, Len => Name'Length,
Parent => Into.Current,
Title => Name, Link_Attr => Attributes));
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
procedure Add_Image (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_IMAGE, Len => Name'Length,
Parent => Into.Current,
Title => Name, Link_Attr => Attributes));
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
procedure Add_Quote (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_QUOTE, Len => Name'Length,
Parent => Into.Current,
Title => Name, Link_Attr => Attributes));
end Add_Quote;
-- ------------------------------
-- 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.
-- ------------------------------
procedure Add_List_Item (Into : in out Document;
Level : in Positive;
Ordered : in Boolean) is
begin
if Ordered then
Append (Into, new Node_Type '(Kind => N_NUM_LIST, Len => 0,
Parent => Into.Current,
Level => Level, others => <>));
else
Append (Into, new Node_Type '(Kind => N_LIST, Len => 0,
Parent => Into.Current,
Level => Level, others => <>));
end if;
end Add_List_Item;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
procedure Add_Blockquote (Into : in out Document;
Level : in Natural) is
begin
Append (Into, new Node_Type '(Kind => N_BLOCKQUOTE, Len => 0,
Parent => Into.Current,
Level => Level, others => <>));
end Add_Blockquote;
-- ------------------------------
-- Add a text block that is pre-formatted.
-- ------------------------------
procedure Add_Preformatted (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString) is
begin
Append (Into, new Node_Type '(Kind => N_PREFORMAT, Len => Text'Length,
Parent => Into.Current,
Preformatted => Text,
Language => Strings.To_UString (Format)));
end Add_Preformatted;
-- ------------------------------
-- Add a new row to the current table.
-- ------------------------------
procedure Add_Row (Into : in out Document) is
Table : Node_Type_Access;
Row : Node_Type_Access;
begin
-- Identify the current table.
Table := Into.Current;
while Table /= null and then Table.Kind /= N_TABLE loop
Table := Table.Parent;
end loop;
-- Create the current table.
if Table = null then
Table := new Node_Type '(Kind => N_TABLE,
Len => 0,
Tag_Start => TABLE_TAG,
Children => null,
Parent => Into.Current,
others => <>);
Append (Into, Table);
end if;
-- Add the row.
Row := new Node_Type '(Kind => N_ROW,
Len => 0,
Tag_Start => TR_TAG,
Children => null,
Parent => Table,
others => <>);
Append (Table, Row);
Into.Current := Row;
end Add_Row;
-- ------------------------------
-- Add a column to the current table row. The column is configured with the
-- given attributes. The column content is provided through calls to Append.
-- ------------------------------
procedure Add_Column (Into : in out Document;
Attributes : in out Wiki.Attributes.Attribute_List) is
Row : Node_Type_Access;
Col : Node_Type_Access;
begin
-- Identify the current row.
Row := Into.Current;
while Row /= null and then Row.Kind /= N_ROW loop
Row := Row.Parent;
end loop;
-- Add the new column.
Col := new Node_Type '(Kind => N_COLUMN,
Len => 0,
Tag_Start => TD_TAG,
Children => null,
Parent => Row,
Attributes => Attributes);
Append (Row, Col);
Into.Current := Col;
end Add_Column;
-- ------------------------------
-- Finish the creation of the table.
-- ------------------------------
procedure Finish_Table (Into : in out Document) is
Table : Node_Type_Access;
begin
-- Identify the current table.
Table := Into.Current;
while Table /= null and then Table.Kind /= N_TABLE loop
Table := Table.Parent;
end loop;
if Table /= null then
Into.Current := Table.Parent;
else
Into.Current := null;
end if;
end Finish_Table;
-- ------------------------------
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
-- ------------------------------
procedure Iterate (Doc : in Document;
Process : not null access procedure (Node : in Node_Type)) is
begin
Iterate (Doc.Nodes, Process);
end Iterate;
-- ------------------------------
-- Returns True if the document is empty.
-- ------------------------------
function Is_Empty (Doc : in Document) return Boolean is
begin
return Wiki.Nodes.Lists.Is_Empty (Doc.Nodes);
end Is_Empty;
-- ------------------------------
-- Returns True if the document displays the table of contents by itself.
-- ------------------------------
function Is_Using_TOC (Doc : in Document) return Boolean is
begin
return Doc.Using_TOC;
end Is_Using_TOC;
-- ------------------------------
-- Returns True if the table of contents is visible and must be rendered.
-- ------------------------------
function Is_Visible_TOC (Doc : in Document) return Boolean is
begin
return Doc.Visible_TOC;
end Is_Visible_TOC;
-- ------------------------------
-- Hide the table of contents.
-- ------------------------------
procedure Hide_TOC (Doc : in out Document) is
begin
Doc.Visible_TOC := False;
end Hide_TOC;
-- ------------------------------
-- Get the table of content node associated with the document.
-- ------------------------------
procedure Get_TOC (Doc : in out Document;
TOC : out Wiki.Nodes.Lists.Node_List_Ref) is
begin
if Wiki.Nodes.Lists.Is_Empty (Doc.TOC) then
Append (Doc.TOC, new Node_Type '(Kind => N_TOC, Len => 0, others => <>));
end if;
TOC := Doc.TOC;
end Get_TOC;
-- ------------------------------
-- Get the table of content node associated with the document.
-- ------------------------------
function Get_TOC (Doc : in Document) return Wiki.Nodes.Lists.Node_List_Ref is
begin
return Doc.TOC;
end Get_TOC;
end Wiki.Documents;
|
-----------------------------------------------------------------------
-- wiki-nodes -- Wiki Document Internal representation
-- Copyright (C) 2016, 2019, 2020, 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.
-----------------------------------------------------------------------
package body Wiki.Documents is
use Wiki.Nodes;
use Wiki.Nodes.Lists;
-- ------------------------------
-- Append a HTML tag start node to the document.
-- ------------------------------
procedure Push_Node (Into : in out Document;
Tag : in Html_Tag;
Attributes : in Wiki.Attributes.Attribute_List) is
Node : constant Node_Type_Access := new Node_Type '(Kind => N_TAG_START,
Len => 0,
Tag_Start => Tag,
Attributes => Attributes,
Children => null,
Parent => Into.Current);
begin
Append (Into, Node);
Into.Current := Node;
end Push_Node;
-- ------------------------------
-- Pop the HTML tag.
-- ------------------------------
procedure Pop_Node (From : in out Document;
Tag : in Html_Tag) is
pragma Unreferenced (Tag);
begin
if From.Current /= null then
From.Current := From.Current.Parent;
end if;
end Pop_Node;
-- ------------------------------
-- Returns True if the current node is the root document node.
-- ------------------------------
function Is_Root_Node (Doc : in Document) return Boolean is
begin
return Doc.Current = null;
end Is_Root_Node;
-- ------------------------------
-- Append a section header at end of the document.
-- ------------------------------
procedure Append (Into : in out Document;
Header : in Wiki.Strings.WString;
Level : in Positive) is
begin
Append (Into, new Node_Type '(Kind => N_HEADER,
Len => Header'Length,
Parent => Into.Current,
Header => Header,
Level => Level));
end Append;
-- ------------------------------
-- Append a node to the document.
-- ------------------------------
procedure Append (Into : in out Document;
Node : in Wiki.Nodes.Node_Type_Access) is
begin
if Into.Current = null then
Append (Into.Nodes, Node);
else
Append (Into.Current, Node);
end if;
end Append;
-- ------------------------------
-- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH.
-- ------------------------------
procedure Append (Into : in out Document;
Kind : in Simple_Node_Kind) is
begin
case Kind is
when N_LINE_BREAK =>
Append (Into, new Node_Type '(Kind => N_LINE_BREAK, Len => 0,
Parent => Into.Current));
when N_HORIZONTAL_RULE =>
Append (Into, new Node_Type '(Kind => N_HORIZONTAL_RULE, Len => 0,
Parent => Into.Current));
when N_PARAGRAPH =>
Append (Into, new Node_Type '(Kind => N_PARAGRAPH, Len => 0,
Parent => Into.Current));
when N_LIST_ITEM =>
Append (Into, new Node_Type '(Kind => N_LIST_ITEM, Len => 0,
Parent => Into.Current));
when N_LIST_END =>
Append (Into, new Node_Type '(Kind => N_LIST_END, Len => 0,
Parent => Into.Current));
when N_NUM_LIST_END =>
Append (Into, new Node_Type '(Kind => N_NUM_LIST_END, Len => 0,
Parent => Into.Current));
when N_LIST_ITEM_END =>
Append (Into, new Node_Type '(Kind => N_LIST_ITEM_END, Len => 0,
Parent => Into.Current));
when N_NEWLINE =>
Append (Into, new Node_Type '(Kind => N_NEWLINE, Len => 0,
Parent => Into.Current));
when N_TOC_DISPLAY =>
Append (Into, new Node_Type '(Kind => N_TOC_DISPLAY, Len => 0,
Parent => Into.Current));
Into.Using_TOC := True;
when N_NONE =>
null;
end case;
end Append;
-- ------------------------------
-- Append the text with the given format at end of the document.
-- ------------------------------
procedure Append (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Format_Map) is
begin
Append (Into, new Node_Type '(Kind => N_TEXT, Len => Text'Length,
Parent => Into.Current,
Text => Text, Format => Format));
end Append;
-- ------------------------------
-- Add a link.
-- ------------------------------
procedure Add_Link (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_LINK, Len => Name'Length,
Parent => Into.Current,
Title => Name, Link_Attr => Attributes));
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
procedure Add_Image (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_IMAGE, Len => Name'Length,
Parent => Into.Current,
Title => Name, Link_Attr => Attributes));
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
procedure Add_Quote (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_QUOTE, Len => Name'Length,
Parent => Into.Current,
Title => Name, Link_Attr => Attributes));
end Add_Quote;
-- ------------------------------
-- Add a list (<ul> or <ol>) starting at the given number.
-- ------------------------------
procedure Add_List (Into : in out Document;
Level : in Positive;
Ordered : in Boolean) is
begin
if Ordered then
Append (Into, new Node_Type '(Kind => N_NUM_LIST_START, Len => 0,
Parent => Into.Current,
Level => Level, others => <>));
else
Append (Into, new Node_Type '(Kind => N_LIST_START, Len => 0,
Parent => Into.Current,
Level => Level, others => <>));
end if;
end Add_List;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
procedure Add_Blockquote (Into : in out Document;
Level : in Natural) is
begin
Append (Into, new Node_Type '(Kind => N_BLOCKQUOTE, Len => 0,
Parent => Into.Current,
Level => Level, others => <>));
end Add_Blockquote;
-- ------------------------------
-- Add a text block that is pre-formatted.
-- ------------------------------
procedure Add_Preformatted (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString) is
begin
Append (Into, new Node_Type '(Kind => N_PREFORMAT, Len => Text'Length,
Parent => Into.Current,
Preformatted => Text,
Language => Strings.To_UString (Format)));
end Add_Preformatted;
-- ------------------------------
-- Add a new row to the current table.
-- ------------------------------
procedure Add_Row (Into : in out Document) is
Table : Node_Type_Access;
Row : Node_Type_Access;
begin
-- Identify the current table.
Table := Into.Current;
while Table /= null and then Table.Kind /= N_TABLE loop
Table := Table.Parent;
end loop;
-- Create the current table.
if Table = null then
Table := new Node_Type '(Kind => N_TABLE,
Len => 0,
Tag_Start => TABLE_TAG,
Children => null,
Parent => Into.Current,
others => <>);
Append (Into, Table);
end if;
-- Add the row.
Row := new Node_Type '(Kind => N_ROW,
Len => 0,
Tag_Start => TR_TAG,
Children => null,
Parent => Table,
others => <>);
Append (Table, Row);
Into.Current := Row;
end Add_Row;
-- ------------------------------
-- Add a column to the current table row. The column is configured with the
-- given attributes. The column content is provided through calls to Append.
-- ------------------------------
procedure Add_Column (Into : in out Document;
Attributes : in out Wiki.Attributes.Attribute_List) is
Row : Node_Type_Access;
Col : Node_Type_Access;
begin
-- Identify the current row.
Row := Into.Current;
while Row /= null and then Row.Kind /= N_ROW loop
Row := Row.Parent;
end loop;
-- Add the new column.
Col := new Node_Type '(Kind => N_COLUMN,
Len => 0,
Tag_Start => TD_TAG,
Children => null,
Parent => Row,
Attributes => Attributes);
Append (Row, Col);
Into.Current := Col;
end Add_Column;
-- ------------------------------
-- Finish the creation of the table.
-- ------------------------------
procedure Finish_Table (Into : in out Document) is
Table : Node_Type_Access;
begin
-- Identify the current table.
Table := Into.Current;
while Table /= null and then Table.Kind /= N_TABLE loop
Table := Table.Parent;
end loop;
if Table /= null then
Into.Current := Table.Parent;
else
Into.Current := null;
end if;
end Finish_Table;
-- ------------------------------
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
-- ------------------------------
procedure Iterate (Doc : in Document;
Process : not null access procedure (Node : in Node_Type)) is
begin
Iterate (Doc.Nodes, Process);
end Iterate;
-- ------------------------------
-- Returns True if the document is empty.
-- ------------------------------
function Is_Empty (Doc : in Document) return Boolean is
begin
return Wiki.Nodes.Lists.Is_Empty (Doc.Nodes);
end Is_Empty;
-- ------------------------------
-- Returns True if the document displays the table of contents by itself.
-- ------------------------------
function Is_Using_TOC (Doc : in Document) return Boolean is
begin
return Doc.Using_TOC;
end Is_Using_TOC;
-- ------------------------------
-- Returns True if the table of contents is visible and must be rendered.
-- ------------------------------
function Is_Visible_TOC (Doc : in Document) return Boolean is
begin
return Doc.Visible_TOC;
end Is_Visible_TOC;
-- ------------------------------
-- Hide the table of contents.
-- ------------------------------
procedure Hide_TOC (Doc : in out Document) is
begin
Doc.Visible_TOC := False;
end Hide_TOC;
-- ------------------------------
-- Get the table of content node associated with the document.
-- ------------------------------
procedure Get_TOC (Doc : in out Document;
TOC : out Wiki.Nodes.Lists.Node_List_Ref) is
begin
if Wiki.Nodes.Lists.Is_Empty (Doc.TOC) then
Append (Doc.TOC, new Node_Type '(Kind => N_TOC, Len => 0, others => <>));
end if;
TOC := Doc.TOC;
end Get_TOC;
-- ------------------------------
-- Get the table of content node associated with the document.
-- ------------------------------
function Get_TOC (Doc : in Document) return Wiki.Nodes.Lists.Node_List_Ref is
begin
return Doc.TOC;
end Get_TOC;
end Wiki.Documents;
|
Change Add_List_Item into Add_List to better represent lists and items in order to identify the start and end of lists and items
|
Change Add_List_Item into Add_List to better represent lists and items in order to identify
the start and end of lists and items
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
3cc8d46ce13e961c59275152624d535b8f237e68
|
awa/src/awa-users-module.adb
|
awa/src/awa-users-module.adb
|
-----------------------------------------------------------------------
-- awa-users-model -- User management module
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Modules.Beans;
with ASF.Beans;
with AWA.Users.Beans;
with Util.Log.Loggers;
package body AWA.Users.Module is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Users.Module");
package Register is new ASF.Modules.Beans (Module => User_Module,
Module_Access => User_Module_Access);
-- ------------------------------
-- Initialize the user module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out User_Module;
App : access ASF.Applications.Main.Application'Class) is
begin
Log.Info ("Initializing the users module");
AWA.Modules.Module (Plugin).Initialize (App);
-- Setup the verify access key filter.
App.Add_Filter ("verify-access-key", Plugin.Key_Filter'Access);
App.Add_Filter_Mapping (Pattern => "/users/validate.html",
Name => "verify-access-key");
Plugin.Key_Filter.Initialize (App.all);
Plugin.Manager := Plugin.Create_User_Manager;
Register.Register (Plugin => Plugin,
Name => "login",
Handler => AWA.Users.Beans.Create_Authenticate_Bean'Access,
Scope => ASF.Beans.REQUEST_SCOPE);
Register.Register (Plugin => Plugin,
Name => "register",
Handler => AWA.Users.Beans.Create_Authenticate_Bean'Access,
Scope => ASF.Beans.REQUEST_SCOPE);
Register.Register (Plugin => Plugin,
Name => "lostPassword",
Handler => AWA.Users.Beans.Create_Authenticate_Bean'Access,
Scope => ASF.Beans.REQUEST_SCOPE);
end Initialize;
-- ------------------------------
-- Get the user manager.
-- ------------------------------
function Get_User_Manager (Plugin : in User_Module) return Services.User_Service_Access is
begin
return Plugin.Manager;
end Get_User_Manager;
-- ------------------------------
-- Create a user manager. This operation can be overriden to provide another
-- user service implementation.
-- ------------------------------
function Create_User_Manager (Plugin : in User_Module) return Services.User_Service_Access is
Result : constant Services.User_Service_Access := new Services.User_Service;
begin
Result.Initialize (Plugin);
return Result;
end Create_User_Manager;
-- ------------------------------
-- Get the user module instance associated with the current application.
-- ------------------------------
function Get_User_Module return User_Module_Access is
function Get is new ASF.Modules.Get (User_Module, User_Module_Access, NAME);
begin
return Get;
end Get_User_Module;
-- ------------------------------
-- Get the user manager instance associated with the current application.
-- ------------------------------
function Get_User_Manager return Services.User_Service_Access is
Module : constant User_Module_Access := Get_User_Module;
begin
if Module = null then
Log.Error ("There is no active User_Module");
return null;
else
return Module.Get_User_Manager;
end if;
end Get_User_Manager;
end AWA.Users.Module;
|
-----------------------------------------------------------------------
-- awa-users-model -- User management module
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Modules.Beans;
with ASF.Beans;
with ASF.Modules.Get;
with AWA.Users.Beans;
with Util.Log.Loggers;
package body AWA.Users.Module is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Users.Module");
package Register is new ASF.Modules.Beans (Module => User_Module,
Module_Access => User_Module_Access);
-- ------------------------------
-- Initialize the user module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out User_Module;
App : access ASF.Applications.Main.Application'Class) is
begin
Log.Info ("Initializing the users module");
AWA.Modules.Module (Plugin).Initialize (App);
-- Setup the resource bundles.
App.Register ("userMsg", "users");
-- Setup the verify access key filter.
App.Add_Filter ("verify-access-key", Plugin.Key_Filter'Access);
App.Add_Filter_Mapping (Pattern => "/users/validate.html",
Name => "verify-access-key");
App.Add_Filter_Mapping (Pattern => "/users/reset-password.html",
Name => "verify-access-key");
Plugin.Key_Filter.Initialize (App.all);
Plugin.Manager := Plugin.Create_User_Manager;
Register.Register (Plugin => Plugin,
Name => "login",
Handler => AWA.Users.Beans.Create_Authenticate_Bean'Access,
Scope => ASF.Beans.REQUEST_SCOPE);
Register.Register (Plugin => Plugin,
Name => "register",
Handler => AWA.Users.Beans.Create_Authenticate_Bean'Access,
Scope => ASF.Beans.REQUEST_SCOPE);
Register.Register (Plugin => Plugin,
Name => "resetPassword",
Handler => AWA.Users.Beans.Create_Authenticate_Bean'Access,
Scope => ASF.Beans.REQUEST_SCOPE);
Register.Register (Plugin => Plugin,
Name => "lostPassword",
Handler => AWA.Users.Beans.Create_Authenticate_Bean'Access,
Scope => ASF.Beans.REQUEST_SCOPE);
end Initialize;
-- ------------------------------
-- Get the user manager.
-- ------------------------------
function Get_User_Manager (Plugin : in User_Module) return Services.User_Service_Access is
begin
return Plugin.Manager;
end Get_User_Manager;
-- ------------------------------
-- Create a user manager. This operation can be overriden to provide another
-- user service implementation.
-- ------------------------------
function Create_User_Manager (Plugin : in User_Module) return Services.User_Service_Access is
Result : constant Services.User_Service_Access := new Services.User_Service;
begin
Result.Initialize (Plugin);
return Result;
end Create_User_Manager;
-- ------------------------------
-- Get the user module instance associated with the current application.
-- ------------------------------
function Get_User_Module return User_Module_Access is
function Get is new ASF.Modules.Get (User_Module, User_Module_Access, NAME);
begin
return Get;
end Get_User_Module;
-- ------------------------------
-- Get the user manager instance associated with the current application.
-- ------------------------------
function Get_User_Manager return Services.User_Service_Access is
Module : constant User_Module_Access := Get_User_Module;
begin
if Module = null then
Log.Error ("There is no active User_Module");
return null;
else
return Module.Get_User_Manager;
end if;
end Get_User_Manager;
end AWA.Users.Module;
|
Apply the Verify_Filter on the reset-password link Add the resetPassword bean
|
Apply the Verify_Filter on the reset-password link
Add the resetPassword bean
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
d227d6de4277438f7836a27b51259099a28473e0
|
awa/plugins/awa-workspaces/src/awa-workspaces-modules.adb
|
awa/plugins/awa-workspaces/src/awa-workspaces-modules.adb
|
-----------------------------------------------------------------------
-- awa-workspaces-module -- Module workspaces
-- 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.Calendar;
with AWA.Users.Models;
with AWA.Modules.Beans;
with AWA.Permissions.Services;
with ADO.SQL;
with Util.Log.Loggers;
with AWA.Workspaces.Beans;
package body AWA.Workspaces.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Workspaces.Module");
package Register is new AWA.Modules.Beans (Module => Workspace_Module,
Module_Access => Workspace_Module_Access);
-- ------------------------------
-- Initialize the workspaces module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Workspace_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the workspaces module");
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "AWA.Workspaces.Beans.Workspaces_Bean",
Handler => AWA.Workspaces.Beans.Create_Workspaces_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the current workspace associated with the current user.
-- If the user has not workspace, create one.
-- ------------------------------
procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session;
Context : in AWA.Services.Contexts.Service_Context_Access;
Workspace : out AWA.Workspaces.Models.Workspace_Ref) is
User : constant AWA.Users.Models.User_Ref := Context.Get_User;
WS : AWA.Workspaces.Models.Workspace_Ref;
Query : ADO.SQL.Query;
Found : Boolean;
begin
if User.Is_Null then
Log.Error ("There is no current user. The workspace cannot be identified");
Workspace := AWA.Workspaces.Models.Null_Workspace;
return;
end if;
-- Find the workspace associated with the current user.
Query.Add_Param (User.Get_Id);
Query.Set_Filter ("o.owner_id = ?");
WS.Find (Session, Query, Found);
if Found then
Workspace := WS;
return;
end if;
-- Create a workspace for this user.
WS.Set_Owner (User);
WS.Set_Create_Date (Ada.Calendar.Clock);
WS.Save (Session);
-- And give full control of the workspace for this user
AWA.Permissions.Services.Add_Permission (Session => Session,
User => User.Get_Id,
Entity => WS);
Workspace := WS;
end Get_Workspace;
end AWA.Workspaces.Modules;
|
-----------------------------------------------------------------------
-- awa-workspaces-module -- Module workspaces
-- 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.Calendar;
with AWA.Users.Models;
with AWA.Modules.Beans;
with AWA.Permissions.Services;
with ADO.SQL;
with Util.Log.Loggers;
with AWA.Users.Modules;
with AWA.Workspaces.Beans;
package body AWA.Workspaces.Modules is
package ASC renames AWA.Services.Contexts;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Workspaces.Module");
package Register is new AWA.Modules.Beans (Module => Workspace_Module,
Module_Access => Workspace_Module_Access);
-- ------------------------------
-- Initialize the workspaces module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Workspace_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the workspaces module");
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "AWA.Workspaces.Beans.Workspaces_Bean",
Handler => AWA.Workspaces.Beans.Create_Workspaces_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
Plugin.User_Manager := AWA.Users.Modules.Get_User_Manager;
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the current workspace associated with the current user.
-- If the user has not workspace, create one.
-- ------------------------------
procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session;
Context : in AWA.Services.Contexts.Service_Context_Access;
Workspace : out AWA.Workspaces.Models.Workspace_Ref) is
User : constant AWA.Users.Models.User_Ref := Context.Get_User;
WS : AWA.Workspaces.Models.Workspace_Ref;
Query : ADO.SQL.Query;
Found : Boolean;
begin
if User.Is_Null then
Log.Error ("There is no current user. The workspace cannot be identified");
Workspace := AWA.Workspaces.Models.Null_Workspace;
return;
end if;
-- Find the workspace associated with the current user.
Query.Add_Param (User.Get_Id);
Query.Set_Filter ("o.owner_id = ?");
WS.Find (Session, Query, Found);
if Found then
Workspace := WS;
return;
end if;
-- Create a workspace for this user.
WS.Set_Owner (User);
WS.Set_Create_Date (Ada.Calendar.Clock);
WS.Save (Session);
-- And give full control of the workspace for this user
AWA.Permissions.Services.Add_Permission (Session => Session,
User => User.Get_Id,
Entity => WS);
Workspace := WS;
end Get_Workspace;
-- ------------------------------
-- Send the invitation to the user.
-- ------------------------------
procedure Send_Invitation (Module : in Workspace_Module;
Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class) is
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
WS : AWA.Workspaces.Models.Workspace_Ref;
Query : ADO.SQL.Query;
Found : Boolean;
Key : AWA.Users.Models.Access_Key_Ref;
begin
Log.Info ("Sending invitation to {0}", String '(Invitation.Get_Email));
Ctx.Start;
if User.Is_Null then
Log.Error ("There is no current user. The workspace cannot be identified");
return;
end if;
-- Find the workspace associated with the current user.
Query.Add_Param (User.Get_Id);
Query.Set_Filter ("o.owner_id = ?");
WS.Find (DB, Query, Found);
if not Found then
return;
end if;
Key := AWA.Users.Models.Access_Key_Ref (Invitation.Get_Access_Key);
-- Key.Set_Key_Value
Key.Save (DB);
Invitation.Set_Inviter (User);
Invitation.Set_Workspace (WS);
Invitation.Set_Create_Date (Ada.Calendar.Clock);
Invitation.Save (DB);
Ctx.Commit;
end Send_Invitation;
end AWA.Workspaces.Modules;
|
Implement the Send_Invitation procedure to make an invitation and send it
|
Implement the Send_Invitation procedure to make an invitation and send it
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
2ed91360dcb1f7f37831fb427d0f498e77df26f1
|
awa/plugins/awa-blogs/src/awa-blogs-services.ads
|
awa/plugins/awa-blogs/src/awa-blogs-services.ads
|
-----------------------------------------------------------------------
-- awa-blogs-services -- Blogs and post management
-- 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 ADO;
with AWA.Modules;
with AWA.Blogs.Models;
with Security.Permissions;
-- The <b>Blogs.Services</b> package defines the service and operations to
-- create, update and delete a post.
package AWA.Blogs.Services is
NAME : constant String := "Blog_Service";
-- Define the permissions.
package ACL_Create_Blog is new Security.Permissions.Permission_ACL ("blog-create");
package ACL_Delete_Blog is new Security.Permissions.Permission_ACL ("blog-delete");
package ACL_Create_Post is new Security.Permissions.Permission_ACL ("blog-create-post");
package ACL_Delete_Post is new Security.Permissions.Permission_ACL ("blog-delete-post");
package ACL_Update_Post is new Security.Permissions.Permission_ACL ("blog-update-post");
-- Exception raised when a post cannot be found.
Not_Found : exception;
type Blog_Service is new AWA.Modules.Module_Manager with private;
type Blog_Service_Access is access all Blog_Service'Class;
-- Create a new blog for the user workspace.
procedure Create_Blog (Model : in Blog_Service;
Workspace_Id : in ADO.Identifier;
Title : in String;
Result : out ADO.Identifier);
-- Create a new post associated with the given blog identifier.
procedure Create_Post (Model : in Blog_Service;
Blog_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Status : in AWA.Blogs.Models.Post_Status_Type;
Result : out ADO.Identifier);
-- Update the post title and text associated with the blog post identified by <b>Post</b>.
procedure Update_Post (Model : in Blog_Service;
Post_Id : in ADO.Identifier;
Title : in String;
Text : in String;
Status : in AWA.Blogs.Models.Post_Status_Type);
-- Delete the post identified by the given identifier.
procedure Delete_Post (Model : in Blog_Service;
Post_Id : in ADO.Identifier);
private
type Blog_Service is new AWA.Modules.Module_Manager with null record;
end AWA.Blogs.Services;
|
-----------------------------------------------------------------------
-- awa-blogs-services -- Blogs and post management
-- 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 ADO;
with AWA.Modules;
with AWA.Blogs.Models;
with Security.Permissions;
-- The <b>Blogs.Services</b> package defines the service and operations to
-- create, update and delete a post.
package AWA.Blogs.Services is
NAME : constant String := "Blog_Service";
-- Define the permissions.
package ACL_Create_Blog is new Security.Permissions.Definition ("blog-create");
package ACL_Delete_Blog is new Security.Permissions.Definition ("blog-delete");
package ACL_Create_Post is new Security.Permissions.Definition ("blog-create-post");
package ACL_Delete_Post is new Security.Permissions.Definition ("blog-delete-post");
package ACL_Update_Post is new Security.Permissions.Definition ("blog-update-post");
-- Exception raised when a post cannot be found.
Not_Found : exception;
type Blog_Service is new AWA.Modules.Module_Manager with private;
type Blog_Service_Access is access all Blog_Service'Class;
-- Create a new blog for the user workspace.
procedure Create_Blog (Model : in Blog_Service;
Workspace_Id : in ADO.Identifier;
Title : in String;
Result : out ADO.Identifier);
-- Create a new post associated with the given blog identifier.
procedure Create_Post (Model : in Blog_Service;
Blog_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Status : in AWA.Blogs.Models.Post_Status_Type;
Result : out ADO.Identifier);
-- Update the post title and text associated with the blog post identified by <b>Post</b>.
procedure Update_Post (Model : in Blog_Service;
Post_Id : in ADO.Identifier;
Title : in String;
Text : in String;
Status : in AWA.Blogs.Models.Post_Status_Type);
-- Delete the post identified by the given identifier.
procedure Delete_Post (Model : in Blog_Service;
Post_Id : in ADO.Identifier);
private
type Blog_Service is new AWA.Modules.Module_Manager with null record;
end AWA.Blogs.Services;
|
Use the Permissions.Definition generic package
|
Use the Permissions.Definition generic package
|
Ada
|
apache-2.0
|
Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa
|
0b2524cad5cd06760a3acce00ee5664bb479bd34
|
src/security-policies-roles.adb
|
src/security-policies-roles.adb
|
-----------------------------------------------------------------------
-- security-policies-roles -- Role based 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 Util.Log.Loggers;
with Util.Serialize.Mappers.Record_Mapper;
with Security.Controllers;
with Security.Controllers.Roles;
package body Security.Policies.Roles is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Security.Policies.Roles");
-- ------------------------------
-- Get the policy name.
-- ------------------------------
overriding
function Get_Name (From : in Role_Policy) return String is
pragma Unreferenced (From);
begin
return "role";
end Get_Name;
-- ------------------------------
-- Get the role name.
-- ------------------------------
function Get_Role_Name (Manager : in Role_Policy;
Role : in Role_Type) return String is
use type Ada.Strings.Unbounded.String_Access;
begin
if Manager.Names (Role) = null then
return "";
else
return Manager.Names (Role).all;
end if;
end Get_Role_Name;
-- ------------------------------
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
-- ------------------------------
function Find_Role (Manager : in Role_Policy;
Name : in String) return Role_Type is
use type Ada.Strings.Unbounded.String_Access;
begin
Log.Debug ("Searching role {0}", Name);
for I in Role_Type'First .. Manager.Next_Role loop
exit when Manager.Names (I) = null;
if Name = Manager.Names (I).all then
return I;
end if;
end loop;
Log.Debug ("Role {0} not found", Name);
raise Invalid_Name;
end Find_Role;
-- ------------------------------
-- Create a role
-- ------------------------------
procedure Create_Role (Manager : in out Role_Policy;
Name : in String;
Role : out Role_Type) is
begin
Role := Manager.Next_Role;
Log.Info ("Role {0} is {1}", Name, Role_Type'Image (Role));
if Manager.Next_Role = Role_Type'Last then
Log.Error ("Too many roles allocated. Number of roles is {0}",
Role_Type'Image (Role_Type'Last));
else
Manager.Next_Role := Manager.Next_Role + 1;
end if;
Manager.Names (Role) := new String '(Name);
end Create_Role;
-- ------------------------------
-- Get or build a permission type for the given name.
-- ------------------------------
procedure Add_Role_Type (Manager : in out Role_Policy;
Name : in String;
Result : out Role_Type) is
begin
Result := Manager.Find_Role (Name);
exception
when Invalid_Name =>
Manager.Create_Role (Name, Result);
end Add_Role_Type;
type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME);
type Controller_Config_Access is access all Controller_Config;
procedure Set_Member (Into : in out Controller_Config;
Field : in Config_Fields;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- Called while parsing the XML policy file when the <name>, <role> and <role-permission>
-- XML entities are found. Create the new permission when the complete permission definition
-- has been parsed and save the permission in the security manager.
-- ------------------------------
procedure Set_Member (Into : in out Controller_Config;
Field : in Config_Fields;
Value : in Util.Beans.Objects.Object) is
use Security.Controllers.Roles;
begin
case Field is
when FIELD_NAME =>
Into.Name := Value;
when FIELD_ROLE =>
declare
Role : constant String := Util.Beans.Objects.To_String (Value);
begin
Into.Roles (Into.Count + 1) := Into.Manager.Find_Role (Role);
Into.Count := Into.Count + 1;
exception
when Permissions.Invalid_Name =>
raise Util.Serialize.Mappers.Field_Error with "Invalid role: " & Role;
end;
when FIELD_ROLE_PERMISSION =>
if Into.Count = 0 then
raise Util.Serialize.Mappers.Field_Error with "Missing at least one role";
end if;
declare
Name : constant String := Util.Beans.Objects.To_String (Into.Name);
Perm : constant Role_Controller_Access
:= new Role_Controller '(Count => Into.Count,
Roles => Into.Roles (1 .. Into.Count));
begin
Into.Manager.Add_Permission (Name, Perm.all'Access);
Into.Count := 0;
end;
when FIELD_ROLE_NAME =>
declare
Name : constant String := Util.Beans.Objects.To_String (Value);
Role : Role_Type;
begin
Into.Manager.Add_Role_Type (Name, Role);
end;
end case;
end Set_Member;
package Config_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config,
Element_Type_Access => Controller_Config_Access,
Fields => Config_Fields,
Set_Member => Set_Member);
Mapper : aliased Config_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the <b>role-permission</b> description.
-- ------------------------------
procedure Prepare_Config (Policy : in out Role_Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is
Config : Controller_Config_Access := new Controller_Config;
begin
Reader.Add_Mapping ("policy-rules", Mapper'Access);
Reader.Add_Mapping ("module", Mapper'Access);
Config.Manager := Policy'Unchecked_Access;
Config_Mapper.Set_Context (Reader, Config);
end Prepare_Config;
-- ------------------------------
-- Finalize the policy manager.
-- ------------------------------
overriding
procedure Finalize (Policy : in out Role_Policy) is
use type Ada.Strings.Unbounded.String_Access;
begin
for I in Policy.Names'Range loop
exit when Policy.Names (I) = null;
Ada.Strings.Unbounded.Free (Policy.Names (I));
end loop;
end Finalize;
begin
Mapper.Add_Mapping ("role-permission", FIELD_ROLE_PERMISSION);
Mapper.Add_Mapping ("role-permission/name", FIELD_NAME);
Mapper.Add_Mapping ("role-permission/role", FIELD_ROLE);
Mapper.Add_Mapping ("security-role/role-name", FIELD_ROLE_NAME);
end Security.Policies.Roles;
|
-----------------------------------------------------------------------
-- security-policies-roles -- Role based 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 Util.Log.Loggers;
with Util.Serialize.Mappers.Record_Mapper;
with Security.Controllers;
with Security.Controllers.Roles;
package body Security.Policies.Roles is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Security.Policies.Roles");
-- ------------------------------
-- Set the roles which are assigned to the user in the security context.
-- The role policy will use these roles to verify a permission.
-- ------------------------------
procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class;
Roles : in Role_Map) is
Policy : constant Security.Policies.Policy_Access := Context.Get_Policy (NAME);
Data : Role_Policy_Context_Access;
begin
if Policy = null then
Log.Error ("There is no security policy: " & NAME);
end if;
Data := new Role_Policy_Context;
Data.Roles := Roles;
Context.Set_Policy_Context (Policy, Data.all'Access);
end Set_Role_Context;
-- ------------------------------
-- Get the policy name.
-- ------------------------------
overriding
function Get_Name (From : in Role_Policy) return String is
pragma Unreferenced (From);
begin
return NAME;
end Get_Name;
-- ------------------------------
-- Get the role name.
-- ------------------------------
function Get_Role_Name (Manager : in Role_Policy;
Role : in Role_Type) return String is
use type Ada.Strings.Unbounded.String_Access;
begin
if Manager.Names (Role) = null then
return "";
else
return Manager.Names (Role).all;
end if;
end Get_Role_Name;
-- ------------------------------
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
-- ------------------------------
function Find_Role (Manager : in Role_Policy;
Name : in String) return Role_Type is
use type Ada.Strings.Unbounded.String_Access;
begin
Log.Debug ("Searching role {0}", Name);
for I in Role_Type'First .. Manager.Next_Role loop
exit when Manager.Names (I) = null;
if Name = Manager.Names (I).all then
return I;
end if;
end loop;
Log.Debug ("Role {0} not found", Name);
raise Invalid_Name;
end Find_Role;
-- ------------------------------
-- Create a role
-- ------------------------------
procedure Create_Role (Manager : in out Role_Policy;
Name : in String;
Role : out Role_Type) is
begin
Role := Manager.Next_Role;
Log.Info ("Role {0} is {1}", Name, Role_Type'Image (Role));
if Manager.Next_Role = Role_Type'Last then
Log.Error ("Too many roles allocated. Number of roles is {0}",
Role_Type'Image (Role_Type'Last));
else
Manager.Next_Role := Manager.Next_Role + 1;
end if;
Manager.Names (Role) := new String '(Name);
end Create_Role;
-- ------------------------------
-- Get or build a permission type for the given name.
-- ------------------------------
procedure Add_Role_Type (Manager : in out Role_Policy;
Name : in String;
Result : out Role_Type) is
begin
Result := Manager.Find_Role (Name);
exception
when Invalid_Name =>
Manager.Create_Role (Name, Result);
end Add_Role_Type;
type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME);
type Controller_Config_Access is access all Controller_Config;
procedure Set_Member (Into : in out Controller_Config;
Field : in Config_Fields;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- Called while parsing the XML policy file when the <name>, <role> and <role-permission>
-- XML entities are found. Create the new permission when the complete permission definition
-- has been parsed and save the permission in the security manager.
-- ------------------------------
procedure Set_Member (Into : in out Controller_Config;
Field : in Config_Fields;
Value : in Util.Beans.Objects.Object) is
use Security.Controllers.Roles;
begin
case Field is
when FIELD_NAME =>
Into.Name := Value;
when FIELD_ROLE =>
declare
Role : constant String := Util.Beans.Objects.To_String (Value);
begin
Into.Roles (Into.Count + 1) := Into.Manager.Find_Role (Role);
Into.Count := Into.Count + 1;
exception
when Permissions.Invalid_Name =>
raise Util.Serialize.Mappers.Field_Error with "Invalid role: " & Role;
end;
when FIELD_ROLE_PERMISSION =>
if Into.Count = 0 then
raise Util.Serialize.Mappers.Field_Error with "Missing at least one role";
end if;
declare
Name : constant String := Util.Beans.Objects.To_String (Into.Name);
Perm : constant Role_Controller_Access
:= new Role_Controller '(Count => Into.Count,
Roles => Into.Roles (1 .. Into.Count));
begin
Into.Manager.Add_Permission (Name, Perm.all'Access);
Into.Count := 0;
end;
when FIELD_ROLE_NAME =>
declare
Name : constant String := Util.Beans.Objects.To_String (Value);
Role : Role_Type;
begin
Into.Manager.Add_Role_Type (Name, Role);
end;
end case;
end Set_Member;
package Config_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config,
Element_Type_Access => Controller_Config_Access,
Fields => Config_Fields,
Set_Member => Set_Member);
Mapper : aliased Config_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the <b>role-permission</b> description.
-- ------------------------------
procedure Prepare_Config (Policy : in out Role_Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is
Config : Controller_Config_Access := new Controller_Config;
begin
Reader.Add_Mapping ("policy-rules", Mapper'Access);
Reader.Add_Mapping ("module", Mapper'Access);
Config.Manager := Policy'Unchecked_Access;
Config_Mapper.Set_Context (Reader, Config);
end Prepare_Config;
-- ------------------------------
-- Finalize the policy manager.
-- ------------------------------
overriding
procedure Finalize (Policy : in out Role_Policy) is
use type Ada.Strings.Unbounded.String_Access;
begin
for I in Policy.Names'Range loop
exit when Policy.Names (I) = null;
Ada.Strings.Unbounded.Free (Policy.Names (I));
end loop;
end Finalize;
begin
Mapper.Add_Mapping ("role-permission", FIELD_ROLE_PERMISSION);
Mapper.Add_Mapping ("role-permission/name", FIELD_NAME);
Mapper.Add_Mapping ("role-permission/role", FIELD_ROLE);
Mapper.Add_Mapping ("security-role/role-name", FIELD_ROLE_NAME);
end Security.Policies.Roles;
|
Implement Set_Role_Context
|
Implement Set_Role_Context
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
e02b126a2408fba8ce14852b43f0705779f3ad19
|
src/atlas-applications.adb
|
src/atlas-applications.adb
|
-----------------------------------------------------------------------
-- atlas -- atlas applications
-----------------------------------------------------------------------
-- Copyright (C) 2012, 2013, 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
with GNAT.MD5;
with Util.Log.Loggers;
with Util.Properties;
with Util.Beans.Basic;
with Util.Strings.Transforms;
with EL.Functions;
with ASF.Applications;
with ASF.Applications.Main;
with ADO.Queries;
with ADO.Sessions;
with AWA.Applications.Factory;
with AWA.Services.Contexts;
with Atlas.Applications.Models;
-- with Atlas.XXX.Module;
package body Atlas.Applications is
package ASC renames AWA.Services.Contexts;
use AWA.Applications;
type User_Stat_Info_Access is access all Atlas.Applications.Models.User_Stat_Info;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Atlas");
procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class);
function Create_User_Stat_Bean return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Create the user statistics bean which indicates what feature the user has used.
-- ------------------------------
function Create_User_Stat_Bean return Util.Beans.Basic.Readonly_Bean_Access is
use type ASC.Service_Context_Access;
Ctx : constant ASC.Service_Context_Access := ASC.Current;
Result : User_Stat_Info_Access;
begin
if Ctx /= null then
declare
List : Atlas.Applications.Models.User_Stat_Info_List_Bean;
Session : ADO.Sessions.Session := ASC.Get_Session (Ctx);
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Query : ADO.Queries.Context;
begin
Query.Set_Query (Atlas.Applications.Models.Query_User_Stat);
Query.Bind_Param ("user_id", User);
Atlas.Applications.Models.List (List, Session, Query);
Result := new Atlas.Applications.Models.User_Stat_Info;
Result.all := List.List.Element (0);
end;
else
Result := new Atlas.Applications.Models.User_Stat_Info;
Result.Post_Count := 0;
Result.Document_Count := 0;
Result.Question_Count := 0;
Result.Answer_Count := 0;
end if;
return Result.all'Access;
end Create_User_Stat_Bean;
-- ------------------------------
-- Given an Email address, return the Gravatar link to the user image.
-- (See http://en.gravatar.com/site/implement/hash/ and
-- http://en.gravatar.com/site/implement/images/)
-- ------------------------------
function Get_Gravatar_Link (Email : in String) return String is
E : constant String := Util.Strings.Transforms.To_Lower_Case (Email);
C : constant GNAT.MD5.Message_Digest := GNAT.MD5.Digest (E);
begin
return "http://www.gravatar.com/avatar/" & C;
end Get_Gravatar_Link;
-- ------------------------------
-- EL function to convert an Email address to a Gravatar image.
-- ------------------------------
function To_Gravatar_Link (Email : in Util.Beans.Objects.Object)
return Util.Beans.Objects.Object is
Link : constant String := Get_Gravatar_Link (Util.Beans.Objects.To_String (Email));
begin
return Util.Beans.Objects.To_Object (Link);
end To_Gravatar_Link;
procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class) is
begin
Mapper.Set_Function (Name => "gravatar",
Namespace => ATLAS_NS_URI,
Func => To_Gravatar_Link'Access);
end Set_Functions;
-- ------------------------------
-- Initialize the application:
-- <ul>
-- <li>Register the servlets and filters.
-- <li>Register the application modules.
-- <li>Define the servlet and filter mappings.
-- </ul>
-- ------------------------------
procedure Initialize (App : in Application_Access) is
Fact : AWA.Applications.Factory.Application_Factory;
C : ASF.Applications.Config;
begin
App.Self := App;
begin
C.Load_Properties ("atlas.properties");
Util.Log.Loggers.Initialize (Util.Properties.Manager (C));
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot read application configuration file {0}", CONFIG_PATH);
end;
App.Initialize (C, Fact);
App.Set_Global ("contextPath", CONTEXT_PATH);
end Initialize;
-- ------------------------------
-- Initialize the ASF components provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the component factories used by the application.
-- ------------------------------
overriding
procedure Initialize_Components (App : in out Application) is
procedure Register is
new ASF.Applications.Main.Register_Functions (Set_Functions);
begin
Register (App);
AWA.Applications.Application (App).Initialize_Components;
App.Add_Converter (Name => "smartDateConverter",
Converter => App.Self.Rel_Date_Converter'Access);
App.Add_Converter (Name => "sizeConverter",
Converter => App.Self.Size_Converter'Access);
App.Register_Class (Name => "Atlas.Applications.User_Stat_Bean",
Handler => Create_User_Stat_Bean'Access);
end Initialize_Components;
-- ------------------------------
-- Initialize the servlets provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application servlets.
-- ------------------------------
overriding
procedure Initialize_Servlets (App : in out Application) is
begin
Log.Info ("Initializing application servlets...");
AWA.Applications.Application (App).Initialize_Servlets;
App.Add_Servlet (Name => "faces", Server => App.Self.Faces'Access);
App.Add_Servlet (Name => "files", Server => App.Self.Files'Access);
App.Add_Servlet (Name => "ajax", Server => App.Self.Ajax'Access);
App.Add_Servlet (Name => "measures", Server => App.Self.Measures'Access);
App.Add_Servlet (Name => "auth", Server => App.Self.Auth'Access);
App.Add_Servlet (Name => "verify-auth", Server => App.Self.Verify_Auth'Access);
end Initialize_Servlets;
-- ------------------------------
-- Initialize the filters provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application filters.
-- ------------------------------
overriding
procedure Initialize_Filters (App : in out Application) is
begin
Log.Info ("Initializing application filters...");
AWA.Applications.Application (App).Initialize_Filters;
App.Add_Filter (Name => "dump", Filter => App.Self.Dump'Access);
App.Add_Filter (Name => "measures", Filter => App.Self.Measures'Access);
App.Add_Filter (Name => "service", Filter => App.Self.Service_Filter'Access);
App.Add_Filter (Name => "no-cache", Filter => App.Self.No_Cache'Access);
end Initialize_Filters;
-- ------------------------------
-- Initialize the AWA modules provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the modules used by the application.
-- ------------------------------
overriding
procedure Initialize_Modules (App : in out Application) is
begin
Log.Info ("Initializing application modules...");
Register (App => App.Self.all'Access,
Name => AWA.Users.Modules.NAME,
URI => "user",
Module => App.User_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Workspaces.Modules.NAME,
URI => "workspaces",
Module => App.Workspace_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Mail.Modules.NAME,
URI => "mail",
Module => App.Mail_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Counters.Modules.NAME,
Module => App.Counter_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Jobs.Modules.NAME,
URI => "jobs",
Module => App.Job_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Tags.Modules.NAME,
URI => "tags",
Module => App.Tag_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Comments.Modules.NAME,
URI => "comments",
Module => App.Comment_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Blogs.Modules.NAME,
URI => "blogs",
Module => App.Blog_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Storages.Modules.NAME,
URI => "storages",
Module => App.Storage_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Images.Modules.NAME,
URI => "images",
Module => App.Image_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Votes.Modules.NAME,
URI => "votes",
Module => App.Vote_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Questions.Modules.NAME,
URI => "questions",
Module => App.Question_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Wikis.Modules.NAME,
URI => "wikis",
Module => App.Wiki_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Wikis.Previews.NAME,
URI => "wikis-preview",
Module => App.Preview_Module'Access);
Register (App => App.Self.all'Access,
Name => Atlas.Microblog.Modules.NAME,
URI => "microblog",
Module => App.Microblog_Module'Access);
Register (App => App.Self.all'Access,
Name => Atlas.Reviews.Modules.NAME,
URI => "reviews",
Module => App.Review_Module'Access);
end Initialize_Modules;
end Atlas.Applications;
|
-----------------------------------------------------------------------
-- atlas -- atlas applications
-----------------------------------------------------------------------
-- Copyright (C) 2012, 2013, 2014, 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 GNAT.MD5;
with Util.Log.Loggers;
with Util.Beans.Basic;
with Util.Strings.Transforms;
with EL.Functions;
with ASF.Applications.Main;
with ADO.Queries;
with ADO.Sessions;
with AWA.Applications.Factory;
with AWA.Services.Contexts;
with Atlas.Applications.Models;
-- with Atlas.XXX.Module;
package body Atlas.Applications is
package ASC renames AWA.Services.Contexts;
use AWA.Applications;
type User_Stat_Info_Access is access all Atlas.Applications.Models.User_Stat_Info;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Atlas");
procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class);
function Create_User_Stat_Bean return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Create the user statistics bean which indicates what feature the user has used.
-- ------------------------------
function Create_User_Stat_Bean return Util.Beans.Basic.Readonly_Bean_Access is
use type ASC.Service_Context_Access;
Ctx : constant ASC.Service_Context_Access := ASC.Current;
Result : User_Stat_Info_Access;
begin
if Ctx /= null then
declare
List : Atlas.Applications.Models.User_Stat_Info_List_Bean;
Session : ADO.Sessions.Session := ASC.Get_Session (Ctx);
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Query : ADO.Queries.Context;
begin
Query.Set_Query (Atlas.Applications.Models.Query_User_Stat);
Query.Bind_Param ("user_id", User);
Atlas.Applications.Models.List (List, Session, Query);
Result := new Atlas.Applications.Models.User_Stat_Info;
Result.all := List.List.Element (0);
end;
else
Result := new Atlas.Applications.Models.User_Stat_Info;
Result.Post_Count := 0;
Result.Document_Count := 0;
Result.Question_Count := 0;
Result.Answer_Count := 0;
end if;
return Result.all'Access;
end Create_User_Stat_Bean;
-- ------------------------------
-- Given an Email address, return the Gravatar link to the user image.
-- (See http://en.gravatar.com/site/implement/hash/ and
-- http://en.gravatar.com/site/implement/images/)
-- ------------------------------
function Get_Gravatar_Link (Email : in String) return String is
E : constant String := Util.Strings.Transforms.To_Lower_Case (Email);
C : constant GNAT.MD5.Message_Digest := GNAT.MD5.Digest (E);
begin
return "http://www.gravatar.com/avatar/" & C;
end Get_Gravatar_Link;
-- ------------------------------
-- EL function to convert an Email address to a Gravatar image.
-- ------------------------------
function To_Gravatar_Link (Email : in Util.Beans.Objects.Object)
return Util.Beans.Objects.Object is
Link : constant String := Get_Gravatar_Link (Util.Beans.Objects.To_String (Email));
begin
return Util.Beans.Objects.To_Object (Link);
end To_Gravatar_Link;
procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class) is
begin
Mapper.Set_Function (Name => "gravatar",
Namespace => ATLAS_NS_URI,
Func => To_Gravatar_Link'Access);
end Set_Functions;
-- ------------------------------
-- Initialize the application:
-- <ul>
-- <li>Register the servlets and filters.
-- <li>Register the application modules.
-- <li>Define the servlet and filter mappings.
-- </ul>
-- ------------------------------
procedure Initialize (App : in Application_Access;
Config : in ASF.Applications.Config) is
Fact : AWA.Applications.Factory.Application_Factory;
begin
App.Self := App;
App.Initialize (Config, Fact);
App.Set_Global ("contextPath", CONTEXT_PATH);
end Initialize;
-- ------------------------------
-- Initialize the ASF components provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the component factories used by the application.
-- ------------------------------
overriding
procedure Initialize_Components (App : in out Application) is
procedure Register is
new ASF.Applications.Main.Register_Functions (Set_Functions);
begin
Register (App);
AWA.Applications.Application (App).Initialize_Components;
App.Add_Converter (Name => "smartDateConverter",
Converter => App.Self.Rel_Date_Converter'Access);
App.Add_Converter (Name => "sizeConverter",
Converter => App.Self.Size_Converter'Access);
App.Register_Class (Name => "Atlas.Applications.User_Stat_Bean",
Handler => Create_User_Stat_Bean'Access);
end Initialize_Components;
-- ------------------------------
-- Initialize the servlets provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application servlets.
-- ------------------------------
overriding
procedure Initialize_Servlets (App : in out Application) is
begin
Log.Info ("Initializing application servlets...");
AWA.Applications.Application (App).Initialize_Servlets;
App.Add_Servlet (Name => "faces", Server => App.Self.Faces'Access);
App.Add_Servlet (Name => "files", Server => App.Self.Files'Access);
App.Add_Servlet (Name => "ajax", Server => App.Self.Ajax'Access);
App.Add_Servlet (Name => "measures", Server => App.Self.Measures'Access);
App.Add_Servlet (Name => "auth", Server => App.Self.Auth'Access);
App.Add_Servlet (Name => "verify-auth", Server => App.Self.Verify_Auth'Access);
end Initialize_Servlets;
-- ------------------------------
-- Initialize the filters provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application filters.
-- ------------------------------
overriding
procedure Initialize_Filters (App : in out Application) is
begin
Log.Info ("Initializing application filters...");
AWA.Applications.Application (App).Initialize_Filters;
App.Add_Filter (Name => "dump", Filter => App.Self.Dump'Access);
App.Add_Filter (Name => "measures", Filter => App.Self.Measures'Access);
App.Add_Filter (Name => "service", Filter => App.Self.Service_Filter'Access);
App.Add_Filter (Name => "no-cache", Filter => App.Self.No_Cache'Access);
end Initialize_Filters;
-- ------------------------------
-- Initialize the AWA modules provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the modules used by the application.
-- ------------------------------
overriding
procedure Initialize_Modules (App : in out Application) is
begin
Log.Info ("Initializing application modules...");
Register (App => App.Self.all'Access,
Name => AWA.Users.Modules.NAME,
URI => "user",
Module => App.User_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Workspaces.Modules.NAME,
URI => "workspaces",
Module => App.Workspace_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Mail.Modules.NAME,
URI => "mail",
Module => App.Mail_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Counters.Modules.NAME,
Module => App.Counter_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Jobs.Modules.NAME,
URI => "jobs",
Module => App.Job_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Tags.Modules.NAME,
URI => "tags",
Module => App.Tag_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Comments.Modules.NAME,
URI => "comments",
Module => App.Comment_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Blogs.Modules.NAME,
URI => "blogs",
Module => App.Blog_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Storages.Modules.NAME,
URI => "storages",
Module => App.Storage_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Images.Modules.NAME,
URI => "images",
Module => App.Image_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Votes.Modules.NAME,
URI => "votes",
Module => App.Vote_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Questions.Modules.NAME,
URI => "questions",
Module => App.Question_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Wikis.Modules.NAME,
URI => "wikis",
Module => App.Wiki_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Wikis.Previews.NAME,
URI => "wikis-preview",
Module => App.Preview_Module'Access);
Register (App => App.Self.all'Access,
Name => Atlas.Microblog.Modules.NAME,
URI => "microblog",
Module => App.Microblog_Module'Access);
Register (App => App.Self.all'Access,
Name => Atlas.Reviews.Modules.NAME,
URI => "reviews",
Module => App.Review_Module'Access);
end Initialize_Modules;
end Atlas.Applications;
|
Update the Initialize procedure to use the Config properties passed as parameter
|
Update the Initialize procedure to use the Config properties passed as parameter
|
Ada
|
apache-2.0
|
stcarrez/atlas
|
8efc2af2bf5d473626176ec1cc76dd008cce0b3f
|
src/util-serialize-io.ads
|
src/util-serialize-io.ads
|
-----------------------------------------------------------------------
-- util-serialize-io -- IO Drivers for serialization
-- Copyright (C) 2010, 2011, 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.Containers;
with Ada.Strings.Unbounded;
with Util.Beans.Objects;
with Util.Streams;
with Util.Streams.Buffered;
with Util.Serialize.Contexts;
with Util.Serialize.Mappers;
with Util.Log.Loggers;
with Util.Stacks;
package Util.Serialize.IO is
Parse_Error : exception;
-- ------------------------------
-- Output stream for serialization
-- ------------------------------
-- The <b>Output_Stream</b> interface defines the abstract operations for
-- the serialization framework to write objects on the stream according to
-- a target format such as XML or JSON.
type Output_Stream is limited interface and Util.Streams.Output_Stream;
-- Start a document.
procedure Start_Document (Stream : in out Output_Stream) is null;
-- Finish a document.
procedure End_Document (Stream : in out Output_Stream) is null;
procedure Start_Entity (Stream : in out Output_Stream;
Name : in String) is null;
procedure End_Entity (Stream : in out Output_Stream;
Name : in String) is null;
-- Write the attribute name/value pair.
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String) is abstract;
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is abstract;
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is abstract;
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is abstract;
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is abstract;
procedure Write_Attribute (Stream : in out Output_Stream'Class;
Name : in String;
Value : in Ada.Strings.Unbounded.Unbounded_String);
-- Write the entity value.
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is abstract;
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is abstract;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is abstract;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is abstract;
procedure Write_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer) is abstract;
procedure Write_Enum_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is abstract;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is abstract;
procedure Write_Entity (Stream : in out Output_Stream'Class;
Name : in String;
Value : in Ada.Strings.Unbounded.Unbounded_String);
procedure Start_Array (Stream : in out Output_Stream;
Name : in String) is null;
procedure End_Array (Stream : in out Output_Stream;
Name : in String) is null;
type Parser is abstract new Util.Serialize.Contexts.Context with private;
-- Parse the stream using the JSON parser.
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class) is abstract;
-- Read the file and parse it using the parser.
procedure Parse (Handler : in out Parser;
File : in String);
-- Parse the content string.
procedure Parse_String (Handler : in out Parser;
Content : in String);
-- Returns true if the <b>Parse</b> operation detected at least one error.
function Has_Error (Handler : in Parser) return Boolean;
-- Set the error logger to report messages while parsing and reading the input file.
procedure Set_Logger (Handler : in out Parser;
Logger : in Util.Log.Loggers.Logger_Access);
-- Start a new object associated with the given name. This is called when
-- the '{' is reached. The reader must be updated so that the next
-- <b>Set_Member</b> procedure will associate the name/value pair on the
-- new object.
procedure Start_Object (Handler : in out Parser;
Name : in String);
-- Finish an object associated with the given name. The reader must be
-- updated to be associated with the previous object.
procedure Finish_Object (Handler : in out Parser;
Name : in String);
procedure Start_Array (Handler : in out Parser;
Name : in String);
procedure Finish_Array (Handler : in out Parser;
Name : in String);
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
procedure Set_Member (Handler : in out Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False);
-- Get the current location (file and line) to report an error message.
function Get_Location (Handler : in Parser) return String;
-- 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);
procedure Add_Mapping (Handler : in out Parser;
Path : in String;
Mapper : in Util.Serialize.Mappers.Mapper_Access);
-- Dump the mapping tree on the logger using the INFO log level.
procedure Dump (Handler : in Parser'Class;
Logger : in Util.Log.Loggers.Logger'Class);
private
-- Implementation limitation: the max number of active mapping nodes
MAX_NODES : constant Positive := 10;
type Mapper_Access_Array is array (1 .. MAX_NODES) of Serialize.Mappers.Mapper_Access;
procedure Push (Handler : in out Parser);
-- Pop the context and restore the previous context when leaving an element
procedure Pop (Handler : in out Parser);
function Find_Mapper (Handler : in Parser;
Name : in String) return Util.Serialize.Mappers.Mapper_Access;
type Element_Context is record
-- The object mapper being process.
Object_Mapper : Util.Serialize.Mappers.Mapper_Access;
-- The active mapping nodes.
Active_Nodes : Mapper_Access_Array;
end record;
type Element_Context_Access is access all Element_Context;
package Context_Stack is new Util.Stacks (Element_Type => Element_Context,
Element_Type_Access => Element_Context_Access);
type Parser is abstract new Util.Serialize.Contexts.Context with record
Error_Flag : Boolean := False;
Stack : Context_Stack.Stack;
Mapping_Tree : aliased Mappers.Mapper;
Current_Mapper : Util.Serialize.Mappers.Mapper_Access;
-- The file name to use when reporting errors.
File : Ada.Strings.Unbounded.Unbounded_String;
-- The logger which is used to report error messages when parsing an input file.
Error_Logger : Util.Log.Loggers.Logger_Access := null;
end record;
end Util.Serialize.IO;
|
-----------------------------------------------------------------------
-- util-serialize-io -- IO Drivers for serialization
-- Copyright (C) 2010, 2011, 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.Containers;
with Ada.Strings.Unbounded;
with Ada.Calendar;
with Util.Beans.Objects;
with Util.Streams;
with Util.Streams.Buffered;
with Util.Serialize.Contexts;
with Util.Serialize.Mappers;
with Util.Log.Loggers;
with Util.Stacks;
package Util.Serialize.IO is
Parse_Error : exception;
-- ------------------------------
-- Output stream for serialization
-- ------------------------------
-- The <b>Output_Stream</b> interface defines the abstract operations for
-- the serialization framework to write objects on the stream according to
-- a target format such as XML or JSON.
type Output_Stream is limited interface and Util.Streams.Output_Stream;
-- Start a document.
procedure Start_Document (Stream : in out Output_Stream) is null;
-- Finish a document.
procedure End_Document (Stream : in out Output_Stream) is null;
procedure Start_Entity (Stream : in out Output_Stream;
Name : in String) is null;
procedure End_Entity (Stream : in out Output_Stream;
Name : in String) is null;
-- Write the attribute name/value pair.
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String) is abstract;
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is abstract;
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is abstract;
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is abstract;
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is abstract;
procedure Write_Attribute (Stream : in out Output_Stream'Class;
Name : in String;
Value : in Ada.Strings.Unbounded.Unbounded_String);
-- Write the entity value.
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is abstract;
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is abstract;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is abstract;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is abstract;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Ada.Calendar.Time) is abstract;
procedure Write_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer) is abstract;
procedure Write_Enum_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is abstract;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is abstract;
procedure Write_Entity (Stream : in out Output_Stream'Class;
Name : in String;
Value : in Ada.Strings.Unbounded.Unbounded_String);
procedure Start_Array (Stream : in out Output_Stream;
Name : in String) is null;
procedure End_Array (Stream : in out Output_Stream;
Name : in String) is null;
type Parser is abstract new Util.Serialize.Contexts.Context with private;
-- Parse the stream using the JSON parser.
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class) is abstract;
-- Read the file and parse it using the parser.
procedure Parse (Handler : in out Parser;
File : in String);
-- Parse the content string.
procedure Parse_String (Handler : in out Parser;
Content : in String);
-- Returns true if the <b>Parse</b> operation detected at least one error.
function Has_Error (Handler : in Parser) return Boolean;
-- Set the error logger to report messages while parsing and reading the input file.
procedure Set_Logger (Handler : in out Parser;
Logger : in Util.Log.Loggers.Logger_Access);
-- Start a new object associated with the given name. This is called when
-- the '{' is reached. The reader must be updated so that the next
-- <b>Set_Member</b> procedure will associate the name/value pair on the
-- new object.
procedure Start_Object (Handler : in out Parser;
Name : in String);
-- Finish an object associated with the given name. The reader must be
-- updated to be associated with the previous object.
procedure Finish_Object (Handler : in out Parser;
Name : in String);
procedure Start_Array (Handler : in out Parser;
Name : in String);
procedure Finish_Array (Handler : in out Parser;
Name : in String);
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
procedure Set_Member (Handler : in out Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False);
-- Get the current location (file and line) to report an error message.
function Get_Location (Handler : in Parser) return String;
-- 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);
procedure Add_Mapping (Handler : in out Parser;
Path : in String;
Mapper : in Util.Serialize.Mappers.Mapper_Access);
-- Dump the mapping tree on the logger using the INFO log level.
procedure Dump (Handler : in Parser'Class;
Logger : in Util.Log.Loggers.Logger'Class);
private
-- Implementation limitation: the max number of active mapping nodes
MAX_NODES : constant Positive := 10;
type Mapper_Access_Array is array (1 .. MAX_NODES) of Serialize.Mappers.Mapper_Access;
procedure Push (Handler : in out Parser);
-- Pop the context and restore the previous context when leaving an element
procedure Pop (Handler : in out Parser);
function Find_Mapper (Handler : in Parser;
Name : in String) return Util.Serialize.Mappers.Mapper_Access;
type Element_Context is record
-- The object mapper being process.
Object_Mapper : Util.Serialize.Mappers.Mapper_Access;
-- The active mapping nodes.
Active_Nodes : Mapper_Access_Array;
end record;
type Element_Context_Access is access all Element_Context;
package Context_Stack is new Util.Stacks (Element_Type => Element_Context,
Element_Type_Access => Element_Context_Access);
type Parser is abstract new Util.Serialize.Contexts.Context with record
Error_Flag : Boolean := False;
Stack : Context_Stack.Stack;
Mapping_Tree : aliased Mappers.Mapper;
Current_Mapper : Util.Serialize.Mappers.Mapper_Access;
-- The file name to use when reporting errors.
File : Ada.Strings.Unbounded.Unbounded_String;
-- The logger which is used to report error messages when parsing an input file.
Error_Logger : Util.Log.Loggers.Logger_Access := null;
end record;
end Util.Serialize.IO;
|
Declare the Write_Entity operation with a date/time
|
Declare the Write_Entity operation with a date/time
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
8857674ac08faec44ec817a5eba672f7f4e74eda
|
src/wiki-filters-html.adb
|
src/wiki-filters-html.adb
|
-----------------------------------------------------------------------
-- wiki-filters-html -- Wiki HTML filters
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Wide_Wide_Characters.Handling;
package body Wiki.Filters.Html is
function Need_Close (Tag : in Html_Tag_Type;
Current_Tag : in Html_Tag_Type) return Boolean;
type Tag_Name_Array is array (Html_Tag_Type) of Unbounded_Wide_Wide_String;
No_End_Tag : constant Tag_Boolean_Array :=
(
BASE_TAG => True,
LINK_TAG => True,
META_TAG => True,
IMG_TAG => True,
HR_TAG => True,
BR_TAG => True,
WBR_TAG => True,
INPUT_TAG => True,
KEYGEN_TAG => True,
others => False);
Tag_Omission : constant Tag_Boolean_Array :=
(
-- Section 4.4 Grouping content
LI_TAG => True,
DT_TAG => True,
DD_TAG => True,
-- Section 4.5 Text-level semantics
RB_TAG => True,
RT_TAG => True,
RTC_TAG => True,
RP_TAG => True,
-- Section 4.9 Tabular data
TH_TAG => True,
TD_TAG => True,
TR_TAG => True,
TBODY_TAG => True,
THEAD_TAG => True,
TFOOT_TAG => True,
OPTGROUP_TAG => True,
OPTION_TAG => True,
others => False);
-- ------------------------------
-- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document.
-- ------------------------------
overriding
procedure Add_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Kind : in Wiki.Nodes.Simple_Node_Kind) is
Tag : Html_Tag_Type;
begin
case Kind is
when N_LINE_BREAK =>
Tag := BR_TAG;
when N_PARAGRAPH =>
Tag := P_TAG;
when N_HORIZONTAL_RULE =>
Tag := HR_TAG;
end case;
if Filter.Allowed (Tag) then
Filter_Type (Filter).Add_Node (Document, Kind);
end if;
end Add_Node;
-- ------------------------------
-- Add a text content with the given format to the document.
-- ------------------------------
overriding
procedure Add_Text (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Nodes.Format_Map) is
begin
if Filter.Hide_Level > 0 then
return;
elsif not Filter.Stack.Is_Empty then
declare
Current_Tag : constant Html_Tag_Type := Filter.Stack.Last_Element;
begin
if No_End_Tag (Current_Tag) then
Filter_Type (Filter).Pop_Node (Document, Current_Tag);
Filter.Stack.Delete_Last;
end if;
end;
end if;
Filter_Type (Filter).Add_Text (Document, Text, Format);
end Add_Text;
-- ------------------------------
-- Add a section header with the given level in the document.
-- ------------------------------
overriding
procedure Add_Header (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Header : in Wiki.Strings.WString;
Level : in Natural) is
begin
Filter.Flush_Stack (Document);
Filter_Type (Filter).Add_Header (Document, Header, Level);
end Add_Header;
-- ------------------------------
-- Push a HTML node with the given tag to the document.
-- ------------------------------
overriding
procedure Push_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Tag : in Wiki.Nodes.Html_Tag_Type;
Attributes : in out Wiki.Attributes.Attribute_List_Type) is
Current_Tag : Html_Tag_Type;
begin
while not Filter.Stack.Is_Empty loop
Current_Tag := Filter.Stack.Last_Element;
if Need_Close (Tag, Current_Tag) then
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Pop_Node (Document, Current_Tag);
end if;
Filter.Stack.Delete_Last;
end if;
exit when not No_End_Tag (Current_Tag);
end loop;
if Filter.Hidden (Tag) then
Filter.Hide_Level := Filter.Hide_Level + 1;
elsif not Filter.Allowed (Tag) then
return;
end if;
Filter.Stack.Append (Tag);
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Push_Node (Document, Tag, Attributes);
end if;
end Push_Node;
-- ------------------------------
-- Pop a HTML node with the given tag.
-- ------------------------------
overriding
procedure Pop_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Tag : in Wiki.Nodes.Html_Tag_Type) is
Current_Tag : Html_Tag_Type;
begin
if Filter.Stack.Is_Empty then
return;
elsif not Filter.Allowed (Tag) and not Filter.Hidden (Tag) then
return;
end if;
-- Emit a end tag element until we find our matching tag and the top most tag
-- allows the end tag to be omitted (ex: a td, tr, td, dd, ...).
while not Filter.Stack.Is_Empty loop
Current_Tag := Filter.Stack.Last_Element;
exit when Current_Tag = Tag or not Tag_Omission (Current_Tag);
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Pop_Node (Document, Current_Tag);
end if;
Filter.Stack.Delete_Last;
end loop;
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Pop_Node (Document, Tag);
end if;
if Filter.Hidden (Current_Tag) then
Filter.Hide_Level := Filter.Hide_Level - 1;
end if;
Filter.Stack.Delete_Last;
end Pop_Node;
-- ------------------------------
-- Add a link.
-- ------------------------------
overriding
procedure Add_Link (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List_Type) is
begin
if Filter.Allowed (A_TAG) then
Filter_Type (Filter).Add_Link (Document, Name, Attributes);
end if;
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
overriding
procedure Add_Image (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List_Type) is
begin
if Filter.Allowed (IMG_TAG) then
Filter_Type (Filter).Add_Image (Document, Name, Attributes);
end if;
end Add_Image;
-- ------------------------------
-- Given the current tag on the top of the stack and the new tag that will be pushed,
-- decide whether the current tag must be closed or not.
-- Returns True if the current tag must be closed.
-- ------------------------------
function Need_Close (Tag : in Html_Tag_Type;
Current_Tag : in Html_Tag_Type) return Boolean is
begin
if No_End_Tag (Current_Tag) then
return True;
elsif Current_Tag = Tag and Tag_Omission (Current_Tag) then
return True;
else
case Current_Tag is
when DT_TAG | DD_TAG =>
return Tag = DD_TAG or Tag = DL_TAG or Tag = DT_TAG;
when TD_TAG =>
return Tag = TD_TAG or Tag = TR_TAG or Tag = TH_TAG;
when TR_TAG =>
return False;
when others =>
return False;
end case;
end if;
end Need_Close;
-- ------------------------------
-- Flush the HTML element that have not yet been closed.
-- ------------------------------
procedure Flush_Stack (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document) is
begin
while not Filter.Stack.Is_Empty loop
declare
Tag : constant Html_Tag_Type := Filter.Stack.Last_Element;
begin
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Pop_Node (Document, Tag);
end if;
if Filter.Hidden (Tag) then
Filter.Hide_Level := Filter.Hide_Level - 1;
end if;
end;
Filter.Stack.Delete_Last;
end loop;
end Flush_Stack;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document) is
begin
Filter.Flush_Stack (Document);
Filter_Type (Filter).Finish (Document);
end Finish;
-- ------------------------------
-- Mark the HTML tag as being forbidden.
-- ------------------------------
procedure Forbidden (Filter : in out Html_Filter_Type;
Tag : in Html_Tag_Type) is
begin
Filter.Allowed (Tag) := False;
end Forbidden;
-- ------------------------------
-- Mark the HTML tag as being allowed.
-- ------------------------------
procedure Allowed (Filter : in out Html_Filter_Type;
Tag : in Html_Tag_Type) is
begin
Filter.Allowed (Tag) := True;
end Allowed;
-- ------------------------------
-- Mark the HTML tag as being hidden. The tag and its inner content including the text
-- will be removed and not passed to the final document.
-- ------------------------------
procedure Hide (Filter : in out Html_Filter_Type;
Tag : in Html_Tag_Type) is
begin
Filter.Hidden (Tag) := True;
end Hide;
-- ------------------------------
-- Mark the HTML tag as being visible.
-- ------------------------------
procedure Visible (Filter : in out Html_Filter_Type;
Tag : in Html_Tag_Type) is
begin
Filter.Hidden (Tag) := False;
end Visible;
end Wiki.Filters.Html;
|
-----------------------------------------------------------------------
-- wiki-filters-html -- Wiki HTML filters
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Wide_Wide_Characters.Handling;
package body Wiki.Filters.Html is
function Need_Close (Tag : in Html_Tag_Type;
Current_Tag : in Html_Tag_Type) return Boolean;
No_End_Tag : constant Tag_Boolean_Array :=
(
BASE_TAG => True,
LINK_TAG => True,
META_TAG => True,
IMG_TAG => True,
HR_TAG => True,
BR_TAG => True,
WBR_TAG => True,
INPUT_TAG => True,
KEYGEN_TAG => True,
others => False);
Tag_Omission : constant Tag_Boolean_Array :=
(
-- Section 4.4 Grouping content
LI_TAG => True,
DT_TAG => True,
DD_TAG => True,
-- Section 4.5 Text-level semantics
RB_TAG => True,
RT_TAG => True,
RTC_TAG => True,
RP_TAG => True,
-- Section 4.9 Tabular data
TH_TAG => True,
TD_TAG => True,
TR_TAG => True,
TBODY_TAG => True,
THEAD_TAG => True,
TFOOT_TAG => True,
OPTGROUP_TAG => True,
OPTION_TAG => True,
others => False);
-- ------------------------------
-- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document.
-- ------------------------------
overriding
procedure Add_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Kind : in Wiki.Nodes.Simple_Node_Kind) is
Tag : Html_Tag_Type;
begin
case Kind is
when N_LINE_BREAK =>
Tag := BR_TAG;
when N_PARAGRAPH =>
Tag := P_TAG;
when N_HORIZONTAL_RULE =>
Tag := HR_TAG;
end case;
if Filter.Allowed (Tag) then
Filter_Type (Filter).Add_Node (Document, Kind);
end if;
end Add_Node;
-- ------------------------------
-- Add a text content with the given format to the document.
-- ------------------------------
overriding
procedure Add_Text (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map) is
begin
if Filter.Hide_Level > 0 then
return;
elsif not Filter.Stack.Is_Empty then
declare
Current_Tag : constant Html_Tag_Type := Filter.Stack.Last_Element;
begin
if No_End_Tag (Current_Tag) then
Filter_Type (Filter).Pop_Node (Document, Current_Tag);
Filter.Stack.Delete_Last;
end if;
end;
end if;
Filter_Type (Filter).Add_Text (Document, Text, Format);
end Add_Text;
-- ------------------------------
-- Add a section header with the given level in the document.
-- ------------------------------
overriding
procedure Add_Header (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Header : in Wiki.Strings.WString;
Level : in Natural) is
begin
Filter.Flush_Stack (Document);
Filter_Type (Filter).Add_Header (Document, Header, Level);
end Add_Header;
-- ------------------------------
-- Push a HTML node with the given tag to the document.
-- ------------------------------
overriding
procedure Push_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Tag : in Wiki.Nodes.Html_Tag_Type;
Attributes : in out Wiki.Attributes.Attribute_List_Type) is
Current_Tag : Html_Tag_Type;
begin
while not Filter.Stack.Is_Empty loop
Current_Tag := Filter.Stack.Last_Element;
if Need_Close (Tag, Current_Tag) then
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Pop_Node (Document, Current_Tag);
end if;
Filter.Stack.Delete_Last;
end if;
exit when not No_End_Tag (Current_Tag);
end loop;
if Filter.Hidden (Tag) then
Filter.Hide_Level := Filter.Hide_Level + 1;
elsif not Filter.Allowed (Tag) then
return;
end if;
Filter.Stack.Append (Tag);
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Push_Node (Document, Tag, Attributes);
end if;
end Push_Node;
-- ------------------------------
-- Pop a HTML node with the given tag.
-- ------------------------------
overriding
procedure Pop_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Tag : in Wiki.Nodes.Html_Tag_Type) is
Current_Tag : Html_Tag_Type;
begin
if Filter.Stack.Is_Empty then
return;
elsif not Filter.Allowed (Tag) and not Filter.Hidden (Tag) then
return;
end if;
-- Emit a end tag element until we find our matching tag and the top most tag
-- allows the end tag to be omitted (ex: a td, tr, td, dd, ...).
while not Filter.Stack.Is_Empty loop
Current_Tag := Filter.Stack.Last_Element;
exit when Current_Tag = Tag or not Tag_Omission (Current_Tag);
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Pop_Node (Document, Current_Tag);
end if;
Filter.Stack.Delete_Last;
end loop;
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Pop_Node (Document, Tag);
end if;
if Filter.Hidden (Current_Tag) then
Filter.Hide_Level := Filter.Hide_Level - 1;
end if;
Filter.Stack.Delete_Last;
end Pop_Node;
-- ------------------------------
-- Add a link.
-- ------------------------------
overriding
procedure Add_Link (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List_Type) is
begin
if Filter.Allowed (A_TAG) then
Filter_Type (Filter).Add_Link (Document, Name, Attributes);
end if;
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
overriding
procedure Add_Image (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List_Type) is
begin
if Filter.Allowed (IMG_TAG) then
Filter_Type (Filter).Add_Image (Document, Name, Attributes);
end if;
end Add_Image;
-- ------------------------------
-- Given the current tag on the top of the stack and the new tag that will be pushed,
-- decide whether the current tag must be closed or not.
-- Returns True if the current tag must be closed.
-- ------------------------------
function Need_Close (Tag : in Html_Tag_Type;
Current_Tag : in Html_Tag_Type) return Boolean is
begin
if No_End_Tag (Current_Tag) then
return True;
elsif Current_Tag = Tag and Tag_Omission (Current_Tag) then
return True;
else
case Current_Tag is
when DT_TAG | DD_TAG =>
return Tag = DD_TAG or Tag = DL_TAG or Tag = DT_TAG;
when TD_TAG =>
return Tag = TD_TAG or Tag = TR_TAG or Tag = TH_TAG;
when TR_TAG =>
return False;
when others =>
return False;
end case;
end if;
end Need_Close;
-- ------------------------------
-- Flush the HTML element that have not yet been closed.
-- ------------------------------
procedure Flush_Stack (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document) is
begin
while not Filter.Stack.Is_Empty loop
declare
Tag : constant Html_Tag_Type := Filter.Stack.Last_Element;
begin
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Pop_Node (Document, Tag);
end if;
if Filter.Hidden (Tag) then
Filter.Hide_Level := Filter.Hide_Level - 1;
end if;
end;
Filter.Stack.Delete_Last;
end loop;
end Flush_Stack;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document) is
begin
Filter.Flush_Stack (Document);
Filter_Type (Filter).Finish (Document);
end Finish;
-- ------------------------------
-- Mark the HTML tag as being forbidden.
-- ------------------------------
procedure Forbidden (Filter : in out Html_Filter_Type;
Tag : in Html_Tag_Type) is
begin
Filter.Allowed (Tag) := False;
end Forbidden;
-- ------------------------------
-- Mark the HTML tag as being allowed.
-- ------------------------------
procedure Allowed (Filter : in out Html_Filter_Type;
Tag : in Html_Tag_Type) is
begin
Filter.Allowed (Tag) := True;
end Allowed;
-- ------------------------------
-- Mark the HTML tag as being hidden. The tag and its inner content including the text
-- will be removed and not passed to the final document.
-- ------------------------------
procedure Hide (Filter : in out Html_Filter_Type;
Tag : in Html_Tag_Type) is
begin
Filter.Hidden (Tag) := True;
end Hide;
-- ------------------------------
-- Mark the HTML tag as being visible.
-- ------------------------------
procedure Visible (Filter : in out Html_Filter_Type;
Tag : in Html_Tag_Type) is
begin
Filter.Hidden (Tag) := False;
end Visible;
end Wiki.Filters.Html;
|
Use Wiki.Format_Map type
|
Use Wiki.Format_Map type
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
d66a676ea4bb4a1497fdb751ce140aaab5f3fc39
|
src/wiki-filters-html.adb
|
src/wiki-filters-html.adb
|
-----------------------------------------------------------------------
-- wiki-filters-html -- Wiki HTML filters
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Wiki.Filters.Html is
function Need_Close (Tag : in Html_Tag;
Current_Tag : in Html_Tag) return Boolean;
No_End_Tag : constant Tag_Boolean_Array :=
(
BASE_TAG => True,
LINK_TAG => True,
META_TAG => True,
IMG_TAG => True,
HR_TAG => True,
BR_TAG => True,
WBR_TAG => True,
INPUT_TAG => True,
KEYGEN_TAG => True,
others => False);
Tag_Omission : constant Tag_Boolean_Array :=
(
-- Section 4.4 Grouping content
LI_TAG => True,
DT_TAG => True,
DD_TAG => True,
-- Section 4.5 Text-level semantics
RB_TAG => True,
RT_TAG => True,
RTC_TAG => True,
RP_TAG => True,
-- Section 4.9 Tabular data
TH_TAG => True,
TD_TAG => True,
TR_TAG => True,
TBODY_TAG => True,
THEAD_TAG => True,
TFOOT_TAG => True,
OPTGROUP_TAG => True,
OPTION_TAG => True,
others => False);
-- ------------------------------
-- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document.
-- ------------------------------
overriding
procedure Add_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Kind : in Wiki.Nodes.Simple_Node_Kind) is
Tag : Html_Tag;
begin
case Kind is
when N_LINE_BREAK =>
Tag := BR_TAG;
when N_PARAGRAPH =>
Tag := P_TAG;
when N_HORIZONTAL_RULE =>
Tag := HR_TAG;
end case;
if Filter.Allowed (Tag) then
Filter_Type (Filter).Add_Node (Document, Kind);
end if;
end Add_Node;
-- ------------------------------
-- Add a text content with the given format to the document.
-- ------------------------------
overriding
procedure Add_Text (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map) is
begin
if Filter.Hide_Level > 0 then
return;
elsif not Filter.Stack.Is_Empty then
declare
Current_Tag : constant Html_Tag := Filter.Stack.Last_Element;
begin
if No_End_Tag (Current_Tag) then
Filter_Type (Filter).Pop_Node (Document, Current_Tag);
Filter.Stack.Delete_Last;
end if;
end;
end if;
Filter_Type (Filter).Add_Text (Document, Text, Format);
end Add_Text;
-- ------------------------------
-- Add a section header with the given level in the document.
-- ------------------------------
overriding
procedure Add_Header (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Natural) is
begin
Filter.Flush_Stack (Document);
Filter_Type (Filter).Add_Header (Document, Header, Level);
end Add_Header;
-- ------------------------------
-- Push a HTML node with the given tag to the document.
-- ------------------------------
overriding
procedure Push_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List) is
Current_Tag : Html_Tag;
begin
while not Filter.Stack.Is_Empty loop
Current_Tag := Filter.Stack.Last_Element;
if Need_Close (Tag, Current_Tag) then
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Pop_Node (Document, Current_Tag);
end if;
Filter.Stack.Delete_Last;
end if;
exit when not No_End_Tag (Current_Tag);
end loop;
if Filter.Hidden (Tag) then
Filter.Hide_Level := Filter.Hide_Level + 1;
elsif not Filter.Allowed (Tag) then
return;
end if;
Filter.Stack.Append (Tag);
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Push_Node (Document, Tag, Attributes);
end if;
end Push_Node;
-- ------------------------------
-- Pop a HTML node with the given tag.
-- ------------------------------
overriding
procedure Pop_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag) is
Current_Tag : Html_Tag;
begin
if Filter.Stack.Is_Empty then
return;
elsif not Filter.Allowed (Tag) and not Filter.Hidden (Tag) then
return;
end if;
-- Emit a end tag element until we find our matching tag and the top most tag
-- allows the end tag to be omitted (ex: a td, tr, td, dd, ...).
while not Filter.Stack.Is_Empty loop
Current_Tag := Filter.Stack.Last_Element;
exit when Current_Tag = Tag or not Tag_Omission (Current_Tag);
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Pop_Node (Document, Current_Tag);
end if;
Filter.Stack.Delete_Last;
end loop;
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Pop_Node (Document, Tag);
end if;
if Filter.Hidden (Current_Tag) then
Filter.Hide_Level := Filter.Hide_Level - 1;
end if;
Filter.Stack.Delete_Last;
end Pop_Node;
-- ------------------------------
-- Add a link.
-- ------------------------------
overriding
procedure Add_Link (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
if Filter.Allowed (A_TAG) then
Filter_Type (Filter).Add_Link (Document, Name, Attributes);
end if;
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
overriding
procedure Add_Image (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
if Filter.Allowed (IMG_TAG) then
Filter_Type (Filter).Add_Image (Document, Name, Attributes);
end if;
end Add_Image;
-- ------------------------------
-- Given the current tag on the top of the stack and the new tag that will be pushed,
-- decide whether the current tag must be closed or not.
-- Returns True if the current tag must be closed.
-- ------------------------------
function Need_Close (Tag : in Html_Tag;
Current_Tag : in Html_Tag) return Boolean is
begin
if No_End_Tag (Current_Tag) then
return True;
elsif Current_Tag = Tag and Tag_Omission (Current_Tag) then
return True;
else
case Current_Tag is
when DT_TAG | DD_TAG =>
return Tag = DD_TAG or Tag = DL_TAG or Tag = DT_TAG;
when TD_TAG =>
return Tag = TD_TAG or Tag = TR_TAG or Tag = TH_TAG;
when TR_TAG =>
return False;
when others =>
return False;
end case;
end if;
end Need_Close;
-- ------------------------------
-- Flush the HTML element that have not yet been closed.
-- ------------------------------
procedure Flush_Stack (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document) is
begin
while not Filter.Stack.Is_Empty loop
declare
Tag : constant Html_Tag := Filter.Stack.Last_Element;
begin
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Pop_Node (Document, Tag);
end if;
if Filter.Hidden (Tag) then
Filter.Hide_Level := Filter.Hide_Level - 1;
end if;
end;
Filter.Stack.Delete_Last;
end loop;
end Flush_Stack;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document) is
begin
Filter.Flush_Stack (Document);
Filter_Type (Filter).Finish (Document);
end Finish;
-- ------------------------------
-- Mark the HTML tag as being forbidden.
-- ------------------------------
procedure Forbidden (Filter : in out Html_Filter_Type;
Tag : in Html_Tag) is
begin
Filter.Allowed (Tag) := False;
end Forbidden;
-- ------------------------------
-- Mark the HTML tag as being allowed.
-- ------------------------------
procedure Allowed (Filter : in out Html_Filter_Type;
Tag : in Html_Tag) is
begin
Filter.Allowed (Tag) := True;
end Allowed;
-- ------------------------------
-- Mark the HTML tag as being hidden. The tag and its inner content including the text
-- will be removed and not passed to the final document.
-- ------------------------------
procedure Hide (Filter : in out Html_Filter_Type;
Tag : in Html_Tag) is
begin
Filter.Hidden (Tag) := True;
end Hide;
-- ------------------------------
-- Mark the HTML tag as being visible.
-- ------------------------------
procedure Visible (Filter : in out Html_Filter_Type;
Tag : in Html_Tag) is
begin
Filter.Hidden (Tag) := False;
end Visible;
end Wiki.Filters.Html;
|
-----------------------------------------------------------------------
-- wiki-filters-html -- Wiki HTML filters
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Helpers;
package body Wiki.Filters.Html is
-- ------------------------------
-- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document.
-- ------------------------------
overriding
procedure Add_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Kind : in Wiki.Nodes.Simple_Node_Kind) is
Tag : Html_Tag;
begin
case Kind is
when N_LINE_BREAK =>
Tag := BR_TAG;
when N_PARAGRAPH =>
Tag := P_TAG;
when N_HORIZONTAL_RULE =>
Tag := HR_TAG;
end case;
if Filter.Allowed (Tag) then
Filter_Type (Filter).Add_Node (Document, Kind);
end if;
end Add_Node;
-- ------------------------------
-- Add a text content with the given format to the document.
-- ------------------------------
overriding
procedure Add_Text (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map) is
begin
if Filter.Hide_Level > 0 then
return;
elsif not Filter.Stack.Is_Empty then
declare
Current_Tag : constant Html_Tag := Filter.Stack.Last_Element;
begin
if No_End_Tag (Current_Tag) then
Filter_Type (Filter).Pop_Node (Document, Current_Tag);
Filter.Stack.Delete_Last;
end if;
end;
end if;
Filter_Type (Filter).Add_Text (Document, Text, Format);
end Add_Text;
-- ------------------------------
-- Add a section header with the given level in the document.
-- ------------------------------
overriding
procedure Add_Header (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Natural) is
begin
Filter.Flush_Stack (Document);
Filter_Type (Filter).Add_Header (Document, Header, Level);
end Add_Header;
-- ------------------------------
-- Push a HTML node with the given tag to the document.
-- ------------------------------
overriding
procedure Push_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List) is
Current_Tag : Html_Tag;
begin
while not Filter.Stack.Is_Empty loop
Current_Tag := Filter.Stack.Last_Element;
if Wiki.Helpers.Need_Close (Tag, Current_Tag) then
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Pop_Node (Document, Current_Tag);
end if;
Filter.Stack.Delete_Last;
end if;
exit when not No_End_Tag (Current_Tag);
end loop;
if Filter.Hidden (Tag) then
Filter.Hide_Level := Filter.Hide_Level + 1;
elsif not Filter.Allowed (Tag) then
return;
end if;
Filter.Stack.Append (Tag);
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Push_Node (Document, Tag, Attributes);
end if;
end Push_Node;
-- ------------------------------
-- Pop a HTML node with the given tag.
-- ------------------------------
overriding
procedure Pop_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag) is
Current_Tag : Html_Tag;
begin
if Filter.Stack.Is_Empty then
return;
elsif not Filter.Allowed (Tag) and not Filter.Hidden (Tag) then
return;
end if;
-- Emit a end tag element until we find our matching tag and the top most tag
-- allows the end tag to be omitted (ex: a td, tr, td, dd, ...).
while not Filter.Stack.Is_Empty loop
Current_Tag := Filter.Stack.Last_Element;
exit when Current_Tag = Tag or not Tag_Omission (Current_Tag);
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Pop_Node (Document, Current_Tag);
end if;
Filter.Stack.Delete_Last;
end loop;
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Pop_Node (Document, Tag);
end if;
if Filter.Hidden (Current_Tag) then
Filter.Hide_Level := Filter.Hide_Level - 1;
end if;
Filter.Stack.Delete_Last;
end Pop_Node;
-- ------------------------------
-- Add a link.
-- ------------------------------
overriding
procedure Add_Link (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
if Filter.Allowed (A_TAG) then
Filter_Type (Filter).Add_Link (Document, Name, Attributes);
end if;
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
overriding
procedure Add_Image (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
if Filter.Allowed (IMG_TAG) then
Filter_Type (Filter).Add_Image (Document, Name, Attributes);
end if;
end Add_Image;
-- ------------------------------
-- Flush the HTML element that have not yet been closed.
-- ------------------------------
procedure Flush_Stack (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document) is
begin
while not Filter.Stack.Is_Empty loop
declare
Tag : constant Html_Tag := Filter.Stack.Last_Element;
begin
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Pop_Node (Document, Tag);
end if;
if Filter.Hidden (Tag) then
Filter.Hide_Level := Filter.Hide_Level - 1;
end if;
end;
Filter.Stack.Delete_Last;
end loop;
end Flush_Stack;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document) is
begin
Filter.Flush_Stack (Document);
Filter_Type (Filter).Finish (Document);
end Finish;
-- ------------------------------
-- Mark the HTML tag as being forbidden.
-- ------------------------------
procedure Forbidden (Filter : in out Html_Filter_Type;
Tag : in Html_Tag) is
begin
Filter.Allowed (Tag) := False;
end Forbidden;
-- ------------------------------
-- Mark the HTML tag as being allowed.
-- ------------------------------
procedure Allowed (Filter : in out Html_Filter_Type;
Tag : in Html_Tag) is
begin
Filter.Allowed (Tag) := True;
end Allowed;
-- ------------------------------
-- Mark the HTML tag as being hidden. The tag and its inner content including the text
-- will be removed and not passed to the final document.
-- ------------------------------
procedure Hide (Filter : in out Html_Filter_Type;
Tag : in Html_Tag) is
begin
Filter.Hidden (Tag) := True;
end Hide;
-- ------------------------------
-- Mark the HTML tag as being visible.
-- ------------------------------
procedure Visible (Filter : in out Html_Filter_Type;
Tag : in Html_Tag) is
begin
Filter.Hidden (Tag) := False;
end Visible;
end Wiki.Filters.Html;
|
Move the Tag_Boolean_Array, Tag_Omission, No_End_Tag to the Wiki package
|
Move the Tag_Boolean_Array, Tag_Omission, No_End_Tag to the Wiki package
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
7e0940d11130f1feab21bfc891cee553a0cf8ce9
|
src/sys/http/util-http-headers.ads
|
src/sys/http/util-http-headers.ads
|
-----------------------------------------------------------------------
-- util-http-headers -- HTTP Headers
-- Copyright (C) 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Dates.RFC7231;
package Util.Http.Headers is
-- Some header names.
Content_Type : constant String := "Content-Type";
Content_Length : constant String := "Content-Length";
Accept_Header : constant String := "Accept";
Accept_Language : constant String := "Accept-Language";
Location : constant String := "Location";
Cookie : constant String := "Cookie";
Cache_Control : constant String := "Cache-Control";
function To_Header (Date : in Ada.Calendar.Time) return String
renames Util.Dates.RFC7231.Image;
type Quality_Type is digits 4 range 0.0 .. 1.0;
-- Split an accept like header into multiple tokens and a quality value.
-- Invoke the `Process` procedure for each token. Example:
--
-- Accept-Language: de, en;q=0.7, jp, fr;q=0.8, ru
--
-- The `Process` will be called for "de", "en" with quality 0.7,
-- and "jp", "fr" with quality 0.8 and then "ru" with quality 1.0.
procedure Split_Header (Header : in String;
Process : access procedure (Item : in String;
Quality : in Quality_Type));
end Util.Http.Headers;
|
-----------------------------------------------------------------------
-- util-http-headers -- HTTP Headers
-- Copyright (C) 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Dates.RFC7231;
with Util.Http.Mimes;
package Util.Http.Headers is
-- Some header names.
Content_Type : constant String := "Content-Type";
Content_Length : constant String := "Content-Length";
Accept_Header : constant String := "Accept";
Accept_Language : constant String := "Accept-Language";
Location : constant String := "Location";
Cookie : constant String := "Cookie";
Cache_Control : constant String := "Cache-Control";
function To_Header (Date : in Ada.Calendar.Time) return String
renames Util.Dates.RFC7231.Image;
type Quality_Type is digits 4 range 0.0 .. 1.0;
-- Split an accept like header into multiple tokens and a quality value.
-- Invoke the `Process` procedure for each token. Example:
--
-- Accept-Language: de, en;q=0.7, jp, fr;q=0.8, ru
--
-- The `Process` will be called for "de", "en" with quality 0.7,
-- and "jp", "fr" with quality 0.8 and then "ru" with quality 1.0.
procedure Split_Header (Header : in String;
Process : access procedure (Item : in String;
Quality : in Quality_Type));
-- Get the accepted media according to the `Accept` header value and a list
-- of media/mime types. The quality matching and wildcard are handled
-- so that we return the best match. With the following HTTP header:
--
-- Accept: image/*; q=0.2, image/jpeg
--
-- and if the mimes list contains `image/png` but not `image/jpeg`, the
-- first one is returned. If the list contains both, then `image/jpeg` is
-- returned.
function Get_Accepted (Header : in String;
Mimes : in Util.Http.Mimes.Mime_List)
return Util.Http.Mimes.Mime_Access;
end Util.Http.Headers;
|
Declare the Get_Accepted function to find the accepted mime/media type according to a list of media types and the Accept header value
|
Declare the Get_Accepted function to find the accepted mime/media type
according to a list of media types and the Accept header value
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
d85996b0bb4c1ba6c744f849c91aa86c7657418b
|
src/util-beans-objects-vectors.ads
|
src/util-beans-objects-vectors.ads
|
-----------------------------------------------------------------------
-- Util.Beans.Objects.Vectors -- Object vectors
-- 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.Containers.Vectors;
package Util.Beans.Objects.Vectors is new
Ada.Containers.Vectors (Index_Type => Natural,
Element_Type => Object);
|
-----------------------------------------------------------------------
-- util-beans-vectors -- Object vectors
-- Copyright (C) 2011, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Vectors;
with Util.Beans.Basic;
package Util.Beans.Objects.Vectors is
package Vectors is
new Ada.Containers.Vectors (Index_Type => Natural,
Element_Type => Object);
subtype Cursor is Vectors.Cursor;
subtype Vector is Vectors.Vector;
-- Make all the Vectors operations available (a kind of 'use Vectors' for anybody).
function Length (Container : in Vector) return Ada.Containers.Count_Type renames Vectors.Length;
function Is_Empty (Container : in Vector) return Boolean renames Vectors.Is_Empty;
procedure Clear (Container : in out Vector) renames Vectors.Clear;
function First (Container : in Vector) return Cursor renames Vectors.First;
function Last (Container : in Vector) return Cursor renames Vectors.Last;
function Element (Container : in Vector;
Position : in Natural) return Object renames Vectors.Element;
procedure Append (Container : in out Vector;
New_Item : in Object;
Count : in Ada.Containers.Count_Type := 1) renames Vectors.Append;
procedure Query_Element (Position : in Cursor;
Process : not null access procedure (Element : Object))
renames Vectors.Query_Element;
procedure Update_Element (Container : in out Vector;
Position : in Cursor;
Process : not null access procedure (Element : in out Object))
renames Vectors.Update_Element;
function Has_Element (Position : Cursor) return Boolean renames Vectors.Has_Element;
function Element (Position : Cursor) return Object renames Vectors.Element;
procedure Next (Position : in out Cursor) renames Vectors.Next;
function Next (Position : Cursor) return Cursor renames Vectors.Next;
function Previous (Position : Cursor) return Cursor renames Vectors.Previous;
procedure Previous (Position : in out Cursor) renames Vectors.Previous;
-- ------------------------------
-- Map Bean
-- ------------------------------
-- The <b>Map_Bean</b> is a map of objects that also exposes the <b>Bean</b> interface.
-- This allows the map to be available and accessed from an Object instance.
type Vector_Bean is new Vectors.Vector and Util.Beans.Basic.Bean with private;
type Vector_Bean_Access is access all Vector_Bean'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
function Get_Value (From : in Vector_Bean;
Name : in String) return Object;
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
procedure Set_Value (From : in out Vector_Bean;
Name : in String;
Value : in Object);
-- Create an object that contains a <tt>Vector_Bean</tt> instance.
function Create return Object;
private
type Vector_Bean is new Vectors.Vector and Util.Beans.Basic.Bean with null record;
end Util.Beans.Objects.Vectors;
|
Refactor the Vectors package so that it provides a Vector_Bean type that can be use to make an Object
|
Refactor the Vectors package so that it provides a Vector_Bean type that can be use to make an Object
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
68661b064859d37dd9f2cd61ab717c292292ef91
|
src/asis/asis-text.ads
|
src/asis/asis-text.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT INTERFACE COMPONENTS --
-- --
-- A S I S . T E X T --
-- --
-- S p e c --
-- --
-- Copyright (C) 1995-2012, Free Software Foundation, Inc. --
-- --
-- This specification is derived from the Ada Semantic Interface --
-- Specification Standard (ISO/IEC 15291) for use with GNAT. The copyright --
-- notice above, and the license provisions that follow apply solely to the --
-- contents of the part following the private keyword. --
-- --
-- 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). --
-- --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- 20 package Asis.Text
------------------------------------------------------------------------------
------------------------------------------------------------------------------
package Asis.Text is
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Asis.Text
--
-- This package encapsulates a set of operations to access the text of ASIS
-- Elements. It assumes no knowledge of the existence, location, or form of
-- the program text.
--
-- The text of a program consists of the texts of one or more compilations.
-- The text of each compilation is a sequence of separate lexical elements.
-- Each lexical element is either a delimiter, an identifier (which can be a
-- reserved word), a numeric literal, a character literal, a string literal,
-- blank space, or a comment.
--
-- Each ASIS Element has a text image whose value is the series of characters
-- contained by the text span of the Element. The text span covers all the
-- characters from the first character of the Element through the last
-- character of the Element over some range of lines.
--
-- General Usage Rules:
--
-- Line lists can be indexed to obtain individual lines. The bounds of each
-- list correspond to the lines with those same numbers from the compilation
-- text.
--
-- Any Asis.Text query may raise ASIS_Failed with a Status of Text_Error if
-- the program text cannot be located or retrieved for any reason such as
-- renaming, deletion, corruption, or moving of the text.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- 20.1 type Line
------------------------------------------------------------------------------
-- An Ada text line abstraction (a private type).
--
-- Used to represent text fragments from a compilation.
-- ASIS Lines are representations of the compilation text.
-- This shall be supported by all ASIS implementations.
------------------------------------------------------------------------------
type Line is private;
Nil_Line : constant Line;
function "=" (Left : Line; Right : Line) return Boolean is abstract;
-- Nil_Line is the value of an uninitialized Line object.
--
------------------------------------------------------------------------------
-- 20.2 type Line_Number
------------------------------------------------------------------------------
-- Line_Number
--
-- A numeric subtype that allows each ASIS implementation to place constraints
-- on the upper bound for Line_List elements and compilation unit size.
--
-- The upper bound of Line_Number (Maximum_Line_Number) is the only
-- allowed variation for these declarations.
--
-- Line_Number = 0 is reserved to act as an "invalid" Line_Number value. No
-- unit text line will ever have a Line_Number of zero.
------------------------------------------------------------------------------
-- Line shall be an undiscriminated private type, or, shall be derived from an
-- undiscriminated private type. It can be declared as a new type or as a
-- subtype of an existing type.
------------------------------------------------------------------------------
Maximum_Line_Number : constant ASIS_Natural :=
Implementation_Defined_Integer_Constant;
subtype Line_Number is ASIS_Natural range 0 .. Maximum_Line_Number;
------------------------------------------------------------------------------
-- 20.3 type Line_Number_Positive
------------------------------------------------------------------------------
subtype Line_Number_Positive is Line_Number range 1 .. Maximum_Line_Number;
------------------------------------------------------------------------------
-- 20.4 type Line_List
------------------------------------------------------------------------------
type Line_List is array (Line_Number_Positive range <>) of Line;
Nil_Line_List : constant Line_List;
------------------------------------------------------------------------------
-- 20.5 type Character_Position
------------------------------------------------------------------------------
-- Character_Position
--
-- A numeric subtype that allows each ASIS implementation to place constraints
-- on the upper bound for Character_Position and for compilation unit line
-- lengths.
--
-- The upper bound of Character_Position (Maximum_Line_Length) is the
-- only allowed variation for these declarations.
--
-- Character_Position = 0 is reserved to act as an "invalid"
-- Character_Position value. No unit text line will ever have a character in
-- position zero.
------------------------------------------------------------------------------
Maximum_Line_Length : constant ASIS_Natural :=
Implementation_Defined_Integer_Constant;
subtype Character_Position is ASIS_Natural range 0 .. Maximum_Line_Length;
------------------------------------------------------------------------------
-- 20.6 type Character_Position_Positive
------------------------------------------------------------------------------
subtype Character_Position_Positive is
Character_Position range 1 .. Maximum_Line_Length;
------------------------------------------------------------------------------
-- 20.7 type Span
------------------------------------------------------------------------------
-- Span
--
-- A single text position is identified by a line number and a column number,
-- that represent the text's position within the compilation unit.
--
-- The text of an element can span one or more lines. The textual Span of an
-- element identifies the lower and upper bound of a span of text positions.
--
-- Spans and positions give client tools the option of accessing compilation
-- unit text through the queries provided by this package, or, to access
-- the text directly through the original compilation unit text file. Type
-- span
-- facilitates the capture of comments before or after an element.
--
-- Note: The original compilation unit text may or may not have existed in a
-- "file", and any such file may or may not still exist. Reference Manual 10.1
-- specifies that the text of a compilation unit is submitted to a compiler.
-- It does not specify that the text is stored in a "file", nor does it
-- specify that the text of a compilation unit has any particular lifetime.
------------------------------------------------------------------------------
type Span is -- Default is Nil_Span
record
First_Line : Line_Number_Positive := 1; -- 1..0 - empty
First_Column : Character_Position_Positive := 1; -- 1..0 - empty
Last_Line : Line_Number := 0;
Last_Column : Character_Position := 0;
end record;
Nil_Span : constant Span := (First_Line => 1,
First_Column => 1,
Last_Line => 0,
Last_Column => 0);
------------------------------------------------------------------------------
-- 20.8 function First_Line_Number
------------------------------------------------------------------------------
function First_Line_Number (Element : Asis.Element) return Line_Number;
------------------------------------------------------------------------------
-- Element - Specifies the element to query
--
-- Returns the first line number on which the text of the element resides.
--
-- Returns 0 if not Is_Text_Available(Element).
--
-- --|AN Application Note:
-- --|AN
-- --|AN The line number recorded for a particular element may or may not
-- --|AN match the "true" line number of the program text for that element if
-- --|AN the Ada environment and the local text editors do not agree on the
-- --|AN definition of "line". For example, the Reference Manual states that
-- --|AN any occurrence of an ASCII.Cr character is to be treated as one or
-- --|AN more end-of-line occurrences. On most Unix systems, the editors do
-- --|AN not treat a carriage return as being an end-of-line character.
-- --|AN
-- --|AN Ada treats all of the following as end-of-line characters: ASCII.Cr,
-- --|AN ASCII.Lf, ASCII.Ff, ASCII.Vt. It is up to the compilation system to
-- --|AN determine whether sequences of these characters causes one, or more,
-- --|AN end-of-line occurrences. Be warned, if the Ada environment and the
-- --|AN system editor (or any other line-counting program) do not use the
-- --|AN same end-of-line conventions, then the line numbers reported by ASIS
-- --|AN may not match those reported by those other programs.
--
------------------------------------------------------------------------------
-- 20.9 function Last_Line_Number
------------------------------------------------------------------------------
function Last_Line_Number (Element : Asis.Element) return Line_Number;
------------------------------------------------------------------------------
-- Element - Specifies the element to query
--
-- Returns the last line number on which the text of the element resides.
--
-- Returns 0 if not Is_Text_Available(Element).
--
------------------------------------------------------------------------------
-- 20.10 function Element_Span
------------------------------------------------------------------------------
function Element_Span (Element : Asis.Element) return Span;
------------------------------------------------------------------------------
-- Element - Specifies the element to query
--
-- Returns the span of the given element.
--
-- Returns a Nil_Span if the text of a Compilation_Unit (Compilation) cannot
-- be located for any reason.
-- --|AN
-- --|AN For this query, Element is only a means to access the
-- --|AN Compilation_Unit (Compilation), the availability of the text of this
-- --|AN Element itself is irrelevant to the result of the query.
--
------------------------------------------------------------------------------
-- 20.11 function Compilation_Unit_Span
------------------------------------------------------------------------------
function Compilation_Unit_Span (Element : Asis.Element) return Span;
------------------------------------------------------------------------------
-- Element - Specifies the element to query
--
-- Returns the span of the text comprising the enclosing compilation unit of
-- the given element.
--
-- Returns a Nil_Span if the text of a Compilation_Unit (Compilation) cannot
-- be located for any reason.
-- --|AN
-- --|AN For this query, Element is only a means to access the
-- --|AN Compilation_Unit (Compilation), the availability of the text of this
-- --|AN Element itself is irrelevant to the result of the query.
--
------------------------------------------------------------------------------
-- 20.12 function Compilation_Span
------------------------------------------------------------------------------
function Compilation_Span (Element : Asis.Element) return Span;
------------------------------------------------------------------------------
-- Element - Specifies the element to query
--
-- Returns the span of the text comprising the compilation to which the
-- element belongs. The text span may include one or more compilation units.
--
-- Returns a Nil_Span if not Is_Text_Available(Element).
--
------------------------------------------------------------------------------
-- 20.13 function Is_Nil
------------------------------------------------------------------------------
function Is_Nil (Right : Line) return Boolean;
------------------------------------------------------------------------------
-- Right - Specifies the line to check
--
-- Returns True if the argument is the Nil_Line.
--
-- A Line from a Line_List obtained from any of the Lines functions
-- will not be Is_Nil even if it has a length of zero.
--
------------------------------------------------------------------------------
-- 20.14 function Is_Nil
------------------------------------------------------------------------------
function Is_Nil (Right : Line_List) return Boolean;
------------------------------------------------------------------------------
-- Right - Specifies the line list to check
--
-- Returns True if the argument has a 'Length of zero.
--
------------------------------------------------------------------------------
-- 20.15 function Is_Nil
------------------------------------------------------------------------------
function Is_Nil (Right : Span) return Boolean;
------------------------------------------------------------------------------
-- Right - Specifies the Span to check
--
-- Returns True if the argument has a Nil_Span.
--
------------------------------------------------------------------------------
-- 20.16 function Is_Equal
------------------------------------------------------------------------------
function Is_Equal (Left : Line; Right : Line) return Boolean;
------------------------------------------------------------------------------
-- Left - Specifies the first of the two lines
-- Right - Specifies the second of the two lines
--
-- Returns True if the two lines encompass the same text (have the same Span
-- and are from the same compilation).
--
------------------------------------------------------------------------------
-- 20.17 function Is_Identical
------------------------------------------------------------------------------
function Is_Identical (Left : Line; Right : Line) return Boolean;
------------------------------------------------------------------------------
-- Left - Specifies the first of the two lines
-- Right - Specifies the second of the two lines
--
-- Returns True if the two lines encompass the same text (have the same Span
-- and are from the same compilation) and are from the same Context.
--
------------------------------------------------------------------------------
-- 20.18 function Length
------------------------------------------------------------------------------
function Length (The_Line : Line) return Character_Position;
------------------------------------------------------------------------------
-- The_Line - Specifies the line to query
--
-- Returns the length of the line.
--
-- Raises ASIS_Inappropriate_Line if Is_Nil (The_Line).
--
------------------------------------------------------------------------------
-- 20.19 function Lines
------------------------------------------------------------------------------
function Lines (Element : Asis.Element) return Line_List;
------------------------------------------------------------------------------
-- Element - Specifies the element to query
--
-- Returns a list of lines covering the span of the given program element.
--
-- Returns a Nil_Span if the text of a Compilation containing a given
-- Element cannot be located for any reason.
--
-- Line lists can be indexed to obtain individual lines. The bounds of each
-- list correspond to the lines with those same numbers in the compilation
-- text.
--
-- The first Line of the result contains text from the compilation starting at
-- the First_Line/First_Column of Element's Span. The last Line of the result
-- contains text from the compilation ending at the Last_Line/Last_Column of
-- the Element's Span. Text before or after those limits is not reflected
-- in the returned list.
-- --|AN
-- --|AN For this query, Element is only a means to access the
-- --|AN Compilation_Unit (Compilation), the availability of the text of this
-- --|AN Element itself is irrelevant to the result of the query.
--
------------------------------------------------------------------------------
-- 20.20 function Lines
------------------------------------------------------------------------------
function Lines
(Element : Asis.Element;
The_Span : Span)
return Line_List;
------------------------------------------------------------------------------
-- Element - Specifies the element to query
-- The_Span - Specifies the textual span to return
--
-- Returns a list of lines covering the given span from the compilation
-- containing the given program element.
--
-- Returns a Nil_Span if the text of a Compilation containing a given
-- Element cannot be located for any reason.
--
-- This operation can be used to access lines from text outside the span of an
-- element, but still within the compilation. For example, lines containing
-- preceding comments or lines between two elements.
--
-- Line lists can be indexed to obtain individual lines. The bounds of each
-- list correspond to the lines with those same numbers in the compilation
-- text.
--
-- The first Line of the result contains text from the compilation starting at
-- line Span.First_Line and column Span.First_Column. The last Line of the
-- result contains text from the compilation ending at line Span.Last_Line and
-- column Span.Last_Column. Text before or after those limits is not
-- reflected in the returned list.
--
-- Raises ASIS_Inappropriate_Line_Number if Is_Nil (The_Span). If
-- The_Span defines a line whose number is outside the range of text lines
-- that can be accessed through the Element, the implementation is encouraged,
-- but not required to raise ASIS_Inappropriate_Line_Number.
-- --|AN
-- --|AN For this query, Element is only a means to access the
-- --|AN Compilation_Unit (Compilation), the availability of the text of this
-- --|AN Element itself is irrelevant to the result of the query.
--
------------------------------------------------------------------------------
-- 20.21 function Lines
------------------------------------------------------------------------------
function Lines
(Element : Asis.Element;
First_Line : Line_Number_Positive;
Last_Line : Line_Number)
return Line_List;
------------------------------------------------------------------------------
-- Element - Specifies the element to query
-- First_Line - Specifies the first line to return
-- Last_Line - Specifies the last line to return
--
-- Returns a list of Lines covering the full text for each of the indicated
-- lines from the compilation containing the given element. This operation
-- can be used to access lines from text outside the span of an element, but
-- still within the compilation.
--
-- Returns a Nil_Span if the text of a Compilation containing a given
-- Element cannot be located for any reason.
--
-- Line lists can be indexed to obtain individual lines. The bounds of each
-- list correspond to the lines with those same numbers in the compilation
-- text.
--
-- Raises ASIS_Inappropriate_Line_Number if the span is nil. If the span
-- defines a line whose number is outside the range of text lines that can be
-- accessed through the Element, the implementation is encouraged, but not
-- required to raise ASIS_Inappropriate_Line_Number.
-- --|AN
-- --|AN For this query, Element is only a means to access the
-- --|AN Compilation_Unit (Compilation), the availability of the text of this
-- --|AN Element itself is irrelevant to the result of the query.
--
------------------------------------------------------------------------------
-- 20.22 function Delimiter_Image
------------------------------------------------------------------------------
function Delimiter_Image return Wide_String;
------------------------------------------------------------------------------
-- Returns the string used as the delimiter separating individual lines of
-- text within the program text image of an element. It is also used as the
-- delimiter separating individual lines of strings returned by Debug_Image.
--
------------------------------------------------------------------------------
-- 20.23 function Element_Image
------------------------------------------------------------------------------
function Element_Image (Element : Asis.Element) return Program_Text;
------------------------------------------------------------------------------
-- Element - Specifies the element to query
--
-- Returns a program text image of the element. The image of an element can
-- span more than one line, in which case the program text returned by the
-- function Delimiter_Image separates the individual lines. The bounds on
-- the returned program text value are 1..N, N is as large as necessary.
--
-- Returns a null string if not Is_Text_Available(Element).
--
-- If an Element's Span begins at column position P, the returned program text
-- will be padded at the beginning with P-1 white space characters (ASCII.' '
-- or ASCII.Ht). The first character of the Element's image will thus begin
-- at character P of the returned program text. Due to the possible presence
-- of ASCII.Ht characters, the "column" position of characters within the
-- image might not be the same as their print-column positions when the image
-- is displayed on a screen or printed.
--
-- NOTE: The image of a large element can exceed the range of Program_Text.
-- In this case, the exception ASIS_Failed is raised with a Status of
-- Capacity_Error. Use the Lines function to operate on the image of large
-- elements.
--
------------------------------------------------------------------------------
-- 20.24 function Line_Image
------------------------------------------------------------------------------
function Line_Image (The_Line : Line) return Program_Text;
------------------------------------------------------------------------------
-- The_Line - Specifies the line to query
--
-- Returns a program text image of the line. The image of a single lexical
-- element can be sliced from the returned value using the first and last
-- column character positions from the Span of the Element. The bounds on the
-- returned program text are 1 .. Length(Line).
--
-- If the Line is the first line from the Lines result for an Element, it can
-- represent only a portion of a line from the original compilation. If the
-- span began at character position P, the first Line of it's Lines
-- result is padded at the beginning with P-1 white space characters
-- (ASCII.' ' or ASCII.Ht). The first character of the image will
-- thus begin at character P of the program text for the first Line. Due to
-- the possible presence of ASCII.Ht characters, the "column" position of
-- characters within the image may not be the same as their print-column
-- positions when the image is displayed or printed.
--
-- Similarly, if the Line is the last line from the Lines result for an
-- Element, it may represent only a portion of a line from the original
-- compilation. The program text image of such a Line is shorter than the
-- line from compilation and will contain only the initial portion of
-- that line.
--
-- Raises ASIS_Inappropriate_Line if Is_Nil (The_Line).
--
------------------------------------------------------------------------------
-- 20.25 function Non_Comment_Image
------------------------------------------------------------------------------
function Non_Comment_Image (The_Line : Line) return Program_Text;
------------------------------------------------------------------------------
-- The_Line - Specifies the line to query
--
-- Returns a program text image of a Line up to, but excluding, any comment
-- appearing in that Line.
--
-- The value returned is the same as that returned by the Image function,
-- except that any hyphens ("--") that start a comment, and any characters
-- that follow those hyphens, are dropped.
--
-- The bounds on the returned program text are 1..N, where N is one less than
-- the column of any hyphens ("--") that start a comment on the line.
--
-- Raises ASIS_Inappropriate_Line if Is_Nil (The_Line).
--
------------------------------------------------------------------------------
-- 20.26 function Comment_Image
------------------------------------------------------------------------------
function Comment_Image (The_Line : Line) return Program_Text;
------------------------------------------------------------------------------
-- The_Line - Specifies the line to query
--
-- Returns a program text image of any comment on that line, excluding any
-- lexical elements preceding the comment.
--
-- The value returned is the same as that returned by the Image function,
-- except that any program text prior to the two adjacent hyphens ("--") which
-- start a comment is replaced by an equal number of spaces. If the hyphens
-- began in column P of the Line, they will also begin in character position
-- P of the returned program text.
--
-- A null string is returned if the line has no comment.
--
-- The bounds of the program text are 1..N, where N is as large as necessary.
--
-- Raises ASIS_Inappropriate_Line if Is_Nil (The_Line).
--
------------------------------------------------------------------------------
-- 20.27 function Is_Text_Available
------------------------------------------------------------------------------
function Is_Text_Available (Element : Asis.Element) return Boolean;
------------------------------------------------------------------------------
-- Element - Specifies the element to query
--
-- Returns True if the implementation can return a valid text image for the
-- given element.
--
-- Returns False for any Element that Is_Nil, Is_Part_Of_Implicit, or
-- Is_Part_Of_Instance.
--
-- Returns False if the text of the element cannot be located for any reason
-- such as renaming, deletion, or moving of text.
--
-- --|IR Implementation Requirements:
-- --|IR
-- --|IR An implementation shall make text available for all explicit
-- --|IR elements.
--
------------------------------------------------------------------------------
-- 20.28 function Debug_Image
------------------------------------------------------------------------------
function Debug_Image (The_Line : Line) return Wide_String;
------------------------------------------------------------------------------
-- The_Line - Specifies the line to convert
--
-- Returns a string value containing implementation-defined debug
-- information associated with the line.
--
-- The return value uses Asis.Text.Delimiter_Image to separate the lines
-- of multi-line results. The return value does not end with
-- Asis.Text.Delimiter_Image.
--
-- These values are intended for two purposes. They are suitable for
-- inclusion in problem reports sent to the ASIS implementor. They can
-- be presumed to contain information useful when debugging the
-- implementation itself. They are also suitable for use by the ASIS
-- application when printing simple application debugging messages during
-- application development. They are intended to be, to some worthwhile
-- degree, intelligible to the user.
--
------------------------------------------------------------------------------
private
-- The content of this private part is specific for the ASIS
-- implementation for GNAT
------------------------------------------------------------------------------
type Line is
record
Sloc : Source_Ptr := No_Location;
Comment_Sloc : Source_Ptr := No_Location;
Length : Character_Position := 0;
Rel_Sloc : Source_Ptr := No_Location;
Enclosing_Unit : Unit_Id := Nil_Unit;
Enclosing_Context : Context_Id := Non_Associated;
Enclosing_Tree : Tree_Id := Nil_Tree;
Obtained : ASIS_OS_Time := Nil_ASIS_OS_Time;
end record;
Nil_Line : constant Line := (Sloc => No_Location,
Comment_Sloc => No_Location,
Length => 0,
Rel_Sloc => No_Location,
Enclosing_Unit => Nil_Unit,
Enclosing_Context => Non_Associated,
Enclosing_Tree => Nil_Tree,
Obtained => Nil_ASIS_OS_Time);
-- Note, that Line does not have the predefined "=" operation (it is
-- overridden by an abstract "=". The predefined "=" is explicitly
-- simulated in the implementation of Is_Nil query, so, if the full
-- declaration for Line is changed, the body of Is_Nil should be revised.
-----------------------------
-- Fields in the Line type --
-----------------------------
-- Sloc : Source_Ptr := No_Location;
-- indicates the beginning of the corresponding line in the Source
-- Buffer. If a given Line is the first line covering the Image of
-- some Element, the position in the Source Buffer pointed by Sloc
-- may or may not correspond to the beginning of the source text
-- line
--
-- Comment_Sloc - represents the starting Sloc position of a comment
-- that is a part of the line. Set to 0 if the line does not contain a
-- a comment. Note, that we assume that in the comment text the bracket
-- encoding can not be used for wide characters
--
-- Length : Character_Position := 0;
-- represents the length of the Line, excluding any character
-- signifying end of line (RM95, 2.2(2))
-- Note, that in the compiler lines of the source code are represented
-- using the String type, and if the line contains a wide character that
-- requires more than one one-byte character for its representation, the
-- length of one-byte character string used to represent wide-character
-- string from the source code may be bigger then the length of the
-- original source line (length here is the number of characters). In the
-- Line type we keep the lenth of the source line counted in source
-- characters, but not the length of the internal representation in
-- one-byte characters. Note that this length does not depend on the
-- encoding method.
--
-- Rel_Sloc : Source_Ptr := No_Location;
-- needed to compare string representing elements of the same
-- compilation units, but probably obtained from different trees
-- containing this unit. Obtained in the same way as for Elements -
-- by subtracting from Sloc field the source location of the
-- N_Compilation_Unit node
--
-- Enclosing_Unit : Unit_Id := Nil_Unit;
-- Enclosing_Context : Context_Id := Non_Associated;
-- These fields represent the Context in which and the Compilation
-- Unit from which the given line was obtained, they are needed
-- for comparing Lines and for tree swapping when obtaining
-- Line_Image
--
-- Enclosing_Tree : Tree_Id := Nil_Tree;
-- Sloc field may be used for obtaining the image of a Line only in
-- the tree from which it was obtained. So the Line has to keep
-- the reference to the tree for tree swapping
--
-- Obtained : ASIS_OS_Time := Nil_ASIS_OS_Time;
-- Lines, as well as Elements, cannot be used after closing the
-- Context from which they were obtained. We use time comparing
-- to check the validity of a Line
-- In the current implementation, ASIS Lines are mapped onto logical
-- GNAT lines, as defined in the Sinput package.
-- The child package Asis.Text.Set_Get defines operations for
-- accessing and updating fields of Lines, for checking the validity
-- of a Line and for creating the new value of the Line type.
-- (This package is similar to the Asis.Set_Get package, which
-- defines similar things for other ASIS abstractions - Element,
-- Context, Compilation_Unit.)
Nil_Line_List : constant Line_List (1 .. 0) := (1 .. 0 => Nil_Line);
------------------------------------------------------------------------------
end Asis.Text;
|
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
|
|
f948568939f6f696a853e57144408f1c6b1d3bb3
|
src/asis/a4g-contt-ut.ads
|
src/asis/a4g-contt-ut.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . C O N T T . U T --
-- --
-- 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). --
-- --
------------------------------------------------------------------------------
-- This package defines for each ASIS Context the corresponding Unit Table,
-- which contains all the information needed for the black-box ASIS queries
-- about Compilation Units. This table also provides the mechanism for
-- searching for a unit by its Ada name, this mechanism is some slight
-- modification of the GNAT Namet package.
with Asis; use Asis;
with Asis.Extensions; use Asis.Extensions;
package A4G.Contt.UT is -- Context_Table.Unit_Tables
---------------------
-- ASIS Unit Table --
---------------------
-- ASIS Unit Table is the main part of the implementation of ASIS Context
-- and ASIS Compilation Unit abstractions. The table is organized in the
-- following way:
-- - the internal representation of an ASIS Compilation Unit is the
-- value of the corresponding Unit Record which is kept in Unit Table
-- and indicated by Unit Id;
-- - each ASIS Context has its own Unit Table, so most the routines
-- dealing with Unit Table contain the Id of an Enclosing Context
-- as a Parameter;
-- - each ASIS Compilation Units keeps the Id of its enclosing
-- Context as a part of its value;
-- - The fully expanded Ada name, together for the spec/body sign,
-- uniquely identifies a given unit inside its enclosing
-- Context/Context; so the triple - expanded Ada name, spec/body
-- sign and some identification of the Unit's enclosing Context/Context
-- uniquely identifies a given unit among all the Unit processed
-- by ASIS;
-- - The normalized Ada name, is obtained from the fully expanded
-- Ada Unit name by folding all the upper case letters in the
-- corresponding lower case letters, appending the spec/body sign
-- (which has the form "%s" for a spec and "%b" for a body);
-- The entries in the table are accessed using a Unit_Id that ranges
-- from First_Unit_Id to Last_Unit_Id. The fields of each entry and
-- the corresponding interfaces may be subdivided into four groups.
-- The first group, called as Unit Name Table, provides the modified
-- version of the functionality of the GNAT Namet package, it is used
-- for storing the names of the Units in two forms - in the normalized
-- and in the form corresponding to the (defining) occurrence of a
-- given name in a source text. Each unit can be effectively searched
-- by its normalized name.
-- The second group contains the black-box attributes of a Unit.
-- The third group contains the information about relations (semantic
-- dependencies) between the given unit and the other units in the
-- enclosing Context/Context Note, that Ada Unit name,
-- included in the first group, logically should also be considered
-- as a black-box Unit attribute.
-- And the fourth group contains the fields needed for organization of the
-- tree swapping during the multiple Units processing.
---------------------
-- Unit Name Table --
---------------------
-- Each Unit entry contain the following fields:
-- "Normalized" Ada name "Normalized" Ada names of the ASIS Compilation
-- Units are their names with upper case letters
-- folded to lower case (by applying the
-- Ada.Character.Handling.To_Lower functions;
-- this lover-case-folding has no relation to GNAT
-- conventions described in Namet!), appended by
-- suffix %s or %b for spec or bodies/subunits, as
-- defined in Uname (spec), and prepended by
-- the string image of the Id value of the unit's
-- enclosing Context. Each of the names of this
-- kind may have only one entry in Unit Name Table.
--
-- Ada name Ada names of the ASIS Compilation Units are
-- stored keeping the casing from the source text.
-- These entries are used to implement the ASIS
-- query (-ies?) returning the Ada name of the
-- Unit. Ada names may be included more than one
-- time in Unit Name Table as the parts of the
-- different table entries, as the name of a spec
-- and the name of a corresponding body.
--
-- Source File Name The name of the Ada source file used to compile
-- the given compilation unit (on its own or as a
-- supporter of some other unit).
--
-- Reference File Name The name of the source file which represents
-- the unit source from the user's viewpoint. It is
-- the same as the Source File name unless the
-- Source_Reference pragma presents for the given
-- unit.
type Column is (Norm_Ada_Name, Ada_Name, Source_File_Name, Ref_File_Name);
-- This enumeration type defines literals used to make the difference
-- between different forms of names stored in the Unit Table
-- Really every name is kept as the reference into the Char table,
-- together with the length of its name.
-- The normalized names are hashed, so that a given normalized name appears
-- only once in the table.
-- Opposite to the GNAT name table, this name table does not handle the
-- one-character values in a special way (there is no need for it, because
-- storing an one-character name does not seem to be a usual thing
-- for this table.)
-- ASIS "normalized" Unit names follow the convention which is
-- very similar to the GNAT convention defined in Uname (spec), the
-- only difference is that ASIS folds all the upper case
-- letters to the corresponding lower case letters without any encoding.
-- ASIS packages implementing the ASIS Context model for GNAT contain
-- "ASIS-related counterparts" of some facilities provided by three
-- GNAT packages - Namet, Uname and Fname.
-- We keep storing the two values, one of type Int and one of type Byte,
-- with each names table entry and subprograms are provided for setting
-- and retrieving these associated values. But for now these values are
-- of no use in ASIS - we simply are keeping this mechanism from the
-- GNAT name table - just in case.
-- Unit Name Table may be considered as having the external view
-- of the two-column table - for each row indicated by Unit_Id the
-- first column contains the Ada name of the corresponding Unit and
-- the second column contains Unit's "normalized" name.
-- In fact we do not use any encoding-decoding in Unit Name Table. ASIS
-- supports only a standard mode of GNAT (that is, it relies on the fact
-- that all the identifiers contain only Row 00 characters). ASIS also
-- assumes that all the names of the source files are the values of
-- the Ada predefined String type.
-- All the Unit Tables shares the same Name Buffer, see the specification
-- of the parent package for its definition.
---------------------------------
-- Unit Name Table Subprograms --
---------------------------------
procedure Get_Name_String (Id : Unit_Id; Col : Column);
-- Get_Name_String is used to retrieve the one of the three strings
-- associated with an entry in the names table. The Col parameter
-- indicates which of the names should be retrieved (Ada name, normalized
-- Ada name or source file name) by indicating the "column" in the table
-- The resulting string is stored in Name_Buffer and Name_Len is set.
function Length_Of_Name (Id : Unit_Id; Col : Column) return Nat;
-- ??? pragma Inline (Length_Of_Name);
-- Returns length of given name in characters, the result is equivalent to
-- calling Get_Name_String and reading Name_Len, except that a call to
-- Length_Of_Name does not affect the contents of Name_Len and Name_Buffer.
function Name_Find (C : Context_Id) return Unit_Id;
-- Name_Find is called with a string stored in Name_Buffer whose length
-- is in Name_Len (i.e. the characters of the name are in subscript
-- positions 1 to Name_Len in Name_Buffer). It searches the names
-- table to see if the string has already been stored. If so the Id of
-- the existing entry is returned. Otherwise (opposite to the GNAT name
-- table, in which a new entry is created it this situation with its
-- Name_Table_Info field set to zero) the Id value corresponding to the
-- ASIS Nil_Compilation_Unit, that is Nil_Unit, is returned.
--
-- Only normalized Ada names are hashed, so this function is intended to
-- be applied to the normalized names only (in is not an error to apply
-- it to other forms of names stored in the table, but the result will
-- always be Nil_Unit.
function Allocate_Unit_Entry (C : Context_Id) return Unit_Id;
-- Allocates the new entry in the Unit Name Table for the "normalized"
-- Ada Unit name stored in the Name_Buffer (Name_Len should be set
-- in a proper way). This routine should be called only if the
-- immediately preceding call to an operation working with Unit Name
-- Table is the call to Name_Find which has yielded Nil_Unit as a
-- result. Note, that this function sets only the "normalized" unit name,
-- it does not set the Ada name or the source file name. It also
-- increases by one the counter of allocated bodies or specs, depending
-- on the suffix in the normalized unit name.
function Allocate_Nonexistent_Unit_Entry (C : Context_Id) return Unit_Id;
-- Differs from the previous function in the following aspects:
-- - 'n' is added to the name suffix to mark that this entry
-- corresponds to the nonexistent unit;
-- - The body/spec counters are not increased
-- - all the attributes of the allocated nonexistent unit are set by
-- this procedure.
--
-- Allocates the new entry in the Unit Name Table for the "normalized"
-- Ada Unit name stored in the Name_Buffer (Name_Len should be set
-- in a proper way). This routine should be called only if the
-- immediately preceding call to an operation working with Unit Name
-- Table is the call to Name_Find which has yielded Nil_Unit as a
-- result. Note, that this function sets only the "normalized" unit name,
-- it does not set the Ada name or the source file name.
function Set_Unit (C : Context_Id; U : Unit_Number_Type) return Unit_Id;
-- Creates the Unit table entry for the unit U and sets the normalized
-- unit name (which is supposed to be stored in A_Name_Buffer when this
-- procedure is called) and the time stamp for the unit. It also adds
-- the (Id of the) currently accessed tree to the (empty) list
-- of (consistent) trees for this unit. All the other unit attributes
-- are set to nil values. The ID of the created entry is returned as a
-- result
procedure Set_Ada_Name (Id : Unit_Id);
pragma Inline (Set_Ada_Name);
-- Sets the string stored in Name_Buffer whose length is Name_Len as the
-- value of the Ada name of the ASIS Unit indicated by Id value
procedure Set_Norm_Ada_Name (Id : Unit_Id);
pragma Inline (Set_Norm_Ada_Name);
-- Sets the string stored in Name_Buffer whose length is Name_Len as the
-- value of the "normalized" Ada name of the ASIS Unit indicated by Id
-- value
procedure Set_Ref_File_As_Source_File (U : Unit_Id);
-- For a given unit in a given context, sets the reference file name equal
-- to the source file name (by copying the corresponding references to
-- the ASIS Chars table
procedure Set_Source_File_Name (Id : Unit_Id; Ref : Boolean := False);
pragma Inline (Set_Source_File_Name);
-- Sets the string stored in the A_Name_Buffer whose length is A_Name_Len
-- as the value of the source or reference (depending on the actual set
-- for the Ref parameter) file name of the ASIS Unit indicated by Id value
procedure Set_Norm_Ada_Name_String;
-- Sets the Normalized Ada Unit name as the value of Name_Buffer.
-- This normalized version of the Ada Unit name is
-- obtained by folding to lover cases of the GNAT unit name
-- which should be previously get as the content of
-- Namet.Name_Buffer (that means that every call to this procedure
-- should be preceded by the appropriate call to
-- Namet.Get_Unqualified_Decoded_Name_String (or
-- Namet.Get_Decoded_Name_String if the caller is sure, that the name is
-- not qualified)
procedure Set_Norm_Ada_Name_String_With_Check
(Unit : Unit_Number_Type;
Success : out Boolean);
-- This is the modified version of Set_Norm_Ada_Name_String: after setting
-- the ASIS name buffer it checks if Unit should be considered as
-- Compilation_Unit by ASIS. The need for this check caused by artificial
-- compilation units created by the compiler for library-level generic
-- instantiations. If the check is successful, Success is set True,
-- otherwise it is set False.
--
-- In case of a tree created for library-level instantiation of a generic
-- package (only package ???) GNAT sets the suffix of the name of the
-- corresponding unit in its unit table as '%b', but ASIS has to see
-- this unit as a spec, therefore in this case this procedure resets the
-- suffix of the unit name to '%s'
procedure Set_Ref_File_Name_String (U : Unit_Id);
-- Is supposed to be called when GNAT Namet.Name_Buffer contains a full
-- reference file name. It sets the Reference File name as the value of
-- A_Name_Buffer. This name is composed from the reference file name
-- obtained from the tree and from the source file name (in which the
-- directory information is already adjusted , if needed, by the
-- corresponding call to Set_S_File_Name_String) to contain the directory
-- information needed to access this file from the current directory.
-------------------------------
-- Black-Box Unit Attributes --
-------------------------------
-- Each Unit entry contains the following fields, representing the Unit
-- black-box attributes, which are for the direct interest for the ASIS
-- queries from the Asis_Compilation_Unit package, the primary idea of
-- implementing the Context/Compilation_Unit stuff in ASIS-for-GNAT is
-- to compute each of these attribute only once, when the new tree is
-- inputted by ASIS for the first time, and then store them in Unit
-- Table, so then ASIS queries will be able to get the required
-- answer without any new tree processing:
-- Top : Node_Id;
-- The top node of the unit subtree in the currently accessed full tree.
-- From one side, this node should be reset every time the full tree
-- is changed. From the other side, the corresponding actions may be
-- considered as too time-consumed. This problem is postponed now as
-- OPEN PROBLEM, it is not important till we are working under the
-- limitation "only one tree can be accessed at a time"
-- Enclosing_Context : Context_Id;
-- The reference to the Context table which indicates the Enclosing
-- Context for a Unit
-- Kind : Unit_Kinds;
-- The kind of a Compilation Unit, as defined by Asis.Unit_Kinds
-- package
-- Class : Unit_Classes;
-- The class of a Compilation Unit, as defined by Asis.Unit_Kinds
-- package
-- Origin : Unit_Origins;
-- The origin of a Compilation Unit, as defined by Asis.Unit_Kinds
-- package
-- Main_Unit : Boolean;
-- The boolean flag indicating if a Compilation Unit may be treated
-- as the main unit for a partition (See RM 10.2(7))
-- GNAT-specific!!??
-- Is_Body_Required : Boolean;
-- The boolean flag indicating if a Compilation Unit requires a body
-- as a completion
-----------------------------------------------------------
-- Black-Box Unit Attributes Access and Update Routines --
-----------------------------------------------------------
function Top (U : Unit_Id) return Node_Id;
-- this function is not trivial, it can have tree swapping as its
-- "side effect"
function Kind (C : Context_Id; U : Unit_Id) return Unit_Kinds;
function Class (C : Context_Id; U : Unit_Id) return Unit_Classes;
function Origin (C : Context_Id; U : Unit_Id) return Unit_Origins;
function Is_Main_Unit (C : Context_Id; U : Unit_Id) return Boolean;
function Is_Body_Required (C : Context_Id; U : Unit_Id) return Boolean;
-- This function does not reset Context, a Caller is responsible for this
function Time_Stamp (C : Context_Id; U : Unit_Id) return Time_Stamp_Type;
function Is_Consistent (C : Context_Id; U : Unit_Id) return Boolean;
function Source_Status (C : Context_Id; U : Unit_Id)
return Source_File_Statuses;
function Main_Tree (C : Context_Id; U : Unit_Id) return Tree_Id;
function Has_Limited_View_Only (C : Context_Id; U : Unit_Id) return Boolean;
-- Checks if U has only limited view in C
--------
procedure Set_Top (C : Context_Id; U : Unit_Id;
N : Node_Id);
procedure Set_Kind (C : Context_Id; U : Unit_Id;
K : Unit_Kinds);
procedure Set_Class (C : Context_Id; U : Unit_Id;
Cl : Unit_Classes);
procedure Set_Origin (C : Context_Id; U : Unit_Id;
O : Unit_Origins);
procedure Set_Is_Main_Unit (C : Context_Id; U : Unit_Id;
M : Boolean);
procedure Set_Is_Body_Required (C : Context_Id; U : Unit_Id;
B : Boolean);
procedure Set_Time_Stamp (C : Context_Id; U : Unit_Id;
T : Time_Stamp_Type);
procedure Set_Is_Consistent (C : Context_Id; U : Unit_Id;
B : Boolean);
procedure Set_Source_Status (C : Context_Id; U : Unit_Id;
S : Source_File_Statuses);
-------------------------------------------------
---------------------------
-- Semantic Dependencies --
---------------------------
----------------------------------------------------
-- Subprograms for Semantic Dependencies Handling --
----------------------------------------------------
function Not_Root return Boolean;
-- Checks if U is not a root library unit (by checking if
-- its name contains a dot). This function itself does not set the
-- normalized name of U in A_Name_Buffer, it is supposed to be called
-- when a proper name is already set.
function Subunits (C : Context_Id; U : Unit_Id) return Unit_Id_List;
-- Returns the full list of Ids of subunits for U (if any). The full list
-- contains nonexistent units for missed subunits
--
-- Note, that this function does not reset Context, it should be done in
-- the caller!
function Get_Subunit
(Parent_Body : Asis.Compilation_Unit;
Stub_Node : Node_Id)
return Asis.Compilation_Unit;
-- This function is intended to be used only when all the Unit attributes
-- are already computed. It gets the Parent_Body, whose tree should
-- contain Stub_Node as a node representing some body stub, and it
-- returns the Compilation Unit containing the proper body for this stub.
-- It returns a Nil_Compilation_Unit, if the Compilation Unit containing
-- the proper body does not exist in the enclosing Context or if it is
-- inconsistent with Parent_Body.
function Children (U : Unit_Id) return Unit_Id_List;
-- returns the list of Ids of children for U (if any)
--
-- Note, that this function does not reset Context, it should be done in
-- the caller!
function GNAT_Compilation_Dependencies (U : Unit_Id) return Unit_Id_List;
-- Returns the full list of GNAT compilation dependencies for U
-- This list is empty if and only if U is not a main unit of some
-- compilation which creates some tree for C.
procedure Form_Parent_Name;
-- supposing A_Name_Buffer containing a normalized unit name, this
-- function forms the normalized name of its parent by stripping out
-- the suffix in the Ada part of the name (that is, the part of the
-- name between the rightmost '.' and '%") and changing the
-- "normalized" suffix to "%s". A_Name_Len is set in accordance with
-- this. If the Ada part of the name contains no suffix (that is, if
-- it corresponds to a root library unit), A_Name_Len is set equal
-- to 0.
function Get_Parent_Unit (C : Context_Id; U : Unit_Id) return Unit_Id;
-- returns the Id of the parent unit declaration for U. If U is
-- First_Unit_Id, returns Nil_Unit.
--
-- Note, that this function does not reset Context, it should be done in
-- the caller!
function Get_Body (C : Context_Id; U : Unit_Id) return Unit_Id;
-- returns the Id of the library_unit_body for the unit U.
-- Nil_Unit is not a valid argument for this function.
--
-- Note, that this function does not reset Context, it should be done in
-- the caller!
function Get_Declaration (C : Context_Id; U : Unit_Id) return Unit_Id;
-- returns the Id of the library_unit_declaration for the unit U.
-- Nil_Unit is not a valid argument for this function.
--
-- Note, that this function does not reset Context, it should be done in
-- the caller!
function Get_Subunit_Parent_Body
(C : Context_Id;
U : Unit_Id)
return Unit_Id;
-- returns the Id of the library_unit_body or subunit being the parent
-- body for subunit U (a caller is responsible for calling this function
-- for subunits).
function Get_Nonexistent_Unit (C : Context_Id) return Unit_Id;
-- Is supposed to be called just after an attempt to get a unit which is
-- supposed to be a needed declaration or a needed body (that is,
-- A_Name_Buffer contains a normalized unit name ending with "%s" or "%b"
-- respectively). Tries to find the unit of A_Nonexistent_Declaration
-- or A_Nonexistent_Body kind with this name, if this attempt fails,
-- allocates the new unit entry for the corresponding nonexistent unit.
-- Returns the Id of found or allocated unit.
function Get_Same_Unit
(Arg_C : Context_Id;
Arg_U : Unit_Id;
Targ_C : Context_Id)
return Unit_Id;
-- Tries to find in Targ_C just the same unit as Arg_U is in Arg_C.
-- Just the same means, that Arg_U and the result of this function
-- should have just the same time stamps. If Arg_C = Targ_C, Arg_U
-- is returned. If there is no "just the same" unit in Targ_C,
-- Nil_Unit is returned.
--
-- If No (Arg_U), then the currently accessed Context is not reset (but
-- this function is not supposed to be called for Arg_U equal to
-- Nil_Unit_Id, although it is not an error). Otherwise Context is reset
-- to Targ_C
--------------------------------------
-- General-Purpose Unit Subprograms --
--------------------------------------
procedure Finalize (C : Context_Id);
-- Currently this routine is only used to generate debugging output
-- for the Unit Table of a given Context.
function Present (Unit : Unit_Id) return Boolean;
-- Tests given Unit Id for equality with Nil_Unit. This allows
-- notations like "if Present (Current_Supporter)" as opposed to
-- "if Current_Supporter /= Nil_Unit
function No (Unit : Unit_Id) return Boolean;
-- Tests given Unit Id for equality with Nil_Unit. This allows
-- notations like "if No (Current_Supporter)" as opposed to
-- "if Current_Supporter = Nil_Unit
function Last_Unit return Unit_Id;
-- Returns the Unit_Id of the last unit which has been allocated in the
-- Unit Name Table. Used to define that the Unit_Id value returned by
-- Name_Find corresponds to the ASIS Compilation Unit which is not
-- known to ASIS.
function Lib_Unit_Decls (C : Context_Id) return Natural;
-- returns the number of library_unit_declaratios allocated in the
-- Context Unit table
function Comp_Unit_Bodies (C : Context_Id) return Natural;
-- returns the number of library_unit_bodies and subunits allocated
-- in the Context Unit table
function Next_Decl (D : Unit_Id) return Unit_Id;
-- Returns the Unit_Id of the next unit (starting from, but not including
-- D), which is a library_unit_declaration. Returns Nil_Unit, if there
-- is no such a unit in C.
--
-- Note, that this function does not reset Context, it should be done in
-- the caller!
function First_Body return Unit_Id;
-- Returns the Unit_Id of the first unit which is a
-- compilation_unit_body or a subunit. Returns Nil_Unit, if there is
-- no such a unit in a current Context.
--
-- Note, that this function does not reset Context, it should be done in
-- the caller!
function Next_Body (B : Unit_Id) return Unit_Id;
-- Returns the Unit_Id of the next unit (starting from, but not including
-- B) which is a compilation_unit_body or a subunit. Returns Nil_Unit,
-- if there is no such a unit in C.
--
-- Note, that this function does not reset Context, it should be done in
-- the caller!
procedure Output_Unit (C : Context_Id; Unit : Unit_Id);
-- Produces the debug output of the Unit Table entry corresponding
-- to Unit
-- DO WE NEED THIS PROCEDURE IN THE SPECIFICATION????
procedure Print_Units (C : Context_Id);
-- Produces the debug output from the Unit table for the Context C.
function Enclosing_Unit
(Cont : Context_Id;
Node : Node_Id)
return Asis.Compilation_Unit;
-- This function is intended to be used to define the enclosing
-- unit for an Element obtained as a result of some ASIS semantic query.
-- It finds the N_Compilation_Unit node for the subtree enclosing
-- the Node given as its argument, and then defines the corresponding
-- Unit Id, which is supposed to be the Id of Enclosing Unit for an
-- Element built up on the base of Node. It does not change the tree
-- being currently accessed. All these computations are supposed
-- to be performed for a Context Cont.
-- Node should not be a result of Atree.Original_Node, because
-- it is used as an argument for Atree.Parent function
--
-- Note, that this function does no consistency check, that is, the
-- currently accessed tree may be not from the list of consistent trees
-- for the resulted Unit.
---------------
-- NEW STUFF --
---------------
procedure Register_Units (Set_First_New_Unit : Boolean := False);
-- When a new tree file is read in during Opening a Context, this procedure
-- goes through all the units represented by this tree and checks if these
-- units are already known to ASIS. If some unit is unknown, this
-- procedure "register" it - it creates the corresponding entry in the
-- unit table, and it sets the normalized unit name. It does not set any
-- other field of unit record except Kind. It sets Kind as Not_A_Unit
-- to indicate, that this unit is only registered, but not processed.
--
-- We need this (pre-)registration to be made before starting unit
-- processing performed by Process_Unit_New, because we need all the units
-- presenting in the tree to be presented also in the Context unit table
-- when storing the dependency information.
--
-- Note, that all the consistency checks are made by Process_Unit_New,
-- even though we can make them here. The reason is to separate this
-- (pre-)registration (which is an auxiliary technical action) from
-- unit-by-unit processing to facilitate the maintainability of the code.
--
-- If Set_First_New_Unit is set ON, stores in A4G.Contt.First_New_Unit
-- the first new unit being registered. If Set_First_New_Unit is set OFF
-- or if no new units has been registered, First_New_Unit is set to
-- Nil_Unit
--
-- ??? The current implementation uses Set_Unit, which also sets time
-- ??? stamp for a unit being registered. It looks like we do not need
-- ??? this, so we can get rid of this.
function Already_Processed (C : Context_Id; U : Unit_Id) return Boolean;
-- Checks if U has already been processed when scanning previous trees
-- during opening C
procedure Check_Source_Consistency
(C : Context_Id;
U_Id : Unit_Id);
-- Is called when a Unit is being investigated as encountered for the first
-- time during opening the Context C. It checks the existence of the source
-- file for this unit, and if the source file exists, it checks that the
-- units as represented by the tree is consistent with the source (if this
-- is required by the options associated with the Context).
-- This procedure should be called after extracting the source file name
-- from the tree and putting this into the Context unit table.
procedure Check_Consistency
(C : Context_Id;
U_Id : Unit_Id;
U_Num : Unit_Number_Type);
-- Is called when a unit is encountered again when opening C. Checks if in
-- the currently accessed tree this unit has the same time stamp as it had
-- in all the previously processed trees. In case if this check fails, it
-- raises ASIS_Failed and forms the diagnosis on behalf of
-- Asis.Ada_Environments.Open. (This procedure does not check the source
-- file for the unit - this should be done by Check_Source_Consistency
-- when the unit was processed for the first time)
function TS_From_OS_Time (T : OS_Time) return Time_Stamp_Type;
-- Converts OS_Time into Time_Stamp_Type. Is this the right place for
-- this function???
procedure Reset_Cache;
-- Resents to the empty state the cache data structure used to speed up the
-- Top function. Should be called as a part of closing a Context.
end A4G.Contt.UT;
|
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
|
|
affb88e3a79b93cc6ceccc0135b595c5be6ab6f7
|
src/asis/a4g-u_conv.ads
|
src/asis/a4g-u_conv.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . U _ C O N V --
-- --
-- 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). --
-- --
------------------------------------------------------------------------------
with GNAT.OS_Lib; use GNAT.OS_Lib;
package A4G.U_Conv is
-- !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-- !! !!
-- !! This package should be completely revised (and very likely - !!
-- !! removed), when migration to using pre-created trees as to the !!
-- !! *ONLY* ASIS operation mode is completed !!
-- !! !!
-- !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-- This paskage contain routines supporting the ASIS and ASIS-GNAT conventions
-- for file and unit names.
-----------------
-- Subprograms --
-----------------
procedure Get_Norm_Unit_Name (U_Name : String;
N_U_Name : out String;
Spec : Boolean;
May_Be_Unit_Name : out Boolean);
-- Having got U_Name as supposetely being an Ada unit name, this procedure
-- checks if it satisfies the Ada unit name syntax structure and tries to
-- convert it into "normalized" form by folding all the letters to
-- lower case and appending the "%s" or "%b" suffix depending on the
-- value of Spec (See also unitt.ads). If U_Name can be treated as Ada
-- unit name, its "normalized" version is returned as the value of
-- N_U_Name, and May_Be_Unit_Name is set True. If the structure of
-- U_Name does not satisfy the syntax rules imposed on the Ada unit
-- names, May_Be_Unit_Name is set False, and the value of N_U_Name is
-- undefined.
--
-- The caller is responcible for the fact, that the length of the actual
-- for N_U_Name is the length of the actual for U_Name plus 2
-- (for "%s" or "%b") ). The caller is also responsible for the
-- fact that the lower bounds of U_Name and N_U_Name are the same.
-- (Otherwise CONSTRAINT_ERROR will be raised). It is also supposed
-- that this procedure will never be called for the empty string as an
-- actual for U_Name.
--
-- Note, that the "normalized" Unit name returned by this routine
-- does not contain the prefix indicating the enclosing Context.
function Source_From_Unit_Name
(S : String;
Spec : Boolean)
return String_Access;
-- Converts S into the ada source file name according to the file name
-- rules specified in GNAT DOCUMENT INTRO. The suffix of the file name
-- is set as ".ads" if Spec is True or ".adb" otherwise.
--
-- It is supposed that this function is called for S that is non-empty
-- string having a structure of the fully expynded Ada unit unit name.
-- This function does not check the content of S leaving it to the
-- caller.
--
-- The result of this function is NUL-terminated
function Tree_From_Source_Name (S : String_Access) return String_Access;
-- Returns the reference to a newly created NUL-terminated string.
-- It is supposed to be called only for the (references to the) Ada
-- source file names obtained as the results of the Locate_In_Context
-- function. It is also supposed that S points to a NUL-terminated
-- string. The content of the returned string is obtained by
-- transforming the content of the string pointed by S and interpreted
-- as Ada source file name into the name of the corresponding tree
-- output file.
--
-- This function requires revising if the effect of Source_File_Name
-- pragma is implemented!
function Is_Predefined_File_Name (S : String_Access) return Boolean;
-- This function is the full analog of the GNAT function
-- Fname.Is_Predefined_File_Name, but it works with the string
-- value which is not stored in the GNAT name buffer.
function To_String (S : String_Access) return String;
-- Should be applied only to the references to NUL terminated
-- strings (usially - file names). Returns the content of the
-- referenced string without the trailing NUL character.
end A4G.U_Conv;
|
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
|
|
f8ca37cc5951563ff4bb157a3cde81c2ca3008ad
|
src/asis/a4g-u_conv.adb
|
src/asis/a4g-u_conv.adb
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . U _ C O N V --
-- --
-- B o d y --
-- --
-- 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). --
-- --
------------------------------------------------------------------------------
with Ada.Characters.Handling; use Ada.Characters.Handling;
with Namet; use Namet;
with Fname; use Fname;
with Krunch;
with Opt; use Opt;
package body A4G.U_Conv is
---------------------------------
-- Local Types and Subprograms --
---------------------------------
-- We use the trivial finite state automata to analyse and to transform
-- strings passed as parameters to ASIS interfaces and processed by ASIS
-- itself below there are type and routines definitions for various
-- versions of this automata
type State is (Beg_Ident, Mid_Ident, Und_Line);
-- The states of the automata. Some versions may use only a part of the
-- whole set of states.
procedure Normalize_Char (In_Char : Character;
Curr_State : in out State;
Out_Char : out Character;
OK : out Boolean);
-- One step of the finite-state-automata analyzing the string which is
-- supposed to be an Ada unit name and producind the "normalized"
-- version of the name. If In_Char under in the state Curr_State may be
-- considered as belonging to the Ada unit name, the "low-case version"
-- of this character is assigned to Out_Char, and OK is ste True,
-- otherwise OK is set false
function Convert_Char (Ch : Character) return Character;
-- performs upper case -> lover case conversion in the GNAT file
-- name style (see GNAT Document INTRO and Fnames.ads - only letters
-- from the A .. Z range are folded to lower case)
------------------
-- Convert_Char --
------------------
function Convert_Char (Ch : Character) return Character is
begin
if Ch = '.' then
return '-';
else
return To_Lower (Ch);
end if;
end Convert_Char;
------------------------
-- Get_Norm_Unit_Name --
------------------------
procedure Get_Norm_Unit_Name
(U_Name : String;
N_U_Name : out String;
Spec : Boolean;
May_Be_Unit_Name : out Boolean)
is
Current_State : State := Beg_Ident;
begin
May_Be_Unit_Name := False;
for I in U_Name'Range loop
Normalize_Char (U_Name (I), Current_State,
N_U_Name (I), May_Be_Unit_Name);
exit when not May_Be_Unit_Name;
end loop;
if not May_Be_Unit_Name then
return;
elsif N_U_Name (U_Name'Last) = '_' or else
N_U_Name (U_Name'Last) = '.'
then
-- something like "Ab_" -> "ab_" or "Ab_Cd." -> "ab_cd."
May_Be_Unit_Name := False;
return;
end if;
-- here we have all the content of U_Name parced and
-- May_Be_Unit_Name is True. All we have to do is to append
-- the "%s" or "%b" suffix
N_U_Name (N_U_Name'Last - 1) := '%';
if Spec then
N_U_Name (N_U_Name'Last) := 's';
else
N_U_Name (N_U_Name'Last) := 'b';
end if;
end Get_Norm_Unit_Name;
-----------------------------
-- Is_Predefined_File_Name --
-----------------------------
function Is_Predefined_File_Name (S : String_Access) return Boolean is
begin
Namet.Name_Len := S'Length - 1;
-- "- 1" is for trailing ASCII.NUL in the file name
Namet.Name_Buffer (1 .. Namet.Name_Len) := To_String (S);
return Fname.Is_Predefined_File_Name (Namet.Name_Enter);
end Is_Predefined_File_Name;
--------------------
-- Normalize_Char --
--------------------
procedure Normalize_Char
(In_Char : Character;
Curr_State : in out State;
Out_Char : out Character;
OK : out Boolean)
is
begin
OK := True;
case Curr_State is
when Beg_Ident =>
if Is_Letter (In_Char) then
Curr_State := Mid_Ident;
else
OK := False;
end if;
when Mid_Ident =>
if Is_Letter (In_Char) or else
Is_Digit (In_Char)
then
null;
elsif In_Char = '_' then
Curr_State := Und_Line;
elsif In_Char = '.' then
Curr_State := Beg_Ident;
else
OK := False;
end if;
when Und_Line =>
if Is_Letter (In_Char) or else
Is_Digit (In_Char)
then
Curr_State := Mid_Ident;
else
OK := False;
end if;
end case;
Out_Char := To_Lower (In_Char);
end Normalize_Char;
---------------------------
-- Source_From_Unit_Name --
---------------------------
function Source_From_Unit_Name
(S : String;
Spec : Boolean)
return String_Access
is
Result_Prefix : String (1 .. S'Length);
Result_Selector : String (1 .. 4) := ".adb";
Initial_Length : constant Natural := S'Length;
Result_Length : Natural := Initial_Length;
-- this is for the name krunching
begin
for I in S'Range loop
Result_Prefix (I) := Convert_Char (S (I));
end loop;
Krunch
(Buffer => Result_Prefix,
Len => Result_Length,
Maxlen => Integer (Maximum_File_Name_Length),
No_Predef => False);
if Spec then
Result_Selector (4) := 's';
end if;
return new String'(Result_Prefix (1 .. Result_Length)
& Result_Selector
& ASCII.NUL);
end Source_From_Unit_Name;
---------------
-- To_String --
---------------
function To_String (S : String_Access) return String is
begin
return S.all (S'First .. S'Last - 1);
end To_String;
---------------------------
-- Tree_From_Source_Name --
---------------------------
function Tree_From_Source_Name (S : String_Access) return String_Access is
Return_Val : String_Access;
begin
Return_Val := new String'(S.all);
-- the content of S should be "*.ad?" & ASCII.NUL
Return_Val (Return_Val'Last - 1) := 't'; -- ".ad?" -> ".adt"
return Return_Val;
end Tree_From_Source_Name;
end A4G.U_Conv;
|
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
|
|
edaaf48ed03608b6cc9d348b9f184b8cbb0addb2
|
mat/src/gtk/mat-targets-gtkmat.ads
|
mat/src/gtk/mat-targets-gtkmat.ads
|
-----------------------------------------------------------------------
-- mat-targets-gtkmat - Gtk target management
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Gtk.Widget;
with Gtkada.Builder;
package MAT.Targets.Gtkmat is
type Target_Type is new MAT.Targets.Target_Type with private;
-- Initialize the widgets and create the Gtk gui.
procedure Initialize_Widget (Target : in out Target_Type;
Widget : out Gtk.Widget.Gtk_Widget);
-- Create a process instance to hold and keep track of memory and other information about
-- the given process ID.
overriding
procedure Create_Process (Target : in out Target_Type;
Pid : in MAT.Types.Target_Process_Ref;
Path : in Ada.Strings.Unbounded.Unbounded_String;
Process : out Target_Process_Type_Access);
private
type Target_Type is new MAT.Targets.Target_Type with record
Builder : Gtkada.Builder.Gtkada_Builder;
end record;
end MAT.Targets.Gtkmat;
|
Define a targets package for the Gtk UI
|
Define a targets package for the Gtk UI
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
|
dfc1f33140bf04ec54dc79eec7e2c753878df867
|
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 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);
type Name_Array is array (Natural range <>) of Value;
-- Return the name of the properties defined in the manager.
function Get_Names (Self : in Manager) return Name_Array;
-- Load the properties from the file input stream. The file must follow
-- the definition of Java property files.
procedure Load_Properties (Self : in out Manager'Class;
File : in Ada.Text_IO.File_Type);
-- Load the properties from the file. The file must follow the
-- definition of Java property files.
-- Raises NAME_ERROR if the file does not exist.
procedure Load_Properties (Self : in out Manager'Class;
Path : in String);
-- Copy the properties from FROM which start with a given prefix.
-- If the prefix is empty, all properties are copied.
procedure Copy (Self : in out Manager'Class;
From : in Manager'Class;
Prefix : in String := "");
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;
-- 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) 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;
procedure Adjust (Object : in out Manager);
procedure Finalize (Object : in out Manager);
end Util.Properties;
|
-----------------------------------------------------------------------
-- 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);
type Name_Array is array (Natural range <>) of Value;
-- Return the name of the properties defined in the manager.
function Get_Names (Self : in Manager) return Name_Array;
-- Load the properties from the file input stream. The file must follow
-- the definition of Java property files.
procedure Load_Properties (Self : in out Manager'Class;
File : in Ada.Text_IO.File_Type);
-- Load the properties from the file. The file must follow the
-- definition of Java property files.
-- Raises NAME_ERROR if the file does not exist.
procedure Load_Properties (Self : in out Manager'Class;
Path : in String);
-- Copy the properties from FROM which start with a given prefix.
-- If the prefix is empty, all properties are copied.
procedure Copy (Self : in out Manager'Class;
From : in Manager'Class;
Prefix : in String := "");
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;
-- 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) 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;
procedure Adjust (Object : in out Manager);
procedure Finalize (Object : in out Manager);
end Util.Properties;
|
Update the Manager_Access to be class-wide access type
|
Update the Manager_Access to be class-wide access type
|
Ada
|
apache-2.0
|
Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util
|
1f1a0379a34a0959996bbbd21e073a519c7dd1ab
|
src/util-files.adb
|
src/util-files.adb
|
-----------------------------------------------------------------------
-- Util.Files -- Various File Utility Packages
-- 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.Directories;
with Ada.Strings.Fixed;
with Ada.Streams;
with Ada.Streams.Stream_IO;
with Ada.Text_IO;
package body Util.Files is
-- ------------------------------
-- Read a complete file into a string.
-- The <b>Max_Size</b> parameter indicates the maximum size that is read.
-- ------------------------------
procedure Read_File (Path : in String;
Into : out Unbounded_String;
Max_Size : in Natural := 0) is
use Ada.Streams;
use Ada.Streams.Stream_IO;
F : File_Type;
Buffer : Stream_Element_Array (1 .. 10_000);
Pos : Positive_Count := 1;
Last : Stream_Element_Offset;
Space : Natural;
begin
if Max_Size = 0 then
Space := Natural'Last;
else
Space := Max_Size;
end if;
Open (Name => Path, File => F, Mode => In_File);
loop
Read (File => F, Item => Buffer, From => Pos, Last => Last);
if Natural (Last) > Space then
Last := Stream_Element_Offset (Space);
end if;
for I in 1 .. Last loop
Append (Into, Character'Val (Buffer (I)));
end loop;
exit when Last < Buffer'Length;
Pos := Pos + Positive_Count (Last);
end loop;
Close (F);
exception
when others =>
if Is_Open (F) then
Close (F);
end if;
raise;
end Read_File;
-- ------------------------------
-- Read the file with the given path, one line at a time and execute the <b>Process</b>
-- procedure with each line as argument.
-- ------------------------------
procedure Read_File (Path : in String;
Process : not null access procedure (Line : in String)) is
File : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Open (File => File,
Mode => Ada.Text_IO.In_File,
Name => Path);
while not Ada.Text_IO.End_Of_File (File) loop
Process (Ada.Text_IO.Get_Line (File));
end loop;
Ada.Text_IO.Close (File);
end Read_File;
-- ------------------------------
-- Save the string into a file creating the file if necessary
-- ------------------------------
procedure Write_File (Path : in String;
Content : in String) is
use Ada.Streams;
use Ada.Streams.Stream_IO;
use Ada.Directories;
F : File_Type;
Buffer : Stream_Element_Array (Stream_Element_Offset (Content'First)
.. Stream_Element_Offset (Content'Last));
Dir : constant String := Containing_Directory (Path);
begin
if not Exists (Dir) then
Create_Path (Dir);
end if;
Create (File => F, Name => Path);
for I in Content'Range loop
Buffer (Stream_Element_Offset (I))
:= Stream_Element (Character'Pos (Content (I)));
end loop;
Write (F, Buffer);
Close (F);
exception
when others =>
if Is_Open (F) then
Close (F);
end if;
raise;
end Write_File;
-- ------------------------------
-- Save the string into a file creating the file if necessary
-- ------------------------------
procedure Write_File (Path : in String;
Content : in Unbounded_String) is
begin
Write_File (Path, Ada.Strings.Unbounded.To_String (Content));
end Write_File;
-- ------------------------------
-- Iterate over the search directories defined in <b>Paths</b> and execute
-- <b>Process</b> with each directory until it returns <b>True</b> in <b>Done</b>
-- or the last search directory is found. Each search directory
-- is separated by ';' (yes, even on Unix). When <b>Going</b> is set to Backward, the
-- directories are searched in reverse order.
-- ------------------------------
procedure Iterate_Path (Path : in String;
Process : not null access procedure (Dir : in String;
Done : out Boolean);
Going : in Direction := Ada.Strings.Forward) is
use Ada.Directories;
use Ada.Strings;
use Ada.Strings.Fixed;
Sep_Pos : Natural;
Pos : Natural;
Last : constant Natural := Path'Last;
begin
case Going is
when Forward =>
Pos := Path'First;
while Pos <= Last loop
Sep_Pos := Index (Path, ";", Pos);
if Sep_Pos = 0 then
Sep_Pos := Last;
else
Sep_Pos := Sep_Pos - 1;
end if;
declare
Dir : constant String := Path (Pos .. Sep_Pos);
Done : Boolean;
begin
Process (Dir => Dir, Done => Done);
exit when Done;
end;
Pos := Sep_Pos + 2;
end loop;
when Backward =>
Pos := Path'Last;
while Pos >= Path'First loop
Sep_Pos := Index (Path, ";", Pos, Backward);
if Sep_Pos = 0 then
Sep_Pos := Path'First;
else
Sep_Pos := Sep_Pos + 1;
end if;
declare
Dir : constant String := Path (Sep_Pos .. Pos);
Done : Boolean;
begin
Process (Dir => Dir, Done => Done);
exit when Done or Sep_Pos = Path'First;
end;
Pos := Sep_Pos - 2;
end loop;
end case;
end Iterate_Path;
-- ------------------------------
-- Find the file in one of the search directories. Each search directory
-- is separated by ';' (yes, even on Unix).
-- Returns the path to be used for reading the file.
-- ------------------------------
function Find_File_Path (Name : String;
Paths : String) return String is
use Ada.Directories;
use Ada.Strings.Fixed;
Sep_Pos : Natural;
Pos : Positive := Paths'First;
Last : constant Natural := Paths'Last;
begin
while Pos <= Last loop
Sep_Pos := Index (Paths, ";", Pos);
if Sep_Pos = 0 then
Sep_Pos := Last;
else
Sep_Pos := Sep_Pos - 1;
end if;
declare
Path : constant String := Util.Files.Compose (Paths (Pos .. Sep_Pos), Name);
begin
if Exists (Path) and then Kind (Path) = Ordinary_File then
return Path;
end if;
exception
when Name_Error =>
null;
end;
Pos := Sep_Pos + 2;
end loop;
return Name;
end Find_File_Path;
-- ------------------------------
-- Iterate over the search directories defined in <b>Path</b> and search
-- for files matching the pattern defined by <b>Pattern</b>. For each file,
-- execute <b>Process</b> with the file basename and the full file path.
-- Stop iterating when the <b>Process</b> procedure returns True.
-- Each search directory is separated by ';'. When <b>Going</b> is set to Backward, the
-- directories are searched in reverse order.
-- ------------------------------
procedure Iterate_Files_Path (Pattern : in String;
Path : in String;
Process : not null access procedure (Name : in String;
File : in String;
Done : out Boolean);
Going : in Direction := Ada.Strings.Forward) is
procedure Find_Files (Dir : in String;
Done : out Boolean);
-- ------------------------------
-- Find the files matching the pattern in <b>Dir</b>.
-- ------------------------------
procedure Find_Files (Dir : in String;
Done : out Boolean) is
use Ada.Directories;
Filter : constant Filter_Type := (Ordinary_File => True, others => False);
Ent : Directory_Entry_Type;
Search : Search_Type;
begin
Done := False;
Start_Search (Search, Directory => Dir,
Pattern => Pattern, Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Name : constant String := Simple_Name (Ent);
File_Path : constant String := Full_Name (Ent);
begin
Process (Name, File_Path, Done);
exit when Done;
end;
end loop;
end Find_Files;
begin
Iterate_Path (Path => Path, Process => Find_Files'Access, Going => Going);
end Iterate_Files_Path;
-- ------------------------------
-- Find the files which match the pattern in the directories specified in the
-- search path <b>Path</b>. Each search directory is separated by ';'.
-- File names are added to the string set in <b>Into</b>.
-- ------------------------------
procedure Find_Files_Path (Pattern : in String;
Path : in String;
Into : in out Util.Strings.Maps.Map) is
procedure Add_File (Name : in String;
File_Path : in String;
Done : out Boolean);
-- ------------------------------
-- Find the files matching the pattern in <b>Dir</b>.
-- ------------------------------
procedure Add_File (Name : in String;
File_Path : in String;
Done : out Boolean) is
begin
if not Into.Contains (Name) then
Into.Insert (Name, File_Path);
end if;
Done := False;
end Add_File;
begin
Iterate_Files_Path (Pattern => Pattern, Path => Path, Process => Add_File'Access);
end Find_Files_Path;
-- ------------------------------
-- Compose an existing path by adding the specified name to each path component
-- and return a new paths having only existing directories. Each directory is
-- separated by ';'.
-- If the composed path exists, it is added to the result path.
-- Example:
-- paths = 'web;regtests' name = 'info'
-- result = 'web/info;regtests/info'
-- Returns the composed path.
-- ------------------------------
function Compose_Path (Paths : in String;
Name : in String) return String is
procedure Compose (Dir : in String;
Done : out Boolean);
Result : Unbounded_String;
-- ------------------------------
-- Build the new path by checking if <b>Name</b> exists in <b>Dir</b>
-- and appending the new path in the <b>Result</b>.
-- ------------------------------
procedure Compose (Dir : in String;
Done : out Boolean) is
use Ada.Directories;
use Ada.Strings.Fixed;
Path : constant String := Util.Files.Compose (Dir, Name);
begin
Done := False;
if Exists (Path) and then Kind (Path) = Directory then
if Length (Result) > 0 then
Append (Result, ';');
end if;
Append (Result, Path);
end if;
exception
when Name_Error =>
null;
end Compose;
begin
Iterate_Path (Path => Paths, Process => Compose'Access);
return To_String (Result);
end Compose_Path;
-- ------------------------------
-- Returns the name of the external file with the specified directory
-- and the name. Unlike the Ada.Directories.Compose, the name can represent
-- a relative path and thus include directory separators.
-- ------------------------------
function Compose (Directory : in String;
Name : in String) return String is
begin
if Name'Length = 0 then
return Directory;
elsif Directory'Length = 0 or Directory = "." or Directory = "./" then
return Name;
elsif Directory (Directory'Last) = '/' and Name (Name'First) = '/' then
return Directory & Name (Name'First + 1 .. Name'Last);
elsif Directory (Directory'Last) = '/' or Name (Name'First) = '/' then
return Directory & Name;
else
return Directory & "/" & Name;
end if;
end Compose;
-- ------------------------------
-- Returns a relative path whose origin is defined by <b>From</b> and which refers
-- to the absolute path referenced by <b>To</b>. Both <b>From</b> and <b>To</b> are
-- assumed to be absolute pathes. Returns the absolute path <b>To</b> if the relative
-- path could not be found. Both paths must have at least one root component in common.
-- ------------------------------
function Get_Relative_Path (From : in String;
To : in String) return String is
Result : Unbounded_String;
Last : Natural := 0;
begin
for I in From'Range loop
if I > To'Last or else From (I) /= To (I) then
-- Nothing in common, return the absolute path <b>To</b>.
if Last <= From'First + 1 then
return To;
end if;
for J in Last .. From'Last - 1 loop
if From (J) = '/' or From (J) = '\' then
Append (Result, "../");
end if;
end loop;
if Last <= To'Last and From (I) /= '/' and From (I) /= '\' then
Append (Result, "../");
Append (Result, To (Last .. To'Last));
end if;
return To_String (Result);
elsif I < From'Last and then (From (I) = '/' or From (I) = '\') then
Last := I + 1;
end if;
end loop;
if To'Last = From'Last or (To'Last = From'Last + 1
and (To (To'Last) = '/' or To (To'Last) = '\')) then
return ".";
elsif Last = 0 then
return To;
elsif To (From'Last + 1) = '/' or To (From'Last + 1) = '\' then
return To (From'Last + 2 .. To'Last);
else
return To (Last .. To'Last);
end if;
end Get_Relative_Path;
end Util.Files;
|
-----------------------------------------------------------------------
-- Util.Files -- Various File Utility Packages
-- 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.Directories;
with Ada.Strings.Fixed;
with Ada.Streams;
with Ada.Streams.Stream_IO;
with Ada.Text_IO;
with Util.Strings.Tokenizers;
package body Util.Files is
-- ------------------------------
-- Read a complete file into a string.
-- The <b>Max_Size</b> parameter indicates the maximum size that is read.
-- ------------------------------
procedure Read_File (Path : in String;
Into : out Unbounded_String;
Max_Size : in Natural := 0) is
use Ada.Streams;
use Ada.Streams.Stream_IO;
F : File_Type;
Buffer : Stream_Element_Array (1 .. 10_000);
Pos : Positive_Count := 1;
Last : Stream_Element_Offset;
Space : Natural;
begin
if Max_Size = 0 then
Space := Natural'Last;
else
Space := Max_Size;
end if;
Open (Name => Path, File => F, Mode => In_File);
loop
Read (File => F, Item => Buffer, From => Pos, Last => Last);
if Natural (Last) > Space then
Last := Stream_Element_Offset (Space);
end if;
for I in 1 .. Last loop
Append (Into, Character'Val (Buffer (I)));
end loop;
exit when Last < Buffer'Length;
Pos := Pos + Positive_Count (Last);
end loop;
Close (F);
exception
when others =>
if Is_Open (F) then
Close (F);
end if;
raise;
end Read_File;
-- ------------------------------
-- Read the file with the given path, one line at a time and execute the <b>Process</b>
-- procedure with each line as argument.
-- ------------------------------
procedure Read_File (Path : in String;
Process : not null access procedure (Line : in String)) is
File : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Open (File => File,
Mode => Ada.Text_IO.In_File,
Name => Path);
while not Ada.Text_IO.End_Of_File (File) loop
Process (Ada.Text_IO.Get_Line (File));
end loop;
Ada.Text_IO.Close (File);
end Read_File;
-- ------------------------------
-- Save the string into a file creating the file if necessary
-- ------------------------------
procedure Write_File (Path : in String;
Content : in String) is
use Ada.Streams;
use Ada.Streams.Stream_IO;
use Ada.Directories;
F : File_Type;
Buffer : Stream_Element_Array (Stream_Element_Offset (Content'First)
.. Stream_Element_Offset (Content'Last));
Dir : constant String := Containing_Directory (Path);
begin
if not Exists (Dir) then
Create_Path (Dir);
end if;
Create (File => F, Name => Path);
for I in Content'Range loop
Buffer (Stream_Element_Offset (I))
:= Stream_Element (Character'Pos (Content (I)));
end loop;
Write (F, Buffer);
Close (F);
exception
when others =>
if Is_Open (F) then
Close (F);
end if;
raise;
end Write_File;
-- ------------------------------
-- Save the string into a file creating the file if necessary
-- ------------------------------
procedure Write_File (Path : in String;
Content : in Unbounded_String) is
begin
Write_File (Path, Ada.Strings.Unbounded.To_String (Content));
end Write_File;
-- ------------------------------
-- Iterate over the search directories defined in <b>Paths</b> and execute
-- <b>Process</b> with each directory until it returns <b>True</b> in <b>Done</b>
-- or the last search directory is found. Each search directory
-- is separated by ';' (yes, even on Unix). When <b>Going</b> is set to Backward, the
-- directories are searched in reverse order.
-- ------------------------------
procedure Iterate_Path (Path : in String;
Process : not null access procedure (Dir : in String;
Done : out Boolean);
Going : in Direction := Ada.Strings.Forward) is
begin
Util.Strings.Tokenizers.Iterate_Tokens (Content => Path,
Pattern => ";",
Process => Process,
Going => Going);
end Iterate_Path;
-- ------------------------------
-- Find the file in one of the search directories. Each search directory
-- is separated by ';' (yes, even on Unix).
-- Returns the path to be used for reading the file.
-- ------------------------------
function Find_File_Path (Name : String;
Paths : String) return String is
use Ada.Directories;
use Ada.Strings.Fixed;
Sep_Pos : Natural;
Pos : Positive := Paths'First;
Last : constant Natural := Paths'Last;
begin
while Pos <= Last loop
Sep_Pos := Index (Paths, ";", Pos);
if Sep_Pos = 0 then
Sep_Pos := Last;
else
Sep_Pos := Sep_Pos - 1;
end if;
declare
Path : constant String := Util.Files.Compose (Paths (Pos .. Sep_Pos), Name);
begin
if Exists (Path) and then Kind (Path) = Ordinary_File then
return Path;
end if;
exception
when Name_Error =>
null;
end;
Pos := Sep_Pos + 2;
end loop;
return Name;
end Find_File_Path;
-- ------------------------------
-- Iterate over the search directories defined in <b>Path</b> and search
-- for files matching the pattern defined by <b>Pattern</b>. For each file,
-- execute <b>Process</b> with the file basename and the full file path.
-- Stop iterating when the <b>Process</b> procedure returns True.
-- Each search directory is separated by ';'. When <b>Going</b> is set to Backward, the
-- directories are searched in reverse order.
-- ------------------------------
procedure Iterate_Files_Path (Pattern : in String;
Path : in String;
Process : not null access procedure (Name : in String;
File : in String;
Done : out Boolean);
Going : in Direction := Ada.Strings.Forward) is
procedure Find_Files (Dir : in String;
Done : out Boolean);
-- ------------------------------
-- Find the files matching the pattern in <b>Dir</b>.
-- ------------------------------
procedure Find_Files (Dir : in String;
Done : out Boolean) is
use Ada.Directories;
Filter : constant Filter_Type := (Ordinary_File => True, others => False);
Ent : Directory_Entry_Type;
Search : Search_Type;
begin
Done := False;
Start_Search (Search, Directory => Dir,
Pattern => Pattern, Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Name : constant String := Simple_Name (Ent);
File_Path : constant String := Full_Name (Ent);
begin
Process (Name, File_Path, Done);
exit when Done;
end;
end loop;
end Find_Files;
begin
Iterate_Path (Path => Path, Process => Find_Files'Access, Going => Going);
end Iterate_Files_Path;
-- ------------------------------
-- Find the files which match the pattern in the directories specified in the
-- search path <b>Path</b>. Each search directory is separated by ';'.
-- File names are added to the string set in <b>Into</b>.
-- ------------------------------
procedure Find_Files_Path (Pattern : in String;
Path : in String;
Into : in out Util.Strings.Maps.Map) is
procedure Add_File (Name : in String;
File_Path : in String;
Done : out Boolean);
-- ------------------------------
-- Find the files matching the pattern in <b>Dir</b>.
-- ------------------------------
procedure Add_File (Name : in String;
File_Path : in String;
Done : out Boolean) is
begin
if not Into.Contains (Name) then
Into.Insert (Name, File_Path);
end if;
Done := False;
end Add_File;
begin
Iterate_Files_Path (Pattern => Pattern, Path => Path, Process => Add_File'Access);
end Find_Files_Path;
-- ------------------------------
-- Compose an existing path by adding the specified name to each path component
-- and return a new paths having only existing directories. Each directory is
-- separated by ';'.
-- If the composed path exists, it is added to the result path.
-- Example:
-- paths = 'web;regtests' name = 'info'
-- result = 'web/info;regtests/info'
-- Returns the composed path.
-- ------------------------------
function Compose_Path (Paths : in String;
Name : in String) return String is
procedure Compose (Dir : in String;
Done : out Boolean);
Result : Unbounded_String;
-- ------------------------------
-- Build the new path by checking if <b>Name</b> exists in <b>Dir</b>
-- and appending the new path in the <b>Result</b>.
-- ------------------------------
procedure Compose (Dir : in String;
Done : out Boolean) is
use Ada.Directories;
use Ada.Strings.Fixed;
Path : constant String := Util.Files.Compose (Dir, Name);
begin
Done := False;
if Exists (Path) and then Kind (Path) = Directory then
if Length (Result) > 0 then
Append (Result, ';');
end if;
Append (Result, Path);
end if;
exception
when Name_Error =>
null;
end Compose;
begin
Iterate_Path (Path => Paths, Process => Compose'Access);
return To_String (Result);
end Compose_Path;
-- ------------------------------
-- Returns the name of the external file with the specified directory
-- and the name. Unlike the Ada.Directories.Compose, the name can represent
-- a relative path and thus include directory separators.
-- ------------------------------
function Compose (Directory : in String;
Name : in String) return String is
begin
if Name'Length = 0 then
return Directory;
elsif Directory'Length = 0 or Directory = "." or Directory = "./" then
return Name;
elsif Directory (Directory'Last) = '/' and Name (Name'First) = '/' then
return Directory & Name (Name'First + 1 .. Name'Last);
elsif Directory (Directory'Last) = '/' or Name (Name'First) = '/' then
return Directory & Name;
else
return Directory & "/" & Name;
end if;
end Compose;
-- ------------------------------
-- Returns a relative path whose origin is defined by <b>From</b> and which refers
-- to the absolute path referenced by <b>To</b>. Both <b>From</b> and <b>To</b> are
-- assumed to be absolute pathes. Returns the absolute path <b>To</b> if the relative
-- path could not be found. Both paths must have at least one root component in common.
-- ------------------------------
function Get_Relative_Path (From : in String;
To : in String) return String is
Result : Unbounded_String;
Last : Natural := 0;
begin
for I in From'Range loop
if I > To'Last or else From (I) /= To (I) then
-- Nothing in common, return the absolute path <b>To</b>.
if Last <= From'First + 1 then
return To;
end if;
for J in Last .. From'Last - 1 loop
if From (J) = '/' or From (J) = '\' then
Append (Result, "../");
end if;
end loop;
if Last <= To'Last and From (I) /= '/' and From (I) /= '\' then
Append (Result, "../");
Append (Result, To (Last .. To'Last));
end if;
return To_String (Result);
elsif I < From'Last and then (From (I) = '/' or From (I) = '\') then
Last := I + 1;
end if;
end loop;
if To'Last = From'Last or (To'Last = From'Last + 1
and (To (To'Last) = '/' or To (To'Last) = '\')) then
return ".";
elsif Last = 0 then
return To;
elsif To (From'Last + 1) = '/' or To (From'Last + 1) = '\' then
return To (From'Last + 2 .. To'Last);
else
return To (Last .. To'Last);
end if;
end Get_Relative_Path;
end Util.Files;
|
Use the string tokenizer to iterate over the search paths
|
Use the string tokenizer to iterate over the search paths
|
Ada
|
apache-2.0
|
Letractively/ada-util,flottokarotto/ada-util,Letractively/ada-util,flottokarotto/ada-util
|
a9b9ec5ac53d31c90ec7a5c3c6d5db5d6456ef4c
|
src/asis/a4g-a_debug.ads
|
src/asis/a4g-a_debug.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . A _ D E B U G --
-- --
-- S p e c --
-- --
-- Copyright (C) 1995-2012, Free Software Foundation, Inc. --
-- --
-- ASIS-for-GNAT is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 2, or (at your option) any later --
-- version. ASIS-for-GNAT is distributed in the hope that it will be use- --
-- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- --
-- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General --
-- Public License for more details. You should have received a copy of the --
-- GNU General Public License distributed with ASIS-for-GNAT; see file --
-- COPYING. If not, write to the Free Software Foundation, 59 Temple Place --
-- - Suite 330, Boston, MA 02111-1307, USA. --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the --
-- Software Engineering Laboratory of the Swiss Federal Institute of --
-- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the --
-- Scientific Research Computer Center of Moscow State University (SRCC --
-- MSU), Russia, with funding partially provided by grants from the Swiss --
-- National Science Foundation and the Swiss Academy of Engineering --
-- Sciences. ASIS-for-GNAT is now maintained by Ada Core Technologies Inc --
-- (http://www.gnat.com). --
-- --
------------------------------------------------------------------------------
package A4G.A_Debug is
-- This package contains global flags used to control the inclusion
-- of debugging code in various phases of the ASIS-for-GNAT. It is
-- an almost complete analog of the GNAT Debug package
-------------------------
-- Dynamic Debug Flags --
-------------------------
-- Thirty six flags that can be used to activate various specialized
-- debugging output information. The flags are preset to False, which
-- corresponds to the given output being suppressed. The individual
-- flags can be turned on using the undocumented switch /dxxx where
-- xxx is a string of letters for flags to be turned on. Documentation
-- on the current usage of these flags is contained in the body of Debug
-- rather than the spec, so that we don't have to recompile the world
-- when a new debug flag is added
Debug_Flag_A : Boolean := False;
Debug_Flag_B : Boolean := False;
Debug_Flag_C : Boolean := False;
Debug_Flag_D : Boolean := False;
Debug_Flag_E : Boolean := False;
Debug_Flag_F : Boolean := False;
Debug_Flag_G : Boolean := False;
Debug_Flag_H : Boolean := False;
Debug_Flag_I : Boolean := False;
Debug_Flag_J : Boolean := False;
Debug_Flag_K : Boolean := False;
Debug_Flag_L : Boolean := False;
Debug_Flag_M : Boolean := False;
Debug_Flag_N : Boolean := False;
Debug_Flag_O : Boolean := False;
Debug_Flag_P : Boolean := False;
Debug_Flag_Q : Boolean := False;
Debug_Flag_R : Boolean := False;
Debug_Flag_S : Boolean := False;
Debug_Flag_T : Boolean := False;
Debug_Flag_U : Boolean := False;
Debug_Flag_V : Boolean := False;
Debug_Flag_W : Boolean := False;
Debug_Flag_X : Boolean := False;
Debug_Flag_Y : Boolean := False;
Debug_Flag_Z : Boolean := False;
Debug_Flag_1 : Boolean := False;
Debug_Flag_2 : Boolean := False;
Debug_Flag_3 : Boolean := False;
Debug_Flag_4 : Boolean := False;
Debug_Flag_5 : Boolean := False;
Debug_Flag_6 : Boolean := False;
Debug_Flag_7 : Boolean := False;
Debug_Flag_8 : Boolean := False;
Debug_Flag_9 : Boolean := False;
procedure Set_Debug_Flag (C : Character; Val : Boolean := True);
-- Where C is 0-9 or a-z, sets the corresponding debug flag to the
-- given value. In the checks off version of debug, the call to
-- Set_Debug_Flag is always a null operation.
procedure Set_Off;
-- Sets all the debug flags OFF (except Debug_Lib_Model for now),
-- is to be called by Asis_Environment.Finalize
procedure Set_On; -- TEMPORARY SOLUTION!!!
-- Sets all the debug flags ON.
------------------------
-- TEMPORARY SOLUTION --
------------------------
Debug_Mode : Boolean := False;
-- Flag indicating if the debugging information should be output by the
-- routines from the A4G.A_Output package
Debug_Lib_Model : Boolean := False;
-- Flag forcing the debug output of the tables implementing the ASIS
-- Context Model to be performed when finalizing the ASIS Environment.
-- Currently should be set by hand. The debug output is produced only if
-- Debug_Mode is set ON.
end A4G.A_Debug;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
|
6ad177a13e7fc74f95eadb9f63f4f3fc96fb30d0
|
mat/src/mat-formats.adb
|
mat/src/mat-formats.adb
|
-----------------------------------------------------------------------
-- mat-formats - Format various types for the console or GUI interface
-- 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 MAT.Formats is
-- ------------------------------
-- Format the address into a string.
-- ------------------------------
function Addr (Value : in MAT.Types.Target_Addr) return String is
Hex : constant String := MAT.Types.Hex_Image (Value);
begin
return Hex;
end Addr;
end MAT.Formats;
|
Implement the Addr function
|
Implement the Addr function
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
|
5c01c8e25205f01ed358d63239670426b69b0400
|
src/security-auth-oauth-googleplus.adb
|
src/security-auth-oauth-googleplus.adb
|
-----------------------------------------------------------------------
-- security-auth-oauth-googleplus -- Google+ 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 Util.Log.Loggers;
with Security.OAuth.JWT;
package body Security.Auth.OAuth.Googleplus is
use Util.Log;
Log : constant Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth.OAuth.Googleplus");
-- ------------------------------
-- 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) is
pragma Unreferenced (Assoc, Request);
begin
-- The token returned by Google+ must contain an id_token.
if not (Token.all in Security.OAuth.Clients.OpenID_Token'Class) then
Log.Warn ("Invalid token instance created: missing the id_token");
Set_Result (Result, INVALID_SIGNATURE, "invalid access token returned");
return;
end if;
-- The id_token is a JWT token that must be decoded and verified.
-- See https://developers.google.com/accounts/docs/OAuth2Login#validatingtoken
-- It contains information to identify the user.
declare
T : constant Security.OAuth.Clients.OpenID_Token_Access :=
Security.OAuth.Clients.OpenID_Token'Class (Token.all)'Access;
Info : constant Security.OAuth.JWT.Token := Security.OAuth.JWT.Decode (T.Get_Id_Token);
begin
-- Verify that the JWT token concerns our application.
if Security.OAuth.JWT.Get_Audience (Info) /= Realm.App.Get_Application_Identifier then
Set_Result (Result, INVALID_SIGNATURE,
"the access token was granted for another application");
return;
-- Verify that the issuer is Google+
elsif Security.OAuth.JWT.Get_Issuer (Info) /= Realm.Issuer then
Set_Result (Result, INVALID_SIGNATURE,
"the access token was not generated by the expected authority");
return;
end if;
Result.Identity := To_Unbounded_String ("https://accounts.google.com/");
Append (Result.Identity, Security.OAuth.JWT.Get_Subject (Info));
Result.Claimed_Id := Result.Identity;
-- The email is optional and depends on the scope.
Result.Email := To_Unbounded_String (Security.OAuth.JWT.Get_Claim (Info, "email", ""));
Set_Result (Result, AUTHENTICATED, "authenticated");
end;
end Verify_Access_Token;
end Security.Auth.OAuth.Googleplus;
|
Implement the support for Google+
|
Implement the support for Google+
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
|
ab817d47e9392cdaa4b8a7176ea1335ddb361a82
|
src/asis/a4g-gnat_int.adb
|
src/asis/a4g-gnat_int.adb
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . G N A T _ I N T --
-- --
-- B o d y --
-- --
-- Copyright (C) 1995-2012, Free Software Foundation, Inc. --
-- --
-- ASIS-for-GNAT is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 2, or (at your option) any later --
-- version. ASIS-for-GNAT is distributed in the hope that it will be use- --
-- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- --
-- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General --
-- Public License for more details. You should have received a copy of the --
-- GNU General Public License distributed with ASIS-for-GNAT; see file --
-- COPYING. If not, write to the Free Software Foundation, 51 Franklin --
-- Street, Fifth Floor, Boston, MA 02110-1301, USA. --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the --
-- Software Engineering Laboratory of the Swiss Federal Institute of --
-- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the --
-- Scientific Research Computer Center of Moscow State University (SRCC --
-- MSU), Russia, with funding partially provided by grants from the Swiss --
-- National Science Foundation and the Swiss Academy of Engineering --
-- Sciences. ASIS-for-GNAT is now maintained by AdaCore --
-- (http://www.adacore.com). --
-- --
------------------------------------------------------------------------------
with Ada.Exceptions;
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
with Ada.Text_IO; use Ada.Text_IO;
with GNAT.Directory_Operations; use GNAT.Directory_Operations;
with Asis.Errors;
with Asis.Exceptions; use Asis.Exceptions;
with Asis.Extensions; use Asis.Extensions;
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.Vcheck; use A4G.Vcheck;
with Aspects;
with Atree;
with Csets;
with Elists;
with Fname;
with Gnatvsn;
with Lib;
with Namet;
with Nlists;
with Opt; use Opt;
with Repinfo;
with Sem_Aux;
with Sinput;
with Stand;
with Stringt;
with Uintp;
with Urealp;
with Tree_IO;
package body A4G.GNAT_Int is
LT : String renames ASIS_Line_Terminator;
Standard_GCC : constant String_Access :=
GNAT.OS_Lib.Locate_Exec_On_Path ("gcc");
-----------------
-- Create_Tree --
-----------------
procedure Create_Tree (Source_File : String_Access;
Context : Context_Id;
Is_Predefined : Boolean;
Success : out Boolean)
is
begin
if Is_Predefined then
Compile (Source_File => Source_File,
Args => (1 => GNAT_Flag),
Success => Success,
GCC => Gcc_To_Call (Context));
else
Compile (Source_File => Source_File,
Args => I_Options (Context),
Success => Success,
GCC => Gcc_To_Call (Context));
end if;
exception
when others =>
Raise_ASIS_Failed ("A4G.GNAT_Int.Create_Tree:" & LT &
" check the path and environment settings for gcc!");
end Create_Tree;
-------------
-- Execute --
-------------
function Execute
(Program : String_Access;
Args : Argument_List;
Compiler_Out : String := "";
Display_Call : Boolean := A4G.A_Debug.Debug_Mode)
return Boolean
is
Success : Boolean;
Return_Code : Integer;
Execute : String_Access := Program;
begin
if Execute = null then
Execute := Standard_GCC;
end if;
if Display_Call then
Put (Standard_Error, Execute.all);
for J in Args'Range loop
Put (Standard_Error, " ");
Put (Standard_Error, Args (J).all);
end loop;
New_Line (Standard_Error);
end if;
if Execute = null then
Ada.Exceptions.Raise_Exception
(Program_Error'Identity,
"A4G.GNAT_Int.Execute: Can not locate program to execute");
end if;
if Compiler_Out /= "" then
GNAT.OS_Lib.Spawn
(Execute.all,
Args,
Compiler_Out,
Success,
Return_Code);
Success := Return_Code = 0;
else
GNAT.OS_Lib.Spawn (Execute.all, Args, Success);
end if;
return Success;
end Execute;
----------------------------------------------
-- General Interfaces between GNAT and ASIS --
----------------------------------------------
function A_Time (T : Time_Stamp_Type) return Time is
Year : Year_Number;
Month : Month_Number;
Day : Day_Number;
Hours : Integer range 0 .. 23;
Minutes : Integer range 0 .. 59;
Seconds : Integer range 0 .. 59;
Day_Time : Day_Duration;
begin
Split_Time_Stamp
(TS => T,
Year => Nat (Year),
Month => Nat (Month),
Day => Nat (Day),
Hour => Nat (Hours),
Minutes => Nat (Minutes),
Seconds => Nat (Seconds));
Day_Time := Duration (Seconds + 60 * Minutes + 3600 * Hours);
return Time_Of (Year, Month, Day, Day_Time);
end A_Time;
--------------------------------
-- Tree_In_With_Version_Check --
--------------------------------
procedure Tree_In_With_Version_Check
(Desc : File_Descriptor;
Cont : Context_Id;
Success : out Boolean)
is
Cont_Mode : constant Context_Mode := Context_Processing_Mode (Cont);
File_Closed : Boolean := False;
ASIS_GNAT_V : constant String := Gnatvsn.Gnat_Version_String;
First_A_Idx : Natural := ASIS_GNAT_V'First;
Last_A_Idx : Natural;
First_T_Idx : Natural;
Last_T_Idx : Natural;
begin
Success := False;
Tree_IO.Tree_Read_Initialize (Desc);
Opt.Tree_Read;
-- GNAT/ASIS version check first
if Tree_ASIS_Version_Number /= Tree_IO.ASIS_Version_Number then
Close (Desc, File_Closed);
Ada.Exceptions.Raise_Exception
(Program_Error'Identity, "Inconsistent versions of GNAT and ASIS");
end if;
-- Check that ASIS Pro uses the tree created by GNAT Pro
First_T_Idx := Tree_Version_String'First;
if ASIS_GNAT_V (First_A_Idx .. First_A_Idx + 2) = "Pro"
and then Tree_Version_String (First_T_Idx .. First_T_Idx + 2) /=
"Pro"
then
Close (Desc, File_Closed);
Ada.Exceptions.Raise_Exception
(Program_Error'Identity, "ASIS Pro can be used with GNAT Pro only");
end if;
if Strong_Version_Check then
-- We check only the dates here!
First_A_Idx :=
Index (Source => ASIS_GNAT_V,
Pattern => "(") + 1;
First_T_Idx :=
Index (Source => Tree_Version_String.all,
Pattern => "(") + 1;
Last_A_Idx := Index (Source => ASIS_GNAT_V,
Pattern => ")") - 1;
if Index (Source => ASIS_GNAT_V, Pattern => "-") /= 0 then
Last_A_Idx := Index (Source => ASIS_GNAT_V,
Pattern => "-") - 1;
end if;
Last_T_Idx := Index (Source => Tree_Version_String.all,
Pattern => ")") - 1;
if Index (Source => Tree_Version_String.all, Pattern => "-") /=
0
then
Last_T_Idx :=
Index (Source => Tree_Version_String.all,
Pattern => "-") - 1;
end if;
if ASIS_GNAT_V (First_A_Idx .. Last_A_Idx) /=
Tree_Version_String (First_T_Idx .. Last_T_Idx)
then
Close (Desc, File_Closed);
Ada.Exceptions.Raise_Exception
(Program_Error'Identity,
"Inconsistent versions of GNAT [" & Tree_Version_String.all &
"] and ASIS [" & ASIS_GNAT_V & ']');
end if;
end if;
-- Check if we are in Ada 2012 mode and need aspects...
-- if Opt.Ada_Version_Config = Ada_2012 then
-- -- For now, reading aspects is protected by the debug '.A' flag
-- Debug.Debug_Flag_Dot_AA := True;
-- end if;
if Operating_Mode /= Check_Semantics then
if Cont_Mode = One_Tree then
-- If in one-tree mode we can not read the only tree we have,
-- there is no reason to continue, so raising an exception
-- is the only choice:
Close (Desc, File_Closed);
-- We did not check File_Closed here, because the fact that the
-- tree is not compile-only seems to be more important for ASIS
Set_Error_Status
(Status => Asis.Errors.Use_Error,
Diagnosis => "Asis.Ada_Environments.Open:"
& ASIS_Line_Terminator
& "tree file "
& Base_Name (A_Name_Buffer (1 .. A_Name_Len))
& " is not compile-only");
raise ASIS_Failed;
elsif Cont_Mode = N_Trees
or else
Cont_Mode = All_Trees
then
-- no need to read the rest of this tree file, but
-- we can continue even if we can not read some trees...
ASIS_Warning
(Message => "Asis.Ada_Environments.Open: "
& ASIS_Line_Terminator
& "tree file "
& Base_Name (A_Name_Buffer (1 .. A_Name_Len))
& " is not compile-only, ignored",
Error => Asis.Errors.Use_Error);
end if;
-- debug stuff...
if (Debug_Flag_O or else
Debug_Lib_Model or else
Debug_Mode)
and then
Cont_Mode /= One_Tree and then
Cont_Mode /= N_Trees
then
Put (Standard_Error, "The tree file ");
Put (Standard_Error, Base_Name (A_Name_Buffer (1 .. A_Name_Len)));
Put (Standard_Error, " is not compile-only");
New_Line (Standard_Error);
end if;
else
Atree.Tree_Read;
Elists.Tree_Read;
Fname.Tree_Read;
Lib.Tree_Read;
Namet.Tree_Read;
Nlists.Tree_Read;
Sem_Aux.Tree_Read;
Sinput.Tree_Read;
Stand.Tree_Read;
Stringt.Tree_Read;
Uintp.Tree_Read;
Urealp.Tree_Read;
Repinfo.Tree_Read;
Aspects.Tree_Read;
Csets.Initialize;
-- debug stuff...
if Debug_Flag_O or else
Debug_Lib_Model or else
Debug_Mode
then
Put (Standard_Error, "The tree file ");
Put (Standard_Error, Base_Name (A_Name_Buffer (1 .. A_Name_Len)));
Put (Standard_Error, " is OK");
New_Line (Standard_Error);
end if;
Success := True;
end if;
Close (Desc, File_Closed);
if not File_Closed then
Raise_ASIS_Failed
(Diagnosis => "Asis.Ada_Environments.Open: " &
"Can not close tree file: " &
Base_Name (A_Name_Buffer (1 .. A_Name_Len)) &
ASIS_Line_Terminator &
"disk is full or file may be used by other program",
Stat => Asis.Errors.Data_Error);
end if;
exception
when Tree_IO.Tree_Format_Error =>
Close (Desc, File_Closed);
Ada.Exceptions.Raise_Exception
(Program_Error'Identity, "Inconsistent versions of GNAT and ASIS");
end Tree_In_With_Version_Check;
end A4G.GNAT_Int;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
7c1b35d9d7f6f7cfa7e937e9a6520f44f50a027a
|
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
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
2106bfdf73852399a3c0767537eacc20fce166ba
|
src/wiki-filters-html.adb
|
src/wiki-filters-html.adb
|
-----------------------------------------------------------------------
-- wiki-filters-html -- Wiki HTML filters
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Wide_Wide_Characters.Handling;
package body Wiki.Filters.Html is
function Tag (Name : in Wide_Wide_String;
Expect : in Wide_Wide_String;
Tag : in Html_Tag_Type) return Html_Tag_Type;
function Need_Close (Tag : in Html_Tag_Type;
Current_Tag : in Html_Tag_Type) return Boolean;
type Tag_Name_Array is array (Html_Tag_Type) of Unbounded_Wide_Wide_String;
No_End_Tag : constant Tag_Boolean_Array :=
(
BASE_TAG => True,
LINK_TAG => True,
META_TAG => True,
IMG_TAG => True,
HR_TAG => True,
BR_TAG => True,
WBR_TAG => True,
INPUT_TAG => True,
KEYGEN_TAG => True,
others => False);
Tag_Omission : constant Tag_Boolean_Array :=
(
-- Section 4.4 Grouping content
LI_TAG => True,
DT_TAG => True,
DD_TAG => True,
-- Section 4.5 Text-level semantics
RB_TAG => True,
RT_TAG => True,
RTC_TAG => True,
RP_TAG => True,
-- Section 4.9 Tabular data
TH_TAG => True,
TD_TAG => True,
TR_TAG => True,
TBODY_TAG => True,
THEAD_TAG => True,
TFOOT_TAG => True,
OPTGROUP_TAG => True,
OPTION_TAG => True,
others => False);
Tag_Names : constant Tag_Name_Array
:= (
B_TAG => To_Unbounded_Wide_Wide_String ("b"),
I_TAG => To_Unbounded_Wide_Wide_String ("i"),
U_TAG => To_Unbounded_Wide_Wide_String ("u"),
IMG_TAG => To_Unbounded_Wide_Wide_String ("img"),
HR_TAG => To_Unbounded_Wide_Wide_String ("hr"),
BR_TAG => To_Unbounded_Wide_Wide_String ("br"),
SPAN_TAG => To_Unbounded_Wide_Wide_String ("span"),
DL_TAG => To_Unbounded_Wide_Wide_String ("dl"),
DT_TAG => To_Unbounded_Wide_Wide_String ("dt"),
DD_TAG => To_Unbounded_Wide_Wide_String ("dd"),
TABLE_TAG => To_Unbounded_Wide_Wide_String ("table"),
TBODY_TAG => To_Unbounded_Wide_Wide_String ("tbody"),
THEAD_TAG => To_Unbounded_Wide_Wide_String ("thead"),
TFOOT_TAG => To_Unbounded_Wide_Wide_String ("tfoot"),
TH_TAG => To_Unbounded_Wide_Wide_String ("th"),
TR_TAG => To_Unbounded_Wide_Wide_String ("tr"),
TD_TAG => To_Unbounded_Wide_Wide_String ("td"),
others => Null_Unbounded_Wide_Wide_String);
function Tag (Name : in Wide_Wide_String;
Expect : in Wide_Wide_String;
Tag : in Html_Tag_Type) return Html_Tag_Type is
begin
if Ada.Wide_Wide_Characters.Handling.To_Lower (Name) = Expect then
return Tag;
else
return UNKNOWN_TAG;
end if;
end Tag;
-- ------------------------------
-- Find the tag from the tag name.
-- ------------------------------
function Find_Tag (Name : in Wide_Wide_String) return Html_Tag_Type is
begin
-- The list of possible tags is well known and will not change very often.
-- The tag lookup is implemented to be efficient with 2 or 3 embedded cases that
-- reduce the comparison to the minimum. The result is a large case statement that
-- becomes unreadable.
case Name'Length is
when 0 =>
return UNKNOWN_TAG;
when 1 =>
case Name (Name'First) is
when 'a' | 'A' =>
return A_TAG;
when 'b' | 'B' =>
return B_TAG;
when 'i' | 'I' =>
return I_TAG;
when 'p' | 'P' =>
return P_TAG;
when 'q' | 'Q' =>
return Q_TAG;
when 's' | 'S' =>
return S_TAG;
when 'u' | 'U' =>
return U_TAG;
when others =>
return UNKNOWN_TAG;
end case;
when 2 =>
case Name (Name'First) is
when 'b' | 'B' =>
case Name (Name'Last) is
when 'r' | 'R' =>
return BR_TAG;
when others =>
return UNKNOWN_TAG;
end case;
when 'd' | 'D' =>
case Name (Name'Last) is
when 'l' | 'L' =>
return DL_TAG;
when 't' | 'T' =>
return DT_TAG;
when 'd' | 'D' =>
return DD_TAG;
when others =>
return UNKNOWN_TAG;
end case;
when 'e' | 'E' =>
case Name (Name'Last) is
when 'm' | 'M' =>
return EM_TAG;
when others =>
return UNKNOWN_TAG;
end case;
when 'h' | 'H' =>
case Name (Name'Last) is
when '1' =>
return H1_TAG;
when '2' =>
return H2_TAG;
when '3' =>
return H3_TAG;
when '4' =>
return H4_TAG;
when '5' =>
return H5_TAG;
when '6' =>
return H6_TAG;
when 'r' | 'R' =>
return HR_TAG;
when others =>
return UNKNOWN_TAG;
end case;
when 'l' | 'L' =>
case Name (Name'Last) is
when 'i' | 'I' =>
return LI_TAG;
when others =>
return UNKNOWN_TAG;
end case;
when 'o' | 'O' =>
case Name (Name'Last) is
when 'l' | 'L' =>
return OL_TAG;
when others =>
return UNKNOWN_TAG;
end case;
when 'r' | 'R' =>
case Name (Name'Last) is
when 'b' | 'B' =>
return RB_TAG;
when 'p' | 'P' =>
return RP_TAG;
when 't' | 'T' =>
return RT_TAG;
when others =>
return UNKNOWN_TAG;
end case;
when 't' | 'T' =>
case Name (Name'Last) is
when 'r' | 'R' =>
return TR_TAG;
when 'd' | 'D' =>
return TD_TAG;
when 'h' | 'H' =>
return TH_TAG;
when others =>
return UNKNOWN_TAG;
end case;
when 'u' | 'U' =>
case Name (Name'Last) is
when 'l' | 'L' =>
return UL_TAG;
when others =>
return UNKNOWN_TAG;
end case;
when others =>
return UNKNOWN_TAG;
end case;
when 3 =>
case Name (Name'First) is
when 'b' | 'B' =>
case Name (Name'Last) is
when 'i' | 'I' =>
return Tag (Name, "bdi", BDI_TAG);
when 'o' | 'O' =>
return Tag (Name, "bdo", BDO_TAG);
when others =>
return UNKNOWN_TAG;
end case;
when 'c' | 'C' =>
return Tag (Name, "col", COL_TAG);
when 'd' | 'D' =>
case Name (Name'First + 1) is
when 'i' | 'I' =>
return Tag (Name, "div", DIV_TAG);
when 'f' | 'F' =>
return Tag (Name, "dfn", DFN_TAG);
when 'e' | 'E' =>
return Tag (Name, "del", DEL_TAG);
when others =>
return UNKNOWN_TAG;
end case;
when 'i' | 'I' =>
case Name (Name'Last) is
when 'g' | 'G' =>
return Tag (Name, "img", IMG_TAG);
when 's' | 'S' =>
return Tag (Name, "ins", INS_TAG);
when others =>
return UNKNOWN_TAG;
end case;
when 'k' | 'K' =>
return Tag (Name, "kbd", KBD_TAG);
when 'm' | 'M' =>
return Tag (Name, "map", MAP_TAG);
when 'n' | 'N' =>
return Tag (Name, "nav", NAV_TAG);
when 'p' | 'P' =>
return Tag (Name, "pre", PRE_TAG);
when 'r' | 'R' =>
return Tag (Name, "rtc", RTC_TAG);
when 's' | 'S' =>
case Name (Name'Last) is
when 'b' | 'B' =>
return Tag (Name, "sub", SUB_TAG);
when 'n' | 'N' =>
return SPAN_TAG;
when 'p' | 'P' =>
return Tag (Name, "sup", SUP_TAG);
when others =>
return UNKNOWN_TAG;
end case;
when 'v' | 'V' =>
return Tag (Name, "var", VAR_TAG);
when 'w' | 'W' =>
return Tag (Name, "wbr", WBR_TAG);
when others =>
return UNKNOWN_TAG;
end case;
when 4 =>
case Name (Name'First) is
when 'a' | 'A' =>
case Name (Name'First + 1) is
when 'b' | 'B' =>
return Tag (Name, "abbr", ABBR_TAG);
when 'r' | 'R' =>
return Tag (Name, "area", AREA_TAG);
when others =>
return UNKNOWN_TAG;
end case;
when 'b' | 'B' =>
case Name (Name'First + 1) is
when 'a' | 'A' =>
return Tag (Name, "base", BASE_TAG);
when 'o' | 'O' =>
return Tag (Name, "body", BODY_TAG);
when others =>
return UNKNOWN_TAG;
end case;
when 'c' | 'C' =>
case Name (Name'First + 1) is
when 'i' | 'I' =>
return Tag (Name, "cite", CITE_TAG);
when 'o' | 'O' =>
return Tag (Name, "code", CODE_TAG);
when others =>
return UNKNOWN_TAG;
end case;
when 'd' | 'D' =>
return Tag (Name, "data", DATA_TAG);
when 'f' | 'F' =>
return Tag (Name, "form", FORM_TAG);
when 'h' | 'H' =>
case Name (Name'First + 1) is
when 't' | 'T' =>
return Tag (Name, "html", HTML_TAG);
when 'e' | 'E' =>
return Tag (Name, "head", HEAD_TAG);
when others =>
return UNKNOWN_TAG;
end case;
when 'l' | 'L' =>
return Tag (Name, "link", LINK_TAG);
when 'm' | 'M' =>
case Name (Name'Last) is
when 'a' | 'A' =>
return Tag (Name, "meta", META_TAG);
when 'n' | 'N' =>
return Tag (Name, "main", MAIN_TAG);
when 'k' | 'K' =>
return Tag (Name, "mark", MARK_TAG);
when others =>
return UNKNOWN_TAG;
end case;
when 'r' | 'R' =>
return Tag (Name, "ruby", RUBY_TAG);
when 's' | 'S' =>
case Name (Name'First + 1) is
when 'p' | 'P' =>
return Tag (Name, "span", SPAN_TAG);
when 'a' | 'A' =>
return Tag (Name, "samp", SAMP_TAG);
when others =>
return UNKNOWN_TAG;
end case;
when 't' | 'T' =>
return Tag (Name, "time", TIME_TAG);
when others =>
return UNKNOWN_TAG;
end case;
when 5 =>
case Name (Name'First) is
when 'a' | 'A' =>
case Name (Name'First + 1) is
when 's' | 'S' =>
return Tag (Name, "aside", ASIDE_TAG);
when 'u' | 'U' =>
return Tag (Name, "audio", AUDIO_TAG);
when others =>
return UNKNOWN_TAG;
end case;
when 'e' | 'E' =>
return Tag (Name, "embed", EMBED_TAG);
when 'i' | 'I' =>
return Tag (Name, "input", INPUT_TAG);
when 'l' | 'L' =>
return Tag (Name, "label", LABEL_TAG);
when 'm' | 'M' =>
return Tag (Name, "meter", METER_TAG);
when 'p' | 'P' =>
return Tag (Name, "param", PARAM_TAG);
when 's' | 'S' =>
case Name (Name'First + 1) is
when 't' | 'T' =>
return Tag (Name, "style", STYLE_TAG);
when 'm' | 'M' =>
return Tag (Name, "small", SMALL_TAG);
when others =>
return UNKNOWN_TAG;
end case;
when 't' | 'T' =>
case Name (Name'First + 1) is
when 'i' | 'I' =>
return Tag (Name, "title", TITLE_TAG);
when 'r' | 'R' =>
return Tag (Name, "track", TRACK_TAG);
when 'a' | 'A' =>
return Tag (Name, "table", TABLE_TAG);
when 'b' | 'B' =>
return Tag (Name, "tbody", TBODY_TAG);
when 'h' | 'H' =>
return Tag (Name, "thead", THEAD_TAG);
when 'f' | 'F' =>
return Tag (Name, "tfoot", TFOOT_TAG);
when others =>
return UNKNOWN_TAG;
end case;
when 'v' | 'V' =>
return Tag (Name, "video", VIDEO_TAG);
when others =>
return UNKNOWN_TAG;
end case;
when others =>
case Name (Name'First) is
when 'a' | 'A' =>
case Name (Name'First + 1) is
when 'r' | 'R' =>
return Tag (Name, "article", ARTICLE_TAG);
when 'd' | 'D' =>
return Tag (Name, "address", ADDRESS_TAG);
when others =>
return UNKNOWN_TAG;
end case;
when 'b' | 'B' =>
case Name (Name'First + 1) is
when 'l' | 'L' =>
return Tag (Name, "blockquote", BLOCKQUOTE_TAG);
when 'u' | 'U' =>
return Tag (Name, "button", BUTTON_TAG);
when others =>
return UNKNOWN_TAG;
end case;
when 'c' | 'C' =>
case Name (Name'First + 2) is
when 'p' | 'P' =>
return Tag (Name, "caption", CAPTION_TAG);
when 'l' | 'L' =>
return Tag (Name, "colgroup", COLGROUP_TAG);
when 'n' | 'N' =>
return Tag (Name, "canvas", CANVAS_TAG);
when others =>
return UNKNOWN_TAG;
end case;
when 'd' | 'D' =>
return Tag (Name, "datalist", DATALIST_TAG);
when 'f' | 'F' =>
case Name (Name'Last) is
when 'r' | 'R' =>
return Tag (Name, "footer", FOOTER_TAG);
when 'e' | 'E' =>
return Tag (Name, "figure", FIGURE_TAG);
when 'n' | 'N' =>
return Tag (Name, "figcaption", FIGCAPTION_TAG);
when 't' | 'T' =>
return Tag (Name, "fieldset", FIELDSET_TAG);
when others =>
return UNKNOWN_TAG;
end case;
when 'h' | 'H' =>
return Tag (Name, "header", HEADER_TAG);
when 'i' | 'I' =>
return Tag (Name, "iframe", IFRAME_TAG);
when 'k' | 'K' =>
return Tag (Name, "keygen", KEYGEN_TAG);
when 'l' | 'L' =>
return Tag (Name, "legend", LEGEND_TAG);
when 'n' | 'N' =>
return Tag (Name, "noscript", NOSCRIPT_TAG);
when 'o' | 'O' =>
case Name (Name'First + 3) is
when 'e' | 'E' =>
return Tag (Name, "object", OBJECT_TAG);
when 'g' | 'G' =>
return Tag (Name, "optgroup", OPTGROUP_TAG);
when 'i' | 'I' =>
return Tag (Name, "option", OPTION_TAG);
when 'p' | 'P' =>
return Tag (Name, "output", OUTPUT_TAG);
when others =>
return UNKNOWN_TAG;
end case;
when 'p' | 'P' =>
return Tag (Name, "progress", PROGRESS_TAG);
when 's' | 'S' =>
case Name (Name'First + 3) is
when 't' | 'T' =>
return Tag (Name, "section", SECTION_TAG);
when 'o' | 'O' =>
return Tag (Name, "strong", STRONG_TAG);
when 'r' | 'R' =>
return Tag (Name, "source", SOURCE_TAG);
when 'e' | 'E' =>
return Tag (Name, "select", SELECT_TAG);
when 'i' | 'I' =>
return Tag (Name, "script", SCRIPT_TAG);
when others =>
return UNKNOWN_TAG;
end case;
when 't' | 'T' =>
case Name (Name'Last) is
when 'a' | 'A' =>
return Tag (Name, "textarea", TEXTAREA_TAG);
when 'e' | 'E' =>
return Tag (Name, "template", TEMPLATE_TAG);
when others =>
return UNKNOWN_TAG;
end case;
when others =>
return UNKNOWN_TAG;
end case;
end case;
end Find_Tag;
-- Add a text block with the given format.
overriding
procedure Add_Text (Document : in out Html_Filter_Type;
Text : in Unbounded_Wide_Wide_String;
Format : in Wiki.Documents.Format_Map) is
begin
if not Document.Stack.Is_Empty then
declare
Current_Tag : constant Html_Tag_Type := Document.Stack.Last_Element;
begin
if No_End_Tag (Current_Tag) then
Filter_Type (Document).End_Element (Tag_Names (Current_Tag));
Document.Stack.Delete_Last;
end if;
end;
end if;
Filter_Type (Document).Add_Text (Text, Format);
end Add_Text;
-- Add a link.
overriding
procedure Add_Link (Document : in out Html_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
if Document.Allowed (A_TAG) then
Filter_Type (Document).Add_Link (Name, Link, Language, Title);
end if;
end Add_Link;
-- Add an image.
overriding
procedure Add_Image (Document : in out Html_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
if Document.Allowed (IMG_TAG) then
Filter_Type (Document).Add_Image (Link, Alt, Position, Description);
end if;
end Add_Image;
-- ------------------------------
-- Given the current tag on the top of the stack and the new tag that will be pushed,
-- decide whether the current tag must be closed or not.
-- Returns True if the current tag must be closed.
-- ------------------------------
function Need_Close (Tag : in Html_Tag_Type;
Current_Tag : in Html_Tag_Type) return Boolean is
begin
if No_End_Tag (Current_Tag) then
return True;
elsif Current_Tag = Tag and Tag_Omission (Current_Tag) then
return True;
else
case Current_Tag is
when DT_TAG | DD_TAG =>
return Tag = DD_TAG or Tag = DL_TAG or Tag = DT_TAG;
when TD_TAG =>
return Tag = TD_TAG or Tag = TR_TAG or Tag = TH_TAG;
when TR_TAG =>
return False;
when others =>
return False;
end case;
end if;
end Need_Close;
overriding
procedure Start_Element (Document : in out Html_Filter_Type;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Wiki.Attributes.Attribute_List_Type) is
Tag : constant Html_Tag_Type := Find_Tag (To_Wide_Wide_String (Name));
Current_Tag : Html_Tag_Type;
begin
if not Document.Allowed (Tag) then
return;
end if;
while not Document.Stack.Is_Empty loop
Current_Tag := Document.Stack.Last_Element;
if Need_Close (Tag, Current_Tag) then
Filter_Type (Document).End_Element (Tag_Names (Current_Tag));
Document.Stack.Delete_Last;
end if;
exit when not No_End_Tag (Current_Tag);
end loop;
Document.Stack.Append (Tag);
Filter_Type (Document).Start_Element (Name, Attributes);
end Start_Element;
overriding
procedure End_Element (Document : in out Html_Filter_Type;
Name : in Unbounded_Wide_Wide_String) is
Tag : constant Html_Tag_Type := Find_Tag (To_Wide_Wide_String (Name));
begin
if not Document.Allowed (Tag) or else Document.Stack.Is_Empty then
return;
end if;
Document.Stack.Delete_Last;
Filter_Type (Document).End_Element (Name);
end End_Element;
-- ------------------------------
-- Flush the HTML element that have not yet been closed.
-- ------------------------------
procedure Flush_Stack (Document : in out Html_Filter_Type) is
begin
while not Document.Stack.Is_Empty loop
declare
Tag : constant Html_Tag_Type := Document.Stack.Last_Element;
begin
Filter_Type (Document).End_Element (Tag_Names (Tag));
end;
Document.Stack.Delete_Last;
end loop;
end Flush_Stack;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Document : in out Html_Filter_Type) is
begin
Document.Flush_Stack;
Filter_Type (Document).Finish;
end Finish;
-- ------------------------------
-- Mark the HTML tag as being forbidden.
-- ------------------------------
procedure Forbidden (Filter : in out Html_Filter_Type;
Tag : in Html_Tag_Type) is
begin
Filter.Allowed (Tag) := False;
end Forbidden;
-- ------------------------------
-- Mark the HTML tag as being allowed.
-- ------------------------------
procedure Allowed (Filter : in out Html_Filter_Type;
Tag : in Html_Tag_Type) is
begin
Filter.Allowed (Tag) := True;
end Allowed;
end Wiki.Filters.Html;
|
Implement the HTML filter to block some HTML, do some corrections on HTML
|
Implement the HTML filter to block some HTML, do some corrections on HTML
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
|
445b07f051506701b37da73a41ce580b14f7f577
|
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
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
|
84123815e19f71efe25504cfcbad0e4f6f9a9543
|
regtests/ado-datasets-tests.adb
|
regtests/ado-datasets-tests.adb
|
-----------------------------------------------------------------------
-- ado-datasets-tests -- Test executing queries and using 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.Test_Caller;
with Util.Properties;
with Regtests.Simple.Model;
with ADO.Queries.Loaders;
package body ADO.Datasets.Tests is
package Caller is new Util.Test_Caller (Test, "ADO.Datasets");
package User_List_Query_File is
new ADO.Queries.Loaders.File (Path => "regtests/files/user-list.xml",
Sha1 => "");
package User_List_Query is
new ADO.Queries.Loaders.Query (Name => "user-list",
File => User_List_Query_File.File'Access);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Datasets.List",
Test_List'Access);
end Add_Tests;
procedure Test_List (T : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Query : ADO.Queries.Context;
Data : ADO.Datasets.Dataset;
Props : constant Util.Properties.Manager := Util.Tests.Get_Properties;
begin
-- Configure the XML query loader.
ADO.Queries.Loaders.Initialize (Props.Get ("ado.queries.paths", ".;db"),
Props.Get ("ado.queries.load", "false") = "true");
for I in 1 .. 100 loop
declare
User : Regtests.Simple.Model.User_Ref;
begin
User.Set_Name ("John " & Integer'Image (I));
User.Set_Select_Name ("test-list");
User.Set_Value (ADO.Identifier (I));
User.Save (DB);
end;
end loop;
DB.Commit;
Query.Set_Query (User_List_Query.Query'Access);
Query.Bind_Param ("filter", String '("test-list"));
ADO.Datasets.List (Data, DB, Query);
Util.Tests.Assert_Equals (T, 100, Data.Get_Count, "Invalid dataset size");
end Test_List;
end ADO.Datasets.Tests;
|
Implement the unit test on datasets
|
Implement the unit test on datasets
|
Ada
|
apache-2.0
|
Letractively/ada-ado
|
|
78869b453f34cf15c130da772172364e7da7241f
|
src/asis/a4g-get_unit.ads
|
src/asis/a4g-get_unit.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . G E T _ U N I T --
-- --
-- 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, 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 A4G.A_Types; use A4G.A_Types;
package A4G.Get_Unit is
-- !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-- !! !!
-- !! This package should be completely revised (and very likely - !!
-- !! removed), when migration to using pre-created trees as to the !!
-- !! *ONLY* ASIS operation mode is completed !!
-- !! !!
-- !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-- This paskage contains routines for obtaining ASIS Compilation Units
-- according to the requests arosen during processing the queries from
-- Asis.Compilation_Units package which get Units and Unit Lists from an
-- ASIS Context. As the first step, these routines try to find the
-- reqiested unit(s) by making the corresponding search among Units
-- which are already known to ASIS by looking for the Units in the internal
-- tables implementing the ASIS Context Model. If this first step does not
-- give the required resuil, the attempt to fing the Unit(s) by processing
-- the Ada sources or pre-created tree output files is undertaken. To obtain
-- information about the Unit which has never been known to ASIS, ASIS has,
-- depending on the options set for a context, either to compile it "on the
-- fly" in order to check its correctness and to produce the tree output
-- file, if the Unit is correct, or to try to locate the pre-created tree
-- output file; then the tree output file has to be read in and analysed.
-- If the tree contains the subtrees for other Ada units which have not
-- been known to ASIS so far, ASIS stores the information about these units
-- in its internal tables (even the ASIS query being processed has no
-- relation to these units).
-----------------
-- Subprograms --
-----------------
function Get_One_Unit
(Name : Wide_String;
Context : Context_Id;
Spec : Boolean)
return Unit_Id;
-- This function defines the top-level control flow for the two
-- functions from the Asis_Compilation_Unit package which yields
-- one ASIS Compilation Unit: Library_Unit_Declaration and
-- Compilation_Unit_Body. Spec is used to make the diffference
-- between these two functions: it is set True for
-- Library_Unit_Declaration and False for Compilation_Unit_Body.
function Fetch_Unit_By_Ada_Name
(Name : String;
Norm_Name : String;
Context : Context_Id;
Spec : Boolean)
return Unit_Id;
-- This function is supposed to be called in the following situation:
--
-- - Name is non-empty string which can be interpreted as an Ada unit
-- name;
--
-- - Norm_Name is non-empty string representing the normalised version
-- of the Ada unit name passed as the actual for Name. This means
-- that Norm_Name'Legth = Name'Length + 2, and Norm_name ends with
-- "%s" or "%b" DEPENDING ON THE VALUE OF SPEC;
--
-- The Context parameter indicates the ASIS Context to look for a Unit
-- indicated by Name and Norm_Name. Spec indicates whether the library
-- unit declaration or the compilation unit body should be fetched
-- (See the documentation for the functions Library_Unit_Declaration
-- and Compilation_Unit_Body from the Asis_Compilation_Units package
-- for the definition of the ASIS meaning of "library unit declaration"
-- and "compilation unit body").
--
-- This function returns the Unit_Id value indicating the desired
-- Unit. Nil_Unit is returned if Context does not contain the -- ##
-- Unit having Name as its unit name.
--
-- If ASIS already knows this Unit, the returned Unit_Id value
-- points to some pre-existing entry in the Unit Table for the given
-- Context. Otherwise ASIS tries to compile Unit from its cource.
-- If the compilation is successful, ASIS retrieves the newly
-- created tree and it obtains and stores in the Unit Table
-- information about the Unit AND ABOUT ALL IS SUPPORTERS, WHICH
-- ARE NOT KNOWN TO ASIS!
--
-- !!! THIS FUNCTION SHOULD ANALYZE EXISTING TREES BEFORE TRYING
-- !!! TO CREATE THE NEW TREE, THIS IS NOT IMPLEMENTED YET
--
-- IMPLEMENTATION LIMITATION : if the file name of an Ada unit is
-- defined by the Source_File_Name pragma, ASIS cannot call GNAT
-- to compile this unit!
function Get_Main_Unit_Tree_On_The_Fly
(Start_Unit : Unit_Id;
Cont : Context_Id;
Spec : Boolean)
return Unit_Id;
-- This function is supposed to be used for the Incremental Context mode
-- only. It purpose is to try to create the main tree for Start_Unit
-- (if Spec is set ON) or for the body of Start_Unit (if Spec is set OFF).
-- If the tree is successfully created, this function returns either
-- Start_From or the Id of the body of Start_From respectively, otherwise
-- Nil_Unit is returned.
--
-- If this function creates the new tree, this tree is added to the set
-- of trees making up the current incremental context, and this tree
-- becomes the tree currently accessed by ASIS.
--
-- This function is supposed to be called with Start_Unit representing
-- some spec unit in the Cont. It is also supposed that the tree which
-- should be created by the call does not exist in Cont. The caller is
-- responsible to insure these conditions.
-- condition
end A4G.Get_Unit;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
c6f598c0f5ea910831146d2938fceebd9d03bf15
|
awa/plugins/awa-questions/regtests/awa-questions-tests.adb
|
awa/plugins/awa-questions/regtests/awa-questions-tests.adb
|
-----------------------------------------------------------------------
-- awa-questions-tests -- Unit tests for questions module
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Strings;
with Servlet.Streams;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Tests;
with AWA.Tests.Helpers.Users;
package body AWA.Questions.Tests is
use Ada.Strings.Unbounded;
use AWA.Tests;
package Caller is new Util.Test_Caller (Test, "Questions");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Questions.Beans.Load_List (Anonymous)",
Test_Anonymous_Access'Access);
Caller.Add_Test (Suite, "Test AWA.Questions.Beans.Save",
Test_Create_Question'Access);
Caller.Add_Test (Suite, "Test AWA.Questions.Beans.Load (missing)",
Test_Missing_Page'Access);
end Add_Tests;
-- ------------------------------
-- Get some access on the wiki as anonymous users.
-- ------------------------------
procedure Verify_Anonymous (T : in out Test;
Page : in String;
Title : in String) is
function Get_Link (Title : in String) return String;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
function Get_Link (Title : in String) return String is
Stream : Servlet.Streams.Print_Stream := Reply.Get_Output_Stream;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Reply.Read_Content (Content);
Stream.Write (Content);
return AWA.Tests.Helpers.Extract_Link (To_String (Content), Title);
end Get_Link;
begin
ASF.Tests.Do_Get (Request, Reply, "/questions/list.html",
"question-list.html");
ASF.Tests.Assert_Contains (T, "<title>Questions</title>", Reply,
"Questions list page is invalid");
ASF.Tests.Do_Get (Request, Reply, "/questions/tags/tag",
"question-list-tagged.html");
ASF.Tests.Assert_Contains (T, "<title>Questions</title>", Reply,
"Questions tag page is invalid");
if Page'Length > 0 then
ASF.Tests.Do_Get (Request, Reply, "/questions/view/" & Page,
"question-page-" & Page & ".html");
ASF.Tests.Assert_Contains (T, Title, Reply,
"Question page " & Page & " is invalid");
ASF.Tests.Assert_Contains (T, "<h2>" & Title & "</h2>", Reply,
"Question page " & Page & " is invalid");
ASF.Tests.Assert_Matches (T, ".input type=.hidden. name=.question-id. "
& "value=.[0-9]+. id=.question-id.../input", Reply,
"Question page " & Page & " is invalid");
end if;
end Verify_Anonymous;
-- ------------------------------
-- Verify that the question list contains the given question.
-- ------------------------------
procedure Verify_List_Contains (T : in out Test;
Id : in String;
Title : in String) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/questions/list.html",
"question-list-recent.html");
ASF.Tests.Assert_Contains (T, "Questions", Reply,
"List of questions page is invalid");
ASF.Tests.Assert_Contains (T, "/questions/view/" & Id, Reply,
"List of questions page does not reference the page");
ASF.Tests.Assert_Contains (T, Title, Reply,
"List of questions page does not contain the question");
end Verify_List_Contains;
-- ------------------------------
-- Test access to the question as anonymous user.
-- ------------------------------
procedure Test_Anonymous_Access (T : in out Test) is
begin
T.Verify_Anonymous ("", "");
end Test_Anonymous_Access;
-- ------------------------------
-- Test creation of question by simulating web requests.
-- ------------------------------
procedure Test_Create_Question (T : in out Test) is
procedure Create_Question (Title : in String);
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Uuid : constant String := Util.Tests.Get_Uuid;
procedure Create_Question (Title : in String) is
begin
Request.Set_Parameter ("post", "1");
Request.Set_Parameter ("title", Title);
Request.Set_Parameter ("text", "# Main title" & ASCII.LF
& "* The question content." & ASCII.LF
& "* Second item." & ASCII.LF);
Request.Set_Parameter ("save", "1");
ASF.Tests.Do_Post (Request, Reply, "/questions/ask.html", "questions-ask.html");
T.Question_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/questions/view/");
Util.Tests.Assert_Matches (T, "[0-9]+$", To_String (T.Question_Ident),
"Invalid redirect after question creation");
-- Remove the 'question' bean from the request so that we get a new instance
-- for the next call.
Request.Remove_Attribute ("question");
end Create_Question;
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
Create_Question ("Question 1 page title1");
T.Verify_List_Contains (To_String (T.Question_Ident), "Question 1 page title1");
T.Verify_Anonymous (To_String (T.Question_Ident), "Question 1 page title1");
Create_Question ("Question 2 page title2");
T.Verify_List_Contains (To_String (T.Question_Ident), "Question 2 page title2");
T.Verify_Anonymous (To_String (T.Question_Ident), "Question 2 page title2");
Create_Question ("Question 3 page title3");
T.Verify_List_Contains (To_String (T.Question_Ident), "Question 3 page title3");
T.Verify_Anonymous (To_String (T.Question_Ident), "Question 3 page title3");
end Test_Create_Question;
-- ------------------------------
-- Test getting a wiki page which does not exist.
-- ------------------------------
procedure Test_Missing_Page (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/questions/view.html?id=12345678",
"question-page-missing.html");
ASF.Tests.Assert_Matches (T, "<title>Question not found</title>", Reply,
"Question page title '12345678' is invalid",
ASF.Responses.SC_NOT_FOUND);
ASF.Tests.Assert_Matches (T, "question.*removed", Reply,
"Question page content '12345678' is invalid",
ASF.Responses.SC_NOT_FOUND);
end Test_Missing_Page;
end AWA.Questions.Tests;
|
Implement new tests for the questions module by simulating web requests
|
Implement new tests for the questions module by simulating web requests
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
|
8100b19dd2b2ab4959f75774ee95064c268bb3d7
|
src/babel-files-queues.adb
|
src/babel-files-queues.adb
|
-----------------------------------------------------------------------
-- babel-files-queues -- File and directory queues
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with Ada.Directories;
with Ada.Containers.Vectors;
with Util.Encoders.SHA1;
with Util.Concurrent.Fifos;
with Util.Strings.Vectors;
with ADO;
with Babel.Base.Models;
package body Babel.Files.Queues is
-- ------------------------------
-- Returns true if there is a directory in the queue.
-- ------------------------------
function Has_Directory (Queue : in Directory_Queue) return Boolean is
begin
return not Queue.Directories.Is_Empty;
end Has_Directory;
-- ------------------------------
-- Get the next directory from the queue.
-- ------------------------------
procedure Peek_Directory (Queue : in out Directory_Queue;
Directory : out Directory_Type) is
begin
Directory := Queue.Directories.Last_Element;
Queue.Directories.Delete_Last;
end Peek_Directory;
end Babel.Files.Queues;
|
Implement the Has_Directory and Peek_Directory operation for the Directory_Queue
|
Implement the Has_Directory and Peek_Directory operation for the Directory_Queue
|
Ada
|
apache-2.0
|
stcarrez/babel
|
|
0bb4059e94ffb218e0e0a218e8705aa13bc0511f
|
src/sys/http/curl/util-http-clients-curl-constants.ads
|
src/sys/http/curl/util-http-clients-curl-constants.ads
|
-- Generated by utildgen.c from system includes
private package Util.Http.Clients.Curl.Constants is
CURLOPT_URL : constant Curl_Option := 10002;
CURLOPT_HTTPGET : constant Curl_Option := 80;
CURLOPT_POST : constant Curl_Option := 47;
CURLOPT_CUSTOMREQUEST : constant Curl_Option := 10036;
CURLOPT_READFUNCTION : constant Curl_Option := 20012;
CURLOPT_WRITEUNCTION : constant Curl_Option := 20011;
CURLOPT_HTTPHEADER : constant Curl_Option := 10023;
CURLOPT_INTERFACE : constant Curl_Option := 10062;
CURLOPT_USERPWD : constant Curl_Option := 10005;
CURLOPT_HTTPAUTH : constant Curl_Option := 107;
CURLOPT_MAXFILESIZE : constant Curl_Option := 114;
CURLOPT_WRITEDATA : constant Curl_Option := 10001;
CURLOPT_HEADER : constant Curl_Option := 42;
CURLOPT_POSTFIELDS : constant Curl_Option := 10015;
CURLOPT_POSTFIELDSIZE : constant Curl_Option := 60;
CURLOPT_CONNECTTIMEOUT : constant Curl_Option := 78;
CURLOPT_TIMEOUT : constant Curl_Option := 13;
CURLINFO_RESPONSE_CODE : constant CURL_Info := 2097154;
end Util.Http.Clients.Curl.Constants;
|
Add Curl.Constants package
|
Add Curl.Constants package
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
|
fb0065f3a78757517efd34e11c09a3b6481df38d
|
src/wiki-helpers-parser.adb
|
src/wiki-helpers-parser.adb
|
-----------------------------------------------------------------------
-- wiki-helpers-parser -- Generic procedure for the wiki parser
-- 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.Helpers;
with Wiki.Streams;
procedure Wiki.Helpers.Parser (Engine : in out Engine_Type;
Content : in Element_Type;
Doc : in out Wiki.Documents.Document) is
use type Wiki.Streams.Input_Stream_Access;
type Wide_Input is new Wiki.Streams.Input_Stream with record
Pos : Positive;
Len : Natural;
end record;
overriding
procedure Read (Buf : in out Wide_Input;
Token : out Wiki.Strings.WChar;
Is_Eof : out Boolean);
procedure Read (Buf : in out Wide_Input;
Token : out Wiki.Strings.WChar;
Is_Eof : out Boolean) is
begin
if Buf.Pos > Buf.Len then
Is_Eof := True;
Token := Wiki.Helpers.CR;
else
Token := Element (Content, Buf.Pos);
Buf.Pos := Buf.Pos + 1;
Is_Eof := False;
end if;
end Read;
Buffer : aliased Wide_Input;
begin
Buffer.Pos := 1;
Buffer.Len := Length (Content);
Parse (Engine, Buffer'Unchecked_Access, Doc);
end Wiki.Helpers.Parser;
|
Implement the generic procedure Wiki.Helpers.Parser to allow easily provide a Parser with various content types
|
Implement the generic procedure Wiki.Helpers.Parser to allow easily
provide a Parser with various content types
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
|
4cb8bf1cae8997eeee3dde138a2579c1e1bd7d80
|
awa/plugins/awa-counters/src/awa-counters-components.ads
|
awa/plugins/awa-counters/src/awa-counters-components.ads
|
-----------------------------------------------------------------------
-- awa-counters-components -- Counter UI component
-- 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.Factory;
with ASF.Contexts.Faces;
with ASF.Components.Html;
-- == Counter Component ==
--
package AWA.Counters.Components is
type UICounter is new ASF.Components.Html.UIHtmlComponent with private;
-- Render the counter component. Starts the DL/DD list and write the input
-- component with the possible associated error message.
overriding
procedure Encode_Begin (UI : in UICounter;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Get the AWA Counter component factory.
function Definition return ASF.Factory.Factory_Bindings_Access;
private
type UICounter is new ASF.Components.Html.UIHtmlComponent with null record;
end AWA.Counters.Components;
|
Change the UICounter to use the UIHtmlComponent base type
|
Change the UICounter to use the UIHtmlComponent base type
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
|
4a1aa56936cf5b0f32f33fd6d51002b0285171db
|
src/asis/a4g-itests.ads
|
src/asis/a4g-itests.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . I T E S 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 tests for defining if an Element based on the
-- given node should test Is_Implicit, Is_Inherited and Is_From_Instance
with Types; use Types;
package A4G.Itests is
function Is_Inherited_Discriminant (N : Node_Id) return Boolean;
-- Tests if N corresponds to the defining occurrence of an inherited
-- discriminant. N should be of N_Defining_Identifier kind
--
-- INCOMPLETE and INRELIABLE for now!
function Is_From_Instance (N : Node_Id) return Boolean;
-- Tests if N corresponds to an implicit or explicit construction from
-- the result of some generic instantiation (that is, from an expanded
-- generic template)
end A4G.Itests;
|
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
|
|
7e3bb9f1b8ac8e55203f34ea5a5eb89dd1102d3b
|
src/lzma/util-streams-buffered-lzma.adb
|
src/lzma/util-streams-buffered-lzma.adb
|
-----------------------------------------------------------------------
-- util-streams-buffered-lzma -- LZMA streams
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Encoders.Base64;
package body Util.Streams.Buffered.Lzma is
-- -----------------------
-- Initialize the stream to write on the given stream.
-- An internal buffer is allocated for writing the stream.
-- -----------------------
procedure Initialize (Stream : in out Compress_Stream;
Output : in Output_Stream_Access;
Size : in Natural;
Format : in String) is
begin
Stream.Initialize (Output, Size);
Stream.Transform := new Util.Encoders.Lzma.Compress;
end Initialize;
-- -----------------------
-- Close the sink.
-- -----------------------
overriding
procedure Close (Stream : in out Compress_Stream) is
begin
Stream.Flush;
Stream.Output.Close;
end Close;
-- -----------------------
-- Write the buffer array to the output stream.
-- -----------------------
overriding
procedure Write (Stream : in out Compress_Stream;
Buffer : in Ada.Streams.Stream_Element_Array) is
First_Encoded : Ada.Streams.Stream_Element_Offset := Buffer'First;
Last_Encoded : Ada.Streams.Stream_Element_Offset;
Last_Pos : Ada.Streams.Stream_Element_Offset;
begin
while First_Encoded <= Buffer'Last loop
Stream.Transform.Transform
(Data => Buffer (First_Encoded .. Buffer'Last),
Into => Stream.Buffer (Stream.Write_Pos .. Stream.Buffer'Last),
Last => Last_Pos,
Encoded => Last_Encoded);
if Last_Encoded < Buffer'Last then
Stream.Output.Write (Stream.Buffer (Stream.Buffer'First .. Last_Pos));
Stream.Write_Pos := Stream.Buffer'First;
else
Stream.Write_Pos := Last_Pos + 1;
end if;
First_Encoded := Last_Encoded + 1;
end loop;
end Write;
-- -----------------------
-- Flush the buffer by writing on the output stream.
-- Raises Data_Error if there is no output stream.
-- -----------------------
overriding
procedure Flush (Stream : in out Compress_Stream) is
Last_Pos : Ada.Streams.Stream_Element_Offset;
begin
loop
Stream.Transform.Finish (Stream.Buffer (Stream.Write_Pos .. Stream.Buffer'Last),
Last_Pos);
Stream.Write_Pos := Last_Pos + 1;
Output_Buffer_Stream (Stream).Flush;
exit when Stream.Write_Pos < Stream.Buffer'Last;
Stream.Write_Pos := 1;
end loop;
end Flush;
-- -----------------------
-- Flush the stream and release the buffer.
-- -----------------------
overriding
procedure Finalize (Object : in out Compress_Stream) is
begin
null;
end Finalize;
end Util.Streams.Buffered.Lzma;
|
Implement the support for LZMA Compress_Stream
|
Implement the support for LZMA Compress_Stream
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
|
4978b7699ea907d4d49743c2da367f554faa49ff
|
regtests/util-commands-tests.adb
|
regtests/util-commands-tests.adb
|
-----------------------------------------------------------------------
-- util-commands-tests - Test for commands
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with GNAT.Command_Line;
with Util.Test_Caller;
with Util.Commands.Parsers.GNAT_Parser;
with Util.Commands.Drivers;
package body Util.Commands.Tests is
package Caller is new Util.Test_Caller (Test, "Commands");
type Test_Context_Type is record
Number : Integer;
Success : Boolean := False;
end record;
package Test_Command is new
Util.Commands.Drivers (Context_Type => Test_Context_Type,
Config_Parser => Util.Commands.Parsers.GNAT_Parser.Config_Parser,
Driver_Name => "test");
type Test_Command_Type is new Test_Command.Command_Type with record
Opt_Count : aliased Integer := 0;
Opt_V : aliased Boolean := False;
Opt_N : aliased Boolean := False;
Expect_V : Boolean := False;
Expect_N : Boolean := False;
Expect_C : Integer := 0;
Expect_A : Integer := 0;
Expect_Help : Boolean := False;
end record;
overriding
procedure Execute (Command : in Test_Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Test_Context_Type);
-- Setup the command before parsing the arguments and executing it.
procedure Setup (Command : in out Test_Command_Type;
Config : in out GNAT.Command_Line.Command_Line_Configuration);
-- Write the help associated with the command.
procedure Help (Command : in Test_Command_Type;
Context : in out Test_Context_Type);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Commands.Driver.Execute",
Test_Execute'Access);
Caller.Add_Test (Suite, "Test Util.Commands.Driver.Help",
Test_Help'Access);
Caller.Add_Test (Suite, "Test Util.Commands.Driver.Usage",
Test_Usage'Access);
end Add_Tests;
overriding
procedure Execute (Command : in Test_Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Test_Context_Type) is
begin
Context.Success := Command.Opt_Count = Command.Expect_C and
Command.Opt_V = Command.Expect_V and
Command.Opt_N = Command.Expect_N and
Args.Get_Count = Command.Expect_A and
not Command.Expect_Help;
end Execute;
-- ------------------------------
-- Setup the command before parsing the arguments and executing it.
-- ------------------------------
procedure Setup (Command : in out Test_Command_Type;
Config : in out GNAT.Command_Line.Command_Line_Configuration) is
begin
GNAT.Command_Line.Define_Switch (Config => Config,
Switch => "-c:",
Long_Switch => "--count=",
Help => "Number option",
Section => "",
Initial => Integer (0),
Default => Integer (10),
Output => Command.Opt_Count'Access);
GNAT.Command_Line.Define_Switch (Config => Config,
Switch => "-v",
Long_Switch => "--verbose",
Help => "Verbose option",
Section => "",
Output => Command.Opt_V'Access);
GNAT.Command_Line.Define_Switch (Config => Config,
Switch => "-n",
Long_Switch => "--not",
Help => "Not option",
Section => "",
Output => Command.Opt_N'Access);
end Setup;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Command : in Test_Command_Type;
Context : in out Test_Context_Type) is
begin
Context.Success := Command.Expect_Help;
end Help;
-- ------------------------------
-- Tests when the execution of commands.
-- ------------------------------
procedure Test_Execute (T : in out Test) is
C1 : aliased Test_Command_Type;
C2 : aliased Test_Command_Type;
D : Test_Command.Driver_Type;
Args : String_Argument_List (500, 30);
begin
D.Set_Description ("Test command");
D.Add_Command ("list", C1'Unchecked_Access);
D.Add_Command ("print", C2'Unchecked_Access);
declare
Ctx : Test_Context_Type;
begin
C1.Expect_V := True;
C1.Expect_N := True;
C1.Expect_C := 4;
C1.Expect_A := 2;
Initialize (Args, "list --count=4 -v -n test titi");
D.Execute ("list", Args, Ctx);
T.Assert (Ctx.Success, "Some arguments not parsed correctly");
end;
declare
Ctx : Test_Context_Type;
begin
C1.Expect_V := False;
C1.Expect_N := True;
C1.Expect_C := 8;
C1.Expect_A := 3;
Initialize (Args, "list -c 8 -n test titi last");
D.Execute ("list", Args, Ctx);
T.Assert (Ctx.Success, "Some arguments not parsed correctly");
end;
end Test_Execute;
-- ------------------------------
-- Test execution of help.
-- ------------------------------
procedure Test_Help (T : in out Test) is
C1 : aliased Test_Command_Type;
C2 : aliased Test_Command_Type;
H : aliased Test_Command.Help_Command_Type;
D : Test_Command.Driver_Type;
Args : String_Argument_List (500, 30);
begin
D.Set_Description ("Test command");
D.Add_Command ("list", C1'Unchecked_Access);
D.Add_Command ("print", C2'Unchecked_Access);
D.Add_Command ("help", H'Unchecked_Access);
declare
Ctx : Test_Context_Type;
begin
C1.Expect_Help := True;
Initialize (Args, "help list");
D.Execute ("help", Args, Ctx);
T.Assert (Ctx.Success, "Some arguments not parsed correctly");
end;
declare
Ctx : Test_Context_Type;
begin
C2.Expect_Help := True;
Initialize (Args, "help print");
D.Execute ("help", Args, Ctx);
T.Assert (Ctx.Success, "Some arguments not parsed correctly");
end;
end Test_Help;
-- ------------------------------
-- Test usage operation.
-- ------------------------------
procedure Test_Usage (T : in out Test) is
C1 : aliased Test_Command_Type;
C2 : aliased Test_Command_Type;
H : aliased Test_Command.Help_Command_Type;
D : Test_Command.Driver_Type;
Args : String_Argument_List (500, 30);
begin
D.Set_Description ("Test command");
D.Add_Command ("list", C1'Unchecked_Access);
D.Add_Command ("print", C2'Unchecked_Access);
D.Add_Command ("help", H'Unchecked_Access);
D.Usage (Args);
declare
Ctx : Test_Context_Type;
begin
C1.Expect_Help := True;
Initialize (Args, "help list");
D.Execute ("help", Args, Ctx);
T.Assert (Ctx.Success, "Some arguments not parsed correctly");
end;
end Test_Usage;
end Util.Commands.Tests;
|
Implement unit tests for the Util.Commands and Util.Commands.Drivers package
|
Implement unit tests for the Util.Commands and Util.Commands.Drivers package
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
|
586f1c1ab1a5b0680213fb1af707bb56e58c7682
|
src/asis/asis-data_decomposition-aux.adb
|
src/asis/asis-data_decomposition-aux.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 . A U X --
-- --
-- B o d y --
-- --
-- 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). --
-- --
------------------------------------------------------------------------------
with Asis.Declarations; use Asis.Declarations;
with Asis.Definitions; use Asis.Definitions;
with Asis.Elements; use Asis.Elements;
with Asis.Expressions; use Asis.Expressions;
with Asis.Extensions; use Asis.Extensions;
with Asis.Iterator; use Asis.Iterator;
with Asis.Set_Get; use Asis.Set_Get;
with A4G.DDA_Aux; use A4G.DDA_Aux;
with Atree; use Atree;
with Einfo; use Einfo;
with Elists; use Elists;
with Sinfo; use Sinfo;
with Uintp; use Uintp;
package body Asis.Data_Decomposition.Aux is
-----------------------
-- Local subprograms --
-----------------------
function Build_Discrim_List_From_Constraint
(Rec : Entity_Id)
return Discrim_List;
-- Given a record entiti which has discriminants, returns a list
-- of discriminant values obtained from teh discriminant constraint or,
-- if there is no constraint, from default discriminant values.
-- Null_Discrims is returned in case if there is no constraint and no
-- default values for discriminants. Raises Variable_Rep_Info
-- if there is a default value which is not a static expression.
function Elist_Len (List : Elist_Id) return Int;
-- Computes the length of Entity list. 0 i sreturned in case if No (List).
function Is_Static_Constraint (Discr_Constr : Elist_Id) return Boolean;
-- Provided that Discr_Constr is obtained as Discriminant_Constraint
-- attribute of some type entity, checks if all the constraints are static
function Is_Empty_Record (Rec_Type_Def : Element) return Boolean;
-- Supposes Rec_Type_Def to be of A_Record_Type_Definition kind. Checks
-- if it defines a record type with no non-discriminant components
----------------------------------------
-- Build_Discrim_List_From_Constraint --
----------------------------------------
function Build_Discrim_List_From_Constraint
(Rec : Entity_Id)
return Discrim_List
is
Constraint : constant Elist_Id := Discriminant_Constraint (Rec);
Res_Len : constant Int := Elist_Len (Constraint);
Result : Discrim_List (1 .. Res_Len);
Next_Constr : Elmt_Id;
Next_Expr : Node_Id;
begin
Next_Constr := First_Elmt (Constraint);
for J in 1 .. Res_Len loop
Next_Expr := Node (Next_Constr);
if Nkind (Next_Expr) = N_Discriminant_Association then
Next_Expr := Sinfo.Expression (Next_Expr);
end if;
Result (J) := Eval_Scalar_Node (Next_Expr);
Next_Constr := Next_Elmt (Next_Constr);
end loop;
return Result;
end Build_Discrim_List_From_Constraint;
------------------------------------------
-- Build_Discrim_List_If_Data_Presented --
------------------------------------------
function Build_Discrim_List_If_Data_Presented
(Rec : Entity_Id;
Data : Asis.Data_Decomposition.Portable_Data;
Ignore_Discs : Boolean := False)
return Discrim_List
is
begin
if Data /= Nil_Portable_Data then
return Build_Discrim_List (Rec, Data);
elsif not Ignore_Discs and then
Has_Discriminants (Rec)
then
-- Here we have the situation when the record type has
-- discriminants, but no data stream is provided. Thit means, that
-- we have to use the default values for discriminants
return Build_Discrim_List_From_Constraint (Rec);
else
return Null_Discrims;
end if;
end Build_Discrim_List_If_Data_Presented;
-------------------------------
-- Component_Type_Definition --
-------------------------------
function Component_Type_Definition (E : Element) return Element is
Result : Element := Nil_Element;
begin
case Int_Kind (E) is
when A_Component_Declaration =>
Result := Object_Declaration_View (E);
Result := Component_Subtype_Indication (Result);
when A_Subtype_Indication =>
Result := E;
when others =>
pragma Assert (False);
null;
end case;
Result := Asis.Definitions.Subtype_Mark (Result);
if Int_Kind (Result) = A_Selected_Component then
Result := Selector (Result);
end if;
Result := Corresponding_Name_Declaration (Result);
Result := Corresponding_First_Subtype (Result);
Result := Type_Declaration_View (Result);
return Result;
end Component_Type_Definition;
---------------------------
-- Constraint_Model_Kind --
---------------------------
function Constraint_Model_Kind
(C : Element)
return Constraint_Model_Kinds
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (C);
Result : Constraint_Model_Kinds := Static_Constraint;
-- We start from the most optimistic assumption
Control : Traverse_Control := Continue;
procedure Analyze_Constraint
(Element : Asis.Element;
Control : in out Traverse_Control;
State : in out Constraint_Model_Kinds);
-- Checks the individual constraint and its components. Used as
-- Pre-Operation
procedure No_Op
(Element : Asis.Element;
Control : in out Traverse_Control;
State : in out Constraint_Model_Kinds);
-- Placeholder for Post-Operation
procedure Traverse_Constraint is new Traverse_Element (
State_Information => Constraint_Model_Kinds,
Pre_Operation => Analyze_Constraint,
Post_Operation => No_Op);
------------------------
-- Analyze_Constraint --
-------------------------
procedure Analyze_Constraint
(Element : Asis.Element;
Control : in out Traverse_Control;
State : in out Constraint_Model_Kinds)
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Element);
Tmp_El : Asis.Element;
Tmp_Node : Node_Id;
begin
if Arg_Kind = An_Identifier
and then
Int_Kind (Enclosing_Element (Element)) =
A_Discriminant_Association
and then
not Is_Equal (Element,
Discriminant_Expression
(Enclosing_Element (Element)))
then
-- If we are here, Element is from discriminant selector names
return;
end if;
case Arg_Kind is
when A_Discrete_Subtype_Indication =>
if Is_Nil (Subtype_Constraint (Element)) then
-- If we are here then we have a range constraint. Let's try
-- to get the information directly from the tree (starting
-- from the overpessimistic assumption).
State := External;
Tmp_El := Asis.Definitions.Subtype_Mark (Element);
if Expression_Kind (Tmp_El) = An_Attribute_Reference then
-- We are overpessimistic in this rather unusial case:
Control := Terminate_Immediately;
return;
end if;
Tmp_Node := R_Node (Tmp_El);
Tmp_Node := Entity (Tmp_Node);
if Present (Tmp_Node) then
Tmp_Node := Scalar_Range (Tmp_Node);
if Is_Static_Expression (Low_Bound (Tmp_Node))
and then
Is_Static_Expression (High_Bound (Tmp_Node))
then
State := Static_Constraint;
end if;
end if;
Control := Terminate_Immediately;
end if;
when A_Discrete_Range_Attribute_Reference =>
if Is_Static (Element) then
Control := Abandon_Children;
else
State := External;
Control := Terminate_Immediately;
end if;
when Internal_Expression_Kinds =>
if Is_True_Expression (Element) then
if Is_Static (Element) then
-- Nothing to do, no need to change State
Control := Abandon_Children;
else
if Arg_Kind = An_Identifier and then
Int_Kind (Corresponding_Name_Declaration (Element)) =
A_Discriminant_Specification
then
-- See RM 95 3.8(12)
State := Discriminated;
Control := Abandon_Children;
else
-- Completely dinamic situation for sure
State := External;
Control := Terminate_Immediately;
end if;
end if;
else
-- The only possibility for those Elements which are in
-- Internal_Expression_Kinds, but are not
-- Is_True_Expression is a type mark, and we do not have to
-- analyze it
Control := Abandon_Children;
end if;
when An_Index_Constraint |
A_Discriminant_Constraint |
A_Discrete_Simple_Expression_Range |
A_Discriminant_Association |
A_Simple_Expression_Range =>
-- Just go down:
null;
when others =>
pragma Assert (False);
null;
end case;
end Analyze_Constraint;
-----------
-- No_Op --
-----------
procedure No_Op
(Element : Asis.Element;
Control : in out Traverse_Control;
State : in out Constraint_Model_Kinds)
is
begin
pragma Unreferenced (Element);
pragma Unreferenced (Control);
pragma Unreferenced (State);
null;
end No_Op;
begin
if Arg_Kind = An_Index_Constraint or else
Arg_Kind = A_Discriminant_Constraint
then
Traverse_Constraint
(Element => C,
Control => Control,
State => Result);
end if;
return Result;
end Constraint_Model_Kind;
---------------------
-- De_Linear_Index --
---------------------
function De_Linear_Index
(Index : Asis.ASIS_Natural;
D : ASIS_Natural;
Ind_Lengths : Dimention_Length;
Conv : Convention_Id := Convention_Ada)
return Dimension_Indexes
is
Len : Asis.ASIS_Natural := 1;
Tmp_Ind : Asis.ASIS_Natural := Index;
Tmp_Res : Asis.ASIS_Natural;
Result : Dimension_Indexes (1 .. D);
begin
for J in 1 .. D loop
Len := Len * Ind_Lengths (J);
end loop;
-- Len can never be 0, because this function can never be called
-- for an empty array
-- For the normal case, we are row major
if Conv /= Convention_Fortran then
for J in Result'Range loop
Len := Len / Ind_Lengths (J);
Tmp_Res := Tmp_Ind / Len;
if Tmp_Res * Len < Tmp_Ind then
Tmp_Res := Tmp_Res + 1;
end if;
Result (J) := Tmp_Res;
Tmp_Ind := Tmp_Ind - Len * (Result (J) - 1);
end loop;
-- For Fortran, we are column major
else
for J in reverse Result'Range loop
Len := Len / Ind_Lengths (J);
Tmp_Res := Tmp_Ind / Len;
if Tmp_Res * Len < Tmp_Ind then
Tmp_Res := Tmp_Res + 1;
end if;
Result (J) := Tmp_Res;
Tmp_Ind := Tmp_Ind - Len * (Result (J) - 1);
end loop;
end if;
return Result;
end De_Linear_Index;
--------------------------------------------
-- Discriminant_Part_From_Type_Definition --
--------------------------------------------
function Discriminant_Part_From_Type_Definition
(T : Element)
return Element
is
Type_Entity : Node_Id;
Tmp_Element : Element;
Result : Element := Nil_Element;
begin
Type_Entity := R_Node (T);
if Nkind (Type_Entity) /= N_Private_Type_Declaration then
Type_Entity := Parent (Type_Entity);
end if;
Type_Entity := Sinfo.Defining_Identifier (Type_Entity);
if Einfo.Has_Discriminants (Type_Entity) then
Result := Enclosing_Element (T);
Result := Discriminant_Part (Result);
if Is_Nil (Result) then
-- Here we already know, that the type defined by T has
-- discriminants. The only possibility is that it is derived
-- from a type with known discriminant part. So we have to
-- traverse backward the derivation chain and return the first
-- known discriminant part found
Tmp_Element := Corresponding_Parent_Subtype (T);
Tmp_Element := Corresponding_First_Subtype (Tmp_Element);
loop
Result := Discriminant_Part (Tmp_Element);
exit when not Is_Nil (Result);
Tmp_Element := Type_Declaration_View (Tmp_Element);
Tmp_Element := Corresponding_Parent_Subtype (Tmp_Element);
Tmp_Element := Corresponding_First_Subtype (Tmp_Element);
end loop;
end if;
end if;
return Result;
end Discriminant_Part_From_Type_Definition;
---------------
-- Elist_Len --
---------------
function Elist_Len (List : Elist_Id) return Int is
Result : Int := 0;
Next_El : Elmt_Id;
begin
if Present (List) then
Next_El := First_Elmt (List);
while Present (Next_El) loop
Result := Result + 1;
Next_El := Next_Elmt (Next_El);
end loop;
end if;
return Result;
end Elist_Len;
----------------------------
-- Is_Derived_From_Record --
----------------------------
function Is_Derived_From_Record (TD : Element) return Boolean is
Result : Boolean := False;
Type_Entity_Node : Node_Id;
begin
if Int_Kind (TD) = A_Derived_Type_Definition then
Type_Entity_Node := R_Node (TD);
Type_Entity_Node := Defining_Identifier (Parent (Type_Entity_Node));
Result := Is_Record_Type (Type_Entity_Node);
end if;
return Result;
end Is_Derived_From_Record;
---------------------------
-- Is_Derived_From_Array --
---------------------------
function Is_Derived_From_Array (TD : Element) return Boolean is
Result : Boolean := False;
Type_Entity_Node : Node_Id;
begin
if Int_Kind (TD) = A_Derived_Type_Definition then
Type_Entity_Node := R_Node (TD);
Type_Entity_Node := Defining_Identifier (Parent (Type_Entity_Node));
Result := Is_Array_Type (Type_Entity_Node);
end if;
return Result;
end Is_Derived_From_Array;
---------------------
-- Is_Empty_Record --
---------------------
function Is_Empty_Record (Rec_Type_Def : Element) return Boolean is
Result : Boolean := False;
Arg_Node : constant Node_Id := R_Node (Rec_Type_Def);
begin
if Null_Present (Arg_Node) or else
Null_Present (Component_List (Arg_Node))
then
Result := True;
end if;
return Result;
end Is_Empty_Record;
--------------------------
-- Is_Static_Constraint --
--------------------------
function Is_Static_Constraint (Discr_Constr : Elist_Id) return Boolean is
Result : Boolean := True;
Next_DA : Elmt_Id;
begin
Next_DA := First_Elmt (Discr_Constr);
while Present (Next_DA) loop
if not Is_Static_Expression (Node (Next_DA)) then
Result := False;
exit;
end if;
Next_DA := Next_Elmt (Next_DA);
end loop;
return Result;
end Is_Static_Constraint;
------------------
-- Linear_Index --
------------------
function Linear_Index
(Inds : Dimension_Indexes;
Ind_Lengths : Dimention_Length;
Conv : Convention_Id := Convention_Ada)
return Asis.ASIS_Natural
is
Indx : Asis.ASIS_Natural := 0;
begin
-- For the normal case, we are row major
if Conv /= Convention_Fortran then
for J in Inds'Range loop
Indx := Indx * Ind_Lengths (J) + Inds (J) - 1;
end loop;
-- For Fortran, we are column major
else
for J in reverse Inds'Range loop
Indx := Indx * Ind_Lengths (J) + Inds (J) - 1;
end loop;
end if;
return Indx + 1;
end Linear_Index;
-------------
-- Max_Len --
-------------
function Max_Len (Component : Array_Component) return Asis.ASIS_Natural is
Result : Asis.ASIS_Natural;
begin
if Component.Length (1) = 0 then
-- the case of an empty array
return 0;
else
Result := 1;
end if;
for J in Component.Length'Range loop
exit when Component.Length (J) = 0;
Result := Result * Component.Length (J);
end loop;
return Result;
end Max_Len;
-----------------------
-- Record_Model_Kind --
-----------------------
function Record_Model_Kind (R : Element) return Type_Model_Kinds is
Type_Entity : Node_Id;
Result : Type_Model_Kinds := Not_A_Type_Model;
Control : Traverse_Control := Continue;
procedure Analyze_Component_Definition
(Element : Asis.Element;
Control : in out Traverse_Control;
State : in out Type_Model_Kinds);
-- Checks the individual component definition. Used as Pre-Operation.
procedure No_Op
(Element : Asis.Element;
Control : in out Traverse_Control;
State : in out Type_Model_Kinds);
-- Placeholder for Post-Operation
procedure Traverse_Record_Definition is new Traverse_Element (
State_Information => Type_Model_Kinds,
Pre_Operation => Analyze_Component_Definition,
Post_Operation => No_Op);
----------------------------------
-- Analyze_Component_Definition --
----------------------------------
procedure Analyze_Component_Definition
(Element : Asis.Element;
Control : in out Traverse_Control;
State : in out Type_Model_Kinds)
is
begin
pragma Unreferenced (State);
if Int_Kind (Element) = A_Component_Declaration then
case Subtype_Model_Kind
(Component_Subtype_Indication
(Object_Declaration_View (Element)))
is
when A_Simple_Static_Model | A_Simple_Dynamic_Model =>
Control := Abandon_Children;
when A_Complex_Dynamic_Model =>
Result := A_Complex_Dynamic_Model;
Control := Terminate_Immediately;
when Not_A_Type_Model =>
Result := Not_A_Type_Model;
Control := Terminate_Immediately;
end case;
end if;
end Analyze_Component_Definition;
-----------
-- No_Op --
-----------
procedure No_Op
(Element : Asis.Element;
Control : in out Traverse_Control;
State : in out Type_Model_Kinds)
is
begin
pragma Unreferenced (Element);
pragma Unreferenced (Control);
pragma Unreferenced (State);
null;
end No_Op;
begin
Type_Entity := R_Node (Enclosing_Element (R));
Type_Entity := Sinfo.Defining_Identifier (Type_Entity);
if Is_Empty_Record (R)
or else
(not (Has_Discriminants (Type_Entity)
and then
not Is_Constrained (Type_Entity))
and then
(RM_Size (Type_Entity) > 0))
then
Result := A_Simple_Static_Model;
elsif RM_Size (Type_Entity) = Uint_0 or else
RM_Size (Type_Entity) = No_Uint
then
-- This is the case when the front-end consider the type to be
-- essentially dynamic and therefore it can not set Esize field
-- at all
Result := A_Complex_Dynamic_Model;
else
-- We start from the most optimistic assumption
Result := A_Simple_Dynamic_Model;
Traverse_Record_Definition
(Element => R,
Control => Control,
State => Result);
end if;
return Result;
end Record_Model_Kind;
---------------------------
-- Root_Array_Definition --
---------------------------
function Root_Array_Definition (Type_Def : Element) return Element is
Result : Element := Type_Def;
begin
if Is_Derived_From_Array (Type_Def) then
Result := Corresponding_Root_Type (Type_Def);
Result := Type_Declaration_View (Result);
end if;
return Result;
end Root_Array_Definition;
----------------------------
-- Root_Record_Definition --
----------------------------
function Root_Record_Definition (Type_Def : Element) return Element is
Result : Element := Type_Def;
begin
if Is_Derived_From_Record (Type_Def) then
Result := Corresponding_Root_Type (Type_Def);
Result := Type_Declaration_View (Result);
end if;
return Result;
end Root_Record_Definition;
--------------------
-- Subtype_Entity --
--------------------
function Subtype_Entity (E : Element) return Entity_Id is
Result : Node_Id := Node (E);
Res_Kind : Node_Kind := Nkind (Result);
begin
while Present (Result) and then
not (Res_Kind = N_Subtype_Declaration or else
Res_Kind = N_Object_Declaration or else
Res_Kind = N_Derived_Type_Definition or else
Res_Kind = N_Full_Type_Declaration or else
Res_Kind = N_Component_Declaration)
loop
Result := Parent (Result);
Res_Kind := Nkind (Result);
end loop;
pragma Assert (Present (Result));
case Res_Kind is
when N_Subtype_Declaration =>
Result := Defining_Identifier (Result);
when N_Object_Declaration | N_Component_Declaration =>
Result := Etype (Defining_Identifier (Result));
when N_Derived_Type_Definition =>
Result := Defining_Identifier (Parent (Result));
when N_Full_Type_Declaration =>
-- Here we are expecting the component subtype definition from
-- array type declaration as the only possible case
Result := Defining_Identifier (Result);
pragma Assert (Is_Array_Type (Result));
Result := Component_Type (Result);
when others =>
null;
end case;
return Result;
end Subtype_Entity;
------------------------
-- Subtype_Model_Kind --
------------------------
function Subtype_Model_Kind (S : Element) return Type_Model_Kinds is
Result : Type_Model_Kinds := Not_A_Type_Model;
Type_Mark_Elem : Element;
Type_Mark_Def : Element;
Constr_Elem : Element;
Constraint_Model : Constraint_Model_Kinds := Not_A_Constraint_Model;
Type_Entity : Entity_Id;
begin
pragma Assert (Int_Kind (S) = A_Subtype_Indication);
Type_Mark_Elem := Asis.Definitions.Subtype_Mark (S);
Constr_Elem := Subtype_Constraint (S);
if Int_Kind (Type_Mark_Elem) = A_Selected_Component then
Type_Mark_Elem := Selector (Type_Mark_Elem);
end if;
Type_Mark_Def := Corresponding_Name_Declaration (Type_Mark_Elem);
if Int_Kind (Type_Mark_Def) = A_Private_Type_Declaration then
Type_Mark_Def := Corresponding_Type_Declaration (Type_Mark_Def);
end if;
Type_Entity := Sinfo.Defining_Identifier (R_Node (Type_Mark_Def));
-- Type_Mark_Def can only be either type or subtype declaration
Type_Mark_Def := Type_Declaration_View (Type_Mark_Def);
case Int_Kind (Type_Mark_Def) is
when Internal_Type_Kinds =>
Result := Type_Model_Kind (Type_Mark_Def);
when A_Subtype_Indication =>
Result := Subtype_Model_Kind (Type_Mark_Def);
when others =>
Result := A_Complex_Dynamic_Model;
end case;
if Result in A_Simple_Static_Model .. A_Simple_Dynamic_Model then
-- Here we have to chech if the constraint (if any) affects the
-- result
case Int_Kind (Constr_Elem) is
when An_Index_Constraint |
A_Discriminant_Constraint =>
Constraint_Model := Constraint_Model_Kind (Constr_Elem);
when Not_An_Element =>
if Has_Discriminants (Type_Entity)
and then
not Is_Empty_Elmt_List (Discriminant_Constraint (Type_Entity))
then
-- This is the case, when a subtype indication to analyze
-- does not contain any explicit constraint, but
-- the corresponding discriminanted subtype might be
-- constrained by explicit constraint or default values
-- somewhere before in subtyping and/or derivation chain
if Is_Static_Constraint
(Discriminant_Constraint (Type_Entity))
then
Constraint_Model := Static_Constraint;
end if;
end if;
when others =>
-- We consider, that other kinds of the constraint can not
-- affect the result
null;
end case;
case Constraint_Model is
when External =>
Result := A_Complex_Dynamic_Model;
when Discriminated =>
Result := A_Simple_Dynamic_Model;
when Static_Constraint =>
Result := A_Simple_Static_Model;
when others =>
null;
end case;
end if;
return Result;
end Subtype_Model_Kind;
---------------------------------------
-- Type_Definition_From_Subtype_Mark --
---------------------------------------
function Type_Definition_From_Subtype_Mark (S : Element) return Element is
Result : Element;
begin
if Int_Kind (S) = A_Selected_Component then
Result := Selector (S);
else
Result := S;
end if;
Result := Corresponding_Name_Declaration (Result);
Result := Corresponding_First_Subtype (Result);
Result := Type_Declaration_View (Result);
return Result;
end Type_Definition_From_Subtype_Mark;
-------------------
-- Wrong_Indexes --
-------------------
function Wrong_Indexes
(Component : Array_Component;
Indexes : Dimension_Indexes)
return Boolean
is
D : constant ASIS_Natural := Component.Dimension;
Result : Boolean := True;
begin
if D = Indexes'Length then
Result := False;
for J in 1 .. D loop
if Indexes (J) > Component.Length (J) then
Result := True;
exit;
end if;
end loop;
end if;
return Result;
end Wrong_Indexes;
end Asis.Data_Decomposition.Aux;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
fa91249d159eb87a131d89760ee6be78bb6c5160
|
src/asis/a4g-asis_tables.ads
|
src/asis/a4g-asis_tables.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . A S I S _ T A B L E S --
-- --
-- S p e c --
-- --
-- Copyright (C) 1995-2012, Free Software Foundation, Inc. --
-- --
-- ASIS-for-GNAT is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 2, or (at your option) any later --
-- version. ASIS-for-GNAT is distributed in the hope that it will be use- --
-- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- --
-- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General --
-- Public License for more details. You should have received a copy of the --
-- GNU General Public License distributed with ASIS-for-GNAT; see file --
-- COPYING. If not, write to the Free Software Foundation, 51 Franklin --
-- Street, Fifth Floor, Boston, MA 02110-1301, USA. --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the --
-- Software Engineering Laboratory of the Swiss Federal Institute of --
-- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the --
-- Scientific Research Computer Center of Moscow State University (SRCC --
-- MSU), Russia, with funding partially provided by grants from the Swiss --
-- National Science Foundation and the Swiss Academy of Engineering --
-- Sciences. ASIS-for-GNAT is now maintained by AdaCore --
-- (http://www.adacore.com). --
-- --
------------------------------------------------------------------------------
-- This package contains definitions of tables and related auxilary resources
-- needed in more than one ASIS implementation package
with Asis;
with Sinfo; use Sinfo;
with Table;
with Types; use Types;
package A4G.Asis_Tables is
package Internal_Asis_Element_Table is new Table.Table (
Table_Component_Type => Asis.Element,
Table_Index_Type => Asis.ASIS_Natural,
Table_Low_Bound => 1,
Table_Initial => 10,
Table_Increment => 100,
Table_Name => "Internal Element_List");
-- This table contains ASIS Elements. It is supposed to be used only for
-- creating the result Element lists in ASIS structural queries. Note that
-- many ASIS queries use instantiations of Traverse_Elements to create
-- result lists, so we have to make sure that ASIS structural queries
-- used in the implementation of Traverse_Element use another table to
-- create result lists
package Asis_Element_Table is new Table.Table (
Table_Component_Type => Asis.Element,
Table_Index_Type => Asis.ASIS_Natural,
Table_Low_Bound => 1,
Table_Initial => 10,
Table_Increment => 100,
Table_Name => "Element_List");
-- This table contains ASIS Elements. It is supposed to be used for any
-- purpose except creating the result Element lists in ASIS structural
-- queries.
procedure Add_New_Element (Element : Asis.Element);
-- Differs from Asis_Element_Table.Append that checks if the argument
-- Element already is in the table, and appends the new element only if the
-- check fails. Note that the implementation is based on a simple array
-- search, so it can result in performance penalties if there are too
-- many elements in the table.
type Node_Trace_Rec is record
Kind : Node_Kind;
Node_Line : Physical_Line_Number;
Node_Col : Column_Number;
end record;
-- This record represents a Node in the node trace used to find the same
-- construct in another tree
package Node_Trace is new Table.Table (
Table_Component_Type => Node_Trace_Rec,
Table_Index_Type => Int,
Table_Low_Bound => 0,
Table_Initial => 10,
Table_Increment => 100,
Table_Name => "Node_Trace");
-- This table is used to create the node trace needed to compare elements
-- from nested instances
function Is_Equal
(N : Node_Id;
Trace_Rec : Node_Trace_Rec)
return Boolean;
-- Checks if N (in the currently accessed tree corresponds to the node
-- for which Trace_Rec was created
procedure Create_Node_Trace (N : Node_Id);
-- Creates the Node trace which is supposed to be used to find the node
-- representing the same construct in another tree. The trace is also used
-- to check is two nodes from different trees, each belonging to expanded
-- generics both denote the same thing. This trace contains the record
-- about N itself and all the enclosing constructs such as package bodies
-- and package specs. For the package which is an expanded generic, the
-- next element in the trace is the corresponding instantiation node.
function Enclosing_Scope (N : Node_Id) return Node_Id;
-- Given a node somewhere from expanded generic, returnes its enclosing
-- "scope" which can be N_Package_Declaration, N_Package_Body or
-- N_Generic_Declaration node. The idea is to use this function to create
-- the node trace either for storing it in the Note Trace table or for
-- creating the trace on the fly to compare it with the stored trace.
end A4G.Asis_Tables;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
|
455313528c5043594b74c35289d782fc17a32af2
|
src/wiki-streams-html-stream.ads
|
src/wiki-streams-html-stream.ads
|
-----------------------------------------------------------------------
-- wiki-streams-html-stream -- Generic Wiki HTML output stream
-- Copyright (C) 2016, 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 Wiki.Strings;
generic
type Output_Stream is limited new Wiki.Streams.Output_Stream with private;
package Wiki.Streams.Html.Stream is
type Html_Output_Stream is limited new Output_Stream
and Html.Html_Output_Stream with private;
-- 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_Stream;
Name : in String;
Content : in Wiki.Strings.UString);
-- 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_Stream;
Name : in String;
Content : in Wide_Wide_String);
-- Start an XML element with the given name.
overriding
procedure Start_Element (Stream : in out Html_Output_Stream;
Name : in String);
-- Closes an XML element of the given name.
overriding
procedure End_Element (Stream : in out Html_Output_Stream;
Name : in String);
-- Write a text escaping any character as necessary.
overriding
procedure Write_Wide_Text (Stream : in out Html_Output_Stream;
Content : in Wiki.Strings.WString);
private
type Html_Output_Stream is limited new Output_Stream
and 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.Stream;
|
Refactor the HTML Text_IO stream into a generic package
|
Refactor the HTML Text_IO stream into a generic package
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
|
6d1eefae2d8522dfa8782c1a050674e450d7d7f4
|
mat/src/readline/readline.ads
|
mat/src/readline/readline.ads
|
-----------------------------------------------------------------------
-- readline -- A simple readline binding
-- 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 Interfaces;
package Readline is
-- Print the prompt and a read a line from the terminal.
-- Raise the Ada.IO_Exceptions.End_Error when the EOF is reached.
function Get_Line (Prompt : in String) return String;
end Readline;
|
Define the Readline package with the Get_Line operation
|
Define the Readline package with the Get_Line operation
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
|
8b5b8d763f4a8bc71f0e2523cab116d49c5c27a9
|
src/asis/asis-exceptions.ads
|
src/asis/asis-exceptions.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT INTERFACE COMPONENTS --
-- --
-- A S I S . E X C E P T 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. --
-- --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- 5 package Asis.Exceptions
------------------------------------------------------------------------------
------------------------------------------------------------------------------
package Asis.Exceptions is
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- ASIS exceptions are:
ASIS_Inappropriate_Context : exception;
------------------------------------------------------------------------------
-- Raised when ASIS is passed a Context value that is not appropriate for the
-- operation. This exception will typically indicate that a user error
-- has occurred within the application.
------------------------------------------------------------------------------
ASIS_Inappropriate_Container : exception;
------------------------------------------------------------------------------
-- Raised when ASIS is passed a Container value that is not appropriate for
-- the operation. This exception will typically indicate that a user error
-- has occurred within the application.
------------------------------------------------------------------------------
ASIS_Inappropriate_Compilation_Unit : exception;
------------------------------------------------------------------------------
-- Raised when ASIS is passed a Compilation_Unit value that is not
-- appropriate. This exception will typically indicate that a user
-- error has occurred within the application.
------------------------------------------------------------------------------
ASIS_Inappropriate_Element : exception;
------------------------------------------------------------------------------
-- Raised when ASIS is given an Element value that is not appropriate. This
-- exception will typically indicate that a user error has occurred within
-- the application.
------------------------------------------------------------------------------
ASIS_Inappropriate_Line : exception;
------------------------------------------------------------------------------
-- Raised when ASIS is given a Line value that is not appropriate.
------------------------------------------------------------------------------
ASIS_Inappropriate_Line_Number : exception;
------------------------------------------------------------------------------
-- Raised when ASIS is given a Line_Number value that is not appropriate.
-- This exception will typically indicate that a user error has occurred
-- within the application.
------------------------------------------------------------------------------
ASIS_Failed : exception;
------------------------------------------------------------------------------
-- This is a catch-all exception that may be raised for different reasons
-- in different ASIS implementations. All ASIS routines may raise ASIS_Failed
-- whenever they cannot normally complete their operation. This exception
-- will typically indicate a failure of the underlying ASIS implementation.
------------------------------------------------------------------------------
end Asis.Exceptions;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
cf9de94b13f8447306f4e72e7cf1dd0f23a7b00b
|
matp/src/mat-interrupts.adb
|
matp/src/mat-interrupts.adb
|
-----------------------------------------------------------------------
-- mat-interrupts - SIGINT management to stop long running commands
-- 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.Interrupts;
with Ada.Interrupts.Names;
with Util.Log.Loggers;
package body MAT.Interrupts is
pragma Interrupt_State (Name => Ada.Interrupts.Names.SIGINT,
State => USER);
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Interrupts");
protected Interrupts is
procedure Interrupt;
pragma Interrupt_Handler (Interrupt);
function Is_Interrupted return Boolean;
procedure Clear;
private
Interrupted : Boolean;
end Interrupts;
protected body Interrupts is
function Is_Interrupted return Boolean is
begin
return Interrupted;
end Is_Interrupted;
procedure Clear is
begin
Interrupted := False;
end Clear;
procedure Interrupt is
begin
Interrupted := True;
Log.Info ("SIGINT signal received");
end Interrupt;
end Interrupts;
-- ------------------------------
-- Install the SIGINT handler.
-- ------------------------------
procedure Install is
begin
Ada.Interrupts.Attach_Handler (Interrupts.Interrupt'Access,
Ada.Interrupts.Names.SIGINT);
Log.Info ("Interrupt handler for SIGINT is installed");
end Install;
-- ------------------------------
-- Reset the interrupted flag.
-- ------------------------------
procedure Clear is
begin
Interrupts.Clear;
end Clear;
-- ------------------------------
-- Check if we have been interrupted.
-- ------------------------------
function Is_Interrupted return Boolean is
begin
return Interrupts.Is_Interrupted;
end Is_Interrupted;
end MAT.Interrupts;
|
Implement the SIGINT interrupt handler with operations to install, check and clear the interrupt flag
|
Implement the SIGINT interrupt handler with operations to install, check
and clear the interrupt flag
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
|
6d6eade7f60f9688851ce587858e225df88f5ec9
|
src/security-auth-oauth.adb
|
src/security-auth-oauth.adb
|
-----------------------------------------------------------------------
-- 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 Util.Log.Loggers;
with Security.OAuth.Clients;
package body Security.Auth.OAuth is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth.OAuth");
-- ------------------------------
-- OAuth Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the OAuth authorization process.
-- Initialize the authentication realm.
overriding
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Provider : in String := PROVIDER_OPENID) is
begin
Realm.App.Set_Application_Identifier (Params.Get_Parameter (Provider & ".client_id"));
Realm.App.Set_Application_Secret (Params.Get_Parameter (Provider & ".secret"));
Realm.App.Set_Application_Callback (Params.Get_Parameter (Provider & ".callback_url"));
Realm.App.Set_Provider_URI (Params.Get_Parameter (Provider & ".request_url"));
Realm.Realm := To_Unbounded_String (Params.Get_Parameter (Provider & ".realm"));
Realm.Scope := To_Unbounded_String (Params.Get_Parameter (Provider & ".scope"));
end Initialize;
-- Discover the OpenID provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned.
-- 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) is
begin
Result.URL := To_Unbounded_String (Name);
end Discover;
-- 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) is
begin
null;
end Associate;
overriding
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String is
Result : Unbounded_String := OP.URL;
State : constant String := Realm.App.Get_State (To_String (Assoc.Assoc_Handle));
Params : constant String := Realm.App.Get_Auth_Params (State, To_String (Realm.Scope));
begin
if Index (Result, "?") > 0 then
Append (Result, "&");
else
Append (Result, "?");
end if;
Append (Result, Params);
Log.Debug ("Params = {0}", Params);
return To_String (Result);
end Get_Authentication_URL;
-- Verify the authentication result
overriding
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication) is
State : constant String := Request.Get_Parameter (Security.OAuth.State);
Code : constant String := Request.Get_Parameter (Security.OAuth.Code);
Error : constant String := Request.Get_Parameter (Security.OAuth.Error_Description);
begin
if Error'Length /= 0 then
Set_Result (Result, CANCEL, "Authentication refused: " & Error);
return;
end if;
-- First, verify that the state parameter matches our internal state.
if not Realm.App.Is_Valid_State (To_String (Assoc.Assoc_Handle), State) then
Set_Result (Result, INVALID_SIGNATURE, "invalid OAuth state parameter");
return;
end if;
-- Get the access token from the authorization code.
declare
use type Security.OAuth.Clients.Access_Token_Access;
Acc : constant Security.OAuth.Clients.Access_Token_Access
:= Realm.App.Request_Access_Token (Code);
begin
if Acc = null then
Set_Result (Result, INVALID_SIGNATURE, "cannot change the code to an access_token");
return;
end if;
-- Last step, verify the access token and get the user identity.
Manager'Class (Realm).Verify_Access_Token (Assoc, Request, Acc, Result);
end;
end Verify;
end Security.Auth.OAuth;
|
Implement the OAuth authorization by using the OAuth Clients
|
Implement the OAuth authorization by using the OAuth Clients
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
|
948a188acafab545ef086ecf5b2f74a5297eb712
|
src/asis/a4g-asis_tables.adb
|
src/asis/a4g-asis_tables.adb
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . A S I S _ T A B L E S --
-- --
-- B o d y --
-- --
-- Copyright (C) 1995-2009, Free Software Foundation, Inc. --
-- --
-- ASIS-for-GNAT is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 2, or (at your option) any later --
-- version. ASIS-for-GNAT is distributed in the hope that it will be use- --
-- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- --
-- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General --
-- Public License for more details. You should have received a copy of the --
-- GNU General Public License distributed with ASIS-for-GNAT; see file --
-- COPYING. If not, write to the Free Software Foundation, 51 Franklin --
-- Street, Fifth Floor, Boston, MA 02110-1301, USA. --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the --
-- Software Engineering Laboratory of the Swiss Federal Institute of --
-- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the --
-- Scientific Research Computer Center of Moscow State University (SRCC --
-- MSU), Russia, with funding partially provided by grants from the Swiss --
-- National Science Foundation and the Swiss Academy of Engineering --
-- Sciences. ASIS-for-GNAT is now maintained by AdaCore --
-- (http://www.adacore.com). --
-- --
------------------------------------------------------------------------------
with Asis.Elements; use Asis.Elements;
with Atree; use Atree;
with Sinput; use Sinput;
with Einfo; use Einfo;
with Nlists; use Nlists;
package body A4G.Asis_Tables is
---------------------
-- Add_New_Element --
---------------------
procedure Add_New_Element (Element : Asis.Element) is
Found : Boolean := False;
begin
for J in 1 .. Asis_Element_Table.Last loop
if Is_Equal (Element, Asis_Element_Table.Table (J)) then
Found := True;
exit;
end if;
end loop;
if not Found then
Asis_Element_Table.Append (Element);
end if;
end Add_New_Element;
-----------------------
-- Create_Node_Trace --
-----------------------
procedure Create_Node_Trace (N : Node_Id) is
Next_Node : Node_Id;
Next_Sloc : Source_Ptr;
Next_Node_Rec : Node_Trace_Rec;
begin
Node_Trace.Init;
Next_Node := N;
while Present (Next_Node) loop
Next_Sloc := Sloc (Next_Node);
Next_Node_Rec.Kind := Nkind (Next_Node);
Next_Node_Rec.Node_Line := Get_Physical_Line_Number (Next_Sloc);
Next_Node_Rec.Node_Col := Get_Column_Number (Next_Sloc);
Node_Trace.Append (Next_Node_Rec);
Next_Node := Enclosing_Scope (Next_Node);
end loop;
end Create_Node_Trace;
---------------------
-- Enclosing_Scope --
---------------------
function Enclosing_Scope (N : Node_Id) return Node_Id is
Result : Node_Id := N;
Entity_Node : Entity_Id := Empty;
begin
if Nkind (Result) = N_Package_Declaration then
Entity_Node := Defining_Unit_Name (Sinfo.Specification (Result));
elsif Nkind (Result) = N_Package_Body then
Entity_Node := Defining_Unit_Name (Result);
end if;
if Nkind (Entity_Node) = N_Defining_Program_Unit_Name then
Entity_Node := Sinfo.Defining_Identifier (Entity_Node);
end if;
if Present (Entity_Node) and then
Is_Generic_Instance (Entity_Node)
then
-- going to the corresponding instantiation
if Nkind (Parent (Result)) = N_Compilation_Unit then
-- We are at the top/ and we do not need a library-level
-- instantiation - it is always unique in the compilation
-- unit
Result := Empty;
else
-- "local" instantiation, therefore - one or two steps down the
-- declaration list to get in the instantiation node:
Result := Next_Non_Pragma (Result);
if Nkind (Result) = N_Package_Body then
-- This is an expanded generic body
Result := Next_Non_Pragma (Result);
end if;
end if;
else
-- One step up to the enclosing scope
Result := Parent (Result);
while not (Nkind (Result) = N_Package_Specification or else
Nkind (Result) = N_Package_Body or else
Nkind (Result) = N_Compilation_Unit or else
Nkind (Result) = N_Subprogram_Body or else
Nkind (Result) = N_Block_Statement)
loop
Result := Parent (Result);
end loop;
if Nkind (Result) = N_Package_Specification then
Result := Parent (Result);
elsif Nkind (Result) = N_Compilation_Unit then
Result := Empty;
end if;
end if;
return Result;
end Enclosing_Scope;
--------------
-- Is_Equal --
--------------
function Is_Equal
(N : Node_Id;
Trace_Rec : Node_Trace_Rec)
return Boolean
is
begin
return Nkind (N) = Trace_Rec.Kind and then
Get_Physical_Line_Number (Sloc (N)) = Trace_Rec.Node_Line and then
Get_Column_Number (Sloc (N)) = Trace_Rec.Node_Col;
end Is_Equal;
end A4G.Asis_Tables;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
b17205ac8a630e11cc6c263456b9d9f28d60d692
|
src/util-serialize-mappers.adb
|
src/util-serialize-mappers.adb
|
-----------------------------------------------------------------------
-- util-serialize-mappers -- Serialize objects in various formats
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
with Ada.Unchecked_Deallocation;
package body Util.Serialize.Mappers is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.Mappers",
Util.Log.WARN_LEVEL);
-- -----------------------
-- Execute the mapping operation on the object associated with the current context.
-- The object is extracted from the context and the <b>Execute</b> operation is called.
-- -----------------------
procedure Execute (Handler : in Mapper;
Map : in Mapping'Class;
Ctx : in out Util.Serialize.Contexts.Context'Class;
Value : in Util.Beans.Objects.Object) is
begin
if Handler.Mapper /= null then
Handler.Mapper.all.Execute (Map, Ctx, Value);
end if;
end Execute;
function Is_Proxy (Controller : in Mapper) return Boolean is
begin
return Controller.Is_Proxy_Mapper;
end Is_Proxy;
-- -----------------------
-- Returns true if the mapper is a wildcard node (matches any element).
-- -----------------------
function Is_Wildcard (Controller : in Mapper) return Boolean is
begin
return Controller.Is_Wildcard;
end Is_Wildcard;
-- -----------------------
-- Returns the mapping name.
-- -----------------------
function Get_Name (Controller : in Mapper) return String is
begin
return Ada.Strings.Unbounded.To_String (Controller.Name);
end Get_Name;
-- -----------------------
-- Find the mapper associated with the given name.
-- Returns null if there is no mapper.
-- -----------------------
function Find_Mapper (Controller : in Mapper;
Name : in String;
Attribute : in Boolean := False) return Mapper_Access is
use type Ada.Strings.Unbounded.Unbounded_String;
Node : Mapper_Access := Controller.First_Child;
begin
if Node = null and Controller.Mapper /= null then
return Controller.Mapper.Find_Mapper (Name, Attribute);
end if;
while Node /= null loop
if Node.Is_Wildcard then
declare
Result : constant Mapper_Access := Node.Find_Mapper (Name, Attribute);
begin
if Result /= null then
return Result;
else
return Node;
end if;
end;
end if;
if Node.Name = Name then
if (Attribute = False and Node.Mapping = null)
or else not Node.Mapping.Is_Attribute then
return Node;
end if;
if Attribute and Node.Mapping.Is_Attribute then
return Node;
end if;
end if;
Node := Node.Next_Mapping;
end loop;
return null;
end Find_Mapper;
-- -----------------------
-- Find a path component representing a child mapper under <b>From</b> and
-- identified by the given <b>Name</b>. If the mapper is not found, a new
-- Mapper_Node is created.
-- -----------------------
procedure Find_Path_Component (From : in out Mapper'Class;
Name : in String;
Result : out Mapper_Access) is
use Ada.Strings.Unbounded;
Node : Mapper_Access := From.First_Child;
Previous : Mapper_Access := null;
Wildcard : constant Boolean := Name = "*";
begin
if Node = null then
Result := new Mapper;
Result.Name := To_Unbounded_String (Name);
Result.Is_Wildcard := Wildcard;
From.First_Child := Result;
return;
end if;
loop
if Node.Name = Name then
Result := Node;
return;
end if;
if Node.Next_Mapping = null then
Result := new Mapper;
Result.Name := To_Unbounded_String (Name);
Result.Is_Wildcard := Wildcard;
if Node.Is_Wildcard then
Result.Next_Mapping := Node;
if Previous = null then
From.First_Child := Result;
else
Previous.Next_Mapping := Result;
end if;
else
Node.Next_Mapping := Result;
end if;
return;
end if;
Previous := Node;
Node := Node.Next_Mapping;
end loop;
end Find_Path_Component;
-- -----------------------
-- Build the mapping tree that corresponds to the given <b>Path</b>.
-- Each path component is represented by a <b>Mapper_Node</b> element.
-- The node is created if it does not exists.
-- -----------------------
procedure Build_Path (Into : in out Mapper'Class;
Path : in String;
Last_Pos : out Natural;
Node : out Mapper_Access) is
Pos : Natural;
begin
Node := Into'Unchecked_Access;
Last_Pos := Path'First;
loop
Pos := Util.Strings.Index (Source => Path,
Char => '/',
From => Last_Pos);
if Pos = 0 then
Node.Find_Path_Component (Name => Path (Last_Pos .. Path'Last),
Result => Node);
Last_Pos := Path'Last + 1;
else
Node.Find_Path_Component (Name => Path (Last_Pos .. Pos - 1),
Result => Node);
Last_Pos := Pos + 1;
end if;
exit when Last_Pos > Path'Last;
end loop;
end Build_Path;
-- -----------------------
-- Add a mapping to associate the given <b>Path</b> to the mapper defined in <b>Map</b>.
-- The <b>Path</b> string describes the matching node using a simplified XPath notation.
-- Example:
-- info/first_name matches: <info><first_name>...</first_name></info>
-- info/a/b/name matches: <info><a><b><name>...</name></b></a></info>
-- */a/b/name matches: <i><i><j><a><b><name>...</name></b></a></j></i></i>
-- -----------------------
procedure Add_Mapping (Into : in out Mapper;
Path : in String;
Map : in Mapper_Access) is
procedure Copy (To : in Mapper_Access;
From : in Mapper_Access);
Node : Mapper_Access;
Last_Pos : Natural;
procedure Copy (To : in Mapper_Access;
From : in Mapper_Access) is
N : Mapper_Access;
Src : Mapper_Access := From;
begin
while Src /= null loop
N := Src.Clone;
N.Is_Clone := True;
N.Next_Mapping := To.First_Child;
To.First_Child := N;
if Src.First_Child /= null then
Copy (N, Src.First_Child);
end if;
Src := Src.Next_Mapping;
end loop;
end Copy;
begin
Log.Info ("Mapping '{0}' for mapper X", Path);
-- Find or build the mapping tree.
Into.Build_Path (Path, Last_Pos, Node);
if Last_Pos < Path'Last then
Log.Warn ("Ignoring the end of mapping path {0}", Path);
end if;
if Node.Mapper /= null then
Log.Warn ("Overriding the mapping {0} for mapper X", Path);
end if;
if Map.First_Child /= null then
Copy (Node, Map.First_Child);
else
Node.Mapper := Map;
end if;
end Add_Mapping;
procedure Add_Mapping (Into : in out Mapper;
Path : in String;
Map : in Mapping_Access) is
use Ada.Strings.Unbounded;
Node : Mapper_Access;
Last_Pos : Natural;
begin
Log.Info ("Mapping {0}", Path);
-- Find or build the mapping tree.
Into.Build_Path (Path, Last_Pos, Node);
if Last_Pos < Path'Last then
Log.Warn ("Ignoring the end of mapping path {0}", Path);
end if;
if Node.Mapping /= null then
Log.Warn ("Overriding the mapping {0} for mapper X", Path);
end if;
if Length (Node.Name) = 0 then
Log.Warn ("Mapped name is empty in mapping path {0}", Path);
elsif Element (Node.Name, 1) = '@' then
Delete (Node.Name, 1, 1);
Map.Is_Attribute := True;
else
Map.Is_Attribute := False;
end if;
Node.Mapping := Map;
Node.Mapper := Into'Unchecked_Access;
end Add_Mapping;
-- -----------------------
-- Clone the <b>Handler</b> instance and get a copy of that single object.
-- -----------------------
function Clone (Handler : in Mapper) return Mapper_Access is
Result : constant Mapper_Access := new Mapper;
begin
Result.Name := Handler.Name;
Result.Mapper := Handler.Mapper;
Result.Mapping := Handler.Mapping;
Result.Is_Proxy_Mapper := Handler.Is_Proxy_Mapper;
Result.Is_Clone := True;
Result.Is_Wildcard := Handler.Is_Wildcard;
return Result;
end Clone;
-- -----------------------
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
-- -----------------------
procedure Set_Member (Handler : in Mapper;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False;
Context : in out Util.Serialize.Contexts.Context'Class) is
Map : constant Mapper_Access := Mapper'Class (Handler).Find_Mapper (Name, Attribute);
begin
if Map /= null and then Map.Mapping /= null and then Map.Mapper /= null then
Map.Mapper.all.Execute (Map.Mapping.all, Context, Value);
end if;
end Set_Member;
procedure Start_Object (Handler : in Mapper;
Context : in out Util.Serialize.Contexts.Context'Class;
Name : in String) is
begin
if Handler.Mapper /= null then
Handler.Mapper.Start_Object (Context, Name);
end if;
end Start_Object;
procedure Finish_Object (Handler : in Mapper;
Context : in out Util.Serialize.Contexts.Context'Class;
Name : in String) is
begin
if Handler.Mapper /= null then
Handler.Mapper.Finish_Object (Context, Name);
end if;
end Finish_Object;
-- -----------------------
-- Dump the mapping tree on the logger using the INFO log level.
-- -----------------------
procedure Dump (Handler : in Mapper'Class;
Log : in Util.Log.Loggers.Logger'Class;
Prefix : in String := "") is
procedure Dump (Map : in Mapper'Class);
-- -----------------------
-- Dump the mapping description
-- -----------------------
procedure Dump (Map : in Mapper'Class) is
begin
if Map.Mapping /= null and then Map.Mapping.Is_Attribute then
Log.Info (" {0}@{1}", Prefix,
Ada.Strings.Unbounded.To_String (Map.Mapping.Name));
else
Log.Info (" {0}/{1}", Prefix, Ada.Strings.Unbounded.To_String (Map.Name));
Dump (Map, Log, Prefix & "/" & Ada.Strings.Unbounded.To_String (Map.Name));
end if;
end Dump;
begin
Iterate (Handler, Dump'Access);
end Dump;
procedure Iterate (Controller : in Mapper;
Process : not null access procedure (Map : in Mapper'Class)) is
Node : Mapper_Access := Controller.First_Child;
begin
-- Pass 1: process the attributes first
while Node /= null loop
if Node.Mapping /= null and then Node.Mapping.Is_Attribute then
Process.all (Node.all);
end if;
Node := Node.Next_Mapping;
end loop;
-- Pass 2: process the elements
Node := Controller.First_Child;
while Node /= null loop
if Node.Mapping = null or else not Node.Mapping.Is_Attribute then
Process.all (Node.all);
end if;
Node := Node.Next_Mapping;
end loop;
end Iterate;
-- -----------------------
-- Finalize the object and release any mapping.
-- -----------------------
overriding
procedure Finalize (Controller : in out Mapper) is
procedure Free is new Ada.Unchecked_Deallocation (Mapper'Class, Mapper_Access);
procedure Free is new Ada.Unchecked_Deallocation (Mapping'Class, Mapping_Access);
Node : Mapper_Access := Controller.First_Child;
Next : Mapper_Access;
begin
Controller.First_Child := null;
while Node /= null loop
Next := Node.Next_Mapping;
Free (Node);
Node := Next;
end loop;
if not Controller.Is_Clone then
Free (Controller.Mapping);
else
Controller.Mapping := null;
end if;
end Finalize;
end Util.Serialize.Mappers;
|
-----------------------------------------------------------------------
-- util-serialize-mappers -- Serialize objects in various formats
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
with Ada.Unchecked_Deallocation;
package body Util.Serialize.Mappers is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.Mappers",
Util.Log.WARN_LEVEL);
-- -----------------------
-- Execute the mapping operation on the object associated with the current context.
-- The object is extracted from the context and the <b>Execute</b> operation is called.
-- -----------------------
procedure Execute (Handler : in Mapper;
Map : in Mapping'Class;
Ctx : in out Util.Serialize.Contexts.Context'Class;
Value : in Util.Beans.Objects.Object) is
begin
if Handler.Mapper /= null then
Handler.Mapper.all.Execute (Map, Ctx, Value);
end if;
end Execute;
function Is_Proxy (Controller : in Mapper) return Boolean is
begin
return Controller.Is_Proxy_Mapper;
end Is_Proxy;
-- -----------------------
-- Returns true if the mapper is a wildcard node (matches any element).
-- -----------------------
function Is_Wildcard (Controller : in Mapper) return Boolean is
begin
return Controller.Is_Wildcard;
end Is_Wildcard;
-- -----------------------
-- Returns the mapping name.
-- -----------------------
function Get_Name (Controller : in Mapper) return String is
begin
return Ada.Strings.Unbounded.To_String (Controller.Name);
end Get_Name;
-- -----------------------
-- Find the mapper associated with the given name.
-- Returns null if there is no mapper.
-- -----------------------
function Find_Mapper (Controller : in Mapper;
Name : in String;
Attribute : in Boolean := False) return Mapper_Access is
use type Ada.Strings.Unbounded.Unbounded_String;
Node : Mapper_Access := Controller.First_Child;
begin
if Node = null and Controller.Mapper /= null then
return Controller.Mapper.Find_Mapper (Name, Attribute);
end if;
while Node /= null loop
if not Attribute and Node.Is_Wildcard then
declare
Result : constant Mapper_Access := Node.Find_Mapper (Name, Attribute);
begin
if Result /= null then
return Result;
else
return Node;
end if;
end;
end if;
if Node.Name = Name then
if (Attribute = False and Node.Mapping = null)
or else not Node.Mapping.Is_Attribute then
return Node;
end if;
if Attribute and Node.Mapping.Is_Attribute then
return Node;
end if;
end if;
Node := Node.Next_Mapping;
end loop;
return null;
end Find_Mapper;
-- -----------------------
-- Find a path component representing a child mapper under <b>From</b> and
-- identified by the given <b>Name</b>. If the mapper is not found, a new
-- Mapper_Node is created.
-- -----------------------
procedure Find_Path_Component (From : in out Mapper'Class;
Name : in String;
Result : out Mapper_Access) is
use Ada.Strings.Unbounded;
Node : Mapper_Access := From.First_Child;
Previous : Mapper_Access := null;
Wildcard : constant Boolean := Name = "*";
begin
if Node = null then
Result := new Mapper;
Result.Name := To_Unbounded_String (Name);
Result.Is_Wildcard := Wildcard;
From.First_Child := Result;
return;
end if;
loop
if Node.Name = Name then
Result := Node;
return;
end if;
if Node.Next_Mapping = null then
Result := new Mapper;
Result.Name := To_Unbounded_String (Name);
Result.Is_Wildcard := Wildcard;
if Node.Is_Wildcard then
Result.Next_Mapping := Node;
if Previous = null then
From.First_Child := Result;
else
Previous.Next_Mapping := Result;
end if;
else
Node.Next_Mapping := Result;
end if;
return;
end if;
Previous := Node;
Node := Node.Next_Mapping;
end loop;
end Find_Path_Component;
-- -----------------------
-- Build the mapping tree that corresponds to the given <b>Path</b>.
-- Each path component is represented by a <b>Mapper_Node</b> element.
-- The node is created if it does not exists.
-- -----------------------
procedure Build_Path (Into : in out Mapper'Class;
Path : in String;
Last_Pos : out Natural;
Node : out Mapper_Access) is
Pos : Natural;
begin
Node := Into'Unchecked_Access;
Last_Pos := Path'First;
loop
Pos := Util.Strings.Index (Source => Path,
Char => '/',
From => Last_Pos);
if Pos = 0 then
Node.Find_Path_Component (Name => Path (Last_Pos .. Path'Last),
Result => Node);
Last_Pos := Path'Last + 1;
else
Node.Find_Path_Component (Name => Path (Last_Pos .. Pos - 1),
Result => Node);
Last_Pos := Pos + 1;
end if;
exit when Last_Pos > Path'Last;
end loop;
end Build_Path;
-- -----------------------
-- Add a mapping to associate the given <b>Path</b> to the mapper defined in <b>Map</b>.
-- The <b>Path</b> string describes the matching node using a simplified XPath notation.
-- Example:
-- info/first_name matches: <info><first_name>...</first_name></info>
-- info/a/b/name matches: <info><a><b><name>...</name></b></a></info>
-- */a/b/name matches: <i><i><j><a><b><name>...</name></b></a></j></i></i>
-- -----------------------
procedure Add_Mapping (Into : in out Mapper;
Path : in String;
Map : in Mapper_Access) is
procedure Copy (To : in Mapper_Access;
From : in Mapper_Access);
Node : Mapper_Access;
Last_Pos : Natural;
procedure Copy (To : in Mapper_Access;
From : in Mapper_Access) is
N : Mapper_Access;
Src : Mapper_Access := From;
begin
while Src /= null loop
N := Src.Clone;
N.Is_Clone := True;
N.Next_Mapping := To.First_Child;
To.First_Child := N;
if Src.First_Child /= null then
Copy (N, Src.First_Child);
end if;
Src := Src.Next_Mapping;
end loop;
end Copy;
begin
Log.Info ("Mapping '{0}' for mapper X", Path);
-- Find or build the mapping tree.
Into.Build_Path (Path, Last_Pos, Node);
if Last_Pos < Path'Last then
Log.Warn ("Ignoring the end of mapping path {0}", Path);
end if;
if Node.Mapper /= null then
Log.Warn ("Overriding the mapping {0} for mapper X", Path);
end if;
if Map.First_Child /= null then
Copy (Node, Map.First_Child);
else
Node.Mapper := Map;
end if;
end Add_Mapping;
procedure Add_Mapping (Into : in out Mapper;
Path : in String;
Map : in Mapping_Access) is
use Ada.Strings.Unbounded;
Node : Mapper_Access;
Last_Pos : Natural;
begin
Log.Info ("Mapping {0}", Path);
-- Find or build the mapping tree.
Into.Build_Path (Path, Last_Pos, Node);
if Last_Pos < Path'Last then
Log.Warn ("Ignoring the end of mapping path {0}", Path);
end if;
if Node.Mapping /= null then
Log.Warn ("Overriding the mapping {0} for mapper X", Path);
end if;
if Length (Node.Name) = 0 then
Log.Warn ("Mapped name is empty in mapping path {0}", Path);
elsif Element (Node.Name, 1) = '@' then
Delete (Node.Name, 1, 1);
Map.Is_Attribute := True;
else
Map.Is_Attribute := False;
end if;
Node.Mapping := Map;
Node.Mapper := Into'Unchecked_Access;
end Add_Mapping;
-- -----------------------
-- Clone the <b>Handler</b> instance and get a copy of that single object.
-- -----------------------
function Clone (Handler : in Mapper) return Mapper_Access is
Result : constant Mapper_Access := new Mapper;
begin
Result.Name := Handler.Name;
Result.Mapper := Handler.Mapper;
Result.Mapping := Handler.Mapping;
Result.Is_Proxy_Mapper := Handler.Is_Proxy_Mapper;
Result.Is_Clone := True;
Result.Is_Wildcard := Handler.Is_Wildcard;
return Result;
end Clone;
-- -----------------------
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
-- -----------------------
procedure Set_Member (Handler : in Mapper;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False;
Context : in out Util.Serialize.Contexts.Context'Class) is
Map : constant Mapper_Access := Mapper'Class (Handler).Find_Mapper (Name, Attribute);
begin
if Map /= null and then Map.Mapping /= null and then Map.Mapper /= null then
Map.Mapper.all.Execute (Map.Mapping.all, Context, Value);
end if;
end Set_Member;
procedure Start_Object (Handler : in Mapper;
Context : in out Util.Serialize.Contexts.Context'Class;
Name : in String) is
begin
if Handler.Mapper /= null then
Handler.Mapper.Start_Object (Context, Name);
end if;
end Start_Object;
procedure Finish_Object (Handler : in Mapper;
Context : in out Util.Serialize.Contexts.Context'Class;
Name : in String) is
begin
if Handler.Mapper /= null then
Handler.Mapper.Finish_Object (Context, Name);
end if;
end Finish_Object;
-- -----------------------
-- Dump the mapping tree on the logger using the INFO log level.
-- -----------------------
procedure Dump (Handler : in Mapper'Class;
Log : in Util.Log.Loggers.Logger'Class;
Prefix : in String := "") is
procedure Dump (Map : in Mapper'Class);
-- -----------------------
-- Dump the mapping description
-- -----------------------
procedure Dump (Map : in Mapper'Class) is
begin
if Map.Mapping /= null and then Map.Mapping.Is_Attribute then
Log.Info (" {0}@{1}", Prefix,
Ada.Strings.Unbounded.To_String (Map.Mapping.Name));
else
Log.Info (" {0}/{1}", Prefix, Ada.Strings.Unbounded.To_String (Map.Name));
Dump (Map, Log, Prefix & "/" & Ada.Strings.Unbounded.To_String (Map.Name));
end if;
end Dump;
begin
Iterate (Handler, Dump'Access);
end Dump;
procedure Iterate (Controller : in Mapper;
Process : not null access procedure (Map : in Mapper'Class)) is
Node : Mapper_Access := Controller.First_Child;
begin
-- Pass 1: process the attributes first
while Node /= null loop
if Node.Mapping /= null and then Node.Mapping.Is_Attribute then
Process.all (Node.all);
end if;
Node := Node.Next_Mapping;
end loop;
-- Pass 2: process the elements
Node := Controller.First_Child;
while Node /= null loop
if Node.Mapping = null or else not Node.Mapping.Is_Attribute then
Process.all (Node.all);
end if;
Node := Node.Next_Mapping;
end loop;
end Iterate;
-- -----------------------
-- Finalize the object and release any mapping.
-- -----------------------
overriding
procedure Finalize (Controller : in out Mapper) is
procedure Free is new Ada.Unchecked_Deallocation (Mapper'Class, Mapper_Access);
procedure Free is new Ada.Unchecked_Deallocation (Mapping'Class, Mapping_Access);
Node : Mapper_Access := Controller.First_Child;
Next : Mapper_Access;
begin
Controller.First_Child := null;
while Node /= null loop
Next := Node.Next_Mapping;
Free (Node);
Node := Next;
end loop;
if not Controller.Is_Clone then
Free (Controller.Mapping);
else
Controller.Mapping := null;
end if;
end Finalize;
end Util.Serialize.Mappers;
|
Fix mapping of attribute when wildcard mapping is also used
|
Fix mapping of attribute when wildcard mapping is also used
|
Ada
|
apache-2.0
|
flottokarotto/ada-util,Letractively/ada-util,flottokarotto/ada-util,Letractively/ada-util
|
63b31eeefdd7cf968a04142675204765e93e4da7
|
src/util-serialize-mappers-record_mapper.adb
|
src/util-serialize-mappers-record_mapper.adb
|
-----------------------------------------------------------------------
-- Util.Serialize.Mappers.Record_Mapper -- Mapper for record types
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Serialize.Contexts;
with Util.Strings.Transforms;
package body Util.Serialize.Mappers.Record_Mapper is
Key : Util.Serialize.Contexts.Data_Key;
-- -----------------------
-- Get the element object.
-- -----------------------
function Get_Element (Data : in Element_Data) return Element_Type_Access is
begin
return Data.Element;
end Get_Element;
-- -----------------------
-- Set the element object.
-- -----------------------
procedure Set_Element (Data : in out Element_Data;
Element : in Element_Type_Access) is
begin
Data.Element := Element;
end Set_Element;
-- -----------------------
-- Execute the mapping operation on the object associated with the current context.
-- The object is extracted from the context and the <b>Execute</b> operation is called.
-- -----------------------
procedure Execute (Handler : in Mapper;
Map : in Mapping'Class;
Ctx : in out Util.Serialize.Contexts.Context'Class;
Value : in Util.Beans.Objects.Object) is
D : constant Contexts.Data_Access := Ctx.Get_Data (Key);
begin
if not (D.all in Element_Data'Class) then
raise Util.Serialize.Contexts.No_Data;
end if;
declare
DE : constant Element_Data_Access := Element_Data'Class (D.all)'Access;
begin
if DE.Element = null then
raise Util.Serialize.Contexts.No_Data;
end if;
Handler.Execute (Map, DE.Element.all, Value);
end;
end Execute;
-- -----------------------
-- Add a mapping for setting a member. When the attribute rule defined by <b>Path</b>
-- is matched, the <b>Set_Member</b> procedure will be called with the value and the
-- <b>Field</b> identification.
-- -----------------------
procedure Add_Mapping (Into : in out Mapper;
Path : in String;
Field : in Fields) is
Map : constant Attribute_Mapping_Access := new Attribute_Mapping;
begin
Map.Index := Field;
Into.Add_Mapping (Path, Map.all'Access);
end Add_Mapping;
-- -----------------------
-- Add a mapping associated with the path and described by a mapper object.
-- The <b>Proxy</b> procedure is in charge of giving access to the target
-- object used by the <b>Map</b> mapper.
-- -----------------------
procedure Add_Mapping (Into : in out Mapper;
Path : in String;
Map : in Util.Serialize.Mappers.Mapper_Access;
Proxy : in Proxy_Object) is
M : Proxy_Mapper_Access := new Proxy_Mapper;
begin
M.Mapper := Map;
M.Execute := Execute'Access;
M.Is_Proxy_Mapper := True;
Into.Mapping.Insert (Key => Path, New_Item => M.all'Access);
end Add_Mapping;
--
procedure Bind (Into : in out Mapper;
Getter : in Get_Member_Access) is
begin
Into.Get_Member := Getter;
end Bind;
procedure Set_Member (Attr : in Attribute_Mapping;
Element : in out Element_Type;
Value : in Util.Beans.Objects.Object) is
begin
Set_Member (Element, Attr.Index, Value);
end Set_Member;
-- -----------------------
-- Set the attribute member described by the <b>Attr</b> mapping
-- into the value passed in <b>Element</b>.
-- -----------------------
procedure Set_Member (Attr : in Mapping'Class;
Element : in out Element_Type;
Value : in Util.Beans.Objects.Object) is
begin
if not (Attr in Attribute_Mapping) then
raise Mapping_Error;
end if;
Attribute_Mapping (Attr).Set_Member (Element, Value);
end Set_Member;
-- -----------------------
-- Set the element in the context.
-- -----------------------
procedure Set_Context (Ctx : in out Util.Serialize.Contexts.Context'Class;
Element : in Element_Type_Access) is
Data_Context : constant Element_Data_Access := new Element_Data;
begin
Data_Context.Element := Element;
Ctx.Set_Data (Key => Key, Content => Data_Context.all'Access);
end Set_Context;
-- -----------------------
-- Find the mapper associated with the given name.
-- Returns null if there is no mapper.
-- -----------------------
overriding
function Find_Mapping (Controller : in Proxy_Mapper;
Name : in String) return Mapping_Access is
Result : Mapping_Access := Controller.Mapper.Find_Mapping (Name);
begin
if Result /= null then
return Result;
else
return Util.Serialize.Mappers.Mapper (Controller).Find_Mapping (Name);
end if;
end Find_Mapping;
-- -----------------------
-- Find the mapper associated with the given name.
-- Returns null if there is no mapper.
-- -----------------------
overriding
function Find_Mapper (Controller : in Proxy_Mapper;
Name : in String) return Util.Serialize.Mappers.Mapper_Access is
Result : Util.Serialize.Mappers.Mapper_Access := Controller.Mapper.Find_Mapper (Name);
begin
if Result /= null then
return Result;
else
return Util.Serialize.Mappers.Mapper (Controller).Find_Mapper (Name);
end if;
end Find_Mapper;
-- -----------------------
-- Copy the mapping definitions defined by <b>From</b> into the target mapper
-- and use the <b>Process</b> procedure to give access to the element.
-- -----------------------
procedure Copy (Into : in out Mapper;
From : in Mapper;
Process : in Process_Object) is
Iter : Mapping_Map.Cursor := From.Rules.First;
begin
Into.Get_Member := From.Get_Member;
while Mapping_Map.Has_Element (Iter) loop
declare
Path : constant String := Mapping_Map.Key (Iter);
E : constant Mapping_Access := Mapping_Map.Element (Iter);
Map : constant Attribute_Mapping_Access := Attribute_Mapping'Class (E.all)'Access;
N : constant Attribute_Mapping_Access := new Attribute_Mapping;
begin
N.Index := Map.Index;
Into.Add_Mapping (Path, N.all'Access);
end;
Mapping_Map.Next (Iter);
end loop;
end Copy;
-- -----------------------
-- Build a default mapping based on the <b>Fields</b> enumeration.
-- The enumeration name is used for the mapping name with the optional <b>FIELD_</b>
-- prefix stripped.
-- -----------------------
procedure Add_Default_Mapping (Into : in out Mapper) is
use Util.Strings.Transforms;
begin
for Field in Fields'Range loop
declare
Name : constant String := To_Lower_Case (Fields'Image (Field));
begin
if Name (Name'First .. Name'First + 5) = "field_" then
Into.Add_Mapping (Name (Name'First + 6 .. Name'Last), Field);
else
Into.Add_Mapping (Name, Field);
end if;
end;
end loop;
end Add_Default_Mapping;
-- -----------------------
-- Write the element on the stream using the mapper description.
-- -----------------------
procedure Write (Handler : in Mapper;
Stream : in out Util.Serialize.IO.Output_Stream'Class;
Element : in Element_Type) is
Iter : Mapping_Map.Cursor := Handler.Rules.First;
begin
Stream.Start_Entity ("");
while Mapping_Map.Has_Element (Iter) loop
declare
Path : constant String := Mapping_Map.Key (Iter);
E : constant Mapping_Access := Mapping_Map.Element (Iter);
Map : constant Attribute_Mapping_Access := Attribute_Mapping'Class (E.all)'Access;
Val : constant Util.Beans.Objects.Object := Handler.Get_Member (Element, Map.Index);
begin
Stream.Write_Attribute (Name => Path, Value => Val);
end;
Mapping_Map.Next (Iter);
end loop;
Stream.End_Entity ("");
end Write;
begin
-- Allocate the unique data key.
Util.Serialize.Contexts.Allocate (Key);
end Util.Serialize.Mappers.Record_Mapper;
|
-----------------------------------------------------------------------
-- Util.Serialize.Mappers.Record_Mapper -- Mapper for record types
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Serialize.Contexts;
with Util.Strings.Transforms;
package body Util.Serialize.Mappers.Record_Mapper is
Key : Util.Serialize.Contexts.Data_Key;
-- -----------------------
-- Get the element object.
-- -----------------------
function Get_Element (Data : in Element_Data) return Element_Type_Access is
begin
return Data.Element;
end Get_Element;
-- -----------------------
-- Set the element object.
-- -----------------------
procedure Set_Element (Data : in out Element_Data;
Element : in Element_Type_Access) is
begin
Data.Element := Element;
end Set_Element;
-- -----------------------
-- Execute the mapping operation on the object associated with the current context.
-- The object is extracted from the context and the <b>Execute</b> operation is called.
-- -----------------------
procedure Execute (Handler : in Mapper;
Map : in Mapping'Class;
Ctx : in out Util.Serialize.Contexts.Context'Class;
Value : in Util.Beans.Objects.Object) is
D : constant Contexts.Data_Access := Ctx.Get_Data (Key);
begin
if not (D.all in Element_Data'Class) then
raise Util.Serialize.Contexts.No_Data;
end if;
declare
DE : constant Element_Data_Access := Element_Data'Class (D.all)'Access;
begin
if DE.Element = null then
raise Util.Serialize.Contexts.No_Data;
end if;
Handler.Execute (Map, DE.Element.all, Value);
end;
end Execute;
-- -----------------------
-- Add a mapping for setting a member. When the attribute rule defined by <b>Path</b>
-- is matched, the <b>Set_Member</b> procedure will be called with the value and the
-- <b>Field</b> identification.
-- -----------------------
procedure Add_Mapping (Into : in out Mapper;
Path : in String;
Field : in Fields) is
Map : constant Attribute_Mapping_Access := new Attribute_Mapping;
begin
Map.Index := Field;
Into.Add_Mapping (Path, Map.all'Access);
end Add_Mapping;
-- -----------------------
-- Add a mapping associated with the path and described by a mapper object.
-- The <b>Proxy</b> procedure is in charge of giving access to the target
-- object used by the <b>Map</b> mapper.
-- -----------------------
procedure Add_Mapping (Into : in out Mapper;
Path : in String;
Map : in Util.Serialize.Mappers.Mapper_Access;
Proxy : in Proxy_Object) is
M : Proxy_Mapper_Access := new Proxy_Mapper;
begin
M.Mapper := Map;
M.Execute := Proxy;
M.Is_Proxy_Mapper := True;
Into.Mapping.Insert (Key => Path, New_Item => M.all'Access);
end Add_Mapping;
--
procedure Bind (Into : in out Mapper;
Getter : in Get_Member_Access) is
begin
Into.Get_Member := Getter;
end Bind;
procedure Set_Member (Attr : in Attribute_Mapping;
Element : in out Element_Type;
Value : in Util.Beans.Objects.Object) is
begin
Set_Member (Element, Attr.Index, Value);
end Set_Member;
-- -----------------------
-- Set the attribute member described by the <b>Attr</b> mapping
-- into the value passed in <b>Element</b>.
-- -----------------------
procedure Set_Member (Attr : in Mapping'Class;
Element : in out Element_Type;
Value : in Util.Beans.Objects.Object) is
begin
if not (Attr in Attribute_Mapping) then
raise Mapping_Error;
end if;
Attribute_Mapping (Attr).Set_Member (Element, Value);
end Set_Member;
-- -----------------------
-- Set the element in the context.
-- -----------------------
procedure Set_Context (Ctx : in out Util.Serialize.Contexts.Context'Class;
Element : in Element_Type_Access) is
Data_Context : constant Element_Data_Access := new Element_Data;
begin
Data_Context.Element := Element;
Ctx.Set_Data (Key => Key, Content => Data_Context.all'Access);
end Set_Context;
-- -----------------------
-- Find the mapper associated with the given name.
-- Returns null if there is no mapper.
-- -----------------------
overriding
function Find_Mapping (Controller : in Proxy_Mapper;
Name : in String) return Mapping_Access is
Result : Mapping_Access := Controller.Mapper.Find_Mapping (Name);
begin
if Result /= null then
return Result;
else
return Util.Serialize.Mappers.Mapper (Controller).Find_Mapping (Name);
end if;
end Find_Mapping;
-- -----------------------
-- Find the mapper associated with the given name.
-- Returns null if there is no mapper.
-- -----------------------
overriding
function Find_Mapper (Controller : in Proxy_Mapper;
Name : in String) return Util.Serialize.Mappers.Mapper_Access is
Result : Util.Serialize.Mappers.Mapper_Access := Controller.Mapper.Find_Mapper (Name);
begin
if Result /= null then
return Result;
else
return Util.Serialize.Mappers.Mapper (Controller).Find_Mapper (Name);
end if;
end Find_Mapper;
-- -----------------------
-- Copy the mapping definitions defined by <b>From</b> into the target mapper
-- and use the <b>Process</b> procedure to give access to the element.
-- -----------------------
procedure Copy (Into : in out Mapper;
From : in Mapper;
Process : in Process_Object) is
Iter : Mapping_Map.Cursor := From.Rules.First;
begin
Into.Get_Member := From.Get_Member;
while Mapping_Map.Has_Element (Iter) loop
declare
Path : constant String := Mapping_Map.Key (Iter);
E : constant Mapping_Access := Mapping_Map.Element (Iter);
Map : constant Attribute_Mapping_Access := Attribute_Mapping'Class (E.all)'Access;
N : constant Attribute_Mapping_Access := new Attribute_Mapping;
begin
N.Index := Map.Index;
Into.Add_Mapping (Path, N.all'Access);
end;
Mapping_Map.Next (Iter);
end loop;
end Copy;
-- -----------------------
-- Build a default mapping based on the <b>Fields</b> enumeration.
-- The enumeration name is used for the mapping name with the optional <b>FIELD_</b>
-- prefix stripped.
-- -----------------------
procedure Add_Default_Mapping (Into : in out Mapper) is
use Util.Strings.Transforms;
begin
for Field in Fields'Range loop
declare
Name : constant String := To_Lower_Case (Fields'Image (Field));
begin
if Name (Name'First .. Name'First + 5) = "field_" then
Into.Add_Mapping (Name (Name'First + 6 .. Name'Last), Field);
else
Into.Add_Mapping (Name, Field);
end if;
end;
end loop;
end Add_Default_Mapping;
-- -----------------------
-- Write the element on the stream using the mapper description.
-- -----------------------
procedure Write (Handler : in Mapper;
Stream : in out Util.Serialize.IO.Output_Stream'Class;
Element : in Element_Type) is
Iter : Mapping_Map.Cursor := Handler.Rules.First;
begin
Stream.Start_Entity ("");
while Mapping_Map.Has_Element (Iter) loop
declare
Path : constant String := Mapping_Map.Key (Iter);
E : constant Mapping_Access := Mapping_Map.Element (Iter);
Map : constant Attribute_Mapping_Access := Attribute_Mapping'Class (E.all)'Access;
Val : constant Util.Beans.Objects.Object := Handler.Get_Member (Element, Map.Index);
begin
Stream.Write_Attribute (Name => Path, Value => Val);
end;
Mapping_Map.Next (Iter);
end loop;
Stream.End_Entity ("");
end Write;
begin
-- Allocate the unique data key.
Util.Serialize.Contexts.Allocate (Key);
end Util.Serialize.Mappers.Record_Mapper;
|
Fix compilation
|
Fix compilation
|
Ada
|
apache-2.0
|
flottokarotto/ada-util,flottokarotto/ada-util,Letractively/ada-util,Letractively/ada-util
|
17a8143009346aa8a1e749816b1274d2b298353c
|
src/register.ads
|
src/register.ads
|
package Register is
end Register;
|
Add register package
|
Add register package
|
Ada
|
mit
|
peterfrankjohnson/assembler
|
|
7d74b941e651dd6a0a5ba21f3aeb2ea7cb9c9f78
|
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.Streams;
package body Util.Serialize.IO.JSON is
use Ada.Strings.Unbounded;
procedure Error (Handler : in out Parser;
Message : in String) is
begin
raise Parse_Error with Natural'Image (Handler.Line_Number) & ":" & Message;
end Error;
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 number
procedure Parse_Number (P : in out Parser'Class;
Result : out Long_Long_Integer);
-- 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);
loop
Parse_Value (P, "");
Peek (P, Token);
exit when Token = T_RIGHT_BRACKET;
if Token /= T_COMMA then
P.Error ("Missing ']'");
end if;
end loop;
P.Finish_Array (Name);
when T_NULL =>
P.Set_Member (Name, Util.Beans.Objects.Null_Object);
when T_NUMBER =>
P.Set_Member (Name, Util.Beans.Objects.To_Object (P.Token));
when T_STRING =>
P.Set_Member (Name, Util.Beans.Objects.To_Object (P.Token));
when T_TRUE =>
P.Set_Member (Name, Util.Beans.Objects.To_Object (True));
when T_FALSE =>
P.Set_Member (Name, Util.Beans.Objects.To_Object (False));
when T_EOF =>
P.Error ("End of stream reached");
return;
when others =>
P.Error ("Invalid token");
end case;
end Parse_Value;
-- ------------------------------
-- Put back a token in the buffer.
-- ------------------------------
procedure Put_Back (P : in out Parser'Class;
Token : in Token_Type) is
begin
P.Pending_Token := Token;
end Put_Back;
-- ------------------------------
-- Parse the expression buffer to find the next token.
-- ------------------------------
procedure Peek (P : in out Parser'Class;
Token : out Token_Type) is
C, C1 : Character;
begin
-- If a token was put back, return it.
if P.Pending_Token /= T_EOF then
Token := P.Pending_Token;
P.Pending_Token := T_EOF;
return;
end if;
if P.Has_Pending_Char then
C := P.Pending_Char;
else
-- Skip white spaces
loop
Stream.Read (Char => C);
if C = Ada.Characters.Latin_1.LF then
P.Line_Number := P.Line_Number + 1;
else
exit when C /= ' '
and C /= Ada.Characters.Latin_1.CR and C /= Ada.Characters.Latin_1.HT;
end if;
end loop;
end if;
P.Has_Pending_Char := False;
-- See what we have and continue parsing.
case C is
-- Literal string using double quotes
-- Collect up to the end of the string and put
-- the result in the parser token result.
when '"' =>
Delete (P.Token, 1, Length (P.Token));
loop
Stream.Read (Char => C1);
if C1 = '\' then
Stream.Read (Char => C1);
case C1 is
when '"' | '\' | '/' =>
C := C1;
when 'b' =>
C1 := Ada.Characters.Latin_1.BS;
when 'f' =>
C1 := Ada.Characters.Latin_1.VT;
when 'n' =>
C1 := Ada.Characters.Latin_1.LF;
when 'r' =>
C1 := Ada.Characters.Latin_1.CR;
when 't' =>
C1 := Ada.Characters.Latin_1.HT;
when 'u' =>
null;
when others =>
null;
end case;
elsif C1 = C then
Token := T_STRING;
return;
end if;
Append (P.Token, C1);
end loop;
P.Error ("Missing '""' to terminate the string");
return;
-- 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;
-- ------------------------------
-- Parse a number
-- ------------------------------
procedure Parse_Number (P : in out Parser'Class;
Result : out Long_Long_Integer) is
Value : Long_Long_Integer := 0;
Num : Long_Long_Integer;
C : Character;
begin
loop
Stream.Read (Char => C);
exit when C not in '0' .. '9';
Num := Character'Pos (C) - Character'Pos ('0');
Value := Value * 10 + Num;
end loop;
Result := Value;
end Parse_Number;
begin
Parse (Handler);
end Parse;
end Util.Serialize.IO.JSON;
|
-----------------------------------------------------------------------
-- util-serialize-io-json -- JSON Serialization Driver
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Characters.Latin_1;
with Ada.IO_Exceptions;
with Util.Streams;
package body Util.Serialize.IO.JSON is
use Ada.Strings.Unbounded;
procedure Error (Handler : in out Parser;
Message : in String) is
begin
raise Parse_Error with Natural'Image (Handler.Line_Number) & ":" & Message;
end Error;
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 number
procedure Parse_Number (P : in out Parser'Class;
Result : out Long_Long_Integer);
-- 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, "");
Peek (P, Token);
exit when Token = T_RIGHT_BRACKET;
if Token /= T_COMMA then
P.Error ("Missing ']'");
end if;
end loop;
end if;
P.Finish_Array (Name);
when T_NULL =>
P.Set_Member (Name, Util.Beans.Objects.Null_Object);
when T_NUMBER =>
P.Set_Member (Name, Util.Beans.Objects.To_Object (P.Token));
when T_STRING =>
P.Set_Member (Name, Util.Beans.Objects.To_Object (P.Token));
when T_TRUE =>
P.Set_Member (Name, Util.Beans.Objects.To_Object (True));
when T_FALSE =>
P.Set_Member (Name, Util.Beans.Objects.To_Object (False));
when T_EOF =>
P.Error ("End of stream reached");
return;
when others =>
P.Error ("Invalid token");
end case;
end Parse_Value;
-- ------------------------------
-- Put back a token in the buffer.
-- ------------------------------
procedure Put_Back (P : in out Parser'Class;
Token : in Token_Type) is
begin
P.Pending_Token := Token;
end Put_Back;
-- ------------------------------
-- Parse the expression buffer to find the next token.
-- ------------------------------
procedure Peek (P : in out Parser'Class;
Token : out Token_Type) is
C, C1 : Character;
begin
-- If a token was put back, return it.
if P.Pending_Token /= T_EOF then
Token := P.Pending_Token;
P.Pending_Token := T_EOF;
return;
end if;
if P.Has_Pending_Char then
C := P.Pending_Char;
else
-- Skip white spaces
loop
Stream.Read (Char => C);
if C = Ada.Characters.Latin_1.LF then
P.Line_Number := P.Line_Number + 1;
else
exit when C /= ' '
and C /= Ada.Characters.Latin_1.CR and C /= Ada.Characters.Latin_1.HT;
end if;
end loop;
end if;
P.Has_Pending_Char := False;
-- See what we have and continue parsing.
case C is
-- Literal string using double quotes
-- Collect up to the end of the string and put
-- the result in the parser token result.
when '"' =>
Delete (P.Token, 1, Length (P.Token));
loop
Stream.Read (Char => C1);
if C1 = '\' then
Stream.Read (Char => C1);
case C1 is
when '"' | '\' | '/' =>
C := C1;
when 'b' =>
C1 := Ada.Characters.Latin_1.BS;
when 'f' =>
C1 := Ada.Characters.Latin_1.VT;
when 'n' =>
C1 := Ada.Characters.Latin_1.LF;
when 'r' =>
C1 := Ada.Characters.Latin_1.CR;
when 't' =>
C1 := Ada.Characters.Latin_1.HT;
when 'u' =>
null;
when others =>
null;
end case;
elsif C1 = C then
Token := T_STRING;
return;
end if;
Append (P.Token, C1);
end loop;
P.Error ("Missing '""' to terminate the string");
return;
-- 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;
-- ------------------------------
-- Parse a number
-- ------------------------------
procedure Parse_Number (P : in out Parser'Class;
Result : out Long_Long_Integer) is
Value : Long_Long_Integer := 0;
Num : Long_Long_Integer;
C : Character;
begin
loop
Stream.Read (Char => C);
exit when C not in '0' .. '9';
Num := Character'Pos (C) - Character'Pos ('0');
Value := Value * 10 + Num;
end loop;
Result := Value;
end Parse_Number;
begin
Parse (Handler);
end Parse;
end Util.Serialize.IO.JSON;
|
Fix parsing of empty JSON arrays
|
Fix parsing of empty JSON arrays
|
Ada
|
apache-2.0
|
Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util
|
e0c0d518354777d494bb839fd96c92b6cf20cbd1
|
src/wiki-plugins-variables.adb
|
src/wiki-plugins-variables.adb
|
-----------------------------------------------------------------------
-- wiki-plugins-variables -- Variables plugin
-- 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 Wiki.Filters.Variables;
package body Wiki.Plugins.Variables is
-- ------------------------------
-- Set or update a variable in the `Wiki.Filters.Variable` filter.
-- ------------------------------
overriding
procedure Expand (Plugin : in out Variable_Plugin;
Document : in out Wiki.Documents.Document;
Params : in out Wiki.Attributes.Attribute_List;
Context : in Plugin_Context) is
pragma Unreferenced (Plugin, Document);
begin
if Wiki.Attributes.Length (Params) >= 3 then
declare
First : Wiki.Attributes.Cursor := Wiki.Attributes.First (Params);
Second : Wiki.Attributes.Cursor;
begin
Wiki.Attributes.Next (First);
Second := First;
Wiki.Attributes.Next (Second);
Wiki.Filters.Variables.Add_Variable (Context.Filters,
Wiki.Attributes.Get_Wide_Value (First),
Wiki.Attributes.Get_Wide_Value (Second));
end;
end if;
end Expand;
end Wiki.Plugins.Variables;
|
Implement the variables plugin to set variables from wiki text
|
Implement the variables plugin to set variables from wiki text
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
|
93f12bc6d342452b278fe76af7027053ef851e2c
|
src/ado-datasets.adb
|
src/ado-datasets.adb
|
-----------------------------------------------------------------------
-- ado-datasets -- Datasets
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Objects.Time;
with ADO.Schemas;
with ADO.Statements;
package body ADO.Datasets is
-- ------------------------------
-- Execute the SQL query on the database session and populate the dataset.
-- The column names are used to setup the dataset row bean definition.
-- ------------------------------
procedure List (Into : in out Dataset;
Session : in out ADO.Sessions.Session'Class;
Query : in ADO.Queries.Context'Class) is
procedure Fill (Data : in out Util.Beans.Objects.Datasets.Object_Array);
Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query);
procedure Fill (Data : in out Util.Beans.Objects.Datasets.Object_Array) is
use ADO.Schemas;
begin
for I in Data'Range loop
case Stmt.Get_Column_Type (I - 1) is
-- Boolean column
when T_BOOLEAN =>
Data (I) := Util.Beans.Objects.To_Object (Stmt.Get_Boolean (I - 1));
when T_TINYINT | T_SMALLINT | T_INTEGER | T_LONG_INTEGER | T_YEAR =>
Data (I) := Util.Beans.Objects.To_Object (Stmt.Get_Integer (I - 1));
when T_FLOAT | T_DOUBLE | T_DECIMAL =>
Data (I) := Util.Beans.Objects.Null_Object;
when T_ENUM =>
Data (I) := Util.Beans.Objects.To_Object (Stmt.Get_String (I - 1));
when T_TIME | T_DATE | T_DATE_TIME | T_TIMESTAMP =>
Data (I) := Util.Beans.Objects.Time.To_Object (Stmt.Get_Time (I - 1));
when T_CHAR | T_VARCHAR =>
Data (I) := Util.Beans.Objects.To_Object (Stmt.Get_String (I - 1));
when T_BLOB =>
Data (I) := Util.Beans.Objects.Null_Object;
when T_SET | T_UNKNOWN | T_NULL =>
Data (I) := Util.Beans.Objects.Null_Object;
end case;
end loop;
end Fill;
begin
Stmt.Execute;
Into.Clear;
if Stmt.Has_Elements then
for I in 1 .. Stmt.Get_Column_Count loop
Into.Add_Column (Stmt.Get_Column_Name (I - 1));
end loop;
while Stmt.Has_Elements loop
Into.Append (Fill'Access);
Stmt.Next;
end loop;
end if;
end List;
end ADO.Datasets;
|
Implement the List operation to setup the database with the SQL query result
|
Implement the List operation to setup the database with the SQL query result
|
Ada
|
apache-2.0
|
Letractively/ada-ado
|
|
cf6db2511c952df1c22d922274af9b688e684266
|
src/asis/a4g-contt-sd.ads
|
src/asis/a4g-contt-sd.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . C O N T T . S D --
-- --
-- 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 defines the procedures which scans the tree search paths for
-- a given Context and analyses the availible tree files
with Namet; use Namet;
package A4G.Contt.SD is
First_Tree_File : Name_Id := First_Name_Id;
Last_Tree_File : Name_Id := First_Name_Id - 1;
-- Indexes of the first and the last tree file candidates, which were
-- found during the last scanning of the tree search path of some
-- directory. Are set by Scan_Tree_Files below. These variables are
-- undefinite
-- SHOULD WE MOVE THESE VARIABLES IN THE BODY
-- AND EVEN MORE - DO WE REALLY NEED THEM AT ALL??!!
procedure Scan_Tree_Files_New (C : Context_Id);
-- Stores the names of the tree files making up the Context C in the Tree
-- table for C. Every tree file name is stored only once.
-- In All_Trees Context mode it scans the tree search path, using the same
-- approach for the tree files with the same name as GNAT does for source
-- files in the source search path. In N_Trees mode it scans the Parametes
-- string set when C was associated. In this case, if the name of the same
-- tree file is given more than once, but in diffrent forms (for example
-- ../my_dir/foo.ats and ../../my_home_dir/my_dir/foo.ats), all these
-- different names of the same tree file will be stored in the tree table
procedure Investigate_Trees_New (C : Context_Id);
-- This procedure implements the second step of opening a Context. It uses
-- the names of the tree files in the Context Tree Table. For every tree
-- file, it reads it in and extracts some information about compilation
-- units presented by this file. It also makes the consistency check.
-- Checks which are made by this procedure depend on the context options
-- which were set when C was associated.
--
-- Is this package the right location for this procedure???
procedure Scan_Units_New;
-- Scans the currently accessed tree which was readed in by the
-- immediately preceding call to Read_and_Check_New. If a unit is "new"
-- (that is, if it has not already been encountered during opening a
-- Context), all the black-box information is computed and stored in the
-- Context table. Otherwise (that is, if the unit is already "known")
-- the consistency check is made.
--
-- When this procedure raises ASIS_Failed, it forms the Diagnosis string
-- on befalf on Asis.Ada_Environments.Open
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
|
|
5707a3a9d59ffb8137e908f25a4cb136ca29b372
|
src/asis/a4g-contt-sd.ads
|
src/asis/a4g-contt-sd.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . C O N T T . S D --
-- --
-- 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 defines the procedures which scans the tree search paths for
-- a given Context and analyses the availible tree files
with Namet; use Namet;
package A4G.Contt.SD is
First_Tree_File : Name_Id := First_Name_Id;
Last_Tree_File : Name_Id := First_Name_Id - 1;
-- Indexes of the first and the last tree file candidates, which were
-- found during the last scanning of the tree search path of some
-- directory. Are set by Scan_Tree_Files below. These variables are
-- undefinite
-- SHOULD WE MOVE THESE VARIABLES IN THE BODY
-- AND EVEN MORE - DO WE REALLY NEED THEM AT ALL??!!
procedure Scan_Tree_Files_New (C : Context_Id);
-- Stores the names of the tree files making up the Context C in the Tree
-- table for C. Every tree file name is stored only once.
-- In All_Trees Context mode it scans the tree search path, using the same
-- approach for the tree files with the same name as GNAT does for source
-- files in the source search path. In N_Trees mode it scans the Parametes
-- string set when C was associated. In this case, if the name of the same
-- tree file is given more than once, but in diffrent forms (for example
-- ../my_dir/foo.ats and ../../my_home_dir/my_dir/foo.ats), all these
-- different names of the same tree file will be stored in the tree table
procedure Investigate_Trees_New (C : Context_Id);
-- This procedure implements the second step of opening a Context. It uses
-- the names of the tree files in the Context Tree Table. For every tree
-- file, it reads it in and extracts some information about compilation
-- units presented by this file. It also makes the consistency check.
-- Checks which are made by this procedure depend on the context options
-- which were set when C was associated.
--
-- Is this package the right location for this procedure???
procedure Scan_Units_New;
-- Scans the currently accessed tree which was readed in by the
-- immediately preceding call to Read_and_Check_New. If a unit is "new"
-- (that is, if it has not already been encountered during opening a
-- Context), all the black-box information is computed and stored in the
-- Context table. Otherwise (that is, if the unit is already "known")
-- the consistency check is made.
--
-- When this procedure raises ASIS_Failed, it forms the Diagnosis string
-- on befalf on Asis.Ada_Environments.Open
end A4G.Contt.SD;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
3b59c9930c47faaf0f7c439ac927363fff3e3174
|
src/asf-components-widgets-gravatars.adb
|
src/asf-components-widgets-gravatars.adb
|
-----------------------------------------------------------------------
-- components-widgets-gravatars -- Gravatar 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.Strings.Transforms;
with GNAT.MD5;
with ASF.Utils;
with ASF.Contexts.Writer;
package body ASF.Components.Widgets.Gravatars is
IMAGE_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
-- ------------------------------
-- Given an Email address, return the Gravatar link to the user image.
-- (See http://en.gravatar.com/site/implement/hash/ and
-- http://en.gravatar.com/site/implement/images/)
-- ------------------------------
function Get_Link (Email : in String;
Secure : in Boolean := False) return String is
E : constant String := Util.Strings.Transforms.To_Lower_Case (Email);
C : constant GNAT.MD5.Message_Digest := GNAT.MD5.Digest (E);
begin
if Secure then
return "https://secure.gravatar.com/avatar/" & C;
else
return "http://www.gravatar.com/avatar/" & C;
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 UIGravatar;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
begin
if UI.Is_Rendered (Context) then
Writer.Start_Element ("img");
UI.Render_Attributes (Context, IMAGE_ATTRIBUTE_NAMES, Writer);
declare
Email : constant String := UI.Get_Attribute ("email", Context, "");
Size : constant Natural := UI.Get_Attribute ("size", Context, 60);
Default : constant String := UI.Get_Attribute ("default", Context, "identicon");
Secure : constant Boolean := UI.Get_Attribute ("secure", Context, False);
D : constant String := Util.Strings.Image (Size);
begin
Writer.Write_Attribute ("width", D);
Writer.Write_Attribute ("height", D);
Writer.Write_Attribute ("src", Get_Link (Email, Secure)
& "?d=" & Default & "&s=" & D);
end;
Writer.End_Element ("img");
end if;
end Encode_Begin;
begin
Utils.Set_Text_Attributes (IMAGE_ATTRIBUTE_NAMES);
end ASF.Components.Widgets.Gravatars;
|
Implement the UI gravatar component
|
Implement the UI gravatar component
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
|
a824bdb40f380bc024645528b141559565b31ea8
|
regtests/asf-navigations-tests.ads
|
regtests/asf-navigations-tests.ads
|
-----------------------------------------------------------------------
-- 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.Tests;
package ASF.Navigations.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Initialize the test application
overriding
procedure Set_Up (T : in out Test);
-- Test a form navigation with an exact match (view, outcome, action).
procedure Test_Exact_Navigation (T : in out Test);
-- Test a form navigation with a partial match (view, outcome).
procedure Test_Partial_Navigation (T : in out Test);
-- Test a form navigation with a exception match (view, outcome).
procedure Test_Exception_Navigation (T : in out Test);
-- 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);
end ASF.Navigations.Tests;
|
Add navigation rule unit test
|
Add navigation rule unit test
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
|
a4f2fc774afc285a514d336a2280fae6554578fd
|
tools/druss-commands-devices.adb
|
tools/druss-commands-devices.adb
|
-----------------------------------------------------------------------
-- druss-commands-devices -- Print information about the devices
-- 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.Properties;
with Bbox.API;
with Druss.Gateways;
package body Druss.Commands.Devices is
-- ------------------------------
-- Execute the wifi 'status' command to print the Wifi current status.
-- ------------------------------
procedure Do_List (Command : in Command_Type;
Args : in Argument_List'Class;
Context : in out Context_Type) is
pragma Unreferenced (Command);
Console : constant Druss.Commands.Consoles.Console_Access := Context.Console;
procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type) is
procedure Print_Device (Manager : in Util.Properties.Manager;
Name : in String) is
Link : constant String := Manager.Get (Name & ".link", "");
Kind : constant String := Manager.Get (Name & ".devicetype", "");
begin
if Manager.Get (Name & ".active", "") = "0" then
return;
end if;
Console.Start_Row;
Console.Print_Field (F_BBOX_IP_ADDR, Gateway.Ip);
Console.Print_Field (F_IP_ADDR, Manager.Get (Name & ".ipaddress", ""));
Console.Print_Field (F_ETHERNET, Manager.Get (Name & ".macaddress", ""));
Console.Print_Field (F_HOSTNAME, Manager.Get (Name & ".hostname", ""));
Console.Print_Field (F_ACTIVE, Manager.Get (Name & ".active", ""));
Console.Print_Field (F_DEVTYPE, (if Kind = "STB" then "STB" else ""));
if Link = "Ethernet" then
Console.Print_Field (F_LINK, Link & " port "
& Manager.Get (Name & ".ethernet.logicalport", ""));
else
Console.Print_Field (F_LINK, Link & " RSSI "
& Manager.Get (Name & ".wireless.rssi0", ""));
end if;
Console.End_Row;
end Print_Device;
begin
Gateway.Refresh;
Bbox.API.Iterate (Gateway.Hosts, "hosts.list", Print_Device'Access);
end Box_Status;
begin
Console.Start_Title;
Console.Print_Title (F_BBOX_IP_ADDR, "Bbox IP", 16);
Console.Print_Title (F_IP_ADDR, "Device IP", 16);
Console.Print_Title (F_ETHERNET, "Ethernet", 20);
Console.Print_Title (F_HOSTNAME, "Hostname", 28);
Console.Print_Title (F_DEVTYPE, "Type", 6);
-- Console.Print_Title (F_ACTIVE, "Active", 8);
Console.Print_Title (F_LINK, "Link", 18);
Console.End_Title;
Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Box_Status'Access);
end Do_List;
-- Execute a status command to report information about the Bbox.
overriding
procedure Execute (Command : in Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type) is
pragma Unreferenced (Name);
begin
Command.Do_List (Args, Context);
end Execute;
-- Write the help associated with the command.
overriding
procedure Help (Command : in Command_Type;
Context : in out Context_Type) is
pragma Unreferenced (Command);
Console : constant Druss.Commands.Consoles.Console_Access := Context.Console;
begin
Console.Notice (N_HELP, "devices: Print information about the devices");
Console.Notice (N_HELP, "Usage: devices [options]");
Console.Notice (N_HELP, "");
end Help;
end Druss.Commands.Devices;
|
Implement the device command to list the devices and give some information
|
Implement the device command to list the devices and give some information
|
Ada
|
apache-2.0
|
stcarrez/bbox-ada-api
|
|
51c9632fe29e17b94da6c6a49003f9c2645bac35
|
regtests/asf-converters-tests.adb
|
regtests/asf-converters-tests.adb
|
-----------------------------------------------------------------------
-- Faces Context Tests - Unit tests for ASF.Contexts.Faces
-- Copyright (C) 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.Calendar;
with Ada.Calendar.Formatting;
with Util.Beans.Objects.Time;
with Util.Test_Caller;
with ASF.Tests;
with ASF.Components.Html.Text;
with ASF.Converters.Dates;
package body ASF.Converters.Tests is
use Util.Tests;
use ASF.Converters.Dates;
package Caller is new Util.Test_Caller (Test, "Converters");
procedure Test_Date_Conversion (T : in out Test;
Date_Style : in Dates.Style_Type;
Time_Style : in Dates.Style_Type;
Expect : in String);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
-- To document what is tested, register the test methods for each
-- operation that is tested.
Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Date, Short)",
Test_Date_Short_Converter'Access);
Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Date, Medium)",
Test_Date_Medium_Converter'Access);
Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Date, Long)",
Test_Date_Long_Converter'Access);
Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Date, Full)",
Test_Date_Full_Converter'Access);
Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Time, Short)",
Test_Time_Short_Converter'Access);
Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Time, Medium)",
Test_Time_Medium_Converter'Access);
Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Time, Long)",
Test_Time_Long_Converter'Access);
end Add_Tests;
-- ------------------------------
-- Test getting an attribute from the faces context.
-- ------------------------------
procedure Test_Date_Conversion (T : in out Test;
Date_Style : in Dates.Style_Type;
Time_Style : in Dates.Style_Type;
Expect : in String) is
Ctx : aliased ASF.Contexts.Faces.Faces_Context;
UI : ASF.Components.Html.Text.UIOutput;
C : ASF.Converters.Dates.Date_Converter_Access;
D : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (2011, 11, 19,
3, 4, 5);
begin
T.Setup (Ctx);
ASF.Contexts.Faces.Set_Current (Ctx'Unchecked_Access, ASF.Tests.Get_Application.all'Access);
if Date_Style = Dates.DEFAULT then
C := ASF.Converters.Dates.Create_Date_Converter (Date => Date_Style,
Time => Time_Style,
Format => ASF.Converters.Dates.TIME,
Locale => "en",
Pattern => "");
elsif Time_Style = Dates.DEFAULT then
C := ASF.Converters.Dates.Create_Date_Converter (Date => Date_Style,
Time => Time_Style,
Format => ASF.Converters.Dates.DATE,
Locale => "en",
Pattern => "");
else
C := ASF.Converters.Dates.Create_Date_Converter (Date => Date_Style,
Time => Time_Style,
Format => ASF.Converters.Dates.BOTH,
Locale => "en",
Pattern => "");
end if;
UI.Set_Converter (C.all'Access);
declare
R : constant String := C.To_String (Ctx, UI, Util.Beans.Objects.Time.To_Object (D));
begin
Util.Tests.Assert_Equals (T, Expect, R, "Invalid date conversion");
end;
end Test_Date_Conversion;
-- ------------------------------
-- Test the date short converter.
-- ------------------------------
procedure Test_Date_Short_Converter (T : in out Test) is
begin
Test_Date_Conversion (T, ASF.Converters.Dates.SHORT, ASF.Converters.Dates.DEFAULT,
"19/11/2011");
end Test_Date_Short_Converter;
-- ------------------------------
-- Test the date medium converter.
-- ------------------------------
procedure Test_Date_Medium_Converter (T : in out Test) is
begin
Test_Date_Conversion (T, ASF.Converters.Dates.MEDIUM, ASF.Converters.Dates.DEFAULT,
"Nov 19, 2011");
end Test_Date_Medium_Converter;
-- ------------------------------
-- Test the date long converter.
-- ------------------------------
procedure Test_Date_Long_Converter (T : in out Test) is
begin
Test_Date_Conversion (T, ASF.Converters.Dates.LONG, ASF.Converters.Dates.DEFAULT,
"November 19, 2011");
end Test_Date_Long_Converter;
-- ------------------------------
-- Test the date full converter.
-- ------------------------------
procedure Test_Date_Full_Converter (T : in out Test) is
begin
Test_Date_Conversion (T, ASF.Converters.Dates.FULL, ASF.Converters.Dates.DEFAULT,
"Saturday, November 19, 2011");
end Test_Date_Full_Converter;
-- ------------------------------
-- Test the time short converter.
-- ------------------------------
procedure Test_Time_Short_Converter (T : in out Test) is
begin
Test_Date_Conversion (T, ASF.Converters.Dates.DEFAULT, ASF.Converters.Dates.SHORT,
"03:04");
end Test_Time_Short_Converter;
-- ------------------------------
-- Test the time short converter.
-- ------------------------------
procedure Test_Time_Medium_Converter (T : in out Test) is
begin
Test_Date_Conversion (T, ASF.Converters.Dates.DEFAULT, ASF.Converters.Dates.MEDIUM,
"03:04");
end Test_Time_Medium_Converter;
-- ------------------------------
-- Test the time long converter.
-- ------------------------------
procedure Test_Time_Long_Converter (T : in out Test) is
begin
Test_Date_Conversion (T, ASF.Converters.Dates.DEFAULT, ASF.Converters.Dates.LONG,
"03:04:05");
end Test_Time_Long_Converter;
end ASF.Converters.Tests;
|
Implement some unit tests for date and time conversion
|
Implement some unit tests for date and time conversion
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
|
ec5ab60ca85b130d764d354e8a048886e1f7f618
|
src/asis/asis-implementation.adb
|
src/asis/asis-implementation.adb
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A S I S . I M P L E M E N T A T I O N --
-- --
-- Copyright (C) 1995-2007, Free Software Foundation, Inc. --
-- --
-- ASIS-for-GNAT is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 2, or (at your option) any later --
-- version. ASIS-for-GNAT is distributed in the hope that it will be use- --
-- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- --
-- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General --
-- Public License for more details. You should have received a copy of the --
-- GNU General Public License distributed with ASIS-for-GNAT; see file --
-- COPYING. If not, write to the Free Software Foundation, 51 Franklin --
-- Street, Fifth Floor, Boston, MA 02110-1301, USA. --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the --
-- Software Engineering Laboratory of the Swiss Federal Institute of --
-- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the --
-- Scientific Research Computer Center of Moscow State University (SRCC --
-- MSU), Russia, with funding partially provided by grants from the Swiss --
-- National Science Foundation and the Swiss Academy of Engineering --
-- Sciences. ASIS-for-GNAT is now maintained by AdaCore --
-- (http://www.adaccore.com). --
-- --
------------------------------------------------------------------------------
with Ada.Characters.Handling; use Ada.Characters.Handling;
with Ada.Strings; use Ada.Strings;
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
with Asis.Errors; use Asis.Errors;
with Asis.Exceptions; use Asis.Exceptions;
with A4G.A_Debug; use A4G.A_Debug;
with A4G.A_Opt; use A4G.A_Opt;
with A4G.Contt; use A4G.Contt;
with A4G.Defaults;
with A4G.Vcheck; use A4G.Vcheck;
with A4G.A_Osint; use A4G.A_Osint;
with Gnatvsn;
with Opt;
package body Asis.Implementation is
Package_Name : constant String := "Asis.Implementation.";
----------------------
-- Asis_Implementor --
----------------------
function ASIS_Implementor return Wide_String is
begin
return "AdaCore (http://www.adacore.com)";
end ASIS_Implementor;
----------------------------------
-- ASIS_Implementor_Information --
----------------------------------
function ASIS_Implementor_Information return Wide_String is
begin
return
"Copyright (C) 1995-" &
To_Wide_String (Gnatvsn.Current_Year) &
", Free Software Foundation";
end ASIS_Implementor_Information;
------------------------------
-- ASIS_Implementor_Version --
------------------------------
function ASIS_Implementor_Version return Wide_String is
GNAT_Version : constant String := Gnatvsn.Gnat_Version_String;
First_Idx : constant Positive := GNAT_Version'First;
Last_Idx : Positive := GNAT_Version'Last;
Minus_Detected : Boolean := False;
begin
for J in reverse GNAT_Version'Range loop
if GNAT_Version (J) = '-' then
Last_Idx := J - 1;
Minus_Detected := True;
exit;
end if;
end loop;
if Minus_Detected then
return ASIS_Version & " for GNAT " &
To_Wide_String (GNAT_Version (First_Idx .. Last_Idx)) & ")";
else
return ASIS_Version & " for GNAT " &
To_Wide_String (GNAT_Version (First_Idx .. Last_Idx));
end if;
end ASIS_Implementor_Version;
------------------
-- ASIS_Version --
------------------
function ASIS_Version return Wide_String is
begin
return "ASIS 2.0.R";
end ASIS_Version;
---------------
-- Diagnosis --
---------------
function Diagnosis return Wide_String is
begin
-- The ASIS Diagnosis string uses only the first 256 values of
-- Wide_Character type
return To_Wide_String (Diagnosis_Buffer (1 .. Diagnosis_Len));
end Diagnosis;
--------------
-- Finalize --
--------------
procedure Finalize (Parameters : Wide_String := "") is
S_Parameters : constant String := Trim (To_String (Parameters), Both);
-- all the valid actuals for Parametes should contain only
-- characters from the first 256 values of Wide_Character type
begin
if not A4G.A_Opt.Is_Initialized then
return;
end if;
if Debug_Flag_C or else
Debug_Lib_Model or else
Debug_Mode
then
Print_Context_Info;
end if;
if S_Parameters'Length > 0 then
Process_Finalization_Parameters (S_Parameters);
end if;
A4G.Contt.Finalize;
A4G.A_Opt.Set_Off;
A4G.A_Debug.Set_Off;
A4G.A_Opt.Is_Initialized := False;
exception
when ASIS_Failed =>
A4G.A_Opt.Set_Off;
A4G.A_Debug.Set_Off;
A4G.A_Opt.Is_Initialized := False;
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information (Outer_Call =>
Package_Name & "Finalize");
end if;
raise;
when Ex : others =>
A4G.A_Opt.Set_Off;
A4G.A_Debug.Set_Off;
A4G.A_Opt.Is_Initialized := False;
Report_ASIS_Bug
(Query_Name => Package_Name & "Finalize",
Ex => Ex);
end Finalize;
----------------
-- Initialize --
----------------
procedure Initialize (Parameters : Wide_String := "") is
S_Parameters : constant String := Trim (To_String (Parameters), Both);
-- all the valid actuals for Parametes should contain only
-- characters from the first 256 values of Wide_Character type
begin
if A4G.A_Opt.Is_Initialized then
return;
end if;
if not A4G.A_Opt.Was_Initialized_At_Least_Once then
Opt.Maximum_File_Name_Length := Get_Max_File_Name_Length;
A4G.A_Opt.Was_Initialized_At_Least_Once := True;
end if;
if S_Parameters'Length > 0 then
Process_Initialization_Parameters (S_Parameters);
end if;
A4G.Contt.Initialize;
A4G.Defaults.Initialize;
A4G.A_Opt.Is_Initialized := True;
exception
when ASIS_Failed =>
A4G.A_Opt.Set_Off;
A4G.A_Debug.Set_Off;
A4G.A_Opt.Is_Initialized := False;
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information (Outer_Call =>
Package_Name & "Initialize");
end if;
raise;
when Ex : others =>
A4G.A_Opt.Set_Off;
A4G.A_Debug.Set_Off;
A4G.A_Opt.Is_Initialized := False;
Report_ASIS_Bug
(Query_Name => Package_Name & "Initialize",
Ex => Ex);
end Initialize;
------------------
-- Is_Finalized --
------------------
function Is_Finalized return Boolean is
begin
return not A4G.A_Opt.Is_Initialized;
end Is_Finalized;
--------------------
-- Is_Initialized --
--------------------
function Is_Initialized return Boolean is
begin
return A4G.A_Opt.Is_Initialized;
end Is_Initialized;
----------------
-- Set_Status --
----------------
procedure Set_Status
(Status : Asis.Errors.Error_Kinds := Asis.Errors.Not_An_Error;
Diagnosis : Wide_String := "")
is
begin
A4G.Vcheck.Set_Error_Status (Status => Status,
Diagnosis => To_String (Diagnosis));
end Set_Status;
------------
-- Status --
------------
function Status return Asis.Errors.Error_Kinds is
begin
return Status_Indicator;
end Status;
end Asis.Implementation;
|
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
|
|
53fee76d946c7d27f1b8185389e412d42a910285
|
src/asf-security-filters-oauth.adb
|
src/asf-security-filters-oauth.adb
|
-----------------------------------------------------------------------
-- 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 Util.Log.Loggers;
with ASF.Applications.Main;
with Security.Contexts;
with Security.Policies.URLs;
package body ASF.Security.Filters.OAuth is
use Ada.Strings.Unbounded;
use Servers;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Filters.OAuth");
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
procedure Initialize (Server : in out Auth_Filter;
Config : in ASF.Servlets.Filter_Config) is
use ASF.Applications;
Context : constant Servlets.Servlet_Registry_Access := Servlets.Get_Servlet_Context (Config);
begin
if Context.all in Main.Application'Class then
Server.Set_Permission_Manager (Main.Application'Class (Context.all).Get_Security_Manager);
end if;
end Initialize;
-- ------------------------------
-- 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) is
begin
Filter.Manager := Manager;
end Set_Permission_Manager;
function Get_Access_Token (Request : in ASF.Requests.Request'Class) return String is
Header : constant String := Request.Get_Header (AUTHORIZATION_HEADER_NAME);
begin
if Header'Length > 0 then
return Header;
end if;
return Header;
end Get_Access_Token;
-- ------------------------------
-- 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) is
use Ada.Strings.Unbounded;
use Policies.URLs;
use type Policies.Policy_Manager_Access;
Servlet : constant String := Request.Get_Servlet_Path;
URL : constant String := Servlet & Request.Get_Path_Info;
begin
if F.Realm = null then
Log.Error ("Deny access on {0} due to missing realm", URL);
Auth_Filter'Class (F).Do_Deny (Request, Response);
return;
end if;
declare
Bearer : constant String := Get_Access_Token (Request);
Auth : Principal_Access;
Grant : Servers.Grant_Type;
Context : aliased Contexts.Security_Context;
begin
if Bearer'Length = 0 then
Log.Info ("Ask authentication on {0} due to missing access token", URL);
Auth_Filter'Class (F).Do_Login (Request, Response);
return;
end if;
F.Realm.Authenticate (Bearer, Grant);
if Grant.Status /= Valid_Grant then
Log.Info ("Ask authentication on {0} due to missing access token", URL);
Auth_Filter'Class (F).Do_Deny (Request, Response);
return;
end if;
-- Request is authorized, proceed to the next filter.
ASF.Servlets.Do_Filter (Chain => Chain,
Request => Request,
Response => Response);
end;
end Do_Filter;
-- ------------------------------
-- 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) is
pragma Unreferenced (F, Request);
begin
Response.Send_Error (ASF.Responses.SC_UNAUTHORIZED);
end Do_Login;
-- ------------------------------
-- 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) is
pragma Unreferenced (Request);
begin
Response.Add_Header (WWW_AUTHENTICATE_HEADER_NAME,
"Bearer realm=""" & To_String (F.Realm_URL)
& """, error=""invalid_token""");
Response.Set_Status (ASF.Responses.SC_FORBIDDEN);
end Do_Deny;
end ASF.Security.Filters.OAuth;
|
Implement the Auth_Filter operations with verification of the access_token for the OAuth API call operation
|
Implement the Auth_Filter operations with verification of the access_token
for the OAuth API call operation
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
|
f127cafbb7607a998e3d121600379ed5bfb6b569
|
samples/date.adb
|
samples/date.adb
|
-----------------------------------------------------------------------
-- date -- Print the date
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Calendar;
with Ada.Strings.Unbounded;
with GNAT.Command_Line;
with Util.Log.Loggers;
with Util.Dates.Formats;
with Util.Properties.Bundles;
procedure Date is
use Util.Log.Loggers;
use Ada.Strings.Unbounded;
use Util.Properties.Bundles;
use GNAT.Command_Line;
Log : constant Logger := Create ("log", "samples/log4j.properties");
Factory : Util.Properties.Bundles.Loader;
Bundle : Util.Properties.Bundles.Manager;
Locale : Unbounded_String := To_Unbounded_String ("en");
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
-- Load the bundles from the current directory
Initialize (Factory, "samples/;bundles");
begin
Load_Bundle (Factory, "dates", To_String (Locale), Bundle);
exception
when NO_BUNDLE =>
Log.Error ("There is no bundle: {0}", "dates");
end;
loop
case Getopt ("h l: locale: help") is
when ASCII.NUL =>
exit;
when 'l' =>
Locale := To_Unbounded_String (Parameter);
when others =>
Log.Info ("Usage: date -l locale format");
return;
end case;
end loop;
loop
declare
Pattern : constant String := Get_Argument;
begin
exit when Pattern = "";
Util.Dates.Formats.Format (Pattern => Pattern,
Date => Ada.Calendar.Clock,
Bundle => Bundle,
Into => Result);
Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Result));
end;
end loop;
end Date;
|
-----------------------------------------------------------------------
-- date -- Print the date
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Calendar;
with Ada.Strings.Unbounded;
with GNAT.Command_Line;
with Util.Log.Loggers;
with Util.Dates.Formats;
with Util.Properties.Bundles;
procedure Date is
use type Ada.Calendar.Time;
use Util.Log.Loggers;
use Ada.Strings.Unbounded;
use Util.Properties.Bundles;
use GNAT.Command_Line;
Log : constant Logger := Create ("log", "samples/log4j.properties");
Factory : Util.Properties.Bundles.Loader;
Bundle : Util.Properties.Bundles.Manager;
Locale : Unbounded_String := To_Unbounded_String ("en");
Date : Ada.Calendar.Time := Ada.Calendar.Clock;
begin
-- Load the bundles from the current directory
Initialize (Factory, "samples/;bundles");
loop
case Getopt ("h l: locale: help") is
when ASCII.NUL =>
exit;
when 'l' =>
Locale := To_Unbounded_String (Parameter);
when others =>
Log.Info ("Usage: date -l locale format");
return;
end case;
end loop;
begin
Load_Bundle (Factory, "dates", To_String (Locale), Bundle);
exception
when NO_BUNDLE =>
Log.Error ("There is no bundle: {0}", "dates");
end;
loop
declare
Pattern : constant String := Get_Argument;
begin
exit when Pattern = "";
Ada.Text_IO.Put_Line (Util.Dates.Formats.Format (Pattern => Pattern,
Date => Date,
Bundle => Bundle));
end;
end loop;
end Date;
|
Update the date example so that -l option works
|
Update the date example so that -l option works
|
Ada
|
apache-2.0
|
Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util
|
732dd630adec0c350cc988743f6fa08efb2d87e8
|
regtests/util-properties-form-tests.adb
|
regtests/util-properties-form-tests.adb
|
-----------------------------------------------------------------------
-- util-properties-form-tests -- Test reading JSON file into properties
-- Copyright (C) 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Files;
package body Util.Properties.Form.Tests is
package Caller is new Util.Test_Caller (Test, "Properties.Properties.Form");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Properties.Form.Parse_Form",
Test_Parse_Form'Access);
end Add_Tests;
-- Test loading a JSON file into a properties object.
procedure Test_Parse_Form (T : in out Test) is
procedure Check (Name : in String;
Value : in String);
P : Util.Properties.Manager;
procedure Check (Name : in String;
Value : in String) is
begin
T.Assert (P.Exists (Name), "Missing property: " & Name);
Util.Tests.Assert_Equals (T, Value, String '(P.Get (Name)),
"Invalid property: " & Name);
end Check;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/files/test-1.form");
S : Ada.Strings.Unbounded.Unbounded_String;
begin
Util.Files.Read_File (Path, S);
Util.Properties.Form.Parse_Form (P, Ada.Strings.Unbounded.To_String (S));
Check ("access_token", "97356");
Check ("token_type", "bearer");
Check ("refresh_token_expires_in", "15724800");
Check ("refresh_token", "r1.714b6");
Check ("scope", "");
Check ("scope", "");
end Test_Parse_Form;
end Util.Properties.Form.Tests;
|
Implement new test for Parse_Form and register it for execution
|
Implement new test for Parse_Form and register it for execution
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
|
678225b830678911d6f6ed9a1bca01d5fe4474a7
|
regtests/babel-base-users-tests.adb
|
regtests/babel-base-users-tests.adb
|
-----------------------------------------------------------------------
-- babel-base-users-tests - Unit tests for babel users
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
package body Babel.Base.Users.Tests is
use type Util.Strings.Name_Access;
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.Users.Find",
Test_Find'Access);
end Add_Tests;
-- ------------------------------
-- Test the Find function resolving some existing user.
-- ------------------------------
procedure Test_Find (T : in out Test) is
Db : Babel.Base.Users.Database;
User : User_Type;
begin
User := Db.Find (0, 0);
T.Assert (User.Name /= null, "User uid=0 was not found");
T.Assert (User.Group /= null, "User gid=0 was not found");
Util.Tests.Assert_Equals (T, "root", User.Name.all, "Invalid root user name");
Util.Tests.Assert_Equals (T, "root", User.Group.all, "Invalid root group name");
end Test_Find;
end Babel.Base.Users.Tests;
|
Implement a simple unit test for the Find operation
|
Implement a simple unit test for the Find operation
|
Ada
|
apache-2.0
|
stcarrez/babel
|
|
2d39e9948914fbaff57f498bff149417e8fa8ef3
|
src/asf-components-widgets-tabs.adb
|
src/asf-components-widgets-tabs.adb
|
-----------------------------------------------------------------------
-- components-widgets-tabs -- Tab views and tabs
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Components.Base;
with ASF.Contexts.Writer;
package body ASF.Components.Widgets.Tabs is
-- ------------------------------
-- Render the tab start.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UITab;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
begin
if UI.Is_Rendered (Context) then
Writer.Start_Element ("div");
Writer.Write_Attribute ("id", UI.Get_Client_Id);
end if;
end Encode_Begin;
-- ------------------------------
-- Render the tab close.
-- ------------------------------
overriding
procedure Encode_End (UI : in UITab;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
begin
if UI.Is_Rendered (Context) then
Writer.End_Element ("div");
end if;
end Encode_End;
-- ------------------------------
-- Render the tab list and prepare to render the tab contents.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UITabView;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
procedure Render_Tab (T : in Components.Base.UIComponent_Access);
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
procedure Render_Tab (T : in Components.Base.UIComponent_Access) is
Id : constant Unbounded_String := T.Get_Client_Id;
begin
if T.all in UITab'Class then
Writer.Start_Element ("li");
Writer.Start_Element ("a");
Writer.Write_Attribute ("href", "#" & To_String (Id));
Writer.Write_Text (T.Get_Attribute ("title", Context));
Writer.End_Element ("a");
Writer.End_Element ("li");
end if;
end Render_Tab;
procedure Render_Tabs is
new ASF.Components.Base.Iterate (Process => Render_Tab);
begin
if UI.Is_Rendered (Context) then
declare
Id : constant Unbounded_String := UI.Get_Client_Id;
begin
Writer.Start_Element ("div");
Writer.Write_Attribute ("id", Id);
Writer.Start_Element ("ul");
Render_Tabs (UI);
Writer.End_Element ("ul");
Writer.Queue_Script ("$(""#");
Writer.Queue_Script (Id);
Writer.Queue_Script (""").tabs({");
Writer.Queue_Script ("});");
end;
end if;
end Encode_Begin;
-- ------------------------------
-- Render the tab view close.
-- ------------------------------
overriding
procedure Encode_End (UI : in UITabView;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
begin
if UI.Is_Rendered (Context) then
Writer.End_Element ("div");
end if;
end Encode_End;
end ASF.Components.Widgets.Tabs;
|
Implement the new <w:tab> and <w:tabView> components
|
Implement the new <w:tab> and <w:tabView> components
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
|
2c5e1bef757cac1574829413f1d87d2f56446c40
|
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
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
|
436af7a953dfbbfc83e436f099111fdf92598e97
|
src/asf-components-widgets-factory.adb
|
src/asf-components-widgets-factory.adb
|
-----------------------------------------------------------------------
-- widgets-factory -- Factory for widget Components
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Views.Nodes;
with ASF.Components.Base;
with ASF.Components.Widgets.Inputs;
package body ASF.Components.Widgets.Factory is
use ASF.Components.Base;
function Create_Input return UIComponent_Access;
-- -------------------------
-- ------------------------------
-- Create a UIFile component
-- ------------------------------
function Create_Input return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIInput;
end Create_Input;
use ASF.Views.Nodes;
URI : aliased constant String := "http://code.google.com/p/ada-asf/widget";
INPUT_TEXT_TAG : aliased constant String := "inputText";
Widget_Bindings : aliased constant ASF.Factory.Binding_Array
:= (1 => (Name => INPUT_TEXT_TAG'Access,
Component => Create_Input'Access,
Tag => Create_Component_Node'Access)
);
Core_Factory : aliased constant ASF.Factory.Factory_Bindings
:= (URI => URI'Access, Bindings => Widget_Bindings'Access);
-- ------------------------------
-- Get the widget component factory.
-- ------------------------------
function Definition return ASF.Factory.Factory_Bindings_Access is
begin
return Core_Factory'Access;
end Definition;
end ASF.Components.Widgets.Factory;
|
Implement the widget component factory
|
Implement the widget component factory
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
|
2e13ad874ac1ecf493dc251f4df071ff91027a28
|
src/asis/asis-ids.ads
|
src/asis/asis-ids.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT INTERFACE COMPONENTS --
-- --
-- A S I S . I D S --
-- --
-- S p e c --
-- --
-- Copyright (C) 1995-2008, Free Software Foundation, Inc. --
-- --
-- This specification is derived from the Ada Semantic Interface --
-- Specification Standard (ISO/IEC 15291) for use with GNAT. The copyright --
-- notice above, and the license provisions that follow apply solely to the --
-- contents of the part following the private keyword. --
-- --
-- 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). --
-- --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- 21 package Asis.Ids
------------------------------------------------------------------------------
------------------------------------------------------------------------------
package Asis.Ids is
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Asis.Ids provides support for permanent unique Element "Identifiers" (Ids).
-- An Id is an efficient way for a tool to reference an ASIS element. The Id
-- is permanent from session to session provided that the Ada compilation
-- environment is unchanged.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- This package encapsulates a set of operations and queries that implement
-- the ASIS Id abstraction. An Id is a way of identifying a particular
-- Element, from a particular Compilation_Unit, from a particular Context.
-- Ids can be written to files. Ids can be read from files and converted into
-- an Element value with the use of a suitable open Context.
--
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- 21.1 type Id
------------------------------------------------------------------------------
-- The Ada element Id abstraction (a private type).
--
-- The Id type is a distinct abstract type representing permanent "names"
-- that correspond to specific Element values.
--
-- These names can be written to files, retrieved at a later time, and
-- converted to Element values.
------------------------------------------------------------------------------
-- ASIS Ids are a means of identifying particular Element values obtained from
-- a particular physical compilation unit. Ids are "relative names". Each Id
-- value is valid (is usable, makes sense, can be interpreted) only in the
-- context of an appropriate open ASIS Context.
--
-- Id shall be an undiscriminated private type, or, shall be derived from an
-- undiscriminated private type. It shall be declared as a new type or as a
-- subtype of an existing type.
------------------------------------------------------------------------------
type Id is private;
Nil_Id : constant Id;
function "=" (Left : Id; Right : Id) return Boolean is abstract;
------------------------------------------------------------------------------
-- 21.2 function Hash
------------------------------------------------------------------------------
function Hash (The_Id : Id) return Asis.ASIS_Integer;
------------------------------------------------------------------------------
-- 21.3 function "<"
------------------------------------------------------------------------------
function "<" (Left : Id; Right : Id) return Boolean;
------------------------------------------------------------------------------
-- 21.4 function ">"
------------------------------------------------------------------------------
function ">" (Left : Id; Right : Id) return Boolean;
------------------------------------------------------------------------------
-- 21.5 function Is_Nil
------------------------------------------------------------------------------
function Is_Nil (Right : Id) return Boolean;
------------------------------------------------------------------------------
-- Right - Specifies the Id to check
--
-- Returns True if the Id is the Nil_Id.
--
------------------------------------------------------------------------------
-- 21.6 function Is_Equal
------------------------------------------------------------------------------
function Is_Equal (Left : Id; Right : Id) return Boolean;
------------------------------------------------------------------------------
-- Left - Specifies the left Id to compare
-- Right - Specifies the right Id to compare
--
-- Returns True if Left and Right represent the same physical Id, from the
-- same physical compilation unit. The two Ids convert
-- to Is_Identical Elements when converted with the same open ASIS Context.
--
------------------------------------------------------------------------------
-- 21.7 function Create_Id
------------------------------------------------------------------------------
function Create_Id (Element : Asis.Element) return Id;
------------------------------------------------------------------------------
-- Element - Specifies any Element value whose Id is desired
--
-- Returns a unique Id value corresponding to this Element, from the
-- corresponding Enclosing_Compilation_Unit and the corresponding
-- Enclosing_Context. The Id value will not be equal ("=") to the Id value
-- for any other Element value unless the two Elements are Is_Identical.
--
-- Nil_Id is returned for a Nil_Element.
--
-- All Element_Kinds are appropriate.
--
------------------------------------------------------------------------------
-- 21.8 function Create_Element
------------------------------------------------------------------------------
function Create_Element
(The_Id : Id;
The_Context : Asis.Context)
return Asis.Element;
------------------------------------------------------------------------------
-- The_Id - Specifies the Id to be converted to an Element
-- The_Context - Specifies the Context containing the Element with this Id
--
-- Returns the Element value corresponding to The_Id. The_Id shall
-- correspond to an Element available from a Compilation_Unit contained by
-- (referencible through) The_Context.
--
-- Raises ASIS_Inappropriate_Element if the Element value is not available
-- though The_Context. The Status is Value_Error and the Diagnosis
-- string will attempt to indicate the reason for the failure. (e.g., "Unit is
-- inconsistent", "No such unit", "Element is inconsistent (Unit
-- inconsistent)", etc.)
--
------------------------------------------------------------------------------
-- 21.9 function Debug_Image
------------------------------------------------------------------------------
function Debug_Image (The_Id : Id) return Wide_String;
------------------------------------------------------------------------------
-- The_Id - Specifies an Id to convert
--
-- Returns a string value containing implementation-defined debug
-- information associated with the Id.
--
-- The return value uses Asis.Text.Delimiter_Image to separate the lines
-- of multi-line results. The return value does not end with
-- Asis.Text.Delimiter_Image.
--
-- These values are intended for two purposes. They are suitable for
-- inclusion in problem reports sent to the ASIS implementor. They can
-- be presumed to contain information useful when debugging the
-- implementation itself. They are also suitable for use by the ASIS
-- application when printing simple application debugging messages during
-- application development. They are intended to be, to some worthwhile
-- degree, intelligible to the user.
--
------------------------------------------------------------------------------
private
-- The content of this private part is specific for the ASIS
-- implementation for GNAT
type Id is access String;
Nil_Id : constant Id := null;
------------------------------------------------------------------------------
end Asis.Ids;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
55b1cf03964048eaf98ae663067e58b3f9fc9dc7
|
src/util-listeners.ads
|
src/util-listeners.ads
|
-----------------------------------------------------------------------
-- util-listeners -- Listeners
-- 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.Concurrent.Arrays;
-- == Introduction ==
-- The `Listeners` package implements a simple observer/listener design pattern.
-- A subscriber registers to a list. When a change is made on an object, the
-- application can notify the subscribers which are then called with the object.
--
-- == Creating the listener list ==
-- The listeners list contains a list of listener interfaces.
--
-- L : Util.Listeners.List;
--
-- The list is heterogeneous meaning that several kinds of listeners could
-- be registered.
--
-- == Creating the observers ==
-- First the `Observers` package must be instantiated with the type being
-- observed. In the example below, we will observe a string:
--
-- package String_Observers is new Util.Listeners.Observers (String);
--
-- == Implementing the observer ==
-- Now we must implement the string observer:
--
-- type String_Observer is new String_Observer.Observer with null record;
-- procedure Update (List : in String_Observer; Item : in String);
--
-- == Registering the observer ==
-- An instance of the string observer must now be registered in the list.
--
-- O : aliased String_Observer;
-- L.Append (O'Access);
--
-- == Publishing ==
-- Notifying the listeners is done by invoking the `Notify` operation
-- provided by the `String_Observers` package:
--
-- String_Observer.Notify (L, "Hello");
--
package Util.Listeners is
-- The listener root interface.
type Listener is limited interface;
type Listener_Access is access all Listener'Class;
-- The multi-task safe list of listeners.
package Listener_Arrays is new Util.Concurrent.Arrays (Listener_Access);
-- ------------------------------
-- List of listeners
-- ------------------------------
-- The `List` type is a list of listeners that have been registered and must be
-- called when a notification is sent. The list uses the concurrent arrays thus
-- allowing tasks to add or remove listeners while dispatching is also running.
type List is new Listener_Arrays.Vector with null record;
procedure Add_Listener (Into : in out Listener_Arrays.Vector;
Item : in Listener_Access) renames Listener_Arrays.Append;
procedure Remove_Listener (Into : in out Listener_Arrays.Vector;
Item : in Listener_Access) renames Listener_Arrays.Remove;
end Util.Listeners;
|
-----------------------------------------------------------------------
-- util-listeners -- Listeners
-- 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.Concurrent.Arrays;
-- == Introduction ==
-- The `Listeners` package implements a simple observer/listener design pattern.
-- A subscriber registers to a list. When a change is made on an object, the
-- application can notify the subscribers which are then called with the object.
--
-- == Creating the listener list ==
-- The listeners list contains a list of listener interfaces.
--
-- L : Util.Listeners.List;
--
-- The list is heterogeneous meaning that several kinds of listeners could
-- be registered.
--
-- == Creating the observers ==
-- First the `Observers` package must be instantiated with the type being
-- observed. In the example below, we will observe a string:
--
-- package String_Observers is new Util.Listeners.Observers (String);
--
-- == Implementing the observer ==
-- Now we must implement the string observer:
--
-- type String_Observer is new String_Observer.Observer with null record;
-- procedure Update (List : in String_Observer; Item : in String);
--
-- == Registering the observer ==
-- An instance of the string observer must now be registered in the list.
--
-- O : aliased String_Observer;
-- L.Append (O'Access);
--
-- == Publishing ==
-- Notifying the listeners is done by invoking the `Notify` operation
-- provided by the `String_Observers` package:
--
-- String_Observer.Notify (L, "Hello");
--
package Util.Listeners is
-- The listener root interface.
type Listener is limited interface;
type Listener_Access is access all Listener'Class;
-- The multi-task safe list of listeners.
package Listener_Arrays is new Util.Concurrent.Arrays (Listener_Access);
-- ------------------------------
-- List of listeners
-- ------------------------------
-- The `List` type is a list of listeners that have been registered and must be
-- called when a notification is sent. The list uses the concurrent arrays thus
-- allowing tasks to add or remove listeners while dispatching is also running.
subtype List is Listener_Arrays.Vector;
procedure Add_Listener (Into : in out Listener_Arrays.Vector;
Item : in Listener_Access) renames Listener_Arrays.Append;
procedure Remove_Listener (Into : in out Listener_Arrays.Vector;
Item : in Listener_Access) renames Listener_Arrays.Remove;
end Util.Listeners;
|
Make the List type a subtype of Listener_Arras.Vector
|
Make the List type a subtype of Listener_Arras.Vector
|
Ada
|
apache-2.0
|
Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util
|
2d727094d1d1bbd9753eccd2ea1e1890c033e400
|
src/asis/a4g-a_output.ads
|
src/asis/a4g-a_output.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . A _ O U T P U T --
-- --
-- S p e c --
-- --
-- $Revision: 15311 $
-- --
-- Copyright (c) 1995-2002, Free Software Foundation, Inc. --
-- --
-- ASIS-for-GNAT is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 2, or (at your option) any later --
-- version. ASIS-for-GNAT is distributed in the hope that it will be use- --
-- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- --
-- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General --
-- Public License for more details. You should have received a copy of the --
-- GNU General Public License distributed with ASIS-for-GNAT; see file --
-- COPYING. If not, write to the Free Software Foundation, 59 Temple Place --
-- - Suite 330, Boston, MA 02111-1307, USA. --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the --
-- Software Engineering Laboratory of the Swiss Federal Institute of --
-- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the --
-- Scientific Research Computer Center of Moscow State University (SRCC --
-- MSU), Russia, with funding partially provided by grants from the Swiss --
-- National Science Foundation and the Swiss Academy of Engineering --
-- Sciences. ASIS-for-GNAT is now maintained by Ada Core Technologies Inc --
-- (http://www.gnat.com). --
-- --
------------------------------------------------------------------------------
-- This package contains the utility routines used for providing ASIS
-- warnings, debug images for ASIS types and internal debugging information.
with Asis; use Asis;
with Asis.Errors; use Asis.Errors;
with Types; use Types;
package A4G.A_Output is
Max_Debug_Buffer_Len : Natural := 8 * 1024;
Debug_Buffer : String (1 .. Max_Debug_Buffer_Len);
Debug_Buffer_Len : Natural range 0 .. Max_Debug_Buffer_Len;
-- buffer to form debug image strings
procedure Add (Phrase : String);
-- Adds Phrase to Debug_Buffer and resets Debug_Buffer_Len
procedure ASIS_Warning
(Message : String;
Error : Asis.Errors.Error_Kinds := Not_An_Error);
-- Produces a warning message (the text of the message is the string
-- passed as an actual for the Message parameter. The effect of calling
-- this procedure depends on which ASIS warning mode was set when ASIS was
-- initialized. In case of Suppress nothing happens, in case of Normal
-- Message is sent to Stderr, and in case of Treat_As_Error the warning
-- is converted into raising ASIS_Failed, Message is sent to ASIS diagnosis
-- and the value of the Error parameter is set to the ASIS Error Status
function Debug_String (CUnit : Compilation_Unit) return String;
-- Produces the string containing debug information about CUnit
function Debug_String (Cont : Context) return String;
-- Produces the string containing debug information about Cont
procedure Debug_String
(CUnit : Compilation_Unit;
No_Abort : Boolean := False);
-- Produces the string containing debug information about CUnit
-- Forms in Debug_Buffer the string containing debug information about
-- the argument unit. If No_Abort is set ON, then any exception raised
-- inside this procedure is suppressed and the message about suppressed
-- exception is added to the result string. This is needed to avoid
-- circularity during reporting of ASIS implementation bug.
procedure Debug_String
(E : Element;
No_Abort : Boolean := False);
-- Forms in Debug_Buffer the string containing debug information about E
-- If No_Abort is set ON, then any exception raised inside this procedure
-- is suppressed and the message about suppressed exception is added to
-- the result string. This is needed to avoid circularity during reporting
-- of ASIS implementation bug.
procedure Write_Node (N : Node_Id; Prefix : String := "");
-- outputs the tree node attributes without using any facilities
-- from the GNAT Treepr package. The string passed as an actual for
-- Prefix is outputted in the beginning of every string
end A4G.A_Output;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
de1803dfdebbdab45716cb5e174b7d72dd171dbb
|
src/security-oauth-file_registry.adb
|
src/security-oauth-file_registry.adb
|
-----------------------------------------------------------------------
-- security-oauth-file_registry -- File Based Application and Realm
-- 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.Strings;
package body Security.OAuth.File_Registry is
-- ------------------------------
-- Get the principal name.
-- ------------------------------
overriding
function Get_Name (From : in File_Principal) return String is
begin
return To_String (From.Name);
end Get_Name;
-- ------------------------------
-- Find the application that correspond to the given client id.
-- The <tt>Invalid_Application</tt> exception should be raised if there is no such application.
-- ------------------------------
overriding
function Find_Application (Realm : in File_Application_Manager;
Client_Id : in String) return Servers.Application'Class is
Pos : Application_Maps.Cursor := Realm.Applications.Find (Client_Id);
begin
if not Application_Maps.Has_Element (Pos) then
raise Servers.Invalid_Application;
end if;
return Application_Maps.Element (Pos);
end Find_Application;
-- ------------------------------
-- Authenticate the token and find the associated authentication principal.
-- The access token has been verified and the token represents the identifier
-- of the Tuple (client_id, user, session) that describes the authentication.
-- The <tt>Authenticate</tt> procedure should look in its database (internal
-- or external) to find the authentication principal that was granted for
-- the token Tuple. When the token was not found (because it was revoked),
-- the procedure should return a null principal. If the authentication
-- principal can be cached, the <tt>Cacheable</tt> value should be set.
-- In that case, the access token and authentication principal are inserted
-- in a cache.
-- ------------------------------
overriding
procedure Authenticate (Realm : in out File_Realm_Manager;
Token : in String;
Auth : out Principal_Access;
Cacheable : out Boolean) is
Pos : constant Token_Maps.Cursor := Realm.Tokens.Find (Token);
begin
if Token_Maps.Has_Element (Pos) then
Auth := Token_Maps.Element (Pos).all'Access;
else
Auth := null;
end if;
Cacheable := True;
end Authenticate;
-- ------------------------------
-- Create an auth token string that identifies the given principal. The returned
-- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The
-- returned token does not need to be signed. It will be inserted in the public part
-- of the returned access token.
-- ------------------------------
overriding
function Authorize (Realm : in File_Realm_Manager;
App : in Servers.Application'Class;
Scope : in String;
Auth : in Principal_Access) return String is
begin
return To_String (File_Principal (Auth.all).Token);
end Authorize;
overriding
procedure Verify (Realm : in out File_Realm_Manager;
Username : in String;
Password : in String;
Auth : out Principal_Access) is
Result : File_Principal_Access;
Pos : constant User_Maps.Cursor := Realm.Users.Find (Username);
begin
if not User_Maps.Has_Element (Pos) then
Auth := null;
return;
end if;
if Password /= User_Maps.Element (Pos) then
Auth := null;
return;
end if;
Result := new File_Principal;
Realm.Tokens.Insert (To_String (Result.Token), Result);
Auth := Result.all'Access;
end Verify;
overriding
procedure Verify (Realm : in out File_Realm_Manager;
Token : in String;
Auth : out Principal_Access) is
begin
null;
end Verify;
overriding
procedure Revoke (Realm : in out File_Realm_Manager;
Auth : in Principal_Access) is
begin
if Auth /= null and then Auth.all in File_Principal'Class then
Realm.Tokens.Delete (To_String (File_Principal (Auth.all).Token));
end if;
end Revoke;
end Security.OAuth.File_Registry;
|
Implement a simple file-base application and user realm for the OAuth server side
|
Implement a simple file-base application and user realm for the OAuth server side
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
|
a782b15c414641b607ec6030106aff801922dc2e
|
src/sys/os-windows/util-systems-os.adb
|
src/sys/os-windows/util-systems-os.adb
|
-----------------------------------------------------------------------
-- util-system-os -- Windows system operations
-- Copyright (C) 2011, 2012, 2015, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Characters.Conversions;
package body Util.Systems.Os is
use type Interfaces.Unsigned_32;
use type Interfaces.Unsigned_64;
use type Interfaces.C.size_t;
function To_WSTR (Value : in String) return Wchar_Ptr is
Result : constant Wchar_Ptr := new Interfaces.C.wchar_array (0 .. Value'Length + 1);
Pos : Interfaces.C.size_t := 0;
begin
for C of Value loop
Result (Pos)
:= Interfaces.C.To_C (Ada.Characters.Conversions.To_Wide_Character (C));
Pos := Pos + 1;
end loop;
Result (Pos) := Interfaces.C.wide_nul;
return Result;
end To_WSTR;
function Sys_SetFilePointerEx (Fs : in File_Type;
Offset : in Util.Systems.Types.off_t;
Result : access Util.Systems.Types.off_t;
Mode : in Util.Systems.Types.Seek_Mode) return BOOL
with Import => True, Convention => Stdcall, Link_Name => "SetFilePointerEx";
function Sys_Lseek (Fs : in File_Type;
Offset : in Util.Systems.Types.off_t;
Mode : in Util.Systems.Types.Seek_Mode)
return Util.Systems.Types.off_t is
Result : aliased Util.Systems.Types.off_t;
begin
if Sys_SetFilePointerEx (Fs, Offset, Result'Access, Mode) /= 0 then
return Result;
else
return -1;
end if;
end Sys_Lseek;
function Sys_GetFileSizeEx (Fs : in File_Type;
Result : access Util.Systems.Types.off_t) return BOOL
with Import => True, Convention => Stdcall, Link_Name => "GetFileSizeEx";
function Sys_GetFileTime (Fs : in File_Type;
Create : access FileTime;
AccessTime : access FileTime;
ModifyTime : access FileTime) return BOOL
with Import => True, Convention => Stdcall, Link_Name => "GetFileSizeEx";
TICKS_PER_SECOND : constant := 10000000;
EPOCH_DIFFERENCE : constant := 11644473600;
function To_Time (Time : in FileTime) return Types.Time_Type is
Value : Interfaces.Unsigned_64;
begin
Value := Interfaces.Shift_Left (Interfaces.Unsigned_64 (Time.dwHighDateTime), 32);
Value := Value + Interfaces.Unsigned_64 (Time.dwLowDateTime);
Value := Value / TICKS_PER_SECOND;
Value := Value - EPOCH_DIFFERENCE;
return Types.Time_Type (Value);
end To_Time;
function Sys_Fstat (Fs : in File_Type;
Stat : access Util.Systems.Types.Stat_Type) return Integer is
Size : aliased Util.Systems.Types.off_t;
Creation_Time : aliased FileTime;
Access_Time : aliased FileTime;
Write_Time : aliased FileTime;
begin
Stat.st_dev := 0;
Stat.st_ino := 0;
Stat.st_mode := 0;
Stat.st_nlink := 0;
Stat.st_uid := 0;
Stat.st_gid := 0;
Stat.st_rdev := 0;
Stat.st_atime := 0;
Stat.st_mtime := 0;
Stat.st_ctime := 0;
if Sys_GetFileSizeEx (Fs, Size'Access) = 0 then
return -1;
end if;
if Sys_GetFileTime (Fs, Creation_Time'Access, Access_Time'Access, Write_Time'Access) = 0 then
return -1;
end if;
Stat.st_size := Size;
Stat.st_ctime := To_Time (Creation_Time);
Stat.st_mtime := To_Time (Write_Time);
Stat.st_atime := To_Time (Access_Time);
return 0;
end Sys_Fstat;
-- Open a file
function Sys_Open (Path : in Ptr;
Flags : in Interfaces.C.int;
Mode : in Util.Systems.Types.mode_t) return File_Type is
pragma Unreferenced (Mode);
function Has_Flag (M : in Interfaces.C.int;
F : in Interfaces.C.int) return Boolean
is ((Interfaces.Unsigned_32 (M) and Interfaces.Unsigned_32 (F)) /= 0);
Sec : aliased Security_Attributes;
Result : File_Type;
Desired_Access : DWORD;
Share_Mode : DWORD := FILE_SHARE_READ + FILE_SHARE_WRITE;
Creation : DWORD;
WPath : Wchar_Ptr;
begin
WPath := To_WSTR (Interfaces.C.Strings.Value (Path));
Sec.Length := Security_Attributes'Size / 8;
Sec.Security_Descriptor := System.Null_Address;
Sec.Inherit := True;
if Has_Flag (Flags, O_WRONLY) then
Desired_Access := GENERIC_WRITE;
elsif Has_Flag (Flags, O_RDWR) then
Desired_Access := GENERIC_READ + GENERIC_WRITE;
else
Desired_Access := GENERIC_READ;
end if;
if Has_Flag (Flags, O_CREAT) then
if Has_Flag (Flags, O_EXCL) then
Creation := CREATE_NEW;
else
Creation := CREATE_ALWAYS;
end if;
else
Creation := OPEN_EXISTING;
end if;
if Has_Flag (Flags, O_APPEND) then
Desired_Access := FILE_APPEND_DATA;
end if;
if Has_Flag (Flags, O_EXCL) then
Share_Mode := 0;
end if;
Result := Create_File (WPath.all'Address,
Desired_Access,
Share_Mode,
Sec'Unchecked_Access,
Creation,
FILE_ATTRIBUTE_NORMAL,
NO_FILE);
Free (WPath);
return Result;
end Sys_Open;
function Sys_SetEndOfFile (Fs : in File_Type) return BOOL
with Import => True, Convention => Stdcall, Link_Name => "SetEndOfFile";
function Sys_Ftruncate (Fs : in File_Type;
Length : in Util.Systems.Types.off_t) return Integer is
begin
if Sys_Lseek (Fs, Length, Util.Systems.Types.SEEK_SET) < 0 then
return -1;
end if;
if Sys_SetEndOfFile (Fs) = 0 then
return -1;
end if;
return 0;
end Sys_Ftruncate;
function Sys_Fchmod (Fd : in File_Type;
Mode : in Util.Systems.Types.mode_t) return Integer is
pragma Unreferenced (Fd, Mode);
begin
return 0;
end Sys_Fchmod;
-- Close a file
function Sys_Close (Fd : in File_Type) return Integer is
begin
if Close_Handle (Fd) = 0 then
return -1;
else
return 0;
end if;
end Sys_Close;
end Util.Systems.Os;
|
Implement Sys_Open, Sys_Ftruncate, Sys_Fstat, Sys_Close on top of Windows file HANDLE
|
Implement Sys_Open, Sys_Ftruncate, Sys_Fstat, Sys_Close on top of Windows file HANDLE
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
|
2e225359ac059445f4b90c7a3c4b7c1ed7238fe3
|
matp/src/events/mat-events-tools.adb
|
matp/src/events/mat-events-tools.adb
|
-----------------------------------------------------------------------
-- mat-events-tools - Profiler Events Description
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body MAT.Events.Tools is
-- ------------------------------
-- Find in the list the first event with the given type.
-- Raise <tt>Not_Found</tt> if the list does not contain such event.
-- ------------------------------
function Find (List : in Target_Event_Vector;
Kind : in Probe_Index_Type) return Target_Event_Type is
Iter : Target_Event_Cursor := List.First;
Event : Target_Event_Type;
begin
while Target_Event_Vectors.Has_Element (Iter) loop
Event := Target_Event_Vectors.Element (Iter);
if Event.Index = Kind then
return Event;
end if;
Target_Event_Vectors.Next (Iter);
end loop;
raise Not_Found;
end Find;
end MAT.Events.Tools;
|
Implement the MAT.Events.Tools package with the Find operation
|
Implement the MAT.Events.Tools package with the Find operation
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
|
6d00e3ae11b7be9245402940ca1fa1058a73eaff
|
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
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
|
4c85c10ca64cac1b8e22c32bf092436c17d71d82
|
mat/src/memory/mat-memory-readers.ads
|
mat/src/memory/mat-memory-readers.ads
|
-----------------------------------------------------------------------
-- Memory Events - Definition and Analysis of memory events
-- 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 MAT.Types;
with MAT.Events;
-- with MAT.Ipc;
with Util.Events;
with MAT.Readers;
with MAT.Memory.Targets;
-- with MAT.Memory.Clients;
-- with MAT.Ipc.Clients;
-- with MAT.Events; use MAT.Events;
package MAT.Memory.Readers is
type Memory_Servant is new MAT.Readers.Reader_Base with record
Data : MAT.Memory.Targets.Client_Memory;
-- Slots : Client_Memory_Ref;
-- Impl : Client_Memory_Ref;
end record;
-- The memory servant is a proxy for the generic communication
-- channel to process incomming events (such as memory allocations).
overriding
procedure Dispatch (For_Servant : in out Memory_Servant;
Id : in MAT.Events.Internal_Reference;
Params : in MAT.Events.Const_Attribute_Table_Access;
Msg : in out MAT.Readers.Message);
procedure Bind (For_Servant : in out Memory_Servant);
-- Bind the servant with the object adapter to register the
-- events it recognizes.
end MAT.Memory.Readers;
|
Package to read the memory events
|
Package to read the memory events
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
|
b5e48cc3525fbcfc2c2671236be8e98a5a0ba0d3
|
src/asf-rest-definition.adb
|
src/asf-rest-definition.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.Definition is
overriding
procedure Dispatch (Handler : in Descriptor;
Req : in out ASF.Rest.Request'Class;
Reply : in out ASF.Rest.Response'Class) is
Object : Object_Type;
begin
Handler.Handler (Object, Req, Reply);
end Dispatch;
package body Definition is
P : aliased String := Pattern;
begin
Instance.Method := Method;
Instance.Permission := Permission;
Instance.Handler := Handler;
Instance.Pattern := P'Access;
ASF.Rest.Register (Entries, Instance'Access);
end Definition;
end ASF.Rest.Definition;
|
Implement the Rest definition package to dispatch the request to the API handler
|
Implement the Rest definition package to dispatch the request to the API handler
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
|
dc2a14dbbd34c1128646a6a85166b802ac8e6d96
|
src/util-properties-json.adb
|
src/util-properties-json.adb
|
-----------------------------------------------------------------------
-- util-properties-json -- read json files into properties
-- 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.JSON;
with Util.Stacks;
with Util.Beans.Objects;
package body Util.Properties.JSON is
type Natural_Access is access all Natural;
package Length_Stack is new Util.Stacks (Element_Type => Natural,
Element_Type_Access => Natural_Access);
type Parser is new Util.Serialize.IO.JSON.Parser with record
Base_Name : Ada.Strings.Unbounded.Unbounded_String;
Lengths : Length_Stack.Stack;
Separator : Ada.Strings.Unbounded.Unbounded_String;
Separator_Length : Natural;
end record;
-- 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);
-- 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);
-- -----------------------
-- 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;
-- -----------------------
-- Parse the JSON content and put the flattened content in the property manager.
-- -----------------------
procedure Parse_JSON (Manager : in out Util.Properties.Manager'Class;
Content : in String;
Flatten_Separator : in String := ".") is
type Local_Parser is new Parser with null record;
-- 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 Local_Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False);
-- -----------------------
-- 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 Local_Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False) is
pragma Unreferenced (Attribute);
begin
Manager.Set (Ada.Strings.Unbounded.To_String (Handler.Base_Name) & Name,
Util.Beans.Objects.To_String (Value));
end Set_Member;
P : Local_Parser;
begin
P.Separator := Ada.Strings.Unbounded.To_Unbounded_String (Flatten_Separator);
P.Separator_Length := Flatten_Separator'Length;
P.Parse_String (Content);
end Parse_JSON;
-- -----------------------
-- Read the JSON file into the property manager.
-- The JSON content is flatten into Flatten the JSON content and add the properties.
-- -----------------------
procedure Read_JSON (Manager : in out Util.Properties.Manager'Class;
Path : in String;
Flatten_Separator : in String := ".") is
type Local_Parser is new Parser with null record;
-- 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 Local_Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False);
-- -----------------------
-- 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 Local_Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False) is
pragma Unreferenced (Attribute);
begin
Manager.Set (Ada.Strings.Unbounded.To_String (Handler.Base_Name) & Name,
Util.Beans.Objects.To_String (Value));
end Set_Member;
P : Local_Parser;
begin
P.Separator := Ada.Strings.Unbounded.To_Unbounded_String (Flatten_Separator);
P.Separator_Length := Flatten_Separator'Length;
P.Parse (Path);
end Read_JSON;
end Util.Properties.JSON;
|
Implement reading JSON content and putting it in property manager
|
Implement reading JSON content and putting it in property manager
|
Ada
|
apache-2.0
|
Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util
|
|
5412d9facbf5cf8b5a280be79bb9dee9a44d6889
|
mat/regtests/mat-expressions-tests.ads
|
mat/regtests/mat-expressions-tests.ads
|
-----------------------------------------------------------------------
-- mat-expressions-tests -- Unit tests for MAT expressions
-- 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 MAT.Expressions.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
procedure Test_Parse_Expression (T : in out Test);
end MAT.Expressions.Tests;
|
Add unit tests for MAT.Expressions
|
Add unit tests for MAT.Expressions
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
|
5fd618edb930f6059e6195be464643717a46cb32
|
awa/src/awa-commands.adb
|
awa/src/awa-commands.adb
|
-----------------------------------------------------------------------
-- awa-commands -- AWA commands for server or admin tool
-- Copyright (C) 2019, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
with Ada.Unchecked_Deallocation;
with Util.Log.Loggers;
with AWA.Applications.Configs;
with Keystore.Passwords.Input;
with Keystore.Passwords.Files;
with Keystore.Passwords.Unsafe;
with Keystore.Passwords.Cmds;
package body AWA.Commands is
use type Keystore.Passwords.Provider_Access;
use type Keystore.Header_Slot_Count_Type;
use type Keystore.Passwords.Keys.Key_Provider_Access;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Commands");
procedure Load_Configuration (Context : in out Context_Type) is
begin
begin
Context.File_Config.Load_Properties (Context.Config_File.all);
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot read application configuration file {0}",
Context.Config_File.all);
end;
if Context.File_Config.Exists (GPG_CRYPT_CONFIG) then
Context.GPG.Set_Encrypt_Command (Context.File_Config.Get (GPG_CRYPT_CONFIG));
end if;
if Context.File_Config.Exists (GPG_DECRYPT_CONFIG) then
Context.GPG.Set_Decrypt_Command (Context.File_Config.Get (GPG_DECRYPT_CONFIG));
end if;
if Context.File_Config.Exists (GPG_LIST_CONFIG) then
Context.GPG.Set_List_Key_Command (Context.File_Config.Get (GPG_LIST_CONFIG));
end if;
Context.Config.Randomize := not Context.Zero;
end Load_Configuration;
-- ------------------------------
-- Returns True if a keystore is used by the configuration and must be unlocked.
-- ------------------------------
function Use_Keystore (Context : in Context_Type) return Boolean is
begin
if Context.Wallet_File'Length > 0 then
return True;
end if;
return Context.File_Config.Exists ("keystore.path");
end Use_Keystore;
-- ------------------------------
-- Open the keystore file using the password password.
-- ------------------------------
procedure Open_Keystore (Context : in out Context_Type) is
begin
Setup_Password_Provider (Context);
Setup_Key_Provider (Context);
Context.Wallet.Open (Path => Context.Get_Keystore_Path,
Data_Path => Context.Data_Path.all,
Config => Context.Config,
Info => Context.Info);
if not Context.No_Password_Opt or else Context.Info.Header_Count = 0 then
if Context.Key_Provider /= null then
Context.Wallet.Set_Master_Key (Context.Key_Provider.all);
end if;
if Context.Provider = null then
Context.Provider := Keystore.Passwords.Input.Create (-("Enter password: "), False);
end if;
Context.Wallet.Unlock (Context.Provider.all, Context.Slot);
else
Context.GPG.Load_Secrets (Context.Wallet);
Context.Wallet.Set_Master_Key (Context.GPG);
Context.Wallet.Unlock (Context.GPG, Context.Slot);
end if;
Keystore.Properties.Initialize (Context.Secure_Config, Context.Wallet'Unchecked_Access);
AWA.Applications.Configs.Merge (Context.App_Config,
Context.File_Config,
Context.Secure_Config,
"");
end Open_Keystore;
-- ------------------------------
-- Configure the application by loading its configuration file and merging it with
-- the keystore file if there is one.
-- ------------------------------
procedure Configure (Application : in out AWA.Applications.Application'Class;
Name : in String;
Context : in out Context_Type) is
Path : constant String := AWA.Applications.Configs.Get_Config_Path (Name);
begin
begin
Context.File_Config.Load_Properties (Path);
exception
when Ada.IO_Exceptions.Name_Error =>
null;
end;
if Context.Use_Keystore then
Open_Keystore (Context);
else
Context.App_Config := Context.File_Config;
end if;
Application.Initialize (Context.App_Config, Context.Factory);
end Configure;
-- ------------------------------
-- Initialize the commands.
-- ------------------------------
overriding
procedure Initialize (Context : in out Context_Type) is
begin
GC.Set_Usage (Config => Context.Command_Config,
Usage => "[switchs] command [arguments]",
Help => -("akt - tool to store and protect your sensitive data"));
GC.Define_Switch (Config => Context.Command_Config,
Output => Context.Version'Access,
Switch => "-V",
Long_Switch => "--version",
Help => -("Print the version"));
GC.Define_Switch (Config => Context.Command_Config,
Output => Context.Verbose'Access,
Switch => "-v",
Long_Switch => "--verbose",
Help => -("Verbose execution mode"));
GC.Define_Switch (Config => Context.Command_Config,
Output => Context.Debug'Access,
Switch => "-vv",
Long_Switch => "--debug",
Help => -("Enable debug execution"));
GC.Define_Switch (Config => Context.Command_Config,
Output => Context.Dump'Access,
Switch => "-vvv",
Long_Switch => "--debug-dump",
Help => -("Enable debug dump execution"));
GC.Define_Switch (Config => Context.Command_Config,
Output => Context.Zero'Access,
Switch => "-z",
Long_Switch => "--zero",
Help => -("Erase and fill with zeros instead of random values"));
GC.Define_Switch (Config => Context.Command_Config,
Output => Context.Config_File'Access,
Switch => "-c:",
Long_Switch => "--config=",
Argument => "PATH",
Help => -("Defines the path for configuration file"));
GC.Initialize_Option_Scan (Stop_At_First_Non_Switch => True);
-- Driver.Set_Description (-("akt - tool to store and protect your sensitive data"));
-- Driver.Set_Usage (-("[-V] [-v] [-vv] [-vvv] [-c path] [-t count] [-z] " &
-- "<command> [<args>]" & ASCII.LF &
-- "where:" & ASCII.LF &
-- " -V Print the tool version" & ASCII.LF &
-- " -v Verbose execution mode" & ASCII.LF &
-- " -vv Debug execution mode" & ASCII.LF &
-- " -vvv Dump execution mode" & ASCII.LF &
-- " -c path Defines the path for akt " &
-- "global configuration" & ASCII.LF &
-- " -t count Number of threads for the " &
-- "encryption/decryption process" & ASCII.LF &
-- " -z Erase and fill with zeros instead of random values"));
-- Driver.Add_Command ("help",
-- -("print some help"),
-- Help_Command'Access);
end Initialize;
-- ------------------------------
-- Setup the command before parsing the arguments and executing it.
-- ------------------------------
procedure Setup (Config : in out GC.Command_Line_Configuration;
Context : in out Context_Type) is
begin
GC.Define_Switch (Config => Config,
Output => Context.Wallet_File'Access,
Switch => "-k:",
Long_Switch => "--keystore=",
Argument => "PATH",
Help => -("Defines the path for the keystore file"));
GC.Define_Switch (Config => Config,
Output => Context.Data_Path'Access,
Switch => "-d:",
Long_Switch => "--data-path=",
Argument => "PATH",
Help => -("The directory which contains the keystore data blocks"));
GC.Define_Switch (Config => Config,
Output => Context.Password_File'Access,
Long_Switch => "--passfile=",
Argument => "PATH",
Help => -("Read the file that contains the password"));
GC.Define_Switch (Config => Config,
Output => Context.Unsafe_Password'Access,
Long_Switch => "--passfd=",
Argument => "NUM",
Help => -("Read the password from the pipe with"
& " the given file descriptor"));
GC.Define_Switch (Config => Config,
Output => Context.Unsafe_Password'Access,
Long_Switch => "--passsocket=",
Help => -("The password is passed within the socket connection"));
GC.Define_Switch (Config => Config,
Output => Context.Password_Env'Access,
Long_Switch => "--passenv=",
Argument => "NAME",
Help => -("Read the environment variable that contains"
& " the password (not safe)"));
GC.Define_Switch (Config => Config,
Output => Context.Unsafe_Password'Access,
Switch => "-p:",
Long_Switch => "--password=",
Help => -("The password is passed within the command line (not safe)"));
GC.Define_Switch (Config => Config,
Output => Context.Password_Askpass'Access,
Long_Switch => "--passask",
Help => -("Run the ssh-askpass command to get the password"));
GC.Define_Switch (Config => Config,
Output => Context.Password_Command'Access,
Long_Switch => "--passcmd=",
Argument => "COMMAND",
Help => -("Run the command to get the password"));
GC.Define_Switch (Config => Config,
Output => Context.Wallet_Key_File'Access,
Long_Switch => "--wallet-key-file=",
Argument => "PATH",
Help => -("Read the file that contains the wallet keys"));
end Setup;
procedure Setup_Password_Provider (Context : in out Context_Type) is
begin
if Context.Password_Askpass then
Context.Provider := Keystore.Passwords.Cmds.Create ("ssh-askpass");
elsif Context.Password_Command'Length > 0 then
Context.Provider := Keystore.Passwords.Cmds.Create (Context.Password_Command.all);
elsif Context.Password_File'Length > 0 then
Context.Provider := Keystore.Passwords.Files.Create (Context.Password_File.all);
elsif Context.Password_Command'Length > 0 then
Context.Provider := Keystore.Passwords.Cmds.Create (Context.Password_Command.all);
elsif Context.Unsafe_Password'Length > 0 then
Context.Provider := Keystore.Passwords.Unsafe.Create (Context.Unsafe_Password.all);
else
Context.No_Password_Opt := True;
end if;
Context.Key_Provider := Keystore.Passwords.Keys.Create (Keystore.DEFAULT_WALLET_KEY);
end Setup_Password_Provider;
procedure Setup_Key_Provider (Context : in out Context_Type) is
begin
if Context.Wallet_Key_File'Length > 0 then
Context.Key_Provider := Keystore.Passwords.Files.Create (Context.Wallet_Key_File.all);
end if;
end Setup_Key_Provider;
-- ------------------------------
-- Get the keystore file path.
-- ------------------------------
function Get_Keystore_Path (Context : in out Context_Type) return String is
begin
if Context.Wallet_File'Length > 0 then
Context.First_Arg := 1;
return Context.Wallet_File.all;
else
raise Error with "No keystore path";
end if;
end Get_Keystore_Path;
overriding
procedure Finalize (Context : in out Context_Type) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Keystore.Passwords.Provider'Class,
Name => Keystore.Passwords.Provider_Access);
begin
GC.Free (Context.Command_Config);
Free (Context.Provider);
end Finalize;
end AWA.Commands;
|
Implement operations for the AWA.Commands package
|
Implement operations for the AWA.Commands package
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
|
83326154bede4e2eab1118f7bbcbc37c14bce811
|
src/asis/a4g-skip_tb.ads
|
src/asis/a4g-skip_tb.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . S K I P _ T B --
-- --
-- S p e c --
-- --
-- Copyright (c) 1995-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;
with Types; use Types;
package A4G.Skip_TB is
-- This package encapsulates routines which is used in finding the end of
-- an Element Span tp scip all the "syntax sugar", such as ";", ")",
-- "end if", "end Unit_Name" etc.
function Skip_Trailing_Brackets
(E : Asis.Element;
S : Source_Ptr)
return Source_Ptr;
-- This function encapsulates all the cases when different kinds of
-- "syntax sugar" should be skiped, being implemented as a look-up
-- table for Internal_Element_Kinds. It returns the location of the
-- very last character of the image of E, provided that S is set to
-- point to iys last component. If a given Element has several levels
-- of subcomponents, this function is called each time when the
-- next right-most component is traversed in the recursive processing
-- defined by A4G.Span_End.Nonterminal_Component.
function Needs_Extra_Parentheses (E : Asis.Element) return Boolean;
-- This function detects if we need an extra parenthesis in the qualified
-- expression in the situation like this
-- Var : String := String'((1 => C));
-- The problem is that from the point of view of ASIS Element hierarchy
-- it there is no difference between this situation and
-- Var : String := String'(1 => C);
-- because we do not have A_Parenthesized_Expression in the first case,
-- we just have to decompose the qualified expression according to the
-- syntax rule: subtype_mark'(expression), and the outer pair of
-- parenthesis belongs to a qualified expression, and the inner - to an
-- enclosed aggregate.
-- We need this function in the spec to use it in gnatpp.
end A4G.Skip_TB;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
9dd3130f9fbb5ad2d6fc00420eabfc60f05fe84d
|
awa/plugins/awa-counters/src/awa-counters-definition.ads
|
awa/plugins/awa-counters/src/awa-counters-definition.ads
|
-----------------------------------------------------------------------
-- awa-counters-definition -- Counter 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.
-----------------------------------------------------------------------
-- The <tt>AWA.Counters.Definition</tt> package is instantiated for each counter definition.
generic
Table : ADO.Schemas.Class_Mapping_Access;
Field : String;
package AWA.Counters.Definition is
Def_Name : aliased constant String := Field;
package Def is new Counter_Arrays.Definition (Counter_Def '(Table, Def_Name'Access));
-- Get the counter definition index.
function Index return Counter_Index_Type renames Def.Kind;
end AWA.Counters.Definition;
|
Define the generic package for a counter definition
|
Define the generic package for a counter definition
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
|
53f1aaa826c52ef7b4131b4db41a9d6980cdf829
|
src/wiki-render-html.ads
|
src/wiki-render-html.ads
|
-----------------------------------------------------------------------
-- wiki-render-html -- Wiki HTML renderer
-- 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.Strings.Wide_Wide_Unbounded;
with Wiki.Documents;
with Wiki.Writers;
-- == HTML Renderer ==
-- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Html is
use Ada.Strings.Wide_Wide_Unbounded;
-- ------------------------------
-- Wiki to HTML writer
-- ------------------------------
type Html_Renderer is new Wiki.Documents.Document_Reader with private;
-- Set the output writer.
procedure Set_Writer (Document : in out Html_Renderer;
Writer : in Wiki.Writers.Html_Writer_Type_Access);
-- Add a section header in the document.
overriding
procedure Add_Header (Document : in out Html_Renderer;
Header : in Unbounded_Wide_Wide_String;
Level : in Positive);
-- Add a line break (<br>).
overriding
procedure Add_Line_Break (Document : in out Html_Renderer);
-- Add a paragraph (<p>). Close the previous paragraph if any.
-- The paragraph must be closed at the next paragraph or next header.
overriding
procedure Add_Paragraph (Document : in out Html_Renderer);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
overriding
procedure Add_Blockquote (Document : in out Html_Renderer;
Level : in Natural);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
overriding
procedure Add_List_Item (Document : in out Html_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Add an horizontal rule (<hr>).
overriding
procedure Add_Horizontal_Rule (Document : in out Html_Renderer);
-- Add a link.
overriding
procedure Add_Link (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String;
Title : in Unbounded_Wide_Wide_String);
-- Add an image.
overriding
procedure Add_Image (Document : in out Html_Renderer;
Link : in Unbounded_Wide_Wide_String;
Alt : in Unbounded_Wide_Wide_String;
Position : in Unbounded_Wide_Wide_String;
Description : in Unbounded_Wide_Wide_String);
-- Add a quote.
overriding
procedure Add_Quote (Document : in out Html_Renderer;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String);
-- Add a text block with the given format.
overriding
procedure Add_Text (Document : in out Html_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Wiki.Documents.Format_Map);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Document : in out Html_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Document : in out Html_Renderer);
private
procedure Close_Paragraph (Document : in out Html_Renderer);
procedure Open_Paragraph (Document : in out Html_Renderer);
type List_Style_Array is array (1 .. 32) of Boolean;
type Html_Renderer is new Wiki.Documents.Document_Reader with record
Writer : Wiki.Writers.Html_Writer_Type_Access := null;
Format : Wiki.Documents.Format_Map := (others => False);
Has_Paragraph : Boolean := False;
Need_Paragraph : Boolean := False;
Current_Level : Natural := 0;
List_Styles : List_Style_Array := (others => False);
Has_Item : Boolean := False;
Quote_Level : Natural := 0;
end record;
end Wiki.Render.Html;
|
Define the renderer to transform a wiki text in HTML
|
Define the renderer to transform a wiki text in HTML
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
|
ace21dbf329fe101dc330ce93589b95f03f4e96d
|
src/asis/a4g-mapping.ads
|
src/asis/a4g-mapping.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . M A P P I N G --
-- --
-- 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). --
-- --
------------------------------------------------------------------------------
-- This package defines and implements the mapping from the nodes in the
-- tree created by the front-end nodes onto ASIS Elements.
-- The main part of this mapping are:
--
-- - the function constructing an ASIS Element from a tree
-- node;
-- - the function constructing an ASIS Element_List from a tree node
-- list;
-- - a set of functions defining the ASIS kind (or, more exactly, the
-- corresponding value of the Internal_Element_Kinds type) of an Element
-- which can be built on the base of a given node. Most of these functions
-- are hidden in the package body, but for some of them their
-- specifications are placed in the package spec in order to make them
-- visible for the implementation of some ASIS queries (for example,
-- sometimes we have to know the exact kind of an operator symbol or
-- of an attribute reference.
-- The functions defined in this package are of relatively low level. In
-- particular, as a rule, they do not check the correctness of their
-- arguments, and a caller is responsible for the correct usage of these
-- functions.
with Asis;
with A4G.A_Types; use A4G.A_Types;
with A4G.Int_Knds; use A4G.Int_Knds;
with Types; use Types;
with Sinfo; use Sinfo;
package A4G.Mapping is
Parent_Node : Node_Id;
-- The determination of the ASIS Internal Element Kind is based on
-- the original tree nodes. Sometimes it requires information about
-- the "context" of a node, that is, about its the parent node.
-- If the node is rewritten, its original node has Parent field
-- set to N_Empty. The global variable Parent_Node is used to
-- transfer the parent node from Node_To_Element function to
-- Asis_Internal_Element_Kind function.
--
-- ???
-- For now, it is defined in the package spec, because it is needed
-- by the current implementation of Enclosing_Element. As soon as
-- the implementation of Enclosing _Element is rewritten on top of
-- Traverse_Element, the declaration of Parent_Node should be
-- moved in the body of the package.
function Asis_Internal_Element_Kind
(Node : Node_Id)
return Internal_Element_Kinds;
-- This function is the kernel of the tree node -> Asis Element
-- mapping. Taking a tree Node, it defines the Internal_Element_Kinds
-- value for the Element which may be constructed on the base of this
-- node. Node should be an original, but not the rewritten node in case
-- if tree rewriting takes place for a given construct.
--
-- This function does not check, whether or not an Element could be
-- really construct for a given Node, a caller is responsible for
-- obtaining the proper node for Element construction, or for filtering
-- out inappropriate nodes in case when this function is applied
-- to construct an Element_List.
--
-- If no Asis_Element could be constructed on the base of the Node, then
-- ASIS_Failed is raised.
--
-- This function is placed in the package spec, because it is needed
-- by A4G.CU_Info2 routines
function N_Operator_Symbol_Mapping
(Node : Node_Id)
return Internal_Element_Kinds;
-- One of the functional components of the general
-- Asis_Internal_Element_Kind function, it is placed in the package spec
-- because it is needed by Asis.Expressions.Prefix.
-- function.
function Is_Not_Duplicated_Decl (Node : Node_Id) return Boolean;
-- This function checks if Node does not correspond to the declaration
-- which is included in the tree twice - first on its own and then
-- as an original node for some rewritten structure. For instance, this
-- is the case for a type derived from private type and having no
-- explicit constrain.
--
-- This function return False for the second of the two duplicated
-- declarations.
--
-- This function is placed in the package spec, because it is used by
-- A4G.Decl_Sem.Serach_First_View
function Subprogram_Attribute_Kind
(Node : Node_Id)
return Internal_Element_Kinds;
-- This function defines the kind of an Element which can be built on
-- N_Attribute_Reference node corresponding to a reference to
-- attribute-subprogram, but opposite to the general attribute kind
-- determination implemented by N_Attribute_Reference_Mapping, it does
-- not classify an Element as a function or a procedure call, but it
-- defines the corresponding Attribute_Kinds value.
function Is_GNAT_Attribute_Routine (N : Node_Id) return Boolean;
-- Checks if N represents a GNAT-specific attribute which is a function or
-- a procedure
function Is_Rewritten_Function_Prefix_Notation
(N : Node_Id)
return Boolean;
-- Checks if N represents a function call given in Object.Operation [(...)]
-- form. In this case N is a rewritten node, and the original subtree
-- is not decorated and the original node is not even classified as
-- a function call
function Is_Rewritten_Impl_Deref_Function_Prefix_Notation
(N : Node_Id)
return Boolean;
-- Checks if N represents a function call given in Object.Operation [(...)]
-- for a special case when the call is used in implicit dereference (the
-- caller is responsible to call this function only for nodes corresponding
-- to implicit dereference!)
function Node_To_Element_New
(Node : Node_Id;
Node_Field_1 : Node_Id := Empty;
Node_Field_2 : Node_Id := Empty;
Starting_Element : Asis.Element := Asis.Nil_Element;
Internal_Kind : Internal_Element_Kinds := Not_An_Element;
Spec_Case : Special_Cases := Not_A_Special_Case;
Norm_Case : Normalization_Cases := Is_Not_Normalized;
Considering_Parent_Count : Boolean := True;
Using_Original_Node : Boolean := True;
Inherited : Boolean := False;
In_Unit : Asis.Compilation_Unit := Asis.Nil_Compilation_Unit)
return Asis.Element;
-- This functions creates the ASIS Element which could be built on the
-- basis of Node. Its other parameters have the following meaning (the
-- wording "the parameter is set" means below that some non-nil value
-- is explicitly passed in the call):
--
-- Starting_Element - if this parameter is set, the following fields
-- of the result Element are set as being equal to the corresponding
-- fields of Starting_Element:
--
-- - Enclosing_Unit (unless the In_Unit parameter is set);
-- - Enclosing_Context (unless the In_Unit parameter is set);
-- - Is_Part_Of_Implicit;
-- - Is_Part_Of_Inherited;
-- - Is_Part_Of_Instance;
-- - Special_Case (unless the Special_Case parameter is set);
-- - Node_Field_1 (unless the Node_Field_1 parameter is set)
-- - Node_Field_2 (unless the Node_Field_2 parameter is set)
-- The typical situation of using this function in the implementations of
-- ASIS (structural) queries is to set Starting_Element as being equal to
-- the argument Element of the ASIS query.
--
-- If Starting_Element is not set, the corresponding fields of the
-- result are computed from Node.
--
-- Internal_Kind - if this parameter is set, its value is set as the
-- value of the Internal_Kind field of the result Element. Otherwise
-- the kind of the result Element is determined automatically
--
-- Spec_Case - if this parameter is set, its value is set as the
-- value of the Special_Case field of the result Element. Otherwise
-- the value of the Special_Case field of the result Element is set
-- from Starting_Element, if Starting_Element itself is set, or as
-- being equal to Not_A_Special_Case, if Starting_Element is not set.
--
-- Norm_Case - This parameter represents if the Element to create is a
-- normalized association. It is not processed by this routine and it
-- is transferred as-is to the low-level Element construction routine.
--
-- Considering_Parent_Count - boolean flag indicating if the value of the
-- Parent_Count field of the Node should be taken into account for the
-- definition of the kind of the Asis Element to be returned by the
-- function.
--
-- Using_Original_Node - boolean flag indicating if the original node
-- should be used as the basis of the Element being constructed.
-- Usually the default True is used, but sometimes we have to
-- avoid using the original node, for example, when constructing the
-- expanded spec for a generic instantiation in case of a library_item
--
-- Inherited - boolean flag indicating if the element being constructed
-- represents a declaration of an implicit inherited subprogram or a
-- subcomponent thereof.
-- ??? why do we need it???
--
-- In_Unit - The Asis Compilation Unit, to which the Element being
-- constructed belongs. It is an error not to set both Starting_Element
-- and In_Unit parameters. If both of them are set, the value of
-- the Enclosing_Unit and Enclosing_Context fields of the result
-- Element are set from In_Unit
--
-- NOTE, that if Starting_Element is NOT set, the Is_Part_Of_Implicit and
-- the Is_Part_Of_Inherited fields of the result are set off (equal to
-- False), therefore the caller (that is, the implementation of the
-- corresponding ASIS query) is responsible for correct setting of these
-- fields. As for the Is_Part_Of_Instance field, it is set on the base of
-- Sloc field of the corresponding Node. (???)
--
-- An Empty node is not an expected parameter for this function. But if it
-- is passed as an actual for Node, the result of the function is
-- Nil_Element, independently of all the other parameters.
function N_To_E_List_New
(List : List_Id;
Include_Pragmas : Boolean := False;
Starting_Element : Asis.Element := Asis.Nil_Element;
Node_Knd : Node_Kind := N_Empty;
Internal_Kind : Internal_Element_Kinds := Not_An_Element;
Special_Case : Special_Cases := Not_A_Special_Case;
Norm_Case : Normalization_Cases := Is_Not_Normalized;
In_Unit : Asis.Compilation_Unit := Asis.Nil_Compilation_Unit)
return Asis.Element_List;
-- This function converts tree Node list into the corresponding ASIS
-- Element List.
--
-- This function is intended to be used to create lists of EXPLICIT
-- ASIS Elements. It checks Comes_From_Source Flag of the tree nodes from
-- its List argument to test if the node should be used to create an
-- Element in the result Element list
--
-- The parameters have the following meaning (we say "if the parameter
-- is set" with the meaning "if some actual different from the default
-- nil value is passed for the parameter")
--
-- List - specifies the tree node list to be converted into an ASIS
-- Element List;
--
-- Include_Pragmas - boolean flags signifying if pragmas should be
-- included in the result list;
--
-- Node_Knd - if this parameter is set, only those nodes from List
-- which have this node kind are used to construct Elements in
-- the result Element List;
--
-- Internal_Kind - if this parameter is set, all the Elements of the
-- result list are set having this kind, otherwise the kind
-- of each element of the result list is determined
-- automatically;
--
-- Special_Case - if this parameter is set, all the Elements of the
-- result list are set having this special case;
--
-- Norm_Case - if this parameter is set, all the Elements of the
-- result list are set having this normalization case;
--
-- Starting_Element - the following fields of all the Elements in
-- the result Element List are set as being equal to the
-- corresponding fields of Starting_Element:
-- - Enclosing_Unit (unless the In_Unit parameter is set);
-- - Enclosing_Context (unless the In_Unit parameter is set);
-- - Is_Part_Of_Implicit;
-- - Is_Part_Of_Inherited;
-- - Is_Part_Of_Instance;
-- - Special_Case (unless the Special_Case parameter is set);
-- Setting Starting_Element as being equal to the argument
-- Element of the ASIS query where N_To_E_List is called
-- to form the result of the query is the common case for the
-- ASIS structural queries
--
-- In_Unit - The Asis Compilation Unit, to which the Elements being
-- constructed belong. It is an error not to set both
-- Starting_Element and In_Unit parameters. If both of them
-- are set, the value of the Enclosing_Unit and
-- Enclosing_Context fields of the result Elements are set
-- from In_Unit
procedure Set_Element_List
(List : List_Id;
Include_Pragmas : Boolean := False;
Starting_Element : Asis.Element := Asis.Nil_Element;
Node_Knd : Node_Kind := N_Empty;
Internal_Kind : Internal_Element_Kinds := Not_An_Element;
Special_Case : Special_Cases := Not_A_Special_Case;
Norm_Case : Normalization_Cases := Is_Not_Normalized;
In_Unit : Asis.Compilation_Unit := Asis.Nil_Compilation_Unit;
Append : Boolean := False);
-- Does exactly the same as the function N_To_E_List_New, but places
-- its result into A4G.Asis_Tables.Internal_Asis_Element_Table.
--
-- If Append parameter is set ON, the list created as the result of the
-- call to this procedure is appended to the current content of the
-- Element Table
--
-- ???
-- It seems that we will have to get rid of functions creating Element
-- Lists and to build Element lists only with Element Table. Moreover, now
-- N_To_E_List_New just calls Set_Element_List with Append OFF and returns
-- the content of Internal_Asis_Element_Table
procedure Set_Inherited_Discriminants (Type_Def : Asis.Element);
-- Provided that Type_Def represents the definition of a derived
-- type which may inherit discriminants, this procedure creates in
-- the Element Table the list of declarations representing inherited
-- discriminants.
-- Note, that this function may not set properly Node_Field_1,
-- Is_Part_Of_Implicit and Is_Part_Of_Inherited fields of the result
-- Elements.
procedure Set_Inherited_Components
(Type_Def : Asis.Element;
Include_Discs : Boolean := True);
-- Provided that Type_Def represents the definition of a derived
-- record type, this procedure creates in
-- A4G.Asis_Tables.Asis_Element_Table the list of declarations representing
-- inherited components. If Include_Discs parameter is set ON, this list
-- also contain discriminants, otherwise it does not. That is, this
-- procedure does not determine itself whether or not the discriminants are
-- inherited by the type, it should be done at the caller side.
-- Note, that this procedure may not set properly Node_Field_1,
-- Is_Part_Of_Implicit and Is_Part_Of_Inherited fields of the result
-- Elements.
procedure Set_Concurrent_Inherited_Components
(Type_Def : Asis.Element;
Include_Discs : Boolean := True);
-- Similar to the previous Set_Inherited_Components procedure, but woks
-- on defininitions of derived concurrent types.
procedure Set_Inherited_Literals (Type_Def : Asis.Element);
-- Provided that Type_Def represents the definition of a derived
-- enumeration type, this procedure creates in
-- A4G.Asis_Tables.Asis_Element_Table the list of enumeration literal
-- specifications representing inherited literals
function Discrete_Choice_Node_To_Element_List
(Choice_List : List_Id;
Starting_Element : Asis.Element)
return Asis.Element_List;
-- This function is a special variant of the Node_To_Element_List
-- function, it constructs the ASIS Element list for an Ada
-- discrete_choice_list. We need a special Note-to-Element list
-- constructor for discrete_choice_list, because the automatic
-- determination of the ASIS kinds for the elements of the resulting
-- ASIS list does not work in this case.
--
-- Starting_Element has the same meaning as in general Node-to-Element
-- and Node-to-Element list constructors.
function Defining_Id_List_From_Normalized
(N : Node_Id;
From_Declaration : Asis.Element)
return Asis.Defining_Name_List;
-- This function constructs an (ASIS) list of A_Defining_Identifier
-- ASIS Elements from a normalized sequence of one-identified
-- declarations or specifications. N should be of one of the
-- following kinds:
-- N_Object_Declaration
-- N_Number_Declaration
-- N_Discriminant_Specification
-- N_Component_Declaration
-- N_Parameter_Specification
-- N_Exception_Declaration
-- N_Formal_Object_Declaration
-- This function is intended to be used in the implementation of
-- Asis.Declarations.Names query
function Normalized_Namet_String (Node : Node_Id) return String;
-- Returns the string representation of the construct representing by
-- Node (assuming that Node represents some terminal Ada construct, such
-- as an identifier) on the base of the information contained in the
-- front-end Name Table and obtained by the value of the Chars field of
-- the Node. This representation is "normalized" by capitalizing the first
-- letter and every letter after underscore (except for some defining names
-- from Standard, such as ASCII, for theses names all the letters are
-- converted to upper case)
function Ureal_Image (N : Node_Id) return String;
-- Returns the string representation of a value represented by an
-- N_Real_Literal node.
function Is_Statement (N : Node_Id) return Boolean;
-- Checks if N is a statement node.
function Parenth_Count
(N : Node_Id;
Original_N : Node_Id)
return Nat;
-- This function is the same as Atree.Paren_Count, except that in case of
-- the argument of a qualified expression, it decreases the level of
-- parentheses to return the result corresponding to the syntax defined
-- in RM 4.7(2) (see 9114-002)
function Get_Next_Configuration_Pragma (N : Node_Id) return Node_Id;
-- Returns the next configuration pragma node in the list. (If the argument
-- is a configuration pragma node, returns the argument). If there is no
-- more configuration pragmas in the list or if N is an empty node, returns
-- Empty. A caller is responsible for calling this function for list
-- elements only.
end A4G.Mapping;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
edd174bcca7ded13835bc622b01ff1380cbc4dea
|
test/AdaFrontend/vce.adb
|
test/AdaFrontend/vce.adb
|
-- RUN: %llvmgcc -c %s -o /dev/null
procedure VCE is
S : String (1 .. 2);
B : Character := 'B';
begin
S := 'A' & B;
end;
|
Test that the size of a view converted object is determined by the target type, not the source type.
|
Test that the size of a view converted object is determined by the target
type, not the source type.
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@35106 91177308-0d34-0410-b5e6-96231b3b80d8
|
Ada
|
apache-2.0
|
llvm-mirror/llvm,dslab-epfl/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,chubbymaggie/asap,dslab-epfl/asap,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,apple/swift-llvm,dslab-epfl/asap,dslab-epfl/asap,llvm-mirror/llvm,apple/swift-llvm,chubbymaggie/asap,llvm-mirror/llvm,dslab-epfl/asap,chubbymaggie/asap,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,chubbymaggie/asap,apple/swift-llvm,llvm-mirror/llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,dslab-epfl/asap
|
|
daf4b5c5cec0dae4e79c4d68f52d685223a7c729
|
src/asf-components-widgets-gravatars.ads
|
src/asf-components-widgets-gravatars.ads
|
-----------------------------------------------------------------------
-- components-widgets-gravatars -- Gravatar Components
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Components.Html;
with ASF.Contexts.Faces;
package ASF.Components.Widgets.Gravatars is
-- Given an Email address, return the Gravatar link to the user image.
-- (See http://en.gravatar.com/site/implement/hash/ and
-- http://en.gravatar.com/site/implement/images/)
function Get_Link (Email : in String;
Secure : in Boolean := False) return String;
-- ------------------------------
-- UIGravatar
-- ------------------------------
-- The <b>UIGravatar</b> component displays a small image whose link is created
-- from a user email address.
type UIGravatar is new ASF.Components.Html.UIHtmlComponent with null record;
-- Render an image with the source link created from an email address to the Gravatars service.
overriding
procedure Encode_Begin (UI : in UIGravatar;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
end ASF.Components.Widgets.Gravatars;
|
Define the gravatar UI component
|
Define the gravatar UI component
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
|
820003ded1b4a142d19221523fc9d06ef0a38f31
|
regtests/wiki-filters-html-tests.ads
|
regtests/wiki-filters-html-tests.ads
|
-----------------------------------------------------------------------
-- wiki-filters-html-tests -- Unit tests for wiki HTML filters
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package Wiki.Filters.Html.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test Find_Tag operation.
procedure Test_Find_Tag (T : in out Test);
end Wiki.Filters.Html.Tests;
|
Add a unit test for HTML filter internals
|
Add a unit test for HTML filter internals
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
|
72e7a162b6b54e95ea76d0d6af3a1dfcb7fdc934
|
src/util-log-locations.adb
|
src/util-log-locations.adb
|
-----------------------------------------------------------------------
-- util-log-locations -- General purpose source file location
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 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.Strings;
package body Util.Log.Locations is
-- ------------------------------
-- Create a <b>File_Info</b> record to identify the file whose path is <b>Path</b>
-- and whose relative path portion starts at <b>Relative_Position</b>.
-- ------------------------------
function Create_File_Info (Path : in String;
Relative_Position : in Natural) return File_Info_Access is
begin
return new File_Info '(Length => Path'Length,
Path => Path,
Relative_Pos => Relative_Position);
end Create_File_Info;
-- ------------------------------
-- Get the relative path name
-- ------------------------------
function Relative_Path (File : in File_Info) return String is
begin
return File.Path (File.Relative_Pos .. File.Path'Last);
end Relative_Path;
-- ------------------------------
-- Get the line number
-- ------------------------------
function Line (Info : Line_Info) return Natural is
begin
return Info.Line;
end Line;
-- ------------------------------
-- Get the column number
-- ------------------------------
function Column (Info : Line_Info) return Natural is
begin
return Info.Column;
end Column;
-- ------------------------------
-- Get the source file
-- ------------------------------
function File (Info : Line_Info) return String is
begin
return Info.File.Path;
end File;
-- ------------------------------
-- Create a source line information.
-- ------------------------------
function Create_Line_Info (File : in File_Info_Access;
Line : in Natural;
Column : in Natural := 0) return Line_Info is
Result : Line_Info;
begin
Result.Line := Line;
Result.Column := Column;
if File = null then
Result.File := NO_FILE'Access;
else
Result.File := File;
end if;
return Result;
end Create_Line_Info;
-- ------------------------------
-- Get a printable representation of the line information using
-- the format:
-- <path>:<line>[:<column>]
-- The path can be reported as relative or absolute path.
-- The column is optional and reported by default.
-- ------------------------------
function To_String (Info : in Line_Info;
Relative : in Boolean := True;
Column : in Boolean := True) return String is
begin
if Relative then
if Column then
return Relative_Path (Info.File.all) & ":" & Util.Strings.Image (Info.Line)
& ":" & Util.Strings.Image (Info.Column);
else
return Relative_Path (Info.File.all) & ":" & Util.Strings.Image (Info.Line);
end if;
else
if Column then
return Info.File.Path & ":" & Util.Strings.Image (Info.Line)
& ":" & Util.Strings.Image (Info.Column);
else
return Info.File.Path & ":" & Util.Strings.Image (Info.Line);
end if;
end if;
end To_String;
end Util.Log.Locations;
|
Implement the package (taken from ASF.Views package implementation)
|
Implement the package (taken from ASF.Views package implementation)
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
|
b754c0a533520dd87def5b2eed9cfa76d62c75ea
|
src/asis/a4g-defaults.adb
|
src/asis/a4g-defaults.adb
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . D E F A U L T S --
-- --
-- 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 Unchecked_Deallocation;
with A4G.A_Osint; use A4G.A_Osint;
with A4G.U_Conv; use A4G.U_Conv;
with Output; use Output;
package body A4G.Defaults is
procedure Free_String is new Unchecked_Deallocation
(String, String_Access);
procedure Add_Src_Search_Dir (Dir : String);
-- Add Dir at the end of the default source file search path.
procedure Add_Lib_Search_Dir (Dir : String);
-- Add Dir at the end of the default library (=object+ALI) file search
-- path.
------------------------
-- Add_Lib_Search_Dir --
------------------------
procedure Add_Lib_Search_Dir (Dir : String) is
begin
ASIS_Lib_Search_Directories.Increment_Last;
ASIS_Lib_Search_Directories.Table (ASIS_Lib_Search_Directories.Last) :=
new String'(Normalize_Directory_Name (Dir));
end Add_Lib_Search_Dir;
------------------------
-- Add_Src_Search_Dir --
------------------------
procedure Add_Src_Search_Dir (Dir : String) is
begin
ASIS_Src_Search_Directories.Increment_Last;
ASIS_Src_Search_Directories.Table (ASIS_Src_Search_Directories.Last) :=
new String'(Normalize_Directory_Name (Dir));
end Add_Src_Search_Dir;
--------------
-- Finalize --
--------------
procedure Finalize is
begin
-- finalise ASIS_Src_Search_Directories:
for I in First_Dir_Id .. ASIS_Src_Search_Directories.Last loop
Free_String (ASIS_Src_Search_Directories.Table (I));
end loop;
-- finalize ASIS_Lib_Search_Directories:
for I in First_Dir_Id .. ASIS_Lib_Search_Directories.Last loop
Free_String (ASIS_Lib_Search_Directories.Table (I));
end loop;
-- finalize ASIS_Tree_Search_Directories
for I in First_Dir_Id .. ASIS_Tree_Search_Directories.Last loop
Free_String (ASIS_Tree_Search_Directories.Table (I));
end loop;
end Finalize;
----------------
-- Initialize --
----------------
procedure Initialize is
Search_Path : String_Access;
begin
-- just in case:
Finalize;
ASIS_Src_Search_Directories.Init;
ASIS_Lib_Search_Directories.Init;
ASIS_Tree_Search_Directories.Init;
-- stroring the defaults for: the code is stolen from Osint
-- (body, rev. 1.147) and then adjusted
for Dir_kind in Search_Dir_Kinds loop
case Dir_kind is
when Source =>
Search_Path := Getenv ("ADA_INCLUDE_PATH");
when Object =>
Search_Path := Getenv ("ADA_OBJECTS_PATH");
when Tree =>
-- There is no environment variable for separate
-- tree path at the moment;
exit;
end case;
if Search_Path'Length > 0 then
declare
Lower_Bound : Positive := 1;
Upper_Bound : Positive;
begin
loop
while Lower_Bound <= Search_Path'Last
and then Search_Path.all (Lower_Bound) =
ASIS_Path_Separator
loop
Lower_Bound := Lower_Bound + 1;
end loop;
exit when Lower_Bound > Search_Path'Last;
Upper_Bound := Lower_Bound;
while Upper_Bound <= Search_Path'Last
and then Search_Path.all (Upper_Bound) /=
ASIS_Path_Separator
loop
Upper_Bound := Upper_Bound + 1;
end loop;
case Dir_kind is
when Source =>
Add_Src_Search_Dir
(Search_Path.all (Lower_Bound .. Upper_Bound - 1));
when Object =>
Add_Lib_Search_Dir
(Search_Path.all (Lower_Bound .. Upper_Bound - 1));
when Tree =>
exit; -- non implemented yet;
end case;
Lower_Bound := Upper_Bound + 1;
end loop;
end;
end if;
end loop;
-- ??? TEMPORARY SOLUTION: the default objects search path
-- is also used as the default tree path
for J in First_Dir_Id .. ASIS_Lib_Search_Directories.Last loop
ASIS_Tree_Search_Directories.Increment_Last;
ASIS_Tree_Search_Directories.Table
(ASIS_Tree_Search_Directories.Last) :=
new String'(ASIS_Lib_Search_Directories.Table (J).all);
end loop;
Free (Search_Path);
end Initialize;
-------------------------
-- Locate_Default_File --
-------------------------
function Locate_Default_File
(File_Name : String_Access;
Dir_Kind : Search_Dir_Kinds)
return String_Access
is
function Is_Here_In_Src (File_Name : String_Access; Dir : Dir_Id)
return Boolean;
function Is_Here_In_Lib (File_Name : String_Access; Dir : Dir_Id)
return Boolean;
-- funtion Is_Here_In_Tree (File_Name : String_Access; Dir : Dir_Id)
-- return Boolean;
function Is_Here_In_Src (File_Name : String_Access; Dir : Dir_Id)
return Boolean
is
begin
return Is_Regular_File (ASIS_Src_Search_Directories.Table (Dir).all
& To_String (File_Name));
end Is_Here_In_Src;
function Is_Here_In_Lib (File_Name : String_Access; Dir : Dir_Id)
return Boolean
is
begin
return Is_Regular_File (ASIS_Lib_Search_Directories.Table (Dir).all
& To_String (File_Name));
end Is_Here_In_Lib;
begin
case Dir_Kind is
when Source =>
for Dir in First_Dir_Id .. ASIS_Src_Search_Directories.Last loop
if Is_Here_In_Src (File_Name, Dir) then
return new String'
(ASIS_Src_Search_Directories.Table (Dir).all
& File_Name.all);
end if;
end loop;
when Object =>
for Dir in First_Dir_Id .. ASIS_Lib_Search_Directories.Last loop
if Is_Here_In_Lib (File_Name, Dir) then
return new String'
(ASIS_Lib_Search_Directories.Table (Dir).all
& File_Name.all);
end if;
end loop;
when Tree =>
null; -- non implemented yet;
end case;
return null;
end Locate_Default_File;
------------------------
-- Print_Lib_Defaults --
------------------------
procedure Print_Lib_Defaults is
begin
if ASIS_Lib_Search_Directories.Last < First_Dir_Id then
Write_Str (" No default library files search path");
Write_Eol;
else
for Dir in First_Dir_Id .. ASIS_Lib_Search_Directories.Last loop
Write_Str (" " & ASIS_Lib_Search_Directories.Table (Dir).all);
Write_Eol;
end loop;
end if;
end Print_Lib_Defaults;
---------------------------
-- Print_Source_Defaults --
---------------------------
procedure Print_Source_Defaults is
begin
if ASIS_Src_Search_Directories.Last < First_Dir_Id then
Write_Str (" No default source search path");
Write_Eol;
else
for Dir in First_Dir_Id .. ASIS_Src_Search_Directories.Last loop
Write_Str (" " & ASIS_Src_Search_Directories.Table (Dir).all);
Write_Eol;
end loop;
end if;
end Print_Source_Defaults;
-------------------------
-- Print_Tree_Defaults --
-------------------------
procedure Print_Tree_Defaults is
begin
if ASIS_Tree_Search_Directories.Last < First_Dir_Id then
Write_Str (" No default tree files search path");
Write_Eol;
else
for Dir in First_Dir_Id .. ASIS_Tree_Search_Directories.Last loop
Write_Str (" " & ASIS_Tree_Search_Directories.Table (Dir).all);
Write_Eol;
end loop;
end if;
end Print_Tree_Defaults;
end A4G.Defaults;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
887839d755e172fd6e8560acc456e97ef2d4ba5f
|
test/AdaFrontend/array_range_ref.adb
|
test/AdaFrontend/array_range_ref.adb
|
-- RUN: %llvmgcc -c %s -o /dev/null
procedure Array_Range_Ref is
A : String (1 .. 3);
B : String := A (A'RANGE)(1 .. 3);
begin
null;
end;
|
Test that ARRAY_RANGE_REF returns an array not an element.
|
Test that ARRAY_RANGE_REF returns an array not an element.
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@35209 91177308-0d34-0410-b5e6-96231b3b80d8
|
Ada
|
apache-2.0
|
llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,chubbymaggie/asap,apple/swift-llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,dslab-epfl/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,dslab-epfl/asap,GPUOpen-Drivers/llvm,chubbymaggie/asap,dslab-epfl/asap,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,apple/swift-llvm,chubbymaggie/asap,apple/swift-llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,chubbymaggie/asap,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,dslab-epfl/asap
|
|
b3576538411bac62e7c164a4a9f3d950bfe11f8c
|
awa/plugins/awa-images/src/awa-images-servlets.adb
|
awa/plugins/awa-images/src/awa-images-servlets.adb
|
-----------------------------------------------------------------------
-- awa-images-servlets -- Serve files saved in the storage service
-- 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 AWA.Images.Servlets is
-- ------------------------------
-- Load the data content that correspond to the GET request and get the name as well
-- as mime-type and date.
-- ------------------------------
overriding
procedure Load (Server : in Image_Servlet;
Request : in out ASF.Requests.Request'Class;
Name : out Ada.Strings.Unbounded.Unbounded_String;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Data : out ADO.Blob_Ref) is
begin
AWA.Storages.Servlets.Storage_Servlet (Server).Load (Request, Name, Mime, Date, Data);
Name := Ada.Strings.Unbounded.To_Unbounded_String ("");
end Load;
end AWA.Images.Servlets;
|
Implement the Load procedure
|
Implement the Load procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
|
2fd777f96d694382c1d9d9dc80a5f30ba24d21f0
|
src/asis/asis-data_decomposition-debug.ads
|
src/asis/asis-data_decomposition-debug.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 . D E B U G --
-- --
-- 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 routines forming debug images for bstractions
-- declared in Asis.Data_Decomposition.
package Asis.Data_Decomposition.Debug is
function Debug_Image (RC : Record_Component) return Wide_String;
function Debug_Image (AC : Array_Component) return Wide_String;
-- Returns a string value containing implementation-defined debug
-- information associated with the element.
--
-- The return value uses Asis.Text.Delimiter_Image to separate the lines
-- of multi-line results. The return value does not end with
-- Asis.Text.Delimiter_Image.
function Is_Derived_From_Record (TD : Element) return Boolean;
function Is_Derived_From_Array (TD : Element) return Boolean;
-- The public renaming of
-- Asis.Data_Decomposition.Aux.Is_Derived_From_Record/
-- Asis.Data_Decomposition.Aux.Is_Derived_From_Array
-- May be, we should have it in Asis.Extensions
function Dimension (Comp : Array_Component) return ASIS_Natural;
-- The public renaming of
-- Asis.Data_Decomposition.Set_Get.Dimension
-- May be, we should have it in Asis.Extensions
-- function Linear_Index
-- (Inds : Dimension_Indexes;
-- D : ASIS_Natural;
-- 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;
-- The public renaming of
-- Asis.Data_Decomposition.Aux.Linear_Index and
-- Asis.Data_Decomposition.Aux.De_Linear_Index
end Asis.Data_Decomposition.Debug;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
94eb9c33db2894a82e1828820a42941564aef8a2
|
src/asf-rest-operation.ads
|
src/asf-rest-operation.ads
|
-----------------------------------------------------------------------
-- asf-rest-operation -- REST API Operation Definition
-- 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.
-----------------------------------------------------------------------
generic
Handler : Operation_Access;
Method : Method_Type := GET;
URI : String;
Permission : Security.Permissions.Permission_Index := Security.Permissions.NONE;
package ASF.Rest.Operation is
function Definition return Descriptor_Access;
end ASF.Rest.Operation;
|
Define new generic package for the REST API definition
|
Define new generic package for the REST API definition
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
|
dc8cf2be7547bba187f23280be891c5166e67ffd
|
mat/src/mat-expressions.adb
|
mat/src/mat-expressions.adb
|
-----------------------------------------------------------------------
-- mat-expressions -- Expressions for memory slot selection
-- 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 MAT.Types;
with MAT.Memory;
package body MAT.Expressions is
-- ------------------------------
-- Create a NOT expression node.
-- ------------------------------
function Create_Not (Expr : in Expression_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Util.Refs.Ref_Entity with
Kind => N_NOT, Expr => Expr.Node);
return Result;
end Create_Not;
end MAT.Expressions;
|
Implement the Create_Not operation
|
Implement the Create_Not operation
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
|
681b412f80de32a5714cd70e22176fab026d3f01
|
src/asis/a4g-span_end.ads
|
src/asis/a4g-span_end.ads
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . S P A N _ E N D --
-- --
-- S p e c --
-- --
-- Copyright (c) 1995-1999, Free Software Foundation, Inc. --
-- --
-- ASIS-for-GNAT is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 2, or (at your option) any later --
-- version. ASIS-for-GNAT is distributed in the hope that it will be use- --
-- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- --
-- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General --
-- Public License for more details. You should have received a copy of the --
-- GNU General Public License distributed with ASIS-for-GNAT; see file --
-- COPYING. If not, write to the Free Software Foundation, 59 Temple Place --
-- - Suite 330, Boston, MA 02111-1307, USA. --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the --
-- Software Engineering Laboratory of the Swiss Federal Institute of --
-- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the --
-- Scientific Research Computer Center of Moscow State University (SRCC --
-- MSU), Russia, with funding partially provided by grants from the Swiss --
-- National Science Foundation and the Swiss Academy of Engineering --
-- Sciences. ASIS-for-GNAT is now maintained by Ada Core Technologies Inc --
-- (http://www.gnat.com). --
-- --
------------------------------------------------------------------------------
with Asis; use Asis;
with Types; use Types;
package A4G.Span_End is
-- This package encapsulates queries needed to find the end of Element's
-- Span (as the pointer to the Source Buffer).
function Set_Image_End (E : Asis.Element) return Source_Ptr;
-- This is the main function in this package. It returns the pointer
-- to the last character of the given element in the Source Buffer
end A4G.Span_End;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
b819a2b5fef660298b4f38ce951dd7f679f66b4f
|
test/AdaFrontend/switch.adb
|
test/AdaFrontend/switch.adb
|
-- RUN: %llvmgcc -c %s -o /dev/null
function Switch (N : Integer) return Integer is
begin
case N is
when Integer'First .. -1 =>
return -1;
when 0 =>
return 0;
when others =>
return 1;
end case;
end;
|
Test handling of switches with wide case ranges.
|
Test handling of switches with wide case ranges.
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@35279 91177308-0d34-0410-b5e6-96231b3b80d8
|
Ada
|
apache-2.0
|
GPUOpen-Drivers/llvm,llvm-mirror/llvm,chubbymaggie/asap,dslab-epfl/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,dslab-epfl/asap,chubbymaggie/asap,llvm-mirror/llvm,dslab-epfl/asap,llvm-mirror/llvm,llvm-mirror/llvm,dslab-epfl/asap,dslab-epfl/asap,apple/swift-llvm,chubbymaggie/asap,llvm-mirror/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,chubbymaggie/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,dslab-epfl/asap
|
|
5e130808555314c3fcabb088ae535befe7fd0dbe
|
src/asis/asis-data_decomposition-set_get.ads
|
src/asis/asis-data_decomposition-set_get.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 . S E T _ G E T --
-- --
-- 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, 59 Temple Place --
-- - Suite 330, Boston, MA 02111-1307, USA. --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the --
-- Software Engineering Laboratory of the Swiss Federal Institute of --
-- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the --
-- Scientific Research Computer Center of Moscow State University (SRCC --
-- MSU), Russia, with funding partially provided by grants from the Swiss --
-- National Science Foundation and the Swiss Academy of Engineering --
-- Sciences. ASIS-for-GNAT is now maintained by Ada Core Technologies Inc --
-- (http://www.gnat.com). --
-- --
------------------------------------------------------------------------------
-- This package contains access and update routines for abstractions
-- declared in Asis.Data_Decomposition.
--
-- It also contains routines for creating lists of record and array
-- components
with A4G.Asis_Tables; use A4G.Asis_Tables;
with A4G.DDA_Aux; use A4G.DDA_Aux;
with Table;
private package Asis.Data_Decomposition.Set_Get is
-- Tables used to create query results which are of list types:
package Record_Component_Table is new Table.Table (
Table_Component_Type => Record_Component,
Table_Index_Type => Asis.ASIS_Natural,
Table_Low_Bound => 1,
Table_Initial => 10,
Table_Increment => 100,
Table_Name => "Record_Componnet_List");
RC_Table : Record_Component_Table.Table_Ptr renames
Record_Component_Table.Table;
Def_N_Table : Asis_Element_Table.Table_Ptr renames
Asis_Element_Table.Table;
Nil_Record_Component_List : Record_Component_List (1 .. 0);
-- Nil constant for Record_Component_List is not provided in the
-- Asis.Data_Decomposition package.
Parent_Type_Definition : Element;
-- Global variable used to store the type definition from which componnets
-- are extracted
Record_Type_Entity : Entity_Id;
-- Global variable used to store the type entity defining the type of
-- a record. This is a type entity which actually defines the
-- type, that is, it may be an implicit type as well
procedure Set_Parent_Type_Definition (E : Element);
-- Sets Parent_Type_Definition (Currently this is a trivial assignment,
-- but we would better keep procedural interface in case if something
-- more smart is really required here.
procedure Set_Record_Type_Entity (RC : Record_Component);
-- Sets Record_Type_Entity for RC, if Is_Record (RC)
procedure Set_Record_Type_Entity (AC : Array_Component);
-- Sets Record_Type_Entity for AC, if Is_Record (AC)
procedure Set_Record_Type_Entity;
-- Sets Record_Type_Entity by using the valuse of Parent_Type_Definition
-- global variable
-- Access functions to Record_Component fields:
subtype RC is Record_Component;
function Parent_Record_Type (Comp : RC) return Asis.Declaration;
function Component_Name (Comp : RC) return Asis.Defining_Name;
function Is_Record_Comp (Comp : RC) return Boolean;
function Is_Array_Comp (Comp : RC) return Boolean;
function Parent_Discrims (Comp : RC) return Discrim_List;
function Get_Type_Entity (Comp : RC) return Entity_Id;
-- Returns type Entity describing the subtype of the component.
-- It may be implicit type as well
function Get_Comp_Entity (Comp : RC) return Entity_Id;
-- Returns the Entity Id of the given record component
function Get_Record_Entity (Comp : RC) return Entity_Id;
-- Returns the Entity Id of the enclosing record type declaration
-- for a given component (it may be a type derived from a record type)
-- Array Components:
subtype AC is Array_Component;
function Parent_Array_Type (Comp : AC) return Asis.Declaration;
function Is_Record_Comp (Comp : AC) return Boolean;
function Is_Array_Comp (Comp : AC) return Boolean;
function Dimension (Comp : AC) return ASIS_Natural;
function Parent_Discrims (Comp : AC) return Discrim_List;
function Get_Array_Type_Entity (Comp : AC) return Entity_Id;
-- Returns the Entity_Id for the array type from which this array
-- component is extracted. It may be the Id of some implicit array type
-- as well
procedure Set_Parent_Discrims (Comp : in out AC; Discs : Discrim_List);
-- Sets Discs as Parent_Discrims for Comp. In case if Discs is
-- Null_Discrims sets Parent_Discrims as null.
type List_Kinds is (New_List, Append);
-- The way of creating a list in Element or Component Table
procedure Set_Named_Components (E : Element; List_Kind : List_Kinds);
-- Stores all the A_Defining_Identifier components contained in E in
-- Asis_Element_Table. If List_Kind is set to New_List, it resets
-- Asis_Element_Table before putting any information in it. If List_Kind
-- is set to Append, the Table is not reset, and the created list
-- is appended to the list already stored in the table.
procedure Set_All_Named_Components (E : Element);
-- Provided that E is a record type definition or a definition of a
-- derived type derived from some record type, this function
-- stores all the A_Defining_Identifier Elements defining the
-- componnets for this type in Asis_Element_Table. Before doing this,
-- the procedure resets Asis_Element_Table.
procedure Set_Record_Components_From_Names
(Parent_First_Bit : ASIS_Natural := 0;
Data_Stream : Portable_Data := Nil_Portable_Data;
Discriminants : Boolean := False);
-- Supposing that an appropriate list of component defining names is set
-- in the Asis_Element_Table, this procedure converts them into
-- the corresponding list of record componnets in Record_Component_Table.
--
-- Parent_First_Bit is needed to compute the first bit and position of
-- the component that is extracted from another (record or array)
-- component. Usually everything is alligned at least bytewise, but in case
-- if representation clauses are used to create heavily packed data
-- structure, we may need to know where to start to compute the component
-- beginning
--
-- If Data_Stream parameter is set, it is used to define which
-- components from the list set in Asis_Element_Table should be
-- presented in the result.
--
-- Discriminants flag is used to indicate the case when (only)
-- discriminant components should be constructed, in this case no
-- discriminant constraint (explicit or default) should be taken into
-- account (they may be dynamic in case of A_Complex_Dynamic_Model type).
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;
-- Sets and returns an Array_Component value. Array_Type_Definition
-- parameter should represent a (constrained or unconstrained) array type
-- definition or a derived type definition for which an ancestor type is
-- an array type. The returned value represent the component of this array
-- type. Enclosing_Record_Component is set when the array componnet to be
-- created is a part of some Record_Component, in this case the
-- corresponding component definition may contain index constraints.
-- Parent_Indication is set when the array componnet to be created is a
-- part of some other array component, in this case the corresponding
-- component subtype indication may contain an index constraint
-- ???? Documentation needs revising!!!
end Asis.Data_Decomposition.Set_Get;
|
Add the ASIS file $i
|
Add the ASIS file $i
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
|
2d0bd022f3f1ccc3b05af0a84a2010e81cfbb54f
|
awa/plugins/awa-wikis/src/awa-wikis-servlets.adb
|
awa/plugins/awa-wikis/src/awa-wikis-servlets.adb
|
-----------------------------------------------------------------------
-- awa-wikis-servlets -- Serve files saved in the storage service
-- 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 Ada.Calendar;
with Util.Log.Loggers;
with ADO.Objects;
with ASF.Streams;
with AWA.Wikis.Modules;
package body AWA.Wikis.Servlets is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Wikis.Servlets");
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
overriding
procedure Initialize (Server : in out Image_Servlet;
Context : in ASF.Servlets.Servlet_Registry'Class) is
begin
null;
end Initialize;
-- ------------------------------
-- Called by the server (via the service method) to allow a servlet to handle
-- a GET request.
--
-- Overriding this method to support a GET request also automatically supports
-- an HTTP HEAD request. A HEAD request is a GET request that returns no body
-- in the response, only the request header fields.
--
-- When overriding this method, read the request data, write the response headers,
-- get the response's writer or output stream object, and finally, write the
-- response data. It's best to include content type and encoding.
-- When using a PrintWriter object to return the response, set the content type
-- before accessing the PrintWriter object.
--
-- The servlet container must write the headers before committing the response,
-- because in HTTP the headers must be sent before the response body.
--
-- Where possible, set the Content-Length header (with the
-- Response.Set_Content_Length method), to allow the servlet container
-- to use a persistent connection to return its response to the client,
-- improving performance. The content length is automatically set if the entire
-- response fits inside the response buffer.
--
-- When using HTTP 1.1 chunked encoding (which means that the response has a
-- Transfer-Encoding header), do not set the Content-Length header.
--
-- The GET method should be safe, that is, without any side effects for which
-- users are held responsible. For example, most form queries have no side effects.
-- If a client request is intended to change stored data, the request should use
-- some other HTTP method.
--
-- The GET method should also be idempotent, meaning that it can be safely repeated.
-- Sometimes making a method safe also makes it idempotent. For example, repeating
-- queries is both safe and idempotent, but buying a product online or modifying
-- data is neither safe nor idempotent.
--
-- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request"
-- ------------------------------
overriding
procedure Do_Get (Server : in Image_Servlet;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
pragma Unreferenced (Server);
Data : ADO.Blob_Ref;
Mime : Ada.Strings.Unbounded.Unbounded_String;
Date : Ada.Calendar.Time;
Module : constant AWA.Wikis.Modules.Wiki_Module_Access := Wikis.Modules.Get_Wiki_Module;
Wiki : constant String := Request.Get_Path_Parameter (1);
File : constant String := Request.Get_Path_Parameter (2);
Name : constant String := Request.Get_Path_Parameter (3);
Wiki_Id : ADO.Identifier;
File_Id : ADO.Identifier;
begin
Wiki_Id := ADO.Identifier'Value (Wiki);
File_Id := ADO.Identifier'Value (File);
Log.Info ("GET storage file {0}/{1}/{2}", Wiki, File, Name);
Module.Load_Image (Wiki_Id => Wiki_Id,
Image_Id => File_Id,
Mime => Mime,
Date => Date,
Into => Data);
-- Send the file.
Response.Set_Content_Type (Ada.Strings.Unbounded.To_String (Mime));
declare
Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream;
begin
Output.Write (Data.Value.Data);
end;
exception
when ADO.Objects.NOT_FOUND | Constraint_Error =>
Log.Info ("Storage file {0}/{1}/{2} not found", Wiki, File, Name);
Response.Send_Error (ASF.Responses.SC_NOT_FOUND);
return;
end Do_Get;
end AWA.Wikis.Servlets;
|
Implement the Image_Servlet type and operations
|
Implement the Image_Servlet type and operations
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
|
1d1180c4c3807ed7ce4a88c6603b826a37add745
|
awa/plugins/awa-wikis/src/awa-wikis-previews.ads
|
awa/plugins/awa-wikis/src/awa-wikis-previews.ads
|
-----------------------------------------------------------------------
-- awa-wikis-previews -- Wiki preview management
-- 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.Applications;
with AWA.Modules;
with AWA.Jobs.Services;
with AWA.Wikis.Modules;
with AWA.Wikis.Models;
-- == Wiki Preview Module ==
-- The <tt>AWA.Wikis.Previews</tt> package implements a preview image generation for a wiki page.
-- This module is optional, it is possible to use the wikis without preview support. When the
-- module is registered, it listens to wiki page lifecycle events. When a new wiki content is
-- changed, it triggers a job to make the preview. The preview job uses the
-- <tt>wkhtmotoimage</tt> external program to make the preview image.
package AWA.Wikis.Previews is
-- The name under which the module is registered.
NAME : constant String := "wiki-previews";
-- The worker procedure that performs the preview job.
procedure Preview_Worker (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class);
-- Preview job definition.
package Preview_Job_Definition is new AWA.Jobs.Services.Work_Definition (Preview_Worker'Access);
-- ------------------------------
-- Preview wiki module
-- ------------------------------
type Preview_Module is new AWA.Modules.Module
and AWA.Wikis.Modules.Wiki_Lifecycle.Listener with private;
type Preview_Module_Access is access all Preview_Module'Class;
-- Initialize the preview wiki module.
overriding
procedure Initialize (Plugin : in out Preview_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- The `On_Create` procedure is called by `Notify_Create` to notify the creation of the page.
overriding
procedure On_Create (Instance : in Preview_Module;
Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class);
-- The `On_Update` procedure is called by `Notify_Update` to notify the update of the page.
overriding
procedure On_Update (Instance : in Preview_Module;
Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class);
-- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion of the page.
overriding
procedure On_Delete (Instance : in Preview_Module;
Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class);
private
type Preview_Module is new AWA.Modules.Module
and AWA.Wikis.Modules.Wiki_Lifecycle.Listener with null record;
end AWA.Wikis.Previews;
|
Define the wiki Previews package module for the generation of wiki page thumbnail preview
|
Define the wiki Previews package module for the generation of wiki page thumbnail preview
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
|
9542c303ce2ece915c4bf4dcb688c1bb779eed18
|
src/util-properties-json.adb
|
src/util-properties-json.adb
|
-----------------------------------------------------------------------
-- util-properties-json -- read json files into properties
-- 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.JSON;
with Util.Stacks;
with Util.Beans.Objects;
package body Util.Properties.JSON is
type Natural_Access is access all Natural;
package Length_Stack is new Util.Stacks (Element_Type => Natural,
Element_Type_Access => Natural_Access);
type Parser is new Util.Serialize.IO.JSON.Parser with record
Base_Name : Ada.Strings.Unbounded.Unbounded_String;
Lengths : Length_Stack.Stack;
Separator : Ada.Strings.Unbounded.Unbounded_String;
Separator_Length : Natural;
end record;
-- 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);
-- 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);
-- -----------------------
-- 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;
-- -----------------------
-- Parse the JSON content and put the flattened content in the property manager.
-- -----------------------
procedure Parse_JSON (Manager : in out Util.Properties.Manager'Class;
Content : in String;
Flatten_Separator : in String := ".") is
type Local_Parser is new Parser with null record;
-- 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 Local_Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False);
-- -----------------------
-- 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 Local_Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False) is
pragma Unreferenced (Attribute);
begin
Manager.Set (Ada.Strings.Unbounded.To_String (Handler.Base_Name) & Name,
Util.Beans.Objects.To_String (Value));
end Set_Member;
P : Local_Parser;
begin
P.Separator := Ada.Strings.Unbounded.To_Unbounded_String (Flatten_Separator);
P.Separator_Length := Flatten_Separator'Length;
P.Parse_String (Content);
end Parse_JSON;
-- -----------------------
-- Read the JSON file into the property manager.
-- The JSON content is flatten into Flatten the JSON content and add the properties.
-- -----------------------
procedure Read_JSON (Manager : in out Util.Properties.Manager'Class;
Path : in String;
Flatten_Separator : in String := ".") is
type Local_Parser is new Parser with null record;
-- 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 Local_Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False);
-- -----------------------
-- 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 Local_Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False) is
pragma Unreferenced (Attribute);
begin
Manager.Set (Ada.Strings.Unbounded.To_String (Handler.Base_Name) & Name,
Util.Beans.Objects.To_String (Value));
end Set_Member;
P : Local_Parser;
begin
P.Separator := Ada.Strings.Unbounded.To_Unbounded_String (Flatten_Separator);
P.Separator_Length := Flatten_Separator'Length;
P.Parse (Path);
end Read_JSON;
end Util.Properties.JSON;
|
Implement reading JSON content and putting it in property manager
|
Implement reading JSON content and putting it in property manager
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.