
    Vh @                    b   U d Z ddlmZ ddlZddlZddlZddl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dlmZmZmZ ddlmZ erdd	lmZmZ  ed
d      Z ej8                  e      Zded<   ej@                   G d d             Z! G d de"      Z#ej@                   G d de	e                Z$y)z$A diagnostic context based on SARIF.    )annotationsN)CallableGenericLiteralTYPE_CHECKINGTypeVar)Self)infra)	formattersarifutils)version)	GeneratorMapping_Diagnostic
Diagnostic)boundlogging.Loggerdiagnostic_loggerc                  h   e Zd ZU ded<   ded<   dZded<    ej                  e      Zd	ed
<    ej                  e      Z	ded<    ej                  e      Z
ded<    ej                  e      Zded<    ej                  e      Zded<    ej                  e      Zded<   dZded<   	  ej                  de      Zded<   	 dZded<   d-dZd.dZd/d Z	 	 	 	 	 	 d0d!Zd1d"Zd2d#Zej2                  	 	 	 	 	 	 d3d$       Zd4d%Zd5d&Zd5d'Zd5d(Zd5d)Zd6d*Z d7d+Z!	 	 d8	 	 	 	 	 	 	 	 	 d9d,Z"y):r   z
infra.Rulerulezinfra.LevellevelN
str | Nonemessagedefault_factoryzlist[infra.Location]	locationszlist[infra.Stack]stackszlist[infra.Graph]graphszlist[infra.ThreadFlowLocation]thread_flow_locationsz	list[str]additional_messageszlist[infra.Tag]tagszException | Nonesource_exceptionFinitdefaultr   loggerr   int_current_log_section_depthc                     y N selfs    ^/home/dcms/DCMS/lib/python3.12/site-packages/torch/onnx/_internal/diagnostics/infra/context.py__post_init__zDiagnostic.__post_init__/   s        c           	     6   | j                   xs | j                  j                  }| j                  r#dj	                  | j                        }| d| }n|}| j
                  t        j                  j                  k(  rdnd}t        j                  t        j                  ||      | j
                  j                  j                         | j                  j                  |      }| j                  D cg c]  }|j                          c}|_        | j                   D cg c]  }|j                          c}|_        | j"                  D cg c]  }|j                          c}|_        t        j$                  t        j&                  | j(                  D 	cg c]  }	|	j                          c}	      g      g|_        t        j,                  | j.                  D 
cg c]  }
|
j0                   c}
	      |_        |S c c}w c c}w c c}w c c}	w c c}
w )
z;Returns the SARIF Result representation of this diagnostic.
z

## Additional Message:

informationalfail)textmarkdown)r   r   rule_idkind)r   )thread_flows)r"   )r   r   message_default_templater!   joinr   r
   LevelNONEr   ResultMessagenameloweridr   r   r   CodeFlow
ThreadFlowr    
code_flowsPropertyBagr"   value
properties)r.   r   additional_messagemessage_markdownr9   sarif_resultlocationstackgraphloctags              r/   r   zDiagnostic.sarif2   s   ,,D$))"D"D##!%4+C+C!D)9:L9MN   '  $zzU[[-=-==O6 	 ||MMw9IJ**//'')IILL	
 DH>>!Rx(.."2!R:>++Fu{{}F:>++Fu{{}FNN$$:>:T:T"U3399;"U#
 #("3"3'+yy1#))1#
  "SFF
 #V 2s   3H HHH Hc                <    | j                   j                  |       | S )z"Adds a location to the diagnostic.)r   appendr.   rM   s     r/   with_locationzDiagnostic.with_locationX   s    h'r1   c                <    | j                   j                  |       | S )z.Adds a thread flow location to the diagnostic.)r    rS   rT   s     r/   with_thread_flow_locationz$Diagnostic.with_thread_flow_location]   s     	""))(3r1   c                <    | j                   j                  |       | S )zAdds a stack to the diagnostic.)r   rS   )r.   rN   s     r/   
with_stackzDiagnostic.with_stackd       5!r1   c                <    | j                   j                  |       | S )zAdds a graph to the diagnostic.)r   rS   )r.   rO   s     r/   
with_graphzDiagnostic.with_graphi   rZ   r1   c              /  ,  K   | j                   j                  |      r,dd| j                  z   d| } | j                  ||g|i | | xj                  dz  c_        	 d | xj                  dz  c_        y# | xj                  dz  c_        w xY ww)a  
        Context manager for a section of log messages, denoted by a title message and increased indentation.

        Same api as `logging.Logger.log`.

        This context manager logs the given title at the specified log level, increases the current
        section depth for subsequent log messages, and ensures that the section depth is decreased
        again when exiting the context.

        Args:
            level: The log level.
            message: The title message to log.
            *args: The arguments to the message. Use `LazyString` to defer the
                expensive evaluation of the arguments until the message is actually logged.
            **kwargs: The keyword arguments for `logging.Logger.log`.

        Yields:
            None: This context manager does not yield any value.

        Example:
            >>> with DiagnosticContext("DummyContext", "1.0"):
            ...     rule = infra.Rule("RuleID", "DummyRule", "Rule message")
            ...     diagnostic = Diagnostic(rule, infra.Level.WARNING)
            ...     with diagnostic.log_section(logging.INFO, "My Section"):
            ...         diagnostic.log(logging.INFO, "My Message")
            ...         with diagnostic.log_section(logging.INFO, "My Subsection"):
            ...             diagnostic.log(logging.INFO, "My Submessage")
            ...     diagnostic.additional_messages
            ['## My Section', 'My Message', '### My Subsection', 'My Submessage']
        z###    N)r'   isEnabledForr)   log)r.   r   r   argskwargsindented_format_messages         r/   log_sectionzDiagnostic.log_sectionn   s     D ;;##E*S4:::;1WIF $ DHH'  	 	''1,'	1++q0+D++q0+s   AB A: $B:BBc                    | j                   j                  |      r?||z  } | j                   j                  ||fi | | j                  j	                  |       yy)a  Logs a message within the diagnostic. Same api as `logging.Logger.log`.

        If logger is not enabled for the given level, the message will not be logged.
        Otherwise, the message will be logged and also added to the diagnostic's additional_messages.

        The default setting for `DiagnosticOptions.verbosity_level` is `logging.INFO`. Based on this default,
        the log level recommendations are as follows. If you've set a different default verbosity level in your
        application, please adjust accordingly:

        - logging.ERROR: Log any events leading to application failure.
        - logging.WARNING: Log events that might result in application issues or failures, although not guaranteed.
        - logging.INFO: Log general useful information, ensuring minimal performance overhead.
        - logging.DEBUG: Log detailed debug information, which might affect performance when logged.

        Args:
            level: The log level.
            message: The message to log.
            *args: The arguments to the message. Use `LazyString` to defer the
                expensive evaluation of the arguments until the message is actually logged.
            **kwargs: The keyword arguments for `logging.Logger.log`.
        N)r'   ra   rb   r!   rS   )r.   r   r   rc   rd   formatted_messages         r/   rb   zDiagnostic.log   sT    , ;;##E* '$DKKOOE#4??$$++,=> +r1   c                N     | j                   t        j                  |g|i | y)zLogs a debug message within the diagnostic. Same api as logging.Logger.debug.

        Checkout `log` for more details.
        N)rb   loggingDEBUGr.   r   rc   rd   s       r/   debugzDiagnostic.debug   "    
 	9$9&9r1   c                N     | j                   t        j                  |g|i | y)zLogs an info message within the diagnostic. Same api as logging.Logger.info.

        Checkout `log` for more details.
        N)rb   rj   INFOrl   s       r/   infozDiagnostic.info   s"    
 	w888r1   c                N     | j                   t        j                  |g|i | y)zLogs a warning message within the diagnostic. Same api as logging.Logger.warning.

        Checkout `log` for more details.
        N)rb   rj   WARNINGrl   s       r/   warningzDiagnostic.warning   s"    
 	';D;F;r1   c                N     | j                   t        j                  |g|i | y)zLogs an error message within the diagnostic. Same api as logging.Logger.error.

        Checkout `log` for more details.
        N)rb   rj   ERRORrl   s       r/   errorzDiagnostic.error   rn   r1   c                    || _         | j                  |d      5  | j                  |dt        j                  |             ddd       y# 1 sw Y   yxY w)zLogs a source exception within the diagnostic.

        Invokes `log_section` and `log` to log the exception in markdown section format.
        zException logz%sN)r#   rf   rb   r   lazy_format_exception)r.   r   	exceptions      r/   log_source_exceptionzDiagnostic.log_source_exception   sP    
 !*e_5 	NHHUD)"A"A)"LM	N 	N 	Ns   'A

Ac                    |dz  }t        j                  |      }| j                  |       t        |j                        dkD  r(| j                  |j                  d   j                         |S )z&Records the current Python call stack.r`   )frames_to_skipr   )r   python_call_stackrY   lenframesrU   rM   )r.   r}   rN   s      r/   record_python_call_stackz#Diagnostic.record_python_call_stack   sZ    !''~Fu||q u||A778r1   c                P   |dz  }t        j                  |d      }t        j                  |      }||_        |j                  j                  dt        j                  |             t        j                  ||t        | j                        |      }| j                  |       |S )z.Records a python call as one thread flow step.r`      )r}   frames_to_logr   )rM   )rM   stateindexrN   )r   r~   function_locationr   r   insertr
   
StackFrameThreadFlowLocationr   r    rW   )r.   fnr   r   r}   rN   rM   thread_flow_locations           r/   record_python_callzDiagnostic.record_python_call   s     	!''~UVW**2."Au//BC$77d001	 
 	&&';<##r1   )returnNone)r   zsarif.Result)r.   r	   rM   zinfra.Locationr   r	   )r.   r	   rM   infra.ThreadFlowLocationr   r	   )r.   r	   rN   infra.Stackr   r	   )r.   r	   rO   zinfra.Graphr   r	   )r   r(   r   strr   zGenerator[None, None, None])r   r(   r   r   r   r   )r   r   r   r   )r   r(   rz   	Exceptionr   r   )r}   r(   r   r   )Nr   )
r   r   r   zMapping[str, str]r   r   r}   r(   r   r   )#__name__
__module____qualname____annotations__r   dataclassesfieldlistr   r   r   r    r!   r"   r#   r   r'   r)   r0   r   rU   rW   rY   r\   
contextlibcontextmanagerrf   rb   rm   rq   rt   rw   r{   r   r   r,   r1   r/   r   r      s   
GZ&7k&7&7&MI#M 1 1 1$ GFG 1 1 1$ GFG<MK<M<M=9  &7[%6%6t%LL-K--dCD/C)-&-B.[..ECTUFNUC&''$L
6	

 /1/1#&/1	$/1 /1b?6:9<:N #$$ !$ 	$
 $ 
"$r1   c                  $     e Zd ZdZd fdZ xZS )RuntimeErrorWithDiagnosticz3Runtime error with enclosed diagnostic information.c                F    t         |   |j                         || _        y r+   )super__init__r   
diagnostic)r.   r   	__class__s     r/   r   z#RuntimeErrorWithDiagnostic.__init__  s    ++,$r1   )r   r   )r   r   r   __doc__r   __classcell__)r   s   @r/   r   r     s    =% %r1   r   c                     e Zd ZU ded<   ded<    ej
                  ej                        Zded<    ej
                  de	      Z
d	ed
<    ej
                  de	      Zd	ed<    ej
                  dej                        Zded<    ej
                  de      Zded<    ej
                  de      Zded<   d Zd Zd dZd!dZd"dZd#d$dZd%dZd%dZej8                  	 	 	 	 d&d       Zd%dZd'dZd(d)dZ y)*DiagnosticContextr   rA   r   r   zinfra.DiagnosticOptionsoptionsF)r%   r   zlist[_Diagnostic]diagnostics_inflight_diagnosticsr$   r(   _previous_log_levelr   r'   type_bound_diagnostic_typec                    | j                   j                  | _        | j                   j                  | j                  j
                         | S r+   )r'   r   r   setLevelr   verbosity_levelr-   s    r/   	__enter__zDiagnosticContext.__enter__  s5    #';;#4#4 T\\99:r1   c                N    | j                   j                  | j                         y r+   )r'   r   r   )r.   exc_typeexc_valexc_tbs       r/   __exit__zDiagnosticContext.__exit__  s    T556r1   c                   | j                   D ch c]  }|j                   }}t        j                  t        j                  t        j
                  | j                  | j                  |D cg c]  }|j                          c}            | j                   D cg c]  }|j                          c}      S c c}w c c}w c c}w )zReturns the SARIF Run object.)rA   r   rules)driver)results)r   r   r   RunToolToolComponentrA   r   )r.   r   unique_rulesr   s       r/   r   zDiagnosticContext.sarif#  s    :>:J:JKJ
KKyyJJ** LL4@AD4::<A ;?:J:JKJZ%%'K	
 		
 L B Ls   B;+C C
c                    t        j                  t        j                  t        j                  | j                         g      S )zReturns the SARIF Log object.)r   
schema_uriruns)r   SarifLogsarif_versionSARIF_VERSIONSARIF_SCHEMA_LINKr-   s    r/   	sarif_logzDiagnosticContext.sarif_log1  s0    ~~!//$66**,
 	
r1   c                H    t        j                  | j                               S r+   )r   sarif_to_jsonr   r-   s    r/   to_jsonzDiagnosticContext.to_json9  s    &&t~~'788r1   c                   |r?t        j                  |d      5 }|j                  | j                                ddd       yt        |d      5 }|j                  | j                                ddd       y# 1 sw Y   yxY w# 1 sw Y   yxY w)zDumps the SARIF log to a file.wtNw)gzipopenwriter   )r.   	file_pathcompressfs       r/   dumpzDiagnosticContext.dump<  s{    9d+ (q'( ( i% ('( (( (( (s    A7 B7B Bc                f   t        || j                        s$t        d| j                   dt        |             | j                  j
                  rF|j                  t        j                  j                  k(  rt        j                  j                  |_        | j                  j                  |       y)zLogs a diagnostic.

        This method should be used only after all the necessary information for the diagnostic
        has been collected.

        Args:
            diagnostic: The diagnostic to add.
        zExpected diagnostic of type z, got N)
isinstancer   	TypeErrorr   r   warnings_as_errorsr   r
   r=   rs   rv   r   rS   r.   r   s     r/   rb   zDiagnosticContext.logE  s     *d&A&AB.t/J/J.K6RVWaRbQcd  <<**z/?/?5;;CVCV/V${{00J
+r1   c                    | j                  |       |j                  t        j                  j                  k(  r#|j
                  |j
                  t        |      y)aL  Logs a diagnostic and raises an exception if it is an error.

        Use this method for logging non inflight diagnostics where diagnostic level is not known or
        lower than ERROR. If it is always expected raise, use `log` and explicit
        `raise` instead. Otherwise there is no way to convey the message that it always
        raises to Python intellisense and type checking tools.

        This method should be used only after all the necessary information for the diagnostic
        has been collected.

        Args:
            diagnostic: The diagnostic to add.
        N)rb   r   r
   r=   rv   r#   r   r   s     r/   log_and_raise_if_errorz(DiagnosticContext.log_and_raise_if_errorV  sP     	u{{000**6 111,Z88 1r1   c              #     K   | j                   j                  |       	 | | j                   j                          y# | j                   j                          w xY ww)zAdds a diagnostic to the context.

        Use this method to add diagnostics that are not created by the context.
        Args:
            diagnostic: The diagnostic to add.
        N)r   rS   popr   s     r/   add_inflight_diagnosticz)DiagnosticContext.add_inflight_diagnosticj  sK      	""))*5	-&&**,D&&**,s   A> AAAc                :    | j                   j                  |       y)zPushes a diagnostic to the inflight diagnostics stack.

        Args:
            diagnostic: The diagnostic to push.

        Raises:
            ValueError: If the rule is not supported by the tool.
        N)r   rS   r   s     r/   push_inflight_diagnosticz*DiagnosticContext.push_inflight_diagnosticz  s     	""))*5r1   c                6    | j                   j                         S )z{Pops the last diagnostic from the inflight diagnostics stack.

        Returns:
            The popped diagnostic.
        )r   r   r-   s    r/   pop_inflight_diagnosticz)DiagnosticContext.pop_inflight_diagnostic  s     ))--//r1   Nc                    |2t        | j                        dk  rt        d      | j                  d   S t        | j                        D ]  }|j                  |k(  s|c S  t        d|j
                         )Nr   zNo inflight diagnosticsz No inflight diagnostic for rule )r   r   AssertionErrorreversedr   rA   )r.   r   r   s      r/   inflight_diagnosticz%DiagnosticContext.inflight_diagnostic  s|    <4--.!3$%>??--b11&t'A'AB &
??d*%%& !#CDII;!OPPr1   )r   z	sarif.Run)r   zsarif.SarifLog)r   r   )F)r   r   r   boolr   r   )r   r   r   r   )r   r   r   z"Generator[_Diagnostic, None, None])r   r   r+   )r   zinfra.Rule | Noner   r   )!r   r   r   r   r   r   r
   DiagnosticOptionsr   r   r   r   rj   rs   r   r   r'   r   r   r   r   r   r   r   r   rb   r   r   r   r   r   r   r   r,   r1   r/   r   r   	  s%   
IL'8{'8'8//(G$  &7[%6%6ESW%XK"X 0A{/@/@D0,   1{00eW__UU.[..ECTUFNU#4;#4#4%#TDT


9(,"9( -%-	+- -	60Qr1   r   )%r   
__future__r   r   r   r   rj   typingr   r   r   r   r   typing_extensionsr	    torch.onnx._internal.diagnosticsr
   &torch.onnx._internal.diagnostics.infrar   r   r   ,torch.onnx._internal.diagnostics.infra.sarifr   r   collections.abcr   r   r   	getLoggerr   r   r   	dataclassr   RuntimeErrorr   r   r,   r1   r/   <module>r      s    * "     E E " 2 J J Q 2 m<8$5G$5$5h$? > ? b$ b$ b$J% % NQ, NQ NQr1   