Advertisement
quab

Untitled

Mar 24th, 2025
527
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 16.87 KB | None | 0 0
  1. __init__.py:
  2.  
  3. # Говнокод от (меня)
  4. import re,asyncio,inspect,json,io,contextlib,traceback,math,importlib,random,time
  5. import nest_asyncio,uuid
  6. try:
  7.     from termcolor import colored
  8. except:
  9.     def colored(a,b):
  10.         return a
  11.  
  12. class funcs:
  13.     def __init__(self) -> None:
  14.         pass
  15. class anonfuncs:
  16.     def __init__(self) -> None:
  17.         pass
  18. class CacheData:
  19.     pass
  20. class AnonFunction:
  21.     def __init__(self,name,code):
  22.         self.name=name
  23.         self.__code=code
  24.     async def compile(self):
  25.         return await parse(self.__code)
  26. VERSION="0.1.7"
  27. cache=CacheData()
  28. class StopWord(Exception):
  29.     def __init__(self, text):
  30.         super().__init__(text)
  31. class Empty(Exception):
  32.     def __init__(self, text):
  33.         super().__init__(text)
  34. class OnlyIf(Exception):
  35.     def __init__(self, text):
  36.         super().__init__(text)
  37. class WrongAnnotation(Exception):
  38.     def __init__(self, text):
  39.         super().__init__(text)
  40. class Raise(Exception):
  41.     def __init__(self, text):
  42.         super().__init__(text)
  43.  
  44. DNTl=["xfexec",'try','if','for','def','while',"dowhile"]
  45. output_rep={"&i":'$',"&j":"&","&k":';',"&s":'//'}
  46.  
  47. async def isempty(item, count=-1):
  48.     fname=traceback.extract_stack()[-2][2]
  49.     fvar=list(inspect.currentframe().f_back.f_locals.items())
  50.     if item == '': raise Empty(f"Mising var {fvar[0][0]} in {fname}")
  51.     elif len(item)<count or count!=-1: raise Empty(f"Mising vars in {fname}")
  52.     return False
  53.  
  54. def isindclass(a,b):
  55.     if a is b:
  56.         return True
  57.     else:
  58.         return False
  59.  
  60. def classreturn(self):
  61.     return f"<Class {self.name}>"
  62.  
  63. def addfunc(clas, name=None):
  64.     def wrapper(func):
  65.         if name == None:
  66.             setattr(clas, func.__name__.lower(), func)
  67.             return func
  68.         setattr(clas, name.lower(), func)
  69.         return func
  70.     return wrapper
  71.  
  72. @addfunc(funcs, 'exec')
  73. async def pyexec(back:bool,*args, **kwargs):
  74.     "Allows to execute python code."
  75.     str_obj = io.StringIO()
  76.     nest_asyncio.apply()
  77.     loop = asyncio.new_event_loop()
  78.     asyncio.set_event_loop(loop)
  79.     try:
  80.         with contextlib.redirect_stdout(str_obj):
  81.             async def execd():
  82.                 exec(args[0])
  83.             loop.run_until_complete(execd())
  84.             loop.close()
  85.     except Exception as e:
  86.         return e
  87.     ret=str_obj.getvalue()
  88.     str_obj.close()
  89.     if back:
  90.         return ret
  91.     else: return ""
  92.  
  93. @addfunc(funcs, 'help')
  94. async def phelp(name: str,*args, **kwargs):
  95.     "Allows you to find out the docstring and arguments of a function."
  96.     a=getattr(funcs, name)
  97.     if a.__doc__ == None or a.__doc__ == '':
  98.         return "The function haven't docstring"
  99.     else:
  100.         return a.__doc__
  101.  
  102. @addfunc(funcs, 'break')
  103. async def pbreak(*args, **kwargs):
  104.     "Why?"
  105.     raise StopWord("Break outside the cycle")
  106.  
  107. @addfunc(funcs, 'raise')
  108. async def praise(error:str,text:str,*args, **kwargs):
  109.     "Allows you to raise errors."
  110.     raise Raise({"name":error,"text":text})
  111.  
  112. @addfunc(funcs, 'input')
  113. async def pinput(text: str, *args, **kwargs):
  114.     "Get user input from console."
  115.     return input(text)
  116.  
  117. @addfunc(funcs, 'print')
  118. async def console(*args, **kwargs):
  119.     "Allows you to send a log message to the console."
  120.     print(colored("[LOG] "+'\n'.join(args),"yellow"))
  121.     return ''
  122.  
  123. @addfunc(funcs, 'xfexec')
  124. async def xfexec(back:bool,*args, **kwargs):
  125.     "Allows you working with xfox from code."
  126.     try:
  127.         a = await __parse_code(args[0], **kwargs)
  128.     except Exception as e:
  129.         return e
  130.     if back == True:
  131.         return a
  132.  
  133. @addfunc(funcs, 'onlyif')
  134. async def onlyif(item: str, message: str, *args, **kwargs):
  135.     "Checks the statement and throws an error, if False.."
  136.     if eval(item):
  137.         return ""
  138.     else:
  139.         raise OnlyIf(message)
  140.    
  141. @addfunc(funcs, 'import')
  142. async def importt(item:str, *args, **kwargs):
  143.     "Just... import..."
  144.     importlib.import_module(item, package=None)
  145.     return ''
  146.        
  147.    
  148. @addfunc(funcs, 'eval')
  149. async def mathh(item:str, *args, **kwargs):
  150.     "Just... eval..."
  151.     return eval(item)
  152.  
  153. @addfunc(funcs, 'let')
  154. async def let(name:str, value, *args, **kwargs):
  155.     "Allows you to store data."
  156.     setattr(cache, name, value)
  157.     return ""
  158. @addfunc(funcs, 'get')
  159. async def get(name:str, *args, **kwargs):
  160.     "Allows you to get data from storage."
  161.     return getattr(cache, name)
  162.  
  163. @addfunc(funcs, 'try')
  164. async def xftry(onerror:str, *args, **kwargs):
  165.     "Just... 'try' from python..."
  166.     try:
  167.         return await __parse_code(args[0], **kwargs)
  168.     except Exception as e:
  169.         await let("_",e)
  170.         return onerror
  171.    
  172. @addfunc(funcs, 'random')
  173. async def xfrandom(x:int, y:int, *args, **kwargs):
  174.     "Allows  to get random number from X to Y"
  175.     return random.randint(x,y)
  176.  
  177. @addfunc(funcs, "if")
  178. async def xfif(*args, **kwargs):
  179.     "Just... 'if' from python..."
  180.     if len(args)%2==0:
  181.         for i in range(0,len(args),2):
  182.             if eval(await parse(args[i],in_cycle=True, **kwargs)):
  183.                 return await parse(args[i+1],in_cycle=True, **kwargs)
  184.     elif len(args)%2==1:
  185.         for i in range(0,len(args[:-1]),2):
  186.             if eval(await parse(args[i],in_cycle=True, **kwargs)):
  187.                 return await parse(args[i+1],in_cycle=True, **kwargs)
  188.         else:
  189.             return await parse(args[::-1][0],in_cycle=True, **kwargs)
  190.  
  191. @addfunc(funcs, "while")
  192. async def xfwhile(q, code:str,*args, **kwargs):
  193.     "Just... 'while' from python..."
  194.     trash=''
  195.     while eval(await parse(q,in_cycle=True,**kwargs)):
  196.         try:
  197.             a=await parse(code, stop_word=True,in_cycle=True, **kwargs)
  198.         except StopWord:
  199.                 break
  200.         trash=trash+a
  201.     return trash
  202.  
  203. @addfunc(funcs, "dowhile")
  204. async def xfdowhile(q, code:str,*args, **kwargs):
  205.     "do 'do' and check 'while'. If 'while'=True continue doing 'do'"
  206.     trash=await parse(code, stop_word=True,in_cycle=True, **kwargs)
  207.     while eval(await parse(q,in_cycle=True,**kwargs)):
  208.         try:
  209.             a=await parse(code, stop_word=True,in_cycle=True, **kwargs)
  210.         except StopWord:
  211.                 break
  212.         trash=trash+a
  213.     return trash
  214.  
  215.  
  216. @addfunc(funcs, "for")
  217. async def xffor(item, code:str,*args, **kwargs):
  218.     "Just... 'for' from python..."
  219.     item=await parse(item, **kwargs)
  220.     trash=''
  221.     try:
  222.         for i,j in dict(json.loads(item)).items():
  223.             await let("i",i)
  224.             await let("j",j)
  225.             try:
  226.                 trash=trash+str(await parse(code,stop_word=True,in_cycle=True, **kwargs))
  227.             except StopWord:
  228.                 break
  229.         return trash
  230.     except TypeError as e:
  231.         if e.args[0]=="cannot convert dictionary update sequence element #0 to a sequence":
  232.             for i in list(json.loads(item)):
  233.                 await let("i",i)
  234.                 try:
  235.                     trash=trash+str(await parse(code,stop_word=True,in_cycle=True, **kwargs))
  236.                 except StopWord:
  237.                     break
  238.             return trash
  239.     except: pass
  240.     if len(item.split(".."))>1:
  241.         a=item.split("..")
  242.         for i in range(int(a[0]),int(a[1])+1):
  243.             await let("i",i)
  244.             try:
  245.                 trash=trash+str(await parse(code,stop_word=True,in_cycle=True, **kwargs))
  246.             except StopWord:
  247.                 break
  248.         return trash
  249.     else:
  250.         for i in range(int(item)):
  251.             await let("i",i)
  252.             try:
  253.                 trash=trash+str(await parse(code,stop_word=True,in_cycle=True, **kwargs))
  254.             except StopWord:
  255.                 break
  256.         return trash
  257.                
  258. @addfunc(funcs, "len")
  259. async def xflen(item,*args, **kwargs):
  260.     "Allows to get string lenght."
  261.     try:
  262.         return len(dict(json.loads(item)).items())
  263.     except TypeError as e:
  264.         if e.args[0]=="cannot convert dictionary update sequence element #0 to a sequence":
  265.             return len(list(json.loads(item)))
  266.         else: return len(item)
  267.  
  268. @addfunc(funcs, "reverse")
  269. async def xfreverse(item:str,*args, **kwargs):
  270.     "Allows to get reversed string."
  271.     try:
  272.         return list(json.loads(item))[::-1]
  273.     except TypeError as e:
  274.         return item[::-1]
  275.  
  276. @addfunc(funcs, "round")
  277. async def xfround(item:float,col:int=0,*args, **kwargs):
  278.     "Allows to get round number."
  279.     if col == 0:
  280.         return int(round(item,col))
  281.     else:
  282.         return round(item,col)
  283.  
  284. @addfunc(funcs, "lower")
  285. async def xflower(item:str,*args, **kwargs):
  286.     "Allows to get lowercase string."
  287.     return item.lower()
  288.  
  289. @addfunc(funcs, "exit")
  290. async def pyexit(*args, **kwargs):
  291.     "Just... 'exit' from python..."
  292.     exit()
  293.  
  294. @addfunc(funcs, "upper")
  295. async def xfupper(item:str,*args, **kwargs):
  296.     "Allows to get uppercase string."
  297.     return item.upper()
  298.  
  299. @addfunc(funcs, "randomtextlist")
  300. async def xfrandomtext(item:list,col:int=1,*args, **kwargs):
  301.     "Allows to get random text from list."
  302.     return random.choices(item,k=col)
  303.  
  304. @addfunc(funcs, "randomtext")
  305. async def xfrandomtext(col:int=1, *args, **kwargs):
  306.     "Allows to get random text from args."
  307.     return random.choices(args[:-1],k=col)
  308.  
  309. @addfunc(funcs, "time")
  310. async def xftimestamp(*args, **kwargs):
  311.     "Allows to get timestamp."
  312.     return time.time()
  313.  
  314. @addfunc(funcs, "fetch")
  315. async def xffetch(item:str,name:str=None,*args, **kwargs):
  316.     "Fetching data and store in storage."
  317.     if name == None:
  318.         await let("_",json.loads(item))
  319.         return "$get[_]"
  320.     else:
  321.         await let(name,json.loads(item))
  322.         return f"$get[{name}]"
  323.  
  324. @addfunc(funcs, "def")
  325. async def deffunc(code:str, name:str=None,*args, **kwargs):
  326.     "Allows to create anonymous (or not) function."
  327.     if name == None:
  328.         name=str(uuid.uuid4())[:6]
  329.         await let(name,code)
  330.         return f"<Function {name}>"
  331.     else:
  332.         @addfunc(anonfuncs, name)
  333.         async def anonf(*args,**kwargs):
  334.             return await parse(code)
  335.         return ''
  336. #parser
  337. async def parse_argument(arg):
  338.     return re.sub(r"(?<!\\)\;", '%#*()', arg).replace("\\",'').split('%#*()')
  339. async def parse_argument_DNT(arg:str):
  340.     code=arg
  341.     while True:
  342.             enn=re.search(r'\$(\w+)\[',code.lower())
  343.             if enn==None:
  344.                 break
  345.             en_s=enn.start()
  346.             if int(en_s)>len(code):
  347.                 break
  348.             en_e=enn.end()
  349.             en=enn.end()
  350.             ens=1
  351.             function=code[en_s:en_e][1:-1].lower()
  352.             if hasattr(funcs,function) or hasattr(anonfuncs,function):
  353.                 try:
  354.                     while ens>0:
  355.                         if code[en]=="[":
  356.                             ens+=1
  357.                         elif code[en]==']':
  358.                             ens-=1
  359.                         elif en>len(code):
  360.                             raise AttributeError("error")
  361.                         en+=1
  362.                 except IndexError:
  363.                     raise IndexError(f"Out of range in '{function}'")
  364.             code=code.replace(code[en_s:en],'&i'+code[en_s:en][1:].replace(";",'\\;'),1)
  365.     return re.sub(r"(?<!\\)\;", '%#*()', code).replace("\\",'').replace("&i",'$').split('%#*()')
  366. async def __parse_code(code: str, stop_word:bool=False, in_cycle:bool=False, **kwargs):
  367.     try:
  368.         while True:
  369.             enn=re.search(r'\$(\w+)\[',code.lower())
  370.             en_s=enn.start()
  371.             if int(en_s)>len(code):
  372.                 raise AttributeError("ERROR")
  373.             en_e=enn.end()
  374.             en=enn.end()
  375.             ens=1
  376.             function=code[en_s:en_e][1:-1].lower()
  377.             if hasattr(funcs,function) or hasattr(anonfuncs,function):
  378.                 try:
  379.                     while ens>0:
  380.                         if code[en]=="[":
  381.                             ens+=1
  382.                         elif code[en]==']':
  383.                             ens-=1
  384.                         elif en>len(code):
  385.                             raise AttributeError("error")
  386.                         en+=1
  387.                 except IndexError:
  388.                     raise IndexError(f"Out of range in '{function}'")
  389.                 argument=code[en_e:en][:-1]
  390.                 if function in DNTl:
  391.                     argument=await parse_argument_DNT(argument)
  392.                 elif argument=='': argument=['']
  393.                 else:
  394.                     argument=await parse_argument(await __parse_code(argument,in_cycle=in_cycle, **kwargs))
  395.                 if hasattr(funcs,function):
  396.                     fun=getattr(funcs, function)
  397.                 elif hasattr(anonfuncs,function):
  398.                     fun=getattr(anonfuncs, function)
  399.                 insp=inspect.getfullargspec(fun).args
  400.                 insp_l=len(insp)
  401.                 for i in insp:
  402.                     if not inspect.signature(fun).parameters[i].default is inspect._empty:
  403.                         insp_l-=1
  404.                 if len(argument) >= insp_l:
  405.                     sgin=inspect.signature(fun)
  406.                     for i,k in zip(insp,argument):
  407.                         isdnsd=sgin.parameters[i].annotation
  408.                         if isindclass(isdnsd, str) or isindclass(isdnsd, inspect._empty):
  409.                             if k == '':
  410.                                 raise Empty(f"Mising var {i} in {fun.__name__}")
  411.                         elif isindclass(isdnsd, AnonFunction):
  412.                             x=re.search(r"<Function (\w+)>", k)
  413.                             if x:
  414.                                 argument[argument.index(k)]=AnonFunction(x.groups()[0],await get(x.groups()[0]))
  415.                             else:
  416.                                 raise Empty(f"Mising var {i} in {fun.__name__}")
  417.                         elif isindclass(isdnsd, int):  
  418.                             if k.isdigit():
  419.                                 argument[argument.index(k)]=int(k)
  420.                             else:
  421.                                 if k.count('.') == 1:
  422.                                     s = k.replace('.', '')
  423.                                     if s.isdigit():
  424.                                         argument[argument.index(k)]=int(k)
  425.                                     else:
  426.                                         raise WrongAnnotation(f"Wrong varible {i} type in {fun.__name__}. Need {isdnsd}")
  427.                                 else:
  428.                                     raise WrongAnnotation(f"Wrong varible {i} type in {fun.__name__}. Need {isdnsd}")
  429.                         elif isindclass(isdnsd, float):
  430.                             try:
  431.                                 argument[argument.index(k)]=float(k)
  432.                             except: raise WrongAnnotation(f"Wrong varible {i} type in {fun.__name__}. Need {isdnsd}")
  433.                         elif isindclass(isdnsd, list) or isindclass(isdnsd, dict):
  434.                             try: argument[argument.index(k)]=json.loads(k)
  435.                             except: raise WrongAnnotation(f"Wrong varible {i} type in {fun.__name__}. Need {isdnsd}")
  436.                         elif isindclass(isdnsd, bool):
  437.                             if k.lower()=="true":
  438.                                 argument[argument.index(k)]=True
  439.                             elif k.lower()=="false":
  440.                                 argument[argument.index(k)]=False
  441.                             else:
  442.                                 raise WrongAnnotation(f"Wrong varible {i} type in {fun.__name__}. Need {isdnsd}")
  443.                         else:
  444.                             raise WrongAnnotation(f"Wrong varible {i} type in {fun.__name__}. Need {isdnsd}")
  445.                     output=''
  446.                     try:
  447.                         output=await fun(*argument,**kwargs)
  448.                     except StopWord:
  449.                         if stop_word==True or in_cycle == True:
  450.                             raise StopWord("0_0")
  451.                     code=code.replace(code[en_s:en], str(output),1)
  452.                 else:
  453.                     raise Empty(f"Mising var {insp[len(argument)]} in {fun.__name__}")
  454.             else:
  455.                 code=re.sub(r"\$(\w+)\[", "&i"+code[en_s+1:en].replace(";",'&k'),code,count=1)
  456.     except AttributeError as e:
  457.         pass
  458.     except OnlyIf as e:
  459.         return e.args[0]
  460.     except Raise as e:
  461.         raise Raise(colored(f"[ERROR] {e.args[0]['name']}: {e.args[0]['text']}","red"))
  462.     return code.strip()
  463. async def parse(code: str,del_empty_lines:bool=False,clear_output:bool=True,stop_word:bool=False,in_cycle:bool=False,**kwargs):
  464.     "Parser for xfox code!"
  465.     output=await __parse_code(re.sub('\/\/.*?\/\/', '', code, flags=re.DOTALL),stop_word=stop_word,in_cycle=in_cycle,**kwargs)
  466.     output=output.strip()
  467.     if clear_output:
  468.         for i,j in output_rep.items():
  469.             output=re.sub(i,j,output)
  470.         output=output
  471.     if del_empty_lines:
  472.         output='\n'.join([line for line in output.splitlines() if line.strip() != ''])
  473.     return output
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement