How to use get_current_scope_name method in Slash

Best Python code snippet using slash

interpreter.py

Source:interpreter.py Github

copy

Full Screen

...124 "variables": [],125 "calls": [],126 }]127 self.stack_funcs = []128 def get_current_scope_name(self):129 return self.stack[self.curr_scope]["scope"]130 def push_new_call(self, name: str, pointer_pos: int, ret_var: Variable) -> None:131 self.stack[self.curr_scope]["calls"].append({132 "name": name,133 "pos": pointer_pos,134 "ret": ret_var,135 })136 def pop_call(self) -> Union[None, object]:137 try:138 # pop the call from the previous scope139 return self.stack[self.curr_scope - 1]["calls"].pop()140 except IndexError:141 return None142 def new_stack_scope(self, name: str) -> None:143 # push new scope to stack144 self.stack.append({145 "scope": name,146 "variables": [],147 "calls": [],148 })149 self.curr_scope = len(self.stack) - 1150 def remove_stack_scope(self, name: str) -> None:151 for index, s in enumerate(self.stack):152 if(s["scope"] == name):153 self.stack.pop(index)154 self.curr_scope = len(self.stack) - 1155 return156 def push_stack_variable(self, var: Union[Variable, Function]) -> None:157 # push to the current scope158 self.stack[self.curr_scope]["variables"].append(var)159 def push_stack_function(self, name: str) -> None:160 self.stack_funcs.append(name)161 def get_stack_function_index(self, name: str) -> None:162 return self.stack_funcs.index(name)163 def get_variable(self, scope, name, _raise):164 # get all the scopes up until ours because we dont need to search a scope "lower down" since we couldnt possibly165 # get a variable from there anyway166 # then reverse the scopes so that we start searching at out scope, and work our way up to the global scope167 for scope in self.stack[:self.curr_scope + 1][::-1]:168 for var in scope["variables"]:169 if(var.name == name):170 return var171 # `_raise` determines whether to skip that command if the variable doesnt exist172 if(_raise):173 raise SkipCommandError174 return None175 # gets a variable from the current scope176 def get_stack_variable(self, name: str, _raise: bool = False) -> Union[Variable, Function]:177 return self.get_variable(self.curr_scope, name, _raise)178 def is_stack_variable(self, name: str) -> bool:179 for scope in self.stack[:self.curr_scope + 1][::-1]:180 for var in scope["variables"]:181 if(var.name == name):182 return True183 return False184# `STACK.new_stack_scope` will create a new local stack185# use quotes in the name since variables can't have quotes in their names so the scope could not possibly be186# overridden187STACK = Stack(GLOBAL_NAME)188class Interpreter():189 def __init__(self, tokens: list) -> None:190 self.commands: object[Union[str, int], list[Command]] = {}191 self.interp(tokens)192 def interp(self, tokens: list) -> list[Command]:193 # default is "global" (with quotes)194 scopes = [GLOBAL_NAME]195 current_command = None196 for token in tokens:197 if(token.type == "EOF"):198 break199 elif(token.type == "COMMAND"):200 current_command = Command(token.value)201 elif(token.type == "R_BRACK"):202 try:203 self.commands[scopes[0]]204 except KeyError:205 self.commands[scopes[0]] = []206 self.commands[scopes[0]].append(current_command)207 # once a right bracket was hit, we need to check if the command is defining a function208 # if so, the following commands we define it as a function in the stack, and create a new "function scope"209 # the commands that follow this one (until a return statement) will be added to the most local function scope210 if(current_command.name == "/"):211 if(Types.eq(current_command.arguments[0].type, Types.VARIABLE)):212 STACK.push_stack_function(213 current_command.arguments[0].value)214 scopes.insert(0, len(STACK.stack_funcs) - 1)215 elif(current_command.name == "\\"):216 scopes.pop(0)217 current_command = None218 elif(Types.eq(token.type, Types.VARIABLE)):219 current_command.add_argument(Types.VARIABLE, token.value)220 elif(Types.eq(token.type, Types.ANY_NUMBER)):221 # the `replace` will either leave `+` or `-` or just `` if there is no sign222 val = SignedNum(token.value, get_sign(token.type))223 current_command.add_argument(Types.LT_NUMBER, val)224 elif(Types.eq(token.type, Types.LT_BOOL)):225 current_command.add_argument(Types.LT_BOOL, Bool(token.value))226 elif(Types.eq(token.type, Types.ANY_VAR)):227 current_command.add_argument(token.type, token.value)228 elif(Types.eq(token.type, Types.LT_STRING)):229 current_command.add_argument(Types.LT_STRING, token.value)230 def exec(self) -> None:231 pointer = Pointer(GLOBAL_NAME, 0)232 # to allow for better recursion, we DONT check if a variable is already defined233 # if the function is recursive234 # this allows you to define variables in a function, without needed to pass them as arguments,235 # while also calling the function recursively236 is_recursive = False237 while(pointer.pos < len(self.commands[pointer.func_scope_name])):238 command: Command = self.commands[pointer.func_scope_name][pointer.pos]239 name = command.name240 pointer.move_forward(1)241 # if strict mode is off, argument types and the number of arguments are not checked therefore there is no guarantee that242 # any of these command will have all the arguments required. to fix this we could check whether all the commands / command values243 # are `None` however this is messy and creates a lot of duplicated code.244 # instead, if the value requested does not exist, the `get_argument_value` will raise a `SkipCommand` error. this will be245 # caught by this try catch, and will just skip that command which is the desired behaviour.246 # it only catches `SkipCommand` so that any other exceptions will pass through247 try:248 if(name == "~"):249 file = Path(command.get_argument_checked(0).value)250 interp = Interpreter([])251 if(not file.exists()):252 raise ImportError(file.name)253 # if(is_cache_up_to_date(file)):254 # interp.commands = get_cached_import_arguments(file)255 # pprint.pprint(interp.commands)256 # interp.exec()257 # else:258 tokens = tokenise(file)259 interp.__init__(tokens)260 # convert tokens to commands and cache them to the file261 cache_imported_arguments(interp.commands, file)262 for k, v in interp.commands.items():263 self.commands.setdefault(k, v)264 interp.exec()265 elif(name == "$"):266 if(is_recursive):267 raise SkipCommandError268 var = command.get_argument_raw(0)269 type = command.get_argument_raw(1)270 # should be the only time we have to check whether something is `None`, since the variable might not exist271 if(var is None or type is None):272 raise SkipCommandError273 try:274 DEFAULT_VALUES[type.value]275 except KeyError:276 raise UknownTypeError(type.value)277 value = DEFAULT_VALUES[type.value]278 if(not STACK.is_stack_variable(var.value)):279 STACK.push_stack_variable(280 Variable(var.value, type.type, value))281 else:282 raise AlreadyDefinedError(var.value)283 elif(name == "="):284 var1 = command.get_argument_checked(0)285 var2 = command.get_argument_checked(1)286 var1.set_value(var2.value)287 elif(name == "+"):288 var1 = command.get_argument_checked(0)289 var2 = command.get_argument_checked(1)290 var1.set_value(291 add_vals(var1.value, var2.value))292 elif(name == "%"):293 var1 = command.get_argument_checked(0)294 var2 = command.get_argument_checked(1)295 var3 = command.get_argument_checked(2)296 try:297 if(var1.value == var2.value):298 var3.set_value(SignedNum(0))299 elif(var1.value > var2.value):300 var3.set_value(SignedNum(1))301 else:302 var3.set_value(SignedNum(-1, "-"))303 except TypeError:304 var3.set_value(SignedNum(-1, "-"))305 elif(name == ":"):306 var1 = command.get_argument_checked(0)307 var2 = command.get_argument_checked(1)308 var1.set_value(var2.value)309 elif(name == "&"):310 var1 = command.get_argument_checked(0)311 var2 = command.get_argument_checked(1)312 var1.set_value(str(var1.value) + str(var2.value))313 elif(name == "!"):314 var1 = command.get_argument_checked(0)315 if(var1.type == Types.KW_STRING):316 var1.set_value(var1.value.upper())317 elif(var1.type == Types.KW_BOOL):318 # the ~ is the bitwise NOT operator.319 # it is used because in `Bool` we have overridden the `__invert__` method which is called when using320 # that operator321 var1.set_value(~var1.value)322 elif(var1.type == Types.KW_NUMBER):323 var1.set_value(var1.value * -1)324 elif(name == "."):325 var1 = command.get_argument_checked(0)326 var1.set_value(var1.value.lower())327 elif(name == "@"):328 var1 = command.get_argument_checked(0)329 var2 = command.get_argument_checked(1)330 var3 = command.get_argument_checked(2)331 if(var1.type == Types.KW_STRING):332 var1.set_value(var1.value[var2.value:var3.value])333 elif(var1.type == Types.KW_NUMBER):334 var1.set_value(var1.value.clamp(335 var2.value, var3.value))336 elif(name == "\""):337 var1 = command.get_argument_checked(0)338 var2 = command.get_argument_checked(1)339 if(var1.type == Types.KW_NUMBER):340 var2.set_value(str(var1.value))341 elif(var1.type == Types.KW_BOOL):342 var2.set_value(str(var1.value))343 elif(name == "1"):344 var1 = command.get_argument_checked(0)345 var2 = command.get_argument_checked(1)346 try:347 var2.set_value(SignedNum(var1.value))348 except ValueError:349 var2.set_value(0)350 elif(name == "#"):351 var1 = command.get_argument_checked(0)352 if(var1.value.get_sign() == "+"):353 pointer.move_forward(var1.value - 1)354 elif(var1.value.get_sign() == "-"):355 pointer.move_backward(var1.value - 1)356 else:357 pointer.set_pos(var1.value - 1)358 elif(name == "?"):359 var1 = command.get_argument_checked(0)360 var2 = command.get_argument_checked(1)361 if(var1.value):362 if(var2.value.get_sign() == "+"):363 pointer.move_forward(var2.value - 1)364 elif(var2.value.get_sign() == "-"):365 pointer.move_backward(var2.value - 1)366 else:367 pointer.set_pos(var2.value - 1)368 elif(len(command.arguments) == 3):369 var3 = command.get_argument_checked(2)370 if(var3.value.get_sign() == "+"):371 pointer.move_forward(var3.value - 1)372 elif(var3.value.get_sign() == "-"):373 pointer.move_backward(var3.value - 1)374 else:375 pointer.set_pos(var3.value - 1)376 elif(name == "/"):377 # the func name (argument 0) is a symbol (variable) but isnt actually a variable defined yet378 # so we need to get it without checking if it exists379 var1 = command.get_argument_raw(0)380 if(STACK.is_stack_variable(var1.value)):381 raise AlreadyDefinedError(var1.value)382 arguments = []383 if(len(command.arguments) > 1):384 arguments = command.arguments[1:]385 # pass down all arguments except the type386 func = Function(STACK.get_stack_function_index(387 var1.value), arguments)388 # create func and define in the current scope389 STACK.push_stack_variable(func)390 elif(name == "\\"):391 var1 = command.get_argument_raw(0)392 ret_val = ""393 if(var1 is not None and not STACK.is_stack_variable(var1.value)):394 raise UndefinedError(var1.value)395 elif(var1 is not None):396 # get the value of the return value397 ret_val = STACK.get_stack_variable(var1.value).value398 # remove the old function call399 old_call = STACK.pop_call()400 # ignore if the call stack is empty401 if(old_call == None):402 raise SkipCommandError403 # remove function scope once it has returned404 STACK.remove_stack_scope(old_call["name"])405 if(old_call["ret"] is not None):406 old_call["ret"].set_value(ret_val)407 # we just removed the function's scope so `get_current_scope_name` will return the correct scope408 pointer.set_func_scope(STACK.get_current_scope_name())409 # take the place where the function was called, move the pointer to there410 # to avoid calling it infinitely411 pointer.set_pos(old_call["pos"])412 elif(name == "|"):413 var1 = command.get_argument_raw(0)414 # try and get the function415 func = STACK.get_stack_variable(416 STACK.get_stack_function_index(var1.value))417 if(func is None):418 raise UndefinedError(var1.value)419 ret_var = None420 argument_values = []421 if(len(command.arguments) > 1):422 # try and get all the values of the arguments passed to the function423 # and put them in the array424 for arg in command.arguments[1:len(func.arguments) + 1]:425 if(Types.eq(arg.type, Types.VARIABLE)):426 val = STACK.get_stack_variable(arg.value)427 if(val is None):428 raise UndefinedError(arg.value)429 argument_values.append(430 {"type": val.type, "value": val.value})431 else:432 # constants are allowed as arguments to a function so their type need to be converted433 # from a literal to the respective keyword type434 argument_values.append(435 {"type": Types.LITERAL_TO_VAR[arg.type], "value": arg.value})436 # if the number of arguments in this command is greater than the number of parameters in the function + 1,437 # consider the last argument to be the return value438 if(len(command.arguments[1:]) > len(func.arguments)):439 ret_var = command.get_argument_raw(-1)440 if(not STACK.is_stack_variable(ret_var.value)):441 raise UndefinedError(ret_var.value)442 ret_var = STACK.get_stack_variable(ret_var.value)443 if(not Types.eq(ret_var.type, Types.ANY_VAR)):444 raise InvalidArgumentTypeError(command.name, len(445 func.arguments), Types.ANY_VAR, ret_var.type)446 # add function call to history447 STACK.push_new_call(func.name, pointer.pos, ret_var)448 # avoid creating a new scope (and variables) on every call (if the function is recursive)449 if(STACK.get_current_scope_name() != func.name):450 is_recursive = False451 # to execute the function, first create a new scope452 STACK.new_stack_scope(func.name)453 # once the function scope has been defined, all the parameters need to be defined as variables454 # using the values we got from the arguments earlier455 for index, arg in enumerate(func.arguments):456 STACK.push_stack_variable(457 Variable(arg.value, argument_values[index]["type"], argument_values[index]["value"]))458 elif(STACK.get_current_scope_name() == func.name):459 # if we are calling ourself from ourself, it is now recursive460 is_recursive = True461 # # move the pointer to inside of the function462 pointer.set_func_scope(func.name)463 pointer.set_pos(0)464 elif(name == ">"):465 var1 = command.get_argument_checked(0)466 var2 = command.get_argument_checked(1)467 inp = input(">: ")468 if(Types.eq(var1.type, Types.KW_NUMBER)):469 try:470 inp = SignedNum(inp)471 except ValueError:472 raise SkipCommandError...

Full Screen

Full Screen

cleanups.py

Source:cleanups.py Github

copy

Full Screen

...23 progress24 """25 if context.session is None or context.session.cleanups is None:26 return None27 return context.session.cleanups.get_current_scope_name()28def is_in_cleanup():29 """30 Returns ``True`` if the session is currently performing any cleanups31 """...

Full Screen

Full Screen

tensorflow.py

Source:tensorflow.py Github

copy

Full Screen

...20 @Args:21 scope: str, the name of this scope, if not provided, all variables in current system will be returned22 """23 return tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope= scope)24def get_current_scope_name():25 """ Return the current tensorflow variable scope name26 """...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Slash automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful