builtins.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. from operator import lt as __operator_lt
  2. from operator import gt as __operator_gt
  3. from __builtins import next as __builtins_next
  4. def __minmax_reduce(op, args, key):
  5. if key is None:
  6. if len(args) == 2:
  7. return args[0] if op(args[0], args[1]) else args[1]
  8. if len(args) == 0:
  9. raise TypeError('expected 1 arguments, got 0')
  10. if len(args) == 1:
  11. args = args[0]
  12. args = iter(args)
  13. res = __builtins_next(args)
  14. if res is StopIteration:
  15. raise ValueError('args is an empty sequence')
  16. while True:
  17. i = __builtins_next(args)
  18. if i is StopIteration:
  19. break
  20. if key is None:
  21. if op(i, res):
  22. res = i
  23. else:
  24. if op(key(i), key(res)):
  25. res = i
  26. return res
  27. def min(*args, key=None):
  28. return __minmax_reduce(__operator_lt, args, key)
  29. def max(*args, key=None):
  30. return __minmax_reduce(__operator_gt, args, key)
  31. def all(iterable):
  32. for i in iterable:
  33. if not i:
  34. return False
  35. return True
  36. def any(iterable):
  37. for i in iterable:
  38. if i:
  39. return True
  40. return False
  41. def enumerate(iterable, start=0):
  42. n = start
  43. for elem in iterable:
  44. yield n, elem
  45. ++n
  46. def sum(iterable):
  47. res = 0
  48. for i in iterable:
  49. res += i
  50. return res
  51. def map(f, iterable):
  52. for i in iterable:
  53. yield f(i)
  54. def filter(f, iterable):
  55. for i in iterable:
  56. if f(i):
  57. yield i
  58. def zip(a, b):
  59. a = iter(a)
  60. b = iter(b)
  61. while True:
  62. ai = __builtins_next(a)
  63. bi = __builtins_next(b)
  64. if ai is StopIteration or bi is StopIteration:
  65. break
  66. yield ai, bi
  67. def reversed(iterable):
  68. a = list(iterable)
  69. a.reverse()
  70. return a
  71. def sorted(iterable, key=None, reverse=False):
  72. a = list(iterable)
  73. a.sort(key=key, reverse=reverse)
  74. return a
  75. ##### str #####
  76. def __format_string(self: str, *args, **kwargs) -> str:
  77. def tokenizeString(s: str):
  78. tokens = []
  79. L, R = 0,0
  80. mode = None
  81. curArg = 0
  82. # lookingForKword = False
  83. while(R<len(s)):
  84. curChar = s[R]
  85. nextChar = s[R+1] if R+1<len(s) else ''
  86. # Invalid case 1: stray '}' encountered, example: "ABCD EFGH {name} IJKL}", "Hello {vv}}", "HELLO {0} WORLD}"
  87. if curChar == '}' and nextChar != '}':
  88. raise ValueError("Single '}' encountered in format string")
  89. # Valid Case 1: Escaping case, we escape "{{ or "}}" to be "{" or "}", example: "{{}}", "{{My Name is {0}}}"
  90. if (curChar == '{' and nextChar == '{') or (curChar == '}' and nextChar == '}'):
  91. if (L<R): # Valid Case 1.1: make sure we are not adding empty string
  92. tokens.append(s[L:R]) # add the string before the escape
  93. tokens.append(curChar) # Valid Case 1.2: add the escape char
  94. L = R+2 # move the left pointer to the next char
  95. R = R+2 # move the right pointer to the next char
  96. continue
  97. # Valid Case 2: Regular command line arg case: example: "ABCD EFGH {} IJKL", "{}", "HELLO {} WORLD"
  98. elif curChar == '{' and nextChar == '}':
  99. if mode is not None and mode != 'auto':
  100. # Invalid case 2: mixing automatic and manual field specifications -- example: "ABCD EFGH {name} IJKL {}", "Hello {vv} {}", "HELLO {0} WORLD {}"
  101. raise ValueError("Cannot switch from manual field numbering to automatic field specification")
  102. mode = 'auto'
  103. if(L<R): # Valid Case 2.1: make sure we are not adding empty string
  104. tokens.append(s[L:R]) # add the string before the special marker for the arg
  105. tokens.append("{"+str(curArg)+"}") # Valid Case 2.2: add the special marker for the arg
  106. curArg+=1 # increment the arg position, this will be used for referencing the arg later
  107. L = R+2 # move the left pointer to the next char
  108. R = R+2 # move the right pointer to the next char
  109. continue
  110. # Valid Case 3: Key-word arg case: example: "ABCD EFGH {name} IJKL", "Hello {vv}", "HELLO {name} WORLD"
  111. elif (curChar == '{'):
  112. if mode is not None and mode != 'manual':
  113. # # Invalid case 2: mixing automatic and manual field specifications -- example: "ABCD EFGH {} IJKL {name}", "Hello {} {1}", "HELLO {} WORLD {name}"
  114. raise ValueError("Cannot switch from automatic field specification to manual field numbering")
  115. mode = 'manual'
  116. if(L<R): # Valid case 3.1: make sure we are not adding empty string
  117. tokens.append(s[L:R]) # add the string before the special marker for the arg
  118. # We look for the end of the keyword
  119. kwL = R # Keyword left pointer
  120. kwR = R+1 # Keyword right pointer
  121. while(kwR<len(s) and s[kwR]!='}'):
  122. if s[kwR] == '{': # Invalid case 3: stray '{' encountered, example: "ABCD EFGH {n{ame} IJKL {", "Hello {vv{}}", "HELLO {0} WOR{LD}"
  123. raise ValueError("Unexpected '{' in field name")
  124. kwR += 1
  125. # Valid case 3.2: We have successfully found the end of the keyword
  126. if kwR<len(s) and s[kwR] == '}':
  127. tokens.append(s[kwL:kwR+1]) # add the special marker for the arg
  128. L = kwR+1
  129. R = kwR+1
  130. # Invalid case 4: We didn't find the end of the keyword, throw error
  131. else:
  132. raise ValueError("Expected '}' before end of string")
  133. continue
  134. R = R+1
  135. # Valid case 4: We have reached the end of the string, add the remaining string to the tokens
  136. if L<R:
  137. tokens.append(s[L:R])
  138. # print(tokens)
  139. return tokens
  140. tokens = tokenizeString(self)
  141. argMap = {}
  142. for i, a in enumerate(args):
  143. argMap[str(i)] = a
  144. final_tokens = []
  145. for t in tokens:
  146. if t[0] == '{' and t[-1] == '}':
  147. key = t[1:-1]
  148. argMapVal = argMap.get(key, None)
  149. kwargsVal = kwargs.get(key, None)
  150. if argMapVal is None and kwargsVal is None:
  151. raise ValueError("No arg found for token: "+t)
  152. elif argMapVal is not None:
  153. final_tokens.append(str(argMapVal))
  154. else:
  155. final_tokens.append(str(kwargsVal))
  156. else:
  157. final_tokens.append(t)
  158. return ''.join(final_tokens)
  159. str.format = __format_string
  160. del __format_string
  161. def help(obj):
  162. if hasattr(obj, '__func__'):
  163. obj = obj.__func__
  164. print(obj.__signature__)
  165. print(obj.__doc__)
  166. def complex(*args, **kwargs):
  167. import cmath
  168. return cmath.complex(*args, **kwargs)
  169. def long(*args, **kwargs):
  170. import _long
  171. return _long.long(*args, **kwargs)
  172. # builtin exceptions
  173. class StackOverflowError(Exception): pass
  174. class IOError(Exception): pass
  175. class NotImplementedError(Exception): pass
  176. class TypeError(Exception): pass
  177. class IndexError(Exception): pass
  178. class ValueError(Exception): pass
  179. class RuntimeError(Exception): pass
  180. class ZeroDivisionError(Exception): pass
  181. class NameError(Exception): pass
  182. class UnboundLocalError(Exception): pass
  183. class AttributeError(Exception): pass
  184. class ImportError(Exception): pass
  185. class AssertionError(Exception): pass
  186. class KeyError(Exception):
  187. def __init__(self, key=...):
  188. self.key = key
  189. if key is ...:
  190. super().__init__()
  191. else:
  192. super().__init__(repr(key))
  193. def __str__(self):
  194. if self.key is ...:
  195. return ''
  196. return str(self.key)
  197. def __repr__(self):
  198. if self.key is ...:
  199. return 'KeyError()'
  200. return f'KeyError({self.key!r})'