
    4Ysh\                     V   d Z ddlZddlZddlZddlmZ ddlmZmZmZm	Z	 ddl
mZmZ ddlmZmZ ddlmZmZmZ ddlmZmZmZmZmZ dd	lmZ dd
lmZ d Zd Z d Z!d Z"d Z#d Z$dDdZ%d Z&d Z'd Z(d Z)d Z*dDdZ+d Z,d Z-d Z.d Z/d Z0d Z1d Z2d Z3d  Z4d! Z5d" Z6 G d# d$e7      Z8d% d% fd&Z9d' fd(Z:d) d) dfd*Z;d+ Z<d, Z=d- Z>d. Z?dDd/Z@d0 ZAd1 ZBd2 ZCd3 ZDd4 Zd5 ZEdEd6ZFd7 ZGd8 ZHdEd9ZIdEd:ZJ G d; d<e7      ZKd=efd>ZLd? ZMeNd@k(  rddlOZOddAlPmQZQ ddlRZSeSj                  j                  eOj                  dB         r$ eWeOj                  dB         j                         ZYneOj                  dB   ZY eQj                  eY      Z[ e\e[        e\dC        eJe[      Z] eMe]       yy)Fz
Converting the 'parse-tree' output of pyparsing to a SPARQL Algebra expression

http://www.w3.org/TR/sparql11-query/#sparqlQuery

    N)reduce)LiteralVariableURIRefBNode)PrologueQuery)	CompValueExpr)and_
TrueFiltersimplify)InvPathAlternativePathSequencePathMulPathNegatedPath)ParseResults)
Identifierc                     t        d| |      S )NOrderBypexprr
   r   s     }/var/www/sten-cake5-migrate2.hellocrow.space/lexinfo-master/env/lib/python3.12/site-packages/rdflib/plugins/sparql/algebra.pyr   r   !   s    Y!$//    c                     t        d|       S )N
ToMultiSetr   r   r    s    r   r   r   %   s    \Q''r   c                     t        d| |      S )NUnionp1p2r   r#   s     r   r"   r"   )       W++r   c                     t        d| |      S )NJoinr#   r   r#   s     r   r(   r(   -   s    Vr**r   c                     t        d| |      S )NMinusr#   r   r#   s     r   r*   r*   1   r&   r   c                     t        d| |      S )NGraph)termr   r   )r-   graphs     r   r,   r,   5   s    W4511r   c                 $    t        d| xs g       S )NBGPtriplesr   r1   s    r   r0   r0   9   s    UGMr22r   c                      t        d| ||      S )NLeftJoinr$   r%   r   r   r5   s      r   r4   r4   =   s    ZB2D99r   c                     t        d| |      S )NFilterr   r   r   r8   s     r   r7   r7   A   s    XDA..r   c                      t        d| ||      S )NExtendr   r   varr   r;   s      r   r:   r:   E   s    X377r   c                     t        d|       S )Nvaluesresr   r?   s    r   ValuesrA   I   s    X3''r   c                     t        d| |      S )NProjectr   PVr   rD   s     r   rC   rC   M   s    Y!++r   c                     t        d| |      S )NGroupr   r   r   s     r   rG   rG   Q   s    W--r   c           
          t        | D cg c]  }||vrt        |t        t        f      r|  c}      t	        fd| D               t        | d   t
               fS c c}w )Nc              3   B   K   | ]  }j                  |d         yw)r   N)get).0x	varscounts     r   	<genexpr>z_knownTerms.<locals>.<genexpr>^   s     1QY]]1a 1s      )len
isinstancer   r   sumr   )triple	varsknownrM   rL   s     ` r   _knownTermsrU   U   sl      I%*Q58I*J 	
 
1&1	11vay'**
 
s   #Ac                 v   d }| D cg c]  }d|f } }t               t        j                  t              | D ]0  }|d   D ]&  }t	        |t
        t        f      s|xx   dz  cc<   ( 2 d}|t        |       k  rt        fd| |d D              | |d | |   d   d   }d}||z   t        |       k  rR| ||z      d   d   |k(  rA| ||z      d   D ]  } ||        |dz  }||z   t        |       k  r| ||z      d   d   |k(  rA|dz  }|t        |       k  r| D cg c]  }|d   	 c}S c c}w c c}w )zZ
    Reorder triple patterns so that we execute the
    ones with most bindings first
    c                 T    t        | t        t        f      r|j                  |        y y N)rQ   r   r   add)r-   rT   s     r   _addvarzreorderTriples.<locals>._addvari   s"    dXu-.MM$ /r   N   r   c              3   H   K   | ]  }t        |d          |d    f  yw)r[   N)rU   )rK   rL   rM   rT   s     r   rN   z!reorderTriples.<locals>.<genexpr>~   s'     XAQqT9i@!A$GXs   ")	setcollectionsdefaultdictintrQ   r   r   rP   sorted)	l_rZ   rL   tcijrM   rT   s	          @@r   reorderTriplesrg   c   sv      	 4)	 B	 I'',I "1 	"A!h./!!	"" 	
A c"g+XQSTUTVQWXX12qE!HQK!ec"go"QU)A,q/Q"6AYq\ &9%&FA !ec"go"QU)A,q/Q"6 	
Q c"g+ QAaD5 
!4 s   D1"D6c           	           t        d         t               dz  dk7  rt        d      t         fdt	        dt               d      D              S )Nc                     | |z   S rX    )rL   ys     r   <lambda>ztriples.<locals>.<lambda>   s
    AE r      r   zthese aint triplesc              3   F   K   | ]  }|   |d z      |dz      f  yw)r[   rO   Nrj   )rK   rL   ls     r   rN   ztriples.<locals>.<genexpr>   s,     R1Q41q51QU84Rs   !)r   rP   	Exceptionrg   range)ro   s   `r   r2   r2      sJ    !1%AA
q,--ReAs1vq>QRRRr   c                 <   t        | t              rk| j                  dk(  r|j                  |       S | j                  dk(  r;t	        | j
                  | j                  |j                  | j                              S yt        | t              r|j                  |       S y)z'
    Expand prefixed/relative URIs
    pnameliteral)langdatatypeN)	rQ   r
   name
absolutizer   stringru   rv   r   )r   prologues     r   translatePNamer{      s     !Y66W&&q))66Yqvv0C0CAJJ0O   
Av	""1%% 
r   c                 :   t        | t              r
| j                  dk(  r9t        | j                        dk(  r| j                  d   S t        | j                   S | j                  dk(  r9t        | j                        dk(  r| j                  d   S t        | j                   S | j                  dk(  r| j                  s| j                  S t        | j                  t              rFt        | j                        dk7  rt        d      t        | j                  d   | j                        S t        | j                  | j                        S | j                  dk(  rjt        | j                  t              r;t        | j                        dk7  rt        d      t        | j                  d         S t        | j                        S | j                  dk(  rJt        | j                  t              rt        t        | j                         S t        | j                        S y	y	)
z,
    Translate PropertyPath expressions
    PathAlternativer[   r   PathSequencePathEltzDenkfehler!PathEltOrInversePathNegatedPropertySetN)rQ   r
   rw   rP   partr   r   modlistrp   r   r   r   r    s    r   translatePathr      s   
 !Y66&&166{avvay &//VV~%166{avvay #QVV,,VVy 55vvaffd+166{a''66"166!9aee44"16615511VV))!&&$'qvv;!##M22qvvay))qvv&VV//!&&$'"?AFF#;<<"166**	 0C  r   c                 &    d }t        | |      } | S )z
    Translate the graph pattern used by EXISTS and NOT EXISTS
    http://www.w3.org/TR/sparql11-query/#sparqlCollectFilters
    c                     t        | t              rU| j                  dv rFt        | j                        | _        | j                  j                  dk(  rd| j                  _        y y y y )N)Builtin_EXISTSBuiltin_NOTEXISTSr7   T)rQ   r
   rw   translateGroupGraphPatternr.   no_isolated_scopens    r   _cztranslateExists.<locals>._c   sU    a#vv@@4QWW=77<<8+04AGG- , A $r   	visitPost)traverse)er   s     r   translateExistsr      s    5 	b!AHr   c                     g }d}|t        |       k  r^| |   }|j                  dk(  r6|j                  t        |j                               | j                  |       n|dz  }|t        |       k  r^|rt        | S y)z

    FILTER expressions apply to the whole group graph pattern in which
    they appear.

    http://www.w3.org/TR/sparql11-query/#sparqlCollectFilters
    r   r7   r[   N)rP   rw   appendr   r   popr   )partsfiltersre   r   s       r   collectAndRemoveFiltersr      sv     G	A
c%j.!H66XNN?16623IIaLFA c%j. W~r   c                 d    d }| j                   D ]  }t        |      }|s|}t        ||      }  |S rX   )r.   r   r"   )graphPatternAgs      r   !translateGroupOrUnionGraphPatternr      s@    A &q)AaA Hr   c                 T    t        | j                  t        | j                              S rX   )r,   r-   r   r.   r   s    r   translateGraphGraphPatternr     s!    ""$>|?Q?Q$RSSr   c                 *    t        t        |             S rX   )r   translateValuesr   s    r   translateInlineDatar     s    ol344r   c                     | j                   dk(  rt        t        |       d         S | j                  sg | _        t	        | j                        }g }| j                  D ]s  }|j                   dk(  rQ|r|d   j                   dk(  s|j                  t                      |d   dxx   t        |j                        z  cc<   c|j                  |       u t               }|D ]  }|j                   dk(  rXt        |j                        }|j                   dk(  r"t        ||j                  |j                        }Yt        ||t              }k|j                   d	k(  r!t        |t        |j                        
      }|j                   dk(  rt        |t!        |      
      }|j                   dk(  rt        |t#        |      
      }|j                   dk(  rt        |t%        |      
      }|j                   dk(  rt        ||
      },|j                   dv rt        ||
      }I|j                   dk(  r#t'        ||j                  |j(                        }{t+        dt-        |      d|j                          |rt/        ||      }|S )zB
    http://www.w3.org/TR/sparql11-query/#convertGraphPattern
    	SubSelectr   TriplesBlockr0   r2   OptionalGraphPatternr7   MinusGraphPatternr#   GroupOrUnionGraphPatternGraphGraphPattern
InlineDataServiceGraphPattern)r0   r:   Bindz#Unknown part in GroupGraphPattern: z - r8   )rw   r   	translater   r   r   r0   r2   r   r.   r4   r   r   r   r*   r(   r   r   r   r:   r<   rp   typer7   )r   r   r   r   Gr   s         r   r   r     s    
 K')L1!455%l&7&78G
A 66^#!B%**-bE)		 22HHQK 	A 66++*1773Avv!QQVV,Q:.VV**9!''BCAVV11?BCAVV**8;<AVV|#1!45AVV,,a AVV((a AVVvq!&&!%%(A @DQP /6 1%Hr   c                       e Zd Zd Zy)StopTraversalc                     || _         y rX   )rv)selfr   s     r   __init__zStopTraversal.__init__I  s	    r   N)__name__
__module____qualname__r   rj   r   r   r   r   H  s    r   r   c                      y rX   rj   r   s    r   rl   rl   M      r   c           
          ||       }||S | yt        | t        t        f      r| D cg c]  }t        |||       c}S t        | t              r$t	        | D cg c]  }t        |||       c}      S t        | t
              r(| j                         D ]  \  }}t        |||      | |<     ||       }||S | S c c}w c c}w )m
    Traverse a parse-tree, visit each node

    if visit functions return a value, replace current node
    N)rQ   r   r   	_traversetupler
   items)r   visitPrer   _erL   kvals          r   r   r   M  s     
!B	~	y!dL)*;<=a	!Xy1==	Au	CAi8Y7CDD	Ay	!ggi 	7FAsS(I6AaD	7 
1B	~	H >Cs   B;C c                      y rX   rj   )r   vs     r   rl   rl   j  r   r   c                    g }t        | t        t        t        f      r| D cg c]  }t	        ||       }}nFt        | t
              r6| j                         D ]#  \  }}|	|j                  t	        ||             %  || |      S c c}w )r   )rQ   r   r   r   _traverseAggr
   r   r   )r   visitorr@   rL   r   r   s         r   r   r   j  s     C!dL%01123A|Aw'33	Ay	!ggi 	7FAs

<W56	7 1c? 4s   Bc                      y rX   rj   r   s    r   rl   rl   ~  r   r   c                 n    	 t        | ||      }||S |S # t        $ r}|j                  cY d}~S d}~ww xY w)z
    Traverse tree, visit each node with visit function
    visit function may raise StopTraversal to stop traversal
    if complete!=None, it is returned on complete traversal,
    otherwise the transformed tree is returned
    N)r   r   r   )treer   r   completersts         r   r   r   ~  s>    dHi0O uus     	4/44c                 r    t        | t              r'| j                  j                  d      rt	        d      yy)zL
    Traverse parse(sub)Tree
    return true if any aggregates are used
    
Aggregate_TN)rQ   r
   rw   
startswithr   )rL   s    r   _hasAggregater     s5     !Y66\*%% +  r   c                     t        | t              rK| j                  j                  d      r/|j	                  |        t        dt        |      z        }|| d<   |S yy)zR
    Collect Aggregates in A
    replaces aggregates with variable references
    r   
__agg_%d__r@   N)rQ   r
   rw   r   r   r   rP   )r   r   aggvars      r   _aggsr     sT     !YAFF$5$5l$C	,Q/0%	 %Dr   c                 >   t        | t              r|j                  |        t        | t              rl| j                  dk(  r|j                  | j
                         | S | j                  dk(  r0| j                  r"|j                  d | j                  D               | S yy)z&
    Find all variables in a tree
    r   r   c              3   P   K   | ]  }|j                   xs |j                     y wrX   r<   evarrK   r   s     r   rN   z_findVars.<locals>.<genexpr>  s     Aq155?AFF?A   $&N)rQ   r   rY   r
   rw   r<   
projectionupdate)rL   r@   s     r   	_findVarsr     s{     !X
!Y66VGGAEENHVV{"||

AALLAAH #	  r   c           	         t        | t              rt        | g      S t        | t              r| j                  dk(  rt               | d<   | d   S | j                  dk(  rNt        t        j                  t        ||       D cg c]  \  }}|dk7  s| c}}t                     | d<   | d   S t        t        t        j                  |t                           | d<   | j                  dk(  r6| j                  rt        d | j                  D              }|S t               }|S | d   S t        t        j                  |t                     S c c}}w )zE
    find which variables may be bound by this part of the query
    RelationalExpression_varsr:   r   r   c              3   P   K   | ]  }|j                   xs |j                     y wrX   r   r   s     r   rN   z_addVars.<locals>.<genexpr>  s     BAEEOQVVOBr   )
rQ   r   r]   r
   rw   r   operatoror_zipr   )rL   childrenchildr   ss        r   _addVarsr     s    !XA3x	Ay	!66++AgJ( z' VVx*-h*:M;5$dfnMAgJ" z VHLL(CEBCAgJvv$<<BQ\\BBA  Az(,,#%00# Ns    EEc                     t        | t              r| j                  j                  d      r| S t        | t              r|| k7  rt        d|       S yy)zO
    For each unaggregated variable V in expr
    Replace V with Sample(V)
    r   Aggregate_SamplevarsN)rQ   r
   rw   r   r   )r   r   s     r   _sampler     sJ    
 !YAFF$5$5l$C!X16+!44 $*r   c                 :    t        | t              rt        |       S y rX   )rQ   r   simplifyFilters)r   s    r   _simplifyFiltersr     s    !Tq!! r   c                    g }g }| j                   r| j                   D ]  }|j                  st        |j                  t	        j
                  t        |j                              |_        t        |j                  t	        j
                  t        |            |_         t        | j                  t        d      rNt        | j                  t              | _        t        | j                  t	        j
                  t        |             t        | j                  t        d      rNt        | j                  t              | _
        t        | j                  t	        j
                  t        |             | j                   r|| j                   D ]m  }|j                  st        dt        |      dz   z        }|j                  t        d|j                  |             |j                  ||j                  f       o t        d	||
      |fS )N)r   )r   Fr   r   r[   r   )r   r@   AggregateJoin)r   r   )r   r   r   r   	functoolspartialr   r   havingr   orderbyr<   r   rP   r   r
   )qMEr   r   r   s         r   translateAggregatesr     so   
A
A 	|| 	IAvv!!&&)*;*;Gqvv*NO!!&&)*;*;EQ*GH	I -%8AHHg.9,,Ua89 		=59QYY0	I--eq9: 	|| 	&Auulc!fqj9:#5AEErJK"aee%		& _Q/22r   c           	         g }| j                   s|S | j                  s|S t        | j                  d   t              s<| j                  D ]"  }|j	                  | j                   d   |i       $ t        |      S | j                  D ]0  }|j	                  t        t        | j                   |                   2 t        |      S )Nr   )r<   valuerQ   r   r   dictr   rA   )r   r@   r   valss       r   r   r     s     C55
77
aggaj$'77 	(CJJa#'	( #; GG 	/DJJtCt,-.	/ #;r   c                 D   t        | t               t        | j                  t              | _        t               }t        | j                  t        j                  t        |             t        | j                        }d}| j                  rg }| j                  j                  D ]_  }t        |t              r<|j                  dk(  r-t        ||j                   |j"                        }|j"                  }|j%                  |       a t'        ||      }d}nft        | j(                  t*        d      s<t        | j,                  t*        d      s t/        d | j0                  xs g D              rt'        |	      }d}|rt3        | |      \  }}ng }| j(                  r't5        t7        | j(                  j                   |
      }| j8                  r)t;        |t=        t?        | j8                                    }| j0                  stA        |      }ntA               }| j0                  D ]  }|j"                  r!||vs|j%                  |j"                         0|jB                  rG||vr|j%                  |jB                         |j%                  |j                   |jB                  f       tE        d       |D ]  \  }	}t        ||	|      } | j,                  rNtG        || j,                  j                  D cg c]$  }t        d|j                   |jH                        & c}      }tK        ||      }| jL                  r9| jL                  dk(  rt        d|	      }n| jL                  dk(  rt        d|	      }| jN                  rd}
| jN                  jP                  $| jN                  jP                  jS                         }
| jN                  jT                  5t        d||
| jN                  jT                  jS                               }||fS t        d||
      }||fS c c}w )z=
    http://www.w3.org/TR/sparql11-query/#convertSolMod

    r   r?   FGroupAsr   Tr   c              3   l   K   | ],  }|j                   rt        |j                  t        d        . yw)Fr   N)r   r   r   r   )rK   rL   s     r   rN   ztranslate.<locals>.<genexpr>?  s/      
vv QVV]U;;
s   24r    r8   r#   zI expected a var or evar here!OrderCondition)r   orderDISTINCTDistinctREDUCEDReducedr   Slice)r   startlength)r   r  )+r   r   r   wherer   r]   r   r   r   r   groupby	conditionrQ   r
   rw   r:   r   r<   r   rG   r   r   r   anyr   r   r7   r   valuesClauser(   r   r   r   r   rp   r   r	  rC   modifierlimitoffsetoffsettoPythonlimit)r   VSr   	aggregate
conditionsrd   r   rE   r   r   r  s              r   r   r     sQ    a!"qww-8AG 
BQWWi''	r:; 	#177+AIyy
$$ 	!A!Y'AFFi,?1affaee,EEa 		! AJ'	=59AII}u= 
\\'R
 
 AJ	"1a(1 	xxahh001Q7 	~~A*_Q^^%DEF<<"XV 
	BAuuB;IIaee$B;IIaff%!&&!&&)* @AA
	B  11aO 	yy ,, *qwwG
 	2Azz::#**AZZ9$)q)A}}==+]]))224F==*1F1==3F3F3O3O3QA b5L 'Qf5Ab5L7s   7)P
c                    t        | t              r| j                  dk(  r| j                  j                  dk(  r.t	        | j                  j
                        dk(  r| j                  S | j                  j                  dk(  r/t	        | j                  j
                        dk(  r| j                  S yy| j                  dk(  rt        | j
                        | d<   | S yy)zRemove joins to empty BGPsr(   r0   r   r2   N)rQ   r
   rw   r$   rP   r2   r%   rg   r   s    r   r   r     s    !Y66VttyyE!c!$$,,&71&<ttttyyE!c!$$,,&71&<tt '=!VVu_)!))4AiLH   r   c                     t        | t              r8| j                  dk(  rt        |      | d<   y| j                  dv ryt        |      S y)z
    Some things can be lazily joined.
    This propegates whether they can up the tree
    and sets lazy flags for all joins
    r(   lazyF)r  r  T)rQ   r
   rw   all)r   r   s     r   analyser"    sG     !Y66VHAfIVV,,x= r   c                 p   |t               }d|_        |r||_        |r*|j                         D ]  \  }}|j                  ||        | D ]h  }|j                  dk(  r|j
                  |_        $|j                  dk(  s4|j                  |j                  |j                  |j
                               j |S )N Base
PrefixDecl)r   baser   bindrw   iriprefixrx   )r   r'  initNsrz   r   r   rL   s          r   translateProloguer,    s    :LLN 	 DAqMM!Q	   @66VEEHMVV|#MM!((H$7$7$>?	@ Or   c                 ,   | j                   rt        | j                         }ng }t        j                  t              }| j                  rH| j                  D ]9  }|j                   s||j
                  xx   t        |j                         z  cc<   ; ||fS rX   )r2   r^   r_   r   quadsNotTriplesr-   )quads
alltriplesallquadsr   s       r   translateQuadsr2    s{    }}U]]+

&&t,H&& 	7Ayy GAII$66 	7 xr   c                 ^   | j                   dv rn| j                   dv rn| j                   dv r1t        | j                        \  }}|| d<   || d<   | j                   dv rn| j                   dk(  r| j                  r<t        | j                  j                        \  | j                  d<   | j                  d<   | j                  r<t        | j                  j                        \  | j                  d<   | j                  d<   t        | j                        | d<   nt        d	| z        || _        | S )
N)LoadClearDropCreate)AddMoveCopy)
InsertData
DeleteDataDeleteWherer/  r2   )r=  r<  Modifyr  z$Unknown type of update operation: %s)	rw   r2  r/  deleteinsertr   r  rp   rz   )urz   rc   r   s       r   translateUpdate1rB    s    vv44	
*	*	
>	>agg&1'
)6622	
8	885CAHHNN5S2AHHY'!2885CAHHNN5S2AHHY'!2/8'
>BCCAJHr   c                 Z   g }d}| j                   s|S t        | j                  | j                         D ]u  \  }}t        ||||      }t	        |t        j                  t        |            }t        |t              }t	        |t              }|j                  t        ||             w |S )z=
    Returns a list of SPARQL Update Algebra expressions
    Nrz   r   )requestr   rz   r,  r   r   r   r{   r   r   r   r   rB  )r   r'  r+  r@   rz   r   rA  s          r   translateUpdaterF    s    
 CH99
AJJ		* 	21$Qfh? Q)"3"3NX"VWa)*Q-0

#Ax01	2 Jr   c                    t        | d   ||      }t        | d   t        j                  t        |            | d<   t        | d         \  }}| d   j                  }| d   j                  dk(  rF| d   j                  rt        | d   j                        nd}t        | d   j                  |||      }nt        | d   j                  |||      }t        |t              }t        |t        	       t        |t               t        ||      S )
z|
    Translate a query-parsetree to a SPARQL Algebra Expression

    Return a rdflib.plugins.sparql.sparql.Query object
    r   r[   rD  r   ConstructQueryN)r   templatedatasetClause)r   rJ  rE   )r   )r,  r   r   r   r{   r   rJ  rw   rI  r2   r
   r   r   r"  r   r	   )	r   r'  r+  rz   PrE   rJ  rI  r@   s	            r   translateQueryrL    s     !1tV4H 	!	)).8LAaD adOEAraD&&Mtyy$$-.qT]]71Q4==)!		QW!		QmK
3(
+Cg&h3r   c                       e Zd Zy)ExpressionNotCoveredExceptionN)r   r   r   rj   r   r   rN  rN     s    r   rN  query_algebrac                     ddl }d 	 	 	 ddt        dt        dt        fdd fd	t        | j                  
       t        dd      j                         } |j                  d       |S )z

    :param query_algebra: An algebra returned by the function call algebra.translateQuery(parse_tree).
    :return: The query form generated from the SPARQL 1.1 algebra tree for select queries.

    r   Nc                 ^    t        dd      }|j                  |        |j                          y )N	query.txtzw+)openwriteclose)textfiles     r   	overwritez#translateAlgebra.<locals>.overwrite-  s#    K&

4

r   search_from_matchsearch_from_match_occurrencecountc                 T   t        dd      5 }|j                         }d d d        d }|r-|r+ |||      }|d | }	||d  j                  | ||      }
|	|
z   }nj                  | ||      }t        dd      5 }|j                  |       d d d        y # 1 sw Y   uxY w# 1 sw Y   y xY w)NrR  r   c                     | j                         j                  |      }|dk\  rA|dkD  r<| j                         j                  ||t        |      z         }|dz  }|dk\  r|dkD  r<|S )Nr   r[   )lowerfindrP   )haystackneedler   r  s       r   find_nthz3translateAlgebra.<locals>.replace.<locals>.find_nth=  sg    NN$))&1E1*Q (--fec&k6IJQ 1*Q Lr   w)rS  readreplacerT  )oldnewrY  rZ  r[  rW  filedatarb  positionfiledata_prefiledata_posts              r   re  z!translateAlgebra.<locals>.replace2  s     +s# 	#tyy{H	#	 !=+-IH $IX.L$XY/77S%HM#m3H''S%8H +s# 	!tJJx 	! 	!+	# 	#*	! 	!s   B7BBB'c                 "   t        | t              r| j                         S t        | t              rd| j                  z   dz   S t        | t
              rd| j                  z   dz   S t        | t              r| S t        dj                  |             )N{},The expression {0} might not be covered yet.)	rQ   r   n3r
   rw   r   strrN  format)node_args    r   convert_node_argz*translateAlgebra.<locals>.convert_node_argR  s~    h
+;;= ),&,,$'&,,#&O/>EEhO r   c                 5   t        | t              r| j                  dk(  r# (d| j                  j                  z   dz          yD| j                  dk(  rMdj	                  d | j
                  D              } )d|        )dd	d
        )ddd
        )ddd
       yD| j                  dk(  r> )dd| j                  j                  z   dz   | j                  j                  z   dz          yD| j                  dk(  r> )dd| j                  j                  z   dz   | j                  j                  z   dz          yD| j                  dk(  rt        | j                  t              r| j                  j                  }nt        d      | j                  rv| j                  j                  dk(  r3 )dd| j                  j                  z   dz           )dd|z   dz          yD )dd|z   dz   | j                  j                  z   dz          yD )dd|z   dz          yD| j                  dk(  r> )dd | j                  j                  z   d!z   | j                  j                  z   dz          yD| j                  d"k(  rDd#| j                  j                         z   d$z   | j                  j                  z   dz   } )d%|       yD| j                  d&k(  rt        d'd(      j                         j                         }|j                  d)      } )| j                   j                         d* '| j                        z   d+z   | j                   j                         z   d,z   d)|-        )d.d| j                  j                  z   dz          yD| j                  d/k(  r@d| j                  j                  z   d0z   | j                  j                  z   dz   } )d1|       yD| j                  d2k(  rg }| j                  r| j                  D ]<  }t        |t"              r |j%                  |j                                3t        d        )d3d| j                  j                  z   dz           )dd4d5j	                  |      z   d5z          yD )d3d| j                  j                  z   dz          yD| j                  dk(  rk )d6d| j                  j                  z   dz          | j&                  D ]7  }t        |j(                  t"              r|j(                  j                         }nt        d      |j                  j+                  d7      d8   }	d}
|j,                  r|j,                  d5z   }
|	d9k(  rI )|d:|
z   |j.                  j                         z   d;z   |j0                  j                         z   d,z          n3 )||	j3                         d*z   |
z    '|j.                        z   d,z           )d<j5                   '|j.                               '|j.                               : yD| j                  d=k(  r7 )d=d5j	                  | j6                  D cg c]
  } '|       c}             yD| j                  d>k(  r5t9        d?        )d@dj	                  dA | j
                  D                     yD| j                  dBk(  rt        d      | j                  dCk(  rg }| j                  D ]v  }t        |j                  t"              rP|j                  j                         }|j:                  |d*z   |j:                  z   d,z   }n|}|j%                  |       mt        d        )dEd| j                  j                  z   dz           )dFd5j	                  |      d5z          yD| j                  dGk(  rg }| j<                  D ]<  }t        |t"              r |j%                  |j                                3t        d       d}| j                  j                  dCk(  rdH} )dId5j	                  |      d z   | j                  j                  z   dz   dz   |z   dz          yD| j                  dJk(  r$ )dKdL| j                  j                  z   dz          yD| j                  dMk(  r$ )dNdO| j                  j                  z   dz          yD| j                  dPk(  rXdQt?        | j@                        z   dRz   t?        | jB                        z   } )dSd| j                  j                  z   dz   |z          yD| j                  dTk(  rd| j                  j                  dUk(  r$ )dVd | j                  j                  z   dz          yD )dVdW| j                  j                  z   dz   dz          yD| j                  dXk(  r '| j                        }| jD                  }t        tF        tI        | jJ                              r+d*dYj	                  'fdZ| jJ                  D              z   d,z   }n '| jJ                        }d[j5                  |||\      } )d]|       yD| j                  d^k(  rOd_j	                  | jJ                  D cg c]
  } '|       c}      } )d` '| j                        d_z   |z          yD| j                  dak(  rUdbj	                  | jJ                  D cg c]
  } '|       c}      } )dcd* '| j                        z   dbz   |z   d,z          yD| j                  ddk(  r\ '| j                        }|}tM        | jD                        D ]&  \  }}||d5z    '| jJ                  |         z   d5z   z  }(  )de|       yD| j                  dfk(  r\ '| j                        }|}tM        | jD                        D ]&  \  }}||d5z    '| jJ                  |         z   d5z   z  }(  )dg|       yD| j                  dhk(  r )didj '| j                        z          yD| j                  jO                  dk      r" '| jP                        } )dldm|z   d,z          yD| j                  jO                  dn      rV '| jR                        } '| jT                        }do| jV                  j                  z   dpz   |z   dYz   |z   d,z   } )dq|       yD| j                  jO                  dr      r2 )dsdtdYj	                  'fdu| jP                  D              z   d,z          yD| j                  jO                  dv      rF )dwdx| jX                  j                  z   dz          t[        | jX                  *y       | jX                  S | j                  jO                  dz      ret9        | jX                  j                          )d{d|| jX                  j                  z   dz          t[        | jX                  *y       | jX                  S | j                  jO                  d}      r6 )d~d '| jV                        z   dYz    '| jR                        z   d,z          yD| j                  jO                  d      r  )dd '| jP                        z   d,z          yD| j                  jO                  d      r  )dd '| jP                        z   d,z          yD| j                  jO                  d      r  )dd '| jP                        z   d,z          yD| j                  jO                  d      r  )dd '| jP                        z   d,z          yD| j                  jO                  d      r  )dd '| jP                        z   d,z          yD| j                  jO                  d      r  )dd '| jP                        z   d,z          yD| j                  jO                  d      r  )dd '| jP                        z   d,z          yD| j                  jO                  d      r  )dd '| jP                        z   d,z          yD| j                  jO                  d      r  )dd '| jP                        z   d,z          yD| j                  jO                  d      r6 )dd '| jV                        z   dYz    '| jR                        z   d,z          yD| j                  jO                  d      r6 )dd '| jV                        z   dYz    '| jR                        z   d,z          yD| j                  jO                  d      r
 )dd       yD| j                  jO                  d      r
 )dd       yD| j                  jO                  d      r  )dd '| jP                        z   d,z          yD| j                  jO                  d      rn| jP                  j                         | j@                  g}| jB                  r|j%                  | jB                         ddYj	                  |      z   d,z   } )d|       yD| j                  jO                  d      r  )dd '| jP                        z   d,z          yD| j                  jO                  d      r  )dd '| jP                        z   d,z          yD| j                  jO                  d      r6 )dd '| jV                        z   dYz    '| jR                        z   d,z          yD| j                  jO                  d      r6 )dd '| jV                        z   dYz    '| jR                        z   d,z          yD| j                  jO                  d      r6 )dd '| jV                        z   dYz    '| jR                        z   d,z          yD| j                  jO                  d      r6 )dd '| jV                        z   dYz    '| jR                        z   d,z          yD| j                  jO                  d      r6 )dd '| jV                        z   dYz    '| jR                        z   d,z          yD| j                  jO                  d«      r  )dd '| jP                        z   d,z          yD| j                  jO                  dū      r<dj5                  dYj	                  dǄ | jP                  D              ȫ      } )d|       yD| j                  jO                  dʫ      r6 )dd '| jV                        z   dYz    '| jR                        z   d,z          yD| j                  jO                  dͫ      rE '| j\                         '| j^                        g}ddYj	                  |      z   d,z   } )d|       yD| j                  jO                  dЫ      rL )dd '| jP                        z   dYz    '| j^                        z   dYz    '| j`                        z   d,z          yD| j                  dk(  r  )dd '| jP                        z   d,z          yD| j                  dk(  r  )dd '| jP                        z   d,z          yD| j                  dk(  r  )dd '| jP                        z   d,z          yD| j                  dk(  r  )dd '| jP                        z   d,z          yD| j                  dk(  r
 )dd       yD| j                  dk(  r
 )dd       yD| j                  dk(  r  )dd '| jP                        z   d,z          yD| j                  dk(  r  )dd '| jP                        z   d,z          yD| j                  dk(  r  )dd '| jP                        z   d,z          yD| j                  dk(  r  )dd '| jP                        z   d,z          yD| j                  dk(  r  )dd '| jP                        z   d,z          yD| j                  dk(  r  )dd '| jP                        z   d,z          yD| j                  dk(  r  )dd '| jP                        z   d,z          yD| j                  dk(  r  )dd '| jP                        z   d,z          yD| j                  dk(  r  )dd '| jP                        z   d,z          yD| j                  d k(  r" )dd '| jP                        z   d,z          yD| j                  dk(  r" )dd '| jP                        z   d,z          yD| j                  dk(  r" )dd '| jP                        z   d,z          yD| j                  d	k(  r" )d
d '| jP                        z   d,z          yD| j                  dUk(  rJg } | j(                  d   jc                         D ]L  }!t        |!t"              r | j%                  |!j                                3t        dj5                  |!             dd5j	                  |       z   d,z   }"d}#| j(                  D ]  }$g }%|$je                         D ]n  }&t        |&t"              r |%j%                  |&j                                3t        |&t>              r|%j%                  |&       Ut        dj5                  |&             |#d*d5j	                  |%      z   d,z   z  }#  )dU|"dz   |#z   dz          yD| j                  dk(  r^ )dd '| j                        z   dz   | jX                  j                  z   dz          t[        | jX                  *y       | jX                  S yDyDc c}w c c}w c c}w (  zl
         https://www.w3.org/TR/sparql11-query/#sparqlSyntax

        :param node:
        :return:
        SelectQueryz-*-SELECT-*- {rn  r0   r$  c              3      K   | ]H  }|d    j                         dz   |d   j                         z   dz   |d   j                         z   dz    J ywr    r[   rO   .Nrp  rK   rS   s     r   rN   z>translateAlgebra.<locals>.sparql_query_text.<locals>.<genexpr>q  sP      " 1ILLNS(6!9<<>9C?&),,.PSVV"   AAz{BGP}z-*-SELECT-*-SELECTr   )r[  z	{GroupBy}z{Having}r(   z{Join}rm  z}{r4   z
{LeftJoin}z}OPTIONAL{{z}}r7   z)This expression might not be covered yet.r   z{Filter}zHAVING({z})zFILTER({z}) {r"   z{Union}z{{z	}}UNION{{r,   zGRAPH z {{z{Graph}r:   rR  r   z-*-select-*-(z as ))rY  rZ  z{Extend}r*   z}MINUS{{z{Minus}rG   z{Group}z	GROUP BY ry  z{AggregateJoin}_r[   GroupConcatzGROUP_CONCAT(z;SEPARATOR=z(SAMPLE({0}) as {0})GroupGraphPatternSubr   triplesblockz{TriplesBlock}c              3      K   | ]H  }|d    j                         dz   |d   j                         z   dz   |d   j                         z   dz    J ywrx  r{  r|  s     r   rN   z>translateAlgebra.<locals>.sparql_query_text.<locals>.<genexpr>  sf       # q	 ),,.)  !),,.	)
 r}  ToListr   Nz	{OrderBy}z{OrderConditions}rC   zORDER BY {OrderConditions}z	{Project}r  z
{Distinct}z
DISTINCT {r  z	{Reduced}z	REDUCED {r  zOFFSET z LIMIT z{Slice}r   r>   z{ToMultiSet}z{-*-SELECT-*- {r   z, c              3   .   K   | ]  } |        y wrX   rj   )rK   r   rt  s     r   rN   z>translateAlgebra.<locals>.sparql_query_text.<locals>.<genexpr>:  s     #Rt$4T$:#R   z{left} {operator} {right})leftr   rightz{RelationalExpression}ConditionalAndExpressionz && z{ConditionalAndExpression}ConditionalOrExpressionz || z{ConditionalOrExpression}MultiplicativeExpressionz{MultiplicativeExpression}AdditiveExpressionz{AdditiveExpression}UnaryNotz
{UnaryNot}!BOUNDz{Builtin_BOUND}zbound(IFzIF({z}, z{Builtin_IF}COALESCEz{Builtin_COALESCE}z	COALESCE(c              3   .   K   | ]  } |        y wrX   rj   )rK   argrt  s     r   rN   z>translateAlgebra.<locals>.sparql_query_text.<locals>.<genexpr>u  s     J# 0 5Jr  r   z{Builtin_EXISTS}z	EXISTS {{r   r   z{Builtin_NOTEXISTS}zNOT EXISTS {{sameTermz{Builtin_sameTerm}z	SAMETERM(Builtin_isIRIz{Builtin_isIRI}zisIRI(Builtin_isBLANKz{Builtin_isBLANK}zisBLANK(Builtin_isLITERALz{Builtin_isLITERAL}z
isLITERAL(Builtin_isNUMERICz{Builtin_isNUMERIC}z
isNUMERIC(Builtin_STRz{Builtin_STR}zSTR(Builtin_LANGz{Builtin_LANG}zLANG(Builtin_DATATYPEz{Builtin_DATATYPE}z	DATATYPE(Builtin_IRIz{Builtin_IRI}zIRI(Builtin_BNODEz{Builtin_BNODE}zBNODE(STRDTz{Builtin_STRDT}zSTRDT(Builtin_STRLANGz{Builtin_STRLANG}zSTRLANG(Builtin_UUIDz{Builtin_UUID}zUUID()Builtin_STRUUIDz{Builtin_STRUUID}z	STRUUID()Builtin_STRLENz{Builtin_STRLEN}zSTRLEN(Builtin_SUBSTRzSUBSTR(z{Builtin_SUBSTR}Builtin_UCASEz{Builtin_UCASE}zUCASE(Builtin_LCASEz{Builtin_LCASE}zLCASE(Builtin_STRSTARTSz{Builtin_STRSTARTS}z
STRSTARTS(Builtin_STRENDSz{Builtin_STRENDS}zSTRENDS(Builtin_CONTAINSz{Builtin_CONTAINS}z	CONTAINS(Builtin_STRBEFOREz{Builtin_STRBEFORE}z
STRBEFORE(Builtin_STRAFTERz{Builtin_STRAFTER}z	STRAFTER(Builtin_ENCODE_FOR_URIz{Builtin_ENCODE_FOR_URI}zENCODE_FOR_URI(Builtin_CONCATzCONCAT({vars})c              3   <   K   | ]  }|j                           y wrX   r{  )rK   elems     r   rN   z>translateAlgebra.<locals>.sparql_query_text.<locals>.<genexpr>  s     "B4779"Bs   r   z{Builtin_CONCAT}Builtin_LANGMATCHESz{Builtin_LANGMATCHES}zLANGMATCHES(REGEXzREGEX(z{Builtin_REGEX}REPLACEz{Builtin_REPLACE}zREPLACE(Builtin_ABSz{Builtin_ABS}zABS(Builtin_ROUNDz{Builtin_ROUND}zROUND(Builtin_CEILz{Builtin_CEIL}zCEIL(Builtin_FLOORz{Builtin_FLOOR}zFLOOR(Builtin_RANDz{Builtin_RAND}zRAND()Builtin_NOWz{Builtin_NOW}zNOW()Builtin_YEARz{Builtin_YEAR}zYEAR(Builtin_MONTHz{Builtin_MONTH}zMONTH(Builtin_DAYz{Builtin_DAY}zDAY(Builtin_HOURSz{Builtin_HOURS}zHOURS(Builtin_MINUTESz{Builtin_MINUTES}zMINUTES(Builtin_SECONDSz{Builtin_SECONDS}zSECONDS(Builtin_TIMEZONEz{Builtin_TIMEZONE}z	TIMEZONE(
Builtin_TZz{Builtin_TZ}zTZ(Builtin_MD5z{Builtin_MD5}zMD5(Builtin_SHA1z{Builtin_SHA1}zSHA1(Builtin_SHA256z{Builtin_SHA256}zSHA256(Builtin_SHA384z{Builtin_SHA384}zSHA384(Builtin_SHA512z{Builtin_SHA512}zSHA512(r   ro  zVALUES (r   z{ServiceGraphPattern}zSERVICE )3rQ   r
   rw   r   joinr2   r$   r%   r   rN  r-   rp  rS  rd  r^  r[  r<   r   r   r   r@   splitdistinctr   	separatorupperrr  r   printr	  rE   rq  r  r  opr   r   other	enumerateendswithr  arg2arg3arg1r.   r   rV  patternreplacementkeysr>   )+noder2   r   query_stringselect_occurrencesgroup_by_varsr<   agg_func
identifieragg_func_namer  r  order_conditionsrd   condproject_variablesorder_by_patternslicer  r  r  inner_nodes	left_sidemultiplicationre   r   addition	bound_varr  r  if_expressionargscolumnskeyr>   rowsr  rowr-   rt  rX  re  sparql_query_texts+                                          r   r  z+translateAlgebra.<locals>.sparql_query_text`  s    dI&yyM)/$&&++=CD e# '' ""&,,"  ) ; Rr2
Bb1f$#"4t";dggll"JS"PQj( $'',,&6EL h&dii399>>D7C  66vv{{o5
C$&&++,=,CD
J,=,DE&
T(9F(BTVV[[(PSV(V J
T(9D(@Ag%tdggll2[@477<<ORVV g%$)),,.058466;;FM	4(h&#K5::<BBD%1%7%7%G"HHKKM*49955>NQTT&41C	 
C$&&++$5$;<g%TWW\\)J6EL	4(g% "99#yy %c:6)00:"? K# 	 IsTVV[['83'>?Ksxx7N)NQT)TUIsTVV[['83'>?o-)3+<s+BC $ &H!(,,
;%-\\__%6
;G  %-MM$7$7$<Q$?M!H((#+#4#4s#:$5&"&' 'mm..01 ,	,
 '003356 ""	  &)//1!"&' /x}}=> "	" .556Fx}}6UV(7G&N 44*HHtyyQG.w7QR n,n%$GG  '+ll  h&3?  i'#%  A!!&&*5ffiik77.#&9qww#6#<D#&D(//5;G  S466;;%6%<=+SXX6F-G#-MNi'$&!77 C!#z2)00:;G 	 $& 66;;)+'C$HH./ffkk"  "	"
 '' !!	 j(lTVV[[&@3&FGi'[466;;%>%DEg%!C

O3i?#dkkBRR	3#4s#:U#BCl*66;;(*ND466;;,>,EF&(>(Ls(RUX(X 44'		2WWdD$45))#Rtzz#RRS  -TZZ8E7>>% ? 	 0)<88$kk8<

C%d+C 0$TYY/&8;F 77$kk8<

C%d+C /*49955>LsR 88,TYY7	!*#,TWW#5 KAx" 3)9$**Q-)HH3NN 4nE22,TYY7	$#,TWW#5 WKAx31A$**Q-1P PSV VVHW.9j(c,<TYY,G&GH ##G,,TXX6	)8i+?#+EF##D)'		2'		2  $))..0584?$FMPSS  6##J/(iiJJJK ##$45
 *,<tzz,NQU,UV.?@zz!##$78
 djjoo&)+?$**//+QTX+X .?@zz! ##J/(&tyy12 'tyy12 	 ##O4)86Ftxx6P+PSV+VW##$56'6Ftxx6P)PSV)V ##$78) #3DHH#==C ##$78) #3DHH#==C ##M22B4882L)Ls)RS##N3('4DTXX4N*NQT*TU##$67(+8H8R*RUX*X ##M22B4882L)Ls)RS##O4)86Ftxx6P+PSV+VW##G,%&tyy12 'tyy12 	 ##$56'&tyy12 'tyy12 	 ##N3((3##$56+[9 ##$45&	4DTXX4N(NQT(T ##$45tzz2;;KK, 499T?2S8*D1##O4)86Ftxx6P+PSV+VW##O4)86Ftxx6P+PSV+VW##$78) &tyy12 'tyy12 	 ##$56'&tyy12 'tyy12 	 ##$67(&tyy12 'tyy12 	 ##$78) &tyy12 'tyy12 	 ##$67(&tyy12 'tyy12 	 ##$<=.%(8(BBSH ##$45'.."B"BB /  *D1##$9:+"&tyy12 'tyy12 	 ##G,(35Edll5ST$))D/1C7)40##I.'&txx01 't||45 	
 't'7'789 	 m+2B4882L)Ls)RSo-)86Ftxx6P+PSV+VWn,('4DTXX4N*NQT*TUo-)86Ftxx6P+PSV+VWn,((3 m+1n,('4DTXX4N*NQT*TUo-)86Ftxx6P+PSV+VWm+2B4882L)Ls)RSo-)86Ftxx6P+PSV+VW//'6Ftxx6P)PSV)V //'6Ftxx6P)PSV)V 00(+8H8R*RUX*X l*0@0J(JS(PQ m+2B4882L)Ls)RSn,('4DTXX4N*NQT*TU..&	4DTXX4N(NQT(T ..&	4DTXX4N(NQT(T ..&	4DTXX4N(NQT(T
 h&88A;++- C!#z2svvx0;JQQRUV 	 $chhw&77#= HH 6DC $ %dJ7JJ $	 (c2JJt,"? N U U$(!"#  C#((3-/#55D6" &3,"5";<33+&tyy12 jjoo& 	 .?@zz! 4y 'z R@ D Ds   ?Ak Ak6Ak
r  rR  r   )NNr[   )osrq  r`   r   algebrarS  rd  remove)rO  r  query_from_algebrart  rX  re  r  s      @@@@r   translateAlgebrar  $  s      "&,0! ! '*	!
 !@n"d ]""->?k3/446BIIkr   c                 t    dfd		  | j                          y # t        $ r | D ]
  } |        Y y w xY w)Nc                     t        | t              st        |        y t        | j                  d       | D ]#  }t        ||dd        | |   |dz          % t        d|z         y )Nr  z =ry  )end    z%s))rQ   r
   r  rw   )r   indr   pps      r   r  zpprintAlgebra.<locals>.pp  ss     !Y'!Hqvv  		#A 
  qtS6\"		# 	eckr   )r  )r  AttributeError)r   rL   r  s     @r   pprintAlgebrar    s=    ,
199  	AqE	s    77__main__)parserr[   z--------rX   )NN)^__doc__r   r   r^   r   rdflibr   r   r   r   rdflib.plugins.sparql.sparqlr   r	   !rdflib.plugins.sparql.parserutilsr
   r   rdflib.plugins.sparql.operatorsr   r   r   r   rdflib.pathsr   r   r   r   r   	pyparsingr   rdflib.termr   r   r   r"   r(   r*   r,   r0   r4   r7   r:   rA   rC   rG   rU   rg   r2   r{   r   r   r   r   r   r   r   rp   r   r   r   r   r   r   r   r   r   r   r   r   r   r"  r,  r2  rB  rF  rL  rN  r  r  r   sysrdflib.plugins.sparqlr  os.pathr  pathexistsargvrS  rd  r   
parseQuerypqr  tqrj   r   r   <module>r     s       3 3 8 = 
 V U "
 #0(,+,23:/8(,.$NS&*+Z&4	T56rI 
 )N : . ( +nt  & 1B5"
3D(jZ
&(  0. B	I 	r	E r	j> z,	ww~~chhqk"!""$HHQK			1	B	"I	*		B" r   