
    vjqD                        d Z ddlZddlZddlZddlZdZd Z G d de      Z G d de      Z	 G d	 d
e      Z
 G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d d      Z G d de      Z G d de      Z G d de      Z G d d e      Z G d! d"e      Z G d# d$ej0                        Z G d% d&ej0                        Zy)'z[
The CadQuery Gateway Interface.
Provides classes and tools for executing CadQuery scripts
    Nz
<cqscript>c                     t        |       }|S )at  
    Parses the script as a model, and returns a model.

    If you would prefer to access the underlying model without building it,
    for example, to inspect its available parameters, construct a CQModel object.

    :param script_source: the script to run. Must be a valid cadquery script
    :return: a CQModel object that defines the script and allows execution
    )CQModel)script_sourcemodels     :/DATA/.local/lib/python3.12/site-packages/cadquery/cqgi.pyparser      s     M"EL    c                   6    e Zd ZdZd Zd Zd Zd Zd	dZd Z	y)
r   a$  
    Represents a Cadquery Script.

    After construction, the metadata property contains
    a ScriptMetaData object, which describes the model in more detail,
    and can be used to retrieve the parameters defined by the model.

    the build method can be used to generate a 3d model
    c                     t               | _        t        j                  |t              | _        || _        | j                          | j                          y)z
        Create an object by parsing the supplied python script.

        :param script_source: a python script to parse
        N)	ScriptMetadatametadataastr   CQSCRIPTast_treer   
_find_vars_find_descriptions)selfr   s     r   __init__zCQModel.__init__&   s@     '(		-:*
 	!r	   c                     t        | j                        }| j                  j                  D ].  }t	        |t
        j                        s|j                  |       0 y)za
        Parse the script, and populate variables that appear to be
        overridable.
        N)ConstantAssignmentFinderr   r   body
isinstancer   Assignvisit_Assign)r   assignment_findernodes      r   r   zCQModel._find_vars6   sC     5T]]CMM&&D$

+!..t4 'r	   c                 d    t        | j                        }|j                  | j                         y N)ParameterDescriptionFinderr   visitr   )r   description_finders     r   r   zCQModel._find_descriptionsG   s#    7F  /r	   c                     t        d      )z
        Determine if the supplied parameters are valid.
        NOT IMPLEMENTED YET-- raises NotImplementedError

        :param params: a dictionary of parameters

        znot yet implemented)NotImplementedError)r   paramss     r   validatezCQModel.validateK   s     ""788r	   Nc                    |si }t        j                         }t               }	 | j                  |       t	               }t               j                         j                         j                  dd      j                  d|j                        j                  d|j                        j                  d|j                        j                         }t        | j                  t        d      }t!        ||       |j#                  |j$                         |j'                  |j(                         ||_        t        j                         }	|	|z
  |_        |S # t,        $ r}|j/                  |       Y d}~?d}~ww xY w)a"  
        Executes the script, using the optional parameters to override those in the model

        :param build_parameters: a dictionary of variables. The variables must be
            assignable to the underlying variable type. These variables override default values in the script
        :param build_options: build options for how to build the model. Build options include things like
            timeouts, tessellation tolerances, etc
        :raises: Nothing. If there is an exception, it will be on the exception property of the result.
            This is the interface so that we can return other information on the result, such as the build time
        :return: a BuildResult object, which includes the status of the result, and either
            a resulting shape or an exception
        __name____cqgi__show_objectdebugdescribe_parameterexecN)timeperf_counterBuildResultset_param_valuesScriptCallbackEnvironmentBuilderwith_real_builtinswith_cadquery_objects	add_entryr)   r*   r+   buildcompiler   r   r,   	set_debugdebugObjectsset_success_resultoutputObjectsenv	Exceptionset_failure_result	buildTime)
r   build_parametersbuild_optionsstartresult	collectorr<   cexends
             r   r6   zCQModel.buildU   s3     !!!#	*!!"23&(I"$##%&&(:z2=)*?*?@7IOO4/1M1MN  x8ACLY334%%i&=&=>FJ
 !;  	*%%b))	*s   DE 	E9E44E9c                     | j                   j                  }|j                         D ]-  \  }}||vrt        d|z        ||   }|j	                  |       / y )Nz4Cannot set value '%s': not a parameter of the model.)r   
parametersitemsInvalidParameterError	set_value)r   r$   model_parameterskvps         r   r0   zCQModel.set_param_values   s[    ==33LLNDAq((+JQN  !#AKKN #r	   NN)
r'   
__module____qualname____doc__r   r   r   r%   r6   r0    r	   r   r   r      s&    " 5"09-^
r	   r   c                       e Zd ZdZd Zy)ShapeResultzN
    An object created by a build, including the user parameters provided
    c                      d | _         d | _        y r   )shapeoptionsr   s    r   r   zShapeResult.__init__   s    
r	   N)r'   rR   rS   rT   r   rU   r	   r   rW   rW      s    r	   rW   c                   (    e Zd ZdZd Zd Zd Zd Zy)r/   aj  
    The result of executing a CadQuery script.
    The success property contains whether the execution was successful.

    If successful, the results property contains a list of all results,
    and the first_result property contains the first result.

    If unsuccessful, the exception property contains a reference to
    the stack trace that occurred.
    c                 X    d | _         g | _        g | _        d | _        d| _        d | _        y NF)r?   resultsr9   first_resultsuccess	exceptionr[   s    r   r   zBuildResult.__init__   s.     r	   c                      || _         d| _        y r^   )rb   ra   )r   rF   s     r   r>   zBuildResult.set_failure_result   s    r	   c                     || _         y r   )r9   )r   r9   s     r   r8   zBuildResult.set_debug   s
    (r	   c                 x    || _         t        | j                         dkD  r| j                   d   | _        d| _        y )Nr   T)r_   lenr`   ra   )r   r_   s     r   r:   zBuildResult.set_success_result   s1    t||q  $QDr	   N)r'   rR   rS   rT   r   r>   r8   r:   rU   r	   r   r/   r/      s    	)r	   r/   c                   "    e Zd ZdZd Zd Zd Zy)r   zw
    Defines the metadata for a parsed CQ Script.
    the parameters property is a dict of InputParameter objects.
    c                     i | _         y r   )rI   r[   s    r   r   zScriptMetadata.__init__   s	    r	   c                 6    || j                   |j                  <   y r   )rI   name)r   rP   s     r   add_script_parameterz#ScriptMetadata.add_script_parameter   s    "#r	   c                 0    | j                   |   }||_        y r   )rI   desc)r   rj   descriptionrP   s       r   add_parameter_descriptionz(ScriptMetadata.add_parameter_description   s    OOD!r	   N)r'   rR   rS   rT   r   rk   ro   rU   r	   r   r   r      s    
$r	   r   c                       e Zd Zy)ParameterTypeNr'   rR   rS   rU   r	   r   rq   rq          r	   rq   c                       e Zd Zy)NumberParameterTypeNrr   rU   r	   r   ru   ru      rs   r	   ru   c                       e Zd Zy)StringParameterTypeNrr   rU   r	   r   rw   rw      rs   r	   rw   c                       e Zd Zy)BooleanParameterTypeNrr   rU   r	   r   ry   ry      rs   r	   ry   c                       e Zd Zy)TupleParameterTypeNrr   rU   r	   r   r{   r{      rs   r	   r{   c                   6    e Zd ZdZd Ze	 dd       Zd Zd Zy)InputParameteraB  
    Defines a parameter that can be supplied when the model is executed.

    Name, varType, and default_value are always available, because they are computed
    from a variable assignment line of code:

    The others are only available if the script has used define_parameter() to
    provide additional metadata

    c                 X    d | _         d | _        d | _        d | _        g | _        d | _        y r   )default_valuerj   varTyperm   valid_valuesast_noder[   s    r   r   zInputParameter.__init__   s8     " 	  	 r	   Nc                 v    |g }t               }| |_        ||_        ||_        ||_        ||_        ||_        |S r   )r}   r   r   rj   rm   r   r   )r   var_namevar_typer   r   rm   rP   s          r   createzInputParameter.create  sF    
 L
'	%r	   c           	         t        | j                        dkD  rP|| j                  vrBt        dj                  t	        |      | j
                  t	        | j                                    | j                  t        k(  r:	 t        |t              rt        |      }nt        |      }|| j                  _        y | j                  t        k(  rt	        |      | j                  _        y | j                  t        k(  r&|rd| j                  _        y d| j                  _        y | j                  t         k(  r_g }|D ]'  }|j#                  t%        j&                  |             ) || j                  _        t%        j*                  | j                         y t        dt	        | j                              # t        $ r/ t        dj                  t	        |      | j
                              w xY w)Nr   zZCannot set value '{0:s}' for parameter '{1:s}': not a valid value. Valid values are {2:s} zJCannot set value '{0:s}' for parameter '{1:s}': parameter must be numeric.TF)valuezUnknown Type of var: )rf   r   rK   formatstrrj   r   ru   r   intfloatr   r   
ValueErrorrw   ry   r{   appendr   Constanteltsfix_missing_locations)r   	new_valuef	constantsnvs        r   rL   zInputParameter.set_value  s~   t  !A%)4;L;L*L'lss	NDIIs43D3D/E  <<..i-IAi(A&'# \\00"%i.DMM\\11&*#&+#\\// I  B!78  !*DMM%%dmm44c$,,6GHH/  +`ggI		 s   =8F. .8G&c                 x    d| j                   dt        | j                        dt        | j                        S )NzInputParameter: {name=z, type=z, defaultValue=)rj   r   r   r   r[   s    r   __str__zInputParameter.__str__<  s-    II""#
 	
r	   rQ   )	r'   rR   rS   rT   r   staticmethodr   rL   r   rU   r	   r   r}   r}      s/    	& MQ  (IT
r	   r}   c                   <    e Zd ZdZd Zi fdZi fdZd Zd Zd Z	y)	r1   z
    Allows a script to communicate with the container
    the show_object() method is exposed to CQ scripts, to allow them
    to return objects to the execution environment
    c                      g | _         g | _        y r   )r;   r9   r[   s    r   r   zScriptCallback.__init__K  s    r	   c                     |j                  |       t               }||_        ||_        | j                  j                  |       y)z
        Return an object to the executing environment, with options.

        :param shape: a cadquery object
        :param options: a dictionary of options that will be made available to the executing environment
        N)updaterW   rZ   rY   r;   r   )r   rY   rZ   kwargsos        r   r)   zScriptCallback.show_objectO  s9     	vM	!!!$r	   c                 j    t               }||_        ||_        | j                  j	                  |       y)zH
        Debug print/output an object, with optional arguments.
        N)rW   rY   rZ   r9   r   )r   objargsss       r   r*   zScriptCallback.debug]  s-     M	  #r	   c                      y)zX
        Do Nothing-- we parsed the ast ahead of execution to get what we need.
        NrU   )r   var_datas     r   r+   z!ScriptCallback.describe_parameterf       	r	   c                      y)ze
        Not implemented yet: allows scripts to indicate that there are problems with inputs
        NrU   )r   param
field_lists      r   	add_errorzScriptCallback.add_errorl  r   r	   c                 2    t        | j                        dkD  S )Nr   )rf   r;   r[   s    r   has_resultszScriptCallback.has_resultsr  s    4%%&**r	   N)
r'   rR   rS   rT   r   r)   r*   r+   r   r   rU   r	   r   r1   r1   D  s/     *, % ! $+r	   r1   c                       e Zd ZdZy)rK   zr
    Raised when an attempt is made to provide a new parameter value
    that cannot be assigned to the model
    Nr'   rR   rS   rT   rU   r	   r   rK   rK   v      
 	r	   rK   c                       e Zd ZdZy)NoOutputErrorz`
    Raised when the script does not execute the show_object() method to
    return a solid
    Nr   rU   r	   r   r   r     r   r	   r   c                   *    e Zd ZdZddZd Zd Zd Zy)ScriptExecutionErrorz|
    Represents a script syntax error.
    Useful for helping clients pinpoint issues with the script
    interactively
    Nc                 H    |d| _         n|| _         |d| _        y || _        y )Nr   zUnknown Script Errorlinemessage)r   r   r   s      r   r   zScriptExecutionError.__init__  s(    <DIDI?1DL"DLr	   c                 "    | j                         S r   __repr__r[   s    r   full_messagez!ScriptExecutionError.full_message      }}r	   c                 "    | j                         S r   r   r[   s    r   r   zScriptExecutionError.__str__  r   r	   c                 :    d| j                   d| j                  S )NzScriptError [Line z]: r   r[   s    r   r   zScriptExecutionError.__repr__  s    .2iiFFr	   rQ   )r'   rR   rS   rT   r   r   r   r   rU   r	   r   r   r     s    	#Gr	   r   c                   4    e Zd ZdZd Zd Zd Zd Zd Zd Z	y)	r2   z
    Builds an execution environment for a cadquery script.
    The environment includes the builtins, as well as
    the other methods the script will need.
    c                     i | _         y r   r<   r[   s    r   r   zEnvironmentBuilder.__init__  s	    r	   c                 ,    | j                  t              S r   )with_builtins__builtins__r[   s    r   r3   z%EnvironmentBuilder.with_real_builtins  s    !!,//r	   c                 $    || j                   d<   | S )Nr   r   )r   env_dicts     r   r   z EnvironmentBuilder.with_builtins  s    #+ r	   c                 R    t         | j                  d<   t         | j                  d<   | S )Ncadquerycq)r   r<   r[   s    r   r4   z(EnvironmentBuilder.with_cadquery_objects  s"    '!r	   c                 $    || j                   |<   | S r   r   )r   rj   r   s      r   r5   zEnvironmentBuilder.add_entry  s    r	   c                     | j                   S r   r   r[   s    r   r6   zEnvironmentBuilder.build  s    xxr	   N)
r'   rR   rS   rT   r   r3   r   r4   r5   r6   rU   r	   r   r2   r2     s%    0
r	   r2   c                       e Zd ZdZd Zd Zy)r   zb
    Visits a parse tree, looking for function calls to describe_parameter(var, description )
    c                     || _         y r   cqModelr   cq_models     r   r   z#ParameterDescriptionFinder.__init__  	    r	   c                     	 |j                   j                  dk(  rN|j                  d   j                  }|j                  d   j                  }| j                  j                  ||       |S #  Y |S xY w)zO
        Called when we see a function call. Is it describe_parameter?
        r+   r      )funcidr   r   r   ro   )r   r   varnamerm   s       r   
visit_Callz%ParameterDescriptionFinder.visit_Call  sh    	yy||33 ))A,//yy|))66wE
 	s   A'A+ +A0N)r'   rR   rS   rT   r   r   rU   r	   r   r   r     s     r	   r   c                   "    e Zd ZdZd Zd Zd Zy)r   zH
    Visits a parse tree, and adds script parameters to the cqModel
    c                     || _         y r   r   r   s     r   r   z!ConstantAssignmentFinder.__init__  r   r	   c           
         	 t        |      t        j                  k(  r|j                  dk(  r6| j                  j                  t        j                  ||t        d             y |j                  dk(  r| j                  j                  t        j                  ||t        d             y t        |      t        j                  k(  rYd}|j                  D ]  }||j                  fz   } | j                  j                  t        j                  ||t        |             y t        t        d      rt        |      t        j                  k(  r{|j                  dk(  r6| j                  j                  t        j                  ||t        d             y | j                  j                  t        j                  ||t        d             y t        t        d      rt        |      t        j                  k(  rt         t        t"        t$        t&        t(        t*        t(        t,        t        i}| j                  j                  t        j                  |||t        |j                           |j                               y y y y #  t/        d|z         Y y xY w)	NTrueTFalseFrU   NameConstantr   z-Unable to handle assignment for variable '%s')typer   Namer   r   rk   r}   r   ry   Tupler   r   r{   hasattrr   r   boolr   rw   r   ru   r   tupleprint)r   r   
value_nodetupentry	type_dicts         r   handle_assignmentz*ConstantAssignmentFinder.handle_assignment  s   <	J388+==F*LL55&--&2F
  ]]g-LL55&--&2F
 j!SYY.'__E.C - 11"))"H.@#
 n-$z2BcFVFV2V##t+LL55&--&2F LL55&--&2F j)d:.>#,,.N .,.,-	 11"))" !$z'7'7"89"((	 /O)? .d	AHLMs.   A I: #AI: )A4I: A0I: 5I: B1I: :Jc                     	 |j                   d   }t        |t        j                        ry t        j                  t        j
                  g}t        |j                        |v r(| j                  |j                  |j                         |S t        |j                        t        j                  k(  rt        |t        j                        r(| j                  |j                  |j                         |S t        |j                  |j                  j                        D ]!  \  }}| j                  |j                  |       # |S #  t        j                          t        dt        j                         z         Y |S xY w)Nr   z)Unable to handle assignment for node '%s')targetsr   r   	Attributer   r   r   r   r   r   r   zipr   	traceback	print_excr   dump)r   r   	left_sideastTypesnrO   s         r   r   z%ConstantAssignmentFinder.visit_Assign$  s   	UQI )S]]3#,,/HDJJ8+&&y||TZZ@  djj!SYY.i2**9<<D  !$INNDJJOO D1..qttQ7 !E 		U!=@SSTs   )E AE A&E 3AE 7E=N)r'   rR   rS   rT   r   r   r   rU   r	   r   r   r     s     =~r	   r   )rT   r   r   r-   r   r   r   objectr   rW   r/   r   rq   ru   rw   ry   r{   r}   r1   r=   rK   r   r   r2   NodeTransformerr   r   rU   r	   r   <module>r      s      sf sl& & DV "	F 		- 		- 		= 		 	_
 _
D/+V /+d	I 		I 	G9 G8 <!4!4 6_s22 _r	   