fhdZddlZddlmZmZmZddlmZddlm Z GddZ Gdd e Z d Z Gd d e Z d ZGdde ZdZGddZGddZGdde ZdZej*fdZdZdZdZdZdZGddZGd d!eZGd"d#eZGd$d%eZ Gd&d'eZ!d(Z"d2d)Z#d3d*Z$d3d+Z%Gd,d-Z&Gd.d/Z'd0e(fd1Z)y)4z0 The Python wrapper for Hyperon Atom Rust types N)AtomKind SerialResult Serializer)Union)ConvertingSerializercJeZdZdZdZdZdZdZdZdZ dZ e d Z y ) AtomzRepresents an Atom of any typec||_y)zInitialize an AtomN)catomselfr s V/var/lib/jenkins/workspace/mettalog/venv/lib/python3.12/site-packages/hyperon/atoms.py__init__z Atom.__init__ s  cBtj|jy)z+Frees an Atom and all associated resources.N)hp atom_freer r s r__del__z Atom.__del__s TZZ rczt|txr*tj|j|jS)z>Checks if two atom objects represent the same conceptual Atom.) isinstancer ratom_eqr r others r__eq__z Atom.__eq__s,5$'4 4::u{{3 5rc@tj|jS)z6Renders a human-readable text description of the Atom.)r atom_to_strr rs r__repr__z Atom.__repr__s~~djj))rc@tj|jS)z5Gets the metatype (kind) of the current Atom instance)ratom_get_metatyper rs r get_metatypezAtom.get_metatypes##DJJ//rctj|j}g}|D]&}|jtj |(|S)zXPerforms a depth-first exhaustive iteration of an Atom and all its children recursively.)r atom_iterater appendr _from_catom)r resresultrs riteratez Atom.iterate"s?oodjj)A MM$**1- . rchttj|j|jS)zBMatches one Atom with another, establishing bindings between them.) BindingsSetratom_match_atomr )r bs r match_atomzAtom.match_atom*s"2--djj!''BCCrcJtj|}|tjk(r t |S|tj k(r t |S|tjk(r t|S|tjk(r t|Stdt|z)z'Constructs an Atom by wrapping a C AtomzUnexpected type of the Atom: ) rr rSYMBOL SymbolAtomVARIABLE VariableAtomEXPRExpressionAtomGROUNDED GroundedAtom Exceptionstr)r types rr%zAtom._from_catom.s##E* 8?? "e$ $ X&& && & X]] "!%( ( X&& && &;c$iGH HrN) __name__ __module__ __qualname____doc__rrrrr!r)r. staticmethodr%rrr r s?(!5 *0D I Irr c(eZdZdZfdZdZxZS)r1zA SymbolAtom represents a single concept, identified by name. If two symbols have the same name, they reference the same concept.c$t||y)zInitialize a SymbolAtomNsuperrr r __class__s rrzSymbolAtom.__init__A rc@tj|jSzReturns the name of the Atom.r atom_get_namer rs rget_namezSymbolAtom.get_nameE ++r)r;r<r=r>rrL __classcell__rFs@rr1r1=s< ,rr1c>ttj|S)z-A convenient method to construct a SymbolAtom)r1ratom_symnames rSrTIs bkk$' ((rc8eZdZdZfdZdZedZxZS)r3zA VariableAtom represents a variable in an expression. It serves as a placeholder that can be matched with, or bound to other Atoms.c$t||y)zInitialize a VariableAtomNrCrEs rrzVariableAtom.__init__QrGrc@tj|jSrIrJrs rrLzVariableAtom.get_nameUrMrc>ttj|S)zXConstruct new VariableAtom instance from VariableAtom.get_name() method results.)r3ratom_var_parse_namerRs r parse_namezVariableAtom.parse_nameYsB224899r) r;r<r=r>rrLr?rZrNrOs@rr3r3Ms'F ,::rr3c>ttj|S)z/A convenient method to construct a VariableAtom)r3ratom_varrRs rVr]_s  D) **rc(eZdZdZfdZdZxZS)r5zKAn ExpressionAtom combines different kinds of Atoms, including expressions.c$t||y)zInitialize an expression atomNrCrEs rrzExpressionAtom.__init__frGrctj|jDcgc]}tj |c}Scc}w)z+Returns all children Atoms of an expression)ratom_get_childrenr r r%r s r get_childrenzExpressionAtom.get_childrenjs0575I5I$**5UVE  'VVVsA)r;r<r=r>rrbrNrOs@rr5r5csU Wrr5cxttj|Dcgc]}|jc}Scc}w)z2A convenient method to construct an ExpressionAtom)r5r atom_exprr )argsatoms rErgos( ",,t'Dt 'DE FF'Ds7 ceZdZdZej ejjZej ejjZ ej ejjZ ej ejjZ ej ejjZ ej ejjZ ej ejjZej ejjZej ejj Zy)AtomTypezDefines all Atom typesN)r;r<r=r>r r%r CAtomType UNDEFINEDTYPEATOMr0r2 EXPRESSIONr6GROUNDED_SPACEUNITr@rrririss   !7!78I   BLL-- .D   BLL-- .D   bll11 2F 5 56H!!",,"9"9:J 5 56H%%bll&A&ABN   BLL-- .DrriceZdZej ej jZej ej jZej ej jZ y)AtomsN) r;r<r=r r%rCAtomsEMPTYrpMETTAr@rrrrrrsJ   RYY__ -E   BIINN +D   RYY__ -Errrc.eZdZdZfdZdZdZxZS)r7a A GroundedAtom represents sub-symbolic knowledge. At the API level, it allows keeping data and behaviour inside an Atom. There are three aspects of a GroundedAtom which can be customized: - the type of GroundedAtom is provided by the Atom itself; - the matching algorithm used by the Atom; - an Atom can be made executable, and used to apply sub-symbolic operations to other Atoms as arguments. c$t||y)zInitialize a GroundedAtomNrCrEs rrzGroundedAtom.__init__rGrctj|jrtj|jSt |S)zReturns the GroundedAtom object, or the Space wrapped inside a GroundedAtom, or convert supported Rust grounded objects into corresponding ValueObjects )ratom_is_cgroundedr atom_get_object_priv_gnd_get_objectrs r get_objectzGroundedAtom.get_objects6    +%%djj1 1'- -rcftjtj|jS)z/Retrieve the grounded type of the GroundedAtom.)r r%ratom_get_grounded_typer rs rget_grounded_typezGroundedAtom.get_grounded_types" 9 9$** EFFr)r;r<r=r>rr|rrNrOs@rr7r7s   .Grr7c|j}|tjk(r4ddlm}|j t j|jS|tdk(s|tdk(rYt}t j|j||jtd|t|jStd|)z Tries to convert grounded object into a one of the standard Python values. This implementation is used to automatically convert values from other runtimes to Python. )SpaceRefBoolNumberzCould not convert atom z'Cannot get_object of unsupported non-C )rrirobaser _from_cspaceratom_get_spacer rTratom_gnd_serializevalue RuntimeError ValueObject TypeError)rftypr converters rr{r{s  "C h%%%"$$R%6%6tzz%BCC & SAhK/(*  djj)4 ?? "!8?@ @y/ /A$HIIrczt|dsJdttj||jS)z/A convenient method to construct a GroundedAtomcopyz4Method copy should be implemented by grounded object)hasattrr7ratom_gndr )objectr:s rGrs2 66 "Z$ZZ "  FDJJ7 88rc6tj|tjk7rtj n*t jtj|d}|Dcgc]}t j|}}|j|d|iScc}w)zQ Private glue for Hyperonpy implementation. Executes grounded Atoms. res_typ) rr rr4rirkr r%raexecute)gndrrerr s r#_priv_call_execute_on_grounded_atomrs %'$8$8$=$Nh    b2237; < 15 6D  U # 6D 6 3;; .g .. 7s&BcJ|jtj|S)zO Private glue for Hyperonpy implementation. Matches grounded atoms )match_r r%)rr s r!_priv_call_match_on_grounded_atomrs ::d&&u- ..rc$|j|S)zR Private glue for Hyperonpy implementation. Serializes grounded atoms ) serialize)r serializers r%_priv_call_serialize_on_grounded_atomrs == $$rctj|tjk(rt |} ||j k(Sy#t $rYywxYw)zz Private glue for Hyperonpy implementation. Tests for equality between a grounded value atom and another atom F)rr rr6r7r|r)rr rfs r_priv_compare_value_atomrsW  E"h&7&77E" $//++ +  sA AAcVtj|j|jS)z!Check if two atoms are equivalent)ratoms_are_equivalentr )firstseconds rrrs " "5;; ==rc$eZdZdZddZdZdZy)GroundedObjectzCA GroundedObject holds some content and, optionally, an identifier.Nc ||_||_y)zGInitializes a new GroundedObject with the given content and identifier.N)contentid)r rrs rrzGroundedObject.__init__s rct|jtrd|jdS|jt |jS|jS)z]Returns the object's ID if present, or a string representation of its content if not.")rrr9rreprrs rrzGroundedObject.__repr__sG dllC (t||nA& &&*WW_tDLL!A$''Arc|S)z Returns a copy of this GroundedObject instance. Note: Currently, this method returns the original instance. r@rs rrzGroundedObject.copys  rN)r;r<r=r>rrrr@rrrrsM Brrc,eZdZdZedZdZdZy)raf A ValueObject is a specialized form of GroundedObject, which treats its content as a value. It allows for equality comparison between the content of two ValueObjects. Example: obj1 = ValueObject(5) obj2 = ValueObject(5) obj3 = ValueObject(6) print(obj1 == obj2) # True print(obj1 == obj3) # False c|jS)z3Gets the value of the object, which is its content.rrs rrzValueObject.value||rcXt|txr|j|jk(S)zNCompares the equality of this ValueObject with another based on their content.)rrrrs rrzValueObject.__eq__s# %-O$,,%--2OOrc`t|jtr|j|jSt|jtr|j |jSt|jt r|j|jStjS)z Serialize standard Python values. This implementation is used to pass Python values into the foreign runtime. ) rrboolserialize_boolint serialize_intfloatserialize_floatr NOT_SUPPORTED)r rs rrzValueObject.serialize#sy dllD ),,T\\: :  c *++DLL9 9  e ,--dll; ;-- -rN)r;r<r=r>propertyrrrr@rrrrs& P .rrceZdZdZy) NoReduceErrorzHCustom exception; raised when a reduction operation cannot be performed.N)r;r<r=r>r@rrrr1sRrrcjeZdZdZdfd ZedZedZejddZ dZ xZ S) OperationObjecta An OperationObject represents an operation as a grounded object, allowing for more advanced logic like lazy evaluation, type-checking, and more. Inherits: GroundedObject: The parent class that provides the basic wrapper around content. Attributes: unwrap (bool): Determines whether to unwrap the content of GroundedAtoms when passed as arguments to the operation. Properties: op: Returns the operation function. name: Returns the identifier name for this operation object. Methods: __init__(name, op, unwrap): Initializes an OperationObject instance. execute(*args, res_typ): Executes the operation with the provided arguments. __eq__(other): Compares the equality of this OperationObject instance with another. Example: def add(a, b): return a + b op_obj = OperationObject("addition", add) result = op_obj.execute(3, 4) c4t|||||_y)a Initializes a new OperationObject with a name identifier, operation function, and an optional unwrap flag. Parameters: name (str): The identifier for this operation. op (function): The function representing the operation. unwrap (bool, optional): Whether to unwrap GroundedAtom content when applying the operation. Defaults to True. N)rDrunwrap)r rSoprrFs rrzOperationObject.__init__Rs T" rc|jS)zReturns the operation function.rrs rrzOperationObject.op`rrc|jS)z6Returns the identifier name for this operation object.)rrs rrSzOperationObject.namees wwr)rc<|jr#g}i}|D]}t|tr|j}t |dkDrkt |ddk(rZ|ddD]Q} |j}t |dk(sJ |djj|t|d<S |j|jj|j|i|} | tjgSt| rt!t | | dgSt#| |gS|j|} t| t$st d |j&zd z| S#t dxYw#txYw#txYw) a Executes the operation with the provided arguments. Parameters: *args: Arguments to pass to the operation function. res_typ (AtomType, optional): The expected result type. Defaults to AtomType.UNDEFINED. Returns: The result of the operation. Raises: NoReduceError: Raised when `unwrap=True` and a non-GroundedAtom argument is provided. RuntimeError: Raised when the result of the operation is not a list. Note: Depending on the `unwrap` attribute, this method will either unwrap GroundedAtoms before passing them to the operation or pass them as is. rKwargsrNzIncorrect kwarg format T)rzGrounded operation `z` should return list)rrr5rblenrrr|rget_string_valuerr$rrrrpcallable OperationAtom ValueAtomlistrS) r ratomsrekwargsachckwargr's rrzOperationObject.executejs( ;;DFa0)B2w{tBqE{h'>!#ABAV()(8'*5zQ 66EJ1XEXEXEZEbEb'7a'A B"(!*KK  6 67!0TWWd-f-F~ |#%d6lF4HIIfg./ /TWWe_Ffd+"#9DII#EH^#^__M5V&25LUG3T&U U6&3o 5* (/)s$ E-,F1)F-E= F  FcXt|txr|j|jk(S)a* Compares the equality of this OperationObject with another based on their names. Parameters: other (OperationObject): Another OperationObject instance to compare. Returns: True if both OperationObjects have the same name; False otherwise. )rrrSrs rrzOperationObject.__eq__s#%1Mdii5::6MMr)T) r;r<r=r>rrrrSrirkrrrNrOs@rrr5sL8 '/&8&89v NrrceZdZdZdZy)MatchableObjecta Represents an object that can be involved in a matching operation with an Atom. This class is meant to be subclassed by objects that define specific matching behavior with an Atom. It provides a stub method for the matching operation that raises a RuntimeError when called, which must be overridden by subclasses. Inherits: ValueObject: The parent class that provides basic value-based equality and representation. Methods: match_(atom): A stub method for matching the object with an Atom. Example: class MyMatchableObject(MatchableObject): def match_(self, atom): # Implement the matching logic here pass my_obj = MyMatchableObject("some_value") my_obj.match_(some_atom) # Should not raise RuntimeError Raises: RuntimeError: Raised when the match_ method is called without being overridden by a subclass. ctd)a A stub method for matching the object with an Atom. This method is intended to be overridden by subclasses to provide specific matching behavior with an Atom. Parameters: atom (Atom): An Atom object to match against. Raises: RuntimeError: Raised when this method is called without being overridden in a subclass. z,MatchableObject::match_() is not implemented)r)r rfs rrzMatchableObject.match_sIJJrN)r;r<r=r>rr@rrrrs 4 Krrc |tjSt|tr,t t dg|Dcgc] }t |c}St|tr!|ddk(rt|ddSt |S|Scc}w)a Transforms a variety of type representations into a unified Atom-based format. This utility function is intended for internal use to handle different ways in which type information can be provided. It converts `type_names` into a form that can be readily used for type checking or other internal operations. Parameters: type_names (Union[None, list, str, AtomType]): The type information to be converted. - If None, will return AtomType.UNDEFINED. - If list, will recursively transform each element. - If str, will return a Variable Atom (`V`) if the string starts with '$'; otherwise, returns a Symbol Atom (`S`). - If already an AtomType, returns it as is. Returns: AtomType: The transformed type information in AtomType format. Examples: _type_sugar(None) => AtomType.UNDEFINED _type_sugar(["int", "str"]) => E(S("->"), S("int"), S("str")) _type_sugar("$var") => V("var") _type_sugar("int") => S("int") _type_sugar(AtomType.SOME_TYPE) => AtomType.SOME_TYPE Nz->r$r) rirkrrrgrT _type_sugarr9r]) type_namesns rrrs~2!!!*d#4@J?qKN?@@*c"$.qMS$8qAB Ka mK @sB cBtt|||t|S)z An OperationAtom wraps an operation with optional type information into a GroundedAtom and associates a name with it. Useful for registering custom operations that can be executed in an Atom-based computational environment. )rrr)rSrrrs rrrs _T2v . J0G HHrc@tt||t|S)z_Creates a GroundedAtom that wraps a given value, optionally specifying its type and identifier.)rrrr type_nameatom_ids rrrs [ (+i*@ AArc@tt||t|S)zn Creates a Grounded Atom that wraps a matchable value, optionally specifying its type and identifier. )rrrrs r MatchableAtomrs _UG ,k).D EErceZdZdZddeej dffdZdZdZ dZ ifdZ d Z d Z d Zdd Zdeded efdZd efdZdZded eedffdZdZy)BindingszFInterface for working with atom matching and variable-to-atom binding.NbindingscJ|tj|_y||_y)z2Initializes with or without pre-existing bindings.N)r bindings_new cbindingsr rs rrzBindings.__init__s  __.DN%DNrc\|j tj|jyy)zFrees the binding resources.Nrr bindings_freers rrzBindings.__del__s# >> %   T^^ , &rczt|txr*tj|j|jS)z>Checks if two bindings objects contain identical associations.)rrr bindings_eqrrs rrzBindings.__eq__s.5(+@t~~u? Arc@tj|jS)z*Renders a text description of the bindings)rbindings_to_strrrs rrzBindings.__repr__#s!!$..11rc"|jS)z$Makes a "deep copy" of the bindings.cloner memodicts r __deepcopy__zBindings.__deepcopy__'zz|rc|SzFor context management.r@rs r __enter__zBindings.__enter__+ rcj|j'tj|jd|_yyzFrees resources on exit.Nrr exc_typeexc_valexc_tbs r__exit__zBindings.__exit__/s* >> %   T^^ ,!DN &rcRttj|jS)z#Makes a "deep copy" of the bindings)rrbindings_clonerrs rrzBindings.clone5s))$..9::rreturnchttj|j|jS)z;Merges with another Bindings instance, into a Bindings Set.)r+rbindings_mergerrs rmergezBindings.merge9s"2,,T^^U__MNNrvarrfcltj|j|j|jS)z.Adds a binding between a variable and an Atom.)rbindings_add_var_bindingrr )r rrfs radd_var_bindingzBindings.add_var_binding=s#**4>>399djjQQrc@tj|jS)z.Checks if a bindings contains no associations.)rbindings_is_emptyrrs ris_emptyzBindings.is_emptyAs##DNN33rctjx}t_|D]"}tj||j$tj |j |tj|y)z*Keeps only specific variable associations.N)r atom_vec_newCVecAtom atom_vec_pushr bindings_narrow_varsr atom_vec_free)r varscvarsrs r narrow_varszBindings.narrow_varsEsU oo// C   UCII . 6 rctj|j|j}|dStj |S)z#Finds the atom for a given variableN)rbindings_resolverr r r%)r rraw_atoms rresolvezBindings.resolveMs7&&t~~syyA'tGT-=-=h-GGrctj|j}|Dcgc]2}tj |dtj |df4}}t |Scc}w)z@Returns an iterator over the variable-atom pairs in the bindingsrr)r bindings_listrr r%iterr r&r(r's riteratorzBindings.iteratorRs\t~~.LOPq4##AaD)4+;+;AaD+ABPPF|Qs7A(r)rrr r+)r;r<r=r>rr CBindingsrrrrrrrrr r3r rrrrr!r&r@rrrrsP&r||T'9!:&- A 2%'" ;OR<RtRR4$4 H<HE$*,=H rrceZdZdZddeej edffdZdZ dZ dZ ifdZ d Z d Zd Zd Zd ZdefdZdefdZdefdZdededefdZdededefdZdedeffdZdZy)r+zsRepresents a set of Bindings frames, potentially expressing all possible matches produced by a match operation.Ninputcd|_|tj|_yt |t r%tj |j|_y||_y)z Initializes with optional input.N) shadow_listrbindings_set_singlec_setrrbindings_set_from_bindingsr)r r)s rrzBindingsSet.__init__\sF =//1DJ x (66uGDJDJrcj|j'tj|jd|_yy)zFrees the BindingsSetNr-rbindings_set_freers rrzBindingsSet.__del__f* :: !   ,DJ "rczt|txr*tj|j|jS)zrr CBindingsSetrrrrrrrrrArDrrrrKrNr3r rrSrWr&r@rrr+r+Xs.eBOOXt$CD = 2%' %4 >4$4 545 =X =S<SSSN$N4NDN BmX&= >Brr+r ct|ts t|}t|dkDrd|dk(r d|dk(r|ddS|S)Nrrrrr)rr9rr)rs rrrsG eS !U  5zA~458+$%)2CQr{ Lr)NT)NN)*r> hyperonpyrrrrtypingrhyperon.conversionrr r1rTr3r]r5rgrirrr7r{rkrrrrrrrrr8rrrrrrrrr+r9rr@rrr_s18831I1If , ,):4:$+ WT WG / /.. G4G@J.%%9 //% >6'..'.R I zNnzNx(Kk(KTBIBFGGRll\sr