diff --git a/langkit/support/langkit_support-iterators.adb b/langkit/support/langkit_support-iterators.adb new file mode 100644 index 000000000..7cf69148c --- /dev/null +++ b/langkit/support/langkit_support-iterators.adb @@ -0,0 +1,21 @@ +package body Langkit_Support.Iterators is + + ------------- + -- Iterate -- + ------------- + + procedure Iterate + (I : in out Iterator'Class; + Proc : access procedure (Element : Element_Type)) + is + Has_Next : Boolean; + Element : Element_Type; + begin + loop + I.Next (Has_Next, Element); + exit when not Has_Next; + Proc (Element); + end loop; + end Iterate; + +end Langkit_Support.Iterators; diff --git a/langkit/support/langkit_support-iterators.ads b/langkit/support/langkit_support-iterators.ads new file mode 100644 index 000000000..a6d0d5260 --- /dev/null +++ b/langkit/support/langkit_support-iterators.ads @@ -0,0 +1,37 @@ +-- This generic package provides for each Element_Type an interface that +-- used to implement iterators. +-- +-- Beyond the fact that it's super simple, the difference with standard +-- iterators is that iteration is destructive: once an element has been +-- yielded, it's not possible to re-yield it once more. +-- +-- The analogy with standard Ada containers is that there's no way to keep a +-- cursor to preserve an iteration state. + +with Ada.Unchecked_Deallocation; + +generic + type Element_Type is private; +package Langkit_Support.Iterators is + + type Iterator is interface; + -- Iterator interface: iterator consumers do not need to mind about + -- concrete interator implementations. + + procedure Next + (I : in out Iterator; + Has_Next : out Boolean; + Element : out Element_Type) is abstract; + -- Get the next iteration element. If there was no element to yield + -- anymore, set Has_Next to False. Otherwise, set it to True and set + -- Element. + + procedure Iterate + (I : in out Iterator'Class; + Proc : access procedure (Element : Element_Type)); + -- Consume completely the I iterator, calling Proc on all yielded elements + + procedure Destroy is new Ada.Unchecked_Deallocation + (Iterator'Class, Iterator_Access); + +end Langkit_Support.Iterators; diff --git a/langkit/support/langkit_support_installed.gpr b/langkit/support/langkit_support_installed.gpr index 1cc424ec0..87216095d 100644 --- a/langkit/support/langkit_support_installed.gpr +++ b/langkit/support/langkit_support_installed.gpr @@ -22,6 +22,7 @@ library project Langkit_Support is "Langkit_Support.Bump_Ptr", "Langkit_Support.Bump_Ptr.Vectors", "Langkit_Support.Diagnostics", + "Langkit_Support.Iterators", "Langkit_Support.Extensions", "Langkit_Support.Lexical_Env", "Langkit_Support.Packrat",