Struct swipl::context::Context

source ·
pub struct Context<'a, T: ContextType> {
    pub context: T,
    /* private fields */
}
Expand description

A context that the underlying prolog engine is in.

See the module documentation for an explanation of this type.

Fields§

§context: T

Implementations§

source§

impl<'a, C: OpenCall> Context<'a, C>

source

pub fn next_solution(&self) -> PrologResult<bool>

Retrieve the next solution.

If solution retrieval led to a failure or an error, this is returned in the Err part of the PrologResult. Otherwise, Ok(true) is returned if there are more solutions, and Ok(false) is returned when this is the last solution.

source

pub fn cut(self)

Cut the query, keeping all data it has created.

Any unifications the query did to terms from parent contexts will be retained.

source

pub fn discard(self)

Discard the query, discarding all data it has created.

Any unifications the query did to terms from parent contexts will be discarded.

source

pub fn once(self) -> PrologResult<()>

Retrieve one result, and then cut.

source

pub fn ignore(self) -> PrologResult<()>

Retrieve one result, ignoring failures, and then cut.

Exceptions will still be returned as such.

source§

impl<'a, T: ContextType> Context<'a, T>

source

pub fn assert_activated(&self)

Panics if this context is not active.

source

pub fn assert_no_exception(&self)

Panics if the engine is in an exceptional state.

source

pub fn engine_ptr(&self) -> PL_engine_t

Returns the underlying engine pointer.

source

pub unsafe fn wrap_term_ref(&self, term: term_t) -> Term<'_>

Wrap the given term_t into a Term with a lifetime corresponding to this context.

Safety

This is unsafe because there’s no way of checking that the given term_t is indeed from this context. The caller will have to ensure that the term lives at least as long as this context.

source

pub fn has_exception(&self) -> bool

Returns true if the underlying engine is in an exceptional state.

source

pub fn clear_exception(&self)

Clear the current exception if there is any.

source

pub fn with_uncleared_exception<'b, R>( &'b self, f: impl FnOnce(Option<ExceptionTerm<'b>>) -> R ) -> R

Call the given function with the exception term, if it exists.

The given function is able to clear the exception term, but not much else is allowed from safe code. Any attempt to do a get, put or unify with the given term will result in a panic.

source

pub fn with_exception<R>(&self, f: impl FnOnce(Option<&Term<'_>>) -> R) -> R

Call the given function with a copy of the exception term, from a context where the exception state has temporarily been cleared.

This allows analysis on the exception term using all the normal safe functions for doing so. When the function returns, the engine will go back into an exceptional state with the original exception term.

source

pub fn raise_exception<R>(&self, term: &Term<'_>) -> PrologResult<R>

Put the engine in an exceptional state.

The given term will be copied and put into the exception term. This function always returns Err(PrologError::Exception).

source

pub fn current_output<'b>(&self) -> WritablePrologStream<'b>

Retrieve the current output stream.

source

pub fn handle_signals(&self) -> PrologResult<u32>

Handle any outstanding synchronous signals, including user interrupts.

This could return PrologError::Exception, which should normally be propagated all the way back to SWI-Prolog. In particular, the raised exception will be a term containing the atom ‘$aborted’ for the case where a user interrupts.

This should be regularly called for long-running foreign code. SWI-Prolog handles signals synchronously at safe points, and therefore will never do so while a foreign predicate is running. The most visible outcome of this is that long-running predicates can normally not be interrupted by the user when they press ctrl-c once.

On success, the number of outstanding signals handled is returned.

source§

impl<'a> Context<'a, Frame>

source

pub fn close(self)

Close the frame.

After closing, any terms created in the context of this frame will no longer be usable. Any data created and put in terms that are still in scope will be retained.

source

pub fn discard(self)

Discard the frame.

This will destroy the frame. Any terms created in the context of this frame will no longer be usable. Furthermore, any term manipulation that happened since opening this frame will be undone. This is equivalent to a rewind followed by a close.

source

pub fn rewind(self) -> Context<'a, Frame>

Rewind the frame.

This will rewind the frame. Any terms created in the context of this frame will no longer be usable. Furthermore, any term manipulation that happened since opening this frame will be undone.

This returns a new context which is to be used for further manipulation of this frame.

source§

impl<'a, C: FrameableContextType> Context<'a, C>

source

pub fn open_frame(&self) -> Context<'_, Frame>

Open a new frame.

This returns a new context for the frame. The current context will become inactive, until the new context is dropped. This may happen implicitely, when it goes out of scope, or explicitely, by calling close() or discard() on it.

source§

impl<'a, T: QueryableContextType> Context<'a, T>

source

pub fn new_term_ref(&self) -> Term<'_>

Create a new Term reference in the current context.

The term ref takes on the lifetime of the Context reference, ensuring that it cannot outlive the context that created it.

source

pub fn new_term_refs<const N: usize>(&self) -> [Term<'_>; N]

create an array of term references.

The term refs all take on the lifetime of the Context reference, ensuring that it cannot outlive the context that created it.

source

pub fn new_term_refs_vec(&self, count: usize) -> Vec<Term<'_>>

create a vec of term references.

The term refs all take on the lifetime of the Context reference, ensuring that it cannot outlive the context that created it.

source

pub fn open<C: Callable<N>, const N: usize>( &self, callable: C, args: [&Term<'_>; N] ) -> Context<'_, C::ContextType>

Open a query.

Example:


   let query = context.open(pred!{format/2},
                            [&term!{context: "hello, ~q~n"}?,
                             &term!{context: ["world"]}?]);
   query.next_solution()?;
   query.cut();
source

pub fn call_once<C: Callable<N>, const N: usize>( &self, callable: C, args: [&Term<'_>; N] ) -> PrologResult<()>

Open a query, get a single result and cut.

Example:


   context.call_once(pred!{format/2},
                     [&term!{context: "hello, ~q~n"}?,
                     &term!{context: ["world"]}?])?;
source

pub fn open_with_module<C: Callable<N>, const N: usize>( &self, callable: C, module: Option<Module>, args: [&Term<'_>; N] ) -> Context<'_, C::ContextType>

Open a query, optionally passing in a context module.

source

pub fn term_from_string(&self, s: &str) -> PrologResult<Term<'_>>

Turn the given string into a prolog term.

This uses the prolog predicate read_term_from_atom/3 for the heavy lifting.

Consider using the term! macro instead.

source

pub fn string_from_term(&self, t: &Term<'_>) -> PrologResult<String>

Turn the given string into a prolog term.

This uses the prolog predicate read_term_from_atom/3 for the heavy lifting.

Consider using the term! macro instead.

source

pub fn open_call(&'a self, t: &Term<'a>) -> Context<'a, impl OpenCall>

Open a query for the given term using the call/1 prolog predicate.

source

pub fn call_term_once(&'a self, t: &Term<'a>) -> PrologResult<()>

source

pub fn try_or_die<R, E: IntoPrologException>( &self, r: Result<R, E> ) -> PrologResult<R>

Turn a result into a PrologResult.

For this to work, the Err component of the Result needs to implement the trait IntoPrologException. This is currently only the case for std::io::Error.

source

pub fn try_or_die_generic<R, E: Error>( &self, r: Result<R, E> ) -> PrologResult<R>

Turn a result into a PrologResult.

For this to work, the Err component of the Result needs to implement the trait Error.

source

pub fn term_list_iter<'b>( &'b self, list: &Term<'_> ) -> TermListIterator<'b, 'a, T>

Iterate over a term list.

this returns a TermListIterator made out of the given term. The TermListIterator will assume this is a cons cell, and unify head and tail on each step of the iterator, returning the head term and storing the tail term. If this unification fails, the iterator stops.

Note that the terms created by this iterator are not automatically thrown away. It is the caller’s responsibility to clean up terms if this is required, for example by using a frame.

source

pub fn term_list_array<const N: usize>(&self, list: &Term<'_>) -> [Term<'_>; N]

Retrieve a term list as a fixed-size array.

This is useful when a term contains a list whose supposed size is known at compile time. If the actual list is larger than this, only the first N elements are used. If the list is smaller, the remaining terms in the array remain variables.

source

pub fn term_list_vec(&self, list: &Term<'_>) -> Vec<Term<'_>>

Retrieve a term list as a Vec.

This will iterate over the given prolog list twice - once to figure out its size, and then another time to actually retrieve the elements. This is done so that we can allocate the terms in a way that leaves no unused terms behind on the stack (as would normally happen when iterating the list using term_list_iter).

If you know in advance what the size is going to be (or you know a reasonable upper bound), consider using term_list_array. If you just wish to iterate over the elements, or don’t care about garbage terms being created, consider using term_list_iter.

source

pub fn compound_terms<const N: usize>( &self, compound: &Term<'_> ) -> PrologResult<[Term<'_>; N]>

Retrieve compound terms as a fixed size array.

This will ensure that the given term is indeed a compound with arity N. If this is true, N terms will be allocated in this context, unified with the argument terms of the compound, and returned as an array. If not, this method will fail.

source

pub fn compound_terms_vec( &self, compound: &Term<'_> ) -> PrologResult<Vec<Term<'_>>>

Retrieve compound terms as a Vec.

This will ensure that the given term is indeed a compound of any arity. If this is true, arity terms will be allocated in this context, unified with the argument terms of the compound, and returned as a Vec. If not, this method will fail.

source

pub fn compound_terms_vec_sized( &self, compound: &Term<'_>, count: usize ) -> PrologResult<Vec<Term<'_>>>

Retrieve compound terms as a fixed size Vec.

This will ensure that the given term is indeed a compound with arity count. If this is true, count terms will be allocated in this context, unified with the argument terms of the compound, and returned as an array. If not, this method will fail.

source

pub fn deserialize_from_term<'de, DT: Deserialize<'de>>( &'de self, term: &'de Term<'de> ) -> Result<DT>

Deserialize a term into a rust value using serde.

source

pub fn serialize_to_term<ST: Serialize>( &self, term: &Term<'_>, obj: &ST ) -> Result<(), Error>

Serialize a value into a prolog term using serde.

This uses the default serialization configuration, meaning:

  • prolog dictionary tags will remain variables.
  • struct type names are ignored and will not be set as the dictionary tag.
source

pub fn serialize_to_term_with_config<ST: Serialize>( &self, term: &Term<'_>, obj: &ST, config: SerializerConfiguration ) -> Result<(), Error>

Serialize a value into a prolog term using serde, providing configuration options.

source

pub fn unify_list_functor<'b>( &'b self, term: &Term<'_> ) -> Result<(Term<'b>, Term<'b>), PrologError>

Unify the term with the list functor, returning a term for the head and the tail.

source

pub fn into_generic(&self) -> GenericQueryableContext<'_>

source§

impl<'a, T: QueryableContextType> Context<'a, T>

source

pub fn dict_entries<'b>(&'b self, term: &Term<'b>) -> DictIterator<'a, 'b, T>

Iterate over the entries in the dictionary referred to by this term.

This will return key-value pairs, where the key is either an atom or an integer, and the value is a term. The term will be created in the current context. A consequence of this is that the iterator will panic if this context is not active.

Created terms will not be automatically unallocated when the iterator moves on. It is the responsibility of the caller to clear them if desired using either a frame or by resetting.

If dict_entries is called on a term that does not contain a dictionary, the iterator is still created but will not return any elements.

Trait Implementations§

source§

impl<'a, T: ContextType> Drop for Context<'a, T>

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl<'a> From<EngineActivation<'a>> for Context<'a, ActivatedEngine<'a>>

source§

fn from(activation: EngineActivation<'a>) -> Context<'a, ActivatedEngine<'a>>

Converts to this type from the input type.

Auto Trait Implementations§

§

impl<'a, T> !RefUnwindSafe for Context<'a, T>

§

impl<'a, T> !Send for Context<'a, T>

§

impl<'a, T> !Sync for Context<'a, T>

§

impl<'a, T> Unpin for Context<'a, T>
where T: Unpin,

§

impl<'a, T> !UnwindSafe for Context<'a, T>

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.