K ipddlmZddlZedddgiZ erddlmZmZmZmZm Z m Z m Z m Z m Z mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZddlmZmZm Z m!Z!dd l"m#Z#m$Z$m%Z%m&Z&m'Z'dd l(m)Z)m*Z*m+Z+m,Z,dd l-m.Z.dd l/m0Z0dd l(m1Z1m2Z2ddl3Z3ddl4Z4GddZ5Gdde5Z6dZ7yGddZ6dZ7y)) import_moduleNz clang.cindexfromlistcindex) import_kwargs)VariableIntegerFloatFunctionPrototypeFunctionDefinition FunctionCallnoneReturn Assignmentintcint8int16int64uint8uint16uint32uint64float32float64float80 aug_assignbool_While CodeBlock) PreDecrement PostDecrement PreIncrement PostIncrement)AddModMulPowRel)And as_BooleanNotOr)Symbol)sympify)falsetrueceZdZdZdZdZy) BaseParserzBase Class for the C parsercJtjj|_y)z6Initializes the Base parser creating a Clang AST indexN)cinIndexcreateindex)selfs ^/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sympy/parsing/c/c_parser.py__init__zBaseParser.__init__?s))+DJc "|jjD]v}tdddddd|jd|jj d|jj d |jjd |j | xy ) z%Diagostics function for the Clang ASTFATALERRORWARNINGNOTEIGNORED)r z (line z, col z) fileN) tu diagnosticsprintseveritylocationrGlinecolumnspelling)r7outdiags r8rIzBaseParser.diagnosticsCs++ !&&(%(  -- ) ** ** ,,    ! !r:N)__name__ __module__ __qualname____doc__r9rIr:r8r1r1<s) , !r:r1ceZdZdZfdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZxZ S)CCodeConverterzThe Code Convereter for Clang AST The converter object takes the C source code or file as input and converts them to SymPy Expressions. cTt|g|_tjj t itjjtitjjttjjttjjttjjt tjj"t$tjj&t(tjj*t,tjj.t0itjj2t4tjj6t8tjj:t<id|_y)zInitializes the code converter)voidboolintfloatN) superr9 _py_nodesr3TypeKindVOIDr BOOLrSCHARrSHORTrINTrLONGrUCHARrUSHORTrUINTrULONGrFLOATrDOUBLEr LONGDOUBLEr _data_types)r7 __class__s r8r9zCCodeConverter.__init__\s G  DNLL%%tLL%%uLL&&LL&&LL$$dLL%%uLL&&LL''LL%%vLL&& LL&&LL''LL++W# D r:ctjj|}|jj ||t j j|_|jjjD]{}|jt jjk(s(|jt jjk(sR|jj!|j#|}|jS)aFunction to parse a file with C source code It takes the filename as an attribute and creates a Clang AST Translation Unit parsing the file. Then the transformation function is called on the translation unit, whose results are collected into a list which is returned by the function. Parameters ========== filename : string Path to the C file to be parsed flags: list Arguments to be passed to Clang while parsing the C code Returns ======= py_nodes: list A list of SymPy AST nodes argsoptions)ospathabspathr6parser3TranslationUnit PARSE_DETAILED_PROCESSING_RECORDrHcursor get_childrenkind CursorKindVAR_DECL FUNCTION_DECLr_append transform)r7filenameflagsfilepathchilds r8rwzCCodeConverter.parsexs2wwx0Hjj&&++LL'DG 446 A::!8!88EJJ#..JfJf> !r:ctjdd}|j||j|j d|j j |j|tjj|_ |j|jjjD]{}|jtj j"k(s(|jtj j$k(sR|j&j)|j+|}|j&S)aFunction to parse a string with C source code It takes the source code as an attribute, stores it in a temporary file and creates a Clang AST Translation Unit parsing the file. Then the transformation function is called on the translation unit, whose results are collected into a list which is returned by the function. Parameters ========== source : string A string containing the C source code to be parsed flags: list Arguments to be passed to Clang while parsing the C code Returns ======= py_nodes: list A list of SymPy AST nodes zw+z.cpp)modesuffixrrq)tempfileNamedTemporaryFilewriteflushseekr6rwnamer3rxryrHcloserzr{r|r}r~rr_rr)r7sourcerrGrs r8 parse_strzCCodeConverter.parse_strs2..dVLD JJv  JJL IIaLjj&& ++LL'DG JJL446 A::!8!88EJJ#..JfJf> !r:c t|d|jjjzd}|Pt d|jddj d|j Ddtj||S) aFTransformation Function for Clang AST nodes It determines the kind of node and calls the respective transformation function for that node. Raises ====== NotImplementedError : if the transformation for the provided node is not implemented z transform_%sNzIgnoring node of type z (rEc34K|]}|jywNrO.0ts r8 z+CCodeConverter.transform..s!C+,AJJ!C)rF) getattrr|rlowerrJjoin get_tokenssysstderr)r7nodehandlers r8rzCCodeConverter.transformsydNTYY^^5I5I5K$KTRG !C040A!CC  4= r:c  |jj|jdvr'|jd|jj}n|jj|jdvr'|jd|jj}nW|jj|jdvr'|jd|jj}n td |j }t |}|jt jjk(s'|jt jjk(r[t |}|jt jjk(r3|jt jjk(r[|j|}t jjt jjt jjt jjt jjt jj t jj"g}|j|vrt%|t&r t)|}nt%|t*r|jj|jdvr|dk(r t-dn t-d}n0|jj|jdvr|dk(r t/dn t/d }n|jj|jdvrt1|}nt%|t,t2t.t4fr|jj|jdvr t-|}nm|jj|jdvr t/|}n<|jj|jdvrt1t+|}n|}t7|j8j;| S|jt jj<k(r%t7|j8j;| Std j?d jAd|jCD#tD$r(t7|j8j;|cYSwxYw)aTransformation Function for Variable Declaration Used to create nodes for variable declarations and assignments with values or function call for the respective nodes in the clang AST Returns ======= A variable node as Declaration, with the initial value if given Raises ====== NotImplementedError : if called for data types not currently implemented Notes ===== The function currently supports following data types: Boolean: bool, _Bool Integer: 8-bit: signed char and unsigned char 16-bit: short, short int, signed short, signed short int, unsigned short, unsigned short int 32-bit: int, signed int, unsigned int 64-bit: long, long int, signed long, signed long int, unsigned long, unsigned long int Floating point: Single Precision: float Double Precision: double Extended Precision: long double r\r]r[&Only bool, int and float are supportedFrrDgg?typevalue)rz=Given variable declaration "{}" is not possible to parse yet!rEc34K|]}|jywrrrs r8rz4CCodeConverter.transform_var_decl..Is)+,AJJ)rr)#rr|rnNotImplementedErrorr{nextr3r} NAMESPACE_REFTYPE_REFrINTEGER_LITERALFLOATING_LITERALUNEXPOSED_EXPRBINARY_OPERATOR PAREN_EXPRUNARY_OPERATORCXX_BOOL_LITERAL_EXPR isinstancestrr,r[rr r-r\r]rrOas_Declaration CALL_EXPRformatrr StopIteration)r7rrchildrenrval supported_rhsrs r8transform_var_declz!CCodeConverter.transform_var_declsNyy~~!1!1%!88''.tyy~~>4#3#3G#<<''0@4#3#3F#;;''/ ?)+.//D ,,.XjjCNN$@$@@EJJRUR`R`RiRiDi NEjjCNN$@$@@EJJRUR`R`RiRiDinnU+NN22NN33NN11NN22NN--NN11NN88! ::.!#s+ &s #C.99>>T-=-=e-DD25,GAJGAJE!YY^^t/?/?/HH25,E#JE#JE!YY^^t/?/?/GG$+CLE#C'3u)EF99>>T-=-=e-DD$+CLE!YY^^t/?/?/HH$)#JE!YY^^t/?/?/GG$+DI$6E ##MM$n# %%ZZ3>>#;#;;# (.$')./8 )040A)!!   .! s-1BS 'S5JS A S>S.TTcT|jj|jdvr'|jd|jj}n|jj|jdvr'|jd|jj}n|jj|jdvr'|jd|jj}nW|jj|jdvr'|jd|jj}n tdg}g}|j D]}|j |}|jt jjk(r|j|M|jt jjk(r|D]}|j||j||gk(rt||j|}|St||j||}|S)aTransformation Function For Function Declaration Used to create nodes for function declarations and definitions for the respective nodes in the clang AST Returns ======= function : Codegen AST node - FunctionPrototype node if function body is not present - FunctionDefinition node if the function body is present r\r]r[rZz,Only void, bool, int and float are supported) return_typer parameters)rrrbody) result_typer|rnrr{rr3r} PARM_DECLr COMPOUND_STMTr rOr ) r7rret_typerparamrdeclrfunctions r8transform_function_declz&CCodeConverter.transform_function_declUs $$(8(8(??++E243C3C3H3HI!!&&$*:*:7*CC++G4T5E5E5J5JK!!&&$*:*:6*BB++F3D4D4D4I4IJ!!&&$*:*:6*BB++F3D4D4D4I4IJ)+.//DE**, &~~e,::!9!99LL&ZZ3>>#?#??#) C()KK% &rz,"*==!&O ."*==!&  Or:c$|jj|jdvr'|jd|jj}n|jj|jdvr'|jd|jj}nW|jj|jdvr'|jd|jj}n td |j }t |}|jt jjt jjt jjfvret |}|jt jjt jjt jjfvre|j|}|jj|jdvr t|}nv|jj|jdvr t|}nE|jj|jdvrtt|}n tdt!|j"j%||} |jt t)d#t&$r(t!|j"j%|}YVwxYw#t&$rY|SwxYw)aTransformation function for Parameter Declaration Used to create parameter nodes for the required functions for the respective nodes in the clang AST Returns ======= param : Codegen AST Node Variable node with the value and type of the variable Raises ====== ValueError if multiple children encountered in the parameter node r\r]r[rrrz+Can't handle multiple children on parameter)rr|rnrr{rr3r}rr TEMPLATE_REFrrr r-r[rrOrr ValueError)r7rrrrlitrrs r8transform_parm_declz"CCodeConverter.transform_parm_decls$yy~~!1!1%!88''.tyy~~>4#3#3G#<<''0@4#3#3F#;;''/ ?)+.//! ,,.XjjS^^%A%A%(^^%<%<%(^^%@%@%BB!NEjjS^^%A%A%(^^%<%<%(^^%@%@%BB nnU+99>>T%5%5e%<<!#,CYY^^t'7'7'@@*CYY^^t'7'7'??!$s),C-/233!MM .! tH~. !NOO!  MM .! ! L s,1CK CK)%L.K?>K? LLc t|jj}t |S#t$r|j}Yt |SwxYw)aTransformation function for integer literal Used to get the value and type of the given integer literal. Returns ======= val : list List with two arguments type and Value type contains the type of the integer value contains the value stored in the variable Notes ===== Only Base Integer type supported for now )rrrOrliteralr\r7rrs r8transform_integer_literalz(CCodeConverter.transform_integer_literalsN& %T__./88u: ! % u:  %s#0AAc t|jj}t |S#ttf$r|j }Yt |SwxYw)aTransformation function for floating literal Used to get the value and type of the given floating literal. Returns ======= val : list List with two arguments type and Value type contains the type of float value contains the value stored in the variable Notes ===== Only Base Float type supported for now )rrrOrrrr]rs r8transform_floating_literalz)CCodeConverter.transform_floating_literalsS& %T__./88< ":. % <  %s#0AAcyrrVr7rs r8transform_string_literalz'CCodeConverter.transform_string_literals r:c t|jj}t t|dS#ttf$r|j }Y4wxYw)aTransformation function for character literal Used to get the value of the given character literal. Returns ======= val : int val contains the ascii value of the character literal Notes ===== Only for cases where character is assigned to a integer value, since character literal is not in SymPy AST rD)rrrOrrrordrrs r8transform_character_literalz*CCodeConverter.transform_character_literalsR$ %T__./88s58}% %":. %  %s#<AAc t|jj}|dk(rdSdS#ttf$r|j }Y&wxYw)zTransformation function for boolean literal Used to get the value of the given boolean literal. Returns ======= value : bool value contains the boolean value of the variable r/TF)rrrOrrrrs r8transform_cxx_bool_literal_exprz.CCodeConverter.transform_cxx_bool_literal_expr,sP %T__./88!F?4 5 5":. %  %s#.A  A cy)z2Transformation function for unexposed declarationsNrVrs r8transform_unexposed_declz'CCodeConverter.transform_unexposed_decl>s r:c |j}|jt|} t|t d#t$rYywxYw#t$rY|SwxYw)aTransformation function for unexposed expression Unexposed expressions are used to wrap float, double literals and expressions Returns ======= expr : Codegen AST Node the result from the wrapped expression None : NoneType No children are found for the node Raises ====== ValueError if the expression contains multiple children Nz&Unexposed expression has > 1 children.r{rrrr)r7rrexprs r8transform_unexposed_exprz'CCodeConverter.transform_unexposed_exprBsk. ,,.~~d8n5 X !IJJ !   ! K s"*AA AA AAc|jS)z-Returns the name of the declaration referencerrs r8transform_decl_ref_exprz&CCodeConverter.transform_decl_ref_exprgs == r:cng}|j}t|}|jtjj k(r3t|}|jtjj k(r3|jtjj k(r3t|}|jtjj k(r3|j|} |D]}|j|}|jtjjk(r|jt|V|jtjjk(r|jt||j|t||S#t$rt|cYSwxYw)aJTransformation function for a call expression Used to create function call nodes for the function calls present in the C code Returns ======= FunctionCall : Codegen AST Node FunctionCall node with parameters if any parameters are present )r{rr|r3r}rrrrrrrr r r)r7rrrr first_childargs r8transform_call_exprz"CCodeConverter.transform_call_exprksAE((*HNE** < <<X** < <<** 7 77X** 7 77../K 1%*E../CzzS^^%C%CC WS\2s~~'F'FF U3Z0 S)*$K77  1#K00 1s$B8FF43F4cZtt|jjS)z.Returns the Return Node for a return statement)rrr{rOrs r8transform_return_stmtz$CCodeConverter.transform_return_stmts!$t0023<<= =r:cxg}|j}|D]"}|j|j|$|S)aTransformation function for compound statements Returns ======= expr : list list of Nodes for the expressions present in the statement None : NoneType if the compound statement is empty )r{rr)r7rrrrs r8transform_compound_stmtz&CCodeConverter.transform_compound_stmts@D((*H! 3 DNN512 3Kr:c |j}|jt|} |jtt d#t$rY1wxYw#t$rYSwxYw)a@Transformation function for declaration statements These statements are used to wrap different kinds of declararions like variable or function declaration The function calls the transformer function for the child of the given node Returns ======= statement : Codegen AST Node contains the node returned by the children node for the type of declaration Raises ====== ValueError if multiple children present z,Don't know how to handle multiple statementsr)r7rr statements r8transform_decl_stmtz"CCodeConverter.transform_decl_stmtsu* ,,. NN4>:  tH~. !OPP !   !   s"*A%A! AA! A.-A.cR|jt|jS)z{Transformation function for Parenthesized expressions Returns the result from its children nodes )rrr{rs r8transform_paren_exprz#CCodeConverter.transform_paren_exprs! >>$t'8'8':";< >=) is encountered )transform_binary_operatorrs r8&transform_compound_assignment_operatorz5CCodeConverter.transform_compound_assignment_operators"11$7 7r:c$gd}t|j}|dj|vrQ|jt |j }t |tr|djdk(r t|S|djdk(rtt|dS|djdk(rtt|S|djdk(rtt|S|djdk(rvtt|S|djdk(r|S|djdk(r t|dS|djdk(rttt|Sy y |d jd vru|jt |j }|d jdk(rtt|S|d jdk(rt!t|Sy t#d ) aTransformation function for handling unary operators Returns ======= unary_expression: Codegen AST node simplified unary expression represented as Codegen AST Raises ====== NotImplementedError If dereferencing operator(*), address operator(&) or bitwise NOT operator(~) is encountered )+-++--!rrrrrrrD)rrz`Dereferencing operator, Address operator and bitwise NOT operator have not been implemented yet!N)listrrOrrr{rrr,r%r!rr*r-r[r"r r)r7roperators_listtokensrs r8transform_unary_operatorz'CCodeConverter.transform_unary_operators$9N$//+,Fay!!^3tD,=,=,?'@AeS)ay))S0%e},ay))S0"6%="55ay))T1+F5M::ay))T1+F5M::ay))S0"6%=11ay))S0$ ay))S0"5"~-ay))S0"74;#78811##|3tD,=,=,?'@A!9%%-(77!9%%-(77.*+566r:ct|j}gd}g}g}|D]?}|jtjj k(r|j dk(r|jdM|j dk(r|r~|ddk7rvt|dkr td|j}|j}|j} |j|j||| |r |ddk7rv|j|j |vr|r|j|j |j|dkrt|dkr td|j}|j}|j} |j|j||| |r1|j|j |j|dkr|j|j |j dvr td|j d vr td td j|j |jtjjk(r|j|j d g|jtjjk(r|j|j d g|jtjj k(r-|j dvr|j|j dgtd j|j |rnt|dkr td|j}|j}|j} |j|j||| |rn|ddS)aTransformation function for handling binary operators Returns ======= binary_expression: Codegen AST node simplified binary expression represented as Codegen AST Raises ====== NotImplementedError If a bitwise operator or unary operator(which is a child of any binary operator in Clang AST) is encountered )rr*/%=>>=<<===!=&&||+=-=*=/=%=(rrrCzCUnary operators as a part of binary operators is not supported yet!)&|^z<>z.Bitwise operator has not been implemented yet!)z&=z|=z^=z<<=z>>=z8Shorthand bitwise operator has not been implemented yet!z&Given token {} is not implemented yet! identifierr)r/r.booleanr)rrr|r3 TokenKind PUNCTUATIONrOrlenrpopperform_operation priority_ofr IDENTIFIERLITERALKEYWORD) r7rrrcombined_variables_stackoperators_stacktokenrhslhsoperators r8rz(CCodeConverter.transform_binary_operator s($//+,FN (* $!O V 1::!:!::~~,'..s33. / / 3s :"#;">"@C":">">"@C'6':':'9. $ 0 0 @#//+B/ 1!1 ##;">"@C":">">"@C'6':':'+FF1/00 ,1/002D#VENN355 ZZ3==#;#;;,3368ZZ3==#8#88,3335jjCMM$9$99*;;,3335.@/11iV 1r"/014-)**/224.224*..0(//**3X>@",B/2 2r:c6|dvry|dvry|dvry|dvry|d vry y ) z%To get the priority of given operator)rrrrrrrD)r rrCr r rrr r rB)rrrA)rrrrrV)r7ops r8rzCCodeConverter.priority_ofs>88\!77Z_$r:c ^|j|}|j|}|dk(rt||dgS|dk(rt|| dgS|dk(rt||dgS|dk(r!t|t|t ddgS|dk(rt ||dgS|dvrt |||dgS|d k(r tt|t|dgS|d k(r tt|t|dgS|d k(rtt||dgS|d vrtt||d |dgSy)zPerforms operation supported by the SymPy core Returns ======= combined_variable: list contains variable content and type of variable rrrrrrrr*r rr)rrrrrrN) get_expr_for_operandr#r%r&rr$r'r(r)r+rrr)r7r'r&r, lhs_value rhs_values r8rz CCodeConverter.perform_operationsZ11#6I11#6ISyIy16::SyI z2F;;SyIy16::SyIs9gbk'BCVLLSyIy16::77Iy"5v>>TzJy1:i3HI6RRTz:i0*Y2GH&QQSy"8I#6 BFKK33"8I#61yI6RR4r:c|ddk(rt|dS|ddk(r5d|dvrtt|dStt |dS|ddk(r|dS|ddk(r|ddk(rt St Sy ) zGives out SymPy Codegen AST node AST node returned is corresponding to combined variable passed.Combined variable contains variable content and type of variable rDrrr.rrr/N)r,r r]rr\r/r.)r7combined_variables r8r.z#CCodeConverter.get_expr_for_operands!#|3/233 #y0+A.. '8';!<=="3'8';#<== #v-(++ #y0#4Q#76#A4LuL1r:ctS)z'Handles Null Statement and returns None)r rs r8transform_null_stmtz"CCodeConverter.transform_null_stmtsKr:c|j}|jt|}|jt|}t|tr t |}n t |}t ||S)aTransformation function for handling while statement Returns ======= while statement : Codegen AST Node contains the while statement node having condition and statement block )r{rrrrrr)r7rr condition statementsstatement_blocks r8transform_while_stmtz#CCodeConverter.transform_while_stmtsa((*HtH~6IX7J*d+"+Z"8"+J"7O4 4r:)!rRrSrTrUr9rwrrrrrrrrrrrrrrrrrrrrrrrr.r5r: __classcell__)ros@r8rXrXUs  8" "H& "P !6t l6 pD L 4 4  &2 6$ # J !# 1J > (! F = 8&8 6tI 3V  SB M(  5r:rXceZdZdZy)rXctd)NzModule not Installed) ImportError)r7rrkwargss r8r9zCCodeConverter.__init__ s45 5r:N)rRrSrTr9rVr:r8rXrX s 6r:ct}tjj|r|j |g}|S|j |g}|S)zFunction for converting a C source code The function reads the source code present in the given file and parses it to give out SymPy Expressions Returns ======= src : list List of Python expression strings )r)rXrtruexistsrwr)r convertersrcs r8parse_crDsQ I ww~~foofbo1 J!!&"!5 Jr:)8sympy.externalrrtr3sympy.codegen.astrrr r r r r rrrrrrrrrrrrrrrrrsympy.codegen.cnodesrr r!r" sympy.corer#r$r%r&r'sympy.logic.boolalgr(r)r*r+sympy.core.symbolr,sympy.core.sympifyr-r.r/rrr1rXrDrVr:r8rLs( NZ(4LM$L------- %%22<<(*1!!2r5r5x 66 r: